@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
@@ -11,7 +11,7 @@ interface RenderResult {
11
11
  }
12
12
  export declare function renderToHTML(route: ResolvedRoute, ctx: Context, root: RootLayout): Promise<RenderResult>;
13
13
  export declare function renderToStream(route: ResolvedRoute, ctx: Context, root: RootLayout): Promise<ReadableStream | Response>;
14
- export declare function prerenderSSG(route: ResolvedRoute, params: Record<string, string>, root: RootLayout, origin?: string): Promise<SsgCacheEntry | Response>;
14
+ export declare function prerenderSSG(route: ResolvedRoute, params: Record<string, string>, root: RootLayout, origin?: string, basePath?: string): Promise<SsgCacheEntry | Response>;
15
15
  export declare function renderSSR(route: ResolvedRoute, ctx: Context, root: RootLayout): Promise<Response>;
16
16
  export declare function handleISR(route: ResolvedRoute, ctx: Context, root: RootLayout, buildId?: string): Promise<string | Response | undefined>;
17
17
  /**
@@ -9,4 +9,4 @@ export type LoaderResult = {
9
9
  type: "redirect";
10
10
  response: Response;
11
11
  };
12
- export declare function runLoaders(route: ResolvedRoute, ctx: Context, rootLayout: RuntimeRoute): Promise<LoaderResult>;
12
+ export declare function runLoaders(route: ResolvedRoute, ctx: Context, _rootLayout: RuntimeRoute): Promise<LoaderResult>;
package/dist/router.js CHANGED
@@ -145,8 +145,21 @@ function assembleHTML(template, headData, reactHtml, data) {
145
145
  }
146
146
 
147
147
  // src/render/index.ts
148
+ import { createElement as createElement2 } from "react";
148
149
  import { renderToReadableStream } from "react-dom/server";
149
150
 
151
+ // src/link.tsx
152
+ import {
153
+ createContext,
154
+ createElement,
155
+ useCallback,
156
+ useContext,
157
+ useEffect,
158
+ useRef,
159
+ useState
160
+ } from "react";
161
+ var RouterContext = createContext(null);
162
+
150
163
  // src/render/cache.ts
151
164
  import { AsyncLocalStorage } from "async_hooks";
152
165
  var MAX_ISR_CACHE_SIZE = 1000;
@@ -218,21 +231,48 @@ function buildElement(route, data, rootLayout) {
218
231
  }
219
232
 
220
233
  // src/render/loaders.ts
221
- async function runLoaders(route, ctx, rootLayout) {
234
+ function createLoaderCtx(ctx, accumulatedParentPromise) {
235
+ const cache = new Map;
236
+ return new Proxy(ctx, {
237
+ get(target, prop) {
238
+ if (typeof prop !== "string") {
239
+ return Reflect.get(target, prop);
240
+ }
241
+ if (prop === "then" || prop === "catch" || prop === "finally" || prop === "toJSON") {
242
+ return Reflect.get(target, prop);
243
+ }
244
+ if (Object.hasOwn(target, prop)) {
245
+ return target[prop];
246
+ }
247
+ let entry = cache.get(prop);
248
+ if (!entry) {
249
+ entry = accumulatedParentPromise.then((data) => data[prop]);
250
+ cache.set(prop, entry);
251
+ }
252
+ return entry;
253
+ }
254
+ });
255
+ }
256
+ async function runLoaders(route, ctx, _rootLayout) {
222
257
  try {
258
+ const ctxRecord = ctx;
223
259
  const loaderMap = new Map;
224
- const deps = (routeRef) => loaderMap.get(routeRef) ?? Promise.resolve({});
225
- const rootPromise = rootLayout.loader ? Promise.resolve(rootLayout.loader({ ...ctx }, deps)).then((r) => r ?? {}) : Promise.resolve({});
226
- loaderMap.set(rootLayout, rootPromise);
227
- const rootData = await rootPromise;
228
- const ctxWithRoot = { ...ctx, ...rootData };
229
- for (let i = 1;i < route.routeChain.length; i++) {
230
- const ancestor = route.routeChain[i];
231
- if (ancestor?.loader) {
232
- loaderMap.set(ancestor, Promise.resolve(ancestor.loader(ctxWithRoot, deps)).then((r) => r ?? {}));
260
+ let accumulatedParentPromise = Promise.resolve({});
261
+ for (const r of route.routeChain) {
262
+ const parentAccum = accumulatedParentPromise;
263
+ if (r.loader) {
264
+ const loaderCtx = createLoaderCtx(ctxRecord, parentAccum);
265
+ const loaderPromise = Promise.resolve(r.loader(loaderCtx)).then((res) => res ?? {});
266
+ loaderMap.set(r, loaderPromise);
267
+ accumulatedParentPromise = Promise.all([parentAccum, loaderPromise]).then(([acc, own]) => ({
268
+ ...acc,
269
+ ...own
270
+ }));
271
+ accumulatedParentPromise.catch(() => {});
233
272
  }
234
273
  }
235
- const pagePromise = route.page?.loader ? Promise.resolve(route.page.loader(ctxWithRoot, deps)).then((r) => r ?? {}) : Promise.resolve({});
274
+ const pageCtx = createLoaderCtx(ctxRecord, accumulatedParentPromise);
275
+ const pagePromise = route.page?.loader ? Promise.resolve(route.page.loader(pageCtx)).then((r) => r ?? {}) : Promise.resolve({});
236
276
  const results = await Promise.all([...loaderMap.values(), pagePromise]);
237
277
  const data = Object.assign({}, ...results);
238
278
  const headers = {};
@@ -278,7 +318,7 @@ function getProductionTemplate() {
278
318
  return null;
279
319
  }
280
320
  }
281
- // ../../node_modules/.bun/evlog@2.11.0+a1ab7c6fe65f988d/node_modules/evlog/dist/elysia/index.mjs
321
+ // ../../node_modules/.bun/evlog@2.13.0+449e6d239244fccb/node_modules/evlog/dist/elysia/index.mjs
282
322
  import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
283
323
  import { Elysia } from "elysia";
284
324
  var storage = new AsyncLocalStorage2;
@@ -294,7 +334,7 @@ function useLogger() {
294
334
  var IS_DEV = true;
295
335
 
296
336
  // src/render/index.ts
297
- async function prepareRender(route, ctx, root) {
337
+ async function prepareRender(route, ctx, root, basePath) {
298
338
  const loaderStart = Date.now();
299
339
  const loaderResult = await runLoaders(route, ctx, root.route);
300
340
  const loader_ms = Date.now() - loaderStart;
@@ -309,13 +349,29 @@ async function prepareRender(route, ctx, root) {
309
349
  path: ctx.path
310
350
  };
311
351
  const headData = buildHeadInjection(route.page?.head?.(componentProps));
312
- const template = IS_DEV ? await getDevTemplate(new URL(ctx.request.url).origin) : getProductionTemplate() ?? generateIndexHtml();
313
- const element = buildElement(route, componentProps, root.route);
352
+ const prodTemplate = getProductionTemplate();
353
+ const template = prodTemplate ?? (IS_DEV ? await getDevTemplate(new URL(ctx.request.url).origin) : generateIndexHtml());
354
+ let element = buildElement(route, componentProps, root.route);
355
+ if (basePath !== undefined) {
356
+ const ssrContext = {
357
+ basePath,
358
+ currentHref: ctx.path,
359
+ navigate: () => Promise.resolve(),
360
+ prefetch: () => {},
361
+ invalidatePrefetch: () => {},
362
+ refresh: () => Promise.resolve(),
363
+ isNavigating: false,
364
+ defaultPreload: "intent",
365
+ defaultPreloadDelay: 50,
366
+ defaultPreloadStaleTime: 30000
367
+ };
368
+ element = createElement2(RouterContext.Provider, { value: ssrContext }, element);
369
+ }
314
370
  return { componentProps, element, headData, headers, loader_ms, template };
315
371
  }
316
- async function renderForPath(route, params, root, origin) {
372
+ async function renderForPath(route, params, root, origin, basePath) {
317
373
  const resolvedPath = resolvePath(route.pattern, params);
318
- return await renderToHTML(route, {
374
+ const ctx = {
319
375
  params,
320
376
  query: {},
321
377
  request: new Request(`${origin}${resolvedPath}`),
@@ -324,10 +380,8 @@ async function renderForPath(route, params, root, origin) {
324
380
  redirect: (url, status = 302) => new Response(null, { status, headers: { Location: url } }),
325
381
  set: { headers: {} },
326
382
  path: resolvedPath
327
- }, root);
328
- }
329
- async function renderToHTML(route, ctx, root) {
330
- const prepared = await prepareRender(route, ctx, root);
383
+ };
384
+ const prepared = await prepareRender(route, ctx, root, basePath);
331
385
  if (prepared instanceof Response) {
332
386
  throw prepared;
333
387
  }
@@ -340,7 +394,7 @@ async function renderToHTML(route, ctx, root) {
340
394
  headers
341
395
  };
342
396
  }
343
- async function prerenderSSG(route, params, root, origin = "http://localhost:3000") {
397
+ async function prerenderSSG(route, params, root, origin = "http://localhost:3000", basePath) {
344
398
  const resolvedPath = resolvePath(route.pattern, params);
345
399
  const cached = getSSGCache(resolvedPath);
346
400
  if (cached && !IS_DEV) {
@@ -348,7 +402,7 @@ async function prerenderSSG(route, params, root, origin = "http://localhost:3000
348
402
  }
349
403
  let result;
350
404
  try {
351
- result = await renderForPath(route, params, root, origin);
405
+ result = await renderForPath(route, params, root, origin, basePath);
352
406
  } catch (err) {
353
407
  if (err instanceof Response) {
354
408
  return err;
@@ -646,11 +700,17 @@ function queryDefaultRedirectHook({ request, query, status, set }) {
646
700
  }
647
701
  async function handleDevRequest(route, ctx, root) {
648
702
  try {
703
+ let currentRoot = root;
704
+ const rootMod = await import(`${root.path}?furin-server&t=${Date.now()}`);
705
+ const rootExport = rootMod.route ?? rootMod.default;
706
+ if (rootExport && isFurinRoute(rootExport) && rootExport.layout) {
707
+ currentRoot = { path: root.path, route: rootExport };
708
+ }
649
709
  const pageMod = await import(`${route.path}?furin-server&t=${Date.now()}`);
650
710
  const page = pageMod.default;
651
711
  if (page && isFurinPage(page)) {
652
712
  const chain = collectRouteChainFromRoute(page._route);
653
- return renderSSR({ ...route, page, routeChain: chain }, ctx, root);
713
+ return renderSSR({ ...route, page, routeChain: chain }, ctx, currentRoot);
654
714
  }
655
715
  } catch (err) {
656
716
  console.error(`[furin] Dev page load error for ${route.path}:`, err);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@teyik0/furin",
3
- "version": "0.1.0-alpha.6",
3
+ "version": "0.1.0-alpha.8",
4
4
  "type": "module",
5
5
  "files": [
6
6
  "dist",
@@ -10,7 +10,7 @@
10
10
  "module": "./dist/furin.js",
11
11
  "types": "./src/furin.ts",
12
12
  "bin": {
13
- "furin": "./dist/cli/index.js"
13
+ "furin": "./src/cli/index.ts"
14
14
  },
15
15
  "exports": {
16
16
  ".": {
@@ -55,12 +55,13 @@
55
55
  "scripts": {
56
56
  "test": "bun test",
57
57
  "test:types": "tsc --noEmit",
58
- "build": "bun run build.ts"
58
+ "build": "bun run build.ts",
59
+ "fix": "ultracite fix"
59
60
  },
60
61
  "dependencies": {
61
- "@elysiajs/static": "^1.4.7",
62
+ "@elysiajs/static": "^1.4.9",
62
63
  "magic-string": "^0.30.21",
63
- "oxc-parser": "^0.123.0"
64
+ "oxc-parser": "^0.126.0"
64
65
  },
65
66
  "devDependencies": {
66
67
  "@types/react": "^19.2.14",
@@ -69,10 +70,8 @@
69
70
  },
70
71
  "peerDependencies": {
71
72
  "elysia": "^1.4.28",
72
- "evlog": "^2.11.0",
73
- "react": "^19.2.4",
74
- "react-dom": "^19.2.4",
75
- "typescript": ">=6.0.2",
76
- "@types/bun": ">=1.3.11"
73
+ "evlog": "^2.13.0",
74
+ "react": "^19.2.5",
75
+ "react-dom": "^19.2.5"
77
76
  }
78
77
  }
@@ -1,5 +1,6 @@
1
1
  import { existsSync, rmSync, writeFileSync } from "node:fs";
2
- import { join, resolve } from "node:path";
2
+ import { dirname, join, resolve } from "node:path";
3
+ import { fileURLToPath } from "node:url";
3
4
  import { buildClient } from "../build/client.ts";
4
5
  import { generateCompileEntry } from "../build/compile-entry.ts";
5
6
  import { generateServerRoutesEntry } from "../build/server-routes-entry.ts";
@@ -9,13 +10,16 @@ import type { BuildTarget } from "../config.ts";
9
10
  import { generateProdIndexHtml } from "../render/shell.ts";
10
11
  import type { ResolvedRoute } from "../router.ts";
11
12
 
13
+ // import.meta.resolve() runs at runtime (not inlined at bundle time), resolves
14
+ // through package exports, and is the Web-standard API.
15
+ const _pkgSrcDir = dirname(fileURLToPath(import.meta.resolve("@teyik0/furin")));
12
16
  const BUILD_ID_INPUT_PATHS = [
13
- resolve(import.meta.dir, "../build/compile-entry.ts"),
14
- resolve(import.meta.dir, "../build/entry-template.ts"),
15
- resolve(import.meta.dir, "../build/server-routes-entry.ts"),
16
- resolve(import.meta.dir, "../render/index.ts"),
17
- resolve(import.meta.dir, "../render/shell.ts"),
18
- resolve(import.meta.dir, "../router.ts"),
17
+ `${_pkgSrcDir}/build/compile-entry.ts`,
18
+ `${_pkgSrcDir}/build/entry-template.ts`,
19
+ `${_pkgSrcDir}/build/server-routes-entry.ts`,
20
+ `${_pkgSrcDir}/render/index.ts`,
21
+ `${_pkgSrcDir}/render/shell.ts`,
22
+ `${_pkgSrcDir}/router.ts`,
19
23
  ];
20
24
 
21
25
  async function createBuildFingerprint(
@@ -83,6 +87,8 @@ export async function buildBunTarget(
83
87
  outDir: targetDir,
84
88
  rootLayout: rootPath,
85
89
  plugins: options.plugins,
90
+ publicPath: "/_client/",
91
+ basePath: "",
86
92
  });
87
93
 
88
94
  const buildFingerprint = await createBuildFingerprint(
@@ -130,8 +136,26 @@ export async function buildBunTarget(
130
136
  compile: { outfile },
131
137
  minify: true,
132
138
  sourcemap: "linked",
139
+ define: { "process.env.NODE_ENV": JSON.stringify("production") },
133
140
  plugins: options.plugins,
134
141
  });
142
+
143
+ // macOS: Gatekeeper kills Bun-compiled binaries because Bun appends JS code to its own
144
+ // signed runtime, corrupting the original Oven signature. We must remove the corrupt
145
+ // signature first, then re-sign ad-hoc (-s -) so macOS accepts the binary.
146
+ if (process.platform === "darwin") {
147
+ Bun.spawnSync(["codesign", "--remove-signature", outfile]);
148
+ const sign = Bun.spawnSync(["codesign", "-f", "-s", "-", outfile]);
149
+ if (sign.exitCode !== 0) {
150
+ console.warn(
151
+ `[furin] Warning: codesign failed (exit ${sign.exitCode}). ` +
152
+ "The binary may be killed by Gatekeeper on macOS. Run manually:\n" +
153
+ ` codesign --remove-signature ${outfile}\n` +
154
+ ` codesign -f -s - ${outfile}`
155
+ );
156
+ }
157
+ }
158
+
135
159
  console.log(`[furin] Server binary: ${outfile}`);
136
160
 
137
161
  targetManifest.serverPath = toPosixPath(join(targetManifest.targetDir, "server"));
@@ -0,0 +1,337 @@
1
+ import { cpSync, existsSync, rmSync, writeFileSync } from "node:fs";
2
+ import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
3
+ import { buildClient } from "../build/client.ts";
4
+ import { ensureDir, toPosixPath } from "../build/shared.ts";
5
+ import type { BuildAppOptions, StaticTargetBuildManifest } from "../build/types.ts";
6
+ import type { StaticExportConfig } from "../config.ts";
7
+ import { resolvePath } from "../render/assemble.ts";
8
+ import { prerenderSSG } from "../render/index.ts";
9
+ import { generateProdIndexHtml } from "../render/shell.ts";
10
+ import { setProductionTemplateContent } from "../render/template.ts";
11
+ import type { ResolvedRoute, RootLayout } from "../router.ts";
12
+
13
+ /** Maximum concurrent pre-render calls (mirrors warmSSGCache). */
14
+ const STATIC_CONCURRENCY = 4;
15
+
16
+ /** Pattern that identifies a dynamic route segment. */
17
+ const DYNAMIC_SEGMENT_RE = /\/:[^/]+|\/\*/;
18
+
19
+ /** Strips all trailing slashes from a string. */
20
+ const TRAILING_SLASHES_RE = /\/+$/;
21
+
22
+ // ── Path helpers ──────────────────────────────────────────────────────────────
23
+
24
+ /**
25
+ * Converts a URL path to a filesystem output path.
26
+ * "/" → "outDir/index.html"
27
+ * "/docs/routing" → "outDir/docs/routing/index.html"
28
+ *
29
+ * The resolved path is validated to stay within `outDir` so that `..`
30
+ * segments injected via dynamic `staticParams()` values cannot escape
31
+ * the output directory.
32
+ */
33
+ function pathToOutputFile(urlPath: string, outDir: string): string {
34
+ const normalizedOutDir = resolve(outDir);
35
+ if (urlPath === "/" || urlPath === "") {
36
+ return join(normalizedOutDir, "index.html");
37
+ }
38
+ const resolved = resolve(normalizedOutDir, urlPath.slice(1), "index.html");
39
+ if (!resolved.startsWith(`${normalizedOutDir}${sep}`)) {
40
+ throw new Error(
41
+ `[furin] static: unsafe output path detected for URL "${urlPath}" — path traversal via ".." is not allowed.`
42
+ );
43
+ }
44
+ return resolved;
45
+ }
46
+
47
+ // ── Pre-render worker ─────────────────────────────────────────────────────────
48
+
49
+ async function prerenderAndWrite(
50
+ route: ResolvedRoute,
51
+ params: Record<string, string>,
52
+ root: RootLayout,
53
+ outDir: string,
54
+ renderedRoutes: string[],
55
+ skippedRoutes: string[],
56
+ basePath: string
57
+ ): Promise<void> {
58
+ const urlPath = resolvePath(route.pattern, params);
59
+ const outputFile = pathToOutputFile(urlPath, outDir);
60
+
61
+ try {
62
+ const entry = await prerenderSSG(route, params, root, "http://localhost", basePath);
63
+
64
+ if (entry instanceof Response) {
65
+ console.warn(
66
+ `[furin] static: route "${route.pattern}" loader returned a redirect — skipping.`
67
+ );
68
+ return;
69
+ }
70
+
71
+ ensureDir(dirname(outputFile));
72
+ writeFileSync(outputFile, entry.html);
73
+ renderedRoutes.push(urlPath);
74
+ console.log(`[furin] static: ${urlPath} → ${toPosixPath(outputFile)}`);
75
+ } catch (err) {
76
+ console.error(
77
+ `[furin] static: prerender failed for "${route.pattern}" (params: ${JSON.stringify(params)}):`,
78
+ err
79
+ );
80
+ skippedRoutes.push(urlPath);
81
+ }
82
+ }
83
+
84
+ // ── SSR validation ────────────────────────────────────────────────────────────
85
+
86
+ /**
87
+ * Returns only the SSG-eligible routes.
88
+ * Throws when onSSR="error" and non-SSG routes exist; warns+skips otherwise.
89
+ * Pushes skipped patterns into `skippedRoutes`.
90
+ */
91
+ function collectSsgRoutes(
92
+ routes: ResolvedRoute[],
93
+ onSSR: "error" | "skip",
94
+ skippedRoutes: string[]
95
+ ): ResolvedRoute[] {
96
+ const nonSsg = routes.filter((r) => r.mode !== "ssg");
97
+
98
+ if (nonSsg.length === 0) {
99
+ return routes;
100
+ }
101
+
102
+ if (onSSR === "error") {
103
+ const list = nonSsg.map((r) => ` • ${r.pattern} (mode: ${r.mode})`).join("\n");
104
+ throw new Error(
105
+ "[furin] Cannot produce a static export: the following routes are not SSG and cannot be pre-rendered.\n" +
106
+ `Either change their mode to "ssg", remove them, or set \`onSSR: "skip"\` in your static config.\n\n` +
107
+ `${list}`
108
+ );
109
+ }
110
+
111
+ // onSSR === "skip"
112
+ for (const r of nonSsg) {
113
+ console.warn(
114
+ `[furin] static: skipping route "${r.pattern}" (mode=${r.mode}) — not statically exportable.`
115
+ );
116
+ skippedRoutes.push(r.pattern);
117
+ }
118
+
119
+ return routes.filter((r) => r.mode === "ssg");
120
+ }
121
+
122
+ // ── Task queue builder ────────────────────────────────────────────────────────
123
+
124
+ /**
125
+ * Builds the flat list of pre-render tasks for all SSG routes.
126
+ * Dynamic routes without staticParams() are warned about and pushed to skippedRoutes.
127
+ */
128
+ async function buildTaskQueue(
129
+ ssgRoutes: ResolvedRoute[],
130
+ root: RootLayout,
131
+ outDir: string,
132
+ renderedRoutes: string[],
133
+ skippedRoutes: string[],
134
+ basePath: string
135
+ ): Promise<Array<() => Promise<void>>> {
136
+ const tasks: Array<() => Promise<void>> = [];
137
+
138
+ for (const route of ssgRoutes) {
139
+ if (!DYNAMIC_SEGMENT_RE.test(route.pattern)) {
140
+ tasks.push(() =>
141
+ prerenderAndWrite(route, {}, root, outDir, renderedRoutes, skippedRoutes, basePath)
142
+ );
143
+ continue;
144
+ }
145
+
146
+ if (!route.page.staticParams) {
147
+ console.warn(
148
+ `[furin] static: skipping dynamic route "${route.pattern}" — no staticParams() defined.`
149
+ );
150
+ skippedRoutes.push(route.pattern);
151
+ continue;
152
+ }
153
+
154
+ try {
155
+ const paramSets = (await route.page.staticParams()) ?? [];
156
+ for (const params of paramSets) {
157
+ tasks.push(() =>
158
+ prerenderAndWrite(route, params, root, outDir, renderedRoutes, skippedRoutes, basePath)
159
+ );
160
+ }
161
+ } catch (err) {
162
+ console.error(`[furin] static: staticParams() failed for "${route.pattern}":`, err);
163
+ skippedRoutes.push(route.pattern);
164
+ }
165
+ }
166
+
167
+ return tasks;
168
+ }
169
+
170
+ // ── Concurrency runner ────────────────────────────────────────────────────────
171
+
172
+ async function runWithConcurrency(
173
+ tasks: Array<() => Promise<void>>,
174
+ concurrency: number
175
+ ): Promise<void> {
176
+ const queue = [...tasks];
177
+ const workerCount = Math.min(concurrency, Math.max(queue.length, 1));
178
+ await Promise.all(
179
+ Array.from({ length: workerCount }, async () => {
180
+ while (queue.length > 0) {
181
+ await queue.shift()?.();
182
+ }
183
+ })
184
+ );
185
+ }
186
+
187
+ // ── Main adapter ──────────────────────────────────────────────────────────────
188
+
189
+ export async function buildStaticTarget(
190
+ routes: ResolvedRoute[],
191
+ rootDir: string,
192
+ buildRoot: string,
193
+ root: RootLayout,
194
+ options: BuildAppOptions
195
+ ): Promise<StaticTargetBuildManifest> {
196
+ const staticConfig: StaticExportConfig = options.staticConfig ?? {};
197
+
198
+ // Normalize basePath: treat "" and "/" identically as no prefix; strip any
199
+ // trailing slash so `${basePath}/_client/` never produces double slashes.
200
+ const rawBasePath = staticConfig.basePath ?? "";
201
+ let basePath: string;
202
+ if (rawBasePath === "/" || rawBasePath === "") {
203
+ basePath = "";
204
+ } else if (rawBasePath.endsWith("/")) {
205
+ basePath = rawBasePath.replace(TRAILING_SLASHES_RE, "");
206
+ } else {
207
+ basePath = rawBasePath;
208
+ }
209
+ if (basePath && !basePath.startsWith("/")) {
210
+ throw new Error(
211
+ `[furin] static: basePath must start with "/" (received "${rawBasePath}"). ` +
212
+ `Use "" for root deployments or "/sub-path" for sub-path deployments.`
213
+ );
214
+ }
215
+
216
+ const outDir = resolve(rootDir, staticConfig.outDir ?? "dist");
217
+
218
+ // Guard against destructive rmSync on obviously wrong output directories.
219
+ const normalizedRoot = resolve(rootDir);
220
+ const normalizedBuildRoot = resolve(buildRoot);
221
+ if (
222
+ outDir === normalizedRoot ||
223
+ outDir === normalizedBuildRoot ||
224
+ outDir === "/" ||
225
+ outDir === "."
226
+ ) {
227
+ throw new Error(
228
+ `[furin] static: outDir resolves to "${outDir}" which is unsafe to delete. ` +
229
+ `Use a dedicated output directory such as "dist".`
230
+ );
231
+ }
232
+ // Also reject ancestor paths: if rootDir or buildRoot is inside outDir, deleting
233
+ // outDir would destroy them. path.relative(outDir, x) not starting with ".." means x
234
+ // is inside (or equal to) outDir. On Windows, paths on different drives produce an
235
+ // absolute result from relative(), which also indicates they are outside outDir.
236
+ function isOutsideOutDir(target: string): boolean {
237
+ const rel = relative(outDir, target);
238
+ return rel.startsWith("..") || isAbsolute(rel);
239
+ }
240
+ if (!(isOutsideOutDir(normalizedRoot) && isOutsideOutDir(normalizedBuildRoot))) {
241
+ throw new Error(
242
+ `[furin] static: outDir resolves to "${outDir}" which is unsafe to delete. ` +
243
+ `Use a dedicated output directory such as "dist".`
244
+ );
245
+ }
246
+
247
+ const onSSR = staticConfig.onSSR ?? "error";
248
+ const publicPath = basePath ? `${basePath}/_client/` : "/_client/";
249
+
250
+ const renderedRoutes: string[] = [];
251
+ const skippedRoutes: string[] = [];
252
+
253
+ // ── 1. Validate SSR/ISR routes before doing any work ─────────────────────
254
+ const ssgRoutes = collectSsgRoutes(routes, onSSR, skippedRoutes);
255
+
256
+ // ── 2. Clean & create output directories ─────────────────────────────────
257
+ rmSync(outDir, { force: true, recursive: true });
258
+ ensureDir(outDir);
259
+
260
+ const targetDir = join(buildRoot, "static");
261
+ rmSync(targetDir, { force: true, recursive: true });
262
+ ensureDir(targetDir);
263
+
264
+ // ── 3. Build client bundle ────────────────────────────────────────────────
265
+ const { entryChunk, cssChunks } = await buildClient(ssgRoutes, {
266
+ outDir: targetDir,
267
+ rootLayout: root.path,
268
+ plugins: options.plugins,
269
+ publicPath,
270
+ basePath,
271
+ });
272
+
273
+ // ── 4. Generate HTML shell template ──────────────────────────────────────
274
+ const shellHtml = generateProdIndexHtml(entryChunk, cssChunks);
275
+
276
+ // ── 5. Prime the renderer with the production shell ──────────────────────
277
+ // Must be called before any prerenderSSG invocation.
278
+ // prepareRender() checks getProductionTemplate() first (before IS_DEV), so
279
+ // setting the content here is sufficient — no need to flip IS_DEV globally.
280
+ setProductionTemplateContent(shellHtml);
281
+
282
+ // ── 6. Copy public/ → outDir/ ─────────────────────────────────────────────
283
+ const publicSrcDir = join(rootDir, "public");
284
+ if (existsSync(publicSrcDir)) {
285
+ cpSync(publicSrcDir, outDir, { recursive: true });
286
+ }
287
+
288
+ // ── 7. Copy _client/ chunks → outDir/_client/ ────────────────────────────
289
+ const clientSrcDir = join(targetDir, "client");
290
+ if (existsSync(clientSrcDir)) {
291
+ cpSync(clientSrcDir, join(outDir, "_client"), { recursive: true });
292
+ }
293
+
294
+ // ── 8. Pre-render SSG routes ──────────────────────────────────────────────
295
+ const tasks = await buildTaskQueue(
296
+ ssgRoutes,
297
+ root,
298
+ outDir,
299
+ renderedRoutes,
300
+ skippedRoutes,
301
+ basePath
302
+ );
303
+ // Snapshot after queue-building: routes skipped due to missing staticParams() are
304
+ // already recorded; only routes added during task execution are prerender failures.
305
+ const afterQueueCount = skippedRoutes.length;
306
+ await runWithConcurrency(tasks, STATIC_CONCURRENCY);
307
+
308
+ // Fail the build when onSSR="error" and any prerender task was recorded as skipped.
309
+ if (onSSR === "error" && skippedRoutes.length > afterQueueCount) {
310
+ const failed = skippedRoutes.slice(afterQueueCount);
311
+ const list = failed.map((r) => ` • ${r}`).join("\n");
312
+ throw new Error(
313
+ `[furin] static: ${failed.length} route(s) failed to pre-render:\n${list}\n` +
314
+ `Set \`onSSR: "skip"\` in your static config to suppress this error.`
315
+ );
316
+ }
317
+
318
+ // ── 9. Write 404.html (SPA fallback for GitHub Pages) ───────────────────
319
+ writeFileSync(join(outDir, "404.html"), shellHtml);
320
+ console.log("[furin] static: wrote 404.html (SPA shell fallback)");
321
+
322
+ // ── 10. Clean up intermediate build artifacts ────────────────────────────
323
+ rmSync(targetDir, { force: true, recursive: true });
324
+
325
+ console.log(
326
+ `[furin] static: export complete → ${toPosixPath(outDir)}` +
327
+ ` (${renderedRoutes.length} rendered, ${skippedRoutes.length} skipped)`
328
+ );
329
+
330
+ return {
331
+ basePath,
332
+ generatedAt: new Date().toISOString(),
333
+ outDir: toPosixPath(outDir),
334
+ renderedRoutes,
335
+ skippedRoutes,
336
+ };
337
+ }