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