UNPKG

@qwik.dev/core

Version:

An open source framework for building instant loading web apps at any scale, without the extra effort.

1,469 lines (1,245 loc) 289 kB
/** * @license * @qwik.dev/core 2.0.0-beta.13-dev+cb19ff7 * Copyright QwikDev. All Rights Reserved. * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://github.com/QwikDev/qwik/blob/main/LICENSE */ import { isDev, isServer, isBrowser } from "@qwik.dev/core/build"; export { isBrowser, isDev, isServer } from "@qwik.dev/core/build"; import { p } from "@qwik.dev/core/preloader"; const version = "2.0.0-beta.13-dev+cb19ff7"; const qDev = !1; const qInspector = !1; const qSerialize = !0; const qDynamicPlatform = !0; const qTest = !1; const qRuntimeQrl = !1; const seal = () => { qDev; }; const STYLE = ""; const logError = (message, ...optionalParams) => createAndLogError(!1, message, ...optionalParams); const throwErrorAndStop = (message, ...optionalParams) => { throw createAndLogError(!1, message, ...optionalParams); }; const logErrorAndStop = (message, ...optionalParams) => createAndLogError(qDev, message, ...optionalParams); const _printed = /*#__PURE__*/ new Set; const logOnceWarn = () => { qDev; }; const logWarn = () => { qDev; }; const createAndLogError = (asyncThrow, message, ...optionalParams) => { const err = message instanceof Error ? message : new Error(message); return console.error("%cQWIK ERROR", "", err.message, ...optionalParams, err.stack), asyncThrow && setTimeout(() => { throw err; }, 0), err; }; const isSerializableObject = v => { const proto = Object.getPrototypeOf(v); return proto === Object.prototype || proto === Array.prototype || null === proto; }; const isObject = v => "object" == typeof v && null !== v; const isArray = v => Array.isArray(v); const isString = v => "string" == typeof v; const isNumber$1 = v => "number" == typeof v; const isFunction = v => "function" == typeof v; const isPrimitive = v => "object" != typeof v && "function" != typeof v && null != v; const codeToText = code => `Code(Q${code}) https://github.com/QwikDev/qwik/blob/main/packages/qwik/src/core/error/error.ts#L${8 + code}`; const qError = (code, errorMessageArgs = []) => { const text = codeToText(code, ...errorMessageArgs); return logErrorAndStop(text, ...errorMessageArgs); }; const SYNC_QRL = "<sync>"; const isSyncQrl = value => isQrl(value) && "<sync>" == value.$symbol$; const isQrl = value => "function" == typeof value && "function" == typeof value.getSymbol; function assertQrl(qrl) { if (isDev && !isQrl(qrl)) { throw new Error("Not a QRL"); } } const getSymbolHash = symbolName => { const index = symbolName.lastIndexOf("_"); return index > -1 ? symbolName.slice(index + 1) : symbolName; }; const OnRenderProp = "q:renderFn"; const ComponentStylesPrefixContent = "⚡️"; const QSlot = "q:slot"; const QSlotParent = "q:sparent"; const QSlotS = "q:s"; const QStyle = "q:style"; const QStyleSelector = "style[q\\:style]"; const QStyleSSelector = "style[q\\:sstyle]"; const QStylesAllSelector = "style[q\\:style],style[q\\:sstyle]"; const QScopedStyle = "q:sstyle"; const QCtxAttr = "q:ctx"; const QBackRefs = "q:brefs"; const QFuncsPrefix = "qFuncs_"; const getQFuncs = (document, hash) => document["qFuncs_" + hash] || []; const QBaseAttr = "q:base"; const QLocaleAttr = "q:locale"; const QManifestHashAttr = "q:manifest-hash"; const QInstanceAttr = "q:instance"; const QContainerIsland = "q:container-island"; const QContainerIslandEnd = "/" + QContainerIsland; const QIgnore = "q:ignore"; const QIgnoreEnd = "/q:ignore"; const QContainerAttr = "q:container"; const QContainerAttrEnd = "/q:container"; const QTemplate = "q:template"; const QContainerSelector = "[q\\:container]:not([q\\:container=html]):not([q\\:container=text])"; const HTML_NS = "http://www.w3.org/1999/xhtml"; const SVG_NS = "http://www.w3.org/2000/svg"; const MATH_NS = "http://www.w3.org/1998/Math/MathML"; const XLINK_NS = "http://www.w3.org/1999/xlink"; const XML_NS = "http://www.w3.org/XML/1998/namespace"; const ResourceEvent = "qResource"; const RenderEvent = "qRender"; const TaskEvent = "qTask"; const QDefaultSlot = ""; const ELEMENT_ID = "q:id"; const ELEMENT_KEY = "q:key"; const ELEMENT_PROPS = "q:props"; const ELEMENT_SEQ = "q:seq"; const ELEMENT_SEQ_IDX = "q:seqIdx"; const Q_PREFIX = "q:"; const NON_SERIALIZABLE_MARKER_PREFIX = ":"; const USE_ON_LOCAL = ":on"; const USE_ON_LOCAL_SEQ_IDX = ":onIdx"; const USE_ON_LOCAL_FLAGS = ":onFlags"; const FLUSH_COMMENT = "qkssr-f"; const STREAM_BLOCK_START_COMMENT = "qkssr-pu"; const STREAM_BLOCK_END_COMMENT = "qkssr-po"; const Q_PROPS_SEPARATOR = ":"; const dangerouslySetInnerHTML = "dangerouslySetInnerHTML"; const qwikInspectorAttr = "data-qwik-inspector"; const createPlatform = () => ({ isServer, importSymbol(containerEl, url, symbolName) { if (isServer) { const hash = getSymbolHash(symbolName); const regSym = globalThis.__qwik_reg_symbols?.get(hash); if (regSym) { return regSym; } } if (!url) { throw qError(14, [ symbolName ]); } if (!containerEl) { throw qError(13, [ url, symbolName ]); } const urlDoc = toUrl(containerEl.ownerDocument, containerEl, url).toString(); const urlCopy = new URL(urlDoc); urlCopy.hash = ""; return import(urlCopy.href).then(mod => mod[symbolName]); }, raf: fn => new Promise(resolve => { requestAnimationFrame(() => { resolve(fn()); }); }), chunkForSymbol: (symbolName, chunk) => [ symbolName, chunk ?? "_" ] }); const toUrl = (doc, containerEl, url) => { const baseURI = doc.baseURI; const base = new URL(containerEl.getAttribute("q:base") ?? baseURI, baseURI); return new URL(url, base); }; let _platform = /*#__PURE__ */ createPlatform(); const setPlatform = plt => _platform = plt; const getPlatform = () => _platform; const isServerPlatform = () => _platform.isServer; const isNode = value => value && "number" == typeof value.nodeType; const isDocument = value => 9 === value.nodeType; const isElement$1 = value => 1 === value.nodeType; const MAX_RETRY_ON_PROMISE_COUNT = 100; const isPromise = value => !!value && "object" == typeof value && "function" == typeof value.then; const safeCall = (call, thenFn, rejectFn) => { try { const result = call(); return isPromise(result) ? result.then(thenFn, rejectFn) : thenFn(result); } catch (e) { return rejectFn(e); } }; const maybeThen = (valueOrPromise, thenFn) => isPromise(valueOrPromise) ? valueOrPromise.then(thenFn, shouldNotError) : thenFn(valueOrPromise); const shouldNotError = reason => { throwErrorAndStop(reason); }; const delay = timeout => new Promise(resolve => { setTimeout(resolve, timeout); }); function retryOnPromise(fn, retryCount = 0) { const retryOrThrow = e => { if (isPromise(e) && retryCount < 100) { return e.then(retryOnPromise.bind(null, fn, retryCount++)); } throw e; }; try { const result = fn(); return isPromise(result) ? result.catch(e => retryOrThrow(e)) : result; } catch (e) { if (isDev && isServer && e instanceof ReferenceError && e.message.includes("window")) { throw e.message = 'It seems like you forgot to add "if (isBrowser) {...}" here:' + e.message, e; } return retryOrThrow(e); } } const ASSERT_DISCLAIMER = "Internal assert, this is likely caused by a bug in Qwik: "; function assertDefined() { qDev; } function assertEqual() { qDev; } function assertTrue() { qDev; } function assertFalse() { qDev; } function assertNumber() { qDev; } let _locale; let localAsyncStore; function getLocale(defaultLocale) { if (localAsyncStore) { const locale = localAsyncStore.getStore(); if (locale) { return locale; } } if (void 0 === _locale) { const ctx = tryGetInvokeContext(); if (ctx && ctx.$locale$) { return ctx.$locale$; } if (void 0 !== defaultLocale) { return defaultLocale; } throw new Error("Reading `locale` outside of context."); } return _locale; } function withLocale(locale, fn) { if (localAsyncStore) { return localAsyncStore.run(locale, fn); } const previousLang = _locale; try { return _locale = locale, fn(); } finally { _locale = previousLang; } } function setLocale(locale) { localAsyncStore ? localAsyncStore.enterWith(locale) : _locale = locale; } isServer && import("node:async_hooks").then(module => { localAsyncStore = new module.AsyncLocalStorage; }).catch(() => {}); const DEBUG_TYPE = "q:type"; const VirtualTypeName = { V: "Virtual", F: "Fragment", S: "Signal", A: "Awaited", C: "Component", I: "InlineComponent", P: "Projection" }; const VNodeDataSeparator = { REFERENCE: 126, ADVANCE_1: 33, ADVANCE_8192: 46 }; const VNodeDataChar = { OPEN: 123, CLOSE: 125, SCOPED_STYLE: 59, RENDER_FN: 60, ID: 61, PROPS: 62, SLOT_PARENT: 63, KEY: 64, SEQ: 91, CONTEXT: 93, SEQ_IDX: 94, BACK_REFS: 96, SEPARATOR: 124, SLOT: 126 }; const mapApp_findIndx = (array, key, start) => { assertTrue(start % 2 == 0, "Expecting even number."); let bottom = start >> 1; let top = array.length - 2 >> 1; for (;bottom <= top; ) { const mid = bottom + (top - bottom >> 1); const midKey = array[mid << 1]; if (midKey === key) { return mid << 1; } midKey < key ? bottom = mid + 1 : top = mid - 1; } return ~(bottom << 1); }; const mapArray_set = (array, key, value, start, allowNullValue = !1) => { const indx = mapApp_findIndx(array, key, start); indx >= 0 ? null != value || allowNullValue ? array[indx + 1] = value : array.splice(indx, 2) : (null != value || allowNullValue) && array.splice(-1 ^ indx, 0, key, value); }; const mapArray_get = (array, key, start) => { const indx = mapApp_findIndx(array, key, start); return indx >= 0 ? array[indx + 1] : null; }; const mapArray_has = (array, key, start) => mapApp_findIndx(array, key, start) >= 0; const isForeignObjectElement = elementName => isDev ? "foreignobject" === elementName.toLowerCase() : "foreignObject" === elementName; const isSvgElement = elementName => "svg" === elementName || isForeignObjectElement(elementName); const isMathElement = elementName => "math" === elementName; const vnode_isDefaultNamespace = vnode => !(192 & vnode.flags); const vnode_getElementNamespaceFlags = element => { switch (fastNamespaceURI(element)) { case SVG_NS: return 64; case MATH_NS: return 128; default: return 0; } }; function vnode_getDomChildrenWithCorrectNamespacesToInsert(journal, domParentVNode, newChild) { const {elementNamespace, elementNamespaceFlag} = getNewElementNamespaceData(domParentVNode, newChild); let domChildren = []; if (elementNamespace === HTML_NS) { domChildren = vnode_getDOMChildNodes(journal, newChild); } else { const children = vnode_getDOMChildNodes(journal, newChild, !0); for (let i = 0; i < children.length; i++) { const childVNode = children[i]; if (vnode_isTextVNode(childVNode)) { domChildren.push(childVNode.textNode); continue; } if ((192 & childVNode.flags) == (192 & domParentVNode.flags)) { domChildren.push(childVNode.element); continue; } const newChildElement = vnode_cloneElementWithNamespace(childVNode, domParentVNode, elementNamespace, elementNamespaceFlag); newChildElement && domChildren.push(newChildElement); } } return domChildren; } function cloneDomTreeWithNamespace(element, elementName, namespace, deep = !1) { const newElement = element.ownerDocument.createElementNS(namespace, elementName); for (const attr of element.attributes) { ":" !== attr.name && newElement.setAttribute(attr.name, attr.value); } if (deep) { for (const child of element.childNodes) { const nodeType = child.nodeType; 3 === nodeType ? newElement.appendChild(child.cloneNode()) : 1 === nodeType && newElement.appendChild(cloneDomTreeWithNamespace(child, child.localName, namespace, deep)); } } return newElement; } function vnode_cloneElementWithNamespace(elementVNode, parentVNode, namespace, namespaceFlag) { ensureElementVNode(elementVNode); let vCursor = elementVNode; let vParent = null; let rootElement = null; let parentElement = null; for (;vCursor; ) { let childElement = null; let newChildElement = null; if (vnode_isElementVNode(vCursor)) { childElement = vCursor.element; const childElementTag = vnode_getElementName(vCursor); const vCursorParent = vCursor.parent; const vCursorDomParent = null == rootElement ? parentVNode : vCursorParent && vnode_getDomParentVNode(vCursorParent); if (vCursorDomParent) { const namespaceData = getNewElementNamespaceData(vCursorDomParent, vnode_getElementName(vCursor)); namespace = namespaceData.elementNamespace, namespaceFlag = namespaceData.elementNamespaceFlag; } const vFirstChild = vnode_getFirstChild(vCursor); if (newChildElement = cloneDomTreeWithNamespace(childElement, childElementTag, namespace, !vFirstChild), childElement.remove(), null == rootElement && (rootElement = newChildElement), parentElement && parentElement.appendChild(newChildElement), vCursor.element = newChildElement, vCursor.flags &= -193, vCursor.flags |= namespaceFlag, vFirstChild) { vCursor = vFirstChild, parentElement = newChildElement; continue; } if (shouldIgnoreChildren(childElement)) { const container = getDomContainerFromQContainerElement(childElement); if (container) { const innerContainerFirstVNode = vnode_getFirstChild(container.rootVNode); if (innerContainerFirstVNode) { vCursor = innerContainerFirstVNode, parentElement = newChildElement; continue; } } } } if (vCursor === elementVNode) { return rootElement; } const vNextSibling = vCursor.nextSibling; if (vNextSibling) { vCursor = vNextSibling; } else { for (vParent = vCursor.parent; vParent; ) { if (vParent === elementVNode) { return rootElement; } const vNextParentSibling = vParent.nextSibling; if (vNextParentSibling) { return vCursor = vNextParentSibling, rootElement; } vParent = vParent.parent; } if (null == vParent) { return rootElement; } } } return rootElement; } function isSvg(tagOrVNode) { return "string" == typeof tagOrVNode ? isSvgElement(tagOrVNode) : !!(64 & tagOrVNode.flags); } function isMath(tagOrVNode) { return "string" == typeof tagOrVNode ? isMathElement(tagOrVNode) : !!(128 & tagOrVNode.flags); } function getNewElementNamespaceData(domParentVNode, tagOrVNode) { const parentIsDefaultNamespace = !domParentVNode || !!vnode_getElementName(domParentVNode) && vnode_isDefaultNamespace(domParentVNode); const parentIsForeignObject = !parentIsDefaultNamespace && isForeignObjectElement(vnode_getElementName(domParentVNode)); let elementNamespace = HTML_NS; let elementNamespaceFlag = 0; const isElementVNodeOrString = "string" == typeof tagOrVNode || vnode_isElementVNode(tagOrVNode); if (isElementVNodeOrString && isSvg(tagOrVNode)) { elementNamespace = SVG_NS, elementNamespaceFlag = 64; } else if (isElementVNodeOrString && isMath(tagOrVNode)) { elementNamespace = MATH_NS, elementNamespaceFlag = 128; } else if (domParentVNode && !parentIsForeignObject && !parentIsDefaultNamespace) { elementNamespace = !!(64 & domParentVNode.flags) ? SVG_NS : !!(128 & domParentVNode.flags) ? MATH_NS : HTML_NS, elementNamespaceFlag = 192 & domParentVNode.flags; } return { elementNamespace, elementNamespaceFlag }; } function getAttributeNamespace(attributeName) { switch (attributeName) { case "xlink:href": case "xlink:actuate": case "xlink:arcrole": case "xlink:role": case "xlink:show": case "xlink:title": case "xlink:type": return XLINK_NS; case "xml:base": case "xml:lang": case "xml:space": return XML_NS; default: return null; } } const mergeMaps = (map1, map2) => { for (const [k, v] of map2) { map1.set(k, v); } return map1; }; const NEEDS_COMPUTATION = Symbol("invalid"); const _EFFECT_BACK_REF = Symbol("backRef"); const STORE_TARGET = Symbol("store.target"); const STORE_HANDLER = Symbol("store.handler"); const STORE_ALL_PROPS = Symbol("store.all"); class SignalImpl { $untrackedValue$; $effects$=null; $container$=null; $wrappedSignal$=null; constructor(container, value) { this.$container$ = container, this.$untrackedValue$ = value; } force() { this.$container$?.$scheduler$(7, null, this, this.$effects$); } get untrackedValue() { return this.$untrackedValue$; } set untrackedValue(value) { this.$untrackedValue$ = value; } get value() { return setupSignalValueAccess(this, () => this.$effects$ ||= new Set, () => this.untrackedValue); } set value(value) { value !== this.$untrackedValue$ && (this.$untrackedValue$ = value, this.$container$?.$scheduler$(7, null, this, this.$effects$)); } valueOf() { qDev; } toString() { return isDev ? `[${this.constructor.name}${1 & this.$flags$ ? " INVALID" : ""} ${String(this.$untrackedValue$)}]` + (Array.from(this.$effects$ || []).map(e => "\n -> " + pad(qwikDebugToString(e[0]), " ")).join("\n") || "") : this.constructor.name; } toJSON() { return { value: this.$untrackedValue$ }; } } const addEffect = (signal, effectSubscriber, effects) => { ensureContainsSubscription(effects, effectSubscriber), ensureContainsBackRef(effectSubscriber, signal), addQrlToSerializationCtx(effectSubscriber, signal.$container$); }; const setupSignalValueAccess = (target, effectsFn, returnValueFn) => { const ctx = tryGetInvokeContext(); if (ctx) { if (null === target.$container$) { if (!ctx.$container$) { return returnValueFn(); } target.$container$ = ctx.$container$; } else { assertTrue(!ctx.$container$ || ctx.$container$ === target.$container$, "Do not use signals across containers"); } const effectSubscriber = ctx.$effectSubscriber$; effectSubscriber && addEffect(target, effectSubscriber, effectsFn()); } return returnValueFn(); }; const _CONST_PROPS = Symbol("CONST"); const _VAR_PROPS = Symbol("VAR"); const _OWNER = Symbol("OWNER"); const _IMMUTABLE = Symbol("IMMUTABLE"); const _UNINITIALIZED = Symbol("UNINITIALIZED"); const EVENT_SUFFIX = "$"; const isHtmlAttributeAnEventName = name => name.startsWith("on:") || name.startsWith("on-window:") || name.startsWith("on-document:"); function jsxEventToHtmlAttribute(jsxEvent) { if (jsxEvent.endsWith("$")) { const [prefix, idx] = getEventScopeDataFromJsxEvent(jsxEvent); if (-1 !== idx) { const name = jsxEvent.slice(idx, -1); return "DOMContentLoaded" === name ? prefix + "-d-o-m-content-loaded" : createEventName("-" === name.charAt(0) ? name.slice(1) : name.toLowerCase(), prefix); } } return null; } function createEventName(event, prefix) { return prefix + fromCamelToKebabCase(event); } function getEventScopeDataFromJsxEvent(eventName) { let prefix = "on:"; let idx = -1; return eventName.startsWith("on") ? (prefix = "on:", idx = 2) : eventName.startsWith("window:on") ? (prefix = "on-window:", idx = 9) : eventName.startsWith("document:on") && (prefix = "on-document:", idx = 11), [ prefix, idx ]; } function isPreventDefault(key) { return key.startsWith("preventdefault:"); } const fromCamelToKebabCase = text => text.replace(/([A-Z-])/g, a => "-" + a.toLowerCase()); const getEventDataFromHtmlAttribute = htmlKey => htmlKey.startsWith("on:") ? [ "", htmlKey.substring(3) ] : htmlKey.startsWith("on-window:") ? [ "window", htmlKey.substring(10) ] : [ "document", htmlKey.substring(12) ]; const EMPTY_ARRAY = []; const EMPTY_OBJ = {}; function createPropsProxy(owner) { return new Proxy({}, new PropsProxyHandler(owner)); } Object.freeze(EMPTY_ARRAY), Object.freeze(EMPTY_OBJ); class PropsProxyHandler { owner; constructor(owner) { this.owner = owner; } get(_, prop) { if (prop === _CONST_PROPS) { return this.owner.constProps; } if (prop === _VAR_PROPS) { return this.owner.varProps; } if (prop === _OWNER) { return this.owner; } let value; if ("children" === prop) { value = this.owner.children; } else { if ("string" == typeof prop && "string" == typeof this.owner.type) { const attr = jsxEventToHtmlAttribute(prop); attr && (prop = attr); } value = directGetPropsProxyProp(this.owner, prop); } return value instanceof WrappedSignalImpl && 4 & value.$flags$ ? value.value : value; } set(_, prop, value) { if (prop === _OWNER) { this.owner = value; } else if ("children" === prop) { this.owner.children = value; } else { if ("string" == typeof prop && "string" == typeof this.owner.type) { const attr = jsxEventToHtmlAttribute(prop); attr && (prop = attr); } this.owner.constProps && prop in this.owner.constProps ? (this.owner.constProps[prop] = void 0, prop in this.owner.varProps || (this.owner.toSort = !0), this.owner.varProps[prop] = value) : (this.owner.varProps === EMPTY_OBJ ? this.owner.varProps = {} : prop in this.owner.varProps || (this.owner.toSort = !0), this.owner.varProps[prop] = value); } return !0; } deleteProperty(_, prop) { let didDelete = delete this.owner.varProps[prop]; return this.owner.constProps && (didDelete = delete this.owner.constProps[prop] || didDelete), null != this.owner.children && "children" === prop && (this.owner.children = null, didDelete = !0), didDelete; } has(_, prop) { if ("children" === prop) { return null != this.owner.children; } if (prop === _CONST_PROPS || prop === _VAR_PROPS) { return !0; } if ("string" == typeof prop && "string" == typeof this.owner.type) { const attr = jsxEventToHtmlAttribute(prop); attr && (prop = attr); } return prop in this.owner.varProps || !!this.owner.constProps && prop in this.owner.constProps; } getOwnPropertyDescriptor(_, p) { return { configurable: !0, enumerable: !0, value: "children" === p ? this.owner.children : this.owner.constProps && p in this.owner.constProps ? this.owner.constProps[p] : this.owner.varProps[p] }; } ownKeys() { const out = Object.keys(this.owner.varProps); if (null != this.owner.children && out.push("children"), this.owner.constProps) { for (const key in this.owner.constProps) { -1 === out.indexOf(key) && out.push(key); } } return out; } } const directGetPropsProxyProp = (jsx, prop) => jsx.constProps && prop in jsx.constProps ? jsx.constProps[prop] : jsx.varProps[prop]; const _getVarProps = props => props ? _VAR_PROPS in props ? "children" in props ? { ...props[_VAR_PROPS], children: props.children } : props[_VAR_PROPS] : props : null; const _getConstProps = props => props && _CONST_PROPS in props ? props[_CONST_PROPS] : null; const isPropsProxy = obj => obj && _VAR_PROPS in obj; function getSubscriber(effect, prop, data) { effect[_EFFECT_BACK_REF] || (isServer && isSsrNode(effect) ? effect.setProp("q:brefs", new Map) : effect[_EFFECT_BACK_REF] = new Map); const subMap = effect[_EFFECT_BACK_REF]; let sub = subMap.get(prop); return sub || (sub = [ effect, prop ], subMap.set(prop, sub)), data && (sub[3] = data), sub; } function isSsrNode(value) { return "__brand__" in value && "SsrNode" === value.__brand__; } const trackFn = (target, container) => (obj, prop) => { const ctx = newInvokeContext(); return ctx.$effectSubscriber$ = getSubscriber(target, ":"), ctx.$container$ = container || void 0, invoke(ctx, () => { if (isFunction(obj)) { return obj(); } if (prop) { return obj[prop]; } if (isSignal(obj)) { return obj.value; } if (isObject(obj) && isStore(obj)) { return addStoreEffect(getStoreTarget(obj), STORE_ALL_PROPS, getStoreHandler(obj), ctx.$effectSubscriber$), obj; } throw qError(2); }); }; const cleanupFn = (target, handleError) => { let cleanupFns = null; return [ fn => { "function" == typeof fn && (cleanupFns || (cleanupFns = [], target.$destroy$ = noSerialize(() => { target.$destroy$ = null, cleanupFns.forEach(fn => { try { fn(); } catch (err) { handleError(err); } }); })), cleanupFns.push(fn)); }, cleanupFns ?? [] ]; }; const DEBUG$1 = !1; const log = (...args) => console.log("COMPUTED SIGNAL", ...args.map(qwikDebugToString)); class ComputedSignalImpl extends SignalImpl { $computeQrl$; $flags$; [_EFFECT_BACK_REF]=null; constructor(container, fn, flags = 33) { super(container, NEEDS_COMPUTATION), this.$computeQrl$ = fn, this.$flags$ = flags; } invalidate() { this.$flags$ |= 1, this.$container$?.$scheduler$(7, null, this, this.$effects$); } force() { this.$flags$ |= 2, super.force(); } get untrackedValue() { return this.$computeIfNeeded$(), assertFalse(this.$untrackedValue$ === NEEDS_COMPUTATION, "Invalid state"), this.$untrackedValue$; } $computeIfNeeded$() { if (!(1 & this.$flags$)) { return; } const computeQrl = this.$computeQrl$; throwIfQRLNotResolved(computeQrl); const ctx = tryGetInvokeContext(); const previousEffectSubscription = ctx?.$effectSubscriber$; ctx && (ctx.$effectSubscriber$ = getSubscriber(this, ".")); try { const untrackedValue = computeQrl.getFn(ctx)(); if (isPromise(untrackedValue)) { throw qError(29, [ computeQrl.dev ? computeQrl.dev.file : "", computeQrl.$hash$ ]); } this.$flags$ &= -2; untrackedValue !== this.$untrackedValue$ && (this.$untrackedValue$ !== NEEDS_COMPUTATION && (this.$flags$ |= 2), this.$untrackedValue$ = untrackedValue); } finally { ctx && (ctx.$effectSubscriber$ = previousEffectSubscription); } } set value(_) { throw qError(30); } get value() { return super.value; } } class AsyncComputedSignalImpl extends ComputedSignalImpl { $untrackedLoading$=!1; $untrackedError$=null; $loadingEffects$=null; $errorEffects$=null; $destroy$; $promiseValue$=NEEDS_COMPUTATION; [_EFFECT_BACK_REF]=null; constructor(container, fn, flags = 1) { super(container, fn, flags); } get loading() { return setupSignalValueAccess(this, () => this.$loadingEffects$ ||= new Set, () => this.untrackedLoading); } set untrackedLoading(value) { value !== this.$untrackedLoading$ && (this.$untrackedLoading$ = value, this.$container$?.$scheduler$(7, null, this, this.$loadingEffects$)); } get untrackedLoading() { return this.$untrackedLoading$; } get error() { return setupSignalValueAccess(this, () => this.$errorEffects$ ||= new Set, () => this.untrackedError); } set untrackedError(value) { value !== this.$untrackedError$ && (this.$untrackedError$ = value, this.$container$?.$scheduler$(7, null, this, this.$errorEffects$)); } get untrackedError() { return this.$untrackedError$; } invalidate() { super.invalidate(), this.$promiseValue$ = NEEDS_COMPUTATION; } async resolve() { return await retryOnPromise(() => this.$computeIfNeeded$()), this.$untrackedValue$; } $computeIfNeeded$() { if (!(1 & this.$flags$)) { return; } const [cleanup] = cleanupFn(this, err => this.$container$?.handleError(err, null)); const untrackedValue = this.$promiseValue$ === NEEDS_COMPUTATION ? this.$computeQrl$.getFn()({ track: trackFn(this, this.$container$), cleanup }) : this.$promiseValue$; if (isPromise(untrackedValue)) { throw this.untrackedLoading = !0, this.untrackedError = null, untrackedValue.then(promiseValue => { this.$promiseValue$ = promiseValue, this.untrackedLoading = !1, this.untrackedError = null; }).catch(err => { this.$promiseValue$ = err, this.untrackedLoading = !1, this.untrackedError = err; }); } this.$promiseValue$ = NEEDS_COMPUTATION, this.$flags$ &= -2; const didChange = untrackedValue !== this.$untrackedValue$; return didChange && (this.$flags$ |= 2, this.$untrackedValue$ = untrackedValue), didChange; } } const implicit$FirstArg = fn => function(first, ...rest) { return fn.call(null, dollar(first), ...rest); }; class SerializerSignalImpl extends ComputedSignalImpl { constructor(container, argQrl) { super(container, argQrl, 33); } $didInitialize$=!1; $computeIfNeeded$() { if (!(1 & this.$flags$)) { return; } throwIfQRLNotResolved(this.$computeQrl$); let arg = this.$computeQrl$.resolved; "function" == typeof arg && (arg = arg()); const {deserialize, initial} = arg; const update = arg.update; const currentValue = this.$untrackedValue$ === NEEDS_COMPUTATION ? initial : this.$untrackedValue$; const untrackedValue = trackSignal(() => this.$didInitialize$ ? update?.(currentValue) || currentValue : deserialize(currentValue), this, ".", this.$container$); const didChange = this.$didInitialize$ && "undefined" !== untrackedValue || untrackedValue !== this.$untrackedValue$; this.$flags$ &= -2, this.$didInitialize$ = !0, didChange && (this.$flags$ |= 2, this.$untrackedValue$ = untrackedValue); } } const createSignal$1 = value => new SignalImpl(null, value); const createComputedSignal = (qrl, options) => new ComputedSignalImpl(options?.container || null, qrl, getComputedSignalFlags(options?.serializationStrategy || "always")); const createAsyncComputedSignal = (qrl, options) => new AsyncComputedSignalImpl(options?.container || null, qrl, getComputedSignalFlags(options?.serializationStrategy || "never")); const createSerializerSignal = arg => new SerializerSignalImpl(null, arg); const createSignal = createSignal$1; const createComputed$ = /*#__PURE__*/ implicit$FirstArg(createComputedSignal); const createAsyncComputed$ = /*#__PURE__*/ implicit$FirstArg(createAsyncComputedSignal); const createSerializer$ = implicit$FirstArg(createSerializerSignal); const getValueProp = p0 => p0.value; const getProp = (p0, p1) => p0[p1]; const getWrapped = args => 1 === args.length ? isSignal(args[0]) ? args[0].$wrappedSignal$ ||= new WrappedSignalImpl(null, getValueProp, args, null) : isStore(args[0]) ? new WrappedSignalImpl(null, getValueProp, args, null) : args[0].value : new WrappedSignalImpl(null, getProp, args, null); const _wrapProp = (...args) => { const obj = args[0]; const prop = args.length < 2 ? "value" : args[1]; if (!isObject(obj)) { return obj[prop]; } if (isSignal(obj)) { return obj instanceof AsyncComputedSignalImpl || assertEqual(prop, "value", "Left side is a signal, prop must be value"), obj instanceof WrappedSignalImpl && 4 & obj.$flags$ ? obj : getWrapped(args); } if (isPropsProxy(obj)) { const constProps = obj[_CONST_PROPS]; if (constProps && prop in constProps) { return constProps[prop]; } } else { const target = getStoreTarget(obj); if (target) { const value = target[prop]; return isSignal(value) ? value : getWrapped(args); } } return obj[prop]; }; const _wrapSignal = (obj, prop) => { const r = _wrapProp(obj, prop); return r === _IMMUTABLE ? obj[prop] : r; }; class WrappedSignalImpl extends SignalImpl { $args$; $func$; $funcStr$; $flags$; $hostElement$=null; [_EFFECT_BACK_REF]=null; constructor(container, fn, args, fnStr, flags = 5) { super(container, NEEDS_COMPUTATION), this.$args$ = args, this.$func$ = fn, this.$funcStr$ = fnStr, this.$flags$ = flags; } invalidate() { this.$flags$ |= 1; try { this.$computeIfNeeded$(); } catch (_) { this.$container$?.$scheduler$(7, this.$hostElement$, this, this.$effects$); } 2 & this.$flags$ && (this.$flags$ &= -3, scheduleEffects(this.$container$, this, this.$effects$)); } force() { this.$flags$ |= 2, this.$container$?.$scheduler$(7, this.$hostElement$, this, this.$effects$); } get untrackedValue() { return this.$computeIfNeeded$(), assertFalse(this.$untrackedValue$ === NEEDS_COMPUTATION, "Invalid state"), this.$untrackedValue$; } $computeIfNeeded$() { if (!(1 & this.$flags$)) { return; } const untrackedValue = trackSignal(() => this.$func$(...this.$args$), this, ".", this.$container$); this.$flags$ &= -3; untrackedValue !== this.$untrackedValue$ && (this.$flags$ |= 2, this.$untrackedValue$ = untrackedValue); } $unwrapIfSignal$() { return this.$func$ === getValueProp && isSignal(this.$args$[0]) ? this.$args$[0] : this; } set value(_) { throw qError(31); } get value() { return super.value; } } let BackRef$1 = class { [_EFFECT_BACK_REF]=null; }; function clearAllEffects(container, consumer) { vnode_isVNode(consumer) && vnode_isElementVNode(consumer) && ensureMaterialized(consumer); const effects = consumer[_EFFECT_BACK_REF]; if (effects) { for (const [, effect] of effects) { clearEffectSubscription(container, effect); } } } function clearEffectSubscription(container, effect) { const backRefs = effect[2]; if (backRefs) { for (const producer of backRefs) { if (producer instanceof SignalImpl) { clearSignal(container, producer, effect); } else if (producer instanceof AsyncComputedSignalImpl) { clearAsyncComputedSignal(producer, effect); } else if (container.$storeProxyMap$.has(producer)) { const target = container.$storeProxyMap$.get(producer); clearStore(getStoreHandler(target), effect); } } } } function clearSignal(container, producer, effect) { const effects = producer.$effects$; effects && effects.has(effect) && effects.delete(effect), producer instanceof WrappedSignalImpl && (producer.$hostElement$ = null, clearAllEffects(container, producer)); } function clearAsyncComputedSignal(producer, effect) { const effects = producer.$effects$; effects && effects.has(effect) && effects.delete(effect); const pendingEffects = producer.$loadingEffects$; pendingEffects && pendingEffects.has(effect) && pendingEffects.delete(effect); } function clearStore(producer, effect) { const effects = producer?.$effects$; if (effects) { for (const propEffects of effects.values()) { propEffects.has(effect) && propEffects.delete(effect); } } } class VNode extends BackRef$1 { flags; parent; previousSibling; nextSibling; props=null; slotParent=null; chores=null; blockedChores=null; constructor(flags, parent, previousSibling, nextSibling) { super(), this.flags = flags, this.parent = parent, this.previousSibling = previousSibling, this.nextSibling = nextSibling; } getProp(key, getObject) { const type = this.flags; if (3 & type) { 1 & type && vnode_ensureElementInflated(this), this.props ||= []; const idx = mapApp_findIndx(this.props, key, 0); if (idx >= 0) { let value = this.props[idx + 1]; return "string" == typeof value && getObject && (this.props[idx + 1] = value = getObject(value)), value; } } return null; } setProp(key, value) { this.props ||= []; const idx = mapApp_findIndx(this.props, key, 0); idx >= 0 ? this.props[idx + 1] = value : null != value && this.props.splice(-1 ^ idx, 0, key, value); } getAttr(key) { return 3 & this.flags ? (vnode_ensureElementInflated(this), this.props ||= [], mapArray_get(this.props, key, 0)) : null; } setAttr(key, value, journal) { if (3 & this.flags) { vnode_ensureElementInflated(this), this.props ||= []; const idx = mapApp_findIndx(this.props, key, 0); idx >= 0 ? (this.props[idx + 1] != value && this instanceof ElementVNode && journal && journal.push(2, this.element, key, value), null == value ? this.props.splice(idx, 2) : this.props[idx + 1] = value) : null != value && (this.props.splice(-1 ^ idx, 0, key, value), this instanceof ElementVNode && journal && journal.push(2, this.element, key, value)); } } toString() { return isDev ? vnode_toString.call(this) : String(this); } } class TextVNode extends VNode { textNode; text; constructor(flags, parent, previousSibling, nextSibling, textNode, text) { super(flags, parent, previousSibling, nextSibling), this.textNode = textNode, this.text = text; } } class VirtualVNode extends VNode { firstChild; lastChild; constructor(flags, parent, previousSibling, nextSibling, firstChild, lastChild) { super(flags, parent, previousSibling, nextSibling), this.firstChild = firstChild, this.lastChild = lastChild; } } class ElementVNode extends VNode { firstChild; lastChild; element; elementName; constructor(flags, parent, previousSibling, nextSibling, firstChild, lastChild, element, elementName) { super(flags, parent, previousSibling, nextSibling), this.firstChild = firstChild, this.lastChild = lastChild, this.element = element, this.elementName = elementName; } } const vnode_newElement = (element, elementName) => { assertEqual(fastNodeType(element), 1, "Expecting element node."); const vnode = new ElementVNode(-247, null, null, null, null, null, element, elementName); return assertTrue(vnode_isElementVNode(vnode), "Incorrect format of ElementVNode."), assertFalse(vnode_isTextVNode(vnode), "Incorrect format of ElementVNode."), assertFalse(vnode_isVirtualVNode(vnode), "Incorrect format of ElementVNode."), element.vNode = vnode, vnode; }; const vnode_newUnMaterializedElement = element => { assertEqual(fastNodeType(element), 1, "Expecting element node."); const vnode = new ElementVNode(-255, null, null, null, void 0, void 0, element, void 0); return assertTrue(vnode_isElementVNode(vnode), "Incorrect format of ElementVNode."), assertFalse(vnode_isTextVNode(vnode), "Incorrect format of ElementVNode."), assertFalse(vnode_isVirtualVNode(vnode), "Incorrect format of ElementVNode."), element.vNode = vnode, vnode; }; const vnode_newSharedText = (previousTextNode, sharedTextNode, textContent) => { sharedTextNode && assertEqual(fastNodeType(sharedTextNode), 3, "Expecting element node."); const vnode = new TextVNode(-252, null, previousTextNode, null, sharedTextNode, textContent); return assertFalse(vnode_isElementVNode(vnode), "Incorrect format of TextVNode."), assertTrue(vnode_isTextVNode(vnode), "Incorrect format of TextVNode."), assertFalse(vnode_isVirtualVNode(vnode), "Incorrect format of TextVNode."), vnode; }; const vnode_newText = (textNode, textContent) => { const vnode = new TextVNode(-244, null, null, null, textNode, textContent); return assertEqual(fastNodeType(textNode), 3, "Expecting element node."), assertFalse(vnode_isElementVNode(vnode), "Incorrect format of TextVNode."), assertTrue(vnode_isTextVNode(vnode), "Incorrect format of TextVNode."), assertFalse(vnode_isVirtualVNode(vnode), "Incorrect format of TextVNode."), vnode; }; const vnode_newVirtual = () => { const vnode = new VirtualVNode(-254, null, null, null, null, null); return assertFalse(vnode_isElementVNode(vnode), "Incorrect format of TextVNode."), assertFalse(vnode_isTextVNode(vnode), "Incorrect format of TextVNode."), assertTrue(vnode_isVirtualVNode(vnode), "Incorrect format of TextVNode."), vnode; }; const vnode_isVNode = vNode => vNode instanceof VNode; const vnode_isElementVNode = vNode => { assertDefined(vNode, "Missing vNode"); return !(1 & ~vNode.flags); }; const vnode_isElementOrTextVNode = vNode => { assertDefined(vNode, "Missing vNode"); return !!(5 & vNode.flags); }; const vnode_isMaterialized = vNode => { assertDefined(vNode, "Missing vNode"); return !(1 & ~vNode.flags) && void 0 !== vNode.firstChild && void 0 !== vNode.lastChild; }; const vnode_isTextVNode = vNode => { assertDefined(vNode, "Missing vNode"); return !(4 & ~vNode.flags); }; const vnode_isVirtualVNode = vNode => { assertDefined(vNode, "Missing vNode"); return !(2 & ~vNode.flags); }; const vnode_isProjection = vNode => { assertDefined(vNode, "Missing vNode"); return !(2 & ~vNode.flags) && null !== vNode.getProp(QSlot, null); }; const ensureTextVNode = vNode => (assertTrue(vnode_isTextVNode(vNode), "Expecting TextVNode was: " + vnode_getNodeTypeName(vNode)), vNode); const ensureElementOrVirtualVNode = vNode => { assertDefined(vNode, "Missing vNode"), assertTrue(!!(3 & vNode.flags), "Expecting ElementVNode or VirtualVNode was: " + vnode_getNodeTypeName(vNode)); }; const ensureElementVNode = vNode => (assertTrue(vnode_isElementVNode(vNode), "Expecting ElementVNode was: " + vnode_getNodeTypeName(vNode)), vNode); const vnode_getNodeTypeName = vNode => { if (vNode) { switch (7 & vNode.flags) { case 1: return "Element"; case 2: return "Virtual"; case 4: return "Text"; } } return "<unknown>"; }; const vnode_ensureElementInflated = vnode => { if (1 == (15 & vnode.flags)) { const elementVNode = vnode; elementVNode.flags ^= 8; const element = elementVNode.element; const attributes = element.attributes; for (let idx = 0; idx < attributes.length; idx++) { const attr = attributes[idx]; const key = attr.name; if (":" === key || !key) { break; } if (key.startsWith("q:container")) { const props = vnode_getProps(elementVNode); "html" === attr.value ? mapArray_set(props, dangerouslySetInnerHTML, element.innerHTML, 0) : "text" === attr.value && "value" in element && mapArray_set(props, "value", element.value, 0); } else if (!key.startsWith("on:")) { const value = attr.value; const props = vnode_getProps(elementVNode); mapArray_set(props, key, value, 0); } } } }; function vnode_walkVNode(vNode, callback) { let vCursor = vNode; if (vnode_isTextVNode(vNode)) { return; } let vParent = null; for (;;) { if (callback?.(vCursor, vParent)) { return; } const vFirstChild = vnode_getFirstChild(vCursor); if (vFirstChild) { vCursor = vFirstChild; continue; } if (vCursor === vNode) { return; } const vNextSibling = vCursor.nextSibling; if (vNextSibling) { vCursor = vNextSibling; } else { for (vParent = vCursor.parent; vParent; ) { if (vParent === vNode) { return; } const vNextParentSibling = vParent.nextSibling; if (vNextParentSibling) { vCursor = vNextParentSibling; break; } vParent = vParent.parent; } if (null == vParent) { return; } } } } function vnode_getDOMChildNodes(journal, root, isVNode = !1, childNodes = []) { if (vnode_isElementOrTextVNode(root)) { return vnode_isTextVNode(root) && vnode_ensureTextInflated(journal, root), childNodes.push(isVNode ? root : vnode_getNode(root)), childNodes; } let vNode = vnode_getFirstChild(root); for (;vNode; ) { vnode_isElementVNode(vNode) ? childNodes.push(isVNode ? vNode : vnode_getNode(vNode)) : vnode_isTextVNode(vNode) ? (vnode_ensureTextInflated(journal, vNode), childNodes.push(isVNode ? vNode : vnode_getNode(vNode))) : vnode_getDOMChildNodes(journal, vNode, !!isVNode, childNodes), vNode = vNode.nextSibling; } return childNodes; } const vnode_getDomSibling = (vNode, nextDirection, descend) => { const childProp = nextDirection ? "firstChild" : "lastChild"; const siblingProp = nextDirection ? "nextSibling" : "previousSibling"; let cursor = vNode; for (;descend && cursor && vnode_isVirtualVNode(cursor); ) { const child = cursor[childProp]; if (!child) { break; } if (5 & child.flags) { return child; } cursor = child; } for (;cursor; ) { let sibling = cursor[siblingProp]; if (sibling && 5 & sibling.flags) { return sibling; } if (!sibling) { let virtual = cursor.parent; if (virtual && !vnode_isVirtualVNode(virtual)) { return null; } for (;virtual && !(sibling = virtual[siblingProp]); ) { if (virtual = virtual.parent, virtual && !vnode_isVirtualVNode(virtual)) { return null; } } if (!sibling) { return null; } if (vnode_isTextVNode(sibling) && virtual && vnode_isElementVNode(virtual)) { return null; } } for (;sibling; ) { if (cursor = sibling, 5 & cursor.flags && vnode_getNode(cursor)) { return cursor; } sibling = cursor[childProp]; } } return null; }; const vnode_ensureInflatedIfText = (journal, vNode) => { vnode_isTextVNode(vNode) && vnode_ensureTextInflated(journal, vNode); }; const vnode_ensureTextInflated = (journal, vnode) => { const textVNode = ensureTextVNode(vnode); if (!(8 & textVNode.flags)) { const parentNode = vnode_getDomParent(vnode); assertDefined(parentNode, "Missing parent node."); const sharedTextNode = textVNode.textNode; const doc = parentNode.ownerDocument; let cursor = vnode_getDomSibling(vnode, !1, !0); const node = vnode_getDomSibling(vnode, !0, !0); const insertBeforeNode = sharedTextNode || (node instanceof ElementVNode ? node.element : node?.textNode) || null; let lastPreviousTextNode = insertBeforeNode; for (;cursor && vnode_isTextVNode(cursor); ) { if (!(8 & cursor.flags)) { const textNode = doc.createTextNode(cursor.text); journal.push(6, parentNode, lastPreviousTextNode, textNode), lastPreviousTextNode = textNode, cursor.textNode = textNode, cursor.flags |= 8; } cursor = vnode_getDomSibling(cursor, !1, !0); } for (cursor = vnode; cursor && vnode_isTextVNode(cursor); ) { const next = vnode_getDomSibling(cursor, !0, !0); const isLastNode = !next || !vnode_isTextVNode(next); if (!(8 & cursor.flags)) { if (isLastNode && sharedTextNode) { journal.push(1, sharedText