hermium 0.1.2 → 0.1.4

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 (150) hide show
  1. package/bin/hermium.mjs +184 -145
  2. package/dist/server/index.mjs +65 -65
  3. package/dist/web-server/__23tanstack-start-plugin-adapters-Cwee5PKy.mjs +6 -0
  4. package/dist/web-server/_chunks/ssr-renderer.mjs +22 -0
  5. package/dist/web-server/_libs/babel__runtime.mjs +237 -0
  6. package/dist/web-server/_libs/bail.mjs +8 -0
  7. package/dist/web-server/_libs/base-ui__react.mjs +9554 -0
  8. package/dist/web-server/_libs/base-ui__utils.mjs +1101 -0
  9. package/dist/web-server/_libs/ccount.mjs +16 -0
  10. package/dist/web-server/_libs/character-entities-legacy.mjs +111 -0
  11. package/dist/web-server/_libs/character-entities.mjs +2130 -0
  12. package/dist/web-server/_libs/character-reference-invalid.mjs +33 -0
  13. package/dist/web-server/_libs/class-variance-authority.mjs +44 -0
  14. package/dist/web-server/_libs/clsx.mjs +16 -0
  15. package/dist/web-server/_libs/comma-separated-tokens.mjs +31 -0
  16. package/dist/web-server/_libs/cookie-es.mjs +44 -0
  17. package/dist/web-server/_libs/croner.mjs +1 -0
  18. package/dist/web-server/_libs/crossws.mjs +1 -0
  19. package/dist/web-server/_libs/decode-named-character-reference+[...].mjs +8 -0
  20. package/dist/web-server/_libs/devlop.mjs +8 -0
  21. package/dist/web-server/_libs/escape-string-regexp.mjs +9 -0
  22. package/dist/web-server/_libs/estree-util-is-identifier-name.mjs +11 -0
  23. package/dist/web-server/_libs/extend.mjs +97 -0
  24. package/dist/web-server/_libs/fault.mjs +1 -0
  25. package/dist/web-server/_libs/floating-ui__core.mjs +663 -0
  26. package/dist/web-server/_libs/floating-ui__dom.mjs +624 -0
  27. package/dist/web-server/_libs/floating-ui__react-dom.mjs +279 -0
  28. package/dist/web-server/_libs/floating-ui__utils.mjs +322 -0
  29. package/dist/web-server/_libs/format.mjs +1 -0
  30. package/dist/web-server/_libs/h3.mjs +408 -0
  31. package/dist/web-server/_libs/hast-util-parse-selector.mjs +39 -0
  32. package/dist/web-server/_libs/hast-util-to-jsx-runtime.mjs +388 -0
  33. package/dist/web-server/_libs/hast-util-whitespace.mjs +10 -0
  34. package/dist/web-server/_libs/hastscript.mjs +200 -0
  35. package/dist/web-server/_libs/highlight.js.mjs +1 -0
  36. package/dist/web-server/_libs/hookable.mjs +1 -0
  37. package/dist/web-server/_libs/html-url-attributes.mjs +26 -0
  38. package/dist/web-server/_libs/inline-style-parser.mjs +142 -0
  39. package/dist/web-server/_libs/is-alphabetical.mjs +7 -0
  40. package/dist/web-server/_libs/is-alphanumerical.mjs +8 -0
  41. package/dist/web-server/_libs/is-decimal.mjs +7 -0
  42. package/dist/web-server/_libs/is-hexadecimal.mjs +7 -0
  43. package/dist/web-server/_libs/is-plain-obj.mjs +10 -0
  44. package/dist/web-server/_libs/isbot.mjs +21 -0
  45. package/dist/web-server/_libs/longest-streak.mjs +25 -0
  46. package/dist/web-server/_libs/lowlight.mjs +1 -0
  47. package/dist/web-server/_libs/markdown-table.mjs +142 -0
  48. package/dist/web-server/_libs/mdast-util-find-and-replace.mjs +109 -0
  49. package/dist/web-server/_libs/mdast-util-from-markdown.mjs +717 -0
  50. package/dist/web-server/_libs/mdast-util-gfm-autolink-literal+[...].mjs +156 -0
  51. package/dist/web-server/_libs/mdast-util-gfm-footnote.mjs +117 -0
  52. package/dist/web-server/_libs/mdast-util-gfm-strikethrough.mjs +54 -0
  53. package/dist/web-server/_libs/mdast-util-gfm-table.mjs +157 -0
  54. package/dist/web-server/_libs/mdast-util-gfm-task-list-item.mjs +77 -0
  55. package/dist/web-server/_libs/mdast-util-gfm.mjs +29 -0
  56. package/dist/web-server/_libs/mdast-util-phrasing.mjs +30 -0
  57. package/dist/web-server/_libs/mdast-util-to-hast.mjs +710 -0
  58. package/dist/web-server/_libs/mdast-util-to-markdown.mjs +798 -0
  59. package/dist/web-server/_libs/mdast-util-to-string.mjs +38 -0
  60. package/dist/web-server/_libs/micromark-core-commonmark.mjs +2259 -0
  61. package/dist/web-server/_libs/micromark-extension-gfm-autolink-literal+[...].mjs +344 -0
  62. package/dist/web-server/_libs/micromark-extension-gfm-footnote+[...].mjs +279 -0
  63. package/dist/web-server/_libs/micromark-extension-gfm-strikethrough+[...].mjs +98 -0
  64. package/dist/web-server/_libs/micromark-extension-gfm-table.mjs +491 -0
  65. package/dist/web-server/_libs/micromark-extension-gfm-tagfilter+[...].mjs +1 -0
  66. package/dist/web-server/_libs/micromark-extension-gfm-task-list-item+[...].mjs +77 -0
  67. package/dist/web-server/_libs/micromark-extension-gfm.mjs +18 -0
  68. package/dist/web-server/_libs/micromark-factory-destination.mjs +94 -0
  69. package/dist/web-server/_libs/micromark-factory-label.mjs +63 -0
  70. package/dist/web-server/_libs/micromark-factory-space.mjs +24 -0
  71. package/dist/web-server/_libs/micromark-factory-title.mjs +65 -0
  72. package/dist/web-server/_libs/micromark-factory-whitespace.mjs +22 -0
  73. package/dist/web-server/_libs/micromark-util-character.mjs +44 -0
  74. package/dist/web-server/_libs/micromark-util-chunked.mjs +36 -0
  75. package/dist/web-server/_libs/micromark-util-classify-character+[...].mjs +12 -0
  76. package/dist/web-server/_libs/micromark-util-combine-extensions+[...].mjs +41 -0
  77. package/dist/web-server/_libs/micromark-util-decode-numeric-character-reference+[...].mjs +19 -0
  78. package/dist/web-server/_libs/micromark-util-decode-string.mjs +21 -0
  79. package/dist/web-server/_libs/micromark-util-encode.mjs +1 -0
  80. package/dist/web-server/_libs/micromark-util-html-tag-name.mjs +69 -0
  81. package/dist/web-server/_libs/micromark-util-normalize-identifier+[...].mjs +6 -0
  82. package/dist/web-server/_libs/micromark-util-resolve-all.mjs +15 -0
  83. package/dist/web-server/_libs/micromark-util-sanitize-uri.mjs +41 -0
  84. package/dist/web-server/_libs/micromark-util-subtokenize.mjs +346 -0
  85. package/dist/web-server/_libs/micromark.mjs +906 -0
  86. package/dist/web-server/_libs/ocache.mjs +1 -0
  87. package/dist/web-server/_libs/ohash.mjs +1 -0
  88. package/dist/web-server/_libs/parse-entities.mjs +245 -0
  89. package/dist/web-server/_libs/property-information.mjs +1210 -0
  90. package/dist/web-server/_libs/react-dom.mjs +10779 -0
  91. package/dist/web-server/_libs/react-markdown.mjs +147 -0
  92. package/dist/web-server/_libs/react-syntax-highlighter.mjs +941 -0
  93. package/dist/web-server/_libs/react.mjs +513 -0
  94. package/dist/web-server/_libs/refractor.mjs +2425 -0
  95. package/dist/web-server/_libs/remark-gfm.mjs +20 -0
  96. package/dist/web-server/_libs/remark-parse.mjs +19 -0
  97. package/dist/web-server/_libs/remark-rehype.mjs +21 -0
  98. package/dist/web-server/_libs/reselect.mjs +1 -0
  99. package/dist/web-server/_libs/rou3.mjs +8 -0
  100. package/dist/web-server/_libs/seroval-plugins.mjs +58 -0
  101. package/dist/web-server/_libs/seroval.mjs +1775 -0
  102. package/dist/web-server/_libs/space-separated-tokens.mjs +11 -0
  103. package/dist/web-server/_libs/srvx.mjs +781 -0
  104. package/dist/web-server/_libs/style-to-js.mjs +72 -0
  105. package/dist/web-server/_libs/style-to-object.mjs +38 -0
  106. package/dist/web-server/_libs/tabler__icons-react.mjs +224 -0
  107. package/dist/web-server/_libs/tanstack__history.mjs +204 -0
  108. package/dist/web-server/_libs/tanstack__query-core.mjs +2552 -0
  109. package/dist/web-server/_libs/tanstack__react-query.mjs +190 -0
  110. package/dist/web-server/_libs/tanstack__react-router.mjs +1120 -0
  111. package/dist/web-server/_libs/tanstack__react-store.mjs +2 -0
  112. package/dist/web-server/_libs/tanstack__router-core.mjs +4288 -0
  113. package/dist/web-server/_libs/tanstack__store.mjs +1 -0
  114. package/dist/web-server/_libs/trim-lines.mjs +41 -0
  115. package/dist/web-server/_libs/trough.mjs +85 -0
  116. package/dist/web-server/_libs/ufo.mjs +54 -0
  117. package/dist/web-server/_libs/unctx.mjs +1 -0
  118. package/dist/web-server/_libs/ungap__structured-clone.mjs +224 -0
  119. package/dist/web-server/_libs/unified.mjs +661 -0
  120. package/dist/web-server/_libs/unist-util-is.mjs +100 -0
  121. package/dist/web-server/_libs/unist-util-position.mjs +27 -0
  122. package/dist/web-server/_libs/unist-util-stringify-position.mjs +27 -0
  123. package/dist/web-server/_libs/unist-util-visit-parents.mjs +83 -0
  124. package/dist/web-server/_libs/unist-util-visit.mjs +24 -0
  125. package/dist/web-server/_libs/unstorage.mjs +1 -0
  126. package/dist/web-server/_libs/use-sync-external-store.mjs +139 -0
  127. package/dist/web-server/_libs/vfile-message.mjs +138 -0
  128. package/dist/web-server/_libs/vfile.mjs +467 -0
  129. package/dist/web-server/_libs/zod.mjs +3915 -0
  130. package/dist/web-server/_libs/zustand.mjs +343 -0
  131. package/dist/web-server/_libs/zwitch.mjs +1 -0
  132. package/dist/web-server/_ssr/index-BLK6uN4p.mjs +612 -0
  133. package/dist/web-server/_ssr/index-BkkxTg0a.mjs +1855 -0
  134. package/dist/web-server/_ssr/index-Bp9a_nTf.mjs +66 -0
  135. package/dist/web-server/_ssr/index-C8t8AZQG.mjs +513 -0
  136. package/dist/web-server/_ssr/index-DSIu0x-q.mjs +449 -0
  137. package/dist/web-server/_ssr/index-DqFrn6kj.mjs +278 -0
  138. package/dist/web-server/_ssr/index-EKE8NFy_.mjs +189 -0
  139. package/dist/web-server/_ssr/index-JzLhPyir.mjs +213 -0
  140. package/dist/web-server/_ssr/index-wTy_4MhH.mjs +369 -0
  141. package/dist/web-server/_ssr/index.mjs +1558 -0
  142. package/dist/web-server/_ssr/input-BQFduUUo.mjs +20 -0
  143. package/dist/web-server/_ssr/router-59cN5lqo.mjs +1998 -0
  144. package/dist/web-server/_ssr/start-HYkvq4Ni.mjs +4 -0
  145. package/dist/web-server/_ssr/switch-Bim4kX8N.mjs +33 -0
  146. package/dist/web-server/_ssr/syntax-highlighter-5vezNTce.mjs +62 -0
  147. package/dist/web-server/_ssr/textarea-CK0ROhfF.mjs +18 -0
  148. package/dist/web-server/_tanstack-start-manifest_v-DLw6M7p4.mjs +4 -0
  149. package/dist/web-server/index.mjs +611 -0
  150. package/package.json +1 -1
@@ -0,0 +1,4288 @@
1
+ import { p as parseHref } from "./tanstack__history.mjs";
2
+ import { s as splitSetCookieString } from "./cookie-es.mjs";
3
+ import { a as ai, r as re, S as Sn, d as dn } from "./seroval.mjs";
4
+ import { p } from "./seroval-plugins.mjs";
5
+ import { ReadableStream as ReadableStream$1 } from "node:stream/web";
6
+ import { Readable } from "node:stream";
7
+ const isServer = true;
8
+ function last(arr) {
9
+ return arr[arr.length - 1];
10
+ }
11
+ function isFunction(d) {
12
+ return typeof d === "function";
13
+ }
14
+ function functionalUpdate(updater, previous) {
15
+ if (isFunction(updater)) return updater(previous);
16
+ return updater;
17
+ }
18
+ const hasOwn = Object.prototype.hasOwnProperty;
19
+ function hasKeys(obj) {
20
+ for (const key in obj) if (hasOwn.call(obj, key)) return true;
21
+ return false;
22
+ }
23
+ const createNull = () => /* @__PURE__ */ Object.create(null);
24
+ const nullReplaceEqualDeep = (prev, next) => replaceEqualDeep(prev, next, createNull);
25
+ function replaceEqualDeep(prev, _next, _makeObj = () => ({}), _depth = 0) {
26
+ return _next;
27
+ }
28
+ function isPlainObject(o) {
29
+ if (!hasObjectPrototype(o)) return false;
30
+ const ctor = o.constructor;
31
+ if (typeof ctor === "undefined") return true;
32
+ const prot = ctor.prototype;
33
+ if (!hasObjectPrototype(prot)) return false;
34
+ if (!prot.hasOwnProperty("isPrototypeOf")) return false;
35
+ return true;
36
+ }
37
+ function hasObjectPrototype(o) {
38
+ return Object.prototype.toString.call(o) === "[object Object]";
39
+ }
40
+ function deepEqual(a, b, opts) {
41
+ if (a === b) return true;
42
+ if (typeof a !== typeof b) return false;
43
+ if (Array.isArray(a) && Array.isArray(b)) {
44
+ if (a.length !== b.length) return false;
45
+ for (let i = 0, l = a.length; i < l; i++) if (!deepEqual(a[i], b[i], opts)) return false;
46
+ return true;
47
+ }
48
+ if (isPlainObject(a) && isPlainObject(b)) {
49
+ const ignoreUndefined = opts?.ignoreUndefined ?? true;
50
+ if (opts?.partial) {
51
+ for (const k in b) if (!ignoreUndefined || b[k] !== void 0) {
52
+ if (!deepEqual(a[k], b[k], opts)) return false;
53
+ }
54
+ return true;
55
+ }
56
+ let aCount = 0;
57
+ if (!ignoreUndefined) aCount = Object.keys(a).length;
58
+ else for (const k in a) if (a[k] !== void 0) aCount++;
59
+ let bCount = 0;
60
+ for (const k in b) if (!ignoreUndefined || b[k] !== void 0) {
61
+ bCount++;
62
+ if (bCount > aCount || !deepEqual(a[k], b[k], opts)) return false;
63
+ }
64
+ return aCount === bCount;
65
+ }
66
+ return false;
67
+ }
68
+ function createControlledPromise(onResolve) {
69
+ let resolveLoadPromise;
70
+ let rejectLoadPromise;
71
+ const controlledPromise = new Promise((resolve, reject) => {
72
+ resolveLoadPromise = resolve;
73
+ rejectLoadPromise = reject;
74
+ });
75
+ controlledPromise.status = "pending";
76
+ controlledPromise.resolve = (value) => {
77
+ controlledPromise.status = "resolved";
78
+ controlledPromise.value = value;
79
+ resolveLoadPromise(value);
80
+ onResolve?.(value);
81
+ };
82
+ controlledPromise.reject = (e) => {
83
+ controlledPromise.status = "rejected";
84
+ rejectLoadPromise(e);
85
+ };
86
+ return controlledPromise;
87
+ }
88
+ function isModuleNotFoundError(error) {
89
+ if (typeof error?.message !== "string") return false;
90
+ return error.message.startsWith("Failed to fetch dynamically imported module") || error.message.startsWith("error loading dynamically imported module") || error.message.startsWith("Importing a module script failed");
91
+ }
92
+ function isPromise(value) {
93
+ return Boolean(value && typeof value === "object" && typeof value.then === "function");
94
+ }
95
+ function sanitizePathSegment(segment) {
96
+ return segment.replace(/[\x00-\x1f\x7f]/g, "");
97
+ }
98
+ function decodeSegment(segment) {
99
+ let decoded;
100
+ try {
101
+ decoded = decodeURI(segment);
102
+ } catch {
103
+ decoded = segment.replaceAll(/%[0-9A-F]{2}/gi, (match) => {
104
+ try {
105
+ return decodeURI(match);
106
+ } catch {
107
+ return match;
108
+ }
109
+ });
110
+ }
111
+ return sanitizePathSegment(decoded);
112
+ }
113
+ const DEFAULT_PROTOCOL_ALLOWLIST = [
114
+ "http:",
115
+ "https:",
116
+ "mailto:",
117
+ "tel:"
118
+ ];
119
+ function isDangerousProtocol(url, allowlist) {
120
+ if (!url) return false;
121
+ try {
122
+ const parsed = new URL(url);
123
+ return !allowlist.has(parsed.protocol);
124
+ } catch {
125
+ return false;
126
+ }
127
+ }
128
+ const HTML_ESCAPE_LOOKUP = {
129
+ "&": "\\u0026",
130
+ ">": "\\u003e",
131
+ "<": "\\u003c",
132
+ "\u2028": "\\u2028",
133
+ "\u2029": "\\u2029"
134
+ };
135
+ const HTML_ESCAPE_REGEX = /[&><\u2028\u2029]/g;
136
+ function escapeHtml(str) {
137
+ return str.replace(HTML_ESCAPE_REGEX, (match) => HTML_ESCAPE_LOOKUP[match]);
138
+ }
139
+ function decodePath(path) {
140
+ if (!path) return {
141
+ path,
142
+ handledProtocolRelativeURL: false
143
+ };
144
+ if (!/[%\\\x00-\x1f\x7f]/.test(path) && !path.startsWith("//")) return {
145
+ path,
146
+ handledProtocolRelativeURL: false
147
+ };
148
+ const re2 = /%25|%5C/gi;
149
+ let cursor = 0;
150
+ let result = "";
151
+ let match;
152
+ while (null !== (match = re2.exec(path))) {
153
+ result += decodeSegment(path.slice(cursor, match.index)) + match[0];
154
+ cursor = re2.lastIndex;
155
+ }
156
+ result = result + decodeSegment(cursor ? path.slice(cursor) : path);
157
+ let handledProtocolRelativeURL = false;
158
+ if (result.startsWith("//")) {
159
+ handledProtocolRelativeURL = true;
160
+ result = "/" + result.replace(/^\/+/, "");
161
+ }
162
+ return {
163
+ path: result,
164
+ handledProtocolRelativeURL
165
+ };
166
+ }
167
+ function encodePathLikeUrl(path) {
168
+ if (!/\s|[^\u0000-\u007F]/.test(path)) return path;
169
+ return path.replace(/\s|[^\u0000-\u007F]/gu, encodeURIComponent);
170
+ }
171
+ function arraysEqual(a, b) {
172
+ if (a === b) return true;
173
+ if (a.length !== b.length) return false;
174
+ for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
175
+ return true;
176
+ }
177
+ function invariant() {
178
+ throw new Error("Invariant failed");
179
+ }
180
+ function createLRUCache(max) {
181
+ const cache = /* @__PURE__ */ new Map();
182
+ let oldest;
183
+ let newest;
184
+ const touch = (entry) => {
185
+ if (!entry.next) return;
186
+ if (!entry.prev) {
187
+ entry.next.prev = void 0;
188
+ oldest = entry.next;
189
+ entry.next = void 0;
190
+ if (newest) {
191
+ entry.prev = newest;
192
+ newest.next = entry;
193
+ }
194
+ } else {
195
+ entry.prev.next = entry.next;
196
+ entry.next.prev = entry.prev;
197
+ entry.next = void 0;
198
+ if (newest) {
199
+ newest.next = entry;
200
+ entry.prev = newest;
201
+ }
202
+ }
203
+ newest = entry;
204
+ };
205
+ return {
206
+ get(key) {
207
+ const entry = cache.get(key);
208
+ if (!entry) return void 0;
209
+ touch(entry);
210
+ return entry.value;
211
+ },
212
+ set(key, value) {
213
+ if (cache.size >= max && oldest) {
214
+ const toDelete = oldest;
215
+ cache.delete(toDelete.key);
216
+ if (toDelete.next) {
217
+ oldest = toDelete.next;
218
+ toDelete.next.prev = void 0;
219
+ }
220
+ if (toDelete === newest) newest = void 0;
221
+ }
222
+ const existing = cache.get(key);
223
+ if (existing) {
224
+ existing.value = value;
225
+ touch(existing);
226
+ } else {
227
+ const entry = {
228
+ key,
229
+ value,
230
+ prev: newest
231
+ };
232
+ if (newest) newest.next = entry;
233
+ newest = entry;
234
+ if (!oldest) oldest = entry;
235
+ cache.set(key, entry);
236
+ }
237
+ },
238
+ clear() {
239
+ cache.clear();
240
+ oldest = void 0;
241
+ newest = void 0;
242
+ }
243
+ };
244
+ }
245
+ const SEGMENT_TYPE_INDEX = 4;
246
+ const SEGMENT_TYPE_PATHLESS = 5;
247
+ function getOpenAndCloseBraces(part) {
248
+ const openBrace = part.indexOf("{");
249
+ if (openBrace === -1) return null;
250
+ const closeBrace = part.indexOf("}", openBrace);
251
+ if (closeBrace === -1) return null;
252
+ if (openBrace + 1 >= part.length) return null;
253
+ return [openBrace, closeBrace];
254
+ }
255
+ function parseSegment(path, start, output = new Uint16Array(6)) {
256
+ const next = path.indexOf("/", start);
257
+ const end = next === -1 ? path.length : next;
258
+ const part = path.substring(start, end);
259
+ if (!part || !part.includes("$")) {
260
+ output[0] = 0;
261
+ output[1] = start;
262
+ output[2] = start;
263
+ output[3] = end;
264
+ output[4] = end;
265
+ output[5] = end;
266
+ return output;
267
+ }
268
+ if (part === "$") {
269
+ const total = path.length;
270
+ output[0] = 2;
271
+ output[1] = start;
272
+ output[2] = start;
273
+ output[3] = total;
274
+ output[4] = total;
275
+ output[5] = total;
276
+ return output;
277
+ }
278
+ if (part.charCodeAt(0) === 36) {
279
+ output[0] = 1;
280
+ output[1] = start;
281
+ output[2] = start + 1;
282
+ output[3] = end;
283
+ output[4] = end;
284
+ output[5] = end;
285
+ return output;
286
+ }
287
+ const braces = getOpenAndCloseBraces(part);
288
+ if (braces) {
289
+ const [openBrace, closeBrace] = braces;
290
+ const firstChar = part.charCodeAt(openBrace + 1);
291
+ if (firstChar === 45) {
292
+ if (openBrace + 2 < part.length && part.charCodeAt(openBrace + 2) === 36) {
293
+ const paramStart = openBrace + 3;
294
+ const paramEnd = closeBrace;
295
+ if (paramStart < paramEnd) {
296
+ output[0] = 3;
297
+ output[1] = start + openBrace;
298
+ output[2] = start + paramStart;
299
+ output[3] = start + paramEnd;
300
+ output[4] = start + closeBrace + 1;
301
+ output[5] = end;
302
+ return output;
303
+ }
304
+ }
305
+ } else if (firstChar === 36) {
306
+ const dollarPos = openBrace + 1;
307
+ const afterDollar = openBrace + 2;
308
+ if (afterDollar === closeBrace) {
309
+ output[0] = 2;
310
+ output[1] = start + openBrace;
311
+ output[2] = start + dollarPos;
312
+ output[3] = start + afterDollar;
313
+ output[4] = start + closeBrace + 1;
314
+ output[5] = path.length;
315
+ return output;
316
+ }
317
+ output[0] = 1;
318
+ output[1] = start + openBrace;
319
+ output[2] = start + afterDollar;
320
+ output[3] = start + closeBrace;
321
+ output[4] = start + closeBrace + 1;
322
+ output[5] = end;
323
+ return output;
324
+ }
325
+ }
326
+ output[0] = 0;
327
+ output[1] = start;
328
+ output[2] = start;
329
+ output[3] = end;
330
+ output[4] = end;
331
+ output[5] = end;
332
+ return output;
333
+ }
334
+ function parseSegments(defaultCaseSensitive, data, route, start, node, depth, onRoute) {
335
+ onRoute?.(route);
336
+ let cursor = start;
337
+ {
338
+ const path = route.fullPath ?? route.from;
339
+ const length = path.length;
340
+ const caseSensitive = route.options?.caseSensitive ?? defaultCaseSensitive;
341
+ const parseParams = route.options?.params?.parse ?? route.options?.parseParams;
342
+ while (cursor < length) {
343
+ const segment = parseSegment(path, cursor, data);
344
+ let nextNode;
345
+ const start2 = cursor;
346
+ const end = segment[5];
347
+ cursor = end + 1;
348
+ depth++;
349
+ switch (segment[0]) {
350
+ case 0: {
351
+ const value = path.substring(segment[2], segment[3]);
352
+ if (caseSensitive) {
353
+ const existingNode = node.static?.get(value);
354
+ if (existingNode) nextNode = existingNode;
355
+ else {
356
+ node.static ??= /* @__PURE__ */ new Map();
357
+ const next = createStaticNode(route.fullPath ?? route.from);
358
+ next.parent = node;
359
+ next.depth = depth;
360
+ nextNode = next;
361
+ node.static.set(value, next);
362
+ }
363
+ } else {
364
+ const name = value.toLowerCase();
365
+ const existingNode = node.staticInsensitive?.get(name);
366
+ if (existingNode) nextNode = existingNode;
367
+ else {
368
+ node.staticInsensitive ??= /* @__PURE__ */ new Map();
369
+ const next = createStaticNode(route.fullPath ?? route.from);
370
+ next.parent = node;
371
+ next.depth = depth;
372
+ nextNode = next;
373
+ node.staticInsensitive.set(name, next);
374
+ }
375
+ }
376
+ break;
377
+ }
378
+ case 1: {
379
+ const prefix_raw = path.substring(start2, segment[1]);
380
+ const suffix_raw = path.substring(segment[4], end);
381
+ const actuallyCaseSensitive = caseSensitive && !!(prefix_raw || suffix_raw);
382
+ const prefix = !prefix_raw ? void 0 : actuallyCaseSensitive ? prefix_raw : prefix_raw.toLowerCase();
383
+ const suffix = !suffix_raw ? void 0 : actuallyCaseSensitive ? suffix_raw : suffix_raw.toLowerCase();
384
+ const existingNode = !parseParams && node.dynamic?.find((s) => !s.parse && s.caseSensitive === actuallyCaseSensitive && s.prefix === prefix && s.suffix === suffix);
385
+ if (existingNode) nextNode = existingNode;
386
+ else {
387
+ const next = createDynamicNode(1, route.fullPath ?? route.from, actuallyCaseSensitive, prefix, suffix);
388
+ nextNode = next;
389
+ next.depth = depth;
390
+ next.parent = node;
391
+ node.dynamic ??= [];
392
+ node.dynamic.push(next);
393
+ }
394
+ break;
395
+ }
396
+ case 3: {
397
+ const prefix_raw = path.substring(start2, segment[1]);
398
+ const suffix_raw = path.substring(segment[4], end);
399
+ const actuallyCaseSensitive = caseSensitive && !!(prefix_raw || suffix_raw);
400
+ const prefix = !prefix_raw ? void 0 : actuallyCaseSensitive ? prefix_raw : prefix_raw.toLowerCase();
401
+ const suffix = !suffix_raw ? void 0 : actuallyCaseSensitive ? suffix_raw : suffix_raw.toLowerCase();
402
+ const existingNode = !parseParams && node.optional?.find((s) => !s.parse && s.caseSensitive === actuallyCaseSensitive && s.prefix === prefix && s.suffix === suffix);
403
+ if (existingNode) nextNode = existingNode;
404
+ else {
405
+ const next = createDynamicNode(3, route.fullPath ?? route.from, actuallyCaseSensitive, prefix, suffix);
406
+ nextNode = next;
407
+ next.parent = node;
408
+ next.depth = depth;
409
+ node.optional ??= [];
410
+ node.optional.push(next);
411
+ }
412
+ break;
413
+ }
414
+ case 2: {
415
+ const prefix_raw = path.substring(start2, segment[1]);
416
+ const suffix_raw = path.substring(segment[4], end);
417
+ const actuallyCaseSensitive = caseSensitive && !!(prefix_raw || suffix_raw);
418
+ const prefix = !prefix_raw ? void 0 : actuallyCaseSensitive ? prefix_raw : prefix_raw.toLowerCase();
419
+ const suffix = !suffix_raw ? void 0 : actuallyCaseSensitive ? suffix_raw : suffix_raw.toLowerCase();
420
+ const next = createDynamicNode(2, route.fullPath ?? route.from, actuallyCaseSensitive, prefix, suffix);
421
+ nextNode = next;
422
+ next.parent = node;
423
+ next.depth = depth;
424
+ node.wildcard ??= [];
425
+ node.wildcard.push(next);
426
+ }
427
+ }
428
+ node = nextNode;
429
+ }
430
+ if (parseParams && route.children && !route.isRoot && route.id && route.id.charCodeAt(route.id.lastIndexOf("/") + 1) === 95) {
431
+ const pathlessNode = createStaticNode(route.fullPath ?? route.from);
432
+ pathlessNode.kind = SEGMENT_TYPE_PATHLESS;
433
+ pathlessNode.parent = node;
434
+ depth++;
435
+ pathlessNode.depth = depth;
436
+ node.pathless ??= [];
437
+ node.pathless.push(pathlessNode);
438
+ node = pathlessNode;
439
+ }
440
+ const isLeaf = (route.path || !route.children) && !route.isRoot;
441
+ if (isLeaf && path.endsWith("/")) {
442
+ const indexNode = createStaticNode(route.fullPath ?? route.from);
443
+ indexNode.kind = SEGMENT_TYPE_INDEX;
444
+ indexNode.parent = node;
445
+ depth++;
446
+ indexNode.depth = depth;
447
+ node.index = indexNode;
448
+ node = indexNode;
449
+ }
450
+ node.parse = parseParams ?? null;
451
+ if (isLeaf && !node.route) {
452
+ node.route = route;
453
+ node.fullPath = route.fullPath ?? route.from;
454
+ }
455
+ }
456
+ if (route.children) for (const child of route.children) parseSegments(defaultCaseSensitive, data, child, cursor, node, depth, onRoute);
457
+ }
458
+ function sortDynamic(a, b) {
459
+ if (a.parse && !b.parse) return -1;
460
+ if (!a.parse && b.parse) return 1;
461
+ if (a.prefix && b.prefix && a.prefix !== b.prefix) {
462
+ if (a.prefix.startsWith(b.prefix)) return -1;
463
+ if (b.prefix.startsWith(a.prefix)) return 1;
464
+ }
465
+ if (a.suffix && b.suffix && a.suffix !== b.suffix) {
466
+ if (a.suffix.endsWith(b.suffix)) return -1;
467
+ if (b.suffix.endsWith(a.suffix)) return 1;
468
+ }
469
+ if (a.prefix && !b.prefix) return -1;
470
+ if (!a.prefix && b.prefix) return 1;
471
+ if (a.suffix && !b.suffix) return -1;
472
+ if (!a.suffix && b.suffix) return 1;
473
+ if (a.caseSensitive && !b.caseSensitive) return -1;
474
+ if (!a.caseSensitive && b.caseSensitive) return 1;
475
+ return 0;
476
+ }
477
+ function sortTreeNodes(node) {
478
+ if (node.pathless) for (const child of node.pathless) sortTreeNodes(child);
479
+ if (node.static) for (const child of node.static.values()) sortTreeNodes(child);
480
+ if (node.staticInsensitive) for (const child of node.staticInsensitive.values()) sortTreeNodes(child);
481
+ if (node.dynamic?.length) {
482
+ node.dynamic.sort(sortDynamic);
483
+ for (const child of node.dynamic) sortTreeNodes(child);
484
+ }
485
+ if (node.optional?.length) {
486
+ node.optional.sort(sortDynamic);
487
+ for (const child of node.optional) sortTreeNodes(child);
488
+ }
489
+ if (node.wildcard?.length) {
490
+ node.wildcard.sort(sortDynamic);
491
+ for (const child of node.wildcard) sortTreeNodes(child);
492
+ }
493
+ }
494
+ function createStaticNode(fullPath) {
495
+ return {
496
+ kind: 0,
497
+ depth: 0,
498
+ pathless: null,
499
+ index: null,
500
+ static: null,
501
+ staticInsensitive: null,
502
+ dynamic: null,
503
+ optional: null,
504
+ wildcard: null,
505
+ route: null,
506
+ fullPath,
507
+ parent: null,
508
+ parse: null
509
+ };
510
+ }
511
+ function createDynamicNode(kind, fullPath, caseSensitive, prefix, suffix) {
512
+ return {
513
+ kind,
514
+ depth: 0,
515
+ pathless: null,
516
+ index: null,
517
+ static: null,
518
+ staticInsensitive: null,
519
+ dynamic: null,
520
+ optional: null,
521
+ wildcard: null,
522
+ route: null,
523
+ fullPath,
524
+ parent: null,
525
+ parse: null,
526
+ caseSensitive,
527
+ prefix,
528
+ suffix
529
+ };
530
+ }
531
+ function processRouteMasks(routeList, processedTree) {
532
+ const segmentTree = createStaticNode("/");
533
+ const data = new Uint16Array(6);
534
+ for (const route of routeList) parseSegments(false, data, route, 1, segmentTree, 0);
535
+ sortTreeNodes(segmentTree);
536
+ processedTree.masksTree = segmentTree;
537
+ processedTree.flatCache = createLRUCache(1e3);
538
+ }
539
+ function findFlatMatch(path, processedTree) {
540
+ path ||= "/";
541
+ const cached = processedTree.flatCache.get(path);
542
+ if (cached) return cached;
543
+ const result = findMatch(path, processedTree.masksTree);
544
+ processedTree.flatCache.set(path, result);
545
+ return result;
546
+ }
547
+ function findSingleMatch(from, caseSensitive, fuzzy, path, processedTree) {
548
+ from ||= "/";
549
+ path ||= "/";
550
+ const key = caseSensitive ? `case\0${from}` : from;
551
+ let tree = processedTree.singleCache.get(key);
552
+ if (!tree) {
553
+ tree = createStaticNode("/");
554
+ parseSegments(caseSensitive, new Uint16Array(6), { from }, 1, tree, 0);
555
+ processedTree.singleCache.set(key, tree);
556
+ }
557
+ return findMatch(path, tree, fuzzy);
558
+ }
559
+ function findRouteMatch(path, processedTree, fuzzy = false) {
560
+ const key = fuzzy ? path : `nofuzz\0${path}`;
561
+ const cached = processedTree.matchCache.get(key);
562
+ if (cached !== void 0) return cached;
563
+ path ||= "/";
564
+ let result;
565
+ try {
566
+ result = findMatch(path, processedTree.segmentTree, fuzzy);
567
+ } catch (err) {
568
+ if (err instanceof URIError) result = null;
569
+ else throw err;
570
+ }
571
+ if (result) result.branch = buildRouteBranch(result.route);
572
+ processedTree.matchCache.set(key, result);
573
+ return result;
574
+ }
575
+ function trimPathRight$1(path) {
576
+ return path === "/" ? path : path.replace(/\/{1,}$/, "");
577
+ }
578
+ function processRouteTree(routeTree, caseSensitive = false, initRoute) {
579
+ const segmentTree = createStaticNode(routeTree.fullPath);
580
+ const data = new Uint16Array(6);
581
+ const routesById = {};
582
+ const routesByPath = {};
583
+ let index = 0;
584
+ parseSegments(caseSensitive, data, routeTree, 1, segmentTree, 0, (route) => {
585
+ initRoute?.(route, index);
586
+ if (route.id in routesById) {
587
+ invariant();
588
+ }
589
+ routesById[route.id] = route;
590
+ if (index !== 0 && route.path) {
591
+ const trimmedFullPath = trimPathRight$1(route.fullPath);
592
+ if (!routesByPath[trimmedFullPath] || route.fullPath.endsWith("/")) routesByPath[trimmedFullPath] = route;
593
+ }
594
+ index++;
595
+ });
596
+ sortTreeNodes(segmentTree);
597
+ return {
598
+ processedTree: {
599
+ segmentTree,
600
+ singleCache: createLRUCache(1e3),
601
+ matchCache: createLRUCache(1e3),
602
+ flatCache: null,
603
+ masksTree: null
604
+ },
605
+ routesById,
606
+ routesByPath
607
+ };
608
+ }
609
+ function findMatch(path, segmentTree, fuzzy = false) {
610
+ const parts = path.split("/");
611
+ const leaf = getNodeMatch(path, parts, segmentTree, fuzzy);
612
+ if (!leaf) return null;
613
+ const [rawParams] = extractParams(path, parts, leaf);
614
+ return {
615
+ route: leaf.node.route,
616
+ rawParams
617
+ };
618
+ }
619
+ function extractParams(path, parts, leaf) {
620
+ const list = buildBranch(leaf.node);
621
+ let nodeParts = null;
622
+ const rawParams = /* @__PURE__ */ Object.create(null);
623
+ let partIndex = leaf.extract?.part ?? 0;
624
+ let nodeIndex = leaf.extract?.node ?? 0;
625
+ let pathIndex = leaf.extract?.path ?? 0;
626
+ let segmentCount = leaf.extract?.segment ?? 0;
627
+ for (; nodeIndex < list.length; partIndex++, nodeIndex++, pathIndex++, segmentCount++) {
628
+ const node = list[nodeIndex];
629
+ if (node.kind === SEGMENT_TYPE_INDEX) break;
630
+ if (node.kind === SEGMENT_TYPE_PATHLESS) {
631
+ segmentCount--;
632
+ partIndex--;
633
+ pathIndex--;
634
+ continue;
635
+ }
636
+ const part = parts[partIndex];
637
+ const currentPathIndex = pathIndex;
638
+ if (part) pathIndex += part.length;
639
+ if (node.kind === 1) {
640
+ nodeParts ??= leaf.node.fullPath.split("/");
641
+ const nodePart = nodeParts[segmentCount];
642
+ const preLength = node.prefix?.length ?? 0;
643
+ if (nodePart.charCodeAt(preLength) === 123) {
644
+ const sufLength = node.suffix?.length ?? 0;
645
+ const name = nodePart.substring(preLength + 2, nodePart.length - sufLength - 1);
646
+ const value = part.substring(preLength, part.length - sufLength);
647
+ rawParams[name] = decodeURIComponent(value);
648
+ } else {
649
+ const name = nodePart.substring(1);
650
+ rawParams[name] = decodeURIComponent(part);
651
+ }
652
+ } else if (node.kind === 3) {
653
+ if (leaf.skipped & 1 << nodeIndex) {
654
+ partIndex--;
655
+ pathIndex = currentPathIndex - 1;
656
+ continue;
657
+ }
658
+ nodeParts ??= leaf.node.fullPath.split("/");
659
+ const nodePart = nodeParts[segmentCount];
660
+ const preLength = node.prefix?.length ?? 0;
661
+ const sufLength = node.suffix?.length ?? 0;
662
+ const name = nodePart.substring(preLength + 3, nodePart.length - sufLength - 1);
663
+ const value = node.suffix || node.prefix ? part.substring(preLength, part.length - sufLength) : part;
664
+ if (value) rawParams[name] = decodeURIComponent(value);
665
+ } else if (node.kind === 2) {
666
+ const n = node;
667
+ const value = path.substring(currentPathIndex + (n.prefix?.length ?? 0), path.length - (n.suffix?.length ?? 0));
668
+ const splat = decodeURIComponent(value);
669
+ rawParams["*"] = splat;
670
+ rawParams._splat = splat;
671
+ break;
672
+ }
673
+ }
674
+ if (leaf.rawParams) Object.assign(rawParams, leaf.rawParams);
675
+ return [rawParams, {
676
+ part: partIndex,
677
+ node: nodeIndex,
678
+ path: pathIndex,
679
+ segment: segmentCount
680
+ }];
681
+ }
682
+ function buildRouteBranch(route) {
683
+ const list = [route];
684
+ while (route.parentRoute) {
685
+ route = route.parentRoute;
686
+ list.push(route);
687
+ }
688
+ list.reverse();
689
+ return list;
690
+ }
691
+ function buildBranch(node) {
692
+ const list = Array(node.depth + 1);
693
+ do {
694
+ list[node.depth] = node;
695
+ node = node.parent;
696
+ } while (node);
697
+ return list;
698
+ }
699
+ function getNodeMatch(path, parts, segmentTree, fuzzy) {
700
+ if (path === "/" && segmentTree.index) return {
701
+ node: segmentTree.index,
702
+ skipped: 0
703
+ };
704
+ const trailingSlash = !last(parts);
705
+ const pathIsIndex = trailingSlash && path !== "/";
706
+ const partsLength = parts.length - (trailingSlash ? 1 : 0);
707
+ const stack = [{
708
+ node: segmentTree,
709
+ index: 1,
710
+ skipped: 0,
711
+ depth: 1,
712
+ statics: 0,
713
+ dynamics: 0,
714
+ optionals: 0
715
+ }];
716
+ let bestFuzzy = null;
717
+ let bestMatch = null;
718
+ while (stack.length) {
719
+ const frame = stack.pop();
720
+ const { node, index, skipped, depth, statics, dynamics, optionals } = frame;
721
+ let { extract, rawParams } = frame;
722
+ if (node.kind === 2 && node.route && !isFrameMoreSpecific(bestMatch, frame)) continue;
723
+ if (node.parse) {
724
+ if (!validateParseParams(path, parts, frame)) continue;
725
+ rawParams = frame.rawParams;
726
+ extract = frame.extract;
727
+ }
728
+ if (fuzzy && node.route && node.kind !== SEGMENT_TYPE_INDEX && isFrameMoreSpecific(bestFuzzy, frame)) bestFuzzy = frame;
729
+ const isBeyondPath = index === partsLength;
730
+ if (isBeyondPath) {
731
+ if (node.route && (!pathIsIndex || node.kind === SEGMENT_TYPE_INDEX || node.kind === 2) && isFrameMoreSpecific(bestMatch, frame)) bestMatch = frame;
732
+ if (!node.optional && !node.wildcard && !node.index && !node.pathless) continue;
733
+ }
734
+ const part = isBeyondPath ? void 0 : parts[index];
735
+ let lowerPart;
736
+ if (isBeyondPath && node.index) {
737
+ const indexFrame = {
738
+ node: node.index,
739
+ index,
740
+ skipped,
741
+ depth: depth + 1,
742
+ statics,
743
+ dynamics,
744
+ optionals,
745
+ extract,
746
+ rawParams
747
+ };
748
+ let indexValid = true;
749
+ if (node.index.parse) {
750
+ if (!validateParseParams(path, parts, indexFrame)) indexValid = false;
751
+ }
752
+ if (indexValid) {
753
+ if (!dynamics && !optionals && !skipped && isPerfectStaticMatch(statics, partsLength)) return indexFrame;
754
+ if (isFrameMoreSpecific(bestMatch, indexFrame)) bestMatch = indexFrame;
755
+ }
756
+ }
757
+ if (node.wildcard) for (let i = node.wildcard.length - 1; i >= 0; i--) {
758
+ const segment = node.wildcard[i];
759
+ const { prefix, suffix } = segment;
760
+ if (prefix) {
761
+ if (isBeyondPath) continue;
762
+ if (!(segment.caseSensitive ? part : lowerPart ??= part.toLowerCase()).startsWith(prefix)) continue;
763
+ }
764
+ if (suffix) {
765
+ if (isBeyondPath) continue;
766
+ const end = parts.slice(index).join("/").slice(-suffix.length);
767
+ if ((segment.caseSensitive ? end : end.toLowerCase()) !== suffix) continue;
768
+ }
769
+ stack.push({
770
+ node: segment,
771
+ index: partsLength,
772
+ skipped,
773
+ depth: depth + 1,
774
+ statics,
775
+ dynamics,
776
+ optionals,
777
+ extract,
778
+ rawParams
779
+ });
780
+ }
781
+ if (node.optional) {
782
+ const nextSkipped = skipped | 1 << depth;
783
+ const nextDepth = depth + 1;
784
+ for (let i = node.optional.length - 1; i >= 0; i--) {
785
+ const segment = node.optional[i];
786
+ stack.push({
787
+ node: segment,
788
+ index,
789
+ skipped: nextSkipped,
790
+ depth: nextDepth,
791
+ statics,
792
+ dynamics,
793
+ optionals,
794
+ extract,
795
+ rawParams
796
+ });
797
+ }
798
+ if (!isBeyondPath) for (let i = node.optional.length - 1; i >= 0; i--) {
799
+ const segment = node.optional[i];
800
+ const { prefix, suffix } = segment;
801
+ if (prefix || suffix) {
802
+ const casePart = segment.caseSensitive ? part : lowerPart ??= part.toLowerCase();
803
+ if (prefix && !casePart.startsWith(prefix)) continue;
804
+ if (suffix && !casePart.endsWith(suffix)) continue;
805
+ }
806
+ stack.push({
807
+ node: segment,
808
+ index: index + 1,
809
+ skipped,
810
+ depth: nextDepth,
811
+ statics,
812
+ dynamics,
813
+ optionals: optionals + segmentScore(partsLength, index),
814
+ extract,
815
+ rawParams
816
+ });
817
+ }
818
+ }
819
+ if (!isBeyondPath && node.dynamic && part) for (let i = node.dynamic.length - 1; i >= 0; i--) {
820
+ const segment = node.dynamic[i];
821
+ const { prefix, suffix } = segment;
822
+ if (prefix || suffix) {
823
+ const casePart = segment.caseSensitive ? part : lowerPart ??= part.toLowerCase();
824
+ if (prefix && !casePart.startsWith(prefix)) continue;
825
+ if (suffix && !casePart.endsWith(suffix)) continue;
826
+ }
827
+ stack.push({
828
+ node: segment,
829
+ index: index + 1,
830
+ skipped,
831
+ depth: depth + 1,
832
+ statics,
833
+ dynamics: dynamics + segmentScore(partsLength, index),
834
+ optionals,
835
+ extract,
836
+ rawParams
837
+ });
838
+ }
839
+ if (!isBeyondPath && node.staticInsensitive) {
840
+ const match = node.staticInsensitive.get(lowerPart ??= part.toLowerCase());
841
+ if (match) stack.push({
842
+ node: match,
843
+ index: index + 1,
844
+ skipped,
845
+ depth: depth + 1,
846
+ statics: statics + segmentScore(partsLength, index),
847
+ dynamics,
848
+ optionals,
849
+ extract,
850
+ rawParams
851
+ });
852
+ }
853
+ if (!isBeyondPath && node.static) {
854
+ const match = node.static.get(part);
855
+ if (match) stack.push({
856
+ node: match,
857
+ index: index + 1,
858
+ skipped,
859
+ depth: depth + 1,
860
+ statics: statics + segmentScore(partsLength, index),
861
+ dynamics,
862
+ optionals,
863
+ extract,
864
+ rawParams
865
+ });
866
+ }
867
+ if (node.pathless) {
868
+ const nextDepth = depth + 1;
869
+ for (let i = node.pathless.length - 1; i >= 0; i--) {
870
+ const segment = node.pathless[i];
871
+ stack.push({
872
+ node: segment,
873
+ index,
874
+ skipped,
875
+ depth: nextDepth,
876
+ statics,
877
+ dynamics,
878
+ optionals,
879
+ extract,
880
+ rawParams
881
+ });
882
+ }
883
+ }
884
+ }
885
+ if (bestMatch) return bestMatch;
886
+ if (fuzzy && bestFuzzy) {
887
+ let sliceIndex = bestFuzzy.index;
888
+ for (let i = 0; i < bestFuzzy.index; i++) sliceIndex += parts[i].length;
889
+ const splat = sliceIndex === path.length ? "/" : path.slice(sliceIndex);
890
+ bestFuzzy.rawParams ??= /* @__PURE__ */ Object.create(null);
891
+ bestFuzzy.rawParams["**"] = decodeURIComponent(splat);
892
+ return bestFuzzy;
893
+ }
894
+ return null;
895
+ }
896
+ function segmentScore(partsLength, index) {
897
+ return 2 ** (partsLength - index - 1);
898
+ }
899
+ function isPerfectStaticMatch(statics, partsLength) {
900
+ return statics === 2 ** (partsLength - 1) - 1;
901
+ }
902
+ function validateParseParams(path, parts, frame) {
903
+ let rawParams;
904
+ let state;
905
+ try {
906
+ [rawParams, state] = extractParams(path, parts, frame);
907
+ } catch {
908
+ return null;
909
+ }
910
+ frame.rawParams = rawParams;
911
+ frame.extract = state;
912
+ if (!frame.node.parse) return true;
913
+ try {
914
+ if (frame.node.parse(rawParams) === false) return null;
915
+ } catch {
916
+ }
917
+ return true;
918
+ }
919
+ function isFrameMoreSpecific(prev, next) {
920
+ if (!prev) return true;
921
+ return next.statics > prev.statics || next.statics === prev.statics && (next.dynamics > prev.dynamics || next.dynamics === prev.dynamics && (next.optionals > prev.optionals || next.optionals === prev.optionals && ((next.node.kind === SEGMENT_TYPE_INDEX) > (prev.node.kind === SEGMENT_TYPE_INDEX) || next.node.kind === SEGMENT_TYPE_INDEX === (prev.node.kind === SEGMENT_TYPE_INDEX) && next.depth > prev.depth)));
922
+ }
923
+ function joinPaths(paths) {
924
+ return cleanPath(paths.filter((val) => {
925
+ return val !== void 0;
926
+ }).join("/"));
927
+ }
928
+ function cleanPath(path) {
929
+ return path.replace(/\/{2,}/g, "/");
930
+ }
931
+ function trimPathLeft(path) {
932
+ return path === "/" ? path : path.replace(/^\/{1,}/, "");
933
+ }
934
+ function trimPathRight(path) {
935
+ const len = path.length;
936
+ return len > 1 && path[len - 1] === "/" ? path.replace(/\/{1,}$/, "") : path;
937
+ }
938
+ function trimPath(path) {
939
+ return trimPathRight(trimPathLeft(path));
940
+ }
941
+ function removeTrailingSlash(value, basepath) {
942
+ if (value?.endsWith("/") && value !== "/" && value !== `${basepath}/`) return value.slice(0, -1);
943
+ return value;
944
+ }
945
+ function exactPathTest(pathName1, pathName2, basepath) {
946
+ return removeTrailingSlash(pathName1, basepath) === removeTrailingSlash(pathName2, basepath);
947
+ }
948
+ function resolvePath({ base, to, trailingSlash = "never", cache }) {
949
+ const isAbsolute = to.startsWith("/");
950
+ const isBase = !isAbsolute && to === ".";
951
+ let key;
952
+ if (cache) {
953
+ key = isAbsolute ? to : isBase ? base : base + "\0" + to;
954
+ const cached = cache.get(key);
955
+ if (cached) return cached;
956
+ }
957
+ let baseSegments;
958
+ if (isBase) baseSegments = base.split("/");
959
+ else if (isAbsolute) baseSegments = to.split("/");
960
+ else {
961
+ baseSegments = base.split("/");
962
+ while (baseSegments.length > 1 && last(baseSegments) === "") baseSegments.pop();
963
+ const toSegments = to.split("/");
964
+ for (let index = 0, length = toSegments.length; index < length; index++) {
965
+ const value = toSegments[index];
966
+ if (value === "") {
967
+ if (!index) baseSegments = [value];
968
+ else if (index === length - 1) baseSegments.push(value);
969
+ } else if (value === "..") baseSegments.pop();
970
+ else if (value === ".") ;
971
+ else baseSegments.push(value);
972
+ }
973
+ }
974
+ if (baseSegments.length > 1) {
975
+ if (last(baseSegments) === "") {
976
+ if (trailingSlash === "never") baseSegments.pop();
977
+ } else if (trailingSlash === "always") baseSegments.push("");
978
+ }
979
+ const result = cleanPath(baseSegments.join("/")) || "/";
980
+ if (key && cache) cache.set(key, result);
981
+ return result;
982
+ }
983
+ function compileDecodeCharMap(pathParamsAllowedCharacters) {
984
+ const charMap = new Map(pathParamsAllowedCharacters.map((char) => [encodeURIComponent(char), char]));
985
+ const pattern = Array.from(charMap.keys()).map((key) => key.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|");
986
+ const regex = new RegExp(pattern, "g");
987
+ return (encoded) => encoded.replace(regex, (match) => charMap.get(match) ?? match);
988
+ }
989
+ function encodeParam(key, params, decoder) {
990
+ const value = params[key];
991
+ if (typeof value !== "string") return value;
992
+ if (key === "_splat") {
993
+ if (/^[a-zA-Z0-9\-._~!/]*$/.test(value)) return value;
994
+ return value.split("/").map((segment) => encodePathParam(segment, decoder)).join("/");
995
+ } else return encodePathParam(value, decoder);
996
+ }
997
+ function interpolatePath({ path, params, decoder, ...rest }) {
998
+ let isMissingParams = false;
999
+ const usedParams = /* @__PURE__ */ Object.create(null);
1000
+ if (!path || path === "/") return {
1001
+ interpolatedPath: "/",
1002
+ usedParams,
1003
+ isMissingParams
1004
+ };
1005
+ if (!path.includes("$")) return {
1006
+ interpolatedPath: path,
1007
+ usedParams,
1008
+ isMissingParams
1009
+ };
1010
+ {
1011
+ if (path.indexOf("{") === -1) {
1012
+ const length2 = path.length;
1013
+ let cursor2 = 0;
1014
+ let joined2 = "";
1015
+ while (cursor2 < length2) {
1016
+ while (cursor2 < length2 && path.charCodeAt(cursor2) === 47) cursor2++;
1017
+ if (cursor2 >= length2) break;
1018
+ const start = cursor2;
1019
+ let end = path.indexOf("/", cursor2);
1020
+ if (end === -1) end = length2;
1021
+ cursor2 = end;
1022
+ const part = path.substring(start, end);
1023
+ if (!part) continue;
1024
+ if (part.charCodeAt(0) === 36) if (part.length === 1) {
1025
+ const splat = params._splat;
1026
+ usedParams._splat = splat;
1027
+ usedParams["*"] = splat;
1028
+ if (!splat) {
1029
+ isMissingParams = true;
1030
+ continue;
1031
+ }
1032
+ const value = encodeParam("_splat", params, decoder);
1033
+ joined2 += "/" + value;
1034
+ } else {
1035
+ const key = part.substring(1);
1036
+ if (!isMissingParams && !(key in params)) isMissingParams = true;
1037
+ usedParams[key] = params[key];
1038
+ const value = encodeParam(key, params, decoder) ?? "undefined";
1039
+ joined2 += "/" + value;
1040
+ }
1041
+ else joined2 += "/" + part;
1042
+ }
1043
+ if (path.endsWith("/")) joined2 += "/";
1044
+ return {
1045
+ usedParams,
1046
+ interpolatedPath: joined2 || "/",
1047
+ isMissingParams
1048
+ };
1049
+ }
1050
+ }
1051
+ const length = path.length;
1052
+ let cursor = 0;
1053
+ let segment;
1054
+ let joined = "";
1055
+ while (cursor < length) {
1056
+ const start = cursor;
1057
+ segment = parseSegment(path, start, segment);
1058
+ const end = segment[5];
1059
+ cursor = end + 1;
1060
+ if (start === end) continue;
1061
+ const kind = segment[0];
1062
+ if (kind === 0) {
1063
+ joined += "/" + path.substring(start, end);
1064
+ continue;
1065
+ }
1066
+ if (kind === 2) {
1067
+ const splat = params._splat;
1068
+ usedParams._splat = splat;
1069
+ usedParams["*"] = splat;
1070
+ const prefix = path.substring(start, segment[1]);
1071
+ const suffix = path.substring(segment[4], end);
1072
+ if (!splat) {
1073
+ isMissingParams = true;
1074
+ if (prefix || suffix) joined += "/" + prefix + suffix;
1075
+ continue;
1076
+ }
1077
+ const value = encodeParam("_splat", params, decoder);
1078
+ joined += "/" + prefix + value + suffix;
1079
+ continue;
1080
+ }
1081
+ if (kind === 1) {
1082
+ const key = path.substring(segment[2], segment[3]);
1083
+ if (!isMissingParams && !(key in params)) isMissingParams = true;
1084
+ usedParams[key] = params[key];
1085
+ const prefix = path.substring(start, segment[1]);
1086
+ const suffix = path.substring(segment[4], end);
1087
+ const value = encodeParam(key, params, decoder) ?? "undefined";
1088
+ joined += "/" + prefix + value + suffix;
1089
+ continue;
1090
+ }
1091
+ if (kind === 3) {
1092
+ const key = path.substring(segment[2], segment[3]);
1093
+ const valueRaw = params[key];
1094
+ if (valueRaw == null) continue;
1095
+ usedParams[key] = valueRaw;
1096
+ const prefix = path.substring(start, segment[1]);
1097
+ const suffix = path.substring(segment[4], end);
1098
+ const value = encodeParam(key, params, decoder) ?? "";
1099
+ joined += "/" + prefix + value + suffix;
1100
+ continue;
1101
+ }
1102
+ }
1103
+ if (path.endsWith("/")) joined += "/";
1104
+ return {
1105
+ usedParams,
1106
+ interpolatedPath: joined || "/",
1107
+ isMissingParams
1108
+ };
1109
+ }
1110
+ function encodePathParam(value, decoder) {
1111
+ const encoded = encodeURIComponent(value);
1112
+ return decoder?.(encoded) ?? encoded;
1113
+ }
1114
+ function isNotFound(obj) {
1115
+ return obj?.isNotFound === true;
1116
+ }
1117
+ function getSafeSessionStorage() {
1118
+ try {
1119
+ return typeof window !== "undefined" && typeof window.sessionStorage === "object" ? window.sessionStorage : void 0;
1120
+ } catch {
1121
+ return;
1122
+ }
1123
+ }
1124
+ const storageKey = "tsr-scroll-restoration-v1_3";
1125
+ function createScrollRestorationCache() {
1126
+ const safeSessionStorage = getSafeSessionStorage();
1127
+ if (!safeSessionStorage) return null;
1128
+ let state = {};
1129
+ try {
1130
+ const parsed = JSON.parse(safeSessionStorage.getItem("tsr-scroll-restoration-v1_3") || "{}");
1131
+ if (isPlainObject(parsed)) state = parsed;
1132
+ } catch {
1133
+ }
1134
+ const persist = () => {
1135
+ try {
1136
+ safeSessionStorage.setItem(storageKey, JSON.stringify(state));
1137
+ } catch {
1138
+ }
1139
+ };
1140
+ return {
1141
+ get state() {
1142
+ return state;
1143
+ },
1144
+ set: (updater) => {
1145
+ state = functionalUpdate(updater, state) || state;
1146
+ },
1147
+ persist
1148
+ };
1149
+ }
1150
+ createScrollRestorationCache();
1151
+ const defaultGetScrollRestorationKey = (location) => {
1152
+ return location.state.__TSR_key || location.href;
1153
+ };
1154
+ function encode(obj, stringify = String) {
1155
+ const result = new URLSearchParams();
1156
+ for (const key in obj) {
1157
+ const val = obj[key];
1158
+ if (val !== void 0) result.set(key, stringify(val));
1159
+ }
1160
+ return result.toString();
1161
+ }
1162
+ function toValue(str) {
1163
+ if (!str) return "";
1164
+ if (str === "false") return false;
1165
+ if (str === "true") return true;
1166
+ return +str * 0 === 0 && +str + "" === str ? +str : str;
1167
+ }
1168
+ function decode(str) {
1169
+ const searchParams = new URLSearchParams(str);
1170
+ const result = /* @__PURE__ */ Object.create(null);
1171
+ for (const [key, value] of searchParams.entries()) {
1172
+ const previousValue = result[key];
1173
+ if (previousValue == null) result[key] = toValue(value);
1174
+ else if (Array.isArray(previousValue)) previousValue.push(toValue(value));
1175
+ else result[key] = [previousValue, toValue(value)];
1176
+ }
1177
+ return result;
1178
+ }
1179
+ const defaultParseSearch = parseSearchWith(JSON.parse);
1180
+ const defaultStringifySearch = stringifySearchWith(JSON.stringify, JSON.parse);
1181
+ function parseSearchWith(parser) {
1182
+ return (searchStr) => {
1183
+ if (searchStr[0] === "?") searchStr = searchStr.substring(1);
1184
+ const query = decode(searchStr);
1185
+ for (const key in query) {
1186
+ const value = query[key];
1187
+ if (typeof value === "string") try {
1188
+ query[key] = parser(value);
1189
+ } catch (_err) {
1190
+ }
1191
+ }
1192
+ return query;
1193
+ };
1194
+ }
1195
+ function stringifySearchWith(stringify, parser) {
1196
+ const hasParser = typeof parser === "function";
1197
+ function stringifyValue(val) {
1198
+ if (typeof val === "object" && val !== null) try {
1199
+ return stringify(val);
1200
+ } catch (_err) {
1201
+ }
1202
+ else if (hasParser && typeof val === "string") try {
1203
+ parser(val);
1204
+ return stringify(val);
1205
+ } catch (_err) {
1206
+ }
1207
+ return val;
1208
+ }
1209
+ return (search) => {
1210
+ const searchStr = encode(search, stringifyValue);
1211
+ return searchStr ? `?${searchStr}` : "";
1212
+ };
1213
+ }
1214
+ const rootRouteId = "__root__";
1215
+ function redirect(opts) {
1216
+ opts.statusCode = opts.statusCode || opts.code || 307;
1217
+ if (!opts._builtLocation && !opts.reloadDocument && typeof opts.href === "string") try {
1218
+ new URL(opts.href);
1219
+ opts.reloadDocument = true;
1220
+ } catch {
1221
+ }
1222
+ const headers = new Headers(opts.headers);
1223
+ if (opts.href && headers.get("Location") === null) headers.set("Location", opts.href);
1224
+ const response = new Response(null, {
1225
+ status: opts.statusCode,
1226
+ headers
1227
+ });
1228
+ response.options = opts;
1229
+ if (opts.throw) throw response;
1230
+ return response;
1231
+ }
1232
+ function isRedirect(obj) {
1233
+ return obj instanceof Response && !!obj.options;
1234
+ }
1235
+ function isResolvedRedirect(obj) {
1236
+ return isRedirect(obj) && !!obj.options.href;
1237
+ }
1238
+ function composeRewrites(rewrites) {
1239
+ return {
1240
+ input: ({ url }) => {
1241
+ for (const rewrite of rewrites) url = executeRewriteInput(rewrite, url);
1242
+ return url;
1243
+ },
1244
+ output: ({ url }) => {
1245
+ for (let i = rewrites.length - 1; i >= 0; i--) url = executeRewriteOutput(rewrites[i], url);
1246
+ return url;
1247
+ }
1248
+ };
1249
+ }
1250
+ function rewriteBasepath(opts) {
1251
+ const trimmedBasepath = trimPath(opts.basepath);
1252
+ const normalizedBasepath = `/${trimmedBasepath}`;
1253
+ const normalizedBasepathWithSlash = `${normalizedBasepath}/`;
1254
+ const checkBasepath = opts.caseSensitive ? normalizedBasepath : normalizedBasepath.toLowerCase();
1255
+ const checkBasepathWithSlash = opts.caseSensitive ? normalizedBasepathWithSlash : normalizedBasepathWithSlash.toLowerCase();
1256
+ return {
1257
+ input: ({ url }) => {
1258
+ const pathname = opts.caseSensitive ? url.pathname : url.pathname.toLowerCase();
1259
+ if (pathname === checkBasepath) url.pathname = "/";
1260
+ else if (pathname.startsWith(checkBasepathWithSlash)) url.pathname = url.pathname.slice(normalizedBasepath.length);
1261
+ return url;
1262
+ },
1263
+ output: ({ url }) => {
1264
+ url.pathname = joinPaths([
1265
+ "/",
1266
+ trimmedBasepath,
1267
+ url.pathname
1268
+ ]);
1269
+ return url;
1270
+ }
1271
+ };
1272
+ }
1273
+ function executeRewriteInput(rewrite, url) {
1274
+ const res = rewrite?.input?.({ url });
1275
+ if (res) {
1276
+ if (typeof res === "string") return new URL(res);
1277
+ else if (res instanceof URL) return res;
1278
+ }
1279
+ return url;
1280
+ }
1281
+ function executeRewriteOutput(rewrite, url) {
1282
+ const res = rewrite?.output?.({ url });
1283
+ if (res) {
1284
+ if (typeof res === "string") return new URL(res);
1285
+ else if (res instanceof URL) return res;
1286
+ }
1287
+ return url;
1288
+ }
1289
+ function createNonReactiveMutableStore(initialValue) {
1290
+ let value = initialValue;
1291
+ return {
1292
+ get() {
1293
+ return value;
1294
+ },
1295
+ set(nextOrUpdater) {
1296
+ value = functionalUpdate(nextOrUpdater, value);
1297
+ }
1298
+ };
1299
+ }
1300
+ function createNonReactiveReadonlyStore(read) {
1301
+ return { get() {
1302
+ return read();
1303
+ } };
1304
+ }
1305
+ function createRouterStores(initialState, config) {
1306
+ const { createMutableStore, createReadonlyStore, batch, init } = config;
1307
+ const matchStores = /* @__PURE__ */ new Map();
1308
+ const pendingMatchStores = /* @__PURE__ */ new Map();
1309
+ const cachedMatchStores = /* @__PURE__ */ new Map();
1310
+ const status = createMutableStore(initialState.status);
1311
+ const loadedAt = createMutableStore(initialState.loadedAt);
1312
+ const isLoading = createMutableStore(initialState.isLoading);
1313
+ const isTransitioning = createMutableStore(initialState.isTransitioning);
1314
+ const location = createMutableStore(initialState.location);
1315
+ const resolvedLocation = createMutableStore(initialState.resolvedLocation);
1316
+ const statusCode = createMutableStore(initialState.statusCode);
1317
+ const redirect2 = createMutableStore(initialState.redirect);
1318
+ const matchesId = createMutableStore([]);
1319
+ const pendingIds = createMutableStore([]);
1320
+ const cachedIds = createMutableStore([]);
1321
+ const matches = createReadonlyStore(() => readPoolMatches(matchStores, matchesId.get()));
1322
+ const pendingMatches = createReadonlyStore(() => readPoolMatches(pendingMatchStores, pendingIds.get()));
1323
+ const cachedMatches = createReadonlyStore(() => readPoolMatches(cachedMatchStores, cachedIds.get()));
1324
+ const firstId = createReadonlyStore(() => matchesId.get()[0]);
1325
+ const hasPending = createReadonlyStore(() => matchesId.get().some((matchId) => {
1326
+ return matchStores.get(matchId)?.get().status === "pending";
1327
+ }));
1328
+ const matchRouteDeps = createReadonlyStore(() => ({
1329
+ locationHref: location.get().href,
1330
+ resolvedLocationHref: resolvedLocation.get()?.href,
1331
+ status: status.get()
1332
+ }));
1333
+ const __store = createReadonlyStore(() => ({
1334
+ status: status.get(),
1335
+ loadedAt: loadedAt.get(),
1336
+ isLoading: isLoading.get(),
1337
+ isTransitioning: isTransitioning.get(),
1338
+ matches: matches.get(),
1339
+ location: location.get(),
1340
+ resolvedLocation: resolvedLocation.get(),
1341
+ statusCode: statusCode.get(),
1342
+ redirect: redirect2.get()
1343
+ }));
1344
+ const matchStoreByRouteIdCache = createLRUCache(64);
1345
+ function getRouteMatchStore(routeId) {
1346
+ let cached = matchStoreByRouteIdCache.get(routeId);
1347
+ if (!cached) {
1348
+ cached = createReadonlyStore(() => {
1349
+ const ids = matchesId.get();
1350
+ for (const id of ids) {
1351
+ const matchStore = matchStores.get(id);
1352
+ if (matchStore && matchStore.routeId === routeId) return matchStore.get();
1353
+ }
1354
+ });
1355
+ matchStoreByRouteIdCache.set(routeId, cached);
1356
+ }
1357
+ return cached;
1358
+ }
1359
+ const store = {
1360
+ status,
1361
+ loadedAt,
1362
+ isLoading,
1363
+ isTransitioning,
1364
+ location,
1365
+ resolvedLocation,
1366
+ statusCode,
1367
+ redirect: redirect2,
1368
+ matchesId,
1369
+ pendingIds,
1370
+ cachedIds,
1371
+ matches,
1372
+ pendingMatches,
1373
+ cachedMatches,
1374
+ firstId,
1375
+ hasPending,
1376
+ matchRouteDeps,
1377
+ matchStores,
1378
+ pendingMatchStores,
1379
+ cachedMatchStores,
1380
+ __store,
1381
+ getRouteMatchStore,
1382
+ setMatches,
1383
+ setPending,
1384
+ setCached
1385
+ };
1386
+ setMatches(initialState.matches);
1387
+ init?.(store);
1388
+ function setMatches(nextMatches) {
1389
+ reconcileMatchPool(nextMatches, matchStores, matchesId, createMutableStore, batch);
1390
+ }
1391
+ function setPending(nextMatches) {
1392
+ reconcileMatchPool(nextMatches, pendingMatchStores, pendingIds, createMutableStore, batch);
1393
+ }
1394
+ function setCached(nextMatches) {
1395
+ reconcileMatchPool(nextMatches, cachedMatchStores, cachedIds, createMutableStore, batch);
1396
+ }
1397
+ return store;
1398
+ }
1399
+ function readPoolMatches(pool, ids) {
1400
+ const matches = [];
1401
+ for (const id of ids) {
1402
+ const matchStore = pool.get(id);
1403
+ if (matchStore) matches.push(matchStore.get());
1404
+ }
1405
+ return matches;
1406
+ }
1407
+ function reconcileMatchPool(nextMatches, pool, idStore, createMutableStore, batch) {
1408
+ const nextIds = nextMatches.map((d) => d.id);
1409
+ const nextIdSet = new Set(nextIds);
1410
+ batch(() => {
1411
+ for (const id of pool.keys()) if (!nextIdSet.has(id)) pool.delete(id);
1412
+ for (const nextMatch of nextMatches) {
1413
+ const existing = pool.get(nextMatch.id);
1414
+ if (!existing) {
1415
+ const matchStore = createMutableStore(nextMatch);
1416
+ matchStore.routeId = nextMatch.routeId;
1417
+ pool.set(nextMatch.id, matchStore);
1418
+ continue;
1419
+ }
1420
+ existing.routeId = nextMatch.routeId;
1421
+ if (existing.get() !== nextMatch) existing.set(nextMatch);
1422
+ }
1423
+ if (!arraysEqual(idStore.get(), nextIds)) idStore.set(nextIds);
1424
+ });
1425
+ }
1426
+ const triggerOnReady = (inner) => {
1427
+ if (!inner.rendered) {
1428
+ inner.rendered = true;
1429
+ return inner.onReady?.();
1430
+ }
1431
+ };
1432
+ const resolvePreload = (inner, matchId) => {
1433
+ return !!(inner.preload && !inner.router.stores.matchStores.has(matchId));
1434
+ };
1435
+ const buildMatchContext = (inner, index, includeCurrentMatch = true) => {
1436
+ const context = { ...inner.router.options.context ?? {} };
1437
+ const end = includeCurrentMatch ? index : index - 1;
1438
+ for (let i = 0; i <= end; i++) {
1439
+ const innerMatch = inner.matches[i];
1440
+ if (!innerMatch) continue;
1441
+ const m = inner.router.getMatch(innerMatch.id);
1442
+ if (!m) continue;
1443
+ Object.assign(context, m.__routeContext, m.__beforeLoadContext);
1444
+ }
1445
+ return context;
1446
+ };
1447
+ const getNotFoundBoundaryIndex = (inner, err) => {
1448
+ if (!inner.matches.length) return;
1449
+ const requestedRouteId = err.routeId;
1450
+ const matchedRootIndex = inner.matches.findIndex((m) => m.routeId === inner.router.routeTree.id);
1451
+ const rootIndex = matchedRootIndex >= 0 ? matchedRootIndex : 0;
1452
+ let startIndex = requestedRouteId ? inner.matches.findIndex((match) => match.routeId === requestedRouteId) : inner.firstBadMatchIndex ?? inner.matches.length - 1;
1453
+ if (startIndex < 0) startIndex = rootIndex;
1454
+ for (let i = startIndex; i >= 0; i--) {
1455
+ const match = inner.matches[i];
1456
+ if (inner.router.looseRoutesById[match.routeId].options.notFoundComponent) return i;
1457
+ }
1458
+ return requestedRouteId ? startIndex : rootIndex;
1459
+ };
1460
+ const handleRedirectAndNotFound = (inner, match, err) => {
1461
+ if (!isRedirect(err) && !isNotFound(err)) return;
1462
+ if (isRedirect(err) && err.redirectHandled && !err.options.reloadDocument) throw err;
1463
+ if (match) {
1464
+ match._nonReactive.beforeLoadPromise?.resolve();
1465
+ match._nonReactive.loaderPromise?.resolve();
1466
+ match._nonReactive.beforeLoadPromise = void 0;
1467
+ match._nonReactive.loaderPromise = void 0;
1468
+ match._nonReactive.error = err;
1469
+ inner.updateMatch(match.id, (prev) => ({
1470
+ ...prev,
1471
+ status: isRedirect(err) ? "redirected" : isNotFound(err) ? "notFound" : prev.status === "pending" ? "success" : prev.status,
1472
+ context: buildMatchContext(inner, match.index),
1473
+ isFetching: false,
1474
+ error: err
1475
+ }));
1476
+ if (isNotFound(err) && !err.routeId) err.routeId = match.routeId;
1477
+ match._nonReactive.loadPromise?.resolve();
1478
+ }
1479
+ if (isRedirect(err)) {
1480
+ inner.rendered = true;
1481
+ err.options._fromLocation = inner.location;
1482
+ err.redirectHandled = true;
1483
+ err = inner.router.resolveRedirect(err);
1484
+ }
1485
+ throw err;
1486
+ };
1487
+ const shouldSkipLoader = (inner, matchId) => {
1488
+ const match = inner.router.getMatch(matchId);
1489
+ if (!match) return true;
1490
+ if (match.ssr === false) return true;
1491
+ return false;
1492
+ };
1493
+ const syncMatchContext = (inner, matchId, index) => {
1494
+ const nextContext = buildMatchContext(inner, index);
1495
+ inner.updateMatch(matchId, (prev) => {
1496
+ return {
1497
+ ...prev,
1498
+ context: nextContext
1499
+ };
1500
+ });
1501
+ };
1502
+ const handleSerialError = (inner, index, err, routerCode) => {
1503
+ const { id: matchId, routeId } = inner.matches[index];
1504
+ const route = inner.router.looseRoutesById[routeId];
1505
+ if (err instanceof Promise) throw err;
1506
+ err.routerCode = routerCode;
1507
+ inner.firstBadMatchIndex ??= index;
1508
+ handleRedirectAndNotFound(inner, inner.router.getMatch(matchId), err);
1509
+ try {
1510
+ route.options.onError?.(err);
1511
+ } catch (errorHandlerErr) {
1512
+ err = errorHandlerErr;
1513
+ handleRedirectAndNotFound(inner, inner.router.getMatch(matchId), err);
1514
+ }
1515
+ inner.updateMatch(matchId, (prev) => {
1516
+ prev._nonReactive.beforeLoadPromise?.resolve();
1517
+ prev._nonReactive.beforeLoadPromise = void 0;
1518
+ prev._nonReactive.loadPromise?.resolve();
1519
+ return {
1520
+ ...prev,
1521
+ error: err,
1522
+ status: "error",
1523
+ isFetching: false,
1524
+ updatedAt: Date.now(),
1525
+ abortController: new AbortController()
1526
+ };
1527
+ });
1528
+ if (!inner.preload && !isRedirect(err) && !isNotFound(err)) inner.serialError ??= err;
1529
+ };
1530
+ const isBeforeLoadSsr = (inner, matchId, index, route) => {
1531
+ const existingMatch = inner.router.getMatch(matchId);
1532
+ const parentMatchId = inner.matches[index - 1]?.id;
1533
+ const parentMatch = parentMatchId ? inner.router.getMatch(parentMatchId) : void 0;
1534
+ if (inner.router.isShell()) {
1535
+ existingMatch.ssr = route.id === rootRouteId;
1536
+ return;
1537
+ }
1538
+ if (parentMatch?.ssr === false) {
1539
+ existingMatch.ssr = false;
1540
+ return;
1541
+ }
1542
+ const parentOverride = (tempSsr2) => {
1543
+ if (tempSsr2 === true && parentMatch?.ssr === "data-only") return "data-only";
1544
+ return tempSsr2;
1545
+ };
1546
+ const defaultSsr = inner.router.options.defaultSsr ?? true;
1547
+ if (route.options.ssr === void 0) {
1548
+ existingMatch.ssr = parentOverride(defaultSsr);
1549
+ return;
1550
+ }
1551
+ if (typeof route.options.ssr !== "function") {
1552
+ existingMatch.ssr = parentOverride(route.options.ssr);
1553
+ return;
1554
+ }
1555
+ const { search, params } = existingMatch;
1556
+ const ssrFnContext = {
1557
+ search: makeMaybe(search, existingMatch.searchError),
1558
+ params: makeMaybe(params, existingMatch.paramsError),
1559
+ location: inner.location,
1560
+ matches: inner.matches.map((match) => ({
1561
+ index: match.index,
1562
+ pathname: match.pathname,
1563
+ fullPath: match.fullPath,
1564
+ staticData: match.staticData,
1565
+ id: match.id,
1566
+ routeId: match.routeId,
1567
+ search: makeMaybe(match.search, match.searchError),
1568
+ params: makeMaybe(match.params, match.paramsError),
1569
+ ssr: match.ssr
1570
+ }))
1571
+ };
1572
+ const tempSsr = route.options.ssr(ssrFnContext);
1573
+ if (isPromise(tempSsr)) return tempSsr.then((ssr) => {
1574
+ existingMatch.ssr = parentOverride(ssr ?? defaultSsr);
1575
+ });
1576
+ existingMatch.ssr = parentOverride(tempSsr ?? defaultSsr);
1577
+ };
1578
+ const setupPendingTimeout = (inner, matchId, route, match) => {
1579
+ if (match._nonReactive.pendingTimeout !== void 0) return;
1580
+ const pendingMs = route.options.pendingMs ?? inner.router.options.defaultPendingMs;
1581
+ if (!!(inner.onReady && false)) {
1582
+ const pendingTimeout = setTimeout(() => {
1583
+ triggerOnReady(inner);
1584
+ }, pendingMs);
1585
+ match._nonReactive.pendingTimeout = pendingTimeout;
1586
+ }
1587
+ };
1588
+ const preBeforeLoadSetup = (inner, matchId, route) => {
1589
+ const existingMatch = inner.router.getMatch(matchId);
1590
+ if (!existingMatch._nonReactive.beforeLoadPromise && !existingMatch._nonReactive.loaderPromise) return;
1591
+ setupPendingTimeout(inner, matchId, route, existingMatch);
1592
+ const then = () => {
1593
+ const match = inner.router.getMatch(matchId);
1594
+ if (match.preload && (match.status === "redirected" || match.status === "notFound")) handleRedirectAndNotFound(inner, match, match.error);
1595
+ };
1596
+ return existingMatch._nonReactive.beforeLoadPromise ? existingMatch._nonReactive.beforeLoadPromise.then(then) : then();
1597
+ };
1598
+ const executeBeforeLoad = (inner, matchId, index, route) => {
1599
+ const match = inner.router.getMatch(matchId);
1600
+ let prevLoadPromise = match._nonReactive.loadPromise;
1601
+ match._nonReactive.loadPromise = createControlledPromise(() => {
1602
+ prevLoadPromise?.resolve();
1603
+ prevLoadPromise = void 0;
1604
+ });
1605
+ const { paramsError, searchError } = match;
1606
+ if (paramsError) handleSerialError(inner, index, paramsError, "PARSE_PARAMS");
1607
+ if (searchError) handleSerialError(inner, index, searchError, "VALIDATE_SEARCH");
1608
+ setupPendingTimeout(inner, matchId, route, match);
1609
+ const abortController = new AbortController();
1610
+ let isPending = false;
1611
+ const pending = () => {
1612
+ if (isPending) return;
1613
+ isPending = true;
1614
+ inner.updateMatch(matchId, (prev) => ({
1615
+ ...prev,
1616
+ isFetching: "beforeLoad",
1617
+ fetchCount: prev.fetchCount + 1,
1618
+ abortController
1619
+ }));
1620
+ };
1621
+ const resolve = () => {
1622
+ match._nonReactive.beforeLoadPromise?.resolve();
1623
+ match._nonReactive.beforeLoadPromise = void 0;
1624
+ inner.updateMatch(matchId, (prev) => ({
1625
+ ...prev,
1626
+ isFetching: false
1627
+ }));
1628
+ };
1629
+ if (!route.options.beforeLoad) {
1630
+ inner.router.batch(() => {
1631
+ pending();
1632
+ resolve();
1633
+ });
1634
+ return;
1635
+ }
1636
+ match._nonReactive.beforeLoadPromise = createControlledPromise();
1637
+ const context = {
1638
+ ...buildMatchContext(inner, index, false),
1639
+ ...match.__routeContext
1640
+ };
1641
+ const { search, params, cause } = match;
1642
+ const preload = resolvePreload(inner, matchId);
1643
+ const beforeLoadFnContext = {
1644
+ search,
1645
+ abortController,
1646
+ params,
1647
+ preload,
1648
+ context,
1649
+ location: inner.location,
1650
+ navigate: (opts) => inner.router.navigate({
1651
+ ...opts,
1652
+ _fromLocation: inner.location
1653
+ }),
1654
+ buildLocation: inner.router.buildLocation,
1655
+ cause: preload ? "preload" : cause,
1656
+ matches: inner.matches,
1657
+ routeId: route.id,
1658
+ ...inner.router.options.additionalContext
1659
+ };
1660
+ const updateContext = (beforeLoadContext2) => {
1661
+ if (beforeLoadContext2 === void 0) {
1662
+ inner.router.batch(() => {
1663
+ pending();
1664
+ resolve();
1665
+ });
1666
+ return;
1667
+ }
1668
+ if (isRedirect(beforeLoadContext2) || isNotFound(beforeLoadContext2)) {
1669
+ pending();
1670
+ handleSerialError(inner, index, beforeLoadContext2, "BEFORE_LOAD");
1671
+ }
1672
+ inner.router.batch(() => {
1673
+ pending();
1674
+ inner.updateMatch(matchId, (prev) => ({
1675
+ ...prev,
1676
+ __beforeLoadContext: beforeLoadContext2
1677
+ }));
1678
+ resolve();
1679
+ });
1680
+ };
1681
+ let beforeLoadContext;
1682
+ try {
1683
+ beforeLoadContext = route.options.beforeLoad(beforeLoadFnContext);
1684
+ if (isPromise(beforeLoadContext)) {
1685
+ pending();
1686
+ return beforeLoadContext.catch((err) => {
1687
+ handleSerialError(inner, index, err, "BEFORE_LOAD");
1688
+ }).then(updateContext);
1689
+ }
1690
+ } catch (err) {
1691
+ pending();
1692
+ handleSerialError(inner, index, err, "BEFORE_LOAD");
1693
+ }
1694
+ updateContext(beforeLoadContext);
1695
+ };
1696
+ const handleBeforeLoad = (inner, index) => {
1697
+ const { id: matchId, routeId } = inner.matches[index];
1698
+ const route = inner.router.looseRoutesById[routeId];
1699
+ const serverSsr = () => {
1700
+ {
1701
+ const maybePromise = isBeforeLoadSsr(inner, matchId, index, route);
1702
+ if (isPromise(maybePromise)) return maybePromise.then(queueExecution);
1703
+ }
1704
+ return queueExecution();
1705
+ };
1706
+ const execute = () => executeBeforeLoad(inner, matchId, index, route);
1707
+ const queueExecution = () => {
1708
+ if (shouldSkipLoader(inner, matchId)) return;
1709
+ const result = preBeforeLoadSetup(inner, matchId, route);
1710
+ return isPromise(result) ? result.then(execute) : execute();
1711
+ };
1712
+ return serverSsr();
1713
+ };
1714
+ const executeHead = (inner, matchId, route) => {
1715
+ const match = inner.router.getMatch(matchId);
1716
+ if (!match) return;
1717
+ if (!route.options.head && !route.options.scripts && !route.options.headers) return;
1718
+ const assetContext = {
1719
+ ssr: inner.router.options.ssr,
1720
+ matches: inner.matches,
1721
+ match,
1722
+ params: match.params,
1723
+ loaderData: match.loaderData
1724
+ };
1725
+ return Promise.all([
1726
+ route.options.head?.(assetContext),
1727
+ route.options.scripts?.(assetContext),
1728
+ route.options.headers?.(assetContext)
1729
+ ]).then(([headFnContent, scripts, headers]) => {
1730
+ return {
1731
+ meta: headFnContent?.meta,
1732
+ links: headFnContent?.links,
1733
+ headScripts: headFnContent?.scripts,
1734
+ headers,
1735
+ scripts,
1736
+ styles: headFnContent?.styles
1737
+ };
1738
+ });
1739
+ };
1740
+ const getLoaderContext = (inner, matchPromises, matchId, index, route) => {
1741
+ const parentMatchPromise = matchPromises[index - 1];
1742
+ const { params, loaderDeps, abortController, cause } = inner.router.getMatch(matchId);
1743
+ const context = buildMatchContext(inner, index);
1744
+ const preload = resolvePreload(inner, matchId);
1745
+ return {
1746
+ params,
1747
+ deps: loaderDeps,
1748
+ preload: !!preload,
1749
+ parentMatchPromise,
1750
+ abortController,
1751
+ context,
1752
+ location: inner.location,
1753
+ navigate: (opts) => inner.router.navigate({
1754
+ ...opts,
1755
+ _fromLocation: inner.location
1756
+ }),
1757
+ cause: preload ? "preload" : cause,
1758
+ route,
1759
+ ...inner.router.options.additionalContext
1760
+ };
1761
+ };
1762
+ const runLoader = async (inner, matchPromises, matchId, index, route) => {
1763
+ try {
1764
+ const match = inner.router.getMatch(matchId);
1765
+ try {
1766
+ if (!(isServer ?? inner.router.isServer) || match.ssr === true) loadRouteChunk(route);
1767
+ const routeLoader = route.options.loader;
1768
+ const loader = typeof routeLoader === "function" ? routeLoader : routeLoader?.handler;
1769
+ const loaderResult = loader?.(getLoaderContext(inner, matchPromises, matchId, index, route));
1770
+ const loaderResultIsPromise = !!loader && isPromise(loaderResult);
1771
+ if (!!(loaderResultIsPromise || route._lazyPromise || route._componentsPromise || route.options.head || route.options.scripts || route.options.headers || match._nonReactive.minPendingPromise)) inner.updateMatch(matchId, (prev) => ({
1772
+ ...prev,
1773
+ isFetching: "loader"
1774
+ }));
1775
+ if (loader) {
1776
+ const loaderData = loaderResultIsPromise ? await loaderResult : loaderResult;
1777
+ handleRedirectAndNotFound(inner, inner.router.getMatch(matchId), loaderData);
1778
+ if (loaderData !== void 0) inner.updateMatch(matchId, (prev) => ({
1779
+ ...prev,
1780
+ loaderData
1781
+ }));
1782
+ }
1783
+ if (route._lazyPromise) await route._lazyPromise;
1784
+ const pendingPromise = match._nonReactive.minPendingPromise;
1785
+ if (pendingPromise) await pendingPromise;
1786
+ if (route._componentsPromise) await route._componentsPromise;
1787
+ inner.updateMatch(matchId, (prev) => ({
1788
+ ...prev,
1789
+ error: void 0,
1790
+ context: buildMatchContext(inner, index),
1791
+ status: "success",
1792
+ isFetching: false,
1793
+ updatedAt: Date.now()
1794
+ }));
1795
+ } catch (e) {
1796
+ let error = e;
1797
+ if (error?.name === "AbortError") {
1798
+ if (match.abortController.signal.aborted) {
1799
+ match._nonReactive.loaderPromise?.resolve();
1800
+ match._nonReactive.loaderPromise = void 0;
1801
+ return;
1802
+ }
1803
+ inner.updateMatch(matchId, (prev) => ({
1804
+ ...prev,
1805
+ status: prev.status === "pending" ? "success" : prev.status,
1806
+ isFetching: false,
1807
+ context: buildMatchContext(inner, index)
1808
+ }));
1809
+ return;
1810
+ }
1811
+ const pendingPromise = match._nonReactive.minPendingPromise;
1812
+ if (pendingPromise) await pendingPromise;
1813
+ if (isNotFound(e)) await route.options.notFoundComponent?.preload?.();
1814
+ handleRedirectAndNotFound(inner, inner.router.getMatch(matchId), e);
1815
+ try {
1816
+ route.options.onError?.(e);
1817
+ } catch (onErrorError) {
1818
+ error = onErrorError;
1819
+ handleRedirectAndNotFound(inner, inner.router.getMatch(matchId), onErrorError);
1820
+ }
1821
+ if (!isRedirect(error) && !isNotFound(error)) await loadRouteChunk(route, ["errorComponent"]);
1822
+ inner.updateMatch(matchId, (prev) => ({
1823
+ ...prev,
1824
+ error,
1825
+ context: buildMatchContext(inner, index),
1826
+ status: "error",
1827
+ isFetching: false
1828
+ }));
1829
+ }
1830
+ } catch (err) {
1831
+ const match = inner.router.getMatch(matchId);
1832
+ if (match) match._nonReactive.loaderPromise = void 0;
1833
+ handleRedirectAndNotFound(inner, match, err);
1834
+ }
1835
+ };
1836
+ const loadRouteMatch = async (inner, matchPromises, index) => {
1837
+ async function handleLoader(preload, prevMatch, previousRouteMatchId, match2, route2) {
1838
+ const age = Date.now() - prevMatch.updatedAt;
1839
+ const staleAge = preload ? route2.options.preloadStaleTime ?? inner.router.options.defaultPreloadStaleTime ?? 3e4 : route2.options.staleTime ?? inner.router.options.defaultStaleTime ?? 0;
1840
+ const shouldReloadOption = route2.options.shouldReload;
1841
+ const shouldReload = typeof shouldReloadOption === "function" ? shouldReloadOption(getLoaderContext(inner, matchPromises, matchId, index, route2)) : shouldReloadOption;
1842
+ const { status, invalid } = match2;
1843
+ const staleMatchShouldReload = age >= staleAge && (!!inner.forceStaleReload || match2.cause === "enter" || previousRouteMatchId !== void 0 && previousRouteMatchId !== match2.id);
1844
+ loaderShouldRunAsync = status === "success" && (invalid || (shouldReload ?? staleMatchShouldReload));
1845
+ if (preload && route2.options.preload === false) ;
1846
+ else if (loaderShouldRunAsync && !inner.sync && shouldReloadInBackground) {
1847
+ loaderIsRunningAsync = true;
1848
+ (async () => {
1849
+ try {
1850
+ await runLoader(inner, matchPromises, matchId, index, route2);
1851
+ const match3 = inner.router.getMatch(matchId);
1852
+ match3._nonReactive.loaderPromise?.resolve();
1853
+ match3._nonReactive.loadPromise?.resolve();
1854
+ match3._nonReactive.loaderPromise = void 0;
1855
+ match3._nonReactive.loadPromise = void 0;
1856
+ } catch (err) {
1857
+ if (isRedirect(err)) await inner.router.navigate(err.options);
1858
+ }
1859
+ })();
1860
+ } else if (status !== "success" || loaderShouldRunAsync) await runLoader(inner, matchPromises, matchId, index, route2);
1861
+ else syncMatchContext(inner, matchId, index);
1862
+ }
1863
+ const { id: matchId, routeId } = inner.matches[index];
1864
+ let loaderShouldRunAsync = false;
1865
+ let loaderIsRunningAsync = false;
1866
+ const route = inner.router.looseRoutesById[routeId];
1867
+ const routeLoader = route.options.loader;
1868
+ const shouldReloadInBackground = ((typeof routeLoader === "function" ? void 0 : routeLoader?.staleReloadMode) ?? inner.router.options.defaultStaleReloadMode) !== "blocking";
1869
+ if (shouldSkipLoader(inner, matchId)) {
1870
+ if (!inner.router.getMatch(matchId)) return inner.matches[index];
1871
+ syncMatchContext(inner, matchId, index);
1872
+ return inner.router.getMatch(matchId);
1873
+ } else {
1874
+ const prevMatch = inner.router.getMatch(matchId);
1875
+ const activeIdAtIndex = inner.router.stores.matchesId.get()[index];
1876
+ const previousRouteMatchId = (activeIdAtIndex && inner.router.stores.matchStores.get(activeIdAtIndex) || null)?.routeId === routeId ? activeIdAtIndex : inner.router.stores.matches.get().find((d) => d.routeId === routeId)?.id;
1877
+ const preload = resolvePreload(inner, matchId);
1878
+ if (prevMatch._nonReactive.loaderPromise) {
1879
+ if (prevMatch.status === "success" && !inner.sync && !prevMatch.preload && shouldReloadInBackground) return prevMatch;
1880
+ await prevMatch._nonReactive.loaderPromise;
1881
+ const match2 = inner.router.getMatch(matchId);
1882
+ const error = match2._nonReactive.error || match2.error;
1883
+ if (error) handleRedirectAndNotFound(inner, match2, error);
1884
+ if (match2.status === "pending") await handleLoader(preload, prevMatch, previousRouteMatchId, match2, route);
1885
+ } else {
1886
+ const nextPreload = preload && !inner.router.stores.matchStores.has(matchId);
1887
+ const match2 = inner.router.getMatch(matchId);
1888
+ match2._nonReactive.loaderPromise = createControlledPromise();
1889
+ if (nextPreload !== match2.preload) inner.updateMatch(matchId, (prev) => ({
1890
+ ...prev,
1891
+ preload: nextPreload
1892
+ }));
1893
+ await handleLoader(preload, prevMatch, previousRouteMatchId, match2, route);
1894
+ }
1895
+ }
1896
+ const match = inner.router.getMatch(matchId);
1897
+ if (!loaderIsRunningAsync) {
1898
+ match._nonReactive.loaderPromise?.resolve();
1899
+ match._nonReactive.loadPromise?.resolve();
1900
+ match._nonReactive.loadPromise = void 0;
1901
+ }
1902
+ clearTimeout(match._nonReactive.pendingTimeout);
1903
+ match._nonReactive.pendingTimeout = void 0;
1904
+ if (!loaderIsRunningAsync) match._nonReactive.loaderPromise = void 0;
1905
+ match._nonReactive.dehydrated = void 0;
1906
+ const nextIsFetching = loaderIsRunningAsync ? match.isFetching : false;
1907
+ if (nextIsFetching !== match.isFetching || match.invalid !== false) {
1908
+ inner.updateMatch(matchId, (prev) => ({
1909
+ ...prev,
1910
+ isFetching: nextIsFetching,
1911
+ invalid: false
1912
+ }));
1913
+ return inner.router.getMatch(matchId);
1914
+ } else return match;
1915
+ };
1916
+ async function loadMatches(arg) {
1917
+ const inner = arg;
1918
+ const matchPromises = [];
1919
+ let beforeLoadNotFound;
1920
+ for (let i = 0; i < inner.matches.length; i++) {
1921
+ try {
1922
+ const beforeLoad = handleBeforeLoad(inner, i);
1923
+ if (isPromise(beforeLoad)) await beforeLoad;
1924
+ } catch (err) {
1925
+ if (isRedirect(err)) throw err;
1926
+ if (isNotFound(err)) beforeLoadNotFound = err;
1927
+ else if (!inner.preload) throw err;
1928
+ break;
1929
+ }
1930
+ if (inner.serialError || inner.firstBadMatchIndex != null) break;
1931
+ }
1932
+ const baseMaxIndexExclusive = inner.firstBadMatchIndex ?? inner.matches.length;
1933
+ const boundaryIndex = beforeLoadNotFound && !inner.preload ? getNotFoundBoundaryIndex(inner, beforeLoadNotFound) : void 0;
1934
+ const maxIndexExclusive = beforeLoadNotFound && inner.preload ? 0 : boundaryIndex !== void 0 ? Math.min(boundaryIndex + 1, baseMaxIndexExclusive) : baseMaxIndexExclusive;
1935
+ let firstNotFound;
1936
+ let firstUnhandledRejection;
1937
+ for (let i = 0; i < maxIndexExclusive; i++) matchPromises.push(loadRouteMatch(inner, matchPromises, i));
1938
+ try {
1939
+ await Promise.all(matchPromises);
1940
+ } catch {
1941
+ const settled = await Promise.allSettled(matchPromises);
1942
+ for (const result of settled) {
1943
+ if (result.status !== "rejected") continue;
1944
+ const reason = result.reason;
1945
+ if (isRedirect(reason)) throw reason;
1946
+ if (isNotFound(reason)) firstNotFound ??= reason;
1947
+ else firstUnhandledRejection ??= reason;
1948
+ }
1949
+ if (firstUnhandledRejection !== void 0) throw firstUnhandledRejection;
1950
+ }
1951
+ const notFoundToThrow = firstNotFound ?? (beforeLoadNotFound && !inner.preload ? beforeLoadNotFound : void 0);
1952
+ let headMaxIndex = inner.firstBadMatchIndex !== void 0 ? inner.firstBadMatchIndex : inner.matches.length - 1;
1953
+ if (!notFoundToThrow && beforeLoadNotFound && inner.preload) return inner.matches;
1954
+ if (notFoundToThrow) {
1955
+ const renderedBoundaryIndex = getNotFoundBoundaryIndex(inner, notFoundToThrow);
1956
+ if (renderedBoundaryIndex === void 0) {
1957
+ invariant();
1958
+ }
1959
+ const boundaryMatch = inner.matches[renderedBoundaryIndex];
1960
+ const boundaryRoute = inner.router.looseRoutesById[boundaryMatch.routeId];
1961
+ const defaultNotFoundComponent = inner.router.options?.defaultNotFoundComponent;
1962
+ if (!boundaryRoute.options.notFoundComponent && defaultNotFoundComponent) boundaryRoute.options.notFoundComponent = defaultNotFoundComponent;
1963
+ notFoundToThrow.routeId = boundaryMatch.routeId;
1964
+ const boundaryIsRoot = boundaryMatch.routeId === inner.router.routeTree.id;
1965
+ inner.updateMatch(boundaryMatch.id, (prev) => ({
1966
+ ...prev,
1967
+ ...boundaryIsRoot ? {
1968
+ status: "success",
1969
+ globalNotFound: true,
1970
+ error: void 0
1971
+ } : {
1972
+ status: "notFound",
1973
+ error: notFoundToThrow
1974
+ },
1975
+ isFetching: false
1976
+ }));
1977
+ headMaxIndex = renderedBoundaryIndex;
1978
+ await loadRouteChunk(boundaryRoute, ["notFoundComponent"]);
1979
+ } else if (!inner.preload) {
1980
+ const rootMatch = inner.matches[0];
1981
+ if (!rootMatch.globalNotFound) {
1982
+ if (inner.router.getMatch(rootMatch.id)?.globalNotFound) inner.updateMatch(rootMatch.id, (prev) => ({
1983
+ ...prev,
1984
+ globalNotFound: false,
1985
+ error: void 0
1986
+ }));
1987
+ }
1988
+ }
1989
+ if (inner.serialError && inner.firstBadMatchIndex !== void 0) {
1990
+ const errorRoute = inner.router.looseRoutesById[inner.matches[inner.firstBadMatchIndex].routeId];
1991
+ await loadRouteChunk(errorRoute, ["errorComponent"]);
1992
+ }
1993
+ for (let i = 0; i <= headMaxIndex; i++) {
1994
+ const { id: matchId, routeId } = inner.matches[i];
1995
+ const route = inner.router.looseRoutesById[routeId];
1996
+ try {
1997
+ const headResult = executeHead(inner, matchId, route);
1998
+ if (headResult) {
1999
+ const head = await headResult;
2000
+ inner.updateMatch(matchId, (prev) => ({
2001
+ ...prev,
2002
+ ...head
2003
+ }));
2004
+ }
2005
+ } catch (err) {
2006
+ console.error(`Error executing head for route ${routeId}:`, err);
2007
+ }
2008
+ }
2009
+ const readyPromise = triggerOnReady(inner);
2010
+ if (isPromise(readyPromise)) await readyPromise;
2011
+ if (notFoundToThrow) throw notFoundToThrow;
2012
+ if (inner.serialError && !inner.preload && !inner.onReady) throw inner.serialError;
2013
+ return inner.matches;
2014
+ }
2015
+ function preloadRouteComponents(route, componentTypesToLoad) {
2016
+ const preloads = componentTypesToLoad.map((type) => route.options[type]?.preload?.()).filter(Boolean);
2017
+ if (preloads.length === 0) return void 0;
2018
+ return Promise.all(preloads);
2019
+ }
2020
+ function loadRouteChunk(route, componentTypesToLoad = componentTypes) {
2021
+ if (!route._lazyLoaded && route._lazyPromise === void 0) if (route.lazyFn) route._lazyPromise = route.lazyFn().then((lazyRoute) => {
2022
+ const { id: _id, ...options } = lazyRoute.options;
2023
+ Object.assign(route.options, options);
2024
+ route._lazyLoaded = true;
2025
+ route._lazyPromise = void 0;
2026
+ });
2027
+ else route._lazyLoaded = true;
2028
+ const runAfterLazy = () => route._componentsLoaded ? void 0 : componentTypesToLoad === componentTypes ? (() => {
2029
+ if (route._componentsPromise === void 0) {
2030
+ const componentsPromise = preloadRouteComponents(route, componentTypes);
2031
+ if (componentsPromise) route._componentsPromise = componentsPromise.then(() => {
2032
+ route._componentsLoaded = true;
2033
+ route._componentsPromise = void 0;
2034
+ });
2035
+ else route._componentsLoaded = true;
2036
+ }
2037
+ return route._componentsPromise;
2038
+ })() : preloadRouteComponents(route, componentTypesToLoad);
2039
+ return route._lazyPromise ? route._lazyPromise.then(runAfterLazy) : runAfterLazy();
2040
+ }
2041
+ function makeMaybe(value, error) {
2042
+ if (error) return {
2043
+ status: "error",
2044
+ error
2045
+ };
2046
+ return {
2047
+ status: "success",
2048
+ value
2049
+ };
2050
+ }
2051
+ function routeNeedsPreload(route) {
2052
+ for (const componentType of componentTypes) if (route.options[componentType]?.preload) return true;
2053
+ return false;
2054
+ }
2055
+ const componentTypes = [
2056
+ "component",
2057
+ "errorComponent",
2058
+ "pendingComponent",
2059
+ "notFoundComponent"
2060
+ ];
2061
+ function getLocationChangeInfo(location, resolvedLocation) {
2062
+ const fromLocation = resolvedLocation;
2063
+ const toLocation = location;
2064
+ return {
2065
+ fromLocation,
2066
+ toLocation,
2067
+ pathChanged: fromLocation?.pathname !== toLocation.pathname,
2068
+ hrefChanged: fromLocation?.href !== toLocation.href,
2069
+ hashChanged: fromLocation?.hash !== toLocation.hash
2070
+ };
2071
+ }
2072
+ var RouterCore = class {
2073
+ /**
2074
+ * @deprecated Use the `createRouter` function instead
2075
+ */
2076
+ constructor(options, getStoreConfig) {
2077
+ this.tempLocationKey = `${Math.round(Math.random() * 1e7)}`;
2078
+ this.resetNextScroll = true;
2079
+ this.shouldViewTransition = void 0;
2080
+ this.isViewTransitionTypesSupported = void 0;
2081
+ this.subscribers = /* @__PURE__ */ new Set();
2082
+ this.isScrollRestoring = false;
2083
+ this.isScrollRestorationSetup = false;
2084
+ this.routeBranchCache = /* @__PURE__ */ new WeakMap();
2085
+ this.startTransition = (fn) => fn();
2086
+ this.update = (newOptions) => {
2087
+ const prevOptions = this.options;
2088
+ const prevBasepath = this.basepath ?? prevOptions?.basepath ?? "/";
2089
+ const basepathWasUnset = this.basepath === void 0;
2090
+ const prevRewriteOption = prevOptions?.rewrite;
2091
+ this.options = {
2092
+ ...prevOptions,
2093
+ ...newOptions
2094
+ };
2095
+ this.isServer = this.options.isServer ?? typeof document === "undefined";
2096
+ this.protocolAllowlist = new Set(this.options.protocolAllowlist);
2097
+ if (this.options.pathParamsAllowedCharacters) this.pathParamsDecoder = compileDecodeCharMap(this.options.pathParamsAllowedCharacters);
2098
+ if (!this.history || this.options.history && this.options.history !== this.history) if (!this.options.history) ;
2099
+ else this.history = this.options.history;
2100
+ this.origin = this.options.origin;
2101
+ if (!this.origin) this.origin = "http://localhost";
2102
+ if (this.history) this.updateLatestLocation();
2103
+ if (this.options.routeTree !== this.routeTree) {
2104
+ this.routeTree = this.options.routeTree;
2105
+ let processRouteTreeResult;
2106
+ if (globalThis.__TSR_CACHE__ && globalThis.__TSR_CACHE__.routeTree === this.routeTree) {
2107
+ const cached = globalThis.__TSR_CACHE__;
2108
+ this.resolvePathCache = cached.resolvePathCache;
2109
+ processRouteTreeResult = cached.processRouteTreeResult;
2110
+ } else {
2111
+ this.resolvePathCache = createLRUCache(1e3);
2112
+ processRouteTreeResult = this.buildRouteTree();
2113
+ if (globalThis.__TSR_CACHE__ === void 0) globalThis.__TSR_CACHE__ = {
2114
+ routeTree: this.routeTree,
2115
+ processRouteTreeResult,
2116
+ resolvePathCache: this.resolvePathCache
2117
+ };
2118
+ }
2119
+ this.setRoutes(processRouteTreeResult);
2120
+ }
2121
+ if (!this.stores && this.latestLocation) {
2122
+ const config = this.getStoreConfig(this);
2123
+ this.batch = config.batch;
2124
+ this.stores = createRouterStores(getInitialRouterState(this.latestLocation), config);
2125
+ }
2126
+ let needsLocationUpdate = false;
2127
+ const nextBasepath = this.options.basepath ?? "/";
2128
+ const nextRewriteOption = this.options.rewrite;
2129
+ if (basepathWasUnset || prevBasepath !== nextBasepath || prevRewriteOption !== nextRewriteOption) {
2130
+ this.basepath = nextBasepath;
2131
+ const rewrites = [];
2132
+ const trimmed = trimPath(nextBasepath);
2133
+ if (trimmed && trimmed !== "/") rewrites.push(rewriteBasepath({ basepath: nextBasepath }));
2134
+ if (nextRewriteOption) rewrites.push(nextRewriteOption);
2135
+ this.rewrite = rewrites.length === 0 ? void 0 : rewrites.length === 1 ? rewrites[0] : composeRewrites(rewrites);
2136
+ if (this.history) this.updateLatestLocation();
2137
+ needsLocationUpdate = true;
2138
+ }
2139
+ if (needsLocationUpdate && this.stores) this.stores.location.set(this.latestLocation);
2140
+ if (typeof window !== "undefined" && "CSS" in window && typeof window.CSS?.supports === "function") this.isViewTransitionTypesSupported = window.CSS.supports("selector(:active-view-transition-type(a)");
2141
+ };
2142
+ this.updateLatestLocation = () => {
2143
+ this.latestLocation = this.parseLocation(this.history.location, this.latestLocation);
2144
+ };
2145
+ this.buildRouteTree = () => {
2146
+ const result = processRouteTree(this.routeTree, this.options.caseSensitive, (route, i) => {
2147
+ route.init({ originalIndex: i });
2148
+ });
2149
+ if (this.options.routeMasks) processRouteMasks(this.options.routeMasks, result.processedTree);
2150
+ return result;
2151
+ };
2152
+ this.subscribe = (eventType, fn) => {
2153
+ const listener = {
2154
+ eventType,
2155
+ fn
2156
+ };
2157
+ this.subscribers.add(listener);
2158
+ return () => {
2159
+ this.subscribers.delete(listener);
2160
+ };
2161
+ };
2162
+ this.emit = (routerEvent) => {
2163
+ this.subscribers.forEach((listener) => {
2164
+ if (listener.eventType === routerEvent.type) listener.fn(routerEvent);
2165
+ });
2166
+ };
2167
+ this.parseLocation = (locationToParse, previousLocation) => {
2168
+ const parse = ({ pathname, search, hash, href, state }) => {
2169
+ if (!this.rewrite && !/[ \x00-\x1f\x7f\u0080-\uffff]/.test(pathname)) {
2170
+ const parsedSearch2 = this.options.parseSearch(search);
2171
+ const searchStr2 = this.options.stringifySearch(parsedSearch2);
2172
+ return {
2173
+ href: pathname + searchStr2 + hash,
2174
+ publicHref: pathname + searchStr2 + hash,
2175
+ pathname: decodePath(pathname).path,
2176
+ external: false,
2177
+ searchStr: searchStr2,
2178
+ search: nullReplaceEqualDeep(previousLocation?.search, parsedSearch2),
2179
+ hash: decodePath(hash.slice(1)).path,
2180
+ state: replaceEqualDeep(previousLocation?.state, state)
2181
+ };
2182
+ }
2183
+ const fullUrl = new URL(href, this.origin);
2184
+ const url = executeRewriteInput(this.rewrite, fullUrl);
2185
+ const parsedSearch = this.options.parseSearch(url.search);
2186
+ const searchStr = this.options.stringifySearch(parsedSearch);
2187
+ url.search = searchStr;
2188
+ return {
2189
+ href: url.href.replace(url.origin, ""),
2190
+ publicHref: href,
2191
+ pathname: decodePath(url.pathname).path,
2192
+ external: !!this.rewrite && url.origin !== this.origin,
2193
+ searchStr,
2194
+ search: nullReplaceEqualDeep(previousLocation?.search, parsedSearch),
2195
+ hash: decodePath(url.hash.slice(1)).path,
2196
+ state: replaceEqualDeep(previousLocation?.state, state)
2197
+ };
2198
+ };
2199
+ const location = parse(locationToParse);
2200
+ const { __tempLocation, __tempKey } = location.state;
2201
+ if (__tempLocation && (!__tempKey || __tempKey === this.tempLocationKey)) {
2202
+ const parsedTempLocation = parse(__tempLocation);
2203
+ parsedTempLocation.state.key = location.state.key;
2204
+ parsedTempLocation.state.__TSR_key = location.state.__TSR_key;
2205
+ delete parsedTempLocation.state.__tempLocation;
2206
+ return {
2207
+ ...parsedTempLocation,
2208
+ maskedLocation: location
2209
+ };
2210
+ }
2211
+ return location;
2212
+ };
2213
+ this.resolvePathWithBase = (from, path) => {
2214
+ return resolvePath({
2215
+ base: from,
2216
+ to: path.includes("//") ? cleanPath(path) : path,
2217
+ trailingSlash: this.options.trailingSlash,
2218
+ cache: this.resolvePathCache
2219
+ });
2220
+ };
2221
+ this.matchRoutes = (pathnameOrNext, locationSearchOrOpts, opts) => {
2222
+ if (typeof pathnameOrNext === "string") return this.matchRoutesInternal({
2223
+ pathname: pathnameOrNext,
2224
+ search: locationSearchOrOpts
2225
+ }, opts);
2226
+ return this.matchRoutesInternal(pathnameOrNext, locationSearchOrOpts);
2227
+ };
2228
+ this.getMatchedRoutes = (pathname) => {
2229
+ return getMatchedRoutes({
2230
+ pathname,
2231
+ routesById: this.routesById,
2232
+ processedTree: this.processedTree
2233
+ });
2234
+ };
2235
+ this.cancelMatch = (id) => {
2236
+ const match = this.getMatch(id);
2237
+ if (!match) return;
2238
+ match.abortController.abort();
2239
+ clearTimeout(match._nonReactive.pendingTimeout);
2240
+ match._nonReactive.pendingTimeout = void 0;
2241
+ };
2242
+ this.cancelMatches = () => {
2243
+ this.stores.pendingIds.get().forEach((matchId) => {
2244
+ this.cancelMatch(matchId);
2245
+ });
2246
+ this.stores.matchesId.get().forEach((matchId) => {
2247
+ if (this.stores.pendingMatchStores.has(matchId)) return;
2248
+ const match = this.stores.matchStores.get(matchId)?.get();
2249
+ if (!match) return;
2250
+ if (match.status === "pending" || match.isFetching === "loader") this.cancelMatch(matchId);
2251
+ });
2252
+ };
2253
+ this.buildLocation = (opts) => {
2254
+ const build = (dest = {}) => {
2255
+ const currentLocation = dest._fromLocation || this.pendingBuiltLocation || this.latestLocation;
2256
+ const lightweightResult = this.matchRoutesLightweight(currentLocation);
2257
+ if (dest.from && false) ;
2258
+ const defaultedFromPath = dest.unsafeRelative === "path" ? currentLocation.pathname : dest.from ?? lightweightResult.fullPath;
2259
+ const destTo = dest.to ? `${dest.to}` : void 0;
2260
+ const fromSearch = lightweightResult.search;
2261
+ const fromParams = Object.assign(/* @__PURE__ */ Object.create(null), lightweightResult.params);
2262
+ const sourcePath = destTo?.charCodeAt(0) === 47 ? "/" : this.resolvePathWithBase(defaultedFromPath, ".");
2263
+ const nextTo = destTo ? this.resolvePathWithBase(sourcePath, destTo) : sourcePath;
2264
+ const nextParams = dest.params === false || dest.params === null ? /* @__PURE__ */ Object.create(null) : (dest.params ?? true) === true ? fromParams : Object.assign(fromParams, functionalUpdate(dest.params, fromParams));
2265
+ const destRoute = this.routesByPath[trimPathRight(nextTo)];
2266
+ let destRoutes;
2267
+ if (destRoute) destRoutes = this.getRouteBranch(destRoute);
2268
+ else if (nextTo.includes("$")) destRoutes = [];
2269
+ else {
2270
+ const destMatchResult = this.getMatchedRoutes(nextTo);
2271
+ destRoutes = destMatchResult.matchedRoutes;
2272
+ if (this.options.notFoundRoute && (!destMatchResult.foundRoute || destMatchResult.foundRoute.path !== "/" && destMatchResult.routeParams["**"])) destRoutes = [...destRoutes, this.options.notFoundRoute];
2273
+ }
2274
+ if (destRoutes.length && hasKeys(nextParams)) for (const route of destRoutes) {
2275
+ const fn = route.options.params?.stringify ?? route.options.stringifyParams;
2276
+ if (fn) try {
2277
+ Object.assign(nextParams, fn(nextParams));
2278
+ } catch {
2279
+ }
2280
+ }
2281
+ const nextPathname = opts.leaveParams ? nextTo : decodePath(interpolatePath({
2282
+ path: nextTo,
2283
+ params: nextParams,
2284
+ decoder: this.pathParamsDecoder,
2285
+ server: this.isServer
2286
+ }).interpolatedPath).path;
2287
+ let nextSearch = fromSearch;
2288
+ if (opts._includeValidateSearch && this.options.search?.strict) {
2289
+ const validatedSearch = {};
2290
+ destRoutes.forEach((route) => {
2291
+ if (route.options.validateSearch) try {
2292
+ Object.assign(validatedSearch, validateSearch(route.options.validateSearch, {
2293
+ ...validatedSearch,
2294
+ ...nextSearch
2295
+ }));
2296
+ } catch {
2297
+ }
2298
+ });
2299
+ nextSearch = validatedSearch;
2300
+ }
2301
+ nextSearch = applySearchMiddleware({
2302
+ search: nextSearch,
2303
+ dest,
2304
+ destRoutes,
2305
+ _includeValidateSearch: opts._includeValidateSearch
2306
+ });
2307
+ nextSearch = nullReplaceEqualDeep(fromSearch, nextSearch);
2308
+ const searchStr = this.options.stringifySearch(nextSearch);
2309
+ const hash = dest.hash === true ? currentLocation.hash : dest.hash ? functionalUpdate(dest.hash, currentLocation.hash) : void 0;
2310
+ const hashStr = hash ? `#${hash}` : "";
2311
+ let nextState = dest.state === true ? currentLocation.state : dest.state ? functionalUpdate(dest.state, currentLocation.state) : {};
2312
+ nextState = replaceEqualDeep(currentLocation.state, nextState);
2313
+ const fullPath = `${nextPathname}${searchStr}${hashStr}`;
2314
+ let href;
2315
+ let publicHref;
2316
+ let external = false;
2317
+ if (this.rewrite) {
2318
+ const url = new URL(fullPath, this.origin);
2319
+ const rewrittenUrl = executeRewriteOutput(this.rewrite, url);
2320
+ href = url.href.replace(url.origin, "");
2321
+ if (rewrittenUrl.origin !== this.origin) {
2322
+ publicHref = rewrittenUrl.href;
2323
+ external = true;
2324
+ } else publicHref = rewrittenUrl.pathname + rewrittenUrl.search + rewrittenUrl.hash;
2325
+ } else {
2326
+ href = encodePathLikeUrl(fullPath);
2327
+ publicHref = href;
2328
+ }
2329
+ return {
2330
+ publicHref,
2331
+ href,
2332
+ pathname: nextPathname,
2333
+ search: nextSearch,
2334
+ searchStr,
2335
+ state: nextState,
2336
+ hash: hash ?? "",
2337
+ external,
2338
+ unmaskOnReload: dest.unmaskOnReload
2339
+ };
2340
+ };
2341
+ const buildWithMatches = (dest = {}, maskedDest) => {
2342
+ const next = build(dest);
2343
+ let maskedNext = maskedDest ? build(maskedDest) : void 0;
2344
+ if (!maskedNext) {
2345
+ const params = /* @__PURE__ */ Object.create(null);
2346
+ if (this.options.routeMasks) {
2347
+ const match = findFlatMatch(next.pathname, this.processedTree);
2348
+ if (match) {
2349
+ Object.assign(params, match.rawParams);
2350
+ const { from: _from, params: maskParams, ...maskProps } = match.route;
2351
+ const nextParams = maskParams === false || maskParams === null ? /* @__PURE__ */ Object.create(null) : (maskParams ?? true) === true ? params : Object.assign(params, functionalUpdate(maskParams, params));
2352
+ maskedDest = {
2353
+ from: opts.from,
2354
+ ...maskProps,
2355
+ params: nextParams
2356
+ };
2357
+ maskedNext = build(maskedDest);
2358
+ }
2359
+ }
2360
+ }
2361
+ if (maskedNext) next.maskedLocation = maskedNext;
2362
+ return next;
2363
+ };
2364
+ if (opts.mask) return buildWithMatches(opts, {
2365
+ from: opts.from,
2366
+ ...opts.mask
2367
+ });
2368
+ return buildWithMatches(opts);
2369
+ };
2370
+ this.commitLocation = async ({ viewTransition, ignoreBlocker, ...next }) => {
2371
+ const isSameState = () => {
2372
+ const ignoredProps = [
2373
+ "key",
2374
+ "__TSR_key",
2375
+ "__TSR_index",
2376
+ "__hashScrollIntoViewOptions"
2377
+ ];
2378
+ ignoredProps.forEach((prop) => {
2379
+ next.state[prop] = this.latestLocation.state[prop];
2380
+ });
2381
+ const isEqual = deepEqual(next.state, this.latestLocation.state);
2382
+ ignoredProps.forEach((prop) => {
2383
+ delete next.state[prop];
2384
+ });
2385
+ return isEqual;
2386
+ };
2387
+ const isSameUrl = trimPathRight(this.latestLocation.href) === trimPathRight(next.href);
2388
+ let previousCommitPromise = this.commitLocationPromise;
2389
+ this.commitLocationPromise = createControlledPromise(() => {
2390
+ previousCommitPromise?.resolve();
2391
+ previousCommitPromise = void 0;
2392
+ });
2393
+ if (isSameUrl && isSameState()) this.load();
2394
+ else {
2395
+ let { maskedLocation, hashScrollIntoView, ...nextHistory } = next;
2396
+ if (maskedLocation) {
2397
+ nextHistory = {
2398
+ ...maskedLocation,
2399
+ state: {
2400
+ ...maskedLocation.state,
2401
+ __tempKey: void 0,
2402
+ __tempLocation: {
2403
+ ...nextHistory,
2404
+ search: nextHistory.searchStr,
2405
+ state: {
2406
+ ...nextHistory.state,
2407
+ __tempKey: void 0,
2408
+ __tempLocation: void 0,
2409
+ __TSR_key: void 0,
2410
+ key: void 0
2411
+ }
2412
+ }
2413
+ }
2414
+ };
2415
+ if (nextHistory.unmaskOnReload ?? this.options.unmaskOnReload ?? false) nextHistory.state.__tempKey = this.tempLocationKey;
2416
+ }
2417
+ nextHistory.state.__hashScrollIntoViewOptions = hashScrollIntoView ?? this.options.defaultHashScrollIntoView ?? true;
2418
+ this.shouldViewTransition = viewTransition;
2419
+ this.history[next.replace ? "replace" : "push"](nextHistory.publicHref, nextHistory.state, { ignoreBlocker });
2420
+ }
2421
+ this.resetNextScroll = next.resetScroll ?? true;
2422
+ if (!this.history.subscribers.size) this.load();
2423
+ return this.commitLocationPromise;
2424
+ };
2425
+ this.buildAndCommitLocation = ({ replace, resetScroll, hashScrollIntoView, viewTransition, ignoreBlocker, href, ...rest } = {}) => {
2426
+ if (href) {
2427
+ const currentIndex = this.history.location.state.__TSR_index;
2428
+ const parsed = parseHref(href, { __TSR_index: replace ? currentIndex : currentIndex + 1 });
2429
+ const hrefUrl = new URL(parsed.pathname, this.origin);
2430
+ rest.to = executeRewriteInput(this.rewrite, hrefUrl).pathname;
2431
+ rest.search = this.options.parseSearch(parsed.search);
2432
+ rest.hash = parsed.hash.slice(1);
2433
+ }
2434
+ const location = this.buildLocation({
2435
+ ...rest,
2436
+ _includeValidateSearch: true
2437
+ });
2438
+ this.pendingBuiltLocation = location;
2439
+ const commitPromise = this.commitLocation({
2440
+ ...location,
2441
+ viewTransition,
2442
+ replace,
2443
+ resetScroll,
2444
+ hashScrollIntoView,
2445
+ ignoreBlocker
2446
+ });
2447
+ Promise.resolve().then(() => {
2448
+ if (this.pendingBuiltLocation === location) this.pendingBuiltLocation = void 0;
2449
+ });
2450
+ return commitPromise;
2451
+ };
2452
+ this.navigate = async ({ to, reloadDocument, href, publicHref, ...rest }) => {
2453
+ let hrefIsUrl = false;
2454
+ if (href) try {
2455
+ new URL(`${href}`);
2456
+ hrefIsUrl = true;
2457
+ } catch {
2458
+ }
2459
+ if (hrefIsUrl && !reloadDocument) reloadDocument = true;
2460
+ if (reloadDocument) {
2461
+ if (to !== void 0 || !href) {
2462
+ const location = this.buildLocation({
2463
+ to,
2464
+ ...rest
2465
+ });
2466
+ href = href ?? location.publicHref;
2467
+ publicHref = publicHref ?? location.publicHref;
2468
+ }
2469
+ const reloadHref = !hrefIsUrl && publicHref ? publicHref : href;
2470
+ if (isDangerousProtocol(reloadHref, this.protocolAllowlist)) {
2471
+ return Promise.resolve();
2472
+ }
2473
+ if (!rest.ignoreBlocker) {
2474
+ const blockers = this.history.getBlockers?.() ?? [];
2475
+ for (const blocker of blockers) if (blocker?.blockerFn) {
2476
+ if (await blocker.blockerFn({
2477
+ currentLocation: this.latestLocation,
2478
+ nextLocation: this.latestLocation,
2479
+ action: "PUSH"
2480
+ })) return Promise.resolve();
2481
+ }
2482
+ }
2483
+ if (rest.replace) window.location.replace(reloadHref);
2484
+ else window.location.href = reloadHref;
2485
+ return Promise.resolve();
2486
+ }
2487
+ return this.buildAndCommitLocation({
2488
+ ...rest,
2489
+ href,
2490
+ to,
2491
+ _isNavigate: true
2492
+ });
2493
+ };
2494
+ this.beforeLoad = () => {
2495
+ this.cancelMatches();
2496
+ this.updateLatestLocation();
2497
+ {
2498
+ const nextLocation = this.buildLocation({
2499
+ to: this.latestLocation.pathname,
2500
+ search: true,
2501
+ params: true,
2502
+ hash: true,
2503
+ state: true,
2504
+ _includeValidateSearch: true
2505
+ });
2506
+ if (this.latestLocation.publicHref !== nextLocation.publicHref) {
2507
+ const href = this.getParsedLocationHref(nextLocation);
2508
+ if (nextLocation.external) throw redirect({ href });
2509
+ else throw redirect({
2510
+ href,
2511
+ _builtLocation: nextLocation
2512
+ });
2513
+ }
2514
+ }
2515
+ const pendingMatches = this.matchRoutes(this.latestLocation);
2516
+ const nextCachedMatches = this.stores.cachedMatches.get().filter((d) => !pendingMatches.some((e) => e.id === d.id));
2517
+ this.batch(() => {
2518
+ this.stores.status.set("pending");
2519
+ this.stores.statusCode.set(200);
2520
+ this.stores.isLoading.set(true);
2521
+ this.stores.location.set(this.latestLocation);
2522
+ this.stores.setPending(pendingMatches);
2523
+ this.stores.setCached(nextCachedMatches);
2524
+ });
2525
+ };
2526
+ this.load = async (opts) => {
2527
+ let redirect2;
2528
+ let notFound;
2529
+ let loadPromise;
2530
+ const previousLocation = this.stores.resolvedLocation.get() ?? this.stores.location.get();
2531
+ loadPromise = new Promise((resolve) => {
2532
+ this.startTransition(async () => {
2533
+ try {
2534
+ this.beforeLoad();
2535
+ const next = this.latestLocation;
2536
+ const locationChangeInfo = getLocationChangeInfo(next, this.stores.resolvedLocation.get());
2537
+ if (!this.stores.redirect.get()) this.emit({
2538
+ type: "onBeforeNavigate",
2539
+ ...locationChangeInfo
2540
+ });
2541
+ this.emit({
2542
+ type: "onBeforeLoad",
2543
+ ...locationChangeInfo
2544
+ });
2545
+ await loadMatches({
2546
+ router: this,
2547
+ sync: opts?.sync,
2548
+ forceStaleReload: previousLocation.href === next.href,
2549
+ matches: this.stores.pendingMatches.get(),
2550
+ location: next,
2551
+ updateMatch: this.updateMatch,
2552
+ onReady: async () => {
2553
+ this.startTransition(() => {
2554
+ this.startViewTransition(async () => {
2555
+ let exitingMatches = null;
2556
+ let hookExitingMatches = null;
2557
+ let hookEnteringMatches = null;
2558
+ let hookStayingMatches = null;
2559
+ this.batch(() => {
2560
+ const pendingMatches = this.stores.pendingMatches.get();
2561
+ const mountPending = pendingMatches.length;
2562
+ const currentMatches = this.stores.matches.get();
2563
+ exitingMatches = mountPending ? currentMatches.filter((match) => !this.stores.pendingMatchStores.has(match.id)) : null;
2564
+ const pendingRouteIds = /* @__PURE__ */ new Set();
2565
+ for (const s of this.stores.pendingMatchStores.values()) if (s.routeId) pendingRouteIds.add(s.routeId);
2566
+ const activeRouteIds = /* @__PURE__ */ new Set();
2567
+ for (const s of this.stores.matchStores.values()) if (s.routeId) activeRouteIds.add(s.routeId);
2568
+ hookExitingMatches = mountPending ? currentMatches.filter((match) => !pendingRouteIds.has(match.routeId)) : null;
2569
+ hookEnteringMatches = mountPending ? pendingMatches.filter((match) => !activeRouteIds.has(match.routeId)) : null;
2570
+ hookStayingMatches = mountPending ? pendingMatches.filter((match) => activeRouteIds.has(match.routeId)) : currentMatches;
2571
+ this.stores.isLoading.set(false);
2572
+ this.stores.loadedAt.set(Date.now());
2573
+ if (mountPending) {
2574
+ this.stores.setMatches(pendingMatches);
2575
+ this.stores.setPending([]);
2576
+ this.stores.setCached([...this.stores.cachedMatches.get(), ...exitingMatches.filter((d) => d.status !== "error" && d.status !== "notFound" && d.status !== "redirected")]);
2577
+ this.clearExpiredCache();
2578
+ }
2579
+ });
2580
+ for (const [matches, hook] of [
2581
+ [hookExitingMatches, "onLeave"],
2582
+ [hookEnteringMatches, "onEnter"],
2583
+ [hookStayingMatches, "onStay"]
2584
+ ]) {
2585
+ if (!matches) continue;
2586
+ for (const match of matches) this.looseRoutesById[match.routeId].options[hook]?.(match);
2587
+ }
2588
+ });
2589
+ });
2590
+ }
2591
+ });
2592
+ } catch (err) {
2593
+ if (isRedirect(err)) {
2594
+ redirect2 = err;
2595
+ } else if (isNotFound(err)) notFound = err;
2596
+ const nextStatusCode = redirect2 ? redirect2.status : notFound ? 404 : this.stores.matches.get().some((d) => d.status === "error") ? 500 : 200;
2597
+ this.batch(() => {
2598
+ this.stores.statusCode.set(nextStatusCode);
2599
+ this.stores.redirect.set(redirect2);
2600
+ });
2601
+ }
2602
+ if (this.latestLoadPromise === loadPromise) {
2603
+ this.commitLocationPromise?.resolve();
2604
+ this.latestLoadPromise = void 0;
2605
+ this.commitLocationPromise = void 0;
2606
+ }
2607
+ resolve();
2608
+ });
2609
+ });
2610
+ this.latestLoadPromise = loadPromise;
2611
+ await loadPromise;
2612
+ while (this.latestLoadPromise && loadPromise !== this.latestLoadPromise) await this.latestLoadPromise;
2613
+ let newStatusCode = void 0;
2614
+ if (this.hasNotFoundMatch()) newStatusCode = 404;
2615
+ else if (this.stores.matches.get().some((d) => d.status === "error")) newStatusCode = 500;
2616
+ if (newStatusCode !== void 0) this.stores.statusCode.set(newStatusCode);
2617
+ };
2618
+ this.startViewTransition = (fn) => {
2619
+ const shouldViewTransition = this.shouldViewTransition ?? this.options.defaultViewTransition;
2620
+ this.shouldViewTransition = void 0;
2621
+ if (shouldViewTransition && typeof document !== "undefined" && "startViewTransition" in document && typeof document.startViewTransition === "function") {
2622
+ let startViewTransitionParams;
2623
+ if (typeof shouldViewTransition === "object" && this.isViewTransitionTypesSupported) {
2624
+ const next = this.latestLocation;
2625
+ const prevLocation = this.stores.resolvedLocation.get();
2626
+ const resolvedViewTransitionTypes = typeof shouldViewTransition.types === "function" ? shouldViewTransition.types(getLocationChangeInfo(next, prevLocation)) : shouldViewTransition.types;
2627
+ if (resolvedViewTransitionTypes === false) {
2628
+ fn();
2629
+ return;
2630
+ }
2631
+ startViewTransitionParams = {
2632
+ update: fn,
2633
+ types: resolvedViewTransitionTypes
2634
+ };
2635
+ } else startViewTransitionParams = fn;
2636
+ document.startViewTransition(startViewTransitionParams);
2637
+ } else fn();
2638
+ };
2639
+ this.updateMatch = (id, updater) => {
2640
+ this.startTransition(() => {
2641
+ const pendingMatch = this.stores.pendingMatchStores.get(id);
2642
+ if (pendingMatch) {
2643
+ pendingMatch.set(updater);
2644
+ return;
2645
+ }
2646
+ const activeMatch = this.stores.matchStores.get(id);
2647
+ if (activeMatch) {
2648
+ activeMatch.set(updater);
2649
+ return;
2650
+ }
2651
+ const cachedMatch = this.stores.cachedMatchStores.get(id);
2652
+ if (cachedMatch) {
2653
+ const next = updater(cachedMatch.get());
2654
+ if (next.status === "redirected") {
2655
+ if (this.stores.cachedMatchStores.delete(id)) this.stores.cachedIds.set((prev) => prev.filter((matchId) => matchId !== id));
2656
+ } else cachedMatch.set(next);
2657
+ }
2658
+ });
2659
+ };
2660
+ this.getMatch = (matchId) => {
2661
+ return this.stores.cachedMatchStores.get(matchId)?.get() ?? this.stores.pendingMatchStores.get(matchId)?.get() ?? this.stores.matchStores.get(matchId)?.get();
2662
+ };
2663
+ this.invalidate = (opts) => {
2664
+ const invalidate = (d) => {
2665
+ if (opts?.filter?.(d) ?? true) return {
2666
+ ...d,
2667
+ invalid: true,
2668
+ ...opts?.forcePending || d.status === "error" || d.status === "notFound" ? {
2669
+ status: "pending",
2670
+ error: void 0
2671
+ } : void 0
2672
+ };
2673
+ return d;
2674
+ };
2675
+ this.batch(() => {
2676
+ this.stores.setMatches(this.stores.matches.get().map(invalidate));
2677
+ this.stores.setCached(this.stores.cachedMatches.get().map(invalidate));
2678
+ this.stores.setPending(this.stores.pendingMatches.get().map(invalidate));
2679
+ });
2680
+ this.shouldViewTransition = false;
2681
+ return this.load({ sync: opts?.sync });
2682
+ };
2683
+ this.getParsedLocationHref = (location) => {
2684
+ return location.publicHref || "/";
2685
+ };
2686
+ this.resolveRedirect = (redirect2) => {
2687
+ const locationHeader = redirect2.headers.get("Location");
2688
+ if (!redirect2.options.href || redirect2.options._builtLocation) {
2689
+ const location = redirect2.options._builtLocation ?? this.buildLocation(redirect2.options);
2690
+ const href = this.getParsedLocationHref(location);
2691
+ redirect2.options.href = href;
2692
+ redirect2.headers.set("Location", href);
2693
+ } else if (locationHeader) try {
2694
+ const url = new URL(locationHeader);
2695
+ if (this.origin && url.origin === this.origin) {
2696
+ const href = url.pathname + url.search + url.hash;
2697
+ redirect2.options.href = href;
2698
+ redirect2.headers.set("Location", href);
2699
+ }
2700
+ } catch {
2701
+ }
2702
+ if (redirect2.options.href && !redirect2.options._builtLocation && isDangerousProtocol(redirect2.options.href, this.protocolAllowlist)) throw new Error("Redirect blocked: unsafe protocol");
2703
+ if (!redirect2.headers.get("Location")) redirect2.headers.set("Location", redirect2.options.href);
2704
+ return redirect2;
2705
+ };
2706
+ this.clearCache = (opts) => {
2707
+ const filter = opts?.filter;
2708
+ if (filter !== void 0) this.stores.setCached(this.stores.cachedMatches.get().filter((m) => !filter(m)));
2709
+ else this.stores.setCached([]);
2710
+ };
2711
+ this.clearExpiredCache = () => {
2712
+ const now = Date.now();
2713
+ const filter = (d) => {
2714
+ const route = this.looseRoutesById[d.routeId];
2715
+ if (!route.options.loader) return true;
2716
+ const gcTime = (d.preload ? route.options.preloadGcTime ?? this.options.defaultPreloadGcTime : route.options.gcTime ?? this.options.defaultGcTime) ?? 300 * 1e3;
2717
+ if (d.status === "error") return true;
2718
+ return now - d.updatedAt >= gcTime;
2719
+ };
2720
+ this.clearCache({ filter });
2721
+ };
2722
+ this.loadRouteChunk = loadRouteChunk;
2723
+ this.preloadRoute = async (opts) => {
2724
+ const next = opts._builtLocation ?? this.buildLocation(opts);
2725
+ let matches = this.matchRoutes(next, {
2726
+ throwOnError: true,
2727
+ preload: true,
2728
+ dest: opts
2729
+ });
2730
+ const activeMatchIds = /* @__PURE__ */ new Set([...this.stores.matchesId.get(), ...this.stores.pendingIds.get()]);
2731
+ const loadedMatchIds = /* @__PURE__ */ new Set([...activeMatchIds, ...this.stores.cachedIds.get()]);
2732
+ const matchesToCache = matches.filter((match) => !loadedMatchIds.has(match.id));
2733
+ if (matchesToCache.length) {
2734
+ const cachedMatches = this.stores.cachedMatches.get();
2735
+ this.stores.setCached([...cachedMatches, ...matchesToCache]);
2736
+ }
2737
+ try {
2738
+ matches = await loadMatches({
2739
+ router: this,
2740
+ matches,
2741
+ location: next,
2742
+ preload: true,
2743
+ updateMatch: (id, updater) => {
2744
+ if (activeMatchIds.has(id)) matches = matches.map((d) => d.id === id ? updater(d) : d);
2745
+ else this.updateMatch(id, updater);
2746
+ }
2747
+ });
2748
+ return matches;
2749
+ } catch (err) {
2750
+ if (isRedirect(err)) {
2751
+ if (err.options.reloadDocument) return;
2752
+ return await this.preloadRoute({
2753
+ ...err.options,
2754
+ _fromLocation: next
2755
+ });
2756
+ }
2757
+ if (!isNotFound(err)) console.error(err);
2758
+ return;
2759
+ }
2760
+ };
2761
+ this.matchRoute = (location, opts) => {
2762
+ const matchLocation = {
2763
+ ...location,
2764
+ to: location.to ? this.resolvePathWithBase(location.from || "", location.to) : void 0,
2765
+ params: location.params || {},
2766
+ leaveParams: true
2767
+ };
2768
+ const next = this.buildLocation(matchLocation);
2769
+ if (opts?.pending && this.stores.status.get() !== "pending") return false;
2770
+ const baseLocation = (opts?.pending === void 0 ? !this.stores.isLoading.get() : opts.pending) ? this.latestLocation : this.stores.resolvedLocation.get() || this.stores.location.get();
2771
+ const match = findSingleMatch(next.pathname, opts?.caseSensitive ?? false, opts?.fuzzy ?? false, baseLocation.pathname, this.processedTree);
2772
+ if (!match) return false;
2773
+ if (location.params) {
2774
+ if (!deepEqual(match.rawParams, location.params, { partial: true })) return false;
2775
+ }
2776
+ if (opts?.includeSearch ?? true) return deepEqual(baseLocation.search, next.search, { partial: true }) ? match.rawParams : false;
2777
+ return match.rawParams;
2778
+ };
2779
+ this.hasNotFoundMatch = () => {
2780
+ return this.stores.matches.get().some((d) => d.status === "notFound" || d.globalNotFound);
2781
+ };
2782
+ this.getStoreConfig = getStoreConfig;
2783
+ this.update({
2784
+ defaultPreloadDelay: 50,
2785
+ defaultPendingMs: 1e3,
2786
+ defaultPendingMinMs: 500,
2787
+ context: void 0,
2788
+ ...options,
2789
+ caseSensitive: options.caseSensitive ?? false,
2790
+ notFoundMode: options.notFoundMode ?? "fuzzy",
2791
+ stringifySearch: options.stringifySearch ?? defaultStringifySearch,
2792
+ parseSearch: options.parseSearch ?? defaultParseSearch,
2793
+ protocolAllowlist: options.protocolAllowlist ?? DEFAULT_PROTOCOL_ALLOWLIST
2794
+ });
2795
+ if (typeof document !== "undefined") self.__TSR_ROUTER__ = this;
2796
+ }
2797
+ isShell() {
2798
+ return !!this.options.isShell;
2799
+ }
2800
+ isPrerendering() {
2801
+ return !!this.options.isPrerendering;
2802
+ }
2803
+ get state() {
2804
+ return this.stores.__store.get();
2805
+ }
2806
+ setRoutes({ routesById, routesByPath, processedTree }) {
2807
+ this.routesById = routesById;
2808
+ this.routesByPath = routesByPath;
2809
+ this.processedTree = processedTree;
2810
+ const notFoundRoute = this.options.notFoundRoute;
2811
+ if (notFoundRoute) {
2812
+ notFoundRoute.init({ originalIndex: 99999999999 });
2813
+ this.routesById[notFoundRoute.id] = notFoundRoute;
2814
+ }
2815
+ }
2816
+ getRouteBranch(route) {
2817
+ let branch = this.routeBranchCache.get(route);
2818
+ if (!branch) {
2819
+ branch = buildRouteBranch(route);
2820
+ this.routeBranchCache.set(route, branch);
2821
+ }
2822
+ return branch;
2823
+ }
2824
+ get looseRoutesById() {
2825
+ return this.routesById;
2826
+ }
2827
+ getParentContext(parentMatch) {
2828
+ return !parentMatch?.id ? this.options.context ?? void 0 : parentMatch.context ?? this.options.context ?? void 0;
2829
+ }
2830
+ matchRoutesInternal(next, opts) {
2831
+ const matchedRoutesResult = this.getMatchedRoutes(next.pathname);
2832
+ const { foundRoute, routeParams } = matchedRoutesResult;
2833
+ let { matchedRoutes } = matchedRoutesResult;
2834
+ let isGlobalNotFound = false;
2835
+ if (foundRoute ? foundRoute.path !== "/" && routeParams["**"] : trimPathRight(next.pathname)) if (this.options.notFoundRoute) matchedRoutes = [...matchedRoutes, this.options.notFoundRoute];
2836
+ else isGlobalNotFound = true;
2837
+ const globalNotFoundRouteId = isGlobalNotFound ? findGlobalNotFoundRouteId(this.options.notFoundMode, matchedRoutes) : void 0;
2838
+ const matches = new Array(matchedRoutes.length);
2839
+ const previousActiveMatchesByRouteId = /* @__PURE__ */ new Map();
2840
+ for (const store of this.stores.matchStores.values()) if (store.routeId) previousActiveMatchesByRouteId.set(store.routeId, store.get());
2841
+ for (let index = 0; index < matchedRoutes.length; index++) {
2842
+ const route = matchedRoutes[index];
2843
+ const parentMatch = matches[index - 1];
2844
+ let preMatchSearch;
2845
+ let strictMatchSearch;
2846
+ let searchError;
2847
+ {
2848
+ const parentSearch = parentMatch?.search ?? next.search;
2849
+ const parentStrictSearch = parentMatch?._strictSearch ?? void 0;
2850
+ try {
2851
+ const strictSearch = validateSearch(route.options.validateSearch, { ...parentSearch }) ?? void 0;
2852
+ preMatchSearch = {
2853
+ ...parentSearch,
2854
+ ...strictSearch
2855
+ };
2856
+ strictMatchSearch = {
2857
+ ...parentStrictSearch,
2858
+ ...strictSearch
2859
+ };
2860
+ searchError = void 0;
2861
+ } catch (err) {
2862
+ let searchParamError = err;
2863
+ if (!(err instanceof SearchParamError)) searchParamError = new SearchParamError(err.message, { cause: err });
2864
+ if (opts?.throwOnError) throw searchParamError;
2865
+ preMatchSearch = parentSearch;
2866
+ strictMatchSearch = {};
2867
+ searchError = searchParamError;
2868
+ }
2869
+ }
2870
+ const loaderDeps = route.options.loaderDeps?.({ search: preMatchSearch }) ?? "";
2871
+ const loaderDepsHash = loaderDeps ? JSON.stringify(loaderDeps) : "";
2872
+ const { interpolatedPath, usedParams } = interpolatePath({
2873
+ path: route.fullPath,
2874
+ params: routeParams,
2875
+ decoder: this.pathParamsDecoder,
2876
+ server: this.isServer
2877
+ });
2878
+ const matchId = route.id + interpolatedPath + loaderDepsHash;
2879
+ const existingMatch = this.getMatch(matchId);
2880
+ const previousMatch = previousActiveMatchesByRouteId.get(route.id);
2881
+ const strictParams = existingMatch?._strictParams ?? usedParams;
2882
+ let paramsError = void 0;
2883
+ if (!existingMatch) try {
2884
+ extractStrictParams(route, strictParams);
2885
+ } catch (err) {
2886
+ if (isNotFound(err) || isRedirect(err)) paramsError = err;
2887
+ else paramsError = new PathParamError(err.message, { cause: err });
2888
+ if (opts?.throwOnError) throw paramsError;
2889
+ }
2890
+ Object.assign(routeParams, strictParams);
2891
+ const cause = previousMatch ? "stay" : "enter";
2892
+ let match;
2893
+ if (existingMatch) match = {
2894
+ ...existingMatch,
2895
+ cause,
2896
+ params: previousMatch?.params ?? routeParams,
2897
+ _strictParams: strictParams,
2898
+ search: previousMatch ? nullReplaceEqualDeep(previousMatch.search, preMatchSearch) : nullReplaceEqualDeep(existingMatch.search, preMatchSearch),
2899
+ _strictSearch: strictMatchSearch
2900
+ };
2901
+ else {
2902
+ const status = route.options.loader || route.options.beforeLoad || route.lazyFn || routeNeedsPreload(route) ? "pending" : "success";
2903
+ match = {
2904
+ id: matchId,
2905
+ ssr: void 0,
2906
+ index,
2907
+ routeId: route.id,
2908
+ params: previousMatch?.params ?? routeParams,
2909
+ _strictParams: strictParams,
2910
+ pathname: interpolatedPath,
2911
+ updatedAt: Date.now(),
2912
+ search: previousMatch ? nullReplaceEqualDeep(previousMatch.search, preMatchSearch) : preMatchSearch,
2913
+ _strictSearch: strictMatchSearch,
2914
+ searchError: void 0,
2915
+ status,
2916
+ isFetching: false,
2917
+ error: void 0,
2918
+ paramsError,
2919
+ __routeContext: void 0,
2920
+ _nonReactive: { loadPromise: createControlledPromise() },
2921
+ __beforeLoadContext: void 0,
2922
+ context: {},
2923
+ abortController: new AbortController(),
2924
+ fetchCount: 0,
2925
+ cause,
2926
+ loaderDeps: previousMatch ? replaceEqualDeep(previousMatch.loaderDeps, loaderDeps) : loaderDeps,
2927
+ invalid: false,
2928
+ preload: false,
2929
+ links: void 0,
2930
+ scripts: void 0,
2931
+ headScripts: void 0,
2932
+ meta: void 0,
2933
+ staticData: route.options.staticData || {},
2934
+ fullPath: route.fullPath
2935
+ };
2936
+ }
2937
+ if (!opts?.preload) match.globalNotFound = globalNotFoundRouteId === route.id;
2938
+ match.searchError = searchError;
2939
+ const parentContext = this.getParentContext(parentMatch);
2940
+ match.context = {
2941
+ ...parentContext,
2942
+ ...match.__routeContext,
2943
+ ...match.__beforeLoadContext
2944
+ };
2945
+ matches[index] = match;
2946
+ }
2947
+ for (let index = 0; index < matches.length; index++) {
2948
+ const match = matches[index];
2949
+ const route = this.looseRoutesById[match.routeId];
2950
+ const existingMatch = this.getMatch(match.id);
2951
+ const previousMatch = previousActiveMatchesByRouteId.get(match.routeId);
2952
+ match.params = previousMatch ? nullReplaceEqualDeep(previousMatch.params, routeParams) : routeParams;
2953
+ if (!existingMatch) {
2954
+ const parentMatch = matches[index - 1];
2955
+ const parentContext = this.getParentContext(parentMatch);
2956
+ if (route.options.context) {
2957
+ const contextFnContext = {
2958
+ deps: match.loaderDeps,
2959
+ params: match.params,
2960
+ context: parentContext ?? {},
2961
+ location: next,
2962
+ navigate: (opts2) => this.navigate({
2963
+ ...opts2,
2964
+ _fromLocation: next
2965
+ }),
2966
+ buildLocation: this.buildLocation,
2967
+ cause: match.cause,
2968
+ abortController: match.abortController,
2969
+ preload: !!match.preload,
2970
+ matches,
2971
+ routeId: route.id
2972
+ };
2973
+ match.__routeContext = route.options.context(contextFnContext) ?? void 0;
2974
+ }
2975
+ match.context = {
2976
+ ...parentContext,
2977
+ ...match.__routeContext,
2978
+ ...match.__beforeLoadContext
2979
+ };
2980
+ }
2981
+ }
2982
+ return matches;
2983
+ }
2984
+ /**
2985
+ * Lightweight route matching for buildLocation.
2986
+ * Only computes fullPath, accumulated search, and params - skipping expensive
2987
+ * operations like AbortController, ControlledPromise, loaderDeps, and full match objects.
2988
+ */
2989
+ matchRoutesLightweight(location) {
2990
+ const { matchedRoutes, routeParams } = this.getMatchedRoutes(location.pathname);
2991
+ const lastRoute = last(matchedRoutes);
2992
+ const accumulatedSearch = { ...location.search };
2993
+ for (const route of matchedRoutes) try {
2994
+ Object.assign(accumulatedSearch, validateSearch(route.options.validateSearch, accumulatedSearch));
2995
+ } catch {
2996
+ }
2997
+ const lastStateMatchId = last(this.stores.matchesId.get());
2998
+ const lastStateMatch = lastStateMatchId && this.stores.matchStores.get(lastStateMatchId)?.get();
2999
+ const canReuseParams = lastStateMatch && lastStateMatch.routeId === lastRoute.id && lastStateMatch.pathname === location.pathname;
3000
+ let params;
3001
+ if (canReuseParams) params = lastStateMatch.params;
3002
+ else {
3003
+ const strictParams = Object.assign(/* @__PURE__ */ Object.create(null), routeParams);
3004
+ for (const route of matchedRoutes) try {
3005
+ extractStrictParams(route, strictParams);
3006
+ } catch {
3007
+ }
3008
+ params = strictParams;
3009
+ }
3010
+ return {
3011
+ matchedRoutes,
3012
+ fullPath: lastRoute.fullPath,
3013
+ search: accumulatedSearch,
3014
+ params
3015
+ };
3016
+ }
3017
+ };
3018
+ var SearchParamError = class extends Error {
3019
+ };
3020
+ var PathParamError = class extends Error {
3021
+ };
3022
+ function getInitialRouterState(location) {
3023
+ return {
3024
+ loadedAt: 0,
3025
+ isLoading: false,
3026
+ isTransitioning: false,
3027
+ status: "idle",
3028
+ resolvedLocation: void 0,
3029
+ location,
3030
+ matches: [],
3031
+ statusCode: 200
3032
+ };
3033
+ }
3034
+ function validateSearch(validateSearch2, input) {
3035
+ if (validateSearch2 == null) return {};
3036
+ if ("~standard" in validateSearch2) {
3037
+ const result = validateSearch2["~standard"].validate(input);
3038
+ if (result instanceof Promise) throw new SearchParamError("Async validation not supported");
3039
+ if (result.issues) throw new SearchParamError(JSON.stringify(result.issues, void 0, 2), { cause: result });
3040
+ return result.value;
3041
+ }
3042
+ if ("parse" in validateSearch2) return validateSearch2.parse(input);
3043
+ if (typeof validateSearch2 === "function") return validateSearch2(input);
3044
+ return {};
3045
+ }
3046
+ function getMatchedRoutes({ pathname, routesById, processedTree }) {
3047
+ const routeParams = /* @__PURE__ */ Object.create(null);
3048
+ const trimmedPath = trimPathRight(pathname);
3049
+ let foundRoute = void 0;
3050
+ const match = findRouteMatch(trimmedPath, processedTree, true);
3051
+ if (match) {
3052
+ foundRoute = match.route;
3053
+ Object.assign(routeParams, match.rawParams);
3054
+ }
3055
+ return {
3056
+ matchedRoutes: match?.branch || [routesById["__root__"]],
3057
+ routeParams,
3058
+ foundRoute
3059
+ };
3060
+ }
3061
+ function applySearchMiddleware({ search, dest, destRoutes, _includeValidateSearch }) {
3062
+ return buildMiddlewareChain(destRoutes)(search, dest, _includeValidateSearch ?? false);
3063
+ }
3064
+ function buildMiddlewareChain(destRoutes) {
3065
+ const context = {
3066
+ dest: null,
3067
+ _includeValidateSearch: false,
3068
+ middlewares: []
3069
+ };
3070
+ for (const route of destRoutes) {
3071
+ if ("search" in route.options) {
3072
+ if (route.options.search?.middlewares) context.middlewares.push(...route.options.search.middlewares);
3073
+ } else if (route.options.preSearchFilters || route.options.postSearchFilters) {
3074
+ const legacyMiddleware = ({ search, next }) => {
3075
+ let nextSearch = search;
3076
+ if ("preSearchFilters" in route.options && route.options.preSearchFilters) nextSearch = route.options.preSearchFilters.reduce((prev, next2) => next2(prev), search);
3077
+ const result = next(nextSearch);
3078
+ if ("postSearchFilters" in route.options && route.options.postSearchFilters) return route.options.postSearchFilters.reduce((prev, next2) => next2(prev), result);
3079
+ return result;
3080
+ };
3081
+ context.middlewares.push(legacyMiddleware);
3082
+ }
3083
+ if (route.options.validateSearch) {
3084
+ const validate = ({ search, next }) => {
3085
+ const result = next(search);
3086
+ if (!context._includeValidateSearch) return result;
3087
+ try {
3088
+ return {
3089
+ ...result,
3090
+ ...validateSearch(route.options.validateSearch, result) ?? void 0
3091
+ };
3092
+ } catch {
3093
+ return result;
3094
+ }
3095
+ };
3096
+ context.middlewares.push(validate);
3097
+ }
3098
+ }
3099
+ const final = ({ search }) => {
3100
+ const dest = context.dest;
3101
+ if (!dest.search) return {};
3102
+ if (dest.search === true) return search;
3103
+ return functionalUpdate(dest.search, search);
3104
+ };
3105
+ context.middlewares.push(final);
3106
+ const applyNext = (index, currentSearch, middlewares) => {
3107
+ if (index >= middlewares.length) return currentSearch;
3108
+ const middleware = middlewares[index];
3109
+ const next = (newSearch) => {
3110
+ return applyNext(index + 1, newSearch, middlewares);
3111
+ };
3112
+ return middleware({
3113
+ search: currentSearch,
3114
+ next
3115
+ });
3116
+ };
3117
+ return function middleware(search, dest, _includeValidateSearch) {
3118
+ context.dest = dest;
3119
+ context._includeValidateSearch = _includeValidateSearch;
3120
+ return applyNext(0, search, context.middlewares);
3121
+ };
3122
+ }
3123
+ function findGlobalNotFoundRouteId(notFoundMode, routes) {
3124
+ if (notFoundMode !== "root") for (let i = routes.length - 1; i >= 0; i--) {
3125
+ const route = routes[i];
3126
+ if (route.children) return route.id;
3127
+ }
3128
+ return rootRouteId;
3129
+ }
3130
+ function extractStrictParams(route, accumulatedParams) {
3131
+ const parseParams = route.options.params?.parse ?? route.options.parseParams;
3132
+ if (parseParams) {
3133
+ const result = parseParams(accumulatedParams);
3134
+ if (result === false) throw new Error("Route params.parse returned false for a matched route");
3135
+ Object.assign(accumulatedParams, result);
3136
+ }
3137
+ }
3138
+ function getAssetCrossOrigin(assetCrossOrigin, kind) {
3139
+ if (!assetCrossOrigin) return;
3140
+ if (typeof assetCrossOrigin === "string") return assetCrossOrigin;
3141
+ return assetCrossOrigin[kind];
3142
+ }
3143
+ function resolveManifestAssetLink(link) {
3144
+ if (typeof link === "string") return {
3145
+ href: link,
3146
+ crossOrigin: void 0
3147
+ };
3148
+ return link;
3149
+ }
3150
+ function getStylesheetHref(asset) {
3151
+ if (asset.tag !== "link") return void 0;
3152
+ const rel = asset.attrs?.rel;
3153
+ const href = asset.attrs?.href;
3154
+ if (typeof href !== "string") return void 0;
3155
+ if (!(typeof rel === "string" ? rel.split(/\s+/) : []).includes("stylesheet")) return void 0;
3156
+ return href;
3157
+ }
3158
+ function isInlinableStylesheet(manifest, asset) {
3159
+ const href = getStylesheetHref(asset);
3160
+ return !!href && manifest?.inlineCss?.styles[href] !== void 0;
3161
+ }
3162
+ function createInlineCssStyleAsset(css) {
3163
+ return {
3164
+ tag: "style",
3165
+ attrs: { suppressHydrationWarning: true },
3166
+ inlineCss: true,
3167
+ children: css
3168
+ };
3169
+ }
3170
+ function createInlineCssPlaceholderAsset() {
3171
+ return {
3172
+ tag: "style",
3173
+ attrs: { suppressHydrationWarning: true },
3174
+ inlineCss: true
3175
+ };
3176
+ }
3177
+ var BaseRoute = class {
3178
+ get to() {
3179
+ return this._to;
3180
+ }
3181
+ get id() {
3182
+ return this._id;
3183
+ }
3184
+ get path() {
3185
+ return this._path;
3186
+ }
3187
+ get fullPath() {
3188
+ return this._fullPath;
3189
+ }
3190
+ constructor(options) {
3191
+ this.init = (opts) => {
3192
+ this.originalIndex = opts.originalIndex;
3193
+ const options2 = this.options;
3194
+ const isRoot = !options2?.path && !options2?.id;
3195
+ this.parentRoute = this.options.getParentRoute?.();
3196
+ if (isRoot) this._path = rootRouteId;
3197
+ else if (!this.parentRoute) {
3198
+ invariant();
3199
+ }
3200
+ let path = isRoot ? rootRouteId : options2?.path;
3201
+ if (path && path !== "/") path = trimPathLeft(path);
3202
+ const customId = options2?.id || path;
3203
+ let id = isRoot ? rootRouteId : joinPaths([this.parentRoute.id === "__root__" ? "" : this.parentRoute.id, customId]);
3204
+ if (path === "__root__") path = "/";
3205
+ if (id !== "__root__") id = joinPaths(["/", id]);
3206
+ const fullPath = id === "__root__" ? "/" : joinPaths([this.parentRoute.fullPath, path]);
3207
+ this._path = path;
3208
+ this._id = id;
3209
+ this._fullPath = fullPath;
3210
+ this._to = trimPathRight(fullPath);
3211
+ };
3212
+ this.addChildren = (children) => {
3213
+ return this._addFileChildren(children);
3214
+ };
3215
+ this._addFileChildren = (children) => {
3216
+ if (Array.isArray(children)) this.children = children;
3217
+ if (typeof children === "object" && children !== null) this.children = Object.values(children);
3218
+ return this;
3219
+ };
3220
+ this._addFileTypes = () => {
3221
+ return this;
3222
+ };
3223
+ this.updateLoader = (options2) => {
3224
+ Object.assign(this.options, options2);
3225
+ return this;
3226
+ };
3227
+ this.update = (options2) => {
3228
+ Object.assign(this.options, options2);
3229
+ return this;
3230
+ };
3231
+ this.lazy = (lazyFn) => {
3232
+ this.lazyFn = lazyFn;
3233
+ return this;
3234
+ };
3235
+ this.redirect = (opts) => redirect({
3236
+ from: this.fullPath,
3237
+ ...opts
3238
+ });
3239
+ this.options = options || {};
3240
+ this.isRoot = !options?.getParentRoute;
3241
+ if (options?.id && options?.path) throw new Error(`Route cannot have both an 'id' and a 'path' option.`);
3242
+ }
3243
+ };
3244
+ var BaseRootRoute = class extends BaseRoute {
3245
+ constructor(options) {
3246
+ super(options);
3247
+ }
3248
+ };
3249
+ const GLOBAL_TSR = "$_TSR";
3250
+ const TSR_SCRIPT_BARRIER_ID = "$tsr-stream-barrier";
3251
+ function createSerializationAdapter(opts) {
3252
+ return opts;
3253
+ }
3254
+ // @__NO_SIDE_EFFECTS__
3255
+ function makeSsrSerovalPlugin(serializationAdapter, options) {
3256
+ return /* @__PURE__ */ ai({
3257
+ tag: "$TSR/t/" + serializationAdapter.key,
3258
+ test: serializationAdapter.test,
3259
+ parse: { stream(value, ctx, _data) {
3260
+ return { v: ctx.parse(serializationAdapter.toSerializable(value)) };
3261
+ } },
3262
+ serialize(node, ctx, _data) {
3263
+ options.didRun = true;
3264
+ return GLOBAL_TSR + '.t.get("' + serializationAdapter.key + '")(' + ctx.serialize(node.v) + ")";
3265
+ },
3266
+ deserialize: void 0
3267
+ });
3268
+ }
3269
+ // @__NO_SIDE_EFFECTS__
3270
+ function makeSerovalPlugin(serializationAdapter) {
3271
+ return /* @__PURE__ */ ai({
3272
+ tag: "$TSR/t/" + serializationAdapter.key,
3273
+ test: serializationAdapter.test,
3274
+ parse: {
3275
+ sync(value, ctx, _data) {
3276
+ return { v: ctx.parse(serializationAdapter.toSerializable(value)) };
3277
+ },
3278
+ async async(value, ctx, _data) {
3279
+ return { v: await ctx.parse(serializationAdapter.toSerializable(value)) };
3280
+ },
3281
+ stream(value, ctx, _data) {
3282
+ return { v: ctx.parse(serializationAdapter.toSerializable(value)) };
3283
+ }
3284
+ },
3285
+ serialize: void 0,
3286
+ deserialize(node, ctx, _data) {
3287
+ return serializationAdapter.fromSerializable(ctx.deserialize(node.v));
3288
+ }
3289
+ });
3290
+ }
3291
+ var RawStream = class {
3292
+ constructor(stream, options) {
3293
+ this.stream = stream;
3294
+ this.hint = options?.hint ?? "binary";
3295
+ }
3296
+ };
3297
+ const BufferCtor = globalThis.Buffer;
3298
+ const hasNodeBuffer = !!BufferCtor && typeof BufferCtor.from === "function";
3299
+ function uint8ArrayToBase64(bytes) {
3300
+ if (bytes.length === 0) return "";
3301
+ if (hasNodeBuffer) return BufferCtor.from(bytes).toString("base64");
3302
+ const CHUNK_SIZE = 32768;
3303
+ const chunks = [];
3304
+ for (let i = 0; i < bytes.length; i += CHUNK_SIZE) {
3305
+ const chunk = bytes.subarray(i, i + CHUNK_SIZE);
3306
+ chunks.push(String.fromCharCode.apply(null, chunk));
3307
+ }
3308
+ return btoa(chunks.join(""));
3309
+ }
3310
+ function base64ToUint8Array(base64) {
3311
+ if (base64.length === 0) return new Uint8Array(0);
3312
+ if (hasNodeBuffer) {
3313
+ const buf = BufferCtor.from(base64, "base64");
3314
+ return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
3315
+ }
3316
+ const binary = atob(base64);
3317
+ const bytes = new Uint8Array(binary.length);
3318
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
3319
+ return bytes;
3320
+ }
3321
+ const RAW_STREAM_FACTORY_BINARY = /* @__PURE__ */ Object.create(null);
3322
+ const RAW_STREAM_FACTORY_TEXT = /* @__PURE__ */ Object.create(null);
3323
+ const RAW_STREAM_FACTORY_CONSTRUCTOR_BINARY = (stream) => new ReadableStream({ start(controller) {
3324
+ stream.on({
3325
+ next(base64) {
3326
+ try {
3327
+ controller.enqueue(base64ToUint8Array(base64));
3328
+ } catch {
3329
+ }
3330
+ },
3331
+ throw(error) {
3332
+ controller.error(error);
3333
+ },
3334
+ return() {
3335
+ try {
3336
+ controller.close();
3337
+ } catch {
3338
+ }
3339
+ }
3340
+ });
3341
+ } });
3342
+ const textEncoderForFactory = new TextEncoder();
3343
+ const RAW_STREAM_FACTORY_CONSTRUCTOR_TEXT = (stream) => {
3344
+ return new ReadableStream({ start(controller) {
3345
+ stream.on({
3346
+ next(value) {
3347
+ try {
3348
+ if (typeof value === "string") controller.enqueue(textEncoderForFactory.encode(value));
3349
+ else controller.enqueue(base64ToUint8Array(value.$b64));
3350
+ } catch {
3351
+ }
3352
+ },
3353
+ throw(error) {
3354
+ controller.error(error);
3355
+ },
3356
+ return() {
3357
+ try {
3358
+ controller.close();
3359
+ } catch {
3360
+ }
3361
+ }
3362
+ });
3363
+ } });
3364
+ };
3365
+ const FACTORY_BINARY = `(s=>new ReadableStream({start(c){s.on({next(b){try{const d=atob(b),a=new Uint8Array(d.length);for(let i=0;i<d.length;i++)a[i]=d.charCodeAt(i);c.enqueue(a)}catch(_){}},throw(e){c.error(e)},return(){try{c.close()}catch(_){}}})}}))`;
3366
+ const FACTORY_TEXT = `(s=>{const e=new TextEncoder();return new ReadableStream({start(c){s.on({next(v){try{if(typeof v==='string'){c.enqueue(e.encode(v))}else{const d=atob(v.$b64),a=new Uint8Array(d.length);for(let i=0;i<d.length;i++)a[i]=d.charCodeAt(i);c.enqueue(a)}}catch(_){}},throw(x){c.error(x)},return(){try{c.close()}catch(_){}}})}})})`;
3367
+ function toBinaryStream(readable) {
3368
+ const stream = re();
3369
+ const reader = readable.getReader();
3370
+ (async () => {
3371
+ try {
3372
+ while (true) {
3373
+ const { done, value } = await reader.read();
3374
+ if (done) {
3375
+ stream.return(void 0);
3376
+ break;
3377
+ }
3378
+ stream.next(uint8ArrayToBase64(value));
3379
+ }
3380
+ } catch (error) {
3381
+ stream.throw(error);
3382
+ } finally {
3383
+ reader.releaseLock();
3384
+ }
3385
+ })();
3386
+ return stream;
3387
+ }
3388
+ function toTextStream(readable) {
3389
+ const stream = re();
3390
+ const reader = readable.getReader();
3391
+ const decoder = new TextDecoder("utf-8", { fatal: true });
3392
+ (async () => {
3393
+ try {
3394
+ while (true) {
3395
+ const { done, value } = await reader.read();
3396
+ if (done) {
3397
+ try {
3398
+ const remaining = decoder.decode();
3399
+ if (remaining.length > 0) stream.next(remaining);
3400
+ } catch {
3401
+ }
3402
+ stream.return(void 0);
3403
+ break;
3404
+ }
3405
+ try {
3406
+ const text = decoder.decode(value, { stream: true });
3407
+ if (text.length > 0) stream.next(text);
3408
+ } catch {
3409
+ stream.next({ $b64: uint8ArrayToBase64(value) });
3410
+ }
3411
+ }
3412
+ } catch (error) {
3413
+ stream.throw(error);
3414
+ } finally {
3415
+ reader.releaseLock();
3416
+ }
3417
+ })();
3418
+ return stream;
3419
+ }
3420
+ const RawStreamSSRPlugin = /* @__PURE__ */ ai({
3421
+ tag: "tss/RawStream",
3422
+ extends: [/* @__PURE__ */ ai({
3423
+ tag: "tss/RawStreamFactory",
3424
+ test(value) {
3425
+ return value === RAW_STREAM_FACTORY_BINARY;
3426
+ },
3427
+ parse: {
3428
+ sync(_value, _ctx, _data) {
3429
+ return {};
3430
+ },
3431
+ async async(_value, _ctx, _data) {
3432
+ return {};
3433
+ },
3434
+ stream(_value, _ctx, _data) {
3435
+ return {};
3436
+ }
3437
+ },
3438
+ serialize(_node, _ctx, _data) {
3439
+ return FACTORY_BINARY;
3440
+ },
3441
+ deserialize(_node, _ctx, _data) {
3442
+ return RAW_STREAM_FACTORY_BINARY;
3443
+ }
3444
+ }), /* @__PURE__ */ ai({
3445
+ tag: "tss/RawStreamFactoryText",
3446
+ test(value) {
3447
+ return value === RAW_STREAM_FACTORY_TEXT;
3448
+ },
3449
+ parse: {
3450
+ sync(_value, _ctx, _data) {
3451
+ return {};
3452
+ },
3453
+ async async(_value, _ctx, _data) {
3454
+ return {};
3455
+ },
3456
+ stream(_value, _ctx, _data) {
3457
+ return {};
3458
+ }
3459
+ },
3460
+ serialize(_node, _ctx, _data) {
3461
+ return FACTORY_TEXT;
3462
+ },
3463
+ deserialize(_node, _ctx, _data) {
3464
+ return RAW_STREAM_FACTORY_TEXT;
3465
+ }
3466
+ })],
3467
+ test(value) {
3468
+ return value instanceof RawStream;
3469
+ },
3470
+ parse: {
3471
+ sync(value, ctx, _data) {
3472
+ const factory = value.hint === "text" ? RAW_STREAM_FACTORY_TEXT : RAW_STREAM_FACTORY_BINARY;
3473
+ return {
3474
+ hint: ctx.parse(value.hint),
3475
+ factory: ctx.parse(factory),
3476
+ stream: ctx.parse(re())
3477
+ };
3478
+ },
3479
+ async async(value, ctx, _data) {
3480
+ const factory = value.hint === "text" ? RAW_STREAM_FACTORY_TEXT : RAW_STREAM_FACTORY_BINARY;
3481
+ const encodedStream = value.hint === "text" ? toTextStream(value.stream) : toBinaryStream(value.stream);
3482
+ return {
3483
+ hint: await ctx.parse(value.hint),
3484
+ factory: await ctx.parse(factory),
3485
+ stream: await ctx.parse(encodedStream)
3486
+ };
3487
+ },
3488
+ stream(value, ctx, _data) {
3489
+ const factory = value.hint === "text" ? RAW_STREAM_FACTORY_TEXT : RAW_STREAM_FACTORY_BINARY;
3490
+ const encodedStream = value.hint === "text" ? toTextStream(value.stream) : toBinaryStream(value.stream);
3491
+ return {
3492
+ hint: ctx.parse(value.hint),
3493
+ factory: ctx.parse(factory),
3494
+ stream: ctx.parse(encodedStream)
3495
+ };
3496
+ }
3497
+ },
3498
+ serialize(node, ctx, _data) {
3499
+ return "(" + ctx.serialize(node.factory) + ")(" + ctx.serialize(node.stream) + ")";
3500
+ },
3501
+ deserialize(node, ctx, _data) {
3502
+ const stream = ctx.deserialize(node.stream);
3503
+ return ctx.deserialize(node.hint) === "text" ? RAW_STREAM_FACTORY_CONSTRUCTOR_TEXT(stream) : RAW_STREAM_FACTORY_CONSTRUCTOR_BINARY(stream);
3504
+ }
3505
+ });
3506
+ // @__NO_SIDE_EFFECTS__
3507
+ function createRawStreamRPCPlugin(onRawStream) {
3508
+ let nextStreamId = 1;
3509
+ return /* @__PURE__ */ ai({
3510
+ tag: "tss/RawStream",
3511
+ test(value) {
3512
+ return value instanceof RawStream;
3513
+ },
3514
+ parse: {
3515
+ async async(value, ctx, _data) {
3516
+ const streamId = nextStreamId++;
3517
+ onRawStream(streamId, value.stream);
3518
+ return { streamId: await ctx.parse(streamId) };
3519
+ },
3520
+ stream(value, ctx, _data) {
3521
+ const streamId = nextStreamId++;
3522
+ onRawStream(streamId, value.stream);
3523
+ return { streamId: ctx.parse(streamId) };
3524
+ }
3525
+ },
3526
+ serialize() {
3527
+ throw new Error("RawStreamRPCPlugin.serialize should not be called. RPC uses JSON serialization, not JS code generation.");
3528
+ },
3529
+ deserialize() {
3530
+ throw new Error("RawStreamRPCPlugin.deserialize should not be called. Use createRawStreamDeserializePlugin on client.");
3531
+ }
3532
+ });
3533
+ }
3534
+ const ShallowErrorPlugin = /* @__PURE__ */ ai({
3535
+ tag: "$TSR/Error",
3536
+ test(value) {
3537
+ return value instanceof Error;
3538
+ },
3539
+ parse: {
3540
+ sync(value, ctx) {
3541
+ return { message: ctx.parse(value.message) };
3542
+ },
3543
+ async async(value, ctx) {
3544
+ return { message: await ctx.parse(value.message) };
3545
+ },
3546
+ stream(value, ctx) {
3547
+ return { message: ctx.parse(value.message) };
3548
+ }
3549
+ },
3550
+ serialize(node, ctx) {
3551
+ return "new Error(" + ctx.serialize(node.message) + ")";
3552
+ },
3553
+ deserialize(node, ctx) {
3554
+ return new Error(ctx.deserialize(node.message));
3555
+ }
3556
+ });
3557
+ const defaultSerovalPlugins = [
3558
+ ShallowErrorPlugin,
3559
+ RawStreamSSRPlugin,
3560
+ p
3561
+ ];
3562
+ function toHeadersInstance(init) {
3563
+ if (init instanceof Headers) return init;
3564
+ else if (Array.isArray(init)) return new Headers(init);
3565
+ else if (typeof init === "object") return new Headers(init);
3566
+ else return null;
3567
+ }
3568
+ function mergeHeaders(...headers) {
3569
+ return headers.reduce((acc, header) => {
3570
+ const headersInstance = toHeadersInstance(header);
3571
+ if (!headersInstance) return acc;
3572
+ for (const [key, value] of headersInstance.entries()) if (key === "set-cookie") splitSetCookieString(value).forEach((cookie) => acc.append("set-cookie", cookie));
3573
+ else acc.set(key, value);
3574
+ return acc;
3575
+ }, new Headers());
3576
+ }
3577
+ function dehydrateSsrMatchId(id) {
3578
+ return id.replaceAll("/", "\0");
3579
+ }
3580
+ var tsrScript_default = "self.$_TSR={h(){this.hydrated=!0,this.c()},e(){this.streamEnded=!0,this.c()},c(){this.hydrated&&this.streamEnded&&(delete self.$_TSR,delete self.$R.tsr)},p(e){this.initialized?e():this.buffer.push(e)},buffer:[]}";
3581
+ const SCOPE_ID = "tsr";
3582
+ const TSR_PREFIX = GLOBAL_TSR + ".router=";
3583
+ const P_PREFIX = GLOBAL_TSR + ".p(()=>";
3584
+ const P_SUFFIX = ")";
3585
+ function dehydrateMatch(match) {
3586
+ const dehydratedMatch = {
3587
+ i: dehydrateSsrMatchId(match.id),
3588
+ u: match.updatedAt,
3589
+ s: match.status
3590
+ };
3591
+ for (const [key, shorthand] of [
3592
+ ["__beforeLoadContext", "b"],
3593
+ ["loaderData", "l"],
3594
+ ["error", "e"],
3595
+ ["ssr", "ssr"]
3596
+ ]) if (match[key] !== void 0) dehydratedMatch[shorthand] = match[key];
3597
+ if (match.globalNotFound) dehydratedMatch.g = true;
3598
+ return dehydratedMatch;
3599
+ }
3600
+ const INITIAL_SCRIPTS = [dn(SCOPE_ID), tsrScript_default];
3601
+ var ScriptBuffer = class {
3602
+ constructor(router) {
3603
+ this._scriptBarrierLifted = false;
3604
+ this._cleanedUp = false;
3605
+ this._pendingMicrotask = false;
3606
+ this.router = router;
3607
+ this._queue = INITIAL_SCRIPTS.slice();
3608
+ }
3609
+ enqueue(script) {
3610
+ if (this._cleanedUp) return;
3611
+ this._queue.push(script);
3612
+ if (this._scriptBarrierLifted && !this._pendingMicrotask) {
3613
+ this._pendingMicrotask = true;
3614
+ queueMicrotask(() => {
3615
+ this._pendingMicrotask = false;
3616
+ this.injectBufferedScripts();
3617
+ });
3618
+ }
3619
+ }
3620
+ liftBarrier() {
3621
+ if (this._scriptBarrierLifted || this._cleanedUp) return;
3622
+ this._scriptBarrierLifted = true;
3623
+ if (this._queue.length > 0 && !this._pendingMicrotask) {
3624
+ this._pendingMicrotask = true;
3625
+ queueMicrotask(() => {
3626
+ this._pendingMicrotask = false;
3627
+ this.injectBufferedScripts();
3628
+ });
3629
+ }
3630
+ }
3631
+ /**
3632
+ * Flushes any pending scripts synchronously.
3633
+ * Call this before emitting onSerializationFinished to ensure all scripts are injected.
3634
+ *
3635
+ * IMPORTANT: Only injects if the barrier has been lifted. Before the barrier is lifted,
3636
+ * scripts should remain in the queue so takeBufferedScripts() can retrieve them
3637
+ */
3638
+ flush() {
3639
+ if (!this._scriptBarrierLifted) return;
3640
+ if (this._cleanedUp) return;
3641
+ this._pendingMicrotask = false;
3642
+ const scriptsToInject = this.takeAll();
3643
+ if (scriptsToInject && this.router?.serverSsr) this.router.serverSsr.injectScript(scriptsToInject);
3644
+ }
3645
+ takeAll() {
3646
+ const bufferedScripts = this._queue;
3647
+ this._queue = [];
3648
+ if (bufferedScripts.length === 0) return;
3649
+ if (bufferedScripts.length === 1) return bufferedScripts[0] + ";document.currentScript.remove()";
3650
+ return bufferedScripts.join(";") + ";document.currentScript.remove()";
3651
+ }
3652
+ injectBufferedScripts() {
3653
+ if (this._cleanedUp) return;
3654
+ if (this._queue.length === 0) return;
3655
+ const scriptsToInject = this.takeAll();
3656
+ if (scriptsToInject && this.router?.serverSsr) this.router.serverSsr.injectScript(scriptsToInject);
3657
+ }
3658
+ cleanup() {
3659
+ this._cleanedUp = true;
3660
+ this._queue = [];
3661
+ this.router = void 0;
3662
+ }
3663
+ };
3664
+ const MANIFEST_CACHE_SIZE = 100;
3665
+ const manifestCaches = /* @__PURE__ */ new WeakMap();
3666
+ const inlineCssCaches = /* @__PURE__ */ new WeakMap();
3667
+ function getManifestCache(manifest) {
3668
+ const cache = manifestCaches.get(manifest);
3669
+ if (cache) return cache;
3670
+ const newCache = createLRUCache(MANIFEST_CACHE_SIZE);
3671
+ manifestCaches.set(manifest, newCache);
3672
+ return newCache;
3673
+ }
3674
+ function getInlineCssCache(manifest) {
3675
+ const cache = inlineCssCaches.get(manifest);
3676
+ if (cache) return cache;
3677
+ const newCache = createLRUCache(MANIFEST_CACHE_SIZE);
3678
+ inlineCssCaches.set(manifest, newCache);
3679
+ return newCache;
3680
+ }
3681
+ function getInlineCssHrefsForMatches(manifest, matches) {
3682
+ const styles = manifest?.inlineCss?.styles;
3683
+ if (!styles) return [];
3684
+ const seen = /* @__PURE__ */ new Set();
3685
+ const hrefs = [];
3686
+ for (const match of matches) {
3687
+ const assets = manifest?.routes[match.routeId]?.assets ?? [];
3688
+ for (const asset of assets) {
3689
+ const href = getStylesheetHref(asset);
3690
+ if (!href || seen.has(href) || styles[href] === void 0) continue;
3691
+ seen.add(href);
3692
+ hrefs.push(href);
3693
+ }
3694
+ }
3695
+ return hrefs;
3696
+ }
3697
+ function getInlineCssForHrefs(manifest, hrefs) {
3698
+ const styles = manifest.inlineCss?.styles;
3699
+ if (!styles || hrefs.length === 0) return void 0;
3700
+ const cacheKey = hrefs.join("\0");
3701
+ {
3702
+ const cached = getInlineCssCache(manifest).get(cacheKey);
3703
+ if (cached !== void 0) return cached;
3704
+ }
3705
+ const css = hrefs.map((href) => styles[href]).join("");
3706
+ getInlineCssCache(manifest).set(cacheKey, css);
3707
+ return css;
3708
+ }
3709
+ function getInlineCssAssetForMatches(manifest, matches) {
3710
+ if (!manifest?.inlineCss) return void 0;
3711
+ const css = getInlineCssForHrefs(manifest, getInlineCssHrefsForMatches(manifest, matches));
3712
+ return css === void 0 ? void 0 : createInlineCssStyleAsset(css);
3713
+ }
3714
+ function stripInlinedStylesheetAssets(manifest, routes, matches) {
3715
+ if (!manifest.inlineCss) return routes;
3716
+ const nextRoutes = {};
3717
+ for (const [routeId, route] of Object.entries(routes)) {
3718
+ const assets = route.assets?.filter((asset) => !isInlinableStylesheet(manifest, asset));
3719
+ const nextRoute = { ...route };
3720
+ if (assets) if (assets.length > 0) nextRoute.assets = assets;
3721
+ else delete nextRoute.assets;
3722
+ nextRoutes[routeId] = nextRoute;
3723
+ }
3724
+ if (getInlineCssAssetForMatches(manifest, matches)) {
3725
+ const rootRoute = nextRoutes["__root__"] ?? {};
3726
+ nextRoutes[rootRouteId] = {
3727
+ ...rootRoute,
3728
+ assets: [createInlineCssPlaceholderAsset(), ...rootRoute.assets ?? []]
3729
+ };
3730
+ }
3731
+ return nextRoutes;
3732
+ }
3733
+ function attachRouterServerSsrUtils({ router, manifest, getRequestAssets, includeUnmatchedRouteAssets = true }) {
3734
+ router.ssr = { get manifest() {
3735
+ const requestAssets = getRequestAssets?.();
3736
+ const inlineCssAsset = getInlineCssAssetForMatches(manifest, router.stores.matches.get());
3737
+ if (!requestAssets?.length && !inlineCssAsset) return manifest;
3738
+ return {
3739
+ ...manifest,
3740
+ routes: {
3741
+ ...manifest?.routes,
3742
+ [rootRouteId]: {
3743
+ ...manifest?.routes?.[rootRouteId],
3744
+ assets: [
3745
+ ...requestAssets ?? [],
3746
+ ...inlineCssAsset ? [inlineCssAsset] : [],
3747
+ ...manifest?.routes?.["__root__"]?.assets ?? []
3748
+ ]
3749
+ }
3750
+ }
3751
+ };
3752
+ } };
3753
+ let _dehydrated = false;
3754
+ let _serializationFinished = false;
3755
+ const renderFinishedListeners = [];
3756
+ const serializationFinishedListeners = [];
3757
+ const scriptBuffer = new ScriptBuffer(router);
3758
+ let injectedHtmlBuffer = "";
3759
+ router.serverSsr = {
3760
+ injectHtml: (html) => {
3761
+ if (!html) return;
3762
+ injectedHtmlBuffer += html;
3763
+ router.emit({ type: "onInjectedHtml" });
3764
+ },
3765
+ injectScript: (script) => {
3766
+ if (!script) return;
3767
+ const html = `<script${router.options.ssr?.nonce ? ` nonce='${router.options.ssr.nonce}'` : ""}>${script}<\/script>`;
3768
+ router.serverSsr.injectHtml(html);
3769
+ },
3770
+ dehydrate: async (opts) => {
3771
+ if (_dehydrated) {
3772
+ invariant();
3773
+ }
3774
+ let matchesToDehydrate = router.stores.matches.get();
3775
+ if (router.isShell()) matchesToDehydrate = matchesToDehydrate.slice(0, 1);
3776
+ const matches = matchesToDehydrate.map(dehydrateMatch);
3777
+ let manifestToDehydrate = void 0;
3778
+ if (manifest) {
3779
+ const currentRouteIdsList = matchesToDehydrate.map((m) => m.routeId);
3780
+ const manifestCacheKey = `${currentRouteIdsList.join("\0")}\0includeUnmatchedRouteAssets=${includeUnmatchedRouteAssets}`;
3781
+ let filteredRoutes;
3782
+ filteredRoutes = getManifestCache(manifest).get(manifestCacheKey);
3783
+ if (!filteredRoutes) {
3784
+ const currentRouteIds = new Set(currentRouteIdsList);
3785
+ const nextFilteredRoutes = {};
3786
+ for (const routeId in manifest.routes) {
3787
+ const routeManifest = manifest.routes[routeId];
3788
+ if (currentRouteIds.has(routeId)) nextFilteredRoutes[routeId] = routeManifest;
3789
+ else if (includeUnmatchedRouteAssets && routeManifest.assets && routeManifest.assets.length > 0) nextFilteredRoutes[routeId] = { assets: routeManifest.assets };
3790
+ }
3791
+ filteredRoutes = stripInlinedStylesheetAssets(manifest, nextFilteredRoutes, matchesToDehydrate);
3792
+ getManifestCache(manifest).set(manifestCacheKey, filteredRoutes);
3793
+ }
3794
+ manifestToDehydrate = { routes: { ...filteredRoutes } };
3795
+ if (opts?.requestAssets?.length) {
3796
+ const existingRoot = manifestToDehydrate.routes[rootRouteId];
3797
+ manifestToDehydrate.routes[rootRouteId] = {
3798
+ ...existingRoot,
3799
+ assets: [...opts.requestAssets, ...existingRoot?.assets ?? []]
3800
+ };
3801
+ }
3802
+ }
3803
+ const dehydratedRouter = {
3804
+ manifest: manifestToDehydrate,
3805
+ matches
3806
+ };
3807
+ const lastMatchId = matchesToDehydrate[matchesToDehydrate.length - 1]?.id;
3808
+ if (lastMatchId) dehydratedRouter.lastMatchId = dehydrateSsrMatchId(lastMatchId);
3809
+ const dehydratedData = await router.options.dehydrate?.();
3810
+ if (dehydratedData) dehydratedRouter.dehydratedData = dehydratedData;
3811
+ _dehydrated = true;
3812
+ const trackPlugins = { didRun: false };
3813
+ const serializationAdapters = router.options.serializationAdapters;
3814
+ const plugins = serializationAdapters ? serializationAdapters.map((t) => /* @__PURE__ */ makeSsrSerovalPlugin(t, trackPlugins)).concat(defaultSerovalPlugins) : defaultSerovalPlugins;
3815
+ const signalSerializationComplete = () => {
3816
+ _serializationFinished = true;
3817
+ try {
3818
+ serializationFinishedListeners.forEach((l) => l());
3819
+ router.emit({ type: "onSerializationFinished" });
3820
+ } catch (err) {
3821
+ console.error("Serialization listener error:", err);
3822
+ } finally {
3823
+ serializationFinishedListeners.length = 0;
3824
+ renderFinishedListeners.length = 0;
3825
+ }
3826
+ };
3827
+ Sn(dehydratedRouter, {
3828
+ refs: /* @__PURE__ */ new Map(),
3829
+ plugins,
3830
+ onSerialize: (data, initial) => {
3831
+ let serialized = initial ? TSR_PREFIX + data : data;
3832
+ if (trackPlugins.didRun) serialized = P_PREFIX + serialized + P_SUFFIX;
3833
+ scriptBuffer.enqueue(serialized);
3834
+ },
3835
+ onError: (err) => {
3836
+ console.error("Serialization error:", err);
3837
+ if (err && err.stack) console.error(err.stack);
3838
+ signalSerializationComplete();
3839
+ },
3840
+ scopeId: SCOPE_ID,
3841
+ onDone: () => {
3842
+ scriptBuffer.enqueue(GLOBAL_TSR + ".e()");
3843
+ scriptBuffer.flush();
3844
+ signalSerializationComplete();
3845
+ }
3846
+ });
3847
+ },
3848
+ isDehydrated() {
3849
+ return _dehydrated;
3850
+ },
3851
+ isSerializationFinished() {
3852
+ return _serializationFinished;
3853
+ },
3854
+ onRenderFinished: (listener) => renderFinishedListeners.push(listener),
3855
+ onSerializationFinished: (listener) => serializationFinishedListeners.push(listener),
3856
+ setRenderFinished: () => {
3857
+ try {
3858
+ renderFinishedListeners.forEach((l) => l());
3859
+ } catch (err) {
3860
+ console.error("Error in render finished listener:", err);
3861
+ } finally {
3862
+ renderFinishedListeners.length = 0;
3863
+ }
3864
+ scriptBuffer.liftBarrier();
3865
+ },
3866
+ takeBufferedScripts() {
3867
+ const scripts = scriptBuffer.takeAll();
3868
+ return {
3869
+ tag: "script",
3870
+ attrs: {
3871
+ nonce: router.options.ssr?.nonce,
3872
+ className: "$tsr",
3873
+ id: TSR_SCRIPT_BARRIER_ID
3874
+ },
3875
+ children: scripts
3876
+ };
3877
+ },
3878
+ liftScriptBarrier() {
3879
+ scriptBuffer.liftBarrier();
3880
+ },
3881
+ takeBufferedHtml() {
3882
+ if (!injectedHtmlBuffer) return;
3883
+ const buffered = injectedHtmlBuffer;
3884
+ injectedHtmlBuffer = "";
3885
+ return buffered;
3886
+ },
3887
+ cleanup() {
3888
+ if (!router.serverSsr) return;
3889
+ renderFinishedListeners.length = 0;
3890
+ serializationFinishedListeners.length = 0;
3891
+ injectedHtmlBuffer = "";
3892
+ scriptBuffer.cleanup();
3893
+ router.serverSsr = void 0;
3894
+ }
3895
+ };
3896
+ }
3897
+ function getOrigin(request) {
3898
+ try {
3899
+ return new URL(request.url).origin;
3900
+ } catch {
3901
+ }
3902
+ return "http://localhost";
3903
+ }
3904
+ function getNormalizedURL(url, base) {
3905
+ if (typeof url === "string") url = url.replace("\\", "%5C");
3906
+ const rawUrl = new URL(url, base);
3907
+ const { path: decodedPathname, handledProtocolRelativeURL } = decodePath(rawUrl.pathname);
3908
+ const searchParams = new URLSearchParams(rawUrl.search);
3909
+ const normalizedHref = decodedPathname + (searchParams.size > 0 ? "?" : "") + searchParams.toString() + rawUrl.hash;
3910
+ return {
3911
+ url: new URL(normalizedHref, rawUrl.origin),
3912
+ handledProtocolRelativeURL
3913
+ };
3914
+ }
3915
+ function defineHandlerCallback(handler) {
3916
+ return handler;
3917
+ }
3918
+ function transformReadableStreamWithRouter(router, routerStream) {
3919
+ return transformStreamWithRouter(router, routerStream);
3920
+ }
3921
+ function transformPipeableStreamWithRouter(router, routerStream) {
3922
+ return Readable.fromWeb(transformStreamWithRouter(router, Readable.toWeb(routerStream)));
3923
+ }
3924
+ const BODY_END_TAG = "</body>";
3925
+ const HTML_END_TAG = "</html>";
3926
+ const MIN_CLOSING_TAG_LENGTH = 4;
3927
+ const DEFAULT_SERIALIZATION_TIMEOUT_MS = 6e4;
3928
+ const DEFAULT_LIFETIME_TIMEOUT_MS = 6e4;
3929
+ const textEncoder = new TextEncoder();
3930
+ function findLastClosingTagEnd(str) {
3931
+ const len = str.length;
3932
+ if (len < MIN_CLOSING_TAG_LENGTH) return -1;
3933
+ let i = len - 1;
3934
+ while (i >= MIN_CLOSING_TAG_LENGTH - 1) {
3935
+ if (str.charCodeAt(i) === 62) {
3936
+ let j = i - 1;
3937
+ while (j >= 1) {
3938
+ const code = str.charCodeAt(j);
3939
+ if (code >= 97 && code <= 122 || code >= 65 && code <= 90 || code >= 48 && code <= 57 || code === 95 || code === 58 || code === 46 || code === 45) j--;
3940
+ else break;
3941
+ }
3942
+ const tagNameStart = j + 1;
3943
+ if (tagNameStart < i) {
3944
+ const startCode = str.charCodeAt(tagNameStart);
3945
+ if (startCode >= 97 && startCode <= 122 || startCode >= 65 && startCode <= 90) {
3946
+ if (j >= 1 && str.charCodeAt(j) === 47 && str.charCodeAt(j - 1) === 60) return i + 1;
3947
+ }
3948
+ }
3949
+ }
3950
+ i--;
3951
+ }
3952
+ return -1;
3953
+ }
3954
+ function transformStreamWithRouter(router, appStream, opts) {
3955
+ const serializationAlreadyFinished = router.serverSsr?.isSerializationFinished() ?? false;
3956
+ const initialBufferedHtml = router.serverSsr?.takeBufferedHtml();
3957
+ if (serializationAlreadyFinished && !initialBufferedHtml) {
3958
+ let cleanedUp2 = false;
3959
+ let controller2;
3960
+ let isStreamClosed2 = false;
3961
+ let lifetimeTimeoutHandle2;
3962
+ const cleanup2 = () => {
3963
+ if (cleanedUp2) return;
3964
+ cleanedUp2 = true;
3965
+ if (lifetimeTimeoutHandle2 !== void 0) {
3966
+ clearTimeout(lifetimeTimeoutHandle2);
3967
+ lifetimeTimeoutHandle2 = void 0;
3968
+ }
3969
+ router.serverSsr?.cleanup();
3970
+ };
3971
+ const safeClose2 = () => {
3972
+ if (isStreamClosed2) return;
3973
+ isStreamClosed2 = true;
3974
+ try {
3975
+ controller2?.close();
3976
+ } catch {
3977
+ }
3978
+ };
3979
+ const safeError2 = (error) => {
3980
+ if (isStreamClosed2) return;
3981
+ isStreamClosed2 = true;
3982
+ try {
3983
+ controller2?.error(error);
3984
+ } catch {
3985
+ }
3986
+ };
3987
+ const lifetimeMs2 = DEFAULT_LIFETIME_TIMEOUT_MS;
3988
+ lifetimeTimeoutHandle2 = setTimeout(() => {
3989
+ if (!cleanedUp2 && !isStreamClosed2) {
3990
+ console.warn(`SSR stream transform exceeded maximum lifetime (${lifetimeMs2}ms), forcing cleanup`);
3991
+ safeError2(/* @__PURE__ */ new Error("Stream lifetime exceeded"));
3992
+ cleanup2();
3993
+ }
3994
+ }, lifetimeMs2);
3995
+ const stream2 = new ReadableStream$1({
3996
+ start(c) {
3997
+ controller2 = c;
3998
+ },
3999
+ cancel() {
4000
+ isStreamClosed2 = true;
4001
+ cleanup2();
4002
+ }
4003
+ });
4004
+ (async () => {
4005
+ const reader = appStream.getReader();
4006
+ try {
4007
+ while (true) {
4008
+ const { done, value } = await reader.read();
4009
+ if (done) break;
4010
+ if (cleanedUp2 || isStreamClosed2) return;
4011
+ controller2?.enqueue(value);
4012
+ }
4013
+ if (cleanedUp2 || isStreamClosed2) return;
4014
+ router.serverSsr?.setRenderFinished();
4015
+ safeClose2();
4016
+ cleanup2();
4017
+ } catch (error) {
4018
+ if (cleanedUp2) return;
4019
+ console.error("Error reading appStream:", error);
4020
+ router.serverSsr?.setRenderFinished();
4021
+ safeError2(error);
4022
+ cleanup2();
4023
+ } finally {
4024
+ reader.releaseLock();
4025
+ }
4026
+ })().catch((error) => {
4027
+ if (cleanedUp2) return;
4028
+ console.error("Error in stream transform:", error);
4029
+ safeError2(error);
4030
+ cleanup2();
4031
+ });
4032
+ return stream2;
4033
+ }
4034
+ let stopListeningToInjectedHtml;
4035
+ let stopListeningToSerializationFinished;
4036
+ let serializationTimeoutHandle;
4037
+ let lifetimeTimeoutHandle;
4038
+ let cleanedUp = false;
4039
+ let controller;
4040
+ let isStreamClosed = false;
4041
+ const textDecoder = new TextDecoder();
4042
+ let pendingRouterHtml = initialBufferedHtml ?? "";
4043
+ let leftover = "";
4044
+ let pendingClosingTags = "";
4045
+ const MAX_LEFTOVER_CHARS = 2048;
4046
+ let isAppRendering = true;
4047
+ let streamBarrierLifted = false;
4048
+ let serializationFinished = serializationAlreadyFinished;
4049
+ function safeEnqueue(chunk) {
4050
+ if (isStreamClosed) return;
4051
+ if (typeof chunk === "string") controller.enqueue(textEncoder.encode(chunk));
4052
+ else controller.enqueue(chunk);
4053
+ }
4054
+ function safeClose() {
4055
+ if (isStreamClosed) return;
4056
+ isStreamClosed = true;
4057
+ try {
4058
+ controller.close();
4059
+ } catch {
4060
+ }
4061
+ }
4062
+ function safeError(error) {
4063
+ if (isStreamClosed) return;
4064
+ isStreamClosed = true;
4065
+ try {
4066
+ controller.error(error);
4067
+ } catch {
4068
+ }
4069
+ }
4070
+ function cleanup() {
4071
+ if (cleanedUp) return;
4072
+ cleanedUp = true;
4073
+ try {
4074
+ stopListeningToInjectedHtml?.();
4075
+ stopListeningToSerializationFinished?.();
4076
+ } catch {
4077
+ }
4078
+ stopListeningToInjectedHtml = void 0;
4079
+ stopListeningToSerializationFinished = void 0;
4080
+ if (serializationTimeoutHandle !== void 0) {
4081
+ clearTimeout(serializationTimeoutHandle);
4082
+ serializationTimeoutHandle = void 0;
4083
+ }
4084
+ if (lifetimeTimeoutHandle !== void 0) {
4085
+ clearTimeout(lifetimeTimeoutHandle);
4086
+ lifetimeTimeoutHandle = void 0;
4087
+ }
4088
+ pendingRouterHtml = "";
4089
+ leftover = "";
4090
+ pendingClosingTags = "";
4091
+ router.serverSsr?.cleanup();
4092
+ }
4093
+ const stream = new ReadableStream$1({
4094
+ start(c) {
4095
+ controller = c;
4096
+ },
4097
+ cancel() {
4098
+ isStreamClosed = true;
4099
+ cleanup();
4100
+ }
4101
+ });
4102
+ function flushPendingRouterHtml() {
4103
+ if (!pendingRouterHtml) return;
4104
+ safeEnqueue(pendingRouterHtml);
4105
+ pendingRouterHtml = "";
4106
+ }
4107
+ function appendRouterHtml(html) {
4108
+ if (!html) return;
4109
+ pendingRouterHtml += html;
4110
+ }
4111
+ function tryFinish() {
4112
+ if (isAppRendering || !serializationFinished) return;
4113
+ if (cleanedUp || isStreamClosed) return;
4114
+ if (serializationTimeoutHandle !== void 0) {
4115
+ clearTimeout(serializationTimeoutHandle);
4116
+ serializationTimeoutHandle = void 0;
4117
+ }
4118
+ const decoderRemainder = textDecoder.decode();
4119
+ if (leftover) safeEnqueue(leftover);
4120
+ if (decoderRemainder) safeEnqueue(decoderRemainder);
4121
+ flushPendingRouterHtml();
4122
+ if (pendingClosingTags) safeEnqueue(pendingClosingTags);
4123
+ safeClose();
4124
+ cleanup();
4125
+ }
4126
+ const lifetimeMs = DEFAULT_LIFETIME_TIMEOUT_MS;
4127
+ lifetimeTimeoutHandle = setTimeout(() => {
4128
+ if (!cleanedUp && !isStreamClosed) {
4129
+ console.warn(`SSR stream transform exceeded maximum lifetime (${lifetimeMs}ms), forcing cleanup`);
4130
+ safeError(/* @__PURE__ */ new Error("Stream lifetime exceeded"));
4131
+ cleanup();
4132
+ }
4133
+ }, lifetimeMs);
4134
+ if (!serializationAlreadyFinished) {
4135
+ stopListeningToInjectedHtml = router.subscribe("onInjectedHtml", () => {
4136
+ if (cleanedUp || isStreamClosed) return;
4137
+ const html = router.serverSsr?.takeBufferedHtml();
4138
+ if (!html) return;
4139
+ if (isAppRendering || leftover || pendingClosingTags) appendRouterHtml(html);
4140
+ else {
4141
+ flushPendingRouterHtml();
4142
+ safeEnqueue(html);
4143
+ }
4144
+ });
4145
+ stopListeningToSerializationFinished = router.subscribe("onSerializationFinished", () => {
4146
+ serializationFinished = true;
4147
+ tryFinish();
4148
+ });
4149
+ }
4150
+ (async () => {
4151
+ const reader = appStream.getReader();
4152
+ try {
4153
+ while (true) {
4154
+ const { done, value } = await reader.read();
4155
+ if (done) break;
4156
+ if (cleanedUp || isStreamClosed) return;
4157
+ const text = value instanceof Uint8Array ? textDecoder.decode(value, { stream: true }) : String(value);
4158
+ const chunkString = leftover ? leftover + text : text;
4159
+ if (!streamBarrierLifted) {
4160
+ if (chunkString.includes("$tsr-stream-barrier")) {
4161
+ streamBarrierLifted = true;
4162
+ router.serverSsr?.liftScriptBarrier();
4163
+ }
4164
+ }
4165
+ if (pendingClosingTags) {
4166
+ pendingClosingTags += chunkString;
4167
+ leftover = "";
4168
+ continue;
4169
+ }
4170
+ const bodyEndIndex = chunkString.indexOf(BODY_END_TAG);
4171
+ const htmlEndIndex = chunkString.indexOf(HTML_END_TAG);
4172
+ if (bodyEndIndex !== -1 && htmlEndIndex !== -1 && bodyEndIndex < htmlEndIndex) {
4173
+ pendingClosingTags = chunkString.slice(bodyEndIndex);
4174
+ safeEnqueue(chunkString.slice(0, bodyEndIndex));
4175
+ flushPendingRouterHtml();
4176
+ leftover = "";
4177
+ continue;
4178
+ }
4179
+ const lastClosingTagEnd = findLastClosingTagEnd(chunkString);
4180
+ if (lastClosingTagEnd > 0) {
4181
+ safeEnqueue(chunkString.slice(0, lastClosingTagEnd));
4182
+ flushPendingRouterHtml();
4183
+ leftover = chunkString.slice(lastClosingTagEnd);
4184
+ if (leftover.length > MAX_LEFTOVER_CHARS) {
4185
+ safeEnqueue(leftover.slice(0, leftover.length - MAX_LEFTOVER_CHARS));
4186
+ leftover = leftover.slice(-MAX_LEFTOVER_CHARS);
4187
+ }
4188
+ } else {
4189
+ const combined = chunkString;
4190
+ if (combined.length > MAX_LEFTOVER_CHARS) {
4191
+ const flushUpto = combined.length - MAX_LEFTOVER_CHARS;
4192
+ safeEnqueue(combined.slice(0, flushUpto));
4193
+ leftover = combined.slice(flushUpto);
4194
+ } else leftover = combined;
4195
+ }
4196
+ }
4197
+ if (cleanedUp || isStreamClosed) return;
4198
+ isAppRendering = false;
4199
+ router.serverSsr?.setRenderFinished();
4200
+ if (serializationFinished) tryFinish();
4201
+ else {
4202
+ const timeoutMs = opts?.timeoutMs ?? DEFAULT_SERIALIZATION_TIMEOUT_MS;
4203
+ serializationTimeoutHandle = setTimeout(() => {
4204
+ if (!cleanedUp && !isStreamClosed) {
4205
+ console.error("Serialization timeout after app render finished");
4206
+ safeError(/* @__PURE__ */ new Error("Serialization timeout after app render finished"));
4207
+ cleanup();
4208
+ }
4209
+ }, timeoutMs);
4210
+ }
4211
+ } catch (error) {
4212
+ if (cleanedUp) return;
4213
+ console.error("Error reading appStream:", error);
4214
+ isAppRendering = false;
4215
+ router.serverSsr?.setRenderFinished();
4216
+ safeError(error);
4217
+ cleanup();
4218
+ } finally {
4219
+ reader.releaseLock();
4220
+ }
4221
+ })().catch((error) => {
4222
+ if (cleanedUp) return;
4223
+ console.error("Error in stream transform:", error);
4224
+ safeError(error);
4225
+ cleanup();
4226
+ });
4227
+ return stream;
4228
+ }
4229
+ var scroll_restoration_inline_default = 'function(t){let s;try{s=JSON.parse(sessionStorage.getItem(t.storageKey)||"{}")}catch(e){console.error(e);return}const c=t.key||window.history.state?.__TSR_key,r=c?s[c]:void 0;if(t.shouldScrollRestoration&&r&&typeof r=="object"&&Object.keys(r).length>0){for(const e in r){const o=r[e];if(!o||typeof o!="object")continue;const l=o.scrollX,i=o.scrollY;if(!(!Number.isFinite(l)||!Number.isFinite(i))){if(e==="window")window.scrollTo({top:i,left:l,behavior:t.behavior});else if(e){let n;try{n=document.querySelector(e)}catch{continue}n&&(n.scrollLeft=l,n.scrollTop=i)}}}return}const a=window.location.hash.split("#",2)[1];if(a){const e=window.history.state?.__hashScrollIntoViewOptions??!0;if(e){const o=document.getElementById(a);o&&o.scrollIntoView(e)}return}window.scrollTo({top:0,left:0,behavior:t.behavior})}';
4230
+ const defaultInlineScrollRestorationScript = `(${scroll_restoration_inline_default})(${escapeHtml(JSON.stringify({
4231
+ storageKey,
4232
+ shouldScrollRestoration: true
4233
+ }))})`;
4234
+ function getScrollRestorationScript(options) {
4235
+ if (options.storageKey === "tsr-scroll-restoration-v1_3" && options.shouldScrollRestoration === true && options.key === void 0 && options.behavior === void 0) return defaultInlineScrollRestorationScript;
4236
+ return `(${scroll_restoration_inline_default})(${escapeHtml(JSON.stringify(options))})`;
4237
+ }
4238
+ function getScrollRestorationScriptForRouter(router) {
4239
+ if (typeof router.options.scrollRestoration === "function" && !router.options.scrollRestoration({ location: router.latestLocation })) return null;
4240
+ const getKey = router.options.getScrollRestorationKey;
4241
+ if (!getKey) return defaultInlineScrollRestorationScript;
4242
+ const location = router.latestLocation;
4243
+ const userKey = getKey(location);
4244
+ if (userKey === defaultGetScrollRestorationKey(location)) return defaultInlineScrollRestorationScript;
4245
+ return getScrollRestorationScript({
4246
+ storageKey,
4247
+ shouldScrollRestoration: true,
4248
+ key: userKey
4249
+ });
4250
+ }
4251
+ export {
4252
+ createSerializationAdapter as A,
4253
+ BaseRootRoute as B,
4254
+ createRawStreamRPCPlugin as C,
4255
+ isResolvedRedirect as D,
4256
+ getStylesheetHref as E,
4257
+ mergeHeaders as F,
4258
+ executeRewriteInput as G,
4259
+ defaultSerovalPlugins as H,
4260
+ makeSerovalPlugin as I,
4261
+ RouterCore as R,
4262
+ isDangerousProtocol as a,
4263
+ BaseRoute as b,
4264
+ isModuleNotFoundError as c,
4265
+ deepEqual as d,
4266
+ exactPathTest as e,
4267
+ functionalUpdate as f,
4268
+ isNotFound as g,
4269
+ hasKeys as h,
4270
+ invariant as i,
4271
+ getScrollRestorationScriptForRouter as j,
4272
+ rootRouteId as k,
4273
+ isServer as l,
4274
+ isRedirect as m,
4275
+ createNonReactiveReadonlyStore as n,
4276
+ createNonReactiveMutableStore as o,
4277
+ escapeHtml as p,
4278
+ isInlinableStylesheet as q,
4279
+ removeTrailingSlash as r,
4280
+ getAssetCrossOrigin as s,
4281
+ resolveManifestAssetLink as t,
4282
+ transformReadableStreamWithRouter as u,
4283
+ transformPipeableStreamWithRouter as v,
4284
+ getNormalizedURL as w,
4285
+ getOrigin as x,
4286
+ attachRouterServerSsrUtils as y,
4287
+ defineHandlerCallback as z
4288
+ };