UNPKG

marko

Version:

Optimized runtime for Marko templates.

2,602 lines • 120 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;
}, K_SCOPE_ID = Symbol("Scope ID"), kTouchedIterator = /* @__PURE__ */ Symbol.for("marko.touchedIterator"), { hasOwnProperty } = {}, objectProto = Object.prototype, arrayProto = Array.prototype, Generator = (/* @__PURE__ */ (function* () {})()).constructor, AsyncGenerator = (/* @__PURE__ */ (async function* () {})()).constructor, REGISTRY = /* @__PURE__ */ new WeakMap(), KNOWN_SYMBOLS = /* @__PURE__ */ (() => {
	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.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.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, kSelectedValue = Symbol("selectedValue"), checkedValuesRefs = /* @__PURE__ */ new WeakMap(), singleQuoteAttrReplacements = /['\r]|&(?=[#a-zA-Z])/g, doubleQuoteAttrReplacements = /["\r]|&(?=[#a-zA-Z])/g, needsQuotedAttr = /["'>\s]|&[#a-zA-Z]|\/$/g, $chunk, kPendingContexts = Symbol("Pending Contexts"), kBranchId = Symbol("Branch Id"), kAsyncContent = Symbol("Async Content"), writeScope = (scopeId, partialScope) => {
	let { state } = $chunk.boundary, target = $chunk.channel, scope = scopeWithId(state, scopeId);
	return state.needsWalkerRuntime = !0, countResumeWrite($chunk), writeAsyncVisits($chunk), Object.assign(scope, partialScope), state.queueScope(target, scopeId, partialScope), scope;
}, ALL_GROUPS = 715827883, NOOP$2 = () => {}, tick = globalThis.setImmediate || globalThis.setTimeout || globalThis.queueMicrotask || ((cb) => Promise.resolve().then(cb)), tickQueue, unsafeXMLReg = /[<&\r]/g, replaceUnsafeXML = (c) => c === "&" ? "&amp;" : c === "<" ? "&lt;" : "&#13;", escapeXMLStr = (str) => unsafeXMLReg.test(str) ? str.replace(unsafeXMLReg, replaceUnsafeXML) : str, unsafeScriptReg = /<(\/?script|!--)/gi, escapeScriptStr = (str) => unsafeScriptReg.test(str) ? str.replace(unsafeScriptReg, "\\u003C$1") : str, unsafeScriptTemplateLiteralReg = /[`\\\r]|\$\{|<(?=\/?script|!--)/gi, replaceUnsafeScriptTemplateLiteral = (c) => c === "<" ? "\\x3C" : c === "\r" ? "\\r" : "\\" + c, quoteScriptTemplateLiteral = (str) => "`" + (unsafeScriptTemplateLiteralReg.test(str) ? str.replace(unsafeScriptTemplateLiteralReg, replaceUnsafeScriptTemplateLiteral) : str) + "`", unsafeStyleReg = /<(\/style)/gi, escapeStyleStr = (str) => unsafeStyleReg.test(str) ? str.replace(unsafeStyleReg, "\\3C$1") : str, unsafeCommentReg = />/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, markerGuard, tagVar) => {
	let shouldResume = markerGuard !== 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(_attrs_textarea_value(branchId, "a", input));
				else {
					if (renderContent && 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 ? () => _dynamic_tag(branchId, "a", renderContent, void 0, 0, void 0, markerGuard) : void 0, 1) : renderContent && _dynamic_tag(branchId, "a", renderContent, void 0, 0, void 0, markerGuard);
				}
				_html(`</${renderer}>`);
			}
			let childScope = getScopeById(branchId), needsScript = childScope && (childScope.Ia || childScope.Ea);
			needsScript && _script(branchId, "_d"), (shouldResume || needsScript) && _html(state.mark("(", scopeId + " " + accessor + " " + branchId));
		})(), result = _el(scopeId, "-" + accessor);
	} else {
		let chunk = getChunk(), beforeBranch = shouldResume ? deferBranchStart(chunk) : void 0, render = () => {
			if (renderer) try {
				return _set_scope_reason(shouldResume ? ALL_GROUPS : 0), inputIsArgs ? renderer(...inputOrArgs) : renderer(content ? {
					...inputOrArgs,
					content
				} : inputOrArgs);
			} finally {
				_set_scope_reason(void 0);
			}
			else content && content();
		};
		result = shouldResume ? withBranchId(branchId, render) : render(), rendered = _peek_scope_id() !== branchId, beforeBranch !== void 0 && (applyBranchStart(chunk, beforeBranch, rendered), _html(state.mark("]", scopeId + " " + accessor + (rendered ? " " + branchId : ""))), renderer && _existing_scope(branchId));
	}
	return rendered ? shouldResume && writeScope(scopeId, { ["D" + accessor]: rendererKey(renderer) }) : _scope_id(), result;
}, patchDynamicTag = /* @__PURE__ */ ((originalDynamicTag) => (patch) => {
	_dynamic_tag = (scopeId, accessor, tag, input, content, inputIsArgs, markerGuard, tagVar) => {
		let patched = patch(tag, scopeId, accessor);
		return patched !== tag && (patched.a = tag), originalDynamicTag(scopeId, accessor, patched, input, content, inputIsArgs, markerGuard, tagVar);
	};
})(_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(), kHead = Symbol(), SET_SCOPE_REGISTER_ID = "$C_s", RENDER_BODY_ID = "$C_b", K_TAGS_API_STATE = Symbol(), COMPAT_REGISTRY = /* @__PURE__ */ new WeakMap(), compat = {
	$global,
	writeLoadAsset,
	fork: _await,
	write: _html,
	writeScript,
	nextScopeId: _scope_id,
	peekNextScopeId: _peek_scope_id,
	isInResumedBranch,
	withChunk,
	getChunk,
	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(boundary) {
			let { state } = boundary, reorders = swapReorders(state, null);
			return fn(this), swapReorders(state, reorders), flushHTML.call(this, boundary);
		};
	},
	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 = REGISTRY.get(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;
		};
	},
	joinChunks(chunks) {
		let joined;
		for (let chunk of chunks) chunk.boundary.aborted || (joined ? joined.append(chunk) : joined = chunk);
		return joined;
	},
	appendChunks(chunks) {
		let chunk = getChunk();
		for (let part of chunks) chunk.append(part), part.effects && (chunk.lastEffect = part.lastEffect);
	},
	deferReorders(reorders) {
		let chunk = getChunk();
		for (let i = reorders.length; i--;) {
			let carrier = chunk.fork(chunk.boundary, chunk.next);
			carrier.deferredReorder = reorders[i], chunk.next = carrier;
		}
	},
	createChunk($global) {
		let state = this.ensureState($global);
		return new Chunk(new Boundary(state), null, null, state);
	},
	flushScript(chunk, reorders) {
		let { boundary } = chunk, { state } = boundary, html = "", scripts = "";
		if (reorders) for (let reorder of reorders) state.reorder(reorder);
		if (boundary.flush() === 0 && ({html, scripts} = chunk.flush(boundary)), boundary.aborted) throw boundary.reason;
		if (boundary.count) throw Error("Cannot serialize promise across tags/class compat layer.");
		return {
			html,
			scripts
		};
	},
	render(renderer, willRerender, classAPIOut, component, input, componentScopes, registerChildScope, parentChunk) {
		if (parentChunk?.boundary.aborted) return;
		let state = this.ensureState(classAPIOut.global), boundary = new Boundary(state, void 0, parentChunk?.boundary), context = getChunk()?.context ?? null, head = new Chunk(boundary, new Chunk(boundary, null, context, state), context, state), normalizedInput = input;
		if ("renderBody" in input) {
			normalizedInput = {};
			for (let key in input) normalizedInput[key === "renderBody" ? "content" : key] = input[key];
		}
		let componentScope = new Chunk(boundary, null, context, state);
		componentScope.render(() => {
			if (this.hasPendingClassFunctions(classAPIOut.global) && drainClassFunctions(classAPIOut.global, (hostId) => {
				let fnScopeId = _scope_id(), scope = writeScope(fnScopeId, {
					m5c: component.id,
					m5h: hostId
				});
				return _script(fnScopeId, SET_SCOPE_REGISTER_ID), scope;
			}), willRerender || registerChildScope) {
				let scopeId = _peek_scope_id();
				writeScope(scopeId, { m5c: component.id }), _script(scopeId, SET_SCOPE_REGISTER_ID);
			}
		}), head.render(() => {
			_set_scope_reason(willRerender ? ALL_GROUPS : 0);
			try {
				renderer(normalizedInput);
			} finally {
				_set_scope_reason(void 0);
			}
			let asyncOut = classAPIOut.beginAsync({
				last: !0,
				timeout: -1
			});
			classAPIOut.onLast((next) => {
				(boundary.onNext = () => {
					if (boundary.aborted) boundary.onNext = NOOP, parentChunk?.boundary.aborted ? (asyncOut.end(), next()) : asyncOut.error(boundary.reason);
					else if (!boundary.count) {
						boundary.onNext = NOOP;
						let queued = swapReorders(state, null);
						head = head.consume(boundary);
						let reorders = swapReorders(state, queued);
						reorders && asyncOut.writer.get("reorders").push(...reorders);
						let heldEffects = head.takeHeldEffects();
						heldEffects && (head.effects = joinHeldEffects(heldEffects, head.effects), head.lastEffect = ""), asyncOut.write(head.html), asyncOut.script(head.scripts), head.html = head.scripts = "", asyncOut.writer.get("chunks").push(head), asyncOut.end(), componentScopes.push(componentScope), next();
					}
				})();
			});
		});
	},
	register,
	registerRenderBody(fn) {
		register(RENDER_BODY_ID, fn);
	},
	registerClassFunctions(input) {
		for (let key in input) {
			let value = input[key];
			typeof value == "function" && !REGISTRY.has(value) && register(RENDER_BODY_ID, value);
		}
	},
	registerClassFunction($global, id, fn, hostId) {
		let pending = pendingClassFunctions.get($global);
		return pending || pendingClassFunctions.set($global, pending = []), pending.push([
			id,
			fn,
			hostId
		]), fn;
	},
	hasPendingClassFunctions($global) {
		return !!pendingClassFunctions.get($global)?.length;
	}
}, pendingClassFunctions = /* @__PURE__ */ new WeakMap();
//#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 stringifyClassEntry(name, value) {
	return value ? name : "";
}
function stringifyStyleEntry(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 getEventType(name) {
	return name[2] === "-" ? name.slice(3) : name.slice(2).toLowerCase();
}
function hasKeys(obj) {
	for (let _ in obj) return !0;
	return !1;
}
function isNullishOrFalse(value) {
	return value == null || value === !1;
}
function isNotNullishOrFalse(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 _assert_class_toggles(classes, toggles) {}
function _el_read_error() {}
function _hoist_read_error() {}
function _assert_hoist(value) {}
//#endregion
//#region src/common/opt.ts
function reduce(opt, cb, acc) {
	if (opt) {
		if (Array.isArray(opt)) for (let item of opt) acc = cb(acc, item);
		else acc = cb(acc, opt);
	}
	return acc;
}
function push(opt, item) {
	return opt ? Array.isArray(opt) ? (opt.push(item), opt) : [opt, item] : item;
}
function concat(opt, other) {
	if (!opt) return other;
	if (!other) return opt;
	if (Array.isArray(opt)) {
		if (Array.isArray(other)) for (let item of other) opt.push(item);
		else opt.push(other);
		return opt;
	}
	return Array.isArray(other) ? [opt, ...other] : [opt, other];
}
patchIteratorNext(Generator.prototype), patchIteratorNext(AsyncGenerator.prototype);
var State$1 = class {
	ids = 0;
	flushId = 0;
	wroteUndefined = !1;
	buf = [];
	strs = /* @__PURE__ */ new Map();
	refs = /* @__PURE__ */ new WeakMap();
	deferredRefs = /* @__PURE__ */ new Set();
	boundary;
	channel = void 0;
	channelDeps = null;
	queuedCalls = [];
	queuedReadyCalls = [];
	scopeRef(scope, scopeId) {
		return this.refs.get(scope) || newScopeReference(this, scope, scopeId);
	}
	writeScopeProps(props, ref) {
		return writeObjectProps(this, props, ref);
	}
	scopesCursor(scopeId) {
		return scopeId + ",";
	}
	writeTrailing(scopesIndex) {
		let { buf } = this;
		return ~scopesIndex && (buf[scopesIndex] = "_([" + buf[scopesIndex], buf.push("])")), writeDeferred(this), ",0)";
	}
	wrapPayload(result, extras) {
		let arrow = this.wroteUndefined ? "(_,$)=>" : "_=>";
		return this.wroteUndefined = !1, extras ? arrow + result : arrow + "[" + result + "]";
	}
	writeScopedRegistration(val, parent, accessor, registered) {
		let ref = new Reference(parent, accessor, this.flushId, this.buf.length);
		ref.channel = this.channel, this.refs.set(val, ref);
		let scope = registered.scope, scopeId = scope[K_SCOPE_ID];
		trackScope(this, scope, scopeId);
		let locals = registered.locals?.(this.boundary.state.scope);
		if (locals) {
			this.buf.push(registered.access + "(_(" + scopeId + ")");
			for (let local of locals) this.buf.push(","), writePlainObject(this, local, newArgReference(this, ref, local));
		} else this.buf.push("_(" + scopeId + "," + quoteRegisterId(registered.id));
		this.buf.push(")");
	}
}, Reference = class {
	assignments = null;
	deferredMembers = null;
	scopeId = void 0;
	channel = void 0;
	parent;
	accessor;
	flushId;
	pos;
	id;
	path = null;
	constructor(parent, accessor, flushId, pos = null, id = null) {
		this.parent = parent, this.accessor = accessor, this.flushId = flushId, this.pos = pos, this.id = id;
	}
};
function stringifyScopes(state, flushes, boundary, channel) {
	try {
		return state.boundary = boundary, state.channel = channel, writeScopesRoot(state, flushes);
	} catch (err) {
		return abortRender(boundary, err), "";
	} finally {
		state.flushId++, state.buf = [];
	}
}
function pendingReadyChannel(state) {
	let calls = state.queuedReadyCalls;
	return calls.length ? calls[0].channel : void 0;
}
function takeChannelDeps(state) {
	let deps = state.channelDeps;
	return state.channelDeps = null, deps;
}
function queueCall(state, value, object, method, channel) {
	(channel?.readyId ? state.queuedReadyCalls : state.queuedCalls).push({
		method,
		value,
		object,
		channel,
		valueId: null
	});
}
function dropQueuedCall(state, value, object, method, channel) {
	let queuedCalls = channel?.readyId ? state.queuedReadyCalls : state.queuedCalls;
	for (let i = 0; i < queuedCalls.length; i++) {
		let call = queuedCalls[i];
		if (call.value === value && call.object === object && call.method === method) return queuedCalls.splice(i, 1), !0;
	}
	return !1;
}
function register(id, val, scope, locals, access = "_._" + toAccess(toObjectKey(id))) {
	return REGISTRY.set(val, {
		id,
		scope,
		locals,
		access
	}), val;
}
function writeScopesRoot(state, flushes) {
	let { buf } = state, nextSlotId = -1, scopesIndex = -1;
	for (let flush of flushes) {
		let scopeId = flush[0], scope = flush[1], ref = state.scopeRef(scope, scopeId), openIndex = buf.push("") - 1;
		state.writeScopeProps(flush[2], ref) ? (buf[openIndex] = nextSlotId === -1 ? state.scopesCursor(scopeId) + "{" : (scopeId === nextSlotId ? "" : "," + (scopeId - nextSlotId)) + ",{", scopesIndex === -1 && (scopesIndex = openIndex), nextSlotId = scopeId + 1, buf.push("}")) : buf.pop();
	}
	let extras = "";
	(state.deferredRefs.size || hasChannelCalls(state)) && (extras = state.writeTrailing(scopesIndex));
	let result = extras && "(";
	for (let chunk of buf) result += chunk;
	return result += extras, result ? state.wrapPayload(result, extras) : "";
}
function writeDeferred(state) {
	let sep = state.buf.length ? "," : "";
	if (state.deferredRefs.size) {
		let pending = state.deferredRefs;
		state.deferredRefs = /* @__PURE__ */ new Set();
		let buf = "", hasCalls = !1;
		for (let ref of pending) ref.assignments && (buf += sep + assignmentsToString(ref.assignments, ref.id), ref.assignments = null, sep = ","), hasCalls ||= ref.deferredMembers !== null;
		if (buf && state.buf.push(buf), hasCalls) for (let ref of pending) {
			let members = ref.deferredMembers;
			members && (writeDeferredMembers(state, ref.id, members), ref.deferredMembers = null);
		}
	}
	let readyId = state.channel?.readyId, calls = state.queuedCalls;
	if (readyId) {
		calls = [];
		let remaining = [];
		for (let call of state.queuedReadyCalls) (call.channel.readyId === readyId ? calls : remaining).push(call);
		state.queuedReadyCalls = remaining;
	} else calls.length && (state.queuedCalls = []);
	for (let call of calls) {
		let objectStartIndex = state.buf.push(state.buf.length === 0 ? "" : ",");
		if (writeProp(state, call.object, null, "")) {
			let objectRef = state.refs.get(call.object);
			!objectRef.id && !isAncestorChannelRef(state, objectRef) ? (objectRef.id = nextRefAccess(state), state.buf[objectStartIndex] = "(" + objectRef.id + "=" + state.buf[objectStartIndex], state.buf.push(")")) : objectRef.id && state.buf[objectStartIndex] !== objectRef.id && (state.buf[objectStartIndex] = "(" + state.buf[objectStartIndex], state.buf.push(")"));
		} else state.buf.push("void 0");
		state.buf.push("." + call.method + "("), call.value !== void 0 && writeCallArg(state, call.value, call.valueId), state.buf.push(")");
	}
	state.deferredRefs.size && writeDeferred(state);
}
function writeDeferredMembers(state, id, { collection, first, rest }) {
	if (collection instanceof Map) {
		writeDeferredEntry(state, id, first);
		for (let entry of rest) writeDeferredEntry(state, id, entry);
	} else {
		writeDeferredMember(state, id, first);
		for (let member of rest) writeDeferredMember(state, id, member);
	}
}
function writeDeferredEntry(state, id, [key, value]) {
	state.buf.push("," + id + ".set("), (key !== void 0 || value !== void 0) && writeCallArg(state, key, null), value !== void 0 && (state.buf.push(","), writeCallArg(state, value, null)), state.buf.push(")");
}
function writeDeferredMember(state, id, member) {
	state.buf.push("," + id + ".add("), member !== void 0 && writeCallArg(state, member, null), state.buf.push(")");
}
function writeCallArg(state, val, valueId) {
	let startIndex = state.buf.length;
	if (val === void 0) state.wroteUndefined = !0, state.buf.push("$");
	else if (writeProp(state, val, null, "")) {
		let ref = typeof val == "string" ? state.strs.get(val) : state.refs.get(val);
		ref && !ref.id && ref.scopeId === void 0 && !isAncestorChannelRef(state, ref) && (ref.id = valueId || nextRefAccess(state), state.buf[startIndex] = ref.id + "=" + state.buf[startIndex]);
	} else state.buf.push("void 0");
}
function hasChannelCalls(state) {
	return hasMatchingCalls(state, state.channel?.readyId);
}
function hasMatchingCalls(state, readyId) {
	if (!readyId) return state.queuedCalls.length > 0;
	for (let call of state.queuedReadyCalls) if (call.channel.readyId === readyId) return !0;
	return !1;
}
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) ? (ensureRefAccess(state, ref), state.deferredRefs.add(ref), addAssignment(ref, accessId(state, parent) + toAccess(accessor)), !1) : (writeRef(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.flushId, 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.flushId);
	return ref.scopeId = scopeId, ref.channel = state.channel, state.refs.set(val, ref), ref;
}
function quoteRegisterId(id) {
	return "\"" + id + "\"";
}
function writeRegistered(state, val, parent, accessor, registered) {
	let { scope } = registered;
	return scope ? state.writeScopedRegistration(val, parent, accessor, registered) : state.buf.push(registered.access), !0;
}
function writeString(state, val, parent, accessor) {
	if (val.length > 12) {
		let ref = state.strs.get(val);
		if (ref) {
			if (trackChannel(state, ref)) return writeRef(state, ref), !0;
		} else {
			let ref = new Reference(parent, accessor, state.flushId, 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);
	let constructor = proto?.constructor;
	switch (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, constructor.name, 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, constructor.name, 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 source.includes("<") ? state.buf.push(`RegExp(${quote(source, 0)}${val.flags ? ",\"" + val.flags + "\"" : ""})`) : state.buf.push("/" + (unsafeRegExpSourceDetect.test(source) ? source.replace(unsafeRegExpSourceReg, replaceUnsafeRegExpSourceChar) : source) + "/" + val.flags), !0;
}
function writePromise(state, val, ref) {
	let { boundary, channel } = state, 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) => queueAsyncCall(state, boundary, handle, "f", v, channel, pId), (v) => queueAsyncCall(state, boundary, handle, "r", v, channel, pId)), boundary.startAsync(), !0;
}
function newAsyncHandle(state, parent, id) {
	let handle = {}, handleRef = new Reference(parent, null, state.flushId, 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 = [], assignments, needsId, i = 0, entries = val.entries();
	if (val.size < 25) {
		for (let entry of entries) {
			let [itemKey, itemValue] = entry;
			if (itemKey !== val && isAncestorMember(state, ref, itemKey) || itemValue !== val && isAncestorMember(state, ref, itemValue)) {
				if (deferMembers(state, ref, val, entry, entries), !i) return state.buf.push("new Map"), !0;
				break;
			}
			itemKey === val && (itemKey = void 0, (assignments ||= []).push("a[" + i + "][0]")), itemValue === val && (itemValue = void 0, (assignments ||= []).push("a[" + i + "][1]")), needsId ||= isReusableMember(itemKey) || isReusableMember(itemValue), i = items.push(itemValue === void 0 ? itemKey === void 0 ? [] : [itemKey] : [itemKey, itemValue]);
		}
		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);
	} else {
		for (let entry of entries) {
			let [itemKey, itemValue] = entry;
			if (itemKey !== val && isAncestorMember(state, ref, itemKey) || itemValue !== val && isAncestorMember(state, ref, itemValue)) {
				if (deferMembers(state, ref, val, entry, entries), !i) return state.buf.push("new Map"), !0;
				break;
			}
			itemKey === val && (itemKey = 0, (assignments ||= []).push("a[" + i + "]")), itemValue === val && (itemValue = 0, (assignments ||= []).push("a[" + (i + 1) + "]")), needsId ||= isReusableMember(itemKey) || isReusableMember(itemValue), i = items.push(itemKey, itemValue);
		}
		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);
	}
	return !0;
}
function writeSet(state, val, ref) {
	if (!val.size) return state.buf.push("new Set"), !0;
	let items = [], assignments, needsId, i = 0, members = val.values();
	for (let item of members) {
		if (item !== val && isAncestorMember(state, ref, item)) {
			if (deferMembers(state, ref, val, item, members), !i) return state.buf.push("new Set"), !0;
			break;
		}
		item === val ? (item = 0, (assignments ||= []).push("i[" + i + "]")) : needsId ||= isReusableMember(item), i = items.push(item);
	}
	return writeArrayArg(state, ref, items, assignments && "((s,i)=>(" + assignmentsToString(assignments, "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 deferMembers(state, ref, collection, first, rest) {
	ensureRefAccess(state, ref), ref.deferredMembers = {
		collection,
		first,
		rest
	}, state.deferredRefs.add(ref);
}
function writeArrayArg(state, ref, items, assignsPrefix, plainPrefix, needsId) {
	if (assignsPrefix || needsId) {
		let arrayRef = new Reference(ref, null, state.flushId, 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.flushId, state.buf.length));
	state.buf.push(")");
}
function newArgReference(state, parent, val) {
	for (let key in val) {
		let member = val[key];
		if (isReusableMember(member) && !(typeof member == "string" ? state.strs.has(member) : state.refs.has(member))) {
			let ref = new Reference(parent, null, state.flushId, null, nextRefAccess(state));
			return state.buf.push(ref.id + "="), ref;
		}
	}
	return new Reference(parent, null, state.flushId, state.buf.length);
}
function isReusableMember(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, name, 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 " + 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.flushId, null)), state.buf.push("new " + 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, name, ref) {
	let result = "new " + 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.deferredRefs.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:" + ensureRefAccess(state, seenHeaders), sep = ",";
	else {
		state.refs.set(val.headers, new Reference(ref, "headers", state.flushId, 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:" + ensureRefAccess(state, seenHeaders);
	else {
		state.refs.set(val.headers, new Reference(ref, "headers", state.flushId, 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();
	state.buf.push("new Intl." + name + "(" + quote(locale, 0) + ",");
	let optionsRef = newArgReference(state, ref, options);
	return 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) {
	if (val.locked) return !1;
	let { boundary, channel } = state, reader = val.getReader(), iterId = nextRefAccess(state), handle = newAsyncHandle(state, ref, iterId), onFulfilled = ({ value, done }) => {
		done ? queueAsyncCall(state, boundary, handle, "r", value, channel) : boundary.aborted || (reader.read().then(onFulfilled, onRejected), boundary.startAsync(), queueAsyncCall(state, boundary, handle, "f", value, channel));
	}, onRejected = (reason) => {
		queueAsyncCall(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 ||= isReusableMember(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.flushId, null, nextRefAccess(state));
		state.buf.push(arrayRef.id + "="), writeArray(state, yields, arrayRef);
	} else writeArray(state, yields, new Reference(ref, null, state.flushId, state.buf.length));
	if (heldReturn) {
		let holder = new Reference(ref, null, state.flushId, null, nextRefAccess(state));
		state.buf.push("," + holder.id + "={}"), writeProp(state, returnValue, holder, "v");
	} else if (returnValue !== void 0 && (state.buf.push(","), writeProp(state, returnValue, ref, "") && isReusableMember(returnValue))) {
		let retRef = typeof returnValue == "string" ? state.strs.get(returnValue) : state.refs.get(returnValue);
		retRef && ensureRefAccess(state, retRef);
	}
	return state.buf.push(")"), !0;
}
function writeAsyncGenerator(state, iter, ref) {
	if (iter[kTouchedIterator]) return state.buf.push("(async function*(){}())"), !0;
	let { boundary, channel } = state, iterId = nextRefAccess(state), handle = newAsyncHandle(state, ref, iterId), onFulfilled = ({ value, done }) => {
		done ? queueAsyncCall(state, boundary, handle, "r", value, channel) : boundary.aborted || (iter.next().then(onFulfilled, onRejected), boundary.startAsync(), queueAsyncCall(state, boundary, handle, "f", value, channel));
	}, onRejected = (reason) => {
		queueAsyncCall(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.flushId, 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 queueAsyncCall(state, boundary, handle, method, value, channel, valueId = null) {
	boundary.aborted || ((channel?.readyId ? state.queuedReadyCalls : state.queuedCalls).push({
		method,
		value,
		object: handle,
		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 isAncestorChannelRef(state, ref) {
	return ref.channel?.readyId !== state.channel?.readyId;
}
function abortRender(boundary, err) {
	for (; boundary.parent;) boundary = boundary.parent;
	boundary.abort(err);
}
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;
}
function toAccess(accessor) {
	let start = accessor[0];
	return start === "[" ? accessor : start === "\"" || start >= "0" && start <= "9" ? "[" + accessor + "]" : "." + accessor;
}
function quote(str, startPos) {
	if (!unsafeQuoteReg.test(str)) return "\"" + str + "\"";
	let result = "", lastPos = 0;
	for (let i = startPos; i < str.length; i++) {
		let replacement, code = str.charCodeAt(i);
		switch (code) {
			case 34:
				replacement = "\\\"";
				break;
			case 92:
				replacement = "\\\\";
				break;
			case 60:
				replacement = "\\x3C";
				break;
			case 10:
				replacement = "\\n";
				break;
			case 13:
				replacement = "\\r";
				break;
			case 8232:
				replacement = "\\u2028";
				break;
			case 8233:
				replacement = "\\u2029";
				break;
			case 0:
				replacement = "\\x00";
				break;
			default:
				if (code < 55296 || code > 57343) continue;
				if (code < 56320) {
					let next = str.charCodeAt(i + 1);
					if (next >= 56320 && next <= 57343) {
						i++;
						continue;
					}
				}
				replacement = "\\u" + code.toString(16);
		}
		result += str.slice(lastPos, i) + replacement, lastPos = i + 1;
	}
	return "\"" + (lastPos === startPos ? str : result + str.slice(lastPos)) + "\"";
}
function writeRef(state, ref) {
	ref.id === null && ref.scopeId === void 0 && ref.path === null && (ref.pos === null || ref.flushId !== state.flushId) && !isAncestorChannelRef(state, ref) ? (ref.path = accessPath(state, ref), ref.pos = state.buf.length, ref.flushId = state.flushId, state.buf.push(ref.path)) : state.buf.push(ensureRefAccess(state, ref));
}
function ensureRefAccess(state, ref) {
	return ref.scopeId === void 0 ? ref.id ? (trackChannel(state, ref), ref.id) : claimRefAccess(state, ref) : (trackChannel(state, ref), "_(" + ref.scopeId + ")");
}
function accessId(state, ref) {
	let id = ensureRefAccess(state, ref);
	return id === ref.id || ref.scopeId !== void 0 ? id : "(" + id + ")";
}
function claimRefAccess(state, ref) {
	let { pos } = ref;
	return pos !== null && ref.flushId === state.flushId ? (ref.id = nextRefAccess(state), pos === 0 ? state.buf[0] = ref.id + "=" + state.buf[0] : state.buf[pos - 1] += ref.id + "=", ref.id) : isAncestorChannelRef(state, ref) ? ref.path || accessPath(state, ref) : (ref.id = nextRefAccess(state), ref.id + "=" + (ref.path || accessPath(state, ref)));
}
function accessPath(state, ref) {
	let cur = ref, accessPrevValue = "";
	do {
		accessPrevValue = toAccess(cur.accessor) + accessPrevValue;
		let parent = cur.parent;
		if (parent.id) return trackChannel(state, parent), parent.id + accessPrevValue;
		if (parent.flushId === state.flushId || parent.scopeId !== void 0) return accessId(state, parent) + accessPrevValue;
		cur = parent;
	} while (cur);
	return accessPrevValue;
}
function assignmentsToString(assignments, value) {
	return assignments.length > 100 ? "($=>(" + assignments.join("=$,") + "=$))(" + value + ")" : assignments.join("=") + "=" + value;
}
function addAssignment(ref, assign) {
	ref.assignments ? ref.assignments.push(assign) : ref.assignments = [assign];
}
function nextRefAccess(state) {
	return "_." + nextId(state);
}
function nextId(state) {
	let c = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_0123456789", n = state.ids++, r = c[n % 53];
	for (n = n / 53 | 0; n; n >>>= 6) r += c[n & 63];
	return r === "name" ? nextId(state) : r;
}
function hasSymbolIterator(value) {
	return Symbol.iterator in value;
}
function stringEntriesToHeadersInit(entries) {
	let list = [...entries];
	if (!list.length) return "";
	let duplicate = !1, seen = /* @__PURE__ */ new Set();
	for (let [key] of list) {
		if (seen.has(key)) {
			duplicate = !0;
			break;
		}
		seen.add(key);
	}
	let result = "", sep = "";
	for (let [key, value] of list) result += duplicate ? sep + "[" + quote(key, 0) + "," + quote(value, 0) + "]" : sep + toObjectKey(key) + ":" + quote(value, 0), sep = ",";
	return duplicate ? "[" + result + "]" : "{" + result + "}";
}
function typedArrayToInitString(view) {
	let suffix = typeof view[0] == "bigint" ? "n" : "", result = "[", sep = "";
	for (let i = 0; i < view.length; i++) result += sep + view[i] + suffix, sep = ",";
	return result += "]", result;
}
function hasOnlyZeros(typedArray) {
	let zero = typeof typedArray[0] == "bigint" ? 0n : 0;
	for (let i = 0; i < typedArray.length; i++) if (typedArray[i] !== zero) return !1;
	return !0;
}
function patchIteratorNext(proto) {
	if (proto.next[kTouchedIterator]) return;
	let { next } = proto;
	proto.next = function(value) {
		return this[kTouchedIterator] = 1, next.call(this, value);
	}, proto.next[kTouchedIterator] = !0;
}
//#endregion
//#region src/html/attrs.ts
function _attr_class(value) {
	return stringAttr("class", toDelimitedString(value, " ", stringifyClassEntry));
}
function _attr_style(value) {
	return stringAttr("style", toDelimitedString(value, ";", stringifyStyleEntry));
}
function _attr_option_value(value) {
	let valueAttr = _attr("value", value), selectedValue = getContext(kSelectedValue);
	return selectedValue !== void 0 && normalizedValueMatches(selectedValue, value) ? valueAttr + " selected" : valueAttr;
}
function _attr_select_value(scopeId, nodeAccessor, value, valueChange, content, serializeType) {
	valueChange && writeControlledScope(3, scopeId, nodeAccessor, void 0, valueChange, serializeType), content && withContext(kSelectedValue, value ?? "", content);
}
function _attrs_select_value(scopeId, nodeAccessor, data, content) {
	data && ("value" in data || data.valueChange) ? _attr_select_value(scopeId, nodeAccessor, data.value, data.valueChange, content, 1) : content();
}
function _attr_textarea_value(scopeId, nodeAccessor, value, valueChange, serializeType) {
	return valueChange && writeControlledScope(2, scopeId, nodeAccessor, void 0, valueChange, serializeType), _textarea_value(value);
}
function _attrs_textarea_value(scopeId, nodeAccessor, data) {
	return _attr_textarea_value(scopeId, nodeAccessor, data?.value, data?.valueChange, 1);
}
function _textarea_value(value) {
	let escaped = _escape(normalizeStrAttrValue(value));
	return escaped[0] === "\n" ? "\n" + escaped : escaped;
}
function _attr_input_value(scopeId, nodeAccessor, value, valueChange, serializeType) {
	return valueChange && writeControlledScope(2, scopeId, nodeAccessor, void 0, valueChange, serializeType), _attr("value", value);
}
function _attr_input_checked(scopeId, nodeAccessor, checked, checkedChange, serializeType) {
	return checkedChange && writeControlledScope(0, scopeId, nodeAccessor, void 0, checkedChange, serializeType), isNotNullishOrFalse(checked) ? " checked" : "";
}
function _attr_input_checkedValue(scopeId, nodeAccessor, checkedValue, checkedValueChange, value, serializeType) {
	let valueAttr = _attr("value", value);
	return checkedValueChange && writeControlledScope(1, scopeId, nodeAccessor, getCheckedValueRef(checkedValue), checkedValueChange, serializeType), normalizedValueMatches(checkedValue, value) ? valueAttr + " checked" : valueAttr;
}
function getCheckedValueRef(checkedValue) {
	if (Array.isArray(checkedValue)) {
		let ref = checkedValuesRefs.get(checkedValue);
		return ref || (ref = [], checkedValuesRefs.set(checkedValue, ref)), ref;
	}
}
function _attr_details_or_dialog_open(scopeId, nodeAccessor, open, openChange, serializeType) {
	let normalizedOpen = isNotNullishOrFalse(open);
	return openChange && writeControlledScope(4, scopeId, nodeAccessor, normalizedOpen || void 0, openChange, serializeType), normalizedOpen ? " open" : "";
}
function _attr_nonce() {
	return getChunk().boundary.state.nonceAttr;
}
function _style_html(decls) {
	let id = _id();
	return `<style${_attr_nonce()} class=${id}>.${id}~*{${decls}}</style>`;
}
function _attr(name, value) {
	return isNullishOrFalse(value) ? "" : stringifyAttr(name, value);
}
function _attr_and(name, value, attr) {
	return value ? attr : _attr(name, value);
}
function _attr_or(name, value, attr) {
	return value ? _attr(name, value) : attr;
}
function _attr_nullish(name, value, attr) {
	return value == null ? attr : _attr(name, value);
}
function _attrs(data, nodeAccessor, scopeId, tagName) {
	let result = "", skip = /[\s/>"'=]/, events;
	switch (data && tagName) {
		case "input":
			data.checkedChange ? (result += _attr_input_checked(scopeId, nodeAccessor, data.checked, data.checkedChange, 1), skip = /^checked(?:Value)?(?:Change)?$|[\s/>"'=]/) : "checkedValue" in data || data.checkedValueChange ? (result += _attr_input_checkedValue(scopeId, nodeAccessor, data.checkedValue, data.checkedValueChange, data.value, 1), skip = /^(?:value|checked(?:Value)?)(?:Change)?$|[\s/>"'=]/) : data.valueChange && (result += _attr_input_value(scopeId, nodeAccessor, data.value, data.valueChange, 1), skip = /^value(?:Change)?$|[\s/>"'=]/);
			break;
		case "select":
		case "textarea":
			("value" in data || data.valueChange) && (skip = /^value(?:Change)?$|[\s/>"'=]/);
			break;
		case "option":
			"value" in data && (result += _attr_option_value(data.value), skip = /^value$|[\s/>"'=]/);
			break;
		case "details":
		case "dialog": data.openChange && (result += _attr_details_or_dialog_open(scopeId, nodeAccessor, data.open, data.openChange, 1), skip = /^open(?:Change)?$|[\s/>"'=]/);
	}
	for (let name in data) {
		let value = data[name];
		switch (name) {
			case "class":
				result += _attr_class(value);
				break;
			case "style":
				result += _attr_style(value);
				break;
			default: name && !(isNullishOrFalse(value) || skip.test(name) || name === "content" && tagName !== "meta") && (isEventHandler(name) ? (events || (events = {}, writeScope(scopeId, { ["I" + nodeAccessor]: events })), events[getEventType(name)] = value) : result += stringifyAttr(name, value));
		}
	}
	return result;
}
function _attrs_content(data, nodeAccessor, scopeId, tagName, markerGuard) {
	_html(`${_attrs(data, nodeAccessor, scopeId, tagName)}>`), _attr_content(nodeAccessor, scopeId, data?.content, markerGuard);
}
function _attrs_partial(data, skip, nodeAccessor, scopeId, tagName) {
	let partial = {};
	for (let name in data) {
		let key = isEventHandler(name) ? `on-${getEventType(name)}` : name;
		skip[key] || (partial[key] = data[name]);
	}
	return _attrs(partial, nodeAccessor, scopeId, tagName);
}
function _attrs_partial_content(data, skip, nodeAccessor, scopeId, tagName, markerGuard) {
	_html(`${_attrs_partial(data, skip, nodeAccessor, scopeId, tagName)}>`), _attr_content(nodeAccessor, scopeId, data?.content, markerGuard);
}
function writeControlledScope(type, scopeId, nodeAccessor, value, valueChange, serializeType) {
	writeScope(scopeId, serializeType ? {
		["F" + nodeAccessor]: type,
		["G" + nodeAccessor]: value,
		["E" + nodeAccessor]: valueChange
	} : {
		["G" + nodeAccessor]: value,
		["E" + nodeAccessor]: valueChange
	});
}
function stringAttr(name, value) {
	return value && " " + name + attrAssignment(value);
}
function stringifyAttr(name, value) {
	switch (typeof value) {
		case "string": return " " + name + attrAssignment(value);
		case "boolean": return " " + name;
		case "number": return " " + name + "=" + value;
	}
	return " " + name + attrAssignment(value + "");
}
function attrAssignment(value) {
	return value ? needsQuotedAttr.test(value) ? value[needsQuotedAttr.lastIndex - 1] === (needsQuotedAttr.lastIndex = 0, "\"") ? "='" + escapeSingleQuotedAttrValue(value) + "'" : "=\"" + escapeDoubleQuotedAttrValue(value) + "\"" : "=" + value : "";
}
function escapeSingleQuotedAttrValue(value) {
	return singleQuoteAttrReplacements.test(value) ? value.replace(singleQuoteAttrReplacements, replaceUnsafeSingleQuoteAttrChar) : value;
}
function replaceUnsafeSingleQuoteAttrChar(match) {
	return match === "'" ? "&#39;" : match === "\r" ? "&#13;" : "&amp;";
}
function escapeDoubleQuotedAttrValue(value) {
	return doubleQuoteAttrReplacements.test(value) ? value.replace(doubleQuoteAttrReplacements, replaceUnsafeDoubleQuoteAttrChar) : value;
}
function replaceUnsafeDoubleQuoteAttrChar(match) {
	return match === "\"" ? "&#34;" : match === "\r" ? "&#13;" : "&amp;";
}
function normalizedValueMatches(a, b) {
	let value = normalizeStrAttrValue(b);
	if (Array.isArray(a)) {
		for (let item of a) if (normalizeStrAttrValue(item) === value) return !0;
	} else if (normalizeStrAttrValue(a) === value) return !0;
	return !1;
}
function normalizeStrAttrValue(value) {
	return isNotNullishOrFalse(value) && value !== !0 ? value + "" : "";
}
//#endregion
//#region src/html/inlined-runtimes.ts
//#endregion
//#region src/html/writer.ts
function getChunk() {
	return $chunk;
}
function withChunk(chunk, cb) {
	let prev = $chunk;
	$chunk = chunk;
	try {
		return cb();
	} finally {
		$chunk = prev;
	}
}
function getContext(key) {
	return $chunk.context?.[key];
}
function getState() {
	return $chunk.boundary.state;
}
function rendererKey(renderer) {
	return renderer?.e === void 0 ? renderer?.a || renderer : renderer.a + " " + renderer.e;
}
function getScopeId(scope) {
	return scope[K_SCOPE_ID];
}
function getScopeById(scopeId) {
	if (scopeId !== void 0) return $chunk.boundary.state.scopes.get(scopeId);
}
function $global() {
	return $chunk.boundary.state.$global;
}
function _id() {
	let state = $chunk.boundary.state, { $global } = state;
	return "s" + $global.runtimeId + $global.renderId + (state.tagId++).toString(36);
}
function _scope_id() {
	return $chunk.boundary.state.scopeId++;
}
function _peek_scope_id() {
	return $chunk.boundary.state.scopeId;
}
function withContext(key, value, cb, cbValue, cbValue2) {
	let ctx = $chunk.context ||= { [kPendingContexts]: 0 }, prev = ctx[key];
	ctx[kPendingContexts]++, ctx[key] = value;
	try {
		return cb(cbValue, cbValue2);
	} finally {
		ctx[kPendingContexts]--, ctx[key] = prev;
	}
}
function captureContext(chunk) {
	chunk.context?.[kPendingContexts] && (chunk.context = {
		...chunk.context,
		[kPendingContexts]: 0
	});
}
function isInResumedBranch() {
	return $chunk?.context?.[kBranchId] !== void 0;
}
function withBranchId(branchId, cb, cbValue, cbValue2) {
	return withContext(kBranchId, branchId, cb, cbValue, cbValue2);
}
function withAsyncContent(async, cb, value) {
	return withContext(kAsyncContent, async, cb, value);
}
function _html(html) {
	$chunk.writeHTML(html);
}
function writeScript(script) {
	$chunk.writeScript(script);
}
function catchableBoundary() {
	let { boundary } = $chunk;
	return boundary.withinCatch ? boundary : null;
}
function mayDrop(written) {
	let { boundary } = $chunk;
	for (let cur = written; cur && !isWithin(boundary, cur); cur = cur.parent) if (cur.aborted || cur.count) return !0;
	return !1;
}
function _script(scopeId, registryId, markerGuard) {
	markerGuard === 0 && ($chunk.channel.readyId || $chunk.context?.[kAsyncContent]) && _resume_branch(scopeId), $chunk.boundary.state.queueEffect(scopeId, registryId);
}
function _trailers(html) {
	$chunk.boundary.state.trailerHTML += html;
}
function _resume(val, id, scopeId, locals) {
	return register(id, val, scopeId === void 0 ? void 0 : _scope_with_id(scopeId), locals);
}
function _resume_locals(val, id, locals, ownerScopeId) {
	return ownerScopeId !== void 0 && (locals._ = _scope_with_id(ownerScopeId)), register(id, val, writeScope(_scope_id(), locals));
}
function _el(scopeId, id) {
	return _resume(() => void 0, id, scopeId);
}
function _hoist(scopeId, id) {
	let getter = () => void 0;
	return getter[Symbol.iterator] = _hoist_read_error, _resume(getter, id, scopeId);
}
function _el_resume(scopeId, accessor, markerGuard) {
	if (markerGuard === 0) return "";
	let { state } = $chunk.boundary;
	return state.needsWalkerRuntime = !0, state.mark("$", scopeId + " " + accessor);
}
function _text_resume(scopeId, accessor, val, markerGuard) {
	return markText(scopeId, accessor, _escape(val), markerGuard);
}
function _html_resume(scopeId, accessor, val, markerGuard) {
	let html = _unescaped(val);
	if (markerGuard === 0 || !~html.indexOf("<")) return markText(scopeId, accessor, html, markerGuard);
	let { state } = $chunk.boundary;
	return state.needsWalkerRuntime = !0, state.mark("&", "") + html + state.mark("'", scopeId + " " + accessor);
}
function markText(scopeId, accessor, text, markerGuard) {
	if (markerGuard === 0) return text;
	let { state } = $chunk.boundary;
	return state.needsWalkerRuntime = !0, text ? (markerGuard === 2 ? "<!>" : "") + text + state.mark("$", scopeId + " " + accessor) : state.mark("%", scopeId + " " + accessor);
}
function _resume_branch(scopeId) {
	let branchId = $chunk.context?.[kBranchId];
	branchId !== void 0 && branchId !== scopeId && writeScope(scopeId, { G: branchId });
}
function _attr_content(nodeAccessor, scopeId, content, markerGuard) {
	let shouldResume = markerGuard !== 0, render = normalizeServerRender(content), branchId = _peek_scope_id();
	if (render) try {
		_set_scope_reason(shouldResume ? ALL_GROUPS : 0), shouldResume ? withBranchId(branchId, render) : render();
	} finally {
		_set_scope_reason(void 0);
	}
	_peek_scope_id() === branchId ? _scope_id() : shouldResume && writeScope(scopeId, {
		["A" + nodeAccessor]: writeScope(branchId, {}),
		["D" + nodeAccessor]: rendererKey(render)
	});
}
function normalizeServerRender(value) {
	let renderer = normalizeDynamicRenderer(value);
	if (renderer && typeof renderer == "function") return renderer;
}
function _var(parentScopeId, scopeOffsetAccessor, childScopeId, registryId, nodeAccessor) {
	writeScopePassive(parentScopeId, { [scopeOffsetAccessor]: _scope_id() });
	let childScope = writeScopePassive(childScopeId, { T: _resume({}, registryId, parentScopeId) });
	nodeAccessor !== void 0 && writeScope(parentScopeId, { ["A" + nodeAccessor]: childScope });
}
function writeScopePassive(scopeId, partialScope) {
	let target = $chunk.channel, scope = _scope_with_id(scopeId);
	return Object.assign(scope, partialScope), $chunk.boundary.state.queuePassiveScope(target, scopeId, partialScope), scope;
}
function _existing_scope(scopeId) {
	return writeScope(scopeId, {});
}
function _scope_with_id(scopeId) {
	return scopeWithId($chunk.boundary.state, scopeId);
}
function scopeWithId(state, scopeId) {
	let { scopes } = state, scope = scopes.get(scopeId);
	return scope || scopes.set(scopeId, scope = { [K_SCOPE_ID]: scopeId }), scope;
}
function _subscribe(subscribers, scope, resumeId, markerGuard) {
	if (subscribers) {
		let { boundary, channel } = $chunk, { serializer } = boundary.state;
		!channel.readyId && !serializer.refs.has(subscribers) ? subscribers.add(scope) : resumeId ? _script(scope[K_SCOPE_ID], resumeId, markerGuard) : queueCall(serializer, scope, subscribers, "add", channel), boundary.withinCatch && (boundary.subscribed ||= []).push(subscribers, scope, channel);
	}
	return scope;
}
function getGroupReason(reason, group) {
	return reason === 715827883 ? 1 : typeof reason == "number" ? group < 15 ? reason >>> 1 + 2 * group & 3 : 0 : reason[group] ?? 0;
}
function _set_scope_reason(reason) {
	$chunk.boundary.state.scopeReason = reason;
}
function _scope_reason() {
	let reason = $chunk.boundary.state.scopeReason;
	return $chunk.boundary.state.scopeReason = void 0, reason;
}
function _write_if(reason, group) {
	return reason && getGroupReason(reason, group) ? 1 : void 0;
}
function _write_guard(reason, group) {
	return _write_if(reason, group) || 0;
}
function writeWaitReady(readyId, renderer, input) {
	let chunk = $chunk, { boundary } = chunk, body = new Chunk(boundary, null, chunk.context, {
		readyId,
		parent: chunk.channel,
		resumes: "",
		writeScopes: {},
		flushScopes: !1
	}), bodyEnd = body.render(renderer, input);
	if (boundary.aborted) throw boundary.reason;
	body === bodyEnd ? (chunk.writeHTML(body.html), body.deferOwnReady(), chunk.deferredReady = push(chunk.deferredReady, body)) : (bodyEnd.next = chunk.forkRest(boundary), chunk.next = body);
}
function deferBranchStart(chunk) {
	let beforeBranch = chunk.html;
	return chunk.html = "", beforeBranch;
}
function applyBranchStart(chunk, beforeBranch, rendered) {
	chunk.html = beforeBranch + (rendered ? chunk.boundary.state.mark("[", "") : "") + chunk.html;
}
function unsubscribe(subscribed, serializer) {
	for (let i = 0; i < subscribed.length; i += 3) {
		let subscribers = subscribed[i], scope = subscribed[i + 1];
		if (!serializer.refs.has(subscribers)) subscribers.delete(scope);
		else {
			let channel = subscribed[i + 2];
			dropQueuedCall(serializer, scope, subscribers, "add", channel) || queueCall(serializer, scope, subscribers, "delete", channel);
		}
	}
}
function countResumeWrite(chunk) {
	for (let boundary = chunk.boundary; boundary; boundary = boundary.parent) boundary.resumeWrites++;
}
function writeAsyncVisits(chunk) {
	for (let async = getAsyncContent(chunk); async && !async.resumed; async = async.parent) async.resumed = !0, async.end?.writeHTML(async.visit);
}
function getAsyncContent(chunk) {
	return chunk.context?.[kAsyncContent];
}
var State = class {
	tagId = 1;
	scopeId = 1;
	reorderId = 1;
	readyGate = 1;
	hasWrittenGlobals = !1;
	needsWalkerRuntime = !1;
	hasWalkerRuntime = !1;
	hasWrittenReady = !1;
	hasReorderRuntime = !1;
	hasWrittenResume = !1;
	walkOnNextFlush = !1;
	trailerHTML = "";
	resumes = "";
	nonceAttr = "";
	serializer = new State$1();
	writeReorders = null;
	scopes = /* @__PURE__ */ new Map();
	scope = (scopeId) => scopeWithId(this, scopeId);
	flushScopes = !1;
	writeScopes = {};
	readyIds = null;
	scopeReason;
	$global;
	constructor($global) {
		this.$global = $global, $global.cspNonce && (this.nonceAttr = " nonce" + attrAssignment($global.cspNonce));
	}
	joinFlush(html, scripts, pending) {
		let { $global, nonceAttr } = this, { __flush__ } = $global;
		return scripts && (html += "<script" + nonceAttr + ">" + scripts + "<\/script>"), __flush__ && ($global.__flush__ = void 0, html = __flush__($global, html)), pending ? html : html + this.trailerHTML;
	}
	walkScript() {
		return this.runtimePrefix + ".w()";
	}
	addResumes(channel, resumes) {
		channel.resumes = concatSequence(channel.resumes, resumes);
	}
	queueScope(target, scopeId, partialScope) {
		let pending = target.writeScopes[scopeId];
		pending && pending !== partialScope ? Object.assign(pending, partialScope) : target.writeScopes[scopeId] = partialScope, target.flushScopes = !0;
	}
	queuePassiveScope(target, scopeId, partialScope) {
		let passive = target.passiveScopes ||= {};
		passive[scopeId] = Object.assign(passive[scopeId] || {}, partialScope);
	}
	queueEffect(scopeId, registryId) {
		this.needsWalkerRuntime = !0, $chunk.writeEffect(scopeId, registryId);
	}
	serializeFlush(boundary) {
		flushSerializer(boundary, this);
	}
	runtimeScript() {
		return "(e=>(self[e]||=(l,f=e+l,s=f.length,a={},d=[],t=document,n=t.createTreeWalker(t,129))=>t=self[e][l]={i:f,d:t,l:a,v:d,x(){},w(e,l,r){for(;e=n.nextNode();)t.x(l=(l=e.data)&&!l.indexOf(f)&&(r=l.slice(s+1),(l=l[s])>\"#\"||(a[r]=e),l),r,e),l>\"#\"&&d.push(e)}},self[e]))(\"" + this.$global.runtimeId + "\")(\"" + this.$global.renderId + "\")";
	}
	keepsTryMarks(chunk, resumeWrites) {
		return chunk !== $chunk || chunk.boundary.resumeWrites !== resumeWrites;
	}
	resumeScript(resumes) {
		return this.hasWrittenResume ? this.runtimePrefix + ".r.push(" + resumes + ")" : (this.hasWrittenResume = !0, this.runtimePrefix + ".r=[" + resumes + "]");
	}
	get runtimePrefix() {
		let { $global } = this;
		return $global.runtimeId + "." + $global.renderId;
	}
	get commentPrefix() {
		let { $global } = this;
		return $global.runtimeId + $global.renderId;
	}
	reorder(chunk) {
		this.writeReorders ? this.writeReorders.push(chunk) : (this.needsWalkerRuntime = !0, this.writeReorders = [chunk]);
	}
	readyScript(id, resumes) {
		let readyKey = toObjectKey(id);
		return this.readyIds?.has(id) ? this.readyAccess(readyKey) + ".push(" + resumes + ")" : ((this.readyIds ||= /* @__PURE__ */ new Set()).add(id), this.hasWrittenReady ? this.readyAccess(readyKey) + "=[" + resumes + "]" : (this.hasWrittenReady = !0, this.runtimePrefix + ".b={" + readyKey + ":[" + resumes + "]}"));
	}
	readyAccess(readyKey) {
		return this.runtimePrefix + ".b" + toAccess(readyKey);
	}
	nextReorderId() {
		let c = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_0123456789", n = this.reorderId++, r = c[n % 54];
		for (n = n / 54 | 0; n; n >>>= 6) r += c[n & 63];
		return r;
	}
	mark(code, str) {
		return "<!--" + this.commentPrefix + code + str + "-->";
	}
}, Boundary = class {
	onNext = NOOP$2;
	count = 0;
	resumeWrites = 0;
	state;
	parent;
	aborted = !1;
	reason;
	subscribed;
	pendingReorders;
	children;
	withinCatch = !1;
	constructor(state, signal, parent) {
		this.state = state, this.parent = parent, parent ? (this.withinCatch = parent.withinCatch, parent.aborted ? this.abort(parent.reason) : (parent.children ||= []).push(this)) : signal && (signal.aborted ? this.abort(signal.reason) : signal.addEventListener("abort", this));
	}
	abort(reason) {
		if (this.aborted) return;
		let { state } = this;
		if (this.aborted = !0, this.reason = reason, this.subscribed && unsubscribe(this.subscribed, state.serializer), this.pendingReorders) {
			for (let reorder of this.pendingReorders) state.reorder(reorder);
			this.pendingReorders = void 0;
		}
		if (this.count = 0, this.state = new State(state.$global), this.children) for (let child of this.children) child.abort(reason);
		this.onNext();
	}
	handleEvent(event) {
		this.abort(event.target.reason);
	}
	flush() {
		return this.aborted || this.state.serializeFlush(this), this.count ? 1 : this.aborted ? 2 : 0;
	}
	startAsync() {
		this.aborted || this.count++;
	}
	endAsync() {
		this.aborted || (this.count--, this.onNext());
	}
}, Chunk = class Chunk {
	html = "";
	scripts = "";
	effects = "";
	lastEffect = "";
	async = !1;
	consumed = !1;
	reorderId = null;
	reorderBranch = 0;
	deferredReady = null;
	heldEffects = null;
	deferredReorder = null;
	catchRange = null;
	placeholder = null;
	boundary;
	next;
	context;
	channel;
	constructor(boundary, next, context, channel) {
		this.boundary = boundary, this.next = next, this.context = context, this.channel = channel;
	}
	fork(boundary, next) {
		return new Chunk(boundary, next, this.context, this.channel);
	}
	forkRest(boundary) {
		return $chunk = this.fork(boundary, this.next);
	}
	writeHTML(html) {
		this.html += html;
	}
	writeEffect(scopeId, registryId) {
		countResumeWrite(this), writeAsyncVisits(this), this.lastEffect === registryId ? this.effects = concatEffects(this.effects, scopeId + "") : (this.lastEffect = registryId, this.effects = concatEffects(this.effects, registryId + " " + scopeId));
	}
	writeScript(script) {
		this.scripts = concatScripts(this.scripts, script);
	}
	append(chunk) {
		this.html += chunk.html, this.effects = concatEffects(this.effects, chunk.effects), this.scripts = concatScripts(this.scripts, chunk.scripts), this.lastEffect = chunk.lastEffect || this.lastEffect, this.deferredReady = concat(this.deferredReady, chunk.takeDeferredReady());
	}
	takeHeldEffects() {
		let { heldEffects } = this;
		return this.heldEffects = null, heldEffects;
	}
	takeDeferredReady() {
		let { deferredReady } = this;
		return this.deferredReady = null, deferredReady;
	}
	deferOwnReady() {
		if (this.channel.readyId && (this.effects || this.scripts || this.channel.flushScopes)) {
			let deferred = this.fork(this.boundary, null);
			deferred.effects = this.effects, deferred.scripts = this.scripts, this.effects = this.scripts = this.lastEffect = "", this.deferredReady = concat(deferred, this.deferredReady);
		}
	}
	renderPlaceholders(boundary) {
		let { state } = boundary;
		restart: for (;;) {
			let reorders = null;
			for (let cur = this; cur.next && !cur.async; cur = cur.next) {
				if (cur.renderPlaceholder(state)) {
					if (boundary.aborted) return;
					continue restart;
				}
				cur.deferredReorder && (reorders ||= []).push(cur.deferredReorder);
			}
			if (state.writeReorders) {
				for (let reorder of state.writeReorders) if ((reorders = renderReorderPlaceholders(reorder, reorders)) === !1) {
					if (boundary.aborted) return;
					continue restart;
				}
			}
			for (let i = 0; reorders && i < reorders.length; i++) if ((reorders = renderReorderPlaceholders(reorders[i], reorders)) === !1) {
				if (boundary.aborted) return;
				continue restart;
			}
			return;
		}
	}
	renderPlaceholder(state) {
		let { placeholder } = this;
		if (!placeholder || (this.placeholder = null, this.boundary.aborted)) return !1;
		let { body } = placeholder, end = body;
		for (; end.next && !end.async;) end = end.next;
		if (!end.async) return end.next = this.next, this.next = body, !1;
		let { branchId, scopeId, placeholderBranchId } = placeholder, reorderId = body.reorderId = branchId + "";
		this.writeHTML(state.mark("!^", reorderId));
		let { effects } = this, beforeBranch = deferBranchStart(this);
		if (this.render(withBranchId, placeholderBranchId, placeholder.render) !== this && this.boundary.abort(/* @__PURE__ */ Error("An @placeholder cannot contain async content.")), this.boundary.aborted) return !0;
		let stateful = this.effects !== effects;
		return applyBranchStart(this, beforeBranch, stateful), stateful && (this.render(writeScope, branchId, { P: scopeWithId(state, placeholderBranchId) }), this.writeHTML(state.mark("]", scopeId + " " + ("P" + branchId) + " " + placeholderBranchId)), dismissChunk(end, body).writeEffect(branchId, "_f")), this.writeHTML(state.mark("!", reorderId)), this.deferredReorder = body, !1;
	}
	markCatchRange() {
		let { catchRange } = this;
		if (catchRange) {
			let { state } = this.boundary;
			this.catchRange = null, this.writeHTML(state.mark("!^", catchRange.id)), catchRange.end.writeHTML(state.mark("!", catchRange.id));
		}
	}
	queueDeferredReorder() {
		let { deferredReorder } = this;
		deferredReorder && (this.deferredReorder = null, deferredReorder.boundary.state.reorder(deferredReorder));
	}
	consume(boundary) {
		this.renderPlaceholders(boundary);
		let cur = this, html = "", effects = "", scripts = "", effectsEnd, heldEffects = this.heldEffects, deferredReady;
		for (this.heldEffects = null, this.channel.readyId && this.effects && followHeldEffects(this); cur.next && !cur.async;) cur.markCatchRange(), cur.queueDeferredReorder(), html += cur.html, cur.channel.readyId ? deferredReady = push(deferredReady, cur) : (cur.effects && (effectsEnd && effectsEnd.boundary !== cur.boundary && (heldEffects = holdEffectsOn(heldEffects, effectsEnd, effects), effects = ""), effectsEnd = cur, effects = concatEffects(effects, cur.effects)), scripts = concatScripts(scripts, cur.scripts)), deferredReady = concat(deferredReady, cur.takeDeferredReady()), cur.consumed = !0, cur = cur.next;
		return cur.deferOwnReady(), effects && (cur.channel.readyId ? heldEffects = holdEffectsOn(heldEffects, effectsEnd, effects) : effectsEnd.boundary === cur.boundary ? (cur.effects = concatEffects(effects, cur.effects), cur.lastEffect ||= effectsEnd.lastEffect) : (heldEffects = holdEffectsOn(heldEffects, effectsEnd, effects), isWithin(cur.boundary, effectsEnd.boundary) && (cur.lastEffect ||= effectsEnd.lastEffect))), cur.heldEffects = heldEffects, cur.deferredReady = concat(deferredReady, cur.deferredReady), cur.html = html + cur.html, cur.scripts = concatScripts(scripts, cur.scripts), cur;
	}
	render(content, val, val2) {
		let prev = $chunk;
		$chunk = this;
		try {
			return content(val, val2), $chunk;
		} catch (err) {
			return this.boundary.abort(err), this;
		} finally {
			$chunk = prev;
		}
	}
	flushReadyScripts(boundary, reservations, holdEffects) {
		let { channel } = this, { readyId } = channel, scripts = "", held = this.takeDeferredReady();
		if (held) for (let chunk of Array.isArray(held) ? held : [held]) chunk.boundary.aborted || (scripts = concatScripts(scripts, chunk.flushReadyScripts(boundary, reservations, holdEffects)), (chunk.effects || chunk.deferredReady) && (this.deferredReady = push(this.deferredReady, chunk)));
		if (readyId && !this.async) {
			let { state } = boundary;
			flushSerializer(boundary, channel);
			let deps = takeChannelDeps(state.serializer), effects = holdEffects ? "" : this.effects, { resumes } = channel, chunkScripts = this.scripts;
			if (channel.resumes = this.scripts = "", effects && (this.effects = this.lastEffect = ""), resumes || effects) {
				state.needsWalkerRuntime = !0;
				let batch = concatSequence(depsMarker(deps), concatSequence(resumes, effects && `"${effects}"`));
				if (reservations) {
					let gate = state.readyGate++;
					reservations.push(state.readyScript(readyId, gate + "")), scripts = concatScripts(scripts, "(b=>b.splice(b.indexOf(" + gate + "),1," + batch + "))(" + state.readyAccess(toObjectKey(readyId)) + ")");
				} else scripts = concatScripts(scripts, state.readyScript(readyId, batch));
			}
			scripts = concatScripts(scripts, chunkScripts);
		}
		return scripts;
	}
	flush(boundary) {
		let { state } = boundary, { runtimePrefix } = state, needsWalk = state.walkOnNextFlush;
		needsWalk && (state.walkOnNextFlush = !1), flushSerializer(boundary, state);
		let readyResumeScripts = this.flushReadyScripts(boundary, void 0, this.async);
		for (let channel; !boundary.aborted && (channel = pendingReadyChannel(state.serializer));) {
			let resumes = stringifyScopes(state.serializer, [], boundary, channel), deps = takeChannelDeps(state.serializer);
			state.needsWalkerRuntime = !0, readyResumeScripts = concatScripts(readyResumeScripts, state.readyScript(channel.readyId, concatSequence(depsMarker(deps), resumes)));
		}
		readyResumeScripts && (needsWalk = !0);
		let effects = this.async ? "" : joinHeldEffects(this.takeHeldEffects(), this.effects), { html, scripts } = this;
		html && state.hasReorderRuntime && (html = state.mark("*", "") + html), state.needsWalkerRuntime && !state.hasWalkerRuntime && (state.hasWalkerRuntime = !0, scripts = concatScripts(scripts, state.runtimeScript())), scripts = concatScripts(scripts, readyResumeScripts), effects && (needsWalk = !0, state.resumes = state.resumes ? state.resumes + ",\"" + effects + "\"" : "\"" + effects + "\"");
		let reordered = "", needsResumeArray = !1;
		if (state.writeReorders) {
			for (let reorderedChunk of state.writeReorders) {
				needsWalk = !0, state.hasReorderRuntime || (state.hasReorderRuntime = !0, scripts = concatScripts(scripts, "(e=>{if(e.j)return;let i,l,r,t=e.p={},c=(i,l)=>e.l[i].replaceWith(...l.childNodes);e.j={},e.x=(n,a,d,o,g)=>{d==r&&i(),\"#\"==n?(t[a]=l).i++:\"T\"==d.tagName&&(a=d.getAttribute(e.i))&&(r=d.nextSibling,i=()=>{d.remove(),o||c(a,d),l.c()},l=t[a]||(o=t[a]={i:1,r:a,c(i=e.l[\"^\"+a],f=d.cloneNode()){if(--o.i)return 1;for(;f.prepend(r=e.l[a].previousSibling||i),i!=r;);c(a,d)}}),e.v.push({data:e.i+\"*\"+l.r}),(n=e.j[a])&&(g=l.c,l.c=()=>g()||n(e.r)))}})(" + runtimePrefix + ")"));
				let { reorderId, reorderBranch } = reorderedChunk, rootBranch = reorderBranch || +reorderId, readyReservations = [], reorderHTML = "", reorderEffects = "", effectsBoundary = reorderedChunk.boundary, reorderScripts = "", cur = reorderedChunk.boundary.aborted ? null : reorderedChunk;
				for (reorderedChunk.reorderId = null; cur;) {
					cur.markCatchRange(), cur.queueDeferredReorder(), cur.deferOwnReady();
					let { next } = cur, readyResumeScripts = cur.flushReadyScripts(boundary, readyReservations, this.async);
					if (this.deferredReady = concat(this.deferredReady, cur.takeDeferredReady()), cur.consumed = !0, reorderHTML += cur.html, this.async && cur.effects && cur.boundary !== effectsBoundary && (reorderEffects &&= (holdReorderEffects(this, effectsBoundary, reorderEffects), ""), effectsBoundary = cur.boundary), reorderEffects = concatEffects(reorderEffects, cur.effects), reorderScripts = concatScripts(reorderScripts, concatScripts(readyResumeScripts, cur.scripts)), cur.async) {
						reorderHTML += state.mark("#", cur.reorderId = state.nextReorderId());
						let holeBranch = cur.context?.[kBranchId];
						cur.reorderBranch = holeBranch > rootBranch ? holeBranch : reorderBranch, (cur.boundary.pendingReorders ||= /* @__PURE__ */ new Set()).add(cur), cur.html = cur.effects = cur.scripts = cur.lastEffect = "", cur.next = null;
					}
					cur = next;
				}
				reorderEffects && (this.async ? holdReorderEffects(this, effectsBoundary, reorderEffects) : (needsResumeArray = !0, reorderScripts = concatScripts(reorderScripts, "_.push(\"" + reorderEffects + "\")")));
				for (let reservation of readyReservations) reordered = concatScripts(reordered, reservation);
				reordered = concatScripts(reordered, reorderScripts && runtimePrefix + ".j" + toAccess(reorderId) + "=_=>{" + reorderScripts + "}"), html += "<t hidden " + state.commentPrefix + "=" + reorderId + ">" + (reorderBranch ? state.mark("*", reorderBranch + "") : "") + reorderHTML + "</t>";
			}
			state.writeReorders = null;
		}
		return (state.resumes || needsResumeArray && !state.hasWrittenResume) && (scripts = concatScripts(scripts, state.resumeScript(state.resumes))), scripts = concatScripts(scripts, reordered), needsWalk && (scripts = concatScripts(scripts, state.walkScript())), this.html = html, this.scripts = scripts, this.async || (this.effects = this.lastEffect = ""), state.resumes = "", this;
	}
	flushHTML(boundary) {
		let { state } = boundary;
		this.flush(boundary);
		let { html, scripts } = this;
		return this.html = this.scripts = "", state.joinFlush(html, scripts, boundary.count);
	}
};
function renderReorderPlaceholders(reorder, reorders) {
	if (!reorder.boundary.aborted) for (let cur = reorder; cur; cur = cur.next) {
		if (cur.renderPlaceholder(reorder.boundary.state)) return !1;
		cur.deferredReorder && (reorders ||= []).push(cur.deferredReorder);
	}
	return reorders;
}
function dismissChunk(end, body) {
	if (end.boundary !== body.boundary) for (; end.next;) end = end.next;
	return end;
}
function followHeldEffects(chunk) {
	let held = reduce(chunk.deferredReady, lastHeldOf, chunk);
	held !== chunk && (held.effects = concatEffects(held.effects, chunk.effects), chunk.effects = "");
}
function lastHeldOf(held, cur) {
	return cur.channel === held.channel && cur.boundary === held.boundary ? cur : held;
}
function holdEffectsOn(heldEffects, chunk, effects) {
	return chunk.effects = effects, push(heldEffects, chunk);
}
function isWithin(boundary, outer) {
	for (; boundary && boundary !== outer;) boundary = boundary.parent;
	return !!boundary;
}
function holdReorderEffects(head, boundary, effects) {
	head.channel.readyId || (head.effects && (head.heldEffects = holdEffectsOn(head.heldEffects, head.fork(head.boundary, null), head.effects)), head.effects = head.lastEffect = ""), head.heldEffects = holdEffectsOn(head.heldEffects, head.fork(boundary, null), effects);
}
function joinHeldEffects(heldEffects, effects) {
	return concatEffects(reduce(heldEffects, joinUncaught, ""), effects);
}
function joinUncaught(joined, held) {
	return held.boundary.aborted ? joined : concatEffects(joined, held.effects);
}
function flushSerializer(boundary, channel) {
	let { state } = boundary, { serializer } = state, pending = hasMatchingCalls(serializer, channel.readyId);
	if (channel.flushScopes || pending) {
		let { writeScopes, passiveScopes } = channel, flushes = [];
		if (passiveScopes) for (let key in passiveScopes) {
			let props = writeScopes[key];
			props && (writeScopes[key] = Object.assign(passiveScopes[key], props), delete passiveScopes[key]);
		}
		if (!channel.readyId && !state.hasWrittenGlobals) {
			state.hasWrittenGlobals = !0;
			let globals = getFilteredGlobals(state.$global);
			globals && flushes.push([
				0,
				globals,
				globals
			]);
		}
		for (let key in writeScopes) {
			let scopeId = +key, props = writeScopes[scopeId];
			hasKeys(props) && flushes.push([
				scopeId,
				state.scopes.get(scopeId),
				props
			]);
		}
		(flushes.length || pending) && (channel.readyId && !state.hasWrittenGlobals && flushSerializerGlobals(boundary), state.addResumes(channel, stringifyScopes(serializer, flushes, boundary, channel))), channel.writeScopes = {}, channel.flushScopes = !1, pending && (state.walkOnNextFlush = !0);
	}
}
function flushSerializerGlobals(boundary) {
	let { state } = boundary, globals = getFilteredGlobals(state.$global);
	globals && (state.hasWrittenGlobals = !0, state.needsWalkerRuntime = !0, state.resumes = concatSequence(state.resumes, stringifyScopes(state.serializer, [[
		0,
		globals,
		globals
	]], boundary)));
}
function depsMarker(deps) {
	let marker = "";
	if (deps) {
		for (let dep of deps) marker += (marker ? "," : "[") + quote(dep, 0);
		marker += "]";
	}
	return marker;
}
function getFilteredGlobals($global) {
	if (!$global) return 0;
	let serializedGlobals = $global.serializedGlobals;
	if (!serializedGlobals) return 0;
	let filtered = 0;
	if (Array.isArray(serializedGlobals)) for (let key of serializedGlobals) {
		let value = $global[key];
		value !== void 0 && (filtered ? filtered[key] = value : filtered = { [key]: value });
	}
	else for (let key in serializedGlobals) if (serializedGlobals[key]) {
		let value = $global[key];
		value !== void 0 && (filtered ? filtered[key] = value : filtered = { [key]: value });
	}
	return filtered;
}
function concatEffects(a, b) {
	return a ? b ? a + " " + b : a : b;
}
function concatSequence(a, b) {
	return a ? b ? a + "," + b : a : b;
}
function concatScripts(a, b) {
	return a ? b ? a + ";" + b : a : b;
}
function queueTick(cb) {
	tickQueue ? tickQueue.add(cb) : (tickQueue = /* @__PURE__ */ new Set([cb]), tick(flushTickQueue));
}
function offTick(cb) {
	tickQueue?.delete(cb);
}
function flushTickQueue() {
	let queue = tickQueue;
	tickQueue = void 0;
	for (let cb of queue) try {
		cb(!0);
	} catch (err) {
		tick(() => {
			throw err;
		});
	}
}
//#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 escapeCommentStr(str) {
	return unsafeCommentReg.test(str) && (str = str.replace(unsafeCommentReg, "&gt;")), str.startsWith(getState().commentPrefix) ? "&#" + str.charCodeAt(0) + ";" + str.slice(1) : str;
}
function _escape_comment(val) {
	return val ? escapeCommentStr(val + "") : val === 0 ? "0" : "";
}
//#endregion
//#region src/html/dynamic-tag.ts
function _content(id, fn, scopeId) {
	return fn.a = id, fn.e = scopeId, fn;
}
function _content_resume(id, fn, scopeId, locals) {
	return _resume(_content(id, fn, scopeId), id, scopeId, locals);
}
//#endregion
//#region src/html/template.ts
function render(input = {}) {
	return startRender(this, input, State);
}
function startRender(template, input, StateClass) {
	let { $global } = input;
	$global ? ({$global, ...input} = input, $global = {
		runtimeId: "M",
		renderId: getDefaultRenderId(template),
		...$global
	}) : $global = {
		runtimeId: "M",
		renderId: getDefaultRenderId(template)
	};
	let state = new StateClass($global), head = new Chunk(new Boundary(state, $global.signal), null, null, state);
	return template.i ? head.render(() => writeWaitReady(template.a, template, input)) : head.render(template, input), new ServerRendered(head);
}
function getDefaultRenderId(template) {
	if (template.i) {
		let ENCODE_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_0123456789", n = Math.random() * 4294967296 >>> 0, r = ENCODE_CHARS[n % 52];
		for (n = n / 52 | 0; n; n = n / 63 | 0) r += ENCODE_CHARS[n % 63];
		return r;
	}
	return "_";
}
var ServerRendered = class {
	#head;
	#cachedPromise = null;
	constructor(head) {
		this.#head = head;
	}
	[Symbol.asyncIterator]() {
		let resolve, reject, value = "", done = !1, aborted = !1, reason, boundary = this.#read((html) => {
			if (value += html, resolve) {
				let settle = resolve;
				resolve = reject = void 0, settle({
					value,
					done
				}), value = "";
			}
		}, (err) => {
			if (aborted = !0, reason = err, reject) {
				let settle = reject;
				resolve = reject = void 0, settle(err);
			}
		}, () => {
			if (done = !0, resolve) {
				let settle = resolve;
				resolve = reject = void 0, settle({
					value,
					done: !value
				}), value = "";
			}
		});
		return {
			next() {
				if (aborted) return Promise.reject(reason);
				if (value) {
					let result = {
						value,
						done: !1
					};
					return value = "", Promise.resolve(result);
				}
				return done ? Promise.resolve({
					value: "",
					done
				}) : new Promise(exec);
			},
			throw(error) {
				return done || aborted || boundary?.abort(error), Promise.resolve({
					value: "",
					done: !0
				});
			},
			return(value) {
				return done || aborted || boundary?.abort(/* @__PURE__ */ Error("Iterator returned before consumed.")), Promise.resolve({
					value,
					done: !0
				});
			}
		};
		function exec(_resolve, _reject) {
			resolve = _resolve, reject = _reject;
		}
	}
	pipe(stream) {
		this.#read((html) => {
			stream.write(html), stream.flush?.();
		}, (err) => {
			let socket = "socket" in stream && stream.socket;
			if (socket && typeof socket.destroySoon == "function" ? socket.destroySoon() : stream.destroy ? stream.destroy() : stream.end(), !stream.emit?.("error", err)) throw err;
		}, () => {
			stream.end();
		});
	}
	toReadable() {
		let cancelled = !1, started = !1, boundary, encoder = new TextEncoder();
		return new ReadableStream({
			pull: (ctrl) => {
				started || (started = !0, boundary = this.#read((html) => {
					ctrl.enqueue(encoder.encode(html));
				}, (err) => {
					boundary = void 0, cancelled || ctrl.error(err);
				}, () => {
					boundary = void 0, ctrl.close();
				}));
			},
			cancel: (reason) => {
				cancelled = !0, boundary?.abort(reason);
			}
		}, { highWaterMark: 0 });
	}
	then(onfulfilled, onrejected) {
		return this.#promise().then(onfulfilled, onrejected);
	}
	catch(onrejected) {
		return this.#promise().catch(onrejected);
	}
	finally(onfinally) {
		return this.#promise().finally(onfinally);
	}
	#promise() {
		return this.#cachedPromise ||= new Promise((resolve, reject) => {
			let head = this.#head;
			if (this.#head = null, !head) return reject(/* @__PURE__ */ Error(CONSUMED_RESULT_MESSAGE));
			let { boundary } = head, html = "";
			(boundary.onNext = () => {
				switch (!boundary.count && boundary.flush()) {
					case 2:
						settle(boundary), reject(boundary.reason);
						break;
					case 0:
						if (head = head.consume(boundary), boundary.aborted) break;
						html += head.flushHTML(boundary), boundary.count || boundary.aborted || (settle(boundary), resolve(html));
				}
			})();
		});
	}
	#read(onWrite, onAbort, onClose) {
		let tick = !0, flushing = !1, again = !1, head = this.#head;
		if (this.#head = null, !head) {
			onAbort(/* @__PURE__ */ Error(CONSUMED_RESULT_MESSAGE));
			return;
		}
		let { boundary } = head, onNext = boundary.onNext = (write) => {
			if (flushing) {
				again = !0;
				return;
			}
			flushing = !0;
			do {
				again = !1;
				let status = boundary.flush();
				if (status === 2) {
					tick || offTick(onNext), settle(boundary), onAbort(boundary.reason);
					return;
				}
				if (write || status === 0) {
					if (head = head.consume(boundary), boundary.aborted) continue;
					let html = head.flushHTML(boundary);
					if (boundary.aborted) continue;
					if (html && onWrite(html), !boundary.count) {
						tick || offTick(onNext), settle(boundary), onClose();
						return;
					}
					write && (tick = !0);
				} else tick && (tick = !1, queueTick(onNext));
			} while (again);
			flushing = !1;
		};
		return onNext(), boundary;
	}
	toString() {
		let head = this.#head;
		if (this.#head = null, !head) throw Error(CONSUMED_RESULT_MESSAGE);
		let { boundary } = head, html = boundary.flush() === 0 ? head.consume(boundary).flushHTML(boundary) : "";
		if (boundary.count && boundary.abort(/* @__PURE__ */ Error("Cannot consume asynchronous render with 'toString'")), settle(boundary), boundary.aborted) throw boundary.reason;
		return html;
	}
};
function settle(boundary) {
	boundary.onNext = NOOP$1, boundary.state.$global.signal?.removeEventListener("abort", boundary);
}
function NOOP$1() {}
//#endregion
//#region src/html/assets.ts
function withLoadAssets(renderer, flush, assetId, triggers) {
	return register(renderer.a, Object.assign((input) => (writeLoadAsset(assetId, flush, triggers), writeWaitReady(assetId, renderer, input)), renderer));
}
function writeLoadAsset(assetId, flush, triggers) {
	let g = $global();
	writeAsset(g, addAsset(g, assetId, flush, triggers));
}
function withPageAssets(template, flush, assetId, runtimeId) {
	return Object.assign((input) => {
		let g = $global();
		runtimeId && (g[kAssets] || (g.runtimeId = runtimeId));
		let asset = addAsset(g, assetId, flush);
		return g.__flush__ ? (writeAsset(g, asset), writeWaitReady(assetId, template, input)) : (g.__flush__ = flushPage, template(input));
	}, template);
}
function _flush_head() {
	let g = $global();
	return g[kAssets] ? (g[kHead] = !0, takeAssets(g, catchableBoundary())) : "";
}
function flushPage(g, html) {
	return takeAssets(g, null) + html;
}
function takeAssets(g, at) {
	let block = "", defer = "";
	for (let asset of g[kAssets]) asset.htmlAt === void 0 && (asset.htmlAt = at, block += blockHTML(g, asset), asset.triggers || (defer += deferHTML(g, asset)));
	return block + defer;
}
function writeAsset(g, asset) {
	if (needsWrite(asset.htmlAt) && (asset.htmlAt = void 0, g[kHead] || g.__flush__ !== flushPage)) {
		let block = blockHTML(g, asset);
		_html(block + (asset.triggers ? "" : deferHTML(g, asset))), block && isInResumedBranch() && writeScript(`document.head.insertAdjacentHTML("beforeend",${quoteScriptTemplateLiteral(block)})`), asset.htmlAt = catchableBoundary();
	}
	if (asset.triggers && needsWrite(asset.scriptAt)) {
		let defer = deferHTML(g, asset);
		defer && writeScript(asset.script ||= triggerScript(asset.id, defer, asset.triggers)), asset.scriptAt = catchableBoundary();
	}
}
function needsWrite(at) {
	return at === void 0 || at !== null && mayDrop(at);
}
function blockHTML(g, asset) {
	return asset.block ??= asset.flush(g, "block", asset.id);
}
function deferHTML(g, asset) {
	return asset.defer ??= asset.flush(g, "defer", asset.id);
}
function addAsset(g, id, flush, triggers) {
	let assets = g[kAssets] ||= [], asset = assets.find((a) => a.id === id);
	return asset || assets.push(asset = {
		id,
		flush,
		triggers,
		block: void 0,
		defer: void 0,
		script: void 0,
		htmlAt: void 0,
		scriptAt: void 0
	}), asset;
}
function triggerScript(id, html, triggers) {
	let htmlStr = quoteScriptTemplateLiteral(html), exprs = triggers.map((trigger) => {
		let options = trigger.options && toObjectExpression(trigger.options);
		switch (trigger.type) {
			case "visible": return `(e=>e&&new IntersectionObserver((e,i)=>e.some(e=>e.isIntersecting)&&i.disconnect()+l()${options ? `,${options}` : ""}).observe(e))(${querySelectorOrLoad(trigger.selector)})`;
			case "idle": return `(self.requestIdleCallback||l)(l${options ? `,${options}` : ""})`;
			case "media": return `(m=>m.matches?l():m.addEventListener("change",l,{once:1}))(matchMedia(${JSON.stringify(trigger.selector)}))`;
			default: return `(e=>e?.addEventListener("${trigger.type.slice(3)}",l,{once:1}))(${querySelectorOrLoad(trigger.selector)})`;
		}
	});
	return `((h,d,l=$=>{d||document.head.append(new Range().createContextualFragment(d=h))})=>${exprs.length > 1 ? `{${exprs.join(";")}}` : exprs[0]})(${htmlStr})`;
}
function querySelectorOrLoad(selector) {
	return `document.querySelector(${JSON.stringify(selector)})||l()`;
}
function toObjectExpression(options) {
	let result = "{", sep = "";
	for (let key in options) Object.hasOwn(options, key) && (result += sep + toObjectKey(key) + ":" + JSON.stringify(options[key]), sep = ",");
	return result + "}";
}
//#endregion
//#region src/common/compat-meta.ts
//#endregion
//#region src/common/for.ts
function forIn(obj, cb) {
	for (let key in obj) cb(key, obj[key]);
}
function forOf(list, cb) {
	if (list) {
		let i = 0;
		for (let item of list) cb(item, i++);
	}
}
function forTo(to, from, step, cb) {
	let start = from || 0, delta = step || 1;
	for (let steps = (to - start) / delta, i = 0; i <= steps; i++) cb(start + i * delta);
}
function forUntil(until, from, step, cb) {
	let start = from || 0, delta = step || 1;
	for (let steps = (until - start) / delta, i = 0; i < steps; i++) cb(start + i * delta);
}
//#endregion
//#region src/html/for.ts
function forOfBy(by, item, index) {
	return by ? typeof by == "string" ? item[by] : by(item, index) : index;
}
function forInBy(by, name, value) {
	return by ? by(name, value) : name;
}
function forStepBy(by, index) {
	return by ? by(index) : index;
}
//#endregion
//#region src/html/control-flow.ts
function _show_start(display, markerGuard, branchExprGuard, parentEndTag) {
	display ? resumesMarker(markerGuard, branchExprGuard, parentEndTag) && $chunk.writeHTML($chunk.boundary.state.mark("[", "")) : $chunk.writeHTML("<t hidden>");
}
function _show_end(scopeId, accessor, display, markerGuard, branchExprGuard, parentEndTag, singleNode) {
	let branchId = _scope_id(), wrap = !display;
	wrap && $chunk.writeHTML("</t>"), writeBranchEnd(scopeId, accessor, branchExprGuard, markerGuard, parentEndTag, wrap || singleNode ? 1 : void 0, " " + branchId);
}
function _for_of(list, cb, by, scopeId, accessor, branchGuard, markerGuard, branchExprGuard, parentEndTag, singleNode) {
	forBranches(by, cb, iterateForOf(list, cb, by), scopeId, accessor, branchGuard, markerGuard, branchExprGuard, parentEndTag, singleNode);
}
function iterateForOf(list, cb, by) {
	return (each) => each ? forOf(list, (item, index) => {
		let itemKey = forOfBy(by, item, index);
		each(itemKey, itemKey === index, item, index);
	}) : forOf(list, cb);
}
function _for_in(obj, cb, by, scopeId, accessor, branchGuard, markerGuard, branchExprGuard, parentEndTag, singleNode) {
	forBranches(by, cb, iterateForIn(obj, cb, by), scopeId, accessor, branchGuard, markerGuard, branchExprGuard, parentEndTag, singleNode);
}
function iterateForIn(obj, cb, by) {
	return (each) => each ? forIn(obj, (key, value) => {
		each(forInBy(by, key, value), !1, key, value);
	}) : forIn(obj, cb);
}
function _for_to(to, from, step, cb, by, scopeId, accessor, branchGuard, markerGuard, branchExprGuard, parentEndTag, singleNode) {
	forBranches(by, cb, iterateForTo(to, from, step, cb, by), scopeId, accessor, branchGuard, markerGuard, branchExprGuard, parentEndTag, singleNode);
}
function iterateForTo(to, from, step, cb, by) {
	return (each) => {
		let index = 0;
		return each ? forTo(to, from, step, (value) => {
			let itemKey = forStepBy(by, value);
			each(itemKey, itemKey === index++, value);
		}) : forTo(to, from, step, cb);
	};
}
function _for_until(until, from, step, cb, by, scopeId, accessor, branchGuard, markerGuard, branchExprGuard, parentEndTag, singleNode) {
	forBranches(by, cb, iterateForUntil(until, from, step, cb, by), scopeId, accessor, branchGuard, markerGuard, branchExprGuard, parentEndTag, singleNode);
}
function iterateForUntil(until, from, step, cb, by) {
	return (each) => {
		let index = 0;
		return each ? forUntil(until, from, step, (value) => {
			let itemKey = forStepBy(by, value);
			each(itemKey, itemKey === index++, value);
		}) : forUntil(until, from, step, cb);
	};
}
function forBranches(by, cb, iterate, scopeId, accessor, branchGuard, markerGuard, branchExprGuard, parentEndTag, singleNode) {
	if (branchGuard === 0) {
		iterate(0), writeBranchEnd(scopeId, accessor, branchExprGuard, markerGuard, parentEndTag, singleNode, "");
		return;
	}
	let { state } = $chunk.boundary, resumeKeys = markerGuard !== 0, resumeMarker = resumesMarker(markerGuard, branchExprGuard, parentEndTag), flushBranchIds = "", loopScopes;
	iterate((itemKey, sameAsIndex, a, b) => {
		let branchId = _peek_scope_id();
		resumeMarker && (singleNode ? flushBranchIds = " " + branchId + flushBranchIds : ($chunk.writeHTML(state.mark("[", flushBranchIds)), flushBranchIds = branchId + "")), withBranchId(branchId, cb, a, b);
		let branchScope = writeScope(branchId, resumeKeys && !sameAsIndex ? { M: itemKey } : {});
		resumeMarker || (loopScopes = push(loopScopes, branchScope));
	}), loopScopes && writeScope(scopeId, { ["A" + accessor]: loopScopes }), writeBranchEnd(scopeId, accessor, branchExprGuard, markerGuard, parentEndTag, singleNode, singleNode ? flushBranchIds : flushBranchIds ? " " + flushBranchIds : "");
}
function _if(cb, scopeId, accessor, branchGuard, markerGuard, branchExprGuard, parentEndTag, singleNode) {
	let resumeBranch = branchGuard !== 0, resumeMarker = resumesMarker(markerGuard, branchExprGuard, parentEndTag), branchId = _peek_scope_id(), chunk = $chunk, beforeBranch = resumeMarker && resumeBranch && !singleNode ? deferBranchStart(chunk) : void 0, branchIndex = resumeBranch ? withBranchId(branchId, cb) : cb(), shouldWriteBranch = resumeBranch && branchIndex !== void 0;
	beforeBranch !== void 0 && applyBranchStart(chunk, beforeBranch, shouldWriteBranch), shouldWriteBranch && (branchIndex || !resumeMarker) && writeScope(scopeId, {
		["D" + accessor]: branchIndex || void 0,
		["A" + accessor]: resumeMarker ? void 0 : writeScope(branchId, {})
	}), writeBranchEnd(scopeId, accessor, branchExprGuard, markerGuard, parentEndTag, singleNode, shouldWriteBranch ? " " + branchId : "");
}
function resumesMarker(markerGuard, branchExprGuard, parentEndTag) {
	return markerGuard !== 0 && (!parentEndTag || branchExprGuard !== 0);
}
function writeBranchEnd(scopeId, accessor, branchExprGuard, markerGuard, parentEndTag, singleNode, branchIds) {
	let endTag = parentEndTag || "";
	if (resumesMarker(markerGuard, branchExprGuard, parentEndTag)) {
		let { state } = $chunk.boundary, mark = singleNode ? state.mark(parentEndTag ? "}" : "|", scopeId + " " + accessor + (branchIds || "")) : state.mark(parentEndTag ? ")" : "]", scopeId + " " + accessor + (branchIds || ""));
		$chunk.writeHTML(mark + endTag);
	} else markerGuard === 0 ? $chunk.writeHTML(endTag) : $chunk.writeHTML(endTag + _el_resume(scopeId, accessor));
}
function _await(scopeId, accessor, promise, content, markerGuard) {
	let resumeMarker = markerGuard !== 0;
	if (!isPromise(promise)) {
		if (resumeMarker) {
			let branchId = _peek_scope_id();
			$chunk.writeHTML($chunk.boundary.state.mark("[", "")), withBranchId(branchId, content, promise), $chunk.writeHTML($chunk.boundary.state.mark("]", scopeId + " " + accessor + " " + branchId));
		} else content(promise);
		return;
	}
	let chunk = $chunk, { boundary } = chunk, startId = _peek_scope_id(), after = chunk.next = chunk.forkRest(boundary);
	chunk.async = !0, captureContext(chunk), boundary.startAsync(), promise.then((value) => {
		if (chunk.async && (chunk.async = !1, !boundary.aborted)) {
			let { state } = boundary;
			chunk.render(() => {
				if (resumeMarker) {
					let branchId = _peek_scope_id();
					$chunk.writeHTML($chunk.boundary.state.mark("[", "")), withBranchId(branchId, () => withAsyncContent({ parent: getAsyncContent(chunk) }, content, value)), $chunk.writeHTML($chunk.boundary.state.mark("]", scopeId + " " + accessor + " " + branchId));
				} else {
					let renderedSince = _peek_scope_id() !== startId, async = { parent: getAsyncContent(chunk) };
					withAsyncContent(async, content, value), async.visit = renderedSince && (after.html || after.next) ? $chunk.boundary.state.mark("]", scopeId + " " + accessor) : "", async.resumed && $chunk.writeHTML(async.visit), async.end = $chunk;
				}
			}), !chunk.async && boundary.pendingReorders?.delete(chunk) && state.reorder(chunk), boundary.endAsync();
		}
	}, (err) => {
		chunk.async = !1, boundary.abort(err);
	});
}
function _try(scopeId, accessor, content, placeholderContent, catchContent, placeholderId, catchId) {
	let placeholderBranchId = placeholderContent ? _scope_id() : 0, branchId = _peek_scope_id(), chunk = $chunk, { boundary } = chunk, { state } = boundary, { resumeWrites } = boundary, beforeBranch = deferBranchStart(chunk), renderers = () => writeTryRenderers(branchId, catchContent && _resume(catchContent, catchId), placeholderContent && _resume(placeholderContent, placeholderId)), writesRenderers = tryBoundary(placeholderContent ? () => tryPlaceholder(content, placeholderContent, branchId, scopeId, placeholderBranchId) : content, catchContent, branchId, renderers), keepsMarks = state.keepsTryMarks(chunk, resumeWrites);
	applyBranchStart(chunk, beforeBranch, keepsMarks), keepsMarks && (writesRenderers || renderers(), $chunk.writeHTML(state.mark("]", scopeId + " " + accessor + " " + branchId)));
}
function tryPlaceholder(content, placeholder, branchId, scopeId, placeholderBranchId) {
	let chunk = $chunk, { boundary } = chunk, body = chunk.fork(boundary, null);
	if (body === body.render(content)) {
		chunk.append(body);
		return;
	}
	chunk.next = chunk.forkRest(boundary), captureContext(chunk), chunk.placeholder = {
		body,
		render: placeholder,
		branchId,
		scopeId,
		placeholderBranchId
	};
}
function tryBoundary(content, catchContent, branchId, renderers) {
	let chunk = $chunk, { boundary } = chunk, { state } = boundary, bodyBoundary = new Boundary(state, void 0, boundary);
	catchContent && (bodyBoundary.withinCatch = !0);
	let body = chunk.fork(bodyBoundary, null), bodyEnd = body.render(withBranchId, branchId, content);
	if (bodyBoundary.aborted) {
		if (!catchContent) throw bodyBoundary.reason;
		return catchContent(bodyBoundary.reason), !0;
	}
	if (body === bodyEnd) return chunk.append(body), !1;
	let renderersAtSettle = !bodyBoundary.resumeWrites, bodyNext = bodyEnd.next = chunk.forkRest(boundary);
	chunk.next = body, boundary.startAsync();
	let reorderId = catchContent ? state.nextReorderId() : "";
	return reorderId && (chunk.catchRange = {
		id: reorderId,
		end: bodyEnd
	}, captureContext(chunk)), bodyBoundary.onNext = () => {
		if (!boundary.aborted) {
			if (bodyBoundary.aborted) {
				if (!reorderId) {
					boundary.abort(bodyBoundary.reason);
					return;
				}
				let streamed = !chunk.catchRange, catchChunk = chunk.fork(boundary, null);
				chunk.catchRange = null, renderersAtSettle || catchChunk.render(clearTryRenderers, branchId);
				let inOrder = catchChunk === catchChunk.render(catchContent, bodyBoundary.reason);
				if (boundary.aborted) return;
				if ((bodyEnd.consumed || !inOrder) && (catchChunk.reorderBranch = branchId), bodyEnd.consumed) catchChunk.reorderId = reorderId, state.reorder(catchChunk);
				else {
					let reorder = null;
					inOrder ? streamed && (reorder = chunk.fork(boundary, null)) : reorder = catchChunk, reorder && (reorder.reorderId = reorderId);
					let endMarker = state.mark("!", reorderId), cut = body;
					for (; cut.consumed;) cut = cut.next;
					cut.async = !1, cut.next = inOrder ? catchChunk : bodyNext, cut.html = streamed ? endMarker : inOrder ? "" : state.mark("!^", reorderId) + endMarker, cut.scripts = cut.effects = cut.lastEffect = "", cut.placeholder = cut.reorderId = cut.catchRange = null, cut.deferredReorder = reorder, inOrder && (catchChunk.next = bodyNext);
				}
				boundary.endAsync();
			} else bodyBoundary.count ? boundary.onNext() : (renderersAtSettle && bodyBoundary.resumeWrites && bodyEnd.render(renderers), chunk.catchRange = null, boundary.endAsync());
		}
	}, renderersAtSettle;
}
function clearTryRenderers(branchId) {
	writeScope(branchId, {
		E: 0,
		Q: _scope_with_id(branchId).Q && 0
	});
}
function writeTryRenderers(branchId, catchContent, placeholderContent) {
	writeScope(branchId, {
		E: catchContent,
		Q: placeholderContent
	});
}
//#endregion
//#region src/html/compat.ts
function drainClassFunctions($global, writeScope) {
	let pending = pendingClassFunctions.get($global), scopeByHost = {};
	for (let [id, fn, hostId] of pending) register(id, fn, scopeByHost[hostId] ||= writeScope(hostId));
	pending.length = 0;
}
function swapReorders(state, reorders) {
	let { writeReorders } = state;
	return state.writeReorders = reorders, writeReorders;
}
function NOOP() {}
//#endregion
export { $global, _assert_class_toggles, _assert_hoist, _attr, _attr_and, _attr_class, _attr_content, _attr_details_or_dialog_open as _attr_details_open, _attr_details_or_dialog_open as _attr_dialog_open, _attr_input_checked, _attr_input_checkedValue, _attr_input_value, _attr_nonce, _attr_nullish, _attr_option_value, _attr_or, _attr_select_value, _attr_style, _attr_textarea_value, _attrs, _attrs_content, _attrs_partial, _attrs_partial_content, _attrs_select_value, _attrs_textarea_value, _await, _content, _content_resume, _dynamic_tag, _el, _el_read_error, _el_resume, _escape, _escape_comment, _escape_script, _escape_style, _escape_style_value, _existing_scope, _flush_head, _for_in, _for_of, _for_to, _for_until, _hoist, _hoist_read_error, _html, _html_resume, _id, _if, _peek_scope_id, _resume, _resume_branch, _resume_locals, writeScope as _scope, _scope_id, _scope_reason, _scope_with_id, _script, _set_scope_reason, _show_end, _show_start, _style_html, _subscribe, _template, _text_resume, _textarea_value, _to_text, _trailers, _try, _unescaped, _var, _write_guard, _write_if, attrTag, attrTags, compat, forIn, forOf, forTo, forUntil, withLoadAssets, withPageAssets };