@solidjs/router 0.17.0-next.5 → 1.0.0-next.10

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 (51) hide show
  1. package/README.md +526 -716
  2. package/dist/claims.d.ts +21 -0
  3. package/dist/claims.js +115 -0
  4. package/dist/data/action.d.ts +28 -1
  5. package/dist/data/action.js +218 -52
  6. package/dist/data/events.d.ts +8 -0
  7. package/dist/data/events.js +23 -22
  8. package/dist/data/flash.d.ts +21 -0
  9. package/dist/data/flash.js +78 -0
  10. package/dist/data/flashCookie.d.ts +7 -0
  11. package/dist/data/flashCookie.js +20 -0
  12. package/dist/data/query.js +11 -4
  13. package/dist/data/serverForms.d.ts +1 -0
  14. package/dist/data/serverForms.js +5 -0
  15. package/dist/index.d.ts +5 -3
  16. package/dist/index.js +1548 -683
  17. package/dist/index.jsx +2 -2
  18. package/dist/lifecycle.d.ts +29 -4
  19. package/dist/lifecycle.js +40 -37
  20. package/dist/paths.d.ts +117 -0
  21. package/dist/paths.js +41 -0
  22. package/dist/routers/components.d.ts +10 -21
  23. package/dist/routers/components.jsx +29 -44
  24. package/dist/routers/factory.d.ts +66 -0
  25. package/dist/routers/factory.jsx +151 -0
  26. package/dist/routers/history.d.ts +26 -0
  27. package/dist/routers/history.js +180 -0
  28. package/dist/routers/index.d.ts +4 -11
  29. package/dist/routers/index.js +2 -6
  30. package/dist/routers/scrollRestoration.d.ts +33 -0
  31. package/dist/routers/scrollRestoration.js +135 -0
  32. package/dist/routing.d.ts +80 -44
  33. package/dist/routing.js +311 -108
  34. package/dist/server.d.ts +79 -0
  35. package/dist/server.js +284 -0
  36. package/dist/types.d.ts +75 -6
  37. package/dist/utils.d.ts +2 -0
  38. package/dist/utils.js +2 -0
  39. package/package.json +10 -8
  40. package/dist/components.d.ts +0 -31
  41. package/dist/components.jsx +0 -46
  42. package/dist/routers/HashRouter.d.ts +0 -9
  43. package/dist/routers/HashRouter.js +0 -41
  44. package/dist/routers/MemoryRouter.d.ts +0 -24
  45. package/dist/routers/MemoryRouter.js +0 -57
  46. package/dist/routers/Router.d.ts +0 -9
  47. package/dist/routers/Router.js +0 -45
  48. package/dist/routers/StaticRouter.d.ts +0 -6
  49. package/dist/routers/StaticRouter.js +0 -15
  50. package/dist/routers/createRouter.d.ts +0 -10
  51. package/dist/routers/createRouter.js +0 -40
package/dist/index.js CHANGED
@@ -1,87 +1,6 @@
1
- import { isServer, getRequestEvent, createComponent as createComponent$1, memo, isResponseEnvelope, delegateEvents, spread, mergeProps, template } from '@solidjs/web';
2
- import { getOwner, runWithOwner, createMemo, createContext, onCleanup, useContext, untrack, createSignal, flush, createComponent, children, merge, createRoot, sharedConfig, getObserver, $TRACK, action as action$1, omit } from 'solid-js';
3
- import { decodeResponse } 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, isPending, flush, createComponent, createRoot, createEffect, 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,6 +180,355 @@ function setFunctionName(obj, value) {
258
180
  return obj;
259
181
  }
260
182
 
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
+ }
211
+
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;
229
+ }
230
+ if (url.origin !== window.location.origin || basePath && url.pathname && !url.pathname.toLowerCase().startsWith(basePath.toLowerCase())) return;
231
+ return comparablePath(url.pathname);
232
+ }
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
+ //
271
+ // `transparent` keeps the effect invisible to the hydration id scheme.
272
+ // This setup is client-only, so an id-consuming node here has no server
273
+ // counterpart and every subsequent hydration id would shift by one child
274
+ // slot — lazy-route lookups miss and hydration leaves server nodes
275
+ // unclaimed. (The option is honored by the runtime but missing from the
276
+ // published EffectOptions type, hence the cast.)
277
+ createRenderEffect(() => (router.location.pathname, router.isRouting()), () => registry.forEach(a => refresh(a, claimed.get(a))), {
278
+ transparent: true
279
+ });
280
+ onCleanup(registerElementClaim(node => {
281
+ if (node.nodeName.toUpperCase() !== "A") return;
282
+ const a = node;
283
+ // re-claim (href changed): the claiming write runs inside another
284
+ // effect, so refresh without leaking subscriptions into it
285
+ const existing = claimed.get(a);
286
+ if (existing) return refresh(a, existing);
287
+ const rec = {
288
+ current: false
289
+ };
290
+ claimed.set(a, rec);
291
+ // claims fire during component setup, so an owner is present in
292
+ // practice to bound the registry entry's lifetime; without one, state
293
+ // is still applied once at creation
294
+ if (getOwner()) {
295
+ registry.add(a);
296
+ onCleanup(() => registry.delete(a));
297
+ }
298
+ refresh(a, rec);
299
+ }));
300
+ }
301
+
302
+ /**
303
+ * The submit delegation consults this slot instead of importing the action
304
+ * module: the action side installs its handler on first action creation
305
+ * (see data/action.ts), so an app that never creates an action never pulls
306
+ * the data layer into its bundle through the router's event wiring.
307
+ */
308
+
309
+ let formHandler;
310
+ function setRouterFormHandler(handler) {
311
+ formHandler = handler;
312
+ }
313
+ function setupNativeEvents({
314
+ preload = true,
315
+ explicitLinks = false,
316
+ actionBase = "/_server",
317
+ transformUrl
318
+ } = {}) {
319
+ return router => {
320
+ const basePath = router.base.path();
321
+ const navigateFromRoute = router.navigatorFactory(router.base);
322
+ let preloadTimeout;
323
+ let lastElement;
324
+ function isSvg(el) {
325
+ return el.namespaceURI === "http://www.w3.org/2000/svg";
326
+ }
327
+ function handleAnchor(evt) {
328
+ if (evt.defaultPrevented || evt.button !== 0 || evt.metaKey || evt.altKey || evt.ctrlKey || evt.shiftKey) return;
329
+ const a = evt.composedPath().find(el => el instanceof Node && el.nodeName.toUpperCase() === "A");
330
+ if (!a || explicitLinks && !a.hasAttribute("link")) return;
331
+ const svg = isSvg(a);
332
+ const href = svg ? a.href.baseVal : a.href;
333
+ const target = svg ? a.target.baseVal : a.target;
334
+ if (target || !href && !a.hasAttribute("state")) return;
335
+ const rel = (a.getAttribute("rel") || "").split(/\s+/);
336
+ if (a.hasAttribute("download") || rel && rel.includes("external")) return;
337
+ const url = svg ? new URL(href, document.baseURI) : new URL(href);
338
+ if (url.origin !== window.location.origin || basePath && url.pathname && !url.pathname.toLowerCase().startsWith(basePath.toLowerCase())) return;
339
+ return [a, url];
340
+ }
341
+ function handleAnchorClick(evt) {
342
+ const res = handleAnchor(evt);
343
+ if (!res) return;
344
+ const [a, url] = res;
345
+ const to = router.parsePath(url.pathname + url.search + url.hash);
346
+ const state = a.getAttribute("state");
347
+ evt.preventDefault();
348
+ navigateFromRoute(to, {
349
+ resolve: false,
350
+ replace: a.hasAttribute("replace"),
351
+ scroll: !a.hasAttribute("noscroll"),
352
+ state: state ? JSON.parse(state) : undefined
353
+ });
354
+ }
355
+ function handleAnchorPreload(evt) {
356
+ const res = handleAnchor(evt);
357
+ if (!res) return;
358
+ const [a, url] = res;
359
+ transformUrl && (url.pathname = transformUrl(url.pathname));
360
+ router.preloadRoute(url, a.getAttribute("preload") !== "false");
361
+ }
362
+ function handleAnchorMove(evt) {
363
+ clearTimeout(preloadTimeout);
364
+ const res = handleAnchor(evt);
365
+ if (!res) return lastElement = null;
366
+ const [a, url] = res;
367
+ if (lastElement === a) return;
368
+ transformUrl && (url.pathname = transformUrl(url.pathname));
369
+ preloadTimeout = setTimeout(() => {
370
+ router.preloadRoute(url, a.getAttribute("preload") !== "false");
371
+ lastElement = a;
372
+ }, 20);
373
+ }
374
+ function handleFormSubmit(evt) {
375
+ if (formHandler) return formHandler(evt, router, actionBase);
376
+ // No form handler means no action module in the client graph at all
377
+ // (e.g. server components binding forms straight to server functions).
378
+ // A POST to a url under actionBase is self-describing, so delegation
379
+ // is still sufficient: intercept synchronously — the no-JS treatment
380
+ // is reserved for clients with no JS — capture the FormData, and load
381
+ // the handler lazily. Apps that never submit one never load it.
382
+ if (evt.defaultPrevented) return;
383
+ const form = evt.target;
384
+ const ref = evt.submitter && evt.submitter.hasAttribute("formaction") ? evt.submitter.getAttribute("formaction") : form.getAttribute("action");
385
+ if (!ref || ref.startsWith("https://action/")) return;
386
+ const url = new URL(ref, document.baseURI);
387
+ const path = router.parsePath(url.pathname + url.search);
388
+ if (!path.startsWith(actionBase) || form.method.toUpperCase() !== "POST") return;
389
+ evt.preventDefault();
390
+ const data = new FormData(form, evt.submitter);
391
+ Promise.resolve().then(function () { return serverForms; }).then(m => m.submitServerForm(router, path, form, data));
392
+ }
393
+
394
+ // ensure delegated event run first
395
+ delegateEvents(["click", "submit"]);
396
+ document.addEventListener("click", handleAnchorClick);
397
+ if (preload) {
398
+ document.addEventListener("mousemove", handleAnchorMove, {
399
+ passive: true
400
+ });
401
+ document.addEventListener("focusin", handleAnchorPreload, {
402
+ passive: true
403
+ });
404
+ document.addEventListener("touchstart", handleAnchorPreload, {
405
+ passive: true
406
+ });
407
+ }
408
+ document.addEventListener("submit", handleFormSubmit);
409
+ onCleanup(() => {
410
+ document.removeEventListener("click", handleAnchorClick);
411
+ if (preload) {
412
+ document.removeEventListener("mousemove", handleAnchorMove);
413
+ document.removeEventListener("focusin", handleAnchorPreload);
414
+ document.removeEventListener("touchstart", handleAnchorPreload);
415
+ }
416
+ document.removeEventListener("submit", handleFormSubmit);
417
+ });
418
+ };
419
+ }
420
+
421
+ /*
422
+ * The typed path proxy. Property access descends into static segments, calls
423
+ * bind params, and a zero-arg or search-object call terminates to a plain
424
+ * string. The runtime is tree-agnostic — it just builds strings — while the
425
+ * `RoutePaths<R>` type derived from the route config constrains which
426
+ * accesses and calls exist. Every node also coerces via `toString`, so nodes
427
+ * drop straight into `href`, `navigate()`, and `redirect()`.
428
+ */
429
+
430
+ // ---------------------------------------------------------------------------
431
+ // Typed match filters
432
+ // ---------------------------------------------------------------------------
433
+
434
+ /**
435
+ * A match filter that also declares the TypeScript type accepted for the
436
+ * param at `paths` callsites (the runtime param remains a string).
437
+ */
438
+
439
+ /** Matches integer segments; types the param as `number` in the path proxy. */
440
+ const int = s => /^-?\d+$/.test(s);
441
+
442
+ // ---------------------------------------------------------------------------
443
+ // RoutePaths<R> — the proxy's type, derived from the route tree
444
+ // ---------------------------------------------------------------------------
445
+
446
+ /** Collects a maximal run of required params (and a trailing splat) into one call's argument tuple. */
447
+
448
+ /** The search param types a route end carries: input builds URLs, output is what parsing returns. */
449
+
450
+ /** Terminating calls available on every route end: zero-arg, or search object plus optional hash. */
451
+
452
+ /**
453
+ * Sees through a lazy `children` thunk: the routes the import's promise
454
+ * resolves to (its `default` or `routes` export, matching the runtime) type
455
+ * exactly like inline children. Only tables genuinely built at runtime —
456
+ * where the thunk's return type is a plain `RouteDefinition[]` — degrade to
457
+ * untyped, definitionally.
458
+ */
459
+
460
+ /**
461
+ * The type of a router instance's `paths` proxy for a given route tree.
462
+ * Requires the tree to be a literal tuple (`as const` or a `const` type
463
+ * param); non-literal trees fall back to an untyped proxy.
464
+ */
465
+
466
+ /** Extracts the params record a paths node binds, as runtime (string-valued) params. */
467
+
468
+ // ---------------------------------------------------------------------------
469
+ // Runtime
470
+ // ---------------------------------------------------------------------------
471
+
472
+ const encodeParam = value => String(value).split("/").map(encodeURIComponent).join("/");
473
+
474
+ /**
475
+ * Creates the runtime path proxy. It is instance-scoped: `renderPath` comes
476
+ * from the router's history adapter (eg. hash routing prefixes `#`), and
477
+ * `base` is baked into every produced path.
478
+ */
479
+ function createPathsProxy(renderPath = p => p, base = "") {
480
+ const toHref = (pathname, suffix = "") => renderPath(pathname || "/") + suffix;
481
+ function node(pathname) {
482
+ const build = (...args) => {
483
+ let path = pathname;
484
+ for (let i = 0; i < args.length; i++) {
485
+ const arg = args[i];
486
+ if (typeof arg === "object" && arg !== null) {
487
+ // a search object terminates; an optional hash string may follow
488
+ const hash = typeof args[i + 1] === "string" ? `#${args[i + 1]}` : "";
489
+ return toHref(path, mergeSearchString("", arg) + hash);
490
+ }
491
+ path += `/${encodeParam(arg)}`;
492
+ }
493
+ // zero-arg calls terminate; param-only calls stay chainable
494
+ return args.length ? node(path) : toHref(path);
495
+ };
496
+ return new Proxy(build, {
497
+ get(_, prop) {
498
+ if (prop === "toString") return () => toHref(pathname);
499
+ if (typeof prop === "symbol") return prop === Symbol.toPrimitive ? () => toHref(pathname) : undefined;
500
+ return node(`${pathname}/${prop}`);
501
+ }
502
+ });
503
+ }
504
+ return node(normalizePath(base));
505
+ }
506
+
507
+ // The flash cookie's name and one-shot clearing — split from the codec in
508
+ // flash.ts so the router core can consume the cookie eagerly (the clear must
509
+ // be appended before streaming flushes the response headers, and an unread
510
+ // outcome must not haunt a later request) without carrying the encode/decode
511
+ // machinery into client bundles that never load the action layer.
512
+
513
+ const FLASH_COOKIE = "flash";
514
+ const FLASH_MATCHER = new RegExp(`(?:^|;\\s*)${FLASH_COOKIE}=([^;]+)`);
515
+
516
+ /** Whether a Cookie header carries a flash cookie (readable or not). */
517
+ function hasFlashCookie(cookieHeader) {
518
+ return !!cookieHeader && FLASH_MATCHER.test(cookieHeader);
519
+ }
520
+
521
+ /** The raw encoded flash payload out of a Cookie header, if present. */
522
+ function matchFlashCookie(cookieHeader) {
523
+ const match = cookieHeader && cookieHeader.match(FLASH_MATCHER);
524
+ return match ? match[1] : undefined;
525
+ }
526
+
527
+ /** The Set-Cookie value clearing the flash cookie after it has been read. */
528
+ function clearFlashCookie() {
529
+ return `${FLASH_COOKIE}=; Max-Age=0; Path=/`;
530
+ }
531
+
261
532
  const MAX_REDIRECTS = 100;
262
533
 
263
534
  /** Consider this API opaque and internal. It is likely to change in the future. */
@@ -334,22 +605,6 @@ const useLocation = () => useRouter().location;
334
605
  */
335
606
  const useIsRouting = () => useRouter().isRouting;
336
607
 
337
- /**
338
- * usePreloadRoute returns a function that can be used to preload a route manual.
339
- * This is what happens automatically with link hovering and similar focus based behavior, but it is available here as an API.
340
- *
341
- * @example
342
- * ```js
343
- * const preload = usePreloadRoute();
344
- *
345
- * preload(`/users/settings`, { preloadData: true });
346
- * ```
347
- */
348
- const usePreloadRoute = () => {
349
- const pre = useRouter().preloadRoute;
350
- return (url, options = {}) => pre(url instanceof URL ? url : new URL(url, mockBase), options.preloadData);
351
- };
352
-
353
608
  /**
354
609
  * `useMatch` takes an accessor that returns the path and creates a `Memo` that returns match information if the current path matches the provided path.
355
610
  * Useful for determining if a given path matches the current route.
@@ -373,34 +628,57 @@ const useMatch = (path, matchFilters) => {
373
628
  };
374
629
 
375
630
  /**
376
- * `useCurrentMatches` returns all the matches for the current matched route.
377
- * Useful for getting all the route information.
378
- *
631
+ * `useRouteMatches` returns an accessor of the router's resolved matches for
632
+ * the current location — the chain of route definitions producing the current
633
+ * render, outermost first. Useful for reading `info` metadata off the matched
634
+ * chain. Unlike `useMatch`, which tests a path pattern you supply against the
635
+ * location, this reflects the route tree itself.
636
+ *
379
637
  * @example
380
638
  * ```js
381
- * const matches = useCurrentMatches();
382
- *
383
- * const breadcrumbs = createMemo(() => matches().map(m => m.route.info.breadcrumb))
639
+ * const matches = useRouteMatches();
640
+ *
641
+ * const breadcrumbs = createMemo(() => matches().map(m => m.route.info.breadcrumb));
384
642
  * ```
385
643
  */
386
- const useCurrentMatches = () => {
644
+ const useRouteMatches = () => {
387
645
  const router = useRouter();
388
646
  // return a copy so user mutations (eg. `.reverse()`) can't corrupt router state
389
647
  return () => router.matches().slice();
390
648
  };
391
649
 
392
650
  /**
393
- * Retrieves a reactive, store-like object containing the current route path parameters as defined in the Route.
394
- *
651
+ * `usePreloadRoute` returns a function for warming a route by hand — the same
652
+ * work link hover/focus intent triggers automatically: the matched routes'
653
+ * lazy components load, and with `preloadData` their `preload` functions run.
654
+ *
395
655
  * @example
396
656
  * ```js
397
- * const params = useParams();
398
- *
399
- * // fetch user based on the id path parameter
400
- * const getUser = query(() => fetchUser(params.id), "user");
657
+ * const preload = usePreloadRoute();
658
+ *
659
+ * preload(paths.users(2).settings, { preloadData: true });
660
+ * ```
661
+ */
662
+ const usePreloadRoute = () => {
663
+ const pre = useRouter().preloadRoute;
664
+ return (url, options = {}) => pre(url instanceof URL ? url : new URL(String(url), mockBase), options.preloadData);
665
+ };
666
+
667
+ /**
668
+ * Retrieves a reactive, store-like object containing the current route path parameters as defined in the Route.
669
+ *
670
+ * @example
671
+ * ```js
672
+ * const params = useParams();
673
+ *
674
+ * // fetch user based on the id path parameter
675
+ * const getUser = query(() => fetchUser(params.id), "user");
401
676
  * ```
402
677
  */
403
- const useParams = () => useRoute().params;
678
+
679
+ function useParams(_path) {
680
+ return useRoute().params;
681
+ }
404
682
 
405
683
  /**
406
684
  * Retrieves a tuple containing a reactive object to read the current location's query parameters and a method to update them.
@@ -429,7 +707,8 @@ const useParams = () => useRoute().params;
429
707
  * );
430
708
  * ```
431
709
  */
432
- const useSearchParams = () => {
710
+
711
+ function useSearchParams(path) {
433
712
  const router = useRouter();
434
713
  const location = router.location;
435
714
  const navigate = useNavigate();
@@ -449,43 +728,73 @@ const useSearchParams = () => {
449
728
  ...options
450
729
  });
451
730
  };
452
- return [location.query, setSearchParams];
453
- };
454
-
731
+ // Passing a paths node opts into schema parsing. The node itself is a
732
+ // type-level reference; the schemas that run come from the currently
733
+ // matched routes (root→leaf), whose outputs merge over the raw query.
734
+ // A schema that reports issues is skipped, leaving raw values — search
735
+ // strings are user input, so defaults belong in the schema itself.
736
+ const query = path ? createMemoObject(createMemo(() => {
737
+ const raw = {
738
+ ...location.query
739
+ };
740
+ let result;
741
+ for (const match of router.matches()) {
742
+ const schema = match.route.key.search;
743
+ if (!schema) continue;
744
+ const outcome = schema["~standard"].validate(raw);
745
+ if (outcome instanceof Promise) throw new Error("Async Standard Schema validation is not supported for search params");
746
+ if (!outcome.issues) result = Object.assign(result || {
747
+ ...raw
748
+ }, outcome.value);
749
+ }
750
+ return result || raw;
751
+ })) : location.query;
752
+ return [query, setSearchParams];
753
+ }
455
754
  /**
456
- * useBeforeLeave takes a function that will be called prior to leaving a route.
457
- * The function will be called with:
458
- *
459
- * - from (*Location*): current location (before change).
460
- * - to (*string | number*): path passed to `navigate`.
461
- * - options (*NavigateOptions*): options passed to navigate.
462
- * - preventDefault (*function*): call to block the route change.
463
- * - defaultPrevented (*readonly boolean*): `true` if any previously called leave handlers called `preventDefault`.
464
- * - 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).
465
- *
755
+ * Reactive link state for custom link components — the programmatic
756
+ * counterpart of the attribute vocabulary plain anchors receive
757
+ * (`aria-current`, `data-active`, `data-pending`).
758
+ *
466
759
  * @example
467
- * ```js
468
- * useBeforeLeave((e: BeforeLeaveEventArgs) => {
469
- * if (form.isDirty && !e.defaultPrevented) {
470
- * // preventDefault to block immediately and prompt user async
471
- * e.preventDefault();
472
- * setTimeout(() => {
473
- * if (window.confirm("Discard unsaved changes - are you sure?")) {
474
- * // user wants to proceed anyway so retry with force=true
475
- * e.retry(true);
476
- * }
477
- * }, 100);
478
- * }
479
- * });
760
+ * ```tsx
761
+ * function TabLink(props: { href: string; children: JSX.Element }) {
762
+ * const link = useLinkState(() => props.href);
763
+ * return (
764
+ * <a href={props.href} class="tab" data-selected={link.active() || undefined}>
765
+ * {props.children}
766
+ * </a>
767
+ * );
768
+ * }
480
769
  * ```
481
770
  */
482
- const useBeforeLeave = listener => {
483
- const s = useRouter().beforeLeave.subscribe({
484
- listener,
485
- location: useLocation(),
486
- navigate: useNavigate()
771
+ const useLinkState = (href, options = {}) => {
772
+ const router = useRouter();
773
+ const location = router.location;
774
+ const to = useResolvedPath(() => String(href()));
775
+ // trailing slashes are ignored so `/route` and `/route/` share state
776
+ const path = createMemo(() => {
777
+ const to_ = to();
778
+ return to_ === undefined ? undefined : comparablePath(to_);
487
779
  });
488
- onCleanup(s);
780
+ const matches = loc => {
781
+ const path_ = path();
782
+ if (path_ === undefined) return [false, false];
783
+ const exact = loc === path_;
784
+ return [exact || !options.end && loc.startsWith(path_ + "/"), exact];
785
+ };
786
+ const state = createMemo(() => matches(decodeURI(comparablePath(location.pathname))));
787
+ return {
788
+ active: () => state()[0],
789
+ current: () => state()[1],
790
+ // match the in-flight target explicitly (rather than active-while-routing)
791
+ // so the answer is the same from pure reads and from effects, which
792
+ // observe the committed location during a transition
793
+ pending: createMemo(() => {
794
+ state(); // location dependency: mid-flight target swaps recompute
795
+ return router.isRouting() && !!router.pendingTarget && matches(decodeURI(comparablePath(router.pendingTarget.value)))[0];
796
+ })
797
+ };
489
798
  };
490
799
 
491
800
  // Encodes a static path segment like `encodeURIComponent`, but leaves RFC 3986
@@ -493,6 +802,82 @@ const useBeforeLeave = listener => {
493
802
  // report them in `location.pathname`. Non-ASCII characters (eg. CJK paths) are
494
803
  // still percent-encoded exactly as before, since browsers encode those too.
495
804
  const encodeSegment = s => encodeURIComponent(s).replace(/%(2B|40|3A|24|26|2C|3B|3D)/g, m => decodeURIComponent(m));
805
+
806
+ // ---------------------------------------------------------------------------
807
+ // Lazy route subtrees
808
+ // ---------------------------------------------------------------------------
809
+ //
810
+ // A `children` thunk (`() => import("./feature/routes")`) is a *boundary*:
811
+ // until it resolves, the compiled tree carries a param-less catch-all
812
+ // placeholder branch under the boundary's pattern (splat-scored, so static
813
+ // siblings still win). Resolution is append-only and cached per thunk, then a
814
+ // module-level version signal bumps and every `branches()` consumer
815
+ // recompiles — matches, params, and route states all react. The placeholder's
816
+ // component reads a memo of the resolution promise, which keeps the enclosing
817
+ // navigation transition pending exactly like a `lazy()` route component; its
818
+ // `preload` *is* the resolver, so hover-intent preloading kicks the table
819
+ // load through the existing component-preload path.
820
+
821
+ const lazyBoundaries = new WeakMap();
822
+ // Module scope: boundary resolution is global, deterministic state (same
823
+ // thunk -> same routes), shared by every factory instance and the server's
824
+ // flight collector.
825
+ const [lazyTreeVersion, setLazyTreeVersion] = createSignal(0);
826
+
827
+ /** Reactive read of the lazy-subtree version — recompile compiled branches when it changes. */
828
+ function trackLazySubtrees() {
829
+ return lazyTreeVersion();
830
+ }
831
+ function getLazyBoundary(thunk) {
832
+ let record = lazyBoundaries.get(thunk);
833
+ if (!record) lazyBoundaries.set(thunk, record = {
834
+ thunk
835
+ });
836
+ return record;
837
+ }
838
+
839
+ /**
840
+ * Kicks (or joins) a boundary's resolution. Returns the resolved routes
841
+ * synchronously once available, the in-flight promise otherwise. Commit is
842
+ * always async — even for thunks returning arrays — so the version bump
843
+ * never writes a signal from inside a render computation.
844
+ */
845
+ function resolveLazySubtree(record) {
846
+ if (record.resolved) return record.resolved;
847
+ return record.promise ||= Promise.resolve(record.thunk()).then(m => {
848
+ const routes = Array.isArray(m) ? m : m.default || m.routes || [];
849
+ record.resolved = routes;
850
+ setLazyTreeVersion(v => v + 1);
851
+ return record.resolved;
852
+ });
853
+ }
854
+
855
+ /**
856
+ * The unresolved boundaries in a match chain. Rendering gates on these (the
857
+ * route-states memo suspends until they land — see routers/components.tsx)
858
+ * and the server's flight collector awaits them before its preload pass.
859
+ */
860
+ function unresolvedLazyMatches(matches) {
861
+ const pending = [];
862
+ for (const match of matches) if (match.route.lazy && !match.route.lazy.resolved) pending.push(match.route.lazy);
863
+ return pending;
864
+ }
865
+ function createLazyPlaceholder(pattern, record) {
866
+ // The placeholder never renders and needs no component — `matches` parks
867
+ // on unresolved boundaries before route contexts are created (kicking the
868
+ // resolver as it does), preloadRoute kicks it directly, and the version
869
+ // bump swaps in the real routes. `path + "/*"` with no splat name matches
870
+ // the boundary itself and everything beneath it without recording a param
871
+ // (createMatcher skips empty splat names).
872
+ const placeholderPattern = pattern + "/*";
873
+ return {
874
+ key: record,
875
+ originalPath: "*",
876
+ pattern: placeholderPattern,
877
+ matcher: createMatcher(placeholderPattern),
878
+ lazy: record
879
+ };
880
+ }
496
881
  function createRoutes(routeDef, base = "") {
497
882
  const {
498
883
  component,
@@ -557,9 +942,23 @@ function createBranches(routeDef, base = "", stack = [], branches = []) {
557
942
  const routes = createRoutes(def, base);
558
943
  for (const route of routes) {
559
944
  stack.push(route);
560
- const isEmptyArray = Array.isArray(def.children) && def.children.length === 0;
561
- if (def.children && !isEmptyArray) {
562
- createBranches(def.children, route.pattern, stack, branches);
945
+ let children = def.children;
946
+ if (typeof children === "function") {
947
+ const record = getLazyBoundary(children);
948
+ if (record.resolved) {
949
+ children = record.resolved;
950
+ } else {
951
+ // unresolved boundary: a catch-all placeholder holds its ground
952
+ stack.push(createLazyPlaceholder(route.pattern, record));
953
+ branches.push(createBranch([...stack], branches.length));
954
+ stack.pop();
955
+ stack.pop();
956
+ continue;
957
+ }
958
+ }
959
+ const isEmptyArray = Array.isArray(children) && children.length === 0;
960
+ if (children && !isEmptyArray) {
961
+ createBranches(children, route.pattern, stack, branches);
563
962
  } else {
564
963
  const branch = createBranch([...stack], branches.length);
565
964
  branches.push(branch);
@@ -627,6 +1026,49 @@ function createLocation(path, state, queryWrapper) {
627
1026
  query: queryWrapper ? queryWrapper(queryFn) : createMemoObject(queryFn)
628
1027
  };
629
1028
  }
1029
+
1030
+ /**
1031
+ * Rendezvous between the router and the data layer's single-flight consumer.
1032
+ * The Router registers itself at mount (unless `singleFlight={false}`); the
1033
+ * action side provides the consumer factory when the first action is created
1034
+ * (see data/action.ts). Whichever side arrives first waits for the other, so
1035
+ * an action module loaded lazily (a code-split route) still attaches to the
1036
+ * already-mounted router — and a router-only app, where no action ever
1037
+ * loads, never subscribes to the transport, so the server is never asked to
1038
+ * collect.
1039
+ */
1040
+ let flightConsumerFactory;
1041
+ const flightRouters = new Map();
1042
+ function registerFlightRouter(router) {
1043
+ flightRouters.set(router, flightConsumerFactory && flightConsumerFactory(router));
1044
+ return () => {
1045
+ const unsubscribe = flightRouters.get(router);
1046
+ flightRouters.delete(router);
1047
+ unsubscribe && unsubscribe();
1048
+ };
1049
+ }
1050
+ function provideFlightConsumer(factory) {
1051
+ if (flightConsumerFactory) return;
1052
+ flightConsumerFactory = factory;
1053
+ for (const [router, unsubscribe] of flightRouters) {
1054
+ if (!unsubscribe) flightRouters.set(router, factory(router));
1055
+ }
1056
+ }
1057
+
1058
+ /**
1059
+ * The flash-cookie codec, provided by the action side (data/action.ts) so
1060
+ * the router core never carries it: the core consumes the cookie eagerly
1061
+ * per request (detection + one-shot clear via the tiny flashCookie.ts half)
1062
+ * but defers decoding to this slot, read when the submissions signal
1063
+ * initializes. Actions are created at module scope, so on the server the
1064
+ * decoder is always installed before useSubmission can read — and a
1065
+ * router-only app, where it never installs, has no actions that could have
1066
+ * produced a flash cookie in the first place.
1067
+ */
1068
+ let flashDecoder;
1069
+ function provideFlashDecoder(decoder) {
1070
+ flashDecoder || (flashDecoder = decoder);
1071
+ }
630
1072
  let intent;
631
1073
  function getIntent() {
632
1074
  return intent;
@@ -645,7 +1087,8 @@ function createRouterContext(integration, branches, getContext, options = {}) {
645
1087
  } = integration;
646
1088
  const parsePath = utils.parsePath || (p => p);
647
1089
  const renderPath = utils.renderPath || (p => p);
648
- const beforeLeave = utils.beforeLeave || createBeforeLeave();
1090
+ // An empty slot until `useBeforeLeave` installs the guard on first use.
1091
+ const beforeLeave = utils.beforeLeave || {};
649
1092
  const basePath = resolvePath("", options.base || "");
650
1093
  const initialSource = untrack(source);
651
1094
  if (basePath === undefined) {
@@ -657,7 +1100,7 @@ function createRouterContext(integration, branches, getContext, options = {}) {
657
1100
  scroll: false
658
1101
  });
659
1102
  }
660
- const [isRouting, setIsRouting] = createSignal(false, {
1103
+ const [isNavigating, setIsRouting] = createSignal(false, {
661
1104
  ownedWrite: true
662
1105
  });
663
1106
 
@@ -674,15 +1117,47 @@ function createRouterContext(integration, branches, getContext, options = {}) {
674
1117
  const effective = createMemo(() => navigateTarget() ?? source());
675
1118
  const location = createLocation(() => effective().value, () => effective().state, utils.queryWrapper);
676
1119
  const referrers = [];
677
- const submissions = createSignal(isServer ? initFromFlash() : [], {
678
- ownedWrite: true
679
- });
680
- const matches = createMemo(() => {
681
- if (typeof options.transformUrl === "function") {
682
- return getRouteMatches(branches(), options.transformUrl(location.pathname));
1120
+ // The flash cookie is consumed eagerly: its one-shot clear (Set-Cookie)
1121
+ // must be appended before streaming flushes the response headers, and an
1122
+ // unread outcome must not haunt a later request's render. Only detection
1123
+ // and clearing happen here (the tiny flashCookie.ts half); the raw header
1124
+ // is stashed and decoding waits for the action-provided codec, read when
1125
+ // the lazily allocated submissions signal below first initializes.
1126
+ let flashCookieHeader;
1127
+ if (isServer) {
1128
+ const e = getRequestEvent();
1129
+ if (e && !(e.router && e.router.submission)) {
1130
+ const cookieHeader = e.request.headers.get("cookie");
1131
+ if (hasFlashCookie(cookieHeader)) {
1132
+ flashCookieHeader = cookieHeader;
1133
+ // one-shot: clear it even when unreadable so it can't haunt later renders
1134
+ if (e.response && e.response.headers) e.response.headers.append("Set-Cookie", clearFlashCookie());
1135
+ }
683
1136
  }
684
- return getRouteMatches(branches(), location.pathname);
1137
+ }
1138
+ let submissions;
1139
+ const matches = createMemo(() => {
1140
+ const pathname = typeof options.transformUrl === "function" ? options.transformUrl(location.pathname) : location.pathname;
1141
+ const m = getRouteMatches(branches(), pathname);
1142
+ // An unresolved lazy subtree parks readers on not-ready semantics — the
1143
+ // navigation transition (or the SSR stream) holds until the table lands.
1144
+ // NotReadyError (not a returned promise) because a match chain is full
1145
+ // of component functions the hydration serializer must never see. The
1146
+ // recompute comes from the version-signal dependency on the client and
1147
+ // from the carried promise's retry on the server; a boundary nested
1148
+ // inside a boundary just parks the recomputed chain again.
1149
+ const pending = unresolvedLazyMatches(m);
1150
+ if (pending.length) throw new NotReadyError(Promise.all(pending.map(resolveLazySubtree)));
1151
+ return m;
685
1152
  });
1153
+
1154
+ // Every write is a transition in Solid 2, so a native history pop forks the
1155
+ // source signal exactly like programmatic navigation does. isRouting is
1156
+ // therefore derived: the manual flag covers navigateFromRoute's explicit
1157
+ // window, and isPending over the location/matches read reports any
1158
+ // in-flight fork — including popstate traversals and the lazy-subtree
1159
+ // resolution matches() parks on.
1160
+ const isRouting = createMemo(() => isNavigating() || isPending(() => (matches(), location.search, location.hash)));
686
1161
  const buildParams = () => mergeParams(matches());
687
1162
  const wrapParams = utils.paramsWrapper ? getParams => utils.paramsWrapper(getParams, branches) : getParams => createMemoObject(getParams);
688
1163
  const params = wrapParams(buildParams);
@@ -711,7 +1186,11 @@ function createRouterContext(integration, branches, getContext, options = {}) {
711
1186
  beforeLeave,
712
1187
  preloadRoute,
713
1188
  singleFlight: options.singleFlight === undefined ? true : options.singleFlight,
714
- submissions
1189
+ get submissions() {
1190
+ return submissions ||= createSignal(isServer ? initSubmissions() : [], {
1191
+ ownedWrite: true
1192
+ });
1193
+ }
715
1194
  };
716
1195
  function navigateFromRoute(route, to, options) {
717
1196
  // Untrack in case someone navigates in an effect - don't want to track `reference` or route paths
@@ -724,6 +1203,8 @@ function createRouterContext(integration, branches, getContext, options = {}) {
724
1203
  }
725
1204
  return;
726
1205
  }
1206
+ // typed path proxy nodes coerce to their href
1207
+ if (typeof to !== "string") to = to.toString();
727
1208
  const queryOnly = !to || to[0] === "?";
728
1209
  const {
729
1210
  replace,
@@ -758,7 +1239,7 @@ function createRouterContext(integration, branches, getContext, options = {}) {
758
1239
  scroll,
759
1240
  state: nextState
760
1241
  });
761
- } else if (beforeLeave.confirm(resolvedTo, options)) {
1242
+ } else if (!beforeLeave.current || beforeLeave.current.confirm(resolvedTo, options)) {
762
1243
  referrers.push({
763
1244
  value: current.value,
764
1245
  replace,
@@ -769,12 +1250,15 @@ function createRouterContext(integration, branches, getContext, options = {}) {
769
1250
  value: resolvedTo,
770
1251
  state: nextState
771
1252
  };
772
- if (lastTransitionTarget === undefined) {
1253
+ const firstNavigation = lastTransitionTarget === undefined;
1254
+ intent = "navigate";
1255
+ // assign the target before flushing so effects that run for the
1256
+ // isRouting flip (e.g. pending link state) can read it
1257
+ lastTransitionTarget = newTarget;
1258
+ if (firstNavigation) {
773
1259
  setIsRouting(true);
774
1260
  flush();
775
1261
  }
776
- intent = "navigate";
777
- lastTransitionTarget = newTarget;
778
1262
  if (lastTransitionTarget === newTarget) {
779
1263
  setNavigateTarget({
780
1264
  ...lastTransitionTarget
@@ -810,6 +1294,11 @@ function createRouterContext(integration, branches, getContext, options = {}) {
810
1294
  }
811
1295
  function preloadRoute(url, preloadData) {
812
1296
  const matches = getRouteMatches(branches(), url.pathname);
1297
+ // An unresolved lazy subtree in the chain: the placeholder's
1298
+ // component.preload (below) kicks the table load; once it lands,
1299
+ // preload again so the real inner routes warm too.
1300
+ const boundary = matches.find(m => m.route.lazy && !m.route.lazy.resolved);
1301
+ boundary && resolveLazySubtree(boundary.route.lazy).then(() => preloadRoute(url, preloadData));
813
1302
  const prevIntent = intent;
814
1303
  intent = "preload";
815
1304
  for (let match in matches) {
@@ -838,11 +1327,19 @@ function createRouterContext(integration, branches, getContext, options = {}) {
838
1327
  }
839
1328
  intent = prevIntent;
840
1329
  }
841
- function initFromFlash() {
1330
+
1331
+ // Seeds the initial submission from a no-JS form post: the server
1332
+ // function handler redirected back with the outcome in a one-shot flash
1333
+ // cookie (see src/server.ts's handleNoJS), consumed eagerly above and
1334
+ // decoded here — so the post-redirect SSR renders useSubmission() state
1335
+ // exactly as a scripted submission would. An explicitly pre-seeded
1336
+ // `event.router.submission` (framework integrations) takes precedence.
1337
+ function initSubmissions() {
842
1338
  const e = getRequestEvent();
843
- if (!(e && e.router && e.router.submission)) return [];
1339
+ const submission = e && e.router && e.router.submission || (flashDecoder && flashCookieHeader !== undefined ? flashDecoder(flashCookieHeader) : undefined);
1340
+ if (!submission) return [];
844
1341
  return [{
845
- ...e.router.submission,
1342
+ ...submission,
846
1343
  clear() {},
847
1344
  retry() {}
848
1345
  }];
@@ -892,61 +1389,20 @@ function createRouteContext(router, parent, outlet, match, matches = () => [matc
892
1389
  return route;
893
1390
  }
894
1391
 
895
- const createRouterComponent = router => function IntegratedRouter(props) {
896
- const {
897
- base,
898
- singleFlight,
899
- transformUrl,
900
- root,
901
- rootPreload,
902
- routeChildren
903
- } = untrack(() => ({
904
- base: props.base,
905
- singleFlight: props.singleFlight,
906
- transformUrl: props.transformUrl,
907
- root: props.root,
908
- rootPreload: props.rootPreload,
909
- routeChildren: props.children
910
- }));
911
- const routeDefs = children(() => routeChildren);
912
- const branches = createMemo(() => createBranches(routeDefs(), base || ""));
913
- let context;
914
- const routerState = createRouterContext(router, branches, () => context, {
915
- base,
916
- singleFlight,
917
- transformUrl
918
- });
919
- router.create && router.create(routerState);
920
- return createComponent$1(RouterContextObj, {
921
- value: routerState,
922
- get children() {
923
- return createComponent$1(Root, {
924
- routerState: routerState,
925
- root: root,
926
- preload: rootPreload,
927
- get children() {
928
- return [memo(() => (context = getOwner()) && null), createComponent$1(Routes, {
929
- routerState: routerState,
930
- get branches() {
931
- return branches();
932
- }
933
- })];
934
- }
935
- });
936
- }
937
- });
938
- };
939
1392
  function Root(props) {
940
1393
  const location = props.routerState.location;
941
1394
  const params = props.routerState.params;
942
1395
  const data = createMemo(() => props.preload && untrack(() => {
943
1396
  setInPreloadFn(true);
944
- props.preload({
945
- params,
946
- location,
947
- intent: getIntent() || "initial"
948
- });
949
- setInPreloadFn(false);
1397
+ try {
1398
+ return props.preload({
1399
+ params,
1400
+ location,
1401
+ intent: getIntent() || "initial"
1402
+ });
1403
+ } finally {
1404
+ setInPreloadFn(false);
1405
+ }
950
1406
  }));
951
1407
  const RootComp = props.root;
952
1408
  if (RootComp) {
@@ -967,20 +1423,29 @@ function Routes(props) {
967
1423
  if (isServer) {
968
1424
  const e = getRequestEvent();
969
1425
  if (e && e.router && e.router.dataOnly) {
970
- dataOnly(e, props.routerState, props.branches);
1426
+ dataOnly(e, props.routerState, props.branches());
971
1427
  return;
972
1428
  }
973
- e && ((e.router || (e.router = {})).matches || (e.router.matches = props.routerState.matches().map(({
974
- route,
975
- path,
976
- params
977
- }) => ({
978
- path: route.originalPath,
979
- pattern: route.pattern,
980
- match: path,
981
- params,
982
- info: route.info
983
- }))));
1429
+ if (e && !(e.router && e.router.matches)) {
1430
+ // A lazy getter rather than a snapshot: unresolved lazy subtrees mean
1431
+ // the match chain can still improve while the render streams, and
1432
+ // frameworks read this after the render settles.
1433
+ Object.defineProperty(e.router || (e.router = {}), "matches", {
1434
+ configurable: true,
1435
+ enumerable: true,
1436
+ get: () => props.routerState.matches().map(({
1437
+ route,
1438
+ path,
1439
+ params
1440
+ }) => ({
1441
+ path: route.originalPath,
1442
+ pattern: route.pattern,
1443
+ match: path,
1444
+ params,
1445
+ info: route.info
1446
+ }))
1447
+ });
1448
+ }
984
1449
  }
985
1450
  const disposers = [];
986
1451
  let root;
@@ -993,6 +1458,9 @@ function Routes(props) {
993
1458
  // computation (which disposes its children every time it re-runs).
994
1459
  const owner = getOwner();
995
1460
  const routeStates = createMemo(prev => {
1461
+ // While a lazy subtree resolves, `matches()` is not ready and this
1462
+ // computation parks with it — no route contexts are created against
1463
+ // placeholder matches.
996
1464
  const nextMatches = props.routerState.matches();
997
1465
  const previousMatches = prevMatches;
998
1466
  let equal = previousMatches && nextMatches.length === previousMatches.length;
@@ -1048,20 +1516,16 @@ const createOutlet = child => {
1048
1516
  return undefined;
1049
1517
  };
1050
1518
  };
1051
- const Route = props => {
1052
- const childRoutes = children(() => props.children);
1053
- return merge(props, {
1054
- get children() {
1055
- return childRoutes();
1056
- }
1057
- });
1058
- };
1059
1519
 
1060
1520
  // for data only mode with single flight mutations
1061
1521
  function dataOnly(event, routerState, branches) {
1062
1522
  const url = new URL(event.request.url);
1063
1523
  const prevMatches = getRouteMatches(branches, new URL(event.router.previousUrl || event.request.url).pathname);
1064
1524
  const matches = getRouteMatches(branches, url.pathname);
1525
+ // This pass is synchronous — an unresolved lazy subtree can only be
1526
+ // kicked, not awaited (the flight collector's own runner awaits; see
1527
+ // src/server.ts). Best effort so a subsequent pass sees the table.
1528
+ unresolvedLazyMatches([...prevMatches, ...matches]).forEach(resolveLazySubtree);
1065
1529
  for (let match = 0; match < matches.length; match++) {
1066
1530
  if (!prevMatches[match] || matches[match].route !== prevMatches[match].route) event.router.dataOnly = true;
1067
1531
  const {
@@ -1076,35 +1540,50 @@ function dataOnly(event, routerState, branches) {
1076
1540
  }
1077
1541
  }
1078
1542
 
1079
- function createRouter(config) {
1080
- let ignore = false;
1081
- const wrap = value => typeof value === "string" ? {
1082
- value
1083
- } : value;
1084
- const [read, write] = createSignal(wrap(config.get()), {
1085
- equals: (a, b) => a.value === b.value && a.state === b.state,
1086
- ownedWrite: true
1087
- });
1088
- const signal = [read, next => {
1089
- !ignore && config.set(next);
1090
- if (sharedConfig.registry && !sharedConfig.done) sharedConfig.done = true;
1091
- write(next);
1092
- }];
1093
- config.init && onCleanup(config.init((value = config.get()) => {
1094
- ignore = true;
1095
- signal[1](wrap(value));
1096
- ignore = false;
1097
- }));
1098
- return createRouterComponent({
1099
- signal,
1100
- create: config.create,
1101
- utils: config.utils
1102
- });
1103
- }
1104
1543
  function bindEvent(target, type, handler) {
1105
1544
  target.addEventListener(type, handler);
1106
1545
  return () => target.removeEventListener(type, handler);
1107
1546
  }
1547
+
1548
+ // Depth stamping supports blocking browser-initiated navigation (back/forward)
1549
+ // for `useBeforeLeave`. It stays always-on — a couple of history.state writes —
1550
+ // so blocking stays exact no matter when the first guard subscribes, while the
1551
+ // guard machinery itself lives behind the lazy `beforeLeave` slot.
1552
+
1553
+ let depth;
1554
+ function saveCurrentDepth() {
1555
+ if (!window.history.state || window.history.state._depth == null) {
1556
+ window.history.replaceState({
1557
+ ...window.history.state,
1558
+ _depth: window.history.length - 1
1559
+ }, "");
1560
+ }
1561
+ depth = window.history.state._depth;
1562
+ }
1563
+ function keepDepth(state) {
1564
+ return {
1565
+ ...state,
1566
+ _depth: window.history.state && window.history.state._depth
1567
+ };
1568
+ }
1569
+ function notifyIfNotBlocked(notify, block) {
1570
+ let ignore = false;
1571
+ return () => {
1572
+ const prevDepth = depth;
1573
+ saveCurrentDepth();
1574
+ const delta = prevDepth == null ? null : depth - prevDepth;
1575
+ if (ignore) {
1576
+ ignore = false;
1577
+ return;
1578
+ }
1579
+ if (delta && block(delta)) {
1580
+ ignore = true;
1581
+ window.history.go(-delta);
1582
+ } else {
1583
+ notify();
1584
+ }
1585
+ };
1586
+ }
1108
1587
  function scrollToHash(hash, fallbackTop) {
1109
1588
  const el = hash && document.getElementById(hash);
1110
1589
  if (el) {
@@ -1114,46 +1593,583 @@ function scrollToHash(hash, fallbackTop) {
1114
1593
  }
1115
1594
  }
1116
1595
 
1117
- function getPath(url) {
1118
- const u = new URL(url);
1119
- return u.pathname + u.search;
1120
- }
1121
- function StaticRouter(props) {
1122
- let e;
1123
- const obj = {
1124
- value: props.url || (e = getRequestEvent()) && getPath(e.request.url) || ""
1125
- };
1126
- return createRouterComponent({
1127
- signal: [() => obj, next => Object.assign(obj, next)]
1128
- })(props);
1129
- }
1130
-
1131
- const LocationHeader = "Location";
1132
- const PRELOAD_TIMEOUT = 5000;
1133
- const CACHE_TIMEOUT = 180000;
1134
- let cacheMap = new Map();
1596
+ /**
1597
+ * A history adapter: the source of truth for the current URL and how
1598
+ * navigations write back to it. Adapters are plain imported values so
1599
+ * unused ones never enter the bundle — `createRouter` defaults to browser
1600
+ * history on the client and the request URL on the server.
1601
+ */
1135
1602
 
1136
- // cleanup forward/back cache
1137
- if (!isServer) {
1138
- setInterval(() => {
1139
- const now = Date.now();
1140
- for (let [k, v] of cacheMap.entries()) {
1141
- if (!v[4].count && now - v[0] > CACHE_TIMEOUT) {
1142
- cacheMap.delete(k);
1603
+ function browserHistory() {
1604
+ const getSource = () => {
1605
+ const url = window.location.pathname + window.location.search;
1606
+ const state = window.history.state && window.history.state._depth && Object.keys(window.history.state).length === 1 ? undefined : window.history.state;
1607
+ return {
1608
+ value: url + window.location.hash,
1609
+ state
1610
+ };
1611
+ };
1612
+ const beforeLeave = {};
1613
+ if (!isServer) saveCurrentDepth();
1614
+ return {
1615
+ get: getSource,
1616
+ set({
1617
+ value,
1618
+ replace,
1619
+ scroll,
1620
+ state
1621
+ }) {
1622
+ if (replace) {
1623
+ window.history.replaceState(keepDepth(state), "", value);
1624
+ } else {
1625
+ window.history.pushState(state, "", value);
1626
+ }
1627
+ scrollToHash(decodeURIComponent(window.location.hash.slice(1)), scroll);
1628
+ saveCurrentDepth();
1629
+ },
1630
+ init: notify => bindEvent(window, "popstate", notifyIfNotBlocked(notify, delta => {
1631
+ const guard = beforeLeave.current;
1632
+ if (!guard) return false;
1633
+ if (delta) {
1634
+ return !guard.confirm(delta);
1635
+ } else {
1636
+ const s = getSource();
1637
+ return !guard.confirm(s.value, {
1638
+ state: s.state
1639
+ });
1143
1640
  }
1641
+ })),
1642
+ utils: {
1643
+ go: delta => window.history.go(delta),
1644
+ beforeLeave
1144
1645
  }
1145
- }, 300000);
1146
- }
1147
- function getCache() {
1148
- if (!isServer) return cacheMap;
1149
- const req = getRequestEvent();
1150
- if (!req) throw new Error("Cannot find cache context");
1151
- return (req.router || (req.router = {})).cache || (req.router.cache = new Map());
1646
+ };
1152
1647
  }
1153
-
1154
- /**
1155
- * Revalidates the given cache entry/entries.
1156
- */
1648
+ function hashParser(str) {
1649
+ const to = str.replace(/^.*?#/, "");
1650
+ // Hash-only hrefs like `#foo` from plain anchors will come in as `/#foo` whereas a link to
1651
+ // `/foo` will be `/#/foo`. Check if the to starts with a `/` and if not append it as a hash
1652
+ // to the current path so we can handle these in-page anchors correctly.
1653
+ if (!to.startsWith("/")) {
1654
+ const [, path = "/"] = window.location.hash.split("#", 2);
1655
+ return `${path}#${to}`;
1656
+ }
1657
+ return to;
1658
+ }
1659
+ function hashHistory() {
1660
+ const getSource = () => window.location.hash.slice(1);
1661
+ const beforeLeave = {};
1662
+ if (!isServer) saveCurrentDepth();
1663
+ return {
1664
+ get: getSource,
1665
+ set({
1666
+ value,
1667
+ replace,
1668
+ scroll,
1669
+ state
1670
+ }) {
1671
+ if (replace) {
1672
+ window.history.replaceState(keepDepth(state), "", "#" + value);
1673
+ } else {
1674
+ window.history.pushState(state, "", "#" + value);
1675
+ }
1676
+ const hashIndex = value.indexOf("#");
1677
+ const hash = hashIndex >= 0 ? value.slice(hashIndex + 1) : "";
1678
+ scrollToHash(hash, scroll);
1679
+ saveCurrentDepth();
1680
+ },
1681
+ init: notify => bindEvent(window, "hashchange", notifyIfNotBlocked(notify, delta => {
1682
+ const guard = beforeLeave.current;
1683
+ return !!guard && !guard.confirm(delta && delta < 0 ? delta : getSource());
1684
+ })),
1685
+ utils: {
1686
+ go: delta => window.history.go(delta),
1687
+ renderPath: path => `#${path}`,
1688
+ parsePath: hashParser,
1689
+ beforeLeave
1690
+ }
1691
+ };
1692
+ }
1693
+ function memoryHistory(initial = "/") {
1694
+ const entries = [initial];
1695
+ let index = 0;
1696
+ const listeners = [];
1697
+ const go = n => {
1698
+ // https://github.com/remix-run/react-router/blob/682810ca929d0e3c64a76f8d6e465196b7a2ac58/packages/router/history.ts#L245
1699
+ index = Math.max(0, Math.min(index + n, entries.length - 1));
1700
+ const value = entries[index];
1701
+ listeners.forEach(listener => listener(value));
1702
+ };
1703
+ const listen = listener => {
1704
+ listeners.push(listener);
1705
+ return () => {
1706
+ const i = listeners.indexOf(listener);
1707
+ listeners.splice(i, 1);
1708
+ };
1709
+ };
1710
+ return {
1711
+ get: () => entries[index],
1712
+ set: ({
1713
+ value,
1714
+ scroll,
1715
+ replace
1716
+ }) => {
1717
+ if (replace) {
1718
+ entries[index] = value;
1719
+ } else {
1720
+ entries.splice(index + 1, entries.length - index, value);
1721
+ index++;
1722
+ }
1723
+ listeners.forEach(listener => listener(value));
1724
+ setTimeout(() => {
1725
+ if (scroll) {
1726
+ scrollToHash(value.split("#")[1] || "", true);
1727
+ }
1728
+ }, 0);
1729
+ },
1730
+ back: () => go(-1),
1731
+ forward: () => go(1),
1732
+ go,
1733
+ listen,
1734
+ init: listen,
1735
+ utils: {
1736
+ go
1737
+ }
1738
+ };
1739
+ }
1740
+
1741
+ const STORAGE_KEY = "solid-router:scroll";
1742
+
1743
+ /**
1744
+ * Explicit scroll restoration for back/forward navigation. The browser's
1745
+ * native same-document heuristic is unreliable for suspense-driven rendering:
1746
+ * if the destination route forces a layout while the document is still short,
1747
+ * the saved offset for the previous entry is clamped and lost (#577).
1748
+ *
1749
+ * Positions are captured continuously from the scroll event, keyed by the
1750
+ * `_depth` the router already stamps on every history entry — capturing at
1751
+ * scroll time (rather than at exit) stays correct through `useBeforeLeave`
1752
+ * blocked/reverted traversals. The map persists to sessionStorage on pagehide
1753
+ * so restoration survives reloads, which `scrollRestoration = "manual"`
1754
+ * otherwise disables. Restoration runs once routing settles; if the document
1755
+ * is still shorter than the target (a boundary below the fold hasn't
1756
+ * resolved), a ResizeObserver retries as content grows, cancelled by the
1757
+ * first user scroll.
1758
+ */
1759
+ function createScrollRestoration() {
1760
+ window.history.scrollRestoration = "manual";
1761
+ // the current entry needs its depth stamp for captures to have a key, even
1762
+ // if something replaced history.state after the adapter stamped it
1763
+ saveCurrentDepth();
1764
+ let positions = {};
1765
+ try {
1766
+ positions = JSON.parse(sessionStorage.getItem(STORAGE_KEY)) || {};
1767
+ } catch {}
1768
+ const depth = () => window.history.state && window.history.state._depth;
1769
+ let programmatic = false;
1770
+ let pending;
1771
+ let disconnect;
1772
+ const cancelGuard = () => {
1773
+ disconnect && disconnect();
1774
+ disconnect = undefined;
1775
+ };
1776
+ const unbind = [bindEvent(window, "scroll", () => {
1777
+ const d = depth();
1778
+ if (d != null) positions[d] = window.scrollY;
1779
+ if (!programmatic) {
1780
+ // the user took over — a pending or chasing restore would yank them
1781
+ pending = undefined;
1782
+ cancelGuard();
1783
+ }
1784
+ }), bindEvent(window, "pagehide", () => {
1785
+ try {
1786
+ sessionStorage.setItem(STORAGE_KEY, JSON.stringify(positions));
1787
+ } catch {}
1788
+ })];
1789
+ const restore = () => {
1790
+ if (pending == null) return;
1791
+ const y = positions[pending];
1792
+ pending = undefined;
1793
+ if (y == null) return;
1794
+ cancelGuard();
1795
+ const attempt = () => {
1796
+ programmatic = true;
1797
+ window.scrollTo(0, y);
1798
+ programmatic = false;
1799
+ // reachable once the document is tall enough to hold the offset
1800
+ return document.documentElement.scrollHeight - window.innerHeight >= y;
1801
+ };
1802
+ if (!attempt() && typeof ResizeObserver !== "undefined") {
1803
+ const observer = new ResizeObserver(() => attempt() && cancelGuard());
1804
+ observer.observe(document.documentElement);
1805
+ disconnect = () => observer.disconnect();
1806
+ }
1807
+ };
1808
+ return {
1809
+ /** When the adapter notifies a traversal: mark the target for restoration. */
1810
+ onPop() {
1811
+ pending = depth();
1812
+ },
1813
+ /** After a push: forward entries died, and this depth may be reused. */
1814
+ onPush() {
1815
+ const d = depth();
1816
+ if (d != null) for (const k in positions) +k >= d && delete positions[k];
1817
+ },
1818
+ create(router) {
1819
+ // Restore once the traversal has settled: key on the location (a fully
1820
+ // synchronous pop commits without isRouting ever flipping) and on
1821
+ // isRouting, which reports in-flight transitions — native pops
1822
+ // included — and holds the restore until they commit. restore() no-ops
1823
+ // unless a traversal marked a target, so push navigations are inert.
1824
+ createEffect(() => ({
1825
+ url: router.location.pathname + router.location.search + router.location.hash,
1826
+ routing: router.isRouting()
1827
+ }), current => {
1828
+ if (!current.routing) restore();
1829
+ });
1830
+ onCleanup(() => {
1831
+ unbind.forEach(u => u());
1832
+ cancelGuard();
1833
+ });
1834
+ // reload/back_forward document loads land on an existing entry (a fresh
1835
+ // navigation starts a new one and belongs at the top); the effect's
1836
+ // initial run performs the restore after first render
1837
+ const [nav] = performance.getEntriesByType && performance.getEntriesByType("navigation");
1838
+ if (nav && nav.type !== "navigate") pending = depth();
1839
+ }
1840
+ };
1841
+ }
1842
+ /**
1843
+ * Threads restoration through a history adapter: pushes prune dead forward
1844
+ * entries, and adapter notifications (unblocked pops) mark the traversal
1845
+ * target. Notification runs after the adapter's depth bookkeeping, so the
1846
+ * marked depth is the entry being restored to.
1847
+ */
1848
+ function withScrollRestoration(history, restoration) {
1849
+ return {
1850
+ ...history,
1851
+ set(next) {
1852
+ history.set(next);
1853
+ next.replace || restoration.onPush();
1854
+ },
1855
+ init: history.init && (notify => history.init(value => {
1856
+ restoration.onPop();
1857
+ notify(value);
1858
+ }))
1859
+ };
1860
+ }
1861
+
1862
+ /**
1863
+ * Identity helper that preserves literal types when the route tree is
1864
+ * declared as a separate variable. `createRouter` infers literally from
1865
+ * inline arrays, but an extracted `const routes = [...]` widens paths to
1866
+ * `string` and silently degrades `paths` and the typed hooks unless it is
1867
+ * declared `as const` — `defineRoutes` makes that impossible to forget.
1868
+ */
1869
+ function defineRoutes(routes) {
1870
+ return routes;
1871
+ }
1872
+ /** Wraps a history adapter in the integration signal the router core consumes. Must run under a reactive owner. */
1873
+ function createIntegration(history) {
1874
+ let ignore = false;
1875
+ const wrap = value => typeof value === "string" ? {
1876
+ value
1877
+ } : value;
1878
+ const [read, write] = createSignal(wrap(history.get()), {
1879
+ equals: (a, b) => a.value === b.value && a.state === b.state,
1880
+ ownedWrite: true
1881
+ });
1882
+ const signal = [read, next => {
1883
+ !ignore && history.set(next);
1884
+ if (sharedConfig.registry && !sharedConfig.done) sharedConfig.done = true;
1885
+ write(next);
1886
+ }];
1887
+ history.init && onCleanup(history.init((value = history.get()) => {
1888
+ ignore = true;
1889
+ signal[1](wrap(value));
1890
+ ignore = false;
1891
+ }));
1892
+ return {
1893
+ signal,
1894
+ utils: history.utils
1895
+ };
1896
+ }
1897
+
1898
+ /**
1899
+ * Server default: a static view of the request URL — no signal machinery, a
1900
+ * server render never navigates. The request event (when the harness scopes
1901
+ * one) wins; the provider's `url` prop is the fallback for renders outside a
1902
+ * request scope (SSG scripts, server-side tests, runtimes without
1903
+ * `node:async_hooks`). History adapters are a client navigation concern and
1904
+ * play no part in locating a server render.
1905
+ */
1906
+ function staticIntegration(url, utils) {
1907
+ const e = getRequestEvent();
1908
+ const source = e ? e.request.url : url;
1909
+ let value = "";
1910
+ if (source) {
1911
+ const u = new URL(source, mockBase);
1912
+ value = u.pathname + u.search;
1913
+ }
1914
+ const obj = {
1915
+ value
1916
+ };
1917
+ return {
1918
+ signal: [() => obj, next => Object.assign(obj, next)],
1919
+ utils
1920
+ };
1921
+ }
1922
+ function createRouter(config) {
1923
+ const basePath = config.base || "";
1924
+ // Routes are immutable per instance, so compilation is shared by every
1925
+ // mount, request, and `match()` call — recompiled only when a lazy subtree
1926
+ // resolves (append-only: resolution, not mutation). Reading the version
1927
+ // inside a computation subscribes it; plain calls just see current state.
1928
+ let compiled;
1929
+ let compiledVersion = -1;
1930
+ const branches = () => {
1931
+ const version = trackLazySubtrees();
1932
+ if (!compiled || compiledVersion !== version) {
1933
+ compiled = createBranches(config.routes, basePath);
1934
+ compiledVersion = version;
1935
+ }
1936
+ return compiled;
1937
+ };
1938
+ const renderPath = config.history && config.history.utils && config.history.utils.renderPath || undefined;
1939
+ function RouterComponent(props) {
1940
+ // One router per app: the session (location, history, delegation, link
1941
+ // claims, preloading) has a single owner, and a second instance would
1942
+ // fight it — stale content on click navigations, conflicting link
1943
+ // attributes. Compose route trees instead; lazy subtrees are the planned
1944
+ // answer for definitions unknown at build time.
1945
+ if (useOptionalContext(RouterContextObj)) {
1946
+ console.warn("Mounting a router inside another router is not supported. " + "Compose route trees in one createRouter config instead.");
1947
+ }
1948
+ const root = untrack(() => props.children);
1949
+ let restoration;
1950
+ let history = config.history;
1951
+ if (!isServer && (config.scrollRestoration ?? !history)) {
1952
+ restoration = createScrollRestoration();
1953
+ history = withScrollRestoration(history || browserHistory(), restoration);
1954
+ }
1955
+ const integration = isServer ? staticIntegration(props.url, config.history && config.history.utils) : createIntegration(history || browserHistory());
1956
+ let context;
1957
+ const routerState = createRouterContext(integration, branches, () => context, {
1958
+ base: basePath,
1959
+ singleFlight: config.singleFlight,
1960
+ transformUrl: config.transformUrl
1961
+ });
1962
+ if (!isServer) {
1963
+ setupNativeEvents({
1964
+ preload: config.preloadLinks,
1965
+ explicitLinks: config.explicitLinks,
1966
+ actionBase: config.actionBase,
1967
+ transformUrl: config.transformUrl
1968
+ })(routerState);
1969
+ setupLinkClaims(routerState, config.explicitLinks);
1970
+ if (routerState.singleFlight) onCleanup(registerFlightRouter(routerState));
1971
+ restoration && restoration.create(routerState);
1972
+ }
1973
+ return createComponent$1(RouterContextObj, {
1974
+ value: routerState,
1975
+ get children() {
1976
+ return createComponent$1(Root, {
1977
+ routerState: routerState,
1978
+ root: root,
1979
+ get preload() {
1980
+ return config.preload;
1981
+ },
1982
+ get children() {
1983
+ return [memo(() => (context = getOwner()) && null), createComponent$1(Routes, {
1984
+ routerState: routerState,
1985
+ branches: branches
1986
+ })];
1987
+ }
1988
+ });
1989
+ }
1990
+ });
1991
+ }
1992
+ const instance = Object.assign(RouterComponent, {
1993
+ routes: config.routes,
1994
+ config,
1995
+ match(url) {
1996
+ const u = new URL(url, mockBase);
1997
+ const pathname = config.transformUrl ? config.transformUrl(u.pathname) : u.pathname;
1998
+ return getRouteMatches(branches(), pathname).map(({
1999
+ route,
2000
+ path,
2001
+ params
2002
+ }) => ({
2003
+ path: route.originalPath,
2004
+ pattern: route.pattern,
2005
+ match: path,
2006
+ params,
2007
+ info: route.info
2008
+ }));
2009
+ }
2010
+ });
2011
+ // Built on first access (a getter via Object.assign would run during the
2012
+ // copy) so runtimes without Proxy — some older TVs — can still route as
2013
+ // long as they never touch typed paths.
2014
+ let paths;
2015
+ Object.defineProperty(instance, "paths", {
2016
+ get: () => paths || (paths = createPathsProxy(renderPath, basePath))
2017
+ });
2018
+ return instance;
2019
+ }
2020
+
2021
+ function createBeforeLeave() {
2022
+ let listeners = new Set();
2023
+ function subscribe(listener) {
2024
+ listeners.add(listener);
2025
+ return () => listeners.delete(listener);
2026
+ }
2027
+ let ignore = false;
2028
+ function confirm(to, options) {
2029
+ if (ignore) return !(ignore = false);
2030
+ const e = {
2031
+ to,
2032
+ options,
2033
+ defaultPrevented: false,
2034
+ preventDefault: () => e.defaultPrevented = true
2035
+ };
2036
+ for (const l of listeners) l.listener({
2037
+ to,
2038
+ options,
2039
+ // delegate to the shared event so later listeners' preventDefault
2040
+ // calls are observable from earlier listeners
2041
+ get defaultPrevented() {
2042
+ return e.defaultPrevented;
2043
+ },
2044
+ preventDefault: e.preventDefault,
2045
+ from: l.location,
2046
+ retry: force => {
2047
+ force && (ignore = true);
2048
+ l.navigate(to, {
2049
+ ...options,
2050
+ resolve: false
2051
+ });
2052
+ }
2053
+ });
2054
+ return !e.defaultPrevented;
2055
+ }
2056
+ return {
2057
+ subscribe,
2058
+ confirm
2059
+ };
2060
+ }
2061
+
2062
+ /**
2063
+ * useBeforeLeave takes a function that will be called prior to leaving a route.
2064
+ * The function will be called with:
2065
+ *
2066
+ * - from (*Location*): current location (before change).
2067
+ * - to (*string | number*): path passed to `navigate`.
2068
+ * - options (*NavigateOptions*): options passed to navigate.
2069
+ * - preventDefault (*function*): call to block the route change.
2070
+ * - defaultPrevented (*readonly boolean*): `true` if any previously called leave handlers called `preventDefault`.
2071
+ * - 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).
2072
+ *
2073
+ * @example
2074
+ * ```js
2075
+ * useBeforeLeave((e: BeforeLeaveEventArgs) => {
2076
+ * if (form.isDirty && !e.defaultPrevented) {
2077
+ * // preventDefault to block immediately and prompt user async
2078
+ * e.preventDefault();
2079
+ * setTimeout(() => {
2080
+ * if (window.confirm("Discard unsaved changes - are you sure?")) {
2081
+ * // user wants to proceed anyway so retry with force=true
2082
+ * e.retry(true);
2083
+ * }
2084
+ * }, 100);
2085
+ * }
2086
+ * });
2087
+ * ```
2088
+ */
2089
+ const useBeforeLeave = listener => {
2090
+ // Installing the guard here (instead of eagerly in the router/history) keeps
2091
+ // all of createBeforeLeave tree-shakeable for apps that never block leaves.
2092
+ const slot = useRouter().beforeLeave;
2093
+ const s = (slot.current || (slot.current = createBeforeLeave())).subscribe({
2094
+ listener,
2095
+ location: useLocation(),
2096
+ navigate: useNavigate()
2097
+ });
2098
+ onCleanup(s);
2099
+ };
2100
+
2101
+ // The no-JS form convention's cookie codec. When a form posts to a server
2102
+ // function without the client runtime (no instance header), the server
2103
+ // handler redirects back carrying the outcome in a one-shot "flash" cookie;
2104
+ // the next SSR pass reads it and seeds the router's submission state so
2105
+ // useSubmission() renders the result exactly as a scripted submission would.
2106
+ // Both codec halves live in this module so the write (src/server.ts, the
2107
+ // handler's handleNoJS) and the read (provided to the router core by
2108
+ // data/action.ts) can never drift apart. The cookie's name/clearing live in
2109
+ // flashCookie.ts — the only piece the router core itself consumes — so this
2110
+ // codec stays out of bundles that never load the action layer.
2111
+
2112
+ function decodeInputValue(value) {
2113
+ if (value && typeof value === "object") {
2114
+ if (Array.isArray(value.$f)) {
2115
+ const form = new FormData();
2116
+ for (const [k, v] of value.$f) form.append(k, v);
2117
+ return form;
2118
+ }
2119
+ if (Array.isArray(value.$u)) return new URLSearchParams(value.$u);
2120
+ }
2121
+ return value;
2122
+ }
2123
+
2124
+ /**
2125
+ * Decodes the flash cookie out of a request's Cookie header. Returns
2126
+ * undefined when absent or unreadable (a malformed cookie must never take
2127
+ * down SSR — it is cleared either way).
2128
+ */
2129
+ function decodeFlashCookie(cookieHeader) {
2130
+ const match = matchFlashCookie(cookieHeader);
2131
+ if (!match) return;
2132
+ try {
2133
+ const payload = JSON.parse(decodeURIComponent(match));
2134
+ if (!payload || !payload.result) return;
2135
+ const result = payload.error ? new Error(payload.result) : payload.result;
2136
+ return {
2137
+ input: Array.isArray(payload.input) ? payload.input.map(decodeInputValue) : [],
2138
+ url: payload.url,
2139
+ result: payload.thrown ? undefined : result,
2140
+ error: payload.thrown ? result : undefined
2141
+ };
2142
+ } catch (error) {
2143
+ console.error(error);
2144
+ }
2145
+ }
2146
+
2147
+ const LocationHeader = "Location";
2148
+ const PRELOAD_TIMEOUT = 5000;
2149
+ const CACHE_TIMEOUT = 180000;
2150
+ let cacheMap = new Map();
2151
+
2152
+ // cleanup forward/back cache
2153
+ if (!isServer) {
2154
+ setInterval(() => {
2155
+ const now = Date.now();
2156
+ for (let [k, v] of cacheMap.entries()) {
2157
+ if (!v[4].count && now - v[0] > CACHE_TIMEOUT) {
2158
+ cacheMap.delete(k);
2159
+ }
2160
+ }
2161
+ }, 300000);
2162
+ }
2163
+ function getCache() {
2164
+ if (!isServer) return cacheMap;
2165
+ const req = getRequestEvent();
2166
+ if (!req) throw new Error("Cannot find cache context");
2167
+ return (req.router || (req.router = {})).cache || (req.router.cache = new Map());
2168
+ }
2169
+
2170
+ /**
2171
+ * Revalidates the given cache entry/entries.
2172
+ */
1157
2173
  function revalidate(key, force = true) {
1158
2174
  const now = Date.now();
1159
2175
  cacheKeyOp(key, entry => {
@@ -1168,8 +2184,16 @@ function cacheKeyOp(key, fn) {
1168
2184
  }
1169
2185
  }
1170
2186
  function query(fn, name) {
1171
- // prioritize GET for server functions
1172
- if (fn.GET) fn = fn.GET;
2187
+ // query implies GET: the router primitive is the declaration site, so a
2188
+ // server function handed to query() is wrapped with core `GET(fn)` here,
2189
+ // at query-creation (module scope) — the server half records the method
2190
+ // declaration for dispatch, the client half swaps in the GET transport.
2191
+ // An explicit `GET(fn)` already carries the declaration on the metadata
2192
+ // channel (`getServerFunctionMetadata(fn)?.method === "GET"`) and passes
2193
+ // through; non-server functions are untouched.
2194
+ if (isServerFunction(fn) && !getServerFunctionMetadata(fn)?.method) {
2195
+ fn = GET(fn);
2196
+ }
1173
2197
  const cachedFn = (...args) => {
1174
2198
  const cache = getCache();
1175
2199
  const intent = getIntent();
@@ -1336,7 +2360,113 @@ function isPlainObject(obj) {
1336
2360
  const submitHooksSymbol = Symbol("routerActionSubmitHooks");
1337
2361
  const settledHooksSymbol = Symbol("routerActionSettledHooks");
1338
2362
  const invokeSymbol = Symbol("routerActionInvoke");
2363
+
2364
+ // Forms submitted through delegation are marked `aria-busy` while their
2365
+ // action is in flight — the form half of the attribute vocabulary links get
2366
+ // (`data-active`/`data-pending`). Style with `form[aria-busy] button { ... }`.
2367
+ // A counter (not a boolean) keeps the attribute through overlapping
2368
+ // submissions from the same form.
2369
+ const busyForms = /* #__PURE__ */new WeakMap();
2370
+ function setFormBusy(form, delta) {
2371
+ const count = (busyForms.get(form) || 0) + delta;
2372
+ busyForms.set(form, count);
2373
+ count > 0 ? form.setAttribute("aria-busy", "true") : form.removeAttribute("aria-busy");
2374
+ }
1339
2375
  const actions = /* #__PURE__ */new Map();
2376
+
2377
+ /**
2378
+ * The document-delegation submit handler for router actions. Lives here —
2379
+ * not in events.ts — so the router's event wiring holds no static reference
2380
+ * to the action module; `installRouterIntegrations` slots it in when the
2381
+ * first action is created on the client.
2382
+ */
2383
+ function handleFormAction(evt, router, actionBase) {
2384
+ if (evt.defaultPrevented) return;
2385
+ let actionRef = evt.submitter && evt.submitter.hasAttribute("formaction") ? evt.submitter.getAttribute("formaction") : evt.target.getAttribute("action");
2386
+ if (!actionRef) return;
2387
+ const serverAction = !actionRef.startsWith("https://action/");
2388
+ if (serverAction) {
2389
+ // normalize server actions
2390
+ const url = new URL(actionRef, mockBase);
2391
+ actionRef = router.parsePath(url.pathname + url.search);
2392
+ if (!actionRef.startsWith(actionBase)) return;
2393
+ }
2394
+ if (evt.target.method.toUpperCase() !== "POST") throw new Error("Only POST forms are supported for Actions");
2395
+ // A registry miss on a server-action url is a direct bind whose module
2396
+ // never loaded client-side (server components): the url is self-describing
2397
+ // (`?id`, bound `?args`), so a generic invocation is synthesized from it —
2398
+ // delegation alone is sufficient, the no-JS path stays a no-JS fallback.
2399
+ // Client-only actions (`https://action/`) are their module's JS by
2400
+ // definition, so a miss there falls through to native submission.
2401
+ const handler = actions.get(actionRef) || serverAction && createServerFormAction(actionRef);
2402
+ if (handler) {
2403
+ evt.preventDefault();
2404
+ const data = new FormData(evt.target, evt.submitter);
2405
+ handler.call({
2406
+ r: router,
2407
+ f: evt.target
2408
+ }, evt.target.enctype === "multipart/form-data" ? data : new URLSearchParams(data));
2409
+ }
2410
+ }
2411
+
2412
+ /**
2413
+ * Synthesizes a router action for a server-rendered action url. The url
2414
+ * carries everything an invocation needs — the function id and any bound
2415
+ * `.with()` arguments (plain JSON in `?args`, which the server prepends for
2416
+ * natural-encoding bodies exactly as it does for no-JS posts) — so the
2417
+ * FormData is posted to it verbatim through the server-function transport:
2418
+ * submissions, `aria-busy`, redirects, revalidation, and single-flight all
2419
+ * flow through the normal action machinery. Registered under the url, so
2420
+ * repeat submits reuse it (and a later real registration overrides it).
2421
+ */
2422
+ function createServerFormAction(url) {
2423
+ const id = new URL(url, mockBase).searchParams.get("id");
2424
+ if (!id) return undefined;
2425
+ // typecheck resolves the server half of the dual module; this path only
2426
+ // runs in the browser, where the client transport's signature applies
2427
+ const stub = createServerReference(id, undefined, url);
2428
+ const caller = Object.assign(form => stub(form), {
2429
+ url
2430
+ });
2431
+ return actionImpl(caller);
2432
+ }
2433
+
2434
+ /**
2435
+ * Entry point for delegation's lazy fallback (data/events.ts): when no form
2436
+ * handler was ever installed — no action module in the client graph at all —
2437
+ * the router intercepts posts to server-action urls synchronously and loads
2438
+ * this module to run them. The FormData was captured at submit time; only
2439
+ * the enctype conversion and the generic invocation happen here.
2440
+ */
2441
+ function submitServerForm(router, url, form, data) {
2442
+ const handler = actions.get(url) || createServerFormAction(url);
2443
+ // no `?id` — not the server function convention; nothing can run it,
2444
+ // resubmit natively (submit() bypasses the delegated handler)
2445
+ if (!handler) return form.submit();
2446
+ handler.call({
2447
+ r: router,
2448
+ f: form
2449
+ }, form.enctype === "multipart/form-data" ? data : new URLSearchParams(data));
2450
+ }
2451
+
2452
+ // Wires the action layer into the router's slots exactly once, triggered by
2453
+ // the first action creation. Not an import side effect — with
2454
+ // `sideEffects: false`, module evaluation only happens when action() is
2455
+ // actually used, which is precisely when the wiring is wanted: no action in
2456
+ // the graph means no form interception, no single-flight subscription (the
2457
+ // server is never asked to collect), and no flash cookies to decode. On the
2458
+ // server, actions are created at module scope, so the flash decoder is
2459
+ // always installed before useSubmission can read the submissions signal.
2460
+ let integrationsInstalled = false;
2461
+ function installRouterIntegrations() {
2462
+ if (integrationsInstalled) return;
2463
+ integrationsInstalled = true;
2464
+ provideFlashDecoder(decodeFlashCookie);
2465
+ if (!isServer) {
2466
+ setRouterFormHandler(handleFormAction);
2467
+ provideFlightConsumer(setupFlightDataConsumer);
2468
+ }
2469
+ }
1340
2470
  function useSubmissions(fn, filter) {
1341
2471
  const router = useRouter();
1342
2472
  const subs = createMemo(() => router.submissions[0]().filter(s => s.url === fn.base && (!filter || filter(s.input))));
@@ -1362,11 +2492,10 @@ function actionImpl(fn, options = {}) {
1362
2492
  const form = this.f;
1363
2493
  const submitHooks = current[submitHooksSymbol];
1364
2494
  const settledHooks = current[settledHooksSymbol];
1365
- const runMutation = () => (router.singleFlight && fn.withOptions ? fn.withOptions({
1366
- headers: {
1367
- "X-Single-Flight": "true"
1368
- }
1369
- }) : fn)(...variables);
2495
+ // Single-flight opt-in is no longer per call: the router's registered
2496
+ // flight-data consumer (see setupFlightDataConsumer) makes the transport
2497
+ // send the request header itself, so the mutation is just called.
2498
+ const runMutation = () => fn(...variables);
1370
2499
  const run = action$1(async function* (context) {
1371
2500
  context.optimistic?.();
1372
2501
  try {
@@ -1384,20 +2513,33 @@ function actionImpl(fn, options = {}) {
1384
2513
  };
1385
2514
  }
1386
2515
  });
1387
- const settled = await settleActionResult(run({
1388
- call: runMutation,
1389
- optimistic: submitHooks.size ? () => {
1390
- for (const hook of submitHooks.values()) hook(...variables);
1391
- } : undefined
1392
- }));
1393
- const response = await handleResponse(settled.value, settled.error, router.navigatorFactory());
1394
- if (!response) return undefined;
2516
+ form && setFormBusy(form, 1);
2517
+ let settled;
2518
+ let response;
2519
+ // The transport consumer is awaited before a single-flight mutation
2520
+ // resolves, so a counter delta over the call tells whether this action's
2521
+ // metadata was already applied. Overlapping mutations can cross-attribute
2522
+ // a run (skipping one default revalidation another pass just covered) —
2523
+ // a far smaller window than predicting from the function's identity,
2524
+ // which misses every response the server returned without flight data.
2525
+ const flightApplicationsBefore = flightApplications;
2526
+ try {
2527
+ settled = await settleActionResult(run({
2528
+ call: runMutation,
2529
+ optimistic: submitHooks.size ? () => {
2530
+ for (const hook of submitHooks.values()) hook(...variables);
2531
+ } : undefined
2532
+ }));
2533
+ response = await handleResponse(settled.value, settled.error, router.navigatorFactory(), flightApplications !== flightApplicationsBefore);
2534
+ } finally {
2535
+ form && setFormBusy(form, -1);
2536
+ }
1395
2537
  let submission;
1396
2538
  submission = {
1397
2539
  input: variables,
1398
2540
  url,
1399
- result: response.data,
1400
- error: response.error,
2541
+ result: response && response.data,
2542
+ error: response && response.error,
1401
2543
  clear() {
1402
2544
  router.submissions[1](entries => entries.filter(entry => entry !== submission));
1403
2545
  },
@@ -1409,10 +2551,18 @@ function actionImpl(fn, options = {}) {
1409
2551
  }, variables, current);
1410
2552
  }
1411
2553
  };
1412
- router.submissions[1](entries => [...entries, submission]);
2554
+ // Book-keeping is intentional: only outcomes worth showing or retrying
2555
+ // (a result or an error) enter the submissions list, so the typical void
2556
+ // mutation leaves nothing behind. Settled hooks still see every
2557
+ // completion — void, metadata-only, and redirects included — one
2558
+ // `onSettled` per invocation (#580).
2559
+ response && router.submissions[1](entries => [...entries, submission]);
1413
2560
  for (const hook of settledHooks.values()) hook(submission);
1414
- if (response.error && !form) throw response.error;
1415
- return response.data;
2561
+ if (response) {
2562
+ if (response.error && !form) throw response.error;
2563
+ return response.data;
2564
+ }
2565
+ return undefined;
1416
2566
  }
1417
2567
  const o = typeof options === "string" ? {
1418
2568
  name: options
@@ -1455,6 +2605,7 @@ function toAction(invoke, url, boundArgs = [], base = url, submitHooks = new Map
1455
2605
  fn[submitHooksSymbol] = submitHooks;
1456
2606
  fn[settledHooksSymbol] = settledHooks;
1457
2607
  fn[invokeSymbol] = invoke;
2608
+ installRouterIntegrations();
1458
2609
  if (!isServer) {
1459
2610
  actions.set(url, fn);
1460
2611
  // Only remove the registration if it still belongs to this instance —
@@ -1476,15 +2627,67 @@ async function settleActionResult(result) {
1476
2627
  while (!next.done) {
1477
2628
  next = await iterator.next();
1478
2629
  }
1479
- return next.value;
2630
+ return next.value;
2631
+ }
2632
+ return result;
2633
+ }
2634
+
2635
+ // Invocation count of the flight-data consumer. An action compares it across
2636
+ // its mutation call to learn whether the transport already applied this
2637
+ // response's metadata (and so the default revalidation pass must not run
2638
+ // again and wipe the freshly seeded cache).
2639
+ let flightApplications = 0;
2640
+
2641
+ /**
2642
+ * Registers the router as the single-flight consumer of the server function
2643
+ * transport. Subscribing is the opt-in: while registered, the transport
2644
+ * sends the `X-Single-Flight` request header on mutations and delivers the
2645
+ * folded payload here — fresh route data is seeded into the `query` cache
2646
+ * and the envelope metadata (redirect `Location`, `X-Revalidate` keys) is
2647
+ * applied, all before the action sees its plain return value. Called by the
2648
+ * Router component on the client unless `singleFlight={false}`, which now
2649
+ * simply means "never subscribe" — no consumer, no request header, no
2650
+ * collection work on the server. Returns the unsubscribe function.
2651
+ */
2652
+ function setupFlightDataConsumer(router) {
2653
+ return subscribeFlightData((data, {
2654
+ response
2655
+ }) => {
2656
+ flightApplications++;
2657
+ return applyResponseMetadata(response, router.navigatorFactory(), data);
2658
+ });
2659
+ }
2660
+
2661
+ /**
2662
+ * Applies a server function response's integration metadata: `X-Revalidate`
2663
+ * keys invalidate, `Location` navigates (hard for absolute urls), flight
2664
+ * data seeds the query cache, and matching entries revalidate. Shared by
2665
+ * the flight-data consumer and the action response path (which still sees
2666
+ * metadata-bearing responses when no flight data was collected).
2667
+ */
2668
+ function applyResponseMetadata(metadata, navigate, flightData) {
2669
+ let keys;
2670
+ if (metadata) {
2671
+ if (metadata.headers.has("X-Revalidate")) keys = metadata.headers.get("X-Revalidate").split(",");
2672
+ if (metadata.headers.has("Location")) {
2673
+ const locationUrl = metadata.headers.get("Location") || "/";
2674
+ if (locationUrl.startsWith("http")) {
2675
+ window.location.href = locationUrl;
2676
+ } else {
2677
+ navigate(locationUrl);
2678
+ }
2679
+ }
1480
2680
  }
1481
- return result;
2681
+ // invalidate
2682
+ cacheKeyOp(keys, entry => entry[0] = 0);
2683
+ // set cache
2684
+ flightData && Object.keys(flightData).forEach(k => query.set(k, flightData[k]));
2685
+ // trigger revalidation
2686
+ revalidate(keys, false);
1482
2687
  }
1483
- async function handleResponse(response, error, navigate) {
2688
+ async function handleResponse(response, error, navigate, metadataHandled) {
1484
2689
  let data;
1485
- let custom;
1486
- let keys;
1487
- let flightKeys;
2690
+ let flightData;
1488
2691
  let metadata;
1489
2692
  if (isResponseEnvelope(response)) {
1490
2693
  // client-only respond(): the value rides in memory beside the metadata
@@ -1492,377 +2695,39 @@ async function handleResponse(response, error, navigate) {
1492
2695
  metadata = response.response;
1493
2696
  } else if (response instanceof Response) {
1494
2697
  metadata = response;
1495
- // responses the transport hands over whole (redirects, revalidation,
1496
- // single-flight) carry a codec-encoded body the router decodes itself
2698
+ // responses the transport hands over whole (redirects, revalidation)
2699
+ // carry a codec-encoded body the router decodes itself. With the
2700
+ // flight-data consumer registered single-flight payloads never reach
2701
+ // this path, but a manually opted-in call (no consumer) still can —
2702
+ // unwrap the standardized { value, data } shape for it too.
1497
2703
  if (response.body) {
1498
2704
  data = await decodeResponse(response);
1499
2705
  if (response.headers.has("X-Single-Flight")) {
1500
- custom = data;
1501
- data = custom._$value;
1502
- delete custom._$value;
1503
- flightKeys = Object.keys(custom);
2706
+ const payload = data;
2707
+ data = payload.value;
2708
+ flightData = payload.data;
1504
2709
  }
1505
2710
  }
1506
2711
  } else if (error) return {
1507
2712
  error: response
1508
2713
  };else data = response;
1509
- if (metadata) {
1510
- if (metadata.headers.has("X-Revalidate")) keys = metadata.headers.get("X-Revalidate").split(",");
1511
- if (metadata.headers.has("Location")) {
1512
- const locationUrl = metadata.headers.get("Location") || "/";
1513
- if (locationUrl.startsWith("http")) {
1514
- window.location.href = locationUrl;
1515
- } else {
1516
- navigate(locationUrl);
1517
- }
1518
- }
1519
- }
1520
- // invalidate
1521
- cacheKeyOp(keys, entry => entry[0] = 0);
1522
- // set cache
1523
- flightKeys && flightKeys.forEach(k => query.set(k, custom[k]));
1524
- // trigger revalidation
1525
- await revalidate(keys, false);
2714
+ // The transport consumer applies metadata before returning a server
2715
+ // function's unwrapped value. Do not treat that value as a second plain
2716
+ // action response and invalidate the freshly seeded query cache again.
2717
+ if (!metadataHandled || metadata || flightData) applyResponseMetadata(metadata, navigate, flightData);
1526
2718
  return data != null ? {
1527
2719
  data
1528
2720
  } : undefined;
1529
2721
  }
1530
2722
 
1531
- function setupNativeEvents({
1532
- preload = true,
1533
- explicitLinks = false,
1534
- actionBase = "/_server",
1535
- transformUrl
1536
- } = {}) {
1537
- return router => {
1538
- const basePath = router.base.path();
1539
- const navigateFromRoute = router.navigatorFactory(router.base);
1540
- let preloadTimeout;
1541
- let lastElement;
1542
- function isSvg(el) {
1543
- return el.namespaceURI === "http://www.w3.org/2000/svg";
1544
- }
1545
- function handleAnchor(evt) {
1546
- if (evt.defaultPrevented || evt.button !== 0 || evt.metaKey || evt.altKey || evt.ctrlKey || evt.shiftKey) return;
1547
- const a = evt.composedPath().find(el => el instanceof Node && el.nodeName.toUpperCase() === "A");
1548
- if (!a || explicitLinks && !a.hasAttribute("link")) return;
1549
- const svg = isSvg(a);
1550
- const href = svg ? a.href.baseVal : a.href;
1551
- const target = svg ? a.target.baseVal : a.target;
1552
- if (target || !href && !a.hasAttribute("state")) return;
1553
- const rel = (a.getAttribute("rel") || "").split(/\s+/);
1554
- if (a.hasAttribute("download") || rel && rel.includes("external")) return;
1555
- const url = svg ? new URL(href, document.baseURI) : new URL(href);
1556
- if (url.origin !== window.location.origin || basePath && url.pathname && !url.pathname.toLowerCase().startsWith(basePath.toLowerCase())) return;
1557
- return [a, url];
1558
- }
1559
- function handleAnchorClick(evt) {
1560
- const res = handleAnchor(evt);
1561
- if (!res) return;
1562
- const [a, url] = res;
1563
- const to = router.parsePath(url.pathname + url.search + url.hash);
1564
- const state = a.getAttribute("state");
1565
- evt.preventDefault();
1566
- navigateFromRoute(to, {
1567
- resolve: false,
1568
- replace: a.hasAttribute("replace"),
1569
- scroll: !a.hasAttribute("noscroll"),
1570
- state: state ? JSON.parse(state) : undefined
1571
- });
1572
- }
1573
- function handleAnchorPreload(evt) {
1574
- const res = handleAnchor(evt);
1575
- if (!res) return;
1576
- const [a, url] = res;
1577
- transformUrl && (url.pathname = transformUrl(url.pathname));
1578
- router.preloadRoute(url, a.getAttribute("preload") !== "false");
1579
- }
1580
- function handleAnchorMove(evt) {
1581
- clearTimeout(preloadTimeout);
1582
- const res = handleAnchor(evt);
1583
- if (!res) return lastElement = null;
1584
- const [a, url] = res;
1585
- if (lastElement === a) return;
1586
- transformUrl && (url.pathname = transformUrl(url.pathname));
1587
- preloadTimeout = setTimeout(() => {
1588
- router.preloadRoute(url, a.getAttribute("preload") !== "false");
1589
- lastElement = a;
1590
- }, 20);
1591
- }
1592
- function handleFormSubmit(evt) {
1593
- if (evt.defaultPrevented) return;
1594
- let actionRef = evt.submitter && evt.submitter.hasAttribute("formaction") ? evt.submitter.getAttribute("formaction") : evt.target.getAttribute("action");
1595
- if (!actionRef) return;
1596
- if (!actionRef.startsWith("https://action/")) {
1597
- // normalize server actions
1598
- const url = new URL(actionRef, mockBase);
1599
- actionRef = router.parsePath(url.pathname + url.search);
1600
- if (!actionRef.startsWith(actionBase)) return;
1601
- }
1602
- if (evt.target.method.toUpperCase() !== "POST") throw new Error("Only POST forms are supported for Actions");
1603
- const handler = actions.get(actionRef);
1604
- if (handler) {
1605
- evt.preventDefault();
1606
- const data = new FormData(evt.target, evt.submitter);
1607
- handler.call({
1608
- r: router,
1609
- f: evt.target
1610
- }, evt.target.enctype === "multipart/form-data" ? data : new URLSearchParams(data));
1611
- }
1612
- }
1613
-
1614
- // ensure delegated event run first
1615
- delegateEvents(["click", "submit"]);
1616
- document.addEventListener("click", handleAnchorClick);
1617
- if (preload) {
1618
- document.addEventListener("mousemove", handleAnchorMove, {
1619
- passive: true
1620
- });
1621
- document.addEventListener("focusin", handleAnchorPreload, {
1622
- passive: true
1623
- });
1624
- document.addEventListener("touchstart", handleAnchorPreload, {
1625
- passive: true
1626
- });
1627
- }
1628
- document.addEventListener("submit", handleFormSubmit);
1629
- onCleanup(() => {
1630
- document.removeEventListener("click", handleAnchorClick);
1631
- if (preload) {
1632
- document.removeEventListener("mousemove", handleAnchorMove);
1633
- document.removeEventListener("focusin", handleAnchorPreload);
1634
- document.removeEventListener("touchstart", handleAnchorPreload);
1635
- }
1636
- document.removeEventListener("submit", handleFormSubmit);
1637
- });
1638
- };
1639
- }
1640
-
1641
- function Router(props) {
1642
- if (isServer) return StaticRouter(props);
1643
- const getSource = () => {
1644
- const url = window.location.pathname + window.location.search;
1645
- const state = window.history.state && window.history.state._depth && Object.keys(window.history.state).length === 1 ? undefined : window.history.state;
1646
- return {
1647
- value: url + window.location.hash,
1648
- state
1649
- };
1650
- };
1651
- const beforeLeave = createBeforeLeave();
1652
- return createRouter({
1653
- get: getSource,
1654
- set({
1655
- value,
1656
- replace,
1657
- scroll,
1658
- state
1659
- }) {
1660
- if (replace) {
1661
- window.history.replaceState(keepDepth(state), "", value);
1662
- } else {
1663
- window.history.pushState(state, "", value);
1664
- }
1665
- scrollToHash(decodeURIComponent(window.location.hash.slice(1)), scroll);
1666
- saveCurrentDepth();
1667
- },
1668
- init: notify => bindEvent(window, "popstate", notifyIfNotBlocked(notify, delta => {
1669
- if (delta) {
1670
- return !beforeLeave.confirm(delta);
1671
- } else {
1672
- const s = getSource();
1673
- return !beforeLeave.confirm(s.value, {
1674
- state: s.state
1675
- });
1676
- }
1677
- })),
1678
- create: setupNativeEvents({
1679
- preload: props.preload,
1680
- explicitLinks: props.explicitLinks,
1681
- actionBase: props.actionBase,
1682
- transformUrl: props.transformUrl
1683
- }),
1684
- utils: {
1685
- go: delta => window.history.go(delta),
1686
- beforeLeave
1687
- }
1688
- })(props);
1689
- }
1690
-
1691
- function hashParser(str) {
1692
- const to = str.replace(/^.*?#/, "");
1693
- // Hash-only hrefs like `#foo` from plain anchors will come in as `/#foo` whereas a link to
1694
- // `/foo` will be `/#/foo`. Check if the to starts with a `/` and if not append it as a hash
1695
- // to the current path so we can handle these in-page anchors correctly.
1696
- if (!to.startsWith("/")) {
1697
- const [, path = "/"] = window.location.hash.split("#", 2);
1698
- return `${path}#${to}`;
1699
- }
1700
- return to;
1701
- }
1702
- function HashRouter(props) {
1703
- const getSource = () => window.location.hash.slice(1);
1704
- const beforeLeave = createBeforeLeave();
1705
- return createRouter({
1706
- get: getSource,
1707
- set({
1708
- value,
1709
- replace,
1710
- scroll,
1711
- state
1712
- }) {
1713
- if (replace) {
1714
- window.history.replaceState(keepDepth(state), "", "#" + value);
1715
- } else {
1716
- window.history.pushState(state, "", "#" + value);
1717
- }
1718
- const hashIndex = value.indexOf("#");
1719
- const hash = hashIndex >= 0 ? value.slice(hashIndex + 1) : "";
1720
- scrollToHash(hash, scroll);
1721
- saveCurrentDepth();
1722
- },
1723
- init: notify => bindEvent(window, "hashchange", notifyIfNotBlocked(notify, delta => !beforeLeave.confirm(delta && delta < 0 ? delta : getSource()))),
1724
- create: setupNativeEvents({
1725
- preload: props.preload,
1726
- explicitLinks: props.explicitLinks,
1727
- actionBase: props.actionBase
1728
- }),
1729
- utils: {
1730
- go: delta => window.history.go(delta),
1731
- renderPath: path => `#${path}`,
1732
- parsePath: hashParser,
1733
- beforeLeave
1734
- }
1735
- })(props);
1736
- }
1737
-
1738
- function createMemoryHistory() {
1739
- const entries = ["/"];
1740
- let index = 0;
1741
- const listeners = [];
1742
- const go = n => {
1743
- // https://github.com/remix-run/react-router/blob/682810ca929d0e3c64a76f8d6e465196b7a2ac58/packages/router/history.ts#L245
1744
- index = Math.max(0, Math.min(index + n, entries.length - 1));
1745
- const value = entries[index];
1746
- listeners.forEach(listener => listener(value));
1747
- };
1748
- return {
1749
- get: () => entries[index],
1750
- set: ({
1751
- value,
1752
- scroll,
1753
- replace
1754
- }) => {
1755
- if (replace) {
1756
- entries[index] = value;
1757
- } else {
1758
- entries.splice(index + 1, entries.length - index, value);
1759
- index++;
1760
- }
1761
- listeners.forEach(listener => listener(value));
1762
- setTimeout(() => {
1763
- if (scroll) {
1764
- scrollToHash(value.split("#")[1] || "", true);
1765
- }
1766
- }, 0);
1767
- },
1768
- back: () => {
1769
- go(-1);
1770
- },
1771
- forward: () => {
1772
- go(1);
1773
- },
1774
- go,
1775
- listen: listener => {
1776
- listeners.push(listener);
1777
- return () => {
1778
- const index = listeners.indexOf(listener);
1779
- listeners.splice(index, 1);
1780
- };
1781
- }
1782
- };
1783
- }
1784
- function MemoryRouter(props) {
1785
- const memoryHistory = props.history || createMemoryHistory();
1786
- return createRouter({
1787
- get: memoryHistory.get,
1788
- set: memoryHistory.set,
1789
- init: memoryHistory.listen,
1790
- create: setupNativeEvents({
1791
- preload: props.preload,
1792
- explicitLinks: props.explicitLinks,
1793
- actionBase: props.actionBase
1794
- }),
1795
- utils: {
1796
- go: memoryHistory.go
1797
- }
1798
- })(props);
1799
- }
1800
-
1801
- var _tmpl$ = /*#__PURE__*/template(`<a>`);
2723
+ // The delegation fallback's lazy entry (see data/events.ts). Nothing imports
2724
+ // this module statically — it exists so the dynamic import has a target that
2725
+ // bundlers can keep as a split point: router-only apps never load the action
2726
+ // machinery unless a server-action form actually submits.
1802
2727
 
1803
- // the JSX namespace lives in @solidjs/web's jsx-runtime module as of 2.0
1804
-
1805
- function toClassName(value) {
1806
- if (!value) return "";
1807
- if (typeof value === "string" || typeof value === "number") return String(value);
1808
- if (Array.isArray(value)) return value.map(toClassName).filter(Boolean).join(" ");
1809
- if (typeof value === "object") {
1810
- return Object.entries(value).filter(([, enabled]) => enabled).map(([name]) => name).join(" ");
1811
- }
1812
- return "";
1813
- }
1814
- function A(props) {
1815
- props = merge({
1816
- inactiveClass: "inactive",
1817
- activeClass: "active"
1818
- }, props);
1819
- const rest = omit(props, "href", "state", "class", "activeClass", "inactiveClass", "end");
1820
- const to = useResolvedPath(() => props.href);
1821
- const href = useHref(to);
1822
- const location = useLocation();
1823
- const isActive = createMemo(() => {
1824
- const to_ = to();
1825
- if (to_ === undefined) return [false, false];
1826
- // trailing slashes are ignored so `/route` and `/route/` share active state
1827
- const path = normalizePath(to_.split(/[?#]/, 1)[0]).toLowerCase().replace(/\/$/, "");
1828
- const loc = decodeURI(normalizePath(location.pathname).toLowerCase().replace(/\/$/, ""));
1829
- return [props.end ? path === loc : loc.startsWith(path + "/") || loc === path, path === loc];
1830
- });
1831
- const className = createMemo(() => [toClassName(props.class), isActive()[0] ? props.activeClass : props.inactiveClass].filter(Boolean).join(" "));
1832
- var _el$ = _tmpl$();
1833
- spread(_el$, mergeProps(rest, {
1834
- get href() {
1835
- return href() || props.href;
1836
- },
1837
- get state() {
1838
- return JSON.stringify(props.state);
1839
- },
1840
- get ["class"]() {
1841
- return className();
1842
- },
1843
- "link": true,
1844
- get ["aria-current"]() {
1845
- return isActive()[1] ? "page" : undefined;
1846
- }
1847
- }), false);
1848
- return _el$;
1849
- }
1850
- function Navigate(props) {
1851
- const navigate = useNavigate();
1852
- const location = useLocation();
1853
- const {
1854
- href,
1855
- state
1856
- } = props;
1857
- const path = typeof href === "function" ? href({
1858
- navigate,
1859
- location
1860
- }) : href;
1861
- navigate(path, {
1862
- replace: true,
1863
- state
1864
- });
1865
- return null;
1866
- }
2728
+ var serverForms = /*#__PURE__*/Object.freeze({
2729
+ __proto__: null,
2730
+ submitServerForm: submitServerForm
2731
+ });
1867
2732
 
1868
- 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 };
2733
+ 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 };