@rangojs/router 0.0.0-experimental.fa8a383a → 0.0.0-experimental.fb4fdc18

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 (175) hide show
  1. package/README.md +188 -35
  2. package/dist/bin/rango.js +130 -47
  3. package/dist/vite/index.js +1884 -537
  4. package/dist/vite/index.js.bak +5448 -0
  5. package/dist/vite/plugins/cloudflare-protocol-loader-hook.mjs +76 -0
  6. package/package.json +7 -5
  7. package/skills/breadcrumbs/SKILL.md +3 -1
  8. package/skills/cache-guide/SKILL.md +32 -0
  9. package/skills/caching/SKILL.md +8 -0
  10. package/skills/handler-use/SKILL.md +362 -0
  11. package/skills/hooks/SKILL.md +33 -20
  12. package/skills/i18n/SKILL.md +276 -0
  13. package/skills/intercept/SKILL.md +20 -0
  14. package/skills/layout/SKILL.md +22 -0
  15. package/skills/links/SKILL.md +93 -17
  16. package/skills/loader/SKILL.md +123 -46
  17. package/skills/middleware/SKILL.md +36 -3
  18. package/skills/migrate-nextjs/SKILL.md +562 -0
  19. package/skills/migrate-react-router/SKILL.md +769 -0
  20. package/skills/parallel/SKILL.md +133 -0
  21. package/skills/prerender/SKILL.md +110 -68
  22. package/skills/rango/SKILL.md +26 -22
  23. package/skills/response-routes/SKILL.md +8 -0
  24. package/skills/route/SKILL.md +75 -0
  25. package/skills/router-setup/SKILL.md +87 -2
  26. package/skills/server-actions/SKILL.md +739 -0
  27. package/skills/streams-and-websockets/SKILL.md +283 -0
  28. package/skills/typesafety/SKILL.md +19 -1
  29. package/src/__internal.ts +1 -1
  30. package/src/browser/app-shell.ts +52 -0
  31. package/src/browser/app-version.ts +14 -0
  32. package/src/browser/event-controller.ts +44 -4
  33. package/src/browser/navigation-bridge.ts +95 -7
  34. package/src/browser/navigation-client.ts +128 -53
  35. package/src/browser/navigation-store.ts +68 -9
  36. package/src/browser/partial-update.ts +93 -12
  37. package/src/browser/prefetch/cache.ts +129 -21
  38. package/src/browser/prefetch/fetch.ts +156 -18
  39. package/src/browser/prefetch/queue.ts +92 -29
  40. package/src/browser/prefetch/resource-ready.ts +77 -0
  41. package/src/browser/rango-state.ts +53 -13
  42. package/src/browser/react/Link.tsx +72 -8
  43. package/src/browser/react/NavigationProvider.tsx +82 -21
  44. package/src/browser/react/context.ts +7 -2
  45. package/src/browser/react/filter-segment-order.ts +51 -7
  46. package/src/browser/react/use-handle.ts +9 -58
  47. package/src/browser/react/use-navigation.ts +22 -2
  48. package/src/browser/react/use-params.ts +17 -4
  49. package/src/browser/react/use-router.ts +29 -9
  50. package/src/browser/react/use-segments.ts +11 -8
  51. package/src/browser/rsc-router.tsx +60 -9
  52. package/src/browser/scroll-restoration.ts +10 -8
  53. package/src/browser/segment-reconciler.ts +36 -14
  54. package/src/browser/server-action-bridge.ts +8 -6
  55. package/src/browser/types.ts +46 -5
  56. package/src/build/generate-manifest.ts +6 -6
  57. package/src/build/generate-route-types.ts +3 -0
  58. package/src/build/route-trie.ts +52 -25
  59. package/src/build/route-types/include-resolution.ts +8 -1
  60. package/src/build/route-types/router-processing.ts +211 -72
  61. package/src/build/route-types/scan-filter.ts +8 -1
  62. package/src/cache/cache-runtime.ts +15 -11
  63. package/src/cache/cache-scope.ts +46 -5
  64. package/src/cache/cf/cf-cache-store.ts +5 -7
  65. package/src/cache/taint.ts +55 -0
  66. package/src/client.tsx +84 -230
  67. package/src/context-var.ts +72 -2
  68. package/src/handle.ts +40 -0
  69. package/src/index.rsc.ts +6 -1
  70. package/src/index.ts +49 -6
  71. package/src/outlet-context.ts +1 -1
  72. package/src/prerender/store.ts +5 -4
  73. package/src/prerender.ts +138 -77
  74. package/src/response-utils.ts +28 -0
  75. package/src/reverse.ts +28 -2
  76. package/src/route-definition/dsl-helpers.ts +210 -35
  77. package/src/route-definition/helpers-types.ts +73 -20
  78. package/src/route-definition/index.ts +3 -0
  79. package/src/route-definition/redirect.ts +9 -1
  80. package/src/route-definition/resolve-handler-use.ts +155 -0
  81. package/src/route-types.ts +18 -0
  82. package/src/router/content-negotiation.ts +100 -1
  83. package/src/router/handler-context.ts +102 -25
  84. package/src/router/intercept-resolution.ts +9 -4
  85. package/src/router/lazy-includes.ts +6 -6
  86. package/src/router/loader-resolution.ts +159 -21
  87. package/src/router/manifest.ts +22 -13
  88. package/src/router/match-api.ts +128 -192
  89. package/src/router/match-handlers.ts +1 -0
  90. package/src/router/match-middleware/background-revalidation.ts +12 -1
  91. package/src/router/match-middleware/cache-lookup.ts +74 -14
  92. package/src/router/match-middleware/cache-store.ts +21 -4
  93. package/src/router/match-middleware/segment-resolution.ts +53 -0
  94. package/src/router/match-result.ts +112 -9
  95. package/src/router/metrics.ts +6 -1
  96. package/src/router/middleware-types.ts +20 -33
  97. package/src/router/middleware.ts +56 -12
  98. package/src/router/navigation-snapshot.ts +182 -0
  99. package/src/router/pattern-matching.ts +101 -17
  100. package/src/router/prerender-match.ts +110 -10
  101. package/src/router/preview-match.ts +30 -102
  102. package/src/router/request-classification.ts +310 -0
  103. package/src/router/revalidation.ts +15 -1
  104. package/src/router/route-snapshot.ts +245 -0
  105. package/src/router/router-context.ts +1 -0
  106. package/src/router/router-interfaces.ts +36 -4
  107. package/src/router/router-options.ts +37 -11
  108. package/src/router/segment-resolution/fresh.ts +114 -18
  109. package/src/router/segment-resolution/helpers.ts +29 -24
  110. package/src/router/segment-resolution/revalidation.ts +257 -127
  111. package/src/router/trie-matching.ts +18 -13
  112. package/src/router/types.ts +1 -0
  113. package/src/router/url-params.ts +49 -0
  114. package/src/router.ts +55 -7
  115. package/src/rsc/handler.ts +478 -383
  116. package/src/rsc/helpers.ts +69 -41
  117. package/src/rsc/loader-fetch.ts +23 -3
  118. package/src/rsc/manifest-init.ts +5 -1
  119. package/src/rsc/progressive-enhancement.ts +18 -2
  120. package/src/rsc/response-route-handler.ts +14 -1
  121. package/src/rsc/rsc-rendering.ts +20 -1
  122. package/src/rsc/server-action.ts +12 -0
  123. package/src/rsc/ssr-setup.ts +2 -2
  124. package/src/rsc/types.ts +15 -1
  125. package/src/segment-content-promise.ts +67 -0
  126. package/src/segment-loader-promise.ts +122 -0
  127. package/src/segment-system.tsx +22 -62
  128. package/src/server/context.ts +76 -4
  129. package/src/server/handle-store.ts +19 -0
  130. package/src/server/loader-registry.ts +9 -8
  131. package/src/server/request-context.ts +185 -57
  132. package/src/ssr/index.tsx +8 -1
  133. package/src/static-handler.ts +18 -6
  134. package/src/types/cache-types.ts +4 -4
  135. package/src/types/handler-context.ts +145 -68
  136. package/src/types/loader-types.ts +41 -15
  137. package/src/types/request-scope.ts +126 -0
  138. package/src/types/route-entry.ts +12 -1
  139. package/src/types/segments.ts +18 -1
  140. package/src/urls/include-helper.ts +24 -14
  141. package/src/urls/path-helper-types.ts +39 -6
  142. package/src/urls/path-helper.ts +47 -12
  143. package/src/urls/pattern-types.ts +12 -0
  144. package/src/urls/response-types.ts +18 -16
  145. package/src/use-loader.tsx +77 -5
  146. package/src/vite/debug.ts +184 -0
  147. package/src/vite/discovery/bundle-postprocess.ts +30 -33
  148. package/src/vite/discovery/discover-routers.ts +36 -4
  149. package/src/vite/discovery/gate-state.ts +171 -0
  150. package/src/vite/discovery/prerender-collection.ts +175 -74
  151. package/src/vite/discovery/self-gen-tracking.ts +27 -1
  152. package/src/vite/discovery/state.ts +13 -4
  153. package/src/vite/index.ts +4 -0
  154. package/src/vite/plugin-types.ts +60 -5
  155. package/src/vite/plugins/cjs-to-esm.ts +5 -0
  156. package/src/vite/plugins/client-ref-dedup.ts +16 -0
  157. package/src/vite/plugins/client-ref-hashing.ts +16 -4
  158. package/src/vite/plugins/cloudflare-protocol-loader-hook.d.mts +23 -0
  159. package/src/vite/plugins/cloudflare-protocol-loader-hook.mjs +76 -0
  160. package/src/vite/plugins/cloudflare-protocol-stub.ts +214 -0
  161. package/src/vite/plugins/expose-action-id.ts +52 -28
  162. package/src/vite/plugins/expose-id-utils.ts +12 -0
  163. package/src/vite/plugins/expose-ids/handler-transform.ts +30 -0
  164. package/src/vite/plugins/expose-ids/router-transform.ts +20 -3
  165. package/src/vite/plugins/expose-internal-ids.ts +563 -316
  166. package/src/vite/plugins/performance-tracks.ts +96 -0
  167. package/src/vite/plugins/refresh-cmd.ts +88 -26
  168. package/src/vite/plugins/use-cache-transform.ts +56 -43
  169. package/src/vite/plugins/version-injector.ts +37 -11
  170. package/src/vite/rango.ts +63 -11
  171. package/src/vite/router-discovery.ts +732 -86
  172. package/src/vite/utils/banner.ts +1 -1
  173. package/src/vite/utils/package-resolution.ts +41 -1
  174. package/src/vite/utils/prerender-utils.ts +38 -5
  175. package/src/vite/utils/shared-utils.ts +3 -2
@@ -31,25 +31,25 @@ export function postprocessBundle(state: DiscoveryState): void {
31
31
  state.rscEntryFileName ?? "index.js",
32
32
  );
33
33
 
34
- // 1. Evict handler code from __prerender-handlers and __static-handlers chunks.
35
- // handlerChunkInfo/staticHandlerChunkInfo are populated by generateBundle
34
+ // 1. Evict handler code from whichever chunks contain handler exports.
35
+ // handlerChunkInfoMap/staticHandlerChunkInfoMap are populated by generateBundle
36
36
  // after the production RSC build. In Vite 6 multi-environment builds, the
37
- // RSC build runs twice (analysis + production). Chunk info is only available
38
- // after the production pass, so we run eviction whenever it becomes available.
37
+ // RSC build runs twice (analysis + production). The maps are cleared at the
38
+ // start of each generateBundle pass so only production data is used here.
39
39
  const evictionTargets: Array<{
40
- info: typeof state.handlerChunkInfo;
40
+ infos: Iterable<import("./state.js").ChunkInfo>;
41
41
  fnName: string;
42
42
  brand: string;
43
43
  label: string;
44
44
  }> = [
45
45
  {
46
- info: state.handlerChunkInfo,
46
+ infos: state.handlerChunkInfoMap.values(),
47
47
  fnName: "Prerender",
48
48
  brand: "prerenderHandler",
49
49
  label: "handler code from RSC bundle",
50
50
  },
51
51
  {
52
- info: state.staticHandlerChunkInfo,
52
+ infos: state.staticHandlerChunkInfoMap.values(),
53
53
  fnName: "Static",
54
54
  brand: "staticHandler",
55
55
  label: "static handler code",
@@ -57,35 +57,32 @@ export function postprocessBundle(state: DiscoveryState): void {
57
57
  ];
58
58
 
59
59
  for (const target of evictionTargets) {
60
- if (!target.info) continue;
61
- const chunkPath = resolve(
62
- state.projectRoot,
63
- "dist/rsc",
64
- target.info.fileName,
65
- );
66
- try {
67
- const code = readFileSync(chunkPath, "utf-8");
68
- const result = evictHandlerCode(
69
- code,
70
- target.info.exports,
71
- target.fnName,
72
- target.brand,
73
- );
74
- if (result) {
75
- writeFileSync(chunkPath, result.code);
76
- const savedKB = (result.savedBytes / 1024).toFixed(1);
77
- console.log(
78
- `[rsc-router] Evicted ${target.label} (${savedKB} KB saved): ${target.info.fileName}`,
60
+ for (const info of target.infos) {
61
+ const chunkPath = resolve(state.projectRoot, "dist/rsc", info.fileName);
62
+ try {
63
+ const code = readFileSync(chunkPath, "utf-8");
64
+ const result = evictHandlerCode(
65
+ code,
66
+ info.exports,
67
+ target.fnName,
68
+ target.brand,
69
+ );
70
+ if (result) {
71
+ writeFileSync(chunkPath, result.code);
72
+ const savedKB = (result.savedBytes / 1024).toFixed(1);
73
+ console.log(
74
+ `[rsc-router] Evicted ${target.label} (${savedKB} KB saved): ${info.fileName}`,
75
+ );
76
+ }
77
+ } catch (replaceErr: any) {
78
+ console.warn(
79
+ `[rsc-router] Failed to evict ${target.label}: ${replaceErr.message}`,
79
80
  );
80
81
  }
81
- } catch (replaceErr: any) {
82
- console.warn(
83
- `[rsc-router] Failed to evict ${target.label}: ${replaceErr.message}`,
84
- );
85
82
  }
86
83
  }
87
- state.handlerChunkInfo = null;
88
- state.staticHandlerChunkInfo = null;
84
+ state.handlerChunkInfoMap.clear();
85
+ state.staticHandlerChunkInfoMap.clear();
89
86
 
90
87
  // 2. Write prerender data as separate importable asset modules
91
88
  // and inject a lazy manifest loader into the RSC entry.
@@ -138,7 +135,7 @@ export function postprocessBundle(state: DiscoveryState): void {
138
135
  // and inject a __STATIC_MANIFEST import into the RSC entry.
139
136
  if (hasStaticData && existsSync(rscEntryPath)) {
140
137
  const rscCode = readFileSync(rscEntryPath, "utf-8");
141
- if (!rscCode.includes("__STATIC_MANIFEST")) {
138
+ if (!rscCode.includes("__static-manifest.js")) {
142
139
  try {
143
140
  const manifestEntries: string[] = [];
144
141
  let totalBytes = copyStagedBuildAssets(
@@ -20,6 +20,9 @@ import {
20
20
  expandPrerenderRoutes,
21
21
  renderStaticHandlers,
22
22
  } from "./prerender-collection.js";
23
+ import { createRangoDebugger, timed, NS } from "../debug.js";
24
+
25
+ const debug = createRangoDebugger(NS.discovery);
23
26
 
24
27
  /**
25
28
  * Import the user's entry via RSC runner, generate manifests for each
@@ -38,10 +41,16 @@ export async function discoverRouters(
38
41
  // Import the entry file via RSC environment.
39
42
  // For node preset: this is the router file (createRouter() registers in RouterRegistry).
40
43
  // For cloudflare preset: this is the worker entry (which imports the router).
41
- await rscEnv.runner.import(state.resolvedEntryPath);
44
+ await timed(debug, "inner: import entry", () =>
45
+ rscEnv.runner.import(state.resolvedEntryPath),
46
+ );
42
47
 
43
48
  // Import the router package to access the registry
44
- const serverMod = await rscEnv.runner.import("@rangojs/router/server");
49
+ const serverMod = await timed(
50
+ debug,
51
+ "inner: import @rangojs/router/server",
52
+ () => rscEnv.runner.import("@rangojs/router/server"),
53
+ );
45
54
  let registry: Map<string, any> = serverMod.RouterRegistry;
46
55
 
47
56
  if (!registry || registry.size === 0) {
@@ -100,9 +109,15 @@ export async function discoverRouters(
100
109
  }
101
110
 
102
111
  // Import build utilities for manifest generation
103
- const buildMod = await rscEnv.runner.import("@rangojs/router/build");
112
+ const buildMod = await timed(
113
+ debug,
114
+ "inner: import @rangojs/router/build",
115
+ () => rscEnv.runner.import("@rangojs/router/build"),
116
+ );
104
117
  const generateManifestFull = buildMod.generateManifestFull;
105
118
 
119
+ debug?.("inner: found %d router(s) in registry", registry.size);
120
+
106
121
  const nestedRouterConflict = findNestedRouterConflict(
107
122
  [...registry.values()]
108
123
  .map((router) => router.__sourceFile)
@@ -130,12 +145,17 @@ export async function discoverRouters(
130
145
  // Collect all manifests for trie building (avoid re-running generateManifest)
131
146
  const allManifests: Array<{ id: string; manifest: any }> = [];
132
147
 
148
+ const manifestGenStart = debug ? performance.now() : 0;
133
149
  for (const [id, router] of registry) {
134
150
  if (!router.urlpatterns || !generateManifestFull) {
135
151
  continue;
136
152
  }
137
153
 
138
- const manifest = generateManifestFull(router.urlpatterns, routerMountIndex);
154
+ const manifest = generateManifestFull(
155
+ router.urlpatterns,
156
+ routerMountIndex,
157
+ router.__basename ? { urlPrefix: router.__basename } : undefined,
158
+ );
139
159
  routerMountIndex++;
140
160
  allManifests.push({ id, manifest });
141
161
  const routeCount = Object.keys(manifest.routeManifest).length;
@@ -230,8 +250,15 @@ export async function discoverRouters(
230
250
  }
231
251
  }
232
252
 
253
+ debug?.(
254
+ "inner: generated manifests for %d router(s) (%sms)",
255
+ allManifests.length,
256
+ (performance.now() - manifestGenStart).toFixed(1),
257
+ );
258
+
233
259
  // Build route trie from merged manifest + ancestry
234
260
  let newMergedRouteTrie: any = null;
261
+ const trieStart = debug ? performance.now() : 0;
235
262
  if (Object.keys(newMergedRouteManifest).length > 0) {
236
263
  const buildRouteTrie = buildMod.buildRouteTrie;
237
264
  if (buildRouteTrie && mergedRouteAncestry) {
@@ -325,6 +352,11 @@ export async function discoverRouters(
325
352
  }
326
353
  }
327
354
 
355
+ debug?.(
356
+ "inner: trie build done (%sms)",
357
+ (performance.now() - trieStart).toFixed(1),
358
+ );
359
+
328
360
  // Commit all local state to the shared discovery state atomically.
329
361
  // This ensures a failed re-discovery (e.g. from a transient module
330
362
  // evaluation error) preserves the last known-good state.
@@ -0,0 +1,171 @@
1
+ import type { Debugger } from "../debug.js";
2
+
3
+ /**
4
+ * Manifest-readiness gate + rediscovery scheduler.
5
+ *
6
+ * Owns the four pieces of state that cooperate to keep
7
+ * `s.discoveryDone` (the promise the manifest virtual module's `load()`
8
+ * hook awaits) consistent across HMR fan-out:
9
+ *
10
+ * - **gatePending**: a Promise has been issued and not yet resolved.
11
+ * Workerd's manifest virtual module load() is blocked on it.
12
+ * - **inProgress**: a refresh's work callback is currently executing.
13
+ * - **queued**: a refresh was attempted while one was already in
14
+ * flight; the active run consumes this in its `finally` and
15
+ * recurses.
16
+ * - **pendingEvents**: a route-file event has been received (gate
17
+ * already reset) but the corresponding refresh's work hasn't started
18
+ * yet — i.e. the debounce hasn't fired. Set in `noteRouteEvent`,
19
+ * cleared at the start of each refresh cycle. Refresh's finally MUST
20
+ * hold the gate if this is true even when `queued` is false,
21
+ * otherwise an event whose debounce fires AFTER the active refresh
22
+ * completes (the "tail-race" window) would observe a resolved gate.
23
+ *
24
+ * The HMR-event flow (cloudflare-stress repro):
25
+ *
26
+ * t=0 Touch 1 → noteRouteEvent → pendingEvents=true, beginGate
27
+ * (gate1 pending)
28
+ * → debounce 100ms
29
+ * t=100 runRefreshCycle(work) → clear pendingEvents, work starts
30
+ * t=750 Touch 2 → noteRouteEvent → pendingEvents=true (no-op gate)
31
+ * → debounce fires at t=850
32
+ * t=800 refresh A's finally → queued=false, pendingEvents=true
33
+ * → HOLD gate (don't resolve)
34
+ * t=850 runRefreshCycle (debounce) → clear pendingEvents, work starts
35
+ * t=1500 refresh B's finally → queued=false, pendingEvents=false
36
+ * → resolveGate (gate1 resolves)
37
+ *
38
+ * @internal Exported only for unit tests.
39
+ */
40
+ export interface DiscoveryGate {
41
+ /**
42
+ * Reset the gate to a fresh pending Promise via `s.discoveryDone`.
43
+ * No-op when a gate is already pending — file watchers can fire
44
+ * multiple events for one save, and replacing the resolver would
45
+ * orphan the original promise (workerd's manifest load() would hang).
46
+ */
47
+ beginGate(): void;
48
+ /**
49
+ * Resolve the current pending gate. No-op when no gate is pending.
50
+ * Called at the tail of the last refresh cycle in a burst.
51
+ */
52
+ resolveGate(): void;
53
+ /**
54
+ * Record that a route-file event has arrived. Sets `pendingEvents`
55
+ * and begins the gate. Idempotent for both flags.
56
+ */
57
+ noteRouteEvent(): void;
58
+ /**
59
+ * Run one refresh cycle, managing queue + pending state around it.
60
+ * If a cycle is already in flight, sets `queued=true` and returns.
61
+ * Otherwise clears `pendingEvents`, runs `work`, and in `finally`:
62
+ *
63
+ * - queued → recurse, gate stays pending
64
+ * - pendingEvents → hold gate (next debounced cycle resolves)
65
+ * - neither → resolveGate
66
+ */
67
+ runRefreshCycle(work: () => Promise<void>): Promise<void>;
68
+ /** Snapshot of internal state. Test-only. */
69
+ readonly state: () => Readonly<{
70
+ gatePending: boolean;
71
+ inProgress: boolean;
72
+ queued: boolean;
73
+ pendingEvents: boolean;
74
+ }>;
75
+ }
76
+
77
+ /** State container the gate writes `discoveryDone` into. */
78
+ export interface GateOwner {
79
+ discoveryDone: Promise<void> | null | undefined;
80
+ }
81
+
82
+ export function createDiscoveryGate(
83
+ s: GateOwner,
84
+ debug?: Debugger,
85
+ ): DiscoveryGate {
86
+ let gatePending = false;
87
+ let gateResolver: () => void = () => {};
88
+ let inProgress = false;
89
+ let queued = false;
90
+ let pendingEvents = false;
91
+
92
+ const beginGate = (): void => {
93
+ if (gatePending) return;
94
+ s.discoveryDone = new Promise<void>((resolve) => {
95
+ gateResolver = resolve;
96
+ });
97
+ gatePending = true;
98
+ };
99
+
100
+ const resolveGate = (): void => {
101
+ if (!gatePending) return;
102
+ // Defer resolution while a refresh cycle is in flight or queued, or
103
+ // while an unprocessed route-file event is pending its debounce.
104
+ // Without this guard, cold-start's `discover().then(resolveGate)`
105
+ // could fire while an HMR-triggered runRefreshCycle is mid-flight,
106
+ // prematurely unblocking workerd's manifest load() against the
107
+ // stale cold-start gen. The active cycle's `finally` calls
108
+ // resolveGate again at the tail and finishes the resolution then.
109
+ if (inProgress || queued || pendingEvents) {
110
+ debug?.(
111
+ "hmr: resolveGate deferred — work in flight (inProgress=%s queued=%s pendingEvents=%s)",
112
+ inProgress,
113
+ queued,
114
+ pendingEvents,
115
+ );
116
+ return;
117
+ }
118
+ gatePending = false;
119
+ debug?.("hmr: discoveryDone resolved");
120
+ gateResolver();
121
+ };
122
+
123
+ const noteRouteEvent = (): void => {
124
+ pendingEvents = true;
125
+ beginGate();
126
+ };
127
+
128
+ const runRefreshCycle = async (work: () => Promise<void>): Promise<void> => {
129
+ if (inProgress) {
130
+ queued = true;
131
+ debug?.("hmr: rediscovery in flight — queued for a follow-up cycle");
132
+ return;
133
+ }
134
+ // Snapshot the current pendingEvents into "we're about to process";
135
+ // events arriving from now on re-set it.
136
+ pendingEvents = false;
137
+ inProgress = true;
138
+ try {
139
+ await work();
140
+ } finally {
141
+ inProgress = false;
142
+ if (queued) {
143
+ queued = false;
144
+ debug?.("hmr: consuming queued rediscovery");
145
+ runRefreshCycle(work).catch((err: unknown) => {
146
+ debug?.(
147
+ "hmr: queued cycle rejected — releasing gate (%s)",
148
+ err instanceof Error ? err.message : String(err),
149
+ );
150
+ // Belt-and-suspenders: even if the queued cycle's own try/catch
151
+ // missed something, ensure workerd doesn't hang.
152
+ resolveGate();
153
+ });
154
+ } else if (pendingEvents) {
155
+ debug?.(
156
+ "hmr: holding gate for pending events (debounce not yet fired)",
157
+ );
158
+ } else {
159
+ resolveGate();
160
+ }
161
+ }
162
+ };
163
+
164
+ return {
165
+ beginGate,
166
+ resolveGate,
167
+ noteRouteEvent,
168
+ runRefreshCycle,
169
+ state: () => ({ gatePending, inProgress, queued, pendingEvents }),
170
+ };
171
+ }