/* tslint:disable */
/* eslint-disable */

/**
 * The main Hypen engine interface for JavaScript/WASM runtimes.
 *
 * `WasmEngine` manages the full lifecycle of a Hypen UI: parsing DSL source,
 * maintaining the virtual tree, tracking reactive dependencies, and emitting
 * minimal patches when state changes. It runs in a single-threaded WASM
 * environment (browsers, Node.js, Bun, Deno).
 *
 * # Quick Start
 *
 * ```js
 * import { WasmEngine } from "@hypen-space/core";
 *
 * const engine = new WasmEngine();
 *
 * // 1. Register primitives so the engine doesn't try to resolve them as components
 * engine.registerPrimitive("Text");
 * engine.registerPrimitive("Column");
 *
 * // 2. Receive patches via callback
 * engine.setRenderCallback((patches) => {
 *     for (const patch of patches) {
 *         applyPatch(patch); // Create, SetProp, Insert, Remove, etc.
 *     }
 * });
 *
 * // 3. Optionally set up a module for stateful UI
 * engine.setModule("Counter", ["increment"], ["count"], { count: 0 });
 *
 * // 4. Render DSL source — patches are emitted via the callback
 * engine.renderSource('Column { Text("Count: ${state.count}") }');
 *
 * // 5. Update state — only affected nodes are re-rendered
 * engine.updateState({ count: 1 });
 * ```
 *
 * # Patch Protocol
 *
 * All UI mutations are expressed as [`Patch`] values emitted through the render
 * callback. Patches use camelCase field names for direct JavaScript consumption.
 * See [`Patch`] for the full variant list and field documentation.
 *
 * # Component Resolution
 *
 * Custom components (anything not registered as a primitive) are resolved lazily
 * via the component resolver callback set with [`set_component_resolver`]. The
 * resolver receives `(componentName, contextPath)` and should return
 * `{ source: string, path: string }` or `null`.
 *
 * # Revision Tracking
 *
 * Every render cycle (initial render or state update that produces patches)
 * increments the revision counter. Use [`get_revision`] to detect stale state
 * in async workflows.
 */
export class WasmEngine {
    free(): void;
    [Symbol.dispose](): void;
    /**
     * Remove all nodes from the instance tree without emitting Remove patches.
     *
     * Use this when tearing down the UI entirely (e.g. navigating away or
     * switching samples). The renderer is responsible for clearing its own
     * DOM/canvas state separately.
     */
    clearTree(): void;
    /**
     * Return a JSON snapshot of the active module's current state.
     *
     * Returns `null` (as a `JsValue`) if no module is set.
     * Useful for debugging and DevTools integration.
     */
    currentState(): any;
    /**
     * Parse a component and return a human-readable debug string.
     *
     * Intended for development tooling only — the output format is not stable.
     */
    debugParseComponent(source: string): string;
    /**
     * Dispatch a named action, invoking the registered handler (if any).
     *
     * Actions are the primary way UI events flow from the renderer back to
     * application logic. In Hypen DSL, buttons reference actions like
     * `Button("@actions.submit")` — the renderer maps clicks to
     * `engine.dispatchAction("submit", payload)`.
     *
     * # Arguments
     * * `name` — Action name (e.g. `"submit"`, `"increment"`)
     * * `payload` — Optional JS value passed to the handler. `null`/`undefined` are treated as no payload.
     *
     * # Errors
     *
     * Returns an error if the payload cannot be deserialized. Does **not** error
     * if no handler is registered (the action is silently dropped).
     */
    dispatchAction(name: string, payload: any): void;
    /**
     * Get the current revision number.
     *
     * Starts at 0 and increments by 1 for each render cycle that produces
     * patches. Useful for cache invalidation and detecting stale async results.
     */
    getRevision(): bigint;
    /**
     * Create a new engine instance with an empty tree and no module.
     *
     * After construction, you typically:
     * 1. Register primitives with [`register_primitive`]
     * 2. Set a render callback with [`set_render_callback`]
     * 3. Optionally set a component resolver with [`set_component_resolver`]
     * 4. Optionally initialize a module with [`set_module`]
     * 5. Render source with [`render_source`]
     */
    constructor();
    /**
     * Register a JavaScript function as the handler for a named action.
     *
     * When [`dispatch_action`] is called with a matching name, the handler
     * receives a serialized [`Action`] object with `{ name, payload }`.
     *
     * Registering a handler for the same name replaces the previous one.
     */
    onAction(action_name: string, handler: Function): void;
    /**
     * Register a handler for data source actions.
     *
     * When [`dispatch_action`] is called with a name like `"spacetime.sendMessage"`
     * and no explicit action handler is registered for that name, the engine checks
     * if the prefix (`"spacetime"`) is a registered data source. If so, it calls
     * this handler with `{ provider, method, payload }`.
     *
     * This enables `@actions.spacetime.sendMessage` in DSL to automatically route
     * to the appropriate data source plugin without manual handler registration.
     */
    onDataSourceAction(handler: Function): void;
    /**
     * Register a primitive element (like Text, Button, etc.) to skip component resolution
     * This prevents unnecessary resolver calls for built-in DOM elements
     */
    registerPrimitive(name: string): void;
    /**
     * Remove a data source context entirely.
     *
     * Drops the provider's state and re-renders bound nodes (they resolve to `null`).
     */
    removeContext(name: string): void;
    /**
     * Render a component into a specific parent node (subtree rendering)
     * This is used for lazy routing where components are rendered on-demand into route containers
     *
     * # Arguments
     * * `source` - The Hypen DSL source to parse and render
     * * `parent_node_id_str` - The serialized node ID string of the parent element
     * * `state_js` - The state to use for rendering (as JsValue)
     */
    renderInto(source: string, parent_node_id_str: string, state_js: any): void;
    /**
     * Render a component source on-demand (for lazy-loaded routes).
     *
     * Equivalent to calling [`render_source`] — the source is parsed as a full
     * document and replaces the current tree.
     */
    renderLazyComponent(source: string): void;
    /**
     * Parse and render Hypen DSL source code, emitting patches via the render callback.
     *
     * Supports full document syntax including `import` statements. Imports are
     * resolved synchronously through the component resolver callback (if set).
     *
     * This performs a **full reconciliation** — the existing tree is diffed against
     * the new IR and minimal patches are emitted. Calling this multiple times with
     * different source replaces the previous UI.
     *
     * # Errors
     *
     * Returns a `JsValue` string error if the source fails to parse.
     */
    renderSource(source: string): void;
    /**
     * Fully reset the engine to its initial empty state.
     *
     * Clears the tree, module, dependencies, scheduler, action handlers,
     * component registry, and resets the revision to 0. The render callback
     * and component resolver are preserved.
     */
    reset(): void;
    /**
     * Set the component resolver callback
     * The resolver receives (componentName, contextPath) and should return
     * { source: string, path: string } or null
     *
     * contextPath is the path of the component that's referencing this component
     * The returned path should be the resolved absolute path to the component file
     */
    setComponentResolver(resolver: Function): void;
    /**
     * Set (or replace) a named data source context.
     *
     * Registers the provider in the dependency graph (if not already known),
     * stores the data, and re-renders every node bound to `$name.*`.
     * Sparse merging (if needed) should happen at the SDK layer before
     * calling this method with the merged object.
     *
     * # Example (JS)
     * ```js
     * engine.setContext("spacetime", {
     *     message: [{ id: 1, text: "Hello" }, { id: 2, text: "World" }],
     *     user: [{ id: 1, name: "Alice", online: true }]
     * });
     * ```
     */
    setContext(name: string, data_js: any): void;
    /**
     * Initialize (or replace) the active module with the given configuration.
     *
     * A module provides stateful context for `${state.xxx}` bindings in the DSL.
     * Only one module is active at a time — calling this again replaces it.
     *
     * # Arguments
     * * `name` — Module identifier (e.g. `"Counter"`, `"ProfilePage"`)
     * * `actions` — List of action names this module handles
     * * `state_keys` — List of top-level state keys (used for validation)
     * * `initial_state` — The starting state as a JS object
     *
     * # Errors
     *
     * Returns an error if `initial_state` cannot be deserialized as JSON.
     */
    setModule(name: string, actions: string[], state_keys: string[], initial_state: any): void;
    /**
     * Set the callback that receives UI patches after each render cycle.
     *
     * The callback is invoked with a single argument: a JavaScript array of
     * [`Patch`] objects. Each patch describes one atomic DOM operation (Create,
     * SetProp, SetText, Insert, Move, Remove, RemoveProp).
     *
     * The callback is called synchronously during `renderSource()`, `updateState()`,
     * `updateStateSparse()`, and `renderInto()`.
     *
     * # Example (JS)
     * ```js
     * engine.setRenderCallback((patches) => {
     *     for (const p of patches) {
     *         switch (p.type) {
     *             case "create": createElement(p.id, p.elementType, p.props); break;
     *             case "setProp": setProperty(p.id, p.name, p.value); break;
     *             case "insert": insertChild(p.parentId, p.id, p.beforeId); break;
     *             // ...
     *         }
     *     }
     * });
     * ```
     */
    setRenderCallback(callback: Function): void;
    /**
     * Return the total number of nodes currently in the instance tree.
     *
     * Useful for debugging, performance monitoring, and DevTools.
     */
    treeSize(): number;
    /**
     * Apply a state patch and re-render affected nodes.
     *
     * The `state_patch` is a JavaScript object whose keys are merged into the
     * current module state (deep merge). Only nodes whose bindings reference
     * changed paths are re-rendered, producing minimal patches.
     *
     * # Example (JS)
     * ```js
     * // Updates state.user.name and state.count, re-renders bound nodes
     * engine.updateState({ user: { name: "Bob" }, count: 42 });
     * ```
     *
     * # Errors
     *
     * Returns an error if `state_patch` cannot be deserialized as JSON.
     */
    updateState(state_patch: any): void;
    /**
     * Apply a sparse state update using explicit path-value pairs.
     *
     * More efficient than [`update_state`] for large state objects when only a
     * few deeply-nested paths changed, because it avoids a full deep-merge.
     *
     * # Arguments
     * * `paths_js` — JS array of dot-separated paths that changed (e.g. `["user.name", "count"]`)
     * * `values_js` — JS object mapping each path to its new value (e.g. `{ "user.name": "Bob", "count": 42 }`)
     *
     * # Errors
     *
     * Returns an error if either argument cannot be deserialized.
     */
    updateStateSparse(paths_js: any, values_js: any): void;
    /**
     * Validate that the engine is in a consistent state.
     *
     * Checks that:
     * - All child references point to existing nodes
     * - All parent back-references are correct
     * - The root node (if any) exists in the tree
     *
     * Returns `null` if valid, or a string describing the first inconsistency found.
     * Intended for testing and debugging only — not for production hot paths.
     */
    validate(): any;
}

export function main(): void;

/**
 * Parse Hypen DSL source and return the AST as a pretty-printed JSON string.
 *
 * Useful for tooling, syntax highlighting, and debugging the parser output.
 */
export function parseToJson(source: string): string;

/**
 * Serialize a patches array to a pretty-printed JSON string.
 *
 * Intended for debugging and logging — not for production use.
 * Accepts a JS array of patch objects and returns formatted JSON.
 */
export function patchesToJson(patches: any): string;

export type InitInput = RequestInfo | URL | Response | BufferSource | WebAssembly.Module;

export interface InitOutput {
    readonly memory: WebAssembly.Memory;
    readonly __wbg_wasmengine_free: (a: number, b: number) => void;
    readonly main: () => void;
    readonly parseToJson: (a: number, b: number) => [number, number, number, number];
    readonly patchesToJson: (a: any) => [number, number, number, number];
    readonly wasmengine_clearTree: (a: number) => void;
    readonly wasmengine_currentState: (a: number) => any;
    readonly wasmengine_debugParseComponent: (a: number, b: number, c: number) => [number, number, number, number];
    readonly wasmengine_dispatchAction: (a: number, b: number, c: number, d: any) => [number, number];
    readonly wasmengine_getRevision: (a: number) => bigint;
    readonly wasmengine_new: () => number;
    readonly wasmengine_onAction: (a: number, b: number, c: number, d: any) => void;
    readonly wasmengine_onDataSourceAction: (a: number, b: any) => void;
    readonly wasmengine_registerPrimitive: (a: number, b: number, c: number) => void;
    readonly wasmengine_removeContext: (a: number, b: number, c: number) => void;
    readonly wasmengine_renderInto: (a: number, b: number, c: number, d: number, e: number, f: any) => [number, number];
    readonly wasmengine_renderLazyComponent: (a: number, b: number, c: number) => [number, number];
    readonly wasmengine_reset: (a: number) => void;
    readonly wasmengine_setComponentResolver: (a: number, b: any) => void;
    readonly wasmengine_setContext: (a: number, b: number, c: number, d: any) => [number, number];
    readonly wasmengine_setModule: (a: number, b: number, c: number, d: number, e: number, f: number, g: number, h: any) => [number, number];
    readonly wasmengine_setRenderCallback: (a: number, b: any) => void;
    readonly wasmengine_treeSize: (a: number) => number;
    readonly wasmengine_updateState: (a: number, b: any) => [number, number];
    readonly wasmengine_updateStateSparse: (a: number, b: any, c: any) => [number, number];
    readonly wasmengine_validate: (a: number) => any;
    readonly wasmengine_renderSource: (a: number, b: number, c: number) => [number, number];
    readonly __wbindgen_malloc: (a: number, b: number) => number;
    readonly __wbindgen_realloc: (a: number, b: number, c: number, d: number) => number;
    readonly __wbindgen_exn_store: (a: number) => void;
    readonly __externref_table_alloc: () => number;
    readonly __wbindgen_externrefs: WebAssembly.Table;
    readonly __externref_table_dealloc: (a: number) => void;
    readonly __wbindgen_free: (a: number, b: number, c: number) => void;
    readonly __wbindgen_start: () => void;
}

export type SyncInitInput = BufferSource | WebAssembly.Module;

/**
 * Instantiates the given `module`, which can either be bytes or
 * a precompiled `WebAssembly.Module`.
 *
 * @param {{ module: SyncInitInput }} module - Passing `SyncInitInput` directly is deprecated.
 *
 * @returns {InitOutput}
 */
export function initSync(module: { module: SyncInitInput } | SyncInitInput): InitOutput;

/**
 * If `module_or_path` is {RequestInfo} or {URL}, makes a request and
 * for everything else, calls `WebAssembly.instantiate` directly.
 *
 * @param {{ module_or_path: InitInput | Promise<InitInput> }} module_or_path - Passing `InitInput` directly is deprecated.
 *
 * @returns {Promise<InitOutput>}
 */
export default function __wbg_init (module_or_path?: { module_or_path: InitInput | Promise<InitInput> } | InitInput | Promise<InitInput>): Promise<InitOutput>;
