@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.
@@ -87,6 +87,8 @@ export async function buildBunTarget(
87
87
  outDir: targetDir,
88
88
  rootLayout: rootPath,
89
89
  plugins: options.plugins,
90
+ publicPath: "/_client/",
91
+ basePath: "",
90
92
  });
91
93
 
92
94
  const buildFingerprint = await createBuildFingerprint(
@@ -134,8 +136,26 @@ export async function buildBunTarget(
134
136
  compile: { outfile },
135
137
  minify: true,
136
138
  sourcemap: "linked",
139
+ define: { "process.env.NODE_ENV": JSON.stringify("production") },
137
140
  plugins: options.plugins,
138
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
+
139
159
  console.log(`[furin] Server binary: ${outfile}`);
140
160
 
141
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
+ }
@@ -4,16 +4,16 @@ import { transformForClient } from "../plugin/transform-client";
4
4
  import type { ResolvedRoute } from "../router";
5
5
  import { generateHydrateEntry } from "./hydrate";
6
6
  import { CLIENT_MODULE_PATH, LINK_MODULE_PATH } from "./shared";
7
- import type { BunBuildAliasConfig, BuildClientOptions } from "./types";
7
+ import type { BuildClientOptions, BunBuildAliasConfig } from "./types";
8
8
 
9
9
  const TS_FILE_FILTER = /\.(tsx|ts)$/;
10
10
  const REACT_IMPORT_RE = /import\s+React\b/;
11
11
 
12
12
  export interface BuildClientResult {
13
- /** Public path of the JS entry chunk, e.g. `/_client/chunk-abc.js` */
14
- entryChunk: string;
15
13
  /** Public paths of all CSS chunks, e.g. `["/_client/chunk-abc.css"]` */
16
14
  cssChunks: string[];
15
+ /** Public path of the JS entry chunk, e.g. `/_client/chunk-abc.js` */
16
+ entryChunk: string;
17
17
  }
18
18
 
19
19
  /**
@@ -34,7 +34,7 @@ export interface BuildClientResult {
34
34
  */
35
35
  export async function buildClient(
36
36
  routes: ResolvedRoute[],
37
- { outDir, rootLayout, plugins }: BuildClientOptions
37
+ { outDir, rootLayout, plugins, publicPath, basePath }: BuildClientOptions
38
38
  ): Promise<BuildClientResult> {
39
39
  const clientDir = join(outDir, "client");
40
40
 
@@ -45,7 +45,7 @@ export async function buildClient(
45
45
  mkdirSync(clientDir, { recursive: true });
46
46
  }
47
47
 
48
- const hydrateCode = generateHydrateEntry(routes, rootLayout);
48
+ const hydrateCode = generateHydrateEntry(routes, rootLayout, basePath);
49
49
  const hydratePath = join(outDir, "_hydrate.tsx");
50
50
  writeFileSync(hydratePath, hydrateCode);
51
51
 
@@ -57,7 +57,7 @@ export async function buildClient(
57
57
  build.onLoad({ filter: TS_FILE_FILTER }, async (args) => {
58
58
  const { path } = args;
59
59
  if (path.includes("node_modules")) {
60
- return undefined;
60
+ return;
61
61
  }
62
62
 
63
63
  const code = await Bun.file(path).text();
@@ -81,7 +81,7 @@ export async function buildClient(
81
81
  };
82
82
  } catch (error) {
83
83
  console.error(`[furin] Transform error for ${path}:`, error);
84
- return undefined;
84
+ return;
85
85
  }
86
86
  });
87
87
  },
@@ -106,8 +106,9 @@ export async function buildClient(
106
106
  entry: "[dir]/[name]-[hash].[ext]",
107
107
  chunk: "[name]-[hash].[ext]",
108
108
  },
109
- // Absolute public path so SSR template asset URLs resolve on any route
110
- publicPath: "/_client/",
109
+ // Absolute public path so SSR template asset URLs resolve on any route.
110
+ // Overridable via the `publicPath` option (e.g. "/furin/_client/" for basePath builds).
111
+ publicPath,
111
112
  // User plugins run before the internal transform so they pre-process files first
112
113
  plugins: plugins ? [...plugins, transformPlugin] : [transformPlugin],
113
114
  alias: {
@@ -135,8 +136,17 @@ export async function buildClient(
135
136
  throw new Error("[furin] client build did not emit entry chunk");
136
137
  }
137
138
 
138
- const entryChunk = `/_client/${basename(entryOutput.path)}`;
139
- const cssChunks = cssOutputs.map((o) => `/_client/${basename(o.path)}`);
139
+ // Normalise: ensure publicPath ends with exactly one "/".
140
+ // Preserve an empty publicPath ("") as-is so callers that want
141
+ // relative chunk URLs don't get an unintended root-absolute "/".
142
+ let publicPrefix: string;
143
+ if (publicPath === "") {
144
+ publicPrefix = "";
145
+ } else {
146
+ publicPrefix = publicPath.endsWith("/") ? publicPath : `${publicPath}/`;
147
+ }
148
+ const entryChunk = `${publicPrefix}${basename(entryOutput.path)}`;
149
+ const cssChunks = cssOutputs.map((o) => `${publicPrefix}${basename(o.path)}`);
140
150
 
141
151
  console.log("[furin] Production client build complete");
142
152
  return { entryChunk, cssChunks };
@@ -5,12 +5,12 @@ import { collectFilesRecursive, ensureDir, toPosixPath } from "./shared";
5
5
 
6
6
  export interface CompileEntryOptions {
7
7
  buildId?: string;
8
+ embed?: { clientDir: string };
8
9
  outDir: string;
10
+ publicDir?: string;
9
11
  rootPath: string;
10
12
  routes: Array<{ mode: "ssr" | "ssg" | "isr"; path: string; pattern: string }>;
11
13
  serverEntry: string;
12
- embed?: { clientDir: string };
13
- publicDir?: string;
14
14
  }
15
15
 
16
16
  /**
@@ -29,7 +29,9 @@ export function generateCompileEntry(options: CompileEntryOptions): string {
29
29
  let embeddedBlock: string[] = [];
30
30
  if (embed) {
31
31
  if (!existsSync(embed.clientDir)) {
32
- throw new Error(`[furin] Client directory not found: ${embed.clientDir}. Run the client build first.`);
32
+ throw new Error(
33
+ `[furin] Client directory not found: ${embed.clientDir}. Run the client build first.`
34
+ );
33
35
  }
34
36
  const clientFiles = collectFilesRecursive(embed.clientDir);
35
37
  const assetEntries: string[] = [];
@@ -9,12 +9,12 @@ const RUNTIME_ENV_MODULE_PATH = `${_pkgSrcDir}/runtime-env.ts`;
9
9
 
10
10
  export interface EntryTemplateOptions {
11
11
  buildId?: string;
12
+ extraContext?: string[];
13
+ extraImports?: string[];
12
14
  headerComment: string;
13
15
  rootPath: string;
14
16
  routes: Array<{ mode: "ssr" | "ssg" | "isr"; path: string; pattern: string }>;
15
17
  serverEntry: string;
16
- extraImports?: string[];
17
- extraContext?: string[];
18
18
  }
19
19
 
20
20
  export function buildEntrySource(options: EntryTemplateOptions): string {
@@ -14,8 +14,16 @@ import type { BuildClientOptions } from "./types";
14
14
  *
15
15
  * @param routes - Resolved routes to include in the hydration manifest.
16
16
  * @param rootLayout - Absolute path to the root layout module.
17
+ * @param basePath - Optional sub-path prefix for static deployments (e.g. "/furin").
18
+ * When set, the generated code strips the prefix from `window.location.pathname`
19
+ * before matching routes, and passes `basePath` to `RouterProvider` so SPA
20
+ * navigation uses the correct physical URLs.
17
21
  */
18
- export function generateHydrateEntry(routes: ResolvedRoute[], rootLayout: string): string {
22
+ export function generateHydrateEntry(
23
+ routes: ResolvedRoute[],
24
+ rootLayout: string,
25
+ basePath: string
26
+ ): string {
19
27
  const routeEntries: string[] = [];
20
28
 
21
29
  for (const route of routes) {
@@ -27,20 +35,38 @@ export function generateHydrateEntry(routes: ResolvedRoute[], rootLayout: string
27
35
  );
28
36
  }
29
37
 
38
+ // basePath stripping: when deployed to a sub-path (e.g. /furin), strip the
39
+ // prefix before route matching so patterns like /docs/routing still work.
40
+ const basePathLiteral = JSON.stringify(basePath);
41
+ // Strip basePath only when it matches on a path boundary (prevents "/furin" from
42
+ // matching "/furinity/foo"). The boundary holds when the pathname ends exactly
43
+ // at the prefix length OR the next character is "/".
44
+ const pathnameExpr = basePath
45
+ ? `(() => { const p = window.location.pathname; const b = ${basePathLiteral}; return (p.startsWith(b) && (p.length === b.length || p[b.length] === "/")) ? p.slice(b.length) || "/" : p; })()`
46
+ : "window.location.pathname";
47
+
48
+ // Log drain endpoint: prepend basePath so the request goes to the correct origin path.
49
+ const logEndpoint = basePath
50
+ ? `${JSON.stringify(basePath)} + "/_furin/ingest"`
51
+ : `"/_furin/ingest"`;
52
+
53
+ // RouterProvider receives basePath so navigate() / Link push physical paths.
54
+ const basePathProp = basePath ? `\n basePath: ${basePathLiteral},` : "";
55
+
30
56
  return `import { hydrateRoot, createRoot } from "react-dom/client";
31
57
  import { createElement } from "react";
32
58
  import { initLogger, log } from "evlog";
33
- import { createBrowserLogDrain } from "evlog/browser";
59
+ import { createHttpLogDrain } from "evlog/http";
34
60
  import { RouterProvider } from "@teyik0/furin/link";
35
61
  import { route as root } from "${rootLayout.replace(/\\/g, "/")}";
36
62
 
37
- initLogger({ drain: createBrowserLogDrain({ drain: { endpoint: "/_furin/ingest" } }) });
63
+ initLogger({ drain: createHttpLogDrain({ drain: { endpoint: ${logEndpoint} } }) });
38
64
 
39
65
  const routes = [
40
66
  ${routeEntries.join(",\n")}
41
67
  ];
42
68
 
43
- const pathname = window.location.pathname;
69
+ const pathname = ${pathnameExpr};
44
70
  const _match = routes.find((r) => r.regex.test(pathname));
45
71
 
46
72
  // Eagerly load only the current page module for initial hydration.
@@ -60,7 +86,7 @@ const _match = routes.find((r) => r.regex.test(pathname));
60
86
  routes,
61
87
  root,
62
88
  initialMatch: match,
63
- initialData: loaderData,
89
+ initialData: loaderData,${basePathProp}
64
90
  } as any);
65
91
 
66
92
  if (import.meta.hot) {
@@ -99,14 +125,14 @@ const _match = routes.find((r) => r.regex.test(pathname));
99
125
  */
100
126
  export function writeDevFiles(
101
127
  routes: ResolvedRoute[],
102
- { outDir, rootLayout }: BuildClientOptions,
103
- projectRoot: string,
128
+ { outDir, rootLayout, basePath }: BuildClientOptions,
129
+ projectRoot: string
104
130
  ): void {
105
131
  if (!existsSync(outDir)) {
106
132
  mkdirSync(outDir, { recursive: true });
107
133
  }
108
134
 
109
- const hydrateCode = generateHydrateEntry(routes, rootLayout);
135
+ const hydrateCode = generateHydrateEntry(routes, rootLayout, basePath);
110
136
  const hydratePath = join(outDir, "_hydrate.tsx");
111
137
  const existingHydrate = existsSync(hydratePath) ? readFileSync(hydratePath, "utf8") : "";
112
138
  if (hydrateCode !== existingHydrate) {
@@ -122,5 +148,7 @@ export function writeDevFiles(
122
148
 
123
149
  writeRouteTypes(routes, projectRoot);
124
150
 
125
- console.log("[furin] Dev files written (.furin/_hydrate.tsx + .furin/index.html + furin-env.d.ts)");
151
+ console.log(
152
+ "[furin] Dev files written (.furin/_hydrate.tsx + .furin/index.html + furin-env.d.ts)"
153
+ );
126
154
  }