{"version":3,"file":"styloviz-core-ai.mjs","names":[],"sources":["../../../../projects/core/ai/privacy.ts","../../../../projects/core/ai/webmcp.source.ts","../../../../projects/core/ai/webmcp.ts","../../../../projects/core/ai/webmcp.register.ts"],"sourcesContent":["import {\n  InjectionToken,\n  inject,\n  makeEnvironmentProviders,\n  type EnvironmentProviders,\n} from '@angular/core';\nimport { svCompilePattern } from '@styloviz/core/security';\nimport { svWarnOnce } from '@styloviz/core/dev';\n\n/**\n * ============================================================================\n *  `X-2` — one privacy and redaction contract for the AI pack\n * ============================================================================\n *\n * ★★★ EVERY COMPONENT IN THE PACK RENDERS SAFELY AND THE PORTFOLIO HAS NO\n *     POLICY, which is a different defect from an unsafe component and a harder\n *     one to see. Tool arguments, approval edits, reasoning content, voice\n *     transcripts, chat messages and retrieved chunks can all carry a key, a\n *     customer's address or a patient identifier — and a host that wants those\n *     masked had to configure eight components separately, in eight shapes, and\n *     keep them agreeing with each other for ever. The first one it forgets is\n *     the leak.\n *\n * ★★ MASKING IS A RENDER-TIME TRANSFORM AND NEVER TOUCHES THE DATA. Same rule\n *    as the scale ceiling: the host's array is not edited, the model is not\n *    rewritten, and a copy of the ORIGINAL is what a permitted export gets.\n *    A component that masked its own inputs would corrupt the thing it was\n *    handed, and the corruption would survive into whatever the host persisted\n *    next.\n *\n * ★★ THE PATTERNS ARE HOST-SUPPLIED SOURCES, COMPILED THROUGH\n *    `svCompilePattern`, because a mask pattern is exactly the untrusted regex\n *    that module exists for — and worse than the case it was written for: a\n *    catastrophic pattern that froze one field on one keystroke here runs over\n *    every message in a transcript on every render. A pattern that cannot be\n *    compiled safely is dropped with one dev warning naming it, and masking\n *    carries on with the rest; refusing the whole policy would turn one bad\n *    regex into no redaction at all, which is the failure mode that matters.\n */\n\n/** One thing to mask, and what to show instead. */\nexport interface SvAiMaskPattern {\n  /** Stable id, used in warnings and by hosts toggling patterns. */\n  readonly id: string;\n  /**\n   * The regular expression SOURCE — a string, not a `RegExp`.\n   *\n   * ★★ A `RegExp` handed over by a host is either stateful (the `g` flag keeps\n   *    `lastIndex`, so a policy object shared by two surfaces skips matches in\n   *    the second) or not global, in which case it can only ever mask the FIRST\n   *    secret in a message. Taking the source and compiling it here is what\n   *    makes both impossible.\n   */\n  readonly source: string;\n  /** What replaces a match. `'[REDACTED]'` when omitted. */\n  readonly label?: string;\n}\n\nexport interface SvAiPrivacyPolicy {\n  /**\n   * What to mask. Empty by default — see {@link SV_AI_COMMON_PATTERNS}.\n   *\n   * ★★★ NO PATTERNS BY DEFAULT, DELIBERATELY. A default mask set would rewrite\n   *     content in every existing surface the moment this shipped, and the\n   *     rewrite that matters is the wrong one: a code block containing `sk-` or\n   *     a sentence containing an `@` would come out mangled, in a component\n   *     whose job is to show the user what the model said. The patterns that\n   *     are right vary per tenant, which is the definition of a policy rather\n   *     than a default. `SV_AI_COMMON_PATTERNS` is one call away.\n   */\n  readonly patterns: readonly SvAiMaskPattern[];\n  /**\n   * May a viewer unmask what was masked?\n   *\n   * ★★★ FALSE BY DEFAULT, AND THIS IS THE ONE DEFAULT THAT IS NOT NEGOTIABLE.\n   *     A reveal control that exists unless a host turns it off is a leak\n   *     unless a host remembers — and the host that most needs masking is the\n   *     one least likely to audit for an affordance it never asked for. Role\n   *     gating lives with the host: it knows who is looking.\n   */\n  readonly reveal: boolean;\n  /**\n   * May a viewer copy or export content from these surfaces?\n   *\n   * ★ TRUE by default, because copy is a shipped feature of `sv-ai-chat` and\n   *   flipping it would silently remove a control people use. A host that\n   *   masks on screen and wants the export masked too sets this `false` and\n   *   offers its own export path — the component cannot know whether the\n   *   clipboard is going into a ticket or a support channel.\n   */\n  readonly copy: boolean;\n  /**\n   * May a surface include content in analytics or telemetry events?\n   *\n   * ★★★ FALSE by default. Content-bearing telemetry that is on unless someone\n   *     turns it off is the worst available default in this whole contract: it\n   *     exfiltrates continuously, to a third party, with no UI anywhere that\n   *     shows it happening.\n   */\n  readonly telemetry: boolean;\n}\n\n/** The policy a surface applies when the host has provided none. */\nexport const SV_AI_PRIVACY_DEFAULT: SvAiPrivacyPolicy = Object.freeze({\n  patterns: Object.freeze([]) as readonly SvAiMaskPattern[],\n  reveal: false,\n  copy: true,\n  telemetry: false,\n});\n\n/**\n * A conservative, opt-in mask set for the things that are secrets whatever the\n * tenant: provider keys, bearer tokens, JWTs, and private-key blocks.\n *\n * ★★ WHAT IS NOT IN HERE IS THE POINT. No e-mail pattern, no phone pattern, no\n *    credit-card pattern — those match legitimate content constantly (a chat\n *    about a customer, a tool argument that IS an address), and a mask set that\n *    eats the answer is the over-redaction failure `sv-guardrail-panel` exists\n *    to make visible. Add those per tenant, having decided they are worth it.\n */\nexport const SV_AI_COMMON_PATTERNS: readonly SvAiMaskPattern[] = Object.freeze([\n  { id: 'provider-key', source: '\\\\b(?:sk|pk|rk)-[A-Za-z0-9_-]{16,}', label: '[API KEY]' },\n  { id: 'bearer', source: '\\\\bBearer\\\\s+[A-Za-z0-9._~+/-]{12,}=*', label: 'Bearer [TOKEN]' },\n  { id: 'jwt', source: '\\\\bey[A-Za-z0-9_-]{8,}\\\\.[A-Za-z0-9_-]{8,}\\\\.[A-Za-z0-9_-]{8,}', label: '[JWT]' },\n  { id: 'aws-key', source: '\\\\b(?:AKIA|ASIA)[A-Z0-9]{16}', label: '[AWS KEY]' },\n  {\n    id: 'private-key',\n    source: '-----BEGIN [A-Z ]*PRIVATE KEY-----[\\\\s\\\\S]*?-----END [A-Z ]*PRIVATE KEY-----',\n    label: '[PRIVATE KEY]',\n  },\n  /**\n   * ★★ A URL IS A CREDENTIAL CARRIER THAT DOES NOT LOOK LIKE ONE. Connection\n   *    strings put the password in the userinfo (`postgres://app:hunter2@db`),\n   *    and a failing client echoes the URL it called into its error message.\n   *    Only the userinfo is replaced, so the host and path — what the reader\n   *    needs to diagnose the call — stay on screen. A bare short user name\n   *    (`ssh://git@host`) is left alone: it is not a secret, and masking it is\n   *    the over-redaction this set is written to avoid. A long one is a token\n   *    used as the user name (`https://ghp_…@github.com`) and is masked.\n   */\n  {\n    id: 'url-credentials',\n    source: '(?<=://)(?:[^\\\\s/?#@:]*:[^\\\\s/?#@]+|[^\\\\s/?#@:]{16,})(?=@)',\n    label: '[CREDENTIALS]',\n  },\n  /**\n   * ★ Query and fragment parameters that are secrets by name — `?token=`,\n   *   `&api_key=`, `#access_token=` (the OAuth implicit flow), and the signed-URL\n   *   parameters S3 presigning adds. The parameter NAME stays, so the reader can\n   *   still see which kind of URL it was.\n   */\n  {\n    id: 'url-secret-param',\n    source:\n      '(?<=[?&#;](?:access_token|refresh_token|id_token|token|api_key|apikey|api-key|key|' +\n      'secret|client_secret|password|passwd|pwd|auth|sig|signature|' + // sv-i18n-ignore: regex source\n      'X-Amz-Signature|X-Amz-Credential|X-Amz-Security-Token)=)[^&#\\\\s]+',\n    label: '[REDACTED]',\n  },\n]);\n\nexport const SV_AI_PRIVACY = new InjectionToken<SvAiPrivacyPolicy>('SvAiPrivacyPolicy');\n\n/**\n * Configure masking, reveal, copy and telemetry for the whole AI pack, once.\n *\n * @example\n * ```ts\n * providers: [\n *   provideSvAiPrivacy({ patterns: SV_AI_COMMON_PATTERNS, copy: false }),\n * ]\n * ```\n */\nexport function provideSvAiPrivacy(policy: Partial<SvAiPrivacyPolicy> = {}): EnvironmentProviders {\n  return makeEnvironmentProviders([\n    { provide: SV_AI_PRIVACY, useValue: { ...SV_AI_PRIVACY_DEFAULT, ...policy } },\n  ]);\n}\n\n/**\n * The policy in force, for a component to read.\n *\n * ★ Optional injection with the default as the fallback, so every surface in\n *   the pack works in an app that has never heard of this contract — which is\n *   every app that upgrades into it.\n */\nexport function svAiPrivacy(): SvAiPrivacyPolicy {\n  return inject(SV_AI_PRIVACY, { optional: true }) ?? SV_AI_PRIVACY_DEFAULT;\n}\n\nexport interface SvAiMasked {\n  /** The text to render. */\n  readonly text: string;\n  /** How many matches were replaced. */\n  readonly count: number;\n  /** Ids of the patterns that matched, in the order they first did. */\n  readonly matched: readonly string[];\n}\n\ninterface Span {\n  readonly start: number;\n  readonly end: number;\n  readonly label: string;\n  readonly id: string;\n}\n\n/**\n * Mask every match in one string.\n *\n * ★★★ `policy.reveal` IS DELIBERATELY NOT READ HERE. `reveal` is a PERMISSION\n *     for a viewer to unmask one value on request, never an instruction to stop\n *     masking: a host that sets it `true` wants a reveal control, and still\n *     wants every surface masked until somebody uses it. A mask that honoured\n *     `reveal` would turn that flag into \"masking off\" for the whole pack. The\n *     surface owns the per-value reveal state (`sv-agent-approval`'s argument\n *     reveal, `sv-mcp-tool-registry`'s per-server reveal) and simply renders the\n *     original text for a value the viewer has revealed; it offers the control\n *     only when `reveal` is true and this function reported `count > 0`.\n *\n * ★★★ MATCHES ARE COLLECTED, MERGED AND THEN SPLICED ONCE — never replaced one\n *     pattern at a time. Two patterns matching overlapping ranges (a bearer\n *     header that contains a JWT) spliced in sequence shift every offset after\n *     the first replacement, and the visible result is a mangled\n *     `Bearer [RE[JWT]D]`: the same defect `svMergeSpans` documents for\n *     redaction in `sv-guardrail-panel`, arrived at from the other direction.\n *\n * ★★ THE LONGEST MATCH WINS AN OVERLAP, because the longer span is the more\n *    complete secret. A `Bearer eyJ…` masked as `[JWT]` leaves the word Bearer\n *    and a truncated token on screen; masked as the whole header it leaves\n *    nothing.\n */\nexport function svAiMask(text: string, policy: SvAiPrivacyPolicy): SvAiMasked {\n  if (!text || policy.patterns.length === 0) return { text, count: 0, matched: [] };\n\n  const spans: Span[] = [];\n  for (const pattern of policy.patterns) {\n    const compiled = svCompilePattern(pattern.source, { anchor: false });\n    if (!compiled.regexp) {\n      svWarnOnce(\n        `sv-ai-privacy/pattern/${pattern.id}`,\n        `sv-ai privacy: mask pattern \"${pattern.id}\" was dropped — ${compiled.reason} ` +\n          'The other patterns are still applied; one bad expression must not turn ' +\n          'redaction off altogether.',\n      );\n      continue;\n    }\n    const rx = new RegExp(compiled.regexp.source, 'g');\n    for (const match of text.matchAll(rx)) {\n      if (match.index === undefined || match[0].length === 0) continue;\n      spans.push({\n        start: match.index,\n        end: match.index + match[0].length,\n        label: pattern.label ?? '[REDACTED]',\n        id: pattern.id,\n      });\n    }\n  }\n\n  if (spans.length === 0) return { text, count: 0, matched: [] };\n\n  // Longest first at a given start, so the more complete secret wins an overlap.\n  spans.sort((a, b) => a.start - b.start || b.end - a.end);\n\n  const kept: Span[] = [];\n  for (const span of spans) {\n    const last = kept[kept.length - 1];\n    if (last && span.start < last.end) continue;   // inside a span already kept\n    kept.push(span);\n  }\n\n  let out = '';\n  let cursor = 0;\n  const matched: string[] = [];\n  for (const span of kept) {\n    out += text.slice(cursor, span.start) + span.label;\n    cursor = span.end;\n    if (!matched.includes(span.id)) matched.push(span.id);\n  }\n  out += text.slice(cursor);\n\n  return { text: out, count: kept.length, matched };\n}\n","import { InjectionToken } from '@angular/core';\n\n/**\n * `FL-E2` — the half of WebMCP a widget imports: the tool vocabulary, the\n * `SV_WEBMCP_SOURCE` token and `svWebMcpResult`. Kept apart from the directive\n * and the argument check (`./webmcp`) so a widget that is never exposed to an\n * agent ships a token and a few types, not the registration code.\n */\n\n/** JSON Schema subset the kit's tools use, and the subset `svCheckWebMcpArgs` enforces. */\nexport interface SvWebMcpSchema {\n  readonly type?: 'object' | 'string' | 'number' | 'integer' | 'boolean' | 'array';\n  readonly description?: string;\n  readonly enum?: readonly (string | number)[];\n  readonly properties?: Readonly<Record<string, SvWebMcpSchema>>;\n  readonly required?: readonly string[];\n  readonly additionalProperties?: boolean;\n  readonly items?: SvWebMcpSchema;\n  readonly anyOf?: readonly SvWebMcpSchema[];\n  readonly minimum?: number;\n  readonly maximum?: number;\n  readonly minLength?: number;\n  readonly maxLength?: number;\n  readonly minItems?: number;\n  readonly maxItems?: number;\n}\n\n/** Behaviour hints an agent reads before it decides to call a tool (WebMCP `annotations`). */\nexport interface SvWebMcpAnnotations {\n  /** The tool changes nothing the user can see. */\n  readonly readOnlyHint?: boolean;\n  /** The result carries the host's data, which the agent should treat as untrusted content. */\n  readonly untrustedContentHint?: boolean;\n  /** The tool has an effect beyond the screen (it saves, sends or deletes). */\n  readonly consequentialHint?: boolean;\n}\n\n/** The context of one call: aborted when the widget goes away or the agent cancels. */\nexport interface SvWebMcpClient {\n  readonly signal: AbortSignal;\n}\n\n/** One tool, as a widget describes it. `name` is local — the directive prefixes it. */\nexport interface SvWebMcpTool {\n  readonly name: string;\n  readonly description: string;\n  readonly inputSchema: SvWebMcpSchema;\n  readonly annotations?: SvWebMcpAnnotations;\n  /** Runs with arguments already checked against `inputSchema`. Returns text for the agent. */\n  execute(args: Readonly<Record<string, unknown>>, client: SvWebMcpClient): string | Promise<string>;\n}\n\n/** What a widget provides (as `SV_WEBMCP_SOURCE`) to be exposed by `svWebMcp`. */\nexport interface SvWebMcpToolSource {\n  /**\n   * The widget's tools; called once per registration. A promise, so a widget\n   * can `import()` its tool set — nobody downloads tool code until a page\n   * actually puts `svWebMcp` on the widget.\n   */\n  svWebMcpTools(): Promise<readonly SvWebMcpTool[]>;\n}\n\n/** Provided by every widget that can be exposed to an agent: `useExisting` the component. */\nexport const SV_WEBMCP_SOURCE = new InjectionToken<SvWebMcpToolSource>('SV_WEBMCP_SOURCE');\n\n/** A refusal or an answer, as the text the agent reads. */\nexport function svWebMcpResult(value: unknown): string {\n  return typeof value === 'string' ? value : JSON.stringify(value);\n}\n\n/** The browser's registry, as far as the kit uses it (draft API; shapes differ between builds). */\nexport interface SvModelContextLike {\n  registerTool(tool: object, options?: { signal?: AbortSignal }): unknown;\n  unregisterTool?(name: string): unknown;\n}\n\n/** `document.modelContext` or `navigator.modelContext`, when the browser has one. */\nexport function svModelContext(doc: Document | null | undefined): SvModelContextLike | null {\n  const candidates: unknown[] = [\n    (doc as { modelContext?: unknown } | null | undefined)?.modelContext,\n    (doc?.defaultView?.navigator as { modelContext?: unknown } | undefined)?.modelContext,\n  ];\n  for (const candidate of candidates) {\n    if (candidate && typeof (candidate as SvModelContextLike).registerTool === 'function') {\n      return candidate as SvModelContextLike;\n    }\n  }\n  return null;\n}\n\nconst NAME = /^[A-Za-z][A-Za-z0-9_-]{0,63}$/;\n\n/** `true` for a usable tool prefix or name: a letter, then letters, digits, `_` or `-`, up to 64. */\nexport function svIsWebMcpName(value: string): boolean {\n  return NAME.test(value);\n}\n","import {\n  Directive,\n  booleanAttribute,\n  PLATFORM_ID,\n  effect,\n  inject,\n  input,\n  signal,\n  untracked,\n} from '@angular/core';\nimport { DOCUMENT, isPlatformBrowser } from '@angular/common';\nimport { svWarnOnce } from '@styloviz/core/dev';\nimport { SV_WEBMCP_SOURCE, svIsWebMcpName, svModelContext } from './webmcp.source';\n\n/**\n * ============================================================================\n *  `FL-E2` — WebMCP: the big widgets as tools a browser agent can call\n * ============================================================================\n *\n * WebMCP (`navigator.modelContext`, W3C Web Machine Learning CG draft) lets a\n * page hand an in-browser agent typed tools instead of making it click\n * through pixels. Angular 22 ships `declareExperimentalWebMcpTool`; this is\n * the kit's own registration because the packages still support Angular 21,\n * and because a widget's tools have to come and go with the widget, not with\n * an environment injector.\n *\n * ★★ THE AGENT'S ARGUMENTS ARE UNTRUSTED INPUT. Every call is checked against\n *    the tool's own `inputSchema` (`svCheckWebMcpArgs`) before `execute` sees\n *    it, and a widget's `execute` still validates meaning (a column that is\n *    not sortable, a card id that does not exist) and answers with a refusal\n *    the agent can read, never a thrown stack.\n *\n * ★★ A TOOL CHANGES STATE THROUGH THE SAME PATH AS A CLICK. Sorting from a\n *    tool emits `sortChange` and a server-side `queryChange` exactly as a\n *    header click does; moving a card runs the same transition rules and WIP\n *    limits. A host wired for users is wired for agents.\n *\n * ★ Nothing registers on the server, or where the browser has no\n *   `modelContext` — the directive is then inert and costs one check.\n */\n\n/**\n * `svWebMcp` — exposes the widget it sits on to a browser agent as WebMCP tools.\n *\n * ```html\n * <sv-data-table-pro svWebMcp=\"orders\" [columns]=\"columns\" [rows]=\"rows\" />\n * <!-- registers orders_describe, orders_sort, orders_search, orders_filter, orders_select, orders_rows -->\n * ```\n *\n * The tools live exactly as long as the widget; changing the prefix or the\n * filters re-registers them. Inert on the server and where the browser has no\n * `modelContext`.\n */\n@Directive({\n  selector: '[svWebMcp]',\n  standalone: true,\n  exportAs: 'svWebMcp',\n  host: { '[attr.data-sv-webmcp]': 'prefix()' },\n})\nexport class SvWebMcpDirective {\n  /** Tool-name prefix, unique on the page: `orders` → `orders_sort`. A letter, then letters, digits, `_` or `-`. */\n  readonly prefix = input.required<string>({ alias: 'svWebMcp' });\n  /** Only these tools (local names, e.g. `['describe', 'sort']`); `null` exposes all. @default null */\n  readonly include = input<readonly string[] | null>(null, { alias: 'svWebMcpInclude' });\n  /** Expose only the tools marked read-only — an agent can look but not change anything. @default false */\n  readonly readOnly = input<boolean, unknown>(false, { alias: 'svWebMcpReadOnly', transform: booleanAttribute });\n\n  /** The full names registered right now — `[]` with no WebMCP in the browser. */\n  readonly registered = signal<readonly string[]>([]);\n\n  private readonly source = inject(SV_WEBMCP_SOURCE, { self: true, optional: true });\n\n  /**\n   * Calls one of the widget's tools (by local name) exactly as an agent's call\n   * runs — arguments checked first, the answer as text — whether or not the\n   * browser has WebMCP. For a demo, a test, or an in-page assistant.\n   */\n  async call(name: string, args: Readonly<Record<string, unknown>> = {}): Promise<string> {\n    const [{ svRunWebMcpTool }, tools] = await Promise.all([import('./webmcp.register'), this.source?.svWebMcpTools() ?? []]);\n    const tool = tools.find((t) => t.name === name);\n    return tool ? svRunWebMcpTool(tool, args, new AbortController().signal) : `Refused: no tool \"${name}\".`;\n  }\n\n  constructor() {\n    const source = this.source;\n    if (!source) {\n      svWarnOnce('webmcp-no-source', '[svWebMcp] this element exposes no tools — put it on a widget that provides SV_WEBMCP_SOURCE (data table, scheduler, Gantt, kanban, form builder).');\n      return;\n    }\n    const document = inject(DOCUMENT);\n    // No registry, no work: the widget's tool set is never even downloaded.\n    if (!isPlatformBrowser(inject(PLATFORM_ID)) || !svModelContext(document)) return;\n    // The effect's cleanup runs before each re-registration and on destroy.\n    effect((onCleanup) => {\n      const prefix = this.prefix();\n      const include = this.include();\n      const readOnly = this.readOnly();\n      const current = new AbortController();\n      onCleanup(() => current.abort());\n      untracked(() => this.registered.set([]));\n      if (!svIsWebMcpName(prefix)) {\n        svWarnOnce(`webmcp-prefix:${prefix}`, `[svWebMcp] \"${prefix}\" is not a usable prefix (a letter, then letters, digits, _ or -) — no tools registered.`);\n        return;\n      }\n      void (async () => {\n        const [{ svRegisterWebMcpTools }, all] = await Promise.all([import('./webmcp.register'), source.svWebMcpTools()]);\n        const tools = all.filter((tool) =>\n          (!include || include.includes(tool.name)) && (!readOnly || tool.annotations?.readOnlyHint === true));\n        const names = await svRegisterWebMcpTools(document, tools, { signal: current.signal, prefix });\n        if (!current.signal.aborted) this.registered.set(names);\n      })();\n    });\n  }\n}\n","import { svWarnOnce } from '@styloviz/core/dev';\nimport { svIsWebMcpName, svModelContext, type SvWebMcpSchema, type SvWebMcpTool } from './webmcp.source';\n\n/**\n * `FL-E2` — the half of WebMCP that runs only where a browser has\n * `modelContext`: the argument check and the registration. `svWebMcp` loads it\n * with `import()` once it has found a registry, and `call()` when a host asks.\n */\n\nfunction typeOf(value: unknown): string {\n  if (value === null) return 'null';\n  if (Array.isArray(value)) return 'array';\n  return typeof value;\n}\n\n/**\n * Checks `value` against `schema` and returns the first problem as a sentence,\n * or `null` when it fits. Enforces the subset in `SvWebMcpSchema`; unknown\n * object keys are refused unless `additionalProperties` is `true`.\n */\nexport function svCheckWebMcpArgs(schema: SvWebMcpSchema, value: unknown, path = 'arguments'): string | null {\n  if (schema.anyOf) {\n    return schema.anyOf.some((option) => svCheckWebMcpArgs(option, value, path) === null)\n      ? null\n      : `${path} matches none of the allowed shapes.`;\n  }\n  const actual = typeOf(value);\n  switch (schema.type) {\n    case 'object': {\n      if (actual !== 'object') return `${path} must be an object, got ${actual}.`;\n      const record = value as Record<string, unknown>;\n      for (const key of schema.required ?? []) {\n        if (record[key] === undefined) return `${path}.${key} is required.`;\n      }\n      const properties = schema.properties ?? {};\n      for (const [key, entry] of Object.entries(record)) {\n        const child = Object.hasOwn(properties, key) ? properties[key] : undefined;\n        if (!child) {\n          if (schema.additionalProperties === true) continue;\n          return `${path}.${key} is not a known argument.`;\n        }\n        if (entry === undefined) continue;\n        const problem = svCheckWebMcpArgs(child, entry, `${path}.${key}`);\n        if (problem) return problem;\n      }\n      return null;\n    }\n    case 'array': {\n      if (actual !== 'array') return `${path} must be an array, got ${actual}.`;\n      const list = value as readonly unknown[];\n      if (schema.minItems !== undefined && list.length < schema.minItems) return `${path} needs at least ${schema.minItems} item(s).`;\n      if (schema.maxItems !== undefined && list.length > schema.maxItems) return `${path} takes at most ${schema.maxItems} item(s).`;\n      if (schema.items) {\n        for (let i = 0; i < list.length; i++) {\n          const problem = svCheckWebMcpArgs(schema.items, list[i], `${path}[${i}]`);\n          if (problem) return problem;\n        }\n      }\n      return null;\n    }\n    case 'string': {\n      if (actual !== 'string') return `${path} must be a string, got ${actual}.`;\n      const text = value as string;\n      if (schema.minLength !== undefined && text.length < schema.minLength) return `${path} must be at least ${schema.minLength} character(s).`;\n      if (schema.maxLength !== undefined && text.length > schema.maxLength) return `${path} must be at most ${schema.maxLength} character(s).`;\n      break;\n    }\n    case 'number':\n    case 'integer': {\n      if (actual !== 'number' || !Number.isFinite(value as number)) return `${path} must be a finite number.`;\n      const n = value as number;\n      if (schema.type === 'integer' && !Number.isInteger(n)) return `${path} must be a whole number.`;\n      if (schema.minimum !== undefined && n < schema.minimum) return `${path} must be at least ${schema.minimum}.`;\n      if (schema.maximum !== undefined && n > schema.maximum) return `${path} must be at most ${schema.maximum}.`;\n      break;\n    }\n    case 'boolean':\n      if (actual !== 'boolean') return `${path} must be true or false.`;\n      break;\n  }\n  if (schema.enum && !schema.enum.includes(value as string | number)) {\n    return `${path} must be one of ${schema.enum.map((v) => JSON.stringify(v)).join(', ')}.`;\n  }\n  return null;\n}\n\n/**\n * Runs one tool as an agent's call does: the arguments are checked against its\n * schema first, a refusal or a thrown error comes back as text, and nothing\n * runs once `signal` has aborted.\n */\nexport async function svRunWebMcpTool(tool: SvWebMcpTool, args: unknown, signal: AbortSignal): Promise<string> {\n  const input = args ?? {};\n  const problem = svCheckWebMcpArgs(tool.inputSchema, input);\n  if (problem) return `Refused: ${problem}`;\n  if (signal.aborted) return 'Refused: the widget is no longer on the page.';\n  try {\n    return await tool.execute(input as Readonly<Record<string, unknown>>, { signal });\n  } catch (error) {\n    return `Failed: ${error instanceof Error ? error.message : String(error)}`;\n  }\n}\n\n/** Options for `svRegisterWebMcpTools`. */\nexport interface SvWebMcpRegisterOptions {\n  /** Unregisters every tool when aborted. */\n  readonly signal: AbortSignal;\n  /** Prepended to each tool's name with `_` (`orders` + `sort` → `orders_sort`). */\n  readonly prefix?: string;\n  /** Called with each registered name, or with the reason a tool was skipped. */\n  readonly onRegistered?: (name: string) => void;\n}\n\n/**\n * Registers `tools` with the browser's `modelContext`, each wrapped so its\n * arguments are checked before it runs and a thrown error comes back as text.\n * Resolves to the names registered — `[]` when the browser has no WebMCP.\n */\nexport async function svRegisterWebMcpTools(\n  doc: Document,\n  tools: readonly SvWebMcpTool[],\n  options: SvWebMcpRegisterOptions,\n): Promise<readonly string[]> {\n  const context = svModelContext(doc);\n  if (!context || options.signal.aborted) return [];\n  const registered: string[] = [];\n  for (const tool of tools) {\n    const name = options.prefix ? `${options.prefix}_${tool.name}` : tool.name;\n    if (!svIsWebMcpName(name)) {\n      svWarnOnce(`webmcp-name:${name}`, `[svWebMcp] \"${name}\" is not a usable tool name (a letter, then letters, digits, _ or -, up to 64) — skipped.`);\n      continue;\n    }\n    const wrapped = {\n      name,\n      description: tool.description,\n      inputSchema: tool.inputSchema,\n      ...(tool.annotations ? { annotations: tool.annotations } : {}),\n      execute: (args: unknown, client?: { signal?: AbortSignal }): Promise<string> => {\n        const signal = client?.signal && typeof AbortSignal.any === 'function' ? AbortSignal.any([options.signal, client.signal]) : options.signal;\n        return svRunWebMcpTool(tool, args, signal);\n      },\n    };\n    try {\n      await context.registerTool(wrapped, { signal: options.signal });\n    } catch (error) {\n      if (error instanceof DOMException && error.name === 'AbortError') return registered;\n      svWarnOnce(`webmcp-register:${name}`, `[svWebMcp] the browser refused \"${name}\": ${error instanceof Error ? error.message : String(error)}`);\n      continue;\n    }\n    registered.push(name);\n    options.onRegistered?.(name);\n    // Builds whose registerTool ignores `signal` unregister by name instead.\n    options.signal.addEventListener('abort', () => {\n      try { context.unregisterTool?.(name); } catch { /* already gone */ }\n    }, { once: true });\n  }\n  return registered;\n}\n"],"mappings":";;;;;;;;;;;;;;;AAuGA,MAAa,wBAA2C,OAAO,OAAO;CACpE,UAAU,OAAO,OAAO,CAAA,CAAE;CAC1B,QAAQ;CACR,MAAM;CACN,WAAW;AACZ,CAAA;AAYD,MAAa,wBAAoD,OAAO,OAAO;CAC7E;EAAE,IAAI;EAAgB,QAAQ;EAAsC,OAAO;CAAW;CACtF;EAAE,IAAI;EAAU,QAAQ;EAAyC,OAAO;CAAgB;CACxF;EAAE,IAAI;EAAO,QAAQ;EAAkE,OAAO;CAAO;CACrG;EAAE,IAAI;EAAW,QAAQ;EAAgC,OAAO;CAAW;CAC3E;EACE,IAAI;EACJ,QAAQ;EACR,OAAO;CACR;CAWD;EACE,IAAI;EACJ,QAAQ;EACR,OAAO;CACR;CAOD;EACE,IAAI;EACJ,QACE;EAGF,OAAO;CACR;AACF,CAAA;AAED,MAAa,gBAAgB,IAAI,eAAkC,mBAAmB;AAYtF,SAAgB,mBAAmB,SAAqC,CAAA,GAAE;CACxE,OAAO,yBAAyB,CAC9B;EAAE,SAAS;EAAe,UAAU;GAAE,GAAG;GAAuB,GAAG;EAAM;CAAE,CAC5E,CAAA;AACH;AASA,SAAgB,cAAW;CACzB,OAAO,OAAO,eAAe,EAAE,UAAU,KAAI,CAAE,KAAK;AACtD;AA2CA,SAAgB,SAAS,MAAc,QAAyB;CAC9D,IAAI,CAAC,QAAQ,OAAO,SAAS,WAAW,GAAG,OAAO;EAAE;EAAM,OAAO;EAAG,SAAS,CAAA;CAAE;CAE/E,MAAM,QAAgB,CAAA;CACt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