@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.
- package/dist/adapter/bun.d.ts +17 -1
- package/dist/adapter/package.d.ts +26 -0
- package/dist/build/client.d.ts +1 -1
- package/dist/build/compile-entry.d.ts +3 -3
- package/dist/build/compile-entry.ts +88 -83
- package/dist/build/entry-template.d.ts +35 -9
- package/dist/build/entry-template.ts +106 -56
- package/dist/build/hydrate.d.ts +1 -1
- package/dist/build/index.js +643 -247
- package/dist/build/scan-server.d.ts +10 -4
- package/dist/build/server-routes-entry.d.ts +3 -3
- package/dist/build/server-routes-entry.ts +5 -11
- package/dist/build/ssg-cache.d.ts +1 -1
- package/dist/build/types.d.ts +36 -1
- package/dist/cli/config.d.ts +6 -1
- package/dist/cli/index.js +662 -260
- package/dist/config.d.ts +11 -2
- package/dist/config.js +5 -1
- package/dist/furin.d.ts +36 -18
- package/dist/furin.js +630 -310
- package/dist/server/auto-invalidate/registry.d.ts +8 -1
- package/dist/server/cache/dev-loader.d.ts +3 -2
- package/dist/server/cache/invalidation.d.ts +19 -0
- package/dist/server/cache/isr.d.ts +6 -2
- package/dist/server/cache/registry.d.ts +3 -3
- package/dist/server/cache/ssg.d.ts +6 -2
- package/dist/server/cache/store-view.d.ts +11 -0
- package/dist/server/instance.d.ts +86 -0
- package/dist/server/internal.d.ts +16 -1
- package/dist/server/internal.js +72 -5
- package/dist/server/render/template.d.ts +3 -2
- package/dist/server/sync/config.d.ts +11 -0
- package/dist/server/sync/stream.d.ts +8 -1
- package/dist/shared/prefix.d.ts +15 -0
- package/package.json +6 -1
- package/src/adapter/bun.ts +113 -50
- package/src/adapter/package.ts +206 -0
- package/src/build/client.ts +9 -3
- package/src/build/compile-entry.ts +88 -83
- package/src/build/entry-template.ts +106 -56
- package/src/build/hydrate.ts +4 -2
- package/src/build/index.ts +99 -28
- package/src/build/scan-server.ts +23 -7
- package/src/build/server-routes-entry.ts +5 -11
- package/src/build/ssg-cache.ts +6 -2
- package/src/build/types.ts +37 -1
- package/src/cli/config.ts +9 -3
- package/src/cli/index.ts +21 -3
- package/src/config.ts +14 -1
- package/src/furin.ts +297 -143
- package/src/server/auto-invalidate/registry.ts +23 -1
- package/src/server/auto-invalidate/runtime.ts +29 -4
- package/src/server/cache/dev-loader.ts +77 -38
- package/src/server/cache/invalidation.ts +71 -30
- package/src/server/cache/isr.ts +20 -5
- package/src/server/cache/registry.ts +17 -20
- package/src/server/cache/ssg.ts +19 -4
- package/src/server/cache/store-view.ts +30 -0
- package/src/server/instance.ts +252 -0
- package/src/server/internal.ts +100 -5
- package/src/server/render/not-found.ts +9 -3
- package/src/server/render/ssr.ts +16 -4
- package/src/server/render/template.ts +57 -24
- package/src/server/sync/config.ts +32 -1
- package/src/server/sync/plugin.ts +4 -5
- package/src/server/sync/stream.ts +19 -9
- package/src/shared/prefix.ts +38 -0
package/src/furin.ts
CHANGED
|
@@ -5,13 +5,20 @@ import { staticPlugin } from "@elysiajs/static";
|
|
|
5
5
|
import { type AnyElysia, Elysia, file } from "elysia";
|
|
6
6
|
import { type DrainContext, initLogger } from "evlog";
|
|
7
7
|
import { type EvlogElysiaOptions, evlog } from "evlog/elysia";
|
|
8
|
-
import {
|
|
9
|
-
_runWithRequestInvalidationScope,
|
|
10
|
-
consumePendingInvalidations,
|
|
11
|
-
getBuildId,
|
|
12
|
-
setBuildId,
|
|
13
|
-
} from "./server/cache/invalidation.ts";
|
|
8
|
+
import { consumePendingInvalidations } from "./server/cache/invalidation.ts";
|
|
14
9
|
import { setSSGCache } from "./server/cache/ssg.ts";
|
|
10
|
+
import {
|
|
11
|
+
assertPrefixAvailable,
|
|
12
|
+
createInstance,
|
|
13
|
+
type FurinInstance,
|
|
14
|
+
hasRequestScope,
|
|
15
|
+
markTraffic,
|
|
16
|
+
normalizePrefix,
|
|
17
|
+
registerInstance,
|
|
18
|
+
resolveInstanceByPath,
|
|
19
|
+
runWithInstanceScope,
|
|
20
|
+
withInstance,
|
|
21
|
+
} from "./server/instance.ts";
|
|
15
22
|
import type { CompileContext, EmbeddedAppData } from "./server/internal.ts";
|
|
16
23
|
import { getCompileContext } from "./server/internal.ts";
|
|
17
24
|
import { renderRootNotFound, warmSSGCache } from "./server/render/index.ts";
|
|
@@ -30,7 +37,6 @@ import {
|
|
|
30
37
|
createSyncStreamPlugin,
|
|
31
38
|
type FurinSyncOption,
|
|
32
39
|
resolveSyncStreamPath,
|
|
33
|
-
runWithSyncStreamPath,
|
|
34
40
|
} from "./server/sync/index.ts";
|
|
35
41
|
|
|
36
42
|
// biome-ignore lint/suspicious/noEmptyInterface: intentionally augmentable via furin-env.d.ts
|
|
@@ -38,24 +44,33 @@ export interface FurinCacheTags {}
|
|
|
38
44
|
|
|
39
45
|
export type CacheTag = keyof FurinCacheTags extends never ? string : keyof FurinCacheTags;
|
|
40
46
|
|
|
41
|
-
|
|
47
|
+
import { clientDirNameForPrefix } from "./shared/prefix.ts";
|
|
48
|
+
|
|
49
|
+
// biome-ignore lint/performance/noBarrelFile: furin.ts is the public package entry
|
|
50
|
+
export { clientDirNameForPrefix } from "./shared/prefix.ts";
|
|
51
|
+
|
|
52
|
+
function resolveClientDirFromArgv(prefix: string): string {
|
|
53
|
+
const dirName = clientDirNameForPrefix(prefix);
|
|
42
54
|
return (
|
|
43
|
-
resolveClientDirFromEnv() ??
|
|
44
|
-
resolveClientDirFromModuleUrl() ??
|
|
45
|
-
resolveClientDirFromProcessArgs() ??
|
|
46
|
-
resolveFallbackClientDir()
|
|
55
|
+
resolveClientDirFromEnv(dirName) ??
|
|
56
|
+
resolveClientDirFromModuleUrl(dirName) ??
|
|
57
|
+
resolveClientDirFromProcessArgs(dirName) ??
|
|
58
|
+
resolveFallbackClientDir(dirName)
|
|
47
59
|
);
|
|
48
60
|
}
|
|
49
61
|
|
|
50
|
-
function resolveClientDirFromEnv(): string | null {
|
|
62
|
+
function resolveClientDirFromEnv(dirName: string): string | null {
|
|
51
63
|
const envClientDir = process.env.FURIN_CLIENT_DIR;
|
|
52
64
|
if (!envClientDir) {
|
|
53
65
|
return null;
|
|
54
66
|
}
|
|
55
|
-
|
|
67
|
+
const base = envClientDir.startsWith("/") ? envClientDir : resolve(process.cwd(), envClientDir);
|
|
68
|
+
// FURIN_CLIENT_DIR points at the ROOT instance's client dir; sibling
|
|
69
|
+
// instances live next to it under their own dir name.
|
|
70
|
+
return dirName === "client" ? base : join(dirname(base), dirName);
|
|
56
71
|
}
|
|
57
72
|
|
|
58
|
-
function resolveClientDirFromModuleUrl(): string | null {
|
|
73
|
+
function resolveClientDirFromModuleUrl(dirName: string): string | null {
|
|
59
74
|
try {
|
|
60
75
|
const moduleUrl = new URL(import.meta.url);
|
|
61
76
|
if (moduleUrl.protocol !== "file:") {
|
|
@@ -65,7 +80,7 @@ function resolveClientDirFromModuleUrl(): string | null {
|
|
|
65
80
|
if (modulePath.includes("/$bunfs/")) {
|
|
66
81
|
return null;
|
|
67
82
|
}
|
|
68
|
-
const moduleClientDir = join(dirname(modulePath),
|
|
83
|
+
const moduleClientDir = join(dirname(modulePath), dirName);
|
|
69
84
|
if (existsSync(join(moduleClientDir, "index.html"))) {
|
|
70
85
|
return moduleClientDir;
|
|
71
86
|
}
|
|
@@ -75,7 +90,7 @@ function resolveClientDirFromModuleUrl(): string | null {
|
|
|
75
90
|
return null;
|
|
76
91
|
}
|
|
77
92
|
|
|
78
|
-
function resolveClientDirFromProcessArgs(): string | null {
|
|
93
|
+
function resolveClientDirFromProcessArgs(dirName: string): string | null {
|
|
79
94
|
const candidates = [
|
|
80
95
|
process.argv[1],
|
|
81
96
|
process.argv[0],
|
|
@@ -84,7 +99,7 @@ function resolveClientDirFromProcessArgs(): string | null {
|
|
|
84
99
|
].filter((value): value is string => typeof value === "string" && value.length > 0);
|
|
85
100
|
|
|
86
101
|
for (const candidate of candidates) {
|
|
87
|
-
const resolved = resolveClientDirFromCandidate(candidate);
|
|
102
|
+
const resolved = resolveClientDirFromCandidate(candidate, dirName);
|
|
88
103
|
if (resolved) {
|
|
89
104
|
return resolved;
|
|
90
105
|
}
|
|
@@ -93,7 +108,7 @@ function resolveClientDirFromProcessArgs(): string | null {
|
|
|
93
108
|
return null;
|
|
94
109
|
}
|
|
95
110
|
|
|
96
|
-
function resolveClientDirFromCandidate(candidate: string): string | null {
|
|
111
|
+
function resolveClientDirFromCandidate(candidate: string, dirName: string): string | null {
|
|
97
112
|
const name = basename(candidate);
|
|
98
113
|
if (name === "bun" || name === "node") {
|
|
99
114
|
return null;
|
|
@@ -104,46 +119,47 @@ function resolveClientDirFromCandidate(candidate: string): string | null {
|
|
|
104
119
|
|
|
105
120
|
const absolute = candidate.startsWith("/") ? candidate : resolve(process.cwd(), candidate);
|
|
106
121
|
if (existsSync(absolute)) {
|
|
107
|
-
return join(dirname(absolute),
|
|
122
|
+
return join(dirname(absolute), dirName);
|
|
108
123
|
}
|
|
109
124
|
|
|
110
125
|
if (!candidate.includes("/")) {
|
|
111
|
-
return resolveClientDirFromPath(candidate);
|
|
126
|
+
return resolveClientDirFromPath(candidate, dirName);
|
|
112
127
|
}
|
|
113
128
|
|
|
114
129
|
return null;
|
|
115
130
|
}
|
|
116
131
|
|
|
117
|
-
function resolveClientDirFromPath(candidate: string): string | null {
|
|
132
|
+
function resolveClientDirFromPath(candidate: string, dirName: string): string | null {
|
|
118
133
|
const pathEntries = process.env.PATH?.split(":") ?? [];
|
|
119
134
|
for (const dir of pathEntries) {
|
|
120
135
|
const fullPath = join(dir, candidate);
|
|
121
136
|
if (existsSync(fullPath)) {
|
|
122
|
-
return join(dirname(fullPath),
|
|
137
|
+
return join(dirname(fullPath), dirName);
|
|
123
138
|
}
|
|
124
139
|
}
|
|
125
140
|
return null;
|
|
126
141
|
}
|
|
127
142
|
|
|
128
|
-
function resolveFallbackClientDir(): string {
|
|
129
|
-
const defaultClientDir = resolve(process.cwd(), ".furin/build/bun
|
|
143
|
+
function resolveFallbackClientDir(dirName: string): string {
|
|
144
|
+
const defaultClientDir = resolve(process.cwd(), ".furin/build/bun", dirName);
|
|
130
145
|
if (existsSync(join(defaultClientDir, "index.html"))) {
|
|
131
146
|
return defaultClientDir;
|
|
132
147
|
}
|
|
133
148
|
|
|
134
|
-
return join(process.cwd(),
|
|
149
|
+
return join(process.cwd(), dirName);
|
|
135
150
|
}
|
|
136
151
|
|
|
137
152
|
async function setupProdTemplate(
|
|
138
153
|
embedded: EmbeddedAppData | undefined,
|
|
139
|
-
clientDir: string
|
|
154
|
+
clientDir: string,
|
|
155
|
+
instance: FurinInstance
|
|
140
156
|
): Promise<void> {
|
|
141
157
|
if (embedded) {
|
|
142
158
|
if (!embedded.template) {
|
|
143
159
|
throw new Error("[furin] Embedded app is missing its HTML template (index.html).");
|
|
144
160
|
}
|
|
145
161
|
const html = await Bun.file(embedded.template).text();
|
|
146
|
-
setProductionTemplateContent(html);
|
|
162
|
+
setProductionTemplateContent(html, instance);
|
|
147
163
|
return;
|
|
148
164
|
}
|
|
149
165
|
|
|
@@ -151,88 +167,40 @@ async function setupProdTemplate(
|
|
|
151
167
|
if (!existsSync(templatePath)) {
|
|
152
168
|
throw new Error("[furin] No pre-built assets found. Run `bun run build` first.");
|
|
153
169
|
}
|
|
154
|
-
setProductionTemplatePath(templatePath);
|
|
170
|
+
setProductionTemplatePath(templatePath, instance);
|
|
155
171
|
}
|
|
156
172
|
|
|
157
173
|
/**
|
|
158
|
-
*
|
|
159
|
-
*
|
|
160
|
-
* `
|
|
161
|
-
*
|
|
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
|
-
* ```
|
|
174
|
+
* Shape of one browser-submitted log event. The named keys are the dangerous
|
|
175
|
+
* ones stripped before `log.set` (prototype-pollution vectors, plus the
|
|
176
|
+
* browser `environment` which must not overwrite the server's); everything
|
|
177
|
+
* else is forwarded as-is.
|
|
199
178
|
*/
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
}
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
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);
|
|
179
|
+
type FurinBrowserEvent = {
|
|
180
|
+
__proto__?: unknown;
|
|
181
|
+
constructor?: unknown;
|
|
182
|
+
prototype?: unknown;
|
|
183
|
+
environment?: unknown;
|
|
184
|
+
} & Record<string, unknown>;
|
|
185
|
+
|
|
186
|
+
/** Evlog wide-event plugin + browser log ingest endpoint for one instance. */
|
|
187
|
+
function createLoggerPlugin(
|
|
188
|
+
prefix: string,
|
|
189
|
+
syncStreamPath: string | undefined,
|
|
190
|
+
logger: EvlogElysiaOptions | undefined
|
|
191
|
+
): Elysia {
|
|
223
192
|
const { exclude: userExclude, ...evlogOptions } = logger ?? {};
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
const loggerPlugin = new Elysia()
|
|
193
|
+
return new Elysia()
|
|
227
194
|
.use(
|
|
228
195
|
evlog({
|
|
229
196
|
...evlogOptions,
|
|
197
|
+
// Exclude patterns match the PHYSICAL request path — prefix them.
|
|
230
198
|
exclude: [
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
...(syncStreamPath ? [syncStreamPath] : []),
|
|
199
|
+
`${prefix}/_client/**`,
|
|
200
|
+
`${prefix}/public/**`,
|
|
201
|
+
`${prefix}/favicon.ico`,
|
|
202
|
+
`${prefix}/_bun_hmr_entry/**`,
|
|
203
|
+
...(syncStreamPath ? [`${prefix}${syncStreamPath}`] : []),
|
|
236
204
|
// Note: /_furin/data is logged with the *logical* path rewritten by
|
|
237
205
|
// createDataEndpoint via useLogger().set({ path }), so SPA navigations
|
|
238
206
|
// appear as "GET /board/123 200" — same shape as a normal SSR nav.
|
|
@@ -257,7 +225,7 @@ export async function furin({
|
|
|
257
225
|
continue;
|
|
258
226
|
}
|
|
259
227
|
// Pick only safe, known fields from the event to prevent prototype pollution
|
|
260
|
-
const event = entry.event as
|
|
228
|
+
const event = entry.event as FurinBrowserEvent | undefined;
|
|
261
229
|
if (!event || typeof event !== "object") {
|
|
262
230
|
continue;
|
|
263
231
|
}
|
|
@@ -267,26 +235,142 @@ export async function furin({
|
|
|
267
235
|
prototype,
|
|
268
236
|
environment: _browserEnv,
|
|
269
237
|
...safeEvent
|
|
270
|
-
} = event
|
|
238
|
+
} = event;
|
|
271
239
|
log.set({ ...safeEvent, service: "furin:browser" });
|
|
272
240
|
}
|
|
273
241
|
return status("No Content");
|
|
274
242
|
},
|
|
275
243
|
{ parse: "json" }
|
|
276
|
-
);
|
|
244
|
+
) as unknown as Elysia;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* Registers a HigherOrderFunction on the Elysia instance so that every request
|
|
249
|
+
* runs inside a fresh instance-bound `AsyncLocalStorage` scope. This isolates
|
|
250
|
+
* `pendingInvalidations` per request AND binds the request to the furin
|
|
251
|
+
* instance that owns its path, so render/cache code resolves the right
|
|
252
|
+
* per-instance state (build ID, template, caches, sync path).
|
|
253
|
+
*
|
|
254
|
+
* Uses `app.wrap()` (Elysia HigherOrderFunction) instead of mutating
|
|
255
|
+
* `app.handle`, because handle mutations are lost when the Furin plugin is
|
|
256
|
+
* `.use()`-d by a parent Elysia instance. HigherOrderFunctions survive the
|
|
257
|
+
* plugin merge and wrap the entire composed `map` handler.
|
|
258
|
+
*
|
|
259
|
+
* IMPORTANT — multi-instance: HigherOrderFunctions apply to the WHOLE parent
|
|
260
|
+
* app, so with N mounted furin instances all N wraps run stacked on every
|
|
261
|
+
* request. The scope guard makes the wrap idempotent (first one wins) and the
|
|
262
|
+
* owning instance is resolved from the request PATH, never from this
|
|
263
|
+
* closure — which wrap executes first is therefore irrelevant.
|
|
264
|
+
*/
|
|
265
|
+
function wrapWithRequestScope(app: AnyElysia): Elysia {
|
|
266
|
+
return app.wrap((handler, request) => (ctx: unknown) => {
|
|
267
|
+
if (hasRequestScope()) {
|
|
268
|
+
return handler(ctx);
|
|
269
|
+
}
|
|
270
|
+
markTraffic();
|
|
271
|
+
const req = request ?? (ctx as { request?: Request } | undefined)?.request;
|
|
272
|
+
const pathname = req ? new URL(req.url).pathname : "/";
|
|
273
|
+
return runWithInstanceScope(resolveInstanceByPath(pathname), () => handler(ctx));
|
|
274
|
+
});
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
function hydrateSSGCacheFromCompileContext(ctx: CompileContext): void {
|
|
278
|
+
if (!ctx.ssgCache) {
|
|
279
|
+
return;
|
|
280
|
+
}
|
|
281
|
+
for (const [path, entry] of Object.entries(ctx.ssgCache)) {
|
|
282
|
+
setSSGCache(path, entry);
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/** Options for the {@link furin} plugin. */
|
|
287
|
+
export interface FurinOptions {
|
|
288
|
+
/**
|
|
289
|
+
* Production only: explicit directory holding this app's built client
|
|
290
|
+
* assets (chunks + index.html template). Packaged furin apps pass their own
|
|
291
|
+
* `dist/furin/client` here; when omitted the directory is auto-resolved
|
|
292
|
+
* next to the server artifact.
|
|
293
|
+
*/
|
|
294
|
+
clientDir?: string;
|
|
295
|
+
/**
|
|
296
|
+
* Initialize the browser HTTP log drain in the hydration entry. Off by
|
|
297
|
+
* default — enabling it adds `evlog/http` drain setup and points browser
|
|
298
|
+
* events at `/_furin/ingest`. Server-side logging is configured via `logger`
|
|
299
|
+
* and unaffected.
|
|
300
|
+
*/
|
|
301
|
+
clientLogging?: boolean;
|
|
302
|
+
logger?: EvlogElysiaOptions;
|
|
303
|
+
pagesDir?: string;
|
|
304
|
+
/**
|
|
305
|
+
* Mount prefix for this app, e.g. `"/admin"`. All pages, framework
|
|
306
|
+
* endpoints (`/_furin/*`) and client assets (`/_client/*`) are served under
|
|
307
|
+
* it, and the client bundle is built with the matching basePath. Defaults
|
|
308
|
+
* to `""` (root). Mounting two furin instances on the same prefix throws.
|
|
309
|
+
*/
|
|
310
|
+
prefix?: string;
|
|
311
|
+
/**
|
|
312
|
+
* Enables Furin's built-in sync event stream. The opinionated default mounts
|
|
313
|
+
* Server-Sent Events at `/_furin/sync`; pass an object only for constrained
|
|
314
|
+
* reverse-proxy deployments that need a custom internal path.
|
|
315
|
+
*/
|
|
316
|
+
sync?: FurinSyncOption;
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
/**
|
|
320
|
+
* Main Furin plugin.
|
|
321
|
+
*
|
|
322
|
+
* Returns a standalone Elysia instance (async function) so that routes are
|
|
323
|
+
* properly registered in Elysia's router for SPA navigation to work.
|
|
324
|
+
*
|
|
325
|
+
* ## Usage
|
|
326
|
+
*
|
|
327
|
+
* ```ts
|
|
328
|
+
* new Elysia()
|
|
329
|
+
* .use(await furin({ pagesDir: "./src/pages" }))
|
|
330
|
+
* .use(await furin({ pagesDir: "./src/admin", prefix: "/admin" }))
|
|
331
|
+
* .listen(3000)
|
|
332
|
+
* ```
|
|
333
|
+
*/
|
|
334
|
+
export async function furin({
|
|
335
|
+
pagesDir,
|
|
336
|
+
prefix: rawPrefix,
|
|
337
|
+
clientDir: explicitClientDir,
|
|
338
|
+
logger,
|
|
339
|
+
clientLogging,
|
|
340
|
+
sync,
|
|
341
|
+
}: FurinOptions = {}) {
|
|
342
|
+
const prefix = normalizePrefix(rawPrefix);
|
|
343
|
+
const syncStreamPath = resolveSyncStreamPath(sync);
|
|
344
|
+
initLogger({ env: { service: "furin" } });
|
|
345
|
+
const loggerPlugin = createLoggerPlugin(prefix, syncStreamPath, logger);
|
|
277
346
|
|
|
278
347
|
const cwd = process.cwd();
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
348
|
+
// The pagesDir param drives which compile context this instance loads. In a
|
|
349
|
+
// deployed binary the cwd-resolved path may miss the build-time key — the
|
|
350
|
+
// lookup then falls back to the (stable) prefix, then to the sole context.
|
|
351
|
+
const paramPagesDir = resolve(cwd, pagesDir ?? "src/pages");
|
|
352
|
+
const ctx = getCompileContext(paramPagesDir, prefix);
|
|
353
|
+
const resolvedPagesDir = ctx?.rootPath ? dirname(ctx.rootPath) : paramPagesDir;
|
|
283
354
|
|
|
284
355
|
// Unique name per pagesDir to avoid Elysia's name-based plugin dedup.
|
|
285
|
-
const instanceName = `furin-${resolvedPagesDir.replaceAll("\\", "/")}`;
|
|
356
|
+
const instanceName = `furin-${prefix}-${resolvedPagesDir.replaceAll("\\", "/")}`;
|
|
357
|
+
|
|
358
|
+
// Same prefix + different pagesDir is a mount collision — fail fast, but
|
|
359
|
+
// only REGISTER right before returning so a failed mount leaves no stale
|
|
360
|
+
// registration behind. All per-app runtime state (build ID, caches,
|
|
361
|
+
// template, sync path) hangs off this object; requests are bound to it by
|
|
362
|
+
// path in wrapWithRequestScope.
|
|
363
|
+
const normalizedPagesDir = resolvedPagesDir.replaceAll("\\", "/");
|
|
364
|
+
assertPrefixAvailable(prefix, normalizedPagesDir);
|
|
365
|
+
const instance = createInstance(prefix, normalizedPagesDir);
|
|
366
|
+
instance.syncStreamPath = syncStreamPath;
|
|
286
367
|
|
|
287
368
|
// ── Dev: Bun native HMR ────────────────────────────────────────────────
|
|
288
369
|
if (IS_DEV) {
|
|
289
|
-
|
|
370
|
+
// Each instance gets its own generated-files dir so two mounted apps do
|
|
371
|
+
// not overwrite each other's hydrate entry (root keeps plain `.furin`).
|
|
372
|
+
const instanceSlug = prefix === "" ? "" : prefix.slice(1).replaceAll("/", "__");
|
|
373
|
+
const furinDir = resolve(cwd, ".furin", instanceSlug);
|
|
290
374
|
// Lazy import — build pipeline has native deps not available in compiled binaries
|
|
291
375
|
const { registerDevPagePlugin } = await import("./server/dev-page-plugin.ts");
|
|
292
376
|
registerDevPagePlugin();
|
|
@@ -303,9 +387,12 @@ export async function furin({
|
|
|
303
387
|
{
|
|
304
388
|
outDir: furinDir,
|
|
305
389
|
rootLayout: root.path,
|
|
306
|
-
basePath:
|
|
307
|
-
publicPath:
|
|
390
|
+
basePath: prefix,
|
|
391
|
+
publicPath: `${prefix}/_client/`,
|
|
308
392
|
clientLogging: clientLogging ?? false,
|
|
393
|
+
// furin-env.d.ts is one file at the project root — only the root
|
|
394
|
+
// instance owns it, otherwise mounted apps clobber each other's types.
|
|
395
|
+
skipRouteTypes: prefix !== "",
|
|
309
396
|
},
|
|
310
397
|
cwd
|
|
311
398
|
);
|
|
@@ -313,14 +400,23 @@ export async function furin({
|
|
|
313
400
|
const publicDir = resolve(cwd, "public");
|
|
314
401
|
const publicExists = existsSync(publicDir);
|
|
315
402
|
|
|
316
|
-
|
|
403
|
+
// Routes registered below are LOGICAL — Elysia's `prefix` makes them
|
|
404
|
+
// physical when this plugin is merged into the parent app (child prefixes
|
|
405
|
+
// like staticPlugin's compose underneath).
|
|
406
|
+
const devApp = new Elysia({
|
|
407
|
+
name: instanceName,
|
|
408
|
+
seed: resolvedPagesDir,
|
|
409
|
+
prefix: prefix || undefined,
|
|
410
|
+
})
|
|
317
411
|
.use(loggerPlugin)
|
|
318
|
-
|
|
412
|
+
// Local scope (default) — a global hook would leak onto sibling furin
|
|
413
|
+
// instances mounted on the same parent app.
|
|
414
|
+
.onError(async ({ code, request }) => {
|
|
319
415
|
if (code === "NOT_FOUND") {
|
|
320
416
|
return await renderRootNotFound(root, request);
|
|
321
417
|
}
|
|
322
418
|
})
|
|
323
|
-
.onAfterHandle(
|
|
419
|
+
.onAfterHandle(({ set }) => {
|
|
324
420
|
// Forward pending revalidation paths so the client can bust its prefetch cache
|
|
325
421
|
const pending = consumePendingInvalidations();
|
|
326
422
|
if (pending.length > 0) {
|
|
@@ -338,15 +434,21 @@ export async function furin({
|
|
|
338
434
|
: () => new Response(null, { status: 404 })
|
|
339
435
|
)
|
|
340
436
|
.use(createDevInspectorPlugin())
|
|
341
|
-
.use(
|
|
437
|
+
.use(
|
|
438
|
+
syncStreamPath
|
|
439
|
+
? createSyncStreamPlugin(syncStreamPath, `${prefix}${syncStreamPath}`)
|
|
440
|
+
: new Elysia()
|
|
441
|
+
)
|
|
342
442
|
.use(createDataEndpoint(routes))
|
|
343
|
-
.use((app) =>
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
443
|
+
.use((app) =>
|
|
444
|
+
routes.reduce(
|
|
445
|
+
(chain, route) => chain.use(createRoutePlugin(route, root, undefined, searchRoutes)),
|
|
446
|
+
app
|
|
447
|
+
)
|
|
448
|
+
)
|
|
449
|
+
.use(createNotFoundHandling(prefix, routes, root));
|
|
450
|
+
registerInstance(instance);
|
|
451
|
+
return wrapWithRequestScope(devApp);
|
|
350
452
|
}
|
|
351
453
|
|
|
352
454
|
// ── Production ──────────────────────────────────────────────────────────
|
|
@@ -356,24 +458,35 @@ export async function furin({
|
|
|
356
458
|
const { root, routes } = loadProdRoutes(ctx);
|
|
357
459
|
const searchRoutes = createSearchRouteMetadata(routes);
|
|
358
460
|
const prodBuildId = ctx.buildId ?? "";
|
|
359
|
-
|
|
360
|
-
|
|
461
|
+
instance.buildId = prodBuildId;
|
|
462
|
+
// Init-time writes target THIS instance explicitly — with several mounted
|
|
463
|
+
// apps there is no ambient request scope to resolve it from.
|
|
464
|
+
withInstance(instance, () => {
|
|
465
|
+
hydrateSSGCacheFromCompileContext(ctx);
|
|
466
|
+
});
|
|
361
467
|
|
|
362
468
|
const embedded = ctx?.embedded;
|
|
363
|
-
const clientDir = embedded ? "" : resolveClientDirFromArgv();
|
|
364
|
-
await setupProdTemplate(embedded, clientDir);
|
|
365
|
-
|
|
366
|
-
const
|
|
469
|
+
const clientDir = embedded ? "" : (explicitClientDir ?? resolveClientDirFromArgv(prefix));
|
|
470
|
+
await setupProdTemplate(embedded, clientDir, instance);
|
|
471
|
+
|
|
472
|
+
const clientAssetPrefix = `${prefix}/_client/`;
|
|
473
|
+
const prodApp = new Elysia({
|
|
474
|
+
name: instanceName,
|
|
475
|
+
seed: resolvedPagesDir,
|
|
476
|
+
prefix: prefix || undefined,
|
|
477
|
+
})
|
|
367
478
|
.use(loggerPlugin)
|
|
368
|
-
|
|
479
|
+
// Local scope (default) — a global hook would leak onto sibling furin
|
|
480
|
+
// instances mounted on the same parent app.
|
|
481
|
+
.onError(async ({ code, request }) => {
|
|
369
482
|
if (code === "NOT_FOUND") {
|
|
370
483
|
return await renderRootNotFound(root, request);
|
|
371
484
|
}
|
|
372
485
|
})
|
|
373
|
-
.onAfterHandle(
|
|
486
|
+
.onAfterHandle(({ path, set }) => {
|
|
374
487
|
// Content-hashed client assets are permanently cacheable — browsers never need to
|
|
375
488
|
// revalidate them because any change produces a new filename.
|
|
376
|
-
if (path.startsWith(
|
|
489
|
+
if (path.startsWith(clientAssetPrefix)) {
|
|
377
490
|
set.headers["cache-control"] = "public, max-age=31536000, immutable";
|
|
378
491
|
}
|
|
379
492
|
// Forward pending revalidation paths so the client can bust its prefetch cache
|
|
@@ -382,9 +495,8 @@ export async function furin({
|
|
|
382
495
|
set.headers["x-furin-revalidate"] = pending.join(",");
|
|
383
496
|
}
|
|
384
497
|
// Tell the client the current build ID so it can detect stale deploys
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
set.headers["x-furin-build-id"] = buildId;
|
|
498
|
+
if (instance.buildId) {
|
|
499
|
+
set.headers["x-furin-build-id"] = instance.buildId;
|
|
388
500
|
}
|
|
389
501
|
})
|
|
390
502
|
.onStart(async ({ server }) => {
|
|
@@ -392,7 +504,9 @@ export async function furin({
|
|
|
392
504
|
return;
|
|
393
505
|
}
|
|
394
506
|
const origin = server?.url?.origin ?? "http://localhost:3000";
|
|
395
|
-
|
|
507
|
+
// Synthetic (non-request) renders — bind them to this instance so the
|
|
508
|
+
// render pipeline resolves its template/caches, not a sibling's.
|
|
509
|
+
await withInstance(instance, () => warmSSGCache(routes, root, origin, searchRoutes));
|
|
396
510
|
})
|
|
397
511
|
.use(
|
|
398
512
|
await (async () => {
|
|
@@ -431,18 +545,58 @@ export async function furin({
|
|
|
431
545
|
return app;
|
|
432
546
|
})()
|
|
433
547
|
)
|
|
434
|
-
.use(
|
|
548
|
+
.use(
|
|
549
|
+
syncStreamPath
|
|
550
|
+
? createSyncStreamPlugin(syncStreamPath, `${prefix}${syncStreamPath}`)
|
|
551
|
+
: new Elysia()
|
|
552
|
+
)
|
|
435
553
|
.use(createDataEndpoint(routes))
|
|
436
|
-
.use((app) =>
|
|
437
|
-
|
|
438
|
-
|
|
554
|
+
.use((app) =>
|
|
555
|
+
routes.reduce(
|
|
556
|
+
(chain, route) => chain.use(createRoutePlugin(route, root, prodBuildId, searchRoutes)),
|
|
557
|
+
app
|
|
558
|
+
)
|
|
559
|
+
)
|
|
560
|
+
.use(createNotFoundHandling(prefix, routes, root));
|
|
561
|
+
registerInstance(instance);
|
|
562
|
+
return wrapWithRequestScope(prodApp);
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
/**
|
|
566
|
+
* 404 handling per mount position:
|
|
567
|
+
*
|
|
568
|
+
* - ROOT instance (`prefix === ""`): the historical `{as:"global"}`
|
|
569
|
+
* onError(NOT_FOUND) hook — it owns the root scope, and a parent `.onError`
|
|
570
|
+
* registered BEFORE `.use(furin)` still wins (documented escape hatch for
|
|
571
|
+
* JSON API 404s).
|
|
572
|
+
* - PREFIXED instance: a global hook would leak onto sibling apps, and a
|
|
573
|
+
* local one never sees unmatched paths (they belong to no route). Instead
|
|
574
|
+
* the instance registers a lowest-priority catch-all under its own prefix;
|
|
575
|
+
* the router prefers every more-specific route, so this only fires for
|
|
576
|
+
* paths no page matched. Skipped when the app defines its own `[...rest]`
|
|
577
|
+
* catch-all page.
|
|
578
|
+
*/
|
|
579
|
+
function createNotFoundHandling(
|
|
580
|
+
prefix: string,
|
|
581
|
+
routes: Array<{ pattern: string }>,
|
|
582
|
+
root: Parameters<typeof renderRootNotFound>[0]
|
|
583
|
+
): Elysia {
|
|
584
|
+
const app = new Elysia();
|
|
585
|
+
if (prefix === "") {
|
|
586
|
+
app.onError({ as: "global" }, async ({ code, request }) => {
|
|
587
|
+
if (code === "NOT_FOUND") {
|
|
588
|
+
return await renderRootNotFound(root, request);
|
|
439
589
|
}
|
|
440
|
-
return app;
|
|
441
590
|
});
|
|
442
|
-
|
|
591
|
+
return app;
|
|
592
|
+
}
|
|
593
|
+
if (routes.some((route) => route.pattern === "/*")) {
|
|
594
|
+
return app;
|
|
595
|
+
}
|
|
596
|
+
app.get("/*", ({ request }) => renderRootNotFound(root, request));
|
|
597
|
+
return app;
|
|
443
598
|
}
|
|
444
599
|
|
|
445
|
-
// biome-ignore lint/performance/noBarrelFile: furin.ts is the public package entry
|
|
446
600
|
export { FurinErrorBoundary, FurinNotFoundBoundary } from "./client/boundaries.tsx";
|
|
447
601
|
// ── Public API re-export ──────────────────────────────────────────────────────
|
|
448
602
|
// biome-ignore-start lint/performance/noBarrelFile: intentional — furin.ts is the public package entry
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { type FurinInstance, instanceSlot } from "../instance.ts";
|
|
2
|
+
|
|
1
3
|
export class AutoInvalidateRegistry {
|
|
2
4
|
private readonly pathToTags = new Map<string, Set<string>>();
|
|
3
5
|
private readonly tagToPaths = new Map<string, Set<string>>();
|
|
@@ -57,4 +59,24 @@ export class AutoInvalidateRegistry {
|
|
|
57
59
|
}
|
|
58
60
|
}
|
|
59
61
|
|
|
60
|
-
|
|
62
|
+
const instanceAutoInvalidateRegistry = instanceSlot(() => new AutoInvalidateRegistry());
|
|
63
|
+
|
|
64
|
+
/** The current furin instance's registry (see server/instance.ts). */
|
|
65
|
+
export function getAutoInvalidateRegistry(instance?: FurinInstance): AutoInvalidateRegistry {
|
|
66
|
+
return instanceAutoInvalidateRegistry(instance);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Instance-scoped facade kept under the historical singleton name so call
|
|
71
|
+
* sites read the same — every method resolves the current instance's registry.
|
|
72
|
+
*/
|
|
73
|
+
export const autoInvalidateRegistry: Pick<
|
|
74
|
+
AutoInvalidateRegistry,
|
|
75
|
+
"registerLoaderTags" | "pathsForTags" | "unregisterPath" | "reset"
|
|
76
|
+
> = {
|
|
77
|
+
registerLoaderTags: (urlPath, tags) =>
|
|
78
|
+
instanceAutoInvalidateRegistry().registerLoaderTags(urlPath, tags),
|
|
79
|
+
pathsForTags: (tags) => instanceAutoInvalidateRegistry().pathsForTags(tags),
|
|
80
|
+
unregisterPath: (urlPath) => instanceAutoInvalidateRegistry().unregisterPath(urlPath),
|
|
81
|
+
reset: () => instanceAutoInvalidateRegistry().reset(),
|
|
82
|
+
};
|