@qwik.dev/router 2.0.0-beta.11 → 2.0.0-beta.14

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 (132) hide show
  1. package/lib/adapters/azure-swa/vite/index.mjs +28 -207
  2. package/lib/adapters/bun-server/vite/index.mjs +16 -202
  3. package/lib/adapters/cloud-run/vite/index.mjs +15 -201
  4. package/lib/adapters/cloudflare-pages/vite/index.mjs +65 -6
  5. package/lib/adapters/deno-server/vite/index.mjs +18 -204
  6. package/lib/adapters/netlify-edge/vite/index.mjs +58 -246
  7. package/lib/adapters/node-server/vite/index.mjs +16 -202
  8. package/lib/adapters/shared/vite/index.d.ts +4 -4
  9. package/lib/adapters/shared/vite/index.mjs +250 -149
  10. package/lib/adapters/ssg/vite/index.mjs +12 -199
  11. package/lib/adapters/vercel-edge/vite/index.d.ts +1 -1
  12. package/lib/adapters/vercel-edge/vite/index.mjs +50 -235
  13. package/lib/chunks/error-handler.mjs +57 -0
  14. package/lib/chunks/format-error.mjs +137 -0
  15. package/lib/chunks/fs.mjs +254 -0
  16. package/lib/chunks/index.mjs +884 -0
  17. package/lib/chunks/mime-types.mjs +52 -0
  18. package/lib/chunks/routing.qwik.mjs +429 -0
  19. package/lib/chunks/types.qwik.mjs +22 -0
  20. package/lib/index.d.ts +11 -4
  21. package/lib/index.qwik.mjs +533 -1019
  22. package/lib/middleware/aws-lambda/index.mjs +38 -28
  23. package/lib/middleware/azure-swa/index.mjs +65 -48
  24. package/lib/middleware/bun/index.mjs +104 -119
  25. package/lib/middleware/cloudflare-pages/index.mjs +69 -49
  26. package/lib/middleware/deno/index.mjs +94 -114
  27. package/lib/middleware/firebase/index.mjs +26 -18
  28. package/lib/middleware/netlify-edge/index.mjs +53 -38
  29. package/lib/middleware/node/index.mjs +184 -167
  30. package/lib/middleware/request-handler/index.d.ts +22 -4
  31. package/lib/middleware/request-handler/index.mjs +1203 -877
  32. package/lib/middleware/vercel-edge/index.mjs +72 -49
  33. package/lib/service-worker/index.mjs +4 -0
  34. package/lib/ssg/index.mjs +14 -22
  35. package/lib/vite/index.d.ts +13 -7
  36. package/lib/vite/index.mjs +1609 -1217
  37. package/package.json +27 -44
  38. package/lib/adapters/azure-swa/vite/index-BqUeglYs.cjs +0 -1
  39. package/lib/adapters/azure-swa/vite/index-CBIchDYq.js +0 -651
  40. package/lib/adapters/azure-swa/vite/index-ClHGw5z1.js +0 -6
  41. package/lib/adapters/azure-swa/vite/index-CrwlB95_.js +0 -22
  42. package/lib/adapters/azure-swa/vite/index-DTIOTwZo.cjs +0 -11
  43. package/lib/adapters/azure-swa/vite/index-vQuPcef3.cjs +0 -1
  44. package/lib/adapters/azure-swa/vite/index.cjs +0 -5
  45. package/lib/adapters/bun-server/vite/index-BqUeglYs.cjs +0 -1
  46. package/lib/adapters/bun-server/vite/index-CBIchDYq.js +0 -651
  47. package/lib/adapters/bun-server/vite/index-ClHGw5z1.js +0 -6
  48. package/lib/adapters/bun-server/vite/index-CrwlB95_.js +0 -22
  49. package/lib/adapters/bun-server/vite/index-DTIOTwZo.cjs +0 -11
  50. package/lib/adapters/bun-server/vite/index-vQuPcef3.cjs +0 -1
  51. package/lib/adapters/bun-server/vite/index.cjs +0 -5
  52. package/lib/adapters/cloud-run/vite/index-BqUeglYs.cjs +0 -1
  53. package/lib/adapters/cloud-run/vite/index-CBIchDYq.js +0 -651
  54. package/lib/adapters/cloud-run/vite/index-ClHGw5z1.js +0 -6
  55. package/lib/adapters/cloud-run/vite/index-CrwlB95_.js +0 -22
  56. package/lib/adapters/cloud-run/vite/index-DTIOTwZo.cjs +0 -11
  57. package/lib/adapters/cloud-run/vite/index-vQuPcef3.cjs +0 -1
  58. package/lib/adapters/cloud-run/vite/index.cjs +0 -5
  59. package/lib/adapters/cloudflare-pages/vite/index-Bg_9YkM5.js +0 -22
  60. package/lib/adapters/cloudflare-pages/vite/index-C1aDmh1S.cjs +0 -1
  61. package/lib/adapters/cloudflare-pages/vite/index-CHT9Y93A.js +0 -254
  62. package/lib/adapters/cloudflare-pages/vite/index-Ck7KvpK1.cjs +0 -11
  63. package/lib/adapters/cloudflare-pages/vite/index-ClHGw5z1.js +0 -6
  64. package/lib/adapters/cloudflare-pages/vite/index-Cp1cjAds.js +0 -645
  65. package/lib/adapters/cloudflare-pages/vite/index-D9RL9dvJ.cjs +0 -5
  66. package/lib/adapters/cloudflare-pages/vite/index-vQuPcef3.cjs +0 -1
  67. package/lib/adapters/cloudflare-pages/vite/index.cjs +0 -1
  68. package/lib/adapters/deno-server/vite/index-BqUeglYs.cjs +0 -1
  69. package/lib/adapters/deno-server/vite/index-CBIchDYq.js +0 -651
  70. package/lib/adapters/deno-server/vite/index-ClHGw5z1.js +0 -6
  71. package/lib/adapters/deno-server/vite/index-CrwlB95_.js +0 -22
  72. package/lib/adapters/deno-server/vite/index-DTIOTwZo.cjs +0 -11
  73. package/lib/adapters/deno-server/vite/index-vQuPcef3.cjs +0 -1
  74. package/lib/adapters/deno-server/vite/index.cjs +0 -5
  75. package/lib/adapters/netlify-edge/vite/index-BqUeglYs.cjs +0 -1
  76. package/lib/adapters/netlify-edge/vite/index-CBIchDYq.js +0 -651
  77. package/lib/adapters/netlify-edge/vite/index-ClHGw5z1.js +0 -6
  78. package/lib/adapters/netlify-edge/vite/index-CrwlB95_.js +0 -22
  79. package/lib/adapters/netlify-edge/vite/index-DTIOTwZo.cjs +0 -11
  80. package/lib/adapters/netlify-edge/vite/index-vQuPcef3.cjs +0 -1
  81. package/lib/adapters/netlify-edge/vite/index.cjs +0 -6
  82. package/lib/adapters/node-server/vite/index-BqUeglYs.cjs +0 -1
  83. package/lib/adapters/node-server/vite/index-CBIchDYq.js +0 -651
  84. package/lib/adapters/node-server/vite/index-ClHGw5z1.js +0 -6
  85. package/lib/adapters/node-server/vite/index-CrwlB95_.js +0 -22
  86. package/lib/adapters/node-server/vite/index-DTIOTwZo.cjs +0 -11
  87. package/lib/adapters/node-server/vite/index-vQuPcef3.cjs +0 -1
  88. package/lib/adapters/node-server/vite/index.cjs +0 -5
  89. package/lib/adapters/shared/vite/index-BqUeglYs.cjs +0 -1
  90. package/lib/adapters/shared/vite/index-CBIchDYq.js +0 -651
  91. package/lib/adapters/shared/vite/index-ClHGw5z1.js +0 -6
  92. package/lib/adapters/shared/vite/index-CrwlB95_.js +0 -22
  93. package/lib/adapters/shared/vite/index-DTIOTwZo.cjs +0 -11
  94. package/lib/adapters/shared/vite/index-vQuPcef3.cjs +0 -1
  95. package/lib/adapters/shared/vite/index.cjs +0 -5
  96. package/lib/adapters/ssg/vite/index-BqUeglYs.cjs +0 -1
  97. package/lib/adapters/ssg/vite/index-CBIchDYq.js +0 -651
  98. package/lib/adapters/ssg/vite/index-ClHGw5z1.js +0 -6
  99. package/lib/adapters/ssg/vite/index-CrwlB95_.js +0 -22
  100. package/lib/adapters/ssg/vite/index-DTIOTwZo.cjs +0 -11
  101. package/lib/adapters/ssg/vite/index-vQuPcef3.cjs +0 -1
  102. package/lib/adapters/ssg/vite/index.cjs +0 -5
  103. package/lib/adapters/vercel-edge/vite/index-BqUeglYs.cjs +0 -1
  104. package/lib/adapters/vercel-edge/vite/index-CBIchDYq.js +0 -651
  105. package/lib/adapters/vercel-edge/vite/index-ClHGw5z1.js +0 -6
  106. package/lib/adapters/vercel-edge/vite/index-CrwlB95_.js +0 -22
  107. package/lib/adapters/vercel-edge/vite/index-DTIOTwZo.cjs +0 -11
  108. package/lib/adapters/vercel-edge/vite/index-vQuPcef3.cjs +0 -1
  109. package/lib/adapters/vercel-edge/vite/index.cjs +0 -5
  110. package/lib/index.qwik.cjs +0 -2126
  111. package/lib/middleware/aws-lambda/index.cjs +0 -1
  112. package/lib/middleware/azure-swa/index.cjs +0 -1
  113. package/lib/middleware/bun/index.cjs +0 -1
  114. package/lib/middleware/cloudflare-pages/index.cjs +0 -1
  115. package/lib/middleware/deno/index.cjs +0 -1
  116. package/lib/middleware/firebase/index.cjs +0 -1
  117. package/lib/middleware/netlify-edge/index.cjs +0 -1
  118. package/lib/middleware/node/index.cjs +0 -1
  119. package/lib/middleware/request-handler/index.cjs +0 -18
  120. package/lib/middleware/vercel-edge/index.cjs +0 -1
  121. package/lib/service-worker.cjs +0 -1
  122. package/lib/service-worker.mjs +0 -5
  123. package/lib/ssg/deno.cjs +0 -1
  124. package/lib/ssg/deno.mjs +0 -6
  125. package/lib/ssg/index-CBIchDYq.js +0 -651
  126. package/lib/ssg/index-ClHGw5z1.js +0 -6
  127. package/lib/ssg/index-DTIOTwZo.cjs +0 -11
  128. package/lib/ssg/index-vQuPcef3.cjs +0 -1
  129. package/lib/ssg/index.cjs +0 -1
  130. package/lib/ssg/node.cjs +0 -11
  131. package/lib/ssg/node.mjs +0 -651
  132. package/lib/vite/index.cjs +0 -42
@@ -1,2126 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- const jsxRuntime = require("@qwik.dev/core/jsx-runtime");
4
- const core = require("@qwik.dev/core");
5
- const preloader = require("@qwik.dev/core/preloader");
6
- const internal = require("@qwik.dev/core/internal");
7
- const qwikRouterConfig = require("@qwik-router-config");
8
- const zod = require("zod");
9
- const swRegister = require("@qwik-router-sw-register");
10
- const server = require("@qwik.dev/core/server");
11
- function _interopNamespaceDefault(e) {
12
- const n = Object.create(null, { [Symbol.toStringTag]: { value: "Module" } });
13
- if (e) {
14
- for (const k in e) {
15
- if (k !== "default") {
16
- const d = Object.getOwnPropertyDescriptor(e, k);
17
- Object.defineProperty(n, k, d.get ? d : {
18
- enumerable: true,
19
- get: () => e[k]
20
- });
21
- }
22
- }
23
- }
24
- n.default = e;
25
- return Object.freeze(n);
26
- }
27
- const qwikRouterConfig__namespace = /* @__PURE__ */ _interopNamespaceDefault(qwikRouterConfig);
28
- const ErrorBoundary = core.component$((props) => {
29
- const store2 = core.useErrorBoundary();
30
- core.useOnWindow("qerror", core.$((e) => {
31
- store2.error = e.detail.error;
32
- }));
33
- if (store2.error && props.fallback$) {
34
- return /* @__PURE__ */ jsxRuntime.jsx(jsxRuntime.Fragment, {
35
- children: props.fallback$(store2.error)
36
- });
37
- }
38
- return /* @__PURE__ */ jsxRuntime.jsx(core.Slot, {});
39
- });
40
- const MODULE_CACHE = /* @__PURE__ */ new WeakMap();
41
- const CLIENT_DATA_CACHE = /* @__PURE__ */ new Map();
42
- const QACTION_KEY = "qaction";
43
- const QLOADER_KEY = "qloaders";
44
- const QFN_KEY = "qfunc";
45
- const QDATA_KEY = "qdata";
46
- const Q_ROUTE = "q:route";
47
- const DEFAULT_LOADERS_SERIALIZATION_STRATEGY = globalThis.__DEFAULT_LOADERS_SERIALIZATION_STRATEGY__ || "never";
48
- const MAX_Q_DATA_RETRY_COUNT = 3;
49
- const loadClientData = async (url, element, opts, retryCount = 0) => {
50
- const pagePathname = url.pathname;
51
- const pageSearch = url.search;
52
- const clientDataPath = getClientDataPath(pagePathname, pageSearch, {
53
- actionId: opts?.action?.id,
54
- loaderIds: opts?.loaderIds
55
- });
56
- let qData;
57
- if (!opts?.action) {
58
- qData = CLIENT_DATA_CACHE.get(clientDataPath);
59
- }
60
- if (opts?.preloadRouteBundles !== false) {
61
- preloadRouteBundles(pagePathname, 0.8);
62
- }
63
- let resolveFn;
64
- if (!qData) {
65
- const fetchOptions = getFetchOptions(opts?.action, opts?.clearCache);
66
- if (opts?.action) {
67
- opts.action.data = void 0;
68
- }
69
- qData = fetch(clientDataPath, fetchOptions).then((rsp) => {
70
- if (rsp.status === 404 && opts?.loaderIds && retryCount < MAX_Q_DATA_RETRY_COUNT) {
71
- opts.loaderIds = void 0;
72
- return loadClientData(url, element, opts, retryCount + 1);
73
- }
74
- if (rsp.redirected) {
75
- const redirectedURL = new URL(rsp.url);
76
- const isQData = redirectedURL.pathname.endsWith("/q-data.json");
77
- if (!isQData || redirectedURL.origin !== location.origin) {
78
- if (!opts?.isPrefetch) {
79
- location.href = redirectedURL.href;
80
- }
81
- return;
82
- }
83
- }
84
- if ((rsp.headers.get("content-type") || "").includes("json")) {
85
- return rsp.text().then((text) => {
86
- const [clientData] = internal._deserialize(text, element);
87
- if (!clientData) {
88
- location.href = url.href;
89
- return;
90
- }
91
- if (opts?.clearCache) {
92
- CLIENT_DATA_CACHE.delete(clientDataPath);
93
- }
94
- if (clientData.redirect) {
95
- location.href = clientData.redirect;
96
- } else if (opts?.action) {
97
- const { action } = opts;
98
- const actionData = clientData.loaders[action.id];
99
- resolveFn = () => {
100
- action.resolve({
101
- status: rsp.status,
102
- result: actionData
103
- });
104
- };
105
- }
106
- return clientData;
107
- });
108
- } else {
109
- if (opts?.isPrefetch !== true) {
110
- location.href = url.href;
111
- }
112
- return void 0;
113
- }
114
- });
115
- if (!opts?.action) {
116
- CLIENT_DATA_CACHE.set(clientDataPath, qData);
117
- }
118
- }
119
- return qData.then((v) => {
120
- if (!v) {
121
- CLIENT_DATA_CACHE.delete(clientDataPath);
122
- }
123
- resolveFn && resolveFn();
124
- return v;
125
- });
126
- };
127
- const getFetchOptions = (action, noCache) => {
128
- const actionData = action?.data;
129
- if (!actionData) {
130
- if (noCache) {
131
- return {
132
- cache: "no-cache",
133
- headers: {
134
- "Cache-Control": "no-cache",
135
- Pragma: "no-cache"
136
- }
137
- };
138
- }
139
- return void 0;
140
- }
141
- if (actionData instanceof FormData) {
142
- return {
143
- method: "POST",
144
- body: actionData
145
- };
146
- } else {
147
- return {
148
- method: "POST",
149
- body: JSON.stringify(actionData),
150
- headers: {
151
- "Content-Type": "application/json; charset=UTF-8"
152
- }
153
- };
154
- }
155
- };
156
- const toPath = (url) => url.pathname + url.search + url.hash;
157
- const toUrl = (url, baseUrl) => new URL(url, baseUrl.href);
158
- const isSameOrigin = (a, b) => a.origin === b.origin;
159
- const withSlash = (path) => path.endsWith("/") ? path : path + "/";
160
- const isSamePathname = ({ pathname: a }, { pathname: b }) => {
161
- const lDiff = Math.abs(a.length - b.length);
162
- return lDiff === 0 ? a === b : lDiff === 1 && withSlash(a) === withSlash(b);
163
- };
164
- const isSameSearchQuery = (a, b) => a.search === b.search;
165
- const isSamePath = (a, b) => isSameSearchQuery(a, b) && isSamePathname(a, b);
166
- const getClientDataPath = (pathname, pageSearch, options) => {
167
- let search = pageSearch ?? "";
168
- if (options?.actionId) {
169
- search += (search ? "&" : "?") + QACTION_KEY + "=" + encodeURIComponent(options.actionId);
170
- }
171
- if (options?.loaderIds) {
172
- for (const loaderId of options.loaderIds) {
173
- search += (search ? "&" : "?") + QLOADER_KEY + "=" + encodeURIComponent(loaderId);
174
- }
175
- }
176
- return pathname + (pathname.endsWith("/") ? "" : "/") + "q-data.json" + search;
177
- };
178
- const getClientNavPath = (props, baseUrl) => {
179
- const href = props.href;
180
- if (typeof href === "string" && typeof props.target !== "string" && !props.reload) {
181
- try {
182
- const linkUrl = toUrl(href.trim(), baseUrl.url);
183
- const currentUrl = toUrl("", baseUrl.url);
184
- if (isSameOrigin(linkUrl, currentUrl)) {
185
- return toPath(linkUrl);
186
- }
187
- } catch (e) {
188
- console.error(e);
189
- }
190
- } else if (props.reload) {
191
- return toPath(toUrl("", baseUrl.url));
192
- }
193
- return null;
194
- };
195
- const shouldPreload = (clientNavPath, currentLoc) => {
196
- if (clientNavPath) {
197
- const prefetchUrl = toUrl(clientNavPath, currentLoc.url);
198
- const currentUrl = toUrl("", currentLoc.url);
199
- return !isSamePathname(prefetchUrl, currentUrl);
200
- }
201
- return false;
202
- };
203
- const isPromise = (value) => {
204
- return value && typeof value.then === "function";
205
- };
206
- const createLoaderSignal = (loadersObject, loaderId, url, serializationStrategy, container) => {
207
- return core.createAsyncComputed$(async () => {
208
- if (core.isBrowser && loadersObject[loaderId] === internal._UNINITIALIZED) {
209
- const data = await loadClientData(url, void 0, {
210
- loaderIds: [
211
- loaderId
212
- ]
213
- });
214
- loadersObject[loaderId] = data?.loaders[loaderId] ?? internal._UNINITIALIZED;
215
- }
216
- return loadersObject[loaderId];
217
- }, {
218
- container,
219
- serializationStrategy
220
- });
221
- };
222
- const clientNavigate = (win, navType, fromURL, toURL, replaceState = false) => {
223
- if (navType !== "popstate") {
224
- const samePath = isSamePath(fromURL, toURL);
225
- const sameHash = fromURL.hash === toURL.hash;
226
- if (!samePath || !sameHash) {
227
- const newState = {
228
- _qRouterScroll: newScrollState()
229
- };
230
- if (replaceState) {
231
- win.history.replaceState(newState, "", toPath(toURL));
232
- } else {
233
- win.history.pushState(newState, "", toPath(toURL));
234
- }
235
- }
236
- }
237
- };
238
- const newScrollState = () => {
239
- return {
240
- x: 0,
241
- y: 0,
242
- w: 0,
243
- h: 0
244
- };
245
- };
246
- const preloadRouteBundles = (path, probability = 0.8) => {
247
- if (core.isBrowser) {
248
- path = path.endsWith("/") ? path : path + "/";
249
- path = path.length > 1 && path.startsWith("/") ? path.slice(1) : path;
250
- preloader.p(path, probability);
251
- }
252
- };
253
- const RouteStateContext = /* @__PURE__ */ core.createContextId("qc-s");
254
- const ContentContext = /* @__PURE__ */ core.createContextId("qc-c");
255
- const ContentInternalContext = /* @__PURE__ */ core.createContextId("qc-ic");
256
- const DocumentHeadContext = /* @__PURE__ */ core.createContextId("qc-h");
257
- const RouteLocationContext = /* @__PURE__ */ core.createContextId("qc-l");
258
- const RouteNavigateContext = /* @__PURE__ */ core.createContextId("qc-n");
259
- const RouteActionContext = /* @__PURE__ */ core.createContextId("qc-a");
260
- const RouteInternalContext = /* @__PURE__ */ core.createContextId("qc-ir");
261
- const RoutePreventNavigateContext = /* @__PURE__ */ core.createContextId("qc-p");
262
- const useContent = () => core.useContext(ContentContext);
263
- const useDocumentHead = () => core.useContext(DocumentHeadContext);
264
- const useLocation = () => core.useContext(RouteLocationContext);
265
- const useNavigate = () => core.useContext(RouteNavigateContext);
266
- const usePreventNavigateQrl = (fn) => {
267
- if (!__EXPERIMENTAL__.preventNavigate) {
268
- throw new Error('usePreventNavigate$ is experimental and must be enabled with `experimental: ["preventNavigate"]` in the `qwikVite` plugin.');
269
- }
270
- const registerPreventNav = core.useContext(RoutePreventNavigateContext);
271
- core.useVisibleTask$(() => registerPreventNav(fn));
272
- };
273
- const usePreventNavigate$ = core.implicit$FirstArg(usePreventNavigateQrl);
274
- const useAction = () => core.useContext(RouteActionContext);
275
- const useQwikRouterEnv = () => core.noSerialize(core.useServerData("qwikrouter"));
276
- const Link = core.component$((props) => {
277
- const nav = useNavigate();
278
- const loc = useLocation();
279
- const originalHref = props.href;
280
- const anchorRef = core.useSignal();
281
- const { onClick$, prefetch: prefetchProp, reload, replaceState, scroll, ...linkProps } = /* @__PURE__ */ (() => props)();
282
- const clientNavPath = core.untrack(() => getClientNavPath({
283
- ...linkProps,
284
- reload
285
- }, loc));
286
- linkProps.href = clientNavPath || originalHref;
287
- const prefetchData = core.untrack(() => !!clientNavPath && prefetchProp !== false && prefetchProp !== "js" || void 0);
288
- const prefetch = core.untrack(() => prefetchData || !!clientNavPath && prefetchProp !== false && shouldPreload(clientNavPath, loc));
289
- const handlePrefetch = prefetch ? core.$((_, elm) => {
290
- if (navigator.connection?.saveData) {
291
- return;
292
- }
293
- if (elm && elm.href) {
294
- const url = new URL(elm.href);
295
- preloadRouteBundles(url.pathname);
296
- if (elm.hasAttribute("data-prefetch")) {
297
- loadClientData(url, elm, {
298
- preloadRouteBundles: false,
299
- isPrefetch: true
300
- });
301
- }
302
- }
303
- }) : void 0;
304
- const preventDefault = clientNavPath ? core.sync$((event) => {
305
- if (!(event.metaKey || event.ctrlKey || event.shiftKey || event.altKey)) {
306
- event.preventDefault();
307
- }
308
- }) : void 0;
309
- const handleClientSideNavigation = clientNavPath ? core.$((event, elm) => {
310
- if (event.defaultPrevented) {
311
- if (elm.href) {
312
- elm.setAttribute("aria-pressed", "true");
313
- nav(elm.href, {
314
- forceReload: reload,
315
- replaceState,
316
- scroll
317
- }).then(() => {
318
- elm.removeAttribute("aria-pressed");
319
- });
320
- }
321
- }
322
- }) : void 0;
323
- const handlePreload = core.$((_, elm) => {
324
- const url = new URL(elm.href);
325
- preloadRouteBundles(url.pathname, 1);
326
- });
327
- core.useVisibleTask$(({ track }) => {
328
- track(() => loc.url.pathname);
329
- const handler = linkProps.onQVisible$;
330
- if (handler) {
331
- const event = new CustomEvent("qvisible");
332
- if (Array.isArray(handler)) {
333
- handler.flat(10).forEach((handler2) => handler2?.(event, anchorRef.value));
334
- } else {
335
- handler?.(event, anchorRef.value);
336
- }
337
- }
338
- if (!core.isDev && anchorRef.value) {
339
- handlePrefetch?.(void 0, anchorRef.value);
340
- }
341
- });
342
- return /* @__PURE__ */ jsxRuntime.jsx("a", {
343
- ref: anchorRef,
344
- "q:link": !!clientNavPath,
345
- ...linkProps,
346
- onClick$: [
347
- preventDefault,
348
- handlePreload,
349
- onClick$,
350
- handleClientSideNavigation
351
- ],
352
- "data-prefetch": prefetchData,
353
- onMouseOver$: [
354
- linkProps.onMouseOver$,
355
- handlePrefetch
356
- ],
357
- onFocus$: [
358
- linkProps.onFocus$,
359
- handlePrefetch
360
- ],
361
- // We need to prevent the onQVisible$ from being called twice since it is handled in the visible task
362
- onQVisible$: [],
363
- children: /* @__PURE__ */ jsxRuntime.jsx(core.Slot, {})
364
- });
365
- });
366
- const resolveHead = (endpoint, routeLocation, contentModules, locale, defaults) => {
367
- const head = createDocumentHead(defaults);
368
- const getData = (loaderOrAction) => {
369
- const id = loaderOrAction.__id;
370
- if (loaderOrAction.__brand === "server_loader") {
371
- if (!(id in endpoint.loaders)) {
372
- throw new Error("You can not get the returned data of a loader that has not been executed for this request.");
373
- }
374
- }
375
- const data = endpoint.loaders[id];
376
- if (isPromise(data)) {
377
- throw new Error("Loaders returning a promise can not be resolved for the head function.");
378
- }
379
- return data;
380
- };
381
- const fns = [];
382
- for (const contentModule of contentModules) {
383
- const contentModuleHead = contentModule?.head;
384
- if (contentModuleHead) {
385
- if (typeof contentModuleHead === "function") {
386
- fns.unshift(contentModuleHead);
387
- } else if (typeof contentModuleHead === "object") {
388
- resolveDocumentHead(head, contentModuleHead);
389
- }
390
- }
391
- }
392
- if (fns.length) {
393
- const headProps = {
394
- head,
395
- withLocale: (fn) => core.withLocale(locale, fn),
396
- resolveValue: getData,
397
- ...routeLocation
398
- };
399
- core.withLocale(locale, () => {
400
- for (const fn of fns) {
401
- resolveDocumentHead(head, fn(headProps));
402
- }
403
- });
404
- }
405
- return head;
406
- };
407
- const resolveDocumentHead = (resolvedHead, updatedHead) => {
408
- if (typeof updatedHead.title === "string") {
409
- resolvedHead.title = updatedHead.title;
410
- }
411
- mergeArray(resolvedHead.meta, updatedHead.meta);
412
- mergeArray(resolvedHead.links, updatedHead.links);
413
- mergeArray(resolvedHead.styles, updatedHead.styles);
414
- mergeArray(resolvedHead.scripts, updatedHead.scripts);
415
- Object.assign(resolvedHead.frontmatter, updatedHead.frontmatter);
416
- };
417
- const mergeArray = (existingArr, newArr) => {
418
- if (Array.isArray(newArr)) {
419
- for (const newItem of newArr) {
420
- if (typeof newItem.key === "string") {
421
- const existingIndex = existingArr.findIndex((i) => i.key === newItem.key);
422
- if (existingIndex > -1) {
423
- existingArr[existingIndex] = newItem;
424
- continue;
425
- }
426
- }
427
- existingArr.push(newItem);
428
- }
429
- }
430
- };
431
- const createDocumentHead = (defaults) => ({
432
- title: defaults?.title || "",
433
- meta: [
434
- ...defaults?.meta || []
435
- ],
436
- links: [
437
- ...defaults?.links || []
438
- ],
439
- styles: [
440
- ...defaults?.styles || []
441
- ],
442
- scripts: [
443
- ...defaults?.scripts || []
444
- ],
445
- frontmatter: {
446
- ...defaults?.frontmatter
447
- }
448
- });
449
- function matchRoute(route, path) {
450
- const routeIdx = startIdxSkipSlash(route);
451
- const routeLength = lengthNoTrailingSlash(route);
452
- const pathIdx = startIdxSkipSlash(path);
453
- const pathLength = lengthNoTrailingSlash(path);
454
- return matchRoutePart(route, routeIdx, routeLength, path, pathIdx, pathLength);
455
- }
456
- function matchRoutePart(route, routeIdx, routeLength, path, pathIdx, pathLength) {
457
- if (path.startsWith("/build/")) {
458
- return null;
459
- }
460
- let params = null;
461
- while (routeIdx < routeLength) {
462
- const routeCh = route.charCodeAt(routeIdx++);
463
- const pathCh = path.charCodeAt(pathIdx++);
464
- if (routeCh === 91) {
465
- const isMany = isThreeDots(route, routeIdx);
466
- const paramNameStart = routeIdx + (isMany ? 3 : 0);
467
- const paramNameEnd = scan(route, paramNameStart, routeLength, 93);
468
- const paramName = route.substring(paramNameStart, paramNameEnd);
469
- const paramSuffixEnd = scan(route, paramNameEnd + 1, routeLength, 47);
470
- const suffix = route.substring(paramNameEnd + 1, paramSuffixEnd);
471
- routeIdx = paramNameEnd + 1;
472
- const paramValueStart = pathIdx - 1;
473
- if (isMany) {
474
- const match = recursiveScan(paramName, suffix, path, paramValueStart, pathLength, route, routeIdx + suffix.length + 1, routeLength);
475
- if (match) {
476
- return Object.assign(params || (params = {}), match);
477
- }
478
- }
479
- const paramValueEnd = scan(path, paramValueStart, pathLength, 47, suffix);
480
- if (paramValueEnd == -1) {
481
- return null;
482
- }
483
- const paramValue = path.substring(paramValueStart, paramValueEnd);
484
- if (!isMany && !suffix && !paramValue) {
485
- return null;
486
- }
487
- pathIdx = paramValueEnd;
488
- (params || (params = {}))[paramName] = decodeURIComponent(paramValue);
489
- } else if (routeCh !== pathCh) {
490
- if (!(isNaN(pathCh) && isRestParameter(route, routeIdx))) {
491
- return null;
492
- }
493
- }
494
- }
495
- if (allConsumed(route, routeIdx) && allConsumed(path, pathIdx)) {
496
- return params || {};
497
- } else {
498
- return null;
499
- }
500
- }
501
- function isRestParameter(text, idx) {
502
- return text.charCodeAt(idx) === 91 && isThreeDots(text, idx + 1);
503
- }
504
- function lengthNoTrailingSlash(text) {
505
- const length = text.length;
506
- return length > 1 && text.charCodeAt(length - 1) === 47 ? length - 1 : length;
507
- }
508
- function allConsumed(text, idx) {
509
- const length = text.length;
510
- return idx >= length || idx == length - 1 && text.charCodeAt(idx) === 47;
511
- }
512
- function startIdxSkipSlash(text) {
513
- return text.charCodeAt(0) === 47 ? 1 : 0;
514
- }
515
- function isThreeDots(text, idx) {
516
- return text.charCodeAt(idx) === 46 && text.charCodeAt(idx + 1) === 46 && text.charCodeAt(idx + 2) === 46;
517
- }
518
- function scan(text, idx, end, ch, suffix = "") {
519
- while (idx < end && text.charCodeAt(idx) !== ch) {
520
- idx++;
521
- }
522
- const suffixLength = suffix.length;
523
- for (let i = 0; i < suffixLength; i++) {
524
- if (text.charCodeAt(idx - suffixLength + i) !== suffix.charCodeAt(i)) {
525
- return -1;
526
- }
527
- }
528
- return idx - suffixLength;
529
- }
530
- function recursiveScan(paramName, suffix, path, pathStart, pathLength, route, routeStart, routeLength) {
531
- if (path.charCodeAt(pathStart) === 47) {
532
- pathStart++;
533
- }
534
- let pathIdx = pathLength;
535
- const sep = suffix + "/";
536
- while (pathIdx >= pathStart) {
537
- const match = matchRoutePart(route, routeStart, routeLength, path, pathIdx, pathLength);
538
- if (match) {
539
- let value = path.substring(pathStart, Math.min(pathIdx, pathLength));
540
- if (value.endsWith(sep)) {
541
- value = value.substring(0, value.length - sep.length);
542
- }
543
- match[paramName] = decodeURIComponent(value);
544
- return match;
545
- }
546
- const newPathIdx = lastIndexOf(path, pathStart, sep, pathIdx, pathStart - 1) + sep.length;
547
- if (pathIdx === newPathIdx) {
548
- break;
549
- }
550
- pathIdx = newPathIdx;
551
- }
552
- return null;
553
- }
554
- function lastIndexOf(text, start, match, searchIdx, notFoundIdx) {
555
- let idx = text.lastIndexOf(match, searchIdx);
556
- if (idx == searchIdx - match.length) {
557
- idx = text.lastIndexOf(match, searchIdx - match.length - 1);
558
- }
559
- return idx > start ? idx : notFoundIdx;
560
- }
561
- var RouteDataProp = /* @__PURE__ */ (function(RouteDataProp2) {
562
- RouteDataProp2[RouteDataProp2["RouteName"] = 0] = "RouteName";
563
- RouteDataProp2[RouteDataProp2["Loaders"] = 1] = "Loaders";
564
- RouteDataProp2[RouteDataProp2["OriginalPathname"] = 2] = "OriginalPathname";
565
- RouteDataProp2[RouteDataProp2["RouteBundleNames"] = 3] = "RouteBundleNames";
566
- return RouteDataProp2;
567
- })({});
568
- var MenuDataProp = /* @__PURE__ */ (function(MenuDataProp2) {
569
- MenuDataProp2[MenuDataProp2["Pathname"] = 0] = "Pathname";
570
- MenuDataProp2[MenuDataProp2["MenuLoader"] = 1] = "MenuLoader";
571
- return MenuDataProp2;
572
- })({});
573
- const deepFreeze = (obj) => {
574
- if (obj == null) {
575
- return obj;
576
- }
577
- Object.getOwnPropertyNames(obj).forEach((prop) => {
578
- const value = obj[prop];
579
- if (value && typeof value === "object" && !Object.isFrozen(value)) {
580
- deepFreeze(value);
581
- }
582
- });
583
- return Object.freeze(obj);
584
- };
585
- const loadRoute = async (routes, menus, cacheModules, pathname, isInternal) => {
586
- if (!Array.isArray(routes)) {
587
- return null;
588
- }
589
- for (const routeData of routes) {
590
- const routeName = routeData[RouteDataProp.RouteName];
591
- const params = matchRoute(routeName, pathname);
592
- if (!params) {
593
- continue;
594
- }
595
- const loaders = routeData[RouteDataProp.Loaders];
596
- const routeBundleNames = routeData[RouteDataProp.RouteBundleNames];
597
- const modules = new Array(loaders.length);
598
- const pendingLoads = [];
599
- loaders.forEach((moduleLoader, i) => {
600
- loadModule(moduleLoader, pendingLoads, (routeModule) => modules[i] = routeModule, cacheModules);
601
- });
602
- let menu = void 0;
603
- {
604
- const menuLoader = getMenuLoader(menus, pathname);
605
- loadModule(menuLoader, pendingLoads, (menuModule) => menu = menuModule?.default, cacheModules);
606
- }
607
- if (pendingLoads.length > 0) {
608
- await Promise.all(pendingLoads);
609
- }
610
- return [
611
- routeName,
612
- params,
613
- modules,
614
- deepFreeze(menu),
615
- routeBundleNames
616
- ];
617
- }
618
- return null;
619
- };
620
- const loadModule = (moduleLoader, pendingLoads, moduleSetter, cacheModules) => {
621
- if (typeof moduleLoader === "function") {
622
- const loadedModule = MODULE_CACHE.get(moduleLoader);
623
- if (loadedModule) {
624
- moduleSetter(loadedModule);
625
- } else {
626
- const moduleOrPromise = moduleLoader();
627
- if (typeof moduleOrPromise.then === "function") {
628
- pendingLoads.push(moduleOrPromise.then((loadedModule2) => {
629
- if (cacheModules !== false) {
630
- MODULE_CACHE.set(moduleLoader, loadedModule2);
631
- }
632
- moduleSetter(loadedModule2);
633
- }));
634
- } else if (moduleOrPromise) {
635
- moduleSetter(moduleOrPromise);
636
- }
637
- }
638
- }
639
- };
640
- const getMenuLoader = (menus, pathname) => {
641
- if (menus) {
642
- pathname = pathname.endsWith("/") ? pathname : pathname + "/";
643
- const menu = menus.find((m) => m[MenuDataProp.Pathname] === pathname || pathname.startsWith(m[MenuDataProp.Pathname]));
644
- if (menu) {
645
- return menu[MenuDataProp.MenuLoader];
646
- }
647
- }
648
- };
649
- function callRestoreScrollOnDocument() {
650
- if (document.__q_scroll_restore__) {
651
- document.__q_scroll_restore__();
652
- document.__q_scroll_restore__ = void 0;
653
- }
654
- }
655
- const restoreScroll = (type, toUrl2, fromUrl, scroller, scrollState) => {
656
- if (type === "popstate" && scrollState) {
657
- scroller.scrollTo(scrollState.x, scrollState.y);
658
- } else if (type === "link" || type === "form") {
659
- if (!hashScroll(toUrl2, fromUrl)) {
660
- scroller.scrollTo(0, 0);
661
- }
662
- }
663
- };
664
- const hashScroll = (toUrl2, fromUrl) => {
665
- const elmId = toUrl2.hash.slice(1);
666
- const elm = elmId && document.getElementById(elmId);
667
- if (elm) {
668
- elm.scrollIntoView();
669
- return true;
670
- } else if (!elm && toUrl2.hash && isSamePath(toUrl2, fromUrl)) {
671
- return true;
672
- }
673
- return false;
674
- };
675
- const currentScrollState = (elm) => {
676
- return {
677
- x: elm.scrollLeft,
678
- y: elm.scrollTop,
679
- w: Math.max(elm.scrollWidth, elm.clientWidth),
680
- h: Math.max(elm.scrollHeight, elm.clientHeight)
681
- };
682
- };
683
- const getScrollHistory = () => {
684
- const state = history.state;
685
- return state?._qRouterScroll;
686
- };
687
- const saveScrollHistory = (scrollState) => {
688
- const state = history.state || {};
689
- state._qRouterScroll = scrollState;
690
- history.replaceState(state, "");
691
- };
692
- const spaInit = core.event$((_, el) => {
693
- const win = window;
694
- const spa = "_qRouterSPA";
695
- const initPopstate = "_qRouterInitPopstate";
696
- const initAnchors = "_qRouterInitAnchors";
697
- const initVisibility = "_qRouterInitVisibility";
698
- const initScroll = "_qRouterInitScroll";
699
- if (!win[spa] && !win[initPopstate] && !win[initAnchors] && !win[initVisibility] && !win[initScroll]) {
700
- const currentPath = location.pathname + location.search;
701
- const historyPatch = "_qRouterHistoryPatch";
702
- const scrollEnabled = "_qRouterScrollEnabled";
703
- const debounceTimeout = "_qRouterScrollDebounce";
704
- const scrollHistory = "_qRouterScroll";
705
- const checkAndScroll = (scrollState) => {
706
- if (scrollState) {
707
- win.scrollTo(scrollState.x, scrollState.y);
708
- }
709
- };
710
- const currentScrollState2 = () => {
711
- const elm = document.documentElement;
712
- return {
713
- x: elm.scrollLeft,
714
- y: elm.scrollTop,
715
- w: Math.max(elm.scrollWidth, elm.clientWidth),
716
- h: Math.max(elm.scrollHeight, elm.clientHeight)
717
- };
718
- };
719
- const saveScrollState = (scrollState) => {
720
- const state = history.state || {};
721
- state[scrollHistory] = scrollState || currentScrollState2();
722
- history.replaceState(state, "");
723
- };
724
- saveScrollState();
725
- win[initPopstate] = () => {
726
- if (win[spa]) {
727
- return;
728
- }
729
- win[scrollEnabled] = false;
730
- clearTimeout(win[debounceTimeout]);
731
- if (currentPath !== location.pathname + location.search) {
732
- const getContainer = (el2) => el2.closest("[q\\:container]:not([q\\:container=html]):not([q\\:container=text])");
733
- const container = getContainer(el);
734
- const domContainer = container.qContainer;
735
- const hostElement = domContainer.vNodeLocate(el);
736
- const nav = domContainer?.resolveContext(hostElement, {
737
- id: "qc--n"
738
- });
739
- if (nav) {
740
- nav(location.href, {
741
- type: "popstate"
742
- });
743
- } else {
744
- location.reload();
745
- }
746
- } else {
747
- if (history.scrollRestoration === "manual") {
748
- const scrollState = history.state?.[scrollHistory];
749
- checkAndScroll(scrollState);
750
- win[scrollEnabled] = true;
751
- }
752
- }
753
- };
754
- if (!win[historyPatch]) {
755
- win[historyPatch] = true;
756
- const pushState = history.pushState;
757
- const replaceState = history.replaceState;
758
- const prepareState = (state) => {
759
- if (state === null || typeof state === "undefined") {
760
- state = {};
761
- } else if (state?.constructor !== Object) {
762
- state = {
763
- _data: state
764
- };
765
- if (core.isDev) {
766
- console.warn("In a Qwik SPA context, `history.state` is used to store scroll state. Direct calls to `pushState()` and `replaceState()` must supply an actual Object type. We need to be able to automatically attach the scroll state to your state object. A new state object has been created, your data has been moved to: `history.state._data`");
767
- }
768
- }
769
- state._qRouterScroll = state._qRouterScroll || currentScrollState2();
770
- return state;
771
- };
772
- history.pushState = (state, title, url) => {
773
- state = prepareState(state);
774
- return pushState.call(history, state, title, url);
775
- };
776
- history.replaceState = (state, title, url) => {
777
- state = prepareState(state);
778
- return replaceState.call(history, state, title, url);
779
- };
780
- }
781
- win[initAnchors] = (event) => {
782
- if (win[spa] || event.defaultPrevented) {
783
- return;
784
- }
785
- const target = event.target.closest("a[href]");
786
- if (target && !target.hasAttribute("preventdefault:click")) {
787
- const href = target.getAttribute("href");
788
- const prev = new URL(location.href);
789
- const dest = new URL(href, prev);
790
- const sameOrigin = dest.origin === prev.origin;
791
- const samePath = dest.pathname + dest.search === prev.pathname + prev.search;
792
- if (sameOrigin && samePath) {
793
- event.preventDefault();
794
- if (dest.href !== prev.href) {
795
- history.pushState(null, "", dest);
796
- }
797
- if (!dest.hash) {
798
- if (dest.href.endsWith("#")) {
799
- window.scrollTo(0, 0);
800
- } else {
801
- win[scrollEnabled] = false;
802
- clearTimeout(win[debounceTimeout]);
803
- saveScrollState({
804
- ...currentScrollState2(),
805
- x: 0,
806
- y: 0
807
- });
808
- location.reload();
809
- }
810
- } else {
811
- const elmId = dest.hash.slice(1);
812
- const elm = document.getElementById(elmId);
813
- if (elm) {
814
- elm.scrollIntoView();
815
- }
816
- }
817
- }
818
- }
819
- };
820
- win[initVisibility] = () => {
821
- if (!win[spa] && win[scrollEnabled] && document.visibilityState === "hidden") {
822
- saveScrollState();
823
- }
824
- };
825
- win[initScroll] = () => {
826
- if (win[spa] || !win[scrollEnabled]) {
827
- return;
828
- }
829
- clearTimeout(win[debounceTimeout]);
830
- win[debounceTimeout] = setTimeout(() => {
831
- saveScrollState();
832
- win[debounceTimeout] = void 0;
833
- }, 200);
834
- };
835
- win[scrollEnabled] = true;
836
- setTimeout(() => {
837
- win.addEventListener("popstate", win[initPopstate]);
838
- win.addEventListener("scroll", win[initScroll], {
839
- passive: true
840
- });
841
- document.body.addEventListener("click", win[initAnchors]);
842
- if (!win.navigation) {
843
- document.addEventListener("visibilitychange", win[initVisibility], {
844
- passive: true
845
- });
846
- }
847
- }, 0);
848
- }
849
- });
850
- const startViewTransition = (params) => {
851
- if (!params.update) {
852
- return;
853
- }
854
- if ("startViewTransition" in document) {
855
- let transition;
856
- try {
857
- transition = document.startViewTransition(params);
858
- } catch {
859
- transition = document.startViewTransition(params.update);
860
- }
861
- const event = new CustomEvent("qviewtransition", {
862
- detail: transition
863
- });
864
- document.dispatchEvent(event);
865
- return transition;
866
- } else {
867
- params.update?.();
868
- }
869
- };
870
- const transitionCss = "@layer qwik {\n @supports selector(html:active-view-transition-type(type)) {\n html:active-view-transition-type(qwik-navigation) {\n :root {\n view-transition-name: none;\n }\n }\n }\n @supports not selector(html:active-view-transition-type(type)) {\n :root {\n view-transition-name: none;\n }\n }\n}\n";
871
- const QWIK_CITY_SCROLLER = "_qCityScroller";
872
- const QWIK_ROUTER_SCROLLER = "_qRouterScroller";
873
- const preventNav = {};
874
- const internalState = {
875
- navCount: 0
876
- };
877
- const useQwikRouter = (props) => {
878
- core.useStyles$(transitionCss);
879
- const env = useQwikRouterEnv();
880
- if (!env?.params) {
881
- throw new Error(`Missing Qwik Router Env Data for help visit https://github.com/QwikDev/qwik/issues/6237`);
882
- }
883
- const urlEnv = core.useServerData("url");
884
- if (!urlEnv) {
885
- throw new Error(`Missing Qwik URL Env Data`);
886
- }
887
- const serverHead = core.useServerData("documentHead");
888
- if (core.isServer) {
889
- if (env.ev.originalUrl.pathname !== env.ev.url.pathname && !__EXPERIMENTAL__.enableRequestRewrite) {
890
- throw new Error(`enableRequestRewrite is an experimental feature and is not enabled. Please enable the feature flag by adding \`experimental: ["enableRequestRewrite"]\` to your qwikVite plugin options.`);
891
- }
892
- }
893
- const url = new URL(urlEnv);
894
- const routeLocationTarget = {
895
- url,
896
- params: env.params,
897
- isNavigating: false,
898
- prevUrl: void 0
899
- };
900
- const routeLocation = core.useStore(routeLocationTarget, {
901
- deep: false
902
- });
903
- const navResolver = {};
904
- const container = internal._getContextContainer();
905
- const getSerializationStrategy = (loaderId) => {
906
- return env.response.loadersSerializationStrategy.get(loaderId) || DEFAULT_LOADERS_SERIALIZATION_STRATEGY;
907
- };
908
- const loadersObject = {};
909
- const loaderState = {};
910
- for (const [key, value] of Object.entries(env.response.loaders)) {
911
- loadersObject[key] = value;
912
- loaderState[key] = createLoaderSignal(loadersObject, key, url, getSerializationStrategy(key), container);
913
- }
914
- loadersObject[internal.SerializerSymbol] = (obj) => {
915
- const loadersSerializationObject = {};
916
- for (const [k, v] of Object.entries(obj)) {
917
- loadersSerializationObject[k] = getSerializationStrategy(k) === "always" ? v : internal._UNINITIALIZED;
918
- }
919
- return loadersSerializationObject;
920
- };
921
- const routeInternal = core.useSignal({
922
- type: "initial",
923
- dest: url,
924
- forceReload: false,
925
- replaceState: false,
926
- scroll: true
927
- });
928
- const documentHead = core.useStore(() => createDocumentHead(serverHead));
929
- const content = core.useStore({
930
- headings: void 0,
931
- menu: void 0
932
- });
933
- const contentInternal = core.useSignal();
934
- const currentActionId = env.response.action;
935
- const currentAction = currentActionId ? env.response.loaders[currentActionId] : void 0;
936
- const actionState = core.useSignal(currentAction ? {
937
- id: currentActionId,
938
- data: env.response.formData,
939
- output: {
940
- result: currentAction,
941
- status: env.response.status
942
- }
943
- } : void 0);
944
- const registerPreventNav = core.$((fn$) => {
945
- if (!core.isBrowser) {
946
- return;
947
- }
948
- preventNav.$handler$ || (preventNav.$handler$ = (event) => {
949
- internalState.navCount++;
950
- if (!preventNav.$cbs$) {
951
- return;
952
- }
953
- const prevents = [
954
- ...preventNav.$cbs$.values()
955
- ].map((cb) => cb.resolved ? cb.resolved() : cb());
956
- if (prevents.some(Boolean)) {
957
- event.preventDefault();
958
- event.returnValue = true;
959
- }
960
- });
961
- (preventNav.$cbs$ || (preventNav.$cbs$ = /* @__PURE__ */ new Set())).add(fn$);
962
- fn$.resolve();
963
- window.addEventListener("beforeunload", preventNav.$handler$);
964
- return () => {
965
- if (preventNav.$cbs$) {
966
- preventNav.$cbs$.delete(fn$);
967
- if (!preventNav.$cbs$.size) {
968
- preventNav.$cbs$ = void 0;
969
- window.removeEventListener("beforeunload", preventNav.$handler$);
970
- }
971
- }
972
- };
973
- });
974
- const goto = core.$(async (path, opt) => {
975
- const { type = "link", forceReload = path === void 0, replaceState = false, scroll = true } = typeof opt === "object" ? opt : {
976
- forceReload: opt
977
- };
978
- internalState.navCount++;
979
- const lastDest = routeInternal.value.dest;
980
- const dest = path === void 0 ? lastDest : typeof path === "number" ? path : toUrl(path, routeLocation.url);
981
- if (preventNav.$cbs$ && (forceReload || typeof dest === "number" || !isSamePath(dest, lastDest) || !isSameOrigin(dest, lastDest))) {
982
- const ourNavId = internalState.navCount;
983
- const prevents = await Promise.all([
984
- ...preventNav.$cbs$.values()
985
- ].map((cb) => cb(dest)));
986
- if (ourNavId !== internalState.navCount || prevents.some(Boolean)) {
987
- if (ourNavId === internalState.navCount && type === "popstate") {
988
- history.pushState(null, "", lastDest);
989
- }
990
- return;
991
- }
992
- }
993
- if (typeof dest === "number") {
994
- if (core.isBrowser) {
995
- history.go(dest);
996
- }
997
- return;
998
- }
999
- if (!isSameOrigin(dest, lastDest)) {
1000
- if (core.isBrowser) {
1001
- location.href = dest.href;
1002
- }
1003
- return;
1004
- }
1005
- if (!forceReload && isSamePath(dest, lastDest)) {
1006
- if (core.isBrowser) {
1007
- if (type === "link" && dest.href !== location.href) {
1008
- history.pushState(null, "", dest);
1009
- }
1010
- let scroller = document.getElementById(QWIK_ROUTER_SCROLLER);
1011
- if (!scroller) {
1012
- scroller = document.getElementById(QWIK_CITY_SCROLLER);
1013
- if (scroller && core.isDev) {
1014
- console.warn(`Please update your scroller ID to "${QWIK_ROUTER_SCROLLER}" as "${QWIK_CITY_SCROLLER}" is deprecated and will be removed in V3`);
1015
- }
1016
- }
1017
- if (!scroller) {
1018
- scroller = document.documentElement;
1019
- }
1020
- restoreScroll(type, dest, new URL(location.href), scroller, getScrollHistory());
1021
- if (type === "popstate") {
1022
- window._qRouterScrollEnabled = true;
1023
- }
1024
- }
1025
- return;
1026
- }
1027
- routeInternal.value = {
1028
- type,
1029
- dest,
1030
- forceReload,
1031
- replaceState,
1032
- scroll
1033
- };
1034
- if (core.isBrowser) {
1035
- loadClientData(dest, internal._getContextElement());
1036
- loadRoute(qwikRouterConfig__namespace.routes, qwikRouterConfig__namespace.menus, qwikRouterConfig__namespace.cacheModules, dest.pathname);
1037
- }
1038
- actionState.value = void 0;
1039
- routeLocation.isNavigating = true;
1040
- return new Promise((resolve) => {
1041
- navResolver.r = resolve;
1042
- });
1043
- });
1044
- core.useContextProvider(ContentContext, content);
1045
- core.useContextProvider(ContentInternalContext, contentInternal);
1046
- core.useContextProvider(DocumentHeadContext, documentHead);
1047
- core.useContextProvider(RouteLocationContext, routeLocation);
1048
- core.useContextProvider(RouteNavigateContext, goto);
1049
- core.useContextProvider(RouteStateContext, loaderState);
1050
- core.useContextProvider(RouteActionContext, actionState);
1051
- core.useContextProvider(RouteInternalContext, routeInternal);
1052
- core.useContextProvider(RoutePreventNavigateContext, registerPreventNav);
1053
- core.useTask$(({ track }) => {
1054
- async function run() {
1055
- const [navigation, action] = track(() => [
1056
- routeInternal.value,
1057
- actionState.value
1058
- ]);
1059
- const locale = core.getLocale("");
1060
- const prevUrl = routeLocation.url;
1061
- const navType = action ? "form" : navigation.type;
1062
- const replaceState = navigation.replaceState;
1063
- let trackUrl;
1064
- let clientPageData;
1065
- let loadedRoute = null;
1066
- let elm;
1067
- if (core.isServer) {
1068
- trackUrl = new URL(navigation.dest, routeLocation.url);
1069
- loadedRoute = env.loadedRoute;
1070
- clientPageData = env.response;
1071
- } else {
1072
- trackUrl = new URL(navigation.dest, location);
1073
- if (trackUrl.pathname.endsWith("/")) {
1074
- if (globalThis.__NO_TRAILING_SLASH__) {
1075
- trackUrl.pathname = trackUrl.pathname.slice(0, -1);
1076
- }
1077
- } else if (!globalThis.__NO_TRAILING_SLASH__) {
1078
- trackUrl.pathname += "/";
1079
- }
1080
- let loadRoutePromise = loadRoute(qwikRouterConfig__namespace.routes, qwikRouterConfig__namespace.menus, qwikRouterConfig__namespace.cacheModules, trackUrl.pathname);
1081
- elm = internal._getContextElement();
1082
- const pageData = clientPageData = await loadClientData(trackUrl, elm, {
1083
- action,
1084
- clearCache: true
1085
- });
1086
- if (!pageData) {
1087
- routeInternal.untrackedValue = {
1088
- type: navType,
1089
- dest: trackUrl
1090
- };
1091
- return;
1092
- }
1093
- const newHref = pageData.href;
1094
- const newURL = new URL(newHref, trackUrl);
1095
- if (!isSamePath(newURL, trackUrl)) {
1096
- if (!pageData.isRewrite) {
1097
- trackUrl = newURL;
1098
- }
1099
- loadRoutePromise = loadRoute(
1100
- qwikRouterConfig__namespace.routes,
1101
- qwikRouterConfig__namespace.menus,
1102
- qwikRouterConfig__namespace.cacheModules,
1103
- newURL.pathname
1104
- // Load the actual required path.
1105
- );
1106
- }
1107
- try {
1108
- loadedRoute = await loadRoutePromise;
1109
- } catch (e) {
1110
- console.error(e);
1111
- window.location.href = newHref;
1112
- return;
1113
- }
1114
- }
1115
- if (loadedRoute) {
1116
- const [routeName, params, mods, menu] = loadedRoute;
1117
- const contentModules = mods;
1118
- const pageModule = contentModules[contentModules.length - 1];
1119
- if (navigation.dest.search && !!isSamePath(trackUrl, prevUrl)) {
1120
- trackUrl.search = navigation.dest.search;
1121
- }
1122
- let shouldForcePrevUrl = false;
1123
- let shouldForceUrl = false;
1124
- let shouldForceParams = false;
1125
- if (!isSamePath(trackUrl, prevUrl)) {
1126
- if (internal._hasStoreEffects(routeLocation, "prevUrl")) {
1127
- shouldForcePrevUrl = true;
1128
- }
1129
- routeLocationTarget.prevUrl = prevUrl;
1130
- }
1131
- if (routeLocationTarget.url !== trackUrl) {
1132
- if (internal._hasStoreEffects(routeLocation, "url")) {
1133
- shouldForceUrl = true;
1134
- }
1135
- routeLocationTarget.url = trackUrl;
1136
- }
1137
- if (routeLocationTarget.params !== params) {
1138
- if (internal._hasStoreEffects(routeLocation, "params")) {
1139
- shouldForceParams = true;
1140
- }
1141
- routeLocationTarget.params = params;
1142
- }
1143
- routeInternal.untrackedValue = {
1144
- type: navType,
1145
- dest: trackUrl
1146
- };
1147
- const resolvedHead = resolveHead(clientPageData, routeLocation, contentModules, locale, serverHead);
1148
- content.headings = pageModule.headings;
1149
- content.menu = menu;
1150
- contentInternal.untrackedValue = core.noSerialize(contentModules);
1151
- documentHead.links = resolvedHead.links;
1152
- documentHead.meta = resolvedHead.meta;
1153
- documentHead.styles = resolvedHead.styles;
1154
- documentHead.scripts = resolvedHead.scripts;
1155
- documentHead.title = resolvedHead.title;
1156
- documentHead.frontmatter = resolvedHead.frontmatter;
1157
- if (core.isBrowser) {
1158
- let scrollState;
1159
- if (navType === "popstate") {
1160
- scrollState = getScrollHistory();
1161
- }
1162
- const scroller = document.getElementById(QWIK_ROUTER_SCROLLER) ?? document.documentElement;
1163
- if (navigation.scroll && (!navigation.forceReload || !isSamePath(trackUrl, prevUrl)) && (navType === "link" || navType === "popstate") || navType === "form" && !isSamePath(trackUrl, prevUrl)) {
1164
- document.__q_scroll_restore__ = () => restoreScroll(navType, trackUrl, prevUrl, scroller, scrollState);
1165
- }
1166
- const loaders = clientPageData?.loaders;
1167
- if (loaders) {
1168
- const container2 = internal._getContextContainer();
1169
- for (const [key, value] of Object.entries(loaders)) {
1170
- const signal = loaderState[key];
1171
- const awaitedValue = await value;
1172
- loadersObject[key] = awaitedValue;
1173
- if (!signal) {
1174
- loaderState[key] = createLoaderSignal(loadersObject, key, trackUrl, DEFAULT_LOADERS_SERIALIZATION_STRATEGY, container2);
1175
- } else {
1176
- signal.invalidate();
1177
- }
1178
- }
1179
- }
1180
- CLIENT_DATA_CACHE.clear();
1181
- const win = window;
1182
- if (!win._qRouterSPA) {
1183
- win._qRouterSPA = true;
1184
- history.scrollRestoration = "manual";
1185
- win.addEventListener("popstate", () => {
1186
- win._qRouterScrollEnabled = false;
1187
- clearTimeout(win._qRouterScrollDebounce);
1188
- goto(location.href, {
1189
- type: "popstate"
1190
- });
1191
- });
1192
- win.removeEventListener("popstate", win._qRouterInitPopstate);
1193
- win._qRouterInitPopstate = void 0;
1194
- if (!win._qRouterHistoryPatch) {
1195
- win._qRouterHistoryPatch = true;
1196
- const pushState = history.pushState;
1197
- const replaceState2 = history.replaceState;
1198
- const prepareState = (state) => {
1199
- if (state === null || typeof state === "undefined") {
1200
- state = {};
1201
- } else if (state?.constructor !== Object) {
1202
- state = {
1203
- _data: state
1204
- };
1205
- if (core.isDev) {
1206
- console.warn("In a Qwik SPA context, `history.state` is used to store scroll state. Direct calls to `pushState()` and `replaceState()` must supply an actual Object type. We need to be able to automatically attach the scroll state to your state object. A new state object has been created, your data has been moved to: `history.state._data`");
1207
- }
1208
- }
1209
- state._qRouterScroll = state._qRouterScroll || currentScrollState(scroller);
1210
- return state;
1211
- };
1212
- history.pushState = (state, title, url2) => {
1213
- state = prepareState(state);
1214
- return pushState.call(history, state, title, url2);
1215
- };
1216
- history.replaceState = (state, title, url2) => {
1217
- state = prepareState(state);
1218
- return replaceState2.call(history, state, title, url2);
1219
- };
1220
- }
1221
- document.body.addEventListener("click", (event) => {
1222
- if (event.defaultPrevented) {
1223
- return;
1224
- }
1225
- const target = event.target.closest("a[href]");
1226
- if (target && !target.hasAttribute("preventdefault:click")) {
1227
- const href = target.getAttribute("href");
1228
- const prev = new URL(location.href);
1229
- const dest = new URL(href, prev);
1230
- if (isSameOrigin(dest, prev) && isSamePath(dest, prev)) {
1231
- event.preventDefault();
1232
- if (!dest.hash && !dest.href.endsWith("#")) {
1233
- if (dest.href !== prev.href) {
1234
- history.pushState(null, "", dest);
1235
- }
1236
- win._qRouterScrollEnabled = false;
1237
- clearTimeout(win._qRouterScrollDebounce);
1238
- saveScrollHistory({
1239
- ...currentScrollState(scroller),
1240
- x: 0,
1241
- y: 0
1242
- });
1243
- location.reload();
1244
- return;
1245
- }
1246
- goto(target.getAttribute("href"));
1247
- }
1248
- }
1249
- });
1250
- document.body.removeEventListener("click", win._qRouterInitAnchors);
1251
- win._qRouterInitAnchors = void 0;
1252
- if (!window.navigation) {
1253
- document.addEventListener("visibilitychange", () => {
1254
- if ((win._qRouterScrollEnabled || win._qCityScrollEnabled) && document.visibilityState === "hidden") {
1255
- if (win._qCityScrollEnabled) {
1256
- console.warn('"_qCityScrollEnabled" is deprecated. Use "_qRouterScrollEnabled" instead.');
1257
- }
1258
- const scrollState2 = currentScrollState(scroller);
1259
- saveScrollHistory(scrollState2);
1260
- }
1261
- }, {
1262
- passive: true
1263
- });
1264
- document.removeEventListener("visibilitychange", win._qRouterInitVisibility);
1265
- win._qRouterInitVisibility = void 0;
1266
- }
1267
- win.addEventListener("scroll", () => {
1268
- if (!win._qRouterScrollEnabled && !win._qCityScrollEnabled) {
1269
- return;
1270
- }
1271
- clearTimeout(win._qRouterScrollDebounce);
1272
- win._qRouterScrollDebounce = setTimeout(() => {
1273
- const scrollState2 = currentScrollState(scroller);
1274
- saveScrollHistory(scrollState2);
1275
- win._qRouterScrollDebounce = void 0;
1276
- }, 200);
1277
- }, {
1278
- passive: true
1279
- });
1280
- removeEventListener("scroll", win._qRouterInitScroll);
1281
- win._qRouterInitScroll = void 0;
1282
- spaInit.resolve();
1283
- }
1284
- if (navType !== "popstate") {
1285
- win._qRouterScrollEnabled = false;
1286
- clearTimeout(win._qRouterScrollDebounce);
1287
- const scrollState2 = currentScrollState(scroller);
1288
- saveScrollHistory(scrollState2);
1289
- }
1290
- const navigate = () => {
1291
- clientNavigate(window, navType, prevUrl, trackUrl, replaceState);
1292
- contentInternal.force();
1293
- return internal._waitUntilRendered(elm);
1294
- };
1295
- const _waitNextPage = () => {
1296
- if (core.isServer || props?.viewTransition === false) {
1297
- return navigate();
1298
- } else {
1299
- const viewTransition = startViewTransition({
1300
- update: navigate,
1301
- types: [
1302
- "qwik-navigation"
1303
- ]
1304
- });
1305
- if (!viewTransition) {
1306
- return Promise.resolve();
1307
- }
1308
- return viewTransition.ready;
1309
- }
1310
- };
1311
- _waitNextPage().then(() => {
1312
- const container2 = internal._getQContainerElement(elm);
1313
- container2.setAttribute(Q_ROUTE, routeName);
1314
- const scrollState2 = currentScrollState(scroller);
1315
- saveScrollHistory(scrollState2);
1316
- win._qRouterScrollEnabled = true;
1317
- if (core.isBrowser) {
1318
- callRestoreScrollOnDocument();
1319
- }
1320
- if (shouldForcePrevUrl) {
1321
- internal.forceStoreEffects(routeLocation, "prevUrl");
1322
- }
1323
- if (shouldForceUrl) {
1324
- internal.forceStoreEffects(routeLocation, "url");
1325
- }
1326
- if (shouldForceParams) {
1327
- internal.forceStoreEffects(routeLocation, "params");
1328
- }
1329
- routeLocation.isNavigating = false;
1330
- navResolver.r?.();
1331
- });
1332
- }
1333
- }
1334
- }
1335
- if (core.isServer) {
1336
- return run();
1337
- } else {
1338
- run();
1339
- }
1340
- });
1341
- };
1342
- const QwikRouterProvider = core.component$((props) => {
1343
- useQwikRouter(props);
1344
- return /* @__PURE__ */ jsxRuntime.jsx(core.Slot, {});
1345
- });
1346
- const QwikCityProvider = QwikRouterProvider;
1347
- const useQwikMockRouter = (props) => {
1348
- const urlEnv = props.url ?? "http://localhost/";
1349
- const url = new URL(urlEnv);
1350
- const routeLocation = core.useStore({
1351
- url,
1352
- params: props.params ?? {},
1353
- isNavigating: false,
1354
- prevUrl: void 0
1355
- }, {
1356
- deep: false
1357
- });
1358
- const loaderState = {};
1359
- const routeInternal = core.useSignal({
1360
- type: "initial",
1361
- dest: url
1362
- });
1363
- const goto = props.goto ?? core.$(async () => {
1364
- console.warn("QwikRouterMockProvider: goto not provided");
1365
- });
1366
- const documentHead = core.useStore(createDocumentHead, {
1367
- deep: false
1368
- });
1369
- const content = core.useStore({
1370
- headings: void 0,
1371
- menu: void 0
1372
- }, {
1373
- deep: false
1374
- });
1375
- const contentInternal = core.useSignal();
1376
- const actionState = core.useSignal();
1377
- core.useContextProvider(ContentContext, content);
1378
- core.useContextProvider(ContentInternalContext, contentInternal);
1379
- core.useContextProvider(DocumentHeadContext, documentHead);
1380
- core.useContextProvider(RouteLocationContext, routeLocation);
1381
- core.useContextProvider(RouteNavigateContext, goto);
1382
- core.useContextProvider(RouteStateContext, loaderState);
1383
- core.useContextProvider(RouteActionContext, actionState);
1384
- core.useContextProvider(RouteInternalContext, routeInternal);
1385
- };
1386
- const QwikRouterMockProvider = core.component$((props) => {
1387
- useQwikMockRouter(props);
1388
- return /* @__PURE__ */ jsxRuntime.jsx(core.Slot, {});
1389
- });
1390
- const QwikCityMockProvider = QwikRouterMockProvider;
1391
- const RouterOutlet = core.component$(() => {
1392
- const serverData = core.useServerData("containerAttributes");
1393
- if (!serverData) {
1394
- throw new Error("PrefetchServiceWorker component must be rendered on the server.");
1395
- }
1396
- const internalContext = core.useContext(ContentInternalContext);
1397
- const contents = internalContext.value;
1398
- if (contents && contents.length > 0) {
1399
- const contentsLen = contents.length;
1400
- let cmp = null;
1401
- for (let i = contentsLen - 1; i >= 0; i--) {
1402
- if (contents[i].default) {
1403
- cmp = core.jsx(contents[i].default, {
1404
- children: cmp
1405
- });
1406
- }
1407
- }
1408
- return /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, {
1409
- children: [
1410
- cmp,
1411
- !__EXPERIMENTAL__.noSPA && /* @__PURE__ */ jsxRuntime.jsx("script", {
1412
- "document:onQCInit$": spaInit,
1413
- "document:onQInit$": core.sync$(() => {
1414
- ((w, h) => {
1415
- if (!w._qcs && h.scrollRestoration === "manual") {
1416
- w._qcs = true;
1417
- const s = h.state?._qRouterScroll;
1418
- if (s) {
1419
- w.scrollTo(s.x, s.y);
1420
- }
1421
- document.dispatchEvent(new Event("qcinit"));
1422
- }
1423
- })(window, history);
1424
- })
1425
- })
1426
- ]
1427
- });
1428
- }
1429
- return core.SkipRender;
1430
- });
1431
- var store;
1432
- // @__NO_SIDE_EFFECTS__
1433
- function getGlobalConfig(config2) {
1434
- return {
1435
- lang: config2?.lang ?? store?.lang,
1436
- message: config2?.message,
1437
- abortEarly: config2?.abortEarly ?? store?.abortEarly,
1438
- abortPipeEarly: config2?.abortPipeEarly ?? store?.abortPipeEarly
1439
- };
1440
- }
1441
- // @__NO_SIDE_EFFECTS__
1442
- function getDotPath(issue) {
1443
- if (issue.path) {
1444
- let key = "";
1445
- for (const item of issue.path) {
1446
- if (typeof item.key === "string" || typeof item.key === "number") {
1447
- if (key) {
1448
- key += `.${item.key}`;
1449
- } else {
1450
- key += item.key;
1451
- }
1452
- } else {
1453
- return null;
1454
- }
1455
- }
1456
- return key;
1457
- }
1458
- return null;
1459
- }
1460
- // @__NO_SIDE_EFFECTS__
1461
- function flatten(issues) {
1462
- const flatErrors = {};
1463
- for (const issue of issues) {
1464
- if (issue.path) {
1465
- const dotPath = /* @__PURE__ */ getDotPath(issue);
1466
- if (dotPath) {
1467
- if (!flatErrors.nested) {
1468
- flatErrors.nested = {};
1469
- }
1470
- if (flatErrors.nested[dotPath]) {
1471
- flatErrors.nested[dotPath].push(issue.message);
1472
- } else {
1473
- flatErrors.nested[dotPath] = [issue.message];
1474
- }
1475
- } else {
1476
- if (flatErrors.other) {
1477
- flatErrors.other.push(issue.message);
1478
- } else {
1479
- flatErrors.other = [issue.message];
1480
- }
1481
- }
1482
- } else {
1483
- if (flatErrors.root) {
1484
- flatErrors.root.push(issue.message);
1485
- } else {
1486
- flatErrors.root = [issue.message];
1487
- }
1488
- }
1489
- }
1490
- return flatErrors;
1491
- }
1492
- // @__NO_SIDE_EFFECTS__
1493
- async function safeParseAsync(schema, input, config2) {
1494
- const dataset = await schema["~run"](
1495
- { value: input },
1496
- /* @__PURE__ */ getGlobalConfig(config2)
1497
- );
1498
- return {
1499
- typed: dataset.typed,
1500
- success: !dataset.issues,
1501
- output: dataset.value,
1502
- issues: dataset.issues
1503
- };
1504
- }
1505
- const routeActionQrl = (actionQrl, ...rest) => {
1506
- const { id, validators } = getValidators(rest, actionQrl);
1507
- function action() {
1508
- const loc = useLocation();
1509
- const currentAction = useAction();
1510
- const initialState = {
1511
- actionPath: `?${QACTION_KEY}=${id}`,
1512
- submitted: false,
1513
- isRunning: false,
1514
- status: void 0,
1515
- value: void 0,
1516
- formData: void 0
1517
- };
1518
- const state = core.useStore(() => {
1519
- const value = currentAction.value;
1520
- if (value && value?.id === id) {
1521
- const data = value.data;
1522
- if (data instanceof FormData) {
1523
- initialState.formData = data;
1524
- }
1525
- if (value.output) {
1526
- const { status, result } = value.output;
1527
- initialState.status = status;
1528
- initialState.value = result;
1529
- }
1530
- }
1531
- return initialState;
1532
- });
1533
- const submit = core.$((input = {}) => {
1534
- if (core.isServer) {
1535
- throw new Error(`Actions can not be invoked within the server during SSR.
1536
- Action.run() can only be called on the browser, for example when a user clicks a button, or submits a form.`);
1537
- }
1538
- let data;
1539
- let form;
1540
- if (input instanceof SubmitEvent) {
1541
- form = input.target;
1542
- data = new FormData(form);
1543
- if ((input.submitter instanceof HTMLInputElement || input.submitter instanceof HTMLButtonElement) && input.submitter.name) {
1544
- if (input.submitter.name) {
1545
- data.append(input.submitter.name, input.submitter.value);
1546
- }
1547
- }
1548
- } else {
1549
- data = input;
1550
- }
1551
- return new Promise((resolve) => {
1552
- if (data instanceof FormData) {
1553
- state.formData = data;
1554
- }
1555
- state.submitted = true;
1556
- state.isRunning = true;
1557
- loc.isNavigating = true;
1558
- currentAction.value = {
1559
- data,
1560
- id,
1561
- resolve: core.noSerialize(resolve)
1562
- };
1563
- }).then(({ result, status }) => {
1564
- state.isRunning = false;
1565
- state.status = status;
1566
- state.value = result;
1567
- if (form) {
1568
- if (form.getAttribute("data-spa-reset") === "true") {
1569
- form.reset();
1570
- }
1571
- const detail = {
1572
- status,
1573
- value: result
1574
- };
1575
- form.dispatchEvent(new CustomEvent("submitcompleted", {
1576
- bubbles: false,
1577
- cancelable: false,
1578
- composed: false,
1579
- detail
1580
- }));
1581
- }
1582
- return {
1583
- status,
1584
- value: result
1585
- };
1586
- });
1587
- });
1588
- initialState.submit = submit;
1589
- return state;
1590
- }
1591
- action.__brand = "server_action";
1592
- action.__validators = validators;
1593
- action.__qrl = actionQrl;
1594
- action.__id = id;
1595
- Object.freeze(action);
1596
- return action;
1597
- };
1598
- const globalActionQrl = (actionQrl, ...rest) => {
1599
- const action = routeActionQrl(actionQrl, ...rest);
1600
- if (core.isServer) {
1601
- if (typeof globalThis._qwikActionsMap === "undefined") {
1602
- globalThis._qwikActionsMap = /* @__PURE__ */ new Map();
1603
- }
1604
- globalThis._qwikActionsMap.set(action.__id, action);
1605
- }
1606
- return action;
1607
- };
1608
- const routeAction$ = /* @__PURE__ */ core.implicit$FirstArg(routeActionQrl);
1609
- const globalAction$ = /* @__PURE__ */ core.implicit$FirstArg(globalActionQrl);
1610
- const routeLoaderQrl = (loaderQrl, ...rest) => {
1611
- const { id, validators, serializationStrategy } = getValidators(rest, loaderQrl);
1612
- function loader() {
1613
- const state = internal._resolveContextWithoutSequentialScope(RouteStateContext);
1614
- if (!(id in state)) {
1615
- throw new Error(`routeLoader$ "${loaderQrl.getSymbol()}" was invoked in a route where it was not declared.
1616
- This is because the routeLoader$ was not exported in a 'layout.tsx' or 'index.tsx' file of the existing route.
1617
- For more information check: https://qwik.dev/docs/route-loader/
1618
-
1619
- If your are managing reusable logic or a library it is essential that this function is re-exported from within 'layout.tsx' or 'index.tsx file of the existing route otherwise it will not run or throw exception.
1620
- For more information check: https://qwik.dev/docs/re-exporting-loaders/`);
1621
- }
1622
- core.untrack(() => state[id].value);
1623
- return state[id];
1624
- }
1625
- loader.__brand = "server_loader";
1626
- loader.__qrl = loaderQrl;
1627
- loader.__validators = validators;
1628
- loader.__id = id;
1629
- loader.__serializationStrategy = serializationStrategy;
1630
- Object.freeze(loader);
1631
- return loader;
1632
- };
1633
- const routeLoader$ = /* @__PURE__ */ core.implicit$FirstArg(routeLoaderQrl);
1634
- const validatorQrl = (validator) => {
1635
- if (core.isServer) {
1636
- return {
1637
- validate: validator
1638
- };
1639
- }
1640
- return void 0;
1641
- };
1642
- const validator$ = /* @__PURE__ */ core.implicit$FirstArg(validatorQrl);
1643
- const flattenValibotIssues = (issues) => {
1644
- return issues.reduce((acc, issue) => {
1645
- if (issue.path) {
1646
- const hasArrayType = issue.path.some((path) => path.type === "array");
1647
- if (hasArrayType) {
1648
- const keySuffix = issue.expected === "Array" ? "[]" : "";
1649
- const key = issue.path.map((item) => item.type === "array" ? "*" : item.key).join(".").replace(/\.\*/g, "[]") + keySuffix;
1650
- acc[key] = acc[key] || [];
1651
- if (Array.isArray(acc[key])) {
1652
- acc[key].push(issue.message);
1653
- }
1654
- return acc;
1655
- } else {
1656
- acc[issue.path.map((item) => item.key).join(".")] = issue.message;
1657
- }
1658
- }
1659
- return acc;
1660
- }, {});
1661
- };
1662
- const valibotQrl = (qrl) => {
1663
- if (!__EXPERIMENTAL__.valibot) {
1664
- throw new Error('Valibot is an experimental feature and is not enabled. Please enable the feature flag by adding `experimental: ["valibot"]` to your qwikVite plugin options.');
1665
- }
1666
- if (core.isServer) {
1667
- return {
1668
- __brand: "valibot",
1669
- async validate(ev, inputData) {
1670
- const schema = await qrl.resolve().then((obj) => typeof obj === "function" ? obj(ev) : obj);
1671
- const data = inputData ?? await ev.parseBody();
1672
- const result = await /* @__PURE__ */ safeParseAsync(schema, data);
1673
- if (result.success) {
1674
- return {
1675
- success: true,
1676
- data: result.output
1677
- };
1678
- } else {
1679
- if (core.isDev) {
1680
- console.error("ERROR: Valibot validation failed", result.issues);
1681
- }
1682
- return {
1683
- success: false,
1684
- status: 400,
1685
- error: {
1686
- formErrors: (/* @__PURE__ */ flatten(result.issues)).root ?? [],
1687
- fieldErrors: flattenValibotIssues(result.issues)
1688
- }
1689
- };
1690
- }
1691
- }
1692
- };
1693
- }
1694
- return void 0;
1695
- };
1696
- const valibot$ = /* @__PURE__ */ core.implicit$FirstArg(valibotQrl);
1697
- const flattenZodIssues = (issues) => {
1698
- issues = Array.isArray(issues) ? issues : [
1699
- issues
1700
- ];
1701
- return issues.reduce((acc, issue) => {
1702
- const isExpectingArray = "expected" in issue && issue.expected === "array";
1703
- const hasArrayType = issue.path.some((path) => typeof path === "number") || isExpectingArray;
1704
- if (hasArrayType) {
1705
- const keySuffix = "expected" in issue && issue.expected === "array" ? "[]" : "";
1706
- const key = issue.path.map((path) => typeof path === "number" ? "*" : path).join(".").replace(/\.\*/g, "[]") + keySuffix;
1707
- acc[key] = acc[key] || [];
1708
- if (Array.isArray(acc[key])) {
1709
- acc[key].push(issue.message);
1710
- }
1711
- return acc;
1712
- } else {
1713
- acc[issue.path.join(".")] = issue.message;
1714
- }
1715
- return acc;
1716
- }, {});
1717
- };
1718
- const zodQrl = (qrl) => {
1719
- if (core.isServer) {
1720
- return {
1721
- __brand: "zod",
1722
- async validate(ev, inputData) {
1723
- const schema = await qrl.resolve().then((obj) => {
1724
- if (typeof obj === "function") {
1725
- obj = obj(zod.z, ev);
1726
- }
1727
- if (obj instanceof zod.z.Schema) {
1728
- return obj;
1729
- } else {
1730
- return zod.z.object(obj);
1731
- }
1732
- });
1733
- const data = inputData ?? await ev.parseBody();
1734
- const result = await core.withLocale(ev.locale(), () => schema.safeParseAsync(data));
1735
- if (result.success) {
1736
- return result;
1737
- } else {
1738
- if (core.isDev) {
1739
- console.error("ERROR: Zod validation failed", result.error.issues);
1740
- }
1741
- return {
1742
- success: false,
1743
- status: 400,
1744
- error: {
1745
- formErrors: result.error.flatten().formErrors,
1746
- fieldErrors: flattenZodIssues(result.error.issues)
1747
- }
1748
- };
1749
- }
1750
- }
1751
- };
1752
- }
1753
- return void 0;
1754
- };
1755
- const zod$ = /* @__PURE__ */ core.implicit$FirstArg(zodQrl);
1756
- const serverQrl = (qrl, options) => {
1757
- if (core.isServer) {
1758
- const captured = qrl.getCaptured();
1759
- if (captured && captured.length > 0 && !internal._getContextElement()) {
1760
- throw new Error("For security reasons, we cannot serialize QRLs that capture lexical scope.");
1761
- }
1762
- }
1763
- const method = options?.method?.toUpperCase?.() || "POST";
1764
- const headers = options?.headers || {};
1765
- const origin = options?.origin || "";
1766
- const fetchOptions = options?.fetchOptions || {};
1767
- function rpc() {
1768
- return core.$(async function(...args) {
1769
- const abortSignal = args.length > 0 && args[0] instanceof AbortSignal ? args.shift() : void 0;
1770
- if (core.isServer) {
1771
- let requestEvent = globalThis.qcAsyncRequestStore?.getStore();
1772
- if (!requestEvent) {
1773
- const contexts = [
1774
- useQwikRouterEnv()?.ev,
1775
- this,
1776
- internal._getContextEvent()
1777
- ];
1778
- requestEvent = contexts.find((v2) => v2 && Object.prototype.hasOwnProperty.call(v2, "sharedMap") && Object.prototype.hasOwnProperty.call(v2, "cookie"));
1779
- }
1780
- return qrl.apply(requestEvent, core.isDev ? deepFreeze(args) : args);
1781
- } else {
1782
- const ctxElm = internal._getContextElement();
1783
- const filteredArgs = args.map((arg) => {
1784
- if (arg instanceof SubmitEvent && arg.target instanceof HTMLFormElement) {
1785
- return new FormData(arg.target);
1786
- } else if (arg instanceof Event) {
1787
- return null;
1788
- } else if (arg instanceof Node) {
1789
- return null;
1790
- }
1791
- return arg;
1792
- });
1793
- const qrlHash = qrl.getHash();
1794
- let query = "";
1795
- const config = {
1796
- ...fetchOptions,
1797
- method,
1798
- headers: {
1799
- ...headers,
1800
- "Content-Type": "application/qwik-json",
1801
- Accept: "application/json, application/qwik-json, text/qwik-json-stream, text/plain",
1802
- // Required so we don't call accidentally
1803
- "X-QRL": qrlHash
1804
- },
1805
- signal: abortSignal
1806
- };
1807
- const body = await internal._serialize([
1808
- qrl,
1809
- ...filteredArgs
1810
- ]);
1811
- if (method === "GET") {
1812
- query += `&${QDATA_KEY}=${encodeURIComponent(body)}`;
1813
- } else {
1814
- config.body = body;
1815
- }
1816
- const res = await fetch(`${origin}?${QFN_KEY}=${qrlHash}${query}`, config);
1817
- const contentType = res.headers.get("Content-Type");
1818
- if (res.ok && contentType === "text/qwik-json-stream" && res.body) {
1819
- return (async function* () {
1820
- try {
1821
- for await (const result of deserializeStream(res.body, ctxElm ?? document.documentElement, abortSignal)) {
1822
- yield result;
1823
- }
1824
- } finally {
1825
- if (!abortSignal?.aborted) {
1826
- await res.body.cancel();
1827
- }
1828
- }
1829
- })();
1830
- } else if (contentType === "application/qwik-json") {
1831
- const str = await res.text();
1832
- const [obj] = internal._deserialize(str, ctxElm ?? document.documentElement);
1833
- if (res.status >= 400) {
1834
- throw obj;
1835
- }
1836
- return obj;
1837
- } else if (contentType === "application/json") {
1838
- const obj = await res.json();
1839
- if (res.status >= 400) {
1840
- throw obj;
1841
- }
1842
- return obj;
1843
- } else if (contentType === "text/plain" || contentType === "text/html") {
1844
- const str = await res.text();
1845
- if (res.status >= 400) {
1846
- throw str;
1847
- }
1848
- return str;
1849
- }
1850
- }
1851
- });
1852
- }
1853
- return rpc();
1854
- };
1855
- const server$ = /* @__PURE__ */ core.implicit$FirstArg(serverQrl);
1856
- const getValidators = (rest, qrl) => {
1857
- let id;
1858
- let serializationStrategy = DEFAULT_LOADERS_SERIALIZATION_STRATEGY;
1859
- const validators = [];
1860
- if (rest.length === 1) {
1861
- const options = rest[0];
1862
- if (options && typeof options === "object") {
1863
- if ("validate" in options) {
1864
- validators.push(options);
1865
- } else {
1866
- id = options.id;
1867
- if (options.serializationStrategy) {
1868
- serializationStrategy = options.serializationStrategy;
1869
- }
1870
- if (options.validation) {
1871
- validators.push(...options.validation);
1872
- }
1873
- }
1874
- }
1875
- } else if (rest.length > 1) {
1876
- validators.push(...rest.filter((v2) => !!v2));
1877
- }
1878
- if (typeof id === "string") {
1879
- if (core.isDev) {
1880
- if (!/^[\w/.-]+$/.test(id)) {
1881
- throw new Error(`Invalid id: ${id}, id can only contain [a-zA-Z0-9_.-]`);
1882
- }
1883
- }
1884
- id = `id_${id}`;
1885
- } else {
1886
- id = qrl.getHash();
1887
- }
1888
- return {
1889
- validators: validators.reverse(),
1890
- id,
1891
- serializationStrategy
1892
- };
1893
- };
1894
- const deserializeStream = async function* (stream, ctxElm, abortSignal) {
1895
- const reader = stream.getReader();
1896
- try {
1897
- let buffer = "";
1898
- const decoder = new TextDecoder();
1899
- while (!abortSignal?.aborted) {
1900
- const result = await reader.read();
1901
- if (result.done) {
1902
- break;
1903
- }
1904
- buffer += decoder.decode(result.value, {
1905
- stream: true
1906
- });
1907
- const lines = buffer.split(/\n/);
1908
- buffer = lines.pop();
1909
- for (const line of lines) {
1910
- const [deserializedData] = internal._deserialize(line, ctxElm);
1911
- yield deserializedData;
1912
- }
1913
- }
1914
- } finally {
1915
- reader.releaseLock();
1916
- }
1917
- };
1918
- const ServiceWorkerRegister = (props) => /* @__PURE__ */ jsxRuntime.jsx("script", {
1919
- type: "module",
1920
- dangerouslySetInnerHTML: swRegister,
1921
- nonce: props.nonce
1922
- });
1923
- const Form = ({ action, spaReset, reloadDocument, onSubmit$, ...rest }, key) => {
1924
- if (action) {
1925
- const isArrayApi = Array.isArray(onSubmit$);
1926
- if (isArrayApi) {
1927
- return core.jsx("form", {
1928
- ...rest,
1929
- action: action.actionPath,
1930
- "preventdefault:submit": !reloadDocument,
1931
- onSubmit$: [
1932
- ...onSubmit$,
1933
- // action.submit "submitcompleted" event for onSubmitCompleted$ events
1934
- !reloadDocument ? core.$((evt) => {
1935
- if (!action.submitted) {
1936
- return action.submit(evt);
1937
- }
1938
- }) : void 0
1939
- ],
1940
- method: "post",
1941
- ["data-spa-reset"]: spaReset ? "true" : void 0
1942
- }, key);
1943
- }
1944
- return core.jsx("form", {
1945
- ...rest,
1946
- action: action.actionPath,
1947
- "preventdefault:submit": !reloadDocument,
1948
- onSubmit$: [
1949
- // Since v2, this fires before the action is executed so it can be prevented
1950
- onSubmit$,
1951
- // action.submit "submitcompleted" event for onSubmitCompleted$ events
1952
- !reloadDocument ? action.submit : void 0
1953
- ],
1954
- method: "post",
1955
- ["data-spa-reset"]: spaReset ? "true" : void 0
1956
- }, key);
1957
- } else {
1958
- return /* @__PURE__ */ jsxRuntime.jsx(GetForm, {
1959
- spaReset,
1960
- reloadDocument,
1961
- onSubmit$,
1962
- ...rest
1963
- }, key);
1964
- }
1965
- };
1966
- const GetForm = core.component$(({ action: _0, spaReset, reloadDocument, onSubmit$, ...rest }) => {
1967
- const nav = useNavigate();
1968
- return /* @__PURE__ */ jsxRuntime.jsx("form", {
1969
- action: "get",
1970
- "preventdefault:submit": !reloadDocument,
1971
- "data-spa-reset": spaReset ? "true" : void 0,
1972
- ...rest,
1973
- onSubmit$: [
1974
- ...Array.isArray(onSubmit$) ? onSubmit$ : [
1975
- onSubmit$
1976
- ],
1977
- core.$(async (_evt, form) => {
1978
- const formData = new FormData(form);
1979
- const params = new URLSearchParams();
1980
- formData.forEach((value, key) => {
1981
- if (typeof value === "string") {
1982
- params.append(key, value);
1983
- }
1984
- });
1985
- await nav("?" + params.toString(), {
1986
- type: "form",
1987
- forceReload: true
1988
- });
1989
- }),
1990
- core.$((_evt, form) => {
1991
- if (form.getAttribute("data-spa-reset") === "true") {
1992
- form.reset();
1993
- }
1994
- form.dispatchEvent(new CustomEvent("submitcompleted", {
1995
- bubbles: false,
1996
- cancelable: false,
1997
- composed: false,
1998
- detail: {
1999
- status: 200
2000
- }
2001
- }));
2002
- })
2003
- ],
2004
- children: /* @__PURE__ */ jsxRuntime.jsx(core.Slot, {})
2005
- });
2006
- });
2007
- const untypedAppUrl = function appUrl(route, params, paramsPrefix = "") {
2008
- const path = route.split("/");
2009
- for (let i = 0; i < path.length; i++) {
2010
- const segment = path[i];
2011
- if (segment.startsWith("[") && segment.endsWith("]")) {
2012
- const isSpread = segment.startsWith("[...");
2013
- const key = segment.substring(segment.startsWith("[...") ? 4 : 1, segment.length - 1);
2014
- const value = params ? params[paramsPrefix + key] || params[key] : "";
2015
- path[i] = isSpread ? value : encodeURIComponent(value);
2016
- }
2017
- if (segment.startsWith("(") && segment.endsWith(")")) {
2018
- path.splice(i, 1);
2019
- }
2020
- }
2021
- let url = path.join("/");
2022
- let baseURL = "/";
2023
- if (baseURL) {
2024
- if (!baseURL.endsWith("/")) {
2025
- baseURL += "/";
2026
- }
2027
- while (url.startsWith("/")) {
2028
- url = url.substring(1);
2029
- }
2030
- url = baseURL + url;
2031
- }
2032
- return url;
2033
- };
2034
- function omitProps(obj, keys) {
2035
- const omittedObj = {};
2036
- for (const key in obj) {
2037
- if (!key.startsWith("param:") && !keys.includes(key)) {
2038
- omittedObj[key] = obj[key];
2039
- }
2040
- }
2041
- return omittedObj;
2042
- }
2043
- const createRenderer = (getOptions) => {
2044
- return (opts) => {
2045
- const { jsx, options } = getOptions(opts);
2046
- return server.renderToStream(jsx, options);
2047
- };
2048
- };
2049
- const DocumentHeadTags = core.component$((props) => {
2050
- let head = useDocumentHead();
2051
- if (props) {
2052
- head = {
2053
- ...head,
2054
- ...props
2055
- };
2056
- }
2057
- return /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, {
2058
- children: [
2059
- head.title && /* @__PURE__ */ jsxRuntime.jsx("title", {
2060
- children: head.title
2061
- }),
2062
- head.meta.map((m) => /* @__PURE__ */ jsxRuntime.jsx("meta", {
2063
- ...m
2064
- })),
2065
- head.links.map((l) => /* @__PURE__ */ jsxRuntime.jsx("link", {
2066
- ...l
2067
- })),
2068
- head.styles.map((s) => {
2069
- const props2 = s.props || s;
2070
- return /* @__PURE__ */ core.createElement("style", {
2071
- ...props2,
2072
- dangerouslySetInnerHTML: s.style || props2.dangerouslySetInnerHTML,
2073
- key: s.key
2074
- });
2075
- }),
2076
- head.scripts.map((s) => {
2077
- const props2 = s.props || s;
2078
- return /* @__PURE__ */ core.createElement("script", {
2079
- ...props2,
2080
- dangerouslySetInnerHTML: s.script || props2.dangerouslySetInnerHTML,
2081
- key: s.key
2082
- });
2083
- })
2084
- ]
2085
- });
2086
- });
2087
- Object.defineProperty(exports, "z", {
2088
- enumerable: true,
2089
- get: () => zod.z
2090
- });
2091
- exports.DocumentHeadTags = DocumentHeadTags;
2092
- exports.ErrorBoundary = ErrorBoundary;
2093
- exports.Form = Form;
2094
- exports.Link = Link;
2095
- exports.QWIK_CITY_SCROLLER = QWIK_CITY_SCROLLER;
2096
- exports.QWIK_ROUTER_SCROLLER = QWIK_ROUTER_SCROLLER;
2097
- exports.QwikCityMockProvider = QwikCityMockProvider;
2098
- exports.QwikCityProvider = QwikCityProvider;
2099
- exports.QwikRouterMockProvider = QwikRouterMockProvider;
2100
- exports.QwikRouterProvider = QwikRouterProvider;
2101
- exports.RouterOutlet = RouterOutlet;
2102
- exports.ServiceWorkerRegister = ServiceWorkerRegister;
2103
- exports.createRenderer = createRenderer;
2104
- exports.globalAction$ = globalAction$;
2105
- exports.globalActionQrl = globalActionQrl;
2106
- exports.omitProps = omitProps;
2107
- exports.routeAction$ = routeAction$;
2108
- exports.routeActionQrl = routeActionQrl;
2109
- exports.routeLoader$ = routeLoader$;
2110
- exports.routeLoaderQrl = routeLoaderQrl;
2111
- exports.server$ = server$;
2112
- exports.serverQrl = serverQrl;
2113
- exports.untypedAppUrl = untypedAppUrl;
2114
- exports.useContent = useContent;
2115
- exports.useDocumentHead = useDocumentHead;
2116
- exports.useLocation = useLocation;
2117
- exports.useNavigate = useNavigate;
2118
- exports.usePreventNavigate$ = usePreventNavigate$;
2119
- exports.usePreventNavigateQrl = usePreventNavigateQrl;
2120
- exports.useQwikRouter = useQwikRouter;
2121
- exports.valibot$ = valibot$;
2122
- exports.valibotQrl = valibotQrl;
2123
- exports.validator$ = validator$;
2124
- exports.validatorQrl = validatorQrl;
2125
- exports.zod$ = zod$;
2126
- exports.zodQrl = zodQrl;