marko 6.4.10 → 6.4.12

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 (112) hide show
  1. package/dist/common/accessor.d.ts +0 -3
  2. package/dist/common/accessor.debug.d.ts +0 -3
  3. package/dist/common/attr-tag.d.ts +1 -0
  4. package/dist/common/errors.d.ts +2 -0
  5. package/dist/common/helpers.d.ts +3 -1
  6. package/dist/common/types.d.ts +4 -3
  7. package/dist/debug/dom/catch.feat.js +1 -1
  8. package/dist/debug/dom/catch.feat.mjs +1 -1
  9. package/dist/debug/dom/compat.feat.js +143 -0
  10. package/dist/debug/dom/compat.feat.mjs +141 -0
  11. package/dist/debug/dom/controllable-input.feat.js +1 -1
  12. package/dist/debug/dom/controllable-input.feat.mjs +1 -1
  13. package/dist/debug/dom/controllable-open.feat.js +1 -1
  14. package/dist/debug/dom/controllable-open.feat.mjs +1 -1
  15. package/dist/debug/dom/controllable-select.feat.js +1 -1
  16. package/dist/debug/dom/controllable-select.feat.mjs +1 -1
  17. package/dist/debug/dom/controllable-textarea.feat.js +1 -1
  18. package/dist/debug/dom/controllable-textarea.feat.mjs +1 -1
  19. package/dist/debug/dom/controllable.feat.js +1 -1
  20. package/dist/debug/dom/controllable.feat.mjs +1 -1
  21. package/dist/debug/dom/dynamic-tag-script.feat.js +1 -1
  22. package/dist/debug/dom/dynamic-tag-script.feat.mjs +1 -1
  23. package/dist/debug/dom/dynamic-tag-var.feat.js +1 -1
  24. package/dist/debug/dom/dynamic-tag-var.feat.mjs +1 -1
  25. package/dist/debug/dom/lazy.feat.js +1 -1
  26. package/dist/debug/dom/lazy.feat.mjs +1 -1
  27. package/dist/debug/dom/placeholder.feat.js +1 -1
  28. package/dist/debug/dom/placeholder.feat.mjs +1 -1
  29. package/dist/debug/{dom-DNB5yq3U.js → dom-CtXOr4Nm.js} +257 -230
  30. package/dist/debug/{dom-C1V5vpFs.mjs → dom-DaHYZpf2.mjs} +238 -229
  31. package/dist/debug/dom.js +8 -134
  32. package/dist/debug/dom.mjs +5 -126
  33. package/dist/debug/html/compat.feat.js +222 -0
  34. package/dist/debug/html/compat.feat.mjs +220 -0
  35. package/dist/debug/html-DMo6pc_h.mjs +3931 -0
  36. package/dist/debug/html-DfZjMkhx.js +4513 -0
  37. package/dist/debug/html.js +83 -4239
  38. package/dist/debug/html.mjs +1 -4152
  39. package/dist/dom/abort-signal.d.ts +1 -1
  40. package/dist/dom/catch.feat.js +3 -3
  41. package/dist/dom/catch.feat.mjs +1 -1
  42. package/dist/dom/{compat.d.ts → compat.feat.d.ts} +18 -9
  43. package/dist/dom/compat.feat.js +101 -0
  44. package/dist/dom/compat.feat.mjs +100 -0
  45. package/dist/dom/control-flow.d.ts +4 -5
  46. package/dist/dom/controllable-input.feat.js +2 -2
  47. package/dist/dom/controllable-input.feat.mjs +1 -1
  48. package/dist/dom/controllable-open.feat.js +2 -2
  49. package/dist/dom/controllable-open.feat.mjs +1 -1
  50. package/dist/dom/controllable-select.feat.js +2 -2
  51. package/dist/dom/controllable-select.feat.mjs +1 -1
  52. package/dist/dom/controllable-textarea.feat.js +2 -2
  53. package/dist/dom/controllable-textarea.feat.mjs +1 -1
  54. package/dist/dom/controllable.feat.js +2 -2
  55. package/dist/dom/controllable.feat.mjs +1 -1
  56. package/dist/dom/dom.d.ts +2 -1
  57. package/dist/dom/dynamic-tag-script.feat.js +2 -2
  58. package/dist/dom/dynamic-tag-script.feat.mjs +1 -1
  59. package/dist/dom/dynamic-tag-var.feat.js +1 -1
  60. package/dist/dom/dynamic-tag-var.feat.mjs +1 -1
  61. package/dist/dom/lazy.feat.js +1 -1
  62. package/dist/dom/lazy.feat.mjs +1 -1
  63. package/dist/dom/load.d.ts +3 -4
  64. package/dist/dom/placeholder.feat.js +3 -3
  65. package/dist/dom/placeholder.feat.mjs +1 -1
  66. package/dist/dom/queue.d.ts +1 -2
  67. package/dist/dom/resume.d.ts +3 -1
  68. package/dist/dom/signals.d.ts +5 -7
  69. package/dist/{dom-C2-Flitp.js → dom-BB-Te-3z.js} +222 -239
  70. package/dist/{dom-DsHYWMCR.mjs → dom-BO-0hzLZ.mjs} +124 -146
  71. package/dist/dom.d.ts +1 -2
  72. package/dist/dom.js +17 -95
  73. package/dist/dom.mjs +6 -79
  74. package/dist/html/assets.d.ts +3 -4
  75. package/dist/html/{compat.d.ts → compat.feat.d.ts} +5 -4
  76. package/dist/html/compat.feat.js +165 -0
  77. package/dist/html/compat.feat.mjs +164 -0
  78. package/dist/html/dynamic-tag.d.ts +1 -2
  79. package/dist/html/for.d.ts +0 -1
  80. package/dist/html/writer.d.ts +4 -3
  81. package/dist/html-DMDc0zKs.mjs +2404 -0
  82. package/dist/html-DrHsybFm.js +2880 -0
  83. package/dist/html.d.ts +1 -2
  84. package/dist/html.js +2 -2578
  85. package/dist/html.mjs +3 -2573
  86. package/dist/translator/index.d.ts +0 -1
  87. package/dist/translator/index.js +4889 -4733
  88. package/dist/translator/interop/out-global.d.ts +5 -0
  89. package/dist/translator/util/assert.d.ts +6 -0
  90. package/dist/translator/util/branch-tag.d.ts +1 -1
  91. package/dist/translator/util/entry-builder.d.ts +1 -1
  92. package/dist/translator/util/finalize-references.d.ts +2 -1
  93. package/dist/translator/util/for-selector.d.ts +1 -1
  94. package/dist/translator/util/known-tag.d.ts +10 -1
  95. package/dist/translator/util/optional.d.ts +0 -1
  96. package/dist/translator/util/reasons.d.ts +0 -1
  97. package/dist/translator/util/references.d.ts +12 -5
  98. package/dist/translator/util/runtime.d.ts +1 -0
  99. package/dist/translator/util/sections.d.ts +11 -2
  100. package/dist/translator/util/signals.d.ts +2 -1
  101. package/dist/translator/util/style-interpolation.d.ts +1 -1
  102. package/dist/translator/util/tag-facts.d.ts +2 -0
  103. package/dist/translator/util/tag-name-type.d.ts +1 -0
  104. package/dist/translator/util/translate-attrs.d.ts +1 -4
  105. package/dist/translator/util/visitors.d.ts +1 -1
  106. package/dist/translator/util/write-guard.d.ts +2 -0
  107. package/dist/translator/visitors/program/index.d.ts +2 -6
  108. package/dist/translator/visitors/referenced-identifier.d.ts +3 -1
  109. package/index.d.ts +2 -7
  110. package/package.json +4 -4
  111. package/dist/common/constants/keyed-scopes-prop.d.ts +0 -4
  112. package/dist/common/constants/keyed-scopes-prop.debug.d.ts +0 -4
@@ -1,4246 +1,90 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- // src/common/attr-tag.ts
4
- const empty = [];
5
- const rest = Symbol("Attribute Tag");
6
- function attrTag(attrs) {
7
- attrs[Symbol.iterator] = attrTagIterator;
8
- attrs[rest] = empty;
9
- return attrs;
10
- }
11
- function attrTags(first, attrs) {
12
- if (first) {
13
- if (first[rest] === empty) first[rest] = [attrs];
14
- else first[rest].push(attrs);
15
- return first;
16
- }
17
- return attrTag(attrs);
18
- }
19
- function* attrTagIterator() {
20
- yield this;
21
- yield* this[rest];
22
- }
23
- // src/common/constants/accessor-prefix.debug.ts
24
- const BranchScopes = "BranchScopes:";
25
- const ConditionalRenderer = "ConditionalRenderer:";
26
- const ControlledHandler = "ControlledHandler:";
27
- const ControlledType = "ControlledType:";
28
- const ControlledValue = "ControlledValue:";
29
- const EventAttributes = "EventAttributes:";
30
- const CatchContent = "#CatchContent";
31
- const ClosestBranchId = "#ClosestBranchId";
32
- const LoopKey = "#LoopKey";
33
- const PlaceholderBranch = "#PlaceholderBranch";
34
- const PlaceholderContent = "#PlaceholderContent";
35
- const Renderer = "#Renderer";
36
- const TagVariable = "#TagVariable";
37
- const Owner = "owner";
38
- const Embed = "embed";
39
- const Lazy = "lazy";
40
- // src/common/helpers.ts
41
- const invalidNativeAttrNameReg = /^[^a-z_]|[^a-z0-9._:-]/i;
42
- const knownWrongAttrs = {
43
- className: "class",
44
- classList: "class",
45
- htmlFor: "for",
46
- acceptCharset: "accept-charset",
47
- httpEquiv: "http-equiv",
48
- defaultValue: "value",
49
- defaultChecked: "checked",
50
- dangerouslySetInnerHTML: "$!{html}",
51
- key: "<for by>",
52
- ref: "<tag/ref>",
53
- "v-if": "<if>",
54
- "v-else": "<else>",
55
- "v-else-if": "<else if>",
56
- "v-for": "<for>",
57
- "v-show": "<if>",
58
- "v-model": "value:=state",
59
- "v-bind": "...attrs",
60
- "v-html": "$!{html}",
61
- "v-text": "${text}"
62
- };
63
- function getWrongAttrSuggestion(name) {
64
- if (Object.hasOwn(knownWrongAttrs, name)) return knownWrongAttrs[name];
65
- const colon = name.indexOf(":");
66
- if (colon > 0) {
67
- const rest = name.slice(colon + 1);
68
- switch (name.slice(0, colon)) {
69
- case "class": return `class={ ${rest}: condition }`;
70
- case "style": return `style={ ${rest}: value }`;
71
- case "on":
72
- case "v-on": return `on${rest.charAt(0).toUpperCase()}${rest.slice(1)}`;
73
- case "bind":
74
- case "v-model": return `${rest}:=state`;
75
- case "v-bind": return rest;
76
- }
77
- }
78
- }
79
- function stringifyClassEntry(name, value) {
80
- return value ? name : "";
81
- }
82
- const warnedStyleKeys = /* @__PURE__ */ new Set();
83
- function stringifyStyleEntry(name, value) {
84
- if (/[A-Z]/.test(name) && !name.includes("-") && !warnedStyleKeys.has(name)) {
85
- warnedStyleKeys.add(name);
86
- console.warn(`\`${name}\` is not a CSS property name; \`style\` object keys are written verbatim, so it renders as invalid CSS. Use \`${name.replace(/[A-Z]/g, (m) => "-" + m.toLowerCase()).replace(/^ms-/, "-ms-")}\`.`);
87
- }
88
- if (value !== value || typeof value === "bigint" && !value) console.warn(`The \`${name}\` style value \`${value !== value ? "NaN" : "0n"}\` drops the declaration; convert it to a string or number to render it.`);
89
- return value || value === 0 ? escapeStyleAttr(name) + ":" + escapeStyleAttr(value + "") : "";
90
- }
91
- const unsafeStyleAttrReg = /[\\;]/g;
92
- const replaceUnsafeStyleAttr = (c) => c === ";" ? "\\3B " : "\\\\";
93
- function escapeStyleAttr(str) {
94
- return unsafeStyleAttrReg.test(str) ? str.replace(unsafeStyleAttrReg, replaceUnsafeStyleAttr) : str;
95
- }
96
- function escapeStyleValue(str) {
97
- let closers = "";
98
- const result = str.replace(/[\\"'{};<>]|\/(?=\*)/g, (c) => c === "<" ? "\\3C " : c === ";" ? "\\3B " : c === "{" ? "\\7B " : "\\" + c);
99
- for (const c of result) if (c === "(") closers = ")" + closers;
100
- else if (c === "[") closers = "]" + closers;
101
- else if (c === closers[0]) closers = closers.slice(1);
102
- return result + closers;
103
- }
104
- const toDelimitedString = function toDelimitedString(val, delimiter, stringify) {
105
- let str = "";
106
- let sep = "";
107
- let part;
108
- if (val) {
109
- if (typeof val !== "object") str += val;
110
- else if (Array.isArray(val)) for (const v of val) {
111
- part = toDelimitedString(v, delimiter, stringify);
112
- if (part) {
113
- str += sep + part;
114
- sep = delimiter;
115
- }
116
- }
117
- else for (const name in val) {
118
- part = stringify(name, val[name]);
119
- if (part) {
120
- str += sep + part;
121
- sep = delimiter;
122
- }
123
- }
124
- }
125
- return str;
126
- };
127
- function isEventHandler(name) {
128
- return /^on[A-Z-]/.test(name);
129
- }
130
- function getEventType(name) {
131
- return name[2] === "-" ? name.slice(3) : name.slice(2).toLowerCase();
132
- }
133
- function hasKeys(obj) {
134
- for (const _ in obj) return true;
135
- return false;
136
- }
137
- function isNullishOrFalse(value) {
138
- return value == null || value === false;
139
- }
140
- function isNotNullishOrFalse(value) {
141
- return value != null && value !== false;
142
- }
143
- function isPromise(value) {
144
- return value != null && typeof value.then === "function";
145
- }
146
- function normalizeDynamicRenderer(value) {
147
- if (value) {
148
- if (typeof value === "string") return value;
149
- const normalized = value.content || value.default || value;
150
- if (!((typeof normalized === "object" || typeof normalized === "function") && "id" in normalized)) {
151
- if (value.content) throw new Error(`A dynamic tag must be a string tag name (like \`"div"\`) or a Marko template/component, but received an object whose \`content\` is not a template/component.`);
152
- if (typeof value !== "object" && typeof value !== "function") throw new Error(`A dynamic tag must be a string tag name (like \`"div"\`) or a Marko template/component, but received a ${typeof value}.`);
153
- }
154
- if ("id" in normalized) return normalized;
155
- }
156
- }
157
- // src/common/errors.ts
158
- const lowercaseOnAttrReg = /^on[a-z]/;
159
- function assertValidAttrValue(name, value) {
160
- if (value && typeof value !== "string" && lowercaseOnAttrReg.test(name)) throw new Error(`The \`${name}\` attribute must be a string or a falsey value (\`null\`, \`undefined\`, \`false\`, \`0\`, …), but received type "${typeof value}". To attach an event listener, use the \`on${name[2].toUpperCase()}${name.slice(3)}\` event handler instead.`);
161
- if (typeof value === "function") throw new Error(`The \`${name}\` attribute cannot be a function.${/Change$/.test(name) ? " A change handler is only used when its matching controllable attribute combination applies." : ""}`);
162
- const unrenderable = describeUnrenderable(value);
163
- if (unrenderable) throw new Error(`The \`${name}\` attribute cannot be ${unrenderable}.`);
164
- }
165
- function _assert_class_toggles(classes, toggles) {
166
- {
167
- const written = new Set(classes.split(" "));
168
- for (const toggle of toggles) {
169
- const names = new Set(toggle.split(" "));
170
- for (const name of names) if (written.has(name)) throw new Error(`The toggled class \`${name}\` is also written by another part of the \`class\` value; a toggled class may appear only once.`);
171
- for (const name of names) written.add(name);
172
- }
173
- }
174
- }
175
- function assertValidTextValue(value) {
176
- const unrenderable = describeUnrenderable(value);
177
- if (unrenderable) throw new Error(`Text content cannot be ${unrenderable}.`);
178
- if (isSilentlyDropped(value)) console.warn(`Text content of \`${describeDropped(value)}\` renders as nothing; convert it to a string or number to render it.`);
179
- }
180
- function isSilentlyDropped(value) {
181
- return value !== value || typeof value === "bigint" && !value;
182
- }
183
- function describeDropped(value) {
184
- return value !== value ? "NaN" : "0n";
185
- }
186
- function describeUnrenderable(value) {
187
- if (typeof value === "symbol") return "a symbol";
188
- if (typeof value === "object" && value !== null) {
189
- let stringified;
190
- try {
191
- stringified = `${value}`;
192
- } catch {
193
- stringified = "[object Object]";
194
- }
195
- if (/^\[object \w+\]$/.test(stringified)) return stringified === "[object Promise]" ? "a promise (use the `<await>` tag to render its resolved value)" : stringified === "[object Object]" ? "a plain object (it would render as `[object Object]`)" : `a value that renders as \`${stringified}\``;
196
- }
197
- }
198
- function assertValidLoopKey(key, seenKeys) {
199
- if (typeof key !== "string" && typeof key !== "number" || key !== key) throw new Error(`A \`<for>\` tag's \`by\` attribute must return a string or number for each item, but received ${key === null || key !== key ? key : `type "${typeof key}"`}.`);
200
- if (seenKeys) {
201
- if (seenKeys.has(key)) throw new Error(`A \`<for>\` tag's \`by\` attribute must return a unique value for each item, but \`${key}\` was used more than once.`);
202
- seenKeys.add(key);
203
- }
204
- }
205
- function assertValidList(value) {
206
- if (value && typeof value[Symbol.iterator] !== "function") throw new Error(`A \`<for>\` tag's \`of\` attribute must be an iterable, such as an array, but received ${describeForValue(value)}.`);
207
- }
208
- function assertOptionalRangeNumber(name, value) {
209
- if (value && (typeof value !== "number" || !isFinite(value))) throw new Error(`A \`<for>\` tag's \`${name}\` attribute must be a finite number, but received ${describeForValue(value)}.`);
210
- }
211
- function assertValidRangeBound(name, value) {
212
- if (!isFinite(value)) throw new Error(`A \`<for>\` tag's \`${name}\` attribute must be a finite number, but received ${describeForValue(value)}.`);
213
- }
214
- function describeForValue(value) {
215
- return typeof value === "number" || typeof value === "bigint" ? `\`${value}\`` : value === null ? "null" : `type "${typeof value}"`;
216
- }
217
- function assertValidAttrName(name) {
218
- if (invalidNativeAttrNameReg.test(name)) throw new Error(`Invalid attribute name: ${JSON.stringify(name)}`);
219
- const suggestion = getWrongAttrSuggestion(name);
220
- if (suggestion) throw new Error(`\`${name}\` is not a valid attribute, did you mean \`${suggestion}\`?`);
221
- }
222
- function _el_read_error() {
223
- throw new Error("Element references can only be read in scripts and event handlers.");
224
- }
225
- function _hoist_read_error() {
226
- throw new Error("Hoisted values can only be read in scripts and event handlers.");
227
- }
228
- function _signal_read_error() {
229
- throw new Error("Cannot use $signal in a server render.");
230
- }
231
- function _assert_hoist(value) {
232
- if (value !== void 0 && typeof value !== "function") throw new Error(`Hoisted values must be functions, received type "${typeof value}".`);
233
- }
234
- function assertExclusiveAttrs(attrs, onError = throwErr, isSet = isTruthy) {
235
- if (attrs) {
236
- let exclusiveAttrs;
237
- if (isSet(attrs.checkedChange)) (exclusiveAttrs ||= []).push("checkedChange");
238
- if ("checkedValue" in attrs) {
239
- (exclusiveAttrs ||= []).push("checkedValue");
240
- if ("checked" in attrs) exclusiveAttrs.push("checked");
241
- } else if (isSet(attrs.checkedValueChange)) {
242
- (exclusiveAttrs ||= []).push("checkedValueChange");
243
- if ("checked" in attrs) exclusiveAttrs.push("checked");
244
- }
245
- if (isSet(attrs.valueChange)) {
246
- (exclusiveAttrs ||= []).push("valueChange");
247
- if ("checked" in attrs && !exclusiveAttrs.includes("checked")) exclusiveAttrs.push("checked");
248
- }
249
- if (exclusiveAttrs && exclusiveAttrs.length > 1) onError(`The attributes ${joinWithAnd(exclusiveAttrs)} are mutually exclusive.`);
250
- }
251
- }
252
- function assertNoValueBindingOnCheckable(type, valueChange) {
253
- if (valueChange && /^(?:button|checkbox|hidden|image|radio|reset|submit)$/i.test(type)) console.error(`\`valueChange\` cannot be used on a \`type="${type}"\` \`<input>\` — user interaction can never change its \`value\`.` + (/^[cr]/i.test(type) ? " Bind `checked` or `checkedValue` instead." : ""));
254
- }
255
- function assertHandlerIsFunction(name, value) {
256
- if (value && typeof value !== "function") throw new Error(`The \`${name}\` handler must be a function or a falsey value (\`null\`, \`undefined\`, \`false\`, \`0\`, …), but received type "${typeof value}".`);
257
- }
258
- function assertValidTagName(tagName) {
259
- if (!/^[a-z][a-z0-9._-]*$/i.test(tagName)) throw new Error(`Invalid tag name: "${tagName}". Tag names must start with a letter and contain only letters, numbers, periods, hyphens, and underscores.`);
260
- }
261
- function isTruthy(value) {
262
- return value;
263
- }
264
- function throwErr(msg) {
265
- throw new Error(msg);
266
- }
267
- function joinWithAnd(a) {
268
- switch (a.length) {
269
- case 0: return "";
270
- case 1: return a[0];
271
- case 2: return `${a[0]} and ${a[1]}`;
272
- default: return `${a.slice(0, -1).join(", ")}, and ${a[a.length - 1]}`;
273
- }
274
- }
275
- // src/common/meta.ts
276
- const DYNAMIC_TAG_SCRIPT_REGISTER_ID = "_dynamicTagScript";
277
- const DYNAMIC_TAG_VAR_REGISTER_ID = "_dynamicTagVar";
278
- const PLACEHOLDER_DISMISS_REGISTER_ID = "_placeholderDismiss";
279
- // src/common/opt.ts
280
- function reduce(opt, cb, acc) {
281
- if (opt) {
282
- if (Array.isArray(opt)) for (const item of opt) acc = cb(acc, item);
283
- else acc = cb(acc, opt);
284
- }
285
- return acc;
286
- }
287
- function push(opt, item) {
288
- return opt ? Array.isArray(opt) ? (opt.push(item), opt) : [opt, item] : item;
289
- }
290
- function concat(opt, other) {
291
- if (!opt) return other;
292
- if (!other) return opt;
293
- if (Array.isArray(opt)) {
294
- if (Array.isArray(other)) for (const item of other) opt.push(item);
295
- else opt.push(other);
296
- return opt;
297
- }
298
- return Array.isArray(other) ? [opt, ...other] : [opt, other];
299
- }
300
- // src/html/serializer.ts
301
- const K_SCOPE_ID = Symbol("Scope ID");
302
- const kTouchedIterator = /* @__PURE__ */ Symbol.for("marko.touchedIterator");
303
- const { hasOwnProperty } = {};
304
- const objectProto = Object.prototype;
305
- const arrayProto = Array.prototype;
306
- const Generator = (/* @__PURE__ */ (function* () {})()).constructor;
307
- const AsyncGenerator = (/* @__PURE__ */ (async function* () {})()).constructor;
308
- patchIteratorNext(Generator.prototype);
309
- patchIteratorNext(AsyncGenerator.prototype);
310
- const REGISTRY = /* @__PURE__ */ new WeakMap();
311
- const KNOWN_SYMBOLS = /* @__PURE__ */ (() => {
312
- const KNOWN_SYMBOLS = /* @__PURE__ */ new Map();
313
- for (const name of Object.getOwnPropertyNames(Symbol)) {
314
- const symbol = Symbol[name];
315
- if (typeof symbol === "symbol") KNOWN_SYMBOLS.set(symbol, "Symbol." + name);
316
- }
317
- return KNOWN_SYMBOLS;
318
- })();
319
- const KNOWN_FUNCTIONS = /* @__PURE__ */ (() => /* @__PURE__ */ new Map([
320
- [AggregateError, "AggregateError"],
321
- [Array, "Array"],
322
- [Array.from, "Array.from"],
323
- [Array.isArray, "Array.isArray"],
324
- [Array.of, "Array.of"],
325
- [ArrayBuffer, "ArrayBuffer"],
326
- [ArrayBuffer.isView, "ArrayBuffer.isView"],
327
- [Atomics.add, "Atomics.add"],
328
- [Atomics.and, "Atomics.and"],
329
- [Atomics.compareExchange, "Atomics.compareExchange"],
330
- [Atomics.exchange, "Atomics.exchange"],
331
- [Atomics.isLockFree, "Atomics.isLockFree"],
332
- [Atomics.load, "Atomics.load"],
333
- [Atomics.notify, "Atomics.notify"],
334
- [Atomics.or, "Atomics.or"],
335
- [Atomics.store, "Atomics.store"],
336
- [Atomics.sub, "Atomics.sub"],
337
- [Atomics.wait, "Atomics.wait"],
338
- [BigInt, "BigInt"],
339
- [BigInt.asIntN, "BigInt.asIntN"],
340
- [BigInt.asUintN, "BigInt.asUintN"],
341
- [BigInt64Array, "BigInt64Array"],
342
- [BigInt64Array.from, "BigInt64Array.from"],
343
- [BigInt64Array.of, "BigInt64Array.of"],
344
- [BigUint64Array, "BigUint64Array"],
345
- [BigUint64Array.from, "BigUint64Array.from"],
346
- [BigUint64Array.of, "BigUint64Array.of"],
347
- [Boolean, "Boolean"],
348
- [console.assert, "console.assert"],
349
- [console.clear, "console.clear"],
350
- [console.count, "console.count"],
351
- [console.countReset, "console.countReset"],
352
- [console.debug, "console.debug"],
353
- [console.dir, "console.dir"],
354
- [console.dirxml, "console.dirxml"],
355
- [console.error, "console.error"],
356
- [console.group, "console.group"],
357
- [console.groupCollapsed, "console.groupCollapsed"],
358
- [console.groupEnd, "console.groupEnd"],
359
- [console.info, "console.info"],
360
- [console.log, "console.log"],
361
- [console.table, "console.table"],
362
- [console.time, "console.time"],
363
- [console.timeEnd, "console.timeEnd"],
364
- [console.timeLog, "console.timeLog"],
365
- [console.timeStamp, "console.timeStamp"],
366
- [console.trace, "console.trace"],
367
- [console.warn, "console.warn"],
368
- [DataView, "DataView"],
369
- [Date, "Date"],
370
- [Date.now, "Date.now"],
371
- [Date.parse, "Date.parse"],
372
- [Date.UTC, "Date.UTC"],
373
- [decodeURI, "decodeURI"],
374
- [decodeURIComponent, "decodeURIComponent"],
375
- [encodeURI, "encodeURI"],
376
- [encodeURIComponent, "encodeURIComponent"],
377
- [Error, "Error"],
378
- [EvalError, "EvalError"],
379
- [Float32Array, "Float32Array"],
380
- [Float32Array.from, "Float32Array.from"],
381
- [Float32Array.of, "Float32Array.of"],
382
- [Float64Array, "Float64Array"],
383
- [Float64Array.from, "Float64Array.from"],
384
- [Float64Array.of, "Float64Array.of"],
385
- [Function, "Function"],
386
- [globalThis.atob, "atob"],
387
- [globalThis.btoa, "btoa"],
388
- [globalThis.clearInterval, "clearInterval"],
389
- [globalThis.clearTimeout, "clearTimeout"],
390
- [globalThis.crypto?.getRandomValues, "crypto.getRandomValues"],
391
- [globalThis.crypto?.randomUUID, "crypto.randomUUID"],
392
- [globalThis.fetch, "fetch"],
393
- [globalThis.performance?.now, "performance.now"],
394
- [globalThis.queueMicrotask, "queueMicrotask"],
395
- [globalThis.setInterval, "setInterval"],
396
- [globalThis.setTimeout, "setTimeout"],
397
- [globalThis.structuredClone, "structuredClone"],
398
- [globalThis.URL, "URL"],
399
- [globalThis.URLSearchParams, "URLSearchParams"],
400
- [globalThis.WritableStream, "WritableStream"],
401
- [Int16Array, "Int16Array"],
402
- [Int16Array.from, "Int16Array.from"],
403
- [Int16Array.of, "Int16Array.of"],
404
- [Int32Array, "Int32Array"],
405
- [Int32Array.from, "Int32Array.from"],
406
- [Int32Array.of, "Int32Array.of"],
407
- [Int8Array, "Int8Array"],
408
- [Int8Array.from, "Int8Array.from"],
409
- [Int8Array.of, "Int8Array.of"],
410
- [Intl.Collator, "Intl.Collator"],
411
- [Intl.DateTimeFormat, "Intl.DateTimeFormat"],
412
- [Intl.DisplayNames, "Intl.DisplayNames"],
413
- [Intl.getCanonicalLocales, "Intl.getCanonicalLocales"],
414
- [Intl.ListFormat, "Intl.ListFormat"],
415
- [Intl.Locale, "Intl.Locale"],
416
- [Intl.NumberFormat, "Intl.NumberFormat"],
417
- [Intl.PluralRules, "Intl.PluralRules"],
418
- [Intl.RelativeTimeFormat, "Intl.RelativeTimeFormat"],
419
- [Intl.Segmenter, "Intl.Segmenter"],
420
- [Intl.supportedValuesOf, "Intl.supportedValuesOf"],
421
- [isFinite, "isFinite"],
422
- [isNaN, "isNaN"],
423
- [JSON.parse, "JSON.parse"],
424
- [JSON.stringify, "JSON.stringify"],
425
- [Map, "Map"],
426
- [Map.groupBy, "Map.groupBy"],
427
- [Math.abs, "Math.abs"],
428
- [Math.acos, "Math.acos"],
429
- [Math.acosh, "Math.acosh"],
430
- [Math.asin, "Math.asin"],
431
- [Math.asinh, "Math.asinh"],
432
- [Math.atan, "Math.atan"],
433
- [Math.atan2, "Math.atan2"],
434
- [Math.atanh, "Math.atanh"],
435
- [Math.cbrt, "Math.cbrt"],
436
- [Math.ceil, "Math.ceil"],
437
- [Math.clz32, "Math.clz32"],
438
- [Math.cos, "Math.cos"],
439
- [Math.cosh, "Math.cosh"],
440
- [Math.exp, "Math.exp"],
441
- [Math.expm1, "Math.expm1"],
442
- [Math.floor, "Math.floor"],
443
- [Math.fround, "Math.fround"],
444
- [Math.hypot, "Math.hypot"],
445
- [Math.imul, "Math.imul"],
446
- [Math.log, "Math.log"],
447
- [Math.log10, "Math.log10"],
448
- [Math.log1p, "Math.log1p"],
449
- [Math.log2, "Math.log2"],
450
- [Math.max, "Math.max"],
451
- [Math.min, "Math.min"],
452
- [Math.pow, "Math.pow"],
453
- [Math.random, "Math.random"],
454
- [Math.round, "Math.round"],
455
- [Math.sign, "Math.sign"],
456
- [Math.sin, "Math.sin"],
457
- [Math.sinh, "Math.sinh"],
458
- [Math.sqrt, "Math.sqrt"],
459
- [Math.tan, "Math.tan"],
460
- [Math.tanh, "Math.tanh"],
461
- [Math.trunc, "Math.trunc"],
462
- [Number, "Number"],
463
- [Number.isFinite, "Number.isFinite"],
464
- [Number.isInteger, "Number.isInteger"],
465
- [Number.isNaN, "Number.isNaN"],
466
- [Number.isSafeInteger, "Number.isSafeInteger"],
467
- [Number.parseFloat, "Number.parseFloat"],
468
- [Number.parseInt, "Number.parseInt"],
469
- [Object, "Object"],
470
- [Object.assign, "Object.assign"],
471
- [Object.create, "Object.create"],
472
- [Object.defineProperties, "Object.defineProperties"],
473
- [Object.defineProperty, "Object.defineProperty"],
474
- [Object.entries, "Object.entries"],
475
- [Object.freeze, "Object.freeze"],
476
- [Object.fromEntries, "Object.fromEntries"],
477
- [Object.getOwnPropertyDescriptor, "Object.getOwnPropertyDescriptor"],
478
- [Object.getOwnPropertyDescriptors, "Object.getOwnPropertyDescriptors"],
479
- [Object.getOwnPropertyNames, "Object.getOwnPropertyNames"],
480
- [Object.getOwnPropertySymbols, "Object.getOwnPropertySymbols"],
481
- [Object.getPrototypeOf, "Object.getPrototypeOf"],
482
- [Object.is, "Object.is"],
483
- [Object.isExtensible, "Object.isExtensible"],
484
- [Object.isFrozen, "Object.isFrozen"],
485
- [Object.isSealed, "Object.isSealed"],
486
- [Object.keys, "Object.keys"],
487
- [Object.preventExtensions, "Object.preventExtensions"],
488
- [Object.seal, "Object.seal"],
489
- [Object.setPrototypeOf, "Object.setPrototypeOf"],
490
- [Object.values, "Object.values"],
491
- [parseFloat, "parseFloat"],
492
- [parseInt, "parseInt"],
493
- [Promise, "Promise"],
494
- [Proxy, "Proxy"],
495
- [RangeError, "RangeError"],
496
- [ReferenceError, "ReferenceError"],
497
- [Reflect.apply, "Reflect.apply"],
498
- [Reflect.construct, "Reflect.construct"],
499
- [Reflect.defineProperty, "Reflect.defineProperty"],
500
- [Reflect.deleteProperty, "Reflect.deleteProperty"],
501
- [Reflect.get, "Reflect.get"],
502
- [Reflect.getOwnPropertyDescriptor, "Reflect.getOwnPropertyDescriptor"],
503
- [Reflect.getPrototypeOf, "Reflect.getPrototypeOf"],
504
- [Reflect.has, "Reflect.has"],
505
- [Reflect.isExtensible, "Reflect.isExtensible"],
506
- [Reflect.ownKeys, "Reflect.ownKeys"],
507
- [Reflect.preventExtensions, "Reflect.preventExtensions"],
508
- [Reflect.set, "Reflect.set"],
509
- [Reflect.setPrototypeOf, "Reflect.setPrototypeOf"],
510
- [RegExp, "RegExp"],
511
- [Set, "Set"],
512
- [String, "String"],
513
- [String.fromCharCode, "String.fromCharCode"],
514
- [String.fromCodePoint, "String.fromCodePoint"],
515
- [String.raw, "String.raw"],
516
- [Symbol, "Symbol"],
517
- [Symbol.for, "Symbol.for"],
518
- [SyntaxError, "SyntaxError"],
519
- [TypeError, "TypeError"],
520
- [Uint16Array, "Uint16Array"],
521
- [Uint16Array.from, "Uint16Array.from"],
522
- [Uint16Array.of, "Uint16Array.of"],
523
- [Uint32Array, "Uint32Array"],
524
- [Uint32Array.from, "Uint32Array.from"],
525
- [Uint32Array.of, "Uint32Array.of"],
526
- [Uint8Array, "Uint8Array"],
527
- [Uint8Array.from, "Uint8Array.from"],
528
- [Uint8Array.of, "Uint8Array.of"],
529
- [Uint8ClampedArray, "Uint8ClampedArray"],
530
- [Uint8ClampedArray.from, "Uint8ClampedArray.from"],
531
- [Uint8ClampedArray.of, "Uint8ClampedArray.of"],
532
- [URIError, "URIError"],
533
- [WeakMap, "WeakMap"],
534
- [WeakSet, "WeakSet"]
535
- ]))();
536
- const KNOWN_OBJECTS = /* @__PURE__ */ (() => /* @__PURE__ */ new Map([
537
- [Atomics, "Atomics"],
538
- [console, "console"],
539
- [globalThis, "globalThis"],
540
- [globalThis.crypto, "crypto"],
541
- [Intl, "Intl"],
542
- [JSON, "JSON"],
543
- [Math, "Math"],
544
- [Reflect, "Reflect"]
545
- ]))();
546
- var State$1 = class {
547
- ids = 0;
548
- flushId = 0;
549
- wroteUndefined = false;
550
- buf = [];
551
- strs = /* @__PURE__ */ new Map();
552
- refs = /* @__PURE__ */ new WeakMap();
553
- deferredRefs = /* @__PURE__ */ new Set();
554
- boundary;
555
- channel = void 0;
556
- channelDeps = null;
557
- queuedCalls = [];
558
- queuedReadyCalls = [];
559
- scopeRef(scope, scopeId) {
560
- return this.refs.get(scope) || newScopeReference(this, scope, scopeId);
561
- }
562
- writeScopeProps(props, ref) {
563
- return writeObjectProps(this, props, ref);
564
- }
565
- scopesCursor(scopeId) {
566
- return scopeId + ",";
567
- }
568
- writeTrailing(scopesIndex) {
569
- const { buf } = this;
570
- if (~scopesIndex) {
571
- buf[scopesIndex] = "_([" + buf[scopesIndex];
572
- buf.push("])");
573
- }
574
- writeDeferred(this);
575
- return ",0)";
576
- }
577
- wrapPayload(result, extras) {
578
- const arrow = this.wroteUndefined ? "(_,$)=>" : "_=>";
579
- this.wroteUndefined = false;
580
- return extras ? arrow + result : arrow + "[" + result + "]";
581
- }
582
- writeScopedRegistration(val, parent, accessor, registered) {
583
- const ref = new Reference(parent, accessor, this.flushId, this.buf.length);
584
- ref.channel = this.channel;
585
- this.refs.set(val, ref);
586
- ref.debug = DEBUG.get(val);
587
- const scope = registered.scope;
588
- const scopeId = scope[K_SCOPE_ID];
589
- trackScope(this, scope, scopeId);
590
- const locals = registered.locals?.(this.boundary.state.scope);
591
- if (locals) {
592
- this.buf.push(registered.access + "(_(" + scopeId + ")");
593
- for (const local of locals) {
594
- this.buf.push(",");
595
- writePlainObject(this, local, newArgReference(this, ref, local));
596
- }
597
- } else this.buf.push("_(" + scopeId + "," + quoteRegistryId(registered.id));
598
- this.buf.push(")");
599
- }
600
- };
601
- var Reference = class {
602
- assignments = null;
603
- deferredMembers = null;
604
- scopeId = void 0;
605
- channel = void 0;
606
- parent;
607
- accessor;
608
- flushId;
609
- pos;
610
- id;
611
- path = null;
612
- constructor(parent, accessor, flushId, pos = null, id = null) {
613
- this.parent = parent;
614
- this.accessor = accessor;
615
- this.flushId = flushId;
616
- this.pos = pos;
617
- this.id = id;
618
- }
619
- };
620
- const DEBUG = /* @__PURE__ */ new WeakMap();
621
- function setDebugInfo(obj, file, loc, vars) {
622
- DEBUG.set(obj, {
623
- file,
624
- loc,
625
- vars,
626
- slots: DEBUG.get(obj)?.slots
627
- });
628
- }
629
- function setDebugSlotName(obj, accessor, name) {
630
- const debug = DEBUG.get(obj);
631
- if (debug) (debug.slots ??= {})[accessor] = name;
632
- else DEBUG.set(obj, {
633
- file: "",
634
- loc: 0,
635
- vars: void 0,
636
- slots: { [accessor]: name }
637
- });
638
- }
639
- function stringifyScopes(state, flushes, boundary, channel) {
640
- try {
641
- state.boundary = boundary;
642
- state.channel = channel;
643
- return writeScopesRoot(state, flushes);
644
- } catch (err) {
645
- abortRender(boundary, err);
646
- return "";
647
- } finally {
648
- state.flushId++;
649
- state.buf = [];
650
- }
651
- }
652
- function pendingReadyChannel(state) {
653
- const calls = state.queuedReadyCalls;
654
- return calls.length ? calls[0].channel : void 0;
655
- }
656
- function takeChannelDeps(state) {
657
- const deps = state.channelDeps;
658
- state.channelDeps = null;
659
- return deps;
660
- }
661
- function queueCall(state, value, object, method, channel) {
662
- (channel?.readyId ? state.queuedReadyCalls : state.queuedCalls).push({
663
- method,
664
- value,
665
- object,
666
- channel,
667
- valueId: null
668
- });
669
- }
670
- function dropQueuedCall(state, value, object, method, channel) {
671
- const queuedCalls = channel?.readyId ? state.queuedReadyCalls : state.queuedCalls;
672
- for (let i = 0; i < queuedCalls.length; i++) {
673
- const call = queuedCalls[i];
674
- if (call.value === value && call.object === object && call.method === method) {
675
- queuedCalls.splice(i, 1);
676
- return true;
677
- }
678
- }
679
- return false;
680
- }
681
- function register(id, val, scope, locals, access = "_._" + toAccess(toObjectKey(id))) {
682
- REGISTRY.set(val, {
683
- id,
684
- scope,
685
- locals,
686
- access
687
- });
688
- return val;
689
- }
690
- function writeScopesRoot(state, flushes) {
691
- const { buf } = state;
692
- let nextSlotId = -1;
693
- let scopesIndex = -1;
694
- for (const flush of flushes) {
695
- const scopeId = flush[0];
696
- const scope = flush[1];
697
- const ref = state.scopeRef(scope, scopeId);
698
- const openIndex = buf.push("") - 1;
699
- if (state.writeScopeProps(flush[2], ref)) {
700
- buf[openIndex] = nextSlotId === -1 ? state.scopesCursor(scopeId) + "{" : (scopeId !== nextSlotId ? "," + (scopeId - nextSlotId) : "") + ",{";
701
- if (scopesIndex === -1) scopesIndex = openIndex;
702
- nextSlotId = scopeId + 1;
703
- buf.push("}");
704
- } else buf.pop();
705
- }
706
- let extras = "";
707
- if (state.deferredRefs.size || hasChannelCalls(state)) extras = state.writeTrailing(scopesIndex);
708
- let result = extras && "(";
709
- for (const chunk of buf) result += chunk;
710
- result += extras;
711
- if (!result) return "";
712
- return state.wrapPayload(result, extras);
713
- }
714
- function writeDeferred(state) {
715
- let sep = state.buf.length ? "," : "";
716
- if (state.deferredRefs.size) {
717
- const pending = state.deferredRefs;
718
- state.deferredRefs = /* @__PURE__ */ new Set();
719
- let buf = "";
720
- let hasCalls = false;
721
- for (const ref of pending) {
722
- if (ref.assignments) {
723
- buf += sep + assignmentsToString(ref.assignments, ref.id);
724
- ref.assignments = null;
725
- sep = ",";
726
- }
727
- hasCalls ||= ref.deferredMembers !== null;
728
- }
729
- if (buf) state.buf.push(buf);
730
- if (hasCalls) for (const ref of pending) {
731
- const members = ref.deferredMembers;
732
- if (members) {
733
- writeDeferredMembers(state, ref.id, members);
734
- ref.deferredMembers = null;
735
- }
736
- }
737
- }
738
- const readyId = state.channel?.readyId;
739
- let calls = state.queuedCalls;
740
- if (readyId) {
741
- calls = [];
742
- const remaining = [];
743
- for (const call of state.queuedReadyCalls) (call.channel.readyId === readyId ? calls : remaining).push(call);
744
- state.queuedReadyCalls = remaining;
745
- } else if (calls.length) state.queuedCalls = [];
746
- for (const call of calls) {
747
- const objectStartIndex = state.buf.push(state.buf.length === 0 ? "" : ",");
748
- if (writeProp(state, call.object, null, "")) {
749
- const objectRef = state.refs.get(call.object);
750
- if (!objectRef.id && !isAncestorChannelRef(state, objectRef)) {
751
- objectRef.id = nextRefAccess(state);
752
- state.buf[objectStartIndex] = "(" + objectRef.id + "=" + state.buf[objectStartIndex];
753
- state.buf.push(")");
754
- } else if (objectRef.id && state.buf[objectStartIndex] !== objectRef.id) {
755
- state.buf[objectStartIndex] = "(" + state.buf[objectStartIndex];
756
- state.buf.push(")");
757
- }
758
- } else state.buf.push("void 0");
759
- state.buf.push("." + call.method + "(");
760
- if (call.value !== void 0) writeCallArg(state, call.value, call.valueId);
761
- state.buf.push(")");
762
- }
763
- if (state.deferredRefs.size) writeDeferred(state);
764
- }
765
- function writeDeferredMembers(state, id, { collection, first, rest }) {
766
- if (collection instanceof Map) {
767
- writeDeferredEntry(state, id, first);
768
- for (const entry of rest) writeDeferredEntry(state, id, entry);
769
- } else {
770
- writeDeferredMember(state, id, first);
771
- for (const member of rest) writeDeferredMember(state, id, member);
772
- }
773
- }
774
- function writeDeferredEntry(state, id, [key, value]) {
775
- state.buf.push("," + id + ".set(");
776
- if (key !== void 0 || value !== void 0) writeCallArg(state, key, null);
777
- if (value !== void 0) {
778
- state.buf.push(",");
779
- writeCallArg(state, value, null);
780
- }
781
- state.buf.push(")");
782
- }
783
- function writeDeferredMember(state, id, member) {
784
- state.buf.push("," + id + ".add(");
785
- if (member !== void 0) writeCallArg(state, member, null);
786
- state.buf.push(")");
787
- }
788
- function writeCallArg(state, val, valueId) {
789
- const startIndex = state.buf.length;
790
- if (val === void 0) {
791
- state.wroteUndefined = true;
792
- state.buf.push("$");
793
- } else if (writeProp(state, val, null, "")) {
794
- const ref = typeof val === "string" ? state.strs.get(val) : state.refs.get(val);
795
- if (ref && !ref.id && ref.scopeId === void 0 && !isAncestorChannelRef(state, ref)) {
796
- ref.id = valueId || nextRefAccess(state);
797
- state.buf[startIndex] = ref.id + "=" + state.buf[startIndex];
798
- }
799
- } else state.buf.push("void 0");
800
- }
801
- function hasChannelCalls(state) {
802
- return hasMatchingCalls(state, state.channel?.readyId);
803
- }
804
- function hasMatchingCalls(state, readyId) {
805
- if (!readyId) return state.queuedCalls.length > 0;
806
- for (const call of state.queuedReadyCalls) if (call.channel.readyId === readyId) return true;
807
- return false;
808
- }
809
- function writeProp(state, val, parent, accessor) {
810
- switch (typeof val) {
811
- case "string": return writeString(state, val, parent, accessor);
812
- case "number": return writeNumber(state, val);
813
- case "boolean": return writeBoolean(state, val);
814
- case "bigint": return writeBigInt(state, val);
815
- case "symbol": return writeSymbol(state, val, parent, accessor);
816
- case "function": return writeFunction(state, val, parent, accessor);
817
- case "object": return writeObject(state, val, parent, accessor);
818
- default:
819
- throwUnserializable(state, val, parent, accessor);
820
- return false;
821
- }
822
- }
823
- function writeReferenceOr(state, write, val, parent, accessor) {
824
- let ref = state.refs.get(val);
825
- if (ref) {
826
- if (!trackChannel(state, ref)) {
827
- abortUnreachableChannel(state, val);
828
- return false;
829
- }
830
- if (parent && isCircular(parent, ref)) {
831
- ensureRefAccess(state, ref);
832
- state.deferredRefs.add(ref);
833
- addAssignment(ref, accessId(state, parent) + toAccess(accessor));
834
- return false;
835
- }
836
- writeRef(state, ref);
837
- return true;
838
- }
839
- const registered = REGISTRY.get(val);
840
- if (registered) return writeRegistered(state, val, parent, accessor, registered);
841
- state.refs.set(val, ref = new Reference(parent, accessor, state.flushId, state.buf.length));
842
- ref.channel = state.channel;
843
- ref.debug = DEBUG.get(val);
844
- if (write(state, val, ref)) return true;
845
- state.refs.delete(val);
846
- return false;
847
- }
848
- function trackScope(state, val, scopeId) {
849
- const ref = state.refs.get(val);
850
- if (ref) trackChannel(state, ref);
851
- else newScopeReference(state, val, scopeId);
852
- }
853
- function newScopeReference(state, val, scopeId) {
854
- const ref = new Reference(null, null, state.flushId);
855
- ref.scopeId = scopeId;
856
- ref.channel = state.channel;
857
- state.refs.set(val, ref);
858
- ref.debug = DEBUG.get(val);
859
- return ref;
860
- }
861
- function quoteRegistryId(id) {
862
- return quote(id, 0);
863
- }
864
- function writeRegistered(state, val, parent, accessor, registered) {
865
- const { scope } = registered;
866
- if (scope) state.writeScopedRegistration(val, parent, accessor, registered);
867
- else state.buf.push(registered.access);
868
- return true;
869
- }
870
- const STRING_DEDUP_LENGTH = 12;
871
- function writeString(state, val, parent, accessor) {
872
- if (val.length > STRING_DEDUP_LENGTH) {
873
- const ref = state.strs.get(val);
874
- if (ref) {
875
- if (trackChannel(state, ref)) {
876
- writeRef(state, ref);
877
- return true;
878
- }
879
- } else {
880
- const ref = new Reference(parent, accessor, state.flushId, state.buf.length);
881
- ref.channel = state.channel;
882
- state.strs.set(val, ref);
883
- }
884
- }
885
- state.buf.push(quote(val, 0));
886
- return true;
887
- }
888
- function writeNumber(state, val) {
889
- state.buf.push(val + "");
890
- return true;
891
- }
892
- function writeBoolean(state, val) {
893
- state.buf.push(val ? "!0" : "!1");
894
- return true;
895
- }
896
- function writeBigInt(state, val) {
897
- state.buf.push(val + "n");
898
- return true;
899
- }
900
- function writeFunction(state, val, parent, accessor) {
901
- const wellKnownFunction = KNOWN_FUNCTIONS.get(val);
902
- if (wellKnownFunction) {
903
- state.buf.push(wellKnownFunction);
904
- return true;
905
- }
906
- return writeReferenceOr(state, writeNever, val, parent, accessor);
907
- }
908
- function writeSymbol(state, val, parent, accessor) {
909
- const wellKnownSymbol = KNOWN_SYMBOLS.get(val);
910
- if (wellKnownSymbol) {
911
- state.buf.push(wellKnownSymbol);
912
- return true;
913
- }
914
- const key = Symbol.keyFor(val);
915
- if (key !== void 0) {
916
- state.buf.push("Symbol.for(" + quote(key, 0) + ")");
917
- return true;
918
- }
919
- return writeReferenceOr(state, writeUnknownSymbol, val, parent, accessor);
920
- }
921
- function writeUnknownSymbol(state) {
922
- state.buf.push("Symbol()");
923
- return true;
924
- }
925
- function writeNever(state, val, ref) {
926
- throwUnserializable(state, val, ref);
927
- return false;
928
- }
929
- function writeNull(state) {
930
- state.buf.push("null");
931
- return true;
932
- }
933
- function writeObject(state, val, parent, accessor) {
934
- if (val === null) return writeNull(state);
935
- const scopeId = val[K_SCOPE_ID];
936
- if (scopeId !== void 0) {
937
- trackScope(state, val, scopeId);
938
- state.buf.push("_(" + scopeId + ")");
939
- return true;
940
- }
941
- const wellKnownObject = KNOWN_OBJECTS.get(val);
942
- if (wellKnownObject) {
943
- state.buf.push(wellKnownObject);
944
- return true;
945
- }
946
- return writeReferenceOr(state, writeUnknownObject, val, parent, accessor);
947
- }
948
- function writeUnknownObject(state, val, ref) {
949
- const proto = Object.getPrototypeOf(val);
950
- if (proto === objectProto) return writePlainObject(state, val, ref);
951
- if (proto === arrayProto) return writeArray(state, val, ref);
952
- const constructor = proto?.constructor;
953
- switch (constructor) {
954
- case void 0: return writeNullObject(state, val, ref);
955
- case Object: return writePlainObject(state, val, ref);
956
- case Array: return writeArray(state, val, ref);
957
- case Date: return writeDate(state, val);
958
- case RegExp: return writeRegExp(state, val);
959
- case Promise: return writePromise(state, val, ref);
960
- case Map: return writeMap(state, val, ref);
961
- case Set: return writeSet(state, val, ref);
962
- case Generator: return writeGenerator(state, val, ref);
963
- case AsyncGenerator: return writeAsyncGenerator(state, val, ref);
964
- case Error:
965
- case EvalError:
966
- case RangeError:
967
- case ReferenceError:
968
- case SyntaxError:
969
- case TypeError:
970
- case URIError: return writeError(state, val, constructor.name, ref);
971
- case AggregateError: return writeAggregateError(state, val, ref);
972
- case ArrayBuffer: return writeArrayBuffer(state, val);
973
- case Int8Array:
974
- case Uint8Array:
975
- case Uint8ClampedArray:
976
- case Int16Array:
977
- case Uint16Array:
978
- case Int32Array:
979
- case Uint32Array:
980
- case Float32Array:
981
- case Float64Array:
982
- case BigInt64Array:
983
- case BigUint64Array: return writeTypedArray(state, val, constructor.name, ref);
984
- case DataView: return writeDataView(state, val, ref);
985
- case WeakSet: return writeWeakSet(state);
986
- case WeakMap: return writeWeakMap(state);
987
- case globalThis.URL: return writeURL(state, val);
988
- case globalThis.URLSearchParams: return writeURLSearchParams(state, val);
989
- case globalThis.Headers: return writeHeaders(state, val);
990
- case globalThis.FormData: return writeFormData(state, val, ref);
991
- case globalThis.ReadableStream: return writeReadableStream(state, val, ref);
992
- case globalThis.Request: return writeRequest(state, val, ref);
993
- case globalThis.Response: return writeResponse(state, val, ref);
994
- case globalThis.Intl?.NumberFormat: return writeIntl(state, val, "NumberFormat", ref);
995
- case globalThis.Intl?.DateTimeFormat: return writeIntl(state, val, "DateTimeFormat", ref);
996
- case globalThis.Intl?.Collator: return writeIntl(state, val, "Collator", ref);
997
- case globalThis.Intl?.PluralRules: return writeIntl(state, val, "PluralRules", ref);
998
- case globalThis.Intl?.RelativeTimeFormat: return writeIntl(state, val, "RelativeTimeFormat", ref);
999
- case globalThis.Intl?.ListFormat: return writeIntl(state, val, "ListFormat", ref);
1000
- case globalThis.Intl?.DisplayNames: return writeIntl(state, val, "DisplayNames", ref);
1001
- case globalThis.Intl?.Segmenter: return writeIntl(state, val, "Segmenter", ref);
1002
- case globalThis.Intl?.DurationFormat: return writeIntl(state, val, "DurationFormat", ref);
1003
- case globalThis.Intl?.Locale: return writeIntlLocale(state, val);
1004
- case globalThis.Temporal?.Instant: return writeTemporal(state, val, "Instant");
1005
- case globalThis.Temporal?.Duration: return writeTemporal(state, val, "Duration");
1006
- case globalThis.Temporal?.PlainDate: return writeTemporal(state, val, "PlainDate");
1007
- case globalThis.Temporal?.PlainDateTime: return writeTemporal(state, val, "PlainDateTime");
1008
- case globalThis.Temporal?.PlainMonthDay: return writeTemporal(state, val, "PlainMonthDay");
1009
- case globalThis.Temporal?.PlainTime: return writeTemporal(state, val, "PlainTime");
1010
- case globalThis.Temporal?.PlainYearMonth: return writeTemporal(state, val, "PlainYearMonth");
1011
- case globalThis.Temporal?.ZonedDateTime: return writeTemporal(state, val, "ZonedDateTime");
1012
- }
1013
- throwUnserializable(state, val, ref);
1014
- return false;
1015
- }
1016
- function writePlainObject(state, val, ref) {
1017
- state.buf.push("{");
1018
- writeMaybeIterableProps(state, val, ref);
1019
- state.buf.push("}");
1020
- return true;
1021
- }
1022
- function writeArray(state, val, ref) {
1023
- let sep = "[";
1024
- for (let i = 0; i < val.length; i++) {
1025
- const item = val[i];
1026
- state.buf.push(sep);
1027
- sep = ",";
1028
- if (item === void 0) {
1029
- state.wroteUndefined = true;
1030
- state.buf.push("$");
1031
- } else writeProp(state, item, ref, "" + i);
1032
- }
1033
- if (sep === "[") state.buf.push("[]");
1034
- else state.buf.push("]");
1035
- return true;
1036
- }
1037
- function writeDate(state, val) {
1038
- state.buf.push("new Date(" + +val + ")");
1039
- return true;
1040
- }
1041
- const unsafeRegExpSourceReg = /\\[\s\S]|[<\0\ud800-\udfff]/gu;
1042
- const unsafeRegExpSourceDetect = /[<\0\ud800-\udfff]/u;
1043
- const replaceUnsafeRegExpSourceChar = (match) => {
1044
- const ch = match.length === 3 ? "" : match[match.length - 1];
1045
- if (ch === "<") return "\\x3C";
1046
- if (ch === "\0") return "\\x00";
1047
- const code = ch.charCodeAt(0);
1048
- return code >= 55296 && code <= 57343 ? "\\u" + code.toString(16).padStart(4, "0") : match;
1049
- };
1050
- function writeRegExp(state, val) {
1051
- const { source } = val;
1052
- if (source.includes("<")) state.buf.push(`RegExp(${quote(source, 0)}${val.flags ? ",\"" + val.flags + "\"" : ""})`);
1053
- else state.buf.push("/" + (unsafeRegExpSourceDetect.test(source) ? source.replace(unsafeRegExpSourceReg, replaceUnsafeRegExpSourceChar) : source) + "/" + val.flags);
1054
- return true;
1055
- }
1056
- function writePromise(state, val, ref) {
1057
- const { boundary, channel } = state;
1058
- const pId = nextRefAccess(state);
1059
- const handle = newAsyncHandle(state, ref, pId);
1060
- state.buf.push("(p=>p=new Promise((f,r)=>" + pId + "={f,r(e){p.catch(_=>0);r(e)}}))()");
1061
- val.then((v) => queueAsyncCall(state, boundary, handle, "f", v, channel, pId), (v) => queueAsyncCall(state, boundary, handle, "r", v, channel, pId));
1062
- boundary.startAsync();
1063
- return true;
1064
- }
1065
- function newAsyncHandle(state, parent, id) {
1066
- const handle = {};
1067
- const handleRef = new Reference(parent, null, state.flushId, null, id);
1068
- handleRef.channel = state.channel;
1069
- state.refs.set(handle, handleRef);
1070
- return handle;
1071
- }
1072
- function writeMap(state, val, ref) {
1073
- if (!val.size) {
1074
- state.buf.push("new Map");
1075
- return true;
1076
- }
1077
- const items = [];
1078
- let assignments;
1079
- let needsId;
1080
- let i = 0;
1081
- const entries = val.entries();
1082
- if (val.size < 25) {
1083
- for (const entry of entries) {
1084
- let [itemKey, itemValue] = entry;
1085
- if (itemKey !== val && isAncestorMember(state, ref, itemKey) || itemValue !== val && isAncestorMember(state, ref, itemValue)) {
1086
- deferMembers(state, ref, val, entry, entries);
1087
- if (!i) {
1088
- state.buf.push("new Map");
1089
- return true;
1090
- }
1091
- break;
1092
- }
1093
- if (itemKey === val) {
1094
- itemKey = void 0;
1095
- (assignments ||= []).push("a[" + i + "][0]");
1096
- }
1097
- if (itemValue === val) {
1098
- itemValue = void 0;
1099
- (assignments ||= []).push("a[" + i + "][1]");
1100
- }
1101
- needsId ||= isReusableMember(itemKey) || isReusableMember(itemValue);
1102
- i = items.push(itemValue === void 0 ? itemKey === void 0 ? [] : [itemKey] : [itemKey, itemValue]);
1103
- }
1104
- writeArrayArg(state, ref, items, assignments && "((m,a)=>(" + assignmentsToString(assignments, "m") + ",a.forEach(i=>m.set(i[0],i[1])),m))(new Map,", "new Map(", needsId);
1105
- } else {
1106
- for (const entry of entries) {
1107
- let [itemKey, itemValue] = entry;
1108
- if (itemKey !== val && isAncestorMember(state, ref, itemKey) || itemValue !== val && isAncestorMember(state, ref, itemValue)) {
1109
- deferMembers(state, ref, val, entry, entries);
1110
- if (!i) {
1111
- state.buf.push("new Map");
1112
- return true;
1113
- }
1114
- break;
1115
- }
1116
- if (itemKey === val) {
1117
- itemKey = 0;
1118
- (assignments ||= []).push("a[" + i + "]");
1119
- }
1120
- if (itemValue === val) {
1121
- itemValue = 0;
1122
- (assignments ||= []).push("a[" + (i + 1) + "]");
1123
- }
1124
- needsId ||= isReusableMember(itemKey) || isReusableMember(itemValue);
1125
- i = items.push(itemKey, itemValue);
1126
- }
1127
- writeArrayArg(state, ref, items, assignments && "(a=>a.reduce((m,v,i)=>i%2?m:m.set(v,a[i+1])," + assignmentsToString(assignments, "new Map") + "))(", "(a=>a.reduce((m,v,i)=>i%2?m:m.set(v,a[i+1]),new Map))(", needsId);
1128
- }
1129
- return true;
1130
- }
1131
- function writeSet(state, val, ref) {
1132
- if (!val.size) {
1133
- state.buf.push("new Set");
1134
- return true;
1135
- }
1136
- const items = [];
1137
- let assignments;
1138
- let needsId;
1139
- let i = 0;
1140
- const members = val.values();
1141
- for (let item of members) {
1142
- if (item !== val && isAncestorMember(state, ref, item)) {
1143
- deferMembers(state, ref, val, item, members);
1144
- if (!i) {
1145
- state.buf.push("new Set");
1146
- return true;
1147
- }
1148
- break;
1149
- }
1150
- if (item === val) {
1151
- item = 0;
1152
- (assignments ||= []).push("i[" + i + "]");
1153
- } else needsId ||= isReusableMember(item);
1154
- i = items.push(item);
1155
- }
1156
- writeArrayArg(state, ref, items, assignments && "((s,i)=>(" + assignmentsToString(assignments, "s") + ",i.forEach(i=>s.add(i)),s))(new Set,", "new Set(", needsId);
1157
- return true;
1158
- }
1159
- function isAncestorMember(state, container, member) {
1160
- if (member === null || typeof member !== "object" && typeof member !== "function") return false;
1161
- const ref = state.refs.get(member);
1162
- return ref !== void 0 && isCircular(container, ref);
1163
- }
1164
- function deferMembers(state, ref, collection, first, rest) {
1165
- ensureRefAccess(state, ref);
1166
- ref.deferredMembers = {
1167
- collection,
1168
- first,
1169
- rest
1170
- };
1171
- state.deferredRefs.add(ref);
1172
- }
1173
- function writeArrayArg(state, ref, items, assignsPrefix, plainPrefix, needsId) {
1174
- if (assignsPrefix || needsId) {
1175
- const arrayRef = new Reference(ref, null, state.flushId, null, nextRefAccess(state));
1176
- state.buf.push((assignsPrefix || plainPrefix) + arrayRef.id + "=");
1177
- writeArray(state, items, arrayRef);
1178
- } else {
1179
- state.buf.push(plainPrefix);
1180
- writeArray(state, items, new Reference(ref, null, state.flushId, state.buf.length));
1181
- }
1182
- state.buf.push(")");
1183
- }
1184
- function newArgReference(state, parent, val) {
1185
- for (const key in val) {
1186
- const member = val[key];
1187
- if (isReusableMember(member) && !(typeof member === "string" ? state.strs.has(member) : state.refs.has(member))) {
1188
- const ref = new Reference(parent, null, state.flushId, null, nextRefAccess(state));
1189
- state.buf.push(ref.id + "=");
1190
- return ref;
1191
- }
1192
- }
1193
- return new Reference(parent, null, state.flushId, state.buf.length);
1194
- }
1195
- function isReusableMember(val) {
1196
- switch (typeof val) {
1197
- case "object": return val !== null && val[K_SCOPE_ID] === void 0;
1198
- case "function":
1199
- case "symbol": return true;
1200
- case "string": return val.length > STRING_DEDUP_LENGTH;
1201
- default: return false;
1202
- }
1203
- }
1204
- function canWriteBuffer(state, buffer, ref) {
1205
- if (Object.getPrototypeOf(buffer)?.constructor === ArrayBuffer) return true;
1206
- throwUnserializable(state, buffer, ref, "buffer");
1207
- return false;
1208
- }
1209
- function writeDataView(state, val, ref) {
1210
- const { buffer } = val;
1211
- if (!canWriteBuffer(state, buffer, ref)) return false;
1212
- const needsLength = val.byteOffset + val.byteLength < buffer.byteLength;
1213
- state.buf.push("new DataView(");
1214
- writeProp(state, buffer, ref, "buffer");
1215
- state.buf.push((val.byteOffset || needsLength ? "," + val.byteOffset + (needsLength ? "," + val.byteLength : "") : "") + ")");
1216
- return true;
1217
- }
1218
- function writeArrayBuffer(state, val) {
1219
- let result;
1220
- if (val.byteLength) {
1221
- const view = new Int8Array(val);
1222
- result = hasOnlyZeros(view) ? "new ArrayBuffer(" + val.byteLength + ")" : "new Int8Array(" + typedArrayToInitString(view) + ").buffer";
1223
- } else result = "new ArrayBuffer";
1224
- state.buf.push(result);
1225
- return true;
1226
- }
1227
- function writeTypedArray(state, val, name, ref) {
1228
- if (val.byteOffset || val.byteLength < val.buffer.byteLength || state.refs.has(val.buffer)) {
1229
- if (!canWriteBuffer(state, val.buffer, ref)) return false;
1230
- const needsLength = val.byteOffset + val.byteLength < val.buffer.byteLength;
1231
- state.buf.push("new " + name + "(");
1232
- writeProp(state, val.buffer, ref, "buffer");
1233
- state.buf.push((val.byteOffset || needsLength ? "," + val.byteOffset + (needsLength ? "," + val.length : "") : "") + ")");
1234
- } else {
1235
- state.refs.set(val.buffer, new Reference(ref, "buffer", state.flushId, null));
1236
- state.buf.push("new " + name + (val.length === 0 ? "" : "(" + (hasOnlyZeros(val) ? val.length : typedArrayToInitString(val)) + ")"));
1237
- }
1238
- return true;
1239
- }
1240
- function writeWeakSet(state) {
1241
- state.buf.push("new WeakSet");
1242
- return true;
1243
- }
1244
- function writeWeakMap(state) {
1245
- state.buf.push("new WeakMap");
1246
- return true;
1247
- }
1248
- function writeError(state, val, name, ref) {
1249
- const result = "new " + name + "(" + quote(val.message + "", 0);
1250
- if (val.cause !== void 0) {
1251
- const pos = state.buf.push(result + ",{cause:") - 1;
1252
- if (writeProp(state, val.cause, ref, "cause")) state.buf.push("})");
1253
- else state.buf[pos] = state.buf[pos].slice(0, -8) + ")";
1254
- } else state.buf.push(result + ")");
1255
- return true;
1256
- }
1257
- function writeAggregateError(state, val, ref) {
1258
- state.buf.push("new AggregateError(");
1259
- const inlined = writeProp(state, val.errors, ref, "errors");
1260
- if (!inlined) state.buf.push("[]");
1261
- if (val.message) state.buf.push("," + quote(val.message + "", 0) + ")");
1262
- else state.buf.push(")");
1263
- if (inlined) {
1264
- const errorsRef = state.refs.get(val.errors);
1265
- if (errorsRef?.id) {
1266
- state.deferredRefs.add(errorsRef);
1267
- addAssignment(errorsRef, accessId(state, ref) + toAccess("errors"));
1268
- }
1269
- }
1270
- return true;
1271
- }
1272
- function writeURL(state, val) {
1273
- state.buf.push("new URL(" + quote(val.toString(), 0) + ")");
1274
- return true;
1275
- }
1276
- function writeURLSearchParams(state, val) {
1277
- const str = val.toString();
1278
- if (str) state.buf.push("new URLSearchParams(" + quote(str, 0) + ")");
1279
- else state.buf.push("new URLSearchParams");
1280
- return true;
1281
- }
1282
- function writeHeaders(state, val) {
1283
- const headers = stringEntriesToHeadersInit(val);
1284
- state.buf.push("new Headers" + (headers ? "(" + headers + ")" : ""));
1285
- return true;
1286
- }
1287
- function writeFormData(state, val, ref) {
1288
- let sep = "[";
1289
- let valStr = "";
1290
- for (const [key, value] of val) {
1291
- if (typeof value !== "string") {
1292
- throwUnserializable(state, value, ref, key);
1293
- return false;
1294
- }
1295
- valStr += sep + quote(key, 0) + "," + quote(value, 0);
1296
- sep = ",";
1297
- }
1298
- if (sep === "[") state.buf.push("new FormData");
1299
- else state.buf.push(valStr + "].reduce((f,v,i,a)=>i%2&&f.append(a[i-1],v)||f,new FormData)");
1300
- return true;
1301
- }
1302
- function writeRequest(state, val, ref) {
1303
- let sep = "";
1304
- let bodySerialized = false;
1305
- const hasBody = val.body && !val.bodyUsed && val.duplex === "half";
1306
- state.buf.push("new Request(" + quote(val.url, 0));
1307
- if (hasBody) {
1308
- state.buf.push(",{body:");
1309
- if (writeProp(state, val.body, ref, "body")) {
1310
- state.buf.push(",duplex:\"half\"");
1311
- sep = ",";
1312
- bodySerialized = true;
1313
- } else state.buf.pop();
1314
- }
1315
- let options = "";
1316
- if (val.cache !== "default") {
1317
- options += sep + "cache:" + quote(val.cache, 0);
1318
- sep = ",";
1319
- }
1320
- if (val.credentials !== "same-origin") {
1321
- options += sep + "credentials:" + quote(val.credentials, 0);
1322
- sep = ",";
1323
- }
1324
- const seenHeaders = state.refs.get(val.headers);
1325
- if (seenHeaders) {
1326
- options += sep + "headers:" + ensureRefAccess(state, seenHeaders);
1327
- sep = ",";
1328
- } else {
1329
- state.refs.set(val.headers, new Reference(ref, "headers", state.flushId, null));
1330
- const headers = stringEntriesToHeadersInit(val.headers);
1331
- if (headers) {
1332
- options += sep + "headers:" + headers;
1333
- sep = ",";
1334
- }
1335
- }
1336
- if (val.integrity) {
1337
- options += sep + "integrity:" + quote(val.integrity, 0);
1338
- sep = ",";
1339
- }
1340
- if (val.keepalive) {
1341
- options += sep + "keepalive:true";
1342
- sep = ",";
1343
- }
1344
- if (val.method !== "GET") {
1345
- options += sep + "method:" + quote(val.method, 0);
1346
- sep = ",";
1347
- }
1348
- if (val.mode !== "cors") {
1349
- options += sep + "mode:" + quote(val.mode, 0);
1350
- sep = ",";
1351
- }
1352
- if (val.redirect !== "follow") {
1353
- options += sep + "redirect:" + quote(val.redirect, 0);
1354
- sep = ",";
1355
- }
1356
- if (val.referrer !== "about:client") {
1357
- options += sep + "referrer:" + quote(val.referrer, 0);
1358
- sep = ",";
1359
- }
1360
- if (val.referrerPolicy) options += sep + "referrerPolicy:" + quote(val.referrerPolicy, 0);
1361
- state.buf.push(bodySerialized ? options + "})" : options ? ",{" + options + "})" : ")");
1362
- return true;
1363
- }
1364
- function writeResponse(state, val, ref) {
1365
- let sep = "";
1366
- let options = "";
1367
- if (val.status !== 200) {
1368
- options += "status:" + val.status;
1369
- sep = ",";
1370
- }
1371
- if (val.statusText) {
1372
- options += sep + "statusText:" + quote(val.statusText, 0);
1373
- sep = ",";
1374
- }
1375
- const seenHeaders = state.refs.get(val.headers);
1376
- if (seenHeaders) options += sep + "headers:" + ensureRefAccess(state, seenHeaders);
1377
- else {
1378
- state.refs.set(val.headers, new Reference(ref, "headers", state.flushId, null));
1379
- const headers = stringEntriesToHeadersInit(val.headers);
1380
- if (headers) options += sep + "headers:" + headers;
1381
- }
1382
- if (!val.body || val.bodyUsed) state.buf.push("new Response" + (options ? "(null,{" + options + "})" : ""));
1383
- else {
1384
- state.buf.push("new Response(");
1385
- state.buf.push((writeProp(state, val.body, ref, "body") ? "" : "null") + (options ? ",{" + options + "})" : ")"));
1386
- }
1387
- return true;
1388
- }
1389
- function writeIntl(state, val, name, ref) {
1390
- const { locale, ...options } = val.resolvedOptions();
1391
- state.buf.push("new Intl." + name + "(" + quote(locale, 0) + ",");
1392
- const optionsRef = newArgReference(state, ref, options);
1393
- state.buf.push("{");
1394
- writeObjectProps(state, options, optionsRef);
1395
- state.buf.push("})");
1396
- return true;
1397
- }
1398
- function writeIntlLocale(state, val) {
1399
- state.buf.push("new Intl.Locale(" + quote(val.toString(), 0) + ")");
1400
- return true;
1401
- }
1402
- function writeTemporal(state, val, name) {
1403
- state.buf.push("Temporal." + name + ".from(" + quote(val.toString(), 0) + ")");
1404
- return true;
1405
- }
1406
- function writeReadableStream(state, val, ref) {
1407
- if (val.locked) {
1408
- throwUnserializable(state, val, ref, "", "The ReadableStream is locked by a reader on the server; to also send it to the browser, `tee()` it (or `clone()` its `Request`/`Response`) before reading.");
1409
- return false;
1410
- }
1411
- const { boundary, channel } = state;
1412
- const reader = val.getReader();
1413
- const iterId = nextRefAccess(state);
1414
- const handle = newAsyncHandle(state, ref, iterId);
1415
- const onFulfilled = ({ value, done }) => {
1416
- if (done) queueAsyncCall(state, boundary, handle, "r", value, channel);
1417
- else if (!boundary.aborted) {
1418
- reader.read().then(onFulfilled, onRejected);
1419
- boundary.startAsync();
1420
- queueAsyncCall(state, boundary, handle, "f", value, channel);
1421
- }
1422
- };
1423
- const onRejected = (reason) => {
1424
- queueAsyncCall(state, boundary, handle, "j", reason, channel);
1425
- };
1426
- state.buf.push("new ReadableStream({start(c){(async(_,f,v,l,i,p=a=>l=new Promise((r,j)=>{f=_.r=r;_.j=j}),a=((_.f=v=>{f(v);a.push(p())}),[p()]))=>{for(i of a)v=await i,i==l?c.close():c.enqueue(v)})(" + iterId + "={}).catch(e=>c.error(e))}})");
1427
- reader.read().then(onFulfilled, onRejected);
1428
- boundary.startAsync();
1429
- return true;
1430
- }
1431
- function writeGenerator(state, iter, ref) {
1432
- if (iter[kTouchedIterator]) {
1433
- state.buf.push("(function*(){}())");
1434
- return true;
1435
- }
1436
- const yields = [];
1437
- let returnValue;
1438
- let needsId;
1439
- while (true) {
1440
- const { value, done } = iter.next();
1441
- if (done) {
1442
- returnValue = value;
1443
- break;
1444
- }
1445
- needsId ||= isReusableMember(value);
1446
- yields.push(value);
1447
- }
1448
- if (returnValue === void 0 && !yields.length) {
1449
- state.buf.push("(function*(){})()");
1450
- return true;
1451
- }
1452
- const heldReturn = returnValue !== void 0 && isAncestorMember(state, ref, returnValue);
1453
- state.buf.push(returnValue === void 0 ? "(function*(a){yield*a})(" : heldReturn ? "(function*(a,r){yield*a;return r.v})(" : "(function*(a,r){yield*a;return r})(");
1454
- if (needsId) {
1455
- const arrayRef = new Reference(ref, null, state.flushId, null, nextRefAccess(state));
1456
- state.buf.push(arrayRef.id + "=");
1457
- writeArray(state, yields, arrayRef);
1458
- } else writeArray(state, yields, new Reference(ref, null, state.flushId, state.buf.length));
1459
- if (heldReturn) {
1460
- const holder = new Reference(ref, null, state.flushId, null, nextRefAccess(state));
1461
- state.buf.push("," + holder.id + "={}");
1462
- writeProp(state, returnValue, holder, "v");
1463
- } else if (returnValue !== void 0) {
1464
- state.buf.push(",");
1465
- if (writeProp(state, returnValue, ref, "") && isReusableMember(returnValue)) {
1466
- const retRef = typeof returnValue === "string" ? state.strs.get(returnValue) : state.refs.get(returnValue);
1467
- if (retRef) ensureRefAccess(state, retRef);
1468
- }
1469
- }
1470
- state.buf.push(")");
1471
- return true;
1472
- }
1473
- function writeAsyncGenerator(state, iter, ref) {
1474
- if (iter[kTouchedIterator]) {
1475
- state.buf.push("(async function*(){}())");
1476
- return true;
1477
- }
1478
- const { boundary, channel } = state;
1479
- const iterId = nextRefAccess(state);
1480
- const handle = newAsyncHandle(state, ref, iterId);
1481
- const onFulfilled = ({ value, done }) => {
1482
- if (done) queueAsyncCall(state, boundary, handle, "r", value, channel);
1483
- else if (!boundary.aborted) {
1484
- iter.next().then(onFulfilled, onRejected);
1485
- boundary.startAsync();
1486
- queueAsyncCall(state, boundary, handle, "f", value, channel);
1487
- }
1488
- };
1489
- const onRejected = (reason) => {
1490
- queueAsyncCall(state, boundary, handle, "j", reason, channel);
1491
- };
1492
- state.buf.push("(async function*(_,f,v,l,i,p=a=>l=new Promise((r,j)=>{f=_.r=r;_.j=j}),a=((_.f=v=>{f(v);a.push(p())}),[p()])){for(i of a)v=await i,i!=l&&(yield v);return v})(" + iterId + "={})");
1493
- iter.next().then(onFulfilled, onRejected);
1494
- boundary.startAsync();
1495
- return true;
1496
- }
1497
- function writeNullObject(state, val, ref) {
1498
- state.buf.push("{");
1499
- state.buf.push(writeMaybeIterableProps(state, val, ref) + "__proto__:null}");
1500
- return true;
1501
- }
1502
- function writeObjectProps(state, val, ref) {
1503
- let sep = "";
1504
- for (const key in val) if (hasOwnProperty.call(val, key)) {
1505
- const escapedKey = toObjectKey(key);
1506
- state.buf.push(sep + escapedKey + ":");
1507
- if (writeProp(state, val[key], ref, escapedKey)) sep = ",";
1508
- else state.buf.pop();
1509
- }
1510
- return sep;
1511
- }
1512
- function writeMaybeIterableProps(state, val, ref) {
1513
- let sep = writeObjectProps(state, val, ref);
1514
- if (hasSymbolIterator(val)) {
1515
- let yieldSelf = "";
1516
- const iterArr = [];
1517
- for (const item of val) if (item === val && !(yieldSelf || iterArr.length)) yieldSelf = "yield this;";
1518
- else iterArr.push(item);
1519
- if (iterArr.length) {
1520
- const iterRef = new Reference(ref, null, state.flushId, null, nextRefAccess(state));
1521
- state.buf.push(sep + "*[(" + iterRef.id + "=");
1522
- writeArray(state, iterArr, iterRef);
1523
- state.buf.push(",Symbol.iterator)](){" + yieldSelf + "yield*" + iterRef.id + "}");
1524
- } else state.buf.push(sep + "*[Symbol.iterator](){" + yieldSelf.slice(0, -1) + "}");
1525
- sep = ",";
1526
- }
1527
- return sep;
1528
- }
1529
- function queueAsyncCall(state, boundary, handle, method, value, channel, valueId = null) {
1530
- if (boundary.aborted) return;
1531
- (channel?.readyId ? state.queuedReadyCalls : state.queuedCalls).push({
1532
- method,
1533
- value,
1534
- object: handle,
1535
- channel,
1536
- valueId
1537
- });
1538
- boundary.endAsync();
1539
- }
1540
- function throwUnserializable(state, cause, ref = null, accessor = "", hint = "Values referenced in the browser must be serializable.") {
1541
- if (cause !== void 0) {
1542
- let message = "Unable to serialize";
1543
- let access = "";
1544
- while (ref) {
1545
- const { accessor } = ref;
1546
- const debug = ref.parent?.debug;
1547
- if (accessor && debug) {
1548
- const rawAccessor = fromObjectKey(accessor);
1549
- const varLoc = debug.vars?.[rawAccessor];
1550
- const slotName = debug.slots?.[rawAccessor];
1551
- let debugAccess = varLoc ? rawAccessor : void 0;
1552
- let debugLoc = debug.loc;
1553
- if (varLoc) {
1554
- if (Array.isArray(varLoc)) {
1555
- debugAccess = varLoc[0];
1556
- if (varLoc[1]) debugLoc = varLoc[1];
1557
- } else debugLoc = varLoc;
1558
- }
1559
- let display;
1560
- if (debugAccess !== void 0) display = slotName && debugAccess.startsWith("...") ? `\`${slotName}\` from \`${debugAccess}\`` : JSON.stringify(debugAccess);
1561
- else display = describeAccessor(rawAccessor, slotName) ?? JSON.stringify(rawAccessor);
1562
- message += ` ${display} in ${debug.file}`;
1563
- if (debugLoc) message += `:${debugLoc}`;
1564
- break;
1565
- }
1566
- if (accessor) access = toAccess(accessor) + access;
1567
- ref = ref.parent;
1568
- }
1569
- if (accessor) access = toAccess(accessor) + access;
1570
- if (access[0] === ".") access = access.slice(1);
1571
- if (access) message += ` (reading ${access})`;
1572
- message += ". " + hint;
1573
- const err = new TypeError(message, { cause });
1574
- err.stack = void 0;
1575
- abortRender(state.boundary, err);
1576
- }
1577
- }
1578
- const accessorPrefixDescriptions = {
1579
- BranchScopes: "the branch scopes",
1580
- ClosureScopes: "the closure scopes",
1581
- ClosureSignalIndex: "the closure signal index",
1582
- ConditionalRenderer: "the conditional renderer",
1583
- ControlledObserver: "the controlled observer",
1584
- ControlledHandler: "the change handler",
1585
- ControlledType: "the controlled type",
1586
- ControlledValue: "the controlled value",
1587
- DynamicHTMLLastChild: "the dynamic html",
1588
- DynamicHTMLValue: "the dynamic html value",
1589
- EventAttributes: "the event handlers",
1590
- IdFallback: "the generated id",
1591
- KeyedScopes: "the keyed scopes",
1592
- Lifecycle: "the lifecycle handlers",
1593
- Promise: "the pending promise",
1594
- TagVariableChange: "the tag variable change handler",
1595
- TryBranch: "the try branch"
1596
- };
1597
- function describeAccessor(accessor, slotName) {
1598
- const sep = accessor.indexOf(":");
1599
- if (~sep) {
1600
- const description = slotName === void 0 ? accessorPrefixDescriptions[accessor.slice(0, sep)] : `the \`${slotName}\` handler`;
1601
- if (description) {
1602
- const node = /^#([a-z-]+)\//i.exec(accessor.slice(sep + 1));
1603
- return node ? `${description} of \`<${node[1]}>\`` : description;
1604
- }
1605
- }
1606
- }
1607
- function fromObjectKey(key) {
1608
- try {
1609
- if (key[0] === "\"") return JSON.parse(key.replace(/\\x/g, "\\u00"));
1610
- if (key[0] === "[") return JSON.parse(key.slice(1, -1));
1611
- } catch {}
1612
- return key;
1613
- }
1614
- function trackChannel(state, ref) {
1615
- const refReadyId = ref.channel?.readyId;
1616
- if (!refReadyId || refReadyId === state.channel?.readyId) return true;
1617
- let cur = state.channel?.parent;
1618
- while (cur) {
1619
- if (cur.readyId === refReadyId) {
1620
- (state.channelDeps ||= /* @__PURE__ */ new Set()).add(refReadyId);
1621
- return true;
1622
- }
1623
- cur = cur.parent;
1624
- }
1625
- return false;
1626
- }
1627
- function isAncestorChannelRef(state, ref) {
1628
- return ref.channel?.readyId !== state.channel?.readyId;
1629
- }
1630
- function abortUnreachableChannel(state, val) {
1631
- const err = new TypeError("Unable to serialize a value shared between independently lazy loaded content. Values shared this way must also be serialized by content that is not lazily loaded, or by a common parent.", { cause: val });
1632
- err.stack = void 0;
1633
- abortRender(state.boundary, err);
1634
- }
1635
- function abortRender(boundary, err) {
1636
- while (boundary.parent) boundary = boundary.parent;
1637
- boundary.abort(err);
1638
- }
1639
- function isCircular(parent, ref) {
1640
- let cur = parent;
1641
- while (cur) {
1642
- if (cur === ref) return true;
1643
- cur = cur.parent;
1644
- }
1645
- return false;
1646
- }
1647
- function toObjectKey(name) {
1648
- if (name === "") return "\"\"";
1649
- if (name === "__proto__") return "[\"__proto__\"]";
1650
- const len = name.length;
1651
- const c0 = name.charCodeAt(0);
1652
- if (c0 >= 48 && c0 <= 57) {
1653
- if (c0 === 48) {
1654
- if (len !== 1) return quote(name, 1);
1655
- } else {
1656
- for (let i = 1; i < len; i++) {
1657
- const c = name.charCodeAt(i);
1658
- if (c < 48 || c > 57) return quote(name, i);
1659
- }
1660
- if (len > 15 && "" + +name !== name) return quote(name, 0);
1661
- }
1662
- } else if (c0 >= 97 && c0 <= 122 || c0 >= 65 && c0 <= 90 || c0 === 95 || c0 === 36) for (let i = 1; i < len; i++) {
1663
- const c = name.charCodeAt(i);
1664
- if (!(c >= 97 && c <= 122 || c >= 65 && c <= 90 || c >= 48 && c <= 57 || c === 95 || c === 36)) return quote(name, i);
1665
- }
1666
- else return quote(name, 0);
1667
- return name;
1668
- }
1669
- function toAccess(accessor) {
1670
- const start = accessor[0];
1671
- return start === "[" ? accessor : start === "\"" || start >= "0" && start <= "9" ? "[" + accessor + "]" : "." + accessor;
1672
- }
1673
- const unsafeQuoteReg = /["\\<\n\r\u2028\u2029\0\ud800-\udfff]/u;
1674
- function quote(str, startPos) {
1675
- if (!unsafeQuoteReg.test(str)) return "\"" + str + "\"";
1676
- let result = "";
1677
- let lastPos = 0;
1678
- for (let i = startPos; i < str.length; i++) {
1679
- let replacement;
1680
- const code = str.charCodeAt(i);
1681
- switch (code) {
1682
- case 34:
1683
- replacement = "\\\"";
1684
- break;
1685
- case 92:
1686
- replacement = "\\\\";
1687
- break;
1688
- case 60:
1689
- replacement = "\\x3C";
1690
- break;
1691
- case 10:
1692
- replacement = "\\n";
1693
- break;
1694
- case 13:
1695
- replacement = "\\r";
1696
- break;
1697
- case 8232:
1698
- replacement = "\\u2028";
1699
- break;
1700
- case 8233:
1701
- replacement = "\\u2029";
1702
- break;
1703
- case 0:
1704
- replacement = "\\x00";
1705
- break;
1706
- default:
1707
- if (code < 55296 || code > 57343) continue;
1708
- if (code < 56320) {
1709
- const next = str.charCodeAt(i + 1);
1710
- if (next >= 56320 && next <= 57343) {
1711
- i++;
1712
- continue;
1713
- }
1714
- }
1715
- replacement = "\\u" + code.toString(16);
1716
- }
1717
- result += str.slice(lastPos, i) + replacement;
1718
- lastPos = i + 1;
1719
- }
1720
- return "\"" + (lastPos === startPos ? str : result + str.slice(lastPos)) + "\"";
1721
- }
1722
- function writeRef(state, ref) {
1723
- if (ref.id === null && ref.scopeId === void 0 && ref.path === null && (ref.pos === null || ref.flushId !== state.flushId) && !isAncestorChannelRef(state, ref)) {
1724
- ref.path = accessPath(state, ref);
1725
- ref.pos = state.buf.length;
1726
- ref.flushId = state.flushId;
1727
- state.buf.push(ref.path);
1728
- } else state.buf.push(ensureRefAccess(state, ref));
1729
- }
1730
- function ensureRefAccess(state, ref) {
1731
- if (ref.scopeId !== void 0) {
1732
- trackChannel(state, ref);
1733
- return "_(" + ref.scopeId + ")";
1734
- }
1735
- if (ref.id) {
1736
- trackChannel(state, ref);
1737
- return ref.id;
1738
- }
1739
- return claimRefAccess(state, ref);
1740
- }
1741
- function accessId(state, ref) {
1742
- const id = ensureRefAccess(state, ref);
1743
- return id === ref.id || ref.scopeId !== void 0 ? id : "(" + id + ")";
1744
- }
1745
- function claimRefAccess(state, ref) {
1746
- const { pos } = ref;
1747
- if (pos !== null && ref.flushId === state.flushId) {
1748
- ref.id = nextRefAccess(state);
1749
- if (pos === 0) state.buf[0] = ref.id + "=" + state.buf[0];
1750
- else state.buf[pos - 1] += ref.id + "=";
1751
- return ref.id;
1752
- }
1753
- if (isAncestorChannelRef(state, ref)) return ref.path || accessPath(state, ref);
1754
- ref.id = nextRefAccess(state);
1755
- return ref.id + "=" + (ref.path || accessPath(state, ref));
1756
- }
1757
- function accessPath(state, ref) {
1758
- let cur = ref;
1759
- let accessPrevValue = "";
1760
- do {
1761
- if (cur.accessor === null) throw new Error("Unable to serialize a reused value: no access path reaches where it was first written, and it has no id.");
1762
- accessPrevValue = toAccess(cur.accessor) + accessPrevValue;
1763
- const parent = cur.parent;
1764
- if (parent.id) {
1765
- trackChannel(state, parent);
1766
- return parent.id + accessPrevValue;
1767
- }
1768
- if (parent.flushId === state.flushId || parent.scopeId !== void 0) return accessId(state, parent) + accessPrevValue;
1769
- cur = parent;
1770
- } while (cur);
1771
- return accessPrevValue;
1772
- }
1773
- function assignmentsToString(assignments, value) {
1774
- if (assignments.length > 100) return "($=>(" + assignments.join("=$,") + "=$))(" + value + ")";
1775
- return assignments.join("=") + "=" + value;
1776
- }
1777
- function addAssignment(ref, assign) {
1778
- if (ref.assignments) ref.assignments.push(assign);
1779
- else ref.assignments = [assign];
1780
- }
1781
- function nextRefAccess(state) {
1782
- return "_." + nextId(state);
1783
- }
1784
- function nextId(state) {
1785
- const c = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_0123456789";
1786
- let n = state.ids++;
1787
- let r = c[n % 53];
1788
- for (n = n / 53 | 0; n; n >>>= 6) r += c[n & 63];
1789
- return r === "name" ? nextId(state) : r;
1790
- }
1791
- function hasSymbolIterator(value) {
1792
- return Symbol.iterator in value;
1793
- }
1794
- function stringEntriesToHeadersInit(entries) {
1795
- const list = [...entries];
1796
- if (!list.length) return "";
1797
- let duplicate = false;
1798
- const seen = /* @__PURE__ */ new Set();
1799
- for (const [key] of list) {
1800
- if (seen.has(key)) {
1801
- duplicate = true;
1802
- break;
1803
- }
1804
- seen.add(key);
1805
- }
1806
- let result = "";
1807
- let sep = "";
1808
- for (const [key, value] of list) {
1809
- result += duplicate ? sep + "[" + quote(key, 0) + "," + quote(value, 0) + "]" : sep + toObjectKey(key) + ":" + quote(value, 0);
1810
- sep = ",";
1811
- }
1812
- return duplicate ? "[" + result + "]" : "{" + result + "}";
1813
- }
1814
- function typedArrayToInitString(view) {
1815
- const suffix = typeof view[0] === "bigint" ? "n" : "";
1816
- let result = "[";
1817
- let sep = "";
1818
- for (let i = 0; i < view.length; i++) {
1819
- result += sep + view[i] + suffix;
1820
- sep = ",";
1821
- }
1822
- result += "]";
1823
- return result;
1824
- }
1825
- function hasOnlyZeros(typedArray) {
1826
- const zero = typeof typedArray[0] === "bigint" ? 0n : 0;
1827
- for (let i = 0; i < typedArray.length; i++) if (typedArray[i] !== zero) return false;
1828
- return true;
1829
- }
1830
- function patchIteratorNext(proto) {
1831
- if (proto.next[kTouchedIterator]) return;
1832
- const { next } = proto;
1833
- proto.next = function(value) {
1834
- this[kTouchedIterator] = 1;
1835
- return next.call(this, value);
1836
- };
1837
- proto.next[kTouchedIterator] = true;
1838
- }
1839
- // src/html/attrs.ts
1840
- function _attr_class(value) {
1841
- return stringAttr("class", toDelimitedString(value, " ", stringifyClassEntry));
1842
- }
1843
- function _attr_style(value) {
1844
- return stringAttr("style", toDelimitedString(value, ";", stringifyStyleEntry));
1845
- }
1846
- function _attr_option_value(value) {
1847
- const valueAttr = _attr("value", value);
1848
- const selectedValue = getContext(kSelectedValue);
1849
- if (selectedValue !== void 0 && normalizedValueMatches(selectedValue, value)) {
1850
- getContext(kSelectedValueMatched)?.add(normalizeStrAttrValue(value));
1851
- return valueAttr + " selected";
1852
- }
1853
- return valueAttr;
1854
- }
1855
- const kSelectedValue = Symbol("selectedValue");
1856
- const kSelectedValueMatched = Symbol("selectedValueMatched");
1857
- function _attr_select_value(scopeId, nodeAccessor, value, valueChange, content, serializeType) {
1858
- if (valueChange) writeControlledScope(3, scopeId, nodeAccessor, void 0, valueChange, serializeType);
1859
- if (content) {
1860
- const selectedValue = value ?? "";
1861
- if (valueChange) {
1862
- const matched = /* @__PURE__ */ new Set();
1863
- withContext(kSelectedValue, selectedValue, () => withContext(kSelectedValueMatched, matched, content));
1864
- if ((Array.isArray(value) ? value : [value]).some((v) => {
1865
- const str = normalizeStrAttrValue(v);
1866
- return str !== "" && !matched.has(str);
1867
- })) console.error("A controlled `<select>`'s `value` has no matching `<option>`:", value);
1868
- } else withContext(kSelectedValue, selectedValue, content);
1869
- }
1870
- }
1871
- function _attrs_select_value(scopeId, nodeAccessor, data, content) {
1872
- if (data && ("value" in data || data.valueChange)) _attr_select_value(scopeId, nodeAccessor, data.value, data.valueChange, content, 1);
1873
- else content();
1874
- }
1875
- function _attr_textarea_value(scopeId, nodeAccessor, value, valueChange, serializeType) {
1876
- if (valueChange) writeControlledScope(2, scopeId, nodeAccessor, void 0, valueChange, serializeType);
1877
- return _textarea_value(value);
1878
- }
1879
- function _attrs_textarea_value(scopeId, nodeAccessor, data) {
1880
- return _attr_textarea_value(scopeId, nodeAccessor, data?.value, data?.valueChange, 1);
1881
- }
1882
- function _textarea_value(value) {
1883
- const escaped = _escape(normalizeStrAttrValue(value));
1884
- return escaped[0] === "\n" ? "\n" + escaped : escaped;
1885
- }
1886
- function _attr_input_value(scopeId, nodeAccessor, value, valueChange, serializeType) {
1887
- if (valueChange) writeControlledScope(2, scopeId, nodeAccessor, void 0, valueChange, serializeType);
1888
- return _attr("value", value);
1889
- }
1890
- function _attr_input_checked(scopeId, nodeAccessor, checked, checkedChange, serializeType) {
1891
- if (checkedChange) writeControlledScope(0, scopeId, nodeAccessor, void 0, checkedChange, serializeType);
1892
- return isNotNullishOrFalse(checked) ? " checked" : "";
1893
- }
1894
- function _attr_input_checkedValue(scopeId, nodeAccessor, checkedValue, checkedValueChange, value, serializeType) {
1895
- const valueAttr = _attr("value", value);
1896
- if (checkedValueChange) writeControlledScope(1, scopeId, nodeAccessor, getCheckedValueRef(checkedValue), checkedValueChange, serializeType);
1897
- return normalizedValueMatches(checkedValue, value) ? valueAttr + " checked" : valueAttr;
1898
- }
1899
- const checkedValuesRefs = /* @__PURE__ */ new WeakMap();
1900
- function getCheckedValueRef(checkedValue) {
1901
- if (Array.isArray(checkedValue)) {
1902
- let ref = checkedValuesRefs.get(checkedValue);
1903
- if (!ref) {
1904
- ref = [];
1905
- checkedValuesRefs.set(checkedValue, ref);
1906
- }
1907
- return ref;
1908
- }
1909
- }
1910
- function _attr_details_or_dialog_open(scopeId, nodeAccessor, open, openChange, serializeType) {
1911
- const normalizedOpen = isNotNullishOrFalse(open);
1912
- if (openChange) writeControlledScope(4, scopeId, nodeAccessor, normalizedOpen || void 0, openChange, serializeType);
1913
- return normalizedOpen ? " open" : "";
1914
- }
1915
- function _attr_nonce() {
1916
- return getChunk().boundary.state.nonceAttr;
1917
- }
1918
- function _style_html(decls) {
1919
- const id = _id();
1920
- return `<style${_attr_nonce()} class=${id}>.${id}~*{${decls}}</style>`;
1921
- }
1922
- function _attr(name, value) {
1923
- return isNullishOrFalse(value) ? "" : stringifyAttr(name, value);
1924
- }
1925
- function _attr_and(name, value, attr) {
1926
- return value ? attr : _attr(name, value);
1927
- }
1928
- function _attr_or(name, value, attr) {
1929
- return value ? _attr(name, value) : attr;
1930
- }
1931
- function _attr_nullish(name, value, attr) {
1932
- return value == null ? attr : _attr(name, value);
1933
- }
1934
- function _attrs(data, nodeAccessor, scopeId, tagName) {
1935
- let result = "";
1936
- let skip = /[\s/>"'=]/;
1937
- let events;
1938
- switch (data && tagName) {
1939
- case "input":
1940
- assertExclusiveAttrs(data);
1941
- if (data.checkedChange) {
1942
- result += _attr_input_checked(scopeId, nodeAccessor, data.checked, data.checkedChange, 1);
1943
- skip = /^checked(?:Value)?(?:Change)?$|[\s/>"'=]/;
1944
- } else if ("checkedValue" in data || data.checkedValueChange) {
1945
- result += _attr_input_checkedValue(scopeId, nodeAccessor, data.checkedValue, data.checkedValueChange, data.value, 1);
1946
- skip = /^(?:value|checked(?:Value)?)(?:Change)?$|[\s/>"'=]/;
1947
- } else if (data.valueChange) {
1948
- assertNoValueBindingOnCheckable(data.type, data.valueChange);
1949
- result += _attr_input_value(scopeId, nodeAccessor, data.value, data.valueChange, 1);
1950
- skip = /^value(?:Change)?$|[\s/>"'=]/;
1951
- }
1952
- break;
1953
- case "select":
1954
- case "textarea":
1955
- if ("value" in data || data.valueChange) skip = /^value(?:Change)?$|[\s/>"'=]/;
1956
- break;
1957
- case "option":
1958
- if ("value" in data) {
1959
- result += _attr_option_value(data.value);
1960
- skip = /^value$|[\s/>"'=]/;
1961
- }
1962
- break;
1963
- case "details":
1964
- case "dialog": if (data.openChange) {
1965
- result += _attr_details_or_dialog_open(scopeId, nodeAccessor, data.open, data.openChange, 1);
1966
- skip = /^open(?:Change)?$|[\s/>"'=]/;
1967
- }
1968
- }
1969
- for (const name in data) {
1970
- const value = data[name];
1971
- switch (name) {
1972
- case "class":
1973
- result += _attr_class(value);
1974
- break;
1975
- case "style":
1976
- result += _attr_style(value);
1977
- break;
1978
- default:
1979
- if (name) assertValidAttrName(name);
1980
- if (name && !(isNullishOrFalse(value) || skip.test(name) || name === "content" && tagName !== "meta")) {
1981
- if (isEventHandler(name)) {
1982
- if (!events) {
1983
- events = {};
1984
- writeScope(scopeId, { [EventAttributes + nodeAccessor]: events });
1985
- }
1986
- events[getEventType(name)] = value;
1987
- } else result += stringifyAttr(name, value);
1988
- }
1989
- }
1990
- }
1991
- return result;
1992
- }
1993
- function _attrs_content(data, nodeAccessor, scopeId, tagName, markerGuard) {
1994
- _html(`${_attrs(data, nodeAccessor, scopeId, tagName)}>`);
1995
- _attr_content(nodeAccessor, scopeId, data?.content, markerGuard);
1996
- }
1997
- function _attrs_partial(data, skip, nodeAccessor, scopeId, tagName) {
1998
- const partial = {};
1999
- for (const name in data) {
2000
- const key = isEventHandler(name) ? `on-${getEventType(name)}` : name;
2001
- if (!skip[key]) partial[key] = data[name];
2002
- }
2003
- assertExclusiveAttrs({
2004
- ...data,
2005
- ...skip
2006
- });
2007
- return _attrs(partial, nodeAccessor, scopeId, tagName);
2008
- }
2009
- function _attrs_partial_content(data, skip, nodeAccessor, scopeId, tagName, markerGuard) {
2010
- _html(`${_attrs_partial(data, skip, nodeAccessor, scopeId, tagName)}>`);
2011
- _attr_content(nodeAccessor, scopeId, data?.content, markerGuard);
2012
- }
2013
- function writeControlledScope(type, scopeId, nodeAccessor, value, valueChange, serializeType) {
2014
- var handlerName = [
2015
- "checkedChange",
2016
- "checkedValueChange",
2017
- "valueChange",
2018
- "valueChange",
2019
- "openChange"
2020
- ][type];
2021
- assertHandlerIsFunction(handlerName, valueChange);
2022
- setDebugSlotName(writeScope(scopeId, serializeType ? {
2023
- [ControlledType + nodeAccessor]: type,
2024
- [ControlledValue + nodeAccessor]: value,
2025
- [ControlledHandler + nodeAccessor]: valueChange
2026
- } : {
2027
- [ControlledValue + nodeAccessor]: value,
2028
- [ControlledHandler + nodeAccessor]: valueChange
2029
- }), ControlledHandler + nodeAccessor, handlerName);
2030
- }
2031
- function stringAttr(name, value) {
2032
- return value && " " + name + attrAssignment(value);
2033
- }
2034
- function stringifyAttr(name, value) {
2035
- assertValidAttrValue(name, value);
2036
- switch (typeof value) {
2037
- case "string": return " " + name + attrAssignment(value);
2038
- case "boolean": return " " + name;
2039
- case "number": return " " + name + "=" + value;
2040
- }
2041
- return " " + name + attrAssignment(value + "");
2042
- }
2043
- const singleQuoteAttrReplacements = /['\r]|&(?=[#a-zA-Z])/g;
2044
- const doubleQuoteAttrReplacements = /["\r]|&(?=[#a-zA-Z])/g;
2045
- const needsQuotedAttr = /["'>\s]|&[#a-zA-Z]|\/$/g;
2046
- function attrAssignment(value) {
2047
- return value ? needsQuotedAttr.test(value) ? value[needsQuotedAttr.lastIndex - 1] === (needsQuotedAttr.lastIndex = 0, "\"") ? "='" + escapeSingleQuotedAttrValue(value) + "'" : "=\"" + escapeDoubleQuotedAttrValue(value) + "\"" : "=" + value : "";
2048
- }
2049
- function escapeSingleQuotedAttrValue(value) {
2050
- return singleQuoteAttrReplacements.test(value) ? value.replace(singleQuoteAttrReplacements, replaceUnsafeSingleQuoteAttrChar) : value;
2051
- }
2052
- function replaceUnsafeSingleQuoteAttrChar(match) {
2053
- return match === "'" ? "&#39;" : match === "\r" ? "&#13;" : "&amp;";
2054
- }
2055
- function escapeDoubleQuotedAttrValue(value) {
2056
- return doubleQuoteAttrReplacements.test(value) ? value.replace(doubleQuoteAttrReplacements, replaceUnsafeDoubleQuoteAttrChar) : value;
2057
- }
2058
- function replaceUnsafeDoubleQuoteAttrChar(match) {
2059
- return match === "\"" ? "&#34;" : match === "\r" ? "&#13;" : "&amp;";
2060
- }
2061
- function normalizedValueMatches(a, b) {
2062
- const value = normalizeStrAttrValue(b);
2063
- if (Array.isArray(a)) {
2064
- for (const item of a) if (normalizeStrAttrValue(item) === value) return true;
2065
- } else if (normalizeStrAttrValue(a) === value) return true;
2066
- return false;
2067
- }
2068
- function normalizeStrAttrValue(value) {
2069
- return isNotNullishOrFalse(value) && value !== true ? value + "" : "";
2070
- }
2071
- // src/html/inlined-runtimes.debug.ts
2072
- const WALKER_RUNTIME_CODE = `((runtimeId) => (self[runtimeId] ||= (
2073
- renderId,
2074
- prefix = runtimeId + renderId,
2075
- prefixLen = prefix.length,
2076
- lookup = {},
2077
- visits = [],
2078
- doc = document,
2079
- walker = doc.createTreeWalker(
2080
- doc,
2081
- 129 /* NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_ELEMENT */,
2082
- ),
2083
- ) =>
2084
- doc = (self[runtimeId][renderId] = {
2085
- i: prefix,
2086
- l: lookup,
2087
- v: visits,
2088
- x() {},
2089
- w(node, op, id) {
2090
- while ((node = walker.nextNode())) {
2091
- // Only reorder markers ("#", "!") are ever looked up, so only they are
2092
- // kept: the lookup lives as long as the page, and every node marker
2093
- // would otherwise stay referenced in it after resume consumed it.
2094
- doc.x(
2095
- (op =
2096
- (op = node.data) &&
2097
- !op.indexOf(prefix) &&
2098
- ((id = op.slice(prefixLen + 1)),
2099
- (op = op[prefixLen]) > "#" || (lookup[id] = node),
2100
- op)),
2101
- id,
2102
- node,
2103
- );
2104
-
2105
- if (op > "#") {
2106
- visits.push(node);
2107
- }
2108
- }
2109
- },
2110
- })
2111
- , self[runtimeId]))`;
2112
- const REORDER_RUNTIME_CODE = `((runtime) => {
2113
- if (runtime.j) return;
2114
- let onNextSibling,
2115
- placeholder,
2116
- nextSibling,
2117
- placeholders = runtime.p = {},
2118
- replace = (id, container) => runtime.l[id].replaceWith(...container.childNodes);
2119
- runtime.j = {};
2120
- runtime.x = (op, id, node, placeholderRoot, placeholderCb) => {
2121
- if (node == nextSibling) {
2122
- onNextSibling();
2123
- }
2124
-
2125
- if (op == "#") {
2126
- (placeholders[id] = placeholder).i++;
2127
- } else if (node.tagName == "T" && (id = node.getAttribute(runtime.i))) {
2128
- nextSibling = node.nextSibling;
2129
- onNextSibling = (_) => {
2130
- node.remove();
2131
- placeholderRoot || replace(id, node);
2132
- placeholder.c();
2133
- };
2134
- placeholder =
2135
- placeholders[id] ||
2136
- (placeholderRoot = placeholders[id] =
2137
- {
2138
- // The writer streams a reorder only after its markers.
2139
- i: 1,
2140
- r: id,
2141
- // Resume may still walk markers inside the dropped placeholder, so
2142
- // park it in any detached parent (a bare <t> clone is the cheapest).
2143
- c(start = runtime.l["^" + id], removed = node.cloneNode()) {
2144
- if (--placeholderRoot.i) return 1;
2145
- for (
2146
- ;
2147
- removed.prepend(
2148
- (nextSibling = runtime.l[id].previousSibling || start),
2149
- ),
2150
- start != nextSibling;
2151
-
2152
- );
2153
- replace(id, node);
2154
- },
2155
- });
2156
- // Opens the chunk's visits for resume to parent to the root's branch; the
2157
- // walk that this chunk's own script triggers closes it.
2158
- runtime.v.push({ data: runtime.i + "*" + placeholder.r });
2159
- // repurpose "op" for callbacks ...carefully
2160
- if ((op = runtime.j[id])) {
2161
- placeholderCb = placeholder.c;
2162
- placeholder.c = (_) => placeholderCb() || op(runtime.r);
2163
- }
2164
- }
2165
- };
2166
- })`;
2167
- // src/html/writer.ts
2168
- let $chunk;
2169
- function getChunk() {
2170
- return $chunk;
2171
- }
2172
- function withChunk(chunk, cb) {
2173
- const prev = $chunk;
2174
- $chunk = chunk;
2175
- try {
2176
- return cb();
2177
- } finally {
2178
- $chunk = prev;
2179
- }
2180
- }
2181
- function getContext(key) {
2182
- return $chunk.context?.[key];
2183
- }
2184
- function getState() {
2185
- return $chunk.boundary.state;
2186
- }
2187
- function rendererKey(renderer) {
2188
- return renderer?.["owner"] === void 0 ? renderer?.["id"] || renderer : renderer["id"] + " " + renderer[Owner];
2189
- }
2190
- function getScopeId(scope) {
2191
- return scope[K_SCOPE_ID];
2192
- }
2193
- function getScopeById(scopeId) {
2194
- if (scopeId !== void 0) return $chunk.boundary.state.scopes.get(scopeId);
2195
- }
2196
- function $global() {
2197
- return $chunk.boundary.state.$global;
2198
- }
2199
- function _id() {
2200
- const state = $chunk.boundary.state;
2201
- const { $global } = state;
2202
- return "s" + $global.runtimeId + $global.renderId + (state.tagId++).toString(36);
2203
- }
2204
- function _scope_id() {
2205
- return $chunk.boundary.state.scopeId++;
2206
- }
2207
- function _peek_scope_id() {
2208
- return $chunk.boundary.state.scopeId;
2209
- }
2210
- const kPendingContexts = Symbol("Pending Contexts");
2211
- function withContext(key, value, cb, cbValue, cbValue2) {
2212
- const ctx = $chunk.context ||= { [kPendingContexts]: 0 };
2213
- const prev = ctx[key];
2214
- ctx[kPendingContexts]++;
2215
- ctx[key] = value;
2216
- try {
2217
- return cb(cbValue, cbValue2);
2218
- } finally {
2219
- ctx[kPendingContexts]--;
2220
- ctx[key] = prev;
2221
- }
2222
- }
2223
- function captureContext(chunk) {
2224
- if (chunk.context?.[kPendingContexts]) chunk.context = {
2225
- ...chunk.context,
2226
- [kPendingContexts]: 0
2227
- };
2228
- }
2229
- const kBranchId = Symbol("Branch Id");
2230
- const kAsyncContent = Symbol("Async Content");
2231
- function isInResumedBranch() {
2232
- return $chunk?.context?.[kBranchId] !== void 0;
2233
- }
2234
- function withBranchId(branchId, cb, cbValue, cbValue2) {
2235
- return withContext(kBranchId, branchId, cb, cbValue, cbValue2);
2236
- }
2237
- function withAsyncContent(async, cb, value) {
2238
- return withContext(kAsyncContent, async, cb, value);
2239
- }
2240
- function _html(html) {
2241
- $chunk.writeHTML(html);
2242
- }
2243
- function writeScript(script) {
2244
- $chunk.writeScript(script);
2245
- }
2246
- function catchableBoundary() {
2247
- const { boundary } = $chunk;
2248
- return boundary.withinCatch ? boundary : null;
2249
- }
2250
- function mayDrop(written) {
2251
- const { boundary } = $chunk;
2252
- for (let cur = written; cur && !isWithin(boundary, cur); cur = cur.parent) if (cur.aborted || cur.count) return true;
2253
- return false;
2254
- }
2255
- function _script(scopeId, registryId, markerGuard) {
2256
- if (markerGuard === 0 && ($chunk.channel.readyId || $chunk.context?.[kAsyncContent])) _resume_branch(scopeId);
2257
- $chunk.boundary.state.queueEffect(scopeId, registryId);
2258
- }
2259
- function _trailers(html) {
2260
- $chunk.boundary.state.trailerHTML += html;
2261
- }
2262
- function _resume(val, id, scopeId, locals) {
2263
- return register(id, val, scopeId === void 0 ? void 0 : _scope_with_id(scopeId), locals);
2264
- }
2265
- function _resume_locals(val, id, locals, ownerScopeId) {
2266
- if (ownerScopeId !== void 0) locals["_"] = _scope_with_id(ownerScopeId);
2267
- return register(id, val, writeScope(_scope_id(), locals));
2268
- }
2269
- function _el(scopeId, id) {
2270
- return _resume(() => _el_read_error(), id, scopeId);
2271
- }
2272
- function _hoist(scopeId, id) {
2273
- const getter = () => _hoist_read_error();
2274
- getter[Symbol.iterator] = _hoist_read_error;
2275
- return _resume(getter, id, scopeId);
2276
- }
2277
- function _el_mark(scopeId, accessor, markerGuard) {
2278
- if (markerGuard === 0) return "";
2279
- const { state } = $chunk.boundary;
2280
- state.needsWalkerRuntime = true;
2281
- return state.mark("$", scopeId + " " + accessor);
2282
- }
2283
- function _text_mark(scopeId, accessor, val, markerGuard) {
2284
- return markText(scopeId, accessor, _escape(val), markerGuard);
2285
- }
2286
- function _html_mark(scopeId, accessor, val, markerGuard) {
2287
- const html = _unescaped(val);
2288
- if (markerGuard === 0 || !~html.indexOf("<")) return markText(scopeId, accessor, html, markerGuard);
2289
- const { state } = $chunk.boundary;
2290
- state.needsWalkerRuntime = true;
2291
- return state.mark("&", "") + html + state.mark("'", scopeId + " " + accessor);
2292
- }
2293
- function markText(scopeId, accessor, text, markerGuard) {
2294
- if (markerGuard === 0) return text;
2295
- const { state } = $chunk.boundary;
2296
- state.needsWalkerRuntime = true;
2297
- return text ? (markerGuard === 2 ? "<!>" : "") + text + state.mark("$", scopeId + " " + accessor) : state.mark("%", scopeId + " " + accessor);
2298
- }
2299
- function _resume_branch(scopeId) {
2300
- const branchId = $chunk.context?.[kBranchId];
2301
- if (branchId !== void 0 && branchId !== scopeId) writeScope(scopeId, { [ClosestBranchId]: branchId });
2302
- }
2303
- function _attr_content(nodeAccessor, scopeId, content, markerGuard) {
2304
- const shouldResume = markerGuard !== 0;
2305
- const render = normalizeServerRender(content);
2306
- const branchId = _peek_scope_id();
2307
- if (render) try {
2308
- _set_scope_reason(shouldResume ? ALL_GROUPS : 0);
2309
- if (shouldResume) withBranchId(branchId, render);
2310
- else render();
2311
- } finally {
2312
- _set_scope_reason(void 0);
2313
- }
2314
- if (_peek_scope_id() !== branchId) {
2315
- if (shouldResume) writeScope(scopeId, {
2316
- [BranchScopes + nodeAccessor]: writeScope(branchId, {}),
2317
- [ConditionalRenderer + nodeAccessor]: rendererKey(render)
2318
- });
2319
- } else _scope_id();
2320
- }
2321
- function normalizeServerRender(value) {
2322
- const renderer = normalizeDynamicRenderer(value);
2323
- if (renderer) {
2324
- if (typeof renderer === "function") return renderer;
2325
- else throw new Error(`Invalid \`content\` attribute. Received ${typeof value}`);
2326
- }
2327
- }
2328
- function _var(parentScopeId, scopeOffsetAccessor, childScopeId, registryId, nodeAccessor) {
2329
- writeScopePassive(parentScopeId, { [scopeOffsetAccessor]: _scope_id() });
2330
- const childScope = writeScopePassive(childScopeId, { [TagVariable]: _resume({}, registryId, parentScopeId) });
2331
- if (nodeAccessor !== void 0) writeScope(parentScopeId, { [BranchScopes + nodeAccessor]: childScope });
2332
- }
2333
- function writeScopePassive(scopeId, partialScope) {
2334
- const target = $chunk.channel;
2335
- const scope = _scope_with_id(scopeId);
2336
- Object.assign(scope, partialScope);
2337
- $chunk.boundary.state.queuePassiveScope(target, scopeId, partialScope);
2338
- return scope;
2339
- }
2340
- let writeScope = (scopeId, partialScope) => {
2341
- const { state } = $chunk.boundary;
2342
- const target = $chunk.channel;
2343
- const scope = scopeWithId(state, scopeId);
2344
- state.needsWalkerRuntime = true;
2345
- countResumeWrite($chunk);
2346
- writeAsyncVisits($chunk);
2347
- Object.assign(scope, partialScope);
2348
- state.queueScope(target, scopeId, partialScope);
2349
- return scope;
2350
- };
2351
- writeScope = ((writeScope) => (scopeId, partialScope, file, loc, vars) => {
2352
- const scope = writeScope(scopeId, partialScope);
2353
- if (file && loc !== void 0) setDebugInfo(scope, file, loc, vars);
2354
- return scope;
2355
- })(writeScope);
2356
- function _existing_scope(scopeId) {
2357
- return writeScope(scopeId, {});
2358
- }
2359
- function _scope_with_id(scopeId) {
2360
- return scopeWithId($chunk.boundary.state, scopeId);
2361
- }
2362
- function scopeWithId(state, scopeId) {
2363
- const { scopes } = state;
2364
- let scope = scopes.get(scopeId);
2365
- if (!scope) scopes.set(scopeId, scope = { [K_SCOPE_ID]: scopeId });
2366
- return scope;
2367
- }
2368
- function _subscribe(subscribers, scope, resumeId, markerGuard) {
2369
- if (subscribers) {
2370
- const { boundary, channel } = $chunk;
2371
- const { serializer } = boundary.state;
2372
- if (!channel.readyId && !serializer.refs.has(subscribers)) subscribers.add(scope);
2373
- else if (resumeId) _script(scope[K_SCOPE_ID], resumeId, markerGuard);
2374
- else queueCall(serializer, scope, subscribers, "add", channel);
2375
- if (boundary.withinCatch) (boundary.subscribed ||= []).push(subscribers, scope, channel);
2376
- }
2377
- return scope;
2378
- }
2379
- const ALL_GROUPS = 715827883;
2380
- function getGroupReason(reason, group) {
2381
- return reason === 715827883 ? 1 : typeof reason === "number" ? group < 15 ? reason >>> 1 + 2 * group & 3 : 0 : reason[group] ?? 0;
2382
- }
2383
- function _set_scope_reason(reason) {
2384
- $chunk.boundary.state.scopeReason = reason;
2385
- }
2386
- function _scope_reason() {
2387
- const reason = $chunk.boundary.state.scopeReason;
2388
- $chunk.boundary.state.scopeReason = void 0;
2389
- return reason;
2390
- }
2391
- function _write_if(reason, group) {
2392
- return reason && getGroupReason(reason, group) ? 1 : void 0;
2393
- }
2394
- function _write_guard(reason, group) {
2395
- return _write_if(reason, group) || 0;
2396
- }
2397
- function writeWaitReady(readyId, renderer, input) {
2398
- const chunk = $chunk;
2399
- const { boundary } = chunk;
2400
- const body = new Chunk(boundary, null, chunk.context, {
2401
- readyId,
2402
- parent: chunk.channel,
2403
- resumes: "",
2404
- writeScopes: {},
2405
- flushScopes: false
2406
- });
2407
- const bodyEnd = body.render(renderer, input);
2408
- if (boundary.aborted) throw boundary.reason;
2409
- if (body === bodyEnd) {
2410
- chunk.writeHTML(body.html);
2411
- body.deferOwnReady();
2412
- chunk.deferredReady = push(chunk.deferredReady, body);
2413
- } else {
2414
- bodyEnd.next = chunk.forkRest(boundary);
2415
- chunk.next = body;
2416
- }
2417
- }
2418
- function deferBranchStart(chunk) {
2419
- const beforeBranch = chunk.html;
2420
- chunk.html = "";
2421
- return beforeBranch;
2422
- }
2423
- function applyBranchStart(chunk, beforeBranch, rendered) {
2424
- chunk.html = beforeBranch + (rendered ? chunk.boundary.state.mark("[", "") : "") + chunk.html;
2425
- }
2426
- function unsubscribe(subscribed, serializer) {
2427
- for (let i = 0; i < subscribed.length; i += 3) {
2428
- const subscribers = subscribed[i];
2429
- const scope = subscribed[i + 1];
2430
- if (!serializer.refs.has(subscribers)) subscribers.delete(scope);
2431
- else {
2432
- const channel = subscribed[i + 2];
2433
- if (!dropQueuedCall(serializer, scope, subscribers, "add", channel)) queueCall(serializer, scope, subscribers, "delete", channel);
2434
- }
2435
- }
2436
- }
2437
- const NOOP$2 = () => {};
2438
- function countResumeWrite(chunk) {
2439
- for (let boundary = chunk.boundary; boundary; boundary = boundary.parent) boundary.resumeWrites++;
2440
- }
2441
- function writeAsyncVisits(chunk) {
2442
- for (let async = getAsyncContent(chunk); async && !async.resumed; async = async.parent) {
2443
- async.resumed = true;
2444
- async.end?.writeHTML(async.visit);
2445
- }
2446
- }
2447
- function getAsyncContent(chunk) {
2448
- return chunk.context?.[kAsyncContent];
2449
- }
2450
- var State = class {
2451
- tagId = 1;
2452
- scopeId = 1;
2453
- reorderId = 1;
2454
- readyGate = 1;
2455
- hasWrittenGlobals = false;
2456
- needsWalkerRuntime = false;
2457
- hasWalkerRuntime = false;
2458
- hasWrittenReady = false;
2459
- hasReorderRuntime = false;
2460
- hasWrittenResume = false;
2461
- walkOnNextFlush = false;
2462
- trailerHTML = "";
2463
- resumes = "";
2464
- nonceAttr = "";
2465
- serializer = new State$1();
2466
- writeReorders = null;
2467
- scopes = /* @__PURE__ */ new Map();
2468
- scope = (scopeId) => scopeWithId(this, scopeId);
2469
- flushScopes = false;
2470
- writeScopes = {};
2471
- readyIds = null;
2472
- scopeReason;
2473
- $global;
2474
- constructor($global) {
2475
- this.$global = $global;
2476
- if ($global.cspNonce) this.nonceAttr = " nonce" + attrAssignment($global.cspNonce);
2477
- }
2478
- joinFlush(html, scripts, pending) {
2479
- const { $global, nonceAttr } = this;
2480
- const { __flush__ } = $global;
2481
- if (scripts) html += "<script" + nonceAttr + ">" + scripts + "<\/script>";
2482
- if (__flush__) {
2483
- $global.__flush__ = void 0;
2484
- html = __flush__($global, html);
2485
- }
2486
- return pending ? html : html + this.trailerHTML;
2487
- }
2488
- walkScript() {
2489
- return this.runtimePrefix + ".w()";
2490
- }
2491
- addResumes(channel, resumes) {
2492
- channel.resumes = concatSequence(channel.resumes, resumes);
2493
- }
2494
- queueScope(target, scopeId, partialScope) {
2495
- const pending = target.writeScopes[scopeId];
2496
- if (pending && pending !== partialScope) Object.assign(pending, partialScope);
2497
- else target.writeScopes[scopeId] = partialScope;
2498
- target.flushScopes = true;
2499
- }
2500
- queuePassiveScope(target, scopeId, partialScope) {
2501
- const passive = target.passiveScopes ||= {};
2502
- passive[scopeId] = Object.assign(passive[scopeId] || {}, partialScope);
2503
- }
2504
- queueEffect(scopeId, registryId) {
2505
- this.needsWalkerRuntime = true;
2506
- $chunk.writeEffect(scopeId, registryId);
2507
- }
2508
- serializeFlush(boundary) {
2509
- flushSerializer(boundary, this);
2510
- }
2511
- runtimeScript() {
2512
- return WALKER_RUNTIME_CODE + "(\"" + this.$global.runtimeId + "\")(\"" + this.$global.renderId + "\")";
2513
- }
2514
- keepsTryMarks(chunk, resumeWrites) {
2515
- return chunk !== $chunk || chunk.boundary.resumeWrites !== resumeWrites;
2516
- }
2517
- resumeScript(resumes) {
2518
- if (this.hasWrittenResume) return this.runtimePrefix + ".r.push(" + resumes + ")";
2519
- this.hasWrittenResume = true;
2520
- return this.runtimePrefix + ".r=[" + resumes + "]";
2521
- }
2522
- get runtimePrefix() {
2523
- const { $global } = this;
2524
- return $global.runtimeId + "." + $global.renderId;
2525
- }
2526
- get commentPrefix() {
2527
- const { $global } = this;
2528
- return $global.runtimeId + $global.renderId;
2529
- }
2530
- reorder(chunk) {
2531
- if (this.writeReorders) this.writeReorders.push(chunk);
2532
- else {
2533
- this.needsWalkerRuntime = true;
2534
- this.writeReorders = [chunk];
2535
- }
2536
- }
2537
- readyScript(id, resumes) {
2538
- const readyKey = toObjectKey(id);
2539
- if (this.readyIds?.has(id)) return this.readyAccess(readyKey) + ".push(" + resumes + ")";
2540
- (this.readyIds ||= /* @__PURE__ */ new Set()).add(id);
2541
- if (this.hasWrittenReady) return this.readyAccess(readyKey) + "=[" + resumes + "]";
2542
- this.hasWrittenReady = true;
2543
- return this.runtimePrefix + ".b={" + readyKey + ":[" + resumes + "]}";
2544
- }
2545
- readyAccess(readyKey) {
2546
- return this.runtimePrefix + ".b" + toAccess(readyKey);
2547
- }
2548
- nextReorderId() {
2549
- const c = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_0123456789";
2550
- let n = this.reorderId++;
2551
- let r = c[n % 54];
2552
- for (n = n / 54 | 0; n; n >>>= 6) r += c[n & 63];
2553
- return r;
2554
- }
2555
- mark(code, str) {
2556
- return "<!--" + this.commentPrefix + code + str + "-->";
2557
- }
2558
- };
2559
- var Boundary = class {
2560
- onNext = NOOP$2;
2561
- count = 0;
2562
- resumeWrites = 0;
2563
- state;
2564
- parent;
2565
- aborted = false;
2566
- reason;
2567
- subscribed;
2568
- pendingReorders;
2569
- children;
2570
- withinCatch = false;
2571
- constructor(state, signal, parent) {
2572
- this.state = state;
2573
- this.parent = parent;
2574
- if (parent) {
2575
- this.withinCatch = parent.withinCatch;
2576
- if (parent.aborted) this.abort(parent.reason);
2577
- else (parent.children ||= []).push(this);
2578
- } else if (signal) {
2579
- if (signal.aborted) this.abort(signal.reason);
2580
- else signal.addEventListener("abort", this);
2581
- }
2582
- }
2583
- abort(reason) {
2584
- if (this.aborted) return;
2585
- const { state } = this;
2586
- this.aborted = true;
2587
- this.reason = reason;
2588
- if (this.subscribed) unsubscribe(this.subscribed, state.serializer);
2589
- if (this.pendingReorders) {
2590
- for (const reorder of this.pendingReorders) state.reorder(reorder);
2591
- this.pendingReorders = void 0;
2592
- }
2593
- this.count = 0;
2594
- this.state = new State(state.$global);
2595
- if (this.children) for (const child of this.children) child.abort(reason);
2596
- this.onNext();
2597
- }
2598
- handleEvent(event) {
2599
- this.abort(event.target.reason);
2600
- }
2601
- flush() {
2602
- if (!this.aborted) this.state.serializeFlush(this);
2603
- return this.count ? 1 : this.aborted ? 2 : 0;
2604
- }
2605
- startAsync() {
2606
- if (!this.aborted) this.count++;
2607
- }
2608
- endAsync() {
2609
- if (!this.aborted) {
2610
- if (!this.count) throw new Error("A boundary ended more async work than it started.");
2611
- this.count--;
2612
- this.onNext();
2613
- }
2614
- }
2615
- };
2616
- var Chunk = class Chunk {
2617
- html = "";
2618
- scripts = "";
2619
- effects = "";
2620
- lastEffect = "";
2621
- async = false;
2622
- consumed = false;
2623
- reorderId = null;
2624
- reorderBranch = 0;
2625
- deferredReady = null;
2626
- heldEffects = null;
2627
- deferredReorder = null;
2628
- catchRange = null;
2629
- placeholder = null;
2630
- boundary;
2631
- next;
2632
- context;
2633
- channel;
2634
- constructor(boundary, next, context, channel) {
2635
- this.boundary = boundary;
2636
- this.next = next;
2637
- this.context = context;
2638
- this.channel = channel;
2639
- }
2640
- fork(boundary, next) {
2641
- return new Chunk(boundary, next, this.context, this.channel);
2642
- }
2643
- forkRest(boundary) {
2644
- return $chunk = this.fork(boundary, this.next);
2645
- }
2646
- writeHTML(html) {
2647
- this.html += html;
2648
- }
2649
- writeEffect(scopeId, registryId) {
2650
- countResumeWrite(this);
2651
- writeAsyncVisits(this);
2652
- if (this.lastEffect === registryId) this.effects = concatEffects(this.effects, scopeId + "");
2653
- else {
2654
- this.lastEffect = registryId;
2655
- this.effects = concatEffects(this.effects, registryId + " " + scopeId);
2656
- }
2657
- }
2658
- writeScript(script) {
2659
- this.scripts = concatScripts(this.scripts, script);
2660
- }
2661
- append(chunk) {
2662
- this.html += chunk.html;
2663
- this.effects = concatEffects(this.effects, chunk.effects);
2664
- this.scripts = concatScripts(this.scripts, chunk.scripts);
2665
- this.lastEffect = chunk.lastEffect || this.lastEffect;
2666
- this.deferredReady = concat(this.deferredReady, chunk.takeDeferredReady());
2667
- }
2668
- takeHeldEffects() {
2669
- const { heldEffects } = this;
2670
- this.heldEffects = null;
2671
- return heldEffects;
2672
- }
2673
- takeDeferredReady() {
2674
- const { deferredReady } = this;
2675
- this.deferredReady = null;
2676
- return deferredReady;
2677
- }
2678
- deferOwnReady() {
2679
- if (this.channel.readyId && (this.effects || this.scripts || this.channel.flushScopes)) {
2680
- const deferred = this.fork(this.boundary, null);
2681
- deferred.effects = this.effects;
2682
- deferred.scripts = this.scripts;
2683
- this.effects = this.scripts = this.lastEffect = "";
2684
- this.deferredReady = concat(deferred, this.deferredReady);
2685
- }
2686
- }
2687
- renderPlaceholders(boundary) {
2688
- const { state } = boundary;
2689
- restart: for (;;) {
2690
- let reorders = null;
2691
- for (let cur = this; cur.next && !cur.async; cur = cur.next) {
2692
- if (cur.renderPlaceholder(state)) {
2693
- if (boundary.aborted) return;
2694
- continue restart;
2695
- }
2696
- if (cur.deferredReorder) (reorders ||= []).push(cur.deferredReorder);
2697
- }
2698
- if (state.writeReorders) {
2699
- for (const reorder of state.writeReorders) if ((reorders = renderReorderPlaceholders(reorder, reorders)) === false) {
2700
- if (boundary.aborted) return;
2701
- continue restart;
2702
- }
2703
- }
2704
- for (let i = 0; reorders && i < reorders.length; i++) if ((reorders = renderReorderPlaceholders(reorders[i], reorders)) === false) {
2705
- if (boundary.aborted) return;
2706
- continue restart;
2707
- }
2708
- return;
2709
- }
2710
- }
2711
- renderPlaceholder(state) {
2712
- const { placeholder } = this;
2713
- if (!placeholder) return false;
2714
- this.placeholder = null;
2715
- if (this.boundary.aborted) return false;
2716
- const { body } = placeholder;
2717
- let end = body;
2718
- while (end.next && !end.async) end = end.next;
2719
- if (!end.async) {
2720
- end.next = this.next;
2721
- this.next = body;
2722
- return false;
2723
- }
2724
- const { branchId, scopeId, placeholderBranchId } = placeholder;
2725
- const reorderId = body.reorderId = branchId + "";
2726
- this.writeHTML(state.mark("!^", reorderId));
2727
- const { effects } = this;
2728
- const beforeBranch = deferBranchStart(this);
2729
- if (this.render(withBranchId, placeholderBranchId, placeholder.render) !== this) this.boundary.abort(/* @__PURE__ */ new Error("An @placeholder cannot contain async content."));
2730
- if (this.boundary.aborted) return true;
2731
- const stateful = this.effects !== effects;
2732
- applyBranchStart(this, beforeBranch, stateful);
2733
- if (stateful) {
2734
- this.render(writeScope, branchId, { [PlaceholderBranch]: scopeWithId(state, placeholderBranchId) });
2735
- this.writeHTML(state.mark("]", scopeId + " " + (PlaceholderBranch + branchId) + " " + placeholderBranchId));
2736
- dismissChunk(end, body).writeEffect(branchId, PLACEHOLDER_DISMISS_REGISTER_ID);
2737
- }
2738
- this.writeHTML(state.mark("!", reorderId));
2739
- this.deferredReorder = body;
2740
- return false;
2741
- }
2742
- markCatchRange() {
2743
- const { catchRange } = this;
2744
- if (catchRange) {
2745
- const { state } = this.boundary;
2746
- this.catchRange = null;
2747
- this.writeHTML(state.mark("!^", catchRange.id));
2748
- catchRange.end.writeHTML(state.mark("!", catchRange.id));
2749
- }
2750
- }
2751
- queueDeferredReorder() {
2752
- const { deferredReorder } = this;
2753
- if (deferredReorder) {
2754
- this.deferredReorder = null;
2755
- deferredReorder.boundary.state.reorder(deferredReorder);
2756
- }
2757
- }
2758
- consume(boundary) {
2759
- this.renderPlaceholders(boundary);
2760
- let cur = this;
2761
- let html = "";
2762
- let effects = "";
2763
- let scripts = "";
2764
- let effectsEnd;
2765
- let heldEffects = this.heldEffects;
2766
- let deferredReady;
2767
- this.heldEffects = null;
2768
- if (this.channel.readyId && this.effects) followHeldEffects(this);
2769
- while (cur.next && !cur.async) {
2770
- cur.markCatchRange();
2771
- cur.queueDeferredReorder();
2772
- html += cur.html;
2773
- if (cur.channel.readyId) deferredReady = push(deferredReady, cur);
2774
- else {
2775
- if (cur.effects) {
2776
- if (effectsEnd && effectsEnd.boundary !== cur.boundary) {
2777
- heldEffects = holdEffectsOn(heldEffects, effectsEnd, effects);
2778
- effects = "";
2779
- }
2780
- effectsEnd = cur;
2781
- effects = concatEffects(effects, cur.effects);
2782
- }
2783
- scripts = concatScripts(scripts, cur.scripts);
2784
- }
2785
- deferredReady = concat(deferredReady, cur.takeDeferredReady());
2786
- cur.consumed = true;
2787
- cur = cur.next;
2788
- }
2789
- cur.deferOwnReady();
2790
- if (effects) {
2791
- if (cur.channel.readyId) heldEffects = holdEffectsOn(heldEffects, effectsEnd, effects);
2792
- else if (effectsEnd.boundary !== cur.boundary) {
2793
- heldEffects = holdEffectsOn(heldEffects, effectsEnd, effects);
2794
- if (isWithin(cur.boundary, effectsEnd.boundary)) cur.lastEffect ||= effectsEnd.lastEffect;
2795
- } else {
2796
- cur.effects = concatEffects(effects, cur.effects);
2797
- cur.lastEffect ||= effectsEnd.lastEffect;
2798
- }
2799
- }
2800
- cur.heldEffects = heldEffects;
2801
- cur.deferredReady = concat(deferredReady, cur.deferredReady);
2802
- cur.html = html + cur.html;
2803
- cur.scripts = concatScripts(scripts, cur.scripts);
2804
- return cur;
2805
- }
2806
- render(content, val, val2) {
2807
- const prev = $chunk;
2808
- $chunk = this;
2809
- try {
2810
- content(val, val2);
2811
- return $chunk;
2812
- } catch (err) {
2813
- this.boundary.abort(err);
2814
- return this;
2815
- } finally {
2816
- $chunk = prev;
2817
- }
2818
- }
2819
- flushReadyScripts(boundary, reservations, holdEffects) {
2820
- const { channel } = this;
2821
- const { readyId } = channel;
2822
- let scripts = "";
2823
- const held = this.takeDeferredReady();
2824
- if (held) for (const chunk of Array.isArray(held) ? held : [held]) {
2825
- if (chunk.boundary.aborted) continue;
2826
- scripts = concatScripts(scripts, chunk.flushReadyScripts(boundary, reservations, holdEffects));
2827
- if (chunk.effects || chunk.deferredReady) this.deferredReady = push(this.deferredReady, chunk);
2828
- }
2829
- if (readyId && !this.async) {
2830
- const { state } = boundary;
2831
- const effects = holdEffects ? "" : this.effects;
2832
- if (effects) flushSerializerGlobals(boundary);
2833
- flushSerializer(boundary, channel);
2834
- const deps = takeChannelDeps(state.serializer);
2835
- const { resumes } = channel;
2836
- const chunkScripts = this.scripts;
2837
- channel.resumes = this.scripts = "";
2838
- if (effects) this.effects = this.lastEffect = "";
2839
- if (resumes || effects) {
2840
- state.needsWalkerRuntime = true;
2841
- const batch = concatSequence(depsMarker(deps), concatSequence(resumes, effects && `"${effects}"`));
2842
- if (reservations) {
2843
- const gate = state.readyGate++;
2844
- reservations.push(state.readyScript(readyId, gate + ""));
2845
- scripts = concatScripts(scripts, "(b=>b.splice(b.indexOf(" + gate + "),1," + batch + "))(" + state.readyAccess(toObjectKey(readyId)) + ")");
2846
- } else scripts = concatScripts(scripts, state.readyScript(readyId, batch));
2847
- }
2848
- scripts = concatScripts(scripts, chunkScripts);
2849
- }
2850
- return scripts;
2851
- }
2852
- flush(boundary) {
2853
- const { state } = boundary;
2854
- const { runtimePrefix } = state;
2855
- let needsWalk = state.walkOnNextFlush;
2856
- if (needsWalk) state.walkOnNextFlush = false;
2857
- flushSerializer(boundary, state);
2858
- let readyResumeScripts = this.flushReadyScripts(boundary, void 0, this.async);
2859
- for (let channel; !boundary.aborted && (channel = pendingReadyChannel(state.serializer));) {
2860
- const resumes = stringifyScopes(state.serializer, [], boundary, channel);
2861
- const deps = takeChannelDeps(state.serializer);
2862
- state.needsWalkerRuntime = true;
2863
- readyResumeScripts = concatScripts(readyResumeScripts, state.readyScript(channel.readyId, concatSequence(depsMarker(deps), resumes)));
2864
- }
2865
- if (readyResumeScripts) needsWalk = true;
2866
- const effects = this.async ? "" : joinHeldEffects(this.takeHeldEffects(), this.effects);
2867
- let { html, scripts } = this;
2868
- if (html && state.hasReorderRuntime) html = state.mark("*", "") + html;
2869
- if (state.needsWalkerRuntime && !state.hasWalkerRuntime) {
2870
- state.hasWalkerRuntime = true;
2871
- scripts = concatScripts(scripts, state.runtimeScript());
2872
- }
2873
- scripts = concatScripts(scripts, readyResumeScripts);
2874
- if (effects) {
2875
- needsWalk = true;
2876
- flushSerializerGlobals(boundary);
2877
- state.resumes = state.resumes ? state.resumes + ",\"" + effects + "\"" : "\"" + effects + "\"";
2878
- }
2879
- let reordered = "";
2880
- let needsResumeArray = false;
2881
- if (state.writeReorders) {
2882
- for (const reorderedChunk of state.writeReorders) {
2883
- needsWalk = true;
2884
- if (!state.hasReorderRuntime) {
2885
- state.hasReorderRuntime = true;
2886
- scripts = concatScripts(scripts, REORDER_RUNTIME_CODE + "(" + runtimePrefix + ")");
2887
- }
2888
- const { reorderId, reorderBranch } = reorderedChunk;
2889
- const rootBranch = reorderBranch || +reorderId;
2890
- const readyReservations = [];
2891
- let reorderHTML = "";
2892
- let reorderEffects = "";
2893
- let effectsBoundary = reorderedChunk.boundary;
2894
- let reorderScripts = "";
2895
- let cur = reorderedChunk.boundary.aborted ? null : reorderedChunk;
2896
- reorderedChunk.reorderId = null;
2897
- while (cur) {
2898
- cur.markCatchRange();
2899
- cur.queueDeferredReorder();
2900
- cur.deferOwnReady();
2901
- const { next } = cur;
2902
- const readyResumeScripts = cur.flushReadyScripts(boundary, readyReservations, this.async);
2903
- this.deferredReady = concat(this.deferredReady, cur.takeDeferredReady());
2904
- cur.consumed = true;
2905
- reorderHTML += cur.html;
2906
- if (this.async && cur.effects && cur.boundary !== effectsBoundary) {
2907
- if (reorderEffects) {
2908
- holdReorderEffects(this, effectsBoundary, reorderEffects);
2909
- reorderEffects = "";
2910
- }
2911
- effectsBoundary = cur.boundary;
2912
- }
2913
- reorderEffects = concatEffects(reorderEffects, cur.effects);
2914
- reorderScripts = concatScripts(reorderScripts, concatScripts(readyResumeScripts, cur.scripts));
2915
- if (cur.async) {
2916
- reorderHTML += state.mark("#", cur.reorderId = state.nextReorderId());
2917
- const holeBranch = cur.context?.[kBranchId];
2918
- cur.reorderBranch = holeBranch > rootBranch ? holeBranch : reorderBranch;
2919
- (cur.boundary.pendingReorders ||= /* @__PURE__ */ new Set()).add(cur);
2920
- cur.html = cur.effects = cur.scripts = cur.lastEffect = "";
2921
- cur.next = null;
2922
- }
2923
- cur = next;
2924
- }
2925
- if (reorderEffects) {
2926
- if (this.async) holdReorderEffects(this, effectsBoundary, reorderEffects);
2927
- else {
2928
- needsResumeArray = true;
2929
- reorderScripts = concatScripts(reorderScripts, "_.push(\"" + reorderEffects + "\")");
2930
- }
2931
- }
2932
- for (const reservation of readyReservations) reordered = concatScripts(reordered, reservation);
2933
- reordered = concatScripts(reordered, reorderScripts && runtimePrefix + ".j" + toAccess(reorderId) + "=_=>{" + reorderScripts + "}");
2934
- html += "<t hidden " + state.commentPrefix + "=" + reorderId + ">" + (reorderBranch ? state.mark("*", reorderBranch + "") : "") + reorderHTML + "</t>";
2935
- }
2936
- state.writeReorders = null;
2937
- }
2938
- if (state.resumes || needsResumeArray && !state.hasWrittenResume) scripts = concatScripts(scripts, state.resumeScript(state.resumes));
2939
- scripts = concatScripts(scripts, reordered);
2940
- if (needsWalk) scripts = concatScripts(scripts, state.walkScript());
2941
- this.html = html;
2942
- this.scripts = scripts;
2943
- if (!this.async) this.effects = this.lastEffect = "";
2944
- state.resumes = "";
2945
- return this;
2946
- }
2947
- flushHTML(boundary) {
2948
- const { state } = boundary;
2949
- this.flush(boundary);
2950
- const { html, scripts } = this;
2951
- this.html = this.scripts = "";
2952
- return state.joinFlush(html, scripts, boundary.count);
2953
- }
2954
- };
2955
- function renderReorderPlaceholders(reorder, reorders) {
2956
- if (!reorder.boundary.aborted) for (let cur = reorder; cur; cur = cur.next) {
2957
- if (cur.renderPlaceholder(reorder.boundary.state)) return false;
2958
- if (cur.deferredReorder) (reorders ||= []).push(cur.deferredReorder);
2959
- }
2960
- return reorders;
2961
- }
2962
- function dismissChunk(end, body) {
2963
- if (end.boundary !== body.boundary) while (end.next) end = end.next;
2964
- return end;
2965
- }
2966
- function followHeldEffects(chunk) {
2967
- const held = reduce(chunk.deferredReady, lastHeldOf, chunk);
2968
- if (held !== chunk) {
2969
- held.effects = concatEffects(held.effects, chunk.effects);
2970
- chunk.effects = "";
2971
- }
2972
- }
2973
- function lastHeldOf(held, cur) {
2974
- return cur.channel === held.channel && cur.boundary === held.boundary ? cur : held;
2975
- }
2976
- function holdEffectsOn(heldEffects, chunk, effects) {
2977
- chunk.effects = effects;
2978
- return push(heldEffects, chunk);
2979
- }
2980
- function isWithin(boundary, outer) {
2981
- while (boundary && boundary !== outer) boundary = boundary.parent;
2982
- return !!boundary;
2983
- }
2984
- function holdReorderEffects(head, boundary, effects) {
2985
- if (!head.channel.readyId) {
2986
- if (head.effects) head.heldEffects = holdEffectsOn(head.heldEffects, head.fork(head.boundary, null), head.effects);
2987
- head.effects = head.lastEffect = "";
2988
- }
2989
- head.heldEffects = holdEffectsOn(head.heldEffects, head.fork(boundary, null), effects);
2990
- }
2991
- function joinHeldEffects(heldEffects, effects) {
2992
- return concatEffects(reduce(heldEffects, joinUncaught, ""), effects);
2993
- }
2994
- function joinUncaught(joined, held) {
2995
- return held.boundary.aborted ? joined : concatEffects(joined, held.effects);
2996
- }
2997
- function flushSerializer(boundary, channel) {
2998
- const { state } = boundary;
2999
- const { serializer } = state;
3000
- const pending = hasMatchingCalls(serializer, channel.readyId);
3001
- if (channel.flushScopes || pending) {
3002
- const { writeScopes, passiveScopes } = channel;
3003
- const flushes = [];
3004
- if (passiveScopes) for (const key in passiveScopes) {
3005
- const props = writeScopes[key];
3006
- if (props) {
3007
- writeScopes[key] = Object.assign(passiveScopes[key], props);
3008
- delete passiveScopes[key];
3009
- }
3010
- }
3011
- if (!channel.readyId && !state.hasWrittenGlobals) {
3012
- state.hasWrittenGlobals = true;
3013
- const globals = getFilteredGlobals(state.$global);
3014
- if (globals) flushes.push([
3015
- 0,
3016
- globals,
3017
- globals
3018
- ]);
3019
- }
3020
- for (const key in writeScopes) {
3021
- const scopeId = +key;
3022
- const props = writeScopes[scopeId];
3023
- if (hasKeys(props)) flushes.push([
3024
- scopeId,
3025
- state.scopes.get(scopeId),
3026
- props
3027
- ]);
3028
- }
3029
- if (flushes.length || pending) {
3030
- if (channel.readyId) flushSerializerGlobals(boundary);
3031
- state.addResumes(channel, stringifyScopes(serializer, flushes, boundary, channel));
3032
- }
3033
- channel.writeScopes = {};
3034
- channel.flushScopes = false;
3035
- if (pending) state.walkOnNextFlush = true;
3036
- }
3037
- }
3038
- function flushSerializerGlobals(boundary) {
3039
- const { state } = boundary;
3040
- if (state.hasWrittenGlobals) return;
3041
- state.hasWrittenGlobals = true;
3042
- const globals = getFilteredGlobals(state.$global);
3043
- if (globals) {
3044
- state.needsWalkerRuntime = true;
3045
- state.resumes = concatSequence(state.resumes, stringifyScopes(state.serializer, [[
3046
- 0,
3047
- globals,
3048
- globals
3049
- ]], boundary));
3050
- }
3051
- }
3052
- function depsMarker(deps) {
3053
- let marker = "";
3054
- if (deps) {
3055
- for (const dep of deps) marker += (marker ? "," : "[") + quote(dep, 0);
3056
- marker += "]";
3057
- }
3058
- return marker;
3059
- }
3060
- function getFilteredGlobals($global) {
3061
- if (!$global) return 0;
3062
- const serializedGlobals = $global.serializedGlobals;
3063
- if (!serializedGlobals) return 0;
3064
- let filtered = 0;
3065
- if (Array.isArray(serializedGlobals)) for (const key of serializedGlobals) {
3066
- const value = $global[key];
3067
- if (value !== void 0) {
3068
- if (filtered) filtered[key] = value;
3069
- else filtered = { [key]: value };
3070
- }
3071
- }
3072
- else for (const key in serializedGlobals) if (serializedGlobals[key]) {
3073
- const value = $global[key];
3074
- if (value !== void 0) {
3075
- if (filtered) filtered[key] = value;
3076
- else filtered = { [key]: value };
3077
- }
3078
- }
3079
- return filtered;
3080
- }
3081
- function concatEffects(a, b) {
3082
- return a ? b ? a + " " + b : a : b;
3083
- }
3084
- function concatSequence(a, b) {
3085
- return a ? b ? a + "," + b : a : b;
3086
- }
3087
- function concatScripts(a, b) {
3088
- return a ? b ? a + ";" + b : a : b;
3089
- }
3090
- const tick = globalThis.setImmediate || globalThis.setTimeout || globalThis.queueMicrotask || ((cb) => Promise.resolve().then(cb));
3091
- let tickQueue;
3092
- function queueTick(cb) {
3093
- if (tickQueue) tickQueue.add(cb);
3094
- else {
3095
- tickQueue = /* @__PURE__ */ new Set([cb]);
3096
- tick(flushTickQueue);
3097
- }
3098
- }
3099
- function offTick(cb) {
3100
- tickQueue?.delete(cb);
3101
- }
3102
- function flushTickQueue() {
3103
- const queue = tickQueue;
3104
- tickQueue = void 0;
3105
- for (const cb of queue) try {
3106
- cb(true);
3107
- } catch (err) {
3108
- tick(() => {
3109
- throw err;
3110
- });
3111
- }
3112
- }
3113
- // src/html/content.ts
3114
- function _to_text(val) {
3115
- assertValidTextValue(val);
3116
- return val || val === 0 ? val + "" : "";
3117
- }
3118
- function _unescaped(val) {
3119
- assertValidTextValue(val);
3120
- return val ? val + "" : val === 0 ? "0" : "";
3121
- }
3122
- const unsafeXMLReg = /[<&\r]/g;
3123
- const replaceUnsafeXML = (c) => c === "&" ? "&amp;" : c === "<" ? "&lt;" : "&#13;";
3124
- const escapeXMLStr = (str) => unsafeXMLReg.test(str) ? str.replace(unsafeXMLReg, replaceUnsafeXML) : str;
3125
- function _escape(val) {
3126
- assertValidTextValue(val);
3127
- return val ? escapeXMLStr(val + "") : val === 0 ? "0" : "";
3128
- }
3129
- const unsafeScriptReg = /<(\/?script|!--)/gi;
3130
- const escapeScriptStr = (str) => unsafeScriptReg.test(str) ? str.replace(unsafeScriptReg, "\\u003C$1") : str;
3131
- function _escape_script(val) {
3132
- assertValidTextValue(val);
3133
- return val ? escapeScriptStr(val + "") : val === 0 ? "0" : "";
3134
- }
3135
- const unsafeScriptTemplateLiteralReg = /[`\\\r]|\$\{|<(?=\/?script|!--)/gi;
3136
- const replaceUnsafeScriptTemplateLiteral = (c) => c === "<" ? "\\x3C" : c === "\r" ? "\\r" : "\\" + c;
3137
- const quoteScriptTemplateLiteral = (str) => "`" + (unsafeScriptTemplateLiteralReg.test(str) ? str.replace(unsafeScriptTemplateLiteralReg, replaceUnsafeScriptTemplateLiteral) : str) + "`";
3138
- const unsafeStyleReg = /<(\/style)/gi;
3139
- const escapeStyleStr = (str) => unsafeStyleReg.test(str) ? str.replace(unsafeStyleReg, "\\3C$1") : str;
3140
- function _escape_style(val) {
3141
- assertValidTextValue(val);
3142
- return val ? escapeStyleStr(val + "") : val === 0 ? "0" : "";
3143
- }
3144
- function _escape_style_value(val) {
3145
- assertValidTextValue(val);
3146
- return val || val === 0 ? escapeStyleValue(val + "") : "";
3147
- }
3148
- const unsafeCommentReg = />/g;
3149
- function escapeCommentStr(str) {
3150
- if (unsafeCommentReg.test(str)) str = str.replace(unsafeCommentReg, "&gt;");
3151
- return str.startsWith(getState().commentPrefix) ? "&#" + str.charCodeAt(0) + ";" + str.slice(1) : str;
3152
- }
3153
- function _escape_comment(val) {
3154
- assertValidTextValue(val);
3155
- return val ? escapeCommentStr(val + "") : val === 0 ? "0" : "";
3156
- }
3157
- // src/html/dynamic-tag.ts
3158
- const voidElementsReg = /^(?:area|b(?:ase|r)|col|embed|hr|i(?:mg|nput)|link|meta|param|source|track|wbr)$/;
3159
- let _dynamic_tag = (scopeId, accessor, tag, inputOrArgs, content, inputIsArgs, markerGuard, tagVar) => {
3160
- const shouldResume = markerGuard !== 0;
3161
- const renderer = normalizeDynamicRenderer(tag);
3162
- const state = getState();
3163
- const branchId = _peek_scope_id();
3164
- let rendered;
3165
- let result;
3166
- if (typeof renderer === "string") {
3167
- assertValidTagName(renderer);
3168
- const input = (inputIsArgs ? inputOrArgs[0] : inputOrArgs) || {};
3169
- rendered = true;
3170
- const renderNative = () => {
3171
- _scope_id();
3172
- _html(`<${renderer}${_attrs(input, `#${renderer.toLowerCase()}/0`, branchId, renderer)}>`);
3173
- if (!voidElementsReg.test(renderer)) {
3174
- const renderContent = content || normalizeDynamicRenderer(input.content);
3175
- if (renderer === "textarea") {
3176
- if (renderContent) throw new Error("A dynamic tag rendering a `<textarea>` cannot have `content` and must use the `value` attribute instead.");
3177
- _html(_attrs_textarea_value(branchId, `#${renderer.toLowerCase()}/0`, input));
3178
- } else {
3179
- if (renderContent && typeof renderContent !== "function") throw new Error(`Body content is not supported for the \`<${renderer}>\` tag.`);
3180
- if (renderer === "select" && ("value" in input || "valueChange" in input)) _attr_select_value(branchId, `#${renderer.toLowerCase()}/0`, input.value, input.valueChange, renderContent ? () => _dynamic_tag(branchId, `#${renderer.toLowerCase()}/0`, renderContent, void 0, 0, void 0, markerGuard) : void 0, 1);
3181
- else if (renderContent) _dynamic_tag(branchId, `#${renderer.toLowerCase()}/0`, renderContent, void 0, 0, void 0, markerGuard);
3182
- }
3183
- _html(`</${renderer}>`);
3184
- } else if (content) throw new Error(`Body content is not supported for the \`<${renderer}>\` tag.`);
3185
- const childScope = getScopeById(branchId);
3186
- const needsScript = childScope && (childScope[`EventAttributes:#${renderer.toLowerCase()}/0`] || childScope[`ControlledHandler:#${renderer.toLowerCase()}/0`]);
3187
- if (needsScript) {
3188
- writeScope(branchId, { [Renderer]: renderer });
3189
- _script(branchId, DYNAMIC_TAG_SCRIPT_REGISTER_ID);
3190
- }
3191
- if (shouldResume || needsScript) _html(state.mark("(", scopeId + " " + accessor + " " + branchId));
3192
- };
3193
- renderNative();
3194
- result = _el(scopeId, DYNAMIC_TAG_VAR_REGISTER_ID + accessor);
3195
- } else {
3196
- if (tagVar && renderer?.["lazy"]) throw new Error(`A dynamic tag with a [tag variable](https://markojs.com/docs/reference/language#tag-variables) rendered \`${renderer["id"]}\`, which is lazily loaded, so it does not support one. Import it without \`load\`, or remove the variable.`);
3197
- const chunk = getChunk();
3198
- const beforeBranch = shouldResume ? deferBranchStart(chunk) : void 0;
3199
- const render = () => {
3200
- if (renderer) try {
3201
- _set_scope_reason(shouldResume ? ALL_GROUPS : 0);
3202
- return inputIsArgs ? renderer(...inputOrArgs) : renderer(content ? {
3203
- ...inputOrArgs,
3204
- content
3205
- } : inputOrArgs);
3206
- } finally {
3207
- _set_scope_reason(void 0);
3208
- }
3209
- else if (content) content();
3210
- };
3211
- result = shouldResume ? withBranchId(branchId, render) : render();
3212
- rendered = _peek_scope_id() !== branchId;
3213
- if (beforeBranch !== void 0) {
3214
- applyBranchStart(chunk, beforeBranch, rendered);
3215
- _html(state.mark("]", scopeId + " " + accessor + (rendered ? " " + branchId : "")));
3216
- if (renderer) _existing_scope(branchId);
3217
- }
3218
- }
3219
- if (rendered) {
3220
- if (shouldResume) writeScope(scopeId, { [ConditionalRenderer + accessor]: rendererKey(renderer) });
3221
- } else _scope_id();
3222
- return result;
3223
- };
3224
- function _content(id, fn, scopeId) {
3225
- fn["id"] = id;
3226
- fn[Owner] = scopeId;
3227
- return fn;
3228
- }
3229
- function _content_resume(id, fn, scopeId, locals) {
3230
- return _resume(_content(id, fn, scopeId), id, scopeId, locals);
3231
- }
3232
- const patchDynamicTag = /* @__PURE__ */ ((originalDynamicTag) => (patch) => {
3233
- _dynamic_tag = (scopeId, accessor, tag, input, content, inputIsArgs, markerGuard, tagVar) => {
3234
- const patched = patch(tag, scopeId, accessor);
3235
- if (patched !== tag) patched["id"] = tag;
3236
- return originalDynamicTag(scopeId, accessor, patched, input, content, inputIsArgs, markerGuard, tagVar);
3237
- };
3238
- })(_dynamic_tag);
3239
- // src/html/template.ts
3240
- const CONSUMED_RESULT_MESSAGE = "Cannot read from a consumed render result";
3241
- const _template = (templateId, renderer, page) => {
3242
- renderer.render = render;
3243
- renderer[Embed] = !page;
3244
- renderer._ = renderer;
3245
- renderer.mount = () => {
3246
- throw new Error(`mount() is not implemented for the HTML compilation of a Marko template`);
3247
- };
3248
- return _content_resume(templateId, renderer);
3249
- };
3250
- function render(input = {}) {
3251
- return startRender(this, input, State);
3252
- }
3253
- function startRender(template, input, StateClass) {
3254
- let { $global } = input;
3255
- if ($global) {
3256
- ({$global, ...input} = input);
3257
- $global = {
3258
- runtimeId: "M",
3259
- renderId: getDefaultRenderId(template),
3260
- ...$global
3261
- };
3262
- if (!String($global.runtimeId).match(/^[_a-z][_a-z0-9]*$/i)) throw new Error(`Invalid runtimeId: "${$global.runtimeId}". The runtimeId must start with a letter or underscore and only contain letters, numbers, and underscores.`);
3263
- if (!String($global.renderId).match(/^[_a-z][_a-z0-9]*$/i)) throw new Error(`Invalid renderId: "${$global.renderId}". The renderId must start with a letter or underscore and only contain letters, numbers, and underscores.`);
3264
- } else $global = {
3265
- runtimeId: "M",
3266
- renderId: getDefaultRenderId(template)
3267
- };
3268
- const state = new StateClass($global);
3269
- const head = new Chunk(new Boundary(state, $global.signal), null, null, state);
3270
- if (template["embed"]) head.render(() => writeWaitReady(template["id"], template, input));
3271
- else head.render(template, input);
3272
- return new ServerRendered(head);
3273
- }
3274
- function getDefaultRenderId(template) {
3275
- if (template["embed"]) {
3276
- const ENCODE_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_0123456789";
3277
- let n = Math.random() * 4294967296 >>> 0;
3278
- let r = ENCODE_CHARS[n % 52];
3279
- for (n = n / 52 | 0; n; n = n / 63 | 0) r += ENCODE_CHARS[n % 63];
3280
- return r;
3281
- }
3282
- return "_";
3283
- }
3284
- var ServerRendered = class {
3285
- #head;
3286
- #cachedPromise = null;
3287
- constructor(head) {
3288
- this.#head = head;
3289
- }
3290
- [Symbol.asyncIterator]() {
3291
- let resolve;
3292
- let reject;
3293
- let value = "";
3294
- let done = false;
3295
- let aborted = false;
3296
- let reason;
3297
- const boundary = this.#read((html) => {
3298
- value += html;
3299
- if (resolve) {
3300
- const settle = resolve;
3301
- resolve = reject = void 0;
3302
- settle({
3303
- value,
3304
- done
3305
- });
3306
- value = "";
3307
- }
3308
- }, (err) => {
3309
- aborted = true;
3310
- reason = err;
3311
- if (reject) {
3312
- const settle = reject;
3313
- resolve = reject = void 0;
3314
- settle(err);
3315
- }
3316
- }, () => {
3317
- done = true;
3318
- if (resolve) {
3319
- const settle = resolve;
3320
- resolve = reject = void 0;
3321
- settle({
3322
- value,
3323
- done: !value
3324
- });
3325
- value = "";
3326
- }
3327
- });
3328
- return {
3329
- next() {
3330
- if (aborted) return Promise.reject(reason);
3331
- else if (value) {
3332
- const result = {
3333
- value,
3334
- done: false
3335
- };
3336
- value = "";
3337
- return Promise.resolve(result);
3338
- } else if (done) return Promise.resolve({
3339
- value: "",
3340
- done
3341
- });
3342
- else return new Promise(exec);
3343
- },
3344
- throw(error) {
3345
- if (!(done || aborted)) boundary?.abort(error);
3346
- return Promise.resolve({
3347
- value: "",
3348
- done: true
3349
- });
3350
- },
3351
- return(value) {
3352
- if (!(done || aborted)) boundary?.abort(/* @__PURE__ */ new Error("Iterator returned before consumed."));
3353
- return Promise.resolve({
3354
- value,
3355
- done: true
3356
- });
3357
- }
3358
- };
3359
- function exec(_resolve, _reject) {
3360
- resolve = _resolve;
3361
- reject = _reject;
3362
- }
3363
- }
3364
- pipe(stream) {
3365
- this.#read((html) => {
3366
- stream.write(html);
3367
- stream.flush?.();
3368
- }, (err) => {
3369
- const socket = "socket" in stream && stream.socket;
3370
- if (socket && typeof socket.destroySoon === "function") socket.destroySoon();
3371
- else if (stream.destroy) stream.destroy();
3372
- else stream.end();
3373
- if (!stream.emit?.("error", err)) throw err;
3374
- }, () => {
3375
- stream.end();
3376
- });
3377
- }
3378
- toReadable() {
3379
- let cancelled = false;
3380
- let started = false;
3381
- let boundary;
3382
- const encoder = new TextEncoder();
3383
- return new ReadableStream({
3384
- pull: (ctrl) => {
3385
- if (started) return;
3386
- started = true;
3387
- boundary = this.#read((html) => {
3388
- ctrl.enqueue(encoder.encode(html));
3389
- }, (err) => {
3390
- boundary = void 0;
3391
- if (!cancelled) ctrl.error(err);
3392
- }, () => {
3393
- boundary = void 0;
3394
- ctrl.close();
3395
- });
3396
- },
3397
- cancel: (reason) => {
3398
- cancelled = true;
3399
- boundary?.abort(reason);
3400
- }
3401
- }, { highWaterMark: 0 });
3402
- }
3403
- then(onfulfilled, onrejected) {
3404
- return this.#promise().then(onfulfilled, onrejected);
3405
- }
3406
- catch(onrejected) {
3407
- return this.#promise().catch(onrejected);
3408
- }
3409
- finally(onfinally) {
3410
- return this.#promise().finally(onfinally);
3411
- }
3412
- #promise() {
3413
- return this.#cachedPromise ||= new Promise((resolve, reject) => {
3414
- let head = this.#head;
3415
- this.#head = null;
3416
- if (!head) return reject(/* @__PURE__ */ new Error(CONSUMED_RESULT_MESSAGE));
3417
- const { boundary } = head;
3418
- let html = "";
3419
- (boundary.onNext = () => {
3420
- switch (!boundary.count && boundary.flush()) {
3421
- case 2:
3422
- settle(boundary);
3423
- reject(boundary.reason);
3424
- break;
3425
- case 0:
3426
- head = head.consume(boundary);
3427
- if (boundary.aborted) break;
3428
- html += head.flushHTML(boundary);
3429
- if (!(boundary.count || boundary.aborted)) {
3430
- settle(boundary);
3431
- resolve(html);
3432
- }
3433
- }
3434
- })();
3435
- });
3436
- }
3437
- #read(onWrite, onAbort, onClose) {
3438
- let tick = true;
3439
- let flushing = false;
3440
- let again = false;
3441
- let head = this.#head;
3442
- this.#head = null;
3443
- if (!head) {
3444
- onAbort(/* @__PURE__ */ new Error(CONSUMED_RESULT_MESSAGE));
3445
- return;
3446
- }
3447
- const { boundary } = head;
3448
- const onNext = boundary.onNext = (write) => {
3449
- if (flushing) {
3450
- again = true;
3451
- return;
3452
- }
3453
- flushing = true;
3454
- do {
3455
- again = false;
3456
- const status = boundary.flush();
3457
- if (status === 2) {
3458
- if (!tick) offTick(onNext);
3459
- settle(boundary);
3460
- onAbort(boundary.reason);
3461
- return;
3462
- }
3463
- if (write || status === 0) {
3464
- head = head.consume(boundary);
3465
- if (boundary.aborted) continue;
3466
- const html = head.flushHTML(boundary);
3467
- if (boundary.aborted) continue;
3468
- if (html) onWrite(html);
3469
- if (!boundary.count) {
3470
- if (!tick) offTick(onNext);
3471
- settle(boundary);
3472
- onClose();
3473
- return;
3474
- }
3475
- if (write) tick = true;
3476
- } else if (tick) {
3477
- tick = false;
3478
- queueTick(onNext);
3479
- }
3480
- } while (again);
3481
- flushing = false;
3482
- };
3483
- onNext();
3484
- return boundary;
3485
- }
3486
- toString() {
3487
- const head = this.#head;
3488
- this.#head = null;
3489
- if (!head) throw /* @__PURE__ */ new Error(CONSUMED_RESULT_MESSAGE);
3490
- const { boundary } = head;
3491
- const html = boundary.flush() === 0 ? head.consume(boundary).flushHTML(boundary) : "";
3492
- if (boundary.count) boundary.abort(/* @__PURE__ */ new Error("Cannot consume asynchronous render with 'toString'"));
3493
- settle(boundary);
3494
- if (boundary.aborted) throw boundary.reason;
3495
- return html;
3496
- }
3497
- };
3498
- function settle(boundary) {
3499
- boundary.onNext = NOOP$1;
3500
- boundary.state.$global.signal?.removeEventListener("abort", boundary);
3501
- }
3502
- function NOOP$1() {}
3503
- // src/html/assets.ts
3504
- const kAssets = Symbol();
3505
- const kHead = Symbol();
3506
- function withLoadAssets(template, id, flush, assetId, triggers) {
3507
- const renderer = (input) => {
3508
- writeLoadAsset(assetId, flush, triggers);
3509
- return writeWaitReady(assetId, template(), input);
3510
- };
3511
- renderer[Lazy] = 1;
3512
- _template(id, renderer);
3513
- return renderer;
3514
- }
3515
- function writeLoadAsset(assetId, flush, triggers) {
3516
- const g = $global();
3517
- writeAsset(g, addAsset(g, assetId, flush, triggers));
3518
- }
3519
- function withPageAssets(template, flush, assetId, runtimeId) {
3520
- return Object.assign((input) => {
3521
- const g = $global();
3522
- if (runtimeId) {
3523
- if (!g[kAssets]) {
3524
- if (g.runtimeId !== "M" && g.runtimeId !== runtimeId) throw new Error(`$global.runtimeId ("${g.runtimeId}") conflicts with the runtimeId this entry was compiled with ("${runtimeId}").`);
3525
- g.runtimeId = runtimeId;
3526
- } else if (g.runtimeId !== runtimeId) console.error(`A page entry compiled with runtimeId "${runtimeId}" is nested in a render using runtimeId "${g.runtimeId}", so its content cannot resume.`);
3527
- }
3528
- const asset = addAsset(g, assetId, flush);
3529
- if (g.__flush__) {
3530
- writeAsset(g, asset);
3531
- return writeWaitReady(assetId, template, input);
3532
- }
3533
- g.__flush__ = flushPage;
3534
- return template(input);
3535
- }, template);
3536
- }
3537
- function _flush_head() {
3538
- const g = $global();
3539
- if (!g[kAssets]) return "";
3540
- g[kHead] = true;
3541
- return takeAssets(g, catchableBoundary());
3542
- }
3543
- function flushPage(g, html) {
3544
- return takeAssets(g, null) + html;
3545
- }
3546
- function takeAssets(g, at) {
3547
- let block = "";
3548
- let defer = "";
3549
- for (const asset of g[kAssets]) if (asset.htmlAt === void 0) {
3550
- asset.htmlAt = at;
3551
- block += blockHTML(g, asset);
3552
- if (!asset.triggers) defer += deferHTML(g, asset);
3553
- }
3554
- return block + defer;
3555
- }
3556
- function writeAsset(g, asset) {
3557
- if (needsWrite(asset.htmlAt)) {
3558
- asset.htmlAt = void 0;
3559
- if (g[kHead] || g.__flush__ !== flushPage) {
3560
- const block = blockHTML(g, asset);
3561
- _html(block + (asset.triggers ? "" : deferHTML(g, asset)));
3562
- if (block && isInResumedBranch()) writeScript(`document.head.insertAdjacentHTML("beforeend",${quoteScriptTemplateLiteral(block)})`);
3563
- asset.htmlAt = catchableBoundary();
3564
- }
3565
- }
3566
- if (asset.triggers && needsWrite(asset.scriptAt)) {
3567
- const defer = deferHTML(g, asset);
3568
- if (defer) writeScript(asset.script ||= triggerScript(asset.id, defer, asset.triggers));
3569
- asset.scriptAt = catchableBoundary();
3570
- }
3571
- }
3572
- function needsWrite(at) {
3573
- return at === void 0 || at !== null && mayDrop(at);
3574
- }
3575
- function blockHTML(g, asset) {
3576
- return asset.block ??= asset.flush(g, "block", asset.id);
3577
- }
3578
- function deferHTML(g, asset) {
3579
- return asset.defer ??= asset.flush(g, "defer", asset.id);
3580
- }
3581
- function addAsset(g, id, flush, triggers) {
3582
- const assets = g[kAssets] ||= [];
3583
- let asset = assets.find((a) => a.id === id);
3584
- if (!asset) assets.push(asset = {
3585
- id,
3586
- flush,
3587
- triggers,
3588
- block: void 0,
3589
- defer: void 0,
3590
- script: void 0,
3591
- htmlAt: void 0,
3592
- scriptAt: void 0
3593
- });
3594
- else if (JSON.stringify(asset.triggers) !== JSON.stringify(triggers)) console.error(`The lazy asset "${id}" is imported with different \`load\` triggers; an asset must use one consistent trigger.`);
3595
- return asset;
3596
- }
3597
- function triggerScript(id, html, triggers) {
3598
- const htmlStr = quoteScriptTemplateLiteral(html);
3599
- const insert = `(d=new Range().createContextualFragment(h),d.querySelectorAll("script").forEach(s=>s.onerror=()=>console.error(${quoteScriptTemplateLiteral(`The lazy module for "${id}" failed to load; its server-rendered content cannot become interactive.`)})),document.head.append(d))`;
3600
- const exprs = triggers.map((trigger) => {
3601
- const options = trigger.options && toObjectExpression(trigger.options);
3602
- switch (trigger.type) {
3603
- case "visible": return `(e=>e&&new IntersectionObserver((e,i)=>e.some(e=>e.isIntersecting)&&i.disconnect()+l()${options ? `,${options}` : ""}).observe(e))(${querySelectorOrLoad(trigger.selector)})`;
3604
- case "idle": return `(self.requestIdleCallback||l)(l${options ? `,${options}` : ""})`;
3605
- case "media": return `(m=>m.matches?l():m.addEventListener("change",l,{once:1}))(matchMedia(${JSON.stringify(trigger.selector)}))`;
3606
- default: return `(e=>e?.addEventListener("${trigger.type.slice(3)}",l,{once:1}))(${querySelectorOrLoad(trigger.selector)})`;
3607
- }
3608
- });
3609
- return `((h,d,l=$=>{d||${insert}})=>${exprs.length > 1 ? `{${exprs.join(";")}}` : exprs[0]})(${htmlStr})`;
3610
- }
3611
- function querySelectorOrLoad(selector) {
3612
- return `document.querySelector(${JSON.stringify(selector)})||${`(console.warn(${JSON.stringify(`A lazy load trigger could not find an element matching "${selector}". The module was loaded immediately.`)}),l())`}`;
3613
- }
3614
- function toObjectExpression(options) {
3615
- let result = "{";
3616
- let sep = "";
3617
- for (const key in options) if (Object.hasOwn(options, key)) {
3618
- result += sep + toObjectKey(key) + ":" + JSON.stringify(options[key]);
3619
- sep = ",";
3620
- }
3621
- return result + "}";
3622
- }
3623
- // src/common/compat-meta.ts
3624
- const SET_SCOPE_REGISTER_ID = "$compat_setScope";
3625
- const RENDER_BODY_ID = "$compat_renderBody";
3626
- // src/common/for.ts
3627
- function forIn(obj, cb) {
3628
- for (const key in obj) cb(key, obj[key]);
3629
- }
3630
- function forOf(list, cb) {
3631
- assertValidList(list);
3632
- if (list) {
3633
- let i = 0;
3634
- for (const item of list) cb(item, i++);
3635
- }
3636
- }
3637
- function forTo(to, from, step, cb) {
3638
- assertValidRangeBound("to", to);
3639
- assertOptionalRangeNumber("from", from);
3640
- assertOptionalRangeNumber("step", step);
3641
- const start = from || 0;
3642
- const delta = step || 1;
3643
- for (let steps = (to - start) / delta, i = 0; i <= steps; i++) cb(start + i * delta);
3644
- }
3645
- function forUntil(until, from, step, cb) {
3646
- assertValidRangeBound("until", until);
3647
- assertOptionalRangeNumber("from", from);
3648
- assertOptionalRangeNumber("step", step);
3649
- const start = from || 0;
3650
- const delta = step || 1;
3651
- for (let steps = (until - start) / delta, i = 0; i < steps; i++) cb(start + i * delta);
3652
- }
3653
- // src/html/for.ts
3654
- function forOfBy(by, item, index) {
3655
- return by ? typeof by === "string" ? item[by] : by(item, index) : index;
3656
- }
3657
- function forInBy(by, name, value) {
3658
- return by ? by(name, value) : name;
3659
- }
3660
- function forStepBy(by, index) {
3661
- return by ? by(index) : index;
3662
- }
3663
- // src/html/control-flow.ts
3664
- function _show_start(display, markerGuard, branchExprGuard, parentEndTag) {
3665
- if (display) {
3666
- if (resumesMarker(markerGuard, branchExprGuard, parentEndTag)) $chunk.writeHTML($chunk.boundary.state.mark("[", ""));
3667
- } else $chunk.writeHTML("<t hidden>");
3668
- }
3669
- function _show_end(scopeId, accessor, display, markerGuard, branchExprGuard, parentEndTag, singleNode) {
3670
- const branchId = _scope_id();
3671
- const wrap = !display;
3672
- if (wrap) $chunk.writeHTML("</t>");
3673
- writeBranchEnd(scopeId, accessor, branchExprGuard, markerGuard, parentEndTag, wrap || singleNode ? 1 : void 0, " " + branchId);
3674
- }
3675
- function _for_of(list, cb, by, scopeId, accessor, branchGuard, markerGuard, branchExprGuard, parentEndTag, singleNode) {
3676
- forBranches(by, cb, iterateForOf(list, cb, by), scopeId, accessor, branchGuard, markerGuard, branchExprGuard, parentEndTag, singleNode);
3677
- }
3678
- function iterateForOf(list, cb, by) {
3679
- return (each) => each ? forOf(list, (item, index) => {
3680
- const itemKey = forOfBy(by, item, index);
3681
- each(itemKey, itemKey === index, item, index);
3682
- }) : forOf(list, cb);
3683
- }
3684
- function _for_in(obj, cb, by, scopeId, accessor, branchGuard, markerGuard, branchExprGuard, parentEndTag, singleNode) {
3685
- forBranches(by, cb, iterateForIn(obj, cb, by), scopeId, accessor, branchGuard, markerGuard, branchExprGuard, parentEndTag, singleNode);
3686
- }
3687
- function iterateForIn(obj, cb, by) {
3688
- return (each) => each ? forIn(obj, (key, value) => {
3689
- each(forInBy(by, key, value), false, key, value);
3690
- }) : forIn(obj, cb);
3691
- }
3692
- function _for_to(to, from, step, cb, by, scopeId, accessor, branchGuard, markerGuard, branchExprGuard, parentEndTag, singleNode) {
3693
- forBranches(by, cb, iterateForTo(to, from, step, cb, by), scopeId, accessor, branchGuard, markerGuard, branchExprGuard, parentEndTag, singleNode);
3694
- }
3695
- function iterateForTo(to, from, step, cb, by) {
3696
- return (each) => {
3697
- let index = 0;
3698
- return each ? forTo(to, from, step, (value) => {
3699
- const itemKey = forStepBy(by, value);
3700
- each(itemKey, itemKey === index++, value);
3701
- }) : forTo(to, from, step, cb);
3702
- };
3703
- }
3704
- function _for_until(until, from, step, cb, by, scopeId, accessor, branchGuard, markerGuard, branchExprGuard, parentEndTag, singleNode) {
3705
- forBranches(by, cb, iterateForUntil(until, from, step, cb, by), scopeId, accessor, branchGuard, markerGuard, branchExprGuard, parentEndTag, singleNode);
3706
- }
3707
- function iterateForUntil(until, from, step, cb, by) {
3708
- return (each) => {
3709
- let index = 0;
3710
- return each ? forUntil(until, from, step, (value) => {
3711
- const itemKey = forStepBy(by, value);
3712
- each(itemKey, itemKey === index++, value);
3713
- }) : forUntil(until, from, step, cb);
3714
- };
3715
- }
3716
- function checkLoopKeys(cb, iterate) {
3717
- const seenKeys = /* @__PURE__ */ new Set();
3718
- return (each) => iterate((itemKey, sameAsIndex, a, b) => {
3719
- assertValidLoopKey(itemKey, seenKeys);
3720
- if (each) each(itemKey, sameAsIndex, a, b);
3721
- else cb(a, b);
3722
- });
3723
- }
3724
- function forBranches(by, cb, iterate, scopeId, accessor, branchGuard, markerGuard, branchExprGuard, parentEndTag, singleNode) {
3725
- if (by) iterate = checkLoopKeys(cb, iterate);
3726
- if (branchGuard === 0) {
3727
- iterate(0);
3728
- writeBranchEnd(scopeId, accessor, branchExprGuard, markerGuard, parentEndTag, singleNode, "");
3729
- return;
3730
- }
3731
- const { state } = $chunk.boundary;
3732
- const resumeKeys = markerGuard !== 0;
3733
- const resumeMarker = resumesMarker(markerGuard, branchExprGuard, parentEndTag);
3734
- let flushBranchIds = "";
3735
- let loopScopes;
3736
- iterate((itemKey, sameAsIndex, a, b) => {
3737
- const branchId = _peek_scope_id();
3738
- if (resumeMarker) {
3739
- if (singleNode) flushBranchIds = " " + branchId + flushBranchIds;
3740
- else {
3741
- $chunk.writeHTML(state.mark("[", flushBranchIds));
3742
- flushBranchIds = branchId + "";
3743
- }
3744
- }
3745
- withBranchId(branchId, cb, a, b);
3746
- const branchScope = writeScope(branchId, resumeKeys && !sameAsIndex ? { [LoopKey]: itemKey } : {});
3747
- if (!resumeMarker) loopScopes = push(loopScopes, branchScope);
3748
- });
3749
- if (loopScopes) writeScope(scopeId, { [BranchScopes + accessor]: loopScopes });
3750
- writeBranchEnd(scopeId, accessor, branchExprGuard, markerGuard, parentEndTag, singleNode, singleNode ? flushBranchIds : flushBranchIds ? " " + flushBranchIds : "");
3751
- }
3752
- function _if(cb, scopeId, accessor, branchGuard, markerGuard, branchExprGuard, parentEndTag, singleNode) {
3753
- const resumeBranch = branchGuard !== 0;
3754
- const resumeMarker = resumesMarker(markerGuard, branchExprGuard, parentEndTag);
3755
- const branchId = _peek_scope_id();
3756
- const chunk = $chunk;
3757
- const beforeBranch = resumeMarker && resumeBranch && !singleNode ? deferBranchStart(chunk) : void 0;
3758
- const branchIndex = resumeBranch ? withBranchId(branchId, cb) : cb();
3759
- const shouldWriteBranch = resumeBranch && branchIndex !== void 0;
3760
- if (beforeBranch !== void 0) applyBranchStart(chunk, beforeBranch, shouldWriteBranch);
3761
- if (shouldWriteBranch && (branchIndex || !resumeMarker)) writeScope(scopeId, {
3762
- [ConditionalRenderer + accessor]: branchIndex || void 0,
3763
- [BranchScopes + accessor]: resumeMarker ? void 0 : writeScope(branchId, {})
3764
- });
3765
- writeBranchEnd(scopeId, accessor, branchExprGuard, markerGuard, parentEndTag, singleNode, shouldWriteBranch ? " " + branchId : "");
3766
- }
3767
- function resumesMarker(markerGuard, branchExprGuard, parentEndTag) {
3768
- return markerGuard !== 0 && (!parentEndTag || branchExprGuard !== 0);
3769
- }
3770
- function writeBranchEnd(scopeId, accessor, branchExprGuard, markerGuard, parentEndTag, singleNode, branchIds) {
3771
- const endTag = parentEndTag || "";
3772
- if (resumesMarker(markerGuard, branchExprGuard, parentEndTag)) {
3773
- const { state } = $chunk.boundary;
3774
- const mark = singleNode ? state.mark(parentEndTag ? "}" : "|", scopeId + " " + accessor + (branchIds || "")) : state.mark(parentEndTag ? ")" : "]", scopeId + " " + accessor + (branchIds || ""));
3775
- $chunk.writeHTML(mark + endTag);
3776
- } else if (markerGuard !== 0) $chunk.writeHTML(endTag + _el_mark(scopeId, accessor));
3777
- else $chunk.writeHTML(endTag);
3778
- }
3779
- function _await(scopeId, accessor, promise, content, markerGuard) {
3780
- const resumeMarker = markerGuard !== 0;
3781
- if (!isPromise(promise)) {
3782
- if (resumeMarker) {
3783
- const branchId = _peek_scope_id();
3784
- $chunk.writeHTML($chunk.boundary.state.mark("[", ""));
3785
- withBranchId(branchId, content, promise);
3786
- $chunk.writeHTML($chunk.boundary.state.mark("]", scopeId + " " + accessor + " " + branchId));
3787
- } else content(promise);
3788
- return;
3789
- }
3790
- const chunk = $chunk;
3791
- const { boundary } = chunk;
3792
- const startId = _peek_scope_id();
3793
- const after = chunk.next = chunk.forkRest(boundary);
3794
- chunk.async = true;
3795
- captureContext(chunk);
3796
- boundary.startAsync();
3797
- promise.then((value) => {
3798
- if (chunk.async) {
3799
- chunk.async = false;
3800
- if (!boundary.aborted) {
3801
- const { state } = boundary;
3802
- chunk.render(() => {
3803
- if (resumeMarker) {
3804
- const branchId = _peek_scope_id();
3805
- $chunk.writeHTML($chunk.boundary.state.mark("[", ""));
3806
- withBranchId(branchId, () => withAsyncContent({ parent: getAsyncContent(chunk) }, content, value));
3807
- $chunk.writeHTML($chunk.boundary.state.mark("]", scopeId + " " + accessor + " " + branchId));
3808
- } else {
3809
- const renderedSince = _peek_scope_id() !== startId;
3810
- const async = { parent: getAsyncContent(chunk) };
3811
- withAsyncContent(async, content, value);
3812
- async.visit = renderedSince && (after.html || after.next) ? $chunk.boundary.state.mark("]", scopeId + " " + accessor) : "";
3813
- if (async.resumed) $chunk.writeHTML(async.visit);
3814
- async.end = $chunk;
3815
- }
3816
- });
3817
- if (!chunk.async && boundary.pendingReorders?.delete(chunk)) state.reorder(chunk);
3818
- boundary.endAsync();
3819
- }
3820
- }
3821
- }, (err) => {
3822
- chunk.async = false;
3823
- boundary.abort(err);
3824
- });
3825
- }
3826
- function _try(scopeId, accessor, content, placeholderContent, catchContent, placeholderId, catchId) {
3827
- const placeholderBranchId = placeholderContent ? _scope_id() : 0;
3828
- const branchId = _peek_scope_id();
3829
- const chunk = $chunk;
3830
- const { boundary } = chunk;
3831
- const { state } = boundary;
3832
- const { resumeWrites } = boundary;
3833
- const beforeBranch = deferBranchStart(chunk);
3834
- const renderers = () => writeTryRenderers(branchId, catchContent && _resume(catchContent, catchId), placeholderContent && _resume(placeholderContent, placeholderId));
3835
- const writesRenderers = tryBoundary(placeholderContent ? () => tryPlaceholder(content, placeholderContent, branchId, scopeId, placeholderBranchId) : content, catchContent, branchId, renderers);
3836
- const keepsMarks = state.keepsTryMarks(chunk, resumeWrites);
3837
- applyBranchStart(chunk, beforeBranch, keepsMarks);
3838
- if (!keepsMarks) return;
3839
- if (!writesRenderers) renderers();
3840
- $chunk.writeHTML(state.mark("]", scopeId + " " + accessor + " " + branchId));
3841
- }
3842
- function tryPlaceholder(content, placeholder, branchId, scopeId, placeholderBranchId) {
3843
- const chunk = $chunk;
3844
- const { boundary } = chunk;
3845
- const body = chunk.fork(boundary, null);
3846
- if (body === body.render(content)) {
3847
- chunk.append(body);
3848
- return;
3849
- }
3850
- chunk.next = chunk.forkRest(boundary);
3851
- captureContext(chunk);
3852
- chunk.placeholder = {
3853
- body,
3854
- render: placeholder,
3855
- branchId,
3856
- scopeId,
3857
- placeholderBranchId
3858
- };
3859
- }
3860
- function tryBoundary(content, catchContent, branchId, renderers) {
3861
- const chunk = $chunk;
3862
- const { boundary } = chunk;
3863
- const { state } = boundary;
3864
- const bodyBoundary = new Boundary(state, void 0, boundary);
3865
- if (catchContent) bodyBoundary.withinCatch = true;
3866
- const body = chunk.fork(bodyBoundary, null);
3867
- const bodyEnd = body.render(withBranchId, branchId, content);
3868
- if (bodyBoundary.aborted) {
3869
- if (!catchContent) throw bodyBoundary.reason;
3870
- catchContent(bodyBoundary.reason);
3871
- return true;
3872
- }
3873
- if (body === bodyEnd) {
3874
- chunk.append(body);
3875
- return false;
3876
- }
3877
- const renderersAtSettle = !bodyBoundary.resumeWrites;
3878
- const bodyNext = bodyEnd.next = chunk.forkRest(boundary);
3879
- chunk.next = body;
3880
- boundary.startAsync();
3881
- const reorderId = catchContent ? state.nextReorderId() : "";
3882
- if (reorderId) {
3883
- chunk.catchRange = {
3884
- id: reorderId,
3885
- end: bodyEnd
3886
- };
3887
- captureContext(chunk);
3888
- }
3889
- bodyBoundary.onNext = () => {
3890
- if (boundary.aborted) return;
3891
- if (bodyBoundary.aborted) {
3892
- if (!reorderId) {
3893
- boundary.abort(bodyBoundary.reason);
3894
- return;
3895
- }
3896
- const streamed = !chunk.catchRange;
3897
- const catchChunk = chunk.fork(boundary, null);
3898
- chunk.catchRange = null;
3899
- if (!renderersAtSettle) catchChunk.render(clearTryRenderers, branchId);
3900
- const inOrder = catchChunk === catchChunk.render(catchContent, bodyBoundary.reason);
3901
- if (boundary.aborted) return;
3902
- if (bodyEnd.consumed || !inOrder) catchChunk.reorderBranch = branchId;
3903
- if (bodyEnd.consumed) {
3904
- catchChunk.reorderId = reorderId;
3905
- state.reorder(catchChunk);
3906
- } else {
3907
- let reorder = null;
3908
- if (!inOrder) reorder = catchChunk;
3909
- else if (streamed) reorder = chunk.fork(boundary, null);
3910
- if (reorder) reorder.reorderId = reorderId;
3911
- const endMarker = state.mark("!", reorderId);
3912
- let cut = body;
3913
- while (cut.consumed) cut = cut.next;
3914
- cut.async = false;
3915
- cut.next = inOrder ? catchChunk : bodyNext;
3916
- cut.html = streamed ? endMarker : inOrder ? "" : state.mark("!^", reorderId) + endMarker;
3917
- cut.scripts = cut.effects = cut.lastEffect = "";
3918
- cut.placeholder = cut.reorderId = cut.catchRange = null;
3919
- cut.deferredReorder = reorder;
3920
- if (inOrder) catchChunk.next = bodyNext;
3921
- }
3922
- boundary.endAsync();
3923
- } else if (!bodyBoundary.count) {
3924
- if (renderersAtSettle && bodyBoundary.resumeWrites) bodyEnd.render(renderers);
3925
- chunk.catchRange = null;
3926
- boundary.endAsync();
3927
- } else boundary.onNext();
3928
- };
3929
- return renderersAtSettle;
3930
- }
3931
- function clearTryRenderers(branchId) {
3932
- writeScope(branchId, {
3933
- [CatchContent]: 0,
3934
- [PlaceholderContent]: _scope_with_id(branchId)["#PlaceholderContent"] && 0
3935
- });
3936
- }
3937
- function writeTryRenderers(branchId, catchContent, placeholderContent) {
3938
- writeScope(branchId, {
3939
- [CatchContent]: catchContent,
3940
- [PlaceholderContent]: placeholderContent
3941
- });
3942
- }
3943
- // src/html/compat.ts
3944
- const K_TAGS_API_STATE = Symbol();
3945
- const COMPAT_REGISTRY = /* @__PURE__ */ new WeakMap();
3946
- const compat = {
3947
- $global,
3948
- writeLoadAsset,
3949
- fork: ((scopeId, accessor, promise, content) => _await(scopeId, accessor, promise, (value) => {
3950
- const branchId = _peek_scope_id();
3951
- content(value);
3952
- if (_peek_scope_id() === branchId) _scope_id();
3953
- })),
3954
- write: _html,
3955
- writeScript,
3956
- nextScopeId: _scope_id,
3957
- peekNextScopeId: _peek_scope_id,
3958
- isInResumedBranch,
3959
- withChunk,
3960
- getChunk,
3961
- ensureState($global) {
3962
- let state = $global[K_TAGS_API_STATE] ||= getChunk()?.boundary.state;
3963
- if (!state) {
3964
- $global.runtimeId ||= "M";
3965
- $global.renderId ||= $global.componentIdPrefix || $global.widgetIdPrefix || "_";
3966
- $global[K_TAGS_API_STATE] = state = new State($global);
3967
- }
3968
- return state;
3969
- },
3970
- isTagsAPI(fn) {
3971
- return !!fn["id"];
3972
- },
3973
- onFlush(fn) {
3974
- const { flushHTML } = Chunk.prototype;
3975
- Chunk.prototype.flushHTML = function(boundary) {
3976
- const { state } = boundary;
3977
- const reorders = swapReorders(state, null);
3978
- fn(this);
3979
- swapReorders(state, reorders);
3980
- return flushHTML.call(this, boundary);
3981
- };
3982
- },
3983
- patchDynamicTag,
3984
- writeSetScopeForComponent(branchId, m5c, m5i) {
3985
- writeScope(branchId, {
3986
- m5c,
3987
- m5i
3988
- });
3989
- _script(branchId, SET_SCOPE_REGISTER_ID);
3990
- },
3991
- toJSON() {
3992
- return function toJSON() {
3993
- let compatRegistered = COMPAT_REGISTRY.get(this);
3994
- if (!compatRegistered) {
3995
- const registered = REGISTRY.get(this);
3996
- if (registered) {
3997
- const scopeId = registered.scope ? getScopeId(registered.scope) : void 0;
3998
- if (scopeId !== void 0) _script(scopeId, SET_SCOPE_REGISTER_ID);
3999
- COMPAT_REGISTRY.set(this, compatRegistered = [registered.id, scopeId]);
4000
- }
4001
- }
4002
- return compatRegistered;
4003
- };
4004
- },
4005
- joinChunks(chunks) {
4006
- let joined;
4007
- for (const chunk of chunks) {
4008
- if (chunk.boundary.aborted) continue;
4009
- if (joined) joined.append(chunk);
4010
- else joined = chunk;
4011
- }
4012
- return joined;
4013
- },
4014
- appendChunks(chunks) {
4015
- const chunk = getChunk();
4016
- for (const part of chunks) {
4017
- chunk.append(part);
4018
- if (part.effects) chunk.lastEffect = part.lastEffect;
4019
- }
4020
- },
4021
- deferReorders(reorders) {
4022
- const chunk = getChunk();
4023
- for (let i = reorders.length; i--;) {
4024
- const carrier = chunk.fork(chunk.boundary, chunk.next);
4025
- carrier.deferredReorder = reorders[i];
4026
- chunk.next = carrier;
4027
- }
4028
- },
4029
- createChunk($global) {
4030
- const state = this.ensureState($global);
4031
- return new Chunk(new Boundary(state), null, null, state);
4032
- },
4033
- flushScript(chunk, reorders) {
4034
- const { boundary } = chunk;
4035
- const { state } = boundary;
4036
- let html = "";
4037
- let scripts = "";
4038
- if (reorders) for (const reorder of reorders) state.reorder(reorder);
4039
- if (boundary.flush() === 0) ({html, scripts} = chunk.flush(boundary));
4040
- if (boundary.aborted) throw boundary.reason;
4041
- if (boundary.count) throw /* @__PURE__ */ new Error("Cannot serialize promise across tags/class compat layer.");
4042
- return {
4043
- html,
4044
- scripts
4045
- };
4046
- },
4047
- render(renderer, willRerender, classAPIOut, component, input, componentScopes, registerChildScope, parentChunk) {
4048
- if (parentChunk?.boundary.aborted) return;
4049
- const state = this.ensureState(classAPIOut.global);
4050
- const boundary = new Boundary(state, void 0, parentChunk?.boundary);
4051
- const context = getChunk()?.context ?? null;
4052
- let head = new Chunk(boundary, new Chunk(boundary, null, context, state), context, state);
4053
- let normalizedInput = input;
4054
- if ("renderBody" in input) {
4055
- normalizedInput = {};
4056
- for (const key in input) normalizedInput[key === "renderBody" ? "content" : key] = input[key];
4057
- }
4058
- const componentScope = new Chunk(boundary, null, context, state);
4059
- componentScope.render(() => {
4060
- if (this.hasPendingClassFunctions(classAPIOut.global)) drainClassFunctions(classAPIOut.global, (hostId) => {
4061
- const fnScopeId = _scope_id();
4062
- const scope = writeScope(fnScopeId, {
4063
- m5c: component.id,
4064
- m5h: hostId
4065
- });
4066
- _script(fnScopeId, SET_SCOPE_REGISTER_ID);
4067
- return scope;
4068
- });
4069
- if (willRerender || registerChildScope) {
4070
- const scopeId = _peek_scope_id();
4071
- writeScope(scopeId, { m5c: component.id });
4072
- _script(scopeId, SET_SCOPE_REGISTER_ID);
4073
- }
4074
- });
4075
- head.render(() => {
4076
- _set_scope_reason(willRerender ? ALL_GROUPS : 0);
4077
- try {
4078
- renderer(normalizedInput);
4079
- } finally {
4080
- _set_scope_reason(void 0);
4081
- }
4082
- const asyncOut = classAPIOut.beginAsync({
4083
- last: true,
4084
- timeout: -1
4085
- });
4086
- classAPIOut.onLast((next) => {
4087
- (boundary.onNext = () => {
4088
- if (boundary.aborted) {
4089
- boundary.onNext = NOOP;
4090
- if (parentChunk?.boundary.aborted) {
4091
- asyncOut.end();
4092
- next();
4093
- } else asyncOut.error(boundary.reason);
4094
- } else if (!boundary.count) {
4095
- boundary.onNext = NOOP;
4096
- const queued = swapReorders(state, null);
4097
- head = head.consume(boundary);
4098
- const reorders = swapReorders(state, queued);
4099
- if (reorders) asyncOut.writer.get("reorders").push(...reorders);
4100
- const heldEffects = head.takeHeldEffects();
4101
- if (heldEffects) {
4102
- head.effects = joinHeldEffects(heldEffects, head.effects);
4103
- head.lastEffect = "";
4104
- }
4105
- asyncOut.write(head.html);
4106
- asyncOut.script(head.scripts);
4107
- head.html = head.scripts = "";
4108
- asyncOut.writer.get("chunks").push(head);
4109
- asyncOut.end();
4110
- componentScopes.push(componentScope);
4111
- next();
4112
- }
4113
- })();
4114
- });
4115
- });
4116
- },
4117
- register,
4118
- registerRenderBody(fn) {
4119
- register(RENDER_BODY_ID, fn);
4120
- },
4121
- registerClassFunctions(input) {
4122
- for (const key in input) {
4123
- const value = input[key];
4124
- if (typeof value === "function" && !REGISTRY.has(value)) register(RENDER_BODY_ID, value);
4125
- }
4126
- },
4127
- registerClassFunction($global, id, fn, hostId) {
4128
- let pending = pendingClassFunctions.get($global);
4129
- if (!pending) pendingClassFunctions.set($global, pending = []);
4130
- pending.push([
4131
- id,
4132
- fn,
4133
- hostId
4134
- ]);
4135
- return fn;
4136
- },
4137
- hasPendingClassFunctions($global) {
4138
- return !!pendingClassFunctions.get($global)?.length;
4139
- }
4140
- };
4141
- const pendingClassFunctions = /* @__PURE__ */ new WeakMap();
4142
- function drainClassFunctions($global, writeScope) {
4143
- const pending = pendingClassFunctions.get($global);
4144
- const scopeByHost = {};
4145
- for (const [id, fn, hostId] of pending) register(id, fn, scopeByHost[hostId] ||= writeScope(hostId));
4146
- pending.length = 0;
4147
- }
4148
- function swapReorders(state, reorders) {
4149
- const { writeReorders } = state;
4150
- state.writeReorders = reorders;
4151
- return writeReorders;
4152
- }
4153
- function NOOP() {}
4154
- exports.$global = $global;
4155
- exports._assert_class_toggles = _assert_class_toggles;
4156
- exports._assert_hoist = _assert_hoist;
4157
- exports._attr = _attr;
4158
- exports._attr_and = _attr_and;
4159
- exports._attr_class = _attr_class;
4160
- exports._attr_content = _attr_content;
4161
- exports._attr_details_open = _attr_details_or_dialog_open;
4162
- exports._attr_dialog_open = _attr_details_or_dialog_open;
4163
- exports._attr_input_checked = _attr_input_checked;
4164
- exports._attr_input_checkedValue = _attr_input_checkedValue;
4165
- exports._attr_input_value = _attr_input_value;
4166
- exports._attr_nonce = _attr_nonce;
4167
- exports._attr_nullish = _attr_nullish;
4168
- exports._attr_option_value = _attr_option_value;
4169
- exports._attr_or = _attr_or;
4170
- exports._attr_select_value = _attr_select_value;
4171
- exports._attr_style = _attr_style;
4172
- exports._attr_textarea_value = _attr_textarea_value;
4173
- exports._attrs = _attrs;
4174
- exports._attrs_content = _attrs_content;
4175
- exports._attrs_partial = _attrs_partial;
4176
- exports._attrs_partial_content = _attrs_partial_content;
4177
- exports._attrs_select_value = _attrs_select_value;
4178
- exports._attrs_textarea_value = _attrs_textarea_value;
4179
- exports._await = _await;
4180
- exports._content = _content;
4181
- exports._content_resume = _content_resume;
4182
- Object.defineProperty(exports, "_dynamic_tag", {
4183
- enumerable: true,
4184
- get: function() {
4185
- return _dynamic_tag;
4186
- }
4187
- });
4188
- exports._el = _el;
4189
- exports._el_mark = _el_mark;
4190
- exports._el_read_error = _el_read_error;
4191
- exports._escape = _escape;
4192
- exports._escape_comment = _escape_comment;
4193
- exports._escape_script = _escape_script;
4194
- exports._escape_style = _escape_style;
4195
- exports._escape_style_value = _escape_style_value;
4196
- exports._existing_scope = _existing_scope;
4197
- exports._flush_head = _flush_head;
4198
- exports._for_in = _for_in;
4199
- exports._for_of = _for_of;
4200
- exports._for_to = _for_to;
4201
- exports._for_until = _for_until;
4202
- exports._hoist = _hoist;
4203
- exports._hoist_read_error = _hoist_read_error;
4204
- exports._html = _html;
4205
- exports._html_mark = _html_mark;
4206
- exports._id = _id;
4207
- exports._if = _if;
4208
- exports._peek_scope_id = _peek_scope_id;
4209
- exports._resume = _resume;
4210
- exports._resume_branch = _resume_branch;
4211
- exports._resume_locals = _resume_locals;
3
+ const require_control_flow = require("./html-DfZjMkhx.js");
4
+ exports.$global = require_control_flow.$global;
5
+ exports._assert_class_toggles = require_control_flow._assert_class_toggles;
6
+ exports._assert_hoist = require_control_flow._assert_hoist;
7
+ exports._attr = require_control_flow._attr;
8
+ exports._attr_and = require_control_flow._attr_and;
9
+ exports._attr_class = require_control_flow._attr_class;
10
+ exports._attr_content = require_control_flow._attr_content;
11
+ exports._attr_details_open = require_control_flow._attr_details_or_dialog_open;
12
+ exports._attr_dialog_open = require_control_flow._attr_details_or_dialog_open;
13
+ exports._attr_input_checked = require_control_flow._attr_input_checked;
14
+ exports._attr_input_checkedValue = require_control_flow._attr_input_checkedValue;
15
+ exports._attr_input_value = require_control_flow._attr_input_value;
16
+ exports._attr_nonce = require_control_flow._attr_nonce;
17
+ exports._attr_nullish = require_control_flow._attr_nullish;
18
+ exports._attr_option_value = require_control_flow._attr_option_value;
19
+ exports._attr_or = require_control_flow._attr_or;
20
+ exports._attr_select_value = require_control_flow._attr_select_value;
21
+ exports._attr_style = require_control_flow._attr_style;
22
+ exports._attr_textarea_value = require_control_flow._attr_textarea_value;
23
+ exports._attrs = require_control_flow._attrs;
24
+ exports._attrs_content = require_control_flow._attrs_content;
25
+ exports._attrs_partial = require_control_flow._attrs_partial;
26
+ exports._attrs_partial_content = require_control_flow._attrs_partial_content;
27
+ exports._attrs_select_value = require_control_flow._attrs_select_value;
28
+ exports._attrs_textarea_value = require_control_flow._attrs_textarea_value;
29
+ exports._await = require_control_flow._await;
30
+ exports._content = require_control_flow._content;
31
+ exports._content_resume = require_control_flow._content_resume;
32
+ exports._dynamic_tag = require_control_flow._dynamic_tag;
33
+ exports._el = require_control_flow._el;
34
+ exports._el_mark = require_control_flow._el_mark;
35
+ exports._el_read_error = require_control_flow._el_read_error;
36
+ exports._escape = require_control_flow._escape;
37
+ exports._escape_comment = require_control_flow._escape_comment;
38
+ exports._escape_script = require_control_flow._escape_script;
39
+ exports._escape_style = require_control_flow._escape_style;
40
+ exports._escape_style_value = require_control_flow._escape_style_value;
41
+ exports._existing_scope = require_control_flow._existing_scope;
42
+ exports._flush_head = require_control_flow._flush_head;
43
+ exports._for_in = require_control_flow._for_in;
44
+ exports._for_of = require_control_flow._for_of;
45
+ exports._for_to = require_control_flow._for_to;
46
+ exports._for_until = require_control_flow._for_until;
47
+ exports._hoist = require_control_flow._hoist;
48
+ exports._hoist_read_error = require_control_flow._hoist_read_error;
49
+ exports._html = require_control_flow._html;
50
+ exports._html_mark = require_control_flow._html_mark;
51
+ exports._id = require_control_flow._id;
52
+ exports._if = require_control_flow._if;
53
+ exports._peek_scope_id = require_control_flow._peek_scope_id;
54
+ exports._resume = require_control_flow._resume;
55
+ exports._resume_branch = require_control_flow._resume_branch;
56
+ exports._resume_locals = require_control_flow._resume_locals;
4212
57
  Object.defineProperty(exports, "_scope", {
4213
58
  enumerable: true,
4214
59
  get: function() {
4215
- return writeScope;
60
+ return require_control_flow.writeScope;
4216
61
  }
4217
62
  });
4218
- exports._scope_id = _scope_id;
4219
- exports._scope_reason = _scope_reason;
4220
- exports._scope_with_id = _scope_with_id;
4221
- exports._script = _script;
4222
- exports._set_scope_reason = _set_scope_reason;
4223
- exports._show_end = _show_end;
4224
- exports._show_start = _show_start;
4225
- exports._signal_read_error = _signal_read_error;
4226
- exports._style_html = _style_html;
4227
- exports._subscribe = _subscribe;
4228
- exports._template = _template;
4229
- exports._text_mark = _text_mark;
4230
- exports._textarea_value = _textarea_value;
4231
- exports._to_text = _to_text;
4232
- exports._trailers = _trailers;
4233
- exports._try = _try;
4234
- exports._unescaped = _unescaped;
4235
- exports._var = _var;
4236
- exports._write_guard = _write_guard;
4237
- exports._write_if = _write_if;
4238
- exports.attrTag = attrTag;
4239
- exports.attrTags = attrTags;
4240
- exports.compat = compat;
4241
- exports.forIn = forIn;
4242
- exports.forOf = forOf;
4243
- exports.forTo = forTo;
4244
- exports.forUntil = forUntil;
4245
- exports.withLoadAssets = withLoadAssets;
4246
- exports.withPageAssets = withPageAssets;
63
+ exports._scope_id = require_control_flow._scope_id;
64
+ exports._scope_reason = require_control_flow._scope_reason;
65
+ exports._scope_with_id = require_control_flow._scope_with_id;
66
+ exports._script = require_control_flow._script;
67
+ exports._set_scope_reason = require_control_flow._set_scope_reason;
68
+ exports._show_end = require_control_flow._show_end;
69
+ exports._show_start = require_control_flow._show_start;
70
+ exports._signal_read_error = require_control_flow._signal_read_error;
71
+ exports._style_html = require_control_flow._style_html;
72
+ exports._subscribe = require_control_flow._subscribe;
73
+ exports._template = require_control_flow._template;
74
+ exports._text_mark = require_control_flow._text_mark;
75
+ exports._textarea_value = require_control_flow._textarea_value;
76
+ exports._to_text = require_control_flow._to_text;
77
+ exports._trailers = require_control_flow._trailers;
78
+ exports._try = require_control_flow._try;
79
+ exports._unescaped = require_control_flow._unescaped;
80
+ exports._var = require_control_flow._var;
81
+ exports._write_guard = require_control_flow._write_guard;
82
+ exports._write_if = require_control_flow._write_if;
83
+ exports.attrTag = require_control_flow.attrTag;
84
+ exports.attrTags = require_control_flow.attrTags;
85
+ exports.forIn = require_control_flow.forIn;
86
+ exports.forOf = require_control_flow.forOf;
87
+ exports.forTo = require_control_flow.forTo;
88
+ exports.forUntil = require_control_flow.forUntil;
89
+ exports.withLoadAssets = require_control_flow.withLoadAssets;
90
+ exports.withPageAssets = require_control_flow.withPageAssets;