@qwik.dev/router 2.0.0-rc.4 → 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,62 +1,268 @@
1
1
  import { t as ensureSlash } from "./pathname.mjs";
2
- import { D as getRouteLoaderResponse, E as getRouteLoaderParams, M as matchesRouteLoaderId, O as getRouteLoaderValues, P as resolveRouteLoaderByHash, S as getLoaderRequestEvent, T as getRouteLoaderCtx, _ as clearRouteLoaderData, a as isPromise, ct as QACTION_KEY, dt as Q_ROUTE, ft as RequestEvRouterConfig, j as loadRouteLoader, lt as QDATA_KEY, p as FULLPATH_HEADER, pt as _asyncRequestStore, r as resolveRouteConfig, ut as QFN_KEY, z as setRouteLoaders } from "./head.qwik.mjs";
3
- import { a as QLoaderId, c as resolveValidInternalFullPathname, i as QActionId, s as recognizeRequest, t as IsQAction, u as trimRecognizedInternalPathname } from "./request-path.mjs";
2
+ import { D as resolveRouteLoaderByHash, M as setRouteLoaders, P as isPromise, T as matchesRouteLoaderId, _t as setETagHeader, b as getRouteLoaderResponse, dt as QFN_KEY, ft as Q_ROUTE, gt as resolvePreETag, h as getLoaderRequestEvent, ht as performETagMatch, lt as QACTION_KEY, mt as normalizeETag, o as FULLPATH_HEADER, pt as hash, r as resolveRouteConfig, s as ROUTE_PATH_HEADER, u as clearRouteLoaderData, ut as QDATA_KEY, v as getRouteLoaderCtx, vt as RequestEvRouterConfig, w as loadRouteLoader, x as getRouteLoaderValues, y as getRouteLoaderParams, yt as _asyncRequestStore } from "./head.qwik.mjs";
3
+ import { a as QActionId, c as recognizeRequest, d as trimRecognizedInternalPathname, l as resolveValidInternalFullPathname, o as QLoaderId, t as IsQAction } from "./request-path.mjs";
4
4
  import { a as shareClassIdentity, i as RedirectMessage, n as throwIfControlFlowSignal, r as AbortMessage, t as ServerError } from "./server-error.mjs";
5
5
  import { inlinedQrl, isDev } from "@qwik.dev/core";
6
- import { _deserialize, _serialize, _verifySerializable, isDev as isDev$1 } from "@qwik.dev/core/internal";
6
+ import { _deserialize, _verifySerializable, isDev as isDev$1 } from "@qwik.dev/core/internal";
7
+ import { _serialize } from "@qwik.dev/core/internal/serializer";
8
+ var MAX_CACHE_SIZE = typeof globalThis.__SSR_CACHE_SIZE__ === "number" ? globalThis.__SSR_CACHE_SIZE__ : 50;
9
+ function createLruCache() {
10
+ const cache = /* @__PURE__ */ new Map();
11
+ return {
12
+ get(key) {
13
+ const entry = cache.get(key);
14
+ if (entry !== void 0) {
15
+ cache.delete(key);
16
+ cache.set(key, entry);
17
+ }
18
+ return entry;
19
+ },
20
+ set(key, entry) {
21
+ if (MAX_CACHE_SIZE <= 0) return;
22
+ if (cache.size >= MAX_CACHE_SIZE) {
23
+ const firstKey = cache.keys().next().value;
24
+ cache.delete(firstKey);
25
+ }
26
+ cache.set(key, entry);
27
+ },
28
+ clear(key) {
29
+ if (key != null) cache.delete(key);
30
+ else cache.clear();
31
+ }
32
+ };
33
+ }
34
+ var ssrCache = createLruCache();
35
+ var loaderCache = createLruCache();
7
36
  /**
8
- * FNV-1a 32-bit hash for generating eTags from response data. Cheap to compute, sufficient
9
- * collision resistance for cache validation (not cryptographic).
37
+ * Resolve an eTag value from a ContentModuleETag (string, function, or undefined). Returns the eTag
38
+ * string or null.
10
39
  */
11
- function hash(str) {
12
- let hash = 2166136261;
13
- for (let i = 0; i < str.length; i++) {
14
- hash ^= str.charCodeAt(i);
15
- hash = hash * 16777619 | 0;
16
- }
17
- return (hash >>> 0).toString(36);
40
+ function resolveETag(eTagExport, headProps) {
41
+ if (eTagExport === void 0) return null;
42
+ if (typeof eTagExport === "function") return eTagExport(headProps);
43
+ return eTagExport;
18
44
  }
19
45
  /**
20
- * Normalize an ETag header value (or a single `If-None-Match` entry) into a canonical form so byte
21
- * equality compares the same logical tag. Strips weak ETag syntax (`W/"..."`), quotes, and any
22
- * character outside RFC 7232's `etagc` grammar (printable ASCII except DQUOTE — no escape mechanism
23
- * exists, and non-ASCII bytes are mangled by many HTTP stacks even though `obs-text` technically
24
- * permits them). Idempotent.
46
+ * Resolve a cache key from a CacheKeyFn. The default key callback is only called when `cacheKey ===
47
+ * true`.
25
48
  */
26
- function normalizeETag(raw) {
27
- let tag = raw.trim();
28
- if (tag.endsWith("\"") && tag.startsWith("W/\"")) tag = tag.slice(3);
29
- tag = tag.replace(/[^!#-~]/g, "");
30
- return tag;
49
+ function resolveCacheKey(cacheKeyExport, defaultKey, requestEv, eTag) {
50
+ if (cacheKeyExport === true) return defaultKey(requestEv, eTag);
51
+ if (typeof cacheKeyExport !== "function") return "";
52
+ return cacheKeyExport(requestEv, eTag) || "";
31
53
  }
32
- function setETagHeader(requestEv, normalizedETag) {
33
- const headerETag = `"${normalizedETag}"`;
34
- requestEv.headers.set("ETag", headerETag);
54
+ /** Build the default SSR cache key. eTag slot is dropped when no eTag was resolved. */
55
+ function defaultSsrCacheKey(requestEv, eTag) {
56
+ const status = requestEv.status();
57
+ const { origin, pathname } = requestEv.originalUrl;
58
+ const url = origin + pathname;
59
+ return eTag ? `${status}|${eTag}|${url}` : `${status}|${url}`;
60
+ }
61
+ /** Build the default loader cache key. eTag slot is dropped when no eTag was resolved. */
62
+ function defaultLoaderCacheKey(requestEv, eTag) {
63
+ const loaderId = requestEv.sharedMap.get(QLoaderId);
64
+ const { origin, pathname, search } = requestEv.url;
65
+ const base = `${origin}${pathname}|${search}|${loaderId}`;
66
+ return eTag ? `${base}|${eTag}` : base;
67
+ }
68
+ /** Get a cached SSR entry by key (LRU touch). */
69
+ function getCachedSsr(key) {
70
+ return ssrCache.get(key);
71
+ }
72
+ /** Cache an SSR entry by key, evicting the least recently used entry if at capacity. */
73
+ function setCachedSsr(key, entry) {
74
+ ssrCache.set(key, entry);
75
+ }
76
+ /** Get a cached loader entry by key (LRU touch). */
77
+ function getCachedLoader(key) {
78
+ return loaderCache.get(key);
79
+ }
80
+ /** Cache a loader entry by key, evicting the least recently used entry if at capacity. */
81
+ function setCachedLoader(key, entry) {
82
+ loaderCache.set(key, entry);
35
83
  }
36
84
  /**
37
- * Set the strong ETag header on the response and check the request's `If-None-Match` against it.
38
- * The eTag argument must already be normalized. Returns true if a 304 was sent (caller should stop
39
- * processing).
85
+ * Clear the in-memory SSR cache. Call after deployments or data changes.
86
+ *
87
+ * When `cacheKey` is provided, only that single entry is removed; otherwise the entire cache is
88
+ * cleared.
89
+ *
90
+ * @public
40
91
  */
41
- function performETagMatch(requestEv, normalizedETag, beforeNotModified) {
42
- setETagHeader(requestEv, normalizedETag);
43
- const ifNoneMatch = requestEv.request.headers.get("If-None-Match");
44
- if (ifNoneMatch) {
45
- let found = ifNoneMatch.trim() === "*";
46
- if (!found) {
47
- for (const entry of ifNoneMatch.split(",")) if (normalizeETag(entry) === normalizedETag) {
48
- found = true;
49
- break;
50
- }
92
+ function clearSsrCache(cacheKey) {
93
+ ssrCache.clear(cacheKey);
94
+ }
95
+ /**
96
+ * Clear the in-memory loader cache. Call after deployments or data changes.
97
+ *
98
+ * When `cacheKey` is provided, only that single entry is removed; otherwise the entire cache is
99
+ * cleared.
100
+ *
101
+ * @public
102
+ */
103
+ function clearLoaderCache(cacheKey) {
104
+ loaderCache.clear(cacheKey);
105
+ }
106
+ /**
107
+ * Create per-loader request event views. Loader-specific URL/search data is scoped to the view,
108
+ * while request-wide state (headers, cookies, loader value maps, etc.) still delegates to the
109
+ * original request event.
110
+ */
111
+ function createLoaderRequestEventFactory(requestEv) {
112
+ return (loader) => getLoaderRequestEvent(loader, requestEv);
113
+ }
114
+ /**
115
+ * Handler that executes the requested loader and returns the result as JSON. Runs AFTER
116
+ * plugin/route middleware, so middleware redirects/errors are handled by `jsonRequestWrapper`. The
117
+ * loader function's own redirects/errors are caught by getRouteLoaderResponse and serialized in the
118
+ * LoaderResponse envelope ({ d, r, e }).
119
+ */
120
+ function loaderHandler(routeLoaders, route) {
121
+ return async (requestEvent) => {
122
+ const requestEv = requestEvent;
123
+ if (!requestEv.sharedMap.has("@isQLoader")) return;
124
+ if (requestEv.headersSent || requestEv.exited) return;
125
+ const loaderId = requestEv.sharedMap.get(QLoaderId);
126
+ const loader = resolveRouteLoaderByHash(routeLoaders, loaderId);
127
+ if (!loader) {
128
+ requestEv.json(404, { error: "Loader not found" });
129
+ return;
51
130
  }
52
- if (found) {
53
- beforeNotModified?.();
54
- requestEv.status(304);
55
- requestEv.send(304, "");
56
- return true;
131
+ setRouteLoaderData(requestEv, routeLoaders, route);
132
+ await runRouteGuards(routeLoaders, loader, requestEv);
133
+ const loaderRequestEv = createLoaderRequestEventFactory(requestEv)(loader);
134
+ const cacheControl = resolveLoaderCacheControl(loader.__cacheControl, loaderRequestEv);
135
+ const applyCacheControl = () => {
136
+ if (cacheControl !== null && !requestEv.headers.has("Cache-Control")) requestEv.cacheControl(cacheControl);
137
+ };
138
+ const normalizedETag = loader.__eTag !== void 0 ? resolvePreETag(loader.__eTag, loaderRequestEv) : "";
139
+ if (normalizedETag && performETagMatch(loaderRequestEv, normalizedETag, applyCacheControl)) return;
140
+ let cacheKey = "";
141
+ if (loader.__cacheKey) cacheKey = resolveCacheKey(loader.__cacheKey, defaultLoaderCacheKey, loaderRequestEv, normalizedETag);
142
+ if (cacheKey) {
143
+ const cached = getCachedLoader(cacheKey);
144
+ if (cached) {
145
+ if (!normalizedETag) {
146
+ if (performETagMatch(loaderRequestEv, cached.eTag, applyCacheControl)) return;
147
+ } else setETagHeader(loaderRequestEv, cached.eTag);
148
+ await sendLoaderResponse(requestEv, cached.body, cacheControl);
149
+ return;
150
+ }
57
151
  }
152
+ const responseData = await getRouteLoaderResponse(loader.__qrl, loader.__validators, loaderRequestEv);
153
+ const data = await _serialize(responseData);
154
+ const failed = responseData.d && typeof responseData.d === "object" && responseData.d.failed;
155
+ const cacheable = cacheKey && !responseData.r && !responseData.e && !failed;
156
+ const finalETag = normalizedETag || (cacheable ? hash(data) : "");
157
+ if (cacheable && finalETag) setCachedLoader(cacheKey, {
158
+ eTag: finalETag,
159
+ body: data
160
+ });
161
+ if (!normalizedETag && finalETag && performETagMatch(loaderRequestEv, finalETag, applyCacheControl)) return;
162
+ if (responseData.e || failed) requestEv.headers.set("Cache-Control", "no-store");
163
+ await sendLoaderResponse(requestEv, data, cacheControl);
164
+ };
165
+ }
166
+ /**
167
+ * Resolve the loader's cacheControl option. Loaders default to private revalidation; pair with
168
+ * `eTag` for cheap 304s. A function form may return `null` to skip the header entirely.
169
+ */
170
+ function resolveLoaderCacheControl(option, requestEv) {
171
+ const value = typeof option === "function" ? option(requestEv) : option;
172
+ return value === void 0 ? "private" : value;
173
+ }
174
+ /** Blocking loaders guard the route, so they all run whatever the export order. */
175
+ async function runRouteGuards(routeLoaders, targetLoader, requestEv) {
176
+ for (const loader of routeLoaders) if (loader !== targetLoader && loader.__blockSSR) await loadRouteLoader(loader, requestEv);
177
+ }
178
+ function setRouteLoaderData(requestEv, routeLoaders, route) {
179
+ if (route?.$loaderPaths$) Object.assign(getRouteLoaderCtx(requestEv).loaderPaths, route.$loaderPaths$);
180
+ if (route?.$loaderParams$) Object.assign(getRouteLoaderParams(requestEv), route.$loaderParams$);
181
+ setRouteLoaders(requestEv, routeLoaders);
182
+ }
183
+ async function sendLoaderResponse(requestEv, data, cacheControl) {
184
+ requestEv.headers.set("Content-Type", "application/json; charset=utf-8");
185
+ addVaryHeader(requestEv, FULLPATH_HEADER);
186
+ if (isDev) addVaryHeader(requestEv, ROUTE_PATH_HEADER);
187
+ if (cacheControl !== null && !requestEv.headers.has("Cache-Control")) requestEv.cacheControl(cacheControl);
188
+ requestEv.send(200, data);
189
+ }
190
+ function addVaryHeader(requestEv, value) {
191
+ const vary = requestEv.headers.get("Vary");
192
+ if (!vary) {
193
+ requestEv.headers.set("Vary", value);
194
+ return;
58
195
  }
59
- return false;
196
+ if (!vary.split(",").map((item) => item.trim().toLowerCase()).includes(value.toLowerCase())) requestEv.headers.set("Vary", `${vary}, ${value}`);
197
+ }
198
+ /** Serialize and send a JSON response (used by error/redirect paths in jsonRequestWrapper). */
199
+ async function sendJsonResponse(requestEv, responseData, status = 200) {
200
+ const data = await _serialize(responseData);
201
+ requestEv.headers.set("Content-Type", "application/json; charset=utf-8");
202
+ if (!requestEv.headers.has("Cache-Control")) requestEv.cacheControl("private");
203
+ requestEv.send(status, data);
204
+ }
205
+ async function sendActionResponse(requestEv, responseData) {
206
+ const data = await _serialize(responseData);
207
+ requestEv.headers.set("Content-Type", "application/json; charset=utf-8");
208
+ requestEv.send(responseData.s || 200, data);
209
+ }
210
+ /** Shared by route selection and the URL rewrite so both agree on the page. */
211
+ function resolveLoaderPagePathname(request, loaderPathname, isDevRequest = isDev) {
212
+ const routePath = request.headers.get("X-Qwik-fullpath") ?? (isDevRequest ? request.headers.get("X-Qwik-route-path") : null);
213
+ return resolveValidInternalFullPathname(loaderPathname, routePath);
214
+ }
215
+ /**
216
+ * Early handler that wraps `next()` for JSON API requests (q-loader and q-action).
217
+ *
218
+ * For `IsQLoader` requests, it also rewrites the URL using the `X-Qwik-fullpath` header (or the dev
219
+ * `X-Qwik-route-path` header) so that downstream middleware sees the real page URL.
220
+ *
221
+ * By calling `await next()` inside a try/catch, middleware redirects and errors are captured and
222
+ * returned as JSON envelopes instead of HTTP redirects/error pages. This keeps SPA navigation
223
+ * intact on the client.
224
+ */
225
+ function jsonRequestWrapper() {
226
+ return async (requestEvent) => {
227
+ const requestEv = requestEvent;
228
+ const isLoader = requestEv.internalRequest === "loader";
229
+ const isActionJson = requestEv.internalRequest === "action";
230
+ if (!isLoader && !isActionJson) return;
231
+ if (isLoader) {
232
+ addVaryHeader(requestEv, FULLPATH_HEADER);
233
+ if (isDev) addVaryHeader(requestEv, ROUTE_PATH_HEADER);
234
+ const pagePathname = resolveLoaderPagePathname(requestEv.request, requestEv.url.pathname);
235
+ if (pagePathname) requestEv.url.pathname = pagePathname;
236
+ }
237
+ try {
238
+ await requestEv.next();
239
+ } catch (err) {
240
+ if (requestEv.headersSent) return;
241
+ if (err instanceof RedirectMessage) {
242
+ const location = requestEv.headers.get("Location") || "/";
243
+ requestEv.headers.delete("Location");
244
+ if (isLoader) await sendJsonResponse(requestEv, { r: location });
245
+ else await sendActionResponse(requestEv, { redirect: location });
246
+ } else if (err instanceof ServerError) {
247
+ requestEv.headers.set("Cache-Control", "no-store");
248
+ if (isLoader) await sendJsonResponse(requestEv, { e: err });
249
+ else await sendActionResponse(requestEv, {
250
+ e: err,
251
+ s: err.status
252
+ });
253
+ } else if (err instanceof Error) {
254
+ console.error("JSON request error:", err);
255
+ requestEv.headers.set("Cache-Control", "no-store");
256
+ const message = isDev ? `${err.message}\n(this is only visible in dev mode)` : "Internal Server Error";
257
+ const se = new ServerError(500, message);
258
+ if (isLoader) await sendJsonResponse(requestEv, { e: se });
259
+ else await sendActionResponse(requestEv, {
260
+ e: se,
261
+ s: 500
262
+ });
263
+ } else throw err;
264
+ }
265
+ };
60
266
  }
61
267
  function createCacheControl(cacheControl) {
62
268
  const controls = [];
@@ -219,11 +425,6 @@ var encoder = /*#__PURE__*/ new TextEncoder();
219
425
  function getContentType(headers) {
220
426
  return (headers.get("content-type")?.split(/[;,]/, 1)[0].trim() ?? "").toLowerCase();
221
427
  }
222
- function isContentType(headers, ...types) {
223
- const type = getContentType(headers);
224
- for (let i = 0; i < types.length; i++) if (types[i].toLowerCase() === type) return true;
225
- return false;
226
- }
227
428
  var RequestEvMode = Symbol("RequestEvMode");
228
429
  var RequestEvRoute = Symbol("RequestEvRoute");
229
430
  var RequestRouteName = "@routeName";
@@ -234,6 +435,7 @@ var RequestEvIsRewrite = "@rewrite";
234
435
  var RequestEvShareServerTiming = "@serverTiming";
235
436
  var RequestEvETagCacheKey = "@eTagCacheKey";
236
437
  var RequestEvCaughtError = "@caughtError";
438
+ var RequestEvSentServerError = "@sentServerError";
237
439
  var RequestEvHttpStatusMessage = "@httpStatusMessage";
238
440
  function createRequestEvent(serverRequestEv, loadedRoute, requestHandlers, basePathname, resolved, routerConfig) {
239
441
  const { request, platform, env } = serverRequestEv;
@@ -246,7 +448,7 @@ function createRequestEvent(serverRequestEv, loadedRoute, requestHandlers, baseP
246
448
  if (recognized) {
247
449
  url.pathname = trimRecognizedInternalPathname(url.pathname, recognized);
248
450
  sharedMap.set(recognized.type, true);
249
- internalRequest = "loader";
451
+ if (recognized.type === "@isQLoader") internalRequest = "loader";
250
452
  if (recognized.data?.loaderId) sharedMap.set(QLoaderId, recognized.data.loaderId);
251
453
  }
252
454
  const actionId = url.searchParams.get(QACTION_KEY);
@@ -550,265 +752,6 @@ var formToObj = (formData) => {
550
752
  }
551
753
  return values;
552
754
  };
553
- var MAX_CACHE_SIZE = typeof globalThis.__SSR_CACHE_SIZE__ === "number" ? globalThis.__SSR_CACHE_SIZE__ : 50;
554
- function createLruCache() {
555
- const cache = /* @__PURE__ */ new Map();
556
- return {
557
- get(key) {
558
- const entry = cache.get(key);
559
- if (entry !== void 0) {
560
- cache.delete(key);
561
- cache.set(key, entry);
562
- }
563
- return entry;
564
- },
565
- set(key, entry) {
566
- if (MAX_CACHE_SIZE <= 0) return;
567
- if (cache.size >= MAX_CACHE_SIZE) {
568
- const firstKey = cache.keys().next().value;
569
- cache.delete(firstKey);
570
- }
571
- cache.set(key, entry);
572
- },
573
- clear(key) {
574
- if (key != null) cache.delete(key);
575
- else cache.clear();
576
- }
577
- };
578
- }
579
- var ssrCache = createLruCache();
580
- var loaderCache = createLruCache();
581
- /**
582
- * Resolve an eTag value from a ContentModuleETag (string, function, or undefined). Returns the eTag
583
- * string or null.
584
- */
585
- function resolveETag(eTagExport, headProps) {
586
- if (eTagExport === void 0) return null;
587
- if (typeof eTagExport === "function") return eTagExport(headProps);
588
- return eTagExport;
589
- }
590
- /**
591
- * Resolve a cache key from a CacheKeyFn. The default key callback is only called when `cacheKey ===
592
- * true`.
593
- */
594
- function resolveCacheKey(cacheKeyExport, defaultKey, requestEv, eTag) {
595
- if (cacheKeyExport === true) return defaultKey(requestEv, eTag);
596
- if (typeof cacheKeyExport !== "function") return "";
597
- return cacheKeyExport(requestEv, eTag) || "";
598
- }
599
- /** Build the default SSR cache key. eTag slot is dropped when no eTag was resolved. */
600
- function defaultSsrCacheKey(requestEv, eTag) {
601
- const status = requestEv.status();
602
- const { origin, pathname } = requestEv.originalUrl;
603
- const url = origin + pathname;
604
- return eTag ? `${status}|${eTag}|${url}` : `${status}|${url}`;
605
- }
606
- /** Build the default loader cache key. eTag slot is dropped when no eTag was resolved. */
607
- function defaultLoaderCacheKey(requestEv, eTag) {
608
- const loaderId = requestEv.sharedMap.get(QLoaderId);
609
- const { origin, pathname, search } = requestEv.url;
610
- const base = `${origin}${pathname}|${search}|${loaderId}`;
611
- return eTag ? `${base}|${eTag}` : base;
612
- }
613
- /** Get a cached SSR entry by key (LRU touch). */
614
- function getCachedSsr(key) {
615
- return ssrCache.get(key);
616
- }
617
- /** Cache an SSR entry by key, evicting the least recently used entry if at capacity. */
618
- function setCachedSsr(key, entry) {
619
- ssrCache.set(key, entry);
620
- }
621
- /** Get a cached loader entry by key (LRU touch). */
622
- function getCachedLoader(key) {
623
- return loaderCache.get(key);
624
- }
625
- /** Cache a loader entry by key, evicting the least recently used entry if at capacity. */
626
- function setCachedLoader(key, entry) {
627
- loaderCache.set(key, entry);
628
- }
629
- /**
630
- * Clear the in-memory SSR cache. Call after deployments or data changes.
631
- *
632
- * When `cacheKey` is provided, only that single entry is removed; otherwise the entire cache is
633
- * cleared.
634
- *
635
- * @public
636
- */
637
- function clearSsrCache(cacheKey) {
638
- ssrCache.clear(cacheKey);
639
- }
640
- /**
641
- * Clear the in-memory loader cache. Call after deployments or data changes.
642
- *
643
- * When `cacheKey` is provided, only that single entry is removed; otherwise the entire cache is
644
- * cleared.
645
- *
646
- * @public
647
- */
648
- function clearLoaderCache(cacheKey) {
649
- loaderCache.clear(cacheKey);
650
- }
651
- /**
652
- * Create per-loader request event views. Loader-specific URL/search data is scoped to the view,
653
- * while request-wide state (headers, cookies, loader value maps, etc.) still delegates to the
654
- * original request event.
655
- */
656
- function createLoaderRequestEventFactory(requestEv) {
657
- return (loader) => getLoaderRequestEvent(loader, requestEv);
658
- }
659
- /**
660
- * Handler that executes the requested loader and returns the result as JSON. Runs AFTER
661
- * plugin/route middleware, so middleware redirects/errors are handled by `jsonRequestWrapper`. The
662
- * loader function's own redirects/errors are caught by getRouteLoaderResponse and serialized in the
663
- * LoaderResponse envelope ({ d, r, e }).
664
- */
665
- function loaderHandler(routeLoaders, route) {
666
- return async (requestEvent) => {
667
- const requestEv = requestEvent;
668
- if (!requestEv.sharedMap.has("@isQLoader")) return;
669
- if (requestEv.headersSent || requestEv.exited) return;
670
- const loaderId = requestEv.sharedMap.get(QLoaderId);
671
- const loader = resolveRouteLoaderByHash(routeLoaders, loaderId);
672
- if (!loader) {
673
- requestEv.json(404, { error: "Loader not found" });
674
- return;
675
- }
676
- setRouteLoaderData(requestEv, routeLoaders, route);
677
- await runRouteGuards(routeLoaders, loader, requestEv);
678
- const loaderRequestEv = createLoaderRequestEventFactory(requestEv)(loader);
679
- const cacheControl = resolveLoaderCacheControl(loader.__cacheControl, loaderRequestEv);
680
- const applyCacheControl = () => {
681
- if (cacheControl !== null && !requestEv.headers.has("Cache-Control")) requestEv.cacheControl(cacheControl);
682
- };
683
- const normalizedETag = loader.__eTag !== void 0 ? resolvePreETag(loader.__eTag, loaderRequestEv) : "";
684
- if (normalizedETag && performETagMatch(loaderRequestEv, normalizedETag, applyCacheControl)) return;
685
- let cacheKey = "";
686
- if (loader.__cacheKey) cacheKey = resolveCacheKey(loader.__cacheKey, defaultLoaderCacheKey, loaderRequestEv, normalizedETag);
687
- if (cacheKey) {
688
- const cached = getCachedLoader(cacheKey);
689
- if (cached) {
690
- if (!normalizedETag) {
691
- if (performETagMatch(loaderRequestEv, cached.eTag, applyCacheControl)) return;
692
- } else setETagHeader(loaderRequestEv, cached.eTag);
693
- await sendLoaderResponse(requestEv, cached.body, cacheControl);
694
- return;
695
- }
696
- }
697
- const responseData = await getRouteLoaderResponse(loader.__qrl, loader.__validators, loaderRequestEv);
698
- const data = await _serialize(responseData);
699
- const failed = responseData.d && typeof responseData.d === "object" && responseData.d.failed;
700
- const cacheable = cacheKey && !responseData.r && !responseData.e && !failed;
701
- const finalETag = normalizedETag || (cacheable ? hash(data) : "");
702
- if (cacheable && finalETag) setCachedLoader(cacheKey, {
703
- eTag: finalETag,
704
- body: data
705
- });
706
- if (!normalizedETag && finalETag && performETagMatch(loaderRequestEv, finalETag, applyCacheControl)) return;
707
- if (responseData.e || failed) requestEv.headers.set("Cache-Control", "no-store");
708
- await sendLoaderResponse(requestEv, data, cacheControl);
709
- };
710
- }
711
- /**
712
- * Resolve the loader's cacheControl option. Loaders default to private revalidation; pair with
713
- * `eTag` for cheap 304s. A function form may return `null` to skip the header entirely.
714
- */
715
- function resolveLoaderCacheControl(option, requestEv) {
716
- const value = typeof option === "function" ? option(requestEv) : option;
717
- return value === void 0 ? "private" : value;
718
- }
719
- /** Blocking loaders guard the route, so they all run whatever the export order. */
720
- async function runRouteGuards(routeLoaders, targetLoader, requestEv) {
721
- for (const loader of routeLoaders) if (loader !== targetLoader && loader.__blockSSR) await loadRouteLoader(loader, requestEv);
722
- }
723
- function setRouteLoaderData(requestEv, routeLoaders, route) {
724
- if (route?.$loaderPaths$) Object.assign(getRouteLoaderCtx(requestEv).loaderPaths, route.$loaderPaths$);
725
- if (route?.$loaderParams$) Object.assign(getRouteLoaderParams(requestEv), route.$loaderParams$);
726
- setRouteLoaders(requestEv, routeLoaders);
727
- }
728
- /** Resolve eTag from a static string or function (before running the loader). */
729
- function resolvePreETag(eTagOption, requestEv) {
730
- if (typeof eTagOption === "string") return normalizeETag(eTagOption);
731
- const result = eTagOption(requestEv);
732
- return result ? normalizeETag(result) : "";
733
- }
734
- async function sendLoaderResponse(requestEv, data, cacheControl) {
735
- requestEv.headers.set("Content-Type", "application/json; charset=utf-8");
736
- addVaryHeader(requestEv, FULLPATH_HEADER);
737
- if (cacheControl !== null && !requestEv.headers.has("Cache-Control")) requestEv.cacheControl(cacheControl);
738
- requestEv.send(200, data);
739
- }
740
- function addVaryHeader(requestEv, value) {
741
- const vary = requestEv.headers.get("Vary");
742
- if (!vary) {
743
- requestEv.headers.set("Vary", value);
744
- return;
745
- }
746
- if (!vary.split(",").map((item) => item.trim().toLowerCase()).includes(value.toLowerCase())) requestEv.headers.set("Vary", `${vary}, ${value}`);
747
- }
748
- /** Serialize and send a JSON response (used by error/redirect paths in jsonRequestWrapper). */
749
- async function sendJsonResponse(requestEv, responseData, status = 200) {
750
- const data = await _serialize(responseData);
751
- requestEv.headers.set("Content-Type", "application/json; charset=utf-8");
752
- if (!requestEv.headers.has("Cache-Control")) requestEv.cacheControl("private");
753
- requestEv.send(status, data);
754
- }
755
- async function sendActionResponse(requestEv, responseData) {
756
- const data = await _serialize(responseData);
757
- requestEv.headers.set("Content-Type", "application/json; charset=utf-8");
758
- requestEv.send(responseData.s || 200, data);
759
- }
760
- /**
761
- * Early handler that wraps `next()` for JSON API requests (q-loader and q-action).
762
- *
763
- * For `IsQLoader` requests, it also rewrites the URL using the `X-Qwik-fullpath` header so that
764
- * downstream middleware sees the real page URL.
765
- *
766
- * By calling `await next()` inside a try/catch, middleware redirects and errors are captured and
767
- * returned as JSON envelopes instead of HTTP redirects/error pages. This keeps SPA navigation
768
- * intact on the client.
769
- */
770
- function jsonRequestWrapper() {
771
- return async (requestEvent) => {
772
- const requestEv = requestEvent;
773
- const isLoader = requestEv.internalRequest === "loader";
774
- const isActionJson = requestEv.internalRequest === "action";
775
- if (!isLoader && !isActionJson) return;
776
- if (isLoader) {
777
- addVaryHeader(requestEv, FULLPATH_HEADER);
778
- const pagePath = requestEv.request.headers.get(FULLPATH_HEADER);
779
- const pagePathname = resolveValidInternalFullPathname(requestEv.url.pathname, pagePath);
780
- if (pagePathname) requestEv.url.pathname = pagePathname;
781
- }
782
- try {
783
- await requestEv.next();
784
- } catch (err) {
785
- if (requestEv.headersSent) return;
786
- if (err instanceof RedirectMessage) {
787
- const location = requestEv.headers.get("Location") || "/";
788
- requestEv.headers.delete("Location");
789
- if (isLoader) await sendJsonResponse(requestEv, { r: location });
790
- else await sendActionResponse(requestEv, { redirect: location });
791
- } else if (err instanceof ServerError) {
792
- requestEv.headers.set("Cache-Control", "no-store");
793
- if (isLoader) await sendJsonResponse(requestEv, { e: err });
794
- else await sendActionResponse(requestEv, {
795
- e: err,
796
- s: err.status
797
- });
798
- } else if (err instanceof Error) {
799
- console.error("JSON request error:", err);
800
- requestEv.headers.set("Cache-Control", "no-store");
801
- const message = isDev ? `${err.message}\n(this is only visible in dev mode)` : "Internal Server Error";
802
- const se = new ServerError(500, message);
803
- if (isLoader) await sendJsonResponse(requestEv, { e: se });
804
- else await sendActionResponse(requestEv, {
805
- e: se,
806
- s: 500
807
- });
808
- } else throw err;
809
- }
810
- };
811
- }
812
755
  /**
813
756
  * Handler for action requests (`?qaction={actionId}`).
814
757
  *
@@ -892,6 +835,21 @@ async function measure$1(requestEv, name, fn) {
892
835
  }
893
836
  }
894
837
  /**
838
+ * Answers `q-route.json` requests with the pathname the URL finally routes to, after any
839
+ * `rewrite()`. It sits after the plugins and route middleware, so a rewrite has already re-resolved
840
+ * the route by the time it runs. Lets the client load a rewrite target it can't match by itself.
841
+ *
842
+ * The response carries the headers set so far, so a middleware can make a rewrite cacheable with
843
+ * `cacheControl()` / `headers.set('Cache-Tag', ...)` before `throw rewrite(...)`.
844
+ */
845
+ function routeResolveHandler() {
846
+ return (requestEv) => {
847
+ if (!requestEv.sharedMap.has("@isQRoute") || requestEv.headersSent || requestEv.exited) return;
848
+ if (!requestEv.headers.has("Cache-Control")) requestEv.cacheControl("private");
849
+ requestEv.json(200, { p: requestEv.url.pathname });
850
+ };
851
+ }
852
+ /**
895
853
  * A set of static paths generated by the SSG, including loader json. Routes always have a trailing
896
854
  * slash, short for `.../index.html`
897
855
  */
@@ -1310,6 +1268,7 @@ function createResolveRequestHandlers() {
1310
1268
  else requestHandlers.unshift(csrfCheckMiddleware);
1311
1269
  }
1312
1270
  if (isPageRoute) {
1271
+ requestHandlers.push(routeResolveHandler());
1313
1272
  requestHandlers.push(loaderHandler(routeLoaders, route));
1314
1273
  requestHandlers.push(actionHandler(routeActions));
1315
1274
  requestHandlers.push(route.$notFound$ ? fixStaticTrailingSlash : fixTrailingSlash);
@@ -1632,14 +1591,12 @@ function createResolveRequestHandlers() {
1632
1591
  checkCSRF(requestEv);
1633
1592
  }
1634
1593
  function checkCSRF(requestEv, laxProto) {
1635
- if (!requestEv.request.headers.get("content-type") || isContentType(requestEv.request.headers, "application/x-www-form-urlencoded", "multipart/form-data", "text/plain")) {
1636
- const inputOrigin = requestEv.request.headers.get("origin");
1637
- const origin = requestEv.url.origin;
1638
- let forbidden = inputOrigin !== origin;
1639
- if (forbidden && laxProto && inputOrigin?.replace(/^http(s)?/g, "") === origin.replace(/^http(s)?/g, "")) forbidden = false;
1640
- if (forbidden) throw requestEv.error(403, `CSRF check failed. Cross-site ${requestEv.method} form submissions are forbidden.
1594
+ const inputOrigin = requestEv.request.headers.get("origin");
1595
+ const origin = requestEv.url.origin;
1596
+ let forbidden = inputOrigin !== origin;
1597
+ if (forbidden && laxProto && inputOrigin?.replace(/^http(s)?/g, "") === origin.replace(/^http(s)?/g, "")) forbidden = false;
1598
+ if (forbidden) throw requestEv.error(403, `CSRF check failed. Cross-site ${requestEv.method} requests are forbidden.
1641
1599
  The request origin "${inputOrigin}" does not match the server origin "${origin}".`);
1642
- }
1643
1600
  }
1644
1601
  function renderQwikMiddleware(render, trustForwardedHeaders = false) {
1645
1602
  return async (requestEv) => {
@@ -1829,7 +1786,8 @@ async function runNext(requestEv, rebuildRouteInfo, resolve) {
1829
1786
  const message = "Resource Not Found";
1830
1787
  requestEv.status(status);
1831
1788
  requestEv.html(status, getErrorHtml(status, message));
1832
- return new ServerError(status, message);
1789
+ requestEv.sharedMap.set(RequestEvSentServerError, new ServerError(status, message));
1790
+ return;
1833
1791
  }
1834
1792
  let rewriteAttempt = 1;
1835
1793
  async function runOnce() {
@@ -1838,7 +1796,7 @@ async function runNext(requestEv, rebuildRouteInfo, resolve) {
1838
1796
  } catch (e) {
1839
1797
  if (e instanceof RedirectMessage) {
1840
1798
  await requestEv.getWritableStream().close();
1841
- return e;
1799
+ return;
1842
1800
  } else if (e instanceof RewriteMessage) {
1843
1801
  if (rewriteAttempt > 50) return /* @__PURE__ */ new Error(`Infinite rewrite loop`);
1844
1802
  rewriteAttempt += 1;
@@ -1856,9 +1814,10 @@ async function runNext(requestEv, rebuildRouteInfo, resolve) {
1856
1814
  requestEv.headers.set("Content-Type", "application/qwik-json");
1857
1815
  requestEv.send(status, await _serialize(e.data));
1858
1816
  } else requestEv.html(status, getErrorHtml(status, e.data));
1859
- return e;
1817
+ requestEv.sharedMap.set(RequestEvSentServerError, e);
1818
+ return;
1860
1819
  }
1861
- if (!isDev$1) try {
1820
+ if (!isDev$1 || requestEv.headersSent) try {
1862
1821
  if (!requestEv.headersSent) {
1863
1822
  requestEv.headers.set("content-type", "text/html; charset=utf-8");
1864
1823
  requestEv.cacheControl({ noCache: true });
@@ -1867,7 +1826,7 @@ async function runNext(requestEv, rebuildRouteInfo, resolve) {
1867
1826
  const stream = requestEv.getWritableStream();
1868
1827
  if (!stream.locked) {
1869
1828
  const writer = stream.getWriter();
1870
- await writer.write(encoder.encode(getErrorHtml(500, "Internal Server Error")));
1829
+ await writer.write(encoder.encode(getErrorHtml(500, isDev$1 ? e : "Internal Server Error")));
1871
1830
  await writer.close();
1872
1831
  }
1873
1832
  } catch {
@@ -1882,4 +1841,4 @@ async function runNext(requestEv, rebuildRouteInfo, resolve) {
1882
1841
  if (!requestEv.isDirty()) resolve(null);
1883
1842
  }
1884
1843
  }
1885
- export { getStaticPathRedirect as a, clearSsrCache as c, mergeHeadersCookies as d, resolveRequestHandlers as i, RequestEvCaughtError as l, getErrorHtml as n, isStaticPath as o, renderQwikMiddleware as r, clearLoaderCache as s, runQwikRouter as t, RewriteMessage as u };
1844
+ export { getStaticPathRedirect as a, RequestEvHttpStatusMessage as c, mergeHeadersCookies as d, resolveLoaderPagePathname as f, resolveRequestHandlers as i, RequestEvSentServerError as l, clearSsrCache as m, getErrorHtml as n, isStaticPath as o, clearLoaderCache as p, renderQwikMiddleware as r, RequestEvCaughtError as s, runQwikRouter as t, RewriteMessage as u };