@teyik0/furin 0.1.0-alpha.6 → 0.1.0-alpha.8

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.
Files changed (42) hide show
  1. package/dist/adapter/static.d.ts +3 -0
  2. package/dist/build/client.d.ts +3 -3
  3. package/dist/build/compile-entry.d.ts +4 -4
  4. package/dist/build/entry-template.d.ts +2 -2
  5. package/dist/build/hydrate.d.ts +6 -2
  6. package/dist/build/index.d.ts +1 -1
  7. package/dist/build/index.js +668 -90
  8. package/dist/build/types.d.ts +26 -3
  9. package/dist/cli/index.d.ts +1 -0
  10. package/dist/cli/index.js +704 -103
  11. package/dist/client.d.ts +22 -15
  12. package/dist/config.d.ts +33 -2
  13. package/dist/config.js +6 -1
  14. package/dist/dev-page-plugin.d.ts +77 -0
  15. package/dist/furin.js +771 -81
  16. package/dist/link.d.ts +31 -3
  17. package/dist/link.js +511 -62
  18. package/dist/render/index.d.ts +1 -1
  19. package/dist/render/loaders.d.ts +1 -1
  20. package/dist/router.js +84 -24
  21. package/package.json +9 -10
  22. package/src/adapter/bun.ts +31 -7
  23. package/src/adapter/static.ts +337 -0
  24. package/src/build/client.ts +28 -11
  25. package/src/build/compile-entry.ts +5 -3
  26. package/src/build/entry-template.ts +9 -5
  27. package/src/build/hydrate.ts +40 -10
  28. package/src/build/index.ts +56 -21
  29. package/src/build/scan-server.ts +43 -21
  30. package/src/build/shared.ts +7 -3
  31. package/src/build/types.ts +28 -3
  32. package/src/cli/index.ts +14 -5
  33. package/src/client.ts +26 -31
  34. package/src/config.ts +35 -1
  35. package/src/dev-page-plugin.ts +339 -4
  36. package/src/furin.ts +6 -2
  37. package/src/link.tsx +268 -62
  38. package/src/plugin/index.ts +2 -2
  39. package/src/render/index.ts +64 -24
  40. package/src/render/loaders.ts +77 -36
  41. package/src/render/shell.ts +2 -2
  42. package/src/router.ts +11 -1
@@ -1,11 +1,12 @@
1
1
  // @bun
2
2
  // src/build/index.ts
3
- import { existsSync as existsSync8, writeFileSync as writeFileSync7 } from "fs";
4
- import { join as join9, relative as relative3, resolve as resolve4 } from "path";
3
+ import { existsSync as existsSync9, writeFileSync as writeFileSync8 } from "fs";
4
+ import { join as join10, relative as relative4, resolve as resolve3 } from "path";
5
5
 
6
6
  // src/adapter/bun.ts
7
7
  import { existsSync as existsSync6, rmSync as rmSync2, writeFileSync as writeFileSync6 } from "fs";
8
- import { join as join7, resolve as resolve3 } from "path";
8
+ import { dirname as dirname2, join as join7, resolve } from "path";
9
+ import { fileURLToPath } from "url";
9
10
 
10
11
  // src/build/client.ts
11
12
  import { existsSync as existsSync4, mkdirSync as mkdirSync3, writeFileSync as writeFileSync3 } from "fs";
@@ -1373,9 +1374,83 @@ import { existsSync as existsSync2, mkdirSync, readFileSync as readFileSync2, wr
1373
1374
  import { join as join2 } from "path";
1374
1375
 
1375
1376
  // src/render/shell.ts
1377
+ function extractTitle(meta) {
1378
+ if (!meta) {
1379
+ return;
1380
+ }
1381
+ for (const entry of meta) {
1382
+ if ("title" in entry) {
1383
+ return entry.title;
1384
+ }
1385
+ }
1386
+ return;
1387
+ }
1388
+ function isMetaTag(entry) {
1389
+ return !(("title" in entry) || ("charSet" in entry) || ("script:ld+json" in entry) || ("tagName" in entry));
1390
+ }
1376
1391
  function escapeHtml(str) {
1377
1392
  return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#039;");
1378
1393
  }
1394
+ function safeJson(value) {
1395
+ return JSON.stringify(value).replace(/</g, "\\u003c").replace(/>/g, "\\u003e").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
1396
+ }
1397
+ function renderAttrs(obj) {
1398
+ return Object.entries(obj).filter(([, v]) => v !== undefined).map(([k, v]) => `${k}="${escapeHtml(String(v))}"`).join(" ");
1399
+ }
1400
+ function buildMetaParts(meta) {
1401
+ const parts = [];
1402
+ const title = extractTitle(meta);
1403
+ if (title) {
1404
+ parts.push(`<title>${escapeHtml(title)}</title>`);
1405
+ }
1406
+ for (const m of meta) {
1407
+ if (isMetaTag(m)) {
1408
+ parts.push(`<meta ${renderAttrs(m)} />`);
1409
+ }
1410
+ if ("script:ld+json" in m) {
1411
+ parts.push(`<script type="application/ld+json">${safeJson(m["script:ld+json"])}</script>`);
1412
+ }
1413
+ }
1414
+ return parts;
1415
+ }
1416
+ function buildLinkParts(links) {
1417
+ return links.map((link) => `<link ${renderAttrs(link)} />`);
1418
+ }
1419
+ function buildScriptParts(scripts) {
1420
+ return scripts.map((script) => {
1421
+ const { children, ...rest } = script;
1422
+ const attrs = renderAttrs(rest);
1423
+ if (children) {
1424
+ return `<script ${attrs}>${children}</script>`;
1425
+ }
1426
+ return `<script ${attrs}></script>`;
1427
+ });
1428
+ }
1429
+ function buildStyleParts(styles) {
1430
+ return styles.map((style) => {
1431
+ const typeAttr = style.type ? ` type="${escapeHtml(style.type)}"` : "";
1432
+ return `<style${typeAttr}>${style.children}</style>`;
1433
+ });
1434
+ }
1435
+ function buildHeadInjection(headData) {
1436
+ const parts = [];
1437
+ if (headData?.meta) {
1438
+ parts.push(...buildMetaParts(headData.meta));
1439
+ }
1440
+ if (headData?.links) {
1441
+ parts.push(...buildLinkParts(headData.links));
1442
+ }
1443
+ if (headData?.scripts) {
1444
+ parts.push(...buildScriptParts(headData.scripts));
1445
+ }
1446
+ if (headData?.styles) {
1447
+ parts.push(...buildStyleParts(headData.styles));
1448
+ }
1449
+ return parts.length > 0 ? `
1450
+ ${parts.join(`
1451
+ `)}
1452
+ ` : "";
1453
+ }
1379
1454
  var THEME_INIT_SCRIPT = `<script>try{var __t=localStorage.getItem("furin-theme");` + `document.documentElement.classList.add(__t==="light"?"light":"dark")}` + `catch(e){document.documentElement.classList.add("dark")}</script>`;
1380
1455
  function generateIndexHtml() {
1381
1456
  return `<!DOCTYPE html>
@@ -1481,28 +1556,33 @@ ${entries.join(`;
1481
1556
  }
1482
1557
 
1483
1558
  // src/build/hydrate.ts
1484
- function generateHydrateEntry(routes, rootLayout) {
1559
+ function generateHydrateEntry(routes, rootLayout, basePath) {
1485
1560
  const routeEntries = [];
1486
1561
  for (const route of routes) {
1487
1562
  const resolvedPage = route.path.replace(/\\/g, "/");
1488
1563
  const regexPattern = route.pattern.replace(/:[^/]+/g, "([^/]+)").replace(/\*/g, "(.*)");
1489
1564
  routeEntries.push(` { pattern: "${route.pattern}", regex: new RegExp("^${regexPattern}$"), load: () => import("${resolvedPage}") }`);
1490
1565
  }
1566
+ const basePathLiteral = JSON.stringify(basePath);
1567
+ const pathnameExpr = basePath ? `(() => { const p = window.location.pathname; const b = ${basePathLiteral}; return (p.startsWith(b) && (p.length === b.length || p[b.length] === "/")) ? p.slice(b.length) || "/" : p; })()` : "window.location.pathname";
1568
+ const logEndpoint = basePath ? `${JSON.stringify(basePath)} + "/_furin/ingest"` : `"/_furin/ingest"`;
1569
+ const basePathProp = basePath ? `
1570
+ basePath: ${basePathLiteral},` : "";
1491
1571
  return `import { hydrateRoot, createRoot } from "react-dom/client";
1492
1572
  import { createElement } from "react";
1493
1573
  import { initLogger, log } from "evlog";
1494
- import { createBrowserLogDrain } from "evlog/browser";
1574
+ import { createHttpLogDrain } from "evlog/http";
1495
1575
  import { RouterProvider } from "@teyik0/furin/link";
1496
1576
  import { route as root } from "${rootLayout.replace(/\\/g, "/")}";
1497
1577
 
1498
- initLogger({ drain: createBrowserLogDrain({ drain: { endpoint: "/_furin/ingest" } }) });
1578
+ initLogger({ drain: createHttpLogDrain({ drain: { endpoint: ${logEndpoint} } }) });
1499
1579
 
1500
1580
  const routes = [
1501
1581
  ${routeEntries.join(`,
1502
1582
  `)}
1503
1583
  ];
1504
1584
 
1505
- const pathname = window.location.pathname;
1585
+ const pathname = ${pathnameExpr};
1506
1586
  const _match = routes.find((r) => r.regex.test(pathname));
1507
1587
 
1508
1588
  // Eagerly load only the current page module for initial hydration.
@@ -1522,7 +1602,7 @@ const _match = routes.find((r) => r.regex.test(pathname));
1522
1602
  routes,
1523
1603
  root,
1524
1604
  initialMatch: match,
1525
- initialData: loaderData,
1605
+ initialData: loaderData,${basePathProp}
1526
1606
  } as any);
1527
1607
 
1528
1608
  if (import.meta.hot) {
@@ -1547,14 +1627,16 @@ const _match = routes.find((r) => r.regex.test(pathname));
1547
1627
  } else {
1548
1628
  log.error({ action: "hydrate_no_match", pathname });
1549
1629
  }
1550
- })();
1630
+ })().catch((err: unknown) => {
1631
+ log.error({ action: "hydrate_failed", pathname, error: String(err) });
1632
+ });
1551
1633
  `;
1552
1634
  }
1553
- function writeDevFiles(routes, { outDir, rootLayout }, projectRoot) {
1635
+ function writeDevFiles(routes, { outDir, rootLayout, basePath }, projectRoot) {
1554
1636
  if (!existsSync2(outDir)) {
1555
1637
  mkdirSync(outDir, { recursive: true });
1556
1638
  }
1557
- const hydrateCode = generateHydrateEntry(routes, rootLayout);
1639
+ const hydrateCode = generateHydrateEntry(routes, rootLayout, basePath);
1558
1640
  const hydratePath = join2(outDir, "_hydrate.tsx");
1559
1641
  const existingHydrate = existsSync2(hydratePath) ? readFileSync2(hydratePath, "utf8") : "";
1560
1642
  if (hydrateCode !== existingHydrate) {
@@ -1572,9 +1654,9 @@ function writeDevFiles(routes, { outDir, rootLayout }, projectRoot) {
1572
1654
 
1573
1655
  // src/build/shared.ts
1574
1656
  import { cpSync, existsSync as existsSync3, mkdirSync as mkdirSync2, readdirSync, rmSync } from "fs";
1575
- import { join as join3, relative, resolve } from "path";
1576
- var CLIENT_MODULE_PATH = resolve(import.meta.dir, "../client.ts").replace(/\\/g, "/");
1577
- var LINK_MODULE_PATH = resolve(import.meta.dir, "../link.tsx").replace(/\\/g, "/");
1657
+ import { join as join3, relative } from "path";
1658
+ var CLIENT_MODULE_PATH = new URL(import.meta.resolve("@teyik0/furin/client")).pathname;
1659
+ var LINK_MODULE_PATH = new URL(import.meta.resolve("@teyik0/furin/link")).pathname;
1578
1660
  function ensureDir(path) {
1579
1661
  if (!existsSync3(path)) {
1580
1662
  mkdirSync2(path, { recursive: true });
@@ -1628,7 +1710,7 @@ function buildTargetManifest(rootDir, buildRoot, target, serverEntry) {
1628
1710
  // src/build/client.ts
1629
1711
  var TS_FILE_FILTER = /\.(tsx|ts)$/;
1630
1712
  var REACT_IMPORT_RE = /import\s+React\b/;
1631
- async function buildClient(routes, { outDir, rootLayout, plugins }) {
1713
+ async function buildClient(routes, { outDir, rootLayout, plugins, publicPath, basePath }) {
1632
1714
  const clientDir = join4(outDir, "client");
1633
1715
  if (!existsSync4(outDir)) {
1634
1716
  mkdirSync3(outDir, { recursive: true });
@@ -1636,7 +1718,7 @@ async function buildClient(routes, { outDir, rootLayout, plugins }) {
1636
1718
  if (!existsSync4(clientDir)) {
1637
1719
  mkdirSync3(clientDir, { recursive: true });
1638
1720
  }
1639
- const hydrateCode = generateHydrateEntry(routes, rootLayout);
1721
+ const hydrateCode = generateHydrateEntry(routes, rootLayout, basePath);
1640
1722
  const hydratePath = join4(outDir, "_hydrate.tsx");
1641
1723
  writeFileSync3(hydratePath, hydrateCode);
1642
1724
  console.log("[furin] Building production client bundle\u2026");
@@ -1676,7 +1758,11 @@ ${transformed}`;
1676
1758
  splitting: true,
1677
1759
  minify: true,
1678
1760
  sourcemap: "linked",
1679
- publicPath: "/_client/",
1761
+ naming: {
1762
+ entry: "[dir]/[name]-[hash].[ext]",
1763
+ chunk: "[name]-[hash].[ext]"
1764
+ },
1765
+ publicPath,
1680
1766
  plugins: plugins ? [...plugins, transformPlugin] : [transformPlugin],
1681
1767
  alias: {
1682
1768
  "@teyik0/furin/client": CLIENT_MODULE_PATH,
@@ -1695,8 +1781,14 @@ ${transformed}`;
1695
1781
  if (!entryOutput) {
1696
1782
  throw new Error("[furin] client build did not emit entry chunk");
1697
1783
  }
1698
- const entryChunk = `/_client/${basename(entryOutput.path)}`;
1699
- const cssChunks = cssOutputs.map((o) => `/_client/${basename(o.path)}`);
1784
+ let publicPrefix;
1785
+ if (publicPath === "") {
1786
+ publicPrefix = "";
1787
+ } else {
1788
+ publicPrefix = publicPath.endsWith("/") ? publicPath : `${publicPath}/`;
1789
+ }
1790
+ const entryChunk = `${publicPrefix}${basename(entryOutput.path)}`;
1791
+ const cssChunks = cssOutputs.map((o) => `${publicPrefix}${basename(o.path)}`);
1700
1792
  console.log("[furin] Production client build complete");
1701
1793
  return { entryChunk, cssChunks };
1702
1794
  }
@@ -1706,9 +1798,10 @@ import { existsSync as existsSync5, writeFileSync as writeFileSync4 } from "fs";
1706
1798
  import { join as join5, relative as relative2 } from "path";
1707
1799
 
1708
1800
  // src/build/entry-template.ts
1709
- import { resolve as resolve2 } from "path";
1710
- var INTERNAL_MODULE_PATH = resolve2(import.meta.dir, "../internal.ts").replace(/\\/g, "/");
1711
- var RUNTIME_ENV_MODULE_PATH = resolve2(import.meta.dir, "../runtime-env.ts").replace(/\\/g, "/");
1801
+ import { dirname } from "path";
1802
+ var _pkgSrcDir = dirname(new URL(import.meta.resolve("@teyik0/furin")).pathname);
1803
+ var INTERNAL_MODULE_PATH = `${_pkgSrcDir}/internal.ts`;
1804
+ var RUNTIME_ENV_MODULE_PATH = `${_pkgSrcDir}/runtime-env.ts`;
1712
1805
  function buildEntrySource(options) {
1713
1806
  const { buildId, headerComment, rootPath, routes, serverEntry } = options;
1714
1807
  let { extraImports, extraContext } = options;
@@ -1840,13 +1933,14 @@ function generateServerRoutesEntry(options) {
1840
1933
  }
1841
1934
 
1842
1935
  // src/adapter/bun.ts
1936
+ var _pkgSrcDir2 = dirname2(fileURLToPath(import.meta.resolve("@teyik0/furin")));
1843
1937
  var BUILD_ID_INPUT_PATHS = [
1844
- resolve3(import.meta.dir, "../build/compile-entry.ts"),
1845
- resolve3(import.meta.dir, "../build/entry-template.ts"),
1846
- resolve3(import.meta.dir, "../build/server-routes-entry.ts"),
1847
- resolve3(import.meta.dir, "../render/index.ts"),
1848
- resolve3(import.meta.dir, "../render/shell.ts"),
1849
- resolve3(import.meta.dir, "../router.ts")
1938
+ `${_pkgSrcDir2}/build/compile-entry.ts`,
1939
+ `${_pkgSrcDir2}/build/entry-template.ts`,
1940
+ `${_pkgSrcDir2}/build/server-routes-entry.ts`,
1941
+ `${_pkgSrcDir2}/render/index.ts`,
1942
+ `${_pkgSrcDir2}/render/shell.ts`,
1943
+ `${_pkgSrcDir2}/router.ts`
1850
1944
  ];
1851
1945
  async function createBuildFingerprint(entryChunk, cssChunks, routes, rootPath, serverEntry) {
1852
1946
  const fingerprintPaths = new Set([rootPath, ...routes.map((route) => route.path)]);
@@ -1873,13 +1967,15 @@ async function buildBunTarget(routes, rootDir, buildRoot, rootPath, serverEntry,
1873
1967
  }
1874
1968
  const target = "bun";
1875
1969
  const targetManifest = buildTargetManifest(rootDir, buildRoot, target, serverEntry);
1876
- const targetDir = resolve3(rootDir, targetManifest.targetDir);
1970
+ const targetDir = resolve(rootDir, targetManifest.targetDir);
1877
1971
  rmSync2(targetDir, { force: true, recursive: true });
1878
1972
  ensureDir(targetDir);
1879
1973
  const { entryChunk, cssChunks } = await buildClient(routes, {
1880
1974
  outDir: targetDir,
1881
1975
  rootLayout: rootPath,
1882
- plugins: options.plugins
1976
+ plugins: options.plugins,
1977
+ publicPath: "/_client/",
1978
+ basePath: ""
1883
1979
  });
1884
1980
  const buildFingerprint = await createBuildFingerprint(entryChunk, cssChunks, routes, rootPath, serverEntry);
1885
1981
  const buildId = Bun.hash(buildFingerprint).toString(16).slice(0, 12);
@@ -1909,8 +2005,18 @@ async function buildBunTarget(routes, rootDir, buildRoot, rootPath, serverEntry,
1909
2005
  compile: { outfile },
1910
2006
  minify: true,
1911
2007
  sourcemap: "linked",
2008
+ define: { "process.env.NODE_ENV": JSON.stringify("production") },
1912
2009
  plugins: options.plugins
1913
2010
  });
2011
+ if (process.platform === "darwin") {
2012
+ Bun.spawnSync(["codesign", "--remove-signature", outfile]);
2013
+ const sign = Bun.spawnSync(["codesign", "-f", "-s", "-", outfile]);
2014
+ if (sign.exitCode !== 0) {
2015
+ console.warn(`[furin] Warning: codesign failed (exit ${sign.exitCode}). ` + `The binary may be killed by Gatekeeper on macOS. Run manually:
2016
+ ` + ` codesign --remove-signature ${outfile}
2017
+ ` + ` codesign -f -s - ${outfile}`);
2018
+ }
2019
+ }
1914
2020
  console.log(`[furin] Server binary: ${outfile}`);
1915
2021
  targetManifest.serverPath = toPosixPath(join7(targetManifest.targetDir, "server"));
1916
2022
  if (options.compile === "embed") {
@@ -1948,9 +2054,464 @@ async function buildBunTarget(routes, rootDir, buildRoot, rootPath, serverEntry,
1948
2054
  return targetManifest;
1949
2055
  }
1950
2056
 
2057
+ // src/adapter/static.ts
2058
+ import { cpSync as cpSync2, existsSync as existsSync7, rmSync as rmSync3, writeFileSync as writeFileSync7 } from "fs";
2059
+ import { dirname as dirname3, isAbsolute, join as join8, relative as relative3, resolve as resolve2, sep } from "path";
2060
+
2061
+ // src/render/assemble.ts
2062
+ function resolvePath(pattern, params) {
2063
+ let path = pattern;
2064
+ for (const [key, val] of Object.entries(params ?? {})) {
2065
+ path = path.replace(key === "*" ? "*" : `:${key}`, val);
2066
+ }
2067
+ return path;
2068
+ }
2069
+ async function streamToString(stream) {
2070
+ const reader = stream.getReader();
2071
+ const decoder = new TextDecoder;
2072
+ let html = "";
2073
+ for (;; ) {
2074
+ const { done, value } = await reader.read();
2075
+ if (done) {
2076
+ break;
2077
+ }
2078
+ html += decoder.decode(value, { stream: true });
2079
+ }
2080
+ html += decoder.decode();
2081
+ return html;
2082
+ }
2083
+ function splitTemplate(template) {
2084
+ const [headPre, afterHead = ""] = template.split("<!--ssr-head-->");
2085
+ const [bodyPre, bodyPost = ""] = afterHead.split("<!--ssr-outlet-->");
2086
+ return { headPre, bodyPre, bodyPost };
2087
+ }
2088
+ function assembleHTML(template, headData, reactHtml, data) {
2089
+ const { headPre, bodyPre, bodyPost } = splitTemplate(template);
2090
+ const dataScript = data ? `<script id="__FURIN_DATA__" type="application/json">${safeJson(data)}</script>` : "";
2091
+ let injectedBodyPost = bodyPost;
2092
+ if (dataScript) {
2093
+ injectedBodyPost = bodyPost.includes("</body>") ? bodyPost.replace("</body>", `${dataScript}</body>`) : bodyPost + dataScript;
2094
+ }
2095
+ return headPre + headData + bodyPre + reactHtml + injectedBodyPost;
2096
+ }
2097
+
2098
+ // src/render/index.ts
2099
+ import { createElement as createElement2 } from "react";
2100
+ import { renderToReadableStream } from "react-dom/server";
2101
+
2102
+ // src/link.tsx
2103
+ import {
2104
+ createContext,
2105
+ createElement,
2106
+ useCallback,
2107
+ useContext,
2108
+ useEffect,
2109
+ useRef,
2110
+ useState
2111
+ } from "react";
2112
+ var RouterContext = createContext(null);
2113
+
2114
+ // src/render/cache.ts
2115
+ import { AsyncLocalStorage } from "async_hooks";
2116
+ var MAX_SSG_CACHE_SIZE = 1000;
2117
+ var isrCache = new Map;
2118
+ var ssgCache = new Map;
2119
+ function evictOldest(map, maxSize) {
2120
+ if (map.size > maxSize) {
2121
+ const oldest = map.keys().next().value;
2122
+ if (oldest !== undefined) {
2123
+ map.delete(oldest);
2124
+ }
2125
+ }
2126
+ }
2127
+ function getSSGCache(key) {
2128
+ const entry = ssgCache.get(key);
2129
+ if (entry !== undefined) {
2130
+ ssgCache.delete(key);
2131
+ ssgCache.set(key, entry);
2132
+ }
2133
+ return entry;
2134
+ }
2135
+ function setSSGCache(key, entry) {
2136
+ ssgCache.delete(key);
2137
+ ssgCache.set(key, entry);
2138
+ evictOldest(ssgCache, MAX_SSG_CACHE_SIZE);
2139
+ }
2140
+ var _requestInvalidationScope = new AsyncLocalStorage;
2141
+ var _globalPendingInvalidations = new Set;
2142
+
2143
+ // src/render/element.tsx
2144
+ import { jsxDEV } from "react/jsx-dev-runtime";
2145
+ function buildElement(route, data, rootLayout) {
2146
+ const Component = route.page.component;
2147
+ let element = /* @__PURE__ */ jsxDEV(Component, {
2148
+ ...data
2149
+ }, undefined, false, undefined, this);
2150
+ for (let i = route.routeChain.length - 1;i >= 1; i--) {
2151
+ const routeEntry = route.routeChain[i];
2152
+ if (routeEntry?.layout) {
2153
+ const Layout = routeEntry.layout;
2154
+ element = /* @__PURE__ */ jsxDEV(Layout, {
2155
+ ...data,
2156
+ children: element
2157
+ }, undefined, false, undefined, this);
2158
+ }
2159
+ }
2160
+ if (rootLayout.layout) {
2161
+ const RootLayoutComponent = rootLayout.layout;
2162
+ element = /* @__PURE__ */ jsxDEV(RootLayoutComponent, {
2163
+ ...data,
2164
+ children: element
2165
+ }, undefined, false, undefined, this);
2166
+ }
2167
+ return element;
2168
+ }
2169
+
2170
+ // src/render/loaders.ts
2171
+ function createLoaderCtx(ctx, accumulatedParentPromise) {
2172
+ const cache = new Map;
2173
+ return new Proxy(ctx, {
2174
+ get(target, prop) {
2175
+ if (typeof prop !== "string") {
2176
+ return Reflect.get(target, prop);
2177
+ }
2178
+ if (prop === "then" || prop === "catch" || prop === "finally" || prop === "toJSON") {
2179
+ return Reflect.get(target, prop);
2180
+ }
2181
+ if (Object.hasOwn(target, prop)) {
2182
+ return target[prop];
2183
+ }
2184
+ let entry = cache.get(prop);
2185
+ if (!entry) {
2186
+ entry = accumulatedParentPromise.then((data) => data[prop]);
2187
+ cache.set(prop, entry);
2188
+ }
2189
+ return entry;
2190
+ }
2191
+ });
2192
+ }
2193
+ async function runLoaders(route, ctx, _rootLayout) {
2194
+ try {
2195
+ const ctxRecord = ctx;
2196
+ const loaderMap = new Map;
2197
+ let accumulatedParentPromise = Promise.resolve({});
2198
+ for (const r of route.routeChain) {
2199
+ const parentAccum = accumulatedParentPromise;
2200
+ if (r.loader) {
2201
+ const loaderCtx = createLoaderCtx(ctxRecord, parentAccum);
2202
+ const loaderPromise = Promise.resolve(r.loader(loaderCtx)).then((res) => res ?? {});
2203
+ loaderMap.set(r, loaderPromise);
2204
+ accumulatedParentPromise = Promise.all([parentAccum, loaderPromise]).then(([acc, own]) => ({
2205
+ ...acc,
2206
+ ...own
2207
+ }));
2208
+ accumulatedParentPromise.catch(() => {});
2209
+ }
2210
+ }
2211
+ const pageCtx = createLoaderCtx(ctxRecord, accumulatedParentPromise);
2212
+ const pagePromise = route.page?.loader ? Promise.resolve(route.page.loader(pageCtx)).then((r) => r ?? {}) : Promise.resolve({});
2213
+ const results = await Promise.all([...loaderMap.values(), pagePromise]);
2214
+ const data = Object.assign({}, ...results);
2215
+ const headers = {};
2216
+ Object.assign(headers, ctx.set.headers);
2217
+ return { type: "data", data, headers };
2218
+ } catch (err) {
2219
+ if (err instanceof Response) {
2220
+ return { type: "redirect", response: err };
2221
+ }
2222
+ throw err;
2223
+ }
2224
+ }
2225
+
2226
+ // src/render/template.ts
2227
+ import { readFileSync as readFileSync3 } from "fs";
2228
+ var _prodTemplatePath = null;
2229
+ var _prodTemplateContent = null;
2230
+ var _devTemplateCache = null;
2231
+ var DEV_TEMPLATE_TTL_MS = 1000;
2232
+ async function getDevTemplate(origin) {
2233
+ if (_devTemplateCache && Date.now() - _devTemplateCache.ts < DEV_TEMPLATE_TTL_MS) {
2234
+ return _devTemplateCache.html;
2235
+ }
2236
+ const r = await fetch(`${origin}/_bun_hmr_entry`);
2237
+ if (!r.ok) {
2238
+ throw new Error(`/_bun_hmr_entry returned ${r.status}`);
2239
+ }
2240
+ const html = await r.text();
2241
+ _devTemplateCache = { html, ts: Date.now() };
2242
+ return html;
2243
+ }
2244
+ function setProductionTemplateContent(content) {
2245
+ _prodTemplatePath = null;
2246
+ _prodTemplateContent = content;
2247
+ }
2248
+ function getProductionTemplate() {
2249
+ if (_prodTemplateContent !== null) {
2250
+ return _prodTemplateContent;
2251
+ }
2252
+ if (!_prodTemplatePath) {
2253
+ return null;
2254
+ }
2255
+ try {
2256
+ _prodTemplateContent = readFileSync3(_prodTemplatePath, "utf8");
2257
+ return _prodTemplateContent;
2258
+ } catch {
2259
+ return null;
2260
+ }
2261
+ }
2262
+ // src/runtime-env.ts
2263
+ var IS_DEV = true;
2264
+
2265
+ // src/render/index.ts
2266
+ async function prepareRender(route, ctx, root, basePath) {
2267
+ const loaderStart = Date.now();
2268
+ const loaderResult = await runLoaders(route, ctx, root.route);
2269
+ const loader_ms = Date.now() - loaderStart;
2270
+ if (loaderResult.type === "redirect") {
2271
+ return loaderResult.response;
2272
+ }
2273
+ const { data, headers } = loaderResult;
2274
+ const componentProps = {
2275
+ ...data,
2276
+ params: ctx.params,
2277
+ query: ctx.query,
2278
+ path: ctx.path
2279
+ };
2280
+ const headData = buildHeadInjection(route.page?.head?.(componentProps));
2281
+ const prodTemplate = getProductionTemplate();
2282
+ const template = prodTemplate ?? (IS_DEV ? await getDevTemplate(new URL(ctx.request.url).origin) : generateIndexHtml());
2283
+ let element = buildElement(route, componentProps, root.route);
2284
+ if (basePath !== undefined) {
2285
+ const ssrContext = {
2286
+ basePath,
2287
+ currentHref: ctx.path,
2288
+ navigate: () => Promise.resolve(),
2289
+ prefetch: () => {},
2290
+ invalidatePrefetch: () => {},
2291
+ refresh: () => Promise.resolve(),
2292
+ isNavigating: false,
2293
+ defaultPreload: "intent",
2294
+ defaultPreloadDelay: 50,
2295
+ defaultPreloadStaleTime: 30000
2296
+ };
2297
+ element = createElement2(RouterContext.Provider, { value: ssrContext }, element);
2298
+ }
2299
+ return { componentProps, element, headData, headers, loader_ms, template };
2300
+ }
2301
+ async function renderForPath(route, params, root, origin, basePath) {
2302
+ const resolvedPath = resolvePath(route.pattern, params);
2303
+ const ctx = {
2304
+ params,
2305
+ query: {},
2306
+ request: new Request(`${origin}${resolvedPath}`),
2307
+ headers: {},
2308
+ cookie: {},
2309
+ redirect: (url, status = 302) => new Response(null, { status, headers: { Location: url } }),
2310
+ set: { headers: {} },
2311
+ path: resolvedPath
2312
+ };
2313
+ const prepared = await prepareRender(route, ctx, root, basePath);
2314
+ if (prepared instanceof Response) {
2315
+ throw prepared;
2316
+ }
2317
+ const { componentProps, element, headData, headers, template } = prepared;
2318
+ const stream = await renderToReadableStream(element);
2319
+ await stream.allReady;
2320
+ const reactHtml = await streamToString(stream);
2321
+ return {
2322
+ html: assembleHTML(template, headData, reactHtml, componentProps),
2323
+ headers
2324
+ };
2325
+ }
2326
+ async function prerenderSSG(route, params, root, origin = "http://localhost:3000", basePath) {
2327
+ const resolvedPath = resolvePath(route.pattern, params);
2328
+ const cached = getSSGCache(resolvedPath);
2329
+ if (cached && !IS_DEV) {
2330
+ return cached;
2331
+ }
2332
+ let result;
2333
+ try {
2334
+ result = await renderForPath(route, params, root, origin, basePath);
2335
+ } catch (err) {
2336
+ if (err instanceof Response) {
2337
+ return err;
2338
+ }
2339
+ throw err;
2340
+ }
2341
+ const entry = { html: result.html, cachedAt: Date.now() };
2342
+ if (!IS_DEV) {
2343
+ setSSGCache(resolvedPath, entry);
2344
+ }
2345
+ return entry;
2346
+ }
2347
+ var pendingRevalidations = new Set;
2348
+
2349
+ // src/adapter/static.ts
2350
+ var STATIC_CONCURRENCY = 4;
2351
+ var DYNAMIC_SEGMENT_RE = /\/:[^/]+|\/\*/;
2352
+ var TRAILING_SLASHES_RE = /\/+$/;
2353
+ function pathToOutputFile(urlPath, outDir) {
2354
+ const normalizedOutDir = resolve2(outDir);
2355
+ if (urlPath === "/" || urlPath === "") {
2356
+ return join8(normalizedOutDir, "index.html");
2357
+ }
2358
+ const resolved = resolve2(normalizedOutDir, urlPath.slice(1), "index.html");
2359
+ if (!resolved.startsWith(`${normalizedOutDir}${sep}`)) {
2360
+ throw new Error(`[furin] static: unsafe output path detected for URL "${urlPath}" \u2014 path traversal via ".." is not allowed.`);
2361
+ }
2362
+ return resolved;
2363
+ }
2364
+ async function prerenderAndWrite(route, params, root, outDir, renderedRoutes, skippedRoutes, basePath) {
2365
+ const urlPath = resolvePath(route.pattern, params);
2366
+ const outputFile = pathToOutputFile(urlPath, outDir);
2367
+ try {
2368
+ const entry = await prerenderSSG(route, params, root, "http://localhost", basePath);
2369
+ if (entry instanceof Response) {
2370
+ console.warn(`[furin] static: route "${route.pattern}" loader returned a redirect \u2014 skipping.`);
2371
+ return;
2372
+ }
2373
+ ensureDir(dirname3(outputFile));
2374
+ writeFileSync7(outputFile, entry.html);
2375
+ renderedRoutes.push(urlPath);
2376
+ console.log(`[furin] static: ${urlPath} \u2192 ${toPosixPath(outputFile)}`);
2377
+ } catch (err) {
2378
+ console.error(`[furin] static: prerender failed for "${route.pattern}" (params: ${JSON.stringify(params)}):`, err);
2379
+ skippedRoutes.push(urlPath);
2380
+ }
2381
+ }
2382
+ function collectSsgRoutes(routes, onSSR, skippedRoutes) {
2383
+ const nonSsg = routes.filter((r) => r.mode !== "ssg");
2384
+ if (nonSsg.length === 0) {
2385
+ return routes;
2386
+ }
2387
+ if (onSSR === "error") {
2388
+ const list = nonSsg.map((r) => ` \u2022 ${r.pattern} (mode: ${r.mode})`).join(`
2389
+ `);
2390
+ throw new Error(`[furin] Cannot produce a static export: the following routes are not SSG and cannot be pre-rendered.
2391
+ ` + `Either change their mode to "ssg", remove them, or set \`onSSR: "skip"\` in your static config.
2392
+
2393
+ ` + `${list}`);
2394
+ }
2395
+ for (const r of nonSsg) {
2396
+ console.warn(`[furin] static: skipping route "${r.pattern}" (mode=${r.mode}) \u2014 not statically exportable.`);
2397
+ skippedRoutes.push(r.pattern);
2398
+ }
2399
+ return routes.filter((r) => r.mode === "ssg");
2400
+ }
2401
+ async function buildTaskQueue(ssgRoutes, root, outDir, renderedRoutes, skippedRoutes, basePath) {
2402
+ const tasks = [];
2403
+ for (const route of ssgRoutes) {
2404
+ if (!DYNAMIC_SEGMENT_RE.test(route.pattern)) {
2405
+ tasks.push(() => prerenderAndWrite(route, {}, root, outDir, renderedRoutes, skippedRoutes, basePath));
2406
+ continue;
2407
+ }
2408
+ if (!route.page.staticParams) {
2409
+ console.warn(`[furin] static: skipping dynamic route "${route.pattern}" \u2014 no staticParams() defined.`);
2410
+ skippedRoutes.push(route.pattern);
2411
+ continue;
2412
+ }
2413
+ try {
2414
+ const paramSets = await route.page.staticParams() ?? [];
2415
+ for (const params of paramSets) {
2416
+ tasks.push(() => prerenderAndWrite(route, params, root, outDir, renderedRoutes, skippedRoutes, basePath));
2417
+ }
2418
+ } catch (err) {
2419
+ console.error(`[furin] static: staticParams() failed for "${route.pattern}":`, err);
2420
+ skippedRoutes.push(route.pattern);
2421
+ }
2422
+ }
2423
+ return tasks;
2424
+ }
2425
+ async function runWithConcurrency(tasks, concurrency) {
2426
+ const queue = [...tasks];
2427
+ const workerCount = Math.min(concurrency, Math.max(queue.length, 1));
2428
+ await Promise.all(Array.from({ length: workerCount }, async () => {
2429
+ while (queue.length > 0) {
2430
+ await queue.shift()?.();
2431
+ }
2432
+ }));
2433
+ }
2434
+ async function buildStaticTarget(routes, rootDir, buildRoot, root, options) {
2435
+ const staticConfig = options.staticConfig ?? {};
2436
+ const rawBasePath = staticConfig.basePath ?? "";
2437
+ let basePath;
2438
+ if (rawBasePath === "/" || rawBasePath === "") {
2439
+ basePath = "";
2440
+ } else if (rawBasePath.endsWith("/")) {
2441
+ basePath = rawBasePath.replace(TRAILING_SLASHES_RE, "");
2442
+ } else {
2443
+ basePath = rawBasePath;
2444
+ }
2445
+ if (basePath && !basePath.startsWith("/")) {
2446
+ throw new Error(`[furin] static: basePath must start with "/" (received "${rawBasePath}"). ` + `Use "" for root deployments or "/sub-path" for sub-path deployments.`);
2447
+ }
2448
+ const outDir = resolve2(rootDir, staticConfig.outDir ?? "dist");
2449
+ const normalizedRoot = resolve2(rootDir);
2450
+ const normalizedBuildRoot = resolve2(buildRoot);
2451
+ if (outDir === normalizedRoot || outDir === normalizedBuildRoot || outDir === "/" || outDir === ".") {
2452
+ throw new Error(`[furin] static: outDir resolves to "${outDir}" which is unsafe to delete. ` + `Use a dedicated output directory such as "dist".`);
2453
+ }
2454
+ function isOutsideOutDir(target) {
2455
+ const rel = relative3(outDir, target);
2456
+ return rel.startsWith("..") || isAbsolute(rel);
2457
+ }
2458
+ if (!(isOutsideOutDir(normalizedRoot) && isOutsideOutDir(normalizedBuildRoot))) {
2459
+ throw new Error(`[furin] static: outDir resolves to "${outDir}" which is unsafe to delete. ` + `Use a dedicated output directory such as "dist".`);
2460
+ }
2461
+ const onSSR = staticConfig.onSSR ?? "error";
2462
+ const publicPath = basePath ? `${basePath}/_client/` : "/_client/";
2463
+ const renderedRoutes = [];
2464
+ const skippedRoutes = [];
2465
+ const ssgRoutes = collectSsgRoutes(routes, onSSR, skippedRoutes);
2466
+ rmSync3(outDir, { force: true, recursive: true });
2467
+ ensureDir(outDir);
2468
+ const targetDir = join8(buildRoot, "static");
2469
+ rmSync3(targetDir, { force: true, recursive: true });
2470
+ ensureDir(targetDir);
2471
+ const { entryChunk, cssChunks } = await buildClient(ssgRoutes, {
2472
+ outDir: targetDir,
2473
+ rootLayout: root.path,
2474
+ plugins: options.plugins,
2475
+ publicPath,
2476
+ basePath
2477
+ });
2478
+ const shellHtml = generateProdIndexHtml(entryChunk, cssChunks);
2479
+ setProductionTemplateContent(shellHtml);
2480
+ const publicSrcDir = join8(rootDir, "public");
2481
+ if (existsSync7(publicSrcDir)) {
2482
+ cpSync2(publicSrcDir, outDir, { recursive: true });
2483
+ }
2484
+ const clientSrcDir = join8(targetDir, "client");
2485
+ if (existsSync7(clientSrcDir)) {
2486
+ cpSync2(clientSrcDir, join8(outDir, "_client"), { recursive: true });
2487
+ }
2488
+ const tasks = await buildTaskQueue(ssgRoutes, root, outDir, renderedRoutes, skippedRoutes, basePath);
2489
+ const afterQueueCount = skippedRoutes.length;
2490
+ await runWithConcurrency(tasks, STATIC_CONCURRENCY);
2491
+ if (onSSR === "error" && skippedRoutes.length > afterQueueCount) {
2492
+ const failed = skippedRoutes.slice(afterQueueCount);
2493
+ const list = failed.map((r) => ` \u2022 ${r}`).join(`
2494
+ `);
2495
+ throw new Error(`[furin] static: ${failed.length} route(s) failed to pre-render:
2496
+ ${list}
2497
+ ` + `Set \`onSSR: "skip"\` in your static config to suppress this error.`);
2498
+ }
2499
+ writeFileSync7(join8(outDir, "404.html"), shellHtml);
2500
+ console.log("[furin] static: wrote 404.html (SPA shell fallback)");
2501
+ rmSync3(targetDir, { force: true, recursive: true });
2502
+ console.log(`[furin] static: export complete \u2192 ${toPosixPath(outDir)}` + ` (${renderedRoutes.length} rendered, ${skippedRoutes.length} skipped)`);
2503
+ return {
2504
+ basePath,
2505
+ generatedAt: new Date().toISOString(),
2506
+ outDir: toPosixPath(outDir),
2507
+ renderedRoutes,
2508
+ skippedRoutes
2509
+ };
2510
+ }
2511
+
1951
2512
  // src/config.ts
1952
2513
  import { t } from "elysia";
1953
- var BUILD_TARGETS = ["bun", "node", "vercel", "cloudflare"];
2514
+ var BUILD_TARGETS = ["bun", "node", "vercel", "cloudflare", "static"];
1954
2515
  var buildTargetSchema = t.Union(BUILD_TARGETS.map((v) => t.Literal(v)));
1955
2516
  var compileTargetSchema = t.Union([t.Literal("server"), t.Literal("embed")]);
1956
2517
  var configSchema = t.Object({
@@ -1960,13 +2521,18 @@ var configSchema = t.Object({
1960
2521
  targets: t.Optional(t.Array(buildTargetSchema)),
1961
2522
  bun: t.Optional(t.Object({
1962
2523
  compile: t.Optional(compileTargetSchema)
2524
+ })),
2525
+ static: t.Optional(t.Object({
2526
+ basePath: t.Optional(t.String()),
2527
+ outDir: t.Optional(t.String()),
2528
+ onSSR: t.Optional(t.Union([t.Literal("error"), t.Literal("skip")]))
1963
2529
  }))
1964
2530
  });
1965
2531
 
1966
2532
  // src/router.ts
1967
- import { existsSync as existsSync7 } from "fs";
2533
+ import { existsSync as existsSync8 } from "fs";
1968
2534
  import { readdir } from "fs/promises";
1969
- import { join as join8, parse } from "path";
2535
+ import { join as join9, parse } from "path";
1970
2536
  import { Elysia } from "elysia";
1971
2537
 
1972
2538
  // src/internal.ts
@@ -1975,24 +2541,6 @@ function getCompileContext() {
1975
2541
  return _compileCtx;
1976
2542
  }
1977
2543
 
1978
- // src/render/index.ts
1979
- import { renderToReadableStream } from "react-dom/server";
1980
-
1981
- // src/render/cache.ts
1982
- import { AsyncLocalStorage } from "async_hooks";
1983
- var isrCache = new Map;
1984
- var ssgCache = new Map;
1985
- var _requestInvalidationScope = new AsyncLocalStorage;
1986
- var _globalPendingInvalidations = new Set;
1987
-
1988
- // src/render/element.tsx
1989
- import { jsxDEV } from "react/jsx-dev-runtime";
1990
- // src/runtime-env.ts
1991
- var IS_DEV = true;
1992
-
1993
- // src/render/index.ts
1994
- var pendingRevalidations = new Set;
1995
-
1996
2544
  // src/utils.ts
1997
2545
  function isFurinPage(value) {
1998
2546
  return typeof value === "object" && value !== null && "__type" in value && value.__type === "FURIN_PAGE";
@@ -2043,7 +2591,7 @@ async function scanPages(pagesDir) {
2043
2591
  async function scanRootLayout(pagesDir) {
2044
2592
  const rootPath = `${pagesDir}/root.tsx`;
2045
2593
  const ctx = getCompileContext();
2046
- if (!(existsSync7(rootPath) || ctx?.modules[rootPath])) {
2594
+ if (!(existsSync8(rootPath) || ctx?.modules[rootPath])) {
2047
2595
  throw new Error("[furin] root.tsx: not found.");
2048
2596
  }
2049
2597
  const mod = ctx?.modules[rootPath] ?? await import(rootPath);
@@ -2116,7 +2664,7 @@ async function buildDevRoute(absolutePath, relativePath, root) {
2116
2664
  async function collectPageFilePaths(dir) {
2117
2665
  const files = [];
2118
2666
  for (const entry of await readdir(dir, { withFileTypes: true })) {
2119
- const absolutePath = join8(dir, entry.name);
2667
+ const absolutePath = join9(dir, entry.name);
2120
2668
  if (entry.isDirectory()) {
2121
2669
  files.push(...await collectPageFilePaths(absolutePath));
2122
2670
  continue;
@@ -2164,10 +2712,10 @@ function filePathToPattern(path) {
2164
2712
  }
2165
2713
 
2166
2714
  // src/build/scan-server.ts
2167
- import { readFileSync as readFileSync3 } from "fs";
2715
+ import { readFileSync as readFileSync4 } from "fs";
2168
2716
  import { parseSync as parseSync2 } from "oxc-parser";
2169
2717
  function scanFurinInstances(serverEntryPath) {
2170
- const code = readFileSync3(serverEntryPath, "utf8");
2718
+ const code = readFileSync4(serverEntryPath, "utf8");
2171
2719
  const { program, errors } = parseSync2(serverEntryPath, code);
2172
2720
  if (errors.length > 0) {
2173
2721
  return [];
@@ -2176,26 +2724,28 @@ function scanFurinInstances(serverEntryPath) {
2176
2724
  walkNode(program, results);
2177
2725
  return results;
2178
2726
  }
2179
- function walkNode(node, out) {
2180
- if (!node || typeof node !== "object")
2727
+ var SKIP_KEYS = new Set(["type", "start", "end"]);
2728
+ function checkFurinCall(node, out) {
2729
+ const callee = node.callee;
2730
+ const args = node.arguments;
2731
+ const isFurinCall = callee?.type === "Identifier" && callee.name === "furin";
2732
+ if (!(isFurinCall && Array.isArray(args)) || args.length === 0) {
2733
+ return;
2734
+ }
2735
+ const firstArg = args[0];
2736
+ if (firstArg?.type !== "ObjectExpression") {
2181
2737
  return;
2182
- if (node.type === "CallExpression") {
2183
- const callee = node.callee;
2184
- const args = node.arguments;
2185
- const isFurinCall = callee?.type === "Identifier" && callee.name === "furin";
2186
- if (isFurinCall && Array.isArray(args) && args.length > 0) {
2187
- const firstArg = args[0];
2188
- if (firstArg?.type === "ObjectExpression") {
2189
- const pagesDir = extractStringProperty(firstArg, "pagesDir");
2190
- if (pagesDir !== null) {
2191
- out.push(pagesDir);
2192
- }
2193
- }
2194
- }
2195
2738
  }
2739
+ const pagesDir = extractStringProperty(firstArg, "pagesDir");
2740
+ if (pagesDir !== null) {
2741
+ out.push(pagesDir);
2742
+ }
2743
+ }
2744
+ function walkChildren(node, out) {
2196
2745
  for (const key of Object.keys(node)) {
2197
- if (key === "type" || key === "start" || key === "end")
2746
+ if (SKIP_KEYS.has(key)) {
2198
2747
  continue;
2748
+ }
2199
2749
  const child = node[key];
2200
2750
  if (Array.isArray(child)) {
2201
2751
  for (const item of child) {
@@ -2208,18 +2758,30 @@ function walkNode(node, out) {
2208
2758
  }
2209
2759
  }
2210
2760
  }
2761
+ function walkNode(node, out) {
2762
+ if (!node || typeof node !== "object") {
2763
+ return;
2764
+ }
2765
+ if (node.type === "CallExpression") {
2766
+ checkFurinCall(node, out);
2767
+ }
2768
+ walkChildren(node, out);
2769
+ }
2211
2770
  function extractStringProperty(obj, propName) {
2212
2771
  const properties = obj.properties;
2213
- if (!Array.isArray(properties))
2772
+ if (!Array.isArray(properties)) {
2214
2773
  return null;
2774
+ }
2215
2775
  for (const prop of properties) {
2216
- if (prop.type !== "Property")
2776
+ if (prop.type !== "Property") {
2217
2777
  continue;
2778
+ }
2218
2779
  const key = prop.key;
2219
2780
  const value = prop.value;
2220
2781
  const keyMatches = key.type === "Identifier" && key.name === propName || key.type === "Literal" && key.value === propName;
2221
- if (!keyMatches)
2782
+ if (!keyMatches) {
2222
2783
  continue;
2784
+ }
2223
2785
  if (value?.type === "Literal" && typeof value.value === "string") {
2224
2786
  return value.value;
2225
2787
  }
@@ -2229,33 +2791,46 @@ function extractStringProperty(obj, propName) {
2229
2791
  }
2230
2792
 
2231
2793
  // src/build/index.ts
2232
- var IMPLEMENTED_TARGETS = ["bun"];
2794
+ var IMPLEMENTED_TARGETS = ["bun", "static"];
2233
2795
  var BUILD_OUTPUT_DIR = ".furin/build";
2234
2796
  function resolvePagesDirFromServer(serverEntry, rootDir) {
2235
- if (!serverEntry)
2797
+ if (!serverEntry) {
2236
2798
  return null;
2799
+ }
2237
2800
  const detected = scanFurinInstances(serverEntry);
2238
- if (detected.length === 0)
2801
+ if (detected.length === 0) {
2239
2802
  return null;
2240
- return resolve4(rootDir, detected[0]);
2803
+ }
2804
+ return resolve3(rootDir, detected[0]);
2241
2805
  }
2242
2806
  async function buildApp(options) {
2243
- const rootDir = resolve4(options.rootDir ?? process.cwd());
2244
- const buildRoot = join9(rootDir, BUILD_OUTPUT_DIR);
2807
+ const rootDir = resolve3(options.rootDir ?? process.cwd());
2808
+ const buildRoot = join10(rootDir, BUILD_OUTPUT_DIR);
2245
2809
  const serverEntry = (() => {
2810
+ if (options.target === "static") {
2811
+ return null;
2812
+ }
2246
2813
  if (options.serverEntry) {
2247
- const resolved = resolve4(rootDir, options.serverEntry);
2248
- if (existsSync8(resolved))
2814
+ const resolved = resolve3(rootDir, options.serverEntry);
2815
+ if (existsSync9(resolved)) {
2249
2816
  return resolved;
2817
+ }
2250
2818
  }
2251
- const serverEntry2 = resolve4(rootDir, "src/server.ts");
2252
- if (!existsSync8(serverEntry2)) {
2819
+ const entry = resolve3(rootDir, "src/server.ts");
2820
+ if (!existsSync9(entry)) {
2253
2821
  throw new Error("[furin] Entrypoint server.ts not found");
2254
2822
  }
2255
- return serverEntry2;
2823
+ return entry;
2256
2824
  })();
2825
+ for (const plugin of options.plugins ?? []) {
2826
+ try {
2827
+ Bun.plugin(plugin);
2828
+ } catch (err) {
2829
+ console.debug("[furin] Skipped build-only plugin at runtime:", err);
2830
+ }
2831
+ }
2257
2832
  const rawPagesDir = options.pagesDir ?? resolvePagesDirFromServer(serverEntry, rootDir) ?? "src/pages";
2258
- const pagesDir = resolve4(rootDir, rawPagesDir);
2833
+ const pagesDir = resolve3(rootDir, rawPagesDir);
2259
2834
  const requestedTargets = options.target === "all" ? [...IMPLEMENTED_TARGETS] : [options.target].map((target) => {
2260
2835
  if (!BUILD_TARGETS.includes(target)) {
2261
2836
  throw new Error(`[furin] Unsupported build target "${target}"`);
@@ -2268,9 +2843,9 @@ async function buildApp(options) {
2268
2843
  version: 1,
2269
2844
  generatedAt: new Date().toISOString(),
2270
2845
  rootDir: toPosixPath(rootDir),
2271
- pagesDir: toPosixPath(relative3(rootDir, pagesDir)),
2272
- rootPath: toPosixPath(relative3(rootDir, root.path)),
2273
- serverEntry: serverEntry ? toPosixPath(relative3(rootDir, serverEntry)) : null,
2846
+ pagesDir: toPosixPath(relative4(rootDir, pagesDir)),
2847
+ rootPath: toPosixPath(relative4(rootDir, root.path)),
2848
+ serverEntry: serverEntry ? toPosixPath(relative4(rootDir, serverEntry)) : null,
2274
2849
  routes: routes.map((route) => toBuildRouteManifestEntry(route, rootDir)),
2275
2850
  targets: {}
2276
2851
  };
@@ -2279,6 +2854,9 @@ async function buildApp(options) {
2279
2854
  case "bun":
2280
2855
  manifest.targets.bun = await buildBunTarget(routes, rootDir, buildRoot, root.path, serverEntry, options);
2281
2856
  break;
2857
+ case "static":
2858
+ manifest.targets.static = await buildStaticTarget(routes, rootDir, buildRoot, root, options);
2859
+ break;
2282
2860
  case "node":
2283
2861
  case "vercel":
2284
2862
  case "cloudflare":
@@ -2287,7 +2865,7 @@ async function buildApp(options) {
2287
2865
  throw new Error(`[furin] Unsupported build target "${target}"`);
2288
2866
  }
2289
2867
  }
2290
- writeFileSync7(join9(buildRoot, "manifest.json"), `${JSON.stringify(manifest, null, 2)}
2868
+ writeFileSync8(join10(buildRoot, "manifest.json"), `${JSON.stringify(manifest, null, 2)}
2291
2869
  `);
2292
2870
  return {
2293
2871
  manifest,