{"version":3,"file":"namespaced-state.mjs","names":[],"sources":["../../../../../../../../ai/src/middleware/utils/namespaced-state.ts"],"sourcesContent":["import type { MiddlewareState } from \"../../contracts/middleware\";\n\n/**\n * Typed accessor over `ctx.state` for a single namespace key. Wraps\n * the raw `Map<string, unknown>` so middleware authors stop typing\n * `as Counters | undefined` on every read.\n *\n * **Role.** Every built-in middleware reads and writes one or two\n * entries in `ctx.state` under its own name. Without a helper,\n * every call-site looks like:\n *\n * ```ts\n * const counters = context.state.get(\"budget.counters\") as Counters | undefined;\n * if (!counters) { ... }\n * counters.tokens += n;\n * ```\n *\n * — cast noise, no type narrowing on `set`, no protection against\n * key typos. `namespacedState<T>` eliminates all three.\n *\n * **Scope.** Deliberately narrow: one key, typed value, four methods\n * (`get` / `set` / `delete` / `has`). Does NOT try to model compound\n * or nested keys — if you need those, use the raw `ctx.state` Map\n * directly, or create a second namespaced accessor for the second key.\n *\n * **Namespace convention.** Use the middleware's `name` as the key\n * (or a `name.<field>` prefix when a middleware needs multiple\n * entries). The pipeline does not enforce this — it is a convention\n * the built-ins follow to avoid collisions between middlewares.\n *\n * @example\n * // Inside a budget middleware:\n * const counters = namespacedState<Counters>(ctx, \"budget\");\n *\n * if (!counters.has()) {\n *   counters.set({ tokens: 0, costUSD: 0 });\n * }\n *\n * const current = counters.get()!;\n * current.tokens += response.usage.total;\n */\nexport function namespacedState<T>(\n  ctx: { readonly state: MiddlewareState },\n  namespace: string,\n): NamespacedStateAccessor<T> {\n  return {\n    get(): T | undefined {\n      return ctx.state.get(namespace) as T | undefined;\n    },\n    set(value: T): void {\n      ctx.state.set(namespace, value);\n    },\n    delete(): void {\n      ctx.state.delete(namespace);\n    },\n    has(): boolean {\n      return ctx.state.has(namespace);\n    },\n  };\n}\n\n/**\n * Four-method accessor returned by `namespacedState`. Callers hold\n * it for the lifetime of a hook body — it is a thin typed view over\n * `ctx.state`, not a detached snapshot. Reads are live; writes hit\n * the underlying Map immediately and are visible to every other\n * hook that uses the same namespace.\n */\nexport type NamespacedStateAccessor<T> = {\n  get(): T | undefined;\n  set(value: T): void;\n  delete(): void;\n  has(): boolean;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCA,SAAgB,gBACd,KACA,WAC4B;CAC5B,OAAO;EACL,MAAqB;GACnB,OAAO,IAAI,MAAM,IAAI,SAAS;EAChC;EACA,IAAI,OAAgB;GAClB,IAAI,MAAM,IAAI,WAAW,KAAK;EAChC;EACA,SAAe;GACb,IAAI,MAAM,OAAO,SAAS;EAC5B;EACA,MAAe;GACb,OAAO,IAAI,MAAM,IAAI,SAAS;EAChC;CACF;AACF"}