@flexireact/core 3.0.3 → 4.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +14 -15
- package/dist/cli/index.js +31 -17
- package/dist/cli/index.js.map +1 -1
- package/dist/core/build/index.js +689 -0
- package/dist/core/build/index.js.map +1 -0
- package/dist/core/client/index.js +12 -15
- package/dist/core/client/index.js.map +1 -1
- package/dist/core/config.js +86 -0
- package/dist/core/config.js.map +1 -0
- package/dist/core/index.js +94 -51
- package/dist/core/index.js.map +1 -1
- package/dist/core/server/index.js +3 -0
- package/dist/core/server/index.js.map +1 -1
- package/dist/core/start-dev.js +3095 -0
- package/dist/core/start-dev.js.map +1 -0
- package/dist/core/start-prod.js +3095 -0
- package/dist/core/start-prod.js.map +1 -0
- package/package.json +11 -9
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../core/server/index.ts","../../core/config.ts","../../core/router/index.ts","../../core/utils.ts","../../core/render/index.ts","../../core/middleware/index.ts","../../core/plugins/index.ts","../../core/islands/index.ts","../../core/context.ts","../../core/logger.ts","../../core/helpers.ts","../../core/actions/index.ts","../../core/image/index.ts","../../core/font/index.ts","../../core/start-dev.ts"],"sourcesContent":["/**\r\n * FlexiReact Server v2\r\n * Production-ready server with SSR, RSC, Islands, and more\r\n */\r\n\r\nimport http from 'http';\r\nimport fs from 'fs';\r\nimport path from 'path';\r\nimport { fileURLToPath, pathToFileURL } from 'url';\r\nimport { loadConfig, resolvePaths } from '../config.js';\r\nimport { buildRouteTree, matchRoute, findRouteLayouts } from '../router/index.js';\r\nimport { renderPage, renderError, renderLoading } from '../render/index.js';\r\nimport { loadMiddleware, runMiddleware } from '../middleware/index.js';\r\nimport { loadPlugins, pluginManager, PluginHooks } from '../plugins/index.js';\r\nimport { getRegisteredIslands, generateAdvancedHydrationScript } from '../islands/index.js';\r\nimport { createRequestContext, RequestContext, RouteContext } from '../context.js';\r\nimport { logger } from '../logger.js';\r\nimport { RedirectError, NotFoundError } from '../helpers.js';\r\nimport { executeAction, deserializeArgs } from '../actions/index.js';\r\nimport { handleImageOptimization } from '../image/index.js';\r\nimport { handleFontRequest } from '../font/index.js';\r\nimport React from 'react';\r\n\r\nconst __filename = fileURLToPath(import.meta.url);\r\nconst __dirname = path.dirname(__filename);\r\n\r\n// MIME types\r\nconst MIME_TYPES = {\r\n '.html': 'text/html',\r\n '.css': 'text/css',\r\n '.js': 'application/javascript',\r\n '.mjs': 'application/javascript',\r\n '.json': 'application/json',\r\n '.png': 'image/png',\r\n '.jpg': 'image/jpeg',\r\n '.jpeg': 'image/jpeg',\r\n '.gif': 'image/gif',\r\n '.svg': 'image/svg+xml',\r\n '.ico': 'image/x-icon',\r\n '.woff': 'font/woff',\r\n '.woff2': 'font/woff2',\r\n '.ttf': 'font/ttf',\r\n '.webp': 'image/webp',\r\n '.mp4': 'video/mp4',\r\n '.webm': 'video/webm'\r\n};\r\n\r\n/**\r\n * Creates the FlexiReact server\r\n */\r\ninterface CreateServerOptions {\r\n projectRoot?: string;\r\n mode?: 'development' | 'production';\r\n port?: number;\r\n host?: string;\r\n}\r\n\r\nexport async function createServer(options: CreateServerOptions = {}) {\r\n const serverStartTime = Date.now();\r\n const projectRoot = options.projectRoot || process.cwd();\r\n const isDev = options.mode === 'development';\r\n\r\n // Show logo\r\n logger.logo();\r\n\r\n // Load configuration\r\n const rawConfig = await loadConfig(projectRoot);\r\n const config = resolvePaths(rawConfig, projectRoot);\r\n\r\n // Load plugins\r\n await loadPlugins(projectRoot, config);\r\n\r\n // Run config hook\r\n await pluginManager.runHook(PluginHooks.CONFIG, config);\r\n\r\n // Load middleware\r\n const middleware = await loadMiddleware(projectRoot);\r\n\r\n // Build routes\r\n let routes = buildRouteTree(config.pagesDir, config.layoutsDir);\r\n\r\n // Run routes loaded hook\r\n await pluginManager.runHook(PluginHooks.ROUTES_LOADED, routes);\r\n\r\n // Create module loader with cache busting for dev\r\n const loadModule = createModuleLoader(isDev);\r\n\r\n // Create HTTP server\r\n const server = http.createServer(async (req, res) => {\r\n const startTime = Date.now();\r\n \r\n // Parse URL early so it's available in finally block\r\n const url = new URL(req.url, `http://${req.headers.host || 'localhost'}`);\r\n const pathname = url.pathname;\r\n\r\n try {\r\n\r\n // Run request hook\r\n await pluginManager.runHook(PluginHooks.REQUEST, req, res);\r\n\r\n // Run middleware\r\n const middlewareResult = await runMiddleware(req, res, middleware);\r\n if (!middlewareResult.continue) {\r\n return;\r\n }\r\n\r\n // Handle rewritten URL\r\n const effectivePath = middlewareResult.rewritten \r\n ? new URL(req.url, `http://${req.headers.host}`).pathname \r\n : pathname;\r\n\r\n // Serve static files from public directory\r\n if (await serveStaticFile(res, config.publicDir, effectivePath)) {\r\n return;\r\n }\r\n\r\n // Serve built assets in production\r\n if (!isDev && effectivePath.startsWith('/_flexi/')) {\r\n const assetPath = path.join(config.outDir, 'client', effectivePath.slice(8));\r\n if (await serveStaticFile(res, path.dirname(assetPath), path.basename(assetPath))) {\r\n return;\r\n }\r\n }\r\n\r\n // Serve client components (for hydration)\r\n if (effectivePath.startsWith('/_flexi/component/')) {\r\n const componentName = effectivePath.slice(18).replace('.js', '');\r\n return await serveClientComponent(res, config.pagesDir, componentName);\r\n }\r\n\r\n // Handle server actions\r\n if (effectivePath === '/_flexi/action' && req.method === 'POST') {\r\n return await handleServerAction(req, res);\r\n }\r\n\r\n // Handle image optimization\r\n if (effectivePath.startsWith('/_flexi/image')) {\r\n return await handleImageOptimization(req, res, config.images || {});\r\n }\r\n\r\n // Handle font requests\r\n if (effectivePath.startsWith('/_flexi/font')) {\r\n return await handleFontRequest(req, res);\r\n }\r\n\r\n // Rebuild routes in dev mode for hot reload\r\n if (isDev) {\r\n routes = buildRouteTree(config.pagesDir, config.layoutsDir);\r\n }\r\n\r\n // Match API routes\r\n const apiRoute = matchRoute(effectivePath, routes.api);\r\n if (apiRoute) {\r\n return await handleApiRoute(req, res, apiRoute, loadModule);\r\n }\r\n\r\n // Match FlexiReact v2 routes (routes/ directory - priority)\r\n const flexiRoute = matchRoute(effectivePath, routes.flexiRoutes || []);\r\n if (flexiRoute) {\r\n return await handlePageRoute(req, res, flexiRoute, routes, config, loadModule, url);\r\n }\r\n\r\n // Match app routes (app/ directory - Next.js style)\r\n const appRoute = matchRoute(effectivePath, routes.appRoutes || []);\r\n if (appRoute) {\r\n return await handlePageRoute(req, res, appRoute, routes, config, loadModule, url);\r\n }\r\n\r\n // Match page routes (pages/ directory - legacy fallback)\r\n const pageRoute = matchRoute(effectivePath, routes.pages);\r\n if (pageRoute) {\r\n return await handlePageRoute(req, res, pageRoute, routes, config, loadModule, url);\r\n }\r\n\r\n // 404 Not Found\r\n res.writeHead(404, { 'Content-Type': 'text/html' });\r\n res.end(renderError(404, 'Page not found'));\r\n\r\n } catch (error: any) {\r\n // Handle redirect() calls\r\n if (error instanceof RedirectError) {\r\n res.writeHead(error.statusCode, { 'Location': error.url });\r\n res.end();\r\n return;\r\n }\r\n\r\n // Handle notFound() calls\r\n if (error instanceof NotFoundError) {\r\n res.writeHead(404, { 'Content-Type': 'text/html' });\r\n res.end(renderError(404, error.message));\r\n return;\r\n }\r\n\r\n console.error('Server Error:', error);\r\n\r\n if (!res.headersSent) {\r\n res.writeHead(500, { 'Content-Type': 'text/html' });\r\n res.end(renderError(500, error.message, isDev ? error.stack : null));\r\n }\r\n } finally {\r\n const duration = Date.now() - startTime;\r\n if (isDev) {\r\n // Determine route type for logging\r\n const routeType = pathname.startsWith('/api/') ? 'api' : \r\n pathname.startsWith('/_flexi/') ? 'asset' :\r\n pathname.match(/\\.(js|css|png|jpg|svg|ico)$/) ? 'asset' : 'dynamic';\r\n logger.request(req.method, pathname, res.statusCode, duration, { type: routeType });\r\n }\r\n\r\n // Run response hook\r\n await pluginManager.runHook(PluginHooks.RESPONSE, req, res, duration);\r\n }\r\n });\r\n\r\n // Start server\r\n const port = process.env.PORT || options.port || config.server.port;\r\n const host = options.host || config.server.host;\r\n\r\n return new Promise((resolve, reject) => {\r\n // Handle port in use error\r\n server.on('error', (err: NodeJS.ErrnoException) => {\r\n if (err.code === 'EADDRINUSE') {\r\n logger.portInUse(port);\r\n process.exit(1);\r\n } else {\r\n logger.error('Server error', err);\r\n reject(err);\r\n }\r\n });\r\n\r\n server.listen(port, host, async () => {\r\n // Show startup info with styled logger\r\n logger.serverStart({\r\n port,\r\n host,\r\n mode: isDev ? 'development' : 'production',\r\n pagesDir: config.pagesDir,\r\n islands: config.islands?.enabled,\r\n rsc: config.rsc?.enabled\r\n }, serverStartTime);\r\n\r\n // Run server start hook\r\n await pluginManager.runHook(PluginHooks.SERVER_START, server);\r\n\r\n resolve(server);\r\n });\r\n });\r\n}\r\n\r\n/**\r\n * Creates a module loader with optional cache busting\r\n */\r\nfunction createModuleLoader(isDev) {\r\n return async (filePath) => {\r\n const url = pathToFileURL(filePath).href;\r\n const cacheBuster = isDev ? `?t=${Date.now()}` : '';\r\n return import(`${url}${cacheBuster}`);\r\n };\r\n}\r\n\r\n/**\r\n * Serves static files\r\n */\r\nasync function serveStaticFile(res, baseDir, pathname) {\r\n // Prevent directory traversal\r\n const safePath = path.normalize(pathname).replace(/^(\\.\\.[\\/\\\\])+/, '');\r\n const filePath = path.join(baseDir, safePath);\r\n\r\n // Check if file exists and is within base directory\r\n if (!filePath.startsWith(baseDir) || !fs.existsSync(filePath)) {\r\n return false;\r\n }\r\n\r\n const stat = fs.statSync(filePath);\r\n if (!stat.isFile()) {\r\n return false;\r\n }\r\n\r\n const ext = path.extname(filePath).toLowerCase();\r\n const contentType = MIME_TYPES[ext] || 'application/octet-stream';\r\n\r\n res.writeHead(200, {\r\n 'Content-Type': contentType,\r\n 'Content-Length': stat.size,\r\n 'Cache-Control': 'public, max-age=31536000'\r\n });\r\n\r\n fs.createReadStream(filePath).pipe(res);\r\n return true;\r\n}\r\n\r\n/**\r\n * Handles API route requests\r\n */\r\nasync function handleApiRoute(req, res, route, loadModule) {\r\n try {\r\n const module = await loadModule(route.filePath);\r\n const method = req.method.toLowerCase();\r\n\r\n // Parse request body\r\n const body = await parseBody(req);\r\n\r\n // Parse query\r\n const url = new URL(req.url, `http://${req.headers.host}`);\r\n const query = Object.fromEntries(url.searchParams);\r\n\r\n // Enhanced request\r\n const enhancedReq = {\r\n ...req,\r\n body,\r\n query,\r\n params: route.params,\r\n method: req.method\r\n };\r\n\r\n // Enhanced response\r\n const enhancedRes = createApiResponse(res);\r\n\r\n // Find handler (check both lowercase and uppercase method names)\r\n const handler = module[method] || module[method.toUpperCase()] || module.default;\r\n\r\n if (!handler) {\r\n enhancedRes.status(405).json({ error: 'Method not allowed' });\r\n return;\r\n }\r\n\r\n await handler(enhancedReq, enhancedRes);\r\n\r\n } catch (error) {\r\n console.error('API Error:', error);\r\n if (!res.headersSent) {\r\n res.writeHead(500, { 'Content-Type': 'application/json' });\r\n res.end(JSON.stringify({ error: 'Internal Server Error' }));\r\n }\r\n }\r\n}\r\n\r\n/**\r\n * Handles server action requests\r\n */\r\nasync function handleServerAction(req, res) {\r\n try {\r\n // Parse request body\r\n const body: any = await parseBody(req);\r\n const { actionId, args } = body;\r\n\r\n if (!actionId) {\r\n res.writeHead(400, { 'Content-Type': 'application/json' });\r\n res.end(JSON.stringify({ success: false, error: 'Missing actionId' }));\r\n return;\r\n }\r\n\r\n // Deserialize arguments\r\n const deserializedArgs = deserializeArgs(args || []);\r\n\r\n // Execute the action\r\n const result = await executeAction(actionId, deserializedArgs, {\r\n request: new Request(`http://${req.headers.host}${req.url}`, {\r\n method: req.method,\r\n headers: req.headers as any\r\n })\r\n });\r\n\r\n // Send response\r\n res.writeHead(200, { \r\n 'Content-Type': 'application/json',\r\n 'X-Flexi-Action': actionId\r\n });\r\n res.end(JSON.stringify(result));\r\n\r\n } catch (error: any) {\r\n console.error('Server Action Error:', error);\r\n res.writeHead(500, { 'Content-Type': 'application/json' });\r\n res.end(JSON.stringify({ \r\n success: false, \r\n error: error.message || 'Action execution failed' \r\n }));\r\n }\r\n}\r\n\r\n/**\r\n * Creates an enhanced API response object\r\n */\r\nfunction createApiResponse(res) {\r\n return {\r\n _res: res,\r\n _status: 200,\r\n _headers: {},\r\n\r\n status(code) {\r\n this._status = code;\r\n return this;\r\n },\r\n\r\n setHeader(name, value) {\r\n this._headers[name] = value;\r\n return this;\r\n },\r\n\r\n json(data) {\r\n this._headers['Content-Type'] = 'application/json';\r\n this._send(JSON.stringify(data));\r\n },\r\n\r\n send(data) {\r\n if (typeof data === 'object') {\r\n this.json(data);\r\n } else {\r\n this._headers['Content-Type'] = this._headers['Content-Type'] || 'text/plain';\r\n this._send(String(data));\r\n }\r\n },\r\n\r\n html(data) {\r\n this._headers['Content-Type'] = 'text/html';\r\n this._send(data);\r\n },\r\n\r\n redirect(url, status = 302) {\r\n this._status = status;\r\n this._headers['Location'] = url;\r\n this._send('');\r\n },\r\n\r\n _send(body) {\r\n if (!this._res.headersSent) {\r\n this._res.writeHead(this._status, this._headers);\r\n this._res.end(body);\r\n }\r\n }\r\n };\r\n}\r\n\r\n/**\r\n * Handles page route requests with SSR\r\n */\r\nasync function handlePageRoute(req, res, route, routes, config, loadModule, url) {\r\n try {\r\n // Run route-specific middleware if exists\r\n if (route.middleware) {\r\n try {\r\n const middlewareModule = await loadModule(route.middleware);\r\n const middlewareFn = middlewareModule.default || middlewareModule.middleware;\r\n \r\n if (typeof middlewareFn === 'function') {\r\n const result = await middlewareFn(req, res, { route, params: route.params });\r\n \r\n // If middleware returns a response, use it\r\n if (result?.redirect) {\r\n res.writeHead(result.statusCode || 307, { 'Location': result.redirect });\r\n res.end();\r\n return;\r\n }\r\n \r\n if (result?.rewrite) {\r\n // Rewrite to different path\r\n req.url = result.rewrite;\r\n }\r\n \r\n if (result === false || result?.stop) {\r\n // Middleware stopped the request\r\n return;\r\n }\r\n }\r\n } catch (middlewareError: any) {\r\n console.error('Route middleware error:', middlewareError.message);\r\n }\r\n }\r\n\r\n // Load page module\r\n const pageModule = await loadModule(route.filePath);\r\n const Component = pageModule.default;\r\n\r\n if (!Component) {\r\n throw new Error(`No default export in ${route.filePath}`);\r\n }\r\n\r\n // Create request context\r\n const query = Object.fromEntries(url.searchParams);\r\n const context = createRequestContext(req, res, route.params, query);\r\n\r\n // Get page props\r\n let props = { params: route.params, query };\r\n\r\n // Handle getServerSideProps\r\n if (pageModule.getServerSideProps) {\r\n const result = await pageModule.getServerSideProps({\r\n params: route.params,\r\n query,\r\n req,\r\n res\r\n });\r\n\r\n if (result.redirect) {\r\n res.writeHead(result.redirect.statusCode || 302, {\r\n Location: result.redirect.destination\r\n });\r\n res.end();\r\n return;\r\n }\r\n\r\n if (result.notFound) {\r\n res.writeHead(404, { 'Content-Type': 'text/html' });\r\n res.end(renderError(404, 'Page not found'));\r\n return;\r\n }\r\n\r\n props = { ...props, ...result.props };\r\n }\r\n\r\n // Handle getStaticProps (for ISR)\r\n if (pageModule.getStaticProps) {\r\n const result = await pageModule.getStaticProps({ params: route.params });\r\n \r\n if (result.notFound) {\r\n res.writeHead(404, { 'Content-Type': 'text/html' });\r\n res.end(renderError(404, 'Page not found'));\r\n return;\r\n }\r\n\r\n props = { ...props, ...result.props };\r\n }\r\n\r\n // Load layouts (only if layouts directory exists and has layouts)\r\n const layouts = [];\r\n \r\n try {\r\n const layoutConfigs = findRouteLayouts(route, routes.layouts);\r\n for (const layoutConfig of layoutConfigs) {\r\n if (layoutConfig.filePath) {\r\n const layoutModule = await loadModule(layoutConfig.filePath);\r\n if (layoutModule.default) {\r\n layouts.push({\r\n Component: layoutModule.default,\r\n props: {}\r\n });\r\n }\r\n }\r\n }\r\n } catch (layoutError) {\r\n // Layouts are optional, continue without them\r\n console.warn('Layout loading skipped:', layoutError.message);\r\n }\r\n\r\n // Load loading component if exists\r\n let LoadingComponent = null;\r\n if (route.loading) {\r\n const loadingModule = await loadModule(route.loading);\r\n LoadingComponent = loadingModule.default;\r\n }\r\n\r\n // Load error component if exists\r\n let ErrorComponent = null;\r\n if (route.error) {\r\n const errorModule = await loadModule(route.error);\r\n ErrorComponent = errorModule.default;\r\n }\r\n\r\n // Run before render hook\r\n props = await pluginManager.runWaterfallHook(\r\n PluginHooks.BEFORE_RENDER,\r\n props,\r\n { route, Component }\r\n );\r\n\r\n // Check if this is a client component (needs hydration)\r\n const isClientComponent = route.isClientComponent || \r\n (pageModule.__isClient) ||\r\n (typeof pageModule.default === 'function' && pageModule.default.toString().includes('useState'));\r\n\r\n // Render the page\r\n let html = await renderPage({\r\n Component,\r\n props,\r\n layouts,\r\n loading: LoadingComponent,\r\n error: ErrorComponent,\r\n islands: getRegisteredIslands(),\r\n title: pageModule.title || pageModule.metadata?.title || 'FlexiReact App',\r\n meta: pageModule.metadata || {},\r\n styles: config.styles || [],\r\n scripts: config.scripts || [],\r\n favicon: config.favicon || null,\r\n needsHydration: isClientComponent,\r\n componentPath: route.filePath,\r\n route: route.path || url.pathname,\r\n isSSG: !!pageModule.getStaticProps\r\n });\r\n\r\n // Add island hydration script\r\n const islands = getRegisteredIslands();\r\n if (islands.length > 0 && config.islands.enabled) {\r\n const hydrationScript = generateAdvancedHydrationScript(islands);\r\n html = html.replace('</body>', `${hydrationScript}</body>`);\r\n }\r\n\r\n // Add client hydration for 'use client' components\r\n if (isClientComponent) {\r\n const hydrationScript = generateClientHydrationScript(route.filePath, props);\r\n html = html.replace('</body>', `${hydrationScript}</body>`);\r\n }\r\n\r\n // Run after render hook\r\n html = await pluginManager.runWaterfallHook(\r\n PluginHooks.AFTER_RENDER,\r\n html,\r\n { route, Component, props }\r\n );\r\n\r\n res.writeHead(200, { 'Content-Type': 'text/html' });\r\n res.end(html);\r\n\r\n } catch (error) {\r\n console.error('Page Render Error:', error);\r\n throw error;\r\n }\r\n}\r\n\r\n/**\r\n * Serves a client component as JavaScript for hydration\r\n */\r\nasync function serveClientComponent(res, pagesDir, componentName) {\r\n const { transformSync } = await import('esbuild');\r\n \r\n // Remove .tsx.js or .jsx.js suffix if present\r\n const cleanName = componentName.replace(/\\.(tsx|jsx|ts|js)\\.js$/, '').replace(/\\.js$/, '');\r\n \r\n // Find the component file (support TypeScript)\r\n const possiblePaths = [\r\n path.join(pagesDir, `${cleanName}.tsx`),\r\n path.join(pagesDir, `${cleanName}.ts`),\r\n path.join(pagesDir, `${cleanName}.jsx`),\r\n path.join(pagesDir, `${cleanName}.js`),\r\n ];\r\n \r\n let componentPath = null;\r\n for (const p of possiblePaths) {\r\n if (fs.existsSync(p)) {\r\n componentPath = p;\r\n break;\r\n }\r\n }\r\n \r\n if (!componentPath) {\r\n res.writeHead(404, { 'Content-Type': 'text/plain' });\r\n res.end(`Component not found: ${cleanName}`);\r\n return;\r\n }\r\n \r\n // Determine loader based on extension\r\n const ext = path.extname(componentPath);\r\n const loader = ext === '.tsx' ? 'tsx' : ext === '.ts' ? 'ts' : 'jsx';\r\n \r\n try {\r\n let source = fs.readFileSync(componentPath, 'utf-8');\r\n \r\n // Remove 'use client' directive\r\n source = source.replace(/^['\"]use (client|server|island)['\"];?\\s*/m, '');\r\n \r\n // Transform for browser\r\n const result = transformSync(source, {\r\n loader,\r\n format: 'esm',\r\n jsx: 'transform',\r\n jsxFactory: 'React.createElement',\r\n jsxFragment: 'React.Fragment',\r\n target: 'es2020',\r\n // Replace React imports with global\r\n banner: `\r\n const React = window.React;\r\n const useState = window.useState;\r\n const useEffect = window.useEffect;\r\n const useCallback = window.useCallback;\r\n const useMemo = window.useMemo;\r\n const useRef = window.useRef;\r\n `\r\n });\r\n \r\n // Remove all React imports since we're using globals\r\n let code = result.code;\r\n // Remove: import React from 'react'\r\n code = code.replace(/import\\s+React\\s+from\\s+['\"]react['\"];?\\s*/g, '');\r\n // Remove: import { useState } from 'react'\r\n code = code.replace(/import\\s+\\{[^}]+\\}\\s+from\\s+['\"]react['\"];?\\s*/g, '');\r\n // Remove: import React, { useState } from 'react'\r\n code = code.replace(/import\\s+React\\s*,\\s*\\{[^}]+\\}\\s+from\\s+['\"]react['\"];?\\s*/g, '');\r\n \r\n res.writeHead(200, { \r\n 'Content-Type': 'application/javascript',\r\n 'Cache-Control': 'no-cache'\r\n });\r\n res.end(code);\r\n \r\n } catch (error) {\r\n console.error('Error serving client component:', error);\r\n res.writeHead(500, { 'Content-Type': 'text/plain' });\r\n res.end('Error compiling component');\r\n }\r\n}\r\n\r\n/**\r\n * Generates client hydration script for 'use client' components\r\n */\r\nfunction generateClientHydrationScript(componentPath, props) {\r\n // Create a relative path for the client bundle (handle .tsx, .ts, .jsx, .js)\r\n const ext = path.extname(componentPath);\r\n const componentName = path.basename(componentPath, ext);\r\n \r\n return `\r\n<script type=\"module\">\r\n // FlexiReact Client Hydration\r\n (async function() {\r\n try {\r\n const React = await import('https://esm.sh/react@18.3.1');\r\n const ReactDOM = await import('https://esm.sh/react-dom@18.3.1/client');\r\n \r\n // Make React available globally for the component\r\n window.React = React.default || React;\r\n window.useState = React.useState;\r\n window.useEffect = React.useEffect;\r\n window.useCallback = React.useCallback;\r\n window.useMemo = React.useMemo;\r\n window.useRef = React.useRef;\r\n \r\n // Fetch the component code\r\n const response = await fetch('/_flexi/component/${componentName}.js');\r\n const code = await response.text();\r\n \r\n // Create and import the module\r\n const blob = new Blob([code], { type: 'application/javascript' });\r\n const moduleUrl = URL.createObjectURL(blob);\r\n const module = await import(moduleUrl);\r\n \r\n const Component = module.default;\r\n const props = ${JSON.stringify(props)};\r\n \r\n // Hydrate the root\r\n const root = document.getElementById('root');\r\n ReactDOM.hydrateRoot(root, window.React.createElement(Component, props));\r\n \r\n console.log('⚡ FlexiReact: Component hydrated successfully');\r\n } catch (error) {\r\n console.error('⚡ FlexiReact: Hydration failed', error);\r\n }\r\n })();\r\n</script>`;\r\n}\r\n\r\n/**\r\n * Parses request body\r\n */\r\nasync function parseBody(req) {\r\n return new Promise((resolve) => {\r\n const contentType = req.headers['content-type'] || '';\r\n let body = '';\r\n\r\n req.on('data', chunk => {\r\n body += chunk.toString();\r\n });\r\n\r\n req.on('end', () => {\r\n try {\r\n if (contentType.includes('application/json') && body) {\r\n resolve(JSON.parse(body));\r\n } else if (contentType.includes('application/x-www-form-urlencoded') && body) {\r\n resolve(Object.fromEntries(new URLSearchParams(body)));\r\n } else {\r\n resolve(body || null);\r\n }\r\n } catch {\r\n resolve(body);\r\n }\r\n });\r\n\r\n req.on('error', () => resolve(null));\r\n });\r\n}\r\n\r\nexport default createServer;\r\n","/**\r\n * FlexiReact Configuration System\r\n * Handles loading and merging of configuration from flexireact.config.js\r\n */\r\n\r\nimport fs from 'fs';\r\nimport path from 'path';\r\nimport { pathToFileURL } from 'url';\r\n\r\n// Default configuration\r\nexport const defaultConfig = {\r\n // Directories\r\n pagesDir: 'pages',\r\n layoutsDir: 'layouts',\r\n publicDir: 'public',\r\n outDir: '.flexi',\r\n \r\n // Build options\r\n build: {\r\n target: 'es2022',\r\n minify: true,\r\n sourcemap: true,\r\n splitting: true\r\n },\r\n \r\n // Server options\r\n server: {\r\n port: 3000,\r\n host: 'localhost'\r\n },\r\n \r\n // SSG options\r\n ssg: {\r\n enabled: false,\r\n paths: []\r\n },\r\n \r\n // Islands (partial hydration)\r\n islands: {\r\n enabled: true\r\n },\r\n \r\n // RSC options\r\n rsc: {\r\n enabled: true\r\n },\r\n \r\n // Plugins\r\n plugins: [],\r\n \r\n // Styles (CSS files to include)\r\n styles: [],\r\n \r\n // Scripts (JS files to include)\r\n scripts: [],\r\n \r\n // Favicon path\r\n favicon: null\r\n};\r\n\r\n/**\r\n * Loads configuration from the project root\r\n * @param {string} projectRoot - Path to project root\r\n * @returns {Object} Merged configuration\r\n */\r\nexport async function loadConfig(projectRoot: string) {\r\n // Try .ts first, then .js\r\n const configPathTs = path.join(projectRoot, 'flexireact.config.ts');\r\n const configPathJs = path.join(projectRoot, 'flexireact.config.js');\r\n const configPath = fs.existsSync(configPathTs) ? configPathTs : configPathJs;\r\n \r\n let userConfig = {};\r\n \r\n if (fs.existsSync(configPath)) {\r\n try {\r\n const configUrl = pathToFileURL(configPath).href;\r\n const module = await import(`${configUrl}?t=${Date.now()}`);\r\n userConfig = module.default || module;\r\n } catch (error: any) {\r\n console.warn('Warning: Failed to load flexireact config:', error.message);\r\n }\r\n }\r\n \r\n // Deep merge configs\r\n return deepMerge(defaultConfig, userConfig);\r\n}\r\n\r\n/**\r\n * Deep merge two objects\r\n */\r\nfunction deepMerge(target, source) {\r\n const result = { ...target };\r\n \r\n for (const key in source) {\r\n if (source[key] && typeof source[key] === 'object' && !Array.isArray(source[key])) {\r\n result[key] = deepMerge(target[key] || {}, source[key]);\r\n } else {\r\n result[key] = source[key];\r\n }\r\n }\r\n \r\n return result;\r\n}\r\n\r\n/**\r\n * Resolves all paths in config relative to project root\r\n */\r\nexport function resolvePaths(config, projectRoot) {\r\n return {\r\n ...config,\r\n pagesDir: path.resolve(projectRoot, config.pagesDir),\r\n layoutsDir: path.resolve(projectRoot, config.layoutsDir),\r\n publicDir: path.resolve(projectRoot, config.publicDir),\r\n outDir: path.resolve(projectRoot, config.outDir)\r\n };\r\n}\r\n","/**\r\n * FlexiReact Router v2\r\n * Advanced file-based routing with nested routes, loading, and error boundaries\r\n * \r\n * Supports multiple routing conventions:\r\n * - pages/ : Traditional file-based routing (index.tsx, about.tsx)\r\n * - app/ : Next.js style App Router (page.tsx, layout.tsx)\r\n * - routes/ : FlexiReact v2 routes directory (home.tsx → /, [slug].tsx → /:slug)\r\n */\r\n\r\nimport fs from 'fs';\r\nimport path from 'path';\r\nimport { isServerComponent, isClientComponent, isIsland } from '../utils.js';\r\n\r\n/**\r\n * Route types\r\n */\r\nexport const RouteType = {\r\n PAGE: 'page',\r\n API: 'api',\r\n LAYOUT: 'layout',\r\n LOADING: 'loading',\r\n ERROR: 'error',\r\n NOT_FOUND: 'not-found'\r\n};\r\n\r\n/**\r\n * Builds the complete route tree from all routing directories\r\n */\r\nexport function buildRouteTree(pagesDir, layoutsDir, appDir = null, routesDir = null) {\r\n const projectRoot = path.dirname(pagesDir);\r\n \r\n const routes: {\r\n pages: any[];\r\n api: any[];\r\n layouts: Map<any, any>;\r\n tree: Record<string, any>;\r\n appRoutes: any[];\r\n flexiRoutes: any[];\r\n rootLayout?: string;\r\n } = {\r\n pages: [],\r\n api: [],\r\n layouts: new Map(),\r\n tree: {},\r\n appRoutes: [], // Next.js style app router routes\r\n flexiRoutes: [] // FlexiReact v2 routes/ directory\r\n };\r\n\r\n // 1. Scan routes/ directory (FlexiReact v2 - priority)\r\n const routesDirPath = routesDir || path.join(projectRoot, 'routes');\r\n if (fs.existsSync(routesDirPath)) {\r\n scanRoutesDirectory(routesDirPath, routesDirPath, routes);\r\n }\r\n\r\n // 2. Scan app/ directory (Next.js style App Router)\r\n const appDirPath = appDir || path.join(projectRoot, 'app');\r\n if (fs.existsSync(appDirPath)) {\r\n scanAppDirectory(appDirPath, appDirPath, routes);\r\n }\r\n\r\n // 3. Scan pages/ directory (traditional routing - fallback)\r\n if (fs.existsSync(pagesDir)) {\r\n scanDirectory(pagesDir, pagesDir, routes);\r\n }\r\n \r\n // 4. Scan layouts/ directory\r\n if (fs.existsSync(layoutsDir)) {\r\n scanLayouts(layoutsDir, routes.layouts);\r\n }\r\n\r\n // 5. Check for root layout in app/ directory\r\n const rootLayoutPath = path.join(appDirPath, 'layout.tsx');\r\n const rootLayoutPathJs = path.join(appDirPath, 'layout.jsx');\r\n if (fs.existsSync(rootLayoutPath)) {\r\n routes.rootLayout = rootLayoutPath;\r\n } else if (fs.existsSync(rootLayoutPathJs)) {\r\n routes.rootLayout = rootLayoutPathJs;\r\n }\r\n\r\n // Build route tree for nested routes\r\n routes.tree = buildTree([...routes.flexiRoutes, ...routes.appRoutes, ...routes.pages]);\r\n\r\n return routes;\r\n}\r\n\r\n/**\r\n * Scans routes/ directory for FlexiReact v2 style routing\r\n * \r\n * Convention:\r\n * - home.tsx → /\r\n * - about.tsx → /about\r\n * - blog/index.tsx → /blog\r\n * - blog/[slug].tsx → /blog/:slug\r\n * - (public)/home.tsx → / (route group, not in URL)\r\n * - api/hello.ts → /api/hello (API route)\r\n * - dashboard/layout.tsx → layout for /dashboard/*\r\n */\r\nfunction scanRoutesDirectory(baseDir, currentDir, routes, parentSegments = [], parentLayout = null, parentMiddleware = null) {\r\n const entries = fs.readdirSync(currentDir, { withFileTypes: true });\r\n \r\n // Find special files in current directory\r\n let layoutFile = null;\r\n let loadingFile = null;\r\n let errorFile = null;\r\n let middlewareFile = null;\r\n \r\n for (const entry of entries) {\r\n if (entry.isFile()) {\r\n const name = entry.name.replace(/\\.(jsx|js|tsx|ts)$/, '');\r\n const fullPath = path.join(currentDir, entry.name);\r\n const ext = path.extname(entry.name);\r\n \r\n // Special files\r\n if (name === 'layout') layoutFile = fullPath;\r\n if (name === 'loading') loadingFile = fullPath;\r\n if (name === 'error') errorFile = fullPath;\r\n if (name === '_middleware' || name === 'middleware') middlewareFile = fullPath;\r\n \r\n // Skip special files and non-route files\r\n if (['layout', 'loading', 'error', 'not-found', '_middleware', 'middleware'].includes(name)) continue;\r\n if (!['.tsx', '.jsx', '.ts', '.js'].includes(ext)) continue;\r\n \r\n // API routes (in api/ folder or .ts/.js files in api/)\r\n const relativePath = path.relative(baseDir, currentDir);\r\n const isApiRoute = relativePath.startsWith('api') || relativePath.startsWith('api/');\r\n \r\n if (isApiRoute && ['.ts', '.js'].includes(ext)) {\r\n const apiPath = '/' + [...parentSegments, name === 'index' ? '' : name].filter(Boolean).join('/');\r\n routes.api.push({\r\n type: RouteType.API,\r\n path: apiPath.replace(/\\/+/g, '/') || '/',\r\n filePath: fullPath,\r\n pattern: createRoutePattern(apiPath),\r\n segments: [...parentSegments, name === 'index' ? '' : name].filter(Boolean)\r\n });\r\n continue;\r\n }\r\n \r\n // Page routes\r\n if (['.tsx', '.jsx'].includes(ext)) {\r\n let routePath;\r\n \r\n // home.tsx → /\r\n if (name === 'home' && parentSegments.length === 0) {\r\n routePath = '/';\r\n }\r\n // index.tsx → parent path\r\n else if (name === 'index') {\r\n routePath = '/' + parentSegments.join('/') || '/';\r\n }\r\n // [param].tsx → /:param\r\n else if (name.startsWith('[') && name.endsWith(']')) {\r\n const paramName = name.slice(1, -1);\r\n // Handle catch-all [...slug]\r\n if (paramName.startsWith('...')) {\r\n routePath = '/' + [...parentSegments, '*' + paramName.slice(3)].join('/');\r\n } else {\r\n routePath = '/' + [...parentSegments, ':' + paramName].join('/');\r\n }\r\n }\r\n // regular.tsx → /regular\r\n else {\r\n routePath = '/' + [...parentSegments, name].join('/');\r\n }\r\n \r\n routes.flexiRoutes.push({\r\n type: RouteType.PAGE,\r\n path: routePath.replace(/\\/+/g, '/'),\r\n filePath: fullPath,\r\n pattern: createRoutePattern(routePath),\r\n segments: routePath.split('/').filter(Boolean),\r\n layout: layoutFile || parentLayout,\r\n loading: loadingFile,\r\n error: errorFile,\r\n middleware: middlewareFile || parentMiddleware,\r\n isFlexiRouter: true,\r\n isServerComponent: isServerComponent(fullPath),\r\n isClientComponent: isClientComponent(fullPath),\r\n isIsland: isIsland(fullPath)\r\n });\r\n }\r\n }\r\n }\r\n \r\n // Recursively scan subdirectories\r\n for (const entry of entries) {\r\n if (entry.isDirectory()) {\r\n const fullPath = path.join(currentDir, entry.name);\r\n const dirName = entry.name;\r\n \r\n // Skip special directories\r\n if (dirName.startsWith('_') || dirName.startsWith('.')) continue;\r\n \r\n // Handle route groups (parentheses) - don't add to URL\r\n const isGroup = dirName.startsWith('(') && dirName.endsWith(')');\r\n \r\n // Handle dynamic segments [param]\r\n let segmentName = dirName;\r\n if (dirName.startsWith('[') && dirName.endsWith(']')) {\r\n const paramName = dirName.slice(1, -1);\r\n if (paramName.startsWith('...')) {\r\n segmentName = '*' + paramName.slice(3);\r\n } else {\r\n segmentName = ':' + paramName;\r\n }\r\n }\r\n \r\n const newSegments = isGroup ? parentSegments : [...parentSegments, segmentName];\r\n const newLayout = layoutFile || parentLayout;\r\n const newMiddleware = middlewareFile || parentMiddleware;\r\n \r\n scanRoutesDirectory(baseDir, fullPath, routes, newSegments, newLayout, newMiddleware);\r\n }\r\n }\r\n}\r\n\r\n/**\r\n * Scans app directory for Next.js style routing\r\n * Supports: page.tsx, layout.tsx, loading.tsx, error.tsx, not-found.tsx\r\n */\r\nfunction scanAppDirectory(baseDir, currentDir, routes, parentSegments = [], parentLayout = null, parentMiddleware = null) {\r\n const entries = fs.readdirSync(currentDir, { withFileTypes: true });\r\n \r\n // Find special files in current directory\r\n const specialFiles: Record<string, string | null> = {\r\n page: null,\r\n layout: null,\r\n loading: null,\r\n error: null,\r\n notFound: null,\r\n template: null,\r\n middleware: null\r\n };\r\n\r\n for (const entry of entries) {\r\n if (entry.isFile()) {\r\n const name = entry.name.replace(/\\.(jsx|js|tsx|ts)$/, '');\r\n const fullPath = path.join(currentDir, entry.name);\r\n \r\n if (name === 'page') specialFiles.page = fullPath;\r\n if (name === 'layout') specialFiles.layout = fullPath;\r\n if (name === 'loading') specialFiles.loading = fullPath;\r\n if (name === 'error') specialFiles.error = fullPath;\r\n if (name === 'not-found') specialFiles.notFound = fullPath;\r\n if (name === 'template') specialFiles.template = fullPath;\r\n if (name === 'middleware' || name === '_middleware') specialFiles.middleware = fullPath;\r\n }\r\n }\r\n\r\n // If there's a page.tsx, create a route\r\n if (specialFiles.page) {\r\n const routePath = '/' + parentSegments.join('/') || '/';\r\n \r\n routes.appRoutes.push({\r\n type: RouteType.PAGE,\r\n path: routePath.replace(/\\/+/g, '/'),\r\n filePath: specialFiles.page,\r\n pattern: createRoutePattern(routePath),\r\n segments: parentSegments,\r\n layout: specialFiles.layout || parentLayout,\r\n loading: specialFiles.loading,\r\n error: specialFiles.error,\r\n notFound: specialFiles.notFound,\r\n template: specialFiles.template,\r\n middleware: specialFiles.middleware || parentMiddleware,\r\n isAppRouter: true,\r\n isServerComponent: isServerComponent(specialFiles.page),\r\n isClientComponent: isClientComponent(specialFiles.page),\r\n isIsland: isIsland(specialFiles.page)\r\n });\r\n }\r\n\r\n // Recursively scan subdirectories\r\n for (const entry of entries) {\r\n if (entry.isDirectory()) {\r\n const fullPath = path.join(currentDir, entry.name);\r\n \r\n // Handle route groups (parentheses) - don't add to URL\r\n const isGroup = entry.name.startsWith('(') && entry.name.endsWith(')');\r\n \r\n // Handle dynamic segments [param]\r\n let segmentName = entry.name;\r\n if (entry.name.startsWith('[') && entry.name.endsWith(']')) {\r\n // Convert [param] to :param\r\n segmentName = ':' + entry.name.slice(1, -1);\r\n // Handle catch-all [...param]\r\n if (entry.name.startsWith('[...')) {\r\n segmentName = '*' + entry.name.slice(4, -1);\r\n }\r\n // Handle optional catch-all [[...param]]\r\n if (entry.name.startsWith('[[...')) {\r\n segmentName = '*' + entry.name.slice(5, -2);\r\n }\r\n }\r\n \r\n const newSegments = isGroup ? parentSegments : [...parentSegments, segmentName];\r\n const newLayout = specialFiles.layout || parentLayout;\r\n const newMiddleware = specialFiles.middleware || parentMiddleware;\r\n \r\n scanAppDirectory(baseDir, fullPath, routes, newSegments, newLayout, newMiddleware);\r\n }\r\n }\r\n}\r\n\r\n/**\r\n * Scans directory recursively for route files\r\n */\r\nfunction scanDirectory(baseDir, currentDir, routes, parentSegments = []) {\r\n const entries = fs.readdirSync(currentDir, { withFileTypes: true });\r\n \r\n // First, find special files in current directory\r\n const specialFiles = {\r\n layout: null,\r\n loading: null,\r\n error: null,\r\n notFound: null\r\n };\r\n\r\n for (const entry of entries) {\r\n if (entry.isFile()) {\r\n const name = entry.name.replace(/\\.(jsx|js|tsx|ts)$/, '');\r\n const fullPath = path.join(currentDir, entry.name);\r\n \r\n if (name === 'layout') specialFiles.layout = fullPath;\r\n if (name === 'loading') specialFiles.loading = fullPath;\r\n if (name === 'error') specialFiles.error = fullPath;\r\n if (name === 'not-found' || name === '404') specialFiles.notFound = fullPath;\r\n }\r\n }\r\n\r\n for (const entry of entries) {\r\n const fullPath = path.join(currentDir, entry.name);\r\n const relativePath = path.relative(baseDir, fullPath);\r\n\r\n if (entry.isDirectory()) {\r\n // Handle route groups (parentheses)\r\n const isGroup = entry.name.startsWith('(') && entry.name.endsWith(')');\r\n const newSegments = isGroup ? parentSegments : [...parentSegments, entry.name];\r\n \r\n scanDirectory(baseDir, fullPath, routes, newSegments);\r\n } else if (entry.isFile()) {\r\n const ext = path.extname(entry.name);\r\n const baseName = path.basename(entry.name, ext);\r\n \r\n // Skip special files (already processed)\r\n if (['layout', 'loading', 'error', 'not-found', '404'].includes(baseName)) {\r\n continue;\r\n }\r\n \r\n if (['.jsx', '.js', '.tsx', '.ts'].includes(ext)) {\r\n const isApi = relativePath.startsWith('api' + path.sep) || relativePath.startsWith('api/');\r\n \r\n if (isApi && ['.js', '.ts'].includes(ext)) {\r\n routes.api.push(createRoute(fullPath, baseDir, specialFiles, RouteType.API));\r\n } else if (!isApi && ['.jsx', '.tsx'].includes(ext)) {\r\n routes.pages.push(createRoute(fullPath, baseDir, specialFiles, RouteType.PAGE));\r\n }\r\n }\r\n }\r\n }\r\n}\r\n\r\n/**\r\n * Creates a route object from file path\r\n */\r\nfunction createRoute(filePath, baseDir, specialFiles, type) {\r\n const relativePath = path.relative(baseDir, filePath);\r\n const routePath = filePathToRoute(relativePath);\r\n \r\n return {\r\n type,\r\n path: routePath,\r\n filePath,\r\n pattern: createRoutePattern(routePath),\r\n segments: routePath.split('/').filter(Boolean),\r\n layout: specialFiles.layout,\r\n loading: specialFiles.loading,\r\n error: specialFiles.error,\r\n notFound: specialFiles.notFound,\r\n isServerComponent: isServerComponent(filePath),\r\n isClientComponent: isClientComponent(filePath),\r\n isIsland: isIsland(filePath)\r\n };\r\n}\r\n\r\n/**\r\n * Scans layouts directory\r\n */\r\nfunction scanLayouts(layoutsDir, layoutsMap) {\r\n const entries = fs.readdirSync(layoutsDir, { withFileTypes: true });\r\n \r\n for (const entry of entries) {\r\n if (entry.isFile() && /\\.(jsx|tsx)$/.test(entry.name)) {\r\n const name = entry.name.replace(/\\.(jsx|tsx)$/, '');\r\n layoutsMap.set(name, path.join(layoutsDir, entry.name));\r\n }\r\n }\r\n}\r\n\r\n/**\r\n * Converts file path to route path\r\n */\r\nfunction filePathToRoute(filePath) {\r\n let route = filePath.replace(/\\\\/g, '/');\r\n \r\n // Remove extension\r\n route = route.replace(/\\.(jsx|js|tsx|ts)$/, '');\r\n \r\n // Convert [param] to :param\r\n route = route.replace(/\\[\\.\\.\\.([^\\]]+)\\]/g, '*$1'); // Catch-all [...slug]\r\n route = route.replace(/\\[([^\\]]+)\\]/g, ':$1');\r\n \r\n // Handle index files\r\n if (route.endsWith('/index')) {\r\n route = route.slice(0, -6) || '/';\r\n } else if (route === 'index') {\r\n route = '/';\r\n }\r\n \r\n // Handle route groups - remove (groupName) from path\r\n route = route.replace(/\\/?\\([^)]+\\)\\/?/g, '/');\r\n \r\n // Ensure leading slash and clean up\r\n if (!route.startsWith('/')) {\r\n route = '/' + route;\r\n }\r\n route = route.replace(/\\/+/g, '/');\r\n \r\n return route;\r\n}\r\n\r\n/**\r\n * Creates regex pattern for route matching\r\n */\r\nfunction createRoutePattern(routePath) {\r\n let pattern = routePath\r\n .replace(/\\*[^/]*/g, '(.*)') // Catch-all\r\n .replace(/:[^/]+/g, '([^/]+)') // Dynamic segments\r\n .replace(/\\//g, '\\\\/');\r\n \r\n return new RegExp(`^${pattern}$`);\r\n}\r\n\r\n/**\r\n * Builds a tree structure for nested routes\r\n */\r\nfunction buildTree(routes) {\r\n const tree = { children: {}, routes: [] };\r\n \r\n for (const route of routes) {\r\n let current = tree;\r\n \r\n for (const segment of route.segments) {\r\n if (!current.children[segment]) {\r\n current.children[segment] = { children: {}, routes: [] };\r\n }\r\n current = current.children[segment];\r\n }\r\n \r\n current.routes.push(route);\r\n }\r\n \r\n return tree;\r\n}\r\n\r\n/**\r\n * Matches URL path against routes\r\n */\r\nexport function matchRoute(urlPath, routes) {\r\n const normalizedPath = urlPath === '' ? '/' : urlPath.split('?')[0];\r\n \r\n for (const route of routes) {\r\n const match = normalizedPath.match(route.pattern);\r\n \r\n if (match) {\r\n const params = extractParams(route.path, match);\r\n return { ...route, params };\r\n }\r\n }\r\n \r\n return null;\r\n}\r\n\r\n/**\r\n * Extracts parameters from route match\r\n */\r\nfunction extractParams(routePath, match) {\r\n const params = {};\r\n const paramNames = [];\r\n \r\n // Extract param names from route path\r\n const paramRegex = /:([^/]+)|\\*([^/]*)/g;\r\n let paramMatch;\r\n \r\n while ((paramMatch = paramRegex.exec(routePath)) !== null) {\r\n paramNames.push(paramMatch[1] || paramMatch[2] || 'splat');\r\n }\r\n \r\n paramNames.forEach((name, index) => {\r\n params[name] = match[index + 1];\r\n });\r\n \r\n return params;\r\n}\r\n\r\n/**\r\n * Finds all layouts that apply to a route\r\n */\r\nexport function findRouteLayouts(route, layoutsMap) {\r\n const layouts = [];\r\n \r\n // Check for segment-based layouts\r\n let currentPath = '';\r\n for (const segment of route.segments) {\r\n currentPath += '/' + segment;\r\n const layoutName = segment;\r\n \r\n if (layoutsMap.has(layoutName)) {\r\n layouts.push({\r\n name: layoutName,\r\n filePath: layoutsMap.get(layoutName)\r\n });\r\n }\r\n }\r\n \r\n // Check for route-specific layout\r\n if (route.layout) {\r\n layouts.push({\r\n name: 'route',\r\n filePath: route.layout\r\n });\r\n }\r\n \r\n // Check for root layout\r\n if (layoutsMap.has('root')) {\r\n layouts.unshift({\r\n name: 'root',\r\n filePath: layoutsMap.get('root')\r\n });\r\n }\r\n \r\n return layouts;\r\n}\r\n\r\nexport default {\r\n buildRouteTree,\r\n matchRoute,\r\n findRouteLayouts,\r\n RouteType\r\n};\r\n","/**\r\n * FlexiReact Utility Functions\r\n */\r\n\r\nimport fs from 'fs';\r\nimport path from 'path';\r\nimport crypto from 'crypto';\r\n\r\n/**\r\n * Generates a unique hash for cache busting\r\n */\r\nexport function generateHash(content) {\r\n return crypto.createHash('md5').update(content).digest('hex').slice(0, 8);\r\n}\r\n\r\n/**\r\n * Escapes HTML special characters\r\n */\r\nexport function escapeHtml(str) {\r\n const htmlEntities = {\r\n '&': '&',\r\n '<': '<',\r\n '>': '>',\r\n '\"': '"',\r\n \"'\": '''\r\n };\r\n return String(str).replace(/[&<>\"']/g, char => htmlEntities[char]);\r\n}\r\n\r\n/**\r\n * Recursively finds all files matching a pattern\r\n */\r\nexport function findFiles(dir, pattern, files = []) {\r\n if (!fs.existsSync(dir)) return files;\r\n \r\n const entries = fs.readdirSync(dir, { withFileTypes: true });\r\n \r\n for (const entry of entries) {\r\n const fullPath = path.join(dir, entry.name);\r\n \r\n if (entry.isDirectory()) {\r\n findFiles(fullPath, pattern, files);\r\n } else if (pattern.test(entry.name)) {\r\n files.push(fullPath);\r\n }\r\n }\r\n \r\n return files;\r\n}\r\n\r\n/**\r\n * Ensures a directory exists\r\n */\r\nexport function ensureDir(dir) {\r\n if (!fs.existsSync(dir)) {\r\n fs.mkdirSync(dir, { recursive: true });\r\n }\r\n}\r\n\r\n/**\r\n * Cleans a directory\r\n */\r\nexport function cleanDir(dir) {\r\n if (fs.existsSync(dir)) {\r\n fs.rmSync(dir, { recursive: true, force: true });\r\n }\r\n fs.mkdirSync(dir, { recursive: true });\r\n}\r\n\r\n/**\r\n * Copies a directory recursively\r\n */\r\nexport function copyDir(src, dest) {\r\n ensureDir(dest);\r\n \r\n const entries = fs.readdirSync(src, { withFileTypes: true });\r\n \r\n for (const entry of entries) {\r\n const srcPath = path.join(src, entry.name);\r\n const destPath = path.join(dest, entry.name);\r\n \r\n if (entry.isDirectory()) {\r\n copyDir(srcPath, destPath);\r\n } else {\r\n fs.copyFileSync(srcPath, destPath);\r\n }\r\n }\r\n}\r\n\r\n/**\r\n * Debounce function for file watching\r\n */\r\nexport function debounce(fn, delay) {\r\n let timeout;\r\n return (...args) => {\r\n clearTimeout(timeout);\r\n timeout = setTimeout(() => fn(...args), delay);\r\n };\r\n}\r\n\r\n/**\r\n * Formats bytes to human readable string\r\n */\r\nexport function formatBytes(bytes) {\r\n if (bytes === 0) return '0 B';\r\n const k = 1024;\r\n const sizes = ['B', 'KB', 'MB', 'GB'];\r\n const i = Math.floor(Math.log(bytes) / Math.log(k));\r\n return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];\r\n}\r\n\r\n/**\r\n * Formats milliseconds to human readable string\r\n */\r\nexport function formatTime(ms) {\r\n if (ms < 1000) return `${ms}ms`;\r\n return `${(ms / 1000).toFixed(2)}s`;\r\n}\r\n\r\n/**\r\n * Creates a deferred promise\r\n */\r\nexport function createDeferred() {\r\n let resolve, reject;\r\n const promise = new Promise((res, rej) => {\r\n resolve = res;\r\n reject = rej;\r\n });\r\n return { promise, resolve, reject };\r\n}\r\n\r\n/**\r\n * Sleep utility\r\n */\r\nexport function sleep(ms) {\r\n return new Promise(resolve => setTimeout(resolve, ms));\r\n}\r\n\r\n/**\r\n * Check if a file is a server component (has 'use server' directive)\r\n */\r\nexport function isServerComponent(filePath) {\r\n try {\r\n const content = fs.readFileSync(filePath, 'utf-8');\r\n const firstLine = content.split('\\n')[0].trim();\r\n return firstLine === \"'use server'\" || firstLine === '\"use server\"';\r\n } catch {\r\n return false;\r\n }\r\n}\r\n\r\n/**\r\n * Check if a file is a client component (has 'use client' directive)\r\n */\r\nexport function isClientComponent(filePath) {\r\n try {\r\n const content = fs.readFileSync(filePath, 'utf-8');\r\n const firstLine = content.split('\\n')[0].trim();\r\n return firstLine === \"'use client'\" || firstLine === '\"use client\"';\r\n } catch {\r\n return false;\r\n }\r\n}\r\n\r\n/**\r\n * Check if a component is an island (has 'use island' directive)\r\n */\r\nexport function isIsland(filePath) {\r\n try {\r\n const content = fs.readFileSync(filePath, 'utf-8');\r\n const firstLine = content.split('\\n')[0].trim();\r\n return firstLine === \"'use island'\" || firstLine === '\"use island\"';\r\n } catch {\r\n return false;\r\n }\r\n}\r\n","/**\r\n * FlexiReact Render System v2\r\n * SSR with layouts, loading states, error boundaries, and islands\r\n */\r\n\r\nimport React from 'react';\r\nimport { renderToString, renderToPipeableStream } from 'react-dom/server';\r\nimport { escapeHtml } from '../utils.js';\r\n\r\n/**\r\n * Renders a page with all its layouts and wrappers\r\n */\r\nexport async function renderPage(options) {\r\n const {\r\n Component,\r\n props = {},\r\n layouts = [],\r\n loading = null,\r\n error = null,\r\n islands = [],\r\n title = 'FlexiReact App',\r\n meta = {},\r\n scripts = [],\r\n styles = [],\r\n favicon = null,\r\n isSSG = false,\r\n route = '/',\r\n needsHydration = false\r\n } = options;\r\n\r\n const renderStart = Date.now();\r\n\r\n try {\r\n // Build the component tree - start with the page component\r\n let element: any = React.createElement(Component, props);\r\n \r\n // Wrap with error boundary if error component exists\r\n if (error) {\r\n element = React.createElement(ErrorBoundaryWrapper as any, {\r\n fallback: error,\r\n children: element\r\n });\r\n }\r\n\r\n // Wrap with Suspense if loading component exists (for streaming/async)\r\n if (loading) {\r\n element = React.createElement(React.Suspense as any, {\r\n fallback: React.createElement(loading),\r\n children: element\r\n });\r\n }\r\n \r\n // Wrap with layouts (innermost to outermost)\r\n // Each layout receives children as a prop\r\n for (const layout of [...layouts].reverse()) {\r\n if (layout.Component) {\r\n const LayoutComponent = layout.Component;\r\n element = React.createElement(LayoutComponent, {\r\n ...layout.props\r\n }, element);\r\n }\r\n }\r\n\r\n // Render to string\r\n const content = renderToString(element);\r\n \r\n // Calculate render time\r\n const renderTime = Date.now() - renderStart;\r\n \r\n // Generate island hydration scripts\r\n const islandScripts = generateIslandScripts(islands);\r\n \r\n // Build full HTML document\r\n return buildHtmlDocument({\r\n content,\r\n title,\r\n meta,\r\n scripts: [...scripts, ...islandScripts],\r\n styles,\r\n favicon,\r\n props,\r\n isSSG,\r\n renderTime,\r\n route,\r\n isClientComponent: needsHydration\r\n });\r\n\r\n } catch (err) {\r\n console.error('Render Error:', err);\r\n throw err;\r\n }\r\n}\r\n\r\n/**\r\n * Streaming SSR with React 18\r\n * Renders the page progressively, sending HTML chunks as they become ready\r\n */\r\nexport async function renderPageStream(options: {\r\n Component: React.ComponentType<any>;\r\n props?: Record<string, any>;\r\n layouts?: Array<{ Component: React.ComponentType<any>; props?: Record<string, any> }>;\r\n loading?: React.ComponentType | null;\r\n error?: React.ComponentType<{ error: Error }> | null;\r\n title?: string;\r\n meta?: Record<string, string>;\r\n scripts?: Array<string | { src?: string; content?: string; type?: string }>;\r\n styles?: Array<string | { content: string }>;\r\n favicon?: string | null;\r\n route?: string;\r\n onShellReady?: () => void;\r\n onAllReady?: () => void;\r\n onError?: (error: Error) => void;\r\n}): Promise<{ stream: NodeJS.ReadableStream; shellReady: Promise<void> }> {\r\n const {\r\n Component,\r\n props = {},\r\n layouts = [],\r\n loading = null,\r\n error = null,\r\n title = 'FlexiReact App',\r\n meta = {},\r\n scripts = [],\r\n styles = [],\r\n favicon = null,\r\n route = '/',\r\n onShellReady,\r\n onAllReady,\r\n onError\r\n } = options;\r\n\r\n const renderStart = Date.now();\r\n\r\n // Build the component tree\r\n let element: any = React.createElement(Component, props);\r\n\r\n // Wrap with error boundary if error component exists\r\n if (error) {\r\n element = React.createElement(ErrorBoundaryWrapper as any, {\r\n fallback: error,\r\n children: element\r\n });\r\n }\r\n\r\n // Wrap with Suspense if loading component exists\r\n if (loading) {\r\n element = React.createElement(React.Suspense as any, {\r\n fallback: React.createElement(loading),\r\n children: element\r\n });\r\n }\r\n\r\n // Wrap with layouts\r\n for (const layout of [...layouts].reverse()) {\r\n if (layout.Component) {\r\n element = React.createElement(layout.Component, layout.props, element);\r\n }\r\n }\r\n\r\n // Create the full document wrapper\r\n const DocumentWrapper = ({ children }: { children: React.ReactNode }) => {\r\n return React.createElement('html', { lang: 'en', className: 'dark' },\r\n React.createElement('head', null,\r\n React.createElement('meta', { charSet: 'UTF-8' }),\r\n React.createElement('meta', { name: 'viewport', content: 'width=device-width, initial-scale=1.0' }),\r\n React.createElement('title', null, title),\r\n favicon && React.createElement('link', { rel: 'icon', href: favicon }),\r\n ...Object.entries(meta).map(([name, content]) => \r\n React.createElement('meta', { key: name, name, content })\r\n ),\r\n ...styles.map((style, i) => \r\n typeof style === 'string'\r\n ? React.createElement('link', { key: i, rel: 'stylesheet', href: style })\r\n : React.createElement('style', { key: i, dangerouslySetInnerHTML: { __html: style.content } })\r\n )\r\n ),\r\n React.createElement('body', null,\r\n React.createElement('div', { id: 'root' }, children),\r\n ...scripts.map((script, i) => \r\n typeof script === 'string'\r\n ? React.createElement('script', { key: i, src: script })\r\n : script.src\r\n ? React.createElement('script', { key: i, src: script.src, type: script.type })\r\n : React.createElement('script', { key: i, type: script.type, dangerouslySetInnerHTML: { __html: script.content } })\r\n )\r\n )\r\n );\r\n };\r\n\r\n const fullElement = React.createElement(DocumentWrapper, null, element);\r\n\r\n // Create streaming render\r\n let shellReadyResolve: () => void;\r\n const shellReady = new Promise<void>((resolve) => {\r\n shellReadyResolve = resolve;\r\n });\r\n\r\n const { pipe, abort } = renderToPipeableStream(fullElement, {\r\n onShellReady() {\r\n const renderTime = Date.now() - renderStart;\r\n console.log(`⚡ Shell ready in ${renderTime}ms`);\r\n shellReadyResolve();\r\n onShellReady?.();\r\n },\r\n onAllReady() {\r\n const renderTime = Date.now() - renderStart;\r\n console.log(`✨ All content ready in ${renderTime}ms`);\r\n onAllReady?.();\r\n },\r\n onError(err: Error) {\r\n console.error('Streaming SSR Error:', err);\r\n onError?.(err);\r\n }\r\n });\r\n\r\n // Create a passthrough stream\r\n const { PassThrough } = await import('stream');\r\n const passThrough = new PassThrough();\r\n \r\n // Pipe the render stream to our passthrough\r\n pipe(passThrough);\r\n\r\n return {\r\n stream: passThrough,\r\n shellReady\r\n };\r\n}\r\n\r\n/**\r\n * Render to stream for HTTP response\r\n * Use this in the server to stream HTML to the client\r\n */\r\nexport function streamToResponse(\r\n res: { write: (chunk: string) => void; end: () => void },\r\n stream: NodeJS.ReadableStream,\r\n options: { onFinish?: () => void } = {}\r\n): void {\r\n stream.on('data', (chunk) => {\r\n res.write(chunk.toString());\r\n });\r\n\r\n stream.on('end', () => {\r\n res.end();\r\n options.onFinish?.();\r\n });\r\n\r\n stream.on('error', (err) => {\r\n console.error('Stream error:', err);\r\n res.end();\r\n });\r\n}\r\n\r\n/**\r\n * Error Boundary Wrapper for SSR\r\n */\r\ninterface ErrorBoundaryProps {\r\n fallback: React.ComponentType<{ error: Error }>;\r\n children: React.ReactNode;\r\n}\r\n\r\ninterface ErrorBoundaryState {\r\n hasError: boolean;\r\n error: Error | null;\r\n}\r\n\r\nclass ErrorBoundaryWrapper extends React.Component<ErrorBoundaryProps, ErrorBoundaryState> {\r\n constructor(props: ErrorBoundaryProps) {\r\n super(props);\r\n this.state = { hasError: false, error: null };\r\n }\r\n\r\n static getDerivedStateFromError(error: Error): ErrorBoundaryState {\r\n return { hasError: true, error };\r\n }\r\n\r\n render() {\r\n if (this.state.hasError) {\r\n const FallbackComponent = this.props.fallback;\r\n return React.createElement(FallbackComponent, { error: this.state.error! });\r\n }\r\n return this.props.children;\r\n }\r\n}\r\n\r\n/**\r\n * Generates hydration scripts for islands\r\n */\r\nfunction generateIslandScripts(islands) {\r\n if (!islands.length) return [];\r\n \r\n const scripts = [];\r\n \r\n for (const island of islands) {\r\n scripts.push({\r\n type: 'module',\r\n content: `\r\n import { hydrateIsland } from '/_flexi/client.js';\r\n import ${island.name} from '${island.clientPath}';\r\n hydrateIsland('${island.id}', ${island.name}, ${JSON.stringify(island.props)});\r\n `\r\n });\r\n }\r\n \r\n return scripts;\r\n}\r\n\r\n/**\r\n * Generates the Dev Toolbar HTML (FlexiReact v2 - Premium DevTools)\r\n */\r\ninterface DevToolbarOptions {\r\n renderTime?: number;\r\n pageType?: string;\r\n route?: string;\r\n hasError?: boolean;\r\n isHydrated?: boolean;\r\n errorMessage?: string | null;\r\n componentName?: string | null;\r\n}\r\n\r\nfunction generateDevToolbar(options: DevToolbarOptions = {}) {\r\n const { \r\n renderTime = 0, \r\n pageType = 'SSR', \r\n route = '/',\r\n hasError = false,\r\n isHydrated = false,\r\n errorMessage = null,\r\n componentName = null\r\n } = options;\r\n\r\n const timeColor = renderTime < 50 ? '#00FF9C' : renderTime < 200 ? '#fbbf24' : '#ef4444';\r\n const timeLabel = renderTime < 50 ? 'Fast' : renderTime < 200 ? 'OK' : 'Slow';\r\n\r\n return `\r\n<!-- FlexiReact v2 Dev Toolbar -->\r\n<div id=\"flexi-dev-toolbar\" class=\"flexi-dev-collapsed\">\r\n <style>\r\n #flexi-dev-toolbar {\r\n position: fixed;\r\n bottom: 16px;\r\n left: 16px;\r\n z-index: 99999;\r\n font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;\r\n font-size: 13px;\r\n }\r\n \r\n /* Main Button */\r\n .flexi-dev-trigger {\r\n display: flex;\r\n align-items: center;\r\n gap: 8px;\r\n padding: 8px 12px;\r\n background: rgba(10, 10, 10, 0.95);\r\n backdrop-filter: blur(20px);\r\n border: 1px solid rgba(0, 255, 156, 0.2);\r\n border-radius: 10px;\r\n color: #fafafa;\r\n cursor: pointer;\r\n transition: all 0.2s cubic-bezier(0.16, 1, 0.3, 1);\r\n box-shadow: 0 4px 20px rgba(0, 0, 0, 0.5);\r\n }\r\n \r\n .flexi-dev-trigger:hover {\r\n border-color: rgba(0, 255, 156, 0.5);\r\n box-shadow: 0 4px 30px rgba(0, 0, 0, 0.6), 0 0 20px rgba(0, 255, 156, 0.15);\r\n transform: translateY(-2px);\r\n }\r\n \r\n .flexi-dev-trigger.has-error {\r\n border-color: rgba(239, 68, 68, 0.5);\r\n box-shadow: 0 4px 20px rgba(0, 0, 0, 0.5), 0 0 15px rgba(239, 68, 68, 0.2);\r\n }\r\n \r\n .flexi-dev-logo {\r\n width: 20px;\r\n height: 20px;\r\n background: linear-gradient(135deg, #00FF9C, #00D68F);\r\n border-radius: 5px;\r\n display: flex;\r\n align-items: center;\r\n justify-content: center;\r\n font-weight: 800;\r\n font-size: 11px;\r\n color: #000;\r\n }\r\n \r\n .flexi-dev-trigger.has-error .flexi-dev-logo {\r\n background: linear-gradient(135deg, #ef4444, #dc2626);\r\n }\r\n \r\n .flexi-dev-indicator {\r\n display: flex;\r\n align-items: center;\r\n gap: 6px;\r\n }\r\n \r\n .flexi-dev-dot {\r\n width: 6px;\r\n height: 6px;\r\n border-radius: 50%;\r\n background: #00FF9C;\r\n box-shadow: 0 0 8px rgba(0, 255, 156, 0.6);\r\n }\r\n \r\n .flexi-dev-dot.error {\r\n background: #ef4444;\r\n box-shadow: 0 0 8px rgba(239, 68, 68, 0.6);\r\n animation: errorPulse 1s infinite;\r\n }\r\n \r\n @keyframes errorPulse {\r\n 0%, 100% { opacity: 1; }\r\n 50% { opacity: 0.4; }\r\n }\r\n \r\n .flexi-dev-time {\r\n font-size: 11px;\r\n font-weight: 600;\r\n color: ${timeColor};\r\n font-variant-numeric: tabular-nums;\r\n }\r\n \r\n /* Panel */\r\n .flexi-dev-panel {\r\n position: absolute;\r\n bottom: calc(100% + 8px);\r\n left: 0;\r\n min-width: 340px;\r\n background: rgba(10, 10, 10, 0.98);\r\n backdrop-filter: blur(20px);\r\n border: 1px solid rgba(255, 255, 255, 0.08);\r\n border-radius: 16px;\r\n opacity: 0;\r\n visibility: hidden;\r\n transform: translateY(8px) scale(0.96);\r\n transition: all 0.25s cubic-bezier(0.16, 1, 0.3, 1);\r\n box-shadow: 0 20px 50px rgba(0, 0, 0, 0.7);\r\n overflow: hidden;\r\n }\r\n \r\n #flexi-dev-toolbar.flexi-dev-open .flexi-dev-panel {\r\n opacity: 1;\r\n visibility: visible;\r\n transform: translateY(0) scale(1);\r\n }\r\n \r\n /* Header */\r\n .flexi-dev-header {\r\n display: flex;\r\n align-items: center;\r\n gap: 10px;\r\n padding: 14px 16px;\r\n background: linear-gradient(135deg, rgba(0, 255, 156, 0.08), rgba(0, 214, 143, 0.04));\r\n border-bottom: 1px solid rgba(255, 255, 255, 0.05);\r\n }\r\n \r\n .flexi-dev-header-logo {\r\n width: 26px;\r\n height: 26px;\r\n background: linear-gradient(135deg, #00FF9C, #00D68F);\r\n border-radius: 7px;\r\n display: flex;\r\n align-items: center;\r\n justify-content: center;\r\n font-weight: 800;\r\n font-size: 13px;\r\n color: #000;\r\n }\r\n \r\n .flexi-dev-header-info {\r\n flex: 1;\r\n }\r\n \r\n .flexi-dev-header-title {\r\n font-weight: 700;\r\n font-size: 14px;\r\n color: #fafafa;\r\n }\r\n \r\n .flexi-dev-header-subtitle {\r\n font-size: 11px;\r\n color: #52525b;\r\n margin-top: 1px;\r\n }\r\n \r\n .flexi-dev-close {\r\n width: 24px;\r\n height: 24px;\r\n display: flex;\r\n align-items: center;\r\n justify-content: center;\r\n background: rgba(255, 255, 255, 0.05);\r\n border: none;\r\n border-radius: 6px;\r\n color: #71717a;\r\n cursor: pointer;\r\n transition: all 0.15s;\r\n }\r\n \r\n .flexi-dev-close:hover {\r\n background: rgba(255, 255, 255, 0.1);\r\n color: #fafafa;\r\n }\r\n \r\n /* Content */\r\n .flexi-dev-content {\r\n padding: 12px 16px;\r\n }\r\n \r\n .flexi-dev-section {\r\n margin-bottom: 12px;\r\n }\r\n \r\n .flexi-dev-section:last-child {\r\n margin-bottom: 0;\r\n }\r\n \r\n .flexi-dev-section-title {\r\n font-size: 10px;\r\n font-weight: 600;\r\n color: #52525b;\r\n text-transform: uppercase;\r\n letter-spacing: 0.5px;\r\n margin-bottom: 8px;\r\n }\r\n \r\n .flexi-dev-grid {\r\n display: grid;\r\n grid-template-columns: 1fr 1fr;\r\n gap: 8px;\r\n }\r\n \r\n .flexi-dev-stat {\r\n background: rgba(255, 255, 255, 0.03);\r\n border: 1px solid rgba(255, 255, 255, 0.05);\r\n border-radius: 10px;\r\n padding: 10px 12px;\r\n }\r\n \r\n .flexi-dev-stat-label {\r\n font-size: 10px;\r\n color: #52525b;\r\n margin-bottom: 4px;\r\n }\r\n \r\n .flexi-dev-stat-value {\r\n font-size: 14px;\r\n font-weight: 600;\r\n color: #fafafa;\r\n }\r\n \r\n .flexi-dev-stat-value.success { color: #00FF9C; }\r\n .flexi-dev-stat-value.warning { color: #fbbf24; }\r\n .flexi-dev-stat-value.error { color: #ef4444; }\r\n \r\n /* Badges */\r\n .flexi-dev-badge {\r\n display: inline-flex;\r\n align-items: center;\r\n padding: 3px 8px;\r\n border-radius: 5px;\r\n font-size: 10px;\r\n font-weight: 700;\r\n letter-spacing: 0.3px;\r\n }\r\n \r\n .flexi-dev-badge.ssr { background: rgba(251, 191, 36, 0.15); color: #fbbf24; }\r\n .flexi-dev-badge.ssg { background: rgba(0, 255, 156, 0.15); color: #00FF9C; }\r\n .flexi-dev-badge.csr { background: rgba(6, 182, 212, 0.15); color: #06b6d4; }\r\n .flexi-dev-badge.isr { background: rgba(139, 92, 246, 0.15); color: #a78bfa; }\r\n \r\n /* Error Display */\r\n .flexi-dev-error {\r\n background: rgba(239, 68, 68, 0.1);\r\n border: 1px solid rgba(239, 68, 68, 0.2);\r\n border-radius: 10px;\r\n padding: 12px;\r\n margin-top: 8px;\r\n }\r\n \r\n .flexi-dev-error-title {\r\n display: flex;\r\n align-items: center;\r\n gap: 6px;\r\n font-size: 11px;\r\n font-weight: 600;\r\n color: #ef4444;\r\n margin-bottom: 6px;\r\n }\r\n \r\n .flexi-dev-error-message {\r\n font-size: 12px;\r\n color: #fca5a5;\r\n font-family: 'SF Mono', 'Fira Code', monospace;\r\n word-break: break-word;\r\n line-height: 1.5;\r\n }\r\n \r\n /* Footer */\r\n .flexi-dev-footer {\r\n display: flex;\r\n gap: 6px;\r\n padding: 12px 16px;\r\n background: rgba(0, 0, 0, 0.3);\r\n border-top: 1px solid rgba(255, 255, 255, 0.05);\r\n }\r\n \r\n .flexi-dev-action {\r\n flex: 1;\r\n padding: 8px;\r\n background: rgba(255, 255, 255, 0.03);\r\n border: 1px solid rgba(255, 255, 255, 0.06);\r\n border-radius: 8px;\r\n color: #71717a;\r\n font-size: 11px;\r\n font-weight: 500;\r\n text-decoration: none;\r\n text-align: center;\r\n cursor: pointer;\r\n transition: all 0.15s;\r\n }\r\n \r\n .flexi-dev-action:hover {\r\n background: rgba(0, 255, 156, 0.1);\r\n border-color: rgba(0, 255, 156, 0.2);\r\n color: #00FF9C;\r\n }\r\n </style>\r\n \r\n <button class=\"flexi-dev-trigger ${hasError ? 'has-error' : ''}\" onclick=\"this.parentElement.classList.toggle('flexi-dev-open')\">\r\n <div class=\"flexi-dev-logo\">F</div>\r\n <div class=\"flexi-dev-indicator\">\r\n <div class=\"flexi-dev-dot ${hasError ? 'error' : ''}\"></div>\r\n <span class=\"flexi-dev-time\">${renderTime}ms</span>\r\n </div>\r\n </button>\r\n \r\n <div class=\"flexi-dev-panel\">\r\n <div class=\"flexi-dev-header\">\r\n <div class=\"flexi-dev-header-logo\">F</div>\r\n <div class=\"flexi-dev-header-info\">\r\n <div class=\"flexi-dev-header-title\">FlexiReact</div>\r\n <div class=\"flexi-dev-header-subtitle\">v2.0.0 • Development</div>\r\n </div>\r\n <button class=\"flexi-dev-close\" onclick=\"this.closest('#flexi-dev-toolbar').classList.remove('flexi-dev-open')\">✕</button>\r\n </div>\r\n \r\n <div class=\"flexi-dev-content\">\r\n <div class=\"flexi-dev-section\">\r\n <div class=\"flexi-dev-section-title\">Page Info</div>\r\n <div class=\"flexi-dev-grid\">\r\n <div class=\"flexi-dev-stat\">\r\n <div class=\"flexi-dev-stat-label\">Route</div>\r\n <div class=\"flexi-dev-stat-value\">${route}</div>\r\n </div>\r\n <div class=\"flexi-dev-stat\">\r\n <div class=\"flexi-dev-stat-label\">Type</div>\r\n <div class=\"flexi-dev-stat-value\"><span class=\"flexi-dev-badge ${pageType.toLowerCase()}\">${pageType}</span></div>\r\n </div>\r\n </div>\r\n </div>\r\n \r\n <div class=\"flexi-dev-section\">\r\n <div class=\"flexi-dev-section-title\">Performance</div>\r\n <div class=\"flexi-dev-grid\">\r\n <div class=\"flexi-dev-stat\">\r\n <div class=\"flexi-dev-stat-label\">Render Time</div>\r\n <div class=\"flexi-dev-stat-value ${renderTime < 50 ? 'success' : renderTime < 200 ? 'warning' : 'error'}\">${renderTime}ms <small style=\"color:#52525b\">${timeLabel}</small></div>\r\n </div>\r\n <div class=\"flexi-dev-stat\">\r\n <div class=\"flexi-dev-stat-label\">Hydration</div>\r\n <div class=\"flexi-dev-stat-value\" id=\"flexi-hydration-status\">${isHydrated ? '✓ Client' : '○ Server'}</div>\r\n </div>\r\n </div>\r\n </div>\r\n \r\n ${hasError && errorMessage ? `\r\n <div class=\"flexi-dev-error\">\r\n <div class=\"flexi-dev-error-title\">\r\n <span>⚠</span> Runtime Error\r\n </div>\r\n <div class=\"flexi-dev-error-message\">${errorMessage}</div>\r\n </div>\r\n ` : ''}\r\n </div>\r\n \r\n <div class=\"flexi-dev-footer\">\r\n <a href=\"/_flexi/routes\" class=\"flexi-dev-action\">Routes</a>\r\n <button class=\"flexi-dev-action\" onclick=\"location.reload()\">Refresh</button>\r\n <a href=\"https://github.com/flexireact/flexireact\" target=\"_blank\" class=\"flexi-dev-action\">Docs ↗</a>\r\n </div>\r\n </div>\r\n</div>\r\n\r\n<script>\r\n // FlexiReact v2 DevTools\r\n window.__FLEXI_DEV__ = {\r\n version: '2.0.0',\r\n renderTime: ${renderTime},\r\n pageType: '${pageType}',\r\n route: '${route}',\r\n hydrated: false,\r\n errors: []\r\n };\r\n \r\n // Track hydration\r\n const root = document.getElementById('root');\r\n if (root) {\r\n const observer = new MutationObserver(() => {\r\n if (root.children.length > 0) {\r\n window.__FLEXI_DEV__.hydrated = true;\r\n const el = document.getElementById('flexi-hydration-status');\r\n if (el) el.textContent = '✓ Client';\r\n observer.disconnect();\r\n }\r\n });\r\n observer.observe(root, { childList: true, subtree: true });\r\n }\r\n \r\n // Capture runtime errors\r\n window.addEventListener('error', (e) => {\r\n window.__FLEXI_DEV__.errors.push({\r\n message: e.message,\r\n file: e.filename,\r\n line: e.lineno,\r\n col: e.colno\r\n });\r\n console.error('%c[FlexiReact Error]', 'color: #ef4444; font-weight: bold;', e.message);\r\n });\r\n \r\n // Console branding\r\n console.log(\r\n '%c ⚡ FlexiReact v2 %c ${pageType} %c ${renderTime}ms ',\r\n 'background: #00FF9C; color: #000; font-weight: bold; padding: 2px 6px; border-radius: 4px 0 0 4px;',\r\n 'background: #1e1e1e; color: #fafafa; padding: 2px 6px;',\r\n 'background: ${timeColor}20; color: ${timeColor}; padding: 2px 6px; border-radius: 0 4px 4px 0;'\r\n );\r\n</script>\r\n`;\r\n}\r\n\r\n/**\r\n * Builds complete HTML document\r\n */\r\nfunction buildHtmlDocument(options) {\r\n const {\r\n content,\r\n title,\r\n meta = {},\r\n scripts = [],\r\n styles = [],\r\n props = {},\r\n isSSG = false,\r\n renderTime = 0,\r\n route = '/',\r\n isClientComponent = false,\r\n favicon = null\r\n } = options;\r\n\r\n const metaTags = Object.entries(meta)\r\n .map(([name, content]) => {\r\n if (name.startsWith('og:')) {\r\n return `<meta property=\"${escapeHtml(name)}\" content=\"${escapeHtml(content)}\">`;\r\n }\r\n return `<meta name=\"${escapeHtml(name)}\" content=\"${escapeHtml(content)}\">`;\r\n })\r\n .join('\\n ');\r\n\r\n const styleTags = styles\r\n .map(style => {\r\n if (typeof style === 'string') {\r\n return `<link rel=\"stylesheet\" href=\"${escapeHtml(style)}\">`;\r\n }\r\n return `<style>${style.content}</style>`;\r\n })\r\n .join('\\n ');\r\n\r\n const scriptTags = scripts\r\n .map(script => {\r\n if (typeof script === 'string') {\r\n return `<script src=\"${escapeHtml(script)}\"></script>`;\r\n }\r\n const type = script.type ? ` type=\"${script.type}\"` : '';\r\n if (script.src) {\r\n return `<script${type} src=\"${escapeHtml(script.src)}\"></script>`;\r\n }\r\n return `<script${type}>${script.content}</script>`;\r\n })\r\n .join('\\n ');\r\n\r\n // FlexiReact SVG favicon (properly encoded)\r\n const faviconSvg = encodeURIComponent(`<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 32 32\"><rect width=\"32\" height=\"32\" rx=\"8\" fill=\"#00FF9C\"/><text x=\"50%\" y=\"50%\" dominant-baseline=\"central\" text-anchor=\"middle\" fill=\"#000\" font-family=\"system-ui\" font-weight=\"bold\" font-size=\"16\">F</text></svg>`);\r\n\r\n // Generate Dev Toolbar for development mode\r\n const isDev = process.env.NODE_ENV !== 'production';\r\n const pageType = isSSG ? 'SSG' : isClientComponent ? 'CSR' : 'SSR';\r\n const devToolbar = isDev ? generateDevToolbar({ \r\n renderTime, \r\n pageType, \r\n route,\r\n isHydrated: isClientComponent\r\n }) : '';\r\n\r\n // Determine favicon link\r\n const faviconLink = favicon \r\n ? `<link rel=\"icon\" href=\"${escapeHtml(favicon)}\">`\r\n : `<link rel=\"icon\" type=\"image/svg+xml\" href=\"data:image/svg+xml,${faviconSvg}\">`;\r\n\r\n return `<!DOCTYPE html>\r\n<html lang=\"en\" class=\"dark\">\r\n<head>\r\n <meta charset=\"UTF-8\">\r\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\r\n <title>${escapeHtml(title)}</title>\r\n ${faviconLink}\r\n ${metaTags}\r\n <style>\r\n :root { --flexi-bg: #0f172a; --flexi-fg: #f8fafc; }\r\n html, body { background-color: #0f172a; color: #f8fafc; min-height: 100vh; margin: 0; }\r\n </style>\r\n ${styleTags}\r\n <script>\r\n (function() {\r\n var theme = localStorage.getItem('theme');\r\n if (theme === 'light') {\r\n document.documentElement.classList.remove('dark');\r\n document.documentElement.style.backgroundColor = '#ffffff';\r\n document.documentElement.style.color = '#0f172a';\r\n document.body.style.backgroundColor = '#ffffff';\r\n document.body.style.color = '#0f172a';\r\n }\r\n })();\r\n </script>\r\n</head>\r\n<body>\r\n <div id=\"root\">${content}</div>\r\n <script>\r\n window.__FLEXI_DATA__ = ${JSON.stringify({ props, isSSG })};\r\n </script>\r\n ${scriptTags}\r\n ${devToolbar}\r\n</body>\r\n</html>`;\r\n}\r\n\r\n/**\r\n * Renders an error page with beautiful styling (FlexiReact v2)\r\n */\r\nexport function renderError(statusCode, message, stack = null) {\r\n const showStack = process.env.NODE_ENV !== 'production' && stack;\r\n const isDev = process.env.NODE_ENV !== 'production';\r\n \r\n // Parse error for better display\r\n const errorDetails = parseErrorStack(stack);\r\n \r\n // Different messages for different status codes\r\n const errorMessages = {\r\n 404: { title: 'Page Not Found', icon: 'search', color: '#00FF9C', desc: 'The page you\\'re looking for doesn\\'t exist or has been moved.' },\r\n 500: { title: 'Server Error', icon: 'alert', color: '#ef4444', desc: 'Something went wrong on our end.' },\r\n 403: { title: 'Forbidden', icon: 'lock', color: '#f59e0b', desc: 'You don\\'t have permission to access this resource.' },\r\n 401: { title: 'Unauthorized', icon: 'key', color: '#8b5cf6', desc: 'Please log in to access this page.' },\r\n };\r\n \r\n const errorInfo = errorMessages[statusCode] || { title: 'Error', icon: 'alert', color: '#ef4444', desc: message };\r\n \r\n // Generate error frames HTML for dev mode\r\n const errorFramesHtml = showStack && errorDetails?.frames?.length > 0 \r\n ? errorDetails.frames.slice(0, 5).map((frame, i) => `\r\n <div class=\"error-frame ${i === 0 ? 'error-frame-first' : ''}\">\r\n <div class=\"error-frame-fn\">${escapeHtml(frame.fn)}</div>\r\n <div class=\"error-frame-loc\">${escapeHtml(frame.file)}:${frame.line}:${frame.col}</div>\r\n </div>\r\n `).join('')\r\n : '';\r\n\r\n return `<!DOCTYPE html>\r\n<html lang=\"en\">\r\n<head>\r\n <meta charset=\"UTF-8\">\r\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\r\n <title>${statusCode} - ${errorInfo.title} | FlexiReact</title>\r\n <link rel=\"icon\" type=\"image/svg+xml\" href=\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Crect width='32' height='32' rx='8' fill='%2300FF9C'/%3E%3Ctext x='50%25' y='50%25' dominant-baseline='central' text-anchor='middle' fill='%23000' font-family='system-ui' font-weight='bold' font-size='16'%3EF%3C/text%3E%3C/svg%3E\">\r\n <style>\r\n * { margin: 0; padding: 0; box-sizing: border-box; }\r\n \r\n body {\r\n font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\r\n min-height: 100vh;\r\n background: #0a0a0a;\r\n color: #fafafa;\r\n display: flex;\r\n align-items: center;\r\n justify-content: center;\r\n overflow-x: hidden;\r\n }\r\n \r\n /* Animated background */\r\n .bg-pattern {\r\n position: fixed;\r\n inset: 0;\r\n background-image: \r\n radial-gradient(circle at 25% 25%, rgba(0, 255, 156, 0.03) 0%, transparent 50%),\r\n radial-gradient(circle at 75% 75%, rgba(99, 102, 241, 0.03) 0%, transparent 50%);\r\n pointer-events: none;\r\n }\r\n \r\n .bg-grid {\r\n position: fixed;\r\n inset: 0;\r\n background-image: \r\n linear-gradient(rgba(255, 255, 255, 0.02) 1px, transparent 1px),\r\n linear-gradient(90deg, rgba(255, 255, 255, 0.02) 1px, transparent 1px);\r\n background-size: 64px 64px;\r\n pointer-events: none;\r\n }\r\n \r\n .container {\r\n position: relative;\r\n width: 100%;\r\n max-width: ${showStack ? '800px' : '500px'};\r\n padding: 2rem;\r\n animation: fadeIn 0.6s cubic-bezier(0.16, 1, 0.3, 1);\r\n }\r\n \r\n @keyframes fadeIn {\r\n from { opacity: 0; transform: translateY(30px); }\r\n to { opacity: 1; transform: translateY(0); }\r\n }\r\n \r\n /* Error Card */\r\n .error-card {\r\n background: linear-gradient(145deg, rgba(23, 23, 23, 0.9), rgba(10, 10, 10, 0.95));\r\n border: 1px solid rgba(255, 255, 255, 0.08);\r\n border-radius: 24px;\r\n padding: 3rem;\r\n text-align: center;\r\n backdrop-filter: blur(20px);\r\n box-shadow: \r\n 0 0 0 1px rgba(255, 255, 255, 0.05),\r\n 0 20px 50px -20px rgba(0, 0, 0, 0.5),\r\n 0 0 100px -50px ${errorInfo.color}40;\r\n }\r\n \r\n /* Logo */\r\n .logo {\r\n width: 56px;\r\n height: 56px;\r\n background: linear-gradient(135deg, #00FF9C, #00D68F);\r\n border-radius: 14px;\r\n display: flex;\r\n align-items: center;\r\n justify-content: center;\r\n margin: 0 auto 2rem;\r\n font-weight: 800;\r\n font-size: 24px;\r\n color: #000;\r\n box-shadow: 0 0 30px rgba(0, 255, 156, 0.3);\r\n }\r\n \r\n /* Error Code */\r\n .error-code {\r\n font-size: 7rem;\r\n font-weight: 800;\r\n line-height: 1;\r\n background: linear-gradient(135deg, ${errorInfo.color}, ${errorInfo.color}99);\r\n -webkit-background-clip: text;\r\n -webkit-text-fill-color: transparent;\r\n background-clip: text;\r\n margin-bottom: 0.5rem;\r\n letter-spacing: -4px;\r\n }\r\n \r\n .error-title {\r\n font-size: 1.5rem;\r\n font-weight: 600;\r\n color: #fafafa;\r\n margin-bottom: 0.75rem;\r\n }\r\n \r\n .error-desc {\r\n font-size: 1rem;\r\n color: #71717a;\r\n line-height: 1.6;\r\n margin-bottom: 2rem;\r\n }\r\n \r\n /* Buttons */\r\n .buttons {\r\n display: flex;\r\n gap: 12px;\r\n justify-content: center;\r\n flex-wrap: wrap;\r\n }\r\n \r\n .btn {\r\n display: inline-flex;\r\n align-items: center;\r\n gap: 8px;\r\n padding: 12px 24px;\r\n border-radius: 12px;\r\n font-weight: 600;\r\n font-size: 14px;\r\n text-decoration: none;\r\n transition: all 0.2s cubic-bezier(0.16, 1, 0.3, 1);\r\n border: none;\r\n cursor: pointer;\r\n }\r\n \r\n .btn-primary {\r\n background: #00FF9C;\r\n color: #000;\r\n box-shadow: 0 0 20px rgba(0, 255, 156, 0.3);\r\n }\r\n \r\n .btn-primary:hover {\r\n transform: translateY(-2px);\r\n box-shadow: 0 0 30px rgba(0, 255, 156, 0.5);\r\n }\r\n \r\n .btn-secondary {\r\n background: rgba(255, 255, 255, 0.06);\r\n color: #a1a1aa;\r\n border: 1px solid rgba(255, 255, 255, 0.1);\r\n }\r\n \r\n .btn-secondary:hover {\r\n background: rgba(255, 255, 255, 0.1);\r\n color: #fafafa;\r\n border-color: rgba(255, 255, 255, 0.2);\r\n }\r\n \r\n /* Error Stack (Dev Mode) */\r\n .error-stack {\r\n margin-top: 2rem;\r\n text-align: left;\r\n }\r\n \r\n .error-stack-header {\r\n display: flex;\r\n align-items: center;\r\n gap: 8px;\r\n margin-bottom: 12px;\r\n font-size: 12px;\r\n font-weight: 600;\r\n color: #ef4444;\r\n text-transform: uppercase;\r\n letter-spacing: 0.5px;\r\n }\r\n \r\n .error-stack-header::before {\r\n content: '';\r\n width: 8px;\r\n height: 8px;\r\n background: #ef4444;\r\n border-radius: 50%;\r\n animation: pulse 2s infinite;\r\n }\r\n \r\n @keyframes pulse {\r\n 0%, 100% { opacity: 1; }\r\n 50% { opacity: 0.5; }\r\n }\r\n \r\n .error-message {\r\n background: rgba(239, 68, 68, 0.1);\r\n border: 1px solid rgba(239, 68, 68, 0.2);\r\n border-radius: 12px;\r\n padding: 16px;\r\n margin-bottom: 12px;\r\n font-family: 'SF Mono', 'Fira Code', monospace;\r\n font-size: 13px;\r\n color: #fca5a5;\r\n word-break: break-word;\r\n }\r\n \r\n .error-frames {\r\n background: rgba(0, 0, 0, 0.4);\r\n border: 1px solid rgba(255, 255, 255, 0.05);\r\n border-radius: 12px;\r\n overflow: hidden;\r\n }\r\n \r\n .error-frame {\r\n padding: 12px 16px;\r\n border-bottom: 1px solid rgba(255, 255, 255, 0.05);\r\n font-family: 'SF Mono', 'Fira Code', monospace;\r\n font-size: 12px;\r\n }\r\n \r\n .error-frame:last-child {\r\n border-bottom: none;\r\n }\r\n \r\n .error-frame-first {\r\n background: rgba(239, 68, 68, 0.05);\r\n }\r\n \r\n .error-frame-fn {\r\n color: #fafafa;\r\n font-weight: 500;\r\n margin-bottom: 4px;\r\n }\r\n \r\n .error-frame-loc {\r\n color: #52525b;\r\n font-size: 11px;\r\n }\r\n \r\n /* Dev Badge */\r\n .dev-badge {\r\n position: fixed;\r\n bottom: 20px;\r\n right: 20px;\r\n display: flex;\r\n align-items: center;\r\n gap: 8px;\r\n padding: 8px 14px;\r\n background: rgba(0, 0, 0, 0.8);\r\n border: 1px solid rgba(255, 255, 255, 0.1);\r\n border-radius: 10px;\r\n font-size: 12px;\r\n font-weight: 500;\r\n color: #71717a;\r\n backdrop-filter: blur(10px);\r\n }\r\n \r\n .dev-badge-dot {\r\n width: 8px;\r\n height: 8px;\r\n background: #00FF9C;\r\n border-radius: 50%;\r\n box-shadow: 0 0 10px rgba(0, 255, 156, 0.5);\r\n }\r\n </style>\r\n</head>\r\n<body>\r\n <div class=\"bg-pattern\"></div>\r\n <div class=\"bg-grid\"></div>\r\n \r\n <div class=\"container\">\r\n <div class=\"error-card\">\r\n <div class=\"logo\">F</div>\r\n \r\n <div class=\"error-code\">${statusCode}</div>\r\n <h1 class=\"error-title\">${errorInfo.title}</h1>\r\n <p class=\"error-desc\">${errorInfo.desc}</p>\r\n \r\n <div class=\"buttons\">\r\n <a href=\"/\" class=\"btn btn-primary\">\r\n ← Back to Home\r\n </a>\r\n <a href=\"javascript:history.back()\" class=\"btn btn-secondary\">\r\n Go Back\r\n </a>\r\n </div>\r\n \r\n ${showStack ? `\r\n <div class=\"error-stack\">\r\n <div class=\"error-stack-header\">Error Details</div>\r\n <div class=\"error-message\">${escapeHtml(message)}</div>\r\n ${errorFramesHtml ? `<div class=\"error-frames\">${errorFramesHtml}</div>` : ''}\r\n </div>\r\n ` : ''}\r\n </div>\r\n </div>\r\n \r\n ${isDev ? `\r\n <div class=\"dev-badge\">\r\n <div class=\"dev-badge-dot\"></div>\r\n FlexiReact v2\r\n </div>\r\n ` : ''}\r\n</body>\r\n</html>`;\r\n}\r\n\r\n/**\r\n * Parses error stack for better display\r\n */\r\nfunction parseErrorStack(stack) {\r\n if (!stack) return null;\r\n \r\n const lines = stack.split('\\n');\r\n const parsed = {\r\n message: lines[0] || '',\r\n frames: []\r\n };\r\n \r\n for (let i = 1; i < lines.length; i++) {\r\n const line = lines[i].trim();\r\n const match = line.match(/at\\s+(.+?)\\s+\\((.+?):(\\d+):(\\d+)\\)/) ||\r\n line.match(/at\\s+(.+?):(\\d+):(\\d+)/);\r\n \r\n if (match) {\r\n parsed.frames.push({\r\n fn: match[1] || 'anonymous',\r\n file: match[2] || match[1],\r\n line: match[3] || match[2],\r\n col: match[4] || match[3]\r\n });\r\n }\r\n }\r\n \r\n return parsed;\r\n}\r\n\r\n/**\r\n * Renders a loading state\r\n */\r\nexport function renderLoading(LoadingComponent) {\r\n if (!LoadingComponent) {\r\n return `<div class=\"flexi-loading\">\r\n <div class=\"flexi-spinner\"></div>\r\n <style>\r\n .flexi-loading {\r\n display: flex;\r\n align-items: center;\r\n justify-content: center;\r\n min-height: 200px;\r\n }\r\n .flexi-spinner {\r\n width: 40px;\r\n height: 40px;\r\n border: 3px solid #f3f3f3;\r\n border-top: 3px solid #667eea;\r\n border-radius: 50%;\r\n animation: spin 1s linear infinite;\r\n }\r\n @keyframes spin {\r\n 0% { transform: rotate(0deg); }\r\n 100% { transform: rotate(360deg); }\r\n }\r\n </style>\r\n </div>`;\r\n }\r\n \r\n return renderToString(React.createElement(LoadingComponent));\r\n}\r\n\r\nexport default {\r\n renderPage,\r\n renderError,\r\n renderLoading\r\n};\r\n","/**\r\n * FlexiReact Middleware System\r\n * \r\n * Middlewares run before every request and can:\r\n * - Modify the request/response\r\n * - Redirect or rewrite URLs\r\n * - Add headers\r\n * - Authenticate users\r\n * - Log requests\r\n * \r\n * Usage:\r\n * Create a middleware.js file in your project root:\r\n * \r\n * export default function middleware(request) {\r\n * // Return a response to short-circuit\r\n * // Return NextResponse.next() to continue\r\n * // Return NextResponse.redirect() to redirect\r\n * }\r\n * \r\n * export const config = {\r\n * matcher: ['/protected/:path*']\r\n * };\r\n */\r\n\r\nimport fs from 'fs';\r\nimport path from 'path';\r\nimport { pathToFileURL } from 'url';\r\n\r\n/**\r\n * Middleware response helpers\r\n */\r\ninterface MiddlewareResponseOptions {\r\n type?: string;\r\n status?: number;\r\n headers?: Record<string, string>;\r\n body?: any;\r\n url?: string | null;\r\n}\r\n\r\nexport class MiddlewareResponse {\r\n type: string;\r\n status: number;\r\n headers: Map<string, string>;\r\n body: any;\r\n url: string | null;\r\n\r\n constructor(options: MiddlewareResponseOptions = {}) {\r\n this.type = options.type || 'next';\r\n this.status = options.status || 200;\r\n this.headers = new Map(Object.entries(options.headers || {}));\r\n this.body = options.body || null;\r\n this.url = options.url || null;\r\n }\r\n\r\n /**\r\n * Continue to the next middleware/handler\r\n */\r\n static next(options = {}) {\r\n return new MiddlewareResponse({ ...options, type: 'next' });\r\n }\r\n\r\n /**\r\n * Redirect to a different URL\r\n */\r\n static redirect(url, status = 302) {\r\n return new MiddlewareResponse({\r\n type: 'redirect',\r\n url,\r\n status\r\n });\r\n }\r\n\r\n /**\r\n * Rewrite the request to a different URL (internal)\r\n */\r\n static rewrite(url) {\r\n return new MiddlewareResponse({\r\n type: 'rewrite',\r\n url\r\n });\r\n }\r\n\r\n /**\r\n * Return a JSON response\r\n */\r\n static json(data: any, options: { status?: number; headers?: Record<string, string> } = {}) {\r\n return new MiddlewareResponse({\r\n type: 'response',\r\n status: options.status || 200,\r\n headers: { 'Content-Type': 'application/json', ...options.headers },\r\n body: JSON.stringify(data)\r\n });\r\n }\r\n\r\n /**\r\n * Return an HTML response\r\n */\r\n static html(content: string, options: { status?: number; headers?: Record<string, string> } = {}) {\r\n return new MiddlewareResponse({\r\n type: 'response',\r\n status: options.status || 200,\r\n headers: { 'Content-Type': 'text/html', ...options.headers },\r\n body: content\r\n });\r\n }\r\n}\r\n\r\n/**\r\n * Middleware request wrapper\r\n */\r\nexport class MiddlewareRequest {\r\n raw: any;\r\n method: string;\r\n url: string;\r\n headers: Map<string, string>;\r\n pathname: string;\r\n searchParams: URLSearchParams;\r\n query: Record<string, string>;\r\n cookies: Map<string, string>;\r\n\r\n constructor(req: any) {\r\n this.raw = req;\r\n this.method = req.method;\r\n this.url = req.url;\r\n this.headers = new Map(Object.entries(req.headers || {}));\r\n \r\n // Parse URL\r\n const parsedUrl = new URL(req.url, `http://${req.headers.host || 'localhost'}`);\r\n this.pathname = parsedUrl.pathname;\r\n this.searchParams = parsedUrl.searchParams;\r\n this.query = Object.fromEntries(parsedUrl.searchParams) as Record<string, string>;\r\n \r\n // Parse cookies\r\n this.cookies = this._parseCookies(req.headers.cookie || '');\r\n }\r\n\r\n _parseCookies(cookieHeader) {\r\n const cookies = new Map();\r\n if (!cookieHeader) return cookies;\r\n \r\n cookieHeader.split(';').forEach(cookie => {\r\n const [name, ...rest] = cookie.split('=');\r\n if (name) {\r\n cookies.set(name.trim(), rest.join('=').trim());\r\n }\r\n });\r\n \r\n return cookies;\r\n }\r\n\r\n /**\r\n * Get a header value\r\n */\r\n header(name) {\r\n return this.headers.get(name.toLowerCase());\r\n }\r\n\r\n /**\r\n * Get a cookie value\r\n */\r\n cookie(name) {\r\n return this.cookies.get(name);\r\n }\r\n\r\n /**\r\n * Check if request matches a path pattern\r\n */\r\n matches(pattern) {\r\n return matchPath(this.pathname, pattern);\r\n }\r\n}\r\n\r\n/**\r\n * Loads middleware from project\r\n */\r\nexport async function loadMiddleware(projectRoot) {\r\n const middlewarePath = path.join(projectRoot, 'middleware.js');\r\n \r\n if (!fs.existsSync(middlewarePath)) {\r\n return null;\r\n }\r\n\r\n try {\r\n const url = pathToFileURL(middlewarePath).href;\r\n const module = await import(`${url}?t=${Date.now()}`);\r\n \r\n return {\r\n handler: module.default,\r\n config: module.config || {}\r\n };\r\n } catch (error) {\r\n console.error('Failed to load middleware:', error);\r\n return null;\r\n }\r\n}\r\n\r\n/**\r\n * Runs middleware chain\r\n */\r\nexport async function runMiddleware(req, res, middleware) {\r\n if (!middleware) {\r\n return { continue: true };\r\n }\r\n\r\n const { handler, config } = middleware;\r\n const request = new MiddlewareRequest(req);\r\n\r\n // Check if request matches middleware patterns\r\n if (config.matcher) {\r\n const patterns = Array.isArray(config.matcher) ? config.matcher : [config.matcher];\r\n const matches = patterns.some(pattern => matchPath(request.pathname, pattern));\r\n \r\n if (!matches) {\r\n return { continue: true };\r\n }\r\n }\r\n\r\n try {\r\n const response = await handler(request);\r\n\r\n if (!response || response.type === 'next') {\r\n // Apply any headers from middleware\r\n if (response?.headers) {\r\n for (const [key, value] of response.headers) {\r\n res.setHeader(key, value);\r\n }\r\n }\r\n return { continue: true };\r\n }\r\n\r\n if (response.type === 'redirect') {\r\n res.writeHead(response.status, { Location: response.url });\r\n res.end();\r\n return { continue: false };\r\n }\r\n\r\n if (response.type === 'rewrite') {\r\n // Modify the request URL internally\r\n req.url = response.url;\r\n return { continue: true, rewritten: true };\r\n }\r\n\r\n if (response.type === 'response') {\r\n // Apply headers\r\n for (const [key, value] of response.headers) {\r\n res.setHeader(key, value);\r\n }\r\n res.writeHead(response.status);\r\n res.end(response.body);\r\n return { continue: false };\r\n }\r\n\r\n return { continue: true };\r\n\r\n } catch (error) {\r\n console.error('Middleware error:', error);\r\n return { continue: true, error };\r\n }\r\n}\r\n\r\n/**\r\n * Matches a path against a pattern\r\n */\r\nfunction matchPath(pathname, pattern) {\r\n // Convert pattern to regex\r\n let regex = pattern\r\n .replace(/\\*/g, '.*')\r\n .replace(/:path\\*/g, '.*')\r\n .replace(/:(\\w+)/g, '[^/]+');\r\n \r\n regex = `^${regex}$`;\r\n \r\n return new RegExp(regex).test(pathname);\r\n}\r\n\r\n/**\r\n * Compose multiple middleware functions\r\n */\r\nexport function composeMiddleware(...middlewares) {\r\n return async (request) => {\r\n for (const middleware of middlewares) {\r\n const response = await middleware(request);\r\n \r\n if (response && response.type !== 'next') {\r\n return response;\r\n }\r\n }\r\n \r\n return MiddlewareResponse.next();\r\n };\r\n}\r\n\r\n/**\r\n * Built-in middleware helpers\r\n */\r\nexport const middlewares = {\r\n /**\r\n * CORS middleware\r\n */\r\n cors(options: { origin?: string; methods?: string; headers?: string; credentials?: boolean } = {}) {\r\n const {\r\n origin = '*',\r\n methods = 'GET,HEAD,PUT,PATCH,POST,DELETE',\r\n headers = 'Content-Type,Authorization',\r\n credentials = false\r\n } = options;\r\n\r\n return (request) => {\r\n const response = MiddlewareResponse.next({\r\n headers: {\r\n 'Access-Control-Allow-Origin': origin,\r\n 'Access-Control-Allow-Methods': methods,\r\n 'Access-Control-Allow-Headers': headers,\r\n ...(credentials && { 'Access-Control-Allow-Credentials': 'true' })\r\n }\r\n });\r\n\r\n // Handle preflight\r\n if (request.method === 'OPTIONS') {\r\n return MiddlewareResponse.json({}, { status: 204, headers: Object.fromEntries(response.headers) });\r\n }\r\n\r\n return response;\r\n };\r\n },\r\n\r\n /**\r\n * Basic auth middleware\r\n */\r\n basicAuth(options) {\r\n const { username, password, realm = 'Protected' } = options;\r\n const expected = Buffer.from(`${username}:${password}`).toString('base64');\r\n\r\n return (request) => {\r\n const auth = request.header('authorization');\r\n \r\n if (!auth || !auth.startsWith('Basic ')) {\r\n return MiddlewareResponse.html('Unauthorized', {\r\n status: 401,\r\n headers: { 'WWW-Authenticate': `Basic realm=\"${realm}\"` }\r\n });\r\n }\r\n\r\n const provided = auth.slice(6);\r\n if (provided !== expected) {\r\n return MiddlewareResponse.html('Unauthorized', { status: 401 });\r\n }\r\n\r\n return MiddlewareResponse.next();\r\n };\r\n },\r\n\r\n /**\r\n * Rate limiting middleware\r\n */\r\n rateLimit(options: { windowMs?: number; max?: number } = {}) {\r\n const { windowMs = 60000, max = 100 } = options;\r\n const requests = new Map();\r\n\r\n return (request) => {\r\n const ip = request.header('x-forwarded-for') || 'unknown';\r\n const now = Date.now();\r\n \r\n // Clean old entries\r\n for (const [key, data] of requests) {\r\n if (now - data.start > windowMs) {\r\n requests.delete(key);\r\n }\r\n }\r\n\r\n // Check rate limit\r\n const data = requests.get(ip) || { count: 0, start: now };\r\n data.count++;\r\n requests.set(ip, data);\r\n\r\n if (data.count > max) {\r\n return MiddlewareResponse.json(\r\n { error: 'Too many requests' },\r\n { status: 429 }\r\n );\r\n }\r\n\r\n return MiddlewareResponse.next({\r\n headers: {\r\n 'X-RateLimit-Limit': String(max),\r\n 'X-RateLimit-Remaining': String(max - data.count)\r\n }\r\n });\r\n };\r\n },\r\n\r\n /**\r\n * Logging middleware\r\n */\r\n logger(options: { format?: string } = {}) {\r\n const { format = 'combined' } = options;\r\n\r\n return (request) => {\r\n const start = Date.now();\r\n const { method, pathname } = request;\r\n \r\n console.log(`→ ${method} ${pathname}`);\r\n \r\n return MiddlewareResponse.next();\r\n };\r\n }\r\n};\r\n\r\nexport default {\r\n MiddlewareRequest,\r\n MiddlewareResponse,\r\n loadMiddleware,\r\n runMiddleware,\r\n composeMiddleware,\r\n middlewares\r\n};\r\n","/**\r\n * FlexiReact Plugin System\r\n * \r\n * Plugins can extend FlexiReact's functionality by hooking into various lifecycle events.\r\n * \r\n * Usage:\r\n * Create a flexireact.plugin.js file:\r\n * \r\n * export default {\r\n * name: 'my-plugin',\r\n * \r\n * // Called when the server starts\r\n * onServerStart(server) {},\r\n * \r\n * // Called before each request\r\n * onRequest(req, res) {},\r\n * \r\n * // Called before rendering a page\r\n * onBeforeRender(page, props) {},\r\n * \r\n * // Called after rendering a page\r\n * onAfterRender(html, page) {},\r\n * \r\n * // Called during build\r\n * onBuild(config) {},\r\n * \r\n * // Modify esbuild config\r\n * esbuildConfig(config) {},\r\n * };\r\n */\r\n\r\nimport fs from 'fs';\r\nimport path from 'path';\r\nimport { pathToFileURL } from 'url';\r\n\r\n/**\r\n * Plugin lifecycle hooks\r\n */\r\nexport const PluginHooks = {\r\n // Server lifecycle\r\n SERVER_START: 'onServerStart',\r\n SERVER_STOP: 'onServerStop',\r\n \r\n // Request lifecycle\r\n REQUEST: 'onRequest',\r\n RESPONSE: 'onResponse',\r\n \r\n // Render lifecycle\r\n BEFORE_RENDER: 'onBeforeRender',\r\n AFTER_RENDER: 'onAfterRender',\r\n \r\n // Build lifecycle\r\n BUILD_START: 'onBuildStart',\r\n BUILD_END: 'onBuildEnd',\r\n \r\n // Route lifecycle\r\n ROUTES_LOADED: 'onRoutesLoaded',\r\n \r\n // Config\r\n CONFIG: 'onConfig',\r\n ESBUILD_CONFIG: 'esbuildConfig'\r\n};\r\n\r\n/**\r\n * Plugin manager class\r\n */\r\nexport class PluginManager {\r\n plugins: any[];\r\n hooks: Map<string, any[]>;\r\n\r\n constructor() {\r\n this.plugins = [];\r\n this.hooks = new Map();\r\n \r\n // Initialize hook arrays\r\n for (const hook of Object.values(PluginHooks)) {\r\n this.hooks.set(hook as string, []);\r\n }\r\n }\r\n\r\n /**\r\n * Registers a plugin\r\n */\r\n register(plugin) {\r\n if (!plugin.name) {\r\n throw new Error('Plugin must have a name');\r\n }\r\n\r\n // Check for duplicate\r\n if (this.plugins.find(p => p.name === plugin.name)) {\r\n console.warn(`Plugin \"${plugin.name}\" is already registered`);\r\n return;\r\n }\r\n\r\n this.plugins.push(plugin);\r\n\r\n // Register hooks\r\n for (const [hookName, handlers] of this.hooks) {\r\n if (typeof plugin[hookName] === 'function') {\r\n handlers.push({\r\n plugin: plugin.name,\r\n handler: plugin[hookName].bind(plugin)\r\n });\r\n }\r\n }\r\n\r\n console.log(` ✓ Plugin loaded: ${plugin.name}`);\r\n }\r\n\r\n /**\r\n * Unregisters a plugin\r\n */\r\n unregister(pluginName) {\r\n const index = this.plugins.findIndex(p => p.name === pluginName);\r\n if (index === -1) return;\r\n\r\n this.plugins.splice(index, 1);\r\n\r\n // Remove hooks\r\n for (const handlers of this.hooks.values()) {\r\n const hookIndex = handlers.findIndex(h => h.plugin === pluginName);\r\n if (hookIndex !== -1) {\r\n handlers.splice(hookIndex, 1);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Runs a hook with all registered handlers\r\n */\r\n async runHook(hookName, ...args) {\r\n const handlers = this.hooks.get(hookName) || [];\r\n const results = [];\r\n\r\n for (const { plugin, handler } of handlers) {\r\n try {\r\n const result = await handler(...args);\r\n results.push({ plugin, result });\r\n } catch (error) {\r\n console.error(`Plugin \"${plugin}\" error in ${hookName}:`, error);\r\n results.push({ plugin, error });\r\n }\r\n }\r\n\r\n return results;\r\n }\r\n\r\n /**\r\n * Runs a hook that can modify a value (waterfall)\r\n */\r\n async runWaterfallHook(hookName, initialValue, ...args) {\r\n const handlers = this.hooks.get(hookName) || [];\r\n let value = initialValue;\r\n\r\n for (const { plugin, handler } of handlers) {\r\n try {\r\n const result = await handler(value, ...args);\r\n if (result !== undefined) {\r\n value = result;\r\n }\r\n } catch (error) {\r\n console.error(`Plugin \"${plugin}\" error in ${hookName}:`, error);\r\n }\r\n }\r\n\r\n return value;\r\n }\r\n\r\n /**\r\n * Checks if any plugin handles a hook\r\n */\r\n hasHook(hookName) {\r\n const handlers = this.hooks.get(hookName) || [];\r\n return handlers.length > 0;\r\n }\r\n\r\n /**\r\n * Gets all registered plugins\r\n */\r\n getPlugins() {\r\n return [...this.plugins];\r\n }\r\n}\r\n\r\n// Global plugin manager instance\r\nexport const pluginManager = new PluginManager();\r\n\r\n/**\r\n * Loads plugins from project and config\r\n */\r\nexport async function loadPlugins(projectRoot, config) {\r\n console.log('\\n📦 Loading plugins...\\n');\r\n\r\n // Load from flexireact.plugin.js\r\n const pluginPath = path.join(projectRoot, 'flexireact.plugin.js');\r\n \r\n if (fs.existsSync(pluginPath)) {\r\n try {\r\n const url = pathToFileURL(pluginPath).href;\r\n const module = await import(`${url}?t=${Date.now()}`);\r\n const plugin = module.default;\r\n \r\n if (plugin) {\r\n pluginManager.register(plugin);\r\n }\r\n } catch (error) {\r\n console.error('Failed to load flexireact.plugin.js:', error);\r\n }\r\n }\r\n\r\n // Load plugins from config\r\n if (config.plugins && Array.isArray(config.plugins)) {\r\n for (const pluginConfig of config.plugins) {\r\n try {\r\n if (typeof pluginConfig === 'string') {\r\n // Load from node_modules\r\n const module = await import(pluginConfig);\r\n pluginManager.register(module.default);\r\n } else if (typeof pluginConfig === 'object') {\r\n // Inline plugin\r\n pluginManager.register(pluginConfig);\r\n } else if (typeof pluginConfig === 'function') {\r\n // Plugin factory\r\n pluginManager.register(pluginConfig());\r\n }\r\n } catch (error) {\r\n console.error(`Failed to load plugin:`, error);\r\n }\r\n }\r\n }\r\n\r\n console.log(`\\n Total plugins: ${pluginManager.getPlugins().length}\\n`);\r\n\r\n return pluginManager;\r\n}\r\n\r\n/**\r\n * Creates a plugin\r\n */\r\nexport function definePlugin(options) {\r\n return {\r\n name: options.name || 'unnamed-plugin',\r\n ...options\r\n };\r\n}\r\n\r\n/**\r\n * Built-in plugins\r\n */\r\nexport const builtinPlugins = {\r\n /**\r\n * Analytics plugin\r\n */\r\n analytics(options: { trackingId?: string } = {}) {\r\n const { trackingId } = options;\r\n\r\n return definePlugin({\r\n name: 'flexi-analytics',\r\n\r\n onAfterRender(html) {\r\n if (!trackingId) return html;\r\n\r\n const script = `\r\n <script async src=\"https://www.googletagmanager.com/gtag/js?id=${trackingId}\"></script>\r\n <script>\r\n window.dataLayer = window.dataLayer || [];\r\n function gtag(){dataLayer.push(arguments);}\r\n gtag('js', new Date());\r\n gtag('config', '${trackingId}');\r\n </script>\r\n `;\r\n\r\n return html.replace('</head>', `${script}</head>`);\r\n }\r\n });\r\n },\r\n\r\n /**\r\n * PWA plugin\r\n */\r\n pwa(options: { manifest?: string; serviceWorker?: string } = {}) {\r\n const { manifest = '/manifest.json', serviceWorker = '/sw.js' } = options;\r\n\r\n return definePlugin({\r\n name: 'flexi-pwa',\r\n\r\n onAfterRender(html) {\r\n const tags = `\r\n <link rel=\"manifest\" href=\"${manifest}\">\r\n <script>\r\n if ('serviceWorker' in navigator) {\r\n navigator.serviceWorker.register('${serviceWorker}');\r\n }\r\n </script>\r\n `;\r\n\r\n return html.replace('</head>', `${tags}</head>`);\r\n }\r\n });\r\n },\r\n\r\n /**\r\n * SEO plugin\r\n */\r\n seo(options: { defaultTitle?: string; titleTemplate?: string; defaultDescription?: string } = {}) {\r\n const { defaultTitle, titleTemplate = '%s', defaultDescription } = options;\r\n\r\n return definePlugin({\r\n name: 'flexi-seo',\r\n\r\n onBeforeRender(page, props) {\r\n const title = props.title || page.title || defaultTitle;\r\n const description = props.description || page.description || defaultDescription;\r\n\r\n return {\r\n ...props,\r\n _seo: {\r\n title: titleTemplate.replace('%s', title),\r\n description\r\n }\r\n };\r\n }\r\n });\r\n },\r\n\r\n /**\r\n * Compression plugin (for production)\r\n */\r\n compression() {\r\n return definePlugin({\r\n name: 'flexi-compression',\r\n\r\n onResponse(req, res, html) {\r\n // Note: Actual compression would require zlib\r\n // This is a placeholder for the concept\r\n res.setHeader('Content-Encoding', 'identity');\r\n return html;\r\n }\r\n });\r\n },\r\n\r\n /**\r\n * Security headers plugin\r\n */\r\n securityHeaders(options: { headers?: Record<string, string> } = {}) {\r\n const headers: Record<string, string> = {\r\n 'X-Content-Type-Options': 'nosniff',\r\n 'X-Frame-Options': 'DENY',\r\n 'X-XSS-Protection': '1; mode=block',\r\n 'Referrer-Policy': 'strict-origin-when-cross-origin',\r\n ...options.headers\r\n };\r\n\r\n return definePlugin({\r\n name: 'flexi-security',\r\n\r\n onRequest(req, res) {\r\n for (const [key, value] of Object.entries(headers)) {\r\n res.setHeader(key, value);\r\n }\r\n }\r\n });\r\n }\r\n};\r\n\r\nexport default {\r\n PluginManager,\r\n PluginHooks,\r\n pluginManager,\r\n loadPlugins,\r\n definePlugin,\r\n builtinPlugins\r\n};\r\n","/**\r\n * FlexiReact Islands Architecture\r\n * \r\n * Islands allow partial hydration - only interactive components are hydrated on the client,\r\n * while static content remains as HTML. This dramatically reduces JavaScript bundle size.\r\n * \r\n * Usage:\r\n * - Add 'use island' at the top of a component file\r\n * - The component will be rendered on server and hydrated on client\r\n * - Non-island components are pure HTML (no JS)\r\n */\r\n\r\nimport React from 'react';\r\nimport { renderToString } from 'react-dom/server';\r\nimport crypto from 'crypto';\r\n\r\n// Island registry for tracking all islands in a render\r\nconst islandRegistry = new Map();\r\n\r\n/**\r\n * Generates a unique island ID\r\n */\r\nfunction generateIslandId(componentName) {\r\n const hash = crypto.randomBytes(4).toString('hex');\r\n return `island-${componentName}-${hash}`;\r\n}\r\n\r\n/**\r\n * Island wrapper component for server-side rendering\r\n */\r\nexport function Island({ component: Component, props = {}, name, clientPath }) {\r\n const islandId = generateIslandId(name);\r\n \r\n // Register island for hydration\r\n islandRegistry.set(islandId, {\r\n id: islandId,\r\n name,\r\n clientPath,\r\n props\r\n });\r\n\r\n // Render the component\r\n const content = renderToString(React.createElement(Component, props));\r\n\r\n // Return wrapper with hydration marker\r\n return React.createElement('div', {\r\n 'data-island': islandId,\r\n 'data-island-name': name,\r\n 'data-island-props': JSON.stringify(props),\r\n dangerouslySetInnerHTML: { __html: content }\r\n });\r\n}\r\n\r\n/**\r\n * Gets all registered islands and clears the registry\r\n */\r\nexport function getRegisteredIslands() {\r\n const islands = Array.from(islandRegistry.values());\r\n islandRegistry.clear();\r\n return islands;\r\n}\r\n\r\n/**\r\n * Creates an island component wrapper\r\n */\r\ninterface IslandOptions {\r\n name?: string;\r\n clientPath?: string;\r\n}\r\n\r\nexport function createIsland(Component: React.ComponentType<any>, options: IslandOptions = {}) {\r\n const { name = (Component as any).name || 'Island', clientPath } = options;\r\n\r\n function IslandWrapper(props) {\r\n return Island({\r\n component: Component,\r\n props,\r\n name,\r\n clientPath: clientPath || `/_flexi/islands/${name}.js`\r\n });\r\n }\r\n\r\n IslandWrapper.displayName = `Island(${name})`;\r\n IslandWrapper.isIsland = true;\r\n IslandWrapper.originalComponent = Component;\r\n\r\n return IslandWrapper;\r\n}\r\n\r\n/**\r\n * Generates the client-side hydration script\r\n */\r\nexport function generateHydrationScript(islands) {\r\n if (!islands.length) return '';\r\n\r\n const islandData = islands.map(island => ({\r\n id: island.id,\r\n name: island.name,\r\n path: island.clientPath,\r\n props: island.props\r\n }));\r\n\r\n return `\r\n<script type=\"module\">\r\n const islands = ${JSON.stringify(islandData)};\r\n \r\n async function hydrateIslands() {\r\n const { hydrateRoot } = await import('/_flexi/react-dom-client.js');\r\n const React = await import('/_flexi/react.js');\r\n \r\n for (const island of islands) {\r\n try {\r\n const element = document.querySelector(\\`[data-island=\"\\${island.id}\"]\\`);\r\n if (!element) continue;\r\n \r\n const module = await import(island.path);\r\n const Component = module.default;\r\n \r\n // Hydrate the island\r\n hydrateRoot(element, React.createElement(Component, island.props));\r\n \r\n // Mark as hydrated\r\n element.setAttribute('data-hydrated', 'true');\r\n } catch (error) {\r\n console.error(\\`Failed to hydrate island \\${island.name}:\\`, error);\r\n }\r\n }\r\n }\r\n \r\n // Hydrate when DOM is ready\r\n if (document.readyState === 'loading') {\r\n document.addEventListener('DOMContentLoaded', hydrateIslands);\r\n } else {\r\n hydrateIslands();\r\n }\r\n</script>`;\r\n}\r\n\r\n/**\r\n * Island loading strategies\r\n */\r\nexport const LoadStrategy = {\r\n // Hydrate immediately when page loads\r\n IMMEDIATE: 'immediate',\r\n // Hydrate when island becomes visible\r\n VISIBLE: 'visible',\r\n // Hydrate when user interacts with the page\r\n IDLE: 'idle',\r\n // Hydrate on specific media query\r\n MEDIA: 'media'\r\n};\r\n\r\n/**\r\n * Creates a lazy island that hydrates based on strategy\r\n */\r\ninterface LazyIslandOptions {\r\n name?: string;\r\n clientPath?: string;\r\n strategy?: string;\r\n media?: string | null;\r\n}\r\n\r\nexport function createLazyIsland(Component: React.ComponentType<any>, options: LazyIslandOptions = {}) {\r\n const {\r\n name = (Component as any).name || 'LazyIsland',\r\n clientPath,\r\n strategy = LoadStrategy.VISIBLE,\r\n media = null\r\n } = options;\r\n\r\n function LazyIslandWrapper(props) {\r\n const islandId = generateIslandId(name);\r\n const content = renderToString(React.createElement(Component, props));\r\n\r\n // Register with loading strategy\r\n islandRegistry.set(islandId, {\r\n id: islandId,\r\n name,\r\n clientPath: clientPath || `/_flexi/islands/${name}.js`,\r\n props,\r\n strategy,\r\n media\r\n });\r\n\r\n return React.createElement('div', {\r\n 'data-island': islandId,\r\n 'data-island-name': name,\r\n 'data-island-strategy': strategy,\r\n 'data-island-media': media,\r\n 'data-island-props': JSON.stringify(props),\r\n dangerouslySetInnerHTML: { __html: content }\r\n });\r\n }\r\n\r\n LazyIslandWrapper.displayName = `LazyIsland(${name})`;\r\n LazyIslandWrapper.isIsland = true;\r\n LazyIslandWrapper.isLazy = true;\r\n\r\n return LazyIslandWrapper;\r\n}\r\n\r\n/**\r\n * Generates advanced hydration script with loading strategies\r\n */\r\nexport function generateAdvancedHydrationScript(islands) {\r\n if (!islands.length) return '';\r\n\r\n const islandData = islands.map(island => ({\r\n id: island.id,\r\n name: island.name,\r\n path: island.clientPath,\r\n props: island.props,\r\n strategy: island.strategy || LoadStrategy.IMMEDIATE,\r\n media: island.media\r\n }));\r\n\r\n return `\r\n<script type=\"module\">\r\n const islands = ${JSON.stringify(islandData)};\r\n \r\n async function hydrateIsland(island) {\r\n const element = document.querySelector(\\`[data-island=\"\\${island.id}\"]\\`);\r\n if (!element || element.hasAttribute('data-hydrated')) return;\r\n \r\n try {\r\n const { hydrateRoot } = await import('/_flexi/react-dom-client.js');\r\n const React = await import('/_flexi/react.js');\r\n const module = await import(island.path);\r\n const Component = module.default;\r\n \r\n hydrateRoot(element, React.createElement(Component, island.props));\r\n element.setAttribute('data-hydrated', 'true');\r\n } catch (error) {\r\n console.error(\\`Failed to hydrate island \\${island.name}:\\`, error);\r\n }\r\n }\r\n \r\n // Intersection Observer for visible strategy\r\n const visibleObserver = new IntersectionObserver((entries) => {\r\n entries.forEach(entry => {\r\n if (entry.isIntersecting) {\r\n const id = entry.target.getAttribute('data-island');\r\n const island = islands.find(i => i.id === id);\r\n if (island) {\r\n hydrateIsland(island);\r\n visibleObserver.unobserve(entry.target);\r\n }\r\n }\r\n });\r\n }, { rootMargin: '50px' });\r\n \r\n // Process islands based on strategy\r\n function processIslands() {\r\n for (const island of islands) {\r\n const element = document.querySelector(\\`[data-island=\"\\${island.id}\"]\\`);\r\n if (!element) continue;\r\n \r\n switch (island.strategy) {\r\n case 'immediate':\r\n hydrateIsland(island);\r\n break;\r\n case 'visible':\r\n visibleObserver.observe(element);\r\n break;\r\n case 'idle':\r\n requestIdleCallback(() => hydrateIsland(island));\r\n break;\r\n case 'media':\r\n if (island.media && window.matchMedia(island.media).matches) {\r\n hydrateIsland(island);\r\n }\r\n break;\r\n }\r\n }\r\n }\r\n \r\n if (document.readyState === 'loading') {\r\n document.addEventListener('DOMContentLoaded', processIslands);\r\n } else {\r\n processIslands();\r\n }\r\n</script>`;\r\n}\r\n\r\nexport default {\r\n Island,\r\n createIsland,\r\n createLazyIsland,\r\n getRegisteredIslands,\r\n generateHydrationScript,\r\n generateAdvancedHydrationScript,\r\n LoadStrategy\r\n};\r\n","/**\r\n * FlexiReact Context System\r\n * Provides request context and shared state for SSR/RSC\r\n */\r\n\r\nimport React from 'react';\r\n\r\n// Server-side request context\r\nexport const RequestContext = React.createContext(null);\r\n\r\n// Route context for nested routes\r\nexport const RouteContext = React.createContext(null);\r\n\r\n// Layout context\r\nexport const LayoutContext = React.createContext(null);\r\n\r\n/**\r\n * Creates a request context value\r\n */\r\nexport function createRequestContext(req, res, params = {}, query = {}) {\r\n return {\r\n req,\r\n res,\r\n params,\r\n query,\r\n url: req.url,\r\n method: req.method,\r\n headers: req.headers,\r\n cookies: parseCookies(req.headers.cookie || '')\r\n };\r\n}\r\n\r\n/**\r\n * Parse cookies from header string\r\n */\r\nfunction parseCookies(cookieHeader) {\r\n const cookies = {};\r\n if (!cookieHeader) return cookies;\r\n \r\n cookieHeader.split(';').forEach(cookie => {\r\n const [name, ...rest] = cookie.split('=');\r\n if (name) {\r\n cookies[name.trim()] = rest.join('=').trim();\r\n }\r\n });\r\n \r\n return cookies;\r\n}\r\n\r\n/**\r\n * Hook to access request context (server-side only)\r\n */\r\nexport function useRequest() {\r\n const context = React.useContext(RequestContext);\r\n if (!context) {\r\n throw new Error('useRequest must be used within a RequestContext provider');\r\n }\r\n return context;\r\n}\r\n\r\n/**\r\n * Hook to access route params\r\n */\r\nexport function useParams() {\r\n const context = React.useContext(RouteContext);\r\n return context?.params || {};\r\n}\r\n\r\n/**\r\n * Hook to access query parameters\r\n */\r\nexport function useQuery() {\r\n const context = React.useContext(RouteContext);\r\n return context?.query || {};\r\n}\r\n\r\n/**\r\n * Hook to access current pathname\r\n */\r\nexport function usePathname() {\r\n const context = React.useContext(RouteContext);\r\n return context?.pathname || '/';\r\n}\r\n","/**\r\n * FlexiReact Logger\r\n * Premium console output inspired by Next.js, Vite, and Bun\r\n */\r\n\r\n// ANSI color codes\r\nconst colors = {\r\n reset: '\\x1b[0m',\r\n bold: '\\x1b[1m',\r\n dim: '\\x1b[2m',\r\n italic: '\\x1b[3m',\r\n underline: '\\x1b[4m',\r\n \r\n // Text colors\r\n black: '\\x1b[30m',\r\n red: '\\x1b[31m',\r\n green: '\\x1b[32m',\r\n yellow: '\\x1b[33m',\r\n blue: '\\x1b[34m',\r\n magenta: '\\x1b[35m',\r\n cyan: '\\x1b[36m',\r\n white: '\\x1b[37m',\r\n gray: '\\x1b[90m',\r\n \r\n // Bright colors\r\n brightRed: '\\x1b[91m',\r\n brightGreen: '\\x1b[92m',\r\n brightYellow: '\\x1b[93m',\r\n brightBlue: '\\x1b[94m',\r\n brightMagenta: '\\x1b[95m',\r\n brightCyan: '\\x1b[96m',\r\n brightWhite: '\\x1b[97m',\r\n \r\n // Background colors\r\n bgRed: '\\x1b[41m',\r\n bgGreen: '\\x1b[42m',\r\n bgYellow: '\\x1b[43m',\r\n bgBlue: '\\x1b[44m',\r\n bgMagenta: '\\x1b[45m',\r\n bgCyan: '\\x1b[46m',\r\n};\r\n\r\nconst c = colors;\r\n\r\n// Get current time formatted\r\nfunction getTime() {\r\n const now = new Date();\r\n return `${c.dim}${now.toLocaleTimeString('en-US', { hour12: false })}${c.reset}`;\r\n}\r\n\r\n// Status code colors\r\nfunction getStatusColor(status) {\r\n if (status >= 500) return c.red;\r\n if (status >= 400) return c.yellow;\r\n if (status >= 300) return c.cyan;\r\n if (status >= 200) return c.green;\r\n return c.white;\r\n}\r\n\r\n// Method colors\r\nfunction getMethodColor(method) {\r\n const methodColors = {\r\n GET: c.brightGreen,\r\n POST: c.brightBlue,\r\n PUT: c.brightYellow,\r\n PATCH: c.brightMagenta,\r\n DELETE: c.brightRed,\r\n OPTIONS: c.gray,\r\n HEAD: c.gray,\r\n };\r\n return methodColors[method] || c.white;\r\n}\r\n\r\n// Format time\r\nfunction formatTime(ms) {\r\n if (ms < 1) return `${c.gray}<1ms${c.reset}`;\r\n if (ms < 100) return `${c.green}${ms}ms${c.reset}`;\r\n if (ms < 500) return `${c.yellow}${ms}ms${c.reset}`;\r\n return `${c.red}${ms}ms${c.reset}`;\r\n}\r\n\r\n// FlexiReact ASCII Logo - Premium Design\r\nconst LOGO = `\r\n${c.green} ╭─────────────────────────────────────────────╮${c.reset}\r\n${c.green} │${c.reset} ${c.green}│${c.reset}\r\n${c.green} │${c.reset} ${c.brightGreen}⚡${c.reset} ${c.bold}${c.white}F L E X I R E A C T${c.reset} ${c.dim}v1.0.0${c.reset} ${c.green}│${c.reset}\r\n${c.green} │${c.reset} ${c.green}│${c.reset}\r\n${c.green} │${c.reset} ${c.dim}The Modern React Framework${c.reset} ${c.green}│${c.reset}\r\n${c.green} │${c.reset} ${c.green}│${c.reset}\r\n${c.green} ╰─────────────────────────────────────────────╯${c.reset}\r\n`;\r\n\r\nconst MINI_LOGO = `${c.brightGreen}⚡${c.reset} ${c.bold}FlexiReact${c.reset}`;\r\n\r\n// Compact ready message like Next.js\r\nconst READY_MSG = ` ${c.green}▲${c.reset} ${c.bold}Ready${c.reset} in`;\r\n\r\nexport const logger = {\r\n // Show startup logo\r\n logo() {\r\n console.log(LOGO);\r\n },\r\n\r\n // Server started - Next.js style\r\n serverStart(config, startTime = Date.now()) {\r\n const { port, host, mode, pagesDir, islands, rsc } = config;\r\n const elapsed = Date.now() - startTime;\r\n \r\n console.log('');\r\n console.log(` ${c.green}▲${c.reset} ${c.bold}Ready${c.reset} in ${c.cyan}${elapsed}ms${c.reset}`);\r\n console.log('');\r\n console.log(` ${c.dim}┌${c.reset} ${c.bold}Local:${c.reset} ${c.cyan}http://${host}:${port}${c.reset}`);\r\n console.log(` ${c.dim}├${c.reset} ${c.bold}Environment:${c.reset} ${mode === 'development' ? `${c.yellow}development${c.reset}` : `${c.green}production${c.reset}`}`);\r\n if (islands) {\r\n console.log(` ${c.dim}├${c.reset} ${c.bold}Islands:${c.reset} ${c.green}enabled${c.reset}`);\r\n }\r\n if (rsc) {\r\n console.log(` ${c.dim}├${c.reset} ${c.bold}RSC:${c.reset} ${c.green}enabled${c.reset}`);\r\n }\r\n console.log(` ${c.dim}└${c.reset} ${c.bold}Pages:${c.reset} ${c.dim}${pagesDir}${c.reset}`);\r\n console.log('');\r\n },\r\n\r\n // HTTP request log - Compact single line like Next.js\r\n request(method: string, path: string, status: number, time: number, extra: { type?: string } = {}) {\r\n const methodColor = getMethodColor(method);\r\n const statusColor = getStatusColor(status);\r\n const timeStr = formatTime(time);\r\n \r\n // Route type badge\r\n let badge = '';\r\n if (extra.type === 'static' || extra.type === 'ssg') {\r\n badge = `${c.dim}○${c.reset}`; // Static\r\n } else if (extra.type === 'dynamic' || extra.type === 'ssr') {\r\n badge = `${c.magenta}ƒ${c.reset}`; // Function/SSR\r\n } else if (extra.type === 'api') {\r\n badge = `${c.blue}λ${c.reset}`; // API\r\n } else if (extra.type === 'asset') {\r\n badge = `${c.dim}◦${c.reset}`; // Asset\r\n } else {\r\n badge = `${c.magenta}ƒ${c.reset}`;\r\n }\r\n \r\n const statusStr = `${statusColor}${status}${c.reset}`;\r\n const methodStr = `${methodColor}${method}${c.reset}`;\r\n \r\n // Single line format like Next.js\r\n console.log(` ${badge} ${methodStr} ${path} ${statusStr} ${c.dim}in${c.reset} ${timeStr}`);\r\n },\r\n\r\n // Info message\r\n info(msg) {\r\n console.log(` ${c.cyan}ℹ${c.reset} ${msg}`);\r\n },\r\n\r\n // Success message\r\n success(msg) {\r\n console.log(` ${c.green}✓${c.reset} ${msg}`);\r\n },\r\n\r\n // Warning message\r\n warn(msg) {\r\n console.log(` ${c.yellow}⚠${c.reset} ${c.yellow}${msg}${c.reset}`);\r\n },\r\n\r\n // Error message\r\n error(msg, err = null) {\r\n console.log(` ${c.red}✗${c.reset} ${c.red}${msg}${c.reset}`);\r\n if (err && err.stack) {\r\n const stack = err.stack.split('\\n').slice(1, 4).join('\\n');\r\n console.log(`${c.dim}${stack}${c.reset}`);\r\n }\r\n },\r\n\r\n // Compilation message\r\n compile(file, time) {\r\n console.log(` ${c.magenta}◉${c.reset} Compiled ${c.cyan}${file}${c.reset} ${c.dim}(${time}ms)${c.reset}`);\r\n },\r\n\r\n // Hot reload\r\n hmr(file) {\r\n console.log(` ${c.yellow}↻${c.reset} HMR update: ${c.cyan}${file}${c.reset}`);\r\n },\r\n\r\n // Plugin loaded\r\n plugin(name) {\r\n console.log(` ${c.blue}⬡${c.reset} Plugin: ${c.cyan}${name}${c.reset}`);\r\n },\r\n\r\n // Route info\r\n route(path, type) {\r\n const typeColors = {\r\n static: c.green,\r\n dynamic: c.yellow,\r\n api: c.blue,\r\n };\r\n const color = typeColors[type] || c.white;\r\n console.log(` ${c.dim}├─${c.reset} ${path} ${color}[${type}]${c.reset}`);\r\n },\r\n\r\n // Divider\r\n divider() {\r\n console.log(`${c.dim} ─────────────────────────────────────────${c.reset}`);\r\n },\r\n\r\n // Blank line\r\n blank() {\r\n console.log('');\r\n },\r\n\r\n // Port in use error with solution\r\n portInUse(port) {\r\n console.log(`\r\n${c.red} ✗ Port ${port} is already in use${c.reset}\r\n\r\n ${c.dim}Try one of these solutions:${c.reset}\r\n \r\n ${c.yellow}1.${c.reset} Kill the process using the port:\r\n ${c.cyan}npx kill-port ${port}${c.reset}\r\n \r\n ${c.yellow}2.${c.reset} Use a different port in ${c.cyan}flexireact.config.js${c.reset}:\r\n ${c.dim}server: { port: 3001 }${c.reset}\r\n \r\n ${c.yellow}3.${c.reset} Set PORT environment variable:\r\n ${c.cyan}PORT=3001 npm run dev${c.reset}\r\n`);\r\n },\r\n\r\n // Build info\r\n build(stats) {\r\n console.log(`\r\n ${c.green}✓${c.reset} Build complete!\r\n \r\n ${c.dim}├─${c.reset} Pages: ${c.cyan}${stats.pages}${c.reset}\r\n ${c.dim}├─${c.reset} API: ${c.cyan}${stats.api}${c.reset}\r\n ${c.dim}├─${c.reset} Assets: ${c.cyan}${stats.assets}${c.reset}\r\n ${c.dim}└─${c.reset} Time: ${c.green}${stats.time}ms${c.reset}\r\n`);\r\n },\r\n};\r\n\r\nexport default logger;\r\n","/**\r\n * FlexiReact Server Helpers\r\n * Utility functions for server-side operations\r\n */\r\n\r\n// ============================================================================\r\n// Response Helpers\r\n// ============================================================================\r\n\r\n/**\r\n * Custom error classes for control flow\r\n */\r\nexport class RedirectError extends Error {\r\n public readonly url: string;\r\n public readonly statusCode: number;\r\n public readonly type = 'redirect' as const;\r\n\r\n constructor(url: string, statusCode: number = 307) {\r\n super(`Redirect to ${url}`);\r\n this.name = 'RedirectError';\r\n this.url = url;\r\n this.statusCode = statusCode;\r\n }\r\n}\r\n\r\nexport class NotFoundError extends Error {\r\n public readonly type = 'notFound' as const;\r\n\r\n constructor(message: string = 'Page not found') {\r\n super(message);\r\n this.name = 'NotFoundError';\r\n }\r\n}\r\n\r\n/**\r\n * Redirect to a different URL\r\n * @param url - The URL to redirect to\r\n * @param type - 'replace' (307) or 'push' (308) for permanent\r\n * \r\n * @example\r\n * ```tsx\r\n * import { redirect } from '@flexireact/core';\r\n * \r\n * export default function ProtectedPage() {\r\n * const user = getUser();\r\n * if (!user) {\r\n * redirect('/login');\r\n * }\r\n * return <Dashboard user={user} />;\r\n * }\r\n * ```\r\n */\r\nexport function redirect(url: string, type: 'replace' | 'permanent' = 'replace'): never {\r\n const statusCode = type === 'permanent' ? 308 : 307;\r\n throw new RedirectError(url, statusCode);\r\n}\r\n\r\n/**\r\n * Trigger a 404 Not Found response\r\n * \r\n * @example\r\n * ```tsx\r\n * import { notFound } from '@flexireact/core';\r\n * \r\n * export default function ProductPage({ params }) {\r\n * const product = getProduct(params.id);\r\n * if (!product) {\r\n * notFound();\r\n * }\r\n * return <Product data={product} />;\r\n * }\r\n * ```\r\n */\r\nexport function notFound(message?: string): never {\r\n throw new NotFoundError(message);\r\n}\r\n\r\n/**\r\n * Create a JSON response\r\n * \r\n * @example\r\n * ```ts\r\n * // In API route\r\n * export function GET() {\r\n * return json({ message: 'Hello' });\r\n * }\r\n * \r\n * export function POST() {\r\n * return json({ error: 'Bad request' }, { status: 400 });\r\n * }\r\n * ```\r\n */\r\nexport function json<T>(\r\n data: T,\r\n options: {\r\n status?: number;\r\n headers?: Record<string, string>;\r\n } = {}\r\n): Response {\r\n const { status = 200, headers = {} } = options;\r\n \r\n return new Response(JSON.stringify(data), {\r\n status,\r\n headers: {\r\n 'Content-Type': 'application/json',\r\n ...headers\r\n }\r\n });\r\n}\r\n\r\n/**\r\n * Create an HTML response\r\n */\r\nexport function html(\r\n content: string,\r\n options: {\r\n status?: number;\r\n headers?: Record<string, string>;\r\n } = {}\r\n): Response {\r\n const { status = 200, headers = {} } = options;\r\n \r\n return new Response(content, {\r\n status,\r\n headers: {\r\n 'Content-Type': 'text/html; charset=utf-8',\r\n ...headers\r\n }\r\n });\r\n}\r\n\r\n/**\r\n * Create a text response\r\n */\r\nexport function text(\r\n content: string,\r\n options: {\r\n status?: number;\r\n headers?: Record<string, string>;\r\n } = {}\r\n): Response {\r\n const { status = 200, headers = {} } = options;\r\n \r\n return new Response(content, {\r\n status,\r\n headers: {\r\n 'Content-Type': 'text/plain; charset=utf-8',\r\n ...headers\r\n }\r\n });\r\n}\r\n\r\n// ============================================================================\r\n// Cookies API\r\n// ============================================================================\r\n\r\nexport interface CookieOptions {\r\n /** Max age in seconds */\r\n maxAge?: number;\r\n /** Expiration date */\r\n expires?: Date;\r\n /** Cookie path */\r\n path?: string;\r\n /** Cookie domain */\r\n domain?: string;\r\n /** Secure flag (HTTPS only) */\r\n secure?: boolean;\r\n /** HttpOnly flag */\r\n httpOnly?: boolean;\r\n /** SameSite policy */\r\n sameSite?: 'strict' | 'lax' | 'none';\r\n}\r\n\r\n/**\r\n * Cookie utilities for server-side operations\r\n */\r\nexport const cookies = {\r\n /**\r\n * Parse cookies from a cookie header string\r\n */\r\n parse(cookieHeader: string): Record<string, string> {\r\n const cookies: Record<string, string> = {};\r\n if (!cookieHeader) return cookies;\r\n\r\n cookieHeader.split(';').forEach(cookie => {\r\n const [name, ...rest] = cookie.split('=');\r\n if (name) {\r\n const value = rest.join('=');\r\n cookies[name.trim()] = decodeURIComponent(value.trim());\r\n }\r\n });\r\n\r\n return cookies;\r\n },\r\n\r\n /**\r\n * Get a cookie value from request headers\r\n */\r\n get(request: Request, name: string): string | undefined {\r\n const cookieHeader = request.headers.get('cookie') || '';\r\n const parsed = this.parse(cookieHeader);\r\n return parsed[name];\r\n },\r\n\r\n /**\r\n * Get all cookies from request\r\n */\r\n getAll(request: Request): Record<string, string> {\r\n const cookieHeader = request.headers.get('cookie') || '';\r\n return this.parse(cookieHeader);\r\n },\r\n\r\n /**\r\n * Serialize a cookie for Set-Cookie header\r\n */\r\n serialize(name: string, value: string, options: CookieOptions = {}): string {\r\n let cookie = `${encodeURIComponent(name)}=${encodeURIComponent(value)}`;\r\n\r\n if (options.maxAge !== undefined) {\r\n cookie += `; Max-Age=${options.maxAge}`;\r\n }\r\n if (options.expires) {\r\n cookie += `; Expires=${options.expires.toUTCString()}`;\r\n }\r\n if (options.path) {\r\n cookie += `; Path=${options.path}`;\r\n }\r\n if (options.domain) {\r\n cookie += `; Domain=${options.domain}`;\r\n }\r\n if (options.secure) {\r\n cookie += '; Secure';\r\n }\r\n if (options.httpOnly) {\r\n cookie += '; HttpOnly';\r\n }\r\n if (options.sameSite) {\r\n cookie += `; SameSite=${options.sameSite.charAt(0).toUpperCase() + options.sameSite.slice(1)}`;\r\n }\r\n\r\n return cookie;\r\n },\r\n\r\n /**\r\n * Create a Set-Cookie header value\r\n */\r\n set(name: string, value: string, options: CookieOptions = {}): string {\r\n return this.serialize(name, value, {\r\n path: '/',\r\n httpOnly: true,\r\n secure: process.env.NODE_ENV === 'production',\r\n sameSite: 'lax',\r\n ...options\r\n });\r\n },\r\n\r\n /**\r\n * Create a cookie deletion header\r\n */\r\n delete(name: string, options: Omit<CookieOptions, 'maxAge' | 'expires'> = {}): string {\r\n return this.serialize(name, '', {\r\n ...options,\r\n path: '/',\r\n maxAge: 0\r\n });\r\n }\r\n};\r\n\r\n// ============================================================================\r\n// Headers API\r\n// ============================================================================\r\n\r\n/**\r\n * Headers utilities for server-side operations\r\n */\r\nexport const headers = {\r\n /**\r\n * Create a new Headers object with common defaults\r\n */\r\n create(init?: HeadersInit): Headers {\r\n return new Headers(init);\r\n },\r\n\r\n /**\r\n * Get a header value from request\r\n */\r\n get(request: Request, name: string): string | null {\r\n return request.headers.get(name);\r\n },\r\n\r\n /**\r\n * Get all headers as an object\r\n */\r\n getAll(request: Request): Record<string, string> {\r\n const result: Record<string, string> = {};\r\n request.headers.forEach((value, key) => {\r\n result[key] = value;\r\n });\r\n return result;\r\n },\r\n\r\n /**\r\n * Check if request has a specific header\r\n */\r\n has(request: Request, name: string): boolean {\r\n return request.headers.has(name);\r\n },\r\n\r\n /**\r\n * Get content type from request\r\n */\r\n contentType(request: Request): string | null {\r\n return request.headers.get('content-type');\r\n },\r\n\r\n /**\r\n * Check if request accepts JSON\r\n */\r\n acceptsJson(request: Request): boolean {\r\n const accept = request.headers.get('accept') || '';\r\n return accept.includes('application/json') || accept.includes('*/*');\r\n },\r\n\r\n /**\r\n * Check if request is AJAX/fetch\r\n */\r\n isAjax(request: Request): boolean {\r\n return request.headers.get('x-requested-with') === 'XMLHttpRequest' ||\r\n this.acceptsJson(request);\r\n },\r\n\r\n /**\r\n * Get authorization header\r\n */\r\n authorization(request: Request): { type: string; credentials: string } | null {\r\n const auth = request.headers.get('authorization');\r\n if (!auth) return null;\r\n\r\n const [type, ...rest] = auth.split(' ');\r\n return {\r\n type: type.toLowerCase(),\r\n credentials: rest.join(' ')\r\n };\r\n },\r\n\r\n /**\r\n * Get bearer token from authorization header\r\n */\r\n bearerToken(request: Request): string | null {\r\n const auth = this.authorization(request);\r\n if (auth?.type === 'bearer') {\r\n return auth.credentials;\r\n }\r\n return null;\r\n },\r\n\r\n /**\r\n * Common security headers\r\n */\r\n security(): Record<string, string> {\r\n return {\r\n 'X-Content-Type-Options': 'nosniff',\r\n 'X-Frame-Options': 'DENY',\r\n 'X-XSS-Protection': '1; mode=block',\r\n 'Referrer-Policy': 'strict-origin-when-cross-origin',\r\n 'Permissions-Policy': 'camera=(), microphone=(), geolocation=()'\r\n };\r\n },\r\n\r\n /**\r\n * CORS headers\r\n */\r\n cors(options: {\r\n origin?: string;\r\n methods?: string[];\r\n headers?: string[];\r\n credentials?: boolean;\r\n maxAge?: number;\r\n } = {}): Record<string, string> {\r\n const {\r\n origin = '*',\r\n methods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],\r\n headers: allowHeaders = ['Content-Type', 'Authorization'],\r\n credentials = false,\r\n maxAge = 86400\r\n } = options;\r\n\r\n const corsHeaders: Record<string, string> = {\r\n 'Access-Control-Allow-Origin': origin,\r\n 'Access-Control-Allow-Methods': methods.join(', '),\r\n 'Access-Control-Allow-Headers': allowHeaders.join(', '),\r\n 'Access-Control-Max-Age': String(maxAge)\r\n };\r\n\r\n if (credentials) {\r\n corsHeaders['Access-Control-Allow-Credentials'] = 'true';\r\n }\r\n\r\n return corsHeaders;\r\n },\r\n\r\n /**\r\n * Cache control headers\r\n */\r\n cache(options: {\r\n maxAge?: number;\r\n sMaxAge?: number;\r\n staleWhileRevalidate?: number;\r\n private?: boolean;\r\n noStore?: boolean;\r\n } = {}): Record<string, string> {\r\n if (options.noStore) {\r\n return { 'Cache-Control': 'no-store, no-cache, must-revalidate' };\r\n }\r\n\r\n const directives: string[] = [];\r\n \r\n if (options.private) {\r\n directives.push('private');\r\n } else {\r\n directives.push('public');\r\n }\r\n\r\n if (options.maxAge !== undefined) {\r\n directives.push(`max-age=${options.maxAge}`);\r\n }\r\n\r\n if (options.sMaxAge !== undefined) {\r\n directives.push(`s-maxage=${options.sMaxAge}`);\r\n }\r\n\r\n if (options.staleWhileRevalidate !== undefined) {\r\n directives.push(`stale-while-revalidate=${options.staleWhileRevalidate}`);\r\n }\r\n\r\n return { 'Cache-Control': directives.join(', ') };\r\n }\r\n};\r\n\r\n// ============================================================================\r\n// Request Helpers\r\n// ============================================================================\r\n\r\n/**\r\n * Parse JSON body from request\r\n */\r\nexport async function parseJson<T = unknown>(request: Request): Promise<T> {\r\n try {\r\n return await request.json();\r\n } catch {\r\n throw new Error('Invalid JSON body');\r\n }\r\n}\r\n\r\n/**\r\n * Parse form data from request\r\n */\r\nexport async function parseFormData(request: Request): Promise<FormData> {\r\n return await request.formData();\r\n}\r\n\r\n/**\r\n * Parse URL search params\r\n */\r\nexport function parseSearchParams(request: Request): URLSearchParams {\r\n const url = new URL(request.url);\r\n return url.searchParams;\r\n}\r\n\r\n/**\r\n * Get request method\r\n */\r\nexport function getMethod(request: Request): string {\r\n return request.method.toUpperCase();\r\n}\r\n\r\n/**\r\n * Get request pathname\r\n */\r\nexport function getPathname(request: Request): string {\r\n const url = new URL(request.url);\r\n return url.pathname;\r\n}\r\n\r\n/**\r\n * Check if request method matches\r\n */\r\nexport function isMethod(request: Request, method: string | string[]): boolean {\r\n const reqMethod = getMethod(request);\r\n if (Array.isArray(method)) {\r\n return method.map(m => m.toUpperCase()).includes(reqMethod);\r\n }\r\n return reqMethod === method.toUpperCase();\r\n}\r\n","/**\r\n * FlexiReact Server Actions\r\n * \r\n * React 19 native actions with FlexiReact enhancements.\r\n * \r\n * Usage:\r\n * ```tsx\r\n * // In a server file (actions.ts)\r\n * 'use server';\r\n * \r\n * export async function createUser(prevState: any, formData: FormData) {\r\n * const name = formData.get('name');\r\n * // Save to database...\r\n * return { success: true, id: 123 };\r\n * }\r\n * \r\n * // In a client component - React 19 style\r\n * 'use client';\r\n * import { useActionState } from '@flexireact/core';\r\n * import { createUser } from './actions';\r\n * \r\n * function Form() {\r\n * const [state, formAction, isPending] = useActionState(createUser, null);\r\n * return (\r\n * <form action={formAction}>\r\n * <input name=\"name\" />\r\n * <button type=\"submit\" disabled={isPending}>Create</button>\r\n * </form>\r\n * );\r\n * }\r\n * ```\r\n */\r\n\r\n// ============================================================================\r\n// React 19 Hooks (re-exported for convenience)\r\n// ============================================================================\r\nexport { useActionState, useOptimistic } from 'react';\r\nexport { useFormStatus } from 'react-dom';\r\n\r\nimport { cookies, headers, redirect, notFound, RedirectError, NotFoundError } from '../helpers.js';\r\n\r\n// Global action registry\r\ndeclare global {\r\n var __FLEXI_ACTIONS__: Record<string, ServerActionFunction>;\r\n var __FLEXI_ACTION_CONTEXT__: ActionContext | null;\r\n}\r\n\r\nglobalThis.__FLEXI_ACTIONS__ = globalThis.__FLEXI_ACTIONS__ || {};\r\nglobalThis.__FLEXI_ACTION_CONTEXT__ = null;\r\n\r\nexport interface ActionContext {\r\n request: Request;\r\n cookies: typeof cookies;\r\n headers: typeof headers;\r\n redirect: typeof redirect;\r\n notFound: typeof notFound;\r\n}\r\n\r\nexport type ServerActionFunction = (...args: any[]) => Promise<any>;\r\n\r\nexport interface ActionResult<T = any> {\r\n success: boolean;\r\n data?: T;\r\n error?: string;\r\n redirect?: string;\r\n}\r\n\r\n/**\r\n * Decorator to mark a function as a server action\r\n */\r\nexport function serverAction<T extends ServerActionFunction>(\r\n fn: T,\r\n actionId?: string\r\n): T {\r\n const id = actionId || `action_${fn.name}_${generateActionId()}`;\r\n\r\n // Register the action\r\n globalThis.__FLEXI_ACTIONS__[id] = fn;\r\n\r\n // Create a proxy that will be serialized for the client\r\n const proxy = (async (...args: any[]) => {\r\n // If we're on the server, execute directly\r\n if (typeof window === 'undefined') {\r\n return await executeAction(id, args);\r\n }\r\n\r\n // If we're on the client, make a fetch request\r\n return await callServerAction(id, args);\r\n }) as T;\r\n\r\n // Mark as server action\r\n (proxy as any).$$typeof = Symbol.for('react.server.action');\r\n (proxy as any).$$id = id;\r\n (proxy as any).$$bound = null;\r\n\r\n return proxy;\r\n}\r\n\r\n/**\r\n * Register a server action\r\n */\r\nexport function registerAction(id: string, fn: ServerActionFunction): void {\r\n globalThis.__FLEXI_ACTIONS__[id] = fn;\r\n}\r\n\r\n/**\r\n * Get a registered action\r\n */\r\nexport function getAction(id: string): ServerActionFunction | undefined {\r\n return globalThis.__FLEXI_ACTIONS__[id];\r\n}\r\n\r\n/**\r\n * Execute a server action on the server\r\n */\r\nexport async function executeAction(\r\n actionId: string,\r\n args: any[],\r\n context?: Partial<ActionContext>\r\n): Promise<ActionResult> {\r\n const action = globalThis.__FLEXI_ACTIONS__[actionId];\r\n\r\n if (!action) {\r\n return {\r\n success: false,\r\n error: `Server action not found: ${actionId}`\r\n };\r\n }\r\n\r\n // Set up action context\r\n const actionContext: ActionContext = {\r\n request: context?.request || new Request('http://localhost'),\r\n cookies,\r\n headers,\r\n redirect,\r\n notFound\r\n };\r\n\r\n globalThis.__FLEXI_ACTION_CONTEXT__ = actionContext;\r\n\r\n try {\r\n const result = await action(...args);\r\n\r\n return {\r\n success: true,\r\n data: result\r\n };\r\n } catch (error: any) {\r\n // Handle redirect\r\n if (error instanceof RedirectError) {\r\n return {\r\n success: true,\r\n redirect: error.url\r\n };\r\n }\r\n\r\n // Handle not found\r\n if (error instanceof NotFoundError) {\r\n return {\r\n success: false,\r\n error: 'Not found'\r\n };\r\n }\r\n\r\n return {\r\n success: false,\r\n error: error.message || 'Action failed'\r\n };\r\n } finally {\r\n globalThis.__FLEXI_ACTION_CONTEXT__ = null;\r\n }\r\n}\r\n\r\n/**\r\n * Call a server action from the client\r\n */\r\nexport async function callServerAction(\r\n actionId: string,\r\n args: any[]\r\n): Promise<ActionResult> {\r\n try {\r\n const response = await fetch('/_flexi/action', {\r\n method: 'POST',\r\n headers: {\r\n 'Content-Type': 'application/json',\r\n 'X-Flexi-Action': actionId\r\n },\r\n body: JSON.stringify({\r\n actionId,\r\n args: serializeArgs(args)\r\n }),\r\n credentials: 'same-origin'\r\n });\r\n\r\n if (!response.ok) {\r\n throw new Error(`Action failed: ${response.statusText}`);\r\n }\r\n\r\n const result = await response.json();\r\n\r\n // Handle redirect\r\n if (result.redirect) {\r\n window.location.href = result.redirect;\r\n return result;\r\n }\r\n\r\n return result;\r\n } catch (error: any) {\r\n return {\r\n success: false,\r\n error: error.message || 'Network error'\r\n };\r\n }\r\n}\r\n\r\n/**\r\n * Serialize action arguments for transmission\r\n */\r\nfunction serializeArgs(args: any[]): any[] {\r\n return args.map(arg => {\r\n // Handle FormData\r\n if (arg instanceof FormData) {\r\n const obj: Record<string, any> = {};\r\n arg.forEach((value, key) => {\r\n if (obj[key]) {\r\n // Handle multiple values\r\n if (Array.isArray(obj[key])) {\r\n obj[key].push(value);\r\n } else {\r\n obj[key] = [obj[key], value];\r\n }\r\n } else {\r\n obj[key] = value;\r\n }\r\n });\r\n return { $$type: 'FormData', data: obj };\r\n }\r\n\r\n // Handle File\r\n if (typeof File !== 'undefined' && arg instanceof File) {\r\n return { $$type: 'File', name: arg.name, type: arg.type, size: arg.size };\r\n }\r\n\r\n // Handle Date\r\n if (arg instanceof Date) {\r\n return { $$type: 'Date', value: arg.toISOString() };\r\n }\r\n\r\n // Handle regular objects\r\n if (typeof arg === 'object' && arg !== null) {\r\n return JSON.parse(JSON.stringify(arg));\r\n }\r\n\r\n return arg;\r\n });\r\n}\r\n\r\n/**\r\n * Deserialize action arguments on the server\r\n */\r\nexport function deserializeArgs(args: any[]): any[] {\r\n return args.map(arg => {\r\n if (arg && typeof arg === 'object') {\r\n // Handle FormData\r\n if (arg.$$type === 'FormData') {\r\n const formData = new FormData();\r\n for (const [key, value] of Object.entries(arg.data)) {\r\n if (Array.isArray(value)) {\r\n value.forEach(v => formData.append(key, v as string));\r\n } else {\r\n formData.append(key, value as string);\r\n }\r\n }\r\n return formData;\r\n }\r\n\r\n // Handle Date\r\n if (arg.$$type === 'Date') {\r\n return new Date(arg.value);\r\n }\r\n }\r\n\r\n return arg;\r\n });\r\n}\r\n\r\n/**\r\n * Generate a unique action ID\r\n */\r\nfunction generateActionId(): string {\r\n return Math.random().toString(36).substring(2, 10);\r\n}\r\n\r\n/**\r\n * Hook to get the current action context\r\n */\r\nexport function useActionContext(): ActionContext | null {\r\n return globalThis.__FLEXI_ACTION_CONTEXT__;\r\n}\r\n\r\n/**\r\n * Create a form action handler\r\n * Wraps a server action for use with HTML forms\r\n */\r\nexport function formAction<T>(\r\n action: (formData: FormData) => Promise<T>\r\n): (formData: FormData) => Promise<ActionResult<T>> {\r\n return async (formData: FormData) => {\r\n try {\r\n const result = await action(formData);\r\n return { success: true, data: result };\r\n } catch (error: any) {\r\n if (error instanceof RedirectError) {\r\n return { success: true, redirect: error.url };\r\n }\r\n return { success: false, error: error.message };\r\n }\r\n };\r\n}\r\n\r\n/**\r\n * Enhanced action state hook with FlexiReact context integration\r\n * Wraps React 19's useActionState with additional features\r\n * \r\n * @example\r\n * ```tsx\r\n * const [state, dispatch, isPending] = useFlexiAction(submitForm, { errors: [] });\r\n * ```\r\n */\r\nimport { useActionState as useActionStateReact } from 'react';\r\n\r\nexport function useFlexiAction<State, Payload>(\r\n action: (state: Awaited<State>, payload: Payload) => State | Promise<State>,\r\n initialState: Awaited<State>,\r\n permalink?: string\r\n): [state: Awaited<State>, dispatch: (payload: Payload) => void, isPending: boolean] {\r\n return useActionStateReact(action, initialState, permalink);\r\n}\r\n\r\n/**\r\n * @deprecated Since v3.1 - Use `useActionState` from React 19 instead.\r\n * This function will be removed in v4.0.\r\n * \r\n * Migration:\r\n * ```tsx\r\n * // Before (React 18)\r\n * const formState = createFormState(submitAction, null);\r\n * \r\n * // After (React 19)\r\n * const [state, formAction, isPending] = useActionState(submitAction, null);\r\n * ```\r\n */\r\nexport function createFormState<T>(\r\n action: (formData: FormData) => Promise<ActionResult<T>>,\r\n initialState: T | null = null\r\n) {\r\n if (typeof window !== 'undefined' && process.env.NODE_ENV === 'development') {\r\n console.warn(\r\n '[FlexiReact] createFormState is deprecated. Use useActionState from React 19 instead.\\n' +\r\n 'See migration guide: https://flexireact.dev/docs/react-19-migration'\r\n );\r\n }\r\n return {\r\n action,\r\n initialState,\r\n pending: false,\r\n error: null as string | null,\r\n data: initialState\r\n };\r\n}\r\n\r\n/**\r\n * Bind arguments to a server action\r\n * Creates a new action with pre-filled arguments\r\n */\r\nexport function bindArgs<T extends ServerActionFunction>(\r\n action: T,\r\n ...boundArgs: any[]\r\n): T {\r\n const boundAction = (async (...args: any[]) => {\r\n return await (action as any)(...boundArgs, ...args);\r\n }) as T;\r\n\r\n // Copy action metadata\r\n (boundAction as any).$$typeof = (action as any).$$typeof;\r\n (boundAction as any).$$id = (action as any).$$id;\r\n (boundAction as any).$$bound = boundArgs;\r\n\r\n return boundAction;\r\n}\r\n\r\nexport default {\r\n serverAction,\r\n registerAction,\r\n getAction,\r\n executeAction,\r\n callServerAction,\r\n deserializeArgs,\r\n useActionContext,\r\n formAction,\r\n createFormState, // deprecated\r\n useFlexiAction,\r\n bindArgs\r\n};\r\n","/**\r\n * FlexiReact Image Optimization\r\n * \r\n * Optimized image component with:\r\n * - Automatic WebP/AVIF conversion\r\n * - Responsive srcset generation\r\n * - Lazy loading with blur placeholder\r\n * - Priority loading for LCP images\r\n * - Automatic width/height to prevent CLS\r\n */\r\n\r\nimport React from 'react';\r\nimport path from 'path';\r\nimport fs from 'fs';\r\nimport crypto from 'crypto';\r\n\r\n// Image optimization config\r\nexport interface ImageConfig {\r\n domains: string[];\r\n deviceSizes: number[];\r\n imageSizes: number[];\r\n formats: ('webp' | 'avif' | 'png' | 'jpeg')[];\r\n minimumCacheTTL: number;\r\n dangerouslyAllowSVG: boolean;\r\n quality: number;\r\n cacheDir: string;\r\n}\r\n\r\nexport const defaultImageConfig: ImageConfig = {\r\n domains: [],\r\n deviceSizes: [640, 750, 828, 1080, 1200, 1920, 2048, 3840],\r\n imageSizes: [16, 32, 48, 64, 96, 128, 256, 384],\r\n formats: ['webp', 'avif'],\r\n minimumCacheTTL: 60 * 60 * 24 * 30, // 30 days\r\n dangerouslyAllowSVG: false,\r\n quality: 75,\r\n cacheDir: '.flexi/image-cache'\r\n};\r\n\r\n// Image props\r\nexport interface ImageProps {\r\n src: string;\r\n alt: string;\r\n width?: number;\r\n height?: number;\r\n fill?: boolean;\r\n sizes?: string;\r\n quality?: number;\r\n priority?: boolean;\r\n placeholder?: 'blur' | 'empty' | 'data:image/...';\r\n blurDataURL?: string;\r\n loading?: 'lazy' | 'eager';\r\n className?: string;\r\n style?: React.CSSProperties;\r\n onLoad?: () => void;\r\n onError?: () => void;\r\n unoptimized?: boolean;\r\n}\r\n\r\n// Generate blur placeholder\r\nexport async function generateBlurPlaceholder(imagePath: string): Promise<string> {\r\n try {\r\n // For now, return a simple SVG blur placeholder\r\n // In production, we'd use sharp to generate a tiny blurred version\r\n return `data:image/svg+xml;base64,${Buffer.from(\r\n `<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 8 5\">\r\n <filter id=\"b\" color-interpolation-filters=\"sRGB\">\r\n <feGaussianBlur stdDeviation=\"1\"/>\r\n </filter>\r\n <rect width=\"100%\" height=\"100%\" fill=\"#1a1a1a\"/>\r\n <rect width=\"100%\" height=\"100%\" filter=\"url(#b)\" opacity=\"0.5\" fill=\"#333\"/>\r\n </svg>`\r\n ).toString('base64')}`;\r\n } catch {\r\n return '';\r\n }\r\n}\r\n\r\n// Get image dimensions\r\nexport async function getImageDimensions(src: string): Promise<{ width: number; height: number } | null> {\r\n try {\r\n // For local files\r\n if (!src.startsWith('http')) {\r\n const imagePath = path.join(process.cwd(), 'public', src);\r\n if (fs.existsSync(imagePath)) {\r\n // Read first bytes to detect dimensions\r\n const buffer = fs.readFileSync(imagePath);\r\n return detectDimensions(buffer);\r\n }\r\n }\r\n return null;\r\n } catch {\r\n return null;\r\n }\r\n}\r\n\r\n// Detect image dimensions from buffer\r\nfunction detectDimensions(buffer: Buffer): { width: number; height: number } | null {\r\n // PNG\r\n if (buffer[0] === 0x89 && buffer[1] === 0x50) {\r\n return {\r\n width: buffer.readUInt32BE(16),\r\n height: buffer.readUInt32BE(20)\r\n };\r\n }\r\n \r\n // JPEG\r\n if (buffer[0] === 0xff && buffer[1] === 0xd8) {\r\n let offset = 2;\r\n while (offset < buffer.length) {\r\n if (buffer[offset] !== 0xff) break;\r\n const marker = buffer[offset + 1];\r\n if (marker === 0xc0 || marker === 0xc2) {\r\n return {\r\n height: buffer.readUInt16BE(offset + 5),\r\n width: buffer.readUInt16BE(offset + 7)\r\n };\r\n }\r\n offset += 2 + buffer.readUInt16BE(offset + 2);\r\n }\r\n }\r\n \r\n // GIF\r\n if (buffer[0] === 0x47 && buffer[1] === 0x49 && buffer[2] === 0x46) {\r\n return {\r\n width: buffer.readUInt16LE(6),\r\n height: buffer.readUInt16LE(8)\r\n };\r\n }\r\n \r\n // WebP\r\n if (buffer[0] === 0x52 && buffer[1] === 0x49 && buffer[8] === 0x57 && buffer[9] === 0x45) {\r\n // VP8\r\n if (buffer[12] === 0x56 && buffer[13] === 0x50 && buffer[14] === 0x38) {\r\n if (buffer[15] === 0x20) { // VP8\r\n return {\r\n width: buffer.readUInt16LE(26) & 0x3fff,\r\n height: buffer.readUInt16LE(28) & 0x3fff\r\n };\r\n }\r\n if (buffer[15] === 0x4c) { // VP8L\r\n const bits = buffer.readUInt32LE(21);\r\n return {\r\n width: (bits & 0x3fff) + 1,\r\n height: ((bits >> 14) & 0x3fff) + 1\r\n };\r\n }\r\n }\r\n }\r\n \r\n return null;\r\n}\r\n\r\n// Generate srcset for responsive images\r\nexport function generateSrcSet(\r\n src: string,\r\n widths: number[],\r\n quality: number = 75\r\n): string {\r\n return widths\r\n .map(w => `/_flexi/image?url=${encodeURIComponent(src)}&w=${w}&q=${quality} ${w}w`)\r\n .join(', ');\r\n}\r\n\r\n// Generate sizes attribute\r\nexport function generateSizes(sizes?: string): string {\r\n if (sizes) return sizes;\r\n return '100vw';\r\n}\r\n\r\n// Image optimization endpoint handler\r\nexport async function handleImageOptimization(\r\n req: any,\r\n res: any,\r\n config: Partial<ImageConfig> = {}\r\n): Promise<void> {\r\n const fullConfig = { ...defaultImageConfig, ...config };\r\n const url = new URL(req.url, `http://${req.headers.host}`);\r\n \r\n const imageUrl = url.searchParams.get('url');\r\n const width = parseInt(url.searchParams.get('w') || '0', 10);\r\n const quality = parseInt(url.searchParams.get('q') || String(fullConfig.quality), 10);\r\n const format = url.searchParams.get('f') as 'webp' | 'avif' | 'png' | 'jpeg' | null;\r\n \r\n if (!imageUrl) {\r\n res.writeHead(400, { 'Content-Type': 'text/plain' });\r\n res.end('Missing url parameter');\r\n return;\r\n }\r\n \r\n try {\r\n let imageBuffer: Buffer;\r\n let contentType: string;\r\n \r\n // Fetch image\r\n if (imageUrl.startsWith('http')) {\r\n // Remote image\r\n const response = await fetch(imageUrl);\r\n if (!response.ok) throw new Error('Failed to fetch image');\r\n imageBuffer = Buffer.from(await response.arrayBuffer());\r\n contentType = response.headers.get('content-type') || 'image/jpeg';\r\n } else {\r\n // Local image\r\n const imagePath = path.join(process.cwd(), 'public', imageUrl);\r\n if (!fs.existsSync(imagePath)) {\r\n res.writeHead(404, { 'Content-Type': 'text/plain' });\r\n res.end('Image not found');\r\n return;\r\n }\r\n imageBuffer = fs.readFileSync(imagePath);\r\n contentType = getContentType(imagePath);\r\n }\r\n \r\n // Generate cache key\r\n const cacheKey = crypto\r\n .createHash('md5')\r\n .update(`${imageUrl}-${width}-${quality}-${format}`)\r\n .digest('hex');\r\n \r\n const cacheDir = path.join(process.cwd(), fullConfig.cacheDir);\r\n const cachePath = path.join(cacheDir, `${cacheKey}.${format || 'webp'}`);\r\n \r\n // Check cache\r\n if (fs.existsSync(cachePath)) {\r\n const cachedImage = fs.readFileSync(cachePath);\r\n res.writeHead(200, {\r\n 'Content-Type': `image/${format || 'webp'}`,\r\n 'Cache-Control': `public, max-age=${fullConfig.minimumCacheTTL}`,\r\n 'X-Flexi-Image-Cache': 'HIT'\r\n });\r\n res.end(cachedImage);\r\n return;\r\n }\r\n \r\n // For now, serve original image\r\n // In production, we'd use sharp for resizing/conversion\r\n // TODO: Integrate sharp for actual optimization\r\n \r\n res.writeHead(200, {\r\n 'Content-Type': contentType,\r\n 'Cache-Control': `public, max-age=${fullConfig.minimumCacheTTL}`,\r\n 'X-Flexi-Image-Cache': 'MISS'\r\n });\r\n res.end(imageBuffer);\r\n \r\n } catch (error: any) {\r\n console.error('Image optimization error:', error);\r\n res.writeHead(500, { 'Content-Type': 'text/plain' });\r\n res.end('Image optimization failed');\r\n }\r\n}\r\n\r\n// Get content type from file extension\r\nfunction getContentType(filePath: string): string {\r\n const ext = path.extname(filePath).toLowerCase();\r\n const types: Record<string, string> = {\r\n '.jpg': 'image/jpeg',\r\n '.jpeg': 'image/jpeg',\r\n '.png': 'image/png',\r\n '.gif': 'image/gif',\r\n '.webp': 'image/webp',\r\n '.avif': 'image/avif',\r\n '.svg': 'image/svg+xml',\r\n '.ico': 'image/x-icon'\r\n };\r\n return types[ext] || 'application/octet-stream';\r\n}\r\n\r\n// Image component (server-side rendered)\r\nexport function createImageComponent(config: Partial<ImageConfig> = {}) {\r\n const fullConfig = { ...defaultImageConfig, ...config };\r\n \r\n return function Image(props: ImageProps): React.ReactElement {\r\n const {\r\n src,\r\n alt,\r\n width,\r\n height,\r\n fill = false,\r\n sizes,\r\n quality = fullConfig.quality,\r\n priority = false,\r\n placeholder = 'empty',\r\n blurDataURL,\r\n loading,\r\n className = '',\r\n style = {},\r\n unoptimized = false,\r\n ...rest\r\n } = props;\r\n \r\n // Determine loading strategy\r\n const loadingAttr = priority ? 'eager' : (loading || 'lazy');\r\n \r\n // Generate optimized src\r\n const optimizedSrc = unoptimized \r\n ? src \r\n : `/_flexi/image?url=${encodeURIComponent(src)}&w=${width || 1920}&q=${quality}`;\r\n \r\n // Generate srcset for responsive images\r\n const allSizes = [...fullConfig.imageSizes, ...fullConfig.deviceSizes].sort((a, b) => a - b);\r\n const relevantSizes = width \r\n ? allSizes.filter(s => s <= width * 2)\r\n : allSizes;\r\n \r\n const srcSet = unoptimized \r\n ? undefined \r\n : generateSrcSet(src, relevantSizes, quality);\r\n \r\n // Build styles\r\n const imgStyle: React.CSSProperties = {\r\n ...style,\r\n ...(fill ? {\r\n position: 'absolute',\r\n top: 0,\r\n left: 0,\r\n width: '100%',\r\n height: '100%',\r\n objectFit: 'cover'\r\n } : {})\r\n };\r\n \r\n // Placeholder styles\r\n const wrapperStyle: React.CSSProperties = fill ? {\r\n position: 'relative',\r\n width: '100%',\r\n height: '100%'\r\n } : {};\r\n \r\n const placeholderStyle: React.CSSProperties = placeholder === 'blur' ? {\r\n backgroundImage: `url(${blurDataURL || generateBlurPlaceholderSync()})`,\r\n backgroundSize: 'cover',\r\n backgroundPosition: 'center',\r\n filter: 'blur(20px)',\r\n transform: 'scale(1.1)'\r\n } : {};\r\n \r\n // Create image element\r\n const imgElement = React.createElement('img', {\r\n src: optimizedSrc,\r\n alt,\r\n width: fill ? undefined : width,\r\n height: fill ? undefined : height,\r\n loading: loadingAttr,\r\n decoding: 'async',\r\n srcSet,\r\n sizes: generateSizes(sizes),\r\n className: `flexi-image ${className}`.trim(),\r\n style: imgStyle,\r\n fetchPriority: priority ? 'high' : undefined,\r\n ...rest\r\n });\r\n \r\n // Wrap with placeholder if needed\r\n if (fill || placeholder === 'blur') {\r\n return React.createElement('div', {\r\n className: 'flexi-image-wrapper',\r\n style: { ...wrapperStyle, ...placeholderStyle }\r\n }, imgElement);\r\n }\r\n \r\n return imgElement;\r\n };\r\n}\r\n\r\n// Sync blur placeholder (for SSR)\r\nfunction generateBlurPlaceholderSync(): string {\r\n return `data:image/svg+xml;base64,${Buffer.from(\r\n `<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 8 5\">\r\n <filter id=\"b\" color-interpolation-filters=\"sRGB\">\r\n <feGaussianBlur stdDeviation=\"1\"/>\r\n </filter>\r\n <rect width=\"100%\" height=\"100%\" fill=\"#1a1a1a\"/>\r\n </svg>`\r\n ).toString('base64')}`;\r\n}\r\n\r\n// Default Image component\r\nexport const Image = createImageComponent();\r\n\r\n// Loader types for different image providers\r\nexport interface ImageLoader {\r\n (props: { src: string; width: number; quality?: number }): string;\r\n}\r\n\r\n// Built-in loaders\r\nexport const imageLoaders = {\r\n default: ({ src, width, quality = 75 }: { src: string; width: number; quality?: number }) =>\r\n `/_flexi/image?url=${encodeURIComponent(src)}&w=${width}&q=${quality}`,\r\n \r\n cloudinary: ({ src, width, quality = 75 }: { src: string; width: number; quality?: number }) =>\r\n `https://res.cloudinary.com/demo/image/fetch/w_${width},q_${quality}/${src}`,\r\n \r\n imgix: ({ src, width, quality = 75 }: { src: string; width: number; quality?: number }) =>\r\n `${src}?w=${width}&q=${quality}&auto=format`,\r\n \r\n vercel: ({ src, width, quality = 75 }: { src: string; width: number; quality?: number }) =>\r\n `/_vercel/image?url=${encodeURIComponent(src)}&w=${width}&q=${quality}`,\r\n \r\n cloudflare: ({ src, width, quality = 75 }: { src: string; width: number; quality?: number }) =>\r\n `/cdn-cgi/image/width=${width},quality=${quality}/${src}`\r\n};\r\n\r\nexport default {\r\n Image,\r\n createImageComponent,\r\n handleImageOptimization,\r\n generateBlurPlaceholder,\r\n getImageDimensions,\r\n generateSrcSet,\r\n imageLoaders,\r\n defaultImageConfig\r\n};\r\n","/**\r\n * FlexiReact Font Optimization\r\n * \r\n * Optimized font loading with:\r\n * - Automatic font subsetting\r\n * - Preload hints generation\r\n * - Font-display: swap by default\r\n * - Self-hosted Google Fonts\r\n * - Variable font support\r\n * - CSS variable generation\r\n */\r\n\r\nimport fs from 'fs';\r\nimport path from 'path';\r\nimport crypto from 'crypto';\r\n\r\n// Font configuration\r\nexport interface FontConfig {\r\n family: string;\r\n weight?: string | number | (string | number)[];\r\n style?: 'normal' | 'italic' | 'oblique';\r\n subsets?: string[];\r\n display?: 'auto' | 'block' | 'swap' | 'fallback' | 'optional';\r\n preload?: boolean;\r\n fallback?: string[];\r\n variable?: string;\r\n adjustFontFallback?: boolean;\r\n}\r\n\r\nexport interface FontResult {\r\n className: string;\r\n style: {\r\n fontFamily: string;\r\n fontWeight?: number | string;\r\n fontStyle?: string;\r\n };\r\n variable?: string;\r\n}\r\n\r\n// Google Fonts API\r\nconst GOOGLE_FONTS_API = 'https://fonts.googleapis.com/css2';\r\n\r\n// Popular Google Fonts with their weights\r\nexport const googleFonts = {\r\n Inter: {\r\n weights: [100, 200, 300, 400, 500, 600, 700, 800, 900],\r\n variable: true,\r\n subsets: ['latin', 'latin-ext', 'cyrillic', 'greek', 'vietnamese']\r\n },\r\n Roboto: {\r\n weights: [100, 300, 400, 500, 700, 900],\r\n variable: false,\r\n subsets: ['latin', 'latin-ext', 'cyrillic', 'greek', 'vietnamese']\r\n },\r\n 'Open Sans': {\r\n weights: [300, 400, 500, 600, 700, 800],\r\n variable: true,\r\n subsets: ['latin', 'latin-ext', 'cyrillic', 'greek', 'vietnamese']\r\n },\r\n Poppins: {\r\n weights: [100, 200, 300, 400, 500, 600, 700, 800, 900],\r\n variable: false,\r\n subsets: ['latin', 'latin-ext']\r\n },\r\n Montserrat: {\r\n weights: [100, 200, 300, 400, 500, 600, 700, 800, 900],\r\n variable: true,\r\n subsets: ['latin', 'latin-ext', 'cyrillic', 'vietnamese']\r\n },\r\n 'Fira Code': {\r\n weights: [300, 400, 500, 600, 700],\r\n variable: true,\r\n subsets: ['latin', 'latin-ext', 'cyrillic', 'greek']\r\n },\r\n 'JetBrains Mono': {\r\n weights: [100, 200, 300, 400, 500, 600, 700, 800],\r\n variable: true,\r\n subsets: ['latin', 'latin-ext', 'cyrillic', 'greek']\r\n },\r\n Geist: {\r\n weights: [100, 200, 300, 400, 500, 600, 700, 800, 900],\r\n variable: true,\r\n subsets: ['latin', 'latin-ext']\r\n },\r\n 'Geist Mono': {\r\n weights: [100, 200, 300, 400, 500, 600, 700, 800, 900],\r\n variable: true,\r\n subsets: ['latin', 'latin-ext']\r\n }\r\n};\r\n\r\n// Generate font CSS\r\nexport function generateFontCSS(config: FontConfig): string {\r\n const {\r\n family,\r\n weight = 400,\r\n style = 'normal',\r\n display = 'swap',\r\n fallback = ['system-ui', 'sans-serif'],\r\n variable\r\n } = config;\r\n\r\n const weights = Array.isArray(weight) ? weight : [weight];\r\n const fallbackStr = fallback.map(f => f.includes(' ') ? `\"${f}\"` : f).join(', ');\r\n\r\n let css = '';\r\n\r\n // Generate @font-face for each weight\r\n for (const w of weights) {\r\n css += `\r\n@font-face {\r\n font-family: '${family}';\r\n font-style: ${style};\r\n font-weight: ${w};\r\n font-display: ${display};\r\n src: local('${family}'),\r\n url('/_flexi/font/${encodeURIComponent(family)}?weight=${w}&style=${style}') format('woff2');\r\n}\r\n`;\r\n }\r\n\r\n // Generate CSS variable if specified\r\n if (variable) {\r\n css += `\r\n:root {\r\n ${variable}: '${family}', ${fallbackStr};\r\n}\r\n`;\r\n }\r\n\r\n return css;\r\n}\r\n\r\n// Generate preload link tags\r\nexport function generateFontPreloadTags(fonts: FontConfig[]): string {\r\n return fonts\r\n .filter(f => f.preload !== false)\r\n .map(f => {\r\n const weights = Array.isArray(f.weight) ? f.weight : [f.weight || 400];\r\n return weights.map(w => \r\n `<link rel=\"preload\" href=\"/_flexi/font/${encodeURIComponent(f.family)}?weight=${w}&style=${f.style || 'normal'}\" as=\"font\" type=\"font/woff2\" crossorigin>`\r\n ).join('\\n');\r\n })\r\n .join('\\n');\r\n}\r\n\r\n// Create a font loader function (like next/font)\r\nexport function createFont(config: FontConfig): FontResult {\r\n const {\r\n family,\r\n weight = 400,\r\n style = 'normal',\r\n fallback = ['system-ui', 'sans-serif'],\r\n variable\r\n } = config;\r\n\r\n // Generate unique class name\r\n const hash = crypto\r\n .createHash('md5')\r\n .update(`${family}-${weight}-${style}`)\r\n .digest('hex')\r\n .slice(0, 8);\r\n\r\n const className = `__font_${hash}`;\r\n const fallbackStr = fallback.map(f => f.includes(' ') ? `\"${f}\"` : f).join(', ');\r\n\r\n return {\r\n className,\r\n style: {\r\n fontFamily: `'${family}', ${fallbackStr}`,\r\n fontWeight: Array.isArray(weight) ? undefined : weight,\r\n fontStyle: style\r\n },\r\n variable: variable || undefined\r\n };\r\n}\r\n\r\n// Google Font loader\r\nexport function googleFont(config: FontConfig): FontResult {\r\n return createFont({\r\n ...config,\r\n // Google Fonts are always preloaded\r\n preload: true\r\n });\r\n}\r\n\r\n// Local font loader\r\nexport function localFont(config: FontConfig & { src: string | { path: string; weight?: string | number; style?: string }[] }): FontResult {\r\n return createFont(config);\r\n}\r\n\r\n// Handle font requests\r\nexport async function handleFontRequest(\r\n req: any,\r\n res: any\r\n): Promise<void> {\r\n const url = new URL(req.url, `http://${req.headers.host}`);\r\n const pathParts = url.pathname.split('/');\r\n const fontFamily = decodeURIComponent(pathParts[pathParts.length - 1] || '');\r\n const weight = url.searchParams.get('weight') || '400';\r\n const style = url.searchParams.get('style') || 'normal';\r\n\r\n if (!fontFamily) {\r\n res.writeHead(400, { 'Content-Type': 'text/plain' });\r\n res.end('Missing font family');\r\n return;\r\n }\r\n\r\n try {\r\n // Check local cache first\r\n const cacheDir = path.join(process.cwd(), '.flexi', 'font-cache');\r\n const cacheKey = crypto\r\n .createHash('md5')\r\n .update(`${fontFamily}-${weight}-${style}`)\r\n .digest('hex');\r\n const cachePath = path.join(cacheDir, `${cacheKey}.woff2`);\r\n\r\n if (fs.existsSync(cachePath)) {\r\n const fontData = fs.readFileSync(cachePath);\r\n res.writeHead(200, {\r\n 'Content-Type': 'font/woff2',\r\n 'Cache-Control': 'public, max-age=31536000, immutable',\r\n 'X-Flexi-Font-Cache': 'HIT'\r\n });\r\n res.end(fontData);\r\n return;\r\n }\r\n\r\n // Fetch from Google Fonts\r\n const googleUrl = `${GOOGLE_FONTS_API}?family=${encodeURIComponent(fontFamily)}:wght@${weight}&display=swap`;\r\n \r\n const cssResponse = await fetch(googleUrl, {\r\n headers: {\r\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'\r\n }\r\n });\r\n\r\n if (!cssResponse.ok) {\r\n throw new Error('Failed to fetch font CSS');\r\n }\r\n\r\n const css = await cssResponse.text();\r\n \r\n // Extract woff2 URL from CSS\r\n const woff2Match = css.match(/url\\((https:\\/\\/fonts\\.gstatic\\.com[^)]+\\.woff2)\\)/);\r\n \r\n if (!woff2Match) {\r\n throw new Error('Could not find woff2 URL');\r\n }\r\n\r\n // Fetch the actual font file\r\n const fontResponse = await fetch(woff2Match[1]);\r\n \r\n if (!fontResponse.ok) {\r\n throw new Error('Failed to fetch font file');\r\n }\r\n\r\n const fontBuffer = Buffer.from(await fontResponse.arrayBuffer());\r\n\r\n // Cache the font\r\n if (!fs.existsSync(cacheDir)) {\r\n fs.mkdirSync(cacheDir, { recursive: true });\r\n }\r\n fs.writeFileSync(cachePath, fontBuffer);\r\n\r\n // Serve the font\r\n res.writeHead(200, {\r\n 'Content-Type': 'font/woff2',\r\n 'Cache-Control': 'public, max-age=31536000, immutable',\r\n 'X-Flexi-Font-Cache': 'MISS'\r\n });\r\n res.end(fontBuffer);\r\n\r\n } catch (error: any) {\r\n console.error('Font loading error:', error);\r\n res.writeHead(500, { 'Content-Type': 'text/plain' });\r\n res.end('Font loading failed');\r\n }\r\n}\r\n\r\n// Pre-built font configurations\r\nexport const fonts = {\r\n // Sans-serif\r\n inter: (config: Partial<FontConfig> = {}) => googleFont({ family: 'Inter', variable: '--font-inter', ...config }),\r\n roboto: (config: Partial<FontConfig> = {}) => googleFont({ family: 'Roboto', variable: '--font-roboto', ...config }),\r\n openSans: (config: Partial<FontConfig> = {}) => googleFont({ family: 'Open Sans', variable: '--font-open-sans', ...config }),\r\n poppins: (config: Partial<FontConfig> = {}) => googleFont({ family: 'Poppins', variable: '--font-poppins', ...config }),\r\n montserrat: (config: Partial<FontConfig> = {}) => googleFont({ family: 'Montserrat', variable: '--font-montserrat', ...config }),\r\n geist: (config: Partial<FontConfig> = {}) => googleFont({ family: 'Geist', variable: '--font-geist', ...config }),\r\n \r\n // Monospace\r\n firaCode: (config: Partial<FontConfig> = {}) => googleFont({ family: 'Fira Code', variable: '--font-fira-code', fallback: ['monospace'], ...config }),\r\n jetbrainsMono: (config: Partial<FontConfig> = {}) => googleFont({ family: 'JetBrains Mono', variable: '--font-jetbrains', fallback: ['monospace'], ...config }),\r\n geistMono: (config: Partial<FontConfig> = {}) => googleFont({ family: 'Geist Mono', variable: '--font-geist-mono', fallback: ['monospace'], ...config })\r\n};\r\n\r\nexport default {\r\n createFont,\r\n googleFont,\r\n localFont,\r\n generateFontCSS,\r\n generateFontPreloadTags,\r\n handleFontRequest,\r\n fonts,\r\n googleFonts\r\n};\r\n","/**\r\n * Development server starter\r\n */\r\nimport { createServer } from './server/index.js';\r\n\r\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;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,sBAS/C,KAAK,UAAU,KAAK,CAAC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAY3C;AAKA,eAAe,UAAU,KAAK;AAC5B,SAAO,IAAI,QAAQ,CAAC,YAAY;AAC9B,UAAM,cAAc,IAAI,QAAQ,cAAc,KAAK;AACnD,QAAI,OAAO;AAEX,QAAI,GAAG,QAAQ,WAAS;AACtB,cAAQ,MAAM,SAAS;AAAA,IACzB,CAAC;AAED,QAAI,GAAG,OAAO,MAAM;AAClB,UAAI;AACF,YAAI,YAAY,SAAS,kBAAkB,KAAK,MAAM;AACpD,kBAAQ,KAAK,MAAM,IAAI,CAAC;AAAA,QAC1B,WAAW,YAAY,SAAS,mCAAmC,KAAK,MAAM;AAC5E,kBAAQ,OAAO,YAAY,IAAI,gBAAgB,IAAI,CAAC,CAAC;AAAA,QACvD,OAAO;AACL,kBAAQ,QAAQ,IAAI;AAAA,QACtB;AAAA,MACF,QAAQ;AACN,gBAAQ,IAAI;AAAA,MACd;AAAA,IACF,CAAC;AAED,QAAI,GAAG,SAAS,MAAM,QAAQ,IAAI,CAAC;AAAA,EACrC,CAAC;AACH;;;AcnwBA,aAAa,EAAE,MAAM,cAAc,CAAC;","names":["fs","path","pathToFileURL","fs","path","fs","fs","path","fs","isClientComponent","content","fs","path","pathToFileURL","cookies","path","fs","pathToFileURL","fs","path","pathToFileURL","React","renderToString","React","cookies","path","cookies","React","path","fs","path","fs","Image","React","fs","path","crypto","path","crypto","fs","__filename","__dirname","path","pathToFileURL","fs","isClientComponent"]}
|