@teyik0/furin 0.1.0-alpha.7 → 0.1.0-alpha.9
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/adapter/static.d.ts +3 -0
- package/dist/build/client.d.ts +3 -3
- package/dist/build/compile-entry.d.ts +4 -4
- package/dist/build/entry-template.d.ts +2 -2
- package/dist/build/hydrate.d.ts +6 -2
- package/dist/build/index.d.ts +1 -1
- package/dist/build/index.js +1491 -78
- package/dist/build/types.d.ts +26 -3
- package/dist/cli/index.js +1525 -91
- package/dist/client.d.ts +18 -11
- package/dist/config.d.ts +33 -2
- package/dist/config.js +6 -1
- package/dist/context-logger.d.ts +26 -0
- package/dist/dev-page-plugin.d.ts +77 -0
- package/dist/furin.js +459 -69
- package/dist/link.d.ts +31 -3
- package/dist/link.js +198 -51
- package/dist/render/assemble.d.ts +4 -2
- package/dist/render/index.d.ts +1 -1
- package/dist/render/loaders.d.ts +1 -1
- package/dist/render/shell.d.ts +4 -1
- package/dist/router.d.ts +11 -0
- package/dist/router.js +942 -41
- package/package.json +6 -5
- package/src/adapter/bun.ts +20 -0
- package/src/adapter/static.ts +341 -0
- package/src/build/client.ts +21 -11
- package/src/build/compile-entry.ts +5 -3
- package/src/build/entry-template.ts +2 -2
- package/src/build/hydrate.ts +37 -9
- package/src/build/index.ts +56 -21
- package/src/build/scan-server.ts +43 -21
- package/src/build/types.ts +28 -3
- package/src/cli/index.ts +13 -5
- package/src/client.ts +19 -25
- package/src/config.ts +35 -1
- package/src/context-logger.ts +71 -0
- package/src/dev-page-plugin.ts +339 -4
- package/src/furin.ts +6 -2
- package/src/link.tsx +355 -64
- package/src/plugin/index.ts +2 -2
- package/src/render/assemble.ts +4 -2
- package/src/render/index.ts +67 -23
- package/src/render/loaders.ts +81 -36
- package/src/render/shell.ts +11 -4
- package/src/router.ts +55 -6
package/dist/build/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// @bun
|
|
2
2
|
// src/build/index.ts
|
|
3
|
-
import { existsSync as
|
|
4
|
-
import { join as
|
|
3
|
+
import { existsSync as existsSync9, writeFileSync as writeFileSync8 } from "fs";
|
|
4
|
+
import { join as join10, relative as relative4, resolve as resolve3 } from "path";
|
|
5
5
|
|
|
6
6
|
// src/adapter/bun.ts
|
|
7
7
|
import { existsSync as existsSync6, rmSync as rmSync2, writeFileSync as writeFileSync6 } from "fs";
|
|
@@ -1374,9 +1374,83 @@ import { existsSync as existsSync2, mkdirSync, readFileSync as readFileSync2, wr
|
|
|
1374
1374
|
import { join as join2 } from "path";
|
|
1375
1375
|
|
|
1376
1376
|
// src/render/shell.ts
|
|
1377
|
+
function extractTitle(meta) {
|
|
1378
|
+
if (!meta) {
|
|
1379
|
+
return;
|
|
1380
|
+
}
|
|
1381
|
+
for (const entry of meta) {
|
|
1382
|
+
if ("title" in entry) {
|
|
1383
|
+
return entry.title;
|
|
1384
|
+
}
|
|
1385
|
+
}
|
|
1386
|
+
return;
|
|
1387
|
+
}
|
|
1388
|
+
function isMetaTag(entry) {
|
|
1389
|
+
return !(("title" in entry) || ("charSet" in entry) || ("script:ld+json" in entry) || ("tagName" in entry));
|
|
1390
|
+
}
|
|
1377
1391
|
function escapeHtml(str) {
|
|
1378
1392
|
return str.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
1379
1393
|
}
|
|
1394
|
+
function safeJson(value) {
|
|
1395
|
+
return JSON.stringify(value).replace(/</g, "\\u003c").replace(/>/g, "\\u003e").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
|
|
1396
|
+
}
|
|
1397
|
+
function renderAttrs(obj) {
|
|
1398
|
+
return Object.entries(obj).filter(([, v]) => v !== undefined).map(([k, v]) => `${k}="${escapeHtml(String(v))}"`).join(" ");
|
|
1399
|
+
}
|
|
1400
|
+
function buildMetaParts(meta) {
|
|
1401
|
+
const parts = [];
|
|
1402
|
+
const title = extractTitle(meta);
|
|
1403
|
+
if (title) {
|
|
1404
|
+
parts.push(`<title>${escapeHtml(title)}</title>`);
|
|
1405
|
+
}
|
|
1406
|
+
for (const m of meta) {
|
|
1407
|
+
if (isMetaTag(m)) {
|
|
1408
|
+
parts.push(`<meta ${renderAttrs(m)} />`);
|
|
1409
|
+
}
|
|
1410
|
+
if ("script:ld+json" in m) {
|
|
1411
|
+
parts.push(`<script type="application/ld+json">${safeJson(m["script:ld+json"])}</script>`);
|
|
1412
|
+
}
|
|
1413
|
+
}
|
|
1414
|
+
return parts;
|
|
1415
|
+
}
|
|
1416
|
+
function buildLinkParts(links) {
|
|
1417
|
+
return links.map((link) => `<link ${renderAttrs(link)} />`);
|
|
1418
|
+
}
|
|
1419
|
+
function buildScriptParts(scripts) {
|
|
1420
|
+
return scripts.map((script) => {
|
|
1421
|
+
const { children, ...rest } = script;
|
|
1422
|
+
const attrs = renderAttrs(rest);
|
|
1423
|
+
if (children) {
|
|
1424
|
+
return `<script ${attrs}>${children}</script>`;
|
|
1425
|
+
}
|
|
1426
|
+
return `<script ${attrs}></script>`;
|
|
1427
|
+
});
|
|
1428
|
+
}
|
|
1429
|
+
function buildStyleParts(styles) {
|
|
1430
|
+
return styles.map((style) => {
|
|
1431
|
+
const typeAttr = style.type ? ` type="${escapeHtml(style.type)}"` : "";
|
|
1432
|
+
return `<style${typeAttr}>${style.children}</style>`;
|
|
1433
|
+
});
|
|
1434
|
+
}
|
|
1435
|
+
function buildHeadInjection(headData) {
|
|
1436
|
+
const parts = [];
|
|
1437
|
+
if (headData?.meta) {
|
|
1438
|
+
parts.push(...buildMetaParts(headData.meta));
|
|
1439
|
+
}
|
|
1440
|
+
if (headData?.links) {
|
|
1441
|
+
parts.push(...buildLinkParts(headData.links));
|
|
1442
|
+
}
|
|
1443
|
+
if (headData?.scripts) {
|
|
1444
|
+
parts.push(...buildScriptParts(headData.scripts));
|
|
1445
|
+
}
|
|
1446
|
+
if (headData?.styles) {
|
|
1447
|
+
parts.push(...buildStyleParts(headData.styles));
|
|
1448
|
+
}
|
|
1449
|
+
return parts.length > 0 ? `
|
|
1450
|
+
${parts.join(`
|
|
1451
|
+
`)}
|
|
1452
|
+
` : "";
|
|
1453
|
+
}
|
|
1380
1454
|
var THEME_INIT_SCRIPT = `<script>try{var __t=localStorage.getItem("furin-theme");` + `document.documentElement.classList.add(__t==="light"?"light":"dark")}` + `catch(e){document.documentElement.classList.add("dark")}</script>`;
|
|
1381
1455
|
function generateIndexHtml() {
|
|
1382
1456
|
return `<!DOCTYPE html>
|
|
@@ -1394,11 +1468,13 @@ function generateIndexHtml() {
|
|
|
1394
1468
|
</html>
|
|
1395
1469
|
`;
|
|
1396
1470
|
}
|
|
1397
|
-
function generateProdIndexHtml(entryChunk, cssChunks, buildId) {
|
|
1471
|
+
function generateProdIndexHtml(entryChunk, cssChunks, buildId, faviconHref) {
|
|
1398
1472
|
const cssLinks = cssChunks.map((c) => ` <link rel="stylesheet" crossorigin href="${c}">`).join(`
|
|
1399
1473
|
`);
|
|
1400
1474
|
const scriptTag = `<script type="module" crossorigin src="${entryChunk}"></script>`;
|
|
1401
1475
|
const buildIdMeta = buildId ? ` <meta name="furin-build-id" content="${escapeHtml(buildId)}">
|
|
1476
|
+
` : "";
|
|
1477
|
+
const faviconLink = faviconHref ? ` <link rel="icon" href="${escapeHtml(faviconHref)}">
|
|
1402
1478
|
` : "";
|
|
1403
1479
|
return `<!DOCTYPE html>
|
|
1404
1480
|
<html lang="en">
|
|
@@ -1406,7 +1482,7 @@ function generateProdIndexHtml(entryChunk, cssChunks, buildId) {
|
|
|
1406
1482
|
<meta charset="UTF-8">
|
|
1407
1483
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
1408
1484
|
${THEME_INIT_SCRIPT}
|
|
1409
|
-
${buildIdMeta}${cssLinks ? `${cssLinks}
|
|
1485
|
+
${buildIdMeta}${faviconLink}${cssLinks ? `${cssLinks}
|
|
1410
1486
|
` : ""} <!--ssr-head-->
|
|
1411
1487
|
</head>
|
|
1412
1488
|
<body>
|
|
@@ -1482,28 +1558,33 @@ ${entries.join(`;
|
|
|
1482
1558
|
}
|
|
1483
1559
|
|
|
1484
1560
|
// src/build/hydrate.ts
|
|
1485
|
-
function generateHydrateEntry(routes, rootLayout) {
|
|
1561
|
+
function generateHydrateEntry(routes, rootLayout, basePath) {
|
|
1486
1562
|
const routeEntries = [];
|
|
1487
1563
|
for (const route of routes) {
|
|
1488
1564
|
const resolvedPage = route.path.replace(/\\/g, "/");
|
|
1489
1565
|
const regexPattern = route.pattern.replace(/:[^/]+/g, "([^/]+)").replace(/\*/g, "(.*)");
|
|
1490
1566
|
routeEntries.push(` { pattern: "${route.pattern}", regex: new RegExp("^${regexPattern}$"), load: () => import("${resolvedPage}") }`);
|
|
1491
1567
|
}
|
|
1568
|
+
const basePathLiteral = JSON.stringify(basePath);
|
|
1569
|
+
const pathnameExpr = basePath ? `(() => { const p = window.location.pathname; const b = ${basePathLiteral}; return (p.startsWith(b) && (p.length === b.length || p[b.length] === "/")) ? p.slice(b.length) || "/" : p; })()` : "window.location.pathname";
|
|
1570
|
+
const logEndpoint = basePath ? `${JSON.stringify(basePath)} + "/_furin/ingest"` : `"/_furin/ingest"`;
|
|
1571
|
+
const basePathProp = basePath ? `
|
|
1572
|
+
basePath: ${basePathLiteral},` : "";
|
|
1492
1573
|
return `import { hydrateRoot, createRoot } from "react-dom/client";
|
|
1493
1574
|
import { createElement } from "react";
|
|
1494
1575
|
import { initLogger, log } from "evlog";
|
|
1495
|
-
import {
|
|
1576
|
+
import { createHttpLogDrain } from "evlog/http";
|
|
1496
1577
|
import { RouterProvider } from "@teyik0/furin/link";
|
|
1497
1578
|
import { route as root } from "${rootLayout.replace(/\\/g, "/")}";
|
|
1498
1579
|
|
|
1499
|
-
initLogger({ drain:
|
|
1580
|
+
initLogger({ drain: createHttpLogDrain({ drain: { endpoint: ${logEndpoint} } }) });
|
|
1500
1581
|
|
|
1501
1582
|
const routes = [
|
|
1502
1583
|
${routeEntries.join(`,
|
|
1503
1584
|
`)}
|
|
1504
1585
|
];
|
|
1505
1586
|
|
|
1506
|
-
const pathname =
|
|
1587
|
+
const pathname = ${pathnameExpr};
|
|
1507
1588
|
const _match = routes.find((r) => r.regex.test(pathname));
|
|
1508
1589
|
|
|
1509
1590
|
// Eagerly load only the current page module for initial hydration.
|
|
@@ -1523,7 +1604,7 @@ const _match = routes.find((r) => r.regex.test(pathname));
|
|
|
1523
1604
|
routes,
|
|
1524
1605
|
root,
|
|
1525
1606
|
initialMatch: match,
|
|
1526
|
-
initialData: loaderData
|
|
1607
|
+
initialData: loaderData,${basePathProp}
|
|
1527
1608
|
} as any);
|
|
1528
1609
|
|
|
1529
1610
|
if (import.meta.hot) {
|
|
@@ -1553,11 +1634,11 @@ const _match = routes.find((r) => r.regex.test(pathname));
|
|
|
1553
1634
|
});
|
|
1554
1635
|
`;
|
|
1555
1636
|
}
|
|
1556
|
-
function writeDevFiles(routes, { outDir, rootLayout }, projectRoot) {
|
|
1637
|
+
function writeDevFiles(routes, { outDir, rootLayout, basePath }, projectRoot) {
|
|
1557
1638
|
if (!existsSync2(outDir)) {
|
|
1558
1639
|
mkdirSync(outDir, { recursive: true });
|
|
1559
1640
|
}
|
|
1560
|
-
const hydrateCode = generateHydrateEntry(routes, rootLayout);
|
|
1641
|
+
const hydrateCode = generateHydrateEntry(routes, rootLayout, basePath);
|
|
1561
1642
|
const hydratePath = join2(outDir, "_hydrate.tsx");
|
|
1562
1643
|
const existingHydrate = existsSync2(hydratePath) ? readFileSync2(hydratePath, "utf8") : "";
|
|
1563
1644
|
if (hydrateCode !== existingHydrate) {
|
|
@@ -1631,7 +1712,7 @@ function buildTargetManifest(rootDir, buildRoot, target, serverEntry) {
|
|
|
1631
1712
|
// src/build/client.ts
|
|
1632
1713
|
var TS_FILE_FILTER = /\.(tsx|ts)$/;
|
|
1633
1714
|
var REACT_IMPORT_RE = /import\s+React\b/;
|
|
1634
|
-
async function buildClient(routes, { outDir, rootLayout, plugins }) {
|
|
1715
|
+
async function buildClient(routes, { outDir, rootLayout, plugins, publicPath, basePath }) {
|
|
1635
1716
|
const clientDir = join4(outDir, "client");
|
|
1636
1717
|
if (!existsSync4(outDir)) {
|
|
1637
1718
|
mkdirSync3(outDir, { recursive: true });
|
|
@@ -1639,7 +1720,7 @@ async function buildClient(routes, { outDir, rootLayout, plugins }) {
|
|
|
1639
1720
|
if (!existsSync4(clientDir)) {
|
|
1640
1721
|
mkdirSync3(clientDir, { recursive: true });
|
|
1641
1722
|
}
|
|
1642
|
-
const hydrateCode = generateHydrateEntry(routes, rootLayout);
|
|
1723
|
+
const hydrateCode = generateHydrateEntry(routes, rootLayout, basePath);
|
|
1643
1724
|
const hydratePath = join4(outDir, "_hydrate.tsx");
|
|
1644
1725
|
writeFileSync3(hydratePath, hydrateCode);
|
|
1645
1726
|
console.log("[furin] Building production client bundle\u2026");
|
|
@@ -1683,7 +1764,7 @@ ${transformed}`;
|
|
|
1683
1764
|
entry: "[dir]/[name]-[hash].[ext]",
|
|
1684
1765
|
chunk: "[name]-[hash].[ext]"
|
|
1685
1766
|
},
|
|
1686
|
-
publicPath
|
|
1767
|
+
publicPath,
|
|
1687
1768
|
plugins: plugins ? [...plugins, transformPlugin] : [transformPlugin],
|
|
1688
1769
|
alias: {
|
|
1689
1770
|
"@teyik0/furin/client": CLIENT_MODULE_PATH,
|
|
@@ -1702,8 +1783,14 @@ ${transformed}`;
|
|
|
1702
1783
|
if (!entryOutput) {
|
|
1703
1784
|
throw new Error("[furin] client build did not emit entry chunk");
|
|
1704
1785
|
}
|
|
1705
|
-
|
|
1706
|
-
|
|
1786
|
+
let publicPrefix;
|
|
1787
|
+
if (publicPath === "") {
|
|
1788
|
+
publicPrefix = "";
|
|
1789
|
+
} else {
|
|
1790
|
+
publicPrefix = publicPath.endsWith("/") ? publicPath : `${publicPath}/`;
|
|
1791
|
+
}
|
|
1792
|
+
const entryChunk = `${publicPrefix}${basename(entryOutput.path)}`;
|
|
1793
|
+
const cssChunks = cssOutputs.map((o) => `${publicPrefix}${basename(o.path)}`);
|
|
1707
1794
|
console.log("[furin] Production client build complete");
|
|
1708
1795
|
return { entryChunk, cssChunks };
|
|
1709
1796
|
}
|
|
@@ -1888,7 +1975,9 @@ async function buildBunTarget(routes, rootDir, buildRoot, rootPath, serverEntry,
|
|
|
1888
1975
|
const { entryChunk, cssChunks } = await buildClient(routes, {
|
|
1889
1976
|
outDir: targetDir,
|
|
1890
1977
|
rootLayout: rootPath,
|
|
1891
|
-
plugins: options.plugins
|
|
1978
|
+
plugins: options.plugins,
|
|
1979
|
+
publicPath: "/_client/",
|
|
1980
|
+
basePath: ""
|
|
1892
1981
|
});
|
|
1893
1982
|
const buildFingerprint = await createBuildFingerprint(entryChunk, cssChunks, routes, rootPath, serverEntry);
|
|
1894
1983
|
const buildId = Bun.hash(buildFingerprint).toString(16).slice(0, 12);
|
|
@@ -1918,8 +2007,18 @@ async function buildBunTarget(routes, rootDir, buildRoot, rootPath, serverEntry,
|
|
|
1918
2007
|
compile: { outfile },
|
|
1919
2008
|
minify: true,
|
|
1920
2009
|
sourcemap: "linked",
|
|
2010
|
+
define: { "process.env.NODE_ENV": JSON.stringify("production") },
|
|
1921
2011
|
plugins: options.plugins
|
|
1922
2012
|
});
|
|
2013
|
+
if (process.platform === "darwin") {
|
|
2014
|
+
Bun.spawnSync(["codesign", "--remove-signature", outfile]);
|
|
2015
|
+
const sign = Bun.spawnSync(["codesign", "-f", "-s", "-", outfile]);
|
|
2016
|
+
if (sign.exitCode !== 0) {
|
|
2017
|
+
console.warn(`[furin] Warning: codesign failed (exit ${sign.exitCode}). ` + `The binary may be killed by Gatekeeper on macOS. Run manually:
|
|
2018
|
+
` + ` codesign --remove-signature ${outfile}
|
|
2019
|
+
` + ` codesign -f -s - ${outfile}`);
|
|
2020
|
+
}
|
|
2021
|
+
}
|
|
1923
2022
|
console.log(`[furin] Server binary: ${outfile}`);
|
|
1924
2023
|
targetManifest.serverPath = toPosixPath(join7(targetManifest.targetDir, "server"));
|
|
1925
2024
|
if (options.compile === "embed") {
|
|
@@ -1957,9 +2056,1305 @@ async function buildBunTarget(routes, rootDir, buildRoot, rootPath, serverEntry,
|
|
|
1957
2056
|
return targetManifest;
|
|
1958
2057
|
}
|
|
1959
2058
|
|
|
2059
|
+
// src/adapter/static.ts
|
|
2060
|
+
import { cpSync as cpSync2, existsSync as existsSync7, rmSync as rmSync3, writeFileSync as writeFileSync7 } from "fs";
|
|
2061
|
+
import { dirname as dirname3, isAbsolute, join as join8, relative as relative3, resolve as resolve2, sep } from "path";
|
|
2062
|
+
|
|
2063
|
+
// src/render/assemble.ts
|
|
2064
|
+
function resolvePath(pattern, params) {
|
|
2065
|
+
let path = pattern;
|
|
2066
|
+
for (const [key, val] of Object.entries(params ?? {})) {
|
|
2067
|
+
path = path.replace(key === "*" ? "*" : `:${key}`, val);
|
|
2068
|
+
}
|
|
2069
|
+
return path;
|
|
2070
|
+
}
|
|
2071
|
+
async function streamToString(stream) {
|
|
2072
|
+
const reader = stream.getReader();
|
|
2073
|
+
const decoder = new TextDecoder;
|
|
2074
|
+
let html = "";
|
|
2075
|
+
for (;; ) {
|
|
2076
|
+
const { done, value } = await reader.read();
|
|
2077
|
+
if (done) {
|
|
2078
|
+
break;
|
|
2079
|
+
}
|
|
2080
|
+
html += decoder.decode(value, { stream: true });
|
|
2081
|
+
}
|
|
2082
|
+
html += decoder.decode();
|
|
2083
|
+
return html;
|
|
2084
|
+
}
|
|
2085
|
+
function splitTemplate(template) {
|
|
2086
|
+
const [headPre, afterHead = ""] = template.split("<!--ssr-head-->");
|
|
2087
|
+
const [bodyPre, bodyPost = ""] = afterHead.split("<!--ssr-outlet-->");
|
|
2088
|
+
return { headPre, bodyPre, bodyPost };
|
|
2089
|
+
}
|
|
2090
|
+
function assembleHTML(template, headData, reactHtml, data) {
|
|
2091
|
+
const { headPre, bodyPre, bodyPost } = splitTemplate(template);
|
|
2092
|
+
const dataScript = data ? `<script id="__FURIN_DATA__" type="application/json">${safeJson(data)}</script>` : "";
|
|
2093
|
+
let injectedBodyPost = bodyPost;
|
|
2094
|
+
if (dataScript) {
|
|
2095
|
+
injectedBodyPost = bodyPost.includes("</body>") ? bodyPost.replace("</body>", `${dataScript}</body>`) : bodyPost + dataScript;
|
|
2096
|
+
}
|
|
2097
|
+
return headPre + headData + bodyPre + reactHtml + injectedBodyPost;
|
|
2098
|
+
}
|
|
2099
|
+
|
|
2100
|
+
// src/render/index.ts
|
|
2101
|
+
import { createElement as createElement2 } from "react";
|
|
2102
|
+
import { renderToReadableStream } from "react-dom/server";
|
|
2103
|
+
// ../../node_modules/.bun/evlog@2.13.0+449e6d239244fccb/node_modules/evlog/dist/utils.mjs
|
|
2104
|
+
function formatDuration(ms) {
|
|
2105
|
+
if (ms < 1000)
|
|
2106
|
+
return `${Math.round(ms)}ms`;
|
|
2107
|
+
return `${(ms / 1000).toFixed(2)}s`;
|
|
2108
|
+
}
|
|
2109
|
+
function isClient() {
|
|
2110
|
+
return typeof window !== "undefined";
|
|
2111
|
+
}
|
|
2112
|
+
function isDev() {
|
|
2113
|
+
if (typeof process !== "undefined")
|
|
2114
|
+
return true;
|
|
2115
|
+
if (typeof window !== "undefined")
|
|
2116
|
+
return true;
|
|
2117
|
+
return false;
|
|
2118
|
+
}
|
|
2119
|
+
function detectEnvironment() {
|
|
2120
|
+
const env = typeof process !== "undefined" ? process.env : {};
|
|
2121
|
+
const defaultEnvironment = isDev() ? "development" : "production";
|
|
2122
|
+
return {
|
|
2123
|
+
environment: env.NODE_ENV || defaultEnvironment,
|
|
2124
|
+
service: env.SERVICE_NAME || "app",
|
|
2125
|
+
version: env.APP_VERSION,
|
|
2126
|
+
commitHash: env.COMMIT_SHA || env.GITHUB_SHA || env.VERCEL_GIT_COMMIT_SHA || env.CF_PAGES_COMMIT_SHA,
|
|
2127
|
+
region: env.VERCEL_REGION || env.AWS_REGION || env.FLY_REGION || env.CF_REGION
|
|
2128
|
+
};
|
|
2129
|
+
}
|
|
2130
|
+
var LEVEL_ORDER = {
|
|
2131
|
+
debug: 0,
|
|
2132
|
+
info: 1,
|
|
2133
|
+
warn: 2,
|
|
2134
|
+
error: 3
|
|
2135
|
+
};
|
|
2136
|
+
function isLevelEnabled(level, minLevel) {
|
|
2137
|
+
return LEVEL_ORDER[level] >= LEVEL_ORDER[minLevel];
|
|
2138
|
+
}
|
|
2139
|
+
function getConsoleMethod(level) {
|
|
2140
|
+
return level;
|
|
2141
|
+
}
|
|
2142
|
+
var colors = {
|
|
2143
|
+
reset: "\x1B[0m",
|
|
2144
|
+
bold: "\x1B[1m",
|
|
2145
|
+
dim: "\x1B[2m",
|
|
2146
|
+
red: "\x1B[31m",
|
|
2147
|
+
green: "\x1B[32m",
|
|
2148
|
+
yellow: "\x1B[33m",
|
|
2149
|
+
blue: "\x1B[34m",
|
|
2150
|
+
magenta: "\x1B[35m",
|
|
2151
|
+
cyan: "\x1B[36m",
|
|
2152
|
+
white: "\x1B[37m",
|
|
2153
|
+
gray: "\x1B[90m"
|
|
2154
|
+
};
|
|
2155
|
+
var levelColorMap = {
|
|
2156
|
+
error: colors.red,
|
|
2157
|
+
warn: colors.yellow,
|
|
2158
|
+
info: colors.cyan,
|
|
2159
|
+
debug: colors.gray
|
|
2160
|
+
};
|
|
2161
|
+
function getLevelColor(level) {
|
|
2162
|
+
return levelColorMap[level] ?? colors.white;
|
|
2163
|
+
}
|
|
2164
|
+
var cssColors = {
|
|
2165
|
+
dim: "color: #6b7280",
|
|
2166
|
+
red: "color: #ef4444; font-weight: bold",
|
|
2167
|
+
green: "color: #22c55e",
|
|
2168
|
+
yellow: "color: #f59e0b; font-weight: bold",
|
|
2169
|
+
cyan: "color: #06b6d4; font-weight: bold",
|
|
2170
|
+
gray: "color: #6b7280; font-weight: bold",
|
|
2171
|
+
reset: "color: inherit; font-weight: normal"
|
|
2172
|
+
};
|
|
2173
|
+
var cssLevelColorMap = {
|
|
2174
|
+
error: cssColors.red,
|
|
2175
|
+
warn: cssColors.yellow,
|
|
2176
|
+
info: cssColors.cyan,
|
|
2177
|
+
debug: cssColors.gray
|
|
2178
|
+
};
|
|
2179
|
+
function getCssLevelColor(level) {
|
|
2180
|
+
return cssLevelColorMap[level] ?? cssColors.reset;
|
|
2181
|
+
}
|
|
2182
|
+
function escapeFormatString(str) {
|
|
2183
|
+
return str.replace(/%/g, "%%");
|
|
2184
|
+
}
|
|
2185
|
+
var patternCache = /* @__PURE__ */ new Map;
|
|
2186
|
+
function matchesPattern(path, pattern) {
|
|
2187
|
+
let regex = patternCache.get(pattern);
|
|
2188
|
+
if (!regex) {
|
|
2189
|
+
const regexPattern = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*\*/g, "{{GLOBSTAR}}").replace(/\*/g, "[^/]*").replace(/{{GLOBSTAR}}/g, ".*").replace(/\?/g, "[^/]");
|
|
2190
|
+
regex = new RegExp(`^${regexPattern}$`);
|
|
2191
|
+
patternCache.set(pattern, regex);
|
|
2192
|
+
}
|
|
2193
|
+
return regex.test(path);
|
|
2194
|
+
}
|
|
2195
|
+
|
|
2196
|
+
// ../../node_modules/.bun/evlog@2.13.0+449e6d239244fccb/node_modules/evlog/dist/logger-DnobymUQ.mjs
|
|
2197
|
+
var DEFAULT_REPLACEMENT = "[REDACTED]";
|
|
2198
|
+
var builtinPatterns = {
|
|
2199
|
+
creditCard: {
|
|
2200
|
+
pattern: /\b\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}\b/g,
|
|
2201
|
+
mask: (m) => `****${m.replace(/[\s-]/g, "").slice(-4)}`
|
|
2202
|
+
},
|
|
2203
|
+
email: {
|
|
2204
|
+
pattern: /[\w.+-]+@[\w-]+\.[\w.]+/g,
|
|
2205
|
+
mask: (m) => {
|
|
2206
|
+
if (m.indexOf("@") < 1)
|
|
2207
|
+
return "***@***";
|
|
2208
|
+
const tld = m.slice(m.lastIndexOf("."));
|
|
2209
|
+
return `${m[0]}***@***${tld}`;
|
|
2210
|
+
}
|
|
2211
|
+
},
|
|
2212
|
+
ipv4: {
|
|
2213
|
+
pattern: /\b(?!0\.0\.0\.0\b)(?!127\.0\.0\.1\b)\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/g,
|
|
2214
|
+
mask: (m) => `***.***.***.${m.split(".").pop()}`
|
|
2215
|
+
},
|
|
2216
|
+
phone: {
|
|
2217
|
+
pattern: /(?:\+\d{1,3}[\s.-]?)?\(?\d{1,4}\)?[\s.-]?\d{2,4}[\s.-]?\d{2,4}[\s.-]?\d{2,4}\b/g,
|
|
2218
|
+
mask: (m) => {
|
|
2219
|
+
const digits = m.replace(/[^\d]/g, "");
|
|
2220
|
+
if (m.startsWith("+") && digits.length > 4) {
|
|
2221
|
+
const ccMatch = m.match(/^\+\d{1,3}/);
|
|
2222
|
+
return `${ccMatch ? ccMatch[0] : "+"}******${digits.slice(-2)}`;
|
|
2223
|
+
}
|
|
2224
|
+
if (digits.length > 2)
|
|
2225
|
+
return `${"*".repeat(digits.length - 2)}${digits.slice(-2)}`;
|
|
2226
|
+
return "***";
|
|
2227
|
+
}
|
|
2228
|
+
},
|
|
2229
|
+
jwt: {
|
|
2230
|
+
pattern: /\beyJ[\w-]*\.[\w-]*\.[\w-]*\b/g,
|
|
2231
|
+
mask: () => "eyJ***.***"
|
|
2232
|
+
},
|
|
2233
|
+
bearer: {
|
|
2234
|
+
pattern: /\bBearer\s+[\w\-.~+/]{8,}=*/gi,
|
|
2235
|
+
mask: () => "Bearer ***"
|
|
2236
|
+
},
|
|
2237
|
+
iban: {
|
|
2238
|
+
pattern: /\b[A-Z]{2}\d{2}[\s-]?[\dA-Z]{4}[\s-]?[\dA-Z]{4}[\s-]?[\dA-Z]{4}[\s-]?[\dA-Z]{0,4}[\s-]?[\dA-Z]{0,4}[\s-]?[\dA-Z]{0,4}\b/g,
|
|
2239
|
+
mask: (m) => {
|
|
2240
|
+
const clean = m.replace(/[\s-]/g, "");
|
|
2241
|
+
return `${clean.slice(0, 4)}****${clean.slice(-3)}`;
|
|
2242
|
+
}
|
|
2243
|
+
}
|
|
2244
|
+
};
|
|
2245
|
+
function resolveRedactConfig(input) {
|
|
2246
|
+
if (input === undefined || input === false)
|
|
2247
|
+
return;
|
|
2248
|
+
if (input === true)
|
|
2249
|
+
return { _maskers: allBuiltinMaskers() };
|
|
2250
|
+
if (input.builtins === false)
|
|
2251
|
+
return input;
|
|
2252
|
+
const maskers = Array.isArray(input.builtins) ? input.builtins.map((name) => builtinPatterns[name]).filter(Boolean).map((b) => [cloneRegex(b.pattern), b.mask]) : allBuiltinMaskers();
|
|
2253
|
+
return {
|
|
2254
|
+
...input,
|
|
2255
|
+
_maskers: maskers
|
|
2256
|
+
};
|
|
2257
|
+
}
|
|
2258
|
+
function allBuiltinMaskers() {
|
|
2259
|
+
return Object.values(builtinPatterns).map((b) => [cloneRegex(b.pattern), b.mask]);
|
|
2260
|
+
}
|
|
2261
|
+
function cloneRegex(re) {
|
|
2262
|
+
return new RegExp(re.source, re.flags);
|
|
2263
|
+
}
|
|
2264
|
+
function redactEvent(event, config) {
|
|
2265
|
+
const replacement = config.replacement ?? DEFAULT_REPLACEMENT;
|
|
2266
|
+
if (config.paths?.length)
|
|
2267
|
+
for (const path of config.paths)
|
|
2268
|
+
redactPath(event, path.split("."), replacement);
|
|
2269
|
+
if (config._maskers?.length)
|
|
2270
|
+
applyMaskersToTree(event, config._maskers);
|
|
2271
|
+
if (config.patterns?.length)
|
|
2272
|
+
redactPatterns(event, config.patterns, replacement);
|
|
2273
|
+
}
|
|
2274
|
+
function redactPath(obj, segments, replacement) {
|
|
2275
|
+
let current = obj;
|
|
2276
|
+
for (let i = 0;i < segments.length - 1; i++) {
|
|
2277
|
+
if (current === null || current === undefined || typeof current !== "object")
|
|
2278
|
+
return;
|
|
2279
|
+
current = current[segments[i]];
|
|
2280
|
+
}
|
|
2281
|
+
if (current === null || current === undefined || typeof current !== "object")
|
|
2282
|
+
return;
|
|
2283
|
+
const leaf = segments[segments.length - 1];
|
|
2284
|
+
if (leaf in current)
|
|
2285
|
+
current[leaf] = replacement;
|
|
2286
|
+
}
|
|
2287
|
+
function redactPatterns(obj, patterns, replacement) {
|
|
2288
|
+
if (obj === null || obj === undefined)
|
|
2289
|
+
return;
|
|
2290
|
+
if (Array.isArray(obj)) {
|
|
2291
|
+
for (let i = 0;i < obj.length; i++)
|
|
2292
|
+
if (typeof obj[i] === "string")
|
|
2293
|
+
obj[i] = applyPatterns(obj[i], patterns, replacement);
|
|
2294
|
+
else if (typeof obj[i] === "object")
|
|
2295
|
+
redactPatterns(obj[i], patterns, replacement);
|
|
2296
|
+
return;
|
|
2297
|
+
}
|
|
2298
|
+
if (typeof obj === "object") {
|
|
2299
|
+
const record = obj;
|
|
2300
|
+
for (const key in record) {
|
|
2301
|
+
const val = record[key];
|
|
2302
|
+
if (typeof val === "string")
|
|
2303
|
+
record[key] = applyPatterns(val, patterns, replacement);
|
|
2304
|
+
else if (typeof val === "object")
|
|
2305
|
+
redactPatterns(val, patterns, replacement);
|
|
2306
|
+
}
|
|
2307
|
+
}
|
|
2308
|
+
}
|
|
2309
|
+
function applyPatterns(value, patterns, replacement) {
|
|
2310
|
+
let result = value;
|
|
2311
|
+
for (const pattern of patterns) {
|
|
2312
|
+
pattern.lastIndex = 0;
|
|
2313
|
+
result = result.replace(pattern, replacement);
|
|
2314
|
+
}
|
|
2315
|
+
return result;
|
|
2316
|
+
}
|
|
2317
|
+
function applyMaskersToTree(obj, maskers) {
|
|
2318
|
+
if (obj === null || obj === undefined)
|
|
2319
|
+
return;
|
|
2320
|
+
if (Array.isArray(obj)) {
|
|
2321
|
+
for (let i = 0;i < obj.length; i++)
|
|
2322
|
+
if (typeof obj[i] === "string")
|
|
2323
|
+
obj[i] = applyMaskers(obj[i], maskers);
|
|
2324
|
+
else if (typeof obj[i] === "object")
|
|
2325
|
+
applyMaskersToTree(obj[i], maskers);
|
|
2326
|
+
return;
|
|
2327
|
+
}
|
|
2328
|
+
if (typeof obj === "object") {
|
|
2329
|
+
const record = obj;
|
|
2330
|
+
for (const key in record) {
|
|
2331
|
+
const val = record[key];
|
|
2332
|
+
if (typeof val === "string")
|
|
2333
|
+
record[key] = applyMaskers(val, maskers);
|
|
2334
|
+
else if (typeof val === "object")
|
|
2335
|
+
applyMaskersToTree(val, maskers);
|
|
2336
|
+
}
|
|
2337
|
+
}
|
|
2338
|
+
}
|
|
2339
|
+
function applyMaskers(value, maskers) {
|
|
2340
|
+
let result = value;
|
|
2341
|
+
for (const [pattern, mask] of maskers) {
|
|
2342
|
+
pattern.lastIndex = 0;
|
|
2343
|
+
result = result.replace(pattern, mask);
|
|
2344
|
+
}
|
|
2345
|
+
return result;
|
|
2346
|
+
}
|
|
2347
|
+
function isPlainObject(val) {
|
|
2348
|
+
return val !== null && typeof val === "object" && !Array.isArray(val);
|
|
2349
|
+
}
|
|
2350
|
+
var _tsDate = /* @__PURE__ */ new Date;
|
|
2351
|
+
function isoNow() {
|
|
2352
|
+
_tsDate.setTime(Date.now());
|
|
2353
|
+
return _tsDate.toISOString();
|
|
2354
|
+
}
|
|
2355
|
+
var POST_EMIT_FORK_HINT = "For intentional background work tied to this request, use log.fork('label', fn) when your integration supports it (see https://evlog.dev).";
|
|
2356
|
+
function warnPostEmit(method, detail) {
|
|
2357
|
+
console.warn(`[evlog] ${method} called after the wide event was emitted \u2014 ${detail} This data will not appear in observability. ${POST_EMIT_FORK_HINT}`);
|
|
2358
|
+
}
|
|
2359
|
+
function mergeInto(target, source) {
|
|
2360
|
+
for (const key in source) {
|
|
2361
|
+
const sourceVal = source[key];
|
|
2362
|
+
if (sourceVal === undefined || sourceVal === null)
|
|
2363
|
+
continue;
|
|
2364
|
+
const targetVal = target[key];
|
|
2365
|
+
if (isPlainObject(sourceVal) && isPlainObject(targetVal))
|
|
2366
|
+
mergeInto(targetVal, sourceVal);
|
|
2367
|
+
else if (Array.isArray(targetVal) && Array.isArray(sourceVal))
|
|
2368
|
+
target[key] = [...targetVal, ...sourceVal];
|
|
2369
|
+
else
|
|
2370
|
+
target[key] = sourceVal;
|
|
2371
|
+
}
|
|
2372
|
+
}
|
|
2373
|
+
var globalEnv = {
|
|
2374
|
+
service: "app",
|
|
2375
|
+
environment: "development"
|
|
2376
|
+
};
|
|
2377
|
+
var globalPretty = isDev();
|
|
2378
|
+
var globalSampling = {};
|
|
2379
|
+
var globalStringify = true;
|
|
2380
|
+
var globalDrain;
|
|
2381
|
+
var globalRedact;
|
|
2382
|
+
var globalEnabled = true;
|
|
2383
|
+
var globalSilent = false;
|
|
2384
|
+
var globalMinLevel = "debug";
|
|
2385
|
+
function initLogger(config = {}) {
|
|
2386
|
+
globalEnabled = config.enabled ?? true;
|
|
2387
|
+
const detected = detectEnvironment();
|
|
2388
|
+
globalEnv = {
|
|
2389
|
+
service: config.env?.service ?? detected.service ?? "app",
|
|
2390
|
+
environment: config.env?.environment ?? detected.environment ?? "development",
|
|
2391
|
+
version: config.env?.version ?? detected.version,
|
|
2392
|
+
commitHash: config.env?.commitHash ?? detected.commitHash,
|
|
2393
|
+
region: config.env?.region ?? detected.region
|
|
2394
|
+
};
|
|
2395
|
+
globalPretty = config.pretty ?? isDev();
|
|
2396
|
+
globalSampling = config.sampling ?? {};
|
|
2397
|
+
globalStringify = config.stringify ?? true;
|
|
2398
|
+
globalDrain = config.drain;
|
|
2399
|
+
globalRedact = resolveRedactConfig(config.redact ?? !isDev());
|
|
2400
|
+
globalSilent = config.silent ?? false;
|
|
2401
|
+
globalMinLevel = config.minLevel ?? "debug";
|
|
2402
|
+
if (globalSilent && !globalDrain && !config._suppressDrainWarning)
|
|
2403
|
+
console.warn("[evlog] silent mode is enabled but no drain is configured. Events will be built and sampled but not output anywhere. Set a drain via initLogger({ drain }) or a framework hook (evlog:drain).");
|
|
2404
|
+
}
|
|
2405
|
+
function shouldSample(level) {
|
|
2406
|
+
const { rates } = globalSampling;
|
|
2407
|
+
if (!rates)
|
|
2408
|
+
return true;
|
|
2409
|
+
const percentage = level === "error" && rates.error === undefined ? 100 : rates[level] ?? 100;
|
|
2410
|
+
if (percentage <= 0)
|
|
2411
|
+
return false;
|
|
2412
|
+
if (percentage >= 100)
|
|
2413
|
+
return true;
|
|
2414
|
+
return Math.random() * 100 < percentage;
|
|
2415
|
+
}
|
|
2416
|
+
function shouldKeep(ctx) {
|
|
2417
|
+
const { keep } = globalSampling;
|
|
2418
|
+
if (!keep?.length)
|
|
2419
|
+
return false;
|
|
2420
|
+
return keep.some((condition) => {
|
|
2421
|
+
if (condition.status !== undefined && ctx.status !== undefined && ctx.status >= condition.status)
|
|
2422
|
+
return true;
|
|
2423
|
+
if (condition.duration !== undefined && ctx.duration !== undefined && ctx.duration >= condition.duration)
|
|
2424
|
+
return true;
|
|
2425
|
+
if (condition.path && ctx.path && matchesPattern(ctx.path, condition.path))
|
|
2426
|
+
return true;
|
|
2427
|
+
return false;
|
|
2428
|
+
});
|
|
2429
|
+
}
|
|
2430
|
+
function emitWideEvent(level, event, deferDrain = false, ownsEvent = false) {
|
|
2431
|
+
if (!globalEnabled)
|
|
2432
|
+
return null;
|
|
2433
|
+
if (!ownsEvent) {
|
|
2434
|
+
if (!isLevelEnabled(level, globalMinLevel))
|
|
2435
|
+
return null;
|
|
2436
|
+
if (!shouldSample(level))
|
|
2437
|
+
return null;
|
|
2438
|
+
}
|
|
2439
|
+
let formatted;
|
|
2440
|
+
if (ownsEvent) {
|
|
2441
|
+
event.timestamp = isoNow();
|
|
2442
|
+
event.level = level;
|
|
2443
|
+
if (event.service === undefined)
|
|
2444
|
+
event.service = globalEnv.service;
|
|
2445
|
+
if (event.environment === undefined)
|
|
2446
|
+
event.environment = globalEnv.environment;
|
|
2447
|
+
if (globalEnv.version !== undefined && event.version === undefined)
|
|
2448
|
+
event.version = globalEnv.version;
|
|
2449
|
+
if (globalEnv.commitHash !== undefined && event.commitHash === undefined)
|
|
2450
|
+
event.commitHash = globalEnv.commitHash;
|
|
2451
|
+
if (globalEnv.region !== undefined && event.region === undefined)
|
|
2452
|
+
event.region = globalEnv.region;
|
|
2453
|
+
formatted = event;
|
|
2454
|
+
} else
|
|
2455
|
+
formatted = {
|
|
2456
|
+
timestamp: isoNow(),
|
|
2457
|
+
level,
|
|
2458
|
+
...globalEnv,
|
|
2459
|
+
...event
|
|
2460
|
+
};
|
|
2461
|
+
if (globalRedact)
|
|
2462
|
+
redactEvent(formatted, globalRedact);
|
|
2463
|
+
if (!globalSilent)
|
|
2464
|
+
if (globalPretty)
|
|
2465
|
+
prettyPrintWideEvent(formatted);
|
|
2466
|
+
else if (globalStringify)
|
|
2467
|
+
console[getConsoleMethod(level)](JSON.stringify(formatted));
|
|
2468
|
+
else
|
|
2469
|
+
console[getConsoleMethod(level)](formatted);
|
|
2470
|
+
if (globalDrain && !deferDrain)
|
|
2471
|
+
Promise.resolve(globalDrain({ event: formatted })).catch((err) => {
|
|
2472
|
+
console.error("[evlog] drain failed:", err);
|
|
2473
|
+
});
|
|
2474
|
+
return formatted;
|
|
2475
|
+
}
|
|
2476
|
+
function emitTaggedLog(level, tag, message) {
|
|
2477
|
+
if (!globalEnabled)
|
|
2478
|
+
return;
|
|
2479
|
+
if (globalPretty && !globalSilent) {
|
|
2480
|
+
if (!isLevelEnabled(level, globalMinLevel))
|
|
2481
|
+
return;
|
|
2482
|
+
if (!shouldSample(level))
|
|
2483
|
+
return;
|
|
2484
|
+
if (isClient()) {
|
|
2485
|
+
const levelColor = getCssLevelColor(level);
|
|
2486
|
+
const timestamp = isoNow().slice(11, 23);
|
|
2487
|
+
console.log(`%c${timestamp}%c %c[${escapeFormatString(tag)}]%c ${escapeFormatString(message)}`, cssColors.dim, cssColors.reset, levelColor, cssColors.reset);
|
|
2488
|
+
} else {
|
|
2489
|
+
const color = getLevelColor(level);
|
|
2490
|
+
const timestamp = isoNow().slice(11, 23);
|
|
2491
|
+
console.log(`${colors.dim}${timestamp}${colors.reset} ${color}[${tag}]${colors.reset} ${message}`);
|
|
2492
|
+
}
|
|
2493
|
+
return;
|
|
2494
|
+
}
|
|
2495
|
+
emitWideEvent(level, {
|
|
2496
|
+
tag,
|
|
2497
|
+
message
|
|
2498
|
+
});
|
|
2499
|
+
}
|
|
2500
|
+
function formatValue(value) {
|
|
2501
|
+
if (value === null || value === undefined)
|
|
2502
|
+
return String(value);
|
|
2503
|
+
if (typeof value === "object") {
|
|
2504
|
+
const pairs = [];
|
|
2505
|
+
for (const [k, v] of Object.entries(value))
|
|
2506
|
+
if (v !== undefined && v !== null)
|
|
2507
|
+
if (typeof v === "object")
|
|
2508
|
+
pairs.push(`${k}=${JSON.stringify(v)}`);
|
|
2509
|
+
else
|
|
2510
|
+
pairs.push(`${k}=${v}`);
|
|
2511
|
+
return pairs.join(" ");
|
|
2512
|
+
}
|
|
2513
|
+
return String(value);
|
|
2514
|
+
}
|
|
2515
|
+
function formatCost(cost) {
|
|
2516
|
+
if (cost < 0.01)
|
|
2517
|
+
return `$${cost.toFixed(6)}`;
|
|
2518
|
+
if (cost < 1)
|
|
2519
|
+
return `$${cost.toFixed(4)}`;
|
|
2520
|
+
return `$${cost.toFixed(2)}`;
|
|
2521
|
+
}
|
|
2522
|
+
function buildAIEntries(ai) {
|
|
2523
|
+
const entries = [];
|
|
2524
|
+
const headerParts = [];
|
|
2525
|
+
if (ai.model) {
|
|
2526
|
+
let m = String(ai.model);
|
|
2527
|
+
if (ai.provider)
|
|
2528
|
+
m += ` (${ai.provider})`;
|
|
2529
|
+
headerParts.push(m);
|
|
2530
|
+
}
|
|
2531
|
+
if (ai.calls)
|
|
2532
|
+
headerParts.push(`${ai.calls} call${ai.calls > 1 ? "s" : ""}`);
|
|
2533
|
+
if (ai.steps && ai.steps > 1)
|
|
2534
|
+
headerParts.push(`${ai.steps} steps`);
|
|
2535
|
+
entries.push({
|
|
2536
|
+
key: "ai",
|
|
2537
|
+
value: headerParts.join(" \xB7 ")
|
|
2538
|
+
});
|
|
2539
|
+
const inputTokens = ai.inputTokens;
|
|
2540
|
+
const outputTokens = ai.outputTokens;
|
|
2541
|
+
const totalTokens = ai.totalTokens;
|
|
2542
|
+
if (inputTokens !== undefined && outputTokens !== undefined) {
|
|
2543
|
+
let tokLine = `${inputTokens} in \u2192 ${outputTokens} out`;
|
|
2544
|
+
if (totalTokens)
|
|
2545
|
+
tokLine += ` (${totalTokens} total)`;
|
|
2546
|
+
const extras = [];
|
|
2547
|
+
if (ai.cacheReadTokens)
|
|
2548
|
+
extras.push(`${ai.cacheReadTokens} cache read`);
|
|
2549
|
+
if (ai.cacheWriteTokens)
|
|
2550
|
+
extras.push(`${ai.cacheWriteTokens} cache write`);
|
|
2551
|
+
if (ai.reasoningTokens)
|
|
2552
|
+
extras.push(`${ai.reasoningTokens} reasoning`);
|
|
2553
|
+
if (extras.length)
|
|
2554
|
+
tokLine += ` \xB7 ${extras.join(" \xB7 ")}`;
|
|
2555
|
+
entries.push({
|
|
2556
|
+
key: "ai.tokens",
|
|
2557
|
+
value: tokLine
|
|
2558
|
+
});
|
|
2559
|
+
}
|
|
2560
|
+
const msFirst = ai.msToFirstChunk;
|
|
2561
|
+
const msFinish = ai.msToFinish;
|
|
2562
|
+
const tps = ai.tokensPerSecond;
|
|
2563
|
+
if (msFirst !== undefined || msFinish !== undefined) {
|
|
2564
|
+
const parts = [];
|
|
2565
|
+
if (msFirst !== undefined)
|
|
2566
|
+
parts.push(`${formatDuration(msFirst)} to first chunk`);
|
|
2567
|
+
if (msFinish !== undefined)
|
|
2568
|
+
parts.push(`${formatDuration(msFinish)} total`);
|
|
2569
|
+
let streamLine = parts.join(" \u2192 ");
|
|
2570
|
+
if (tps)
|
|
2571
|
+
streamLine += ` \xB7 ${tps} tok/s`;
|
|
2572
|
+
entries.push({
|
|
2573
|
+
key: "ai.streaming",
|
|
2574
|
+
value: streamLine
|
|
2575
|
+
});
|
|
2576
|
+
}
|
|
2577
|
+
if (ai.estimatedCost !== undefined)
|
|
2578
|
+
entries.push({
|
|
2579
|
+
key: "ai.cost",
|
|
2580
|
+
value: formatCost(ai.estimatedCost)
|
|
2581
|
+
});
|
|
2582
|
+
if (ai.totalDurationMs !== undefined)
|
|
2583
|
+
entries.push({
|
|
2584
|
+
key: "ai.totalDuration",
|
|
2585
|
+
value: formatDuration(ai.totalDurationMs)
|
|
2586
|
+
});
|
|
2587
|
+
const toolCalls = ai.toolCalls;
|
|
2588
|
+
const tools = ai.tools;
|
|
2589
|
+
const hasInputs = toolCalls?.length ? typeof toolCalls[0] === "object" : false;
|
|
2590
|
+
if (tools?.length) {
|
|
2591
|
+
const children = tools.map((t, idx) => {
|
|
2592
|
+
const mark = t.success ? "\u2713" : "\u2717";
|
|
2593
|
+
let line = `${t.name} ${formatDuration(t.durationMs)} ${mark}`;
|
|
2594
|
+
if (t.error)
|
|
2595
|
+
line += ` ${t.error}`;
|
|
2596
|
+
if (hasInputs && toolCalls && idx < toolCalls.length) {
|
|
2597
|
+
const tc = toolCalls[idx];
|
|
2598
|
+
const inputStr = typeof tc.input === "string" ? tc.input : JSON.stringify(tc.input);
|
|
2599
|
+
const truncated = inputStr.length > 100 ? `${inputStr.slice(0, 100)}\u2026` : inputStr;
|
|
2600
|
+
line += ` ${truncated}`;
|
|
2601
|
+
}
|
|
2602
|
+
return line;
|
|
2603
|
+
});
|
|
2604
|
+
entries.push({
|
|
2605
|
+
key: "ai.tools",
|
|
2606
|
+
value: "",
|
|
2607
|
+
children
|
|
2608
|
+
});
|
|
2609
|
+
} else if (toolCalls?.length)
|
|
2610
|
+
if (hasInputs) {
|
|
2611
|
+
const children = toolCalls.map((tc) => {
|
|
2612
|
+
const inputStr = typeof tc.input === "string" ? tc.input : JSON.stringify(tc.input);
|
|
2613
|
+
const truncated = inputStr.length > 100 ? `${inputStr.slice(0, 100)}\u2026` : inputStr;
|
|
2614
|
+
return `${tc.name}(${truncated})`;
|
|
2615
|
+
});
|
|
2616
|
+
entries.push({
|
|
2617
|
+
key: "ai.tools",
|
|
2618
|
+
value: "",
|
|
2619
|
+
children
|
|
2620
|
+
});
|
|
2621
|
+
} else
|
|
2622
|
+
entries.push({
|
|
2623
|
+
key: "ai.tools",
|
|
2624
|
+
value: toolCalls.join(", ")
|
|
2625
|
+
});
|
|
2626
|
+
const stepsUsage = ai.stepsUsage;
|
|
2627
|
+
if (stepsUsage?.length) {
|
|
2628
|
+
const allSameModel = stepsUsage.every((s) => s.model === stepsUsage[0].model);
|
|
2629
|
+
const children = stepsUsage.map((s) => {
|
|
2630
|
+
let line = `${allSameModel ? "" : `${s.model} `}${s.inputTokens} in \u2192 ${s.outputTokens} out`;
|
|
2631
|
+
const stepTools = s.toolCalls;
|
|
2632
|
+
if (stepTools?.length)
|
|
2633
|
+
line += ` [${stepTools.join(", ")}]`;
|
|
2634
|
+
return line;
|
|
2635
|
+
});
|
|
2636
|
+
entries.push({
|
|
2637
|
+
key: "ai.steps",
|
|
2638
|
+
value: "",
|
|
2639
|
+
children
|
|
2640
|
+
});
|
|
2641
|
+
} else if (ai.steps && ai.steps > 1)
|
|
2642
|
+
entries.push({
|
|
2643
|
+
key: "ai.steps",
|
|
2644
|
+
value: String(ai.steps)
|
|
2645
|
+
});
|
|
2646
|
+
const embedding = ai.embedding;
|
|
2647
|
+
if (embedding) {
|
|
2648
|
+
const parts = [];
|
|
2649
|
+
if (embedding.model)
|
|
2650
|
+
parts.push(String(embedding.model));
|
|
2651
|
+
parts.push(`${embedding.tokens} tokens`);
|
|
2652
|
+
if (embedding.dimensions)
|
|
2653
|
+
parts.push(`${embedding.dimensions}d`);
|
|
2654
|
+
if (embedding.count)
|
|
2655
|
+
parts.push(`${embedding.count} items`);
|
|
2656
|
+
entries.push({
|
|
2657
|
+
key: "ai.embedding",
|
|
2658
|
+
value: parts.join(" \xB7 ")
|
|
2659
|
+
});
|
|
2660
|
+
}
|
|
2661
|
+
if (ai.finishReason)
|
|
2662
|
+
entries.push({
|
|
2663
|
+
key: "ai.finishReason",
|
|
2664
|
+
value: String(ai.finishReason)
|
|
2665
|
+
});
|
|
2666
|
+
if (ai.error)
|
|
2667
|
+
entries.push({
|
|
2668
|
+
key: "ai.error",
|
|
2669
|
+
value: String(ai.error)
|
|
2670
|
+
});
|
|
2671
|
+
if (ai.responseId)
|
|
2672
|
+
entries.push({
|
|
2673
|
+
key: "ai.responseId",
|
|
2674
|
+
value: String(ai.responseId)
|
|
2675
|
+
});
|
|
2676
|
+
return entries;
|
|
2677
|
+
}
|
|
2678
|
+
function prettyPrintWideEvent(event) {
|
|
2679
|
+
const { timestamp, level, service, environment, version, ...rest } = event;
|
|
2680
|
+
const ts = timestamp.slice(11, 23);
|
|
2681
|
+
const browser = isClient();
|
|
2682
|
+
const parts = [];
|
|
2683
|
+
const styles = [];
|
|
2684
|
+
if (browser) {
|
|
2685
|
+
const lc = getCssLevelColor(level);
|
|
2686
|
+
parts.push(`%c${ts}%c %c${level.toUpperCase()}%c %c[${escapeFormatString(String(service))}]%c`);
|
|
2687
|
+
styles.push(cssColors.dim, cssColors.reset, lc, cssColors.reset, cssColors.cyan, cssColors.reset);
|
|
2688
|
+
} else {
|
|
2689
|
+
const lc = getLevelColor(level);
|
|
2690
|
+
parts.push(`${colors.dim}${ts}${colors.reset} ${lc}${level.toUpperCase()}${colors.reset} ${colors.cyan}[${service}]${colors.reset}`);
|
|
2691
|
+
}
|
|
2692
|
+
if (rest.method && rest.path) {
|
|
2693
|
+
parts.push(browser ? ` ${escapeFormatString(String(rest.method))} ${escapeFormatString(String(rest.path))}` : ` ${rest.method} ${rest.path}`);
|
|
2694
|
+
delete rest.method;
|
|
2695
|
+
delete rest.path;
|
|
2696
|
+
}
|
|
2697
|
+
if (rest.status) {
|
|
2698
|
+
const sc = browser ? rest.status >= 400 ? cssColors.red : cssColors.green : rest.status >= 400 ? colors.red : colors.green;
|
|
2699
|
+
if (browser) {
|
|
2700
|
+
parts.push(` %c${rest.status}%c`);
|
|
2701
|
+
styles.push(sc, cssColors.reset);
|
|
2702
|
+
} else
|
|
2703
|
+
parts.push(` ${sc}${rest.status}${colors.reset}`);
|
|
2704
|
+
delete rest.status;
|
|
2705
|
+
}
|
|
2706
|
+
if (rest.duration) {
|
|
2707
|
+
if (browser) {
|
|
2708
|
+
parts.push(` %c${escapeFormatString(`in ${rest.duration}`)}%c`);
|
|
2709
|
+
styles.push(cssColors.dim, cssColors.reset);
|
|
2710
|
+
} else
|
|
2711
|
+
parts.push(` ${colors.dim}in ${rest.duration}${colors.reset}`);
|
|
2712
|
+
delete rest.duration;
|
|
2713
|
+
}
|
|
2714
|
+
console.log(parts.join(""), ...styles);
|
|
2715
|
+
const aiData = rest.ai;
|
|
2716
|
+
if (aiData && typeof aiData === "object")
|
|
2717
|
+
delete rest.ai;
|
|
2718
|
+
const restEntries = Object.entries(rest).filter(([_, v]) => v !== undefined);
|
|
2719
|
+
const aiEntries = aiData ? buildAIEntries(aiData) : [];
|
|
2720
|
+
const allEntries = [...restEntries.map(([key, value]) => ({
|
|
2721
|
+
key,
|
|
2722
|
+
value: formatValue(value)
|
|
2723
|
+
})), ...aiEntries];
|
|
2724
|
+
for (let i = 0;i < allEntries.length; i++) {
|
|
2725
|
+
const entry = allEntries[i];
|
|
2726
|
+
const hasChildren = entry.children && entry.children.length > 0;
|
|
2727
|
+
const prefix = i === allEntries.length - 1 && !hasChildren ? "\u2514\u2500" : "\u251C\u2500";
|
|
2728
|
+
if (browser) {
|
|
2729
|
+
const val = entry.value ? ` ${escapeFormatString(entry.value)}` : "";
|
|
2730
|
+
console.log(` %c${prefix}%c %c${escapeFormatString(entry.key)}:%c${val}`, cssColors.dim, cssColors.reset, cssColors.cyan, cssColors.reset);
|
|
2731
|
+
} else {
|
|
2732
|
+
const val = entry.value ? ` ${entry.value}` : "";
|
|
2733
|
+
console.log(` ${colors.dim}${prefix}${colors.reset} ${colors.cyan}${entry.key}:${colors.reset}${val}`);
|
|
2734
|
+
}
|
|
2735
|
+
if (hasChildren) {
|
|
2736
|
+
const connector = i === allEntries.length - 1 ? " " : "\u2502";
|
|
2737
|
+
for (let j = 0;j < entry.children.length; j++) {
|
|
2738
|
+
const child = entry.children[j];
|
|
2739
|
+
const childPrefix = j === entry.children.length - 1 ? "\u2514\u2500" : "\u251C\u2500";
|
|
2740
|
+
if (browser)
|
|
2741
|
+
console.log(` %c${connector} ${childPrefix}%c ${escapeFormatString(child)}`, cssColors.dim, cssColors.reset);
|
|
2742
|
+
else
|
|
2743
|
+
console.log(` ${colors.dim}${connector} ${childPrefix}${colors.reset} ${child}`);
|
|
2744
|
+
}
|
|
2745
|
+
}
|
|
2746
|
+
}
|
|
2747
|
+
}
|
|
2748
|
+
function createLogMethod(level) {
|
|
2749
|
+
return function logMethod(tagOrEvent, message) {
|
|
2750
|
+
if (typeof tagOrEvent === "string" && message !== undefined)
|
|
2751
|
+
emitTaggedLog(level, tagOrEvent, message);
|
|
2752
|
+
else if (typeof tagOrEvent === "object")
|
|
2753
|
+
emitWideEvent(level, tagOrEvent);
|
|
2754
|
+
else
|
|
2755
|
+
emitTaggedLog(level, "log", String(tagOrEvent));
|
|
2756
|
+
};
|
|
2757
|
+
}
|
|
2758
|
+
var _log = {
|
|
2759
|
+
info: createLogMethod("info"),
|
|
2760
|
+
error: createLogMethod("error"),
|
|
2761
|
+
warn: createLogMethod("warn"),
|
|
2762
|
+
debug: createLogMethod("debug")
|
|
2763
|
+
};
|
|
2764
|
+
var noopLogger = {
|
|
2765
|
+
set() {},
|
|
2766
|
+
error() {},
|
|
2767
|
+
info() {},
|
|
2768
|
+
warn() {},
|
|
2769
|
+
emit() {
|
|
2770
|
+
return null;
|
|
2771
|
+
},
|
|
2772
|
+
getContext() {
|
|
2773
|
+
return {};
|
|
2774
|
+
}
|
|
2775
|
+
};
|
|
2776
|
+
function createLogger(initialContext = {}, internalOptions) {
|
|
2777
|
+
if (!globalEnabled)
|
|
2778
|
+
return noopLogger;
|
|
2779
|
+
const deferDrain = internalOptions?._deferDrain ?? false;
|
|
2780
|
+
const startTime = Date.now();
|
|
2781
|
+
const context = { ...initialContext };
|
|
2782
|
+
let hasError = false;
|
|
2783
|
+
let hasWarn = false;
|
|
2784
|
+
let emitted = false;
|
|
2785
|
+
function addLog(level, message) {
|
|
2786
|
+
if (!Array.isArray(context.requestLogs))
|
|
2787
|
+
context.requestLogs = [];
|
|
2788
|
+
context.requestLogs.push({
|
|
2789
|
+
level,
|
|
2790
|
+
message,
|
|
2791
|
+
timestamp: isoNow()
|
|
2792
|
+
});
|
|
2793
|
+
}
|
|
2794
|
+
return {
|
|
2795
|
+
set(data) {
|
|
2796
|
+
if (emitted) {
|
|
2797
|
+
const keys = Object.keys(data);
|
|
2798
|
+
warnPostEmit("log.set()", `Keys dropped: ${keys.length ? keys.join(", ") : "(empty)"}.`);
|
|
2799
|
+
return;
|
|
2800
|
+
}
|
|
2801
|
+
mergeInto(context, data);
|
|
2802
|
+
},
|
|
2803
|
+
error(error, errorContext) {
|
|
2804
|
+
if (emitted) {
|
|
2805
|
+
warnPostEmit("log.error()", `Keys dropped: ${(errorContext ? [...Object.keys(errorContext), "error"] : ["error"]).join(", ")}.`);
|
|
2806
|
+
return;
|
|
2807
|
+
}
|
|
2808
|
+
hasError = true;
|
|
2809
|
+
const err = typeof error === "string" ? new Error(error) : error;
|
|
2810
|
+
if (errorContext)
|
|
2811
|
+
mergeInto(context, errorContext);
|
|
2812
|
+
const errorObj = {
|
|
2813
|
+
name: err.name,
|
|
2814
|
+
message: err.message,
|
|
2815
|
+
stack: err.stack
|
|
2816
|
+
};
|
|
2817
|
+
const errRecord = err;
|
|
2818
|
+
for (const k of [
|
|
2819
|
+
"status",
|
|
2820
|
+
"statusText",
|
|
2821
|
+
"statusCode",
|
|
2822
|
+
"statusMessage",
|
|
2823
|
+
"data",
|
|
2824
|
+
"cause",
|
|
2825
|
+
"internal"
|
|
2826
|
+
])
|
|
2827
|
+
if (k in err)
|
|
2828
|
+
errorObj[k] = errRecord[k];
|
|
2829
|
+
if (isPlainObject(context.error))
|
|
2830
|
+
mergeInto(context.error, errorObj);
|
|
2831
|
+
else
|
|
2832
|
+
context.error = errorObj;
|
|
2833
|
+
},
|
|
2834
|
+
info(message, infoContext) {
|
|
2835
|
+
if (emitted) {
|
|
2836
|
+
warnPostEmit("log.info()", `Keys dropped: ${(infoContext ? ["message", ...Object.keys(infoContext).filter((k) => k !== "requestLogs")] : ["message"]).join(", ")}.`);
|
|
2837
|
+
return;
|
|
2838
|
+
}
|
|
2839
|
+
addLog("info", message);
|
|
2840
|
+
if (infoContext) {
|
|
2841
|
+
const { requestLogs: _, ...rest } = infoContext;
|
|
2842
|
+
mergeInto(context, rest);
|
|
2843
|
+
}
|
|
2844
|
+
},
|
|
2845
|
+
warn(message, warnContext) {
|
|
2846
|
+
if (emitted) {
|
|
2847
|
+
warnPostEmit("log.warn()", `Keys dropped: ${(warnContext ? ["message", ...Object.keys(warnContext).filter((k) => k !== "requestLogs")] : ["message"]).join(", ")}.`);
|
|
2848
|
+
return;
|
|
2849
|
+
}
|
|
2850
|
+
hasWarn = true;
|
|
2851
|
+
addLog("warn", message);
|
|
2852
|
+
if (warnContext) {
|
|
2853
|
+
const { requestLogs: _, ...rest } = warnContext;
|
|
2854
|
+
mergeInto(context, rest);
|
|
2855
|
+
}
|
|
2856
|
+
},
|
|
2857
|
+
emit(overrides) {
|
|
2858
|
+
if (emitted) {
|
|
2859
|
+
warnPostEmit("log.emit()", "Ignoring duplicate emit.");
|
|
2860
|
+
return null;
|
|
2861
|
+
}
|
|
2862
|
+
const durationMs = Date.now() - startTime;
|
|
2863
|
+
const level = hasError ? "error" : hasWarn ? "warn" : "info";
|
|
2864
|
+
let forceKeep = false;
|
|
2865
|
+
if (overrides?._forceKeep)
|
|
2866
|
+
forceKeep = true;
|
|
2867
|
+
else if (globalSampling.keep?.length)
|
|
2868
|
+
forceKeep = shouldKeep({
|
|
2869
|
+
status: overrides?.status ?? context.status,
|
|
2870
|
+
duration: durationMs,
|
|
2871
|
+
path: context.path,
|
|
2872
|
+
method: context.method,
|
|
2873
|
+
context
|
|
2874
|
+
});
|
|
2875
|
+
if (!forceKeep && !shouldSample(level)) {
|
|
2876
|
+
emitted = true;
|
|
2877
|
+
return null;
|
|
2878
|
+
}
|
|
2879
|
+
if (overrides) {
|
|
2880
|
+
const obj = overrides;
|
|
2881
|
+
for (const key in obj)
|
|
2882
|
+
if (key !== "_forceKeep")
|
|
2883
|
+
context[key] = obj[key];
|
|
2884
|
+
}
|
|
2885
|
+
context.duration = formatDuration(durationMs);
|
|
2886
|
+
const wide = emitWideEvent(level, context, deferDrain, true);
|
|
2887
|
+
emitted = true;
|
|
2888
|
+
return wide;
|
|
2889
|
+
},
|
|
2890
|
+
getContext() {
|
|
2891
|
+
return { ...context };
|
|
2892
|
+
}
|
|
2893
|
+
};
|
|
2894
|
+
}
|
|
2895
|
+
if (typeof __EVLOG_CONFIG__ !== "undefined")
|
|
2896
|
+
initLogger(__EVLOG_CONFIG__);
|
|
2897
|
+
// src/link.tsx
|
|
2898
|
+
import {
|
|
2899
|
+
createContext,
|
|
2900
|
+
createElement,
|
|
2901
|
+
useCallback,
|
|
2902
|
+
useContext,
|
|
2903
|
+
useEffect,
|
|
2904
|
+
useRef,
|
|
2905
|
+
useState
|
|
2906
|
+
} from "react";
|
|
2907
|
+
var RouterContext = createContext(null);
|
|
2908
|
+
|
|
2909
|
+
// src/render/cache.ts
|
|
2910
|
+
import { AsyncLocalStorage } from "async_hooks";
|
|
2911
|
+
var MAX_SSG_CACHE_SIZE = 1000;
|
|
2912
|
+
var isrCache = new Map;
|
|
2913
|
+
var ssgCache = new Map;
|
|
2914
|
+
function evictOldest(map, maxSize) {
|
|
2915
|
+
if (map.size > maxSize) {
|
|
2916
|
+
const oldest = map.keys().next().value;
|
|
2917
|
+
if (oldest !== undefined) {
|
|
2918
|
+
map.delete(oldest);
|
|
2919
|
+
}
|
|
2920
|
+
}
|
|
2921
|
+
}
|
|
2922
|
+
function getSSGCache(key) {
|
|
2923
|
+
const entry = ssgCache.get(key);
|
|
2924
|
+
if (entry !== undefined) {
|
|
2925
|
+
ssgCache.delete(key);
|
|
2926
|
+
ssgCache.set(key, entry);
|
|
2927
|
+
}
|
|
2928
|
+
return entry;
|
|
2929
|
+
}
|
|
2930
|
+
function setSSGCache(key, entry) {
|
|
2931
|
+
ssgCache.delete(key);
|
|
2932
|
+
ssgCache.set(key, entry);
|
|
2933
|
+
evictOldest(ssgCache, MAX_SSG_CACHE_SIZE);
|
|
2934
|
+
}
|
|
2935
|
+
var _requestInvalidationScope = new AsyncLocalStorage;
|
|
2936
|
+
var _globalPendingInvalidations = new Set;
|
|
2937
|
+
|
|
2938
|
+
// src/render/element.tsx
|
|
2939
|
+
import { jsxDEV } from "react/jsx-dev-runtime";
|
|
2940
|
+
function buildElement(route, data, rootLayout) {
|
|
2941
|
+
const Component = route.page.component;
|
|
2942
|
+
let element = /* @__PURE__ */ jsxDEV(Component, {
|
|
2943
|
+
...data
|
|
2944
|
+
}, undefined, false, undefined, this);
|
|
2945
|
+
for (let i = route.routeChain.length - 1;i >= 1; i--) {
|
|
2946
|
+
const routeEntry = route.routeChain[i];
|
|
2947
|
+
if (routeEntry?.layout) {
|
|
2948
|
+
const Layout = routeEntry.layout;
|
|
2949
|
+
element = /* @__PURE__ */ jsxDEV(Layout, {
|
|
2950
|
+
...data,
|
|
2951
|
+
children: element
|
|
2952
|
+
}, undefined, false, undefined, this);
|
|
2953
|
+
}
|
|
2954
|
+
}
|
|
2955
|
+
if (rootLayout.layout) {
|
|
2956
|
+
const RootLayoutComponent = rootLayout.layout;
|
|
2957
|
+
element = /* @__PURE__ */ jsxDEV(RootLayoutComponent, {
|
|
2958
|
+
...data,
|
|
2959
|
+
children: element
|
|
2960
|
+
}, undefined, false, undefined, this);
|
|
2961
|
+
}
|
|
2962
|
+
return element;
|
|
2963
|
+
}
|
|
2964
|
+
|
|
2965
|
+
// src/context-logger.ts
|
|
2966
|
+
import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
|
|
2967
|
+
|
|
2968
|
+
// ../../node_modules/.bun/evlog@2.13.0+449e6d239244fccb/node_modules/evlog/dist/elysia/index.mjs
|
|
2969
|
+
import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
|
|
2970
|
+
import { Elysia } from "elysia";
|
|
2971
|
+
var storage = new AsyncLocalStorage2;
|
|
2972
|
+
var activeLoggers = /* @__PURE__ */ new WeakSet;
|
|
2973
|
+
function useLogger2() {
|
|
2974
|
+
const logger = storage.getStore();
|
|
2975
|
+
if (!logger || !activeLoggers.has(logger))
|
|
2976
|
+
throw new Error("[evlog] useLogger() was called outside of an evlog plugin context. Make sure app.use(evlog()) is registered before your routes.");
|
|
2977
|
+
return logger;
|
|
2978
|
+
}
|
|
2979
|
+
|
|
2980
|
+
// src/context-logger.ts
|
|
2981
|
+
var noopLogger2 = {
|
|
2982
|
+
set: () => {},
|
|
2983
|
+
error: () => {},
|
|
2984
|
+
info: () => {},
|
|
2985
|
+
warn: () => {},
|
|
2986
|
+
emit: () => null,
|
|
2987
|
+
getContext: () => ({}),
|
|
2988
|
+
fork: (_label, fn) => fn()
|
|
2989
|
+
};
|
|
2990
|
+
var syntheticRenderStorage = new AsyncLocalStorage3;
|
|
2991
|
+
function useLogger3() {
|
|
2992
|
+
try {
|
|
2993
|
+
return useLogger2();
|
|
2994
|
+
} catch {
|
|
2995
|
+
return syntheticRenderStorage.getStore() ?? noopLogger2;
|
|
2996
|
+
}
|
|
2997
|
+
}
|
|
2998
|
+
async function runInSyntheticRenderScope(fn, initialContext) {
|
|
2999
|
+
const logger = createLogger(initialContext);
|
|
3000
|
+
try {
|
|
3001
|
+
const result = await syntheticRenderStorage.run(logger, () => Promise.resolve(fn()));
|
|
3002
|
+
logger.emit();
|
|
3003
|
+
return result;
|
|
3004
|
+
} catch (err) {
|
|
3005
|
+
logger.error(err instanceof Error ? err : new Error(String(err)));
|
|
3006
|
+
logger.emit();
|
|
3007
|
+
throw err;
|
|
3008
|
+
}
|
|
3009
|
+
}
|
|
3010
|
+
|
|
3011
|
+
// src/render/loaders.ts
|
|
3012
|
+
function createLoaderCtx(ctx, accumulatedParentPromise) {
|
|
3013
|
+
const cache = new Map;
|
|
3014
|
+
return new Proxy(ctx, {
|
|
3015
|
+
get(target, prop) {
|
|
3016
|
+
if (typeof prop !== "string") {
|
|
3017
|
+
return Reflect.get(target, prop);
|
|
3018
|
+
}
|
|
3019
|
+
if (prop === "then" || prop === "catch" || prop === "finally" || prop === "toJSON") {
|
|
3020
|
+
return Reflect.get(target, prop);
|
|
3021
|
+
}
|
|
3022
|
+
if (Object.hasOwn(target, prop)) {
|
|
3023
|
+
return target[prop];
|
|
3024
|
+
}
|
|
3025
|
+
let entry = cache.get(prop);
|
|
3026
|
+
if (!entry) {
|
|
3027
|
+
entry = accumulatedParentPromise.then((data) => data[prop]);
|
|
3028
|
+
cache.set(prop, entry);
|
|
3029
|
+
}
|
|
3030
|
+
return entry;
|
|
3031
|
+
}
|
|
3032
|
+
});
|
|
3033
|
+
}
|
|
3034
|
+
async function runLoaders(route, ctx, _rootLayout) {
|
|
3035
|
+
try {
|
|
3036
|
+
const ctxRecord = { ...ctx, log: useLogger3() };
|
|
3037
|
+
const loaderMap = new Map;
|
|
3038
|
+
let accumulatedParentPromise = Promise.resolve({});
|
|
3039
|
+
for (const r of route.routeChain) {
|
|
3040
|
+
const parentAccum = accumulatedParentPromise;
|
|
3041
|
+
if (r.loader) {
|
|
3042
|
+
const loaderCtx = createLoaderCtx(ctxRecord, parentAccum);
|
|
3043
|
+
const loaderPromise = Promise.resolve(r.loader(loaderCtx)).then((res) => res ?? {});
|
|
3044
|
+
loaderMap.set(r, loaderPromise);
|
|
3045
|
+
accumulatedParentPromise = Promise.all([parentAccum, loaderPromise]).then(([acc, own]) => ({
|
|
3046
|
+
...acc,
|
|
3047
|
+
...own
|
|
3048
|
+
}));
|
|
3049
|
+
accumulatedParentPromise.catch(() => {});
|
|
3050
|
+
}
|
|
3051
|
+
}
|
|
3052
|
+
const pageCtx = createLoaderCtx(ctxRecord, accumulatedParentPromise);
|
|
3053
|
+
const pagePromise = route.page?.loader ? Promise.resolve(route.page.loader(pageCtx)).then((r) => r ?? {}) : Promise.resolve({});
|
|
3054
|
+
const results = await Promise.all([...loaderMap.values(), pagePromise]);
|
|
3055
|
+
const data = Object.assign({}, ...results);
|
|
3056
|
+
const headers = {};
|
|
3057
|
+
Object.assign(headers, ctx.set.headers);
|
|
3058
|
+
return { type: "data", data, headers };
|
|
3059
|
+
} catch (err) {
|
|
3060
|
+
if (err instanceof Response) {
|
|
3061
|
+
return { type: "redirect", response: err };
|
|
3062
|
+
}
|
|
3063
|
+
throw err;
|
|
3064
|
+
}
|
|
3065
|
+
}
|
|
3066
|
+
|
|
3067
|
+
// src/render/template.ts
|
|
3068
|
+
import { readFileSync as readFileSync3 } from "fs";
|
|
3069
|
+
var _prodTemplatePath = null;
|
|
3070
|
+
var _prodTemplateContent = null;
|
|
3071
|
+
var _devTemplateCache = null;
|
|
3072
|
+
var DEV_TEMPLATE_TTL_MS = 1000;
|
|
3073
|
+
async function getDevTemplate(origin) {
|
|
3074
|
+
if (_devTemplateCache && Date.now() - _devTemplateCache.ts < DEV_TEMPLATE_TTL_MS) {
|
|
3075
|
+
return _devTemplateCache.html;
|
|
3076
|
+
}
|
|
3077
|
+
const r = await fetch(`${origin}/_bun_hmr_entry`);
|
|
3078
|
+
if (!r.ok) {
|
|
3079
|
+
throw new Error(`/_bun_hmr_entry returned ${r.status}`);
|
|
3080
|
+
}
|
|
3081
|
+
const html = await r.text();
|
|
3082
|
+
_devTemplateCache = { html, ts: Date.now() };
|
|
3083
|
+
return html;
|
|
3084
|
+
}
|
|
3085
|
+
function setProductionTemplateContent(content) {
|
|
3086
|
+
_prodTemplatePath = null;
|
|
3087
|
+
_prodTemplateContent = content;
|
|
3088
|
+
}
|
|
3089
|
+
function getProductionTemplate() {
|
|
3090
|
+
if (_prodTemplateContent !== null) {
|
|
3091
|
+
return _prodTemplateContent;
|
|
3092
|
+
}
|
|
3093
|
+
if (!_prodTemplatePath) {
|
|
3094
|
+
return null;
|
|
3095
|
+
}
|
|
3096
|
+
try {
|
|
3097
|
+
_prodTemplateContent = readFileSync3(_prodTemplatePath, "utf8");
|
|
3098
|
+
return _prodTemplateContent;
|
|
3099
|
+
} catch {
|
|
3100
|
+
return null;
|
|
3101
|
+
}
|
|
3102
|
+
}
|
|
3103
|
+
// src/runtime-env.ts
|
|
3104
|
+
var IS_DEV = true;
|
|
3105
|
+
|
|
3106
|
+
// src/render/index.ts
|
|
3107
|
+
async function prepareRender(route, ctx, root, basePath) {
|
|
3108
|
+
const loaderStart = Date.now();
|
|
3109
|
+
const loaderResult = await runLoaders(route, ctx, root.route);
|
|
3110
|
+
const loader_ms = Date.now() - loaderStart;
|
|
3111
|
+
if (loaderResult.type === "redirect") {
|
|
3112
|
+
return loaderResult.response;
|
|
3113
|
+
}
|
|
3114
|
+
const { data, headers } = loaderResult;
|
|
3115
|
+
const componentProps = {
|
|
3116
|
+
...data,
|
|
3117
|
+
params: ctx.params,
|
|
3118
|
+
query: ctx.query,
|
|
3119
|
+
path: ctx.path
|
|
3120
|
+
};
|
|
3121
|
+
const headData = buildHeadInjection(route.page?.head?.(componentProps));
|
|
3122
|
+
const prodTemplate = getProductionTemplate();
|
|
3123
|
+
const template = prodTemplate ?? (IS_DEV ? await getDevTemplate(new URL(ctx.request.url).origin) : generateIndexHtml());
|
|
3124
|
+
let element = buildElement(route, componentProps, root.route);
|
|
3125
|
+
if (basePath !== undefined) {
|
|
3126
|
+
const ssrContext = {
|
|
3127
|
+
basePath,
|
|
3128
|
+
currentHref: ctx.path,
|
|
3129
|
+
navigate: () => Promise.resolve(),
|
|
3130
|
+
prefetch: () => {},
|
|
3131
|
+
invalidatePrefetch: () => {},
|
|
3132
|
+
refresh: () => Promise.resolve(),
|
|
3133
|
+
isNavigating: false,
|
|
3134
|
+
defaultPreload: "intent",
|
|
3135
|
+
defaultPreloadDelay: 50,
|
|
3136
|
+
defaultPreloadStaleTime: 30000
|
|
3137
|
+
};
|
|
3138
|
+
element = createElement2(RouterContext.Provider, { value: ssrContext }, element);
|
|
3139
|
+
}
|
|
3140
|
+
return { componentProps, element, headData, headers, loader_ms, template };
|
|
3141
|
+
}
|
|
3142
|
+
async function renderForPath(route, params, root, origin, basePath) {
|
|
3143
|
+
const resolvedPath = resolvePath(route.pattern, params);
|
|
3144
|
+
const ctx = {
|
|
3145
|
+
params,
|
|
3146
|
+
query: {},
|
|
3147
|
+
request: new Request(`${origin}${resolvedPath}`),
|
|
3148
|
+
headers: {},
|
|
3149
|
+
cookie: {},
|
|
3150
|
+
redirect: (url, status = 302) => new Response(null, { status, headers: { Location: url } }),
|
|
3151
|
+
set: { headers: {} },
|
|
3152
|
+
path: resolvedPath
|
|
3153
|
+
};
|
|
3154
|
+
const prepared = await runInSyntheticRenderScope(() => prepareRender(route, ctx, root, basePath), { route: route.pattern });
|
|
3155
|
+
if (prepared instanceof Response) {
|
|
3156
|
+
throw prepared;
|
|
3157
|
+
}
|
|
3158
|
+
const { componentProps, element, headData, headers, template } = prepared;
|
|
3159
|
+
const stream = await renderToReadableStream(element);
|
|
3160
|
+
await stream.allReady;
|
|
3161
|
+
const reactHtml = await streamToString(stream);
|
|
3162
|
+
return {
|
|
3163
|
+
html: assembleHTML(template, headData, reactHtml, componentProps),
|
|
3164
|
+
headers
|
|
3165
|
+
};
|
|
3166
|
+
}
|
|
3167
|
+
async function prerenderSSG(route, params, root, origin = "http://localhost:3000", basePath) {
|
|
3168
|
+
const resolvedPath = resolvePath(route.pattern, params);
|
|
3169
|
+
const cached = getSSGCache(resolvedPath);
|
|
3170
|
+
if (cached && !IS_DEV) {
|
|
3171
|
+
return cached;
|
|
3172
|
+
}
|
|
3173
|
+
let result;
|
|
3174
|
+
try {
|
|
3175
|
+
result = await renderForPath(route, params, root, origin, basePath);
|
|
3176
|
+
} catch (err) {
|
|
3177
|
+
if (err instanceof Response) {
|
|
3178
|
+
return err;
|
|
3179
|
+
}
|
|
3180
|
+
throw err;
|
|
3181
|
+
}
|
|
3182
|
+
const entry = { html: result.html, cachedAt: Date.now() };
|
|
3183
|
+
if (!IS_DEV) {
|
|
3184
|
+
setSSGCache(resolvedPath, entry);
|
|
3185
|
+
}
|
|
3186
|
+
return entry;
|
|
3187
|
+
}
|
|
3188
|
+
var pendingRevalidations = new Set;
|
|
3189
|
+
|
|
3190
|
+
// src/adapter/static.ts
|
|
3191
|
+
var STATIC_CONCURRENCY = 4;
|
|
3192
|
+
var DYNAMIC_SEGMENT_RE = /\/:[^/]+|\/\*/;
|
|
3193
|
+
var TRAILING_SLASHES_RE = /\/+$/;
|
|
3194
|
+
function pathToOutputFile(urlPath, outDir) {
|
|
3195
|
+
const normalizedOutDir = resolve2(outDir);
|
|
3196
|
+
if (urlPath === "/" || urlPath === "") {
|
|
3197
|
+
return join8(normalizedOutDir, "index.html");
|
|
3198
|
+
}
|
|
3199
|
+
const resolved = resolve2(normalizedOutDir, urlPath.slice(1), "index.html");
|
|
3200
|
+
if (!resolved.startsWith(`${normalizedOutDir}${sep}`)) {
|
|
3201
|
+
throw new Error(`[furin] static: unsafe output path detected for URL "${urlPath}" \u2014 path traversal via ".." is not allowed.`);
|
|
3202
|
+
}
|
|
3203
|
+
return resolved;
|
|
3204
|
+
}
|
|
3205
|
+
async function prerenderAndWrite(route, params, root, outDir, renderedRoutes, skippedRoutes, basePath) {
|
|
3206
|
+
const urlPath = resolvePath(route.pattern, params);
|
|
3207
|
+
const outputFile = pathToOutputFile(urlPath, outDir);
|
|
3208
|
+
try {
|
|
3209
|
+
const entry = await prerenderSSG(route, params, root, "http://localhost", basePath);
|
|
3210
|
+
if (entry instanceof Response) {
|
|
3211
|
+
console.warn(`[furin] static: route "${route.pattern}" loader returned a redirect \u2014 skipping.`);
|
|
3212
|
+
return;
|
|
3213
|
+
}
|
|
3214
|
+
ensureDir(dirname3(outputFile));
|
|
3215
|
+
writeFileSync7(outputFile, entry.html);
|
|
3216
|
+
renderedRoutes.push(urlPath);
|
|
3217
|
+
console.log(`[furin] static: ${urlPath} \u2192 ${toPosixPath(outputFile)}`);
|
|
3218
|
+
} catch (err) {
|
|
3219
|
+
console.error(`[furin] static: prerender failed for "${route.pattern}" (params: ${JSON.stringify(params)}):`, err);
|
|
3220
|
+
skippedRoutes.push(urlPath);
|
|
3221
|
+
}
|
|
3222
|
+
}
|
|
3223
|
+
function collectSsgRoutes(routes, onSSR, skippedRoutes) {
|
|
3224
|
+
const nonSsg = routes.filter((r) => r.mode !== "ssg");
|
|
3225
|
+
if (nonSsg.length === 0) {
|
|
3226
|
+
return routes;
|
|
3227
|
+
}
|
|
3228
|
+
if (onSSR === "error") {
|
|
3229
|
+
const list = nonSsg.map((r) => ` \u2022 ${r.pattern} (mode: ${r.mode})`).join(`
|
|
3230
|
+
`);
|
|
3231
|
+
throw new Error(`[furin] Cannot produce a static export: the following routes are not SSG and cannot be pre-rendered.
|
|
3232
|
+
` + `Either change their mode to "ssg", remove them, or set \`onSSR: "skip"\` in your static config.
|
|
3233
|
+
|
|
3234
|
+
` + `${list}`);
|
|
3235
|
+
}
|
|
3236
|
+
for (const r of nonSsg) {
|
|
3237
|
+
console.warn(`[furin] static: skipping route "${r.pattern}" (mode=${r.mode}) \u2014 not statically exportable.`);
|
|
3238
|
+
skippedRoutes.push(r.pattern);
|
|
3239
|
+
}
|
|
3240
|
+
return routes.filter((r) => r.mode === "ssg");
|
|
3241
|
+
}
|
|
3242
|
+
async function buildTaskQueue(ssgRoutes, root, outDir, renderedRoutes, skippedRoutes, basePath) {
|
|
3243
|
+
const tasks = [];
|
|
3244
|
+
for (const route of ssgRoutes) {
|
|
3245
|
+
if (!DYNAMIC_SEGMENT_RE.test(route.pattern)) {
|
|
3246
|
+
tasks.push(() => prerenderAndWrite(route, {}, root, outDir, renderedRoutes, skippedRoutes, basePath));
|
|
3247
|
+
continue;
|
|
3248
|
+
}
|
|
3249
|
+
if (!route.page.staticParams) {
|
|
3250
|
+
console.warn(`[furin] static: skipping dynamic route "${route.pattern}" \u2014 no staticParams() defined.`);
|
|
3251
|
+
skippedRoutes.push(route.pattern);
|
|
3252
|
+
continue;
|
|
3253
|
+
}
|
|
3254
|
+
try {
|
|
3255
|
+
const paramSets = await route.page.staticParams() ?? [];
|
|
3256
|
+
for (const params of paramSets) {
|
|
3257
|
+
tasks.push(() => prerenderAndWrite(route, params, root, outDir, renderedRoutes, skippedRoutes, basePath));
|
|
3258
|
+
}
|
|
3259
|
+
} catch (err) {
|
|
3260
|
+
console.error(`[furin] static: staticParams() failed for "${route.pattern}":`, err);
|
|
3261
|
+
skippedRoutes.push(route.pattern);
|
|
3262
|
+
}
|
|
3263
|
+
}
|
|
3264
|
+
return tasks;
|
|
3265
|
+
}
|
|
3266
|
+
async function runWithConcurrency(tasks, concurrency) {
|
|
3267
|
+
const queue = [...tasks];
|
|
3268
|
+
const workerCount = Math.min(concurrency, Math.max(queue.length, 1));
|
|
3269
|
+
await Promise.all(Array.from({ length: workerCount }, async () => {
|
|
3270
|
+
while (queue.length > 0) {
|
|
3271
|
+
await queue.shift()?.();
|
|
3272
|
+
}
|
|
3273
|
+
}));
|
|
3274
|
+
}
|
|
3275
|
+
async function buildStaticTarget(routes, rootDir, buildRoot, root, options) {
|
|
3276
|
+
const staticConfig = options.staticConfig ?? {};
|
|
3277
|
+
const rawBasePath = staticConfig.basePath ?? "";
|
|
3278
|
+
let basePath;
|
|
3279
|
+
if (rawBasePath === "/" || rawBasePath === "") {
|
|
3280
|
+
basePath = "";
|
|
3281
|
+
} else if (rawBasePath.endsWith("/")) {
|
|
3282
|
+
basePath = rawBasePath.replace(TRAILING_SLASHES_RE, "");
|
|
3283
|
+
} else {
|
|
3284
|
+
basePath = rawBasePath;
|
|
3285
|
+
}
|
|
3286
|
+
if (basePath && !basePath.startsWith("/")) {
|
|
3287
|
+
throw new Error(`[furin] static: basePath must start with "/" (received "${rawBasePath}"). ` + `Use "" for root deployments or "/sub-path" for sub-path deployments.`);
|
|
3288
|
+
}
|
|
3289
|
+
const outDir = resolve2(rootDir, staticConfig.outDir ?? "dist");
|
|
3290
|
+
const normalizedRoot = resolve2(rootDir);
|
|
3291
|
+
const normalizedBuildRoot = resolve2(buildRoot);
|
|
3292
|
+
if (outDir === normalizedRoot || outDir === normalizedBuildRoot || outDir === "/" || outDir === ".") {
|
|
3293
|
+
throw new Error(`[furin] static: outDir resolves to "${outDir}" which is unsafe to delete. ` + `Use a dedicated output directory such as "dist".`);
|
|
3294
|
+
}
|
|
3295
|
+
function isOutsideOutDir(target) {
|
|
3296
|
+
const rel = relative3(outDir, target);
|
|
3297
|
+
return rel.startsWith("..") || isAbsolute(rel);
|
|
3298
|
+
}
|
|
3299
|
+
if (!(isOutsideOutDir(normalizedRoot) && isOutsideOutDir(normalizedBuildRoot))) {
|
|
3300
|
+
throw new Error(`[furin] static: outDir resolves to "${outDir}" which is unsafe to delete. ` + `Use a dedicated output directory such as "dist".`);
|
|
3301
|
+
}
|
|
3302
|
+
const onSSR = staticConfig.onSSR ?? "error";
|
|
3303
|
+
const publicPath = basePath ? `${basePath}/_client/` : "/_client/";
|
|
3304
|
+
const renderedRoutes = [];
|
|
3305
|
+
const skippedRoutes = [];
|
|
3306
|
+
const ssgRoutes = collectSsgRoutes(routes, onSSR, skippedRoutes);
|
|
3307
|
+
rmSync3(outDir, { force: true, recursive: true });
|
|
3308
|
+
ensureDir(outDir);
|
|
3309
|
+
const targetDir = join8(buildRoot, "static");
|
|
3310
|
+
rmSync3(targetDir, { force: true, recursive: true });
|
|
3311
|
+
ensureDir(targetDir);
|
|
3312
|
+
const { entryChunk, cssChunks } = await buildClient(ssgRoutes, {
|
|
3313
|
+
outDir: targetDir,
|
|
3314
|
+
rootLayout: root.path,
|
|
3315
|
+
plugins: options.plugins,
|
|
3316
|
+
publicPath,
|
|
3317
|
+
basePath
|
|
3318
|
+
});
|
|
3319
|
+
const publicFavicon = join8(rootDir, "public", "favicon.ico");
|
|
3320
|
+
const faviconHref = existsSync7(publicFavicon) ? `${basePath}/favicon.ico` : undefined;
|
|
3321
|
+
const shellHtml = generateProdIndexHtml(entryChunk, cssChunks, undefined, faviconHref);
|
|
3322
|
+
setProductionTemplateContent(shellHtml);
|
|
3323
|
+
const publicSrcDir = join8(rootDir, "public");
|
|
3324
|
+
if (existsSync7(publicSrcDir)) {
|
|
3325
|
+
cpSync2(publicSrcDir, outDir, { recursive: true });
|
|
3326
|
+
}
|
|
3327
|
+
const clientSrcDir = join8(targetDir, "client");
|
|
3328
|
+
if (existsSync7(clientSrcDir)) {
|
|
3329
|
+
cpSync2(clientSrcDir, join8(outDir, "_client"), { recursive: true });
|
|
3330
|
+
}
|
|
3331
|
+
const tasks = await buildTaskQueue(ssgRoutes, root, outDir, renderedRoutes, skippedRoutes, basePath);
|
|
3332
|
+
const afterQueueCount = skippedRoutes.length;
|
|
3333
|
+
await runWithConcurrency(tasks, STATIC_CONCURRENCY);
|
|
3334
|
+
if (onSSR === "error" && skippedRoutes.length > afterQueueCount) {
|
|
3335
|
+
const failed = skippedRoutes.slice(afterQueueCount);
|
|
3336
|
+
const list = failed.map((r) => ` \u2022 ${r}`).join(`
|
|
3337
|
+
`);
|
|
3338
|
+
throw new Error(`[furin] static: ${failed.length} route(s) failed to pre-render:
|
|
3339
|
+
${list}
|
|
3340
|
+
` + `Set \`onSSR: "skip"\` in your static config to suppress this error.`);
|
|
3341
|
+
}
|
|
3342
|
+
writeFileSync7(join8(outDir, "404.html"), shellHtml);
|
|
3343
|
+
console.log("[furin] static: wrote 404.html (SPA shell fallback)");
|
|
3344
|
+
rmSync3(targetDir, { force: true, recursive: true });
|
|
3345
|
+
console.log(`[furin] static: export complete \u2192 ${toPosixPath(outDir)}` + ` (${renderedRoutes.length} rendered, ${skippedRoutes.length} skipped)`);
|
|
3346
|
+
return {
|
|
3347
|
+
basePath,
|
|
3348
|
+
generatedAt: new Date().toISOString(),
|
|
3349
|
+
outDir: toPosixPath(outDir),
|
|
3350
|
+
renderedRoutes,
|
|
3351
|
+
skippedRoutes
|
|
3352
|
+
};
|
|
3353
|
+
}
|
|
3354
|
+
|
|
1960
3355
|
// src/config.ts
|
|
1961
3356
|
import { t } from "elysia";
|
|
1962
|
-
var BUILD_TARGETS = ["bun", "node", "vercel", "cloudflare"];
|
|
3357
|
+
var BUILD_TARGETS = ["bun", "node", "vercel", "cloudflare", "static"];
|
|
1963
3358
|
var buildTargetSchema = t.Union(BUILD_TARGETS.map((v) => t.Literal(v)));
|
|
1964
3359
|
var compileTargetSchema = t.Union([t.Literal("server"), t.Literal("embed")]);
|
|
1965
3360
|
var configSchema = t.Object({
|
|
@@ -1969,14 +3364,19 @@ var configSchema = t.Object({
|
|
|
1969
3364
|
targets: t.Optional(t.Array(buildTargetSchema)),
|
|
1970
3365
|
bun: t.Optional(t.Object({
|
|
1971
3366
|
compile: t.Optional(compileTargetSchema)
|
|
3367
|
+
})),
|
|
3368
|
+
static: t.Optional(t.Object({
|
|
3369
|
+
basePath: t.Optional(t.String()),
|
|
3370
|
+
outDir: t.Optional(t.String()),
|
|
3371
|
+
onSSR: t.Optional(t.Union([t.Literal("error"), t.Literal("skip")]))
|
|
1972
3372
|
}))
|
|
1973
3373
|
});
|
|
1974
3374
|
|
|
1975
3375
|
// src/router.ts
|
|
1976
|
-
import { existsSync as
|
|
3376
|
+
import { existsSync as existsSync8 } from "fs";
|
|
1977
3377
|
import { readdir } from "fs/promises";
|
|
1978
|
-
import { join as
|
|
1979
|
-
import { Elysia } from "elysia";
|
|
3378
|
+
import { join as join9, parse } from "path";
|
|
3379
|
+
import { Elysia as Elysia2, t as t2 } from "elysia";
|
|
1980
3380
|
|
|
1981
3381
|
// src/internal.ts
|
|
1982
3382
|
var _compileCtx = null;
|
|
@@ -1984,24 +3384,6 @@ function getCompileContext() {
|
|
|
1984
3384
|
return _compileCtx;
|
|
1985
3385
|
}
|
|
1986
3386
|
|
|
1987
|
-
// src/render/index.ts
|
|
1988
|
-
import { renderToReadableStream } from "react-dom/server";
|
|
1989
|
-
|
|
1990
|
-
// src/render/cache.ts
|
|
1991
|
-
import { AsyncLocalStorage } from "async_hooks";
|
|
1992
|
-
var isrCache = new Map;
|
|
1993
|
-
var ssgCache = new Map;
|
|
1994
|
-
var _requestInvalidationScope = new AsyncLocalStorage;
|
|
1995
|
-
var _globalPendingInvalidations = new Set;
|
|
1996
|
-
|
|
1997
|
-
// src/render/element.tsx
|
|
1998
|
-
import { jsxDEV } from "react/jsx-dev-runtime";
|
|
1999
|
-
// src/runtime-env.ts
|
|
2000
|
-
var IS_DEV = true;
|
|
2001
|
-
|
|
2002
|
-
// src/render/index.ts
|
|
2003
|
-
var pendingRevalidations = new Set;
|
|
2004
|
-
|
|
2005
3387
|
// src/utils.ts
|
|
2006
3388
|
function isFurinPage(value) {
|
|
2007
3389
|
return typeof value === "object" && value !== null && "__type" in value && value.__type === "FURIN_PAGE";
|
|
@@ -2052,7 +3434,7 @@ async function scanPages(pagesDir) {
|
|
|
2052
3434
|
async function scanRootLayout(pagesDir) {
|
|
2053
3435
|
const rootPath = `${pagesDir}/root.tsx`;
|
|
2054
3436
|
const ctx = getCompileContext();
|
|
2055
|
-
if (!(
|
|
3437
|
+
if (!(existsSync8(rootPath) || ctx?.modules[rootPath])) {
|
|
2056
3438
|
throw new Error("[furin] root.tsx: not found.");
|
|
2057
3439
|
}
|
|
2058
3440
|
const mod = ctx?.modules[rootPath] ?? await import(rootPath);
|
|
@@ -2122,10 +3504,11 @@ async function buildDevRoute(absolutePath, relativePath, root) {
|
|
|
2122
3504
|
routeChain
|
|
2123
3505
|
};
|
|
2124
3506
|
}
|
|
3507
|
+
var TOBJECT_STRUCTURAL_KEYS = new Set(["type", "properties", "required"]);
|
|
2125
3508
|
async function collectPageFilePaths(dir) {
|
|
2126
3509
|
const files = [];
|
|
2127
3510
|
for (const entry of await readdir(dir, { withFileTypes: true })) {
|
|
2128
|
-
const absolutePath =
|
|
3511
|
+
const absolutePath = join9(dir, entry.name);
|
|
2129
3512
|
if (entry.isDirectory()) {
|
|
2130
3513
|
files.push(...await collectPageFilePaths(absolutePath));
|
|
2131
3514
|
continue;
|
|
@@ -2173,10 +3556,10 @@ function filePathToPattern(path) {
|
|
|
2173
3556
|
}
|
|
2174
3557
|
|
|
2175
3558
|
// src/build/scan-server.ts
|
|
2176
|
-
import { readFileSync as
|
|
3559
|
+
import { readFileSync as readFileSync4 } from "fs";
|
|
2177
3560
|
import { parseSync as parseSync2 } from "oxc-parser";
|
|
2178
3561
|
function scanFurinInstances(serverEntryPath) {
|
|
2179
|
-
const code =
|
|
3562
|
+
const code = readFileSync4(serverEntryPath, "utf8");
|
|
2180
3563
|
const { program, errors } = parseSync2(serverEntryPath, code);
|
|
2181
3564
|
if (errors.length > 0) {
|
|
2182
3565
|
return [];
|
|
@@ -2185,26 +3568,28 @@ function scanFurinInstances(serverEntryPath) {
|
|
|
2185
3568
|
walkNode(program, results);
|
|
2186
3569
|
return results;
|
|
2187
3570
|
}
|
|
2188
|
-
|
|
2189
|
-
|
|
3571
|
+
var SKIP_KEYS = new Set(["type", "start", "end"]);
|
|
3572
|
+
function checkFurinCall(node, out) {
|
|
3573
|
+
const callee = node.callee;
|
|
3574
|
+
const args = node.arguments;
|
|
3575
|
+
const isFurinCall = callee?.type === "Identifier" && callee.name === "furin";
|
|
3576
|
+
if (!(isFurinCall && Array.isArray(args)) || args.length === 0) {
|
|
2190
3577
|
return;
|
|
2191
|
-
if (node.type === "CallExpression") {
|
|
2192
|
-
const callee = node.callee;
|
|
2193
|
-
const args = node.arguments;
|
|
2194
|
-
const isFurinCall = callee?.type === "Identifier" && callee.name === "furin";
|
|
2195
|
-
if (isFurinCall && Array.isArray(args) && args.length > 0) {
|
|
2196
|
-
const firstArg = args[0];
|
|
2197
|
-
if (firstArg?.type === "ObjectExpression") {
|
|
2198
|
-
const pagesDir = extractStringProperty(firstArg, "pagesDir");
|
|
2199
|
-
if (pagesDir !== null) {
|
|
2200
|
-
out.push(pagesDir);
|
|
2201
|
-
}
|
|
2202
|
-
}
|
|
2203
|
-
}
|
|
2204
3578
|
}
|
|
3579
|
+
const firstArg = args[0];
|
|
3580
|
+
if (firstArg?.type !== "ObjectExpression") {
|
|
3581
|
+
return;
|
|
3582
|
+
}
|
|
3583
|
+
const pagesDir = extractStringProperty(firstArg, "pagesDir");
|
|
3584
|
+
if (pagesDir !== null) {
|
|
3585
|
+
out.push(pagesDir);
|
|
3586
|
+
}
|
|
3587
|
+
}
|
|
3588
|
+
function walkChildren(node, out) {
|
|
2205
3589
|
for (const key of Object.keys(node)) {
|
|
2206
|
-
if (key
|
|
3590
|
+
if (SKIP_KEYS.has(key)) {
|
|
2207
3591
|
continue;
|
|
3592
|
+
}
|
|
2208
3593
|
const child = node[key];
|
|
2209
3594
|
if (Array.isArray(child)) {
|
|
2210
3595
|
for (const item of child) {
|
|
@@ -2217,18 +3602,30 @@ function walkNode(node, out) {
|
|
|
2217
3602
|
}
|
|
2218
3603
|
}
|
|
2219
3604
|
}
|
|
3605
|
+
function walkNode(node, out) {
|
|
3606
|
+
if (!node || typeof node !== "object") {
|
|
3607
|
+
return;
|
|
3608
|
+
}
|
|
3609
|
+
if (node.type === "CallExpression") {
|
|
3610
|
+
checkFurinCall(node, out);
|
|
3611
|
+
}
|
|
3612
|
+
walkChildren(node, out);
|
|
3613
|
+
}
|
|
2220
3614
|
function extractStringProperty(obj, propName) {
|
|
2221
3615
|
const properties = obj.properties;
|
|
2222
|
-
if (!Array.isArray(properties))
|
|
3616
|
+
if (!Array.isArray(properties)) {
|
|
2223
3617
|
return null;
|
|
3618
|
+
}
|
|
2224
3619
|
for (const prop of properties) {
|
|
2225
|
-
if (prop.type !== "Property")
|
|
3620
|
+
if (prop.type !== "Property") {
|
|
2226
3621
|
continue;
|
|
3622
|
+
}
|
|
2227
3623
|
const key = prop.key;
|
|
2228
3624
|
const value = prop.value;
|
|
2229
3625
|
const keyMatches = key.type === "Identifier" && key.name === propName || key.type === "Literal" && key.value === propName;
|
|
2230
|
-
if (!keyMatches)
|
|
3626
|
+
if (!keyMatches) {
|
|
2231
3627
|
continue;
|
|
3628
|
+
}
|
|
2232
3629
|
if (value?.type === "Literal" && typeof value.value === "string") {
|
|
2233
3630
|
return value.value;
|
|
2234
3631
|
}
|
|
@@ -2238,33 +3635,46 @@ function extractStringProperty(obj, propName) {
|
|
|
2238
3635
|
}
|
|
2239
3636
|
|
|
2240
3637
|
// src/build/index.ts
|
|
2241
|
-
var IMPLEMENTED_TARGETS = ["bun"];
|
|
3638
|
+
var IMPLEMENTED_TARGETS = ["bun", "static"];
|
|
2242
3639
|
var BUILD_OUTPUT_DIR = ".furin/build";
|
|
2243
3640
|
function resolvePagesDirFromServer(serverEntry, rootDir) {
|
|
2244
|
-
if (!serverEntry)
|
|
3641
|
+
if (!serverEntry) {
|
|
2245
3642
|
return null;
|
|
3643
|
+
}
|
|
2246
3644
|
const detected = scanFurinInstances(serverEntry);
|
|
2247
|
-
if (detected.length === 0)
|
|
3645
|
+
if (detected.length === 0) {
|
|
2248
3646
|
return null;
|
|
2249
|
-
|
|
3647
|
+
}
|
|
3648
|
+
return resolve3(rootDir, detected[0]);
|
|
2250
3649
|
}
|
|
2251
3650
|
async function buildApp(options) {
|
|
2252
|
-
const rootDir =
|
|
2253
|
-
const buildRoot =
|
|
3651
|
+
const rootDir = resolve3(options.rootDir ?? process.cwd());
|
|
3652
|
+
const buildRoot = join10(rootDir, BUILD_OUTPUT_DIR);
|
|
2254
3653
|
const serverEntry = (() => {
|
|
3654
|
+
if (options.target === "static") {
|
|
3655
|
+
return null;
|
|
3656
|
+
}
|
|
2255
3657
|
if (options.serverEntry) {
|
|
2256
|
-
const resolved =
|
|
2257
|
-
if (
|
|
3658
|
+
const resolved = resolve3(rootDir, options.serverEntry);
|
|
3659
|
+
if (existsSync9(resolved)) {
|
|
2258
3660
|
return resolved;
|
|
3661
|
+
}
|
|
2259
3662
|
}
|
|
2260
|
-
const
|
|
2261
|
-
if (!
|
|
3663
|
+
const entry = resolve3(rootDir, "src/server.ts");
|
|
3664
|
+
if (!existsSync9(entry)) {
|
|
2262
3665
|
throw new Error("[furin] Entrypoint server.ts not found");
|
|
2263
3666
|
}
|
|
2264
|
-
return
|
|
3667
|
+
return entry;
|
|
2265
3668
|
})();
|
|
3669
|
+
for (const plugin of options.plugins ?? []) {
|
|
3670
|
+
try {
|
|
3671
|
+
Bun.plugin(plugin);
|
|
3672
|
+
} catch (err) {
|
|
3673
|
+
console.debug("[furin] Skipped build-only plugin at runtime:", err);
|
|
3674
|
+
}
|
|
3675
|
+
}
|
|
2266
3676
|
const rawPagesDir = options.pagesDir ?? resolvePagesDirFromServer(serverEntry, rootDir) ?? "src/pages";
|
|
2267
|
-
const pagesDir =
|
|
3677
|
+
const pagesDir = resolve3(rootDir, rawPagesDir);
|
|
2268
3678
|
const requestedTargets = options.target === "all" ? [...IMPLEMENTED_TARGETS] : [options.target].map((target) => {
|
|
2269
3679
|
if (!BUILD_TARGETS.includes(target)) {
|
|
2270
3680
|
throw new Error(`[furin] Unsupported build target "${target}"`);
|
|
@@ -2277,9 +3687,9 @@ async function buildApp(options) {
|
|
|
2277
3687
|
version: 1,
|
|
2278
3688
|
generatedAt: new Date().toISOString(),
|
|
2279
3689
|
rootDir: toPosixPath(rootDir),
|
|
2280
|
-
pagesDir: toPosixPath(
|
|
2281
|
-
rootPath: toPosixPath(
|
|
2282
|
-
serverEntry: serverEntry ? toPosixPath(
|
|
3690
|
+
pagesDir: toPosixPath(relative4(rootDir, pagesDir)),
|
|
3691
|
+
rootPath: toPosixPath(relative4(rootDir, root.path)),
|
|
3692
|
+
serverEntry: serverEntry ? toPosixPath(relative4(rootDir, serverEntry)) : null,
|
|
2283
3693
|
routes: routes.map((route) => toBuildRouteManifestEntry(route, rootDir)),
|
|
2284
3694
|
targets: {}
|
|
2285
3695
|
};
|
|
@@ -2288,6 +3698,9 @@ async function buildApp(options) {
|
|
|
2288
3698
|
case "bun":
|
|
2289
3699
|
manifest.targets.bun = await buildBunTarget(routes, rootDir, buildRoot, root.path, serverEntry, options);
|
|
2290
3700
|
break;
|
|
3701
|
+
case "static":
|
|
3702
|
+
manifest.targets.static = await buildStaticTarget(routes, rootDir, buildRoot, root, options);
|
|
3703
|
+
break;
|
|
2291
3704
|
case "node":
|
|
2292
3705
|
case "vercel":
|
|
2293
3706
|
case "cloudflare":
|
|
@@ -2296,7 +3709,7 @@ async function buildApp(options) {
|
|
|
2296
3709
|
throw new Error(`[furin] Unsupported build target "${target}"`);
|
|
2297
3710
|
}
|
|
2298
3711
|
}
|
|
2299
|
-
|
|
3712
|
+
writeFileSync8(join10(buildRoot, "manifest.json"), `${JSON.stringify(manifest, null, 2)}
|
|
2300
3713
|
`);
|
|
2301
3714
|
return {
|
|
2302
3715
|
manifest,
|