@tschk/moonshine-dom 0.4.4 → 0.4.49

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.
package/src/ssr.ts CHANGED
@@ -13,35 +13,61 @@ import {
13
13
  type Owner,
14
14
  } from "./reactive";
15
15
  import { styleEntries } from "./style";
16
- import { attributeValue } from "./attributes";
16
+ import { attributeValue, sourceAttributeValue } from "./attributes";
17
17
  import { createComponent } from "./component";
18
- import { createSSRRenderAttempt, type SSRRenderAttempt } from "./ssr-attempt";
19
- import { ssrOwner, withSSRRendering, type OwnedSSRChild } from "./ssr-owner";
18
+ import {
19
+ createSSRRenderAttempt,
20
+ resetSSRRenderAttempt,
21
+ withSSRRenderAttempt,
22
+ type SSRRenderAttempt,
23
+ } from "./ssr-attempt";
24
+ import {
25
+ ssrOwner,
26
+ withSSRRendering,
27
+ isSSRRendering,
28
+ type OwnedSSRChild,
29
+ } from "./ssr-owner";
20
30
  export { scopeSSRChild } from "./ssr-owner";
21
31
 
22
32
  /** Compiler-only typed selection; payloads preserve literal function/object identity. */
23
33
  export const selectBinding = Symbol("moonshine server select binding");
24
34
  export const optionBinding = Symbol("moonshine server option binding");
25
- type BindingValue = { value: unknown };
26
- function bindingValue(
27
- props: Record<string, unknown> | null,
28
- key: symbol,
29
- ): BindingValue | undefined {
30
- if (!props || !Object.hasOwn(props, key)) return undefined;
31
- const box = Reflect.get(props, key);
32
- if (
33
- box === null ||
34
- typeof box !== "object" ||
35
- (Object.getPrototypeOf(box) !== Object.prototype &&
36
- Object.getPrototypeOf(box) !== null)
37
- )
35
+ type BindingValue = { value: unknown; preserveSelected?: boolean };
36
+ const ELEMENT_NAME = /^[a-zA-Z][a-zA-Z0-9:_-]*$/;
37
+ const ATTRIBUTE_NAME = /^[a-zA-Z_:][a-zA-Z0-9:_.-]*$/;
38
+ const EVENT_NAME = /^on/i;
39
+
40
+ function validateBindingBox(box: unknown): BindingValue {
41
+ if (box === null || typeof box !== "object")
42
+ throw new TypeError(
43
+ "Server binding metadata requires a plain { value } box",
44
+ );
45
+ const proto = Object.getPrototypeOf(box);
46
+ if (proto !== Object.prototype && proto !== null)
38
47
  throw new TypeError(
39
48
  "Server binding metadata requires a plain { value } box",
40
49
  );
41
50
  const descriptor = Object.getOwnPropertyDescriptor(box, "value");
42
51
  if (!descriptor || !("value" in descriptor))
43
52
  throw new TypeError("Server binding metadata requires an own data value");
44
- return { value: descriptor.value };
53
+ let preserveSelected: boolean | undefined;
54
+ if (Object.hasOwn(box, "preserveSelected")) {
55
+ const policy = Object.getOwnPropertyDescriptor(box, "preserveSelected");
56
+ if (policy && (!("value" in policy) || typeof policy.value !== "boolean"))
57
+ throw new TypeError(
58
+ "Server selected policy requires an own boolean data value",
59
+ );
60
+ preserveSelected = policy?.value;
61
+ }
62
+ return { value: descriptor.value, preserveSelected };
63
+ }
64
+
65
+ function bindingValue(
66
+ props: Record<string, unknown> | null,
67
+ key: symbol,
68
+ ): BindingValue | undefined {
69
+ if (!props || !Object.hasOwn(props, key)) return undefined;
70
+ return validateBindingBox(Reflect.get(props, key));
45
71
  }
46
72
  const html = Symbol("moonshine server HTML");
47
73
  type Selection = {
@@ -90,7 +116,8 @@ export function rawHTML(value: unknown): HTML {
90
116
  }
91
117
 
92
118
  export function escapeHtml(value: unknown): string {
93
- const text = String(value);
119
+ const text = typeof value === "string" ? value : String(value);
120
+ if (text.length === 0) return "";
94
121
  // Bun emits &#x27; for apostrophes; retain this API's exact &#39; output.
95
122
  if (typeof Bun !== "undefined" && !text.includes("'"))
96
123
  return Bun.escapeHTML(text);
@@ -111,45 +138,66 @@ export function escapeHtml(value: unknown): string {
111
138
  }
112
139
 
113
140
  function resolve(child: SSRChild): SSRChild {
114
- if (typeof child === "function") return resolve(child());
115
- if (Array.isArray(child)) return child.map(resolve);
116
- if (
117
- child != null &&
118
- typeof child === "object" &&
119
- !(html in child) &&
120
- !(ssrOwner in child)
121
- ) {
141
+ while (typeof child === "function") child = child();
142
+ if (child == null || typeof child !== "object") return child;
143
+ if (Array.isArray(child)) {
144
+ const length = child.length;
145
+ if (length === 0) return "";
146
+ if (length === 1) return resolve(child[0]);
147
+ const resolved: SSRChild[] = [];
148
+ for (let index = 0; index < length; index++)
149
+ resolved.push(resolve(child[index]));
150
+ return resolved;
151
+ }
152
+ if (!(html in child) && !(ssrOwner in child)) {
122
153
  throw new TypeError("Server children must be text or factory HTML");
123
154
  }
124
155
  return child;
125
156
  }
126
157
 
127
158
  function text(child: SSRChild): string {
128
- if (child && typeof child === "object" && ssrOwner in child)
129
- return inSSRScope(child, () => text(child.child));
130
- if (typeof child === "function") return text(child());
131
- if (Array.isArray(child)) return child.map(text).join("");
159
+ while (typeof child === "function") child = child();
132
160
  if (child == null || typeof child === "boolean") return "";
133
- if (typeof child === "object") {
134
- throw new TypeError("Server textarea/title/option children must be text");
161
+ if (typeof child === "string") return child;
162
+ if (typeof child !== "object") return String(child);
163
+ if (ssrOwner in child) return inSSRScope(child, () => text(child.child));
164
+ if (Array.isArray(child)) {
165
+ let out = "";
166
+ for (let index = 0; index < child.length; index++)
167
+ out += text(child[index]);
168
+ return out;
135
169
  }
136
- return String(child);
170
+ throw new TypeError("Server textarea/title/option children must be text");
137
171
  }
138
172
 
139
173
  function content(child: SSRChild, selection?: Selection, svg = false): string {
140
- if (child && typeof child === "object" && ssrOwner in child)
141
- return inSSRScope(child, () => content(child.child, selection, svg));
142
- if (typeof child === "function") return content(child(), selection, svg);
143
- if (Array.isArray(child))
144
- return child.map((value) => content(value, selection, svg)).join("");
174
+ while (typeof child === "function") child = child();
145
175
  if (child == null || typeof child === "boolean") return "";
146
176
  if (typeof child === "object") {
147
177
  if (html in child) return (child as HTML)[html](selection, svg);
178
+ if (ssrOwner in child)
179
+ return inSSRScope(child, () => content(child.child, selection, svg));
180
+ if (Array.isArray(child)) {
181
+ let out = "";
182
+ for (let index = 0; index < child.length; index++)
183
+ out += content(child[index], selection, svg);
184
+ return out;
185
+ }
148
186
  throw new TypeError("Server children must be text or factory HTML");
149
187
  }
150
188
  return escapeHtml(child);
151
189
  }
152
190
 
191
+ /** Serialize within the active request and owner without starting or disposing a root. */
192
+ export function serializeSSRChild(child: SSRChild): string {
193
+ const owner = getOwner();
194
+ if (!isSSRRendering() || !owner || owner.disposed)
195
+ throw new Error(
196
+ "SSR child serialization requires a live server render owner",
197
+ );
198
+ return content(child);
199
+ }
200
+
153
201
  function inSSRScope<T>(child: OwnedSSRChild, render: () => T): T {
154
202
  const owner = child[ssrOwner];
155
203
  if (owner.disposed)
@@ -200,7 +248,9 @@ export function boundary(
200
248
  // The attempt owns a fresh context map; setup errors belong to this buffer.
201
249
  scope.context!.delete(errorHandlerKey);
202
250
  try {
203
- return content(renderBranch(), localSelection, svg);
251
+ return withSSRRenderAttempt(attempt, () =>
252
+ content(renderBranch(), localSelection, svg),
253
+ );
204
254
  } catch (error) {
205
255
  // createRoot cleans failed setup before returning to the outer catch.
206
256
  attempt.status = "discarded";
@@ -269,12 +319,14 @@ export function settle(
269
319
  stop = dispose;
270
320
  scope = getOwner()!;
271
321
  attempt = createSSRRenderAttempt();
272
- return content(
273
- renderTemplate(() => {
274
- dirty = true;
275
- }),
276
- localSelection,
277
- svg,
322
+ return withSSRRenderAttempt(attempt, () =>
323
+ content(
324
+ renderTemplate(() => {
325
+ dirty = true;
326
+ }),
327
+ localSelection,
328
+ svg,
329
+ ),
278
330
  );
279
331
  }),
280
332
  );
@@ -346,61 +398,186 @@ export function h<P extends Record<string, unknown>>(
346
398
  "ssr",
347
399
  );
348
400
  }
349
- if (!/^[a-zA-Z][a-zA-Z0-9:_-]*$/.test(tag)) {
401
+ return intrinsic(tag, props, children);
402
+ }
403
+
404
+ /** Compiler-only source attribute codec; children use the existing lazy contract. */
405
+ export function hSource(
406
+ tag: string,
407
+ props: Record<string, unknown> | null = null,
408
+ ...children: SSRChild[]
409
+ ): HTML {
410
+ return intrinsic(tag, props, children, sourceAttributeValue);
411
+ }
412
+
413
+ /** Compiler-only ordered source attributes, including repeated authored names. */
414
+ export function hSourceEntries(
415
+ tag: string,
416
+ entries: ReadonlyArray<readonly [string, unknown]>,
417
+ ...children: SSRChild[]
418
+ ): HTML {
419
+ return intrinsic(tag, null, children, sourceAttributeValue, entries);
420
+ }
421
+
422
+ /** Explicit HTML attributes without DOM property aliases or form-binding inference. */
423
+ export function hAttributes(
424
+ tag: string,
425
+ attributes: Record<string, unknown> | null = null,
426
+ ...children: SSRChild[]
427
+ ): HTML {
428
+ return intrinsic(tag, attributes, children, undefined, undefined, true);
429
+ }
430
+
431
+ /** Compiler-facing ordered explicit attributes; repeated names retain source order. */
432
+ export function hAttributeEntries(
433
+ tag: string,
434
+ entries: ReadonlyArray<readonly [string, unknown]>,
435
+ ...children: SSRChild[]
436
+ ): HTML {
437
+ return intrinsic(tag, null, children, undefined, entries, true);
438
+ }
439
+
440
+ /** Compiler-only explicit attributes with independent typed select/option identity. */
441
+ export function hSelectionEntries(
442
+ tag: "select" | "option",
443
+ entries: ReadonlyArray<readonly [string, unknown]>,
444
+ selection: { value: unknown; preserveSelected?: boolean },
445
+ ...children: SSRChild[]
446
+ ): HTML {
447
+ if (tag !== "select" && tag !== "option")
448
+ throw new TypeError("Selection entries require select or option");
449
+ return intrinsic(
450
+ tag,
451
+ null,
452
+ children,
453
+ undefined,
454
+ entries,
455
+ true,
456
+ validateBindingBox(selection),
457
+ );
458
+ }
459
+
460
+ function intrinsic(
461
+ tag: string,
462
+ props: Record<string, unknown> | null,
463
+ children: SSRChild[],
464
+ sourceCodec?: typeof sourceAttributeValue,
465
+ sourceEntries?: ReadonlyArray<readonly [string, unknown]>,
466
+ explicitAttributes = false,
467
+ selectionBox?: BindingValue,
468
+ ): HTML {
469
+ if (!ELEMENT_NAME.test(tag)) {
350
470
  throw new TypeError("Invalid server element name");
351
471
  }
352
472
  const owner = getOwner();
353
473
  const lower = tag.toLowerCase();
354
474
  const typedSelect =
355
- lower === "select" ? bindingValue(props, selectBinding) : undefined;
475
+ lower === "select"
476
+ ? (selectionBox ??
477
+ (!explicitAttributes ? bindingValue(props, selectBinding) : undefined))
478
+ : undefined;
356
479
  const typedOption =
357
- lower === "option" ? bindingValue(props, optionBinding) : undefined;
480
+ lower === "option"
481
+ ? (selectionBox ??
482
+ (!explicitAttributes ? bindingValue(props, optionBinding) : undefined))
483
+ : undefined;
358
484
  if (lower === "script" || lower === "style") {
359
485
  throw new TypeError("Server script/style elements are unsupported");
360
486
  }
361
- const attributes: Array<[string, unknown]> = [];
487
+ const staticMode = explicitAttributes || Boolean(sourceCodec);
488
+ let staticAttributes = "";
489
+ const attributes: Array<[string, unknown]> | undefined = staticMode
490
+ ? undefined
491
+ : [];
362
492
  let textareaValue: unknown;
363
493
  let hasTextareaValue = false;
364
494
  let selectValue: unknown;
365
495
  let hasSelectValue = false;
366
496
  let multiple = false;
367
497
  let optionValue: string | undefined;
498
+ let typedOptionValueSlot = false;
368
499
  let selectedAttribute = "";
369
- for (const name of Object.keys(props ?? {})) {
370
- if (!/^[a-zA-Z_:][a-zA-Z0-9:_.-]*$/.test(name)) {
500
+ let sourceNamespace: unknown;
501
+ const names = sourceEntries
502
+ ? undefined
503
+ : props
504
+ ? Object.keys(props)
505
+ : undefined;
506
+ const attributeCount = sourceEntries
507
+ ? sourceEntries.length
508
+ : (names?.length ?? 0);
509
+ for (let index = 0; index < attributeCount; index++) {
510
+ const name = sourceEntries ? sourceEntries[index]![0] : names![index]!;
511
+ if (!ATTRIBUTE_NAME.test(name)) {
371
512
  throw new TypeError("Invalid server attribute name");
372
513
  }
373
514
  // Event and ref handlers are client-only and must never execute on the server.
374
- if (/^on/i.test(name) || name === "ref" || name === "children") continue;
375
- if (["innerHTML", "outerHTML", "dangerouslySetInnerHTML"].includes(name)) {
515
+ if (
516
+ EVENT_NAME.test(name) ||
517
+ (!explicitAttributes && (name === "ref" || name === "children"))
518
+ )
519
+ continue;
520
+ if (
521
+ !explicitAttributes &&
522
+ (name === "innerHTML" ||
523
+ name === "outerHTML" ||
524
+ name === "dangerouslySetInnerHTML")
525
+ ) {
376
526
  throw new TypeError("Raw server HTML is unsupported");
377
527
  }
378
- if (name === "defaultValue" && lower !== "input" && lower !== "textarea")
528
+ if (
529
+ !explicitAttributes &&
530
+ name === "defaultValue" &&
531
+ lower !== "input" &&
532
+ lower !== "textarea"
533
+ )
379
534
  throw new TypeError(
380
535
  "defaultValue is supported only on input and textarea",
381
536
  );
382
- if (name === "defaultChecked" && lower !== "input")
537
+ if (!explicitAttributes && name === "defaultChecked" && lower !== "input")
383
538
  throw new TypeError("defaultChecked is supported only on input");
384
539
  const property =
385
- name === "defaultValue"
540
+ !explicitAttributes && name === "defaultValue"
386
541
  ? "value"
387
- : name === "defaultChecked"
542
+ : !explicitAttributes && name === "defaultChecked"
388
543
  ? "checked"
389
544
  : name;
390
- if (property !== name && Object.hasOwn(props!, property)) continue;
545
+ if (
546
+ property !== name &&
547
+ (sourceEntries
548
+ ? sourceEntries.some(([candidate]) => candidate === property)
549
+ : Object.hasOwn(props!, property))
550
+ )
551
+ continue;
391
552
  // Typed options carry their serialized value as well as comparison identity.
392
553
  // The ordinary value prop loses precedence without invoking its getter/accessor.
393
- if (name === "value" && (typedOption || typedSelect)) continue;
394
- const supplied = props![name];
554
+ if (name === "value" && (typedOption || typedSelect)) {
555
+ if (typedOption && staticMode) {
556
+ typedOptionValueSlot = true;
557
+ if (
558
+ typedOption.value != null &&
559
+ typeof typedOption.value !== "function"
560
+ ) {
561
+ optionValue = String(typedOption.value);
562
+ staticAttributes += ` value="${escapeHtml(optionValue)}"`;
563
+ }
564
+ }
565
+ continue;
566
+ }
567
+ const supplied = sourceEntries ? sourceEntries[index]![1] : props![name];
395
568
  let value = typeof supplied === "function" ? supplied() : supplied;
396
- if (name === "style") {
569
+ if (name === "xmlns") sourceNamespace = value;
570
+ if (!explicitAttributes && name === "style") {
397
571
  if (value == null || value === false) value = undefined;
398
572
  else if (typeof value === "object") {
399
- value = styleEntries(value)
400
- .map(([property, entry]) =>
401
- entry == null || entry === "" ? "" : `${property}:${entry};`,
402
- )
403
- .join("");
573
+ const entries = styleEntries(value);
574
+ let styleText = "";
575
+ for (let styleIndex = 0; styleIndex < entries.length; styleIndex++) {
576
+ const [styleProp, entry] = entries[styleIndex]!;
577
+ if (entry != null && entry !== "")
578
+ styleText += `${styleProp}:${entry};`;
579
+ }
580
+ value = styleText;
404
581
  } else if (typeof value !== "string") {
405
582
  throw new TypeError(
406
583
  "Style must be a CSS string, plain record, nullish or false",
@@ -408,44 +585,83 @@ export function h<P extends Record<string, unknown>>(
408
585
  }
409
586
  }
410
587
 
411
- if (lower === "select" && name === "multiple") {
412
- multiple = attributeValue(name, value, true) !== undefined;
588
+ if (
589
+ (!explicitAttributes || typedSelect) &&
590
+ lower === "select" &&
591
+ name === "multiple"
592
+ ) {
593
+ multiple =
594
+ (sourceCodec
595
+ ? sourceCodec(name, value, true)
596
+ : attributeValue(name, value, true)) !== undefined;
413
597
  }
414
- if (lower === "select" && name === "value") {
598
+ if (!explicitAttributes && lower === "select" && name === "value") {
415
599
  selectValue = value;
416
600
  hasSelectValue = true;
417
601
  continue;
418
602
  }
419
- if (lower === "option" && name === "selected") {
420
- if (attributeValue(name, value, true) !== undefined)
603
+ if (!explicitAttributes && lower === "option" && name === "selected") {
604
+ if (
605
+ (sourceCodec
606
+ ? sourceCodec(name, value, true)
607
+ : attributeValue(name, value, true)) !== undefined
608
+ )
421
609
  selectedAttribute = ` selected=""`;
422
610
  continue;
423
611
  }
424
- if (lower === "textarea" && property === "value") {
612
+ if (!explicitAttributes && lower === "textarea" && property === "value") {
425
613
  textareaValue = value;
426
614
  hasTextareaValue = true;
427
615
  continue;
428
616
  }
429
617
  const attr =
430
- property === "className"
618
+ !explicitAttributes && property === "className"
431
619
  ? "class"
432
- : property === "htmlFor"
620
+ : !explicitAttributes && property === "htmlFor"
433
621
  ? "for"
434
622
  : property;
435
- if (property === "value") {
436
- if (lower === "option") optionValue = String(value ?? "");
437
- attributes.push(["value", value]);
623
+ if (!explicitAttributes && property === "value") {
624
+ if (sourceCodec) {
625
+ const serialized = sourceCodec(
626
+ "value",
627
+ value,
628
+ typeof supplied === "function",
629
+ );
630
+ if (lower === "option") optionValue = String(serialized ?? "");
631
+ if (serialized !== undefined)
632
+ staticAttributes += ` value="${escapeHtml(serialized)}"`;
633
+ } else {
634
+ if (lower === "option") optionValue = String(value ?? "");
635
+ attributes!.push(["value", value]);
636
+ }
438
637
  continue;
439
638
  }
440
- attributes.push([attr, value]);
639
+ if (explicitAttributes) {
640
+ if (value != null) staticAttributes += ` ${attr}="${escapeHtml(value)}"`;
641
+ } else if (sourceCodec) {
642
+ const serialized = sourceCodec(
643
+ attr,
644
+ value,
645
+ typeof supplied === "function",
646
+ );
647
+ if (serialized !== undefined)
648
+ staticAttributes += ` ${attr}="${escapeHtml(serialized)}"`;
649
+ } else {
650
+ attributes!.push([attr, value]);
651
+ }
441
652
  }
442
653
  if (
443
654
  typedOption &&
655
+ !typedOptionValueSlot &&
444
656
  typedOption.value != null &&
445
657
  typeof typedOption.value !== "function"
446
658
  ) {
447
659
  optionValue = String(typedOption.value);
448
- attributes.push(["value", optionValue]);
660
+ if (staticMode) {
661
+ staticAttributes += ` value="${escapeHtml(optionValue)}"`;
662
+ } else {
663
+ attributes!.push(["value", optionValue]);
664
+ }
449
665
  }
450
666
  if (
451
667
  lower === "select" &&
@@ -464,44 +680,67 @@ export function h<P extends Record<string, unknown>>(
464
680
  ? children[0]
465
681
  : children.length
466
682
  ? children
467
- : (props?.children as SSRChild);
683
+ : explicitAttributes
684
+ ? undefined
685
+ : (props?.children as SSRChild);
468
686
  const bodyChild = resolve(sourceChild);
469
687
  const bodyText = textOnly
470
688
  ? hasTextareaValue
471
689
  ? String(textareaValue ?? "")
472
690
  : text(bodyChild)
473
691
  : undefined;
474
- const explicitNamespace = attributes.find(([name]) => name === "xmlns")?.[1];
692
+ let escapedBodyText =
693
+ bodyText === undefined ? undefined : escapeHtml(bodyText);
694
+ if (
695
+ escapedBodyText !== undefined &&
696
+ !explicitAttributes &&
697
+ lower === "textarea" &&
698
+ (escapedBodyText.startsWith("\n") || escapedBodyText.startsWith("\r"))
699
+ ) {
700
+ escapedBodyText = `\n${escapedBodyText}`;
701
+ }
475
702
  const isSvg = (inherited = false) =>
476
- explicitNamespace != null
477
- ? explicitNamespace === "http://www.w3.org/2000/svg"
703
+ sourceNamespace != null
704
+ ? sourceNamespace === "http://www.w3.org/2000/svg"
478
705
  : lower === "svg" || inherited;
479
- const renderAttributes = (svg: boolean) =>
480
- attributes
481
- .map(([attr, value]) => {
482
- if (!svg && attr === "checked" && !value) return "";
483
- const text = attributeValue(
484
- attr,
485
- !svg &&
486
- attr === "value" &&
487
- lower !== "progress" &&
488
- lower !== "meter" &&
489
- lower !== "li"
490
- ? (value ?? "")
491
- : value,
492
- !svg,
493
- );
494
- return text === undefined ? "" : ` ${attr}="${escapeHtml(text)}"`;
495
- })
496
- .join("");
706
+ const renderAttributes = (svg: boolean) => {
707
+ if (staticMode) return staticAttributes;
708
+ let out = "";
709
+ for (let index = 0; index < attributes!.length; index++) {
710
+ const [attr, value] = attributes![index]!;
711
+ if (!svg && attr === "checked" && !value) continue;
712
+ const serialized = attributeValue(
713
+ attr,
714
+ !svg &&
715
+ attr === "value" &&
716
+ lower !== "progress" &&
717
+ lower !== "meter" &&
718
+ lower !== "li"
719
+ ? (value ?? "")
720
+ : value,
721
+ !svg,
722
+ );
723
+ if (serialized !== undefined)
724
+ out += ` ${attr}="${escapeHtml(serialized)}"`;
725
+ }
726
+ return out;
727
+ };
497
728
  if (VOID.has(lower)) {
498
- if (content(bodyChild))
729
+ if (bodyChild != null && bodyChild !== false && content(bodyChild))
499
730
  throw new TypeError("Void server elements cannot have children");
731
+ if (staticMode) {
732
+ const markup = `<${tag}${staticAttributes}>`;
733
+ return { [html]: () => markup };
734
+ }
500
735
  return {
501
736
  [html]: (_selection, inheritedSvg) =>
502
737
  `<${tag}${renderAttributes(isSvg(inheritedSvg))}>`,
503
738
  };
504
739
  }
740
+ if (staticMode && escapedBodyText !== undefined && lower !== "option") {
741
+ const markup = `<${tag}${staticAttributes}>${escapedBodyText}</${tag}>`;
742
+ return { [html]: () => markup };
743
+ }
505
744
  return {
506
745
  [html]: (inherited, inheritedSvg) => {
507
746
  const svg = isSvg(inheritedSvg);
@@ -530,25 +769,45 @@ export function h<P extends Record<string, unknown>>(
530
769
  let selected = selectedAttribute;
531
770
  if (lower === "option" && selection) {
532
771
  selection.options++;
533
- const value =
534
- optionValue ??
535
- bodyText!.replace(/[\t\n\f\r ]+/g, " ").replace(/^ | $/g, "");
536
- const raw = typedOption ? typedOption.value : value;
537
- const matches = selection.binding
538
- ? selection.multiple && Array.isArray(selection.binding.value)
539
- ? selection.binding.value.includes(raw)
540
- : raw === selection.binding.value
541
- : selection.values!.has(value) &&
772
+ let matches: boolean;
773
+ if (selection.binding) {
774
+ const raw =
775
+ typedOption !== undefined
776
+ ? typedOption.value
777
+ : (optionValue ??
778
+ bodyText!.replace(/[\t\n\f\r ]+/g, " ").replace(/^ | $/g, ""));
779
+ matches =
780
+ selection.multiple && Array.isArray(selection.binding.value)
781
+ ? selection.binding.value.includes(raw)
782
+ : raw === selection.binding.value;
783
+ } else {
784
+ const value =
785
+ optionValue ??
786
+ bodyText!.replace(/[\t\n\f\r ]+/g, " ").replace(/^ | $/g, "");
787
+ matches =
788
+ selection.values!.has(value) &&
542
789
  (selection.multiple || !selection.matched);
543
- selected = matches ? ` selected=""` : "";
790
+ }
791
+ selected =
792
+ matches || (selection.binding?.preserveSelected && selectedAttribute)
793
+ ? ` selected=""`
794
+ : "";
544
795
  if (matches) selection.matched = true;
545
796
  }
546
- let body =
547
- bodyText === undefined
548
- ? runWithOwner(owner && !owner.disposed ? owner : getOwner(), () =>
549
- content(bodyChild, selection, svg && lower !== "foreignobject"),
550
- )
551
- : escapeHtml(bodyText);
797
+ let body: string;
798
+ if (escapedBodyText !== undefined) {
799
+ body = escapedBodyText;
800
+ } else {
801
+ const activeOwner = getOwner();
802
+ const targetOwner = owner && !owner.disposed ? owner : activeOwner;
803
+ const nextSvg = svg && lower !== "foreignobject";
804
+ body =
805
+ targetOwner === activeOwner
806
+ ? content(bodyChild, selection, nextSvg)
807
+ : runWithOwner(targetOwner, () =>
808
+ content(bodyChild, selection, nextSvg),
809
+ );
810
+ }
552
811
  if (
553
812
  lower === "select" &&
554
813
  selection &&
@@ -559,41 +818,39 @@ export function h<P extends Record<string, unknown>>(
559
818
  ) {
560
819
  throw new TypeError("Server select value has no matching option");
561
820
  }
562
- if (
563
- lower === "textarea" &&
564
- (body.startsWith("\n") || body.startsWith("\r"))
565
- )
566
- body = `\n${body}`;
567
- return `<${tag}${renderAttributes(svg)}${selected}>${body}</${tag}>`;
821
+ return `<${tag}${staticMode ? staticAttributes : renderAttributes(svg)}${selected}>${body}</${tag}>`;
568
822
  },
569
823
  };
570
824
  }
571
825
 
572
826
  export function renderToString(fn: () => SSRChild): string {
573
- return withSSRRendering(() => {
574
- let dispose = () => {};
575
- let result: string;
576
- try {
577
- result = createRoot((stop) => {
578
- dispose = stop;
579
- const requestOwner = getOwner()!;
580
- if (requestOwner.context?.has(cleanupOrderKey)) {
581
- requestOwner.context = new Map(requestOwner.context);
582
- requestOwner.context.delete(cleanupOrderKey);
583
- }
584
- return content(fn());
585
- });
586
- } catch (error) {
827
+ return withSSRRendering(() =>
828
+ withSSRRenderAttempt(undefined, () => {
829
+ let dispose = () => {};
830
+ let result: string;
587
831
  try {
588
- dispose();
589
- } catch {
590
- /* Preserve the render error. */
832
+ result = createRoot((stop) => {
833
+ dispose = stop;
834
+ resetSSRRenderAttempt();
835
+ const requestOwner = getOwner()!;
836
+ if (requestOwner.context?.has(cleanupOrderKey)) {
837
+ requestOwner.context = new Map(requestOwner.context);
838
+ requestOwner.context.delete(cleanupOrderKey);
839
+ }
840
+ return content(fn());
841
+ });
842
+ } catch (error) {
843
+ try {
844
+ dispose();
845
+ } catch {
846
+ /* Preserve the render error. */
847
+ }
848
+ throw error;
591
849
  }
592
- throw error;
593
- }
594
- dispose();
595
- return result;
596
- });
850
+ dispose();
851
+ return result;
852
+ }),
853
+ );
597
854
  }
598
855
 
599
856
  /** Server lowering must import lifecycle hooks here; browser effects never run. */