@krate/runtime 0.5.0-alpha.4 → 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.
Files changed (165) hide show
  1. package/dist/action-context.d.ts +5 -1
  2. package/dist/action-context.js +33 -3
  3. package/dist/action-context.test.js +26 -1
  4. package/dist/actions.d.ts +12 -1
  5. package/dist/actions.js +84 -4
  6. package/dist/actions.test.js +61 -1
  7. package/dist/assets-static.d.ts +5 -0
  8. package/dist/assets-static.js +31 -0
  9. package/dist/boundary.d.ts +12 -0
  10. package/dist/boundary.js +53 -13
  11. package/dist/cache-adapter.d.ts +113 -0
  12. package/dist/cache-adapter.js +217 -0
  13. package/dist/cache-adapter.test.d.ts +1 -0
  14. package/dist/cache-adapter.test.js +244 -0
  15. package/dist/cache-redis.d.ts +27 -0
  16. package/dist/cache-redis.js +110 -0
  17. package/dist/cache-scope.d.ts +25 -9
  18. package/dist/cache-scope.js +64 -13
  19. package/dist/cache.d.ts +1 -0
  20. package/dist/cache.js +3 -3
  21. package/dist/cache.test.js +16 -0
  22. package/dist/class-component.js +6 -0
  23. package/dist/class-component.test.js +53 -2
  24. package/dist/class-helpers.d.ts +4 -4
  25. package/dist/class-helpers.js +357 -32
  26. package/dist/class-helpers.test.d.ts +1 -0
  27. package/dist/class-helpers.test.js +169 -0
  28. package/dist/context.d.ts +16 -2
  29. package/dist/context.js +44 -3
  30. package/dist/dev-overlay.js +85 -12
  31. package/dist/dev-overlay.test.js +22 -0
  32. package/dist/dom.d.ts +15 -0
  33. package/dist/dom.js +97 -3
  34. package/dist/effect-errors.test.d.ts +1 -0
  35. package/dist/effect-errors.test.js +163 -0
  36. package/dist/effects.d.ts +8 -0
  37. package/dist/effects.js +13 -0
  38. package/dist/error-overlay.js +7 -7
  39. package/dist/handler-html.d.ts +63 -0
  40. package/dist/handler-html.js +285 -0
  41. package/dist/handler-html.test.d.ts +1 -0
  42. package/dist/handler-html.test.js +256 -0
  43. package/dist/handler-routing.d.ts +83 -0
  44. package/dist/handler-routing.js +579 -0
  45. package/dist/handler-routing.test.d.ts +1 -0
  46. package/dist/handler-routing.test.js +99 -0
  47. package/dist/handler-segments.d.ts +43 -0
  48. package/dist/handler-segments.js +115 -0
  49. package/dist/handler-segments.test.d.ts +1 -0
  50. package/dist/handler-segments.test.js +217 -0
  51. package/dist/head-tags.d.ts +51 -0
  52. package/dist/head-tags.js +329 -0
  53. package/dist/head-tags.test.d.ts +1 -0
  54. package/dist/head-tags.test.js +131 -0
  55. package/dist/highlight-bind.d.ts +42 -0
  56. package/dist/highlight-bind.js +176 -0
  57. package/dist/highlight-bind.test.d.ts +1 -0
  58. package/dist/highlight-bind.test.js +124 -0
  59. package/dist/highlight.d.ts +93 -0
  60. package/dist/highlight.js +426 -0
  61. package/dist/highlight.test.d.ts +1 -0
  62. package/dist/highlight.test.js +56 -0
  63. package/dist/hints.d.ts +19 -0
  64. package/dist/hints.js +97 -0
  65. package/dist/hook-args.d.ts +7 -0
  66. package/dist/hook-args.js +10 -0
  67. package/dist/htmlspec-attributes.d.ts +1 -0
  68. package/dist/htmlspec-attributes.js +159 -0
  69. package/dist/index.d.ts +4 -0
  70. package/dist/index.js +3 -0
  71. package/dist/jsx-types.d.ts +11 -0
  72. package/dist/krate-core.js +2 -0
  73. package/dist/krate-dev.js +75 -12
  74. package/dist/krate-f-actions.js +2 -0
  75. package/dist/krate-f-classes.js +8 -0
  76. package/dist/krate-f-helpers.js +2 -0
  77. package/dist/krate-f-highlight.js +2 -0
  78. package/dist/krate-f-list.js +2 -0
  79. package/dist/krate-f-navigation.js +2 -0
  80. package/dist/krate-f-router-lite.js +2 -0
  81. package/dist/krate-f-router.js +2 -0
  82. package/dist/krate-features.json +493 -0
  83. package/dist/krate-hydrate-lite.js +5 -5
  84. package/dist/krate-hydrate.js +5 -5
  85. package/dist/krate-runtime.js +5 -5
  86. package/dist/list.js +4 -2
  87. package/dist/metadata-routes.d.ts +75 -0
  88. package/dist/metadata-routes.js +76 -0
  89. package/dist/metadata.d.ts +222 -0
  90. package/dist/metadata.js +452 -0
  91. package/dist/metadata.test.d.ts +1 -0
  92. package/dist/metadata.test.js +167 -0
  93. package/dist/navigation-server.d.ts +27 -0
  94. package/dist/navigation-server.js +90 -0
  95. package/dist/navigation.d.ts +37 -0
  96. package/dist/navigation.js +195 -0
  97. package/dist/navigation.test.d.ts +1 -0
  98. package/dist/navigation.test.js +130 -0
  99. package/dist/node-server.d.ts +22 -0
  100. package/dist/node-server.js +436 -0
  101. package/dist/node-server.test.d.ts +1 -0
  102. package/dist/node-server.test.js +492 -0
  103. package/dist/og-files.d.ts +2 -0
  104. package/dist/og-files.js +19 -0
  105. package/dist/og.d.ts +56 -0
  106. package/dist/og.js +156 -0
  107. package/dist/patterns.test.d.ts +1 -0
  108. package/dist/patterns.test.js +98 -0
  109. package/dist/react.d.ts +47 -0
  110. package/dist/react.js +59 -1
  111. package/dist/react19.test.d.ts +1 -0
  112. package/dist/react19.test.js +176 -0
  113. package/dist/reactivity-core.test.d.ts +1 -0
  114. package/dist/reactivity-core.test.js +152 -0
  115. package/dist/reconcile.js +4 -2
  116. package/dist/request-context.d.ts +23 -0
  117. package/dist/request-context.js +45 -0
  118. package/dist/resp.d.ts +55 -0
  119. package/dist/resp.js +239 -0
  120. package/dist/router-layout.test.js +70 -0
  121. package/dist/router-nav.test.js +65 -0
  122. package/dist/router-speculation.test.d.ts +1 -0
  123. package/dist/router-speculation.test.js +25 -0
  124. package/dist/router-styles.test.d.ts +1 -0
  125. package/dist/router-styles.test.js +98 -0
  126. package/dist/router.js +175 -36
  127. package/dist/segmented-lru.d.ts +19 -0
  128. package/dist/segmented-lru.js +87 -0
  129. package/dist/server-async.test.js +43 -1
  130. package/dist/server-handler.d.ts +165 -0
  131. package/dist/server-handler.js +1826 -0
  132. package/dist/server-handler.test.d.ts +1 -0
  133. package/dist/server-handler.test.js +522 -0
  134. package/dist/server-highlight.test.d.ts +1 -0
  135. package/dist/server-highlight.test.js +32 -0
  136. package/dist/server-renderer.js +165 -720
  137. package/dist/server-renderer.test.d.ts +1 -0
  138. package/dist/server-renderer.test.js +266 -0
  139. package/dist/server.d.ts +13 -1
  140. package/dist/server.js +131 -16
  141. package/dist/server.test.js +20 -0
  142. package/dist/sha256.d.ts +1 -0
  143. package/dist/sha256.js +66 -0
  144. package/dist/sha256.test.d.ts +1 -0
  145. package/dist/sha256.test.js +13 -0
  146. package/dist/shared-isr.d.ts +31 -0
  147. package/dist/shared-isr.js +142 -0
  148. package/dist/signal.d.ts +3 -2
  149. package/dist/signal.js +163 -23
  150. package/dist/slots.js +12 -1
  151. package/dist/ssr-core-behavior.test.d.ts +1 -0
  152. package/dist/ssr-core-behavior.test.js +620 -0
  153. package/dist/ssr-core.d.ts +175 -0
  154. package/dist/ssr-core.js +940 -0
  155. package/dist/ssr-core.test.d.ts +1 -0
  156. package/dist/ssr-core.test.js +324 -0
  157. package/dist/static-memory.d.ts +3 -0
  158. package/dist/static-memory.js +47 -0
  159. package/dist/static-memory.test.d.ts +1 -0
  160. package/dist/static-memory.test.js +26 -0
  161. package/dist/test-redis.d.ts +12 -0
  162. package/dist/test-redis.js +131 -0
  163. package/dist/use-id.d.ts +8 -0
  164. package/dist/use-id.js +40 -0
  165. package/package.json +30 -2
@@ -0,0 +1,329 @@
1
+ // <Head> children of request-time renders.
2
+ //
3
+ // A <Head> in an async page renders its children in place, between two comment
4
+ // markers (server.ts Head). takeHead lifts them out of the rendered body, and
5
+ // mergeHead puts them into the <head> of the response, so crawlers and social
6
+ // scrapers see them in the first bytes. The Go host does the same merge
7
+ // (internal/build/headmerge.go); both must keep the same rules:
8
+ //
9
+ // - A page tag replaces a baked tag with the same key: meta name,
10
+ // property or http-equiv, meta charset, link rel=canonical, base. The
11
+ // page wins over layouts and site config.
12
+ // - Among the page's own tags a repeated name, http-equiv, charset,
13
+ // canonical or base keeps the last one. A repeated property (og:image,
14
+ // article:tag) keeps all of them.
15
+ // - A tag identical to one already in the head is not added twice.
16
+ // - Only meta, link, base, script, style and noscript are head content;
17
+ // anything else inside <Head> is dropped.
18
+ // - The title replaces the baked title, or is added when there is none.
19
+ export const HEAD_OPEN = "<!--krate-head-->";
20
+ export const HEAD_CLOSE = "<!--/krate-head-->";
21
+ /**
22
+ * Splits the document head content out of rendered page html: the <title>
23
+ * (the last one that is not inside an <svg>, as with static <Head> hoisting
24
+ * where a nested Head overrides its parent) and everything inside <Head>
25
+ * markers. Both are removed from the returned html.
26
+ */
27
+ export function takeHead(html) {
28
+ const hasHead = html.indexOf(HEAD_OPEN) !== -1;
29
+ const hasTitle = /<title[\s>]/i.test(html);
30
+ if (!hasHead && !hasTitle)
31
+ return { title: "", head: "", html };
32
+ let body = html;
33
+ let headText = "";
34
+ if (hasHead) {
35
+ // Head blocks may nest; the outermost pair wins and inner markers go.
36
+ let out = "";
37
+ let i = 0;
38
+ for (;;) {
39
+ const open = body.indexOf(HEAD_OPEN, i);
40
+ if (open === -1) {
41
+ out += body.slice(i);
42
+ break;
43
+ }
44
+ out += body.slice(i, open);
45
+ let depth = 1;
46
+ let j = open + HEAD_OPEN.length;
47
+ let inner = "";
48
+ let from = j;
49
+ while (depth > 0) {
50
+ const nextOpen = body.indexOf(HEAD_OPEN, j);
51
+ const nextClose = body.indexOf(HEAD_CLOSE, j);
52
+ if (nextClose === -1) {
53
+ // Unbalanced: keep the rest as head text.
54
+ inner += body.slice(from);
55
+ j = body.length;
56
+ depth = 0;
57
+ break;
58
+ }
59
+ if (nextOpen !== -1 && nextOpen < nextClose) {
60
+ inner += body.slice(from, nextOpen);
61
+ from = nextOpen + HEAD_OPEN.length;
62
+ j = from;
63
+ depth++;
64
+ }
65
+ else {
66
+ inner += body.slice(from, nextClose);
67
+ from = nextClose + HEAD_CLOSE.length;
68
+ j = from;
69
+ depth--;
70
+ }
71
+ }
72
+ headText += inner;
73
+ i = j;
74
+ }
75
+ body = out;
76
+ }
77
+ const fromHead = takeTitles(headText);
78
+ const fromBody = takeTitles(body);
79
+ return {
80
+ title: fromHead.title || fromBody.title,
81
+ head: fromHead.html,
82
+ html: fromBody.html,
83
+ };
84
+ }
85
+ function takeTitles(html) {
86
+ if (html.indexOf("<title") === -1 && html.indexOf("<TITLE") === -1)
87
+ return { title: "", html };
88
+ const re = /<title(?:\s[^>]*)?>([\s\S]*?)<\/title>/gi;
89
+ const found = [];
90
+ let m;
91
+ while ((m = re.exec(html))) {
92
+ if (insideSVG(html, m.index))
93
+ continue;
94
+ found.push({ index: m.index, length: m[0].length, text: m[1].trim() });
95
+ }
96
+ if (found.length === 0)
97
+ return { title: "", html };
98
+ let out = "";
99
+ let last = 0;
100
+ for (const f of found) {
101
+ out += html.slice(last, f.index);
102
+ last = f.index + f.length;
103
+ }
104
+ out += html.slice(last);
105
+ return { title: found[found.length - 1].text, html: out };
106
+ }
107
+ function insideSVG(html, pos) {
108
+ const before = html.slice(0, pos).toLowerCase();
109
+ let depth = 0;
110
+ const re = /<(\/?)svg[\s>\/]/g;
111
+ let m;
112
+ while ((m = re.exec(before)))
113
+ depth += m[1] ? -1 : 1;
114
+ return depth > 0;
115
+ }
116
+ const RAW_TEXT = new Set(["script", "style", "noscript", "title", "textarea", "template"]);
117
+ function isSpace(c) {
118
+ return c === " " || c === "\t" || c === "\n" || c === "\r" || c === "\f";
119
+ }
120
+ /**
121
+ * Scans the elements of head markup: tag, attributes (quoted, unquoted and
122
+ * valueless, as the HTML tokenizer reads them) and the raw text of script,
123
+ * style and noscript. Comments and text between elements are skipped.
124
+ */
125
+ export function scanHeadElements(s) {
126
+ const out = [];
127
+ let lower = null;
128
+ let i = 0;
129
+ while (i < s.length) {
130
+ const lt = s.indexOf("<", i);
131
+ if (lt === -1)
132
+ break;
133
+ if (s.startsWith("<!--", lt)) {
134
+ const end = s.indexOf("-->", lt + 4);
135
+ i = end === -1 ? s.length : end + 3;
136
+ continue;
137
+ }
138
+ const c = s.charAt(lt + 1);
139
+ if (!/[a-zA-Z]/.test(c)) {
140
+ const gt = s.indexOf(">", lt);
141
+ i = gt === -1 ? s.length : gt + 1;
142
+ continue;
143
+ }
144
+ let j = lt + 1;
145
+ while (j < s.length && !isSpace(s[j]) && s[j] !== "/" && s[j] !== ">")
146
+ j++;
147
+ const name = s.slice(lt + 1, j).toLowerCase();
148
+ const attrs = new Map();
149
+ let closed = false;
150
+ while (j < s.length) {
151
+ while (j < s.length && (isSpace(s[j]) || s[j] === "/"))
152
+ j++;
153
+ if (s[j] === ">") {
154
+ j++;
155
+ closed = true;
156
+ break;
157
+ }
158
+ let k = j;
159
+ while (k < s.length && !isSpace(s[k]) && s[k] !== "=" && s[k] !== ">" && s[k] !== "/")
160
+ k++;
161
+ if (k === j) {
162
+ j++;
163
+ continue;
164
+ }
165
+ const an = s.slice(j, k).toLowerCase();
166
+ j = k;
167
+ while (j < s.length && isSpace(s[j]))
168
+ j++;
169
+ let value = "";
170
+ if (s[j] === "=") {
171
+ j++;
172
+ while (j < s.length && isSpace(s[j]))
173
+ j++;
174
+ if (s[j] === '"' || s[j] === "'") {
175
+ const q = s[j];
176
+ const e = s.indexOf(q, j + 1);
177
+ value = s.slice(j + 1, e === -1 ? s.length : e);
178
+ j = e === -1 ? s.length : e + 1;
179
+ }
180
+ else {
181
+ let e = j;
182
+ while (e < s.length && !isSpace(s[e]) && s[e] !== ">")
183
+ e++;
184
+ value = s.slice(j, e);
185
+ j = e;
186
+ }
187
+ }
188
+ if (!attrs.has(an))
189
+ attrs.set(an, value);
190
+ }
191
+ if (!closed)
192
+ break;
193
+ let end = j;
194
+ let inner = "";
195
+ if (RAW_TEXT.has(name)) {
196
+ if (lower === null)
197
+ lower = s.toLowerCase();
198
+ const close = lower.indexOf("</" + name, j);
199
+ if (close === -1) {
200
+ inner = s.slice(j);
201
+ end = s.length;
202
+ }
203
+ else {
204
+ inner = s.slice(j, close);
205
+ const gt = s.indexOf(">", close);
206
+ end = gt === -1 ? s.length : gt + 1;
207
+ }
208
+ }
209
+ out.push({ name, start: lt, end, attrs, inner });
210
+ i = end;
211
+ }
212
+ return out;
213
+ }
214
+ const HEAD_CONTENT = new Set(["meta", "link", "base", "script", "style", "noscript"]);
215
+ /** The dedupe key of an element ("" when it never replaces another). */
216
+ export function headKey(el) {
217
+ const a = el.attrs;
218
+ if (el.name === "meta") {
219
+ if (a.has("charset"))
220
+ return "meta:charset";
221
+ if (a.has("name"))
222
+ return "meta:name:" + (a.get("name") || "").toLowerCase();
223
+ if (a.has("property"))
224
+ return "meta:property:" + (a.get("property") || "").toLowerCase();
225
+ if (a.has("http-equiv"))
226
+ return "meta:http-equiv:" + (a.get("http-equiv") || "").toLowerCase();
227
+ return "";
228
+ }
229
+ if (el.name === "link") {
230
+ const rel = (a.get("rel") || "").toLowerCase().split(/\s+/);
231
+ if (rel.includes("canonical"))
232
+ return "link:canonical";
233
+ return "";
234
+ }
235
+ if (el.name === "base")
236
+ return "base";
237
+ return "";
238
+ }
239
+ // A repeated property (og:image) is legitimate; every other key is single.
240
+ function singleKey(key) {
241
+ return key !== "" && !key.startsWith("meta:property:");
242
+ }
243
+ function signature(el) {
244
+ const attrs = [...el.attrs.entries()].sort((x, y) => (x[0] < y[0] ? -1 : x[0] > y[0] ? 1 : 0));
245
+ return el.name + "|" + attrs.map(([k, v]) => k + "=" + v).join("&") + "|" + el.inner;
246
+ }
247
+ /** The head tags of a <Head> fragment: only head content, last single key wins. */
248
+ export function parseHeadTags(fragment) {
249
+ const tags = [];
250
+ for (const el of scanHeadElements(fragment)) {
251
+ if (!HEAD_CONTENT.has(el.name))
252
+ continue;
253
+ tags.push({ html: fragment.slice(el.start, el.end), key: headKey(el), el });
254
+ }
255
+ const last = new Map();
256
+ tags.forEach((t, i) => {
257
+ if (singleKey(t.key))
258
+ last.set(t.key, i);
259
+ });
260
+ return tags.filter((t, i) => !singleKey(t.key) || last.get(t.key) === i);
261
+ }
262
+ /**
263
+ * Merges page head content into the head section of a document: `head` is the
264
+ * text from the start of the document up to (not including) </head>. Returns
265
+ * the new head section.
266
+ */
267
+ export function mergeHeadSection(head, title, fragment) {
268
+ const tags = fragment ? parseHeadTags(fragment) : [];
269
+ if (title === "" && tags.length === 0)
270
+ return head;
271
+ const els = scanHeadElements(head);
272
+ // Edits are collected as [start, end, replacement] over the original text.
273
+ const edits = [];
274
+ const pageKeys = new Set(tags.map((t) => t.key).filter((k) => k !== ""));
275
+ const kept = new Set();
276
+ let titleDone = false;
277
+ for (const el of els) {
278
+ if (el.name === "title" && title !== "" && !titleDone) {
279
+ edits.push([el.start, el.end, "<title>" + title + "</title>"]);
280
+ titleDone = true;
281
+ continue;
282
+ }
283
+ if (el.name === "title" && title !== "") {
284
+ edits.push([el.start, el.end, ""]);
285
+ continue;
286
+ }
287
+ const key = headKey(el);
288
+ if (key !== "" && pageKeys.has(key)) {
289
+ edits.push([el.start, el.end, ""]);
290
+ continue;
291
+ }
292
+ kept.add(signature(el));
293
+ }
294
+ let add = "";
295
+ if (title !== "" && !titleDone)
296
+ add += "<title>" + title + "</title>";
297
+ for (const t of tags) {
298
+ const sig = signature(t.el);
299
+ if (kept.has(sig))
300
+ continue;
301
+ kept.add(sig);
302
+ add += t.html;
303
+ }
304
+ let out = "";
305
+ let at = 0;
306
+ for (const [s, e, r] of edits.sort((x, y) => x[0] - y[0])) {
307
+ out += head.slice(at, s) + r;
308
+ at = e;
309
+ }
310
+ out += head.slice(at);
311
+ return out + add;
312
+ }
313
+ /** Index where the head section of a document ends (</head>, else <body), or -1. */
314
+ export function headEndOf(doc) {
315
+ const lower = doc.toLowerCase();
316
+ const h = lower.indexOf("</head");
317
+ if (h !== -1)
318
+ return h;
319
+ return lower.indexOf("<body");
320
+ }
321
+ /** Merges the title and head tags into the head of a whole document. */
322
+ export function mergeHead(doc, title, fragment) {
323
+ if (title === "" && fragment === "")
324
+ return doc;
325
+ const end = headEndOf(doc);
326
+ if (end === -1)
327
+ return doc;
328
+ return mergeHeadSection(doc.slice(0, end), title, fragment) + doc.slice(end);
329
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,131 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { Head, renderToStringAsync, jsx } from "./server.js";
3
+ import { mergeHead, parseHeadTags, takeHead } from "./head-tags.js";
4
+ // The merge cases below are mirrored in internal/build/headmerge_test.go: the
5
+ // Go host and this handler must produce the same document head.
6
+ const MERGE_CASES = [
7
+ {
8
+ name: "adds tags before </head>, title when the shell has none",
9
+ doc: "<html><head><meta charset=UTF-8></head><body>x</body></html>",
10
+ title: "Post",
11
+ head: '<meta name="description" content="d"><link rel="canonical" href="https://e.com/a">',
12
+ want: "<html><head><meta charset=UTF-8><title>Post</title>" +
13
+ '<meta name="description" content="d"><link rel="canonical" href="https://e.com/a"></head><body>x</body></html>',
14
+ },
15
+ {
16
+ name: "page wins over baked tags with the same name, property and canonical (minified shell)",
17
+ doc: "<head><meta name=description content=\"layout\"/><meta property=og:title content=Site /><meta property=og:site_name content=Site />" +
18
+ "<link rel=canonical href=https://e.com/layout /><title>Baked</title></head>",
19
+ title: "Fresh",
20
+ head: '<meta name="description" content="page"><meta property="og:title" content="Page">' +
21
+ '<link rel="canonical" href="https://e.com/page">',
22
+ want: "<head><meta property=og:site_name content=Site /><title>Fresh</title>" +
23
+ '<meta name="description" content="page"><meta property="og:title" content="Page">' +
24
+ '<link rel="canonical" href="https://e.com/page"></head>',
25
+ },
26
+ {
27
+ name: "repeated property keeps every tag, repeated name keeps the last",
28
+ doc: "<head></head>",
29
+ title: "",
30
+ head: '<meta property="og:image" content="a"><meta property="og:image" content="b">' +
31
+ '<meta name="robots" content="index"><meta name="robots" content="noindex">',
32
+ want: '<head><meta property="og:image" content="a"><meta property="og:image" content="b"><meta name="robots" content="noindex"></head>',
33
+ },
34
+ {
35
+ name: "identical tags are not added twice, scripts and links are appended",
36
+ doc: '<head><link rel=stylesheet href=/a.css><script type=application/ld+json>{"a":1}</script></head>',
37
+ title: "",
38
+ head: '<link rel="stylesheet" href="/a.css"><link rel="stylesheet" href="/b.css">' +
39
+ '<script type="application/ld+json">{"a":1}</script><script type="application/ld+json">{"b":2}</script>',
40
+ want: '<head><link rel=stylesheet href=/a.css><script type=application/ld+json>{"a":1}</script>' +
41
+ '<link rel="stylesheet" href="/b.css"><script type="application/ld+json">{"b":2}</script></head>',
42
+ },
43
+ {
44
+ name: "a meta inside a baked script is not a tag, other elements are dropped",
45
+ doc: '<head><script>var s="<meta name=description content=x>";</script></head>',
46
+ title: "",
47
+ head: '<meta name="description" content="p"><div>no</div><p>no</p>',
48
+ want: '<head><script>var s="<meta name=description content=x>";</script><meta name="description" content="p"></head>',
49
+ },
50
+ {
51
+ name: "escaped attribute values pass through",
52
+ doc: "<head></head>",
53
+ title: "A &amp; B",
54
+ head: '<meta name="description" content="About &lt;&quot;x&quot;&gt; &amp; more">',
55
+ want: '<head><title>A &amp; B</title><meta name="description" content="About &lt;&quot;x&quot;&gt; &amp; more"></head>',
56
+ },
57
+ {
58
+ name: "no head tags and no title leaves the document alone",
59
+ doc: "<head><title>Baked</title></head>",
60
+ title: "",
61
+ head: "",
62
+ want: "<head><title>Baked</title></head>",
63
+ },
64
+ {
65
+ name: "title only replaces the baked one",
66
+ doc: "<head><title>Baked</title><meta name=description content=keep></head>",
67
+ title: "New",
68
+ head: "",
69
+ want: "<head><title>New</title><meta name=description content=keep></head>",
70
+ },
71
+ ];
72
+ describe("takeHead", () => {
73
+ it("lifts the title and the Head content out of the body, in place order", () => {
74
+ const html = '<main><!--krate-head--><title>T</title><meta name="description" content="d"><!--/krate-head--><h1>x</h1>' +
75
+ '<!--krate-head--><link rel="canonical" href="/c"><!--/krate-head--></main>';
76
+ const out = takeHead(html);
77
+ expect(out.title).toBe("T");
78
+ expect(out.head).toBe('<meta name="description" content="d"><link rel="canonical" href="/c">');
79
+ expect(out.html).toBe("<main><h1>x</h1></main>");
80
+ });
81
+ it("keeps a body <meta itemprop> that is not inside <Head>", () => {
82
+ const html = '<div itemscope><meta itemprop="name" content="n"><span>x</span></div>';
83
+ expect(takeHead(html)).toEqual({ title: "", head: "", html });
84
+ });
85
+ it("flattens nested Head blocks and keeps an svg title", () => {
86
+ const html = '<!--krate-head--><meta name="a" content="1"><!--krate-head--><meta name="b" content="2"><!--/krate-head--><!--/krate-head-->' +
87
+ "<svg><title>icon</title></svg>";
88
+ const out = takeHead(html);
89
+ expect(out.head).toBe('<meta name="a" content="1"><meta name="b" content="2">');
90
+ expect(out.html).toBe("<svg><title>icon</title></svg>");
91
+ expect(out.title).toBe("");
92
+ });
93
+ it("an unterminated Head block does not swallow the page", () => {
94
+ const out = takeHead('<p>a</p><!--krate-head--><meta name="x" content="y">');
95
+ expect(out.html).toBe("<p>a</p>");
96
+ expect(out.head).toBe('<meta name="x" content="y">');
97
+ });
98
+ });
99
+ describe("mergeHead", () => {
100
+ for (const c of MERGE_CASES) {
101
+ it(c.name, () => {
102
+ expect(mergeHead(c.doc, c.title, c.head)).toBe(c.want);
103
+ });
104
+ }
105
+ it("does nothing to a document without a head section", () => {
106
+ expect(mergeHead("<p>x</p>", "T", '<meta name="a" content="b">')).toBe("<p>x</p>");
107
+ });
108
+ });
109
+ describe("parseHeadTags", () => {
110
+ it("reads unquoted, quoted and valueless attributes", () => {
111
+ const tags = parseHeadTags("<script async src=/x.js></script><link rel='canonical' href=\"/c\"/>");
112
+ expect(tags.map((t) => t.el.name)).toEqual(["script", "link"]);
113
+ expect(tags[0].el.attrs.get("src")).toBe("/x.js");
114
+ expect(tags[0].el.attrs.has("async")).toBe(true);
115
+ expect(tags[1].key).toBe("link:canonical");
116
+ });
117
+ });
118
+ describe("<Head> in a request-time render", () => {
119
+ it("renders its children between markers and script text raw", async () => {
120
+ const html = await renderToStringAsync(jsx(Head, {
121
+ children: [
122
+ jsx("meta", { name: "description", content: 'a "b" <c>' }),
123
+ jsx("script", { type: "application/ld+json", children: JSON.stringify({ n: "</script><b>" }) }),
124
+ ],
125
+ }));
126
+ const out = takeHead(html);
127
+ expect(out.html).toBe("");
128
+ expect(out.head).toContain('<meta name="description" content="a &quot;b&quot; &lt;c&gt;">');
129
+ expect(out.head).toContain('<script type="application/ld+json">{"n":"<\\/script><b>"}</script>');
130
+ });
131
+ });
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Highlights code that changes at run time, in the browser.
3
+ *
4
+ * A `<Code lang="ts">{code()}</Code>` whose text is not known at build time is
5
+ * written as plain text between slot markers, inside a
6
+ * `<code data-krate-hl="ts">`. This module watches such elements: when the
7
+ * text changes (a signal updates the slot) it shows the new text as is, waits
8
+ * for a quiet moment, then swaps in highlighted markup. The tokenizer and the
9
+ * language's tables are not part of the runtime: they are a separate chunk the
10
+ * compiler writes only for the languages a page uses, loaded here on first use
11
+ * (`window.__KRATE_HL` maps a language to its chunk).
12
+ *
13
+ * Highlighting happens in the browser only for code that is truly dynamic.
14
+ * Text known at build time is highlighted by the compiler and ships no
15
+ * JavaScript for it.
16
+ */
17
+ interface HighlightChunk {
18
+ highlight(code: string, lang: string, lines?: string): string | null;
19
+ trimSpace(s: string): string;
20
+ }
21
+ declare global {
22
+ interface Window {
23
+ /** Language name to the URL of the chunk that highlights it. */
24
+ __KRATE_HL?: Record<string, string>;
25
+ /** Replaces dynamic import() when loading a chunk (tests). */
26
+ __KRATE_HL_LOAD?: (url: string) => Promise<HighlightChunk>;
27
+ }
28
+ }
29
+ /**
30
+ * Highlights code with the chunk for its language, loading it first. Resolves
31
+ * to the inner HTML of a highlighted block (what the compiler writes for the
32
+ * same code), or null when the language is not available on this page or the
33
+ * text is too large to highlight; show it as plain text then.
34
+ */
35
+ export declare function krateHighlight(code: string, lang: string, lines?: string): Promise<string | null>;
36
+ /**
37
+ * Starts highlighting every `<code data-krate-hl>` under root, and the ones
38
+ * added to the page afterwards. The compiler calls this at the end of a page's
39
+ * script, for pages that have such code.
40
+ */
41
+ export declare function krateHighlightInit(root?: ParentNode): void;
42
+ export {};
@@ -0,0 +1,176 @@
1
+ /**
2
+ * Highlights code that changes at run time, in the browser.
3
+ *
4
+ * A `<Code lang="ts">{code()}</Code>` whose text is not known at build time is
5
+ * written as plain text between slot markers, inside a
6
+ * `<code data-krate-hl="ts">`. This module watches such elements: when the
7
+ * text changes (a signal updates the slot) it shows the new text as is, waits
8
+ * for a quiet moment, then swaps in highlighted markup. The tokenizer and the
9
+ * language's tables are not part of the runtime: they are a separate chunk the
10
+ * compiler writes only for the languages a page uses, loaded here on first use
11
+ * (`window.__KRATE_HL` maps a language to its chunk).
12
+ *
13
+ * Highlighting happens in the browser only for code that is truly dynamic.
14
+ * Text known at build time is highlighted by the compiler and ships no
15
+ * JavaScript for it.
16
+ */
17
+ /** Quiet time, in ms, before changed code is highlighted. */
18
+ const DEBOUNCE_MS = 120;
19
+ const chunks = new Map();
20
+ /** Loads the chunk for a language, once. Resolves to null when the page has none. */
21
+ function loadChunk(lang) {
22
+ let p = chunks.get(lang);
23
+ if (p === undefined) {
24
+ const url = typeof window !== "undefined" && window.__KRATE_HL ? window.__KRATE_HL[lang] : undefined;
25
+ const load = window.__KRATE_HL_LOAD || ((u) => import(/* @vite-ignore */ u));
26
+ p = url ? load(url).then((m) => m, () => null) : Promise.resolve(null);
27
+ chunks.set(lang, p);
28
+ }
29
+ return p;
30
+ }
31
+ /**
32
+ * Highlights code with the chunk for its language, loading it first. Resolves
33
+ * to the inner HTML of a highlighted block (what the compiler writes for the
34
+ * same code), or null when the language is not available on this page or the
35
+ * text is too large to highlight; show it as plain text then.
36
+ */
37
+ export function krateHighlight(code, lang, lines) {
38
+ return loadChunk(lang).then((c) => (c ? c.highlight(c.trimSpace(code), lang, lines) : null));
39
+ }
40
+ const bound = new WeakSet();
41
+ /** The slot markers inside a code element, or null when it has none. */
42
+ function markersOf(code) {
43
+ for (let n = code.firstChild; n; n = n.nextSibling) {
44
+ if (n.nodeType === 8 && n.data.startsWith("k:")) {
45
+ const end = "/" + n.data;
46
+ for (let m = n.nextSibling; m; m = m.nextSibling) {
47
+ if (m.nodeType === 8 && m.data === end)
48
+ return [n, m];
49
+ }
50
+ }
51
+ }
52
+ return null;
53
+ }
54
+ function bindCode(code) {
55
+ if (bound.has(code))
56
+ return;
57
+ bound.add(code);
58
+ const lang = code.getAttribute("data-krate-hl") || "";
59
+ if (!lang)
60
+ return;
61
+ /** The text last shown or highlighted. */
62
+ let last = null;
63
+ let timer;
64
+ let version = 0;
65
+ let own = false;
66
+ const region = () => {
67
+ const m = markersOf(code);
68
+ return m ? { start: m[0], end: m[1] } : { start: null, end: null };
69
+ };
70
+ const firstNode = (r) => (r.start ? r.start.nextSibling : code.firstChild);
71
+ const textOf = (r) => {
72
+ let s = "";
73
+ for (let n = firstNode(r); n && n !== r.end; n = n.nextSibling)
74
+ s += n.textContent || "";
75
+ return s;
76
+ };
77
+ // Server markup that is already highlighted (a request-time render) holds
78
+ // the text as it is; remember it so unchanged code is not highlighted again.
79
+ const init = region();
80
+ const first = firstNode(init);
81
+ if (first && first.nodeType === 1)
82
+ last = textOf(init);
83
+ const apply = (html) => {
84
+ const r = region();
85
+ const tpl = document.createElement("template");
86
+ tpl.innerHTML = html;
87
+ own = true;
88
+ for (let n = firstNode(r); n && n !== r.end;) {
89
+ const next = n.nextSibling;
90
+ if (n.parentNode)
91
+ n.parentNode.removeChild(n);
92
+ n = next;
93
+ }
94
+ (r.end && r.end.parentNode ? r.end.parentNode : code).insertBefore(tpl.content, r.end);
95
+ own = false;
96
+ // Our own writes are not changes to the text.
97
+ mo.takeRecords();
98
+ };
99
+ const schedule = (text, delay) => {
100
+ const mine = ++version;
101
+ if (timer !== undefined)
102
+ clearTimeout(timer);
103
+ timer = setTimeout(() => {
104
+ timer = undefined;
105
+ loadChunk(lang).then((c) => {
106
+ if (!c || mine !== version || !code.isConnected)
107
+ return;
108
+ const html = c.highlight(c.trimSpace(text), lang);
109
+ if (html !== null && mine === version)
110
+ apply(html);
111
+ });
112
+ }, delay);
113
+ };
114
+ // Called when the slot wrote new text. The slot's text node comes first; any
115
+ // highlighted markup after it is from the text before and is dropped.
116
+ const sync = () => {
117
+ if (own)
118
+ return;
119
+ if (!code.isConnected) {
120
+ mo.disconnect();
121
+ return;
122
+ }
123
+ const r = region();
124
+ const node = firstNode(r);
125
+ if (!node || node.nodeType !== 3)
126
+ return;
127
+ for (let n = node.nextSibling; n && n !== r.end;) {
128
+ const next = n.nextSibling;
129
+ n.parentNode && n.parentNode.removeChild(n);
130
+ n = next;
131
+ }
132
+ const text = node.textContent || "";
133
+ if (text === last)
134
+ return;
135
+ const firstRun = last === null;
136
+ last = text;
137
+ schedule(text, firstRun ? 0 : DEBOUNCE_MS);
138
+ };
139
+ const mo = new MutationObserver(sync);
140
+ mo.observe(code, { childList: true, characterData: true, subtree: true });
141
+ sync();
142
+ }
143
+ let watching = false;
144
+ /** Binds code elements that are added to the page later (a conditional branch, a route change). */
145
+ function watchForNewCode() {
146
+ if (watching || typeof MutationObserver === "undefined")
147
+ return;
148
+ watching = true;
149
+ new MutationObserver((records) => {
150
+ for (const r of records) {
151
+ for (let i = 0; i < r.addedNodes.length; i++) {
152
+ const n = r.addedNodes[i];
153
+ if (n.nodeType !== 1)
154
+ continue;
155
+ const el = n;
156
+ if (el.matches("code[data-krate-hl]"))
157
+ bindCode(el);
158
+ else if (el.querySelector("code[data-krate-hl]"))
159
+ krateHighlightInit(el);
160
+ }
161
+ }
162
+ }).observe(document.documentElement, { childList: true, subtree: true });
163
+ }
164
+ /**
165
+ * Starts highlighting every `<code data-krate-hl>` under root, and the ones
166
+ * added to the page afterwards. The compiler calls this at the end of a page's
167
+ * script, for pages that have such code.
168
+ */
169
+ export function krateHighlightInit(root) {
170
+ const scope = root || document;
171
+ const codes = scope.querySelectorAll("code[data-krate-hl]");
172
+ for (let i = 0; i < codes.length; i++)
173
+ bindCode(codes[i]);
174
+ if (!root)
175
+ watchForNewCode();
176
+ }