@krate/runtime 0.5.0-rc.6 → 0.5.0-rc.7

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.
@@ -37,29 +37,6 @@ export declare function isInternalOutputPath(urlPath: string): boolean;
37
37
  export declare function isHiddenName(name: string): boolean;
38
38
  /** True when any segment of a (decoded) URL path is a dotfile name. */
39
39
  export declare function isHiddenPath(urlPath: string): boolean;
40
- export interface RuleMatch {
41
- params: Record<string, string>;
42
- mods: Record<string, string>;
43
- }
44
- /**
45
- * Matches a request path against a redirect/rewrite source: exact, a trailing
46
- * "/*" wildcard (param "splat"), or named segments with the "*", "+" and "?"
47
- * modifiers.
48
- */
49
- export declare function matchRedirectParamsMods(path: string, source: string): RuleMatch | null;
50
- export declare function matchRedirect(path: string, source: string): boolean;
51
- /** url.PathEscape of Go: segment-escapes everything but unreserved and $&+=:@. */
52
- export declare function pathEscape(s: string): string;
53
- /** Percent-encodes a matched (decoded) value segment by segment, keeping "/" between segments. */
54
- export declare function escapeRedirectValue(v: string): string;
55
- /** Keeps a substituted path destination on-site (no "//host" or "/\\host" results). */
56
- export declare function sanitizeRedirectTarget(configured: string, out: string): string;
57
- /** Fills ":splat" and ":name" placeholders of a destination from the matched path. */
58
- export declare function rewriteDestination(path: string, source: string, destination: string): string;
59
- /** path.Match for slash paths: "*" and "?" do not cross "/", "[...]" classes. */
60
- export declare function pathMatch(pattern: string, name: string): boolean;
61
- /** Exact path, trailing "*" prefix, or path.Match glob (config `headers[].source`). */
62
- export declare function headerSourceMatches(pattern: string, p: string): boolean;
63
40
  export declare const DYNAMIC_PARAM_PREFIX = "__KRATE_PARAM_";
64
41
  export declare function dynamicParamSentinel(name: string): string;
65
42
  /** Go's html.EscapeString (used for dynamic template params). */
@@ -73,6 +50,8 @@ export declare function escapeHTML(s: string): string;
73
50
  export declare function applyDynamicRouteParams(templateHTML: string, params: Record<string, string>): string;
74
51
  /** json.Marshal of a string map: sorted keys, HTML-significant characters escaped. */
75
52
  export declare function goJSON(obj: Record<string, string>): string;
53
+ /** Cache-Control of a content-hashed asset; a user headers rule never replaces it. */
54
+ export declare const IMMUTABLE_CACHE_CONTROL = "public, max-age=31536000, immutable";
76
55
  export declare function staticCacheControl(urlPath: string, hashed: ReadonlySet<string>): string;
77
56
  export declare function compileMatcher(src: unknown): RegExp;
78
57
  /**
@@ -191,193 +191,7 @@ export function isHiddenPath(urlPath) {
191
191
  const decoded = decodePath(urlPath);
192
192
  return decoded.split(/[/\\]/).filter(Boolean).some(isHiddenName);
193
193
  }
194
- // Redirect and rewrite rules
195
- function splitURLPath(p) {
196
- const t = trimSlashes(p);
197
- return t === "" ? [] : t.split("/");
198
- }
199
- function splitParamModifier(name) {
200
- const n = name.length;
201
- if (n > 0) {
202
- const c = name[n - 1];
203
- if (c === "*" || c === "+" || c === "?")
204
- return [name.slice(0, n - 1), c];
205
- }
206
- return [name, ""];
207
- }
208
- /**
209
- * Matches a request path against a redirect/rewrite source: exact, a trailing
210
- * "/*" wildcard (param "splat"), or named segments with the "*", "+" and "?"
211
- * modifiers.
212
- */
213
- export function matchRedirectParamsMods(path, source) {
214
- const params = {};
215
- const mods = {};
216
- if (source === path)
217
- return { params, mods };
218
- if (!/[*:]/.test(source))
219
- return null;
220
- if (source.endsWith("/*")) {
221
- const prefix = source.slice(0, -2);
222
- if (path === prefix) {
223
- params.splat = "";
224
- return { params, mods };
225
- }
226
- if (!path.startsWith(prefix + "/"))
227
- return null;
228
- params.splat = path.slice(prefix.length).replace(/^\//, "");
229
- return { params, mods };
230
- }
231
- const sourceParts = splitURLPath(source);
232
- const pathParts = splitURLPath(path);
233
- let pi = 0;
234
- for (const part of sourceParts) {
235
- if (part.startsWith(":")) {
236
- const [name, mod] = splitParamModifier(part.slice(1));
237
- mods[name] = mod;
238
- switch (mod) {
239
- case "*":
240
- params[name] = pathParts.slice(pi).join("/");
241
- return { params, mods };
242
- case "+":
243
- if (pi >= pathParts.length)
244
- return null;
245
- params[name] = pathParts.slice(pi).join("/");
246
- return { params, mods };
247
- case "?":
248
- if (pi < pathParts.length) {
249
- params[name] = pathParts[pi];
250
- pi++;
251
- }
252
- else {
253
- params[name] = "";
254
- }
255
- continue;
256
- }
257
- if (pi >= pathParts.length)
258
- return null;
259
- params[name] = pathParts[pi];
260
- pi++;
261
- continue;
262
- }
263
- if (pi >= pathParts.length || part !== pathParts[pi])
264
- return null;
265
- pi++;
266
- }
267
- if (pi !== pathParts.length)
268
- return null;
269
- return { params, mods };
270
- }
271
- export function matchRedirect(path, source) {
272
- return matchRedirectParamsMods(path, source) !== null;
273
- }
274
- /** url.PathEscape of Go: segment-escapes everything but unreserved and $&+=:@. */
275
- export function pathEscape(s) {
276
- return encodeURIComponent(s)
277
- .replace(/[!'()*]/g, (c) => "%" + c.charCodeAt(0).toString(16).toUpperCase())
278
- .replace(/%(24|26|2B|3D|3A|40)/g, (_m, h) => String.fromCharCode(parseInt(h, 16)));
279
- }
280
- /** Percent-encodes a matched (decoded) value segment by segment, keeping "/" between segments. */
281
- export function escapeRedirectValue(v) {
282
- if (v === "")
283
- return "";
284
- return v.split("/").map(pathEscape).join("/");
285
- }
286
- function replaceDestParams(destination, params, mods) {
287
- const re = /:([A-Za-z_][A-Za-z0-9_]*)/g;
288
- let out = "";
289
- let last = 0;
290
- let m;
291
- while ((m = re.exec(destination)) !== null) {
292
- const name = m[1];
293
- if (!Object.prototype.hasOwnProperty.call(params, name))
294
- continue;
295
- let end = m.index + m[0].length;
296
- const mod = mods[name];
297
- if (mod && end < destination.length && destination[end] === mod)
298
- end++;
299
- out += destination.slice(last, m.index) + escapeRedirectValue(params[name]);
300
- last = end;
301
- re.lastIndex = end;
302
- }
303
- return out + destination.slice(last);
304
- }
305
- /** Keeps a substituted path destination on-site (no "//host" or "/\\host" results). */
306
- export function sanitizeRedirectTarget(configured, out) {
307
- if (!configured.startsWith("/") || configured.startsWith("//") || configured.startsWith("/\\"))
308
- return out;
309
- out = out.replace(/[\u0000-\u001f\u007f]/g, (c) => "%" + c.charCodeAt(0).toString(16).toUpperCase().padStart(2, "0"));
310
- const trimmed = out.replace(/^[/\\]+/, "");
311
- return trimmed !== out ? "/" + trimmed : out;
312
- }
313
- /** Fills ":splat" and ":name" placeholders of a destination from the matched path. */
314
- export function rewriteDestination(path, source, destination) {
315
- const m = matchRedirectParamsMods(path, source);
316
- if (!m)
317
- return destination;
318
- let out;
319
- if (Object.prototype.hasOwnProperty.call(m.params, "splat")) {
320
- const splat = m.params.splat;
321
- if (destination.includes(":splat"))
322
- out = destination.split(":splat").join(escapeRedirectValue(splat));
323
- else if (splat !== "")
324
- out = destination.replace(/\/+$/, "") + "/" + escapeRedirectValue(splat);
325
- else
326
- out = destination;
327
- }
328
- else {
329
- out = replaceDestParams(destination, m.params, m.mods);
330
- }
331
- return sanitizeRedirectTarget(destination, out);
332
- }
333
- // Header rules
334
- /** path.Match for slash paths: "*" and "?" do not cross "/", "[...]" classes. */
335
- export function pathMatch(pattern, name) {
336
- let re = "^";
337
- for (let i = 0; i < pattern.length; i++) {
338
- const c = pattern[i];
339
- if (c === "*")
340
- re += "[^/]*";
341
- else if (c === "?")
342
- re += "[^/]";
343
- else if (c === "[") {
344
- const end = pattern.indexOf("]", i + 1);
345
- if (end < 0)
346
- return false;
347
- let cls = pattern.slice(i + 1, end);
348
- let neg = false;
349
- if (cls.startsWith("^")) {
350
- neg = true;
351
- cls = cls.slice(1);
352
- }
353
- re += "[" + (neg ? "^" : "") + cls.replace(/\\/g, "\\\\") + "]";
354
- i = end;
355
- }
356
- else if (c === "\\" && i + 1 < pattern.length) {
357
- re += pattern[++i].replace(/[.*+?^${}()|[\]\\/]/g, "\\$&");
358
- }
359
- else {
360
- re += c.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&");
361
- }
362
- }
363
- try {
364
- return new RegExp(re + "$").test(name);
365
- }
366
- catch {
367
- return false;
368
- }
369
- }
370
- /** Exact path, trailing "*" prefix, or path.Match glob (config `headers[].source`). */
371
- export function headerSourceMatches(pattern, p) {
372
- pattern = pattern.trim();
373
- if (pattern === "")
374
- return false;
375
- if (!pattern.includes("*"))
376
- return p === pattern;
377
- if (pattern.endsWith("*"))
378
- return p.startsWith(pattern.slice(0, -1));
379
- return pathMatch(pattern, p);
380
- }
194
+ // Redirect, rewrite and header rule matching lives in route-source.ts.
381
195
  // Dynamic SSG templates
382
196
  export const DYNAMIC_PARAM_PREFIX = "__KRATE_PARAM_";
383
197
  export function dynamicParamSentinel(name) {
@@ -417,9 +231,11 @@ export function goJSON(obj) {
417
231
  return "{" + keys.map((k) => enc(k) + ":" + enc(obj[k])).join(",") + "}";
418
232
  }
419
233
  // Hashed assets
234
+ /** Cache-Control of a content-hashed asset; a user headers rule never replaces it. */
235
+ export const IMMUTABLE_CACHE_CONTROL = "public, max-age=31536000, immutable";
420
236
  export function staticCacheControl(urlPath, hashed) {
421
237
  if (hashed.has(urlPath))
422
- return "public, max-age=31536000, immutable";
238
+ return IMMUTABLE_CACHE_CONTROL;
423
239
  return "no-cache";
424
240
  }
425
241
  // Middleware matcher (path-to-regexp subset), shared with the Go runtimes
package/dist/head-tags.js CHANGED
@@ -218,8 +218,11 @@ export function headKey(el) {
218
218
  if (el.name === "meta") {
219
219
  if (a.has("charset"))
220
220
  return "meta:charset";
221
- if (a.has("name"))
222
- return "meta:name:" + (a.get("name") || "").toLowerCase();
221
+ if (a.has("name")) {
222
+ // A media-qualified tag (light and dark theme-color) is a different tag.
223
+ const media = (a.get("media") || "").toLowerCase();
224
+ return "meta:name:" + (a.get("name") || "").toLowerCase() + (media ? "|" + media : "");
225
+ }
223
226
  if (a.has("property"))
224
227
  return "meta:property:" + (a.get("property") || "").toLowerCase();
225
228
  if (a.has("http-equiv"))
@@ -4,8 +4,9 @@
4
4
  * (rule lists with JavaScript regular expressions); this file runs them. It
5
5
  * follows chroma's RegexLexer state machine and its HTML formatter, so for the
6
6
  * same code and language the markup is identical to what a build produces:
7
- * one `<span class="line"><span class="cl">` per line and one classed span per
8
- * token, coloured by the same stylesheet in light and dark.
7
+ * one classed span per token (wrapped in a `<span class="line hl">` only for
8
+ * lines marked for highlighting), coloured by the same stylesheet in light and
9
+ * dark.
9
10
  *
10
11
  * Nothing here touches the DOM or any global, so it runs unchanged on the
11
12
  * server (SSR sidecars) and in the browser.
package/dist/highlight.js CHANGED
@@ -4,8 +4,9 @@
4
4
  * (rule lists with JavaScript regular expressions); this file runs them. It
5
5
  * follows chroma's RegexLexer state machine and its HTML formatter, so for the
6
6
  * same code and language the markup is identical to what a build produces:
7
- * one `<span class="line"><span class="cl">` per line and one classed span per
8
- * token, coloured by the same stylesheet in light and dark.
7
+ * one classed span per token (wrapped in a `<span class="line hl">` only for
8
+ * lines marked for highlighting), coloured by the same stylesheet in light and
9
+ * dark.
9
10
  *
10
11
  * Nothing here touches the DOM or any global, so it runs unchanged on the
11
12
  * server (SSR sidecars) and in the browser.
@@ -303,19 +304,24 @@ function shouldHighlight(ranges, idx, line) {
303
304
  /** Writes tokens as chroma's HTML formatter does (class mode, no line numbers). */
304
305
  function format(tokens, ranges) {
305
306
  const lines = splitLines(tokens);
307
+ // Line wrappers only carry the highlight class, so unmarked code omits them.
308
+ const wrap = ranges.length > 0;
306
309
  let html = "";
307
310
  let idx = 0;
308
311
  for (let i = 0; i < lines.length; i++) {
309
- const [hl, next] = shouldHighlight(ranges, idx, i + 1);
310
- idx = next;
311
- html += hl ? '<span class="line hl"><span class="cl">' : '<span class="line"><span class="cl">';
312
+ if (wrap) {
313
+ const [hl, next] = shouldHighlight(ranges, idx, i + 1);
314
+ idx = next;
315
+ html += hl ? '<span class="line hl"><span class="cl">' : '<span class="line"><span class="cl">';
316
+ }
312
317
  for (const [cls, value] of lines[i]) {
313
318
  if (cls === null)
314
319
  continue;
315
320
  const text = escapeHTML(value);
316
321
  html += cls === "" ? text : '<span class="' + cls + '">' + text + "</span>";
317
322
  }
318
- html += "</span></span>";
323
+ if (wrap)
324
+ html += "</span></span>";
319
325
  }
320
326
  return html;
321
327
  }
@@ -0,0 +1,45 @@
1
+ /** A server-children slot a Preact island adopted from the document. */
2
+ export interface IslandSlot {
3
+ id: string;
4
+ /** The slot's server HTML (outerHTML of its nodes) when it was adopted. */
5
+ html: string;
6
+ /** The live top-level nodes of the slot (the island keeps the array current). */
7
+ set: Node[];
8
+ }
9
+ /** What an island chunk's mount returns. */
10
+ export interface IslandHandle {
11
+ update(props: unknown, pool?: Record<string, Node[][]>): unknown;
12
+ unmount(): void;
13
+ slots?: IslandSlot[];
14
+ }
15
+ /** An island record of window.__krateIslands. */
16
+ export interface IslandRecord {
17
+ status?: string;
18
+ handle?: IslandHandle | null;
19
+ gone?: boolean;
20
+ }
21
+ /** Serializes nodes as the island chunks snapshot a slot's server HTML. */
22
+ export declare function nodesHTML(nodes: ArrayLike<Node>): string;
23
+ /**
24
+ * HTML with every island replaced by a marker naming its component, so two
25
+ * renders compare equal when only the islands (their props, or what they
26
+ * rendered since) differ.
27
+ */
28
+ export declare function maskIslands(html: string): string;
29
+ /**
30
+ * Unmounts every island in nodes, innermost first, so their effects and
31
+ * portals are cleaned up before the nodes leave the document. An island still
32
+ * loading is marked gone (the loader unmounts it once its chunk mounted).
33
+ */
34
+ export declare function unmountIslandsIn(nodes: ArrayLike<Node>): void;
35
+ export interface SwapOptions {
36
+ /** Only islands whose server props are unchanged are kept (a navigation to another page). */
37
+ sameProps?: boolean;
38
+ }
39
+ /**
40
+ * Replaces the live children of parent between start and end (exclusive;
41
+ * all children when both are null) with newNodes (imported into the
42
+ * document, detached), keeping matched islands mounted. Returns the pending
43
+ * work of island updates (a re-render that loads more chunks first).
44
+ */
45
+ export declare function swapPreservingIslands(parent: Node, start: Node | null, end: Node | null, newNodes: Node[], opts?: SwapOptions): Promise<unknown>[];