@krate/runtime 0.5.0-rc.1 → 0.5.0-rc.10

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 (214) hide show
  1. package/dist/action-context.js +1 -1
  2. package/dist/actions.d.ts +7 -0
  3. package/dist/actions.js +34 -10
  4. package/dist/after.d.ts +28 -0
  5. package/dist/after.js +48 -0
  6. package/dist/assets-static.d.ts +10 -1
  7. package/dist/assets-static.js +10 -2
  8. package/dist/base-path.d.ts +7 -0
  9. package/dist/base-path.js +20 -0
  10. package/dist/boundary.js +1 -1
  11. package/dist/builtin-tags.d.ts +12 -0
  12. package/dist/builtin-tags.js +42 -0
  13. package/dist/cache-adapter.js +1 -1
  14. package/dist/cache-scope.d.ts +8 -0
  15. package/dist/cache-scope.js +14 -1
  16. package/dist/cloudflare-workers.d.ts +2 -0
  17. package/dist/cloudflare-workers.js +27 -0
  18. package/dist/context.d.ts +5 -0
  19. package/dist/context.js +28 -17
  20. package/dist/dev-overlay.d.ts +54 -3
  21. package/dist/dev-overlay.js +470 -77
  22. package/dist/dom.js +18 -3
  23. package/dist/effects.js +2 -2
  24. package/dist/flight-props.d.ts +7 -0
  25. package/dist/flight-props.js +105 -0
  26. package/dist/handler-html.js +4 -4
  27. package/dist/handler-routing.d.ts +2 -23
  28. package/dist/handler-routing.js +9 -190
  29. package/dist/handler-segments.d.ts +6 -0
  30. package/dist/handler-segments.js +18 -4
  31. package/dist/head-tags.d.ts +9 -0
  32. package/dist/head-tags.js +93 -6
  33. package/dist/highlight-bind.js +1 -1
  34. package/dist/highlight.d.ts +3 -2
  35. package/dist/highlight.js +17 -12
  36. package/dist/hints.d.ts +25 -2
  37. package/dist/hints.js +147 -74
  38. package/dist/index.d.ts +2 -0
  39. package/dist/index.js +3 -0
  40. package/dist/island-swap.d.ts +47 -0
  41. package/dist/island-swap.js +635 -0
  42. package/dist/jsx-dev-runtime.d.ts +1 -1
  43. package/dist/jsx-types.d.ts +99 -3
  44. package/dist/krate-core.js +1 -1
  45. package/dist/krate-dev.js +385 -66
  46. package/dist/krate-f-actions.js +1 -1
  47. package/dist/krate-f-classes.js +1 -1
  48. package/dist/krate-f-highlight.js +1 -1
  49. package/dist/krate-f-list.js +1 -1
  50. package/dist/krate-f-navigation.js +1 -1
  51. package/dist/krate-f-router-lite.js +1 -1
  52. package/dist/krate-f-router.js +1 -1
  53. package/dist/krate-features.json +454 -0
  54. package/dist/krate-hydrate-lite.js +5 -5
  55. package/dist/krate-hydrate.js +5 -5
  56. package/dist/krate-island-swap.js +1 -0
  57. package/dist/krate-runtime.js +5 -5
  58. package/dist/list.d.ts +14 -4
  59. package/dist/list.js +4 -5
  60. package/dist/metadata.js +5 -2
  61. package/dist/navigation-react.d.ts +13 -0
  62. package/dist/navigation-react.js +86 -0
  63. package/dist/navigation.d.ts +19 -0
  64. package/dist/navigation.js +35 -0
  65. package/dist/node-server.js +3 -3
  66. package/dist/og.js +1 -1
  67. package/dist/platform.d.ts +52 -0
  68. package/dist/platform.js +57 -0
  69. package/dist/react-compat.d.ts +39 -0
  70. package/dist/react-compat.js +359 -0
  71. package/dist/react-server.d.ts +63 -0
  72. package/dist/react-server.js +125 -0
  73. package/dist/region-wire.d.ts +10 -0
  74. package/dist/region-wire.js +154 -0
  75. package/dist/request-context.js +1 -1
  76. package/dist/request-extras.d.ts +4 -0
  77. package/dist/request-extras.js +51 -0
  78. package/dist/resp.js +1 -1
  79. package/dist/route-source.d.ts +39 -0
  80. package/dist/route-source.js +532 -0
  81. package/dist/router-lite.js +3 -9
  82. package/dist/router.d.ts +1 -1
  83. package/dist/router.js +628 -98
  84. package/dist/server-handler.d.ts +69 -1
  85. package/dist/server-handler.js +515 -96
  86. package/dist/server-renderer.js +16 -7
  87. package/dist/server.d.ts +73 -16
  88. package/dist/server.js +619 -102
  89. package/dist/sha256.js +9 -9
  90. package/dist/signal.js +0 -6
  91. package/dist/site-config.d.ts +15 -0
  92. package/dist/site-config.js +28 -0
  93. package/dist/slot.d.ts +12 -0
  94. package/dist/slot.js +23 -0
  95. package/dist/ssr-core.d.ts +2 -0
  96. package/dist/ssr-core.js +12 -4
  97. package/dist/testing.d.ts +62 -0
  98. package/dist/testing.js +90 -0
  99. package/dist/use-id.js +1 -1
  100. package/package.json +28 -3
  101. package/dist/action-context.test.d.ts +0 -1
  102. package/dist/action-context.test.js +0 -72
  103. package/dist/actions.test.d.ts +0 -1
  104. package/dist/actions.test.js +0 -477
  105. package/dist/cache-adapter.test.d.ts +0 -1
  106. package/dist/cache-adapter.test.js +0 -244
  107. package/dist/cache.test.d.ts +0 -1
  108. package/dist/cache.test.js +0 -233
  109. package/dist/class-component.test.d.ts +0 -1
  110. package/dist/class-component.test.js +0 -462
  111. package/dist/class-helpers.test.d.ts +0 -1
  112. package/dist/class-helpers.test.js +0 -169
  113. package/dist/context.test.d.ts +0 -1
  114. package/dist/context.test.js +0 -57
  115. package/dist/derived.test.d.ts +0 -1
  116. package/dist/derived.test.js +0 -140
  117. package/dist/dev-overlay.test.d.ts +0 -1
  118. package/dist/dev-overlay.test.js +0 -165
  119. package/dist/discrete.test.d.ts +0 -1
  120. package/dist/discrete.test.js +0 -100
  121. package/dist/dom.test.d.ts +0 -1
  122. package/dist/dom.test.js +0 -39
  123. package/dist/effect-errors.test.d.ts +0 -1
  124. package/dist/effect-errors.test.js +0 -199
  125. package/dist/effects.test.d.ts +0 -1
  126. package/dist/effects.test.js +0 -485
  127. package/dist/events.test.d.ts +0 -1
  128. package/dist/events.test.js +0 -447
  129. package/dist/handler-html.test.d.ts +0 -1
  130. package/dist/handler-html.test.js +0 -256
  131. package/dist/handler-routing.test.d.ts +0 -1
  132. package/dist/handler-routing.test.js +0 -99
  133. package/dist/handler-segments.test.d.ts +0 -1
  134. package/dist/handler-segments.test.js +0 -217
  135. package/dist/head-tags.test.d.ts +0 -1
  136. package/dist/head-tags.test.js +0 -131
  137. package/dist/highlight-bind.test.d.ts +0 -1
  138. package/dist/highlight-bind.test.js +0 -124
  139. package/dist/highlight.test.d.ts +0 -1
  140. package/dist/highlight.test.js +0 -56
  141. package/dist/lanes.test.d.ts +0 -1
  142. package/dist/lanes.test.js +0 -59
  143. package/dist/list.test.d.ts +0 -1
  144. package/dist/list.test.js +0 -435
  145. package/dist/metadata.test.d.ts +0 -1
  146. package/dist/metadata.test.js +0 -167
  147. package/dist/navigation.test.d.ts +0 -1
  148. package/dist/navigation.test.js +0 -130
  149. package/dist/node-server.test.d.ts +0 -1
  150. package/dist/node-server.test.js +0 -492
  151. package/dist/optimistic-lanes.test.d.ts +0 -1
  152. package/dist/optimistic-lanes.test.js +0 -45
  153. package/dist/patterns.test.d.ts +0 -1
  154. package/dist/patterns.test.js +0 -125
  155. package/dist/portal.test.d.ts +0 -1
  156. package/dist/portal.test.js +0 -99
  157. package/dist/react-effects.test.d.ts +0 -1
  158. package/dist/react-effects.test.js +0 -133
  159. package/dist/react-suspense.test.d.ts +0 -1
  160. package/dist/react-suspense.test.js +0 -194
  161. package/dist/react.test.d.ts +0 -1
  162. package/dist/react.test.js +0 -60
  163. package/dist/react19.test.d.ts +0 -1
  164. package/dist/react19.test.js +0 -176
  165. package/dist/reactivity-core.test.d.ts +0 -1
  166. package/dist/reactivity-core.test.js +0 -152
  167. package/dist/reconcile.test.d.ts +0 -1
  168. package/dist/reconcile.test.js +0 -110
  169. package/dist/refs.test.d.ts +0 -1
  170. package/dist/refs.test.js +0 -257
  171. package/dist/router-layout.test.d.ts +0 -1
  172. package/dist/router-layout.test.js +0 -249
  173. package/dist/router-nav.test.d.ts +0 -1
  174. package/dist/router-nav.test.js +0 -559
  175. package/dist/router-slots.test.d.ts +0 -1
  176. package/dist/router-slots.test.js +0 -144
  177. package/dist/router-speculation.test.d.ts +0 -1
  178. package/dist/router-speculation.test.js +0 -25
  179. package/dist/router-styles.test.d.ts +0 -1
  180. package/dist/router-styles.test.js +0 -98
  181. package/dist/router.test.d.ts +0 -1
  182. package/dist/router.test.js +0 -36
  183. package/dist/server-async.test.d.ts +0 -1
  184. package/dist/server-async.test.js +0 -216
  185. package/dist/server-handler.test.d.ts +0 -1
  186. package/dist/server-handler.test.js +0 -535
  187. package/dist/server-highlight.test.d.ts +0 -1
  188. package/dist/server-highlight.test.js +0 -32
  189. package/dist/server-renderer.test.d.ts +0 -1
  190. package/dist/server-renderer.test.js +0 -266
  191. package/dist/server.test.d.ts +0 -1
  192. package/dist/server.test.js +0 -88
  193. package/dist/sha256.test.d.ts +0 -1
  194. package/dist/sha256.test.js +0 -13
  195. package/dist/signal-lanes.test.d.ts +0 -1
  196. package/dist/signal-lanes.test.js +0 -32
  197. package/dist/signal.test.d.ts +0 -1
  198. package/dist/signal.test.js +0 -68
  199. package/dist/slots.test.d.ts +0 -1
  200. package/dist/slots.test.js +0 -187
  201. package/dist/snapshots.test.d.ts +0 -1
  202. package/dist/snapshots.test.js +0 -208
  203. package/dist/ssr-core-behavior.test.d.ts +0 -1
  204. package/dist/ssr-core-behavior.test.js +0 -620
  205. package/dist/ssr-core.test.d.ts +0 -1
  206. package/dist/ssr-core.test.js +0 -324
  207. package/dist/static-memory.test.d.ts +0 -1
  208. package/dist/static-memory.test.js +0 -26
  209. package/dist/storage.test.d.ts +0 -1
  210. package/dist/storage.test.js +0 -46
  211. package/dist/suspense-actions.test.d.ts +0 -1
  212. package/dist/suspense-actions.test.js +0 -72
  213. package/dist/suspense.test.d.ts +0 -1
  214. package/dist/suspense.test.js +0 -556
@@ -0,0 +1,532 @@
1
+ // Redirect, rewrite and header sources, has/missing conditions and
2
+ // destinations. This is the TypeScript twin of the Go package
3
+ // internal/routesource and the helpers in build/routesource.go; keep the two
4
+ // in step. The syntax is the path-to-regexp 6 subset Next.js uses, plus
5
+ // Krate's "/x/*" splat form and the header globs.
6
+ const DEFAULT_PATTERN = "[^/#?]+?";
7
+ function lex(s) {
8
+ const out = [];
9
+ const word = /[0-9A-Za-z_]/;
10
+ for (let i = 0; i < s.length;) {
11
+ const c = s[i];
12
+ if (c === "*" || c === "+" || c === "?") {
13
+ out.push(["MODIFIER", c]);
14
+ i++;
15
+ }
16
+ else if (c === "\\") {
17
+ if (i + 1 >= s.length)
18
+ throw new Error("a trailing backslash");
19
+ out.push(["ESCAPED", s[i + 1]]);
20
+ i += 2;
21
+ }
22
+ else if (c === "{") {
23
+ out.push(["OPEN", c]);
24
+ i++;
25
+ }
26
+ else if (c === "}") {
27
+ out.push(["CLOSE", c]);
28
+ i++;
29
+ }
30
+ else if (c === ":") {
31
+ let j = i + 1;
32
+ while (j < s.length && word.test(s[j]))
33
+ j++;
34
+ if (j === i + 1)
35
+ throw new Error("missing parameter name");
36
+ out.push(["NAME", s.slice(i + 1, j)]);
37
+ i = j;
38
+ }
39
+ else if (c === "(") {
40
+ let count = 1;
41
+ let j = i + 1;
42
+ if (s[j] === "?")
43
+ throw new Error('a pattern cannot start with "?"');
44
+ let pat = "";
45
+ while (j < s.length) {
46
+ if (s[j] === "\\") {
47
+ pat += s[j] + (s[j + 1] ?? "");
48
+ j += 2;
49
+ continue;
50
+ }
51
+ if (s[j] === ")") {
52
+ count--;
53
+ if (count === 0) {
54
+ j++;
55
+ break;
56
+ }
57
+ }
58
+ else if (s[j] === "(") {
59
+ count++;
60
+ if (s[j + 1] !== "?")
61
+ throw new Error("capturing groups are not allowed");
62
+ }
63
+ pat += s[j++];
64
+ }
65
+ if (count)
66
+ throw new Error("unbalanced pattern");
67
+ if (!pat)
68
+ throw new Error("missing pattern");
69
+ out.push(["PATTERN", pat]);
70
+ i = j;
71
+ }
72
+ else {
73
+ out.push(["CHAR", c]);
74
+ i++;
75
+ }
76
+ }
77
+ out.push(["END", ""]);
78
+ return out;
79
+ }
80
+ function parse(s) {
81
+ const lt = lex(s);
82
+ let i = 0;
83
+ const tryC = (kind) => (lt[i][0] === kind ? lt[i++][1] : undefined);
84
+ const text = () => {
85
+ let out = "";
86
+ for (;;) {
87
+ const v = tryC("CHAR") ?? tryC("ESCAPED");
88
+ if (v === undefined)
89
+ return out;
90
+ out += v;
91
+ }
92
+ };
93
+ const toks = [];
94
+ let lit = "";
95
+ const flush = () => {
96
+ if (lit)
97
+ toks.push({ lit });
98
+ lit = "";
99
+ };
100
+ while (lt[i][0] !== "END") {
101
+ const ch = tryC("CHAR");
102
+ const name = tryC("NAME");
103
+ const pat = tryC("PATTERN");
104
+ if (name !== undefined || pat !== undefined) {
105
+ let prefix = ch ?? "";
106
+ if (prefix !== "." && prefix !== "/") {
107
+ lit += prefix;
108
+ prefix = "";
109
+ }
110
+ flush();
111
+ toks.push({ param: true, name: name ?? "", prefix, suffix: "", pattern: pat ?? DEFAULT_PATTERN, mod: tryC("MODIFIER") ?? "" });
112
+ continue;
113
+ }
114
+ if (ch !== undefined) {
115
+ lit += ch;
116
+ continue;
117
+ }
118
+ const esc = tryC("ESCAPED");
119
+ if (esc !== undefined) {
120
+ lit += esc;
121
+ continue;
122
+ }
123
+ flush();
124
+ if (tryC("OPEN") !== undefined) {
125
+ const prefix = text();
126
+ const n = tryC("NAME");
127
+ const p = tryC("PATTERN");
128
+ const suffix = text();
129
+ if (tryC("CLOSE") === undefined)
130
+ throw new Error('expected "}"');
131
+ toks.push({ param: true, name: n ?? "", prefix, suffix, pattern: n !== undefined && p === undefined ? DEFAULT_PATTERN : (p ?? ""), mod: tryC("MODIFIER") ?? "" });
132
+ continue;
133
+ }
134
+ throw new Error(`unexpected ${lt[i][0].toLowerCase()} ${JSON.stringify(lt[i][1])}`);
135
+ }
136
+ flush();
137
+ return toks;
138
+ }
139
+ const quote = (s) => s.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&");
140
+ /** Removes leading (?!...) groups from a parameter pattern. */
141
+ function splitLookaheads(p) {
142
+ const negs = [];
143
+ while (p.startsWith("(?!")) {
144
+ let depth = 1;
145
+ let i = 3;
146
+ let inClass = false;
147
+ for (; i < p.length; i++) {
148
+ const c = p[i];
149
+ if (c === "\\")
150
+ i++;
151
+ else if (inClass) {
152
+ if (c === "]")
153
+ inClass = false;
154
+ }
155
+ else if (c === "[")
156
+ inClass = true;
157
+ else if (c === "(")
158
+ depth++;
159
+ else if (c === ")")
160
+ depth--;
161
+ if (depth === 0)
162
+ break;
163
+ }
164
+ if (depth !== 0)
165
+ throw new Error("unbalanced lookahead");
166
+ negs.push(p.slice(3, i));
167
+ p = p.slice(i + 1);
168
+ }
169
+ if (negs.length && p === "")
170
+ throw new Error("a lookahead needs a pattern after it");
171
+ return { negs, rest: p };
172
+ }
173
+ function compilePattern(src) {
174
+ let pat = src;
175
+ let splat = false;
176
+ if (pat.endsWith("/*")) {
177
+ pat = pat.slice(0, -2);
178
+ splat = true;
179
+ }
180
+ const toks = parse(pat);
181
+ let re = "^";
182
+ let group = 0;
183
+ const params = [];
184
+ for (const t of toks) {
185
+ if (!t.param) {
186
+ re += quote(t.lit);
187
+ continue;
188
+ }
189
+ const prefix = quote(t.prefix);
190
+ const suffix = quote(t.suffix);
191
+ const mod = t.mod;
192
+ if (!t.pattern) {
193
+ re += `(?:${prefix}${suffix})${mod}`;
194
+ continue;
195
+ }
196
+ const { negs, rest } = splitLookaheads(t.pattern);
197
+ group++;
198
+ params.push({ name: t.name, group, mod, negs: negs.map((n) => new RegExp("^(?:" + n + ")")) });
199
+ if ((mod === "+" || mod === "*") && (prefix || suffix)) {
200
+ re += `(?:${prefix}((?:${rest})(?:${suffix}${prefix}(?:${rest}))*)${suffix})${mod === "*" ? "?" : ""}`;
201
+ }
202
+ else if (prefix || suffix) {
203
+ re += `(?:${prefix}(${rest})${suffix})${mod}`;
204
+ }
205
+ else if (mod === "+" || mod === "*") {
206
+ re += `((?:${rest})${mod})`;
207
+ }
208
+ else {
209
+ re += `(${rest})${mod}`;
210
+ }
211
+ }
212
+ let splatGroup = 0;
213
+ if (splat) {
214
+ splatGroup = ++group;
215
+ re += "(?:/([\\s\\S]*))?$";
216
+ }
217
+ else {
218
+ re += "/?$";
219
+ }
220
+ const rx = new RegExp(re);
221
+ return {
222
+ match(path) {
223
+ const m = rx.exec(path);
224
+ if (!m)
225
+ return null;
226
+ const out = { params: {}, mods: {} };
227
+ for (const p of params) {
228
+ const v = m[p.group];
229
+ if (v !== undefined && p.negs.some((n) => n.test(v)))
230
+ return null;
231
+ if (!p.name)
232
+ continue;
233
+ out.mods[p.name] = p.mod;
234
+ if (v !== undefined || p.mod === "?" || p.mod === "*")
235
+ out.params[p.name] = v ?? "";
236
+ }
237
+ if (splatGroup)
238
+ out.params.splat = m[splatGroup] ?? "";
239
+ return out;
240
+ },
241
+ };
242
+ }
243
+ /** path.Match for slash paths: "*" and "?" do not cross "/", "[...]" classes. */
244
+ function pathMatch(pattern, name) {
245
+ let re = "^";
246
+ for (let i = 0; i < pattern.length; i++) {
247
+ const c = pattern[i];
248
+ if (c === "*")
249
+ re += "[^/]*";
250
+ else if (c === "?")
251
+ re += "[^/]";
252
+ else if (c === "[") {
253
+ const end = pattern.indexOf("]", i + 1);
254
+ if (end === -1)
255
+ return false;
256
+ let cls = pattern.slice(i + 1, end);
257
+ let neg = false;
258
+ if (cls.startsWith("^")) {
259
+ neg = true;
260
+ cls = cls.slice(1);
261
+ }
262
+ re += "[" + (neg ? "^" : "") + cls.replace(/\\/g, "\\\\") + "]";
263
+ i = end;
264
+ }
265
+ else if (c === "\\" && i + 1 < pattern.length)
266
+ re += quote(pattern[++i]);
267
+ else
268
+ re += quote(c);
269
+ }
270
+ try {
271
+ return new RegExp(re + "$").test(name);
272
+ }
273
+ catch {
274
+ return false;
275
+ }
276
+ }
277
+ /** Compiles a source. It throws when the source cannot be matched. */
278
+ export function compileSource(source, kind) {
279
+ if (kind === "header")
280
+ source = source.trim();
281
+ const none = () => ({ params: {}, mods: {} });
282
+ if (!/[:({]/.test(source)) {
283
+ if (kind === "header") {
284
+ return {
285
+ match(p) {
286
+ if (source === "")
287
+ return null;
288
+ if (!source.includes("*"))
289
+ return p === source ? none() : null;
290
+ if (source.endsWith("*"))
291
+ return p.startsWith(source.slice(0, -1)) ? none() : null;
292
+ return pathMatch(source, p) ? none() : null;
293
+ },
294
+ };
295
+ }
296
+ if (source.endsWith("/*")) {
297
+ const prefix = source.slice(0, -2);
298
+ return {
299
+ match(p) {
300
+ if (p === prefix)
301
+ return { params: { splat: "" }, mods: {} };
302
+ if (!p.startsWith(prefix + "/"))
303
+ return null;
304
+ return { params: { splat: p.slice(prefix.length + 1) }, mods: {} };
305
+ },
306
+ };
307
+ }
308
+ return { match: (p) => (p === source ? none() : null) };
309
+ }
310
+ return compilePattern(source);
311
+ }
312
+ const safeParamName = (key) => key.replace(/[^A-Za-z]/g, "");
313
+ function condValue(c, req) {
314
+ let v;
315
+ switch (c.type) {
316
+ case "query": {
317
+ const all = req.url.searchParams.getAll(c.key || "");
318
+ v = all.length ? all[all.length - 1] : undefined;
319
+ break;
320
+ }
321
+ case "header":
322
+ v = req.headers.get(c.key || "") ?? undefined;
323
+ break;
324
+ case "cookie":
325
+ for (const part of (req.headers.get("cookie") || "").split(";")) {
326
+ const i = part.indexOf("=");
327
+ if (i > 0 && part.slice(0, i).trim() === c.key) {
328
+ const raw = part.slice(i + 1).trim();
329
+ try {
330
+ v = decodeURIComponent(raw);
331
+ }
332
+ catch {
333
+ v = raw;
334
+ }
335
+ break;
336
+ }
337
+ }
338
+ break;
339
+ case "host":
340
+ v = (req.headers.get("host") || req.url.host).split(":")[0].toLowerCase();
341
+ break;
342
+ }
343
+ return v || undefined;
344
+ }
345
+ function condMatch(c, req, into) {
346
+ const v = condValue(c, req);
347
+ if (v === undefined)
348
+ return false;
349
+ if (!c.re) {
350
+ const key = c.type === "header" ? (c.key || "").toLowerCase() : c.key || "";
351
+ into[safeParamName(key)] = v;
352
+ return true;
353
+ }
354
+ const m = c.re.exec(v);
355
+ if (!m)
356
+ return false;
357
+ if (m.groups)
358
+ Object.assign(into, m.groups);
359
+ else if (c.type === "host" && m[0])
360
+ into.host = m[0];
361
+ return true;
362
+ }
363
+ /** Compiles has/missing; null when there are none. It throws on an invalid item. */
364
+ export function compileConditions(has = [], missing = []) {
365
+ if (!has.length && !missing.length)
366
+ return null;
367
+ const one = (c) => {
368
+ if (!["query", "header", "cookie", "host"].includes(c.type))
369
+ throw new Error(`condition type must be query, header, cookie or host, got ${c.type}`);
370
+ if (c.type !== "host" && !c.key)
371
+ throw new Error(`condition type ${c.type} needs a key`);
372
+ return { ...c, re: c.value ? new RegExp("^(?:" + c.value + ")$") : undefined };
373
+ };
374
+ const h = has.map(one);
375
+ const m = missing.map(one);
376
+ return {
377
+ match(req) {
378
+ const params = {};
379
+ for (const c of h)
380
+ if (!condMatch(c, req, params))
381
+ return null;
382
+ for (const c of m)
383
+ if (condMatch(c, req, {}))
384
+ return null;
385
+ return params;
386
+ },
387
+ };
388
+ }
389
+ export function compileMatcher(source, kind, has, missing) {
390
+ const src = compileSource(source, kind);
391
+ const cond = compileConditions(has, missing);
392
+ return {
393
+ match(path, req) {
394
+ const m = src.match(path);
395
+ if (!m)
396
+ return null;
397
+ if (!cond)
398
+ return m;
399
+ const extra = cond.match(req);
400
+ if (!extra)
401
+ return null;
402
+ return { params: { ...m.params, ...extra }, mods: m.mods };
403
+ },
404
+ };
405
+ }
406
+ // Destinations
407
+ /** url.PathEscape of Go: segment-escapes everything but unreserved and $&+=:@. */
408
+ export function pathEscape(s) {
409
+ return encodeURIComponent(s)
410
+ .replace(/[!'()*]/g, (c) => "%" + c.charCodeAt(0).toString(16).toUpperCase())
411
+ .replace(/%(24|26|2B|3D|3A|40)/g, (_m, h) => String.fromCharCode(parseInt(h, 16)));
412
+ }
413
+ /** Percent-encodes a matched (decoded) value segment by segment, keeping "/" between segments. */
414
+ export function escapeRedirectValue(v) {
415
+ if (v === "")
416
+ return "";
417
+ return v.split("/").map(pathEscape).join("/");
418
+ }
419
+ function escapeQueryValue(v) {
420
+ return encodeURIComponent(v).replace(/%2F/gi, "/");
421
+ }
422
+ function replaceDestParams(destination, params, mods) {
423
+ const queryAt = destination.indexOf("?");
424
+ const re = /:([A-Za-z_][A-Za-z0-9_]*)/g;
425
+ let out = "";
426
+ let last = 0;
427
+ let m;
428
+ while ((m = re.exec(destination)) !== null) {
429
+ const name = m[1];
430
+ if (name === "splat" || !Object.prototype.hasOwnProperty.call(params, name))
431
+ continue;
432
+ let end = m.index + m[0].length;
433
+ const mod = mods[name];
434
+ if (mod && end < destination.length && destination[end] === mod)
435
+ end++;
436
+ let prefix = destination.slice(last, m.index);
437
+ // An optional parameter that matched nothing takes its "/" with it (path-to-regexp).
438
+ if (params[name] === "" && (queryAt === -1 || m.index < queryAt) && (mod === "*" || mod === "?") && prefix.endsWith("/") && out.length + prefix.length > 1)
439
+ prefix = prefix.slice(0, -1);
440
+ out += prefix + (queryAt !== -1 && m.index > queryAt ? escapeQueryValue(params[name]) : escapeRedirectValue(params[name]));
441
+ last = end;
442
+ re.lastIndex = end;
443
+ }
444
+ return out + destination.slice(last);
445
+ }
446
+ /** Keeps a substituted path destination on-site (no "//host" or "/\\host" results). */
447
+ export function sanitizeRedirectTarget(configured, out) {
448
+ if (!configured.startsWith("/") || configured.startsWith("//") || configured.startsWith("/\\"))
449
+ return out;
450
+ out = out.replace(/[\u0000-\u001F\u007F]/g, (c) => "%" + c.charCodeAt(0).toString(16).toUpperCase().padStart(2, "0"));
451
+ const trimmed = out.replace(/^[/\\]+/, "");
452
+ return trimmed !== out ? "/" + trimmed : out;
453
+ }
454
+ /** Fills ":splat" and ":name" placeholders of a destination from a match. */
455
+ export function buildDestination(destination, m) {
456
+ const params = m.params;
457
+ let out;
458
+ if (Object.prototype.hasOwnProperty.call(params, "splat")) {
459
+ const splat = params.splat;
460
+ if (destination.includes(":splat"))
461
+ out = destination.split(":splat").join(escapeRedirectValue(splat));
462
+ else if (splat !== "")
463
+ out = destination.replace(/\/+$/, "") + "/" + escapeRedirectValue(splat);
464
+ else
465
+ out = destination;
466
+ if (Object.keys(params).length > 1)
467
+ out = replaceDestParams(out, params, m.mods);
468
+ }
469
+ else {
470
+ out = replaceDestParams(destination, params, m.mods);
471
+ }
472
+ return sanitizeRedirectTarget(destination, out);
473
+ }
474
+ function parseQuery(raw) {
475
+ const out = [];
476
+ const idx = new Map();
477
+ for (const part of raw.split("&")) {
478
+ if (!part)
479
+ continue;
480
+ const eq = part.indexOf("=");
481
+ let k;
482
+ let v;
483
+ try {
484
+ k = decodeURIComponent((eq === -1 ? part : part.slice(0, eq)).replace(/\+/g, " "));
485
+ v = decodeURIComponent((eq === -1 ? "" : part.slice(eq + 1)).replace(/\+/g, " "));
486
+ }
487
+ catch {
488
+ continue;
489
+ }
490
+ const i = idx.get(k);
491
+ if (i === undefined) {
492
+ idx.set(k, out.length);
493
+ out.push([k, [v]]);
494
+ }
495
+ else
496
+ out[i][1].push(v);
497
+ }
498
+ return out;
499
+ }
500
+ /** Adds the request's query to the destination's own; the destination's keys win. */
501
+ export function mergeRequestQuery(dest, rawQuery) {
502
+ if (rawQuery.startsWith("?"))
503
+ rawQuery = rawQuery.slice(1);
504
+ if (!rawQuery)
505
+ return dest;
506
+ let frag = "";
507
+ const h = dest.indexOf("#");
508
+ if (h !== -1) {
509
+ frag = dest.slice(h);
510
+ dest = dest.slice(0, h);
511
+ }
512
+ let destQuery = "";
513
+ const q = dest.indexOf("?");
514
+ if (q !== -1) {
515
+ destQuery = dest.slice(q + 1);
516
+ dest = dest.slice(0, q);
517
+ }
518
+ const pairs = parseQuery(rawQuery);
519
+ const idx = new Map(pairs.map(([k], i) => [k, i]));
520
+ for (const [k, vals] of parseQuery(destQuery)) {
521
+ const i = idx.get(k);
522
+ if (i !== undefined)
523
+ pairs[i][1] = vals;
524
+ else {
525
+ idx.set(k, pairs.length);
526
+ pairs.push([k, vals]);
527
+ }
528
+ }
529
+ const enc = (s) => encodeURIComponent(s);
530
+ const qs = pairs.flatMap(([k, vals]) => vals.map((v) => enc(k) + "=" + enc(v))).join("&");
531
+ return dest + (qs ? "?" + qs : "") + frag;
532
+ }
@@ -1,13 +1,7 @@
1
1
  // Router API for sites with the SPA router disabled (`spa: false`). Every
2
2
  // navigation is a full document load; the API surface matches router.ts so
3
3
  // application code (and the Next.js migration shim) works unchanged.
4
- function basePath() {
5
- const cfg = globalThis.__KRATE_CFG__;
6
- const bp = (cfg && cfg.basePath) || '';
7
- if (!bp || bp === '/')
8
- return '';
9
- return '/' + bp.replace(/^\/+|\/+$/g, '');
10
- }
4
+ import { basePath, withBase } from './base-path.js';
11
5
  export function getNavigationState() {
12
6
  if (typeof location === 'undefined')
13
7
  return { url: '', pathname: '/', search: '', hash: '', status: 'idle' };
@@ -39,9 +33,9 @@ export function navigate(url, opts = {}) {
39
33
  if (typeof location === 'undefined')
40
34
  return true;
41
35
  if (opts.replace)
42
- location.replace(url);
36
+ location.replace(withBase(url));
43
37
  else
44
- location.assign(url);
38
+ location.assign(withBase(url));
45
39
  return true;
46
40
  }
47
41
  export const krateRouter = {
package/dist/router.d.ts CHANGED
@@ -4,7 +4,7 @@
4
4
  * these warms the route's JS in addition to its HTML, so an SPA navigation does
5
5
  * not stall waiting on the chunk after the HTML swap.
6
6
  */
7
- export declare function pageAssetURLs(html: string, baseUrl: string, loaded: Set<string>): string[];
7
+ export declare function pageAssetURLs(html: string | Document, baseUrl: string, loaded: Set<string>): string[];
8
8
  export interface NavigateOptions {
9
9
  /** Replace the current history entry instead of pushing a new one. */
10
10
  replace?: boolean;