@krate/runtime 0.5.0-beta.1 → 0.5.0-beta.2
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.
- package/dist/actions.js +2 -1
- package/dist/assets-static.d.ts +5 -0
- package/dist/assets-static.js +31 -0
- package/dist/boundary.d.ts +12 -0
- package/dist/boundary.js +53 -13
- package/dist/cache-adapter.d.ts +113 -0
- package/dist/cache-adapter.js +217 -0
- package/dist/cache-adapter.test.d.ts +1 -0
- package/dist/cache-adapter.test.js +244 -0
- package/dist/cache-redis.d.ts +27 -0
- package/dist/cache-redis.js +110 -0
- package/dist/cache-scope.d.ts +25 -9
- package/dist/cache-scope.js +60 -12
- package/dist/cache.d.ts +1 -0
- package/dist/cache.js +3 -3
- package/dist/class-component.js +6 -0
- package/dist/class-component.test.js +53 -2
- package/dist/dev-overlay.js +10 -10
- package/dist/dom.d.ts +8 -0
- package/dist/dom.js +28 -0
- package/dist/effect-errors.test.d.ts +1 -0
- package/dist/effect-errors.test.js +163 -0
- package/dist/effects.d.ts +8 -0
- package/dist/effects.js +13 -0
- package/dist/error-overlay.js +4 -4
- package/dist/handler-html.d.ts +63 -0
- package/dist/handler-html.js +285 -0
- package/dist/handler-html.test.d.ts +1 -0
- package/dist/handler-html.test.js +256 -0
- package/dist/handler-routing.d.ts +83 -0
- package/dist/handler-routing.js +579 -0
- package/dist/handler-routing.test.d.ts +1 -0
- package/dist/handler-routing.test.js +99 -0
- package/dist/handler-segments.d.ts +43 -0
- package/dist/handler-segments.js +115 -0
- package/dist/handler-segments.test.d.ts +1 -0
- package/dist/handler-segments.test.js +217 -0
- package/dist/head-tags.d.ts +51 -0
- package/dist/head-tags.js +329 -0
- package/dist/head-tags.test.d.ts +1 -0
- package/dist/head-tags.test.js +131 -0
- package/dist/highlight-bind.d.ts +42 -0
- package/dist/highlight-bind.js +176 -0
- package/dist/highlight-bind.test.d.ts +1 -0
- package/dist/highlight-bind.test.js +124 -0
- package/dist/highlight.d.ts +93 -0
- package/dist/highlight.js +426 -0
- package/dist/highlight.test.d.ts +1 -0
- package/dist/highlight.test.js +56 -0
- package/dist/hints.d.ts +19 -0
- package/dist/hints.js +97 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +2 -0
- package/dist/jsx-types.d.ts +11 -0
- package/dist/krate-core.js +1 -1
- package/dist/krate-dev.js +10 -10
- package/dist/krate-f-actions.js +1 -1
- package/dist/krate-f-classes.js +5 -5
- package/dist/krate-f-highlight.js +2 -0
- package/dist/krate-f-list.js +1 -1
- package/dist/krate-f-navigation.js +2 -0
- package/dist/krate-f-router.js +1 -1
- package/dist/krate-features.json +254 -0
- package/dist/krate-hydrate-lite.js +5 -5
- package/dist/krate-hydrate.js +5 -5
- package/dist/krate-runtime.js +5 -5
- package/dist/list.js +4 -2
- package/dist/metadata-routes.d.ts +75 -0
- package/dist/metadata-routes.js +76 -0
- package/dist/metadata.d.ts +222 -0
- package/dist/metadata.js +452 -0
- package/dist/metadata.test.d.ts +1 -0
- package/dist/metadata.test.js +167 -0
- package/dist/navigation-server.d.ts +27 -0
- package/dist/navigation-server.js +90 -0
- package/dist/navigation.d.ts +37 -0
- package/dist/navigation.js +195 -0
- package/dist/navigation.test.d.ts +1 -0
- package/dist/navigation.test.js +130 -0
- package/dist/node-server.d.ts +22 -0
- package/dist/node-server.js +436 -0
- package/dist/node-server.test.d.ts +1 -0
- package/dist/node-server.test.js +492 -0
- package/dist/og-files.d.ts +2 -0
- package/dist/og-files.js +19 -0
- package/dist/og.d.ts +56 -0
- package/dist/og.js +156 -0
- package/dist/react.d.ts +47 -0
- package/dist/react.js +59 -1
- package/dist/react19.test.d.ts +1 -0
- package/dist/react19.test.js +176 -0
- package/dist/request-context.d.ts +23 -0
- package/dist/request-context.js +45 -0
- package/dist/resp.d.ts +55 -0
- package/dist/resp.js +239 -0
- package/dist/router-layout.test.js +70 -0
- package/dist/router-nav.test.js +27 -0
- package/dist/router.js +59 -4
- package/dist/segmented-lru.d.ts +19 -0
- package/dist/segmented-lru.js +87 -0
- package/dist/server-async.test.js +23 -1
- package/dist/server-handler.d.ts +165 -0
- package/dist/server-handler.js +1826 -0
- package/dist/server-handler.test.d.ts +1 -0
- package/dist/server-handler.test.js +522 -0
- package/dist/server-highlight.test.d.ts +1 -0
- package/dist/server-highlight.test.js +32 -0
- package/dist/server-renderer.js +146 -788
- package/dist/server-renderer.test.d.ts +1 -0
- package/dist/server-renderer.test.js +266 -0
- package/dist/server.d.ts +12 -1
- package/dist/server.js +42 -6
- package/dist/sha256.d.ts +1 -0
- package/dist/sha256.js +66 -0
- package/dist/sha256.test.d.ts +1 -0
- package/dist/sha256.test.js +13 -0
- package/dist/shared-isr.d.ts +31 -0
- package/dist/shared-isr.js +142 -0
- package/dist/signal.js +63 -8
- package/dist/ssr-core-behavior.test.d.ts +1 -0
- package/dist/ssr-core-behavior.test.js +620 -0
- package/dist/ssr-core.d.ts +175 -0
- package/dist/ssr-core.js +940 -0
- package/dist/ssr-core.test.d.ts +1 -0
- package/dist/ssr-core.test.js +324 -0
- package/dist/static-memory.d.ts +3 -0
- package/dist/static-memory.js +47 -0
- package/dist/static-memory.test.d.ts +1 -0
- package/dist/static-memory.test.js +26 -0
- package/dist/test-redis.d.ts +12 -0
- package/dist/test-redis.js +131 -0
- package/dist/use-id.d.ts +8 -0
- package/dist/use-id.js +40 -0
- package/package.json +29 -1
|
@@ -0,0 +1,579 @@
|
|
|
1
|
+
// Pure routing and URL helpers for the portable server handler. Everything
|
|
2
|
+
// here is a port of the Go host (internal/build: routematch.go, serve.go,
|
|
3
|
+
// serve_pages.go, serve_hardening.go), so `krate start` and the serverless
|
|
4
|
+
// targets decide identically. No Node or platform imports.
|
|
5
|
+
export function parseRoutePattern(pattern) {
|
|
6
|
+
const trimmed = trimSlashes(pattern);
|
|
7
|
+
if (trimmed === "" || trimmed === ".")
|
|
8
|
+
return [];
|
|
9
|
+
return trimmed.split("/").map(parseRouteSeg);
|
|
10
|
+
}
|
|
11
|
+
function parseRouteSeg(p) {
|
|
12
|
+
if (p.startsWith("[[...") && p.endsWith("]]") && p.length > 7)
|
|
13
|
+
return { kind: 3, text: p.slice(5, -2) };
|
|
14
|
+
if (p.startsWith("[...") && p.endsWith("]") && p.length > 5)
|
|
15
|
+
return { kind: 2, text: p.slice(4, -1) };
|
|
16
|
+
if (p.startsWith("[") && p.endsWith("]") && p.length > 2)
|
|
17
|
+
return { kind: 1, text: p.slice(1, -1) };
|
|
18
|
+
return { kind: 0, text: p };
|
|
19
|
+
}
|
|
20
|
+
export function trimSlashes(s) {
|
|
21
|
+
let a = 0;
|
|
22
|
+
let b = s.length;
|
|
23
|
+
while (a < b && s.charCodeAt(a) === 47)
|
|
24
|
+
a++;
|
|
25
|
+
while (b > a && s.charCodeAt(b - 1) === 47)
|
|
26
|
+
b--;
|
|
27
|
+
return s.slice(a, b);
|
|
28
|
+
}
|
|
29
|
+
export function isDynamicPattern(pattern) {
|
|
30
|
+
return parseRoutePattern(pattern).some((s) => s.kind !== 0);
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Matches a URL path against a route pattern. A param matches one non-empty
|
|
34
|
+
* segment; a catch-all one or more remaining segments, an optional catch-all
|
|
35
|
+
* zero or more. Catch-all values are the matched segments joined with "/".
|
|
36
|
+
*/
|
|
37
|
+
export function matchRoutePattern(urlPath, pattern) {
|
|
38
|
+
const segs = parseRoutePattern(pattern);
|
|
39
|
+
const trimmed = trimSlashes(urlPath);
|
|
40
|
+
const parts = trimmed === "" ? [] : trimmed.split("/");
|
|
41
|
+
const params = {};
|
|
42
|
+
for (let i = 0; i < segs.length; i++) {
|
|
43
|
+
const s = segs[i];
|
|
44
|
+
if (s.kind === 2 || s.kind === 3) {
|
|
45
|
+
if (i !== segs.length - 1)
|
|
46
|
+
return null;
|
|
47
|
+
const rest = parts.slice(Math.min(i, parts.length));
|
|
48
|
+
if (s.kind === 2 && rest.length === 0)
|
|
49
|
+
return null;
|
|
50
|
+
for (const r of rest)
|
|
51
|
+
if (r === "")
|
|
52
|
+
return null;
|
|
53
|
+
params[s.text] = rest.join("/");
|
|
54
|
+
return params;
|
|
55
|
+
}
|
|
56
|
+
if (i >= parts.length)
|
|
57
|
+
return null;
|
|
58
|
+
if (s.kind === 1) {
|
|
59
|
+
if (parts[i] === "")
|
|
60
|
+
return null;
|
|
61
|
+
params[s.text] = parts[i];
|
|
62
|
+
}
|
|
63
|
+
else if (parts[i] !== s.text) {
|
|
64
|
+
return null;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
if (parts.length !== segs.length)
|
|
68
|
+
return null;
|
|
69
|
+
return params;
|
|
70
|
+
}
|
|
71
|
+
function strCompare(a, b) {
|
|
72
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
73
|
+
}
|
|
74
|
+
/** Negative when a is more specific than b: static > param > catch-all > optional catch-all. */
|
|
75
|
+
export function compareRouteSpecificity(a, b) {
|
|
76
|
+
const sa = parseRoutePattern(a);
|
|
77
|
+
const sb = parseRoutePattern(b);
|
|
78
|
+
for (let i = 0; i < sa.length && i < sb.length; i++) {
|
|
79
|
+
if (sa[i].kind !== sb[i].kind)
|
|
80
|
+
return sa[i].kind - sb[i].kind;
|
|
81
|
+
if (sa[i].kind === 0 && sa[i].text !== sb[i].text)
|
|
82
|
+
return strCompare(sa[i].text, sb[i].text);
|
|
83
|
+
}
|
|
84
|
+
if (sa.length !== sb.length)
|
|
85
|
+
return sb.length - sa.length;
|
|
86
|
+
return strCompare(a, b);
|
|
87
|
+
}
|
|
88
|
+
export function normalizeRoutePattern(p) {
|
|
89
|
+
p = p.trim();
|
|
90
|
+
if (p === "")
|
|
91
|
+
return "/";
|
|
92
|
+
if (!p.startsWith("/"))
|
|
93
|
+
p = "/" + p;
|
|
94
|
+
if (p.length > 1)
|
|
95
|
+
p = p.replace(/\/+$/, "") || "/";
|
|
96
|
+
return p;
|
|
97
|
+
}
|
|
98
|
+
/** The route form used by the manifest: no trailing slash, "/" for the root. */
|
|
99
|
+
export function requestRoute(urlPath) {
|
|
100
|
+
const r = urlPath.replace(/\/+$/, "");
|
|
101
|
+
return r === "" ? "/" : r;
|
|
102
|
+
}
|
|
103
|
+
export function isFileLikePath(p) {
|
|
104
|
+
return baseName(p).includes(".");
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* The internal path a rewrite serves. Page URLs are canonical with a trailing
|
|
108
|
+
* slash and the slashless spelling answers 301, so a rewrite to "/feedback" would
|
|
109
|
+
* change the visible URL; the canonical form keeps it invisible. API routes,
|
|
110
|
+
* internal paths and file-like paths are left alone.
|
|
111
|
+
*/
|
|
112
|
+
export function rewriteTargetPath(p) {
|
|
113
|
+
if (p === "" || p === "/" || p.endsWith("/") || isFileLikePath(p))
|
|
114
|
+
return p;
|
|
115
|
+
if (p === "/api" || p.startsWith("/api/") || p.startsWith("/__krate/"))
|
|
116
|
+
return p;
|
|
117
|
+
return p + "/";
|
|
118
|
+
}
|
|
119
|
+
/** path.Base for slash paths. */
|
|
120
|
+
export function baseName(p) {
|
|
121
|
+
if (p === "")
|
|
122
|
+
return ".";
|
|
123
|
+
let end = p.length;
|
|
124
|
+
while (end > 0 && p[end - 1] === "/")
|
|
125
|
+
end--;
|
|
126
|
+
if (end === 0)
|
|
127
|
+
return "/";
|
|
128
|
+
const s = p.slice(0, end);
|
|
129
|
+
const i = s.lastIndexOf("/");
|
|
130
|
+
return i >= 0 ? s.slice(i + 1) : s;
|
|
131
|
+
}
|
|
132
|
+
export function isHTMLDocRequest(urlPath) {
|
|
133
|
+
return urlPath === "" || urlPath.endsWith("/") || urlPath.endsWith(".html");
|
|
134
|
+
}
|
|
135
|
+
/** path.Ext for slash paths. */
|
|
136
|
+
export function extName(p) {
|
|
137
|
+
for (let i = p.length - 1; i >= 0; i--) {
|
|
138
|
+
if (p[i] === ".")
|
|
139
|
+
return p.slice(i);
|
|
140
|
+
if (p[i] === "/")
|
|
141
|
+
return "";
|
|
142
|
+
}
|
|
143
|
+
return "";
|
|
144
|
+
}
|
|
145
|
+
/** path.Clean for slash paths. */
|
|
146
|
+
export function cleanPath(p) {
|
|
147
|
+
if (p === "")
|
|
148
|
+
return ".";
|
|
149
|
+
const rooted = p[0] === "/";
|
|
150
|
+
const out = [];
|
|
151
|
+
for (const seg of p.split("/")) {
|
|
152
|
+
if (seg === "" || seg === ".")
|
|
153
|
+
continue;
|
|
154
|
+
if (seg === "..") {
|
|
155
|
+
if (out.length > 0 && out[out.length - 1] !== "..")
|
|
156
|
+
out.pop();
|
|
157
|
+
else if (!rooted)
|
|
158
|
+
out.push("..");
|
|
159
|
+
continue;
|
|
160
|
+
}
|
|
161
|
+
out.push(seg);
|
|
162
|
+
}
|
|
163
|
+
const joined = out.join("/");
|
|
164
|
+
if (rooted)
|
|
165
|
+
return "/" + joined;
|
|
166
|
+
return joined === "" ? "." : joined;
|
|
167
|
+
}
|
|
168
|
+
function decodePath(p) {
|
|
169
|
+
try {
|
|
170
|
+
return decodeURIComponent(p);
|
|
171
|
+
}
|
|
172
|
+
catch {
|
|
173
|
+
return p;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
/** True for requests aimed at Krate's server-only output directory. */
|
|
177
|
+
export function isInternalOutputPath(urlPath) {
|
|
178
|
+
const p = cleanPath("/" + decodePath(urlPath).replace(/\\/g, "/"));
|
|
179
|
+
if (p === "/.krate" || p.startsWith("/.krate/"))
|
|
180
|
+
return true;
|
|
181
|
+
return p === "/server-manifest.json" || p === "/api-node" || p.startsWith("/api-node/");
|
|
182
|
+
}
|
|
183
|
+
export function isHiddenName(name) {
|
|
184
|
+
return name.startsWith(".") && name !== ".well-known" && name !== "." && name !== "..";
|
|
185
|
+
}
|
|
186
|
+
/** True when any segment of a (decoded) URL path is a dotfile name. */
|
|
187
|
+
export function isHiddenPath(urlPath) {
|
|
188
|
+
const decoded = decodePath(urlPath);
|
|
189
|
+
return decoded.split(/[/\\]/).filter(Boolean).some(isHiddenName);
|
|
190
|
+
}
|
|
191
|
+
// Redirect and rewrite rules
|
|
192
|
+
function splitURLPath(p) {
|
|
193
|
+
const t = trimSlashes(p);
|
|
194
|
+
return t === "" ? [] : t.split("/");
|
|
195
|
+
}
|
|
196
|
+
function splitParamModifier(name) {
|
|
197
|
+
const n = name.length;
|
|
198
|
+
if (n > 0) {
|
|
199
|
+
const c = name[n - 1];
|
|
200
|
+
if (c === "*" || c === "+" || c === "?")
|
|
201
|
+
return [name.slice(0, n - 1), c];
|
|
202
|
+
}
|
|
203
|
+
return [name, ""];
|
|
204
|
+
}
|
|
205
|
+
/**
|
|
206
|
+
* Matches a request path against a redirect/rewrite source: exact, a trailing
|
|
207
|
+
* "/*" wildcard (param "splat"), or named segments with the "*", "+" and "?"
|
|
208
|
+
* modifiers.
|
|
209
|
+
*/
|
|
210
|
+
export function matchRedirectParamsMods(path, source) {
|
|
211
|
+
const params = {};
|
|
212
|
+
const mods = {};
|
|
213
|
+
if (source === path)
|
|
214
|
+
return { params, mods };
|
|
215
|
+
if (!/[*:]/.test(source))
|
|
216
|
+
return null;
|
|
217
|
+
if (source.endsWith("/*")) {
|
|
218
|
+
const prefix = source.slice(0, -2);
|
|
219
|
+
if (path === prefix) {
|
|
220
|
+
params.splat = "";
|
|
221
|
+
return { params, mods };
|
|
222
|
+
}
|
|
223
|
+
if (!path.startsWith(prefix + "/"))
|
|
224
|
+
return null;
|
|
225
|
+
params.splat = path.slice(prefix.length).replace(/^\//, "");
|
|
226
|
+
return { params, mods };
|
|
227
|
+
}
|
|
228
|
+
const sourceParts = splitURLPath(source);
|
|
229
|
+
const pathParts = splitURLPath(path);
|
|
230
|
+
let pi = 0;
|
|
231
|
+
for (const part of sourceParts) {
|
|
232
|
+
if (part.startsWith(":")) {
|
|
233
|
+
const [name, mod] = splitParamModifier(part.slice(1));
|
|
234
|
+
mods[name] = mod;
|
|
235
|
+
switch (mod) {
|
|
236
|
+
case "*":
|
|
237
|
+
params[name] = pathParts.slice(pi).join("/");
|
|
238
|
+
return { params, mods };
|
|
239
|
+
case "+":
|
|
240
|
+
if (pi >= pathParts.length)
|
|
241
|
+
return null;
|
|
242
|
+
params[name] = pathParts.slice(pi).join("/");
|
|
243
|
+
return { params, mods };
|
|
244
|
+
case "?":
|
|
245
|
+
if (pi < pathParts.length) {
|
|
246
|
+
params[name] = pathParts[pi];
|
|
247
|
+
pi++;
|
|
248
|
+
}
|
|
249
|
+
else {
|
|
250
|
+
params[name] = "";
|
|
251
|
+
}
|
|
252
|
+
continue;
|
|
253
|
+
}
|
|
254
|
+
if (pi >= pathParts.length)
|
|
255
|
+
return null;
|
|
256
|
+
params[name] = pathParts[pi];
|
|
257
|
+
pi++;
|
|
258
|
+
continue;
|
|
259
|
+
}
|
|
260
|
+
if (pi >= pathParts.length || part !== pathParts[pi])
|
|
261
|
+
return null;
|
|
262
|
+
pi++;
|
|
263
|
+
}
|
|
264
|
+
if (pi !== pathParts.length)
|
|
265
|
+
return null;
|
|
266
|
+
return { params, mods };
|
|
267
|
+
}
|
|
268
|
+
export function matchRedirect(path, source) {
|
|
269
|
+
return matchRedirectParamsMods(path, source) !== null;
|
|
270
|
+
}
|
|
271
|
+
/** url.PathEscape of Go: segment-escapes everything but unreserved and $&+=:@. */
|
|
272
|
+
export function pathEscape(s) {
|
|
273
|
+
return encodeURIComponent(s)
|
|
274
|
+
.replace(/[!'()*]/g, (c) => "%" + c.charCodeAt(0).toString(16).toUpperCase())
|
|
275
|
+
.replace(/%(24|26|2B|3D|3A|40)/g, (_m, h) => String.fromCharCode(parseInt(h, 16)));
|
|
276
|
+
}
|
|
277
|
+
/** Percent-encodes a matched (decoded) value segment by segment, keeping "/" between segments. */
|
|
278
|
+
export function escapeRedirectValue(v) {
|
|
279
|
+
if (v === "")
|
|
280
|
+
return "";
|
|
281
|
+
return v.split("/").map(pathEscape).join("/");
|
|
282
|
+
}
|
|
283
|
+
function replaceDestParams(destination, params, mods) {
|
|
284
|
+
const re = /:([A-Za-z_][A-Za-z0-9_]*)/g;
|
|
285
|
+
let out = "";
|
|
286
|
+
let last = 0;
|
|
287
|
+
let m;
|
|
288
|
+
while ((m = re.exec(destination)) !== null) {
|
|
289
|
+
const name = m[1];
|
|
290
|
+
if (!Object.prototype.hasOwnProperty.call(params, name))
|
|
291
|
+
continue;
|
|
292
|
+
let end = m.index + m[0].length;
|
|
293
|
+
const mod = mods[name];
|
|
294
|
+
if (mod && end < destination.length && destination[end] === mod)
|
|
295
|
+
end++;
|
|
296
|
+
out += destination.slice(last, m.index) + escapeRedirectValue(params[name]);
|
|
297
|
+
last = end;
|
|
298
|
+
re.lastIndex = end;
|
|
299
|
+
}
|
|
300
|
+
return out + destination.slice(last);
|
|
301
|
+
}
|
|
302
|
+
/** Keeps a substituted path destination on-site (no "//host" or "/\\host" results). */
|
|
303
|
+
export function sanitizeRedirectTarget(configured, out) {
|
|
304
|
+
if (!configured.startsWith("/") || configured.startsWith("//") || configured.startsWith("/\\"))
|
|
305
|
+
return out;
|
|
306
|
+
out = out.replace(/[\u0000-\u001f\u007f]/g, (c) => "%" + c.charCodeAt(0).toString(16).toUpperCase().padStart(2, "0"));
|
|
307
|
+
const trimmed = out.replace(/^[/\\]+/, "");
|
|
308
|
+
return trimmed !== out ? "/" + trimmed : out;
|
|
309
|
+
}
|
|
310
|
+
/** Fills ":splat" and ":name" placeholders of a destination from the matched path. */
|
|
311
|
+
export function rewriteDestination(path, source, destination) {
|
|
312
|
+
const m = matchRedirectParamsMods(path, source);
|
|
313
|
+
if (!m)
|
|
314
|
+
return destination;
|
|
315
|
+
let out;
|
|
316
|
+
if (Object.prototype.hasOwnProperty.call(m.params, "splat")) {
|
|
317
|
+
const splat = m.params.splat;
|
|
318
|
+
if (destination.includes(":splat"))
|
|
319
|
+
out = destination.split(":splat").join(escapeRedirectValue(splat));
|
|
320
|
+
else if (splat !== "")
|
|
321
|
+
out = destination.replace(/\/+$/, "") + "/" + escapeRedirectValue(splat);
|
|
322
|
+
else
|
|
323
|
+
out = destination;
|
|
324
|
+
}
|
|
325
|
+
else {
|
|
326
|
+
out = replaceDestParams(destination, m.params, m.mods);
|
|
327
|
+
}
|
|
328
|
+
return sanitizeRedirectTarget(destination, out);
|
|
329
|
+
}
|
|
330
|
+
// Header rules
|
|
331
|
+
/** path.Match for slash paths: "*" and "?" do not cross "/", "[...]" classes. */
|
|
332
|
+
export function pathMatch(pattern, name) {
|
|
333
|
+
let re = "^";
|
|
334
|
+
for (let i = 0; i < pattern.length; i++) {
|
|
335
|
+
const c = pattern[i];
|
|
336
|
+
if (c === "*")
|
|
337
|
+
re += "[^/]*";
|
|
338
|
+
else if (c === "?")
|
|
339
|
+
re += "[^/]";
|
|
340
|
+
else if (c === "[") {
|
|
341
|
+
const end = pattern.indexOf("]", i + 1);
|
|
342
|
+
if (end < 0)
|
|
343
|
+
return false;
|
|
344
|
+
let cls = pattern.slice(i + 1, end);
|
|
345
|
+
let neg = false;
|
|
346
|
+
if (cls.startsWith("^")) {
|
|
347
|
+
neg = true;
|
|
348
|
+
cls = cls.slice(1);
|
|
349
|
+
}
|
|
350
|
+
re += "[" + (neg ? "^" : "") + cls.replace(/\\/g, "\\\\") + "]";
|
|
351
|
+
i = end;
|
|
352
|
+
}
|
|
353
|
+
else if (c === "\\" && i + 1 < pattern.length) {
|
|
354
|
+
re += pattern[++i].replace(/[.*+?^${}()|[\]\\/]/g, "\\$&");
|
|
355
|
+
}
|
|
356
|
+
else {
|
|
357
|
+
re += c.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&");
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
try {
|
|
361
|
+
return new RegExp(re + "$").test(name);
|
|
362
|
+
}
|
|
363
|
+
catch {
|
|
364
|
+
return false;
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
/** Exact path, trailing "*" prefix, or path.Match glob (config `headers[].source`). */
|
|
368
|
+
export function headerSourceMatches(pattern, p) {
|
|
369
|
+
pattern = pattern.trim();
|
|
370
|
+
if (pattern === "")
|
|
371
|
+
return false;
|
|
372
|
+
if (!pattern.includes("*"))
|
|
373
|
+
return p === pattern;
|
|
374
|
+
if (pattern.endsWith("*"))
|
|
375
|
+
return p.startsWith(pattern.slice(0, -1));
|
|
376
|
+
return pathMatch(pattern, p);
|
|
377
|
+
}
|
|
378
|
+
// Dynamic SSG templates
|
|
379
|
+
export const DYNAMIC_PARAM_PREFIX = "__KRATE_PARAM_";
|
|
380
|
+
export function dynamicParamSentinel(name) {
|
|
381
|
+
return DYNAMIC_PARAM_PREFIX + name + "__";
|
|
382
|
+
}
|
|
383
|
+
const htmlEscapes = { "&": "&", "<": "<", ">": ">", '"': """, "'": "'" };
|
|
384
|
+
/** Go's html.EscapeString (used for dynamic template params). */
|
|
385
|
+
export function goHTMLEscape(s) {
|
|
386
|
+
return s.replace(/[&<>"']/g, (c) => htmlEscapes[c]);
|
|
387
|
+
}
|
|
388
|
+
/** escape.HTML of the compiler: & < > " ' */
|
|
389
|
+
export function escapeHTML(s) {
|
|
390
|
+
return s.replace(/[&<>"']/g, (c) => (c === '"' ? """ : htmlEscapes[c]));
|
|
391
|
+
}
|
|
392
|
+
/**
|
|
393
|
+
* Renders a dynamic-route template for one request: injects the matched params
|
|
394
|
+
* for client-side access and replaces every build-time sentinel.
|
|
395
|
+
*/
|
|
396
|
+
export function applyDynamicRouteParams(templateHTML, params) {
|
|
397
|
+
const injectScript = "<script>window.__KRATE_PARAMS__=" + goJSON(params) + "</script>";
|
|
398
|
+
const at = templateHTML.indexOf("</head>");
|
|
399
|
+
let out = at < 0 ? templateHTML : templateHTML.slice(0, at) + injectScript + templateHTML.slice(at);
|
|
400
|
+
for (const [name, value] of Object.entries(params)) {
|
|
401
|
+
out = out.split(dynamicParamSentinel(name)).join(goHTMLEscape(value));
|
|
402
|
+
}
|
|
403
|
+
return out;
|
|
404
|
+
}
|
|
405
|
+
/** json.Marshal of a string map: sorted keys, HTML-significant characters escaped. */
|
|
406
|
+
export function goJSON(obj) {
|
|
407
|
+
const keys = Object.keys(obj).sort();
|
|
408
|
+
const enc = (s) => JSON.stringify(s)
|
|
409
|
+
.replace(/</g, "\\u003c")
|
|
410
|
+
.replace(/>/g, "\\u003e")
|
|
411
|
+
.replace(/&/g, "\\u0026")
|
|
412
|
+
.replace(/\u2028/g, "\\u2028")
|
|
413
|
+
.replace(/\u2029/g, "\\u2029");
|
|
414
|
+
return "{" + keys.map((k) => enc(k) + ":" + enc(obj[k])).join(",") + "}";
|
|
415
|
+
}
|
|
416
|
+
// Hashed assets
|
|
417
|
+
export function staticCacheControl(urlPath, hashed) {
|
|
418
|
+
if (hashed.has(urlPath))
|
|
419
|
+
return "public, max-age=31536000, immutable";
|
|
420
|
+
return "no-cache";
|
|
421
|
+
}
|
|
422
|
+
// Middleware matcher (path-to-regexp subset), shared with the Go runtimes
|
|
423
|
+
export function compileMatcher(src) {
|
|
424
|
+
if (typeof src !== "string")
|
|
425
|
+
throw new Error("middleware matcher must be a string or { source }");
|
|
426
|
+
if (src.charAt(0) !== "/")
|
|
427
|
+
throw new Error('middleware matcher "' + src + '" must start with "/"');
|
|
428
|
+
let out = "";
|
|
429
|
+
let i = 0;
|
|
430
|
+
const n = src.length;
|
|
431
|
+
const esc = (c) => c.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&");
|
|
432
|
+
while (i < n) {
|
|
433
|
+
let c = src.charAt(i);
|
|
434
|
+
let prefix = "";
|
|
435
|
+
if ((c === "/" || c === ".") && i + 1 < n && (src.charAt(i + 1) === ":" || src.charAt(i + 1) === "(")) {
|
|
436
|
+
prefix = c;
|
|
437
|
+
i++;
|
|
438
|
+
c = src.charAt(i);
|
|
439
|
+
}
|
|
440
|
+
if (c === ":" || c === "(") {
|
|
441
|
+
let pattern = "";
|
|
442
|
+
if (c === ":") {
|
|
443
|
+
let j = i + 1;
|
|
444
|
+
while (j < n && /[A-Za-z0-9_]/.test(src.charAt(j)))
|
|
445
|
+
j++;
|
|
446
|
+
i = j;
|
|
447
|
+
if (src.charAt(i) === "(") {
|
|
448
|
+
let depth = 0;
|
|
449
|
+
let k = i;
|
|
450
|
+
for (; k < n; k++) {
|
|
451
|
+
const ch = src.charAt(k);
|
|
452
|
+
if (ch === "\\") {
|
|
453
|
+
k++;
|
|
454
|
+
continue;
|
|
455
|
+
}
|
|
456
|
+
if (ch === "(")
|
|
457
|
+
depth++;
|
|
458
|
+
else if (ch === ")") {
|
|
459
|
+
depth--;
|
|
460
|
+
if (depth === 0)
|
|
461
|
+
break;
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
pattern = src.slice(i + 1, k);
|
|
465
|
+
i = k + 1;
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
else {
|
|
469
|
+
let depth2 = 0;
|
|
470
|
+
let k2 = i;
|
|
471
|
+
for (; k2 < n; k2++) {
|
|
472
|
+
const ch2 = src.charAt(k2);
|
|
473
|
+
if (ch2 === "\\") {
|
|
474
|
+
k2++;
|
|
475
|
+
continue;
|
|
476
|
+
}
|
|
477
|
+
if (ch2 === "(")
|
|
478
|
+
depth2++;
|
|
479
|
+
else if (ch2 === ")") {
|
|
480
|
+
depth2--;
|
|
481
|
+
if (depth2 === 0)
|
|
482
|
+
break;
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
pattern = src.slice(i + 1, k2);
|
|
486
|
+
i = k2 + 1;
|
|
487
|
+
}
|
|
488
|
+
let mod = src.charAt(i);
|
|
489
|
+
if (mod === "*" || mod === "+" || mod === "?")
|
|
490
|
+
i++;
|
|
491
|
+
else
|
|
492
|
+
mod = "";
|
|
493
|
+
const body = pattern || "[^\\/]+?";
|
|
494
|
+
const p = prefix ? esc(prefix) : "";
|
|
495
|
+
if (mod === "*")
|
|
496
|
+
out += "(?:" + p + "(" + body + "(?:" + esc(prefix || "/") + body + ")*))?";
|
|
497
|
+
else if (mod === "+")
|
|
498
|
+
out += p + "(" + body + "(?:" + esc(prefix || "/") + body + ")*)";
|
|
499
|
+
else if (mod === "?")
|
|
500
|
+
out += "(?:" + p + "(" + body + "))?";
|
|
501
|
+
else
|
|
502
|
+
out += p + "(" + body + ")";
|
|
503
|
+
continue;
|
|
504
|
+
}
|
|
505
|
+
if (c === "*") {
|
|
506
|
+
out += ".*";
|
|
507
|
+
i++;
|
|
508
|
+
continue;
|
|
509
|
+
}
|
|
510
|
+
out += esc(c);
|
|
511
|
+
i++;
|
|
512
|
+
}
|
|
513
|
+
return new RegExp("^" + out + "\\/?$", "i");
|
|
514
|
+
}
|
|
515
|
+
// Go http.Redirect
|
|
516
|
+
function hexEscapeNonASCII(s) {
|
|
517
|
+
let out = "";
|
|
518
|
+
const bytes = new TextEncoder().encode(s);
|
|
519
|
+
let ascii = true;
|
|
520
|
+
for (const b of bytes)
|
|
521
|
+
if (b >= 0x80)
|
|
522
|
+
ascii = false;
|
|
523
|
+
if (ascii)
|
|
524
|
+
return s;
|
|
525
|
+
for (const b of bytes)
|
|
526
|
+
out += b >= 0x80 ? "%" + b.toString(16).toUpperCase().padStart(2, "0") : String.fromCharCode(b);
|
|
527
|
+
return out;
|
|
528
|
+
}
|
|
529
|
+
const statusText = {
|
|
530
|
+
301: "Moved Permanently",
|
|
531
|
+
302: "Found",
|
|
532
|
+
303: "See Other",
|
|
533
|
+
307: "Temporary Redirect",
|
|
534
|
+
308: "Permanent Redirect",
|
|
535
|
+
};
|
|
536
|
+
/**
|
|
537
|
+
* Builds the response http.Redirect writes: a relative target is resolved
|
|
538
|
+
* against the request path and cleaned, Location is escaped, and a GET gets a
|
|
539
|
+
* small HTML body.
|
|
540
|
+
*/
|
|
541
|
+
export function goRedirect(target, requestPath, method, status, extra) {
|
|
542
|
+
let url = target;
|
|
543
|
+
let hasScheme = false;
|
|
544
|
+
try {
|
|
545
|
+
const u = new URL(target);
|
|
546
|
+
hasScheme = u.protocol !== "" && /^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(target);
|
|
547
|
+
}
|
|
548
|
+
catch {
|
|
549
|
+
hasScheme = false;
|
|
550
|
+
}
|
|
551
|
+
const schemeRelative = target.startsWith("//");
|
|
552
|
+
if (!hasScheme && !schemeRelative) {
|
|
553
|
+
const oldpath = requestPath === "" ? "/" : requestPath;
|
|
554
|
+
if (url === "" || url[0] !== "/") {
|
|
555
|
+
const slash = oldpath.lastIndexOf("/");
|
|
556
|
+
url = oldpath.slice(0, slash + 1) + url;
|
|
557
|
+
}
|
|
558
|
+
let query = "";
|
|
559
|
+
const qi = url.indexOf("?");
|
|
560
|
+
if (qi !== -1) {
|
|
561
|
+
query = url.slice(qi);
|
|
562
|
+
url = url.slice(0, qi);
|
|
563
|
+
}
|
|
564
|
+
const trailing = url.endsWith("/");
|
|
565
|
+
url = cleanPath(url);
|
|
566
|
+
if (trailing && !url.endsWith("/"))
|
|
567
|
+
url += "/";
|
|
568
|
+
url += query;
|
|
569
|
+
}
|
|
570
|
+
const headers = extra ? new Headers(extra) : new Headers();
|
|
571
|
+
const hadCT = headers.has("content-type");
|
|
572
|
+
headers.set("Location", hexEscapeNonASCII(url));
|
|
573
|
+
if (!hadCT && (method === "GET" || method === "HEAD"))
|
|
574
|
+
headers.set("Content-Type", "text/html; charset=utf-8");
|
|
575
|
+
let body = null;
|
|
576
|
+
if (!hadCT && method === "GET")
|
|
577
|
+
body = "<a href=\"" + goHTMLEscape(headers.get("Location")) + "\">" + (statusText[status] || "") + "</a>.\n\n";
|
|
578
|
+
return new Response(body, { status, headers });
|
|
579
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { describe, expect, it } from "vitest";
|
|
2
|
+
import { applyDynamicRouteParams, compareRouteSpecificity, compileMatcher, goRedirect, headerSourceMatches, isHiddenPath, isInternalOutputPath, matchRedirect, matchRoutePattern, rewriteDestination, } from "./handler-routing.js";
|
|
3
|
+
// The vectors below are copied from the Go host's tests (internal/build
|
|
4
|
+
// serve_test.go, serve_security_test.go, routematch tests) so the portable
|
|
5
|
+
// handler decides like `krate start`.
|
|
6
|
+
describe("redirect matching", () => {
|
|
7
|
+
const cases = [
|
|
8
|
+
["/old", "/old", true],
|
|
9
|
+
["/old", "/old/", false],
|
|
10
|
+
["/old/page", "/old", false],
|
|
11
|
+
["/old/page", "/old/*", true],
|
|
12
|
+
["/old", "/old/*", true],
|
|
13
|
+
["/oldpage", "/old/*", false],
|
|
14
|
+
["/old/", "/old/*", true],
|
|
15
|
+
["/old//double", "/old/*", true],
|
|
16
|
+
["/a", "/b", false],
|
|
17
|
+
];
|
|
18
|
+
for (const [path, source, want] of cases) {
|
|
19
|
+
it(`${path} ~ ${source}`, () => expect(matchRedirect(path, source)).toBe(want));
|
|
20
|
+
}
|
|
21
|
+
});
|
|
22
|
+
describe("rewriteDestination", () => {
|
|
23
|
+
const cases = [
|
|
24
|
+
["/legacy//evil.com", "/legacy/*", "/:splat", "/evil.com"],
|
|
25
|
+
["/legacy/\\evil.com", "/legacy/*", "/:splat", "/%5Cevil.com"],
|
|
26
|
+
["/u/\\\\evil.com", "/u/:name", "/:name", "/%5C%5Cevil.com"],
|
|
27
|
+
["/legacy/https://evil.com", "/legacy/*", "/:splat", "/https://evil.com"],
|
|
28
|
+
["/legacy/a\nb", "/legacy/*", "/x/:splat", "/x/a%0Ab"],
|
|
29
|
+
["/old/\\evil.com", "/old/*", "/new", "/new/%5Cevil.com"],
|
|
30
|
+
["/go/x", "/go/*", "https://example.com/:splat", "https://example.com/x"],
|
|
31
|
+
["/go/x", "/go/*", "//cdn.example.com/:splat", "//cdn.example.com/x"],
|
|
32
|
+
["/legacy/a b", "/legacy/*", "/new/:splat", "/new/a%20b"],
|
|
33
|
+
["/docs/a/b", "/docs/:path*", "/documentation/:path*", "/documentation/a/b"],
|
|
34
|
+
["/docs", "/docs/:path*", "/documentation/:path*", "/documentation/"],
|
|
35
|
+
["/docs/a", "/docs/:slug?", "/documentation/:slug?", "/documentation/a"],
|
|
36
|
+
["/p/7", "/p/:id", "/item/:id?ref=1", "/item/7?ref=1"],
|
|
37
|
+
["/u/bob", "/u/:name", "/:name", "/bob"],
|
|
38
|
+
["/old", "/old", "/new", "/new"],
|
|
39
|
+
];
|
|
40
|
+
for (const [path, source, dest, want] of cases) {
|
|
41
|
+
it(`${path} ${source} -> ${dest}`, () => expect(rewriteDestination(path, source, dest)).toBe(want));
|
|
42
|
+
}
|
|
43
|
+
it("rejects non-matching optional/plus forms", () => {
|
|
44
|
+
expect(matchRedirect("/docs", "/docs/:path+")).toBe(false);
|
|
45
|
+
expect(matchRedirect("/docs/a/b", "/docs/:slug?")).toBe(false);
|
|
46
|
+
});
|
|
47
|
+
});
|
|
48
|
+
describe("route patterns", () => {
|
|
49
|
+
it("matches params and catch-alls", () => {
|
|
50
|
+
expect(matchRoutePattern("/blog/x", "blog/[slug]")).toEqual({ slug: "x" });
|
|
51
|
+
expect(matchRoutePattern("/docs/a/b", "docs/[...rest]")).toEqual({ rest: "a/b" });
|
|
52
|
+
expect(matchRoutePattern("/docs", "docs/[...rest]")).toBeNull();
|
|
53
|
+
expect(matchRoutePattern("/shop", "shop/[[...filter]]")).toEqual({ filter: "" });
|
|
54
|
+
expect(matchRoutePattern("/blog", "blog/[slug]")).toBeNull();
|
|
55
|
+
});
|
|
56
|
+
it("orders by specificity: static > param > catch-all > optional catch-all", () => {
|
|
57
|
+
const routes = ["/a/[[...x]]", "/a/[...x]", "/a/[x]", "/a/b"];
|
|
58
|
+
expect([...routes].sort(compareRouteSpecificity)).toEqual(["/a/b", "/a/[x]", "/a/[...x]", "/a/[[...x]]"]);
|
|
59
|
+
});
|
|
60
|
+
});
|
|
61
|
+
describe("paths and headers", () => {
|
|
62
|
+
it("hides internal and dot paths", () => {
|
|
63
|
+
for (const p of ["/api-node/hello.js", "/server-manifest.json", "/%61pi-node/x.js", "/.krate/x", "/a/../.krate/x"]) {
|
|
64
|
+
expect(isInternalOutputPath(p)).toBe(true);
|
|
65
|
+
}
|
|
66
|
+
for (const p of ["/manifest.json", "/api/hello", "/api-nodes/x"])
|
|
67
|
+
expect(isInternalOutputPath(p)).toBe(false);
|
|
68
|
+
expect(isHiddenPath("/.env")).toBe(true);
|
|
69
|
+
expect(isHiddenPath("/.well-known/acme")).toBe(false);
|
|
70
|
+
expect(isHiddenPath("/a/%2eenv")).toBe(true);
|
|
71
|
+
});
|
|
72
|
+
it("matches header sources", () => {
|
|
73
|
+
expect(headerSourceMatches("/about", "/about")).toBe(true);
|
|
74
|
+
expect(headerSourceMatches("/assets/*", "/assets/a/b.js")).toBe(true);
|
|
75
|
+
expect(headerSourceMatches("/a/*/c", "/a/b/c")).toBe(true);
|
|
76
|
+
expect(headerSourceMatches("/a/*/c", "/a/b/d/c")).toBe(false);
|
|
77
|
+
});
|
|
78
|
+
it("compiles the middleware matcher like the Go runtimes", () => {
|
|
79
|
+
expect(compileMatcher("/api/:path*").test("/api/x/y")).toBe(true);
|
|
80
|
+
expect(compileMatcher("/api/:path*").test("/other")).toBe(false);
|
|
81
|
+
expect(compileMatcher("/admin").test("/admin/")).toBe(true);
|
|
82
|
+
expect(() => compileMatcher("nope")).toThrow(/start with/);
|
|
83
|
+
});
|
|
84
|
+
});
|
|
85
|
+
describe("templates and redirects", () => {
|
|
86
|
+
it("substitutes sentinels and injects params", () => {
|
|
87
|
+
const html = applyDynamicRouteParams("<head></head><p>__KRATE_PARAM_slug__</p>", { slug: "a<b" });
|
|
88
|
+
expect(html).toContain("<p>a<b</p>");
|
|
89
|
+
expect(html).toContain('<script>window.__KRATE_PARAMS__={"slug":"a\\u003cb"}</script></head>');
|
|
90
|
+
});
|
|
91
|
+
it("builds http.Redirect responses", async () => {
|
|
92
|
+
const r = goRedirect("/about", "/old", "GET", 301);
|
|
93
|
+
expect(r.status).toBe(301);
|
|
94
|
+
expect(r.headers.get("location")).toBe("/about");
|
|
95
|
+
expect(await r.text()).toBe('<a href="/about">Moved Permanently</a>.\n\n');
|
|
96
|
+
expect(await goRedirect("rel", "/a/b", "GET", 302).headers.get("location")).toBe("/a/rel");
|
|
97
|
+
expect(goRedirect("/x", "/y", "HEAD", 302).headers.get("content-type")).toContain("text/html");
|
|
98
|
+
});
|
|
99
|
+
});
|