@qwik.dev/router 2.0.0-beta.10 → 2.0.0-beta.13

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 (140) hide show
  1. package/lib/adapters/azure-swa/vite/index.cjs +61 -5
  2. package/lib/adapters/azure-swa/vite/index.mjs +26 -201
  3. package/lib/adapters/bun-server/vite/index.cjs +27 -5
  4. package/lib/adapters/bun-server/vite/index.mjs +14 -196
  5. package/lib/adapters/cloud-run/vite/index.cjs +24 -5
  6. package/lib/adapters/cloud-run/vite/index.mjs +13 -195
  7. package/lib/adapters/cloudflare-pages/vite/index.cjs +65 -1
  8. package/lib/adapters/cloudflare-pages/vite/index.mjs +63 -4
  9. package/lib/adapters/deno-server/vite/index.cjs +39 -5
  10. package/lib/adapters/deno-server/vite/index.mjs +16 -198
  11. package/lib/adapters/netlify-edge/vite/index.cjs +88 -6
  12. package/lib/adapters/netlify-edge/vite/index.mjs +56 -240
  13. package/lib/adapters/node-server/vite/index.cjs +27 -5
  14. package/lib/adapters/node-server/vite/index.mjs +14 -196
  15. package/lib/adapters/shared/vite/index.cjs +303 -2
  16. package/lib/adapters/shared/vite/index.d.ts +4 -4
  17. package/lib/adapters/shared/vite/index.mjs +248 -143
  18. package/lib/adapters/ssg/vite/index.cjs +19 -5
  19. package/lib/adapters/ssg/vite/index.mjs +11 -193
  20. package/lib/adapters/vercel-edge/vite/index.cjs +81 -5
  21. package/lib/adapters/vercel-edge/vite/index.d.ts +1 -1
  22. package/lib/adapters/vercel-edge/vite/index.mjs +48 -229
  23. package/lib/chunks/error-handler.cjs +58 -0
  24. package/lib/chunks/error-handler.mjs +59 -0
  25. package/lib/chunks/format-error.cjs +136 -0
  26. package/lib/chunks/format-error.mjs +137 -0
  27. package/lib/chunks/fs.cjs +274 -0
  28. package/lib/chunks/fs.mjs +275 -0
  29. package/lib/chunks/index.cjs +877 -0
  30. package/lib/chunks/index.mjs +876 -0
  31. package/lib/chunks/mime-types.cjs +52 -0
  32. package/lib/chunks/mime-types.mjs +53 -0
  33. package/lib/chunks/routing.qwik.cjs +452 -0
  34. package/lib/chunks/routing.qwik.mjs +453 -0
  35. package/lib/chunks/types.qwik.cjs +24 -0
  36. package/lib/chunks/types.qwik.mjs +25 -0
  37. package/lib/index.d.ts +9 -3
  38. package/lib/index.qwik.cjs +543 -1001
  39. package/lib/index.qwik.mjs +512 -972
  40. package/lib/middleware/aws-lambda/index.cjs +52 -1
  41. package/lib/middleware/aws-lambda/index.mjs +37 -26
  42. package/lib/middleware/azure-swa/index.cjs +92 -1
  43. package/lib/middleware/azure-swa/index.mjs +64 -46
  44. package/lib/middleware/bun/index.cjs +143 -1
  45. package/lib/middleware/bun/index.mjs +103 -117
  46. package/lib/middleware/cloudflare-pages/index.cjs +96 -1
  47. package/lib/middleware/cloudflare-pages/index.mjs +68 -47
  48. package/lib/middleware/deno/index.cjs +130 -1
  49. package/lib/middleware/deno/index.mjs +93 -112
  50. package/lib/middleware/firebase/index.cjs +33 -1
  51. package/lib/middleware/firebase/index.mjs +25 -16
  52. package/lib/middleware/netlify-edge/index.cjs +71 -1
  53. package/lib/middleware/netlify-edge/index.mjs +52 -36
  54. package/lib/middleware/node/index.cjs +219 -1
  55. package/lib/middleware/node/index.mjs +178 -165
  56. package/lib/middleware/request-handler/index.cjs +1488 -18
  57. package/lib/middleware/request-handler/index.d.ts +20 -2
  58. package/lib/middleware/request-handler/index.mjs +1225 -873
  59. package/lib/middleware/vercel-edge/index.cjs +98 -1
  60. package/lib/middleware/vercel-edge/index.mjs +71 -47
  61. package/lib/service-worker/index.cjs +5 -0
  62. package/lib/service-worker/index.mjs +5 -0
  63. package/lib/ssg/index.cjs +15 -1
  64. package/lib/ssg/index.mjs +12 -19
  65. package/lib/vite/index.cjs +2006 -27
  66. package/lib/vite/index.d.ts +9 -9
  67. package/lib/vite/index.mjs +1597 -1216
  68. package/package.json +9 -8
  69. package/lib/adapters/azure-swa/vite/index-BqUeglYs.cjs +0 -1
  70. package/lib/adapters/azure-swa/vite/index-CBIchDYq.js +0 -651
  71. package/lib/adapters/azure-swa/vite/index-ClHGw5z1.js +0 -6
  72. package/lib/adapters/azure-swa/vite/index-CrwlB95_.js +0 -22
  73. package/lib/adapters/azure-swa/vite/index-DTIOTwZo.cjs +0 -11
  74. package/lib/adapters/azure-swa/vite/index-vQuPcef3.cjs +0 -1
  75. package/lib/adapters/bun-server/vite/index-BqUeglYs.cjs +0 -1
  76. package/lib/adapters/bun-server/vite/index-CBIchDYq.js +0 -651
  77. package/lib/adapters/bun-server/vite/index-ClHGw5z1.js +0 -6
  78. package/lib/adapters/bun-server/vite/index-CrwlB95_.js +0 -22
  79. package/lib/adapters/bun-server/vite/index-DTIOTwZo.cjs +0 -11
  80. package/lib/adapters/bun-server/vite/index-vQuPcef3.cjs +0 -1
  81. package/lib/adapters/cloud-run/vite/index-BqUeglYs.cjs +0 -1
  82. package/lib/adapters/cloud-run/vite/index-CBIchDYq.js +0 -651
  83. package/lib/adapters/cloud-run/vite/index-ClHGw5z1.js +0 -6
  84. package/lib/adapters/cloud-run/vite/index-CrwlB95_.js +0 -22
  85. package/lib/adapters/cloud-run/vite/index-DTIOTwZo.cjs +0 -11
  86. package/lib/adapters/cloud-run/vite/index-vQuPcef3.cjs +0 -1
  87. package/lib/adapters/cloudflare-pages/vite/index-BIeHg2Cj.cjs +0 -5
  88. package/lib/adapters/cloudflare-pages/vite/index-C455V8_A.cjs +0 -1
  89. package/lib/adapters/cloudflare-pages/vite/index-ClHGw5z1.js +0 -6
  90. package/lib/adapters/cloudflare-pages/vite/index-D3HITboM.js +0 -645
  91. package/lib/adapters/cloudflare-pages/vite/index-DKcVHRBy.cjs +0 -11
  92. package/lib/adapters/cloudflare-pages/vite/index-DwovcBp3.js +0 -22
  93. package/lib/adapters/cloudflare-pages/vite/index-bogwy7wh.js +0 -250
  94. package/lib/adapters/cloudflare-pages/vite/index-vQuPcef3.cjs +0 -1
  95. package/lib/adapters/deno-server/vite/index-BqUeglYs.cjs +0 -1
  96. package/lib/adapters/deno-server/vite/index-CBIchDYq.js +0 -651
  97. package/lib/adapters/deno-server/vite/index-ClHGw5z1.js +0 -6
  98. package/lib/adapters/deno-server/vite/index-CrwlB95_.js +0 -22
  99. package/lib/adapters/deno-server/vite/index-DTIOTwZo.cjs +0 -11
  100. package/lib/adapters/deno-server/vite/index-vQuPcef3.cjs +0 -1
  101. package/lib/adapters/netlify-edge/vite/index-BqUeglYs.cjs +0 -1
  102. package/lib/adapters/netlify-edge/vite/index-CBIchDYq.js +0 -651
  103. package/lib/adapters/netlify-edge/vite/index-ClHGw5z1.js +0 -6
  104. package/lib/adapters/netlify-edge/vite/index-CrwlB95_.js +0 -22
  105. package/lib/adapters/netlify-edge/vite/index-DTIOTwZo.cjs +0 -11
  106. package/lib/adapters/netlify-edge/vite/index-vQuPcef3.cjs +0 -1
  107. package/lib/adapters/node-server/vite/index-BqUeglYs.cjs +0 -1
  108. package/lib/adapters/node-server/vite/index-CBIchDYq.js +0 -651
  109. package/lib/adapters/node-server/vite/index-ClHGw5z1.js +0 -6
  110. package/lib/adapters/node-server/vite/index-CrwlB95_.js +0 -22
  111. package/lib/adapters/node-server/vite/index-DTIOTwZo.cjs +0 -11
  112. package/lib/adapters/node-server/vite/index-vQuPcef3.cjs +0 -1
  113. package/lib/adapters/shared/vite/index-BqUeglYs.cjs +0 -1
  114. package/lib/adapters/shared/vite/index-CBIchDYq.js +0 -651
  115. package/lib/adapters/shared/vite/index-ClHGw5z1.js +0 -6
  116. package/lib/adapters/shared/vite/index-CrwlB95_.js +0 -22
  117. package/lib/adapters/shared/vite/index-DTIOTwZo.cjs +0 -11
  118. package/lib/adapters/shared/vite/index-vQuPcef3.cjs +0 -1
  119. package/lib/adapters/ssg/vite/index-BqUeglYs.cjs +0 -1
  120. package/lib/adapters/ssg/vite/index-CBIchDYq.js +0 -651
  121. package/lib/adapters/ssg/vite/index-ClHGw5z1.js +0 -6
  122. package/lib/adapters/ssg/vite/index-CrwlB95_.js +0 -22
  123. package/lib/adapters/ssg/vite/index-DTIOTwZo.cjs +0 -11
  124. package/lib/adapters/ssg/vite/index-vQuPcef3.cjs +0 -1
  125. package/lib/adapters/vercel-edge/vite/index-BqUeglYs.cjs +0 -1
  126. package/lib/adapters/vercel-edge/vite/index-CBIchDYq.js +0 -651
  127. package/lib/adapters/vercel-edge/vite/index-ClHGw5z1.js +0 -6
  128. package/lib/adapters/vercel-edge/vite/index-CrwlB95_.js +0 -22
  129. package/lib/adapters/vercel-edge/vite/index-DTIOTwZo.cjs +0 -11
  130. package/lib/adapters/vercel-edge/vite/index-vQuPcef3.cjs +0 -1
  131. package/lib/service-worker.cjs +0 -1
  132. package/lib/service-worker.mjs +0 -5
  133. package/lib/ssg/deno.cjs +0 -1
  134. package/lib/ssg/deno.mjs +0 -6
  135. package/lib/ssg/index-CBIchDYq.js +0 -651
  136. package/lib/ssg/index-ClHGw5z1.js +0 -6
  137. package/lib/ssg/index-DTIOTwZo.cjs +0 -11
  138. package/lib/ssg/index-vQuPcef3.cjs +0 -1
  139. package/lib/ssg/node.cjs +0 -11
  140. package/lib/ssg/node.mjs +0 -651
@@ -1,1116 +1,1468 @@
1
- import { _serialize as D, _UNINITIALIZED as ye, _deserialize as ee, _verifySerializable as Se } from "@qwik.dev/core/internal";
2
- import "@qwik.dev/core";
3
- import { ServerError as F, RedirectMessage as H, RewriteMessage as we, AbortMessage as pe } from "@qwik.dev/router/middleware/request-handler";
4
- const ne = /* @__PURE__ */ new WeakMap(), te = "qaction", v = "qloaders", Qe = "qfunc", re = "qdata", je = "q:route";
5
- function Ee(e, t) {
6
- const n = ae(e), r = ie(e), o = ae(t), i = ie(t);
7
- return Re(e, n, r, t, o, i);
8
- }
9
- function Re(e, t, n, r, o, i) {
10
- if (r.startsWith("/build/"))
11
- return null;
12
- let a = null;
13
- for (; t < n; ) {
14
- const s = e.charCodeAt(t++), c = r.charCodeAt(o++);
15
- if (s === 91) {
16
- const f = be(e, t), l = t + (f ? 3 : 0), u = B(
17
- e,
18
- l,
19
- n,
20
- 93
21
- /* CLOSE_BRACKET */
22
- ), h = e.substring(l, u), y = B(
23
- e,
24
- u + 1,
25
- n,
26
- 47
27
- /* SLASH */
28
- ), w = e.substring(u + 1, y);
29
- t = u + 1;
30
- const R = o - 1;
31
- if (f) {
32
- const M = ze(
33
- h,
34
- w,
35
- r,
36
- R,
37
- i,
38
- e,
39
- t + w.length + 1,
40
- n
41
- );
42
- if (M)
43
- return Object.assign(a || (a = {}), M);
44
- }
45
- const p = B(r, R, i, 47, w);
46
- if (p == -1)
47
- return null;
48
- const T = r.substring(R, p);
49
- if (!f && !w && !T)
50
- return null;
51
- o = p, (a || (a = {}))[h] = decodeURIComponent(T);
52
- } else if (s !== c && !(isNaN(c) && Ge(e, t)))
53
- return null;
1
+ var __defProp = Object.defineProperty;
2
+ var __typeError = (msg) => {
3
+ throw TypeError(msg);
4
+ };
5
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
6
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
7
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
8
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
9
+ var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
10
+ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
11
+ var _a, _b, _c, _pendingHighSurrogate, _handle, _transform;
12
+ import { isServer } from "@qwik.dev/core/build";
13
+ import { i as isPromise, k as QDATA_KEY, Q as Q_ROUTE, h as QFN_KEY, m as QLOADER_KEY, j as QACTION_KEY, d as loadRoute } from "../../chunks/routing.qwik.mjs";
14
+ import { inlinedQrl } from "@qwik.dev/core";
15
+ import { _serialize, _UNINITIALIZED, _deserialize, _verifySerializable } from "@qwik.dev/core/internal";
16
+ import { L as LoadedRouteProp } from "../../chunks/types.qwik.mjs";
17
+ import { _asyncRequestStore as _asyncRequestStore$1, ServerError as ServerError$1, RedirectMessage as RedirectMessage$1, RewriteMessage as RewriteMessage$1, AbortMessage as AbortMessage$1 } from "@qwik.dev/router/middleware/request-handler";
18
+ import { g as getErrorHtml, m as minimalHtmlResponse } from "../../chunks/error-handler.mjs";
19
+ import "@qwik.dev/core/preloader";
20
+ var HttpStatus = /* @__PURE__ */ ((HttpStatus2) => {
21
+ HttpStatus2[HttpStatus2["Continue"] = 100] = "Continue";
22
+ HttpStatus2[HttpStatus2["SwitchingProtocols"] = 101] = "SwitchingProtocols";
23
+ HttpStatus2[HttpStatus2["Processing"] = 102] = "Processing";
24
+ HttpStatus2[HttpStatus2["Ok"] = 200] = "Ok";
25
+ HttpStatus2[HttpStatus2["Created"] = 201] = "Created";
26
+ HttpStatus2[HttpStatus2["Accepted"] = 202] = "Accepted";
27
+ HttpStatus2[HttpStatus2["NonAuthoritativeInformation"] = 203] = "NonAuthoritativeInformation";
28
+ HttpStatus2[HttpStatus2["NoContent"] = 204] = "NoContent";
29
+ HttpStatus2[HttpStatus2["ResetContent"] = 205] = "ResetContent";
30
+ HttpStatus2[HttpStatus2["PartialContent"] = 206] = "PartialContent";
31
+ HttpStatus2[HttpStatus2["MultiStatus"] = 207] = "MultiStatus";
32
+ HttpStatus2[HttpStatus2["AlreadyReported"] = 208] = "AlreadyReported";
33
+ HttpStatus2[HttpStatus2["ImUsed"] = 226] = "ImUsed";
34
+ HttpStatus2[HttpStatus2["MultipleChoices"] = 300] = "MultipleChoices";
35
+ HttpStatus2[HttpStatus2["MovedPermanently"] = 301] = "MovedPermanently";
36
+ HttpStatus2[HttpStatus2["Found"] = 302] = "Found";
37
+ HttpStatus2[HttpStatus2["SeeOther"] = 303] = "SeeOther";
38
+ HttpStatus2[HttpStatus2["NotModified"] = 304] = "NotModified";
39
+ HttpStatus2[HttpStatus2["UseProxy"] = 305] = "UseProxy";
40
+ HttpStatus2[HttpStatus2["SwitchProxy"] = 306] = "SwitchProxy";
41
+ HttpStatus2[HttpStatus2["TemporaryRedirect"] = 307] = "TemporaryRedirect";
42
+ HttpStatus2[HttpStatus2["PermanentRedirect"] = 308] = "PermanentRedirect";
43
+ HttpStatus2[HttpStatus2["BadRequest"] = 400] = "BadRequest";
44
+ HttpStatus2[HttpStatus2["Unauthorized"] = 401] = "Unauthorized";
45
+ HttpStatus2[HttpStatus2["PaymentRequired"] = 402] = "PaymentRequired";
46
+ HttpStatus2[HttpStatus2["Forbidden"] = 403] = "Forbidden";
47
+ HttpStatus2[HttpStatus2["NotFound"] = 404] = "NotFound";
48
+ HttpStatus2[HttpStatus2["MethodNotAllowed"] = 405] = "MethodNotAllowed";
49
+ HttpStatus2[HttpStatus2["NotAcceptable"] = 406] = "NotAcceptable";
50
+ HttpStatus2[HttpStatus2["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired";
51
+ HttpStatus2[HttpStatus2["RequestTimeout"] = 408] = "RequestTimeout";
52
+ HttpStatus2[HttpStatus2["Conflict"] = 409] = "Conflict";
53
+ HttpStatus2[HttpStatus2["Gone"] = 410] = "Gone";
54
+ HttpStatus2[HttpStatus2["LengthRequired"] = 411] = "LengthRequired";
55
+ HttpStatus2[HttpStatus2["PreconditionFailed"] = 412] = "PreconditionFailed";
56
+ HttpStatus2[HttpStatus2["PayloadTooLarge"] = 413] = "PayloadTooLarge";
57
+ HttpStatus2[HttpStatus2["UriTooLong"] = 414] = "UriTooLong";
58
+ HttpStatus2[HttpStatus2["UnsupportedMediaType"] = 415] = "UnsupportedMediaType";
59
+ HttpStatus2[HttpStatus2["RangeNotSatisfiable"] = 416] = "RangeNotSatisfiable";
60
+ HttpStatus2[HttpStatus2["ExpectationFailed"] = 417] = "ExpectationFailed";
61
+ HttpStatus2[HttpStatus2["IAmATeapot"] = 418] = "IAmATeapot";
62
+ HttpStatus2[HttpStatus2["MisdirectedRequest"] = 421] = "MisdirectedRequest";
63
+ HttpStatus2[HttpStatus2["UnprocessableEntity"] = 422] = "UnprocessableEntity";
64
+ HttpStatus2[HttpStatus2["Locked"] = 423] = "Locked";
65
+ HttpStatus2[HttpStatus2["FailedDependency"] = 424] = "FailedDependency";
66
+ HttpStatus2[HttpStatus2["UpgradeRequired"] = 426] = "UpgradeRequired";
67
+ HttpStatus2[HttpStatus2["PreconditionRequired"] = 428] = "PreconditionRequired";
68
+ HttpStatus2[HttpStatus2["TooManyRequests"] = 429] = "TooManyRequests";
69
+ HttpStatus2[HttpStatus2["RequestHeaderFieldsTooLarge"] = 431] = "RequestHeaderFieldsTooLarge";
70
+ HttpStatus2[HttpStatus2["UnavailableForLegalReasons"] = 451] = "UnavailableForLegalReasons";
71
+ HttpStatus2[HttpStatus2["InternalServerError"] = 500] = "InternalServerError";
72
+ HttpStatus2[HttpStatus2["NotImplemented"] = 501] = "NotImplemented";
73
+ HttpStatus2[HttpStatus2["BadGateway"] = 502] = "BadGateway";
74
+ HttpStatus2[HttpStatus2["ServiceUnavailable"] = 503] = "ServiceUnavailable";
75
+ HttpStatus2[HttpStatus2["GatewayTimeout"] = 504] = "GatewayTimeout";
76
+ HttpStatus2[HttpStatus2["HttpVersionNotSupported"] = 505] = "HttpVersionNotSupported";
77
+ HttpStatus2[HttpStatus2["VariantAlsoNegotiates"] = 506] = "VariantAlsoNegotiates";
78
+ HttpStatus2[HttpStatus2["InsufficientStorage"] = 507] = "InsufficientStorage";
79
+ HttpStatus2[HttpStatus2["LoopDetected"] = 508] = "LoopDetected";
80
+ HttpStatus2[HttpStatus2["NotExtended"] = 510] = "NotExtended";
81
+ HttpStatus2[HttpStatus2["NetworkAuthenticationRequired"] = 511] = "NetworkAuthenticationRequired";
82
+ return HttpStatus2;
83
+ })(HttpStatus || {});
84
+ function createCacheControl(cacheControl) {
85
+ const controls = [];
86
+ if (cacheControl === "day") {
87
+ cacheControl = 60 * 60 * 24;
88
+ } else if (cacheControl === "week") {
89
+ cacheControl = 60 * 60 * 24 * 7;
90
+ } else if (cacheControl === "month") {
91
+ cacheControl = 60 * 60 * 24 * 30;
92
+ } else if (cacheControl === "year") {
93
+ cacheControl = 60 * 60 * 24 * 365;
94
+ } else if (cacheControl === "private") {
95
+ cacheControl = {
96
+ private: true,
97
+ noCache: true
98
+ };
99
+ } else if (cacheControl === "immutable") {
100
+ cacheControl = {
101
+ public: true,
102
+ immutable: true,
103
+ maxAge: 60 * 60 * 24 * 365
104
+ };
105
+ } else if (cacheControl === "no-cache") {
106
+ cacheControl = {
107
+ noCache: true
108
+ };
54
109
  }
55
- return oe(e, t) && oe(r, o) ? a || {} : null;
56
- }
57
- function Ge(e, t) {
58
- return e.charCodeAt(t) === 91 && be(e, t + 1);
59
- }
60
- function ie(e) {
61
- const t = e.length;
62
- return t > 1 && e.charCodeAt(t - 1) === 47 ? t - 1 : t;
63
- }
64
- function oe(e, t) {
65
- const n = e.length;
66
- return t >= n || t == n - 1 && e.charCodeAt(t) === 47;
67
- }
68
- function ae(e) {
69
- return e.charCodeAt(0) === 47 ? 1 : 0;
70
- }
71
- function be(e, t) {
72
- return e.charCodeAt(t) === 46 && e.charCodeAt(t + 1) === 46 && e.charCodeAt(t + 2) === 46;
73
- }
74
- function B(e, t, n, r, o = "") {
75
- for (; t < n && e.charCodeAt(t) !== r; )
76
- t++;
77
- const i = o.length;
78
- for (let a = 0; a < i; a++)
79
- if (e.charCodeAt(t - i + a) !== o.charCodeAt(a))
80
- return -1;
81
- return t - i;
82
- }
83
- function ze(e, t, n, r, o, i, a, s) {
84
- n.charCodeAt(r) === 47 && r++;
85
- let c = o;
86
- const f = t + "/";
87
- for (; c >= r; ) {
88
- const l = Re(i, a, s, n, c, o);
89
- if (l) {
90
- let h = n.substring(r, Math.min(c, o));
91
- return h.endsWith(f) && (h = h.substring(0, h.length - f.length)), l[e] = decodeURIComponent(h), l;
92
- }
93
- const u = Be(n, r, f, c, r - 1) + f.length;
94
- if (c === u)
95
- break;
96
- c = u;
110
+ if (typeof cacheControl === "number") {
111
+ cacheControl = {
112
+ maxAge: cacheControl,
113
+ sMaxAge: cacheControl
114
+ };
97
115
  }
98
- return null;
99
- }
100
- function Be(e, t, n, r, o) {
101
- let i = e.lastIndexOf(n, r);
102
- return i == r - n.length && (i = e.lastIndexOf(n, r - n.length - 1)), i > t ? i : o;
103
- }
104
- var k = /* @__PURE__ */ ((e) => (e[e.RouteName = 0] = "RouteName", e[e.Loaders = 1] = "Loaders", e[e.OriginalPathname = 2] = "OriginalPathname", e[e.RouteBundleNames = 3] = "RouteBundleNames", e))(k || {}), $ = /* @__PURE__ */ ((e) => (e[e.Pathname = 0] = "Pathname", e[e.MenuLoader = 1] = "MenuLoader", e))($ || {}), L = /* @__PURE__ */ ((e) => (e[e.RouteName = 0] = "RouteName", e[e.Params = 1] = "Params", e[e.Mods = 2] = "Mods", e[e.Menu = 3] = "Menu", e[e.RouteBundleNames = 4] = "RouteBundleNames", e))(L || {});
105
- const Ae = (e) => e == null ? e : (Object.getOwnPropertyNames(e).forEach((t) => {
106
- const n = e[t];
107
- n && typeof n == "object" && !Object.isFrozen(n) && Ae(n);
108
- }), Object.freeze(e)), Ke = async (e, t, n, r) => {
109
- if (!Array.isArray(e))
110
- return null;
111
- for (const o of e) {
112
- const i = o[k.RouteName], a = Ee(i, r);
113
- if (!a)
114
- continue;
115
- const s = o[k.Loaders], c = o[k.RouteBundleNames], f = new Array(s.length), l = [];
116
- s.forEach((y, w) => {
117
- se(
118
- y,
119
- l,
120
- (R) => f[w] = R,
121
- n
122
- );
123
- });
124
- const u = Je(t, r);
125
- let h;
126
- return se(
127
- u,
128
- l,
129
- (y) => h = y?.default,
130
- n
131
- ), l.length > 0 && await Promise.all(l), [i, a, f, Ae(h), c];
116
+ if (cacheControl.immutable) {
117
+ controls.push("immutable");
132
118
  }
133
- return null;
134
- }, se = (e, t, n, r) => {
135
- if (typeof e == "function") {
136
- const o = ne.get(e);
137
- if (o)
138
- n(o);
139
- else {
140
- const i = e();
141
- typeof i.then == "function" ? t.push(
142
- i.then((a) => {
143
- r !== !1 && ne.set(e, a), n(a);
144
- })
145
- ) : i && n(i);
146
- }
119
+ if (cacheControl.maxAge) {
120
+ controls.push(`max-age=${cacheControl.maxAge}`);
147
121
  }
148
- }, Je = (e, t) => {
149
- if (e) {
150
- t = t.endsWith("/") ? t : t + "/";
151
- const n = e.find(
152
- (r) => r[$.Pathname] === t || t.startsWith(r[$.Pathname] + (t.endsWith("/") ? "" : "/"))
153
- );
154
- if (n)
155
- return n[$.MenuLoader];
122
+ if (cacheControl.sMaxAge) {
123
+ controls.push(`s-maxage=${cacheControl.sMaxAge}`);
156
124
  }
157
- };
158
- var V = /* @__PURE__ */ ((e) => (e[e.Continue = 100] = "Continue", e[e.SwitchingProtocols = 101] = "SwitchingProtocols", e[e.Processing = 102] = "Processing", e[e.Ok = 200] = "Ok", e[e.Created = 201] = "Created", e[e.Accepted = 202] = "Accepted", e[e.NonAuthoritativeInformation = 203] = "NonAuthoritativeInformation", e[e.NoContent = 204] = "NoContent", e[e.ResetContent = 205] = "ResetContent", e[e.PartialContent = 206] = "PartialContent", e[e.MultiStatus = 207] = "MultiStatus", e[e.AlreadyReported = 208] = "AlreadyReported", e[e.ImUsed = 226] = "ImUsed", e[e.MultipleChoices = 300] = "MultipleChoices", e[e.MovedPermanently = 301] = "MovedPermanently", e[e.Found = 302] = "Found", e[e.SeeOther = 303] = "SeeOther", e[e.NotModified = 304] = "NotModified", e[e.UseProxy = 305] = "UseProxy", e[e.SwitchProxy = 306] = "SwitchProxy", e[e.TemporaryRedirect = 307] = "TemporaryRedirect", e[e.PermanentRedirect = 308] = "PermanentRedirect", e[e.BadRequest = 400] = "BadRequest", e[e.Unauthorized = 401] = "Unauthorized", e[e.PaymentRequired = 402] = "PaymentRequired", e[e.Forbidden = 403] = "Forbidden", e[e.NotFound = 404] = "NotFound", e[e.MethodNotAllowed = 405] = "MethodNotAllowed", e[e.NotAcceptable = 406] = "NotAcceptable", e[e.ProxyAuthenticationRequired = 407] = "ProxyAuthenticationRequired", e[e.RequestTimeout = 408] = "RequestTimeout", e[e.Conflict = 409] = "Conflict", e[e.Gone = 410] = "Gone", e[e.LengthRequired = 411] = "LengthRequired", e[e.PreconditionFailed = 412] = "PreconditionFailed", e[e.PayloadTooLarge = 413] = "PayloadTooLarge", e[e.UriTooLong = 414] = "UriTooLong", e[e.UnsupportedMediaType = 415] = "UnsupportedMediaType", e[e.RangeNotSatisfiable = 416] = "RangeNotSatisfiable", e[e.ExpectationFailed = 417] = "ExpectationFailed", e[e.IAmATeapot = 418] = "IAmATeapot", e[e.MisdirectedRequest = 421] = "MisdirectedRequest", e[e.UnprocessableEntity = 422] = "UnprocessableEntity", e[e.Locked = 423] = "Locked", e[e.FailedDependency = 424] = "FailedDependency", e[e.UpgradeRequired = 426] = "UpgradeRequired", e[e.PreconditionRequired = 428] = "PreconditionRequired", e[e.TooManyRequests = 429] = "TooManyRequests", e[e.RequestHeaderFieldsTooLarge = 431] = "RequestHeaderFieldsTooLarge", e[e.UnavailableForLegalReasons = 451] = "UnavailableForLegalReasons", e[e.InternalServerError = 500] = "InternalServerError", e[e.NotImplemented = 501] = "NotImplemented", e[e.BadGateway = 502] = "BadGateway", e[e.ServiceUnavailable = 503] = "ServiceUnavailable", e[e.GatewayTimeout = 504] = "GatewayTimeout", e[e.HttpVersionNotSupported = 505] = "HttpVersionNotSupported", e[e.VariantAlsoNegotiates = 506] = "VariantAlsoNegotiates", e[e.InsufficientStorage = 507] = "InsufficientStorage", e[e.LoopDetected = 508] = "LoopDetected", e[e.NotExtended = 510] = "NotExtended", e[e.NetworkAuthenticationRequired = 511] = "NetworkAuthenticationRequired", e))(V || {});
159
- const Ye = (e) => e && typeof e.then == "function";
160
- function ve(e) {
161
- const t = [];
162
- return e === "day" ? e = 3600 * 24 : e === "week" ? e = 3600 * 24 * 7 : e === "month" ? e = 3600 * 24 * 30 : e === "year" ? e = 3600 * 24 * 365 : e === "private" ? e = {
163
- private: !0,
164
- noCache: !0
165
- } : e === "immutable" ? e = {
166
- public: !0,
167
- immutable: !0,
168
- maxAge: 3600 * 24 * 365
169
- } : e === "no-cache" && (e = {
170
- noCache: !0
171
- }), typeof e == "number" && (e = {
172
- maxAge: e,
173
- sMaxAge: e
174
- }), e.immutable && t.push("immutable"), e.maxAge && t.push(`max-age=${e.maxAge}`), e.sMaxAge && t.push(`s-maxage=${e.sMaxAge}`), e.noStore && t.push("no-store"), e.noCache && t.push("no-cache"), e.private && t.push("private"), e.public && t.push("public"), e.staleWhileRevalidate && t.push(`stale-while-revalidate=${e.staleWhileRevalidate}`), e.staleIfError && t.push(`stale-if-error=${e.staleIfError}`), t.join(", ");
125
+ if (cacheControl.noStore) {
126
+ controls.push("no-store");
127
+ }
128
+ if (cacheControl.noCache) {
129
+ controls.push("no-cache");
130
+ }
131
+ if (cacheControl.private) {
132
+ controls.push("private");
133
+ }
134
+ if (cacheControl.public) {
135
+ controls.push("public");
136
+ }
137
+ if (cacheControl.staleWhileRevalidate) {
138
+ controls.push(`stale-while-revalidate=${cacheControl.staleWhileRevalidate}`);
139
+ }
140
+ if (cacheControl.staleIfError) {
141
+ controls.push(`stale-if-error=${cacheControl.staleIfError}`);
142
+ }
143
+ return controls.join(", ");
175
144
  }
176
- const Ve = {
145
+ const SAMESITE = {
177
146
  lax: "Lax",
178
147
  Lax: "Lax",
179
148
  None: "None",
180
149
  none: "None",
181
150
  strict: "Strict",
182
151
  Strict: "Strict"
183
- }, Xe = {
152
+ };
153
+ const UNIT = {
184
154
  seconds: 1,
185
- minutes: 60,
186
- hours: 3600,
187
- days: 3600 * 24,
188
- weeks: 3600 * 24 * 7
189
- }, ce = (e, t, n) => {
190
- const r = [`${e}=${t}`];
191
- typeof n.domain == "string" && r.push(`Domain=${n.domain}`), typeof n.maxAge == "number" ? r.push(`Max-Age=${n.maxAge}`) : Array.isArray(n.maxAge) ? r.push(`Max-Age=${n.maxAge[0] * Xe[n.maxAge[1]]}`) : typeof n.expires == "number" || typeof n.expires == "string" ? r.push(`Expires=${n.expires}`) : n.expires instanceof Date && r.push(`Expires=${n.expires.toUTCString()}`), n.httpOnly && r.push("HttpOnly"), typeof n.path == "string" && r.push(`Path=${n.path}`);
192
- const o = He(n.sameSite);
193
- return o && r.push(`SameSite=${o}`), n.secure && r.push("Secure"), r.join("; ");
155
+ minutes: 1 * 60,
156
+ hours: 1 * 60 * 60,
157
+ days: 1 * 60 * 60 * 24,
158
+ weeks: 1 * 60 * 60 * 24 * 7
194
159
  };
195
- function le(e) {
160
+ const createSetCookieValue = (cookieName, cookieValue, options) => {
161
+ const c = [`${cookieName}=${cookieValue}`];
162
+ if (typeof options.domain === "string") {
163
+ c.push(`Domain=${options.domain}`);
164
+ }
165
+ if (typeof options.maxAge === "number") {
166
+ c.push(`Max-Age=${options.maxAge}`);
167
+ } else if (Array.isArray(options.maxAge)) {
168
+ c.push(`Max-Age=${options.maxAge[0] * UNIT[options.maxAge[1]]}`);
169
+ } else if (typeof options.expires === "number" || typeof options.expires == "string") {
170
+ c.push(`Expires=${options.expires}`);
171
+ } else if (options.expires instanceof Date) {
172
+ c.push(`Expires=${options.expires.toUTCString()}`);
173
+ }
174
+ if (options.httpOnly) {
175
+ c.push("HttpOnly");
176
+ }
177
+ if (typeof options.path === "string") {
178
+ c.push(`Path=${options.path}`);
179
+ }
180
+ const sameSite = resolveSameSite(options.sameSite);
181
+ if (sameSite) {
182
+ c.push(`SameSite=${sameSite}`);
183
+ }
184
+ if (options.secure) {
185
+ c.push("Secure");
186
+ }
187
+ return c.join("; ");
188
+ };
189
+ function tryDecodeUriComponent(str) {
196
190
  try {
197
- return decodeURIComponent(e);
191
+ return decodeURIComponent(str);
198
192
  } catch {
199
- return e;
193
+ return str;
200
194
  }
201
195
  }
202
- const Ze = (e) => {
203
- const t = {};
204
- if (typeof e == "string" && e !== "") {
205
- const n = e.split(";");
206
- for (const r of n) {
207
- const o = r.indexOf("=");
208
- o !== -1 && (t[le(r.slice(0, o).trim())] = le(r.slice(o + 1).trim()));
196
+ const parseCookieString = (cookieString) => {
197
+ const cookie = {};
198
+ if (typeof cookieString === "string" && cookieString !== "") {
199
+ const cookieSegments = cookieString.split(";");
200
+ for (const cookieSegment of cookieSegments) {
201
+ const separatorIndex = cookieSegment.indexOf("=");
202
+ if (separatorIndex !== -1) {
203
+ cookie[tryDecodeUriComponent(cookieSegment.slice(0, separatorIndex).trim())] = tryDecodeUriComponent(cookieSegment.slice(separatorIndex + 1).trim());
204
+ }
209
205
  }
210
206
  }
211
- return t;
207
+ return cookie;
212
208
  };
213
- function He(e) {
214
- if (e === !0)
209
+ function resolveSameSite(sameSite) {
210
+ if (sameSite === true) {
215
211
  return "Strict";
216
- if (e === !1)
212
+ }
213
+ if (sameSite === false) {
217
214
  return "None";
218
- if (e)
219
- return Ve[e];
215
+ }
216
+ if (sameSite) {
217
+ return SAMESITE[sameSite];
218
+ }
219
+ return void 0;
220
220
  }
221
- const x = Symbol("request-cookies"), q = Symbol("response-cookies"), _ = Symbol("live-cookies");
222
- class en {
223
- [x];
224
- [q] = {};
225
- [_] = {};
226
- appendCounter = 0;
227
- constructor(t) {
228
- this[x] = Ze(t), this[_] = { ...this[x] };
229
- }
230
- get(t, n = !0) {
231
- const r = this[n ? _ : x][t];
232
- return r ? {
233
- value: r,
221
+ const REQ_COOKIE = Symbol("request-cookies");
222
+ const RES_COOKIE = Symbol("response-cookies");
223
+ const LIVE_COOKIE = Symbol("live-cookies");
224
+ _c = REQ_COOKIE, _b = RES_COOKIE, _a = LIVE_COOKIE;
225
+ class Cookie {
226
+ constructor(cookieString) {
227
+ __publicField(this, _c);
228
+ __publicField(this, _b, {});
229
+ __publicField(this, _a, {});
230
+ __publicField(this, "appendCounter", 0);
231
+ this[REQ_COOKIE] = parseCookieString(cookieString);
232
+ this[LIVE_COOKIE] = { ...this[REQ_COOKIE] };
233
+ }
234
+ get(cookieName, live = true) {
235
+ const value = this[live ? LIVE_COOKIE : REQ_COOKIE][cookieName];
236
+ if (!value) {
237
+ return null;
238
+ }
239
+ return {
240
+ value,
234
241
  json() {
235
- return JSON.parse(r);
242
+ return JSON.parse(value);
236
243
  },
237
244
  number() {
238
- return Number(r);
245
+ return Number(value);
239
246
  }
240
- } : null;
247
+ };
241
248
  }
242
- getAll(t = !0) {
243
- return Object.keys(this[t ? _ : x]).reduce(
244
- (n, r) => (n[r] = this.get(r), n),
249
+ getAll(live = true) {
250
+ return Object.keys(this[live ? LIVE_COOKIE : REQ_COOKIE]).reduce(
251
+ (cookies, cookieName) => {
252
+ cookies[cookieName] = this.get(cookieName);
253
+ return cookies;
254
+ },
245
255
  {}
246
256
  );
247
257
  }
248
- has(t, n = !0) {
249
- return !!this[n ? _ : x][t];
250
- }
251
- set(t, n, r = {}) {
252
- this[_][t] = typeof n == "string" ? n : JSON.stringify(n);
253
- const o = typeof n == "string" ? n : encodeURIComponent(JSON.stringify(n));
254
- this[q][t] = ce(t, o, r);
255
- }
256
- append(t, n, r = {}) {
257
- this[_][t] = typeof n == "string" ? n : JSON.stringify(n);
258
- const o = typeof n == "string" ? n : encodeURIComponent(JSON.stringify(n));
259
- this[q][++this.appendCounter] = ce(
260
- t,
261
- o,
262
- r
258
+ has(cookieName, live = true) {
259
+ return !!this[live ? LIVE_COOKIE : REQ_COOKIE][cookieName];
260
+ }
261
+ set(cookieName, cookieValue, options = {}) {
262
+ this[LIVE_COOKIE][cookieName] = typeof cookieValue === "string" ? cookieValue : JSON.stringify(cookieValue);
263
+ const resolvedValue = typeof cookieValue === "string" ? cookieValue : encodeURIComponent(JSON.stringify(cookieValue));
264
+ this[RES_COOKIE][cookieName] = createSetCookieValue(cookieName, resolvedValue, options);
265
+ }
266
+ append(cookieName, cookieValue, options = {}) {
267
+ this[LIVE_COOKIE][cookieName] = typeof cookieValue === "string" ? cookieValue : JSON.stringify(cookieValue);
268
+ const resolvedValue = typeof cookieValue === "string" ? cookieValue : encodeURIComponent(JSON.stringify(cookieValue));
269
+ this[RES_COOKIE][++this.appendCounter] = createSetCookieValue(
270
+ cookieName,
271
+ resolvedValue,
272
+ options
263
273
  );
264
274
  }
265
- delete(t, n) {
266
- this.set(t, "deleted", { ...n, maxAge: 0 }), this[_][t] = null;
275
+ delete(name, options) {
276
+ this.set(name, "deleted", { ...options, maxAge: 0 });
277
+ this[LIVE_COOKIE][name] = null;
267
278
  }
268
279
  headers() {
269
- return Object.values(this[q]);
280
+ return Object.values(this[RES_COOKIE]);
270
281
  }
271
282
  }
272
- const Un = (e, t) => {
273
- const n = t.headers();
274
- if (n.length > 0) {
275
- const r = new Headers(e);
276
- for (const o of n)
277
- r.append("Set-Cookie", o);
278
- return r;
279
- }
280
- return e;
283
+ const mergeHeadersCookies = (headers, cookies) => {
284
+ const cookieHeaders = cookies.headers();
285
+ if (cookieHeaders.length > 0) {
286
+ const newHeaders = new Headers(headers);
287
+ for (const cookie of cookieHeaders) {
288
+ newHeaders.append("Set-Cookie", cookie);
289
+ }
290
+ return newHeaders;
291
+ }
292
+ return headers;
281
293
  };
282
- function K(e, t) {
283
- let n = "Server Error";
284
- return t != null && (typeof t.message == "string" ? n = t.message : n = String(t)), "<html>" + _e(e, n) + "</html>";
285
- }
286
- function _e(e, t) {
287
- typeof e != "number" && (e = 500), typeof t == "string" ? t = tn(t) : t = "";
288
- const n = typeof t == "string" ? "600px" : "300px", r = e >= 500 ? on : rn;
289
- return `
290
- <head>
291
- <meta charset="utf-8">
292
- <meta http-equiv="Status" content="${e}">
293
- <title>${e} ${t}</title>
294
- <meta name="viewport" content="width=device-width,initial-scale=1">
295
- <style>
296
- body { color: ${r}; background-color: #fafafa; padding: 30px; font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, Roboto, sans-serif; }
297
- p { max-width: ${n}; margin: 60px auto 30px auto; background: white; border-radius: 4px; box-shadow: 0px 0px 50px -20px ${r}; overflow: hidden; }
298
- strong { display: inline-block; padding: 15px; background: ${r}; color: white; }
299
- span { display: inline-block; padding: 15px; }
300
- </style>
301
- </head>
302
- <body><p><strong>${e}</strong> <span>${t}</span></p></body>
303
- `;
304
- }
305
- const nn = /[&<>]/g, tn = (e) => e.replace(nn, (t) => {
306
- switch (t) {
307
- case "&":
308
- return "&amp;";
309
- case "<":
310
- return "&lt;";
311
- case ">":
312
- return "&gt;";
313
- default:
314
- return "";
315
- }
316
- }), rn = "#006ce9", on = "#713fc2";
317
- let S;
318
- import("node:async_hooks").then((e) => {
319
- const t = e.AsyncLocalStorage;
320
- S = new t(), globalThis.qcAsyncRequestStore = S;
321
- }).catch((e) => {
322
- console.warn(
323
- "AsyncLocalStorage not available, continuing without it. This might impact concurrent server calls.",
324
- e
325
- );
326
- });
327
- function an(e, t, n, r, o = "/") {
328
- let i;
329
- const a = new Promise((c) => i = c), s = cn(
330
- e,
331
- t,
332
- n,
333
- o,
334
- i
294
+ function runQwikRouter(serverRequestEv, loadedRoute, requestHandlers, rebuildRouteInfo, basePathname = "/") {
295
+ let resolve;
296
+ const responsePromise = new Promise((r) => resolve = r);
297
+ const requestEv = createRequestEvent(
298
+ serverRequestEv,
299
+ loadedRoute,
300
+ requestHandlers,
301
+ basePathname,
302
+ resolve
335
303
  );
336
304
  return {
337
- response: a,
338
- requestEv: s,
339
- completion: S ? S.run(s, de, s, r, i) : de(s, r, i)
305
+ response: responsePromise,
306
+ requestEv,
307
+ completion: _asyncRequestStore$1 ? _asyncRequestStore$1.run(requestEv, runNext, requestEv, rebuildRouteInfo, resolve) : runNext(requestEv, rebuildRouteInfo, resolve)
340
308
  };
341
309
  }
342
- async function de(e, t, n) {
310
+ async function runNext(requestEv, rebuildRouteInfo, resolve) {
343
311
  try {
344
- ((a) => new URL(a.pathname + a.search, a))(e.originalUrl);
312
+ const isValidURL = (url) => new URL(url.pathname + url.search, url);
313
+ isValidURL(requestEv.originalUrl);
345
314
  } catch {
346
- const a = "Resource Not Found";
347
- e.status(404);
348
- const s = K(404, a);
349
- return e.html(404, s), new F(404, a);
315
+ const status = 404;
316
+ const message = "Resource Not Found";
317
+ requestEv.status(status);
318
+ const html = getErrorHtml(status, message);
319
+ requestEv.html(status, html);
320
+ return new ServerError$1(status, message);
350
321
  }
351
- let r = 1;
352
- async function o() {
322
+ let rewriteAttempt = 1;
323
+ async function _runNext() {
353
324
  try {
354
- await e.next();
355
- } catch (i) {
356
- if (i instanceof H)
357
- await e.getWritableStream().close();
358
- else if (i instanceof we) {
359
- if (r > 50)
360
- throw new Error("Infinite rewrite loop");
361
- r += 1;
362
- const a = new URL(e.url);
363
- a.pathname = i.pathname;
364
- const { loadedRoute: s, requestHandlers: c } = await t(a);
365
- return e.resetRoute(s, c, a), await o();
366
- } else if (i instanceof F) {
367
- if (!e.headersSent) {
368
- const a = i.status, s = e.request.headers.get("Accept");
369
- if (s && !s.includes("text/html"))
370
- e.headers.set("Content-Type", "application/qwik-json"), e.send(a, await D([i.data]));
371
- else {
372
- const c = K(i.status, i.data);
373
- e.html(a, c);
374
- }
325
+ await requestEv.next();
326
+ } catch (e) {
327
+ if (e instanceof RedirectMessage$1) {
328
+ const stream = requestEv.getWritableStream();
329
+ await stream.close();
330
+ return e;
331
+ } else if (e instanceof RewriteMessage$1) {
332
+ if (rewriteAttempt > 50) {
333
+ return new Error(`Infinite rewrite loop`);
375
334
  }
376
- } else if (!(i instanceof pe)) {
377
- if (P(e) !== "dev")
378
- try {
379
- e.headersSent || (e.headers.set("content-type", "text/html; charset=utf-8"), e.cacheControl({ noCache: !0 }), e.status(500));
380
- const a = e.getWritableStream();
381
- if (!a.locked) {
382
- const s = a.getWriter();
383
- await s.write(E.encode(K(500, "Internal Server Error"))), await s.close();
384
- }
385
- } catch {
386
- console.error("Unable to render error page");
335
+ rewriteAttempt += 1;
336
+ const url = new URL(requestEv.url);
337
+ url.pathname = e.pathname;
338
+ const { loadedRoute, requestHandlers } = await rebuildRouteInfo(url);
339
+ requestEv.resetRoute(loadedRoute, requestHandlers, url);
340
+ return await _runNext();
341
+ } else if (e instanceof AbortMessage$1) {
342
+ return;
343
+ } else if (e instanceof ServerError$1 && !requestEv.headersSent) {
344
+ const status = e.status;
345
+ const accept = requestEv.request.headers.get("Accept");
346
+ if (accept && !accept.includes("text/html")) {
347
+ requestEv.headers.set("Content-Type", "application/qwik-json");
348
+ requestEv.send(status, await _serialize([e.data]));
349
+ } else {
350
+ requestEv.html(status, getErrorHtml(status, e.data));
351
+ }
352
+ return e;
353
+ }
354
+ if (getRequestMode(requestEv) !== "dev") {
355
+ try {
356
+ if (!requestEv.headersSent) {
357
+ requestEv.headers.set("content-type", "text/html; charset=utf-8");
358
+ requestEv.cacheControl({ noCache: true });
359
+ requestEv.status(500);
387
360
  }
388
- return i;
361
+ const stream = requestEv.getWritableStream();
362
+ if (!stream.locked) {
363
+ const writer = stream.getWriter();
364
+ await writer.write(encoder.encode(getErrorHtml(500, "Internal Server Error")));
365
+ await writer.close();
366
+ }
367
+ } catch {
368
+ console.error("Unable to render error page");
369
+ }
389
370
  }
371
+ return e;
390
372
  }
391
373
  }
392
374
  try {
393
- return await o();
375
+ return await _runNext();
394
376
  } finally {
395
- e.isDirty() || n(null);
377
+ if (!requestEv.isDirty()) {
378
+ resolve(null);
379
+ }
396
380
  }
397
381
  }
398
- function fe(e) {
399
- if (e.endsWith(C)) {
400
- const t = e.length - Te + (globalThis.__NO_TRAILING_SLASH__ ? 0 : 1);
401
- e = e.slice(0, t), e === "" && (e = "/");
382
+ function getRouteMatchPathname(pathname) {
383
+ const isInternal = pathname.endsWith(QDATA_JSON);
384
+ if (isInternal) {
385
+ const trimEnd = pathname.length - QDATA_JSON.length + (globalThis.__NO_TRAILING_SLASH__ ? 0 : 1);
386
+ pathname = pathname.slice(0, trimEnd);
387
+ if (pathname === "") {
388
+ pathname = "/";
389
+ }
402
390
  }
403
- return e;
391
+ return { pathname, isInternal };
404
392
  }
405
- const O = "@isQData", C = "/q-data.json", Te = C.length, Me = Symbol("RequestEvLoaders"), Ne = Symbol("RequestEvMode"), xe = Symbol("RequestEvRoute"), Ce = Symbol(
393
+ const IsQData = "@isQData";
394
+ const QDATA_JSON = "/q-data.json";
395
+ const RequestEvLoaders = Symbol("RequestEvLoaders");
396
+ const RequestEvMode = Symbol("RequestEvMode");
397
+ const RequestEvRoute = Symbol("RequestEvRoute");
398
+ const RequestEvLoaderSerializationStrategyMap = Symbol(
406
399
  "RequestEvLoaderSerializationStrategyMap"
407
- ), Pe = "@routeName", j = "@actionId", Ie = "@actionFormData", sn = "@nonce", Le = "@rewrite", X = "@serverTiming", Oe = "qData";
408
- function cn(e, t, n, r, o) {
409
- const { request: i, platform: a, env: s } = e, c = /* @__PURE__ */ new Map(), f = new en(i.headers.get("cookie")), l = new Headers(), u = new URL(i.url);
410
- u.pathname.endsWith(C) && (u.pathname = u.pathname.slice(0, -Te), !globalThis.__NO_TRAILING_SLASH__ && !u.pathname.endsWith("/") && (u.pathname += "/"), c.set(O, !0));
411
- let h = -1, y = null, w, R = e.locale, p = 200;
412
- const T = async () => {
413
- for (h++; h < n.length; ) {
414
- const d = n[h], m = globalThis.qcAsyncRequestStore, g = m?.run ? m.run(b, d, b) : d(b);
415
- Ye(g) && await g, h++;
400
+ );
401
+ const RequestRouteName = "@routeName";
402
+ const RequestEvSharedActionId = "@actionId";
403
+ const RequestEvSharedActionFormData = "@actionFormData";
404
+ const RequestEvSharedNonce = "@nonce";
405
+ const RequestEvIsRewrite = "@rewrite";
406
+ const RequestEvShareServerTiming = "@serverTiming";
407
+ const RequestEvShareQData = "qData";
408
+ function createRequestEvent(serverRequestEv, loadedRoute, requestHandlers, basePathname, resolved) {
409
+ const { request, platform, env } = serverRequestEv;
410
+ const sharedMap = /* @__PURE__ */ new Map();
411
+ const cookie = new Cookie(request.headers.get("cookie"));
412
+ const headers = new Headers();
413
+ const url = new URL(request.url);
414
+ const { pathname, isInternal } = getRouteMatchPathname(url.pathname);
415
+ if (isInternal) {
416
+ url.pathname = pathname;
417
+ sharedMap.set(IsQData, true);
418
+ }
419
+ let routeModuleIndex = -1;
420
+ let writableStream = null;
421
+ let requestData = void 0;
422
+ let locale = serverRequestEv.locale;
423
+ let status = 200;
424
+ const next = async () => {
425
+ routeModuleIndex++;
426
+ while (routeModuleIndex < requestHandlers.length) {
427
+ const moduleRequestHandler = requestHandlers[routeModuleIndex];
428
+ const result = moduleRequestHandler(requestEv);
429
+ if (isPromise(result)) {
430
+ await result;
431
+ }
432
+ routeModuleIndex++;
416
433
  }
417
- }, M = (d, m, g = u) => {
418
- t = d, n = m, u.pathname = g.pathname, u.search = g.search, h = -1;
419
- }, N = () => {
420
- if (y !== null)
434
+ };
435
+ const resetRoute = (_loadedRoute, _requestHandlers, _url = url) => {
436
+ loadedRoute = _loadedRoute;
437
+ requestHandlers = _requestHandlers;
438
+ url.pathname = _url.pathname;
439
+ url.search = _url.search;
440
+ routeModuleIndex = -1;
441
+ };
442
+ const check = () => {
443
+ if (writableStream !== null) {
421
444
  throw new Error("Response already sent");
422
- }, W = (d, m) => {
423
- if (N(), typeof d == "number") {
424
- p = d;
425
- const A = b.getWritableStream().getWriter();
426
- A.write(typeof m == "string" ? E.encode(m) : m), A.close();
427
- } else if (p = d.status, d.headers.forEach((g, A) => {
428
- A.toLowerCase() !== "set-cookie" && l.append(A, g);
429
- }), d.headers.getSetCookie().forEach((g) => {
430
- const A = g.indexOf("=");
431
- if (A === -1)
432
- return;
433
- const De = g.slice(0, A).trim(), Fe = g.slice(A + 1).trim();
434
- f.set(De, Fe);
435
- }), d.body) {
436
- const g = b.getWritableStream();
437
- d.body.pipeTo(g);
438
- } else
439
- b.getWritableStream().getWriter().close();
440
- return z();
441
- }, z = () => (h = ue, new pe()), I = {}, b = {
442
- [Me]: I,
443
- [Ce]: /* @__PURE__ */ new Map(),
444
- [Ne]: e.mode,
445
- get [xe]() {
446
- return t;
445
+ }
446
+ };
447
+ const send = (statusOrResponse, body) => {
448
+ check();
449
+ if (typeof statusOrResponse === "number") {
450
+ status = statusOrResponse;
451
+ const writableStream2 = requestEv.getWritableStream();
452
+ const writer = writableStream2.getWriter();
453
+ writer.write(typeof body === "string" ? encoder.encode(body) : body);
454
+ writer.close();
455
+ } else {
456
+ status = statusOrResponse.status;
457
+ statusOrResponse.headers.forEach((value, key) => {
458
+ if (key.toLowerCase() === "set-cookie") {
459
+ return;
460
+ }
461
+ headers.append(key, value);
462
+ });
463
+ statusOrResponse.headers.getSetCookie().forEach((ck) => {
464
+ const index = ck.indexOf("=");
465
+ if (index === -1) {
466
+ return;
467
+ }
468
+ const key = ck.slice(0, index).trim();
469
+ const value = ck.slice(index + 1).trim();
470
+ cookie.set(key, value);
471
+ });
472
+ if (statusOrResponse.body) {
473
+ const writableStream2 = requestEv.getWritableStream();
474
+ statusOrResponse.body.pipeTo(writableStream2);
475
+ } else {
476
+ requestEv.getWritableStream().getWriter().close();
477
+ }
478
+ }
479
+ return exit();
480
+ };
481
+ const exit = (message = new AbortMessage$1()) => {
482
+ routeModuleIndex = ABORT_INDEX;
483
+ return message;
484
+ };
485
+ const loaders = {};
486
+ const requestEv = {
487
+ [RequestEvLoaders]: loaders,
488
+ [RequestEvLoaderSerializationStrategyMap]: /* @__PURE__ */ new Map(),
489
+ [RequestEvMode]: serverRequestEv.mode,
490
+ get [RequestEvRoute]() {
491
+ return loadedRoute;
447
492
  },
448
- cookie: f,
449
- headers: l,
450
- env: s,
451
- method: i.method,
452
- signal: i.signal,
453
- originalUrl: new URL(u),
493
+ cookie,
494
+ headers,
495
+ env,
496
+ method: request.method,
497
+ signal: request.signal,
498
+ originalUrl: new URL(url),
454
499
  get params() {
455
- return t?.[L.Params] ?? {};
500
+ return loadedRoute?.[LoadedRouteProp.Params] ?? {};
456
501
  },
457
502
  get pathname() {
458
- return u.pathname;
503
+ return url.pathname;
459
504
  },
460
- platform: a,
505
+ platform,
461
506
  get query() {
462
- return u.searchParams;
507
+ return url.searchParams;
463
508
  },
464
- request: i,
465
- url: u,
466
- basePathname: r,
467
- sharedMap: c,
509
+ request,
510
+ url,
511
+ basePathname,
512
+ sharedMap,
468
513
  get headersSent() {
469
- return y !== null;
514
+ return writableStream !== null;
470
515
  },
471
516
  get exited() {
472
- return h >= ue;
517
+ return routeModuleIndex >= ABORT_INDEX;
473
518
  },
474
519
  get clientConn() {
475
- return e.getClientConn();
520
+ return serverRequestEv.getClientConn();
476
521
  },
477
- next: T,
478
- resetRoute: M,
479
- exit: z,
480
- cacheControl: (d, m = "Cache-Control") => {
481
- N(), l.set(m, ve(d));
522
+ next,
523
+ resetRoute,
524
+ exit,
525
+ cacheControl: (cacheControl, target = "Cache-Control") => {
526
+ check();
527
+ headers.set(target, createCacheControl(cacheControl));
482
528
  },
483
- resolveValue: (async (d) => {
484
- const m = d.__id;
485
- if (d.__brand === "server_loader") {
486
- if (!(m in I))
529
+ resolveValue: (async (loaderOrAction) => {
530
+ const id = loaderOrAction.__id;
531
+ if (loaderOrAction.__brand === "server_loader") {
532
+ if (!(id in loaders)) {
487
533
  throw new Error(
488
534
  "You can not get the returned data of a loader that has not been executed for this request."
489
535
  );
490
- if (I[m] === ye) {
491
- const g = P(b) === "dev";
492
- await We(d, I, b, g);
536
+ }
537
+ if (loaders[id] === _UNINITIALIZED) {
538
+ const isDev = getRequestMode(requestEv) === "dev";
539
+ await getRouteLoaderPromise(loaderOrAction, loaders, requestEv, isDev);
493
540
  }
494
541
  }
495
- return I[m];
542
+ return loaders[id];
496
543
  }),
497
- status: (d) => typeof d == "number" ? (N(), p = d, d) : p,
498
- locale: (d) => (typeof d == "string" && (R = d), R || ""),
499
- error: (d, m) => (p = d, l.delete("Cache-Control"), new F(d, m)),
500
- redirect: (d, m) => {
501
- if (N(), p = d, m) {
502
- const g = m.replace(/([^:])\/{2,}/g, "$1/");
503
- m !== g && console.warn(`Redirect URL ${m} is invalid, fixing to ${g}`), l.set("Location", g);
544
+ status: (statusCode) => {
545
+ if (typeof statusCode === "number") {
546
+ check();
547
+ status = statusCode;
548
+ return statusCode;
549
+ }
550
+ return status;
551
+ },
552
+ locale: (_locale) => {
553
+ if (typeof _locale === "string") {
554
+ locale = _locale;
555
+ }
556
+ return locale || "";
557
+ },
558
+ error: (statusCode, message) => {
559
+ status = statusCode;
560
+ headers.delete("Cache-Control");
561
+ return new ServerError$1(statusCode, message);
562
+ },
563
+ redirect: (statusCode, url2) => {
564
+ check();
565
+ status = statusCode;
566
+ if (url2) {
567
+ if (/([^:])\/{2,}/.test(url2)) {
568
+ const fixedURL = url2.replace(/([^:])\/{2,}/g, "$1/");
569
+ console.warn(`Redirect URL ${url2} is invalid, fixing to ${fixedURL}`);
570
+ url2 = fixedURL;
571
+ }
572
+ headers.set("Location", url2);
504
573
  }
505
- return l.delete("Cache-Control"), d > 301 && l.set("Cache-Control", "no-store"), z(), new H();
574
+ headers.delete("Cache-Control");
575
+ if (statusCode > 301) {
576
+ headers.set("Cache-Control", "no-store");
577
+ }
578
+ return exit(new RedirectMessage$1());
506
579
  },
507
- rewrite: (d) => {
508
- if (N(), d.startsWith("http"))
580
+ rewrite: (pathname2) => {
581
+ check();
582
+ if (pathname2.startsWith("http")) {
509
583
  throw new Error("Rewrite does not support absolute urls");
510
- return c.set(Le, !0), new we(d.replace(/\/+/g, "/"));
584
+ }
585
+ sharedMap.set(RequestEvIsRewrite, true);
586
+ return exit(new RewriteMessage$1(pathname2.replace(/\/+/g, "/")));
587
+ },
588
+ defer: (returnData) => {
589
+ return typeof returnData === "function" ? returnData : () => returnData;
590
+ },
591
+ fail: (statusCode, data) => {
592
+ check();
593
+ status = statusCode;
594
+ headers.delete("Cache-Control");
595
+ return {
596
+ failed: true,
597
+ ...data
598
+ };
599
+ },
600
+ text: (statusCode, text) => {
601
+ headers.set("Content-Type", "text/plain; charset=utf-8");
602
+ return send(statusCode, text);
603
+ },
604
+ html: (statusCode, html) => {
605
+ headers.set("Content-Type", "text/html; charset=utf-8");
606
+ return send(statusCode, html);
607
+ },
608
+ parseBody: async () => {
609
+ if (requestData !== void 0) {
610
+ return requestData;
611
+ }
612
+ return requestData = parseRequest(requestEv, sharedMap);
613
+ },
614
+ json: (statusCode, data) => {
615
+ headers.set("Content-Type", "application/json; charset=utf-8");
616
+ return send(statusCode, JSON.stringify(data));
617
+ },
618
+ send,
619
+ isDirty: () => {
620
+ return writableStream !== null;
511
621
  },
512
- defer: (d) => typeof d == "function" ? d : () => d,
513
- fail: (d, m) => (N(), p = d, l.delete("Cache-Control"), {
514
- failed: !0,
515
- ...m
516
- }),
517
- text: (d, m) => (l.set("Content-Type", "text/plain; charset=utf-8"), W(d, m)),
518
- html: (d, m) => (l.set("Content-Type", "text/html; charset=utf-8"), W(d, m)),
519
- parseBody: async () => w !== void 0 ? w : w = dn(b, c),
520
- json: (d, m) => (l.set("Content-Type", "application/json; charset=utf-8"), W(d, JSON.stringify(m))),
521
- send: W,
522
- isDirty: () => y !== null,
523
622
  getWritableStream: () => {
524
- if (y === null) {
525
- if (e.mode === "dev") {
526
- const d = c.get(X);
527
- d && l.set(
528
- "Server-Timing",
529
- d.map(([m, g]) => `${m};dur=${g}`).join(",")
530
- );
623
+ if (writableStream === null) {
624
+ if (serverRequestEv.mode === "dev") {
625
+ const serverTiming = sharedMap.get(RequestEvShareServerTiming);
626
+ if (serverTiming) {
627
+ headers.set(
628
+ "Server-Timing",
629
+ serverTiming.map(([name, duration]) => `${name};dur=${duration}`).join(",")
630
+ );
631
+ }
531
632
  }
532
- y = e.getWritableStream(
533
- p,
534
- l,
535
- f,
536
- o,
537
- b
633
+ writableStream = serverRequestEv.getWritableStream(
634
+ status,
635
+ headers,
636
+ cookie,
637
+ resolved,
638
+ requestEv
538
639
  );
539
640
  }
540
- return y;
641
+ return writableStream;
541
642
  }
542
643
  };
543
- return Object.freeze(b);
644
+ return Object.freeze(requestEv);
544
645
  }
545
- function U(e) {
546
- return e[Me];
646
+ function getRequestLoaders(requestEv) {
647
+ return requestEv[RequestEvLoaders];
547
648
  }
548
- function Ue(e) {
549
- return e[Ce];
649
+ function getRequestLoaderSerializationStrategyMap(requestEv) {
650
+ return requestEv[RequestEvLoaderSerializationStrategyMap];
550
651
  }
551
- function ln(e) {
552
- return e[xe];
652
+ function getRequestRoute(requestEv) {
653
+ return requestEv[RequestEvRoute];
553
654
  }
554
- function P(e) {
555
- return e[Ne];
655
+ function getRequestMode(requestEv) {
656
+ return requestEv[RequestEvMode];
556
657
  }
557
- const ue = Number.MAX_SAFE_INTEGER, dn = async ({ request: e, method: t, query: n }, r) => {
558
- const o = e.headers.get("content-type")?.split(/[;,]/, 1)[0].trim() ?? "";
559
- if (o === "application/x-www-form-urlencoded" || o === "multipart/form-data") {
560
- const i = await e.formData();
561
- return r.set(Ie, i), fn(i);
562
- } else {
563
- if (o === "application/json")
564
- return await e.json();
565
- if (o === "application/qwik-json") {
566
- if (t === "GET" && n.has(re)) {
567
- const i = n.get(re);
568
- if (i)
569
- try {
570
- return ee(decodeURIComponent(i));
571
- } catch {
572
- }
658
+ const ABORT_INDEX = Number.MAX_SAFE_INTEGER;
659
+ const parseRequest = async ({ request, method, query }, sharedMap) => {
660
+ const type = request.headers.get("content-type")?.split(/[;,]/, 1)[0].trim() ?? "";
661
+ if (type === "application/x-www-form-urlencoded" || type === "multipart/form-data") {
662
+ const formData = await request.formData();
663
+ sharedMap.set(RequestEvSharedActionFormData, formData);
664
+ return formToObj(formData);
665
+ } else if (type === "application/json") {
666
+ const data = await request.json();
667
+ return data;
668
+ } else if (type === "application/qwik-json") {
669
+ if (method === "GET" && query.has(QDATA_KEY)) {
670
+ const data = query.get(QDATA_KEY);
671
+ if (data) {
672
+ try {
673
+ return _deserialize(decodeURIComponent(data));
674
+ } catch {
675
+ }
573
676
  }
574
- return ee(await e.text());
575
677
  }
678
+ return _deserialize(await request.text());
679
+ }
680
+ return void 0;
681
+ };
682
+ const formToObj = (formData) => {
683
+ const values = [...formData.entries()].reduce((values2, [name, value]) => {
684
+ name.split(".").reduce((object, key, index, keys) => {
685
+ if (key.endsWith("[]")) {
686
+ const arrayKey = key.slice(0, -2);
687
+ object[arrayKey] = object[arrayKey] || [];
688
+ return object[arrayKey] = [...object[arrayKey], value];
689
+ }
690
+ if (index < keys.length - 1) {
691
+ return object[key] = object[key] || (Number.isNaN(+keys[index + 1]) ? {} : []);
692
+ }
693
+ return object[key] = value;
694
+ }, values2);
695
+ return values2;
696
+ }, {});
697
+ return values;
698
+ };
699
+ function getQwikRouterServerData(requestEv) {
700
+ const { params, request, status, locale, originalUrl } = requestEv;
701
+ const requestHeaders = {};
702
+ request.headers.forEach((value, key) => requestHeaders[key] = value);
703
+ const action = requestEv.sharedMap.get(RequestEvSharedActionId);
704
+ const formData = requestEv.sharedMap.get(RequestEvSharedActionFormData);
705
+ const routeName = requestEv.sharedMap.get(RequestRouteName);
706
+ const nonce = requestEv.sharedMap.get(RequestEvSharedNonce);
707
+ const headers = requestEv.request.headers;
708
+ const reconstructedUrl = new URL(originalUrl.pathname + originalUrl.search, originalUrl);
709
+ const host = headers.get("X-Forwarded-Host");
710
+ const protocol = headers.get("X-Forwarded-Proto");
711
+ if (host) {
712
+ reconstructedUrl.port = "";
713
+ reconstructedUrl.host = host;
576
714
  }
577
- }, fn = (e) => [...e.entries()].reduce((n, [r, o]) => (r.split(".").reduce((i, a, s, c) => {
578
- if (a.endsWith("[]")) {
579
- const f = a.slice(0, -2);
580
- return i[f] = i[f] || [], i[f] = [...i[f], o];
581
- }
582
- return s < c.length - 1 ? i[a] = i[a] || (Number.isNaN(+c[s + 1]) ? {} : []) : i[a] = o;
583
- }, n), n), {});
584
- function un(e) {
585
- const { params: t, request: n, status: r, locale: o, originalUrl: i } = e, a = {};
586
- n.headers.forEach((T, M) => a[M] = T);
587
- const s = e.sharedMap.get(j), c = e.sharedMap.get(Ie), f = e.sharedMap.get(Pe), l = e.sharedMap.get(sn), u = e.request.headers, h = new URL(i.pathname + i.search, i), y = u.get("X-Forwarded-Host"), w = u.get("X-Forwarded-Proto");
588
- y && (h.port = "", h.host = y), w && (h.protocol = w);
589
- const R = U(e), p = Ue(e);
715
+ if (protocol) {
716
+ reconstructedUrl.protocol = protocol;
717
+ }
718
+ const loaders = getRequestLoaders(requestEv);
719
+ const loadersSerializationStrategy = getRequestLoaderSerializationStrategyMap(requestEv);
590
720
  return {
591
- url: h.href,
592
- requestHeaders: a,
593
- locale: o(),
594
- nonce: l,
721
+ url: reconstructedUrl.href,
722
+ requestHeaders,
723
+ locale: locale(),
724
+ nonce,
595
725
  containerAttributes: {
596
- [je]: f
726
+ [Q_ROUTE]: routeName
597
727
  },
598
728
  qwikrouter: {
599
- routeName: f,
600
- ev: e,
601
- params: { ...t },
602
- loadedRoute: ln(e),
729
+ routeName,
730
+ ev: requestEv,
731
+ params: { ...params },
732
+ loadedRoute: getRequestRoute(requestEv),
603
733
  response: {
604
- status: r(),
605
- loaders: R,
606
- loadersSerializationStrategy: p,
607
- action: s,
608
- formData: c
734
+ status: status(),
735
+ loaders,
736
+ loadersSerializationStrategy,
737
+ action,
738
+ formData
609
739
  }
610
740
  }
611
741
  };
612
742
  }
613
- const hn = (e, t, n, r, o) => {
614
- const i = [], a = [], s = [], c = !!(t && bn(t[L.Mods]));
615
- if (e && he(
616
- i,
617
- a,
618
- s,
619
- e,
620
- c,
621
- n
622
- ), t) {
623
- const f = t[L.RouteName];
624
- r && (n === "POST" || n === "PUT" || n === "PATCH" || n === "DELETE") && (r === "lax-proto" ? s.unshift(An) : s.unshift(_n)), c && ((n === "POST" || n === "GET") && s.push(wn), s.push(pn), s.push(Nn));
625
- const l = t[L.Mods];
626
- s.push(Mn), he(
627
- i,
628
- a,
629
- s,
630
- l,
631
- c,
632
- n
633
- ), c && (s.push((u) => {
634
- u.sharedMap.set(Pe, f);
635
- }), s.push(mn(a)), s.push(gn(i)), s.push(o));
636
- }
637
- return s;
638
- }, he = (e, t, n, r, o, i) => {
639
- for (const a of r) {
640
- typeof a.onRequest == "function" ? n.push(a.onRequest) : Array.isArray(a.onRequest) && n.push(...a.onRequest);
641
- let s;
642
- switch (i) {
743
+ const resolveRequestHandlers = (serverPlugins, route, method, checkOrigin, renderHandler, isInternal) => {
744
+ const routeLoaders = [];
745
+ const routeActions = [];
746
+ const requestHandlers = [];
747
+ const isPageRoute = !!(route && isLastModulePageRoute(route[LoadedRouteProp.Mods]));
748
+ if (isInternal) {
749
+ requestHandlers.push(handleQDataRedirect);
750
+ }
751
+ if (serverPlugins) {
752
+ _resolveRequestHandlers(
753
+ routeLoaders,
754
+ routeActions,
755
+ requestHandlers,
756
+ serverPlugins,
757
+ isPageRoute,
758
+ method
759
+ );
760
+ }
761
+ if (route) {
762
+ const routeModules = route[LoadedRouteProp.Mods];
763
+ _resolveRequestHandlers(
764
+ routeLoaders,
765
+ routeActions,
766
+ requestHandlers,
767
+ routeModules,
768
+ isPageRoute,
769
+ method
770
+ );
771
+ const routeName = route[LoadedRouteProp.RouteName];
772
+ if (checkOrigin && (method === "POST" || method === "PUT" || method === "PATCH" || method === "DELETE")) {
773
+ if (checkOrigin === "lax-proto") {
774
+ requestHandlers.unshift(csrfLaxProtoCheckMiddleware);
775
+ } else {
776
+ requestHandlers.unshift(csrfCheckMiddleware);
777
+ }
778
+ }
779
+ if (isPageRoute) {
780
+ if (method === "POST" || method === "GET") {
781
+ requestHandlers.push(runServerFunction);
782
+ }
783
+ requestHandlers.push(fixTrailingSlash);
784
+ if (isInternal) {
785
+ requestHandlers.push(renderQData);
786
+ }
787
+ }
788
+ if (isPageRoute) {
789
+ requestHandlers.push((ev) => {
790
+ ev.sharedMap.set(RequestRouteName, routeName);
791
+ });
792
+ requestHandlers.push(actionsMiddleware(routeActions));
793
+ requestHandlers.push(loadersMiddleware(routeLoaders));
794
+ requestHandlers.push(renderHandler);
795
+ }
796
+ }
797
+ return requestHandlers;
798
+ };
799
+ const _resolveRequestHandlers = (routeLoaders, routeActions, requestHandlers, routeModules, collectActions, method) => {
800
+ for (const routeModule of routeModules) {
801
+ if (typeof routeModule.onRequest === "function") {
802
+ requestHandlers.push(routeModule.onRequest);
803
+ } else if (Array.isArray(routeModule.onRequest)) {
804
+ requestHandlers.push(...routeModule.onRequest);
805
+ }
806
+ let methodReqHandler;
807
+ switch (method) {
643
808
  case "GET": {
644
- s = a.onGet;
809
+ methodReqHandler = routeModule.onGet;
645
810
  break;
646
811
  }
647
812
  case "POST": {
648
- s = a.onPost;
813
+ methodReqHandler = routeModule.onPost;
649
814
  break;
650
815
  }
651
816
  case "PUT": {
652
- s = a.onPut;
817
+ methodReqHandler = routeModule.onPut;
653
818
  break;
654
819
  }
655
820
  case "PATCH": {
656
- s = a.onPatch;
821
+ methodReqHandler = routeModule.onPatch;
657
822
  break;
658
823
  }
659
824
  case "DELETE": {
660
- s = a.onDelete;
825
+ methodReqHandler = routeModule.onDelete;
661
826
  break;
662
827
  }
663
828
  case "OPTIONS": {
664
- s = a.onOptions;
829
+ methodReqHandler = routeModule.onOptions;
665
830
  break;
666
831
  }
667
832
  case "HEAD": {
668
- s = a.onHead;
833
+ methodReqHandler = routeModule.onHead;
669
834
  break;
670
835
  }
671
836
  }
672
- if (typeof s == "function" ? n.push(s) : Array.isArray(s) && n.push(...s), o)
673
- for (const c of Object.values(a))
674
- typeof c == "function" && (c.__brand === "server_loader" ? e.push(c) : c.__brand === "server_action" && t.push(c));
837
+ if (typeof methodReqHandler === "function") {
838
+ requestHandlers.push(methodReqHandler);
839
+ } else if (Array.isArray(methodReqHandler)) {
840
+ requestHandlers.push(...methodReqHandler);
841
+ }
842
+ if (collectActions) {
843
+ for (const module of Object.values(routeModule)) {
844
+ if (typeof module === "function") {
845
+ if (module.__brand === "server_loader") {
846
+ routeLoaders.push(module);
847
+ } else if (module.__brand === "server_action") {
848
+ routeActions.push(module);
849
+ }
850
+ }
851
+ }
852
+ }
675
853
  }
676
854
  };
677
- function mn(e) {
678
- return async (t) => {
679
- const n = t;
680
- if (n.headersSent) {
681
- n.exit();
855
+ function actionsMiddleware(routeActions) {
856
+ return async (requestEvent) => {
857
+ const requestEv = requestEvent;
858
+ if (requestEv.headersSent) {
859
+ requestEv.exit();
682
860
  return;
683
861
  }
684
- const { method: r } = n, o = U(n), i = P(n) === "dev";
685
- if (i && r === "GET" && n.query.has(te) && console.warn(
686
- `Seems like you are submitting a Qwik Action via GET request. Qwik Actions should be submitted via POST request.
687
- Make sure your <form> has method="POST" attribute, like this: <form method="POST">`
688
- ), r === "POST") {
689
- const a = n.query.get(te);
690
- if (a) {
691
- const s = globalThis._qwikActionsMap, c = e.find((f) => f.__id === a) ?? s?.get(a);
692
- if (c) {
693
- n.sharedMap.set(j, a);
694
- const f = await n.parseBody();
695
- if (!f || typeof f != "object")
862
+ const { method } = requestEv;
863
+ const loaders = getRequestLoaders(requestEv);
864
+ const isDev = getRequestMode(requestEv) === "dev";
865
+ if (isDev && method === "GET") {
866
+ if (requestEv.query.has(QACTION_KEY)) {
867
+ console.warn(
868
+ 'Seems like you are submitting a Qwik Action via GET request. Qwik Actions should be submitted via POST request.\nMake sure your <form> has method="POST" attribute, like this: <form method="POST">'
869
+ );
870
+ }
871
+ }
872
+ if (method === "POST") {
873
+ const selectedActionId = requestEv.query.get(QACTION_KEY);
874
+ if (selectedActionId) {
875
+ const serverActionsMap = globalThis._qwikActionsMap;
876
+ const action = routeActions.find((action2) => action2.__id === selectedActionId) ?? serverActionsMap?.get(selectedActionId);
877
+ if (action) {
878
+ requestEv.sharedMap.set(RequestEvSharedActionId, selectedActionId);
879
+ const data = await requestEv.parseBody();
880
+ if (!data || typeof data !== "object") {
696
881
  throw new Error(
697
- `Expected request data for the action id ${a} to be an object`
882
+ `Expected request data for the action id ${selectedActionId} to be an object`
698
883
  );
699
- const l = await qe(n, c.__validators, f, i);
700
- if (!l.success)
701
- o[a] = n.fail(l.status ?? 500, l.error);
702
- else {
703
- const u = i ? await G(
704
- n,
705
- c.__qrl.getHash(),
706
- () => c.__qrl.call(n, l.data, n)
707
- ) : await c.__qrl.call(n, l.data, n);
708
- i && Q(u, c.__qrl), o[a] = u;
884
+ }
885
+ const result = await runValidators(requestEv, action.__validators, data, isDev);
886
+ if (!result.success) {
887
+ loaders[selectedActionId] = requestEv.fail(result.status ?? 500, result.error);
888
+ } else {
889
+ const actionResolved = isDev ? await measure(
890
+ requestEv,
891
+ action.__qrl.getHash(),
892
+ () => action.__qrl.call(requestEv, result.data, requestEv)
893
+ ) : await action.__qrl.call(requestEv, result.data, requestEv);
894
+ if (isDev) {
895
+ verifySerializable(actionResolved, action.__qrl);
896
+ }
897
+ loaders[selectedActionId] = actionResolved;
709
898
  }
710
899
  }
711
900
  }
712
901
  }
713
902
  };
714
903
  }
715
- function gn(e) {
716
- return async (t) => {
717
- const n = t;
718
- if (n.headersSent) {
719
- n.exit();
904
+ function loadersMiddleware(routeLoaders) {
905
+ return async (requestEvent) => {
906
+ const requestEv = requestEvent;
907
+ if (requestEv.headersSent) {
908
+ requestEv.exit();
720
909
  return;
721
910
  }
722
- const r = U(n), o = P(n) === "dev";
723
- if (e.length > 0) {
724
- let i = [];
725
- if (n.query.has(v)) {
726
- const s = n.query.getAll(v);
727
- for (const c of e)
728
- s.includes(c.__id) ? i.push(c) : r[c.__id] = ye;
729
- } else
730
- i = e;
731
- const a = i.map(
732
- (s) => We(s, r, n, o)
911
+ const loaders = getRequestLoaders(requestEv);
912
+ const isDev = getRequestMode(requestEv) === "dev";
913
+ if (routeLoaders.length > 0) {
914
+ const resolvedLoadersPromises = routeLoaders.map(
915
+ (loader) => getRouteLoaderPromise(loader, loaders, requestEv, isDev)
733
916
  );
734
- await Promise.all(a);
917
+ await Promise.all(resolvedLoadersPromises);
735
918
  }
736
919
  };
737
920
  }
738
- async function We(e, t, n, r) {
739
- const o = e.__id;
740
- return t[o] = qe(
741
- n,
742
- e.__validators,
921
+ async function getRouteLoaderPromise(loader, loaders, requestEv, isDev) {
922
+ const loaderId = loader.__id;
923
+ loaders[loaderId] = runValidators(
924
+ requestEv,
925
+ loader.__validators,
743
926
  void 0,
744
927
  // data
745
- r
746
- ).then((a) => a.success ? r ? G(
747
- n,
748
- e.__qrl.getHash(),
749
- () => e.__qrl.call(n, n)
750
- ) : e.__qrl.call(n, n) : n.fail(a.status ?? 500, a.error)).then((a) => (typeof a == "function" ? t[o] = a() : (r && Q(a, e.__qrl), t[o] = a), a)), Ue(n).set(o, e.__serializationStrategy), t[o];
928
+ isDev
929
+ ).then((res) => {
930
+ if (res.success) {
931
+ if (isDev) {
932
+ return measure(
933
+ requestEv,
934
+ loader.__qrl.getHash(),
935
+ () => loader.__qrl.call(requestEv, requestEv)
936
+ );
937
+ } else {
938
+ return loader.__qrl.call(requestEv, requestEv);
939
+ }
940
+ } else {
941
+ return requestEv.fail(res.status ?? 500, res.error);
942
+ }
943
+ }).then((resolvedLoader) => {
944
+ if (typeof resolvedLoader === "function") {
945
+ loaders[loaderId] = resolvedLoader();
946
+ } else {
947
+ if (isDev) {
948
+ verifySerializable(resolvedLoader, loader.__qrl);
949
+ }
950
+ loaders[loaderId] = resolvedLoader;
951
+ }
952
+ return resolvedLoader;
953
+ });
954
+ const loadersSerializationStrategy = getRequestLoaderSerializationStrategyMap(requestEv);
955
+ loadersSerializationStrategy.set(loaderId, loader.__serializationStrategy);
956
+ return loaders[loaderId];
751
957
  }
752
- async function qe(e, t, n, r) {
753
- let o = {
754
- success: !0,
755
- data: n
958
+ async function runValidators(requestEv, validators, data, isDev) {
959
+ let lastResult = {
960
+ success: true,
961
+ data
756
962
  };
757
- if (t)
758
- for (const i of t)
759
- if (r ? o = await G(
760
- e,
761
- "validator$",
762
- () => i.validate(e, n)
763
- ) : o = await i.validate(e, n), o.success)
764
- n = o.data;
765
- else
766
- return o;
767
- return o;
963
+ if (validators) {
964
+ for (const validator of validators) {
965
+ if (isDev) {
966
+ lastResult = await measure(
967
+ requestEv,
968
+ `validator$`,
969
+ () => validator.validate(requestEv, data)
970
+ );
971
+ } else {
972
+ lastResult = await validator.validate(requestEv, data);
973
+ }
974
+ if (!lastResult.success) {
975
+ return lastResult;
976
+ } else {
977
+ data = lastResult.data;
978
+ }
979
+ }
980
+ }
981
+ return lastResult;
768
982
  }
769
- function yn(e) {
770
- return e ? typeof e == "object" && Symbol.asyncIterator in e : !1;
983
+ function isAsyncIterator(obj) {
984
+ return obj ? typeof obj === "object" && Symbol.asyncIterator in obj : false;
771
985
  }
772
- async function wn(e) {
773
- const t = e.query.get(Qe);
774
- if (t && e.request.headers.get("X-QRL") === t && e.request.headers.get("Content-Type") === "application/qwik-json") {
775
- e.exit();
776
- const n = P(e) === "dev", r = await e.parseBody();
777
- if (Array.isArray(r)) {
778
- const [o, ...i] = r;
779
- if (Rn(o) && o.getHash() === t) {
780
- let a;
781
- try {
782
- n ? a = await G(
783
- e,
784
- `server_${o.getSymbol()}`,
785
- () => o.apply(e, i)
786
- ) : a = await o.apply(e, i);
787
- } catch (s) {
788
- throw s instanceof F ? e.error(s.status, s.data) : e.error(500, "Invalid request");
986
+ async function runServerFunction(ev) {
987
+ const serverFnHash = ev.query.get(QFN_KEY);
988
+ if (serverFnHash && ev.request.headers.get("X-QRL") === serverFnHash && ev.request.headers.get("Content-Type") === "application/qwik-json") {
989
+ ev.exit();
990
+ const isDev = getRequestMode(ev) === "dev";
991
+ const data = await ev.parseBody();
992
+ if (Array.isArray(data)) {
993
+ const qrl = inlinedQrl(null, serverFnHash, data[1]);
994
+ let result;
995
+ try {
996
+ if (isDev) {
997
+ result = await measure(
998
+ ev,
999
+ `server_${serverFnHash}`,
1000
+ () => qrl.apply(ev, data[0])
1001
+ );
1002
+ } else {
1003
+ result = await qrl.apply(ev, data[0]);
789
1004
  }
790
- if (yn(a)) {
791
- e.headers.set("Content-Type", "text/qwik-json-stream");
792
- const c = e.getWritableStream().getWriter();
793
- for await (const f of a) {
794
- n && Q(f, o);
795
- const l = await D([f]);
796
- if (e.signal.aborted)
797
- break;
798
- await c.write(E.encode(`${l}
799
- `));
1005
+ } catch (err) {
1006
+ if (err instanceof ServerError$1) {
1007
+ throw ev.error(err.status, err.data);
1008
+ }
1009
+ console.error(`Server function ${serverFnHash} failed:`, err);
1010
+ throw ev.error(500, "Invalid request");
1011
+ }
1012
+ if (isAsyncIterator(result)) {
1013
+ ev.headers.set("Content-Type", "text/qwik-json-stream");
1014
+ const writable = ev.getWritableStream();
1015
+ const stream = writable.getWriter();
1016
+ for await (const item of result) {
1017
+ if (isDev) {
1018
+ verifySerializable(item, qrl);
800
1019
  }
801
- c.close();
802
- } else {
803
- Q(a, o), e.headers.set("Content-Type", "application/qwik-json");
804
- const s = await D([a]);
805
- e.send(200, s);
1020
+ const message = await _serialize([item]);
1021
+ if (ev.signal.aborted) {
1022
+ break;
1023
+ }
1024
+ await stream.write(encoder.encode(`${message}
1025
+ `));
806
1026
  }
807
- return;
1027
+ stream.close();
1028
+ } else {
1029
+ verifySerializable(result, qrl);
1030
+ ev.headers.set("Content-Type", "application/qwik-json");
1031
+ const message = await _serialize([result]);
1032
+ ev.send(200, message);
808
1033
  }
1034
+ return;
809
1035
  }
810
- throw e.error(500, "Invalid request");
1036
+ throw ev.error(500, "Invalid request");
811
1037
  }
812
1038
  }
813
- function pn(e) {
814
- const { basePathname: t, originalUrl: n, sharedMap: r } = e, { pathname: o, search: i } = n;
815
- if (!r.has(O) && o !== t && !o.endsWith(".html")) {
816
- if (globalThis.__NO_TRAILING_SLASH__) {
817
- if (o.endsWith("/"))
818
- throw e.redirect(
819
- V.MovedPermanently,
820
- o.slice(0, o.length - 1) + i
1039
+ function fixTrailingSlash(ev) {
1040
+ const { basePathname, originalUrl, sharedMap } = ev;
1041
+ const { pathname, search } = originalUrl;
1042
+ const isQData = sharedMap.has(IsQData);
1043
+ if (!isQData && pathname !== basePathname && !pathname.endsWith(".html")) {
1044
+ if (!globalThis.__NO_TRAILING_SLASH__) {
1045
+ if (!pathname.endsWith("/")) {
1046
+ throw ev.redirect(HttpStatus.MovedPermanently, pathname + "/" + search);
1047
+ }
1048
+ } else {
1049
+ if (pathname.endsWith("/")) {
1050
+ throw ev.redirect(
1051
+ HttpStatus.MovedPermanently,
1052
+ pathname.slice(0, pathname.length - 1) + search
821
1053
  );
822
- } else if (!o.endsWith("/"))
823
- throw e.redirect(V.MovedPermanently, o + "/" + i);
1054
+ }
1055
+ }
824
1056
  }
825
1057
  }
826
- function Q(e, t) {
1058
+ function verifySerializable(data, qrl) {
827
1059
  try {
828
- Se(e, void 0);
829
- } catch (n) {
830
- throw n instanceof Error && t.dev && (n.loc = t.dev), n;
1060
+ _verifySerializable(data, void 0);
1061
+ } catch (e) {
1062
+ if (e instanceof Error && qrl.dev) {
1063
+ e.loc = qrl.dev;
1064
+ }
1065
+ throw e;
831
1066
  }
832
1067
  }
833
- const Rn = (e) => typeof e == "function" && typeof e.getSymbol == "function";
834
- function bn(e) {
835
- const t = e[e.length - 1];
836
- return t && typeof t.default == "function";
1068
+ function isLastModulePageRoute(routeModules) {
1069
+ const lastRouteModule = routeModules[routeModules.length - 1];
1070
+ return lastRouteModule && typeof lastRouteModule.default === "function";
837
1071
  }
838
- function Z(e) {
839
- e = new URL(e), e.pathname.endsWith(C) && (e.pathname = e.pathname.slice(0, -C.length)), globalThis.__NO_TRAILING_SLASH__ ? e.pathname.endsWith("/") && (e.pathname = e.pathname.slice(0, -1)) : e.pathname.endsWith("/") || (e.pathname += "/");
840
- const t = e.search.slice(1).replaceAll(/&?q(action|data|func|loaders)=[^&]+/g, "");
841
- return `${e.pathname}${t ? `?${t}` : ""}${e.hash}`;
1072
+ function getPathname(url) {
1073
+ url = new URL(url);
1074
+ if (url.pathname.endsWith(QDATA_JSON)) {
1075
+ url.pathname = url.pathname.slice(0, -QDATA_JSON.length);
1076
+ }
1077
+ if (!globalThis.__NO_TRAILING_SLASH__) {
1078
+ if (!url.pathname.endsWith("/")) {
1079
+ url.pathname += "/";
1080
+ }
1081
+ } else {
1082
+ if (url.pathname.endsWith("/")) {
1083
+ url.pathname = url.pathname.slice(0, -1);
1084
+ }
1085
+ }
1086
+ const search = url.search.slice(1).replaceAll(/&?q(action|data|func|loaders)=[^&]+/g, "");
1087
+ return `${url.pathname}${search ? `?${search}` : ""}${url.hash}`;
842
1088
  }
843
- const E = /* @__PURE__ */ new TextEncoder();
844
- function An(e) {
845
- ke(e, "lax-proto");
1089
+ const encoder = /* @__PURE__ */ new TextEncoder();
1090
+ function csrfLaxProtoCheckMiddleware(requestEv) {
1091
+ checkCSRF(requestEv, "lax-proto");
846
1092
  }
847
- function _n(e) {
848
- ke(e);
1093
+ function csrfCheckMiddleware(requestEv) {
1094
+ checkCSRF(requestEv);
849
1095
  }
850
- function ke(e, t) {
851
- if (Cn(
852
- e.request.headers,
1096
+ function checkCSRF(requestEv, laxProto) {
1097
+ const isForm = isContentType(
1098
+ requestEv.request.headers,
853
1099
  "application/x-www-form-urlencoded",
854
1100
  "multipart/form-data",
855
1101
  "text/plain"
856
- )) {
857
- const r = e.request.headers.get("origin"), o = e.url.origin;
858
- let i = r !== o;
859
- if (i && t && r?.replace(/^http(s)?/g, "") === o.replace(/^http(s)?/g, "") && (i = !1), i)
860
- throw e.error(
1102
+ );
1103
+ if (isForm) {
1104
+ const inputOrigin = requestEv.request.headers.get("origin");
1105
+ const origin = requestEv.url.origin;
1106
+ let forbidden = inputOrigin !== origin;
1107
+ if (forbidden && laxProto && inputOrigin?.replace(/^http(s)?/g, "") === origin.replace(/^http(s)?/g, "")) {
1108
+ forbidden = false;
1109
+ }
1110
+ if (forbidden) {
1111
+ throw requestEv.error(
861
1112
  403,
862
- `CSRF check failed. Cross-site ${e.method} form submissions are forbidden.
863
- The request origin "${r}" does not match the server origin "${o}".`
1113
+ `CSRF check failed. Cross-site ${requestEv.method} form submissions are forbidden.
1114
+ The request origin "${inputOrigin}" does not match the server origin "${origin}".`
864
1115
  );
1116
+ }
865
1117
  }
866
1118
  }
867
- function Tn(e) {
868
- return async (t) => {
869
- if (t.headersSent || t.sharedMap.has(O))
1119
+ function renderQwikMiddleware(render) {
1120
+ return async (requestEv) => {
1121
+ if (requestEv.headersSent) {
870
1122
  return;
871
- t.request.headers.forEach((l, u) => l);
872
- const r = t.headers;
873
- r.has("Content-Type") || r.set("Content-Type", "text/html; charset=utf-8");
874
- const { readable: o, writable: i } = new TextEncoderStream(), a = t.getWritableStream(), s = o.pipeTo(a, { preventClose: !0 }), c = i.getWriter(), f = t.status();
1123
+ }
1124
+ const isPageDataReq = requestEv.sharedMap.has(IsQData);
1125
+ if (isPageDataReq) {
1126
+ return;
1127
+ }
1128
+ requestEv.request.headers.forEach((value, key) => value);
1129
+ const responseHeaders = requestEv.headers;
1130
+ if (!responseHeaders.has("Content-Type")) {
1131
+ responseHeaders.set("Content-Type", "text/html; charset=utf-8");
1132
+ }
1133
+ const { readable, writable } = new TextEncoderStream();
1134
+ const writableStream = requestEv.getWritableStream();
1135
+ const pipe = readable.pipeTo(writableStream, { preventClose: true });
1136
+ const stream = writable.getWriter();
1137
+ const status = requestEv.status();
875
1138
  try {
876
- const l = P(t) === "static", u = un(t), h = await e({
877
- base: t.basePathname + "build/",
878
- stream: c,
879
- serverData: u,
1139
+ const isStatic = getRequestMode(requestEv) === "static";
1140
+ const serverData = getQwikRouterServerData(requestEv);
1141
+ const result = await render({
1142
+ base: requestEv.basePathname + "build/",
1143
+ stream,
1144
+ serverData,
880
1145
  containerAttributes: {
881
- "q:render": l ? "static" : "",
882
- ...u.containerAttributes
1146
+ ["q:render"]: isStatic ? "static" : "",
1147
+ ...serverData.containerAttributes
883
1148
  }
884
- }), y = {
885
- loaders: U(t),
886
- action: t.sharedMap.get(j),
887
- status: f !== 200 ? f : 200,
888
- href: Z(t.url)
1149
+ });
1150
+ const qData = {
1151
+ loaders: getRequestLoaders(requestEv),
1152
+ action: requestEv.sharedMap.get(RequestEvSharedActionId),
1153
+ status: status !== 200 ? status : 200,
1154
+ href: getPathname(requestEv.url)
889
1155
  };
890
- typeof h.html == "string" && await c.write(h.html), t.sharedMap.set(Oe, y);
1156
+ if (typeof result.html === "string") {
1157
+ await stream.write(result.html);
1158
+ }
1159
+ requestEv.sharedMap.set(RequestEvShareQData, qData);
891
1160
  } finally {
892
- await c.ready, await c.close(), await s;
1161
+ await stream.ready;
1162
+ await stream.close();
1163
+ await pipe;
893
1164
  }
894
- await a.close();
1165
+ await writableStream.close();
895
1166
  };
896
1167
  }
897
- async function Mn(e) {
898
- if (!e.sharedMap.has(O))
899
- return;
1168
+ async function handleQDataRedirect(requestEv) {
900
1169
  try {
901
- await e.next();
902
- } catch (i) {
903
- if (!(i instanceof H))
904
- throw i;
1170
+ await requestEv.next();
1171
+ } catch (err) {
1172
+ if (!(err instanceof RedirectMessage$1)) {
1173
+ throw err;
1174
+ }
905
1175
  }
906
- if (e.headersSent)
1176
+ if (requestEv.headersSent) {
907
1177
  return;
908
- const n = e.status(), r = e.headers.get("Location");
909
- if (n >= 301 && n <= 308 && r) {
910
- const i = xn(r);
911
- if (i) {
912
- e.headers.set("Location", i), e.getWritableStream().close();
1178
+ }
1179
+ const status = requestEv.status();
1180
+ const location = requestEv.headers.get("Location");
1181
+ const isRedirect = status >= 301 && status <= 308 && location;
1182
+ if (isRedirect) {
1183
+ const adaptedLocation = makeQDataPath(location);
1184
+ if (adaptedLocation) {
1185
+ requestEv.headers.set("Location", adaptedLocation);
1186
+ requestEv.getWritableStream().close();
913
1187
  return;
914
- } else
915
- e.status(200), e.headers.delete("Location");
1188
+ } else {
1189
+ requestEv.status(200);
1190
+ requestEv.headers.delete("Location");
1191
+ }
916
1192
  }
917
1193
  }
918
- async function Nn(e) {
919
- if (!e.sharedMap.has(O) || (await e.next(), e.headersSent || e.exited))
1194
+ async function renderQData(requestEv) {
1195
+ await requestEv.next();
1196
+ if (requestEv.headersSent || requestEv.exited) {
920
1197
  return;
921
- const n = e.status(), r = e.headers.get("Location");
922
- e.request.headers.forEach((l, u) => l), e.headers.set("Content-Type", "application/json; charset=utf-8");
923
- let o = U(e);
924
- const i = e.query.getAll(v), a = i.length > 0;
925
- if (a) {
926
- const l = {};
927
- for (const u of i) {
928
- const h = o[u];
929
- l[u] = h;
1198
+ }
1199
+ const status = requestEv.status();
1200
+ const redirectLocation = requestEv.headers.get("Location");
1201
+ requestEv.request.headers.forEach((value, key) => value);
1202
+ requestEv.headers.set("Content-Type", "application/json; charset=utf-8");
1203
+ let loaders = getRequestLoaders(requestEv);
1204
+ const selectedLoaderIds = requestEv.query.getAll(QLOADER_KEY);
1205
+ const hasCustomLoaders = selectedLoaderIds.length > 0;
1206
+ if (hasCustomLoaders) {
1207
+ const selectedLoaders = {};
1208
+ for (const loaderId of selectedLoaderIds) {
1209
+ const loader = loaders[loaderId];
1210
+ selectedLoaders[loaderId] = loader;
930
1211
  }
931
- o = l;
1212
+ loaders = selectedLoaders;
932
1213
  }
933
- const s = a ? {
1214
+ const qData = hasCustomLoaders ? {
934
1215
  // send minimal data to the client
935
- loaders: o,
936
- status: n !== 200 ? n : 200,
937
- href: Z(e.url)
1216
+ loaders,
1217
+ status: status !== 200 ? status : 200,
1218
+ href: getPathname(requestEv.url)
938
1219
  } : {
939
- loaders: o,
940
- action: e.sharedMap.get(j),
941
- status: n !== 200 ? n : 200,
942
- href: Z(e.url),
943
- redirect: r ?? void 0,
944
- isRewrite: e.sharedMap.get(Le)
945
- }, c = e.getWritableStream().getWriter(), f = await D([s]);
946
- c.write(E.encode(f)), e.sharedMap.set(Oe, s), c.close();
1220
+ loaders,
1221
+ action: requestEv.sharedMap.get(RequestEvSharedActionId),
1222
+ status: status !== 200 ? status : 200,
1223
+ href: getPathname(requestEv.url),
1224
+ redirect: redirectLocation ?? void 0,
1225
+ isRewrite: requestEv.sharedMap.get(RequestEvIsRewrite)
1226
+ };
1227
+ const writer = requestEv.getWritableStream().getWriter();
1228
+ const data = await _serialize([qData]);
1229
+ writer.write(encoder.encode(data));
1230
+ requestEv.sharedMap.set(RequestEvShareQData, qData);
1231
+ writer.close();
947
1232
  }
948
- function xn(e) {
949
- if (e.startsWith("/")) {
950
- const t = C, n = new URL(e, "http://localhost");
951
- return (n.pathname.endsWith("/") ? n.pathname.slice(0, -1) : n.pathname) + (t.startsWith("/") ? "" : "/") + t + n.search;
952
- } else
953
- return;
1233
+ function makeQDataPath(href) {
1234
+ if (href.startsWith("/")) {
1235
+ if (!href.includes(QDATA_JSON)) {
1236
+ const url = new URL(href, "http://localhost");
1237
+ const pathname = url.pathname.endsWith("/") ? url.pathname.slice(0, -1) : url.pathname;
1238
+ return pathname + QDATA_JSON + url.search;
1239
+ }
1240
+ return href;
1241
+ } else {
1242
+ return void 0;
1243
+ }
954
1244
  }
955
- function me() {
956
- return typeof performance < "u" ? performance.now() : 0;
1245
+ function now() {
1246
+ return typeof performance !== "undefined" ? performance.now() : 0;
957
1247
  }
958
- async function G(e, t, n) {
959
- const r = me();
1248
+ async function measure(requestEv, name, fn) {
1249
+ const start = now();
960
1250
  try {
961
- return await n();
1251
+ return await fn();
962
1252
  } finally {
963
- const o = me() - r;
964
- let i = e.sharedMap.get(X);
965
- i || e.sharedMap.set(X, i = []), i.push([t, o]);
1253
+ const duration = now() - start;
1254
+ let measurements = requestEv.sharedMap.get(RequestEvShareServerTiming);
1255
+ if (!measurements) {
1256
+ requestEv.sharedMap.set(RequestEvShareServerTiming, measurements = []);
1257
+ }
1258
+ measurements.push([name, duration]);
966
1259
  }
967
1260
  }
968
- function Cn(e, ...t) {
969
- const n = e.get("content-type")?.split(/;/, 1)[0].trim() ?? "";
970
- return t.includes(n);
1261
+ function isContentType(headers, ...types) {
1262
+ const type = headers.get("content-type")?.split(/;/, 1)[0].trim() ?? "";
1263
+ return types.includes(type);
1264
+ }
1265
+ let _asyncRequestStore;
1266
+ if (isServer) {
1267
+ import("node:async_hooks").then((module) => {
1268
+ _asyncRequestStore = new module.AsyncLocalStorage();
1269
+ }).catch((err) => {
1270
+ console.warn(
1271
+ "\n=====================\n Qwik Router Warning:\n AsyncLocalStorage is not available, continuing without it.\n This impacts concurrent async server calls, where they lose access to the ServerRequestEv object.\n=====================\n\n",
1272
+ err
1273
+ );
1274
+ });
971
1275
  }
972
- let J;
973
- async function Wn(e, t) {
974
- const { render: n, checkOrigin: r } = t;
975
- let { qwikRouterConfig: o } = t;
976
- if (o || (J || (J = await import("@qwik-router-config")), o = J), !o)
1276
+ let qwikRouterConfigActual;
1277
+ async function requestHandler(serverRequestEv, opts) {
1278
+ const { render, checkOrigin } = opts;
1279
+ let { qwikRouterConfig } = opts;
1280
+ if (!qwikRouterConfig) {
1281
+ if (!qwikRouterConfigActual) {
1282
+ qwikRouterConfigActual = await import("@qwik-router-config");
1283
+ }
1284
+ qwikRouterConfig = qwikRouterConfigActual;
1285
+ }
1286
+ if (!qwikRouterConfig) {
977
1287
  throw new Error("qwikRouterConfig is required.");
978
- const i = e.url.pathname, a = fe(i), s = await ge(
979
- o,
980
- a,
981
- e.request.method,
982
- r ?? !0,
983
- n
1288
+ }
1289
+ const { pathname, isInternal } = getRouteMatchPathname(serverRequestEv.url.pathname);
1290
+ const routeAndHandlers = await loadRequestHandlers(
1291
+ qwikRouterConfig,
1292
+ pathname,
1293
+ serverRequestEv.request.method,
1294
+ checkOrigin ?? true,
1295
+ render,
1296
+ isInternal
984
1297
  );
985
- if (s) {
986
- const [c, f] = s;
987
- return an(
988
- e,
989
- c,
990
- f,
991
- async (u) => {
992
- const h = fe(u.pathname), y = await ge(
993
- o,
994
- h,
995
- e.request.method,
996
- r ?? !0,
997
- n
998
- );
999
- if (y) {
1000
- const [w, R] = y;
1001
- return { loadedRoute: w, requestHandlers: R };
1002
- } else
1003
- return { loadedRoute: null, requestHandlers: [] };
1004
- },
1005
- o.basePathname
1298
+ if (routeAndHandlers) {
1299
+ const [route, requestHandlers] = routeAndHandlers;
1300
+ const rebuildRouteInfo = async (url) => {
1301
+ const { pathname: pathname2 } = getRouteMatchPathname(url.pathname);
1302
+ const routeAndHandlers2 = await loadRequestHandlers(
1303
+ qwikRouterConfig,
1304
+ pathname2,
1305
+ serverRequestEv.request.method,
1306
+ checkOrigin ?? true,
1307
+ render,
1308
+ isInternal
1309
+ );
1310
+ if (routeAndHandlers2) {
1311
+ const [loadedRoute, requestHandlers2] = routeAndHandlers2;
1312
+ return { loadedRoute, requestHandlers: requestHandlers2 };
1313
+ } else {
1314
+ return { loadedRoute: null, requestHandlers: [] };
1315
+ }
1316
+ };
1317
+ return runQwikRouter(
1318
+ serverRequestEv,
1319
+ route,
1320
+ requestHandlers,
1321
+ rebuildRouteInfo,
1322
+ qwikRouterConfig.basePathname
1006
1323
  );
1007
1324
  }
1008
1325
  return null;
1009
1326
  }
1010
- async function ge(e, t, n, r, o) {
1011
- const { routes: i, serverPlugins: a, menus: s, cacheModules: c } = e, f = await Ke(i, s, c, t), l = hn(
1012
- a,
1013
- f,
1014
- n,
1015
- r,
1016
- Tn(o)
1327
+ async function loadRequestHandlers(qwikRouterConfig, pathname, method, checkOrigin, renderFn, isInternal) {
1328
+ const { routes, serverPlugins, menus, cacheModules } = qwikRouterConfig;
1329
+ const route = await loadRoute(routes, menus, cacheModules, pathname, isInternal);
1330
+ const requestHandlers = resolveRequestHandlers(
1331
+ serverPlugins,
1332
+ route,
1333
+ method,
1334
+ checkOrigin,
1335
+ renderQwikMiddleware(renderFn),
1336
+ isInternal
1017
1337
  );
1018
- return l.length > 0 ? [f, l] : null;
1338
+ if (requestHandlers.length > 0) {
1339
+ return [route, requestHandlers];
1340
+ }
1341
+ return null;
1019
1342
  }
1020
- const Pn = [
1343
+ const notFounds = [
1021
1344
  // Will be replaced in post-build with the 404s generated by SSG
1022
1345
  "__QWIK_ROUTER_NOT_FOUND_ARRAY__"
1023
1346
  ];
1024
- function qn(e) {
1025
- for (const [t, n] of Pn)
1026
- if (e.startsWith(t))
1027
- return n;
1028
- return _e(404, "Resource Not Found");
1347
+ function getNotFound(prefix) {
1348
+ for (const [path, html] of notFounds) {
1349
+ if (prefix.startsWith(path)) {
1350
+ return html;
1351
+ }
1352
+ }
1353
+ return minimalHtmlResponse(404, "Resource Not Found");
1029
1354
  }
1030
- const Y = /* @__PURE__ */ new Set(["__QWIK_ROUTER_STATIC_PATHS_ARRAY__"]);
1031
- function kn(e, t) {
1032
- if (e.toUpperCase() !== "GET")
1033
- return !1;
1034
- const n = t.pathname;
1035
- if (n.startsWith("/" + (globalThis.__QWIK_BUILD_DIR__ || "build") + "/") || n.startsWith("/" + (globalThis.__QWIK_ASSETS_DIR__ || "assets") + "/") || Y.has(n))
1036
- return !0;
1037
- if (n.endsWith("/q-data.json")) {
1038
- const r = n.replace(/\/q-data.json$/, "");
1039
- if (Y.has(r + "/") || Y.has(r))
1040
- return !0;
1041
- }
1042
- return !1;
1355
+ const staticPaths = /* @__PURE__ */ new Set(["__QWIK_ROUTER_STATIC_PATHS_ARRAY__"]);
1356
+ function isStaticPath(method, url) {
1357
+ if (method.toUpperCase() !== "GET") {
1358
+ return false;
1359
+ }
1360
+ const p = url.pathname;
1361
+ if (p.startsWith("/" + (globalThis.__QWIK_BUILD_DIR__ || "build") + "/")) {
1362
+ return true;
1363
+ }
1364
+ if (p.startsWith("/" + (globalThis.__QWIK_ASSETS_DIR__ || "assets") + "/")) {
1365
+ return true;
1366
+ }
1367
+ if (staticPaths.has(p)) {
1368
+ return true;
1369
+ }
1370
+ if (p.endsWith("/q-data.json")) {
1371
+ const pWithoutQdata = p.replace(/\/q-data.json$/, "");
1372
+ if (staticPaths.has(pWithoutQdata + "/")) {
1373
+ return true;
1374
+ }
1375
+ if (staticPaths.has(pWithoutQdata)) {
1376
+ return true;
1377
+ }
1378
+ }
1379
+ return false;
1043
1380
  }
1044
- class $n extends Error {
1045
- constructor(t, n) {
1046
- super(typeof n == "string" ? n : void 0), this.status = t, this.data = n;
1381
+ class ServerError extends Error {
1382
+ constructor(status, data) {
1383
+ super(typeof data === "string" ? data : void 0);
1384
+ this.status = status;
1385
+ this.data = data;
1047
1386
  }
1048
1387
  }
1049
- class $e {
1388
+ class AbortMessage {
1050
1389
  }
1051
- class Dn extends $e {
1390
+ class RedirectMessage extends AbortMessage {
1052
1391
  }
1053
- class Fn extends $e {
1054
- constructor(t) {
1055
- super(), this.pathname = t;
1392
+ class RewriteMessage extends AbortMessage {
1393
+ constructor(pathname) {
1394
+ super();
1395
+ this.pathname = pathname;
1056
1396
  }
1057
1397
  }
1058
- class Sn {
1059
- #e = null;
1060
- #n = new TextEncoder();
1061
- #t = new TransformStream({
1062
- transform: (t, n) => {
1063
- t = String(t);
1064
- let r = "";
1065
- for (let o = 0; o < t.length; o++) {
1066
- const i = t[o], a = i.charCodeAt(0);
1067
- if (this.#e !== null) {
1068
- const s = this.#e;
1069
- if (this.#e = null, 56320 <= a && a <= 57343) {
1070
- r += s + i;
1398
+ class _TextEncoderStream_polyfill {
1399
+ constructor() {
1400
+ __privateAdd(this, _pendingHighSurrogate, null);
1401
+ __privateAdd(this, _handle, new TextEncoder());
1402
+ __privateAdd(this, _transform, new TransformStream({
1403
+ transform: (chunk, controller) => {
1404
+ chunk = String(chunk);
1405
+ let finalChunk = "";
1406
+ for (let i = 0; i < chunk.length; i++) {
1407
+ const item = chunk[i];
1408
+ const codeUnit = item.charCodeAt(0);
1409
+ if (__privateGet(this, _pendingHighSurrogate) !== null) {
1410
+ const highSurrogate = __privateGet(this, _pendingHighSurrogate);
1411
+ __privateSet(this, _pendingHighSurrogate, null);
1412
+ if (56320 <= codeUnit && codeUnit <= 57343) {
1413
+ finalChunk += highSurrogate + item;
1414
+ continue;
1415
+ }
1416
+ finalChunk += "�";
1417
+ }
1418
+ if (55296 <= codeUnit && codeUnit <= 56319) {
1419
+ __privateSet(this, _pendingHighSurrogate, item);
1071
1420
  continue;
1072
1421
  }
1073
- r += "�";
1422
+ if (56320 <= codeUnit && codeUnit <= 57343) {
1423
+ finalChunk += "�";
1424
+ continue;
1425
+ }
1426
+ finalChunk += item;
1074
1427
  }
1075
- if (55296 <= a && a <= 56319) {
1076
- this.#e = i;
1077
- continue;
1428
+ if (finalChunk) {
1429
+ controller.enqueue(__privateGet(this, _handle).encode(finalChunk));
1078
1430
  }
1079
- if (56320 <= a && a <= 57343) {
1080
- r += "�";
1081
- continue;
1431
+ },
1432
+ flush: (controller) => {
1433
+ if (__privateGet(this, _pendingHighSurrogate) !== null) {
1434
+ controller.enqueue(new Uint8Array([239, 191, 189]));
1082
1435
  }
1083
- r += i;
1084
1436
  }
1085
- r && n.enqueue(this.#n.encode(r));
1086
- },
1087
- flush: (t) => {
1088
- this.#e !== null && t.enqueue(new Uint8Array([239, 191, 189]));
1089
- }
1090
- });
1437
+ }));
1438
+ }
1091
1439
  get encoding() {
1092
- return this.#n.encoding;
1440
+ return __privateGet(this, _handle).encoding;
1093
1441
  }
1094
1442
  get readable() {
1095
- return this.#t.readable;
1443
+ return __privateGet(this, _transform).readable;
1096
1444
  }
1097
1445
  get writable() {
1098
- return this.#t.writable;
1446
+ return __privateGet(this, _transform).writable;
1099
1447
  }
1100
1448
  get [Symbol.toStringTag]() {
1101
1449
  return "TextEncoderStream";
1102
1450
  }
1103
1451
  }
1452
+ _pendingHighSurrogate = new WeakMap();
1453
+ _handle = new WeakMap();
1454
+ _transform = new WeakMap();
1104
1455
  export {
1105
- $e as AbortMessage,
1106
- Dn as RedirectMessage,
1107
- Oe as RequestEvShareQData,
1108
- Fn as RewriteMessage,
1109
- $n as ServerError,
1110
- Sn as _TextEncoderStream_polyfill,
1111
- K as getErrorHtml,
1112
- qn as getNotFound,
1113
- kn as isStaticPath,
1114
- Un as mergeHeadersCookies,
1115
- Wn as requestHandler
1456
+ AbortMessage,
1457
+ RedirectMessage,
1458
+ RequestEvShareQData,
1459
+ RewriteMessage,
1460
+ ServerError,
1461
+ _TextEncoderStream_polyfill,
1462
+ _asyncRequestStore,
1463
+ getErrorHtml,
1464
+ getNotFound,
1465
+ isStaticPath,
1466
+ mergeHeadersCookies,
1467
+ requestHandler
1116
1468
  };