{"version":3,"file":"context.cjs","names":[],"sources":["../src/context.ts"],"sourcesContent":["/**\n * Component context injection API — `inject` / `injectStrict` / `provide` / `createContext`.\n *\n * Context values are stored on the providing element via a WeakMap registry and\n * resolved by walking up the DOM tree (including through shadow boundaries).\n * Providing is done via `provide(key, value)` inside `setup()`.\n *\n * Keys are `Symbol.for`-based (see `createContext`) so provide/inject still match\n * across a duplicated module graph — the same cross-copy survival rule as the\n * object brands in `utils/brand.ts`.\n */\n\nimport { warn } from './_dev';\nimport { ORE_ERRORS, OreApiError } from './errors';\nimport { onCleanup, type RuntimeContext, requireSetupContext } from './runtime';\n\nconst contextRegistry = new WeakMap<HTMLElement, Map<InjectionKey<unknown>, unknown>>();\n\nexport type InjectionKey<T> = symbol & {\n  readonly __ore_injection_key?: T;\n};\n\n/**\n * Build a linear ancestor chain (including shadow host boundaries).\n * Walks `parentNode` (not `parentElement`) so non-HTML intermediate parents\n * (e.g. an `SVGElement` between child and provider) don't break the chain.\n */\nconst buildAncestorChain = (start: HTMLElement): HTMLElement[] => {\n  const chain: HTMLElement[] = [];\n  let node: Node | null = start;\n\n  while (node) {\n    if (node instanceof HTMLElement) chain.push(node);\n\n    // A ShadowRoot's parentNode is null — hop to its host to keep walking.\n    node = node.parentNode ?? (node instanceof ShadowRoot ? node.host : null);\n  }\n\n  return chain;\n};\n\n/**\n * Register a context value on a specific element.\n * @internal Backs the public `provide()` — do not call directly.\n */\nconst provideOnElement = <T>(el: HTMLElement, key: InjectionKey<T>, value: T): void => {\n  const map = contextRegistry.get(el) ?? new Map<InjectionKey<unknown>, unknown>();\n\n  // `inject()` memoizes its result per consumer (see resolvedCache below), so a\n  // provider swapping the raw value after a descendant already read it would be\n  // silently ignored downstream. Provide a `Readable` (signal/computed) instead\n  // of a raw value so descendants observe updates through the value itself.\n  if (map.has(key)) {\n    warn(\n      `provide(): key already provided on <${el.localName}> — overwriting. Provide a Readable to update it instead.`,\n    );\n  }\n\n  map.set(key, value);\n  contextRegistry.set(el, map);\n};\n\n/**\n * Register a context value on the current component's host element, making it\n * available to descendant components via `inject(key)`.\n *\n * Provide a `Readable` (signal/computed) rather than a raw value if descendants\n * need to observe later changes — `inject()` resolves and caches the value once\n * per consumer, so re-calling `provide()` with a new raw value later is not seen.\n */\nexport const provide = <T>(key: InjectionKey<T>, value: T): void => {\n  const el = requireSetupContext('provide').element;\n\n  provideOnElement(el, key, value);\n\n  onCleanup(() => {\n    const map = contextRegistry.get(el);\n\n    if (!map) return;\n\n    map.delete(key);\n\n    if (map.size === 0) contextRegistry.delete(el);\n  });\n};\n\nconst NOT_FOUND_SENTINEL = Symbol('inject.not_found');\n\n/** Per-setup-context cache: avoids repeated ancestor walks for the same key. */\nconst resolvedCache = new WeakMap<object, Map<InjectionKey<unknown>, unknown>>();\n\nconst walkAndFind = <T>(element: HTMLElement, key: InjectionKey<T>): T | typeof NOT_FOUND_SENTINEL => {\n  const chain = buildAncestorChain(element);\n\n  for (const node of chain) {\n    const map = contextRegistry.get(node);\n\n    if (map?.has(key)) return map.get(key) as T;\n  }\n\n  return NOT_FOUND_SENTINEL;\n};\n\n/** Cached ancestor-walk lookup shared by `inject()` and `injectStrict()`. */\nconst lookup = <T>(ctx: RuntimeContext, key: InjectionKey<T>): T | typeof NOT_FOUND_SENTINEL => {\n  let cache = resolvedCache.get(ctx);\n\n  if (!cache) {\n    cache = new Map();\n    resolvedCache.set(ctx, cache);\n  }\n\n  const cacheKey = key as InjectionKey<unknown>;\n\n  if (!cache.has(cacheKey)) cache.set(cacheKey, walkAndFind(ctx.element, key));\n\n  return cache.get(cacheKey) as T | typeof NOT_FOUND_SENTINEL;\n};\n\nexport function inject<T>(key: InjectionKey<T>): T | undefined;\nexport function inject<T>(key: InjectionKey<T>, fallback: T): T;\nexport function inject<T>(key: InjectionKey<T>, ...rest: [T?]): T | undefined {\n  const found = lookup(requireSetupContext('inject'), key);\n\n  if (found === NOT_FOUND_SENTINEL) return rest.length > 0 ? rest[0] : undefined;\n\n  return found;\n}\n\nexport const injectStrict = <T>(key: InjectionKey<T>): T => {\n  const ctx = requireSetupContext('injectStrict');\n  const found = lookup(ctx, key);\n\n  if (found !== NOT_FOUND_SENTINEL) return found;\n\n  throw new OreApiError(ORE_ERRORS.injectStrictFailed(String(key), ctx.element.localName));\n};\n\nlet anonymousKeyCounter = 0;\n\n/**\n * Create a typed context key. `Symbol.for`-keyed (`ore:context:<description>`) so\n * a provider and an injector loaded from two bundled copies of ore still match\n * (see module header). Two `createContext('theme')` calls intentionally produce\n * the same key — use distinct descriptions for distinct contexts.\n *\n * Always pass a description: anonymous keys are minted from a per-graph counter,\n * so they do NOT survive duplicated module graphs (each copy numbers its own).\n */\nexport function createContext<T>(description?: string): InjectionKey<T> {\n  if (description === undefined) {\n    warn(\n      'createContext() called without a description — anonymous context keys do not survive duplicated module graphs.',\n    );\n  }\n\n  return Symbol.for(`ore:context:${description ?? `anonymous-${++anonymousKeyCounter}`}`) as InjectionKey<T>;\n}\n"],"mappings":"iFAgBA,IAAM,EAAkB,IAAI,QAWtB,EAAsB,GAAsC,CAChE,IAAM,EAAuB,CAAC,EAC1B,EAAoB,EAExB,KAAO,GACD,aAAgB,aAAa,EAAM,KAAK,CAAI,EAGhD,EAAO,EAAK,aAAe,aAAgB,WAAa,EAAK,KAAO,MAGtE,OAAO,CACT,EAMM,GAAuB,EAAiB,EAAsB,IAAmB,CACrF,IAAM,EAAM,EAAgB,IAAI,CAAE,GAAK,IAAI,IAMvC,EAAI,IAAI,CAAG,GAEX,GAAuC,EAAG,UAA1C,EAIJ,EAAI,IAAI,EAAK,CAAK,EAClB,EAAgB,IAAI,EAAI,CAAG,CAC7B,EAUa,GAAc,EAAsB,IAAmB,CAClE,IAAM,EAAK,EAAA,oBAAoB,SAAS,CAAC,CAAC,QAE1C,EAAiB,EAAI,EAAK,CAAK,EAE/B,EAAA,cAAgB,CACd,IAAM,EAAM,EAAgB,IAAI,CAAE,EAE7B,IAEL,EAAI,OAAO,CAAG,EAEV,EAAI,OAAS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