@teyik0/furin 0.4.0-alpha.1 → 0.4.0-alpha.2

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 (193) hide show
  1. package/dist/adapter/bun.d.ts +2 -18
  2. package/dist/adapter/package.d.ts +2 -2
  3. package/dist/adapter/runtime-build.d.ts +33 -0
  4. package/dist/adapter/vercel.d.ts +3 -0
  5. package/dist/build/client.d.ts +1 -1
  6. package/dist/build/compile-entry.d.ts +4 -3
  7. package/dist/build/compile-entry.ts +24 -69
  8. package/dist/build/entry-template.d.ts +4 -2
  9. package/dist/build/entry-template.ts +31 -8
  10. package/dist/build/index.d.ts +1 -1
  11. package/dist/build/index.js +8596 -6375
  12. package/dist/build/ssg-cache.d.ts +13 -0
  13. package/dist/build/types.d.ts +25 -2
  14. package/dist/build/virtual-entry.d.ts +8 -0
  15. package/dist/cache.d.ts +5 -0
  16. package/dist/cache.js +97 -0
  17. package/dist/cli/index.js +9099 -6771
  18. package/dist/cli/preview.d.ts +7 -0
  19. package/dist/client/boundaries.d.ts +1 -0
  20. package/dist/client/browser-events-runtime.d.ts +2 -0
  21. package/dist/client/browser-events.d.ts +2 -0
  22. package/dist/client/define-route.d.ts +9 -8
  23. package/dist/client/dev-error-overlay.d.ts +1 -0
  24. package/dist/client/dev-error-overlay.ts +201 -0
  25. package/dist/client/document.d.ts +1 -0
  26. package/dist/client/hmr.d.ts +4 -2
  27. package/dist/client/link.js +251 -82
  28. package/dist/client/router/provider.d.ts +1 -1
  29. package/dist/client/router/sync-catch-up.d.ts +1 -1
  30. package/dist/client/router/types.d.ts +8 -10
  31. package/dist/client.js +37 -23
  32. package/dist/config.d.ts +17 -0
  33. package/dist/config.js +9 -1
  34. package/dist/define-route.d.ts +11 -8
  35. package/dist/devtools/protocol.d.ts +2 -2
  36. package/dist/furin.d.ts +1 -1
  37. package/dist/furin.js +12991 -9491
  38. package/dist/plugin/index.js +476 -7
  39. package/dist/plugin/routes.d.ts +4 -3
  40. package/dist/rsc/build/index.d.ts +5 -1
  41. package/dist/server/browser-events/plugin.d.ts +11 -0
  42. package/dist/server/browser-events/types.d.ts +9 -0
  43. package/dist/server/cache/invalidation.d.ts +1 -2
  44. package/dist/server/cache/isr.d.ts +1 -0
  45. package/dist/server/cache/purger.d.ts +7 -0
  46. package/dist/server/cache/runtime-cache.d.ts +21 -0
  47. package/dist/server/dev/browser-events.d.ts +4 -0
  48. package/dist/server/dev/diagnostics.d.ts +39 -0
  49. package/dist/server/dev/error.d.ts +17 -0
  50. package/dist/server/dev/graph.d.ts +86 -0
  51. package/dist/server/dev/plugin.d.ts +9 -0
  52. package/dist/server/dev/request-security.d.ts +1 -0
  53. package/dist/server/dev/rewrite-module-specifiers.d.ts +7 -0
  54. package/dist/server/dev/runtime.production.d.ts +5 -0
  55. package/dist/server/dev/symbolicate.d.ts +11 -0
  56. package/dist/server/dev/transform-failure.d.ts +4 -0
  57. package/dist/server/dev-page-plugin.production.d.ts +1 -0
  58. package/dist/server/devtools/hub.d.ts +3 -2
  59. package/dist/server/devtools/instrumentation.d.ts +1 -1
  60. package/dist/server/devtools/instrumentation.production.d.ts +1 -1
  61. package/dist/server/devtools/plugin.d.ts +1 -1
  62. package/dist/server/external-prerender.d.ts +2 -0
  63. package/dist/server/instance.d.ts +2 -2
  64. package/dist/server/internal.d.ts +14 -2
  65. package/dist/server/internal.js +436 -1
  66. package/dist/server/render/element.d.ts +1 -0
  67. package/dist/server/render/index.d.ts +1 -1
  68. package/dist/server/render/index.ts +1 -1
  69. package/dist/server/render/ppr-document.d.ts +21 -0
  70. package/dist/server/render/ppr-request.d.ts +26 -0
  71. package/dist/server/render/ppr-route.d.ts +3 -1
  72. package/dist/server/render/shell.ts +0 -12
  73. package/dist/server/render/ssg.d.ts +2 -0
  74. package/dist/server/render/ssr.d.ts +17 -6
  75. package/dist/server/router/hmr.production.d.ts +2 -0
  76. package/dist/server/router/patterns.d.ts +1 -0
  77. package/dist/server/router/plugin.d.ts +3 -1
  78. package/dist/server/sync/adapter.d.ts +13 -0
  79. package/dist/server/sync/config.d.ts +5 -5
  80. package/dist/server/sync/index.d.ts +6 -6
  81. package/dist/server/sync/index.js +491 -516
  82. package/dist/server/sync/notifier.d.ts +1 -0
  83. package/dist/server/sync/postgres/index.d.ts +12 -1
  84. package/dist/server/sync/postgres/index.js +101 -6
  85. package/dist/server/sync/stream.d.ts +4 -13
  86. package/dist/shared/await.d.ts +3 -3
  87. package/dist/shared/browser-events.d.ts +22 -0
  88. package/dist/shared/compact-json.d.ts +8 -0
  89. package/dist/shared/deferred-ndjson.d.ts +6 -5
  90. package/dist/shared/dev-diagnostics.d.ts +36 -0
  91. package/dist/shared/prefix.d.ts +2 -0
  92. package/package.json +16 -7
  93. package/src/adapter/README.md +45 -0
  94. package/src/adapter/bun.ts +45 -268
  95. package/src/adapter/package.ts +15 -9
  96. package/src/adapter/runtime-build.ts +375 -0
  97. package/src/adapter/static.ts +79 -2
  98. package/src/adapter/vercel.ts +857 -0
  99. package/src/build/client.ts +38 -13
  100. package/src/build/compile-entry.ts +24 -69
  101. package/src/build/entry-template.ts +31 -8
  102. package/src/build/hydrate.ts +60 -20
  103. package/src/build/index.ts +19 -5
  104. package/src/build/production-instrumentation.ts +56 -4
  105. package/src/build/shared.ts +2 -1
  106. package/src/build/ssg-cache.ts +97 -11
  107. package/src/build/types.ts +31 -2
  108. package/src/build/virtual-entry.ts +27 -0
  109. package/src/cache.ts +14 -0
  110. package/src/cli/index.ts +55 -3
  111. package/src/cli/preview.ts +90 -0
  112. package/src/client/boundaries.tsx +10 -1
  113. package/src/client/browser-events-runtime.ts +204 -0
  114. package/src/client/browser-events.ts +22 -0
  115. package/src/client/define-route.ts +7 -17
  116. package/src/client/dev-error-overlay.ts +201 -0
  117. package/src/client/document.tsx +4 -7
  118. package/src/client/hmr.ts +26 -3
  119. package/src/client/router/boundary-tree.tsx +4 -4
  120. package/src/client/router/provider.tsx +165 -63
  121. package/src/client/router/sync-catch-up.ts +3 -4
  122. package/src/client/router/types.ts +6 -6
  123. package/src/config.ts +25 -0
  124. package/src/define-route.ts +20 -7
  125. package/src/devtools/devtools-element.js +56 -77
  126. package/src/devtools/protocol.ts +2 -2
  127. package/src/furin.ts +157 -77
  128. package/src/plugin/routes.ts +206 -36
  129. package/src/plugin/transform-client.ts +685 -3
  130. package/src/react-dom-edge.d.ts +6 -0
  131. package/src/rsc/build/index.ts +15 -3
  132. package/src/server/auto-invalidate/runtime.ts +5 -2
  133. package/src/server/browser-events/plugin.ts +168 -0
  134. package/src/server/browser-events/types.ts +11 -0
  135. package/src/server/cache/dev-loader.ts +30 -29
  136. package/src/server/cache/invalidation.ts +13 -22
  137. package/src/server/cache/isr.ts +9 -0
  138. package/src/server/cache/purger.ts +41 -0
  139. package/src/server/cache/runtime-cache.ts +137 -0
  140. package/src/server/dev/browser-events.ts +54 -0
  141. package/src/server/dev/diagnostics.ts +297 -0
  142. package/src/server/dev/error.ts +148 -0
  143. package/src/server/dev/graph.ts +438 -0
  144. package/src/server/dev/plugin.ts +130 -0
  145. package/src/server/dev/request-security.ts +38 -0
  146. package/src/server/dev/rewrite-module-specifiers.ts +81 -0
  147. package/src/server/dev/runtime.production.ts +24 -0
  148. package/src/server/dev/symbolicate.ts +135 -0
  149. package/src/server/dev/transform-failure.ts +8 -0
  150. package/src/server/dev-page-plugin.production.ts +3 -0
  151. package/src/server/dev-page-plugin.ts +92 -53
  152. package/src/server/devtools/hub.ts +6 -5
  153. package/src/server/devtools/instrumentation.production.ts +1 -1
  154. package/src/server/devtools/instrumentation.ts +12 -6
  155. package/src/server/devtools/plugin.ts +7 -150
  156. package/src/server/external-prerender.ts +10 -0
  157. package/src/server/instance.ts +3 -3
  158. package/src/server/internal.ts +39 -2
  159. package/src/server/render/assemble.ts +4 -4
  160. package/src/server/render/document.tsx +13 -4
  161. package/src/server/render/element.tsx +18 -14
  162. package/src/server/render/index.ts +1 -1
  163. package/src/server/render/isr.ts +44 -19
  164. package/src/server/render/loaders.ts +13 -3
  165. package/src/server/render/not-found.ts +28 -4
  166. package/src/server/render/ppr-document.ts +239 -0
  167. package/src/server/render/ppr-request.ts +104 -0
  168. package/src/server/render/ppr-route.ts +152 -31
  169. package/src/server/render/shell.ts +0 -12
  170. package/src/server/render/ssg.ts +38 -20
  171. package/src/server/render/ssr.ts +211 -83
  172. package/src/server/render/template.ts +47 -11
  173. package/src/server/router/defined-route.ts +7 -39
  174. package/src/server/router/hmr.production.ts +7 -0
  175. package/src/server/router/hmr.ts +106 -67
  176. package/src/server/router/patterns.ts +5 -1
  177. package/src/server/router/plugin.ts +124 -35
  178. package/src/server/router/source-version.ts +3 -10
  179. package/src/server/sync/adapter.ts +13 -0
  180. package/src/server/sync/config.ts +12 -12
  181. package/src/server/sync/index.ts +8 -8
  182. package/src/server/sync/notifier.ts +1 -0
  183. package/src/server/sync/plugin.ts +4 -1
  184. package/src/server/sync/postgres/index.ts +111 -5
  185. package/src/server/sync/runtime.ts +12 -0
  186. package/src/server/sync/stream.ts +78 -113
  187. package/src/shared/await.tsx +3 -3
  188. package/src/shared/browser-events.ts +28 -0
  189. package/src/shared/compact-json.ts +77 -0
  190. package/src/shared/deferred-ndjson.ts +20 -6
  191. package/src/shared/dev-diagnostics.ts +44 -0
  192. package/src/shared/prefix.ts +8 -0
  193. package/src/shared/route-map.ts +10 -1
@@ -0,0 +1,438 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { readFileSync, statSync } from "node:fs";
3
+ import { dirname, extname } from "node:path";
4
+ import type { FurinRouteDispatcher } from "../../define-route.ts";
5
+ import { currentInstance, type FurinInstance } from "../instance.ts";
6
+ import type { ResolvedRoute, RootLayout } from "../router/types.ts";
7
+
8
+ export const DEV_ERROR_PROTOCOL_VERSION = 1;
9
+
10
+ export type DevErrorPhase = "hydrate" | "import" | "loader" | "render" | "transform";
11
+
12
+ export interface DevErrorPayload {
13
+ cause: string | null;
14
+ column: number | null;
15
+ file: string | null;
16
+ importChain: string[];
17
+ line: number | null;
18
+ message: string;
19
+ phase: DevErrorPhase;
20
+ route: string;
21
+ stack: string | null;
22
+ }
23
+
24
+ export interface DevelopmentRouteSnapshot {
25
+ render: FurinRouteDispatcher;
26
+ root: RootLayout;
27
+ routes: ResolvedRoute[];
28
+ }
29
+
30
+ interface DevEventBase {
31
+ id: number;
32
+ revision: number;
33
+ serverId: string;
34
+ version: typeof DEV_ERROR_PROTOCOL_VERSION;
35
+ }
36
+
37
+ export type DevGraphEvent =
38
+ | (DevEventBase & { error: DevErrorPayload; type: "error" })
39
+ | (DevEventBase & { type: "ready" });
40
+
41
+ interface DevModuleCacheEntry {
42
+ module: Promise<unknown>;
43
+ sourceVersion: string;
44
+ }
45
+
46
+ interface DevModuleRevision {
47
+ fingerprint: string;
48
+ revision: number;
49
+ }
50
+
51
+ export interface DevGraphMetrics {
52
+ events: number;
53
+ modules: number;
54
+ revision: number;
55
+ }
56
+
57
+ export interface DevSourcePosition {
58
+ column: number | null;
59
+ file: string;
60
+ line: number | null;
61
+ }
62
+
63
+ type DevModuleImporter<Module> = (specifier: string) => Promise<Module>;
64
+
65
+ const EVENT_LIMIT = 100;
66
+
67
+ function normalizeModulePath(path: string): string {
68
+ return path.replaceAll("\\", "/");
69
+ }
70
+
71
+ export function resolveDevSourceImports(
72
+ source: string,
73
+ path: string,
74
+ loader: "js" | "jsx" | "ts" | "tsx"
75
+ ) {
76
+ const imports: string[] = [];
77
+ const transpiler = new Bun.Transpiler({ loader });
78
+ for (const imported of transpiler.scanImports(source)) {
79
+ try {
80
+ const resolved = normalizeModulePath(Bun.resolveSync(imported.path, dirname(path)));
81
+ if (!resolved.includes("/node_modules/")) {
82
+ imports.push(resolved);
83
+ }
84
+ } catch {
85
+ // Bun's import error remains the primary diagnostic.
86
+ }
87
+ }
88
+ return { imports, transpiler };
89
+ }
90
+
91
+ function transformErrorPosition(
92
+ error: unknown,
93
+ message: string,
94
+ path: string
95
+ ): DevSourcePosition | undefined {
96
+ if (!(error instanceof Error) || error.message !== message) {
97
+ return;
98
+ }
99
+ const { position } = error as Error & {
100
+ position?: { column?: unknown; line?: unknown };
101
+ };
102
+ return {
103
+ column: typeof position?.column === "number" ? position.column : null,
104
+ file: path,
105
+ line: typeof position?.line === "number" ? position.line : null,
106
+ };
107
+ }
108
+
109
+ /**
110
+ * Single source of truth for development runtime state.
111
+ *
112
+ * A graph commit swaps the complete route snapshot before publishing `ready`,
113
+ * so requests never observe a partially rebuilt route tree. Module identities,
114
+ * per-runtime cache state, compilation revisions, and overlay events share the
115
+ * same lifetime.
116
+ */
117
+ export class DevGraph<Snapshot> {
118
+ readonly #dependencies = new Map<string, Set<string>>();
119
+ readonly #events: DevGraphEvent[] = [];
120
+ readonly #listeners = new Set<(event: DevGraphEvent) => void>();
121
+ readonly #moduleCaches = new WeakMap<
122
+ DevModuleImporter<unknown>,
123
+ Map<string, DevModuleCacheEntry>
124
+ >();
125
+ readonly #state = new Map<symbol, unknown>();
126
+ readonly #modulePaths = new Set<string>();
127
+ readonly #moduleRevisions = new Map<string, DevModuleRevision>();
128
+ readonly #sourceErrors = new Map<string, Map<string, DevSourcePosition>>();
129
+ readonly #serverId = randomUUID();
130
+ #eventSequence = 0;
131
+ #revision = 0;
132
+ #snapshot: Snapshot;
133
+ #sourceGeneration = 0;
134
+
135
+ constructor(initialSnapshot: Snapshot) {
136
+ this.#snapshot = initialSnapshot;
137
+ }
138
+
139
+ get events(): DevGraphEvent[] {
140
+ return [...this.#events];
141
+ }
142
+
143
+ get revision(): number {
144
+ return this.#revision;
145
+ }
146
+
147
+ get metrics(): DevGraphMetrics {
148
+ return {
149
+ events: this.#events.length,
150
+ modules: this.#modulePaths.size,
151
+ revision: this.#revision,
152
+ };
153
+ }
154
+
155
+ get snapshot(): Snapshot {
156
+ return this.#snapshot;
157
+ }
158
+
159
+ commit(snapshot: Snapshot): void {
160
+ this.#snapshot = snapshot;
161
+ this.#revision += 1;
162
+ this.#publish({ type: "ready" });
163
+ }
164
+
165
+ diagnoseTransformError(entryPath: string, message: string): DevSourcePosition | undefined {
166
+ const pending = [normalizeModulePath(entryPath)];
167
+ const visited = new Set<string>();
168
+ while (pending.length > 0) {
169
+ const path = pending.shift();
170
+ if (!path || visited.has(path)) {
171
+ continue;
172
+ }
173
+ visited.add(path);
174
+ const loader = sourceLoader(path);
175
+ if (loader === undefined) {
176
+ continue;
177
+ }
178
+ try {
179
+ const source = readFileSync(path, "utf8");
180
+ const { imports, transpiler } = resolveDevSourceImports(source, path, loader);
181
+ this.recordImports(path, imports);
182
+ try {
183
+ transpiler.transformSync(source, loader);
184
+ } catch (error) {
185
+ const position = transformErrorPosition(error, message, path);
186
+ if (position) {
187
+ return position;
188
+ }
189
+ }
190
+ pending.push(...imports);
191
+ } catch {
192
+ // A removed or unreadable source cannot contribute a diagnostic.
193
+ }
194
+ }
195
+ }
196
+
197
+ async importModule<Module>(
198
+ path: string,
199
+ sourceVersion: string,
200
+ importModule: DevModuleImporter<Module>
201
+ ): Promise<Module> {
202
+ const modulePath = normalizeModulePath(path);
203
+ this.#modulePaths.add(modulePath);
204
+ const importer = importModule as DevModuleImporter<unknown>;
205
+ let cache = this.#moduleCaches.get(importer);
206
+ if (!cache) {
207
+ cache = new Map();
208
+ this.#moduleCaches.set(importer, cache);
209
+ }
210
+ const cached = cache.get(modulePath);
211
+ if (cached?.sourceVersion === sourceVersion) {
212
+ return cached.module as Promise<Module>;
213
+ }
214
+
215
+ const entry: DevModuleCacheEntry = {
216
+ module: importModule(`${modulePath}?furin-server&t=${sourceVersion}`),
217
+ sourceVersion,
218
+ };
219
+ cache.set(modulePath, entry);
220
+ try {
221
+ return (await entry.module) as Module;
222
+ } catch (error) {
223
+ if (cache.get(modulePath) === entry) {
224
+ cache.delete(modulePath);
225
+ }
226
+ throw error;
227
+ }
228
+ }
229
+
230
+ importChain(from: string, to: string): string[] {
231
+ const normalizedFrom = normalizeModulePath(from);
232
+ const normalizedTo = normalizeModulePath(to);
233
+ if (normalizedFrom === normalizedTo) {
234
+ return [normalizedFrom];
235
+ }
236
+ const pending: Array<{ chain: string[]; path: string }> = [
237
+ { chain: [normalizedFrom], path: normalizedFrom },
238
+ ];
239
+ const visited = new Set([normalizedFrom]);
240
+ while (pending.length > 0) {
241
+ const current = pending.shift();
242
+ if (!current) {
243
+ break;
244
+ }
245
+ for (const dependency of this.#dependencies.get(current.path) ?? []) {
246
+ const chain = [...current.chain, dependency];
247
+ if (dependency === normalizedTo) {
248
+ return chain;
249
+ }
250
+ if (!visited.has(dependency)) {
251
+ visited.add(dependency);
252
+ pending.push({ chain, path: dependency });
253
+ }
254
+ }
255
+ }
256
+ return [normalizedFrom];
257
+ }
258
+
259
+ dependsOn(from: string, to: string): boolean {
260
+ const normalizedTo = normalizeModulePath(to);
261
+ return this.importChain(from, normalizedTo).includes(normalizedTo);
262
+ }
263
+
264
+ clearSourceErrors(path: string): void {
265
+ const modulePath = normalizeModulePath(path);
266
+ for (const [message, positions] of this.#sourceErrors) {
267
+ positions.delete(modulePath);
268
+ if (positions.size === 0) {
269
+ this.#sourceErrors.delete(message);
270
+ }
271
+ }
272
+ }
273
+
274
+ publishError(error: DevErrorPayload): Extract<DevGraphEvent, { type: "error" }> {
275
+ const latest = this.#events.at(-1);
276
+ if (latest?.type === "error" && JSON.stringify(latest.error) === JSON.stringify(error)) {
277
+ return latest;
278
+ }
279
+ return this.#publish({ error, type: "error" }) as Extract<DevGraphEvent, { type: "error" }>;
280
+ }
281
+
282
+ recordImports(importer: string, imports: string[]): void {
283
+ this.#dependencies.set(
284
+ normalizeModulePath(importer),
285
+ new Set(imports.map(normalizeModulePath))
286
+ );
287
+ }
288
+
289
+ recordSourceError(message: string, position: DevSourcePosition): void {
290
+ let positions = this.#sourceErrors.get(message);
291
+ if (!positions) {
292
+ positions = new Map();
293
+ this.#sourceErrors.set(message, positions);
294
+ }
295
+ const file = normalizeModulePath(position.file);
296
+ positions.set(file, { ...position, file });
297
+ }
298
+
299
+ sourceError(message: string, entryPath: string): DevSourcePosition | undefined {
300
+ const positions = this.#sourceErrors.get(message);
301
+ if (!positions) {
302
+ return;
303
+ }
304
+ for (const position of positions.values()) {
305
+ if (this.dependsOn(entryPath, position.file)) {
306
+ return position;
307
+ }
308
+ }
309
+ }
310
+
311
+ invalidateModules(): void {
312
+ this.#sourceGeneration += 1;
313
+ }
314
+
315
+ sourceVersion(path: string): string {
316
+ const modulePath = normalizeModulePath(path);
317
+ const fingerprint = this.#sourceFingerprint(modulePath, new Set());
318
+ const current = this.#moduleRevisions.get(modulePath);
319
+ if (current?.fingerprint === fingerprint) {
320
+ return String(current.revision);
321
+ }
322
+ const revision = (current?.revision ?? 0) + 1;
323
+ this.#moduleRevisions.set(modulePath, { fingerprint, revision });
324
+ return String(revision);
325
+ }
326
+
327
+ #sourceFingerprint(path: string, visited: Set<string>): string {
328
+ if (visited.has(path)) {
329
+ return path;
330
+ }
331
+ visited.add(path);
332
+ let ownFingerprint: string;
333
+ try {
334
+ const stats = statSync(path, { bigint: true });
335
+ ownFingerprint = `${stats.mtimeNs}:${stats.size}:${this.#sourceGeneration}`;
336
+ } catch {
337
+ ownFingerprint = `missing:${this.#sourceGeneration}`;
338
+ }
339
+ const dependencies = [...(this.#dependencies.get(path) ?? [])]
340
+ .toSorted((left, right) => left.localeCompare(right))
341
+ .map((dependency) => this.#sourceFingerprint(dependency, visited));
342
+ return `${path}:${ownFingerprint}:${dependencies.join(",")}`;
343
+ }
344
+
345
+ state<Value>(key: symbol, initialize: () => Value): Value {
346
+ if (this.#state.has(key)) {
347
+ return this.#state.get(key) as Value;
348
+ }
349
+ const value = initialize();
350
+ this.#state.set(key, value);
351
+ return value;
352
+ }
353
+
354
+ subscribe(
355
+ after: number,
356
+ serverId: string | undefined,
357
+ listener: (event: DevGraphEvent) => void
358
+ ): { replay: DevGraphEvent[]; unsubscribe: () => void } {
359
+ this.#listeners.add(listener);
360
+ const cursor = serverId === this.#serverId ? after : 0;
361
+ return {
362
+ replay: this.#events.filter((event) => event.id > cursor),
363
+ unsubscribe: () => {
364
+ this.#listeners.delete(listener);
365
+ },
366
+ };
367
+ }
368
+
369
+ #publish(event: { error: DevErrorPayload; type: "error" } | { type: "ready" }): DevGraphEvent {
370
+ this.#eventSequence += 1;
371
+ const complete = {
372
+ ...event,
373
+ id: this.#eventSequence,
374
+ revision: this.#revision,
375
+ serverId: this.#serverId,
376
+ version: DEV_ERROR_PROTOCOL_VERSION,
377
+ } as DevGraphEvent;
378
+ this.#events.push(complete);
379
+ if (this.#events.length > EVENT_LIMIT) {
380
+ this.#events.shift();
381
+ }
382
+ for (const listener of this.#listeners) {
383
+ try {
384
+ listener(complete);
385
+ } catch {
386
+ // A closing development socket must not abort an atomic graph commit.
387
+ }
388
+ }
389
+ return complete;
390
+ }
391
+ }
392
+
393
+ function sourceLoader(path: string): "js" | "jsx" | "ts" | "tsx" | undefined {
394
+ const extension = extname(path);
395
+ if (extension === ".js" || extension === ".jsx" || extension === ".ts" || extension === ".tsx") {
396
+ return extension.slice(1) as "js" | "jsx" | "ts" | "tsx";
397
+ }
398
+ }
399
+
400
+ const DEV_GRAPH_STATE = Symbol.for("@teyik0/furin/dev-graph");
401
+ const DEVELOPMENT_GRAPHS = Symbol.for("@teyik0/furin/development-graphs");
402
+
403
+ function developmentGraphMap(): Map<string, DevGraph<DevelopmentRouteSnapshot | null>> {
404
+ const existing = Reflect.get(globalThis, DEVELOPMENT_GRAPHS);
405
+ if (existing instanceof Map) {
406
+ return existing as Map<string, DevGraph<DevelopmentRouteSnapshot | null>>;
407
+ }
408
+ const graphs = new Map<string, DevGraph<DevelopmentRouteSnapshot | null>>();
409
+ Reflect.set(globalThis, DEVELOPMENT_GRAPHS, graphs);
410
+ return graphs;
411
+ }
412
+
413
+ export function developmentGraphs(): DevGraph<DevelopmentRouteSnapshot | null>[] {
414
+ return [...new Set(developmentGraphMap().values())];
415
+ }
416
+
417
+ export function devGraph(
418
+ instance: FurinInstance | undefined
419
+ ): DevGraph<DevelopmentRouteSnapshot | null> {
420
+ const target = instance ?? currentInstance();
421
+ const key = `${target.pagesDir}\0${target.prefix}`;
422
+ const graphs = developmentGraphMap();
423
+ const registered = graphs.get(key);
424
+ if (registered) {
425
+ target.state.set(DEV_GRAPH_STATE, registered);
426
+ return registered;
427
+ }
428
+ const existing = target.state.get(DEV_GRAPH_STATE);
429
+ if (existing !== undefined) {
430
+ const graph = existing as DevGraph<DevelopmentRouteSnapshot | null>;
431
+ graphs.set(key, graph);
432
+ return graph;
433
+ }
434
+ const graph = new DevGraph<DevelopmentRouteSnapshot | null>(null);
435
+ target.state.set(DEV_GRAPH_STATE, graph);
436
+ graphs.set(key, graph);
437
+ return graph;
438
+ }
@@ -0,0 +1,130 @@
1
+ import { type AnyElysia, Elysia } from "elysia";
2
+ import type { DevDiagnosticEvent } from "../../shared/dev-diagnostics.ts";
3
+ import { browserEventsClientScript } from "../browser-events/plugin.ts";
4
+ import type { FurinInstance } from "../instance.ts";
5
+ import {
6
+ type ClientErrorReport,
7
+ type DevDiagnosticStore,
8
+ publishClientDiagnostic,
9
+ } from "./diagnostics.ts";
10
+ import { forbiddenDevelopmentRequest } from "./request-security.ts";
11
+
12
+ interface EmbeddedDiagnosticState {
13
+ basePath: string;
14
+ event: Extract<DevDiagnosticEvent, { type: "error" }>;
15
+ }
16
+
17
+ let overlayClientSource: string | undefined;
18
+
19
+ async function clientSource(): Promise<string> {
20
+ if (overlayClientSource !== undefined) {
21
+ return overlayClientSource;
22
+ }
23
+ const candidates = [
24
+ new URL("../../client/dev-error-overlay.ts", import.meta.url),
25
+ new URL("./client/dev-error-overlay.ts", import.meta.url),
26
+ ];
27
+ const sources = await Promise.all(
28
+ candidates.map(async (path) => {
29
+ const file = Bun.file(path);
30
+ return (await file.exists()) ? await file.text() : undefined;
31
+ })
32
+ );
33
+ const source = sources.find((candidate) => candidate !== undefined);
34
+ if (source !== undefined) {
35
+ overlayClientSource = new Bun.Transpiler({ loader: "ts" }).transformSync(source, "ts");
36
+ return overlayClientSource;
37
+ }
38
+ throw new Error("Furin development overlay source is missing from the package.");
39
+ }
40
+
41
+ function clientErrorReport(value: unknown): ClientErrorReport | undefined {
42
+ if (typeof value !== "object" || value === null) {
43
+ return;
44
+ }
45
+ const candidate = value as {
46
+ cause?: unknown;
47
+ message?: unknown;
48
+ phase?: unknown;
49
+ route?: unknown;
50
+ stack?: unknown;
51
+ };
52
+ if (
53
+ typeof candidate.message !== "string" ||
54
+ (candidate.phase !== "client-render" && candidate.phase !== "hydrate") ||
55
+ typeof candidate.route !== "string"
56
+ ) {
57
+ return;
58
+ }
59
+ return {
60
+ cause: typeof candidate.cause === "string" ? candidate.cause : undefined,
61
+ message: candidate.message,
62
+ phase: candidate.phase,
63
+ route: candidate.route,
64
+ stack: typeof candidate.stack === "string" ? candidate.stack : undefined,
65
+ };
66
+ }
67
+
68
+ function serializeForHtml(value: EmbeddedDiagnosticState): string {
69
+ return JSON.stringify(value).replaceAll("<", "\\u003c");
70
+ }
71
+
72
+ export function createDevDiagnosticPlugin(
73
+ store: DevDiagnosticStore,
74
+ instance: FurinInstance | undefined,
75
+ reconcileRoutes: (() => Promise<void>) | undefined
76
+ ): AnyElysia {
77
+ return new Elysia({ name: "furin-dev-diagnostics" })
78
+ .get("/_furin/dev/overlay.js", async ({ request, server }) => {
79
+ const forbidden = forbiddenDevelopmentRequest(request, server);
80
+ if (forbidden) {
81
+ return forbidden;
82
+ }
83
+ return new Response(await clientSource(), {
84
+ headers: {
85
+ "cache-control": "no-store",
86
+ "content-type": "text/javascript; charset=utf-8",
87
+ "x-content-type-options": "nosniff",
88
+ },
89
+ });
90
+ })
91
+ .post("/_furin/dev/client-errors", async ({ body, request, server }) => {
92
+ const forbidden = forbiddenDevelopmentRequest(request, server);
93
+ if (forbidden) {
94
+ return forbidden;
95
+ }
96
+ const report = clientErrorReport(body);
97
+ if (!report) {
98
+ return new Response("Invalid client diagnostic", { status: 400 });
99
+ }
100
+ await reconcileRoutes?.();
101
+ return await publishClientDiagnostic(store, report, new URL(request.url).origin, instance);
102
+ });
103
+ }
104
+
105
+ export function injectDevDiagnosticClient(html: string, basePath: string): string {
106
+ const script = `<script data-furin-framework-module="" type="module" src="${basePath}/_furin/dev/overlay.js"></script>`;
107
+ if (html.includes(script)) {
108
+ return html;
109
+ }
110
+ return html.includes("</head>")
111
+ ? html.replace("</head>", `${script}</head>`)
112
+ : `${script}${html}`;
113
+ }
114
+
115
+ export function renderDevDiagnosticResponse(
116
+ event: Extract<DevDiagnosticEvent, { type: "error" }>,
117
+ basePath: string
118
+ ): Response {
119
+ const state = serializeForHtml({ basePath, event });
120
+ return new Response(
121
+ `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Furin development error</title>${browserEventsClientScript(basePath)}</head><body><script id="__FURIN_DEV_DIAGNOSTIC__" type="application/json">${state}</script><script type="module" src="${basePath}/_furin/dev/overlay.js"></script></body></html>`,
122
+ {
123
+ headers: {
124
+ "cache-control": "no-store",
125
+ "content-type": "text/html; charset=utf-8",
126
+ },
127
+ status: 500,
128
+ }
129
+ );
130
+ }
@@ -0,0 +1,38 @@
1
+ function isLoopbackAddress(address: string): boolean {
2
+ return (
3
+ address === "::1" ||
4
+ address === "0:0:0:0:0:0:0:1" ||
5
+ address.startsWith("127.") ||
6
+ address.startsWith("::ffff:127.")
7
+ );
8
+ }
9
+
10
+ export function forbiddenDevelopmentRequest(
11
+ request: Request,
12
+ server: Bun.Server<unknown> | null
13
+ ): Response | undefined {
14
+ if (server !== null) {
15
+ const peer = server.requestIP(request);
16
+ if (peer === null || !isLoopbackAddress(peer.address)) {
17
+ return new Response("Forbidden", { status: 403 });
18
+ }
19
+ }
20
+ const requestUrl = new URL(request.url);
21
+ const host = request.headers.get("host") ?? requestUrl.host;
22
+ let hostname: string;
23
+ try {
24
+ ({ hostname } = new URL(`http://${host}`));
25
+ } catch {
26
+ return new Response("Forbidden", { status: 403 });
27
+ }
28
+ if (hostname !== "localhost" && hostname !== "127.0.0.1" && hostname !== "[::1]") {
29
+ return new Response("Forbidden", { status: 403 });
30
+ }
31
+ const origin = request.headers.get("origin");
32
+ if (origin !== null && origin !== requestUrl.origin) {
33
+ return new Response("Forbidden", { status: 403 });
34
+ }
35
+ if (request.headers.get("sec-fetch-site") === "cross-site") {
36
+ return new Response("Forbidden", { status: 403 });
37
+ }
38
+ }
@@ -0,0 +1,81 @@
1
+ import { dirname, resolve } from "node:path";
2
+ import MagicString from "magic-string";
3
+ import { parseSource } from "../../shared/parser.ts";
4
+ import type { AstNode } from "../../shared/utils/ast-walk.ts";
5
+ import { walkAST } from "../../shared/utils/ast-walk.ts";
6
+ import { detectLangFromPath } from "../lang-detect.ts";
7
+ import { routeModuleSourceVersion } from "../router/source-version.ts";
8
+
9
+ interface RewriteModuleSpecifiersInput {
10
+ code: string;
11
+ filePath: string;
12
+ versioned: boolean;
13
+ }
14
+
15
+ const DEV_SOURCE_PATH_RE = /\.(?:jsx?|tsx?)$/;
16
+ const MODULE_SPECIFIER_NODES = new Set([
17
+ "ExportAllDeclaration",
18
+ "ExportNamedDeclaration",
19
+ "ImportDeclaration",
20
+ "ImportExpression",
21
+ ]);
22
+
23
+ function sourcePosition(source: string, byteOffset: number): { column: number; line: number } {
24
+ const bytes = new TextEncoder().encode(source);
25
+ const prefix = new TextDecoder().decode(bytes.slice(0, byteOffset));
26
+ const lines = prefix.split("\n");
27
+ return {
28
+ column: (lines.at(-1)?.length ?? 0) + 1,
29
+ line: lines.length,
30
+ };
31
+ }
32
+
33
+ function relativeSpecifier(node: AstNode): AstNode | undefined {
34
+ if (!MODULE_SPECIFIER_NODES.has(node.type)) {
35
+ return;
36
+ }
37
+ const { source } = node;
38
+ if (!source || typeof source !== "object") {
39
+ return;
40
+ }
41
+ const literal = source as AstNode;
42
+ return literal.type === "Literal" && typeof literal.value === "string" ? literal : undefined;
43
+ }
44
+
45
+ function resolvedSpecifier(specifier: string, directory: string, versioned: boolean): string {
46
+ const path = versioned ? Bun.resolveSync(specifier, directory) : resolve(directory, specifier);
47
+ const normalized = path.replaceAll("\\", "/");
48
+ return versioned && DEV_SOURCE_PATH_RE.test(normalized)
49
+ ? `${normalized}?furin-server&t=${routeModuleSourceVersion(normalized)}`
50
+ : normalized;
51
+ }
52
+
53
+ export function rewriteModuleSpecifiers(input: RewriteModuleSpecifiersInput): string {
54
+ const { diagnostics, program } = parseSource(input.code, detectLangFromPath(input.filePath));
55
+ const parseError = diagnostics.find((diagnostic) => diagnostic.severity === "error");
56
+ if (parseError) {
57
+ const error = new Error(`Failed to parse ${input.filePath}: ${parseError.message}`);
58
+ Reflect.set(error, "position", sourcePosition(input.code, parseError.start));
59
+ throw error;
60
+ }
61
+
62
+ const directory = dirname(input.filePath);
63
+ const output = new MagicString(input.code);
64
+ walkAST(program, (node) => {
65
+ const literal = relativeSpecifier(node);
66
+ const specifier = literal?.value;
67
+ if (
68
+ !literal ||
69
+ typeof specifier !== "string" ||
70
+ !(specifier.startsWith("./") || specifier.startsWith("../"))
71
+ ) {
72
+ return;
73
+ }
74
+ output.update(
75
+ literal.start,
76
+ literal.end,
77
+ JSON.stringify(resolvedSpecifier(specifier, directory, input.versioned))
78
+ );
79
+ });
80
+ return output.toString();
81
+ }