@teyik0/furin 0.2.0-alpha.1 → 0.2.0-alpha.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +33 -33
  3. package/dist/adapter/static.d.ts +1 -1
  4. package/dist/build/compile-entry.ts +109 -109
  5. package/dist/build/entry-template.ts +156 -156
  6. package/dist/build/index.js +1724 -687
  7. package/dist/build/route-types.d.ts +3 -1
  8. package/dist/build/server-routes-entry.ts +36 -36
  9. package/dist/build/shared.d.ts +1 -0
  10. package/dist/build/ssg-cache.d.ts +1 -1
  11. package/dist/cli/index.js +1673 -658
  12. package/dist/client/link.js +883 -89
  13. package/dist/client/router/index.d.ts +4 -0
  14. package/dist/client/router/link-utils.d.ts +3 -1
  15. package/dist/client/router/navigation.d.ts +10 -0
  16. package/dist/client/router/provider.d.ts +1 -1
  17. package/dist/client/router/search/index.d.ts +18 -0
  18. package/dist/client/router/search-store.d.ts +21 -0
  19. package/dist/client/router/types.d.ts +14 -1
  20. package/dist/client/sync.d.ts +25 -0
  21. package/dist/client.d.ts +1 -0
  22. package/dist/client.js +44 -0
  23. package/dist/furin.d.ts +9 -1
  24. package/dist/furin.js +1578 -258
  25. package/dist/server/auto-invalidate/runtime.d.ts +1 -1
  26. package/dist/server/dev-page-plugin.d.ts +3 -0
  27. package/dist/server/render/assemble.d.ts +2 -0
  28. package/dist/server/render/isr.d.ts +2 -1
  29. package/dist/server/render/ssg.d.ts +3 -2
  30. package/dist/server/render/ssr.d.ts +5 -4
  31. package/dist/server/router/hmr.d.ts +4 -3
  32. package/dist/server/router/index.d.ts +1 -1
  33. package/dist/server/router/index.js +1 -2
  34. package/dist/server/router/index.ts +1 -2
  35. package/dist/server/router/plugin.d.ts +2 -1
  36. package/dist/server/router/schemas.d.ts +25 -17
  37. package/dist/server/sync/config.d.ts +6 -0
  38. package/dist/server/sync/index.d.ts +4 -0
  39. package/dist/server/sync/plugin.d.ts +369 -0
  40. package/dist/server/sync/stream.d.ts +47 -0
  41. package/dist/shared/search-params.d.ts +17 -0
  42. package/package.json +10 -5
  43. package/src/adapter/README.md +13 -13
  44. package/src/adapter/static.ts +23 -6
  45. package/src/build/client.ts +152 -149
  46. package/src/build/compile-entry.ts +109 -109
  47. package/src/build/entry-template.ts +156 -156
  48. package/src/build/hydrate.ts +340 -331
  49. package/src/build/index.ts +152 -152
  50. package/src/build/route-types.ts +145 -115
  51. package/src/build/scan-server.ts +95 -95
  52. package/src/build/server-routes-entry.ts +36 -36
  53. package/src/build/shared.ts +80 -78
  54. package/src/build/ssg-cache.ts +32 -31
  55. package/src/build/types.ts +89 -89
  56. package/src/client/link.tsx +13 -4
  57. package/src/client/router/context.ts +2 -0
  58. package/src/client/router/index.ts +9 -0
  59. package/src/client/router/link-utils.ts +184 -180
  60. package/src/client/router/navigation.ts +61 -0
  61. package/src/client/router/provider.tsx +804 -723
  62. package/src/client/router/search/index.ts +99 -0
  63. package/src/client/router/search-store.ts +86 -0
  64. package/src/client/router/types.ts +276 -263
  65. package/src/client/sync.ts +98 -0
  66. package/src/client.ts +369 -355
  67. package/src/furin.ts +465 -437
  68. package/src/server/auto-invalidate/runtime.ts +134 -133
  69. package/src/server/dev-page-plugin.ts +454 -449
  70. package/src/server/render/assemble.ts +160 -133
  71. package/src/server/render/isr.ts +323 -295
  72. package/src/server/render/not-found.ts +2 -0
  73. package/src/server/render/ssg.ts +15 -4
  74. package/src/server/render/ssr.ts +585 -545
  75. package/src/server/router/hmr.ts +14 -10
  76. package/src/server/router/index.ts +1 -2
  77. package/src/server/router/patterns.ts +5 -0
  78. package/src/server/router/plugin.ts +384 -401
  79. package/src/server/router/schemas.ts +172 -57
  80. package/src/server/sync/config.ts +29 -0
  81. package/src/server/sync/index.ts +14 -0
  82. package/src/server/sync/plugin.ts +108 -0
  83. package/src/server/sync/stream.ts +144 -0
  84. package/src/shared/search-params.ts +182 -0
package/src/furin.ts CHANGED
@@ -1,437 +1,465 @@
1
- import { existsSync } from "node:fs";
2
- import { basename, dirname, join, resolve } from "node:path";
3
- import { fileURLToPath } from "node:url";
4
- import { staticPlugin } from "@elysiajs/static";
5
- import { type AnyElysia, Elysia, file } from "elysia";
6
- import { type DrainContext, initLogger } from "evlog";
7
- import { type EvlogElysiaOptions, evlog } from "evlog/elysia";
8
- import {
9
- _runWithRequestInvalidationScope,
10
- consumePendingInvalidations,
11
- getBuildId,
12
- setBuildId,
13
- } from "./server/cache/invalidation.ts";
14
- import { setSSGCache } from "./server/cache/ssg.ts";
15
- import type { CompileContext, EmbeddedAppData } from "./server/internal.ts";
16
- import { getCompileContext } from "./server/internal.ts";
17
- import { renderRootNotFound, warmSSGCache } from "./server/render/index.ts";
18
- import {
19
- setProductionTemplateContent,
20
- setProductionTemplatePath,
21
- } from "./server/render/template.ts";
22
- import { createDataEndpoint, createRoutePlugin, loadProdRoutes } from "./server/router/index.ts";
23
- import { IS_DEV } from "./server/runtime-env.ts";
24
-
25
- // biome-ignore lint/suspicious/noEmptyInterface: intentionally augmentable via furin-env.d.ts
26
- export interface FurinCacheTags {}
27
-
28
- export type CacheTag = keyof FurinCacheTags extends never ? string : keyof FurinCacheTags;
29
-
30
- function resolveClientDirFromArgv(): string {
31
- return (
32
- resolveClientDirFromEnv() ??
33
- resolveClientDirFromModuleUrl() ??
34
- resolveClientDirFromProcessArgs() ??
35
- resolveFallbackClientDir()
36
- );
37
- }
38
-
39
- function resolveClientDirFromEnv(): string | null {
40
- const envClientDir = process.env.FURIN_CLIENT_DIR;
41
- if (!envClientDir) {
42
- return null;
43
- }
44
- return envClientDir.startsWith("/") ? envClientDir : resolve(process.cwd(), envClientDir);
45
- }
46
-
47
- function resolveClientDirFromModuleUrl(): string | null {
48
- try {
49
- const moduleUrl = new URL(import.meta.url);
50
- if (moduleUrl.protocol !== "file:") {
51
- return null;
52
- }
53
- const modulePath = fileURLToPath(moduleUrl);
54
- if (modulePath.includes("/$bunfs/")) {
55
- return null;
56
- }
57
- const moduleClientDir = join(dirname(modulePath), "client");
58
- if (existsSync(join(moduleClientDir, "index.html"))) {
59
- return moduleClientDir;
60
- }
61
- } catch {
62
- // ignore, fallback to argv-based resolution
63
- }
64
- return null;
65
- }
66
-
67
- function resolveClientDirFromProcessArgs(): string | null {
68
- const candidates = [
69
- process.argv[1],
70
- process.argv[0],
71
- (process as { argv0?: string }).argv0,
72
- process.execPath,
73
- ].filter((value): value is string => typeof value === "string" && value.length > 0);
74
-
75
- for (const candidate of candidates) {
76
- const resolved = resolveClientDirFromCandidate(candidate);
77
- if (resolved) {
78
- return resolved;
79
- }
80
- }
81
-
82
- return null;
83
- }
84
-
85
- function resolveClientDirFromCandidate(candidate: string): string | null {
86
- const name = basename(candidate);
87
- if (name === "bun" || name === "node") {
88
- return null;
89
- }
90
- if (candidate.includes("/$bunfs/") || candidate.startsWith("bunfs:")) {
91
- return null;
92
- }
93
-
94
- const absolute = candidate.startsWith("/") ? candidate : resolve(process.cwd(), candidate);
95
- if (existsSync(absolute)) {
96
- return join(dirname(absolute), "client");
97
- }
98
-
99
- if (!candidate.includes("/")) {
100
- return resolveClientDirFromPath(candidate);
101
- }
102
-
103
- return null;
104
- }
105
-
106
- function resolveClientDirFromPath(candidate: string): string | null {
107
- const pathEntries = process.env.PATH?.split(":") ?? [];
108
- for (const dir of pathEntries) {
109
- const fullPath = join(dir, candidate);
110
- if (existsSync(fullPath)) {
111
- return join(dirname(fullPath), "client");
112
- }
113
- }
114
- return null;
115
- }
116
-
117
- function resolveFallbackClientDir(): string {
118
- const defaultClientDir = resolve(process.cwd(), ".furin/build/bun/client");
119
- if (existsSync(join(defaultClientDir, "index.html"))) {
120
- return defaultClientDir;
121
- }
122
-
123
- return join(process.cwd(), "client");
124
- }
125
-
126
- async function setupProdTemplate(
127
- embedded: EmbeddedAppData | undefined,
128
- clientDir: string
129
- ): Promise<void> {
130
- if (embedded) {
131
- if (!embedded.template) {
132
- throw new Error("[furin] Embedded app is missing its HTML template (index.html).");
133
- }
134
- const html = await Bun.file(embedded.template).text();
135
- setProductionTemplateContent(html);
136
- return;
137
- }
138
-
139
- const templatePath = join(clientDir, "index.html");
140
- if (!existsSync(templatePath)) {
141
- throw new Error("[furin] No pre-built assets found. Run `bun run build` first.");
142
- }
143
- setProductionTemplatePath(templatePath);
144
- }
145
-
146
- /**
147
- * Registers a HigherOrderFunction on the Elysia instance so that every request
148
- * runs inside a fresh `AsyncLocalStorage` scope. This isolates
149
- * `pendingInvalidations` per request, preventing concurrent requests from
150
- * stealing each other's `revalidatePath()` calls.
151
- *
152
- * Uses `app.wrap()` (Elysia HigherOrderFunction) instead of mutating
153
- * `app.handle`, because handle mutations are lost when the Furin plugin is
154
- * `.use()`-d by a parent Elysia instance. HigherOrderFunctions survive the
155
- * plugin merge and wrap the entire composed `map` handler.
156
- */
157
- function wrapWithRequestScope(app: AnyElysia): Elysia {
158
- return app.wrap(
159
- (handler, _request) => (ctx: unknown) => _runWithRequestInvalidationScope(() => handler(ctx))
160
- );
161
- }
162
-
163
- function hydrateSSGCacheFromCompileContext(ctx: CompileContext): void {
164
- if (!ctx.ssgCache) {
165
- return;
166
- }
167
- for (const [path, entry] of Object.entries(ctx.ssgCache)) {
168
- setSSGCache(path, entry);
169
- }
170
- }
171
-
172
- /**
173
- * Main Furin plugin.
174
- *
175
- * Returns a standalone Elysia instance (async function) so that routes are
176
- * properly registered in Elysia's router for SPA navigation to work.
177
- *
178
- * ## Usage
179
- *
180
- * ```ts
181
- * new Elysia()
182
- * .use(await furin({ ... }))
183
- * .listen(3000)
184
- * ```
185
- */
186
- export async function furin({
187
- pagesDir,
188
- logger,
189
- clientLogging,
190
- }: {
191
- pagesDir?: string;
192
- logger?: EvlogElysiaOptions;
193
- /**
194
- * Initialize the browser HTTP log drain in the hydration entry. Off by
195
- * default — enabling it adds `evlog/http` drain setup and points browser
196
- * events at `/_furin/ingest`. Server-side logging is configured via `logger`
197
- * and unaffected.
198
- */
199
- clientLogging?: boolean;
200
- }) {
201
- const { exclude: userExclude, ...evlogOptions } = logger ?? {};
202
- initLogger({ env: { service: "furin" } });
203
-
204
- const loggerPlugin = new Elysia()
205
- .use(
206
- evlog({
207
- ...evlogOptions,
208
- exclude: [
209
- "/_client/**",
210
- "/public/**",
211
- "/favicon.ico",
212
- "/_bun_hmr_entry/**",
213
- // Note: /_furin/data is logged with the *logical* path rewritten by
214
- // createDataEndpoint via useLogger().set({ path }), so SPA navigations
215
- // appear as "GET /board/123 200" — same shape as a normal SSR nav.
216
- // /_furin/ingest is kept loggable so browser-side events show up.
217
- // evlog's `matchesPattern` only supports `*`, `**`, `?` — extglob
218
- // like `!(...)` matches nothing, so don't add patterns relying on it.
219
- ...(userExclude ?? []),
220
- ],
221
- })
222
- )
223
- .post(
224
- "/_furin/ingest",
225
- ({ body, log, status }) => {
226
- if (!Array.isArray(body)) {
227
- return status("Bad Request");
228
- }
229
- // Cap batch size to prevent abuse
230
- const batch = (body as DrainContext[]).slice(0, 100);
231
- for (const entry of batch) {
232
- if (!entry || typeof entry !== "object" || !("event" in entry)) {
233
- log.set({ msg: "[furin] ingest: skipping malformed entry" });
234
- continue;
235
- }
236
- // Pick only safe, known fields from the event to prevent prototype pollution
237
- const event = entry.event as Record<string, unknown> | undefined;
238
- if (!event || typeof event !== "object") {
239
- continue;
240
- }
241
- const {
242
- __proto__,
243
- constructor: _ctor,
244
- prototype,
245
- environment: _browserEnv,
246
- ...safeEvent
247
- } = event as Record<string, unknown>;
248
- log.set({ ...safeEvent, service: "furin:browser" });
249
- }
250
- return status("No Content");
251
- },
252
- { parse: "json" }
253
- );
254
-
255
- const cwd = process.cwd();
256
- const ctx = getCompileContext();
257
- const resolvedPagesDir = ctx?.rootPath
258
- ? dirname(ctx.rootPath)
259
- : resolve(cwd, pagesDir ?? "src/pages");
260
-
261
- // Unique name per pagesDir to avoid Elysia's name-based plugin dedup.
262
- const instanceName = `furin-${resolvedPagesDir.replaceAll("\\", "/")}`;
263
-
264
- // ── Dev: Bun native HMR ────────────────────────────────────────────────
265
- if (IS_DEV) {
266
- const furinDir = resolve(cwd, ".furin");
267
- // Lazy import — build pipeline has native deps not available in compiled binaries
268
- const { registerDevPagePlugin } = await import("./server/dev-page-plugin.ts");
269
- registerDevPagePlugin();
270
-
271
- const { createDevInspectorPlugin } = await import("./server/dev-inspector.ts");
272
-
273
- const { scanPages } = await import("./server/router/index.ts");
274
- const { root, routes } = await scanPages(resolvedPagesDir);
275
-
276
- const { writeDevFiles } = await import("./build/hydrate.ts");
277
- writeDevFiles(
278
- routes,
279
- {
280
- outDir: furinDir,
281
- rootLayout: root.path,
282
- basePath: "",
283
- publicPath: "/_client/",
284
- clientLogging: clientLogging ?? false,
285
- },
286
- cwd
287
- );
288
-
289
- const publicDir = resolve(cwd, "public");
290
- const publicExists = existsSync(publicDir);
291
-
292
- const devApp = new Elysia({ name: instanceName, seed: resolvedPagesDir })
293
- .use(loggerPlugin)
294
- .onError({ as: "global" }, async ({ code, request }) => {
295
- if (code === "NOT_FOUND") {
296
- return await renderRootNotFound(root, request);
297
- }
298
- })
299
- .onAfterHandle({ as: "global" }, ({ set }) => {
300
- // Forward pending revalidation paths so the client can bust its prefetch cache
301
- const pending = consumePendingInvalidations();
302
- if (pending.length > 0) {
303
- set.headers["x-furin-revalidate"] = pending.join(",");
304
- }
305
- })
306
- .use(await staticPlugin({ assets: furinDir, prefix: "/_bun_hmr_entry", bunFullstack: true }))
307
- .use(
308
- publicExists ? await staticPlugin({ assets: publicDir, prefix: "/public" }) : new Elysia()
309
- )
310
- .get(
311
- "/favicon.ico",
312
- publicExists
313
- ? file(join(publicDir, "favicon.ico"))
314
- : () => new Response(null, { status: 404 })
315
- )
316
- .use(createDevInspectorPlugin())
317
- .use(createDataEndpoint(routes))
318
- .use((app) => {
319
- for (const route of routes) {
320
- app.use(createRoutePlugin(route, root));
321
- }
322
- return app;
323
- });
324
- return wrapWithRequestScope(devApp);
325
- }
326
-
327
- // ── Production ──────────────────────────────────────────────────────────
328
- if (!ctx) {
329
- throw new Error("[furin] No pre-built assets found. Run `bunx furin build` first.");
330
- }
331
- const { root, routes } = loadProdRoutes(ctx);
332
- const prodBuildId = ctx.buildId ?? "";
333
- setBuildId(prodBuildId);
334
- hydrateSSGCacheFromCompileContext(ctx);
335
-
336
- const embedded = ctx?.embedded;
337
- const clientDir = embedded ? "" : resolveClientDirFromArgv();
338
- await setupProdTemplate(embedded, clientDir);
339
-
340
- const prodApp = new Elysia({ name: instanceName, seed: resolvedPagesDir })
341
- .use(loggerPlugin)
342
- .onError({ as: "global" }, async ({ code, request }) => {
343
- if (code === "NOT_FOUND") {
344
- return await renderRootNotFound(root, request);
345
- }
346
- })
347
- .onAfterHandle({ as: "global" }, ({ path, set }) => {
348
- // Content-hashed client assets are permanently cacheable — browsers never need to
349
- // revalidate them because any change produces a new filename.
350
- if (path.startsWith("/_client/")) {
351
- set.headers["cache-control"] = "public, max-age=31536000, immutable";
352
- }
353
- // Forward pending revalidation paths so the client can bust its prefetch cache
354
- const pending = consumePendingInvalidations();
355
- if (pending.length > 0) {
356
- set.headers["x-furin-revalidate"] = pending.join(",");
357
- }
358
- // Tell the client the current build ID so it can detect stale deploys
359
- const buildId = getBuildId();
360
- if (buildId) {
361
- set.headers["x-furin-build-id"] = buildId;
362
- }
363
- })
364
- .onStart(async ({ server }) => {
365
- if (ctx.ssgCache) {
366
- return;
367
- }
368
- const origin = server?.url?.origin ?? "http://localhost:3000";
369
- await warmSSGCache(routes, root, origin);
370
- })
371
- .use(
372
- await (async () => {
373
- if (embedded) {
374
- return new Elysia()
375
- .get("/favicon.ico", ({ status }) => {
376
- const asset = embedded.assets["/public/favicon.ico"];
377
- if (!asset) {
378
- return status("Not Found");
379
- }
380
- return Bun.file(asset);
381
- })
382
- .get("/_client/*", ({ params, status }) => {
383
- const asset = embedded.assets[`/_client/${params["*"]}`];
384
- if (!asset) {
385
- return status("Not Found");
386
- }
387
- return Bun.file(asset);
388
- })
389
- .get("/public/*", ({ params, status }) => {
390
- const asset = embedded.assets[`/public/${params["*"]}`];
391
- if (!asset) {
392
- return status("Not Found");
393
- }
394
- return Bun.file(asset);
395
- });
396
- }
397
- const publicDir = join(dirname(clientDir), "public");
398
- const app = new Elysia();
399
- if (existsSync(publicDir)) {
400
- app
401
- .get("/favicon.ico", file(join(publicDir, "favicon.ico")))
402
- .use(await staticPlugin({ assets: publicDir, prefix: "/public" }));
403
- }
404
- app.use(await staticPlugin({ assets: clientDir, prefix: "/_client" }));
405
- return app;
406
- })()
407
- )
408
- .use(createDataEndpoint(routes))
409
- .use((app) => {
410
- for (const route of routes) {
411
- app.use(createRoutePlugin(route, root, prodBuildId));
412
- }
413
- return app;
414
- });
415
- return wrapWithRequestScope(prodApp);
416
- }
417
-
418
- // biome-ignore lint/performance/noBarrelFile: furin.ts is the public package entry
419
- export { FurinErrorBoundary, FurinNotFoundBoundary } from "./client/boundaries.tsx";
420
- // ── Public API re-export ──────────────────────────────────────────────────────
421
- // biome-ignore-start lint/performance/noBarrelFile: intentional — furin.ts is the public package entry
422
- export type { DeferredData, RuntimePage, RuntimeRoute } from "./client.ts";
423
- export { defer, isDeferred } from "./client.ts";
424
- export type { InvalidationInput, InvalidationRule } from "./server/auto-invalidate/index.ts";
425
- export { furinInvalidate, revalidateTag } from "./server/auto-invalidate/index.ts";
426
- export { revalidatePath, setCachePurger } from "./server/cache/invalidation.ts";
427
- export { buildElement, buildErrorElement, renderRootNotFound } from "./server/render/index.ts";
428
- export type { ResolvedRoute, SegmentBoundary } from "./server/router/index.ts";
429
- export { Await, useAsyncError, useAsyncValue } from "./shared/await.tsx";
430
- export type { ErrorComponent, ErrorProps } from "./shared/error.ts";
431
- export type {
432
- NotFoundComponent,
433
- NotFoundOptions,
434
- NotFoundProps,
435
- } from "./shared/not-found.ts";
436
- export { isNotFoundError, notFound } from "./shared/not-found.ts";
437
- // biome-ignore-end lint/performance/noBarrelFile: intentional — furin.ts is the public package entry
1
+ import { existsSync } from "node:fs";
2
+ import { basename, dirname, join, resolve } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import { staticPlugin } from "@elysiajs/static";
5
+ import { type AnyElysia, Elysia, file } from "elysia";
6
+ import { type DrainContext, initLogger } from "evlog";
7
+ import { type EvlogElysiaOptions, evlog } from "evlog/elysia";
8
+ import {
9
+ _runWithRequestInvalidationScope,
10
+ consumePendingInvalidations,
11
+ getBuildId,
12
+ setBuildId,
13
+ } from "./server/cache/invalidation.ts";
14
+ import { setSSGCache } from "./server/cache/ssg.ts";
15
+ import type { CompileContext, EmbeddedAppData } from "./server/internal.ts";
16
+ import { getCompileContext } from "./server/internal.ts";
17
+ import { renderRootNotFound, warmSSGCache } from "./server/render/index.ts";
18
+ import {
19
+ setProductionTemplateContent,
20
+ setProductionTemplatePath,
21
+ } from "./server/render/template.ts";
22
+ import {
23
+ createDataEndpoint,
24
+ createRoutePlugin,
25
+ createSearchRouteMetadata,
26
+ loadProdRoutes,
27
+ } from "./server/router/index.ts";
28
+ import { IS_DEV } from "./server/runtime-env.ts";
29
+ import {
30
+ createSyncStreamPlugin,
31
+ type FurinSyncOption,
32
+ resolveSyncStreamPath,
33
+ runWithSyncStreamPath,
34
+ } from "./server/sync/index.ts";
35
+
36
+ // biome-ignore lint/suspicious/noEmptyInterface: intentionally augmentable via furin-env.d.ts
37
+ export interface FurinCacheTags {}
38
+
39
+ export type CacheTag = keyof FurinCacheTags extends never ? string : keyof FurinCacheTags;
40
+
41
+ function resolveClientDirFromArgv(): string {
42
+ return (
43
+ resolveClientDirFromEnv() ??
44
+ resolveClientDirFromModuleUrl() ??
45
+ resolveClientDirFromProcessArgs() ??
46
+ resolveFallbackClientDir()
47
+ );
48
+ }
49
+
50
+ function resolveClientDirFromEnv(): string | null {
51
+ const envClientDir = process.env.FURIN_CLIENT_DIR;
52
+ if (!envClientDir) {
53
+ return null;
54
+ }
55
+ return envClientDir.startsWith("/") ? envClientDir : resolve(process.cwd(), envClientDir);
56
+ }
57
+
58
+ function resolveClientDirFromModuleUrl(): string | null {
59
+ try {
60
+ const moduleUrl = new URL(import.meta.url);
61
+ if (moduleUrl.protocol !== "file:") {
62
+ return null;
63
+ }
64
+ const modulePath = fileURLToPath(moduleUrl);
65
+ if (modulePath.includes("/$bunfs/")) {
66
+ return null;
67
+ }
68
+ const moduleClientDir = join(dirname(modulePath), "client");
69
+ if (existsSync(join(moduleClientDir, "index.html"))) {
70
+ return moduleClientDir;
71
+ }
72
+ } catch {
73
+ // ignore, fallback to argv-based resolution
74
+ }
75
+ return null;
76
+ }
77
+
78
+ function resolveClientDirFromProcessArgs(): string | null {
79
+ const candidates = [
80
+ process.argv[1],
81
+ process.argv[0],
82
+ (process as { argv0?: string }).argv0,
83
+ process.execPath,
84
+ ].filter((value): value is string => typeof value === "string" && value.length > 0);
85
+
86
+ for (const candidate of candidates) {
87
+ const resolved = resolveClientDirFromCandidate(candidate);
88
+ if (resolved) {
89
+ return resolved;
90
+ }
91
+ }
92
+
93
+ return null;
94
+ }
95
+
96
+ function resolveClientDirFromCandidate(candidate: string): string | null {
97
+ const name = basename(candidate);
98
+ if (name === "bun" || name === "node") {
99
+ return null;
100
+ }
101
+ if (candidate.includes("/$bunfs/") || candidate.startsWith("bunfs:")) {
102
+ return null;
103
+ }
104
+
105
+ const absolute = candidate.startsWith("/") ? candidate : resolve(process.cwd(), candidate);
106
+ if (existsSync(absolute)) {
107
+ return join(dirname(absolute), "client");
108
+ }
109
+
110
+ if (!candidate.includes("/")) {
111
+ return resolveClientDirFromPath(candidate);
112
+ }
113
+
114
+ return null;
115
+ }
116
+
117
+ function resolveClientDirFromPath(candidate: string): string | null {
118
+ const pathEntries = process.env.PATH?.split(":") ?? [];
119
+ for (const dir of pathEntries) {
120
+ const fullPath = join(dir, candidate);
121
+ if (existsSync(fullPath)) {
122
+ return join(dirname(fullPath), "client");
123
+ }
124
+ }
125
+ return null;
126
+ }
127
+
128
+ function resolveFallbackClientDir(): string {
129
+ const defaultClientDir = resolve(process.cwd(), ".furin/build/bun/client");
130
+ if (existsSync(join(defaultClientDir, "index.html"))) {
131
+ return defaultClientDir;
132
+ }
133
+
134
+ return join(process.cwd(), "client");
135
+ }
136
+
137
+ async function setupProdTemplate(
138
+ embedded: EmbeddedAppData | undefined,
139
+ clientDir: string
140
+ ): Promise<void> {
141
+ if (embedded) {
142
+ if (!embedded.template) {
143
+ throw new Error("[furin] Embedded app is missing its HTML template (index.html).");
144
+ }
145
+ const html = await Bun.file(embedded.template).text();
146
+ setProductionTemplateContent(html);
147
+ return;
148
+ }
149
+
150
+ const templatePath = join(clientDir, "index.html");
151
+ if (!existsSync(templatePath)) {
152
+ throw new Error("[furin] No pre-built assets found. Run `bun run build` first.");
153
+ }
154
+ setProductionTemplatePath(templatePath);
155
+ }
156
+
157
+ /**
158
+ * Registers a HigherOrderFunction on the Elysia instance so that every request
159
+ * runs inside a fresh `AsyncLocalStorage` scope. This isolates
160
+ * `pendingInvalidations` per request, preventing concurrent requests from
161
+ * stealing each other's `revalidatePath()` calls.
162
+ *
163
+ * Uses `app.wrap()` (Elysia HigherOrderFunction) instead of mutating
164
+ * `app.handle`, because handle mutations are lost when the Furin plugin is
165
+ * `.use()`-d by a parent Elysia instance. HigherOrderFunctions survive the
166
+ * plugin merge and wrap the entire composed `map` handler.
167
+ */
168
+ function wrapWithRequestScope(app: AnyElysia, syncStreamPath: string | undefined): Elysia {
169
+ return app.wrap(
170
+ (handler, _request) => (ctx: unknown) =>
171
+ runWithSyncStreamPath(syncStreamPath, () =>
172
+ _runWithRequestInvalidationScope(() => handler(ctx))
173
+ )
174
+ );
175
+ }
176
+
177
+ function hydrateSSGCacheFromCompileContext(ctx: CompileContext): void {
178
+ if (!ctx.ssgCache) {
179
+ return;
180
+ }
181
+ for (const [path, entry] of Object.entries(ctx.ssgCache)) {
182
+ setSSGCache(path, entry);
183
+ }
184
+ }
185
+
186
+ /**
187
+ * Main Furin plugin.
188
+ *
189
+ * Returns a standalone Elysia instance (async function) so that routes are
190
+ * properly registered in Elysia's router for SPA navigation to work.
191
+ *
192
+ * ## Usage
193
+ *
194
+ * ```ts
195
+ * new Elysia()
196
+ * .use(await furin({ ... }))
197
+ * .listen(3000)
198
+ * ```
199
+ */
200
+ export async function furin({
201
+ pagesDir,
202
+ logger,
203
+ clientLogging,
204
+ sync,
205
+ }: {
206
+ pagesDir?: string;
207
+ logger?: EvlogElysiaOptions;
208
+ /**
209
+ * Initialize the browser HTTP log drain in the hydration entry. Off by
210
+ * default — enabling it adds `evlog/http` drain setup and points browser
211
+ * events at `/_furin/ingest`. Server-side logging is configured via `logger`
212
+ * and unaffected.
213
+ */
214
+ clientLogging?: boolean;
215
+ /**
216
+ * Enables Furin's built-in sync event stream. The opinionated default mounts
217
+ * Server-Sent Events at `/_furin/sync`; pass an object only for constrained
218
+ * reverse-proxy deployments that need a custom internal path.
219
+ */
220
+ sync?: FurinSyncOption;
221
+ }) {
222
+ const syncStreamPath = resolveSyncStreamPath(sync);
223
+ const { exclude: userExclude, ...evlogOptions } = logger ?? {};
224
+ initLogger({ env: { service: "furin" } });
225
+
226
+ const loggerPlugin = new Elysia()
227
+ .use(
228
+ evlog({
229
+ ...evlogOptions,
230
+ exclude: [
231
+ "/_client/**",
232
+ "/public/**",
233
+ "/favicon.ico",
234
+ "/_bun_hmr_entry/**",
235
+ ...(syncStreamPath ? [syncStreamPath] : []),
236
+ // Note: /_furin/data is logged with the *logical* path rewritten by
237
+ // createDataEndpoint via useLogger().set({ path }), so SPA navigations
238
+ // appear as "GET /board/123 200" — same shape as a normal SSR nav.
239
+ // /_furin/ingest is kept loggable so browser-side events show up.
240
+ // evlog's `matchesPattern` only supports `*`, `**`, `?` — extglob
241
+ // like `!(...)` matches nothing, so don't add patterns relying on it.
242
+ ...(userExclude ?? []),
243
+ ],
244
+ })
245
+ )
246
+ .post(
247
+ "/_furin/ingest",
248
+ ({ body, log, status }) => {
249
+ if (!Array.isArray(body)) {
250
+ return status("Bad Request");
251
+ }
252
+ // Cap batch size to prevent abuse
253
+ const batch = (body as DrainContext[]).slice(0, 100);
254
+ for (const entry of batch) {
255
+ if (!entry || typeof entry !== "object" || !("event" in entry)) {
256
+ log.set({ msg: "[furin] ingest: skipping malformed entry" });
257
+ continue;
258
+ }
259
+ // Pick only safe, known fields from the event to prevent prototype pollution
260
+ const event = entry.event as Record<string, unknown> | undefined;
261
+ if (!event || typeof event !== "object") {
262
+ continue;
263
+ }
264
+ const {
265
+ __proto__,
266
+ constructor: _ctor,
267
+ prototype,
268
+ environment: _browserEnv,
269
+ ...safeEvent
270
+ } = event as Record<string, unknown>;
271
+ log.set({ ...safeEvent, service: "furin:browser" });
272
+ }
273
+ return status("No Content");
274
+ },
275
+ { parse: "json" }
276
+ );
277
+
278
+ const cwd = process.cwd();
279
+ const ctx = getCompileContext();
280
+ const resolvedPagesDir = ctx?.rootPath
281
+ ? dirname(ctx.rootPath)
282
+ : resolve(cwd, pagesDir ?? "src/pages");
283
+
284
+ // Unique name per pagesDir to avoid Elysia's name-based plugin dedup.
285
+ const instanceName = `furin-${resolvedPagesDir.replaceAll("\\", "/")}`;
286
+
287
+ // ── Dev: Bun native HMR ────────────────────────────────────────────────
288
+ if (IS_DEV) {
289
+ const furinDir = resolve(cwd, ".furin");
290
+ // Lazy import — build pipeline has native deps not available in compiled binaries
291
+ const { registerDevPagePlugin } = await import("./server/dev-page-plugin.ts");
292
+ registerDevPagePlugin();
293
+
294
+ const { createDevInspectorPlugin } = await import("./server/dev-inspector.ts");
295
+
296
+ const { scanPages } = await import("./server/router/index.ts");
297
+ const { root, routes } = await scanPages(resolvedPagesDir);
298
+ const searchRoutes = createSearchRouteMetadata(routes);
299
+
300
+ const { writeDevFiles } = await import("./build/hydrate.ts");
301
+ writeDevFiles(
302
+ routes,
303
+ {
304
+ outDir: furinDir,
305
+ rootLayout: root.path,
306
+ basePath: "",
307
+ publicPath: "/_client/",
308
+ clientLogging: clientLogging ?? false,
309
+ },
310
+ cwd
311
+ );
312
+
313
+ const publicDir = resolve(cwd, "public");
314
+ const publicExists = existsSync(publicDir);
315
+
316
+ const devApp = new Elysia({ name: instanceName, seed: resolvedPagesDir })
317
+ .use(loggerPlugin)
318
+ .onError({ as: "global" }, async ({ code, request }) => {
319
+ if (code === "NOT_FOUND") {
320
+ return await renderRootNotFound(root, request);
321
+ }
322
+ })
323
+ .onAfterHandle({ as: "global" }, ({ set }) => {
324
+ // Forward pending revalidation paths so the client can bust its prefetch cache
325
+ const pending = consumePendingInvalidations();
326
+ if (pending.length > 0) {
327
+ set.headers["x-furin-revalidate"] = pending.join(",");
328
+ }
329
+ })
330
+ .use(await staticPlugin({ assets: furinDir, prefix: "/_bun_hmr_entry", bunFullstack: true }))
331
+ .use(
332
+ publicExists ? await staticPlugin({ assets: publicDir, prefix: "/public" }) : new Elysia()
333
+ )
334
+ .get(
335
+ "/favicon.ico",
336
+ publicExists
337
+ ? file(join(publicDir, "favicon.ico"))
338
+ : () => new Response(null, { status: 404 })
339
+ )
340
+ .use(createDevInspectorPlugin())
341
+ .use(syncStreamPath ? createSyncStreamPlugin(syncStreamPath) : new Elysia())
342
+ .use(createDataEndpoint(routes))
343
+ .use((app) => {
344
+ for (const route of routes) {
345
+ app.use(createRoutePlugin(route, root, undefined, searchRoutes));
346
+ }
347
+ return app;
348
+ });
349
+ return wrapWithRequestScope(devApp, syncStreamPath);
350
+ }
351
+
352
+ // ── Production ──────────────────────────────────────────────────────────
353
+ if (!ctx) {
354
+ throw new Error("[furin] No pre-built assets found. Run `bunx furin build` first.");
355
+ }
356
+ const { root, routes } = loadProdRoutes(ctx);
357
+ const searchRoutes = createSearchRouteMetadata(routes);
358
+ const prodBuildId = ctx.buildId ?? "";
359
+ setBuildId(prodBuildId);
360
+ hydrateSSGCacheFromCompileContext(ctx);
361
+
362
+ const embedded = ctx?.embedded;
363
+ const clientDir = embedded ? "" : resolveClientDirFromArgv();
364
+ await setupProdTemplate(embedded, clientDir);
365
+
366
+ const prodApp = new Elysia({ name: instanceName, seed: resolvedPagesDir })
367
+ .use(loggerPlugin)
368
+ .onError({ as: "global" }, async ({ code, request }) => {
369
+ if (code === "NOT_FOUND") {
370
+ return await renderRootNotFound(root, request);
371
+ }
372
+ })
373
+ .onAfterHandle({ as: "global" }, ({ path, set }) => {
374
+ // Content-hashed client assets are permanently cacheable — browsers never need to
375
+ // revalidate them because any change produces a new filename.
376
+ if (path.startsWith("/_client/")) {
377
+ set.headers["cache-control"] = "public, max-age=31536000, immutable";
378
+ }
379
+ // Forward pending revalidation paths so the client can bust its prefetch cache
380
+ const pending = consumePendingInvalidations();
381
+ if (pending.length > 0) {
382
+ set.headers["x-furin-revalidate"] = pending.join(",");
383
+ }
384
+ // Tell the client the current build ID so it can detect stale deploys
385
+ const buildId = getBuildId();
386
+ if (buildId) {
387
+ set.headers["x-furin-build-id"] = buildId;
388
+ }
389
+ })
390
+ .onStart(async ({ server }) => {
391
+ if (ctx.ssgCache) {
392
+ return;
393
+ }
394
+ const origin = server?.url?.origin ?? "http://localhost:3000";
395
+ await warmSSGCache(routes, root, origin, searchRoutes);
396
+ })
397
+ .use(
398
+ await (async () => {
399
+ if (embedded) {
400
+ return new Elysia()
401
+ .get("/favicon.ico", ({ status }) => {
402
+ const asset = embedded.assets["/public/favicon.ico"];
403
+ if (!asset) {
404
+ return status("Not Found");
405
+ }
406
+ return Bun.file(asset);
407
+ })
408
+ .get("/_client/*", ({ params, status }) => {
409
+ const asset = embedded.assets[`/_client/${params["*"]}`];
410
+ if (!asset) {
411
+ return status("Not Found");
412
+ }
413
+ return Bun.file(asset);
414
+ })
415
+ .get("/public/*", ({ params, status }) => {
416
+ const asset = embedded.assets[`/public/${params["*"]}`];
417
+ if (!asset) {
418
+ return status("Not Found");
419
+ }
420
+ return Bun.file(asset);
421
+ });
422
+ }
423
+ const publicDir = join(dirname(clientDir), "public");
424
+ const app = new Elysia();
425
+ if (existsSync(publicDir)) {
426
+ app
427
+ .get("/favicon.ico", file(join(publicDir, "favicon.ico")))
428
+ .use(await staticPlugin({ assets: publicDir, prefix: "/public" }));
429
+ }
430
+ app.use(await staticPlugin({ assets: clientDir, prefix: "/_client" }));
431
+ return app;
432
+ })()
433
+ )
434
+ .use(syncStreamPath ? createSyncStreamPlugin(syncStreamPath) : new Elysia())
435
+ .use(createDataEndpoint(routes))
436
+ .use((app) => {
437
+ for (const route of routes) {
438
+ app.use(createRoutePlugin(route, root, prodBuildId, searchRoutes));
439
+ }
440
+ return app;
441
+ });
442
+ return wrapWithRequestScope(prodApp, syncStreamPath);
443
+ }
444
+
445
+ // biome-ignore lint/performance/noBarrelFile: furin.ts is the public package entry
446
+ export { FurinErrorBoundary, FurinNotFoundBoundary } from "./client/boundaries.tsx";
447
+ // ── Public API re-export ──────────────────────────────────────────────────────
448
+ // biome-ignore-start lint/performance/noBarrelFile: intentional — furin.ts is the public package entry
449
+ export type { DeferredData, RuntimePage, RuntimeRoute } from "./client.ts";
450
+ export { defer, isDeferred } from "./client.ts";
451
+ export type { InvalidationInput, InvalidationRule } from "./server/auto-invalidate/index.ts";
452
+ export { furinInvalidate, revalidateTag } from "./server/auto-invalidate/index.ts";
453
+ export { revalidatePath, setCachePurger } from "./server/cache/invalidation.ts";
454
+ export { buildElement, buildErrorElement, renderRootNotFound } from "./server/render/index.ts";
455
+ export type { ResolvedRoute, SegmentBoundary } from "./server/router/index.ts";
456
+ export { furinSync, type SyncInput } from "./server/sync/index.ts";
457
+ export { Await, useAsyncError, useAsyncValue } from "./shared/await.tsx";
458
+ export type { ErrorComponent, ErrorProps } from "./shared/error.ts";
459
+ export type {
460
+ NotFoundComponent,
461
+ NotFoundOptions,
462
+ NotFoundProps,
463
+ } from "./shared/not-found.ts";
464
+ export { isNotFoundError, notFound } from "./shared/not-found.ts";
465
+ // biome-ignore-end lint/performance/noBarrelFile: intentional — furin.ts is the public package entry