UNPKG

marko

Version:

Optimized runtime for Marko templates.

1,049 lines • 100 kB
let empty = [], rest = Symbol(), unsafeStyleAttrReg = /[\\;]/g, replaceUnsafeStyleAttr = (c) => c === ";" ? "\\3B " : "\\\\", toDelimitedString = function toDelimitedString(val, delimiter, stringify) { let str = "", sep = "", part; if (val) if (typeof val != "object") str += val; else if (Array.isArray(val)) for (let v of val) part = toDelimitedString(v, delimiter, stringify), part && (str += sep + part, sep = delimiter); else for (let name in val) part = stringify(name, val[name]), part && (str += sep + part, sep = delimiter); return str; }, unsafeXMLReg = /[<&]/g, replaceUnsafeXML = (c) => c === "&" ? "&amp;" : "&lt;", escapeXMLStr = (str) => unsafeXMLReg.test(str) ? str.replace(unsafeXMLReg, replaceUnsafeXML) : str, unsafeScriptReg = /<(\/?script|!--)/gi, escapeScriptStr = (str) => unsafeScriptReg.test(str) ? str.replace(unsafeScriptReg, "\\x3C$1") : str, unsafeStyleReg = /<(\/style)/gi, escapeStyleStr = (str) => unsafeStyleReg.test(str) ? str.replace(unsafeStyleReg, "\\3C$1") : str, unsafeCommentReg = />/g, escapeCommentStr = (str) => unsafeCommentReg.test(str) ? str.replace(unsafeCommentReg, "&gt;") : str, K_SCOPE_ID = Symbol("Scope ID"), kTouchedIterator = Symbol.for("marko.touchedIterator"), { hasOwnProperty } = {}, objectProto = Object.prototype, arrayProto = Array.prototype, Generator = (function* () {})().constructor, AsyncGenerator = (async function* () {})().constructor, REGISTRY = /* @__PURE__ */ new WeakMap(), KNOWN_SYMBOLS = (() => { let KNOWN_SYMBOLS = /* @__PURE__ */ new Map(); for (let name of Object.getOwnPropertyNames(Symbol)) { let symbol = Symbol[name]; typeof symbol == "symbol" && KNOWN_SYMBOLS.set(symbol, "Symbol." + name); } return KNOWN_SYMBOLS; })(), KNOWN_FUNCTIONS = /* @__PURE__ */ new Map([ [AggregateError, "AggregateError"], [Array, "Array"], [Array.from, "Array.from"], [Array.isArray, "Array.isArray"], [Array.of, "Array.of"], [ArrayBuffer, "ArrayBuffer"], [ArrayBuffer.isView, "ArrayBuffer.isView"], [Atomics.add, "Atomics.add"], [Atomics.and, "Atomics.and"], [Atomics.compareExchange, "Atomics.compareExchange"], [Atomics.exchange, "Atomics.exchange"], [Atomics.isLockFree, "Atomics.isLockFree"], [Atomics.load, "Atomics.load"], [Atomics.notify, "Atomics.notify"], [Atomics.or, "Atomics.or"], [Atomics.store, "Atomics.store"], [Atomics.sub, "Atomics.sub"], [Atomics.wait, "Atomics.wait"], [BigInt, "BigInt"], [BigInt.asIntN, "BigInt.asIntN"], [BigInt.asUintN, "BigInt.asUintN"], [BigInt64Array, "BigInt64Array"], [BigInt64Array.from, "BigInt64Array.from"], [BigInt64Array.of, "BigInt64Array.of"], [BigUint64Array, "BigUint64Array"], [BigUint64Array.from, "BigUint64Array.from"], [BigUint64Array.of, "BigUint64Array.of"], [Boolean, "Boolean"], [console.assert, "console.assert"], [console.clear, "console.clear"], [console.count, "console.count"], [console.countReset, "console.countReset"], [console.debug, "console.debug"], [console.dir, "console.dir"], [console.dirxml, "console.dirxml"], [console.error, "console.error"], [console.group, "console.group"], [console.groupCollapsed, "console.groupCollapsed"], [console.groupEnd, "console.groupEnd"], [console.info, "console.info"], [console.log, "console.log"], [console.table, "console.table"], [console.time, "console.time"], [console.timeEnd, "console.timeEnd"], [console.timeLog, "console.timeLog"], [console.timeStamp, "console.timeStamp"], [console.trace, "console.trace"], [console.warn, "console.warn"], [DataView, "DataView"], [Date, "Date"], [Date.now, "Date.now"], [Date.parse, "Date.parse"], [Date.UTC, "Date.UTC"], [decodeURI, "decodeURI"], [decodeURIComponent, "decodeURIComponent"], [encodeURI, "encodeURI"], [encodeURIComponent, "encodeURIComponent"], [Error, "Error"], [EvalError, "EvalError"], [Float32Array, "Float32Array"], [Float32Array.from, "Float32Array.from"], [Float32Array.of, "Float32Array.of"], [Float64Array, "Float64Array"], [Float64Array.from, "Float64Array.from"], [Float64Array.of, "Float64Array.of"], [Function, "Function"], [globalThis.atob, "atob"], [globalThis.btoa, "btoa"], [globalThis.clearImmediate, "clearImmediate"], [globalThis.clearInterval, "clearInterval"], [globalThis.clearTimeout, "clearTimeout"], [globalThis.crypto?.getRandomValues, "crypto.getRandomValues"], [globalThis.crypto?.randomUUID, "crypto.randomUUID"], [globalThis.fetch, "fetch"], [globalThis.performance?.now, "performance.now"], [globalThis.queueMicrotask, "queueMicrotask"], [globalThis.setImmediate, "setImmediate"], [globalThis.setInterval, "setInterval"], [globalThis.setTimeout, "setTimeout"], [globalThis.structuredClone, "structuredClone"], [globalThis.URL, "URL"], [globalThis.URLSearchParams, "URLSearchParams"], [globalThis.WritableStream, "WritableStream"], [Int16Array, "Int16Array"], [Int16Array.from, "Int16Array.from"], [Int16Array.of, "Int16Array.of"], [Int32Array, "Int32Array"], [Int32Array.from, "Int32Array.from"], [Int32Array.of, "Int32Array.of"], [Int8Array, "Int8Array"], [Int8Array.from, "Int8Array.from"], [Int8Array.of, "Int8Array.of"], [Intl.Collator, "Intl.Collator"], [Intl.DateTimeFormat, "Intl.DateTimeFormat"], [Intl.DisplayNames, "Intl.DisplayNames"], [Intl.getCanonicalLocales, "Intl.getCanonicalLocales"], [Intl.ListFormat, "Intl.ListFormat"], [Intl.Locale, "Intl.Locale"], [Intl.NumberFormat, "Intl.NumberFormat"], [Intl.PluralRules, "Intl.PluralRules"], [Intl.RelativeTimeFormat, "Intl.RelativeTimeFormat"], [Intl.Segmenter, "Intl.Segmenter"], [Intl.supportedValuesOf, "Intl.supportedValuesOf"], [isFinite, "isFinite"], [isNaN, "isNaN"], [JSON.parse, "JSON.parse"], [JSON.stringify, "JSON.stringify"], [Map, "Map"], [Map.groupBy, "Map.groupBy"], [Math.abs, "Math.abs"], [Math.acos, "Math.acos"], [Math.acosh, "Math.acosh"], [Math.asin, "Math.asin"], [Math.asinh, "Math.asinh"], [Math.atan, "Math.atan"], [Math.atan2, "Math.atan2"], [Math.atanh, "Math.atanh"], [Math.cbrt, "Math.cbrt"], [Math.ceil, "Math.ceil"], [Math.clz32, "Math.clz32"], [Math.cos, "Math.cos"], [Math.cosh, "Math.cosh"], [Math.exp, "Math.exp"], [Math.expm1, "Math.expm1"], [Math.floor, "Math.floor"], [Math.fround, "Math.fround"], [Math.hypot, "Math.hypot"], [Math.imul, "Math.imul"], [Math.log, "Math.log"], [Math.log10, "Math.log10"], [Math.log1p, "Math.log1p"], [Math.log2, "Math.log2"], [Math.max, "Math.max"], [Math.min, "Math.min"], [Math.pow, "Math.pow"], [Math.random, "Math.random"], [Math.round, "Math.round"], [Math.sign, "Math.sign"], [Math.sin, "Math.sin"], [Math.sinh, "Math.sinh"], [Math.sqrt, "Math.sqrt"], [Math.tan, "Math.tan"], [Math.tanh, "Math.tanh"], [Math.trunc, "Math.trunc"], [Number, "Number"], [Number.isFinite, "Number.isFinite"], [Number.isInteger, "Number.isInteger"], [Number.isNaN, "Number.isNaN"], [Number.isSafeInteger, "Number.isSafeInteger"], [Number.parseFloat, "Number.parseFloat"], [Number.parseInt, "Number.parseInt"], [Object, "Object"], [Object.assign, "Object.assign"], [Object.create, "Object.create"], [Object.defineProperties, "Object.defineProperties"], [Object.defineProperty, "Object.defineProperty"], [Object.entries, "Object.entries"], [Object.freeze, "Object.freeze"], [Object.fromEntries, "Object.fromEntries"], [Object.getOwnPropertyDescriptor, "Object.getOwnPropertyDescriptor"], [Object.getOwnPropertyDescriptors, "Object.getOwnPropertyDescriptors"], [Object.getOwnPropertyNames, "Object.getOwnPropertyNames"], [Object.getOwnPropertySymbols, "Object.getOwnPropertySymbols"], [Object.getPrototypeOf, "Object.getPrototypeOf"], [Object.is, "Object.is"], [Object.isExtensible, "Object.isExtensible"], [Object.isFrozen, "Object.isFrozen"], [Object.isSealed, "Object.isSealed"], [Object.keys, "Object.keys"], [Object.preventExtensions, "Object.preventExtensions"], [Object.seal, "Object.seal"], [Object.setPrototypeOf, "Object.setPrototypeOf"], [Object.values, "Object.values"], [parseFloat, "parseFloat"], [parseInt, "parseInt"], [Promise, "Promise"], [Proxy, "Proxy"], [RangeError, "RangeError"], [ReferenceError, "ReferenceError"], [Reflect.apply, "Reflect.apply"], [Reflect.construct, "Reflect.construct"], [Reflect.defineProperty, "Reflect.defineProperty"], [Reflect.deleteProperty, "Reflect.deleteProperty"], [Reflect.get, "Reflect.get"], [Reflect.getOwnPropertyDescriptor, "Reflect.getOwnPropertyDescriptor"], [Reflect.getPrototypeOf, "Reflect.getPrototypeOf"], [Reflect.has, "Reflect.has"], [Reflect.isExtensible, "Reflect.isExtensible"], [Reflect.ownKeys, "Reflect.ownKeys"], [Reflect.preventExtensions, "Reflect.preventExtensions"], [Reflect.set, "Reflect.set"], [Reflect.setPrototypeOf, "Reflect.setPrototypeOf"], [RegExp, "RegExp"], [Set, "Set"], [String, "String"], [String.fromCharCode, "String.fromCharCode"], [String.fromCodePoint, "String.fromCodePoint"], [String.raw, "String.raw"], [Symbol, "Symbol"], [Symbol.for, "Symbol.for"], [SyntaxError, "SyntaxError"], [TypeError, "TypeError"], [Uint16Array, "Uint16Array"], [Uint16Array.from, "Uint16Array.from"], [Uint16Array.of, "Uint16Array.of"], [Uint32Array, "Uint32Array"], [Uint32Array.from, "Uint32Array.from"], [Uint32Array.of, "Uint32Array.of"], [Uint8Array, "Uint8Array"], [Uint8Array.from, "Uint8Array.from"], [Uint8Array.of, "Uint8Array.of"], [Uint8ClampedArray, "Uint8ClampedArray"], [Uint8ClampedArray.from, "Uint8ClampedArray.from"], [Uint8ClampedArray.of, "Uint8ClampedArray.of"], [URIError, "URIError"], [WeakMap, "WeakMap"], [WeakSet, "WeakSet"] ]), KNOWN_OBJECTS = /* @__PURE__ */ new Map([ [Atomics, "Atomics"], [console, "console"], [globalThis, "globalThis"], [globalThis.crypto, "crypto"], [Intl, "Intl"], [JSON, "JSON"], [Math, "Math"], [Reflect, "Reflect"] ]), unsafeRegExpSourceReg = /\\[\s\S]|[<\0\ud800-\udfff]/gu, unsafeRegExpSourceDetect = /[<\0\ud800-\udfff]/u, replaceUnsafeRegExpSourceChar = (match) => { let ch = match.length === 3 ? "" : match[match.length - 1]; if (ch === "<") return "\\x3C"; if (ch === "\0") return "\\x00"; let code = ch.charCodeAt(0); return code >= 55296 && code <= 57343 ? "\\u" + code.toString(16).padStart(4, "0") : match; }, unsafeQuoteReg = /["\\<\n\r\u2028\u2029\0\ud800-\udfff]/u, $chunk, kPendingContexts = Symbol("Pending Contexts"), kBranchId = Symbol("Branch Id"), kIsAsync = Symbol("Is Async"), writeScope = (scopeId, partialScope) => { let { state } = $chunk.boundary, target = $chunk.serializeState, scope = scopeWithId(state, scopeId), pending = target.writeScopes[scopeId]; return state.needsMainRuntime = !0, Object.assign(scope, partialScope), pending && pending !== partialScope ? Object.assign(pending, partialScope) : target.writeScopes[scopeId] = partialScope, target.flushScopes = !0, scope; }, NOOP$2 = () => {}, tick = globalThis.setImmediate || globalThis.setTimeout || globalThis.queueMicrotask || ((cb) => Promise.resolve().then(cb)), tickQueue, kSelectedValue = Symbol("selectedValue"), checkedValuesRefs = /* @__PURE__ */ new WeakMap(), singleQuoteAttrReplacements = /'|&(?=[#a-zA-Z])/g, doubleQuoteAttrReplacements = /"|&(?=[#a-zA-Z])/g, needsQuotedAttr = /["'>\s]|&[#a-zA-Z]|\/$/g, voidElementsReg = /^(?:area|b(?:ase|r)|col|embed|hr|i(?:mg|nput)|link|meta|param|source|track|wbr)$/, _dynamic_tag = (scopeId, accessor, tag, inputOrArgs, content, inputIsArgs, serializeReason) => { let shouldResume = serializeReason !== 0, renderer = normalizeDynamicRenderer(tag), state = getState(), branchId = _peek_scope_id(), rendered, result; if (typeof renderer == "string") { let input = (inputIsArgs ? inputOrArgs[0] : inputOrArgs) || {}; rendered = !0, (() => { if (_scope_id(), _html(`<${renderer}${_attrs(input, "a", branchId, renderer)}>`), !voidElementsReg.test(renderer)) { let renderContent = content || normalizeDynamicRenderer(input.content); if (renderer === "textarea") _html(_attr_textarea_value(branchId, "a", input.value, input.valueChange, 1)); else if (renderContent) { if (typeof renderContent != "function") throw Error(`Body content is not supported for the \`<${renderer}>\` tag.`); renderer === "select" && ("value" in input || "valueChange" in input) ? _attr_select_value(branchId, "a", input.value, input.valueChange, renderContent, 1) : _dynamic_tag(branchId, "a", renderContent, void 0, 0, void 0, serializeReason); } _html(`</${renderer}>`); } let childScope = getScopeById(branchId), needsScript = childScope && (childScope.Ia || childScope.Ea); needsScript && _script(branchId, "d"), (shouldResume || needsScript) && _html(state.mark("'", scopeId + " " + accessor + " " + branchId)); })(); } else { shouldResume && _html(state.mark("[", "")); let render = () => { if (renderer) try { return _set_serialize_reason(shouldResume && inputOrArgs !== void 0 ? 1 : 0), inputIsArgs ? renderer(...inputOrArgs) : renderer(content ? { ...inputOrArgs, content } : inputOrArgs); } finally { _set_serialize_reason(void 0); } else if (content) return content(); }; result = shouldResume ? withBranchId(branchId, render) : render(), rendered = _peek_scope_id() !== branchId, shouldResume && _html(state.mark("]", scopeId + " " + accessor + (rendered ? " " + branchId : ""))); } return rendered ? shouldResume && writeScope(scopeId, { ["D" + accessor]: renderer?.a || renderer }) : _scope_id(), result; }, patchDynamicTag = ((originalDynamicTag) => (patch) => { _dynamic_tag = (scopeId, accessor, tag, input, content, inputIsArgs, resume) => { let patched = patch(tag, scopeId, accessor); return patched !== tag && (patched.a = tag), originalDynamicTag(scopeId, accessor, patched, input, content, inputIsArgs, resume); }; })(_dynamic_tag), CONSUMED_RESULT_MESSAGE = "Cannot read from a consumed render result", _template = (templateId, renderer, page) => (renderer.render = render, renderer.i = !page, renderer._ = renderer, _content_resume(templateId, renderer)), kAssets = Symbol(), kBlockIndex = Symbol(), kDeferIndex = Symbol(), assetFlush, SET_SCOPE_REGISTER_ID = "$C_s", K_TAGS_API_STATE = Symbol(), COMPAT_REGISTRY = /* @__PURE__ */ new WeakMap(), compat = { $global, fork: _await, write: _html, writeScript, nextScopeId: _scope_id, peekNextScopeId: _peek_scope_id, isInResumedBranch, ensureState($global) { let state = $global[K_TAGS_API_STATE] ||= getChunk()?.boundary.state; return state || ($global.runtimeId ||= "M", $global.renderId ||= $global.componentIdPrefix || $global.widgetIdPrefix || "_", $global[K_TAGS_API_STATE] = state = new State($global)), state; }, isTagsAPI(fn) { return !!fn.a; }, onFlush(fn) { let { flushHTML } = Chunk.prototype; Chunk.prototype.flushHTML = function() { return fn(this), flushHTML.call(this); }; }, patchDynamicTag, writeSetScopeForComponent(branchId, m5c, m5i) { writeScope(branchId, { m5c, m5i }), _script(branchId, SET_SCOPE_REGISTER_ID); }, toJSON() { return function() { let compatRegistered = COMPAT_REGISTRY.get(this); if (!compatRegistered) { let registered = getRegistered(this); if (registered) { let scopeId = registered.scope ? getScopeId(registered.scope) : void 0; scopeId !== void 0 && _script(scopeId, SET_SCOPE_REGISTER_ID), COMPAT_REGISTRY.set(this, compatRegistered = [registered.id, scopeId]); } } return compatRegistered; }; }, flushScript($global) { let state = this.ensureState($global), boundary = new Boundary(state); if (boundary.flush() === 1) throw Error("Cannot serialize promise across tags/class compat layer."); return new Chunk(boundary, null, null, state).flushScript().scripts; }, render(renderer, willRerender, classAPIOut, component, input, completeChunks, registerChildScope) { let state = this.ensureState(classAPIOut.global), boundary = new Boundary(state), head = new Chunk(boundary, null, getChunk()?.context ?? null, state), normalizedInput = input; if ("renderBody" in input) { normalizedInput = {}; for (let key in input) normalizedInput[key === "renderBody" ? "content" : key] = input[key]; } head.render(() => { if (willRerender || registerChildScope) { let scopeId = _peek_scope_id(); writeScope(scopeId, { m5c: component.id }), _script(scopeId, SET_SCOPE_REGISTER_ID); } _set_serialize_reason(+!!willRerender); try { renderer(normalizedInput); } finally { _set_serialize_reason(void 0); } let asyncOut = classAPIOut.beginAsync({ last: !0, timeout: -1 }); classAPIOut.onLast((next) => { (boundary.onNext = () => { boundary.signal.aborted ? (asyncOut.error(boundary.signal.reason), boundary.onNext = NOOP) : boundary.count || (boundary.onNext = NOOP, head = head.consume(), asyncOut.write(head.html), asyncOut.script(head.scripts), asyncOut.end(), head.html = head.scripts = "", completeChunks.push(head), next()); })(); }); }); }, register, registerRenderBody(fn) { register("$C_b", fn); } }; //#region src/common/attr-tag.ts function attrTag(attrs) { return attrs[Symbol.iterator] = attrTagIterator, attrs[rest] = empty, attrs; } function attrTags(first, attrs) { return first ? (first[rest] === empty ? first[rest] = [attrs] : first[rest].push(attrs), first) : attrTag(attrs); } function* attrTagIterator() { yield this, yield* this[rest]; } //#endregion //#region src/common/helpers.ts function stringifyClassObject(name, value) { return value ? name : ""; } function stringifyStyleObject(name, value) { return value || value === 0 ? escapeStyleAttr(name) + ":" + escapeStyleAttr(value + "") : ""; } function escapeStyleAttr(str) { return unsafeStyleAttrReg.test(str) ? str.replace(unsafeStyleAttrReg, replaceUnsafeStyleAttr) : str; } function escapeStyleValue(str) { let closers = "", result = str.replace(/[\\"'{};<>]|\/(?=\*)/g, (c) => c === "<" ? "\\3C " : c === ";" ? "\\3B " : c === "{" ? "\\7B " : "\\" + c); for (let c of result) c === "(" ? closers = ")" + closers : c === "[" ? closers = "]" + closers : c === closers[0] && (closers = closers.slice(1)); return result + closers; } function isEventHandler(name) { return /^on[A-Z-]/.test(name); } function getEventHandlerName(name) { return name[2] === "-" ? name.slice(3) : name.slice(2).toLowerCase(); } function isVoid(value) { return value == null || value === !1; } function isNotVoid(value) { return value != null && value !== !1; } function isPromise(value) { return value != null && typeof value.then == "function"; } function normalizeDynamicRenderer(value) { if (value) { if (typeof value == "string") return value; let normalized = value.content || value.default || value; if ("a" in normalized) return normalized; } } //#endregion //#region src/common/errors.ts function _el_read_error() {} function _hoist_read_error() {} function _assert_hoist(value) {} //#endregion //#region src/html/content.ts function _to_text(val) { return val || val === 0 ? val + "" : ""; } function _unescaped(val) { return val ? val + "" : val === 0 ? "0" : ""; } function _escape(val) { return val ? escapeXMLStr(val + "") : val === 0 ? "0" : ""; } function _escape_script(val) { return val ? escapeScriptStr(val + "") : val === 0 ? "0" : ""; } function _escape_style(val) { return val ? escapeStyleStr(val + "") : val === 0 ? "0" : ""; } function _escape_style_value(val) { return val || val === 0 ? escapeStyleValue(val + "") : ""; } function _escape_comment(val) { return val ? escapeCommentStr(val + "") : val === 0 ? "0" : ""; } patchIteratorNext(Generator.prototype), patchIteratorNext(AsyncGenerator.prototype); var State$1 = class { ids = 0; flush = 0; wroteUndefined = !1; buf = []; strs = /* @__PURE__ */ new Map(); refs = /* @__PURE__ */ new WeakMap(); assigned = /* @__PURE__ */ new Set(); boundary = void 0; channel = void 0; channelDeps = null; mutated = []; }, Reference = class { assigns = null; calls = null; scopeId = void 0; channel = void 0; parent; accessor; flush; pos; id; constructor(parent, accessor, flush, pos = null, id = null) { this.parent = parent, this.accessor = accessor, this.flush = flush, this.pos = pos, this.id = id; } }, Serializer = class { #state = new State$1(); pending(channel) { return hasMatchingMutations(this.#state.mutated, channel?.readyId); } pendingReadyChannel() { for (let mutation of this.#state.mutated) if (mutation.channel?.readyId) return mutation.channel; } stringifyScopes(flushes, boundary, channel) { try { return this.#state.boundary = boundary, this.#state.channel = channel, writeScopesRoot(this.#state, flushes); } finally { this.#state.flush++, this.#state.buf = []; } } written(val) { return this.#state.refs.has(val); } takeChannelDeps() { let deps = this.#state.channelDeps; return this.#state.channelDeps = null, deps; } writeCall(value, object, property, channel) { this.#state.mutated.push({ value, object, property, channel }); } }; function register(id, val, scope) { return REGISTRY.set(val, { id, scope, access: "_._" + toAccess(toObjectKey(id)) }), val; } function getRegistered(val) { let registered = REGISTRY.get(val); if (registered) return { id: registered.id, scope: registered.scope }; } function writeScopesRoot(state, flushes) { let { buf } = state, nextSlotId = -1, fillIndex = -1; for (let flush of flushes) { let scopeId = flush[0], scope = flush[1], ref = state.refs.get(scope) || newScopeReference(state, scope, scopeId), openIndex = buf.push("") - 1; writeObjectProps(state, flush[2], ref) ? (buf[openIndex] = nextSlotId === -1 ? "[" + scopeId + ",{" : (scopeId === nextSlotId ? "" : "," + (scopeId - nextSlotId)) + ",{", fillIndex === -1 && (fillIndex = openIndex), nextSlotId = scopeId + 1, buf.push("}")) : buf.pop(); } nextSlotId !== -1 && buf.push("]"); let extras = ""; (state.assigned.size || hasChannelMutations(state)) && (extras = ",0)", fillIndex !== -1 && (buf[fillIndex] = "_(" + buf[fillIndex], buf.push(")")), writeAssigned(state)); let result = extras && "("; for (let chunk of buf) result += chunk; return result += extras, result ? state.wroteUndefined ? (state.wroteUndefined = !1, "(_,$)=>" + result) : "_=>" + result : ""; } function writeAssigned(state) { let sep = state.buf.length ? "," : ""; if (state.assigned.size) { let assigned = state.assigned; state.assigned = /* @__PURE__ */ new Set(); let buf = "", hasCalls = !1; for (let ref of assigned) ref.assigns && (buf += sep + assignsToString(ref.assigns, ref.id), ref.assigns = null, sep = ","), hasCalls ||= ref.calls !== null; if (buf && state.buf.push(buf), hasCalls) { for (let ref of assigned) if (ref.calls) { for (let { method, args } of ref.calls) { state.buf.push((state.buf.length ? "," : "") + ref.id + "." + method + "("); for (let a = 0; a < args.length; a++) a && state.buf.push(","), writeCallArg(state, args[a]); state.buf.push(")"); } ref.calls = null; } } } if (hasChannelMutations(state)) { let remaining = []; for (let mutation of state.mutated) { if (!mutationMatchesReadyId(mutation, state.channel?.readyId)) { remaining.push(mutation); continue; } let hasSeen = state.refs.get(mutation.object)?.id, objectStartIndex = state.buf.push(state.buf.length === 0 ? "" : ","); if (writeProp(state, mutation.object, null, "")) { let objectRef = state.refs.get(mutation.object); objectRef && objectRef.scopeId === void 0 && (objectRef.id ? hasSeen || (state.buf[objectStartIndex] = "(" + state.buf[objectStartIndex], state.buf.push(")")) : (objectRef.id = nextRefAccess(state), state.buf[objectStartIndex] = "(" + objectRef.id + "=" + state.buf[objectStartIndex], state.buf.push(")"))); } else state.buf.push("void 0"); let valueStartIndex = state.buf.push(toAccess(toObjectKey(mutation.property)) + "("); if (mutation.value !== void 0) if (writeProp(state, mutation.value, null, "")) { let valueRef = typeof mutation.value == "string" ? state.strs.get(mutation.value) : state.refs.get(mutation.value); valueRef && !valueRef.id && valueRef.scopeId === void 0 && (valueRef.id = mutation.valueId || nextRefAccess(state), state.buf[valueStartIndex] = valueRef.id + "=" + state.buf[valueStartIndex]); } else state.buf.push("void 0"); state.buf.push(")"); } state.mutated = remaining; } state.assigned.size && writeAssigned(state); } function writeCallArg(state, val) { val === void 0 ? (state.wroteUndefined = !0, state.buf.push("$")) : writeProp(state, val, null, "") || state.buf.push("void 0"); } function hasChannelMutations(state) { return hasMatchingMutations(state.mutated, state.channel?.readyId); } function hasMatchingMutations(mutated, readyId) { for (let mutation of mutated) if (mutationMatchesReadyId(mutation, readyId)) return !0; return !1; } function mutationMatchesReadyId(mutation, readyId) { return mutation.channel?.readyId ? mutation.channel.readyId === readyId : !readyId; } function writeProp(state, val, parent, accessor) { switch (typeof val) { case "string": return writeString(state, val, parent, accessor); case "number": return writeNumber(state, val); case "boolean": return writeBoolean(state, val); case "bigint": return writeBigInt(state, val); case "symbol": return writeSymbol(state, val, parent, accessor); case "function": return writeFunction(state, val, parent, accessor); case "object": return writeObject(state, val, parent, accessor); default: return !1; } } function writeReferenceOr(state, write, val, parent, accessor) { let ref = state.refs.get(val); if (ref) return trackChannel(state, ref) ? parent && isCircular(parent, ref) ? (ensureId(state, ref), state.assigned.add(ref), addAssignment(ref, accessId(state, parent) + toAccess(accessor)), !1) : (state.buf.push(ensureId(state, ref)), !0) : !1; let registered = REGISTRY.get(val); return registered ? writeRegistered(state, val, parent, accessor, registered) : (state.refs.set(val, ref = new Reference(parent, accessor, state.flush, state.buf.length)), ref.channel = state.channel, write(state, val, ref) ? !0 : (state.refs.delete(val), !1)); } function trackScope(state, val, scopeId) { let ref = state.refs.get(val); ref ? trackChannel(state, ref) : newScopeReference(state, val, scopeId); } function newScopeReference(state, val, scopeId) { let ref = new Reference(null, null, state.flush); return ref.scopeId = scopeId, ref.channel = state.channel, state.refs.set(val, ref), ref; } function writeRegistered(state, val, parent, accessor, registered) { let { scope } = registered; if (scope) { let ref = new Reference(parent, accessor, state.flush, state.buf.length); ref.channel = state.channel, state.refs.set(val, ref); let scopeId = scope[K_SCOPE_ID]; trackScope(state, scope, scopeId), state.buf.push("_(" + scopeId + "," + quote(registered.id, 0) + ")"); } else state.buf.push(registered.access); return !0; } function writeString(state, val, parent, accessor) { if (val.length > 12) { let ref = state.strs.get(val); if (ref) { if (trackChannel(state, ref)) return state.buf.push(ensureId(state, ref)), !0; } else { let ref = new Reference(parent, accessor, state.flush, state.buf.length); ref.channel = state.channel, state.strs.set(val, ref); } } return state.buf.push(quote(val, 0)), !0; } function writeNumber(state, val) { return state.buf.push(val + ""), !0; } function writeBoolean(state, val) { return state.buf.push(val ? "!0" : "!1"), !0; } function writeBigInt(state, val) { return state.buf.push(val + "n"), !0; } function writeFunction(state, val, parent, accessor) { let wellKnownFunction = KNOWN_FUNCTIONS.get(val); return wellKnownFunction ? (state.buf.push(wellKnownFunction), !0) : writeReferenceOr(state, writeNever, val, parent, accessor); } function writeSymbol(state, val, parent, accessor) { let wellKnownSymbol = KNOWN_SYMBOLS.get(val); if (wellKnownSymbol) return state.buf.push(wellKnownSymbol), !0; let key = Symbol.keyFor(val); return key === void 0 ? writeReferenceOr(state, writeUnknownSymbol, val, parent, accessor) : (state.buf.push("Symbol.for(" + quote(key, 0) + ")"), !0); } function writeUnknownSymbol(state) { return state.buf.push("Symbol()"), !0; } function writeNever(state, val, ref) { return !1; } function writeNull(state) { return state.buf.push("null"), !0; } function writeObject(state, val, parent, accessor) { if (val === null) return writeNull(state); let scopeId = val[K_SCOPE_ID]; if (scopeId !== void 0) return trackScope(state, val, scopeId), state.buf.push("_(" + scopeId + ")"), !0; let wellKnownObject = KNOWN_OBJECTS.get(val); return wellKnownObject ? (state.buf.push(wellKnownObject), !0) : writeReferenceOr(state, writeUnknownObject, val, parent, accessor); } function writeUnknownObject(state, val, ref) { let proto = Object.getPrototypeOf(val); if (proto === objectProto) return writePlainObject(state, val, ref); if (proto === arrayProto) return writeArray(state, val, ref); switch (proto?.constructor) { case void 0: return writeNullObject(state, val, ref); case Object: return writePlainObject(state, val, ref); case Array: return writeArray(state, val, ref); case Date: return writeDate(state, val); case RegExp: return writeRegExp(state, val); case Promise: return writePromise(state, val, ref); case Map: return writeMap(state, val, ref); case Set: return writeSet(state, val, ref); case Generator: return writeGenerator(state, val, ref); case AsyncGenerator: return writeAsyncGenerator(state, val, ref); case Error: case EvalError: case RangeError: case ReferenceError: case SyntaxError: case TypeError: case URIError: return writeError(state, val, ref); case AggregateError: return writeAggregateError(state, val, ref); case ArrayBuffer: return writeArrayBuffer(state, val); case Int8Array: case Uint8Array: case Uint8ClampedArray: case Int16Array: case Uint16Array: case Int32Array: case Uint32Array: case Float32Array: case Float64Array: case BigInt64Array: case BigUint64Array: return writeTypedArray(state, val, ref); case DataView: return writeDataView(state, val, ref); case WeakSet: return writeWeakSet(state); case WeakMap: return writeWeakMap(state); case globalThis.URL: return writeURL(state, val); case globalThis.URLSearchParams: return writeURLSearchParams(state, val); case globalThis.Headers: return writeHeaders(state, val); case globalThis.FormData: return writeFormData(state, val, ref); case globalThis.ReadableStream: return writeReadableStream(state, val, ref); case globalThis.Request: return writeRequest(state, val, ref); case globalThis.Response: return writeResponse(state, val, ref); case globalThis.Intl?.NumberFormat: return writeIntl(state, val, "NumberFormat", ref); case globalThis.Intl?.DateTimeFormat: return writeIntl(state, val, "DateTimeFormat", ref); case globalThis.Intl?.Collator: return writeIntl(state, val, "Collator", ref); case globalThis.Intl?.PluralRules: return writeIntl(state, val, "PluralRules", ref); case globalThis.Intl?.RelativeTimeFormat: return writeIntl(state, val, "RelativeTimeFormat", ref); case globalThis.Intl?.ListFormat: return writeIntl(state, val, "ListFormat", ref); case globalThis.Intl?.DisplayNames: return writeIntl(state, val, "DisplayNames", ref); case globalThis.Intl?.Segmenter: return writeIntl(state, val, "Segmenter", ref); case globalThis.Intl?.DurationFormat: return writeIntl(state, val, "DurationFormat", ref); case globalThis.Intl?.Locale: return writeIntlLocale(state, val); case globalThis.Temporal?.Instant: return writeTemporal(state, val, "Instant"); case globalThis.Temporal?.Duration: return writeTemporal(state, val, "Duration"); case globalThis.Temporal?.PlainDate: return writeTemporal(state, val, "PlainDate"); case globalThis.Temporal?.PlainDateTime: return writeTemporal(state, val, "PlainDateTime"); case globalThis.Temporal?.PlainMonthDay: return writeTemporal(state, val, "PlainMonthDay"); case globalThis.Temporal?.PlainTime: return writeTemporal(state, val, "PlainTime"); case globalThis.Temporal?.PlainYearMonth: return writeTemporal(state, val, "PlainYearMonth"); case globalThis.Temporal?.ZonedDateTime: return writeTemporal(state, val, "ZonedDateTime"); } return !1; } function writePlainObject(state, val, ref) { return state.buf.push("{"), writeMaybeIterableProps(state, val, ref), state.buf.push("}"), !0; } function writeArray(state, val, ref) { let sep = "["; for (let i = 0; i < val.length; i++) { let item = val[i]; state.buf.push(sep), sep = ",", item === void 0 ? (state.wroteUndefined = !0, state.buf.push("$")) : writeProp(state, item, ref, "" + i); } return sep === "[" ? state.buf.push("[]") : state.buf.push("]"), !0; } function writeDate(state, val) { return state.buf.push("new Date(" + +val + ")"), !0; } function writeRegExp(state, val) { let { source } = val; return state.buf.push("/" + (unsafeRegExpSourceDetect.test(source) ? source.replace(unsafeRegExpSourceReg, replaceUnsafeRegExpSourceChar) : source) + "/" + val.flags), !0; } function writePromise(state, val, ref) { let { boundary, channel } = state; if (!boundary) return !1; let pId = nextRefAccess(state), handle = newAsyncHandle(state, ref, pId); return state.buf.push("(p=>p=new Promise((f,r)=>" + pId + "={f,r(e){p.catch(_=>0);r(e)}}))()"), val.then((v) => writeAsyncCall(state, boundary, handle, "f", v, channel, pId), (v) => writeAsyncCall(state, boundary, handle, "r", v, channel, pId)), boundary.startAsync(), !0; } function newAsyncHandle(state, parent, id) { let handle = {}, handleRef = new Reference(parent, null, state.flush, null, id); return handleRef.channel = state.channel, state.refs.set(handle, handleRef), handle; } function writeMap(state, val, ref) { if (!val.size) return state.buf.push("new Map"), !0; let items = [], assigns, needsId, deferring = !1, i = 0; if (val.size < 25) { for (let [itemKey, itemValue] of val) { if (!deferring && (itemKey !== val && isAncestorMember(state, ref, itemKey) || itemValue !== val && isAncestorMember(state, ref, itemValue)) && (deferring = !0), deferring) { deferCall(state, ref, "set", [itemKey, itemValue]); continue; } itemKey === val && (itemKey = void 0, (assigns ||= []).push("a[" + i + "][0]")), itemValue === val && (itemValue = void 0, (assigns ||= []).push("a[" + i + "][1]")), needsId ||= isDedupedMember(itemKey) || isDedupedMember(itemValue), i = items.push(itemValue === void 0 ? itemKey === void 0 ? [] : [itemKey] : [itemKey, itemValue]); } writeArrayArg(state, ref, items, assigns && "((m,a)=>(" + assignsToString(assigns, "m") + ",a.forEach(i=>m.set(i[0],i[1])),m))(new Map,", "new Map(", needsId); } else { for (let [itemKey, itemValue] of val) { if (!deferring && (itemKey !== val && isAncestorMember(state, ref, itemKey) || itemValue !== val && isAncestorMember(state, ref, itemValue)) && (deferring = !0), deferring) { deferCall(state, ref, "set", [itemKey, itemValue]); continue; } itemKey === val && (itemKey = 0, (assigns ||= []).push("a[" + i + "]")), itemValue === val && (itemValue = 0, (assigns ||= []).push("a[" + (i + 1) + "]")), needsId ||= isDedupedMember(itemKey) || isDedupedMember(itemValue), i = items.push(itemKey, itemValue); } writeArrayArg(state, ref, items, assigns && "(a=>a.reduce((m,v,i)=>i%2?m:m.set(v,a[i+1])," + assignsToString(assigns, "new Map") + "))(", "(a=>a.reduce((m,v,i)=>i%2?m:m.set(v,a[i+1]),new Map))(", needsId); } return !0; } function writeSet(state, val, ref) { if (!val.size) return state.buf.push("new Set"), !0; let items = [], assigns, needsId, deferring = !1, i = 0; for (let item of val) { if (!deferring && item !== val && isAncestorMember(state, ref, item) && (deferring = !0), deferring) { deferCall(state, ref, "add", [item]); continue; } item === val ? (item = 0, (assigns ||= []).push("i[" + i + "]")) : needsId ||= isDedupedMember(item), i = items.push(item); } return writeArrayArg(state, ref, items, assigns && "((s,i)=>(" + assignsToString(assigns, "s") + ",i.forEach(i=>s.add(i)),s))(new Set,", "new Set(", needsId), !0; } function isAncestorMember(state, container, member) { if (member === null || typeof member != "object" && typeof member != "function") return !1; let ref = state.refs.get(member); return ref !== void 0 && isCircular(container, ref); } function deferCall(state, ref, method, args) { ensureId(state, ref), (ref.calls ||= []).push({ method, args }), state.assigned.add(ref); } function writeArrayArg(state, ref, items, assignsPrefix, plainPrefix, needsId) { if (assignsPrefix || needsId) { let arrayRef = new Reference(ref, null, state.flush, null, nextRefAccess(state)); state.buf.push((assignsPrefix || plainPrefix) + arrayRef.id + "="), writeArray(state, items, arrayRef); } else state.buf.push(plainPrefix), writeArray(state, items, new Reference(ref, null, state.flush, state.buf.length)); state.buf.push(")"); } function isDedupedMember(val) { switch (typeof val) { case "object": return val !== null && val[K_SCOPE_ID] === void 0; case "function": case "symbol": return !0; case "string": return val.length > 12; default: return !1; } } function canWriteBuffer(state, buffer, ref) { return Object.getPrototypeOf(buffer)?.constructor === ArrayBuffer; } function writeDataView(state, val, ref) { let { buffer } = val; if (!canWriteBuffer(state, buffer, ref)) return !1; let needsLength = val.byteOffset + val.byteLength < buffer.byteLength; return state.buf.push("new DataView("), writeProp(state, buffer, ref, "buffer"), state.buf.push((val.byteOffset || needsLength ? "," + val.byteOffset + (needsLength ? "," + val.byteLength : "") : "") + ")"), !0; } function writeArrayBuffer(state, val) { let result; if (val.byteLength) { let view = new Int8Array(val); result = hasOnlyZeros(view) ? "new ArrayBuffer(" + val.byteLength + ")" : "new Int8Array(" + typedArrayToInitString(view) + ").buffer"; } else result = "new ArrayBuffer"; return state.buf.push(result), !0; } function writeTypedArray(state, val, ref) { if (val.byteOffset || val.byteLength < val.buffer.byteLength || state.refs.has(val.buffer)) { if (!canWriteBuffer(state, val.buffer, ref)) return !1; let needsLength = val.byteOffset + val.byteLength < val.buffer.byteLength; state.buf.push("new " + val.constructor.name + "("), writeProp(state, val.buffer, ref, "buffer"), state.buf.push((val.byteOffset || needsLength ? "," + val.byteOffset + (needsLength ? "," + val.length : "") : "") + ")"); } else state.refs.set(val.buffer, new Reference(ref, "buffer", state.flush, null)), state.buf.push("new " + val.constructor.name + (val.length === 0 ? "" : "(" + (hasOnlyZeros(val) ? val.length : typedArrayToInitString(val)) + ")")); return !0; } function writeWeakSet(state) { return state.buf.push("new WeakSet"), !0; } function writeWeakMap(state) { return state.buf.push("new WeakMap"), !0; } function writeError(state, val, ref) { let result = "new " + val.constructor.name + "(" + quote(val.message + "", 0); if (val.cause !== void 0) { let pos = state.buf.push(result + ",{cause:") - 1; writeProp(state, val.cause, ref, "cause") ? state.buf.push("})") : state.buf[pos] = state.buf[pos].slice(0, -8) + ")"; } else state.buf.push(result + ")"); return !0; } function writeAggregateError(state, val, ref) { state.buf.push("new AggregateError("); let inlined = writeProp(state, val.errors, ref, "errors"); if (inlined || state.buf.push("[]"), val.message ? state.buf.push("," + quote(val.message + "", 0) + ")") : state.buf.push(")"), inlined) { let errorsRef = state.refs.get(val.errors); errorsRef?.id && (state.assigned.add(errorsRef), addAssignment(errorsRef, accessId(state, ref) + toAccess("errors"))); } return !0; } function writeURL(state, val) { return state.buf.push("new URL(" + quote(val.toString(), 0) + ")"), !0; } function writeURLSearchParams(state, val) { let str = val.toString(); return str ? state.buf.push("new URLSearchParams(" + quote(str, 0) + ")") : state.buf.push("new URLSearchParams"), !0; } function writeHeaders(state, val) { let headers = stringEntriesToHeadersInit(val); return state.buf.push("new Headers" + (headers ? "(" + headers + ")" : "")), !0; } function writeFormData(state, val, ref) { let sep = "[", valStr = ""; for (let [key, value] of val) { if (typeof value != "string") return !1; valStr += sep + quote(key, 0) + "," + quote(value, 0), sep = ","; } return sep === "[" ? state.buf.push("new FormData") : state.buf.push(valStr + "].reduce((f,v,i,a)=>i%2&&f.append(a[i-1],v)||f,new FormData)"), !0; } function writeRequest(state, val, ref) { let sep = "", bodySerialized = !1, hasBody = val.body && !val.bodyUsed && val.duplex === "half"; state.buf.push("new Request(" + quote(val.url, 0)), hasBody && (state.buf.push(",{body:"), writeProp(state, val.body, ref, "body") ? (state.buf.push(",duplex:\"half\""), sep = ",", bodySerialized = !0) : state.buf.pop()); let options = ""; val.cache !== "default" && (options += sep + "cache:" + quote(val.cache, 0), sep = ","), val.credentials !== "same-origin" && (options += sep + "credentials:" + quote(val.credentials, 0), sep = ","); let seenHeaders = state.refs.get(val.headers); if (seenHeaders) options += sep + "headers:" + ensureId(state, seenHeaders), sep = ","; else { state.refs.set(val.headers, new Reference(ref, "headers", state.flush, null)); let headers = stringEntriesToHeadersInit(val.headers); headers && (options += sep + "headers:" + headers, sep = ","); } return val.integrity && (options += sep + "integrity:" + quote(val.integrity, 0), sep = ","), val.keepalive && (options += sep + "keepalive:true", sep = ","), val.method !== "GET" && (options += sep + "method:" + quote(val.method, 0), sep = ","), val.mode !== "cors" && (options += sep + "mode:" + quote(val.mode, 0), sep = ","), val.redirect !== "follow" && (options += sep + "redirect:" + quote(val.redirect, 0), sep = ","), val.referrer !== "about:client" && (options += sep + "referrer:" + quote(val.referrer, 0), sep = ","), val.referrerPolicy && (options += sep + "referrerPolicy:" + quote(val.referrerPolicy, 0)), state.buf.push(bodySerialized ? options + "})" : options ? ",{" + options + "})" : ")"), !0; } function writeResponse(state, val, ref) { let sep = "", options = ""; val.status !== 200 && (options += "status:" + val.status, sep = ","), val.statusText && (options += sep + "statusText:" + quote(val.statusText, 0), sep = ","); let seenHeaders = state.refs.get(val.headers); if (seenHeaders) options += sep + "headers:" + ensureId(state, seenHeaders); else { state.refs.set(val.headers, new Reference(ref, "headers", state.flush, null)); let headers = stringEntriesToHeadersInit(val.headers); headers && (options += sep + "headers:" + headers); } return !val.body || val.bodyUsed ? state.buf.push("new Response" + (options ? "(null,{" + options + "})" : "")) : (state.buf.push("new Response("), state.buf.push((writeProp(state, val.body, ref, "body") ? "" : "null") + (options ? ",{" + options + "})" : ")"))), !0; } function writeIntl(state, val, name, ref) { let { locale, ...options } = val.resolvedOptions(), needsId = !1; for (let key in options) if (isDedupedMember(options[key])) { needsId = !0; break; } state.buf.push("new Intl." + name + "(" + quote(locale, 0) + ","); let optionsRef; return needsId ? (optionsRef = new Reference(ref, null, state.flush, null, nextRefAccess(state)), state.buf.push(optionsRef.id + "={")) : (optionsRef = new Reference(ref, null, state.flush, state.buf.length), state.buf.push("{")), writeObjectProps(state, options, optionsRef), state.buf.push("})"), !0; } function writeIntlLocale(state, val) { return state.buf.push("new Intl.Locale(" + quote(val.toString(), 0) + ")"), !0; } function writeTemporal(state, val, name) { return state.buf.push("Temporal." + name + ".from(" + quote(val.toString(), 0) + ")"), !0; } function writeReadableStream(state, val, ref) { let { boundary, channel } = state; if (!boundary || val.locked) return !1; let reader = val.getReader(), iterId = nextRefAccess(state), handle = newAsyncHandle(state, ref, iterId), onFulfilled = ({ value, done }) => { done ? writeAsyncCall(state, boundary, handle, "r", value, channel) : boundary.signal.aborted || (reader.read().then(onFulfilled, onRejected), boundary.startAsync(), writeAsyncCall(state, boundary, handle, "f", value, channel)); }, onRejected = (reason) => { writeAsyncCall(state, boundary, handle, "j", reason, channel); }; return 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))}})"), reader.read().then(onFulfilled, onRejected), boundary.startAsync(), !0; } function writeGenerator(state, iter, ref) { if (iter[kTouchedIterator]) return state.buf.push("(function*(){}())"), !0; let yields = [], returnValue, needsId; for (;;) { let { value, done } = iter.next(); if (done) { returnValue = value; break; } needsId ||= isDedupedMember(value), yields.push(value); } if (returnValue === void 0 && !yields.length) return state.buf.push("(function*(){})()"), !0; let heldReturn = returnValue !== void 0 && isAncestorMember(state, ref, returnValue); if (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})("), needsId) { let arrayRef = new Reference(ref, null, state.flush, null, nextRefAccess(state)); state.buf.push(arrayRef.id + "="), writeArray(state, yields, arrayRef); } else writeArray(state, yields, new Reference(ref, null, state.flush, state.buf.length)); if (heldReturn) { let holder = new Reference(ref, null, state.flush, null, nextRefAccess(state)); state.buf.push("," + holder.id + "={}"), writeProp(state, returnValue, holder, "v"); } else if (returnValue !== void 0) { let sepIndex = state.buf.push(",") - 1; if (writeProp(state, returnValue, ref, "") && isDedupedMember(returnValue)) { let retRef = typeof returnValue == "string" ? state.strs.get(returnValue) : state.refs.get(returnValue); retRef && !retRef.id && retRef.scopeId === void 0 && (retRef.id = nextRefAccess(state), state.buf[sepIndex] = "," + retRef.id + "="); } } return state.buf.push(")"), !0; } function writeAsyncGenerator(state, iter, ref) { if (iter[kTouchedIterator]) return state.buf.push("(async function*(){}())"), !0; let { boundary, channel } = state; if (!boundary) return !1; let iterId = nextRefAccess(state), handle = newAsyncHandle(state, ref, iterId), onFulfilled = ({ value, done }) => { done ? writeAsyncCall(state, boundary, handle, "r", value, channel) : boundary.signal.aborted || (iter.next().then(onFulfilled, onRejected), boundary.startAsync(), writeAsyncCall(state, boundary, handle, "f", value, channel)); }, onRejected = (reason) => { writeAsyncCall(state, boundary, handle, "j", reason, channel); }; return 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 + "={})"), iter.next().then(onFulfilled, onRejected), boundary.startAsync(), !0; } function writeNullObject(state, val, ref) { return state.buf.push("{"), state.buf.push(writeMaybeIterableProps(state, val, ref) + "__proto__:null}"), !0; } function writeObjectProps(state, val, ref) { let sep = ""; for (let key in val) if (hasOwnProperty.call(val, key)) { let escapedKey = toObjectKey(key); state.buf.push(sep + escapedKey + ":"), writeProp(state, val[key], ref, escapedKey) ? sep = "," : state.buf.pop(); } return sep; } function writeMaybeIterableProps(state, val, ref) { let sep = writeObjectProps(state, val, ref); if (hasSymbolIterator(val)) { let yieldSelf = "", iterArr = []; for (let item of val) item === val && !(yieldSelf || iterArr.length) ? yieldSelf = "yield this;" : iterArr.push(item); if (iterArr.length) { let iterRef = new Reference(ref, null, state.flush, null, nextRefAccess(state)); state.buf.push(sep + "*[(" + iterRef.id + "="), writeArray(state, iterArr, iterRef), state.buf.push(",Symbol.iterator)](){" + yieldSelf + "yield*" + iterRef.id + "}"); } else state.buf.push(sep + "*[Symbol.iterator](){" + yieldSelf.slice(0, -1) + "}"); sep = ","; } return sep; } function writeAsyncCall(state, boundary, handle, method, value, channel, valueId = null) { boundary.signal.aborted || (state.mutated.push({ value, object: handle, property: method, channel, valueId }), boundary.endAsync()); } function trackChannel(state, ref) { let refReadyId = ref.channel?.readyId; if (!refReadyId || refReadyId === state.channel?.readyId) return !0; let cur = state.channel?.parent; for (; cur;) { if (cur.readyId === refReadyId) return (state.channelDeps ||= /* @__PURE__ */ new Set()).add(refReadyId), !0; cur = cur.parent; } return !1; } function isCircular(parent, ref) { let cur = parent; for (; cur;) { if (cur === ref) return !0; cur = cur.parent; } return !1; } function toObjectKey(name) { if (name === "") return "\"\""; if (name === "__proto__") return "[\"__proto__\"]"; let len = name.length, c0 = name.charCodeAt(0); if (c0 >= 48 && c0 <= 57) if (c0 === 48) { if (len !== 1) return quote(name, 1); } else { for (let i = 1; i < len; i++) { let c = name.charCodeAt(i); if (c < 48 || c > 57) return quote(name, i); } if (len > 15 && "" + +name !== name) return quote(name, 0); } else if (c0 >= 97 && c0 <= 122 || c0 >= 65 && c0 <= 90 || c0 === 95 || c0 === 36) for (let i = 1; i < len; i++) { let c = name.charCodeAt(i); if (!(c >= 97 && c <= 122 || c >= 65 && c <= 90 || c >= 48 && c <= 57 || c === 95 || c === 36)) return quote(name, i); } else return quote(name, 0); return name