@solidjs/router 0.17.0-next.6 → 1.0.0-next.7

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 (48) hide show
  1. package/README.md +526 -716
  2. package/dist/claims.d.ts +21 -0
  3. package/dist/claims.js +108 -0
  4. package/dist/data/action.d.ts +15 -0
  5. package/dist/data/action.js +127 -12
  6. package/dist/data/events.d.ts +8 -0
  7. package/dist/data/events.js +23 -22
  8. package/dist/data/flash.d.ts +1 -5
  9. package/dist/data/flash.js +10 -18
  10. package/dist/data/flashCookie.d.ts +7 -0
  11. package/dist/data/flashCookie.js +20 -0
  12. package/dist/data/serverForms.d.ts +1 -0
  13. package/dist/data/serverForms.js +5 -0
  14. package/dist/index.d.ts +5 -3
  15. package/dist/index.js +1728 -1158
  16. package/dist/index.jsx +2 -2
  17. package/dist/lifecycle.d.ts +29 -4
  18. package/dist/lifecycle.js +40 -37
  19. package/dist/paths.d.ts +117 -0
  20. package/dist/paths.js +41 -0
  21. package/dist/routers/components.d.ts +10 -21
  22. package/dist/routers/components.jsx +29 -51
  23. package/dist/routers/factory.d.ts +45 -0
  24. package/dist/routers/factory.jsx +143 -0
  25. package/dist/routers/history.d.ts +24 -0
  26. package/dist/routers/history.js +180 -0
  27. package/dist/routers/index.d.ts +4 -11
  28. package/dist/routers/index.js +2 -6
  29. package/dist/routing.d.ts +79 -52
  30. package/dist/routing.js +296 -127
  31. package/dist/server.d.ts +25 -15
  32. package/dist/server.js +43 -7
  33. package/dist/types.d.ts +74 -5
  34. package/dist/utils.d.ts +2 -0
  35. package/dist/utils.js +2 -0
  36. package/package.json +6 -6
  37. package/dist/components.d.ts +0 -31
  38. package/dist/components.jsx +0 -46
  39. package/dist/routers/HashRouter.d.ts +0 -9
  40. package/dist/routers/HashRouter.js +0 -41
  41. package/dist/routers/MemoryRouter.d.ts +0 -24
  42. package/dist/routers/MemoryRouter.js +0 -57
  43. package/dist/routers/Router.d.ts +0 -9
  44. package/dist/routers/Router.js +0 -45
  45. package/dist/routers/StaticRouter.d.ts +0 -6
  46. package/dist/routers/StaticRouter.js +0 -15
  47. package/dist/routers/createRouter.d.ts +0 -10
  48. package/dist/routers/createRouter.js +0 -40
package/dist/index.js CHANGED
@@ -1,87 +1,6 @@
1
- import { isServer, getRequestEvent, isResponseEnvelope, createComponent as createComponent$1, memo, delegateEvents, spread, mergeProps, template } from '@solidjs/web';
2
- import { getOwner, runWithOwner, createMemo, createContext, onCleanup, useContext, untrack, children, createSignal, flush, createComponent, getObserver, sharedConfig, $TRACK, action as action$1, merge, createRoot, omit } from 'solid-js';
3
- import { isServerFunction, getServerFunctionMetadata, GET, decodeResponse, subscribeFlightData } from '@solidjs/web/server-functions';
4
-
5
- function createBeforeLeave() {
6
- let listeners = new Set();
7
- function subscribe(listener) {
8
- listeners.add(listener);
9
- return () => listeners.delete(listener);
10
- }
11
- let ignore = false;
12
- function confirm(to, options) {
13
- if (ignore) return !(ignore = false);
14
- const e = {
15
- to,
16
- options,
17
- defaultPrevented: false,
18
- preventDefault: () => e.defaultPrevented = true
19
- };
20
- for (const l of listeners) l.listener({
21
- to,
22
- options,
23
- // delegate to the shared event so later listeners' preventDefault
24
- // calls are observable from earlier listeners
25
- get defaultPrevented() {
26
- return e.defaultPrevented;
27
- },
28
- preventDefault: e.preventDefault,
29
- from: l.location,
30
- retry: force => {
31
- force && (ignore = true);
32
- l.navigate(to, {
33
- ...options,
34
- resolve: false
35
- });
36
- }
37
- });
38
- return !e.defaultPrevented;
39
- }
40
- return {
41
- subscribe,
42
- confirm
43
- };
44
- }
45
-
46
- // The following supports browser initiated blocking (eg back/forward)
47
-
48
- let depth;
49
- function saveCurrentDepth() {
50
- if (!window.history.state || window.history.state._depth == null) {
51
- window.history.replaceState({
52
- ...window.history.state,
53
- _depth: window.history.length - 1
54
- }, "");
55
- }
56
- depth = window.history.state._depth;
57
- }
58
- if (!isServer) {
59
- saveCurrentDepth();
60
- }
61
- function keepDepth(state) {
62
- return {
63
- ...state,
64
- _depth: window.history.state && window.history.state._depth
65
- };
66
- }
67
- function notifyIfNotBlocked(notify, block) {
68
- let ignore = false;
69
- return () => {
70
- const prevDepth = depth;
71
- saveCurrentDepth();
72
- const delta = prevDepth == null ? null : depth - prevDepth;
73
- if (ignore) {
74
- ignore = false;
75
- return;
76
- }
77
- if (delta && block(delta)) {
78
- ignore = true;
79
- window.history.go(-delta);
80
- } else {
81
- notify();
82
- }
83
- };
84
- }
1
+ import { getOwner, runWithOwner, createMemo, createRenderEffect, onCleanup, untrack, createContext, createSignal, useContext, NotReadyError, flush, createComponent, createRoot, sharedConfig, getObserver, $TRACK, action as action$1 } from 'solid-js';
2
+ import { registerElementClaim, delegateEvents, isServer, getRequestEvent, createComponent as createComponent$1, memo, isResponseEnvelope } from '@solidjs/web';
3
+ import { isServerFunction, getServerFunctionMetadata, GET, decodeResponse, subscribeFlightData, createServerReference } from '@solidjs/web/server-functions';
85
4
 
86
5
  const hasSchemeRegex = /^(?:[a-z0-9]+:)?\/\//i;
87
6
  const trimPathRegex = /^\/+|(\/)\/+$/g;
@@ -90,6 +9,9 @@ function normalizePath(path, omitSlash = false) {
90
9
  const s = path.replace(trimPathRegex, "$1");
91
10
  return s ? omitSlash || /^[?#]/.test(s) ? s : "/" + s : "";
92
11
  }
12
+
13
+ /** Pathname stripped of search/hash and trailing slash, lowercased — the form link matching compares. */
14
+ const comparablePath = path => normalizePath(path.split(/[?#]/, 1)[0]).toLowerCase().replace(/\/$/, "");
93
15
  function resolvePath(base, path, from) {
94
16
  if (hasSchemeRegex.test(path)) {
95
17
  return undefined;
@@ -258,74 +180,357 @@ function setFunctionName(obj, value) {
258
180
  return obj;
259
181
  }
260
182
 
261
- // The no-JS form convention's cookie codec. When a form posts to a server
262
- // function without the client runtime (no instance header), the server
263
- // handler redirects back carrying the outcome in a one-shot "flash" cookie;
264
- // the next SSR pass reads it here and seeds the router's submission state so
265
- // useSubmission() renders the result exactly as a scripted submission would.
266
- // Both halves live in this module so the write (src/server.ts, the handler's
267
- // handleNoJS) and the read (src/routing.ts, SSR initialization) can never
268
- // drift apart.
183
+ /**
184
+ * The compiler claims every `a[href]` (and `form[action]`, which this handler
185
+ * ignores) at creation, and the runtime re-claims on `href` writes. This
186
+ * consumer gives each router-managed anchor the link-state vocabulary without
187
+ * a wrapper component:
188
+ *
189
+ * - `aria-current="page"` — the location matches the link exactly
190
+ * - `data-active` — exact or prefix match
191
+ * - `data-pending` — the link is the target of an in-flight navigation
192
+ *
193
+ * Elements are claimed at creation, so late mounts (`<Show>`, `<For>`,
194
+ * portals) are correct immediately. One render effect (owned by the router)
195
+ * subscribes to the location and sweeps a registry of claimed anchors —
196
+ * anchors themselves carry no reactive machinery, just a registry entry
197
+ * removed by their creating owner's cleanup. State is applied once at claim
198
+ * so it is correct before the next navigation; re-claims (an `href` write)
199
+ * are the same one-shot untracked refresh, reading the element's current
200
+ * `href` from the DOM.
201
+ */
202
+ function setupLinkClaims(router, explicitLinks) {
203
+ const basePath = router.base.path();
204
+ // per-element record; `current` remembers whether we set `aria-current`,
205
+ // so user-authored values (steppers, breadcrumbs) are never stripped
206
+ const claimed = new WeakMap();
207
+ const registry = new Set();
208
+ function isSvg(el) {
209
+ return el.namespaceURI === "http://www.w3.org/2000/svg";
210
+ }
269
211
 
270
- const FLASH_COOKIE = "flash";
271
- function decodeInputValue(value) {
272
- if (value && typeof value === "object") {
273
- if (Array.isArray(value.$f)) {
274
- const form = new FormData();
275
- for (const [k, v] of value.$f) form.append(k, v);
276
- return form;
212
+ /** The comparable pathname when the router manages this anchor, else `undefined`. */
213
+ function managedPath(a) {
214
+ if (explicitLinks && !a.hasAttribute("link")) return;
215
+ const svg = isSvg(a);
216
+ // claims fire at creation while the element is still in the template's
217
+ // inert fragment, where the `href` property is not resolved — resolve the
218
+ // raw attribute against the live document instead
219
+ const href = svg ? a.href.baseVal : a.getAttribute("href");
220
+ const target = svg ? a.target.baseVal : a.target;
221
+ if (target || !href) return;
222
+ const rel = (a.getAttribute("rel") || "").split(/\s+/);
223
+ if (a.hasAttribute("download") || rel.includes("external")) return;
224
+ let url;
225
+ try {
226
+ url = new URL(href, document.baseURI);
227
+ } catch {
228
+ return;
277
229
  }
278
- if (Array.isArray(value.$u)) return new URLSearchParams(value.$u);
230
+ if (url.origin !== window.location.origin || basePath && url.pathname && !url.pathname.toLowerCase().startsWith(basePath.toLowerCase())) return;
231
+ return comparablePath(url.pathname);
279
232
  }
280
- return value;
233
+ function linkState(a) {
234
+ // read reactive sources unconditionally so the owning effect stays
235
+ // subscribed even while the anchor is not router-managed
236
+ const loc = decodeURI(comparablePath(router.location.pathname));
237
+ const routing = router.isRouting();
238
+ const path = managedPath(a);
239
+ // the root path is a prefix of everything, so it only matches exactly —
240
+ // there is no per-anchor `end` opt-out like useLinkState has
241
+ const matches = target => path !== undefined && (target === path || path !== "" && target.startsWith(path + "/"));
242
+ // effects observe the committed location during a transition, so the
243
+ // in-flight target comes from pendingTarget — readable here because the
244
+ // isRouting write flushes after the target is assigned
245
+ const pending = routing && !!router.pendingTarget && matches(decodeURI(comparablePath(router.pendingTarget.value)));
246
+ return {
247
+ active: matches(loc),
248
+ pending,
249
+ exact: path !== undefined && loc === path
250
+ };
251
+ }
252
+ function apply(a, rec, {
253
+ active,
254
+ pending,
255
+ exact
256
+ }) {
257
+ active ? a.setAttribute("data-active", "") : a.removeAttribute("data-active");
258
+ pending ? a.setAttribute("data-pending", "") : a.removeAttribute("data-pending");
259
+ if (exact !== rec.current) {
260
+ exact ? a.setAttribute("aria-current", "page") : a.removeAttribute("aria-current");
261
+ rec.current = exact;
262
+ }
263
+ }
264
+ const refresh = (a, rec) => untrack(() => apply(a, rec, linkState(a)));
265
+
266
+ // The one subscription for every anchor: compute tracks the sources
267
+ // linkState derives from (the in-flight pendingTarget is readable in the
268
+ // effect phase because the isRouting write flushes after the target is
269
+ // assigned), the effect phase sweeps the registry untracked.
270
+ createRenderEffect(() => (router.location.pathname, router.isRouting()), () => registry.forEach(a => refresh(a, claimed.get(a))));
271
+ onCleanup(registerElementClaim(node => {
272
+ if (node.nodeName.toUpperCase() !== "A") return;
273
+ const a = node;
274
+ // re-claim (href changed): the claiming write runs inside another
275
+ // effect, so refresh without leaking subscriptions into it
276
+ const existing = claimed.get(a);
277
+ if (existing) return refresh(a, existing);
278
+ const rec = {
279
+ current: false
280
+ };
281
+ claimed.set(a, rec);
282
+ // claims fire during component setup, so an owner is present in
283
+ // practice to bound the registry entry's lifetime; without one, state
284
+ // is still applied once at creation
285
+ if (getOwner()) {
286
+ registry.add(a);
287
+ onCleanup(() => registry.delete(a));
288
+ }
289
+ refresh(a, rec);
290
+ }));
281
291
  }
282
292
 
283
- /** The Set-Cookie value clearing the flash cookie after it has been read. */
284
- function clearFlashCookie() {
285
- return `${FLASH_COOKIE}=; Max-Age=0; Path=/`;
293
+ /**
294
+ * The submit delegation consults this slot instead of importing the action
295
+ * module: the action side installs its handler on first action creation
296
+ * (see data/action.ts), so an app that never creates an action never pulls
297
+ * the data layer into its bundle through the router's event wiring.
298
+ */
299
+
300
+ let formHandler;
301
+ function setRouterFormHandler(handler) {
302
+ formHandler = handler;
286
303
  }
287
- const FLASH_MATCHER = new RegExp(`(?:^|;\\s*)${FLASH_COOKIE}=([^;]+)`);
304
+ function setupNativeEvents({
305
+ preload = true,
306
+ explicitLinks = false,
307
+ actionBase = "/_server",
308
+ transformUrl
309
+ } = {}) {
310
+ return router => {
311
+ const basePath = router.base.path();
312
+ const navigateFromRoute = router.navigatorFactory(router.base);
313
+ let preloadTimeout;
314
+ let lastElement;
315
+ function isSvg(el) {
316
+ return el.namespaceURI === "http://www.w3.org/2000/svg";
317
+ }
318
+ function handleAnchor(evt) {
319
+ if (evt.defaultPrevented || evt.button !== 0 || evt.metaKey || evt.altKey || evt.ctrlKey || evt.shiftKey) return;
320
+ const a = evt.composedPath().find(el => el instanceof Node && el.nodeName.toUpperCase() === "A");
321
+ if (!a || explicitLinks && !a.hasAttribute("link")) return;
322
+ const svg = isSvg(a);
323
+ const href = svg ? a.href.baseVal : a.href;
324
+ const target = svg ? a.target.baseVal : a.target;
325
+ if (target || !href && !a.hasAttribute("state")) return;
326
+ const rel = (a.getAttribute("rel") || "").split(/\s+/);
327
+ if (a.hasAttribute("download") || rel && rel.includes("external")) return;
328
+ const url = svg ? new URL(href, document.baseURI) : new URL(href);
329
+ if (url.origin !== window.location.origin || basePath && url.pathname && !url.pathname.toLowerCase().startsWith(basePath.toLowerCase())) return;
330
+ return [a, url];
331
+ }
332
+ function handleAnchorClick(evt) {
333
+ const res = handleAnchor(evt);
334
+ if (!res) return;
335
+ const [a, url] = res;
336
+ const to = router.parsePath(url.pathname + url.search + url.hash);
337
+ const state = a.getAttribute("state");
338
+ evt.preventDefault();
339
+ navigateFromRoute(to, {
340
+ resolve: false,
341
+ replace: a.hasAttribute("replace"),
342
+ scroll: !a.hasAttribute("noscroll"),
343
+ state: state ? JSON.parse(state) : undefined
344
+ });
345
+ }
346
+ function handleAnchorPreload(evt) {
347
+ const res = handleAnchor(evt);
348
+ if (!res) return;
349
+ const [a, url] = res;
350
+ transformUrl && (url.pathname = transformUrl(url.pathname));
351
+ router.preloadRoute(url, a.getAttribute("preload") !== "false");
352
+ }
353
+ function handleAnchorMove(evt) {
354
+ clearTimeout(preloadTimeout);
355
+ const res = handleAnchor(evt);
356
+ if (!res) return lastElement = null;
357
+ const [a, url] = res;
358
+ if (lastElement === a) return;
359
+ transformUrl && (url.pathname = transformUrl(url.pathname));
360
+ preloadTimeout = setTimeout(() => {
361
+ router.preloadRoute(url, a.getAttribute("preload") !== "false");
362
+ lastElement = a;
363
+ }, 20);
364
+ }
365
+ function handleFormSubmit(evt) {
366
+ if (formHandler) return formHandler(evt, router, actionBase);
367
+ // No form handler means no action module in the client graph at all
368
+ // (e.g. server components binding forms straight to server functions).
369
+ // A POST to a url under actionBase is self-describing, so delegation
370
+ // is still sufficient: intercept synchronously — the no-JS treatment
371
+ // is reserved for clients with no JS — capture the FormData, and load
372
+ // the handler lazily. Apps that never submit one never load it.
373
+ if (evt.defaultPrevented) return;
374
+ const form = evt.target;
375
+ const ref = evt.submitter && evt.submitter.hasAttribute("formaction") ? evt.submitter.getAttribute("formaction") : form.getAttribute("action");
376
+ if (!ref || ref.startsWith("https://action/")) return;
377
+ const url = new URL(ref, document.baseURI);
378
+ const path = router.parsePath(url.pathname + url.search);
379
+ if (!path.startsWith(actionBase) || form.method.toUpperCase() !== "POST") return;
380
+ evt.preventDefault();
381
+ const data = new FormData(form, evt.submitter);
382
+ Promise.resolve().then(function () { return serverForms; }).then(m => m.submitServerForm(router, path, form, data));
383
+ }
288
384
 
289
- /** Whether a Cookie header carries a flash cookie (readable or not). */
290
- function hasFlashCookie(cookieHeader) {
291
- return !!cookieHeader && FLASH_MATCHER.test(cookieHeader);
385
+ // ensure delegated event run first
386
+ delegateEvents(["click", "submit"]);
387
+ document.addEventListener("click", handleAnchorClick);
388
+ if (preload) {
389
+ document.addEventListener("mousemove", handleAnchorMove, {
390
+ passive: true
391
+ });
392
+ document.addEventListener("focusin", handleAnchorPreload, {
393
+ passive: true
394
+ });
395
+ document.addEventListener("touchstart", handleAnchorPreload, {
396
+ passive: true
397
+ });
398
+ }
399
+ document.addEventListener("submit", handleFormSubmit);
400
+ onCleanup(() => {
401
+ document.removeEventListener("click", handleAnchorClick);
402
+ if (preload) {
403
+ document.removeEventListener("mousemove", handleAnchorMove);
404
+ document.removeEventListener("focusin", handleAnchorPreload);
405
+ document.removeEventListener("touchstart", handleAnchorPreload);
406
+ }
407
+ document.removeEventListener("submit", handleFormSubmit);
408
+ });
409
+ };
292
410
  }
293
411
 
412
+ /*
413
+ * The typed path proxy. Property access descends into static segments, calls
414
+ * bind params, and a zero-arg or search-object call terminates to a plain
415
+ * string. The runtime is tree-agnostic — it just builds strings — while the
416
+ * `RoutePaths<R>` type derived from the route config constrains which
417
+ * accesses and calls exist. Every node also coerces via `toString`, so nodes
418
+ * drop straight into `href`, `navigate()`, and `redirect()`.
419
+ */
420
+
421
+ // ---------------------------------------------------------------------------
422
+ // Typed match filters
423
+ // ---------------------------------------------------------------------------
424
+
294
425
  /**
295
- * Decodes the flash cookie out of a request's Cookie header. Returns
296
- * undefined when absent or unreadable (a malformed cookie must never take
297
- * down SSR — it is cleared either way).
426
+ * A match filter that also declares the TypeScript type accepted for the
427
+ * param at `paths` callsites (the runtime param remains a string).
298
428
  */
299
- function decodeFlashCookie(cookieHeader) {
300
- if (!cookieHeader) return;
301
- const match = cookieHeader.match(FLASH_MATCHER);
302
- if (!match) return;
303
- try {
304
- const payload = JSON.parse(decodeURIComponent(match[1]));
305
- if (!payload || !payload.result) return;
306
- const result = payload.error ? new Error(payload.result) : payload.result;
307
- return {
308
- input: Array.isArray(payload.input) ? payload.input.map(decodeInputValue) : [],
309
- url: payload.url,
310
- result: payload.thrown ? undefined : result,
311
- error: payload.thrown ? result : undefined
429
+
430
+ /** Matches integer segments; types the param as `number` in the path proxy. */
431
+ const int = s => /^-?\d+$/.test(s);
432
+
433
+ // ---------------------------------------------------------------------------
434
+ // RoutePaths<R> — the proxy's type, derived from the route tree
435
+ // ---------------------------------------------------------------------------
436
+
437
+ /** Collects a maximal run of required params (and a trailing splat) into one call's argument tuple. */
438
+
439
+ /** The search param types a route end carries: input builds URLs, output is what parsing returns. */
440
+
441
+ /** Terminating calls available on every route end: zero-arg, or search object plus optional hash. */
442
+
443
+ /**
444
+ * Sees through a lazy `children` thunk: the routes the import's promise
445
+ * resolves to (its `default` or `routes` export, matching the runtime) type
446
+ * exactly like inline children. Only tables genuinely built at runtime —
447
+ * where the thunk's return type is a plain `RouteDefinition[]` — degrade to
448
+ * untyped, definitionally.
449
+ */
450
+
451
+ /**
452
+ * The type of a router instance's `paths` proxy for a given route tree.
453
+ * Requires the tree to be a literal tuple (`as const` or a `const` type
454
+ * param); non-literal trees fall back to an untyped proxy.
455
+ */
456
+
457
+ /** Extracts the params record a paths node binds, as runtime (string-valued) params. */
458
+
459
+ // ---------------------------------------------------------------------------
460
+ // Runtime
461
+ // ---------------------------------------------------------------------------
462
+
463
+ const encodeParam = value => String(value).split("/").map(encodeURIComponent).join("/");
464
+
465
+ /**
466
+ * Creates the runtime path proxy. It is instance-scoped: `renderPath` comes
467
+ * from the router's history adapter (eg. hash routing prefixes `#`), and
468
+ * `base` is baked into every produced path.
469
+ */
470
+ function createPathsProxy(renderPath = p => p, base = "") {
471
+ const toHref = (pathname, suffix = "") => renderPath(pathname || "/") + suffix;
472
+ function node(pathname) {
473
+ const build = (...args) => {
474
+ let path = pathname;
475
+ for (let i = 0; i < args.length; i++) {
476
+ const arg = args[i];
477
+ if (typeof arg === "object" && arg !== null) {
478
+ // a search object terminates; an optional hash string may follow
479
+ const hash = typeof args[i + 1] === "string" ? `#${args[i + 1]}` : "";
480
+ return toHref(path, mergeSearchString("", arg) + hash);
481
+ }
482
+ path += `/${encodeParam(arg)}`;
483
+ }
484
+ // zero-arg calls terminate; param-only calls stay chainable
485
+ return args.length ? node(path) : toHref(path);
312
486
  };
313
- } catch (error) {
314
- console.error(error);
487
+ return new Proxy(build, {
488
+ get(_, prop) {
489
+ if (prop === "toString") return () => toHref(pathname);
490
+ if (typeof prop === "symbol") return prop === Symbol.toPrimitive ? () => toHref(pathname) : undefined;
491
+ return node(`${pathname}/${prop}`);
492
+ }
493
+ });
315
494
  }
495
+ return node(normalizePath(base));
316
496
  }
317
497
 
318
- const MAX_REDIRECTS = 100;
498
+ // The flash cookie's name and one-shot clearing — split from the codec in
499
+ // flash.ts so the router core can consume the cookie eagerly (the clear must
500
+ // be appended before streaming flushes the response headers, and an unread
501
+ // outcome must not haunt a later request) without carrying the encode/decode
502
+ // machinery into client bundles that never load the action layer.
319
503
 
320
- /** Consider this API opaque and internal. It is likely to change in the future. */
321
- const RouterContextObj = createContext();
322
- const RouteContextObj = createContext();
323
- function useOptionalContext(context) {
324
- try {
325
- return useContext(context);
326
- } catch {
327
- return undefined;
328
- }
504
+ const FLASH_COOKIE = "flash";
505
+ const FLASH_MATCHER = new RegExp(`(?:^|;\\s*)${FLASH_COOKIE}=([^;]+)`);
506
+
507
+ /** Whether a Cookie header carries a flash cookie (readable or not). */
508
+ function hasFlashCookie(cookieHeader) {
509
+ return !!cookieHeader && FLASH_MATCHER.test(cookieHeader);
510
+ }
511
+
512
+ /** The raw encoded flash payload out of a Cookie header, if present. */
513
+ function matchFlashCookie(cookieHeader) {
514
+ const match = cookieHeader && cookieHeader.match(FLASH_MATCHER);
515
+ return match ? match[1] : undefined;
516
+ }
517
+
518
+ /** The Set-Cookie value clearing the flash cookie after it has been read. */
519
+ function clearFlashCookie() {
520
+ return `${FLASH_COOKIE}=; Max-Age=0; Path=/`;
521
+ }
522
+
523
+ const MAX_REDIRECTS = 100;
524
+
525
+ /** Consider this API opaque and internal. It is likely to change in the future. */
526
+ const RouterContextObj = createContext();
527
+ const RouteContextObj = createContext();
528
+ function useOptionalContext(context) {
529
+ try {
530
+ return useContext(context);
531
+ } catch {
532
+ return undefined;
533
+ }
329
534
  }
330
535
  const useRouter = () => invariant(useContext(RouterContextObj), "<A> and 'use' router primitives can be only used inside a Route.");
331
536
  const useRoute = () => useOptionalContext(RouteContextObj) || useRouter().base;
@@ -391,22 +596,6 @@ const useLocation = () => useRouter().location;
391
596
  */
392
597
  const useIsRouting = () => useRouter().isRouting;
393
598
 
394
- /**
395
- * usePreloadRoute returns a function that can be used to preload a route manual.
396
- * This is what happens automatically with link hovering and similar focus based behavior, but it is available here as an API.
397
- *
398
- * @example
399
- * ```js
400
- * const preload = usePreloadRoute();
401
- *
402
- * preload(`/users/settings`, { preloadData: true });
403
- * ```
404
- */
405
- const usePreloadRoute = () => {
406
- const pre = useRouter().preloadRoute;
407
- return (url, options = {}) => pre(url instanceof URL ? url : new URL(url, mockBase), options.preloadData);
408
- };
409
-
410
599
  /**
411
600
  * `useMatch` takes an accessor that returns the path and creates a `Memo` that returns match information if the current path matches the provided path.
412
601
  * Useful for determining if a given path matches the current route.
@@ -430,22 +619,42 @@ const useMatch = (path, matchFilters) => {
430
619
  };
431
620
 
432
621
  /**
433
- * `useCurrentMatches` returns all the matches for the current matched route.
434
- * Useful for getting all the route information.
435
- *
622
+ * `useRouteMatches` returns an accessor of the router's resolved matches for
623
+ * the current location — the chain of route definitions producing the current
624
+ * render, outermost first. Useful for reading `info` metadata off the matched
625
+ * chain. Unlike `useMatch`, which tests a path pattern you supply against the
626
+ * location, this reflects the route tree itself.
627
+ *
436
628
  * @example
437
629
  * ```js
438
- * const matches = useCurrentMatches();
439
- *
440
- * const breadcrumbs = createMemo(() => matches().map(m => m.route.info.breadcrumb))
630
+ * const matches = useRouteMatches();
631
+ *
632
+ * const breadcrumbs = createMemo(() => matches().map(m => m.route.info.breadcrumb));
441
633
  * ```
442
634
  */
443
- const useCurrentMatches = () => {
635
+ const useRouteMatches = () => {
444
636
  const router = useRouter();
445
637
  // return a copy so user mutations (eg. `.reverse()`) can't corrupt router state
446
638
  return () => router.matches().slice();
447
639
  };
448
640
 
641
+ /**
642
+ * `usePreloadRoute` returns a function for warming a route by hand — the same
643
+ * work link hover/focus intent triggers automatically: the matched routes'
644
+ * lazy components load, and with `preloadData` their `preload` functions run.
645
+ *
646
+ * @example
647
+ * ```js
648
+ * const preload = usePreloadRoute();
649
+ *
650
+ * preload(paths.users(2).settings, { preloadData: true });
651
+ * ```
652
+ */
653
+ const usePreloadRoute = () => {
654
+ const pre = useRouter().preloadRoute;
655
+ return (url, options = {}) => pre(url instanceof URL ? url : new URL(String(url), mockBase), options.preloadData);
656
+ };
657
+
449
658
  /**
450
659
  * Retrieves a reactive, store-like object containing the current route path parameters as defined in the Route.
451
660
  *
@@ -457,7 +666,10 @@ const useCurrentMatches = () => {
457
666
  * const getUser = query(() => fetchUser(params.id), "user");
458
667
  * ```
459
668
  */
460
- const useParams = () => useRoute().params;
669
+
670
+ function useParams(_path) {
671
+ return useRoute().params;
672
+ }
461
673
 
462
674
  /**
463
675
  * Retrieves a tuple containing a reactive object to read the current location's query parameters and a method to update them.
@@ -486,7 +698,8 @@ const useParams = () => useRoute().params;
486
698
  * );
487
699
  * ```
488
700
  */
489
- const useSearchParams = () => {
701
+
702
+ function useSearchParams(path) {
490
703
  const router = useRouter();
491
704
  const location = router.location;
492
705
  const navigate = useNavigate();
@@ -506,43 +719,73 @@ const useSearchParams = () => {
506
719
  ...options
507
720
  });
508
721
  };
509
- return [location.query, setSearchParams];
510
- };
511
-
722
+ // Passing a paths node opts into schema parsing. The node itself is a
723
+ // type-level reference; the schemas that run come from the currently
724
+ // matched routes (root→leaf), whose outputs merge over the raw query.
725
+ // A schema that reports issues is skipped, leaving raw values — search
726
+ // strings are user input, so defaults belong in the schema itself.
727
+ const query = path ? createMemoObject(createMemo(() => {
728
+ const raw = {
729
+ ...location.query
730
+ };
731
+ let result;
732
+ for (const match of router.matches()) {
733
+ const schema = match.route.key.search;
734
+ if (!schema) continue;
735
+ const outcome = schema["~standard"].validate(raw);
736
+ if (outcome instanceof Promise) throw new Error("Async Standard Schema validation is not supported for search params");
737
+ if (!outcome.issues) result = Object.assign(result || {
738
+ ...raw
739
+ }, outcome.value);
740
+ }
741
+ return result || raw;
742
+ })) : location.query;
743
+ return [query, setSearchParams];
744
+ }
512
745
  /**
513
- * useBeforeLeave takes a function that will be called prior to leaving a route.
514
- * The function will be called with:
515
- *
516
- * - from (*Location*): current location (before change).
517
- * - to (*string | number*): path passed to `navigate`.
518
- * - options (*NavigateOptions*): options passed to navigate.
519
- * - preventDefault (*function*): call to block the route change.
520
- * - defaultPrevented (*readonly boolean*): `true` if any previously called leave handlers called `preventDefault`.
521
- * - retry (*function*, force?: boolean ): call to retry the same navigation, perhaps after confirming with the user. Pass `true` to skip running the leave handlers again (i.e. force navigate without confirming).
522
- *
746
+ * Reactive link state for custom link components — the programmatic
747
+ * counterpart of the attribute vocabulary plain anchors receive
748
+ * (`aria-current`, `data-active`, `data-pending`).
749
+ *
523
750
  * @example
524
- * ```js
525
- * useBeforeLeave((e: BeforeLeaveEventArgs) => {
526
- * if (form.isDirty && !e.defaultPrevented) {
527
- * // preventDefault to block immediately and prompt user async
528
- * e.preventDefault();
529
- * setTimeout(() => {
530
- * if (window.confirm("Discard unsaved changes - are you sure?")) {
531
- * // user wants to proceed anyway so retry with force=true
532
- * e.retry(true);
533
- * }
534
- * }, 100);
535
- * }
536
- * });
751
+ * ```tsx
752
+ * function TabLink(props: { href: string; children: JSX.Element }) {
753
+ * const link = useLinkState(() => props.href);
754
+ * return (
755
+ * <a href={props.href} class="tab" data-selected={link.active() || undefined}>
756
+ * {props.children}
757
+ * </a>
758
+ * );
759
+ * }
537
760
  * ```
538
761
  */
539
- const useBeforeLeave = listener => {
540
- const s = useRouter().beforeLeave.subscribe({
541
- listener,
542
- location: useLocation(),
543
- navigate: useNavigate()
762
+ const useLinkState = (href, options = {}) => {
763
+ const router = useRouter();
764
+ const location = router.location;
765
+ const to = useResolvedPath(() => String(href()));
766
+ // trailing slashes are ignored so `/route` and `/route/` share state
767
+ const path = createMemo(() => {
768
+ const to_ = to();
769
+ return to_ === undefined ? undefined : comparablePath(to_);
544
770
  });
545
- onCleanup(s);
771
+ const matches = loc => {
772
+ const path_ = path();
773
+ if (path_ === undefined) return [false, false];
774
+ const exact = loc === path_;
775
+ return [exact || !options.end && loc.startsWith(path_ + "/"), exact];
776
+ };
777
+ const state = createMemo(() => matches(decodeURI(comparablePath(location.pathname))));
778
+ return {
779
+ active: () => state()[0],
780
+ current: () => state()[1],
781
+ // match the in-flight target explicitly (rather than active-while-routing)
782
+ // so the answer is the same from pure reads and from effects, which
783
+ // observe the committed location during a transition
784
+ pending: createMemo(() => {
785
+ state(); // location dependency: mid-flight target swaps recompute
786
+ return router.isRouting() && !!router.pendingTarget && matches(decodeURI(comparablePath(router.pendingTarget.value)))[0];
787
+ })
788
+ };
546
789
  };
547
790
 
548
791
  // Encodes a static path segment like `encodeURIComponent`, but leaves RFC 3986
@@ -550,6 +793,82 @@ const useBeforeLeave = listener => {
550
793
  // report them in `location.pathname`. Non-ASCII characters (eg. CJK paths) are
551
794
  // still percent-encoded exactly as before, since browsers encode those too.
552
795
  const encodeSegment = s => encodeURIComponent(s).replace(/%(2B|40|3A|24|26|2C|3B|3D)/g, m => decodeURIComponent(m));
796
+
797
+ // ---------------------------------------------------------------------------
798
+ // Lazy route subtrees
799
+ // ---------------------------------------------------------------------------
800
+ //
801
+ // A `children` thunk (`() => import("./feature/routes")`) is a *boundary*:
802
+ // until it resolves, the compiled tree carries a param-less catch-all
803
+ // placeholder branch under the boundary's pattern (splat-scored, so static
804
+ // siblings still win). Resolution is append-only and cached per thunk, then a
805
+ // module-level version signal bumps and every `branches()` consumer
806
+ // recompiles — matches, params, and route states all react. The placeholder's
807
+ // component reads a memo of the resolution promise, which keeps the enclosing
808
+ // navigation transition pending exactly like a `lazy()` route component; its
809
+ // `preload` *is* the resolver, so hover-intent preloading kicks the table
810
+ // load through the existing component-preload path.
811
+
812
+ const lazyBoundaries = new WeakMap();
813
+ // Module scope: boundary resolution is global, deterministic state (same
814
+ // thunk -> same routes), shared by every factory instance and the server's
815
+ // flight collector.
816
+ const [lazyTreeVersion, setLazyTreeVersion] = createSignal(0);
817
+
818
+ /** Reactive read of the lazy-subtree version — recompile compiled branches when it changes. */
819
+ function trackLazySubtrees() {
820
+ return lazyTreeVersion();
821
+ }
822
+ function getLazyBoundary(thunk) {
823
+ let record = lazyBoundaries.get(thunk);
824
+ if (!record) lazyBoundaries.set(thunk, record = {
825
+ thunk
826
+ });
827
+ return record;
828
+ }
829
+
830
+ /**
831
+ * Kicks (or joins) a boundary's resolution. Returns the resolved routes
832
+ * synchronously once available, the in-flight promise otherwise. Commit is
833
+ * always async — even for thunks returning arrays — so the version bump
834
+ * never writes a signal from inside a render computation.
835
+ */
836
+ function resolveLazySubtree(record) {
837
+ if (record.resolved) return record.resolved;
838
+ return record.promise ||= Promise.resolve(record.thunk()).then(m => {
839
+ const routes = Array.isArray(m) ? m : m.default || m.routes || [];
840
+ record.resolved = routes;
841
+ setLazyTreeVersion(v => v + 1);
842
+ return record.resolved;
843
+ });
844
+ }
845
+
846
+ /**
847
+ * The unresolved boundaries in a match chain. Rendering gates on these (the
848
+ * route-states memo suspends until they land — see routers/components.tsx)
849
+ * and the server's flight collector awaits them before its preload pass.
850
+ */
851
+ function unresolvedLazyMatches(matches) {
852
+ const pending = [];
853
+ for (const match of matches) if (match.route.lazy && !match.route.lazy.resolved) pending.push(match.route.lazy);
854
+ return pending;
855
+ }
856
+ function createLazyPlaceholder(pattern, record) {
857
+ // The placeholder never renders and needs no component — `matches` parks
858
+ // on unresolved boundaries before route contexts are created (kicking the
859
+ // resolver as it does), preloadRoute kicks it directly, and the version
860
+ // bump swaps in the real routes. `path + "/*"` with no splat name matches
861
+ // the boundary itself and everything beneath it without recording a param
862
+ // (createMatcher skips empty splat names).
863
+ const placeholderPattern = pattern + "/*";
864
+ return {
865
+ key: record,
866
+ originalPath: "*",
867
+ pattern: placeholderPattern,
868
+ matcher: createMatcher(placeholderPattern),
869
+ lazy: record
870
+ };
871
+ }
553
872
  function createRoutes(routeDef, base = "") {
554
873
  const {
555
874
  component,
@@ -605,17 +924,6 @@ function createBranch(routes, index = 0) {
605
924
  function asArray(value) {
606
925
  return Array.isArray(value) ? value : [value];
607
926
  }
608
-
609
- /**
610
- * Resolves the route tree an app hands the router — JSX `<Route>` children
611
- * (`Route` is a data-holder component, evaluating to its merged props),
612
- * config objects, arrays, or thunks producing either — into route
613
- * definitions. Shared by the `<Router>` component (which keeps the
614
- * resolution live) and the server integration's preload runner (one-shot).
615
- */
616
- function resolveRouteDefinitions(routes) {
617
- return children(() => routes);
618
- }
619
927
  function createBranches(routeDef, base = "", stack = [], branches = []) {
620
928
  const routeDefs = asArray(routeDef);
621
929
  for (let i = 0, len = routeDefs.length; i < len; i++) {
@@ -625,9 +933,23 @@ function createBranches(routeDef, base = "", stack = [], branches = []) {
625
933
  const routes = createRoutes(def, base);
626
934
  for (const route of routes) {
627
935
  stack.push(route);
628
- const isEmptyArray = Array.isArray(def.children) && def.children.length === 0;
629
- if (def.children && !isEmptyArray) {
630
- createBranches(def.children, route.pattern, stack, branches);
936
+ let children = def.children;
937
+ if (typeof children === "function") {
938
+ const record = getLazyBoundary(children);
939
+ if (record.resolved) {
940
+ children = record.resolved;
941
+ } else {
942
+ // unresolved boundary: a catch-all placeholder holds its ground
943
+ stack.push(createLazyPlaceholder(route.pattern, record));
944
+ branches.push(createBranch([...stack], branches.length));
945
+ stack.pop();
946
+ stack.pop();
947
+ continue;
948
+ }
949
+ }
950
+ const isEmptyArray = Array.isArray(children) && children.length === 0;
951
+ if (children && !isEmptyArray) {
952
+ createBranches(children, route.pattern, stack, branches);
631
953
  } else {
632
954
  const branch = createBranch([...stack], branches.length);
633
955
  branches.push(branch);
@@ -695,6 +1017,49 @@ function createLocation(path, state, queryWrapper) {
695
1017
  query: queryWrapper ? queryWrapper(queryFn) : createMemoObject(queryFn)
696
1018
  };
697
1019
  }
1020
+
1021
+ /**
1022
+ * Rendezvous between the router and the data layer's single-flight consumer.
1023
+ * The Router registers itself at mount (unless `singleFlight={false}`); the
1024
+ * action side provides the consumer factory when the first action is created
1025
+ * (see data/action.ts). Whichever side arrives first waits for the other, so
1026
+ * an action module loaded lazily (a code-split route) still attaches to the
1027
+ * already-mounted router — and a router-only app, where no action ever
1028
+ * loads, never subscribes to the transport, so the server is never asked to
1029
+ * collect.
1030
+ */
1031
+ let flightConsumerFactory;
1032
+ const flightRouters = new Map();
1033
+ function registerFlightRouter(router) {
1034
+ flightRouters.set(router, flightConsumerFactory && flightConsumerFactory(router));
1035
+ return () => {
1036
+ const unsubscribe = flightRouters.get(router);
1037
+ flightRouters.delete(router);
1038
+ unsubscribe && unsubscribe();
1039
+ };
1040
+ }
1041
+ function provideFlightConsumer(factory) {
1042
+ if (flightConsumerFactory) return;
1043
+ flightConsumerFactory = factory;
1044
+ for (const [router, unsubscribe] of flightRouters) {
1045
+ if (!unsubscribe) flightRouters.set(router, factory(router));
1046
+ }
1047
+ }
1048
+
1049
+ /**
1050
+ * The flash-cookie codec, provided by the action side (data/action.ts) so
1051
+ * the router core never carries it: the core consumes the cookie eagerly
1052
+ * per request (detection + one-shot clear via the tiny flashCookie.ts half)
1053
+ * but defers decoding to this slot, read when the submissions signal
1054
+ * initializes. Actions are created at module scope, so on the server the
1055
+ * decoder is always installed before useSubmission can read — and a
1056
+ * router-only app, where it never installs, has no actions that could have
1057
+ * produced a flash cookie in the first place.
1058
+ */
1059
+ let flashDecoder;
1060
+ function provideFlashDecoder(decoder) {
1061
+ flashDecoder || (flashDecoder = decoder);
1062
+ }
698
1063
  let intent;
699
1064
  function getIntent() {
700
1065
  return intent;
@@ -713,7 +1078,8 @@ function createRouterContext(integration, branches, getContext, options = {}) {
713
1078
  } = integration;
714
1079
  const parsePath = utils.parsePath || (p => p);
715
1080
  const renderPath = utils.renderPath || (p => p);
716
- const beforeLeave = utils.beforeLeave || createBeforeLeave();
1081
+ // An empty slot until `useBeforeLeave` installs the guard on first use.
1082
+ const beforeLeave = utils.beforeLeave || {};
717
1083
  const basePath = resolvePath("", options.base || "");
718
1084
  const initialSource = untrack(source);
719
1085
  if (basePath === undefined) {
@@ -742,14 +1108,38 @@ function createRouterContext(integration, branches, getContext, options = {}) {
742
1108
  const effective = createMemo(() => navigateTarget() ?? source());
743
1109
  const location = createLocation(() => effective().value, () => effective().state, utils.queryWrapper);
744
1110
  const referrers = [];
745
- const submissions = createSignal(isServer ? initFromFlash() : [], {
746
- ownedWrite: true
747
- });
748
- const matches = createMemo(() => {
749
- if (typeof options.transformUrl === "function") {
750
- return getRouteMatches(branches(), options.transformUrl(location.pathname));
1111
+ // The flash cookie is consumed eagerly: its one-shot clear (Set-Cookie)
1112
+ // must be appended before streaming flushes the response headers, and an
1113
+ // unread outcome must not haunt a later request's render. Only detection
1114
+ // and clearing happen here (the tiny flashCookie.ts half); the raw header
1115
+ // is stashed and decoding waits for the action-provided codec, read when
1116
+ // the lazily allocated submissions signal below first initializes.
1117
+ let flashCookieHeader;
1118
+ if (isServer) {
1119
+ const e = getRequestEvent();
1120
+ if (e && !(e.router && e.router.submission)) {
1121
+ const cookieHeader = e.request.headers.get("cookie");
1122
+ if (hasFlashCookie(cookieHeader)) {
1123
+ flashCookieHeader = cookieHeader;
1124
+ // one-shot: clear it even when unreadable so it can't haunt later renders
1125
+ if (e.response && e.response.headers) e.response.headers.append("Set-Cookie", clearFlashCookie());
1126
+ }
751
1127
  }
752
- return getRouteMatches(branches(), location.pathname);
1128
+ }
1129
+ let submissions;
1130
+ const matches = createMemo(() => {
1131
+ const pathname = typeof options.transformUrl === "function" ? options.transformUrl(location.pathname) : location.pathname;
1132
+ const m = getRouteMatches(branches(), pathname);
1133
+ // An unresolved lazy subtree parks readers on not-ready semantics — the
1134
+ // navigation transition (or the SSR stream) holds until the table lands.
1135
+ // NotReadyError (not a returned promise) because a match chain is full
1136
+ // of component functions the hydration serializer must never see. The
1137
+ // recompute comes from the version-signal dependency on the client and
1138
+ // from the carried promise's retry on the server; a boundary nested
1139
+ // inside a boundary just parks the recomputed chain again.
1140
+ const pending = unresolvedLazyMatches(m);
1141
+ if (pending.length) throw new NotReadyError(Promise.all(pending.map(resolveLazySubtree)));
1142
+ return m;
753
1143
  });
754
1144
  const buildParams = () => mergeParams(matches());
755
1145
  const wrapParams = utils.paramsWrapper ? getParams => utils.paramsWrapper(getParams, branches) : getParams => createMemoObject(getParams);
@@ -779,7 +1169,11 @@ function createRouterContext(integration, branches, getContext, options = {}) {
779
1169
  beforeLeave,
780
1170
  preloadRoute,
781
1171
  singleFlight: options.singleFlight === undefined ? true : options.singleFlight,
782
- submissions
1172
+ get submissions() {
1173
+ return submissions ||= createSignal(isServer ? initSubmissions() : [], {
1174
+ ownedWrite: true
1175
+ });
1176
+ }
783
1177
  };
784
1178
  function navigateFromRoute(route, to, options) {
785
1179
  // Untrack in case someone navigates in an effect - don't want to track `reference` or route paths
@@ -792,6 +1186,8 @@ function createRouterContext(integration, branches, getContext, options = {}) {
792
1186
  }
793
1187
  return;
794
1188
  }
1189
+ // typed path proxy nodes coerce to their href
1190
+ if (typeof to !== "string") to = to.toString();
795
1191
  const queryOnly = !to || to[0] === "?";
796
1192
  const {
797
1193
  replace,
@@ -826,7 +1222,7 @@ function createRouterContext(integration, branches, getContext, options = {}) {
826
1222
  scroll,
827
1223
  state: nextState
828
1224
  });
829
- } else if (beforeLeave.confirm(resolvedTo, options)) {
1225
+ } else if (!beforeLeave.current || beforeLeave.current.confirm(resolvedTo, options)) {
830
1226
  referrers.push({
831
1227
  value: current.value,
832
1228
  replace,
@@ -837,12 +1233,15 @@ function createRouterContext(integration, branches, getContext, options = {}) {
837
1233
  value: resolvedTo,
838
1234
  state: nextState
839
1235
  };
840
- if (lastTransitionTarget === undefined) {
1236
+ const firstNavigation = lastTransitionTarget === undefined;
1237
+ intent = "navigate";
1238
+ // assign the target before flushing so effects that run for the
1239
+ // isRouting flip (e.g. pending link state) can read it
1240
+ lastTransitionTarget = newTarget;
1241
+ if (firstNavigation) {
841
1242
  setIsRouting(true);
842
1243
  flush();
843
1244
  }
844
- intent = "navigate";
845
- lastTransitionTarget = newTarget;
846
1245
  if (lastTransitionTarget === newTarget) {
847
1246
  setNavigateTarget({
848
1247
  ...lastTransitionTarget
@@ -878,6 +1277,11 @@ function createRouterContext(integration, branches, getContext, options = {}) {
878
1277
  }
879
1278
  function preloadRoute(url, preloadData) {
880
1279
  const matches = getRouteMatches(branches(), url.pathname);
1280
+ // An unresolved lazy subtree in the chain: the placeholder's
1281
+ // component.preload (below) kicks the table load; once it lands,
1282
+ // preload again so the real inner routes warm too.
1283
+ const boundary = matches.find(m => m.route.lazy && !m.route.lazy.resolved);
1284
+ boundary && resolveLazySubtree(boundary.route.lazy).then(() => preloadRoute(url, preloadData));
881
1285
  const prevIntent = intent;
882
1286
  intent = "preload";
883
1287
  for (let match in matches) {
@@ -909,20 +1313,13 @@ function createRouterContext(integration, branches, getContext, options = {}) {
909
1313
 
910
1314
  // Seeds the initial submission from a no-JS form post: the server
911
1315
  // function handler redirected back with the outcome in a one-shot flash
912
- // cookie (see src/server.ts's handleNoJS), which is read here — and
913
- // cleared — so the post-redirect SSR renders useSubmission() state
1316
+ // cookie (see src/server.ts's handleNoJS), consumed eagerly above and
1317
+ // decoded here — so the post-redirect SSR renders useSubmission() state
914
1318
  // exactly as a scripted submission would. An explicitly pre-seeded
915
1319
  // `event.router.submission` (framework integrations) takes precedence.
916
- function initFromFlash() {
1320
+ function initSubmissions() {
917
1321
  const e = getRequestEvent();
918
- if (!e) return [];
919
- let submission = e.router && e.router.submission;
920
- if (!submission) {
921
- const cookieHeader = e.request.headers.get("cookie");
922
- submission = decodeFlashCookie(cookieHeader);
923
- // one-shot: clear it even when unreadable so it can't haunt later renders
924
- if (hasFlashCookie(cookieHeader) && e.response && e.response.headers) e.response.headers.append("Set-Cookie", clearFlashCookie());
925
- }
1322
+ const submission = e && e.router && e.router.submission || (flashDecoder && flashCookieHeader !== undefined ? flashDecoder(flashCookieHeader) : undefined);
926
1323
  if (!submission) return [];
927
1324
  return [{
928
1325
  ...submission,
@@ -975,1019 +1372,1192 @@ function createRouteContext(router, parent, outlet, match, matches = () => [matc
975
1372
  return route;
976
1373
  }
977
1374
 
978
- const LocationHeader = "Location";
979
- const PRELOAD_TIMEOUT = 5000;
980
- const CACHE_TIMEOUT = 180000;
981
- let cacheMap = new Map();
982
-
983
- // cleanup forward/back cache
984
- if (!isServer) {
985
- setInterval(() => {
986
- const now = Date.now();
987
- for (let [k, v] of cacheMap.entries()) {
988
- if (!v[4].count && now - v[0] > CACHE_TIMEOUT) {
989
- cacheMap.delete(k);
990
- }
1375
+ function Root(props) {
1376
+ const location = props.routerState.location;
1377
+ const params = props.routerState.params;
1378
+ const data = createMemo(() => props.preload && untrack(() => {
1379
+ setInPreloadFn(true);
1380
+ try {
1381
+ return props.preload({
1382
+ params,
1383
+ location,
1384
+ intent: getIntent() || "initial"
1385
+ });
1386
+ } finally {
1387
+ setInPreloadFn(false);
991
1388
  }
992
- }, 300000);
993
- }
994
- function getCache() {
995
- if (!isServer) return cacheMap;
996
- const req = getRequestEvent();
997
- if (!req) throw new Error("Cannot find cache context");
998
- return (req.router || (req.router = {})).cache || (req.router.cache = new Map());
999
- }
1000
-
1001
- /**
1002
- * Revalidates the given cache entry/entries.
1003
- */
1004
- function revalidate(key, force = true) {
1005
- const now = Date.now();
1006
- cacheKeyOp(key, entry => {
1007
- force && (entry[0] = 0); //force cache miss
1008
- entry[4][1](now); // retrigger live signals
1009
- });
1010
- }
1011
- function cacheKeyOp(key, fn) {
1012
- key && !Array.isArray(key) && (key = [key]);
1013
- for (let k of cacheMap.keys()) {
1014
- if (key === undefined || matchKey(k, key)) fn(cacheMap.get(k));
1389
+ }));
1390
+ const RootComp = props.root;
1391
+ if (RootComp) {
1392
+ return createComponent$1(RootComp, {
1393
+ params: params,
1394
+ location: location,
1395
+ get data() {
1396
+ return data();
1397
+ },
1398
+ get children() {
1399
+ return props.children;
1400
+ }
1401
+ });
1015
1402
  }
1403
+ return props.children;
1016
1404
  }
1017
- function query(fn, name) {
1018
- // query implies GET: the router primitive is the declaration site, so a
1019
- // server function handed to query() is wrapped with core `GET(fn)` here,
1020
- // at query-creation (module scope) — the server half records the method
1021
- // declaration for dispatch, the client half swaps in the GET transport.
1022
- // An explicit `GET(fn)` already carries the declaration on the metadata
1023
- // channel (`getServerFunctionMetadata(fn)?.method === "GET"`) and passes
1024
- // through; non-server functions are untouched.
1025
- if (isServerFunction(fn) && !getServerFunctionMetadata(fn)?.method) {
1026
- fn = GET(fn);
1027
- }
1028
- const cachedFn = (...args) => {
1029
- const cache = getCache();
1030
- const intent = getIntent();
1031
- const inPreloadFn = getInPreloadFn();
1032
- const owner = getOwner();
1033
- const navigate = owner ? useNavigate() : undefined;
1034
- const now = Date.now();
1035
- const key = name + hashKey(args);
1036
- let cached = cache.get(key);
1037
- let tracking;
1038
- if (isServer) {
1039
- const e = getRequestEvent();
1040
- if (e) {
1041
- const dataOnly = (e.router || (e.router = {})).dataOnly;
1042
- if (dataOnly) {
1043
- const data = e && (e.router.data || (e.router.data = {}));
1044
- if (data && key in data) return data[key];
1045
- if (Array.isArray(dataOnly) && !matchKey(key, dataOnly)) {
1046
- data[key] = undefined;
1047
- return Promise.resolve();
1048
- }
1049
- }
1050
- }
1405
+ function Routes(props) {
1406
+ if (isServer) {
1407
+ const e = getRequestEvent();
1408
+ if (e && e.router && e.router.dataOnly) {
1409
+ dataOnly(e, props.routerState, props.branches());
1410
+ return;
1051
1411
  }
1052
- if (getObserver() && !isServer) {
1053
- tracking = true;
1054
- onCleanup(() => cached[4].count--);
1412
+ if (e && !(e.router && e.router.matches)) {
1413
+ // A lazy getter rather than a snapshot: unresolved lazy subtrees mean
1414
+ // the match chain can still improve while the render streams, and
1415
+ // frameworks read this after the render settles.
1416
+ Object.defineProperty(e.router || (e.router = {}), "matches", {
1417
+ configurable: true,
1418
+ enumerable: true,
1419
+ get: () => props.routerState.matches().map(({
1420
+ route,
1421
+ path,
1422
+ params
1423
+ }) => ({
1424
+ path: route.originalPath,
1425
+ pattern: route.pattern,
1426
+ match: path,
1427
+ params,
1428
+ info: route.info
1429
+ }))
1430
+ });
1055
1431
  }
1056
- if (cached && cached[0] && (isServer || intent === "native" || cached[4].count || Date.now() - cached[0] < PRELOAD_TIMEOUT)) {
1057
- if (tracking) {
1058
- cached[4].count++;
1059
- cached[4][0](); // track
1060
- }
1061
- if (cached[3] === "preload" && intent !== "preload") {
1062
- cached[0] = now;
1063
- }
1064
- let res = cached[1];
1065
- if (intent !== "preload") {
1066
- res = "then" in cached[1] ? cached[1].then(handleResponse(false), handleResponse(true)) : handleResponse(false)(cached[1]);
1067
- !isServer && intent === "navigate" && cached[4][1](cached[0]); // update version
1432
+ }
1433
+ const disposers = [];
1434
+ let root;
1435
+ let prevMatches;
1436
+ // dispose the detached per-route roots when this component unmounts, otherwise
1437
+ // they stay subscribed to `matches` and crash on a later navigation (#451)
1438
+ onCleanup(() => disposers.forEach(dispose => dispose()));
1439
+ // Route roots must outlive re-runs of the `routeStates` memo below, so they
1440
+ // are created under the owner of this component rather than the memo's
1441
+ // computation (which disposes its children every time it re-runs).
1442
+ const owner = getOwner();
1443
+ const routeStates = createMemo(prev => {
1444
+ // While a lazy subtree resolves, `matches()` is not ready and this
1445
+ // computation parks with it — no route contexts are created against
1446
+ // placeholder matches.
1447
+ const nextMatches = props.routerState.matches();
1448
+ const previousMatches = prevMatches;
1449
+ let equal = previousMatches && nextMatches.length === previousMatches.length;
1450
+ const next = [];
1451
+ for (let i = 0, len = nextMatches.length; i < len; i++) {
1452
+ const prevMatch = previousMatches && previousMatches[i];
1453
+ const nextMatch = nextMatches[i];
1454
+ if (prev && prevMatch && nextMatch.route.key === prevMatch.route.key) {
1455
+ next[i] = prev[i];
1456
+ } else {
1457
+ equal = false;
1458
+ if (disposers[i]) {
1459
+ disposers[i]();
1460
+ }
1461
+ runWithOwner(owner, () => createRoot(dispose => {
1462
+ disposers[i] = dispose;
1463
+ const routeKey = nextMatch.route.key;
1464
+ // Retain the last matches in which this route participated so
1465
+ // that its components and preloads never observe another
1466
+ // route's params/path while this route is being torn down.
1467
+ const matchesAtLevel = createMemo(prev => {
1468
+ const routeMatches = props.routerState.matches();
1469
+ const m = routeMatches[i];
1470
+ return m && m.route.key === routeKey ? routeMatches : prev || nextMatches;
1471
+ });
1472
+ next[i] = createRouteContext(props.routerState, next[i - 1] || props.routerState.base, createOutlet(() => routeStates()?.[i + 1]), () => matchesAtLevel()[i], matchesAtLevel);
1473
+ }));
1068
1474
  }
1069
- inPreloadFn && "then" in res && res.catch(() => {});
1070
- return res;
1071
- }
1072
- let res;
1073
- if (!isServer && sharedConfig.has && sharedConfig.has(key)) {
1074
- res = sharedConfig.load(key); // hydrating
1075
- // @ts-ignore at least until we add a delete method to sharedConfig
1076
- delete globalThis._$HY.r[key];
1077
- } else res = fn(...args);
1078
- if (cached) {
1079
- cached[0] = now;
1080
- cached[1] = res;
1081
- cached[3] = intent;
1082
- !isServer && intent === "navigate" && cached[4][1](cached[0]); // update version
1083
- } else {
1084
- cache.set(key, cached = [now, res,, intent, createSignal(now, {
1085
- ownedWrite: true
1086
- })]);
1087
- cached[4].count = 0;
1088
- }
1089
- if (tracking) {
1090
- cached[4].count++;
1091
- cached[4][0](); // track
1092
- }
1093
- if (isServer) {
1094
- const e = getRequestEvent();
1095
- if (e && e.router.dataOnly) return e.router.data[key] = res;
1096
- }
1097
- if (intent !== "preload") {
1098
- res = "then" in res ? res.then(handleResponse(false), handleResponse(true)) : handleResponse(false)(res);
1099
1475
  }
1100
- inPreloadFn && "then" in res && res.catch(() => {});
1101
- // serialize on server
1102
- if (isServer && sharedConfig.context && sharedConfig.context.async && !sharedConfig.context.noHydrate) {
1103
- const e = getRequestEvent();
1104
- (!e || !e.serverOnly) && sharedConfig.context.serialize(key, res);
1476
+ disposers.splice(nextMatches.length).forEach(dispose => dispose());
1477
+ if (prev && equal) {
1478
+ prevMatches = nextMatches;
1479
+ return prev;
1105
1480
  }
1106
- return res;
1107
- function handleResponse(error) {
1108
- return async v => {
1109
- let enveloped;
1110
- let hasEnveloped = false;
1111
- if (isResponseEnvelope(v)) {
1112
- // respond(): the value rides in memory beside the metadata
1113
- enveloped = v.value;
1114
- hasEnveloped = true;
1115
- v = v.response;
1116
- }
1117
- if (v instanceof Response) {
1118
- const e = getRequestEvent();
1119
- if (e) {
1120
- for (const [key, value] of v.headers) {
1121
- if (key == "set-cookie") e.response.headers.append("set-cookie", value);else e.response.headers.set(key, value);
1122
- }
1123
- }
1124
- const url = v.headers.get(LocationHeader);
1125
- if (url !== null) {
1126
- // client + server relative redirect
1127
- if (navigate && url.startsWith("/")) navigate(url, {
1128
- replace: true
1129
- });else if (!isServer) window.location.href = url;else if (e) e.response.status = 302;
1130
- return;
1131
- }
1132
- if (hasEnveloped) v = enveloped;else if (v.body) {
1133
- // responses the transport hands over whole (revalidation) carry a
1134
- // codec-encoded body; anything else (a raw user Response) stays whole
1135
- const decoded = await decodeResponse(v);
1136
- if (decoded !== undefined) v = decoded;
1137
- }
1481
+ root = next[0];
1482
+ prevMatches = nextMatches;
1483
+ return next;
1484
+ });
1485
+ const outlet = createOutlet(() => routeStates() && root);
1486
+ return memo(outlet);
1487
+ }
1488
+ const createOutlet = child => {
1489
+ return () => {
1490
+ const c = child();
1491
+ if (c) {
1492
+ return createComponent$1(RouteContextObj, {
1493
+ value: c,
1494
+ get children() {
1495
+ return c.outlet();
1138
1496
  }
1139
- if (error) throw v;
1140
- cached[2] = v;
1141
- return v;
1142
- };
1497
+ });
1143
1498
  }
1499
+ return undefined;
1144
1500
  };
1145
- cachedFn.keyFor = (...args) => name + hashKey(args);
1146
- cachedFn.key = name;
1147
- return cachedFn;
1148
- }
1149
- query.get = key => {
1150
- const cached = getCache().get(key);
1151
- return cached[2];
1152
- };
1153
- query.set = (key, value) => {
1154
- const cache = getCache();
1155
- const now = Date.now();
1156
- let cached = cache.get(key);
1157
- if (cached) {
1158
- cached[0] = now;
1159
- cached[1] = Promise.resolve(value);
1160
- cached[2] = value;
1161
- cached[3] = "preload";
1162
- } else {
1163
- cache.set(key, cached = [now, Promise.resolve(value), value, "preload", createSignal(now, {
1164
- ownedWrite: true
1165
- })]);
1166
- cached[4].count = 0;
1167
- }
1168
1501
  };
1169
- query.delete = key => getCache().delete(key);
1170
- query.clear = () => getCache().clear();
1171
- function matchKey(key, keys) {
1172
- for (let k of keys) {
1173
- if (k && key.startsWith(k)) return true;
1502
+
1503
+ // for data only mode with single flight mutations
1504
+ function dataOnly(event, routerState, branches) {
1505
+ const url = new URL(event.request.url);
1506
+ const prevMatches = getRouteMatches(branches, new URL(event.router.previousUrl || event.request.url).pathname);
1507
+ const matches = getRouteMatches(branches, url.pathname);
1508
+ // This pass is synchronous — an unresolved lazy subtree can only be
1509
+ // kicked, not awaited (the flight collector's own runner awaits; see
1510
+ // src/server.ts). Best effort so a subsequent pass sees the table.
1511
+ unresolvedLazyMatches([...prevMatches, ...matches]).forEach(resolveLazySubtree);
1512
+ for (let match = 0; match < matches.length; match++) {
1513
+ if (!prevMatches[match] || matches[match].route !== prevMatches[match].route) event.router.dataOnly = true;
1514
+ const {
1515
+ route,
1516
+ params
1517
+ } = matches[match];
1518
+ route.preload && route.preload({
1519
+ params,
1520
+ location: routerState.location,
1521
+ intent: "preload"
1522
+ });
1174
1523
  }
1175
- return false;
1176
1524
  }
1177
1525
 
1178
- // Modified from the amazing Tanstack Query library (MIT)
1179
- // https://github.com/TanStack/query/blob/main/packages/query-core/src/utils.ts#L168
1180
- function hashKey(args) {
1181
- return JSON.stringify(args, (_, val) => isPlainObject(val) ? Object.keys(val).sort().reduce((result, key) => {
1182
- result[key] = val[key];
1183
- return result;
1184
- }, {}) : val);
1185
- }
1186
- function isPlainObject(obj) {
1187
- let proto;
1188
- return obj != null && typeof obj === "object" && (!(proto = Object.getPrototypeOf(obj)) || proto === Object.prototype);
1526
+ function bindEvent(target, type, handler) {
1527
+ target.addEventListener(type, handler);
1528
+ return () => target.removeEventListener(type, handler);
1189
1529
  }
1190
1530
 
1191
- const submitHooksSymbol = Symbol("routerActionSubmitHooks");
1192
- const settledHooksSymbol = Symbol("routerActionSettledHooks");
1193
- const invokeSymbol = Symbol("routerActionInvoke");
1194
- const actions = /* #__PURE__ */new Map();
1195
- function useSubmissions(fn, filter) {
1196
- const router = useRouter();
1197
- const subs = createMemo(() => router.submissions[0]().filter(s => s.url === fn.base && (!filter || filter(s.input))));
1198
- return new Proxy([], {
1199
- get(_, property) {
1200
- if (property === $TRACK) return subs();
1201
- return subs()[property];
1202
- },
1203
- has(_, property) {
1204
- return property in subs();
1531
+ // Depth stamping supports blocking browser-initiated navigation (back/forward)
1532
+ // for `useBeforeLeave`. It stays always-on — a couple of history.state writes —
1533
+ // so blocking stays exact no matter when the first guard subscribes, while the
1534
+ // guard machinery itself lives behind the lazy `beforeLeave` slot.
1535
+
1536
+ let depth;
1537
+ function saveCurrentDepth() {
1538
+ if (!window.history.state || window.history.state._depth == null) {
1539
+ window.history.replaceState({
1540
+ ...window.history.state,
1541
+ _depth: window.history.length - 1
1542
+ }, "");
1543
+ }
1544
+ depth = window.history.state._depth;
1545
+ }
1546
+ function keepDepth(state) {
1547
+ return {
1548
+ ...state,
1549
+ _depth: window.history.state && window.history.state._depth
1550
+ };
1551
+ }
1552
+ function notifyIfNotBlocked(notify, block) {
1553
+ let ignore = false;
1554
+ return () => {
1555
+ const prevDepth = depth;
1556
+ saveCurrentDepth();
1557
+ const delta = prevDepth == null ? null : depth - prevDepth;
1558
+ if (ignore) {
1559
+ ignore = false;
1560
+ return;
1205
1561
  }
1206
- });
1562
+ if (delta && block(delta)) {
1563
+ ignore = true;
1564
+ window.history.go(-delta);
1565
+ } else {
1566
+ notify();
1567
+ }
1568
+ };
1207
1569
  }
1208
- function useAction(action) {
1209
- const r = useRouter();
1210
- return (...args) => action.apply({
1211
- r
1212
- }, args);
1570
+ function scrollToHash(hash, fallbackTop) {
1571
+ const el = hash && document.getElementById(hash);
1572
+ if (el) {
1573
+ el.scrollIntoView();
1574
+ } else if (fallbackTop) {
1575
+ window.scrollTo(0, 0);
1576
+ }
1213
1577
  }
1214
- function actionImpl(fn, options = {}) {
1215
- async function invoke(variables, current) {
1216
- const router = this.r;
1217
- const form = this.f;
1218
- const submitHooks = current[submitHooksSymbol];
1219
- const settledHooks = current[settledHooksSymbol];
1220
- // Single-flight opt-in is no longer per call: the router's registered
1221
- // flight-data consumer (see setupFlightDataConsumer) makes the transport
1222
- // send the request header itself, so the mutation is just called.
1223
- const runMutation = () => fn(...variables);
1224
- const run = action$1(async function* (context) {
1225
- context.optimistic?.();
1226
- try {
1227
- const value = await context.call();
1228
- yield;
1229
- return {
1230
- error: false,
1231
- value
1232
- };
1233
- } catch (error) {
1234
- yield;
1235
- return {
1236
- error: true,
1237
- value: error
1238
- };
1578
+
1579
+ /**
1580
+ * A history adapter: the source of truth for the current URL and how
1581
+ * navigations write back to it. Adapters are plain imported values so
1582
+ * unused ones never enter the bundle — `createRouter` defaults to browser
1583
+ * history on the client and the request URL on the server.
1584
+ */
1585
+
1586
+ function browserHistory() {
1587
+ const getSource = () => {
1588
+ const url = window.location.pathname + window.location.search;
1589
+ const state = window.history.state && window.history.state._depth && Object.keys(window.history.state).length === 1 ? undefined : window.history.state;
1590
+ return {
1591
+ value: url + window.location.hash,
1592
+ state
1593
+ };
1594
+ };
1595
+ const beforeLeave = {};
1596
+ if (!isServer) saveCurrentDepth();
1597
+ return {
1598
+ get: getSource,
1599
+ set({
1600
+ value,
1601
+ replace,
1602
+ scroll,
1603
+ state
1604
+ }) {
1605
+ if (replace) {
1606
+ window.history.replaceState(keepDepth(state), "", value);
1607
+ } else {
1608
+ window.history.pushState(state, "", value);
1239
1609
  }
1240
- });
1241
- const settled = await settleActionResult(run({
1242
- call: runMutation,
1243
- optimistic: submitHooks.size ? () => {
1244
- for (const hook of submitHooks.values()) hook(...variables);
1245
- } : undefined
1246
- }));
1247
- const response = await handleResponse(settled.value, settled.error, router.navigatorFactory());
1248
- if (!response) return undefined;
1249
- let submission;
1250
- submission = {
1251
- input: variables,
1252
- url,
1253
- result: response.data,
1254
- error: response.error,
1255
- clear() {
1256
- router.submissions[1](entries => entries.filter(entry => entry !== submission));
1257
- },
1258
- retry() {
1259
- submission.clear();
1260
- return current[invokeSymbol].call({
1261
- r: router,
1262
- f: form
1263
- }, variables, current);
1610
+ scrollToHash(decodeURIComponent(window.location.hash.slice(1)), scroll);
1611
+ saveCurrentDepth();
1612
+ },
1613
+ init: notify => bindEvent(window, "popstate", notifyIfNotBlocked(notify, delta => {
1614
+ const guard = beforeLeave.current;
1615
+ if (!guard) return false;
1616
+ if (delta) {
1617
+ return !guard.confirm(delta);
1618
+ } else {
1619
+ const s = getSource();
1620
+ return !guard.confirm(s.value, {
1621
+ state: s.state
1622
+ });
1264
1623
  }
1265
- };
1266
- router.submissions[1](entries => [...entries, submission]);
1267
- for (const hook of settledHooks.values()) hook(submission);
1268
- if (response.error && !form) throw response.error;
1269
- return response.data;
1624
+ })),
1625
+ utils: {
1626
+ go: delta => window.history.go(delta),
1627
+ beforeLeave
1628
+ }
1629
+ };
1630
+ }
1631
+ function hashParser(str) {
1632
+ const to = str.replace(/^.*?#/, "");
1633
+ // Hash-only hrefs like `#foo` from plain anchors will come in as `/#foo` whereas a link to
1634
+ // `/foo` will be `/#/foo`. Check if the to starts with a `/` and if not append it as a hash
1635
+ // to the current path so we can handle these in-page anchors correctly.
1636
+ if (!to.startsWith("/")) {
1637
+ const [, path = "/"] = window.location.hash.split("#", 2);
1638
+ return `${path}#${to}`;
1270
1639
  }
1271
- const o = typeof options === "string" ? {
1272
- name: options
1273
- } : options;
1274
- const name = o.name || (!isServer ? String(hashString(fn.toString())) : undefined);
1275
- const url = fn.url || name && `https://action/${name}` || "";
1276
- const wrapped = toAction(invoke, url);
1277
- if (name) setFunctionName(wrapped, name);
1278
- return wrapped;
1640
+ return to;
1279
1641
  }
1280
- const action = actionImpl;
1281
- function toAction(invoke, url, boundArgs = [], base = url, submitHooks = new Map(), settledHooks = new Map()) {
1282
- const fn = function (...args) {
1283
- return invoke.call(this, [...boundArgs, ...args], fn);
1284
- };
1285
- fn.toString = () => {
1286
- if (!url) throw new Error("Client Actions need explicit names if server rendered");
1287
- return url;
1288
- };
1289
- fn.with = function (...args) {
1290
- const uri = new URL(url, mockBase);
1291
- uri.searchParams.set("args", hashKey(args));
1292
- const next = toAction(invoke, (uri.origin === "https://action" ? uri.origin : "") + uri.pathname + uri.search, [...boundArgs, ...args], base, submitHooks, settledHooks);
1293
- return next;
1642
+ function hashHistory() {
1643
+ const getSource = () => window.location.hash.slice(1);
1644
+ const beforeLeave = {};
1645
+ if (!isServer) saveCurrentDepth();
1646
+ return {
1647
+ get: getSource,
1648
+ set({
1649
+ value,
1650
+ replace,
1651
+ scroll,
1652
+ state
1653
+ }) {
1654
+ if (replace) {
1655
+ window.history.replaceState(keepDepth(state), "", "#" + value);
1656
+ } else {
1657
+ window.history.pushState(state, "", "#" + value);
1658
+ }
1659
+ const hashIndex = value.indexOf("#");
1660
+ const hash = hashIndex >= 0 ? value.slice(hashIndex + 1) : "";
1661
+ scrollToHash(hash, scroll);
1662
+ saveCurrentDepth();
1663
+ },
1664
+ init: notify => bindEvent(window, "hashchange", notifyIfNotBlocked(notify, delta => {
1665
+ const guard = beforeLeave.current;
1666
+ return !!guard && !guard.confirm(delta && delta < 0 ? delta : getSource());
1667
+ })),
1668
+ utils: {
1669
+ go: delta => window.history.go(delta),
1670
+ renderPath: path => `#${path}`,
1671
+ parsePath: hashParser,
1672
+ beforeLeave
1673
+ }
1294
1674
  };
1295
- fn.onSubmit = function (hook) {
1296
- const id = Symbol("actionOnSubmitHook");
1297
- submitHooks.set(id, hook);
1298
- getOwner() && onCleanup(() => submitHooks.delete(id));
1299
- return this;
1675
+ }
1676
+ function memoryHistory(initial = "/") {
1677
+ const entries = [initial];
1678
+ let index = 0;
1679
+ const listeners = [];
1680
+ const go = n => {
1681
+ // https://github.com/remix-run/react-router/blob/682810ca929d0e3c64a76f8d6e465196b7a2ac58/packages/router/history.ts#L245
1682
+ index = Math.max(0, Math.min(index + n, entries.length - 1));
1683
+ const value = entries[index];
1684
+ listeners.forEach(listener => listener(value));
1300
1685
  };
1301
- fn.onSettled = function (hook) {
1302
- const id = Symbol("actionOnSettledHook");
1303
- settledHooks.set(id, hook);
1304
- getOwner() && onCleanup(() => settledHooks.delete(id));
1305
- return this;
1686
+ const listen = listener => {
1687
+ listeners.push(listener);
1688
+ return () => {
1689
+ const i = listeners.indexOf(listener);
1690
+ listeners.splice(i, 1);
1691
+ };
1306
1692
  };
1307
- fn.url = url;
1308
- fn.base = base;
1309
- fn[submitHooksSymbol] = submitHooks;
1310
- fn[settledHooksSymbol] = settledHooks;
1311
- fn[invokeSymbol] = invoke;
1312
- if (!isServer) {
1313
- actions.set(url, fn);
1314
- // Only remove the registration if it still belongs to this instance —
1315
- // a re-created action (e.g. a new `.with()` binding after revalidation)
1316
- // may have registered itself under the same URL since.
1317
- getOwner() && onCleanup(() => actions.get(url) === fn && actions.delete(url));
1318
- }
1319
- return fn;
1320
- }
1321
- const hashString = s => s.split("").reduce((a, b) => (a << 5) - a + b.charCodeAt(0) | 0, 0);
1322
- async function settleActionResult(result) {
1323
- const value = result;
1324
- if (value && typeof value.then === "function") {
1325
- return result.then(value => value);
1326
- }
1327
- if (value && typeof value.next === "function") {
1328
- const iterator = value;
1329
- let next = await iterator.next();
1330
- while (!next.done) {
1331
- next = await iterator.next();
1693
+ return {
1694
+ get: () => entries[index],
1695
+ set: ({
1696
+ value,
1697
+ scroll,
1698
+ replace
1699
+ }) => {
1700
+ if (replace) {
1701
+ entries[index] = value;
1702
+ } else {
1703
+ entries.splice(index + 1, entries.length - index, value);
1704
+ index++;
1705
+ }
1706
+ listeners.forEach(listener => listener(value));
1707
+ setTimeout(() => {
1708
+ if (scroll) {
1709
+ scrollToHash(value.split("#")[1] || "", true);
1710
+ }
1711
+ }, 0);
1712
+ },
1713
+ back: () => go(-1),
1714
+ forward: () => go(1),
1715
+ go,
1716
+ listen,
1717
+ init: listen,
1718
+ utils: {
1719
+ go
1332
1720
  }
1333
- return next.value;
1334
- }
1335
- return result;
1721
+ };
1336
1722
  }
1337
1723
 
1338
1724
  /**
1339
- * Registers the router as the single-flight consumer of the server function
1340
- * transport. Subscribing is the opt-in: while registered, the transport
1341
- * sends the `X-Single-Flight` request header on mutations and delivers the
1342
- * folded payload here — fresh route data is seeded into the `query` cache
1343
- * and the envelope metadata (redirect `Location`, `X-Revalidate` keys) is
1344
- * applied, all before the action sees its plain return value. Called by the
1345
- * Router component on the client unless `singleFlight={false}`, which now
1346
- * simply means "never subscribe" — no consumer, no request header, no
1347
- * collection work on the server. Returns the unsubscribe function.
1725
+ * Identity helper that preserves literal types when the route tree is
1726
+ * declared as a separate variable. `createRouter` infers literally from
1727
+ * inline arrays, but an extracted `const routes = [...]` widens paths to
1728
+ * `string` and silently degrades `paths` and the typed hooks unless it is
1729
+ * declared `as const` — `defineRoutes` makes that impossible to forget.
1348
1730
  */
1349
- function setupFlightDataConsumer(router) {
1350
- return subscribeFlightData((data, {
1351
- response
1352
- }) => applyResponseMetadata(response, router.navigatorFactory(), data));
1731
+ function defineRoutes(routes) {
1732
+ return routes;
1733
+ }
1734
+ /** Wraps a history adapter in the integration signal the router core consumes. Must run under a reactive owner. */
1735
+ function createIntegration(history) {
1736
+ let ignore = false;
1737
+ const wrap = value => typeof value === "string" ? {
1738
+ value
1739
+ } : value;
1740
+ const [read, write] = createSignal(wrap(history.get()), {
1741
+ equals: (a, b) => a.value === b.value && a.state === b.state,
1742
+ ownedWrite: true
1743
+ });
1744
+ const signal = [read, next => {
1745
+ !ignore && history.set(next);
1746
+ if (sharedConfig.registry && !sharedConfig.done) sharedConfig.done = true;
1747
+ write(next);
1748
+ }];
1749
+ history.init && onCleanup(history.init((value = history.get()) => {
1750
+ ignore = true;
1751
+ signal[1](wrap(value));
1752
+ ignore = false;
1753
+ }));
1754
+ return {
1755
+ signal,
1756
+ utils: history.utils
1757
+ };
1353
1758
  }
1354
1759
 
1355
1760
  /**
1356
- * Applies a server function response's integration metadata: `X-Revalidate`
1357
- * keys invalidate, `Location` navigates (hard for absolute urls), flight
1358
- * data seeds the query cache, and matching entries revalidate. Shared by
1359
- * the flight-data consumer and the action response path (which still sees
1360
- * metadata-bearing responses when no flight data was collected).
1761
+ * Server default: a static view of the request URL — no signal machinery, a
1762
+ * server render never navigates. Without a request event (SSG scripts,
1763
+ * server-side tests) the configured history adapter provides the location,
1764
+ * so e.g. `memoryHistory("/page")` works isomorphically.
1361
1765
  */
1362
- async function applyResponseMetadata(metadata, navigate, flightData) {
1363
- let keys;
1364
- if (metadata) {
1365
- if (metadata.headers.has("X-Revalidate")) keys = metadata.headers.get("X-Revalidate").split(",");
1366
- if (metadata.headers.has("Location")) {
1367
- const locationUrl = metadata.headers.get("Location") || "/";
1368
- if (locationUrl.startsWith("http")) {
1369
- window.location.href = locationUrl;
1370
- } else {
1371
- navigate(locationUrl);
1372
- }
1373
- }
1766
+ function staticIntegration(history) {
1767
+ const e = getRequestEvent();
1768
+ let value = "";
1769
+ if (e) {
1770
+ const url = new URL(e.request.url);
1771
+ value = url.pathname + url.search;
1772
+ } else if (history) {
1773
+ value = history.get();
1374
1774
  }
1375
- // invalidate
1376
- cacheKeyOp(keys, entry => entry[0] = 0);
1377
- // set cache
1378
- flightData && Object.keys(flightData).forEach(k => query.set(k, flightData[k]));
1379
- // trigger revalidation
1380
- await revalidate(keys, false);
1775
+ const obj = typeof value === "string" ? {
1776
+ value
1777
+ } : {
1778
+ ...value
1779
+ };
1780
+ return {
1781
+ signal: [() => obj, next => Object.assign(obj, next)],
1782
+ utils: history && history.utils
1783
+ };
1381
1784
  }
1382
- async function handleResponse(response, error, navigate) {
1383
- let data;
1384
- let flightData;
1385
- let metadata;
1386
- if (isResponseEnvelope(response)) {
1387
- // client-only respond(): the value rides in memory beside the metadata
1388
- data = response.value;
1389
- metadata = response.response;
1390
- } else if (response instanceof Response) {
1391
- metadata = response;
1392
- // responses the transport hands over whole (redirects, revalidation)
1393
- // carry a codec-encoded body the router decodes itself. With the
1394
- // flight-data consumer registered single-flight payloads never reach
1395
- // this path, but a manually opted-in call (no consumer) still can —
1396
- // unwrap the standardized { value, data } shape for it too.
1397
- if (response.body) {
1398
- data = await decodeResponse(response);
1399
- if (response.headers.has("X-Single-Flight")) {
1400
- const payload = data;
1401
- data = payload.value;
1402
- flightData = payload.data;
1785
+ function createRouter(config) {
1786
+ const basePath = config.base || "";
1787
+ // Routes are immutable per instance, so compilation is shared by every
1788
+ // mount, request, and `match()` call — recompiled only when a lazy subtree
1789
+ // resolves (append-only: resolution, not mutation). Reading the version
1790
+ // inside a computation subscribes it; plain calls just see current state.
1791
+ let compiled;
1792
+ let compiledVersion = -1;
1793
+ const branches = () => {
1794
+ const version = trackLazySubtrees();
1795
+ if (!compiled || compiledVersion !== version) {
1796
+ compiled = createBranches(config.routes, basePath);
1797
+ compiledVersion = version;
1798
+ }
1799
+ return compiled;
1800
+ };
1801
+ const renderPath = config.history && config.history.utils && config.history.utils.renderPath || undefined;
1802
+ function RouterComponent(props) {
1803
+ // One router per app: the session (location, history, delegation, link
1804
+ // claims, preloading) has a single owner, and a second instance would
1805
+ // fight it — stale content on click navigations, conflicting link
1806
+ // attributes. Compose route trees instead; lazy subtrees are the planned
1807
+ // answer for definitions unknown at build time.
1808
+ if (useOptionalContext(RouterContextObj)) {
1809
+ console.warn("Mounting a router inside another router is not supported. " + "Compose route trees in one createRouter config instead.");
1810
+ }
1811
+ const root = untrack(() => props.children);
1812
+ const integration = isServer ? staticIntegration(config.history) : createIntegration(config.history || browserHistory());
1813
+ let context;
1814
+ const routerState = createRouterContext(integration, branches, () => context, {
1815
+ base: basePath,
1816
+ singleFlight: config.singleFlight,
1817
+ transformUrl: config.transformUrl
1818
+ });
1819
+ if (!isServer) {
1820
+ setupNativeEvents({
1821
+ preload: config.preloadLinks,
1822
+ explicitLinks: config.explicitLinks,
1823
+ actionBase: config.actionBase,
1824
+ transformUrl: config.transformUrl
1825
+ })(routerState);
1826
+ setupLinkClaims(routerState, config.explicitLinks);
1827
+ if (routerState.singleFlight) onCleanup(registerFlightRouter(routerState));
1828
+ }
1829
+ return createComponent$1(RouterContextObj, {
1830
+ value: routerState,
1831
+ get children() {
1832
+ return createComponent$1(Root, {
1833
+ routerState: routerState,
1834
+ root: root,
1835
+ get preload() {
1836
+ return config.preload;
1837
+ },
1838
+ get children() {
1839
+ return [memo(() => (context = getOwner()) && null), createComponent$1(Routes, {
1840
+ routerState: routerState,
1841
+ branches: branches
1842
+ })];
1843
+ }
1844
+ });
1403
1845
  }
1846
+ });
1847
+ }
1848
+ const instance = Object.assign(RouterComponent, {
1849
+ routes: config.routes,
1850
+ config,
1851
+ match(url) {
1852
+ const u = new URL(url, mockBase);
1853
+ const pathname = config.transformUrl ? config.transformUrl(u.pathname) : u.pathname;
1854
+ return getRouteMatches(branches(), pathname).map(({
1855
+ route,
1856
+ path,
1857
+ params
1858
+ }) => ({
1859
+ path: route.originalPath,
1860
+ pattern: route.pattern,
1861
+ match: path,
1862
+ params,
1863
+ info: route.info
1864
+ }));
1404
1865
  }
1405
- } else if (error) return {
1406
- error: response
1407
- };else data = response;
1408
- await applyResponseMetadata(metadata, navigate, flightData);
1409
- return data != null ? {
1410
- data
1411
- } : undefined;
1866
+ });
1867
+ // Built on first access (a getter via Object.assign would run during the
1868
+ // copy) so runtimes without Proxy — some older TVs — can still route as
1869
+ // long as they never touch typed paths.
1870
+ let paths;
1871
+ Object.defineProperty(instance, "paths", {
1872
+ get: () => paths || (paths = createPathsProxy(renderPath, basePath))
1873
+ });
1874
+ return instance;
1412
1875
  }
1413
1876
 
1414
- const createRouterComponent = router => function IntegratedRouter(props) {
1415
- const {
1416
- base,
1417
- singleFlight,
1418
- transformUrl,
1419
- root,
1420
- rootPreload,
1421
- routeChildren
1422
- } = untrack(() => ({
1423
- base: props.base,
1424
- singleFlight: props.singleFlight,
1425
- transformUrl: props.transformUrl,
1426
- root: props.root,
1427
- rootPreload: props.rootPreload,
1428
- routeChildren: props.children
1429
- }));
1430
- const routeDefs = resolveRouteDefinitions(routeChildren);
1431
- const branches = createMemo(() => createBranches(routeDefs(), base || ""));
1432
- let context;
1433
- const routerState = createRouterContext(router, branches, () => context, {
1434
- base,
1435
- singleFlight,
1436
- transformUrl
1437
- });
1438
- router.create && router.create(routerState);
1439
- if (!isServer && routerState.singleFlight) {
1440
- // Registering the consumer IS the single-flight opt-in: the transport
1441
- // sends the request header while one is subscribed. `singleFlight={false}`
1442
- // simply never subscribes, so the server is never asked to collect.
1443
- onCleanup(setupFlightDataConsumer(routerState));
1877
+ function createBeforeLeave() {
1878
+ let listeners = new Set();
1879
+ function subscribe(listener) {
1880
+ listeners.add(listener);
1881
+ return () => listeners.delete(listener);
1444
1882
  }
1445
- return createComponent$1(RouterContextObj, {
1446
- value: routerState,
1447
- get children() {
1448
- return createComponent$1(Root, {
1449
- routerState: routerState,
1450
- root: root,
1451
- preload: rootPreload,
1452
- get children() {
1453
- return [memo(() => (context = getOwner()) && null), createComponent$1(Routes, {
1454
- routerState: routerState,
1455
- get branches() {
1456
- return branches();
1457
- }
1458
- })];
1459
- }
1460
- });
1461
- }
1462
- });
1463
- };
1464
- function Root(props) {
1465
- const location = props.routerState.location;
1466
- const params = props.routerState.params;
1467
- const data = createMemo(() => props.preload && untrack(() => {
1468
- setInPreloadFn(true);
1469
- props.preload({
1470
- params,
1471
- location,
1472
- intent: getIntent() || "initial"
1473
- });
1474
- setInPreloadFn(false);
1475
- }));
1476
- const RootComp = props.root;
1477
- if (RootComp) {
1478
- return createComponent$1(RootComp, {
1479
- params: params,
1480
- location: location,
1481
- get data() {
1482
- return data();
1883
+ let ignore = false;
1884
+ function confirm(to, options) {
1885
+ if (ignore) return !(ignore = false);
1886
+ const e = {
1887
+ to,
1888
+ options,
1889
+ defaultPrevented: false,
1890
+ preventDefault: () => e.defaultPrevented = true
1891
+ };
1892
+ for (const l of listeners) l.listener({
1893
+ to,
1894
+ options,
1895
+ // delegate to the shared event so later listeners' preventDefault
1896
+ // calls are observable from earlier listeners
1897
+ get defaultPrevented() {
1898
+ return e.defaultPrevented;
1483
1899
  },
1484
- get children() {
1485
- return props.children;
1900
+ preventDefault: e.preventDefault,
1901
+ from: l.location,
1902
+ retry: force => {
1903
+ force && (ignore = true);
1904
+ l.navigate(to, {
1905
+ ...options,
1906
+ resolve: false
1907
+ });
1486
1908
  }
1487
1909
  });
1910
+ return !e.defaultPrevented;
1488
1911
  }
1489
- return props.children;
1912
+ return {
1913
+ subscribe,
1914
+ confirm
1915
+ };
1490
1916
  }
1491
- function Routes(props) {
1492
- if (isServer) {
1493
- const e = getRequestEvent();
1494
- if (e && e.router && e.router.dataOnly) {
1495
- dataOnly(e, props.routerState, props.branches);
1496
- return;
1917
+
1918
+ /**
1919
+ * useBeforeLeave takes a function that will be called prior to leaving a route.
1920
+ * The function will be called with:
1921
+ *
1922
+ * - from (*Location*): current location (before change).
1923
+ * - to (*string | number*): path passed to `navigate`.
1924
+ * - options (*NavigateOptions*): options passed to navigate.
1925
+ * - preventDefault (*function*): call to block the route change.
1926
+ * - defaultPrevented (*readonly boolean*): `true` if any previously called leave handlers called `preventDefault`.
1927
+ * - retry (*function*, force?: boolean ): call to retry the same navigation, perhaps after confirming with the user. Pass `true` to skip running the leave handlers again (i.e. force navigate without confirming).
1928
+ *
1929
+ * @example
1930
+ * ```js
1931
+ * useBeforeLeave((e: BeforeLeaveEventArgs) => {
1932
+ * if (form.isDirty && !e.defaultPrevented) {
1933
+ * // preventDefault to block immediately and prompt user async
1934
+ * e.preventDefault();
1935
+ * setTimeout(() => {
1936
+ * if (window.confirm("Discard unsaved changes - are you sure?")) {
1937
+ * // user wants to proceed anyway so retry with force=true
1938
+ * e.retry(true);
1939
+ * }
1940
+ * }, 100);
1941
+ * }
1942
+ * });
1943
+ * ```
1944
+ */
1945
+ const useBeforeLeave = listener => {
1946
+ // Installing the guard here (instead of eagerly in the router/history) keeps
1947
+ // all of createBeforeLeave tree-shakeable for apps that never block leaves.
1948
+ const slot = useRouter().beforeLeave;
1949
+ const s = (slot.current || (slot.current = createBeforeLeave())).subscribe({
1950
+ listener,
1951
+ location: useLocation(),
1952
+ navigate: useNavigate()
1953
+ });
1954
+ onCleanup(s);
1955
+ };
1956
+
1957
+ // The no-JS form convention's cookie codec. When a form posts to a server
1958
+ // function without the client runtime (no instance header), the server
1959
+ // handler redirects back carrying the outcome in a one-shot "flash" cookie;
1960
+ // the next SSR pass reads it and seeds the router's submission state so
1961
+ // useSubmission() renders the result exactly as a scripted submission would.
1962
+ // Both codec halves live in this module so the write (src/server.ts, the
1963
+ // handler's handleNoJS) and the read (provided to the router core by
1964
+ // data/action.ts) can never drift apart. The cookie's name/clearing live in
1965
+ // flashCookie.ts — the only piece the router core itself consumes — so this
1966
+ // codec stays out of bundles that never load the action layer.
1967
+
1968
+ function decodeInputValue(value) {
1969
+ if (value && typeof value === "object") {
1970
+ if (Array.isArray(value.$f)) {
1971
+ const form = new FormData();
1972
+ for (const [k, v] of value.$f) form.append(k, v);
1973
+ return form;
1497
1974
  }
1498
- e && ((e.router || (e.router = {})).matches || (e.router.matches = props.routerState.matches().map(({
1499
- route,
1500
- path,
1501
- params
1502
- }) => ({
1503
- path: route.originalPath,
1504
- pattern: route.pattern,
1505
- match: path,
1506
- params,
1507
- info: route.info
1508
- }))));
1975
+ if (Array.isArray(value.$u)) return new URLSearchParams(value.$u);
1509
1976
  }
1510
- const disposers = [];
1511
- let root;
1512
- let prevMatches;
1513
- // dispose the detached per-route roots when this component unmounts, otherwise
1514
- // they stay subscribed to `matches` and crash on a later navigation (#451)
1515
- onCleanup(() => disposers.forEach(dispose => dispose()));
1516
- // Route roots must outlive re-runs of the `routeStates` memo below, so they
1517
- // are created under the owner of this component rather than the memo's
1518
- // computation (which disposes its children every time it re-runs).
1519
- const owner = getOwner();
1520
- const routeStates = createMemo(prev => {
1521
- const nextMatches = props.routerState.matches();
1522
- const previousMatches = prevMatches;
1523
- let equal = previousMatches && nextMatches.length === previousMatches.length;
1524
- const next = [];
1525
- for (let i = 0, len = nextMatches.length; i < len; i++) {
1526
- const prevMatch = previousMatches && previousMatches[i];
1527
- const nextMatch = nextMatches[i];
1528
- if (prev && prevMatch && nextMatch.route.key === prevMatch.route.key) {
1529
- next[i] = prev[i];
1530
- } else {
1531
- equal = false;
1532
- if (disposers[i]) {
1533
- disposers[i]();
1534
- }
1535
- runWithOwner(owner, () => createRoot(dispose => {
1536
- disposers[i] = dispose;
1537
- const routeKey = nextMatch.route.key;
1538
- // Retain the last matches in which this route participated so
1539
- // that its components and preloads never observe another
1540
- // route's params/path while this route is being torn down.
1541
- const matchesAtLevel = createMemo(prev => {
1542
- const routeMatches = props.routerState.matches();
1543
- const m = routeMatches[i];
1544
- return m && m.route.key === routeKey ? routeMatches : prev || nextMatches;
1545
- });
1546
- next[i] = createRouteContext(props.routerState, next[i - 1] || props.routerState.base, createOutlet(() => routeStates()?.[i + 1]), () => matchesAtLevel()[i], matchesAtLevel);
1547
- }));
1977
+ return value;
1978
+ }
1979
+
1980
+ /**
1981
+ * Decodes the flash cookie out of a request's Cookie header. Returns
1982
+ * undefined when absent or unreadable (a malformed cookie must never take
1983
+ * down SSR — it is cleared either way).
1984
+ */
1985
+ function decodeFlashCookie(cookieHeader) {
1986
+ const match = matchFlashCookie(cookieHeader);
1987
+ if (!match) return;
1988
+ try {
1989
+ const payload = JSON.parse(decodeURIComponent(match));
1990
+ if (!payload || !payload.result) return;
1991
+ const result = payload.error ? new Error(payload.result) : payload.result;
1992
+ return {
1993
+ input: Array.isArray(payload.input) ? payload.input.map(decodeInputValue) : [],
1994
+ url: payload.url,
1995
+ result: payload.thrown ? undefined : result,
1996
+ error: payload.thrown ? result : undefined
1997
+ };
1998
+ } catch (error) {
1999
+ console.error(error);
2000
+ }
2001
+ }
2002
+
2003
+ const LocationHeader = "Location";
2004
+ const PRELOAD_TIMEOUT = 5000;
2005
+ const CACHE_TIMEOUT = 180000;
2006
+ let cacheMap = new Map();
2007
+
2008
+ // cleanup forward/back cache
2009
+ if (!isServer) {
2010
+ setInterval(() => {
2011
+ const now = Date.now();
2012
+ for (let [k, v] of cacheMap.entries()) {
2013
+ if (!v[4].count && now - v[0] > CACHE_TIMEOUT) {
2014
+ cacheMap.delete(k);
1548
2015
  }
1549
2016
  }
1550
- disposers.splice(nextMatches.length).forEach(dispose => dispose());
1551
- if (prev && equal) {
1552
- prevMatches = nextMatches;
1553
- return prev;
1554
- }
1555
- root = next[0];
1556
- prevMatches = nextMatches;
1557
- return next;
2017
+ }, 300000);
2018
+ }
2019
+ function getCache() {
2020
+ if (!isServer) return cacheMap;
2021
+ const req = getRequestEvent();
2022
+ if (!req) throw new Error("Cannot find cache context");
2023
+ return (req.router || (req.router = {})).cache || (req.router.cache = new Map());
2024
+ }
2025
+
2026
+ /**
2027
+ * Revalidates the given cache entry/entries.
2028
+ */
2029
+ function revalidate(key, force = true) {
2030
+ const now = Date.now();
2031
+ cacheKeyOp(key, entry => {
2032
+ force && (entry[0] = 0); //force cache miss
2033
+ entry[4][1](now); // retrigger live signals
1558
2034
  });
1559
- const outlet = createOutlet(() => routeStates() && root);
1560
- return memo(outlet);
1561
2035
  }
1562
- const createOutlet = child => {
1563
- return () => {
1564
- const c = child();
1565
- if (c) {
1566
- return createComponent$1(RouteContextObj, {
1567
- value: c,
1568
- get children() {
1569
- return c.outlet();
2036
+ function cacheKeyOp(key, fn) {
2037
+ key && !Array.isArray(key) && (key = [key]);
2038
+ for (let k of cacheMap.keys()) {
2039
+ if (key === undefined || matchKey(k, key)) fn(cacheMap.get(k));
2040
+ }
2041
+ }
2042
+ function query(fn, name) {
2043
+ // query implies GET: the router primitive is the declaration site, so a
2044
+ // server function handed to query() is wrapped with core `GET(fn)` here,
2045
+ // at query-creation (module scope) — the server half records the method
2046
+ // declaration for dispatch, the client half swaps in the GET transport.
2047
+ // An explicit `GET(fn)` already carries the declaration on the metadata
2048
+ // channel (`getServerFunctionMetadata(fn)?.method === "GET"`) and passes
2049
+ // through; non-server functions are untouched.
2050
+ if (isServerFunction(fn) && !getServerFunctionMetadata(fn)?.method) {
2051
+ fn = GET(fn);
2052
+ }
2053
+ const cachedFn = (...args) => {
2054
+ const cache = getCache();
2055
+ const intent = getIntent();
2056
+ const inPreloadFn = getInPreloadFn();
2057
+ const owner = getOwner();
2058
+ const navigate = owner ? useNavigate() : undefined;
2059
+ const now = Date.now();
2060
+ const key = name + hashKey(args);
2061
+ let cached = cache.get(key);
2062
+ let tracking;
2063
+ if (isServer) {
2064
+ const e = getRequestEvent();
2065
+ if (e) {
2066
+ const dataOnly = (e.router || (e.router = {})).dataOnly;
2067
+ if (dataOnly) {
2068
+ const data = e && (e.router.data || (e.router.data = {}));
2069
+ if (data && key in data) return data[key];
2070
+ if (Array.isArray(dataOnly) && !matchKey(key, dataOnly)) {
2071
+ data[key] = undefined;
2072
+ return Promise.resolve();
2073
+ }
1570
2074
  }
1571
- });
2075
+ }
2076
+ }
2077
+ if (getObserver() && !isServer) {
2078
+ tracking = true;
2079
+ onCleanup(() => cached[4].count--);
2080
+ }
2081
+ if (cached && cached[0] && (isServer || intent === "native" || cached[4].count || Date.now() - cached[0] < PRELOAD_TIMEOUT)) {
2082
+ if (tracking) {
2083
+ cached[4].count++;
2084
+ cached[4][0](); // track
2085
+ }
2086
+ if (cached[3] === "preload" && intent !== "preload") {
2087
+ cached[0] = now;
2088
+ }
2089
+ let res = cached[1];
2090
+ if (intent !== "preload") {
2091
+ res = "then" in cached[1] ? cached[1].then(handleResponse(false), handleResponse(true)) : handleResponse(false)(cached[1]);
2092
+ !isServer && intent === "navigate" && cached[4][1](cached[0]); // update version
2093
+ }
2094
+ inPreloadFn && "then" in res && res.catch(() => {});
2095
+ return res;
2096
+ }
2097
+ let res;
2098
+ if (!isServer && sharedConfig.has && sharedConfig.has(key)) {
2099
+ res = sharedConfig.load(key); // hydrating
2100
+ // @ts-ignore at least until we add a delete method to sharedConfig
2101
+ delete globalThis._$HY.r[key];
2102
+ } else res = fn(...args);
2103
+ if (cached) {
2104
+ cached[0] = now;
2105
+ cached[1] = res;
2106
+ cached[3] = intent;
2107
+ !isServer && intent === "navigate" && cached[4][1](cached[0]); // update version
2108
+ } else {
2109
+ cache.set(key, cached = [now, res,, intent, createSignal(now, {
2110
+ ownedWrite: true
2111
+ })]);
2112
+ cached[4].count = 0;
2113
+ }
2114
+ if (tracking) {
2115
+ cached[4].count++;
2116
+ cached[4][0](); // track
2117
+ }
2118
+ if (isServer) {
2119
+ const e = getRequestEvent();
2120
+ if (e && e.router.dataOnly) return e.router.data[key] = res;
2121
+ }
2122
+ if (intent !== "preload") {
2123
+ res = "then" in res ? res.then(handleResponse(false), handleResponse(true)) : handleResponse(false)(res);
2124
+ }
2125
+ inPreloadFn && "then" in res && res.catch(() => {});
2126
+ // serialize on server
2127
+ if (isServer && sharedConfig.context && sharedConfig.context.async && !sharedConfig.context.noHydrate) {
2128
+ const e = getRequestEvent();
2129
+ (!e || !e.serverOnly) && sharedConfig.context.serialize(key, res);
2130
+ }
2131
+ return res;
2132
+ function handleResponse(error) {
2133
+ return async v => {
2134
+ let enveloped;
2135
+ let hasEnveloped = false;
2136
+ if (isResponseEnvelope(v)) {
2137
+ // respond(): the value rides in memory beside the metadata
2138
+ enveloped = v.value;
2139
+ hasEnveloped = true;
2140
+ v = v.response;
2141
+ }
2142
+ if (v instanceof Response) {
2143
+ const e = getRequestEvent();
2144
+ if (e) {
2145
+ for (const [key, value] of v.headers) {
2146
+ if (key == "set-cookie") e.response.headers.append("set-cookie", value);else e.response.headers.set(key, value);
2147
+ }
2148
+ }
2149
+ const url = v.headers.get(LocationHeader);
2150
+ if (url !== null) {
2151
+ // client + server relative redirect
2152
+ if (navigate && url.startsWith("/")) navigate(url, {
2153
+ replace: true
2154
+ });else if (!isServer) window.location.href = url;else if (e) e.response.status = 302;
2155
+ return;
2156
+ }
2157
+ if (hasEnveloped) v = enveloped;else if (v.body) {
2158
+ // responses the transport hands over whole (revalidation) carry a
2159
+ // codec-encoded body; anything else (a raw user Response) stays whole
2160
+ const decoded = await decodeResponse(v);
2161
+ if (decoded !== undefined) v = decoded;
2162
+ }
2163
+ }
2164
+ if (error) throw v;
2165
+ cached[2] = v;
2166
+ return v;
2167
+ };
1572
2168
  }
1573
- return undefined;
1574
2169
  };
2170
+ cachedFn.keyFor = (...args) => name + hashKey(args);
2171
+ cachedFn.key = name;
2172
+ return cachedFn;
2173
+ }
2174
+ query.get = key => {
2175
+ const cached = getCache().get(key);
2176
+ return cached[2];
1575
2177
  };
1576
- const Route = props => {
1577
- const childRoutes = children(() => props.children);
1578
- return merge(props, {
1579
- get children() {
1580
- return childRoutes();
1581
- }
1582
- });
2178
+ query.set = (key, value) => {
2179
+ const cache = getCache();
2180
+ const now = Date.now();
2181
+ let cached = cache.get(key);
2182
+ if (cached) {
2183
+ cached[0] = now;
2184
+ cached[1] = Promise.resolve(value);
2185
+ cached[2] = value;
2186
+ cached[3] = "preload";
2187
+ } else {
2188
+ cache.set(key, cached = [now, Promise.resolve(value), value, "preload", createSignal(now, {
2189
+ ownedWrite: true
2190
+ })]);
2191
+ cached[4].count = 0;
2192
+ }
1583
2193
  };
1584
-
1585
- // for data only mode with single flight mutations
1586
- function dataOnly(event, routerState, branches) {
1587
- const url = new URL(event.request.url);
1588
- const prevMatches = getRouteMatches(branches, new URL(event.router.previousUrl || event.request.url).pathname);
1589
- const matches = getRouteMatches(branches, url.pathname);
1590
- for (let match = 0; match < matches.length; match++) {
1591
- if (!prevMatches[match] || matches[match].route !== prevMatches[match].route) event.router.dataOnly = true;
1592
- const {
1593
- route,
1594
- params
1595
- } = matches[match];
1596
- route.preload && route.preload({
1597
- params,
1598
- location: routerState.location,
1599
- intent: "preload"
1600
- });
2194
+ query.delete = key => getCache().delete(key);
2195
+ query.clear = () => getCache().clear();
2196
+ function matchKey(key, keys) {
2197
+ for (let k of keys) {
2198
+ if (k && key.startsWith(k)) return true;
1601
2199
  }
2200
+ return false;
1602
2201
  }
1603
2202
 
1604
- function createRouter(config) {
1605
- let ignore = false;
1606
- const wrap = value => typeof value === "string" ? {
1607
- value
1608
- } : value;
1609
- const [read, write] = createSignal(wrap(config.get()), {
1610
- equals: (a, b) => a.value === b.value && a.state === b.state,
1611
- ownedWrite: true
1612
- });
1613
- const signal = [read, next => {
1614
- !ignore && config.set(next);
1615
- if (sharedConfig.registry && !sharedConfig.done) sharedConfig.done = true;
1616
- write(next);
1617
- }];
1618
- config.init && onCleanup(config.init((value = config.get()) => {
1619
- ignore = true;
1620
- signal[1](wrap(value));
1621
- ignore = false;
1622
- }));
1623
- return createRouterComponent({
1624
- signal,
1625
- create: config.create,
1626
- utils: config.utils
1627
- });
1628
- }
1629
- function bindEvent(target, type, handler) {
1630
- target.addEventListener(type, handler);
1631
- return () => target.removeEventListener(type, handler);
2203
+ // Modified from the amazing Tanstack Query library (MIT)
2204
+ // https://github.com/TanStack/query/blob/main/packages/query-core/src/utils.ts#L168
2205
+ function hashKey(args) {
2206
+ return JSON.stringify(args, (_, val) => isPlainObject(val) ? Object.keys(val).sort().reduce((result, key) => {
2207
+ result[key] = val[key];
2208
+ return result;
2209
+ }, {}) : val);
1632
2210
  }
1633
- function scrollToHash(hash, fallbackTop) {
1634
- const el = hash && document.getElementById(hash);
1635
- if (el) {
1636
- el.scrollIntoView();
1637
- } else if (fallbackTop) {
1638
- window.scrollTo(0, 0);
1639
- }
2211
+ function isPlainObject(obj) {
2212
+ let proto;
2213
+ return obj != null && typeof obj === "object" && (!(proto = Object.getPrototypeOf(obj)) || proto === Object.prototype);
1640
2214
  }
1641
2215
 
1642
- function getPath(url) {
1643
- const u = new URL(url);
1644
- return u.pathname + u.search;
2216
+ const submitHooksSymbol = Symbol("routerActionSubmitHooks");
2217
+ const settledHooksSymbol = Symbol("routerActionSettledHooks");
2218
+ const invokeSymbol = Symbol("routerActionInvoke");
2219
+
2220
+ // Forms submitted through delegation are marked `aria-busy` while their
2221
+ // action is in flight — the form half of the attribute vocabulary links get
2222
+ // (`data-active`/`data-pending`). Style with `form[aria-busy] button { ... }`.
2223
+ // A counter (not a boolean) keeps the attribute through overlapping
2224
+ // submissions from the same form.
2225
+ const busyForms = /* #__PURE__ */new WeakMap();
2226
+ function setFormBusy(form, delta) {
2227
+ const count = (busyForms.get(form) || 0) + delta;
2228
+ busyForms.set(form, count);
2229
+ count > 0 ? form.setAttribute("aria-busy", "true") : form.removeAttribute("aria-busy");
1645
2230
  }
1646
- function StaticRouter(props) {
1647
- let e;
1648
- const obj = {
1649
- value: props.url || (e = getRequestEvent()) && getPath(e.request.url) || ""
1650
- };
1651
- return createRouterComponent({
1652
- signal: [() => obj, next => Object.assign(obj, next)]
1653
- })(props);
2231
+ const actions = /* #__PURE__ */new Map();
2232
+
2233
+ /**
2234
+ * The document-delegation submit handler for router actions. Lives here —
2235
+ * not in events.ts — so the router's event wiring holds no static reference
2236
+ * to the action module; `installRouterIntegrations` slots it in when the
2237
+ * first action is created on the client.
2238
+ */
2239
+ function handleFormAction(evt, router, actionBase) {
2240
+ if (evt.defaultPrevented) return;
2241
+ let actionRef = evt.submitter && evt.submitter.hasAttribute("formaction") ? evt.submitter.getAttribute("formaction") : evt.target.getAttribute("action");
2242
+ if (!actionRef) return;
2243
+ const serverAction = !actionRef.startsWith("https://action/");
2244
+ if (serverAction) {
2245
+ // normalize server actions
2246
+ const url = new URL(actionRef, mockBase);
2247
+ actionRef = router.parsePath(url.pathname + url.search);
2248
+ if (!actionRef.startsWith(actionBase)) return;
2249
+ }
2250
+ if (evt.target.method.toUpperCase() !== "POST") throw new Error("Only POST forms are supported for Actions");
2251
+ // A registry miss on a server-action url is a direct bind whose module
2252
+ // never loaded client-side (server components): the url is self-describing
2253
+ // (`?id`, bound `?args`), so a generic invocation is synthesized from it —
2254
+ // delegation alone is sufficient, the no-JS path stays a no-JS fallback.
2255
+ // Client-only actions (`https://action/`) are their module's JS by
2256
+ // definition, so a miss there falls through to native submission.
2257
+ const handler = actions.get(actionRef) || serverAction && createServerFormAction(actionRef);
2258
+ if (handler) {
2259
+ evt.preventDefault();
2260
+ const data = new FormData(evt.target, evt.submitter);
2261
+ handler.call({
2262
+ r: router,
2263
+ f: evt.target
2264
+ }, evt.target.enctype === "multipart/form-data" ? data : new URLSearchParams(data));
2265
+ }
1654
2266
  }
1655
2267
 
1656
- function setupNativeEvents({
1657
- preload = true,
1658
- explicitLinks = false,
1659
- actionBase = "/_server",
1660
- transformUrl
1661
- } = {}) {
1662
- return router => {
1663
- const basePath = router.base.path();
1664
- const navigateFromRoute = router.navigatorFactory(router.base);
1665
- let preloadTimeout;
1666
- let lastElement;
1667
- function isSvg(el) {
1668
- return el.namespaceURI === "http://www.w3.org/2000/svg";
1669
- }
1670
- function handleAnchor(evt) {
1671
- if (evt.defaultPrevented || evt.button !== 0 || evt.metaKey || evt.altKey || evt.ctrlKey || evt.shiftKey) return;
1672
- const a = evt.composedPath().find(el => el instanceof Node && el.nodeName.toUpperCase() === "A");
1673
- if (!a || explicitLinks && !a.hasAttribute("link")) return;
1674
- const svg = isSvg(a);
1675
- const href = svg ? a.href.baseVal : a.href;
1676
- const target = svg ? a.target.baseVal : a.target;
1677
- if (target || !href && !a.hasAttribute("state")) return;
1678
- const rel = (a.getAttribute("rel") || "").split(/\s+/);
1679
- if (a.hasAttribute("download") || rel && rel.includes("external")) return;
1680
- const url = svg ? new URL(href, document.baseURI) : new URL(href);
1681
- if (url.origin !== window.location.origin || basePath && url.pathname && !url.pathname.toLowerCase().startsWith(basePath.toLowerCase())) return;
1682
- return [a, url];
1683
- }
1684
- function handleAnchorClick(evt) {
1685
- const res = handleAnchor(evt);
1686
- if (!res) return;
1687
- const [a, url] = res;
1688
- const to = router.parsePath(url.pathname + url.search + url.hash);
1689
- const state = a.getAttribute("state");
1690
- evt.preventDefault();
1691
- navigateFromRoute(to, {
1692
- resolve: false,
1693
- replace: a.hasAttribute("replace"),
1694
- scroll: !a.hasAttribute("noscroll"),
1695
- state: state ? JSON.parse(state) : undefined
1696
- });
1697
- }
1698
- function handleAnchorPreload(evt) {
1699
- const res = handleAnchor(evt);
1700
- if (!res) return;
1701
- const [a, url] = res;
1702
- transformUrl && (url.pathname = transformUrl(url.pathname));
1703
- router.preloadRoute(url, a.getAttribute("preload") !== "false");
1704
- }
1705
- function handleAnchorMove(evt) {
1706
- clearTimeout(preloadTimeout);
1707
- const res = handleAnchor(evt);
1708
- if (!res) return lastElement = null;
1709
- const [a, url] = res;
1710
- if (lastElement === a) return;
1711
- transformUrl && (url.pathname = transformUrl(url.pathname));
1712
- preloadTimeout = setTimeout(() => {
1713
- router.preloadRoute(url, a.getAttribute("preload") !== "false");
1714
- lastElement = a;
1715
- }, 20);
1716
- }
1717
- function handleFormSubmit(evt) {
1718
- if (evt.defaultPrevented) return;
1719
- let actionRef = evt.submitter && evt.submitter.hasAttribute("formaction") ? evt.submitter.getAttribute("formaction") : evt.target.getAttribute("action");
1720
- if (!actionRef) return;
1721
- if (!actionRef.startsWith("https://action/")) {
1722
- // normalize server actions
1723
- const url = new URL(actionRef, mockBase);
1724
- actionRef = router.parsePath(url.pathname + url.search);
1725
- if (!actionRef.startsWith(actionBase)) return;
1726
- }
1727
- if (evt.target.method.toUpperCase() !== "POST") throw new Error("Only POST forms are supported for Actions");
1728
- const handler = actions.get(actionRef);
1729
- if (handler) {
1730
- evt.preventDefault();
1731
- const data = new FormData(evt.target, evt.submitter);
1732
- handler.call({
1733
- r: router,
1734
- f: evt.target
1735
- }, evt.target.enctype === "multipart/form-data" ? data : new URLSearchParams(data));
1736
- }
1737
- }
2268
+ /**
2269
+ * Synthesizes a router action for a server-rendered action url. The url
2270
+ * carries everything an invocation needs — the function id and any bound
2271
+ * `.with()` arguments (plain JSON in `?args`, which the server prepends for
2272
+ * natural-encoding bodies exactly as it does for no-JS posts) — so the
2273
+ * FormData is posted to it verbatim through the server-function transport:
2274
+ * submissions, `aria-busy`, redirects, revalidation, and single-flight all
2275
+ * flow through the normal action machinery. Registered under the url, so
2276
+ * repeat submits reuse it (and a later real registration overrides it).
2277
+ */
2278
+ function createServerFormAction(url) {
2279
+ const id = new URL(url, mockBase).searchParams.get("id");
2280
+ if (!id) return undefined;
2281
+ // typecheck resolves the server half of the dual module; this path only
2282
+ // runs in the browser, where the client transport's signature applies
2283
+ const stub = createServerReference(id, undefined, url);
2284
+ const caller = Object.assign(form => stub(form), {
2285
+ url
2286
+ });
2287
+ return actionImpl(caller);
2288
+ }
1738
2289
 
1739
- // ensure delegated event run first
1740
- delegateEvents(["click", "submit"]);
1741
- document.addEventListener("click", handleAnchorClick);
1742
- if (preload) {
1743
- document.addEventListener("mousemove", handleAnchorMove, {
1744
- passive: true
1745
- });
1746
- document.addEventListener("focusin", handleAnchorPreload, {
1747
- passive: true
1748
- });
1749
- document.addEventListener("touchstart", handleAnchorPreload, {
1750
- passive: true
1751
- });
1752
- }
1753
- document.addEventListener("submit", handleFormSubmit);
1754
- onCleanup(() => {
1755
- document.removeEventListener("click", handleAnchorClick);
1756
- if (preload) {
1757
- document.removeEventListener("mousemove", handleAnchorMove);
1758
- document.removeEventListener("focusin", handleAnchorPreload);
1759
- document.removeEventListener("touchstart", handleAnchorPreload);
1760
- }
1761
- document.removeEventListener("submit", handleFormSubmit);
1762
- });
1763
- };
2290
+ /**
2291
+ * Entry point for delegation's lazy fallback (data/events.ts): when no form
2292
+ * handler was ever installed — no action module in the client graph at all —
2293
+ * the router intercepts posts to server-action urls synchronously and loads
2294
+ * this module to run them. The FormData was captured at submit time; only
2295
+ * the enctype conversion and the generic invocation happen here.
2296
+ */
2297
+ function submitServerForm(router, url, form, data) {
2298
+ const handler = actions.get(url) || createServerFormAction(url);
2299
+ // no `?id` — not the server function convention; nothing can run it,
2300
+ // resubmit natively (submit() bypasses the delegated handler)
2301
+ if (!handler) return form.submit();
2302
+ handler.call({
2303
+ r: router,
2304
+ f: form
2305
+ }, form.enctype === "multipart/form-data" ? data : new URLSearchParams(data));
1764
2306
  }
1765
2307
 
1766
- function Router(props) {
1767
- if (isServer) return StaticRouter(props);
1768
- const getSource = () => {
1769
- const url = window.location.pathname + window.location.search;
1770
- const state = window.history.state && window.history.state._depth && Object.keys(window.history.state).length === 1 ? undefined : window.history.state;
1771
- return {
1772
- value: url + window.location.hash,
1773
- state
1774
- };
1775
- };
1776
- const beforeLeave = createBeforeLeave();
1777
- return createRouter({
1778
- get: getSource,
1779
- set({
1780
- value,
1781
- replace,
1782
- scroll,
1783
- state
1784
- }) {
1785
- if (replace) {
1786
- window.history.replaceState(keepDepth(state), "", value);
1787
- } else {
1788
- window.history.pushState(state, "", value);
1789
- }
1790
- scrollToHash(decodeURIComponent(window.location.hash.slice(1)), scroll);
1791
- saveCurrentDepth();
2308
+ // Wires the action layer into the router's slots exactly once, triggered by
2309
+ // the first action creation. Not an import side effect — with
2310
+ // `sideEffects: false`, module evaluation only happens when action() is
2311
+ // actually used, which is precisely when the wiring is wanted: no action in
2312
+ // the graph means no form interception, no single-flight subscription (the
2313
+ // server is never asked to collect), and no flash cookies to decode. On the
2314
+ // server, actions are created at module scope, so the flash decoder is
2315
+ // always installed before useSubmission can read the submissions signal.
2316
+ let integrationsInstalled = false;
2317
+ function installRouterIntegrations() {
2318
+ if (integrationsInstalled) return;
2319
+ integrationsInstalled = true;
2320
+ provideFlashDecoder(decodeFlashCookie);
2321
+ if (!isServer) {
2322
+ setRouterFormHandler(handleFormAction);
2323
+ provideFlightConsumer(setupFlightDataConsumer);
2324
+ }
2325
+ }
2326
+ function useSubmissions(fn, filter) {
2327
+ const router = useRouter();
2328
+ const subs = createMemo(() => router.submissions[0]().filter(s => s.url === fn.base && (!filter || filter(s.input))));
2329
+ return new Proxy([], {
2330
+ get(_, property) {
2331
+ if (property === $TRACK) return subs();
2332
+ return subs()[property];
1792
2333
  },
1793
- init: notify => bindEvent(window, "popstate", notifyIfNotBlocked(notify, delta => {
1794
- if (delta) {
1795
- return !beforeLeave.confirm(delta);
1796
- } else {
1797
- const s = getSource();
1798
- return !beforeLeave.confirm(s.value, {
1799
- state: s.state
1800
- });
2334
+ has(_, property) {
2335
+ return property in subs();
2336
+ }
2337
+ });
2338
+ }
2339
+ function useAction(action) {
2340
+ const r = useRouter();
2341
+ return (...args) => action.apply({
2342
+ r
2343
+ }, args);
2344
+ }
2345
+ function actionImpl(fn, options = {}) {
2346
+ async function invoke(variables, current) {
2347
+ const router = this.r;
2348
+ const form = this.f;
2349
+ const submitHooks = current[submitHooksSymbol];
2350
+ const settledHooks = current[settledHooksSymbol];
2351
+ // Single-flight opt-in is no longer per call: the router's registered
2352
+ // flight-data consumer (see setupFlightDataConsumer) makes the transport
2353
+ // send the request header itself, so the mutation is just called.
2354
+ const runMutation = () => fn(...variables);
2355
+ const run = action$1(async function* (context) {
2356
+ context.optimistic?.();
2357
+ try {
2358
+ const value = await context.call();
2359
+ yield;
2360
+ return {
2361
+ error: false,
2362
+ value
2363
+ };
2364
+ } catch (error) {
2365
+ yield;
2366
+ return {
2367
+ error: true,
2368
+ value: error
2369
+ };
1801
2370
  }
1802
- })),
1803
- create: setupNativeEvents({
1804
- preload: props.preload,
1805
- explicitLinks: props.explicitLinks,
1806
- actionBase: props.actionBase,
1807
- transformUrl: props.transformUrl
1808
- }),
1809
- utils: {
1810
- go: delta => window.history.go(delta),
1811
- beforeLeave
2371
+ });
2372
+ form && setFormBusy(form, 1);
2373
+ let settled;
2374
+ let response;
2375
+ try {
2376
+ settled = await settleActionResult(run({
2377
+ call: runMutation,
2378
+ optimistic: submitHooks.size ? () => {
2379
+ for (const hook of submitHooks.values()) hook(...variables);
2380
+ } : undefined
2381
+ }));
2382
+ response = await handleResponse(settled.value, settled.error, router.navigatorFactory());
2383
+ } finally {
2384
+ form && setFormBusy(form, -1);
1812
2385
  }
1813
- })(props);
2386
+ if (!response) return undefined;
2387
+ let submission;
2388
+ submission = {
2389
+ input: variables,
2390
+ url,
2391
+ result: response.data,
2392
+ error: response.error,
2393
+ clear() {
2394
+ router.submissions[1](entries => entries.filter(entry => entry !== submission));
2395
+ },
2396
+ retry() {
2397
+ submission.clear();
2398
+ return current[invokeSymbol].call({
2399
+ r: router,
2400
+ f: form
2401
+ }, variables, current);
2402
+ }
2403
+ };
2404
+ router.submissions[1](entries => [...entries, submission]);
2405
+ for (const hook of settledHooks.values()) hook(submission);
2406
+ if (response.error && !form) throw response.error;
2407
+ return response.data;
2408
+ }
2409
+ const o = typeof options === "string" ? {
2410
+ name: options
2411
+ } : options;
2412
+ const name = o.name || (!isServer ? String(hashString(fn.toString())) : undefined);
2413
+ const url = fn.url || name && `https://action/${name}` || "";
2414
+ const wrapped = toAction(invoke, url);
2415
+ if (name) setFunctionName(wrapped, name);
2416
+ return wrapped;
1814
2417
  }
1815
-
1816
- function hashParser(str) {
1817
- const to = str.replace(/^.*?#/, "");
1818
- // Hash-only hrefs like `#foo` from plain anchors will come in as `/#foo` whereas a link to
1819
- // `/foo` will be `/#/foo`. Check if the to starts with a `/` and if not append it as a hash
1820
- // to the current path so we can handle these in-page anchors correctly.
1821
- if (!to.startsWith("/")) {
1822
- const [, path = "/"] = window.location.hash.split("#", 2);
1823
- return `${path}#${to}`;
2418
+ const action = actionImpl;
2419
+ function toAction(invoke, url, boundArgs = [], base = url, submitHooks = new Map(), settledHooks = new Map()) {
2420
+ const fn = function (...args) {
2421
+ return invoke.call(this, [...boundArgs, ...args], fn);
2422
+ };
2423
+ fn.toString = () => {
2424
+ if (!url) throw new Error("Client Actions need explicit names if server rendered");
2425
+ return url;
2426
+ };
2427
+ fn.with = function (...args) {
2428
+ const uri = new URL(url, mockBase);
2429
+ uri.searchParams.set("args", hashKey(args));
2430
+ const next = toAction(invoke, (uri.origin === "https://action" ? uri.origin : "") + uri.pathname + uri.search, [...boundArgs, ...args], base, submitHooks, settledHooks);
2431
+ return next;
2432
+ };
2433
+ fn.onSubmit = function (hook) {
2434
+ const id = Symbol("actionOnSubmitHook");
2435
+ submitHooks.set(id, hook);
2436
+ getOwner() && onCleanup(() => submitHooks.delete(id));
2437
+ return this;
2438
+ };
2439
+ fn.onSettled = function (hook) {
2440
+ const id = Symbol("actionOnSettledHook");
2441
+ settledHooks.set(id, hook);
2442
+ getOwner() && onCleanup(() => settledHooks.delete(id));
2443
+ return this;
2444
+ };
2445
+ fn.url = url;
2446
+ fn.base = base;
2447
+ fn[submitHooksSymbol] = submitHooks;
2448
+ fn[settledHooksSymbol] = settledHooks;
2449
+ fn[invokeSymbol] = invoke;
2450
+ installRouterIntegrations();
2451
+ if (!isServer) {
2452
+ actions.set(url, fn);
2453
+ // Only remove the registration if it still belongs to this instance —
2454
+ // a re-created action (e.g. a new `.with()` binding after revalidation)
2455
+ // may have registered itself under the same URL since.
2456
+ getOwner() && onCleanup(() => actions.get(url) === fn && actions.delete(url));
1824
2457
  }
1825
- return to;
2458
+ return fn;
1826
2459
  }
1827
- function HashRouter(props) {
1828
- const getSource = () => window.location.hash.slice(1);
1829
- const beforeLeave = createBeforeLeave();
1830
- return createRouter({
1831
- get: getSource,
1832
- set({
1833
- value,
1834
- replace,
1835
- scroll,
1836
- state
1837
- }) {
1838
- if (replace) {
1839
- window.history.replaceState(keepDepth(state), "", "#" + value);
1840
- } else {
1841
- window.history.pushState(state, "", "#" + value);
1842
- }
1843
- const hashIndex = value.indexOf("#");
1844
- const hash = hashIndex >= 0 ? value.slice(hashIndex + 1) : "";
1845
- scrollToHash(hash, scroll);
1846
- saveCurrentDepth();
1847
- },
1848
- init: notify => bindEvent(window, "hashchange", notifyIfNotBlocked(notify, delta => !beforeLeave.confirm(delta && delta < 0 ? delta : getSource()))),
1849
- create: setupNativeEvents({
1850
- preload: props.preload,
1851
- explicitLinks: props.explicitLinks,
1852
- actionBase: props.actionBase
1853
- }),
1854
- utils: {
1855
- go: delta => window.history.go(delta),
1856
- renderPath: path => `#${path}`,
1857
- parsePath: hashParser,
1858
- beforeLeave
2460
+ const hashString = s => s.split("").reduce((a, b) => (a << 5) - a + b.charCodeAt(0) | 0, 0);
2461
+ async function settleActionResult(result) {
2462
+ const value = result;
2463
+ if (value && typeof value.then === "function") {
2464
+ return result.then(value => value);
2465
+ }
2466
+ if (value && typeof value.next === "function") {
2467
+ const iterator = value;
2468
+ let next = await iterator.next();
2469
+ while (!next.done) {
2470
+ next = await iterator.next();
1859
2471
  }
1860
- })(props);
2472
+ return next.value;
2473
+ }
2474
+ return result;
1861
2475
  }
1862
2476
 
1863
- function createMemoryHistory() {
1864
- const entries = ["/"];
1865
- let index = 0;
1866
- const listeners = [];
1867
- const go = n => {
1868
- // https://github.com/remix-run/react-router/blob/682810ca929d0e3c64a76f8d6e465196b7a2ac58/packages/router/history.ts#L245
1869
- index = Math.max(0, Math.min(index + n, entries.length - 1));
1870
- const value = entries[index];
1871
- listeners.forEach(listener => listener(value));
1872
- };
1873
- return {
1874
- get: () => entries[index],
1875
- set: ({
1876
- value,
1877
- scroll,
1878
- replace
1879
- }) => {
1880
- if (replace) {
1881
- entries[index] = value;
2477
+ /**
2478
+ * Registers the router as the single-flight consumer of the server function
2479
+ * transport. Subscribing is the opt-in: while registered, the transport
2480
+ * sends the `X-Single-Flight` request header on mutations and delivers the
2481
+ * folded payload here — fresh route data is seeded into the `query` cache
2482
+ * and the envelope metadata (redirect `Location`, `X-Revalidate` keys) is
2483
+ * applied, all before the action sees its plain return value. Called by the
2484
+ * Router component on the client unless `singleFlight={false}`, which now
2485
+ * simply means "never subscribe" — no consumer, no request header, no
2486
+ * collection work on the server. Returns the unsubscribe function.
2487
+ */
2488
+ function setupFlightDataConsumer(router) {
2489
+ return subscribeFlightData((data, {
2490
+ response
2491
+ }) => applyResponseMetadata(response, router.navigatorFactory(), data));
2492
+ }
2493
+
2494
+ /**
2495
+ * Applies a server function response's integration metadata: `X-Revalidate`
2496
+ * keys invalidate, `Location` navigates (hard for absolute urls), flight
2497
+ * data seeds the query cache, and matching entries revalidate. Shared by
2498
+ * the flight-data consumer and the action response path (which still sees
2499
+ * metadata-bearing responses when no flight data was collected).
2500
+ */
2501
+ async function applyResponseMetadata(metadata, navigate, flightData) {
2502
+ let keys;
2503
+ if (metadata) {
2504
+ if (metadata.headers.has("X-Revalidate")) keys = metadata.headers.get("X-Revalidate").split(",");
2505
+ if (metadata.headers.has("Location")) {
2506
+ const locationUrl = metadata.headers.get("Location") || "/";
2507
+ if (locationUrl.startsWith("http")) {
2508
+ window.location.href = locationUrl;
1882
2509
  } else {
1883
- entries.splice(index + 1, entries.length - index, value);
1884
- index++;
2510
+ navigate(locationUrl);
1885
2511
  }
1886
- listeners.forEach(listener => listener(value));
1887
- setTimeout(() => {
1888
- if (scroll) {
1889
- scrollToHash(value.split("#")[1] || "", true);
1890
- }
1891
- }, 0);
1892
- },
1893
- back: () => {
1894
- go(-1);
1895
- },
1896
- forward: () => {
1897
- go(1);
1898
- },
1899
- go,
1900
- listen: listener => {
1901
- listeners.push(listener);
1902
- return () => {
1903
- const index = listeners.indexOf(listener);
1904
- listeners.splice(index, 1);
1905
- };
1906
2512
  }
1907
- };
2513
+ }
2514
+ // invalidate
2515
+ cacheKeyOp(keys, entry => entry[0] = 0);
2516
+ // set cache
2517
+ flightData && Object.keys(flightData).forEach(k => query.set(k, flightData[k]));
2518
+ // trigger revalidation
2519
+ await revalidate(keys, false);
1908
2520
  }
1909
- function MemoryRouter(props) {
1910
- const memoryHistory = props.history || createMemoryHistory();
1911
- return createRouter({
1912
- get: memoryHistory.get,
1913
- set: memoryHistory.set,
1914
- init: memoryHistory.listen,
1915
- create: setupNativeEvents({
1916
- preload: props.preload,
1917
- explicitLinks: props.explicitLinks,
1918
- actionBase: props.actionBase
1919
- }),
1920
- utils: {
1921
- go: memoryHistory.go
2521
+ async function handleResponse(response, error, navigate) {
2522
+ let data;
2523
+ let flightData;
2524
+ let metadata;
2525
+ if (isResponseEnvelope(response)) {
2526
+ // client-only respond(): the value rides in memory beside the metadata
2527
+ data = response.value;
2528
+ metadata = response.response;
2529
+ } else if (response instanceof Response) {
2530
+ metadata = response;
2531
+ // responses the transport hands over whole (redirects, revalidation)
2532
+ // carry a codec-encoded body the router decodes itself. With the
2533
+ // flight-data consumer registered single-flight payloads never reach
2534
+ // this path, but a manually opted-in call (no consumer) still can —
2535
+ // unwrap the standardized { value, data } shape for it too.
2536
+ if (response.body) {
2537
+ data = await decodeResponse(response);
2538
+ if (response.headers.has("X-Single-Flight")) {
2539
+ const payload = data;
2540
+ data = payload.value;
2541
+ flightData = payload.data;
2542
+ }
1922
2543
  }
1923
- })(props);
2544
+ } else if (error) return {
2545
+ error: response
2546
+ };else data = response;
2547
+ await applyResponseMetadata(metadata, navigate, flightData);
2548
+ return data != null ? {
2549
+ data
2550
+ } : undefined;
1924
2551
  }
1925
2552
 
1926
- var _tmpl$ = /*#__PURE__*/template(`<a>`);
2553
+ // The delegation fallback's lazy entry (see data/events.ts). Nothing imports
2554
+ // this module statically — it exists so the dynamic import has a target that
2555
+ // bundlers can keep as a split point: router-only apps never load the action
2556
+ // machinery unless a server-action form actually submits.
1927
2557
 
1928
- // the JSX namespace lives in @solidjs/web's jsx-runtime module as of 2.0
1929
-
1930
- function toClassName(value) {
1931
- if (!value) return "";
1932
- if (typeof value === "string" || typeof value === "number") return String(value);
1933
- if (Array.isArray(value)) return value.map(toClassName).filter(Boolean).join(" ");
1934
- if (typeof value === "object") {
1935
- return Object.entries(value).filter(([, enabled]) => enabled).map(([name]) => name).join(" ");
1936
- }
1937
- return "";
1938
- }
1939
- function A(props) {
1940
- props = merge({
1941
- inactiveClass: "inactive",
1942
- activeClass: "active"
1943
- }, props);
1944
- const rest = omit(props, "href", "state", "class", "activeClass", "inactiveClass", "end");
1945
- const to = useResolvedPath(() => props.href);
1946
- const href = useHref(to);
1947
- const location = useLocation();
1948
- const isActive = createMemo(() => {
1949
- const to_ = to();
1950
- if (to_ === undefined) return [false, false];
1951
- // trailing slashes are ignored so `/route` and `/route/` share active state
1952
- const path = normalizePath(to_.split(/[?#]/, 1)[0]).toLowerCase().replace(/\/$/, "");
1953
- const loc = decodeURI(normalizePath(location.pathname).toLowerCase().replace(/\/$/, ""));
1954
- return [props.end ? path === loc : loc.startsWith(path + "/") || loc === path, path === loc];
1955
- });
1956
- const className = createMemo(() => [toClassName(props.class), isActive()[0] ? props.activeClass : props.inactiveClass].filter(Boolean).join(" "));
1957
- var _el$ = _tmpl$();
1958
- spread(_el$, mergeProps(rest, {
1959
- get href() {
1960
- return href() || props.href;
1961
- },
1962
- get state() {
1963
- return JSON.stringify(props.state);
1964
- },
1965
- get ["class"]() {
1966
- return className();
1967
- },
1968
- "link": true,
1969
- get ["aria-current"]() {
1970
- return isActive()[1] ? "page" : undefined;
1971
- }
1972
- }), false);
1973
- return _el$;
1974
- }
1975
- function Navigate(props) {
1976
- const navigate = useNavigate();
1977
- const location = useLocation();
1978
- const {
1979
- href,
1980
- state
1981
- } = props;
1982
- const path = typeof href === "function" ? href({
1983
- navigate,
1984
- location
1985
- }) : href;
1986
- navigate(path, {
1987
- replace: true,
1988
- state
1989
- });
1990
- return null;
1991
- }
2558
+ var serverForms = /*#__PURE__*/Object.freeze({
2559
+ __proto__: null,
2560
+ submitServerForm: submitServerForm
2561
+ });
1992
2562
 
1993
- export { A, HashRouter, MemoryRouter, Navigate, Route, Router, RouterContextObj as RouterContext, StaticRouter, mergeSearchString as _mergeSearchString, action, createBeforeLeave, createMemoryHistory, createRouter, keepDepth, notifyIfNotBlocked, query, revalidate, saveCurrentDepth, useAction, useBeforeLeave, useCurrentMatches, useHref, useIsRouting, useLocation, useMatch, useNavigate, useParams, usePreloadRoute, useResolvedPath, useSearchParams, useSubmissions };
2563
+ export { RouterContextObj as RouterContext, mergeSearchString as _mergeSearchString, action, browserHistory, createBeforeLeave, createRouter, defineRoutes, hashHistory, int, memoryHistory, query, revalidate, useAction, useBeforeLeave, useHref, useIsRouting, useLinkState, useLocation, useMatch, useNavigate, useParams, usePreloadRoute, useResolvedPath, useRouteMatches, useSearchParams, useSubmissions };