UNPKG

@builder.io/qwik

Version:

An Open-Source sub-framework designed with a focus on server-side-rendering, lazy-loading, and styling/animation.

1,532 lines (1,504 loc) 336 kB
/** * @license * @builder.io/qwik 1.16.0 * Copyright Builder.io, Inc. 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 { isServer, isBrowser, isDev } from '@builder.io/qwik/build'; export { isBrowser, isDev, isServer } from '@builder.io/qwik/build'; import { p } from '@builder.io/qwik/preloader'; // <docs markdown="../readme.md#implicit$FirstArg"> // !!DO NOT EDIT THIS COMMENT DIRECTLY!!! // (edit ../readme.md#implicit$FirstArg instead) /** * Create a `____$(...)` convenience method from `___(...)`. * * It is very common for functions to take a lazy-loadable resource as a first argument. For this * reason, the Qwik Optimizer automatically extracts the first argument from any function which ends * in `$`. * * This means that `foo$(arg0)` and `foo($(arg0))` are equivalent with respect to Qwik Optimizer. * The former is just a shorthand for the latter. * * For example, these function calls are equivalent: * * - `component$(() => {...})` is same as `component($(() => {...}))` * * ```tsx * export function myApi(callback: QRL<() => void>): void { * // ... * } * * export const myApi$ = implicit$FirstArg(myApi); * // type of myApi$: (callback: () => void): void * * // can be used as: * myApi$(() => console.log('callback')); * * // will be transpiled to: * // FILE: <current file> * myApi(qrl('./chunk-abc.js', 'callback')); * * // FILE: chunk-abc.js * export const callback = () => console.log('callback'); * ``` * * @param fn - A function that should have its first argument automatically `$`. * @public */ // </docs> const implicit$FirstArg = (fn) => { return function (first, ...rest) { return fn.call(null, $(first), ...rest); }; }; const qDev = globalThis.qDev !== false; const qInspector = globalThis.qInspector === true; const qSerialize = globalThis.qSerialize !== false; const qDynamicPlatform = globalThis.qDynamicPlatform !== false; const qTest = globalThis.qTest === true; const qRuntimeQrl = globalThis.qRuntimeQrl === true; const seal = (obj) => { if (qDev) { Object.seal(obj); } }; const isNode$1 = (value) => { return value && typeof value.nodeType === 'number'; }; const isDocument = (value) => { return value.nodeType === 9; }; const isElement$1 = (value) => { return value.nodeType === 1; }; const isQwikElement = (value) => { const nodeType = value.nodeType; return nodeType === 1 || nodeType === 111; }; const isNodeElement = (value) => { const nodeType = value.nodeType; return nodeType === 1 || nodeType === 111 || nodeType === 3; }; const isVirtualElement = (value) => { return value.nodeType === 111; }; const isText = (value) => { return value.nodeType === 3; }; const isComment = (value) => { return value.nodeType === 8; }; const STYLE = qDev ? `background: #564CE0; color: white; padding: 2px 3px; border-radius: 2px; font-size: 0.8em;` : ''; const logError = (message, ...optionalParams) => { return createAndLogError(false, message, ...optionalParams); }; const throwErrorAndStop = (message, ...optionalParams) => { const error = createAndLogError(false, message, ...optionalParams); // eslint-disable-next-line no-debugger debugger; throw error; }; const logErrorAndStop = (message, ...optionalParams) => { const err = createAndLogError(qDev, message, ...optionalParams); // eslint-disable-next-line no-debugger debugger; return err; }; const _printed = /*#__PURE__*/ new Set(); const logOnceWarn = (message, ...optionalParams) => { if (qDev) { const key = 'warn' + String(message); if (!_printed.has(key)) { _printed.add(key); logWarn(message, ...optionalParams); } } }; const logWarn = (message, ...optionalParams) => { if (qDev) { console.warn('%cQWIK WARN', STYLE, message, ...printParams(optionalParams)); } }; const logDebug = (message, ...optionalParams) => { if (qDev) { // eslint-disable-next-line no-console console.debug('%cQWIK', STYLE, message, ...printParams(optionalParams)); } }; const tryGetContext$1 = (element) => { return element['_qc_']; }; const printParams = (optionalParams) => { if (qDev) { return optionalParams.map((p) => { if (isNode$1(p) && isElement$1(p)) { return printElement(p); } return p; }); } return optionalParams; }; const printElement = (el) => { const ctx = tryGetContext$1(el); const isServer = /*#__PURE__*/ (() => typeof process !== 'undefined' && !!process.versions && !!process.versions.node)(); return { tagName: el.tagName, renderQRL: ctx?.$componentQrl$?.getSymbol(), element: isServer ? undefined : el, ctx: isServer ? undefined : ctx, }; }; const createAndLogError = (asyncThrow, message, ...optionalParams) => { const err = message instanceof Error ? message : new Error(message); // display the error message first, then the optional params, and finally the stack trace // the stack needs to be displayed last because the given params will be lost among large stack traces so it will // provide a bad developer experience console.error('%cQWIK ERROR', STYLE, err.message, ...printParams(optionalParams), err.stack); asyncThrow && !qTest && setTimeout(() => { // throwing error asynchronously to avoid breaking the current call stack. // We throw so that the error is delivered to the global error handler for // reporting it to a third-party tools such as Qwik Insights, Sentry or New Relic. throw err; }, 0); return err; }; const ASSERT_DISCLAIMER = 'Internal assert, this is likely caused by a bug in Qwik: '; function assertDefined(value, text, ...parts) { if (qDev) { if (value != null) { return; } throwErrorAndStop(ASSERT_DISCLAIMER + text, ...parts); } } function assertEqual(value1, value2, text, ...parts) { if (qDev) { if (value1 === value2) { return; } throwErrorAndStop(ASSERT_DISCLAIMER + text, ...parts); } } function assertFail(text, ...parts) { if (qDev) { throwErrorAndStop(ASSERT_DISCLAIMER + text, ...parts); } } function assertTrue(value1, text, ...parts) { if (qDev) { if (value1 === true) { return; } throwErrorAndStop(ASSERT_DISCLAIMER + text, ...parts); } } function assertNumber(value1, text, ...parts) { if (qDev) { if (typeof value1 === 'number') { return; } throwErrorAndStop(ASSERT_DISCLAIMER + text, ...parts); } } function assertString(value1, text, ...parts) { if (qDev) { if (typeof value1 === 'string') { return; } throwErrorAndStop(ASSERT_DISCLAIMER + text, ...parts); } } function assertQwikElement(el) { if (qDev) { if (!isQwikElement(el)) { console.error('Not a Qwik Element, got', el); throwErrorAndStop(ASSERT_DISCLAIMER + 'Not a Qwik Element'); } } } function assertElement(el) { if (qDev) { if (!isElement$1(el)) { console.error('Not a Element, got', el); throwErrorAndStop(ASSERT_DISCLAIMER + 'Not an Element'); } } } const codeToText = (code, ...parts) => { if (qDev) { // Keep one error, one line to make it easier to search for the error message. const MAP = [ 'Error while serializing class or style attributes', // 0 'Can not serialize a HTML Node that is not an Element', // 1 'Runtime but no instance found on element.', // 2 'Only primitive and object literals can be serialized', // 3 'Crash while rendering', // 4 'You can render over a existing q:container. Skipping render().', // 5 'Set property {{0}}', // 6 "Only function's and 'string's are supported.", // 7 "Only objects can be wrapped in 'QObject'", // 8 `Only objects literals can be wrapped in 'QObject'`, // 9 'QRL is not a function', // 10 'Dynamic import not found', // 11 'Unknown type argument', // 12 `Actual value for useContext({{0}}) can not be found, make sure some ancestor component has set a value using useContextProvider(). In the browser make sure that the context was used during SSR so its state was serialized.`, // 13 "Invoking 'use*()' method outside of invocation context.", // 14 'Cant access renderCtx for existing context', // 15 'Cant access document for existing context', // 16 'props are immutable', // 17 '<div> component can only be used at the root of a Qwik component$()', // 18 'Props are immutable by default.', // 19 `Calling a 'use*()' method outside 'component$(() => { HERE })' is not allowed. 'use*()' methods provide hooks to the 'component$' state and lifecycle, ie 'use' hooks can only be called synchronously within the 'component$' function or another 'use' method.\nSee https://qwik.dev/docs/components/tasks/#use-method-rules`, // 20 'Container is already paused. Skipping', // 21 '', // 22 -- unused 'When rendering directly on top of Document, the root node must be a <html>', // 23 'A <html> node must have 2 children. The first one <head> and the second one a <body>', // 24 'Invalid JSXNode type "{{0}}". It must be either a function or a string. Found:', // 25 'Tracking value changes can only be done to useStore() objects and component props', // 26 'Missing Object ID for captured object', // 27 'The provided Context reference "{{0}}" is not a valid context created by createContextId()', // 28 '<html> is the root container, it can not be rendered inside a component', // 29 'QRLs can not be resolved because it does not have an attached container. This means that the QRL does not know where it belongs inside the DOM, so it cant dynamically import() from a relative path.', // 30 'QRLs can not be dynamically resolved, because it does not have a chunk path', // 31 'The JSX ref attribute must be a Signal', // 32 ]; let text = MAP[code] ?? ''; if (parts.length) { text = text.replaceAll(/{{(\d+)}}/g, (_, index) => { let v = parts[index]; if (v && typeof v === 'object' && v.constructor === Object) { v = JSON.stringify(v).slice(0, 50); } return v; }); } return `Code(${code}): ${text}`; } else { // cute little hack to give roughly the correct line number. Update the line number if it shifts. return `Code(${code}) https://github.com/QwikDev/qwik/blob/main/packages/qwik/src/core/error/error.ts#L${8 + code}`; } }; const QError_stringifyClassOrStyle = 0; const QError_verifySerializable = 3; const QError_cannotRenderOverExistingContainer = 5; const QError_setProperty = 6; const QError_qrlIsNotFunction = 10; const QError_dynamicImportFailed = 11; const QError_unknownTypeArgument = 12; const QError_notFoundContext = 13; const QError_useMethodOutsideContext = 14; const QError_immutableProps = 17; const QError_useInvokeContext = 20; const QError_containerAlreadyPaused = 21; const QError_invalidJsxNodeType = 25; const QError_trackUseStore = 26; const QError_missingObjectId = 27; const QError_invalidContext = 28; const QError_canNotRenderHTML = 29; const QError_qrlMissingContainer = 30; const QError_qrlMissingChunk = 31; const QError_invalidRefValue = 32; const qError = (code, ...parts) => { const text = codeToText(code, ...parts); return logErrorAndStop(text, ...parts); }; // keep this import from qwik/build so the cjs build works const createPlatform = () => { return { 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(QError_qrlMissingChunk, symbolName); } if (!containerEl) { throw qError(QError_qrlMissingContainer, url, symbolName); } const urlDoc = toUrl(containerEl.ownerDocument, containerEl, url).toString(); const urlCopy = new URL(urlDoc); urlCopy.hash = ''; const importURL = urlCopy.href; return import(/* @vite-ignore */ importURL).then((mod) => { return mod[symbolName]; }); }, raf: (fn) => { return new Promise((resolve) => { requestAnimationFrame(() => { resolve(fn()); }); }); }, nextTick: (fn) => { return new Promise((resolve) => { setTimeout(() => { resolve(fn()); }); }); }, chunkForSymbol(symbolName, chunk) { return [symbolName, chunk ?? '_']; }, }; }; /** * Convert relative base URI and relative URL into a fully qualified URL. * * @param base -`QRL`s are relative, and therefore they need a base for resolution. * * - `Element` use `base.ownerDocument.baseURI` * - `Document` use `base.baseURI` * - `string` use `base` as is * - `QConfig` use `base.baseURI` * * @param url - Relative URL * @returns Fully qualified URL. */ 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(); // <docs markdown="./readme.md#setPlatform"> // !!DO NOT EDIT THIS COMMENT DIRECTLY!!! // (edit ./readme.md#setPlatform instead) /** * Sets the `CorePlatform`. * * This is useful to override the platform in tests to change the behavior of, * `requestAnimationFrame`, and import resolution. * * @param doc - The document of the application for which the platform is needed. * @param platform - The platform to use. * @public */ // </docs> const setPlatform = (plt) => (_platform = plt); // <docs markdown="./readme.md#getPlatform"> // !!DO NOT EDIT THIS COMMENT DIRECTLY!!! // (edit ./readme.md#getPlatform instead) /** * Retrieve the `CorePlatform`. * * The `CorePlatform` is also responsible for retrieving the Manifest, that contains mappings from * symbols to javascript import chunks. For this reason, `CorePlatform` can't be global, but is * specific to the application currently running. On server it is possible that many different * applications are running in a single server instance, and for this reason the `CorePlatform` is * associated with the application document. * * @param docOrNode - The document (or node) of the application for which the platform is needed. * @public */ // </docs> const getPlatform = () => { return _platform; }; const isServerPlatform = () => { if (qDynamicPlatform) { return _platform.isServer; } return false; }; /** @private */ const isSerializableObject = (v) => { const proto = Object.getPrototypeOf(v); return proto === Object.prototype || proto === null; }; const isObject = (v) => { return !!v && typeof v === 'object'; }; const isArray = (v) => { return Array.isArray(v); }; const isString = (v) => { return typeof v === 'string'; }; const isFunction = (v) => { return typeof v === 'function'; }; const isPromise = (value) => { // not using "value instanceof Promise" to have zone.js support return value && typeof value.then === 'function'; }; const safeCall = (call, thenFn, rejectFn) => { try { const promise = call(); if (isPromise(promise)) { return promise.then(thenFn, rejectFn); } else { return thenFn(promise); } } catch (e) { return rejectFn(e); } }; const maybeThen = (promise, thenFn) => { return isPromise(promise) ? promise.then(thenFn) : thenFn(promise); }; const promiseAll = (promises) => { const hasPromise = promises.some(isPromise); if (hasPromise) { return Promise.all(promises); } return promises; }; const promiseAllLazy = (promises) => { if (promises.length > 0) { return Promise.all(promises); } return promises; }; const isNotNullable = (v) => { return v != null; }; const delay = (timeout) => { return new Promise((resolve) => { setTimeout(resolve, timeout); }); }; // import { qDev } from './qdev'; const EMPTY_ARRAY = []; const EMPTY_OBJ = {}; if (qDev) { Object.freeze(EMPTY_ARRAY); Object.freeze(EMPTY_OBJ); } const getDocument = (node) => { if (!qDynamicPlatform) { return document; } if (typeof document !== 'undefined') { return document; } if (node.nodeType === 9) { return node; } const doc = node.ownerDocument; assertDefined(doc, 'doc must be defined'); return doc; }; /** State factory of the component. */ const OnRenderProp = 'q:renderFn'; /** Component style content prefix */ const ComponentStylesPrefixContent = '⭐️'; /** `<some-element q:slot="...">` */ const QSlot = 'q:slot'; const QSlotRef = 'q:sref'; const QSlotS = 'q:s'; const QStyle = 'q:style'; const QScopedStyle = 'q:sstyle'; const QInstance = 'q:instance'; const QFuncsPrefix = 'qFuncs_'; const getQFuncs = (document, hash) => { return document[QFuncsPrefix + hash] || []; }; const QLocaleAttr = 'q:locale'; const QContainerAttr = 'q:container'; const QContainerSelector = '[q\\:container]'; const ResourceEvent = 'qResource'; const ComputedEvent = 'qComputed'; const RenderEvent = 'qRender'; const TaskEvent = 'qTask'; const ELEMENT_ID = 'q:id'; const ELEMENT_ID_PREFIX = '#'; const QObjectRecursive = 1 << 0; const QObjectImmutable = 1 << 1; const QOjectTargetSymbol = Symbol('proxy target'); const QObjectFlagsSymbol = Symbol('proxy flags'); const QObjectManagerSymbol = Symbol('proxy manager'); /** @internal */ const _IMMUTABLE = Symbol('IMMUTABLE'); const _IMMUTABLE_PREFIX = '$$'; /** * @internal * Key for the virtual element stored on qv comments */ const VIRTUAL_SYMBOL = '__virtual'; /** * @internal * Key for the `QContext` object stored on QwikElements */ const Q_CTX = '_qc_'; const directSetAttribute = (el, prop, value) => { return el.setAttribute(prop, value); }; const directGetAttribute = (el, prop) => { return el.getAttribute(prop); }; const directRemoveAttribute = (el, prop) => { return el.removeAttribute(prop); }; const fromCamelToKebabCase = (text) => { return text.replace(/([A-Z])/g, '-$1').toLowerCase(); }; const fromKebabToCamelCase = (text) => { return text.replace(/-./g, (x) => x[1].toUpperCase()); }; // keep this import from qwik/build so the cjs build works const emitEvent$1 = (el, eventName, detail, bubbles) => { if (!qTest && (isBrowser || typeof CustomEvent === 'function')) { if (el) { el.dispatchEvent(new CustomEvent(eventName, { detail, bubbles: bubbles, composed: bubbles, })); } } }; /** Creates a proxy that notifies of any writes. */ const getOrCreateProxy = (target, containerState, flags = 0) => { const proxy = containerState.$proxyMap$.get(target); if (proxy) { return proxy; } if (flags !== 0) { setObjectFlags(target, flags); } return createProxy(target, containerState, undefined); }; const createProxy = (target, containerState, subs) => { assertEqual(unwrapProxy(target), target, 'Unexpected proxy at this location', target); assertTrue(!containerState.$proxyMap$.has(target), 'Proxy was already created', target); assertTrue(isObject(target), 'Target must be an object'); assertTrue(isSerializableObject(target) || isArray(target), 'Target must be a serializable object'); const manager = containerState.$subsManager$.$createManager$(subs); const proxy = new Proxy(target, new ReadWriteProxyHandler(containerState, manager)); containerState.$proxyMap$.set(target, proxy); return proxy; }; const createPropsState = () => { const props = {}; setObjectFlags(props, QObjectImmutable); return props; }; const setObjectFlags = (obj, flags) => { Object.defineProperty(obj, QObjectFlagsSymbol, { value: flags, enumerable: false }); }; /** @internal */ const _restProps = (props, omit) => { const rest = {}; for (const key in props) { if (!omit.includes(key)) { rest[key] = props[key]; } } return rest; }; class ReadWriteProxyHandler { $containerState$; $manager$; constructor($containerState$, $manager$) { this.$containerState$ = $containerState$; this.$manager$ = $manager$; } deleteProperty(target, prop) { if (target[QObjectFlagsSymbol] & QObjectImmutable) { throw qError(QError_immutableProps); } if (typeof prop != 'string' || !delete target[prop]) { return false; } this.$manager$.$notifySubs$(isArray(target) ? undefined : prop); return true; } get(target, prop) { if (typeof prop === 'symbol') { if (prop === QOjectTargetSymbol) { return target; } if (prop === QObjectManagerSymbol) { return this.$manager$; } return target[prop]; } const flags = target[QObjectFlagsSymbol] ?? 0; assertNumber(flags, 'flags must be an number'); const invokeCtx = tryGetInvokeContext(); const recursive = (flags & QObjectRecursive) !== 0; const immutable = (flags & QObjectImmutable) !== 0; const hiddenSignal = target[_IMMUTABLE_PREFIX + prop]; let subscriber; let value; if (invokeCtx) { subscriber = invokeCtx.$subscriber$; } if (immutable && (!(prop in target) || immutableValue(target[_IMMUTABLE]?.[prop]))) { subscriber = null; } if (hiddenSignal) { assertTrue(isSignal(hiddenSignal), '$$ prop must be a signal'); value = hiddenSignal.value; subscriber = null; } else { value = target[prop]; } if (subscriber) { const isA = isArray(target); this.$manager$.$addSub$(subscriber, isA ? undefined : prop); } return recursive ? wrap(value, this.$containerState$) : value; } set(target, prop, newValue) { if (typeof prop === 'symbol') { target[prop] = newValue; return true; } const flags = target[QObjectFlagsSymbol] ?? 0; assertNumber(flags, 'flags must be an number'); const immutable = (flags & QObjectImmutable) !== 0; if (immutable) { throw qError(QError_immutableProps); } const recursive = (flags & QObjectRecursive) !== 0; const unwrappedNewValue = recursive ? unwrapProxy(newValue) : newValue; if (qDev) { if (qSerialize) { verifySerializable(unwrappedNewValue); } const invokeCtx = tryGetInvokeContext(); if (invokeCtx) { if (invokeCtx.$event$ === RenderEvent) { logError('State mutation inside render function. Move mutation to useTask$() or useVisibleTask$()', prop); } else if (invokeCtx.$event$ === ComputedEvent) { logWarn('State mutation inside useComputed$() is an antipattern. Use useTask$() instead', invokeCtx.$hostElement$); } else if (invokeCtx.$event$ === ResourceEvent) { logWarn('State mutation inside useResource$() is an antipattern. Use useTask$() instead', invokeCtx.$hostElement$); } } } const isA = isArray(target); if (isA) { target[prop] = unwrappedNewValue; this.$manager$.$notifySubs$(); return true; } const oldValue = target[prop]; target[prop] = unwrappedNewValue; if (oldValue !== unwrappedNewValue) { this.$manager$.$notifySubs$(prop); } return true; } has(target, prop) { if (prop === QOjectTargetSymbol) { return true; } const invokeCtx = tryGetInvokeContext(); if (typeof prop === 'string' && invokeCtx) { const subscriber = invokeCtx.$subscriber$; if (subscriber) { const isA = isArray(target); this.$manager$.$addSub$(subscriber, isA ? undefined : prop); } } const hasOwnProperty = Object.prototype.hasOwnProperty; if (hasOwnProperty.call(target, prop)) { return true; } if (typeof prop === 'string' && hasOwnProperty.call(target, _IMMUTABLE_PREFIX + prop)) { return true; } return false; } ownKeys(target) { const flags = target[QObjectFlagsSymbol] ?? 0; assertNumber(flags, 'flags must be an number'); const immutable = (flags & QObjectImmutable) !== 0; if (!immutable) { let subscriber = null; const invokeCtx = tryGetInvokeContext(); if (invokeCtx) { subscriber = invokeCtx.$subscriber$; } if (subscriber) { this.$manager$.$addSub$(subscriber); } } if (isArray(target)) { return Reflect.ownKeys(target); } return Reflect.ownKeys(target).map((a) => { return typeof a === 'string' && a.startsWith(_IMMUTABLE_PREFIX) ? a.slice(_IMMUTABLE_PREFIX.length) : a; }); } getOwnPropertyDescriptor(target, prop) { const descriptor = Reflect.getOwnPropertyDescriptor(target, prop); if (isArray(target) || typeof prop === 'symbol') { return descriptor; } if (descriptor && !descriptor.configurable) { return descriptor; } return { enumerable: true, configurable: true, }; } } const immutableValue = (value) => { return value === _IMMUTABLE || isSignal(value); }; const wrap = (value, containerState) => { if (isObject(value)) { if (Object.isFrozen(value)) { return value; } const nakedValue = unwrapProxy(value); if (nakedValue !== value) { // already a proxy return; return value; } if (fastSkipSerialize(nakedValue)) { return value; } if (isSerializableObject(nakedValue) || isArray(nakedValue)) { const proxy = containerState.$proxyMap$.get(nakedValue); return proxy ? proxy : getOrCreateProxy(nakedValue, containerState, QObjectRecursive); } } return value; }; const ON_PROP_REGEX = /^(on|window:|document:)/; const PREVENT_DEFAULT = 'preventdefault:'; const isOnProp = (prop) => { return prop.endsWith('$') && ON_PROP_REGEX.test(prop); }; const groupListeners = (listeners) => { if (listeners.length === 0) { return EMPTY_ARRAY; } if (listeners.length === 1) { const listener = listeners[0]; return [[listener[0], [listener[1]]]]; } const keys = []; for (let i = 0; i < listeners.length; i++) { const eventName = listeners[i][0]; if (!keys.includes(eventName)) { keys.push(eventName); } } return keys.map((eventName) => { return [eventName, listeners.filter((l) => l[0] === eventName).map((a) => a[1])]; }); }; const setEvent = (existingListeners, prop, input, containerEl) => { assertTrue(prop.endsWith('$'), 'render: event property does not end with $', prop); prop = normalizeOnProp(prop.slice(0, -1)); if (input) { if (isArray(input)) { const processed = input .flat(Infinity) .filter((q) => q != null) .map((q) => [prop, ensureQrl(q, containerEl)]); existingListeners.push(...processed); } else { existingListeners.push([prop, ensureQrl(input, containerEl)]); } } return prop; }; const PREFIXES = ['on', 'window:on', 'document:on']; const SCOPED = ['on', 'on-window', 'on-document']; const normalizeOnProp = (prop) => { let scope = 'on'; for (let i = 0; i < PREFIXES.length; i++) { const prefix = PREFIXES[i]; if (prop.startsWith(prefix)) { scope = SCOPED[i]; prop = prop.slice(prefix.length); break; } } if (prop.startsWith('-')) { prop = fromCamelToKebabCase(prop.slice(1)); } else { prop = prop.toLowerCase(); } return scope + ':' + prop; }; const ensureQrl = (value, containerEl) => { if (qSerialize && !qRuntimeQrl) { assertQrl(value); value.$setContainer$(containerEl); return value; } const qrl = isQrl(value) ? value : $(value); qrl.$setContainer$(containerEl); return qrl; }; const getDomListeners = (elCtx, containerEl) => { const attributes = elCtx.$element$.attributes; const listeners = []; for (let i = 0; i < attributes.length; i++) { const { name, value } = attributes.item(i); if (name.startsWith('on:') || name.startsWith('on-window:') || name.startsWith('on-document:')) { const urls = value.split('\n'); for (const url of urls) { const qrl = parseQRL(url, containerEl); if (qrl.$capture$) { inflateQrl(qrl, elCtx); } listeners.push([name, qrl]); } } } return listeners; }; const hashCode = (text, hash = 0) => { for (let i = 0; i < text.length; i++) { const chr = text.charCodeAt(i); hash = (hash << 5) - hash + chr; hash |= 0; // Convert to 32bit integer } return Number(Math.abs(hash)).toString(36); }; const styleKey = (qStyles, index) => { assertQrl(qStyles); return `${hashCode(qStyles.$hash$)}-${index}`; }; const styleContent = (styleId) => { return ComponentStylesPrefixContent + styleId; }; const serializeSStyle = (scopeIds) => { const value = scopeIds.join('|'); if (value.length > 0) { return value; } return undefined; }; /** * QWIK_VERSION * * @public */ const version = "1.16.0"; /** * @internal * The storage provider for hooks. Each invocation increases index i. Data is stored in an array. */ const useSequentialScope = () => { const iCtx = useInvokeContext(); const hostElement = iCtx.$hostElement$; const elCtx = getContext(hostElement, iCtx.$renderCtx$.$static$.$containerState$); const seq = (elCtx.$seq$ ||= []); const i = iCtx.$i$++; const set = (value) => { if (qDev && qSerialize) { verifySerializable(value); } return (seq[i] = value); }; return { val: seq[i], set, i, iCtx, elCtx, }; }; // <docs markdown="../readme.md#createContextId"> // !!DO NOT EDIT THIS COMMENT DIRECTLY!!! // (edit ../readme.md#createContextId instead) /** * Create a context ID to be used in your application. The name should be written with no spaces. * * Context is a way to pass stores to the child components without prop-drilling. * * Use `createContextId()` to create a `ContextId`. A `ContextId` is just a serializable identifier * for the context. It is not the context value itself. See `useContextProvider()` and * `useContext()` for the values. Qwik needs a serializable ID for the context so that the it can * track context providers and consumers in a way that survives resumability. * * ### Example * * ```tsx * // Declare the Context type. * interface TodosStore { * items: string[]; * } * // Create a Context ID (no data is saved here.) * // You will use this ID to both create and retrieve the Context. * export const TodosContext = createContextId<TodosStore>('Todos'); * * // Example of providing context to child components. * export const App = component$(() => { * useContextProvider( * TodosContext, * useStore<TodosStore>({ * items: ['Learn Qwik', 'Build Qwik app', 'Profit'], * }) * ); * * return <Items />; * }); * * // Example of retrieving the context provided by a parent component. * export const Items = component$(() => { * const todos = useContext(TodosContext); * return ( * <ul> * {todos.items.map((item) => ( * <li>{item}</li> * ))} * </ul> * ); * }); * * ``` * * @param name - The name of the context. * @public */ // </docs> const createContextId = (name) => { assertTrue(/^[\w/.-]+$/.test(name), 'Context name must only contain A-Z,a-z,0-9, _', name); return /*#__PURE__*/ Object.freeze({ id: fromCamelToKebabCase(name), }); }; // <docs markdown="../readme.md#useContextProvider"> // !!DO NOT EDIT THIS COMMENT DIRECTLY!!! // (edit ../readme.md#useContextProvider instead) /** * Assign a value to a Context. * * Use `useContextProvider()` to assign a value to a context. The assignment happens in the * component's function. Once assigned, use `useContext()` in any child component to retrieve the * value. * * Context is a way to pass stores to the child components without prop-drilling. Note that scalar * values are allowed, but for reactivity you need signals or stores. * * ### Example * * ```tsx * // Declare the Context type. * interface TodosStore { * items: string[]; * } * // Create a Context ID (no data is saved here.) * // You will use this ID to both create and retrieve the Context. * export const TodosContext = createContextId<TodosStore>('Todos'); * * // Example of providing context to child components. * export const App = component$(() => { * useContextProvider( * TodosContext, * useStore<TodosStore>({ * items: ['Learn Qwik', 'Build Qwik app', 'Profit'], * }) * ); * * return <Items />; * }); * * // Example of retrieving the context provided by a parent component. * export const Items = component$(() => { * const todos = useContext(TodosContext); * return ( * <ul> * {todos.items.map((item) => ( * <li>{item}</li> * ))} * </ul> * ); * }); * * ``` * * @param context - The context to assign a value to. * @param value - The value to assign to the context. * @public */ // </docs> const useContextProvider = (context, newValue) => { const { val, set, elCtx } = useSequentialScope(); if (val !== undefined) { return; } if (qDev) { validateContext(context); } const contexts = (elCtx.$contexts$ ||= new Map()); if (qDev && qSerialize) { verifySerializable(newValue); } contexts.set(context.id, newValue); set(true); }; // <docs markdown="../readme.md#useContext"> // !!DO NOT EDIT THIS COMMENT DIRECTLY!!! // (edit ../readme.md#useContext instead) /** * Retrieve Context value. * * Use `useContext()` to retrieve the value of context in a component. To retrieve a value a parent * component needs to invoke `useContextProvider()` to assign a value. * * ### Example * * ```tsx * // Declare the Context type. * interface TodosStore { * items: string[]; * } * // Create a Context ID (no data is saved here.) * // You will use this ID to both create and retrieve the Context. * export const TodosContext = createContextId<TodosStore>('Todos'); * * // Example of providing context to child components. * export const App = component$(() => { * useContextProvider( * TodosContext, * useStore<TodosStore>({ * items: ['Learn Qwik', 'Build Qwik app', 'Profit'], * }) * ); * * return <Items />; * }); * * // Example of retrieving the context provided by a parent component. * export const Items = component$(() => { * const todos = useContext(TodosContext); * return ( * <ul> * {todos.items.map((item) => ( * <li>{item}</li> * ))} * </ul> * ); * }); * * ``` * * @param context - The context to retrieve a value from. * @public */ // </docs> const useContext = (context, defaultValue) => { const { val, set, iCtx, elCtx } = useSequentialScope(); if (val !== undefined) { return val; } if (qDev) { validateContext(context); } const value = resolveContext(context, elCtx, iCtx.$renderCtx$.$static$.$containerState$); if (typeof defaultValue === 'function') { return set(invoke(undefined, defaultValue, value)); } if (value !== undefined) { return set(value); } if (defaultValue !== undefined) { return set(defaultValue); } throw qError(QError_notFoundContext, context.id); }; /** Find a wrapping Virtual component in the DOM */ const findParentCtx = (el, containerState) => { let node = el; let stack = 1; while (node && !node.hasAttribute?.('q:container')) { // Walk the siblings backwards, each comment might be the Virtual wrapper component while ((node = node.previousSibling)) { if (isComment(node)) { const virtual = node[VIRTUAL_SYMBOL]; if (virtual) { const qtx = virtual[Q_CTX]; if (node === virtual.open) { // We started inside this node so this is our parent return qtx ?? getContext(virtual, containerState); } // This is a sibling, check if it knows our parent if (qtx?.$parentCtx$) { return qtx.$parentCtx$; } // Skip over this entire virtual sibling node = virtual; continue; } if (node.data === '/qv') { stack++; } else if (node.data.startsWith('qv ')) { stack--; if (stack === 0) { return getContext(getVirtualElement(node), containerState); } } } } // No more siblings, walk up the DOM tree. The parent will never be a Virtual component. node = el.parentElement; el = node; } return null; }; const getParentProvider = (ctx, containerState) => { // `null` means there's no parent, `undefined` means we don't know yet. if (ctx.$parentCtx$ === undefined) { // Not fully resumed container, find context from DOM // We cannot recover $realParentCtx$ from this but that's fine because we don't need to pause on the client ctx.$parentCtx$ = findParentCtx(ctx.$element$, containerState); } /** * Note, the parentCtx is used during pause to to get the immediate parent, so we can't shortcut * the search for $contexts$ here. If that turns out to be needed, it needs to be cached in a * separate property. */ return ctx.$parentCtx$; }; const resolveContext = (context, hostCtx, containerState) => { const contextID = context.id; if (!hostCtx) { return; } let ctx = hostCtx; while (ctx) { const found = ctx.$contexts$?.get(contextID); if (found) { return found; } ctx = getParentProvider(ctx, containerState); } }; const validateContext = (context) => { if (!isObject(context) || typeof context.id !== 'string' || context.id.length === 0) { throw qError(QError_invalidContext, context); } }; const ERROR_CONTEXT = /*#__PURE__*/ createContextId('qk-error'); const handleError = (err, hostElement, rCtx) => { const elCtx = tryGetContext(hostElement); if (qDev) { // Clean vdom if (!isServerPlatform() && typeof document !== 'undefined' && isVirtualElement(hostElement)) { // (hostElement as any).$vdom$ = null; elCtx.$vdom$ = null; const errorDiv = document.createElement('errored-host'); if (err && err instanceof Error) { errorDiv.props = { error: err }; } errorDiv.setAttribute('q:key', '_error_'); errorDiv.append(...hostElement.childNodes); hostElement.appendChild(errorDiv); } if (err && err instanceof Error) { if (!('hostElement' in err)) { err['hostElement'] = hostElement; } } if (!isRecoverable(err)) { throw err; } } if (isServerPlatform()) { throw err; } else { const errorStore = resolveContext(ERROR_CONTEXT, elCtx, rCtx.$static$.$containerState$); if (errorStore === undefined) { throw err; } errorStore.error = err; } }; const isRecoverable = (err) => { if (err && err instanceof Error) { if ('plugin' in err) { return false; } } return true; }; /** CSS properties which accept numbers but are not in units of "px". */ const unitlessNumbers = new Set([ 'animationIterationCount', 'aspectRatio', 'borderImageOutset', 'borderImageSlice', 'borderImageWidth', 'boxFlex', 'boxFlexGroup', 'boxOrdinalGroup', 'columnCount', 'columns', 'flex', 'flexGrow', 'flexShrink', 'gridArea', 'gridRow', 'gridRowEnd', 'gridRowStart', 'gridColumn', 'gridColumnEnd', 'gridColumnStart', 'fontWeight', 'lineClamp', 'lineHeight', 'opacity', 'order', 'orphans', 'scale', 'tabSize', 'widows', 'zIndex', 'zoom', 'MozAnimationIterationCount', // Known Prefixed Properties 'MozBoxFlex', // TODO: Remove these since they shouldn't be used in modern code 'msFlex', 'msFlexPositive', 'WebkitAnimationIterationCount', 'WebkitBoxFlex', 'WebkitBoxOrdinalGroup', 'WebkitColumnCount', 'WebkitColumns', 'WebkitFlex', 'WebkitFlexGrow', 'WebkitFlexShrink', 'WebkitLineClamp', ]); const isUnitlessNumber = (name) => { return unitlessNumbers.has(name); }; const executeComponent = (rCtx, elCtx, attempt) => { elCtx.$flags$ &= ~HOST_FLAG_DIRTY; elCtx.$flags$ |= HOST_FLAG_MOUNTED; elCtx.$slots$ = []; elCtx.li.length = 0; const hostElement = elCtx.$element$; const componentQRL = elCtx.$componentQrl$; const props = elCtx.$props$; const iCtx = newInvokeContext(rCtx.$static$.$locale$, hostElement, undefined, RenderEvent); const waitOn = (iCtx.$waitOn$ = []); assertDefined(componentQRL, `render: host element to render must have a $renderQrl$:`, elCtx); assertDefined(props, `render: host element to render must have defined props`, elCtx); // Set component context const newCtx = pushRenderContext(rCtx); newCtx.$cmpCtx$ = elCtx; newCtx.$slotCtx$ = undefined; // Invoke render hook iCtx.$subscriber$ = [0, hostElement]; iCtx.$renderCtx$ = rCtx; // Resolve render function componentQRL.$setContainer$(rCtx.$static$.$containerState$.$containerEl$); const componentFn = componentQRL.getFn(iCtx); return safeCall(() => componentFn(props), (jsxNode) => { return maybeThen(isServerPlatform() ? maybeThen(promiseAllLazy(waitOn), () => // Run dirty tasks before SSR output is generated. maybeThen(executeSSRTasks(rCtx.$static$.$containerState$, rCtx), () => promiseAllLazy(waitOn))) : promiseAllLazy(waitOn), () => { if (elCtx.$flags$ & HOST_FLAG_DIRTY) { if (attempt && attempt > 100) { logWarn(`Infinite loop detected. Element: ${elCtx.$componentQrl$?.$symbol$}`); } else { return executeComponent(rCtx, elCtx, attempt ? attempt + 1 : 1); } } return { node: jsxNode, rCtx: newCtx, }; }); }, (err) => { if (err === SignalUnassignedException) { if (attempt && attempt > 100) { logWarn(`Infinite loop detected. Element: ${elCtx.$componentQrl$?.$symbol$}`); } else { return maybeThen(promiseAllLazy(waitOn), () => { return executeComponent(rCtx, elCtx, attempt ? attempt + 1 : 1); }); } } handleError(err, hostElement, rCtx); return { node: SkipRender, rCtx: newCtx, }; }); }; const createRenderContext = (doc, containerState) => { const ctx = { $static$: { $doc$: doc, $locale$: containerState.$serverData$.locale, $containerState$: containerState, $hostElements$: new Set(), $operations$: [], $postOperations$: [], $roots$: [], $addSlots$: [], $rmSlots$: [], $visited$: [], }, $cmpCtx$: null, $slotCtx$: undefined, }; seal(ctx); seal(ctx.$static$); return ctx; }; const pushRenderContext = (ctx) => { const newCtx = { $static$: ctx.$static$, $cmpCtx$: ctx.$cmpCtx$, $slotCtx$: ctx.$slotCtx$, }; return newCtx; }; const serializeClassWithHost = (obj, hostCtx) => { if (hostCtx?.$scopeIds$?.length) { return hostCtx.$scopeIds$.join(' ') + ' ' + serializeClass(obj); } return serializeClass(obj); }; const serializeClass = (obj) => { if (!obj) { return ''; } if (isString(obj)) { return obj.trim(); } const classes = []; if (isArray(obj)) { for (const o of obj) { const classList = serializeClass(o); if (classList) { classes.push(classList); } } } else { for (const [key, value] of Object.entries(obj)) { if (value) { classes.push(key.trim()); } } } return classes.join(' '); }; const stringifyStyle = (obj) => { if (obj == null) { return ''; } if (typeof obj == 'object') { if (isArray(obj)) { throw qError(QError_stringifyClassOrStyle, obj, 'style'); } else { const chunks = []; for (const key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { const value = obj[key]; if (value != null && typeof value !== 'function') { if (key.startsWith('--')) { chunks.push(key + ':' + value); } else { chunks.push(fromCamelToKebabCase(key) + ':' + setValueForStyle(key, value)); } } } } return chunks.join(';'); } } return String(obj); }; const setValueForStyle = (styleName, value) => { if (typeof value === 'number' && value !== 0 && !isUnitlessNumber(styleName)) { return value + 'px'; } return value; }; const getNextIndex = (ctx) => { return intToStr(ctx.$static$.$containerState$.$elementIndex$++); }; const setQId = (rCtx, elCtx) => { const id = getNextIndex(rCtx); elCtx.$id$ = id; }; const jsxToString = (data) => { if (isSignal(data)) { return jsxToString(data.value); } return data == null || typeof data === 'boolean' ? '' : String(data); }; function isAriaAttribute(prop) { return prop.startsWith('aria-'); } const shouldWrapFunctional = (res, node) => { if (node.key) { return !isJSXNode(res) || (!isFunction(res.type) && res.key != node.key); } return false; }; const static_listeners = 1 << 0; const static_subtree = 1 << 1; const dangerouslySetInnerHTML = 'dangerouslySetInnerHTML'; const FLUSH_COMMENT = '<!--qkssr-f-->'; const IS_HEAD$1 = 1 << 0; const IS_HTML = 1 << 2; const IS_TEXT = 1 << 3; const IS_INVISIBLE = 1 << 4; const IS_PHASING = 1 << 5; const IS_ANCHOR = 1 << 6; const IS_BUTTON = 1 << 7; const IS_TABLE = 1 << 8; const IS_PHRASING_CONTAINER = 1 << 9; const IS_IMMUTABLE$1 = 1 << 10; class MockElement { nodeType; [Q_CTX] = null; constructor(nodeType) { this.nodeType = nodeType; seal(this); } } const createDocument = () => { return new MockElement(9); }; /** @internal */ const _renderSSR = async (node, opts) => { const root = opts.containerTagName; const containerEl = createMockQContext(1).$element$; const containerState = createContainerState(containerEl, opts.base ?? '/'); containerState.$serverData$.locale = opts.serverData?.locale; const doc = createDocument(); const rCtx = createRenderContext(doc, containerState); const headNodes = opts.beforeContent ?? []; if (qDev) { if (root in phasingContent ||