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

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