@teyik0/furin 0.1.0-alpha.7 → 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.
@@ -1,7 +1,7 @@
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 resolve2 } 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";
@@ -1374,9 +1374,83 @@ import { existsSync as existsSync2, mkdirSync, readFileSync as readFileSync2, wr
1374
1374
  import { join as join2 } from "path";
1375
1375
 
1376
1376
  // src/render/shell.ts
1377
+ function extractTitle(meta) {
1378
+ if (!meta) {
1379
+ return;
1380
+ }
1381
+ for (const entry of meta) {
1382
+ if ("title" in entry) {
1383
+ return entry.title;
1384
+ }
1385
+ }
1386
+ return;
1387
+ }
1388
+ function isMetaTag(entry) {
1389
+ return !(("title" in entry) || ("charSet" in entry) || ("script:ld+json" in entry) || ("tagName" in entry));
1390
+ }
1377
1391
  function escapeHtml(str) {
1378
1392
  return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#039;");
1379
1393
  }
1394
+ function safeJson(value) {
1395
+ return JSON.stringify(value).replace(/</g, "\\u003c").replace(/>/g, "\\u003e").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
1396
+ }
1397
+ function renderAttrs(obj) {
1398
+ return Object.entries(obj).filter(([, v]) => v !== undefined).map(([k, v]) => `${k}="${escapeHtml(String(v))}"`).join(" ");
1399
+ }
1400
+ function buildMetaParts(meta) {
1401
+ const parts = [];
1402
+ const title = extractTitle(meta);
1403
+ if (title) {
1404
+ parts.push(`<title>${escapeHtml(title)}</title>`);
1405
+ }
1406
+ for (const m of meta) {
1407
+ if (isMetaTag(m)) {
1408
+ parts.push(`<meta ${renderAttrs(m)} />`);
1409
+ }
1410
+ if ("script:ld+json" in m) {
1411
+ parts.push(`<script type="application/ld+json">${safeJson(m["script:ld+json"])}</script>`);
1412
+ }
1413
+ }
1414
+ return parts;
1415
+ }
1416
+ function buildLinkParts(links) {
1417
+ return links.map((link) => `<link ${renderAttrs(link)} />`);
1418
+ }
1419
+ function buildScriptParts(scripts) {
1420
+ return scripts.map((script) => {
1421
+ const { children, ...rest } = script;
1422
+ const attrs = renderAttrs(rest);
1423
+ if (children) {
1424
+ return `<script ${attrs}>${children}</script>`;
1425
+ }
1426
+ return `<script ${attrs}></script>`;
1427
+ });
1428
+ }
1429
+ function buildStyleParts(styles) {
1430
+ return styles.map((style) => {
1431
+ const typeAttr = style.type ? ` type="${escapeHtml(style.type)}"` : "";
1432
+ return `<style${typeAttr}>${style.children}</style>`;
1433
+ });
1434
+ }
1435
+ function buildHeadInjection(headData) {
1436
+ const parts = [];
1437
+ if (headData?.meta) {
1438
+ parts.push(...buildMetaParts(headData.meta));
1439
+ }
1440
+ if (headData?.links) {
1441
+ parts.push(...buildLinkParts(headData.links));
1442
+ }
1443
+ if (headData?.scripts) {
1444
+ parts.push(...buildScriptParts(headData.scripts));
1445
+ }
1446
+ if (headData?.styles) {
1447
+ parts.push(...buildStyleParts(headData.styles));
1448
+ }
1449
+ return parts.length > 0 ? `
1450
+ ${parts.join(`
1451
+ `)}
1452
+ ` : "";
1453
+ }
1380
1454
  var THEME_INIT_SCRIPT = `<script>try{var __t=localStorage.getItem("furin-theme");` + `document.documentElement.classList.add(__t==="light"?"light":"dark")}` + `catch(e){document.documentElement.classList.add("dark")}</script>`;
1381
1455
  function generateIndexHtml() {
1382
1456
  return `<!DOCTYPE html>
@@ -1482,28 +1556,33 @@ ${entries.join(`;
1482
1556
  }
1483
1557
 
1484
1558
  // src/build/hydrate.ts
1485
- function generateHydrateEntry(routes, rootLayout) {
1559
+ function generateHydrateEntry(routes, rootLayout, basePath) {
1486
1560
  const routeEntries = [];
1487
1561
  for (const route of routes) {
1488
1562
  const resolvedPage = route.path.replace(/\\/g, "/");
1489
1563
  const regexPattern = route.pattern.replace(/:[^/]+/g, "([^/]+)").replace(/\*/g, "(.*)");
1490
1564
  routeEntries.push(` { pattern: "${route.pattern}", regex: new RegExp("^${regexPattern}$"), load: () => import("${resolvedPage}") }`);
1491
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},` : "";
1492
1571
  return `import { hydrateRoot, createRoot } from "react-dom/client";
1493
1572
  import { createElement } from "react";
1494
1573
  import { initLogger, log } from "evlog";
1495
- import { createBrowserLogDrain } from "evlog/browser";
1574
+ import { createHttpLogDrain } from "evlog/http";
1496
1575
  import { RouterProvider } from "@teyik0/furin/link";
1497
1576
  import { route as root } from "${rootLayout.replace(/\\/g, "/")}";
1498
1577
 
1499
- initLogger({ drain: createBrowserLogDrain({ drain: { endpoint: "/_furin/ingest" } }) });
1578
+ initLogger({ drain: createHttpLogDrain({ drain: { endpoint: ${logEndpoint} } }) });
1500
1579
 
1501
1580
  const routes = [
1502
1581
  ${routeEntries.join(`,
1503
1582
  `)}
1504
1583
  ];
1505
1584
 
1506
- const pathname = window.location.pathname;
1585
+ const pathname = ${pathnameExpr};
1507
1586
  const _match = routes.find((r) => r.regex.test(pathname));
1508
1587
 
1509
1588
  // Eagerly load only the current page module for initial hydration.
@@ -1523,7 +1602,7 @@ const _match = routes.find((r) => r.regex.test(pathname));
1523
1602
  routes,
1524
1603
  root,
1525
1604
  initialMatch: match,
1526
- initialData: loaderData,
1605
+ initialData: loaderData,${basePathProp}
1527
1606
  } as any);
1528
1607
 
1529
1608
  if (import.meta.hot) {
@@ -1553,11 +1632,11 @@ const _match = routes.find((r) => r.regex.test(pathname));
1553
1632
  });
1554
1633
  `;
1555
1634
  }
1556
- function writeDevFiles(routes, { outDir, rootLayout }, projectRoot) {
1635
+ function writeDevFiles(routes, { outDir, rootLayout, basePath }, projectRoot) {
1557
1636
  if (!existsSync2(outDir)) {
1558
1637
  mkdirSync(outDir, { recursive: true });
1559
1638
  }
1560
- const hydrateCode = generateHydrateEntry(routes, rootLayout);
1639
+ const hydrateCode = generateHydrateEntry(routes, rootLayout, basePath);
1561
1640
  const hydratePath = join2(outDir, "_hydrate.tsx");
1562
1641
  const existingHydrate = existsSync2(hydratePath) ? readFileSync2(hydratePath, "utf8") : "";
1563
1642
  if (hydrateCode !== existingHydrate) {
@@ -1631,7 +1710,7 @@ function buildTargetManifest(rootDir, buildRoot, target, serverEntry) {
1631
1710
  // src/build/client.ts
1632
1711
  var TS_FILE_FILTER = /\.(tsx|ts)$/;
1633
1712
  var REACT_IMPORT_RE = /import\s+React\b/;
1634
- async function buildClient(routes, { outDir, rootLayout, plugins }) {
1713
+ async function buildClient(routes, { outDir, rootLayout, plugins, publicPath, basePath }) {
1635
1714
  const clientDir = join4(outDir, "client");
1636
1715
  if (!existsSync4(outDir)) {
1637
1716
  mkdirSync3(outDir, { recursive: true });
@@ -1639,7 +1718,7 @@ async function buildClient(routes, { outDir, rootLayout, plugins }) {
1639
1718
  if (!existsSync4(clientDir)) {
1640
1719
  mkdirSync3(clientDir, { recursive: true });
1641
1720
  }
1642
- const hydrateCode = generateHydrateEntry(routes, rootLayout);
1721
+ const hydrateCode = generateHydrateEntry(routes, rootLayout, basePath);
1643
1722
  const hydratePath = join4(outDir, "_hydrate.tsx");
1644
1723
  writeFileSync3(hydratePath, hydrateCode);
1645
1724
  console.log("[furin] Building production client bundle\u2026");
@@ -1683,7 +1762,7 @@ ${transformed}`;
1683
1762
  entry: "[dir]/[name]-[hash].[ext]",
1684
1763
  chunk: "[name]-[hash].[ext]"
1685
1764
  },
1686
- publicPath: "/_client/",
1765
+ publicPath,
1687
1766
  plugins: plugins ? [...plugins, transformPlugin] : [transformPlugin],
1688
1767
  alias: {
1689
1768
  "@teyik0/furin/client": CLIENT_MODULE_PATH,
@@ -1702,8 +1781,14 @@ ${transformed}`;
1702
1781
  if (!entryOutput) {
1703
1782
  throw new Error("[furin] client build did not emit entry chunk");
1704
1783
  }
1705
- const entryChunk = `/_client/${basename(entryOutput.path)}`;
1706
- 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)}`);
1707
1792
  console.log("[furin] Production client build complete");
1708
1793
  return { entryChunk, cssChunks };
1709
1794
  }
@@ -1888,7 +1973,9 @@ async function buildBunTarget(routes, rootDir, buildRoot, rootPath, serverEntry,
1888
1973
  const { entryChunk, cssChunks } = await buildClient(routes, {
1889
1974
  outDir: targetDir,
1890
1975
  rootLayout: rootPath,
1891
- plugins: options.plugins
1976
+ plugins: options.plugins,
1977
+ publicPath: "/_client/",
1978
+ basePath: ""
1892
1979
  });
1893
1980
  const buildFingerprint = await createBuildFingerprint(entryChunk, cssChunks, routes, rootPath, serverEntry);
1894
1981
  const buildId = Bun.hash(buildFingerprint).toString(16).slice(0, 12);
@@ -1918,8 +2005,18 @@ async function buildBunTarget(routes, rootDir, buildRoot, rootPath, serverEntry,
1918
2005
  compile: { outfile },
1919
2006
  minify: true,
1920
2007
  sourcemap: "linked",
2008
+ define: { "process.env.NODE_ENV": JSON.stringify("production") },
1921
2009
  plugins: options.plugins
1922
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
+ }
1923
2020
  console.log(`[furin] Server binary: ${outfile}`);
1924
2021
  targetManifest.serverPath = toPosixPath(join7(targetManifest.targetDir, "server"));
1925
2022
  if (options.compile === "embed") {
@@ -1957,9 +2054,464 @@ async function buildBunTarget(routes, rootDir, buildRoot, rootPath, serverEntry,
1957
2054
  return targetManifest;
1958
2055
  }
1959
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
+
1960
2512
  // src/config.ts
1961
2513
  import { t } from "elysia";
1962
- var BUILD_TARGETS = ["bun", "node", "vercel", "cloudflare"];
2514
+ var BUILD_TARGETS = ["bun", "node", "vercel", "cloudflare", "static"];
1963
2515
  var buildTargetSchema = t.Union(BUILD_TARGETS.map((v) => t.Literal(v)));
1964
2516
  var compileTargetSchema = t.Union([t.Literal("server"), t.Literal("embed")]);
1965
2517
  var configSchema = t.Object({
@@ -1969,13 +2521,18 @@ var configSchema = t.Object({
1969
2521
  targets: t.Optional(t.Array(buildTargetSchema)),
1970
2522
  bun: t.Optional(t.Object({
1971
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")]))
1972
2529
  }))
1973
2530
  });
1974
2531
 
1975
2532
  // src/router.ts
1976
- import { existsSync as existsSync7 } from "fs";
2533
+ import { existsSync as existsSync8 } from "fs";
1977
2534
  import { readdir } from "fs/promises";
1978
- import { join as join8, parse } from "path";
2535
+ import { join as join9, parse } from "path";
1979
2536
  import { Elysia } from "elysia";
1980
2537
 
1981
2538
  // src/internal.ts
@@ -1984,24 +2541,6 @@ function getCompileContext() {
1984
2541
  return _compileCtx;
1985
2542
  }
1986
2543
 
1987
- // src/render/index.ts
1988
- import { renderToReadableStream } from "react-dom/server";
1989
-
1990
- // src/render/cache.ts
1991
- import { AsyncLocalStorage } from "async_hooks";
1992
- var isrCache = new Map;
1993
- var ssgCache = new Map;
1994
- var _requestInvalidationScope = new AsyncLocalStorage;
1995
- var _globalPendingInvalidations = new Set;
1996
-
1997
- // src/render/element.tsx
1998
- import { jsxDEV } from "react/jsx-dev-runtime";
1999
- // src/runtime-env.ts
2000
- var IS_DEV = true;
2001
-
2002
- // src/render/index.ts
2003
- var pendingRevalidations = new Set;
2004
-
2005
2544
  // src/utils.ts
2006
2545
  function isFurinPage(value) {
2007
2546
  return typeof value === "object" && value !== null && "__type" in value && value.__type === "FURIN_PAGE";
@@ -2052,7 +2591,7 @@ async function scanPages(pagesDir) {
2052
2591
  async function scanRootLayout(pagesDir) {
2053
2592
  const rootPath = `${pagesDir}/root.tsx`;
2054
2593
  const ctx = getCompileContext();
2055
- if (!(existsSync7(rootPath) || ctx?.modules[rootPath])) {
2594
+ if (!(existsSync8(rootPath) || ctx?.modules[rootPath])) {
2056
2595
  throw new Error("[furin] root.tsx: not found.");
2057
2596
  }
2058
2597
  const mod = ctx?.modules[rootPath] ?? await import(rootPath);
@@ -2125,7 +2664,7 @@ async function buildDevRoute(absolutePath, relativePath, root) {
2125
2664
  async function collectPageFilePaths(dir) {
2126
2665
  const files = [];
2127
2666
  for (const entry of await readdir(dir, { withFileTypes: true })) {
2128
- const absolutePath = join8(dir, entry.name);
2667
+ const absolutePath = join9(dir, entry.name);
2129
2668
  if (entry.isDirectory()) {
2130
2669
  files.push(...await collectPageFilePaths(absolutePath));
2131
2670
  continue;
@@ -2173,10 +2712,10 @@ function filePathToPattern(path) {
2173
2712
  }
2174
2713
 
2175
2714
  // src/build/scan-server.ts
2176
- import { readFileSync as readFileSync3 } from "fs";
2715
+ import { readFileSync as readFileSync4 } from "fs";
2177
2716
  import { parseSync as parseSync2 } from "oxc-parser";
2178
2717
  function scanFurinInstances(serverEntryPath) {
2179
- const code = readFileSync3(serverEntryPath, "utf8");
2718
+ const code = readFileSync4(serverEntryPath, "utf8");
2180
2719
  const { program, errors } = parseSync2(serverEntryPath, code);
2181
2720
  if (errors.length > 0) {
2182
2721
  return [];
@@ -2185,26 +2724,28 @@ function scanFurinInstances(serverEntryPath) {
2185
2724
  walkNode(program, results);
2186
2725
  return results;
2187
2726
  }
2188
- function walkNode(node, out) {
2189
- 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) {
2190
2733
  return;
2191
- if (node.type === "CallExpression") {
2192
- const callee = node.callee;
2193
- const args = node.arguments;
2194
- const isFurinCall = callee?.type === "Identifier" && callee.name === "furin";
2195
- if (isFurinCall && Array.isArray(args) && args.length > 0) {
2196
- const firstArg = args[0];
2197
- if (firstArg?.type === "ObjectExpression") {
2198
- const pagesDir = extractStringProperty(firstArg, "pagesDir");
2199
- if (pagesDir !== null) {
2200
- out.push(pagesDir);
2201
- }
2202
- }
2203
- }
2204
2734
  }
2735
+ const firstArg = args[0];
2736
+ if (firstArg?.type !== "ObjectExpression") {
2737
+ return;
2738
+ }
2739
+ const pagesDir = extractStringProperty(firstArg, "pagesDir");
2740
+ if (pagesDir !== null) {
2741
+ out.push(pagesDir);
2742
+ }
2743
+ }
2744
+ function walkChildren(node, out) {
2205
2745
  for (const key of Object.keys(node)) {
2206
- if (key === "type" || key === "start" || key === "end")
2746
+ if (SKIP_KEYS.has(key)) {
2207
2747
  continue;
2748
+ }
2208
2749
  const child = node[key];
2209
2750
  if (Array.isArray(child)) {
2210
2751
  for (const item of child) {
@@ -2217,18 +2758,30 @@ function walkNode(node, out) {
2217
2758
  }
2218
2759
  }
2219
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
+ }
2220
2770
  function extractStringProperty(obj, propName) {
2221
2771
  const properties = obj.properties;
2222
- if (!Array.isArray(properties))
2772
+ if (!Array.isArray(properties)) {
2223
2773
  return null;
2774
+ }
2224
2775
  for (const prop of properties) {
2225
- if (prop.type !== "Property")
2776
+ if (prop.type !== "Property") {
2226
2777
  continue;
2778
+ }
2227
2779
  const key = prop.key;
2228
2780
  const value = prop.value;
2229
2781
  const keyMatches = key.type === "Identifier" && key.name === propName || key.type === "Literal" && key.value === propName;
2230
- if (!keyMatches)
2782
+ if (!keyMatches) {
2231
2783
  continue;
2784
+ }
2232
2785
  if (value?.type === "Literal" && typeof value.value === "string") {
2233
2786
  return value.value;
2234
2787
  }
@@ -2238,33 +2791,46 @@ function extractStringProperty(obj, propName) {
2238
2791
  }
2239
2792
 
2240
2793
  // src/build/index.ts
2241
- var IMPLEMENTED_TARGETS = ["bun"];
2794
+ var IMPLEMENTED_TARGETS = ["bun", "static"];
2242
2795
  var BUILD_OUTPUT_DIR = ".furin/build";
2243
2796
  function resolvePagesDirFromServer(serverEntry, rootDir) {
2244
- if (!serverEntry)
2797
+ if (!serverEntry) {
2245
2798
  return null;
2799
+ }
2246
2800
  const detected = scanFurinInstances(serverEntry);
2247
- if (detected.length === 0)
2801
+ if (detected.length === 0) {
2248
2802
  return null;
2249
- return resolve2(rootDir, detected[0]);
2803
+ }
2804
+ return resolve3(rootDir, detected[0]);
2250
2805
  }
2251
2806
  async function buildApp(options) {
2252
- const rootDir = resolve2(options.rootDir ?? process.cwd());
2253
- const buildRoot = join9(rootDir, BUILD_OUTPUT_DIR);
2807
+ const rootDir = resolve3(options.rootDir ?? process.cwd());
2808
+ const buildRoot = join10(rootDir, BUILD_OUTPUT_DIR);
2254
2809
  const serverEntry = (() => {
2810
+ if (options.target === "static") {
2811
+ return null;
2812
+ }
2255
2813
  if (options.serverEntry) {
2256
- const resolved = resolve2(rootDir, options.serverEntry);
2257
- if (existsSync8(resolved))
2814
+ const resolved = resolve3(rootDir, options.serverEntry);
2815
+ if (existsSync9(resolved)) {
2258
2816
  return resolved;
2817
+ }
2259
2818
  }
2260
- const serverEntry2 = resolve2(rootDir, "src/server.ts");
2261
- if (!existsSync8(serverEntry2)) {
2819
+ const entry = resolve3(rootDir, "src/server.ts");
2820
+ if (!existsSync9(entry)) {
2262
2821
  throw new Error("[furin] Entrypoint server.ts not found");
2263
2822
  }
2264
- return serverEntry2;
2823
+ return entry;
2265
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
+ }
2266
2832
  const rawPagesDir = options.pagesDir ?? resolvePagesDirFromServer(serverEntry, rootDir) ?? "src/pages";
2267
- const pagesDir = resolve2(rootDir, rawPagesDir);
2833
+ const pagesDir = resolve3(rootDir, rawPagesDir);
2268
2834
  const requestedTargets = options.target === "all" ? [...IMPLEMENTED_TARGETS] : [options.target].map((target) => {
2269
2835
  if (!BUILD_TARGETS.includes(target)) {
2270
2836
  throw new Error(`[furin] Unsupported build target "${target}"`);
@@ -2277,9 +2843,9 @@ async function buildApp(options) {
2277
2843
  version: 1,
2278
2844
  generatedAt: new Date().toISOString(),
2279
2845
  rootDir: toPosixPath(rootDir),
2280
- pagesDir: toPosixPath(relative3(rootDir, pagesDir)),
2281
- rootPath: toPosixPath(relative3(rootDir, root.path)),
2282
- 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,
2283
2849
  routes: routes.map((route) => toBuildRouteManifestEntry(route, rootDir)),
2284
2850
  targets: {}
2285
2851
  };
@@ -2288,6 +2854,9 @@ async function buildApp(options) {
2288
2854
  case "bun":
2289
2855
  manifest.targets.bun = await buildBunTarget(routes, rootDir, buildRoot, root.path, serverEntry, options);
2290
2856
  break;
2857
+ case "static":
2858
+ manifest.targets.static = await buildStaticTarget(routes, rootDir, buildRoot, root, options);
2859
+ break;
2291
2860
  case "node":
2292
2861
  case "vercel":
2293
2862
  case "cloudflare":
@@ -2296,7 +2865,7 @@ async function buildApp(options) {
2296
2865
  throw new Error(`[furin] Unsupported build target "${target}"`);
2297
2866
  }
2298
2867
  }
2299
- writeFileSync7(join9(buildRoot, "manifest.json"), `${JSON.stringify(manifest, null, 2)}
2868
+ writeFileSync8(join10(buildRoot, "manifest.json"), `${JSON.stringify(manifest, null, 2)}
2300
2869
  `);
2301
2870
  return {
2302
2871
  manifest,