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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +37 -33
  3. package/dist/adapter/bun.d.ts +17 -1
  4. package/dist/adapter/package.d.ts +26 -0
  5. package/dist/build/client.d.ts +1 -1
  6. package/dist/build/compile-entry.d.ts +3 -3
  7. package/dist/build/compile-entry.ts +114 -109
  8. package/dist/build/entry-template.d.ts +35 -9
  9. package/dist/build/entry-template.ts +206 -156
  10. package/dist/build/hydrate.d.ts +1 -1
  11. package/dist/build/index.js +643 -247
  12. package/dist/build/scan-server.d.ts +10 -4
  13. package/dist/build/server-routes-entry.d.ts +3 -3
  14. package/dist/build/server-routes-entry.ts +30 -36
  15. package/dist/build/ssg-cache.d.ts +1 -1
  16. package/dist/build/types.d.ts +36 -1
  17. package/dist/cli/config.d.ts +6 -1
  18. package/dist/cli/index.js +662 -260
  19. package/dist/client/link.js +163 -16
  20. package/dist/client/router/abort.d.ts +1 -0
  21. package/dist/client/router/sync-catch-up.d.ts +29 -0
  22. package/dist/config.d.ts +11 -2
  23. package/dist/config.js +5 -1
  24. package/dist/furin.d.ts +37 -19
  25. package/dist/furin.js +982 -378
  26. package/dist/server/auto-invalidate/registry.d.ts +8 -1
  27. package/dist/server/cache/dev-loader.d.ts +3 -2
  28. package/dist/server/cache/invalidation.d.ts +19 -0
  29. package/dist/server/cache/isr.d.ts +6 -2
  30. package/dist/server/cache/registry.d.ts +3 -3
  31. package/dist/server/cache/ssg.d.ts +6 -2
  32. package/dist/server/cache/store-view.d.ts +11 -0
  33. package/dist/server/instance.d.ts +86 -0
  34. package/dist/server/internal.d.ts +16 -1
  35. package/dist/server/internal.js +72 -5
  36. package/dist/server/render/template.d.ts +3 -2
  37. package/dist/server/sync/adapter.d.ts +62 -0
  38. package/dist/server/sync/config.d.ts +11 -0
  39. package/dist/server/sync/fingerprint.d.ts +6 -0
  40. package/dist/server/sync/index.d.ts +2 -2
  41. package/dist/server/sync/memory-adapter.d.ts +17 -0
  42. package/dist/server/sync/plugin.d.ts +12 -195
  43. package/dist/server/sync/response.d.ts +4 -0
  44. package/dist/server/sync/stream.d.ts +24 -5
  45. package/dist/shared/prefix.d.ts +15 -0
  46. package/package.json +6 -1
  47. package/src/adapter/README.md +13 -13
  48. package/src/adapter/bun.ts +113 -50
  49. package/src/adapter/package.ts +206 -0
  50. package/src/build/client.ts +158 -152
  51. package/src/build/compile-entry.ts +114 -109
  52. package/src/build/entry-template.ts +206 -156
  53. package/src/build/hydrate.ts +342 -340
  54. package/src/build/index.ts +223 -152
  55. package/src/build/route-types.ts +145 -145
  56. package/src/build/scan-server.ts +111 -95
  57. package/src/build/server-routes-entry.ts +30 -36
  58. package/src/build/shared.ts +80 -80
  59. package/src/build/ssg-cache.ts +36 -32
  60. package/src/build/types.ts +125 -89
  61. package/src/cli/config.ts +9 -3
  62. package/src/cli/index.ts +21 -3
  63. package/src/client/router/abort.ts +5 -0
  64. package/src/client/router/link-utils.ts +184 -184
  65. package/src/client/router/provider.tsx +883 -804
  66. package/src/client/router/sync-catch-up.ts +113 -0
  67. package/src/client/router/types.ts +276 -276
  68. package/src/client/sync.ts +98 -98
  69. package/src/client.ts +369 -369
  70. package/src/config.ts +14 -1
  71. package/src/furin.ts +619 -465
  72. package/src/server/auto-invalidate/registry.ts +23 -1
  73. package/src/server/auto-invalidate/runtime.ts +159 -134
  74. package/src/server/cache/dev-loader.ts +77 -38
  75. package/src/server/cache/invalidation.ts +71 -30
  76. package/src/server/cache/isr.ts +20 -5
  77. package/src/server/cache/registry.ts +17 -20
  78. package/src/server/cache/ssg.ts +19 -4
  79. package/src/server/cache/store-view.ts +30 -0
  80. package/src/server/dev-page-plugin.ts +454 -454
  81. package/src/server/instance.ts +252 -0
  82. package/src/server/internal.ts +100 -5
  83. package/src/server/render/assemble.ts +160 -160
  84. package/src/server/render/isr.ts +323 -323
  85. package/src/server/render/not-found.ts +9 -3
  86. package/src/server/render/ssr.ts +603 -585
  87. package/src/server/render/template.ts +57 -24
  88. package/src/server/router/plugin.ts +384 -384
  89. package/src/server/sync/adapter.ts +65 -0
  90. package/src/server/sync/config.ts +60 -29
  91. package/src/server/sync/fingerprint.ts +44 -0
  92. package/src/server/sync/index.ts +15 -14
  93. package/src/server/sync/memory-adapter.ts +196 -0
  94. package/src/server/sync/plugin.ts +199 -108
  95. package/src/server/sync/response.ts +77 -0
  96. package/src/server/sync/stream.ts +162 -144
  97. package/src/shared/deferred-ndjson.ts +7 -0
  98. package/src/shared/prefix.ts +38 -0
package/dist/furin.js CHANGED
@@ -2355,6 +2355,120 @@ var init_context_logger = __esm(() => {
2355
2355
  syntheticRenderStorage = new AsyncLocalStorage2;
2356
2356
  });
2357
2357
 
2358
+ // src/server/instance.ts
2359
+ import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
2360
+ function createInstance(prefix, pagesDir) {
2361
+ return {
2362
+ prefix,
2363
+ pagesDir,
2364
+ syncStreamPath: undefined,
2365
+ buildId: "",
2366
+ registrationEpoch: 0,
2367
+ state: new Map
2368
+ };
2369
+ }
2370
+ function markTraffic() {
2371
+ _trafficEpoch++;
2372
+ }
2373
+ function defaultInstance() {
2374
+ if (!_defaultInstance) {
2375
+ _defaultInstance = createInstance("", "");
2376
+ }
2377
+ return _defaultInstance;
2378
+ }
2379
+ function defaultInstanceBucket() {
2380
+ return defaultInstance();
2381
+ }
2382
+ function normalizePrefix(prefix) {
2383
+ if (prefix === undefined || prefix === "" || prefix === "/") {
2384
+ return "";
2385
+ }
2386
+ if (!prefix.startsWith("/")) {
2387
+ throw new Error(`[furin] prefix must start with "/" (got "${prefix}").`);
2388
+ }
2389
+ if (prefix.includes("//") || WHITESPACE_RE.test(prefix)) {
2390
+ throw new Error(`[furin] invalid prefix "${prefix}".`);
2391
+ }
2392
+ return prefix.endsWith("/") ? prefix.slice(0, -1) : prefix;
2393
+ }
2394
+ function assertPrefixAvailable(prefix, pagesDir) {
2395
+ const existing = _instances.get(prefix);
2396
+ if (existing && existing.pagesDir !== pagesDir && existing.registrationEpoch === _trafficEpoch) {
2397
+ throw new Error(`[furin] prefix "${prefix || "/"}" is already mounted by pagesDir "${existing.pagesDir}" ` + `(attempted to mount "${pagesDir}"). Give each furin() instance a unique prefix.`);
2398
+ }
2399
+ }
2400
+ function registerInstance(instance) {
2401
+ assertPrefixAvailable(instance.prefix, instance.pagesDir);
2402
+ instance.registrationEpoch = _trafficEpoch;
2403
+ _instances.set(instance.prefix, instance);
2404
+ return instance;
2405
+ }
2406
+ function resolveInstanceByPath(pathname) {
2407
+ let best = null;
2408
+ for (const [prefix, instance] of _instances) {
2409
+ if (prefix === "") {
2410
+ best ??= instance;
2411
+ continue;
2412
+ }
2413
+ if ((pathname === prefix || pathname.startsWith(prefix) && pathname.charCodeAt(prefix.length) === 47) && (!best || prefix.length > best.prefix.length || best.prefix === "")) {
2414
+ best = instance;
2415
+ }
2416
+ }
2417
+ if (best) {
2418
+ return best;
2419
+ }
2420
+ return defaultInstance();
2421
+ }
2422
+ function currentInstance() {
2423
+ const scope = _requestScope.getStore();
2424
+ if (scope) {
2425
+ return scope.instance;
2426
+ }
2427
+ if (_instances.size === 1) {
2428
+ const only = _instances.values().next().value;
2429
+ if (only) {
2430
+ return only;
2431
+ }
2432
+ }
2433
+ return defaultInstance();
2434
+ }
2435
+ function allInstances() {
2436
+ if (_instances.size === 0) {
2437
+ return [defaultInstance()];
2438
+ }
2439
+ return [..._instances.values()];
2440
+ }
2441
+ function hasRequestScope() {
2442
+ return _requestScope.getStore() !== undefined;
2443
+ }
2444
+ function requestPendingInvalidations() {
2445
+ return _requestScope.getStore()?.pending;
2446
+ }
2447
+ function runWithInstanceScope(instance, fn) {
2448
+ return _requestScope.run({ instance, pending: new Set }, fn);
2449
+ }
2450
+ function withInstance(instance, fn) {
2451
+ return runWithInstanceScope(instance, fn);
2452
+ }
2453
+ function instanceSlot(init) {
2454
+ const key = Symbol("furin-instance-slot");
2455
+ return (instance) => {
2456
+ const target = instance ?? currentInstance();
2457
+ if (target.state.has(key)) {
2458
+ return target.state.get(key);
2459
+ }
2460
+ const value = init(target);
2461
+ target.state.set(key, value);
2462
+ return value;
2463
+ };
2464
+ }
2465
+ var _requestScope, WHITESPACE_RE, _instances, _defaultInstance = null, _trafficEpoch = 0;
2466
+ var init_instance = __esm(() => {
2467
+ _requestScope = new AsyncLocalStorage3;
2468
+ WHITESPACE_RE = /\s/;
2469
+ _instances = new Map;
2470
+ });
2471
+
2358
2472
  // src/server/auto-invalidate/registry.ts
2359
2473
  class AutoInvalidateRegistry {
2360
2474
  pathToTags = new Map;
@@ -2407,37 +2521,42 @@ class AutoInvalidateRegistry {
2407
2521
  this.tagToPaths.clear();
2408
2522
  }
2409
2523
  }
2410
- var autoInvalidateRegistry;
2524
+ function getAutoInvalidateRegistry(instance) {
2525
+ return instanceAutoInvalidateRegistry(instance);
2526
+ }
2527
+ var instanceAutoInvalidateRegistry, autoInvalidateRegistry;
2411
2528
  var init_registry = __esm(() => {
2412
- autoInvalidateRegistry = new AutoInvalidateRegistry;
2529
+ init_instance();
2530
+ instanceAutoInvalidateRegistry = instanceSlot(() => new AutoInvalidateRegistry);
2531
+ autoInvalidateRegistry = {
2532
+ registerLoaderTags: (urlPath, tags) => instanceAutoInvalidateRegistry().registerLoaderTags(urlPath, tags),
2533
+ pathsForTags: (tags) => instanceAutoInvalidateRegistry().pathsForTags(tags),
2534
+ unregisterPath: (urlPath) => instanceAutoInvalidateRegistry().unregisterPath(urlPath),
2535
+ reset: () => instanceAutoInvalidateRegistry().reset()
2536
+ };
2413
2537
  });
2414
2538
 
2415
2539
  // src/server/cache/registry.ts
2416
- function registerCacheInvalidator(invalidator) {
2417
- const existing = _cacheInvalidators.get(invalidator.name);
2540
+ function registerCacheInvalidator(invalidator, instance) {
2541
+ const invalidators = instanceInvalidators(instance);
2542
+ const existing = invalidators.get(invalidator.name);
2418
2543
  if (existing !== undefined && existing !== invalidator) {
2419
- throw new Error(`Cache invalidator "${invalidator.name}" is already registered with a different instance.`);
2420
- }
2421
- if (existing === invalidator) {
2422
- return () => {
2423
- if (_cacheInvalidators.get(invalidator.name) === invalidator) {
2424
- _cacheInvalidators.delete(invalidator.name);
2425
- }
2426
- };
2544
+ throw new Error(`Cache invalidator "${invalidator.name}" is already registered for this furin instance with a different invalidator object.`);
2427
2545
  }
2428
- _cacheInvalidators.set(invalidator.name, invalidator);
2546
+ invalidators.set(invalidator.name, invalidator);
2429
2547
  return () => {
2430
- if (_cacheInvalidators.get(invalidator.name) === invalidator) {
2431
- _cacheInvalidators.delete(invalidator.name);
2548
+ if (invalidators.get(invalidator.name) === invalidator) {
2549
+ invalidators.delete(invalidator.name);
2432
2550
  }
2433
2551
  };
2434
2552
  }
2435
- function getCacheInvalidators() {
2436
- return _cacheInvalidators.values();
2553
+ function getCacheInvalidators(instance) {
2554
+ return instanceInvalidators(instance).values();
2437
2555
  }
2438
- var _cacheInvalidators;
2556
+ var instanceInvalidators;
2439
2557
  var init_registry2 = __esm(() => {
2440
- _cacheInvalidators = new Map;
2558
+ init_instance();
2559
+ instanceInvalidators = instanceSlot(() => new Map);
2441
2560
  });
2442
2561
 
2443
2562
  // src/server/cache/route-cache.ts
@@ -2532,33 +2651,33 @@ function createRouteCache(options) {
2532
2651
 
2533
2652
  // src/server/cache/dev-loader.ts
2534
2653
  import { statSync } from "fs";
2535
- function indexEntryDependencies(cacheKey, deps) {
2654
+ function indexEntryDependencies(index, cacheKey, deps) {
2536
2655
  for (const dep of deps) {
2537
- let bucket = sourceFileToCacheKeys.get(dep);
2656
+ let bucket = index.get(dep);
2538
2657
  if (!bucket) {
2539
2658
  bucket = new Set;
2540
- sourceFileToCacheKeys.set(dep, bucket);
2659
+ index.set(dep, bucket);
2541
2660
  }
2542
2661
  bucket.add(cacheKey);
2543
2662
  }
2544
2663
  }
2545
- function unindexEntryDependencies(cacheKey, deps) {
2664
+ function unindexEntryDependencies(index, cacheKey, deps) {
2546
2665
  for (const dep of deps) {
2547
- const bucket = sourceFileToCacheKeys.get(dep);
2666
+ const bucket = index.get(dep);
2548
2667
  if (!bucket) {
2549
2668
  continue;
2550
2669
  }
2551
2670
  bucket.delete(cacheKey);
2552
2671
  if (bucket.size === 0) {
2553
- sourceFileToCacheKeys.delete(dep);
2672
+ index.delete(dep);
2554
2673
  }
2555
2674
  }
2556
2675
  }
2557
- function createDevLoaderCache(name) {
2676
+ function createDevLoaderCache(name, index) {
2558
2677
  return createRouteCache({
2559
2678
  name,
2560
2679
  onDelete: (key, entry) => {
2561
- unindexEntryDependencies(key, entry.dependencies);
2680
+ unindexEntryDependencies(index, key, entry.dependencies);
2562
2681
  const urlPath = urlPathFromCacheKey(key);
2563
2682
  if (urlPath) {
2564
2683
  autoInvalidateRegistry.unregisterPath(urlPath);
@@ -2566,27 +2685,24 @@ function createDevLoaderCache(name) {
2566
2685
  },
2567
2686
  onSet: (key, entry, previous) => {
2568
2687
  if (previous) {
2569
- unindexEntryDependencies(key, previous.dependencies);
2688
+ unindexEntryDependencies(index, key, previous.dependencies);
2570
2689
  }
2571
- indexEntryDependencies(key, entry.dependencies);
2690
+ indexEntryDependencies(index, key, entry.dependencies);
2572
2691
  },
2573
2692
  pathFromKey: urlPathFromCacheKey
2574
2693
  });
2575
2694
  }
2576
- function setEntry(handle, key, entry) {
2577
- handle.cache.set(key, entry);
2578
- }
2579
2695
  function getDevISRLoaderCache(key) {
2580
- return devISRLoaderCache.get(key);
2696
+ return instanceDevLoaderState().isr.cache.get(key);
2581
2697
  }
2582
2698
  function setDevISRLoaderCache(key, entry) {
2583
- setEntry(isrHandle, key, entry);
2699
+ instanceDevLoaderState().isr.cache.set(key, entry);
2584
2700
  }
2585
2701
  function getDevSSGLoaderCache(key) {
2586
- return devSSGLoaderCache.get(key);
2702
+ return instanceDevLoaderState().ssg.cache.get(key);
2587
2703
  }
2588
2704
  function setDevSSGLoaderCache(key, entry) {
2589
- setEntry(ssgHandle, key, entry);
2705
+ instanceDevLoaderState().ssg.cache.set(key, entry);
2590
2706
  }
2591
2707
  function urlPathFromCacheKey(key) {
2592
2708
  const sep = key.lastIndexOf(":/");
@@ -2596,7 +2712,8 @@ function urlPathFromCacheKey(key) {
2596
2712
  return key.slice(sep + 1);
2597
2713
  }
2598
2714
  function invalidateDevLoaderCacheBySource(filePath) {
2599
- const keys = sourceFileToCacheKeys.get(filePath);
2715
+ const state = instanceDevLoaderState();
2716
+ const keys = state.sourceFileToCacheKeys.get(filePath);
2600
2717
  if (!keys || keys.size === 0) {
2601
2718
  return { cleared: [], isr: 0, ssg: 0 };
2602
2719
  }
@@ -2605,16 +2722,16 @@ function invalidateDevLoaderCacheBySource(filePath) {
2605
2722
  let ssg = 0;
2606
2723
  const snapshot = [...keys];
2607
2724
  for (const key of snapshot) {
2608
- const isrEntry = devISRLoaderCache.get(key);
2725
+ const isrEntry = state.isr.cache.get(key);
2609
2726
  if (isrEntry) {
2610
- devISRLoaderCache.delete(key);
2727
+ state.isr.cache.delete(key);
2611
2728
  cleared.push(key);
2612
2729
  isr++;
2613
2730
  continue;
2614
2731
  }
2615
- const ssgEntry = devSSGLoaderCache.get(key);
2732
+ const ssgEntry = state.ssg.cache.get(key);
2616
2733
  if (ssgEntry) {
2617
- devSSGLoaderCache.delete(key);
2734
+ state.ssg.cache.delete(key);
2618
2735
  cleared.push(key);
2619
2736
  ssg++;
2620
2737
  }
@@ -2642,19 +2759,28 @@ function isDevLoaderCacheValid(entry) {
2642
2759
  return true;
2643
2760
  }
2644
2761
  function getAllDevISRLoaderEntries() {
2645
- return [...devISRLoaderCache.entries()];
2762
+ return [...instanceDevLoaderState().isr.cache.entries()];
2646
2763
  }
2647
2764
  function getAllDevSSGLoaderEntries() {
2648
- return [...devSSGLoaderCache.entries()];
2765
+ return [...instanceDevLoaderState().ssg.cache.entries()];
2649
2766
  }
2650
- var sourceFileToCacheKeys, devISRLoaderCache, devSSGLoaderCache, isrHandle, ssgHandle;
2767
+ var instanceDevLoaderState;
2651
2768
  var init_dev_loader = __esm(() => {
2652
2769
  init_registry();
2653
- sourceFileToCacheKeys = new Map;
2654
- devISRLoaderCache = createDevLoaderCache("render:dev-isr-loader");
2655
- devSSGLoaderCache = createDevLoaderCache("render:dev-ssg-loader");
2656
- isrHandle = { cache: devISRLoaderCache, kind: "isr" };
2657
- ssgHandle = { cache: devSSGLoaderCache, kind: "ssg" };
2770
+ init_instance();
2771
+ init_registry2();
2772
+ instanceDevLoaderState = instanceSlot((instance) => {
2773
+ const sourceFileToCacheKeys = new Map;
2774
+ const isrCache = createDevLoaderCache("render:dev-isr-loader", sourceFileToCacheKeys);
2775
+ const ssgCache = createDevLoaderCache("render:dev-ssg-loader", sourceFileToCacheKeys);
2776
+ registerCacheInvalidator(isrCache, instance);
2777
+ registerCacheInvalidator(ssgCache, instance);
2778
+ return {
2779
+ isr: { cache: isrCache, kind: "isr" },
2780
+ sourceFileToCacheKeys,
2781
+ ssg: { cache: ssgCache, kind: "ssg" }
2782
+ };
2783
+ });
2658
2784
  });
2659
2785
 
2660
2786
  // src/server/cache/isr-ssg.ts
@@ -2672,44 +2798,131 @@ var init_isr_ssg = __esm(() => {
2672
2798
  init_registry();
2673
2799
  });
2674
2800
 
2801
+ // src/server/cache/store-view.ts
2802
+ function createStoreView(resolve) {
2803
+ return {
2804
+ clear: () => resolve().clear(),
2805
+ delete: (key) => resolve().delete(key),
2806
+ entries: () => resolve().entries(),
2807
+ get: (key) => resolve().get(key),
2808
+ has: (key) => resolve().has(key),
2809
+ keys: () => resolve().keys(),
2810
+ set: (key, entry) => {
2811
+ resolve().set(key, entry);
2812
+ },
2813
+ get size() {
2814
+ return resolve().size;
2815
+ }
2816
+ };
2817
+ }
2818
+
2675
2819
  // src/server/cache/isr.ts
2676
2820
  function getISRCache(key) {
2677
- return isrRouteCache.get(key);
2821
+ return instanceIsrCache().get(key);
2678
2822
  }
2679
2823
  function deleteISRCache(key) {
2680
- return isrRouteCache.delete(key);
2824
+ return instanceIsrCache().delete(key);
2681
2825
  }
2682
2826
  function setISRCache(key, entry) {
2683
- isrRouteCache.set(key, entry);
2827
+ instanceIsrCache().set(key, entry);
2684
2828
  }
2685
- var isrRouteCache, isrCache;
2829
+ var instanceIsrCache, isrCache;
2686
2830
  var init_isr = __esm(() => {
2831
+ init_instance();
2687
2832
  init_isr_ssg();
2688
- isrRouteCache = createHtmlRouteCache("isr");
2689
- isrCache = isrRouteCache.store;
2833
+ init_registry2();
2834
+ instanceIsrCache = instanceSlot((instance) => {
2835
+ const cache = createHtmlRouteCache("isr");
2836
+ registerCacheInvalidator(cache, instance);
2837
+ return cache;
2838
+ });
2839
+ isrCache = createStoreView(() => instanceIsrCache().store);
2690
2840
  });
2691
2841
 
2692
2842
  // src/server/cache/ssg.ts
2693
2843
  function getSSGCache(key) {
2694
- return ssgRouteCache.get(key);
2844
+ return instanceSsgCache().get(key);
2695
2845
  }
2696
2846
  function setSSGCache(key, entry) {
2697
- ssgRouteCache.set(key, entry);
2847
+ instanceSsgCache().set(key, entry);
2698
2848
  autoInvalidateRegistry.registerLoaderTags(key, entry.tags);
2699
2849
  }
2700
- var ssgRouteCache, ssgCache;
2850
+ var instanceSsgCache, ssgCache;
2701
2851
  var init_ssg = __esm(() => {
2702
2852
  init_registry();
2853
+ init_instance();
2703
2854
  init_isr_ssg();
2704
- ssgRouteCache = createHtmlRouteCache("ssg");
2705
- ssgCache = ssgRouteCache.store;
2855
+ init_registry2();
2856
+ instanceSsgCache = instanceSlot((instance) => {
2857
+ const cache = createHtmlRouteCache("ssg");
2858
+ registerCacheInvalidator(cache, instance);
2859
+ return cache;
2860
+ });
2861
+ ssgCache = createStoreView(() => instanceSsgCache().store);
2706
2862
  });
2707
2863
 
2708
2864
  // src/server/internal.ts
2709
- function getCompileContext() {
2710
- return _compileCtx;
2865
+ function normalizeContextKey(path) {
2866
+ return path.replaceAll("\\", "/");
2711
2867
  }
2712
- var _compileCtx = null;
2868
+ function pagesDirOf(ctx) {
2869
+ const rootPath = normalizeContextKey(ctx.rootPath);
2870
+ const lastSlash = rootPath.lastIndexOf("/");
2871
+ return lastSlash === -1 ? rootPath : rootPath.slice(0, lastSlash);
2872
+ }
2873
+ function contextKey(pagesDir, prefix) {
2874
+ return `${pagesDir}\x00${prefix}`;
2875
+ }
2876
+ function getCompileContext(pagesDir, prefix) {
2877
+ if (pagesDir !== undefined) {
2878
+ const dir = normalizeContextKey(pagesDir);
2879
+ if (prefix !== undefined) {
2880
+ const exact = _compileContexts.get(contextKey(dir, prefix));
2881
+ if (exact) {
2882
+ return exact;
2883
+ }
2884
+ }
2885
+ const dirMatch = soleContextForPagesDir(dir);
2886
+ if (dirMatch) {
2887
+ return dirMatch;
2888
+ }
2889
+ }
2890
+ if (prefix !== undefined) {
2891
+ const prefixMatch = contextForPrefix(prefix);
2892
+ if (prefixMatch) {
2893
+ return prefixMatch;
2894
+ }
2895
+ }
2896
+ if (_compileContexts.size === 1) {
2897
+ return _compileContexts.values().next().value ?? null;
2898
+ }
2899
+ return null;
2900
+ }
2901
+ function soleContextForPagesDir(dir) {
2902
+ let match = null;
2903
+ for (const ctx of _compileContexts.values()) {
2904
+ if (pagesDirOf(ctx) !== dir) {
2905
+ continue;
2906
+ }
2907
+ if (match) {
2908
+ return null;
2909
+ }
2910
+ match = ctx;
2911
+ }
2912
+ return match;
2913
+ }
2914
+ function contextForPrefix(prefix) {
2915
+ for (const ctx of _compileContexts.values()) {
2916
+ if ((ctx.prefix ?? "") === prefix) {
2917
+ return ctx;
2918
+ }
2919
+ }
2920
+ return null;
2921
+ }
2922
+ var _compileContexts;
2923
+ var init_internal = __esm(() => {
2924
+ _compileContexts = new Map;
2925
+ });
2713
2926
 
2714
2927
  // src/shared/digest.ts
2715
2928
  function computeErrorDigest(err) {
@@ -2912,6 +3125,24 @@ function findSearchDefaultsForRouteTarget(to, routes) {
2912
3125
  }
2913
3126
  }
2914
3127
 
3128
+ // src/client/server-error.ts
3129
+ function isFurinServerError(err) {
3130
+ return err instanceof FurinServerError || typeof err === "object" && err !== null && err.__furinBrand === SERVER_ERROR_BRAND;
3131
+ }
3132
+ var SERVER_ERROR_BRAND = "FURIN_SERVER_ERROR", FurinServerError;
3133
+ var init_server_error = __esm(() => {
3134
+ FurinServerError = class FurinServerError extends Error {
3135
+ __furinBrand = SERVER_ERROR_BRAND;
3136
+ digest;
3137
+ status;
3138
+ constructor(args) {
3139
+ super(args.message);
3140
+ this.status = args.status;
3141
+ this.digest = args.digest;
3142
+ }
3143
+ };
3144
+ });
3145
+
2915
3146
  // src/client/router/context.ts
2916
3147
  import { createContext, useContext } from "react";
2917
3148
  function useRouter() {
@@ -2966,75 +3197,13 @@ function normalizeHref(href) {
2966
3197
  }
2967
3198
  return pathname + url.search + url.hash;
2968
3199
  }
2969
- var init_link_utils = () => {};
2970
-
2971
- // src/client/router/search-store.ts
2972
- import { createContext as createContext2 } from "react";
2973
- function searchSnapshotChanged(a, b) {
2974
- return a.currentHref !== b.currentHref || a.navigate !== b.navigate || a.search !== b.search || a.searchRoutes !== b.searchRoutes;
2975
- }
2976
- function createSearchStore(initialSnapshot) {
2977
- let snapshot = initialSnapshot;
2978
- let version = 0;
2979
- let flushedVersion = 0;
2980
- const listeners = new Set;
2981
- return {
2982
- flush: () => {
2983
- if (flushedVersion === version) {
2984
- return;
2985
- }
2986
- flushedVersion = version;
2987
- for (const listener of [...listeners]) {
2988
- listener();
2989
- }
2990
- },
2991
- getServerSnapshot: () => snapshot,
2992
- getSnapshot: () => snapshot,
2993
- setSnapshot: (next) => {
2994
- if (!searchSnapshotChanged(snapshot, next)) {
2995
- return;
2996
- }
2997
- snapshot = next;
2998
- version++;
2999
- },
3000
- subscribe: (listener) => {
3001
- listeners.add(listener);
3002
- return () => {
3003
- listeners.delete(listener);
3004
- };
3005
- }
3006
- };
3007
- }
3008
- function searchSnapshotFromRouterContext(context) {
3009
- return {
3010
- currentHref: context.currentHref,
3011
- navigate: context.navigate,
3012
- search: context.search,
3013
- searchRoutes: context.searchRoutes
3014
- };
3200
+ function toLogical(physicalPathname, basePath) {
3201
+ if (basePath && physicalPathname.startsWith(basePath) && (physicalPathname.length === basePath.length || physicalPathname[basePath.length] === "/")) {
3202
+ return physicalPathname.slice(basePath.length) || "/";
3203
+ }
3204
+ return physicalPathname;
3015
3205
  }
3016
- var FALLBACK_SEARCH_STORE, SearchStoreContext;
3017
- var init_search_store = __esm(() => {
3018
- FALLBACK_SEARCH_STORE = createSearchStore({
3019
- currentHref: "/",
3020
- navigate: (href, _opts) => {
3021
- if (typeof window !== "undefined") {
3022
- window.location.href = href;
3023
- }
3024
- return Promise.resolve();
3025
- },
3026
- search: {},
3027
- searchRoutes: []
3028
- });
3029
- SearchStoreContext = createContext2(null);
3030
- });
3031
-
3032
- // src/client/router/index.ts
3033
- var init_router = __esm(() => {
3034
- init_context();
3035
- init_link_utils();
3036
- init_search_store();
3037
- });
3206
+ var init_link_utils = () => {};
3038
3207
 
3039
3208
  // ../../node_modules/.bun/seroval@1.5.4/node_modules/seroval/dist/esm/development/index.mjs
3040
3209
  function createSerovalNode(t, i, s, c, m, p, e, a, f, b, o, l) {
@@ -4490,6 +4659,74 @@ There are few workarounds for this problem:
4490
4659
  REF_CHARS_LEN = REF_CHARS.length;
4491
4660
  });
4492
4661
 
4662
+ // src/client/router/search-store.ts
4663
+ import { createContext as createContext2 } from "react";
4664
+ function searchSnapshotChanged(a, b) {
4665
+ return a.currentHref !== b.currentHref || a.navigate !== b.navigate || a.search !== b.search || a.searchRoutes !== b.searchRoutes;
4666
+ }
4667
+ function createSearchStore(initialSnapshot) {
4668
+ let snapshot = initialSnapshot;
4669
+ let version = 0;
4670
+ let flushedVersion = 0;
4671
+ const listeners = new Set;
4672
+ return {
4673
+ flush: () => {
4674
+ if (flushedVersion === version) {
4675
+ return;
4676
+ }
4677
+ flushedVersion = version;
4678
+ for (const listener of [...listeners]) {
4679
+ listener();
4680
+ }
4681
+ },
4682
+ getServerSnapshot: () => snapshot,
4683
+ getSnapshot: () => snapshot,
4684
+ setSnapshot: (next) => {
4685
+ if (!searchSnapshotChanged(snapshot, next)) {
4686
+ return;
4687
+ }
4688
+ snapshot = next;
4689
+ version++;
4690
+ },
4691
+ subscribe: (listener) => {
4692
+ listeners.add(listener);
4693
+ return () => {
4694
+ listeners.delete(listener);
4695
+ };
4696
+ }
4697
+ };
4698
+ }
4699
+ function searchSnapshotFromRouterContext(context) {
4700
+ return {
4701
+ currentHref: context.currentHref,
4702
+ navigate: context.navigate,
4703
+ search: context.search,
4704
+ searchRoutes: context.searchRoutes
4705
+ };
4706
+ }
4707
+ var FALLBACK_SEARCH_STORE, SearchStoreContext;
4708
+ var init_search_store = __esm(() => {
4709
+ FALLBACK_SEARCH_STORE = createSearchStore({
4710
+ currentHref: "/",
4711
+ navigate: (href, _opts) => {
4712
+ if (typeof window !== "undefined") {
4713
+ window.location.href = href;
4714
+ }
4715
+ return Promise.resolve();
4716
+ },
4717
+ search: {},
4718
+ searchRoutes: []
4719
+ });
4720
+ SearchStoreContext = createContext2(null);
4721
+ });
4722
+
4723
+ // src/client/router/index.ts
4724
+ var init_router = __esm(() => {
4725
+ init_context();
4726
+ init_link_utils();
4727
+ init_search_store();
4728
+ });
4729
+
4493
4730
  // src/client/link.tsx
4494
4731
  import { createElement, useCallback, useEffect, useRef } from "react";
4495
4732
  function computeLinkView({
@@ -4961,24 +5198,6 @@ html, body {
4961
5198
  `;
4962
5199
  });
4963
5200
 
4964
- // src/client/server-error.ts
4965
- function isFurinServerError(err) {
4966
- return err instanceof FurinServerError || typeof err === "object" && err !== null && err.__furinBrand === SERVER_ERROR_BRAND;
4967
- }
4968
- var SERVER_ERROR_BRAND = "FURIN_SERVER_ERROR", FurinServerError;
4969
- var init_server_error = __esm(() => {
4970
- FurinServerError = class FurinServerError extends Error {
4971
- __furinBrand = SERVER_ERROR_BRAND;
4972
- digest;
4973
- status;
4974
- constructor(args) {
4975
- super(args.message);
4976
- this.status = args.status;
4977
- this.digest = args.digest;
4978
- }
4979
- };
4980
- });
4981
-
4982
5201
  // src/client/boundaries.tsx
4983
5202
  import { Component, Fragment } from "react";
4984
5203
  import { jsxDEV as jsxDEV2 } from "react/jsx-dev-runtime";
@@ -5160,13 +5379,26 @@ function resolveSyncStreamPath(sync) {
5160
5379
  return sync.streamPath ?? SYNC_STREAM_DEFAULT_PATH;
5161
5380
  }
5162
5381
  function getSyncStreamPath() {
5163
- return requestSyncStreamPath.getStore();
5382
+ const override = requestSyncStreamPath.getStore();
5383
+ if (override !== undefined) {
5384
+ return override;
5385
+ }
5386
+ return currentInstance().syncStreamPath;
5164
5387
  }
5165
- function runWithSyncStreamPath(path, fn) {
5166
- return requestSyncStreamPath.run(path, fn);
5388
+ function syncPublishChannels() {
5389
+ const override = requestSyncStreamPath.getStore();
5390
+ if (override !== undefined) {
5391
+ return [override];
5392
+ }
5393
+ const channels = allInstances().filter((instance) => instance.syncStreamPath !== undefined).map((instance) => `${instance.prefix}${instance.syncStreamPath}`);
5394
+ if (channels.length > 0) {
5395
+ return channels;
5396
+ }
5397
+ return [SYNC_STREAM_DEFAULT_PATH];
5167
5398
  }
5168
5399
  var SYNC_STREAM_DEFAULT_PATH = "/_furin/sync", requestSyncStreamPath;
5169
5400
  var init_config = __esm(() => {
5401
+ init_instance();
5170
5402
  requestSyncStreamPath = new AsyncLocalStorage4;
5171
5403
  });
5172
5404
 
@@ -5596,41 +5828,57 @@ var init_loaders = __esm(() => {
5596
5828
  // src/server/render/template.ts
5597
5829
  import { readFileSync } from "fs";
5598
5830
  async function getDevTemplate(origin) {
5599
- if (_devTemplateCache && Date.now() - _devTemplateCache.ts < DEV_TEMPLATE_TTL_MS) {
5600
- return _devTemplateCache.html;
5831
+ const instance = currentInstance();
5832
+ const state = instanceTemplateState(instance);
5833
+ if (state.devCache && Date.now() - state.devCache.ts < DEV_TEMPLATE_TTL_MS) {
5834
+ return state.devCache.html;
5601
5835
  }
5602
- const r = await fetch(`${origin}/_bun_hmr_entry`);
5836
+ const entryPath = `${instance.prefix}/_bun_hmr_entry`;
5837
+ const r = await fetch(`${origin}${entryPath}`);
5603
5838
  if (!r.ok) {
5604
- throw new Error(`/_bun_hmr_entry returned ${r.status}`);
5839
+ throw new Error(`${entryPath} returned ${r.status}`);
5605
5840
  }
5606
5841
  const html = await r.text();
5607
- _devTemplateCache = { html, ts: Date.now() };
5842
+ state.devCache = { html, ts: Date.now() };
5608
5843
  return html;
5609
5844
  }
5610
- function setProductionTemplatePath(path) {
5611
- _prodTemplatePath = path;
5612
- _prodTemplateContent = null;
5845
+ function setProductionTemplatePath(path, instance) {
5846
+ const state = instanceTemplateState(instance);
5847
+ state.prodPath = path;
5848
+ state.prodContent = null;
5613
5849
  }
5614
- function setProductionTemplateContent(content) {
5615
- _prodTemplatePath = null;
5616
- _prodTemplateContent = content;
5850
+ function setProductionTemplateContent(content, instance) {
5851
+ const state = instanceTemplateState(instance);
5852
+ state.prodPath = null;
5853
+ state.prodContent = content;
5617
5854
  }
5618
5855
  function getProductionTemplate() {
5619
- if (_prodTemplateContent !== null) {
5620
- return _prodTemplateContent;
5856
+ const own = readTemplate(instanceTemplateState());
5857
+ if (own !== null) {
5858
+ return own;
5621
5859
  }
5622
- if (!_prodTemplatePath) {
5860
+ const fallback = instanceTemplateState(defaultInstanceBucket());
5861
+ return readTemplate(fallback);
5862
+ }
5863
+ function readTemplate(state) {
5864
+ if (state.prodContent !== null) {
5865
+ return state.prodContent;
5866
+ }
5867
+ if (!state.prodPath) {
5623
5868
  return null;
5624
5869
  }
5625
5870
  try {
5626
- _prodTemplateContent = readFileSync(_prodTemplatePath, "utf8");
5627
- return _prodTemplateContent;
5871
+ state.prodContent = readFileSync(state.prodPath, "utf8");
5872
+ return state.prodContent;
5628
5873
  } catch {
5629
5874
  return null;
5630
5875
  }
5631
5876
  }
5632
- var _prodTemplatePath = null, _prodTemplateContent = null, _devTemplateCache = null, DEV_TEMPLATE_TTL_MS = 1000;
5633
- var init_template = () => {};
5877
+ var instanceTemplateState, DEV_TEMPLATE_TTL_MS = 1000;
5878
+ var init_template = __esm(() => {
5879
+ init_instance();
5880
+ instanceTemplateState = instanceSlot(() => ({ devCache: null, prodContent: null, prodPath: null }));
5881
+ });
5634
5882
 
5635
5883
  // src/server/render/ssr.ts
5636
5884
  import { createElement as createElement3 } from "react";
@@ -5657,10 +5905,10 @@ function assertDeferredModeAllowed(route, deferredPromises) {
5657
5905
  throw new Error(`[furin] page "${route.pattern}" returned defer() but the route is rendered in "${route.mode}" mode. ` + "defer() streams data progressively and is only supported in SSR. " + "Return the data directly (await it inside the loader) or switch the route to SSR mode.");
5658
5906
  }
5659
5907
  }
5660
- function currentHrefFromContext(ctx) {
5908
+ function currentHrefFromContext(ctx, basePath) {
5661
5909
  const pathUrl = new URL(ctx.path, "http://furin.local");
5662
5910
  const requestUrl = new URL(ctx.request.url);
5663
- return normalizeHref(pathUrl.pathname) + (pathUrl.search || requestUrl.search);
5911
+ return normalizeHref(toLogical(pathUrl.pathname, basePath)) + (pathUrl.search || requestUrl.search);
5664
5912
  }
5665
5913
  function buildSuccessRender(route, root, componentProps, throwOnFailure) {
5666
5914
  try {
@@ -5722,9 +5970,10 @@ async function prepareRender(route, ctx, root, basePath, throwOnFailure, precomp
5722
5970
  errorDigest = success.errorDigest;
5723
5971
  status = success.status;
5724
5972
  }
5973
+ const resolvedBasePath = basePath ?? currentInstance().prefix;
5725
5974
  const ssrContext = {
5726
- basePath: basePath ?? "",
5727
- currentHref: currentHrefFromContext(ctx),
5975
+ basePath: resolvedBasePath,
5976
+ currentHref: currentHrefFromContext(ctx, resolvedBasePath),
5728
5977
  search: ctx.query ?? {},
5729
5978
  searchRoutes: searchRoutes ?? [],
5730
5979
  navigate: (_href, _opts) => Promise.resolve(),
@@ -5804,6 +6053,7 @@ async function renderSSR(route, ctx, root, precomputedLoaderResult, searchRoutes
5804
6053
  if (prepared instanceof Response) {
5805
6054
  return prepared;
5806
6055
  }
6056
+ autoInvalidateRegistry.registerLoaderTags(resolvePath(route.pattern, ctx.params ?? {}), route.tags);
5807
6057
  useLogger3().set({
5808
6058
  furin: {
5809
6059
  render: route.mode,
@@ -5894,7 +6144,9 @@ var init_ssr = __esm(() => {
5894
6144
  init_development();
5895
6145
  init_router();
5896
6146
  init_search_store();
6147
+ init_registry();
5897
6148
  init_context_logger();
6149
+ init_instance();
5898
6150
  init_assemble();
5899
6151
  init_element();
5900
6152
  init_loaders();
@@ -6134,9 +6386,10 @@ async function renderRootNotFound(root, request) {
6134
6386
  template = generateIndexHtml();
6135
6387
  }
6136
6388
  const notFoundError = new FurinNotFoundError(undefined);
6389
+ const basePath = currentInstance().prefix;
6137
6390
  const notFoundContext = {
6138
- basePath: "",
6139
- currentHref: request ? normalizeHref(new URL(request.url).pathname) : "/",
6391
+ basePath,
6392
+ currentHref: request ? normalizeHref(toLogical(new URL(request.url).pathname, basePath)) : "/",
6140
6393
  search: {},
6141
6394
  searchRoutes: [],
6142
6395
  navigate: (_href, _opts) => Promise.resolve(),
@@ -6180,6 +6433,7 @@ var init_not_found2 = __esm(() => {
6180
6433
  init_router();
6181
6434
  init_not_found();
6182
6435
  init_context_logger();
6436
+ init_instance();
6183
6437
  init_assemble();
6184
6438
  init_element();
6185
6439
  init_shell();
@@ -6776,6 +7030,7 @@ async function collectPageFilePaths(dir) {
6776
7030
  }
6777
7031
  var CONVENTION_FILE_NAMES, SOURCE_MODULE_EXTENSIONS, DIR_SCAN_CONCURRENCY = 8;
6778
7032
  var init_discovery = __esm(() => {
7033
+ init_internal();
6779
7034
  init_patterns();
6780
7035
  CONVENTION_FILE_NAMES = ["not-found", "error"];
6781
7036
  SOURCE_MODULE_EXTENSIONS = [".tsx", ".ts", ".jsx", ".js"];
@@ -6948,6 +7203,7 @@ function computeRouteDependencies(pagePath, rootPath) {
6948
7203
  var init_hmr = __esm(() => {
6949
7204
  init_registry();
6950
7205
  init_dev_loader();
7206
+ init_internal();
6951
7207
  init_assemble();
6952
7208
  init_render();
6953
7209
  init_discovery();
@@ -7969,7 +8225,7 @@ const rootEl = document.getElementById("root") as HTMLElement;
7969
8225
  });
7970
8226
  `;
7971
8227
  }
7972
- function writeDevFiles(routes, { outDir, rootLayout, basePath, clientLogging }, projectRoot) {
8228
+ function writeDevFiles(routes, { outDir, rootLayout, basePath, clientLogging, skipRouteTypes }, projectRoot) {
7973
8229
  if (!existsSync4(outDir)) {
7974
8230
  mkdirSync(outDir, { recursive: true });
7975
8231
  }
@@ -7985,7 +8241,9 @@ function writeDevFiles(routes, { outDir, rootLayout, basePath, clientLogging },
7985
8241
  if (indexHtml !== existingIndex) {
7986
8242
  writeFileSync2(indexPath, indexHtml);
7987
8243
  }
7988
- writeRouteTypes(routes, projectRoot);
8244
+ if (!skipRouteTypes) {
8245
+ writeRouteTypes(routes, projectRoot);
8246
+ }
7989
8247
  console.log("[furin] Dev files written (.furin/_hydrate.tsx + .furin/index.html + furin-env.d.ts)");
7990
8248
  }
7991
8249
  var init_hydrate = __esm(() => {
@@ -8006,29 +8264,11 @@ import { Elysia as Elysia7, file } from "elysia";
8006
8264
 
8007
8265
  // src/server/cache/invalidation.ts
8008
8266
  init_context_logger();
8009
- init_dev_loader();
8010
- init_isr();
8267
+ init_instance();
8011
8268
  init_registry2();
8012
- init_ssg();
8013
- import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
8014
- registerCacheInvalidator(isrRouteCache);
8015
- registerCacheInvalidator(ssgRouteCache);
8016
- registerCacheInvalidator(devISRLoaderCache);
8017
- registerCacheInvalidator(devSSGLoaderCache);
8018
- var _buildId = "";
8019
- function setBuildId(id) {
8020
- _buildId = id;
8021
- }
8022
- function getBuildId() {
8023
- return _buildId;
8024
- }
8025
- var _requestInvalidationScope = new AsyncLocalStorage3;
8026
8269
  var _globalPendingInvalidations = new Set;
8027
8270
  function _activeInvalidationSet() {
8028
- return _requestInvalidationScope.getStore() ?? _globalPendingInvalidations;
8029
- }
8030
- function _runWithRequestInvalidationScope(fn) {
8031
- return _requestInvalidationScope.run(new Set, fn);
8271
+ return requestPendingInvalidations() ?? _globalPendingInvalidations;
8032
8272
  }
8033
8273
  function consumePendingInvalidations() {
8034
8274
  const set = _activeInvalidationSet();
@@ -8060,23 +8300,37 @@ function callCachePurger(paths) {
8060
8300
  });
8061
8301
  }
8062
8302
  function revalidatePath(path, type) {
8063
- _activeInvalidationSet().add(type === "layout" ? `${path}:layout` : path);
8064
8303
  let deleted = false;
8065
8304
  const purgedPaths = [];
8066
- for (const invalidator of getCacheInvalidators()) {
8067
- const result = invalidator.invalidatePath(path, type);
8305
+ for (const instance of allInstances()) {
8306
+ const result = revalidatePathForInstance(instance, path, type);
8068
8307
  deleted = result.deleted || deleted;
8069
8308
  purgedPaths.push(...result.purgedPaths);
8070
8309
  }
8071
8310
  callCachePurger(dedupePaths([...purgedPaths, path]));
8072
8311
  return deleted;
8073
8312
  }
8313
+ function revalidatePathForInstance(instance, path, type) {
8314
+ _activeInvalidationSet().add(type === "layout" ? `${path}:layout` : path);
8315
+ let deleted = false;
8316
+ const purgedPaths = [];
8317
+ withInstance(instance, () => {
8318
+ for (const invalidator of getCacheInvalidators(instance)) {
8319
+ const result = invalidator.invalidatePath(path, type);
8320
+ deleted = result.deleted || deleted;
8321
+ purgedPaths.push(...result.purgedPaths);
8322
+ }
8323
+ });
8324
+ return { deleted, purgedPaths };
8325
+ }
8074
8326
  function dedupePaths(paths) {
8075
8327
  return [...new Set(paths)];
8076
8328
  }
8077
8329
 
8078
8330
  // src/furin.ts
8079
8331
  init_ssg();
8332
+ init_instance();
8333
+ init_internal();
8080
8334
  init_render();
8081
8335
  init_template();
8082
8336
  init_router2();
@@ -8088,6 +8342,7 @@ init_config();
8088
8342
  import { Elysia as Elysia4 } from "elysia";
8089
8343
 
8090
8344
  // src/server/auto-invalidate/runtime.ts
8345
+ init_instance();
8091
8346
  init_registry();
8092
8347
  function toRules(input) {
8093
8348
  return Array.isArray(input) ? input : [input];
@@ -8180,9 +8435,18 @@ function appendPendingInvalidationHeader(set) {
8180
8435
  function revalidateTag(tags) {
8181
8436
  const tagList = typeof tags === "string" ? [tags] : [...tags];
8182
8437
  let deleted = false;
8183
- for (const path of autoInvalidateRegistry.pathsForTags(tagList)) {
8184
- deleted = revalidatePath(path, "page") || deleted;
8438
+ const purgedPaths = new Set;
8439
+ for (const instance of allInstances()) {
8440
+ for (const path of getAutoInvalidateRegistry(instance).pathsForTags(tagList)) {
8441
+ const result = revalidatePathForInstance(instance, path, "page");
8442
+ deleted = result.deleted || deleted;
8443
+ purgedPaths.add(`${instance.prefix}${path}`);
8444
+ for (const purged of result.purgedPaths) {
8445
+ purgedPaths.add(`${instance.prefix}${purged}`);
8446
+ }
8447
+ }
8185
8448
  }
8449
+ callCachePurger([...purgedPaths]);
8186
8450
  return deleted;
8187
8451
  }
8188
8452
  function runInvalidationRules(input) {
@@ -8198,12 +8462,263 @@ function runInvalidationRules(input) {
8198
8462
  return deleted;
8199
8463
  }
8200
8464
 
8465
+ // src/server/sync/fingerprint.ts
8466
+ function compareCodePoints(left, right) {
8467
+ if (left === right) {
8468
+ return 0;
8469
+ }
8470
+ return left < right ? -1 : 1;
8471
+ }
8472
+ function canonicalize(value) {
8473
+ if (Array.isArray(value)) {
8474
+ return value.map(canonicalize);
8475
+ }
8476
+ if (value && typeof value === "object" && Object.getPrototypeOf(value) === Object.prototype) {
8477
+ return Object.fromEntries(Object.entries(value).sort(([left], [right]) => compareCodePoints(left, right)).map(([key, entry]) => [key, canonicalize(entry)]));
8478
+ }
8479
+ return value;
8480
+ }
8481
+ async function createMutationFingerprint(input) {
8482
+ const url = new URL(input.request.url);
8483
+ const query = [...url.searchParams.entries()].sort(([leftKey, leftValue], [rightKey, rightValue]) => leftKey === rightKey ? compareCodePoints(leftValue, rightValue) : compareCodePoints(leftKey, rightKey));
8484
+ const source = JSON.stringify({
8485
+ body: canonicalize(input.body) ?? null,
8486
+ contentType: input.request.headers.get("content-type") ?? "",
8487
+ method: input.request.method,
8488
+ pathname: url.pathname,
8489
+ query
8490
+ });
8491
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(source));
8492
+ return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
8493
+ }
8494
+
8495
+ // src/server/sync/memory-adapter.ts
8496
+ var MAX_CHANGES = 1000;
8497
+ var MAX_MUTATIONS = 1e4;
8498
+ var MUTATION_TTL_MS = 24 * 60 * 60 * 1000;
8499
+
8500
+ class MemorySyncAdapter {
8501
+ changes = new Map;
8502
+ mutationKeys = new Map;
8503
+ mutations = new Map;
8504
+ beginMutation(input) {
8505
+ this.evictMutations();
8506
+ const mutationKey = `${input.principal}:${input.key}`;
8507
+ const existingId = this.mutationKeys.get(mutationKey);
8508
+ const existing = existingId ? this.mutations.get(existingId) : undefined;
8509
+ if (existing) {
8510
+ if (existing.fingerprint !== input.fingerprint) {
8511
+ return { kind: "conflict", reason: "payload-mismatch" };
8512
+ }
8513
+ if (existing.state === "in-progress") {
8514
+ return { kind: "conflict", reason: "in-progress" };
8515
+ }
8516
+ return { kind: "replay", response: existing.response };
8517
+ }
8518
+ if (this.mutations.size >= MAX_MUTATIONS) {
8519
+ return { kind: "unavailable" };
8520
+ }
8521
+ const mutationId = crypto.randomUUID();
8522
+ this.mutationKeys.set(mutationKey, mutationId);
8523
+ this.mutations.set(mutationId, {
8524
+ createdAt: Date.now(),
8525
+ fingerprint: input.fingerprint,
8526
+ mutationId,
8527
+ state: "in-progress"
8528
+ });
8529
+ return { kind: "execute", mutationId };
8530
+ }
8531
+ commitMutation(input) {
8532
+ const existing = this.mutations.get(input.mutationId);
8533
+ if (!existing) {
8534
+ return;
8535
+ }
8536
+ this.mutations.set(input.mutationId, {
8537
+ ...existing,
8538
+ response: input.response,
8539
+ state: "succeeded"
8540
+ });
8541
+ }
8542
+ abortMutation(input) {
8543
+ const existing = this.mutations.get(input.mutationId);
8544
+ if (!existing) {
8545
+ return;
8546
+ }
8547
+ this.mutations.delete(input.mutationId);
8548
+ for (const [key, mutationId] of this.mutationKeys) {
8549
+ if (mutationId === input.mutationId) {
8550
+ this.mutationKeys.delete(key);
8551
+ break;
8552
+ }
8553
+ }
8554
+ }
8555
+ appendChanges(input) {
8556
+ const state = this.getChangeState(input.path);
8557
+ const change = {
8558
+ cursor: String(state.nextCursor),
8559
+ invalidations: [...input.invalidations]
8560
+ };
8561
+ state.nextCursor += 1;
8562
+ state.changes.push(change);
8563
+ if (state.changes.length > MAX_CHANGES) {
8564
+ state.changes.shift();
8565
+ }
8566
+ for (const listener of [...state.listeners]) {
8567
+ listener(change);
8568
+ }
8569
+ return { change };
8570
+ }
8571
+ readChanges(input) {
8572
+ const state = this.getChangeState(input.path);
8573
+ const currentCursor = String(state.nextCursor - 1);
8574
+ if (input.after === undefined) {
8575
+ return { changes: [], cursor: currentCursor, hasMore: false, reset: false };
8576
+ }
8577
+ const after = Number.parseInt(input.after, 10);
8578
+ const oldest = Number.parseInt(state.changes[0]?.cursor ?? currentCursor, 10);
8579
+ if (after < oldest - 1) {
8580
+ return {
8581
+ changes: [{ cursor: currentCursor, invalidations: ["/:layout"] }],
8582
+ cursor: currentCursor,
8583
+ hasMore: false,
8584
+ reset: true
8585
+ };
8586
+ }
8587
+ const available = state.changes.filter((change) => Number.parseInt(change.cursor, 10) > after);
8588
+ const changes = available.slice(0, input.limit);
8589
+ return {
8590
+ changes,
8591
+ cursor: changes.at(-1)?.cursor ?? input.after,
8592
+ hasMore: available.length > changes.length,
8593
+ reset: false
8594
+ };
8595
+ }
8596
+ subscribe(path, listener) {
8597
+ const listeners = this.getChangeState(path).listeners;
8598
+ listeners.add(listener);
8599
+ return () => listeners.delete(listener);
8600
+ }
8601
+ reset() {
8602
+ this.changes.clear();
8603
+ this.mutationKeys.clear();
8604
+ this.mutations.clear();
8605
+ }
8606
+ evictMutations() {
8607
+ const expiredBefore = Date.now() - MUTATION_TTL_MS;
8608
+ for (const [mutationId, mutation] of this.mutations) {
8609
+ if (mutation.createdAt < expiredBefore) {
8610
+ this.deleteMutation(mutationId);
8611
+ }
8612
+ }
8613
+ while (this.mutations.size >= MAX_MUTATIONS) {
8614
+ const oldest = [...this.mutations.values()].find((entry) => entry.state === "succeeded");
8615
+ if (!oldest) {
8616
+ break;
8617
+ }
8618
+ this.deleteMutation(oldest.mutationId);
8619
+ }
8620
+ }
8621
+ deleteMutation(mutationId) {
8622
+ this.mutations.delete(mutationId);
8623
+ for (const [key, storedId] of this.mutationKeys) {
8624
+ if (storedId === mutationId) {
8625
+ this.mutationKeys.delete(key);
8626
+ return;
8627
+ }
8628
+ }
8629
+ }
8630
+ getChangeState(path) {
8631
+ const existing = this.changes.get(path);
8632
+ if (existing) {
8633
+ return existing;
8634
+ }
8635
+ const state = { changes: [], listeners: new Set, nextCursor: 1 };
8636
+ this.changes.set(path, state);
8637
+ return state;
8638
+ }
8639
+ }
8640
+ var memorySyncAdapter = new MemorySyncAdapter;
8641
+
8642
+ // src/server/sync/response.ts
8643
+ import { ElysiaCustomStatusResponse, StatusMap } from "elysia";
8644
+ var HOP_BY_HOP_HEADERS = new Set(["connection", "keep-alive", "transfer-encoding", "upgrade"]);
8645
+ function statusCode(status) {
8646
+ if (typeof status === "number") {
8647
+ return status;
8648
+ }
8649
+ return status === undefined ? 200 : StatusMap[status];
8650
+ }
8651
+ function unwrapStatusResponse(value) {
8652
+ if (!(value instanceof ElysiaCustomStatusResponse)) {
8653
+ return;
8654
+ }
8655
+ return { status: value.code, value: value.response };
8656
+ }
8657
+ function responseHeaders(headers) {
8658
+ const result = new Headers;
8659
+ for (const [name, value] of Object.entries(headers)) {
8660
+ if (value !== undefined && !HOP_BY_HOP_HEADERS.has(name.toLowerCase())) {
8661
+ for (const entry of Array.isArray(value) ? value : [value]) {
8662
+ result.append(name, String(entry));
8663
+ }
8664
+ }
8665
+ }
8666
+ return result;
8667
+ }
8668
+ async function storeResponse(responseValue, set) {
8669
+ if (responseValue instanceof Response) {
8670
+ const clone = responseValue.clone();
8671
+ const headers2 = [...clone.headers.entries()].filter(([name]) => !HOP_BY_HOP_HEADERS.has(name.toLowerCase()));
8672
+ return {
8673
+ body: new Uint8Array(await clone.arrayBuffer()),
8674
+ headers: headers2,
8675
+ status: clone.status
8676
+ };
8677
+ }
8678
+ const headers = responseHeaders(set.headers);
8679
+ const statusResponse = unwrapStatusResponse(responseValue);
8680
+ const value = statusResponse?.value ?? responseValue;
8681
+ let body;
8682
+ if (value === undefined || value === null) {
8683
+ body = new Uint8Array;
8684
+ } else if (typeof value === "string") {
8685
+ headers.set("content-type", headers.get("content-type") ?? "text/plain;charset=utf-8");
8686
+ body = new TextEncoder().encode(value);
8687
+ } else {
8688
+ headers.set("content-type", headers.get("content-type") ?? "application/json");
8689
+ body = new TextEncoder().encode(JSON.stringify(value));
8690
+ }
8691
+ return {
8692
+ body,
8693
+ headers: [...headers.entries()],
8694
+ status: statusResponse?.status ?? statusCode(set.status)
8695
+ };
8696
+ }
8697
+ function replayResponse(stored) {
8698
+ const body = stored.status === 204 || stored.status === 205 || stored.status === 304 ? null : stored.body.slice();
8699
+ return new Response(body, {
8700
+ headers: new Headers(stored.headers.map(([name, value]) => [name, value])),
8701
+ status: stored.status
8702
+ });
8703
+ }
8704
+
8201
8705
  // src/server/sync/stream.ts
8202
8706
  init_config();
8203
8707
  import { Elysia as Elysia3 } from "elysia";
8204
- var encoder = new TextEncoder;
8708
+ var DEFAULT_CHANGE_LIMIT = 100;
8709
+ var MAX_CHANGE_LIMIT = 500;
8710
+ var CURSOR_PATTERN = /^\d+$/;
8205
8711
  var defaultStreamPath = "/_furin/sync";
8712
+ var encoder = new TextEncoder;
8206
8713
  var streams = new Map;
8714
+ function encodeSseChange(change) {
8715
+ return encoder.encode(`id: ${change.cursor}
8716
+ event: furin.sync
8717
+ retry: 3000
8718
+ data: ${JSON.stringify({ cursor: change.cursor })}
8719
+
8720
+ `);
8721
+ }
8207
8722
  function getStreamState(path) {
8208
8723
  const existing = streams.get(path);
8209
8724
  if (existing) {
@@ -8212,69 +8727,70 @@ function getStreamState(path) {
8212
8727
  const state = {
8213
8728
  clients: new Set,
8214
8729
  heartbeats: new Set,
8215
- history: [],
8216
- nextEventId: 1
8730
+ unsubscribe: undefined
8217
8731
  };
8732
+ state.unsubscribe = memorySyncAdapter.subscribe(path, (change) => {
8733
+ const chunk = encodeSseChange(change);
8734
+ for (const client of [...state.clients]) {
8735
+ try {
8736
+ client.enqueue(chunk);
8737
+ } catch {
8738
+ state.clients.delete(client);
8739
+ }
8740
+ }
8741
+ });
8218
8742
  streams.set(path, state);
8219
8743
  return state;
8220
8744
  }
8221
- function encodeSseEvent(id, event, data) {
8222
- return encoder.encode(`id: ${id}
8223
- event: ${event}
8224
- retry: 3000
8225
- data: ${JSON.stringify(data)}
8226
-
8227
- `);
8745
+ function parseChangeQuery(request) {
8746
+ const url = new URL(request.url);
8747
+ const after = url.searchParams.get("after") ?? undefined;
8748
+ if (after !== undefined && !CURSOR_PATTERN.test(after)) {
8749
+ return { error: Response.json({ code: "FURIN_INVALID_SYNC_CURSOR" }, { status: 400 }) };
8750
+ }
8751
+ const limitValue = url.searchParams.get("limit");
8752
+ if (limitValue !== null && !CURSOR_PATTERN.test(limitValue)) {
8753
+ return { error: Response.json({ code: "FURIN_INVALID_SYNC_LIMIT" }, { status: 400 }) };
8754
+ }
8755
+ const limit = limitValue === null ? DEFAULT_CHANGE_LIMIT : Number.parseInt(limitValue, 10);
8756
+ if (!Number.isInteger(limit) || limit < 1 || limit > MAX_CHANGE_LIMIT) {
8757
+ return { error: Response.json({ code: "FURIN_INVALID_SYNC_LIMIT" }, { status: 400 }) };
8758
+ }
8759
+ return { after, limit };
8228
8760
  }
8229
8761
  function publishSyncInvalidation(invalidations) {
8230
8762
  if (invalidations.length === 0) {
8231
8763
  return;
8232
8764
  }
8233
- const state = getStreamState(getSyncStreamPath() ?? defaultStreamPath);
8234
- const id = state.nextEventId++;
8235
- const chunk = encodeSseEvent(id, "furin.invalidate", {
8236
- invalidations
8237
- });
8238
- state.history.push({ chunk, id });
8239
- if (state.history.length > 100) {
8240
- state.history.shift();
8241
- }
8242
- for (const client of [...state.clients]) {
8243
- try {
8244
- client.enqueue(chunk);
8245
- } catch {
8246
- state.clients.delete(client);
8247
- }
8765
+ for (const channel of syncPublishChannels()) {
8766
+ memorySyncAdapter.appendChanges({
8767
+ invalidations,
8768
+ path: channel
8769
+ });
8248
8770
  }
8249
8771
  }
8250
- function createSyncStreamPlugin(path) {
8772
+ function createSyncStreamPlugin(path, channel) {
8251
8773
  const streamPath = path ?? defaultStreamPath;
8252
- return new Elysia3({ name: `furin-sync-stream-${streamPath}` }).get(streamPath, ({ request }) => {
8253
- const state = getStreamState(streamPath);
8774
+ const channelKey = channel ?? streamPath;
8775
+ return new Elysia3({ name: `furin-sync-stream-${channelKey}` }).get(`${streamPath}/changes`, ({ request, set }) => {
8776
+ set.headers["cache-control"] = "no-store";
8777
+ const query = parseChangeQuery(request);
8778
+ if ("error" in query) {
8779
+ return query.error;
8780
+ }
8781
+ return memorySyncAdapter.readChanges({ ...query, path: channelKey });
8782
+ }).get(streamPath, () => {
8783
+ const state = getStreamState(channelKey);
8254
8784
  let controllerRef;
8255
8785
  let heartbeat;
8256
8786
  const stream = new ReadableStream({
8257
8787
  start(controller) {
8258
8788
  controllerRef = controller;
8259
8789
  state.clients.add(controller);
8260
- const lastEventId = Number.parseInt(request.headers.get("Last-Event-ID") ?? "", 10);
8261
- const oldestEventId = state.history[0]?.id;
8262
- const hasReplayGap = !Number.isNaN(lastEventId) && oldestEventId !== undefined && lastEventId < oldestEventId - 1;
8263
- const replay = Number.isNaN(lastEventId) ? [] : state.history.filter((entry) => entry.id > lastEventId);
8264
- if (hasReplayGap) {
8265
- controller.enqueue(encodeSseEvent(state.nextEventId - 1, "furin.invalidate", {
8266
- invalidations: ["/:layout"]
8267
- }));
8268
- } else if (replay.length > 0) {
8269
- for (const entry of replay) {
8270
- controller.enqueue(entry.chunk);
8271
- }
8272
- } else {
8273
- controller.enqueue(encoder.encode(`: connected
8790
+ controller.enqueue(encoder.encode(`: connected
8274
8791
  retry: 3000
8275
8792
 
8276
8793
  `));
8277
- }
8278
8794
  heartbeat = setInterval(() => {
8279
8795
  try {
8280
8796
  controller.enqueue(encoder.encode(`: heartbeat
@@ -8311,6 +8827,8 @@ retry: 3000
8311
8827
  }
8312
8828
 
8313
8829
  // src/server/sync/plugin.ts
8830
+ var routeMetadata = new WeakMap;
8831
+ var activeMutations = new WeakMap;
8314
8832
  function invalidationInputFromSync(input) {
8315
8833
  if (input && typeof input === "object" && "invalidate" in input) {
8316
8834
  return input.invalidate;
@@ -8328,69 +8846,113 @@ function getIdempotencyKey(ctx) {
8328
8846
  const fromRequest = ctx.request.headers.get("Idempotency-Key");
8329
8847
  return fromRequest || undefined;
8330
8848
  }
8849
+ async function getPrincipalScope(request) {
8850
+ const authorization = request.headers.get("authorization");
8851
+ const credentials = authorization ? JSON.stringify(["authorization", authorization]) : JSON.stringify(["cookie", request.headers.get("cookie") ?? ""]);
8852
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(credentials));
8853
+ return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
8854
+ }
8855
+ function supportsReplayBody(request) {
8856
+ const contentType = request.headers.get("content-type")?.toLowerCase();
8857
+ const mediaType = contentType?.split(";", 1)[0]?.trim();
8858
+ return contentType === undefined || mediaType === "application/json" || mediaType?.startsWith("application/") === true && mediaType.endsWith("+json") || contentType.startsWith("application/x-www-form-urlencoded") || contentType.startsWith("text/");
8859
+ }
8860
+ function conflictResponse(reason) {
8861
+ const inProgress = reason === "in-progress";
8862
+ return Response.json({
8863
+ code: inProgress ? "FURIN_MUTATION_IN_PROGRESS" : "FURIN_IDEMPOTENCY_MISMATCH",
8864
+ message: inProgress ? "A mutation with this Idempotency-Key is still running." : "The Idempotency-Key was already used with a different request."
8865
+ }, {
8866
+ status: 409,
8867
+ headers: inProgress ? { "retry-after": "1" } : undefined
8868
+ });
8869
+ }
8870
+ async function beginMutation(ctx) {
8871
+ if (!isMutationMethod(ctx.request.method) || routeMetadata.get(ctx.request)?.disabled) {
8872
+ return;
8873
+ }
8874
+ const idempotencyKey = getIdempotencyKey(ctx);
8875
+ if (!idempotencyKey) {
8876
+ return new Response("Missing Idempotency-Key header", {
8877
+ status: 428,
8878
+ headers: { "content-type": "text/plain; charset=utf-8" }
8879
+ });
8880
+ }
8881
+ if (!supportsReplayBody(ctx.request)) {
8882
+ return Response.json({
8883
+ code: "FURIN_UNSUPPORTED_SYNC_BODY",
8884
+ message: "This request body cannot be replayed. Set sync: false on the route."
8885
+ }, { status: 415 });
8886
+ }
8887
+ const url = new URL(ctx.request.url);
8888
+ const principal = await getPrincipalScope(ctx.request);
8889
+ const key = `${ctx.request.method}:${url.pathname}:${idempotencyKey}`;
8890
+ const fingerprint = await createMutationFingerprint({ body: ctx.body, request: ctx.request });
8891
+ const result = await memorySyncAdapter.beginMutation({ fingerprint, key, principal });
8892
+ if (result.kind === "replay") {
8893
+ return replayResponse(result.response);
8894
+ }
8895
+ if (result.kind === "conflict") {
8896
+ return conflictResponse(result.reason);
8897
+ }
8898
+ if (result.kind === "unavailable") {
8899
+ return Response.json({
8900
+ code: "FURIN_SYNC_CAPACITY_EXCEEDED",
8901
+ message: "The mutation replay store is temporarily full."
8902
+ }, { headers: { "retry-after": "1" }, status: 503 });
8903
+ }
8904
+ activeMutations.set(ctx.request, { mutationId: result.mutationId });
8905
+ }
8906
+ async function abortMutation(request) {
8907
+ const active = activeMutations.get(request);
8908
+ if (!active) {
8909
+ return;
8910
+ }
8911
+ activeMutations.delete(request);
8912
+ await memorySyncAdapter.abortMutation(active);
8913
+ }
8331
8914
  function furinSync() {
8332
- const idempotencyKeys = new Set;
8333
- const requestKeys = new WeakMap;
8334
8915
  return new Elysia4({ name: "furin-sync" }).macro({
8335
8916
  sync(input) {
8336
- const invalidate = invalidationInputFromSync(input);
8337
8917
  return {
8338
- beforeHandle(ctx) {
8339
- if (!isMutationMethod(ctx.request.method)) {
8340
- return;
8341
- }
8342
- const key = getIdempotencyKey(ctx);
8343
- if (!key) {
8344
- return new Response("Missing Idempotency-Key header", {
8345
- status: 428,
8346
- headers: { "content-type": "text/plain; charset=utf-8" }
8347
- });
8348
- }
8349
- const requestKey = `${ctx.request.method}:${new URL(ctx.request.url).pathname}:${key}`;
8350
- if (idempotencyKeys.has(requestKey)) {
8351
- return new Response("Duplicate Idempotency-Key header", {
8352
- status: 409,
8353
- headers: { "content-type": "text/plain; charset=utf-8" }
8354
- });
8355
- }
8356
- idempotencyKeys.add(requestKey);
8357
- requestKeys.set(ctx.request, requestKey);
8358
- if (idempotencyKeys.size > 1000) {
8359
- const oldest = idempotencyKeys.values().next().value;
8360
- if (typeof oldest === "string") {
8361
- idempotencyKeys.delete(oldest);
8362
- }
8363
- }
8364
- },
8365
- afterHandle(ctx) {
8366
- if (!isSuccessfulMutationResponse(ctx)) {
8367
- const requestKey = requestKeys.get(ctx.request);
8368
- if (requestKey) {
8369
- idempotencyKeys.delete(requestKey);
8370
- requestKeys.delete(ctx.request);
8371
- }
8372
- return;
8373
- }
8374
- requestKeys.delete(ctx.request);
8375
- runInvalidationRules(invalidate);
8376
- const pending = appendPendingInvalidationHeader(ctx.set);
8377
- if (pending.length === 0) {
8378
- return;
8379
- }
8380
- ctx.set.headers["x-furin-sync"] = "1";
8381
- publishSyncInvalidation(pending);
8382
- },
8383
- error({ request }) {
8384
- const requestKey = requestKeys.get(request);
8385
- if (requestKey) {
8386
- idempotencyKeys.delete(requestKey);
8387
- requestKeys.delete(request);
8388
- }
8918
+ transform({ request }) {
8919
+ routeMetadata.set(request, input === false ? { disabled: true } : { disabled: false, invalidate: invalidationInputFromSync(input) });
8389
8920
  }
8390
8921
  };
8391
8922
  }
8392
- });
8923
+ }).onBeforeHandle({ as: "global" }, beginMutation).onAfterHandle({ as: "global" }, async (ctx) => {
8924
+ const active = activeMutations.get(ctx.request);
8925
+ if (!active) {
8926
+ return;
8927
+ }
8928
+ if (!isSuccessfulMutationResponse(ctx)) {
8929
+ await abortMutation(ctx.request);
8930
+ return;
8931
+ }
8932
+ const invalidate = routeMetadata.get(ctx.request)?.invalidate;
8933
+ if (invalidate) {
8934
+ runInvalidationRules(invalidate);
8935
+ }
8936
+ const pending = appendPendingInvalidationHeader(ctx.set);
8937
+ if (pending.length > 0) {
8938
+ ctx.set.headers["x-furin-sync"] = "1";
8939
+ }
8940
+ const response = await storeResponse(ctx.responseValue, ctx.set);
8941
+ await memorySyncAdapter.commitMutation({ ...active, response });
8942
+ activeMutations.delete(ctx.request);
8943
+ if (pending.length > 0) {
8944
+ publishSyncInvalidation(pending);
8945
+ }
8946
+ }).onError({ as: "global" }, ({ request }) => abortMutation(request));
8947
+ }
8948
+ // src/shared/prefix.ts
8949
+ function clientDirNameForPrefix(prefix) {
8950
+ return prefix === "" ? "client" : `client-${prefixSlug(prefix)}`;
8951
+ }
8952
+ function prefixSlug(prefix) {
8953
+ return prefix.slice(1).replaceAll("/", "-");
8393
8954
  }
8955
+
8394
8956
  // src/furin.ts
8395
8957
  init_boundaries();
8396
8958
  init_client();
@@ -8416,17 +8978,19 @@ function furinInvalidate() {
8416
8978
  init_render();
8417
8979
  init_await();
8418
8980
  init_not_found();
8419
- function resolveClientDirFromArgv() {
8420
- return resolveClientDirFromEnv() ?? resolveClientDirFromModuleUrl() ?? resolveClientDirFromProcessArgs() ?? resolveFallbackClientDir();
8981
+ function resolveClientDirFromArgv(prefix) {
8982
+ const dirName = clientDirNameForPrefix(prefix);
8983
+ return resolveClientDirFromEnv(dirName) ?? resolveClientDirFromModuleUrl(dirName) ?? resolveClientDirFromProcessArgs(dirName) ?? resolveFallbackClientDir(dirName);
8421
8984
  }
8422
- function resolveClientDirFromEnv() {
8985
+ function resolveClientDirFromEnv(dirName) {
8423
8986
  const envClientDir = process.env.FURIN_CLIENT_DIR;
8424
8987
  if (!envClientDir) {
8425
8988
  return null;
8426
8989
  }
8427
- return envClientDir.startsWith("/") ? envClientDir : resolve2(process.cwd(), envClientDir);
8990
+ const base = envClientDir.startsWith("/") ? envClientDir : resolve2(process.cwd(), envClientDir);
8991
+ return dirName === "client" ? base : join4(dirname2(base), dirName);
8428
8992
  }
8429
- function resolveClientDirFromModuleUrl() {
8993
+ function resolveClientDirFromModuleUrl(dirName) {
8430
8994
  try {
8431
8995
  const moduleUrl = new URL(import.meta.url);
8432
8996
  if (moduleUrl.protocol !== "file:") {
@@ -8436,14 +9000,14 @@ function resolveClientDirFromModuleUrl() {
8436
9000
  if (modulePath.includes("/$bunfs/")) {
8437
9001
  return null;
8438
9002
  }
8439
- const moduleClientDir = join4(dirname2(modulePath), "client");
9003
+ const moduleClientDir = join4(dirname2(modulePath), dirName);
8440
9004
  if (existsSync5(join4(moduleClientDir, "index.html"))) {
8441
9005
  return moduleClientDir;
8442
9006
  }
8443
9007
  } catch {}
8444
9008
  return null;
8445
9009
  }
8446
- function resolveClientDirFromProcessArgs() {
9010
+ function resolveClientDirFromProcessArgs(dirName) {
8447
9011
  const candidates = [
8448
9012
  process.argv[1],
8449
9013
  process.argv[0],
@@ -8451,14 +9015,14 @@ function resolveClientDirFromProcessArgs() {
8451
9015
  process.execPath
8452
9016
  ].filter((value) => typeof value === "string" && value.length > 0);
8453
9017
  for (const candidate of candidates) {
8454
- const resolved = resolveClientDirFromCandidate(candidate);
9018
+ const resolved = resolveClientDirFromCandidate(candidate, dirName);
8455
9019
  if (resolved) {
8456
9020
  return resolved;
8457
9021
  }
8458
9022
  }
8459
9023
  return null;
8460
9024
  }
8461
- function resolveClientDirFromCandidate(candidate) {
9025
+ function resolveClientDirFromCandidate(candidate, dirName) {
8462
9026
  const name = basename(candidate);
8463
9027
  if (name === "bun" || name === "node") {
8464
9028
  return null;
@@ -8468,73 +9032,55 @@ function resolveClientDirFromCandidate(candidate) {
8468
9032
  }
8469
9033
  const absolute = candidate.startsWith("/") ? candidate : resolve2(process.cwd(), candidate);
8470
9034
  if (existsSync5(absolute)) {
8471
- return join4(dirname2(absolute), "client");
9035
+ return join4(dirname2(absolute), dirName);
8472
9036
  }
8473
9037
  if (!candidate.includes("/")) {
8474
- return resolveClientDirFromPath(candidate);
9038
+ return resolveClientDirFromPath(candidate, dirName);
8475
9039
  }
8476
9040
  return null;
8477
9041
  }
8478
- function resolveClientDirFromPath(candidate) {
9042
+ function resolveClientDirFromPath(candidate, dirName) {
8479
9043
  const pathEntries = process.env.PATH?.split(":") ?? [];
8480
9044
  for (const dir of pathEntries) {
8481
9045
  const fullPath = join4(dir, candidate);
8482
9046
  if (existsSync5(fullPath)) {
8483
- return join4(dirname2(fullPath), "client");
9047
+ return join4(dirname2(fullPath), dirName);
8484
9048
  }
8485
9049
  }
8486
9050
  return null;
8487
9051
  }
8488
- function resolveFallbackClientDir() {
8489
- const defaultClientDir = resolve2(process.cwd(), ".furin/build/bun/client");
9052
+ function resolveFallbackClientDir(dirName) {
9053
+ const defaultClientDir = resolve2(process.cwd(), ".furin/build/bun", dirName);
8490
9054
  if (existsSync5(join4(defaultClientDir, "index.html"))) {
8491
9055
  return defaultClientDir;
8492
9056
  }
8493
- return join4(process.cwd(), "client");
9057
+ return join4(process.cwd(), dirName);
8494
9058
  }
8495
- async function setupProdTemplate(embedded, clientDir) {
9059
+ async function setupProdTemplate(embedded, clientDir, instance) {
8496
9060
  if (embedded) {
8497
9061
  if (!embedded.template) {
8498
9062
  throw new Error("[furin] Embedded app is missing its HTML template (index.html).");
8499
9063
  }
8500
9064
  const html = await Bun.file(embedded.template).text();
8501
- setProductionTemplateContent(html);
9065
+ setProductionTemplateContent(html, instance);
8502
9066
  return;
8503
9067
  }
8504
9068
  const templatePath = join4(clientDir, "index.html");
8505
9069
  if (!existsSync5(templatePath)) {
8506
9070
  throw new Error("[furin] No pre-built assets found. Run `bun run build` first.");
8507
9071
  }
8508
- setProductionTemplatePath(templatePath);
8509
- }
8510
- function wrapWithRequestScope(app, syncStreamPath) {
8511
- return app.wrap((handler, _request) => (ctx) => runWithSyncStreamPath(syncStreamPath, () => _runWithRequestInvalidationScope(() => handler(ctx))));
9072
+ setProductionTemplatePath(templatePath, instance);
8512
9073
  }
8513
- function hydrateSSGCacheFromCompileContext(ctx) {
8514
- if (!ctx.ssgCache) {
8515
- return;
8516
- }
8517
- for (const [path, entry] of Object.entries(ctx.ssgCache)) {
8518
- setSSGCache(path, entry);
8519
- }
8520
- }
8521
- async function furin({
8522
- pagesDir,
8523
- logger,
8524
- clientLogging,
8525
- sync
8526
- }) {
8527
- const syncStreamPath = resolveSyncStreamPath(sync);
9074
+ function createLoggerPlugin(prefix, syncStreamPath, logger) {
8528
9075
  const { exclude: userExclude, ...evlogOptions } = logger ?? {};
8529
- initLogger({ env: { service: "furin" } });
8530
- const loggerPlugin = new Elysia7().use(evlog({
9076
+ return new Elysia7().use(evlog({
8531
9077
  ...evlogOptions,
8532
9078
  exclude: [
8533
- "/_client/**",
8534
- "/public/**",
8535
- "/favicon.ico",
8536
- "/_bun_hmr_entry/**",
8537
- ...syncStreamPath ? [syncStreamPath] : [],
9079
+ `${prefix}/_client/**`,
9080
+ `${prefix}/public/**`,
9081
+ `${prefix}/favicon.ico`,
9082
+ `${prefix}/_bun_hmr_entry/**`,
9083
+ ...syncStreamPath ? [`${prefix}${syncStreamPath}`] : [],
8538
9084
  ...userExclude ?? []
8539
9085
  ]
8540
9086
  })).post("/_furin/ingest", ({ body, log, status }) => {
@@ -8562,12 +9108,50 @@ async function furin({
8562
9108
  }
8563
9109
  return status("No Content");
8564
9110
  }, { parse: "json" });
9111
+ }
9112
+ function wrapWithRequestScope(app) {
9113
+ return app.wrap((handler, request) => (ctx) => {
9114
+ if (hasRequestScope()) {
9115
+ return handler(ctx);
9116
+ }
9117
+ markTraffic();
9118
+ const req = request ?? ctx?.request;
9119
+ const pathname = req ? new URL(req.url).pathname : "/";
9120
+ return runWithInstanceScope(resolveInstanceByPath(pathname), () => handler(ctx));
9121
+ });
9122
+ }
9123
+ function hydrateSSGCacheFromCompileContext(ctx) {
9124
+ if (!ctx.ssgCache) {
9125
+ return;
9126
+ }
9127
+ for (const [path, entry] of Object.entries(ctx.ssgCache)) {
9128
+ setSSGCache(path, entry);
9129
+ }
9130
+ }
9131
+ async function furin({
9132
+ pagesDir,
9133
+ prefix: rawPrefix,
9134
+ clientDir: explicitClientDir,
9135
+ logger,
9136
+ clientLogging,
9137
+ sync
9138
+ } = {}) {
9139
+ const prefix = normalizePrefix(rawPrefix);
9140
+ const syncStreamPath = resolveSyncStreamPath(sync);
9141
+ initLogger({ env: { service: "furin" } });
9142
+ const loggerPlugin = createLoggerPlugin(prefix, syncStreamPath, logger);
8565
9143
  const cwd = process.cwd();
8566
- const ctx = getCompileContext();
8567
- const resolvedPagesDir = ctx?.rootPath ? dirname2(ctx.rootPath) : resolve2(cwd, pagesDir ?? "src/pages");
8568
- const instanceName = `furin-${resolvedPagesDir.replaceAll("\\", "/")}`;
9144
+ const paramPagesDir = resolve2(cwd, pagesDir ?? "src/pages");
9145
+ const ctx = getCompileContext(paramPagesDir, prefix);
9146
+ const resolvedPagesDir = ctx?.rootPath ? dirname2(ctx.rootPath) : paramPagesDir;
9147
+ const instanceName = `furin-${prefix}-${resolvedPagesDir.replaceAll("\\", "/")}`;
9148
+ const normalizedPagesDir = resolvedPagesDir.replaceAll("\\", "/");
9149
+ assertPrefixAvailable(prefix, normalizedPagesDir);
9150
+ const instance = createInstance(prefix, normalizedPagesDir);
9151
+ instance.syncStreamPath = syncStreamPath;
8569
9152
  if (IS_DEV) {
8570
- const furinDir = resolve2(cwd, ".furin");
9153
+ const instanceSlug = prefix === "" ? "" : prefix.slice(1).replaceAll("/", "__");
9154
+ const furinDir = resolve2(cwd, ".furin", instanceSlug);
8571
9155
  const { registerDevPagePlugin: registerDevPagePlugin2 } = await Promise.resolve().then(() => (init_dev_page_plugin(), exports_dev_page_plugin));
8572
9156
  registerDevPagePlugin2();
8573
9157
  const { createDevInspectorPlugin: createDevInspectorPlugin2 } = await Promise.resolve().then(() => (init_dev_inspector(), exports_dev_inspector));
@@ -8578,28 +9162,29 @@ async function furin({
8578
9162
  writeDevFiles2(routes2, {
8579
9163
  outDir: furinDir,
8580
9164
  rootLayout: root2.path,
8581
- basePath: "",
8582
- publicPath: "/_client/",
8583
- clientLogging: clientLogging ?? false
9165
+ basePath: prefix,
9166
+ publicPath: `${prefix}/_client/`,
9167
+ clientLogging: clientLogging ?? false,
9168
+ skipRouteTypes: prefix !== ""
8584
9169
  }, cwd);
8585
9170
  const publicDir = resolve2(cwd, "public");
8586
9171
  const publicExists = existsSync5(publicDir);
8587
- const devApp = new Elysia7({ name: instanceName, seed: resolvedPagesDir }).use(loggerPlugin).onError({ as: "global" }, async ({ code, request }) => {
9172
+ const devApp = new Elysia7({
9173
+ name: instanceName,
9174
+ seed: resolvedPagesDir,
9175
+ prefix: prefix || undefined
9176
+ }).use(loggerPlugin).onError(async ({ code, request }) => {
8588
9177
  if (code === "NOT_FOUND") {
8589
9178
  return await renderRootNotFound(root2, request);
8590
9179
  }
8591
- }).onAfterHandle({ as: "global" }, ({ set }) => {
9180
+ }).onAfterHandle(({ set }) => {
8592
9181
  const pending = consumePendingInvalidations();
8593
9182
  if (pending.length > 0) {
8594
9183
  set.headers["x-furin-revalidate"] = pending.join(",");
8595
9184
  }
8596
- }).use(await staticPlugin({ assets: furinDir, prefix: "/_bun_hmr_entry", bunFullstack: true })).use(publicExists ? await staticPlugin({ assets: publicDir, prefix: "/public" }) : new Elysia7).get("/favicon.ico", publicExists ? file(join4(publicDir, "favicon.ico")) : () => new Response(null, { status: 404 })).use(createDevInspectorPlugin2()).use(syncStreamPath ? createSyncStreamPlugin(syncStreamPath) : new Elysia7).use(createDataEndpoint(routes2)).use((app) => {
8597
- for (const route of routes2) {
8598
- app.use(createRoutePlugin(route, root2, undefined, searchRoutes2));
8599
- }
8600
- return app;
8601
- });
8602
- return wrapWithRequestScope(devApp, syncStreamPath);
9185
+ }).use(await staticPlugin({ assets: furinDir, prefix: "/_bun_hmr_entry", bunFullstack: true })).use(publicExists ? await staticPlugin({ assets: publicDir, prefix: "/public" }) : new Elysia7).get("/favicon.ico", publicExists ? file(join4(publicDir, "favicon.ico")) : () => new Response(null, { status: 404 })).use(createDevInspectorPlugin2()).use(syncStreamPath ? createSyncStreamPlugin(syncStreamPath, `${prefix}${syncStreamPath}`) : new Elysia7).use(createDataEndpoint(routes2)).use((app) => routes2.reduce((chain, route) => chain.use(createRoutePlugin(route, root2, undefined, searchRoutes2)), app)).use(createNotFoundHandling(prefix, routes2, root2));
9186
+ registerInstance(instance);
9187
+ return wrapWithRequestScope(devApp);
8603
9188
  }
8604
9189
  if (!ctx) {
8605
9190
  throw new Error("[furin] No pre-built assets found. Run `bunx furin build` first.");
@@ -8607,33 +9192,39 @@ async function furin({
8607
9192
  const { root, routes } = loadProdRoutes(ctx);
8608
9193
  const searchRoutes = createSearchRouteMetadata(routes);
8609
9194
  const prodBuildId = ctx.buildId ?? "";
8610
- setBuildId(prodBuildId);
8611
- hydrateSSGCacheFromCompileContext(ctx);
9195
+ instance.buildId = prodBuildId;
9196
+ withInstance(instance, () => {
9197
+ hydrateSSGCacheFromCompileContext(ctx);
9198
+ });
8612
9199
  const embedded = ctx?.embedded;
8613
- const clientDir = embedded ? "" : resolveClientDirFromArgv();
8614
- await setupProdTemplate(embedded, clientDir);
8615
- const prodApp = new Elysia7({ name: instanceName, seed: resolvedPagesDir }).use(loggerPlugin).onError({ as: "global" }, async ({ code, request }) => {
9200
+ const clientDir = embedded ? "" : explicitClientDir ?? resolveClientDirFromArgv(prefix);
9201
+ await setupProdTemplate(embedded, clientDir, instance);
9202
+ const clientAssetPrefix = `${prefix}/_client/`;
9203
+ const prodApp = new Elysia7({
9204
+ name: instanceName,
9205
+ seed: resolvedPagesDir,
9206
+ prefix: prefix || undefined
9207
+ }).use(loggerPlugin).onError(async ({ code, request }) => {
8616
9208
  if (code === "NOT_FOUND") {
8617
9209
  return await renderRootNotFound(root, request);
8618
9210
  }
8619
- }).onAfterHandle({ as: "global" }, ({ path, set }) => {
8620
- if (path.startsWith("/_client/")) {
9211
+ }).onAfterHandle(({ path, set }) => {
9212
+ if (path.startsWith(clientAssetPrefix)) {
8621
9213
  set.headers["cache-control"] = "public, max-age=31536000, immutable";
8622
9214
  }
8623
9215
  const pending = consumePendingInvalidations();
8624
9216
  if (pending.length > 0) {
8625
9217
  set.headers["x-furin-revalidate"] = pending.join(",");
8626
9218
  }
8627
- const buildId = getBuildId();
8628
- if (buildId) {
8629
- set.headers["x-furin-build-id"] = buildId;
9219
+ if (instance.buildId) {
9220
+ set.headers["x-furin-build-id"] = instance.buildId;
8630
9221
  }
8631
9222
  }).onStart(async ({ server }) => {
8632
9223
  if (ctx.ssgCache) {
8633
9224
  return;
8634
9225
  }
8635
9226
  const origin = server?.url?.origin ?? "http://localhost:3000";
8636
- await warmSSGCache(routes, root, origin, searchRoutes);
9227
+ await withInstance(instance, () => warmSSGCache(routes, root, origin, searchRoutes));
8637
9228
  }).use(await (async () => {
8638
9229
  if (embedded) {
8639
9230
  return new Elysia7().get("/favicon.ico", ({ status }) => {
@@ -8663,13 +9254,25 @@ async function furin({
8663
9254
  }
8664
9255
  app.use(await staticPlugin({ assets: clientDir, prefix: "/_client" }));
8665
9256
  return app;
8666
- })()).use(syncStreamPath ? createSyncStreamPlugin(syncStreamPath) : new Elysia7).use(createDataEndpoint(routes)).use((app) => {
8667
- for (const route of routes) {
8668
- app.use(createRoutePlugin(route, root, prodBuildId, searchRoutes));
8669
- }
9257
+ })()).use(syncStreamPath ? createSyncStreamPlugin(syncStreamPath, `${prefix}${syncStreamPath}`) : new Elysia7).use(createDataEndpoint(routes)).use((app) => routes.reduce((chain, route) => chain.use(createRoutePlugin(route, root, prodBuildId, searchRoutes)), app)).use(createNotFoundHandling(prefix, routes, root));
9258
+ registerInstance(instance);
9259
+ return wrapWithRequestScope(prodApp);
9260
+ }
9261
+ function createNotFoundHandling(prefix, routes, root) {
9262
+ const app = new Elysia7;
9263
+ if (prefix === "") {
9264
+ app.onError({ as: "global" }, async ({ code, request }) => {
9265
+ if (code === "NOT_FOUND") {
9266
+ return await renderRootNotFound(root, request);
9267
+ }
9268
+ });
8670
9269
  return app;
8671
- });
8672
- return wrapWithRequestScope(prodApp, syncStreamPath);
9270
+ }
9271
+ if (routes.some((route) => route.pattern === "/*")) {
9272
+ return app;
9273
+ }
9274
+ app.get("/*", ({ request }) => renderRootNotFound(root, request));
9275
+ return app;
8673
9276
  }
8674
9277
  export {
8675
9278
  useAsyncValue,
@@ -8685,6 +9288,7 @@ export {
8685
9288
  furinInvalidate,
8686
9289
  furin,
8687
9290
  defer,
9291
+ clientDirNameForPrefix,
8688
9292
  buildErrorElement,
8689
9293
  buildElement,
8690
9294
  FurinNotFoundBoundary,