@qwik.dev/router 2.0.0-rc.3 → 2.0.0-rc.5

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.
@@ -1,8 +1,9 @@
1
1
  import { t as ensureSlash } from "./chunks/pathname.mjs";
2
- import { $ as HttpStatusContext, B as _setRouterConfig, C as getRequestEvent, F as routeLoader$, G as REFRESH_HEAD, H as getRouterConfig, I as routeLoaderQrl, J as preventNav, K as RUN_PENDING_ACTION, L as setLoaderSignalValue, M as prepareRouteLoaders, P as restoreRouteLoaders, Q as DocumentHeadContext, S as getModuleRouteLoaders, U as getRoutes, V as getBasePathname, W as getTrailingSlash, X as ContentContext, Y as registerPreventNav, Z as ContentInternalContext, _ as commitRouteLoaders, a as isPromise, at as RouteStateContext, b as getClientRouteLoaders, c as shouldPreload, ct as QFN_KEY, d as loadRoute, et as RouteActionContext, h as clearNavFetchCache, i as getClientNavPath, it as RouteNavigateContext, k as isImmutableLoader, l as toPath, lt as Q_ROUTE, m as abortRouteLoaderNavigation, n as resolveHead, nt as RouteLoaderCtxContext, o as isSameOrigin, ot as QACTION_KEY, q as internalState, rt as RouteLocationContext, s as isSamePath, st as QDATA_KEY, t as createDocumentHead, tt as RouteActionRunnerContext, u as toUrl, v as ensureRouteLoaderSignals, y as fetchRouteLoaderData, z as _getServiceWorkerUrl } from "./chunks/head.qwik.mjs";
3
- import { SkipRender, Slot, _capturesObj, _fnSignal, _getConstProps, _getVarProps, _jsxSorted, _jsxSplit, _qrlSync, _restProps, _wrapProp, componentQrl, createComputedQrl, createElement, eventQrl, getLocale, implicit$FirstArg, inlinedQrl, isBrowser, isDev, isServer, noSerialize, untrack, useContext, useContextProvider, useServerData, useSignal, useStore, useTaskQrl, useVisibleTaskQrl, withLocale } from "@qwik.dev/core";
4
- import { _deserialize, _getContextContainer, _getContextHostElement, _getDomContainer, _hasStoreEffects, _regInlinedQrl, _requestPreload, _serialize, _waitOn, _waitUntilRendered, forceStoreEffects } from "@qwik.dev/core/internal";
2
+ import { $ as ContentContext, A as routeLoaderQrl, B as toUrl, C as isImmutableLoader, E as prepareRouteLoaders, F as isSameOrigin, G as getRouterConfig, H as _setRouterConfig, I as isSamePath, J as REFRESH_HEAD, K as getRoutes, L as shouldPreload, N as getClientNavPath, O as restoreRouteLoaders, P as isPromise, Q as registerPreventNav, R as toPath, U as findRouterConfig, V as _getServiceWorkerUrl, W as getBasePathname, X as internalState, Y as RUN_PENDING_ACTION, Z as preventNav, _ as getRequestEvent, a as matchRouteTree, at as RouteLoaderCtxContext, c as abortRouteLoaderNavigation, ct as RouteStateContext, d as commitRouteLoaders, dt as QFN_KEY, et as ContentInternalContext, f as ensureRouteLoaderSignals, ft as Q_ROUTE, g as getModuleRouteLoaders, i as loadRoute, it as RouteActionRunnerContext, j as setLoaderSignalValue, k as routeLoader$, l as clearNavFetchCache, lt as QACTION_KEY, m as getClientRouteLoaders, n as resolveHead, nt as HttpStatusContext, ot as RouteLocationContext, p as fetchRouteLoaderData, q as getTrailingSlash, rt as RouteActionContext, st as RouteNavigateContext, t as createDocumentHead, tt as DocumentHeadContext, ut as QDATA_KEY, z as toSafeRedirectUrl } from "./chunks/head.qwik.mjs";
3
+ import { SkipRender, Slot, _capturesObj, _fnSignal, _getConstProps, _getVarProps, _jsxSorted, _jsxSplit, _qrlSync, _restProps, _wrapProp, componentQrl, createComputedQrl, eventQrl, getLocale, implicit$FirstArg, inlinedQrl, isBrowser, isDev, isServer, noSerialize, untrack, useContext, useContextProvider, useServerData, useSignal, useStore, useTaskQrl, useVisibleTaskQrl, withLocale } from "@qwik.dev/core";
4
+ import { _deserialize, _getContextContainer, _getContextHostElement, _getDomContainer, _hasStoreEffects, _isSyncQrl, _regInlinedQrl, _requestPreload, _waitOn, _waitUntilRendered, forceStoreEffects } from "@qwik.dev/core/internal";
5
5
  import { Fragment } from "@qwik.dev/core/jsx-runtime";
6
+ import { _serialize } from "@qwik.dev/core/internal/serializer";
6
7
  import * as v from "valibot";
7
8
  import * as z$1 from "zod";
8
9
  import { z } from "zod";
@@ -134,6 +135,8 @@ var Link = /*#__PURE__*/ componentQrl(/*#__PURE__*/ inlinedQrl((props) => {
134
135
  const shouldPrefetch = untrack(shouldPreload, clientNavPath, loc);
135
136
  const shouldVisiblePrefetchBundles = !!clientNavPath && shouldPrefetch && !isDepratedPrefetchDisabled && (prefetchBundlesProp === "visible" || prefetchProp === "js" || prefetchProp === true);
136
137
  const shouldVisiblePrefetchData = !!clientNavPath && shouldPrefetch && !isDepratedPrefetchDisabled && (prefetchDataProp === "visible" || prefetchProp === true);
138
+ const routes = shouldVisiblePrefetchBundles && findRouterConfig()?.routes;
139
+ const route = routes && untrack(() => matchRouteTree(routes, new URL(clientNavPath, loc.url).pathname));
137
140
  const shouldPrefetchBundles = !!clientNavPath && prefetchBundlesProp !== "off" && shouldPrefetch && !isDepratedPrefetchDisabled;
138
141
  const shouldPrefetchData = !!clientNavPath && prefetchDataProp !== "off" && shouldPrefetch && !isDepratedPrefetchDisabled;
139
142
  const handleBundlePrefetch = shouldPrefetchBundles ? /*#__PURE__*/ inlinedQrl((_, elm) => {
@@ -167,13 +170,13 @@ var Link = /*#__PURE__*/ componentQrl(/*#__PURE__*/ inlinedQrl((props) => {
167
170
  let nav = _capturesObj._[0], reload = _capturesObj._[1], replaceState = _capturesObj._[2], scroll = _capturesObj._[3];
168
171
  if (event.defaultPrevented) {
169
172
  if (elm.href) {
170
- elm.setAttribute("aria-pressed", "true");
173
+ elm.setAttribute("data-navigating", "");
171
174
  nav(elm.href, {
172
175
  forceReload: reload,
173
176
  replaceState,
174
177
  scroll
175
- }).then(() => {
176
- elm.removeAttribute("aria-pressed");
178
+ }).finally(() => {
179
+ elm.removeAttribute("data-navigating");
177
180
  });
178
181
  }
179
182
  }
@@ -184,10 +187,10 @@ var Link = /*#__PURE__*/ componentQrl(/*#__PURE__*/ inlinedQrl((props) => {
184
187
  scroll
185
188
  ]) : null;
186
189
  return /*#__PURE__*/ _jsxSplit("a", {
187
- ..._getVarProps({ "q:link": !!clientNavPath }),
188
- ..._getConstProps({ "q:link": !!clientNavPath }),
190
+ "q:link": !!clientNavPath,
189
191
  ...linkProps,
190
192
  "data-q-prefetch": shouldVisiblePrefetchBundles && shouldVisiblePrefetchData ? "bd" : shouldVisiblePrefetchBundles ? "b" : shouldVisiblePrefetchData ? "d" : null,
193
+ "data-q-route": route && !route.notFound ? "/" + route.routeParts.join("/") : void 0,
191
194
  "q-e:click": [
192
195
  preventDefault,
193
196
  /*#__PURE__*/ inlinedQrl((_, elm) => {
@@ -233,11 +236,11 @@ var newScrollState = () => {
233
236
  h: 0
234
237
  };
235
238
  };
236
- var preloadRouteBundles = (path, probability = .8) => {
239
+ var preloadRouteBundles = (routeName, probability = .8) => {
237
240
  if (isBrowser) {
238
- path = ensureSlash(path);
239
- path = path.length > 1 && path.startsWith("/") ? path.slice(1) : path;
240
- _requestPreload(path, probability);
241
+ routeName = ensureSlash(routeName);
242
+ routeName = routeName.length > 1 && routeName.startsWith("/") ? routeName.slice(1) : routeName;
243
+ _requestPreload(routeName, probability);
241
244
  }
242
245
  };
243
246
  var prefetchedLinks = /* @__PURE__ */ new WeakSet();
@@ -269,7 +272,8 @@ var createLinkPrefetchObserver = (manifestHash) => {
269
272
  const currentUrl = new URL(location.href);
270
273
  if (!isSameOrigin(url, currentUrl) || !shouldPreload(toPath(url), { url: currentUrl })) return;
271
274
  const mode = anchor.getAttribute("data-q-prefetch") || "";
272
- if (mode.includes("b")) preloadRouteBundles(url.pathname);
275
+ const routeName = anchor.getAttribute("data-q-route");
276
+ if (mode.includes("b") && routeName) preloadRouteBundles(routeName);
273
277
  if (mode.includes("d")) prefetchRoute(url, true, .8, manifestHash, false);
274
278
  };
275
279
  if (typeof IntersectionObserver === "undefined") {
@@ -335,6 +339,7 @@ var createCurrentPathTracker = (initialPath) => {
335
339
  var dispatchRouterPopstate = (document1, href) => {
336
340
  document1.dispatchEvent(new CustomEvent(Q_ROUTER_POPSTATE_EVENT, { detail: { href } }));
337
341
  };
342
+ var isPlainPrimaryClick = (event) => event.button === 0 && !(event.metaKey || event.ctrlKey || event.shiftKey || event.altKey);
338
343
  var spa_init_default = eventQrl(/*#__PURE__*/ inlinedQrl((_, el) => {
339
344
  if (!window._qRouterSPA && !window._qRouterInitPopstate) {
340
345
  const currentPath = location.pathname + location.search;
@@ -362,8 +367,10 @@ var spa_init_default = eventQrl(/*#__PURE__*/ inlinedQrl((_, el) => {
362
367
  if (window._qRouterSPA) return;
363
368
  window._qRouterScrollEnabled = false;
364
369
  clearTimeout(window._qRouterScrollDebounce);
365
- if (hasPathChanged(location.pathname + location.search)) dispatchRouterPopstate(document, location.href);
366
- else if (history.scrollRestoration === "manual") {
370
+ if (hasPathChanged(location.pathname + location.search)) {
371
+ if (window._qRouterInitNavigate) window._qRouterInitNavigate(location.href, { type: "popstate" });
372
+ else dispatchRouterPopstate(document, location.href);
373
+ } else if (history.scrollRestoration === "manual") {
367
374
  const scrollState = history.state?._qRouterScroll;
368
375
  checkAndScroll(scrollState);
369
376
  window._qRouterScrollEnabled = true;
@@ -384,15 +391,19 @@ var spa_init_default = eventQrl(/*#__PURE__*/ inlinedQrl((_, el) => {
384
391
  };
385
392
  history.pushState = (state, title, url) => {
386
393
  state = prepareState(state);
387
- return pushState.call(history, state, title, url);
394
+ const result = pushState.call(history, state, title, url);
395
+ hasPathChanged(location.pathname + location.search);
396
+ return result;
388
397
  };
389
398
  history.replaceState = (state, title, url) => {
390
399
  state = prepareState(state);
391
- return replaceState.call(history, state, title, url);
400
+ const result = replaceState.call(history, state, title, url);
401
+ hasPathChanged(location.pathname + location.search);
402
+ return result;
392
403
  };
393
404
  }
394
405
  window._qRouterInitAnchors = (event) => {
395
- if (window._qRouterSPA || event.defaultPrevented) return;
406
+ if (window._qRouterSPA || event.defaultPrevented || !isPlainPrimaryClick(event)) return;
396
407
  const target = event.target.closest("a[href]");
397
408
  if (target && !target.hasAttribute("preventdefault:click")) {
398
409
  const href = target.getAttribute("href");
@@ -486,8 +497,9 @@ async function submitAction(action, routeUrl) {
486
497
  loaderHashes: data?.loaderHashes
487
498
  };
488
499
  }
500
+ throw new Error(`Unexpected action response (${response.status}): expected JSON`);
489
501
  }
490
- var qwik_view_transition_default = "@layer qwik{@supports selector(html:active-view-transition-type(type)){html:active-view-transition-type(qwik-navigation){& :root{view-transition-name:none}}}@supports not selector(html:active-view-transition-type(type)){:root{view-transition-name:none}}}";
502
+ var qwik_view_transition_default = "@layer qwik{@supports selector(html:active-view-transition-type(type)){html:active-view-transition-type(qwik-navigation){view-transition-name:none}}@supports not selector(html:active-view-transition-type(type)){:root{view-transition-name:none}}}";
491
503
  /** View transitions are opt-in and require browser support. */
492
504
  var shouldStartViewTransition = (viewTransition) => viewTransition === true && "startViewTransition" in document;
493
505
  var VIEW_TRANSITION_STYLE_ID = "qwik-view-transition";
@@ -523,10 +535,36 @@ var startViewTransition = (params) => {
523
535
  var QWIK_CITY_SCROLLER = "_qCityScroller";
524
536
  /** @public */
525
537
  var QWIK_ROUTER_SCROLLER = "_qRouterScroller";
538
+ var NavigationStartType = /* @__PURE__ */ function(NavigationStartType) {
539
+ NavigationStartType[NavigationStartType["Unchanged"] = 0] = "Unchanged";
540
+ NavigationStartType[NavigationStartType["Duplicate"] = 1] = "Duplicate";
541
+ NavigationStartType[NavigationStartType["Prepared"] = 2] = "Prepared";
542
+ NavigationStartType[NavigationStartType["Superseded"] = 3] = "Superseded";
543
+ NavigationStartType[NavigationStartType["External"] = 4] = "External";
544
+ return NavigationStartType;
545
+ }(NavigationStartType || {});
526
546
  var ensureRouteInternal = (routeInternal, routeLocation) => routeInternal.untrackedValue ||= {
527
547
  type: "initial",
528
548
  dest: routeLocation.url
529
549
  };
550
+ /**
551
+ * A URL the client can't render itself (no matching page) may be a server `rewrite()`. Ask the
552
+ * server where it routes to. Returns the target pathname, `'reload'` if the server redirects, or
553
+ * `undefined` when the URL is not rewritten.
554
+ */
555
+ var resolveServerRewrite = async (url) => {
556
+ try {
557
+ const response = await fetch(`${ensureSlash(url.pathname)}q-route.json${url.search}`, {
558
+ redirect: "manual",
559
+ headers: { accept: "application/json" }
560
+ });
561
+ if (response.type === "opaqueredirect" || response.status >= 300 && response.status < 400) return "reload";
562
+ if (response.ok) {
563
+ const { p } = await response.json();
564
+ return typeof p === "string" ? p : void 0;
565
+ }
566
+ } catch {}
567
+ };
530
568
  var getRouterContainer = () => _getDomContainer(document.documentElement);
531
569
  var getServerHttpStatus = (notFound, response) => {
532
570
  if (notFound) return {
@@ -653,6 +691,32 @@ var useQwikRouter = (props) => {
653
691
  return;
654
692
  }
655
693
  if (path === RUN_PENDING_ACTION) return loadNavigation(ensureRouteInternal(routeInternal, routeLocation), actionState.value, getRouterContainer());
694
+ return prepareNavigation(path, opt).started.then((started) => started.finished);
695
+ };
696
+ const prepareNavigation = (path, opt) => {
697
+ let resolvePreparation;
698
+ let rejectPreparation;
699
+ const prepared = new Promise((resolve, reject) => {
700
+ resolvePreparation = resolve;
701
+ rejectPreparation = reject;
702
+ });
703
+ prepared.catch(() => {});
704
+ const preparation = {
705
+ promise: prepared,
706
+ resolve: resolvePreparation
707
+ };
708
+ const started = beginNavigation(path, opt, preparation);
709
+ started.then(async (result) => {
710
+ if (result.type !== NavigationStartType.Duplicate && navResolver.preparation !== preparation && preparation.navCount !== internalState.navCount || result.type === NavigationStartType.Superseded || result.type === NavigationStartType.External) return;
711
+ await navResolver.routePreparation?.started;
712
+ if (getClientRouteLoaders(routeLoaderCtx).navCount === internalState.navCount) resolvePreparation();
713
+ }, rejectPreparation).catch(rejectPreparation);
714
+ return {
715
+ prepared,
716
+ started
717
+ };
718
+ };
719
+ const beginNavigation = async (path, opt, preparation) => {
656
720
  const { type = "link", forceReload = path === void 0, replaceState = false, scroll = true } = typeof opt === "object" ? opt : { forceReload: opt };
657
721
  const current = ensureRouteInternal(routeInternal, routeLocation);
658
722
  if (isBrowser && type === "link" && current.type === "initial") {
@@ -662,24 +726,31 @@ var useQwikRouter = (props) => {
662
726
  }
663
727
  const lastDest = current.dest;
664
728
  const dest = path === void 0 ? lastDest : typeof path === "number" ? path : toUrl(path, routeLocation.url);
665
- if (navResolver.p && !forceReload && typeof dest !== "number" && isSamePath(dest, lastDest) && dest.href === lastDest.href) return navResolver.p;
729
+ if (navResolver.p && !forceReload && typeof dest !== "number" && isSamePath(dest, lastDest) && dest.href === lastDest.href) return {
730
+ type: NavigationStartType.Duplicate,
731
+ finished: navResolver.p
732
+ };
733
+ const previousPreparation = navResolver.preparation;
734
+ navResolver.preparation = preparation;
735
+ if (previousPreparation?.navCount === void 0) previousPreparation?.resolve(preparation.promise);
666
736
  const attemptCount = ++internalState.attemptCount;
667
737
  if (preventNav.$cbs$ && (forceReload || typeof dest === "number" || !isSamePath(dest, lastDest) || !isSameOrigin(dest, lastDest))) {
668
738
  const prevents = await Promise.all([...preventNav.$cbs$.values()].map((cb) => cb(dest)));
669
- if (attemptCount !== internalState.attemptCount || prevents.some(Boolean)) {
670
- if (attemptCount === internalState.attemptCount && type === "popstate") history.pushState(null, "", lastDest);
671
- return;
739
+ if (attemptCount !== internalState.attemptCount) return { type: NavigationStartType.Superseded };
740
+ if (prevents.some(Boolean)) {
741
+ if (type === "popstate") history.pushState(null, "", lastDest);
742
+ return { type: NavigationStartType.Unchanged };
672
743
  }
673
744
  }
674
745
  if (typeof dest === "number") {
675
746
  if (isBrowser) history.go(dest);
676
- return;
747
+ return { type: NavigationStartType.External };
677
748
  }
678
749
  if (!isSameOrigin(dest, lastDest)) {
679
750
  if (isBrowser) location.href = dest.href;
680
- return;
751
+ return { type: NavigationStartType.External };
681
752
  }
682
- if (!forceReload && isSamePath(dest, lastDest)) {
753
+ if (!forceReload && isSamePath(dest, lastDest) && (!navResolver.dest || isSamePath(navResolver.dest, dest) && navResolver.dest.href === dest.href)) {
683
754
  if (isBrowser) {
684
755
  if (type === "link" && dest.href !== location.href) history.pushState(null, "", dest);
685
756
  const scroller = getScroller();
@@ -693,13 +764,34 @@ var useQwikRouter = (props) => {
693
764
  const contentModules = contentInternal.untrackedValue;
694
765
  if (contentModules) updateHead(contentModules, actionDataSignal.untrackedValue, internalState.navCount);
695
766
  }
696
- return navResolver.p;
767
+ return {
768
+ type: NavigationStartType.Unchanged,
769
+ finished: navResolver.p
770
+ };
697
771
  }
698
772
  const navCount = ++internalState.navCount;
773
+ preparation.navCount = navCount;
774
+ navResolver.routePreparation?.preparation.resolve(preparation.promise);
699
775
  internalState.currentTransition?.skipTransition();
700
776
  navResolver.cancel?.();
701
777
  navResolver.cancel = void 0;
702
778
  navResolver.r?.();
779
+ navResolver.dest = dest;
780
+ const preparing = preparePageNavigation({
781
+ type,
782
+ dest,
783
+ forceReload,
784
+ replaceState,
785
+ scroll
786
+ }, navCount);
787
+ navResolver.routePreparation = {
788
+ started: preparing,
789
+ preparation
790
+ };
791
+ return preparing;
792
+ };
793
+ const preparePageNavigation = async (navigation, navCount) => {
794
+ const { type, dest, forceReload, replaceState } = navigation;
703
795
  let historyUpdated = false;
704
796
  if (isBrowser) getClientRouteLoaders(routeLoaderCtx, routeLocation.url.href);
705
797
  if (isBrowser && type === "link" && !forceReload) {
@@ -715,18 +807,12 @@ var useQwikRouter = (props) => {
715
807
  const container = isBrowser ? _getContextContainer() : void 0;
716
808
  if (container && !wasNavigating) {
717
809
  await _waitUntilRendered(container);
718
- if (navCount !== internalState.navCount) return;
810
+ if (navCount !== internalState.navCount) return { type: NavigationStartType.Superseded };
719
811
  }
720
812
  actionState.value = void 0;
721
- const navigation = {
722
- type,
723
- dest,
724
- forceReload,
725
- replaceState,
726
- scroll,
727
- historyUpdated
728
- };
813
+ navigation.historyUpdated = historyUpdated;
729
814
  routeInternal.value = navigation;
815
+ navResolver.dest = void 0;
730
816
  if (wasNavigating) abortRouteLoaderNavigation(routeLoaderCtx);
731
817
  if (isBrowser) prefetchRoute(dest, false, .8, manifestHash, true);
732
818
  navResolver.p = new Promise((resolve) => {
@@ -737,8 +823,11 @@ var useQwikRouter = (props) => {
737
823
  };
738
824
  });
739
825
  const navigated = navResolver.p;
740
- loadNavigation(navigation, void 0, container ?? getRouterContainer());
741
- return navigated;
826
+ await loadNavigation(navigation, void 0, container ?? getRouterContainer());
827
+ return {
828
+ type: NavigationStartType.Prepared,
829
+ finished: navigated
830
+ };
742
831
  };
743
832
  const loadNavigation = async (navigation, action, container) => {
744
833
  action?.resolveDispatch?.();
@@ -754,6 +843,13 @@ var useQwikRouter = (props) => {
754
843
  const canceled = new Promise((resolve) => {
755
844
  navResolver.cancel = () => resolve(void 0);
756
845
  });
846
+ const abandonAction = () => {
847
+ action?.reject?.(/* @__PURE__ */ new Error("Action submission was superseded by a navigation"));
848
+ if (action) {
849
+ action.resolve = void 0;
850
+ action.reject = void 0;
851
+ }
852
+ };
757
853
  if (trackUrl.pathname.endsWith("/")) {
758
854
  if (globalThis.__NO_TRAILING_SLASH__) trackUrl.pathname = trackUrl.pathname.slice(0, -1);
759
855
  } else if (!globalThis.__NO_TRAILING_SLASH__) trackUrl.pathname = ensureSlash(trackUrl.pathname);
@@ -763,27 +859,72 @@ var useQwikRouter = (props) => {
763
859
  });
764
860
  try {
765
861
  const route = await Promise.race([loadRoutePromise, canceled]);
766
- if (!route) return;
862
+ if (!route) {
863
+ abandonAction();
864
+ return;
865
+ }
767
866
  loadedRoute = route;
768
867
  } catch (e) {
769
- if (internalState.navCount !== navCountBefore) return;
868
+ if (internalState.navCount !== navCountBefore) {
869
+ abandonAction();
870
+ return;
871
+ }
770
872
  const preparedNavCount = getClientRouteLoaders(routeLoaderCtx).navCount;
771
873
  if (preparedNavCount !== void 0) restoreRouteLoaders(loaderState, routeLoaderCtx, preparedNavCount);
772
874
  console.error(`Could not load route ${trackUrl.pathname}, reloading:`, e);
773
875
  window.location.href = trackUrl.href;
774
876
  return;
775
877
  }
776
- if (internalState.navCount !== navCountBefore) return;
878
+ if (internalState.navCount !== navCountBefore) {
879
+ abandonAction();
880
+ return;
881
+ }
882
+ let rewrittenTo;
883
+ const lastModule = loadedRoute.$mods$[loadedRoute.$mods$.length - 1];
884
+ if (loadedRoute.$notFound$ || typeof lastModule?.default !== "function" || loadedRoute.$routeName$.includes("[")) {
885
+ const resolved = await Promise.race([resolveServerRewrite(trackUrl), canceled]);
886
+ if (internalState.navCount !== navCountBefore) {
887
+ abandonAction();
888
+ return;
889
+ }
890
+ if (resolved === "reload") {
891
+ if (!action) {
892
+ window.location.href = trackUrl.href;
893
+ return;
894
+ }
895
+ } else if (resolved && resolved !== trackUrl.pathname) {
896
+ try {
897
+ const config = await getRouterConfig();
898
+ loadedRoute = await loadRoute(config.routes, config.cacheModules, resolved);
899
+ rewrittenTo = resolved;
900
+ } catch (e) {
901
+ if (internalState.navCount !== navCountBefore) {
902
+ abandonAction();
903
+ return;
904
+ }
905
+ console.error(`Could not load rewritten route ${resolved}, reloading:`, e);
906
+ window.location.href = trackUrl.href;
907
+ return;
908
+ }
909
+ if (internalState.navCount !== navCountBefore) {
910
+ abandonAction();
911
+ return;
912
+ }
913
+ }
914
+ }
777
915
  if (action) {
778
916
  const result = await Promise.race([submitAction(action, trackUrl).then((result) => {
779
- if (result && action.resolve) {
780
- action.resolve({
781
- status: result.status,
782
- result: result.result
783
- });
784
- action.resolve = void 0;
785
- }
917
+ action.resolve?.({
918
+ status: result.status,
919
+ result: result.result
920
+ });
921
+ action.resolve = void 0;
922
+ action.reject = void 0;
786
923
  return result;
924
+ }, (error) => {
925
+ action.reject?.(error);
926
+ action.reject = void 0;
927
+ action.resolve = void 0;
787
928
  }), canceled]);
788
929
  if (internalState.navCount !== navCountBefore || action !== actionState.untrackedValue) return;
789
930
  navResolver.cancel = void 0;
@@ -792,11 +933,14 @@ var useQwikRouter = (props) => {
792
933
  type: navType,
793
934
  dest: trackUrl
794
935
  };
936
+ routeLocation.isNavigating = false;
937
+ navResolver.r?.();
795
938
  return;
796
939
  }
797
940
  if (result.redirect) {
798
- if (result.redirect instanceof URL) location.href = result.redirect.href;
799
- else startNavigation(result.redirect, { replaceState: true });
941
+ const redirectUrl = toSafeRedirectUrl(result.redirect, routeLocation.url);
942
+ if (result.redirect instanceof URL) location.href = redirectUrl.href;
943
+ else startNavigation(redirectUrl, { replaceState: true });
800
944
  return;
801
945
  }
802
946
  actionData = {
@@ -809,8 +953,8 @@ var useQwikRouter = (props) => {
809
953
  navResolver.cancel = void 0;
810
954
  const { $routeName$, $params$, $mods$, $menu$, $notFound$ } = loadedRoute;
811
955
  const contentModules = $mods$;
812
- routeLoaderCtx.goto = noSerialize(startNavigation);
813
- const routeLoaders = prepareRouteLoaders(contentModules, loaderState, routeLoaderCtx, loadedRoute.$loaderPaths$, trackUrl, prevUrl, navCountBefore, action ? actionLoaderHashes ?? null : void 0, action ?? navigation);
956
+ routeLoaderCtx.goto = noSerialize((path, opt) => prepareNavigation(path, opt).prepared);
957
+ const routeLoaders = prepareRouteLoaders(contentModules, loaderState, routeLoaderCtx, rewrittenTo ? void 0 : loadedRoute.$loaderPaths$, trackUrl, prevUrl, navCountBefore, action ? actionLoaderHashes ?? null : void 0, action ?? navigation);
814
958
  await whenReady(() => {
815
959
  for (let i = 0; i < routeLoaders.length; i++) {
816
960
  const loader = routeLoaders[i];
@@ -958,6 +1102,7 @@ var useQwikRouter = (props) => {
958
1102
  });
959
1103
  });
960
1104
  };
1105
+ if (isBrowser && !window._qRouterSPA) window._qRouterInitNavigate = startNavigation;
961
1106
  return startNavigation(path, opt);
962
1107
  }, "useQwikRouter_goto_8j8Vrz2yUIM", [
963
1108
  actionDataSignal,
@@ -1001,6 +1146,7 @@ function initializeSPA(goto, scroller) {
1001
1146
  });
1002
1147
  window.removeEventListener("popstate", window._qRouterInitPopstate);
1003
1148
  window._qRouterInitPopstate = void 0;
1149
+ window._qRouterInitNavigate = void 0;
1004
1150
  if (!window._qRouterHistoryPatch) {
1005
1151
  window._qRouterHistoryPatch = true;
1006
1152
  const pushState = history.pushState;
@@ -1024,7 +1170,7 @@ function initializeSPA(goto, scroller) {
1024
1170
  };
1025
1171
  }
1026
1172
  document.addEventListener("click", (event) => {
1027
- if (event.defaultPrevented) return;
1173
+ if (event.defaultPrevented || !isPlainPrimaryClick(event)) return;
1028
1174
  const target = event.target.closest("a[href]");
1029
1175
  if (target && !target.hasAttribute("preventdefault:click")) {
1030
1176
  const href = target.getAttribute("href");
@@ -1222,34 +1368,33 @@ Action.run() can only be called on the browser, for example when a user clicks a
1222
1368
  let form;
1223
1369
  if (input instanceof SubmitEvent) {
1224
1370
  form = input.target;
1225
- data = new FormData(form);
1226
- if ((input.submitter instanceof HTMLInputElement || input.submitter instanceof HTMLButtonElement) && input.submitter.name) {
1227
- if (input.submitter.name) data.append(input.submitter.name, input.submitter.value);
1228
- }
1371
+ data = new FormData(form, input.submitter);
1229
1372
  } else data = input;
1230
1373
  const submission = {};
1231
1374
  latestSubmission.current = submission;
1375
+ state.isRunning = true;
1232
1376
  const previousDispatch = currentAction.pendingDispatch ?? Promise.resolve();
1233
1377
  let resolveDispatch;
1234
1378
  currentAction.pendingDispatch = noSerialize(new Promise((resolve) => {
1235
1379
  resolveDispatch = resolve;
1236
1380
  }));
1237
- return previousDispatch.then(() => new Promise((resolve) => {
1381
+ return previousDispatch.then(() => new Promise((resolve, reject) => {
1238
1382
  if (data instanceof FormData) state.formData = data;
1239
1383
  state.submitted = true;
1240
- state.isRunning = true;
1241
1384
  loc.isNavigating = true;
1242
1385
  currentAction.value = {
1243
1386
  data,
1244
1387
  id,
1245
1388
  resolve: noSerialize(resolve),
1389
+ reject: noSerialize(reject),
1246
1390
  resolveDispatch: noSerialize(resolveDispatch)
1247
1391
  };
1248
1392
  runAction?.(RUN_PENDING_ACTION);
1249
- })).then(({ result, status }) => {
1393
+ })).finally(() => {
1394
+ if (latestSubmission.current === submission) state.isRunning = false;
1395
+ }).then(({ result, status }) => {
1250
1396
  const isLatestSubmission = latestSubmission.current === submission;
1251
1397
  if (isLatestSubmission) {
1252
- state.isRunning = false;
1253
1398
  state.status = status;
1254
1399
  state.value = result;
1255
1400
  }
@@ -1456,29 +1601,7 @@ function serverQrl(qrl, options) {
1456
1601
  const body = await _serialize(toSend);
1457
1602
  if (method === "GET") query += `&${QDATA_KEY}=${encodeURIComponent(body)}`;
1458
1603
  else config.body = body;
1459
- const res = await fetch(`${origin}?${QFN_KEY}=${qrlHash}${query}`, config);
1460
- const contentType = res.headers.get("Content-Type");
1461
- if (res.ok && contentType === "text/qwik-json-stream" && res.body) return (async function* () {
1462
- try {
1463
- for await (const result of deserializeStream(res.body, abortSignal)) yield result;
1464
- } finally {
1465
- if (!abortSignal?.aborted) await res.body.cancel();
1466
- }
1467
- })();
1468
- else if (contentType === "application/qwik-json") {
1469
- const str = await res.text();
1470
- const obj = await _deserialize(str);
1471
- if (res.status >= 400) throw obj;
1472
- return obj;
1473
- } else if (contentType === "application/json") {
1474
- const obj = await res.json();
1475
- if (res.status >= 400) throw obj;
1476
- return obj;
1477
- } else if (contentType === "text/plain" || contentType === "text/html") {
1478
- const str = await res.text();
1479
- if (res.status >= 400) throw str;
1480
- return str;
1481
- }
1604
+ return readServerFunctionResponse(await fetch(`${origin}?${QFN_KEY}=${qrlHash}${query}`, config), abortSignal);
1482
1605
  }
1483
1606
  }, "serverQrl_w03grD0Ag68", [
1484
1607
  fetchOptions,
@@ -1488,6 +1611,32 @@ function serverQrl(qrl, options) {
1488
1611
  qrl
1489
1612
  ]);
1490
1613
  }
1614
+ /** @internal Exported for tests */
1615
+ async function readServerFunctionResponse(res, abortSignal) {
1616
+ const contentType = res.headers.get("Content-Type")?.split(";")[0].trim().toLowerCase();
1617
+ if (res.ok && contentType === "text/qwik-json-stream" && res.body) return (async function* () {
1618
+ try {
1619
+ for await (const result of deserializeStream(res.body, abortSignal)) yield result;
1620
+ } finally {
1621
+ if (!abortSignal?.aborted) await res.body.cancel();
1622
+ }
1623
+ })();
1624
+ else if (contentType === "application/qwik-json") {
1625
+ const str = await res.text();
1626
+ const obj = await _deserialize(str);
1627
+ if (res.status >= 400) throw obj;
1628
+ return obj;
1629
+ } else if (contentType === "application/json") {
1630
+ const obj = await res.json();
1631
+ if (res.status >= 400) throw obj;
1632
+ return obj;
1633
+ } else if (contentType === "text/plain") {
1634
+ const str = await res.text();
1635
+ if (res.status >= 400) throw str;
1636
+ return str;
1637
+ }
1638
+ throw new Error(`server$ got an unexpected response: ${res.status} ${res.headers.get("Content-Type") ?? "(no Content-Type)"}`);
1639
+ }
1491
1640
  /** @public */
1492
1641
  var server$ = /*#__PURE__*/ implicit$FirstArg(serverQrl);
1493
1642
  function getValidators(rest, qrl) {
@@ -1555,37 +1704,46 @@ var ServiceWorkerRegister = (props) => /*#__PURE__*/ _jsxSorted("script", {
1555
1704
  dangerouslySetInnerHTML: _getServiceWorkerScript(_getServiceWorkerUrl()),
1556
1705
  nonce: _wrapProp(props, "nonce")
1557
1706
  }, { type: "module" }, null, 3, "UM_0");
1558
- var _hf0 = (p0) => p0.spaReset ? "true" : void 0;
1559
- var _hf0_str = "p0.spaReset?\"true\":undefined";
1707
+ var _hf0$1 = (p0) => p0.spaReset ? "true" : void 0;
1708
+ var _hf0_str$1 = "p0.spaReset?\"true\":undefined";
1560
1709
  /** @public */
1561
1710
  var Form = ({ action, spaReset, reloadDocument, onSubmit$, ...rest }, key) => {
1562
1711
  if (action) {
1563
- if (Array.isArray(onSubmit$)) return /*#__PURE__*/ _jsxSplit("form", {
1564
- ..._getVarProps(rest),
1565
- ..._getConstProps(rest),
1566
- action: _wrapProp(action, "actionPath"),
1567
- "preventdefault:submit": !reloadDocument,
1568
- "q-e:submit": [...onSubmit$, !reloadDocument ? /*#__PURE__*/ inlinedQrl((evt) => {
1569
- let action = _capturesObj._[0];
1570
- if (!action.submitted) return action.submit(evt);
1571
- }, "Form_form_q_e_submit_6i0Jq5q8JFg", [action]) : void 0],
1572
- ["data-spa-reset"]: spaReset ? "true" : void 0
1573
- }, { method: "post" }, null, 0, key);
1712
+ const submitHandlers = [onSubmit$].flat(Infinity);
1713
+ const firstAsyncHandler = submitHandlers.findIndex((handler) => handler && !_isSyncQrl(handler));
1714
+ const syncHandlers = firstAsyncHandler === -1 ? submitHandlers : submitHandlers.slice(0, firstAsyncHandler);
1715
+ const asyncHandlers = firstAsyncHandler === -1 ? [] : submitHandlers.slice(firstAsyncHandler);
1574
1716
  return /*#__PURE__*/ _jsxSplit("form", {
1575
1717
  ..._getVarProps(rest),
1576
1718
  ..._getConstProps(rest),
1577
1719
  action: _wrapProp(action, "actionPath"),
1578
1720
  "preventdefault:submit": !reloadDocument,
1579
- "q-e:submit": [onSubmit$, !reloadDocument ? action.submit : void 0],
1721
+ "q-e:submit": [
1722
+ !reloadDocument ? _qrlSync((event, form) => {
1723
+ form._qSubmit ??= event;
1724
+ }, "(event,form)=>{form._qSubmit??=event;}") : void 0,
1725
+ ...!reloadDocument ? syncHandlers : [],
1726
+ !reloadDocument ? /*#__PURE__*/ inlinedQrl(async (event, form) => {
1727
+ let action = _capturesObj._[0], asyncHandlers = _capturesObj._[1];
1728
+ if (form._qSubmit !== event) return;
1729
+ try {
1730
+ for (const handler of asyncHandlers) await handler?.(event, form);
1731
+ await action.submit(event);
1732
+ } finally {
1733
+ delete form._qSubmit;
1734
+ }
1735
+ }, "Form_form_q_e_submit_6i0Jq5q8JFg", [action, asyncHandlers]) : onSubmit$,
1736
+ !reloadDocument ? _qrlSync((event, form) => {
1737
+ if (form._qSubmit === event) delete form._qSubmit;
1738
+ }, "(event,form)=>{if(form._qSubmit===event){delete form._qSubmit;}}") : void 0
1739
+ ],
1580
1740
  ["data-spa-reset"]: spaReset ? "true" : void 0
1581
1741
  }, { method: "post" }, null, 0, key);
1582
- } else return /*#__PURE__*/ createElement(GetForm, {
1583
- ...rest,
1742
+ } else return /*#__PURE__*/ _jsxSplit(GetForm, {
1584
1743
  spaReset,
1585
1744
  reloadDocument,
1586
- onSubmit$,
1587
- key
1588
- });
1745
+ ...rest
1746
+ }, { onSubmit$ }, null, 0, key);
1589
1747
  };
1590
1748
  var GetForm = /*#__PURE__*/ componentQrl(/*#__PURE__*/ inlinedQrl((_rawProps) => {
1591
1749
  const rest = _restProps(_rawProps, [
@@ -1597,7 +1755,7 @@ var GetForm = /*#__PURE__*/ componentQrl(/*#__PURE__*/ inlinedQrl((_rawProps) =>
1597
1755
  const nav = useNavigate();
1598
1756
  return /*#__PURE__*/ _jsxSplit("form", {
1599
1757
  action: "get",
1600
- "data-spa-reset": _fnSignal(_hf0, [_rawProps], _hf0_str),
1758
+ "data-spa-reset": _fnSignal(_hf0$1, [_rawProps], _hf0_str$1),
1601
1759
  ..._getVarProps(rest),
1602
1760
  "q-e:submit": [
1603
1761
  ...Array.isArray(_rawProps.onSubmit$) ? _rawProps.onSubmit$ : [_rawProps.onSubmit$],
@@ -1704,6 +1862,8 @@ var createRenderer = (getOptions) => {
1704
1862
  return renderToStream(jsx, renderOptions);
1705
1863
  });
1706
1864
  };
1865
+ var _hf0 = (p0, p1) => p1 || p0.dangerouslySetInnerHTML;
1866
+ var _hf0_str = "p1||p0.dangerouslySetInnerHTML";
1707
1867
  var trackWholeStore = (store) => {
1708
1868
  Object.keys(store);
1709
1869
  return untrack(() => ({ ...store }));
@@ -1744,20 +1904,22 @@ var DocumentHeadTags = /*#__PURE__*/ componentQrl(/*#__PURE__*/ inlinedQrl((prop
1744
1904
  head.meta.map((m) => /*#__PURE__*/ _jsxSplit("meta", { ..._getVarProps(m) }, _getConstProps(m), null, 0, "eL_1")),
1745
1905
  head.links.map((l) => /*#__PURE__*/ _jsxSplit("link", { ..._getVarProps(l) }, _getConstProps(l), null, 0, "eL_2")),
1746
1906
  head.styles.map((s) => {
1747
- const props = s.props || s;
1748
- return /*#__PURE__*/ createElement("style", {
1749
- ...props,
1750
- dangerouslySetInnerHTML: s.style || props.dangerouslySetInnerHTML,
1751
- key: s.key
1752
- });
1907
+ const { style, key, props: oldProps, ...rest } = trackWholeStore(s);
1908
+ const props = oldProps || rest;
1909
+ return /*#__PURE__*/ _jsxSplit("style", {
1910
+ ..._getVarProps(props),
1911
+ ..._getConstProps(props),
1912
+ dangerouslySetInnerHTML: _fnSignal(_hf0, [props, style], _hf0_str)
1913
+ }, null, null, 0, key);
1753
1914
  }),
1754
1915
  head.scripts.map((s) => {
1755
- const props = s.props || s;
1756
- return /*#__PURE__*/ createElement("script", {
1757
- ...props,
1758
- dangerouslySetInnerHTML: s.script || props.dangerouslySetInnerHTML,
1759
- key: s.key
1760
- });
1916
+ const { script, key, props: oldProps, ...rest } = trackWholeStore(s);
1917
+ const props = oldProps || rest;
1918
+ return /*#__PURE__*/ _jsxSplit("script", {
1919
+ ..._getVarProps(props),
1920
+ ..._getConstProps(props),
1921
+ dangerouslySetInnerHTML: _fnSignal(_hf0, [props, script], _hf0_str)
1922
+ }, null, null, 0, key);
1761
1923
  })
1762
1924
  ], 1, "eL_3");
1763
1925
  }, "DocumentHeadTags_component_9CrWYOoCpgY"));