@teyik0/furin 0.2.0-alpha.4 → 0.2.0-alpha.5

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 (67) hide show
  1. package/dist/adapter/bun.d.ts +17 -1
  2. package/dist/adapter/package.d.ts +26 -0
  3. package/dist/build/client.d.ts +1 -1
  4. package/dist/build/compile-entry.d.ts +3 -3
  5. package/dist/build/compile-entry.ts +88 -83
  6. package/dist/build/entry-template.d.ts +35 -9
  7. package/dist/build/entry-template.ts +106 -56
  8. package/dist/build/hydrate.d.ts +1 -1
  9. package/dist/build/index.js +643 -247
  10. package/dist/build/scan-server.d.ts +10 -4
  11. package/dist/build/server-routes-entry.d.ts +3 -3
  12. package/dist/build/server-routes-entry.ts +5 -11
  13. package/dist/build/ssg-cache.d.ts +1 -1
  14. package/dist/build/types.d.ts +36 -1
  15. package/dist/cli/config.d.ts +6 -1
  16. package/dist/cli/index.js +662 -260
  17. package/dist/config.d.ts +11 -2
  18. package/dist/config.js +5 -1
  19. package/dist/furin.d.ts +36 -18
  20. package/dist/furin.js +630 -310
  21. package/dist/server/auto-invalidate/registry.d.ts +8 -1
  22. package/dist/server/cache/dev-loader.d.ts +3 -2
  23. package/dist/server/cache/invalidation.d.ts +19 -0
  24. package/dist/server/cache/isr.d.ts +6 -2
  25. package/dist/server/cache/registry.d.ts +3 -3
  26. package/dist/server/cache/ssg.d.ts +6 -2
  27. package/dist/server/cache/store-view.d.ts +11 -0
  28. package/dist/server/instance.d.ts +86 -0
  29. package/dist/server/internal.d.ts +16 -1
  30. package/dist/server/internal.js +72 -5
  31. package/dist/server/render/template.d.ts +3 -2
  32. package/dist/server/sync/config.d.ts +11 -0
  33. package/dist/server/sync/stream.d.ts +8 -1
  34. package/dist/shared/prefix.d.ts +15 -0
  35. package/package.json +6 -1
  36. package/src/adapter/bun.ts +113 -50
  37. package/src/adapter/package.ts +206 -0
  38. package/src/build/client.ts +9 -3
  39. package/src/build/compile-entry.ts +88 -83
  40. package/src/build/entry-template.ts +106 -56
  41. package/src/build/hydrate.ts +4 -2
  42. package/src/build/index.ts +99 -28
  43. package/src/build/scan-server.ts +23 -7
  44. package/src/build/server-routes-entry.ts +5 -11
  45. package/src/build/ssg-cache.ts +6 -2
  46. package/src/build/types.ts +37 -1
  47. package/src/cli/config.ts +9 -3
  48. package/src/cli/index.ts +21 -3
  49. package/src/config.ts +14 -1
  50. package/src/furin.ts +297 -143
  51. package/src/server/auto-invalidate/registry.ts +23 -1
  52. package/src/server/auto-invalidate/runtime.ts +29 -4
  53. package/src/server/cache/dev-loader.ts +77 -38
  54. package/src/server/cache/invalidation.ts +71 -30
  55. package/src/server/cache/isr.ts +20 -5
  56. package/src/server/cache/registry.ts +17 -20
  57. package/src/server/cache/ssg.ts +19 -4
  58. package/src/server/cache/store-view.ts +30 -0
  59. package/src/server/instance.ts +252 -0
  60. package/src/server/internal.ts +100 -5
  61. package/src/server/render/not-found.ts +9 -3
  62. package/src/server/render/ssr.ts +16 -4
  63. package/src/server/render/template.ts +57 -24
  64. package/src/server/sync/config.ts +32 -1
  65. package/src/server/sync/plugin.ts +4 -5
  66. package/src/server/sync/stream.ts +19 -9
  67. package/src/shared/prefix.ts +38 -0
@@ -0,0 +1,252 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+
3
+ // ── Furin instance model ─────────────────────────────────────────────────────
4
+ // Each `furin({ pagesDir, prefix })` call registers one instance. All
5
+ // previously module-global state (build ID, caches, template, sync path, …)
6
+ // hangs off the instance via `instanceSlot()` so several furin apps can be
7
+ // mounted in one Elysia process without stomping each other.
8
+ //
9
+ // This module is a dependency LEAF: it only imports node:async_hooks. State
10
+ // modules (cache/ssg.ts, render/template.ts, …) import it to declare their
11
+ // per-instance slots — never the other way around.
12
+
13
+ export interface FurinInstance {
14
+ buildId: string;
15
+ /** Absolute pagesDir — also the compile-context key. */
16
+ readonly pagesDir: string;
17
+ /** Mount prefix, `""` for the root app or `/admin`-style (no trailing slash). */
18
+ readonly prefix: string;
19
+ /** @internal Traffic epoch at registration time (see registerInstance). */
20
+ registrationEpoch: number;
21
+ /** Generic per-instance state bag backing `instanceSlot()`. */
22
+ readonly state: Map<symbol, unknown>;
23
+ /** Logical sync stream path (unprefixed) injected into HTML, or undefined. */
24
+ syncStreamPath: string | undefined;
25
+ }
26
+
27
+ interface RequestScope {
28
+ instance: FurinInstance;
29
+ pending: Set<string>;
30
+ }
31
+
32
+ const _requestScope = new AsyncLocalStorage<RequestScope>();
33
+
34
+ const WHITESPACE_RE = /\s/;
35
+
36
+ /** Registered instances, keyed by prefix. */
37
+ const _instances = new Map<string, FurinInstance>();
38
+
39
+ /**
40
+ * Fallback bucket used when no instance was ever registered (unit tests
41
+ * importing state modules directly, build-time rendering). Lazily created so
42
+ * a plain `import` of a state module allocates nothing.
43
+ */
44
+ let _defaultInstance: FurinInstance | null = null;
45
+
46
+ export function createInstance(prefix: string, pagesDir: string): FurinInstance {
47
+ return {
48
+ prefix,
49
+ pagesDir,
50
+ syncStreamPath: undefined,
51
+ buildId: "",
52
+ registrationEpoch: 0,
53
+ state: new Map(),
54
+ };
55
+ }
56
+
57
+ // Bumped on every served request. Lets registerInstance tell a REAL prefix
58
+ // collision (two apps composed in one startup, no traffic in between) from a
59
+ // stale registration left behind by a previous test/server in this process
60
+ // (traffic flowed since — the old mount is dead, replace it).
61
+ let _trafficEpoch = 0;
62
+
63
+ /** @internal Called by the request wrap for every served request. */
64
+ export function markTraffic(): void {
65
+ _trafficEpoch++;
66
+ }
67
+
68
+ function defaultInstance(): FurinInstance {
69
+ if (!_defaultInstance) {
70
+ _defaultInstance = createInstance("", "");
71
+ }
72
+ return _defaultInstance;
73
+ }
74
+
75
+ /**
76
+ * The process-wide fallback bucket. State written outside any instance scope
77
+ * before the first `furin()` registration lands here — config-like readers
78
+ * (e.g. the production template) treat it as a default.
79
+ */
80
+ export function defaultInstanceBucket(): FurinInstance {
81
+ return defaultInstance();
82
+ }
83
+
84
+ /**
85
+ * Normalizes a user-provided mount prefix. Accepts `""`, `"/"` (both → root)
86
+ * or `/segment(/segment)*`. Throws on anything else so misconfiguration fails
87
+ * at startup instead of producing silently unreachable routes.
88
+ */
89
+ export function normalizePrefix(prefix: string | undefined): string {
90
+ if (prefix === undefined || prefix === "" || prefix === "/") {
91
+ return "";
92
+ }
93
+ if (!prefix.startsWith("/")) {
94
+ throw new Error(`[furin] prefix must start with "/" (got "${prefix}").`);
95
+ }
96
+ // Check the RAW value for "//" so "/admin//" is rejected instead of being
97
+ // trimmed to "/admin/" — a trailing slash never matches the path-boundary
98
+ // checks in resolveInstanceByPath, i.e. every route would be unreachable.
99
+ if (prefix.includes("//") || WHITESPACE_RE.test(prefix)) {
100
+ throw new Error(`[furin] invalid prefix "${prefix}".`);
101
+ }
102
+ return prefix.endsWith("/") ? prefix.slice(0, -1) : prefix;
103
+ }
104
+
105
+ /**
106
+ * Throws when mounting `pagesDir` under `prefix` would collide with a LIVE
107
+ * registration. Rules:
108
+ * - same pagesDir → idempotent re-mount (mirrors Elysia's name-based dedup);
109
+ * - different pagesDir, NO traffic since the existing registration → two apps
110
+ * composed into one server are claiming the same prefix: hard error;
111
+ * - different pagesDir, traffic flowed since → the existing registration is a
112
+ * leftover from a torn-down server (tests): replacement is allowed.
113
+ */
114
+ export function assertPrefixAvailable(prefix: string, pagesDir: string): void {
115
+ const existing = _instances.get(prefix);
116
+ if (existing && existing.pagesDir !== pagesDir && existing.registrationEpoch === _trafficEpoch) {
117
+ throw new Error(
118
+ `[furin] prefix "${prefix || "/"}" is already mounted by pagesDir "${existing.pagesDir}" ` +
119
+ `(attempted to mount "${pagesDir}"). Give each furin() instance a unique prefix.`
120
+ );
121
+ }
122
+ }
123
+
124
+ /** Registers an instance under its prefix (see assertPrefixAvailable). */
125
+ export function registerInstance(instance: FurinInstance): FurinInstance {
126
+ assertPrefixAvailable(instance.prefix, instance.pagesDir);
127
+ instance.registrationEpoch = _trafficEpoch;
128
+ _instances.set(instance.prefix, instance);
129
+ return instance;
130
+ }
131
+
132
+ /**
133
+ * Resolves the instance owning `pathname` by longest-prefix match on a path
134
+ * boundary. Falls back to the root (`""`) instance when one is mounted, else
135
+ * the default bucket — never an arbitrary prefixed sibling, whose template/
136
+ * cache/build state would otherwise leak into parent-app routes.
137
+ */
138
+ export function resolveInstanceByPath(pathname: string): FurinInstance {
139
+ let best: FurinInstance | null = null;
140
+ for (const [prefix, instance] of _instances) {
141
+ if (prefix === "") {
142
+ best ??= instance;
143
+ continue;
144
+ }
145
+ if (
146
+ (pathname === prefix ||
147
+ (pathname.startsWith(prefix) && pathname.charCodeAt(prefix.length) === 47)) &&
148
+ (!best || prefix.length > best.prefix.length || best.prefix === "")
149
+ ) {
150
+ best = instance;
151
+ }
152
+ }
153
+ if (best) {
154
+ return best;
155
+ }
156
+ return defaultInstance();
157
+ }
158
+
159
+ /**
160
+ * The instance the current code runs for. Resolution order:
161
+ * 1. request/render ALS scope, 2. sole registered instance, 3. default bucket.
162
+ * With ≥2 instances and no scope, state access is ambiguous — the default
163
+ * bucket keeps out-of-request writes (e.g. build-time template setup)
164
+ * self-consistent instead of leaking into an arbitrary app.
165
+ */
166
+ export function currentInstance(): FurinInstance {
167
+ const scope = _requestScope.getStore();
168
+ if (scope) {
169
+ return scope.instance;
170
+ }
171
+ if (_instances.size === 1) {
172
+ const only = _instances.values().next().value;
173
+ if (only) {
174
+ return only;
175
+ }
176
+ }
177
+ return defaultInstance();
178
+ }
179
+
180
+ /** All registered instances (used by cross-instance ops like revalidateTag). */
181
+ export function allInstances(): FurinInstance[] {
182
+ if (_instances.size === 0) {
183
+ return [defaultInstance()];
184
+ }
185
+ return [..._instances.values()];
186
+ }
187
+
188
+ /**
189
+ * @internal Every live state bucket: registered instances plus the default
190
+ * fallback bucket. Reset helpers iterate this so state written outside any
191
+ * registration (tests, config-before-mount) is covered too.
192
+ */
193
+ export function allStateBuckets(): FurinInstance[] {
194
+ const buckets = [..._instances.values()];
195
+ const fallback = defaultInstance();
196
+ if (!buckets.includes(fallback)) {
197
+ buckets.push(fallback);
198
+ }
199
+ return buckets;
200
+ }
201
+
202
+ /**
203
+ * @internal test-only — forgets registered instances (fresh mounts get a
204
+ * clean registry) while PRESERVING the default bucket, so process-wide
205
+ * defaults installed once (e.g. a test template in `beforeAll`) survive.
206
+ */
207
+ export function __clearInstanceRegistry(): void {
208
+ _instances.clear();
209
+ }
210
+
211
+ export function hasRequestScope(): boolean {
212
+ return _requestScope.getStore() !== undefined;
213
+ }
214
+
215
+ /** Pending client-invalidation paths for the current request, if any. */
216
+ export function requestPendingInvalidations(): Set<string> | undefined {
217
+ return _requestScope.getStore()?.pending;
218
+ }
219
+
220
+ /** Runs `fn` inside a fresh request scope bound to `instance`. */
221
+ export function runWithInstanceScope<T>(instance: FurinInstance, fn: () => T): T {
222
+ return _requestScope.run({ instance, pending: new Set<string>() }, fn);
223
+ }
224
+
225
+ /**
226
+ * Runs `fn` bound to `instance` for synthetic (non-request) work — SSG cache
227
+ * warming, background ISR revalidation kicked off outside a live request.
228
+ */
229
+ export function withInstance<T>(instance: FurinInstance, fn: () => T): T {
230
+ return runWithInstanceScope(instance, fn);
231
+ }
232
+
233
+ /**
234
+ * Declares a lazily-initialized per-instance state slot. Returns an accessor
235
+ * that resolves against the current instance (or an explicit one). This is
236
+ * how state modules attach caches/registries to instances without this module
237
+ * importing them (avoids import cycles).
238
+ */
239
+ export function instanceSlot<T>(
240
+ init: (instance: FurinInstance) => T
241
+ ): (instance?: FurinInstance) => T {
242
+ const key = Symbol("furin-instance-slot");
243
+ return (instance?: FurinInstance) => {
244
+ const target = instance ?? currentInstance();
245
+ if (target.state.has(key)) {
246
+ return target.state.get(key) as T;
247
+ }
248
+ const value = init(target);
249
+ target.state.set(key, value);
250
+ return value;
251
+ };
252
+ }
@@ -1,4 +1,5 @@
1
1
  import type { SsgCacheEntry } from "./cache/index.ts";
2
+ import { __clearInstanceRegistry } from "./instance.ts";
2
3
 
3
4
  // ── Compile-time context for compiled binaries ──────────────────────────────
4
5
  // The generated compile entry calls `__setCompileContext()` before importing
@@ -20,6 +21,8 @@ export interface CompileContext {
20
21
  buildId?: string;
21
22
  embedded?: EmbeddedAppData;
22
23
  modules: Record<string, unknown>;
24
+ /** Mount prefix this app was built for (`""` = root). */
25
+ prefix?: string;
23
26
  /** Root-level conventions discovered at compile time. */
24
27
  rootConventions?: { errorPath?: string; notFoundPath?: string };
25
28
  rootPath: string;
@@ -39,16 +42,108 @@ export interface CompileContext {
39
42
  ssgCache?: Record<string, SsgCacheEntry>;
40
43
  }
41
44
 
42
- let _compileCtx: CompileContext | null = null;
45
+ // Contexts are keyed by (pagesDir, prefix) — pagesDir being the directory
46
+ // containing root.tsx, normalized to posix separators. The SAME pagesDir may
47
+ // legally be mounted under two different prefixes (assertPrefixAvailable only
48
+ // rejects same-prefix collisions), so pagesDir alone would let the second
49
+ // registration overwrite the first. Several packaged furin apps can each ship
50
+ // a self-registering module calling `__setCompileContext()` — registration is
51
+ // ADDITIVE, one context per (app, mount).
52
+ const _compileContexts = new Map<string, CompileContext>();
53
+
54
+ function normalizeContextKey(path: string): string {
55
+ return path.replaceAll("\\", "/");
56
+ }
57
+
58
+ function pagesDirOf(ctx: CompileContext): string {
59
+ const rootPath = normalizeContextKey(ctx.rootPath);
60
+ const lastSlash = rootPath.lastIndexOf("/");
61
+ return lastSlash === -1 ? rootPath : rootPath.slice(0, lastSlash);
62
+ }
63
+
64
+ // "\u0000" cannot appear in a path or a prefix, so the composite key is
65
+ // unambiguous even for pagesDirs containing spaces.
66
+ function contextKey(pagesDir: string, prefix: string): string {
67
+ return `${pagesDir}\u0000${prefix}`;
68
+ }
43
69
 
44
70
  export function __setCompileContext(ctx: CompileContext): void {
45
- _compileCtx = ctx;
71
+ _compileContexts.set(contextKey(pagesDirOf(ctx), ctx.prefix ?? ""), ctx);
72
+ }
73
+
74
+ /**
75
+ * Looks up the compile context for a (pagesDir, prefix) mount. Resolution
76
+ * order, from most to least specific:
77
+ * 1. exact (pagesDir, prefix) key — distinguishes the same app mounted twice;
78
+ * 2. sole context registered for `pagesDir` — callers that don't pass a
79
+ * prefix, and contexts emitted before the prefix field existed;
80
+ * 3. sole context registered for `prefix` — deployed binaries run from a
81
+ * different cwd than the build, so the absolute pagesDir key misses there,
82
+ * but the mount prefix is stable across machines;
83
+ * 4. the sole registered context (single-app back-compat).
84
+ */
85
+ export function getCompileContext(pagesDir?: string, prefix?: string): CompileContext | null {
86
+ if (pagesDir !== undefined) {
87
+ const dir = normalizeContextKey(pagesDir);
88
+ if (prefix !== undefined) {
89
+ const exact = _compileContexts.get(contextKey(dir, prefix));
90
+ if (exact) {
91
+ return exact;
92
+ }
93
+ }
94
+ const dirMatch = soleContextForPagesDir(dir);
95
+ if (dirMatch) {
96
+ return dirMatch;
97
+ }
98
+ }
99
+ if (prefix !== undefined) {
100
+ const prefixMatch = contextForPrefix(prefix);
101
+ if (prefixMatch) {
102
+ return prefixMatch;
103
+ }
104
+ }
105
+ if (_compileContexts.size === 1) {
106
+ return _compileContexts.values().next().value ?? null;
107
+ }
108
+ return null;
109
+ }
110
+
111
+ /**
112
+ * The sole context registered for `dir`, or null when none matches — or when
113
+ * SEVERAL do (the same pagesDir mounted at two prefixes): guessing there
114
+ * would hand one mount the other's assets/build ID.
115
+ */
116
+ function soleContextForPagesDir(dir: string): CompileContext | null {
117
+ let match: CompileContext | null = null;
118
+ for (const ctx of _compileContexts.values()) {
119
+ if (pagesDirOf(ctx) !== dir) {
120
+ continue;
121
+ }
122
+ if (match) {
123
+ return null;
124
+ }
125
+ match = ctx;
126
+ }
127
+ return match;
128
+ }
129
+
130
+ function contextForPrefix(prefix: string): CompileContext | null {
131
+ for (const ctx of _compileContexts.values()) {
132
+ if ((ctx.prefix ?? "") === prefix) {
133
+ return ctx;
134
+ }
135
+ }
136
+ return null;
46
137
  }
47
138
 
48
- export function getCompileContext(): CompileContext | null {
49
- return _compileCtx;
139
+ /** All registered contexts, keyed by the composite (pagesDir, prefix) key. */
140
+ export function getAllCompileContexts(): ReadonlyMap<string, CompileContext> {
141
+ return _compileContexts;
50
142
  }
51
143
 
52
144
  export function __resetCompileContext(): void {
53
- _compileCtx = null;
145
+ _compileContexts.clear();
146
+ // A test tearing down compile contexts is tearing down its furin mounts —
147
+ // forget their prefix registrations too so the next test mounts cleanly.
148
+ __clearInstanceRegistry();
54
149
  }
@@ -1,7 +1,8 @@
1
1
  import { renderToReadableStream } from "react-dom/server";
2
- import { normalizeHref, type RouterContextValue } from "../../client/router/index.ts";
2
+ import { normalizeHref, type RouterContextValue, toLogical } from "../../client/router/index.ts";
3
3
  import { FurinNotFoundError } from "../../shared/not-found.ts";
4
4
  import { useLogger } from "../context-logger.ts";
5
+ import { currentInstance } from "../instance.ts";
5
6
  import type { RootLayout } from "../router/index.ts";
6
7
  import { IS_DEV } from "../runtime-env.ts";
7
8
  import { assembleHTML, streamToString } from "./assemble.ts";
@@ -40,9 +41,14 @@ export async function renderRootNotFound(
40
41
  }
41
42
  const notFoundError = new FurinNotFoundError(undefined);
42
43
 
44
+ // The request-scope wrap binds the path-resolved instance before this
45
+ // handler runs, so its prefix is the basePath — SSR'd links on the 404
46
+ // page must be physical (prefixed), and currentHref logical, exactly like
47
+ // the regular render pipeline.
48
+ const basePath = currentInstance().prefix;
43
49
  const notFoundContext: RouterContextValue = {
44
- basePath: "",
45
- currentHref: request ? normalizeHref(new URL(request.url).pathname) : "/",
50
+ basePath,
51
+ currentHref: request ? normalizeHref(toLogical(new URL(request.url).pathname, basePath)) : "/",
46
52
  search: {},
47
53
  searchRoutes: [],
48
54
  navigate: (_href, _opts) => Promise.resolve(),
@@ -9,6 +9,7 @@ import {
9
9
  RouterContext,
10
10
  type RouterContextValue,
11
11
  SearchStoreContext,
12
+ toLogical,
12
13
  } from "../../client/router/index.ts";
13
14
  import {
14
15
  createSearchStore,
@@ -18,6 +19,7 @@ import { computeErrorDigest } from "../../shared/digest.ts";
18
19
  import type { SearchParamsInput, SearchRouteMetadata } from "../../shared/search-params.ts";
19
20
  import { autoInvalidateRegistry } from "../auto-invalidate/registry.ts";
20
21
  import { runInSyntheticRenderScope, useLogger } from "../context-logger.ts";
22
+ import { currentInstance } from "../instance.ts";
21
23
  // FurinNotFoundError is used indirectly via buildNotFoundElement in element.tsx
22
24
  import type { ResolvedRoute, RootLayout } from "../router/index.ts";
23
25
  import { IS_DEV } from "../runtime-env.ts";
@@ -170,10 +172,16 @@ export function assertDeferredModeAllowed(
170
172
  }
171
173
  }
172
174
 
173
- function currentHrefFromContext(ctx: Context): string {
175
+ function currentHrefFromContext(ctx: Context, basePath: string): string {
174
176
  const pathUrl = new URL(ctx.path, "http://furin.local");
175
177
  const requestUrl = new URL(ctx.request.url);
176
- return normalizeHref(pathUrl.pathname) + (pathUrl.search || requestUrl.search);
178
+ // For a prefixed Elysia plugin `ctx.path` is PHYSICAL (includes the mount
179
+ // prefix). `RouterContextValue.currentHref` must be LOGICAL — the client
180
+ // provider strips basePath the same way — or Link active-state and SSR/CSR
181
+ // markup diverge. Synthetic renders pass logical paths; toLogical no-ops.
182
+ return (
183
+ normalizeHref(toLogical(pathUrl.pathname, basePath)) + (pathUrl.search || requestUrl.search)
184
+ );
177
185
  }
178
186
 
179
187
  /**
@@ -290,9 +298,13 @@ export async function prepareRender(
290
298
  status = success.status;
291
299
  }
292
300
 
301
+ // Explicit basePath (static export) wins; otherwise resolve the mount
302
+ // prefix of the instance serving this render so SSR'd <Link> hrefs match
303
+ // the prefix-aware client hydration entry (built with `basePath: prefix`).
304
+ const resolvedBasePath = basePath ?? currentInstance().prefix;
293
305
  const ssrContext: RouterContextValue = {
294
- basePath: basePath ?? "",
295
- currentHref: currentHrefFromContext(ctx),
306
+ basePath: resolvedBasePath,
307
+ currentHref: currentHrefFromContext(ctx, resolvedBasePath),
296
308
  search: (ctx.query as SearchParamsInput | undefined) ?? {},
297
309
  searchRoutes: searchRoutes ?? [],
298
310
  navigate: (_href, _opts) => Promise.resolve(),
@@ -1,47 +1,77 @@
1
- // ── Dev template ─────────────────────────────────────────────────────────────
1
+ // ── HTML template state (per furin instance) ────────────────────────────────
2
2
 
3
3
  import { readFileSync } from "node:fs";
4
+ import {
5
+ allStateBuckets,
6
+ currentInstance,
7
+ defaultInstanceBucket,
8
+ type FurinInstance,
9
+ instanceSlot,
10
+ } from "../instance.ts";
4
11
 
5
- let _prodTemplatePath: string | null = null;
6
- let _prodTemplateContent: string | null = null;
12
+ interface TemplateState {
13
+ devCache: { html: string; ts: number } | null;
14
+ prodContent: string | null;
15
+ prodPath: string | null;
16
+ }
17
+
18
+ const instanceTemplateState = instanceSlot(
19
+ (): TemplateState => ({ devCache: null, prodContent: null, prodPath: null })
20
+ );
7
21
 
8
- /** Dev template cache — avoids a loopback HTTP fetch on every SSR request. */
9
- let _devTemplateCache: { html: string; ts: number } | null = null;
10
22
  const DEV_TEMPLATE_TTL_MS = 1000;
11
23
 
12
24
  export async function getDevTemplate(origin: string): Promise<string> {
13
- if (_devTemplateCache && Date.now() - _devTemplateCache.ts < DEV_TEMPLATE_TTL_MS) {
14
- return _devTemplateCache.html;
25
+ const instance = currentInstance();
26
+ const state = instanceTemplateState(instance);
27
+ if (state.devCache && Date.now() - state.devCache.ts < DEV_TEMPLATE_TTL_MS) {
28
+ return state.devCache.html;
15
29
  }
16
- const r = await fetch(`${origin}/_bun_hmr_entry`);
30
+ // Each instance's HMR entry is mounted under its own prefix.
31
+ const entryPath = `${instance.prefix}/_bun_hmr_entry`;
32
+ const r = await fetch(`${origin}${entryPath}`);
17
33
  if (!r.ok) {
18
- throw new Error(`/_bun_hmr_entry returned ${r.status}`);
34
+ throw new Error(`${entryPath} returned ${r.status}`);
19
35
  }
20
36
  const html = await r.text();
21
- _devTemplateCache = { html, ts: Date.now() };
37
+ state.devCache = { html, ts: Date.now() };
22
38
  return html;
23
39
  }
24
40
 
25
- export function setProductionTemplatePath(path: string | null): void {
26
- _prodTemplatePath = path;
27
- _prodTemplateContent = null;
41
+ export function setProductionTemplatePath(path: string | null, instance?: FurinInstance): void {
42
+ const state = instanceTemplateState(instance);
43
+ state.prodPath = path;
44
+ state.prodContent = null;
28
45
  }
29
46
 
30
- export function setProductionTemplateContent(content: string): void {
31
- _prodTemplatePath = null;
32
- _prodTemplateContent = content;
47
+ export function setProductionTemplateContent(content: string, instance?: FurinInstance): void {
48
+ const state = instanceTemplateState(instance);
49
+ state.prodPath = null;
50
+ state.prodContent = content;
33
51
  }
34
52
 
35
53
  export function getProductionTemplate(): string | null {
36
- if (_prodTemplateContent !== null) {
37
- return _prodTemplateContent;
54
+ const own = readTemplate(instanceTemplateState());
55
+ if (own !== null) {
56
+ return own;
57
+ }
58
+ // Config-before-mount fallback: `setProductionTemplateContent()` called
59
+ // before any furin() registration lands on the default bucket — treat that
60
+ // as a process-wide default template.
61
+ const fallback = instanceTemplateState(defaultInstanceBucket());
62
+ return readTemplate(fallback);
63
+ }
64
+
65
+ function readTemplate(state: TemplateState): string | null {
66
+ if (state.prodContent !== null) {
67
+ return state.prodContent;
38
68
  }
39
- if (!_prodTemplatePath) {
69
+ if (!state.prodPath) {
40
70
  return null;
41
71
  }
42
72
  try {
43
- _prodTemplateContent = readFileSync(_prodTemplatePath, "utf8");
44
- return _prodTemplateContent;
73
+ state.prodContent = readFileSync(state.prodPath, "utf8");
74
+ return state.prodContent;
45
75
  } catch {
46
76
  return null;
47
77
  }
@@ -49,7 +79,10 @@ export function getProductionTemplate(): string | null {
49
79
 
50
80
  /** @internal test-only — resets all template state */
51
81
  export function __resetTemplateState(): void {
52
- _prodTemplatePath = null;
53
- _prodTemplateContent = null;
54
- _devTemplateCache = null;
82
+ for (const instance of allStateBuckets()) {
83
+ const state = instanceTemplateState(instance);
84
+ state.devCache = null;
85
+ state.prodContent = null;
86
+ state.prodPath = null;
87
+ }
55
88
  }
@@ -1,7 +1,10 @@
1
1
  import { AsyncLocalStorage } from "node:async_hooks";
2
+ import { allInstances, currentInstance } from "../instance.ts";
2
3
 
3
4
  const SYNC_STREAM_DEFAULT_PATH = "/_furin/sync";
4
5
 
6
+ // Explicit override scope (tests, synthetic renders). When unset, the sync
7
+ // stream path comes from the current furin instance.
5
8
  const requestSyncStreamPath = new AsyncLocalStorage<string | undefined>();
6
9
 
7
10
  export type FurinSyncOption =
@@ -20,10 +23,38 @@ export function resolveSyncStreamPath(sync: FurinSyncOption | undefined): string
20
23
  return sync.streamPath ?? SYNC_STREAM_DEFAULT_PATH;
21
24
  }
22
25
 
26
+ /**
27
+ * Logical (unprefixed) sync stream path for the current request — injected
28
+ * into rendered HTML; the client prepends its own basePath before connecting.
29
+ */
23
30
  export function getSyncStreamPath(): string | undefined {
24
- return requestSyncStreamPath.getStore();
31
+ const override = requestSyncStreamPath.getStore();
32
+ if (override !== undefined) {
33
+ return override;
34
+ }
35
+ return currentInstance().syncStreamPath;
25
36
  }
26
37
 
27
38
  export function runWithSyncStreamPath<T>(path: string | undefined, fn: () => T): T {
28
39
  return requestSyncStreamPath.run(path, fn);
29
40
  }
41
+
42
+ /**
43
+ * Physical adapter channels a sync publication must reach. An explicit
44
+ * override wins (historical single-channel behaviour); otherwise every
45
+ * sync-enabled instance gets notified — a mutation on a shared API must wake
46
+ * the SSE clients of every mounted app.
47
+ */
48
+ export function syncPublishChannels(): string[] {
49
+ const override = requestSyncStreamPath.getStore();
50
+ if (override !== undefined) {
51
+ return [override];
52
+ }
53
+ const channels = allInstances()
54
+ .filter((instance) => instance.syncStreamPath !== undefined)
55
+ .map((instance) => `${instance.prefix}${instance.syncStreamPath}`);
56
+ if (channels.length > 0) {
57
+ return channels;
58
+ }
59
+ return [SYNC_STREAM_DEFAULT_PATH];
60
+ }
@@ -5,10 +5,10 @@ import {
5
5
  runInvalidationRules,
6
6
  } from "../auto-invalidate/runtime.ts";
7
7
  import type { InvalidationInput } from "../auto-invalidate/types.ts";
8
- import { getSyncStreamPath } from "./config.ts";
9
8
  import { createMutationFingerprint } from "./fingerprint.ts";
10
9
  import { memorySyncAdapter } from "./memory-adapter.ts";
11
10
  import { replayResponse, storeResponse } from "./response.ts";
11
+ import { publishSyncInvalidation } from "./stream.ts";
12
12
 
13
13
  export type SyncRouteOption =
14
14
  | false
@@ -190,10 +190,9 @@ export function furinSync() {
190
190
  activeMutations.delete(ctx.request);
191
191
 
192
192
  if (pending.length > 0) {
193
- await memorySyncAdapter.appendChanges({
194
- invalidations: pending,
195
- path: getSyncStreamPath() ?? "/_furin/sync",
196
- });
193
+ // Notify every mounted app's sync stream — a mutation on a shared API
194
+ // may invalidate pages rendered by any of them.
195
+ publishSyncInvalidation(pending);
197
196
  }
198
197
  })
199
198
  .onError({ as: "global" }, ({ request }) => abortMutation(request));