@teyik0/furin 0.2.0-alpha.1 → 0.2.0-alpha.3
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/LICENSE +21 -21
- package/README.md +33 -33
- package/dist/adapter/static.d.ts +1 -1
- package/dist/build/compile-entry.ts +109 -109
- package/dist/build/entry-template.ts +156 -156
- package/dist/build/index.js +1724 -687
- package/dist/build/route-types.d.ts +3 -1
- package/dist/build/server-routes-entry.ts +36 -36
- package/dist/build/shared.d.ts +1 -0
- package/dist/build/ssg-cache.d.ts +1 -1
- package/dist/cli/index.js +1673 -658
- package/dist/client/link.js +883 -89
- package/dist/client/router/index.d.ts +4 -0
- package/dist/client/router/link-utils.d.ts +3 -1
- package/dist/client/router/navigation.d.ts +10 -0
- package/dist/client/router/provider.d.ts +1 -1
- package/dist/client/router/search/index.d.ts +18 -0
- package/dist/client/router/search-store.d.ts +21 -0
- package/dist/client/router/types.d.ts +14 -1
- package/dist/client/sync.d.ts +25 -0
- package/dist/client.d.ts +1 -0
- package/dist/client.js +44 -0
- package/dist/furin.d.ts +9 -1
- package/dist/furin.js +1578 -258
- package/dist/server/auto-invalidate/runtime.d.ts +1 -1
- package/dist/server/dev-page-plugin.d.ts +3 -0
- package/dist/server/render/assemble.d.ts +2 -0
- package/dist/server/render/isr.d.ts +2 -1
- package/dist/server/render/ssg.d.ts +3 -2
- package/dist/server/render/ssr.d.ts +5 -4
- package/dist/server/router/hmr.d.ts +4 -3
- package/dist/server/router/index.d.ts +1 -1
- package/dist/server/router/index.js +1 -2
- package/dist/server/router/index.ts +1 -2
- package/dist/server/router/plugin.d.ts +2 -1
- package/dist/server/router/schemas.d.ts +25 -17
- package/dist/server/sync/config.d.ts +6 -0
- package/dist/server/sync/index.d.ts +4 -0
- package/dist/server/sync/plugin.d.ts +369 -0
- package/dist/server/sync/stream.d.ts +47 -0
- package/dist/shared/search-params.d.ts +17 -0
- package/package.json +10 -5
- package/src/adapter/README.md +13 -13
- package/src/adapter/static.ts +23 -6
- package/src/build/client.ts +152 -149
- package/src/build/compile-entry.ts +109 -109
- package/src/build/entry-template.ts +156 -156
- package/src/build/hydrate.ts +340 -331
- package/src/build/index.ts +152 -152
- package/src/build/route-types.ts +145 -115
- package/src/build/scan-server.ts +95 -95
- package/src/build/server-routes-entry.ts +36 -36
- package/src/build/shared.ts +80 -78
- package/src/build/ssg-cache.ts +32 -31
- package/src/build/types.ts +89 -89
- package/src/client/link.tsx +13 -4
- package/src/client/router/context.ts +2 -0
- package/src/client/router/index.ts +9 -0
- package/src/client/router/link-utils.ts +184 -180
- package/src/client/router/navigation.ts +61 -0
- package/src/client/router/provider.tsx +804 -723
- package/src/client/router/search/index.ts +99 -0
- package/src/client/router/search-store.ts +86 -0
- package/src/client/router/types.ts +276 -263
- package/src/client/sync.ts +98 -0
- package/src/client.ts +369 -355
- package/src/furin.ts +465 -437
- package/src/server/auto-invalidate/runtime.ts +134 -133
- package/src/server/dev-page-plugin.ts +454 -449
- package/src/server/render/assemble.ts +160 -133
- package/src/server/render/isr.ts +323 -295
- package/src/server/render/not-found.ts +2 -0
- package/src/server/render/ssg.ts +15 -4
- package/src/server/render/ssr.ts +585 -545
- package/src/server/router/hmr.ts +14 -10
- package/src/server/router/index.ts +1 -2
- package/src/server/router/patterns.ts +5 -0
- package/src/server/router/plugin.ts +384 -401
- package/src/server/router/schemas.ts +172 -57
- package/src/server/sync/config.ts +29 -0
- package/src/server/sync/index.ts +14 -0
- package/src/server/sync/plugin.ts +108 -0
- package/src/server/sync/stream.ts +144 -0
- package/src/shared/search-params.ts +182 -0
package/dist/build/index.js
CHANGED
|
@@ -4,13 +4,13 @@ import { existsSync as existsSync10, writeFileSync as writeFileSync8 } from "fs"
|
|
|
4
4
|
import { join as join11, relative as relative4, resolve as resolve3 } from "path";
|
|
5
5
|
|
|
6
6
|
// src/adapter/bun.ts
|
|
7
|
-
import { existsSync as
|
|
8
|
-
import { dirname as dirname2, join as
|
|
9
|
-
import { fileURLToPath as
|
|
7
|
+
import { existsSync as existsSync8, rmSync as rmSync2, writeFileSync as writeFileSync6 } from "fs";
|
|
8
|
+
import { dirname as dirname2, join as join9, resolve } from "path";
|
|
9
|
+
import { fileURLToPath as fileURLToPath3 } from "url";
|
|
10
10
|
|
|
11
11
|
// src/build/client.ts
|
|
12
|
-
import { existsSync as
|
|
13
|
-
import { basename, join as
|
|
12
|
+
import { existsSync as existsSync5, mkdirSync as mkdirSync3, writeFileSync as writeFileSync3 } from "fs";
|
|
13
|
+
import { basename, join as join5 } from "path";
|
|
14
14
|
|
|
15
15
|
// ../../node_modules/.bun/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs
|
|
16
16
|
var comma = 44;
|
|
@@ -1465,8 +1465,8 @@ function transformForClient(code, filename) {
|
|
|
1465
1465
|
}
|
|
1466
1466
|
|
|
1467
1467
|
// src/build/hydrate.ts
|
|
1468
|
-
import { existsSync as
|
|
1469
|
-
import { join as
|
|
1468
|
+
import { existsSync as existsSync3, mkdirSync, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "fs";
|
|
1469
|
+
import { join as join3 } from "path";
|
|
1470
1470
|
|
|
1471
1471
|
// src/server/render/shell.ts
|
|
1472
1472
|
function extractTitle(meta) {
|
|
@@ -1596,6 +1596,79 @@ ${buildIdMeta}${modeMeta}${faviconLink}${cssLinks ? `${cssLinks}
|
|
|
1596
1596
|
`;
|
|
1597
1597
|
}
|
|
1598
1598
|
|
|
1599
|
+
// src/server/router/discovery.ts
|
|
1600
|
+
import { existsSync } from "fs";
|
|
1601
|
+
import { readdir } from "fs/promises";
|
|
1602
|
+
import { join, parse as parse3 } from "path";
|
|
1603
|
+
|
|
1604
|
+
// src/shared/utils/index.ts
|
|
1605
|
+
function isFurinPage(value) {
|
|
1606
|
+
return typeof value === "object" && value !== null && "__type" in value && value.__type === "FURIN_PAGE";
|
|
1607
|
+
}
|
|
1608
|
+
function isFurinRoute(value) {
|
|
1609
|
+
return typeof value === "object" && value !== null && "__type" in value && value.__type === "FURIN_ROUTE";
|
|
1610
|
+
}
|
|
1611
|
+
function collectRouteChainFromRoute(route) {
|
|
1612
|
+
const chain = [];
|
|
1613
|
+
let current = route;
|
|
1614
|
+
while (current) {
|
|
1615
|
+
chain.unshift(current);
|
|
1616
|
+
current = current.parent;
|
|
1617
|
+
}
|
|
1618
|
+
return chain;
|
|
1619
|
+
}
|
|
1620
|
+
function hasCycle(route) {
|
|
1621
|
+
const visited = new Set;
|
|
1622
|
+
let current = route;
|
|
1623
|
+
while (current) {
|
|
1624
|
+
if (visited.has(current)) {
|
|
1625
|
+
return true;
|
|
1626
|
+
}
|
|
1627
|
+
visited.add(current);
|
|
1628
|
+
current = current.parent;
|
|
1629
|
+
}
|
|
1630
|
+
return false;
|
|
1631
|
+
}
|
|
1632
|
+
async function mapWithConcurrency(items, concurrency, fn) {
|
|
1633
|
+
if (items.length === 0) {
|
|
1634
|
+
return [];
|
|
1635
|
+
}
|
|
1636
|
+
const results = new Array(items.length);
|
|
1637
|
+
let cursor = 0;
|
|
1638
|
+
const workerCount = Math.min(Math.max(concurrency, 1), items.length);
|
|
1639
|
+
await Promise.all(Array.from({ length: workerCount }, async () => {
|
|
1640
|
+
while (true) {
|
|
1641
|
+
const index = cursor++;
|
|
1642
|
+
if (index >= items.length) {
|
|
1643
|
+
return;
|
|
1644
|
+
}
|
|
1645
|
+
results[index] = await fn(items[index], index);
|
|
1646
|
+
}
|
|
1647
|
+
}));
|
|
1648
|
+
return results;
|
|
1649
|
+
}
|
|
1650
|
+
function validateRouteChain(chain, root, pagePath) {
|
|
1651
|
+
const hasRoot = chain.some((r) => r === root);
|
|
1652
|
+
if (!hasRoot) {
|
|
1653
|
+
const location = pagePath ? `in ${pagePath}` : "";
|
|
1654
|
+
throw new Error(`[furin] Page ${location} must inherit from root route. ` + 'Add: import { route } from "./root"; and use route.page() or set parent: route');
|
|
1655
|
+
}
|
|
1656
|
+
for (const route of chain) {
|
|
1657
|
+
if (hasCycle(route)) {
|
|
1658
|
+
throw new Error("[furin] Cycle detected in route chain. A route cannot be its own ancestor.");
|
|
1659
|
+
}
|
|
1660
|
+
}
|
|
1661
|
+
}
|
|
1662
|
+
|
|
1663
|
+
// src/server/internal.ts
|
|
1664
|
+
var _compileCtx = null;
|
|
1665
|
+
function getCompileContext() {
|
|
1666
|
+
return _compileCtx;
|
|
1667
|
+
}
|
|
1668
|
+
|
|
1669
|
+
// src/server/runtime-env.ts
|
|
1670
|
+
var IS_DEV = true;
|
|
1671
|
+
|
|
1599
1672
|
// src/server/router/patterns.ts
|
|
1600
1673
|
import { parse as parse2 } from "path";
|
|
1601
1674
|
function resolveMode(page, routeChain) {
|
|
@@ -1606,6 +1679,10 @@ function resolveMode(page, routeChain) {
|
|
|
1606
1679
|
return mode;
|
|
1607
1680
|
}
|
|
1608
1681
|
const hasLoader = routeChain.some((r) => r.loader) || !!page.loader;
|
|
1682
|
+
const hasQuery = routeChain.some((r) => r.query);
|
|
1683
|
+
if (hasQuery) {
|
|
1684
|
+
return "ssr";
|
|
1685
|
+
}
|
|
1609
1686
|
if (!hasLoader) {
|
|
1610
1687
|
return "ssg";
|
|
1611
1688
|
}
|
|
@@ -1672,163 +1749,592 @@ function buildRouteRegex(pattern) {
|
|
|
1672
1749
|
return { regex: new RegExp(`^${source}$`), paramNames };
|
|
1673
1750
|
}
|
|
1674
1751
|
|
|
1675
|
-
// src/
|
|
1676
|
-
|
|
1677
|
-
|
|
1678
|
-
|
|
1679
|
-
|
|
1680
|
-
|
|
1681
|
-
}
|
|
1682
|
-
function schemaToTypeString(schema) {
|
|
1683
|
-
if (!schema || typeof schema !== "object") {
|
|
1684
|
-
return "unknown";
|
|
1685
|
-
}
|
|
1686
|
-
const s = schema;
|
|
1687
|
-
if (s.anyOf && Array.isArray(s.anyOf)) {
|
|
1688
|
-
const parts = [];
|
|
1689
|
-
for (const item of s.anyOf) {
|
|
1690
|
-
const t = schemaToTypeString(item);
|
|
1691
|
-
if (t !== "null")
|
|
1692
|
-
parts.push(t);
|
|
1752
|
+
// src/server/router/discovery.ts
|
|
1753
|
+
function collectRouteTags(routeChain, page) {
|
|
1754
|
+
const tags = new Set;
|
|
1755
|
+
for (const route of routeChain) {
|
|
1756
|
+
for (const tag of route.tags ?? []) {
|
|
1757
|
+
tags.add(tag);
|
|
1693
1758
|
}
|
|
1694
|
-
return parts.join(" | ") || "unknown";
|
|
1695
1759
|
}
|
|
1696
|
-
|
|
1697
|
-
|
|
1698
|
-
return "string";
|
|
1699
|
-
case "number":
|
|
1700
|
-
case "integer":
|
|
1701
|
-
return "number";
|
|
1702
|
-
case "boolean":
|
|
1703
|
-
return "boolean";
|
|
1704
|
-
case "null":
|
|
1705
|
-
return "null";
|
|
1706
|
-
case "object": {
|
|
1707
|
-
if (!s.properties || typeof s.properties !== "object") {
|
|
1708
|
-
return "Record<string, unknown>";
|
|
1709
|
-
}
|
|
1710
|
-
const required = new Set(Array.isArray(s.required) ? s.required : []);
|
|
1711
|
-
const props = Object.entries(s.properties).map(([k, v]) => `${k}${required.has(k) ? "" : "?"}: ${schemaToTypeString(v)}`).join("; ");
|
|
1712
|
-
return `{ ${props} }`;
|
|
1713
|
-
}
|
|
1714
|
-
default:
|
|
1715
|
-
return "unknown";
|
|
1760
|
+
for (const tag of page?.tags ?? []) {
|
|
1761
|
+
tags.add(tag);
|
|
1716
1762
|
}
|
|
1763
|
+
return tags.size > 0 ? [...tags] : undefined;
|
|
1717
1764
|
}
|
|
1718
|
-
function
|
|
1719
|
-
return
|
|
1765
|
+
function toPosixPath(path) {
|
|
1766
|
+
return path.replaceAll("\\", "/");
|
|
1720
1767
|
}
|
|
1721
|
-
function
|
|
1722
|
-
const
|
|
1723
|
-
|
|
1768
|
+
function routeRelativePath(pagesDir, absolutePath) {
|
|
1769
|
+
const dir = toPosixPath(pagesDir).replace(/\/+$/g, "");
|
|
1770
|
+
const path = toPosixPath(absolutePath);
|
|
1771
|
+
return path.startsWith(`${dir}/`) ? path.slice(dir.length + 1) : path;
|
|
1724
1772
|
}
|
|
1725
|
-
function
|
|
1726
|
-
const
|
|
1727
|
-
const
|
|
1728
|
-
|
|
1729
|
-
|
|
1730
|
-
|
|
1731
|
-
|
|
1732
|
-
|
|
1733
|
-
|
|
1734
|
-
|
|
1735
|
-
|
|
1736
|
-
|
|
1737
|
-
declare module "@teyik0/furin" {
|
|
1738
|
-
interface FurinCacheTags {
|
|
1739
|
-
${sortedTags.map((tag) => ` ${tagKeyToPropertyName(tag)}: ${tagToStringLiteral(tag)};`).join(`
|
|
1740
|
-
`)}
|
|
1773
|
+
async function scanPages(pagesDir) {
|
|
1774
|
+
const dir = toPosixPath(pagesDir);
|
|
1775
|
+
const root = await scanRootLayout(dir);
|
|
1776
|
+
const routes = await scanPageFiles(dir, root);
|
|
1777
|
+
return { root, routes };
|
|
1778
|
+
}
|
|
1779
|
+
async function scanRootLayout(pagesDir) {
|
|
1780
|
+
const rootPath = `${pagesDir}/root.tsx`;
|
|
1781
|
+
const ctx = getCompileContext();
|
|
1782
|
+
if (!(existsSync(rootPath) || ctx?.modules[rootPath])) {
|
|
1783
|
+
throw new Error("[furin] root.tsx: not found.");
|
|
1741
1784
|
}
|
|
1742
|
-
|
|
1743
|
-
const
|
|
1744
|
-
|
|
1745
|
-
|
|
1746
|
-
|
|
1747
|
-
declare module "@teyik0/furin/link" {
|
|
1748
|
-
interface RouteManifest {
|
|
1749
|
-
${entries.join(`;
|
|
1750
|
-
`)};
|
|
1785
|
+
const mod = ctx?.modules[rootPath] ?? await import(rootPath);
|
|
1786
|
+
const rootExport = mod.route ?? mod.default;
|
|
1787
|
+
if (!(rootExport && isFurinRoute(rootExport))) {
|
|
1788
|
+
throw new Error("[furin] root.tsx: createRoute() export not found.");
|
|
1751
1789
|
}
|
|
1752
|
-
|
|
1753
|
-
|
|
1754
|
-
const typesPath = join(projectRoot, "furin-env.d.ts");
|
|
1755
|
-
const existing = existsSync(typesPath) ? readFileSync(typesPath, "utf8") : "";
|
|
1756
|
-
if (content !== existing) {
|
|
1757
|
-
writeFileSync(typesPath, content);
|
|
1790
|
+
if (!rootExport.layout) {
|
|
1791
|
+
throw new Error("[furin] root.tsx: createRoute() has no layout.");
|
|
1758
1792
|
}
|
|
1759
|
-
|
|
1760
|
-
|
|
1761
|
-
|
|
1762
|
-
|
|
1763
|
-
|
|
1764
|
-
|
|
1765
|
-
|
|
1766
|
-
|
|
1767
|
-
|
|
1768
|
-
|
|
1769
|
-
|
|
1770
|
-
}
|
|
1771
|
-
const ident = `__furin_bnd_${idents.size}`;
|
|
1772
|
-
idents.set(filePath, ident);
|
|
1773
|
-
return ident;
|
|
1793
|
+
const [notFoundEntry, errorEntry] = await Promise.all([
|
|
1794
|
+
loadConventionComponent(pagesDir, "not-found"),
|
|
1795
|
+
loadConventionComponent(pagesDir, "error")
|
|
1796
|
+
]);
|
|
1797
|
+
return {
|
|
1798
|
+
path: rootPath,
|
|
1799
|
+
route: rootExport,
|
|
1800
|
+
notFound: notFoundEntry?.component,
|
|
1801
|
+
notFoundPath: notFoundEntry?.path,
|
|
1802
|
+
error: errorEntry?.component,
|
|
1803
|
+
errorPath: errorEntry?.path
|
|
1774
1804
|
};
|
|
1775
|
-
|
|
1776
|
-
|
|
1777
|
-
|
|
1778
|
-
|
|
1779
|
-
|
|
1780
|
-
|
|
1781
|
-
|
|
1782
|
-
|
|
1783
|
-
|
|
1784
|
-
|
|
1785
|
-
|
|
1786
|
-
|
|
1787
|
-
|
|
1788
|
-
|
|
1789
|
-
|
|
1790
|
-
|
|
1791
|
-
if (notFoundIdent) {
|
|
1792
|
-
parts.push(`notFound: ${notFoundIdent}.default`);
|
|
1805
|
+
}
|
|
1806
|
+
var CONVENTION_FILE_NAMES = ["not-found", "error"];
|
|
1807
|
+
var SOURCE_MODULE_EXTENSIONS = [".tsx", ".ts", ".jsx", ".js"];
|
|
1808
|
+
function isConventionFileName(name) {
|
|
1809
|
+
return CONVENTION_FILE_NAMES.includes(name);
|
|
1810
|
+
}
|
|
1811
|
+
function getSourceModuleCandidates(dir, name) {
|
|
1812
|
+
return SOURCE_MODULE_EXTENSIONS.map((ext) => `${dir}/${name}${ext}`);
|
|
1813
|
+
}
|
|
1814
|
+
async function loadConventionComponent(dir, name) {
|
|
1815
|
+
const ctx = getCompileContext();
|
|
1816
|
+
for (const filePath of getSourceModuleCandidates(dir, name)) {
|
|
1817
|
+
if (existsSync(filePath) || ctx?.modules[filePath]) {
|
|
1818
|
+
const mod = ctx?.modules[filePath] ?? await import(filePath);
|
|
1819
|
+
if (mod.default) {
|
|
1820
|
+
return { component: mod.default, path: filePath };
|
|
1793
1821
|
}
|
|
1794
|
-
boundaryLiterals.push(`{ ${parts.join(", ")} }`);
|
|
1795
1822
|
}
|
|
1796
|
-
const lazyImports = [
|
|
1797
|
-
`import("${resolvedPage}")`,
|
|
1798
|
-
...[...boundaryIdents.keys()].map((filePath) => `import("${filePath.replace(/\\/g, "/")}")`)
|
|
1799
|
-
];
|
|
1800
|
-
const loadBody = boundaryLiterals.length > 0 ? `Promise.all([${lazyImports.join(", ")}]).then(([__furin_page, ${[
|
|
1801
|
-
...boundaryIdents.values()
|
|
1802
|
-
].join(", ")}]) => ({ default: __furin_page.default, segmentBoundaries: [${boundaryLiterals.join(", ")}] }))` : `import("${resolvedPage}")`;
|
|
1803
|
-
routeEntries.push(` { pattern: "${route.pattern}", regex: new RegExp(${JSON.stringify(regexPattern)}), load: () => ${loadBody} }`);
|
|
1804
1823
|
}
|
|
1805
|
-
|
|
1806
|
-
|
|
1807
|
-
|
|
1808
|
-
const
|
|
1809
|
-
|
|
1810
|
-
|
|
1811
|
-
|
|
1812
|
-
|
|
1813
|
-
|
|
1814
|
-
|
|
1815
|
-
|
|
1816
|
-
|
|
1817
|
-
|
|
1818
|
-
|
|
1819
|
-
|
|
1820
|
-
|
|
1821
|
-
|
|
1822
|
-
|
|
1823
|
-
|
|
1824
|
-
|
|
1825
|
-
|
|
1826
|
-
|
|
1827
|
-
|
|
1828
|
-
|
|
1829
|
-
|
|
1830
|
-
|
|
1831
|
-
|
|
1824
|
+
return;
|
|
1825
|
+
}
|
|
1826
|
+
async function scanPageFiles(pagesDir, root) {
|
|
1827
|
+
const routes = [];
|
|
1828
|
+
const notFoundCache = new Map;
|
|
1829
|
+
const errorCache = new Map;
|
|
1830
|
+
for (const absolutePath of await collectPageFilePaths(pagesDir)) {
|
|
1831
|
+
if (!SOURCE_MODULE_EXTENSIONS.some((ext) => absolutePath.endsWith(ext))) {
|
|
1832
|
+
continue;
|
|
1833
|
+
}
|
|
1834
|
+
const relativePath = routeRelativePath(pagesDir, absolutePath);
|
|
1835
|
+
const fileName = parse3(relativePath).name;
|
|
1836
|
+
if (fileName.startsWith("_") || fileName === "root" || isConventionFileName(fileName)) {
|
|
1837
|
+
continue;
|
|
1838
|
+
}
|
|
1839
|
+
const [notFound, errorComponent, segmentBoundaries] = await Promise.all([
|
|
1840
|
+
resolveNearestConvention(absolutePath, pagesDir, "not-found", notFoundCache, root.notFound),
|
|
1841
|
+
resolveNearestConvention(absolutePath, pagesDir, "error", errorCache, root.error),
|
|
1842
|
+
collectSegmentBoundaries(absolutePath, pagesDir, notFoundCache, errorCache)
|
|
1843
|
+
]);
|
|
1844
|
+
if (IS_DEV) {
|
|
1845
|
+
const devRoute = await buildDevRoute(absolutePath, relativePath, root);
|
|
1846
|
+
devRoute.notFound = notFound;
|
|
1847
|
+
devRoute.error = errorComponent;
|
|
1848
|
+
devRoute.segmentBoundaries = segmentBoundaries;
|
|
1849
|
+
routes.push(devRoute);
|
|
1850
|
+
continue;
|
|
1851
|
+
}
|
|
1852
|
+
const ctx = getCompileContext();
|
|
1853
|
+
const pageMod = ctx?.modules[absolutePath] ?? await import(absolutePath);
|
|
1854
|
+
const page = pageMod.default;
|
|
1855
|
+
if (!isFurinPage(page)) {
|
|
1856
|
+
throw new Error(`[furin] ${relativePath}: no valid createRoute().page() export found`);
|
|
1857
|
+
}
|
|
1858
|
+
const routeChain = collectRouteChainFromRoute(page._route);
|
|
1859
|
+
validateRouteChain(routeChain, root.route, relativePath);
|
|
1860
|
+
routes.push({
|
|
1861
|
+
pattern: filePathToPattern(relativePath),
|
|
1862
|
+
page,
|
|
1863
|
+
path: absolutePath,
|
|
1864
|
+
routeChain,
|
|
1865
|
+
mode: resolveMode(page, routeChain),
|
|
1866
|
+
notFound,
|
|
1867
|
+
error: errorComponent,
|
|
1868
|
+
segmentBoundaries,
|
|
1869
|
+
tags: collectRouteTags(routeChain, page)
|
|
1870
|
+
});
|
|
1871
|
+
}
|
|
1872
|
+
return routes;
|
|
1873
|
+
}
|
|
1874
|
+
async function collectSegmentBoundaries(pageAbsolutePath, pagesDir, notFoundCache, errorCache) {
|
|
1875
|
+
const pageDir = pageAbsolutePath.slice(0, pageAbsolutePath.lastIndexOf("/"));
|
|
1876
|
+
const dirs = [pagesDir];
|
|
1877
|
+
if (pageDir.length > pagesDir.length) {
|
|
1878
|
+
const relativeTail = pageDir.slice(pagesDir.length + 1);
|
|
1879
|
+
const parts = relativeTail.split("/");
|
|
1880
|
+
let acc = pagesDir;
|
|
1881
|
+
for (const part of parts) {
|
|
1882
|
+
acc = `${acc}/${part}`;
|
|
1883
|
+
dirs.push(acc);
|
|
1884
|
+
}
|
|
1885
|
+
}
|
|
1886
|
+
const boundaries = [];
|
|
1887
|
+
for (let depth = 0;depth < dirs.length; depth++) {
|
|
1888
|
+
const dir = dirs[depth];
|
|
1889
|
+
const [errorEntry, notFoundEntry] = await Promise.all([
|
|
1890
|
+
errorCache.has(dir) ? Promise.resolve(errorCache.get(dir)) : loadConventionComponent(dir, "error").then((r) => {
|
|
1891
|
+
errorCache.set(dir, r);
|
|
1892
|
+
return r;
|
|
1893
|
+
}),
|
|
1894
|
+
notFoundCache.has(dir) ? Promise.resolve(notFoundCache.get(dir)) : loadConventionComponent(dir, "not-found").then((r) => {
|
|
1895
|
+
notFoundCache.set(dir, r);
|
|
1896
|
+
return r;
|
|
1897
|
+
})
|
|
1898
|
+
]);
|
|
1899
|
+
if (errorEntry || notFoundEntry) {
|
|
1900
|
+
boundaries.push({
|
|
1901
|
+
path: dir,
|
|
1902
|
+
depth,
|
|
1903
|
+
error: errorEntry?.component,
|
|
1904
|
+
errorPath: errorEntry?.path,
|
|
1905
|
+
notFound: notFoundEntry?.component,
|
|
1906
|
+
notFoundPath: notFoundEntry?.path
|
|
1907
|
+
});
|
|
1908
|
+
}
|
|
1909
|
+
}
|
|
1910
|
+
return boundaries;
|
|
1911
|
+
}
|
|
1912
|
+
async function resolveNearestConvention(pageAbsolutePath, pagesDir, conventionName, cache, rootFallback) {
|
|
1913
|
+
let dir = pageAbsolutePath.slice(0, pageAbsolutePath.lastIndexOf("/"));
|
|
1914
|
+
while (dir.length >= pagesDir.length) {
|
|
1915
|
+
if (!cache.has(dir)) {
|
|
1916
|
+
cache.set(dir, await loadConventionComponent(dir, conventionName));
|
|
1917
|
+
}
|
|
1918
|
+
const found = cache.get(dir);
|
|
1919
|
+
if (found) {
|
|
1920
|
+
return found.component;
|
|
1921
|
+
}
|
|
1922
|
+
if (dir === pagesDir) {
|
|
1923
|
+
break;
|
|
1924
|
+
}
|
|
1925
|
+
dir = dir.slice(0, dir.lastIndexOf("/"));
|
|
1926
|
+
}
|
|
1927
|
+
return rootFallback;
|
|
1928
|
+
}
|
|
1929
|
+
async function buildDevRoute(absolutePath, relativePath, root) {
|
|
1930
|
+
let page;
|
|
1931
|
+
let routeChain = [];
|
|
1932
|
+
try {
|
|
1933
|
+
const pageMod = await import(`${absolutePath}?furin-server&t=${Date.now()}`);
|
|
1934
|
+
if (isFurinPage(pageMod.default)) {
|
|
1935
|
+
page = pageMod.default;
|
|
1936
|
+
routeChain = collectRouteChainFromRoute(page._route);
|
|
1937
|
+
validateRouteChain(routeChain, root.route, relativePath);
|
|
1938
|
+
}
|
|
1939
|
+
} catch {}
|
|
1940
|
+
const devStubPage = {
|
|
1941
|
+
__type: "FURIN_PAGE",
|
|
1942
|
+
_route: { __type: "FURIN_ROUTE" },
|
|
1943
|
+
component: () => null
|
|
1944
|
+
};
|
|
1945
|
+
return {
|
|
1946
|
+
pattern: filePathToPattern(relativePath),
|
|
1947
|
+
path: absolutePath,
|
|
1948
|
+
mode: page ? resolveMode(page, routeChain) : "ssr",
|
|
1949
|
+
page: page ?? devStubPage,
|
|
1950
|
+
routeChain,
|
|
1951
|
+
tags: collectRouteTags(routeChain, page),
|
|
1952
|
+
segmentBoundaries: []
|
|
1953
|
+
};
|
|
1954
|
+
}
|
|
1955
|
+
var DIR_SCAN_CONCURRENCY = 8;
|
|
1956
|
+
async function collectPageFilePaths(dir) {
|
|
1957
|
+
const files = [];
|
|
1958
|
+
const entries = (await readdir(dir, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name));
|
|
1959
|
+
const resolved = await mapWithConcurrency(entries, DIR_SCAN_CONCURRENCY, async (entry) => {
|
|
1960
|
+
const absolutePath = toPosixPath(join(dir, entry.name));
|
|
1961
|
+
if (entry.isDirectory()) {
|
|
1962
|
+
return await collectPageFilePaths(absolutePath);
|
|
1963
|
+
}
|
|
1964
|
+
if (entry.isFile()) {
|
|
1965
|
+
return [absolutePath];
|
|
1966
|
+
}
|
|
1967
|
+
return [];
|
|
1968
|
+
});
|
|
1969
|
+
for (const chunk of resolved) {
|
|
1970
|
+
files.push(...chunk);
|
|
1971
|
+
}
|
|
1972
|
+
return files;
|
|
1973
|
+
}
|
|
1974
|
+
// src/server/router/schemas.ts
|
|
1975
|
+
import { t } from "elysia";
|
|
1976
|
+
import { parseQueryFromURL, parseQueryStandardSchema } from "elysia/parse-query";
|
|
1977
|
+
import { getSchemaValidator } from "elysia/schema";
|
|
1978
|
+
|
|
1979
|
+
// src/shared/search-params.ts
|
|
1980
|
+
function routeSegmentSpecificity(segment) {
|
|
1981
|
+
if (segment === "*") {
|
|
1982
|
+
return 1;
|
|
1983
|
+
}
|
|
1984
|
+
if (segment.startsWith(":")) {
|
|
1985
|
+
return 2;
|
|
1986
|
+
}
|
|
1987
|
+
return 3;
|
|
1988
|
+
}
|
|
1989
|
+
function compareSearchRouteSpecificity(a, b) {
|
|
1990
|
+
const aSegments = a.split("/").filter((segment) => segment.length > 0);
|
|
1991
|
+
const bSegments = b.split("/").filter((segment) => segment.length > 0);
|
|
1992
|
+
const length = Math.max(aSegments.length, bSegments.length);
|
|
1993
|
+
for (let i = 0;i < length; i++) {
|
|
1994
|
+
const aSegment = aSegments[i];
|
|
1995
|
+
const bSegment = bSegments[i];
|
|
1996
|
+
if (aSegment === undefined) {
|
|
1997
|
+
return -1;
|
|
1998
|
+
}
|
|
1999
|
+
if (bSegment === undefined) {
|
|
2000
|
+
return 1;
|
|
2001
|
+
}
|
|
2002
|
+
const diff = routeSegmentSpecificity(aSegment) - routeSegmentSpecificity(bSegment);
|
|
2003
|
+
if (diff !== 0) {
|
|
2004
|
+
return diff;
|
|
2005
|
+
}
|
|
2006
|
+
}
|
|
2007
|
+
return 0;
|
|
2008
|
+
}
|
|
2009
|
+
function isObject2(value) {
|
|
2010
|
+
return !!value && typeof value === "object" && !Array.isArray(value);
|
|
2011
|
+
}
|
|
2012
|
+
function arraysDeepEqual(a, b) {
|
|
2013
|
+
if (a.length !== b.length) {
|
|
2014
|
+
return false;
|
|
2015
|
+
}
|
|
2016
|
+
for (let i = 0;i < a.length; i++) {
|
|
2017
|
+
if (!deepEqual(a[i], b[i])) {
|
|
2018
|
+
return false;
|
|
2019
|
+
}
|
|
2020
|
+
}
|
|
2021
|
+
return true;
|
|
2022
|
+
}
|
|
2023
|
+
function objectsDeepEqual(a, b) {
|
|
2024
|
+
const aKeys = Object.keys(a);
|
|
2025
|
+
if (aKeys.length !== Object.keys(b).length) {
|
|
2026
|
+
return false;
|
|
2027
|
+
}
|
|
2028
|
+
for (const key of aKeys) {
|
|
2029
|
+
if (!(Object.hasOwn(b, key) && deepEqual(a[key], b[key]))) {
|
|
2030
|
+
return false;
|
|
2031
|
+
}
|
|
2032
|
+
}
|
|
2033
|
+
return true;
|
|
2034
|
+
}
|
|
2035
|
+
function deepEqual(a, b) {
|
|
2036
|
+
if (Object.is(a, b)) {
|
|
2037
|
+
return true;
|
|
2038
|
+
}
|
|
2039
|
+
if (Array.isArray(a) && Array.isArray(b)) {
|
|
2040
|
+
return arraysDeepEqual(a, b);
|
|
2041
|
+
}
|
|
2042
|
+
if (isObject2(a) && isObject2(b)) {
|
|
2043
|
+
return objectsDeepEqual(a, b);
|
|
2044
|
+
}
|
|
2045
|
+
return false;
|
|
2046
|
+
}
|
|
2047
|
+
function stripSearchDefaults(search, defaults) {
|
|
2048
|
+
if (!defaults) {
|
|
2049
|
+
return search;
|
|
2050
|
+
}
|
|
2051
|
+
const stripped = {};
|
|
2052
|
+
for (const [key, value] of Object.entries(search)) {
|
|
2053
|
+
if (Object.hasOwn(defaults, key) && deepEqual(value, defaults[key])) {
|
|
2054
|
+
continue;
|
|
2055
|
+
}
|
|
2056
|
+
stripped[key] = value;
|
|
2057
|
+
}
|
|
2058
|
+
return stripped;
|
|
2059
|
+
}
|
|
2060
|
+
function appendSearchParamValue(params, key, value) {
|
|
2061
|
+
if (value == null) {
|
|
2062
|
+
return;
|
|
2063
|
+
}
|
|
2064
|
+
if (Array.isArray(value)) {
|
|
2065
|
+
for (const item of value) {
|
|
2066
|
+
if (item != null) {
|
|
2067
|
+
params.append(key, typeof item === "object" ? JSON.stringify(item) : String(item));
|
|
2068
|
+
}
|
|
2069
|
+
}
|
|
2070
|
+
return;
|
|
2071
|
+
}
|
|
2072
|
+
params.set(key, typeof value === "object" ? JSON.stringify(value) : String(value));
|
|
2073
|
+
}
|
|
2074
|
+
function buildSearchParams(search, defaults) {
|
|
2075
|
+
const params = new URLSearchParams;
|
|
2076
|
+
for (const [key, value] of Object.entries(stripSearchDefaults(search, defaults))) {
|
|
2077
|
+
appendSearchParamValue(params, key, value);
|
|
2078
|
+
}
|
|
2079
|
+
return params;
|
|
2080
|
+
}
|
|
2081
|
+
function collectSearchDefaults(schema) {
|
|
2082
|
+
if (!(isObject2(schema) && isObject2(schema.properties))) {
|
|
2083
|
+
return;
|
|
2084
|
+
}
|
|
2085
|
+
const defaults = {};
|
|
2086
|
+
for (const [key, value] of Object.entries(schema.properties)) {
|
|
2087
|
+
if (isObject2(value) && Object.hasOwn(value, "default") && value.default != null) {
|
|
2088
|
+
defaults[key] = value.default;
|
|
2089
|
+
}
|
|
2090
|
+
}
|
|
2091
|
+
return Object.keys(defaults).length > 0 ? defaults : undefined;
|
|
2092
|
+
}
|
|
2093
|
+
function findSearchDefaults(pathname, routes) {
|
|
2094
|
+
let match;
|
|
2095
|
+
for (const route of routes) {
|
|
2096
|
+
if (!route.regex.test(pathname)) {
|
|
2097
|
+
continue;
|
|
2098
|
+
}
|
|
2099
|
+
if (!match || compareSearchRouteSpecificity(route.pattern, match.pattern) > 0) {
|
|
2100
|
+
match = route;
|
|
2101
|
+
}
|
|
2102
|
+
}
|
|
2103
|
+
return match?.searchDefaults;
|
|
2104
|
+
}
|
|
2105
|
+
function findSearchDefaultsForRouteTarget(to, routes) {
|
|
2106
|
+
if (to.startsWith("http://") || to.startsWith("https://") || to.startsWith("//")) {
|
|
2107
|
+
return;
|
|
2108
|
+
}
|
|
2109
|
+
try {
|
|
2110
|
+
const pathname = new URL(to, "http://furin.local").pathname;
|
|
2111
|
+
return findSearchDefaults(pathname, routes);
|
|
2112
|
+
} catch {
|
|
2113
|
+
return;
|
|
2114
|
+
}
|
|
2115
|
+
}
|
|
2116
|
+
|
|
2117
|
+
// src/server/router/schemas.ts
|
|
2118
|
+
function isObjectSchema(schema) {
|
|
2119
|
+
return !!schema && typeof schema === "object";
|
|
2120
|
+
}
|
|
2121
|
+
var TOBJECT_STRUCTURAL_KEYS = new Set(["type", "properties", "required"]);
|
|
2122
|
+
var TYPEBOX_KIND = Symbol.for("TypeBox.Kind");
|
|
2123
|
+
function isTypeBoxObjectSchema(schema) {
|
|
2124
|
+
return isObjectSchema(schema) && schema[TYPEBOX_KIND] === "Object";
|
|
2125
|
+
}
|
|
2126
|
+
function mergeRouteSchemas(routeChain, key) {
|
|
2127
|
+
const schemas = routeChain.flatMap((r) => r[key] ? [r[key]] : []);
|
|
2128
|
+
if (schemas.length === 0) {
|
|
2129
|
+
return;
|
|
2130
|
+
}
|
|
2131
|
+
if (schemas.length === 1) {
|
|
2132
|
+
return schemas[0];
|
|
2133
|
+
}
|
|
2134
|
+
if (schemas.some((s) => !isTypeBoxObjectSchema(s))) {
|
|
2135
|
+
throw new Error(`[furin] Merging ${key} schemas across the route chain requires TypeBox in V1. Use TypeBox for parent/child ${key}, or define ${key} only on leaf routes.`);
|
|
2136
|
+
}
|
|
2137
|
+
const mergedProperties = Object.assign({}, ...schemas.map((s) => s.properties ?? {}));
|
|
2138
|
+
const mergedOptions = Object.assign({}, ...schemas.map((s) => Object.fromEntries(Object.entries(s).filter(([k]) => !TOBJECT_STRUCTURAL_KEYS.has(k)))));
|
|
2139
|
+
return t.Object(mergedProperties, mergedOptions);
|
|
2140
|
+
}
|
|
2141
|
+
function createSearchRouteMetadata(routes) {
|
|
2142
|
+
const metadata = [];
|
|
2143
|
+
for (const route of routes) {
|
|
2144
|
+
const searchDefaults = collectSearchDefaults(mergeRouteSchemas(route.routeChain, "query"));
|
|
2145
|
+
if (!searchDefaults) {
|
|
2146
|
+
continue;
|
|
2147
|
+
}
|
|
2148
|
+
metadata.push({
|
|
2149
|
+
pattern: route.pattern,
|
|
2150
|
+
regex: buildRouteRegex(route.pattern).regex,
|
|
2151
|
+
searchDefaults
|
|
2152
|
+
});
|
|
2153
|
+
}
|
|
2154
|
+
return metadata;
|
|
2155
|
+
}
|
|
2156
|
+
// src/build/route-types.ts
|
|
2157
|
+
import { existsSync as existsSync2, readFileSync, writeFileSync } from "fs";
|
|
2158
|
+
import { join as join2 } from "path";
|
|
2159
|
+
function patternToTypeString(pattern) {
|
|
2160
|
+
const t2 = pattern.replace(/:[^/]+/g, "${string}").replace(/\*/g, "${string}");
|
|
2161
|
+
return t2.includes("${") ? `\`${t2}\`` : `"${t2}"`;
|
|
2162
|
+
}
|
|
2163
|
+
function schemaToTypeString(schema) {
|
|
2164
|
+
return schemaToTypeStringWithDefaults(schema, true);
|
|
2165
|
+
}
|
|
2166
|
+
function schemaToTypeStringWithDefaults(schema, defaultsAreRequired) {
|
|
2167
|
+
if (!schema || typeof schema !== "object") {
|
|
2168
|
+
return "unknown";
|
|
2169
|
+
}
|
|
2170
|
+
const s = schema;
|
|
2171
|
+
if (s.anyOf && Array.isArray(s.anyOf)) {
|
|
2172
|
+
const parts = [];
|
|
2173
|
+
for (const item of s.anyOf) {
|
|
2174
|
+
const t2 = schemaToTypeStringWithDefaults(item, defaultsAreRequired);
|
|
2175
|
+
if (t2 !== "null")
|
|
2176
|
+
parts.push(t2);
|
|
2177
|
+
}
|
|
2178
|
+
return parts.join(" | ") || "unknown";
|
|
2179
|
+
}
|
|
2180
|
+
switch (s.type) {
|
|
2181
|
+
case "string":
|
|
2182
|
+
return "string";
|
|
2183
|
+
case "number":
|
|
2184
|
+
case "integer":
|
|
2185
|
+
return "number";
|
|
2186
|
+
case "boolean":
|
|
2187
|
+
return "boolean";
|
|
2188
|
+
case "null":
|
|
2189
|
+
return "null";
|
|
2190
|
+
case "array": {
|
|
2191
|
+
const inner = schemaToTypeStringWithDefaults(s.items, defaultsAreRequired);
|
|
2192
|
+
return inner.includes("|") || inner.includes("&") ? `(${inner})[]` : `${inner}[]`;
|
|
2193
|
+
}
|
|
2194
|
+
case "object": {
|
|
2195
|
+
if (!s.properties || typeof s.properties !== "object") {
|
|
2196
|
+
return "Record<string, unknown>";
|
|
2197
|
+
}
|
|
2198
|
+
const required = new Set(Array.isArray(s.required) ? s.required : []);
|
|
2199
|
+
const props = Object.entries(s.properties).map(([k, v]) => {
|
|
2200
|
+
const isPresent = required.has(k) || defaultsAreRequired && hasNonNullSchemaDefault(v);
|
|
2201
|
+
return `${k}${isPresent ? "" : "?"}: ${schemaToTypeStringWithDefaults(v, defaultsAreRequired)}`;
|
|
2202
|
+
}).join("; ");
|
|
2203
|
+
return `{ ${props} }`;
|
|
2204
|
+
}
|
|
2205
|
+
default:
|
|
2206
|
+
return "unknown";
|
|
2207
|
+
}
|
|
2208
|
+
}
|
|
2209
|
+
function schemaToInputTypeString(schema) {
|
|
2210
|
+
return schemaToTypeStringWithDefaults(schema, false);
|
|
2211
|
+
}
|
|
2212
|
+
function hasNonNullSchemaDefault(schema) {
|
|
2213
|
+
if (!schema || typeof schema !== "object") {
|
|
2214
|
+
return false;
|
|
2215
|
+
}
|
|
2216
|
+
const s = schema;
|
|
2217
|
+
return "default" in s && s.default != null;
|
|
2218
|
+
}
|
|
2219
|
+
function tagKeyToPropertyName(tag) {
|
|
2220
|
+
return /^[$A-Z_a-z][$\w]*$/.test(tag) ? tag : JSON.stringify(tag);
|
|
2221
|
+
}
|
|
2222
|
+
function tagToStringLiteral(tag) {
|
|
2223
|
+
const json = JSON.stringify(tag);
|
|
2224
|
+
return `'${json.slice(1, -1).replaceAll("'", "\\'")}'`;
|
|
2225
|
+
}
|
|
2226
|
+
function writeRouteTypes(routes, projectRoot) {
|
|
2227
|
+
const sortedRoutes = [...routes].sort((a, b) => a.pattern.localeCompare(b.pattern));
|
|
2228
|
+
const entries = sortedRoutes.map((r) => {
|
|
2229
|
+
const typeKey = patternToTypeString(r.pattern);
|
|
2230
|
+
const isDynamic = typeKey.startsWith("`");
|
|
2231
|
+
const querySchema = mergeRouteSchemas(r.routeChain ?? [], "query");
|
|
2232
|
+
const searchType = querySchema ? schemaToTypeString(querySchema) : "never";
|
|
2233
|
+
const searchInputType = querySchema ? schemaToInputTypeString(querySchema) : "never";
|
|
2234
|
+
return isDynamic ? ` [key: ${typeKey}]: { search?: ${searchType}; searchInput?: ${searchInputType} }` : ` ${typeKey}: { search?: ${searchType}; searchInput?: ${searchInputType} }`;
|
|
2235
|
+
});
|
|
2236
|
+
const routeManifestEntries = entries.join(`;
|
|
2237
|
+
`);
|
|
2238
|
+
const sortedTags = [...new Set(routes.flatMap((route) => route.tags ?? []))].sort();
|
|
2239
|
+
const tagBlock = sortedTags.length > 0 ? `
|
|
2240
|
+
|
|
2241
|
+
declare module "@teyik0/furin" {
|
|
2242
|
+
interface FurinCacheTags {
|
|
2243
|
+
${sortedTags.map((tag) => ` ${tagKeyToPropertyName(tag)}: ${tagToStringLiteral(tag)};`).join(`
|
|
2244
|
+
`)}
|
|
2245
|
+
}
|
|
2246
|
+
}` : "";
|
|
2247
|
+
const content = `// Auto-generated by Furin. Do not edit manually.
|
|
2248
|
+
/// <reference types="@teyik0/furin/env" />
|
|
2249
|
+
import "@teyik0/furin/link";
|
|
2250
|
+
|
|
2251
|
+
declare module "@teyik0/furin/link" {
|
|
2252
|
+
interface RouteManifest {
|
|
2253
|
+
${routeManifestEntries};
|
|
2254
|
+
}
|
|
2255
|
+
}${tagBlock}
|
|
2256
|
+
`;
|
|
2257
|
+
const typesPath = join2(projectRoot, "furin-env.d.ts");
|
|
2258
|
+
const existing = existsSync2(typesPath) ? readFileSync(typesPath, "utf8") : "";
|
|
2259
|
+
if (content !== existing) {
|
|
2260
|
+
writeFileSync(typesPath, content);
|
|
2261
|
+
}
|
|
2262
|
+
}
|
|
2263
|
+
|
|
2264
|
+
// src/build/hydrate.ts
|
|
2265
|
+
function generateHydrateEntry(routes, rootLayout, basePath, clientLogging) {
|
|
2266
|
+
const getBoundaryIdent = (idents, filePath) => {
|
|
2267
|
+
if (!filePath) {
|
|
2268
|
+
return;
|
|
2269
|
+
}
|
|
2270
|
+
const existing = idents.get(filePath);
|
|
2271
|
+
if (existing) {
|
|
2272
|
+
return existing;
|
|
2273
|
+
}
|
|
2274
|
+
const ident = `__furin_bnd_${idents.size}`;
|
|
2275
|
+
idents.set(filePath, ident);
|
|
2276
|
+
return ident;
|
|
2277
|
+
};
|
|
2278
|
+
const routeEntries = [];
|
|
2279
|
+
for (const route of routes) {
|
|
2280
|
+
const resolvedPage = route.path.replace(/\\/g, "/");
|
|
2281
|
+
const regexPattern = buildRouteRegex(route.pattern).regex.source;
|
|
2282
|
+
const searchDefaults = collectSearchDefaults(mergeRouteSchemas(route.routeChain ?? [], "query"));
|
|
2283
|
+
const boundaryIdents = new Map;
|
|
2284
|
+
const boundaryLiterals = [];
|
|
2285
|
+
for (const seg of route.segmentBoundaries ?? []) {
|
|
2286
|
+
const errorIdent = getBoundaryIdent(boundaryIdents, seg.errorPath);
|
|
2287
|
+
const notFoundIdent = getBoundaryIdent(boundaryIdents, seg.notFoundPath);
|
|
2288
|
+
if (!(errorIdent || notFoundIdent)) {
|
|
2289
|
+
continue;
|
|
2290
|
+
}
|
|
2291
|
+
const parts = [`depth: ${seg.depth}`];
|
|
2292
|
+
if (errorIdent) {
|
|
2293
|
+
parts.push(`error: ${errorIdent}.default`);
|
|
2294
|
+
}
|
|
2295
|
+
if (notFoundIdent) {
|
|
2296
|
+
parts.push(`notFound: ${notFoundIdent}.default`);
|
|
2297
|
+
}
|
|
2298
|
+
boundaryLiterals.push(`{ ${parts.join(", ")} }`);
|
|
2299
|
+
}
|
|
2300
|
+
const lazyImports = [
|
|
2301
|
+
`import("${resolvedPage}")`,
|
|
2302
|
+
...[...boundaryIdents.keys()].map((filePath) => `import("${filePath.replace(/\\/g, "/")}")`)
|
|
2303
|
+
];
|
|
2304
|
+
const loadBody = boundaryLiterals.length > 0 ? `Promise.all([${lazyImports.join(", ")}]).then(([__furin_page, ${[
|
|
2305
|
+
...boundaryIdents.values()
|
|
2306
|
+
].join(", ")}]) => ({ default: __furin_page.default, segmentBoundaries: [${boundaryLiterals.join(", ")}] }))` : `import("${resolvedPage}")`;
|
|
2307
|
+
const searchDefaultsEntry = searchDefaults ? `, searchDefaults: ${JSON.stringify(searchDefaults)}` : "";
|
|
2308
|
+
routeEntries.push(` { pattern: "${route.pattern}", regex: new RegExp(${JSON.stringify(regexPattern)}), load: () => ${loadBody}${searchDefaultsEntry} }`);
|
|
2309
|
+
}
|
|
2310
|
+
const basePathLiteral = JSON.stringify(basePath);
|
|
2311
|
+
const pathnameExpr = basePath ? `(() => { const p = window.location.pathname; const b = ${basePathLiteral}; const stripped = (p.startsWith(b) && (p.length === b.length || p[b.length] === "/")) ? p.slice(b.length) || "/" : p; return stripped === "/" ? "/" : stripped.replace(/\\/+$/, ""); })()` : `window.location.pathname.replace(/\\/+$/, "") || "/"`;
|
|
2312
|
+
const logEndpoint = basePath ? `${JSON.stringify(basePath)} + "/_furin/ingest"` : `"/_furin/ingest"`;
|
|
2313
|
+
const loggingImports = clientLogging ? `import { initLogger, log } from "evlog";
|
|
2314
|
+
import { createHttpLogDrain } from "evlog/http";
|
|
2315
|
+
` : "";
|
|
2316
|
+
const loggerSetup = clientLogging ? `initLogger({ drain: createHttpLogDrain({ drain: { endpoint: ${logEndpoint} } }) });` : "const log = { error() {}, info() {} };";
|
|
2317
|
+
const routerProviderDefaults = `
|
|
2318
|
+
autoRefresh: true,
|
|
2319
|
+
basePath: ${basePathLiteral},
|
|
2320
|
+
defaultPreload: "intent",
|
|
2321
|
+
defaultPreloadDelay: 50,
|
|
2322
|
+
defaultPreloadStaleTime: 30000,
|
|
2323
|
+
prefetchCacheSize: 50,
|
|
2324
|
+
syncStream,`;
|
|
2325
|
+
return `import { hydrateRoot, createRoot } from "react-dom/client";
|
|
2326
|
+
import { createElement } from "react";
|
|
2327
|
+
${loggingImports}import { RouterProvider } from "@teyik0/furin/link";
|
|
2328
|
+
import { fromCrossJSON } from "@teyik0/furin/link";
|
|
2329
|
+
import type { SerovalNode } from "seroval";
|
|
2330
|
+
import { route as root } from "${rootLayout.replace(/\\/g, "/")}";
|
|
2331
|
+
|
|
2332
|
+
${loggerSetup}
|
|
2333
|
+
|
|
2334
|
+
const routes = [
|
|
2335
|
+
${routeEntries.join(`,
|
|
2336
|
+
`)}
|
|
2337
|
+
];
|
|
1832
2338
|
|
|
1833
2339
|
const pathname = ${pathnameExpr};
|
|
1834
2340
|
const _match = routes.find((r) => r.regex.test(pathname));
|
|
@@ -1842,6 +2348,9 @@ const _match = routes.find((r) => r.regex.test(pathname));
|
|
|
1842
2348
|
// former does not \u2014 so the two cases fork on _match below.
|
|
1843
2349
|
const dataEl = document.getElementById("__FURIN_DATA__");
|
|
1844
2350
|
const loaderData = dataEl ? JSON.parse(dataEl.textContent || "{}") : {};
|
|
2351
|
+
const syncEl = document.getElementById("__FURIN_SYNC__");
|
|
2352
|
+
const syncConfig = syncEl ? JSON.parse(syncEl.textContent || "{}") : {};
|
|
2353
|
+
const syncStream = typeof syncConfig.stream === "string" ? syncConfig.stream : undefined;
|
|
1845
2354
|
|
|
1846
2355
|
// \u2500\u2500 Deferred data hydration \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
1847
2356
|
// window.__FURIN_DEFERRED__ is injected by the server when a loader returns
|
|
@@ -1999,18 +2508,18 @@ const rootEl = document.getElementById("root") as HTMLElement;
|
|
|
1999
2508
|
`;
|
|
2000
2509
|
}
|
|
2001
2510
|
function writeDevFiles(routes, { outDir, rootLayout, basePath, clientLogging }, projectRoot) {
|
|
2002
|
-
if (!
|
|
2511
|
+
if (!existsSync3(outDir)) {
|
|
2003
2512
|
mkdirSync(outDir, { recursive: true });
|
|
2004
2513
|
}
|
|
2005
2514
|
const hydrateCode = generateHydrateEntry(routes, rootLayout, basePath, clientLogging);
|
|
2006
|
-
const hydratePath =
|
|
2007
|
-
const existingHydrate =
|
|
2515
|
+
const hydratePath = join3(outDir, "_hydrate.tsx");
|
|
2516
|
+
const existingHydrate = existsSync3(hydratePath) ? readFileSync2(hydratePath, "utf8") : "";
|
|
2008
2517
|
if (hydrateCode !== existingHydrate) {
|
|
2009
2518
|
writeFileSync2(hydratePath, hydrateCode);
|
|
2010
2519
|
}
|
|
2011
2520
|
const indexHtml = generateIndexHtml();
|
|
2012
|
-
const indexPath =
|
|
2013
|
-
const existingIndex =
|
|
2521
|
+
const indexPath = join3(outDir, "index.html");
|
|
2522
|
+
const existingIndex = existsSync3(indexPath) ? readFileSync2(indexPath, "utf8") : "";
|
|
2014
2523
|
if (indexHtml !== existingIndex) {
|
|
2015
2524
|
writeFileSync2(indexPath, indexHtml);
|
|
2016
2525
|
}
|
|
@@ -2019,23 +2528,25 @@ function writeDevFiles(routes, { outDir, rootLayout, basePath, clientLogging },
|
|
|
2019
2528
|
}
|
|
2020
2529
|
|
|
2021
2530
|
// src/build/shared.ts
|
|
2022
|
-
import { cpSync, existsSync as
|
|
2023
|
-
import { join as
|
|
2024
|
-
|
|
2025
|
-
var
|
|
2531
|
+
import { cpSync, existsSync as existsSync4, mkdirSync as mkdirSync2, readdirSync, rmSync } from "fs";
|
|
2532
|
+
import { join as join4, relative } from "path";
|
|
2533
|
+
import { fileURLToPath } from "url";
|
|
2534
|
+
var CLIENT_MODULE_PATH = fileURLToPath(import.meta.resolve("@teyik0/furin/client"));
|
|
2535
|
+
var LINK_MODULE_PATH = fileURLToPath(import.meta.resolve("@teyik0/furin/link"));
|
|
2536
|
+
var SEARCH_MODULE_PATH = fileURLToPath(import.meta.resolve("@teyik0/furin/search"));
|
|
2026
2537
|
function ensureDir(path) {
|
|
2027
|
-
if (!
|
|
2538
|
+
if (!existsSync4(path)) {
|
|
2028
2539
|
mkdirSync2(path, { recursive: true });
|
|
2029
2540
|
}
|
|
2030
2541
|
}
|
|
2031
|
-
function
|
|
2542
|
+
function toPosixPath2(path) {
|
|
2032
2543
|
return path.replace(/\\/g, "/");
|
|
2033
2544
|
}
|
|
2034
2545
|
function collectFilesRecursive(dir) {
|
|
2035
2546
|
const files = [];
|
|
2036
2547
|
const entries = readdirSync(dir, { withFileTypes: true });
|
|
2037
2548
|
for (const entry of entries) {
|
|
2038
|
-
const absolutePath =
|
|
2549
|
+
const absolutePath = join4(dir, entry.name);
|
|
2039
2550
|
if (entry.isDirectory()) {
|
|
2040
2551
|
files.push(...collectFilesRecursive(absolutePath));
|
|
2041
2552
|
continue;
|
|
@@ -2054,37 +2565,37 @@ function toBuildRouteManifestEntry(route, rootDir) {
|
|
|
2054
2565
|
return {
|
|
2055
2566
|
pattern: route.pattern,
|
|
2056
2567
|
mode: route.mode,
|
|
2057
|
-
pagePath:
|
|
2568
|
+
pagePath: toPosixPath2(relative(rootDir, route.path)),
|
|
2058
2569
|
hasLayout: route.routeChain.some((entry) => !!entry.layout),
|
|
2059
2570
|
hasStaticParams: !!route.page?.staticParams,
|
|
2060
2571
|
revalidate: route.page?._route.revalidate ?? null
|
|
2061
2572
|
};
|
|
2062
2573
|
}
|
|
2063
2574
|
function buildTargetManifest(rootDir, buildRoot, target, serverEntry) {
|
|
2064
|
-
const targetDir =
|
|
2575
|
+
const targetDir = join4(buildRoot, target);
|
|
2065
2576
|
return {
|
|
2066
2577
|
buildId: "",
|
|
2067
2578
|
generatedAt: new Date().toISOString(),
|
|
2068
|
-
targetDir:
|
|
2069
|
-
clientDir:
|
|
2070
|
-
templatePath:
|
|
2579
|
+
targetDir: toPosixPath2(relative(rootDir, targetDir)),
|
|
2580
|
+
clientDir: toPosixPath2(relative(rootDir, join4(targetDir, "client"))),
|
|
2581
|
+
templatePath: toPosixPath2(relative(rootDir, join4(targetDir, "client", "index.html"))),
|
|
2071
2582
|
serverPath: null,
|
|
2072
|
-
serverEntry: serverEntry ?
|
|
2583
|
+
serverEntry: serverEntry ? toPosixPath2(relative(rootDir, serverEntry)) : null
|
|
2073
2584
|
};
|
|
2074
2585
|
}
|
|
2075
2586
|
|
|
2076
2587
|
// src/build/client.ts
|
|
2077
2588
|
var TS_FILE_FILTER = /\.(tsx|ts)$/;
|
|
2078
2589
|
async function buildClient(routes, { outDir, rootLayout, plugins, publicPath, basePath, clientLogging }) {
|
|
2079
|
-
const clientDir =
|
|
2080
|
-
if (!
|
|
2590
|
+
const clientDir = join5(outDir, "client");
|
|
2591
|
+
if (!existsSync5(outDir)) {
|
|
2081
2592
|
mkdirSync3(outDir, { recursive: true });
|
|
2082
2593
|
}
|
|
2083
|
-
if (!
|
|
2594
|
+
if (!existsSync5(clientDir)) {
|
|
2084
2595
|
mkdirSync3(clientDir, { recursive: true });
|
|
2085
2596
|
}
|
|
2086
2597
|
const hydrateCode = generateHydrateEntry(routes, rootLayout, basePath, clientLogging);
|
|
2087
|
-
const hydratePath =
|
|
2598
|
+
const hydratePath = join5(outDir, "_hydrate.tsx");
|
|
2088
2599
|
writeFileSync3(hydratePath, hydrateCode);
|
|
2089
2600
|
console.log("[furin] Building production client bundle\u2026");
|
|
2090
2601
|
const transformPlugin = {
|
|
@@ -2098,7 +2609,7 @@ async function buildClient(routes, { outDir, rootLayout, plugins, publicPath, ba
|
|
|
2098
2609
|
const code = await Bun.file(path).text();
|
|
2099
2610
|
try {
|
|
2100
2611
|
const result2 = transformForClient(code, path);
|
|
2101
|
-
const transformed = result2.code.replaceAll(`"@teyik0/furin/client"`, JSON.stringify(CLIENT_MODULE_PATH)).replaceAll(`'furin/client'`, JSON.stringify(CLIENT_MODULE_PATH)).replaceAll(`"@teyik0/furin/link"`, JSON.stringify(LINK_MODULE_PATH)).replaceAll(`'furin/link'`, JSON.stringify(LINK_MODULE_PATH));
|
|
2612
|
+
const transformed = result2.code.replaceAll(`"@teyik0/furin/client"`, JSON.stringify(CLIENT_MODULE_PATH)).replaceAll(`'furin/client'`, JSON.stringify(CLIENT_MODULE_PATH)).replaceAll(`"@teyik0/furin/link"`, JSON.stringify(LINK_MODULE_PATH)).replaceAll(`'furin/link'`, JSON.stringify(LINK_MODULE_PATH)).replaceAll(`"@teyik0/furin/search"`, JSON.stringify(SEARCH_MODULE_PATH)).replaceAll(`'furin/search'`, JSON.stringify(SEARCH_MODULE_PATH));
|
|
2102
2613
|
return {
|
|
2103
2614
|
contents: transformed,
|
|
2104
2615
|
loader: path.endsWith(".tsx") ? "tsx" : "ts"
|
|
@@ -2126,7 +2637,8 @@ async function buildClient(routes, { outDir, rootLayout, plugins, publicPath, ba
|
|
|
2126
2637
|
plugins: plugins ? [...plugins, transformPlugin] : [transformPlugin],
|
|
2127
2638
|
alias: {
|
|
2128
2639
|
"@teyik0/furin/client": CLIENT_MODULE_PATH,
|
|
2129
|
-
"@teyik0/furin/link": LINK_MODULE_PATH
|
|
2640
|
+
"@teyik0/furin/link": LINK_MODULE_PATH,
|
|
2641
|
+
"@teyik0/furin/search": SEARCH_MODULE_PATH
|
|
2130
2642
|
},
|
|
2131
2643
|
define: {
|
|
2132
2644
|
"process.env.NODE_ENV": JSON.stringify("production")
|
|
@@ -2154,15 +2666,15 @@ async function buildClient(routes, { outDir, rootLayout, plugins, publicPath, ba
|
|
|
2154
2666
|
}
|
|
2155
2667
|
|
|
2156
2668
|
// src/build/compile-entry.ts
|
|
2157
|
-
import { existsSync as
|
|
2158
|
-
import { join as
|
|
2669
|
+
import { existsSync as existsSync7, writeFileSync as writeFileSync4 } from "fs";
|
|
2670
|
+
import { join as join7, relative as relative2 } from "path";
|
|
2159
2671
|
|
|
2160
2672
|
// src/build/entry-template.ts
|
|
2161
|
-
import { existsSync as
|
|
2162
|
-
import { dirname, join as
|
|
2163
|
-
import { fileURLToPath } from "url";
|
|
2164
|
-
var _pkgRoot = dirname(dirname(
|
|
2165
|
-
var _pkgSrcDirRaw =
|
|
2673
|
+
import { existsSync as existsSync6 } from "fs";
|
|
2674
|
+
import { dirname, join as join6 } from "path";
|
|
2675
|
+
import { fileURLToPath as fileURLToPath2 } from "url";
|
|
2676
|
+
var _pkgRoot = dirname(dirname(fileURLToPath2(import.meta.resolve("@teyik0/furin"))));
|
|
2677
|
+
var _pkgSrcDirRaw = existsSync6(join6(_pkgRoot, "src", "furin.ts")) ? join6(_pkgRoot, "src") : join6(_pkgRoot, "dist");
|
|
2166
2678
|
var _pkgSrcDir = _pkgSrcDirRaw.replace(/\\/g, "/");
|
|
2167
2679
|
var _ext = _pkgSrcDir.endsWith("/src") ? ".ts" : ".js";
|
|
2168
2680
|
var INTERNAL_MODULE_PATH = `${_pkgSrcDir}/server/internal${_ext}`;
|
|
@@ -2275,7 +2787,7 @@ function generateCompileEntry(options) {
|
|
|
2275
2787
|
const assetImports = [];
|
|
2276
2788
|
let embeddedBlock = [];
|
|
2277
2789
|
if (embed) {
|
|
2278
|
-
if (!
|
|
2790
|
+
if (!existsSync7(embed.clientDir)) {
|
|
2279
2791
|
throw new Error(`[furin] Client directory not found: ${embed.clientDir}. Run the client build first.`);
|
|
2280
2792
|
}
|
|
2281
2793
|
const clientFiles = collectFilesRecursive(embed.clientDir).filter((file) => !file.endsWith(".map"));
|
|
@@ -2284,10 +2796,10 @@ function generateCompileEntry(options) {
|
|
|
2284
2796
|
let assetIndex = 0;
|
|
2285
2797
|
for (const file of clientFiles) {
|
|
2286
2798
|
const varName = `_asset${assetIndex++}`;
|
|
2287
|
-
const relPath =
|
|
2799
|
+
const relPath = toPosixPath2(relative2(outDir, file));
|
|
2288
2800
|
const importPath = relPath.startsWith(".") ? relPath : `./${relPath}`;
|
|
2289
2801
|
assetImports.push(`import ${varName} from ${JSON.stringify(importPath)} with { type: "file" };`);
|
|
2290
|
-
const clientRelativePath =
|
|
2802
|
+
const clientRelativePath = toPosixPath2(relative2(embed.clientDir, file));
|
|
2291
2803
|
if (clientRelativePath === "index.html") {
|
|
2292
2804
|
templateVarName = varName;
|
|
2293
2805
|
} else {
|
|
@@ -2295,16 +2807,16 @@ function generateCompileEntry(options) {
|
|
|
2295
2807
|
}
|
|
2296
2808
|
}
|
|
2297
2809
|
if (templateVarName === null) {
|
|
2298
|
-
throw new Error(`[furin] Embed mode requires a client index.html at ${
|
|
2810
|
+
throw new Error(`[furin] Embed mode requires a client index.html at ${join7(embed.clientDir, "index.html")}. Run the client build first.`);
|
|
2299
2811
|
}
|
|
2300
|
-
if (publicDir &&
|
|
2812
|
+
if (publicDir && existsSync7(publicDir)) {
|
|
2301
2813
|
const publicFiles = collectFilesRecursive(publicDir);
|
|
2302
2814
|
for (const file of publicFiles) {
|
|
2303
2815
|
const varName = `_asset${assetIndex++}`;
|
|
2304
|
-
const relPath =
|
|
2816
|
+
const relPath = toPosixPath2(relative2(outDir, file));
|
|
2305
2817
|
const importPath = relPath.startsWith(".") ? relPath : `./${relPath}`;
|
|
2306
2818
|
assetImports.push(`import ${varName} from ${JSON.stringify(importPath)} with { type: "file" };`);
|
|
2307
|
-
const publicRelativePath =
|
|
2819
|
+
const publicRelativePath = toPosixPath2(relative2(publicDir, file));
|
|
2308
2820
|
assetEntries.push(` ${JSON.stringify(`/public/${publicRelativePath}`)}: ${varName},`);
|
|
2309
2821
|
}
|
|
2310
2822
|
}
|
|
@@ -2317,102 +2829,43 @@ function generateCompileEntry(options) {
|
|
|
2317
2829
|
" },"
|
|
2318
2830
|
];
|
|
2319
2831
|
}
|
|
2320
|
-
const source = buildEntrySource({
|
|
2321
|
-
buildId,
|
|
2322
|
-
headerComment: "// Auto-generated by furin compile \u2014 do not edit",
|
|
2323
|
-
rootPath,
|
|
2324
|
-
routes,
|
|
2325
|
-
serverEntry,
|
|
2326
|
-
extraImports: assetImports,
|
|
2327
|
-
extraContext: embeddedBlock,
|
|
2328
|
-
rootConventions,
|
|
2329
|
-
routeMetadata,
|
|
2330
|
-
ssgCache
|
|
2331
|
-
});
|
|
2332
|
-
const entryPath =
|
|
2333
|
-
writeFileSync4(entryPath, source);
|
|
2334
|
-
return entryPath;
|
|
2335
|
-
}
|
|
2336
|
-
|
|
2337
|
-
// src/build/server-routes-entry.ts
|
|
2338
|
-
import { writeFileSync as writeFileSync5 } from "fs";
|
|
2339
|
-
import { join as join7 } from "path";
|
|
2340
|
-
function generateServerRoutesEntry(options) {
|
|
2341
|
-
const { buildId, outDir, rootPath, routes, serverEntry, rootConventions, routeMetadata, ssgCache } = options;
|
|
2342
|
-
ensureDir(outDir);
|
|
2343
|
-
const source = buildEntrySource({
|
|
2344
|
-
buildId,
|
|
2345
|
-
headerComment: "// Auto-generated by furin build \u2014 do not edit",
|
|
2346
|
-
rootPath,
|
|
2347
|
-
routes,
|
|
2348
|
-
serverEntry,
|
|
2349
|
-
rootConventions,
|
|
2350
|
-
routeMetadata,
|
|
2351
|
-
ssgCache
|
|
2352
|
-
});
|
|
2353
|
-
const entryPath = join7(outDir, "server.ts");
|
|
2354
|
-
writeFileSync5(entryPath, source);
|
|
2355
|
-
return entryPath;
|
|
2356
|
-
}
|
|
2357
|
-
// src/shared/utils/index.ts
|
|
2358
|
-
function isFurinPage(value) {
|
|
2359
|
-
return typeof value === "object" && value !== null && "__type" in value && value.__type === "FURIN_PAGE";
|
|
2360
|
-
}
|
|
2361
|
-
function isFurinRoute(value) {
|
|
2362
|
-
return typeof value === "object" && value !== null && "__type" in value && value.__type === "FURIN_ROUTE";
|
|
2363
|
-
}
|
|
2364
|
-
function collectRouteChainFromRoute(route) {
|
|
2365
|
-
const chain = [];
|
|
2366
|
-
let current = route;
|
|
2367
|
-
while (current) {
|
|
2368
|
-
chain.unshift(current);
|
|
2369
|
-
current = current.parent;
|
|
2370
|
-
}
|
|
2371
|
-
return chain;
|
|
2372
|
-
}
|
|
2373
|
-
function hasCycle(route) {
|
|
2374
|
-
const visited = new Set;
|
|
2375
|
-
let current = route;
|
|
2376
|
-
while (current) {
|
|
2377
|
-
if (visited.has(current)) {
|
|
2378
|
-
return true;
|
|
2379
|
-
}
|
|
2380
|
-
visited.add(current);
|
|
2381
|
-
current = current.parent;
|
|
2382
|
-
}
|
|
2383
|
-
return false;
|
|
2384
|
-
}
|
|
2385
|
-
async function mapWithConcurrency(items, concurrency, fn) {
|
|
2386
|
-
if (items.length === 0) {
|
|
2387
|
-
return [];
|
|
2388
|
-
}
|
|
2389
|
-
const results = new Array(items.length);
|
|
2390
|
-
let cursor = 0;
|
|
2391
|
-
const workerCount = Math.min(Math.max(concurrency, 1), items.length);
|
|
2392
|
-
await Promise.all(Array.from({ length: workerCount }, async () => {
|
|
2393
|
-
while (true) {
|
|
2394
|
-
const index = cursor++;
|
|
2395
|
-
if (index >= items.length) {
|
|
2396
|
-
return;
|
|
2397
|
-
}
|
|
2398
|
-
results[index] = await fn(items[index], index);
|
|
2399
|
-
}
|
|
2400
|
-
}));
|
|
2401
|
-
return results;
|
|
2402
|
-
}
|
|
2403
|
-
function validateRouteChain(chain, root, pagePath) {
|
|
2404
|
-
const hasRoot = chain.some((r) => r === root);
|
|
2405
|
-
if (!hasRoot) {
|
|
2406
|
-
const location = pagePath ? `in ${pagePath}` : "";
|
|
2407
|
-
throw new Error(`[furin] Page ${location} must inherit from root route. ` + 'Add: import { route } from "./root"; and use route.page() or set parent: route');
|
|
2408
|
-
}
|
|
2409
|
-
for (const route of chain) {
|
|
2410
|
-
if (hasCycle(route)) {
|
|
2411
|
-
throw new Error("[furin] Cycle detected in route chain. A route cannot be its own ancestor.");
|
|
2412
|
-
}
|
|
2413
|
-
}
|
|
2832
|
+
const source = buildEntrySource({
|
|
2833
|
+
buildId,
|
|
2834
|
+
headerComment: "// Auto-generated by furin compile \u2014 do not edit",
|
|
2835
|
+
rootPath,
|
|
2836
|
+
routes,
|
|
2837
|
+
serverEntry,
|
|
2838
|
+
extraImports: assetImports,
|
|
2839
|
+
extraContext: embeddedBlock,
|
|
2840
|
+
rootConventions,
|
|
2841
|
+
routeMetadata,
|
|
2842
|
+
ssgCache
|
|
2843
|
+
});
|
|
2844
|
+
const entryPath = join7(outDir, "_compile-entry.ts");
|
|
2845
|
+
writeFileSync4(entryPath, source);
|
|
2846
|
+
return entryPath;
|
|
2414
2847
|
}
|
|
2415
2848
|
|
|
2849
|
+
// src/build/server-routes-entry.ts
|
|
2850
|
+
import { writeFileSync as writeFileSync5 } from "fs";
|
|
2851
|
+
import { join as join8 } from "path";
|
|
2852
|
+
function generateServerRoutesEntry(options) {
|
|
2853
|
+
const { buildId, outDir, rootPath, routes, serverEntry, rootConventions, routeMetadata, ssgCache } = options;
|
|
2854
|
+
ensureDir(outDir);
|
|
2855
|
+
const source = buildEntrySource({
|
|
2856
|
+
buildId,
|
|
2857
|
+
headerComment: "// Auto-generated by furin build \u2014 do not edit",
|
|
2858
|
+
rootPath,
|
|
2859
|
+
routes,
|
|
2860
|
+
serverEntry,
|
|
2861
|
+
rootConventions,
|
|
2862
|
+
routeMetadata,
|
|
2863
|
+
ssgCache
|
|
2864
|
+
});
|
|
2865
|
+
const entryPath = join8(outDir, "server.ts");
|
|
2866
|
+
writeFileSync5(entryPath, source);
|
|
2867
|
+
return entryPath;
|
|
2868
|
+
}
|
|
2416
2869
|
// src/server/auto-invalidate/registry.ts
|
|
2417
2870
|
class AutoInvalidateRegistry {
|
|
2418
2871
|
pathToTags = new Map;
|
|
@@ -2582,13 +3035,15 @@ function setSSGCache(key, entry) {
|
|
|
2582
3035
|
|
|
2583
3036
|
// src/server/context-logger.ts
|
|
2584
3037
|
import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
|
|
2585
|
-
|
|
2586
|
-
// ../../node_modules/.bun/evlog@2.18.1+21e9b0bb4450b609/node_modules/evlog/dist/utils.mjs
|
|
3038
|
+
// ../../node_modules/.bun/evlog@2.19.2+7724ce3de6b3bca4/node_modules/evlog/dist/utils.mjs
|
|
2587
3039
|
function formatDuration(ms) {
|
|
2588
3040
|
if (ms < 1000)
|
|
2589
3041
|
return `${Math.round(ms)}ms`;
|
|
2590
3042
|
return `${(ms / 1000).toFixed(2)}s`;
|
|
2591
3043
|
}
|
|
3044
|
+
function isServer() {
|
|
3045
|
+
return typeof window === "undefined";
|
|
3046
|
+
}
|
|
2592
3047
|
function isBrowser() {
|
|
2593
3048
|
if (typeof window === "undefined")
|
|
2594
3049
|
return false;
|
|
@@ -2679,25 +3134,468 @@ var SENSITIVE_HEADERS = [
|
|
|
2679
3134
|
"x-auth-token",
|
|
2680
3135
|
"proxy-authorization"
|
|
2681
3136
|
];
|
|
3137
|
+
var SENSITIVE_HEADER_SET = new Set(SENSITIVE_HEADERS);
|
|
2682
3138
|
function filterSafeHeaders(headers) {
|
|
2683
3139
|
const safeHeaders = {};
|
|
2684
3140
|
for (const [key, value] of Object.entries(headers))
|
|
2685
|
-
if (value !== undefined && !
|
|
3141
|
+
if (value !== undefined && !SENSITIVE_HEADER_SET.has(key.toLowerCase()))
|
|
2686
3142
|
safeHeaders[key] = value;
|
|
2687
3143
|
return safeHeaders;
|
|
2688
3144
|
}
|
|
2689
3145
|
var patternCache = /* @__PURE__ */ new Map;
|
|
2690
|
-
function
|
|
2691
|
-
|
|
3146
|
+
function globToRegExp(pattern, separator = "/") {
|
|
3147
|
+
const cacheKey = `${separator}:${pattern}`;
|
|
3148
|
+
let regex = patternCache.get(cacheKey);
|
|
2692
3149
|
if (!regex) {
|
|
2693
|
-
const
|
|
3150
|
+
const segment = separator === "/" ? "[^/]*" : "[^.]*";
|
|
3151
|
+
const char = separator === "/" ? "[^/]" : "[^.]";
|
|
3152
|
+
const regexPattern = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*\*/g, "{{GLOBSTAR}}").replace(/\*/g, segment).replace(/{{GLOBSTAR}}/g, ".*").replace(/\?/g, char);
|
|
2694
3153
|
regex = new RegExp(`^${regexPattern}$`);
|
|
2695
|
-
patternCache.set(
|
|
3154
|
+
patternCache.set(cacheKey, regex);
|
|
3155
|
+
}
|
|
3156
|
+
return regex;
|
|
3157
|
+
}
|
|
3158
|
+
function matchesPattern(path, pattern) {
|
|
3159
|
+
return globToRegExp(pattern, "/").test(path);
|
|
3160
|
+
}
|
|
3161
|
+
|
|
3162
|
+
// ../../node_modules/.bun/evlog@2.19.2+7724ce3de6b3bca4/node_modules/evlog/dist/pretty-error-THg0U0w9.mjs
|
|
3163
|
+
var snippetReader = null;
|
|
3164
|
+
var PRETTY_ERROR_TREE_SPACER = "__EVLOG_TREE_SPACER__";
|
|
3165
|
+
function pushTreeSpacer(children) {
|
|
3166
|
+
children.push(PRETTY_ERROR_TREE_SPACER);
|
|
3167
|
+
}
|
|
3168
|
+
var SKIP_PATH_RE = /(?:^|[/\\])(?:node_modules|\.nuxt|\.next|\.output)(?:[/\\]|$)/;
|
|
3169
|
+
var SKIP_FRAME_PATH_RE = /(?:^|[/\\])(?:packages[/\\]evlog|evlog[/\\](?:dist|src))(?:[/\\]|$)/;
|
|
3170
|
+
var SKIP_FRAME_FN_RE = /^(?:createError|EvlogError|new EvlogError)$/;
|
|
3171
|
+
function isPlainObject(val) {
|
|
3172
|
+
return val !== null && typeof val === "object" && !Array.isArray(val);
|
|
3173
|
+
}
|
|
3174
|
+
function pickString(obj, key) {
|
|
3175
|
+
const val = obj[key];
|
|
3176
|
+
return typeof val === "string" && val.length > 0 ? val : undefined;
|
|
3177
|
+
}
|
|
3178
|
+
function pickNumber(obj, key) {
|
|
3179
|
+
const val = obj[key];
|
|
3180
|
+
return typeof val === "number" ? val : undefined;
|
|
3181
|
+
}
|
|
3182
|
+
function extractGuidance(data) {
|
|
3183
|
+
return {
|
|
3184
|
+
code: pickString(data, "code"),
|
|
3185
|
+
why: pickString(data, "why"),
|
|
3186
|
+
fix: pickString(data, "fix"),
|
|
3187
|
+
link: pickString(data, "link")
|
|
3188
|
+
};
|
|
3189
|
+
}
|
|
3190
|
+
function normalizeErrorContext(error) {
|
|
3191
|
+
if (error === null || error === undefined)
|
|
3192
|
+
return null;
|
|
3193
|
+
if (typeof error === "string")
|
|
3194
|
+
return { message: error };
|
|
3195
|
+
if (!isPlainObject(error))
|
|
3196
|
+
return { message: String(error) };
|
|
3197
|
+
const result = {
|
|
3198
|
+
message: pickString(error, "message") ?? pickString(error, "statusText") ?? pickString(error, "statusMessage") ?? "Unknown error",
|
|
3199
|
+
name: pickString(error, "name"),
|
|
3200
|
+
code: pickString(error, "code"),
|
|
3201
|
+
why: pickString(error, "why"),
|
|
3202
|
+
fix: pickString(error, "fix"),
|
|
3203
|
+
link: pickString(error, "link"),
|
|
3204
|
+
status: pickNumber(error, "status") ?? pickNumber(error, "statusCode"),
|
|
3205
|
+
stack: pickString(error, "stack")
|
|
3206
|
+
};
|
|
3207
|
+
const { data, cause } = error;
|
|
3208
|
+
if (isPlainObject(data)) {
|
|
3209
|
+
const guidance = extractGuidance(data);
|
|
3210
|
+
if (!result.code)
|
|
3211
|
+
result.code = guidance.code;
|
|
3212
|
+
if (!result.why)
|
|
3213
|
+
result.why = guidance.why;
|
|
3214
|
+
if (!result.fix)
|
|
3215
|
+
result.fix = guidance.fix;
|
|
3216
|
+
if (!result.link)
|
|
3217
|
+
result.link = guidance.link;
|
|
3218
|
+
}
|
|
3219
|
+
if (cause instanceof Error)
|
|
3220
|
+
result.cause = cause.message;
|
|
3221
|
+
else if (isPlainObject(cause) && pickString(cause, "message"))
|
|
3222
|
+
result.cause = pickString(cause, "message");
|
|
3223
|
+
return result;
|
|
3224
|
+
}
|
|
3225
|
+
function decodeFileUrl(file) {
|
|
3226
|
+
if (file.startsWith("file://"))
|
|
3227
|
+
try {
|
|
3228
|
+
return decodeURIComponent(new URL(file).pathname);
|
|
3229
|
+
} catch {
|
|
3230
|
+
return file.slice(7);
|
|
3231
|
+
}
|
|
3232
|
+
return file;
|
|
3233
|
+
}
|
|
3234
|
+
function isAppPath(file) {
|
|
3235
|
+
const normalized = decodeFileUrl(file).replace(/\\/g, "/");
|
|
3236
|
+
if (normalized.startsWith("node:"))
|
|
3237
|
+
return false;
|
|
3238
|
+
if (SKIP_PATH_RE.test(normalized))
|
|
3239
|
+
return false;
|
|
3240
|
+
if (normalized.includes("/node_modules/"))
|
|
3241
|
+
return false;
|
|
3242
|
+
if (isFrameworkRuntimePath(normalized))
|
|
3243
|
+
return false;
|
|
3244
|
+
return true;
|
|
3245
|
+
}
|
|
3246
|
+
function formatDisplayPath(file, cwd) {
|
|
3247
|
+
const decoded = decodeFileUrl(file).replace(/\\/g, "/");
|
|
3248
|
+
const cwdNorm = cwd.replace(/\\/g, "/").replace(/\/$/, "");
|
|
3249
|
+
if (cwdNorm && decoded.startsWith(`${cwdNorm}/`)) {
|
|
3250
|
+
const rel = decoded.slice(cwdNorm.length + 1);
|
|
3251
|
+
return rel.startsWith("./") ? rel.slice(2) : rel;
|
|
3252
|
+
}
|
|
3253
|
+
const serverIdx = decoded.indexOf("/server/");
|
|
3254
|
+
if (serverIdx >= 0)
|
|
3255
|
+
return decoded.slice(serverIdx + 1);
|
|
3256
|
+
const srcIdx = decoded.indexOf("/src/");
|
|
3257
|
+
if (srcIdx >= 0)
|
|
3258
|
+
return decoded.slice(srcIdx + 1);
|
|
3259
|
+
return decoded;
|
|
3260
|
+
}
|
|
3261
|
+
function compactStackForStorage(stack, maxFrames = 5) {
|
|
3262
|
+
if (!stack)
|
|
3263
|
+
return;
|
|
3264
|
+
const head = stack.split(`
|
|
3265
|
+
`)[0] ?? "";
|
|
3266
|
+
const useful = parseStackFrames(stack).filter((f) => f.file && f.line && f.isApp && !isInternalErrorFrame(f)).slice(0, maxFrames);
|
|
3267
|
+
if (useful.length === 0)
|
|
3268
|
+
return stack;
|
|
3269
|
+
return [head, ...useful.map((f) => f.raw)].join(`
|
|
3270
|
+
`);
|
|
3271
|
+
}
|
|
3272
|
+
function parseStackFrames(stack) {
|
|
3273
|
+
if (!stack)
|
|
3274
|
+
return [];
|
|
3275
|
+
const lines = stack.split(`
|
|
3276
|
+
`);
|
|
3277
|
+
const frames = [];
|
|
3278
|
+
for (const line of lines) {
|
|
3279
|
+
const trimmed = line.trim();
|
|
3280
|
+
if (!trimmed.startsWith("at "))
|
|
3281
|
+
continue;
|
|
3282
|
+
const withFn = trimmed.match(/^at (.+?) \((.+):(\d+):(\d+)\)$/);
|
|
3283
|
+
if (withFn) {
|
|
3284
|
+
const [, fn, file, lineStr, colStr] = withFn;
|
|
3285
|
+
frames.push({
|
|
3286
|
+
raw: trimmed,
|
|
3287
|
+
fn,
|
|
3288
|
+
file,
|
|
3289
|
+
line: Number(lineStr),
|
|
3290
|
+
column: Number(colStr),
|
|
3291
|
+
isApp: isAppPath(file)
|
|
3292
|
+
});
|
|
3293
|
+
continue;
|
|
3294
|
+
}
|
|
3295
|
+
const withoutFn = trimmed.match(/^at (.+):(\d+):(\d+)$/);
|
|
3296
|
+
if (withoutFn) {
|
|
3297
|
+
const [, file, lineStr, colStr] = withoutFn;
|
|
3298
|
+
frames.push({
|
|
3299
|
+
raw: trimmed,
|
|
3300
|
+
file,
|
|
3301
|
+
line: Number(lineStr),
|
|
3302
|
+
column: Number(colStr),
|
|
3303
|
+
isApp: isAppPath(file)
|
|
3304
|
+
});
|
|
3305
|
+
continue;
|
|
3306
|
+
}
|
|
3307
|
+
const asyncFn = trimmed.match(/^at async (.+?) \((.+):(\d+):(\d+)\)$/);
|
|
3308
|
+
if (asyncFn) {
|
|
3309
|
+
const [, fn, file, lineStr, colStr] = asyncFn;
|
|
3310
|
+
frames.push({
|
|
3311
|
+
raw: trimmed,
|
|
3312
|
+
fn: `async ${fn}`,
|
|
3313
|
+
file,
|
|
3314
|
+
line: Number(lineStr),
|
|
3315
|
+
column: Number(colStr),
|
|
3316
|
+
isApp: isAppPath(file)
|
|
3317
|
+
});
|
|
3318
|
+
}
|
|
3319
|
+
}
|
|
3320
|
+
return frames;
|
|
3321
|
+
}
|
|
3322
|
+
function isFrameworkRuntimePath(path) {
|
|
3323
|
+
const normalized = path.replace(/\\/g, "/");
|
|
3324
|
+
return normalized.includes("route-modules/") || normalized.includes("webpack://next/") || normalized.includes("/next/dist/") || normalized.includes("/compiled/next-server/");
|
|
3325
|
+
}
|
|
3326
|
+
function isFrameworkRuntimeFrame(frame) {
|
|
3327
|
+
if (!frame.file)
|
|
3328
|
+
return false;
|
|
3329
|
+
return isFrameworkRuntimePath(decodeFileUrl(frame.file));
|
|
3330
|
+
}
|
|
3331
|
+
function isInternalErrorFrame(frame) {
|
|
3332
|
+
if (isFrameworkRuntimeFrame(frame))
|
|
3333
|
+
return true;
|
|
3334
|
+
if (frame.fn) {
|
|
3335
|
+
const fn = frame.fn.replace(/^async /, "");
|
|
3336
|
+
if (SKIP_FRAME_FN_RE.test(fn))
|
|
3337
|
+
return true;
|
|
3338
|
+
}
|
|
3339
|
+
if (!frame.file)
|
|
3340
|
+
return true;
|
|
3341
|
+
const path = decodeFileUrl(frame.file).replace(/\\/g, "/");
|
|
3342
|
+
if (SKIP_FRAME_PATH_RE.test(path))
|
|
3343
|
+
return true;
|
|
3344
|
+
if (path.includes(".nuxt/"))
|
|
3345
|
+
return true;
|
|
3346
|
+
if (path.includes(".next/"))
|
|
3347
|
+
return true;
|
|
3348
|
+
return false;
|
|
3349
|
+
}
|
|
3350
|
+
function pickPrimaryFrame(frames) {
|
|
3351
|
+
for (const frame of frames)
|
|
3352
|
+
if (frame.isApp && frame.file && frame.line && !isInternalErrorFrame(frame))
|
|
3353
|
+
return frame;
|
|
3354
|
+
}
|
|
3355
|
+
function readCodeSnippet(file, line, contextLines = 2) {
|
|
3356
|
+
if (!isDev() || isBrowser() || !snippetReader)
|
|
3357
|
+
return null;
|
|
3358
|
+
const path = decodeFileUrl(file).replace(/\\/g, "/");
|
|
3359
|
+
if (path.includes(".next/") || path.includes(".nuxt/") || path.includes(".output/"))
|
|
3360
|
+
return null;
|
|
3361
|
+
return snippetReader(file, line, contextLines);
|
|
3362
|
+
}
|
|
3363
|
+
function formatSnippetLines(snippet) {
|
|
3364
|
+
const width = String(snippet[snippet.length - 1]?.line ?? 0).length;
|
|
3365
|
+
return snippet.map(({ line, content, isErrorLine }) => {
|
|
3366
|
+
const marker = isErrorLine ? `${colors.red}\u276F${colors.reset}` : `${colors.dim} ${colors.reset}`;
|
|
3367
|
+
const numColor = isErrorLine ? colors.red : colors.gray;
|
|
3368
|
+
const trimmed = content.length > 120 ? `${content.slice(0, 117)}\u2026` : content;
|
|
3369
|
+
return `${marker} ${numColor}${String(line).padStart(width, " ")}${colors.reset} ${colors.dim}\u2503${colors.reset} ${colors.dim}${trimmed}${colors.reset}`;
|
|
3370
|
+
});
|
|
3371
|
+
}
|
|
3372
|
+
function formatFrameLocation(frame, cwd) {
|
|
3373
|
+
const file = frame.file ? formatDisplayPath(frame.file, cwd) : "unknown";
|
|
3374
|
+
const loc = frame.line ? `${file}:${frame.line}` : file;
|
|
3375
|
+
const fn = frame.fn && frame.fn !== "<unknown>" ? frame.fn : undefined;
|
|
3376
|
+
return fn ? `at ${fn} (${loc})` : `at ${loc}`;
|
|
3377
|
+
}
|
|
3378
|
+
function formatCollapsedFrame(frame, cwd) {
|
|
3379
|
+
const file = frame.file ? formatDisplayPath(frame.file, cwd) : "unknown";
|
|
3380
|
+
const loc = frame.line ? `${file}:${frame.line}` : file;
|
|
3381
|
+
const prefix = frame.fn?.startsWith("async") ? "at async " : "at ";
|
|
3382
|
+
const fn = frame.fn?.replace(/^async /, "");
|
|
3383
|
+
if (fn && fn !== "<unknown>" && fn !== loc)
|
|
3384
|
+
return `${prefix}${fn} (${loc})`;
|
|
3385
|
+
return `${prefix}${loc}`;
|
|
3386
|
+
}
|
|
3387
|
+
var GUIDANCE_WRAP_WIDTH = 76;
|
|
3388
|
+
var GUIDANCE_CONTINUATION = " ";
|
|
3389
|
+
function formatGuidanceLine(label, text, labelColor) {
|
|
3390
|
+
const prefix = `${labelColor}${label}:${colors.reset} `;
|
|
3391
|
+
const lines = [];
|
|
3392
|
+
let remaining = text.trim();
|
|
3393
|
+
let first = true;
|
|
3394
|
+
while (remaining.length > 0) {
|
|
3395
|
+
const budget = first ? Math.max(24, GUIDANCE_WRAP_WIDTH - prefix.length) : Math.max(24, GUIDANCE_WRAP_WIDTH - 5);
|
|
3396
|
+
if (remaining.length <= budget) {
|
|
3397
|
+
lines.push(first ? `${prefix}${remaining}` : `${GUIDANCE_CONTINUATION}${remaining}`);
|
|
3398
|
+
break;
|
|
3399
|
+
}
|
|
3400
|
+
let split = remaining.lastIndexOf(" ", budget);
|
|
3401
|
+
if (split <= 0)
|
|
3402
|
+
split = budget;
|
|
3403
|
+
const chunk = remaining.slice(0, split).trimEnd();
|
|
3404
|
+
lines.push(first ? `${prefix}${chunk}` : `${GUIDANCE_CONTINUATION}${chunk}`);
|
|
3405
|
+
remaining = remaining.slice(split).trimStart();
|
|
3406
|
+
first = false;
|
|
2696
3407
|
}
|
|
2697
|
-
return
|
|
3408
|
+
return lines;
|
|
2698
3409
|
}
|
|
3410
|
+
function buildErrorEntries(error, options = {}) {
|
|
3411
|
+
const normalized = normalizeErrorContext(error);
|
|
3412
|
+
if (!normalized)
|
|
3413
|
+
return [];
|
|
3414
|
+
const cwd = options.cwd ?? (typeof process !== "undefined" && typeof process.cwd === "function" ? process.cwd() : ".");
|
|
3415
|
+
const compact = options.compact ?? isDev();
|
|
3416
|
+
const guidanceOnly = (options.detail ?? "full") === "guidance";
|
|
3417
|
+
const showFrames = !guidanceOnly && !isBrowser() && (options.snippet ?? isDev());
|
|
3418
|
+
const stackDepth = guidanceOnly ? 0 : options.stackDepth ?? (compact ? 2 : 3);
|
|
3419
|
+
const snippetContextLines = compact ? 1 : 2;
|
|
3420
|
+
const children = [];
|
|
3421
|
+
const frames = guidanceOnly ? [] : parseStackFrames(normalized.stack);
|
|
3422
|
+
const primary = guidanceOnly ? undefined : pickPrimaryFrame(frames);
|
|
3423
|
+
if (!guidanceOnly && primary?.file && primary.line) {
|
|
3424
|
+
pushTreeSpacer(children);
|
|
3425
|
+
if (showFrames) {
|
|
3426
|
+
const snippet = readCodeSnippet(primary.file, primary.line, snippetContextLines);
|
|
3427
|
+
children.push(`${colors.dim} ${formatFrameLocation(primary, cwd)}${colors.reset}`);
|
|
3428
|
+
if (snippet)
|
|
3429
|
+
children.push(...formatSnippetLines(snippet));
|
|
3430
|
+
} else
|
|
3431
|
+
children.push(`${colors.dim} ${formatFrameLocation(primary, cwd)}${colors.reset}`);
|
|
3432
|
+
}
|
|
3433
|
+
if (normalized.code)
|
|
3434
|
+
children.push(`${colors.dim}Code:${colors.reset} ${normalized.code}`);
|
|
3435
|
+
if (Boolean(normalized.why || normalized.fix || normalized.link))
|
|
3436
|
+
pushTreeSpacer(children);
|
|
3437
|
+
if (normalized.why)
|
|
3438
|
+
children.push(...formatGuidanceLine("Why", normalized.why, colors.yellow));
|
|
3439
|
+
if (normalized.fix)
|
|
3440
|
+
children.push(...formatGuidanceLine("Fix", normalized.fix, colors.cyan));
|
|
3441
|
+
if (normalized.link)
|
|
3442
|
+
children.push(`${colors.dim}More:${colors.reset} ${normalized.link}`);
|
|
3443
|
+
if (normalized.cause && normalized.cause !== normalized.message)
|
|
3444
|
+
children.push(`${colors.dim}Caused by:${colors.reset} ${normalized.cause}`);
|
|
3445
|
+
const hiddenCount = guidanceOnly ? 0 : frames.filter((f) => !f.isApp || isInternalErrorFrame(f)).length;
|
|
3446
|
+
const tailFrames = stackDepth > 0 ? frames.filter((f) => f !== primary && !isInternalErrorFrame(f)).slice(0, stackDepth) : [];
|
|
3447
|
+
if (!guidanceOnly && (hiddenCount > 0 || tailFrames.length > 0)) {
|
|
3448
|
+
pushTreeSpacer(children);
|
|
3449
|
+
if (hiddenCount > 0)
|
|
3450
|
+
children.push(`${colors.gray}stack (${hiddenCount} frame${hiddenCount === 1 ? "" : "s"} hidden in node_modules)${colors.reset}`);
|
|
3451
|
+
else
|
|
3452
|
+
children.push(`${colors.gray}stack${colors.reset}`);
|
|
3453
|
+
for (const frame of tailFrames)
|
|
3454
|
+
children.push(`${colors.gray} ${formatCollapsedFrame(frame, cwd)}${colors.reset}`);
|
|
3455
|
+
}
|
|
3456
|
+
return [{
|
|
3457
|
+
key: "error",
|
|
3458
|
+
value: `${colors.red}${colors.bold}${normalized.message}${colors.reset}`,
|
|
3459
|
+
children: children.length > 0 ? children : undefined
|
|
3460
|
+
}];
|
|
3461
|
+
}
|
|
3462
|
+
|
|
3463
|
+
// ../../node_modules/.bun/evlog@2.19.2+7724ce3de6b3bca4/node_modules/evlog/dist/dev-terminal-D4UaEm17.mjs
|
|
3464
|
+
var DEV_PRESETS = {
|
|
3465
|
+
evlog: {
|
|
3466
|
+
frameworkOverlay: false,
|
|
3467
|
+
detail: "full"
|
|
3468
|
+
},
|
|
3469
|
+
nitro: {
|
|
3470
|
+
frameworkOverlay: true,
|
|
3471
|
+
detail: "guidance"
|
|
3472
|
+
},
|
|
3473
|
+
both: {
|
|
3474
|
+
frameworkOverlay: true,
|
|
3475
|
+
detail: "full"
|
|
3476
|
+
}
|
|
3477
|
+
};
|
|
3478
|
+
function finalizePrettyError(partial, frameworkOverlay, pretty, inDev) {
|
|
3479
|
+
const compact = partial.compact ?? (inDev && pretty);
|
|
3480
|
+
const detail = partial.detail ?? (frameworkOverlay ? "guidance" : "full");
|
|
3481
|
+
const stackDepth = detail === "guidance" ? 0 : partial.stackDepth ?? (compact ? 2 : 3);
|
|
3482
|
+
return {
|
|
3483
|
+
snippet: partial.snippet ?? (detail === "full" && pretty && inDev),
|
|
3484
|
+
stackDepth,
|
|
3485
|
+
compact,
|
|
3486
|
+
detail
|
|
3487
|
+
};
|
|
3488
|
+
}
|
|
3489
|
+
function resolveDevTerminal(input = {}) {
|
|
3490
|
+
const pretty = input.pretty ?? isDev();
|
|
3491
|
+
const inDev = isDev();
|
|
3492
|
+
let frameworkOverlay;
|
|
3493
|
+
let prettyError = {};
|
|
3494
|
+
if (typeof input.dev === "string" && input.dev in DEV_PRESETS) {
|
|
3495
|
+
const { frameworkOverlay: presetOverlay, detail } = DEV_PRESETS[input.dev];
|
|
3496
|
+
frameworkOverlay = presetOverlay;
|
|
3497
|
+
prettyError = { detail };
|
|
3498
|
+
} else if (input.dev && typeof input.dev === "object") {
|
|
3499
|
+
const { frameworkOverlay: devOverlay, prettyError: devPrettyError } = input.dev;
|
|
3500
|
+
frameworkOverlay = devOverlay;
|
|
3501
|
+
if (devPrettyError)
|
|
3502
|
+
prettyError = devPrettyError;
|
|
3503
|
+
}
|
|
3504
|
+
if (frameworkOverlay === undefined)
|
|
3505
|
+
frameworkOverlay = !(pretty && inDev);
|
|
3506
|
+
return {
|
|
3507
|
+
frameworkOverlay,
|
|
3508
|
+
prettyError: finalizePrettyError(prettyError, frameworkOverlay, pretty, inDev)
|
|
3509
|
+
};
|
|
3510
|
+
}
|
|
3511
|
+
|
|
3512
|
+
// ../../node_modules/.bun/evlog@2.19.2+7724ce3de6b3bca4/node_modules/evlog/dist/error.mjs
|
|
3513
|
+
var evlogErrorInternalKey = Symbol.for("evlog.error.internal");
|
|
3514
|
+
var EvlogError = class EvlogError2 extends Error {
|
|
3515
|
+
code;
|
|
3516
|
+
status;
|
|
3517
|
+
why;
|
|
3518
|
+
fix;
|
|
3519
|
+
link;
|
|
3520
|
+
get internal() {
|
|
3521
|
+
return this[evlogErrorInternalKey];
|
|
3522
|
+
}
|
|
3523
|
+
constructor(options) {
|
|
3524
|
+
const opts = typeof options === "string" ? { message: options } : options;
|
|
3525
|
+
super(opts.message, { cause: opts.cause });
|
|
3526
|
+
this.name = "EvlogError";
|
|
3527
|
+
this.code = opts.code;
|
|
3528
|
+
this.status = opts.status ?? 500;
|
|
3529
|
+
this.why = opts.why;
|
|
3530
|
+
this.fix = opts.fix;
|
|
3531
|
+
this.link = opts.link;
|
|
3532
|
+
if (opts.internal !== undefined)
|
|
3533
|
+
Object.defineProperty(this, evlogErrorInternalKey, {
|
|
3534
|
+
value: opts.internal,
|
|
3535
|
+
enumerable: false,
|
|
3536
|
+
writable: false,
|
|
3537
|
+
configurable: true
|
|
3538
|
+
});
|
|
3539
|
+
if (Error.captureStackTrace)
|
|
3540
|
+
Error.captureStackTrace(this, EvlogError2);
|
|
3541
|
+
}
|
|
3542
|
+
get statusText() {
|
|
3543
|
+
return this.message;
|
|
3544
|
+
}
|
|
3545
|
+
get statusCode() {
|
|
3546
|
+
return this.status;
|
|
3547
|
+
}
|
|
3548
|
+
get statusMessage() {
|
|
3549
|
+
return this.message;
|
|
3550
|
+
}
|
|
3551
|
+
get data() {
|
|
3552
|
+
if (this.code || this.why || this.fix || this.link)
|
|
3553
|
+
return {
|
|
3554
|
+
code: this.code,
|
|
3555
|
+
why: this.why,
|
|
3556
|
+
fix: this.fix,
|
|
3557
|
+
link: this.link
|
|
3558
|
+
};
|
|
3559
|
+
}
|
|
3560
|
+
toString() {
|
|
3561
|
+
const useColors = isServer();
|
|
3562
|
+
const red = useColors ? colors.red : "";
|
|
3563
|
+
const yellow = useColors ? colors.yellow : "";
|
|
3564
|
+
const cyan = useColors ? colors.cyan : "";
|
|
3565
|
+
const dim = useColors ? colors.dim : "";
|
|
3566
|
+
const reset = useColors ? colors.reset : "";
|
|
3567
|
+
const bold = useColors ? colors.bold : "";
|
|
3568
|
+
const lines = [];
|
|
3569
|
+
lines.push(`${red}${bold}Error:${reset} ${this.message}`);
|
|
3570
|
+
if (this.code)
|
|
3571
|
+
lines.push(`${dim}Code:${reset} ${this.code}`);
|
|
3572
|
+
if (this.why)
|
|
3573
|
+
lines.push(`${yellow}Why:${reset} ${this.why}`);
|
|
3574
|
+
if (this.fix)
|
|
3575
|
+
lines.push(`${cyan}Fix:${reset} ${this.fix}`);
|
|
3576
|
+
if (this.link)
|
|
3577
|
+
lines.push(`${dim}More info:${reset} ${this.link}`);
|
|
3578
|
+
if (this.cause)
|
|
3579
|
+
lines.push(`${dim}Caused by:${reset} ${this.cause.message}`);
|
|
3580
|
+
return lines.join(`
|
|
3581
|
+
`);
|
|
3582
|
+
}
|
|
3583
|
+
toJSON() {
|
|
3584
|
+
const { data } = this;
|
|
3585
|
+
return {
|
|
3586
|
+
name: this.name,
|
|
3587
|
+
message: this.message,
|
|
3588
|
+
status: this.status,
|
|
3589
|
+
...data && { data },
|
|
3590
|
+
...this.cause instanceof Error && { cause: {
|
|
3591
|
+
name: this.cause.name,
|
|
3592
|
+
message: this.cause.message
|
|
3593
|
+
} }
|
|
3594
|
+
};
|
|
3595
|
+
}
|
|
3596
|
+
};
|
|
2699
3597
|
|
|
2700
|
-
// ../../node_modules/.bun/evlog@2.
|
|
3598
|
+
// ../../node_modules/.bun/evlog@2.19.2+7724ce3de6b3bca4/node_modules/evlog/dist/headers-VtmnWcfn.mjs
|
|
2701
3599
|
function extractSafeHeaders(headers) {
|
|
2702
3600
|
const raw = {};
|
|
2703
3601
|
headers.forEach((value, key) => {
|
|
@@ -2715,8 +3613,89 @@ function extractSafeNodeHeaders(headers) {
|
|
|
2715
3613
|
return filterSafeHeaders(raw);
|
|
2716
3614
|
}
|
|
2717
3615
|
|
|
2718
|
-
// ../../node_modules/.bun/evlog@2.
|
|
3616
|
+
// ../../node_modules/.bun/evlog@2.19.2+7724ce3de6b3bca4/node_modules/evlog/dist/audit-CL0q7GJU.mjs
|
|
2719
3617
|
var DEFAULT_REPLACEMENT = "[REDACTED]";
|
|
3618
|
+
function normalizeRedactPathPattern(pattern) {
|
|
3619
|
+
if (!pattern.includes("*") && !pattern.includes("."))
|
|
3620
|
+
return `**.${pattern}`;
|
|
3621
|
+
return pattern;
|
|
3622
|
+
}
|
|
3623
|
+
function compileRedactPathMatchers(patterns) {
|
|
3624
|
+
if (!patterns?.length)
|
|
3625
|
+
return;
|
|
3626
|
+
const exactPaths = /* @__PURE__ */ new Set;
|
|
3627
|
+
const pathGlobs = [];
|
|
3628
|
+
const keyGlobs = [];
|
|
3629
|
+
const caseInsensitiveLeaves = /* @__PURE__ */ new Set;
|
|
3630
|
+
for (const raw of patterns) {
|
|
3631
|
+
if (!raw.includes("*")) {
|
|
3632
|
+
if (raw.includes("."))
|
|
3633
|
+
exactPaths.add(raw);
|
|
3634
|
+
else
|
|
3635
|
+
addPathGlobPattern(normalizeRedactPathPattern(raw), exactPaths, pathGlobs, caseInsensitiveLeaves);
|
|
3636
|
+
continue;
|
|
3637
|
+
}
|
|
3638
|
+
if (!raw.includes("."))
|
|
3639
|
+
keyGlobs.push(globToRegExp(raw, "."));
|
|
3640
|
+
else
|
|
3641
|
+
addPathGlobPattern(raw, exactPaths, pathGlobs, caseInsensitiveLeaves);
|
|
3642
|
+
}
|
|
3643
|
+
if (exactPaths.size === 0 && pathGlobs.length === 0 && keyGlobs.length === 0 && caseInsensitiveLeaves.size === 0)
|
|
3644
|
+
return;
|
|
3645
|
+
return {
|
|
3646
|
+
exactPaths,
|
|
3647
|
+
pathGlobs,
|
|
3648
|
+
keyGlobs,
|
|
3649
|
+
caseInsensitiveLeaves
|
|
3650
|
+
};
|
|
3651
|
+
}
|
|
3652
|
+
function addPathGlobPattern(pattern, exactPaths, pathGlobs, caseInsensitiveLeaves) {
|
|
3653
|
+
pathGlobs.push(globToRegExp(pattern, "."));
|
|
3654
|
+
const leaf = pattern.match(/^\*\*\.([^.?*]+)$/);
|
|
3655
|
+
if (leaf) {
|
|
3656
|
+
exactPaths.add(leaf[1]);
|
|
3657
|
+
caseInsensitiveLeaves.add(leaf[1].toLowerCase());
|
|
3658
|
+
}
|
|
3659
|
+
}
|
|
3660
|
+
function matchesRedactPath(fullPath, leafKey, matchers) {
|
|
3661
|
+
if (matchers.exactPaths.has(fullPath))
|
|
3662
|
+
return true;
|
|
3663
|
+
if (matchers.caseInsensitiveLeaves.has(leafKey.toLowerCase()))
|
|
3664
|
+
return true;
|
|
3665
|
+
for (const glob of matchers.pathGlobs) {
|
|
3666
|
+
glob.lastIndex = 0;
|
|
3667
|
+
if (glob.test(fullPath))
|
|
3668
|
+
return true;
|
|
3669
|
+
}
|
|
3670
|
+
for (const glob of matchers.keyGlobs) {
|
|
3671
|
+
glob.lastIndex = 0;
|
|
3672
|
+
if (glob.test(leafKey))
|
|
3673
|
+
return true;
|
|
3674
|
+
}
|
|
3675
|
+
return false;
|
|
3676
|
+
}
|
|
3677
|
+
function redactPathsInTree(obj, matchers, replacement, prefix = "") {
|
|
3678
|
+
if (obj === null || obj === undefined)
|
|
3679
|
+
return;
|
|
3680
|
+
if (Array.isArray(obj)) {
|
|
3681
|
+
for (let i = 0;i < obj.length; i++) {
|
|
3682
|
+
const segment = String(i);
|
|
3683
|
+
const fullPath = prefix ? `${prefix}.${segment}` : segment;
|
|
3684
|
+
redactPathsInTree(obj[i], matchers, replacement, fullPath);
|
|
3685
|
+
}
|
|
3686
|
+
return;
|
|
3687
|
+
}
|
|
3688
|
+
if (typeof obj === "object") {
|
|
3689
|
+
const record = obj;
|
|
3690
|
+
for (const key in record) {
|
|
3691
|
+
const fullPath = prefix ? `${prefix}.${key}` : key;
|
|
3692
|
+
if (matchesRedactPath(fullPath, key, matchers))
|
|
3693
|
+
record[key] = replacement;
|
|
3694
|
+
else
|
|
3695
|
+
redactPathsInTree(record[key], matchers, replacement, fullPath);
|
|
3696
|
+
}
|
|
3697
|
+
}
|
|
3698
|
+
}
|
|
2720
3699
|
var builtinPatterns = {
|
|
2721
3700
|
creditCard: {
|
|
2722
3701
|
pattern: /\b\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}\b/g,
|
|
@@ -2770,11 +3749,15 @@ function resolveRedactConfig(input) {
|
|
|
2770
3749
|
if (input === true)
|
|
2771
3750
|
return { _maskers: allBuiltinMaskers() };
|
|
2772
3751
|
if (input.builtins === false)
|
|
2773
|
-
return
|
|
3752
|
+
return {
|
|
3753
|
+
...input,
|
|
3754
|
+
_pathMatchers: compileRedactPathMatchers(input.paths)
|
|
3755
|
+
};
|
|
2774
3756
|
const maskers = Array.isArray(input.builtins) ? input.builtins.map((name) => builtinPatterns[name]).filter(Boolean).map((b) => [cloneRegex(b.pattern), b.mask]) : allBuiltinMaskers();
|
|
2775
3757
|
return {
|
|
2776
3758
|
...input,
|
|
2777
|
-
_maskers: maskers
|
|
3759
|
+
_maskers: maskers,
|
|
3760
|
+
_pathMatchers: compileRedactPathMatchers(input.paths)
|
|
2778
3761
|
};
|
|
2779
3762
|
}
|
|
2780
3763
|
function allBuiltinMaskers() {
|
|
@@ -2783,28 +3766,40 @@ function allBuiltinMaskers() {
|
|
|
2783
3766
|
function cloneRegex(re) {
|
|
2784
3767
|
return new RegExp(re.source, re.flags);
|
|
2785
3768
|
}
|
|
3769
|
+
var globallyRedacted = Symbol.for("evlog.globallyRedacted");
|
|
3770
|
+
function markGloballyRedacted(event) {
|
|
3771
|
+
Object.defineProperty(event, globallyRedacted, {
|
|
3772
|
+
value: true,
|
|
3773
|
+
enumerable: false,
|
|
3774
|
+
configurable: true
|
|
3775
|
+
});
|
|
3776
|
+
}
|
|
3777
|
+
function isGloballyRedacted(event) {
|
|
3778
|
+
return Reflect.has(event, globallyRedacted);
|
|
3779
|
+
}
|
|
3780
|
+
function cloneForRedaction(event) {
|
|
3781
|
+
try {
|
|
3782
|
+
return structuredClone(event);
|
|
3783
|
+
} catch {
|
|
3784
|
+
try {
|
|
3785
|
+
return JSON.parse(JSON.stringify(event));
|
|
3786
|
+
} catch {
|
|
3787
|
+
console.warn("[cloneForRedaction] Shallow clone used \u2014 nested objects may be mutated by redactPath, redactPatterns, and applyMaskersToTree");
|
|
3788
|
+
return { ...event };
|
|
3789
|
+
}
|
|
3790
|
+
}
|
|
3791
|
+
}
|
|
2786
3792
|
function redactEvent(event, config) {
|
|
3793
|
+
const clone = cloneForRedaction(event);
|
|
2787
3794
|
const replacement = config.replacement ?? DEFAULT_REPLACEMENT;
|
|
2788
|
-
|
|
2789
|
-
|
|
2790
|
-
|
|
3795
|
+
const pathMatchers = config._pathMatchers ?? compileRedactPathMatchers(config.paths);
|
|
3796
|
+
if (pathMatchers)
|
|
3797
|
+
redactPathsInTree(clone, pathMatchers, replacement);
|
|
2791
3798
|
if (config._maskers?.length)
|
|
2792
|
-
applyMaskersToTree(
|
|
3799
|
+
applyMaskersToTree(clone, config._maskers);
|
|
2793
3800
|
if (config.patterns?.length)
|
|
2794
|
-
redactPatterns(
|
|
2795
|
-
|
|
2796
|
-
function redactPath(obj, segments, replacement) {
|
|
2797
|
-
let current = obj;
|
|
2798
|
-
for (let i = 0;i < segments.length - 1; i++) {
|
|
2799
|
-
if (current === null || current === undefined || typeof current !== "object")
|
|
2800
|
-
return;
|
|
2801
|
-
current = current[segments[i]];
|
|
2802
|
-
}
|
|
2803
|
-
if (current === null || current === undefined || typeof current !== "object")
|
|
2804
|
-
return;
|
|
2805
|
-
const leaf = segments[segments.length - 1];
|
|
2806
|
-
if (leaf in current)
|
|
2807
|
-
current[leaf] = replacement;
|
|
3801
|
+
redactPatterns(clone, config.patterns, replacement);
|
|
3802
|
+
return clone;
|
|
2808
3803
|
}
|
|
2809
3804
|
function redactPatterns(obj, patterns, replacement) {
|
|
2810
3805
|
if (obj === null || obj === undefined)
|
|
@@ -2830,10 +3825,8 @@ function redactPatterns(obj, patterns, replacement) {
|
|
|
2830
3825
|
}
|
|
2831
3826
|
function applyPatterns(value, patterns, replacement) {
|
|
2832
3827
|
let result = value;
|
|
2833
|
-
for (const pattern of patterns)
|
|
2834
|
-
pattern.lastIndex = 0;
|
|
3828
|
+
for (const pattern of patterns)
|
|
2835
3829
|
result = result.replace(pattern, replacement);
|
|
2836
|
-
}
|
|
2837
3830
|
return result;
|
|
2838
3831
|
}
|
|
2839
3832
|
function applyMaskersToTree(obj, maskers) {
|
|
@@ -2860,10 +3853,8 @@ function applyMaskersToTree(obj, maskers) {
|
|
|
2860
3853
|
}
|
|
2861
3854
|
function applyMaskers(value, maskers) {
|
|
2862
3855
|
let result = value;
|
|
2863
|
-
for (const [pattern, mask] of maskers)
|
|
2864
|
-
pattern.lastIndex = 0;
|
|
3856
|
+
for (const [pattern, mask] of maskers)
|
|
2865
3857
|
result = result.replace(pattern, mask);
|
|
2866
|
-
}
|
|
2867
3858
|
return result;
|
|
2868
3859
|
}
|
|
2869
3860
|
function logPluginError(name, hook, err) {
|
|
@@ -2977,6 +3968,10 @@ var emptyRunner = createPluginRunner([]);
|
|
|
2977
3968
|
function getEmptyPluginRunner() {
|
|
2978
3969
|
return emptyRunner;
|
|
2979
3970
|
}
|
|
3971
|
+
var nativeStdoutWrite = typeof process !== "undefined" && typeof process.stdout?.write === "function" ? process.stdout.write.bind(process.stdout) : undefined;
|
|
3972
|
+
function writePrettyStdout(text) {
|
|
3973
|
+
(globalThis.__evlogNativeStdoutWrite ?? nativeStdoutWrite)?.(text);
|
|
3974
|
+
}
|
|
2980
3975
|
function isPlainObject$1(val) {
|
|
2981
3976
|
return val !== null && typeof val === "object" && !Array.isArray(val);
|
|
2982
3977
|
}
|
|
@@ -3003,11 +3998,29 @@ function mergeInto(target, source) {
|
|
|
3003
3998
|
target[key] = sourceVal;
|
|
3004
3999
|
}
|
|
3005
4000
|
}
|
|
4001
|
+
var pendingDrainState = /* @__PURE__ */ new WeakMap;
|
|
4002
|
+
function isAiOnlyFieldUpdate(data) {
|
|
4003
|
+
const keys = Object.keys(data);
|
|
4004
|
+
return keys.length === 1 && keys[0] === "ai";
|
|
4005
|
+
}
|
|
4006
|
+
function markWideEventDrainStarted(event) {
|
|
4007
|
+
if (!event)
|
|
4008
|
+
return;
|
|
4009
|
+
const state = pendingDrainState.get(event);
|
|
4010
|
+
if (state)
|
|
4011
|
+
state.drainStarted = true;
|
|
4012
|
+
}
|
|
3006
4013
|
var globalEnv = {
|
|
3007
4014
|
service: "app",
|
|
3008
4015
|
environment: "development"
|
|
3009
4016
|
};
|
|
3010
4017
|
var globalPretty = isDev();
|
|
4018
|
+
var globalPrettyError = {
|
|
4019
|
+
snippet: isDev(),
|
|
4020
|
+
stackDepth: 2,
|
|
4021
|
+
compact: isDev(),
|
|
4022
|
+
detail: "full"
|
|
4023
|
+
};
|
|
3011
4024
|
var globalSampling = {};
|
|
3012
4025
|
var globalStringify = true;
|
|
3013
4026
|
var globalDrain;
|
|
@@ -3027,6 +4040,7 @@ function initLogger(config = {}) {
|
|
|
3027
4040
|
region: config.env?.region ?? detected.region
|
|
3028
4041
|
};
|
|
3029
4042
|
globalPretty = config.pretty ?? isDev();
|
|
4043
|
+
globalPrettyError = resolveDevTerminal(config).prettyError;
|
|
3030
4044
|
globalSampling = config.sampling ?? {};
|
|
3031
4045
|
globalStringify = config.stringify ?? true;
|
|
3032
4046
|
globalDrain = config.drain;
|
|
@@ -3107,8 +4121,10 @@ function emitWideEvent(level, event, options = {}) {
|
|
|
3107
4121
|
...event
|
|
3108
4122
|
};
|
|
3109
4123
|
finalizeAudit(formatted);
|
|
3110
|
-
if (globalRedact)
|
|
3111
|
-
redactEvent(formatted, globalRedact);
|
|
4124
|
+
if (globalRedact) {
|
|
4125
|
+
formatted = redactEvent(formatted, globalRedact);
|
|
4126
|
+
markGloballyRedacted(formatted);
|
|
4127
|
+
}
|
|
3112
4128
|
if (!globalSilent)
|
|
3113
4129
|
if (globalPretty)
|
|
3114
4130
|
prettyPrintWideEvent(formatted);
|
|
@@ -3298,11 +4314,11 @@ function buildAIEntries(ai) {
|
|
|
3298
4314
|
const toolCallEntries = toolCalls ? asToolCallArray(toolCalls) : undefined;
|
|
3299
4315
|
const hasInputs = toolCallEntries !== undefined && toolCallEntries.length > 0;
|
|
3300
4316
|
if (tools?.length) {
|
|
3301
|
-
const children = tools.map((
|
|
3302
|
-
const mark =
|
|
3303
|
-
let line = `${
|
|
3304
|
-
if (
|
|
3305
|
-
line += ` ${
|
|
4317
|
+
const children = tools.map((t2, idx) => {
|
|
4318
|
+
const mark = t2.success ? "\u2713" : "\u2717";
|
|
4319
|
+
let line = `${t2.name} ${formatDuration(t2.durationMs)} ${mark}`;
|
|
4320
|
+
if (t2.error)
|
|
4321
|
+
line += ` ${t2.error}`;
|
|
3306
4322
|
if (hasInputs && toolCallEntries && idx < toolCallEntries.length) {
|
|
3307
4323
|
const tc = toolCallEntries[idx];
|
|
3308
4324
|
const inputStr = serializeToolInput(tc.input);
|
|
@@ -3389,11 +4405,34 @@ function buildAIEntries(ai) {
|
|
|
3389
4405
|
});
|
|
3390
4406
|
return entries;
|
|
3391
4407
|
}
|
|
4408
|
+
function flushPrettyLines(lines) {
|
|
4409
|
+
if (lines.length === 0)
|
|
4410
|
+
return;
|
|
4411
|
+
const text = `${lines.join(`
|
|
4412
|
+
`)}
|
|
4413
|
+
`;
|
|
4414
|
+
if (nativeStdoutWrite && !isBrowser() && process.env.VITEST !== "true") {
|
|
4415
|
+
writePrettyStdout(text);
|
|
4416
|
+
return;
|
|
4417
|
+
}
|
|
4418
|
+
console.log(lines.join(`
|
|
4419
|
+
`));
|
|
4420
|
+
}
|
|
3392
4421
|
function prettyPrintWideEvent(event) {
|
|
3393
4422
|
const { timestamp, level, service, environment, version, ...rest } = event;
|
|
3394
4423
|
const ts = typeof timestamp === "string" ? timestamp.slice(11, 23) : "";
|
|
3395
4424
|
const levelLabel = typeof level === "string" ? level : "info";
|
|
3396
4425
|
const browser = isBrowser();
|
|
4426
|
+
const lines = [];
|
|
4427
|
+
const writeLine = (...args) => {
|
|
4428
|
+
if (browser) {
|
|
4429
|
+
console.log(...args);
|
|
4430
|
+
return;
|
|
4431
|
+
}
|
|
4432
|
+
const [line] = args;
|
|
4433
|
+
if (typeof line === "string")
|
|
4434
|
+
lines.push(line);
|
|
4435
|
+
};
|
|
3397
4436
|
const parts = [];
|
|
3398
4437
|
const styles = [];
|
|
3399
4438
|
if (browser) {
|
|
@@ -3402,7 +4441,10 @@ function prettyPrintWideEvent(event) {
|
|
|
3402
4441
|
styles.push(cssColors.dim, cssColors.reset, lc, cssColors.reset, cssColors.cyan, cssColors.reset);
|
|
3403
4442
|
} else {
|
|
3404
4443
|
const lc = getLevelColor(levelLabel);
|
|
3405
|
-
|
|
4444
|
+
if (isDev())
|
|
4445
|
+
parts.push(`${lc}${levelLabel.toUpperCase()}${colors.reset} ${colors.cyan}[${service}]${colors.reset}`);
|
|
4446
|
+
else
|
|
4447
|
+
parts.push(`${colors.dim}${ts}${colors.reset} ${lc}${levelLabel.toUpperCase()}${colors.reset} ${colors.cyan}[${service}]${colors.reset}`);
|
|
3406
4448
|
}
|
|
3407
4449
|
if (rest.method && rest.path) {
|
|
3408
4450
|
parts.push(browser ? ` ${escapeFormatString(String(rest.method))} ${escapeFormatString(String(rest.path))}` : ` ${rest.method} ${rest.path}`);
|
|
@@ -3427,16 +4469,21 @@ function prettyPrintWideEvent(event) {
|
|
|
3427
4469
|
parts.push(` ${colors.dim}in ${rest.duration}${colors.reset}`);
|
|
3428
4470
|
delete rest.duration;
|
|
3429
4471
|
}
|
|
3430
|
-
|
|
4472
|
+
writeLine(parts.join(""), ...styles);
|
|
3431
4473
|
const aiData = isPlainObject$1(rest.ai) ? rest.ai : undefined;
|
|
3432
4474
|
if (aiData)
|
|
3433
4475
|
delete rest.ai;
|
|
4476
|
+
const errorData = rest.error;
|
|
4477
|
+
if (errorData !== undefined)
|
|
4478
|
+
delete rest.error;
|
|
3434
4479
|
const restEntries = Object.entries(rest).filter(([_, v]) => v !== undefined);
|
|
3435
4480
|
const aiEntries = aiData ? buildAIEntries(aiData) : [];
|
|
3436
|
-
const
|
|
4481
|
+
const errorEntries = errorData !== undefined ? buildErrorEntries(errorData, globalPrettyError) : [];
|
|
4482
|
+
const contextEntries = [...restEntries.map(([key, value]) => ({
|
|
3437
4483
|
key,
|
|
3438
4484
|
value: formatValue(value)
|
|
3439
4485
|
})), ...aiEntries];
|
|
4486
|
+
const allEntries = errorEntries.length > 0 ? [...errorEntries, ...contextEntries] : contextEntries;
|
|
3440
4487
|
for (let i = 0;i < allEntries.length; i++) {
|
|
3441
4488
|
const entry = allEntries[i];
|
|
3442
4489
|
if (!entry)
|
|
@@ -3446,10 +4493,10 @@ function prettyPrintWideEvent(event) {
|
|
|
3446
4493
|
const prefix = i === allEntries.length - 1 && !hasChildren ? "\u2514\u2500" : "\u251C\u2500";
|
|
3447
4494
|
if (browser) {
|
|
3448
4495
|
const val = entry.value ? ` ${escapeFormatString(entry.value)}` : "";
|
|
3449
|
-
|
|
4496
|
+
writeLine(` %c${prefix}%c %c${escapeFormatString(entry.key)}:%c${val}`, cssColors.dim, cssColors.reset, cssColors.cyan, cssColors.reset);
|
|
3450
4497
|
} else {
|
|
3451
4498
|
const val = entry.value ? ` ${entry.value}` : "";
|
|
3452
|
-
|
|
4499
|
+
writeLine(` ${colors.dim}${prefix}${colors.reset} ${colors.cyan}${entry.key}:${colors.reset}${val}`);
|
|
3453
4500
|
}
|
|
3454
4501
|
if (hasChildren && children) {
|
|
3455
4502
|
const connector = i === allEntries.length - 1 ? " " : "\u2502";
|
|
@@ -3457,14 +4504,26 @@ function prettyPrintWideEvent(event) {
|
|
|
3457
4504
|
const child = children[j];
|
|
3458
4505
|
if (child === undefined)
|
|
3459
4506
|
continue;
|
|
4507
|
+
if (child === "__EVLOG_TREE_SPACER__") {
|
|
4508
|
+
writeLine(` ${colors.dim}${connector}${colors.reset}`);
|
|
4509
|
+
continue;
|
|
4510
|
+
}
|
|
3460
4511
|
const childPrefix = j === children.length - 1 ? "\u2514\u2500" : "\u251C\u2500";
|
|
4512
|
+
if (child === "") {
|
|
4513
|
+
writeLine("");
|
|
4514
|
+
continue;
|
|
4515
|
+
}
|
|
3461
4516
|
if (browser)
|
|
3462
|
-
|
|
4517
|
+
writeLine(` %c${connector} ${childPrefix}%c ${escapeFormatString(child)}`, cssColors.dim, cssColors.reset);
|
|
4518
|
+
else if (child.startsWith(" ") || child.startsWith("\x1B"))
|
|
4519
|
+
writeLine(` ${colors.dim}${connector}${colors.reset}${child}`);
|
|
3463
4520
|
else
|
|
3464
|
-
|
|
4521
|
+
writeLine(` ${colors.dim}${connector} ${childPrefix}${colors.reset} ${child}`);
|
|
3465
4522
|
}
|
|
3466
4523
|
}
|
|
3467
4524
|
}
|
|
4525
|
+
if (!browser && lines.length > 0)
|
|
4526
|
+
flushPrettyLines(lines);
|
|
3468
4527
|
}
|
|
3469
4528
|
function createLogMethod(level) {
|
|
3470
4529
|
return function logMethod(tagOrEvent, message) {
|
|
@@ -3507,6 +4566,7 @@ function createLogger(initialContext = {}, internalOptions) {
|
|
|
3507
4566
|
let hasWarn = false;
|
|
3508
4567
|
let manualLevel;
|
|
3509
4568
|
let emitted = false;
|
|
4569
|
+
let pendingWideEvent = null;
|
|
3510
4570
|
function addLog(level, message) {
|
|
3511
4571
|
if (!Array.isArray(context.requestLogs))
|
|
3512
4572
|
context.requestLogs = [];
|
|
@@ -3539,7 +4599,13 @@ function createLogger(initialContext = {}, internalOptions) {
|
|
|
3539
4599
|
audit: auditMethod,
|
|
3540
4600
|
set(data) {
|
|
3541
4601
|
if (emitted) {
|
|
3542
|
-
const
|
|
4602
|
+
const record = data;
|
|
4603
|
+
const pendingState = pendingWideEvent ? pendingDrainState.get(pendingWideEvent) : undefined;
|
|
4604
|
+
if (pendingWideEvent && pendingState && !pendingState.drainStarted && isAiOnlyFieldUpdate(record)) {
|
|
4605
|
+
mergeInto(pendingWideEvent, record);
|
|
4606
|
+
return;
|
|
4607
|
+
}
|
|
4608
|
+
const keys = Object.keys(record);
|
|
3543
4609
|
warnPostEmit("log.set()", `Keys dropped: ${keys.length ? keys.join(", ") : "(empty)"}.`);
|
|
3544
4610
|
return;
|
|
3545
4611
|
}
|
|
@@ -3564,7 +4630,7 @@ function createLogger(initialContext = {}, internalOptions) {
|
|
|
3564
4630
|
const errorObj = {
|
|
3565
4631
|
name: err.name,
|
|
3566
4632
|
message: err.message,
|
|
3567
|
-
stack: err.stack
|
|
4633
|
+
stack: isDev() ? compactStackForStorage(err.stack) : err.stack
|
|
3568
4634
|
};
|
|
3569
4635
|
const errRecord = err;
|
|
3570
4636
|
for (const k of [
|
|
@@ -3579,6 +4645,18 @@ function createLogger(initialContext = {}, internalOptions) {
|
|
|
3579
4645
|
])
|
|
3580
4646
|
if (k in err)
|
|
3581
4647
|
errorObj[k] = errRecord[k];
|
|
4648
|
+
if (err instanceof EvlogError) {
|
|
4649
|
+
if (err.code)
|
|
4650
|
+
errorObj.code = err.code;
|
|
4651
|
+
if (err.why)
|
|
4652
|
+
errorObj.why = err.why;
|
|
4653
|
+
if (err.fix)
|
|
4654
|
+
errorObj.fix = err.fix;
|
|
4655
|
+
if (err.link)
|
|
4656
|
+
errorObj.link = err.link;
|
|
4657
|
+
if (err.status)
|
|
4658
|
+
errorObj.status = err.status;
|
|
4659
|
+
}
|
|
3582
4660
|
if (isPlainObject$1(context.error))
|
|
3583
4661
|
mergeInto(context.error, errorObj);
|
|
3584
4662
|
else
|
|
@@ -3629,6 +4707,7 @@ function createLogger(initialContext = {}, internalOptions) {
|
|
|
3629
4707
|
});
|
|
3630
4708
|
if (!forceKeep && !shouldSample(level)) {
|
|
3631
4709
|
emitted = true;
|
|
4710
|
+
pendingWideEvent = null;
|
|
3632
4711
|
return null;
|
|
3633
4712
|
}
|
|
3634
4713
|
if (overrides) {
|
|
@@ -3644,6 +4723,9 @@ function createLogger(initialContext = {}, internalOptions) {
|
|
|
3644
4723
|
waitUntil
|
|
3645
4724
|
});
|
|
3646
4725
|
emitted = true;
|
|
4726
|
+
pendingWideEvent = wide;
|
|
4727
|
+
if (wide)
|
|
4728
|
+
pendingDrainState.set(wide, { drainStarted: !deferDrain });
|
|
3647
4729
|
return wide;
|
|
3648
4730
|
},
|
|
3649
4731
|
getContext() {
|
|
@@ -3667,21 +4749,24 @@ function createRequestLogger(options = {}, internalOptions) {
|
|
|
3667
4749
|
}
|
|
3668
4750
|
if (typeof __EVLOG_CONFIG__ !== "undefined")
|
|
3669
4751
|
initLogger(__EVLOG_CONFIG__);
|
|
3670
|
-
function
|
|
4752
|
+
function isPlainObject2(value) {
|
|
3671
4753
|
if (typeof value !== "object" || value === null || Array.isArray(value))
|
|
3672
4754
|
return false;
|
|
3673
4755
|
if (Object.prototype.toString.call(value) !== "[object Object]")
|
|
3674
4756
|
return false;
|
|
3675
4757
|
return Object.getPrototypeOf(value) === Object.prototype || value.constructor === Object;
|
|
3676
4758
|
}
|
|
3677
|
-
function stableStringify(value) {
|
|
4759
|
+
function stableStringify(value, ancestors = /* @__PURE__ */ new WeakSet) {
|
|
3678
4760
|
if (value === null || typeof value !== "object")
|
|
3679
4761
|
return JSON.stringify(value);
|
|
3680
|
-
if (
|
|
3681
|
-
return
|
|
3682
|
-
if (!
|
|
4762
|
+
if (ancestors.has(value))
|
|
4763
|
+
return '"[Circular]"';
|
|
4764
|
+
if (!Array.isArray(value) && !isPlainObject2(value))
|
|
3683
4765
|
return JSON.stringify(value);
|
|
3684
|
-
|
|
4766
|
+
ancestors.add(value);
|
|
4767
|
+
const out = Array.isArray(value) ? `[${value.map((v) => stableStringify(v, ancestors)).join(",")}]` : `{${Object.keys(value).sort().map((k) => `${JSON.stringify(k)}:${stableStringify(value[k], ancestors)}`).join(",")}}`;
|
|
4768
|
+
ancestors.delete(value);
|
|
4769
|
+
return out;
|
|
3685
4770
|
}
|
|
3686
4771
|
function fnv1a32(input, seed) {
|
|
3687
4772
|
let h = seed >>> 0;
|
|
@@ -3725,6 +4810,7 @@ function buildAuditFields(input) {
|
|
|
3725
4810
|
version: input.version ?? 1
|
|
3726
4811
|
};
|
|
3727
4812
|
}
|
|
4813
|
+
var _testCollector = null;
|
|
3728
4814
|
function decorateAudit(audit, timestamp) {
|
|
3729
4815
|
if (audit.idempotencyKey)
|
|
3730
4816
|
return audit;
|
|
@@ -3746,10 +4832,11 @@ function finalizeAudit(event) {
|
|
|
3746
4832
|
const a = event.audit;
|
|
3747
4833
|
if (!a)
|
|
3748
4834
|
return;
|
|
3749
|
-
|
|
4835
|
+
const decorated = decorateAudit(a, String(event.timestamp));
|
|
4836
|
+
event.audit = decorated;
|
|
4837
|
+
_testCollector?.(decorated, event);
|
|
3750
4838
|
}
|
|
3751
|
-
|
|
3752
|
-
// ../../node_modules/.bun/evlog@2.18.1+21e9b0bb4450b609/node_modules/evlog/dist/errors-BQgyQ9xe.mjs
|
|
4839
|
+
// ../../node_modules/.bun/evlog@2.19.2+7724ce3de6b3bca4/node_modules/evlog/dist/errors-DA0cyr8q.mjs
|
|
3753
4840
|
function extractErrorStatus(error) {
|
|
3754
4841
|
if (error === null || typeof error !== "object")
|
|
3755
4842
|
return 500;
|
|
@@ -3758,7 +4845,7 @@ function extractErrorStatus(error) {
|
|
|
3758
4845
|
return Number.isFinite(status) ? status : 500;
|
|
3759
4846
|
}
|
|
3760
4847
|
|
|
3761
|
-
// ../../node_modules/.bun/evlog@2.
|
|
4848
|
+
// ../../node_modules/.bun/evlog@2.19.2+7724ce3de6b3bca4/node_modules/evlog/dist/routes-4rMzRyTk.mjs
|
|
3762
4849
|
function shouldLog(path, include, exclude) {
|
|
3763
4850
|
if (exclude && exclude.length > 0) {
|
|
3764
4851
|
if (exclude.some((pattern) => matchesPattern(path, pattern)))
|
|
@@ -3776,7 +4863,86 @@ function getServiceForPath(path, routes) {
|
|
|
3776
4863
|
return config.service;
|
|
3777
4864
|
}
|
|
3778
4865
|
|
|
3779
|
-
// ../../node_modules/.bun/evlog@2.
|
|
4866
|
+
// ../../node_modules/.bun/evlog@2.19.2+7724ce3de6b3bca4/node_modules/evlog/dist/streamResponse-CmQ3qUbF.mjs
|
|
4867
|
+
function shouldDeferEmitForResponse(response) {
|
|
4868
|
+
if (!response.body)
|
|
4869
|
+
return false;
|
|
4870
|
+
const contentType = (response.headers.get("content-type") ?? "").toLowerCase();
|
|
4871
|
+
if (contentType.includes("text/event-stream"))
|
|
4872
|
+
return true;
|
|
4873
|
+
if (contentType.includes("application/x-ndjson"))
|
|
4874
|
+
return true;
|
|
4875
|
+
if (response.headers.has("x-vercel-ai-ui-message-stream"))
|
|
4876
|
+
return true;
|
|
4877
|
+
if (response.headers.get("transfer-encoding")?.toLowerCase().includes("chunked"))
|
|
4878
|
+
return true;
|
|
4879
|
+
return false;
|
|
4880
|
+
}
|
|
4881
|
+
function toError(value) {
|
|
4882
|
+
return value instanceof Error ? value : new Error(String(value));
|
|
4883
|
+
}
|
|
4884
|
+
function createObservedBody(body, onDone, onError) {
|
|
4885
|
+
if (body.locked) {
|
|
4886
|
+
Promise.resolve(onError(/* @__PURE__ */ new TypeError("stream is already locked"))).catch((err) => {
|
|
4887
|
+
console.error("[evlog] stream error handling failed:", err);
|
|
4888
|
+
});
|
|
4889
|
+
return null;
|
|
4890
|
+
}
|
|
4891
|
+
const reader = body.getReader();
|
|
4892
|
+
let settled = false;
|
|
4893
|
+
const settle = (fn) => {
|
|
4894
|
+
if (settled)
|
|
4895
|
+
return;
|
|
4896
|
+
settled = true;
|
|
4897
|
+
Promise.resolve(fn()).catch((err) => {
|
|
4898
|
+
console.error("[evlog] stream completion handling failed:", err);
|
|
4899
|
+
});
|
|
4900
|
+
};
|
|
4901
|
+
return new ReadableStream({
|
|
4902
|
+
async pull(controller) {
|
|
4903
|
+
try {
|
|
4904
|
+
const { done, value } = await reader.read();
|
|
4905
|
+
if (done) {
|
|
4906
|
+
settle(onDone);
|
|
4907
|
+
controller.close();
|
|
4908
|
+
return;
|
|
4909
|
+
}
|
|
4910
|
+
controller.enqueue(value);
|
|
4911
|
+
} catch (err) {
|
|
4912
|
+
settle(() => onError(err));
|
|
4913
|
+
controller.error(err);
|
|
4914
|
+
}
|
|
4915
|
+
},
|
|
4916
|
+
async cancel(reason) {
|
|
4917
|
+
try {
|
|
4918
|
+
await reader.cancel(reason);
|
|
4919
|
+
} finally {
|
|
4920
|
+
settle(onDone);
|
|
4921
|
+
}
|
|
4922
|
+
}
|
|
4923
|
+
});
|
|
4924
|
+
}
|
|
4925
|
+
function bindStreamingResponseLifecycle(response, onComplete) {
|
|
4926
|
+
if (!response.body) {
|
|
4927
|
+
Promise.resolve(onComplete({ status: response.status })).catch((err) => {
|
|
4928
|
+
console.error("[evlog] stream completion handling failed:", err);
|
|
4929
|
+
});
|
|
4930
|
+
return response;
|
|
4931
|
+
}
|
|
4932
|
+
const body = createObservedBody(response.body, () => onComplete({ status: response.status }), (err) => onComplete({
|
|
4933
|
+
status: response.status,
|
|
4934
|
+
error: toError(err)
|
|
4935
|
+
}));
|
|
4936
|
+
if (!body)
|
|
4937
|
+
return response;
|
|
4938
|
+
return new Response(body, {
|
|
4939
|
+
status: response.status,
|
|
4940
|
+
statusText: response.statusText,
|
|
4941
|
+
headers: response.headers
|
|
4942
|
+
});
|
|
4943
|
+
}
|
|
4944
|
+
|
|
4945
|
+
// ../../node_modules/.bun/evlog@2.19.2+7724ce3de6b3bca4/node_modules/evlog/dist/fork-Di44utlp.mjs
|
|
3780
4946
|
var noopResult = {
|
|
3781
4947
|
logger: {
|
|
3782
4948
|
set() {},
|
|
@@ -3792,6 +4958,7 @@ var noopResult = {
|
|
|
3792
4958
|
}
|
|
3793
4959
|
},
|
|
3794
4960
|
finish: () => Promise.resolve(null),
|
|
4961
|
+
finishResponse: (response) => Promise.resolve(response),
|
|
3795
4962
|
skipped: true
|
|
3796
4963
|
};
|
|
3797
4964
|
var runnerCache = /* @__PURE__ */ new WeakMap;
|
|
@@ -3817,11 +4984,17 @@ function resolveMiddlewarePluginRunner(options) {
|
|
|
3817
4984
|
});
|
|
3818
4985
|
return runner;
|
|
3819
4986
|
}
|
|
4987
|
+
function assignRedactedEvent(target, redacted) {
|
|
4988
|
+
for (const key of Object.keys(target))
|
|
4989
|
+
if (!(key in redacted))
|
|
4990
|
+
delete target[key];
|
|
4991
|
+
Object.assign(target, redacted);
|
|
4992
|
+
}
|
|
3820
4993
|
async function runEnrichAndDrain(emittedEvent, options, requestInfo, responseStatus, plugins) {
|
|
3821
4994
|
const runner = plugins ?? resolveMiddlewarePluginRunner(options);
|
|
3822
4995
|
const resolvedRedact = resolveRedactConfig(options.redact);
|
|
3823
|
-
if (resolvedRedact)
|
|
3824
|
-
redactEvent(emittedEvent, resolvedRedact);
|
|
4996
|
+
if (resolvedRedact && !isGloballyRedacted(emittedEvent))
|
|
4997
|
+
assignRedactedEvent(emittedEvent, redactEvent(emittedEvent, resolvedRedact));
|
|
3825
4998
|
if (options.enrich || runner.hasEnrich) {
|
|
3826
4999
|
const enrichCtx = {
|
|
3827
5000
|
event: emittedEvent,
|
|
@@ -3838,6 +5011,7 @@ async function runEnrichAndDrain(emittedEvent, options, requestInfo, responseSta
|
|
|
3838
5011
|
if (runner.hasEnrich)
|
|
3839
5012
|
await runner.runEnrich(enrichCtx);
|
|
3840
5013
|
}
|
|
5014
|
+
markWideEventDrainStarted(emittedEvent);
|
|
3841
5015
|
const drain = options.drain ?? getGlobalDrain();
|
|
3842
5016
|
const hasUserDrain = !!drain;
|
|
3843
5017
|
const hasPluginDrain = runner.hasDrain;
|
|
@@ -3891,22 +5065,38 @@ function createMiddlewareLogger(options) {
|
|
|
3891
5065
|
request: requestInfo,
|
|
3892
5066
|
headers: options.headers
|
|
3893
5067
|
});
|
|
3894
|
-
const finish =
|
|
5068
|
+
const finish = (opts) => {
|
|
5069
|
+
return performFinish(logger, opts);
|
|
5070
|
+
};
|
|
5071
|
+
const finishResponse = async (response, opts) => {
|
|
5072
|
+
const status = opts?.status ?? response.status;
|
|
5073
|
+
if (!shouldDeferEmitForResponse(response)) {
|
|
5074
|
+
await performFinish(logger, { status });
|
|
5075
|
+
return response;
|
|
5076
|
+
}
|
|
5077
|
+
return bindStreamingResponseLifecycle(response, async (meta) => {
|
|
5078
|
+
await performFinish(logger, {
|
|
5079
|
+
status: meta.status ?? status,
|
|
5080
|
+
error: meta.error
|
|
5081
|
+
});
|
|
5082
|
+
});
|
|
5083
|
+
};
|
|
5084
|
+
async function performFinish(requestLogger, opts) {
|
|
3895
5085
|
const { status, error } = opts ?? {};
|
|
3896
5086
|
if (error) {
|
|
3897
|
-
|
|
5087
|
+
requestLogger.error(error);
|
|
3898
5088
|
const errorStatus = extractErrorStatus(error);
|
|
3899
|
-
|
|
5089
|
+
requestLogger.set({ status: errorStatus });
|
|
3900
5090
|
} else if (status !== undefined)
|
|
3901
|
-
|
|
5091
|
+
requestLogger.set({ status });
|
|
3902
5092
|
const durationMs = Date.now() - startTime;
|
|
3903
|
-
const resolvedStatus = error ? extractErrorStatus(error) : status ??
|
|
5093
|
+
const resolvedStatus = error ? extractErrorStatus(error) : status ?? requestLogger.getContext().status;
|
|
3904
5094
|
const tailCtx = {
|
|
3905
5095
|
status: resolvedStatus,
|
|
3906
5096
|
duration: durationMs,
|
|
3907
5097
|
path,
|
|
3908
5098
|
method,
|
|
3909
|
-
context:
|
|
5099
|
+
context: requestLogger.getContext(),
|
|
3910
5100
|
shouldKeep: false
|
|
3911
5101
|
};
|
|
3912
5102
|
if (keep)
|
|
@@ -3914,12 +5104,12 @@ function createMiddlewareLogger(options) {
|
|
|
3914
5104
|
if (pluginRunner.hasKeep)
|
|
3915
5105
|
await pluginRunner.runKeep(tailCtx);
|
|
3916
5106
|
const forceKeep = tailCtx.shouldKeep || shouldKeep(tailCtx);
|
|
3917
|
-
const emittedEvent =
|
|
5107
|
+
const emittedEvent = requestLogger.emit({ _forceKeep: forceKeep });
|
|
3918
5108
|
if (emittedEvent && (options.enrich || options.drain || pluginRunner.hasEnrich || pluginRunner.hasDrain || getGlobalDrain()))
|
|
3919
5109
|
await runEnrichAndDrain(emittedEvent, options, requestInfo, resolvedStatus, pluginRunner);
|
|
3920
5110
|
if (pluginRunner.hasRequestLifecycle)
|
|
3921
5111
|
pluginRunner.runOnRequestFinish({
|
|
3922
|
-
logger,
|
|
5112
|
+
logger: requestLogger,
|
|
3923
5113
|
request: requestInfo,
|
|
3924
5114
|
headers: options.headers,
|
|
3925
5115
|
event: emittedEvent,
|
|
@@ -3928,10 +5118,11 @@ function createMiddlewareLogger(options) {
|
|
|
3928
5118
|
error
|
|
3929
5119
|
});
|
|
3930
5120
|
return emittedEvent;
|
|
3931
|
-
}
|
|
5121
|
+
}
|
|
3932
5122
|
return {
|
|
3933
5123
|
logger,
|
|
3934
5124
|
finish,
|
|
5125
|
+
finishResponse,
|
|
3935
5126
|
skipped: false
|
|
3936
5127
|
};
|
|
3937
5128
|
}
|
|
@@ -3992,7 +5183,7 @@ function forkBackgroundLogger(options) {
|
|
|
3992
5183
|
});
|
|
3993
5184
|
}
|
|
3994
5185
|
|
|
3995
|
-
// ../../node_modules/.bun/evlog@2.
|
|
5186
|
+
// ../../node_modules/.bun/evlog@2.19.2+7724ce3de6b3bca4/node_modules/evlog/dist/integration-2PpI-bCm.mjs
|
|
3996
5187
|
function normalizeHeaders(headers) {
|
|
3997
5188
|
if (!headers)
|
|
3998
5189
|
return;
|
|
@@ -4031,12 +5222,12 @@ function defineFrameworkIntegration(spec) {
|
|
|
4031
5222
|
} };
|
|
4032
5223
|
}
|
|
4033
5224
|
|
|
4034
|
-
// ../../node_modules/.bun/evlog@2.
|
|
5225
|
+
// ../../node_modules/.bun/evlog@2.19.2+7724ce3de6b3bca4/node_modules/evlog/dist/elysia/index.mjs
|
|
4035
5226
|
import { AsyncLocalStorage } from "async_hooks";
|
|
4036
5227
|
import { Elysia } from "elysia";
|
|
4037
5228
|
var storage = new AsyncLocalStorage;
|
|
4038
5229
|
var activeLoggers = /* @__PURE__ */ new WeakSet;
|
|
4039
|
-
function
|
|
5230
|
+
function useLogger2() {
|
|
4040
5231
|
const logger = storage.getStore();
|
|
4041
5232
|
if (!logger || !activeLoggers.has(logger))
|
|
4042
5233
|
throw new Error("[evlog] useLogger() was called outside of an evlog plugin context. Make sure app.use(evlog()) is registered before your routes.");
|
|
@@ -4079,9 +5270,9 @@ var noopLogger2 = {
|
|
|
4079
5270
|
fork: (_label, fn) => fn()
|
|
4080
5271
|
};
|
|
4081
5272
|
var syntheticRenderStorage = new AsyncLocalStorage2;
|
|
4082
|
-
function
|
|
5273
|
+
function useLogger3() {
|
|
4083
5274
|
try {
|
|
4084
|
-
return
|
|
5275
|
+
return useLogger2();
|
|
4085
5276
|
} catch {
|
|
4086
5277
|
return syntheticRenderStorage.getStore() ?? noopLogger2;
|
|
4087
5278
|
}
|
|
@@ -4099,6 +5290,13 @@ async function runInSyntheticRenderScope(fn, initialContext) {
|
|
|
4099
5290
|
}
|
|
4100
5291
|
}
|
|
4101
5292
|
|
|
5293
|
+
// src/server/sync/config.ts
|
|
5294
|
+
import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
|
|
5295
|
+
var requestSyncStreamPath = new AsyncLocalStorage3;
|
|
5296
|
+
function getSyncStreamPath() {
|
|
5297
|
+
return requestSyncStreamPath.getStore();
|
|
5298
|
+
}
|
|
5299
|
+
|
|
4102
5300
|
// src/server/render/assemble.ts
|
|
4103
5301
|
function resolvePath(pattern, params) {
|
|
4104
5302
|
let path = pattern;
|
|
@@ -4129,11 +5327,20 @@ function splitTemplate(template) {
|
|
|
4129
5327
|
function assembleHTML(template, headData, reactHtml, data) {
|
|
4130
5328
|
const { headPre, bodyPre, bodyPost } = splitTemplate(template);
|
|
4131
5329
|
const dataScript = data ? `<script id="__FURIN_DATA__" type="application/json">${safeJson(data)}</script>` : "";
|
|
5330
|
+
const syncScript = buildSyncRuntimeScript();
|
|
5331
|
+
const runtimeScripts = `${syncScript}${dataScript}`;
|
|
4132
5332
|
let injectedBodyPost = bodyPost;
|
|
4133
|
-
if (
|
|
4134
|
-
injectedBodyPost = bodyPost.includes("</body>") ? bodyPost.replace("</body>", `${
|
|
5333
|
+
if (runtimeScripts) {
|
|
5334
|
+
injectedBodyPost = bodyPost.includes("</body>") ? bodyPost.replace("</body>", `${runtimeScripts}</body>`) : bodyPost + runtimeScripts;
|
|
5335
|
+
}
|
|
5336
|
+
return headPre + headData + bodyPre + reactHtml + injectedBodyPost;
|
|
5337
|
+
}
|
|
5338
|
+
function buildSyncRuntimeScript() {
|
|
5339
|
+
const syncStreamPath = getSyncStreamPath();
|
|
5340
|
+
if (!syncStreamPath) {
|
|
5341
|
+
return "";
|
|
4135
5342
|
}
|
|
4136
|
-
return
|
|
5343
|
+
return `<script id="__FURIN_SYNC__" type="application/json">${safeJson({ stream: syncStreamPath })}</script>`;
|
|
4137
5344
|
}
|
|
4138
5345
|
|
|
4139
5346
|
// src/server/render/ssr.ts
|
|
@@ -4190,9 +5397,9 @@ var ERROR_CONSTRUCTOR_STRING = {
|
|
|
4190
5397
|
[5]: "TypeError",
|
|
4191
5398
|
[6]: "URIError"
|
|
4192
5399
|
};
|
|
4193
|
-
function createSerovalNode(
|
|
5400
|
+
function createSerovalNode(t2, i, s, c, m, p, e, a, f, b, o, l) {
|
|
4194
5401
|
return {
|
|
4195
|
-
t,
|
|
5402
|
+
t: t2,
|
|
4196
5403
|
i,
|
|
4197
5404
|
s,
|
|
4198
5405
|
c,
|
|
@@ -4927,7 +6134,7 @@ async function parseBigIntTypedArray(ctx, depth, id, current) {
|
|
|
4927
6134
|
async function parseDataView(ctx, depth, id, current) {
|
|
4928
6135
|
return createDataViewNode(id, current, await parseAsync(ctx, depth, current.buffer));
|
|
4929
6136
|
}
|
|
4930
|
-
async function
|
|
6137
|
+
async function parseError2(ctx, depth, id, current) {
|
|
4931
6138
|
const options = getErrorOptions(current, ctx.base.features);
|
|
4932
6139
|
return createErrorNode(id, current, options ? await parseProperties(ctx, depth, options) : NIL);
|
|
4933
6140
|
}
|
|
@@ -5047,7 +6254,7 @@ async function parseObjectAsync(ctx, depth, id, current) {
|
|
|
5047
6254
|
case SyntaxError:
|
|
5048
6255
|
case TypeError:
|
|
5049
6256
|
case URIError:
|
|
5050
|
-
return
|
|
6257
|
+
return parseError2(ctx, depth, id, current);
|
|
5051
6258
|
case Number:
|
|
5052
6259
|
case Boolean:
|
|
5053
6260
|
case String:
|
|
@@ -5094,7 +6301,7 @@ async function parseObjectAsync(ctx, depth, id, current) {
|
|
|
5094
6301
|
return parseAggregateError(ctx, depth, id, current);
|
|
5095
6302
|
}
|
|
5096
6303
|
if (current instanceof Error) {
|
|
5097
|
-
return
|
|
6304
|
+
return parseError2(ctx, depth, id, current);
|
|
5098
6305
|
}
|
|
5099
6306
|
if (SYM_ITERATOR in current || SYM_ASYNC_ITERATOR in current) {
|
|
5100
6307
|
return parsePlainObject(ctx, depth, id, current, !!currentClass);
|
|
@@ -5184,6 +6391,8 @@ var RouterContext = createContext(null);
|
|
|
5184
6391
|
var CLIENT_FALLBACK_ROUTER = {
|
|
5185
6392
|
basePath: "",
|
|
5186
6393
|
currentHref: "/",
|
|
6394
|
+
search: {},
|
|
6395
|
+
searchRoutes: [],
|
|
5187
6396
|
navigate: (href, _opts) => {
|
|
5188
6397
|
window.location.href = href;
|
|
5189
6398
|
return Promise.resolve();
|
|
@@ -5204,15 +6413,10 @@ function useRouter() {
|
|
|
5204
6413
|
return ctx ?? CLIENT_FALLBACK_ROUTER;
|
|
5205
6414
|
}
|
|
5206
6415
|
// src/client/router/link-utils.ts
|
|
5207
|
-
function buildHref(to, search, hash) {
|
|
6416
|
+
function buildHref(to, search, hash, searchDefaults) {
|
|
5208
6417
|
let url = to;
|
|
5209
6418
|
if (search && Object.keys(search).length > 0) {
|
|
5210
|
-
const params =
|
|
5211
|
-
for (const [k, v] of Object.entries(search)) {
|
|
5212
|
-
if (v != null) {
|
|
5213
|
-
params.set(k, String(v));
|
|
5214
|
-
}
|
|
5215
|
-
}
|
|
6419
|
+
const params = buildSearchParams(search, searchDefaults);
|
|
5216
6420
|
const qs = params.toString();
|
|
5217
6421
|
if (qs) {
|
|
5218
6422
|
url += `?${qs}`;
|
|
@@ -5231,6 +6435,63 @@ function normalizeHref(href) {
|
|
|
5231
6435
|
}
|
|
5232
6436
|
return pathname + url.search + url.hash;
|
|
5233
6437
|
}
|
|
6438
|
+
// src/client/router/search-store.ts
|
|
6439
|
+
import { createContext as createContext2 } from "react";
|
|
6440
|
+
function searchSnapshotChanged(a, b) {
|
|
6441
|
+
return a.currentHref !== b.currentHref || a.navigate !== b.navigate || a.search !== b.search || a.searchRoutes !== b.searchRoutes;
|
|
6442
|
+
}
|
|
6443
|
+
function createSearchStore(initialSnapshot) {
|
|
6444
|
+
let snapshot = initialSnapshot;
|
|
6445
|
+
let version = 0;
|
|
6446
|
+
let flushedVersion = 0;
|
|
6447
|
+
const listeners = new Set;
|
|
6448
|
+
return {
|
|
6449
|
+
flush: () => {
|
|
6450
|
+
if (flushedVersion === version) {
|
|
6451
|
+
return;
|
|
6452
|
+
}
|
|
6453
|
+
flushedVersion = version;
|
|
6454
|
+
for (const listener of [...listeners]) {
|
|
6455
|
+
listener();
|
|
6456
|
+
}
|
|
6457
|
+
},
|
|
6458
|
+
getServerSnapshot: () => snapshot,
|
|
6459
|
+
getSnapshot: () => snapshot,
|
|
6460
|
+
setSnapshot: (next) => {
|
|
6461
|
+
if (!searchSnapshotChanged(snapshot, next)) {
|
|
6462
|
+
return;
|
|
6463
|
+
}
|
|
6464
|
+
snapshot = next;
|
|
6465
|
+
version++;
|
|
6466
|
+
},
|
|
6467
|
+
subscribe: (listener) => {
|
|
6468
|
+
listeners.add(listener);
|
|
6469
|
+
return () => {
|
|
6470
|
+
listeners.delete(listener);
|
|
6471
|
+
};
|
|
6472
|
+
}
|
|
6473
|
+
};
|
|
6474
|
+
}
|
|
6475
|
+
function searchSnapshotFromRouterContext(context) {
|
|
6476
|
+
return {
|
|
6477
|
+
currentHref: context.currentHref,
|
|
6478
|
+
navigate: context.navigate,
|
|
6479
|
+
search: context.search,
|
|
6480
|
+
searchRoutes: context.searchRoutes
|
|
6481
|
+
};
|
|
6482
|
+
}
|
|
6483
|
+
var FALLBACK_SEARCH_STORE = createSearchStore({
|
|
6484
|
+
currentHref: "/",
|
|
6485
|
+
navigate: (href, _opts) => {
|
|
6486
|
+
if (typeof window !== "undefined") {
|
|
6487
|
+
window.location.href = href;
|
|
6488
|
+
}
|
|
6489
|
+
return Promise.resolve();
|
|
6490
|
+
},
|
|
6491
|
+
search: {},
|
|
6492
|
+
searchRoutes: []
|
|
6493
|
+
});
|
|
6494
|
+
var SearchStoreContext = createContext2(null);
|
|
5234
6495
|
// src/shared/digest.ts
|
|
5235
6496
|
function computeErrorDigest(err) {
|
|
5236
6497
|
let message = "";
|
|
@@ -5266,9 +6527,6 @@ function cyrb53(input) {
|
|
|
5266
6527
|
return 4294967296 * (2097151 & h2) + (4294967295 & h1);
|
|
5267
6528
|
}
|
|
5268
6529
|
|
|
5269
|
-
// src/server/runtime-env.ts
|
|
5270
|
-
var IS_DEV = true;
|
|
5271
|
-
|
|
5272
6530
|
// src/client/boundaries.tsx
|
|
5273
6531
|
import { Component, Fragment } from "react";
|
|
5274
6532
|
|
|
@@ -5306,8 +6564,9 @@ function computeLinkView({
|
|
|
5306
6564
|
activeProps,
|
|
5307
6565
|
inactiveProps
|
|
5308
6566
|
}, router2) {
|
|
5309
|
-
const
|
|
5310
|
-
const
|
|
6567
|
+
const searchDefaults = findSearchDefaultsForRouteTarget(to, router2.searchRoutes);
|
|
6568
|
+
const logicalHref = buildHref(to, search, hash, searchDefaults);
|
|
6569
|
+
const logicalHrefWithoutHash = buildHref(to, search, undefined, searchDefaults);
|
|
5311
6570
|
const isAbsolute = logicalHref.startsWith("http://") || logicalHref.startsWith("https://") || logicalHref.startsWith("//");
|
|
5312
6571
|
const href = isAbsolute ? logicalHref : router2.basePath + logicalHref;
|
|
5313
6572
|
const isActive = !isAbsolute && router2.currentHref === normalizeHref(logicalHrefWithoutHash);
|
|
@@ -5441,6 +6700,8 @@ function LinkInteractive({
|
|
|
5441
6700
|
var SSR_FALLBACK_ROUTER = {
|
|
5442
6701
|
basePath: "",
|
|
5443
6702
|
currentHref: "/",
|
|
6703
|
+
search: {},
|
|
6704
|
+
searchRoutes: [],
|
|
5444
6705
|
navigate: (_href, _opts) => Promise.resolve(),
|
|
5445
6706
|
prefetch: (_href, _opts) => {},
|
|
5446
6707
|
invalidatePrefetch: (_path, _type) => {},
|
|
@@ -6023,7 +7284,7 @@ function mergeLoaderResults(results) {
|
|
|
6023
7284
|
}
|
|
6024
7285
|
async function runLoaders(route, ctx) {
|
|
6025
7286
|
try {
|
|
6026
|
-
const ctxRecord = { ...ctx, log:
|
|
7287
|
+
const ctxRecord = { ...ctx, log: useLogger3() };
|
|
6027
7288
|
const loaderMap = new Map;
|
|
6028
7289
|
let accumulatedParentPromise = Promise.resolve({});
|
|
6029
7290
|
for (const r of route.routeChain) {
|
|
@@ -6117,13 +7378,18 @@ function getProductionTemplate() {
|
|
|
6117
7378
|
|
|
6118
7379
|
// src/server/render/ssr.ts
|
|
6119
7380
|
function withSSRRouterContext(element, contextValue) {
|
|
6120
|
-
return createElement2(RouterContext.Provider, { value: contextValue }, element);
|
|
7381
|
+
return createElement2(SearchStoreContext.Provider, { value: createSearchStore(searchSnapshotFromRouterContext(contextValue)) }, createElement2(RouterContext.Provider, { value: contextValue }, element));
|
|
6121
7382
|
}
|
|
6122
7383
|
function assertDeferredModeAllowed(route, deferredPromises) {
|
|
6123
7384
|
if (deferredPromises !== undefined && route.mode !== "ssr") {
|
|
6124
7385
|
throw new Error(`[furin] page "${route.pattern}" returned defer() but the route is rendered in "${route.mode}" mode. ` + "defer() streams data progressively and is only supported in SSR. " + "Return the data directly (await it inside the loader) or switch the route to SSR mode.");
|
|
6125
7386
|
}
|
|
6126
7387
|
}
|
|
7388
|
+
function currentHrefFromContext(ctx) {
|
|
7389
|
+
const pathUrl = new URL(ctx.path, "http://furin.local");
|
|
7390
|
+
const requestUrl = new URL(ctx.request.url);
|
|
7391
|
+
return normalizeHref(pathUrl.pathname) + (pathUrl.search || requestUrl.search);
|
|
7392
|
+
}
|
|
6127
7393
|
function buildSuccessRender(route, root, componentProps, throwOnFailure) {
|
|
6128
7394
|
try {
|
|
6129
7395
|
const headData = buildHeadInjection(route.page?.head?.(componentProps));
|
|
@@ -6138,7 +7404,7 @@ function buildSuccessRender(route, root, componentProps, throwOnFailure) {
|
|
|
6138
7404
|
return { element, headData: "", errorDigest, status: 500 };
|
|
6139
7405
|
}
|
|
6140
7406
|
}
|
|
6141
|
-
async function prepareRender(route, ctx, root, basePath, throwOnFailure, precomputedLoaderResult) {
|
|
7407
|
+
async function prepareRender(route, ctx, root, basePath, throwOnFailure, precomputedLoaderResult, searchRoutes) {
|
|
6142
7408
|
const loaderStart = Date.now();
|
|
6143
7409
|
const loaderResult = precomputedLoaderResult ?? await runLoaders(route, ctx);
|
|
6144
7410
|
const loader_ms = Date.now() - loaderStart;
|
|
@@ -6186,7 +7452,9 @@ async function prepareRender(route, ctx, root, basePath, throwOnFailure, precomp
|
|
|
6186
7452
|
}
|
|
6187
7453
|
const ssrContext = {
|
|
6188
7454
|
basePath: basePath ?? "",
|
|
6189
|
-
currentHref:
|
|
7455
|
+
currentHref: currentHrefFromContext(ctx),
|
|
7456
|
+
search: ctx.query ?? {},
|
|
7457
|
+
searchRoutes: searchRoutes ?? [],
|
|
6190
7458
|
navigate: (_href, _opts) => Promise.resolve(),
|
|
6191
7459
|
prefetch: (_href, _opts) => {},
|
|
6192
7460
|
invalidatePrefetch: (_path, _type) => {},
|
|
@@ -6212,7 +7480,7 @@ async function prepareRender(route, ctx, root, basePath, throwOnFailure, precomp
|
|
|
6212
7480
|
template
|
|
6213
7481
|
};
|
|
6214
7482
|
}
|
|
6215
|
-
function renderForPath(route, params, root, origin, mode, basePath) {
|
|
7483
|
+
function renderForPath(route, params, root, origin, mode, basePath, searchRoutes) {
|
|
6216
7484
|
return runInSyntheticRenderScope(async () => {
|
|
6217
7485
|
const resolvedPath = resolvePath(route.pattern, params);
|
|
6218
7486
|
const ctx = {
|
|
@@ -6225,11 +7493,11 @@ function renderForPath(route, params, root, origin, mode, basePath) {
|
|
|
6225
7493
|
set: { headers: {} },
|
|
6226
7494
|
path: resolvedPath
|
|
6227
7495
|
};
|
|
6228
|
-
const prepared = await prepareRender(route, ctx, root, basePath, true, undefined);
|
|
7496
|
+
const prepared = await prepareRender(route, ctx, root, basePath, true, undefined, searchRoutes);
|
|
6229
7497
|
if (prepared instanceof Response) {
|
|
6230
7498
|
return prepared;
|
|
6231
7499
|
}
|
|
6232
|
-
|
|
7500
|
+
useLogger3().set({
|
|
6233
7501
|
furin: {
|
|
6234
7502
|
render: mode,
|
|
6235
7503
|
route: route.pattern,
|
|
@@ -6261,7 +7529,7 @@ async function serializeLoaderDataNdjson(syncData, deferredPromises) {
|
|
|
6261
7529
|
}
|
|
6262
7530
|
|
|
6263
7531
|
// src/server/render/ssg.ts
|
|
6264
|
-
async function prerenderSSG(route, params, root, origin, basePath) {
|
|
7532
|
+
async function prerenderSSG(route, params, root, origin, basePath, searchRoutes) {
|
|
6265
7533
|
const resolvedPath = resolvePath(route.pattern, params);
|
|
6266
7534
|
const cached = getSSGCache(resolvedPath);
|
|
6267
7535
|
if (cached) {
|
|
@@ -6272,7 +7540,7 @@ async function prerenderSSG(route, params, root, origin, basePath) {
|
|
|
6272
7540
|
setSSGCache(resolvedPath, taggedEntry);
|
|
6273
7541
|
return taggedEntry;
|
|
6274
7542
|
}
|
|
6275
|
-
const renderResult = await renderForPath(route, params, root, origin, "ssg", basePath);
|
|
7543
|
+
const renderResult = await renderForPath(route, params, root, origin, "ssg", basePath, searchRoutes);
|
|
6276
7544
|
if (renderResult instanceof Response) {
|
|
6277
7545
|
return renderResult;
|
|
6278
7546
|
}
|
|
@@ -6290,13 +7558,14 @@ async function prerenderSSG(route, params, root, origin, basePath) {
|
|
|
6290
7558
|
// src/build/ssg-cache.ts
|
|
6291
7559
|
async function buildSSGCacheSnapshot(routes, root, origin) {
|
|
6292
7560
|
const snapshot = {};
|
|
7561
|
+
const searchRoutes = createSearchRouteMetadata(routes);
|
|
6293
7562
|
for (const route of routes) {
|
|
6294
7563
|
if (route.mode !== "ssg" || !route.page.staticParams) {
|
|
6295
7564
|
continue;
|
|
6296
7565
|
}
|
|
6297
7566
|
const paramSets = await route.page.staticParams();
|
|
6298
7567
|
for (const params of paramSets) {
|
|
6299
|
-
const entry = await prerenderSSG(route, params, root, origin, undefined);
|
|
7568
|
+
const entry = await prerenderSSG(route, params, root, origin, undefined, searchRoutes);
|
|
6300
7569
|
if (entry instanceof Response) {
|
|
6301
7570
|
continue;
|
|
6302
7571
|
}
|
|
@@ -6307,8 +7576,8 @@ async function buildSSGCacheSnapshot(routes, root, origin) {
|
|
|
6307
7576
|
}
|
|
6308
7577
|
|
|
6309
7578
|
// src/adapter/bun.ts
|
|
6310
|
-
var _pkgRoot2 = dirname2(dirname2(
|
|
6311
|
-
var _pkgSrcDir2 =
|
|
7579
|
+
var _pkgRoot2 = dirname2(dirname2(fileURLToPath3(import.meta.resolve("@teyik0/furin"))));
|
|
7580
|
+
var _pkgSrcDir2 = existsSync8(join9(_pkgRoot2, "src", "furin.ts")) ? join9(_pkgRoot2, "src") : join9(_pkgRoot2, "dist");
|
|
6312
7581
|
var _ext2 = ".ts";
|
|
6313
7582
|
var BUILD_ID_INPUT_PATHS = [
|
|
6314
7583
|
`${_pkgSrcDir2}/build/compile-entry${_ext2}`,
|
|
@@ -6340,32 +7609,32 @@ async function createBuildFingerprint(entryChunk, cssChunks, routes, root, serve
|
|
|
6340
7609
|
}
|
|
6341
7610
|
}
|
|
6342
7611
|
for (const path of BUILD_ID_INPUT_PATHS) {
|
|
6343
|
-
if (!
|
|
6344
|
-
console.warn(`[furin] Warning: build fingerprint input "${
|
|
7612
|
+
if (!existsSync8(path)) {
|
|
7613
|
+
console.warn(`[furin] Warning: build fingerprint input "${toPosixPath2(path)}" is missing \u2014 ` + "the generated build ID may not reflect all framework changes.");
|
|
6345
7614
|
}
|
|
6346
7615
|
fingerprintPaths.add(path);
|
|
6347
7616
|
}
|
|
6348
7617
|
const fileParts = await Promise.all([...fingerprintPaths].toSorted().map(async (path) => {
|
|
6349
|
-
const content =
|
|
6350
|
-
return `${
|
|
7618
|
+
const content = existsSync8(path) ? await Bun.file(path).text() : "";
|
|
7619
|
+
return `${toPosixPath2(path)}:${content}`;
|
|
6351
7620
|
}));
|
|
6352
|
-
const routeParts = routes.map((route) => JSON.stringify({ mode: route.mode, path:
|
|
7621
|
+
const routeParts = routes.map((route) => JSON.stringify({ mode: route.mode, path: toPosixPath2(route.path), pattern: route.pattern })).sort();
|
|
6353
7622
|
return [entryChunk, ...[...cssChunks].toSorted(), ...routeParts, ...fileParts].join(`
|
|
6354
7623
|
`);
|
|
6355
7624
|
}
|
|
6356
7625
|
function buildCompileMetadata(root, routes) {
|
|
6357
7626
|
const rootConventions = root.errorPath || root.notFoundPath ? {
|
|
6358
|
-
errorPath: root.errorPath ?
|
|
6359
|
-
notFoundPath: root.notFoundPath ?
|
|
7627
|
+
errorPath: root.errorPath ? toPosixPath2(root.errorPath) : undefined,
|
|
7628
|
+
notFoundPath: root.notFoundPath ? toPosixPath2(root.notFoundPath) : undefined
|
|
6360
7629
|
} : undefined;
|
|
6361
7630
|
const routeMetadata = {};
|
|
6362
7631
|
for (const route of routes) {
|
|
6363
|
-
routeMetadata[
|
|
7632
|
+
routeMetadata[toPosixPath2(route.path)] = {
|
|
6364
7633
|
segmentBoundaries: route.segmentBoundaries.map((b) => ({
|
|
6365
7634
|
depth: b.depth,
|
|
6366
|
-
path:
|
|
6367
|
-
errorPath: b.errorPath ?
|
|
6368
|
-
notFoundPath: b.notFoundPath ?
|
|
7635
|
+
path: toPosixPath2(b.path),
|
|
7636
|
+
errorPath: b.errorPath ? toPosixPath2(b.errorPath) : undefined,
|
|
7637
|
+
notFoundPath: b.notFoundPath ? toPosixPath2(b.notFoundPath) : undefined
|
|
6369
7638
|
}))
|
|
6370
7639
|
};
|
|
6371
7640
|
}
|
|
@@ -6391,21 +7660,21 @@ async function buildBunTarget(routes, rootDir, buildRoot, root, serverEntry, opt
|
|
|
6391
7660
|
const buildFingerprint = await createBuildFingerprint(entryChunk, cssChunks, routes, root, serverEntry);
|
|
6392
7661
|
const buildId = Bun.hash(buildFingerprint).toString(16).slice(0, 12);
|
|
6393
7662
|
targetManifest.buildId = buildId;
|
|
6394
|
-
const clientDir =
|
|
7663
|
+
const clientDir = join9(targetDir, "client");
|
|
6395
7664
|
const indexHtml = generateProdIndexHtml(entryChunk, cssChunks, buildId, undefined, false);
|
|
6396
|
-
writeFileSync6(
|
|
7665
|
+
writeFileSync6(join9(clientDir, "index.html"), indexHtml);
|
|
6397
7666
|
setProductionTemplateContent(indexHtml);
|
|
6398
7667
|
const routeManifest = routes.map((r) => ({ pattern: r.pattern, path: r.path, mode: r.mode }));
|
|
6399
7668
|
const ssgCache2 = serverEntry ? await buildSSGCacheSnapshot(routes, root, "http://localhost") : undefined;
|
|
6400
|
-
const publicDir =
|
|
6401
|
-
const targetPublicDir = publicDir ?
|
|
7669
|
+
const publicDir = existsSync8(join9(rootDir, "public")) ? join9(rootDir, "public") : undefined;
|
|
7670
|
+
const targetPublicDir = publicDir ? join9(targetDir, "public") : undefined;
|
|
6402
7671
|
if (publicDir && targetPublicDir && options.compile !== "embed") {
|
|
6403
7672
|
copyDirRecursive(publicDir, targetPublicDir);
|
|
6404
7673
|
}
|
|
6405
7674
|
const { rootConventions, routeMetadata } = buildCompileMetadata(root, routes);
|
|
6406
7675
|
if (options.compile && serverEntry) {
|
|
6407
|
-
const clientDir2 =
|
|
6408
|
-
const outfile =
|
|
7676
|
+
const clientDir2 = join9(targetDir, "client");
|
|
7677
|
+
const outfile = join9(targetDir, "server");
|
|
6409
7678
|
const entryPath = generateCompileEntry({
|
|
6410
7679
|
buildId,
|
|
6411
7680
|
rootPath: root.path,
|
|
@@ -6427,7 +7696,7 @@ async function buildBunTarget(routes, rootDir, buildRoot, root, serverEntry, opt
|
|
|
6427
7696
|
plugins: options.plugins
|
|
6428
7697
|
});
|
|
6429
7698
|
console.log(`[furin] Server binary: ${outfile}`);
|
|
6430
|
-
targetManifest.serverPath =
|
|
7699
|
+
targetManifest.serverPath = toPosixPath2(join9(targetManifest.targetDir, "server"));
|
|
6431
7700
|
if (options.compile === "embed") {
|
|
6432
7701
|
rmSync2(clientDir2, { force: true, recursive: true });
|
|
6433
7702
|
targetManifest.clientDir = null;
|
|
@@ -6452,8 +7721,8 @@ async function buildBunTarget(routes, rootDir, buildRoot, root, serverEntry, opt
|
|
|
6452
7721
|
sourcemap: "none",
|
|
6453
7722
|
plugins: options.plugins
|
|
6454
7723
|
});
|
|
6455
|
-
console.log(`[furin] Server bundle: ${
|
|
6456
|
-
targetManifest.serverPath =
|
|
7724
|
+
console.log(`[furin] Server bundle: ${toPosixPath2(join9(targetManifest.targetDir, "server.js"))}`);
|
|
7725
|
+
targetManifest.serverPath = toPosixPath2(join9(targetManifest.targetDir, "server.js"));
|
|
6457
7726
|
}
|
|
6458
7727
|
for (const file of [
|
|
6459
7728
|
"_compile-entry.ts",
|
|
@@ -6461,21 +7730,21 @@ async function buildBunTarget(routes, rootDir, buildRoot, root, serverEntry, opt
|
|
|
6461
7730
|
"server.ts",
|
|
6462
7731
|
"_hydrate.tsx"
|
|
6463
7732
|
]) {
|
|
6464
|
-
rmSync2(
|
|
7733
|
+
rmSync2(join9(targetDir, file), { force: true });
|
|
6465
7734
|
}
|
|
6466
7735
|
return targetManifest;
|
|
6467
7736
|
}
|
|
6468
7737
|
|
|
6469
7738
|
// src/adapter/static.ts
|
|
6470
|
-
import { cpSync as cpSync2, existsSync as
|
|
6471
|
-
import { dirname as dirname3, isAbsolute, join as
|
|
7739
|
+
import { cpSync as cpSync2, existsSync as existsSync9, rmSync as rmSync3, writeFileSync as writeFileSync7 } from "fs";
|
|
7740
|
+
import { dirname as dirname3, isAbsolute, join as join10, relative as relative3, resolve as resolve2, sep } from "path";
|
|
6472
7741
|
var STATIC_CONCURRENCY = 4;
|
|
6473
7742
|
var DYNAMIC_SEGMENT_RE = /\/:[^/]+|\/\*/;
|
|
6474
7743
|
var TRAILING_SLASHES_RE2 = /\/+$/;
|
|
6475
7744
|
function pathToOutputFile(urlPath, outDir, fileName) {
|
|
6476
7745
|
const normalizedOutDir = resolve2(outDir);
|
|
6477
7746
|
if (urlPath === "/" || urlPath === "") {
|
|
6478
|
-
return
|
|
7747
|
+
return join10(normalizedOutDir, fileName);
|
|
6479
7748
|
}
|
|
6480
7749
|
const resolved = resolve2(normalizedOutDir, urlPath.slice(1), fileName);
|
|
6481
7750
|
if (!resolved.startsWith(`${normalizedOutDir}${sep}`)) {
|
|
@@ -6483,12 +7752,12 @@ function pathToOutputFile(urlPath, outDir, fileName) {
|
|
|
6483
7752
|
}
|
|
6484
7753
|
return resolved;
|
|
6485
7754
|
}
|
|
6486
|
-
async function prerenderAndWrite(route, params, root, outDir, renderedRoutes, skippedRoutes, basePath) {
|
|
7755
|
+
async function prerenderAndWrite(route, params, root, outDir, renderedRoutes, skippedRoutes, basePath, searchRoutes) {
|
|
6487
7756
|
const urlPath = resolvePath(route.pattern, params);
|
|
6488
7757
|
const htmlOutputFile = pathToOutputFile(urlPath, outDir, "index.html");
|
|
6489
7758
|
const dataOutputFile = pathToOutputFile(urlPath, outDir, "__furin_data.ndjson");
|
|
6490
7759
|
try {
|
|
6491
|
-
const entry = await prerenderSSG(route, params, root, "http://localhost", basePath);
|
|
7760
|
+
const entry = await prerenderSSG(route, params, root, "http://localhost", basePath, searchRoutes);
|
|
6492
7761
|
if (entry instanceof Response) {
|
|
6493
7762
|
console.warn(`[furin] static: route "${route.pattern}" loader returned a redirect \u2014 skipping.`);
|
|
6494
7763
|
return;
|
|
@@ -6497,7 +7766,7 @@ async function prerenderAndWrite(route, params, root, outDir, renderedRoutes, sk
|
|
|
6497
7766
|
writeFileSync7(htmlOutputFile, entry.html);
|
|
6498
7767
|
writeFileSync7(dataOutputFile, entry.ndjson);
|
|
6499
7768
|
renderedRoutes.push(urlPath);
|
|
6500
|
-
console.log(`[furin] static: ${urlPath} \u2192 ${
|
|
7769
|
+
console.log(`[furin] static: ${urlPath} \u2192 ${toPosixPath2(htmlOutputFile)}`);
|
|
6501
7770
|
} catch (err) {
|
|
6502
7771
|
console.error(`[furin] static: prerender failed for "${route.pattern}" (params: ${JSON.stringify(params)}):`, err);
|
|
6503
7772
|
skippedRoutes.push(urlPath);
|
|
@@ -6522,7 +7791,7 @@ function collectSsgRoutes(routes, onSSR, skippedRoutes) {
|
|
|
6522
7791
|
}
|
|
6523
7792
|
return routes.filter((r) => r.mode === "ssg");
|
|
6524
7793
|
}
|
|
6525
|
-
async function buildTaskQueue(ssgRoutes, root, outDir, renderedRoutes, skippedRoutes, basePath) {
|
|
7794
|
+
async function buildTaskQueue(ssgRoutes, root, outDir, renderedRoutes, skippedRoutes, basePath, searchRoutes) {
|
|
6526
7795
|
const tasks = [];
|
|
6527
7796
|
const staticParamsResults = await mapWithConcurrency(ssgRoutes, STATIC_CONCURRENCY, async (route) => {
|
|
6528
7797
|
if (!DYNAMIC_SEGMENT_RE.test(route.pattern)) {
|
|
@@ -6555,7 +7824,7 @@ async function buildTaskQueue(ssgRoutes, root, outDir, renderedRoutes, skippedRo
|
|
|
6555
7824
|
continue;
|
|
6556
7825
|
}
|
|
6557
7826
|
for (const params of result.paramSets) {
|
|
6558
|
-
tasks.push(() => prerenderAndWrite(result.route, params, root, outDir, renderedRoutes, skippedRoutes, basePath));
|
|
7827
|
+
tasks.push(() => prerenderAndWrite(result.route, params, root, outDir, renderedRoutes, skippedRoutes, basePath, searchRoutes));
|
|
6559
7828
|
}
|
|
6560
7829
|
}
|
|
6561
7830
|
return tasks;
|
|
@@ -6601,9 +7870,10 @@ async function buildStaticTarget(routes, rootDir, buildRoot, root, options) {
|
|
|
6601
7870
|
const renderedRoutes = [];
|
|
6602
7871
|
const skippedRoutes = [];
|
|
6603
7872
|
const ssgRoutes = collectSsgRoutes(routes, onSSR, skippedRoutes);
|
|
7873
|
+
const searchRoutes = createSearchRouteMetadata(ssgRoutes);
|
|
6604
7874
|
rmSync3(outDir, { force: true, recursive: true });
|
|
6605
7875
|
ensureDir(outDir);
|
|
6606
|
-
const targetDir =
|
|
7876
|
+
const targetDir = join10(buildRoot, "static");
|
|
6607
7877
|
rmSync3(targetDir, { force: true, recursive: true });
|
|
6608
7878
|
ensureDir(targetDir);
|
|
6609
7879
|
const { entryChunk, cssChunks } = await buildClient(ssgRoutes, {
|
|
@@ -6614,19 +7884,19 @@ async function buildStaticTarget(routes, rootDir, buildRoot, root, options) {
|
|
|
6614
7884
|
basePath,
|
|
6615
7885
|
clientLogging: Boolean(options.clientLogging)
|
|
6616
7886
|
});
|
|
6617
|
-
const publicFavicon =
|
|
6618
|
-
const faviconHref =
|
|
7887
|
+
const publicFavicon = join10(rootDir, "public", "favicon.ico");
|
|
7888
|
+
const faviconHref = existsSync9(publicFavicon) ? `${basePath}/favicon.ico` : undefined;
|
|
6619
7889
|
const shellHtml = generateProdIndexHtml(entryChunk, cssChunks, undefined, faviconHref, true);
|
|
6620
7890
|
setProductionTemplateContent(shellHtml);
|
|
6621
|
-
const publicSrcDir =
|
|
6622
|
-
if (
|
|
7891
|
+
const publicSrcDir = join10(rootDir, "public");
|
|
7892
|
+
if (existsSync9(publicSrcDir)) {
|
|
6623
7893
|
cpSync2(publicSrcDir, outDir, { recursive: true });
|
|
6624
7894
|
}
|
|
6625
|
-
const clientSrcDir =
|
|
6626
|
-
if (
|
|
6627
|
-
cpSync2(clientSrcDir,
|
|
7895
|
+
const clientSrcDir = join10(targetDir, "client");
|
|
7896
|
+
if (existsSync9(clientSrcDir)) {
|
|
7897
|
+
cpSync2(clientSrcDir, join10(outDir, "_client"), { recursive: true });
|
|
6628
7898
|
}
|
|
6629
|
-
const tasks = await buildTaskQueue(ssgRoutes, root, outDir, renderedRoutes, skippedRoutes, basePath);
|
|
7899
|
+
const tasks = await buildTaskQueue(ssgRoutes, root, outDir, renderedRoutes, skippedRoutes, basePath, searchRoutes);
|
|
6630
7900
|
const afterQueueCount = skippedRoutes.length;
|
|
6631
7901
|
await runWithConcurrency(tasks, STATIC_CONCURRENCY);
|
|
6632
7902
|
if (onSSR === "error" && skippedRoutes.length > afterQueueCount) {
|
|
@@ -6637,273 +7907,40 @@ async function buildStaticTarget(routes, rootDir, buildRoot, root, options) {
|
|
|
6637
7907
|
${list}
|
|
6638
7908
|
` + `Set \`onSSR: "skip"\` in your static config to suppress this error.`);
|
|
6639
7909
|
}
|
|
6640
|
-
writeFileSync7(
|
|
7910
|
+
writeFileSync7(join10(outDir, "404.html"), shellHtml);
|
|
6641
7911
|
console.log("[furin] static: wrote 404.html (SPA shell fallback)");
|
|
6642
7912
|
rmSync3(targetDir, { force: true, recursive: true });
|
|
6643
|
-
console.log(`[furin] static: export complete \u2192 ${
|
|
7913
|
+
console.log(`[furin] static: export complete \u2192 ${toPosixPath2(outDir)}` + ` (${renderedRoutes.length} rendered, ${skippedRoutes.length} skipped)`);
|
|
6644
7914
|
return {
|
|
6645
7915
|
basePath,
|
|
6646
7916
|
generatedAt: new Date().toISOString(),
|
|
6647
|
-
outDir:
|
|
7917
|
+
outDir: toPosixPath2(outDir),
|
|
6648
7918
|
renderedRoutes,
|
|
6649
7919
|
skippedRoutes
|
|
6650
7920
|
};
|
|
6651
7921
|
}
|
|
6652
7922
|
|
|
6653
7923
|
// src/config.ts
|
|
6654
|
-
import { t } from "elysia";
|
|
7924
|
+
import { t as t2 } from "elysia";
|
|
6655
7925
|
var BUILD_TARGETS = ["bun", "node", "vercel", "cloudflare", "static"];
|
|
6656
|
-
var buildTargetSchema =
|
|
6657
|
-
var compileTargetSchema =
|
|
6658
|
-
var configSchema =
|
|
6659
|
-
rootDir:
|
|
6660
|
-
pagesDir:
|
|
6661
|
-
serverEntry:
|
|
6662
|
-
clientLogging:
|
|
6663
|
-
targets:
|
|
6664
|
-
bun:
|
|
6665
|
-
compile:
|
|
7926
|
+
var buildTargetSchema = t2.Union(BUILD_TARGETS.map((v) => t2.Literal(v)));
|
|
7927
|
+
var compileTargetSchema = t2.Union([t2.Literal("server"), t2.Literal("embed")]);
|
|
7928
|
+
var configSchema = t2.Object({
|
|
7929
|
+
rootDir: t2.Optional(t2.String()),
|
|
7930
|
+
pagesDir: t2.Optional(t2.String()),
|
|
7931
|
+
serverEntry: t2.Optional(t2.String()),
|
|
7932
|
+
clientLogging: t2.Optional(t2.Boolean()),
|
|
7933
|
+
targets: t2.Optional(t2.Array(buildTargetSchema)),
|
|
7934
|
+
bun: t2.Optional(t2.Object({
|
|
7935
|
+
compile: t2.Optional(compileTargetSchema)
|
|
6666
7936
|
})),
|
|
6667
|
-
static:
|
|
6668
|
-
basePath:
|
|
6669
|
-
outDir:
|
|
6670
|
-
onSSR:
|
|
7937
|
+
static: t2.Optional(t2.Object({
|
|
7938
|
+
basePath: t2.Optional(t2.String()),
|
|
7939
|
+
outDir: t2.Optional(t2.String()),
|
|
7940
|
+
onSSR: t2.Optional(t2.Union([t2.Literal("error"), t2.Literal("skip")]))
|
|
6671
7941
|
}))
|
|
6672
7942
|
});
|
|
6673
7943
|
|
|
6674
|
-
// src/server/router/discovery.ts
|
|
6675
|
-
import { existsSync as existsSync9 } from "fs";
|
|
6676
|
-
import { readdir } from "fs/promises";
|
|
6677
|
-
import { join as join10, parse as parse3 } from "path";
|
|
6678
|
-
|
|
6679
|
-
// src/server/internal.ts
|
|
6680
|
-
var _compileCtx = null;
|
|
6681
|
-
function getCompileContext() {
|
|
6682
|
-
return _compileCtx;
|
|
6683
|
-
}
|
|
6684
|
-
|
|
6685
|
-
// src/server/router/discovery.ts
|
|
6686
|
-
function collectRouteTags(routeChain, page) {
|
|
6687
|
-
const tags = new Set;
|
|
6688
|
-
for (const route of routeChain) {
|
|
6689
|
-
for (const tag of route.tags ?? []) {
|
|
6690
|
-
tags.add(tag);
|
|
6691
|
-
}
|
|
6692
|
-
}
|
|
6693
|
-
for (const tag of page?.tags ?? []) {
|
|
6694
|
-
tags.add(tag);
|
|
6695
|
-
}
|
|
6696
|
-
return tags.size > 0 ? [...tags] : undefined;
|
|
6697
|
-
}
|
|
6698
|
-
function toPosixPath2(path) {
|
|
6699
|
-
return path.replaceAll("\\", "/");
|
|
6700
|
-
}
|
|
6701
|
-
function routeRelativePath(pagesDir, absolutePath) {
|
|
6702
|
-
const dir = toPosixPath2(pagesDir).replace(/\/+$/g, "");
|
|
6703
|
-
const path = toPosixPath2(absolutePath);
|
|
6704
|
-
return path.startsWith(`${dir}/`) ? path.slice(dir.length + 1) : path;
|
|
6705
|
-
}
|
|
6706
|
-
async function scanPages(pagesDir) {
|
|
6707
|
-
const dir = toPosixPath2(pagesDir);
|
|
6708
|
-
const root = await scanRootLayout(dir);
|
|
6709
|
-
const routes = await scanPageFiles(dir, root);
|
|
6710
|
-
return { root, routes };
|
|
6711
|
-
}
|
|
6712
|
-
async function scanRootLayout(pagesDir) {
|
|
6713
|
-
const rootPath = `${pagesDir}/root.tsx`;
|
|
6714
|
-
const ctx = getCompileContext();
|
|
6715
|
-
if (!(existsSync9(rootPath) || ctx?.modules[rootPath])) {
|
|
6716
|
-
throw new Error("[furin] root.tsx: not found.");
|
|
6717
|
-
}
|
|
6718
|
-
const mod = ctx?.modules[rootPath] ?? await import(rootPath);
|
|
6719
|
-
const rootExport = mod.route ?? mod.default;
|
|
6720
|
-
if (!(rootExport && isFurinRoute(rootExport))) {
|
|
6721
|
-
throw new Error("[furin] root.tsx: createRoute() export not found.");
|
|
6722
|
-
}
|
|
6723
|
-
if (!rootExport.layout) {
|
|
6724
|
-
throw new Error("[furin] root.tsx: createRoute() has no layout.");
|
|
6725
|
-
}
|
|
6726
|
-
const [notFoundEntry, errorEntry] = await Promise.all([
|
|
6727
|
-
loadConventionComponent(pagesDir, "not-found"),
|
|
6728
|
-
loadConventionComponent(pagesDir, "error")
|
|
6729
|
-
]);
|
|
6730
|
-
return {
|
|
6731
|
-
path: rootPath,
|
|
6732
|
-
route: rootExport,
|
|
6733
|
-
notFound: notFoundEntry?.component,
|
|
6734
|
-
notFoundPath: notFoundEntry?.path,
|
|
6735
|
-
error: errorEntry?.component,
|
|
6736
|
-
errorPath: errorEntry?.path
|
|
6737
|
-
};
|
|
6738
|
-
}
|
|
6739
|
-
var CONVENTION_FILE_NAMES = ["not-found", "error"];
|
|
6740
|
-
var SOURCE_MODULE_EXTENSIONS = [".tsx", ".ts", ".jsx", ".js"];
|
|
6741
|
-
function isConventionFileName(name) {
|
|
6742
|
-
return CONVENTION_FILE_NAMES.includes(name);
|
|
6743
|
-
}
|
|
6744
|
-
function getSourceModuleCandidates(dir, name) {
|
|
6745
|
-
return SOURCE_MODULE_EXTENSIONS.map((ext) => `${dir}/${name}${ext}`);
|
|
6746
|
-
}
|
|
6747
|
-
async function loadConventionComponent(dir, name) {
|
|
6748
|
-
const ctx = getCompileContext();
|
|
6749
|
-
for (const filePath of getSourceModuleCandidates(dir, name)) {
|
|
6750
|
-
if (existsSync9(filePath) || ctx?.modules[filePath]) {
|
|
6751
|
-
const mod = ctx?.modules[filePath] ?? await import(filePath);
|
|
6752
|
-
if (mod.default) {
|
|
6753
|
-
return { component: mod.default, path: filePath };
|
|
6754
|
-
}
|
|
6755
|
-
}
|
|
6756
|
-
}
|
|
6757
|
-
return;
|
|
6758
|
-
}
|
|
6759
|
-
async function scanPageFiles(pagesDir, root) {
|
|
6760
|
-
const routes = [];
|
|
6761
|
-
const notFoundCache = new Map;
|
|
6762
|
-
const errorCache = new Map;
|
|
6763
|
-
for (const absolutePath of await collectPageFilePaths(pagesDir)) {
|
|
6764
|
-
if (!SOURCE_MODULE_EXTENSIONS.some((ext) => absolutePath.endsWith(ext))) {
|
|
6765
|
-
continue;
|
|
6766
|
-
}
|
|
6767
|
-
const relativePath = routeRelativePath(pagesDir, absolutePath);
|
|
6768
|
-
const fileName = parse3(relativePath).name;
|
|
6769
|
-
if (fileName.startsWith("_") || fileName === "root" || isConventionFileName(fileName)) {
|
|
6770
|
-
continue;
|
|
6771
|
-
}
|
|
6772
|
-
const [notFound, errorComponent, segmentBoundaries] = await Promise.all([
|
|
6773
|
-
resolveNearestConvention(absolutePath, pagesDir, "not-found", notFoundCache, root.notFound),
|
|
6774
|
-
resolveNearestConvention(absolutePath, pagesDir, "error", errorCache, root.error),
|
|
6775
|
-
collectSegmentBoundaries(absolutePath, pagesDir, notFoundCache, errorCache)
|
|
6776
|
-
]);
|
|
6777
|
-
if (IS_DEV) {
|
|
6778
|
-
const devRoute = await buildDevRoute(absolutePath, relativePath, root);
|
|
6779
|
-
devRoute.notFound = notFound;
|
|
6780
|
-
devRoute.error = errorComponent;
|
|
6781
|
-
devRoute.segmentBoundaries = segmentBoundaries;
|
|
6782
|
-
routes.push(devRoute);
|
|
6783
|
-
continue;
|
|
6784
|
-
}
|
|
6785
|
-
const ctx = getCompileContext();
|
|
6786
|
-
const pageMod = ctx?.modules[absolutePath] ?? await import(absolutePath);
|
|
6787
|
-
const page = pageMod.default;
|
|
6788
|
-
if (!isFurinPage(page)) {
|
|
6789
|
-
throw new Error(`[furin] ${relativePath}: no valid createRoute().page() export found`);
|
|
6790
|
-
}
|
|
6791
|
-
const routeChain = collectRouteChainFromRoute(page._route);
|
|
6792
|
-
validateRouteChain(routeChain, root.route, relativePath);
|
|
6793
|
-
routes.push({
|
|
6794
|
-
pattern: filePathToPattern(relativePath),
|
|
6795
|
-
page,
|
|
6796
|
-
path: absolutePath,
|
|
6797
|
-
routeChain,
|
|
6798
|
-
mode: resolveMode(page, routeChain),
|
|
6799
|
-
notFound,
|
|
6800
|
-
error: errorComponent,
|
|
6801
|
-
segmentBoundaries,
|
|
6802
|
-
tags: collectRouteTags(routeChain, page)
|
|
6803
|
-
});
|
|
6804
|
-
}
|
|
6805
|
-
return routes;
|
|
6806
|
-
}
|
|
6807
|
-
async function collectSegmentBoundaries(pageAbsolutePath, pagesDir, notFoundCache, errorCache) {
|
|
6808
|
-
const pageDir = pageAbsolutePath.slice(0, pageAbsolutePath.lastIndexOf("/"));
|
|
6809
|
-
const dirs = [pagesDir];
|
|
6810
|
-
if (pageDir.length > pagesDir.length) {
|
|
6811
|
-
const relativeTail = pageDir.slice(pagesDir.length + 1);
|
|
6812
|
-
const parts = relativeTail.split("/");
|
|
6813
|
-
let acc = pagesDir;
|
|
6814
|
-
for (const part of parts) {
|
|
6815
|
-
acc = `${acc}/${part}`;
|
|
6816
|
-
dirs.push(acc);
|
|
6817
|
-
}
|
|
6818
|
-
}
|
|
6819
|
-
const boundaries = [];
|
|
6820
|
-
for (let depth = 0;depth < dirs.length; depth++) {
|
|
6821
|
-
const dir = dirs[depth];
|
|
6822
|
-
const [errorEntry, notFoundEntry] = await Promise.all([
|
|
6823
|
-
errorCache.has(dir) ? Promise.resolve(errorCache.get(dir)) : loadConventionComponent(dir, "error").then((r) => {
|
|
6824
|
-
errorCache.set(dir, r);
|
|
6825
|
-
return r;
|
|
6826
|
-
}),
|
|
6827
|
-
notFoundCache.has(dir) ? Promise.resolve(notFoundCache.get(dir)) : loadConventionComponent(dir, "not-found").then((r) => {
|
|
6828
|
-
notFoundCache.set(dir, r);
|
|
6829
|
-
return r;
|
|
6830
|
-
})
|
|
6831
|
-
]);
|
|
6832
|
-
if (errorEntry || notFoundEntry) {
|
|
6833
|
-
boundaries.push({
|
|
6834
|
-
path: dir,
|
|
6835
|
-
depth,
|
|
6836
|
-
error: errorEntry?.component,
|
|
6837
|
-
errorPath: errorEntry?.path,
|
|
6838
|
-
notFound: notFoundEntry?.component,
|
|
6839
|
-
notFoundPath: notFoundEntry?.path
|
|
6840
|
-
});
|
|
6841
|
-
}
|
|
6842
|
-
}
|
|
6843
|
-
return boundaries;
|
|
6844
|
-
}
|
|
6845
|
-
async function resolveNearestConvention(pageAbsolutePath, pagesDir, conventionName, cache, rootFallback) {
|
|
6846
|
-
let dir = pageAbsolutePath.slice(0, pageAbsolutePath.lastIndexOf("/"));
|
|
6847
|
-
while (dir.length >= pagesDir.length) {
|
|
6848
|
-
if (!cache.has(dir)) {
|
|
6849
|
-
cache.set(dir, await loadConventionComponent(dir, conventionName));
|
|
6850
|
-
}
|
|
6851
|
-
const found = cache.get(dir);
|
|
6852
|
-
if (found) {
|
|
6853
|
-
return found.component;
|
|
6854
|
-
}
|
|
6855
|
-
if (dir === pagesDir) {
|
|
6856
|
-
break;
|
|
6857
|
-
}
|
|
6858
|
-
dir = dir.slice(0, dir.lastIndexOf("/"));
|
|
6859
|
-
}
|
|
6860
|
-
return rootFallback;
|
|
6861
|
-
}
|
|
6862
|
-
async function buildDevRoute(absolutePath, relativePath, root) {
|
|
6863
|
-
let page;
|
|
6864
|
-
let routeChain = [];
|
|
6865
|
-
try {
|
|
6866
|
-
const pageMod = await import(`${absolutePath}?furin-server&t=${Date.now()}`);
|
|
6867
|
-
if (isFurinPage(pageMod.default)) {
|
|
6868
|
-
page = pageMod.default;
|
|
6869
|
-
routeChain = collectRouteChainFromRoute(page._route);
|
|
6870
|
-
validateRouteChain(routeChain, root.route, relativePath);
|
|
6871
|
-
}
|
|
6872
|
-
} catch {}
|
|
6873
|
-
const devStubPage = {
|
|
6874
|
-
__type: "FURIN_PAGE",
|
|
6875
|
-
_route: { __type: "FURIN_ROUTE" },
|
|
6876
|
-
component: () => null
|
|
6877
|
-
};
|
|
6878
|
-
return {
|
|
6879
|
-
pattern: filePathToPattern(relativePath),
|
|
6880
|
-
path: absolutePath,
|
|
6881
|
-
mode: page ? resolveMode(page, routeChain) : "ssr",
|
|
6882
|
-
page: page ?? devStubPage,
|
|
6883
|
-
routeChain,
|
|
6884
|
-
tags: collectRouteTags(routeChain, page),
|
|
6885
|
-
segmentBoundaries: []
|
|
6886
|
-
};
|
|
6887
|
-
}
|
|
6888
|
-
var DIR_SCAN_CONCURRENCY = 8;
|
|
6889
|
-
async function collectPageFilePaths(dir) {
|
|
6890
|
-
const files = [];
|
|
6891
|
-
const entries = (await readdir(dir, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name));
|
|
6892
|
-
const resolved = await mapWithConcurrency(entries, DIR_SCAN_CONCURRENCY, async (entry) => {
|
|
6893
|
-
const absolutePath = toPosixPath2(join10(dir, entry.name));
|
|
6894
|
-
if (entry.isDirectory()) {
|
|
6895
|
-
return await collectPageFilePaths(absolutePath);
|
|
6896
|
-
}
|
|
6897
|
-
if (entry.isFile()) {
|
|
6898
|
-
return [absolutePath];
|
|
6899
|
-
}
|
|
6900
|
-
return [];
|
|
6901
|
-
});
|
|
6902
|
-
for (const chunk of resolved) {
|
|
6903
|
-
files.push(...chunk);
|
|
6904
|
-
}
|
|
6905
|
-
return files;
|
|
6906
|
-
}
|
|
6907
7944
|
// src/build/scan-server.ts
|
|
6908
7945
|
import { readFileSync as readFileSync4 } from "fs";
|
|
6909
7946
|
import { parse as parse4 } from "yuku-parser";
|
|
@@ -7027,10 +8064,10 @@ async function buildApp(options) {
|
|
|
7027
8064
|
const manifest = {
|
|
7028
8065
|
version: 1,
|
|
7029
8066
|
generatedAt: new Date().toISOString(),
|
|
7030
|
-
rootDir:
|
|
7031
|
-
pagesDir:
|
|
7032
|
-
rootPath:
|
|
7033
|
-
serverEntry: serverEntry ?
|
|
8067
|
+
rootDir: toPosixPath2(rootDir),
|
|
8068
|
+
pagesDir: toPosixPath2(relative4(rootDir, pagesDir)),
|
|
8069
|
+
rootPath: toPosixPath2(relative4(rootDir, root.path)),
|
|
8070
|
+
serverEntry: serverEntry ? toPosixPath2(relative4(rootDir, serverEntry)) : null,
|
|
7034
8071
|
routes: routes.map((route) => toBuildRouteManifestEntry(route, rootDir)),
|
|
7035
8072
|
targets: {}
|
|
7036
8073
|
};
|