import type * as CSS_2 from 'csstype'; import { getAsyncLocalStorage as _getAsyncLocalStorage } from './async-local-storage.js'; import { isBrowser } from './build/index.js'; import { isDev } from './build/index.js'; import { isServer } from './build/index.js'; import { ResolvedManifest } from './optimizer.js'; import type { ServerQwikManifest } from './optimizer.js'; /** * Qwik Optimizer marker function. * * Use `$(...)` to tell Qwik Optimizer to extract the expression in `$(...)` into a lazy-loadable * resource referenced by `QRL`. * * @param expression - Expression which should be lazy loaded * @public * @see `implicit$FirstArg` for additional `____$(...)` rules. * * In this example, `$(...)` is used to capture the callback function of `onmousemove` into a * lazy-loadable reference. This allows the code to refer to the function without actually * loading the function. In this example, the callback function does not get loaded until * `mousemove` event fires. * * ```tsx * useOnDocument( * 'mousemove', * $((event) => console.log('mousemove', event)) * ); * ``` * * In this code, the Qwik Optimizer detects `$(...)` and transforms the code into: * * ```tsx * // FILE: * useOnDocument('mousemove', qrl('./chunk-abc.js', 'onMousemove')); * * // FILE: chunk-abc.js * export const onMousemove = () => console.log('mousemove'); * ``` * * ## Special Rules * * The Qwik Optimizer places special rules on functions that can be lazy-loaded. * * 1. The expression of the `$(expression)` function must be importable by the system. * (expression shows up in `import` or has `export`) * 2. If inlined function, then all lexically captured values must be: * - importable (vars show up in `import`s or `export`s) * - const (The capturing process differs from JS capturing in that writing to captured * variables does not update them, and therefore writes are forbidden. The best practice is that * all captured variables are constants.) * - Must be runtime serializable. * * ```tsx * * import { createContextId, useContext, useContextProvider } from './use/use-context'; * import { Resource } from './use/use-resource'; * import { useResource$ } from './use/use-resource-dollar'; * import { useSignal } from './use/use-signal'; * * export const greet = () => console.log('greet'); * function topLevelFn() {} * * function myCode() { * const store = useStore({}); * function localFn() {} * // Valid Examples * $(greet); // greet is importable * $(() => greet()); // greet is importable; * $(() => console.log(store)); // store is serializable. * * // Compile time errors * $(topLevelFn); // ERROR: `topLevelFn` not importable * $(() => topLevelFn()); // ERROR: `topLevelFn` not importable * * // Runtime errors * $(localFn); // ERROR: `localFn` fails serialization * $(() => localFn()); // ERROR: `localFn` fails serialization * } * * ``` */ export declare const $: (expression: T) => QRL; /** * Register an external projection on a parent component VNode. * * Creates a new VirtualVNode that will render the given component QRL with the given props. The * VNode is stored as a projection on the parent, and a low-priority cursor is added so the cursor * walker will process it. * * Use `_setProjectionTarget` to set the DOM target element before the cursor fires. * * @internal */ export declare function _addProjection(container: _Container, parentVNode: _VirtualVNode, componentQRL: QRL, props: Record, slotName: string): _VirtualVNode; declare interface AddRootFn { (obj: unknown, returnRef?: never): number; (obj: unknown, returnRef: true): SeenRef; } declare type AllEventKeys = keyof AllEventsMap; declare type AllEventMapRaw = QwikHTMLElementEventMap & QwikDocumentEventMap & QwikWindowEventMap; declare type AllEventsMap = Omit & EventCorrectionMap; declare type _AllowPlainQrl = QRLEventHandlerMulti extends Q ? Q extends QRLEventHandlerMulti ? Q | (EL extends Element ? EventHandler : never) : Q : Q extends QRL ? Q | U : NonNullable extends never ? Q : QRL | Q; declare type AllSignalFlags = ComputedSignalFlags | SerializationSignalFlags | AsyncSignalFlags; /** * TS defines these with the React syntax which is not compatible with Qwik. E.g. `ariaAtomic` * instead of `aria-atomic`. * * @public */ declare interface AriaAttributes { /** * Identifies the currently active element when DOM focus is on a composite widget, textbox, * group, or application. */ 'aria-activedescendant'?: string | undefined; /** * Indicates whether assistive technologies will present all, or only parts of, the changed region * based on the change notifications defined by the aria-relevant attribute. */ 'aria-atomic'?: Booleanish | undefined; /** * Indicates whether inputting text could trigger display of one or more predictions of the user's * intended value for an input and specifies how predictions would be presented if they are made. */ 'aria-autocomplete'?: 'none' | 'inline' | 'list' | 'both' | undefined; /** * Indicates an element is being modified and that assistive technologies MAY want to wait until * the modifications are complete before exposing them to the user. */ 'aria-busy'?: Booleanish | undefined; /** * Indicates the current "checked" state of checkboxes, radio buttons, and other widgets. * * @see aria-pressed @see aria-selected. */ 'aria-checked'?: boolean | 'false' | 'mixed' | 'true' | undefined; /** * Defines the total number of columns in a table, grid, or treegrid. * * @see aria-colindex. */ 'aria-colcount'?: number | undefined; /** * Defines an element's column index or position with respect to the total number of columns * within a table, grid, or treegrid. * * @see aria-colcount @see aria-colspan. */ 'aria-colindex'?: number | undefined; /** * Defines the number of columns spanned by a cell or gridcell within a table, grid, or treegrid. * * @see aria-colindex @see aria-rowspan. */ 'aria-colspan'?: number | undefined; /** * Identifies the element (or elements) whose contents or presence are controlled by the current * element. * * @see aria-owns. */ 'aria-controls'?: string | undefined; /** * Indicates the element that represents the current item within a container or set of related * elements. */ 'aria-current'?: boolean | 'false' | 'true' | 'page' | 'step' | 'location' | 'date' | 'time' | undefined; /** * Identifies the element (or elements) that describes the object. * * @see aria-labelledby */ 'aria-describedby'?: string | undefined; /** * Identifies the element that provides a detailed, extended description for the object. * * @see aria-describedby. */ 'aria-details'?: string | undefined; /** * Indicates that the element is perceivable but disabled, so it is not editable or otherwise * operable. * * @see aria-hidden @see aria-readonly. */ 'aria-disabled'?: Booleanish | undefined; /** * Indicates what functions can be performed when a dragged object is released on the drop target. * * @deprecated In ARIA 1.1 */ 'aria-dropeffect'?: 'none' | 'copy' | 'execute' | 'link' | 'move' | 'popup' | undefined; /** * Identifies the element that provides an error message for the object. * * @see aria-invalid @see aria-describedby. */ 'aria-errormessage'?: string | undefined; /** * Indicates whether the element, or another grouping element it controls, is currently expanded * or collapsed. */ 'aria-expanded'?: Booleanish | undefined; /** * Identifies the next element (or elements) in an alternate reading order of content which, at * the user's discretion, allows assistive technology to override the general default of reading * in document source order. */ 'aria-flowto'?: string | undefined; /** * Indicates an element's "grabbed" state in a drag-and-drop operation. * * @deprecated In ARIA 1.1 */ 'aria-grabbed'?: Booleanish | undefined; /** * Indicates the availability and type of interactive popup element, such as menu or dialog, that * can be triggered by an element. */ 'aria-haspopup'?: boolean | 'false' | 'true' | 'menu' | 'listbox' | 'tree' | 'grid' | 'dialog' | undefined; /** * Indicates whether the element is exposed to an accessibility API. * * @see aria-disabled. */ 'aria-hidden'?: Booleanish | undefined; /** * Indicates the entered value does not conform to the format expected by the application. * * @see aria-errormessage. */ 'aria-invalid'?: boolean | 'false' | 'true' | 'grammar' | 'spelling' | undefined; /** * Indicates keyboard shortcuts that an author has implemented to activate or give focus to an * element. */ 'aria-keyshortcuts'?: string | undefined; /** * Defines a string value that labels the current element. * * @see aria-labelledby. */ 'aria-label'?: string | undefined; /** * Identifies the element (or elements) that labels the current element. * * @see aria-describedby. */ 'aria-labelledby'?: string | undefined; /** Defines the hierarchical level of an element within a structure. */ 'aria-level'?: number | undefined; /** * Indicates that an element will be updated, and describes the types of updates the user agents, * assistive technologies, and user can expect from the live region. */ 'aria-live'?: 'off' | 'assertive' | 'polite' | undefined; /** Indicates whether an element is modal when displayed. */ 'aria-modal'?: Booleanish | undefined; /** Indicates whether a text box accepts multiple lines of input or only a single line. */ 'aria-multiline'?: Booleanish | undefined; /** Indicates that the user may select more than one item from the current selectable descendants. */ 'aria-multiselectable'?: Booleanish | undefined; /** Indicates whether the element's orientation is horizontal, vertical, or unknown/ambiguous. */ 'aria-orientation'?: 'horizontal' | 'vertical' | undefined; /** * Identifies an element (or elements) in order to define a visual, functional, or contextual * parent/child relationship between DOM elements where the DOM hierarchy cannot be used to * represent the relationship. * * @see aria-controls. */ 'aria-owns'?: string | undefined; /** * Defines a short hint (a word or short phrase) intended to aid the user with data entry when the * control has no value. A hint could be a sample value or a brief description of the expected * format. */ 'aria-placeholder'?: string | undefined; /** * Defines an element's number or position in the current set of listitems or treeitems. Not * required if all elements in the set are present in the DOM. * * @see aria-setsize. */ 'aria-posinset'?: number | undefined; /** * Indicates the current "pressed" state of toggle buttons. * * @see aria-checked @see aria-selected. */ 'aria-pressed'?: boolean | 'false' | 'mixed' | 'true' | undefined; /** * Indicates that the element is not editable, but is otherwise operable. * * @see aria-disabled. */ 'aria-readonly'?: Booleanish | undefined; /** * Indicates what notifications the user agent will trigger when the accessibility tree within a * live region is modified. * * @see aria-atomic. */ 'aria-relevant'?: 'additions' | 'additions removals' | 'additions text' | 'all' | 'removals' | 'removals additions' | 'removals text' | 'text' | 'text additions' | 'text removals' | undefined; /** Indicates that user input is required on the element before a form may be submitted. */ 'aria-required'?: Booleanish | undefined; /** Defines a human-readable, author-localized description for the role of an element. */ 'aria-roledescription'?: string | undefined; /** * Defines the total number of rows in a table, grid, or treegrid. * * @see aria-rowindex. */ 'aria-rowcount'?: number | undefined; /** * Defines an element's row index or position with respect to the total number of rows within a * table, grid, or treegrid. * * @see aria-rowcount @see aria-rowspan. */ 'aria-rowindex'?: number | undefined; /** * Defines the number of rows spanned by a cell or gridcell within a table, grid, or treegrid. * * @see aria-rowindex @see aria-colspan. */ 'aria-rowspan'?: number | undefined; /** * Indicates the current "selected" state of various widgets. * * @see aria-checked @see aria-pressed. */ 'aria-selected'?: Booleanish | undefined; /** * Defines the number of items in the current set of listitems or treeitems. Not required if all * elements in the set are present in the DOM. * * @see aria-posinset. */ 'aria-setsize'?: number | undefined; /** Indicates if items in a table or grid are sorted in ascending or descending order. */ 'aria-sort'?: 'none' | 'ascending' | 'descending' | 'other' | undefined; /** Defines the maximum allowed value for a range widget. */ 'aria-valuemax'?: number | undefined; /** Defines the minimum allowed value for a range widget. */ 'aria-valuemin'?: number | undefined; /** * Defines the current value for a range widget. * * @see aria-valuetext. */ 'aria-valuenow'?: number | undefined; /** Defines the human readable text alternative of aria-valuenow for a range widget. */ 'aria-valuetext'?: string | undefined; } /** @public */ declare type AriaRole = 'alert' | 'alertdialog' | 'application' | 'article' | 'banner' | 'button' | 'cell' | 'checkbox' | 'columnheader' | 'combobox' | 'complementary' | 'contentinfo' | 'definition' | 'dialog' | 'directory' | 'document' | 'feed' | 'figure' | 'form' | 'grid' | 'gridcell' | 'group' | 'heading' | 'img' | 'link' | 'list' | 'listbox' | 'listitem' | 'log' | 'main' | 'marquee' | 'math' | 'menu' | 'menubar' | 'menuitem' | 'menuitemcheckbox' | 'menuitemradio' | 'navigation' | 'none' | 'note' | 'option' | 'presentation' | 'progressbar' | 'radio' | 'radiogroup' | 'region' | 'row' | 'rowgroup' | 'rowheader' | 'scrollbar' | 'search' | 'searchbox' | 'separator' | 'slider' | 'spinbutton' | 'status' | 'switch' | 'tab' | 'table' | 'tablist' | 'tabpanel' | 'term' | 'textbox' | 'timer' | 'toolbar' | 'tooltip' | 'tree' | 'treegrid' | 'treeitem' | (string & {}); /** * @deprecated Use `ComputedFn` instead. * @public */ export declare type AsyncFn = ComputedFn; /** @deprecated Use `ComputeQRL` instead. */ declare type AsyncQRL = ComputeQRL; /** * An AsyncSignal holds the result of the given async function. If the function uses `track()` to * track reactive state, and that state changes, the AsyncSignal is recalculated, and if the result * changed, all tasks which are tracking the AsyncSignal will be re-run and all subscribers * (components, tasks etc) that read the AsyncSignal will be updated. * * If the value has not yet been resolved, reading the AsyncSignal will throw a Promise, which will * retry the component or task once the value resolves. * * If the value has been resolved, but the async function is re-running, reading the AsyncSignal * will subscribe to it and return the last resolved value until the new value is ready. As soon as * the new value is ready, the subscribers will be updated. * * If the async function threw an error, reading the `.value` will throw that same error. * * @deprecated Use `ComputedSignal` instead, it has async support now. * @public */ export declare type AsyncSignal = ComputedSignal; declare const enum AsyncSignalFlags { EAGER_CLEANUP = 32, CLIENT_ONLY = 64, /** The compute fn is async: the async engine (jobs, loading, error) is active */ ASYNC_MODE = 512, /** Invoke the compute fn AsyncSignal-style: pass the ComputeCtx argument, no auto-tracking */ CTX_ARG = 1024 } /** * # ================================ * * AsyncSignalImpl * * # ================================ * * The async engine (jobs, loading, error) lives in ComputedSignalImpl; this subclass configures it * from options and switches the compute invocation to CTX_ARG mode: the compute fn receives the * ComputeCtx argument and tracks only via its explicit `track()` (no auto-tracking). * * @internal */ export declare class _AsyncSignalImpl extends _ComputedSignalImpl> implements AsyncSignal { constructor(container: _Container | null, fn: AsyncQRL, flags?: number, options?: AsyncSignalOptions); } /** * @deprecated Use `ComputedOptions` instead. * @public */ export declare type AsyncSignalOptions = ComputedOptions; /** * Replace given element's props with custom types and return all props specific to the element. Use * this for known props that are incorrect or missing. * * Uses Prettify so we see the special props for each element in editor hover */ declare type Augmented = Prettify & A>; /** Class for back reference to the EffectSubscription */ declare abstract class BackRef { [_EFFECT_BACK_REF]: Map | undefined; } /** @internal */ export declare const _BIGINT_PAYLOAD_REGEXP: RegExp; declare type BivariantQrlFn = { /** * Resolve the QRL of closure and invoke it. * * @param args - Closure arguments. * @returns A promise of the return value of the closure. */ bivarianceHack(...args: ARGS): Promise; }['bivarianceHack']; /** @public */ declare type Booleanish = boolean | `${boolean}`; /** @internal */ export declare const _caC: (props: CatchProps) => JSXOutput; /** @internal */ export declare const _canSerialize: (value: unknown, seen?: WeakSet) => boolean; declare type Capture = { [K in keyof HTMLElementEventMap as `capture:${K}`]?: boolean; }; /** * Legacy binding for libraries built before `_capturesObj`; their segments read `_captures[N]` from * their own copy of core, so this live binding is kept in sync. * * @deprecated Use `_capturesObj._` instead. * @internal */ export declare let _captures: Readonly | null; /** * Holder for the current captured scope during QRL invocation. This is used to provide the lexical * scope for QRL functions. It is used one time per invocation, synchronously, so it is safe to * store it in one place. * * It is an object (instead of a `let` binding) registered as a singleton, so that duplicated Qwik * modules (e.g. an externalized library and the app both bundling core) share the same holder. * Generated segment code reads captures as `_capturesObj._[N]`. * * @internal */ export declare const _capturesObj: { _: Readonly | null; }; /** @internal */ export declare const _caR: () => void; /** Renders `fallback$` instead of its children when a descendant throws. @public @experimental */ export declare const Catch: Component; /** Structured metadata about a caught error, passed to `onError$`. @public @experimental */ export declare interface CatchInfo { /** Where the caught error originated. */ phase: CatchPhase; /** * Identifies the boundary within the page. Allocated in render order and kept across a resume, so * every report from one boundary shares it — but it shifts when render order changes. */ boundaryId: string; /** * The code a production fallback shows for a server-origin error, so a user's bug report matches * your logs. An error caught during SSR reports a second, different digest if the client * re-derives it — the stacks differ. */ digest: string; } /** Identifies where an error caught by an error boundary originated. @public @experimental */ export declare const enum CatchPhase { Render = "render", Event = "event", Hook = "hook" } /** @public @experimental */ export declare interface CatchProps { /** * Rendered when a descendant throws. The error is always an `Error`, so `{error.message}` is * safe: a non-Error throw is wrapped, and production redacts server-origin errors to a generic * message plus `digest`. Client-origin errors render as thrown — their messages already live in * the browser bundle. * * Wrap `reset` in a handler — `onClick$={() => reset()}`, not `onClick$={reset}` — so it stays * wired in a streamed fallback. */ fallback$: QRL<(error: Error & { digest?: string; }, reset: QRL<() => void>) => JSXOutput>; /** * Side effect only; never affects rendering. Receives the original `Error` — a non-Error throw * arrives wrapped, with `cause` set to the raw value. * * An error caught during SSR fires again when the client re-derives it, so dedupe in your * reporter. */ onError$?: QRL<(error: Error, info: CatchInfo) => void>; } /** * Handles events for bind:checked * * @internal */ export declare function _chk(this: string | undefined, _: any, element: HTMLInputElement): void | Promise; declare const enum ChoreBits { NONE = 0, TASKS = 1, NODE_DIFF = 2, COMPONENT = 4, INLINE_COMPONENT = 8, NODE_PROPS = 16, COMPUTE = 32, CHILDREN = 64, CLEANUP = 128, RECONCILE = 256, ERROR_WRAP = 512, DIRTY_MASK = 1023 } /** * A class list can be a string, a boolean, an array, or an object. * * If it's an array, each item is a class list and they are all added. * * If it's an object, then the keys are class name strings, and the values are booleans that * determine if the class name string should be added or not. * * @public */ export declare type ClassList = string | undefined | null | false | Record | ClassList[]; /** @internal */ export declare interface ClientContainer extends _Container { document: _QDocument; element: _ContainerElement; qContainer: string; $locale$: string; qManifestHash: string; rootVNode: _ElementVNode; $forwardRefs$: Array | null; vNodeLocate(id: string | Element): _VNode; parseQRL(qrl: string): QRL; $getForwardRef$(id: number): number | string | undefined; $setRawState$(id: number, vParent: _ElementVNode | _VirtualVNode): void; } /** * Declare a Qwik component that can be used to create UI. * * Use `component$` to declare a Qwik component. A Qwik component is a special kind of component * that allows the Qwik framework to lazy load and execute the component independently of other Qwik * components as well as lazy load the component's life-cycle hooks and event handlers. * * Side note: You can also declare regular (standard JSX) components that will have standard * synchronous behavior. * * Qwik component is a facade that describes how the component should be used without forcing the * implementation of the component to be eagerly loaded. A minimum Qwik definition consists of: * * ### Example * * An example showing how to create a counter component: * * ```tsx * export interface CounterProps { * initialValue?: number; * step?: number; * } * export const Counter = component$((props: CounterProps) => { * const state = useSignal(props.initialValue || 0); * return ( *
* {state.value} * *
* ); * }); * ``` * * - `component$` is how a component gets declared. * - `{ value?: number; step?: number }` declares the public (props) interface of the component. * - `{ count: number }` declares the private (state) interface of the component. * * The above can then be used like so: * * ```tsx * export const OtherComponent = component$(() => { * return ; * }); * ``` * * See also: `component`, `useCleanup`, `onResume`, `onPause`, `useOn`, `useOnDocument`, * `useOnWindow`, `useStyles` * * @public */ export declare const component$: (onMount: OnRenderFn) => Component; /** * Type representing the Qwik component. * * `Component` is the type returned by invoking `component$`. * * ```tsx * interface MyComponentProps { * someProp: string; * } * const MyComponent: Component = component$((props: MyComponentProps) => { * return {props.someProp}; * }); * ``` * * @public */ export declare type Component = FunctionComponent>; /** @public */ export declare interface ComponentBaseProps { key?: string | number | null | undefined; 'q:slot'?: string; } declare type ComponentChildren = PROPS extends { children: any; } ? never : { children?: JSXChildren; }; /** @internal */ export declare const componentQrl: >(componentQrl: QRL>) => Component; declare type ComputeCtx = { /** * Track reactive reads so the computation re-runs when they change. Computed functions track * synchronous reads automatically, but after the first `await` the tracking context is lost, so * later reads must go through `track()`. */ readonly track: Tracker; /** * Register a cleanup callback to be called when the async computation is aborted or completed. * The next invocation will await the previous cleanup. If you do not want this, do not return a * Promise. */ cleanup: (callback: () => void | Promise) => void; /** * A lazily created AbortSignal, for interrupting the async computation when needed, e.g. when the * component is unmounted or the computation is invalidated. Pass it to `fetch` or other APIs that * support it to ensure that unnecessary work is not performed. */ readonly abortSignal: AbortSignal; /** The result of the previous computation, if any */ readonly previous: T | undefined; /** Extra info passed to `invalidate(info)` for this computation, if any. */ readonly info?: unknown; }; /** * The compute function. The context provides `track()`, `previous` (the last computed value), * `info` (the argument of the `invalidate(info)` call that triggered this computation), `cleanup()` * and `abortSignal`. Synchronous reactive state reads are tracked automatically, use `untrack()` to * read signals without tracking. Return a `Promise` (or use an `async` function) for async values. * After the first `await`, reads are no longer tracked automatically and must use `track()`. * * @public */ export declare type ComputedFn = (ctx: ComputeCtx) => ValueOrPromise; /** @public */ export declare interface ComputedOptions { serializationStrategy?: SerializationStrategy; container?: _Container; /** Like useSignal's `initial`; prevents the throw on first read when uninitialized */ initial?: Awaited | (() => Awaited); /** * Maximum number of concurrent computations. Use `0` for unlimited. * * Defaults to `1`. */ concurrency?: number; /** * When subscribers drop to 0, run cleanup in the next tick, instead of waiting for the function * inputs to change. * * Defaults to `false`, meaning cleanup happens only when inputs change. */ eagerCleanup?: boolean; /** * When true, the async computation is postponed to the browser. On SSR, the signal remains * INVALID and does not execute the function. On the client, it will compute on first read. * * Defaults to `false`. */ clientOnly?: boolean; /** * Maximum time in milliseconds to wait for the async computation to complete. If exceeded, the * computation is aborted and an error is thrown. * * If `0`, no timeout is applied. * * Defaults to `0`. */ timeout?: number; } /** @public */ export declare type ComputedReturnType = ComputedSignal>; /** * A computed signal is a signal which is calculated from other signals. When the signals change, * the computed signal is recalculated, and if the result changed, all tasks which are tracking the * signal will be re-run and all components that read the signal will be re-rendered. * * @public */ export declare interface ComputedSignal extends Signal { /** * Whether the signal is currently loading. Reading it starts a lazy computation if needed. * * @experimental */ pending: boolean; /** * The computation error, if any. Reading it starts a lazy computation if needed. While set, * reading `.value` throws the error. * * @experimental */ error: Error | undefined; /** @deprecated Use `trigger()` instead */ force(): void; /** Use this to force recalculation. */ invalidate(): void; /** * Clear the value and recompute. Unlike `invalidate()`, readers see the loading state (reads * throw the computation promise) instead of the stale value while the new value computes. */ clear(): void; /** A promise that resolves when the value is computed or rejected. */ promise(): Promise; /** Abort the current computation and run cleanups if needed. */ abort(reason?: any): void; /** * Use this to force recalculation. If you pass `info`, it will be provided to the calculation * function. */ invalidate(info?: unknown): void; } declare const enum ComputedSignalFlags { /** A direct source changed: must recompute on next read (DIRTY) */ INVALID = 1, /** The next compute must notify even from NEEDS_COMPUTATION */ SOURCE_CHANGED = 2, PRESERVE_ON_SEQ_CLEANUP = 4, /** A transitive source changed: pull sources before deciding to recompute (maybe dirty) */ CHECK = 128, /** Runtime dirty state; never serialized */ DIRTY_FLAGS = 131 } /** * A signal which is computed from other signals. * * Sync compute functions resolve synchronously and every read they perform is auto-tracked. When * the compute function turns out to be async (it returned a promise), the signal lazily switches on * the async engine — jobs, `loading`, `error` — giving it the same API as an AsyncSignal. * Auto-tracking only covers reads before the first await point (the invoke context is lost after * it); later reads must use the ComputeCtx `track()`. * * @internal */ export declare class _ComputedSignalImpl> extends _SignalImpl implements BackRef { /** * The compute function is stored here. * * Sync computed functions must be executed synchronously (because of this we need to eagerly * resolve the QRL during the mark dirty phase so that any call to it will be synchronous). */ $computeQrl$: S; $flags$: number; [_EFFECT_BACK_REF]: Map<_EffectProperty | string, _EffectSubscription> | undefined; $untrackedPending$: boolean | undefined; $untrackedError$: Error | undefined; $current$: Job | null | undefined; $jobs$: Job[] | undefined; $concurrency$: number | undefined; $timeoutMs$: number | undefined; $loadingEffects$: undefined | Set<_EffectSubscription>; $errorEffects$: undefined | Set<_EffectSubscription>; $disposed$: boolean | undefined; $computationTimeoutId$: ReturnType | undefined; $info$: unknown | undefined; $infoVersion$: number | undefined; constructor(container: _Container | null, fn: S, flags?: number, options?: ComputedOptions); /** Clear the value so readers see the loading state, then recompute. */ clear(): void; invalidate(info?: unknown): void; /** Recompute now; a thrown QRL promise retries. Async signals only resolve CHECK here. */ $pull$(): void; /** * Read the value, subscribing if in a tracking context. Triggers computation if needed. * * Setting the value will mark the signal as not loading and clear any error, and prevent any * pending computations from writing their results. * * If you want to set the value without affecting loading or error state, set `untrackedValue` * instead and make sure to trigger effects manually if needed. * * If you want to abort pending computations when setting, you have to call `abort()` manually. */ get value(): T; set value(value: T); get untrackedValue(): T; set untrackedValue(value: T); /** * Loading is true if the signal is still waiting for the promise to resolve, false if the promise * has resolved or rejected (or the compute function is synchronous). * * Accessing `.pending` will trigger computation if needed, since it's often used like * * ```ts * signal.pending ? : signal.value * ``` */ get pending(): boolean; set untrackedPending(value: boolean); get untrackedPending(): boolean; /** @deprecated Use `pending` instead */ get loading(): boolean; /** @deprecated Use `untrackedPending` instead */ get untrackedLoading(): boolean; set untrackedLoading(value: boolean); /** * The error the compute function threw or rejected with. * * Accessing .error will trigger computation if needed, since it's often used like * * ```ts * signal.error ? : signal.value * ``` */ get error(): Error | undefined; set untrackedError(value: Error | undefined); get untrackedError(): Error | undefined; $setInvalid$(allowRecalc: boolean): void; /** Abort the current computation and run cleanups if needed. */ abort(reason?: any): void; /** Schedule eager cleanup on next macro task if no subscribers remain. */ $scheduleEagerCleanup$(): void; /** Returns a promise resolves when the signal finished computing. */ promise(): Promise; /** Run the computation if needed */ $computeIfNeeded$(): void; /** * Invoke the compute fn with the ComputeCtx argument. CTX_ARG signals (createAsyncQrl, * useResource$) only track via its explicit track(). Computeds auto-track every synchronous read * instead; after the first await they must use the explicit track() too. */ $invokeComputeFn$(fn: Function, job: Job): T | Promise; /** Start an async computation (the async engine; assumes the INVALID flag is set) */ $computeAsync$(): void; $runComputation$(running: Job): Promise; /** Await the computation and publish its result, error, and loading transitions. */ $settleComputation$(running: Job, compute: () => ValueOrPromise): Promise; /** * Sets the error from the given job. We only accept errors from the current job and we ignore * AbortErrors. */ $setError$(job: Job, error: unknown): void; /** Permanently stop computations; keep this cross-package name stable. */ $dispose(): void; /** Clean computations after SSR while preserving dependencies for serialization. */ $destroy$(): Promise; private $hasSubscribers$; $requestCleanups$(job: Job, reason?: any): void; /** Run a job's cleanup callbacks, returning a promise when any of them are async. */ $runCleanupCallbacks$(job: Job): Promise | undefined; /** Clean up and trigger signal compute once complete */ $runCleanups$(job: Job): Promise | undefined; } /** * A computed signal with its pending and error state exposed. * * @internal */ export declare interface _ComputedSignalInternal extends ComputedSignal { /** * Lets you read the pending state without subscribing to `.pending` updates. It also triggers * lazy computation of the signal. * * Setting it will trigger listeners for `.pending`. */ untrackedPending: boolean; /** @deprecated Use `pending` instead */ loading: boolean; /** @deprecated Use `untrackedPending` instead */ untrackedLoading: boolean; /** * Lets you read the error state without subscribing to `.error` updates. It also triggers lazy * computation of the signal. * * Setting it will trigger listeners for `.error`. */ untrackedError: Error | undefined; } declare type ComputeQRL = _QRLInternal>; /** @internal */ export declare const _CONST_PROPS: unique symbol; /** * Effect is something which needs to happen (side-effect) due to signal value change. * * There are three types of effects: * * - `Task`: `useTask`, `useVisibleTask`, `useResource` * - `VNode` and `ISsrNode`: Either a component or `` * - `Signal2`: A derived signal which contains a computation function. */ declare type Consumer = _Task | _VNode | _SignalImpl | ISsrNode; /** @internal */ export declare interface _Container { readonly $version$: string; readonly $storeProxyMap$: ObjToProxyMap; $rootContainer$: _Container | null; $isOutOfOrderSegment$: boolean; readonly $locale$: string; readonly $getObjectById$: (id: number | string) => any; readonly $serverData$: Record; readonly $instanceHash$: string | null; $currentUniqueId$: number; $buildBase$: string | null; $renderPromise$: Promise | null; $resolveRenderPromise$: (() => void) | null; $pendingCount$: number; $checkPendingCount$(): void; handleError(err: any, $host$: _HostElement | null, phase?: CatchPhase): void; getParentHost(host: _HostElement): _HostElement | null; setContext(host: _HostElement, context: ContextId, value: T): void; resolveContext(host: _HostElement, contextId: ContextId): T | undefined; setHostProp(host: _HostElement, name: string, value: T): void; getHostProp(host: _HostElement, name: string): T | null; $appendStyle$(content: string, styleId: string, host: _HostElement, scoped: boolean): void; /** * When component is about to be executed, it may add/remove children. This can cause problems * with the projection because deleting content will prevent the projection references from * looking up vnodes. Therefore before we execute the component we need to ensure that all of its * references to vnode are resolved. * * @param renderHost - Host element to ensure projection is resolved. */ ensureProjectionResolved(host: _HostElement): void; } declare const enum ContainerDataProcessState { NotStarted = 0, ProcessingVNode = 1, ProcessingState = 2, ProcessingStateDone = 3 } /** @internal */ export declare interface _ContainerElement extends HTMLElement { qContainer?: ClientContainer; /** * Map of element ID to Element. If VNodeData has a reference to an element, then it is added to * this map for later retrieval. * * Once retrieved the element is replaced with its VNode. * * NOTE: This map leaks memory! Once the application is resumed we don't know which element IDs * are still in the deserialized state. we will probably need a GC cycle. Some process running in * the idle time which processes few elements at a time to see if they are still referenced and * removes them from the map if they are not. */ qVNodeRefs?: Map; /** String from `; * }); * ``` * * The `nonce` is read on the server while the component renders. Server data is not serialized, so * values like `nonce` or `url` are not available after the app resumes in the browser: copy * anything the client needs into a store, a signal or a context during SSR. * * It isn't meant for `routeLoader$`, `onStaticGenerate` or other code that runs outside rendering; * use module-scoped data or `requestEvent.sharedMap` there instead. * * @param key - The `serverData` key to read. * @returns The value for `key`, or `undefined` when it isn't set. * @public */ export declare function useServerData(key: string): T | undefined; /** * Reads a value from the `serverData` passed to the server render, or returns `defaultValue` when * it isn't set. * * @param key - The `serverData` key to read. * @param defaultValue - Returned when `key` has no value. * @public */ export declare function useServerData(key: string, defaultValue: B): T | B; /** @public */ export declare interface UseSignal { (): Signal; (value: T | (() => T)): Signal; } /** * Creates an object with a single reactive `.value` property, that Qwik can track across * serializations. * * Use it to create state for your application. The object has a getter and setter to track reads * and writes of the `.value` property. When the value changes, any functions that read from it will * re-run. * * Prefer `useSignal` over `useStore` when possible, as it is more efficient. * * ### Example * * ```tsx * const Signals = component$(() => { * const counter = useSignal(1); * const text = useSignal('changeme'); * const toggle = useSignal(false); * * // useSignal() can also accept a function to calculate the initial value * const state = useSignal(() => { * return expensiveInitialValue(); * }); * * return ( *
* * { * // pass signal values as the value, the optimizer will make it pass the signal * } * * { * // signals can be bound to inputs. A property named `bind:x` implies that the property * is a signal * } * * *
* ); * }); * ``` * * @public */ export declare const useSignal: UseSignal; /** * Creates a reactive object that Qwik can track across serialization. * * Use it to create state for your application. The returned object is a Proxy that tracks reads and * writes. When any of the properties change, the functions that read those properties will re-run. * * `Store`s are deep by default, meaning that any objects assigned to properties will also become * `Store`s. This includes arrays. * * Prefer `useSignal` over `useStore` when possible, as it is more efficient. * * ### Example * * Example showing how `useStore` is used in Counter example to keep track of the count. * * ```tsx * const Stores = component$(() => { * const counter = useCounter(1); * * // Reactivity happens even for nested objects and arrays * const userData = useStore({ * name: 'Manu', * address: { * address: '', * city: '', * }, * orgs: [], * }); * * // useStore() can also accept a function to calculate the initial value * const state = useStore(() => { * return { * value: expensiveInitialValue(), * }; * }); * * return ( *
*
Counter: {counter.value}
* *
* ); * }); * * function useCounter(step: number) { * // Multiple stores can be created in custom hooks for convenience and composability * const counterStore = useStore({ * value: 0, * }); * useVisibleTask$(() => { * // Only runs in the client * const timer = setInterval(() => { * counterStore.value += step; * }, 500); * return () => { * clearInterval(timer); * }; * }); * return counterStore; * } * ``` * * @public */ export declare const useStore: (initialState: STATE | (() => STATE), opts?: UseStoreOptions) => STATE; /** @public */ export declare interface UseStoreOptions { /** If `true` then all nested objects and arrays will be tracked as well. Default is `true`. */ deep?: boolean; /** If `false` then the object will not be tracked for changes. Default is `true`. */ reactive?: boolean; } /** * A lazy-loadable reference to a component's styles. * * Component styles allow Qwik to lazy load the style information for the component only when * needed. (And avoid double loading it in case of SSR hydration.) * * ```tsx * import styles from './code-block.css?inline'; * * export const CmpStyles = component$(() => { * useStyles$(styles); * * return
Some text
; * }); * ``` * * @public * @see `useStylesScoped` */ export declare const useStyles$: (qrl: string) => UseStyles; /** @public */ declare interface UseStyles { styleId: string; } /** @internal */ export declare const useStylesQrl: (styles: QRL) => UseStyles; /** * A lazy-loadable reference to a component's styles, that is scoped to the component. * * Component styles allow Qwik to lazy load the style information for the component only when * needed. (And avoid double loading it in case of SSR hydration.) * * ```tsx * import scoped from './code-block.css?inline'; * * export const CmpScopedStyles = component$(() => { * useStylesScoped$(scoped); * * return
Some text
; * }); * ``` * * @public * @see `useStyles` */ export declare const useStylesScoped$: (qrl: string) => UseStylesScoped; /** @public */ export declare interface UseStylesScoped { scopeId: string; } /** @internal */ export declare const useStylesScopedQrl: (styles: QRL) => UseStylesScoped; /** * Reruns the `taskFn` when the observed inputs change. * * Use `useTask` to observe changes on a set of inputs, and then re-execute the `taskFn` when those * inputs change. * * The `taskFn` only executes if the observed inputs change. To observe the inputs, use the `obs` * function to wrap property reads. This creates subscriptions that will trigger the `taskFn` to * rerun. * * Cleanup callbacks registered with `cleanup()` or returned from the task may be async. When a task * reruns, Qwik waits for the previous cleanup to finish before starting the next invocation. * * During SSR, the cleanup function is called immediately after SSR completes. Therefore, it is not * called on the client side after resuming, but only the second time the task runs on the client. * * @param task - Function which should be re-executed when changes to the inputs are detected * @public * * ### Example * * The `useTask` function is used to observe the `store.count` property. Any changes to the * `store.count` cause the `taskFn` to execute which in turn updates the `store.doubleCount` to * the double of `store.count`. * * ```tsx * const Cmp = component$(() => { * const store = useStore({ * count: 0, * doubleCount: 0, * debounced: 0, * }); * * // Double count task * useTask$(({ track }) => { * const count = track(() => store.count); * store.doubleCount = 2 * count; * }); * * // Debouncer task * useTask$(({ track }) => { * const doubleCount = track(() => store.doubleCount); * const timer = setTimeout(() => { * store.debounced = doubleCount; * }, 2000); * return () => { * clearTimeout(timer); * }; * }); * return ( *
*
* {store.count} / {store.doubleCount} *
*
{store.debounced}
*
* ); * }); * ``` * * @public * @see `Tracker` */ export declare const useTask$: (fn: TaskFn, opts?: TaskOptions) => void; /** @internal */ export declare const useTaskQrl: (qrl: QRL, opts?: TaskOptions) => void; /** * ```tsx * const Timer = component$(() => { * const store = useStore({ * count: 0, * }); * * useVisibleTask$(() => { * // Only runs in the client * const timer = setInterval(() => { * store.count++; * }, 500); * return () => { * clearInterval(timer); * }; * }); * * return
{store.count}
; * }); * ``` * * Visible Tasks are a variant of Tasks that only run in the browser, and are registered but not * executed during SSR. They are useful for running code that should only execute in the browser, * such as code that interacts with the DOM or browser APIs. * * Cleanup callbacks registered with `cleanup()` or returned from the task may be async. When a * visible task reruns, Qwik waits for the previous cleanup to finish before starting the next * invocation. * * @public */ export declare const useVisibleTask$: (fn: TaskFn, opts?: OnVisibleTaskOptions) => void; /** @internal */ export declare const useVisibleTaskQrl: (qrl: QRL, opts?: OnVisibleTaskOptions) => void; /** * Handles events for bind:value * * @internal */ export declare function _val(this: string | undefined, _: any, element: HTMLInputElement): void | Promise; /** * Type representing a value which is either resolve or a promise. * * @public */ export declare type ValueOrPromise = T | Promise; /** @internal */ export declare const _VAR_PROPS: unique symbol; /** @internal */ export declare const _verifySerializable: (value: T, preMessage?: string) => T; /** * 2.0.0-rc.5-dev+f1a7e6b * * @public */ export declare const version: string; /** @internal */ export declare class _VirtualVNode extends _VNode { key: string | null; firstChild: _VNode | null | undefined; lastChild: _VNode | null | undefined; constructor(key: string | null, flags: _VNodeFlags, parent: _ElementVNode | _VirtualVNode | null, previousSibling: _VNode | null | undefined, nextSibling: _VNode | null | undefined, props: Props | null, firstChild: _VNode | null | undefined, lastChild: _VNode | null | undefined); } /** @public */ export declare type VisibleTaskStrategy = 'intersection-observer' | 'document-ready' | 'document-idle'; /** @internal */ export declare abstract class _VNode implements BackRef { flags: _VNodeFlags; parent: _VNode | null; previousSibling: _VNode | null | undefined; nextSibling: _VNode | null | undefined; props: Props | null; [_EFFECT_BACK_REF]: Map | undefined; slotParent: _VNode | null; dirty: ChoreBits; dirtyChildren: _VNode[] | null; nextDirtyChildIndex: number; constructor(flags: _VNodeFlags, parent: _VNode | null, previousSibling: _VNode | null | undefined, nextSibling: _VNode | null | undefined, props: Props | null); toString(): string; } /** @internal */ export declare const _vnode_ensureElementInflated: (container: _Container, vnode: _VNode) => void; /** @internal */ export declare const _vnode_getAttrKeys: (container: _Container, vnode: _ElementVNode | _VirtualVNode) => string[]; /** @internal */ export declare const _vnode_getElementName: (vnode: _ElementVNode) => string; /** @internal */ export declare const _vnode_getFirstChild: (vnode: _VNode) => _VNode | null; /** @internal */ export declare const _vnode_getProp: (vNode: _VNode, key: string, getObject: ((id: string) => unknown) | null) => T | null; /** @internal */ export declare const _vnode_getVNodeForChildNode: (vNode: _ElementVNode, childElement: Element) => _ElementVNode; /** @internal */ export declare const _vnode_insertBefore: (journal: _VNodeJournal, parent: _ElementVNode | _VirtualVNode, newChild: _VNode, insertBefore: _VNode | null) => void; /** @internal */ export declare const _vnode_isElementVNode: (vNode: _VNode) => vNode is _ElementVNode; /** @internal */ export declare const _vnode_isMaterialized: (vNode: _VNode) => boolean; /** @internal */ export declare const _vnode_isTextVNode: (vNode: _VNode) => vNode is _TextVNode; /** @internal */ export declare const _vnode_isVirtualVNode: (vNode: _VNode) => vNode is _VirtualVNode; /** @internal */ export declare const _vnode_isVNode: (vNode: any) => vNode is _VNode; /** @internal */ export declare const _vnode_newVirtual: () => _VirtualVNode; /** @internal */ export declare const _vnode_remove: (journal: _VNodeJournal, vParent: _ElementVNode | _VirtualVNode, vToRemove: _VNode, removeDOM: boolean) => void; /** @internal */ export declare const _vnode_setProp: (vNode: _VNode, key: string, value: unknown) => void; /** @internal */ export declare function _vnode_toString(this: _VNode | null, depth?: number, offset?: string, materialize?: boolean, siblings?: boolean, colorize?: boolean, container?: _Container | null): string; /** * Array of numbers which describes virtual nodes in the tree. * * HTML can't account for: * * - Multiple text nodes in a row. (it treats it as a single text node) * - Empty text nodes. (it ignores them) * - And virtual nodes such as `` or `` * * So we need to encode all of that information into the VNodeData. * * Encoding: * * - First position is special and encodes state information and stores VNodeDataFlag. * - Positive numbers are text node lengths. (0 is a special case for empty text node) * - Negative numbers are element counts. * - `OPEN_FRAGMENT` is start of virtual node. * * - If `OPEN_FRAGMENT` than the previous node is an `Array` which contains the props (see * `SsrAttrs`). NOTE: The array is never going to be the last item in the VNodeData, so we can * always assume that the last item in `vNodeData` is a number. * - `CLOSE_FRAGMENT` is end of virtual node. * * NOTE: This is how we store the information during the SSR streaming, once the SSR is complete * this data needs to be serialized into a string and stored in the DOM as a script tag which has * deferent serialization format. */ declare type VNodeData = [VNodeDataFlag, ...(Props | number)[]]; /** * Flags for VNodeData (Flags con be bitwise combined) * * @internal */ declare const enum VNodeDataFlag { NONE = 0, TEXT_DATA = 1, VIRTUAL_NODE = 2, ELEMENT_NODE = 4, REFERENCE = 8, SERIALIZE = 16, INERT = 32 } /** * Flags for VNode. * * # Materialize vs Inflation * * - Materialized: The node has all of its children. Specifically `firstChild`/`lastChild` are NOT * `undefined`. Materialization creates lazy instantiation of the children. NOTE: Only * ElementVNode need to be materialized. * - Inflation: * * - If Text: It means that it is safe to write to the node. When Text nodes are first Deserialized * multiple text nodes can share the same DOM node. On write the sibling text nodes need to be * converted into separate text nodes. * - If Element: It means that the element tag attributes have not yet been read from the DOM. * * Inflation and materialization are not the same, they are two independent things. * * @internal */ export declare const enum _VNodeFlags { Element = 1, Virtual = 2, ELEMENT_OR_VIRTUAL_MASK = 3, Text = 4, ELEMENT_OR_TEXT_MASK = 5, TYPE_MASK = 7, INFLATED_TYPE_MASK = 15, Inflated = 8, Resolved = 16, Deleted = 32, HasIterationItems = 64, InflatedIterationItems = 128, Cursor = 256, NAMESPACE_MASK = 1536, NEGATED_NAMESPACE_MASK = -1537, NS_html = 0,// http://www.w3.org/1999/xhtml NS_svg = 512,// http://www.w3.org/2000/svg NS_math = 1024,// http://www.w3.org/1998/Math/MathML HasTargetElement = 2048 } /** @internal */ export declare type _VNodeJournal = Array; declare type VNodeOperation = DeleteOperation | RemoveAllChildrenOperation | SetTextOperation | InsertOrMoveOperation | SetAttributeOperation; /** @internal */ export declare const _waitOn: (promise: Promise) => void; /** @internal */ export declare const _waitUntilRendered: (container: _Container) => Promise; /** @internal */ export declare function _walkJSX(ssr: SSRContainer, value: JSXOutput, options: SSRRenderJSXOptions): Promise; /** @internal */ export declare const _whenContainerDataReady: (container: ClientContainer, callback: () => T | Promise) => T | Promise; /** * Override the `getLocale` with `lang` within the `fn` execution. * * `fn` may be async. The locale stays set until the returned promise settles, even when * AsyncLocalStorage is not available. * * @public */ export declare function withLocale(locale: string, fn: () => T): T; declare type WrappedProp = T extends Signal ? _WrappedSignalImpl> : PropType; /** @internal */ export declare class _WrappedSignalImpl extends _SignalImpl { $args$: any[]; $func$: (...args: any[]) => T; $funcStr$: string | null; $flags$: AllSignalFlags; $hostElement$: _HostElement | undefined; [_EFFECT_BACK_REF]: Map<_EffectProperty | string, _EffectSubscription> | undefined; constructor(container: _Container | null, fn: (...args: any[]) => T, args: any[], fnStr: string | null, flags?: AllSignalFlags); invalidate(): void; /** * Recompute now; when that throws (e.g. a lazy QRL), defer to a COMPUTE chore on the host. A * signal without a host (e.g. a component prop) retries once the promise settles instead, so it * is not left in CHECK with its sources unsubscribed. */ $pull$(): void; get untrackedValue(): T; $computeIfNeeded$(): void; $unwrapIfSignal$(): _SignalImpl | _WrappedSignalImpl; set value(_: any); get value(): any; } /** * This wraps a property access of a possible Signal/Store into a WrappedSignal. The optimizer does * this automatically when a prop is only used as a prop on JSX. * * When a WrappedSignal is read via the PropsProxy, it will be unwrapped. This allows forwarding the * reactivity of a prop to the point of actual use. * * For efficiency, if you pass only one argument, the property is 'value'. * * @internal */ export declare const _wrapProp: (...args: [T, P?]) => WrappedProp; /** @internal @deprecated v1 compat */ export declare const _wrapSignal: (obj: T, prop: P) => T[P] | WrappedProp; export { }