{"version":3,"file":"runtime.cjs","names":[],"sources":["../src/runtime.ts"],"sourcesContent":["/**\n * Component runtime — implicit \"current component\" context plus every lifecycle\n * hook a `setup()` function can call.\n *\n * Design note: hooks are plain module-level functions (not a bag/context object\n * passed into `setup`). They resolve the active component through a single\n * module-level pointer (`currentContext`), set for the duration of `setup()` and\n * of each queued `onMounted` callback. This is the same mechanism React/Vue/Solid\n * use for their composable hooks — it lets any helper function (not just the\n * top-level `setup()` body) call `onMounted`/`onCleanup`/`bind`/... directly,\n * with no context object to thread through every layer of a composable.\n */\nimport { effect as _effect, type Cleanup, type Readable } from '@vielzeug/ripple';\n\nimport { ORE_ERRORS, OreApiError } from './errors';\nimport { listen as listenInternal } from './utils/dom';\n\n// ─── Runtime context ──────────────────────────────────────────────────────────\n// A single context object carries both the host element and mount callbacks,\n// eliminating two parallel globals that were always set together.\n\nexport type OnMountedCallback = () => Cleanup | undefined;\nexport type OnFormResetCallback = () => void;\n\nexport type RuntimeContext = {\n  element: HTMLElement;\n  formResetCallbacks: OnFormResetCallback[];\n  mountCallbacks: OnMountedCallback[];\n};\n\nlet currentContext: RuntimeContext | null = null;\n\n/**\n * @internal Create a fresh runtime context for a component element. The single\n * construction site for `RuntimeContext` — used by `BaseElement` (setup and\n * per-callback mount contexts) and by `testing/render-hook.ts`, so the test\n * harness can never silently desync from a new required field.\n */\nexport const createRuntimeContext = (element: HTMLElement): RuntimeContext => ({\n  element,\n  formResetCallbacks: [],\n  mountCallbacks: [],\n});\n\n// ─── Pending work tracking ──────────────────────────────────────────────────\n// A single counter of \"in-flight scheduled work\" across every live component\n// instance on the page — incremented when a mount-callback microtask is scheduled\n// (base-element.ts's _scheduleMountCallbacks()), decremented when it completes.\n//\n// Why this exists: `@vielzeug/ripple`'s reactive graph settles fully synchronously on\n// every signal write (see ripple's scheduling.ts) — there is no async flush queue to wait\n// for there. The only genuinely async work `testing/flush()` needs to wait for is ore's own\n// bounded, internal scheduling: `queueMicrotask`-scheduled onMounted callbacks.\n// `testing/flush()` polls `hasPendingWork()` to know precisely when that work has\n// settled, instead of draining a fixed, guessed number of microtask turns.\nlet pendingWork = 0;\n\n/**\n * @internal Mark one scheduled mount-callback microtask as started. Call the\n * returned function exactly once when it completes.\n */\nexport const beginPendingWork = (): (() => void) => {\n  pendingWork++;\n\n  let ended = false;\n\n  return () => {\n    if (ended) return;\n\n    ended = true;\n    pendingWork--;\n  };\n};\n\n/** @internal True while any tracked component work is in flight. Polled by `testing/flush()`. */\nexport const hasPendingWork = (): boolean => pendingWork > 0;\n\n/** @internal Execute fn with a given runtime context active. */\nexport const runWithContext = <T>(ctx: RuntimeContext, fn: () => T): T => {\n  const prev = currentContext;\n\n  currentContext = ctx;\n\n  try {\n    return fn();\n  } finally {\n    currentContext = prev;\n  }\n};\n\n/**\n * Returns the current runtime context, throwing a consistently-worded error\n * (naming the calling API) if called outside `setup()`. Every lifecycle/context\n * hook below routes through this — it's the single place that decides both\n * \"are we inside setup?\" and what the resulting error looks like, so the error\n * message is never worse for one hook than another.\n * @internal\n */\nexport const requireSetupContext = (api: string): RuntimeContext => {\n  if (currentContext) return currentContext;\n\n  throw new OreApiError(`${api}: ${ORE_ERRORS.lifecycleOutsideSetup}`);\n};\n\n/**\n * Returns the current component's host element.\n * Only valid synchronously during component `setup()` (or inside a composable\n * called from it) — throws otherwise.\n */\nexport const getHost = (): HTMLElement => requireSetupContext('getHost').element;\n\nexport const tryRegisterCleanup = (fn: Cleanup): boolean => {\n  if (!currentContext) return false;\n\n  _effect(() => fn);\n\n  return true;\n};\n\n/** Registers cleanup work for component disconnect. */\nexport const onCleanup = (fn: Cleanup): void => {\n  if (!tryRegisterCleanup(fn)) throw new OreApiError(`onCleanup: ${ORE_ERRORS.lifecycleOutsideSetup}`);\n};\n\n/**\n * Register work to run after the component template mounts to the DOM.\n * Multiple callbacks run in registration order.\n */\nexport const onMounted = (fn: OnMountedCallback): void => {\n  requireSetupContext('onMounted').mountCallbacks.push(fn);\n};\n\n/**\n * Register work to run when the ancestor `<form>` is reset (native `formResetCallback`,\n * only fires for `formAssociated: true` components). Multiple callbacks run in\n * registration order, every time the form resets — unlike `onMounted`, this isn't a\n * one-shot hook.\n */\nexport const onFormReset = (fn: OnFormResetCallback): void => {\n  requireSetupContext('onFormReset').formResetCallbacks.push(fn);\n};\n\n/**\n * Create a reactive effect scoped to the component lifecycle.\n * Automatically cleaned up on component disconnect.\n * Returns a stop function that disposes the effect immediately.\n *\n * Named `watchEffect` (not `watch`) to avoid shadowing `@vielzeug/ripple`'s\n * `watch(source, callback)`, which has different semantics (explicit source,\n * old/new value pair) — the two are commonly imported in the same file.\n */\nexport const watchEffect = (fn: () => Cleanup | undefined): (() => void) => {\n  const sub = _effect(fn);\n  const stop = (): void => sub.dispose();\n\n  tryRegisterCleanup(stop);\n\n  return stop;\n};\n\n/**\n * Attach a scoped event listener that is automatically removed on component disconnect.\n * Silently no-ops when `target` is `null` or `undefined` (safe for reactive targets).\n */\nexport function onEvent<K extends keyof HTMLElementEventMap>(\n  target: EventTarget | null | undefined,\n  event: K,\n  listener: (e: HTMLElementEventMap[K]) => void,\n  options?: AddEventListenerOptions,\n): void;\nexport function onEvent(\n  target: EventTarget | null | undefined,\n  event: string,\n  listener: EventListener,\n  options?: AddEventListenerOptions,\n): void {\n  requireSetupContext('onEvent');\n\n  if (!target) return;\n\n  const cleanup = listenInternal(target, event, listener, options);\n\n  if (!tryRegisterCleanup(cleanup)) cleanup();\n}\n\n/**\n * Watch a ref signal and run a callback when it resolves to a non-null element.\n * The callback's return value is used as a cleanup function.\n */\nexport const onElement = <T extends HTMLElement>(\n  ref: Readable<T | null>,\n  callback: (el: T) => Cleanup | undefined | undefined,\n): (() => void) => {\n  return watchEffect(() => {\n    const el = ref.value;\n\n    if (el) return callback(el);\n  });\n};\n"],"mappings":"+FA8BA,IAAI,EAAwC,KAQ/B,EAAwB,IAA0C,CAC7E,UACA,mBAAoB,CAAC,EACrB,eAAgB,CAAC,CACnB,GAaI,EAAc,EAML,MA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