@qwik.dev/router 2.0.0-rc.4 → 2.0.0-rc.6

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 { C as getRouteLoaderValues, D as matchesRouteLoaderId, E as loadRouteLoader, P as setRouteLoaders, S as getRouteLoaderResponse, _ as getLoaderRequestEvent, at as QFN_KEY, b as getRouteLoaderCtx, c as FULLPATH_HEADER, ct as normalizeETag, dt as setETagHeader, f as clearRouteLoaderData, ft as RequestEvRouterConfig, ht as isPromise, it as QDATA_KEY, k as resolveRouteLoaderByHash, l as ROUTE_PATH_HEADER, lt as performETagMatch, ot as Q_ROUTE, pt as _asyncRequestStore, r as resolveRouteConfig, rt as QACTION_KEY, st as hash, ut as resolvePreETag, x as getRouteLoaderParams } 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) || "";
53
+ }
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}`;
31
60
  }
32
- function setETagHeader(requestEv, normalizedETag) {
33
- const headerETag = `"${normalizedETag}"`;
34
- requestEv.headers.set("ETag", headerETag);
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,7 +435,10 @@ 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";
440
+ var RequestEvManifestHash = "@manifestHash";
441
+ /** Builds shared request state and controls route handler execution. */
238
442
  function createRequestEvent(serverRequestEv, loadedRoute, requestHandlers, basePathname, resolved, routerConfig) {
239
443
  const { request, platform, env } = serverRequestEv;
240
444
  const sharedMap = /* @__PURE__ */ new Map();
@@ -246,7 +450,7 @@ function createRequestEvent(serverRequestEv, loadedRoute, requestHandlers, baseP
246
450
  if (recognized) {
247
451
  url.pathname = trimRecognizedInternalPathname(url.pathname, recognized);
248
452
  sharedMap.set(recognized.type, true);
249
- internalRequest = "loader";
453
+ if (recognized.type === "@isQLoader") internalRequest = "loader";
250
454
  if (recognized.data?.loaderId) sharedMap.set(QLoaderId, recognized.data.loaderId);
251
455
  }
252
456
  const actionId = url.searchParams.get(QACTION_KEY);
@@ -280,13 +484,14 @@ function createRequestEvent(serverRequestEv, loadedRoute, requestHandlers, baseP
280
484
  const check = () => {
281
485
  if (writableStream !== null) throw new Error("Response already sent");
282
486
  };
487
+ /** Exits the route synchronously while handling stream failures asynchronously. */
283
488
  const send = (statusOrResponse, body) => {
284
489
  check();
490
+ let responseWrite;
285
491
  if (typeof statusOrResponse === "number") {
286
492
  status = statusOrResponse;
287
493
  const writer = requestEv.getWritableStream().getWriter();
288
- writer.write(typeof body === "string" ? encoder.encode(body) : body);
289
- writer.close();
494
+ responseWrite = Promise.all([writer.write(typeof body === "string" ? encoder.encode(body) : body), writer.close()]);
290
495
  } else {
291
496
  status = statusOrResponse.status;
292
497
  statusOrResponse.headers.forEach((value, key) => {
@@ -302,9 +507,14 @@ function createRequestEvent(serverRequestEv, loadedRoute, requestHandlers, baseP
302
507
  });
303
508
  if (statusOrResponse.body) {
304
509
  const writableStream = requestEv.getWritableStream();
305
- statusOrResponse.body.pipeTo(writableStream);
306
- } else requestEv.getWritableStream().getWriter().close();
510
+ responseWrite = statusOrResponse.body.pipeTo(writableStream);
511
+ } else responseWrite = requestEv.getWritableStream().getWriter().close();
307
512
  }
513
+ responseWrite.catch((error) => {
514
+ const signal = request.signal;
515
+ if (signal.aborted && (error instanceof Error && error.name === "AbortError" || error === signal.reason)) return;
516
+ console.error("Response stream failed:", error);
517
+ });
308
518
  return exit();
309
519
  };
310
520
  const exit = (message = new AbortMessage()) => {
@@ -550,265 +760,6 @@ var formToObj = (formData) => {
550
760
  }
551
761
  return values;
552
762
  };
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
763
  /**
813
764
  * Handler for action requests (`?qaction={actionId}`).
814
765
  *
@@ -892,6 +843,21 @@ async function measure$1(requestEv, name, fn) {
892
843
  }
893
844
  }
894
845
  /**
846
+ * Answers `q-route.json` requests with the pathname the URL finally routes to, after any
847
+ * `rewrite()`. It sits after the plugins and route middleware, so a rewrite has already re-resolved
848
+ * the route by the time it runs. Lets the client load a rewrite target it can't match by itself.
849
+ *
850
+ * The response carries the headers set so far, so a middleware can make a rewrite cacheable with
851
+ * `cacheControl()` / `headers.set('Cache-Tag', ...)` before `throw rewrite(...)`.
852
+ */
853
+ function routeResolveHandler() {
854
+ return (requestEv) => {
855
+ if (!requestEv.sharedMap.has("@isQRoute") || requestEv.headersSent || requestEv.exited) return;
856
+ if (!requestEv.headers.has("Cache-Control")) requestEv.cacheControl("private");
857
+ requestEv.json(200, { p: requestEv.url.pathname });
858
+ };
859
+ }
860
+ /**
895
861
  * A set of static paths generated by the SSG, including loader json. Routes always have a trailing
896
862
  * slash, short for `.../index.html`
897
863
  */
@@ -1310,6 +1276,7 @@ function createResolveRequestHandlers() {
1310
1276
  else requestHandlers.unshift(csrfCheckMiddleware);
1311
1277
  }
1312
1278
  if (isPageRoute) {
1279
+ requestHandlers.push(routeResolveHandler());
1313
1280
  requestHandlers.push(loaderHandler(routeLoaders, route));
1314
1281
  requestHandlers.push(actionHandler(routeActions));
1315
1282
  requestHandlers.push(route.$notFound$ ? fixStaticTrailingSlash : fixTrailingSlash);
@@ -1632,14 +1599,12 @@ function createResolveRequestHandlers() {
1632
1599
  checkCSRF(requestEv);
1633
1600
  }
1634
1601
  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.
1602
+ const inputOrigin = requestEv.request.headers.get("origin");
1603
+ const origin = requestEv.url.origin;
1604
+ let forbidden = inputOrigin !== origin;
1605
+ if (forbidden && laxProto && inputOrigin?.replace(/^http(s)?/g, "") === origin.replace(/^http(s)?/g, "")) forbidden = false;
1606
+ if (forbidden) throw requestEv.error(403, `CSRF check failed. Cross-site ${requestEv.method} requests are forbidden.
1641
1607
  The request origin "${inputOrigin}" does not match the server origin "${origin}".`);
1642
- }
1643
1608
  }
1644
1609
  function renderQwikMiddleware(render, trustForwardedHeaders = false) {
1645
1610
  return async (requestEv) => {
@@ -1650,8 +1615,11 @@ The request origin "${inputOrigin}" does not match the server origin "${origin}"
1650
1615
  const { readable, writable } = new TextEncoderStream();
1651
1616
  let responseWriter;
1652
1617
  const lazyResponseSink = new WritableStream({ write(chunk) {
1618
+ if (requestEv.signal.aborted) return;
1653
1619
  responseWriter ||= requestEv.getWritableStream().getWriter();
1654
- return responseWriter.write(chunk);
1620
+ return responseWriter.write(chunk).catch((error) => {
1621
+ if (!requestEv.signal.aborted) throw error;
1622
+ });
1655
1623
  } });
1656
1624
  let cacheChunks;
1657
1625
  let pipeSource = readable;
@@ -1664,11 +1632,15 @@ The request origin "${inputOrigin}" does not match the server origin "${origin}"
1664
1632
  pipeSource = readable.pipeThrough(capture);
1665
1633
  }
1666
1634
  let pipeError;
1635
+ let hasPipeError = false;
1667
1636
  let boundaryErrored = false;
1668
1637
  let noStoreSent = false;
1669
1638
  let overrodeCacheControl = false;
1670
1639
  const pipe = pipeSource.pipeTo(lazyResponseSink, { preventClose: true }).catch((error) => {
1671
- pipeError = error;
1640
+ if (!requestEv.signal.aborted) {
1641
+ hasPipeError = true;
1642
+ pipeError = error;
1643
+ }
1672
1644
  });
1673
1645
  const stream = writable.getWriter();
1674
1646
  try {
@@ -1692,6 +1664,10 @@ The request origin "${inputOrigin}" does not match the server origin "${origin}"
1692
1664
  }
1693
1665
  }
1694
1666
  });
1667
+ if (isStatic) {
1668
+ const renderedAttributes = serverData.containerAttributes;
1669
+ requestEv.sharedMap.set(RequestEvManifestHash, renderedAttributes["q:manifest-hash"] ?? result.manifest?.manifestHash);
1670
+ }
1695
1671
  if (typeof result.html === "string") await stream.write(result.html);
1696
1672
  boundaryErrored ||= result.hasCaughtError === true;
1697
1673
  if (boundaryErrored) requestEv.sharedMap.set(RequestEvCaughtError, true);
@@ -1699,12 +1675,15 @@ The request origin "${inputOrigin}" does not match the server origin "${origin}"
1699
1675
  try {
1700
1676
  await stream.ready;
1701
1677
  await stream.close();
1678
+ } catch (error) {
1679
+ if (!requestEv.signal.aborted) throw error;
1702
1680
  } finally {
1703
1681
  await pipe;
1704
1682
  responseWriter?.releaseLock();
1705
1683
  }
1706
1684
  }
1707
- if (pipeError) throw pipeError;
1685
+ if (hasPipeError) throw pipeError;
1686
+ if (requestEv.signal.aborted) return;
1708
1687
  if (boundaryErrored && (noStoreSent ? cachePlan || overrodeCacheControl : !!cachePlan)) console.warn(`A <Catch> caught during SSR of ${requestEv.url.pathname} — configured caching disabled: ` + (noStoreSent ? "the response was sent with Cache-Control: no-store." : "the SSR cache was skipped (response headers were already sent)."));
1709
1688
  if (cachePlan && cacheChunks && cacheChunks.length > 0 && !boundaryErrored) {
1710
1689
  const totalLength = cacheChunks.reduce((sum, chunk) => sum + chunk.length, 0);
@@ -1721,7 +1700,11 @@ The request origin "${inputOrigin}" does not match the server origin "${origin}"
1721
1700
  body: html
1722
1701
  });
1723
1702
  }
1724
- if (responseWriter) await requestEv.getWritableStream().close();
1703
+ if (responseWriter) try {
1704
+ await requestEv.getWritableStream().close();
1705
+ } catch (error) {
1706
+ if (!requestEv.signal.aborted) throw error;
1707
+ }
1725
1708
  };
1726
1709
  }
1727
1710
  function now() {
@@ -1829,7 +1812,8 @@ async function runNext(requestEv, rebuildRouteInfo, resolve) {
1829
1812
  const message = "Resource Not Found";
1830
1813
  requestEv.status(status);
1831
1814
  requestEv.html(status, getErrorHtml(status, message));
1832
- return new ServerError(status, message);
1815
+ requestEv.sharedMap.set(RequestEvSentServerError, new ServerError(status, message));
1816
+ return;
1833
1817
  }
1834
1818
  let rewriteAttempt = 1;
1835
1819
  async function runOnce() {
@@ -1838,7 +1822,7 @@ async function runNext(requestEv, rebuildRouteInfo, resolve) {
1838
1822
  } catch (e) {
1839
1823
  if (e instanceof RedirectMessage) {
1840
1824
  await requestEv.getWritableStream().close();
1841
- return e;
1825
+ return;
1842
1826
  } else if (e instanceof RewriteMessage) {
1843
1827
  if (rewriteAttempt > 50) return /* @__PURE__ */ new Error(`Infinite rewrite loop`);
1844
1828
  rewriteAttempt += 1;
@@ -1856,9 +1840,10 @@ async function runNext(requestEv, rebuildRouteInfo, resolve) {
1856
1840
  requestEv.headers.set("Content-Type", "application/qwik-json");
1857
1841
  requestEv.send(status, await _serialize(e.data));
1858
1842
  } else requestEv.html(status, getErrorHtml(status, e.data));
1859
- return e;
1843
+ requestEv.sharedMap.set(RequestEvSentServerError, e);
1844
+ return;
1860
1845
  }
1861
- if (!isDev$1) try {
1846
+ if ((!isDev$1 || requestEv.headersSent) && !requestEv.signal.aborted) try {
1862
1847
  if (!requestEv.headersSent) {
1863
1848
  requestEv.headers.set("content-type", "text/html; charset=utf-8");
1864
1849
  requestEv.cacheControl({ noCache: true });
@@ -1867,7 +1852,7 @@ async function runNext(requestEv, rebuildRouteInfo, resolve) {
1867
1852
  const stream = requestEv.getWritableStream();
1868
1853
  if (!stream.locked) {
1869
1854
  const writer = stream.getWriter();
1870
- await writer.write(encoder.encode(getErrorHtml(500, "Internal Server Error")));
1855
+ await writer.write(encoder.encode(getErrorHtml(500, isDev$1 ? e : "Internal Server Error")));
1871
1856
  await writer.close();
1872
1857
  }
1873
1858
  } catch {
@@ -1882,4 +1867,4 @@ async function runNext(requestEv, rebuildRouteInfo, resolve) {
1882
1867
  if (!requestEv.isDirty()) resolve(null);
1883
1868
  }
1884
1869
  }
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 };
1870
+ export { getStaticPathRedirect as a, RequestEvHttpStatusMessage as c, RewriteMessage as d, mergeHeadersCookies as f, clearSsrCache as h, resolveRequestHandlers as i, RequestEvManifestHash as l, clearLoaderCache as m, getErrorHtml as n, isStaticPath as o, resolveLoaderPagePathname as p, renderQwikMiddleware as r, RequestEvCaughtError as s, runQwikRouter as t, RequestEvSentServerError as u };