ovr 6.2.4 → 7.0.0-next.0

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 (136) hide show
  1. package/README.md +3 -1
  2. package/dist/app/index.d.ts +51 -7
  3. package/dist/app/index.d.ts.map +1 -1
  4. package/dist/app/index.js +163 -28
  5. package/dist/auth/auth-data.d.ts +26 -0
  6. package/dist/auth/auth-data.d.ts.map +1 -0
  7. package/dist/auth/auth-data.js +42 -0
  8. package/dist/auth/cbor.d.ts +50 -0
  9. package/dist/auth/cbor.d.ts.map +1 -0
  10. package/dist/auth/cbor.js +200 -0
  11. package/dist/auth/client-source.d.ts +3 -0
  12. package/dist/auth/client-source.d.ts.map +1 -0
  13. package/dist/auth/client-source.js +3 -0
  14. package/dist/auth/client.d.ts +3 -0
  15. package/dist/auth/client.d.ts.map +1 -0
  16. package/dist/auth/client.js +186 -0
  17. package/dist/auth/configure.d.ts +28 -0
  18. package/dist/auth/configure.d.ts.map +1 -0
  19. package/dist/auth/configure.js +228 -0
  20. package/dist/auth/der.d.ts +6 -0
  21. package/dist/auth/der.d.ts.map +1 -0
  22. package/dist/auth/der.js +36 -0
  23. package/dist/auth/index.d.ts +242 -0
  24. package/dist/auth/index.d.ts.map +1 -0
  25. package/dist/auth/index.js +152 -0
  26. package/dist/auth/issue.d.ts +36 -0
  27. package/dist/auth/issue.d.ts.map +1 -0
  28. package/dist/auth/issue.js +47 -0
  29. package/dist/auth/metadata.d.ts +22 -0
  30. package/dist/auth/metadata.d.ts.map +1 -0
  31. package/dist/auth/metadata.js +134 -0
  32. package/dist/auth/oauth.d.ts +29 -0
  33. package/dist/auth/oauth.d.ts.map +1 -0
  34. package/dist/auth/oauth.js +724 -0
  35. package/dist/auth/passkey.d.ts +101 -0
  36. package/dist/auth/passkey.d.ts.map +1 -0
  37. package/dist/auth/passkey.js +393 -0
  38. package/dist/auth/state.d.ts +49 -0
  39. package/dist/auth/state.d.ts.map +1 -0
  40. package/dist/auth/state.js +184 -0
  41. package/dist/auth/storage.d.ts +193 -0
  42. package/dist/auth/storage.d.ts.map +1 -0
  43. package/dist/auth/storage.js +410 -0
  44. package/dist/auth/token.d.ts +12 -0
  45. package/dist/auth/token.d.ts.map +1 -0
  46. package/dist/auth/token.js +39 -0
  47. package/dist/context/index.d.ts +86 -16
  48. package/dist/context/index.d.ts.map +1 -1
  49. package/dist/context/index.js +166 -42
  50. package/dist/cookie/index.d.ts +3 -0
  51. package/dist/cookie/index.d.ts.map +1 -1
  52. package/dist/cookie/index.js +1 -0
  53. package/dist/database/index.d.ts +262 -0
  54. package/dist/database/index.d.ts.map +1 -0
  55. package/dist/database/index.js +807 -0
  56. package/dist/form/index.d.ts +699 -0
  57. package/dist/form/index.d.ts.map +1 -0
  58. package/dist/form/index.js +901 -0
  59. package/dist/index.d.ts +10 -3
  60. package/dist/index.d.ts.map +1 -1
  61. package/dist/index.js +9 -3
  62. package/dist/jsx/elements.d.ts +28 -2
  63. package/dist/jsx/elements.d.ts.map +1 -1
  64. package/dist/jsx/index.d.ts +20 -4
  65. package/dist/jsx/index.d.ts.map +1 -1
  66. package/dist/jsx/index.js +6 -65
  67. package/dist/limiter/index.d.ts +65 -0
  68. package/dist/limiter/index.d.ts.map +1 -0
  69. package/dist/limiter/index.js +157 -0
  70. package/dist/markdown/index.d.ts +61 -0
  71. package/dist/markdown/index.d.ts.map +1 -0
  72. package/dist/markdown/index.js +1160 -0
  73. package/dist/markup/index.d.ts +188 -0
  74. package/dist/markup/index.d.ts.map +1 -0
  75. package/dist/markup/index.js +718 -0
  76. package/dist/mcp/index.d.ts +73 -0
  77. package/dist/mcp/index.d.ts.map +1 -0
  78. package/dist/mcp/index.js +988 -0
  79. package/dist/middleware/index.d.ts +3 -4
  80. package/dist/middleware/index.d.ts.map +1 -1
  81. package/dist/multipart/index.d.ts +53 -7
  82. package/dist/multipart/index.d.ts.map +1 -1
  83. package/dist/multipart/index.js +332 -124
  84. package/dist/route/index.d.ts +226 -80
  85. package/dist/route/index.d.ts.map +1 -1
  86. package/dist/route/index.js +239 -99
  87. package/dist/schema/index.d.ts +307 -734
  88. package/dist/schema/index.d.ts.map +1 -1
  89. package/dist/schema/index.js +783 -1050
  90. package/dist/table/index.d.ts +132 -0
  91. package/dist/table/index.d.ts.map +1 -0
  92. package/dist/table/index.js +188 -0
  93. package/dist/trie/index.js +4 -4
  94. package/dist/util/index.d.ts +37 -5
  95. package/dist/util/index.d.ts.map +1 -1
  96. package/dist/util/index.js +156 -41
  97. package/package.json +11 -4
  98. package/src/app/index.ts +230 -42
  99. package/src/auth/auth-data.ts +56 -0
  100. package/src/auth/cbor.ts +231 -0
  101. package/src/auth/client-source.ts +3 -0
  102. package/src/auth/client.ts +205 -0
  103. package/src/auth/configure.ts +279 -0
  104. package/src/auth/der.ts +35 -0
  105. package/src/auth/index.ts +387 -0
  106. package/src/auth/issue.ts +52 -0
  107. package/src/auth/metadata.ts +149 -0
  108. package/src/auth/oauth.ts +882 -0
  109. package/src/auth/passkey.ts +556 -0
  110. package/src/auth/state.ts +213 -0
  111. package/src/auth/storage.ts +572 -0
  112. package/src/auth/token.ts +67 -0
  113. package/src/context/index.ts +240 -65
  114. package/src/cookie/index.ts +3 -0
  115. package/src/database/index.ts +1193 -0
  116. package/src/form/index.ts +1720 -0
  117. package/src/index.ts +10 -3
  118. package/src/jsx/elements.ts +45 -25
  119. package/src/jsx/index.ts +24 -69
  120. package/src/limiter/index.ts +221 -0
  121. package/src/markdown/index.ts +1322 -0
  122. package/src/markup/index.ts +853 -0
  123. package/src/mcp/conformance.2025-11-25.yml +39 -0
  124. package/src/mcp/conformance.2026-07-28.yml +56 -0
  125. package/src/mcp/index.ts +1262 -0
  126. package/src/middleware/index.ts +5 -6
  127. package/src/multipart/index.ts +410 -158
  128. package/src/route/index.ts +559 -278
  129. package/src/schema/index.ts +1542 -2256
  130. package/src/table/index.ts +387 -0
  131. package/src/trie/index.ts +4 -4
  132. package/src/util/index.ts +163 -49
  133. package/dist/render/index.d.ts +0 -79
  134. package/dist/render/index.d.ts.map +0 -1
  135. package/dist/render/index.js +0 -257
  136. package/src/render/index.ts +0 -314
@@ -0,0 +1,1160 @@
1
+ import { Group, Render, Tag, readable } from "../markup/index.js";
2
+ /** Internal protocol for the MCP endpoint, to write a form as its tool's call. */
3
+ export const tools = Symbol("tools");
4
+ /** Writes Markdown from rendered chunks, one block at a time */
5
+ class Writer {
6
+ /** Elements and their contents that are not written */
7
+ static #skip = new Set([
8
+ "head",
9
+ "script",
10
+ "style",
11
+ "template",
12
+ "svg",
13
+ "canvas",
14
+ "iframe",
15
+ "object",
16
+ "dialog",
17
+ "math",
18
+ ]);
19
+ /** Containers that are not written themselves at the top level */
20
+ static #containers = new Set([
21
+ "html",
22
+ "body",
23
+ "main",
24
+ "div",
25
+ "section",
26
+ "article",
27
+ "header",
28
+ "footer",
29
+ "nav",
30
+ "aside",
31
+ "hgroup",
32
+ "search",
33
+ ]);
34
+ /** Lists */
35
+ static #lists = new Set(["ul", "ol", "menu"]);
36
+ /** Block elements, everything else is inline */
37
+ static #blockTags = new Set([
38
+ ...Writer.#containers,
39
+ // raw HTML, its own block between blocks
40
+ "!",
41
+ "p",
42
+ "h1",
43
+ "h2",
44
+ "h3",
45
+ "h4",
46
+ "h5",
47
+ "h6",
48
+ ...Writer.#lists,
49
+ "li",
50
+ "pre",
51
+ "blockquote",
52
+ "hr",
53
+ "table",
54
+ "thead",
55
+ "tbody",
56
+ "tfoot",
57
+ "tr",
58
+ "td",
59
+ "th",
60
+ "caption",
61
+ "details",
62
+ "summary",
63
+ "dl",
64
+ "dt",
65
+ "dd",
66
+ "figure",
67
+ "figcaption",
68
+ "form",
69
+ "fieldset",
70
+ "legend",
71
+ "address",
72
+ "noscript",
73
+ ]);
74
+ /** Attributes of an element without any, never changed */
75
+ static #none = Object.freeze({});
76
+ #options;
77
+ /** Open elements below the top level */
78
+ #stack = [];
79
+ /** Inline content at the top level */
80
+ #pending = Writer.#node("");
81
+ /** Depth inside a skipped element */
82
+ #skipping = 0;
83
+ /** Writing a form's table, where a control in a cell is named */
84
+ #controls = false;
85
+ /** Reader mode: before, inside, or after `<main>` */
86
+ #main = "before";
87
+ /** `<main>` elements open, so a nested one does not end the outer one */
88
+ #depth = 0;
89
+ /** Output before `<main>`, written at the end if there is no `<main>` */
90
+ #before = [];
91
+ /** Output ready to be read */
92
+ #output = "";
93
+ /** Blocks written */
94
+ #count = 0;
95
+ /** @param options Conversion options */
96
+ constructor(options = {}) {
97
+ this.#options = options;
98
+ }
99
+ /** @returns The rest of the Markdown */
100
+ end() {
101
+ this.#finish();
102
+ if (this.#main === "before") {
103
+ for (const block of this.#before)
104
+ this.#write(block, true);
105
+ }
106
+ if (this.#count)
107
+ this.#output += "\n";
108
+ return this.read();
109
+ }
110
+ /** @param chunk Rendered chunk, read by its kind instead of parsing its HTML */
111
+ chunk(chunk) {
112
+ if (chunk instanceof Group) {
113
+ for (const child of chunk.chunks)
114
+ this.chunk(child);
115
+ }
116
+ else if (chunk instanceof Tag) {
117
+ if (!chunk.props)
118
+ return this.#close(chunk.name);
119
+ let attrs;
120
+ for (const name in chunk.props) {
121
+ const value = chunk.props[name];
122
+ // as `jsx` writes them, `true` is an attribute without a value
123
+ if (name !== "children" && value != null && value !== false)
124
+ (attrs ??= {})[name.toLowerCase()] =
125
+ value === true ? "" : String(value);
126
+ }
127
+ // most elements have none, and a block's elements are all held until
128
+ // it ends, so they share one empty set, which is never changed
129
+ this.#open(chunk.name, attrs ?? Writer.#none);
130
+ if (chunk.closed)
131
+ this.#close(chunk.name);
132
+ }
133
+ else if (chunk.raw)
134
+ this.#raw(chunk.value);
135
+ else
136
+ this.#text(chunk.value);
137
+ }
138
+ /** @returns Markdown written since it was last read */
139
+ read() {
140
+ const output = this.#output;
141
+ this.#output = "";
142
+ return output;
143
+ }
144
+ /** @param text Added to the open element */
145
+ #text(text) {
146
+ if (!text || this.#skipping)
147
+ return;
148
+ const parent = this.#stack.at(-1) ?? this.#pending;
149
+ const last = parent.children.length - 1;
150
+ if (typeof parent.children[last] === "string")
151
+ parent.children[last] += text;
152
+ else
153
+ parent.children.push(text);
154
+ }
155
+ /**
156
+ * Raw HTML, such as from `Markup.raw`, is valid Markdown, so it is
157
+ * written as it is.
158
+ *
159
+ * @param html HTML
160
+ */
161
+ #raw(html) {
162
+ if (!html || this.#skipping)
163
+ return;
164
+ const node = Writer.#node("!", {}, html);
165
+ const parent = this.#stack.at(-1);
166
+ if (parent)
167
+ parent.children.push(node);
168
+ else if (Writer.#isBlock(node)) {
169
+ // its own block at the top level
170
+ this.#flush();
171
+ this.#write(html);
172
+ }
173
+ else
174
+ this.#pending.children.push(node);
175
+ }
176
+ #open(tag, attrs) {
177
+ if (this.#skipping) {
178
+ this.#skipping++;
179
+ return;
180
+ }
181
+ if (Writer.#skip.has(tag) ||
182
+ "hidden" in attrs ||
183
+ attrs["aria-hidden"] === "true") {
184
+ this.#skipping = 1;
185
+ return;
186
+ }
187
+ if (tag === "main" && this.#main !== "after") {
188
+ // the page's content, however it is wrapped, such as in a custom
189
+ // element: what came before is dropped, and its contents are read as
190
+ // top level
191
+ if (this.#main === "before") {
192
+ this.#stack.length = 0;
193
+ this.#pending = Writer.#node("");
194
+ this.#before = [];
195
+ this.#main = "inside";
196
+ }
197
+ // a nested one is counted, so it does not end the outer one
198
+ this.#depth++;
199
+ return;
200
+ }
201
+ if (!this.#stack.length) {
202
+ // a container is a block too, but is not written itself
203
+ if (Writer.#blockTags.has(tag))
204
+ this.#flush();
205
+ if (Writer.#containers.has(tag))
206
+ return;
207
+ }
208
+ const node = Writer.#node(tag, attrs);
209
+ (this.#stack.at(-1) ?? this.#pending).children.push(node);
210
+ this.#stack.push(node);
211
+ }
212
+ #close(tag) {
213
+ if (this.#skipping) {
214
+ this.#skipping--;
215
+ return;
216
+ }
217
+ if (tag === "main" && this.#main === "inside") {
218
+ if (--this.#depth)
219
+ return;
220
+ // elements left open end with it, so nothing after it is written
221
+ this.#finish();
222
+ this.#main = "after";
223
+ return;
224
+ }
225
+ const index = this.#stack.findLastIndex((node) => node.tag === tag);
226
+ if (index === -1) {
227
+ if (!this.#stack.length && Writer.#containers.has(tag))
228
+ this.#flush();
229
+ return;
230
+ }
231
+ const closed = this.#stack.splice(index);
232
+ const node = closed[0];
233
+ if (!index && (Writer.#blockTags.has(node.tag) || Writer.#holds(node))) {
234
+ // a complete top level block
235
+ this.#pending.children.pop();
236
+ this.#flush();
237
+ this.#write(this.#block(node));
238
+ return;
239
+ }
240
+ // held until its block ends, such as each row of a long table, so its
241
+ // children, final now, are kept at their size instead of the room an
242
+ // array grows to as it is added to
243
+ for (const done of closed)
244
+ done.children = done.children.slice();
245
+ }
246
+ /** Ends the elements left open, and writes what is pending */
247
+ #finish() {
248
+ while (this.#stack.length)
249
+ this.#close(this.#stack.at(-1).tag);
250
+ this.#flush();
251
+ }
252
+ /** Writes inline content at the top level as a paragraph */
253
+ #flush() {
254
+ const pending = this.#pending;
255
+ if (!pending.children.length)
256
+ return;
257
+ this.#pending = Writer.#node("");
258
+ this.#write(this.#block(pending));
259
+ }
260
+ /**
261
+ * @param block Markdown block
262
+ * @param force Write even before `<main>`
263
+ */
264
+ #write(block, force) {
265
+ if (!block)
266
+ return;
267
+ if (this.#main === "after")
268
+ return;
269
+ if (this.#main === "before" && !force) {
270
+ this.#before.push(block);
271
+ return;
272
+ }
273
+ this.#output += (this.#count++ ? "\n\n" : "") + block;
274
+ }
275
+ /**
276
+ * @param children Nodes
277
+ * @param separator Between blocks
278
+ * @param list Before a list, an item's own list follows it without a gap
279
+ * @returns Markdown blocks, with inline runs as paragraphs
280
+ */
281
+ #blocks(children, separator = "\n\n", list = separator) {
282
+ let blocks = "";
283
+ let run = [];
284
+ const add = (block, between = separator) => {
285
+ if (block)
286
+ blocks += (blocks && between) + block;
287
+ };
288
+ const paragraph = () => {
289
+ if (!run.length)
290
+ return;
291
+ add(this.#paragraph(run));
292
+ run = [];
293
+ };
294
+ for (const child of children) {
295
+ if (typeof child === "string" ||
296
+ !(Writer.#isBlock(child) || Writer.#holds(child))) {
297
+ run.push(child);
298
+ }
299
+ else {
300
+ paragraph();
301
+ const block = this.#block(child);
302
+ add(block,
303
+ // a list, or a tool's call on one line, follows what it belongs to
304
+ Writer.#lists.has(child.tag) ||
305
+ (child.tag === "form" &&
306
+ this.#options[tools] &&
307
+ !block.includes("\n"))
308
+ ? list
309
+ : separator);
310
+ }
311
+ }
312
+ paragraph();
313
+ return blocks;
314
+ }
315
+ /**
316
+ * @param children Inline nodes
317
+ * @returns Paragraph with line start characters escaped
318
+ */
319
+ #paragraph(children) {
320
+ return this.#inline(children)
321
+ .split("\n")
322
+ .map((line) => line
323
+ .trim()
324
+ // a quote needs no space after it, and a line of `=` makes a heading of the one above
325
+ .replace(/^(>|=+$|(?:[#+-]|-{2,})(?=\s|$))/, "\\$1")
326
+ // the escape goes before the delimiter, one before a digit is text
327
+ .replace(/^(\d+)([.)])(?=\s|$)/, "$1\\$2"))
328
+ .join("\n")
329
+ .trim();
330
+ }
331
+ /**
332
+ * @param node Block element
333
+ * @returns Markdown
334
+ */
335
+ #block(node) {
336
+ const { tag, children } = node;
337
+ switch (tag) {
338
+ case "":
339
+ case "p":
340
+ case "caption":
341
+ case "legend":
342
+ return this.#paragraph(children);
343
+ case "h1":
344
+ case "h2":
345
+ case "h3":
346
+ case "h4":
347
+ case "h5":
348
+ case "h6": {
349
+ const text = this.#inline(children).replace(/\s+/g, " ").trim();
350
+ return text && `${"#".repeat(Number(tag[1]))} ${text}`;
351
+ }
352
+ case "dt":
353
+ case "summary":
354
+ return Writer.#wrap(this.#paragraph(children), "**");
355
+ case "ul":
356
+ case "ol":
357
+ case "menu":
358
+ return this.#list(node);
359
+ case "pre":
360
+ return this.#pre(node);
361
+ case "blockquote": {
362
+ const text = this.#blocks(children);
363
+ return text && text.replace(/^/gm, "> ").replace(/^> $/gm, ">");
364
+ }
365
+ case "hr":
366
+ return "---";
367
+ case "table":
368
+ return this.#table(node);
369
+ case "form":
370
+ return this.#form(node);
371
+ case "!":
372
+ return children[0];
373
+ default:
374
+ return this.#blocks(children);
375
+ }
376
+ }
377
+ /**
378
+ * @param node List element
379
+ * @returns Markdown list
380
+ */
381
+ #list(node) {
382
+ const ordered = node.tag === "ol";
383
+ let n = Number(node.attrs.start ?? 1) || 1;
384
+ const items = [];
385
+ // lines that are not blank, which need no indent
386
+ const indent = (text, width) => text.replace(/\n(?=[^\n])/g, "\n" + " ".repeat(width)).trimEnd();
387
+ const visit = (parent) => {
388
+ for (const child of parent.children) {
389
+ if (typeof child === "string")
390
+ continue;
391
+ if (child.tag === "li") {
392
+ const marker = ordered ? `${n++}. ` : "- ";
393
+ items.push(marker +
394
+ indent(this.#blocks(child.children, "\n\n", "\n"), marker.length));
395
+ }
396
+ else if (Writer.#lists.has(child.tag)) {
397
+ // a list directly in a list belongs to the item before it
398
+ const width = ordered ? `${n - 1}. `.length : 2;
399
+ const nested = this.#list(child);
400
+ if (!nested)
401
+ continue;
402
+ // on the lines after the item, indented as its contents are
403
+ if (items.length)
404
+ items[items.length - 1] += indent(`\n${nested}`, width);
405
+ else
406
+ items.push(nested);
407
+ }
408
+ else
409
+ visit(child); // items inside a wrapper, such as a custom element
410
+ }
411
+ };
412
+ visit(node);
413
+ return items.join("\n");
414
+ }
415
+ /**
416
+ * @param node `<pre>` element
417
+ * @returns Fenced code block
418
+ */
419
+ #pre(node) {
420
+ const code = node.children.find((child) => typeof child !== "string" && child.tag === "code");
421
+ const language = /(?:^|\s)lang(?:uage)?-(\S+)/.exec(code?.attrs.class ?? node.attrs.class ?? "")?.[1];
422
+ // the newline HTML ignores after `<pre>`, and a last one, which the
423
+ // fence's own line break replaces
424
+ const text = Writer.#content(node).replace(/^\n|\n$/g, "");
425
+ const fence = "`".repeat(Math.max(3, Writer.#ticks(text) + 1));
426
+ return `${fence}${language ?? ""}\n${text}\n${fence}`;
427
+ }
428
+ /** Schemes links and images may use */
429
+ static #schemes = new Set(["http:", "https:", "mailto:", "tel:"]);
430
+ /**
431
+ * @param node `<table>` element
432
+ * @returns GitHub flavored Markdown table
433
+ */
434
+ #table(node) {
435
+ const rows = [];
436
+ let caption = "";
437
+ // a form with fields cannot be written in a row, so it follows the table
438
+ const forms = [];
439
+ const take = (parent) => {
440
+ parent.children = parent.children.flatMap((child) => {
441
+ if (typeof child === "string")
442
+ return [child];
443
+ if (child.tag === "form") {
444
+ const line = this.#form(child, true);
445
+ if (line)
446
+ return [Writer.#node("!", {}, line)];
447
+ forms.push(child);
448
+ return [];
449
+ }
450
+ take(child);
451
+ return [child];
452
+ });
453
+ };
454
+ const visit = (parent) => {
455
+ for (const child of parent.children) {
456
+ if (typeof child === "string")
457
+ continue;
458
+ if (child.tag === "caption")
459
+ caption = this.#paragraph(child.children);
460
+ else if (child.tag === "tr") {
461
+ rows.push(child.children
462
+ .filter((cell) => typeof cell !== "string" &&
463
+ (cell.tag === "td" || cell.tag === "th"))
464
+ .map((cell) => {
465
+ take(cell);
466
+ return this.#inline(cell.children)
467
+ .replace(/\s+/g, " ")
468
+ .trim()
469
+ .replaceAll("|", "\\|");
470
+ }));
471
+ }
472
+ else
473
+ visit(child);
474
+ }
475
+ };
476
+ visit(node);
477
+ let table = "";
478
+ if (rows.length) {
479
+ // a loop, a spread of many rows would overflow the stack
480
+ let width = 0;
481
+ for (const row of rows)
482
+ width = Math.max(width, row.length);
483
+ // the header sets the columns, shorter rows are filled in by the reader
484
+ const line = (row) => `| ${row.join(" | ")} |`;
485
+ table = [
486
+ line(Array.from({ length: width }, (_, i) => rows[0][i] ?? "")),
487
+ line(Array(width).fill("---")),
488
+ ...rows.slice(1).map(line),
489
+ ].join("\n");
490
+ }
491
+ return [caption, table, ...forms.map((form) => this.#form(form))]
492
+ .filter(Boolean)
493
+ .join("\n\n");
494
+ }
495
+ /**
496
+ * Describes a form: where it submits, its fields, and its buttons.
497
+ *
498
+ * @param node `<form>` element
499
+ * @param cell For a table's cell: one line, empty if it does not fit
500
+ * @returns Markdown
501
+ */
502
+ #form(node, cell) {
503
+ const method = (node.attrs.method ?? "GET").toUpperCase();
504
+ // an unsafe action is described as the page itself
505
+ const action = this.#url(node.attrs.action ?? "") ?? this.#url("");
506
+ const tool = this.#options[tools]?.(method, action);
507
+ // read through an MCP endpoint, only what the agent can call is a form
508
+ if (this.#options[tools] && !tool)
509
+ return "";
510
+ const labels = new Map();
511
+ const fields = [];
512
+ const byName = new Map();
513
+ const submits = [];
514
+ const notes = [];
515
+ let legend = "";
516
+ // labels with `for`
517
+ const collect = (parent) => {
518
+ for (const child of parent.children) {
519
+ if (typeof child === "string")
520
+ continue;
521
+ if (child.tag === "label" && child.attrs.for)
522
+ labels.set(child.attrs.for, Writer.#plain(child));
523
+ collect(child);
524
+ }
525
+ };
526
+ collect(node);
527
+ /** A new field, which a later control with its name may add to */
528
+ const add = (label, name, type) => {
529
+ const entry = {
530
+ label,
531
+ name,
532
+ type,
533
+ value: [],
534
+ options: [],
535
+ notes: [],
536
+ rules: [],
537
+ };
538
+ fields.push(entry);
539
+ byName.set(name, entry);
540
+ return entry;
541
+ };
542
+ const field = (control, label) => {
543
+ const { attrs } = control;
544
+ const name = attrs.name;
545
+ const type = control.tag === "input"
546
+ ? (attrs.type ?? "text").toLowerCase()
547
+ : control.tag;
548
+ if (type === "submit" || type === "image") {
549
+ submits.push(attrs.value ?? "Submit");
550
+ return;
551
+ }
552
+ // a tool's form shows its hidden values, such as an ID, which the
553
+ // tool's arguments need and the page shows nowhere else
554
+ if (type === "hidden" && tool && name && attrs.value !== undefined) {
555
+ add(name, name, type).value.push(attrs.value);
556
+ return;
557
+ }
558
+ if (!name || type === "hidden" || type === "button" || type === "reset")
559
+ return;
560
+ label =
561
+ label ||
562
+ (attrs.id && labels.get(attrs.id)) ||
563
+ attrs["aria-label"] ||
564
+ name;
565
+ if (type === "checkbox" || type === "radio") {
566
+ // a box without a label of its own, such as one in each row of a
567
+ // table, is its value alone
568
+ const option = (value, label) => `${value}${label !== value && label !== name ? ` (${label})` : ""}`;
569
+ let group = byName.get(name);
570
+ const value = attrs.value ?? "on";
571
+ if (group?.type === type)
572
+ group.lone = false;
573
+ else {
574
+ group = add(legend || label, name, type);
575
+ group.lone = type === "checkbox" && attrs.value === undefined;
576
+ }
577
+ group.options.push(option(value, label));
578
+ if ("checked" in attrs)
579
+ group.value.push(value);
580
+ Writer.#rules(group, attrs);
581
+ return;
582
+ }
583
+ const entry = add(label, name, type);
584
+ if (control.tag === "select") {
585
+ if ("multiple" in attrs)
586
+ entry.type = "select multiple";
587
+ const options = (parent) => {
588
+ for (const child of parent.children) {
589
+ if (typeof child === "string")
590
+ continue;
591
+ if (child.tag === "option") {
592
+ const text = Writer.#plain(child);
593
+ const value = child.attrs.value ?? text;
594
+ entry.options.push(`${value}${text && text !== value ? ` (${text})` : ""}`);
595
+ if ("selected" in child.attrs)
596
+ entry.value.push(value);
597
+ }
598
+ else
599
+ options(child);
600
+ }
601
+ };
602
+ options(control);
603
+ }
604
+ else if (control.tag === "textarea") {
605
+ const value = Writer.#content(control).replace(/^\n/, "");
606
+ if (value)
607
+ entry.value.push(value);
608
+ }
609
+ else if (attrs.value)
610
+ entry.value.push(attrs.value);
611
+ Writer.#rules(entry, attrs);
612
+ };
613
+ // a block among the notes, with a line between it and the others
614
+ const block = (text) => {
615
+ if (!text)
616
+ return;
617
+ if (notes.length && notes.at(-1))
618
+ notes.push("");
619
+ notes.push(text, "");
620
+ };
621
+ const visit = (parent, label, quiet) => {
622
+ for (const child of parent.children) {
623
+ if (typeof child === "string") {
624
+ // escaped as a paragraph is, so its text cannot write Markdown
625
+ if (!quiet && child.trim())
626
+ notes.push(this.#paragraph([child]));
627
+ continue;
628
+ }
629
+ switch (child.tag) {
630
+ case "input":
631
+ case "select":
632
+ case "textarea":
633
+ field(child, label);
634
+ break;
635
+ case "button":
636
+ if ((child.attrs.type ?? "submit") === "submit") {
637
+ let submit = Writer.#escape(Writer.#plain(child) || "Submit");
638
+ // a button that submits somewhere else, such as a delete
639
+ const to = child.attrs.formaction && this.#url(child.attrs.formaction);
640
+ if (to) {
641
+ const by = (child.attrs.formmethod ?? method).toUpperCase();
642
+ const other = this.#options[tools]?.(by, to);
643
+ submit += other
644
+ ? ` (${Writer.#call(other)})`
645
+ : ` (${Writer.#code(`${by} ${this.#href(to)}`)})`;
646
+ }
647
+ submits.push(submit);
648
+ }
649
+ break;
650
+ case "label":
651
+ // controls inside use the label
652
+ visit(child, child.attrs.for
653
+ ? labels.get(child.attrs.for)
654
+ : Writer.#plain(child, true), true);
655
+ break;
656
+ case "legend":
657
+ legend = Writer.#plain(child);
658
+ break;
659
+ case "table": {
660
+ // its controls are fields, and the table is kept, with each
661
+ // control named in its cell, a row's button included
662
+ const before = submits.length;
663
+ visit(child, label, true);
664
+ submits.length = before;
665
+ this.#controls = true;
666
+ block(this.#table(child));
667
+ this.#controls = false;
668
+ break;
669
+ }
670
+ case "pre":
671
+ block(this.#pre(child));
672
+ break;
673
+ case "!":
674
+ // raw HTML, as it is
675
+ if (!quiet)
676
+ block(child.children[0]);
677
+ break;
678
+ case "a":
679
+ case "p":
680
+ case "span":
681
+ case "small":
682
+ case "output":
683
+ case "noscript":
684
+ case "strong":
685
+ case "em": {
686
+ if (quiet)
687
+ break;
688
+ // the tool's input schema already describes the field with it
689
+ if (tool && "data-description" in child.attrs)
690
+ break;
691
+ if (child.tag !== "a" &&
692
+ child.children.some((c) => typeof c !== "string" &&
693
+ ["input", "select", "textarea", "button"].includes(c.tag))) {
694
+ visit(child, label);
695
+ break;
696
+ }
697
+ const text = this.#paragraph(child.tag === "a" ? [child] : child.children);
698
+ if (text) {
699
+ const last = fields.at(-1);
700
+ // messages after a field, such as errors, belong to it
701
+ if (last && child.tag !== "noscript" && !submits.length)
702
+ last.notes.push(text);
703
+ else
704
+ notes.push(text);
705
+ }
706
+ break;
707
+ }
708
+ default:
709
+ visit(child, label, quiet);
710
+ }
711
+ }
712
+ };
713
+ visit(node);
714
+ // how to encode the body, for an agent that submits it itself
715
+ const encoding = !tool && method !== "GET" && node.attrs.enctype
716
+ ? ` as ${Writer.#code(node.attrs.enctype)}`
717
+ : "";
718
+ // what the form calls: its tool, or the address it submits to
719
+ const call = tool
720
+ ? Writer.#call(tool)
721
+ : Writer.#code(`${method} ${this.#href(action)}`);
722
+ const submit = submits.join(", ");
723
+ while (notes.at(-1) === "")
724
+ notes.pop();
725
+ const lines = tool
726
+ ? // the tool's input schema describes the fields, so only what the
727
+ // page adds: current values, such as an edit form's, and messages
728
+ fields
729
+ .map((f) =>
730
+ // a single checkbox is a boolean argument, unchecked included
731
+ f.lone ? { ...f, value: [String(f.value.length > 0)] } : f)
732
+ .filter((f) => f.value.length || f.notes.length)
733
+ .map((f) => {
734
+ let line = `- ${Writer.#code(f.name)}`;
735
+ if (f.value.length)
736
+ line += `: ${Writer.#codes(f.value)}`;
737
+ return Writer.#notes(f, line);
738
+ })
739
+ : fields.map((f) => {
740
+ let line = `- ${Writer.#escape(f.label)} ${Writer.#code(f.name)} (${[f.type, ...f.rules].join(", ")})`;
741
+ if (f.options.length)
742
+ line += `, options: ${Writer.#codes(f.options)}`;
743
+ if (f.value.length)
744
+ line += `, value: ${Writer.#codes(f.value)}`;
745
+ return Writer.#notes(f, line);
746
+ });
747
+ // a call an agent can make as it is written, such as a delete beside
748
+ // each item, on one line, and only that fits in a table's cell
749
+ if ((tool || cell) && !lines.length && !notes.length)
750
+ return `${submit || "Submit"}: ${call}`;
751
+ if (cell)
752
+ return "";
753
+ return [
754
+ ...(tool
755
+ ? [
756
+ `**Tool:** ${Writer.#code(tool.name)}`,
757
+ "",
758
+ // arguments the address held, unless a field gives the same
759
+ ...Object.entries(tool.args)
760
+ .filter(([name]) => !byName.get(name)?.value.length)
761
+ .map((arg) => `- ${Writer.#argument(arg)}`),
762
+ ...lines,
763
+ ]
764
+ : [
765
+ `**Form:** ${call}${encoding}`,
766
+ ...(lines.length ? ["", ...lines] : []),
767
+ ]),
768
+ ...(notes.length ? ["", ...notes] : []),
769
+ ...(submits.length ? ["", `Submit: ${submit}`] : []),
770
+ ].join("\n");
771
+ }
772
+ /**
773
+ * @param tool Tool and the arguments an address gave
774
+ * @returns The call, as an agent makes it
775
+ */
776
+ static #call(tool) {
777
+ return [
778
+ `tool ${Writer.#code(tool.name)}`,
779
+ ...Object.entries(tool.args).map(Writer.#argument),
780
+ ].join(", ");
781
+ }
782
+ /**
783
+ * @param argument Name and value
784
+ * @returns The argument, as code
785
+ */
786
+ static #argument([name, value]) {
787
+ return `${Writer.#code(name)}: ${Writer.#code(value)}`;
788
+ }
789
+ /**
790
+ * @param field Field in a form
791
+ * @param line Its line
792
+ * @returns The line, with the field's notes below it
793
+ */
794
+ static #notes(field, line) {
795
+ for (const note of field.notes)
796
+ line += `\n - ${note}`;
797
+ return line;
798
+ }
799
+ /**
800
+ * @param children Inline nodes
801
+ * @returns Inline Markdown with whitespace collapsed
802
+ */
803
+ #inline(children) {
804
+ let out = "";
805
+ for (const child of children) {
806
+ if (typeof child === "string") {
807
+ out += Writer.#escape(child.replace(/\s+/g, " "));
808
+ continue;
809
+ }
810
+ const inner = () => this.#inline(child.children);
811
+ switch (child.tag) {
812
+ case "br":
813
+ out += "\n";
814
+ break;
815
+ case "!":
816
+ out += child.children[0];
817
+ break;
818
+ case "strong":
819
+ case "b":
820
+ out += Writer.#wrap(inner(), "**");
821
+ break;
822
+ case "em":
823
+ case "i":
824
+ case "cite":
825
+ case "dfn":
826
+ out += Writer.#wrap(inner(), "_");
827
+ break;
828
+ case "del":
829
+ case "s":
830
+ out += Writer.#wrap(inner(), "~~");
831
+ break;
832
+ case "code":
833
+ case "kbd":
834
+ case "samp":
835
+ out += Writer.#code(Writer.#content(child).replace(/\s+/g, " "));
836
+ break;
837
+ case "a": {
838
+ const text = inner().trim();
839
+ const href = child.attrs.href;
840
+ const resolved = href && !href.startsWith("#") && this.#url(href);
841
+ if (!href || resolved === undefined) {
842
+ out += text;
843
+ break;
844
+ }
845
+ const url = resolved ? this.#href(resolved) : href;
846
+ const destination = Writer.#destination(url);
847
+ out +=
848
+ text === url || !text
849
+ ? `<${destination}>`
850
+ : `[${text}](${destination})`;
851
+ break;
852
+ }
853
+ case "img": {
854
+ const url = child.attrs.src && this.#url(child.attrs.src);
855
+ if (url)
856
+ out += `![${Writer.#escape(child.attrs.alt ?? "")}](${Writer.#destination(this.#href(url))})`;
857
+ break;
858
+ }
859
+ case "input":
860
+ case "select":
861
+ case "textarea":
862
+ case "button": {
863
+ // controls outside of a form do nothing without a script
864
+ if (!this.#controls)
865
+ break;
866
+ const { name, value, type } = child.attrs;
867
+ if (child.tag === "button")
868
+ out += inner();
869
+ if (name && type !== "hidden") {
870
+ // a box sends "on" without a value, others what is typed
871
+ const sent = value ?? (type === "checkbox" || type === "radio" ? "on" : "");
872
+ out += ` ${Writer.#code(sent ? `${name}=${sent}` : name)} `;
873
+ }
874
+ break;
875
+ }
876
+ default:
877
+ out += Writer.#isBlock(child)
878
+ ? ` ${this.#blocks(child.children, "\n")} `
879
+ : inner();
880
+ }
881
+ }
882
+ return out;
883
+ }
884
+ /**
885
+ * @param href Possibly relative URL
886
+ * @returns Resolved URL, `undefined` if it is invalid or not a safe scheme such as `javascript:`
887
+ */
888
+ #url(href) {
889
+ try {
890
+ // parsed first, browsers remove characters such as tabs from the scheme
891
+ const url = new URL(href, this.#options.base ?? "http://localhost/");
892
+ if (Writer.#schemes.has(url.protocol))
893
+ return url;
894
+ }
895
+ catch { }
896
+ }
897
+ /**
898
+ * @param url URL
899
+ * @returns The URL as a link destination, characters that could end it are percent-encoded
900
+ */
901
+ static #destination(url) {
902
+ return url.replace(/[\s()<>]/g, (char) => `%${char.charCodeAt(0).toString(16).toUpperCase().padStart(2, "0")}`);
903
+ }
904
+ /**
905
+ * @param url Resolved URL
906
+ * @returns Relative when there is no base
907
+ */
908
+ #href(url) {
909
+ return this.#options.base ? url.href : url.pathname + url.search + url.hash;
910
+ }
911
+ /** Raw HTML that starts with a block element, or a comment */
912
+ static #rawBlock = new RegExp(`^\\s*<(?:!|(?:${[...Writer.#blockTags].filter((tag) => tag !== "!").join("|")})\\b)`, "i");
913
+ /**
914
+ * @param node Element
915
+ * @returns If the element is a block, raw HTML is one when it starts with one
916
+ */
917
+ static #isBlock(node) {
918
+ return node.tag === "!"
919
+ ? Writer.#rawBlock.test(node.children[0])
920
+ : Writer.#blockTags.has(node.tag);
921
+ }
922
+ /**
923
+ * @param node Inline element
924
+ * @returns If it holds blocks, so it is read as a container, such as a
925
+ * custom element around a card. A link is not, its contents are its text
926
+ */
927
+ static #holds(node) {
928
+ return (node.tag !== "a" &&
929
+ node.children.some((child) => typeof child !== "string" &&
930
+ (Writer.#isBlock(child) || Writer.#holds(child))));
931
+ }
932
+ /**
933
+ * @param tag Tag name
934
+ * @param attrs Attributes
935
+ * @returns New element node
936
+ */
937
+ static #node(tag, attrs = {}, ...children) {
938
+ return { tag, attrs, children };
939
+ }
940
+ /**
941
+ * @param field Field to add requirements to
942
+ * @param attrs Control attributes
943
+ */
944
+ static #rules(field, attrs) {
945
+ const rules = new Set(field.rules);
946
+ if ("required" in attrs)
947
+ rules.add("required");
948
+ if ("multiple" in attrs && field.type !== "select multiple")
949
+ rules.add("multiple");
950
+ for (const name of [
951
+ "min",
952
+ "max",
953
+ "minlength",
954
+ "maxlength",
955
+ "step",
956
+ "pattern",
957
+ "accept",
958
+ ]) {
959
+ if (attrs[name])
960
+ rules.add(`${name} ${attrs[name]}`);
961
+ }
962
+ field.rules = [...rules];
963
+ }
964
+ /**
965
+ * @param node Element
966
+ * @param omitControls Leave out the text of nested controls
967
+ * @returns Text content with whitespace collapsed
968
+ */
969
+ static #plain(node, omitControls) {
970
+ let text = "";
971
+ for (const child of node.children) {
972
+ if (typeof child === "string")
973
+ text += child;
974
+ else if (!omitControls || !["select", "textarea"].includes(child.tag))
975
+ text += " " + Writer.#plain(child, omitControls) + " ";
976
+ }
977
+ return text.replace(/\s+/g, " ").trim();
978
+ }
979
+ /**
980
+ * @param node Element
981
+ * @returns Raw text content
982
+ */
983
+ static #content(node) {
984
+ return node.children
985
+ .map((child) => typeof child === "string"
986
+ ? child
987
+ : child.tag === "br"
988
+ ? "\n"
989
+ : Writer.#content(child))
990
+ .join("");
991
+ }
992
+ /**
993
+ * @param text Text to put in inline code
994
+ * @returns Code span
995
+ */
996
+ static #code(text) {
997
+ // one line, so a value cannot start a line of its own, such as a form
998
+ text = text.replace(/\s*[\r\n]+\s*/g, " ");
999
+ const ticks = "`".repeat(Writer.#ticks(text) + 1);
1000
+ const pad = /^`|`$|^ .* $/.test(text) ? " " : "";
1001
+ return `${ticks}${pad}${text}${pad}${ticks}`;
1002
+ }
1003
+ /**
1004
+ * @param values Values
1005
+ * @returns Each as code, separated by commas
1006
+ */
1007
+ static #codes(values) {
1008
+ return values.map((value) => Writer.#code(value)).join(", ");
1009
+ }
1010
+ /**
1011
+ * @param text Text
1012
+ * @returns Length of its longest run of backticks
1013
+ */
1014
+ static #ticks(text) {
1015
+ // a loop, a spread of many runs would overflow the stack
1016
+ let longest = 0;
1017
+ for (const [run] of text.matchAll(/`+/g))
1018
+ longest = Math.max(longest, run.length);
1019
+ return longest;
1020
+ }
1021
+ /**
1022
+ * @param text Inline Markdown
1023
+ * @param marker Emphasis marker
1024
+ * @returns Text wrapped in the marker, with outer whitespace kept outside
1025
+ */
1026
+ static #wrap(text, marker) {
1027
+ const [, before, inner, after] = /^(\s*)([\s\S]*?)(\s*)$/.exec(text);
1028
+ return inner ? `${before}${marker}${inner}${marker}${after}` : text;
1029
+ }
1030
+ /**
1031
+ * @param text Plain text
1032
+ * @returns Text with Markdown syntax characters escaped
1033
+ */
1034
+ static #escape(text) {
1035
+ // most text has none of these characters, and one test costs less than
1036
+ // the replaces below, which each read all of it
1037
+ if (!/[\\`*[\]<~&_]/.test(text))
1038
+ return text;
1039
+ return (text
1040
+ .replace(/[\\`*[\]<]/g, "\\$&")
1041
+ // a run of `~`, which strikes text through or opens a fence, and not
1042
+ // one alone, as in `~/projects`; and a character reference
1043
+ .replace(/~(?=~)|(?<=~)~|&(?=#?\w+;)/g, "\\$&")
1044
+ .replace(/(^|[^\p{L}\p{N}])_|_(?=[^\p{L}\p{N}]|$)/gu, (m) => m.replace("_", "\\_")));
1045
+ }
1046
+ }
1047
+ /**
1048
+ * Renders an element to Markdown a step at a time, as a render of markup
1049
+ * steps through its chunks, so neither waits unless the element does.
1050
+ */
1051
+ class Blocks {
1052
+ /** Render of the element's chunks */
1053
+ #render;
1054
+ /** Writes Markdown from the chunks */
1055
+ #writer;
1056
+ /** The end of the Markdown is written */
1057
+ #ended = false;
1058
+ /**
1059
+ * @param element Element to render
1060
+ * @param options Markdown options
1061
+ */
1062
+ constructor(element, options) {
1063
+ this.#render = new Render(element, undefined);
1064
+ this.#writer = new Writer(options);
1065
+ }
1066
+ /**
1067
+ * @returns The Markdown of the next complete block or blocks, a promise to
1068
+ * wait for before the next step, or `undefined` once all of it is written
1069
+ */
1070
+ step() {
1071
+ for (let result; (result = this.#render.step());) {
1072
+ if (result instanceof Promise)
1073
+ return result;
1074
+ this.#writer.chunk(result);
1075
+ const text = this.#writer.read();
1076
+ if (text)
1077
+ return text;
1078
+ }
1079
+ if (this.#ended)
1080
+ return;
1081
+ this.#ended = true;
1082
+ return this.#writer.end() || undefined;
1083
+ }
1084
+ /** Ends the render if it is not read to its end. */
1085
+ close() {
1086
+ return this.#render.close();
1087
+ }
1088
+ }
1089
+ /**
1090
+ * Renders an element to Markdown, as an `AsyncIterable` of blocks, a stream,
1091
+ * or a string, from the same elements `Markup` renders. Each top level block is
1092
+ * written as soon as it closes, and when the page has a `<main>` element, only
1093
+ * its contents are kept. Raw HTML is written as it is.
1094
+ *
1095
+ * ```tsx
1096
+ * const markdown = await Markdown.string(<Post post={post} />, { base: url });
1097
+ * ```
1098
+ */
1099
+ export class Markdown {
1100
+ /** Element to render */
1101
+ #element;
1102
+ /** Markdown options */
1103
+ #options;
1104
+ /**
1105
+ * Creates an `AsyncIterable` that renders the element to Markdown.
1106
+ *
1107
+ * @param element Element to render
1108
+ * @param options Markdown options
1109
+ */
1110
+ constructor(element, options) {
1111
+ this.#element = element;
1112
+ this.#options = options;
1113
+ }
1114
+ /** @yields Markdown as each block completes */
1115
+ async *[Symbol.asyncIterator]() {
1116
+ const blocks = new Blocks(this.#element, this.#options);
1117
+ try {
1118
+ for (let result; (result = blocks.step());) {
1119
+ if (typeof result === "string")
1120
+ yield result;
1121
+ else
1122
+ await result;
1123
+ }
1124
+ }
1125
+ finally {
1126
+ await blocks.close();
1127
+ }
1128
+ }
1129
+ /**
1130
+ * @param element Element to render
1131
+ * @param options Markdown options
1132
+ * @returns `ReadableStream` of Markdown
1133
+ */
1134
+ static stream(element, options) {
1135
+ return readable(new Blocks(element, options));
1136
+ }
1137
+ /**
1138
+ * Converts a render into a fully concatenated string of Markdown.
1139
+ *
1140
+ * @param element Element to render
1141
+ * @param options Markdown options
1142
+ * @returns Concatenated Markdown
1143
+ */
1144
+ static async string(element, options) {
1145
+ const blocks = new Blocks(element, options);
1146
+ let markdown = "";
1147
+ try {
1148
+ for (let result; (result = blocks.step());) {
1149
+ if (typeof result === "string")
1150
+ markdown += result;
1151
+ else
1152
+ await result;
1153
+ }
1154
+ }
1155
+ finally {
1156
+ await blocks.close();
1157
+ }
1158
+ return markdown;
1159
+ }
1160
+ }