@withl5e/l5e 0.3.0 → 0.3.2
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/dist/entry-server.js +3 -3
- package/dist/{generateMetadata-Cn2uJjg_.js → generateMetadata-DmoLxT6v.js} +2 -2
- package/dist/{generateMetadata-Cn2uJjg_.js.map → generateMetadata-DmoLxT6v.js.map} +1 -1
- package/dist/index.js +2 -2
- package/dist/island.js +1 -1
- package/dist/{jsx-runtime-Bokflh8Q.js → jsx-runtime-5m2ZiNtU.js} +92 -82
- package/dist/jsx-runtime-5m2ZiNtU.js.map +1 -0
- package/dist/jsx-runtime.js +1 -1
- package/dist/{render-DTXfJu0d.js → render-BaTAJ4Ha.js} +2 -2
- package/dist/{render-DTXfJu0d.js.map → render-BaTAJ4Ha.js.map} +1 -1
- package/dist/seo.js +2 -2
- package/dist/server.js +360 -367
- package/dist/server.js.map +1 -1
- package/package.json +1 -1
- package/src/core/bundler.ts +201 -205
- package/src/core/jsx-runtime.ts +23 -4
- package/src/core/server.ts +10 -3
- package/dist/jsx-runtime-Bokflh8Q.js.map +0 -1
package/dist/server.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.js","sources":["../src/core/bundler.ts","../src/core/server.ts"],"sourcesContent":["/// <reference path=\"./jsx-types.d.ts\" />\nimport { createHash } from 'node:crypto';\nimport fs from 'node:fs/promises';\nimport { createRequire } from 'node:module';\nimport path from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport type { OutputOptions, RollupOptions } from 'rollup';\n\nlet rollupModulePromise: Promise<typeof import('rollup')> | null = null;\n\n/**\n * Resolve rollup lazily. We can't `import 'rollup'` directly because when the\n * framework gets bundled into the consumer's SSR output the bare specifier is\n * hoisted to a static import that pnpm doesn't satisfy. Resolve through `vite`\n * instead — vite is a peer dep so it's always installed, and it always ships\n * rollup as a direct dependency.\n */\nfunction loadRollup(): Promise<typeof import('rollup')> {\n if (!rollupModulePromise) {\n rollupModulePromise = (async () => {\n const require = createRequire(import.meta.url);\n const vitePath = require.resolve('vite');\n const rollupPath = require.resolve('rollup', { paths: [path.dirname(vitePath)] });\n return (await import(pathToFileURL(rollupPath).href)) as typeof import('rollup');\n })();\n }\n return rollupModulePromise;\n}\n\ninterface BundledFile {\n content: string;\n hash: string;\n filename: string;\n mimeType: string;\n}\n\n// Memory map để lưu bundled files\nconst bundledFilesMap = new Map<string, BundledFile>();\n\n// Cache map để deduplicate bundling requests (cacheKey → entry chunk fileName)\nconst bundleCache = new Map<string, string>();\nconst cssCache = new Map<string, string>();\n\n/**\n * Generate hash từ content\n */\nfunction generateHash(content: string): string {\n return createHash('sha256').update(content).digest('hex').substring(0, 16);\n}\n\n/**\n * Bundle JavaScript files từ dist/client thành 1 file\n * Trong production, các file đã được build sẵn trong dist/client\n */\nexport async function bundleScripts(\n scriptPaths: string[],\n rootDir: string,\n distClientDir: string,\n): Promise<{ hash: string; filename: string; content: string }> {\n if (scriptPaths.length === 0) {\n return { hash: '', filename: '', content: '' };\n }\n\n // Dedupe paths (remove duplicates)\n const uniquePaths = [...new Set(scriptPaths)];\n\n // Tạo cache key từ sorted unique paths\n const cacheKey = `scripts:${uniquePaths.sort().join(',')}`;\n\n // Kiểm tra cache - return entry chunk info if already bundled\n const cachedEntryFileName = bundleCache.get(cacheKey);\n if (cachedEntryFileName) {\n const entryFile = bundledFilesMap.get(cachedEntryFileName);\n if (entryFile) {\n return {\n hash: entryFile.hash,\n filename: entryFile.filename,\n content: entryFile.content,\n };\n }\n }\n\n // Temp file path for cleanup\n let entryFile: string | null = null;\n\n try {\n // Sử dụng rollup để bundle nếu cần (resolve imports, etc)\n // Tạo temp entry file\n const hash = generateHash(uniquePaths.join('\\n'));\n const tempDir = path.join(rootDir, '.temp-bundle');\n await fs.mkdir(tempDir, { recursive: true }).catch(() => {});\n\n entryFile = path.join(tempDir, `entry-${hash}.js`);\n // Tạo entry file import tất cả scripts\n const entryContent = uniquePaths\n .map((p, i) => {\n const filePath = p.startsWith('/')\n ? path.join(distClientDir, p.substring(1))\n : path.join(distClientDir, p);\n return `import ${JSON.stringify(filePath)};`;\n })\n .join('\\n');\n\n await fs.writeFile(entryFile, entryContent, 'utf-8');\n console.log(`[bundler] Wrote entry file to ${entryFile}`);\n console.log(`[bundler] Entry content: ${entryContent}`);\n // Rollup config để bundle\n const rollupOptions: RollupOptions = {\n input: entryFile,\n plugins: [\n {\n name: 'vendor-path-rewriter',\n resolveId(source, importer, _options) {\n // Handle vendor/chunk/global files: convert absolute paths to web paths\n // Global files (*.global.*) are already loaded by client.global.ts —\n // re-bundling them would create duplicate module instances (e.g. nanostores)\n if (\n source.includes('vendor-') ||\n source.includes('chunk-') ||\n source.includes('.global')\n ) {\n console.log(`[bundler] Resolving source: ${source}`);\n if (path.isAbsolute(source)) {\n console.log(`[bundler] Resolving absolute path: ${source}`);\n // e.g., C:\\...\\dist\\client\\assets\\vendor-react-XXX.js -> /assets/vendor-react-XXX.js\n const relativePath = path.relative(distClientDir, source);\n const webPath = '/' + relativePath.replace(/\\\\/g, '/');\n return { id: webPath, external: true };\n } else if (importer && source.startsWith('.')) {\n console.log(\n `[bundler] Resolving relative path: ${source} from importer: ${importer}`,\n );\n // Relative path like ./auth.global-BOVr81Z5.js — resolve from importer\n const resolved = path.resolve(path.dirname(importer), source);\n const relativePath = path.relative(distClientDir, resolved);\n const webPath = '/' + relativePath.replace(/\\\\/g, '/');\n return { id: webPath, external: true };\n } else {\n console.log(`[bundler] Resolving source: ${source}`);\n }\n }\n return null; // Let other plugins/external handle\n },\n },\n ],\n external: (id) => {\n // External node_modules\n if (!id.startsWith('.') && !path.isAbsolute(id)) {\n return true;\n }\n\n // Let plugin handle vendor/chunk/global files (don't mark external here)\n if (id.includes('vendor-') || id.includes('chunk-') || id.includes('.global')) {\n return false; // Let plugin's resolveId handle path rewriting\n }\n\n return false;\n },\n };\n\n const outputOptions: OutputOptions = {\n format: 'es',\n inlineDynamicImports: false,\n entryFileNames: 'bundle-[hash].js',\n chunkFileNames: 'bundle-[hash].js',\n };\n\n const { rollup } = await loadRollup();\n const bundle = await rollup(rollupOptions);\n const { output } = await bundle.generate(outputOptions);\n await bundle.close();\n\n // Lấy bundled content từ rollup\n\n output.forEach((o) => {\n if (o.type !== 'chunk') {\n return;\n }\n // Lưu vào map với key = fileName\n const bundledFile: BundledFile = {\n content: o.code || '',\n hash: generateHash(o.code || ''),\n filename: o.fileName,\n mimeType: 'application/javascript',\n };\n bundledFilesMap.set(o.fileName, bundledFile);\n });\n\n // Cache entry chunk fileName for deduplication\n const entryChunk = output[0];\n if (entryChunk?.type === 'chunk') {\n bundleCache.set(cacheKey, entryChunk.fileName);\n }\n\n // Return entry chunk info\n return {\n hash: generateHash(output[0]?.code || ''),\n filename: output[0]?.fileName || '',\n content: output[0]?.code || '',\n };\n } catch (error) {\n console.error('[bundler] Error bundling scripts:', error);\n return { hash: '', filename: '', content: '' };\n } finally {\n // Cleanup temp entry file\n if (entryFile) {\n await fs.unlink(entryFile).catch(() => {\n // Ignore cleanup errors\n });\n }\n }\n}\n\n/**\n * Bundle CSS files từ dist/client thành 1 file\n * Trong production, các file đã được build sẵn trong dist/client\n */\nexport async function bundleCss(\n cssPaths: string[],\n rootDir: string,\n distClientDir: string,\n): Promise<{ hash: string; filename: string; content: string }> {\n if (cssPaths.length === 0) {\n return { hash: '', filename: '', content: '' };\n }\n\n // Dedupe paths (remove duplicates)\n const uniquePaths = [...new Set(cssPaths)];\n\n // Tạo cache key từ sorted unique paths\n const cacheKey = `css:${uniquePaths.sort().join(',')}`;\n\n // Kiểm tra cache - return cached file if already bundled\n const cachedFileName = cssCache.get(cacheKey);\n if (cachedFileName) {\n const cachedFile = bundledFilesMap.get(cachedFileName);\n if (cachedFile) {\n return {\n hash: cachedFile.hash,\n filename: cachedFile.filename,\n content: cachedFile.content,\n };\n }\n }\n\n try {\n // Đọc và gộp tất cả CSS files từ dist/client\n const cssContents: string[] = [];\n\n for (const cssPath of uniquePaths) {\n // cssPath có thể là \"/assets/xxx.css\" hoặc từ manifest\n const filePath = cssPath.startsWith('/')\n ? path.join(distClientDir, cssPath.substring(1))\n : path.join(distClientDir, cssPath);\n\n try {\n const content = await fs.readFile(filePath, 'utf-8');\n cssContents.push(`/* ${cssPath} */\\n${content}\\n`);\n } catch (err) {\n console.warn(`[bundler] Failed to read CSS file: ${cssPath}`, err);\n }\n }\n\n const bundledContent = cssContents.join('\\n\\n');\n const hash = generateHash(bundledContent);\n const filename = `bundle-${hash}.css`;\n\n // Lưu vào map với key = filename\n const bundledFile: BundledFile = {\n content: bundledContent,\n hash,\n filename,\n mimeType: 'text/css',\n };\n bundledFilesMap.set(filename, bundledFile);\n\n // Cache filename for deduplication\n cssCache.set(cacheKey, filename);\n\n return { hash, filename, content: bundledContent };\n } catch (error) {\n console.error('[bundler] Error bundling CSS:', error);\n return { hash: '', filename: '', content: '' };\n }\n}\n\n/**\n * Get bundled file từ map\n */\nexport function getBundledFile(filename: string): BundledFile | undefined {\n return bundledFilesMap.get(filename);\n}\n\n/**\n * Clear bundled files map (useful for testing)\n */\nexport function clearBundledFiles(): void {\n bundledFilesMap.clear();\n}\n","import type { Request as ExpressRequest, Response as ExpressResponse } from 'express';\nimport { existsSync } from 'fs';\nimport fs from 'node:fs/promises';\nimport path from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport requestIp from 'request-ip';\nimport serialize from 'serialize-javascript';\nimport type { ViteDevServer } from 'vite';\nimport { createContext, type MiddlewareHandler, type RewritePayload } from '../middleware';\nimport { bundleCss, bundleScripts, getBundledFile } from './bundler';\nimport type { RenderResult, RequestInfo } from './entry-server';\nimport { escapeProp } from './render';\nimport { createHeadersFromExpressRequest, parseCookies } from './request';\n\nexport interface ServerOptions {\n root?: string;\n port?: number;\n base?: string;\n publicDir?: string;\n setupApp?: (app: any) => void | Promise<void>;\n app?: any; // Express\n}\n\nexport interface ServerContext {\n app: any; // Express app\n vite?: ViteDevServer;\n}\n\n/**\n * Apply or replace lang attribute on <html> tag\n */\nexport function applyHtmlLang(template: string, lang: string): string {\n // Escape so a loader-supplied lang (possibly derived from user input) cannot\n // break out of the attribute / <html> tag (XSS). escapeProp handles \", <, >, &.\n const safeLang = escapeProp(lang);\n return template.replace(/<html\\b([^>]*)>/i, (match, attrs) => {\n // Check if lang already exists\n if (/\\blang\\s*=/i.test(attrs)) {\n // Replace existing lang value (function replacer avoids $-pattern issues)\n return match.replace(/lang\\s*=\\s*\"[^\"]*\"/i, () => `lang=\"${safeLang}\"`);\n } else {\n // Add lang attribute\n return `<html lang=\"${safeLang}\"${attrs}>`;\n }\n });\n}\n\ntype EntryServerModule = {\n render: (url: string, requestInfo?: RequestInfo) => Promise<RenderResult>;\n loadMiddleware?: () => Promise<MiddlewareHandler | undefined>;\n};\n\nfunction getRequestUrl(req: ExpressRequest): URL {\n return new URL(`${req.protocol}://${req.get('host')}${req.originalUrl}`);\n}\n\nfunction getRenderUrl(urlObject: URL, base: string): string {\n const requestPath = `${urlObject.pathname}${urlObject.search}`;\n return requestPath.replace(base, '') || '/';\n}\n\nfunction createWebRequestFromExpress(req: ExpressRequest): globalThis.Request {\n const init: RequestInit & { duplex?: 'half' } = {\n method: req.method,\n headers: createHeadersFromExpressRequest(req),\n };\n\n if (req.method !== 'GET' && req.method !== 'HEAD') {\n init.body = req as unknown as BodyInit;\n init.duplex = 'half';\n }\n\n return new globalThis.Request(getRequestUrl(req).href, init);\n}\n\nfunction createRequestInfo(\n req: ExpressRequest,\n webRequest: globalThis.Request,\n base: string,\n locals: Record<string, unknown>,\n): RequestInfo {\n const urlObject = new URL(webRequest.url);\n const renderUrl = getRenderUrl(urlObject, base);\n const normalizedPath = renderUrl.startsWith('/') ? renderUrl : `/${renderUrl}`;\n const headers: Record<string, string> = {};\n webRequest.headers.forEach((value, key) => {\n headers[key] = value;\n });\n\n return {\n url: urlObject,\n path: normalizedPath,\n pathname: urlObject.pathname,\n method: webRequest.method,\n headers,\n cookies: parseCookies(webRequest.headers.get('cookie') ?? undefined),\n query: Object.fromEntries(urlObject.searchParams.entries()),\n ip: requestIp.getClientIp(req) ?? undefined,\n locals,\n };\n}\n\nfunction createRewriteRequest(\n payload: RewritePayload | undefined,\n currentRequest: globalThis.Request,\n currentUrl: URL,\n): globalThis.Request {\n if (!payload) {\n return currentRequest;\n }\n\n if (payload instanceof globalThis.Request) {\n return payload;\n }\n\n if (payload instanceof URL) {\n return new globalThis.Request(payload.href, currentRequest.clone());\n }\n\n return new globalThis.Request(new URL(payload, currentUrl).href, currentRequest.clone());\n}\n\nasync function sendWebResponse(\n req: ExpressRequest,\n res: ExpressResponse,\n response: globalThis.Response,\n): Promise<void> {\n res.status(response.status);\n const setCookieValues = getSetCookieHeaders(response.headers);\n response.headers.forEach((value, key) => {\n if (key.toLowerCase() === 'set-cookie') {\n return;\n }\n res.setHeader(key, value);\n });\n if (setCookieValues.length > 0) {\n res.setHeader('Set-Cookie', setCookieValues);\n }\n\n if (req.method === 'HEAD') {\n res.end();\n return;\n }\n\n const body = Buffer.from(await response.arrayBuffer());\n res.send(body);\n}\n\nfunction getSetCookieHeaders(headers: Headers): string[] {\n const getSetCookie = (headers as Headers & { getSetCookie?: () => string[] }).getSetCookie;\n if (typeof getSetCookie === 'function') {\n return getSetCookie.call(headers);\n }\n\n const raw = (headers as Headers & { raw?: () => Record<string, string[]> }).raw?.();\n if (raw?.['set-cookie']) {\n return raw['set-cookie'];\n }\n\n const value = headers.get('set-cookie');\n return value ? splitSetCookieHeader(value) : [];\n}\n\nfunction splitSetCookieHeader(value: string): string[] {\n const cookies: string[] = [];\n let start = 0;\n\n for (let i = 0; i < value.length; i++) {\n if (value[i] !== ',') continue;\n\n const rest = value.slice(i + 1);\n if (/^\\s*[^=;,]+=/.test(rest)) {\n cookies.push(value.slice(start, i).trim());\n start = i + 1;\n }\n }\n\n cookies.push(value.slice(start).trim());\n return cookies.filter(Boolean);\n}\n\nfunction createRawResponse(rendered: RenderResult): globalThis.Response | null {\n if (!rendered.rawResponse) {\n return null;\n }\n\n const { body, contentType, statusCode, headers } = rendered.rawResponse;\n const responseHeaders = new Headers(headers);\n responseHeaders.set('Content-Type', contentType);\n\n return new globalThis.Response(body as BodyInit, {\n status: statusCode || 200,\n headers: responseHeaders,\n });\n}\n\nasync function createPageResponse({\n rendered,\n template,\n manifest,\n root,\n distClientDir,\n isProduction,\n}: {\n rendered: RenderResult;\n template: string;\n manifest?: Record<string, any>;\n root: string;\n distClientDir: string;\n isProduction: boolean;\n}): Promise<globalThis.Response> {\n const rawResponse = createRawResponse(rendered);\n if (rawResponse) {\n return rawResponse;\n }\n\n if (rendered.redirect) {\n return new globalThis.Response(null, {\n status: rendered.redirect.statusCode,\n headers: {\n Location: rendered.redirect.url,\n },\n });\n }\n\n let scriptSrcList: string[] = rendered.scripts || [];\n let cssSrcList: string[] = rendered.styles || [];\n const islandEntries = rendered.islands || [];\n let cacheTags: string[] = rendered.cacheTags || [];\n const maxAge: number | undefined = rendered.maxAge;\n const sMaxAge: number | undefined = rendered.sMaxAge;\n const swr: number | undefined = rendered.swr;\n\n let extraHead = '';\n let globalScripts: string[] = [];\n let islandRegistryScript = '';\n\n if (isProduction && manifest) {\n scriptSrcList = scriptSrcList.filter((src) => !src.includes('.global.'));\n cssSrcList = cssSrcList.filter((src) => !src.includes('.global.'));\n\n const cssFiles = new Set<string>();\n const preloadFiles = new Set<string>();\n\n function collectFromEntry(entryKey: string): { file: string | null } {\n const entry = manifest![entryKey];\n if (!entry) return { file: null };\n\n if (entry.css) entry.css.forEach((css: string) => cssFiles.add(css));\n if (entry.imports) {\n entry.imports.forEach((importKey: string) => {\n const importedChunk = manifest![importKey];\n if (importedChunk?.file) preloadFiles.add(importedChunk.file);\n if (importedChunk?.css) {\n importedChunk.css.forEach((css: string) => cssFiles.add(css));\n }\n if (importedChunk?.imports) {\n importedChunk.imports.forEach((key: string) => {\n const chunk = manifest![key];\n if (chunk?.file) preloadFiles.add(chunk.file);\n if (chunk?.css) chunk.css.forEach((css: string) => cssFiles.add(css));\n });\n }\n });\n }\n\n return { file: entry.file };\n }\n\n const mappedScripts: string[] = [];\n for (const src of scriptSrcList) {\n const entryKey = src.replace(/^\\//, '');\n const { file } = collectFromEntry(entryKey);\n if (file) mappedScripts.push(`/${file}`);\n }\n\n const mappedCssFiles: string[] = [];\n for (const src of cssSrcList) {\n const entryKey = src.replace(/^\\//, '');\n const { file } = collectFromEntry(entryKey);\n if (file) {\n mappedCssFiles.push(`/${file}`);\n cssFiles.add(file);\n }\n }\n\n if (mappedScripts.length > 0) {\n const bundledScript = await bundleScripts(mappedScripts, root, distClientDir);\n scriptSrcList = bundledScript.filename ? [`/${bundledScript.filename}`] : mappedScripts;\n }\n\n if (mappedCssFiles.length > 0) {\n const bundledCss = await bundleCss(mappedCssFiles, root, distClientDir);\n if (bundledCss.filename) {\n cssSrcList = [`/${bundledCss.filename}`];\n }\n }\n\n const globalEntry = manifest['src/client.global.ts'];\n if (globalEntry) {\n if (globalEntry.css && globalEntry.css.length > 0) {\n globalEntry.css.forEach((cssFile: string) => {\n extraHead += `<link rel=\"stylesheet\" crossorigin href=\"/${cssFile}\">`;\n });\n }\n if (globalEntry.file) {\n globalScripts.push(`/${globalEntry.file}`);\n }\n }\n\n if (islandEntries.length > 0) {\n const islandMap: Record<string, string> = {};\n for (const island of islandEntries) {\n const entry = manifest[island.src];\n if (entry?.file) {\n islandMap[island.key] = `/${entry.file}`;\n }\n }\n if (Object.keys(islandMap).length > 0) {\n islandRegistryScript = `<script>window.__L5E_ISLANDS__=${serialize(islandMap)}</script>`;\n }\n }\n\n if (cssSrcList.length > 0) {\n extraHead += cssSrcList\n .map((file) => `<link rel=\"stylesheet\" crossorigin href=\"${file}\">`)\n .join('');\n }\n }\n\n let cssHtml = '';\n if (!isProduction) {\n cssHtml = cssSrcList.map((src) => `<link rel=\"stylesheet\" href=\"${src}\">`).join('');\n }\n\n let allScripts = [...globalScripts, ...scriptSrcList];\n\n if (!isProduction) {\n const globalTsPath = path.join(root, 'src', 'client.global.ts');\n if (existsSync(globalTsPath)) {\n allScripts = ['/src/client.global.ts', ...allScripts];\n }\n\n if (islandEntries.length > 0) {\n const islandMap: Record<string, string> = {};\n for (const island of islandEntries) {\n islandMap[island.key] = `/${island.src}`;\n }\n islandRegistryScript = `<script>window.__L5E_ISLANDS__=${serialize(islandMap)}</script>`;\n }\n }\n\n const scriptsHtml =\n islandRegistryScript +\n allScripts.map((src) => `<script type=\"module\" src=\"${src}\"></script>`).join('');\n\n const templateWithLang = rendered.lang ? applyHtmlLang(template, rendered.lang) : template;\n\n // Replacer fns (not strings) so `$`-sequences in rendered HTML — e.g. an SSR\n // island body or user text containing \"$$\" / \"$&\" — aren't interpreted as\n // special String.replace replacement patterns.\n const html = rendered.rawHtml\n ? rendered.html || ''\n : templateWithLang\n .replace(`<!--app-head-->`, () => (rendered.head ?? '') + extraHead + cssHtml)\n .replace(`<!--app-html-->`, () => rendered.html ?? '')\n .replace(`<!--app-scripts-->`, () => scriptsHtml);\n\n const headers = new Headers({\n 'Content-Type': 'text/html',\n });\n\n const cacheControlParts: string[] = ['public'];\n if (maxAge !== undefined) cacheControlParts.push(`max-age=${maxAge}`);\n if (sMaxAge !== undefined) cacheControlParts.push(`s-maxage=${sMaxAge}`);\n if (swr !== undefined) cacheControlParts.push(`stale-while-revalidate=${swr}`);\n\n if (cacheControlParts.length > 1 && isProduction) {\n headers.set('Cache-Control', cacheControlParts.join(', '));\n }\n\n if (process.env.NODE_ENV === 'production') {\n cacheTags = optimizeCacheTags(cacheTags);\n }\n headers.set('Cache-Tag', ['global', ...cacheTags].join(','));\n\n return new globalThis.Response(html, {\n status: rendered.statusCode || 200,\n headers,\n });\n}\n\nexport async function createServer(options: ServerOptions = {}): Promise<ServerContext> {\n const root = options.root || process.cwd();\n const base = options.base || '/';\n const isProduction = process.env.NODE_ENV === 'production';\n\n // Cached production assets\n const templateHtml = isProduction\n ? await fs.readFile(path.join(root, './index.html'), 'utf-8')\n : '';\n\n // Create http server\n // @ts-ignore\n const express = (await import('express')).default;\n const app = options.app || express();\n\n // Serve static files from public directory\n if (options.publicDir) {\n const publicPath = path.isAbsolute(options.publicDir)\n ? options.publicDir\n : path.join(root, options.publicDir);\n\n if (existsSync(publicPath)) {\n app.use(express.static(publicPath));\n }\n }\n\n // Add Vite or respective production middlewares\n let vite: ViteDevServer | undefined;\n const distClientDir = path.join(root, './dist/client');\n\n if (!isProduction) {\n const { createServer } = await import('vite');\n const configFile = path.join(root, 'vite.config.js');\n vite = await createServer({\n root,\n configFile,\n server: { middlewareMode: true },\n appType: 'custom',\n base,\n optimizeDeps: {\n exclude: ['@withl5e/l5e', 'file-type'],\n },\n ssr: {\n resolve: {\n conditions: ['development', 'default'],\n },\n },\n resolve: {\n conditions: ['development', 'default'],\n },\n });\n app.use(vite.middlewares);\n } else {\n // @ts-ignore\n const compression = (await import('compression')).default;\n // @ts-ignore\n const sirv = (await import('sirv')).default;\n app.use(compression());\n app.use(base, sirv(distClientDir, { extensions: [] }));\n\n // Route để serve bundled files từ memory map\n // Äặt route nà y trước route HTML để catch request trước\n app.get(\n `${base === '/' ? '' : base}/bundle-:hash.:ext`,\n async (req: ExpressRequest, res: ExpressResponse) => {\n try {\n const { hash, ext } = req.params;\n const filename = `bundle-${hash}.${ext}`;\n const bundledFile = getBundledFile(filename);\n\n if (!bundledFile) {\n return res.status(404).send('Bundled file not found');\n }\n\n res.set({\n 'Content-Type': bundledFile.mimeType,\n 'Cache-Control': 'public, max-age=31536000, immutable',\n });\n res.send(bundledFile.content);\n } catch (e: any) {\n console.error('[server] Error serving bundled file:', e);\n res.status(500).end('Internal server error');\n }\n },\n );\n }\n\n // Action routes — JSON body parsing scoped to action endpoints only\n app.use('/_l5e/action', express.json({ limit: '100kb' }));\n\n // Validate action key format: actionName_hexHash\n const ACTION_KEY_RE = /^[a-zA-Z]\\w+_[0-9a-f]{1,4}$/;\n\n // Load action registry and viewActions glob from virtual module (dev) or built bundle (prod)\n let prodActionRegistry: Record<string, { modulePath: string; actionName: string }> | null = null;\n let prodViewActions: Record<string, () => Promise<any>> | null = null;\n\n async function getActionRegistry(): Promise<\n Record<string, { modulePath: string; actionName: string }>\n > {\n if (!isProduction) {\n const mod = await vite!.ssrLoadModule('virtual:l5e-actions');\n return mod.actionRegistry || {};\n }\n if (!prodActionRegistry) {\n const registryPath = path.join(root, './dist/server/action-registry.json');\n const json = await fs.readFile(registryPath, 'utf-8');\n prodActionRegistry = JSON.parse(json);\n }\n return prodActionRegistry!;\n }\n\n async function getViewActions(): Promise<Record<string, () => Promise<any>>> {\n if (!isProduction) {\n const mod = await vite!.ssrLoadModule('virtual:l5e-actions');\n return mod.viewActions || {};\n }\n if (!prodViewActions) {\n const entryServerPath = path.join(root, './dist/server/entry-server.js');\n const mod = await import(pathToFileURL(entryServerPath).href);\n prodViewActions = mod.viewActions || {};\n }\n return prodViewActions!;\n }\n\n // Action route handler — hashed action keys\n // URL: /_l5e/action/:actionKey (e.g., /_l5e/action/loadMoreComments_a1b2)\n app.all('/_l5e/action/:actionKey', async (req: ExpressRequest, res: ExpressResponse) => {\n try {\n const { actionKey } = req.params;\n\n // Validate action key format\n if (!ACTION_KEY_RE.test(actionKey)) {\n return res.status(400).send('Invalid action key');\n }\n\n // Look up action in registry\n const registry = await getActionRegistry();\n const entry = registry[actionKey];\n if (!entry) {\n return res.status(404).send('Action not found');\n }\n\n const { modulePath, actionName } = entry;\n\n // Import action module via viewActions glob (works in both dev and prod)\n let actionModule: any;\n if (!isProduction) {\n try {\n actionModule = await vite!.ssrLoadModule(`/src/${modulePath}/actions.tsx`);\n } catch {\n actionModule = await vite!.ssrLoadModule(`/src/${modulePath}/actions.ts`);\n }\n } else {\n const viewActions = await getViewActions();\n // Find matching glob entry by modulePath\n const globKey = viewActions[`/src/${modulePath}/actions.tsx`]\n ? `/src/${modulePath}/actions.tsx`\n : viewActions[`/src/${modulePath}/actions.ts`]\n ? `/src/${modulePath}/actions.ts`\n : null;\n if (!globKey) {\n return res.status(404).send('Action module not found');\n }\n actionModule = await viewActions[globKey]();\n }\n\n // Look up exported action — use hasOwnProperty to avoid prototype pollution\n if (!Object.prototype.hasOwnProperty.call(actionModule, actionName)) {\n return res.status(404).send('Action not found');\n }\n const action = actionModule[actionName];\n if (!action || !action.handler) {\n return res.status(404).send('Action not found');\n }\n\n // Enforce the action's declared HTTP method. Previously `app.all` accepted\n // any method and `action.method` was ignored, so a state-changing POST\n // action could be triggered via GET (e.g. <img src>) — a CSRF vector.\n const allowedMethod = (action.method || 'GET').toUpperCase();\n if (req.method.toUpperCase() !== allowedMethod) {\n return res.status(405).set('Allow', allowedMethod).send('Method Not Allowed');\n }\n\n // Run the request through the middleware chain first — same as the HTML\n // handler — so `locals` (locale, country, preview flags, ...) is\n // populated for actions too. Previously this endpoint built its own\n // bare `requestInfo` and never invoked middleware at all, so `locals`\n // (and thus `getLocale()`) was always empty inside an action handler.\n //\n // Crucially, the action must run *inside* the `next` callback passed to\n // the middleware — not after `await`ing the middleware call — because a\n // middleware like `fromFetchMiddleware(paraglideMiddleware)` calls\n // `next()` synchronously inside a library-owned `AsyncLocalStorage.run()`\n // scope. Running the action afterward, once that scope has already\n // closed, would silently lose the library's own ambient `getLocale()`.\n const entryServerPath = path.join(root, './dist/server/entry-server.js');\n const entryServerModule: EntryServerModule = isProduction\n ? await import(pathToFileURL(entryServerPath).href)\n : await vite!.ssrLoadModule('@withl5e/l5e/entry-server');\n const { runInRenderContext } = await (isProduction\n ? import(pathToFileURL(entryServerPath).href)\n : vite!.ssrLoadModule('@withl5e/l5e/jsx-runtime'));\n const { renderJsxToHtmlString } = await (isProduction\n ? import(pathToFileURL(entryServerPath).href)\n : vite!.ssrLoadModule('@withl5e/l5e'));\n\n const locals: Record<string, unknown> = {};\n const initialRequest = createWebRequestFromExpress(req);\n const middlewareContext = createContext({\n request: initialRequest,\n locals,\n clientAddress: requestIp.getClientIp(req) ?? undefined,\n });\n\n const loadedMiddleware = await entryServerModule.loadMiddleware?.();\n const middlewareHandler: MiddlewareHandler =\n typeof loadedMiddleware === 'function' ? loadedMiddleware : (_ctx, dummyNext) => dummyNext();\n\n // If middleware short-circuits (returns its own Response — a redirect, a\n // 403, ...) instead of calling `next`, this callback never runs and that\n // response wins, same as it would for a page request.\n const response = await middlewareHandler(middlewareContext, async (payload) => {\n const nextRequest = createRewriteRequest(payload, middlewareContext.request, middlewareContext.url);\n const requestInfo = {\n ...createRequestInfo(req, nextRequest, base, locals),\n path: req.originalUrl,\n body: req.body,\n };\n\n const html = await runInRenderContext(\n async () => {\n const jsx = await action.handler(requestInfo);\n return renderJsxToHtmlString(jsx);\n },\n requestInfo,\n modulePath,\n );\n\n return new Response(html, { headers: { 'Content-Type': 'text/html' } });\n });\n\n await sendWebResponse(req, res, response);\n } catch (e: any) {\n vite?.ssrFixStacktrace?.(e);\n console.error('[l5e] Action error:', e.stack || e);\n res.status(500).send('Internal server error');\n }\n });\n\n // Serve HTML\n app.use(async (req: ExpressRequest, res: ExpressResponse) => {\n try {\n const url = req.originalUrl.replace(base, '');\n\n let template: string;\n let render: (url: string, requestInfo?: any) => Promise<any>;\n let loadMiddleware: EntryServerModule['loadMiddleware'];\n let manifest: Record<string, any> | undefined;\n\n if (!isProduction) {\n // Always read fresh template in development\n template = await fs.readFile(path.join(root, './index.html'), 'utf-8');\n template = await vite!.transformIndexHtml(url, template);\n\n // Inject Vite HMR client for hot reload\n if (!template.includes('@vite/client')) {\n template = template.replace(\n '</head>',\n '<script type=\"module\" src=\"/@vite/client\"></script></head>',\n );\n }\n\n const entryServer = (await vite!.ssrLoadModule(\n '@withl5e/l5e/entry-server',\n )) as EntryServerModule;\n render = entryServer.render;\n loadMiddleware = entryServer.loadMiddleware;\n } else {\n template = templateHtml;\n const entryServerPath = path.join(root, './dist/server/entry-server.js');\n const entryServer = (await import(\n pathToFileURL(entryServerPath).href\n )) as EntryServerModule;\n render = entryServer.render;\n loadMiddleware = entryServer.loadMiddleware;\n // Read manifest to map hashed assets\n const manifestJson = await fs.readFile(\n path.join(root, './dist/client/.vite/manifest.json'),\n 'utf-8',\n );\n manifest = JSON.parse(manifestJson);\n }\n\n const loadedMiddleware = await loadMiddleware?.();\n const handler: MiddlewareHandler =\n typeof loadedMiddleware === 'function' ? loadedMiddleware : (_ctx, next) => next();\n\n const locals: Record<string, unknown> = {};\n const initialRequest = createWebRequestFromExpress(req);\n const context = createContext({\n request: initialRequest,\n requestInfo: createRequestInfo(req, initialRequest, base, locals),\n locals,\n clientAddress: requestIp.getClientIp(req),\n });\n\n const renderResponse = async (webRequest: globalThis.Request) => {\n const nextRequestInfo = createRequestInfo(req, webRequest, base, locals);\n const nextUrl = getRenderUrl(nextRequestInfo.url!, base);\n const nextRendered = await render(nextUrl, nextRequestInfo);\n return createPageResponse({\n rendered: nextRendered,\n template,\n manifest,\n root,\n distClientDir,\n isProduction,\n });\n };\n\n const next = async (payload?: RewritePayload) => {\n const nextRequest = createRewriteRequest(payload, context.request, context.url);\n context.request = nextRequest;\n context.url = new URL(nextRequest.url);\n context.cookies = parseCookies(nextRequest.headers.get('cookie') ?? undefined);\n context.requestInfo = createRequestInfo(req, nextRequest, base, locals);\n return renderResponse(nextRequest);\n };\n\n context.rewrite = (payload: RewritePayload) => next(payload);\n\n const response = await handler(context, next);\n await sendWebResponse(req, res, response);\n } catch (e: any) {\n vite?.ssrFixStacktrace?.(e);\n console.error(e.stack);\n // Never leak stack traces to the client in production (info disclosure).\n res.status(500).end(isProduction ? 'Internal Server Error' : e.stack);\n }\n });\n\n return { app, vite };\n}\n\nexport async function startServer(options: ServerOptions = {}): Promise<void> {\n const port = options.port || 5173;\n\n // Create Express app first\n // @ts-ignore\n const express = (await import('express')).default;\n const app = express();\n\n // Call callback if provided to allow custom routes before setting up L5E server\n if (options.setupApp) {\n console.log('setupApp');\n await options.setupApp(app);\n }\n\n const { app: serverApp } = await createServer({ ...options, app });\n\n serverApp.listen(port, () => {\n console.log(`Server started at http://localhost:${port}`);\n });\n}\n\nconst MAX_TAGS = 1000;\n\nexport function hashTag(tag: string): string {\n // global tag is not hashed, better for ci/cd\n if (tag === 'global') {\n return 'global';\n }\n\n let hash = 0;\n for (let i = 0; i < tag.length; i++) {\n const char = tag.charCodeAt(i);\n hash = (hash << 5) - hash + char;\n hash = hash & hash; // Convert to 32bit integer\n }\n return Math.abs(hash).toString(36).substring(0, 8);\n}\n\nexport function optimizeCacheTags(tags: Set<string> | string[]): string[] {\n const _tags = Array.isArray(tags) ? tags : [...tags];\n const result = _tags.slice(0, MAX_TAGS).map(hashTag);\n return result;\n}\n"],"names":["rollupModulePromise","loadRollup","require","createRequire","vitePath","rollupPath","path","pathToFileURL","bundledFilesMap","bundleCache","cssCache","generateHash","content","createHash","bundleScripts","scriptPaths","rootDir","distClientDir","uniquePaths","cacheKey","cachedEntryFileName","entryFile","hash","tempDir","fs","entryContent","p","i","filePath","rollupOptions","source","importer","_options","resolved","id","outputOptions","rollup","bundle","output","bundledFile","entryChunk","error","bundleCss","cssPaths","cachedFileName","cachedFile","cssContents","cssPath","err","bundledContent","filename","getBundledFile","applyHtmlLang","template","lang","safeLang","escapeProp","match","attrs","getRequestUrl","req","getRenderUrl","urlObject","base","createWebRequestFromExpress","init","createHeadersFromExpressRequest","createRequestInfo","webRequest","locals","renderUrl","normalizedPath","headers","value","key","parseCookies","requestIp","createRewriteRequest","payload","currentRequest","currentUrl","sendWebResponse","res","response","setCookieValues","getSetCookieHeaders","body","getSetCookie","raw","splitSetCookieHeader","cookies","start","rest","createRawResponse","rendered","contentType","statusCode","responseHeaders","createPageResponse","manifest","root","isProduction","rawResponse","scriptSrcList","cssSrcList","islandEntries","cacheTags","maxAge","sMaxAge","swr","extraHead","globalScripts","islandRegistryScript","collectFromEntry","entryKey","entry","css","cssFiles","importKey","importedChunk","preloadFiles","chunk","src","mappedScripts","file","mappedCssFiles","bundledScript","bundledCss","globalEntry","cssFile","islandMap","island","serialize","cssHtml","allScripts","globalTsPath","existsSync","scriptsHtml","templateWithLang","html","cacheControlParts","optimizeCacheTags","createServer","options","templateHtml","express","app","publicPath","vite","compression","sirv","ext","e","configFile","ACTION_KEY_RE","prodActionRegistry","prodViewActions","getActionRegistry","registryPath","json","getViewActions","entryServerPath","actionKey","modulePath","actionName","actionModule","viewActions","globKey","action","allowedMethod","entryServerModule","runInRenderContext","renderJsxToHtmlString","initialRequest","middlewareContext","createContext","loadedMiddleware","_ctx","dummyNext","nextRequest","requestInfo","jsx","url","render","loadMiddleware","entryServer","manifestJson","handler","next","context","renderResponse","nextRequestInfo","nextUrl","nextRendered","startServer","port","serverApp","MAX_TAGS","hashTag","tag","char","tags"],"mappings":";;;;;;;;;AAQA,IAAIA,IAA+D;AASnE,SAASC,KAA+C;AACtD,SAAKD,MACHA,KAAuB,YAAY;AACjC,UAAME,IAAUC,GAAc,YAAY,GAAG,GACvCC,IAAWF,EAAQ,QAAQ,MAAM,GACjCG,IAAaH,EAAQ,QAAQ,UAAU,EAAE,OAAO,CAACI,EAAK,QAAQF,CAAQ,CAAC,EAAA,CAAG;AAChF,WAAQ,MAAM,OAAOG,EAAcF,CAAU,EAAE;AAAA,EACjD,GAAA,IAEKL;AACT;AAUA,MAAMQ,wBAAsB,IAAA,GAGtBC,wBAAkB,IAAA,GAClBC,wBAAe,IAAA;AAKrB,SAASC,EAAaC,GAAyB;AAC7C,SAAOC,GAAW,QAAQ,EAAE,OAAOD,CAAO,EAAE,OAAO,KAAK,EAAE,UAAU,GAAG,EAAE;AAC3E;AAMA,eAAsBE,GACpBC,GACAC,GACAC,GAC8D;AAC9D,MAAIF,EAAY,WAAW;AACzB,WAAO,EAAE,MAAM,IAAI,UAAU,IAAI,SAAS,GAAA;AAI5C,QAAMG,IAAc,CAAC,GAAG,IAAI,IAAIH,CAAW,CAAC,GAGtCI,IAAW,WAAWD,EAAY,OAAO,KAAK,GAAG,CAAC,IAGlDE,IAAsBX,EAAY,IAAIU,CAAQ;AACpD,MAAIC,GAAqB;AACvB,UAAMC,IAAYb,EAAgB,IAAIY,CAAmB;AACzD,Q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IAAyB,IAAmB;AAC5E,QAAMoD,IAAOpD,EAAQ,QAAQ,MAIvBE,KAAW,MAAM,OAAO,SAAS,GAAG,SACpCC,IAAMD,EAAA;AAGZ,EAAIF,EAAQ,aACV,QAAQ,IAAI,UAAU,GACtB,MAAMA,EAAQ,SAASG,CAAG;AAG5B,QAAM,EAAE,KAAKkD,MAAc,MAAMtD,GAAa,EAAE,GAAGC,GAAS,KAAAG,GAAK;AAEjE,EAAAkD,EAAU,OAAOD,GAAM,MAAM;AAC3B,YAAQ,IAAI,sCAAsCA,CAAI,EAAE;AAAA,EAC1D,CAAC;AACH;AAEA,MAAME,KAAW;AAEV,SAASC,GAAQC,GAAqB;AAE3C,MAAIA,MAAQ;AACV,WAAO;AAGT,MAAIjL,IAAO;AACX,WAASK,IAAI,GAAGA,IAAI4K,EAAI,QAAQ5K,KAAK;AACnC,UAAM6K,IAAOD,EAAI,WAAW5K,CAAC;AAC7B,IAAAL,KAAQA,KAAQ,KAAKA,IAAOkL,GAC5BlL,IAAOA,IAAOA;AAAA,EAChB;AACA,SAAO,KAAK,IAAIA,CAAI,EAAE,SAAS,EAAE,EAAE,UAAU,GAAG,CAAC;AACnD;AAEO,SAASuH,GAAkB4D,GAAwC;AAGxE,UAFc,MAAM,QAAQA,CAAI,IAAIA,IAAO,CAAC,GAAGA,CAAI,GAC9B,MAAM,GAAGJ,EAAQ,EAAE,IAAIC,EAAO;AAErD;"}
|
|
1
|
+
{"version":3,"file":"server.js","sources":["../src/core/bundler.ts","../src/core/server.ts"],"sourcesContent":["/// <reference path=\"./jsx-types.d.ts\" />\nimport { createHash } from 'node:crypto';\nimport fs from 'node:fs/promises';\nimport { createRequire } from 'node:module';\nimport path from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport type { OutputOptions, Plugin, RollupOptions } from 'rollup';\n\nlet rollupModulePromise: Promise<typeof import('rollup')> | null = null;\n\n/**\n * Resolve rollup lazily. We can't `import 'rollup'` directly because when the\n * framework gets bundled into the consumer's SSR output the bare specifier is\n * hoisted to a static import that pnpm doesn't satisfy. Resolve through `vite`\n * instead — vite is a peer dep so it's always installed, and it always ships\n * rollup as a direct dependency.\n */\nfunction loadRollup(): Promise<typeof import('rollup')> {\n if (!rollupModulePromise) {\n rollupModulePromise = (async () => {\n const require = createRequire(import.meta.url);\n const vitePath = require.resolve('vite');\n const rollupPath = require.resolve('rollup', { paths: [path.dirname(vitePath)] });\n return (await import(pathToFileURL(rollupPath).href)) as typeof import('rollup');\n })();\n }\n return rollupModulePromise;\n}\n\ninterface BundledFile {\n content: string;\n hash: string;\n filename: string;\n mimeType: string;\n}\n\ninterface BundleResult {\n hash: string;\n filename: string;\n content: string;\n}\n\nconst EMPTY_RESULT: BundleResult = { hash: '', filename: '', content: '' };\n\n// Memory map để lưu bundled files\nconst bundledFilesMap = new Map<string, BundledFile>();\n\n/**\n * Single-flight map: cacheKey → promise của lần bundle đang chạy (hoặc đã xong).\n * Vì promise được giữ lại sau khi resolve, map này vừa là in-flight dedup vừa là\n * result cache. Bundle lỗi bị xoá khỏi map để request sau được thử lại.\n */\nconst bundlePromises = new Map<string, Promise<BundleResult>>();\n\n/**\n * Chạy `work` đúng một lần cho mỗi cacheKey, kể cả khi nhiều request đến đồng thời.\n */\nfunction dedupe(cacheKey: string, work: () => Promise<BundleResult>): Promise<BundleResult> {\n const pending = bundlePromises.get(cacheKey);\n if (pending) {\n return pending;\n }\n\n const promise = work().catch((error) => {\n bundlePromises.delete(cacheKey);\n throw error;\n });\n bundlePromises.set(cacheKey, promise);\n return promise;\n}\n\n/**\n * Generate hash từ content\n */\nfunction generateHash(content: string): string {\n return createHash('sha256').update(content).digest('hex').substring(0, 16);\n}\n\n// Rollup coi id bắt đầu bằng \\0 là virtual — nó sẽ không cố đọc từ đĩa.\nconst VIRTUAL_ENTRY_ID = '\\0l5e:bundle-entry';\n\n/**\n * Entry của mỗi lần bundle chỉ là một danh sách import. Giữ nó trong memory thay\n * vì ghi ra đĩa: hai request đồng thời cùng một tập script sinh ra cùng nội dung\n * entry, nên file tạm dùng chung path sẽ bị request này xoá trong lúc rollup của\n * request kia còn đang đọc.\n */\nfunction virtualEntryPlugin(entryContent: string): Plugin {\n return {\n name: 'l5e-virtual-entry',\n resolveId(source) {\n return source === VIRTUAL_ENTRY_ID ? VIRTUAL_ENTRY_ID : null;\n },\n load(id) {\n return id === VIRTUAL_ENTRY_ID ? entryContent : null;\n },\n };\n}\n\n/**\n * Rewrite vendor/chunk/global imports thành web path và để chúng external.\n * Global files (*.global.*) đã được client.global.ts load — bundle lại sẽ tạo\n * module instance trùng (vd nanostores).\n */\nfunction vendorPathRewriterPlugin(distClientDir: string): Plugin {\n const toWebPath = (absolutePath: string) =>\n '/' + path.relative(distClientDir, absolutePath).replace(/\\\\/g, '/');\n\n return {\n name: 'vendor-path-rewriter',\n resolveId(source, importer) {\n if (\n !source.includes('vendor-') &&\n !source.includes('chunk-') &&\n !source.includes('.global')\n ) {\n return null;\n }\n\n if (path.isAbsolute(source)) {\n // e.g. C:\\...\\dist\\client\\assets\\vendor-react-XXX.js -> /assets/vendor-react-XXX.js\n return { id: toWebPath(source), external: true };\n }\n\n if (importer && source.startsWith('.')) {\n // Relative path như ./auth.global-BOVr81Z5.js — resolve từ importer\n return { id: toWebPath(path.resolve(path.dirname(importer), source)), external: true };\n }\n\n return null;\n },\n };\n}\n\nasync function runScriptBundle(\n uniquePaths: string[],\n distClientDir: string,\n): Promise<BundleResult> {\n const entryContent = uniquePaths\n .map((p) => {\n const filePath = p.startsWith('/')\n ? path.join(distClientDir, p.substring(1))\n : path.join(distClientDir, p);\n return `import ${JSON.stringify(filePath)};`;\n })\n .join('\\n');\n\n const rollupOptions: RollupOptions = {\n input: VIRTUAL_ENTRY_ID,\n plugins: [virtualEntryPlugin(entryContent), vendorPathRewriterPlugin(distClientDir)],\n external: (id) => {\n // External node_modules\n if (!id.startsWith('.') && !path.isAbsolute(id) && id !== VIRTUAL_ENTRY_ID) {\n return true;\n }\n\n // Vendor/chunk/global do plugin resolveId lo phần rewrite path\n return false;\n },\n };\n\n const outputOptions: OutputOptions = {\n format: 'es',\n inlineDynamicImports: false,\n entryFileNames: 'bundle-[hash].js',\n chunkFileNames: 'bundle-[hash].js',\n };\n\n const { rollup } = await loadRollup();\n const bundle = await rollup(rollupOptions);\n let output;\n try {\n ({ output } = await bundle.generate(outputOptions));\n } finally {\n await bundle.close();\n }\n\n for (const chunk of output) {\n if (chunk.type !== 'chunk') {\n continue;\n }\n bundledFilesMap.set(chunk.fileName, {\n content: chunk.code || '',\n hash: generateHash(chunk.code || ''),\n filename: chunk.fileName,\n mimeType: 'application/javascript',\n });\n }\n\n const entryChunk = output[0];\n if (entryChunk?.type !== 'chunk') {\n throw new Error('[bundler] rollup produced no entry chunk');\n }\n\n return {\n hash: generateHash(entryChunk.code || ''),\n filename: entryChunk.fileName,\n content: entryChunk.code || '',\n };\n}\n\n/**\n * Bundle JavaScript files từ dist/client thành 1 file\n * Trong production, các file đã được build sẵn trong dist/client\n */\nexport async function bundleScripts(\n scriptPaths: string[],\n distClientDir: string,\n): Promise<BundleResult> {\n if (scriptPaths.length === 0) {\n return EMPTY_RESULT;\n }\n\n const uniquePaths = [...new Set(scriptPaths)].sort();\n const cacheKey = `scripts:${uniquePaths.join(',')}`;\n\n try {\n return await dedupe(cacheKey, () => runScriptBundle(uniquePaths, distClientDir));\n } catch (error) {\n console.error('[bundler] Error bundling scripts:', error);\n return EMPTY_RESULT;\n }\n}\n\nasync function runCssBundle(\n uniquePaths: string[],\n distClientDir: string,\n): Promise<BundleResult> {\n const cssContents: string[] = [];\n\n for (const cssPath of uniquePaths) {\n // cssPath có thể là \"/assets/xxx.css\" hoặc từ manifest\n const filePath = cssPath.startsWith('/')\n ? path.join(distClientDir, cssPath.substring(1))\n : path.join(distClientDir, cssPath);\n\n try {\n const content = await fs.readFile(filePath, 'utf-8');\n cssContents.push(`/* ${cssPath} */\\n${content}\\n`);\n } catch (err) {\n console.warn(`[bundler] Failed to read CSS file: ${cssPath}`, err);\n }\n }\n\n const bundledContent = cssContents.join('\\n\\n');\n const hash = generateHash(bundledContent);\n const filename = `bundle-${hash}.css`;\n\n bundledFilesMap.set(filename, {\n content: bundledContent,\n hash,\n filename,\n mimeType: 'text/css',\n });\n\n return { hash, filename, content: bundledContent };\n}\n\n/**\n * Bundle CSS files từ dist/client thành 1 file\n * Trong production, các file đã được build sẵn trong dist/client\n */\nexport async function bundleCss(\n cssPaths: string[],\n distClientDir: string,\n): Promise<BundleResult> {\n if (cssPaths.length === 0) {\n return EMPTY_RESULT;\n }\n\n const uniquePaths = [...new Set(cssPaths)].sort();\n const cacheKey = `css:${uniquePaths.join(',')}`;\n\n try {\n return await dedupe(cacheKey, () => runCssBundle(uniquePaths, distClientDir));\n } catch (error) {\n console.error('[bundler] Error bundling CSS:', error);\n return EMPTY_RESULT;\n }\n}\n\n/**\n * Get bundled file từ map\n */\nexport function getBundledFile(filename: string): BundledFile | undefined {\n return bundledFilesMap.get(filename);\n}\n\n/**\n * Clear bundled files map (useful for testing)\n */\nexport function clearBundledFiles(): void {\n bundledFilesMap.clear();\n bundlePromises.clear();\n}\n","import type { Request as ExpressRequest, Response as ExpressResponse } from 'express';\nimport { existsSync } from 'fs';\nimport fs from 'node:fs/promises';\nimport path from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport requestIp from 'request-ip';\nimport serialize from 'serialize-javascript';\nimport type { ViteDevServer } from 'vite';\nimport { createContext, type MiddlewareHandler, type RewritePayload } from '../middleware';\nimport { bundleCss, bundleScripts, getBundledFile } from './bundler';\nimport type { RenderResult, RequestInfo } from './entry-server';\nimport { escapeProp } from './render';\nimport { createHeadersFromExpressRequest, parseCookies } from './request';\n\nexport interface ServerOptions {\n root?: string;\n port?: number;\n base?: string;\n publicDir?: string;\n setupApp?: (app: any) => void | Promise<void>;\n app?: any; // Express\n}\n\nexport interface ServerContext {\n app: any; // Express app\n vite?: ViteDevServer;\n}\n\n/**\n * Apply or replace lang attribute on <html> tag\n */\nexport function applyHtmlLang(template: string, lang: string): string {\n // Escape so a loader-supplied lang (possibly derived from user input) cannot\n // break out of the attribute / <html> tag (XSS). escapeProp handles \", <, >, &.\n const safeLang = escapeProp(lang);\n return template.replace(/<html\\b([^>]*)>/i, (match, attrs) => {\n // Check if lang already exists\n if (/\\blang\\s*=/i.test(attrs)) {\n // Replace existing lang value (function replacer avoids $-pattern issues)\n return match.replace(/lang\\s*=\\s*\"[^\"]*\"/i, () => `lang=\"${safeLang}\"`);\n } else {\n // Add lang attribute\n return `<html lang=\"${safeLang}\"${attrs}>`;\n }\n });\n}\n\ntype EntryServerModule = {\n render: (url: string, requestInfo?: RequestInfo) => Promise<RenderResult>;\n loadMiddleware?: () => Promise<MiddlewareHandler | undefined>;\n};\n\nfunction getRequestUrl(req: ExpressRequest): URL {\n return new URL(`${req.protocol}://${req.get('host')}${req.originalUrl}`);\n}\n\nfunction getRenderUrl(urlObject: URL, base: string): string {\n const requestPath = `${urlObject.pathname}${urlObject.search}`;\n return requestPath.replace(base, '') || '/';\n}\n\nfunction createWebRequestFromExpress(req: ExpressRequest): globalThis.Request {\n const init: RequestInit & { duplex?: 'half' } = {\n method: req.method,\n headers: createHeadersFromExpressRequest(req),\n };\n\n if (req.method !== 'GET' && req.method !== 'HEAD') {\n init.body = req as unknown as BodyInit;\n init.duplex = 'half';\n }\n\n return new globalThis.Request(getRequestUrl(req).href, init);\n}\n\nfunction createRequestInfo(\n req: ExpressRequest,\n webRequest: globalThis.Request,\n base: string,\n locals: Record<string, unknown>,\n): RequestInfo {\n const urlObject = new URL(webRequest.url);\n const renderUrl = getRenderUrl(urlObject, base);\n const normalizedPath = renderUrl.startsWith('/') ? renderUrl : `/${renderUrl}`;\n const headers: Record<string, string> = {};\n webRequest.headers.forEach((value, key) => {\n headers[key] = value;\n });\n\n return {\n url: urlObject,\n path: normalizedPath,\n pathname: urlObject.pathname,\n method: webRequest.method,\n headers,\n cookies: parseCookies(webRequest.headers.get('cookie') ?? undefined),\n query: Object.fromEntries(urlObject.searchParams.entries()),\n ip: requestIp.getClientIp(req) ?? undefined,\n locals,\n };\n}\n\nfunction createRewriteRequest(\n payload: RewritePayload | undefined,\n currentRequest: globalThis.Request,\n currentUrl: URL,\n): globalThis.Request {\n if (!payload) {\n return currentRequest;\n }\n\n if (payload instanceof globalThis.Request) {\n return payload;\n }\n\n if (payload instanceof URL) {\n return new globalThis.Request(payload.href, currentRequest.clone());\n }\n\n return new globalThis.Request(new URL(payload, currentUrl).href, currentRequest.clone());\n}\n\nasync function sendWebResponse(\n req: ExpressRequest,\n res: ExpressResponse,\n response: globalThis.Response,\n): Promise<void> {\n res.status(response.status);\n const setCookieValues = getSetCookieHeaders(response.headers);\n response.headers.forEach((value, key) => {\n if (key.toLowerCase() === 'set-cookie') {\n return;\n }\n res.setHeader(key, value);\n });\n if (setCookieValues.length > 0) {\n res.setHeader('Set-Cookie', setCookieValues);\n }\n\n if (req.method === 'HEAD') {\n res.end();\n return;\n }\n\n const body = Buffer.from(await response.arrayBuffer());\n res.send(body);\n}\n\nfunction getSetCookieHeaders(headers: Headers): string[] {\n const getSetCookie = (headers as Headers & { getSetCookie?: () => string[] }).getSetCookie;\n if (typeof getSetCookie === 'function') {\n return getSetCookie.call(headers);\n }\n\n const raw = (headers as Headers & { raw?: () => Record<string, string[]> }).raw?.();\n if (raw?.['set-cookie']) {\n return raw['set-cookie'];\n }\n\n const value = headers.get('set-cookie');\n return value ? splitSetCookieHeader(value) : [];\n}\n\nfunction splitSetCookieHeader(value: string): string[] {\n const cookies: string[] = [];\n let start = 0;\n\n for (let i = 0; i < value.length; i++) {\n if (value[i] !== ',') continue;\n\n const rest = value.slice(i + 1);\n if (/^\\s*[^=;,]+=/.test(rest)) {\n cookies.push(value.slice(start, i).trim());\n start = i + 1;\n }\n }\n\n cookies.push(value.slice(start).trim());\n return cookies.filter(Boolean);\n}\n\nfunction createRawResponse(rendered: RenderResult): globalThis.Response | null {\n if (!rendered.rawResponse) {\n return null;\n }\n\n const { body, contentType, statusCode, headers } = rendered.rawResponse;\n const responseHeaders = new Headers(headers);\n responseHeaders.set('Content-Type', contentType);\n\n return new globalThis.Response(body as BodyInit, {\n status: statusCode || 200,\n headers: responseHeaders,\n });\n}\n\nasync function createPageResponse({\n rendered,\n template,\n manifest,\n root,\n distClientDir,\n isProduction,\n}: {\n rendered: RenderResult;\n template: string;\n manifest?: Record<string, any>;\n root: string;\n distClientDir: string;\n isProduction: boolean;\n}): Promise<globalThis.Response> {\n const rawResponse = createRawResponse(rendered);\n if (rawResponse) {\n return rawResponse;\n }\n\n if (rendered.redirect) {\n return new globalThis.Response(null, {\n status: rendered.redirect.statusCode,\n headers: {\n Location: rendered.redirect.url,\n },\n });\n }\n\n let scriptSrcList: string[] = rendered.scripts || [];\n let cssSrcList: string[] = rendered.styles || [];\n const islandEntries = rendered.islands || [];\n let cacheTags: string[] = rendered.cacheTags || [];\n const maxAge: number | undefined = rendered.maxAge;\n const sMaxAge: number | undefined = rendered.sMaxAge;\n const swr: number | undefined = rendered.swr;\n\n let extraHead = '';\n let globalScripts: string[] = [];\n let islandRegistryScript = '';\n\n if (isProduction && manifest) {\n scriptSrcList = scriptSrcList.filter((src) => !src.includes('.global.'));\n cssSrcList = cssSrcList.filter((src) => !src.includes('.global.'));\n\n const cssFiles = new Set<string>();\n const preloadFiles = new Set<string>();\n\n function collectFromEntry(entryKey: string): { file: string | null } {\n const entry = manifest![entryKey];\n if (!entry) return { file: null };\n\n if (entry.css) entry.css.forEach((css: string) => cssFiles.add(css));\n if (entry.imports) {\n entry.imports.forEach((importKey: string) => {\n const importedChunk = manifest![importKey];\n if (importedChunk?.file) preloadFiles.add(importedChunk.file);\n if (importedChunk?.css) {\n importedChunk.css.forEach((css: string) => cssFiles.add(css));\n }\n if (importedChunk?.imports) {\n importedChunk.imports.forEach((key: string) => {\n const chunk = manifest![key];\n if (chunk?.file) preloadFiles.add(chunk.file);\n if (chunk?.css) chunk.css.forEach((css: string) => cssFiles.add(css));\n });\n }\n });\n }\n\n return { file: entry.file };\n }\n\n const mappedScripts: string[] = [];\n for (const src of scriptSrcList) {\n const entryKey = src.replace(/^\\//, '');\n const { file } = collectFromEntry(entryKey);\n if (file) mappedScripts.push(`/${file}`);\n }\n\n const mappedCssFiles: string[] = [];\n for (const src of cssSrcList) {\n const entryKey = src.replace(/^\\//, '');\n const { file } = collectFromEntry(entryKey);\n if (file) {\n mappedCssFiles.push(`/${file}`);\n cssFiles.add(file);\n }\n }\n\n if (mappedScripts.length > 0) {\n const bundledScript = await bundleScripts(mappedScripts, distClientDir);\n scriptSrcList = bundledScript.filename ? [`/${bundledScript.filename}`] : mappedScripts;\n }\n\n if (mappedCssFiles.length > 0) {\n const bundledCss = await bundleCss(mappedCssFiles, distClientDir);\n if (bundledCss.filename) {\n cssSrcList = [`/${bundledCss.filename}`];\n }\n }\n\n const globalEntry = manifest['src/client.global.ts'];\n if (globalEntry) {\n if (globalEntry.css && globalEntry.css.length > 0) {\n globalEntry.css.forEach((cssFile: string) => {\n extraHead += `<link rel=\"stylesheet\" crossorigin href=\"/${cssFile}\">`;\n });\n }\n if (globalEntry.file) {\n globalScripts.push(`/${globalEntry.file}`);\n }\n }\n\n if (islandEntries.length > 0) {\n const islandMap: Record<string, string> = {};\n for (const island of islandEntries) {\n const entry = manifest[island.src];\n if (entry?.file) {\n islandMap[island.key] = `/${entry.file}`;\n }\n }\n if (Object.keys(islandMap).length > 0) {\n islandRegistryScript = `<script>window.__L5E_ISLANDS__=${serialize(islandMap)}</script>`;\n }\n }\n\n if (cssSrcList.length > 0) {\n extraHead += cssSrcList\n .map((file) => `<link rel=\"stylesheet\" crossorigin href=\"${file}\">`)\n .join('');\n }\n }\n\n let cssHtml = '';\n if (!isProduction) {\n // Registry đã dedupe, nhưng vẫn lọc lại ở đây để dev không bao giờ ra thẻ trùng\n cssHtml = [...new Set(cssSrcList)]\n .map((src) => `<link rel=\"stylesheet\" href=\"${src}\">`)\n .join('');\n }\n\n let allScripts = [...globalScripts, ...scriptSrcList];\n\n if (!isProduction) {\n const globalTsPath = path.join(root, 'src', 'client.global.ts');\n if (existsSync(globalTsPath)) {\n allScripts = ['/src/client.global.ts', ...allScripts];\n }\n\n // useClientJs('/src/client.global.ts') do user tự gọi sẽ trùng với entry\n // được prepend ở trên — registry không bắt được ca này nên dedupe lại\n allScripts = [...new Set(allScripts)];\n\n if (islandEntries.length > 0) {\n const islandMap: Record<string, string> = {};\n for (const island of islandEntries) {\n islandMap[island.key] = `/${island.src}`;\n }\n islandRegistryScript = `<script>window.__L5E_ISLANDS__=${serialize(islandMap)}</script>`;\n }\n }\n\n const scriptsHtml =\n islandRegistryScript +\n allScripts.map((src) => `<script type=\"module\" src=\"${src}\"></script>`).join('');\n\n const templateWithLang = rendered.lang ? applyHtmlLang(template, rendered.lang) : template;\n\n // Replacer fns (not strings) so `$`-sequences in rendered HTML — e.g. an SSR\n // island body or user text containing \"$$\" / \"$&\" — aren't interpreted as\n // special String.replace replacement patterns.\n const html = rendered.rawHtml\n ? rendered.html || ''\n : templateWithLang\n .replace(`<!--app-head-->`, () => (rendered.head ?? '') + extraHead + cssHtml)\n .replace(`<!--app-html-->`, () => rendered.html ?? '')\n .replace(`<!--app-scripts-->`, () => scriptsHtml);\n\n const headers = new Headers({\n 'Content-Type': 'text/html',\n });\n\n const cacheControlParts: string[] = ['public'];\n if (maxAge !== undefined) cacheControlParts.push(`max-age=${maxAge}`);\n if (sMaxAge !== undefined) cacheControlParts.push(`s-maxage=${sMaxAge}`);\n if (swr !== undefined) cacheControlParts.push(`stale-while-revalidate=${swr}`);\n\n if (cacheControlParts.length > 1 && isProduction) {\n headers.set('Cache-Control', cacheControlParts.join(', '));\n }\n\n if (process.env.NODE_ENV === 'production') {\n cacheTags = optimizeCacheTags(cacheTags);\n }\n headers.set('Cache-Tag', ['global', ...cacheTags].join(','));\n\n return new globalThis.Response(html, {\n status: rendered.statusCode || 200,\n headers,\n });\n}\n\nexport async function createServer(options: ServerOptions = {}): Promise<ServerContext> {\n const root = options.root || process.cwd();\n const base = options.base || '/';\n const isProduction = process.env.NODE_ENV === 'production';\n\n // Cached production assets\n const templateHtml = isProduction\n ? await fs.readFile(path.join(root, './index.html'), 'utf-8')\n : '';\n\n // Create http server\n // @ts-ignore\n const express = (await import('express')).default;\n const app = options.app || express();\n\n // Serve static files from public directory\n if (options.publicDir) {\n const publicPath = path.isAbsolute(options.publicDir)\n ? options.publicDir\n : path.join(root, options.publicDir);\n\n if (existsSync(publicPath)) {\n app.use(express.static(publicPath));\n }\n }\n\n // Add Vite or respective production middlewares\n let vite: ViteDevServer | undefined;\n const distClientDir = path.join(root, './dist/client');\n\n if (!isProduction) {\n const { createServer } = await import('vite');\n const configFile = path.join(root, 'vite.config.js');\n vite = await createServer({\n root,\n configFile,\n server: { middlewareMode: true },\n appType: 'custom',\n base,\n optimizeDeps: {\n exclude: ['@withl5e/l5e', 'file-type'],\n },\n ssr: {\n resolve: {\n conditions: ['development', 'default'],\n },\n },\n resolve: {\n conditions: ['development', 'default'],\n },\n });\n app.use(vite.middlewares);\n } else {\n // @ts-ignore\n const compression = (await import('compression')).default;\n // @ts-ignore\n const sirv = (await import('sirv')).default;\n app.use(compression());\n app.use(base, sirv(distClientDir, { extensions: [] }));\n\n // Route để serve bundled files từ memory map\n // Äặt route nà y trước route HTML để catch request trước\n app.get(\n `${base === '/' ? '' : base}/bundle-:hash.:ext`,\n async (req: ExpressRequest, res: ExpressResponse) => {\n try {\n const { hash, ext } = req.params;\n const filename = `bundle-${hash}.${ext}`;\n const bundledFile = getBundledFile(filename);\n\n if (!bundledFile) {\n return res.status(404).send('Bundled file not found');\n }\n\n res.set({\n 'Content-Type': bundledFile.mimeType,\n 'Cache-Control': 'public, max-age=31536000, immutable',\n });\n res.send(bundledFile.content);\n } catch (e: any) {\n console.error('[server] Error serving bundled file:', e);\n res.status(500).end('Internal server error');\n }\n },\n );\n }\n\n // Action routes — JSON body parsing scoped to action endpoints only\n app.use('/_l5e/action', express.json({ limit: '100kb' }));\n\n // Validate action key format: actionName_hexHash\n const ACTION_KEY_RE = /^[a-zA-Z]\\w+_[0-9a-f]{1,4}$/;\n\n // Load action registry and viewActions glob from virtual module (dev) or built bundle (prod)\n let prodActionRegistry: Record<string, { modulePath: string; actionName: string }> | null = null;\n let prodViewActions: Record<string, () => Promise<any>> | null = null;\n\n async function getActionRegistry(): Promise<\n Record<string, { modulePath: string; actionName: string }>\n > {\n if (!isProduction) {\n const mod = await vite!.ssrLoadModule('virtual:l5e-actions');\n return mod.actionRegistry || {};\n }\n if (!prodActionRegistry) {\n const registryPath = path.join(root, './dist/server/action-registry.json');\n const json = await fs.readFile(registryPath, 'utf-8');\n prodActionRegistry = JSON.parse(json);\n }\n return prodActionRegistry!;\n }\n\n async function getViewActions(): Promise<Record<string, () => Promise<any>>> {\n if (!isProduction) {\n const mod = await vite!.ssrLoadModule('virtual:l5e-actions');\n return mod.viewActions || {};\n }\n if (!prodViewActions) {\n const entryServerPath = path.join(root, './dist/server/entry-server.js');\n const mod = await import(pathToFileURL(entryServerPath).href);\n prodViewActions = mod.viewActions || {};\n }\n return prodViewActions!;\n }\n\n // Action route handler — hashed action keys\n // URL: /_l5e/action/:actionKey (e.g., /_l5e/action/loadMoreComments_a1b2)\n app.all('/_l5e/action/:actionKey', async (req: ExpressRequest, res: ExpressResponse) => {\n try {\n const { actionKey } = req.params;\n\n // Validate action key format\n if (!ACTION_KEY_RE.test(actionKey)) {\n return res.status(400).send('Invalid action key');\n }\n\n // Look up action in registry\n const registry = await getActionRegistry();\n const entry = registry[actionKey];\n if (!entry) {\n return res.status(404).send('Action not found');\n }\n\n const { modulePath, actionName } = entry;\n\n // Import action module via viewActions glob (works in both dev and prod)\n let actionModule: any;\n if (!isProduction) {\n try {\n actionModule = await vite!.ssrLoadModule(`/src/${modulePath}/actions.tsx`);\n } catch {\n actionModule = await vite!.ssrLoadModule(`/src/${modulePath}/actions.ts`);\n }\n } else {\n const viewActions = await getViewActions();\n // Find matching glob entry by modulePath\n const globKey = viewActions[`/src/${modulePath}/actions.tsx`]\n ? `/src/${modulePath}/actions.tsx`\n : viewActions[`/src/${modulePath}/actions.ts`]\n ? `/src/${modulePath}/actions.ts`\n : null;\n if (!globKey) {\n return res.status(404).send('Action module not found');\n }\n actionModule = await viewActions[globKey]();\n }\n\n // Look up exported action — use hasOwnProperty to avoid prototype pollution\n if (!Object.prototype.hasOwnProperty.call(actionModule, actionName)) {\n return res.status(404).send('Action not found');\n }\n const action = actionModule[actionName];\n if (!action || !action.handler) {\n return res.status(404).send('Action not found');\n }\n\n // Enforce the action's declared HTTP method. Previously `app.all` accepted\n // any method and `action.method` was ignored, so a state-changing POST\n // action could be triggered via GET (e.g. <img src>) — a CSRF vector.\n const allowedMethod = (action.method || 'GET').toUpperCase();\n if (req.method.toUpperCase() !== allowedMethod) {\n return res.status(405).set('Allow', allowedMethod).send('Method Not Allowed');\n }\n\n // Run the request through the middleware chain first — same as the HTML\n // handler — so `locals` (locale, country, preview flags, ...) is\n // populated for actions too. Previously this endpoint built its own\n // bare `requestInfo` and never invoked middleware at all, so `locals`\n // (and thus `getLocale()`) was always empty inside an action handler.\n //\n // Crucially, the action must run *inside* the `next` callback passed to\n // the middleware — not after `await`ing the middleware call — because a\n // middleware like `fromFetchMiddleware(paraglideMiddleware)` calls\n // `next()` synchronously inside a library-owned `AsyncLocalStorage.run()`\n // scope. Running the action afterward, once that scope has already\n // closed, would silently lose the library's own ambient `getLocale()`.\n const entryServerPath = path.join(root, './dist/server/entry-server.js');\n const entryServerModule: EntryServerModule = isProduction\n ? await import(pathToFileURL(entryServerPath).href)\n : await vite!.ssrLoadModule('@withl5e/l5e/entry-server');\n const { runInRenderContext } = await (isProduction\n ? import(pathToFileURL(entryServerPath).href)\n : vite!.ssrLoadModule('@withl5e/l5e/jsx-runtime'));\n const { renderJsxToHtmlString } = await (isProduction\n ? import(pathToFileURL(entryServerPath).href)\n : vite!.ssrLoadModule('@withl5e/l5e'));\n\n const locals: Record<string, unknown> = {};\n const initialRequest = createWebRequestFromExpress(req);\n const middlewareContext = createContext({\n request: initialRequest,\n locals,\n clientAddress: requestIp.getClientIp(req) ?? undefined,\n });\n\n const loadedMiddleware = await entryServerModule.loadMiddleware?.();\n const middlewareHandler: MiddlewareHandler =\n typeof loadedMiddleware === 'function' ? loadedMiddleware : (_ctx, dummyNext) => dummyNext();\n\n // If middleware short-circuits (returns its own Response — a redirect, a\n // 403, ...) instead of calling `next`, this callback never runs and that\n // response wins, same as it would for a page request.\n const response = await middlewareHandler(middlewareContext, async (payload) => {\n const nextRequest = createRewriteRequest(payload, middlewareContext.request, middlewareContext.url);\n const requestInfo = {\n ...createRequestInfo(req, nextRequest, base, locals),\n path: req.originalUrl,\n body: req.body,\n };\n\n const html = await runInRenderContext(\n async () => {\n const jsx = await action.handler(requestInfo);\n return renderJsxToHtmlString(jsx);\n },\n requestInfo,\n modulePath,\n );\n\n return new Response(html, { headers: { 'Content-Type': 'text/html' } });\n });\n\n await sendWebResponse(req, res, response);\n } catch (e: any) {\n vite?.ssrFixStacktrace?.(e);\n console.error('[l5e] Action error:', e.stack || e);\n res.status(500).send('Internal server error');\n }\n });\n\n // Serve HTML\n app.use(async (req: ExpressRequest, res: ExpressResponse) => {\n try {\n const url = req.originalUrl.replace(base, '');\n\n let template: string;\n let render: (url: string, requestInfo?: any) => Promise<any>;\n let loadMiddleware: EntryServerModule['loadMiddleware'];\n let manifest: Record<string, any> | undefined;\n\n if (!isProduction) {\n // Always read fresh template in development\n template = await fs.readFile(path.join(root, './index.html'), 'utf-8');\n template = await vite!.transformIndexHtml(url, template);\n\n // Inject Vite HMR client for hot reload\n if (!template.includes('@vite/client')) {\n template = template.replace(\n '</head>',\n '<script type=\"module\" src=\"/@vite/client\"></script></head>',\n );\n }\n\n const entryServer = (await vite!.ssrLoadModule(\n '@withl5e/l5e/entry-server',\n )) as EntryServerModule;\n render = entryServer.render;\n loadMiddleware = entryServer.loadMiddleware;\n } else {\n template = templateHtml;\n const entryServerPath = path.join(root, './dist/server/entry-server.js');\n const entryServer = (await import(\n pathToFileURL(entryServerPath).href\n )) as EntryServerModule;\n render = entryServer.render;\n loadMiddleware = entryServer.loadMiddleware;\n // Read manifest to map hashed assets\n const manifestJson = await fs.readFile(\n path.join(root, './dist/client/.vite/manifest.json'),\n 'utf-8',\n );\n manifest = JSON.parse(manifestJson);\n }\n\n const loadedMiddleware = await loadMiddleware?.();\n const handler: MiddlewareHandler =\n typeof loadedMiddleware === 'function' ? loadedMiddleware : (_ctx, next) => next();\n\n const locals: Record<string, unknown> = {};\n const initialRequest = createWebRequestFromExpress(req);\n const context = createContext({\n request: initialRequest,\n requestInfo: createRequestInfo(req, initialRequest, base, locals),\n locals,\n clientAddress: requestIp.getClientIp(req),\n });\n\n const renderResponse = async (webRequest: globalThis.Request) => {\n const nextRequestInfo = createRequestInfo(req, webRequest, base, locals);\n const nextUrl = getRenderUrl(nextRequestInfo.url!, base);\n const nextRendered = await render(nextUrl, nextRequestInfo);\n return createPageResponse({\n rendered: nextRendered,\n template,\n manifest,\n root,\n distClientDir,\n isProduction,\n });\n };\n\n const next = async (payload?: RewritePayload) => {\n const nextRequest = createRewriteRequest(payload, context.request, context.url);\n context.request = nextRequest;\n context.url = new URL(nextRequest.url);\n context.cookies = parseCookies(nextRequest.headers.get('cookie') ?? undefined);\n context.requestInfo = createRequestInfo(req, nextRequest, base, locals);\n return renderResponse(nextRequest);\n };\n\n context.rewrite = (payload: RewritePayload) => next(payload);\n\n const response = await handler(context, next);\n await sendWebResponse(req, res, response);\n } catch (e: any) {\n vite?.ssrFixStacktrace?.(e);\n console.error(e.stack);\n // Never leak stack traces to the client in production (info disclosure).\n res.status(500).end(isProduction ? 'Internal Server Error' : e.stack);\n }\n });\n\n return { app, vite };\n}\n\nexport async function startServer(options: ServerOptions = {}): Promise<void> {\n const port = options.port || 5173;\n\n // Create Express app first\n // @ts-ignore\n const express = (await import('express')).default;\n const app = express();\n\n // Call callback if provided to allow custom routes before setting up L5E server\n if (options.setupApp) {\n console.log('setupApp');\n await options.setupApp(app);\n }\n\n const { app: serverApp } = await createServer({ ...options, app });\n\n serverApp.listen(port, () => {\n console.log(`Server started at http://localhost:${port}`);\n });\n}\n\nconst MAX_TAGS = 1000;\n\nexport function hashTag(tag: string): string {\n // global tag is not hashed, better for ci/cd\n if (tag === 'global') {\n return 'global';\n }\n\n let hash = 0;\n for (let i = 0; i < tag.length; i++) {\n const char = tag.charCodeAt(i);\n hash = (hash << 5) - hash + char;\n hash = hash & hash; // Convert to 32bit integer\n }\n return Math.abs(hash).toString(36).substring(0, 8);\n}\n\nexport function optimizeCacheTags(tags: Set<string> | string[]): string[] {\n const _tags = Array.isArray(tags) ? tags : [...tags];\n const result = _tags.slice(0, MAX_TAGS).map(hashTag);\n return result;\n}\n"],"names":["rollupModulePromise","loadRollup","require","createRequire","vitePath","rollupPath","path","pathToFileURL","EMPTY_RESULT","bundledFilesMap","bundlePromises","dedupe","cacheKey","work","pending","promise","error","generateHash","content","createHash","VIRTUAL_ENTRY_ID","virtualEntryPlugin","entryContent","source","id","vendorPathRewriterPlugin","distClientDir","toWebPath","absolutePath","importer","runScriptBundle","uniquePaths","p","filePath","rollupOptions","outputOptions","rollup","bundle","output","chunk","entryChunk","bundleScripts","scriptPaths","runCssBundle","cssContents","cssPath","fs","err","bundledContent","hash","filename","bundleCss","cssPaths","getBundledFile","applyHtmlLang","template","lang","safeLang","escapeProp","match","attrs","getRequestUrl","req","getRenderUrl","urlObject","base","createWebRequestFromExpress","init","createHeadersFromExpressRequest","createRequestInfo","webRequest","locals","renderUrl","normalizedPath","headers","value","key","parseCookies","requestIp","createRewriteRequest","payload","currentRequest","currentUrl","sendWebResponse","res","response","setCookieValues","getSetCookieHeaders","body","getSetCookie","raw","splitSetCookieHeader","cookies","start","i","rest","createRawResponse","rendered","contentType","statusCode","responseHeaders","createPageResponse","manifest","root","isProduction","rawResponse","scriptSrcList","cssSrcList","islandEntries","cacheTags","maxAge","sMaxAge","swr","extraHead","globalScripts","islandRegistryScript","collectFromEntry","entryKey","entry","css","cssFiles","importKey","importedChunk","preloadFiles","src","mappedScripts","file","mappedCssFiles","bundledScript","bundledCss","globalEntry","cssFile","islandMap","island","serialize","cssHtml","allScripts","globalTsPath","existsSync","scriptsHtml","templateWithLang","html","cacheControlParts","optimizeCacheTags","createServer","options","templateHtml","express","app","publicPath","vite","compression","sirv","ext","bundledFile","e","configFile","ACTION_KEY_RE","prodActionRegistry","prodViewActions","getActionRegistry","registryPath","json","getViewActions","entryServerPath","actionKey","modulePath","actionName","actionModule","viewActions","globKey","action","allowedMethod","entryServerModule","runInRenderContext","renderJsxToHtmlString","initialRequest","middlewareContext","createContext","loadedMiddleware","_ctx","dummyNext","nextRequest","requestInfo","jsx","url","render","loadMiddleware","entryServer","manifestJson","handler","next","context","renderResponse","nextRequestInfo","nextUrl","nextRendered","startServer","port","serverApp","MAX_TAGS","hashTag","tag","char","tags"],"mappings":";;;;;;;;;AAQA,IAAIA,IAA+D;AASnE,SAASC,KAA+C;AACtD,SAAKD,MACHA,KAAuB,YAAY;AACjC,UAAME,IAAUC,GAAc,YAAY,GAAG,GACvCC,IAAWF,EAAQ,QAAQ,MAAM,GACjCG,IAAaH,EAAQ,QAAQ,UAAU,EAAE,OAAO,CAACI,EAAK,QAAQF,CAAQ,CAAC,EAAA,CAAG;AAChF,WAAQ,MAAM,OAAOG,EAAcF,CAAU,EAAE;AAAA,EACjD,GAAA,IAEKL;AACT;AAeA,MAAMQ,IAA6B,EAAE,MAAM,IAAI,UAAU,IAAI,SAAS,GAAA,GAGhEC,wBAAsB,IAAA,GAOtBC,wBAAqB,IAAA;AAK3B,SAASC,GAAOC,GAAkBC,GAA0D;AAC1F,QAAMC,IAAUJ,EAAe,IAAIE,CAAQ;AAC3C,MAAIE;AACF,WAAOA;AAGT,QAAMC,IAAUF,EAAA,EAAO,MAAM,CAACG,MAAU;AACtC,UAAAN,EAAe,OAAOE,CAAQ,GACxBI;AAAA,EACR,CAAC;AACD,SAAAN,EA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