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,853 @@
1
+ import type { JSX } from "../jsx/index.js";
2
+ import { Codec, Size } from "../util/index.js";
3
+
4
+ /** Chunk of a rendered element: text, or markup */
5
+ class Chunk {
6
+ /** Text, or markup when `raw` */
7
+ readonly value: string;
8
+
9
+ /** `true` if the value is markup, which is not escaped */
10
+ readonly raw: boolean | undefined;
11
+
12
+ /**
13
+ * Chunk of a rendered element.
14
+ *
15
+ * @param value Text, escaped when it is rendered as markup
16
+ * @param raw Set to `true` if the value is safe markup that should not be escaped
17
+ */
18
+ constructor(value: unknown, raw?: boolean) {
19
+ this.value = String(value ?? "");
20
+ this.raw = raw;
21
+ }
22
+
23
+ /**
24
+ * @returns Safe markup to render
25
+ */
26
+ toString(): string {
27
+ return this.raw ? this.value : Markup.escape(this.value);
28
+ }
29
+ }
30
+
31
+ /**
32
+ * Start or end tag of an element, internal to ovr. It keeps the element's
33
+ * name and props, so the render can also be written as Markdown.
34
+ */
35
+ export class Tag extends Chunk {
36
+ /** Tag name */
37
+ readonly name: string;
38
+
39
+ /** Props of a start tag, `undefined` for an end tag */
40
+ readonly props: JSX.Props | undefined;
41
+
42
+ /** `true` for a start tag without an end tag, such as `<input>` */
43
+ readonly closed: boolean | undefined;
44
+
45
+ /**
46
+ * @param name Tag name
47
+ * @param props Props of a start tag
48
+ * @param closed The element has no end tag
49
+ */
50
+ constructor(name: string, props?: JSX.Props, closed?: boolean) {
51
+ super("", true);
52
+ this.name = name;
53
+ this.props = props;
54
+ this.closed = closed;
55
+ }
56
+
57
+ /** @returns The tag's markup, built when it is written */
58
+ override toString() {
59
+ const { name, props } = this;
60
+ if (!props) return `</${name}>`;
61
+
62
+ // faster to concatenate attributes than to yield them as separate chunks
63
+ let opening = name;
64
+
65
+ for (const key in props) {
66
+ // more memory efficient to skip children instead of destructuring and using ...rest
67
+ if (key === "children") continue;
68
+
69
+ const value = props[key];
70
+
71
+ if (value === true) {
72
+ // just put the key without the value
73
+ opening += ` ${key}`;
74
+ } else if (typeof value === "string") {
75
+ opening += ` ${key}="${Markup.escape(value, true)}"`;
76
+ } else if (typeof value === "number" || typeof value === "bigint") {
77
+ opening += ` ${key}="${value}"`;
78
+ }
79
+ // otherwise, don't include the attribute
80
+ }
81
+
82
+ return name === "html"
83
+ ? `<!doctype html><${opening}>`
84
+ : name === "xml"
85
+ ? `<?${opening}?>`
86
+ : `<${opening}>`;
87
+ }
88
+ }
89
+
90
+ /**
91
+ * Chunks a later sibling rendered while an earlier one was still rendering,
92
+ * yielded together once they are next. Internal to ovr.
93
+ */
94
+ export class Group extends Chunk {
95
+ /** Chunks in order */
96
+ readonly chunks: Chunk[];
97
+
98
+ /** @param chunks Chunks in order */
99
+ constructor(chunks: Chunk[]) {
100
+ super("", true);
101
+ this.chunks = chunks;
102
+ }
103
+
104
+ override toString() {
105
+ // `join` is several times slower for chunks than for strings
106
+ let markup = "";
107
+ for (const chunk of this.chunks) markup += chunk.toString();
108
+ return markup;
109
+ }
110
+ }
111
+
112
+ /**
113
+ * HTML tags that do not require a closing tag.
114
+ *
115
+ * [MDN Reference](https://developer.mozilla.org/en-US/docs/Glossary/Void_element#self-closing_tags)
116
+ */
117
+ const voids = new Set([
118
+ "area",
119
+ "base",
120
+ "br",
121
+ "col",
122
+ "embed",
123
+ "hr",
124
+ "img",
125
+ "input",
126
+ "link",
127
+ "meta",
128
+ "source",
129
+ "track",
130
+ "wbr",
131
+ "xml",
132
+ ]);
133
+
134
+ /**
135
+ * Element created by `jsx`, internal to ovr. A render reads its tag and props
136
+ * instead of iterating it, which costs a promise for each chunk at every level
137
+ * of the tree. Anything else can still iterate it as the generator of its
138
+ * chunks.
139
+ */
140
+ export class Element implements AsyncGenerator<Chunk, void, unknown> {
141
+ /** Tag name, or component */
142
+ readonly tag: string | ((props: any) => JSX.Element);
143
+
144
+ /** Props */
145
+ readonly props: JSX.Props;
146
+
147
+ /** Rendered, or being rendered, which a generator is only once */
148
+ #taken = false;
149
+
150
+ /** Chunks for what iterates the element itself */
151
+ #chunks?: AsyncGenerator<Chunk, void, unknown>;
152
+
153
+ /**
154
+ * @param tag Tag name, or component
155
+ * @param props Props
156
+ */
157
+ constructor(tag: string | ((props: any) => JSX.Element), props: JSX.Props) {
158
+ this.tag = tag;
159
+ this.props = props;
160
+ }
161
+
162
+ /** @returns `true` once, to the render that writes the element */
163
+ take() {
164
+ return !this.#taken && (this.#taken = true);
165
+ }
166
+
167
+ /**
168
+ * Generator of the element's chunks, empty if it was already rendered.
169
+ * Chunks, not strings, so a render it is part of keeps its tags and what
170
+ * is already escaped.
171
+ */
172
+ get #generator(): AsyncGenerator<Chunk, void, unknown> {
173
+ return (this.#chunks ??= (async function* (element) {
174
+ const render = new Render(element, undefined);
175
+
176
+ try {
177
+ for (let result: Step; (result = render.step());) {
178
+ if (result instanceof Chunk) yield result;
179
+ else await result;
180
+ }
181
+ } finally {
182
+ await render.close();
183
+ }
184
+ // a copy the render can take, since this one now counts as rendered
185
+ })(this.take() ? new Element(this.tag, this.props) : null));
186
+ }
187
+
188
+ next() {
189
+ return this.#generator.next();
190
+ }
191
+
192
+ return(value: void | PromiseLike<void>) {
193
+ return this.#generator.return(value);
194
+ }
195
+
196
+ throw(error: unknown) {
197
+ return this.#generator.throw(error);
198
+ }
199
+
200
+ [Symbol.asyncIterator]() {
201
+ return this;
202
+ }
203
+
204
+ async [Symbol.asyncDispose]() {
205
+ await this.return();
206
+ }
207
+ }
208
+
209
+ /** Internal protocol for a render, to read the element a `Markup` renders. */
210
+ const source = Symbol("source");
211
+
212
+ /** One step of a render: a chunk, a wait before the next step, or nothing once it is done */
213
+ export type Step = Chunk | Promise<unknown> | undefined;
214
+
215
+ /** Iterator a render is reading, of a generator or anything async iterable */
216
+ type Sequence = {
217
+ readonly iterator: Iterator<JSX.Element> | AsyncIterator<JSX.Element>;
218
+ readonly async: boolean;
219
+ };
220
+
221
+ /**
222
+ * Renders an element one chunk at a time, internal to ovr. A step is
223
+ * synchronous unless the element has to be waited for, so nested elements cost
224
+ * a loop instead of a generator and a promise for each chunk at every level.
225
+ */
226
+ export class Render {
227
+ /** Chunks rendered before the element is its parent's current child */
228
+ queue: Chunk[] | undefined;
229
+
230
+ /** Waiting, set by the parent of a child */
231
+ waiting = false;
232
+
233
+ /** Nothing more to render, set by the parent of a child */
234
+ done = false;
235
+
236
+ /** Element to render next */
237
+ #element: unknown;
238
+
239
+ /** `0` no element is next, `1` an element is, `2` the value of a promise is */
240
+ #next: 0 | 1 | 2 = 1;
241
+
242
+ /** Disables escaping, for content that is not markup */
243
+ readonly #raw: boolean | undefined;
244
+
245
+ /** What follows the element: end tags, and iterators and children in progress */
246
+ #stack: (Tag | Sequence | Parallel)[] | undefined;
247
+
248
+ /** The wait the last step returned, if it did */
249
+ #wait: Promise<unknown> | undefined;
250
+
251
+ /**
252
+ * @param element Element to render
253
+ * @param raw Set to `true` to disable escaping
254
+ */
255
+ constructor(element: unknown, raw: boolean | undefined) {
256
+ this.#element = element;
257
+ this.#raw = raw;
258
+ }
259
+
260
+ /**
261
+ * @returns The next chunk, a promise to wait for before the next step, or
262
+ * `undefined` once the element is rendered
263
+ */
264
+ step(): Step {
265
+ this.#wait = undefined;
266
+
267
+ for (;;) {
268
+ if (this.#next) {
269
+ let element = this.#element;
270
+ const resolved = this.#next === 2;
271
+ this.#next = 0;
272
+ this.#element = undefined;
273
+
274
+ if (!resolved) {
275
+ // modifications
276
+ // these are required to allow functions to be used as children
277
+ // instead of creating a separate component to use them
278
+ if (typeof element === "function") element = element();
279
+ if (element instanceof Promise) {
280
+ return (this.#wait = element.then((value: unknown) => {
281
+ this.#element = value;
282
+ this.#next = 2;
283
+ }));
284
+ }
285
+ }
286
+
287
+ // resolve based on type
288
+
289
+ if (element == null || typeof element === "boolean" || element === "") {
290
+ // should not render
291
+ continue;
292
+ }
293
+
294
+ if (element instanceof Chunk) {
295
+ // already escaped or raw
296
+ return element;
297
+ }
298
+
299
+ if (typeof element === "object") {
300
+ // an element is written as markup whatever the options, so one
301
+ // in content that is not markup is iterated as it always was
302
+ if (element instanceof Element && !this.#raw && element.take()) {
303
+ const { tag, props } = element;
304
+
305
+ if (typeof tag === "function") {
306
+ // component or fragment
307
+ this.#element = tag(props);
308
+ this.#next = 1;
309
+ continue;
310
+ }
311
+
312
+ // intrinsic element, its markup is only built if it is written
313
+
314
+ // if children and a void element, render it like normal
315
+ // to account for cases like XML <link>content</link>
316
+ // assumes the user knows what they are doing
317
+ const closed = props.children == null && voids.has(tag);
318
+
319
+ if (!closed) {
320
+ (this.#stack ??= []).push(new Tag(tag));
321
+ this.#element = props.children;
322
+ this.#next = 1;
323
+ }
324
+
325
+ return new Tag(tag, props, closed);
326
+ }
327
+
328
+ if (element instanceof Markup) {
329
+ // its element, which its strings would be escaped as text
330
+ this.#element = element[source];
331
+ this.#next = 1;
332
+ continue;
333
+ }
334
+
335
+ if (Symbol.asyncIterator in element) {
336
+ // any async iterable - lazily resolve
337
+ (this.#stack ??= []).push({
338
+ iterator: (element as AsyncIterable<JSX.Element>)[
339
+ Symbol.asyncIterator
340
+ ](),
341
+ async: true,
342
+ });
343
+ continue;
344
+ }
345
+
346
+ if (Symbol.iterator in element) {
347
+ (this.#stack ??= []).push(
348
+ "next" in element
349
+ ? // sync generator - lazily resolve, avoids loading all in memory
350
+ {
351
+ iterator: (element as Iterable<JSX.Element>)[
352
+ Symbol.iterator
353
+ ](),
354
+ async: false,
355
+ }
356
+ : // other iterable - array, set, etc.
357
+ new Parallel(element as Iterable<JSX.Element>, this.#raw),
358
+ );
359
+ continue;
360
+ }
361
+ }
362
+
363
+ // primitive or other object
364
+ return new Chunk(element, this.#raw);
365
+ }
366
+
367
+ const stack = this.#stack;
368
+ const top = stack?.[stack.length - 1];
369
+
370
+ if (!top) return;
371
+
372
+ if (top instanceof Parallel) {
373
+ // stays on the stack to be closed if it throws
374
+ const result = top.step();
375
+
376
+ if (!result) stack!.pop();
377
+ else if (result instanceof Chunk) return result;
378
+ else return (this.#wait = result);
379
+ } else {
380
+ // an iterator is off the stack while it is read, so one that
381
+ // throws is not closed as well
382
+ stack!.pop();
383
+
384
+ if (top instanceof Tag) return top; // end tag
385
+
386
+ if (top.async) {
387
+ return (this.#wait = Promise.resolve(top.iterator.next()).then(
388
+ (result) => {
389
+ if (!result.done) {
390
+ stack!.push(top);
391
+ this.#element = result.value;
392
+ this.#next = 1;
393
+ }
394
+ },
395
+ ));
396
+ }
397
+
398
+ const result = (top.iterator as Iterator<JSX.Element>).next();
399
+
400
+ if (!result.done) {
401
+ stack!.push(top);
402
+ this.#element = result.value;
403
+ this.#next = 1;
404
+ }
405
+ }
406
+ }
407
+ }
408
+
409
+ /**
410
+ * Ends the iterators and children in progress, so a generator runs its
411
+ * `finally` block when the render fails or is not read to its end.
412
+ */
413
+ async close() {
414
+ try {
415
+ // as `return` does for a generator: a step that is waiting first goes
416
+ // on to its chunk, so a promise it reaches is not left to reject unhandled
417
+ if (this.#wait) {
418
+ await this.#wait;
419
+
420
+ for (
421
+ let result: Step;
422
+ (result = this.step()) && !(result instanceof Chunk);
423
+ )
424
+ await result;
425
+ }
426
+ } catch {}
427
+
428
+ for (let top; (top = this.#stack?.pop());) {
429
+ try {
430
+ if (top instanceof Parallel) await top.close();
431
+ else if (!(top instanceof Tag)) await top.iterator.return?.();
432
+ } catch {}
433
+ }
434
+ }
435
+ }
436
+
437
+ /**
438
+ * Children of an array, or another iterable that is not a generator: rendered
439
+ * at the same time, and yielded in order.
440
+ */
441
+ class Parallel {
442
+ /** Render of each child */
443
+ readonly #children: Render[];
444
+
445
+ /**
446
+ * Children after the current one that can step: not waiting, and not done.
447
+ * Only these are looked at as the others wait, so a list of many children
448
+ * that each wait costs no more for each one that resolves.
449
+ */
450
+ readonly #idle: Render[] = [];
451
+
452
+ /** Index of the child being yielded */
453
+ #current = 0;
454
+
455
+ /** A child failed */
456
+ #failed = false;
457
+
458
+ /** What the child failed with */
459
+ #error: unknown;
460
+
461
+ /** Closed, so no child goes on */
462
+ #closed = false;
463
+
464
+ /** Ends the wait for a child */
465
+ #notify: (() => void) | undefined;
466
+
467
+ /**
468
+ * @param elements Children
469
+ * @param raw Set to `true` to disable escaping
470
+ */
471
+ constructor(elements: Iterable<JSX.Element>, raw: boolean | undefined) {
472
+ this.#children = [];
473
+
474
+ // each child starts before any is waited for
475
+ for (const element of elements) {
476
+ const child = new Render(element, raw);
477
+ const chunk = this.#advance(child);
478
+
479
+ if (chunk) child.queue = [chunk];
480
+ if (this.#children.push(child) > 1 && !child.done && !child.waiting)
481
+ this.#idle.push(child);
482
+ }
483
+ }
484
+
485
+ /** @returns The next step of the children, in their order */
486
+ step(): Step {
487
+ for (;;) {
488
+ if (this.#failed) throw this.#error;
489
+
490
+ const child = this.#children[this.#current];
491
+
492
+ if (!child) return;
493
+
494
+ const chunks = child.queue;
495
+
496
+ if (chunks) {
497
+ child.queue = undefined;
498
+
499
+ // the others go on as the current one is read, so whatever they
500
+ // wait for has started before they are next
501
+ this.#rest();
502
+
503
+ // chunks are queued, never changed, the same chunk may be rendered again
504
+ return chunks.length === 1 ? chunks[0] : new Group(chunks);
505
+ }
506
+
507
+ if (child.done) this.#current++;
508
+ else if (child.waiting) return this.#wait(child);
509
+ else {
510
+ const chunk = this.#advance(child);
511
+
512
+ if (chunk) {
513
+ this.#rest();
514
+ return chunk;
515
+ }
516
+ }
517
+ }
518
+ }
519
+
520
+ /** Ends the children in progress. */
521
+ close() {
522
+ this.#closed = true;
523
+ this.#wake();
524
+
525
+ return Promise.allSettled(this.#children.map((child) => child.close()));
526
+ }
527
+
528
+ /**
529
+ * Steps a child once.
530
+ *
531
+ * @param child Child that is not waiting
532
+ * @returns The chunk, if it rendered one
533
+ */
534
+ #advance(child: Render) {
535
+ let result: Step;
536
+
537
+ try {
538
+ result = child.step();
539
+ } catch (error) {
540
+ return this.#fail(error);
541
+ }
542
+
543
+ if (result instanceof Chunk) return result;
544
+
545
+ if (result) {
546
+ child.waiting = true;
547
+ result.then(
548
+ () => {
549
+ child.waiting = false;
550
+
551
+ // a step goes on to its chunk without being asked again, so
552
+ // whatever the child waits for next starts as soon as it can
553
+ if (!this.#failed && !this.#closed) {
554
+ const chunk = this.#advance(child);
555
+
556
+ if (chunk) (child.queue ??= []).push(chunk);
557
+ if (
558
+ !child.done &&
559
+ !child.waiting &&
560
+ child !== this.#children[this.#current]
561
+ )
562
+ this.#idle.push(child);
563
+ }
564
+
565
+ this.#wake();
566
+ },
567
+ (error: unknown) => this.#fail(error),
568
+ );
569
+ } else child.done = true;
570
+ }
571
+
572
+ /**
573
+ * Steps each child after the current one that can step. Their chunks are
574
+ * queued until they are the current one.
575
+ *
576
+ * @returns `true` if a child stepped
577
+ */
578
+ #rest() {
579
+ const idle = this.#idle;
580
+
581
+ if (!idle.length || this.#failed || this.#closed) return false;
582
+
583
+ const current = this.#children[this.#current];
584
+ let stepped = false;
585
+ let kept = 0;
586
+
587
+ for (let i = 0; i < idle.length; i++) {
588
+ const child = idle[i]!;
589
+
590
+ // the current child is stepped as it is read
591
+ if (child !== current) {
592
+ const chunk = this.#advance(child);
593
+
594
+ if (chunk) (child.queue ??= []).push(chunk);
595
+ // one that waits is added again once it can step
596
+ if (!child.done && !child.waiting) idle[kept++] = child;
597
+ stepped = true;
598
+ }
599
+ }
600
+
601
+ idle.length = kept;
602
+
603
+ return stepped;
604
+ }
605
+
606
+ /**
607
+ * Waits for the current child. The others go on meanwhile, a round of
608
+ * steps at a time, so the current one is next as soon as it can be.
609
+ *
610
+ * @param child Current child, which is waiting
611
+ */
612
+ async #wait(child: Render) {
613
+ while (child.waiting && !this.#failed && !this.#closed) {
614
+ if (this.#rest()) await undefined;
615
+ else await new Promise<void>((resolve) => (this.#notify = resolve));
616
+ }
617
+ }
618
+
619
+ /** Ends the wait, if there is one, to look at the children again. */
620
+ #wake() {
621
+ const notify = this.#notify;
622
+ this.#notify = undefined;
623
+ notify?.();
624
+ }
625
+
626
+ /** @param error What a child failed with, the first is thrown */
627
+ #fail(error: unknown) {
628
+ if (!this.#failed) {
629
+ this.#failed = true;
630
+ this.#error = error;
631
+ }
632
+
633
+ this.#wake();
634
+ }
635
+ }
636
+
637
+ /**
638
+ * A render piped into a `ReadableStream`, internal to ovr.
639
+ *
640
+ * @param render Render of markup, or of text such as Markdown
641
+ * @returns `ReadableStream` of what it renders
642
+ */
643
+ export const readable = (render: {
644
+ step(): Chunk | string | Promise<unknown> | undefined;
645
+ close(): Promise<unknown>;
646
+ }) => {
647
+ // `highWaterMark` defaults to 1
648
+ // https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/ReadableStream#highwatermark
649
+ // setting this ensures at least a small buffer is maintained if the
650
+ // underlying server does not have its own high water mark set
651
+ // https://blog.cloudflare.com/unpacking-cloudflare-workers-cpu-performance-benchmarks/#inefficient-streams-adapters
652
+ // in Node, the default is 16kb, so this stacks another 2kb in front
653
+ // https://nodejs.org/api/http.html#outgoingmessagewritablehighwatermark
654
+ const highWaterMark = 2 * Size.kb;
655
+
656
+ /** Wait a pull left for the next one, since it had text to send first */
657
+ let wait: Promise<unknown> | undefined;
658
+
659
+ /** Cancelled, so a pull that was waiting does not render more */
660
+ let cancelled = false;
661
+
662
+ return new ReadableStream<Uint8Array>(
663
+ {
664
+ // enables zero-copy transfer from underlying source when queue is empty
665
+ // https://developer.mozilla.org/en-US/docs/Web/API/Streams_API/Using_readable_byte_streams#overview
666
+ type: "bytes",
667
+ // `pull` ensures backpressure and cancelled requests stop the render
668
+ async pull(c) {
669
+ let text = "";
670
+ let result: ReturnType<typeof render.step>;
671
+
672
+ try {
673
+ if (wait) {
674
+ const last = wait;
675
+ wait = undefined;
676
+ await last;
677
+ }
678
+
679
+ // The stream pulls until its queue is full, and each chunk it is
680
+ // given costs far more than rendering one. So what is rendered
681
+ // without waiting is sent together, up to as much as the stream
682
+ // would have pulled.
683
+ while (!cancelled && (result = render.step())) {
684
+ if (!(result instanceof Promise)) {
685
+ text += result.toString();
686
+ if (text.length >= highWaterMark) break;
687
+ } else if (text) {
688
+ // send what is rendered before waiting for more
689
+ wait = result;
690
+ // handled when it is awaited, by the next pull or the close
691
+ result.catch(() => {});
692
+ break;
693
+ } else await result;
694
+ }
695
+ } catch (error) {
696
+ await render.close();
697
+ throw error;
698
+ }
699
+
700
+ if (cancelled) return;
701
+
702
+ if (text) {
703
+ c.enqueue(
704
+ // need to encode for Node (ex: during prerendering) or it will error
705
+ // doesn't seem to be needed for browsers
706
+ // faster than piping through a `TextEncoderStream`
707
+ Codec.encode(text),
708
+ );
709
+ }
710
+
711
+ if (!result) c.close();
712
+ },
713
+ async cancel() {
714
+ cancelled = true;
715
+ await render.close();
716
+ },
717
+ },
718
+ { highWaterMark },
719
+ );
720
+ };
721
+
722
+ /** The class `Markup.Chunk` is named for */
723
+ type ChunkClass = Chunk;
724
+
725
+ export namespace Markup {
726
+ /** Markup options */
727
+ export type Options = {
728
+ /** Set to `true` to disable escaping, for content that is not markup */
729
+ raw?: boolean;
730
+ };
731
+
732
+ /** Rendered `Chunk` instance, an interface so declaration files name it */
733
+ export interface Chunk extends ChunkClass {}
734
+ }
735
+
736
+ /**
737
+ * Renders an element to markup, such as HTML, SVG, or XML, as an
738
+ * `AsyncIterable` of strings, a stream, or a string. `Markdown` renders the
739
+ * same elements to Markdown.
740
+ */
741
+ export class Markup {
742
+ /** Regex to find escape character for attributes */
743
+ static readonly #attr = /[&"<]/g;
744
+
745
+ /** Regex to find escape character for content */
746
+ static readonly #content = /[&<]/g;
747
+
748
+ /** Escape character map */
749
+ static readonly #map = { "&": "&amp;", '"': "&quot;", "<": "&lt;" };
750
+
751
+ /** Element to render */
752
+ readonly #element: JSX.Element;
753
+
754
+ /** Markup options */
755
+ readonly #options: Markup.Options | undefined;
756
+
757
+ /**
758
+ * Creates an `AsyncIterable` that renders the `Element`.
759
+ *
760
+ * @param element Element to render
761
+ * @param options Markup options
762
+ */
763
+ constructor(element: JSX.Element, options?: Markup.Options) {
764
+ this.#element = element;
765
+ this.#options = options;
766
+ }
767
+
768
+ /** @returns The element, rendered in place where a `Markup` is a child */
769
+ get [source]() {
770
+ return this.#element;
771
+ }
772
+
773
+ /** @yields Markup as the `Element` resolves */
774
+ async *[Symbol.asyncIterator](): AsyncGenerator<string, void, unknown> {
775
+ const render = new Render(this.#element, this.#options?.raw);
776
+
777
+ try {
778
+ for (let result: Step; (result = render.step());) {
779
+ if (result instanceof Chunk) yield result.toString();
780
+ else await result;
781
+ }
782
+ } finally {
783
+ await render.close();
784
+ }
785
+ }
786
+
787
+ /**
788
+ * `render` piped into a `ReadableStream`.
789
+ * Use `render` when possible to avoid the overhead of the stream.
790
+ *
791
+ * @param element Element to render
792
+ * @param options Markup options
793
+ * @returns `ReadableStream` of markup
794
+ */
795
+ static stream(element: JSX.Element, options?: Markup.Options) {
796
+ return readable(new Render(element, options?.raw));
797
+ }
798
+
799
+ /**
800
+ * Converts a render into a fully concatenated string of markup.
801
+ *
802
+ * ### WARNING
803
+ *
804
+ * This negates streaming benefits and buffers the result into a string.
805
+ *
806
+ * @param element Element to render
807
+ * @param options Markup options
808
+ * @returns Concatenated markup
809
+ */
810
+ static async string(element: JSX.Element, options?: Markup.Options) {
811
+ const render = new Render(element, options?.raw);
812
+ const chunks: Chunk[] = [];
813
+
814
+ try {
815
+ for (let result: Step; (result = render.step());) {
816
+ if (result instanceof Chunk) chunks.push(result);
817
+ else await result;
818
+ }
819
+ } finally {
820
+ await render.close();
821
+ }
822
+
823
+ // written once every chunk is rendered, as a group of them is
824
+ return new Group(chunks).toString();
825
+ }
826
+
827
+ /**
828
+ * Render raw markup and dangerously bypass escaping. It is written as it is
829
+ * in Markdown too, which can contain HTML.
830
+ *
831
+ * @param html Safe markup to render
832
+ * @returns New _safe_ `Chunk`
833
+ */
834
+ static raw(html: unknown): Markup.Chunk {
835
+ return new Chunk(html, true);
836
+ }
837
+
838
+ /**
839
+ * Escapes text for markup.
840
+ *
841
+ * @param html String to escape
842
+ * @param attr Set to `true` if the value is an attribute, otherwise it is content
843
+ * @returns Escaped text
844
+ */
845
+ static escape(html: string, attr?: boolean) {
846
+ return html.replace(
847
+ attr ? Markup.#attr : Markup.#content,
848
+ (c) =>
849
+ // @ts-expect-error - private method type error
850
+ Markup.#map[c],
851
+ );
852
+ }
853
+ }