@krate/runtime 0.5.0-rc.5 → 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.
Files changed (98) hide show
  1. package/dist/actions.js +10 -1
  2. package/dist/cache-scope.d.ts +2 -0
  3. package/dist/cache-scope.js +6 -1
  4. package/dist/context.d.ts +5 -0
  5. package/dist/context.js +28 -17
  6. package/dist/flight-props.d.ts +7 -0
  7. package/dist/flight-props.js +105 -0
  8. package/dist/handler-routing.d.ts +2 -23
  9. package/dist/handler-routing.js +4 -188
  10. package/dist/head-tags.js +5 -2
  11. package/dist/highlight.d.ts +3 -2
  12. package/dist/highlight.js +12 -6
  13. package/dist/hints.d.ts +25 -2
  14. package/dist/hints.js +148 -74
  15. package/dist/index.d.ts +1 -0
  16. package/dist/island-swap.d.ts +45 -0
  17. package/dist/island-swap.js +608 -0
  18. package/dist/jsx-types.d.ts +7 -2
  19. package/dist/krate-core.js +1 -1
  20. package/dist/krate-f-actions.js +1 -1
  21. package/dist/krate-f-list.js +1 -1
  22. package/dist/krate-f-navigation.js +1 -1
  23. package/dist/krate-f-router-lite.js +1 -1
  24. package/dist/krate-f-router.js +1 -1
  25. package/dist/krate-features.json +452 -0
  26. package/dist/krate-hydrate-lite.js +5 -5
  27. package/dist/krate-hydrate.js +5 -5
  28. package/dist/krate-island-swap.js +1 -0
  29. package/dist/krate-runtime.js +5 -5
  30. package/dist/list.d.ts +14 -4
  31. package/dist/list.js +4 -5
  32. package/dist/navigation-react.d.ts +13 -0
  33. package/dist/navigation-react.js +86 -0
  34. package/dist/navigation.d.ts +19 -0
  35. package/dist/navigation.js +35 -0
  36. package/dist/react-compat.d.ts +39 -0
  37. package/dist/react-compat.js +359 -0
  38. package/dist/request-extras.d.ts +4 -0
  39. package/dist/request-extras.js +51 -0
  40. package/dist/route-source.d.ts +39 -0
  41. package/dist/route-source.js +532 -0
  42. package/dist/router.js +293 -23
  43. package/dist/server-handler.d.ts +20 -1
  44. package/dist/server-handler.js +208 -92
  45. package/dist/server.d.ts +24 -17
  46. package/dist/server.js +435 -101
  47. package/dist/site-config.d.ts +2 -0
  48. package/dist/testing.d.ts +4 -1
  49. package/dist/testing.js +3 -1
  50. package/package.json +15 -2
  51. package/dist/actions.test.d.ts +0 -1
  52. package/dist/actions.test.js +0 -75
  53. package/dist/after.test.d.ts +0 -1
  54. package/dist/after.test.js +0 -58
  55. package/dist/builtin-tags.test.d.ts +0 -1
  56. package/dist/builtin-tags.test.js +0 -12
  57. package/dist/cache-adapter.test.d.ts +0 -1
  58. package/dist/cache-adapter.test.js +0 -45
  59. package/dist/cache.test.d.ts +0 -1
  60. package/dist/cache.test.js +0 -37
  61. package/dist/events.test.d.ts +0 -1
  62. package/dist/events.test.js +0 -42
  63. package/dist/handler-html.test.d.ts +0 -1
  64. package/dist/handler-html.test.js +0 -55
  65. package/dist/handler-segments.test.d.ts +0 -1
  66. package/dist/handler-segments.test.js +0 -25
  67. package/dist/head-tags.test.d.ts +0 -1
  68. package/dist/head-tags.test.js +0 -24
  69. package/dist/inline-action-token.test.d.ts +0 -1
  70. package/dist/inline-action-token.test.js +0 -31
  71. package/dist/jsx-svg-types.test.d.ts +0 -1
  72. package/dist/jsx-svg-types.test.js +0 -58
  73. package/dist/link-base-path.test.d.ts +0 -1
  74. package/dist/link-base-path.test.js +0 -28
  75. package/dist/node-server.test.d.ts +0 -1
  76. package/dist/node-server.test.js +0 -138
  77. package/dist/platform.test.d.ts +0 -1
  78. package/dist/platform.test.js +0 -44
  79. package/dist/router-nav.test.d.ts +0 -1
  80. package/dist/router-nav.test.js +0 -130
  81. package/dist/server-handler.test.d.ts +0 -1
  82. package/dist/server-handler.test.js +0 -338
  83. package/dist/server-renderer.test.d.ts +0 -1
  84. package/dist/server-renderer.test.js +0 -162
  85. package/dist/server.test.d.ts +0 -1
  86. package/dist/server.test.js +0 -91
  87. package/dist/sha256.test.d.ts +0 -1
  88. package/dist/sha256.test.js +0 -13
  89. package/dist/signal.test.d.ts +0 -1
  90. package/dist/signal.test.js +0 -68
  91. package/dist/site-config.test.d.ts +0 -1
  92. package/dist/site-config.test.js +0 -30
  93. package/dist/slot.test.d.ts +0 -1
  94. package/dist/slot.test.js +0 -25
  95. package/dist/ssr-core-behavior.test.d.ts +0 -1
  96. package/dist/ssr-core-behavior.test.js +0 -108
  97. package/dist/testing.test.d.ts +0 -1
  98. package/dist/testing.test.js +0 -73
package/dist/actions.js CHANGED
@@ -52,6 +52,12 @@ function navigateTo(url) {
52
52
  else if (typeof location !== 'undefined')
53
53
  location.assign(withBase(safe));
54
54
  }
55
+ /** Follows an absolute http(s) redirect the server marked external. */
56
+ function navigateExternal(url) {
57
+ if (typeof location === 'undefined' || !/^https?:\/\//i.test(url))
58
+ return;
59
+ location.assign(url);
60
+ }
55
61
  /** Only same-origin absolute paths are followed after an action. */
56
62
  function safeRedirect(url) {
57
63
  if (!url || !url.startsWith('/') || url.startsWith('//'))
@@ -127,7 +133,10 @@ export async function callServerAction(url, args) {
127
133
  dispatchRevalidate(payload.revalidation);
128
134
  if (typeof payload.redirect === 'string' && payload.redirect) {
129
135
  redirectsFollowed++;
130
- navigateTo(payload.redirect);
136
+ if (payload.external)
137
+ navigateExternal(payload.redirect);
138
+ else
139
+ navigateTo(payload.redirect);
131
140
  }
132
141
  return payload.result;
133
142
  }
@@ -30,6 +30,8 @@ export interface CacheScope {
30
30
  noStore: boolean;
31
31
  /** True when an error boundary caught a render error (the response is a 500 and uncacheable). */
32
32
  errorCaught?: boolean;
33
+ /** Head tags the render asked for (react-dom preload, preconnect, ...), deduplicated. */
34
+ hints?: Set<string>;
33
35
  }
34
36
  /** Minimal AsyncLocalStorage shape (the Node class satisfies it). */
35
37
  export interface AsyncStore<T> {
@@ -18,6 +18,7 @@
18
18
  * has no Node imports: the embedded QuickJS API runtime bundles it too, and
19
19
  * there the data cache is backed by the Go host (`_go_cache_get/_go_cache_set`).
20
20
  */
21
+ import { HEAD_CLOSE, HEAD_OPEN } from './head-tags.js';
21
22
  const STATE_KEY = Symbol.for('krate.cache.runtime');
22
23
  const REVALIDATE_STORE_KEY = Symbol.for('krate.revalidate.store');
23
24
  /** In-process data cache with tag index and FIFO bound. */
@@ -147,7 +148,11 @@ export async function withCacheScope(route, fn) {
147
148
  const scope = { route, tags: new Set(), revalidate: 0, noStore: false };
148
149
  const epoch = rt.epoch;
149
150
  const store = rt.renderStore;
150
- const result = store ? await store.run(scope, () => Promise.resolve().then(fn)) : await fn();
151
+ let result = store ? await store.run(scope, () => Promise.resolve().then(fn)) : await fn();
152
+ if (scope.hints && scope.hints.size && typeof result === 'string') {
153
+ // react-dom resource hints go to the head of the response like <Head> tags.
154
+ result = (HEAD_OPEN + [...scope.hints].join('') + HEAD_CLOSE + result);
155
+ }
151
156
  return { result, scope, invalidated: rt.epoch !== epoch };
152
157
  }
153
158
  /**
package/dist/context.d.ts CHANGED
@@ -53,3 +53,8 @@ export declare function createContext<T>(defaultValue: T): Context<T>;
53
53
  * the list runtime have no provider on the stack otherwise.
54
54
  */
55
55
  export declare function krateContextRows<A extends unknown[], R>(entries: Array<[Context<any>, () => unknown]>, render: (...args: A) => R): (...args: A) => R;
56
+ /**
57
+ * Runs fn with the given provider values (getters) on top of their context
58
+ * stacks, as if fn rendered inside those providers.
59
+ */
60
+ export declare function krateWithContexts<R>(entries: Array<[Context<any>, () => unknown]>, fn: () => R): R;
package/dist/context.js CHANGED
@@ -109,6 +109,8 @@ export function createContext(defaultValue) {
109
109
  ctx.id = id;
110
110
  ctx.defaultValue = defaultValue;
111
111
  ctx.Provider = Provider;
112
+ // Lets a custom renderer map a provider element back to its context.
113
+ Provider.__kctxOf = ctx;
112
114
  ctx.Consumer = Consumer;
113
115
  ctx.useContext = useContext;
114
116
  ctx.use = useContext;
@@ -123,21 +125,30 @@ export function createContext(defaultValue) {
123
125
  * the list runtime have no provider on the stack otherwise.
124
126
  */
125
127
  export function krateContextRows(entries, render) {
126
- return (...args) => {
127
- const pushed = [];
128
- for (const [ctx, get] of entries) {
129
- const stack = contextStack.get(ctx.id);
130
- if (!stack)
131
- continue;
132
- stack.push(new LiveContext(get));
133
- pushed.push(stack);
134
- }
135
- try {
136
- return render(...args);
137
- }
138
- finally {
139
- for (const stack of pushed)
140
- stack.pop();
141
- }
142
- };
128
+ const wrapped = (...args) => krateWithContexts(entries, () => render(...args));
129
+ // Renderers that evaluate the content later (a custom renderer's deferred
130
+ // components) read the entries to make the same providers visible again.
131
+ wrapped.__kctx = entries;
132
+ return wrapped;
133
+ }
134
+ /**
135
+ * Runs fn with the given provider values (getters) on top of their context
136
+ * stacks, as if fn rendered inside those providers.
137
+ */
138
+ export function krateWithContexts(entries, fn) {
139
+ const pushed = [];
140
+ for (const [ctx, get] of entries) {
141
+ const stack = contextStack.get(ctx.id);
142
+ if (!stack)
143
+ continue;
144
+ stack.push(new LiveContext(get));
145
+ pushed.push(stack);
146
+ }
147
+ try {
148
+ return fn();
149
+ }
150
+ finally {
151
+ for (let i = pushed.length - 1; i >= 0; i--)
152
+ pushed[i].pop();
153
+ }
143
154
  }
@@ -0,0 +1,7 @@
1
+ export type FlightHooks = {
2
+ isAction(v: unknown): string | undefined;
3
+ isJSX(v: unknown): boolean;
4
+ fail(path: string, what: string, hint?: string): Error;
5
+ };
6
+ export declare function describeValue(v: unknown): string;
7
+ export declare function encodeProp(v: unknown, path: string, hooks: FlightHooks): unknown;
@@ -0,0 +1,105 @@
1
+ // Encoding of plain-data props crossing from a server component to a client
2
+ // component, in the spirit of React Flight. JSON carries strings, finite
3
+ // numbers, booleans, null, arrays and plain objects as themselves; every other
4
+ // supported value becomes a tagged object { __krateT: <tag>, v: <payload> }
5
+ // that the client reviver (clientReviveJS in the compiler) turns back into the
6
+ // real value. A plain object that could be mistaken for a tag or a marker is
7
+ // wrapped in an "O" tag so user data can never collide with the encoding.
8
+ const RESERVED = ["__krateT", "__krateAction", "__krateSlotHTML", "__krateSlotTree", "__krateChildren", "__krateTree"];
9
+ const TYPED_ARRAYS = {
10
+ Int8Array: true, Uint8Array: true, Uint8ClampedArray: true, Int16Array: true, Uint16Array: true,
11
+ Int32Array: true, Uint32Array: true, Float32Array: true, Float64Array: true, BigInt64Array: true, BigUint64Array: true,
12
+ };
13
+ function tag(t, v) {
14
+ return v === undefined ? { __krateT: t } : { __krateT: t, v };
15
+ }
16
+ function toBase64(bytes) {
17
+ let s = "";
18
+ for (let i = 0; i < bytes.length; i += 0x8000)
19
+ s += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
20
+ return btoa(s);
21
+ }
22
+ function bytesOf(buf, off = 0, len = buf.byteLength - off) {
23
+ return toBase64(new Uint8Array(buf, off, len));
24
+ }
25
+ export function describeValue(v) {
26
+ if (typeof v === "function")
27
+ return "a function";
28
+ if (typeof v === "symbol")
29
+ return "a symbol that is not registered with Symbol.for";
30
+ if (v && typeof v === "object") {
31
+ const ctor = Object.getPrototypeOf(v)?.constructor?.name;
32
+ return ctor ? `an instance of ${ctor}` : "a non-plain object";
33
+ }
34
+ return typeof v;
35
+ }
36
+ // encodeProp converts one prop value. A top-level undefined is dropped by the
37
+ // caller (an absent prop); nested ones are kept as an "U" tag.
38
+ export function encodeProp(v, path, hooks) {
39
+ if (v === null || typeof v === "string" || typeof v === "boolean")
40
+ return v;
41
+ if (typeof v === "number") {
42
+ if (Object.is(v, -0))
43
+ return tag("N", "-0");
44
+ if (Number.isNaN(v))
45
+ return tag("N", "NaN");
46
+ if (v === Infinity)
47
+ return tag("N", "Infinity");
48
+ if (v === -Infinity)
49
+ return tag("N", "-Infinity");
50
+ return v;
51
+ }
52
+ if (typeof v === "bigint")
53
+ return tag("B", v.toString());
54
+ if (v === undefined)
55
+ return tag("U");
56
+ if (typeof v === "symbol") {
57
+ const key = Symbol.keyFor(v);
58
+ if (key === undefined)
59
+ throw hooks.fail(path, describeValue(v));
60
+ return tag("Y", key);
61
+ }
62
+ const action = hooks.isAction(v);
63
+ if (action !== undefined)
64
+ return { __krateAction: action };
65
+ if (Array.isArray(v))
66
+ return v.map((x, i) => encodeProp(x, `${path}[${i}]`, hooks));
67
+ if (typeof v === "object") {
68
+ if (hooks.isJSX(v)) {
69
+ throw hooks.fail(path, "JSX", "pass JSX as a prop value, an array of JSX, or as children; JSX nested inside an object cannot be sent to a client component");
70
+ }
71
+ const proto = Object.getPrototypeOf(v);
72
+ if (proto === Date.prototype) {
73
+ const t = v.getTime();
74
+ return tag("D", Number.isNaN(t) ? null : t);
75
+ }
76
+ if (proto === Map.prototype) {
77
+ const entries = [];
78
+ let i = 0;
79
+ for (const [k, x] of v) {
80
+ entries.push([encodeProp(k, `${path}.keys[${i}]`, hooks), encodeProp(x, `${path}.get(${i})`, hooks)]);
81
+ i++;
82
+ }
83
+ return tag("M", entries);
84
+ }
85
+ if (proto === Set.prototype) {
86
+ return tag("S", [...v].map((x, i) => encodeProp(x, `${path}.values[${i}]`, hooks)));
87
+ }
88
+ if (proto === ArrayBuffer.prototype)
89
+ return tag("A", bytesOf(v));
90
+ if (ArrayBuffer.isView(v)) {
91
+ if (v instanceof DataView)
92
+ return tag("V", bytesOf(v.buffer, v.byteOffset, v.byteLength));
93
+ const name = v[Symbol.toStringTag];
94
+ if (TYPED_ARRAYS[name])
95
+ return tag("T", { n: name, b: bytesOf(v.buffer, v.byteOffset, v.byteLength) });
96
+ }
97
+ if (proto !== Object.prototype && proto !== null)
98
+ throw hooks.fail(path, describeValue(v));
99
+ const out = {};
100
+ for (const [k, x] of Object.entries(v))
101
+ out[k] = encodeProp(x, `${path}.${k}`, hooks);
102
+ return RESERVED.some((k) => Object.prototype.hasOwnProperty.call(out, k)) ? tag("O", out) : out;
103
+ }
104
+ throw hooks.fail(path, describeValue(v));
105
+ }
@@ -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
  }
package/dist/hints.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- interface HintOptions {
1
+ export interface HintOptions {
2
2
  as?: string;
3
3
  crossOrigin?: string;
4
4
  integrity?: string;
@@ -9,11 +9,34 @@ interface HintOptions {
9
9
  referrerPolicy?: string;
10
10
  imageSrcSet?: string;
11
11
  imageSizes?: string;
12
+ precedence?: string;
12
13
  }
14
+ /**
15
+ * Records head tags the build collected for a component that the server does
16
+ * not render (a real-React client component). Server only; the browser
17
+ * already has them in the document.
18
+ */
19
+ export declare function krateHintTags(tags: readonly string[]): void;
13
20
  export declare function krateHintPreload(href: string, opts?: HintOptions): void;
14
21
  export declare function krateHintPreloadModule(href: string, opts?: HintOptions): void;
15
22
  export declare function krateHintPreconnect(href: string, opts?: HintOptions): void;
16
23
  export declare function krateHintPrefetchDNS(href: string): void;
17
24
  export declare function krateHintPreinit(href: string, opts?: HintOptions): void;
18
25
  export declare function krateHintPreinitModule(href: string, opts?: HintOptions): void;
19
- export {};
26
+ export declare const preload: typeof krateHintPreload;
27
+ export declare const preinit: typeof krateHintPreinit;
28
+ export declare const preconnect: typeof krateHintPreconnect;
29
+ export declare const prefetchDNS: typeof krateHintPrefetchDNS;
30
+ export declare const preloadModule: typeof krateHintPreloadModule;
31
+ export declare const preinitModule: typeof krateHintPreinitModule;
32
+ export declare function flushSync<T>(fn: () => T): T;
33
+ declare const _default: {
34
+ preload: typeof krateHintPreload;
35
+ preinit: typeof krateHintPreinit;
36
+ preconnect: typeof krateHintPreconnect;
37
+ prefetchDNS: typeof krateHintPrefetchDNS;
38
+ preloadModule: typeof krateHintPreloadModule;
39
+ preinitModule: typeof krateHintPreinitModule;
40
+ flushSync: typeof flushSync;
41
+ };
42
+ export default _default;