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

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
package/dist/dom.js CHANGED
@@ -3,6 +3,7 @@ import { krateWithOwner, krateUnmount } from './effects.js';
3
3
  import { krateSanitizeAttr } from './slots.js';
4
4
  import { krateOn, krateControl, krateSetControl } from './events.js';
5
5
  import { krateAttachRef } from './refs.js';
6
+ import { withBase } from './base-path.js';
6
7
  export { krateOn, krateControl, krateSetControl, krateSynthetic, krateEventRoot, krateEventName, krateMountFields, } from './events.js';
7
8
  export { krateAttachRef, krateSetRef, krateRefsEnter, krateRefsLeave, krateRefsFlush, krateRefsHold } from './refs.js';
8
9
  // per-node effect tracking
@@ -207,7 +208,7 @@ export function krateApplyStyle(el, style) {
207
208
  * accessor is not shadowed by the early own property.
208
209
  */
209
210
  export function krateCustomProp(el, key, value) {
210
- if (el.localName.indexOf('-') < 1 || key.indexOf('-') >= 0)
211
+ if (el.localName.indexOf('-') < 1 || key.includes('-'))
211
212
  return false;
212
213
  const complex = (typeof value === 'object' && value !== null) || typeof value === 'function';
213
214
  if (!complex && !(key in el))
@@ -288,9 +289,22 @@ function setAttr(el, key, value) {
288
289
  }
289
290
  }
290
291
  }
292
+ /** A built-in <Link> lowers to these props; plain anchors are left as written. */
293
+ function isLinkProps(props) {
294
+ if ('data-krate-no-base' in props)
295
+ return false;
296
+ return 'data-krate-link' in props || 'data-krate-external' in props;
297
+ }
298
+ function linkHref(href) {
299
+ if (typeof href === 'string')
300
+ return withBase(href);
301
+ if (typeof href === 'function')
302
+ return () => linkHref(href());
303
+ return href;
304
+ }
291
305
  function applyProps(el, props) {
292
306
  for (const key in props) {
293
- const value = props[key];
307
+ const value = key === 'href' && isLinkProps(props) ? linkHref(props[key]) : props[key];
294
308
  if (typeof value === 'function' && (key === 'value' || key === 'checked')) {
295
309
  trackEffect(el, krateControl(el, key, value));
296
310
  }
@@ -323,7 +337,8 @@ export function krateSpread(el, get) {
323
337
  if (key === 'children' || key === 'key' || key === 'dangerouslySetInnerHTML')
324
338
  continue;
325
339
  next.add(key);
326
- setAttr(el, key, props[key]);
340
+ const isLink = key === 'href' && (isLinkProps(props) || (el.hasAttribute('data-krate-link') && !('data-krate-no-base' in props)));
341
+ setAttr(el, key, isLink ? linkHref(props[key]) : props[key]);
327
342
  }
328
343
  const prev = spreadKeys.get(el);
329
344
  if (prev) {
package/dist/effects.js CHANGED
@@ -144,7 +144,7 @@ export function krateUnmount(value) {
144
144
  if (owner.parent) {
145
145
  const list = owner.parent.children;
146
146
  const i = list.indexOf(owner);
147
- if (i >= 0)
147
+ if (i !== -1)
148
148
  list.splice(i, 1);
149
149
  }
150
150
  if (passive.length) {
@@ -733,7 +733,7 @@ function unmountExcept(gone) {
733
733
  continue;
734
734
  disposeTree(child, child.shown, passive);
735
735
  const i = root.children.indexOf(child);
736
- if (i >= 0)
736
+ if (i !== -1)
737
737
  root.children.splice(i, 1);
738
738
  }
739
739
  const keptHooks = [];
@@ -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
+ }
@@ -19,7 +19,7 @@ export function parseRegionShell(shell) {
19
19
  const id = o[2];
20
20
  const openEnd = o.index + o[0].length;
21
21
  const rel = shell.indexOf("<!--/" + kind + ":" + id + "-->", openEnd);
22
- if (rel < 0) {
22
+ if (rel === -1) {
23
23
  e.ok = false;
24
24
  e.roots = [];
25
25
  e.all = [];
@@ -50,13 +50,13 @@ export function allSuspense(all) {
50
50
  export function splitBodyScripts(shell) {
51
51
  const lower = shell.toLowerCase();
52
52
  const body = lower.indexOf("<body");
53
- if (body >= 0) {
53
+ if (body !== -1) {
54
54
  const rel = lower.indexOf("<script", body);
55
- if (rel >= 0)
55
+ if (rel !== -1)
56
56
  return [shell.slice(0, rel), shell.slice(rel)];
57
57
  }
58
58
  const at = lower.lastIndexOf("</body>");
59
- if (at >= 0)
59
+ if (at !== -1)
60
60
  return [shell.slice(0, at), shell.slice(at)];
61
61
  return [shell, ""];
62
62
  }
@@ -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
  /**
@@ -127,7 +127,7 @@ export function baseName(p) {
127
127
  return "/";
128
128
  const s = p.slice(0, end);
129
129
  const i = s.lastIndexOf("/");
130
- return i >= 0 ? s.slice(i + 1) : s;
130
+ return i !== -1 ? s.slice(i + 1) : s;
131
131
  }
132
132
  export function isHTMLDocRequest(urlPath) {
133
133
  return urlPath === "" || urlPath.endsWith("/") || urlPath.endsWith(".html");
@@ -178,6 +178,9 @@ export function isInternalOutputPath(urlPath) {
178
178
  const p = cleanPath("/" + decodePath(urlPath).replace(/\\/g, "/"));
179
179
  if (p === "/.krate" || p.startsWith("/.krate/"))
180
180
  return true;
181
+ // The shell of a segment page that renders per request is not a page of the site.
182
+ if (/(^|\/)__(401|403|404|500)(\/(index\.html)?)?$/.test(p))
183
+ return true;
181
184
  return p === "/server-manifest.json" || p === "/api-node" || p.startsWith("/api-node/");
182
185
  }
183
186
  export function isHiddenName(name) {
@@ -188,193 +191,7 @@ export function isHiddenPath(urlPath) {
188
191
  const decoded = decodePath(urlPath);
189
192
  return decoded.split(/[/\\]/).filter(Boolean).some(isHiddenName);
190
193
  }
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
- }
194
+ // Redirect, rewrite and header rule matching lives in route-source.ts.
378
195
  // Dynamic SSG templates
379
196
  export const DYNAMIC_PARAM_PREFIX = "__KRATE_PARAM_";
380
197
  export function dynamicParamSentinel(name) {
@@ -396,7 +213,7 @@ export function escapeHTML(s) {
396
213
  export function applyDynamicRouteParams(templateHTML, params) {
397
214
  const injectScript = "<script>window.__KRATE_PARAMS__=" + goJSON(params) + "</script>";
398
215
  const at = templateHTML.indexOf("</head>");
399
- let out = at < 0 ? templateHTML : templateHTML.slice(0, at) + injectScript + templateHTML.slice(at);
216
+ let out = at === -1 ? templateHTML : templateHTML.slice(0, at) + injectScript + templateHTML.slice(at);
400
217
  for (const [name, value] of Object.entries(params)) {
401
218
  out = out.split(dynamicParamSentinel(name)).join(goHTMLEscape(value));
402
219
  }
@@ -414,9 +231,11 @@ export function goJSON(obj) {
414
231
  return "{" + keys.map((k) => enc(k) + ":" + enc(obj[k])).join(",") + "}";
415
232
  }
416
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";
417
236
  export function staticCacheControl(urlPath, hashed) {
418
237
  if (hashed.has(urlPath))
419
- return "public, max-age=31536000, immutable";
238
+ return IMMUTABLE_CACHE_CONTROL;
420
239
  return "no-cache";
421
240
  }
422
241
  // Middleware matcher (path-to-regexp subset), shared with the Go runtimes
@@ -10,6 +10,8 @@ export interface SegmentEntry {
10
10
  error?: string;
11
11
  forbidden?: string;
12
12
  unauthorized?: string;
13
+ /** Roles whose page renders per request (its file holds the baked shell). */
14
+ dynamic?: SegmentKind[];
13
15
  }
14
16
  export interface SegmentMatch {
15
17
  /** Page path relative to the output dir ("blog/404.html"). */
@@ -17,7 +19,11 @@ export interface SegmentMatch {
17
19
  key: string;
18
20
  /** Dynamic-segment values when matched against a URL, else undefined. */
19
21
  params?: Record<string, string>;
22
+ /** The renderer's route for a page that renders per request (build/segments.go SegmentRoute). */
23
+ route?: string;
20
24
  }
25
+ /** The route the renderer knows a request-time segment page by ("/__404", "/blog/__404"). */
26
+ export declare function segmentRoute(key: string, kind: SegmentKind): string;
21
27
  /**
22
28
  * Returns the nearest segment page of a kind. matched: the request matched a
23
29
  * route whose source directory is segDir, so the lookup walks up from it.
@@ -9,6 +9,20 @@ export const SEGMENT_KIND_OF_STATUS = {
9
9
  404: "notFound",
10
10
  500: "error",
11
11
  };
12
+ const KIND_STATUS = { notFound: 404, error: 500, forbidden: 403, unauthorized: 401 };
13
+ /** The route the renderer knows a request-time segment page by ("/__404", "/blog/__404"). */
14
+ export function segmentRoute(key, kind) {
15
+ const dir = "__" + KIND_STATUS[kind];
16
+ return key === "" ? "/" + dir : "/" + key + "/" + dir;
17
+ }
18
+ function matchOf(e, kind, params) {
19
+ const m = { file: entryPage(e, kind), key: e.key };
20
+ if (params)
21
+ m.params = params;
22
+ if (e.dynamic && e.dynamic.includes(kind))
23
+ m.route = segmentRoute(e.key, kind);
24
+ return m;
25
+ }
12
26
  function entryPage(e, kind) {
13
27
  switch (kind) {
14
28
  case "error":
@@ -36,11 +50,11 @@ export function lookupSegmentPage(entries, kind, urlPath, matched, segDir) {
36
50
  for (;;) {
37
51
  const e = byKey.get(dir);
38
52
  if (e && entryPage(e, kind) !== "")
39
- return { file: entryPage(e, kind), key: e.key };
53
+ return matchOf(e, kind);
40
54
  if (dir === "")
41
55
  return null;
42
56
  const i = dir.lastIndexOf("/");
43
- dir = i >= 0 ? dir.slice(0, i) : "";
57
+ dir = i !== -1 ? dir.slice(0, i) : "";
44
58
  }
45
59
  }
46
60
  let best = null;
@@ -58,7 +72,7 @@ export function lookupSegmentPage(entries, kind, urlPath, matched, segDir) {
58
72
  }
59
73
  if (!best)
60
74
  return null;
61
- return { file: entryPage(best, kind), key: best.key, params: bestParams };
75
+ return matchOf(best, kind, bestParams);
62
76
  }
63
77
  /** Matches the leading segments of urlPath; a trailing catch-all takes the rest. */
64
78
  function matchRoutePrefix(urlPath, pattern) {
@@ -102,7 +116,7 @@ export function fillServerError(page, e) {
102
116
  page = page.split(sentinel).join(goHTMLEscape(val));
103
117
  const block = '<script type="application/json" id="__krate_error">' + escapeJSONForScript(JSON.stringify(e)) + "</script>";
104
118
  const at = page.indexOf("</head>");
105
- return at >= 0 ? page.slice(0, at) + block + page.slice(at) : block + page;
119
+ return at !== -1 ? page.slice(0, at) + block + page.slice(at) : block + page;
106
120
  }
107
121
  /** A segment page filled for one response (dynamic dir params, then the error). */
108
122
  export function renderSegmentPage(html, m, err) {
@@ -47,5 +47,14 @@ export declare function parseHeadTags(fragment: string): HeadTag[];
47
47
  export declare function mergeHeadSection(head: string, title: string, fragment: string): string;
48
48
  /** Index where the head section of a document ends (</head>, else <body), or -1. */
49
49
  export declare function headEndOf(doc: string): number;
50
+ export type DocAttrs = Map<string, string>;
51
+ /** Removes the <html> and <body> elements from a head fragment and returns their attributes. */
52
+ export declare function splitDocTags(fragment: string): {
53
+ rest: string;
54
+ html: DocAttrs;
55
+ body: DocAttrs;
56
+ };
57
+ /** Sets attrs on the first start tag of `name` in doc, keeping the attributes it already has. */
58
+ export declare function setStartTagAttrs(doc: string, name: string, attrs: DocAttrs): string;
50
59
  /** Merges the title and head tags into the head of a whole document. */
51
60
  export declare function mergeHead(doc: string, title: string, fragment: string): string;