preact-render-to-string 6.5.2 → 6.5.3

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 (43) hide show
  1. package/dist/{jsx-entry.js → jsx/commonjs.js} +1 -1
  2. package/dist/{jsx.js → jsx/index.js} +1 -1
  3. package/dist/jsx/index.js.map +1 -0
  4. package/dist/{jsx.mjs → jsx/index.mjs} +1 -1
  5. package/dist/{jsx.module.js → jsx/index.module.js} +1 -1
  6. package/dist/jsx/index.module.js.map +1 -0
  7. package/dist/{jsx.umd.js → jsx/index.umd.js} +1 -1
  8. package/dist/jsx/index.umd.js.map +1 -0
  9. package/dist/{stream.js → stream/index.js} +1 -1
  10. package/dist/stream/index.js.map +1 -0
  11. package/dist/{stream.module.js → stream/index.mjs} +1 -1
  12. package/dist/stream/index.module.js +2 -0
  13. package/dist/stream/index.module.js.map +1 -0
  14. package/dist/{stream.umd.js → stream/index.umd.js} +1 -1
  15. package/dist/stream/index.umd.js.map +1 -0
  16. package/dist/{stream-node.js → stream/node/index.js} +8 -2
  17. package/dist/stream/node/index.js.map +1 -0
  18. package/dist/{stream-node.module.js → stream/node/index.mjs} +8 -2
  19. package/dist/stream/node/index.module.js +798 -0
  20. package/dist/stream/node/index.module.js.map +1 -0
  21. package/dist/{stream-node.umd.js → stream/node/index.umd.js} +8 -2
  22. package/dist/stream/node/index.umd.js.map +1 -0
  23. package/dist/stream-node.d.ts +19 -0
  24. package/dist/stream.d.ts +10 -0
  25. package/jsx.d.ts +7 -2
  26. package/package.json +25 -26
  27. package/src/stream-node.d.ts +19 -0
  28. package/src/stream-node.js +7 -1
  29. package/src/stream.d.ts +10 -0
  30. package/dist/commonjs.js.map +0 -1
  31. package/dist/jsx-entry.js.map +0 -1
  32. package/dist/jsx.js.map +0 -1
  33. package/dist/jsx.mjs.map +0 -1
  34. package/dist/jsx.module.js.map +0 -1
  35. package/dist/jsx.umd.js.map +0 -1
  36. package/dist/preact-render-to-string-tests.d.ts +0 -1
  37. package/dist/stream-node.js.map +0 -1
  38. package/dist/stream-node.module.js.map +0 -1
  39. package/dist/stream-node.umd.js.map +0 -1
  40. package/dist/stream.js.map +0 -1
  41. package/dist/stream.module.js.map +0 -1
  42. package/dist/stream.umd.js.map +0 -1
  43. package/src/preact-render-to-string-tests.d.ts +0 -1
@@ -0,0 +1,798 @@
1
+ import { PassThrough } from 'node:stream';
2
+ import { options, h, Fragment } from 'preact';
3
+
4
+ const UNSAFE_NAME = /[\s\n\\/='"\0<>]/;
5
+ const NAMESPACE_REPLACE_REGEX = /^(xlink|xmlns|xml)([A-Z])/;
6
+ const HTML_LOWER_CASE = /^accessK|^auto[A-Z]|^cell|^ch|^col|cont|cross|dateT|encT|form[A-Z]|frame|hrefL|inputM|maxL|minL|noV|playsI|popoverT|readO|rowS|spellC|src[A-Z]|tabI|useM|item[A-Z]/;
7
+ const SVG_CAMEL_CASE = /^ac|^ali|arabic|basel|cap|clipPath$|clipRule$|color|dominant|enable|fill|flood|font|glyph[^R]|horiz|image|letter|lighting|marker[^WUH]|overline|panose|pointe|paint|rendering|shape|stop|strikethrough|stroke|text[^L]|transform|underline|unicode|units|^v[^i]|^w|^xH/; // DOM properties that should NOT have "px" added when numeric
8
+
9
+ const ENCODED_ENTITIES = /["&<]/;
10
+ /** @param {string} str */
11
+
12
+ function encodeEntities(str) {
13
+ // Skip all work for strings with no entities needing encoding:
14
+ if (str.length === 0 || ENCODED_ENTITIES.test(str) === false) return str;
15
+ let last = 0,
16
+ i = 0,
17
+ out = '',
18
+ ch = ''; // Seek forward in str until the next entity char:
19
+
20
+ for (; i < str.length; i++) {
21
+ switch (str.charCodeAt(i)) {
22
+ case 34:
23
+ ch = '&quot;';
24
+ break;
25
+
26
+ case 38:
27
+ ch = '&amp;';
28
+ break;
29
+
30
+ case 60:
31
+ ch = '&lt;';
32
+ break;
33
+
34
+ default:
35
+ continue;
36
+ } // Append skipped/buffered characters and the encoded entity:
37
+
38
+
39
+ if (i !== last) out += str.slice(last, i);
40
+ out += ch; // Start the next seek/buffer after the entity's offset:
41
+
42
+ last = i + 1;
43
+ }
44
+
45
+ if (i !== last) out += str.slice(last, i);
46
+ return out;
47
+ }
48
+ const JS_TO_CSS = {};
49
+ const IS_NON_DIMENSIONAL = new Set(['animation-iteration-count', 'border-image-outset', 'border-image-slice', 'border-image-width', 'box-flex', 'box-flex-group', 'box-ordinal-group', 'column-count', 'fill-opacity', 'flex', 'flex-grow', 'flex-negative', 'flex-order', 'flex-positive', 'flex-shrink', 'flood-opacity', 'font-weight', 'grid-column', 'grid-row', 'line-clamp', 'line-height', 'opacity', 'order', 'orphans', 'stop-opacity', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'tab-size', 'widows', 'z-index', 'zoom']);
50
+ const CSS_REGEX = /[A-Z]/g; // Convert an Object style to a CSSText string
51
+
52
+ function styleObjToCss(s) {
53
+ let str = '';
54
+
55
+ for (let prop in s) {
56
+ let val = s[prop];
57
+
58
+ if (val != null && val !== '') {
59
+ const name = prop[0] == '-' ? prop : JS_TO_CSS[prop] || (JS_TO_CSS[prop] = prop.replace(CSS_REGEX, '-$&').toLowerCase());
60
+ let suffix = ';';
61
+
62
+ if (typeof val === 'number' && // Exclude custom-attributes
63
+ !name.startsWith('--') && !IS_NON_DIMENSIONAL.has(name)) {
64
+ suffix = 'px;';
65
+ }
66
+
67
+ str = str + name + ':' + val + suffix;
68
+ }
69
+ }
70
+
71
+ return str || undefined;
72
+ }
73
+ /**
74
+ * @template T
75
+ */
76
+
77
+ class Deferred {
78
+ constructor() {
79
+ // eslint-disable-next-line lines-around-comment
80
+
81
+ /** @type {Promise<T>} */
82
+ this.promise = new Promise((resolve, reject) => {
83
+ this.resolve = resolve;
84
+ this.reject = reject;
85
+ });
86
+ }
87
+
88
+ }
89
+
90
+ // Options hooks
91
+ const DIFF = '__b';
92
+ const RENDER = '__r';
93
+ const DIFFED = 'diffed';
94
+ const COMMIT = '__c';
95
+ const SKIP_EFFECTS = '__s';
96
+ const CATCH_ERROR = '__e'; // VNode properties
97
+
98
+ const COMPONENT = '__c';
99
+ const CHILDREN = '__k';
100
+ const PARENT = '__';
101
+
102
+ const VNODE = '__v';
103
+ const DIRTY = '__d';
104
+ const NEXT_STATE = '__s';
105
+ const CHILD_DID_SUSPEND = '__c';
106
+
107
+ const EMPTY_ARR = [];
108
+ const isArray = Array.isArray;
109
+ const assign = Object.assign; // Global state for the current render pass
110
+
111
+ let beforeDiff, afterDiff, renderHook, ummountHook;
112
+ /**
113
+ * Render Preact JSX + Components to an HTML string.
114
+ * @param {VNode} vnode JSX Element / VNode to render
115
+ * @param {Object} [context={}] Initial root context object
116
+ * @param {RendererState} [_rendererState] for internal use
117
+ * @returns {string} serialized HTML
118
+ */
119
+
120
+ function renderToString(vnode, context, _rendererState) {
121
+ // Performance optimization: `renderToString` is synchronous and we
122
+ // therefore don't execute any effects. To do that we pass an empty
123
+ // array to `options._commit` (`__c`). But we can go one step further
124
+ // and avoid a lot of dirty checks and allocations by setting
125
+ // `options._skipEffects` (`__s`) too.
126
+ const previousSkipEffects = options[SKIP_EFFECTS];
127
+ options[SKIP_EFFECTS] = true; // store options hooks once before each synchronous render call
128
+
129
+ beforeDiff = options[DIFF];
130
+ afterDiff = options[DIFFED];
131
+ renderHook = options[RENDER];
132
+ ummountHook = options.unmount;
133
+ const parent = h(Fragment, null);
134
+ parent[CHILDREN] = [vnode];
135
+
136
+ try {
137
+ const rendered = _renderToString(vnode, context || EMPTY_OBJ, false, undefined, parent, false, _rendererState);
138
+
139
+ if (Array.isArray(rendered)) {
140
+ return rendered.join('');
141
+ }
142
+
143
+ return rendered;
144
+ } catch (e) {
145
+ if (e.then) {
146
+ throw new Error('Use "renderToStringAsync" for suspenseful rendering.');
147
+ }
148
+
149
+ throw e;
150
+ } finally {
151
+ // options._commit, we don't schedule any effects in this library right now,
152
+ // so we can pass an empty queue to this hook.
153
+ if (options[COMMIT]) options[COMMIT](vnode, EMPTY_ARR);
154
+ options[SKIP_EFFECTS] = previousSkipEffects;
155
+ EMPTY_ARR.length = 0;
156
+ }
157
+ }
158
+
159
+ function markAsDirty() {
160
+ this.__d = true;
161
+ }
162
+
163
+ const EMPTY_OBJ = {};
164
+ /**
165
+ * @param {VNode} vnode
166
+ * @param {Record<string, unknown>} context
167
+ */
168
+
169
+ function renderClassComponent(vnode, context) {
170
+ let type =
171
+ /** @type {import("preact").ComponentClass<typeof vnode.props>} */
172
+ vnode.type;
173
+ let isMounting = true;
174
+ let c;
175
+
176
+ if (vnode[COMPONENT]) {
177
+ isMounting = false;
178
+ c = vnode[COMPONENT];
179
+ c.state = c[NEXT_STATE];
180
+ } else {
181
+ c = new type(vnode.props, context);
182
+ }
183
+
184
+ vnode[COMPONENT] = c;
185
+ c[VNODE] = vnode;
186
+ c.props = vnode.props;
187
+ c.context = context; // turn off stateful re-rendering:
188
+
189
+ c[DIRTY] = true;
190
+ if (c.state == null) c.state = EMPTY_OBJ;
191
+
192
+ if (c[NEXT_STATE] == null) {
193
+ c[NEXT_STATE] = c.state;
194
+ }
195
+
196
+ if (type.getDerivedStateFromProps) {
197
+ c.state = assign({}, c.state, type.getDerivedStateFromProps(c.props, c.state));
198
+ } else if (isMounting && c.componentWillMount) {
199
+ c.componentWillMount(); // If the user called setState in cWM we need to flush pending,
200
+ // state updates. This is the same behaviour in React.
201
+
202
+ c.state = c[NEXT_STATE] !== c.state ? c[NEXT_STATE] : c.state;
203
+ } else if (!isMounting && c.componentWillUpdate) {
204
+ c.componentWillUpdate();
205
+ }
206
+
207
+ if (renderHook) renderHook(vnode);
208
+ return c.render(c.props, c.state, context);
209
+ }
210
+ /**
211
+ * Recursively render VNodes to HTML.
212
+ * @param {VNode|any} vnode
213
+ * @param {any} context
214
+ * @param {boolean} isSvgMode
215
+ * @param {any} selectValue
216
+ * @param {VNode} parent
217
+ * @param {boolean} asyncMode
218
+ * @param {RendererState | undefined} [renderer]
219
+ * @returns {string | Promise<string> | (string | Promise<string>)[]}
220
+ */
221
+
222
+
223
+ function _renderToString(vnode, context, isSvgMode, selectValue, parent, asyncMode, renderer) {
224
+ // Ignore non-rendered VNodes/values
225
+ if (vnode == null || vnode === true || vnode === false || vnode === '') {
226
+ return '';
227
+ } // Text VNodes: escape as HTML
228
+
229
+
230
+ if (typeof vnode !== 'object') {
231
+ if (typeof vnode === 'function') return '';
232
+ return encodeEntities(vnode + '');
233
+ } // Recurse into children / Arrays
234
+
235
+
236
+ if (isArray(vnode)) {
237
+ let rendered = '',
238
+ renderArray;
239
+ parent[CHILDREN] = vnode;
240
+
241
+ for (let i = 0; i < vnode.length; i++) {
242
+ let child = vnode[i];
243
+ if (child == null || typeof child === 'boolean') continue;
244
+
245
+ const childRender = _renderToString(child, context, isSvgMode, selectValue, parent, asyncMode, renderer);
246
+
247
+ if (typeof childRender === 'string') {
248
+ rendered += childRender;
249
+ } else {
250
+ renderArray = renderArray || [];
251
+ if (rendered) renderArray.push(rendered);
252
+ rendered = '';
253
+
254
+ if (Array.isArray(childRender)) {
255
+ renderArray.push(...childRender);
256
+ } else {
257
+ renderArray.push(childRender);
258
+ }
259
+ }
260
+ }
261
+
262
+ if (renderArray) {
263
+ if (rendered) renderArray.push(rendered);
264
+ return renderArray;
265
+ }
266
+
267
+ return rendered;
268
+ } // VNodes have {constructor:undefined} to prevent JSON injection:
269
+
270
+
271
+ if (vnode.constructor !== undefined) return '';
272
+ vnode[PARENT] = parent;
273
+ if (beforeDiff) beforeDiff(vnode);
274
+ let type = vnode.type,
275
+ props = vnode.props,
276
+ cctx = context,
277
+ contextType,
278
+ rendered,
279
+ component; // Invoke rendering on Components
280
+
281
+ if (typeof type === 'function') {
282
+ if (type === Fragment) {
283
+ // Serialized precompiled JSX.
284
+ if (props.tpl) {
285
+ let out = '';
286
+
287
+ for (let i = 0; i < props.tpl.length; i++) {
288
+ out += props.tpl[i];
289
+
290
+ if (props.exprs && i < props.exprs.length) {
291
+ const value = props.exprs[i];
292
+ if (value == null) continue; // Check if we're dealing with a vnode or an array of nodes
293
+
294
+ if (typeof value === 'object' && (value.constructor === undefined || isArray(value))) {
295
+ out += _renderToString(value, context, isSvgMode, selectValue, vnode, asyncMode, renderer);
296
+ } else {
297
+ // Values are pre-escaped by the JSX transform
298
+ out += value;
299
+ }
300
+ }
301
+ }
302
+
303
+ return out;
304
+ } else if (props.UNSTABLE_comment) {
305
+ // Fragments are the least used components of core that's why
306
+ // branching here for comments has the least effect on perf.
307
+ return '<!--' + encodeEntities(props.UNSTABLE_comment || '') + '-->';
308
+ }
309
+
310
+ rendered = props.children;
311
+ } else {
312
+ contextType = type.contextType;
313
+
314
+ if (contextType != null) {
315
+ let provider = context[contextType.__c];
316
+ cctx = provider ? provider.props.value : contextType.__;
317
+ }
318
+
319
+ if (type.prototype && typeof type.prototype.render === 'function') {
320
+ rendered =
321
+ /**#__NOINLINE__**/
322
+ renderClassComponent(vnode, cctx);
323
+ component = vnode[COMPONENT];
324
+ } else {
325
+ component = {
326
+ __v: vnode,
327
+ props,
328
+ context: cctx,
329
+ // silently drop state updates
330
+ setState: markAsDirty,
331
+ forceUpdate: markAsDirty,
332
+ __d: true,
333
+ // hooks
334
+ __h: []
335
+ };
336
+ vnode[COMPONENT] = component; // If a hook invokes setState() to invalidate the component during rendering,
337
+ // re-render it up to 25 times to allow "settling" of memoized states.
338
+ // Note:
339
+ // This will need to be updated for Preact 11 to use internal.flags rather than component._dirty:
340
+ // https://github.com/preactjs/preact/blob/d4ca6fdb19bc715e49fd144e69f7296b2f4daa40/src/diff/component.js#L35-L44
341
+
342
+ let count = 0;
343
+
344
+ while (component[DIRTY] && count++ < 25) {
345
+ component[DIRTY] = false;
346
+ if (renderHook) renderHook(vnode);
347
+ rendered = type.call(component, props, cctx);
348
+ }
349
+
350
+ component[DIRTY] = true;
351
+ }
352
+
353
+ if (component.getChildContext != null) {
354
+ context = assign({}, context, component.getChildContext());
355
+ }
356
+
357
+ if ((type.getDerivedStateFromError || component.componentDidCatch) && options.errorBoundaries) {
358
+ let str = ''; // When a component returns a Fragment node we flatten it in core, so we
359
+ // need to mirror that logic here too
360
+
361
+ let isTopLevelFragment = rendered != null && rendered.type === Fragment && rendered.key == null;
362
+ rendered = isTopLevelFragment ? rendered.props.children : rendered;
363
+
364
+ try {
365
+ str = _renderToString(rendered, context, isSvgMode, selectValue, vnode, asyncMode, renderer);
366
+ return str;
367
+ } catch (err) {
368
+ if (type.getDerivedStateFromError) {
369
+ component[NEXT_STATE] = type.getDerivedStateFromError(err);
370
+ }
371
+
372
+ if (component.componentDidCatch) {
373
+ component.componentDidCatch(err, {});
374
+ }
375
+
376
+ if (component[DIRTY]) {
377
+ rendered = renderClassComponent(vnode, context);
378
+ component = vnode[COMPONENT];
379
+
380
+ if (component.getChildContext != null) {
381
+ context = assign({}, context, component.getChildContext());
382
+ }
383
+
384
+ let isTopLevelFragment = rendered != null && rendered.type === Fragment && rendered.key == null;
385
+ rendered = isTopLevelFragment ? rendered.props.children : rendered;
386
+ str = _renderToString(rendered, context, isSvgMode, selectValue, vnode, asyncMode, renderer);
387
+ }
388
+
389
+ return str;
390
+ } finally {
391
+ if (afterDiff) afterDiff(vnode);
392
+ vnode[PARENT] = null;
393
+ if (ummountHook) ummountHook(vnode);
394
+ }
395
+ }
396
+ } // When a component returns a Fragment node we flatten it in core, so we
397
+ // need to mirror that logic here too
398
+
399
+
400
+ let isTopLevelFragment = rendered != null && rendered.type === Fragment && rendered.key == null && rendered.props.tpl == null;
401
+ rendered = isTopLevelFragment ? rendered.props.children : rendered;
402
+
403
+ try {
404
+ // Recurse into children before invoking the after-diff hook
405
+ const str = _renderToString(rendered, context, isSvgMode, selectValue, vnode, asyncMode, renderer);
406
+
407
+ if (afterDiff) afterDiff(vnode); // when we are dealing with suspense we can't do this...
408
+
409
+ vnode[PARENT] = null;
410
+ if (options.unmount) options.unmount(vnode);
411
+ return str;
412
+ } catch (error) {
413
+ if (!asyncMode && renderer && renderer.onError) {
414
+ let res = renderer.onError(error, vnode, child => _renderToString(child, context, isSvgMode, selectValue, vnode, asyncMode, renderer));
415
+ if (res !== undefined) return res;
416
+ let errorHook = options[CATCH_ERROR];
417
+ if (errorHook) errorHook(error, vnode);
418
+ return '';
419
+ }
420
+
421
+ if (!asyncMode) throw error;
422
+ if (!error || typeof error.then !== 'function') throw error;
423
+
424
+ const renderNestedChildren = () => {
425
+ try {
426
+ return _renderToString(rendered, context, isSvgMode, selectValue, vnode, asyncMode, renderer);
427
+ } catch (e) {
428
+ if (!e || typeof e.then !== 'function') throw e;
429
+ return e.then(() => _renderToString(rendered, context, isSvgMode, selectValue, vnode, asyncMode, renderer), () => renderNestedChildren());
430
+ }
431
+ };
432
+
433
+ return error.then(() => renderNestedChildren());
434
+ }
435
+ } // Serialize Element VNodes to HTML
436
+
437
+
438
+ let s = '<' + type,
439
+ html = '',
440
+ children;
441
+
442
+ for (let name in props) {
443
+ let v = props[name];
444
+
445
+ switch (name) {
446
+ case 'children':
447
+ children = v;
448
+ continue;
449
+ // VDOM-specific props
450
+
451
+ case 'key':
452
+ case 'ref':
453
+ case '__self':
454
+ case '__source':
455
+ continue;
456
+ // prefer for/class over htmlFor/className
457
+
458
+ case 'htmlFor':
459
+ if ('for' in props) continue;
460
+ name = 'for';
461
+ break;
462
+
463
+ case 'className':
464
+ if ('class' in props) continue;
465
+ name = 'class';
466
+ break;
467
+ // Form element reflected properties
468
+
469
+ case 'defaultChecked':
470
+ name = 'checked';
471
+ break;
472
+
473
+ case 'defaultSelected':
474
+ name = 'selected';
475
+ break;
476
+ // Special value attribute handling
477
+
478
+ case 'defaultValue':
479
+ case 'value':
480
+ name = 'value';
481
+
482
+ switch (type) {
483
+ // <textarea value="a&b"> --> <textarea>a&amp;b</textarea>
484
+ case 'textarea':
485
+ children = v;
486
+ continue;
487
+ // <select value> is serialized as a selected attribute on the matching option child
488
+
489
+ case 'select':
490
+ selectValue = v;
491
+ continue;
492
+ // Add a selected attribute to <option> if its value matches the parent <select> value
493
+
494
+ case 'option':
495
+ if (selectValue == v && !('selected' in props)) {
496
+ s = s + ' selected';
497
+ }
498
+
499
+ break;
500
+ }
501
+
502
+ break;
503
+
504
+ case 'dangerouslySetInnerHTML':
505
+ html = v && v.__html;
506
+ continue;
507
+ // serialize object styles to a CSS string
508
+
509
+ case 'style':
510
+ if (typeof v === 'object') {
511
+ v = styleObjToCss(v);
512
+ }
513
+
514
+ break;
515
+
516
+ case 'acceptCharset':
517
+ name = 'accept-charset';
518
+ break;
519
+
520
+ case 'httpEquiv':
521
+ name = 'http-equiv';
522
+ break;
523
+
524
+ default:
525
+ {
526
+ if (NAMESPACE_REPLACE_REGEX.test(name)) {
527
+ name = name.replace(NAMESPACE_REPLACE_REGEX, '$1:$2').toLowerCase();
528
+ } else if (UNSAFE_NAME.test(name)) {
529
+ continue;
530
+ } else if ((name[4] === '-' || name === 'draggable') && v != null) {
531
+ // serialize boolean aria-xyz or draggable attribute values as strings
532
+ // `draggable` is an enumerated attribute and not Boolean. A value of `true` or `false` is mandatory
533
+ // https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/draggable
534
+ v += '';
535
+ } else if (isSvgMode) {
536
+ if (SVG_CAMEL_CASE.test(name)) {
537
+ name = name === 'panose1' ? 'panose-1' : name.replace(/([A-Z])/g, '-$1').toLowerCase();
538
+ }
539
+ } else if (HTML_LOWER_CASE.test(name)) {
540
+ name = name.toLowerCase();
541
+ }
542
+ }
543
+ } // write this attribute to the buffer
544
+
545
+
546
+ if (v != null && v !== false && typeof v !== 'function') {
547
+ if (v === true || v === '') {
548
+ s = s + ' ' + name;
549
+ } else {
550
+ s = s + ' ' + name + '="' + encodeEntities(v + '') + '"';
551
+ }
552
+ }
553
+ }
554
+
555
+ if (UNSAFE_NAME.test(type)) {
556
+ // this seems to performs a lot better than throwing
557
+ // return '<!-- -->';
558
+ throw new Error(`${type} is not a valid HTML tag name in ${s}>`);
559
+ }
560
+
561
+ if (html) ; else if (typeof children === 'string') {
562
+ // single text child
563
+ html = encodeEntities(children);
564
+ } else if (children != null && children !== false && children !== true) {
565
+ // recurse into this element VNode's children
566
+ let childSvgMode = type === 'svg' || type !== 'foreignObject' && isSvgMode;
567
+ html = _renderToString(children, context, childSvgMode, selectValue, vnode, asyncMode, renderer);
568
+ }
569
+
570
+ if (afterDiff) afterDiff(vnode); // TODO: this was commented before
571
+
572
+ vnode[PARENT] = null;
573
+ if (ummountHook) ummountHook(vnode); // Emit self-closing tag for empty void elements:
574
+
575
+ if (!html && SELF_CLOSING.has(type)) {
576
+ return s + '/>';
577
+ }
578
+
579
+ const endTag = '</' + type + '>';
580
+ const startTag = s + '>';
581
+ if (Array.isArray(html)) return [startTag, ...html, endTag];else if (typeof html !== 'string') return [startTag, html, endTag];
582
+ return startTag + html + endTag;
583
+ }
584
+
585
+ const SELF_CLOSING = new Set(['area', 'base', 'br', 'col', 'command', 'embed', 'hr', 'img', 'input', 'keygen', 'link', 'meta', 'param', 'source', 'track', 'wbr']);
586
+
587
+ /* eslint-disable no-var, key-spacing, object-curly-spacing, prefer-arrow-callback, semi, keyword-spacing */
588
+ function initPreactIslandElement() {
589
+ class PreactIslandElement extends HTMLElement {
590
+ connectedCallback() {
591
+ var d = this;
592
+ if (!d.isConnected) return;
593
+ let i = this.getAttribute('data-target');
594
+ if (!i) return;
595
+ var s,
596
+ e,
597
+ c = document.createNodeIterator(document, 128);
598
+
599
+ while (c.nextNode()) {
600
+ let n = c.referenceNode;
601
+ if (n.data == 'preact-island:' + i) s = n;else if (n.data == '/preact-island:' + i) e = n;
602
+ if (s && e) break;
603
+ }
604
+
605
+ if (s && e) {
606
+ var p = e.previousSibling;
607
+
608
+ while (p != s) {
609
+ if (!p || p == s) break;
610
+ e.parentNode.removeChild(p);
611
+ p = e.previousSibling;
612
+ }
613
+
614
+ requestAnimationFrame(() => {
615
+ for (let i = 0; i <= d.children.length; i++) {
616
+ const child = d.children[i];
617
+ e.parentNode.insertBefore(child, e);
618
+ }
619
+
620
+ d.parentNode.removeChild(d);
621
+ });
622
+ }
623
+ }
624
+
625
+ }
626
+
627
+ customElements.define('preact-island', PreactIslandElement);
628
+ }
629
+
630
+ const fn = initPreactIslandElement.toString();
631
+ const INIT_SCRIPT = fn.slice(fn.indexOf('{') + 1, fn.lastIndexOf('}')).replace(/\n\s+/gm, '');
632
+ function createInitScript() {
633
+ return `<script>(function(){${INIT_SCRIPT}}())</script>`;
634
+ }
635
+ /**
636
+ * @param {string} id
637
+ * @param {string} content
638
+ * @returns {string}
639
+ */
640
+
641
+ function createSubtree(id, content) {
642
+ return `<preact-island hidden data-target="${id}">${content}</preact-island>`;
643
+ }
644
+
645
+ /**
646
+ * @param {VNode} vnode
647
+ * @param {RenderToChunksOptions} options
648
+ * @returns {Promise<void>}
649
+ */
650
+
651
+ async function renderToChunks(vnode, {
652
+ context,
653
+ onWrite,
654
+ abortSignal
655
+ }) {
656
+ context = context || {};
657
+ /** @type {RendererState} */
658
+
659
+ const renderer = {
660
+ start: Date.now(),
661
+ abortSignal,
662
+ onWrite,
663
+ onError: handleError,
664
+ suspended: []
665
+ }; // Synchronously render the shell
666
+ // @ts-ignore - using third internal RendererState argument
667
+
668
+ const shell = renderToString(vnode, context, renderer);
669
+ onWrite(shell); // Wait for any suspended sub-trees if there are any
670
+
671
+ const len = renderer.suspended.length;
672
+
673
+ if (len > 0) {
674
+ onWrite('<div hidden>');
675
+ onWrite(createInitScript()); // We should keep checking all promises
676
+
677
+ await forkPromises(renderer);
678
+ onWrite('</div>');
679
+ }
680
+ }
681
+
682
+ async function forkPromises(renderer) {
683
+ if (renderer.suspended.length > 0) {
684
+ const suspensions = [...renderer.suspended];
685
+ await Promise.all(renderer.suspended.map(s => s.promise));
686
+ renderer.suspended = renderer.suspended.filter(s => !suspensions.includes(s));
687
+ await forkPromises(renderer);
688
+ }
689
+ }
690
+ /** @type {RendererErrorHandler} */
691
+
692
+
693
+ function handleError(error, vnode, renderChild) {
694
+ if (!error || !error.then) return; // walk up to the Suspense boundary
695
+
696
+ while (vnode = vnode[PARENT]) {
697
+ let component = vnode[COMPONENT];
698
+
699
+ if (component && component[CHILD_DID_SUSPEND]) {
700
+ break;
701
+ }
702
+ }
703
+
704
+ if (!vnode) return;
705
+ const id = vnode.__v;
706
+ const found = this.suspended.find(x => x.id === id);
707
+ const race = new Deferred();
708
+ const abortSignal = this.abortSignal;
709
+
710
+ if (abortSignal) {
711
+ // @ts-ignore 2554 - implicit undefined arg
712
+ if (abortSignal.aborted) race.resolve();else abortSignal.addEventListener('abort', race.resolve);
713
+ }
714
+
715
+ const promise = error.then(() => {
716
+ if (abortSignal && abortSignal.aborted) return;
717
+ const child = renderChild(vnode.props.children);
718
+ if (child) this.onWrite(createSubtree(id, child));
719
+ }, // TODO: Abort and send hydration code snippet to client
720
+ // to attempt to recover during hydration
721
+ this.onError);
722
+ this.suspended.push({
723
+ id,
724
+ vnode,
725
+ promise: Promise.race([promise, race.promise])
726
+ });
727
+ const fallback = renderChild(vnode.props.fallback);
728
+ return found ? '' : `<!--preact-island:${id}-->${fallback}<!--/preact-island:${id}-->`;
729
+ }
730
+
731
+ /**
732
+ * @typedef {object} RenderToPipeableStreamOptions
733
+ * @property {() => void} [onShellReady]
734
+ * @property {() => void} [onAllReady]
735
+ * @property {(error) => void} [onError]
736
+ */
737
+
738
+ /**
739
+ * @typedef {object} PipeableStream
740
+ * @property {() => void} abort
741
+ * @property {(writable: import('stream').Writable) => void} pipe
742
+ */
743
+
744
+ /**
745
+ * @param {import('preact').VNode} vnode
746
+ * @param {RenderToPipeableStreamOptions} options
747
+ * @param {any} [context]
748
+ * @returns {PipeableStream}
749
+ */
750
+
751
+ function renderToPipeableStream(vnode, options, context) {
752
+ const encoder = new TextEncoder('utf-8');
753
+ const controller = new AbortController();
754
+ const stream = new PassThrough();
755
+ renderToChunks(vnode, {
756
+ context,
757
+ abortSignal: controller.signal,
758
+ onError: error => {
759
+ if (options.onError) {
760
+ options.onError(error);
761
+ }
762
+
763
+ controller.abort(error);
764
+ },
765
+
766
+ onWrite(s) {
767
+ stream.write(encoder.encode(s));
768
+ }
769
+
770
+ }).then(() => {
771
+ options.onAllReady && options.onAllReady();
772
+ stream.end();
773
+ }).catch(error => {
774
+ stream.destroy(error);
775
+ });
776
+ Promise.resolve().then(() => {
777
+ options.onShellReady && options.onShellReady();
778
+ });
779
+ return {
780
+ abort() {
781
+ controller.abort();
782
+ stream.destroy(new Error('aborted'));
783
+ },
784
+
785
+ /**
786
+ * @param {import("stream").Writable} writable
787
+ */
788
+ pipe(writable) {
789
+ stream.pipe(writable, {
790
+ end: true
791
+ });
792
+ }
793
+
794
+ };
795
+ }
796
+
797
+ export { renderToPipeableStream };
798
+ //# sourceMappingURL=index.module.js.map