@withl5e/l5e 0.3.3-alpha.2 → 0.3.3-alpha.4

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/server.js CHANGED
@@ -244,8 +244,8 @@ async function jt({
244
244
  base: w
245
245
  });
246
246
  S && g(S, l);
247
- let j = "";
248
- if (t.islandData && t.islandData.length > 0 && (j = `<script type="application/json" id="_l5e_data_">${V(
247
+ let A = "";
248
+ if (t.islandData && t.islandData.length > 0 && (A = `<script type="application/json" id="_l5e_data_">${V(
249
249
  t.islandData,
250
250
  { isJSON: !0 }
251
251
  )}<\/script>`), l && n) {
@@ -260,19 +260,19 @@ async function jt({
260
260
  }), { file: m.file }) : { file: null };
261
261
  };
262
262
  o = o.filter((i) => !i.includes(".global.")), c = c.filter((i) => !i.includes(".global."));
263
- const u = /* @__PURE__ */ new Set(), d = /* @__PURE__ */ new Set(), R = [];
263
+ const u = /* @__PURE__ */ new Set(), d = /* @__PURE__ */ new Set(), j = [];
264
264
  for (const i of o) {
265
265
  const m = i.replace(/^\//, ""), { file: x } = v(m);
266
- x && R.push(`/${x}`);
266
+ x && j.push(`/${x}`);
267
267
  }
268
268
  const F = [];
269
269
  for (const i of c) {
270
270
  const m = i.replace(/^\//, ""), { file: x } = v(m);
271
271
  x && (F.push(`/${x}`), u.add(x));
272
272
  }
273
- if (R.length > 0) {
274
- const i = await gt(R, r);
275
- o = i.filename ? [`/${i.filename}`] : R;
273
+ if (j.length > 0) {
274
+ const i = await gt(j, r);
275
+ o = i.filename ? [`/${i.filename}`] : j;
276
276
  }
277
277
  if (F.length > 0) {
278
278
  const i = await bt(F, r);
@@ -302,10 +302,10 @@ async function jt({
302
302
  $ = `<script>window.__L5E_ISLANDS__=${V(u)}<\/script>`;
303
303
  }
304
304
  }
305
- const M = j + $ + y.map((v) => `<script type="module" src="${v}"><\/script>`).join(""), E = t.lang ? St(e, t.lang) : e, _ = t.rawHtml ? t.html || "" : E.replace("<!--app-head-->", () => (t.head ?? "") + a).replace("<!--app-html-->", () => t.html ?? "").replace("<!--app-scripts-->", () => M), C = new Headers({
305
+ const M = A + $ + y.map((v) => `<script type="module" src="${v}"><\/script>`).join(""), E = t.lang ? St(e, t.lang) : e, _ = t.rawHtml ? t.html || "" : E.replace("<!--app-head-->", () => (t.head ?? "") + a).replace("<!--app-html-->", () => t.html ?? "").replace("<!--app-scripts-->", () => M), C = new Headers({
306
306
  "Content-Type": "text/html"
307
- }), k = [], A = [];
308
- return H !== void 0 && (k.push(`max-age=${H}`), A.push(`max-age=${H}`)), W !== void 0 && A.push(`s-maxage=${W}`), B !== void 0 && A.push(`stale-while-revalidate=${B}`), k.length > 1 && l && (k.push("public"), k.push("must-revalidate"), A.push("public"), C.set("Cache-Control", k.join(", ")), C.set("CDN-Cache-Control", A.join(", "))), process.env.NODE_ENV === "production" && (I = Tt(I)), C.set("Cache-Tag", ["global", ...I].join(",")), new globalThis.Response(_, {
307
+ }), k = [], R = [];
308
+ return H !== void 0 && (k.push(`max-age=${H}`), R.push(`max-age=${H}`)), W !== void 0 && R.push(`s-maxage=${W}`), B !== void 0 && R.push(`stale-while-revalidate=${B}`), (k.length > 0 || R.length > 0) && l && (k.push("public"), k.push("must-revalidate"), R.push("public"), C.set("Cache-Control", k.join(", ")), C.set("CDN-Cache-Control", R.join(", "))), process.env.NODE_ENV === "production" && (I = Tt(I)), C.set("Cache-Tag", ["global", ...I].join(",")), new globalThis.Response(_, {
309
309
  status: t.statusCode || 200,
310
310
  headers: C
311
311
  });
@@ -324,7 +324,7 @@ async function At(t = {}) {
324
324
  `${n === "/" ? "" : n}/bundle-:hash.:ext`,
325
325
  async (g, b) => {
326
326
  try {
327
- const { hash: $, ext: S } = g.params, j = `bundle-${$}.${S}`, y = vt(j);
327
+ const { hash: $, ext: S } = g.params, A = `bundle-${$}.${S}`, y = vt(A);
328
328
  if (!y)
329
329
  return b.status(404).send("Bundled file not found");
330
330
  b.set({
@@ -386,7 +386,7 @@ async function At(t = {}) {
386
386
  const $ = (await W())[g];
387
387
  if (!$)
388
388
  return h.status(404).send("Action not found");
389
- const { modulePath: S, actionName: j } = $;
389
+ const { modulePath: S, actionName: A } = $;
390
390
  let y;
391
391
  if (s) {
392
392
  const i = await B(), m = i[`/src/${S}/actions.tsx`] ? `/src/${S}/actions.tsx` : i[`/src/${S}/actions.ts`] ? `/src/${S}/actions.ts` : null;
@@ -399,19 +399,19 @@ async function At(t = {}) {
399
399
  } catch {
400
400
  y = await o.ssrLoadModule(`/src/${S}/actions.ts`);
401
401
  }
402
- if (!Object.prototype.hasOwnProperty.call(y, j))
402
+ if (!Object.prototype.hasOwnProperty.call(y, A))
403
403
  return h.status(404).send("Action not found");
404
- const M = y[j];
404
+ const M = y[A];
405
405
  if (!M || !M.handler)
406
406
  return h.status(404).send("Action not found");
407
407
  const E = (M.method || "GET").toUpperCase();
408
408
  if (a.method.toUpperCase() !== E)
409
409
  return h.status(405).set("Allow", E).send("Method Not Allowed");
410
- const _ = f.join(e, "./dist/server/entry-server.js"), C = s ? await import(N(_).href) : await o.ssrLoadModule("@withl5e/l5e/entry-server"), { runInRenderContext: k } = await (s ? import(N(_).href) : o.ssrLoadModule("@withl5e/l5e/jsx-runtime")), { renderJsxToHtmlString: A } = await (s ? import(N(_).href) : o.ssrLoadModule("@withl5e/l5e")), v = {}, u = tt(a), d = Q({
410
+ const _ = f.join(e, "./dist/server/entry-server.js"), C = s ? await import(N(_).href) : await o.ssrLoadModule("@withl5e/l5e/entry-server"), { runInRenderContext: k } = await (s ? import(N(_).href) : o.ssrLoadModule("@withl5e/l5e/jsx-runtime")), { renderJsxToHtmlString: R } = await (s ? import(N(_).href) : o.ssrLoadModule("@withl5e/l5e")), v = {}, u = tt(a), d = Q({
411
411
  request: u,
412
412
  locals: v,
413
413
  clientAddress: Y.getClientIp(a) ?? void 0
414
- }), R = await C.loadMiddleware?.(), L = await (typeof R == "function" ? R : (i, m) => m())(d, async (i) => {
414
+ }), j = await C.loadMiddleware?.(), L = await (typeof j == "function" ? j : (i, m) => m())(d, async (i) => {
415
415
  const m = et(i, d.request, d.url), x = {
416
416
  ...J(a, m, n, v),
417
417
  path: a.originalUrl,
@@ -419,7 +419,7 @@ async function At(t = {}) {
419
419
  }, P = await k(
420
420
  async () => {
421
421
  const U = await M.handler(x);
422
- return A(U);
422
+ return R(U);
423
423
  },
424
424
  x,
425
425
  S
@@ -433,16 +433,16 @@ async function At(t = {}) {
433
433
  }), p.use(async (a, h) => {
434
434
  try {
435
435
  const g = a.originalUrl.replace(n, "");
436
- let b, $, S, j;
436
+ let b, $, S, A;
437
437
  if (s) {
438
438
  b = l;
439
439
  const u = f.join(e, "./dist/server/entry-server.js"), d = await import(N(u).href);
440
440
  $ = d.render, S = d.loadMiddleware;
441
- const R = await D.readFile(
441
+ const j = await D.readFile(
442
442
  f.join(e, "./dist/client/.vite/manifest.json"),
443
443
  "utf-8"
444
444
  );
445
- j = JSON.parse(R);
445
+ A = JSON.parse(j);
446
446
  } else {
447
447
  b = await D.readFile(f.join(e, "./index.html"), "utf-8"), b = await o.transformIndexHtml(g, b), b.includes("@vite/client") || (b = b.replace(
448
448
  "</head>",
@@ -459,24 +459,24 @@ async function At(t = {}) {
459
459
  locals: E,
460
460
  clientAddress: Y.getClientIp(a)
461
461
  }), k = async (u) => {
462
- const d = J(a, u, n, E), R = it(d.url, n), F = await $(R, d, {
462
+ const d = J(a, u, n, E), j = it(d.url, n), F = await $(j, d, {
463
463
  externalizeIslandProps: r
464
464
  });
465
465
  return jt({
466
466
  rendered: F,
467
467
  template: b,
468
- manifest: j,
468
+ manifest: A,
469
469
  root: e,
470
470
  distClientDir: c,
471
471
  isProduction: s,
472
472
  assetBase: s ? n : o.config.base
473
473
  });
474
- }, A = async (u) => {
474
+ }, R = async (u) => {
475
475
  const d = et(u, C.request, C.url);
476
476
  return C.request = d, C.url = new URL(d.url), C.cookies = ot(d.headers.get("cookie") ?? void 0), C.requestInfo = J(a, d, n, E), k(d);
477
477
  };
478
- C.rewrite = (u) => A(u);
479
- const v = await M(C, A);
478
+ C.rewrite = (u) => R(u);
479
+ const v = await M(C, R);
480
480
  await nt(a, h, v);
481
481
  } catch (g) {
482
482
  o?.ssrFixStacktrace?.(g), console.error(g.stack), h.status(500).end(s ? "Internal Server Error" : g.stack);
@@ -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, 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 { resolveGlobalStyleHref } from './global-style';\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 * Externalize React island props into a single `<script id=\"_l5e_data_\">` at\n * the end of the document (referenced by `data-island-idx`) instead of inlining\n * a large `data-island-props` attribute on each element — keeps the SSR HTML\n * lean so crawlers read content first. Default true; set false for the legacy\n * inline behavior.\n */\n externalizeIslandProps?: boolean;\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: (\n url: string,\n requestInfo?: RequestInfo,\n options?: { externalizeIslandProps?: boolean },\n ) => 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 assetBase,\n}: {\n rendered: RenderResult;\n template: string;\n manifest?: Record<string, any>;\n root: string;\n distClientDir: string;\n isProduction: boolean;\n assetBase: string;\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 const emittedStyles = new Set<string>();\n const appendStylesheet = (href: string, crossorigin = false) => {\n if (emittedStyles.has(href)) return;\n emittedStyles.add(href);\n extraHead += `<link rel=\"stylesheet\"${crossorigin ? ' crossorigin' : ''} href=\"${escapeProp(href)}\">`;\n };\n let globalScripts: string[] = [];\n let islandRegistryScript = '';\n\n const globalStyleHref = resolveGlobalStyleHref({\n root,\n manifest,\n isProduction,\n base: assetBase,\n });\n if (globalStyleHref) appendStylesheet(globalStyleHref, isProduction);\n\n // Externalized island props → a single JSON script at the end of the document.\n // serialize-javascript with isJSON escapes `<`, `>`, `&` (and U+2028/2029) so the\n // props can't break out of the <script> block or inject markup (XSS). The runtime\n // reads it via `document.getElementById('_l5e_data_')` + JSON.parse.\n let islandDataScript = '';\n if (rendered.islandData && rendered.islandData.length > 0) {\n islandDataScript = `<script type=\"application/json\" id=\"_l5e_data_\">${serialize(\n rendered.islandData,\n { isJSON: true },\n )}</script>`;\n }\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 appendStylesheet(`/${cssFile}`, true);\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 cssSrcList.forEach((file) => appendStylesheet(file, true));\n }\n }\n\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 [...new Set(cssSrcList)].forEach((src) => appendStylesheet(src));\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 islandDataScript +\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)\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[] = [];\n const cdnCacheControlParts: string[] = [];\n if (maxAge !== undefined) {\n cacheControlParts.push(`max-age=${maxAge}`);\n cdnCacheControlParts.push(`max-age=${maxAge}`);\n }\n\n if (sMaxAge !== undefined) {\n cdnCacheControlParts.push(`s-maxage=${sMaxAge}`);\n }\n\n // ko cho phép browser swr\n if (swr !== undefined) {\n cdnCacheControlParts.push(`stale-while-revalidate=${swr}`);\n }\n\n if (cacheControlParts.length > 1 && isProduction) {\n cacheControlParts.push('public');\n cacheControlParts.push('must-revalidate');\n\n cdnCacheControlParts.push('public');\n\n\n headers.set('Cache-Control', cacheControlParts.join(', '));\n headers.set('CDN-Cache-Control', cdnCacheControlParts.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 const externalizeIslandProps = options.externalizeIslandProps ?? true;\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: (\n url: string,\n requestInfo?: any,\n options?: { externalizeIslandProps?: boolean },\n ) => 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 externalizeIslandProps,\n });\n return createPageResponse({\n rendered: nextRendered,\n template,\n manifest,\n root,\n distClientDir,\n isProduction,\n assetBase: isProduction ? base : vite!.config.base,\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","assetBase","rawResponse","scriptSrcList","cssSrcList","islandEntries","cacheTags","maxAge","sMaxAge","swr","extraHead","emittedStyles","appendStylesheet","href","crossorigin","globalScripts","islandRegistryScript","globalStyleHref","resolveGlobalStyleHref","islandDataScript","serialize","collectFromEntry","entryKey","entry","css","cssFiles","importKey","importedChunk","preloadFiles","src","mappedScripts","file","mappedCssFiles","bundledScript","bundledCss","globalEntry","cssFile","islandMap","island","allScripts","globalTsPath","existsSync","scriptsHtml","templateWithLang","html","cacheControlParts","cdnCacheControlParts","optimizeCacheTags","createServer","options","externalizeIslandProps","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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AQ;AACV,WAAO;AAGT,MAAIlK,IAAO;AACX,WAAS6C,IAAI,GAAGA,IAAIqH,EAAI,QAAQrH,KAAK;AACnC,UAAMsH,IAAOD,EAAI,WAAWrH,CAAC;AAC7B,IAAA7C,KAAQA,KAAQ,KAAKA,IAAOmK,GAC5BnK,IAAOA,IAAOA;AAAA,EAChB;AACA,SAAO,KAAK,IAAIA,CAAI,EAAE,SAAS,EAAE,EAAE,UAAU,GAAG,CAAC;AACnD;AAEO,SAASsG,GAAkB8D,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 { resolveGlobalStyleHref } from './global-style';\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 * Externalize React island props into a single `<script id=\"_l5e_data_\">` at\n * the end of the document (referenced by `data-island-idx`) instead of inlining\n * a large `data-island-props` attribute on each element — keeps the SSR HTML\n * lean so crawlers read content first. Default true; set false for the legacy\n * inline behavior.\n */\n externalizeIslandProps?: boolean;\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: (\n url: string,\n requestInfo?: RequestInfo,\n options?: { externalizeIslandProps?: boolean },\n ) => 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 assetBase,\n}: {\n rendered: RenderResult;\n template: string;\n manifest?: Record<string, any>;\n root: string;\n distClientDir: string;\n isProduction: boolean;\n assetBase: string;\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 const emittedStyles = new Set<string>();\n const appendStylesheet = (href: string, crossorigin = false) => {\n if (emittedStyles.has(href)) return;\n emittedStyles.add(href);\n extraHead += `<link rel=\"stylesheet\"${crossorigin ? ' crossorigin' : ''} href=\"${escapeProp(href)}\">`;\n };\n let globalScripts: string[] = [];\n let islandRegistryScript = '';\n\n const globalStyleHref = resolveGlobalStyleHref({\n root,\n manifest,\n isProduction,\n base: assetBase,\n });\n if (globalStyleHref) appendStylesheet(globalStyleHref, isProduction);\n\n // Externalized island props → a single JSON script at the end of the document.\n // serialize-javascript with isJSON escapes `<`, `>`, `&` (and U+2028/2029) so the\n // props can't break out of the <script> block or inject markup (XSS). The runtime\n // reads it via `document.getElementById('_l5e_data_')` + JSON.parse.\n let islandDataScript = '';\n if (rendered.islandData && rendered.islandData.length > 0) {\n islandDataScript = `<script type=\"application/json\" id=\"_l5e_data_\">${serialize(\n rendered.islandData,\n { isJSON: true },\n )}</script>`;\n }\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 appendStylesheet(`/${cssFile}`, true);\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 cssSrcList.forEach((file) => appendStylesheet(file, true));\n }\n }\n\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 [...new Set(cssSrcList)].forEach((src) => appendStylesheet(src));\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 islandDataScript +\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)\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[] = [];\n const cdnCacheControlParts: string[] = [];\n if (maxAge !== undefined) {\n cacheControlParts.push(`max-age=${maxAge}`);\n cdnCacheControlParts.push(`max-age=${maxAge}`);\n }\n\n if (sMaxAge !== undefined) {\n cdnCacheControlParts.push(`s-maxage=${sMaxAge}`);\n }\n\n // ko cho phép browser swr\n if (swr !== undefined) {\n cdnCacheControlParts.push(`stale-while-revalidate=${swr}`);\n }\n\n if ((cacheControlParts.length > 0 || cdnCacheControlParts.length > 0) && isProduction) {\n cacheControlParts.push('public');\n cacheControlParts.push('must-revalidate');\n\n cdnCacheControlParts.push('public');\n\n\n headers.set('Cache-Control', cacheControlParts.join(', '));\n headers.set('CDN-Cache-Control', cdnCacheControlParts.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 const externalizeIslandProps = options.externalizeIslandProps ?? true;\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: (\n url: string,\n requestInfo?: any,\n options?: { externalizeIslandProps?: boolean },\n ) => 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 externalizeIslandProps,\n });\n return createPageResponse({\n rendered: nextRendered,\n template,\n manifest,\n root,\n distClientDir,\n isProduction,\n assetBase: isProduction ? base : vite!.config.base,\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","assetBase","rawResponse","scriptSrcList","cssSrcList","islandEntries","cacheTags","maxAge","sMaxAge","swr","extraHead","emittedStyles","appendStylesheet","href","crossorigin","globalScripts","islandRegistryScript","globalStyleHref","resolveGlobalStyleHref","islandDataScript","serialize","collectFromEntry","entryKey","entry","css","cssFiles","importKey","importedChunk","preloadFiles","src","mappedScripts","file","mappedCssFiles","bundledScript","bundledCss","globalEntry","cssFile","islandMap","island","allScripts","globalTsPath","existsSync","scriptsHtml","templateWithLang","html","cacheControlParts","cdnCacheControlParts","optimizeCacheTags","createServer","options","externalizeIslandProps","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","serverAp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AU,GACtB,MAAMA,EAAQ,SAASI,CAAG;AAG5B,QAAM,EAAE,KAAKmD,MAAc,MAAMxD,GAAa,EAAE,GAAGC,GAAS,KAAAI,GAAK;AAEjE,EAAAmD,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,MAAIlK,IAAO;AACX,WAAS6C,IAAI,GAAGA,IAAIqH,EAAI,QAAQrH,KAAK;AACnC,UAAMsH,IAAOD,EAAI,WAAWrH,CAAC;AAC7B,IAAA7C,KAAQA,KAAQ,KAAKA,IAAOmK,GAC5BnK,IAAOA,IAAOA;AAAA,EAChB;AACA,SAAO,KAAK,IAAIA,CAAI,EAAE,SAAS,EAAE,EAAE,UAAU,GAAG,CAAC;AACnD;AAEO,SAASsG,GAAkB8D,GAAwC;AAGxE,UAFc,MAAM,QAAQA,CAAI,IAAIA,IAAO,CAAC,GAAGA,CAAI,GAC9B,MAAM,GAAGJ,EAAQ,EAAE,IAAIC,EAAO;AAErD;"}
package/dist/tooltip.js CHANGED
@@ -1,89 +1,93 @@
1
1
  import { autoUpdate as u, computePosition as m, offset as f, flip as h, shift as v, hide as b } from "@floating-ui/dom";
2
2
  function y() {
3
- const t = navigator.userAgent.toLowerCase(), e = /android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini|mobile|tablet/i.test(t), o = window.matchMedia("(max-width: 768px)").matches;
4
- return e || o;
3
+ const o = navigator.userAgent.toLowerCase(), e = /android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini|mobile|tablet/i.test(o), t = window.matchMedia("(max-width: 768px)").matches;
4
+ return e || t;
5
5
  }
6
6
  function w() {
7
- const t = document.querySelectorAll("[data-tooltip-id]");
8
- if (t.length === 0) return;
7
+ const o = document.querySelectorAll("[data-tooltip-id]");
8
+ if (o.length === 0) return;
9
9
  const e = y();
10
- t.forEach((o) => {
11
- o.hasAttribute("data-tooltip-initialized") || (o.setAttribute("data-tooltip-initialized", "true"), e ? o.addEventListener("click", async (n) => {
10
+ o.forEach((t) => {
11
+ t.hasAttribute("data-tooltip-initialized") || (t.setAttribute("data-tooltip-initialized", "true"), e ? t.addEventListener("click", async (n) => {
12
12
  n.preventDefault();
13
13
  const { showTooltipMobile: i } = await Promise.resolve().then(() => d);
14
- i(o);
15
- }) : o.addEventListener(
14
+ i(t);
15
+ }) : (t.addEventListener("pointerenter", () => {
16
+ t.setAttribute("data-tooltip-active", "true");
17
+ }), t.addEventListener("pointerleave", () => {
18
+ t.removeAttribute("data-tooltip-active");
19
+ }), t.addEventListener(
16
20
  "pointerenter",
17
21
  async () => {
18
22
  const { showTooltip: n } = await Promise.resolve().then(() => d);
19
- n(o);
23
+ n(t);
20
24
  },
21
25
  { passive: !0 }
22
- ));
26
+ )));
23
27
  });
24
28
  }
25
- function _() {
29
+ function H() {
26
30
  if (window.__tooltipObserver) return;
27
- const t = new MutationObserver((e) => {
28
- let o = !1;
31
+ const o = new MutationObserver((e) => {
32
+ let t = !1;
29
33
  e.forEach((n) => {
30
34
  n.type === "childList" && n.addedNodes.length > 0 && n.addedNodes.forEach((i) => {
31
35
  if (i.nodeType === Node.ELEMENT_NODE) {
32
36
  const a = i;
33
- (a.hasAttribute("data-tooltip-id") || a.querySelector("[data-tooltip-id]")) && (o = !0);
37
+ (a.hasAttribute("data-tooltip-id") || a.querySelector("[data-tooltip-id]")) && (t = !0);
34
38
  }
35
39
  });
36
- }), o && w();
40
+ }), t && w();
37
41
  });
38
- t.observe(document.body, {
42
+ o.observe(document.body, {
39
43
  childList: !0,
40
44
  subtree: !0
41
- }), window.__tooltipObserver = t;
45
+ }), window.__tooltipObserver = o;
42
46
  }
43
- const g = ({ type: t, id: e }) => `/tooltip/${t}/${e}`, L = ({ type: t, id: e }) => {
44
- const o = document.documentElement.lang;
47
+ const L = ({ type: o, id: e }) => `/tooltip/${o}/${e}`, T = ({ type: o, id: e }) => {
48
+ const t = document.documentElement.lang;
45
49
  let n = "";
46
- if (o) {
47
- const i = o.split("-")[0].toLowerCase(), l = location.pathname.match(/^\/([a-zA-Z-]+)(?:\/|$)/)?.[1];
48
- l && (l.toLowerCase() === i || l.toLowerCase() === o.toLowerCase()) && (n = `/${l}`);
50
+ if (t) {
51
+ const i = t.split("-")[0].toLowerCase(), l = location.pathname.match(/^\/([a-zA-Z-]+)(?:\/|$)/)?.[1];
52
+ l && (l.toLowerCase() === i || l.toLowerCase() === t.toLowerCase()) && (n = `/${l}`);
49
53
  }
50
- return `${n}/tooltip/${t}/${e}`;
54
+ return `${n}/tooltip/${o}/${e}`;
51
55
  };
52
- function T(t) {
53
- window.__l5eTooltipUrl = t === "auto-locale" ? L : t;
56
+ function E(o) {
57
+ window.__l5eTooltipUrl = o === "auto-locale" ? T : o;
54
58
  }
55
- function p(t) {
56
- const { tooltipId: e, tooltipType: o } = t.dataset;
57
- return (window.__l5eTooltipUrl ?? g)({ type: o ?? "", id: e ?? "", host: t });
59
+ function p(o) {
60
+ const { tooltipId: e, tooltipType: t } = o.dataset;
61
+ return (window.__l5eTooltipUrl ?? L)({ type: t ?? "", id: e ?? "", host: o });
58
62
  }
59
- async function E(t) {
60
- if (!t.matches(":hover")) return;
63
+ async function x(o) {
64
+ if (!o.hasAttribute("data-tooltip-active")) return;
61
65
  const e = document.createElement("div");
62
66
  e.className = "tp", e.innerHTML = '<div class="tp-loading">Loading...</div>', document.body.append(e);
63
- let o = null;
67
+ let t = null;
64
68
  const n = () => {
65
- o && (o(), o = null), document.body.contains(e) && e.remove();
69
+ t && (t(), t = null), document.body.contains(e) && e.remove();
66
70
  };
67
- if (t.addEventListener("pointerleave", n), !t.matches(":hover")) {
68
- t.removeEventListener("pointerleave", n), e.remove();
71
+ if (o.addEventListener("pointerleave", n), !o.hasAttribute("data-tooltip-active")) {
72
+ o.removeEventListener("pointerleave", n), e.remove();
69
73
  return;
70
74
  }
71
- o = u(t, e, () => s(t, e));
75
+ t = u(o, e, () => s(o, e));
72
76
  try {
73
- const i = await fetch(p(t), {
77
+ const i = await fetch(p(o), {
74
78
  headers: { Accept: "text/html" }
75
79
  }).then((a) => a.text());
76
80
  if (!document.body.contains(e)) return;
77
- e.innerHTML = i, await s(t, e);
81
+ e.innerHTML = i, await s(o, e);
78
82
  } catch {
79
83
  document.body.contains(e) && (e.innerHTML = '<div class="tp-error">Không thể tải tooltip</div>');
80
84
  }
81
85
  }
82
- async function x(t) {
86
+ async function g(o) {
83
87
  const e = document.createElement("div");
84
88
  e.className = "tp-overlay";
85
- const o = document.createElement("div");
86
- o.className = "tp-mobile", o.innerHTML = '<div class="tp-loading">Loading...</div>', e.append(o), document.body.append(e), document.body.style.overflow = "hidden";
89
+ const t = document.createElement("div");
90
+ t.className = "tp-mobile", t.innerHTML = '<div class="tp-loading">Loading...</div>', e.append(t), document.body.append(e), document.body.style.overflow = "hidden";
87
91
  const n = () => {
88
92
  e.remove(), document.body.style.overflow = "";
89
93
  };
@@ -91,38 +95,38 @@ async function x(t) {
91
95
  i.target === e && n();
92
96
  });
93
97
  try {
94
- const i = await fetch(p(t), {
98
+ const i = await fetch(p(o), {
95
99
  headers: { Accept: "text/html" }
96
100
  }).then((c) => c.text());
97
- o.innerHTML = "";
101
+ t.innerHTML = "";
98
102
  const a = document.createElement("button");
99
- a.className = "tp-mobile-close", a.innerHTML = "&#x2715;", a.addEventListener("click", n), o.append(a);
103
+ a.className = "tp-mobile-close", a.innerHTML = "&#x2715;", a.addEventListener("click", n), t.append(a);
100
104
  const l = document.createElement("div");
101
- l.className = "tp-mobile-content", l.innerHTML = i, o.append(l);
102
- const r = t.dataset.href;
105
+ l.className = "tp-mobile-content", l.innerHTML = i, t.append(l);
106
+ const r = o.dataset.href;
103
107
  if (r) {
104
108
  const c = document.createElement("a");
105
- c.className = "tp-mobile-link", c.href = r, c.textContent = "Xem chi tiết", o.append(c);
109
+ c.className = "tp-mobile-link", c.href = r, c.textContent = "Xem chi tiết", t.append(c);
106
110
  }
107
111
  } catch {
108
- o.innerHTML = '<div class="tp-error">Không thể tải tooltip</div>';
112
+ t.innerHTML = '<div class="tp-error">Không thể tải tooltip</div>';
109
113
  }
110
114
  }
111
115
  function M() {
112
116
  return {
113
117
  name: "centerFallback",
114
- fn({ rects: t }) {
115
- const e = window.innerHeight, o = 8;
116
- return t.floating.height <= e * 0.6 ? {} : {
117
- y: window.scrollY + Math.max(o, (e - t.floating.height) / 2),
118
- data: { centered: !0, maxHeight: e - o * 2 }
118
+ fn({ rects: o }) {
119
+ const e = window.innerHeight, t = 8;
120
+ return o.floating.height <= e * 0.6 ? {} : {
121
+ y: window.scrollY + Math.max(t, (e - o.floating.height) / 2),
122
+ data: { centered: !0, maxHeight: e - t * 2 }
119
123
  };
120
124
  }
121
125
  };
122
126
  }
123
- function s(t, e) {
124
- const n = t.dataset.tooltipPlacement ?? "left";
125
- return m(t, e, {
127
+ function s(o, e) {
128
+ const n = o.dataset.tooltipPlacement ?? "left";
129
+ return m(o, e, {
126
130
  placement: n,
127
131
  middleware: [f(6), h(), v({ padding: 5 }), M(), b()]
128
132
  }).then(({ x: i, y: a, middlewareData: l }) => {
@@ -133,15 +137,15 @@ function s(t, e) {
133
137
  }
134
138
  const d = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
135
139
  __proto__: null,
136
- configureTooltip: T,
137
- showTooltip: E,
138
- showTooltipMobile: x
140
+ configureTooltip: E,
141
+ showTooltip: x,
142
+ showTooltipMobile: g
139
143
  }, Symbol.toStringTag, { value: "Module" }));
140
144
  export {
141
- T as configureTooltip,
145
+ E as configureTooltip,
142
146
  w as initTooltips,
143
- _ as setupTooltipObserver,
144
- E as showTooltip,
145
- x as showTooltipMobile
147
+ H as setupTooltipObserver,
148
+ x as showTooltip,
149
+ g as showTooltipMobile
146
150
  };
147
151
  //# sourceMappingURL=tooltip.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"tooltip.js","sources":["../src/tooltip/tooltip-loader.ts","../src/tooltip/tooltip-runtime.ts"],"sourcesContent":["// tooltip-loader.ts\n// File này chỉ làm nhiệm vụ wake up tooltip khi cần thiết\n\n// Định nghĩa kiểu cho tooltip host element\ntype TooltipHost = HTMLElement & {\n dataset: {\n tooltipId: string;\n tooltipType?: string;\n };\n};\n\n/**\n * Kiểm tra xem thiết bị hiện tại có phải là thiết bị di động hay không\n * @returns true nếu là thiết bị di động\n */\nfunction isMobileDevice(): boolean {\n // Kiểm tra User Agent\n const userAgent = navigator.userAgent.toLowerCase();\n const isMobile =\n /android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini|mobile|tablet/i.test(userAgent);\n\n // Kiểm tra thêm kích thước màn hình (dưới 768px thường được coi là thiết bị di động)\n const isTouchScreen = window.matchMedia('(max-width: 768px)').matches;\n\n return isMobile || isTouchScreen;\n}\n\n/**\n * Hàm khởi tạo tooltip, chỉ load runtime khi cần thiết\n */\nexport function initTooltips(): void {\n const tooltipTriggers = document.querySelectorAll<TooltipHost>('[data-tooltip-id]');\n if (tooltipTriggers.length === 0) return;\n\n const mobile = isMobileDevice();\n\n tooltipTriggers.forEach((trigger) => {\n if (trigger.hasAttribute('data-tooltip-initialized')) return;\n trigger.setAttribute('data-tooltip-initialized', 'true');\n\n if (mobile) {\n trigger.addEventListener('click', async (e) => {\n e.preventDefault();\n const { showTooltipMobile } = await import('./tooltip-runtime');\n showTooltipMobile(trigger);\n });\n } else {\n trigger.addEventListener(\n 'pointerenter',\n async () => {\n const { showTooltip } = await import('./tooltip-runtime');\n showTooltip(trigger);\n },\n { passive: true },\n );\n }\n });\n}\n\n// Thêm một MutationObserver để theo dõi các phần tử DOM mới (cho React components)\nexport function setupTooltipObserver(): void {\n // Kiểm tra xem đã có observer chưa\n if (window.__tooltipObserver) return;\n\n // Observer theo dõi khi có phần tử mới được thêm vào DOM\n const observer = new MutationObserver((mutations) => {\n let shouldInit = false;\n\n mutations.forEach((mutation) => {\n if (mutation.type === 'childList' && mutation.addedNodes.length > 0) {\n // Kiểm tra xem có phần tử tooltip nào mới được thêm vào không\n mutation.addedNodes.forEach((node) => {\n if (node.nodeType === Node.ELEMENT_NODE) {\n const element = node as HTMLElement;\n // Kiểm tra nếu phần tử có data-tooltip-id hoặc chứa phần tử con có data-tooltip-id\n if (\n element.hasAttribute('data-tooltip-id') ||\n element.querySelector('[data-tooltip-id]')\n ) {\n shouldInit = true;\n }\n }\n });\n }\n });\n\n // Chỉ gọi initTooltips nếu có phát hiện tooltip mới\n if (shouldInit) {\n initTooltips();\n }\n });\n\n // Bắt đầu theo dõi toàn bộ DOM\n observer.observe(document.body, {\n childList: true,\n subtree: true,\n });\n\n // Lưu observer vào window để tránh tạo nhiều observer\n window.__tooltipObserver = observer;\n}\n\n// Typescript declaration cho window object\ndeclare global {\n interface Window {\n __tooltipObserver?: MutationObserver;\n }\n}\n","// tooltip-runtime.ts\n// Logic đầy đủ cho tooltip, chỉ được tải khi cần thiết\n\nimport type { Middleware, Placement } from '@floating-ui/dom';\nimport { autoUpdate, computePosition, flip, hide, offset, shift } from '@floating-ui/dom';\n\ntype TooltipHost = HTMLElement & {\n dataset: {\n tooltipId: string;\n tooltipType?: string;\n tooltipPlacement?: Placement;\n href?: string;\n };\n};\n\n/** Everything the tooltip system knows about one request, for a custom strategy to build a URL from. */\nexport interface TooltipUrlContext {\n type: string;\n id: string;\n host: TooltipHost;\n}\n\nexport type TooltipUrlStrategy = (ctx: TooltipUrlContext) => string;\n\nconst defaultStrategy: TooltipUrlStrategy = ({ type, id }) => `/tooltip/${type}/${id}`;\n\n/**\n * If the page's own URL already carries a prefix matching `<html lang>` (e.g.\n * `<html lang=\"vi\">` on `/vi/...`), reuse that same prefix — for apps doing\n * URL-prefix locale routing that want each locale to be a distinct,\n * CDN-cacheable tooltip URL with zero per-page setup. A base-locale page\n * (unprefixed URL) naturally infers no prefix.\n */\nconst autoLocaleStrategy: TooltipUrlStrategy = ({ type, id }) => {\n const lang = document.documentElement.lang;\n let prefix = '';\n if (lang) {\n const primary = lang.split('-')[0].toLowerCase();\n const match = location.pathname.match(/^\\/([a-zA-Z-]+)(?:\\/|$)/);\n const segment = match?.[1];\n if (segment && (segment.toLowerCase() === primary || segment.toLowerCase() === lang.toLowerCase())) {\n prefix = `/${segment}`;\n }\n }\n return `${prefix}/tooltip/${type}/${id}`;\n};\n\ndeclare global {\n interface Window {\n // L5E's per-request bundler compiles each view's client script (and\n // client.global.ts) as independent bundles — a view that imports\n // initTooltips()/showTooltip() gets its own inlined copy of this whole\n // module, with its own module-scoped variables. A plain `let` here\n // would only ever be seen by whichever single bundle happens to define\n // it, not by the others — so this has to live on `window`, the one\n // thing every independently-bundled script actually shares.\n __l5eTooltipUrl?: TooltipUrlStrategy;\n }\n}\n\n/**\n * Replace how every tooltip's fetch URL is built. L5E is not an i18n\n * framework and most apps using tooltips don't localize URLs (or need any\n * custom scheme) at all, so the default is `/tooltip/:type/:id` unless an\n * app opts into something else — call this once at startup, e.g. in\n * `client.global.ts` so it runs regardless of which view's own client\n * script actually mounts a tooltip:\n *\n * ```ts\n * configureTooltip('auto-locale'); // infer /vi (or none) from <html lang> + URL\n * // or fully custom:\n * configureTooltip(({ type, id }) => `/api/v2/tooltips/${type}-${id}`);\n * ```\n */\nexport function configureTooltip(strategy: 'auto-locale' | TooltipUrlStrategy): void {\n window.__l5eTooltipUrl = strategy === 'auto-locale' ? autoLocaleStrategy : strategy;\n}\n\nfunction tooltipUrl(host: TooltipHost): string {\n const { tooltipId: id, tooltipType: type } = host.dataset;\n const strategy = window.__l5eTooltipUrl ?? defaultStrategy;\n return strategy({ type: type ?? '', id: id ?? '', host });\n}\n\nexport async function showTooltip(host: TooltipHost): Promise<void> {\n /*\n * Trong lúc chờ dynamic import, con trỏ có thể đã rời khỏi phần tử host.\n * Nếu vậy, việc tạo tooltip là không cần thiết và sẽ không có sự kiện\n * `pointerleave` nào được kích hoạt để ẩn tooltip.\n */\n if (!host.matches(':hover')) return;\n\n const tip = document.createElement('div');\n tip.className = 'tp';\n tip.innerHTML = '<div class=\"tp-loading\">Loading...</div>';\n document.body.append(tip);\n\n // --- Cleanup ---\n let cleanupAutoUpdate: (() => void) | null = null;\n\n const cleanup = () => {\n if (cleanupAutoUpdate) {\n cleanupAutoUpdate();\n cleanupAutoUpdate = null;\n }\n if (document.body.contains(tip)) tip.remove();\n };\n\n host.addEventListener('pointerleave', cleanup);\n\n // Con trỏ đã rời trước khi listener được gắn\n if (!host.matches(':hover')) {\n host.removeEventListener('pointerleave', cleanup);\n tip.remove();\n return;\n }\n\n // --- Position: autoUpdate thay thế manual scroll/resize ---\n cleanupAutoUpdate = autoUpdate(host, tip, () => position(host, tip));\n\n // --- Fetch nội dung từ server ---\n try {\n const html = await fetch(tooltipUrl(host), {\n headers: { Accept: 'text/html' },\n }).then((r) => r.text());\n\n if (!document.body.contains(tip)) return;\n\n tip.innerHTML = html;\n await position(host, tip);\n } catch {\n if (document.body.contains(tip)) {\n tip.innerHTML = '<div class=\"tp-error\">Không thể tải tooltip</div>';\n }\n }\n}\n\n/**\n * Mobile: hiển thị tooltip dạng fullscreen popup.\n * Nếu host có data-href, thêm nút \"Xem chi tiết\" dẫn đến link đó.\n */\nexport async function showTooltipMobile(host: TooltipHost): Promise<void> {\n const overlay = document.createElement('div');\n overlay.className = 'tp-overlay';\n\n const popup = document.createElement('div');\n popup.className = 'tp-mobile';\n popup.innerHTML = '<div class=\"tp-loading\">Loading...</div>';\n\n overlay.append(popup);\n document.body.append(overlay);\n document.body.style.overflow = 'hidden';\n\n const cleanup = () => {\n overlay.remove();\n document.body.style.overflow = '';\n };\n\n // Đóng khi bấm vào overlay (bên ngoài popup)\n overlay.addEventListener('click', (e) => {\n if (e.target === overlay) cleanup();\n });\n\n try {\n const html = await fetch(tooltipUrl(host), {\n headers: { Accept: 'text/html' },\n }).then((r) => r.text());\n\n popup.innerHTML = '';\n\n // Nút đóng\n const closeBtn = document.createElement('button');\n closeBtn.className = 'tp-mobile-close';\n closeBtn.innerHTML = '&#x2715;';\n closeBtn.addEventListener('click', cleanup);\n popup.append(closeBtn);\n\n // Nội dung\n const content = document.createElement('div');\n content.className = 'tp-mobile-content';\n content.innerHTML = html;\n popup.append(content);\n\n // Nút \"Xem chi tiết\" nếu có data-href\n const href = host.dataset.href;\n if (href) {\n const link = document.createElement('a');\n link.className = 'tp-mobile-link';\n link.href = href;\n link.textContent = 'Xem chi tiết';\n popup.append(link);\n }\n } catch {\n popup.innerHTML = '<div class=\"tp-error\">Không thể tải tooltip</div>';\n }\n}\n\n/**\n * Khi tooltip cao hơn 60% viewport, bỏ qua placement trên/dưới host\n * và căn giữa theo chiều dọc màn hình + giới hạn maxHeight để scroll.\n */\nfunction centerFallback(): Middleware {\n return {\n name: 'centerFallback',\n fn({ rects }) {\n const vh = window.innerHeight;\n const padding = 8;\n\n if (rects.floating.height <= vh * 0.6) return {};\n\n return {\n y: window.scrollY + Math.max(padding, (vh - rects.floating.height) / 2),\n data: { centered: true, maxHeight: vh - padding * 2 },\n };\n },\n };\n}\n\nfunction position(host: TooltipHost, tip: HTMLDivElement): Promise<void> {\n const preferredPlacement = host.dataset.tooltipPlacement;\n const placement = preferredPlacement ?? 'left';\n\n return computePosition(host, tip, {\n placement,\n middleware: [offset(6), flip(), shift({ padding: 5 }), centerFallback(), hide()],\n }).then(({ x, y, middlewareData }) => {\n Object.assign(tip.style, { left: `${x}px`, top: `${y}px` });\n\n tip.style.visibility = middlewareData.hide?.referenceHidden ? 'hidden' : 'visible';\n\n const center = middlewareData.centerFallback as { centered?: boolean; maxHeight?: number };\n if (center?.centered) {\n tip.style.maxHeight = `${center.maxHeight}px`;\n tip.style.overflowY = 'auto';\n } else {\n tip.style.maxHeight = '';\n tip.style.overflowY = '';\n }\n });\n}\n"],"names":["isMobileDevice","userAgent","isMobile","isTouchScreen","initTooltips","tooltipTriggers","mobile","trigger","e","showTooltipMobile","tooltipRuntime","showTooltip","setupTooltipObserver","observer","mutations","shouldInit","mutation","node","element","defaultStrategy","type","id","autoLocaleStrategy","lang","prefix","primary","segment","configureTooltip","strategy","tooltipUrl","host","tip","cleanupAutoUpdate","cleanup","autoUpdate","position","html","r","overlay","popup","closeBtn","content","href","link","centerFallback","rects","vh","padding","placement","computePosition","offset","flip","shift","hide","x","y","middlewareData","center"],"mappings":";AAeA,SAASA,IAA0B;AAEjC,QAAMC,IAAY,UAAU,UAAU,YAAA,GAChCC,IACJ,+EAA+E,KAAKD,CAAS,GAGzFE,IAAgB,OAAO,WAAW,oBAAoB,EAAE;AAE9D,SAAOD,KAAYC;AACrB;AAKO,SAASC,IAAqB;AACnC,QAAMC,IAAkB,SAAS,iBAA8B,mBAAmB;AAClF,MAAIA,EAAgB,WAAW,EAAG;AAElC,QAAMC,IAASN,EAAA;AAEf,EAAAK,EAAgB,QAAQ,CAACE,MAAY;AACnC,IAAIA,EAAQ,aAAa,0BAA0B,MACnDA,EAAQ,aAAa,4BAA4B,MAAM,GAEnDD,IACFC,EAAQ,iBAAiB,SAAS,OAAOC,MAAM;AAC7C,MAAAA,EAAE,eAAA;AACF,YAAM,EAAE,mBAAAC,EAAA,IAAsB,MAAM,QAAA,QAAA,EAAA,KAAA,MAAAC,CAAA;AACpC,MAAAD,EAAkBF,CAAO;AAAA,IAC3B,CAAC,IAEDA,EAAQ;AAAA,MACN;AAAA,MACA,YAAY;AACV,cAAM,EAAE,aAAAI,EAAA,IAAgB,MAAM,QAAA,QAAA,EAAA,KAAA,MAAAD,CAAA;AAC9B,QAAAC,EAAYJ,CAAO;AAAA,MACrB;AAAA,MACA,EAAE,SAAS,GAAA;AAAA,IAAK;AAAA,EAGtB,CAAC;AACH;AAGO,SAASK,IAA6B;AAE3C,MAAI,OAAO,kBAAmB;AAG9B,QAAMC,IAAW,IAAI,iBAAiB,CAACC,MAAc;AACnD,QAAIC,IAAa;AAEjB,IAAAD,EAAU,QAAQ,CAACE,MAAa;AAC9B,MAAIA,EAAS,SAAS,eAAeA,EAAS,WAAW,SAAS,KAE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ACA;AAExC,SAAOmB,EAAgBnB,GAAMC,GAAK;AAAA,IAChC,WAAAiB;AAAA,IACA,YAAY,CAACE,EAAO,CAAC,GAAGC,KAAQC,EAAM,EAAE,SAAS,GAAG,GAAGR,EAAA,GAAkBS,GAAM;AAAA,EAAA,CAChF,EAAE,KAAK,CAAC,EAAE,GAAAC,GAAG,GAAAC,GAAG,gBAAAC,QAAqB;AACpC,WAAO,OAAOzB,EAAI,OAAO,EAAE,MAAM,GAAGuB,CAAC,MAAM,KAAK,GAAGC,CAAC,KAAA,CAAM,GAE1DxB,EAAI,MAAM,aAAayB,EAAe,MAAM,kBAAkB,WAAW;AAEzE,UAAMC,IAASD,EAAe;AAC9B,IAAIC,GAAQ,YACV1B,EAAI,MAAM,YAAY,GAAG0B,EAAO,SAAS,MACzC1B,EAAI,MAAM,YAAY,WAEtBA,EAAI,MAAM,YAAY,IACtBA,EAAI,MAAM,YAAY;AAAA,EAE1B,CAAC;AACH;;;;;;;"}
1
+ {"version":3,"file":"tooltip.js","sources":["../src/tooltip/tooltip-loader.ts","../src/tooltip/tooltip-runtime.ts"],"sourcesContent":["// tooltip-loader.ts\n// File này chỉ làm nhiệm vụ wake up tooltip khi cần thiết\n\n// Định nghĩa kiểu cho tooltip host element\ntype TooltipHost = HTMLElement & {\n dataset: {\n tooltipId: string;\n tooltipType?: string;\n };\n};\n\n/**\n * Kiểm tra xem thiết bị hiện tại có phải là thiết bị di động hay không\n * @returns true nếu là thiết bị di động\n */\nfunction isMobileDevice(): boolean {\n // Kiểm tra User Agent\n const userAgent = navigator.userAgent.toLowerCase();\n const isMobile =\n /android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini|mobile|tablet/i.test(userAgent);\n\n // Kiểm tra thêm kích thước màn hình (dưới 768px thường được coi là thiết bị di động)\n const isTouchScreen = window.matchMedia('(max-width: 768px)').matches;\n\n return isMobile || isTouchScreen;\n}\n\n/**\n * Hàm khởi tạo tooltip, chỉ load runtime khi cần thiết\n */\nexport function initTooltips(): void {\n const tooltipTriggers = document.querySelectorAll<TooltipHost>('[data-tooltip-id]');\n if (tooltipTriggers.length === 0) return;\n\n const mobile = isMobileDevice();\n\n tooltipTriggers.forEach((trigger) => {\n if (trigger.hasAttribute('data-tooltip-initialized')) return;\n trigger.setAttribute('data-tooltip-initialized', 'true');\n\n if (mobile) {\n trigger.addEventListener('click', async (e) => {\n e.preventDefault();\n const { showTooltipMobile } = await import('./tooltip-runtime');\n showTooltipMobile(trigger);\n });\n } else {\n // Keep the interaction state explicitly. Firefox can lose the\n // `:hover` match while the lazily-loaded runtime is being evaluated,\n // even though the pointer is still over the trigger.\n trigger.addEventListener('pointerenter', () => {\n trigger.setAttribute('data-tooltip-active', 'true');\n });\n trigger.addEventListener('pointerleave', () => {\n trigger.removeAttribute('data-tooltip-active');\n });\n trigger.addEventListener(\n 'pointerenter',\n async () => {\n const { showTooltip } = await import('./tooltip-runtime');\n showTooltip(trigger);\n },\n { passive: true },\n );\n }\n });\n}\n\n// Thêm một MutationObserver để theo dõi các phần tử DOM mới (cho React components)\nexport function setupTooltipObserver(): void {\n // Kiểm tra xem đã có observer chưa\n if (window.__tooltipObserver) return;\n\n // Observer theo dõi khi có phần tử mới được thêm vào DOM\n const observer = new MutationObserver((mutations) => {\n let shouldInit = false;\n\n mutations.forEach((mutation) => {\n if (mutation.type === 'childList' && mutation.addedNodes.length > 0) {\n // Kiểm tra xem có phần tử tooltip nào mới được thêm vào không\n mutation.addedNodes.forEach((node) => {\n if (node.nodeType === Node.ELEMENT_NODE) {\n const element = node as HTMLElement;\n // Kiểm tra nếu phần tử có data-tooltip-id hoặc chứa phần tử con có data-tooltip-id\n if (\n element.hasAttribute('data-tooltip-id') ||\n element.querySelector('[data-tooltip-id]')\n ) {\n shouldInit = true;\n }\n }\n });\n }\n });\n\n // Chỉ gọi initTooltips nếu có phát hiện tooltip mới\n if (shouldInit) {\n initTooltips();\n }\n });\n\n // Bắt đầu theo dõi toàn bộ DOM\n observer.observe(document.body, {\n childList: true,\n subtree: true,\n });\n\n // Lưu observer vào window để tránh tạo nhiều observer\n window.__tooltipObserver = observer;\n}\n\n// Typescript declaration cho window object\ndeclare global {\n interface Window {\n __tooltipObserver?: MutationObserver;\n }\n}\n","// tooltip-runtime.ts\n// Logic đầy đủ cho tooltip, chỉ được tải khi cần thiết\n\nimport type { Middleware, Placement } from '@floating-ui/dom';\nimport { autoUpdate, computePosition, flip, hide, offset, shift } from '@floating-ui/dom';\n\ntype TooltipHost = HTMLElement & {\n dataset: {\n tooltipId: string;\n tooltipType?: string;\n tooltipPlacement?: Placement;\n href?: string;\n };\n};\n\n/** Everything the tooltip system knows about one request, for a custom strategy to build a URL from. */\nexport interface TooltipUrlContext {\n type: string;\n id: string;\n host: TooltipHost;\n}\n\nexport type TooltipUrlStrategy = (ctx: TooltipUrlContext) => string;\n\nconst defaultStrategy: TooltipUrlStrategy = ({ type, id }) => `/tooltip/${type}/${id}`;\n\n/**\n * If the page's own URL already carries a prefix matching `<html lang>` (e.g.\n * `<html lang=\"vi\">` on `/vi/...`), reuse that same prefix — for apps doing\n * URL-prefix locale routing that want each locale to be a distinct,\n * CDN-cacheable tooltip URL with zero per-page setup. A base-locale page\n * (unprefixed URL) naturally infers no prefix.\n */\nconst autoLocaleStrategy: TooltipUrlStrategy = ({ type, id }) => {\n const lang = document.documentElement.lang;\n let prefix = '';\n if (lang) {\n const primary = lang.split('-')[0].toLowerCase();\n const match = location.pathname.match(/^\\/([a-zA-Z-]+)(?:\\/|$)/);\n const segment = match?.[1];\n if (segment && (segment.toLowerCase() === primary || segment.toLowerCase() === lang.toLowerCase())) {\n prefix = `/${segment}`;\n }\n }\n return `${prefix}/tooltip/${type}/${id}`;\n};\n\ndeclare global {\n interface Window {\n // L5E's per-request bundler compiles each view's client script (and\n // client.global.ts) as independent bundles — a view that imports\n // initTooltips()/showTooltip() gets its own inlined copy of this whole\n // module, with its own module-scoped variables. A plain `let` here\n // would only ever be seen by whichever single bundle happens to define\n // it, not by the others — so this has to live on `window`, the one\n // thing every independently-bundled script actually shares.\n __l5eTooltipUrl?: TooltipUrlStrategy;\n }\n}\n\n/**\n * Replace how every tooltip's fetch URL is built. L5E is not an i18n\n * framework and most apps using tooltips don't localize URLs (or need any\n * custom scheme) at all, so the default is `/tooltip/:type/:id` unless an\n * app opts into something else — call this once at startup, e.g. in\n * `client.global.ts` so it runs regardless of which view's own client\n * script actually mounts a tooltip:\n *\n * ```ts\n * configureTooltip('auto-locale'); // infer /vi (or none) from <html lang> + URL\n * // or fully custom:\n * configureTooltip(({ type, id }) => `/api/v2/tooltips/${type}-${id}`);\n * ```\n */\nexport function configureTooltip(strategy: 'auto-locale' | TooltipUrlStrategy): void {\n window.__l5eTooltipUrl = strategy === 'auto-locale' ? autoLocaleStrategy : strategy;\n}\n\nfunction tooltipUrl(host: TooltipHost): string {\n const { tooltipId: id, tooltipType: type } = host.dataset;\n const strategy = window.__l5eTooltipUrl ?? defaultStrategy;\n return strategy({ type: type ?? '', id: id ?? '', host });\n}\n\nexport async function showTooltip(host: TooltipHost): Promise<void> {\n /*\n * Trong lúc chờ dynamic import, con trỏ có thể đã rời khỏi phần tử host.\n * Nếu vậy, việc tạo tooltip là không cần thiết và sẽ không có sự kiện\n * `pointerleave` nào được kích hoạt để ẩn tooltip.\n */\n if (!host.hasAttribute('data-tooltip-active')) return;\n\n const tip = document.createElement('div');\n tip.className = 'tp';\n tip.innerHTML = '<div class=\"tp-loading\">Loading...</div>';\n document.body.append(tip);\n\n // --- Cleanup ---\n let cleanupAutoUpdate: (() => void) | null = null;\n\n const cleanup = () => {\n if (cleanupAutoUpdate) {\n cleanupAutoUpdate();\n cleanupAutoUpdate = null;\n }\n if (document.body.contains(tip)) tip.remove();\n };\n\n host.addEventListener('pointerleave', cleanup);\n\n // Con trỏ đã rời trước khi listener được gắn\n if (!host.hasAttribute('data-tooltip-active')) {\n host.removeEventListener('pointerleave', cleanup);\n tip.remove();\n return;\n }\n\n // --- Position: autoUpdate thay thế manual scroll/resize ---\n cleanupAutoUpdate = autoUpdate(host, tip, () => position(host, tip));\n\n // --- Fetch nội dung từ server ---\n try {\n const html = await fetch(tooltipUrl(host), {\n headers: { Accept: 'text/html' },\n }).then((r) => r.text());\n\n if (!document.body.contains(tip)) return;\n\n tip.innerHTML = html;\n await position(host, tip);\n } catch {\n if (document.body.contains(tip)) {\n tip.innerHTML = '<div class=\"tp-error\">Không thể tải tooltip</div>';\n }\n }\n}\n\n/**\n * Mobile: hiển thị tooltip dạng fullscreen popup.\n * Nếu host có data-href, thêm nút \"Xem chi tiết\" dẫn đến link đó.\n */\nexport async function showTooltipMobile(host: TooltipHost): Promise<void> {\n const overlay = document.createElement('div');\n overlay.className = 'tp-overlay';\n\n const popup = document.createElement('div');\n popup.className = 'tp-mobile';\n popup.innerHTML = '<div class=\"tp-loading\">Loading...</div>';\n\n overlay.append(popup);\n document.body.append(overlay);\n document.body.style.overflow = 'hidden';\n\n const cleanup = () => {\n overlay.remove();\n document.body.style.overflow = '';\n };\n\n // Đóng khi bấm vào overlay (bên ngoài popup)\n overlay.addEventListener('click', (e) => {\n if (e.target === overlay) cleanup();\n });\n\n try {\n const html = await fetch(tooltipUrl(host), {\n headers: { Accept: 'text/html' },\n }).then((r) => r.text());\n\n popup.innerHTML = '';\n\n // Nút đóng\n const closeBtn = document.createElement('button');\n closeBtn.className = 'tp-mobile-close';\n closeBtn.innerHTML = '&#x2715;';\n closeBtn.addEventListener('click', cleanup);\n popup.append(closeBtn);\n\n // Nội dung\n const content = document.createElement('div');\n content.className = 'tp-mobile-content';\n content.innerHTML = html;\n popup.append(content);\n\n // Nút \"Xem chi tiết\" nếu có data-href\n const href = host.dataset.href;\n if (href) {\n const link = document.createElement('a');\n link.className = 'tp-mobile-link';\n link.href = href;\n link.textContent = 'Xem chi tiết';\n popup.append(link);\n }\n } catch {\n popup.innerHTML = '<div class=\"tp-error\">Không thể tải tooltip</div>';\n }\n}\n\n/**\n * Khi tooltip cao hơn 60% viewport, bỏ qua placement trên/dưới host\n * và căn giữa theo chiều dọc màn hình + giới hạn maxHeight để scroll.\n */\nfunction centerFallback(): Middleware {\n return {\n name: 'centerFallback',\n fn({ rects }) {\n const vh = window.innerHeight;\n const padding = 8;\n\n if (rects.floating.height <= vh * 0.6) return {};\n\n return {\n y: window.scrollY + Math.max(padding, (vh - rects.floating.height) / 2),\n data: { centered: true, maxHeight: vh - padding * 2 },\n };\n },\n };\n}\n\nfunction position(host: TooltipHost, tip: HTMLDivElement): Promise<void> {\n const preferredPlacement = host.dataset.tooltipPlacement;\n const placement = preferredPlacement ?? 'left';\n\n return computePosition(host, tip, {\n placement,\n middleware: [offset(6), flip(), shift({ padding: 5 }), centerFallback(), hide()],\n }).then(({ x, y, middlewareData }) => {\n Object.assign(tip.style, { left: `${x}px`, top: `${y}px` });\n\n tip.style.visibility = middlewareData.hide?.referenceHidden ? 'hidden' : 'visible';\n\n const center = middlewareData.centerFallback as { centered?: boolean; maxHeight?: number };\n if (center?.centered) {\n tip.style.maxHeight = `${center.maxHeight}px`;\n tip.style.overflowY = 'auto';\n } else {\n tip.style.maxHeight = '';\n tip.style.overflowY = '';\n }\n });\n}\n"],"names":["isMobileDevice","userAgent","isMobile","isTouchScreen","initTooltips","tooltipTriggers","mobile","trigger","e","showTooltipMobile","tooltipRuntime","showTooltip","setupTooltipObserver","observer","mutations","shouldInit","mutation","node","element","defaultStrategy","type","id","autoLocaleStrategy","lang","prefix","primary","segment","configureTooltip","strategy","tooltipUrl","host","tip","cleanupAutoUpdate","cleanup","autoUpdate","position","html","r","overlay","popup","closeBtn","content","href","link","centerFallback","rects","vh","padding","placement","computePosition","offset","flip","shift","hide","x","y","middlewareData","center"],"mappings":";AAeA,SAASA,IAA0B;AAEjC,QAAMC,IAAY,UAAU,UAAU,YAAA,GAChCC,IACJ,+EAA+E,KAAKD,CAAS,GAGzFE,IAAgB,OAAO,WAAW,oBAAoB,EAAE;AAE9D,SAAOD,KAAYC;AACrB;AAKO,SAASC,IAAqB;AACnC,Q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,EAAE,GAAAC,GAAG,GAAAC,GAAG,gBAAAC,QAAqB;AACpC,WAAO,OAAOzB,EAAI,OAAO,EAAE,MAAM,GAAGuB,CAAC,MAAM,KAAK,GAAGC,CAAC,KAAA,CAAM,GAE1DxB,EAAI,MAAM,aAAayB,EAAe,MAAM,kBAAkB,WAAW;AAEzE,UAAMC,IAASD,EAAe;AAC9B,IAAIC,GAAQ,YACV1B,EAAI,MAAM,YAAY,GAAG0B,EAAO,SAAS,MACzC1B,EAAI,MAAM,YAAY,WAEtBA,EAAI,MAAM,YAAY,IACtBA,EAAI,MAAM,YAAY;AAAA,EAE1B,CAAC;AACH;;;;;;;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@withl5e/l5e",
3
- "version": "0.3.3-alpha.2",
3
+ "version": "0.3.3-alpha.4",
4
4
  "description": "HTML-first SSR MPA framework with loaders, middleware, islands, actions, swap, SEO and cache controls.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -430,7 +430,7 @@ async function createPageResponse({
430
430
  cdnCacheControlParts.push(`stale-while-revalidate=${swr}`);
431
431
  }
432
432
 
433
- if (cacheControlParts.length > 1 && isProduction) {
433
+ if ((cacheControlParts.length > 0 || cdnCacheControlParts.length > 0) && isProduction) {
434
434
  cacheControlParts.push('public');
435
435
  cacheControlParts.push('must-revalidate');
436
436
 
@@ -45,6 +45,15 @@ export function initTooltips(): void {
45
45
  showTooltipMobile(trigger);
46
46
  });
47
47
  } else {
48
+ // Keep the interaction state explicitly. Firefox can lose the
49
+ // `:hover` match while the lazily-loaded runtime is being evaluated,
50
+ // even though the pointer is still over the trigger.
51
+ trigger.addEventListener('pointerenter', () => {
52
+ trigger.setAttribute('data-tooltip-active', 'true');
53
+ });
54
+ trigger.addEventListener('pointerleave', () => {
55
+ trigger.removeAttribute('data-tooltip-active');
56
+ });
48
57
  trigger.addEventListener(
49
58
  'pointerenter',
50
59
  async () => {
@@ -88,7 +88,7 @@ export async function showTooltip(host: TooltipHost): Promise<void> {
88
88
  * Nếu vậy, việc tạo tooltip là không cần thiết và sẽ không có sự kiện
89
89
  * `pointerleave` nào được kích hoạt để ẩn tooltip.
90
90
  */
91
- if (!host.matches(':hover')) return;
91
+ if (!host.hasAttribute('data-tooltip-active')) return;
92
92
 
93
93
  const tip = document.createElement('div');
94
94
  tip.className = 'tp';
@@ -109,7 +109,7 @@ export async function showTooltip(host: TooltipHost): Promise<void> {
109
109
  host.addEventListener('pointerleave', cleanup);
110
110
 
111
111
  // Con trỏ đã rời trước khi listener được gắn
112
- if (!host.matches(':hover')) {
112
+ if (!host.hasAttribute('data-tooltip-active')) {
113
113
  host.removeEventListener('pointerleave', cleanup);
114
114
  tip.remove();
115
115
  return;