@teyik0/furin 0.1.0-alpha.6 → 0.1.0-alpha.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/dist/adapter/static.d.ts +3 -0
  2. package/dist/build/client.d.ts +3 -3
  3. package/dist/build/compile-entry.d.ts +4 -4
  4. package/dist/build/entry-template.d.ts +2 -2
  5. package/dist/build/hydrate.d.ts +6 -2
  6. package/dist/build/index.d.ts +1 -1
  7. package/dist/build/index.js +668 -90
  8. package/dist/build/types.d.ts +26 -3
  9. package/dist/cli/index.d.ts +1 -0
  10. package/dist/cli/index.js +704 -103
  11. package/dist/client.d.ts +22 -15
  12. package/dist/config.d.ts +33 -2
  13. package/dist/config.js +6 -1
  14. package/dist/dev-page-plugin.d.ts +77 -0
  15. package/dist/furin.js +771 -81
  16. package/dist/link.d.ts +31 -3
  17. package/dist/link.js +511 -62
  18. package/dist/render/index.d.ts +1 -1
  19. package/dist/render/loaders.d.ts +1 -1
  20. package/dist/router.js +84 -24
  21. package/package.json +9 -10
  22. package/src/adapter/bun.ts +31 -7
  23. package/src/adapter/static.ts +337 -0
  24. package/src/build/client.ts +28 -11
  25. package/src/build/compile-entry.ts +5 -3
  26. package/src/build/entry-template.ts +9 -5
  27. package/src/build/hydrate.ts +40 -10
  28. package/src/build/index.ts +56 -21
  29. package/src/build/scan-server.ts +43 -21
  30. package/src/build/shared.ts +7 -3
  31. package/src/build/types.ts +28 -3
  32. package/src/cli/index.ts +14 -5
  33. package/src/client.ts +26 -31
  34. package/src/config.ts +35 -1
  35. package/src/dev-page-plugin.ts +339 -4
  36. package/src/furin.ts +6 -2
  37. package/src/link.tsx +268 -62
  38. package/src/plugin/index.ts +2 -2
  39. package/src/render/index.ts +64 -24
  40. package/src/render/loaders.ts +77 -36
  41. package/src/render/shell.ts +2 -2
  42. package/src/router.ts +11 -1
package/dist/furin.js CHANGED
@@ -15,7 +15,7 @@ var __export = (target, all) => {
15
15
  };
16
16
  var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
17
17
 
18
- // ../../node_modules/.bun/evlog@2.11.0+a1ab7c6fe65f988d/node_modules/evlog/dist/utils.mjs
18
+ // ../../node_modules/.bun/evlog@2.13.0+449e6d239244fccb/node_modules/evlog/dist/utils.mjs
19
19
  function formatDuration(ms) {
20
20
  if (ms < 1000)
21
21
  return `${Math.round(ms)}ms`;
@@ -42,6 +42,9 @@ function detectEnvironment() {
42
42
  region: env.VERCEL_REGION || env.AWS_REGION || env.FLY_REGION || env.CF_REGION
43
43
  };
44
44
  }
45
+ function isLevelEnabled(level, minLevel) {
46
+ return LEVEL_ORDER[level] >= LEVEL_ORDER[minLevel];
47
+ }
45
48
  function getConsoleMethod(level) {
46
49
  return level;
47
50
  }
@@ -70,8 +73,14 @@ function matchesPattern(path, pattern) {
70
73
  }
71
74
  return regex.test(path);
72
75
  }
73
- var colors, levelColorMap, cssColors, cssLevelColorMap, SENSITIVE_HEADERS, patternCache;
76
+ var LEVEL_ORDER, colors, levelColorMap, cssColors, cssLevelColorMap, SENSITIVE_HEADERS, patternCache;
74
77
  var init_utils = __esm(() => {
78
+ LEVEL_ORDER = {
79
+ debug: 0,
80
+ info: 1,
81
+ warn: 2,
82
+ error: 3
83
+ };
75
84
  colors = {
76
85
  reset: "\x1B[0m",
77
86
  bold: "\x1B[1m",
@@ -117,7 +126,109 @@ var init_utils = __esm(() => {
117
126
  patternCache = /* @__PURE__ */ new Map;
118
127
  });
119
128
 
120
- // ../../node_modules/.bun/evlog@2.11.0+a1ab7c6fe65f988d/node_modules/evlog/dist/logger.mjs
129
+ // ../../node_modules/.bun/evlog@2.13.0+449e6d239244fccb/node_modules/evlog/dist/logger-DnobymUQ.mjs
130
+ function resolveRedactConfig(input) {
131
+ if (input === undefined || input === false)
132
+ return;
133
+ if (input === true)
134
+ return { _maskers: allBuiltinMaskers() };
135
+ if (input.builtins === false)
136
+ return input;
137
+ const maskers = Array.isArray(input.builtins) ? input.builtins.map((name) => builtinPatterns[name]).filter(Boolean).map((b) => [cloneRegex(b.pattern), b.mask]) : allBuiltinMaskers();
138
+ return {
139
+ ...input,
140
+ _maskers: maskers
141
+ };
142
+ }
143
+ function allBuiltinMaskers() {
144
+ return Object.values(builtinPatterns).map((b) => [cloneRegex(b.pattern), b.mask]);
145
+ }
146
+ function cloneRegex(re) {
147
+ return new RegExp(re.source, re.flags);
148
+ }
149
+ function redactEvent(event, config) {
150
+ const replacement = config.replacement ?? DEFAULT_REPLACEMENT;
151
+ if (config.paths?.length)
152
+ for (const path of config.paths)
153
+ redactPath(event, path.split("."), replacement);
154
+ if (config._maskers?.length)
155
+ applyMaskersToTree(event, config._maskers);
156
+ if (config.patterns?.length)
157
+ redactPatterns(event, config.patterns, replacement);
158
+ }
159
+ function redactPath(obj, segments, replacement) {
160
+ let current = obj;
161
+ for (let i = 0;i < segments.length - 1; i++) {
162
+ if (current === null || current === undefined || typeof current !== "object")
163
+ return;
164
+ current = current[segments[i]];
165
+ }
166
+ if (current === null || current === undefined || typeof current !== "object")
167
+ return;
168
+ const leaf = segments[segments.length - 1];
169
+ if (leaf in current)
170
+ current[leaf] = replacement;
171
+ }
172
+ function redactPatterns(obj, patterns, replacement) {
173
+ if (obj === null || obj === undefined)
174
+ return;
175
+ if (Array.isArray(obj)) {
176
+ for (let i = 0;i < obj.length; i++)
177
+ if (typeof obj[i] === "string")
178
+ obj[i] = applyPatterns(obj[i], patterns, replacement);
179
+ else if (typeof obj[i] === "object")
180
+ redactPatterns(obj[i], patterns, replacement);
181
+ return;
182
+ }
183
+ if (typeof obj === "object") {
184
+ const record = obj;
185
+ for (const key in record) {
186
+ const val = record[key];
187
+ if (typeof val === "string")
188
+ record[key] = applyPatterns(val, patterns, replacement);
189
+ else if (typeof val === "object")
190
+ redactPatterns(val, patterns, replacement);
191
+ }
192
+ }
193
+ }
194
+ function applyPatterns(value, patterns, replacement) {
195
+ let result = value;
196
+ for (const pattern of patterns) {
197
+ pattern.lastIndex = 0;
198
+ result = result.replace(pattern, replacement);
199
+ }
200
+ return result;
201
+ }
202
+ function applyMaskersToTree(obj, maskers) {
203
+ if (obj === null || obj === undefined)
204
+ return;
205
+ if (Array.isArray(obj)) {
206
+ for (let i = 0;i < obj.length; i++)
207
+ if (typeof obj[i] === "string")
208
+ obj[i] = applyMaskers(obj[i], maskers);
209
+ else if (typeof obj[i] === "object")
210
+ applyMaskersToTree(obj[i], maskers);
211
+ return;
212
+ }
213
+ if (typeof obj === "object") {
214
+ const record = obj;
215
+ for (const key in record) {
216
+ const val = record[key];
217
+ if (typeof val === "string")
218
+ record[key] = applyMaskers(val, maskers);
219
+ else if (typeof val === "object")
220
+ applyMaskersToTree(val, maskers);
221
+ }
222
+ }
223
+ }
224
+ function applyMaskers(value, maskers) {
225
+ let result = value;
226
+ for (const [pattern, mask] of maskers) {
227
+ pattern.lastIndex = 0;
228
+ result = result.replace(pattern, mask);
229
+ }
230
+ return result;
231
+ }
121
232
  function isPlainObject(val) {
122
233
  return val !== null && typeof val === "object" && !Array.isArray(val);
123
234
  }
@@ -125,6 +236,9 @@ function isoNow() {
125
236
  _tsDate.setTime(Date.now());
126
237
  return _tsDate.toISOString();
127
238
  }
239
+ function warnPostEmit(method, detail) {
240
+ console.warn(`[evlog] ${method} called after the wide event was emitted \u2014 ${detail} This data will not appear in observability. ${POST_EMIT_FORK_HINT}`);
241
+ }
128
242
  function mergeInto(target, source) {
129
243
  for (const key in source) {
130
244
  const sourceVal = source[key];
@@ -133,6 +247,8 @@ function mergeInto(target, source) {
133
247
  const targetVal = target[key];
134
248
  if (isPlainObject(sourceVal) && isPlainObject(targetVal))
135
249
  mergeInto(targetVal, sourceVal);
250
+ else if (Array.isArray(targetVal) && Array.isArray(sourceVal))
251
+ target[key] = [...targetVal, ...sourceVal];
136
252
  else
137
253
  target[key] = sourceVal;
138
254
  }
@@ -151,7 +267,9 @@ function initLogger(config = {}) {
151
267
  globalSampling = config.sampling ?? {};
152
268
  globalStringify = config.stringify ?? true;
153
269
  globalDrain = config.drain;
270
+ globalRedact = resolveRedactConfig(config.redact ?? !isDev());
154
271
  globalSilent = config.silent ?? false;
272
+ globalMinLevel = config.minLevel ?? "debug";
155
273
  if (globalSilent && !globalDrain && !config._suppressDrainWarning)
156
274
  console.warn("[evlog] silent mode is enabled but no drain is configured. Events will be built and sampled but not output anywhere. Set a drain via initLogger({ drain }) or a framework hook (evlog:drain).");
157
275
  }
@@ -189,8 +307,12 @@ function shouldKeep(ctx) {
189
307
  function emitWideEvent(level, event, deferDrain = false, ownsEvent = false) {
190
308
  if (!globalEnabled)
191
309
  return null;
192
- if (!ownsEvent && !shouldSample(level))
193
- return null;
310
+ if (!ownsEvent) {
311
+ if (!isLevelEnabled(level, globalMinLevel))
312
+ return null;
313
+ if (!shouldSample(level))
314
+ return null;
315
+ }
194
316
  let formatted;
195
317
  if (ownsEvent) {
196
318
  event.timestamp = isoNow();
@@ -213,6 +335,8 @@ function emitWideEvent(level, event, deferDrain = false, ownsEvent = false) {
213
335
  ...globalEnv,
214
336
  ...event
215
337
  };
338
+ if (globalRedact)
339
+ redactEvent(formatted, globalRedact);
216
340
  if (!globalSilent)
217
341
  if (globalPretty)
218
342
  prettyPrintWideEvent(formatted);
@@ -230,6 +354,8 @@ function emitTaggedLog(level, tag, message) {
230
354
  if (!globalEnabled)
231
355
  return;
232
356
  if (globalPretty && !globalSilent) {
357
+ if (!isLevelEnabled(level, globalMinLevel))
358
+ return;
233
359
  if (!shouldSample(level))
234
360
  return;
235
361
  if (isClient()) {
@@ -263,6 +389,169 @@ function formatValue(value) {
263
389
  }
264
390
  return String(value);
265
391
  }
392
+ function formatCost(cost) {
393
+ if (cost < 0.01)
394
+ return `$${cost.toFixed(6)}`;
395
+ if (cost < 1)
396
+ return `$${cost.toFixed(4)}`;
397
+ return `$${cost.toFixed(2)}`;
398
+ }
399
+ function buildAIEntries(ai) {
400
+ const entries = [];
401
+ const headerParts = [];
402
+ if (ai.model) {
403
+ let m = String(ai.model);
404
+ if (ai.provider)
405
+ m += ` (${ai.provider})`;
406
+ headerParts.push(m);
407
+ }
408
+ if (ai.calls)
409
+ headerParts.push(`${ai.calls} call${ai.calls > 1 ? "s" : ""}`);
410
+ if (ai.steps && ai.steps > 1)
411
+ headerParts.push(`${ai.steps} steps`);
412
+ entries.push({
413
+ key: "ai",
414
+ value: headerParts.join(" \xB7 ")
415
+ });
416
+ const inputTokens = ai.inputTokens;
417
+ const outputTokens = ai.outputTokens;
418
+ const totalTokens = ai.totalTokens;
419
+ if (inputTokens !== undefined && outputTokens !== undefined) {
420
+ let tokLine = `${inputTokens} in \u2192 ${outputTokens} out`;
421
+ if (totalTokens)
422
+ tokLine += ` (${totalTokens} total)`;
423
+ const extras = [];
424
+ if (ai.cacheReadTokens)
425
+ extras.push(`${ai.cacheReadTokens} cache read`);
426
+ if (ai.cacheWriteTokens)
427
+ extras.push(`${ai.cacheWriteTokens} cache write`);
428
+ if (ai.reasoningTokens)
429
+ extras.push(`${ai.reasoningTokens} reasoning`);
430
+ if (extras.length)
431
+ tokLine += ` \xB7 ${extras.join(" \xB7 ")}`;
432
+ entries.push({
433
+ key: "ai.tokens",
434
+ value: tokLine
435
+ });
436
+ }
437
+ const msFirst = ai.msToFirstChunk;
438
+ const msFinish = ai.msToFinish;
439
+ const tps = ai.tokensPerSecond;
440
+ if (msFirst !== undefined || msFinish !== undefined) {
441
+ const parts = [];
442
+ if (msFirst !== undefined)
443
+ parts.push(`${formatDuration(msFirst)} to first chunk`);
444
+ if (msFinish !== undefined)
445
+ parts.push(`${formatDuration(msFinish)} total`);
446
+ let streamLine = parts.join(" \u2192 ");
447
+ if (tps)
448
+ streamLine += ` \xB7 ${tps} tok/s`;
449
+ entries.push({
450
+ key: "ai.streaming",
451
+ value: streamLine
452
+ });
453
+ }
454
+ if (ai.estimatedCost !== undefined)
455
+ entries.push({
456
+ key: "ai.cost",
457
+ value: formatCost(ai.estimatedCost)
458
+ });
459
+ if (ai.totalDurationMs !== undefined)
460
+ entries.push({
461
+ key: "ai.totalDuration",
462
+ value: formatDuration(ai.totalDurationMs)
463
+ });
464
+ const toolCalls = ai.toolCalls;
465
+ const tools = ai.tools;
466
+ const hasInputs = toolCalls?.length ? typeof toolCalls[0] === "object" : false;
467
+ if (tools?.length) {
468
+ const children = tools.map((t, idx) => {
469
+ const mark = t.success ? "\u2713" : "\u2717";
470
+ let line = `${t.name} ${formatDuration(t.durationMs)} ${mark}`;
471
+ if (t.error)
472
+ line += ` ${t.error}`;
473
+ if (hasInputs && toolCalls && idx < toolCalls.length) {
474
+ const tc = toolCalls[idx];
475
+ const inputStr = typeof tc.input === "string" ? tc.input : JSON.stringify(tc.input);
476
+ const truncated = inputStr.length > 100 ? `${inputStr.slice(0, 100)}\u2026` : inputStr;
477
+ line += ` ${truncated}`;
478
+ }
479
+ return line;
480
+ });
481
+ entries.push({
482
+ key: "ai.tools",
483
+ value: "",
484
+ children
485
+ });
486
+ } else if (toolCalls?.length)
487
+ if (hasInputs) {
488
+ const children = toolCalls.map((tc) => {
489
+ const inputStr = typeof tc.input === "string" ? tc.input : JSON.stringify(tc.input);
490
+ const truncated = inputStr.length > 100 ? `${inputStr.slice(0, 100)}\u2026` : inputStr;
491
+ return `${tc.name}(${truncated})`;
492
+ });
493
+ entries.push({
494
+ key: "ai.tools",
495
+ value: "",
496
+ children
497
+ });
498
+ } else
499
+ entries.push({
500
+ key: "ai.tools",
501
+ value: toolCalls.join(", ")
502
+ });
503
+ const stepsUsage = ai.stepsUsage;
504
+ if (stepsUsage?.length) {
505
+ const allSameModel = stepsUsage.every((s) => s.model === stepsUsage[0].model);
506
+ const children = stepsUsage.map((s) => {
507
+ let line = `${allSameModel ? "" : `${s.model} `}${s.inputTokens} in \u2192 ${s.outputTokens} out`;
508
+ const stepTools = s.toolCalls;
509
+ if (stepTools?.length)
510
+ line += ` [${stepTools.join(", ")}]`;
511
+ return line;
512
+ });
513
+ entries.push({
514
+ key: "ai.steps",
515
+ value: "",
516
+ children
517
+ });
518
+ } else if (ai.steps && ai.steps > 1)
519
+ entries.push({
520
+ key: "ai.steps",
521
+ value: String(ai.steps)
522
+ });
523
+ const embedding = ai.embedding;
524
+ if (embedding) {
525
+ const parts = [];
526
+ if (embedding.model)
527
+ parts.push(String(embedding.model));
528
+ parts.push(`${embedding.tokens} tokens`);
529
+ if (embedding.dimensions)
530
+ parts.push(`${embedding.dimensions}d`);
531
+ if (embedding.count)
532
+ parts.push(`${embedding.count} items`);
533
+ entries.push({
534
+ key: "ai.embedding",
535
+ value: parts.join(" \xB7 ")
536
+ });
537
+ }
538
+ if (ai.finishReason)
539
+ entries.push({
540
+ key: "ai.finishReason",
541
+ value: String(ai.finishReason)
542
+ });
543
+ if (ai.error)
544
+ entries.push({
545
+ key: "ai.error",
546
+ value: String(ai.error)
547
+ });
548
+ if (ai.responseId)
549
+ entries.push({
550
+ key: "ai.responseId",
551
+ value: String(ai.responseId)
552
+ });
553
+ return entries;
554
+ }
266
555
  function prettyPrintWideEvent(event) {
267
556
  const { timestamp, level, service, environment, version, ...rest } = event;
268
557
  const ts = timestamp.slice(11, 23);
@@ -300,16 +589,38 @@ function prettyPrintWideEvent(event) {
300
589
  delete rest.duration;
301
590
  }
302
591
  console.log(parts.join(""), ...styles);
303
- const entries = Object.entries(rest).filter(([_, v]) => v !== undefined);
304
- const lastIndex = entries.length - 1;
305
- entries.forEach(([key, value], index) => {
306
- const prefix = index === lastIndex ? "\u2514\u2500" : "\u251C\u2500";
307
- const val = formatValue(value);
308
- if (browser)
309
- console.log(` %c${prefix}%c %c${escapeFormatString(key)}:%c ${escapeFormatString(val)}`, cssColors.dim, cssColors.reset, cssColors.cyan, cssColors.reset);
310
- else
311
- console.log(` ${colors.dim}${prefix}${colors.reset} ${colors.cyan}${key}:${colors.reset} ${val}`);
312
- });
592
+ const aiData = rest.ai;
593
+ if (aiData && typeof aiData === "object")
594
+ delete rest.ai;
595
+ const restEntries = Object.entries(rest).filter(([_, v]) => v !== undefined);
596
+ const aiEntries = aiData ? buildAIEntries(aiData) : [];
597
+ const allEntries = [...restEntries.map(([key, value]) => ({
598
+ key,
599
+ value: formatValue(value)
600
+ })), ...aiEntries];
601
+ for (let i = 0;i < allEntries.length; i++) {
602
+ const entry = allEntries[i];
603
+ const hasChildren = entry.children && entry.children.length > 0;
604
+ const prefix = i === allEntries.length - 1 && !hasChildren ? "\u2514\u2500" : "\u251C\u2500";
605
+ if (browser) {
606
+ const val = entry.value ? ` ${escapeFormatString(entry.value)}` : "";
607
+ console.log(` %c${prefix}%c %c${escapeFormatString(entry.key)}:%c${val}`, cssColors.dim, cssColors.reset, cssColors.cyan, cssColors.reset);
608
+ } else {
609
+ const val = entry.value ? ` ${entry.value}` : "";
610
+ console.log(` ${colors.dim}${prefix}${colors.reset} ${colors.cyan}${entry.key}:${colors.reset}${val}`);
611
+ }
612
+ if (hasChildren) {
613
+ const connector = i === allEntries.length - 1 ? " " : "\u2502";
614
+ for (let j = 0;j < entry.children.length; j++) {
615
+ const child = entry.children[j];
616
+ const childPrefix = j === entry.children.length - 1 ? "\u2514\u2500" : "\u251C\u2500";
617
+ if (browser)
618
+ console.log(` %c${connector} ${childPrefix}%c ${escapeFormatString(child)}`, cssColors.dim, cssColors.reset);
619
+ else
620
+ console.log(` ${colors.dim}${connector} ${childPrefix}${colors.reset} ${child}`);
621
+ }
622
+ }
623
+ }
313
624
  }
314
625
  function createLogMethod(level) {
315
626
  return function logMethod(tagOrEvent, message) {
@@ -329,6 +640,7 @@ function createLogger(initialContext = {}, internalOptions) {
329
640
  const context = { ...initialContext };
330
641
  let hasError = false;
331
642
  let hasWarn = false;
643
+ let emitted = false;
332
644
  function addLog(level, message) {
333
645
  if (!Array.isArray(context.requestLogs))
334
646
  context.requestLogs = [];
@@ -340,9 +652,18 @@ function createLogger(initialContext = {}, internalOptions) {
340
652
  }
341
653
  return {
342
654
  set(data) {
655
+ if (emitted) {
656
+ const keys = Object.keys(data);
657
+ warnPostEmit("log.set()", `Keys dropped: ${keys.length ? keys.join(", ") : "(empty)"}.`);
658
+ return;
659
+ }
343
660
  mergeInto(context, data);
344
661
  },
345
662
  error(error, errorContext) {
663
+ if (emitted) {
664
+ warnPostEmit("log.error()", `Keys dropped: ${(errorContext ? [...Object.keys(errorContext), "error"] : ["error"]).join(", ")}.`);
665
+ return;
666
+ }
346
667
  hasError = true;
347
668
  const err = typeof error === "string" ? new Error(error) : error;
348
669
  if (errorContext)
@@ -370,6 +691,10 @@ function createLogger(initialContext = {}, internalOptions) {
370
691
  context.error = errorObj;
371
692
  },
372
693
  info(message, infoContext) {
694
+ if (emitted) {
695
+ warnPostEmit("log.info()", `Keys dropped: ${(infoContext ? ["message", ...Object.keys(infoContext).filter((k) => k !== "requestLogs")] : ["message"]).join(", ")}.`);
696
+ return;
697
+ }
373
698
  addLog("info", message);
374
699
  if (infoContext) {
375
700
  const { requestLogs: _, ...rest } = infoContext;
@@ -377,6 +702,10 @@ function createLogger(initialContext = {}, internalOptions) {
377
702
  }
378
703
  },
379
704
  warn(message, warnContext) {
705
+ if (emitted) {
706
+ warnPostEmit("log.warn()", `Keys dropped: ${(warnContext ? ["message", ...Object.keys(warnContext).filter((k) => k !== "requestLogs")] : ["message"]).join(", ")}.`);
707
+ return;
708
+ }
380
709
  hasWarn = true;
381
710
  addLog("warn", message);
382
711
  if (warnContext) {
@@ -385,6 +714,10 @@ function createLogger(initialContext = {}, internalOptions) {
385
714
  }
386
715
  },
387
716
  emit(overrides) {
717
+ if (emitted) {
718
+ warnPostEmit("log.emit()", "Ignoring duplicate emit.");
719
+ return null;
720
+ }
388
721
  const durationMs = Date.now() - startTime;
389
722
  const level = hasError ? "error" : hasWarn ? "warn" : "info";
390
723
  let forceKeep = false;
@@ -398,8 +731,10 @@ function createLogger(initialContext = {}, internalOptions) {
398
731
  method: context.method,
399
732
  context
400
733
  });
401
- if (!forceKeep && !shouldSample(level))
734
+ if (!forceKeep && !shouldSample(level)) {
735
+ emitted = true;
402
736
  return null;
737
+ }
403
738
  if (overrides) {
404
739
  const obj = overrides;
405
740
  for (const key in obj)
@@ -407,7 +742,9 @@ function createLogger(initialContext = {}, internalOptions) {
407
742
  context[key] = obj[key];
408
743
  }
409
744
  context.duration = formatDuration(durationMs);
410
- return emitWideEvent(level, context, deferDrain, true);
745
+ const wide = emitWideEvent(level, context, deferDrain, true);
746
+ emitted = true;
747
+ return wide;
411
748
  },
412
749
  getContext() {
413
750
  return { ...context };
@@ -424,9 +761,56 @@ function createRequestLogger(options = {}, internalOptions) {
424
761
  initial.requestId = options.requestId;
425
762
  return createLogger(initial, internalOptions);
426
763
  }
427
- var _tsDate, globalEnv, globalPretty, globalSampling, globalStringify = true, globalDrain, globalEnabled = true, globalSilent = false, _log, noopLogger;
428
- var init_logger = __esm(() => {
764
+ var DEFAULT_REPLACEMENT = "[REDACTED]", builtinPatterns, _tsDate, POST_EMIT_FORK_HINT = "For intentional background work tied to this request, use log.fork('label', fn) when your integration supports it (see https://evlog.dev).", globalEnv, globalPretty, globalSampling, globalStringify = true, globalDrain, globalRedact, globalEnabled = true, globalSilent = false, globalMinLevel = "debug", _log, noopLogger;
765
+ var init_logger_DnobymUQ = __esm(() => {
429
766
  init_utils();
767
+ builtinPatterns = {
768
+ creditCard: {
769
+ pattern: /\b\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}\b/g,
770
+ mask: (m) => `****${m.replace(/[\s-]/g, "").slice(-4)}`
771
+ },
772
+ email: {
773
+ pattern: /[\w.+-]+@[\w-]+\.[\w.]+/g,
774
+ mask: (m) => {
775
+ if (m.indexOf("@") < 1)
776
+ return "***@***";
777
+ const tld = m.slice(m.lastIndexOf("."));
778
+ return `${m[0]}***@***${tld}`;
779
+ }
780
+ },
781
+ ipv4: {
782
+ pattern: /\b(?!0\.0\.0\.0\b)(?!127\.0\.0\.1\b)\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/g,
783
+ mask: (m) => `***.***.***.${m.split(".").pop()}`
784
+ },
785
+ phone: {
786
+ pattern: /(?:\+\d{1,3}[\s.-]?)?\(?\d{1,4}\)?[\s.-]?\d{2,4}[\s.-]?\d{2,4}[\s.-]?\d{2,4}\b/g,
787
+ mask: (m) => {
788
+ const digits = m.replace(/[^\d]/g, "");
789
+ if (m.startsWith("+") && digits.length > 4) {
790
+ const ccMatch = m.match(/^\+\d{1,3}/);
791
+ return `${ccMatch ? ccMatch[0] : "+"}******${digits.slice(-2)}`;
792
+ }
793
+ if (digits.length > 2)
794
+ return `${"*".repeat(digits.length - 2)}${digits.slice(-2)}`;
795
+ return "***";
796
+ }
797
+ },
798
+ jwt: {
799
+ pattern: /\beyJ[\w-]*\.[\w-]*\.[\w-]*\b/g,
800
+ mask: () => "eyJ***.***"
801
+ },
802
+ bearer: {
803
+ pattern: /\bBearer\s+[\w\-.~+/]{8,}=*/gi,
804
+ mask: () => "Bearer ***"
805
+ },
806
+ iban: {
807
+ pattern: /\b[A-Z]{2}\d{2}[\s-]?[\dA-Z]{4}[\s-]?[\dA-Z]{4}[\s-]?[\dA-Z]{4}[\s-]?[\dA-Z]{0,4}[\s-]?[\dA-Z]{0,4}[\s-]?[\dA-Z]{0,4}\b/g,
808
+ mask: (m) => {
809
+ const clean = m.replace(/[\s-]/g, "");
810
+ return `${clean.slice(0, 4)}****${clean.slice(-3)}`;
811
+ }
812
+ }
813
+ };
430
814
  _tsDate = /* @__PURE__ */ new Date;
431
815
  globalEnv = {
432
816
  service: "app",
@@ -456,7 +840,12 @@ var init_logger = __esm(() => {
456
840
  initLogger(__EVLOG_CONFIG__);
457
841
  });
458
842
 
459
- // ../../node_modules/.bun/evlog@2.11.0+a1ab7c6fe65f988d/node_modules/evlog/dist/errors-gH4C9KSC.mjs
843
+ // ../../node_modules/.bun/evlog@2.13.0+449e6d239244fccb/node_modules/evlog/dist/index.mjs
844
+ var init_dist = __esm(() => {
845
+ init_logger_DnobymUQ();
846
+ });
847
+
848
+ // ../../node_modules/.bun/evlog@2.13.0+449e6d239244fccb/node_modules/evlog/dist/errors-BJRXUfMg.mjs
460
849
  function extractErrorStatus(error) {
461
850
  if (error === null || typeof error !== "object")
462
851
  return 500;
@@ -464,9 +853,9 @@ function extractErrorStatus(error) {
464
853
  const status = Number(raw);
465
854
  return Number.isFinite(status) ? status : 500;
466
855
  }
467
- var init_errors_gH4C9KSC = () => {};
856
+ var init_errors_BJRXUfMg = () => {};
468
857
 
469
- // ../../node_modules/.bun/evlog@2.11.0+a1ab7c6fe65f988d/node_modules/evlog/dist/routes-CE3_c-iZ.mjs
858
+ // ../../node_modules/.bun/evlog@2.13.0+449e6d239244fccb/node_modules/evlog/dist/routes-CGPmbzCZ.mjs
470
859
  function shouldLog(path, include, exclude) {
471
860
  if (exclude && exclude.length > 0) {
472
861
  if (exclude.some((pattern) => matchesPattern(path, pattern)))
@@ -483,12 +872,15 @@ function getServiceForPath(path, routes) {
483
872
  if (matchesPattern(path, pattern))
484
873
  return config.service;
485
874
  }
486
- var init_routes_CE3_c_iZ = __esm(() => {
875
+ var init_routes_CGPmbzCZ = __esm(() => {
487
876
  init_utils();
488
877
  });
489
878
 
490
- // ../../node_modules/.bun/evlog@2.11.0+a1ab7c6fe65f988d/node_modules/evlog/dist/headers-BSi3UHKL.mjs
879
+ // ../../node_modules/.bun/evlog@2.13.0+449e6d239244fccb/node_modules/evlog/dist/middleware-BtBuosFV.mjs
491
880
  async function runEnrichAndDrain(emittedEvent, options, requestInfo, responseStatus) {
881
+ const resolvedRedact = resolveRedactConfig(options.redact);
882
+ if (resolvedRedact)
883
+ redactEvent(emittedEvent, resolvedRedact);
492
884
  if (options.enrich) {
493
885
  const enrichCtx = {
494
886
  event: emittedEvent,
@@ -570,10 +962,10 @@ function createMiddlewareLogger(options) {
570
962
  };
571
963
  }
572
964
  var noopResult;
573
- var init_headers_BSi3UHKL = __esm(() => {
574
- init_logger();
575
- init_errors_gH4C9KSC();
576
- init_routes_CE3_c_iZ();
965
+ var init_middleware_BtBuosFV = __esm(() => {
966
+ init_logger_DnobymUQ();
967
+ init_errors_BJRXUfMg();
968
+ init_routes_CGPmbzCZ();
577
969
  noopResult = {
578
970
  logger: {
579
971
  set() {},
@@ -592,7 +984,70 @@ var init_headers_BSi3UHKL = __esm(() => {
592
984
  };
593
985
  });
594
986
 
595
- // ../../node_modules/.bun/evlog@2.11.0+a1ab7c6fe65f988d/node_modules/evlog/dist/elysia/index.mjs
987
+ // ../../node_modules/.bun/evlog@2.13.0+449e6d239244fccb/node_modules/evlog/dist/fork-Y4z8iHti.mjs
988
+ function attachForkToLogger(storage, parent, middlewareOptions, lifecycle) {
989
+ const log = parent;
990
+ log.fork = (label, fn) => {
991
+ forkBackgroundLogger({
992
+ storage,
993
+ parent,
994
+ middlewareOptions,
995
+ label,
996
+ fn,
997
+ lifecycle
998
+ });
999
+ };
1000
+ }
1001
+ function forkBackgroundLogger(options) {
1002
+ const { storage, parent, middlewareOptions, label, fn, lifecycle } = options;
1003
+ const parentCtx = parent.getContext();
1004
+ const parentRequestId = parentCtx.requestId;
1005
+ if (typeof parentRequestId !== "string" || parentRequestId.length === 0)
1006
+ throw new Error("[evlog] log.fork() requires the parent logger to have a requestId. Ensure the request was created by evlog middleware.");
1007
+ const method = String(parentCtx.method ?? middlewareOptions.method);
1008
+ const path = String(parentCtx.path ?? middlewareOptions.path);
1009
+ const child = createRequestLogger({
1010
+ method,
1011
+ path,
1012
+ requestId: crypto.randomUUID()
1013
+ }, { _deferDrain: true });
1014
+ child.set({
1015
+ operation: label,
1016
+ _parentRequestId: parentRequestId
1017
+ });
1018
+ const childRequestInfo = {
1019
+ method,
1020
+ path,
1021
+ requestId: child.getContext().requestId
1022
+ };
1023
+ storage.run(child, () => {
1024
+ lifecycle?.onChildEnter?.(child);
1025
+ Promise.resolve().then(() => fn()).then(async () => {
1026
+ const emittedEvent = child.emit();
1027
+ const ctxStatus = child.getContext().status;
1028
+ const status = emittedEvent?.status ?? (typeof ctxStatus === "number" ? ctxStatus : undefined);
1029
+ if (emittedEvent && (middlewareOptions.enrich || middlewareOptions.drain || getGlobalDrain()))
1030
+ await runEnrichAndDrain(emittedEvent, middlewareOptions, childRequestInfo, status);
1031
+ }).catch(async (err) => {
1032
+ const error = err instanceof Error ? err : new Error(String(err));
1033
+ child.error(error);
1034
+ child.set({ status: extractErrorStatus(error) });
1035
+ const emittedEvent = child.emit();
1036
+ const status = extractErrorStatus(error);
1037
+ if (emittedEvent && (middlewareOptions.enrich || middlewareOptions.drain || getGlobalDrain()))
1038
+ await runEnrichAndDrain(emittedEvent, middlewareOptions, childRequestInfo, status);
1039
+ }).finally(() => {
1040
+ lifecycle?.onChildExit?.(child);
1041
+ });
1042
+ });
1043
+ }
1044
+ var init_fork_Y4z8iHti = __esm(() => {
1045
+ init_logger_DnobymUQ();
1046
+ init_errors_BJRXUfMg();
1047
+ init_middleware_BtBuosFV();
1048
+ });
1049
+
1050
+ // ../../node_modules/.bun/evlog@2.13.0+449e6d239244fccb/node_modules/evlog/dist/elysia/index.mjs
596
1051
  import { AsyncLocalStorage } from "async_hooks";
597
1052
  import { Elysia } from "elysia";
598
1053
  function useLogger2() {
@@ -605,15 +1060,25 @@ function evlog(options = {}) {
605
1060
  const emitted = /* @__PURE__ */ new WeakSet;
606
1061
  const requestState = /* @__PURE__ */ new WeakMap;
607
1062
  return new Elysia({ name: "evlog" }).derive({ as: "global" }, ({ request, path, headers }) => {
608
- const { logger, finish, skipped } = createMiddlewareLogger({
1063
+ const middlewareOpts = {
609
1064
  method: request.method,
610
1065
  path,
611
1066
  requestId: headers["x-request-id"] || crypto.randomUUID(),
612
1067
  headers: filterSafeHeaders(headers),
613
1068
  ...options
614
- });
615
- if (!skipped)
1069
+ };
1070
+ const { logger, finish, skipped } = createMiddlewareLogger(middlewareOpts);
1071
+ if (!skipped) {
1072
+ attachForkToLogger(storage, logger, middlewareOpts, {
1073
+ onChildEnter: (child) => {
1074
+ activeLoggers.add(child);
1075
+ },
1076
+ onChildExit: (child) => {
1077
+ activeLoggers.delete(child);
1078
+ }
1079
+ });
616
1080
  activeLoggers.add(logger);
1081
+ }
617
1082
  storage.enterWith(logger);
618
1083
  requestState.set(request, {
619
1084
  finish,
@@ -644,7 +1109,8 @@ function evlog(options = {}) {
644
1109
  var storage, activeLoggers;
645
1110
  var init_elysia = __esm(() => {
646
1111
  init_utils();
647
- init_headers_BSi3UHKL();
1112
+ init_middleware_BtBuosFV();
1113
+ init_fork_Y4z8iHti();
648
1114
  storage = new AsyncLocalStorage;
649
1115
  activeLoggers = /* @__PURE__ */ new WeakSet;
650
1116
  });
@@ -761,6 +1227,21 @@ var init_cache = __esm(() => {
761
1227
  _globalPendingInvalidations = new Set;
762
1228
  });
763
1229
 
1230
+ // src/link.tsx
1231
+ import {
1232
+ createContext,
1233
+ createElement,
1234
+ useCallback,
1235
+ useContext,
1236
+ useEffect,
1237
+ useRef,
1238
+ useState
1239
+ } from "react";
1240
+ var RouterContext;
1241
+ var init_link = __esm(() => {
1242
+ RouterContext = createContext(null);
1243
+ });
1244
+
764
1245
  // src/render/shell.ts
765
1246
  function extractTitle(meta) {
766
1247
  if (!meta) {
@@ -929,21 +1410,48 @@ function buildElement(route, data, rootLayout) {
929
1410
  var init_element = () => {};
930
1411
 
931
1412
  // src/render/loaders.ts
932
- async function runLoaders(route, ctx, rootLayout) {
1413
+ function createLoaderCtx(ctx, accumulatedParentPromise) {
1414
+ const cache = new Map;
1415
+ return new Proxy(ctx, {
1416
+ get(target, prop) {
1417
+ if (typeof prop !== "string") {
1418
+ return Reflect.get(target, prop);
1419
+ }
1420
+ if (prop === "then" || prop === "catch" || prop === "finally" || prop === "toJSON") {
1421
+ return Reflect.get(target, prop);
1422
+ }
1423
+ if (Object.hasOwn(target, prop)) {
1424
+ return target[prop];
1425
+ }
1426
+ let entry = cache.get(prop);
1427
+ if (!entry) {
1428
+ entry = accumulatedParentPromise.then((data) => data[prop]);
1429
+ cache.set(prop, entry);
1430
+ }
1431
+ return entry;
1432
+ }
1433
+ });
1434
+ }
1435
+ async function runLoaders(route, ctx, _rootLayout) {
933
1436
  try {
1437
+ const ctxRecord = ctx;
934
1438
  const loaderMap = new Map;
935
- const deps = (routeRef) => loaderMap.get(routeRef) ?? Promise.resolve({});
936
- const rootPromise = rootLayout.loader ? Promise.resolve(rootLayout.loader({ ...ctx }, deps)).then((r) => r ?? {}) : Promise.resolve({});
937
- loaderMap.set(rootLayout, rootPromise);
938
- const rootData = await rootPromise;
939
- const ctxWithRoot = { ...ctx, ...rootData };
940
- for (let i = 1;i < route.routeChain.length; i++) {
941
- const ancestor = route.routeChain[i];
942
- if (ancestor?.loader) {
943
- loaderMap.set(ancestor, Promise.resolve(ancestor.loader(ctxWithRoot, deps)).then((r) => r ?? {}));
1439
+ let accumulatedParentPromise = Promise.resolve({});
1440
+ for (const r of route.routeChain) {
1441
+ const parentAccum = accumulatedParentPromise;
1442
+ if (r.loader) {
1443
+ const loaderCtx = createLoaderCtx(ctxRecord, parentAccum);
1444
+ const loaderPromise = Promise.resolve(r.loader(loaderCtx)).then((res) => res ?? {});
1445
+ loaderMap.set(r, loaderPromise);
1446
+ accumulatedParentPromise = Promise.all([parentAccum, loaderPromise]).then(([acc, own]) => ({
1447
+ ...acc,
1448
+ ...own
1449
+ }));
1450
+ accumulatedParentPromise.catch(() => {});
944
1451
  }
945
1452
  }
946
- const pagePromise = route.page?.loader ? Promise.resolve(route.page.loader(ctxWithRoot, deps)).then((r) => r ?? {}) : Promise.resolve({});
1453
+ const pageCtx = createLoaderCtx(ctxRecord, accumulatedParentPromise);
1454
+ const pagePromise = route.page?.loader ? Promise.resolve(route.page.loader(pageCtx)).then((r) => r ?? {}) : Promise.resolve({});
947
1455
  const results = await Promise.all([...loaderMap.values(), pagePromise]);
948
1456
  const data = Object.assign({}, ...results);
949
1457
  const headers = {};
@@ -1000,8 +1508,9 @@ var init_template = () => {};
1000
1508
  var IS_DEV = true;
1001
1509
 
1002
1510
  // src/render/index.ts
1511
+ import { createElement as createElement2 } from "react";
1003
1512
  import { renderToReadableStream } from "react-dom/server";
1004
- async function prepareRender(route, ctx, root) {
1513
+ async function prepareRender(route, ctx, root, basePath) {
1005
1514
  const loaderStart = Date.now();
1006
1515
  const loaderResult = await runLoaders(route, ctx, root.route);
1007
1516
  const loader_ms = Date.now() - loaderStart;
@@ -1016,13 +1525,29 @@ async function prepareRender(route, ctx, root) {
1016
1525
  path: ctx.path
1017
1526
  };
1018
1527
  const headData = buildHeadInjection(route.page?.head?.(componentProps));
1019
- const template = IS_DEV ? await getDevTemplate(new URL(ctx.request.url).origin) : getProductionTemplate() ?? generateIndexHtml();
1020
- const element = buildElement(route, componentProps, root.route);
1528
+ const prodTemplate = getProductionTemplate();
1529
+ const template = prodTemplate ?? (IS_DEV ? await getDevTemplate(new URL(ctx.request.url).origin) : generateIndexHtml());
1530
+ let element = buildElement(route, componentProps, root.route);
1531
+ if (basePath !== undefined) {
1532
+ const ssrContext = {
1533
+ basePath,
1534
+ currentHref: ctx.path,
1535
+ navigate: () => Promise.resolve(),
1536
+ prefetch: () => {},
1537
+ invalidatePrefetch: () => {},
1538
+ refresh: () => Promise.resolve(),
1539
+ isNavigating: false,
1540
+ defaultPreload: "intent",
1541
+ defaultPreloadDelay: 50,
1542
+ defaultPreloadStaleTime: 30000
1543
+ };
1544
+ element = createElement2(RouterContext.Provider, { value: ssrContext }, element);
1545
+ }
1021
1546
  return { componentProps, element, headData, headers, loader_ms, template };
1022
1547
  }
1023
- async function renderForPath(route, params, root, origin) {
1548
+ async function renderForPath(route, params, root, origin, basePath) {
1024
1549
  const resolvedPath = resolvePath(route.pattern, params);
1025
- return await renderToHTML(route, {
1550
+ const ctx = {
1026
1551
  params,
1027
1552
  query: {},
1028
1553
  request: new Request(`${origin}${resolvedPath}`),
@@ -1031,10 +1556,8 @@ async function renderForPath(route, params, root, origin) {
1031
1556
  redirect: (url, status = 302) => new Response(null, { status, headers: { Location: url } }),
1032
1557
  set: { headers: {} },
1033
1558
  path: resolvedPath
1034
- }, root);
1035
- }
1036
- async function renderToHTML(route, ctx, root) {
1037
- const prepared = await prepareRender(route, ctx, root);
1559
+ };
1560
+ const prepared = await prepareRender(route, ctx, root, basePath);
1038
1561
  if (prepared instanceof Response) {
1039
1562
  throw prepared;
1040
1563
  }
@@ -1047,7 +1570,7 @@ async function renderToHTML(route, ctx, root) {
1047
1570
  headers
1048
1571
  };
1049
1572
  }
1050
- async function prerenderSSG(route, params, root, origin = "http://localhost:3000") {
1573
+ async function prerenderSSG(route, params, root, origin = "http://localhost:3000", basePath) {
1051
1574
  const resolvedPath = resolvePath(route.pattern, params);
1052
1575
  const cached = getSSGCache(resolvedPath);
1053
1576
  if (cached && !IS_DEV) {
@@ -1055,7 +1578,7 @@ async function prerenderSSG(route, params, root, origin = "http://localhost:3000
1055
1578
  }
1056
1579
  let result;
1057
1580
  try {
1058
- result = await renderForPath(route, params, root, origin);
1581
+ result = await renderForPath(route, params, root, origin, basePath);
1059
1582
  } catch (err) {
1060
1583
  if (err instanceof Response) {
1061
1584
  return err;
@@ -1218,6 +1741,7 @@ function revalidateInBackground(route, params, cacheKey, revalidate, root, origi
1218
1741
  }
1219
1742
  var SSG_WARM_CONCURRENCY = 4, pendingRevalidations;
1220
1743
  var init_render = __esm(() => {
1744
+ init_link();
1221
1745
  init_assemble();
1222
1746
  init_cache();
1223
1747
  init_element();
@@ -1412,11 +1936,17 @@ function queryDefaultRedirectHook({ request, query, status, set }) {
1412
1936
  }
1413
1937
  async function handleDevRequest(route, ctx, root) {
1414
1938
  try {
1939
+ let currentRoot = root;
1940
+ const rootMod = await import(`${root.path}?furin-server&t=${Date.now()}`);
1941
+ const rootExport = rootMod.route ?? rootMod.default;
1942
+ if (rootExport && isFurinRoute(rootExport) && rootExport.layout) {
1943
+ currentRoot = { path: root.path, route: rootExport };
1944
+ }
1415
1945
  const pageMod = await import(`${route.path}?furin-server&t=${Date.now()}`);
1416
1946
  const page = pageMod.default;
1417
1947
  if (page && isFurinPage(page)) {
1418
1948
  const chain = collectRouteChainFromRoute(page._route);
1419
- return renderSSR({ ...route, page, routeChain: chain }, ctx, root);
1949
+ return renderSSR({ ...route, page, routeChain: chain }, ctx, currentRoot);
1420
1950
  }
1421
1951
  } catch (err) {
1422
1952
  console.error(`[furin] Dev page load error for ${route.path}:`, err);
@@ -1533,10 +2063,62 @@ var init_router = __esm(() => {
1533
2063
  // src/dev-page-plugin.ts
1534
2064
  var exports_dev_page_plugin = {};
1535
2065
  __export(exports_dev_page_plugin, {
2066
+ rewriteSingletonImports: () => rewriteSingletonImports,
1536
2067
  rewriteRelativeImports: () => rewriteRelativeImports,
1537
- registerDevPagePlugin: () => registerDevPagePlugin
2068
+ rewriteBareImports: () => rewriteBareImports,
2069
+ registerDevPagePlugin: () => registerDevPagePlugin,
2070
+ injectJsxHelperImports: () => injectJsxHelperImports
1538
2071
  });
1539
2072
  import { dirname, resolve } from "path";
2073
+ import { fileURLToPath } from "url";
2074
+ function escapeRegExp(s) {
2075
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2076
+ }
2077
+ function rewriteSingletonImports(source) {
2078
+ let result = source;
2079
+ for (const [pkg, absPath] of SINGLETON_PATHS) {
2080
+ const re = new RegExp(`((?:from|import(?:\\s+type)?)\\s+)["']${escapeRegExp(pkg)}["']`, "g");
2081
+ result = result.replace(re, (_, g1) => `${g1}"${absPath}"`);
2082
+ }
2083
+ return result;
2084
+ }
2085
+ function injectJsxHelperImports(transpiled) {
2086
+ const JSX_HELPER_RE = /\b(jsxDEV|jsxs|jsx|Fragment)_([0-9a-z]{8})\b/g;
2087
+ const devRuntime = new Map;
2088
+ const prodRuntime = new Map;
2089
+ for (const [, base, hash] of transpiled.matchAll(JSX_HELPER_RE)) {
2090
+ if (!(base && hash)) {
2091
+ continue;
2092
+ }
2093
+ const varName = `${base}_${hash}`;
2094
+ if (base === "jsxDEV" || base === "Fragment") {
2095
+ devRuntime.set(varName, base);
2096
+ } else {
2097
+ prodRuntime.set(varName, base);
2098
+ }
2099
+ }
2100
+ const lines = [];
2101
+ if (devRuntime.size > 0) {
2102
+ const absPath = SINGLETON_PATHS.get("react/jsx-dev-runtime");
2103
+ if (absPath) {
2104
+ const specifiers = [...devRuntime.entries()].map(([varName, exportName]) => `${exportName} as ${varName}`).join(", ");
2105
+ lines.push(`import { ${specifiers} } from "${absPath}";`);
2106
+ }
2107
+ }
2108
+ if (prodRuntime.size > 0) {
2109
+ const absPath = SINGLETON_PATHS.get("react/jsx-runtime");
2110
+ if (absPath) {
2111
+ const specifiers = [...prodRuntime.entries()].map(([varName, exportName]) => `${exportName} as ${varName}`).join(", ");
2112
+ lines.push(`import { ${specifiers} } from "${absPath}";`);
2113
+ }
2114
+ }
2115
+ if (lines.length === 0) {
2116
+ return transpiled;
2117
+ }
2118
+ return `${lines.join(`
2119
+ `)}
2120
+ ${transpiled}`;
2121
+ }
1540
2122
  function rewriteRelativeImports(source, dir) {
1541
2123
  return source.replace(RELATIVE_SPECIFIER_RE, (match, relPath, offset) => {
1542
2124
  const lineStart = source.lastIndexOf(`
@@ -1550,6 +2132,72 @@ function rewriteRelativeImports(source, dir) {
1550
2132
  return `${keyword} "${absPath}"`;
1551
2133
  });
1552
2134
  }
2135
+ function rewriteBareImports(source, transpiled, dir) {
2136
+ const scanner = new Bun.Transpiler({ loader: "tsx" });
2137
+ let { imports } = scanner.scan(source);
2138
+ const seen = new Set;
2139
+ imports = imports.filter((imp) => {
2140
+ if (seen.has(imp.path)) {
2141
+ return false;
2142
+ }
2143
+ seen.add(imp.path);
2144
+ return true;
2145
+ });
2146
+ let result = transpiled;
2147
+ for (const imp of imports) {
2148
+ const spec = imp.path;
2149
+ if (spec.startsWith(".") || spec.startsWith("/") || spec.startsWith("file:")) {
2150
+ continue;
2151
+ }
2152
+ if (SINGLETON_PATHS.has(spec)) {
2153
+ continue;
2154
+ }
2155
+ let resolved;
2156
+ try {
2157
+ resolved = Bun.resolveSync(spec, dir);
2158
+ } catch {
2159
+ continue;
2160
+ }
2161
+ const re = new RegExp(`((?:from|import(?:\\s+type)?)\\s+)["']${escapeRegExp(spec)}["']`, "g");
2162
+ result = result.replace(re, (_, g1) => `${g1}"${resolved}"`);
2163
+ }
2164
+ return result;
2165
+ }
2166
+ function getSourceLoader(filePath) {
2167
+ if (filePath.endsWith(".tsx")) {
2168
+ return "tsx";
2169
+ }
2170
+ if (filePath.endsWith(".ts")) {
2171
+ return "ts";
2172
+ }
2173
+ if (filePath.endsWith(".jsx")) {
2174
+ return "jsx";
2175
+ }
2176
+ if (filePath.endsWith(".js")) {
2177
+ return "js";
2178
+ }
2179
+ return null;
2180
+ }
2181
+ function shouldSkipWorkspaceTransform(filePath) {
2182
+ const normalized = filePath.replace(/\\/g, "/");
2183
+ return normalized.includes("/.furin/");
2184
+ }
2185
+ function transformDevSource(raw, filePath, options) {
2186
+ const loader = getSourceLoader(filePath);
2187
+ if (!loader) {
2188
+ throw new Error(`[furin] Unsupported source loader for ${filePath}`);
2189
+ }
2190
+ const dir = dirname(filePath);
2191
+ const sourceForTranspile = options.rewriteRelativeImports ? rewriteRelativeImports(raw, dir) : raw;
2192
+ const transpiler = new Bun.Transpiler({ loader });
2193
+ const transpiled = transpiler.transformSync(sourceForTranspile, loader);
2194
+ let result = transpiled;
2195
+ if (options.rewriteBareImports) {
2196
+ result = rewriteBareImports(raw, result, dir);
2197
+ }
2198
+ result = rewriteSingletonImports(result);
2199
+ return injectJsxHelperImports(result);
2200
+ }
1553
2201
  function registerDevPagePlugin() {
1554
2202
  Bun.plugin({
1555
2203
  name: "furin-dev-page-loader",
@@ -1560,25 +2208,64 @@ function registerDevPagePlugin() {
1560
2208
  const resolvedPath = tMatch ? `${filePath}?t=${tMatch[1]}` : filePath;
1561
2209
  return { path: resolvedPath, namespace: "furin-dev-page" };
1562
2210
  });
2211
+ build.onLoad({ filter: WORKSPACE_SOURCE_FILTER }, async (args) => {
2212
+ const raw = await Bun.file(args.path).text();
2213
+ const loader = getSourceLoader(args.path);
2214
+ if (!loader) {
2215
+ throw new Error(`[furin] Unsupported source loader for ${args.path}`);
2216
+ }
2217
+ if (shouldSkipWorkspaceTransform(args.path)) {
2218
+ return {
2219
+ contents: raw,
2220
+ loader
2221
+ };
2222
+ }
2223
+ const contents = transformDevSource(raw, args.path, {
2224
+ rewriteBareImports: false,
2225
+ rewriteRelativeImports: false
2226
+ });
2227
+ return {
2228
+ contents,
2229
+ loader: "js"
2230
+ };
2231
+ });
1563
2232
  build.onLoad({ namespace: "furin-dev-page", filter: ANY_FILTER }, async (args) => {
1564
2233
  const filePath = args.path.replace(STRIP_T_PARAM_RE, "");
1565
2234
  const raw = await Bun.file(filePath).text();
1566
- const contents = rewriteRelativeImports(raw, dirname(filePath));
2235
+ const contents = transformDevSource(raw, filePath, {
2236
+ rewriteBareImports: true,
2237
+ rewriteRelativeImports: true
2238
+ });
1567
2239
  return {
1568
2240
  contents,
1569
- loader: filePath.endsWith(".tsx") ? "tsx" : "ts"
2241
+ loader: "js"
1570
2242
  };
1571
2243
  });
1572
2244
  }
1573
2245
  });
1574
2246
  }
1575
- var FURIN_SERVER_FILTER, ANY_FILTER, T_PARAM_RE, STRIP_FURIN_SERVER_RE, STRIP_T_PARAM_RE, RELATIVE_SPECIFIER_RE;
2247
+ var FURIN_SERVER_FILTER, ANY_FILTER, WORKSPACE_SOURCE_FILTER, T_PARAM_RE, STRIP_FURIN_SERVER_RE, STRIP_T_PARAM_RE, SINGLETON_PKGS, SINGLETON_PATHS, RELATIVE_SPECIFIER_RE;
1576
2248
  var init_dev_page_plugin = __esm(() => {
1577
2249
  FURIN_SERVER_FILTER = /\?furin-server(?:&t=\d+)?$/;
1578
2250
  ANY_FILTER = /.*/;
2251
+ WORKSPACE_SOURCE_FILTER = /^(?!.*(?:\/node_modules\/|\/\.bun\/))(?!.*\.(?:test|spec)\.[jt]sx?$).*\.[jt]sx?$/;
1579
2252
  T_PARAM_RE = /&t=(\d+)/;
1580
2253
  STRIP_FURIN_SERVER_RE = /\?furin-server.*$/;
1581
2254
  STRIP_T_PARAM_RE = /\?t=\d+$/;
2255
+ SINGLETON_PKGS = [
2256
+ "react",
2257
+ "react/jsx-runtime",
2258
+ "react/jsx-dev-runtime",
2259
+ "react-dom",
2260
+ "react-dom/server",
2261
+ "react-dom/client"
2262
+ ];
2263
+ SINGLETON_PATHS = new Map;
2264
+ for (const pkg of SINGLETON_PKGS) {
2265
+ try {
2266
+ SINGLETON_PATHS.set(pkg, fileURLToPath(import.meta.resolve(pkg)));
2267
+ } catch {}
2268
+ }
1582
2269
  RELATIVE_SPECIFIER_RE = /(?:from|import)\s+["'](\.\.?\/[^"']+)["']/g;
1583
2270
  });
1584
2271
 
@@ -1655,28 +2342,33 @@ __export(exports_hydrate, {
1655
2342
  });
1656
2343
  import { existsSync as existsSync3, mkdirSync, readFileSync as readFileSync3, writeFileSync as writeFileSync2 } from "fs";
1657
2344
  import { join as join3 } from "path";
1658
- function generateHydrateEntry(routes, rootLayout) {
2345
+ function generateHydrateEntry(routes, rootLayout, basePath) {
1659
2346
  const routeEntries = [];
1660
2347
  for (const route of routes) {
1661
2348
  const resolvedPage = route.path.replace(/\\/g, "/");
1662
2349
  const regexPattern = route.pattern.replace(/:[^/]+/g, "([^/]+)").replace(/\*/g, "(.*)");
1663
2350
  routeEntries.push(` { pattern: "${route.pattern}", regex: new RegExp("^${regexPattern}$"), load: () => import("${resolvedPage}") }`);
1664
2351
  }
2352
+ const basePathLiteral = JSON.stringify(basePath);
2353
+ const pathnameExpr = basePath ? `(() => { const p = window.location.pathname; const b = ${basePathLiteral}; return (p.startsWith(b) && (p.length === b.length || p[b.length] === "/")) ? p.slice(b.length) || "/" : p; })()` : "window.location.pathname";
2354
+ const logEndpoint = basePath ? `${JSON.stringify(basePath)} + "/_furin/ingest"` : `"/_furin/ingest"`;
2355
+ const basePathProp = basePath ? `
2356
+ basePath: ${basePathLiteral},` : "";
1665
2357
  return `import { hydrateRoot, createRoot } from "react-dom/client";
1666
2358
  import { createElement } from "react";
1667
2359
  import { initLogger, log } from "evlog";
1668
- import { createBrowserLogDrain } from "evlog/browser";
2360
+ import { createHttpLogDrain } from "evlog/http";
1669
2361
  import { RouterProvider } from "@teyik0/furin/link";
1670
2362
  import { route as root } from "${rootLayout.replace(/\\/g, "/")}";
1671
2363
 
1672
- initLogger({ drain: createBrowserLogDrain({ drain: { endpoint: "/_furin/ingest" } }) });
2364
+ initLogger({ drain: createHttpLogDrain({ drain: { endpoint: ${logEndpoint} } }) });
1673
2365
 
1674
2366
  const routes = [
1675
2367
  ${routeEntries.join(`,
1676
2368
  `)}
1677
2369
  ];
1678
2370
 
1679
- const pathname = window.location.pathname;
2371
+ const pathname = ${pathnameExpr};
1680
2372
  const _match = routes.find((r) => r.regex.test(pathname));
1681
2373
 
1682
2374
  // Eagerly load only the current page module for initial hydration.
@@ -1696,7 +2388,7 @@ const _match = routes.find((r) => r.regex.test(pathname));
1696
2388
  routes,
1697
2389
  root,
1698
2390
  initialMatch: match,
1699
- initialData: loaderData,
2391
+ initialData: loaderData,${basePathProp}
1700
2392
  } as any);
1701
2393
 
1702
2394
  if (import.meta.hot) {
@@ -1721,14 +2413,16 @@ const _match = routes.find((r) => r.regex.test(pathname));
1721
2413
  } else {
1722
2414
  log.error({ action: "hydrate_no_match", pathname });
1723
2415
  }
1724
- })();
2416
+ })().catch((err: unknown) => {
2417
+ log.error({ action: "hydrate_failed", pathname, error: String(err) });
2418
+ });
1725
2419
  `;
1726
2420
  }
1727
- function writeDevFiles(routes, { outDir, rootLayout }, projectRoot) {
2421
+ function writeDevFiles(routes, { outDir, rootLayout, basePath }, projectRoot) {
1728
2422
  if (!existsSync3(outDir)) {
1729
2423
  mkdirSync(outDir, { recursive: true });
1730
2424
  }
1731
- const hydrateCode = generateHydrateEntry(routes, rootLayout);
2425
+ const hydrateCode = generateHydrateEntry(routes, rootLayout, basePath);
1732
2426
  const hydratePath = join3(outDir, "_hydrate.tsx");
1733
2427
  const existingHydrate = existsSync3(hydratePath) ? readFileSync3(hydratePath, "utf8") : "";
1734
2428
  if (hydrateCode !== existingHydrate) {
@@ -1749,22 +2443,18 @@ var init_hydrate = __esm(() => {
1749
2443
  });
1750
2444
 
1751
2445
  // src/furin.ts
1752
- import { existsSync as existsSync4 } from "fs";
1753
- import { basename, dirname as dirname2, join as join4, resolve as resolve2 } from "path";
1754
- import { fileURLToPath } from "url";
1755
- import { staticPlugin } from "@elysiajs/static";
1756
- import { Elysia as Elysia3, file } from "elysia";
1757
-
1758
- // ../../node_modules/.bun/evlog@2.11.0+a1ab7c6fe65f988d/node_modules/evlog/dist/index.mjs
1759
- init_logger();
1760
-
1761
- // src/furin.ts
2446
+ init_dist();
1762
2447
  init_elysia();
1763
2448
  init_cache();
1764
2449
  init_render();
1765
2450
  init_template();
1766
2451
  init_router();
1767
2452
  init_cache();
2453
+ import { existsSync as existsSync4 } from "fs";
2454
+ import { basename, dirname as dirname2, join as join4, resolve as resolve2 } from "path";
2455
+ import { fileURLToPath as fileURLToPath2 } from "url";
2456
+ import { staticPlugin } from "@elysiajs/static";
2457
+ import { Elysia as Elysia3, file } from "elysia";
1768
2458
  function resolveClientDirFromArgv() {
1769
2459
  return resolveClientDirFromEnv() ?? resolveClientDirFromModuleUrl() ?? resolveClientDirFromProcessArgs() ?? resolveFallbackClientDir();
1770
2460
  }
@@ -1781,7 +2471,7 @@ function resolveClientDirFromModuleUrl() {
1781
2471
  if (moduleUrl.protocol !== "file:") {
1782
2472
  return null;
1783
2473
  }
1784
- const modulePath = fileURLToPath(moduleUrl);
2474
+ const modulePath = fileURLToPath2(moduleUrl);
1785
2475
  if (modulePath.includes("/$bunfs/")) {
1786
2476
  return null;
1787
2477
  }
@@ -1912,7 +2602,7 @@ async function furin({
1912
2602
  const { scanPages: scanPages2 } = await Promise.resolve().then(() => (init_router(), exports_router));
1913
2603
  const { root: root2, routes: routes2 } = await scanPages2(resolvedPagesDir);
1914
2604
  const { writeDevFiles: writeDevFiles2 } = await Promise.resolve().then(() => (init_hydrate(), exports_hydrate));
1915
- writeDevFiles2(routes2, { outDir: furinDir, rootLayout: root2.path }, cwd);
2605
+ writeDevFiles2(routes2, { outDir: furinDir, rootLayout: root2.path, basePath: "", publicPath: "/_client/" }, cwd);
1916
2606
  const publicDir = resolve2(cwd, "public");
1917
2607
  const publicExists = existsSync4(publicDir);
1918
2608
  const devApp = new Elysia3({ name: instanceName, seed: resolvedPagesDir }).use(loggerPlugin).onAfterHandle({ as: "global" }, ({ set }) => {
@@ -1920,7 +2610,7 @@ async function furin({
1920
2610
  if (pending.length > 0) {
1921
2611
  set.headers["x-furin-revalidate"] = pending.join(",");
1922
2612
  }
1923
- }).use(await staticPlugin({ assets: furinDir, prefix: "/_bun_hmr_entry" })).use(publicExists ? await staticPlugin({ assets: publicDir, prefix: "/public" }) : new Elysia3).get("/favicon.ico", publicExists ? file(join4(publicDir, "favicon.ico")) : () => new Response(null, { status: 404 })).use((app) => {
2613
+ }).use(await staticPlugin({ assets: furinDir, prefix: "/_bun_hmr_entry", bunFullstack: true })).use(publicExists ? await staticPlugin({ assets: publicDir, prefix: "/public" }) : new Elysia3).get("/favicon.ico", publicExists ? file(join4(publicDir, "favicon.ico")) : () => new Response(null, { status: 404 })).use((app) => {
1924
2614
  for (const route of routes2) {
1925
2615
  app.use(createRoutePlugin(route, root2));
1926
2616
  }