@rangojs/router 0.0.0-experimental.19 → 0.0.0-experimental.1c0bdfad

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 (406) hide show
  1. package/AGENTS.md +17 -0
  2. package/README.md +291 -61
  3. package/dist/bin/rango.js +544 -143
  4. package/dist/testing/vitest.js +82 -0
  5. package/dist/vite/index.js +3744 -1329
  6. package/dist/vite/plugins/cloudflare-protocol-loader-hook.mjs +76 -0
  7. package/package.json +67 -13
  8. package/skills/api-client/SKILL.md +211 -0
  9. package/skills/breadcrumbs/SKILL.md +312 -0
  10. package/skills/bundle-analysis/SKILL.md +159 -0
  11. package/skills/cache-guide/SKILL.md +247 -23
  12. package/skills/caching/SKILL.md +322 -19
  13. package/skills/composability/SKILL.md +27 -2
  14. package/skills/css/SKILL.md +76 -0
  15. package/skills/debug-manifest/SKILL.md +4 -2
  16. package/skills/document-cache/SKILL.md +78 -55
  17. package/skills/handler-use/SKILL.md +364 -0
  18. package/skills/hooks/SKILL.md +282 -60
  19. package/skills/host-router/SKILL.md +278 -0
  20. package/skills/i18n/SKILL.md +276 -0
  21. package/skills/intercept/SKILL.md +50 -6
  22. package/skills/layout/SKILL.md +35 -9
  23. package/skills/links/SKILL.md +249 -17
  24. package/skills/loader/SKILL.md +297 -31
  25. package/skills/middleware/SKILL.md +52 -13
  26. package/skills/migrate-nextjs/SKILL.md +584 -0
  27. package/skills/migrate-react-router/SKILL.md +771 -0
  28. package/skills/mime-routes/SKILL.md +28 -1
  29. package/skills/observability/SKILL.md +172 -0
  30. package/skills/parallel/SKILL.md +203 -7
  31. package/skills/prerender/SKILL.md +155 -111
  32. package/skills/rango/SKILL.md +251 -23
  33. package/skills/react-compiler/SKILL.md +168 -0
  34. package/skills/response-routes/SKILL.md +123 -48
  35. package/skills/route/SKILL.md +104 -9
  36. package/skills/router-setup/SKILL.md +124 -11
  37. package/skills/scripts/SKILL.md +179 -0
  38. package/skills/server-actions/SKILL.md +775 -0
  39. package/skills/streams-and-websockets/SKILL.md +283 -0
  40. package/skills/tailwind/SKILL.md +27 -3
  41. package/skills/testing/SKILL.md +125 -222
  42. package/skills/testing/bindings.md +103 -0
  43. package/skills/testing/cache-prerender.md +127 -0
  44. package/skills/testing/client-components.md +124 -0
  45. package/skills/testing/e2e-parity.md +125 -0
  46. package/skills/testing/flight.md +91 -0
  47. package/skills/testing/handles.md +129 -0
  48. package/skills/testing/loader.md +128 -0
  49. package/skills/testing/middleware.md +99 -0
  50. package/skills/testing/render-handler.md +121 -0
  51. package/skills/testing/response-routes.md +95 -0
  52. package/skills/testing/reverse-and-types.md +84 -0
  53. package/skills/testing/server-actions.md +107 -0
  54. package/skills/testing/server-tree.md +128 -0
  55. package/skills/testing/setup.md +123 -0
  56. package/skills/typesafety/SKILL.md +357 -52
  57. package/skills/use-cache/SKILL.md +46 -14
  58. package/skills/view-transitions/SKILL.md +294 -0
  59. package/src/__augment-tests__/augment.ts +81 -0
  60. package/src/__augment-tests__/augmented.check.ts +116 -0
  61. package/src/__internal.ts +67 -40
  62. package/src/bin/rango.ts +18 -0
  63. package/src/browser/action-coordinator.ts +53 -36
  64. package/src/browser/action-fence.ts +47 -0
  65. package/src/browser/app-shell.ts +39 -0
  66. package/src/browser/app-version.ts +14 -0
  67. package/src/browser/connection-warmup.ts +134 -0
  68. package/src/browser/cookie-name.ts +140 -0
  69. package/src/browser/event-controller.ts +197 -150
  70. package/src/browser/history-state.ts +21 -0
  71. package/src/browser/index.ts +3 -3
  72. package/src/browser/invalidate-client-cache.ts +52 -0
  73. package/src/browser/link-interceptor.ts +4 -0
  74. package/src/browser/navigation-bridge.ts +200 -30
  75. package/src/browser/navigation-client.ts +217 -58
  76. package/src/browser/navigation-store-handle.ts +38 -0
  77. package/src/browser/navigation-store.ts +76 -67
  78. package/src/browser/navigation-transaction.ts +18 -66
  79. package/src/browser/network-error-handler.ts +34 -7
  80. package/src/browser/partial-update.ts +187 -112
  81. package/src/browser/prefetch/cache.ts +312 -30
  82. package/src/browser/prefetch/fetch.ts +344 -47
  83. package/src/browser/prefetch/policy.ts +6 -0
  84. package/src/browser/prefetch/queue.ts +126 -20
  85. package/src/browser/prefetch/resource-ready.ts +77 -0
  86. package/src/browser/rango-state.ts +158 -76
  87. package/src/browser/react/Link.tsx +125 -18
  88. package/src/browser/react/NavigationProvider.tsx +135 -120
  89. package/src/browser/react/ScrollRestoration.tsx +10 -6
  90. package/src/browser/react/context.ts +7 -2
  91. package/src/browser/react/filter-segment-order.ts +66 -7
  92. package/src/browser/react/index.ts +0 -48
  93. package/src/browser/react/location-state-shared.ts +178 -8
  94. package/src/browser/react/location-state.ts +39 -14
  95. package/src/browser/react/use-action.ts +6 -15
  96. package/src/browser/react/use-handle.ts +23 -69
  97. package/src/browser/react/use-href.tsx +8 -1
  98. package/src/browser/react/use-link-status.ts +33 -8
  99. package/src/browser/react/use-navigation.ts +32 -7
  100. package/src/browser/react/use-params.ts +20 -10
  101. package/src/browser/react/use-reverse.ts +106 -0
  102. package/src/browser/react/use-router.ts +46 -11
  103. package/src/browser/react/use-search-params.ts +0 -5
  104. package/src/browser/react/use-segments.ts +11 -21
  105. package/src/browser/response-adapter.ts +80 -5
  106. package/src/browser/rsc-router.tsx +226 -75
  107. package/src/browser/scroll-restoration.ts +54 -42
  108. package/src/browser/segment-reconciler.ts +36 -9
  109. package/src/browser/segment-structure-assert.ts +2 -2
  110. package/src/browser/server-action-bridge.ts +619 -442
  111. package/src/browser/types.ts +115 -11
  112. package/src/browser/validate-redirect-origin.ts +43 -16
  113. package/src/build/collect-fallback-refs.ts +107 -0
  114. package/src/build/generate-manifest.ts +65 -40
  115. package/src/build/generate-route-types.ts +7 -1
  116. package/src/build/index.ts +8 -2
  117. package/src/build/prefix-tree-utils.ts +123 -0
  118. package/src/build/route-trie.ts +182 -37
  119. package/src/build/route-types/ast-route-extraction.ts +15 -8
  120. package/src/build/route-types/codegen.ts +16 -5
  121. package/src/build/route-types/include-resolution.ts +125 -24
  122. package/src/build/route-types/param-extraction.ts +6 -3
  123. package/src/build/route-types/per-module-writer.ts +22 -6
  124. package/src/build/route-types/router-processing.ts +392 -106
  125. package/src/build/route-types/scan-filter.ts +9 -2
  126. package/src/build/route-types/source-scan.ts +216 -0
  127. package/src/build/runtime-discovery.ts +9 -20
  128. package/src/cache/cache-error.ts +104 -0
  129. package/src/cache/cache-key-utils.ts +29 -13
  130. package/src/cache/cache-policy.ts +108 -34
  131. package/src/cache/cache-runtime.ts +214 -48
  132. package/src/cache/cache-scope.ts +236 -89
  133. package/src/cache/cache-tag.ts +103 -0
  134. package/src/cache/cf/cf-base64.ts +33 -0
  135. package/src/cache/cf/cf-cache-constants.ts +127 -0
  136. package/src/cache/cf/cf-cache-store.ts +2224 -171
  137. package/src/cache/cf/cf-cache-types.ts +349 -0
  138. package/src/cache/cf/cf-kv-utils.ts +46 -0
  139. package/src/cache/cf/cf-tag-marker-memo.ts +105 -0
  140. package/src/cache/cf/index.ts +11 -17
  141. package/src/cache/document-cache.ts +89 -27
  142. package/src/cache/handle-snapshot.ts +70 -0
  143. package/src/cache/index.ts +11 -20
  144. package/src/cache/memory-segment-store.ts +136 -37
  145. package/src/cache/profile-registry.ts +31 -31
  146. package/src/cache/read-through-swr.ts +41 -11
  147. package/src/cache/segment-codec.ts +9 -17
  148. package/src/cache/tag-invalidation.ts +230 -0
  149. package/src/cache/taint.ts +55 -0
  150. package/src/cache/types.ts +37 -100
  151. package/src/client.rsc.tsx +45 -21
  152. package/src/client.tsx +120 -336
  153. package/src/cloudflare/index.ts +11 -0
  154. package/src/cloudflare/tracing.ts +109 -0
  155. package/src/component-utils.ts +19 -0
  156. package/src/components/DefaultDocument.tsx +8 -2
  157. package/src/context-var.ts +84 -2
  158. package/src/debug.ts +2 -2
  159. package/src/decode-loader-results.ts +52 -0
  160. package/src/defer.ts +196 -0
  161. package/src/deps/ssr.ts +0 -1
  162. package/src/encode-kv.ts +49 -0
  163. package/src/errors.ts +30 -4
  164. package/src/escape-script.ts +52 -0
  165. package/src/handle.ts +70 -22
  166. package/src/handles/MetaTags.tsx +56 -19
  167. package/src/handles/Scripts.tsx +183 -0
  168. package/src/handles/breadcrumbs.ts +95 -0
  169. package/src/handles/is-thenable.ts +19 -0
  170. package/src/handles/meta.ts +51 -40
  171. package/src/handles/script.ts +244 -0
  172. package/src/host/cookie-handler.ts +9 -60
  173. package/src/host/errors.ts +0 -24
  174. package/src/host/index.ts +8 -5
  175. package/src/host/pattern-matcher.ts +23 -52
  176. package/src/host/router.ts +107 -99
  177. package/src/host/testing.ts +40 -27
  178. package/src/host/types.ts +37 -4
  179. package/src/host/utils.ts +1 -1
  180. package/src/href-client.ts +137 -22
  181. package/src/index.rsc.ts +79 -29
  182. package/src/index.ts +149 -65
  183. package/src/internal-debug.ts +11 -10
  184. package/src/loader-store.ts +500 -0
  185. package/src/loader.rsc.ts +20 -13
  186. package/src/loader.ts +12 -11
  187. package/src/missing-id-error.ts +68 -0
  188. package/src/outlet-context.ts +1 -1
  189. package/src/outlet-provider.tsx +1 -5
  190. package/src/prerender/param-hash.ts +16 -16
  191. package/src/prerender/store.ts +63 -26
  192. package/src/prerender.ts +198 -82
  193. package/src/redirect-origin.ts +100 -0
  194. package/src/regex-escape.ts +8 -0
  195. package/src/render-error-thrower.tsx +20 -0
  196. package/src/response-utils.ts +62 -0
  197. package/src/reverse.ts +65 -15
  198. package/src/root-error-boundary.tsx +1 -19
  199. package/src/route-content-wrapper.tsx +7 -72
  200. package/src/route-definition/dsl-helpers.ts +469 -276
  201. package/src/route-definition/helper-factories.ts +29 -139
  202. package/src/route-definition/helpers-types.ts +113 -37
  203. package/src/route-definition/index.ts +3 -3
  204. package/src/route-definition/redirect.ts +53 -12
  205. package/src/route-definition/resolve-handler-use.ts +161 -0
  206. package/src/route-definition/use-item-types.ts +32 -0
  207. package/src/route-map-builder.ts +7 -17
  208. package/src/route-types.ts +37 -41
  209. package/src/router/basename.ts +14 -0
  210. package/src/router/content-negotiation.ts +164 -17
  211. package/src/router/error-handling.ts +45 -18
  212. package/src/router/find-match.ts +45 -22
  213. package/src/router/handler-context.ts +110 -39
  214. package/src/router/instrument.ts +350 -0
  215. package/src/router/intercept-resolution.ts +50 -24
  216. package/src/router/lazy-includes.ts +19 -53
  217. package/src/router/loader-resolution.ts +274 -56
  218. package/src/router/logging.ts +5 -8
  219. package/src/router/manifest.ts +49 -45
  220. package/src/router/match-api.ts +121 -205
  221. package/src/router/match-context.ts +0 -22
  222. package/src/router/match-handlers.ts +58 -58
  223. package/src/router/match-middleware/background-revalidation.ts +33 -6
  224. package/src/router/match-middleware/cache-lookup.ts +214 -263
  225. package/src/router/match-middleware/cache-store.ts +73 -33
  226. package/src/router/match-middleware/intercept-resolution.ts +8 -28
  227. package/src/router/match-middleware/segment-resolution.ts +52 -18
  228. package/src/router/match-pipelines.ts +1 -42
  229. package/src/router/match-result.ts +104 -49
  230. package/src/router/metrics.ts +217 -26
  231. package/src/router/middleware-types.ts +24 -110
  232. package/src/router/middleware.ts +384 -197
  233. package/src/router/navigation-snapshot.ts +131 -0
  234. package/src/router/params-util.ts +23 -0
  235. package/src/router/pattern-matching.ts +148 -91
  236. package/src/router/prefetch-cache-ttl.ts +51 -0
  237. package/src/router/prerender-match.ts +199 -56
  238. package/src/router/preview-match.ts +32 -102
  239. package/src/router/request-classification.ts +276 -0
  240. package/src/router/revalidation.ts +144 -74
  241. package/src/router/route-snapshot.ts +244 -0
  242. package/src/router/router-context.ts +8 -28
  243. package/src/router/router-interfaces.ts +129 -36
  244. package/src/router/router-options.ts +185 -23
  245. package/src/router/router-registry.ts +2 -5
  246. package/src/router/segment-resolution/fresh.ts +281 -76
  247. package/src/router/segment-resolution/helpers.ts +116 -31
  248. package/src/router/segment-resolution/loader-cache.ts +63 -37
  249. package/src/router/segment-resolution/revalidation.ts +493 -391
  250. package/src/router/segment-resolution/static-store.ts +19 -5
  251. package/src/router/segment-resolution/streamed-handler-telemetry.ts +52 -0
  252. package/src/router/segment-resolution/view-transition-default.ts +36 -0
  253. package/src/router/segment-resolution.ts +5 -1
  254. package/src/router/segment-wrappers.ts +8 -5
  255. package/src/router/state-cookie-name.ts +33 -0
  256. package/src/router/substitute-pattern-params.ts +56 -0
  257. package/src/router/telemetry-otel.ts +161 -199
  258. package/src/router/telemetry.ts +96 -19
  259. package/src/router/timeout.ts +0 -20
  260. package/src/router/tracing.ts +206 -0
  261. package/src/router/trie-matching.ts +180 -58
  262. package/src/router/types.ts +10 -63
  263. package/src/router/url-params.ts +44 -0
  264. package/src/router.ts +182 -54
  265. package/src/rsc/handler-context.ts +3 -2
  266. package/src/rsc/handler.ts +702 -460
  267. package/src/rsc/helpers.ts +168 -46
  268. package/src/rsc/index.ts +2 -25
  269. package/src/rsc/json-route-result.ts +38 -0
  270. package/src/rsc/loader-fetch.ts +127 -31
  271. package/src/rsc/manifest-init.ts +33 -42
  272. package/src/rsc/origin-guard.ts +39 -25
  273. package/src/rsc/progressive-enhancement.ts +98 -19
  274. package/src/rsc/redirect-guard.ts +99 -0
  275. package/src/rsc/response-cache-serve.ts +238 -0
  276. package/src/rsc/response-error.ts +79 -12
  277. package/src/rsc/response-route-handler.ts +99 -189
  278. package/src/rsc/rsc-rendering.ts +126 -106
  279. package/src/rsc/runtime-warnings.ts +23 -10
  280. package/src/rsc/server-action.ts +269 -114
  281. package/src/rsc/ssr-setup.ts +144 -0
  282. package/src/rsc/types.ts +34 -6
  283. package/src/runtime-env.ts +18 -0
  284. package/src/search-params.ts +49 -41
  285. package/src/segment-content-promise.ts +67 -0
  286. package/src/segment-loader-promise.ts +149 -0
  287. package/src/segment-system.tsx +281 -129
  288. package/src/serialize.ts +243 -0
  289. package/src/server/context.ts +317 -63
  290. package/src/server/cookie-parse.ts +32 -0
  291. package/src/server/cookie-store.ts +80 -5
  292. package/src/server/handle-store.ts +40 -38
  293. package/src/server/loader-registry.ts +26 -46
  294. package/src/server/request-context.ts +425 -177
  295. package/src/server.ts +6 -0
  296. package/src/ssr/index.tsx +25 -16
  297. package/src/static-handler.ts +27 -18
  298. package/src/testing/cache-status.ts +162 -0
  299. package/src/testing/collect-handle.ts +40 -0
  300. package/src/testing/dispatch.ts +701 -0
  301. package/src/testing/dom.entry.ts +22 -0
  302. package/src/testing/e2e/fixture.ts +188 -0
  303. package/src/testing/e2e/index.ts +128 -0
  304. package/src/testing/e2e/matchers.ts +35 -0
  305. package/src/testing/e2e/page-helpers.ts +272 -0
  306. package/src/testing/e2e/parity.ts +387 -0
  307. package/src/testing/e2e/server.ts +195 -0
  308. package/src/testing/flight-matchers.ts +97 -0
  309. package/src/testing/flight-normalize.ts +11 -0
  310. package/src/testing/flight-runtime.d.ts +57 -0
  311. package/src/testing/flight-tree.ts +682 -0
  312. package/src/testing/flight.entry.ts +52 -0
  313. package/src/testing/flight.ts +257 -0
  314. package/src/testing/generated-routes.ts +183 -0
  315. package/src/testing/index.ts +99 -0
  316. package/src/testing/internal/context.ts +371 -0
  317. package/src/testing/internal/flight-client-globals.ts +30 -0
  318. package/src/testing/internal/seed-vars.ts +54 -0
  319. package/src/testing/render-handler.ts +343 -0
  320. package/src/testing/render-route.tsx +581 -0
  321. package/src/testing/run-loader.ts +385 -0
  322. package/src/testing/run-middleware.ts +205 -0
  323. package/src/testing/vitest-stubs/cloudflare-email.ts +9 -0
  324. package/src/testing/vitest-stubs/cloudflare-workers.ts +21 -0
  325. package/src/testing/vitest-stubs/plugin-rsc.ts +16 -0
  326. package/src/testing/vitest-stubs/version.ts +5 -0
  327. package/src/testing/vitest.ts +305 -0
  328. package/src/theme/ThemeProvider.tsx +20 -58
  329. package/src/theme/ThemeScript.tsx +7 -9
  330. package/src/theme/constants.ts +52 -13
  331. package/src/theme/index.ts +3 -19
  332. package/src/theme/theme-context.ts +1 -5
  333. package/src/theme/theme-script.ts +22 -21
  334. package/src/theme/use-theme.ts +0 -3
  335. package/src/types/boundaries.ts +0 -35
  336. package/src/types/cache-types.ts +17 -8
  337. package/src/types/error-types.ts +30 -90
  338. package/src/types/global-namespace.ts +54 -41
  339. package/src/types/handler-context.ts +236 -88
  340. package/src/types/index.ts +1 -10
  341. package/src/types/loader-types.ts +44 -15
  342. package/src/types/request-scope.ts +112 -0
  343. package/src/types/route-config.ts +10 -45
  344. package/src/types/route-entry.ts +19 -7
  345. package/src/types/segments.ts +37 -19
  346. package/src/urls/include-helper.ts +33 -70
  347. package/src/urls/index.ts +1 -11
  348. package/src/urls/path-helper-types.ts +58 -11
  349. package/src/urls/path-helper.ts +57 -111
  350. package/src/urls/pattern-types.ts +48 -19
  351. package/src/urls/response-types.ts +25 -22
  352. package/src/urls/type-extraction.ts +58 -139
  353. package/src/urls/urls-function.ts +1 -18
  354. package/src/use-loader.tsx +346 -89
  355. package/src/vite/debug.ts +185 -0
  356. package/src/vite/discovery/bundle-postprocess.ts +64 -91
  357. package/src/vite/discovery/discover-routers.ts +147 -88
  358. package/src/vite/discovery/discovery-errors.ts +194 -0
  359. package/src/vite/discovery/gate-state.ts +171 -0
  360. package/src/vite/discovery/prerender-collection.ts +247 -145
  361. package/src/vite/discovery/route-types-writer.ts +40 -84
  362. package/src/vite/discovery/self-gen-tracking.ts +27 -1
  363. package/src/vite/discovery/state.ts +61 -13
  364. package/src/vite/discovery/virtual-module-codegen.ts +14 -34
  365. package/src/vite/index.ts +10 -3
  366. package/src/vite/inject-client-debug.ts +36 -0
  367. package/src/vite/plugin-types.ts +155 -65
  368. package/src/vite/plugins/cjs-to-esm.ts +16 -19
  369. package/src/vite/plugins/client-ref-dedup.ts +120 -0
  370. package/src/vite/plugins/client-ref-hashing.ts +28 -15
  371. package/src/vite/plugins/cloudflare-protocol-loader-hook.d.mts +23 -0
  372. package/src/vite/plugins/cloudflare-protocol-loader-hook.mjs +76 -0
  373. package/src/vite/plugins/cloudflare-protocol-stub.ts +194 -0
  374. package/src/vite/plugins/expose-action-id.ts +49 -98
  375. package/src/vite/plugins/expose-id-utils.ts +96 -51
  376. package/src/vite/plugins/expose-ids/export-analysis.ts +101 -34
  377. package/src/vite/plugins/expose-ids/handler-transform.ts +15 -64
  378. package/src/vite/plugins/expose-ids/loader-transform.ts +14 -24
  379. package/src/vite/plugins/expose-ids/router-transform.ts +118 -29
  380. package/src/vite/plugins/expose-internal-ids.ts +553 -317
  381. package/src/vite/plugins/performance-tracks.ts +89 -0
  382. package/src/vite/plugins/refresh-cmd.ts +127 -0
  383. package/src/vite/plugins/use-cache-transform.ts +73 -83
  384. package/src/vite/plugins/version-injector.ts +21 -25
  385. package/src/vite/plugins/version-plugin.ts +46 -37
  386. package/src/vite/plugins/virtual-entries.ts +13 -18
  387. package/src/vite/rango.ts +241 -287
  388. package/src/vite/router-discovery.ts +956 -149
  389. package/src/vite/utils/ast-handler-extract.ts +26 -35
  390. package/src/vite/utils/banner.ts +4 -4
  391. package/src/vite/utils/bundle-analysis.ts +10 -15
  392. package/src/vite/utils/client-chunks.ts +184 -0
  393. package/src/vite/utils/directive-prologue.ts +40 -0
  394. package/src/vite/utils/forward-user-plugins.ts +171 -0
  395. package/src/vite/utils/manifest-utils.ts +4 -59
  396. package/src/vite/utils/package-resolution.ts +20 -52
  397. package/src/vite/utils/prerender-utils.ts +141 -34
  398. package/src/vite/utils/shared-utils.ts +92 -42
  399. package/CLAUDE.md +0 -5
  400. package/src/browser/action-response-classifier.ts +0 -99
  401. package/src/browser/react/use-client-cache.ts +0 -58
  402. package/src/browser/shallow.ts +0 -40
  403. package/src/handles/index.ts +0 -6
  404. package/src/network-error-thrower.tsx +0 -23
  405. package/src/route-definition/route-function.ts +0 -119
  406. package/src/router/middleware-cookies.ts +0 -55
@@ -4,13 +4,15 @@ import type {
4
4
  RscPayload,
5
5
  } from "./types.js";
6
6
  import { createPartialUpdater } from "./partial-update.js";
7
+ import { enterActionFence, exitActionFence } from "./action-fence.js";
8
+ import { KEEP_CACHE_HEADER } from "./cookie-name.js";
7
9
  import { createNavigationTransaction } from "./navigation-transaction.js";
8
10
  import {
9
11
  reconcileSegments,
10
12
  reconcileErrorSegments,
11
13
  } from "./segment-reconciler.js";
12
14
  import { startTransition } from "react";
13
- import type { EventController } from "./event-controller.js";
15
+ import type { EventController, ActionHandle } from "./event-controller.js";
14
16
  import {
15
17
  toNetworkError,
16
18
  emitNetworkError,
@@ -21,14 +23,20 @@ import {
21
23
  isBrowserDebugEnabled,
22
24
  startBrowserTransaction,
23
25
  } from "./logging.js";
24
- import { validateRedirectOrigin } from "./validate-redirect-origin.js";
26
+ import {
27
+ validateRedirectOrigin,
28
+ validateExternalRedirect,
29
+ } from "./validate-redirect-origin.js";
25
30
  import {
26
31
  extractRscHeaderUrl,
27
32
  emptyResponse,
33
+ handleReloadHeader,
28
34
  teeWithCompletion,
35
+ isForeignRouterId,
29
36
  } from "./response-adapter.js";
30
37
  import { mergeLocationState } from "./history-state.js";
31
38
  import { classifyActionOutcome } from "./action-coordinator.js";
39
+ import { getAppVersion } from "./app-version.js";
32
40
 
33
41
  // Polyfill Symbol.dispose/asyncDispose for Safari and older browsers
34
42
  if (typeof Symbol.dispose === "undefined") {
@@ -43,8 +51,6 @@ if (typeof Symbol.asyncDispose === "undefined") {
43
51
  */
44
52
  export interface ServerActionBridgeConfigWithController extends ServerActionBridgeConfig {
45
53
  eventController: EventController;
46
- /** RSC version from initial payload metadata */
47
- version?: string;
48
54
  /** Callback to trigger SPA navigation (for action redirects) */
49
55
  onNavigate?: (
50
56
  url: string,
@@ -52,6 +58,27 @@ export interface ServerActionBridgeConfigWithController extends ServerActionBrid
52
58
  ) => Promise<void>;
53
59
  }
54
60
 
61
+ /**
62
+ * Merge an action's location-state payload into history.state, restricted to
63
+ * the keys this action is entitled to write. claimLocationState enforces
64
+ * last-initiated-wins for same-key concurrent writes (a later-initiated sibling
65
+ * keeps its value even if this action's response settles afterward); distinct
66
+ * keys from every concurrent action survive. Arbitration is scoped to the
67
+ * action's cohort (captured at startAction), so a newer action on another entry
68
+ * cannot suppress this one. No-op when nothing was set or all keys were already
69
+ * claimed by a later-initiated sibling in the cohort.
70
+ */
71
+ function applyActionLocationState(
72
+ handle: ActionHandle,
73
+ locationState: Record<string, unknown> | undefined,
74
+ ): void {
75
+ if (!locationState) return;
76
+ const winning = handle.claimLocationState(locationState);
77
+ if (Object.keys(winning).length > 0) {
78
+ mergeLocationState(winning);
79
+ }
80
+ }
81
+
55
82
  /**
56
83
  * Create a server action bridge for handling RSC server actions
57
84
  *
@@ -75,10 +102,29 @@ export function createServerActionBridge(
75
102
  deps,
76
103
  onUpdate,
77
104
  renderSegments,
78
- version,
79
105
  onNavigate,
80
106
  } = config;
81
107
 
108
+ // SPA-navigate when onNavigate is set, else hard-reload. state is omitted (not
109
+ // passed as undefined) to match the header path's prior call shape.
110
+ // Callers pass an already same-origin-validated url; the hard-reload fallback
111
+ // re-validates defensively so this leaf cannot become an open redirect if a
112
+ // future caller forgets (the SPA path validates inside the navigation bridge).
113
+ async function dispatchRedirect(url: string, state?: unknown): Promise<void> {
114
+ if (onNavigate) {
115
+ await onNavigate(url, {
116
+ ...(state !== undefined ? { state } : {}),
117
+ replace: true,
118
+ _skipCache: true,
119
+ });
120
+ } else {
121
+ const safe = validateRedirectOrigin(url, window.location.origin);
122
+ if (safe) {
123
+ window.location.href = safe;
124
+ }
125
+ }
126
+ }
127
+
82
128
  let isRegistered = false;
83
129
 
84
130
  const fetchPartialUpdate = createPartialUpdater({
@@ -86,7 +132,7 @@ export function createServerActionBridge(
86
132
  client,
87
133
  onUpdate,
88
134
  renderSegments,
89
- version,
135
+ getVersion: getAppVersion,
90
136
  });
91
137
 
92
138
  /**
@@ -99,27 +145,31 @@ export function createServerActionBridge(
99
145
  interceptSourceUrl?: string | null;
100
146
  }): Promise<void> {
101
147
  const src = opts?.interceptSourceUrl ?? null;
102
- using navTx = createNavigationTransaction(
148
+ const navTx = createNavigationTransaction(
103
149
  store,
104
150
  eventController,
105
151
  window.location.href,
106
152
  { replace: true, skipLoadingState: true },
107
153
  );
108
- await fetchPartialUpdate(
109
- window.location.href,
110
- opts?.segments ?? [],
111
- false,
112
- navTx.handle.signal,
113
- navTx.with({
114
- url: window.location.href,
115
- storeOnly: true,
116
- ...(src ? { intercept: true, interceptSourceUrl: src } : {}),
117
- }),
118
- {
119
- type: "action" as const,
120
- ...(src ? { interceptSourceUrl: src } : {}),
121
- },
122
- );
154
+ try {
155
+ await fetchPartialUpdate(
156
+ window.location.href,
157
+ opts?.segments ?? [],
158
+ false,
159
+ navTx.handle.signal,
160
+ navTx.with({
161
+ url: window.location.href,
162
+ storeOnly: true,
163
+ ...(src ? { intercept: true, interceptSourceUrl: src } : {}),
164
+ }),
165
+ {
166
+ type: "action" as const,
167
+ ...(src ? { interceptSourceUrl: src } : {}),
168
+ },
169
+ );
170
+ } finally {
171
+ navTx[Symbol.dispose]();
172
+ }
123
173
  }
124
174
 
125
175
  /**
@@ -136,441 +186,604 @@ export function createServerActionBridge(
136
186
  const locationKey = window.history.state?.key;
137
187
  log("action start", { id, argsCount: args.length });
138
188
 
139
- // Start action in event controller - handles lifecycle tracking
140
- using handle = eventController.startAction(id, args);
189
+ // Start action in event controller - handles lifecycle tracking. The
190
+ // current history key is the action's cohort: location-state arbitration is
191
+ // scoped to it so a later action on a different entry cannot suppress this
192
+ // one (and vice versa).
193
+ const handle = eventController.startAction(id, args, locationKey);
194
+ // Whether the action's response carried the keepClientCache() directive.
195
+ // Set when the response arrives; gates the deferred invalidation below.
196
+ let keepCache = false;
197
+ // Whether a Response actually settled from the network (the server saw the
198
+ // request). Set true as the first statement in the fetch .then() below.
199
+ // Gates the automatic invalidation: a pre-dispatch failure (encodeReply
200
+ // throw or a fetch rejection — server unreachable/DNS/connection refused)
201
+ // leaves this false, so finalizeAction() must NOT invalidate or broadcast —
202
+ // nothing reached the server, so nothing could have mutated. A failed Flight
203
+ // DECODE after the response arrived keeps it true (the mutation may have
204
+ // committed, so invalidating the now-possibly-stale client cache is correct).
205
+ let responseReceived = false;
206
+ // Single deferred invalidation + fence release, run exactly ONCE however the
207
+ // action terminates (normal, redirect, error, abort, intercept, concurrent).
208
+ // This replaces main's eager clear at action start: every directive-free
209
+ // action invalidates once; keepClientCache() suppresses only the automatic
210
+ // invalidation, so a concurrent directive-free action still invalidates via
211
+ // its own latch. Latched so the finally AND the early SPA-redirect returns
212
+ // (whose Flight stream never settles) can both call it safely.
213
+ let actionFinalized = false;
214
+ // skipInvalidation: the version-mismatch reload terminal released nothing
215
+ // server-side, so it releases the fence without invalidating.
216
+ const finalizeAction = (skipInvalidation = false): void => {
217
+ if (actionFinalized) return;
218
+ actionFinalized = true;
219
+ // finally so a throw in invalidation cannot leak the fence (latch is set).
220
+ try {
221
+ // responseReceived gates the automatic invalidation: a pre-dispatch
222
+ // failure (serialize throw / fetch reject) never reached the server, so
223
+ // marking the cache stale + broadcasting cross-tab would be spurious.
224
+ if (responseReceived && !keepCache && !skipInvalidation) {
225
+ store.markCacheAsStaleAndBroadcast();
226
+ }
227
+ } finally {
228
+ exitActionFence();
229
+ }
230
+ };
231
+ try {
232
+ const segmentState = store.getSegmentState();
233
+
234
+ // Raise the action fence (replaces the old eager clear). Nothing is wiped,
235
+ // rotated, or broadcast yet: navigations during the flight fetch fresh
236
+ // (no-store) and popstate is treated as SWR, but the decision to
237
+ // invalidate is deferred to the response so a no-op action (keepClientCache)
238
+ // can leave the caches and the jar untouched.
239
+ enterActionFence();
240
+
241
+ // Create temporary references for serialization
242
+ const temporaryReferences = deps.createTemporaryReferenceSet();
243
+
244
+ // Capture URL pathname at action start to detect navigation during action
245
+ // Must use window.location (not store.path) because intercepts change URL
246
+ // without changing store.path (e.g., /kanban -> /kanban/card/1)
247
+ const actionStartPathname = window.location.pathname;
248
+
249
+ // Build action request URL with current segments
250
+ const url = new URL(window.location.href);
251
+ url.searchParams.set("_rsc_action", id);
252
+ url.searchParams.set(
253
+ "_rsc_segments",
254
+ segmentState.currentSegmentIds.join(","),
255
+ );
256
+ // Add version param for version mismatch detection
257
+ const version = getAppVersion();
258
+ if (version) {
259
+ url.searchParams.set("_rsc_v", version);
260
+ }
261
+ // Add router ID for app switch detection
262
+ const rid = store.getRouterId?.();
263
+ if (rid) {
264
+ url.searchParams.set("_rsc_rid", rid);
265
+ }
266
+
267
+ // Encode arguments
268
+ const encodedBody = await deps.encodeReply(args, { temporaryReferences });
141
269
 
142
- const segmentState = store.getSegmentState();
270
+ log("sending action request", {
271
+ url: url.href,
272
+ bodyType: typeof encodedBody,
273
+ isFormData: encodedBody instanceof FormData,
274
+ segmentCount: segmentState.currentSegmentIds.length,
275
+ });
143
276
 
144
- // Mark cache as stale immediately when action starts
145
- // This ensures SWR pattern kicks in if user navigates away during action
146
- store.markCacheAsStaleAndBroadcast();
277
+ // Track when the stream completes
278
+ let resolveStreamComplete: () => void;
279
+ const streamComplete = new Promise<void>((resolve) => {
280
+ resolveStreamComplete = resolve;
281
+ });
147
282
 
148
- // Create temporary references for serialization
149
- const temporaryReferences = deps.createTemporaryReferenceSet();
283
+ // Get intercept source URL if in intercept context
284
+ const interceptSourceUrl = store.getInterceptSourceUrl();
285
+
286
+ // Track streaming token - will be set when response arrives
287
+ let streamingToken: { end(): void } | null = null;
288
+
289
+ // Use a dedicated abort controller for the fetch so we can cancel network
290
+ // I/O without disrupting the Flight stream once the response has arrived.
291
+ // Aborting a response mid-stream causes React's Flight decoder to throw
292
+ // asynchronous unhandled errors (BodyStreamBuffer was aborted).
293
+ const fetchAbort = new AbortController();
294
+ const onHandleAbort = () => fetchAbort.abort();
295
+ handle.signal.addEventListener("abort", onHandleAbort, { once: true });
296
+
297
+ // Send action request with stream tracking
298
+ const responsePromise = fetch(url, {
299
+ method: "POST",
300
+ headers: {
301
+ "rsc-action": id,
302
+ "X-RSC-Router-Client-Path": segmentState.currentUrl,
303
+ ...(tx && { "X-RSC-Router-Request-Id": tx.requestId }),
304
+ ...(interceptSourceUrl && {
305
+ "X-RSC-Router-Intercept-Source": interceptSourceUrl,
306
+ }),
307
+ },
308
+ body: encodedBody,
309
+ signal: fetchAbort.signal,
310
+ }).then(async (response) => {
311
+ // A settled fetch promise means the request reached the server and a
312
+ // Response came back (true for 2xx, 4xx, AND 5xx — fetch only rejects
313
+ // on network-layer failure, never on HTTP status). Record it as the
314
+ // first statement so every downstream terminal can invalidate; a
315
+ // pre-dispatch failure never gets here and stays gated out.
316
+ responseReceived = true;
317
+ // Response arrived — disconnect fetch abort from handle abort so
318
+ // abortAllActions() doesn't disrupt the in-progress Flight stream.
319
+ handle.signal.removeEventListener("abort", onHandleAbort);
320
+
321
+ // Did the action call keepClientCache()? If so the deferred invalidation
322
+ // below is suppressed for THIS action (a concurrent directive-free
323
+ // action still invalidates via its own response).
324
+ keepCache = response.headers.get(KEEP_CACHE_HEADER) === "1";
325
+
326
+ // Check for version mismatch - server wants us to reload
327
+ const reloadResult = handleReloadHeader(response, {
328
+ onBlocked: resolveStreamComplete,
329
+ onReload: (url) => {
330
+ log("version mismatch on action, reloading", { reloadUrl: url });
331
+ // Never-settling terminal (navigates away), so the finally never
332
+ // runs: release the fence here. skipInvalidation — the mismatch
333
+ // short-circuits the action server-side, so nothing mutated and a
334
+ // broadcast would only risk hard-reloading a sibling mid-task.
335
+ finalizeAction(true);
336
+ },
337
+ });
338
+ if (reloadResult) return reloadResult;
339
+
340
+ // Simple redirect from action (no state, no RSC payload).
341
+ // Short-circuits before createFromFetch — no Flight deserialization needed.
342
+ // Check handle.signal.aborted to avoid redirecting from a stale action
343
+ // when the user has already navigated away.
344
+ const redirect = extractRscHeaderUrl(response, "X-RSC-Redirect");
345
+ if (redirect && redirect !== "blocked" && !handle.signal.aborted) {
346
+ log("action simple redirect", { url: redirect.url });
347
+ handle.complete(undefined);
348
+ // This path returns a never-settling promise, so the finally never
349
+ // runs: invalidate + release the fence here (the mutation committed
350
+ // and we're navigating away). Latched, so the finally is a no-op.
351
+ finalizeAction();
352
+ await dispatchRedirect(redirect.url);
353
+ return new Promise<Response>(() => {});
354
+ }
355
+ if (redirect === "blocked") {
356
+ resolveStreamComplete();
357
+ return emptyResponse();
358
+ }
150
359
 
151
- // Capture URL pathname at action start to detect navigation during action
152
- // Must use window.location (not store.path) because intercepts change URL
153
- // without changing store.path (e.g., /kanban -> /kanban/card/1)
154
- const actionStartPathname = window.location.pathname;
360
+ // Integrity check (pre-decode): a foreign app's action response must
361
+ // not be decoded + applied here. This is the one decode-and-apply path
362
+ // the post-decode partial-update guard does NOT cover (the action
363
+ // bridge has its own createFromFetch -> onUpdate). Ordered after the
364
+ // reload/redirect handlers, which steer control responses first.
365
+ // Reloads via window.location.reload() rather than navigating to a
366
+ // target (as the navigation-client guard does): an action has no
367
+ // navigation target, so reloading the current URL re-syncs the
368
+ // document against the server-applied action effect.
369
+ if (
370
+ !handle.signal.aborted &&
371
+ isForeignRouterId(response, store.getRouterId?.())
372
+ ) {
373
+ log("action router id mismatch, reloading to re-sync");
374
+ handle.complete(undefined);
375
+ resolveStreamComplete();
376
+ // Never-settling return: release the fence before the reload (the
377
+ // reload resets module state anyway, but stay balanced). Latched.
378
+ finalizeAction();
379
+ window.location.reload();
380
+ return new Promise<Response>(() => {});
381
+ }
155
382
 
156
- // Build action request URL with current segments
157
- const url = new URL(window.location.href);
158
- url.searchParams.set("_rsc_action", id);
159
- url.searchParams.set(
160
- "_rsc_segments",
161
- segmentState.currentSegmentIds.join(","),
162
- );
163
- // Add version param for version mismatch detection
164
- if (version) {
165
- url.searchParams.set("_rsc_v", version);
166
- }
383
+ // Start streaming immediately when response arrives
384
+ if (!handle.signal.aborted) {
385
+ streamingToken = handle.startStreaming();
386
+ }
167
387
 
168
- // Encode arguments
169
- const encodedBody = await deps.encodeReply(args, { temporaryReferences });
170
-
171
- log("sending action request", {
172
- url: url.href,
173
- bodyType: typeof encodedBody,
174
- isFormData: encodedBody instanceof FormData,
175
- segmentCount: segmentState.currentSegmentIds.length,
176
- });
177
-
178
- // Track when the stream completes
179
- let resolveStreamComplete: () => void;
180
- const streamComplete = new Promise<void>((resolve) => {
181
- resolveStreamComplete = resolve;
182
- });
183
-
184
- // Get intercept source URL if in intercept context
185
- const interceptSourceUrl = store.getInterceptSourceUrl();
186
-
187
- // Track streaming token - will be set when response arrives
188
- let streamingToken: { end(): void } | null = null;
189
-
190
- // Use a dedicated abort controller for the fetch so we can cancel network
191
- // I/O without disrupting the Flight stream once the response has arrived.
192
- // Aborting a response mid-stream causes React's Flight decoder to throw
193
- // asynchronous unhandled errors (BodyStreamBuffer was aborted).
194
- const fetchAbort = new AbortController();
195
- const onHandleAbort = () => fetchAbort.abort();
196
- handle.signal.addEventListener("abort", onHandleAbort, { once: true });
197
-
198
- // Send action request with stream tracking
199
- const responsePromise = fetch(url, {
200
- method: "POST",
201
- headers: {
202
- "rsc-action": id,
203
- "X-RSC-Router-Client-Path": segmentState.currentUrl,
204
- ...(tx && { "X-RSC-Router-Request-Id": tx.requestId }),
205
- // Send intercept source URL so server can maintain intercept context
206
- ...(interceptSourceUrl && {
207
- "X-RSC-Router-Intercept-Source": interceptSourceUrl,
208
- }),
209
- },
210
- body: encodedBody,
211
- signal: fetchAbort.signal,
212
- }).then(async (response) => {
213
- // Response arrived — disconnect fetch abort from handle abort so
214
- // abortAllActions() doesn't disrupt the in-progress Flight stream.
215
- handle.signal.removeEventListener("abort", onHandleAbort);
216
-
217
- // Check for version mismatch - server wants us to reload
218
- const reload = extractRscHeaderUrl(response, "X-RSC-Reload");
219
- if (reload === "blocked") {
220
- resolveStreamComplete();
221
- return emptyResponse();
222
- }
223
- if (reload) {
224
- log("version mismatch on action, reloading", { reloadUrl: reload.url });
225
- window.location.href = reload.url;
226
- return new Promise<Response>(() => {});
227
- }
388
+ return teeWithCompletion(response, () => {
389
+ log("stream complete");
390
+ streamingToken?.end();
391
+ resolveStreamComplete();
392
+ });
393
+ });
228
394
 
229
- // Simple redirect from action (no state, no RSC payload).
230
- // Short-circuits before createFromFetch — no Flight deserialization needed.
231
- // Check handle.signal.aborted to avoid redirecting from a stale action
232
- // when the user has already navigated away.
233
- const redirect = extractRscHeaderUrl(response, "X-RSC-Redirect");
234
- if (redirect && redirect !== "blocked" && !handle.signal.aborted) {
235
- log("action simple redirect", { url: redirect.url });
236
- handle.complete(undefined);
237
- if (onNavigate) {
238
- await onNavigate(redirect.url, {
239
- replace: true,
240
- _skipCache: true,
241
- });
242
- } else {
243
- window.location.href = redirect.url;
395
+ // Deserialize response (MUST use same temporaryReferences)
396
+ let payload: RscPayload;
397
+ try {
398
+ payload = await deps.createFromFetch<RscPayload>(responsePromise, {
399
+ temporaryReferences,
400
+ });
401
+ } catch (error) {
402
+ // Clean up streaming token on error (may be null if fetch failed before .then() ran)
403
+ // The token is assigned in .then() callback which runs before this catch block,
404
+ // but TypeScript doesn't track cross-async assignments, so use type assertion
405
+ (streamingToken as { end(): void } | null)?.end();
406
+ // resolveStreamComplete is assigned in the Promise constructor so it's safe to call
407
+ resolveStreamComplete!();
408
+
409
+ // Silently swallow abort errors — the action was intentionally cancelled
410
+ // (e.g., user navigated away or abortAllActions was called).
411
+ // Return undefined instead of throwing to avoid surfacing as a page error.
412
+ // Check both DOMException AbortError and stream-level abort messages
413
+ // (BodyStreamBuffer was aborted) that propagate from the aborted fetch.
414
+ if (handle.signal.aborted) {
415
+ return undefined;
244
416
  }
245
- return new Promise<Response>(() => {});
246
- }
247
- if (redirect === "blocked") {
248
- resolveStreamComplete();
249
- return emptyResponse();
250
- }
251
417
 
252
- // Start streaming immediately when response arrives
253
- if (!handle.signal.aborted) {
254
- streamingToken = handle.startStreaming();
418
+ // Convert network-level errors to NetworkError for proper handling
419
+ const networkError = toNetworkError(error, {
420
+ url: url.toString(),
421
+ operation: "action",
422
+ });
423
+ if (networkError) {
424
+ handle.fail(networkError);
425
+ emitNetworkError(onUpdate, networkError, segmentState.currentUrl);
426
+ throw networkError;
427
+ }
428
+ throw error;
255
429
  }
256
430
 
257
- return teeWithCompletion(response, () => {
258
- log("stream complete");
259
- streamingToken?.end();
260
- resolveStreamComplete();
431
+ log("action response received", {
432
+ isPartial: payload.metadata?.isPartial,
433
+ isError: payload.metadata?.isError,
434
+ matchedCount: payload.metadata?.matched?.length ?? 0,
435
+ diffCount: payload.metadata?.diff?.length ?? 0,
261
436
  });
262
- });
263
-
264
- // Deserialize response (MUST use same temporaryReferences)
265
- let payload: RscPayload;
266
- try {
267
- payload = await deps.createFromFetch<RscPayload>(responsePromise, {
268
- temporaryReferences,
269
- });
270
- } catch (error) {
271
- // Clean up streaming token on error (may be null if fetch failed before .then() ran)
272
- // The token is assigned in .then() callback which runs before this catch block,
273
- // but TypeScript doesn't track cross-async assignments, so use type assertion
274
- (streamingToken as { end(): void } | null)?.end();
275
- // resolveStreamComplete is assigned in the Promise constructor so it's safe to call
276
- resolveStreamComplete!();
277
-
278
- // Silently swallow abort errors — the action was intentionally cancelled
279
- // (e.g., user navigated away or abortAllActions was called).
280
- // Return undefined instead of throwing to avoid surfacing as a page error.
281
- // Check both DOMException AbortError and stream-level abort messages
282
- // (BodyStreamBuffer was aborted) that propagate from the aborted fetch.
437
+ // Guard: if the action was aborted while streaming (e.g., user navigated
438
+ // away or abortAllActions fired), bail out before any reconcile/render/cache
439
+ // writes to avoid overwriting the current UI with stale action results.
283
440
  if (handle.signal.aborted) {
441
+ log("action aborted after response, skipping reconciliation");
284
442
  return undefined;
285
443
  }
286
444
 
287
- // Convert network-level errors to NetworkError for proper handling
288
- const networkError = toNetworkError(error, {
289
- url: url.toString(),
290
- operation: "action",
291
- });
292
- if (networkError) {
293
- handle.fail(networkError);
294
- emitNetworkError(onUpdate, networkError, segmentState.currentUrl);
295
- throw networkError;
296
- }
297
- throw error;
298
- }
445
+ // Process response
446
+ const { metadata, returnValue } = payload;
299
447
 
300
- log("action response received", {
301
- isPartial: payload.metadata?.isPartial,
302
- isError: payload.metadata?.isError,
303
- matchedCount: payload.metadata?.matched?.length ?? 0,
304
- diffCount: payload.metadata?.diff?.length ?? 0,
305
- });
306
-
307
- // Guard: if the action was aborted while streaming (e.g., user navigated
308
- // away or abortAllActions fired), bail out before any reconcile/render/cache
309
- // writes to avoid overwriting the current UI with stale action results.
310
- if (handle.signal.aborted) {
311
- log("action aborted after response, skipping reconciliation");
312
- return undefined;
313
- }
314
-
315
- // Process response
316
- const { metadata, returnValue } = payload;
317
-
318
- // Handle action redirect: server converted the redirect to a Flight payload
319
- // so we can perform SPA navigation instead of a full page reload.
320
- // Check handle.signal.aborted to avoid redirecting from a stale action
321
- // when the user has already navigated away.
322
- if (metadata?.redirect && !handle.signal.aborted) {
323
- const redirectUrl = validateRedirectOrigin(
324
- metadata.redirect.url,
325
- window.location.origin,
326
- );
327
- if (!redirectUrl) {
328
- log("blocked action redirect payload", { url: metadata.redirect.url });
448
+ // Handle action redirect: server converted the redirect to a Flight payload
449
+ // so we can perform SPA navigation instead of a full page reload.
450
+ // Check handle.signal.aborted to avoid redirecting from a stale action
451
+ // when the user has already navigated away.
452
+ if (metadata?.redirect && !handle.signal.aborted) {
453
+ // Explicit off-host redirect (redirect(url, { external: true })):
454
+ // hard-navigate, but still scheme-validate (http/https only). external
455
+ // waives the same-origin check, NOT scheme safety, so a forged payload
456
+ // carrying a javascript:/data: URL cannot script via location.assign.
457
+ if (metadata.redirect.external) {
458
+ const externalUrl = validateExternalRedirect(
459
+ metadata.redirect.url,
460
+ window.location.origin,
461
+ );
462
+ if (!externalUrl) {
463
+ log("blocked external action redirect payload", {
464
+ url: metadata.redirect.url,
465
+ });
466
+ handle.complete(returnValue?.data);
467
+ return returnValue?.data;
468
+ }
469
+ log("external action redirect", { url: externalUrl });
470
+ handle.complete(returnValue?.data);
471
+ window.location.assign(externalUrl);
472
+ return returnValue?.data;
473
+ }
474
+ const redirectUrl = validateRedirectOrigin(
475
+ metadata.redirect.url,
476
+ window.location.origin,
477
+ );
478
+ if (!redirectUrl) {
479
+ log("blocked action redirect payload", {
480
+ url: metadata.redirect.url,
481
+ });
482
+ handle.complete(returnValue?.data);
483
+ return returnValue?.data;
484
+ }
485
+ log("action redirect", { url: redirectUrl });
329
486
  handle.complete(returnValue?.data);
487
+ await dispatchRedirect(redirectUrl, metadata.locationState);
330
488
  return returnValue?.data;
331
489
  }
332
- const redirectState = metadata.locationState;
333
- log("action redirect", { url: redirectUrl });
334
- handle.complete(returnValue?.data);
335
- if (onNavigate) {
336
- await onNavigate(redirectUrl, {
337
- state: redirectState,
338
- replace: true,
339
- _skipCache: true,
340
- });
341
- } else {
342
- window.location.href = redirectUrl;
490
+
491
+ // Bail out if the action was aborted after deserialization (e.g. user
492
+ // navigated away or abortAllActions was called while the Flight stream
493
+ // was being consumed). Without this check the code below would mutate
494
+ // the store / UI for a stale action.
495
+ if (handle.signal.aborted) {
496
+ log("action aborted after deserialization, skipping mutations");
497
+ return returnValue?.data;
343
498
  }
344
- return returnValue?.data;
345
- }
346
499
 
347
- // Bail out if the action was aborted after deserialization (e.g. user
348
- // navigated away or abortAllActions was called while the Flight stream
349
- // was being consumed). Without this check the code below would mutate
350
- // the store / UI for a stale action.
351
- if (handle.signal.aborted) {
352
- log("action aborted after deserialization, skipping mutations");
353
- return returnValue?.data;
354
- }
500
+ const { matched, diff, segments, isPartial, isError } = metadata || {};
355
501
 
356
- const { matched, diff, segments, isPartial, isError } = metadata || {};
502
+ // Log action result
503
+ if (returnValue && !returnValue.ok) {
504
+ console.error(`[Browser] Action failed:`, returnValue.data);
505
+ }
357
506
 
358
- // Log action result
359
- if (returnValue && !returnValue.ok) {
360
- console.error(`[Browser] Action failed:`, returnValue.data);
361
- }
507
+ // Handle error responses with error boundary UI
508
+ if (isError && isPartial && segments && diff) {
509
+ log("processing error boundary response");
362
510
 
363
- // Handle error responses with error boundary UI
364
- if (isError && isPartial && segments && diff) {
365
- log("processing error boundary response");
511
+ // Fail current handle BEFORE aborting all actions so the event controller
512
+ // records the error state (abortAllActions clears inflight entries)
513
+ if (returnValue && !returnValue.ok) {
514
+ handle.fail(returnValue.data);
515
+ }
366
516
 
367
- // Fail current handle BEFORE aborting all actions so the event controller
368
- // records the error state (abortAllActions clears inflight entries)
369
- if (returnValue && !returnValue.ok) {
370
- handle.fail(returnValue.data);
371
- }
517
+ // Abort all other pending action requests - error takes precedence
518
+ // This prevents other actions from completing and overwriting the error UI
519
+ eventController.abortAllActions();
520
+
521
+ // Clear concurrent action tracking - no consolidation needed when showing error
522
+ handle.clearConsolidation();
372
523
 
373
- // Abort all other pending action requests - error takes precedence
374
- // This prevents other actions from completing and overwriting the error UI
375
- eventController.abortAllActions();
524
+ // Get current page's cached segments
525
+ const currentKey = store.getHistoryKey();
526
+ const cached = store.getCachedSegments(currentKey);
527
+ const cachedSegments = cached?.segments || [];
376
528
 
377
- // Clear concurrent action tracking - no consolidation needed when showing error
378
- handle.clearConsolidation();
529
+ // Reconcile error segments with cached tree
530
+ const errorResult = reconcileErrorSegments(cachedSegments, segments);
379
531
 
380
- // Get current page's cached segments
381
- const currentKey = store.getHistoryKey();
382
- const cached = store.getCachedSegments(currentKey);
383
- const cachedSegments = cached?.segments || [];
532
+ // Render the full tree with error segment merged with parent layouts
533
+ const errorTree = await renderSegments(errorResult.mainSegments, {
534
+ isAction: true,
535
+ interceptSegments:
536
+ errorResult.interceptSegments.length > 0
537
+ ? errorResult.interceptSegments
538
+ : undefined,
539
+ });
384
540
 
385
- // Reconcile error segments with cached tree
386
- const errorResult = reconcileErrorSegments(cachedSegments, segments);
541
+ // Re-check route stability after async renderSegments — user may have
542
+ // navigated away while the error tree was being prepared.
543
+ if (window.location.pathname !== actionStartPathname) {
544
+ log("user navigated during error render, skipping");
545
+ if (returnValue && !returnValue.ok) {
546
+ throw returnValue.data;
547
+ }
548
+ handle.complete(undefined);
549
+ return undefined;
550
+ }
551
+ const currentKeyNow = store.getHistoryKey();
552
+ if (currentKeyNow !== currentKey) {
553
+ log("history key changed during error render, skipping cache update");
554
+ if (returnValue && !returnValue.ok) {
555
+ throw returnValue.data;
556
+ }
557
+ handle.complete(undefined);
558
+ return undefined;
559
+ }
387
560
 
388
- // Render the full tree with error segment merged with parent layouts
389
- const errorTree = await renderSegments(errorResult.mainSegments, {
390
- isAction: true,
391
- interceptSegments:
392
- errorResult.interceptSegments.length > 0
393
- ? errorResult.interceptSegments
394
- : undefined,
395
- });
561
+ // Update UI with error boundary
562
+ startTransition(() => {
563
+ onUpdate({ root: errorTree, metadata: metadata! });
564
+ });
396
565
 
397
- // Re-check route stability after async renderSegments — user may have
398
- // navigated away while the error tree was being prepared.
399
- if (window.location.pathname !== actionStartPathname) {
400
- log("user navigated during error render, skipping");
566
+ // Update segment tracking to exclude error segment IDs
567
+ const errorSegmentIds = new Set(diff);
568
+ const segmentIdsAfterError = segmentState.currentSegmentIds.filter(
569
+ (id) => !errorSegmentIds.has(id),
570
+ );
571
+
572
+ // Update store state
573
+ store.setSegmentIds(segmentIdsAfterError);
574
+ const currentHandleData = eventController.getHandleState().data;
575
+ store.cacheSegmentsForHistory(
576
+ currentKey,
577
+ errorResult.segments,
578
+ currentHandleData,
579
+ );
580
+
581
+ // Throw the error so the action promise rejects
401
582
  if (returnValue && !returnValue.ok) {
402
583
  throw returnValue.data;
403
584
  }
585
+
586
+ // No error in returnValue (shouldn't happen with isError: true)
404
587
  handle.complete(undefined);
405
588
  return undefined;
406
589
  }
407
- const currentKeyNow = store.getHistoryKey();
408
- if (currentKeyNow !== currentKey) {
409
- log("history key changed during error render, skipping cache update");
410
- if (returnValue && !returnValue.ok) {
411
- throw returnValue.data;
412
- }
413
- handle.complete(undefined);
414
- return undefined;
590
+
591
+ if (!isPartial) {
592
+ // Protocol invariant: action revalidation responses MUST be partial.
593
+ // The server always sends isPartial: true for successful revalidation
594
+ // and isPartial: true + isError: true for error boundary responses.
595
+ // A non-partial payload here indicates a server-side bug.
596
+ throw new Error(
597
+ `[Browser] Action response missing isPartial — the server must ` +
598
+ `always send partial payloads for action revalidation.`,
599
+ );
415
600
  }
416
601
 
417
- // Update UI with error boundary
418
- startTransition(() => {
419
- onUpdate({ root: errorTree, metadata: metadata! });
602
+ log("processing partial update", {
603
+ serverSegments: segments?.length ?? 0,
604
+ diff: diff?.join(", ") ?? "",
605
+ matched: matched?.join(", ") ?? "",
420
606
  });
421
607
 
422
- // Update segment tracking to exclude error segment IDs
423
- const errorSegmentIds = new Set(diff);
424
- const segmentIdsAfterError = segmentState.currentSegmentIds.filter(
425
- (id) => !errorSegmentIds.has(id),
426
- );
608
+ // Record revalidated segments for concurrent action tracking
609
+ if (diff) {
610
+ handle.recordRevalidatedSegments(diff);
611
+ }
427
612
 
428
- // Update store state
429
- store.setSegmentIds(segmentIdsAfterError);
430
- const currentHandleData = eventController.getHandleState().data;
431
- store.cacheSegmentsForHistory(
432
- currentKey,
433
- errorResult.segments,
434
- currentHandleData,
435
- );
613
+ // Get current page's cached segments for merging
614
+ const currentKey = store.getHistoryKey();
615
+ const cached = store.getCachedSegments(currentKey);
616
+ const cachedSegments = cached?.segments || [];
617
+
618
+ if (!matched) {
619
+ throw new Error("No matched segments in response");
620
+ }
621
+
622
+ // Reconcile server segments with cached segments (single source of truth)
623
+ const reconciled = reconcileSegments({
624
+ actor: "action",
625
+ matched,
626
+ diff: diff || [],
627
+ serverSegments: segments || [],
628
+ cachedSegments,
629
+ });
630
+ const fullSegments = reconciled.segments;
631
+
632
+ const returnData = returnValue?.data;
436
633
 
437
- // Throw the error so the action promise rejects
438
634
  if (returnValue && !returnValue.ok) {
635
+ handle.fail(returnValue.data);
439
636
  throw returnValue.data;
440
637
  }
441
638
 
442
- // No error in returnValue (shouldn't happen with isError: true)
443
- handle.complete(undefined);
444
- return undefined;
445
- }
639
+ // Classify the post-reconciliation scenario
640
+ const scenario = classifyActionOutcome({
641
+ handleId: handle.id,
642
+ inflightActions: eventController.getInflightActions(),
643
+ hadAnyConcurrentActions: eventController.hadAnyConcurrentActions(),
644
+ revalidatedSegments: handle.getRevalidatedSegments(),
645
+ actionStartPathname,
646
+ currentPathname: window.location.pathname,
647
+ actionStartLocationKey: locationKey,
648
+ currentLocationKey: window.history.state?.key,
649
+ reconciledSegmentCount: fullSegments.length,
650
+ matchedCount: matched.length,
651
+ currentInterceptSource: store.getInterceptSourceUrl(),
652
+ });
446
653
 
447
- if (!isPartial) {
448
- // Protocol invariant: action revalidation responses MUST be partial.
449
- // The server always sends isPartial: true for successful revalidation
450
- // and isPartial: true + isError: true for error boundary responses.
451
- // A non-partial payload here indicates a server-side bug.
452
- throw new Error(
453
- `[Browser] Action response missing isPartial — the server must ` +
454
- `always send partial payloads for action revalidation.`,
455
- );
456
- }
654
+ // Apply server-set location state exhaustively here, as a successful-
655
+ // response effect — the terminal switch below decides rendering/refetch,
656
+ // not whether this metadata survives (every refetch path is storeOnly and
657
+ // never writes history.state). Gated on NOT navigated-away: the classifier
658
+ // treats either a pathname OR history-key change as diversion, so this
659
+ // both honors the "diverted state is dropped" contract AND prevents a
660
+ // cross-entry write (mergeLocationState writes the CURRENT entry, which a
661
+ // navigated-away action no longer owns). Done before the switch (and
662
+ // before the normal branch's async renderSegments) so a slow render racing
663
+ // a navigation cannot drop it.
664
+ if (scenario.type !== "navigated-away") {
665
+ applyActionLocationState(handle, metadata?.locationState);
666
+ }
457
667
 
458
- log("processing partial update", {
459
- serverSegments: segments?.length ?? 0,
460
- diff: diff?.join(", ") ?? "",
461
- matched: matched?.join(", ") ?? "",
462
- });
668
+ switch (scenario.type) {
669
+ case "navigated-away": {
670
+ log("user navigated away during action", {
671
+ from: actionStartPathname,
672
+ to: window.location.pathname,
673
+ historyKeyChanged: scenario.historyKeyChanged,
674
+ });
675
+ // Clear concurrent action tracking - don't consolidate for old route's segments
676
+ handle.clearConsolidation();
677
+
678
+ if (scenario.historyKeyChanged) {
679
+ // Invalidation is deferred to finalizeAction(); here we only trigger
680
+ // the revalidation refetch of the new route (suppressed on keep).
681
+ if (!scenario.onInterceptRoute && !keepCache) {
682
+ refetchRoute().catch((error) => {
683
+ if (isBackgroundSuppressible(error)) return;
684
+ console.error(
685
+ "[Browser] Background revalidation failed:",
686
+ error,
687
+ );
688
+ });
689
+ }
690
+ break;
691
+ }
463
692
 
464
- // Record revalidated segments for concurrent action tracking
465
- if (diff) {
466
- handle.recordRevalidatedSegments(diff);
467
- }
693
+ // Same history key but different pathname - safe to refetch current
694
+ // route. Invalidation is deferred to finalizeAction(); here we only
695
+ // trigger the revalidation refetch (suppressed on keep).
696
+ if (!keepCache) {
697
+ await refetchRoute({
698
+ interceptSourceUrl: store.getInterceptSourceUrl(),
699
+ });
700
+ }
701
+ break;
702
+ }
468
703
 
469
- // Get current page's cached segments for merging
470
- const currentKey = store.getHistoryKey();
471
- const cached = store.getCachedSegments(currentKey);
472
- const cachedSegments = cached?.segments || [];
704
+ case "hmr-missing": {
705
+ console.warn(
706
+ `[Browser] Missing segments after action (HMR detected), refetching...`,
707
+ );
708
+ // Repair (not revalidation), so ungated on keepCache: a keep action
709
+ // resolving last must discharge a directive-free sibling's repair.
710
+ // See the keep row in docs/design/rango-state-cookie.md (the all-keep
711
+ // edge, and the benign re-mark-stale-after-refetch end-state delta).
712
+ await refetchRoute({ interceptSourceUrl });
713
+ break;
714
+ }
473
715
 
474
- if (!matched) {
475
- throw new Error("No matched segments in response");
476
- }
716
+ case "consolidation-needed": {
717
+ log("consolidation fetch needed", {
718
+ segmentIds: scenario.segmentIds,
719
+ });
720
+ // Location state already applied above (pre-switch). Calculate
721
+ // segments to send (exclude the ones we want fresh).
722
+ const currentSegmentIds = store.getSegmentState().currentSegmentIds;
723
+ const segmentsToSend = currentSegmentIds.filter(
724
+ (sid) => !scenario.segmentIds.includes(sid),
725
+ );
477
726
 
478
- // Reconcile server segments with cached segments (single source of truth)
479
- const reconciled = reconcileSegments({
480
- actor: "action",
481
- matched,
482
- diff: diff || [],
483
- serverSegments: segments || [],
484
- cachedSegments,
485
- });
486
- const fullSegments = reconciled.segments;
487
-
488
- const returnData = returnValue?.data;
489
-
490
- if (returnValue && !returnValue.ok) {
491
- handle.fail(returnValue.data);
492
- throw returnValue.data;
493
- }
727
+ // Clear consolidation tracking before fetch
728
+ handle.clearConsolidation();
494
729
 
495
- // Classify the post-reconciliation scenario
496
- const scenario = classifyActionOutcome({
497
- handleId: handle.id,
498
- inflightActions: eventController.getInflightActions(),
499
- hadAnyConcurrentActions: eventController.hadAnyConcurrentActions(),
500
- revalidatedSegments: handle.getRevalidatedSegments(),
501
- actionStartPathname,
502
- currentPathname: window.location.pathname,
503
- actionStartLocationKey: locationKey,
504
- currentLocationKey: window.history.state?.key,
505
- reconciledSegmentCount: fullSegments.length,
506
- matchedCount: matched.length,
507
- currentInterceptSource: store.getInterceptSourceUrl(),
508
- });
509
-
510
- switch (scenario.type) {
511
- case "navigated-away": {
512
- log("user navigated away during action", {
513
- from: actionStartPathname,
514
- to: window.location.pathname,
515
- historyKeyChanged: scenario.historyKeyChanged,
516
- });
517
- // Clear concurrent action tracking - don't consolidate for old route's segments
518
- handle.clearConsolidation();
730
+ // Ungated on keepCache, same as hmr-missing above (see the keep row).
731
+ await refetchRoute({
732
+ segments: segmentsToSend,
733
+ interceptSourceUrl,
734
+ });
735
+ break;
736
+ }
519
737
 
520
- if (scenario.historyKeyChanged) {
521
- if (!scenario.onInterceptRoute) {
522
- store.markCacheAsStaleAndBroadcast();
523
- refetchRoute().catch((error) => {
524
- if (isBackgroundSuppressible(error)) return;
525
- console.error("[Browser] Background revalidation failed:", error);
526
- });
738
+ case "concurrent-skip": {
739
+ log("skipping UI update, other actions fetching", {
740
+ otherCount: scenario.otherFetchingCount,
741
+ });
742
+ // Only update store if history key hasn't changed (user didn't navigate away)
743
+ const currentKeyNow = store.getHistoryKey();
744
+ if (currentKeyNow === currentKey) {
745
+ // Location state already applied above (pre-switch); this action's
746
+ // UI render is skipped because a later sibling consolidates.
747
+ store.setSegmentIds(matched);
748
+ const currentHandleData = eventController.getHandleState().data;
749
+ store.cacheSegmentsForHistory(
750
+ currentKey,
751
+ fullSegments,
752
+ currentHandleData,
753
+ );
527
754
  }
528
755
  break;
529
756
  }
530
757
 
531
- // Same history key but different pathname - safe to refetch current route
532
- store.markCacheAsStaleAndBroadcast();
533
- await refetchRoute({
534
- interceptSourceUrl: store.getInterceptSourceUrl(),
535
- });
536
- break;
537
- }
538
-
539
- case "hmr-missing": {
540
- console.warn(
541
- `[Browser] Missing segments after action (HMR detected), refetching...`,
542
- );
543
- await refetchRoute({ interceptSourceUrl });
544
- store.broadcastCacheInvalidation();
545
- break;
546
- }
758
+ case "normal": {
759
+ // Prepare new tree (await loader data resolution)
760
+ const newTree = await renderSegments(reconciled.mainSegments, {
761
+ isAction: true,
762
+ interceptSegments:
763
+ reconciled.interceptSegments.length > 0
764
+ ? reconciled.interceptSegments
765
+ : undefined,
766
+ });
547
767
 
548
- case "consolidation-needed": {
549
- log("consolidation fetch needed", { segmentIds: scenario.segmentIds });
550
- // Calculate segments to send (exclude the ones we want fresh)
551
- const currentSegmentIds = store.getSegmentState().currentSegmentIds;
552
- const segmentsToSend = currentSegmentIds.filter(
553
- (sid) => !scenario.segmentIds.includes(sid),
554
- );
768
+ // Re-check if user navigated away (could happen during async renderSegments)
769
+ if (window.location.pathname !== actionStartPathname) {
770
+ log("user navigated during render, skipping");
771
+ break;
772
+ }
555
773
 
556
- // Clear consolidation tracking before fetch
557
- handle.clearConsolidation();
774
+ // Verify the store's current key still matches what we captured at action start
775
+ // If they differ, user navigated away and we should NOT cache under the old key
776
+ const currentKeyNow = store.getHistoryKey();
777
+ if (currentKeyNow !== currentKey) {
778
+ log("history key changed during action, skipping cache update");
779
+ break;
780
+ }
558
781
 
559
- await refetchRoute({
560
- segments: segmentsToSend,
561
- interceptSourceUrl,
562
- });
563
- store.broadcastCacheInvalidation();
564
- break;
565
- }
782
+ startTransition(() => {
783
+ onUpdate({ root: newTree, metadata: metadata! });
784
+ });
566
785
 
567
- case "concurrent-skip": {
568
- log("skipping UI update, other actions fetching", {
569
- otherCount: scenario.otherFetchingCount,
570
- });
571
- // Only update store if history key hasn't changed (user didn't navigate away)
572
- const currentKeyNow = store.getHistoryKey();
573
- if (currentKeyNow === currentKey) {
786
+ // Location state already applied above (pre-switch). Update store.
574
787
  store.setSegmentIds(matched);
575
788
  const currentHandleData = eventController.getHandleState().data;
576
789
  store.cacheSegmentsForHistory(
@@ -578,59 +791,23 @@ export function createServerActionBridge(
578
791
  fullSegments,
579
792
  currentHandleData,
580
793
  );
581
- }
582
- break;
583
- }
584
-
585
- case "normal": {
586
- // Prepare new tree (await loader data resolution)
587
- const newTree = await renderSegments(reconciled.mainSegments, {
588
- isAction: true,
589
- interceptSegments:
590
- reconciled.interceptSegments.length > 0
591
- ? reconciled.interceptSegments
592
- : undefined,
593
- });
594
-
595
- // Re-check if user navigated away (could happen during async renderSegments)
596
- if (window.location.pathname !== actionStartPathname) {
597
- log("user navigated during render, skipping");
598
- break;
599
- }
600
-
601
- // Verify the store's current key still matches what we captured at action start
602
- // If they differ, user navigated away and we should NOT cache under the old key
603
- const currentKeyNow = store.getHistoryKey();
604
- if (currentKeyNow !== currentKey) {
605
- log("history key changed during action, skipping cache update");
794
+ // Invalidation deferred to finalizeAction() (runs after this caches
795
+ // the fresh segments), suppressed when the action called
796
+ // keepClientCache().
606
797
  break;
607
798
  }
608
-
609
- startTransition(() => {
610
- onUpdate({ root: newTree, metadata: metadata! });
611
- });
612
-
613
- // Apply server-set location state to history.state (non-redirect flow)
614
- const actionLocationState = metadata?.locationState;
615
- if (actionLocationState) {
616
- mergeLocationState(actionLocationState);
617
- }
618
-
619
- // Update store state
620
- store.setSegmentIds(matched);
621
- const currentHandleData = eventController.getHandleState().data;
622
- store.cacheSegmentsForHistory(
623
- currentKey,
624
- fullSegments,
625
- currentHandleData,
626
- );
627
- store.markCacheAsStaleAndBroadcast();
628
- break;
629
799
  }
630
- }
631
800
 
632
- handle.complete(returnData);
633
- return returnData;
801
+ handle.complete(returnData);
802
+ return returnData;
803
+ } finally {
804
+ // The single deferred invalidation + fence release for this action. Runs
805
+ // for every terminal that settles (normal, navigated-away, error, abort,
806
+ // intercept, concurrent); the SPA-redirect paths above already ran it.
807
+ // Latched, so it fires exactly once.
808
+ finalizeAction();
809
+ handle[Symbol.dispose]();
810
+ }
634
811
  }
635
812
 
636
813
  return {