File size: 9,707 Bytes
180578f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
/**
 * DeepStudio Pro - Enhanced Production Server
 * Built with anycoder β†’ https://huggingface.co/spaces/akhaliq/anycoder
 * 
 * Features:
 * - Graceful shutdown handling
 * - Request logging and metrics
 * - Health check endpoint
 * - Memory and performance monitoring
 * - Security headers
 */

const path = require('path');
const http = require('http');
const { parse } = require('url');

const dir = path.join(__dirname);

// Set production environment
process.env.NODE_ENV = 'production';
process.chdir(__dirname);

// Configuration with sensible defaults
const config = {
  port: parseInt(process.env.PORT, 10) || 7860,
  hostname: process.env.HOSTNAME || '0.0.0.0',
  keepAliveTimeout: parseInt(process.env.KEEP_ALIVE_TIMEOUT, 10) || 65000,
  requestTimeout: parseInt(process.env.REQUEST_TIMEOUT, 10) || 30000,
  maxRequestsPerSocket: parseInt(process.env.MAX_REQUESTS_PER_SOCKET, 10) || 0,
};

// Next.js configuration - optimized for production
const nextConfig = {
  env: {},
  webpack: null,
  eslint: { ignoreDuringBuilds: true },
  typescript: { 
    ignoreBuildErrors: false, 
    tsconfigPath: 'tsconfig.json' 
  },
  distDir: './.next',
  cleanDistDir: true,
  assetPrefix: '',
  cacheMaxMemorySize: 52428800,
  configOrigin: 'next.config.ts',
  useFileSystemPublicRoutes: true,
  generateEtags: true,
  pageExtensions: ['tsx', 'ts', 'jsx', 'js'],
  poweredByHeader: false, // Security: disable X-Powered-By
  compress: true,
  images: {
    deviceSizes: [640, 750, 828, 1080, 1200, 1920, 2048, 3840],
    imageSizes: [16, 32, 48, 64, 96, 128, 256, 384],
    path: '/_next/image',
    loader: 'default',
    loaderFile: '',
    domains: [],
    disableStaticImages: false,
    minimumCacheTTL: 60,
    formats: ['image/webp', 'image/avif'],
    dangerouslyAllowSVG: false,
    contentSecurityPolicy: "script-src 'none'; frame-src 'none'; sandbox;",
    contentDispositionType: 'attachment',
    remotePatterns: [],
    unoptimized: false,
  },
  devIndicators: { position: 'bottom-left' },
  onDemandEntries: { maxInactiveAge: 60000, pagesBufferLength: 5 },
  amp: { canonicalBase: '' },
  basePath: '',
  sassOptions: {},
  trailingSlash: false,
  i18n: null,
  productionBrowserSourceMaps: false,
  excludeDefaultMomentLocales: true,
  serverRuntimeConfig: {},
  publicRuntimeConfig: {},
  reactProductionProfiling: false,
  reactStrictMode: true,
  reactMaxHeadersLength: 6000,
  httpAgentOptions: { keepAlive: true },
  logging: {},
  expireTime: 31536000,
  staticPageGenerationTimeout: 60,
  output: 'standalone',
  modularizeImports: {
    '@mui/icons-material': { transform: '@mui/icons-material/{{member}}' },
    'lodash': { transform: 'lodash/{{member}}' },
  },
  outputFileTracingRoot: process.cwd(),
  experimental: {
    optimizeCss: true,
    optimizePackageImports: [
      'lucide-react',
      'date-fns',
      'lodash-es',
      'ramda',
      'antd',
      'react-bootstrap',
      'ahooks',
      '@ant-design/icons',
      '@headlessui/react',
      '@headlessui-float/react',
      '@heroicons/react/20/solid',
      '@heroicons/react/24/solid',
      '@heroicons/react/24/outline',
      '@visx/visx',
      '@tremor/react',
      'rxjs',
      '@mui/material',
      '@mui/icons-material',
      'recharts',
      'react-use',
      'framer-motion',
      '@radix-ui/react-icons',
    ],
  },
};

// Serialize config for Next.js
process.env.__NEXT_PRIVATE_STANDALONE_CONFIG = JSON.stringify(nextConfig);

// Metrics tracking
const metrics = {
  startTime: Date.now(),
  requests: { total: 0, success: 0, error: 0 },
  activeConnections: 0,
};

// Request logging middleware
function logRequest(req, res, startTime) {
  const duration = Date.now() - startTime;
  const logEntry = {
    timestamp: new Date().toISOString(),
    method: req.method,
    url: req.url,
    status: res.statusCode,
    duration: `${duration}ms`,
    userAgent: req.headers['user-agent'],
    ip: req.headers['x-forwarded-for'] || req.socket.remoteAddress,
  };
  
  // Log errors with more detail
  if (res.statusCode >= 400) {
    console.error('[REQUEST ERROR]', JSON.stringify(logEntry));
    metrics.requests.error++;
  } else {
    console.log('[REQUEST]', JSON.stringify(logEntry));
    metrics.requests.success++;
  }
  metrics.requests.total++;
}

// Security headers middleware
function setSecurityHeaders(res) {
  res.setHeader('X-DNS-Prefetch-Control', 'on');
  res.setHeader('Strict-Transport-Security', 'max-age=63072000; includeSubDomains; preload');
  res.setHeader('X-Frame-Options', 'SAMEORIGIN');
  res.setHeader('X-Content-Type-Options', 'nosniff');
  res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin');
  res.setHeader('Permissions-Policy', 'camera=(), microphone=(), geolocation=()');
}

// Health check handler
function healthCheck(req, res) {
  const uptime = Date.now() - metrics.startTime;
  const health = {
    status: 'healthy',
    timestamp: new Date().toISOString(),
    uptime: `${Math.floor(uptime / 1000)}s`,
    version: process.env.npm_package_version || '2.0.0',
    nodejs: process.version,
    memory: process.memoryUsage(),
    metrics: {
      requests: metrics.requests,
      activeConnections: metrics.activeConnections,
    },
  };
  
  res.writeHead(200, { 'Content-Type': 'application/json' });
  res.end(JSON.stringify(health, null, 2));
}

// Metrics endpoint for monitoring
function metricsEndpoint(req, res) {
  res.writeHead(200, { 'Content-Type': 'application/json' });
  res.end(JSON.stringify({
    ...metrics,
    memory: process.memoryUsage(),
    cpu: process.cpuUsage(),
    uptime: process.uptime(),
  }, null, 2));
}

// Main server startup
async function startServer() {
  const { startServer: startNextServer } = require('next/dist/server/lib/start-server');
  
  // Validate keep-alive timeout
  let keepAliveTimeout = config.keepAliveTimeout;
  if (
    Number.isNaN(keepAliveTimeout) ||
    !Number.isFinite(keepAliveTimeout) ||
    keepAliveTimeout < 0
  ) {
    keepAliveTimeout = undefined;
  }

  console.log(`
╔══════════════════════════════════════════════════════════════╗
β•‘           DeepStudio Pro - Starting Production Server        β•‘
β•‘     Built with anycoder β†’ https://huggingface.co/spaces/akhaliq/anycoder    β•‘
╠══════════════════════════════════════════════════════════════╣
  Port:        ${config.port}
  Hostname:    ${config.hostname}
  Node Env:    ${process.env.NODE_ENV}
  Node Ver:    ${process.version}
  Start Time:  ${new Date().toISOString()}
β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•
  `);

  try {
    // Start the Next.js server
    const server = await startNextServer({
      dir,
      isDev: false,
      config: nextConfig,
      hostname: config.hostname,
      port: config.port,
      allowRetry: false,
      keepAliveTimeout,
    });

    // Get the underlying HTTP server to add custom middleware
    const httpServer = server.server;

    // Track connections for graceful shutdown
    httpServer.on('connection', (socket) => {
      metrics.activeConnections++;
      socket.on('close', () => {
        metrics.activeConnections--;
      });
    });

    // Custom request handling for health checks and metrics
    const originalHandler = httpServer.listeners('request')[0];
    httpServer.removeAllListeners('request');
    
    httpServer.on('request', (req, res) => {
      const startTime = Date.now();
      
      // Set security headers on all responses
      setSecurityHeaders(res);
      
      // Intercept health check requests
      const parsedUrl = parse(req.url, true);
      if (parsedUrl.pathname === '/api/health') {
        healthCheck(req, res);
        return;
      }
      
      // Metrics endpoint (basic auth in production recommended)
      if (parsedUrl.pathname === '/api/metrics') {
        metricsEndpoint(req, res);
        return;
      }
      
      // Log response when finished
      res.on('finish', () => logRequest(req, res, startTime));
      
      // Pass to Next.js handler
      originalHandler(req, res);
    });

    // Graceful shutdown handling
    const shutdown = (signal) => {
      console.log(`\n[SHUTDOWN] Received ${signal}. Starting graceful shutdown...`);
      console.log(`[SHUTDOWN] Active connections: ${metrics.activeConnections}`);
      
      // Stop accepting new connections
      httpServer.close(() => {
        console.log('[SHUTDOWN] HTTP server closed');
        process.exit(0);
      });

      // Force shutdown after timeout
      setTimeout(() => {
        console.error('[SHUTDOWN] Forced shutdown after timeout');
        process.exit(1);
      }, 30000);
    };

    process.on('SIGTERM', () => shutdown('SIGTERM'));
    process.on('SIGINT', () => shutdown('SIGINT'));

    // Handle uncaught errors
    process.on('uncaughtException', (err) => {
      console.error('[FATAL] Uncaught exception:', err);
      process.exit(1);
    });

    process.on('unhandledRejection', (reason, promise) => {
      console.error('[FATAL] Unhandled rejection at:', promise, 'reason:', reason);
      process.exit(1);
    });

    console.log(`[READY] Server running at http://${config.hostname}:${config.port}`);
    return server;

  } catch (err) {
    console.error('[FATAL] Failed to start server:', err);
    process.exit(1);
  }
}

// Start the server
startServer();