@rangojs/router 0.0.0-experimental.d7eeaa75 → 0.0.0-experimental.dc2bd2b4

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 (253) hide show
  1. package/README.md +120 -25
  2. package/dist/bin/rango.js +147 -57
  3. package/dist/testing/vitest.js +48 -0
  4. package/dist/vite/index.js +2151 -846
  5. package/dist/vite/plugins/cloudflare-protocol-loader-hook.mjs +76 -0
  6. package/package.json +57 -11
  7. package/skills/breadcrumbs/SKILL.md +3 -1
  8. package/skills/bundle-analysis/SKILL.md +159 -0
  9. package/skills/cache-guide/SKILL.md +220 -30
  10. package/skills/caching/SKILL.md +116 -8
  11. package/skills/composability/SKILL.md +27 -2
  12. package/skills/document-cache/SKILL.md +78 -55
  13. package/skills/handler-use/SKILL.md +364 -0
  14. package/skills/hooks/SKILL.md +229 -20
  15. package/skills/host-router/SKILL.md +45 -20
  16. package/skills/i18n/SKILL.md +276 -0
  17. package/skills/intercept/SKILL.md +46 -4
  18. package/skills/layout/SKILL.md +28 -7
  19. package/skills/links/SKILL.md +247 -17
  20. package/skills/loader/SKILL.md +219 -9
  21. package/skills/middleware/SKILL.md +47 -12
  22. package/skills/migrate-nextjs/SKILL.md +562 -0
  23. package/skills/migrate-react-router/SKILL.md +769 -0
  24. package/skills/mime-routes/SKILL.md +27 -0
  25. package/skills/observability/SKILL.md +137 -0
  26. package/skills/parallel/SKILL.md +71 -6
  27. package/skills/prerender/SKILL.md +14 -33
  28. package/skills/rango/SKILL.md +242 -22
  29. package/skills/react-compiler/SKILL.md +168 -0
  30. package/skills/response-routes/SKILL.md +66 -9
  31. package/skills/route/SKILL.md +57 -4
  32. package/skills/router-setup/SKILL.md +3 -3
  33. package/skills/server-actions/SKILL.md +751 -0
  34. package/skills/streams-and-websockets/SKILL.md +283 -0
  35. package/skills/testing/SKILL.md +647 -0
  36. package/skills/typesafety/SKILL.md +319 -27
  37. package/skills/use-cache/SKILL.md +34 -5
  38. package/skills/view-transitions/SKILL.md +294 -0
  39. package/src/__augment-tests__/augment.ts +81 -0
  40. package/src/__augment-tests__/augmented.check.ts +117 -0
  41. package/src/browser/action-coordinator.ts +53 -36
  42. package/src/browser/app-shell.ts +52 -0
  43. package/src/browser/event-controller.ts +86 -70
  44. package/src/browser/history-state.ts +21 -0
  45. package/src/browser/index.ts +3 -3
  46. package/src/browser/navigation-bridge.ts +84 -11
  47. package/src/browser/navigation-client.ts +76 -28
  48. package/src/browser/navigation-store.ts +32 -9
  49. package/src/browser/navigation-transaction.ts +10 -28
  50. package/src/browser/partial-update.ts +64 -26
  51. package/src/browser/prefetch/cache.ts +129 -21
  52. package/src/browser/prefetch/fetch.ts +148 -16
  53. package/src/browser/prefetch/queue.ts +36 -5
  54. package/src/browser/rango-state.ts +53 -13
  55. package/src/browser/react/Link.tsx +30 -2
  56. package/src/browser/react/NavigationProvider.tsx +72 -31
  57. package/src/browser/react/filter-segment-order.ts +51 -7
  58. package/src/browser/react/index.ts +3 -0
  59. package/src/browser/react/location-state-shared.ts +175 -4
  60. package/src/browser/react/location-state.ts +39 -13
  61. package/src/browser/react/use-handle.ts +17 -9
  62. package/src/browser/react/use-navigation.ts +22 -2
  63. package/src/browser/react/use-params.ts +20 -8
  64. package/src/browser/react/use-reverse.ts +106 -0
  65. package/src/browser/react/use-router.ts +22 -2
  66. package/src/browser/react/use-segments.ts +11 -8
  67. package/src/browser/response-adapter.ts +25 -0
  68. package/src/browser/rsc-router.tsx +64 -22
  69. package/src/browser/scroll-restoration.ts +22 -14
  70. package/src/browser/segment-reconciler.ts +36 -14
  71. package/src/browser/segment-structure-assert.ts +2 -2
  72. package/src/browser/server-action-bridge.ts +23 -30
  73. package/src/browser/types.ts +21 -0
  74. package/src/build/collect-fallback-refs.ts +107 -0
  75. package/src/build/generate-manifest.ts +60 -35
  76. package/src/build/generate-route-types.ts +2 -0
  77. package/src/build/index.ts +2 -0
  78. package/src/build/route-trie.ts +52 -25
  79. package/src/build/route-types/codegen.ts +4 -4
  80. package/src/build/route-types/include-resolution.ts +1 -1
  81. package/src/build/route-types/per-module-writer.ts +7 -4
  82. package/src/build/route-types/router-processing.ts +55 -14
  83. package/src/build/route-types/scan-filter.ts +1 -1
  84. package/src/build/route-types/source-scan.ts +118 -0
  85. package/src/build/runtime-discovery.ts +9 -20
  86. package/src/cache/cache-scope.ts +28 -42
  87. package/src/cache/cf/cf-cache-store.ts +54 -13
  88. package/src/client.rsc.tsx +3 -0
  89. package/src/client.tsx +92 -182
  90. package/src/context-var.ts +5 -5
  91. package/src/decode-loader-results.ts +36 -0
  92. package/src/errors.ts +30 -1
  93. package/src/handle.ts +26 -13
  94. package/src/host/index.ts +2 -2
  95. package/src/host/router.ts +129 -57
  96. package/src/host/types.ts +31 -2
  97. package/src/host/utils.ts +1 -1
  98. package/src/href-client.ts +140 -20
  99. package/src/index.rsc.ts +9 -4
  100. package/src/index.ts +53 -15
  101. package/src/loader-store.ts +500 -0
  102. package/src/loader.rsc.ts +2 -5
  103. package/src/loader.ts +3 -10
  104. package/src/missing-id-error.ts +68 -0
  105. package/src/outlet-context.ts +1 -1
  106. package/src/prerender.ts +4 -4
  107. package/src/response-utils.ts +37 -0
  108. package/src/reverse.ts +65 -36
  109. package/src/route-content-wrapper.tsx +6 -28
  110. package/src/route-definition/dsl-helpers.ts +384 -257
  111. package/src/route-definition/helper-factories.ts +29 -139
  112. package/src/route-definition/helpers-types.ts +100 -28
  113. package/src/route-definition/resolve-handler-use.ts +6 -0
  114. package/src/route-definition/use-item-types.ts +32 -0
  115. package/src/route-types.ts +26 -41
  116. package/src/router/basename.ts +14 -0
  117. package/src/router/content-negotiation.ts +15 -2
  118. package/src/router/error-handling.ts +1 -1
  119. package/src/router/handler-context.ts +21 -38
  120. package/src/router/intercept-resolution.ts +4 -18
  121. package/src/router/lazy-includes.ts +8 -8
  122. package/src/router/loader-resolution.ts +19 -2
  123. package/src/router/manifest.ts +22 -13
  124. package/src/router/match-api.ts +4 -3
  125. package/src/router/match-handlers.ts +63 -20
  126. package/src/router/match-middleware/cache-lookup.ts +44 -91
  127. package/src/router/match-middleware/cache-store.ts +3 -2
  128. package/src/router/match-result.ts +53 -32
  129. package/src/router/metrics.ts +1 -1
  130. package/src/router/middleware-types.ts +15 -26
  131. package/src/router/middleware.ts +99 -84
  132. package/src/router/pattern-matching.ts +101 -17
  133. package/src/router/prerender-match.ts +1 -1
  134. package/src/router/preview-match.ts +3 -1
  135. package/src/router/request-classification.ts +4 -28
  136. package/src/router/revalidation.ts +58 -2
  137. package/src/router/router-interfaces.ts +45 -28
  138. package/src/router/router-options.ts +40 -1
  139. package/src/router/router-registry.ts +2 -5
  140. package/src/router/segment-resolution/fresh.ts +27 -6
  141. package/src/router/segment-resolution/revalidation.ts +147 -106
  142. package/src/router/segment-resolution/view-transition-default.ts +36 -0
  143. package/src/router/substitute-pattern-params.ts +56 -0
  144. package/src/router/telemetry.ts +99 -0
  145. package/src/router/trie-matching.ts +18 -13
  146. package/src/router/types.ts +8 -0
  147. package/src/router/url-params.ts +49 -0
  148. package/src/router.ts +38 -23
  149. package/src/rsc/handler-context.ts +2 -2
  150. package/src/rsc/handler.ts +28 -69
  151. package/src/rsc/helpers.ts +91 -43
  152. package/src/rsc/index.ts +1 -1
  153. package/src/rsc/origin-guard.ts +28 -10
  154. package/src/rsc/progressive-enhancement.ts +4 -0
  155. package/src/rsc/response-route-handler.ts +46 -53
  156. package/src/rsc/rsc-rendering.ts +35 -51
  157. package/src/rsc/runtime-warnings.ts +9 -10
  158. package/src/rsc/server-action.ts +17 -37
  159. package/src/rsc/ssr-setup.ts +16 -0
  160. package/src/rsc/types.ts +8 -2
  161. package/src/search-params.ts +4 -4
  162. package/src/segment-content-promise.ts +67 -0
  163. package/src/segment-loader-promise.ts +122 -0
  164. package/src/segment-system.tsx +132 -116
  165. package/src/serialize.ts +243 -0
  166. package/src/server/context.ts +143 -53
  167. package/src/server/cookie-store.ts +28 -4
  168. package/src/server/request-context.ts +20 -42
  169. package/src/ssr/index.tsx +5 -1
  170. package/src/static-handler.ts +1 -1
  171. package/src/testing/cache-status.ts +166 -0
  172. package/src/testing/collect-handle.ts +63 -0
  173. package/src/testing/dispatch.ts +440 -0
  174. package/src/testing/dom.entry.ts +22 -0
  175. package/src/testing/e2e/fixture.ts +154 -0
  176. package/src/testing/e2e/index.ts +149 -0
  177. package/src/testing/e2e/matchers.ts +51 -0
  178. package/src/testing/e2e/page-helpers.ts +272 -0
  179. package/src/testing/e2e/parity.ts +306 -0
  180. package/src/testing/e2e/server.ts +183 -0
  181. package/src/testing/flight-matchers.ts +104 -0
  182. package/src/testing/flight-runtime.d.ts +21 -0
  183. package/src/testing/flight.entry.ts +22 -0
  184. package/src/testing/flight.ts +182 -0
  185. package/src/testing/generated-routes.ts +223 -0
  186. package/src/testing/index.ts +105 -0
  187. package/src/testing/internal/context.ts +193 -0
  188. package/src/testing/render-route.tsx +536 -0
  189. package/src/testing/run-loader.ts +296 -0
  190. package/src/testing/run-middleware.ts +170 -0
  191. package/src/testing/vitest-stubs/cloudflare-email.ts +9 -0
  192. package/src/testing/vitest-stubs/cloudflare-workers.ts +21 -0
  193. package/src/testing/vitest-stubs/plugin-rsc.ts +16 -0
  194. package/src/testing/vitest-stubs/version.ts +5 -0
  195. package/src/testing/vitest.ts +183 -0
  196. package/src/types/global-namespace.ts +39 -26
  197. package/src/types/handler-context.ts +68 -50
  198. package/src/types/index.ts +1 -0
  199. package/src/types/loader-types.ts +5 -6
  200. package/src/types/request-scope.ts +126 -0
  201. package/src/types/route-entry.ts +11 -0
  202. package/src/types/segments.ts +35 -2
  203. package/src/urls/include-helper.ts +34 -67
  204. package/src/urls/index.ts +0 -3
  205. package/src/urls/path-helper-types.ts +41 -7
  206. package/src/urls/path-helper.ts +17 -52
  207. package/src/urls/pattern-types.ts +36 -19
  208. package/src/urls/response-types.ts +22 -29
  209. package/src/urls/type-extraction.ts +26 -116
  210. package/src/urls/urls-function.ts +1 -5
  211. package/src/use-loader.tsx +413 -42
  212. package/src/vite/debug.ts +185 -0
  213. package/src/vite/discovery/bundle-postprocess.ts +6 -6
  214. package/src/vite/discovery/discover-routers.ts +101 -51
  215. package/src/vite/discovery/discovery-errors.ts +194 -0
  216. package/src/vite/discovery/gate-state.ts +171 -0
  217. package/src/vite/discovery/prerender-collection.ts +67 -26
  218. package/src/vite/discovery/route-types-writer.ts +40 -84
  219. package/src/vite/discovery/self-gen-tracking.ts +27 -1
  220. package/src/vite/discovery/state.ts +33 -0
  221. package/src/vite/discovery/virtual-module-codegen.ts +13 -23
  222. package/src/vite/index.ts +2 -0
  223. package/src/vite/plugin-types.ts +67 -0
  224. package/src/vite/plugins/cjs-to-esm.ts +8 -7
  225. package/src/vite/plugins/client-ref-dedup.ts +16 -0
  226. package/src/vite/plugins/client-ref-hashing.ts +28 -5
  227. package/src/vite/plugins/cloudflare-protocol-loader-hook.d.mts +23 -0
  228. package/src/vite/plugins/cloudflare-protocol-loader-hook.mjs +76 -0
  229. package/src/vite/plugins/cloudflare-protocol-stub.ts +214 -0
  230. package/src/vite/plugins/expose-action-id.ts +54 -30
  231. package/src/vite/plugins/expose-id-utils.ts +12 -8
  232. package/src/vite/plugins/expose-ids/export-analysis.ts +100 -20
  233. package/src/vite/plugins/expose-ids/handler-transform.ts +8 -61
  234. package/src/vite/plugins/expose-ids/loader-transform.ts +3 -5
  235. package/src/vite/plugins/expose-ids/router-transform.ts +20 -3
  236. package/src/vite/plugins/expose-internal-ids.ts +496 -486
  237. package/src/vite/plugins/performance-tracks.ts +29 -25
  238. package/src/vite/plugins/use-cache-transform.ts +65 -50
  239. package/src/vite/plugins/version-injector.ts +39 -23
  240. package/src/vite/plugins/version-plugin.ts +59 -2
  241. package/src/vite/plugins/virtual-entries.ts +2 -2
  242. package/src/vite/rango.ts +116 -29
  243. package/src/vite/router-discovery.ts +750 -100
  244. package/src/vite/utils/ast-handler-extract.ts +15 -15
  245. package/src/vite/utils/banner.ts +1 -1
  246. package/src/vite/utils/bundle-analysis.ts +4 -2
  247. package/src/vite/utils/client-chunks.ts +190 -0
  248. package/src/vite/utils/forward-user-plugins.ts +193 -0
  249. package/src/vite/utils/manifest-utils.ts +21 -5
  250. package/src/vite/utils/package-resolution.ts +41 -1
  251. package/src/vite/utils/prerender-utils.ts +21 -6
  252. package/src/vite/utils/shared-utils.ts +107 -26
  253. package/src/browser/action-response-classifier.ts +0 -99
@@ -0,0 +1,500 @@
1
+ /**
2
+ * LoaderStore — shared subscription model for `useLoader` / `useFetchLoader`.
3
+ *
4
+ * Each bucket key gets one entry that holds the latest committed snapshot plus a
5
+ * set of listeners. Snapshots are frozen and replaced atomically on mutation, so
6
+ * subscribers can compare snapshot identity and avoid unnecessary updates
7
+ * between real changes.
8
+ *
9
+ * The bucket key is `loader.$$id` by default, or `loader.$$id + key` when the
10
+ * hook is given an explicit client refresh `key`. Multiple buckets belonging to
11
+ * the same loader form a family (indexed by `loader.$$id`) so a navigation /
12
+ * route-context reset can clear them all at once via `clearFamily`.
13
+ *
14
+ * Mutations that come in for an old request id (e.g. a slow response that
15
+ * resolves after a newer load() was issued, or after a navigation cleared the
16
+ * entry) are silently dropped. `reserveRequestId` is the only way to claim the
17
+ * "latest" slot; `clear` bumps it too so pre-navigation in-flight loads cannot
18
+ * commit into the new route's context.
19
+ *
20
+ * Bucket lifecycle differs by registration:
21
+ * - Sticky buckets (a route-registered reader subscribed at least once) keep
22
+ * their entry after the last subscriber leaves so an in-flight load() can
23
+ * still commit on remount; they reset on navigation via `clearFamily`.
24
+ * - Ephemeral buckets (only ever subscribed by readers with no route context,
25
+ * i.e. keyed `useFetchLoader` of an unregistered loader) have no
26
+ * route-context reset trigger, so they are reference-counted: dropped once
27
+ * the last subscriber unsubscribes. The drop is deferred to a microtask and
28
+ * cancelled on resubscribe so a StrictMode / transition remount does not
29
+ * reclaim a bucket that is about to be reused, and is held until any
30
+ * in-flight load settles.
31
+ *
32
+ * The store is intentionally module-level: each browser tab is its own JS
33
+ * realm, so there is no cross-request pollution. Server renders never mutate
34
+ * the store — the hook falls back to `OutletContext.loaderData`.
35
+ */
36
+
37
+ export interface LoaderEntry<T = unknown> {
38
+ readonly value: T | undefined;
39
+ /**
40
+ * Whether a load has committed a value to this bucket. Distinguishes a
41
+ * committed `null`/`undefined` result from "never loaded", so a loader that
42
+ * resolves to a falsy value is not mistaken for an empty bucket and is not
43
+ * overridden by the server-seeded context value.
44
+ */
45
+ readonly hasValue: boolean;
46
+ readonly error: Error | null;
47
+ readonly isLoading: boolean;
48
+ /** Identifies the request that produced this snapshot. 0 means "no request". */
49
+ readonly requestId: number;
50
+ }
51
+
52
+ const EMPTY_SNAPSHOT: LoaderEntry = Object.freeze({
53
+ value: undefined,
54
+ hasValue: false,
55
+ error: null,
56
+ isLoading: false,
57
+ requestId: 0,
58
+ });
59
+
60
+ /**
61
+ * Options for `subscribe`.
62
+ */
63
+ export interface SubscribeOptions {
64
+ /**
65
+ * Family id (`loader.$$id`) this bucket belongs to. `clearFamily` uses it to
66
+ * reach every keyed bucket of the same loader. Defaults to the bucket key.
67
+ */
68
+ loaderId?: string;
69
+ /**
70
+ * When true, this subscription is from a reader with no route context (keyed
71
+ * `useFetchLoader` of an unregistered loader). Such buckets have no
72
+ * route-context reset trigger and are reference-counted instead. A bucket
73
+ * becomes sticky for the rest of its life as soon as any non-ephemeral
74
+ * subscriber attaches, and from then on resets via `clearFamily`.
75
+ */
76
+ ephemeral?: boolean;
77
+ /**
78
+ * Cross-loader refresh group name(s). Tags this bucket so `refreshGroups(name)`
79
+ * can refresh it alongside buckets of other loaders. A bucket may be tagged
80
+ * with several group names at once (pass an array); it is then refreshed when
81
+ * ANY of its groups is refreshed. Group membership follows subscriber presence:
82
+ * a bucket leaves a group when that group's last subscriber unsubscribes.
83
+ */
84
+ group?: string | string[];
85
+ /**
86
+ * Plain-GET refresh thunk used by `refreshGroups`. Provided alongside `group`.
87
+ * Refreshes this bucket in place (no params/body) and rejects on failure.
88
+ */
89
+ refetch?: () => Promise<void>;
90
+ }
91
+
92
+ interface InternalEntry {
93
+ snapshot: LoaderEntry;
94
+ listeners: Set<() => void>;
95
+ /** Monotonically increasing. Bumped by reserveRequestId() and clear(). */
96
+ latestRequestId: number;
97
+ /** Family id (loader.$$id) this bucket belongs to. */
98
+ loaderId: string;
99
+ /**
100
+ * True once any non-ephemeral subscriber has attached. Sticky buckets are
101
+ * never reference-count-dropped; they reset via clearFamily().
102
+ */
103
+ sticky: boolean;
104
+ /** A deferred refcount-drop microtask is scheduled and not yet cancelled. */
105
+ pendingClear: boolean;
106
+ /**
107
+ * The last subscriber left while a load() was in flight. Drop the bucket once
108
+ * that request settles, if it is still subscriberless.
109
+ */
110
+ clearWhenSettled: boolean;
111
+ /**
112
+ * Cross-loader refresh groups this bucket belongs to, mapped to the number of
113
+ * current subscribers that requested each group. A bucket can be in several
114
+ * groups at once (one read tagged with multiple names, or different subscribers
115
+ * tagging the same shared bucket with different names); refcounting keeps
116
+ * membership independent of subscribe/unsubscribe order.
117
+ */
118
+ groups: Map<string, number>;
119
+ /** Plain-GET refresh thunk for `refreshGroups`, set while in any group. */
120
+ refetch: (() => Promise<void>) | undefined;
121
+ }
122
+
123
+ /**
124
+ * Normalize a group tag option (`undefined | string | string[]`) to a deduped
125
+ * list of names. Deduping keeps a single subscriber from being counted more than
126
+ * once in one group when the caller passes a repeated name.
127
+ */
128
+ function normalizeGroups(group: string | string[] | undefined): string[] {
129
+ if (group === undefined) return [];
130
+ if (typeof group === "string") return [group];
131
+ return [...new Set(group)];
132
+ }
133
+
134
+ export class LoaderStore {
135
+ private readonly entries = new Map<string, InternalEntry>();
136
+ /** loader.$$id -> set of bucket keys, so clearFamily() can reach every bucket. */
137
+ private readonly families = new Map<string, Set<string>>();
138
+ /** refresh group name -> set of bucket keys, for refreshGroups(). */
139
+ private readonly groups = new Map<string, Set<string>>();
140
+
141
+ private getOrCreate(bucketKey: string): InternalEntry {
142
+ let e = this.entries.get(bucketKey);
143
+ if (!e) {
144
+ e = {
145
+ snapshot: EMPTY_SNAPSHOT,
146
+ listeners: new Set(),
147
+ latestRequestId: 0,
148
+ loaderId: bucketKey,
149
+ sticky: false,
150
+ pendingClear: false,
151
+ clearWhenSettled: false,
152
+ groups: new Map(),
153
+ refetch: undefined,
154
+ };
155
+ this.entries.set(bucketKey, e);
156
+ }
157
+ return e;
158
+ }
159
+
160
+ private registerFamily(loaderId: string, bucketKey: string): void {
161
+ let fam = this.families.get(loaderId);
162
+ if (!fam) {
163
+ fam = new Set();
164
+ this.families.set(loaderId, fam);
165
+ }
166
+ fam.add(bucketKey);
167
+ }
168
+
169
+ /**
170
+ * Subscribe to entry changes for `bucketKey`.
171
+ * Returns an unsubscribe function. A sticky bucket's entry is kept around even
172
+ * after the last subscriber leaves so that an in-flight `load()` can still
173
+ * commit if the consumer remounts. An ephemeral bucket is dropped once its
174
+ * last subscriber leaves (deferred, see maybeScheduleRefcountClear).
175
+ */
176
+ subscribe(
177
+ bucketKey: string,
178
+ cb: () => void,
179
+ options?: SubscribeOptions,
180
+ ): () => void {
181
+ const e = this.getOrCreate(bucketKey);
182
+ const loaderId = options?.loaderId ?? bucketKey;
183
+ e.loaderId = loaderId;
184
+ this.registerFamily(loaderId, bucketKey);
185
+ if (options?.ephemeral !== true) e.sticky = true;
186
+ // Normalize the group tag(s) to a deduped list so one subscriber is counted
187
+ // once per distinct group, and subscribe/unsubscribe stay symmetric (the
188
+ // same list drives both addToGroup and releaseGroup).
189
+ const groups = normalizeGroups(options?.group);
190
+ for (const group of groups) {
191
+ this.addToGroup(group, bucketKey, e, options?.refetch);
192
+ }
193
+ // A fresh subscriber means the bucket is wanted again: cancel any pending
194
+ // refcount-drop and the settle-then-drop intent.
195
+ e.pendingClear = false;
196
+ e.clearWhenSettled = false;
197
+ e.listeners.add(cb);
198
+ return () => {
199
+ e.listeners.delete(cb);
200
+ // Group membership is refcounted per subscriber so refreshGroups() never
201
+ // fetches for an unmounted reader, and a bucket shared by subscribers in
202
+ // different groups stays in each group until ALL of that group's
203
+ // subscribers have left (order-independent).
204
+ for (const group of groups) this.releaseGroup(group, bucketKey, e);
205
+ this.maybeScheduleRefcountClear(bucketKey, e);
206
+ };
207
+ }
208
+
209
+ private addToGroup(
210
+ group: string,
211
+ bucketKey: string,
212
+ e: InternalEntry,
213
+ refetch: (() => Promise<void>) | undefined,
214
+ ): void {
215
+ e.groups.set(group, (e.groups.get(group) ?? 0) + 1);
216
+ // One thunk per bucket — every subscriber of a bucket provides an
217
+ // equivalent plain-GET refresh, so keeping the latest is fine.
218
+ if (refetch) e.refetch = refetch;
219
+ let members = this.groups.get(group);
220
+ if (!members) {
221
+ members = new Set();
222
+ this.groups.set(group, members);
223
+ }
224
+ members.add(bucketKey);
225
+ }
226
+
227
+ private releaseGroup(
228
+ group: string,
229
+ bucketKey: string,
230
+ e: InternalEntry,
231
+ ): void {
232
+ const next = (e.groups.get(group) ?? 0) - 1;
233
+ if (next > 0) {
234
+ e.groups.set(group, next);
235
+ return;
236
+ }
237
+ e.groups.delete(group);
238
+ const members = this.groups.get(group);
239
+ if (members) {
240
+ members.delete(bucketKey);
241
+ if (members.size === 0) this.groups.delete(group);
242
+ }
243
+ }
244
+
245
+ /** Remove a bucket from every group it belongs to (used when it is dropped). */
246
+ private removeFromAllGroups(bucketKey: string, e: InternalEntry): void {
247
+ for (const group of e.groups.keys()) {
248
+ const members = this.groups.get(group);
249
+ if (members) {
250
+ members.delete(bucketKey);
251
+ if (members.size === 0) this.groups.delete(group);
252
+ }
253
+ }
254
+ e.groups.clear();
255
+ }
256
+
257
+ /**
258
+ * Refresh every currently-mounted bucket tagged with ANY of the given group
259
+ * names, with a plain GET (no params/body). Accepts a single name or an array
260
+ * of names. A bucket that belongs to more than one of the named groups is
261
+ * refreshed exactly once (members are unioned and deduped by bucket key), as
262
+ * are multiple reads of one bucket. Resolves when all refreshes settle; rejects
263
+ * with an `AggregateError` of the failures if any member fails — each failing
264
+ * member also records its error on its own snapshot.
265
+ */
266
+ async refreshGroups(groups: string | string[]): Promise<void> {
267
+ const names = typeof groups === "string" ? [groups] : groups;
268
+ // Union the member buckets across every named group, deduped by key, so a
269
+ // bucket tagged into two of the requested groups is fetched a single time.
270
+ const buckets = new Set<string>();
271
+ for (const name of names) {
272
+ const members = this.groups.get(name);
273
+ if (!members) continue;
274
+ for (const bucketKey of members) buckets.add(bucketKey);
275
+ }
276
+ if (buckets.size === 0) return;
277
+ const thunks: Array<() => Promise<void>> = [];
278
+ for (const bucketKey of buckets) {
279
+ const e = this.entries.get(bucketKey);
280
+ if (!e || e.listeners.size === 0 || !e.refetch) continue;
281
+ thunks.push(e.refetch);
282
+ }
283
+ if (thunks.length === 0) return;
284
+ const results = await Promise.allSettled(thunks.map((t) => t()));
285
+ const reasons = results
286
+ .filter((r): r is PromiseRejectedResult => r.status === "rejected")
287
+ .map((r) => r.reason);
288
+ if (reasons.length > 0) {
289
+ const label = names.map((n) => `"${n}"`).join(", ");
290
+ throw new AggregateError(
291
+ reasons,
292
+ `refreshGroups(${label}) had ${reasons.length} failure(s)`,
293
+ );
294
+ }
295
+ }
296
+
297
+ /**
298
+ * Schedule a deferred drop for an ad-hoc (never-sticky) bucket whose last
299
+ * subscriber just left. Deferred to a microtask so a StrictMode / transition
300
+ * remount that resubscribes in the same tick cancels it.
301
+ */
302
+ private maybeScheduleRefcountClear(
303
+ bucketKey: string,
304
+ e: InternalEntry,
305
+ ): void {
306
+ if (e.listeners.size > 0) return;
307
+ // Sticky buckets persist for remount; they reset via clearFamily().
308
+ if (e.sticky) return;
309
+ if (e.pendingClear) return;
310
+ e.pendingClear = true;
311
+ queueMicrotask(() => {
312
+ if (!e.pendingClear) return; // cancelled by a resubscribe
313
+ e.pendingClear = false;
314
+ if (e.listeners.size > 0) return; // resubscribed before the microtask ran
315
+ if (e.snapshot.isLoading) {
316
+ // Don't drop mid-flight; let the request commit, then drop.
317
+ e.clearWhenSettled = true;
318
+ return;
319
+ }
320
+ this.dropBucket(bucketKey);
321
+ });
322
+ }
323
+
324
+ /** Remove a bucket entry entirely and prune it from its family/group indexes. */
325
+ private dropBucket(bucketKey: string): void {
326
+ const e = this.entries.get(bucketKey);
327
+ if (!e) return;
328
+ this.removeFromAllGroups(bucketKey, e);
329
+ this.entries.delete(bucketKey);
330
+ const fam = this.families.get(e.loaderId);
331
+ if (fam) {
332
+ fam.delete(bucketKey);
333
+ if (fam.size === 0) this.families.delete(e.loaderId);
334
+ }
335
+ }
336
+
337
+ /** Drop an ephemeral bucket that settled with no subscribers left. */
338
+ private dropIfSettled(bucketKey: string, e: InternalEntry): void {
339
+ if (e.clearWhenSettled && e.listeners.size === 0) {
340
+ e.clearWhenSettled = false;
341
+ this.dropBucket(bucketKey);
342
+ }
343
+ }
344
+
345
+ /**
346
+ * Returns the current snapshot for `bucketKey`. Stable reference between
347
+ * mutations — subscribers rely on this to avoid spurious re-renders.
348
+ * Returns `EMPTY_SNAPSHOT` (a singleton) when the entry has never been
349
+ * mutated or has been cleared.
350
+ */
351
+ getSnapshot(bucketKey: string): LoaderEntry {
352
+ return this.entries.get(bucketKey)?.snapshot ?? EMPTY_SNAPSHOT;
353
+ }
354
+
355
+ /**
356
+ * Reserve a fresh request id for an upcoming `load()` call. The returned id
357
+ * is the new "latest"; any older in-flight requests will fail their gating
358
+ * check on `finishData` / `finishError` / `finishLoading` and be dropped.
359
+ *
360
+ * Callers should follow with `beginRequest(id, requestId)` to flip the
361
+ * loading flag on AND clear any leftover error from a previous attempt
362
+ * — the latter matters for `throwOnError: false` consumers, which would
363
+ * otherwise keep showing the stale error throughout the retry.
364
+ */
365
+ reserveRequestId(bucketKey: string): number {
366
+ const e = this.getOrCreate(bucketKey);
367
+ e.latestRequestId++;
368
+ return e.latestRequestId;
369
+ }
370
+
371
+ /**
372
+ * Mark the request as in-flight: `isLoading = true`, `error = null`.
373
+ * Combines the two operations so a retry doesn't render the previous
374
+ * error during the new request. Gated on `requestId === latestRequestId`
375
+ * for symmetry with the other mutators.
376
+ */
377
+ beginRequest(bucketKey: string, requestId: number): void {
378
+ const e = this.entries.get(bucketKey);
379
+ if (!e || requestId !== e.latestRequestId) return;
380
+ if (e.snapshot.isLoading && e.snapshot.error === null) return;
381
+ e.snapshot = Object.freeze({
382
+ value: e.snapshot.value,
383
+ hasValue: e.snapshot.hasValue,
384
+ error: null,
385
+ isLoading: true,
386
+ requestId,
387
+ });
388
+ this.notify(e);
389
+ }
390
+
391
+ /**
392
+ * Commit a successful result. No-op if `requestId` is not the latest
393
+ * (a newer `load()` was issued or `clear()` ran). Clearing `error` is
394
+ * intentional: a successful refetch should hide the previous failure.
395
+ */
396
+ finishData<T>(bucketKey: string, requestId: number, value: T): void {
397
+ const e = this.entries.get(bucketKey);
398
+ if (!e || requestId !== e.latestRequestId) return;
399
+ e.snapshot = Object.freeze({
400
+ value,
401
+ hasValue: true,
402
+ error: null,
403
+ isLoading: false,
404
+ requestId,
405
+ });
406
+ this.notify(e);
407
+ this.dropIfSettled(bucketKey, e);
408
+ }
409
+
410
+ /**
411
+ * Commit an error. Preserves the last good `value` so consumers can keep
412
+ * showing previous data while displaying the error if they choose. No-op
413
+ * if `requestId` is not the latest.
414
+ */
415
+ finishError(bucketKey: string, requestId: number, error: Error): void {
416
+ const e = this.entries.get(bucketKey);
417
+ if (!e || requestId !== e.latestRequestId) return;
418
+ e.snapshot = Object.freeze({
419
+ value: e.snapshot.value,
420
+ hasValue: e.snapshot.hasValue,
421
+ error,
422
+ isLoading: false,
423
+ requestId,
424
+ });
425
+ this.notify(e);
426
+ this.dropIfSettled(bucketKey, e);
427
+ }
428
+
429
+ /**
430
+ * Update loading flag. Gated on `requestId` to fix the race where an old
431
+ * load() finishes after a new one started — its `setLoading(false)` would
432
+ * otherwise hide the new request's spinner.
433
+ */
434
+ setLoading(bucketKey: string, requestId: number, isLoading: boolean): void {
435
+ const e = this.entries.get(bucketKey);
436
+ if (!e || requestId !== e.latestRequestId) return;
437
+ if (e.snapshot.isLoading === isLoading) return;
438
+ e.snapshot = Object.freeze({
439
+ ...e.snapshot,
440
+ isLoading,
441
+ });
442
+ this.notify(e);
443
+ }
444
+
445
+ /**
446
+ * Reset a single bucket entry. Bumps `latestRequestId` so any in-flight
447
+ * `load()` whose promise is still pending will fail its gate when it resolves
448
+ * and be dropped — prevents pre-navigation loads from clobbering the new
449
+ * route's context. The entry itself is kept (sticky-bucket semantics).
450
+ */
451
+ clear(bucketKey: string): void {
452
+ const e = this.entries.get(bucketKey);
453
+ if (!e) return;
454
+ e.latestRequestId++;
455
+ if (e.snapshot === EMPTY_SNAPSHOT) return;
456
+ e.snapshot = EMPTY_SNAPSHOT;
457
+ this.notify(e);
458
+ }
459
+
460
+ /**
461
+ * Reset every sticky bucket belonging to `loaderId`. Called on navigation /
462
+ * route-context change: all route-registered reads of the loader (keyed or
463
+ * not) drop back to seeding from fresh `loaderData`. Ephemeral buckets are
464
+ * intentionally left alone — they are governed by subscriber refcount, so a
465
+ * persistent keyed reader outside the outlet keeps its value across a
466
+ * navigation rather than blanking out.
467
+ */
468
+ clearFamily(loaderId: string): void {
469
+ const fam = this.families.get(loaderId);
470
+ if (!fam) return;
471
+ for (const bucketKey of fam) {
472
+ const e = this.entries.get(bucketKey);
473
+ if (!e || !e.sticky) continue;
474
+ this.clear(bucketKey);
475
+ }
476
+ }
477
+
478
+ private notify(e: InternalEntry): void {
479
+ for (const cb of e.listeners) cb();
480
+ }
481
+
482
+ /**
483
+ * Test-only escape hatch. Drops every entry. Production code should never
484
+ * call this; the store is process-scoped and lives for the tab's lifetime.
485
+ * @internal
486
+ */
487
+ reset(): void {
488
+ this.entries.clear();
489
+ this.families.clear();
490
+ this.groups.clear();
491
+ }
492
+ }
493
+
494
+ /**
495
+ * Module-level singleton. Each browser tab gets its own; SSR never mutates it.
496
+ * The hook falls through to `OutletContext.loaderData` during the server render.
497
+ */
498
+ export const loaderStore: LoaderStore = new LoaderStore();
499
+
500
+ export const EMPTY_LOADER_SNAPSHOT: LoaderEntry = EMPTY_SNAPSHOT;
package/src/loader.rsc.ts CHANGED
@@ -21,6 +21,7 @@ import {
21
21
  registerFetchableLoader,
22
22
  getFetchableLoader,
23
23
  } from "./server/fetchable-loader-store.js";
24
+ import { missingInjectedIdError } from "./missing-id-error.js";
24
25
 
25
26
  export { getFetchableLoader };
26
27
 
@@ -53,11 +54,7 @@ export function createLoader<T>(
53
54
  const loaderId = __injectedId || "";
54
55
 
55
56
  if (!loaderId && process.env.NODE_ENV === "development") {
56
- throw new Error(
57
- "[rsc-router] Loader is missing $$id. " +
58
- "Make sure the exposeInternalIds Vite plugin is enabled and " +
59
- "the loader is exported with: export const MyLoader = createLoader(...)",
60
- );
57
+ throw missingInjectedIdError("Loader", "createLoader");
61
58
  }
62
59
 
63
60
  // If not fetchable, store fn in registry (for SSR ctx.use() resolution)
package/src/loader.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * rsc-router/loader (client version)
2
+ * @rangojs/router/loader (client version)
3
3
  *
4
4
  * Client-only stub for createLoader. Returns a minimal loader definition
5
5
  * ({ __brand, $$id }) that can be passed to hooks like useLoader.
@@ -18,6 +18,7 @@ import type {
18
18
  LoaderDefinition,
19
19
  LoaderFn,
20
20
  } from "./types.js";
21
+ import { missingInjectedIdError } from "./missing-id-error.js";
21
22
 
22
23
  // Overload 1: With function only (not fetchable)
23
24
  export function createLoader<T>(
@@ -38,10 +39,6 @@ export function createLoader<T>(
38
39
 
39
40
  // Implementation - client stub that just returns the loader definition
40
41
  // The $$id parameter is injected by Vite plugin, not user-provided
41
- //
42
- // NOTE: For export-only loader files, the Vite plugin replaces the entire
43
- // file with object literals (bypassing this function). This function only
44
- // runs when loaders are in mixed files (not export-only).
45
42
  export function createLoader<T>(
46
43
  _fn: LoaderFn<T, Record<string, string | undefined>, any>,
47
44
  _fetchable?: true | FetchableLoaderOptions,
@@ -50,11 +47,7 @@ export function createLoader<T>(
50
47
  const loaderId = __injectedId || "";
51
48
 
52
49
  if (!loaderId && process.env.NODE_ENV === "development") {
53
- throw new Error(
54
- "[rsc-router] Loader is missing $$id. " +
55
- "Make sure the exposeInternalIds Vite plugin is enabled and " +
56
- "the loader is exported with: export const MyLoader = createLoader(...)",
57
- );
50
+ throw missingInjectedIdError("Loader", "createLoader");
58
51
  }
59
52
 
60
53
  return {
@@ -0,0 +1,68 @@
1
+ // Builds the error thrown when a create*() call (createLoader / createHandle)
2
+ // reaches runtime without an injected $$id. The exposeInternalIds Vite transform
3
+ // injects $$id only for an EXPORTED const declaration, so a non-exported const,
4
+ // an `export let/var`, or an inline create*() call gets none. Previously this
5
+ // failed with a terse message and no source location; this helper adds the
6
+ // offending call site (best-effort, from the stack) and actionable guidance.
7
+ //
8
+ // The "<Kind> is missing $$id" prefix is preserved so existing tests and any
9
+ // log scrapers keep matching. Dev-only: the call sites guard on
10
+ // process.env.NODE_ENV === "development", so production builds fold the branch
11
+ // away and tree-shake this module out.
12
+
13
+ // create*() implementation files to skip when locating the user's call site.
14
+ const SELF_FILES = new Set([
15
+ "missing-id-error",
16
+ "loader",
17
+ "loader.rsc",
18
+ "handle",
19
+ ]);
20
+
21
+ /**
22
+ * Best-effort "path:line:column" of the user's create*() call, parsed from the
23
+ * current stack. Skips @rangojs/router internals and node_modules. Returns
24
+ * undefined if nothing usable is found (stack parsing is inherently fragile).
25
+ */
26
+ function findUserCallSite(): string | undefined {
27
+ try {
28
+ const stack = new Error().stack;
29
+ if (!stack) return undefined;
30
+ for (const frame of stack.split("\n").slice(1)) {
31
+ const m = frame.match(
32
+ /(?:\(|@|\s)(?:file:\/\/)?((?:\/|[A-Za-z]:[\\/])[^()\s]+?\.(?:ts|tsx|js|jsx|mts|cts)):(\d+):(\d+)\)?/,
33
+ );
34
+ if (!m) continue;
35
+ const path = m[1];
36
+ if (path.includes("node_modules") || path.includes("@rangojs/router")) {
37
+ continue;
38
+ }
39
+ const base = path
40
+ .split(/[\\/]/)
41
+ .pop()!
42
+ .replace(/\.(?:ts|tsx|js|jsx|mts|cts)$/, "");
43
+ if (SELF_FILES.has(base)) continue;
44
+ return `${path}:${m[2]}:${m[3]}`;
45
+ }
46
+ } catch {
47
+ // best-effort only
48
+ }
49
+ return undefined;
50
+ }
51
+
52
+ export function missingInjectedIdError(
53
+ kind: "Loader" | "Handle",
54
+ fnName: "createLoader" | "createHandle",
55
+ ): Error {
56
+ const site = findUserCallSite();
57
+ const at = site ? ` (created at ${site})` : "";
58
+ return new Error(
59
+ `[rango] ${kind} is missing $$id${at}.\n` +
60
+ `The @rangojs/router:expose-internal-ids Vite transform injects ${fnName}()'s ` +
61
+ `stable $$id from an EXPORTED const declaration only:\n` +
62
+ ` export const X = ${fnName}(...)\n` +
63
+ ` const X = ${fnName}(...); export { X }\n` +
64
+ `A non-exported const, an \`export let/var\`, or an inline ${fnName}(...) ` +
65
+ `call gets no $$id — export it as \`export const\`. (A matching ` +
66
+ `"Unsupported ${fnName} shape" warning names the exact file:line.)`,
67
+ );
68
+ }
@@ -1,4 +1,4 @@
1
- import { Context, createContext, type ReactNode } from "react";
1
+ import { type Context, createContext, type ReactNode } from "react";
2
2
  import type { ResolvedSegment } from "./types";
3
3
 
4
4
  export interface OutletContextValue {
package/src/prerender.ts CHANGED
@@ -69,9 +69,9 @@ type BuildReverseFunction = [DefaultReverseRouteMap] extends [
69
69
  * Default route map for Prerender named route resolution.
70
70
  * Uses GeneratedRouteMap (from gen file) to avoid circular dependencies.
71
71
  */
72
- type DefaultPrerenderRouteMap = keyof RSCRouter.GeneratedRouteMap extends never
72
+ type DefaultPrerenderRouteMap = keyof Rango.GeneratedRouteMap extends never
73
73
  ? {}
74
- : RSCRouter.GeneratedRouteMap;
74
+ : Rango.GeneratedRouteMap;
75
75
 
76
76
  /** Extract params from a route map entry (string pattern or { path } object). */
77
77
  type ExtractParamsFromEntry<TEntry> = TEntry extends string
@@ -378,7 +378,7 @@ export function Prerender<TParams extends Record<string, any>>(
378
378
 
379
379
  if (!id) {
380
380
  throw new Error(
381
- "[rsc-router] Prerender: missing $$id. " +
381
+ "[rango] Prerender: missing $$id. " +
382
382
  "Ensure the exposeInternalIds Vite plugin is configured.",
383
383
  );
384
384
  }
@@ -499,7 +499,7 @@ export function Passthrough<
499
499
  ): PassthroughHandlerDefinition<TParams, TEnv> {
500
500
  if (!isPrerenderHandler(prerenderDef)) {
501
501
  throw new Error(
502
- "[rsc-router] Passthrough: first argument must be a Prerender() definition.",
502
+ "[rango] Passthrough: first argument must be a Prerender() definition.",
503
503
  );
504
504
  }
505
505
  return {