@grafana/assistant 0.1.35 → 0.1.36
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +110 -0
- package/dist/analyticsEvents.d.ts +33 -0
- package/dist/analyticsEvents.d.ts.map +1 -0
- package/dist/components/button/OpenAssistantButton.d.ts +6 -1
- package/dist/components/button/OpenAssistantButton.d.ts.map +1 -1
- package/dist/components/grots/GrotAvatar.d.ts +31 -0
- package/dist/components/grots/GrotAvatar.d.ts.map +1 -0
- package/dist/components/grots/GrotTopicView.d.ts +19 -0
- package/dist/components/grots/GrotTopicView.d.ts.map +1 -0
- package/dist/components/grots/OpenGrotButton.d.ts +23 -0
- package/dist/components/grots/OpenGrotButton.d.ts.map +1 -0
- package/dist/components/index.d.ts +3 -0
- package/dist/components/index.d.ts.map +1 -1
- package/dist/esm/analyticsEvents.js +31 -0
- package/dist/esm/analyticsEvents.js.map +1 -0
- package/dist/esm/components/button/OpenAssistantButton.js +11 -10
- package/dist/esm/components/button/OpenAssistantButton.js.map +1 -1
- package/dist/esm/components/button/OpenAssistantSplitButton.js +2 -2
- package/dist/esm/components/button/OpenAssistantSplitButton.js.map +1 -1
- package/dist/esm/components/grots/GrotAvatar.js +37 -0
- package/dist/esm/components/grots/GrotAvatar.js.map +1 -0
- package/dist/esm/components/grots/GrotTopicView.js +25 -0
- package/dist/esm/components/grots/GrotTopicView.js.map +1 -0
- package/dist/esm/components/grots/OpenGrotButton.js +36 -0
- package/dist/esm/components/grots/OpenGrotButton.js.map +1 -0
- package/dist/esm/components/index.js +3 -0
- package/dist/esm/components/index.js.map +1 -1
- package/dist/esm/components/prompt-card/AssistantPromptCard.js +2 -2
- package/dist/esm/components/prompt-card/AssistantPromptCard.js.map +1 -1
- package/dist/esm/grots/avatar/appearance.js +303 -0
- package/dist/esm/grots/avatar/appearance.js.map +1 -0
- package/dist/esm/grots/avatar/sprite.js +481 -0
- package/dist/esm/grots/avatar/sprite.js.map +1 -0
- package/dist/esm/grots/client.js +377 -0
- package/dist/esm/grots/client.js.map +1 -0
- package/dist/esm/grots/index.js +2 -0
- package/dist/esm/grots/index.js.map +1 -0
- package/dist/esm/grots/retry.js +67 -0
- package/dist/esm/grots/retry.js.map +1 -0
- package/dist/esm/grots/types.js +2 -0
- package/dist/esm/grots/types.js.map +1 -0
- package/dist/esm/index.js +1 -0
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/sidebar.js +4 -3
- package/dist/esm/sidebar.js.map +1 -1
- package/dist/grots/avatar/appearance.d.ts +82 -0
- package/dist/grots/avatar/appearance.d.ts.map +1 -0
- package/dist/grots/avatar/sprite.d.ts +84 -0
- package/dist/grots/avatar/sprite.d.ts.map +1 -0
- package/dist/grots/client.d.ts +130 -0
- package/dist/grots/client.d.ts.map +1 -0
- package/dist/grots/index.d.ts +3 -0
- package/dist/grots/index.d.ts.map +1 -0
- package/dist/grots/retry.d.ts +7 -0
- package/dist/grots/retry.d.ts.map +1 -0
- package/dist/grots/types.d.ts +331 -0
- package/dist/grots/types.d.ts.map +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/investigations/api.gen.d.ts +3 -3
- package/dist/sidebar.d.ts.map +1 -1
- package/package.json +1 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","mappings":"mBACA,MAAMA,EAAsB,CCA5BA,EAAwB,CAACC,EAASC,KACjC,IAAI,IAAIC,KAAOD,EACXF,EAAoBI,EAAEF,EAAYC,KAASH,EAAoBI,EAAEH,EAASE,IAC5EE,OAAOC,eAAeL,EAASE,EAAK,CAAEI,YAAY,EAAMC,IAAKN,EAAWC,MCJ3EH,EAAwB,CAACS,EAAKC,IAAUL,OAAOM,UAAUC,eAAeC,KAAKJ,EAAKC,GCClFV,EAAyBC,IACxBI,OAAOC,eAAeL,EAASa,OAAOC,YAAa,CAAE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C,OAAQ,+BACRC,SAAU,mCACVC,IAAK,sCACLC,MAAO,SACPC,MAAO,eACPC,aAAc,OACdC,MAAO,aACPC,gBAAiB,uBACjBC,UAAW,aACXC,SAAU,kBACVC,YAAa,iBACbC,MAAO,iCACPC,KAAM,qCACNC,cAAe,2CACfC,QAAS,qCACTC,MAAO,uB","sources":["webpack://@grafana/assistant/webpack/bootstrap","webpack://@grafana/assistant/webpack/runtime/define property getters","webpack://@grafana/assistant/webpack/runtime/hasOwnProperty shorthand","webpack://@grafana/assistant/webpack/runtime/make namespace object","webpack://@grafana/assistant/./src/utils/hash.ts","webpack://@grafana/assistant/./src/context/base.ts","webpack://@grafana/assistant/./src/context/agentSkill.ts","webpack://@grafana/assistant/external commonjs2 \"@grafana/runtime\"","webpack://@grafana/assistant/external commonjs2 \"react\"","webpack://@grafana/assistant/./src/context/page.ts","webpack://@grafana/assistant/./src/context/component.ts","webpack://@grafana/assistant/./src/context/dashboard.ts","webpack://@grafana/assistant/./src/context/datasource.ts","webpack://@grafana/assistant/./src/context/entity.ts","webpack://@grafana/assistant/./src/context/label.ts","webpack://@grafana/assistant/./src/context/factory.ts","webpack://@grafana/assistant/./src/context/chat.ts","webpack://@grafana/assistant/./src/context/skill.ts","webpack://@grafana/assistant/./src/context/questions.ts","webpack://@grafana/assistant/./src/functions.ts","webpack://@grafana/assistant/external commonjs2 \"rxjs\"","webpack://@grafana/assistant/./src/plugin.ts","webpack://@grafana/assistant/external commonjs2 \"@grafana/data\"","webpack://@grafana/assistant/./src/sidebar.ts","webpack://@grafana/assistant/./src/hook.ts","webpack://@grafana/assistant/external commonjs2 \"react/jsx-runtime\"","webpack://@grafana/assistant/external commonjs2 \"@grafana/ui\"","webpack://@grafana/assistant/external commonjs2 \"@emotion/css\"","webpack://@grafana/assistant/./src/components/button/OpenAssistantButton.tsx","webpack://@grafana/assistant/./src/components/button/OpenAssistantSplitButton.tsx","webpack://@grafana/assistant/./src/utils/theme.ts","webpack://@grafana/assistant/./src/inline/inlineAssistant.ts","webpack://@grafana/assistant/./src/utils/errorHandling.ts","webpack://@grafana/assistant/./src/inline/useInlineAssistant.ts","webpack://@grafana/assistant/./src/components/input/useAIGeneration.ts","webpack://@grafana/assistant/./src/components/input/useGeneratingPlaceholder.ts","webpack://@grafana/assistant/./src/components/input/AITextInput.tsx","webpack://@grafana/assistant/./src/components/input/AITextArea.tsx","webpack://@grafana/assistant/./src/components/button/QueryWithAssistantButton.tsx","webpack://@grafana/assistant/./src/components/prompt-card/useAnimatedPlaceholder.ts","webpack://@grafana/assistant/./src/components/prompt-card/AssistantPromptCard.tsx","webpack://@grafana/assistant/./src/lens/investigationLens.ts","webpack://@grafana/assistant/./src/lens/useInvestigationThroughLens.ts","webpack://@grafana/assistant/../../../node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/util.js","webpack://@grafana/assistant/../../../node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/core.js","webpack://@grafana/assistant/../../../node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/memoizer.js","webpack://@grafana/assistant/../../../node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/regexes.js","webpack://@grafana/assistant/../../../node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/checks.js","webpack://@grafana/assistant/../../../node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/doc.js","webpack://@grafana/assistant/../../../node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/versions.js","webpack://@grafana/assistant/../../../node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/schemas.js","webpack://@grafana/assistant/../../../node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/registries.js","webpack://@grafana/assistant/../../../node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/api.js","webpack://@grafana/assistant/../../../node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/to-json-schema.js","webpack://@grafana/assistant/../../../node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/json-schema-processors.js","webpack://@grafana/assistant/../../../node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/en.js","webpack://@grafana/assistant/../../../node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/errors.js","webpack://@grafana/assistant/../../../node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/parse.js","webpack://@grafana/assistant/../../../node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/errors.js","webpack://@grafana/assistant/../../../node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/parse.js","webpack://@grafana/assistant/../../../node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/schemas.js","webpack://@grafana/assistant/./src/investigations/client.ts","webpack://@grafana/assistant/./src/investigations/observe.ts","webpack://@grafana/assistant/./src/terms/versionCompare.ts","webpack://@grafana/assistant/./src/terms/index.ts","webpack://@grafana/assistant/./src/tools/toolFactory.ts","webpack://@grafana/assistant/./src/limits/index.ts","webpack://@grafana/assistant/./src/k6.ts","webpack://@grafana/assistant/./src/pathfinder.ts","webpack://@grafana/assistant/./src/extension/extension.ts","webpack://@grafana/assistant/./src/extension/suggestionContexts.ts"],"sourcesContent":["// The require scope\nconst __webpack_require__ = {};\n\n","// define getter/value functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop));","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","/**\n * Simple hash function that generates a deterministic hash for a given input string.\n * Uses the djb2 algorithm for simplicity and good distribution.\n */\nexport function hash(input: string): string {\n let hash = 5381;\n\n for (let i = 0; i < input.length; i++) {\n hash = (hash << 5) + hash + input.charCodeAt(i);\n }\n\n // Convert to positive hex string\n return (hash >>> 0).toString(16);\n}\n","import type { IconName } from '@grafana/ui';\nimport type { ItemDataType, ContextItemData, UnknownItemData } from './types';\nimport { hash } from '../utils/hash';\n\nexport interface BaseParams {\n title?: string;\n // If true, the context item will not be shown in the context pills\n hidden?: boolean;\n // Image to display, if not selected, we fallback to icon\n img?: string;\n // Icon to display, if img is provided, icon is ignored\n icon?: IconName;\n /**\n * When true, bypasses size limits for fixed-size content that doesn't need truncation.\n *\n * Set `bypassLimits: true` for fixed-size content like:\n * - Static instructions or prompts\n * - Configuration that doesn't change\n * - Small, bounded metadata\n *\n * Keep `bypassLimits: false` (default) for variable-size content like:\n * - Query results, data tables, graphs\n * - User-generated content, logs\n * - Any content that could grow unexpectedly large\n *\n * @default false\n */\n bypassLimits?: boolean;\n}\n\nexport interface NodeDataParams extends BaseParams {\n id: string;\n type: ItemDataType;\n text?: string;\n}\n\nexport class NodeData {\n public id: string;\n public text = '';\n public type: ItemDataType;\n\n constructor(public params: NodeDataParams) {\n this.id = hash(params.id);\n this.type = params.type;\n }\n\n /** Whether size limits should be bypassed for this context item. Defaults to false. */\n get bypassLimits(): boolean {\n return this.params.bypassLimits ?? false;\n }\n\n formatForLLM(codeElementIds?: string[]): ContextItemData {\n return {\n type: this.type,\n codeElementIds,\n bypassLimits: this.bypassLimits,\n data: {\n name: this.params.text ?? '',\n text: this.params.text ?? '',\n } satisfies UnknownItemData,\n };\n }\n\n equals(other: unknown): boolean {\n if (!(other instanceof NodeData)) {\n return false;\n }\n return this.id === other.id && this.type === other.type;\n }\n}\n\nexport interface StructuredNodeDataParams extends BaseParams {\n data: Record<string, any>;\n}\n\nexport class StructuredNodeData extends NodeData {\n public data: Record<string, any>;\n constructor(params: StructuredNodeDataParams) {\n super({ ...params, id: hash(JSON.stringify(params.data)), type: 'structured' });\n this.data = params.data;\n }\n\n formatForLLM(codeElementIds?: string[]): ContextItemData {\n return {\n type: this.type,\n codeElementIds,\n bypassLimits: this.bypassLimits,\n data: this.data,\n };\n }\n}\n","import { type BaseParams, NodeData } from './base';\nimport type { AgentSkillItemData, ContextItemData } from './types';\n\n/**\n * Identity of one Agent Skill, as a turn carries it.\n *\n * Every field is supplied verbatim by the backend descriptor. Nothing here is\n * ever parsed to infer type, provider, capability or scope — `selectionId`,\n * `providerId` and `handle` are opaque strings that only ever get compared and\n * echoed back.\n */\nexport interface AgentSkillReference {\n /**\n * Server-issued selection id, copied verbatim from the catalog descriptor's\n * own `selectionId` field.\n *\n * The only identity the backend resolves an attachment by. A client must\n * never compute it: the server issues it as a SHA-256 over facts a client\n * does not own, and re-implementing that formula here would couple every\n * client to the server-side detail the opaque id exists to hide. So the value\n * is only ever read off a descriptor, stored, and sent back unchanged.\n */\n selectionId: string;\n /** Identity of the provider that owns the skill package. */\n providerId: string;\n /** Provider-local handle of the skill package. */\n handle: string;\n /** Content revision the attachment was pinned to. */\n revision: string;\n /** Display name shown on the attachment tag. */\n displayName: string;\n}\n\nexport interface CreateAgentSkillContextParams extends BaseParams, AgentSkillReference {}\n\n/**\n * The node id of an Agent Skill attachment: its `selectionId`, unchanged.\n *\n * Identity here is the server's, not a key composed locally. The backend reads\n * an attachment's identity out of this id, so anything composed on the client\n * is an id it cannot resolve — which is why this returns the selection id\n * rather than deriving one. The result is still never parsed: no reader may\n * take it apart to recover a provider, a handle, or anything else.\n *\n * Re-pinning a moved revision still updates an existing tag instead of adding a\n * second one, because a selection id names the package rather than the content\n * revision it currently serves.\n */\nexport function agentSkillNodeId(reference: Pick<AgentSkillReference, 'selectionId'>): string {\n return reference.selectionId;\n}\n\n/**\n * Context item for an Agent Skill attached to a turn with \"/\".\n *\n * Deliberately a distinct type from {@link SkillNodeData}: that one means a\n * Reference Library item, and attaching one can auto-approve the tools the\n * item declares. An Agent Skill grants no tool permission whatsoever — it\n * carries identity only, and the backend loads the body server-side. The two\n * must never be collapsed into one type, or the Reference Library's\n * allowed-tools behaviour would silently follow Agent Skills.\n */\nexport class AgentSkillNodeData extends NodeData {\n public selectionId: string;\n public providerId: string;\n public handle: string;\n public revision: string;\n public displayName: string;\n\n constructor(params: CreateAgentSkillContextParams) {\n super({\n ...params,\n id: agentSkillNodeId(params),\n type: 'agent_skill',\n text: params.displayName,\n });\n this.selectionId = params.selectionId;\n this.providerId = params.providerId;\n this.handle = params.handle;\n this.revision = params.revision;\n this.displayName = params.displayName;\n this.text = params.displayName;\n }\n\n /** The reference a request carries. Never a skill body — the backend preloads that. */\n get reference(): AgentSkillReference {\n return {\n selectionId: this.selectionId,\n providerId: this.providerId,\n handle: this.handle,\n revision: this.revision,\n displayName: this.displayName,\n };\n }\n\n formatForLLM(codeElementIds?: string[]): ContextItemData {\n return {\n type: this.type,\n codeElementIds,\n bypassLimits: this.bypassLimits,\n data: {\n name: this.displayName,\n text: this.text,\n selectionId: this.selectionId,\n providerId: this.providerId,\n handle: this.handle,\n revision: this.revision,\n displayName: this.displayName,\n } satisfies AgentSkillItemData,\n };\n }\n}\n","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"@grafana/runtime\");","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"react\");","import { useLocationService } from '@grafana/runtime';\nimport type { ChatContextItem } from './types';\nimport { useEffect, useState, useRef, useCallback } from 'react';\n\n// Extend window interface for the global registries. Declare this once for the\n// whole package: TypeScript 7 rejects the same index signature merged twice.\ndeclare global {\n interface Window {\n [key: string]: any;\n }\n}\n\nexport interface PageContextRegistration {\n id: string;\n urlPattern: string | RegExp;\n context: ChatContextItem[];\n}\n\n// Global registry key\nconst GLOBAL_REGISTRY_KEY = '__grafanaAssistantPageContextRegistry__';\n\n// Custom event for registry changes\nconst REGISTRY_CHANGE_EVENT = 'grafana-assistant:page-context-registry-changed';\n\n/**\n * Legacy event names for backward compatibility with the previous implementation.\n * These events are emitted alongside the new REGISTRY_CHANGE_EVENT to ensure\n * any existing code listening to the old events continues to work.\n *\n * @deprecated These event name is maintained for backward compatibility only.\n * TODO: Remove after old event-based approach is fully deprecated\n */\nconst LEGACY_REGISTRY_UPDATE_EVENT = 'grafana-assistant:page-context-update';\n/**\n * @deprecated These event name is maintained for backward compatibility only.\n * TODO: Remove after old event-based approach is fully deprecated\n */\nconst LEGACY_REGISTRY_REMOVE_EVENT = 'grafana-assistant:page-context-remove';\n/**\n * @deprecated These event name is maintained for backward compatibility only.\n * TODO: Remove after old event-based approach is fully deprecated\n */\nconst LEGACY_REGISTRY_SYNC_EVENT = 'grafana-assistant:page-context-sync';\n\n// Ensure global registry exists on window\nif (!window[GLOBAL_REGISTRY_KEY]) {\n window[GLOBAL_REGISTRY_KEY] = [];\n}\n\n// Get reference to the global registry\nfunction getPageContextRegistry(): PageContextRegistration[] {\n return window[GLOBAL_REGISTRY_KEY];\n}\n\n// TODO: Remove skipLegacyEvents parameter after old event-based approach is fully deprecated\nfunction setPageContextRegistry(newRegistry: PageContextRegistration[], skipLegacyEvents = false): void {\n window[GLOBAL_REGISTRY_KEY] = newRegistry;\n // Notify all listeners that the registry has changed\n window.dispatchEvent(new CustomEvent(REGISTRY_CHANGE_EVENT));\n\n // TODO: Remove this legacy event emission after old event-based approach is fully deprecated\n // Emit legacy sync event for backward compatibility (unless we're processing a legacy event)\n if (!skipLegacyEvents) {\n window.dispatchEvent(\n new CustomEvent(LEGACY_REGISTRY_SYNC_EVENT, {\n detail: { registry: newRegistry },\n })\n );\n }\n}\n\n/**\n * Bridge to handle legacy events from external apps using old versions of @grafana/assistant.\n * This ensures that registrations from external apps get synced into our window registry.\n *\n * TODO: Remove this entire bridge after old event-based approach is fully deprecated\n */\nlet legacyBridgeInitialized = false;\n\nfunction initializeLegacyEventBridge(): void {\n if (legacyBridgeInitialized) {\n return;\n }\n legacyBridgeInitialized = true;\n\n // Handle legacy update events (registration added or updated)\n window.addEventListener(LEGACY_REGISTRY_UPDATE_EVENT, (event: Event) => {\n const customEvent = event as CustomEvent;\n const registration = customEvent.detail as PageContextRegistration;\n\n if (!registration?.id) {\n return;\n }\n\n const currentRegistry = getPageContextRegistry();\n const existingIndex = currentRegistry.findIndex((r) => r.id === registration.id);\n\n if (existingIndex !== -1) {\n // Update existing registration\n const newRegistry = [...currentRegistry];\n newRegistry[existingIndex] = registration;\n setPageContextRegistry(newRegistry, true); // Skip legacy events to avoid loops\n } else {\n // Add new registration\n setPageContextRegistry([...currentRegistry, registration], true); // Skip legacy events to avoid loops\n }\n });\n\n // Handle legacy remove events (registration removed)\n window.addEventListener(LEGACY_REGISTRY_REMOVE_EVENT, (event: Event) => {\n const customEvent = event as CustomEvent;\n const id = customEvent.detail?.id;\n\n if (!id) {\n return;\n }\n\n const currentRegistry = getPageContextRegistry();\n const index = currentRegistry.findIndex((r) => r.id === id);\n\n if (index !== -1) {\n const newRegistry = currentRegistry.filter((_, i) => i !== index);\n setPageContextRegistry(newRegistry, true); // Skip legacy events to avoid loops\n }\n });\n\n // Handle legacy sync events (entire registry sync from external app)\n window.addEventListener(LEGACY_REGISTRY_SYNC_EVENT, (event: Event) => {\n const customEvent = event as CustomEvent;\n const incomingRegistry = customEvent.detail?.registry as PageContextRegistration[];\n\n if (!Array.isArray(incomingRegistry)) {\n return;\n }\n\n const currentRegistry = getPageContextRegistry();\n const currentIds = new Set(currentRegistry.map((r) => r.id));\n\n // Merge: add any registrations from external app that we don't have\n const newRegistrations = incomingRegistry.filter((r) => !currentIds.has(r.id));\n\n if (newRegistrations.length > 0) {\n setPageContextRegistry([...currentRegistry, ...newRegistrations], true); // Skip legacy events to avoid loops\n }\n });\n}\n\n// TODO: Remove this initialization after old event-based approach is fully deprecated\n// Initialize the bridge on module load\ninitializeLegacyEventBridge();\n\n/**\n * Registers context items for specific pages based on URL patterns.\n * Returns a setter function to update the context dynamically, similar to useState.\n *\n * Multiple registrations with the same URL pattern are allowed and will all be merged\n * when the pattern matches. Each call creates a new independent registration.\n *\n * @param urlPattern - URL pattern (string or RegExp) to match against page URLs\n * @param initialContext - *Initial* array of ContextItems to provide when the pattern matches. IMPORTANT: will be overwritten when setContext is used to update the context.\n * @returns A setter function to update the context, with an unregister method attached\n */\nexport function providePageContext(\n urlPattern: string | RegExp,\n initialContext: ChatContextItem[]\n): ((context: ChatContextItem[]) => void) & { unregister: () => void } {\n // Validate URL pattern at registration time (only warn once, not on every match)\n validateUrlPattern(urlPattern);\n\n // Always create a new registration to allow multiple providers with the same URL pattern\n const registration: PageContextRegistration = {\n id: generateRegistrationId(),\n urlPattern,\n context: [...initialContext],\n };\n\n const registry = getPageContextRegistry();\n setPageContextRegistry([...registry, registration]);\n\n // TODO: Remove this legacy event emission after old event-based approach is fully deprecated\n // Emit legacy update event for backward compatibility\n window.dispatchEvent(\n new CustomEvent(LEGACY_REGISTRY_UPDATE_EVENT, {\n detail: registration,\n })\n );\n\n // Create setter function that can update the context\n const setContext = (newContext: ChatContextItem[]) => {\n const currentRegistry = getPageContextRegistry();\n const index = currentRegistry.findIndex((reg) => reg.id === registration.id);\n if (index !== -1) {\n const newRegistry = [...currentRegistry];\n newRegistry[index] = { ...newRegistry[index], context: [...newContext] };\n setPageContextRegistry(newRegistry);\n\n // TODO: Remove this legacy event emission after old event-based approach is fully deprecated\n // Emit legacy update event for backward compatibility\n window.dispatchEvent(\n new CustomEvent(LEGACY_REGISTRY_UPDATE_EVENT, {\n detail: newRegistry[index],\n })\n );\n }\n };\n\n // Add unregister method to the setter\n setContext.unregister = () => {\n const currentRegistry = getPageContextRegistry();\n const index = currentRegistry.findIndex((reg) => reg.id === registration.id);\n if (index !== -1) {\n const newRegistry = currentRegistry.filter((_, i) => i !== index);\n setPageContextRegistry(newRegistry);\n\n // TODO: Remove this legacy event emission after old event-based approach is fully deprecated\n // Emit legacy remove event for backward compatibility\n window.dispatchEvent(\n new CustomEvent(LEGACY_REGISTRY_REMOVE_EVENT, {\n detail: { id: registration.id },\n })\n );\n }\n };\n\n return setContext;\n}\n\nconst empty: ChatContextItem[] = [];\n\n/**\n * React hook for providing page context that automatically cleans up on unmount.\n * This is the recommended way to use page context in React components.\n *\n * @param urlPattern - URL pattern (string or RegExp) to match against page URLs\n * @param initialContext - Initial array of ContextItems to provide when the pattern matches. IMPORTANT: will be overwritten when setContext is used to update the context.\n * @returns A setter function to update the context\n */\nexport function useProvidePageContext(\n urlPattern: string | RegExp,\n initialContext: ChatContextItem[] = empty\n): (context: ChatContextItem[]) => void {\n const setContextRef = useRef<ReturnType<typeof providePageContext> | undefined>(undefined);\n const pendingUpdate = useRef<ChatContextItem[] | undefined>(undefined);\n const isModified = useRef(false);\n\n // Create or update the registration when dependencies change\n // biome-ignore lint/correctness/useExhaustiveDependencies: initialContext is intentionally excluded to prevent re-registering on every render; updates are handled by the second effect\n useEffect(() => {\n // Reset isModified flag when urlPattern changes so that initialContext updates\n // are applied to the new registration until manually modified again\n isModified.current = false;\n\n // If we have pending updates, prefer those over initialContext as they represent\n // newer state from child components\n const contextToUse = pendingUpdate.current !== undefined ? pendingUpdate.current : initialContext;\n setContextRef.current = providePageContext(urlPattern, contextToUse);\n\n // Clear pending update as it's now applied\n if (pendingUpdate.current !== undefined) {\n pendingUpdate.current = undefined;\n }\n\n // Cleanup on unmount or dependency change\n return () => {\n setContextRef.current?.unregister();\n setContextRef.current = undefined;\n };\n // We intentionally exclude initialContext from deps to prevent re-registering on every render\n // Updates to initialContext are handled by the second effect\n }, [urlPattern]);\n\n // Update context when initialContext changes, BUT only if we haven't manually modified it.\n // This prevents unstable initialContext props (e.g. passing [] inline) from overwriting\n // updates made via setContext by child components.\n useEffect(() => {\n if (!isModified.current && setContextRef.current) {\n setContextRef.current(initialContext);\n }\n }, [initialContext]);\n\n // Return a stable setter function\n const setContext = useCallback((newContext: ChatContextItem[]) => {\n isModified.current = true;\n if (setContextRef.current) {\n setContextRef.current(newContext);\n } else {\n pendingUpdate.current = newContext;\n }\n }, []);\n\n return setContext;\n}\n\n/**\n * Gets all context items that match the current URL.\n *\n * @param currentUrl - The current page URL to match against\n * @param registrations - Array of registrations to match against\n * @returns Array of ChatContextItem from all matching registrations\n */\nfunction getActivePageContext(currentUrl: string): ChatContextItem[] {\n if (!currentUrl) {\n return [];\n }\n\n const activeContext: ChatContextItem[] = [];\n const registry = getPageContextRegistry();\n\n for (const registration of registry) {\n if (matchesUrlPattern(currentUrl, registration.urlPattern)) {\n activeContext.push(...registration.context);\n }\n }\n\n return activeContext;\n}\n\nexport function usePageContext(\n options: { allowQuestions: boolean; allowComponents: boolean } = { allowQuestions: false, allowComponents: false }\n): ChatContextItem[] {\n const location = useLocationService();\n const initialPathname = location.getLocation().pathname;\n const [pageContext, setPageContext] = useState<ChatContextItem[]>(() => getActivePageContext(initialPathname));\n const currentPathnameRef = useRef(initialPathname);\n\n useEffect(() => {\n // Function to update context based on current location and registry\n const updateContext = () => {\n const pathname = location.getLocation().pathname;\n const context = getActivePageContext(pathname);\n setPageContext(context);\n };\n\n // Handle registry changes\n const handleRegistryChange = () => {\n updateContext();\n };\n\n // Subscribe to location changes\n const locationSub = location.getLocationObservable().subscribe((loc: { pathname: string }) => {\n const pathname = loc.pathname;\n if (pathname !== currentPathnameRef.current) {\n currentPathnameRef.current = pathname;\n updateContext();\n }\n });\n\n // Listen for registry changes\n window.addEventListener(REGISTRY_CHANGE_EVENT, handleRegistryChange);\n\n // TODO: Remove these legacy event listeners after old event-based approach is fully deprecated\n // Listen for legacy events for backward compatibility\n window.addEventListener(LEGACY_REGISTRY_UPDATE_EVENT, handleRegistryChange);\n window.addEventListener(LEGACY_REGISTRY_REMOVE_EVENT, handleRegistryChange);\n window.addEventListener(LEGACY_REGISTRY_SYNC_EVENT, handleRegistryChange);\n\n // Initial update\n updateContext();\n\n return () => {\n locationSub.unsubscribe();\n window.removeEventListener(REGISTRY_CHANGE_EVENT, handleRegistryChange);\n // TODO: Remove these legacy event listener removals after old event-based approach is fully deprecated\n window.removeEventListener(LEGACY_REGISTRY_UPDATE_EVENT, handleRegistryChange);\n window.removeEventListener(LEGACY_REGISTRY_REMOVE_EVENT, handleRegistryChange);\n window.removeEventListener(LEGACY_REGISTRY_SYNC_EVENT, handleRegistryChange);\n };\n }, [location]);\n\n let filteredContext = pageContext;\n\n if (!options.allowQuestions) {\n filteredContext = filteredContext.filter((item) => item.node.data?.type !== 'question');\n }\n\n if (!options.allowComponents) {\n filteredContext = filteredContext.filter((item) => item.node.data?.type !== 'component');\n }\n\n return filteredContext;\n}\n\nexport function generateRegistrationId(prefix = 'page-context'): string {\n return `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;\n}\n\n/**\n * Validates the URL pattern at registration time and logs warnings for problematic patterns.\n * This is called once during registration, not on every URL match.\n */\nfunction validateUrlPattern(pattern: string | RegExp): void {\n if (pattern instanceof RegExp) {\n // Check if RegExp pattern matches everything (e.g., /.*/, /^.*$/)\n // This is intentional for global contexts (e.g., components), so we use a scoped warning\n const source = pattern.source;\n if (source === '.*' || source === '^.*$' || source === '^.*' || source === '.*$') {\n // Note: This is expected for global contexts like provideComponents.\n // The warning is intentionally omitted here since it's a valid use case.\n // If you want to warn for specific cases, filter them here.\n }\n return;\n }\n\n if (typeof pattern === 'string') {\n // Validate urlPattern - log error if empty string is passed\n if (!pattern || pattern.trim() === '') {\n console.warn(\n 'useProvidePageContext: Empty string passed as urlPattern. This will cause the context to not match any pages.'\n );\n return;\n }\n\n // Check if the pattern matches everything (e.g., ** becomes ^.*$)\n if (pattern === '**') {\n // Note: This is expected for global contexts.\n // The warning is intentionally omitted here since it's a valid use case.\n }\n }\n}\n\nfunction matchesUrlPattern(url: string, pattern: string | RegExp): boolean {\n if (pattern instanceof RegExp) {\n return pattern.test(url);\n }\n\n // For string patterns, support simple wildcards\n if (typeof pattern === 'string') {\n // Empty pattern never matches\n if (!pattern || pattern.trim() === '') {\n return false;\n }\n\n // Convert simple wildcard pattern to regex\n // * matches any characters except /, ** matches any path segments\n // Handle ** first with a placeholder to avoid conflicts\n const regexPattern = pattern\n .replace(/\\*\\*/g, '\\u0000DOUBLE_STAR\\u0000') // Temporary placeholder for **\n .replace(/\\*/g, '[^/]*') // * becomes [^/]*\n // biome-ignore lint/suspicious/noControlCharactersInRegex: intentional \\u0000 null byte used as placeholder to avoid glob pattern conflicts\n .replace(/\\u0000DOUBLE_STAR\\u0000/g, '.*') // Replace placeholder with .*\n .replace(/\\?/g, '.'); // ? becomes .\n\n const finalRegex = `^${regexPattern}$`;\n const regex = new RegExp(finalRegex);\n return regex.test(url);\n }\n\n return false;\n}\n\n/**\n * Test utility function to clear all registrations from the registry.\n * This should only be used in tests to ensure a clean slate between test runs.\n *\n * @internal This is for testing purposes only\n */\nexport function __clearPageContextRegistryForTesting(): void {\n setPageContextRegistry([]);\n}\n","import { type ComponentType, useMemo } from 'react';\nimport { type BaseParams, NodeData } from './base';\nimport type { ContextItemData, ComponentItemData } from './types';\nimport { providePageContext, usePageContext } from './page';\nimport { createAssistantContextItem } from './chat';\n\nexport type ComponentImplementation = ComponentType<any>;\nexport type NamedComponents = Record<string, ComponentImplementation>;\n\n/**\n * Type used to create a component context item.\n */\nexport interface CreateComponentContextParams extends BaseParams {\n components: Record<string, ComponentType<any>>;\n prompt: string;\n namespace?: string;\n}\n\nexport class ComponentNodeData extends NodeData {\n public components: Record<string, ComponentType<any>>;\n public prompt: string;\n public namespace: string;\n\n constructor(params: CreateComponentContextParams) {\n const namespace = params.namespace || 'components';\n super({ ...params, id: `${namespace}-${Object.keys(params.components).join('-')}`, type: 'component' });\n this.components = params.components;\n this.prompt = params.prompt;\n this.namespace = namespace;\n }\n\n formatForLLM(codeElementIds?: string[]): ContextItemData {\n return {\n type: this.type,\n codeElementIds,\n data: {\n name: `Custom UI components (${this.namespace})`,\n prompt: this.prompt\n ? this.prompt +\n '\\n\\nIMPORTANT: The instructions and components described above are scoped to this specific context item only. Do not apply them to unrelated queries or components.'\n : '',\n } satisfies Omit<ComponentItemData, 'components' | 'text' | 'namespace'>,\n };\n }\n}\n\n/**\n * React hook that provides all components available globally.\n * Components are available everywhere, regardless of URL patterns.\n *\n * @returns Object containing all components available globally, keyed by namespace.componentName\n */\nexport function usePageComponents(): Record<string, ComponentImplementation> {\n const pageContext = usePageContext({ allowComponents: true, allowQuestions: false });\n\n // Use useMemo to avoid recreating the components object on every render\n const components = useMemo(() => {\n const allComponents: Record<string, ComponentImplementation> = {};\n\n // Filter for component context items and extract their components\n for (const item of pageContext.filter((item) => item.node.data?.components)) {\n const componentData = item.node.data;\n if (componentData?.components && Object.keys(componentData.components).length > 0) {\n const namespace = componentData.namespace || componentData.name || 'components';\n\n // Add each component with namespace_componentName format\n for (const [componentName, component] of Object.entries(componentData.components)) {\n allComponents[`${namespace}_${componentName}`] = component as ComponentImplementation;\n }\n }\n }\n\n return allComponents;\n }, [pageContext]);\n\n return components;\n}\n\n/**\n * Provide components to the assistant.\n *\n * Components are always available globally, but the prompt is only applied when the URL pattern matches.\n *\n * For catch-all URL patterns, returns a setter that takes a context array.\n * For specific URL patterns, returns a setter that takes components and prompt separately.\n *\n * @param prompt - The prompt to use for the components (only applied when URL matches).\n * @param namespace - The namespace to use for the components.\n * @param components - The components to provide (always available).\n * @param urlPattern - The URL pattern to match for the prompt (components are always available).\n * @returns A setter function to update the context, with an unregister method attached\n */\nexport function provideComponents(\n prompt: string,\n namespace: string,\n components: Record<string, ComponentImplementation>,\n urlPattern: string | RegExp = /.*/\n): ((newComponents: Record<string, ComponentImplementation>, newPrompt: string) => void) & { unregister: () => void } {\n // Check if the URL pattern is catch-all (.*) - if so, register everything together\n const isCatchAll = (pattern: string | RegExp) => {\n if (pattern instanceof RegExp) {\n return pattern.source === '.*' && pattern.flags === '';\n }\n return pattern === '.*' || pattern === '/.*/';\n };\n\n if (isCatchAll(urlPattern)) {\n // If pattern is catch-all, register components and prompt together globally\n const setContext = providePageContext(/.*/, [\n createAssistantContextItem('component', {\n components,\n prompt,\n namespace,\n }),\n ]);\n\n // Create a wrapper setter that matches the expected signature\n const setter = (newComponents: Record<string, ComponentImplementation>, newPrompt: string) => {\n setContext([\n createAssistantContextItem('component', {\n components: newComponents,\n prompt: newPrompt,\n namespace,\n }),\n ]);\n };\n\n // Attach unregister method\n setter.unregister = setContext.unregister;\n\n return setter;\n }\n\n // For specific URL patterns, separate components (global) from prompt (URL-specific)\n const globalComponents = providePageContext(/.*/, [\n createAssistantContextItem('component', {\n components,\n prompt: '', // No prompt for global components\n namespace,\n }),\n ]);\n\n // Only register prompt for specific URL pattern\n const promptContext = providePageContext(urlPattern, [\n createAssistantContextItem('component', {\n components: {}, // No components, just prompt\n prompt,\n namespace,\n }),\n ]);\n\n // Return a setter that properly separates components and prompt\n // When updating, we extract components and prompt from the new data and update each registration appropriately\n const setter = (newComponents: Record<string, ComponentImplementation>, newPrompt: string) => {\n // Update global components registration with new components (but empty prompt)\n globalComponents([\n createAssistantContextItem('component', {\n components: newComponents,\n prompt: '', // No prompt for global components\n namespace,\n }),\n ]);\n\n // Update URL-specific registration with new prompt (but empty components)\n promptContext([\n createAssistantContextItem('component', {\n components: {}, // No components, just prompt\n prompt: newPrompt,\n namespace,\n }),\n ]);\n };\n\n // Attach unregister method that cleans up both registrations\n setter.unregister = () => {\n globalComponents.unregister();\n promptContext.unregister();\n };\n\n return setter;\n}\n","import { type BaseParams, NodeData } from './base';\nimport type { ContextItemData, DashboardItemData, FolderItemData } from './types';\n\nexport interface CreateDashboardContextParams extends BaseParams {\n dashboardUid: string;\n dashboardTitle: string;\n folderUid?: string;\n folderTitle?: string;\n}\n\nexport interface CreateFolderContextParams extends BaseParams {\n folderUid: string;\n folderTitle: string;\n}\n\nexport class DashboardNodeData extends NodeData {\n public dashboardUid: string;\n public dashboardTitle: string;\n public folderUid?: string;\n public folderTitle?: string;\n\n constructor(params: CreateDashboardContextParams) {\n super({ ...params, id: params.dashboardUid, type: 'dashboard' });\n this.dashboardUid = params.dashboardUid;\n this.dashboardTitle = params.dashboardTitle;\n this.folderUid = params.folderUid;\n this.folderTitle = params.folderTitle;\n this.text = params.dashboardTitle;\n }\n\n formatForLLM(codeElementIds?: string[]): ContextItemData {\n return {\n type: this.type,\n codeElementIds,\n bypassLimits: this.bypassLimits,\n data: {\n name: this.dashboardTitle,\n dashboardUid: this.dashboardUid,\n dashboardTitle: this.dashboardTitle,\n folderUid: this.folderUid,\n folderTitle: this.folderTitle,\n text: this.text,\n } satisfies DashboardItemData,\n };\n }\n}\n\nexport class FolderNodeData extends NodeData {\n public folderUid: string;\n public folderTitle: string;\n public text = '';\n\n constructor(params: CreateFolderContextParams) {\n super({ ...params, id: params.folderUid, type: 'dashboard_folder' });\n this.folderUid = params.folderUid;\n this.folderTitle = params.folderTitle;\n this.text = params.folderTitle;\n }\n\n formatForLLM(codeElementIds?: string[]): ContextItemData {\n return {\n type: this.type,\n codeElementIds,\n bypassLimits: this.bypassLimits,\n data: {\n name: this.folderTitle,\n folderUid: this.folderUid,\n folderTitle: this.folderTitle,\n text: this.text,\n } satisfies FolderItemData,\n };\n }\n}\n","import { type BaseParams, NodeData } from './base';\nimport type { DatasourceMeta } from './factory';\nimport type { ContextItemData, DatasourceItemData } from './types';\n\n/**\n * Type used to create a datasource context item.\n *\n * All required attributes will be inferred from the datasources uid.\n */\nexport interface CreateDatasourceContextParams extends BaseParams {\n datasourceUid: string;\n}\n\nexport class DatasourceNodeData extends NodeData {\n public datasourceUid: string;\n public datasourceType: string;\n public datasourceName: string;\n public img?: string;\n\n constructor(params: CreateDatasourceContextParams & DatasourceMeta) {\n super({ ...params, id: params.datasourceUid, type: 'datasource' });\n this.datasourceUid = params.datasourceUid;\n this.datasourceType = params.datasourceType;\n this.datasourceName = params.datasourceName;\n this.img = params.img;\n this.text = params.datasourceName;\n }\n\n formatForLLM(codeElementIds?: string[]): ContextItemData {\n return {\n type: this.type,\n codeElementIds,\n bypassLimits: this.bypassLimits,\n data: {\n name: this.datasourceName,\n uid: this.datasourceUid,\n type: this.datasourceType,\n text: this.text,\n } satisfies DatasourceItemData,\n };\n }\n}\n","import { type BaseParams, NodeData } from './base';\nimport type { ContextItemData, EntityItemData } from './types';\n\n/**\n * Type used to create an entity context item.\n */\nexport interface CreateEntityContextParams extends BaseParams {\n type: string;\n name: string;\n scope?: {\n env?: string;\n site?: string;\n namespace?: string;\n };\n properties?: Record<string, any>;\n}\n\nexport class EntityNodeData extends NodeData {\n public entityType: string;\n public name: string;\n public scope?: {\n env?: string;\n site?: string;\n namespace?: string;\n };\n public properties?: Record<string, any>;\n\n constructor(params: CreateEntityContextParams) {\n super({\n id: `${params.type}-${params.name}-${[params.scope?.env, params.scope?.site, params.scope?.namespace].filter(Boolean).join('-')}`,\n type: 'entity',\n title: params.title,\n hidden: params.hidden,\n img: params.img,\n icon: params.icon,\n text: params.name,\n });\n this.entityType = params.type;\n this.name = params.name;\n this.scope = params.scope;\n this.properties = params.properties;\n this.text = params.name;\n }\n\n formatForLLM(codeElementIds?: string[]): ContextItemData {\n return {\n type: 'entity',\n codeElementIds,\n bypassLimits: this.bypassLimits,\n data: {\n name: this.name,\n text: this.text,\n type: this.entityType,\n scope: this.scope,\n properties: this.properties,\n } satisfies EntityItemData,\n };\n }\n}\n","import { type BaseParams, NodeData } from './base';\nimport type { DatasourceMeta } from './factory';\nimport type { ContextItemData, LabelNameItemData, LabelValueItemData } from './types';\n\nexport interface CreateLabelNameContextParams extends BaseParams {\n datasourceUid: string;\n labelName: string;\n}\n\nexport interface CreateLabelValueContextParams extends CreateLabelNameContextParams {\n labelValue: string;\n /** Filter operator (e.g., '=', '!=', '=~', '!~'). Defaults to '=' if not specified */\n operator?: string;\n}\n\nexport class LabelNameNodeData extends NodeData {\n public datasourceUid: string;\n public datasourceType: string;\n public datasourceName: string;\n public labelName: string;\n public img?: string;\n\n constructor(params: CreateLabelNameContextParams & DatasourceMeta) {\n super({ ...params, id: `${params.datasourceUid}-${params.labelName}`, type: 'label_name' });\n this.datasourceUid = params.datasourceUid;\n this.datasourceType = params.datasourceType;\n this.datasourceName = params.datasourceName;\n this.labelName = params.labelName;\n this.text = params.labelName;\n this.img = params.img;\n }\n\n formatForLLM(codeElementIds?: string[]): ContextItemData {\n return {\n type: this.type,\n codeElementIds,\n bypassLimits: this.bypassLimits,\n data: {\n name: this.labelName,\n datasourceUid: this.datasourceUid,\n datasourceType: this.datasourceType,\n datasourceName: this.datasourceName,\n labelName: this.labelName,\n text: this.text,\n } satisfies LabelNameItemData,\n };\n }\n}\n\nexport class LabelValueNodeData extends NodeData {\n public datasourceUid: string;\n public datasourceType: string;\n public datasourceName: string;\n public labelName: string;\n public labelValue: string;\n public img?: string;\n public operator: string;\n\n constructor(params: CreateLabelValueContextParams & DatasourceMeta) {\n super({\n ...params,\n id: `${params.datasourceUid}-${params.labelName}-${params.labelValue}-${params.operator || '='}`,\n type: 'label_value',\n });\n this.datasourceUid = params.datasourceUid;\n this.datasourceType = params.datasourceType;\n this.datasourceName = params.datasourceName;\n this.labelName = params.labelName;\n this.labelValue = params.labelValue;\n this.text = params.labelValue;\n this.img = params.img;\n this.operator = params.operator || '=';\n }\n\n formatForLLM(codeElementIds?: string[]): ContextItemData {\n return {\n type: this.type,\n codeElementIds,\n bypassLimits: this.bypassLimits,\n data: {\n name: this.labelValue,\n datasourceUid: this.datasourceUid,\n datasourceType: this.datasourceType,\n datasourceName: this.datasourceName,\n labelName: this.labelName,\n labelValue: this.labelValue,\n text: this.text,\n operator: this.operator,\n } satisfies LabelValueItemData,\n };\n }\n}\n","import { getDataSourceSrv } from '@grafana/runtime';\nimport { NodeData, type NodeDataParams, StructuredNodeData, type StructuredNodeDataParams } from './base';\nimport { ComponentNodeData, type CreateComponentContextParams } from './component';\nimport {\n DashboardNodeData,\n FolderNodeData,\n type CreateDashboardContextParams,\n type CreateFolderContextParams,\n} from './dashboard';\nimport { DatasourceNodeData, type CreateDatasourceContextParams } from './datasource';\nimport { EntityNodeData, type CreateEntityContextParams } from './entity';\nimport {\n LabelNameNodeData,\n LabelValueNodeData,\n type CreateLabelNameContextParams,\n type CreateLabelValueContextParams,\n} from './label';\n\n/**\n * registry to handle the type mappings between ItemData type, params and node data\n */\nexport type ContextTypeRegistry = {\n datasource: { params: CreateDatasourceContextParams; node: DatasourceNodeData };\n label_name: { params: CreateLabelNameContextParams; node: LabelNameNodeData };\n label_value: { params: CreateLabelValueContextParams; node: LabelValueNodeData };\n dashboard: { params: CreateDashboardContextParams; node: DashboardNodeData };\n dashboard_folder: { params: CreateFolderContextParams; node: FolderNodeData };\n structured: { params: StructuredNodeDataParams; node: StructuredNodeData };\n component: { params: CreateComponentContextParams; node: ComponentNodeData };\n entity: { params: CreateEntityContextParams; node: EntityNodeData };\n unknown: { params: NodeDataParams; node: NodeData };\n};\n\nexport type DatasourceMeta = {\n datasourceType: string;\n datasourceName: string;\n img?: string;\n};\n\n/**\n * Helper function to get datasource type from datasource UID\n */\nfunction getDatasourceMeta(datasourceUid: string): DatasourceMeta {\n // biome-ignore lint/plugin/no-get-datasource-srv: existing use baselined for MT migration (#13386)\n const datasourceInstance = getDataSourceSrv().getInstanceSettings(datasourceUid);\n return {\n datasourceType: datasourceInstance?.type ?? 'unknown',\n datasourceName: datasourceInstance?.name ?? datasourceUid,\n img: datasourceInstance?.meta?.info?.logos?.small,\n };\n}\n\n/**\n * Creates context nodes based on type with full type safety using generics\n */\nexport function createContextByType<T extends keyof ContextTypeRegistry>(\n type: T,\n params: ContextTypeRegistry[T]['params']\n): ContextTypeRegistry[T]['node'] {\n switch (type) {\n case 'datasource':\n return new DatasourceNodeData({\n ...(params as CreateDatasourceContextParams),\n ...getDatasourceMeta((params as CreateDatasourceContextParams).datasourceUid),\n });\n case 'label_name':\n return new LabelNameNodeData({\n ...(params as CreateLabelNameContextParams),\n ...getDatasourceMeta((params as CreateLabelNameContextParams).datasourceUid),\n });\n case 'label_value':\n return new LabelValueNodeData({\n ...(params as CreateLabelValueContextParams),\n ...getDatasourceMeta((params as CreateLabelValueContextParams).datasourceUid),\n });\n case 'dashboard':\n return new DashboardNodeData(params as CreateDashboardContextParams);\n case 'dashboard_folder':\n return new FolderNodeData(params as CreateFolderContextParams);\n case 'structured':\n return new StructuredNodeData(params as StructuredNodeDataParams);\n case 'component':\n return new ComponentNodeData({\n ...(params as CreateComponentContextParams),\n hidden: true,\n });\n case 'entity':\n return new EntityNodeData(params as CreateEntityContextParams);\n case 'unknown':\n return new NodeData(params as NodeDataParams);\n default:\n console.error(`Unknown context type: ${type}`);\n return new NodeData(params as NodeDataParams);\n }\n}\n","import type { IconName } from '@grafana/ui';\nimport { type NodeData, StructuredNodeData } from './base';\nimport { createContextByType, type ContextTypeRegistry } from './factory';\nimport type { ChatContextItem, ItemDataType } from './types';\n\nconst defaultIcons: Record<ItemDataType, IconName> = {\n datasource: 'database',\n label_name: 'database',\n label_value: 'database',\n dashboard: 'dashboard',\n dashboard_folder: 'folder',\n unknown: 'circle-mono',\n structured: 'gf-grid',\n component: 'gf-grid',\n entity: 'asserts',\n skill: 'play',\n agent_skill: 'ai-sparkle',\n};\n\nfunction getTitleFromContextNode(nodeData: NodeData | StructuredNodeData): string {\n return nodeData instanceof StructuredNodeData\n ? nodeData.formatForLLM().data.name\n : (nodeData.text ?? 'Given Context');\n}\n\nfunction getImgFromContextNode(nodeData: NodeData | StructuredNodeData): string | undefined {\n if ('img' in nodeData) {\n return (nodeData as { img?: string }).img;\n }\n return undefined;\n}\n\n/**\n * Creates a new chat context item that can be added to conversations.\n *\n * This function creates structured context items that provide additional information\n * to the AI assistant during conversations. Context items can include:\n * - Datasources (metrics, logs, traces)\n * - Labels and their values\n * - Dashboards and folders\n * - Structured data objects\n *\n * The created context item includes display metadata (title, icon, image) and\n * the underlying data that will be formatted and sent to the LLM when the\n * context is included in a conversation.\n *\n * @param type - The type of context to create (Datasource, Label, Dashboard etc.)\n * @param params - Type-specific parameters for creating the context item\n * @returns A ChatContextItem that can be added to conversation context\n *\n * @example\n * ```typescript\n * // Create a context that will be passed into the function triggering an assistant open\n * openAssistant({\n * ...\n * origin: 'my-feature',\n * context: [\n * createAssistantContextItem('datasource', {\n * datasourceUid: datasource.uid,\n * img: datasource.meta?.info?.logos?.small,\n * }),\n * ],\n * });\n * ```\n */\nexport function createAssistantContextItem<T extends keyof ContextTypeRegistry>(\n type: T,\n params: ContextTypeRegistry[T]['params']\n): ChatContextItem {\n const nodeData = createContextByType(type, params);\n const defaultTitle = params.title ?? getTitleFromContextNode(nodeData);\n const img = params.img ?? getImgFromContextNode(nodeData);\n return {\n node: {\n id: nodeData.id,\n name: defaultTitle,\n img,\n icon: params.icon ?? defaultIcons[type],\n navigable: false,\n selectable: true,\n data: nodeData,\n },\n occurrences: [],\n };\n}\n","import { type BaseParams, NodeData } from './base';\nimport type { ContextItemData, SkillItemData } from './types';\n\nexport interface CreateSkillContextParams extends BaseParams {\n skillId: string;\n skillName: string;\n}\n\nexport class SkillNodeData extends NodeData {\n public skillId: string;\n public skillName: string;\n\n constructor(params: CreateSkillContextParams) {\n super({\n ...params,\n id: params.skillId,\n type: 'skill',\n text: params.skillName,\n });\n this.skillId = params.skillId;\n this.skillName = params.skillName;\n this.text = params.skillName;\n }\n\n formatForLLM(codeElementIds?: string[]): ContextItemData {\n return {\n type: this.type,\n codeElementIds,\n bypassLimits: this.bypassLimits,\n data: {\n name: this.skillName,\n skillId: this.skillId,\n skillName: this.skillName,\n text: this.text,\n } satisfies SkillItemData,\n };\n }\n}\n","import { useMemo } from 'react';\nimport type { ChatContextItem } from './types';\nimport { providePageContext, useProvidePageContext, usePageContext, generateRegistrationId } from './page';\n\nexport interface Question {\n prompt: string;\n title?: string;\n context?: ChatContextItem[];\n}\n\nexport interface QuestionRegistration {\n id: string;\n urlPattern: string | RegExp;\n questions: Question[];\n}\n\n/**\n * Registers questions for specific pages based on URL patterns.\n * Returns a setter function to update the questions dynamically, similar to useState.\n *\n * Multiple registrations with the same URL pattern are allowed and will all be merged\n * when the pattern matches. Each call creates a new independent registration.\n *\n * @param urlPattern - URL pattern (string or RegExp) to match against page URLs\n * @param initialQuestions - Initial array of questions to provide when the pattern matches\n * @returns A setter function to update the questions, with an unregister method attached\n */\nexport function provideQuestions(\n urlPattern: string | RegExp,\n initialQuestions: Question[]\n): ((questions: Question[]) => void) & { unregister: () => void } {\n // Generate a unique registration ID to prevent collisions when multiple registrations exist\n const registrationId = generateRegistrationId('question');\n\n // Convert questions to ChatContextItem format for the underlying system\n const convertQuestionsToContext = (questions: Question[]): ChatContextItem[] => {\n return questions.map((question, index) => ({\n node: {\n id: `question-${registrationId}-${index}`,\n name: question.title || question.prompt,\n navigable: false,\n selectable: true,\n icon: 'question-circle',\n data: {\n type: 'question',\n prompt: question.prompt,\n title: question.title,\n context: question.context || [],\n },\n },\n occurrences: [],\n }));\n };\n\n // Use the existing providePageContext system\n const setContext = providePageContext(urlPattern, convertQuestionsToContext(initialQuestions));\n\n // Create a wrapper that converts between questions and context\n const setQuestions = (newQuestions: Question[]) => {\n setContext(convertQuestionsToContext(newQuestions));\n };\n\n // Add unregister method\n setQuestions.unregister = setContext.unregister;\n\n return setQuestions;\n}\n\n/**\n * React hook for providing questions that automatically cleans up on unmount.\n * This is the recommended way to use questions in React components.\n *\n * @param urlPattern - URL pattern (string or RegExp) to match against page URLs\n * @param initialQuestions - Initial array of questions to provide when the pattern matches\n * @returns A setter function to update the questions\n */\nexport function useProvideQuestions(\n urlPattern: string | RegExp,\n initialQuestions: Question[] = []\n): (questions: Question[]) => void {\n // Generate a stable unique registration ID per component instance to prevent collisions\n const registrationId = useMemo(\n () => generateRegistrationId('question'),\n [] // Empty deps = generated once per component instance\n );\n\n // Convert questions to ChatContextItem format for the underlying system\n const convertQuestionsToContext = (questions: Question[]): ChatContextItem[] => {\n return questions.map((question, index) => ({\n node: {\n id: `question-${registrationId}-${index}`,\n name: question.title ?? question.prompt,\n navigable: false,\n selectable: true,\n icon: 'question-circle',\n data: {\n type: 'question',\n prompt: question.prompt,\n title: question.title,\n context: question.context || [],\n },\n },\n occurrences: [],\n }));\n };\n\n // Use the existing useProvidePageContext system\n const setContext = useProvidePageContext(urlPattern, convertQuestionsToContext(initialQuestions));\n\n // Create a wrapper that converts between questions and context\n const setQuestions = (newQuestions: Question[]) => {\n setContext(convertQuestionsToContext(newQuestions));\n };\n\n return setQuestions;\n}\n\n/**\n * React hook to get all questions that match the current URL.\n * This filters the page context to only return question-type items.\n *\n * @returns Array of questions from all matching registrations\n */\nexport function useQuestions(): Question[] {\n const pageContext = usePageContext({ allowQuestions: true, allowComponents: false });\n\n // Filter and convert context items to questions\n return convertContextToQuestions(pageContext);\n}\n\nconst convertContextToQuestions = (contextItems: ChatContextItem[]): Question[] => {\n return contextItems\n .filter((item) => item.node.data?.type === 'question')\n .map((item) => ({\n prompt: item.node.data?.prompt || item.node.name,\n title: item.node.data?.title,\n context: item.node.data?.context || [],\n }));\n};\n","import type { PluginExtensionAddedFunctionConfig } from '@grafana/data';\n\nexport type CallbackFunction = () => FunctionNamespace[];\nexport type FunctionImplementation = (...args: any[]) => any;\nexport const CALLBACK_EXTENSION_POINT = 'grafana-assistant-app/callback/v0-alpha';\n\nexport type NamedFunctions = Record<string, FunctionImplementation>;\nexport type FunctionNamespace = {\n namespace: string;\n functions: NamedFunctions;\n};\n\nexport function newFunctionNamespace(namespace: string, functions: NamedFunctions): FunctionNamespace {\n return {\n namespace,\n functions,\n };\n}\n\nexport function getExposeAssistantFunctionsConfig(\n namespaces: FunctionNamespace[]\n): PluginExtensionAddedFunctionConfig<() => FunctionNamespace[]> {\n return {\n title: 'callback',\n targets: [CALLBACK_EXTENSION_POINT],\n fn: () => {\n return namespaces.map((namespace) => {\n return {\n namespace: namespace.namespace,\n functions: namespace.functions,\n };\n });\n },\n };\n}\n","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"rxjs\");","import { getObservablePluginLinks } from '@grafana/runtime';\n// biome-ignore lint/suspicious/noDeprecatedImports: throwError and timer have deprecated overloads but we use the non-deprecated factory/single-arg forms\nimport { catchError, defer, map, type Observable, of, retry, throwError, timer } from 'rxjs';\n\nexport const ASSISTANT_PLUGIN_ID = 'grafana-assistant-app';\nexport const ASSISTANT_PLUGIN_TITLE = 'Grafana Assistant';\n\nconst MAX_RETRY_ATTEMPTS = 10;\nconst INITIAL_RETRY_DELAY = 100; // 100ms\nconst MAX_RETRY_DELAY = 5000; // 5 seconds\n\n/**\n * Check if the assistant is available.\n * @returns An observable that emits true if the assistant is available, false otherwise.\n */\nexport function isAssistantAvailable(): Observable<boolean> {\n // this is to avoid crashing in older Grafana versions\n if (!getObservablePluginLinks) {\n return of(false);\n }\n\n // Use defer to make the call lazy and handle both sync and async errors\n return defer(() => {\n try {\n const links = getObservablePluginLinks({\n extensionPointId: 'grafana/extension-sidebar/v0-alpha',\n });\n return links.pipe(\n map((links: Array<{ pluginId: string; title: string }>) =>\n links.some((link) => link.pluginId === ASSISTANT_PLUGIN_ID && link.title === ASSISTANT_PLUGIN_TITLE)\n )\n );\n } catch (error) {\n // If getObservablePluginLinks throws synchronously, convert to observable error\n return throwError(() => error);\n }\n }).pipe(\n retry({\n count: MAX_RETRY_ATTEMPTS,\n delay: (error, retryCount) => {\n // Check if error indicates Grafana hasn't started yet\n const errorMessage = error?.message?.toLowerCase() || '';\n const isGrafanaNotReady =\n errorMessage.includes('can only be used after') ||\n errorMessage.includes('grafana instance has started') ||\n errorMessage.includes('not started');\n\n // Don't retry for non-race-condition errors\n if (!isGrafanaNotReady) {\n throw error;\n }\n\n // Exponential backoff: delay = INITIAL_RETRY_DELAY * 2^retryCount, capped at MAX_RETRY_DELAY\n const delayMs = Math.min(INITIAL_RETRY_DELAY * 2 ** (retryCount - 1), MAX_RETRY_DELAY);\n return timer(delayMs);\n },\n }),\n catchError(() => {\n // After all retries exhausted, return false\n return of(false);\n })\n );\n}\n","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"@grafana/data\");","import { BusEventBase, BusEventWithPayload } from '@grafana/data';\nimport { getAppEvents, reportInteraction } from '@grafana/runtime';\nimport type { ChatContextItem } from './context/types';\nimport { ASSISTANT_PLUGIN_ID, ASSISTANT_PLUGIN_TITLE } from './plugin';\n\ninterface OpenExtensionSidebarPayload {\n props?: Record<string, unknown>;\n pluginId: string;\n componentTitle: string;\n}\n\nclass OpenExtensionSidebarEvent extends BusEventWithPayload<OpenExtensionSidebarPayload> {\n static type = 'open-extension-sidebar';\n}\n\nclass CloseExtensionSidebarEvent extends BusEventBase {\n static type = 'close-extension-sidebar';\n}\n\nclass ToggleExtensionSidebarEvent extends BusEventWithPayload<OpenExtensionSidebarPayload> {\n static type = 'toggle-extension-sidebar';\n}\n\nfunction openExtensionSidebar(pluginId: string, componentTitle: string, props?: Record<string, unknown>) {\n const event = new OpenExtensionSidebarEvent({\n pluginId,\n componentTitle,\n props,\n });\n getAppEvents().publish(event);\n}\n\nfunction closeExtensionSidebar() {\n const event = new CloseExtensionSidebarEvent();\n getAppEvents().publish(event);\n}\n\nfunction toggleExtensionSidebar(pluginId: string, componentTitle: string, props?: Record<string, unknown>) {\n const event = new ToggleExtensionSidebarEvent({\n pluginId,\n componentTitle,\n props,\n });\n getAppEvents().publish(event);\n}\n\nexport type OpenAssistantProps = {\n origin: string;\n\n prompt?: string;\n context?: ChatContextItem[];\n autoSend?: boolean;\n /** Mode to open the assistant in. Built-in modes: 'assistant', 'investigation', 'dashboarding'. Can also be a backend agent ID. */\n mode?: string;\n /** When set, sends the prompt as a follow-up into this existing conversation instead of creating a new one. */\n chatId?: string;\n /** When true, append context to the chat instead of replacing it. */\n appendContext?: boolean;\n /**\n * One Agent Skill to attach to the new conversation, named by the token a user types\n * after `/` (its invocation name). Never a handle, a canonical name, or the opaque\n * selection id the server issues — those are internal identities and a caller may not\n * carry one.\n *\n * A request, never a grant: the composer resolves it against the catalog the caller's\n * own user may already attach from, so this can only ever reach what typing the same\n * token would reach. Unknown, unavailable and unsupported all attach nothing.\n *\n * Honoured only on a new conversation. Passing it with `chatId` attaches nothing — and still\n * suppresses the send, so a caller cannot get an unshaped turn where it asked for a shaped one.\n */\n agentSkillInvocationName?: string;\n};\n\n/**\n * The prop bag core forwards verbatim to the sidebar component and re-publishes on the app bus.\n *\n * Two normalizations happen here rather than downstream, because this is the one place both\n * consumers of the event see:\n *\n * - a request naming an Agent Skill never auto-sends. A caller shares a link; the person opening\n * it must see what it attached — and be able to remove it — before anything reaches the model.\n * It holds even where the skill cannot be attached, so a surface that drops the request fails\n * by not sending rather than by sending a message the skill was supposed to shape.\n * - a new conversation naming a skill opens in Assistant unless the caller said otherwise. A\n * skill attaches on the assistant surface, and leaving the mode to an instance default that\n * settles a render later would let the attachment land before its routing was known. This one\n * is skipped alongside `chatId`, which would otherwise change an existing conversation's mode.\n *\n * The suppression is *not* skipped for `chatId`, where the skill is ignored: a caller that asked\n * for a skill-shaped turn is better served by no turn than by an unshaped one it did not ask for.\n */\nfunction toSidebarProps(props: OpenAssistantProps): Record<string, unknown> {\n const namesAgentSkill = Boolean(props.agentSkillInvocationName?.trim());\n return {\n // Distinguish intentional repeated calls from rerenders of the same open request.\n // getRandomValues also works on Grafana instances served over plain HTTP.\n initialRequestId: crypto.getRandomValues(new Uint32Array(4)).join('-'),\n initialPrompt: props.prompt,\n initialContext: props.context,\n initialAutoSend: namesAgentSkill ? false : (props.autoSend ?? true),\n origin: props.origin,\n initialMode: props.mode ?? (namesAgentSkill && !props.chatId ? 'assistant' : undefined),\n chatId: props.chatId,\n appendContext: props.appendContext,\n initialAgentSkillInvocationName: props.agentSkillInvocationName,\n };\n}\n\n/**\n * Open the Grafana Assistant sidebar with a given initial prompt.\n *\n * @param props - The props to pass to the assistant.\n * @param props.origin - The origin of the request that opened the assistant. This is used to track the source of the request. Should be a structured string using forward slashes, with the first part as a namespace. Examples: 'grafana-datasources/prometheus/query-builder', 'grafana-slo-app/slo-editor-overview', 'grafana/trace-view-analyzer`.\n * @param props.prompt - The initial prompt to display in the assistant.\n * @param props.context - The initial context to display in the assistant. Created with `createContext`.\n * @param props.autoSend - Whether to automatically send the initial prompt. When true, opens a chat and sends the initial prompt right away. When false, opens chat and updates user message without sending it. Defaults to true.\n * @param props.mode - The mode to open the assistant in. Built-in modes: 'assistant', 'investigation', 'dashboarding'. Can also be a backend agent ID. Defaults to 'assistant'.\n * @param props.chatId - When set, sends the prompt as a follow-up into this existing conversation instead of creating a new one.\n * @param props.agentSkillInvocationName - One Agent Skill to attach to the new conversation, by the token a user types after `/`. Naming one never auto-sends, and pins Assistant mode when no mode and no chatId are given. Attaches nothing with `chatId`, which still does not send.\n */\nexport function openAssistant(props: OpenAssistantProps) {\n reportInteraction('grafana_assistant_app_opened_sidebar', {\n from: props.origin,\n });\n\n openExtensionSidebar(ASSISTANT_PLUGIN_ID, ASSISTANT_PLUGIN_TITLE, toSidebarProps(props));\n}\n\n/**\n * Close the Grafana Assistant sidebar.\n */\nexport function closeAssistant() {\n closeExtensionSidebar();\n}\n\nexport function toggleAssistant(props: OpenAssistantProps) {\n reportInteraction('grafana_assistant_app_toggled_sidebar', {\n from: props.origin,\n prompt: props.prompt ?? '',\n });\n\n toggleExtensionSidebar(ASSISTANT_PLUGIN_ID, ASSISTANT_PLUGIN_TITLE, toSidebarProps(props));\n}\n","import { useEffect, useState } from 'react';\nimport { isAssistantAvailable } from './plugin';\nimport { closeAssistant, openAssistant, toggleAssistant, type OpenAssistantProps } from './sidebar';\n\nexport type AssistantHook = {\n /** Whether the availability check is still in progress. */\n isLoading: boolean;\n isAvailable: boolean;\n openAssistant: ((props: OpenAssistantProps) => void) | undefined;\n closeAssistant: (() => void) | undefined;\n toggleAssistant: ((props: OpenAssistantProps) => void) | undefined;\n};\n/**\n * Hook to check if the assistant is available and return the open, close, and toggle functions.\n * @returns {AssistantHook}\n */\nexport function useAssistant(): AssistantHook {\n const [available, setAvailable] = useState<boolean | undefined>(undefined);\n\n useEffect(() => {\n const sub = isAssistantAvailable().subscribe(setAvailable);\n return () => sub.unsubscribe();\n }, []);\n\n const isAvailable = available ?? false;\n\n return {\n isLoading: available === undefined,\n isAvailable,\n openAssistant: isAvailable ? openAssistant : undefined,\n closeAssistant: isAvailable ? closeAssistant : undefined,\n toggleAssistant: isAvailable ? toggleAssistant : undefined,\n };\n}\n","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"react/jsx-runtime\");","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"@grafana/ui\");","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"@emotion/css\");","import { useEffect } from 'react';\nimport { Button, IconButton, useStyles2 } from '@grafana/ui';\nimport { css } from '@emotion/css';\nimport type { ChatContextItem } from '../../context/types';\nimport { useAssistant } from '../../hook';\nimport type { GrafanaTheme2 } from '@grafana/data';\nimport type { OpenAssistantProps } from '../../sidebar';\nimport { reportInteraction } from '@grafana/runtime';\n\nexport interface OpenAssistantButtonProps {\n /** Prompt to pass to the openAssistant function. */\n prompt: string;\n /** Origin of the request that opened the assistant. This is used to track the source of the request. Should be a structured string using forward slashes, with the first part as a namespace. Examples: 'grafana-datasources/prometheus/query-builder', 'grafana-slo-app/slo-editor-overview', 'grafana/trace-view-analyzer`. */\n origin: string;\n /** Context to pass to the openAssistant function. Optional, defaults to undefined. Created with `createAssistantContextItem`. */\n context?: ChatContextItem[];\n /** Whether to automatically send the prompt. Optional, defaults to true. */\n autoSend?: boolean;\n /** Text to display on the button. Optional, defaults to 'Analyze with Assistant' */\n title?: string;\n /** Button size, defaults to sm */\n size?: 'xs' | 'sm' | 'md' | 'lg';\n /** If true, the button will be Assistant icon only with name as title. Defaults to false. */\n iconOnlyButton?: boolean;\n /** Function to call when the button is clicked. Optional, defaults to undefined. */\n onClick?: () => void;\n}\n\n/**\n * A button component that opens the Grafana Assistant with configurable prompt and context.\n */\nexport function OpenAssistantButton(props: OpenAssistantButtonProps) {\n // If the assistant is not available, return empty\n const { isAvailable, openAssistant } = useAssistant();\n if (!isAvailable || !openAssistant) {\n return null;\n }\n return <OpenAssistantButtonView {...props} openAssistant={openAssistant} />;\n}\n\n/**\n * Presentational component separated from OpenAssistantButton to avoid hook dependencies in previews.\n * It is not exported for users of the package.\n */\nexport function OpenAssistantButtonView({\n prompt,\n origin,\n context,\n autoSend = true,\n title = 'Analyze with Assistant',\n size = 'sm',\n iconOnlyButton = false,\n openAssistant,\n onClick,\n}: OpenAssistantButtonProps & {\n openAssistant: (props: OpenAssistantProps) => void;\n}) {\n const styles = useStyles2(getStyles);\n\n useEffect(() => {\n reportInteraction('grafana_assistant_app_open_sidebar_button_displayed', {\n from: origin,\n });\n }, [origin]);\n\n return (\n <>\n {iconOnlyButton ? (\n <IconButton\n name=\"ai-sparkle\"\n onClick={() => {\n onClick?.();\n openAssistant({ prompt, context, autoSend, origin });\n }}\n variant=\"secondary\"\n size={size}\n aria-label={title}\n className={styles.icon}\n tooltip={title}\n data-testid=\"assistant-icon-button\"\n />\n ) : (\n <Button\n icon=\"ai-sparkle\"\n onClick={() => {\n onClick?.();\n openAssistant({ prompt, context, autoSend, origin });\n }}\n variant=\"secondary\"\n fill=\"solid\"\n size={size}\n title={title}\n aria-label={title}\n className={styles.button}\n data-testid=\"assistant-button\"\n >\n {title}\n </Button>\n )}\n </>\n );\n}\n\nconst getStyles = (theme: GrafanaTheme2) => {\n const baseBackground = theme.colors.secondary.main;\n const elevatedBackground = theme.colors.emphasize(baseBackground, 0.05);\n\n // Canvas is what's typically underneath buttons\n const underlyingColor = theme.colors.background.canvas;\n\n const borderWidth = 1;\n const outerRadius = theme.shape.radius.default;\n // inner radius = outer radius - border width, but take at least 1px\n const innerRadius = `max(calc(${outerRadius} - ${borderWidth}px), 1px)`;\n\n // Gradient border layer (::before)\n const gradientBorderLayer = {\n content: '\"\"',\n position: 'absolute' as const,\n inset: 0,\n borderRadius: outerRadius,\n cornerShape: 'squircle',\n background: 'linear-gradient(90deg, rgb(168, 85, 247), rgb(249, 115, 22))',\n zIndex: -2,\n pointerEvents: 'none' as const,\n };\n\n // Solid background layer factory (::after)\n // Layer transparent color over canvas to make it opaque and mask the gradient properly\n const solidBackgroundLayer = (background: string) => ({\n content: '\"\"',\n position: 'absolute' as const,\n inset: `${borderWidth}px`,\n borderRadius: innerRadius,\n cornerShape: 'squircle',\n background: `linear-gradient(${background}, ${background}), ${underlyingColor}`,\n zIndex: -1,\n transition: 'none',\n pointerEvents: 'none' as const,\n });\n\n return {\n button: css({\n label: 'assistant-button',\n width: 'fit-content',\n maxWidth: '100%',\n position: 'relative',\n isolation: 'isolate',\n border: 'none',\n transition: 'none !important',\n '&::before': gradientBorderLayer,\n '&::after': {\n ...solidBackgroundLayer(baseBackground),\n transition: 'none',\n },\n '&:hover': {\n transition: 'none !important',\n },\n '&:hover::after': {\n background: `linear-gradient(${elevatedBackground}, ${elevatedBackground}), ${underlyingColor}`,\n },\n }),\n icon: css({\n label: 'assistant-icon',\n position: 'relative',\n isolation: 'isolate',\n border: 'none',\n background: 'none',\n padding: theme.spacing(0.5),\n '&::before': { ...gradientBorderLayer, transition: 'background 0.1s ease' },\n '&:hover::after': {\n ...solidBackgroundLayer(baseBackground),\n background: `linear-gradient(${elevatedBackground}, ${elevatedBackground}), ${underlyingColor}`,\n },\n }),\n };\n};\n","import { type ReactElement, useEffect } from 'react';\nimport { Button, ButtonGroup, Dropdown, Tooltip, useStyles2 } from '@grafana/ui';\nimport { css, cx } from '@emotion/css';\nimport type { ChatContextItem } from '../../context/types';\nimport { useAssistant } from '../../hook';\nimport type { GrafanaTheme2 } from '@grafana/data';\nimport type { OpenAssistantProps } from '../../sidebar';\nimport { reportInteraction } from '@grafana/runtime';\n\nexport interface OpenAssistantSplitButtonProps {\n /** Prompt to pass to the openAssistant function. */\n prompt: string;\n /** Origin of the request that opened the assistant. */\n origin: string;\n /** Context to pass to the openAssistant function. Optional, defaults to undefined. */\n context?: ChatContextItem[];\n /** Whether to automatically send the prompt. Optional, defaults to true. */\n autoSend?: boolean;\n /** Text to display on the button. Optional, defaults to 'Chat with Assistant' */\n title?: string;\n /** Button size, defaults to sm */\n size?: 'sm' | 'md' | 'lg';\n /** Function to call when the main button is clicked. Optional. */\n onClick?: () => void;\n /** Additional menu items to show in the dropdown. Optional. */\n menuItems?: ReactElement;\n /** Tooltip text to display on hover. Optional. */\n tooltip?: string;\n /** Width for the dropdown/chevron segment. Accepts pixels as number or any CSS width value. */\n dropdownButtonWidth?: number | string;\n}\n\ntype AssistantButtonSize = NonNullable<OpenAssistantSplitButtonProps['size']>;\n\nconst defaultDropdownButtonWidths: Record<AssistantButtonSize, number> = {\n sm: 32,\n md: 36,\n lg: 40,\n};\n\n/**\n * A split button component that opens the Grafana Assistant with a dropdown for additional actions.\n * The gradient border wraps around both buttons as a unified control.\n */\nexport function OpenAssistantSplitButton(props: OpenAssistantSplitButtonProps) {\n const { isAvailable, openAssistant } = useAssistant();\n if (!isAvailable || !openAssistant) {\n return null;\n }\n return <OpenAssistantSplitButtonView {...props} openAssistant={openAssistant} />;\n}\n\nexport function OpenAssistantSplitButtonView({\n prompt,\n origin,\n context,\n autoSend = true,\n title = 'Chat with Assistant',\n size = 'sm',\n onClick,\n menuItems,\n tooltip,\n dropdownButtonWidth,\n openAssistant,\n}: OpenAssistantSplitButtonProps & {\n openAssistant: (props: OpenAssistantProps) => void;\n}) {\n const styles = useStyles2(getStyles);\n const hasMenuItems = Boolean(menuItems);\n const resolvedDropdownButtonWidth = toCssWidth(dropdownButtonWidth ?? defaultDropdownButtonWidths[size]);\n\n useEffect(() => {\n reportInteraction('grafana_assistant_app_open_sidebar_split_button_displayed', {\n from: origin,\n });\n }, [origin]);\n\n const handleMainClick = () => {\n onClick?.();\n openAssistant({ prompt, context, autoSend, origin });\n };\n\n const wrapperContent = (\n <div className={styles.wrapper}>\n <ButtonGroup className={styles.buttonGroup}>\n <Button\n icon=\"ai-sparkle\"\n onClick={handleMainClick}\n variant=\"secondary\"\n fill=\"solid\"\n size={size}\n aria-label={title}\n className={cx(styles.segmentButton, hasMenuItems ? styles.mainButtonSplit : styles.mainButtonSolo)}\n data-testid=\"assistant-split-button-main\"\n >\n {title}\n </Button>\n {menuItems && (\n <Dropdown overlay={menuItems}>\n <Button\n variant=\"secondary\"\n icon=\"angle-down\"\n size={size}\n aria-label=\"More AI actions\"\n className={cx(styles.segmentButton, styles.dropdownButton)}\n style={{ width: resolvedDropdownButtonWidth, minWidth: resolvedDropdownButtonWidth }}\n data-testid=\"assistant-split-button-dropdown\"\n />\n </Dropdown>\n )}\n </ButtonGroup>\n </div>\n );\n\n return tooltip ? <Tooltip content={tooltip}>{wrapperContent}</Tooltip> : wrapperContent;\n}\n\nconst getStyles = (theme: GrafanaTheme2) => {\n const baseBackground = theme.colors.secondary.main;\n const elevatedBackground = theme.colors.emphasize(baseBackground, 0.05);\n const underlyingColor = theme.colors.background.canvas;\n const dividerColor = theme.colors.border.weak;\n const borderWidth = 1;\n const outerRadius = theme.shape.radius.default;\n const innerRadius = `max(calc(${outerRadius} - ${borderWidth}px), 1px)`;\n\n return {\n wrapper: css({\n label: 'assistant-split-button-wrapper',\n position: 'relative',\n isolation: 'isolate',\n display: 'inline-block',\n padding: borderWidth,\n // Gradient border around the entire button group\n '&::before': {\n content: '\"\"',\n position: 'absolute',\n inset: 0,\n borderRadius: outerRadius,\n cornerShape: 'squircle',\n background: 'linear-gradient(90deg, rgb(168, 85, 247), rgb(249, 115, 22))',\n zIndex: -1,\n pointerEvents: 'none',\n },\n // Solid background layer\n '&::after': {\n content: '\"\"',\n position: 'absolute',\n inset: `${borderWidth}px`,\n borderRadius: innerRadius,\n cornerShape: 'squircle',\n background: `linear-gradient(${baseBackground}, ${baseBackground}), ${underlyingColor}`,\n zIndex: -1,\n pointerEvents: 'none',\n },\n }),\n buttonGroup: css({\n label: 'assistant-split-button-group',\n gap: 0,\n position: 'relative',\n zIndex: 1,\n borderRadius: innerRadius,\n overflow: 'hidden',\n // Make buttons transparent to show the wrapper's gradient\n '& button': {\n border: 'none',\n boxShadow: 'none',\n background: 'transparent !important',\n },\n }),\n segmentButton: css({\n label: 'assistant-split-button-segment',\n position: 'relative',\n '&:hover': {\n background: `${elevatedBackground} !important`,\n },\n '&:focus-visible': {\n background: `${elevatedBackground} !important`,\n },\n '&[aria-expanded=\"true\"]': {\n background: `${elevatedBackground} !important`,\n },\n }),\n mainButtonSolo: css({\n label: 'assistant-split-button-main-solo',\n borderRadius: innerRadius,\n }),\n mainButtonSplit: css({\n label: 'assistant-split-button-main-split',\n borderTopLeftRadius: innerRadius,\n borderBottomLeftRadius: innerRadius,\n borderTopRightRadius: 0,\n borderBottomRightRadius: 0,\n }),\n dropdownButton: css({\n label: 'assistant-split-button-dropdown',\n display: 'inline-flex',\n alignItems: 'center',\n justifyContent: 'center',\n gap: 0,\n borderTopLeftRadius: 0,\n borderBottomLeftRadius: 0,\n borderTopRightRadius: innerRadius,\n borderBottomRightRadius: innerRadius,\n padding: '0 !important',\n boxShadow: `inset 1px 0 0 ${dividerColor}`,\n '& svg': {\n margin: 0,\n },\n }),\n };\n};\n\nfunction toCssWidth(width: number | string): string {\n return typeof width === 'number' ? `${width}px` : width;\n}\n","import type { GrafanaTheme2 } from '@grafana/data';\n\n/**\n * Default gradient colors for the assistant\n */\nconst GRADIENT_COLORS = {\n PURPLE: 'rgb(168, 85, 247)',\n ORANGE: 'rgb(249, 115, 22)',\n} as const;\n\n// FIXME: use SDK as single source of truth for these color schemes?\n\n/**\n * Returns the colors of the background gradient based on the theme.\n *\n * @param theme - The Grafana theme object.\n * @returns The colors of the background gradient as tuple.\n */\nexport const getBackgroundGradientColors = (theme: GrafanaTheme2): [string, string] => {\n const defaultGradientColors: [string, string] = [GRADIENT_COLORS.PURPLE, GRADIENT_COLORS.ORANGE];\n\n // Check if the theme does not use gradients by default\n if (isThemeWithoutGradients(theme)) {\n return defaultGradientColors;\n }\n\n // If the theme uses gradients, extract the colors from the gradient string\n const gradientString = theme.colors.gradients.brandHorizontal;\n const hexColorRegex = /#[0-9A-Fa-f]{6}/g;\n const matches = gradientString.match(hexColorRegex);\n if (!matches || matches.length < 2) {\n // Fallback to default colors if extraction fails\n return defaultGradientColors;\n }\n\n return [matches[0], matches[1]];\n};\n\n/**\n * Creates animation keyframes for a rotating gradient border effect.\n * This is used for loading states in inputs and other components.\n *\n * @param theme - The Grafana theme object\n * @param backgroundColor - The background color to use in the animation\n * @param color1 - First gradient color (optional, defaults to theme purple)\n * @param color2 - Second gradient color (optional, defaults to theme orange)\n * @returns Animation keyframes object for use with @emotion/css keyframes\n *\n * @example\n * ```ts\n * const borderAnimation = keyframes({\n * label: 'border-animation',\n * ...createBorderAnimation(theme, theme.colors.background.primary),\n * });\n * ```\n */\nexport const createBorderAnimation = (\n theme: GrafanaTheme2,\n backgroundColor: string,\n color1?: string,\n color2?: string\n): Record<string, { backgroundImage: string }> => {\n const animationSteps = Array.from({ length: 101 }, (_, i) => i);\n const animationFrames: Record<string, { backgroundImage: string }> = {};\n const [gradientColor1, gradientColor2] = getBackgroundGradientColors(theme);\n\n const finalColor1 = color1 ?? gradientColor1;\n const finalColor2 = color2 ?? gradientColor2;\n\n for (const step of animationSteps) {\n animationFrames[`${step}%`] = {\n backgroundImage: `\n linear-gradient(${backgroundColor}, ${backgroundColor}),\n conic-gradient(from ${step * 3.6}deg, transparent 60%, ${finalColor1} 80%, ${finalColor2} 100%, transparent 15%)\n `,\n };\n }\n\n return animationFrames;\n};\n\n/**\n * Checks if the theme is a \"default\" theme (dark or light) that does not use or expose gradients.\n *\n * @param theme - The Grafana theme object.\n * @returns True if the theme does not use gradients, false otherwise.\n */\nconst isThemeWithoutGradients = (theme: GrafanaTheme2) => {\n const name = theme.name.toLowerCase().replace(/^visual refresh \\((.+)\\)$/, '$1');\n return name === 'dark' || name === 'light';\n};\n","import type { InlineToolRunnable } from '../tools/types';\n\nexport interface InlineAssistantPromptOptions {\n prompt: string;\n agentName?: string;\n agentId?: string;\n systemPrompt?: string;\n tools?: InlineToolRunnable[];\n onStart?: () => void;\n onDelta?: (delta: string) => void;\n onComplete?: (text: string) => void;\n onError?: (error: Error) => void;\n}\n\n/** Reasoning effort for each model call of an inline assistant. */\nexport type InlineAssistantReasoningLevel = 'none' | 'low' | 'medium' | 'high' | 'xhigh' | 'max';\n\n/**\n * How the agent behind an inline assistant runs. It is fixed when the instance is created and\n * applies to every prompt sent to it. Omitted fields keep the defaults, which suit short content\n * generation; raise them for agentic work such as multi-step discovery with your own tools.\n * Grafana Assistant releases that predate this config ignore it and run with the defaults.\n */\nexport interface InlineAssistantConfig {\n /** Most model calls per prompt, an integer from 1 to 76. The agent stops after the last one. Default 5. */\n maxSteps?: number;\n /** Use the smaller, faster model. Default true. */\n weak?: boolean;\n /** Reasoning effort per model call. Default 'none'. */\n reasoningLevel?: InlineAssistantReasoningLevel;\n /** Most output tokens per model call, an integer from 1 to 16000. Default 4096. */\n maxTokens?: number;\n}\n\nexport interface InlineAssistant {\n sendPrompt(options: InlineAssistantPromptOptions): Promise<void>;\n cancel(): void;\n dispose(): void;\n}\n\nexport type InlineAssistantFactory = (origin: string, config?: InlineAssistantConfig) => Promise<InlineAssistant>;\nexport type InlineAssistantInitializer = () => Promise<void>;\n\n// Global registry keys for cross-plugin sharing\nconst GLOBAL_FACTORY_KEY = '__grafanaAssistantInlineFactory__';\nconst GLOBAL_INITIALIZER_KEY = '__grafanaAssistantInlineInitializer__';\nconst GLOBAL_INITIALIZATION_PROMISE_KEY = '__grafanaAssistantInlineInitPromise__';\n\nexport function setInlineAssistantFactory(fn: InlineAssistantFactory): void {\n const existing = window[GLOBAL_FACTORY_KEY] as InlineAssistantFactory | undefined;\n if (existing && existing !== fn) {\n console.warn('InlineAssistant factory already set; ignoring subsequent setInlineAssistantFactory call');\n return;\n }\n if (!existing) {\n window[GLOBAL_FACTORY_KEY] = fn;\n }\n}\n\n/**\n * Register a lazy initializer that will be called on first use.\n * The plugin code should register this to enable lazy loading of the inline assistant.\n *\n * This uses global storage (window) so that all plugins share the same initializer,\n * regardless of which plugin instance or package version loads first.\n */\nexport function setInlineAssistantInitializer(fn: InlineAssistantInitializer): void {\n const existing = window[GLOBAL_INITIALIZER_KEY] as InlineAssistantInitializer | undefined;\n if (existing && existing !== fn) {\n console.warn('InlineAssistant initializer already set; ignoring subsequent setInlineAssistantInitializer call');\n return;\n }\n if (!existing) {\n window[GLOBAL_INITIALIZER_KEY] = fn;\n }\n}\n\n/**\n * Ensure the inline assistant is initialized. If an initializer is registered,\n * it will be called on first use. Otherwise, checks if factory is already registered.\n *\n * Uses global storage (window) so that initialization is shared across all plugins.\n */\nexport async function ensureInlineAssistantInitialized(): Promise<void> {\n // If factory is already set, we're good\n const factory = window[GLOBAL_FACTORY_KEY] as InlineAssistantFactory | undefined;\n if (factory) {\n return;\n }\n\n // If no initializer is registered, throw error\n const initializer = window[GLOBAL_INITIALIZER_KEY] as InlineAssistantInitializer | undefined;\n if (!initializer) {\n throw new Error(\n 'InlineAssistant not initialized. Make sure the Grafana Assistant plugin is loaded and initialized.'\n );\n }\n\n // If initialization is in progress, wait for it\n const existingPromise = window[GLOBAL_INITIALIZATION_PROMISE_KEY] as Promise<void> | null | undefined;\n if (existingPromise !== null && existingPromise !== undefined) {\n return existingPromise;\n }\n\n // Start initialization\n const initPromise = (async () => {\n try {\n await initializer();\n } catch (err) {\n // Reset on error so retry is possible\n window[GLOBAL_INITIALIZATION_PROMISE_KEY] = null;\n throw err;\n }\n })();\n\n window[GLOBAL_INITIALIZATION_PROMISE_KEY] = initPromise;\n return initPromise;\n}\n\nexport function getInlineAssistantFactory(): InlineAssistantFactory {\n const factory = window[GLOBAL_FACTORY_KEY] as InlineAssistantFactory | undefined;\n if (!factory) {\n throw new Error('InlineAssistant factory not initialized. Make sure the Grafana Assistant plugin is loaded.');\n }\n return factory;\n}\n","const nestedErrorKeys = ['message', 'error', 'err', 'detail', 'details'] as const;\n\nfunction getStringValue(value: unknown): string | null {\n if (typeof value !== 'string') {\n return null;\n }\n\n const trimmedValue = value.trim();\n return trimmedValue === '' ? null : trimmedValue;\n}\n\nfunction isUnhelpfulErrorMessage(message: string | null): boolean {\n if (!message) {\n return true;\n }\n\n return message === '[object Object]' || message === 'Error' || message === 'Unknown error';\n}\n\nfunction extractNestedErrorMessage(error: unknown, visited = new Set<object>()): string | null {\n const directString = getStringValue(error);\n if (directString) {\n return directString;\n }\n\n if (error instanceof Error) {\n const errorMessage = getStringValue(error.message);\n if (!isUnhelpfulErrorMessage(errorMessage)) {\n return errorMessage;\n }\n\n const nestedErrorMessage = extractNestedErrorMessage(error.cause, visited);\n if (nestedErrorMessage) {\n return nestedErrorMessage;\n }\n\n const ownPropertiesMessage = extractNestedErrorMessage(\n Object.fromEntries(\n Object.entries(error as Error & Record<string, unknown>).filter(([key]) => key !== 'message' && key !== 'name')\n ),\n visited\n );\n if (ownPropertiesMessage) {\n return ownPropertiesMessage;\n }\n\n return errorMessage ?? getStringValue(error.name) ?? null;\n }\n\n if (!error || typeof error !== 'object') {\n return null;\n }\n\n if (visited.has(error)) {\n return null;\n }\n visited.add(error);\n\n const errorRecord = error as Record<string, unknown>;\n\n if ('data' in errorRecord) {\n const nestedDataMessage = extractNestedErrorMessage(errorRecord.data, visited);\n if (nestedDataMessage) {\n return nestedDataMessage;\n }\n }\n\n for (const key of nestedErrorKeys) {\n if (key in errorRecord) {\n const nestedMessage = extractNestedErrorMessage(errorRecord[key], visited);\n if (nestedMessage) {\n return nestedMessage;\n }\n }\n }\n\n const status = errorRecord.status;\n const statusText = getStringValue(errorRecord.statusText);\n if ((typeof status === 'number' || typeof status === 'string') && statusText) {\n return `HTTP ${status}: ${statusText}`;\n }\n\n if (Array.isArray(error)) {\n const nestedMessages = error\n .map((item) => extractNestedErrorMessage(item, visited))\n .filter((message): message is string => Boolean(message));\n\n if (nestedMessages.length > 0) {\n return nestedMessages.join('; ');\n }\n }\n\n return null;\n}\n\n/**\n * Extract error message from backend errors (handles various error formats).\n *\n * @internal SDK-private helper for useInlineAssistant. Not part of the public\n * `@grafana/assistant` surface — do not re-export from `index.ts`.\n */\nexport function extractErrorMessage(error: unknown): string {\n const extractedMessage = extractNestedErrorMessage(error);\n if (extractedMessage) {\n return extractedMessage;\n }\n\n // Objects that expose no message are not serialized: fetch-like errors carry\n // the request URL, headers and body on `config`, which would end up in the\n // messages this helper feeds back to callers.\n if (error && typeof error === 'object') {\n return 'Unknown error';\n }\n\n if (error == null) {\n return 'Unknown error';\n }\n\n return String(error);\n}\n","import { useState, useCallback, useRef, useEffect } from 'react';\nimport type { InlineAssistantOptions, InlineAssistantResult } from './types';\nimport {\n getInlineAssistantFactory,\n type InlineAssistant,\n type InlineAssistantConfig,\n ensureInlineAssistantInitialized,\n} from './inlineAssistant';\nimport { extractErrorMessage } from '../utils/errorHandling';\n\n/**\n * React hook for inline assistant generation with streaming support.\n *\n * This hook enables generating content (like panel titles or descriptions) inline\n * without opening the assistant sidebar. Each hook instance creates its own chat\n * conversation, so all generations from the same instance are grouped together.\n * Generated content is ephemeral - it won't appear in the user's chat history\n * but will be tracked in the admin UI for analytics.\n *\n * Uses the full BaseMultiStepAgent infrastructure for tool execution and multi-step workflows.\n *\n * The implementation is lazy-loaded on first use to reduce initial bundle size.\n *\n * `config` sets how the agent runs (steps, model, reasoning, output tokens). It is read when the\n * first generation creates the conversation; later changes do not apply to it.\n *\n * @example\n * ```typescript\n * function PanelEditor() {\n * const { generate, isGenerating, content, error, reset } = useInlineAssistant();\n * const [title, setTitle] = useState('');\n *\n * const handleGenerate = () => {\n * generate({\n * prompt: 'Generate a panel title for CPU metrics',\n * origin: 'grafana/panel-editor/title',\n * systemPrompt: 'Generate only the title text, no explanation',\n * onComplete: (text) => setTitle(text.trim()),\n * onError: (err) => console.error(err)\n * });\n * };\n *\n * return (\n * <div>\n * <input value={title} onChange={(e) => setTitle(e.target.value)} />\n * <button onClick={handleGenerate} disabled={isGenerating}>\n * {isGenerating ? 'Generating...' : 'Generate with Assistant'}\n * </button>\n * {isGenerating && <div>{content}</div>}\n * </div>\n * );\n * }\n * ```\n *\n * @example\n * ```typescript\n * // Using tools with inline assistant\n * import { lokiQueryHandlerTool } from 'agent/tools';\n *\n * function ComponentWithTools() {\n * const { generate } = useInlineAssistant();\n *\n * const handleGenerate = async () => {\n * await generate({\n * prompt: 'Query Loki for error logs from the last hour',\n * origin: 'my-app/component',\n * tools: [lokiQueryHandlerTool],\n * onComplete: (text) => console.log('Generated:', text),\n * });\n * };\n *\n * return <button onClick={handleGenerate}>Generate</button>;\n * }\n * ```\n */\nexport function useInlineAssistant(config?: InlineAssistantConfig): InlineAssistantResult {\n const [isGenerating, setIsGenerating] = useState(false);\n const [content, setContent] = useState('');\n const [error, setError] = useState<Error | null>(null);\n const assistantRef = useRef<InlineAssistant | null>(null);\n const configRef = useRef(config);\n configRef.current = config;\n\n /**\n * Reset error and content state\n */\n const reset = useCallback(() => {\n setError(null);\n setContent('');\n }, []);\n\n /**\n * Cancel the current generation\n */\n const cancel = useCallback(() => {\n if (assistantRef.current) {\n assistantRef.current.cancel();\n }\n setIsGenerating(false);\n }, []);\n\n /**\n * Generate content with the given options\n */\n const generate = useCallback(async (options: InlineAssistantOptions): Promise<void> => {\n // Reset state\n setError(null);\n setContent('');\n setIsGenerating(true);\n\n try {\n // Ensure the inline assistant is initialized (lazy-loads on first use)\n await ensureInlineAssistantInitialized();\n\n const factory = getInlineAssistantFactory();\n\n // Create or reuse assistant for this origin\n if (!assistantRef.current) {\n assistantRef.current = await factory(options.origin, configRef.current);\n }\n\n await assistantRef.current.sendPrompt({\n prompt: options.prompt,\n agentName: options.agentName,\n agentId: options.agentId,\n systemPrompt: options.systemPrompt,\n tools: options.tools,\n onStart: () => {\n setIsGenerating(true);\n },\n onDelta: (delta) => {\n setContent((prev) => prev + delta);\n options.onDelta?.(delta);\n },\n onComplete: (text) => {\n setContent(text);\n setIsGenerating(false);\n options.onComplete?.(text);\n },\n onError: (err) => {\n setError(err);\n setIsGenerating(false);\n options.onError?.(err);\n },\n });\n } catch (err) {\n const error = new Error(extractErrorMessage(err), { cause: err });\n setError(error);\n setIsGenerating(false);\n options.onError?.(error);\n }\n }, []);\n\n // Cleanup on unmount\n useEffect(() => {\n return () => {\n if (assistantRef.current) {\n assistantRef.current.cancel();\n assistantRef.current.dispose();\n assistantRef.current = null;\n }\n };\n }, []);\n\n return {\n generate,\n isGenerating,\n content,\n error,\n cancel,\n reset,\n };\n}\n","import { useCallback, useEffect, useRef } from 'react';\nimport { useInlineAssistant } from '../../inline/useInlineAssistant';\n\nexport interface UseAIGenerationOptions {\n value: string;\n onChange: (value: string) => void;\n origin: string;\n systemPrompt?: string;\n onComplete?: (text: string) => void;\n onError?: (error: Error) => void;\n onDelta?: (delta: string) => void;\n disabled?: boolean;\n autoGenerate?: boolean;\n streaming?: boolean;\n getUserPrompt?: (textInput: string) => string;\n}\n\nexport function useAIGeneration({\n value,\n onChange,\n origin,\n systemPrompt,\n onComplete,\n onError,\n onDelta,\n disabled = false,\n autoGenerate = false,\n streaming = false,\n getUserPrompt,\n}: UseAIGenerationOptions) {\n const { generate, isGenerating, content, error, reset } = useInlineAssistant();\n const hasAutoGenerated = useRef(false);\n const valueBeforeGeneration = useRef(value);\n const getUserPromptRef = useRef(getUserPrompt);\n getUserPromptRef.current = getUserPrompt;\n\n let displayValue: string;\n if (isGenerating) {\n if (streaming) {\n displayValue = content;\n } else {\n displayValue = '';\n }\n } else {\n displayValue = value;\n }\n const resolvedPrompt = getUserPrompt ? getUserPrompt(value.trim()) : value.trim();\n const isSendDisabled = !resolvedPrompt || disabled || isGenerating;\n\n const doGenerate = useCallback(\n (prompt: string) => {\n valueBeforeGeneration.current = value;\n onChange('');\n reset();\n\n generate({\n prompt,\n origin,\n systemPrompt,\n onDelta,\n onComplete: (text) => {\n onChange(text);\n onComplete?.(text);\n },\n onError: (err) => {\n onChange(valueBeforeGeneration.current);\n onError?.(err);\n },\n }).catch((error: unknown) => {\n console.warn('Failed to handle the AI generation result:', error);\n });\n },\n [value, onChange, origin, systemPrompt, onDelta, onComplete, onError, generate, reset]\n );\n\n // Auto-generate at most once, on mount, evaluating the props as they are at mount.\n const maybeAutoGenerateRef = useRef<() => void>(() => {});\n maybeAutoGenerateRef.current = () => {\n if (autoGenerate && systemPrompt && !value && !hasAutoGenerated.current && !disabled) {\n hasAutoGenerated.current = true;\n doGenerate(systemPrompt);\n }\n };\n useEffect(() => {\n maybeAutoGenerateRef.current();\n }, []);\n\n const handleGenerate = useCallback(() => {\n const fn = getUserPromptRef.current;\n const prompt = fn ? fn(value.trim()) : value.trim();\n if (!prompt || disabled || isGenerating) {\n return;\n }\n doGenerate(prompt);\n }, [value, disabled, isGenerating, doGenerate]);\n\n return {\n displayValue,\n isSendDisabled,\n handleGenerate,\n isGenerating,\n error,\n };\n}\n","import { useRef, useState } from 'react';\n\nconst GENERATING_PHRASES = [\n 'Generating...',\n 'Brewing...',\n 'Cooking...',\n 'Crunching...',\n 'Phrasing...',\n 'Wording...',\n 'Crafting...',\n 'Composing...',\n 'Drafting...',\n 'Shaping...',\n 'Forming...',\n 'Molding...',\n 'Sketching...',\n 'Whipping up...',\n 'Conjuring...',\n 'Stirring...',\n];\n\n/**\n * Returns a random placeholder phrase while generating, or the provided\n * default placeholder when idle. A new phrase is picked each time generation starts.\n */\nexport function useGeneratingPlaceholder(isGenerating: boolean, defaultPlaceholder: string): string {\n const [phrase, setPhrase] = useState('');\n const wasGenerating = useRef(false);\n\n if (isGenerating && !wasGenerating.current) {\n const next = GENERATING_PHRASES[Math.floor(Math.random() * GENERATING_PHRASES.length)];\n setPhrase(next);\n wasGenerating.current = true;\n return next;\n }\n\n if (!isGenerating) {\n wasGenerating.current = false;\n }\n\n return isGenerating ? phrase : defaultPlaceholder;\n}\n","import type { KeyboardEvent } from 'react';\nimport { Input, IconButton, useStyles2 } from '@grafana/ui';\nimport { css, cx, keyframes } from '@emotion/css';\nimport type { GrafanaTheme2 } from '@grafana/data';\nimport { createBorderAnimation, getBackgroundGradientColors } from '../../utils/theme';\nimport type { AIInputProps } from './types';\nimport { useAIGeneration } from './useAIGeneration';\nimport { useGeneratingPlaceholder } from './useGeneratingPlaceholder';\n\nexport interface AITextInputProps extends AIInputProps {}\n\n/**\n * An AI-powered controlled text input component that uses the Grafana Assistant engine to generate content.\n * Features an integrated send button as well as a gradient border animation while generating.\n */\nexport function AITextInput({\n value,\n onChange,\n placeholder,\n origin,\n systemPrompt,\n onComplete,\n onError,\n onDelta,\n disabled = false,\n autoGenerate = false,\n streaming = false,\n getUserPrompt,\n className,\n 'data-testid': dataTestId,\n}: AITextInputProps) {\n const { displayValue, isSendDisabled, handleGenerate, isGenerating, error } = useAIGeneration({\n value,\n onChange,\n origin,\n systemPrompt,\n onComplete,\n onError,\n onDelta,\n disabled,\n autoGenerate,\n streaming,\n getUserPrompt,\n });\n const styles = useStyles2(getStyles);\n const activePlaceholder = useGeneratingPlaceholder(isGenerating, placeholder ?? 'Ask AI to generate...');\n\n const handleKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {\n // Cmd/Ctrl + Enter to send\n if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) {\n e.preventDefault();\n handleGenerate();\n }\n };\n\n const addonAfter = (\n <IconButton\n name=\"ai-sparkle\"\n onClick={handleGenerate}\n disabled={isSendDisabled}\n tooltip={isSendDisabled ? 'Enter text to generate' : 'Generate with AI'}\n data-testid={dataTestId ? `${dataTestId}-send` : undefined}\n />\n );\n\n return (\n <div className={cx(styles.wrapper, { [styles.animatedWrapper]: isGenerating }, className)} data-testid={dataTestId}>\n <Input\n value={displayValue}\n onKeyDown={handleKeyDown}\n onChange={(e) => onChange(e.currentTarget.value)}\n placeholder={activePlaceholder}\n disabled={disabled || isGenerating}\n suffix={addonAfter}\n invalid={!!error}\n data-testid={dataTestId ? `${dataTestId}-input` : undefined}\n />\n </div>\n );\n}\n\nconst getStyles = (theme: GrafanaTheme2) => {\n const backgroundColor = theme.colors.background.primary;\n const borderAnimation = keyframes({\n label: 'ai-input-border-animation',\n ...createBorderAnimation(theme, backgroundColor),\n });\n\n const [gradientColor1, gradientColor2] = getBackgroundGradientColors(theme);\n\n return {\n wrapper: css({\n label: 'ai-text-input-wrapper',\n position: 'relative',\n border: '1px solid transparent',\n borderRadius: theme.shape.radius.default,\n cornerShape: 'squircle',\n }),\n animatedWrapper: css({\n label: 'ai-text-input-animated',\n border: '1px solid transparent',\n // Set initial backgroundImage with both gradients so Chrome can animate properly\n backgroundImage: `\n linear-gradient(${backgroundColor}, ${backgroundColor}),\n conic-gradient(from 0deg, transparent 60%, ${gradientColor1} 80%, ${gradientColor2} 100%, transparent 15%)\n `,\n backgroundOrigin: 'border-box',\n backgroundClip: 'padding-box, border-box',\n animation: `${borderAnimation} 2s linear infinite`,\n '& input': {\n // Remove the default border from the input when animated wrapper is active\n border: 'none !important',\n },\n }),\n };\n};\n","import type { KeyboardEvent } from 'react';\nimport { TextArea, IconButton, useStyles2 } from '@grafana/ui';\nimport { css, cx, keyframes } from '@emotion/css';\nimport type { GrafanaTheme2 } from '@grafana/data';\nimport { createBorderAnimation, getBackgroundGradientColors } from '../../utils/theme';\nimport type { AIInputProps } from './types';\nimport { useAIGeneration } from './useAIGeneration';\nimport { useGeneratingPlaceholder } from './useGeneratingPlaceholder';\n\nexport interface AITextAreaProps extends AIInputProps {\n /** Number of rows for the textarea */\n rows?: number;\n}\n\n/**\n * An AI-powered controlled textarea component that uses the Grafana Assistant engine to generate content.\n * Features an integrated send button as well as a gradient border animation while generating.\n */\nexport function AITextArea({\n value,\n onChange,\n placeholder,\n origin,\n systemPrompt,\n onComplete,\n onError,\n onDelta,\n disabled = false,\n autoGenerate = false,\n streaming = false,\n getUserPrompt,\n rows = 4,\n className,\n 'data-testid': dataTestId,\n}: AITextAreaProps) {\n const { displayValue, isSendDisabled, handleGenerate, isGenerating, error } = useAIGeneration({\n value,\n onChange,\n origin,\n systemPrompt,\n onComplete,\n onError,\n onDelta,\n disabled,\n autoGenerate,\n streaming,\n getUserPrompt,\n });\n const styles = useStyles2(getStyles);\n const activePlaceholder = useGeneratingPlaceholder(\n isGenerating,\n placeholder ?? 'Ask AI to generate... (Cmd/Ctrl+Enter to send)'\n );\n const effectiveRows = Math.max(rows, 2);\n\n const handleKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {\n // Cmd/Ctrl + Enter to send\n if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) {\n e.preventDefault();\n handleGenerate();\n }\n };\n\n return (\n <div\n className={cx(styles.textareaWrapper, { [styles.animatedWrapper]: isGenerating }, className)}\n data-testid={dataTestId}\n >\n <TextArea\n value={displayValue}\n onKeyDown={handleKeyDown}\n onChange={(e) => onChange(e.currentTarget.value)}\n placeholder={activePlaceholder}\n disabled={disabled || isGenerating}\n rows={effectiveRows}\n className={styles.textarea}\n invalid={!!error}\n data-testid={dataTestId ? `${dataTestId}-textarea` : undefined}\n />\n <IconButton\n name=\"ai-sparkle\"\n onClick={handleGenerate}\n disabled={isSendDisabled}\n className={styles.sendButton}\n aria-label=\"Generate with AI\"\n tooltip={isSendDisabled ? 'Enter text to generate' : 'Generate with AI (Cmd/Ctrl+Enter)'}\n data-testid={dataTestId ? `${dataTestId}-send` : undefined}\n />\n </div>\n );\n}\n\nconst getStyles = (theme: GrafanaTheme2) => {\n const backgroundColor = theme.colors.background.primary;\n const borderAnimation = keyframes({\n label: 'ai-textarea-border-animation',\n ...createBorderAnimation(theme, backgroundColor),\n });\n\n const [gradientColor1, gradientColor2] = getBackgroundGradientColors(theme);\n\n return {\n textareaWrapper: css({\n label: 'ai-textarea-wrapper',\n position: 'relative',\n border: '1px solid transparent',\n borderRadius: theme.shape.radius.default,\n cornerShape: 'squircle',\n }),\n animatedWrapper: css({\n label: 'ai-textarea-animated',\n border: '1px solid transparent',\n // Set initial backgroundImage with both gradients so Chrome can animate properly\n backgroundImage: `\n linear-gradient(${backgroundColor}, ${backgroundColor}),\n conic-gradient(from 0deg, transparent 60%, ${gradientColor1} 80%, ${gradientColor2} 100%, transparent 15%)\n `,\n backgroundOrigin: 'border-box',\n backgroundClip: 'padding-box, border-box',\n animation: `${borderAnimation} 2s linear infinite`,\n '& textarea': {\n // Remove the default border from the textarea when animated wrapper is active\n border: 'none !important',\n },\n }),\n textarea: css({\n label: 'ai-textarea',\n // ensures the text does not \"underflow\" the send button\n paddingRight: theme.spacing(4),\n // Keep at least a 2-row visual height even if outer styles try to shrink the control\n minHeight: theme.spacing(6),\n '& textarea': {\n minHeight: theme.spacing(6),\n },\n // Hide scrollbar\n scrollbarWidth: 'none', // Firefox\n '&::-webkit-scrollbar': {\n display: 'none', // Chrome, Safari, Edge\n },\n }),\n sendButton: css({\n label: 'ai-textarea-send',\n position: 'absolute',\n right: theme.spacing(1),\n top: theme.spacing(1),\n }),\n };\n};\n","import { CoreApp, type DataSourceApi, type DataSourceInstanceSettings } from '@grafana/data';\nimport type { DataQuery, DataSourceJsonData } from '@grafana/schema';\nimport type { ComponentSize } from '@grafana/ui';\nimport { createAssistantContextItem } from '../../context';\nimport { useAssistant } from '../../hook';\nimport { OpenAssistantButtonView } from './OpenAssistantButton';\n\nfunction queryIsEmpty(query: DataQuery): boolean {\n const dataQueryProps = ['refId', 'hide', 'key', 'queryType', 'datasource'];\n\n for (const key in query) {\n if (key === 'label') {\n continue;\n }\n if (!dataQueryProps.includes(key)) {\n return false;\n }\n }\n\n return true;\n}\n\nexport interface QueryWithAssistantButtonProps<TQuery extends DataQuery = DataQuery> {\n size?: ComponentSize;\n currentQuery: TQuery;\n queries: TQuery[];\n dataSourceInstanceSettings: DataSourceInstanceSettings;\n app?: CoreApp;\n datasourceApi: DataSourceApi<TQuery, DataSourceJsonData> | null;\n title?: string;\n}\n\nexport function QueryWithAssistantButton<TQuery extends DataQuery = DataQuery>({\n size,\n currentQuery,\n queries,\n dataSourceInstanceSettings,\n app,\n datasourceApi,\n title = 'Query with Assistant',\n}: QueryWithAssistantButtonProps<TQuery>) {\n const { isAvailable, openAssistant } = useAssistant();\n if (!isAvailable || !openAssistant) {\n return null;\n }\n\n const origin = `grafana/query-editor/${dataSourceInstanceSettings.type}/${app ?? CoreApp.Unknown ?? 'unknown'}`;\n\n const hasCurrentQuery = !queryIsEmpty(currentQuery);\n const otherQueries = queries.filter((q) => q.refId !== currentQuery.refId && !queryIsEmpty(q));\n\n const context = [\n createAssistantContextItem('datasource', {\n datasourceUid: dataSourceInstanceSettings.uid,\n }),\n ];\n\n if (hasCurrentQuery) {\n context.push(\n createAssistantContextItem('structured', {\n title: 'Current query',\n data: currentQuery,\n })\n );\n }\n\n if (otherQueries.length > 0) {\n context.push(\n createAssistantContextItem('structured', {\n title: 'Other queries',\n data: {\n queries: otherQueries,\n },\n })\n );\n }\n\n const queryDisplayText =\n hasCurrentQuery && datasourceApi?.getQueryDisplayText ? datasourceApi.getQueryDisplayText(currentQuery) : null;\n\n const isUpdating = !!queryDisplayText;\n const actionText = isUpdating\n ? 'Help me update the current query to answer my questions and provide the insights I need.'\n : 'Help me create a new query to answer my questions and provide the insights I need.';\n\n const codeBlockLines: string[] = [];\n\n if (queryDisplayText) {\n codeBlockLines.push(`Current query: ${queryDisplayText}`);\n }\n\n codeBlockLines.push(`Selected data source: ${dataSourceInstanceSettings.name}`);\n\n const actionableSentence = isUpdating\n ? 'Please describe what you want to change or improve in this query.'\n : \"Please describe what you want to query and what insights you're looking for.\";\n\n const prompt = [actionText, '```', ...codeBlockLines, '```', actionableSentence].join('\\n');\n\n return (\n <OpenAssistantButtonView\n prompt={prompt}\n origin={origin}\n context={context}\n autoSend={false}\n title={title}\n size={size}\n openAssistant={openAssistant}\n />\n );\n}\n","import { useState, useRef, useEffect } from 'react';\n\nconst DEFAULT_EXAMPLE_PROMPTS = [\n 'What does this panel show?',\n 'Explain the trend in this data',\n 'Why is there a spike?',\n 'Add a threshold at 80%',\n 'Change the legend to table mode',\n];\n\nexport { DEFAULT_EXAMPLE_PROMPTS };\n\nexport function useAnimatedPlaceholder(staticPlaceholder: string, prompts: string[], hasUserInput: boolean): string {\n const [display, setDisplay] = useState('');\n const indexRef = useRef(0);\n const charRef = useRef(0);\n const phaseRef = useRef<'typing' | 'pause' | 'erasing'>('typing');\n\n useEffect(() => {\n indexRef.current = 0;\n charRef.current = 0;\n phaseRef.current = 'typing';\n setDisplay('');\n\n if (hasUserInput || prompts.length === 0) {\n return;\n }\n\n const tick = () => {\n const currentPrompt = prompts[indexRef.current];\n\n if (phaseRef.current === 'typing') {\n charRef.current++;\n setDisplay(currentPrompt.slice(0, charRef.current));\n if (charRef.current >= currentPrompt.length) {\n phaseRef.current = 'pause';\n }\n } else if (phaseRef.current === 'pause') {\n phaseRef.current = 'erasing';\n } else if (phaseRef.current === 'erasing') {\n charRef.current--;\n setDisplay(currentPrompt.slice(0, charRef.current));\n if (charRef.current <= 0) {\n phaseRef.current = 'typing';\n indexRef.current = (indexRef.current + 1) % prompts.length;\n }\n }\n };\n\n const getDelay = () => {\n if (phaseRef.current === 'pause') {\n return 800;\n }\n if (phaseRef.current === 'erasing') {\n return 15;\n }\n return 30 + Math.random() * 20;\n };\n\n let timeoutId: ReturnType<typeof setTimeout>;\n const schedule = () => {\n timeoutId = setTimeout(() => {\n tick();\n schedule();\n }, getDelay());\n };\n schedule();\n\n return () => clearTimeout(timeoutId);\n }, [hasUserInput, prompts]);\n\n if (hasUserInput || prompts.length === 0) {\n return staticPlaceholder;\n }\n\n return display;\n}\n","import { type KeyboardEvent, useRef, useState, useEffect, useCallback } from 'react';\nimport { IconButton, Input, useStyles2 } from '@grafana/ui';\nimport { css, cx, keyframes } from '@emotion/css';\nimport type { GrafanaTheme2 } from '@grafana/data';\nimport { reportInteraction } from '@grafana/runtime';\nimport type { ChatContextItem } from '../../context/types';\nimport { useAssistant } from '../../hook';\nimport type { OpenAssistantProps } from '../../sidebar';\nimport { createBorderAnimation, getBackgroundGradientColors } from '../../utils/theme';\nimport { useAnimatedPlaceholder, DEFAULT_EXAMPLE_PROMPTS } from './useAnimatedPlaceholder';\n\nexport interface AssistantPromptCardProps {\n /** Origin of the request for analytics tracking. Should be a structured string using forward slashes. */\n origin: string;\n /** Context items passed to the assistant on submit. Created with `createAssistantContextItem`. */\n context?: ChatContextItem[];\n /** Assistant mode (e.g. 'dashboarding'). Defaults to 'assistant'. */\n mode?: string;\n /** Placeholder text for the input. */\n placeholder?: string;\n /** Example prompts to cycle through as animated placeholder text. Pass an empty array to disable. */\n examplePrompts?: string[];\n /** Called when the card should close (Escape key, close button). */\n onClose?: () => void;\n /** Called after a prompt is submitted, receives the prompt string. */\n onSubmit?: (prompt: string) => void;\n /** Called when the user clicks the card body. */\n onClick?: () => void;\n /** Whether the card border is animated. Defaults to true. */\n animated?: boolean;\n /** Extra CSS class for the root element. */\n className?: string;\n}\n\n/**\n * A prompt card component that opens the Grafana Assistant with a user-typed prompt and context.\n * Renders nothing if the assistant is not available. Positioning is the consumer's responsibility.\n */\nexport function AssistantPromptCard(props: AssistantPromptCardProps) {\n const { isAvailable, openAssistant } = useAssistant();\n if (!isAvailable || !openAssistant) {\n return null;\n }\n return <AssistantPromptCardView {...props} openAssistant={openAssistant} />;\n}\n\nexport interface AssistantPromptCardViewProps extends AssistantPromptCardProps {\n openAssistant: (props: OpenAssistantProps) => void;\n}\n\nexport function AssistantPromptCardView({\n origin,\n context,\n mode,\n placeholder,\n examplePrompts,\n animated = true,\n onClose,\n onSubmit,\n onClick,\n className,\n openAssistant,\n}: AssistantPromptCardViewProps) {\n const [prompt, setPrompt] = useState('');\n const inputRef = useRef<HTMLInputElement>(null);\n const styles = useStyles2(getStyles);\n const resolvedPrompts = examplePrompts ?? (placeholder !== undefined ? [] : DEFAULT_EXAMPLE_PROMPTS);\n const staticPlaceholder = placeholder ?? 'Ask Assistant...';\n const animatedPlaceholder = useAnimatedPlaceholder(staticPlaceholder, resolvedPrompts, prompt.length > 0);\n\n useEffect(() => {\n reportInteraction('grafana_assistant_app_prompt_card_displayed', { from: origin });\n }, [origin]);\n\n // biome-ignore lint/correctness/useExhaustiveDependencies: context is an intentional re-trigger to re-focus the input when the context changes\n useEffect(() => {\n const rafId = requestAnimationFrame(() => inputRef.current?.focus());\n return () => cancelAnimationFrame(rafId);\n }, [context]);\n\n const submit = useCallback(\n (text: string) => {\n const trimmed = text.trim();\n if (!trimmed) {\n return;\n }\n\n openAssistant({ prompt: trimmed, context, autoSend: true, origin, mode });\n onSubmit?.(trimmed);\n setPrompt('');\n },\n [openAssistant, context, origin, mode, onSubmit]\n );\n\n const handleKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {\n if (e.key === 'Enter' && !e.shiftKey) {\n e.preventDefault();\n submit(prompt);\n }\n\n if (e.key === 'Escape') {\n e.preventDefault();\n onClose?.();\n }\n };\n\n return (\n <div\n className={cx(animated ? styles.card : styles.cardStatic, className)}\n onClick={onClick}\n role=\"search\"\n aria-label={staticPlaceholder}\n data-testid=\"assistant-prompt-card\"\n >\n <div className={styles.inputRow}>\n <Input\n ref={inputRef}\n value={prompt}\n onChange={(e) => setPrompt(e.currentTarget.value)}\n onKeyDown={handleKeyDown}\n placeholder={animatedPlaceholder}\n suffix={\n <IconButton\n name=\"ai-sparkle\"\n onClick={() => submit(prompt)}\n disabled={!prompt.trim()}\n tooltip=\"Send to assistant\"\n aria-label=\"Send to assistant\"\n data-testid=\"assistant-prompt-card-send\"\n />\n }\n data-testid=\"assistant-prompt-card-input\"\n />\n </div>\n </div>\n );\n}\n\nfunction getGlowShadow(theme: GrafanaTheme2) {\n const baseShadow = theme.isDark ? 'rgb(17 18 23)' : 'rgb(245 245 245)';\n return [\n 'rgba(168, 85, 247, 0.25) 3px -1px 20px',\n 'rgba(249, 115, 22, 0.18) -5px 3px 40px',\n 'rgba(168, 85, 247, 0.12) 7px 4px 60px',\n `${baseShadow} 0 6px 30px`,\n ].join(', ');\n}\n\nconst getStyles = (theme: GrafanaTheme2) => {\n const backgroundColor = theme.colors.background.primary;\n const [gradientColor1, gradientColor2] = getBackgroundGradientColors(theme);\n\n const borderAnimation = keyframes({\n label: 'prompt-card-border',\n ...createBorderAnimation(theme, backgroundColor),\n });\n\n const cardBase = {\n label: 'assistant-prompt-card',\n position: 'relative' as const,\n display: 'flex',\n flexDirection: 'column' as const,\n gap: theme.spacing(1),\n padding: theme.spacing(1),\n borderRadius: theme.shape.radius.lg,\n boxShadow: getGlowShadow(theme),\n };\n\n return {\n card: css({\n ...cardBase,\n cornerShape: 'squircle',\n background: backgroundColor,\n border: '1px solid transparent',\n backgroundImage: `\n linear-gradient(${backgroundColor}, ${backgroundColor}),\n conic-gradient(from 0deg, transparent 60%, ${gradientColor1} 80%, ${gradientColor2} 100%, transparent 15%)\n `,\n backgroundOrigin: 'border-box',\n backgroundClip: 'padding-box, border-box',\n [theme.transitions.handleMotion('no-preference')]: {\n animation: `${borderAnimation} 2s linear infinite`,\n },\n }),\n cardStatic: css({\n ...cardBase,\n label: 'assistant-prompt-card-static',\n background: theme.colors.background.elevated,\n border: `1px solid ${theme.colors.border.weak}`,\n }),\n inputRow: css({\n label: 'prompt-card-input-row',\n display: 'flex',\n alignItems: 'center',\n gap: theme.spacing(0.5),\n '& input': {\n border: 'none !important',\n },\n }),\n };\n};\n","import { extractErrorMessage } from '../utils/errorHandling';\nimport type { InvestigationLensError, InvestigationLensErrorCode } from './types';\n\n/**\n * Request passed to the lens implementation registered by the Grafana\n * Assistant plugin.\n */\nexport interface InvestigationLensRequest {\n investigationId: string;\n /** JSON Schema describing the shape of the desired structured view. */\n schema: unknown;\n /** Attribution for the generation, e.g. `'grafana-irm/incident-detail'`. */\n origin: string;\n /** When true, bypass the cached result and regenerate. */\n refresh?: boolean;\n}\n\n/**\n * The lens implementation provided by the Grafana Assistant plugin. Resolves\n * with data conforming to the request's schema, or rejects with an error\n * carrying an {@link InvestigationLensErrorCode} `code` property.\n */\nexport type InvestigationLensImplementation = (request: InvestigationLensRequest) => Promise<unknown>;\nexport type InvestigationLensInitializer = () => Promise<void>;\n\nconst LENS_ERROR_CODES: readonly InvestigationLensErrorCode[] = [\n 'unavailable',\n 'no_report',\n 'permission_denied',\n 'validation_failed',\n 'llm_error',\n];\n\nfunction isLensErrorCode(value: unknown): value is InvestigationLensErrorCode {\n return typeof value === 'string' && (LENS_ERROR_CODES as readonly string[]).includes(value);\n}\n\n/**\n * Typed error the lens implementation throws to signal a specific failure\n * mode. Consumers should not need this class — the hook converts failures to\n * plain {@link InvestigationLensError} values. Conversion is structural (it\n * reads the `code` property), so it works even when the host plugin and the\n * assistant plugin bundle different copies of this package.\n */\nexport class InvestigationLensRequestError extends Error {\n constructor(\n public readonly code: InvestigationLensErrorCode,\n message: string\n ) {\n super(message);\n this.name = 'InvestigationLensRequestError';\n }\n}\n\n/** Converts any thrown value into a plain, typed lens error. */\nexport function toInvestigationLensError(err: unknown): InvestigationLensError {\n if (err && typeof err === 'object' && 'code' in err && isLensErrorCode(err.code)) {\n return { code: err.code, message: extractErrorMessage(err) };\n }\n return { code: 'llm_error', message: extractErrorMessage(err) };\n}\n\n// Global registry keys for cross-plugin sharing: all plugins (and all copies\n// of this package) must observe the same implementation, regardless of which\n// bundle loads first.\nconst GLOBAL_IMPLEMENTATION_KEY = '__grafanaAssistantLensImplementation__';\nconst GLOBAL_INITIALIZER_KEY = '__grafanaAssistantLensInitializer__';\nconst GLOBAL_INITIALIZATION_PROMISE_KEY = '__grafanaAssistantLensInitPromise__';\n\nexport function setInvestigationLensImplementation(fn: InvestigationLensImplementation): void {\n const existing = window[GLOBAL_IMPLEMENTATION_KEY] as InvestigationLensImplementation | undefined;\n if (existing && existing !== fn) {\n console.warn('InvestigationLens implementation already set; ignoring subsequent call');\n return;\n }\n if (!existing) {\n window[GLOBAL_IMPLEMENTATION_KEY] = fn;\n }\n}\n\n/**\n * Register a lazy initializer that is called on first use. The Grafana\n * Assistant plugin registers this at bootstrap so the heavy implementation\n * loads only when a consumer actually requests a lens view.\n */\nexport function setInvestigationLensInitializer(fn: InvestigationLensInitializer): void {\n const existing = window[GLOBAL_INITIALIZER_KEY] as InvestigationLensInitializer | undefined;\n if (existing && existing !== fn) {\n console.warn('InvestigationLens initializer already set; ignoring subsequent call');\n return;\n }\n if (!existing) {\n window[GLOBAL_INITIALIZER_KEY] = fn;\n }\n}\n\n/**\n * Ensure the lens implementation is initialized, invoking the registered\n * initializer on first use. Throws an `unavailable` lens error when no\n * initializer is registered (assistant plugin missing or too old).\n */\nexport async function ensureInvestigationLensInitialized(): Promise<void> {\n const implementation = window[GLOBAL_IMPLEMENTATION_KEY] as InvestigationLensImplementation | undefined;\n if (implementation) {\n return;\n }\n\n const initializer = window[GLOBAL_INITIALIZER_KEY] as InvestigationLensInitializer | undefined;\n if (!initializer) {\n throw new InvestigationLensRequestError(\n 'unavailable',\n 'Investigation lens is not available. Make sure the Grafana Assistant plugin is installed and up to date.'\n );\n }\n\n // If initialization is in progress, wait for it\n const existingPromise = window[GLOBAL_INITIALIZATION_PROMISE_KEY] as Promise<void> | null | undefined;\n if (existingPromise !== null && existingPromise !== undefined) {\n return existingPromise;\n }\n\n const initPromise = (async () => {\n try {\n await initializer();\n } catch (err) {\n // Reset on error so retry is possible\n window[GLOBAL_INITIALIZATION_PROMISE_KEY] = null;\n throw err;\n }\n })();\n\n window[GLOBAL_INITIALIZATION_PROMISE_KEY] = initPromise;\n return initPromise;\n}\n\nexport function getInvestigationLensImplementation(): InvestigationLensImplementation {\n const implementation = window[GLOBAL_IMPLEMENTATION_KEY] as InvestigationLensImplementation | undefined;\n if (!implementation) {\n throw new InvestigationLensRequestError(\n 'unavailable',\n 'Investigation lens is not available. Make sure the Grafana Assistant plugin is installed and up to date.'\n );\n }\n return implementation;\n}\n","// biome.json disables noMisusedPromises here: Biome 2.5.14 stack-overflows resolving FromSchema with dependencies installed.\n// Retest after upgrading Biome; see docs/biome-ratchet.md#biome-2514-exception.\n\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport type { FromSchema, JSONSchema } from 'json-schema-to-ts';\n\nimport {\n ensureInvestigationLensInitialized,\n getInvestigationLensImplementation,\n toInvestigationLensError,\n} from './investigationLens';\nimport type {\n InvestigationLensState,\n UseInvestigationThroughLensOptions,\n UseInvestigationThroughLensResult,\n} from './types';\n\n/**\n * Derives a structured, LLM-generated view of an investigation's report,\n * shaped by a caller-provided JSON Schema. Declarative: generation runs on\n * mount and whenever the schema or investigation changes; results are cached\n * by the Grafana Assistant plugin per (investigation, schema, report\n * content), so remounts don't regenerate for an unchanged report.\n *\n * Field `description`s are per-field instructions to the model — that is the\n * steering mechanism. Deterministic facts (ids, titles, statuses, timestamps,\n * links) are provided to the model verbatim and copied through rather than\n * generated, so reserve schema fields for genuine synthesis from the report.\n *\n * Declare the schema with `as const` to get a fully typed `data` inferred\n * from the schema (via `json-schema-to-ts`):\n *\n * @example\n * ```typescript\n * const schema = {\n * type: 'object',\n * properties: {\n * headline: {\n * type: 'string',\n * description: 'One sentence describing the incident for an executive audience, max 80 characters.',\n * },\n * followUps: {\n * type: 'array',\n * description: 'Concrete follow-up actions to prevent recurrence.',\n * items: {\n * type: 'object',\n * properties: {\n * action: { type: 'string' },\n * urgency: { type: 'string', enum: ['now', 'this-week', 'backlog'] },\n * },\n * required: ['action', 'urgency'],\n * additionalProperties: false,\n * },\n * },\n * },\n * required: ['headline', 'followUps'],\n * additionalProperties: false,\n * } as const;\n *\n * function IncidentReview({ investigationId }: { investigationId: string }) {\n * const lens = useInvestigationThroughLens(schema, investigationId, {\n * origin: 'grafana-irm/incident-review',\n * });\n *\n * if (lens.status === 'loading') return <Spinner />;\n * if (lens.status === 'error') return <span>{lens.error.message}</span>;\n * // lens.data.followUps[0].urgency is 'now' | 'this-week' | 'backlog'\n * return <h3>{lens.data.headline}</h3>;\n * }\n * ```\n *\n * Requires the Grafana Assistant plugin; when it is missing or outdated the\n * hook resolves to an `error` state with code `unavailable` — it never throws\n * into the host's render.\n *\n * Note on `enabled` gating: re-enabling serves cached results by default. If\n * the report may have changed while the hook was disabled — e.g. `enabled`\n * gates on the report streaming — set `refreshOnEnable: true` so the fetch\n * triggered by the false → true transition bypasses the caches once.\n */\nexport function useInvestigationThroughLens<S extends JSONSchema, T = FromSchema<S>>(\n schema: S,\n investigationId: string,\n options: UseInvestigationThroughLensOptions\n): UseInvestigationThroughLensResult<T> {\n const { origin, enabled = true, refreshOnEnable = false } = options;\n const [state, setState] = useState<InvestigationLensState<T>>({ status: 'loading' });\n\n // Key generation on the schema's content, not its identity: consumers\n // typically declare the schema inline, so the object is recreated every\n // render even though it never changes.\n const schemaJson = useMemo(() => JSON.stringify(schema), [schema]);\n\n // refresh() bumps the generation to re-run generation with a cache bypass.\n // The bypass is one-shot: the ref records which generation already consumed\n // it, so a later run triggered by a schema/investigation change (same\n // generation, different deps) does not inherit `refresh: true`.\n const [generation, setGeneration] = useState({ id: 0, bypassCache: false });\n const consumedGenerationRef = useRef(0);\n\n // For refreshOnEnable: tracks whether the previous effect run was enabled,\n // so the run triggered by a false → true transition bypasses caches exactly\n // once. Initialized to the mount-time value so a first mount with\n // `enabled: true` takes the normal cached path.\n const wasEnabledRef = useRef(enabled);\n\n const refresh = useCallback(() => {\n setGeneration((g) => ({ id: g.id + 1, bypassCache: true }));\n }, []);\n\n useEffect(() => {\n const wasEnabled = wasEnabledRef.current;\n wasEnabledRef.current = enabled;\n\n if (!enabled) {\n setState({ status: 'loading' });\n return;\n }\n\n let cancelled = false;\n const bypassFromRefresh = generation.bypassCache && consumedGenerationRef.current !== generation.id;\n consumedGenerationRef.current = generation.id;\n const bypassCache = bypassFromRefresh || (refreshOnEnable && !wasEnabled);\n setState({ status: 'loading' });\n\n void (async () => {\n try {\n await ensureInvestigationLensInitialized();\n const implementation = getInvestigationLensImplementation();\n const data = await implementation({\n investigationId,\n schema: JSON.parse(schemaJson),\n origin,\n refresh: bypassCache,\n });\n if (!cancelled) {\n setState({ status: 'success', data: data as T });\n }\n } catch (err) {\n if (!cancelled) {\n setState({ status: 'error', error: toInvestigationLensError(err) });\n }\n }\n })();\n\n return () => {\n cancelled = true;\n };\n }, [schemaJson, investigationId, origin, enabled, refreshOnEnable, generation]);\n\n return { ...state, refresh };\n}\n","import { globalConfig } from \"./core.js\";\n// functions\nexport function assertEqual(val) {\n return val;\n}\nexport function assertNotEqual(val) {\n return val;\n}\nexport function toZod() {\n return (schema) => schema;\n}\nexport function assertIs(_arg) { }\nexport function assertNever(_x) {\n throw new Error(\"Unexpected value in exhaustive check\");\n}\nexport function assert(_) { }\nexport function getEnumValues(entries) {\n const numericValues = Object.values(entries).filter((v) => typeof v === \"number\");\n const values = Object.entries(entries)\n .filter(([k, _]) => numericValues.indexOf(+k) === -1)\n .map(([_, v]) => v);\n return values;\n}\nexport function joinValues(array, separator = \"|\") {\n return array.map((val) => stringifyPrimitive(val)).join(separator);\n}\nexport function jsonStringifyReplacer(_, value) {\n if (typeof value === \"bigint\")\n return value.toString();\n return value;\n}\n// the accessor lives on a shared prototype: an own accessor makes every box a dictionary-mode object (~360 B and a slow load per read against ~100 B and an inlined getter here)\nclass Cached {\n constructor(getter) {\n this._getter = getter;\n this._value = undefined;\n }\n get value() {\n const getter = this._getter;\n if (getter !== undefined) {\n this._value = getter();\n this._getter = undefined;\n }\n return this._value;\n }\n}\nexport function cached(getter) {\n return new Cached(getter);\n}\nexport function nullish(input) {\n return input === null || input === undefined;\n}\nexport function cleanRegex(source) {\n const start = source.startsWith(\"^\") ? 1 : 0;\n const end = source.endsWith(\"$\") ? source.length - 1 : source.length;\n return source.slice(start, end);\n}\nexport function floatSafeRemainder(val, step) {\n const ratio = val / step;\n const roundedRatio = Math.round(ratio);\n // `val` and `step` each round to a double before the division rounds again, so a true decimal multiple's quotient can sit up to 1.5 of these scaled epsilons from the integer. A 1x tolerance therefore rejected 2.03 as a multiple of 0.07; 4x covers the worst case with margin.\n const tolerance = 4 * Number.EPSILON * Math.max(Math.abs(ratio), 1);\n if (Math.abs(ratio - roundedRatio) < tolerance)\n return 0;\n return ratio - roundedRatio;\n}\nconst EVALUATING = /* @__PURE__*/ Symbol(\"evaluating\");\nexport function defineLazy(object, key, getter) {\n let value = undefined;\n Object.defineProperty(object, key, {\n get() {\n if (value === EVALUATING) {\n // Circular reference detected, return undefined to break the cycle\n return undefined;\n }\n if (value === undefined) {\n value = EVALUATING;\n value = getter();\n }\n return value;\n },\n set(v) {\n Object.defineProperty(object, key, {\n value: v,\n // configurable: true,\n });\n // object[key] = v;\n },\n configurable: true,\n });\n}\nexport function objectClone(obj) {\n return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj));\n}\nexport function assignProp(target, prop, value) {\n Object.defineProperty(target, prop, {\n value,\n writable: true,\n enumerable: true,\n configurable: true,\n });\n}\n/**\n * Whichever object a def's `shape` currently answers from: the one the caller passed until the first read, the frozen copy after it.\n *\n * Its keys and descriptors read without invoking anything, which is what lets a discriminated union check its discriminator, and the cycle walk read a shape, without resolving a getter that references the schema being constructed. A def that answers `shape` from an accessor of its own has none.\n */\nexport function rawShape(def) {\n const desc = Object.getOwnPropertyDescriptor(def, \"shape\");\n return desc?.get ? desc.get.raw : desc?.value;\n}\n// where a builder reads its source's keys and descriptors, resolving only a shape a def answers for itself. A shape resolves by object spread, so only its enumerable keys are ever part of it.\nfunction sourceShape(schema) {\n return rawShape(schema._zod.def) ?? schema._zod.def.shape;\n}\n// a key whose value is not settled yet, self-caching so every read after the first gets the same one\nfunction deferProp(target, key, getter) {\n Object.defineProperty(target, key, {\n get() {\n const value = getter();\n assignProp(this, key, value);\n return value;\n },\n enumerable: true,\n configurable: true,\n });\n}\n// Writes a settled key. A plain assignment is much cheaper than `defineProperty` and produces the same descriptor, but it runs whatever setter already answers to the key — an accessor this shape deferred, or an inherited one, which `__proto__` has on every object and prototype pollution can add for any name.\nfunction putProp(target, key, value) {\n if (key in target)\n assignProp(target, key, value);\n else\n target[key] = value;\n}\n/**\n * Copies `keys` of `source`'s shape onto `target`, each value passed through `wrap`.\n *\n * A key the source has resolved is copied through now, so the derived shape states it outright and nothing has to resolve it to learn what it holds. A key the source still defers stays deferred, and reads back through the source's own `shape`, so it resolves once and both shapes get that one schema.\n */\nfunction mirrorShape(target, source, keys, wrap) {\n const raw = sourceShape(source);\n for (const key of keys) {\n const desc = Object.getOwnPropertyDescriptor(raw, key);\n if (!desc.enumerable)\n continue;\n if (desc.get) {\n deferProp(target, key, () => {\n const value = source._zod.def.shape[key];\n return wrap ? wrap(value, key) : value;\n });\n }\n else\n putProp(target, key, wrap ? wrap(desc.value, key) : desc.value);\n }\n}\n// same, for a plain shape a caller passed rather than a schema's\nfunction mirrorProps(target, source) {\n for (const key of Reflect.ownKeys(source)) {\n const desc = Object.getOwnPropertyDescriptor(source, key);\n if (!desc.enumerable)\n continue;\n if (desc.get)\n deferProp(target, key, () => source[key]);\n else\n putProp(target, key, desc.value);\n }\n}\nexport function mergeDefs(...defs) {\n const mergedDescriptors = {};\n for (const def of defs) {\n const descriptors = Object.getOwnPropertyDescriptors(def);\n Object.assign(mergedDescriptors, descriptors);\n }\n return Object.defineProperties({}, mergedDescriptors);\n}\nexport function cloneDef(schema) {\n return mergeDefs(schema._zod.def);\n}\nexport function getElementAtPath(obj, path) {\n if (!path)\n return obj;\n return path.reduce((acc, key) => acc?.[key], obj);\n}\nexport function promiseAllObject(promisesObj) {\n const keys = Object.keys(promisesObj);\n const promises = keys.map((key) => promisesObj[key]);\n return Promise.all(promises).then((results) => {\n const resolvedObj = {};\n for (let i = 0; i < keys.length; i++) {\n resolvedObj[keys[i]] = results[i];\n }\n return resolvedObj;\n });\n}\nexport function randomString(length = 10) {\n const chars = \"abcdefghijklmnopqrstuvwxyz\";\n let str = \"\";\n for (let i = 0; i < length; i++) {\n str += chars[Math.floor(Math.random() * chars.length)];\n }\n return str;\n}\nexport function esc(str) {\n return JSON.stringify(str);\n}\nexport function slugify(input) {\n return input\n .toLowerCase()\n .trim()\n .replace(/[^\\w\\s-]/g, \"\")\n .replace(/[\\s_-]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n}\nexport const captureStackTrace = (\"captureStackTrace\" in Error ? Error.captureStackTrace : (..._args) => { });\nexport function isObject(data) {\n return typeof data === \"object\" && data !== null && !Array.isArray(data);\n}\nexport const allowsEval = /* @__PURE__*/ cached(() => {\n // Skip the probe under `jitless`: strict CSPs report the caught `new Function` as a `securitypolicyviolation` even though the throw is swallowed.\n if (globalConfig.jitless) {\n return false;\n }\n // @ts-ignore\n if (typeof navigator !== \"undefined\" && navigator?.userAgent?.includes(\"Cloudflare\")) {\n return false;\n }\n try {\n const F = Function;\n new F(\"\");\n return true;\n }\n catch (_) {\n return false;\n }\n});\nexport function isPlainObject(o) {\n if (isObject(o) === false)\n return false;\n // modified constructor\n const ctor = o.constructor;\n if (ctor === undefined)\n return true;\n if (typeof ctor !== \"function\")\n return true;\n // modified prototype\n const prot = ctor.prototype;\n if (isObject(prot) === false)\n return false;\n // ctor doesn't have static `isPrototypeOf`\n if (Object.prototype.hasOwnProperty.call(prot, \"isPrototypeOf\") === false) {\n return false;\n }\n return true;\n}\nexport function shallowClone(o) {\n if (isPlainObject(o))\n return { ...o };\n if (Array.isArray(o))\n return [...o];\n if (o instanceof Map)\n return new Map(o);\n if (o instanceof Set)\n return new Set(o);\n return o;\n}\nexport function numKeys(data) {\n let keyCount = 0;\n for (const key in data) {\n if (Object.prototype.hasOwnProperty.call(data, key)) {\n keyCount++;\n }\n }\n return keyCount;\n}\nexport const getParsedType = (data) => {\n const t = typeof data;\n switch (t) {\n case \"undefined\":\n return \"undefined\";\n case \"string\":\n return \"string\";\n case \"number\":\n return Number.isNaN(data) ? \"nan\" : \"number\";\n case \"boolean\":\n return \"boolean\";\n case \"function\":\n return \"function\";\n case \"bigint\":\n return \"bigint\";\n case \"symbol\":\n return \"symbol\";\n case \"object\":\n if (Array.isArray(data)) {\n return \"array\";\n }\n if (data === null) {\n return \"null\";\n }\n if (data.then && typeof data.then === \"function\" && data.catch && typeof data.catch === \"function\") {\n return \"promise\";\n }\n if (typeof Map !== \"undefined\" && data instanceof Map) {\n return \"map\";\n }\n if (typeof Set !== \"undefined\" && data instanceof Set) {\n return \"set\";\n }\n if (typeof Date !== \"undefined\" && data instanceof Date) {\n return \"date\";\n }\n // @ts-ignore\n if (typeof File !== \"undefined\" && data instanceof File) {\n return \"file\";\n }\n return \"object\";\n default:\n throw new Error(`Unknown data type: ${t}`);\n }\n};\nexport const propertyKeyTypes = /* @__PURE__*/ new Set([\"string\", \"number\", \"symbol\"]);\nexport const primitiveTypes = /* @__PURE__*/ new Set([\n \"string\",\n \"number\",\n \"bigint\",\n \"boolean\",\n \"symbol\",\n \"undefined\",\n]);\nexport function escapeRegex(str) {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n// zod-specific utils\nexport function clone(inst, def, params) {\n const cl = new inst._zod.constr(def ?? inst._zod.def);\n if (!def || params?.parent)\n cl._zod.parent = inst;\n return cl;\n}\nexport function normalizeParams(_params) {\n const params = _params;\n if (!params)\n return {};\n if (typeof params === \"string\")\n return { error: () => params };\n if (params?.message !== undefined) {\n if (params?.error !== undefined)\n throw new Error(\"Cannot specify both `message` and `error` params\");\n params.error = params.message;\n }\n delete params.message;\n if (typeof params.error === \"string\")\n return { ...params, error: () => params.error };\n return params;\n}\nexport function createTransparentProxy(getter) {\n let target;\n return new Proxy({}, {\n get(_, prop, receiver) {\n target ?? (target = getter());\n return Reflect.get(target, prop, receiver);\n },\n set(_, prop, value, receiver) {\n target ?? (target = getter());\n return Reflect.set(target, prop, value, receiver);\n },\n has(_, prop) {\n target ?? (target = getter());\n return Reflect.has(target, prop);\n },\n deleteProperty(_, prop) {\n target ?? (target = getter());\n return Reflect.deleteProperty(target, prop);\n },\n ownKeys(_) {\n target ?? (target = getter());\n return Reflect.ownKeys(target);\n },\n getOwnPropertyDescriptor(_, prop) {\n target ?? (target = getter());\n return Reflect.getOwnPropertyDescriptor(target, prop);\n },\n defineProperty(_, prop, descriptor) {\n target ?? (target = getter());\n return Reflect.defineProperty(target, prop, descriptor);\n },\n });\n}\nexport function stringifyPrimitive(value) {\n if (typeof value === \"bigint\")\n return value.toString() + \"n\";\n if (typeof value === \"string\")\n return `\"${value}\"`;\n return `${value}`;\n}\nexport function optionalKeys(shape) {\n return Object.keys(shape).filter((k) => {\n return shape[k]._zod.optin !== undefined && shape[k]._zod.optout === \"optional\";\n });\n}\n// Wrapped in a `@__PURE__` IIFE: esbuild never tree-shakes a top-level initializer that contains a member access on `Number`, so the bare object literal survived into every bundle.\nexport const NUMBER_FORMAT_RANGES = /*@__PURE__*/ (() => ({\n safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],\n int32: [-2147483648, 2147483647],\n uint32: [0, 4294967295],\n float32: [-3.4028234663852886e38, 3.4028234663852886e38],\n float64: [-Number.MAX_VALUE, Number.MAX_VALUE],\n}))();\nexport const BIGINT_FORMAT_RANGES = {\n int64: [/* @__PURE__*/ BigInt(\"-9223372036854775808\"), /* @__PURE__*/ BigInt(\"9223372036854775807\")],\n uint64: [/* @__PURE__*/ BigInt(0), /* @__PURE__*/ BigInt(\"18446744073709551615\")],\n};\nexport function pick(schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".pick() cannot be used on object schemas containing refinements\");\n }\n const newShape = {};\n mirrorShape(newShape, schema, maskedKeys(schema, mask));\n return clone(schema, mergeDefs(currDef, { shape: newShape, checks: [] }));\n}\n// the mask keys that select something, checked against the source's shape without resolving it\nfunction maskedKeys(schema, mask) {\n const raw = sourceShape(schema);\n const keys = [];\n // `for...in` skips symbols, so a symbol in the mask would select nothing\n for (const key of Reflect.ownKeys(mask)) {\n if (!Object.getOwnPropertyDescriptor(raw, key)?.enumerable) {\n throw new Error(`Unrecognized key: \"${String(key)}\"`);\n }\n if (mask[key])\n keys.push(key);\n }\n return keys;\n}\nexport function omit(schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".omit() cannot be used on object schemas containing refinements\");\n }\n const omitted = new Set(maskedKeys(schema, mask));\n const newShape = {};\n mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)).filter((key) => !omitted.has(key)));\n return clone(schema, mergeDefs(currDef, { shape: newShape, checks: [] }));\n}\nexport function extend(schema, shape) {\n if (!isPlainObject(shape)) {\n throw new Error(\"Invalid input to extend: expected a plain object\");\n }\n const checks = schema._zod.def.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n // Only throw if new shape overlaps with existing shape. Use getOwnPropertyDescriptor to check key existence without accessing values\n const existingShape = sourceShape(schema);\n for (const key of Reflect.ownKeys(shape)) {\n if (Object.getOwnPropertyDescriptor(existingShape, key) !== undefined) {\n throw new Error(\"Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.\");\n }\n }\n }\n return clone(schema, mergeDefs(schema._zod.def, { shape: extended(schema, shape) }));\n}\n// the source's keys, then the caller's overlaid on top\nfunction extended(schema, shape) {\n const newShape = {};\n mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)));\n mirrorProps(newShape, shape);\n return newShape;\n}\nexport function safeExtend(schema, shape) {\n if (!isPlainObject(shape)) {\n throw new Error(\"Invalid input to safeExtend: expected a plain object\");\n }\n return clone(schema, mergeDefs(schema._zod.def, { shape: extended(schema, shape) }));\n}\nexport function merge(a, b) {\n if (!b?._zod?.def) {\n throw new Error(\"Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.\");\n }\n if (a._zod.def.checks?.length) {\n throw new Error(\".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.\");\n }\n const newShape = {};\n mirrorShape(newShape, a, Reflect.ownKeys(sourceShape(a)));\n mirrorShape(newShape, b, Reflect.ownKeys(sourceShape(b)));\n const def = mergeDefs(a._zod.def, {\n shape: newShape,\n get catchall() {\n return b._zod.def.catchall;\n },\n checks: b._zod.def.checks ?? [],\n });\n return clone(a, def);\n}\nexport function partial(Class, schema, mask, name = \"partial\") {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(`.${name}() cannot be used on object schemas containing refinements`);\n }\n const selected = mask ? new Set(maskedKeys(schema, mask)) : undefined;\n const newShape = {};\n mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)), Class &&\n ((value, key) => (selected && !selected.has(key) ? value : new Class({ type: \"optional\", innerType: value }))));\n return clone(schema, mergeDefs(schema._zod.def, { shape: newShape, checks: [] }));\n}\nexport function required(Class, schema, mask) {\n const selected = mask ? new Set(maskedKeys(schema, mask)) : undefined;\n const newShape = {};\n mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)), (value, key) => \n // overwrite with non-optional\n selected && !selected.has(key) ? value : new Class({ type: \"nonoptional\", innerType: value }));\n return clone(schema, mergeDefs(schema._zod.def, { shape: newShape }));\n}\n// invalid_type | too_big | too_small | invalid_format | not_multiple_of | unrecognized_keys | invalid_union | invalid_key | invalid_element | invalid_value | custom\nexport function aborted(x, startIndex = 0) {\n if (x.aborted === true)\n return true;\n for (let i = startIndex; i < x.issues.length; i++) {\n if (x.issues[i]?.continue !== true) {\n return true;\n }\n }\n return false;\n}\n// Checks for explicit abort (continue === false), as opposed to implicit abort (continue === undefined). Used to respect `abort: true` in .refine() even for checks that have a `when` function.\nexport function explicitlyAborted(x, startIndex = 0) {\n if (x.aborted === true)\n return true;\n for (let i = startIndex; i < x.issues.length; i++) {\n if (x.issues[i]?.continue === false) {\n return true;\n }\n }\n return false;\n}\nexport function prefixIssues(path, issues) {\n return issues.map((iss) => {\n var _a;\n (_a = iss).path ?? (_a.path = []);\n iss.path.unshift(path);\n return iss;\n });\n}\nexport function unwrapMessage(message) {\n return typeof message === \"string\" ? message : message?.message;\n}\n/* A check holds no link back to the schema it is attached to — the same check instance is shared by every clone of that schema — so the owner is stamped onto the issues a check just raised, at the only point where both are in scope. Runs on the failure path only; `start` is the issue count from before the check ran. */\n/** The leading size checks of `defChecks` that set an upper bound, each paired with it. */\nexport function sizeCaps(defChecks) {\n const caps = [];\n for (const ch of defChecks ?? []) {\n const d = ch._zod.def;\n // a later check may rewrite the value\n if (!/_(length|size)$|_equals$/.test(d.check))\n break;\n const max = d.maximum ?? d.length ?? d.size;\n if (max >= 0)\n caps.push([max, ch]);\n }\n return caps;\n}\nexport function attachSchema(issues, start, inst) {\n var _a;\n for (let i = start; i < issues.length; i++) {\n (_a = issues[i]).schema ?? (_a.schema = inst);\n }\n}\nexport function finalizeIssue(iss, ctx, config) {\n var _a;\n // A schema that raised an issue itself owns it outright, and outranks any stamp an enclosing check left in `attachSchema`. String formats and z.custom() are schema and check at once, so when they act as a check they defer to that stamp instead.\n const traits = iss.inst?._zod?.traits;\n if (traits?.has(\"$ZodType\")) {\n if (traits.has(\"$ZodCheck\"))\n (_a = iss).schema ?? (_a.schema = iss.inst);\n else\n iss.schema = iss.inst;\n }\n // Decreasing specificity, first map to return a message wins. `inst` is whatever raised the issue, so a check's own map outranks the owning schema's.\n const schemaError = iss.schema !== iss.inst ? iss.schema?._zod.def?.error : undefined;\n const message = iss.message\n ? iss.message\n : (unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ??\n unwrapMessage(schemaError?.(iss)) ??\n unwrapMessage(ctx?.error?.(iss)) ??\n unwrapMessage(config.customError?.(iss)) ??\n unwrapMessage(config.localeError?.(iss)) ??\n \"Invalid input\");\n // an explicit own-key copy beats object rest with excluded keys, which v8 routes through a generic runtime call; Object.keys rather than for-in so an issue pushed with a prototype does not leak inherited keys, and an own __proto__ key is dropped rather than assigned through the setter\n const full = {};\n for (const k of Object.keys(iss)) {\n if (k === \"inst\" || k === \"schema\" || k === \"continue\" || k === \"input\" || k === \"__proto__\")\n continue;\n full[k] = iss[k];\n }\n full.path ?? (full.path = []);\n full.message = message;\n if (ctx?.reportInput) {\n full.input = iss.input;\n }\n return full;\n}\nexport function getSizableOrigin(input) {\n if (input instanceof Set)\n return \"set\";\n if (input instanceof Map)\n return \"map\";\n // @ts-ignore\n if (input instanceof File)\n return \"file\";\n return \"unknown\";\n}\nconst highSurrogate = /[\\uD800-\\uDBFF]/;\n// Code points in `str`: a surrogate pair counts once, a lone surrogate as itself. Hand-rolled because the string iterator allocates and runs ~250x slower on this path; the regex probe exits ~50x quicker for a string with no astral characters.\nexport function codePointLength(str) {\n const units = str.length;\n if (!highSurrogate.test(str))\n return units;\n let count = units;\n for (let i = 0; i < units - 1; i++) {\n if ((str.charCodeAt(i) & 0xfc00) === 0xd800 && (str.charCodeAt(i + 1) & 0xfc00) === 0xdc00) {\n count--;\n i++;\n }\n }\n return count;\n}\nexport function getLengthableOrigin(input) {\n if (Array.isArray(input))\n return \"array\";\n if (typeof input === \"string\")\n return \"string\";\n return \"unknown\";\n}\nexport function parsedType(data) {\n const t = typeof data;\n switch (t) {\n case \"number\": {\n return Number.isNaN(data) ? \"nan\" : \"number\";\n }\n case \"object\": {\n if (data === null) {\n return \"null\";\n }\n if (Array.isArray(data)) {\n return \"array\";\n }\n const obj = data;\n if (obj && Object.getPrototypeOf(obj) !== Object.prototype && \"constructor\" in obj && obj.constructor) {\n return obj.constructor.name;\n }\n }\n }\n return t;\n}\nexport function issue(...args) {\n const [iss, input, inst] = args;\n if (typeof iss === \"string\") {\n return {\n message: iss,\n code: \"custom\",\n input,\n inst,\n };\n }\n return { ...iss };\n}\nexport function cleanEnum(obj) {\n return Object.entries(obj)\n .filter(([k, _]) => {\n // return true if NaN, meaning it's not a number, thus a string key\n return Number.isNaN(Number.parseInt(k, 10));\n })\n .map((el) => el[1]);\n}\n// Codec utility functions\nexport function base64ToUint8Array(base64) {\n const binaryString = atob(base64);\n const bytes = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n bytes[i] = binaryString.charCodeAt(i);\n }\n return bytes;\n}\nexport function uint8ArrayToBase64(bytes) {\n let binaryString = \"\";\n for (let i = 0; i < bytes.length; i++) {\n binaryString += String.fromCharCode(bytes[i]);\n }\n return btoa(binaryString);\n}\nexport function base64urlToUint8Array(base64url) {\n const base64 = base64url.replace(/-/g, \"+\").replace(/_/g, \"/\");\n const padding = \"=\".repeat((4 - (base64.length % 4)) % 4);\n return base64ToUint8Array(base64 + padding);\n}\nexport function uint8ArrayToBase64url(bytes) {\n return uint8ArrayToBase64(bytes).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=/g, \"\");\n}\nexport function hexToUint8Array(hex) {\n const cleanHex = hex.replace(/^0x/, \"\");\n if (cleanHex.length % 2 !== 0) {\n throw new Error(\"Invalid hex string length\");\n }\n const bytes = new Uint8Array(cleanHex.length / 2);\n for (let i = 0; i < cleanHex.length; i += 2) {\n bytes[i / 2] = Number.parseInt(cleanHex.slice(i, i + 2), 16);\n }\n return bytes;\n}\nexport function uint8ArrayToHex(bytes) {\n return Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n// instanceof\nexport class Class {\n constructor(..._args) { }\n}\n////////// PROTOTYPE INSTALLERS //////////\n//\n// Members live on the prototype and materialize per instance on first read, which keeps own-property count under the step where V8 stops using inline slots. Changing anything here means re-measuring runtime, memory and bundle size together — see \"The three axes\" in AGENTS.md.\n/**\n * Installs a trait's members on its prototype. Each value builds that member for the instance on first read; the built value shadows the accessor as an own property, so a detached `const { parse } = schema` keeps working.\n *\n * Call this from a `proto` initializer, which runs once per prototype — never per instance.\n */\nexport function members(proto, table) {\n for (const key in table) {\n const desc = Object.getOwnPropertyDescriptor(table, key);\n // a getter installs as written, so it stays live: `description` reads through to the registry on every access. not enumerable: an object literal's is, and a prototype member never was\n if (desc.get)\n Object.defineProperty(proto, key, { ...desc, enumerable: false });\n // a method materializes bound on first read, which is what keeps a detached member working: `const opt = schema.optional; opt()`\n else\n defineBound(proto, key, desc.value);\n }\n}\n/** Shadows a prototype member with an own value, so a getter that builds from the instance runs once. */\nexport function own(inst, key, value, enumerable = true) {\n Object.defineProperty(inst, key, { configurable: true, writable: true, enumerable, value });\n return value;\n}\n/** Like {@link own}, for a member that was never an own data property and has to stay out of `Object.keys`. */\nexport function hide(inst, key, value) {\n return own(inst, key, value, false);\n}\n/** Adds members a table derives from the instance: each builds on first read and shadows as own data, and assignment shadows the same way, as when these were own properties. */\nexport /*@__NO_SIDE_EFFECTS__*/ function derived(computes, table) {\n for (const key in computes) {\n const compute = computes[key];\n // an object literal's accessor is configurable and enumerable, and `members` copies the descriptor as written\n Object.defineProperty(table, key, {\n configurable: true,\n enumerable: true,\n get() {\n return own(this, key, compute(this));\n },\n set(value) {\n own(this, key, value);\n },\n });\n }\n return table;\n}\nfunction defineBound(proto, key, fn) {\n Object.defineProperty(proto, key, {\n configurable: true,\n get() {\n // vitest's spyOn calls a prototype getter bare to find the function it wraps, so a nullish receiver answers the raw method\n return this == null ? fn : own(this, key, fn.bind(this));\n },\n set(value) {\n own(this, key, value);\n },\n });\n}\n/** Returns the prototype to install on, or `undefined` if this group is already installed on it. */\nfunction claim(inst, sentinel) {\n const proto = Object.getPrototypeOf(inst);\n // Runs on every construction, so `in` rather than the costlier `hasOwnProperty.call`. Sentinels are keys the group itself defines.\n return sentinel in proto ? undefined : proto;\n}\n// The internals whose init chain is installing. A second call for the same one is a derived constructor overriding its base, so it must not construct another schema in between or the override is dropped.\nlet installing;\n// Set while a getter is running, so a value that resolved through a recursion break is not memoized. One shared descriptor shadows the key for the duration, which costs no per-key allocation.\nlet broke = false;\nconst breaker = {\n configurable: true,\n get() {\n broke = true;\n return undefined;\n },\n};\n/**\n * Installs a lazily-derived internal on the `_zod` prototype of `inst`'s\n * constructor, computed from the internals object itself and cached there on\n * first read. One accessor per constructor rather than one per instance.\n */\nexport function defineLazyInternal(inst, key, compute) {\n const proto = Object.getPrototypeOf(inst._zod);\n if (key in proto && installing !== inst._zod) {\n // A repeat construction: everything is installed already. Cleared here so the reference is not held past the first construction of every type.\n installing = undefined;\n return;\n }\n installing = inst._zod;\n Object.defineProperty(proto, key, {\n configurable: true,\n get() {\n // Shadowed before computing so a re-entrant read from a recursive schema resolves to undefined instead of running the getter again.\n Object.defineProperty(this, key, breaker);\n const outer = broke;\n broke = false;\n try {\n const value = compute(this);\n // A result that resolved through a recursion break is recomputed once the graph is complete; everything else memoizes, undefined included.\n if (broke)\n delete this[key];\n else\n Object.defineProperty(this, key, { configurable: true, writable: true, value });\n broke = broke || outer;\n return value;\n }\n catch (err) {\n // A compute that threw memoizes nothing, so a later read runs it again and fails the same way. The shadow goes with it, since leaving it installed would answer undefined for every later read.\n delete this[key];\n broke = broke || outer;\n throw err;\n }\n },\n set(value) {\n Object.defineProperty(this, key, { configurable: true, writable: true, value });\n },\n });\n}\n/**\n * Installs `key` on `inst`'s prototype, computed by `make` on first read and cached there as an own\n * data property. One accessor per constructor rather than one per instance, because an own accessor\n * puts every instance after the first into v8 dictionary mode. The key doubles as the sentinel.\n */\nexport function installLazyProp(inst, key, make, enumerable) {\n const proto = claim(inst, key);\n if (!proto)\n return;\n Object.defineProperty(proto, key, {\n configurable: true,\n get() {\n // Shadowed before computing, so a re-entrant read from a self-referential shape resolves to undefined instead of running the getter again. A data property rather than an accessor: an own accessor is the dictionary-mode transition this exists to avoid.\n const desc = { configurable: true, writable: true, enumerable, value: undefined };\n Object.defineProperty(this, key, desc);\n // a compute that throws leaves the shadow behind, so later reads answer undefined instead of re-throwing; `defineLazy` did the same, and `defineLazyInternal`'s delete-on-catch would cost bytes in every bundle for a case only a throwing user getter reaches\n desc.value = make(this);\n Object.defineProperty(this, key, desc);\n return desc.value;\n },\n set(value) {\n Object.defineProperty(this, key, { configurable: true, writable: true, enumerable, value });\n },\n });\n}\n/** Marks the thunk `_catch` synthesises for a constant catch value. `Function.length` cannot tell that thunk from a user callback — rest and defaulted parameters both report arity 0 — and a user callback reads `ctx.error`, whose issues only finalize correctly against the caller's per-parse error map. Provenance can say what arity cannot. A plain string key rather than `Symbol.for`, whose call at module scope no bundler can prove pure — the same shape that anchored `urlCanParse` into every build. */\nexport const CONSTANT_CATCH = \"~constantCatch\";\n/** Wraps a constant catch value in a thunk tagged with {@link CONSTANT_CATCH}. */\nexport function constantCatch(value) {\n const fn = () => value;\n fn[CONSTANT_CATCH] = true;\n return fn;\n}\n","var _a;\nimport { members as installMembers } from \"./util.js\";\n/** A special constant with type `never` */\nexport const NEVER = /*@__PURE__*/ Object.freeze({\n status: \"aborted\",\n});\n/* Shared descriptor for installing `_zod`; defineProperty reads it\n * synchronously, so reusing one object avoids a per-instance allocation. */\nconst _zodDesc = { value: undefined, enumerable: false };\n// null where suppressing the capture would be unrecoverable: `parse()` puts the frames back with `captureStackTrace`, so without it the throw would lose its stack. also latched to null once `stackTraceLimit` proves unassignable, which a realm can do at any point by hardening Error\nlet _E = \"captureStackTrace\" in Error ? Error : null;\n// v8 captures a stack trace inside the Error constructor, which dominates a failed parse; costs only the frames, and parse() restores those. the constructor must RUN: Object.create is cheaper and passes instanceof, but Error.isError and util.types.isNativeError check an internal slot\nfunction newError(Definition) {\n const E = _E;\n if (E) {\n const saved = E.stackTraceLimit;\n if (typeof saved === \"number\") {\n try {\n E.stackTraceLimit = 0;\n }\n catch {\n _E = null;\n return new Definition();\n }\n try {\n return new Definition();\n }\n finally {\n E.stackTraceLimit = saved;\n }\n }\n }\n return new Definition();\n}\nexport /*@__NO_SIDE_EFFECTS__*/ function $constructor(name, initializer, \n/** This trait's members, installed once on every prototype that composes it. They cannot be declared in the initializer above: that runs per instance, and the prototype is shared. */\nproto, params) {\n // Prototype for this constructor's `_zod` internals. Lazily-derived fields (`values`, `pattern`, `optin`, …) install here once rather than as an accessor on every instance.\n const zodProto = {};\n // Assigning the fields in the constructor body is what gives instances in-object slots; building the object literally and reparenting it costs a second allocation and a generic property copy.\n function Internals(def) {\n this.def = def;\n this.constr = _;\n this.traits = new Set();\n }\n Internals.prototype = zodProto;\n const protoMembers = proto;\n // One trait's members land on every prototype whose chain composes it, so the answer is per prototype rather than per trait.\n const initialized = protoMembers && new WeakSet();\n function init(inst, def) {\n if (!inst._zod) {\n _zodDesc.value = new Internals(def);\n try {\n Object.defineProperty(inst, \"_zod\", _zodDesc);\n }\n finally {\n // Cleared even on throw, so the shared descriptor never leaks one instance's internals into the next.\n _zodDesc.value = undefined;\n }\n }\n else if (inst._zod.traits.has(name)) {\n return;\n }\n inst._zod.traits.add(name);\n initializer(inst, def);\n if (initialized) {\n // `super(def)` from a user subclass gives `this` a prototype the subclass owns, and installing there would overwrite whatever the subclass declared. `constr` built the instance, so its prototype is the one below the subclass's that should carry the members. A receiver whose chain never reaches that prototype installs on its own, which for a plain object handed straight to `init` means `Object.prototype` — unchanged from before.\n const own = Object.getPrototypeOf(inst);\n const ctorProto = inst._zod.constr.prototype;\n let up = own;\n while (up && up !== ctorProto)\n up = Object.getPrototypeOf(up);\n const target = up ?? own;\n if (!initialized.has(target)) {\n initialized.add(target);\n installMembers(target, protoMembers);\n }\n }\n // support prototype modifications; for-in avoids the array allocation of Object.keys on the (usually empty) prototype\n const proto = _.prototype;\n for (const k in proto) {\n if (!Object.prototype.hasOwnProperty.call(proto, k))\n continue;\n if (!(k in inst)) {\n inst[k] = proto[k].bind(inst);\n }\n }\n }\n // doesn't work if Parent has a constructor with arguments\n const Parent = params?.Parent ?? Object;\n class Definition extends Parent {\n }\n Object.defineProperty(Definition, \"name\", { value: name });\n function _(def) {\n const inst = params?.Parent ? newError(Definition) : this;\n init(inst, def);\n const deferred = inst._zod.deferred;\n if (deferred) {\n for (const fn of deferred) {\n fn();\n }\n // Released: initializers run once, and the list would otherwise be retained for the schema's lifetime.\n inst._zod.deferred = undefined;\n }\n // Global post-processor hook. Internal: installed by `import \"zod/compile\"` to enable AOT compilation for every constructed schema. Runs last, once the instance is fully built, because it hands the instance to compile(). The post-processor is expected to be reentrancy-guarded by its own implementation.\n const pp = globalThis.__zod_globalConfig?.postProcessor;\n if (pp)\n pp(inst);\n return inst;\n }\n Object.defineProperty(_, \"init\", { value: init });\n Object.defineProperty(_, Symbol.hasInstance, {\n value: (inst) => {\n if (params?.Parent && inst instanceof params.Parent)\n return true;\n return inst?._zod?.traits?.has(name);\n },\n });\n Object.defineProperty(_, \"name\", { value: name });\n return _;\n}\n////////////////////////////// UTILITIES ///////////////////////////////////////\nexport const $brand = /*@__PURE__*/ Symbol(\"zod_brand\");\nexport class $ZodAsyncError extends Error {\n constructor() {\n super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);\n }\n}\nexport class $ZodEncodeError extends Error {\n constructor(name) {\n super(`Encountered unidirectional transform during encode: ${name}`);\n this.name = \"ZodEncodeError\";\n }\n}\n(_a = globalThis).__zod_globalConfig ?? (_a.__zod_globalConfig = {});\nexport const globalConfig = globalThis.__zod_globalConfig;\nexport function config(newConfig) {\n if (newConfig)\n Object.assign(globalConfig, newConfig);\n return globalConfig;\n}\n","import * as util from \"./util.js\";\nexport class $ZodCyclicError extends Error {\n constructor() {\n super(`Cannot parse a reference cycle that closes through a transform`);\n this.name = \"ZodCyclicError\";\n }\n}\n/** Keyed off the context object every schema in one parse call already shares. */\nconst STATE = \"~memo\";\nconst NO_ISSUES = [];\n// a value a cycle can close through\nfunction isRef(value) {\n return value !== null && typeof value === \"object\";\n}\n// Receivers prefix paths in place, so the cache and every hand-out need their own copies.\nfunction cloneIssues(issues) {\n return issues.map((iss) => (iss.path ? { ...iss, path: iss.path.slice() } : { ...iss }));\n}\nconst recursive = /*@__PURE__*/ new WeakMap();\n/** What the walk established, in order of certainty: ordered so the strongest answer among children wins. */\nconst NONE = 0;\nconst ASSUMED = 1;\nconst PROVEN = 2;\n/** Whether this schema's subtree contains a cycle, so one parse can re-enter it. */\nfunction isRecursive(inst, stack, resolve) {\n const cached = recursive.get(inst);\n if (cached !== undefined)\n return cached ? PROVEN : NONE;\n // Relative to the walk in progress, so not cached.\n if (stack.has(inst))\n return PROVEN;\n stack.add(inst);\n let result = NONE;\n const check = (child) => {\n if (result !== PROVEN && child?._zod) {\n const answer = isRecursive(child, stack, resolve);\n if (answer > result)\n result = answer;\n }\n };\n // `Reflect.ownKeys` rather than `Object.keys`, so a cycle through a declared symbol key is still seen\n const shape = (sh, spread) => {\n let answer = NONE;\n for (const key of Reflect.ownKeys(sh)) {\n const desc = Object.getOwnPropertyDescriptor(sh, key);\n // an object resolves its shape by spread, so a key it does not enumerate is never parsed; `z.properties` reads every own key and so keeps them all\n if (spread && !desc.enumerable)\n continue;\n // resolving runs user code, and a factory mints a fresh subtree per read, so an edge the walk can't follow counts as a cycle\n const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve) : NONE;\n if (child > answer)\n answer = child;\n }\n return answer;\n };\n const merge = (answer) => {\n if (answer > result)\n result = answer;\n };\n const def = inst._zod.def;\n const kind = def.type;\n switch (kind) {\n case \"object\": {\n const raw = util.rawShape(def);\n // a def with no raw shape answers `shape` from an accessor of its own, and running that can mint a whole fresh subtree\n merge(raw ? shape(raw, true) : ASSUMED);\n check(def.catchall);\n break;\n }\n case \"array\":\n check(def.element);\n break;\n case \"tuple\":\n for (const el of def.items)\n check(el);\n check(def.rest);\n break;\n case \"record\":\n case \"map\":\n check(def.keyType);\n check(def.valueType);\n break;\n case \"set\":\n check(def.valueType);\n break;\n case \"union\":\n for (const el of def.options)\n check(el);\n break;\n case \"intersection\":\n check(def.left);\n check(def.right);\n break;\n case \"optional\":\n case \"nullable\":\n case \"default\":\n case \"prefault\":\n case \"catch\":\n case \"readonly\":\n case \"nonoptional\":\n case \"promise\":\n case \"success\":\n check(def.innerType);\n break;\n case \"pipe\":\n check(def.in);\n check(def.out);\n break;\n case \"function\":\n check(def.input);\n check(def.output);\n break;\n // `$ZodLazy` caches its inner on the def, so a resolved edge is followed exactly\n case \"lazy\": {\n const inner = def._cachedInner ?? (resolve ? inst._zod.innerType : undefined);\n // walked with resolution off: one hop sees past the deferral, and a lazy that yields only another unresolved lazy is generative, so it stops there\n merge(inner ? isRecursive(inner, stack, false) : ASSUMED);\n break;\n }\n // a leaf by choice: `parts` are regex fragments, not data positions\n case \"template_literal\":\n // leaves\n case \"string\":\n case \"number\":\n case \"int\":\n case \"boolean\":\n case \"bigint\":\n case \"symbol\":\n case \"undefined\":\n case \"null\":\n case \"void\":\n case \"never\":\n case \"any\":\n case \"unknown\":\n case \"date\":\n case \"nan\":\n case \"enum\":\n case \"literal\":\n case \"file\":\n case \"transform\":\n case \"custom\":\n break;\n default: {\n // a new built-in kind becomes a compile error here\n kind;\n // a user-defined kind can still hold children, and only its author knows where, so fall back to scanning the def — skipping accessors, since reading one can run user code\n for (const key in def) {\n const desc = Object.getOwnPropertyDescriptor(def, key);\n if (!desc || desc.get)\n continue;\n const value = desc.value;\n if (!value || typeof value !== \"object\")\n continue;\n if (value._zod)\n check(value);\n else if (Array.isArray(value))\n for (const el of value)\n check(el);\n }\n }\n }\n stack.delete(inst);\n return settle(inst, result);\n}\n/** An assumed answer must not outlive the resolution that settles it, so only a certain one is cached. */\nfunction settle(inst, answer) {\n if (answer !== ASSUMED)\n recursive.set(inst, answer === PROVEN);\n return answer;\n}\n/**\n * Whether one parse can re-enter this schema, i.e. its subtree contains a cycle.\n * Exported for `z.compile`, which refuses to compile such a schema: cycle\n * breaking is driven from here off state keyed on the parse context, and a\n * generated fast path has no context to key on.\n */\nexport function isRecursiveSchema(inst) {\n // z.compile never parses, so nothing would ever resolve a lazy for it; it runs once and already treats a throw here as recursive\n return isRecursive(inst, new Set(), true) !== NONE;\n}\nfunction bucketFor(state, inst) {\n let bucket = state.buckets.get(inst);\n if (!bucket) {\n bucket = new WeakMap();\n state.buckets.set(inst, bucket);\n }\n return bucket;\n}\n// Set immediately before delegating to core and cleared immediately after, so `alloc` registers only for a visit this module is driving.\nlet handoff;\n// Allocated but unfinished entries. `alloc` and the matching pop both happen in the synchronous part of a parse, so they nest even when children are async, and one stack serves every schema.\nconst open = [];\nconst memo = {\n alloc(_inst, payload, empty) {\n const bucket = handoff;\n if (!bucket)\n return empty;\n handoff = undefined;\n const entry = { value: empty, issues: null };\n bucket.set(payload.value, entry);\n open.push(entry);\n return empty;\n },\n guard(inst) {\n var _a;\n (_a = inst._zod).deferred ?? (_a.deferred = []);\n inst._zod.deferred.push(() => {\n const base = inst._zod.parse;\n const wrapped = (payload, ctx) => {\n // The value is a placeholder a back-edge is still waiting on, so the cycle closes through this transform. Its output can't exist in time to bind.\n if (ctx.direction !== \"backward\" && isBackEdge(ctx, payload.value))\n throw new $ZodCyclicError();\n return base(payload, ctx);\n };\n inst._zod.parse = wrapped;\n if (inst._zod.run === base)\n inst._zod.run = wrapped;\n });\n },\n attach(inst) {\n var _a;\n let isRecursiveInst;\n let rechecked = false;\n // a recursive schema is re-entered many times per parse and its bucket never changes\n let lastCtx;\n let lastBucket;\n // Wraps `parse` in a deferred so it sees the container's final parse. Core's own deferred copies `parse` into `run` when there are no checks, and it ran first, so `run` is patched to match; with checks, `run` reads `parse` dynamically.\n (_a = inst._zod).deferred ?? (_a.deferred = []);\n inst._zod.deferred.push(() => {\n const base = inst._zod.parse;\n const wrapped = (payload, ctx) => {\n if (isRecursiveInst === undefined) {\n const walked = isRecursive(inst, new Set(), false);\n if (walked === NONE) {\n // Nothing here can ever fire, so take it back out.\n inst._zod.parse = base;\n if (inst._zod.run === wrapped)\n inst._zod.run = base;\n return base(payload, ctx);\n }\n // this parse resolves the deferred edges on its own path, so ask once more before latching\n if (walked === PROVEN || rechecked)\n isRecursiveInst = true;\n else\n rechecked = true;\n }\n const input = payload.value;\n if (!isRef(input))\n return base(payload, ctx);\n let state = ctx[STATE];\n if (!state) {\n state = { buckets: new WeakMap(), backEdges: undefined };\n ctx[STATE] = state;\n }\n let bucket;\n if (lastCtx === ctx) {\n bucket = lastBucket;\n }\n else {\n bucket = bucketFor(state, inst);\n lastCtx = ctx;\n lastBucket = bucket;\n }\n const hit = bucket.get(input);\n if (hit) {\n payload.value = hit.value;\n if (hit.issues) {\n if (hit.issues.length)\n payload.issues.push(...cloneIssues(hit.issues));\n }\n else {\n // Still being parsed: its own checks cover it, so skip them here.\n payload.memo = true;\n state.backEdges ?? (state.backEdges = new WeakSet());\n state.backEdges.add(hit.value);\n }\n return payload;\n }\n handoff = bucket;\n const depth = open.length;\n const result = base(payload, ctx);\n handoff = undefined;\n // A container that rejected its input outright allocated nothing.\n const entry = open.length > depth ? open.pop() : undefined;\n // Both paths written out so the sync one allocates no closure. It runs once per node, and capturing here cost more than everything else combined.\n if (result instanceof Promise) {\n return result.then((r) => {\n if (entry)\n entry.issues = r.issues.length ? cloneIssues(r.issues) : NO_ISSUES;\n return r;\n });\n }\n if (entry)\n entry.issues = result.issues.length ? cloneIssues(result.issues) : NO_ISSUES;\n return result;\n };\n inst._zod.parse = wrapped;\n if (inst._zod.run === base)\n inst._zod.run = wrapped;\n });\n },\n};\n/** The memoizer that gives containers cycle support. `zod` installs it by default; `zod/mini` opts in with `config({ memoizer: memoizer() })`. */\nexport function memoizer() {\n return memo;\n}\n/** Whether this value is a node a back-edge resolved to before it finished. */\nexport function isBackEdge(ctx, value) {\n const backEdges = ctx[STATE]?.backEdges;\n return backEdges !== undefined && isRef(value) && backEdges.has(value);\n}\n","import * as util from \"./util.js\";\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link cuid2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport const cuid = /^[cC][0-9a-z]{6,}$/;\nexport const cuid2 = /^[0-9a-z]+$/;\nexport const ulid = /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/;\nexport const xid = /^[0-9a-vA-V]{20}$/;\nexport const ksuid = /^[A-Za-z0-9]{27}$/;\nexport const nanoid = /^[a-zA-Z0-9_-]{21}$/;\nexport function nanoidOfLength(length) {\n return new RegExp(`^[a-zA-Z0-9_-]{${length}}$`);\n}\n/** ISO 8601-1 duration regex. Does not support the 8601-2 extensions like negative durations or fractional/negative components. */\nexport const duration = /^P(?:(\\d+W)|(?!.*W)(?=\\d|T\\d)(\\d+Y)?(\\d+M)?(\\d+D)?(T(?=\\d)(\\d+H)?(\\d+M)?(\\d+([.,]\\d+)?S)?)?)$/;\n/** Implements ISO 8601-2 extensions like explicit +- prefixes, mixing weeks with other units, and fractional/negative components. */\nexport const extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\\d+Y)|(?:[-+]?\\d+[.,]\\d+Y$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:(?:[-+]?\\d+W)|(?:[-+]?\\d+[.,]\\d+W$))?(?:(?:[-+]?\\d+D)|(?:[-+]?\\d+[.,]\\d+D$))?(?:T(?=[\\d+-])(?:(?:[-+]?\\d+H)|(?:[-+]?\\d+[.,]\\d+H$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:[-+]?\\d+(?:[.,]\\d+)?S)?)??$/;\n/** A regex for any UUID-like identifier: 8-4-4-4-12 hex pattern */\nexport const guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;\n/** Returns a regex for validating an RFC 9562/4122 UUID.\n *\n * @param version Optionally specify a version 1-8. If no version is specified, all versions are supported. */\nexport const uuid = (version) => {\n if (!version)\n return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;\n return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);\n};\nexport const uuid4 = /*@__PURE__*/ uuid(4);\nexport const uuid6 = /*@__PURE__*/ uuid(6);\nexport const uuid7 = /*@__PURE__*/ uuid(7);\n/** Practical email validation */\nexport const email = /^(?:[A-Za-z0-9_'+\\-]+\\.)*[A-Za-z0-9_'+\\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$/;\n/** Equivalent to the HTML5 input[type=email] validation implemented by browsers. Source: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email */\nexport const html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n/** The classic emailregex.com regex for RFC 5322-compliant emails */\nexport const rfc5322Email = /^(([^<>()\\[\\]\\\\.,;:\\s@\"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/;\n/** A loose regex that allows Unicode characters, enforces length limits, and that's about it. */\nexport const unicodeEmail = /^[^\\s@\"]{1,64}@[^\\s@]{1,255}$/u;\nexport const idnEmail = unicodeEmail;\nexport const browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression\n// Single character class, not an alternation: the two properties overlap (U+1F9B0-U+1F9B3), so `(A|B)+` backtracks exponentially on a failed match. The leading lookahead then demands one anchor — a pictograph, a regional indicator, or the enclosing keycap — because `\\p{Emoji_Component}` on its own covers ASCII digits, `#`, `*`, ZWJ, variation selectors and skin tone modifiers, none of which is an emoji without a base.\nconst _emoji = `^(?=[\\\\s\\\\S]*[\\\\p{Extended_Pictographic}\\\\p{Regional_Indicator}\\\\u20E3])[\\\\p{Extended_Pictographic}\\\\p{Emoji_Component}]+$`;\nexport function emoji() {\n return new RegExp(_emoji, \"u\");\n}\nexport const ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;\nexport const ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;\nexport const mac = (delimiter) => {\n const escapedDelim = util.escapeRegex(delimiter ?? \":\");\n return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`);\n};\nexport const cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\/([0-9]|[1-2][0-9]|3[0-2])$/;\nexport const cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;\n// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript\nexport const base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;\nexport const base64url = /^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/;\n// based on https://stackoverflow.com/questions/106179/regular-expression-to-match-dns-hostname-or-ip-address\n// export const hostname: RegExp = /^([a-zA-Z0-9-]+\\.)*[a-zA-Z0-9-]+$/;\nexport const hostname = /^(?=.{1,253}\\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\\.?$/;\nexport const domain = /^(?=.{1,253}$)([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,63}$/;\nexport const httpProtocol = /^https?$/;\n// https://blog.stevenlevithan.com/archives/validate-phone-number#r4-3 (regex sans spaces) E.164: leading digit must be 1-9; total digits (excluding '+') between 7-15\nexport const e164 = /^\\+[1-9]\\d{6,14}$/;\n// Credit card shape: 12–19 digits, optionally separated by single spaces or single hyphens. ISO/IEC 7812 caps the PAN at 19 digits; 12 is the shortest issued length (Maestro).\nexport const creditCard = /^\\d(?:[ -]?\\d){11,18}$/;\n// ISO 4217 alpha codes from the SIX list, regenerated by scripts/update-iso-4217.ts\nexport const currencyCode = /^(?:AED|AFN|ALL|AMD|AOA|ARS|AUD|AWG|AZN|BAM|BBD|BDT|BHD|BIF|BMD|BND|BOB|BOV|BRL|BSD|BTN|BWP|BYN|BZD|CAD|CDF|CHE|CHF|CHW|CLF|CLP|CNY|COP|COU|CRC|CUP|CVE|CZK|DJF|DKK|DOP|DZD|EGP|ERN|ETB|EUR|FJD|FKP|GBP|GEL|GHS|GIP|GMD|GNF|GTQ|GYD|HKD|HNL|HTG|HUF|IDR|ILS|INR|IQD|IRR|ISK|JMD|JOD|JPY|KES|KGS|KHR|KMF|KPW|KRW|KWD|KYD|KZT|LAK|LBP|LKR|LRD|LSL|LYD|MAD|MDL|MGA|MKD|MMK|MNT|MOP|MRU|MUR|MVR|MWK|MXN|MXV|MYR|MZN|NAD|NGN|NIO|NOK|NPR|NZD|OMR|PAB|PEN|PGK|PHP|PKR|PLN|PYG|QAR|RON|RSD|RUB|RWF|SAR|SBD|SCR|SDG|SEK|SGD|SHP|SLE|SOS|SRD|SSP|STN|SVC|SYP|SZL|THB|TJS|TMT|TND|TOP|TRY|TTD|TWD|TZS|UAH|UGX|USD|USN|UYI|UYU|UYW|UZS|VED|VES|VND|VUV|WST|XAD|XAF|XAG|XAU|XBA|XBB|XBC|XBD|XCD|XCG|XDR|XOF|XPD|XPF|XPT|XSU|XTS|XUA|XXX|YER|ZAR|ZMW|ZWG)$/;\n// iban electronic format: 2-letter country, check digits 02-98 (the only values `98 - remainder` can produce), 11-30 bban characters\nexport const iban = /^[A-Z]{2}(?!00|01|99)\\d{2}[A-Z0-9]{11,30}$/;\nconst dateSource = `(?:(?:\\\\d\\\\d[2468][048]|\\\\d\\\\d[13579][26]|\\\\d\\\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\\\d|30)|(?:02)-(?:0[1-9]|1\\\\d|2[0-8])))`;\n/** Anchors a pattern source. The interpolation lives here rather than at the call site because\n * esbuild will not drop a `@__PURE__` call whose own argument interpolates a variable, but it\n * will drop `anchor(dateSource)`. Keeping it inline pinned `date` into every bundle. */\nfunction anchor(source) {\n return new RegExp(`^${source}$`);\n}\nexport const date = /*@__PURE__*/ anchor(dateSource);\nfunction timeSource(args) {\n const hhmm = `(?:[01]\\\\d|2[0-3]):[0-5]\\\\d`;\n const regex = typeof args.precision === \"number\"\n ? args.precision === -1\n ? `${hhmm}`\n : args.precision === 0\n ? `${hhmm}:[0-5]\\\\d`\n : `${hhmm}:[0-5]\\\\d\\\\.\\\\d{${args.precision}}`\n : args.seconds\n ? `${hhmm}:[0-5]\\\\d(?:\\\\.\\\\d+)?`\n : `${hhmm}(?::[0-5]\\\\d(?:\\\\.\\\\d+)?)?`;\n return regex;\n}\nexport function time(args) {\n return new RegExp(`^${timeSource(args)}$`);\n}\n// Adapted from https://stackoverflow.com/a/3143231\nexport function datetime(args) {\n const opts = [\"Z\"];\n // if (args.offset) opts.push(`([+-]\\\\d{2}:\\\\d{2})`);\n if (args.offset)\n opts.push(`([+-](?:[01]\\\\d|2[0-3]):[0-5]\\\\d)`);\n // RFC 3339 mandates seconds wherever the time carries a `Z` or an offset, so only the unqualified form `local` adds may omit them\n const qualified = `${timeSource({ precision: args.precision, seconds: true })}(?:${opts.join(\"|\")})`;\n const timeRegex = args.local ? `${qualified}|${timeSource({ precision: args.precision })}` : qualified;\n return new RegExp(`^${dateSource}T(?:${timeRegex})$`);\n}\n// the unbounded form of `string()` as a literal, so every plain string shares one instance instead of building its own\nexport const anyString = /^[\\s\\S]{0,}$/;\nexport const string = (params) => {\n const regex = params ? `[\\\\s\\\\S]{${params?.minimum ?? 0},${params?.maximum ?? \"\"}}` : `[\\\\s\\\\S]*`;\n return new RegExp(`^${regex}$`);\n};\nexport const bigint = /^-?\\d+n?$/;\nexport const integer = /^-?\\d+$/;\nexport const number = /^-?\\d+(?:\\.\\d+)?$/;\nexport const boolean = /^(?:true|false)$/i;\nconst _null = /^null$/i;\nexport { _null as null };\nconst _undefined = /^undefined$/i;\nexport { _undefined as undefined };\n// regex for string with no uppercase letters\nexport const lowercase = /^[^A-Z]*$/;\n// regex for string with no lowercase letters\nexport const uppercase = /^[^a-z]*$/;\n// regex for hexadecimal strings (any length)\nexport const hex = /^[0-9a-fA-F]*$/;\n// Hash regexes for different algorithms and encodings\n// Helper function to create base64 regex with exact length and padding\nfunction fixedBase64(bodyLength, padding) {\n return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`);\n}\n// Helper function to create base64url regex with exact length (no padding)\nfunction fixedBase64url(length) {\n return new RegExp(`^[A-Za-z0-9_-]{${length}}$`);\n}\n// MD5 (16 bytes): base64 = 24 chars total (22 + \"==\")\nexport const md5_hex = /^[0-9a-fA-F]{32}$/;\nexport const md5_base64 = /*@__PURE__*/ fixedBase64(22, \"==\");\nexport const md5_base64url = /*@__PURE__*/ fixedBase64url(22);\n// SHA1 (20 bytes): base64 = 28 chars total (27 + \"=\")\nexport const sha1_hex = /^[0-9a-fA-F]{40}$/;\nexport const sha1_base64 = /*@__PURE__*/ fixedBase64(27, \"=\");\nexport const sha1_base64url = /*@__PURE__*/ fixedBase64url(27);\n// SHA256 (32 bytes): base64 = 44 chars total (43 + \"=\")\nexport const sha256_hex = /^[0-9a-fA-F]{64}$/;\nexport const sha256_base64 = /*@__PURE__*/ fixedBase64(43, \"=\");\nexport const sha256_base64url = /*@__PURE__*/ fixedBase64url(43);\n// SHA384 (48 bytes): base64 = 64 chars total (no padding)\nexport const sha384_hex = /^[0-9a-fA-F]{96}$/;\nexport const sha384_base64 = /*@__PURE__*/ fixedBase64(64, \"\");\nexport const sha384_base64url = /*@__PURE__*/ fixedBase64url(64);\n// SHA512 (64 bytes): base64 = 88 chars total (86 + \"==\")\nexport const sha512_hex = /^[0-9a-fA-F]{128}$/;\nexport const sha512_base64 = /*@__PURE__*/ fixedBase64(86, \"==\");\nexport const sha512_base64url = /*@__PURE__*/ fixedBase64url(86);\n","// import { $ZodType } from \"./schemas.js\";\nimport * as core from \"./core.js\";\nimport * as regexes from \"./regexes.js\";\nimport * as util from \"./util.js\";\nexport const $ZodCheck = /*@__PURE__*/ core.$constructor(\"$ZodCheck\", (inst, def) => {\n var _a;\n inst._zod ?? (inst._zod = {});\n inst._zod.def = def;\n (_a = inst._zod).onattach ?? (_a.onattach = []);\n});\n/** Default `when` for size-based checks: run only on non-nullish values with a `size`. */\nconst _whenHasSize = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.size !== undefined;\n};\n/** Default `when` for length-based checks: run only on non-nullish values with a `length`. */\nconst _whenHasLength = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.length !== undefined;\n};\nconst numericOriginMap = {\n number: \"number\",\n bigint: \"bigint\",\n object: \"date\",\n};\nexport const $ZodCheckLessThan = /*@__PURE__*/ core.$constructor(\"$ZodCheckLessThan\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const origin = numericOriginMap[typeof def.value];\n inst._zod.check = (payload) => {\n if (def.inclusive ? payload.value <= def.value : payload.value < def.value) {\n return;\n }\n payload.issues.push({\n origin: numericOriginMap[typeof payload.value] ?? origin,\n code: \"too_big\",\n maximum: typeof def.value === \"object\" ? def.value.getTime() : def.value,\n input: payload.value,\n inclusive: def.inclusive,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckGreaterThan = /*@__PURE__*/ core.$constructor(\"$ZodCheckGreaterThan\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const origin = numericOriginMap[typeof def.value];\n inst._zod.check = (payload) => {\n if (def.inclusive ? payload.value >= def.value : payload.value > def.value) {\n return;\n }\n payload.issues.push({\n origin: numericOriginMap[typeof payload.value] ?? origin,\n code: \"too_small\",\n minimum: typeof def.value === \"object\" ? def.value.getTime() : def.value,\n input: payload.value,\n inclusive: def.inclusive,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMultipleOf = \n/*@__PURE__*/ core.$constructor(\"$ZodCheckMultipleOf\", (inst, def) => {\n $ZodCheck.init(inst, def);\n inst._zod.check = (payload) => {\n if (typeof payload.value !== typeof def.value)\n throw new Error(\"Cannot mix number and bigint in multiple_of check.\");\n const isMultiple = typeof payload.value === \"bigint\"\n ? // `value % 0n` throws, and nothing is a multiple of zero — the number branch already fails this way via NaN\n def.value !== BigInt(0) && payload.value % def.value === BigInt(0)\n : util.floatSafeRemainder(payload.value, def.value) === 0;\n if (isMultiple)\n return;\n payload.issues.push({\n origin: typeof payload.value,\n code: \"not_multiple_of\",\n divisor: def.value,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckNumberFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckNumberFormat\", (inst, def) => {\n $ZodCheck.init(inst, def); // no format checks\n def.format = def.format || \"float64\";\n const isInt = def.format?.includes(\"int\");\n const origin = isInt ? \"int\" : \"number\";\n const [minimum, maximum] = util.NUMBER_FORMAT_RANGES[def.format];\n inst._zod.check = (payload) => {\n const input = payload.value;\n if (isInt) {\n if (!Number.isInteger(input)) {\n // invalid_format issue\n // payload.issues.push({\n // expected: def.format,\n // format: def.format,\n // code: \"invalid_format\",\n // input,\n // inst,\n // });\n // invalid_type issue\n payload.issues.push({\n expected: origin,\n format: def.format,\n code: \"invalid_type\",\n continue: false,\n input,\n inst,\n });\n return;\n // not_multiple_of issue\n // payload.issues.push({\n // code: \"not_multiple_of\",\n // origin: \"number\",\n // input,\n // inst,\n // divisor: 1,\n // });\n }\n if (!Number.isSafeInteger(input)) {\n if (input > 0) {\n // too_big\n payload.issues.push({\n input,\n code: \"too_big\",\n maximum: Number.MAX_SAFE_INTEGER,\n note: \"Integers must be within the safe integer range.\",\n inst,\n origin,\n inclusive: true,\n continue: !def.abort,\n });\n }\n else {\n // too_small\n payload.issues.push({\n input,\n code: \"too_small\",\n minimum: Number.MIN_SAFE_INTEGER,\n note: \"Integers must be within the safe integer range.\",\n inst,\n origin,\n inclusive: true,\n continue: !def.abort,\n });\n }\n return;\n }\n }\n if (input < minimum) {\n payload.issues.push({\n origin: \"number\",\n input,\n code: \"too_small\",\n minimum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n if (input > maximum) {\n payload.issues.push({\n origin: \"number\",\n input,\n code: \"too_big\",\n maximum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodCheckBigIntFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckBigIntFormat\", (inst, def) => {\n $ZodCheck.init(inst, def); // no format checks\n const [minimum, maximum] = util.BIGINT_FORMAT_RANGES[def.format];\n inst._zod.check = (payload) => {\n const input = payload.value;\n if (input < minimum) {\n payload.issues.push({\n origin: \"bigint\",\n input,\n code: \"too_small\",\n minimum: minimum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n if (input > maximum) {\n payload.issues.push({\n origin: \"bigint\",\n input,\n code: \"too_big\",\n maximum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodCheckMaxSize = /*@__PURE__*/ core.$constructor(\"$ZodCheckMaxSize\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = _whenHasSize);\n inst._zod.check = (payload) => {\n const input = payload.value;\n const size = input.size;\n if (size <= def.maximum)\n return;\n payload.issues.push({\n origin: util.getSizableOrigin(input),\n code: \"too_big\",\n maximum: def.maximum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMinSize = /*@__PURE__*/ core.$constructor(\"$ZodCheckMinSize\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = _whenHasSize);\n inst._zod.check = (payload) => {\n const input = payload.value;\n const size = input.size;\n if (size >= def.minimum)\n return;\n payload.issues.push({\n origin: util.getSizableOrigin(input),\n code: \"too_small\",\n minimum: def.minimum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckSizeEquals = /*@__PURE__*/ core.$constructor(\"$ZodCheckSizeEquals\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = _whenHasSize);\n inst._zod.check = (payload) => {\n const input = payload.value;\n const size = input.size;\n if (size === def.size)\n return;\n const tooBig = size > def.size;\n payload.issues.push({\n origin: util.getSizableOrigin(input),\n ...(tooBig ? { code: \"too_big\", maximum: def.size } : { code: \"too_small\", minimum: def.size }),\n inclusive: true,\n exact: true,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMaxLength = /*@__PURE__*/ core.$constructor(\"$ZodCheckMaxLength\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = _whenHasLength);\n inst._zod.check = (payload) => {\n const input = payload.value;\n const units = input.length;\n // Strings are measured in Unicode code points, not UTF-16 units. A code point is at most two units, so a string that already fits in units fits in code points; only an overflow has to be counted.\n const length = typeof input === \"string\" && units > def.maximum ? util.codePointLength(input) : units;\n if (length <= def.maximum)\n return;\n const origin = util.getLengthableOrigin(input);\n payload.issues.push({\n origin,\n code: \"too_big\",\n maximum: def.maximum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMinLength = /*@__PURE__*/ core.$constructor(\"$ZodCheckMinLength\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = _whenHasLength);\n inst._zod.check = (payload) => {\n const input = payload.value;\n const units = input.length;\n // A code point is one or two UTF-16 units, so fewer units than the floor can never reach it and twice the floor always clears it. Only in between is the exact count in doubt.\n const length = typeof input === \"string\" && units >= def.minimum && units < def.minimum * 2\n ? util.codePointLength(input)\n : units;\n if (length >= def.minimum)\n return;\n const origin = util.getLengthableOrigin(input);\n payload.issues.push({\n origin,\n code: \"too_small\",\n minimum: def.minimum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckLengthEquals = /*@__PURE__*/ core.$constructor(\"$ZodCheckLengthEquals\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = _whenHasLength);\n inst._zod.check = (payload) => {\n const input = payload.value;\n const units = input.length;\n // A code point is one or two UTF-16 units, so outside `[length, length * 2]` units the target is missed either way — and missed in the same direction in both measures.\n const length = typeof input === \"string\" && units >= def.length && units <= def.length * 2\n ? util.codePointLength(input)\n : units;\n if (length === def.length)\n return;\n const origin = util.getLengthableOrigin(input);\n const tooBig = length > def.length;\n payload.issues.push({\n origin,\n ...(tooBig ? { code: \"too_big\", maximum: def.length } : { code: \"too_small\", minimum: def.length }),\n inclusive: true,\n exact: true,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckStringFormat\", (inst, def) => {\n var _a, _b;\n $ZodCheck.init(inst, def);\n if (def.pattern)\n (_a = inst._zod).check ?? (_a.check = (payload) => {\n def.pattern.lastIndex = 0;\n if (def.pattern.test(payload.value))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: def.format,\n input: payload.value,\n ...(def.pattern ? { pattern: def.pattern.toString() } : {}),\n inst,\n continue: !def.abort,\n });\n });\n else\n (_b = inst._zod).check ?? (_b.check = () => { });\n});\nexport const $ZodCheckRegex = /*@__PURE__*/ core.$constructor(\"$ZodCheckRegex\", (inst, def) => {\n $ZodCheckStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n def.pattern.lastIndex = 0;\n if (def.pattern.test(payload.value))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"regex\",\n input: payload.value,\n pattern: def.pattern.toString(),\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckLowerCase = /*@__PURE__*/ core.$constructor(\"$ZodCheckLowerCase\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.lowercase);\n $ZodCheckStringFormat.init(inst, def);\n});\nexport const $ZodCheckUpperCase = /*@__PURE__*/ core.$constructor(\"$ZodCheckUpperCase\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.uppercase);\n $ZodCheckStringFormat.init(inst, def);\n});\nexport const $ZodCheckIncludes = /*@__PURE__*/ core.$constructor(\"$ZodCheckIncludes\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const escapedRegex = util.escapeRegex(def.includes);\n // `String.prototype.includes(sub, position)` matches `sub` at `position`\n // OR LATER, so the pattern must allow at least `position` leading chars\n // (`{N,}`), not exactly `position` chars (`{N}`).\n const pattern = new RegExp(typeof def.position === \"number\" ? `^.{${def.position},}${escapedRegex}` : escapedRegex);\n def.pattern = pattern;\n inst._zod.check = (payload) => {\n if (payload.value.includes(def.includes, def.position))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"includes\",\n includes: def.includes,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckStartsWith = /*@__PURE__*/ core.$constructor(\"$ZodCheckStartsWith\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const pattern = new RegExp(`^${util.escapeRegex(def.prefix)}.*`);\n def.pattern ?? (def.pattern = pattern);\n inst._zod.check = (payload) => {\n if (payload.value.startsWith(def.prefix))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"starts_with\",\n prefix: def.prefix,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckEndsWith = /*@__PURE__*/ core.$constructor(\"$ZodCheckEndsWith\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const pattern = new RegExp(`.*${util.escapeRegex(def.suffix)}$`);\n def.pattern ?? (def.pattern = pattern);\n inst._zod.check = (payload) => {\n if (payload.value.endsWith(def.suffix))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"ends_with\",\n suffix: def.suffix,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\n///////////////////////////////////\n///// $ZodCheckProperty /////\n///////////////////////////////////\nfunction handleCheckPropertyResult(result, payload, property) {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(property, result.issues));\n }\n}\nexport const $ZodCheckProperty = /*@__PURE__*/ core.$constructor(\"$ZodCheckProperty\", (inst, def) => {\n $ZodCheck.init(inst, def);\n inst._zod.check = (payload) => {\n const result = def.schema._zod.run({\n value: payload.value[def.property],\n issues: [],\n }, {});\n if (result instanceof Promise) {\n return result.then((result) => handleCheckPropertyResult(result, payload, def.property));\n }\n handleCheckPropertyResult(result, payload, def.property);\n return;\n };\n});\nexport const $ZodCheckProperties = /*@__PURE__*/ core.$constructor(\"$ZodCheckProperties\", (inst, def) => {\n $ZodCheck.init(inst, def);\n util.hide(inst, Symbol.iterator, function* () {\n yield inst;\n });\n // key and schema snapshotted together: reading one live and the other cached lets a later mutation of the caller's shape object pair a stale key with a missing schema\n let entries;\n inst._zod.check = (payload) => {\n // the base schema already typed the value, so only a nullish one is rejected here: the properties read on a primitive too, matching z.property() on a string's length\n if (payload.value == null) {\n payload.issues.push({ expected: \"object\", code: \"invalid_type\", input: payload.value, inst });\n return undefined;\n }\n entries ?? (entries = Reflect.ownKeys(def.shape).map((key) => [key, def.shape[key]]));\n const input = payload.value;\n let proms;\n for (const [key, schema] of entries) {\n const result = schema._zod.run({ value: input[key], issues: [] }, {});\n if (result instanceof Promise) {\n proms ?? (proms = []);\n proms.push(result.then((result) => handleCheckPropertyResult(result, payload, key)));\n }\n else {\n handleCheckPropertyResult(result, payload, key);\n }\n }\n if (proms)\n return Promise.all(proms).then(() => undefined);\n return undefined;\n };\n});\nexport const $ZodCheckMimeType = /*@__PURE__*/ core.$constructor(\"$ZodCheckMimeType\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const mimeSet = new Set(def.mime);\n inst._zod.check = (payload) => {\n if (mimeSet.has(payload.value.type))\n return;\n payload.issues.push({\n code: \"invalid_value\",\n values: def.mime,\n input: payload.value.type,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckOverwrite = /*@__PURE__*/ core.$constructor(\"$ZodCheckOverwrite\", (inst, def) => {\n $ZodCheck.init(inst, def);\n inst._zod.check = (payload) => {\n payload.value = def.tx(payload.value);\n };\n});\n","export class Doc {\n constructor(args = [], closed = {}) {\n this.content = [];\n this.indent = 0;\n this.args = args;\n this.closed = closed;\n }\n // the compiler catches a child's throw and keeps writing into this doc, so the indent has to unwind with it\n indented(fn) {\n this.indent += 1;\n try {\n fn(this);\n }\n finally {\n this.indent -= 1;\n }\n }\n write(arg) {\n if (typeof arg === \"function\") {\n arg(this, { execution: \"sync\" });\n arg(this, { execution: \"async\" });\n return;\n }\n const content = arg;\n const lines = content.split(\"\\n\").filter((x) => x);\n const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length));\n const dedented = lines.map((x) => x.slice(minIndent)).map((x) => \" \".repeat(this.indent * 2) + x);\n for (const line of dedented) {\n this.content.push(line);\n }\n }\n compile() {\n const F = Function;\n const content = this?.content ?? [``];\n const factory = new F(...Object.keys(this.closed), `return function (${this.args.join(\", \")}) {\\n${content.join(\"\\n\")}\\n};`);\n return factory(...Object.values(this.closed));\n }\n}\n","export const version = {\n major: 4,\n minor: 6,\n patch: 6,\n};\n","import * as checks from \"./checks.js\";\nimport * as core from \"./core.js\";\nimport { Doc } from \"./doc.js\";\nimport { parse, parseAsync } from \"./parse.js\";\nimport * as regexes from \"./regexes.js\";\nimport * as util from \"./util.js\";\nimport { version } from \"./versions.js\";\nexport const $ZodType = /*@__PURE__*/ core.$constructor(\"$ZodType\", (inst, def) => {\n var _a;\n inst ?? (inst = {});\n inst._zod.def = def; // set _def property\n inst._zod.bag = inst._zod.bag || {}; // initialize _bag object\n inst._zod.version = version;\n const defChecks = inst._zod.def.checks;\n // if inst is itself a checks.$ZodCheck, run it as a check\n const checks = inst._zod.traits.has(\"$ZodCheck\")\n ? [inst, ...(defChecks ?? [])]\n : defChecks?.length\n ? [...defChecks]\n : [];\n for (const ch of checks) {\n for (const fn of ch._zod.onattach) {\n fn(inst);\n }\n }\n if (checks.length === 0) {\n // deferred initializer inst._zod.parse is not yet defined\n (_a = inst._zod).deferred ?? (_a.deferred = []);\n inst._zod.deferred?.push(() => {\n inst._zod.run = inst._zod.parse;\n });\n }\n else {\n const runChecks = (payload, checks, ctx) => {\n if (payload.memo)\n return payload;\n let isAborted = util.aborted(payload);\n let asyncResult;\n for (const ch of checks) {\n if (ch._zod.def.when) {\n if (util.explicitlyAborted(payload))\n continue;\n const shouldRun = ch._zod.def.when(payload);\n if (!shouldRun)\n continue;\n }\n else if (isAborted) {\n continue;\n }\n const currLen = payload.issues.length;\n const _ = ch._zod.check(payload);\n if (_ instanceof Promise && ctx?.async === false) {\n throw new core.$ZodAsyncError();\n }\n if (asyncResult || _ instanceof Promise) {\n asyncResult = (asyncResult ?? Promise.resolve()).then(async () => {\n await _;\n const nextLen = payload.issues.length;\n if (nextLen === currLen)\n return;\n util.attachSchema(payload.issues, currLen, inst);\n if (!isAborted)\n isAborted = util.aborted(payload, currLen);\n });\n }\n else {\n const nextLen = payload.issues.length;\n if (nextLen === currLen)\n continue;\n util.attachSchema(payload.issues, currLen, inst);\n if (!isAborted)\n isAborted = util.aborted(payload, currLen);\n }\n }\n if (asyncResult) {\n return asyncResult.then(() => {\n return payload;\n });\n }\n return payload;\n };\n const handleCanaryResult = (canary, payload, ctx) => {\n // abort if the canary is aborted\n if (util.aborted(canary)) {\n canary.aborted = true;\n return canary;\n }\n // run checks first, then\n const checkResult = runChecks(payload, checks, ctx);\n if (checkResult instanceof Promise) {\n if (ctx.async === false)\n throw new core.$ZodAsyncError();\n return checkResult.then((checkResult) => inst._zod.parse(checkResult, ctx));\n }\n return inst._zod.parse(checkResult, ctx);\n };\n inst._zod.run = (payload, ctx) => {\n if (ctx.skipChecks) {\n return inst._zod.parse(payload, ctx);\n }\n if (ctx.direction === \"backward\") {\n // run canary initial pass (no checks)\n const canary = inst._zod.parse({ value: payload.value, issues: [] }, { ...ctx, skipChecks: true });\n if (canary instanceof Promise) {\n return canary.then((canary) => {\n return handleCanaryResult(canary, payload, ctx);\n });\n }\n return handleCanaryResult(canary, payload, ctx);\n }\n // forward\n const result = inst._zod.parse(payload, ctx);\n if (result instanceof Promise) {\n if (ctx.async === false)\n throw new core.$ZodAsyncError();\n return result.then((result) => runChecks(result, checks, ctx));\n }\n return runChecks(result, checks, ctx);\n };\n }\n}, {\n // Wrappers extend this by installing a richer factory over it; reading it eagerly would defeat the laziness.\n get \"~standard\"() {\n return util.hide(this, \"~standard\", standardProps(this));\n },\n set \"~standard\"(value) {\n util.own(this, \"~standard\", value);\n },\n});\n/** The Standard Schema surface for `inst`. Shared so wrappers can extend it without forcing it. */\n// a Standard Schema result only reports issues, so a failure finalizes them straight off the raw payload: no ZodError, and no lazy result to read through\nconst toStandardResult = (r, ctx) => r.issues.length ? { issues: r.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())) } : { value: r.value };\nasync function validateAsync(inst, value) {\n const ctx = { async: true };\n return toStandardResult((await inst._zod.run({ value, issues: [] }, ctx)), ctx);\n}\nexport function standardProps(inst) {\n return {\n validate: (value) => {\n const ctx = { async: false };\n try {\n const r = inst._zod.run({ value, issues: [] }, ctx);\n if (!(r instanceof Promise))\n return toStandardResult(r, ctx);\n }\n catch (_) { }\n // async function so a synchronously throwing check rejects instead of escaping validate\n return validateAsync(inst, value);\n },\n vendor: \"zod\",\n version: 1,\n };\n}\nexport { clone } from \"./util.js\";\nexport const $ZodString = /*@__PURE__*/ core.$constructor(\"$ZodString\", (inst, def) => {\n $ZodType.init(inst, def);\n // a format's own pattern, else unbounded; a template literal derives the check-aware form itself\n inst._zod.pattern = def.pattern ?? regexes.anyString;\n inst._zod.parse = (payload, _) => {\n if (def.coerce)\n try {\n payload.value = String(payload.value);\n }\n catch (_) { }\n if (typeof payload.value === \"string\")\n return payload;\n payload.issues.push({\n expected: \"string\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodStringFormat\", (inst, def) => {\n // check initialization must come first\n checks.$ZodCheckStringFormat.init(inst, def);\n $ZodString.init(inst, def);\n});\nexport const $ZodGUID = /*@__PURE__*/ core.$constructor(\"$ZodGUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.guid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodUUID = /*@__PURE__*/ core.$constructor(\"$ZodUUID\", (inst, def) => {\n if (def.version) {\n const versionMap = {\n v1: 1,\n v2: 2,\n v3: 3,\n v4: 4,\n v5: 5,\n v6: 6,\n v7: 7,\n v8: 8,\n };\n const v = versionMap[def.version];\n if (v === undefined)\n throw new Error(`Invalid UUID version: \"${def.version}\"`);\n def.pattern ?? (def.pattern = regexes.uuid(v));\n }\n else\n def.pattern ?? (def.pattern = regexes.uuid());\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodEmail = /*@__PURE__*/ core.$constructor(\"$ZodEmail\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.email);\n $ZodStringFormat.init(inst, def);\n});\n/** The `://` guard rejected the input before the URL constructor saw it. */\nexport const URL_BAD_FORMAT = 1;\n/** The URL parser rejected the input. */\nexport const URL_UNPARSEABLE = 2;\nexport function canParseURL(input) {\n try {\n if (typeof URL !== \"undefined\" && typeof URL.canParse === \"function\")\n return URL.canParse(input);\n new URL(input);\n return true;\n }\n catch {\n return false;\n }\n}\nexport function validateURL(trimmed, def) {\n if (!(\"normalize\" in def) && !(\"hostname\" in def) && !(\"protocol\" in def)) {\n return canParseURL(trimmed) || URL_UNPARSEABLE;\n }\n return parseURLObject(trimmed, def);\n}\n/** Parses a URL while preserving the non-normalizing HTTP guard. */\nexport function parseURLObject(trimmed, def) {\n // When normalize is off, require :// for http/https URLs. This prevents strings like \"http:example.com\" or \"https:/path\" from being silently accepted\n if (!def.normalize && def.protocol?.source === regexes.httpProtocol.source && !/^https?:\\/\\//i.test(trimmed)) {\n return URL_BAD_FORMAT;\n }\n try {\n if (typeof URL !== \"undefined\") {\n const URLStatic = URL;\n if (typeof URLStatic.parse === \"function\")\n return URLStatic.parse(trimmed) ?? URL_UNPARSEABLE;\n }\n // @ts-ignore\n return new URL(trimmed);\n }\n catch {\n return URL_UNPARSEABLE;\n }\n}\nconst asciiTabOrNewline = /[\\t\\n\\r]/g;\n/** The URL parser deletes every ASCII tab, LF and CR from its input before it parses, so `new URL(\"https://exa\\nmple.com\")` reports on `example.com`. Applying the same deletion to the returned value closes the half of that divergence which can move the host; the parser's other rewrite, stripping C0 controls at the edges, cannot. */\nexport function stripTabAndNewline(value) {\n return value.replace(asciiTabOrNewline, \"\");\n}\nexport function urlHostnameOk(url, hostname) {\n hostname.lastIndex = 0;\n return hostname.test(url.hostname);\n}\nexport function urlProtocolOk(url, protocol) {\n protocol.lastIndex = 0;\n return protocol.test(url.protocol.endsWith(\":\") ? url.protocol.slice(0, -1) : url.protocol);\n}\nexport const $ZodURL = /*@__PURE__*/ core.$constructor(\"$ZodURL\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n try {\n // Trim whitespace from input\n const trimmed = payload.value.trim();\n const url = validateURL(trimmed, def);\n if (url === URL_BAD_FORMAT) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n note: \"Invalid URL format\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n return;\n }\n if (url === URL_UNPARSEABLE) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n return;\n }\n if (url === true) {\n payload.value = stripTabAndNewline(trimmed);\n return;\n }\n if (def.hostname && !urlHostnameOk(url, def.hostname)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n note: \"Invalid hostname\",\n pattern: def.hostname.source,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n if (def.protocol && !urlProtocolOk(url, def.protocol)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n note: \"Invalid protocol\",\n pattern: def.protocol.source,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n // Set the output value based on normalize flag\n payload.value = def.normalize ? url.href : stripTabAndNewline(trimmed);\n return;\n }\n catch (_) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodEmoji = /*@__PURE__*/ core.$constructor(\"$ZodEmoji\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.emoji());\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodNanoID = /*@__PURE__*/ core.$constructor(\"$ZodNanoID\", (inst, def) => {\n if (def.length !== undefined && (!Number.isInteger(def.length) || def.length < 1))\n throw new Error(`Invalid nanoid length: ${def.length}`);\n def.pattern ?? (def.pattern = def.length === undefined ? regexes.nanoid : regexes.nanoidOfLength(def.length));\n $ZodStringFormat.init(inst, def);\n});\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link $ZodCUID2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport const $ZodCUID = /*@__PURE__*/ core.$constructor(\"$ZodCUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cuid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodCUID2 = /*@__PURE__*/ core.$constructor(\"$ZodCUID2\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cuid2);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodULID = /*@__PURE__*/ core.$constructor(\"$ZodULID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ulid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodXID = /*@__PURE__*/ core.$constructor(\"$ZodXID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.xid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodKSUID = /*@__PURE__*/ core.$constructor(\"$ZodKSUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ksuid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODateTime = /*@__PURE__*/ core.$constructor(\"$ZodISODateTime\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.datetime(def));\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODate = /*@__PURE__*/ core.$constructor(\"$ZodISODate\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.date);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISOTime = /*@__PURE__*/ core.$constructor(\"$ZodISOTime\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.time(def));\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODuration = /*@__PURE__*/ core.$constructor(\"$ZodISODuration\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.duration);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodIPv4 = /*@__PURE__*/ core.$constructor(\"$ZodIPv4\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ipv4);\n $ZodStringFormat.init(inst, def);\n});\n/** An IPv6 address is written with hex digits, colons and dots, and nothing else. The guard is what makes the check below an IPv6 check: `new URL(\"http://[...]\")` parses an authority, not an address, so `@` and `\\` re-delimit it and `\"::@1\\\\\"` validates against the host `0.0.0.1`. The URL parser also deletes ASCII tab, LF and CR rather than failing, which is how `\"::1\\n\"` validated as `::1`. */\nconst ipv6Alphabet = /^[0-9a-fA-F:.]+$/;\nexport function isValidIPv6(value) {\n if (!ipv6Alphabet.test(value))\n return false;\n return canParseURL(`http://[${value}]`);\n}\nexport const $ZodIPv6 = /*@__PURE__*/ core.$constructor(\"$ZodIPv6\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ipv6);\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (!isValidIPv6(payload.value)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"ipv6\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodMAC = /*@__PURE__*/ core.$constructor(\"$ZodMAC\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.mac(def.delimiter));\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodCIDRv4 = /*@__PURE__*/ core.$constructor(\"$ZodCIDRv4\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cidrv4);\n $ZodStringFormat.init(inst, def);\n});\nexport function isValidCIDRv6(value) {\n const parts = value.split(\"/\");\n if (parts.length !== 2)\n return false;\n const [address, prefix] = parts;\n if (!prefix)\n return false;\n const prefixNum = Number(prefix);\n if (`${prefixNum}` !== prefix)\n return false;\n if (prefixNum < 0 || prefixNum > 128)\n return false;\n return isValidIPv6(address);\n}\nexport const $ZodCIDRv6 = /*@__PURE__*/ core.$constructor(\"$ZodCIDRv6\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cidrv6); // not used for validation\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (!isValidCIDRv6(payload.value)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"cidrv6\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\n////////////////////////////// ZodBase64 //////////////////////////////\nexport function isValidBase64(data) {\n if (data === \"\")\n return true;\n // atob ignores whitespace, so reject it up front.\n if (/\\s/.test(data))\n return false;\n if (data.length % 4 !== 0)\n return false;\n try {\n // @ts-ignore\n atob(data);\n return true;\n }\n catch {\n return false;\n }\n}\n// lax on purpose: the quantified regexes.base64 overflows the regex stack on multi-MB input and its leading ^$| alternation leaks through template-literal composition; isValidBase64 enforces length and padding\nexport const base64Charset = /^[0-9a-zA-Z+/]*={0,2}$/;\nexport const $ZodBase64 = /*@__PURE__*/ core.$constructor(\"$ZodBase64\", (inst, def) => {\n def.pattern ?? (def.pattern = base64Charset);\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (isValidBase64(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"base64\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\n////////////////////////////// ZodBase64URL //////////////////////////////\n// lax on purpose: the quantified regexes.base64url overflows the regex stack on multi-MB input; isValidBase64 enforces length on the padded string\nexport const base64urlCharset = /^[A-Za-z0-9_-]*$/;\nexport function isValidBase64URL(data) {\n if (!base64urlCharset.test(data))\n return false;\n const base64 = data.replace(/[-_]/g, (c) => (c === \"-\" ? \"+\" : \"/\"));\n const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, \"=\");\n return isValidBase64(padded);\n}\nexport const $ZodBase64URL = /*@__PURE__*/ core.$constructor(\"$ZodBase64URL\", (inst, def) => {\n def.pattern ?? (def.pattern = base64urlCharset);\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (isValidBase64URL(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"base64url\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodE164 = /*@__PURE__*/ core.$constructor(\"$ZodE164\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.e164);\n $ZodStringFormat.init(inst, def);\n});\n////////////////////////////// ZodCreditCard //////////////////////////////\nconst CC_SANITIZE = /[- ]/g;\n/** Luhn checksum on a digit-only string. Adapted from valibot (MIT). */\nfunction isLuhnAlgo(digits) {\n let length = digits.length;\n let bit = 1;\n let sum = 0;\n while (length) {\n const value = digits.charCodeAt(--length) - 48;\n bit ^= 1;\n sum += bit ? [0, 2, 4, 6, 8, 1, 3, 5, 7, 9][value] : value;\n }\n return sum % 10 === 0;\n}\nexport function isValidCreditCard(input) {\n if (!regexes.creditCard.test(input))\n return false;\n return isLuhnAlgo(input.replace(CC_SANITIZE, \"\"));\n}\nexport const $ZodCreditCard = /*@__PURE__*/ core.$constructor(\"$ZodCreditCard\", (inst, def) => {\n // Shape only — the Luhn check below is not expressible as a pattern, so consumers of `pattern` (JSON Schema, template literals) get the length and separator rules alone.\n def.pattern ?? (def.pattern = regexes.creditCard);\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (isValidCreditCard(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"credit_card\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\n////////////////////////////// ZodIBAN //////////////////////////////\n// iso 7064 mod 97-10 checksum without BigInt\nfunction isIso7064Mod97(iban) {\n let remainder = 0;\n const len = iban.length;\n for (let i = 4; i < len; i++) {\n const code = iban.charCodeAt(i);\n remainder = (code >= 65 ? remainder * 100 + (code - 55) : remainder * 10 + (code - 48)) % 97;\n }\n for (let i = 0; i < 4; i++) {\n const code = iban.charCodeAt(i);\n remainder = (code >= 65 ? remainder * 100 + (code - 55) : remainder * 10 + (code - 48)) % 97;\n }\n return remainder === 1;\n}\nexport function isValidIBAN(input) {\n if (!regexes.iban.test(input))\n return false;\n return isIso7064Mod97(input);\n}\nexport const $ZodIBAN = /*@__PURE__*/ core.$constructor(\"$ZodIBAN\", (inst, def) => {\n // shape only — checksum is not expressible as a pattern\n def.pattern ?? (def.pattern = regexes.iban);\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (isValidIBAN(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"iban\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\n////////////////////////////// ZodJWT //////////////////////////////\nexport function isValidJWT(token, algorithm = null) {\n try {\n const tokensParts = token.split(\".\");\n if (tokensParts.length !== 3)\n return false;\n const [header] = tokensParts;\n if (!header)\n return false;\n // @ts-ignore\n const parsedHeader = JSON.parse(atob(header));\n if (\"typ\" in parsedHeader && parsedHeader?.typ !== \"JWT\")\n return false;\n if (!parsedHeader.alg)\n return false;\n if (algorithm && (!(\"alg\" in parsedHeader) || parsedHeader.alg !== algorithm))\n return false;\n return true;\n }\n catch {\n return false;\n }\n}\nexport const $ZodJWT = /*@__PURE__*/ core.$constructor(\"$ZodJWT\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (isValidJWT(payload.value, def.alg))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"jwt\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCustomStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodCustomStringFormat\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (def.fn(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: def.format,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodNumber = /*@__PURE__*/ core.$constructor(\"$ZodNumber\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.number;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = Number(payload.value);\n }\n catch (_) { }\n const input = payload.value;\n if (typeof input === \"number\" && !Number.isNaN(input) && Number.isFinite(input)) {\n return payload;\n }\n const received = typeof input === \"number\"\n ? Number.isNaN(input)\n ? \"NaN\"\n : !Number.isFinite(input)\n ? String(input)\n : undefined\n : undefined;\n payload.issues.push({\n expected: \"number\",\n code: \"invalid_type\",\n input,\n inst,\n ...(received ? { received } : {}),\n });\n return payload;\n };\n});\nexport const $ZodNumberFormat = /*@__PURE__*/ core.$constructor(\"$ZodNumberFormat\", (inst, def) => {\n checks.$ZodCheckNumberFormat.init(inst, def);\n $ZodNumber.init(inst, def); // no format checks\n});\nexport const $ZodBoolean = /*@__PURE__*/ core.$constructor(\"$ZodBoolean\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.boolean;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = Boolean(payload.value);\n }\n catch (_) { }\n const input = payload.value;\n if (typeof input === \"boolean\")\n return payload;\n payload.issues.push({\n expected: \"boolean\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodBigInt = /*@__PURE__*/ core.$constructor(\"$ZodBigInt\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.bigint;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = BigInt(payload.value);\n }\n catch (_) { }\n if (typeof payload.value === \"bigint\")\n return payload;\n payload.issues.push({\n expected: \"bigint\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodBigIntFormat = /*@__PURE__*/ core.$constructor(\"$ZodBigIntFormat\", (inst, def) => {\n checks.$ZodCheckBigIntFormat.init(inst, def);\n $ZodBigInt.init(inst, def); // no format checks\n});\nexport const $ZodSymbol = /*@__PURE__*/ core.$constructor(\"$ZodSymbol\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"symbol\")\n return payload;\n payload.issues.push({\n expected: \"symbol\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodUndefined = /*@__PURE__*/ core.$constructor(\"$ZodUndefined\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.undefined;\n inst._zod.values = new Set([undefined]);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"undefined\")\n return payload;\n payload.issues.push({\n expected: \"undefined\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodNull = /*@__PURE__*/ core.$constructor(\"$ZodNull\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.null;\n inst._zod.values = new Set([null]);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (input === null)\n return payload;\n payload.issues.push({\n expected: \"null\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodAny = /*@__PURE__*/ core.$constructor(\"$ZodAny\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload) => payload;\n});\nexport const $ZodUnknown = /*@__PURE__*/ core.$constructor(\"$ZodUnknown\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload) => payload;\n});\nexport const $ZodNever = /*@__PURE__*/ core.$constructor(\"$ZodNever\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n payload.issues.push({\n expected: \"never\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodVoid = /*@__PURE__*/ core.$constructor(\"$ZodVoid\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"undefined\")\n return payload;\n payload.issues.push({\n expected: \"void\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodDate = /*@__PURE__*/ core.$constructor(\"$ZodDate\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce) {\n try {\n payload.value = new Date(payload.value);\n }\n catch (_err) { }\n }\n const input = payload.value;\n const isDate = input instanceof Date;\n const isValidDate = isDate && !Number.isNaN(input.getTime());\n if (isValidDate)\n return payload;\n payload.issues.push({\n expected: \"date\",\n code: \"invalid_type\",\n input,\n ...(isDate ? { received: \"Invalid Date\" } : {}),\n inst,\n });\n return payload;\n };\n});\n// an oversized container fails its leading size checks before any element is parsed\nfunction capSize(inst, size) {\n const caps = util.sizeCaps(inst._zod.def.checks);\n if (!caps.length)\n return;\n const cap = Math.min(...caps.map((c) => c[0]));\n const parse = inst._zod.parse;\n inst._zod.parse = (payload, ctx) => {\n const n = size(payload.value);\n if (n > cap && !ctx?.skipChecks && ctx?.direction !== \"backward\") {\n for (const [max, ch] of util.sizeCaps(inst._zod.def.checks)) {\n if (n > max && ch._zod.def.when(payload)) {\n const start = payload.issues.length;\n ch._zod.check(payload);\n // the value is still the raw input, so no later check may read it\n payload.issues[start].continue = false;\n util.attachSchema(payload.issues, start, inst);\n return payload;\n }\n }\n }\n return parse(payload, ctx);\n };\n}\nconst arraySize = (input) => (Array.isArray(input) ? input.length : -1);\nconst mapSize = (input) => (input instanceof Map ? input.size : -1);\nconst setSize = (input) => (input instanceof Set ? input.size : -1);\nfunction handleArrayResult(result, final, index) {\n if (result.issues.length) {\n final.issues.push(...util.prefixIssues(index, result.issues));\n }\n final.value[index] = result.value;\n}\nexport const $ZodArray = /*@__PURE__*/ core.$constructor(\"$ZodArray\", (inst, def) => {\n $ZodType.init(inst, def);\n const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!Array.isArray(input)) {\n payload.issues.push({\n expected: \"array\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n payload.value = memo ? memo.alloc(inst, payload, Array(input.length), ctx) : Array(input.length);\n const proms = [];\n const abortEarly = ctx?.abortEarly;\n for (let i = 0; i < input.length; i++) {\n const item = input[i];\n const result = def.element._zod.run({\n value: item,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => handleArrayResult(result, payload, i)));\n }\n else {\n handleArrayResult(result, payload, i);\n // the element's payload is authoritative here, since handleArrayResult forwards every issue; an object's is not, because it drops a failed absent optional\n if (abortEarly && result.issues.length !== 0 && util.aborted(result))\n break;\n }\n }\n if (proms.length) {\n return Promise.all(proms).then(() => payload);\n }\n return payload; //handleArrayResultsAsync(parseResults, final);\n };\n capSize(inst, arraySize);\n});\nfunction handlePropertyResult(result, final, key, input, optin, optout) {\n const isPresent = key in input;\n const isOptionalOut = optout === \"optional\";\n // The middle rung means \"absence permitted, nothing supplied in its place\", so an absent key contributes nothing — whatever the schema made of `undefined` is invented, not substituted. Only `optional` reaches this with a value: `defaulted` substitutes, and a schema that isn't optional-out has to keep the key.\n if (!isPresent && isOptionalOut && optin === \"optional\") {\n return;\n }\n if (result.issues.length) {\n // For optional-in/out schemas, ignore errors on absent keys.\n if (optin !== undefined && isOptionalOut && !isPresent) {\n return;\n }\n final.issues.push(...util.prefixIssues(key, result.issues));\n }\n if (!isPresent && optin === undefined) {\n if (!result.issues.length) {\n final.issues.push({\n code: \"invalid_type\",\n expected: \"nonoptional\",\n input: undefined,\n path: [key],\n });\n }\n return;\n }\n if (result.value === undefined) {\n if (isPresent || (optin === \"defaulted\" && !isOptionalOut)) {\n final.value[key] = undefined;\n }\n }\n else {\n final.value[key] = result.value;\n }\n}\n// one shared instance; a fresh [] per schema cost 56 bytes retained\nconst NO_SYMBOL_KEYS = [];\nfunction normalizeDef(def) {\n const keys = Object.keys(def.shape);\n const ownSymbols = Object.getOwnPropertySymbols(def.shape);\n const symbolKeys = ownSymbols.length ? ownSymbols : NO_SYMBOL_KEYS;\n // aliases `keys` when there are no symbols, so a string-only shape keeps one array\n const allKeys = symbolKeys.length ? [...keys, ...symbolKeys] : keys;\n for (const k of allKeys) {\n if (!def.shape?.[k]?._zod?.traits?.has(\"$ZodType\")) {\n throw new Error(`Invalid element at key \"${String(k)}\": expected a Zod schema`);\n }\n }\n const okeys = util.optionalKeys(def.shape);\n return {\n ...def,\n allKeys,\n symbolKeys,\n // string-only: handleCatchall matches it against `for...in`, which never yields a symbol\n keySet: new Set(keys),\n numKeys: keys.length,\n optionalKeys: new Set(okeys),\n };\n}\nfunction handleCatchall(proms, input, payload, ctx, def, inst, abortEarly) {\n const unrecognized = [];\n const keySet = def.keySet;\n const _catchall = def.catchall._zod;\n const t = _catchall.def.type;\n const optin = _catchall.optin;\n const optout = _catchall.optout;\n // starts at 0, not the current length: the shape phase already ran and may have aborted\n let seen = 0;\n for (const key in input) {\n if (abortEarly && payload.issues.length !== seen) {\n if (util.aborted(payload, seen))\n break;\n seen = payload.issues.length;\n }\n // Must precede the __proto__ branch: a declared key is not unrecognized, even though the shape loop deliberately strips __proto__ from the parsed output.\n if (keySet.has(key))\n continue;\n // Don't copy an undeclared __proto__ into the result; assignment to a plain {} would replace the result prototype. But in strict mode it is still an unknown key, so report it before skipping.\n if (key === \"__proto__\") {\n if (t === \"never\")\n unrecognized.push(key);\n continue;\n }\n if (t === \"never\") {\n unrecognized.push(key);\n continue;\n }\n const r = _catchall.run({ value: input[key], issues: [] }, ctx);\n if (r instanceof Promise) {\n proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, optin, optout)));\n }\n else {\n handlePropertyResult(r, payload, key, input, optin, optout);\n }\n }\n if (unrecognized.length) {\n payload.issues.push({\n code: \"unrecognized_keys\",\n keys: unrecognized,\n input,\n inst,\n // Describes the shape of the input, not the validity of the parsed value, so it never aborts. The parse still fails; the schema's own checks just get to run first, and an enclosing intersection can reconcile the key against a sibling operand.\n continue: true,\n });\n }\n if (!proms.length)\n return payload;\n return Promise.all(proms).then(() => {\n return payload;\n });\n}\nexport const $ZodObject = /*@__PURE__*/ core.$constructor(\"$ZodObject\", (inst, def) => {\n // requires cast because technically $ZodObject doesn't extend\n $ZodType.init(inst, def);\n const desc = Object.getOwnPropertyDescriptor(def, \"shape\");\n // a cloned def carries its source's accessor, which knows the shape it answers from; adopting that keeps the clone's keys readable without running it\n const sh = desc?.get ? desc.get.raw : (def.shape ?? {});\n if (sh) {\n // Freezes the shape on first read, so its getters resolve once and every later read sees the same schemas.\n const get = () => {\n const newSh = { ...sh };\n Object.defineProperty(def, \"shape\", { value: newSh });\n get.raw = newSh;\n return newSh;\n };\n get.raw = sh;\n Object.defineProperty(def, \"shape\", { get });\n }\n const _normalized = util.cached(() => normalizeDef(def));\n util.defineLazyInternal(inst, \"propValues\", (zod) => {\n const shape = zod.def.shape;\n const propValues = {};\n for (const key in shape) {\n const field = shape[key]._zod;\n if (field.values) {\n if (!Object.prototype.hasOwnProperty.call(propValues, key)) {\n util.assignProp(propValues, key, new Set());\n }\n for (const v of field.values)\n propValues[key].add(v);\n // An omittable slot reads back as undefined at a discriminator lookup, so it has to claim undefined: two options that can both omit the key are not discriminable on it.\n if (field.optin !== undefined)\n propValues[key].add(undefined);\n }\n }\n return propValues;\n });\n const isObject = util.isObject;\n const catchall = def.catchall;\n let value;\n const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\n inst._zod.parse = (payload, ctx) => {\n value ?? (value = _normalized.value);\n const input = payload.value;\n if (!isObject(input)) {\n payload.issues.push({\n expected: \"object\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {};\n const proms = [];\n const shape = value.shape;\n const abortEarly = ctx?.abortEarly;\n let seen = payload.issues.length;\n for (const key of value.allKeys) {\n if (abortEarly && payload.issues.length !== seen) {\n if (util.aborted(payload, seen))\n break;\n seen = payload.issues.length;\n }\n if (key === \"__proto__\")\n continue;\n const el = shape[key];\n const optin = el._zod.optin;\n const optout = el._zod.optout;\n const r = el._zod.run({ value: input[key], issues: [] }, ctx);\n if (r instanceof Promise) {\n proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, optin, optout)));\n }\n else {\n handlePropertyResult(r, payload, key, input, optin, optout);\n }\n }\n if (!catchall) {\n return proms.length ? Promise.all(proms).then(() => payload) : payload;\n }\n return handleCatchall(proms, input, payload, ctx, _normalized.value, inst, abortEarly === true);\n };\n});\nexport const $ZodObjectJIT = /*@__PURE__*/ core.$constructor(\"$ZodObjectJIT\", (inst, def) => {\n // requires cast because technically $ZodObject doesn't extend\n $ZodObject.init(inst, def);\n const superParse = inst._zod.parse;\n const _normalized = util.cached(() => normalizeDef(def));\n const memo = core.globalConfig.memoizer;\n const generateFastpass = (shape) => {\n const normalized = _normalized.value;\n const syms = normalized.symbolKeys;\n // a symbol has no source literal, so it is read as `syms[i]` off the closed-over scope\n const doc = new Doc([\"payload\", \"ctx\"], { shape, inst, memo, syms });\n const parseStr = (k) => `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;\n // prefixes in place, like util.prefixIssues. newResult must land before the early return: a catchall runs after this and would otherwise write onto the caller's input\n const prefixStr = (id, k) => `\n let ${id}_ab = false;\n for (let i = 0; i < ${id}.issues.length; i++) {\n const iss = ${id}.issues[i];\n iss.path = iss.path ? [${k}, ...iss.path] : [${k}];\n payload.issues.push(iss);\n if (iss.continue !== true) ${id}_ab = true;\n }\n if (${id}_ab && ctx && ctx.abortEarly) {\n payload.value = newResult;\n return payload;\n }`;\n doc.write(`const input = payload.value;`);\n const ids = Object.create(null);\n let counter = 0;\n for (const key of normalized.allKeys) {\n ids[key] = `key_${counter++}`;\n }\n // A: preserve key order {\n doc.write(memo ? `const newResult = memo.alloc(inst, payload, {}, ctx);` : `const newResult = {};`);\n for (const key of normalized.allKeys) {\n if (key === \"__proto__\")\n continue;\n const id = ids[key];\n const k = typeof key === \"symbol\" ? `syms[${syms.indexOf(key)}]` : util.esc(key);\n const isPresent = `${k} in input`;\n const schema = shape[key];\n const optin = schema?._zod?.optin;\n const isOptionalIn = optin !== undefined;\n const isOptionalOut = schema?._zod?.optout === \"optional\";\n doc.write(`const ${id} = ${parseStr(k)};`);\n if (isOptionalIn && isOptionalOut) {\n // For optional-in/out schemas, ignore errors on absent keys — and, like the interpreted path, drop the value produced alongside them. The middle rung goes further: it permits absence without supplying anything in its place, so an absent key contributes nothing at all.\n const assign = optin === \"optional\" ? `${id}_present` : `${id}.value !== undefined || ${id}_present`;\n doc.write(`\n const ${id}_present = ${isPresent};\n if (!${id}.issues.length || ${id}_present) {\n if (${id}.issues.length) {${prefixStr(id, k)}\n }\n\n if (${assign}) {\n newResult[${k}] = ${id}.value;\n }\n }\n\n `);\n }\n else if (!isOptionalIn) {\n doc.write(`\n const ${id}_present = ${isPresent};\n if (${id}.issues.length) {${prefixStr(id, k)}\n }\n if (!${id}_present && !${id}.issues.length) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"nonoptional\",\n input: undefined,\n path: [${k}]\n });\n if (ctx && ctx.abortEarly) {\n payload.value = newResult;\n return payload;\n }\n }\n\n if (${id}_present) {\n newResult[${k}] = ${id}.value;\n }\n\n `);\n }\n else {\n doc.write(`\n if (${id}.issues.length) {${prefixStr(id, k)}\n }\n `);\n if (optin === \"defaulted\") {\n doc.write(`newResult[${k}] = ${id}.value;`);\n }\n else {\n doc.write(`\n if (${id}.value !== undefined || ${isPresent}) {\n newResult[${k}] = ${id}.value;\n }\n `);\n }\n }\n }\n doc.write(`payload.value = newResult;`);\n doc.write(`return payload;`);\n // closing `shape` in is what pays: turbofan specializes the parser against that one shape object, so every `shape[k]._zod.run` folds to a known callee. as a parameter it stays a generic load and measures 13% slower even with the forwarding frame gone\n return doc.compile();\n };\n let fastpass;\n const isObject = util.isObject;\n const jit = !core.globalConfig.jitless;\n const allowsEval = util.allowsEval;\n const fastEnabled = jit && allowsEval.value; // && !def.catchall;\n const catchall = def.catchall;\n let value;\n inst._zod.parse = (payload, ctx) => {\n value ?? (value = _normalized.value);\n const input = payload.value;\n if (!isObject(input)) {\n payload.issues.push({\n expected: \"object\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) {\n // always synchronous\n if (!fastpass)\n fastpass = generateFastpass(def.shape);\n payload = fastpass(payload, ctx);\n if (!catchall)\n return payload;\n return handleCatchall([], input, payload, ctx, value, inst, ctx?.abortEarly === true);\n }\n return superParse(payload, ctx);\n };\n});\nfunction handleUnionResults(results, final, inst, ctx) {\n for (const result of results) {\n if (result.issues.length === 0) {\n final.value = result.value;\n return final;\n }\n }\n const nonaborted = results.filter((r) => !util.aborted(r));\n if (nonaborted.length === 1) {\n final.value = nonaborted[0].value;\n return nonaborted[0];\n }\n final.issues.push({\n code: \"invalid_union\",\n input: final.value,\n inst,\n errors: results.map((result) => result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n });\n return final;\n}\nexport const $ZodUnion = /*@__PURE__*/ core.$constructor(\"$ZodUnion\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.options.some((o) => o._zod.optin === \"defaulted\")\n ? \"defaulted\"\n : zod.def.options.some((o) => o._zod.optin !== undefined)\n ? \"optional\"\n : undefined);\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.options.some((o) => o._zod.optout === \"optional\") ? \"optional\" : undefined);\n util.defineLazyInternal(inst, \"values\", (zod) => {\n if (zod.def.options.every((o) => o._zod.values)) {\n return new Set(zod.def.options.flatMap((option) => Array.from(option._zod.values)));\n }\n return undefined;\n });\n util.defineLazyInternal(inst, \"pattern\", (zod) => {\n if (zod.def.options.every((o) => o._zod.pattern)) {\n const patterns = zod.def.options.map((o) => o._zod.pattern);\n return new RegExp(`^(${patterns.map((p) => util.cleanRegex(p.source)).join(\"|\")})$`);\n }\n return undefined;\n });\n const first = def.options.length === 1 ? def.options[0]._zod.run : null;\n inst._zod.parse = (payload, ctx) => {\n if (first) {\n return first(payload, ctx);\n }\n let async = false;\n const results = [];\n for (const option of def.options) {\n const result = option._zod.run({\n value: payload.value,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n results.push(result);\n async = true;\n }\n else {\n if (result.issues.length === 0)\n return result;\n results.push(result);\n }\n }\n if (!async)\n return handleUnionResults(results, payload, inst, ctx);\n return Promise.all(results).then((results) => {\n return handleUnionResults(results, payload, inst, ctx);\n });\n };\n});\nfunction handleExclusiveUnionResults(results, final, inst, ctx) {\n const matches = [];\n for (let i = 0; i < results.length; i++) {\n if (results[i].issues.length === 0)\n matches.push(i);\n }\n if (matches.length === 1) {\n final.value = results[matches[0]].value;\n return final;\n }\n if (matches.length === 0) {\n // No matches - same as regular union\n final.issues.push({\n code: \"invalid_union\",\n input: final.value,\n inst,\n errors: results.map((result) => result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n });\n }\n else {\n // Multiple matches - exclusive union failure\n final.issues.push({\n code: \"invalid_union\",\n input: final.value,\n inst,\n errors: [],\n inclusive: false,\n matches,\n });\n }\n return final;\n}\nexport const $ZodXor = /*@__PURE__*/ core.$constructor(\"$ZodXor\", (inst, def) => {\n $ZodUnion.init(inst, def);\n def.inclusive = false;\n const first = def.options.length === 1 ? def.options[0]._zod.run : null;\n inst._zod.parse = (payload, ctx) => {\n if (first) {\n return first(payload, ctx);\n }\n let async = false;\n const results = [];\n for (const option of def.options) {\n const result = option._zod.run({\n value: payload.value,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n results.push(result);\n async = true;\n }\n else {\n results.push(result);\n }\n }\n if (!async)\n return handleExclusiveUnionResults(results, payload, inst, ctx);\n return Promise.all(results).then((results) => {\n return handleExclusiveUnionResults(results, payload, inst, ctx);\n });\n };\n});\n/** Returns the option whose discriminator claims `value`, or throws if ambiguous. */\nexport function getDiscriminatedOption(union, value) {\n const internals = union._zod;\n let map = internals.bag.optionsMap;\n if (!map) {\n map = discriminatorMap(internals.def);\n internals.bag.optionsMap = map;\n }\n const option = map.get(value);\n if (option === null)\n throw new Error(`Ambiguous discriminator value \"${String(value)}\"`);\n return option;\n}\nfunction discriminatorMap(def) {\n const map = new Map();\n for (const option of def.options) {\n const values = option._zod.propValues?.[def.discriminator];\n if (!values || values.size === 0)\n throw new Error(`Invalid discriminated union option at index \"${def.options.indexOf(option)}\"`);\n for (const value of values) {\n if (map.has(value)) {\n if (value !== undefined)\n throw new Error(`Duplicate discriminator value \"${String(value)}\"`);\n // keep the collision marked so a later member cannot reclaim it\n map.set(value, null);\n }\n else {\n map.set(value, option);\n }\n }\n }\n return map;\n}\nexport const $ZodDiscriminatedUnion = \n/*@__PURE__*/\ncore.$constructor(\"$ZodDiscriminatedUnion\", (inst, def) => {\n def.inclusive = false;\n $ZodUnion.init(inst, def);\n const _super = inst._zod.parse;\n util.defineLazyInternal(inst, \"propValues\", (zod) => {\n const propValues = {};\n let undefinedCount = 0;\n for (const option of zod.def.options) {\n const pv = option._zod.propValues;\n if (!pv || Object.keys(pv).length === 0)\n throw new Error(`Invalid discriminated union option at index \"${zod.def.options.indexOf(option)}\"`);\n if (pv[zod.def.discriminator]?.has(undefined))\n undefinedCount++;\n for (const [k, v] of Object.entries(pv)) {\n if (!Object.prototype.hasOwnProperty.call(propValues, k)) {\n util.assignProp(propValues, k, new Set());\n }\n for (const val of v) {\n propValues[k].add(val);\n }\n }\n }\n if (!zod.def.unionFallback && undefinedCount > 1)\n propValues[zod.def.discriminator]?.delete(undefined);\n return propValues;\n });\n // Checked now rather than in the lookup map below, so an option that lacks the discriminator fails at the `discriminatedUnion` call instead of on the first object parsed. Options whose shape cannot be enumerated without resolving it — pipes and lazies — are left to the map.\n def.options.forEach((option, i) => {\n const propShape = util.rawShape(option._zod.def);\n if (propShape && !Object.prototype.hasOwnProperty.call(propShape, def.discriminator)) {\n throw new Error(`Invalid discriminated union option at index \"${i}\"`);\n }\n });\n const disc = util.cached(() => discriminatorMap(def));\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!util.isObject(input)) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"object\",\n input,\n inst,\n });\n return payload;\n }\n const value = input?.[def.discriminator];\n const opt = disc.value.get(value);\n // forward metadata cannot choose an encoder for an absent tag\n if (opt && (value !== undefined || ctx.direction !== \"backward\")) {\n return opt._zod.run(payload, ctx);\n }\n // Fall back to union matching when the fast discriminator path fails:\n // - explicitly enabled via unionFallback, or\n // - during backward direction (encode), since codec-based discriminators have different values in forward vs backward directions\n if (def.unionFallback || ctx.direction === \"backward\") {\n return _super(payload, ctx);\n }\n // no matching discriminator\n payload.issues.push({\n code: \"invalid_union\",\n errors: [],\n note: \"No matching discriminator\",\n discriminator: def.discriminator,\n options: Array.from(disc.value.keys()).filter((value) => disc.value.get(value) !== null),\n input,\n path: [def.discriminator],\n inst,\n });\n return payload;\n };\n});\nexport const $ZodIntersection = /*@__PURE__*/ core.$constructor(\"$ZodIntersection\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n const left = def.left._zod.run({ value: input, issues: [] }, ctx);\n const right = def.right._zod.run({ value: input, issues: [] }, ctx);\n const async = left instanceof Promise || right instanceof Promise;\n if (async) {\n return Promise.all([left, right]).then(([left, right]) => {\n return handleIntersectionResults(payload, left, right);\n });\n }\n return handleIntersectionResults(payload, left, right);\n };\n});\nexport function mergeValues(a, b) {\n // const aType = parse.t(a);\n // const bType = parse.t(b);\n if (a === b) {\n return { valid: true, data: a };\n }\n if (a instanceof Date && b instanceof Date && +a === +b) {\n return { valid: true, data: a };\n }\n if (util.isPlainObject(a) && util.isPlainObject(b)) {\n const bKeys = Object.keys(b);\n const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);\n const newObj = { ...a, ...b };\n if (Object.prototype.hasOwnProperty.call(newObj, \"__proto__\"))\n delete newObj.__proto__;\n for (const key of sharedKeys) {\n if (key === \"__proto__\")\n continue;\n const sharedValue = mergeValues(a[key], b[key]);\n if (!sharedValue.valid) {\n return {\n valid: false,\n mergeErrorPath: [key, ...sharedValue.mergeErrorPath],\n };\n }\n newObj[key] = sharedValue.data;\n }\n return { valid: true, data: newObj };\n }\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) {\n return { valid: false, mergeErrorPath: [] };\n }\n const newArray = [];\n for (let index = 0; index < a.length; index++) {\n const itemA = a[index];\n const itemB = b[index];\n const sharedValue = mergeValues(itemA, itemB);\n if (!sharedValue.valid) {\n return {\n valid: false,\n mergeErrorPath: [index, ...sharedValue.mergeErrorPath],\n };\n }\n newArray.push(sharedValue.data);\n }\n return { valid: true, data: newArray };\n }\n return { valid: false, mergeErrorPath: [] };\n}\nfunction handleIntersectionResults(result, left, right) {\n // Track which side(s) reject each key. A key rejection is reported only when BOTH sides reject it, so a key owned by one branch survives the other's key schema. strictObject reports these as unrecognized_keys; a record with an open key schema reports one invalid_key per key.\n const unrecKeys = new Map();\n let unrecIssue;\n const keyIssues = new Map();\n const collect = (iss, side) => {\n let keys;\n if (iss.code === \"unrecognized_keys\" && !iss.path?.length) {\n unrecIssue ?? (unrecIssue = iss);\n keys = iss.keys;\n }\n else if (iss.code === \"invalid_key\" && iss.origin === \"record\" && iss.path?.length === 1) {\n const k = String(iss.path[0]);\n if (!keyIssues.has(k))\n keyIssues.set(k, iss);\n keys = [k];\n }\n else {\n return false;\n }\n for (const k of keys) {\n if (!unrecKeys.has(k))\n unrecKeys.set(k, {});\n unrecKeys.get(k)[side] = true;\n }\n return true;\n };\n for (const iss of left.issues) {\n if (!collect(iss, \"l\"))\n result.issues.push(iss);\n }\n for (const iss of right.issues) {\n if (!collect(iss, \"r\"))\n result.issues.push(iss);\n }\n // Report only keys rejected by BOTH sides\n const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k);\n if (bothKeys.length) {\n const aggregated = unrecIssue ? bothKeys.filter((k) => unrecIssue.keys.includes(k)) : [];\n if (aggregated.length)\n result.issues.push({ ...unrecIssue, keys: aggregated });\n for (const k of bothKeys) {\n if (!aggregated.includes(k) && keyIssues.has(k))\n result.issues.push(keyIssues.get(k));\n }\n }\n const merged = mergeValues(left.value, right.value);\n if (!merged.valid) {\n if (util.aborted(result))\n return result;\n throw new Error(`Unmergable intersection. Error path: ` + `${JSON.stringify(merged.mergeErrorPath)}`);\n }\n result.value = merged.data;\n return result;\n}\nexport const $ZodTuple = /*@__PURE__*/ core.$constructor(\"$ZodTuple\", (inst, def) => {\n $ZodType.init(inst, def);\n const items = def.items;\n const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!Array.isArray(input)) {\n payload.issues.push({\n input,\n inst,\n expected: \"tuple\",\n code: \"invalid_type\",\n });\n return payload;\n }\n payload.value = memo ? memo.alloc(inst, payload, [], ctx) : [];\n const proms = [];\n const optinStart = getTupleOptStart(items, \"optin\");\n const optoutStart = getTupleOptStart(items, \"optout\");\n if (!def.rest) {\n if (input.length < optinStart) {\n payload.issues.push({\n code: \"too_small\",\n minimum: optinStart,\n inclusive: true,\n input,\n inst,\n origin: \"array\",\n });\n return payload;\n }\n if (input.length > items.length) {\n payload.issues.push({\n code: \"too_big\",\n maximum: items.length,\n inclusive: true,\n input,\n inst,\n origin: \"array\",\n });\n }\n }\n // Run every item in parallel, collecting results into an indexed array. The post-processing in `handleTupleResults` walks them in order so it can decide whether an absent optional-output error can truncate the tail or must be reported to preserve required output.\n const itemResults = new Array(items.length);\n // only tracked when there is a rest loop to skip\n const abortEarly = def.rest ? ctx?.abortEarly : undefined;\n let itemAborted = false;\n for (let i = 0; i < items.length; i++) {\n const r = items[i]._zod.run({ value: input[i], issues: [] }, ctx);\n if (r instanceof Promise) {\n proms.push(r.then((rr) => {\n itemResults[i] = rr;\n }));\n }\n else {\n itemResults[i] = r;\n if (abortEarly && !itemAborted && r.issues.length)\n itemAborted = util.aborted(r);\n }\n }\n // sound because rest is non-empty exactly when every fixed index is present, the one case handleTupleResults cannot discard an item's issues\n if (def.rest && !itemAborted) {\n let i = items.length - 1;\n const rest = input.slice(items.length);\n let seen = payload.issues.length;\n for (const el of rest) {\n if (abortEarly && payload.issues.length !== seen) {\n if (util.aborted(payload, seen))\n break;\n seen = payload.issues.length;\n }\n i++;\n const result = def.rest._zod.run({ value: el, issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((r) => handleTupleResult(r, payload, i)));\n }\n else {\n handleTupleResult(result, payload, i);\n }\n }\n }\n if (proms.length) {\n return Promise.all(proms).then(() => handleTupleResults(itemResults, payload, items, input, optoutStart));\n }\n return handleTupleResults(itemResults, payload, items, input, optoutStart);\n };\n});\nfunction getTupleOptStart(items, key) {\n for (let i = items.length - 1; i >= 0; i--) {\n // optin is a three-rung ladder so any rung above `undefined` permits an absent slot; optout stays two-valued.\n const omittable = key === \"optin\" ? items[i]._zod.optin !== undefined : items[i]._zod.optout === \"optional\";\n if (!omittable)\n return i + 1;\n }\n return 0;\n}\nfunction handleTupleResult(result, final, index) {\n if (result.issues.length) {\n final.issues.push(...util.prefixIssues(index, result.issues));\n }\n final.value[index] = result.value;\n}\nfunction handleTupleResults(itemResults, final, items, input, optoutStart) {\n // Walk results in order. Mirror $ZodObject's swallow-on-absent-optional rule, but only after `optoutStart`: the first index where the output tuple tail can be absent.\n for (let i = 0; i < items.length; i++) {\n const r = itemResults[i];\n const isPresent = i < input.length;\n // The array analog of `handlePropertyResult`'s absent-key early return: the middle rung permits absence without supplying anything in its place, so the tail truncates here instead of materializing whatever the item made of `undefined`.\n if (!isPresent && i >= optoutStart && items[i]._zod.optin === \"optional\") {\n final.value.length = i;\n break;\n }\n if (r.issues.length) {\n if (!isPresent && i >= optoutStart) {\n final.value.length = i;\n break;\n }\n final.issues.push(...util.prefixIssues(i, r.issues));\n }\n final.value[i] = r.value;\n }\n // Drop trailing slots that produced `undefined` for absent input\n // (the array analog of an absent optional key on an object). The\n // `i >= input.length` floor is critical: an explicit `undefined`\n // *inside* the input must be preserved even when the schema is\n // optional-out (e.g. `z.string().or(z.undefined())` accepting an\n // explicit undefined value).\n for (let i = final.value.length - 1; i >= input.length; i--) {\n if (items[i]._zod.optout === \"optional\" && final.value[i] === undefined) {\n final.value.length = i;\n }\n else {\n break;\n }\n }\n return final;\n}\nexport const $ZodRecord = /*@__PURE__*/ core.$constructor(\"$ZodRecord\", (inst, def) => {\n $ZodType.init(inst, def);\n const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!util.isPlainObject(input)) {\n payload.issues.push({\n expected: \"record\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n // no guard in either loop below: a record's invalid_key aborts but an enclosing intersection can reconcile it, so a stopped loop hides keys the sibling does not own and the intersection then rejects nothing\n const proms = [];\n const values = def.keyType._zod.values;\n if (values && !def.partial) {\n payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {};\n const recordKeys = new Set();\n for (const key of values) {\n if (typeof key === \"string\" || typeof key === \"number\" || typeof key === \"symbol\") {\n recordKeys.add(typeof key === \"number\" ? key.toString() : key);\n // A declared __proto__ is stripped but is not an unrecognized key.\n if (key === \"__proto__\")\n continue;\n const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n if (keyResult instanceof Promise) {\n throw new Error(\"Async schemas not supported in object keys currently\");\n }\n if (keyResult.issues.length) {\n payload.issues.push({\n code: \"invalid_key\",\n origin: \"record\",\n issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n input: key,\n path: [key],\n inst,\n });\n continue;\n }\n const outKey = keyResult.value;\n if (outKey === \"__proto__\")\n continue;\n const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[outKey] = result.value;\n }));\n }\n else {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[outKey] = result.value;\n }\n }\n }\n let unrecognized;\n for (const key in input) {\n if (!recordKeys.has(key)) {\n if (def.mode === \"loose\") {\n // skip __proto__ so it can't replace the result prototype via the assignment setter on the plain {} we build into\n if (key === \"__proto__\")\n continue;\n payload.value[key] = input[key];\n }\n else {\n unrecognized = unrecognized ?? [];\n unrecognized.push(key);\n }\n }\n }\n if (unrecognized && unrecognized.length > 0) {\n payload.issues.push({\n code: \"unrecognized_keys\",\n input,\n inst,\n keys: unrecognized,\n continue: true,\n });\n }\n }\n else {\n payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {};\n // An enumerable key schema declares which keys the record owns, so a key outside the set is unrecognized. A non-enumerable one (regex, refine) is a constraint every key must satisfy, so a failing key is invalid. Only the former is reconcilable against the other side of an intersection.\n let unrecognized;\n // Reflect.ownKeys for Symbol-key support; filter non-enumerable to match z.object()\n for (const key of Reflect.ownKeys(input)) {\n if (key === \"__proto__\")\n continue;\n if (!Object.prototype.propertyIsEnumerable.call(input, key))\n continue;\n let keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n if (keyResult instanceof Promise) {\n throw new Error(\"Async schemas not supported in object keys currently\");\n }\n // Numeric string fallback: if key is a numeric string and failed, retry with Number(key). This handles z.number(), z.literal([1, 2, 3]), and unions containing numeric literals\n const checkNumericKey = typeof key === \"string\" && regexes.number.test(key) && keyResult.issues.length;\n if (checkNumericKey) {\n const retryResult = def.keyType._zod.run({ value: Number(key), issues: [] }, ctx);\n if (retryResult instanceof Promise) {\n throw new Error(\"Async schemas not supported in object keys currently\");\n }\n if (retryResult.issues.length === 0) {\n keyResult = retryResult;\n }\n }\n if (keyResult.issues.length) {\n if (def.mode === \"loose\") {\n // Pass through unchanged\n payload.value[key] = input[key];\n }\n else if (values) {\n unrecognized = unrecognized ?? [];\n unrecognized.push(key);\n }\n else {\n // Default \"strict\" behavior: error on invalid key\n payload.issues.push({\n code: \"invalid_key\",\n origin: \"record\",\n issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n input: key,\n path: [key],\n inst,\n });\n }\n continue;\n }\n // the guard above tests the raw input key, but the key schema can normalize an ordinary key into __proto__; re-check the key we actually write under\n const outKey = keyResult.value;\n if (outKey === \"__proto__\")\n continue;\n const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[outKey] = result.value;\n }));\n }\n else {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[outKey] = result.value;\n }\n }\n if (unrecognized && unrecognized.length > 0) {\n payload.issues.push({\n code: \"unrecognized_keys\",\n input,\n inst,\n keys: unrecognized,\n continue: true,\n });\n }\n }\n if (proms.length) {\n return Promise.all(proms).then(() => payload);\n }\n return payload;\n };\n});\nexport const $ZodMap = /*@__PURE__*/ core.$constructor(\"$ZodMap\", (inst, def) => {\n $ZodType.init(inst, def);\n const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!(input instanceof Map)) {\n payload.issues.push({\n expected: \"map\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n const proms = [];\n payload.value = memo ? memo.alloc(inst, payload, new Map(), ctx) : new Map();\n const abortEarly = ctx?.abortEarly;\n let seen = payload.issues.length;\n for (const [key, value] of input) {\n if (abortEarly && payload.issues.length !== seen) {\n if (util.aborted(payload, seen))\n break;\n seen = payload.issues.length;\n }\n const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n const valueResult = def.valueType._zod.run({ value: value, issues: [] }, ctx);\n if (keyResult instanceof Promise || valueResult instanceof Promise) {\n proms.push(Promise.all([keyResult, valueResult]).then(([keyResult, valueResult]) => {\n handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx);\n }));\n }\n else {\n handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx);\n }\n }\n if (proms.length)\n return Promise.all(proms).then(() => payload);\n return payload;\n };\n capSize(inst, mapSize);\n});\nfunction handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) {\n if (keyResult.issues.length) {\n if (util.propertyKeyTypes.has(typeof key)) {\n final.issues.push(...util.prefixIssues(key, keyResult.issues));\n }\n else {\n final.issues.push({\n code: \"invalid_key\",\n origin: \"map\",\n input,\n inst,\n issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n });\n }\n }\n if (valueResult.issues.length) {\n if (util.propertyKeyTypes.has(typeof key)) {\n final.issues.push(...util.prefixIssues(key, valueResult.issues));\n }\n else {\n final.issues.push({\n origin: \"map\",\n code: \"invalid_element\",\n input,\n inst,\n key: key,\n issues: valueResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n });\n }\n }\n final.value.set(keyResult.value, valueResult.value);\n}\nexport const $ZodSet = /*@__PURE__*/ core.$constructor(\"$ZodSet\", (inst, def) => {\n $ZodType.init(inst, def);\n const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!(input instanceof Set)) {\n payload.issues.push({\n input,\n inst,\n expected: \"set\",\n code: \"invalid_type\",\n });\n return payload;\n }\n const proms = [];\n payload.value = memo ? memo.alloc(inst, payload, new Set(), ctx) : new Set();\n const abortEarly = ctx?.abortEarly;\n let seen = payload.issues.length;\n for (const item of input) {\n if (abortEarly && payload.issues.length !== seen) {\n if (util.aborted(payload, seen))\n break;\n seen = payload.issues.length;\n }\n const result = def.valueType._zod.run({ value: item, issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => handleSetResult(result, payload)));\n }\n else\n handleSetResult(result, payload);\n }\n if (proms.length)\n return Promise.all(proms).then(() => payload);\n return payload;\n };\n capSize(inst, setSize);\n});\nfunction handleSetResult(result, final) {\n if (result.issues.length) {\n final.issues.push(...result.issues);\n }\n final.value.add(result.value);\n}\nexport const $ZodEnum = /*@__PURE__*/ core.$constructor(\"$ZodEnum\", (inst, def) => {\n $ZodType.init(inst, def);\n const values = util.getEnumValues(def.entries);\n const valuesSet = new Set(values);\n inst._zod.values = valuesSet;\n util.defineLazyInternal(inst, \"pattern\", (zod) => {\n const patternValues = util.getEnumValues(zod.def.entries).filter((k) => util.propertyKeyTypes.has(typeof k));\n // unmatchable fallback, RE2-safe: an empty alternation would compile to /^()$/, which matches \"\"\n return new RegExp(patternValues.length ? `^(${patternValues.map((o) => util.escapeRegex(o.toString())).join(\"|\")})$` : \"^[^\\\\s\\\\S]$\");\n });\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (valuesSet.has(input)) {\n return payload;\n }\n payload.issues.push({\n code: \"invalid_value\",\n values,\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodLiteral = /*@__PURE__*/ core.$constructor(\"$ZodLiteral\", (inst, def) => {\n $ZodType.init(inst, def);\n const values = new Set(def.values);\n inst._zod.values = values;\n util.defineLazyInternal(inst, \"pattern\", (zod) => {\n const vals = zod.def.values;\n // unmatchable fallback, RE2-safe: an empty alternation would compile to /^()$/, which matches \"\"\n return new RegExp(vals.length\n ? `^(${vals\n .map((o) => typeof o === \"string\" ? util.escapeRegex(o) : o ? util.escapeRegex(o.toString()) : String(o))\n .join(\"|\")})$`\n : \"^[^\\\\s\\\\S]$\");\n });\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (values.has(input)) {\n return payload;\n }\n payload.issues.push({\n code: \"invalid_value\",\n values: def.values,\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodFile = /*@__PURE__*/ core.$constructor(\"$ZodFile\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n // @ts-ignore\n if (input instanceof File)\n return payload;\n payload.issues.push({\n expected: \"file\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodTransform = /*@__PURE__*/ core.$constructor(\"$ZodTransform\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.optin = \"optional\";\n core.globalConfig.memoizer?.guard(inst);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n throw new core.$ZodEncodeError(inst.constructor.name);\n }\n const _out = def.transform(payload.value, payload);\n if (ctx.async) {\n const output = _out instanceof Promise ? _out : Promise.resolve(_out);\n return output.then((output) => {\n payload.value = output;\n return payload;\n });\n }\n if (_out instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n payload.value = _out;\n return payload;\n };\n});\nfunction handleOptionalResult(payload, result) {\n // A substituting schema that still failed has no usable answer; yield undefined. Its issues are simply dropped: it ran on a payload of its own, so there is no shared array to truncate and nothing of the caller's to lose with it.\n payload.value = result.issues.length ? undefined : result.value;\n return payload;\n}\nexport const $ZodOptional = /*@__PURE__*/ core.$constructor(\"$ZodOptional\", (inst, def) => {\n $ZodType.init(inst, def);\n // .optional() propagates absence rather than substituting for it, so a defaulted inner keeps its rung.\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.innerType._zod.optin === \"defaulted\" ? \"defaulted\" : \"optional\");\n inst._zod.optout = \"optional\";\n util.defineLazyInternal(inst, \"values\", (zod) => {\n const values = zod.def.innerType._zod.values;\n return values ? new Set([...values, undefined]) : undefined;\n });\n util.defineLazyInternal(inst, \"pattern\", (zod) => {\n const pattern = zod.def.innerType._zod.pattern;\n return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)})?$`) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n if (payload.value === undefined) {\n // Only the top rung substitutes a value for absence; everything else leaves it intact, which is what .optional() means.\n if (def.innerType._zod.optin !== \"defaulted\")\n return payload;\n // Its own payload, for the same reason $ZodCatch gets one: a pipe forwards an unrecognized key through the caller's issues array, and this must not read that as the substituting schema failing and drop it.\n const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx);\n if (result instanceof Promise)\n return result.then((result) => handleOptionalResult(payload, result));\n return handleOptionalResult(payload, result);\n }\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodExactOptional = /*@__PURE__*/ core.$constructor(\"$ZodExactOptional\", (inst, def) => {\n // Call parent init - inherits optin/optout = \"optional\"\n $ZodOptional.init(inst, def);\n // Override values/pattern to NOT add undefined\n util.defineLazyInternal(inst, \"values\", (zod) => zod.def.innerType._zod.values);\n util.defineLazyInternal(inst, \"pattern\", (zod) => zod.def.innerType._zod.pattern);\n // Override parse to just delegate (no undefined handling)\n inst._zod.parse = (payload, ctx) => {\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodNullable = /*@__PURE__*/ core.$constructor(\"$ZodNullable\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.innerType._zod.optin);\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.innerType._zod.optout);\n util.defineLazyInternal(inst, \"pattern\", (zod) => {\n const pattern = zod.def.innerType._zod.pattern;\n return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)}|null)$`) : undefined;\n });\n util.defineLazyInternal(inst, \"values\", (zod) => {\n return zod.def.innerType._zod.values ? new Set([...zod.def.innerType._zod.values, null]) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n // Forward direction (decode): allow null to pass through\n if (payload.value === null)\n return payload;\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodDefault = /*@__PURE__*/ core.$constructor(\"$ZodDefault\", (inst, def) => {\n $ZodType.init(inst, def);\n // inst._zod.qin = \"true\";\n inst._zod.optin = \"defaulted\";\n util.defineLazyInternal(inst, \"values\", (zod) => zod.def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n // Forward direction (decode): apply defaults for undefined input\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n /**\n * $ZodDefault returns the default value immediately in forward direction.\n * It doesn't pass the default value into the validator (\"prefault\"). There's no reason to pass the default value through validation. The validity of the default is enforced by TypeScript statically. Otherwise, it's the responsibility of the user to ensure the default is valid. In the case of pipes with divergent in/out types, you can specify the default on the `in` schema of your ZodPipe to set a \"prefault\" for the pipe. */\n return payload;\n }\n // Forward direction: continue with default handling\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => handleDefaultResult(result, def));\n }\n return handleDefaultResult(result, def);\n };\n});\nfunction handleDefaultResult(payload, def) {\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n }\n return payload;\n}\nexport const $ZodPrefault = /*@__PURE__*/ core.$constructor(\"$ZodPrefault\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.optin = \"defaulted\";\n util.defineLazyInternal(inst, \"values\", (zod) => zod.def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n // Forward direction (decode): apply prefault for undefined input\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n }\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodNonOptional = /*@__PURE__*/ core.$constructor(\"$ZodNonOptional\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazyInternal(inst, \"values\", (zod) => {\n const v = zod.def.innerType._zod.values;\n return v ? new Set([...v].filter((x) => x !== undefined)) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => handleNonOptionalResult(result, inst));\n }\n return handleNonOptionalResult(result, inst);\n };\n});\nfunction handleNonOptionalResult(payload, inst) {\n if (!payload.issues.length && payload.value === undefined) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"nonoptional\",\n input: payload.value,\n inst,\n });\n }\n return payload;\n}\nexport const $ZodSuccess = /*@__PURE__*/ core.$constructor(\"$ZodSuccess\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n throw new core.$ZodEncodeError(\"ZodSuccess\");\n }\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => {\n payload.value = result.issues.length === 0;\n return payload;\n });\n }\n payload.value = result.issues.length === 0;\n return payload;\n };\n});\nfunction handleCatchResult(payload, result, def, ctx) {\n if (!result.issues.length) {\n payload.value = result.value;\n // The value carries up, so the flag describing it has to carry with it: a back-edge into a node still being parsed must not be frozen by an enclosing readonly, and its checks belong to the node itself. Guarded so the ordinary case adds no own property.\n if (result.memo)\n payload.memo = true;\n return payload;\n }\n // Spread the inner's own payload, not ours: `value` has to stay the input the catch was handed, and the inner ran on a payload of its own so its issues are already private to this call.\n payload.value = def.catchValue({\n ...result,\n value: payload.value,\n error: {\n issues: result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n },\n input: payload.value,\n });\n return payload;\n}\nexport const $ZodCatch = /*@__PURE__*/ core.$constructor(\"$ZodCatch\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.innerType._zod.optin === \"defaulted\" ? \"defaulted\" : \"optional\");\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.innerType._zod.optout);\n util.defineLazyInternal(inst, \"values\", (zod) => zod.def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n // Forward direction (decode): apply catch logic\n const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx);\n if (result instanceof Promise) {\n return result.then((result) => handleCatchResult(payload, result, def, ctx));\n }\n return handleCatchResult(payload, result, def, ctx);\n };\n});\nexport const $ZodNaN = /*@__PURE__*/ core.$constructor(\"$ZodNaN\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"number\" || !Number.isNaN(payload.value)) {\n payload.issues.push({\n input: payload.value,\n inst,\n expected: \"nan\",\n code: \"invalid_type\",\n });\n return payload;\n }\n return payload;\n };\n});\nexport const $ZodPipe = /*@__PURE__*/ core.$constructor(\"$ZodPipe\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazyInternal(inst, \"values\", (zod) => zod.def.in._zod.values);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.in._zod.optin);\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.out._zod.optout);\n util.defineLazyInternal(inst, \"propValues\", (zod) => zod.def.in._zod.propValues);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n const right = def.out._zod.run(payload, ctx);\n if (right instanceof Promise) {\n return right.then((right) => handlePipeResult(right, def.in, ctx));\n }\n return handlePipeResult(right, def.in, ctx);\n }\n const left = def.in._zod.run(payload, ctx);\n if (left instanceof Promise) {\n return left.then((left) => handlePipeResult(left, def.out, ctx));\n }\n return handlePipeResult(left, def.out, ctx);\n };\n});\nfunction handlePipeResult(left, next, ctx) {\n // Any issue stops the pipe, so a failing refinement never feeds its transform. An unrecognized key is the exception: it describes the input's extra properties, not the value being piped, and an enclosing intersection may yet reconcile it.\n if (left.issues.some((iss) => iss.code !== \"unrecognized_keys\")) {\n // prevent further checks\n left.aborted = true;\n return left;\n }\n return next._zod.run({ value: left.value, issues: left.issues }, ctx);\n}\nexport const $ZodCodec = /*@__PURE__*/ core.$constructor(\"$ZodCodec\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazyInternal(inst, \"values\", (zod) => zod.def.in._zod.values);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.in._zod.optin);\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.out._zod.optout);\n util.defineLazyInternal(inst, \"propValues\", (zod) => zod.def.in._zod.propValues);\n inst._zod.parse = (payload, ctx) => {\n const direction = ctx.direction || \"forward\";\n if (direction === \"forward\") {\n const left = def.in._zod.run(payload, ctx);\n if (left instanceof Promise) {\n return left.then((left) => handleCodecAResult(left, def, ctx));\n }\n return handleCodecAResult(left, def, ctx);\n }\n else {\n const right = def.out._zod.run(payload, ctx);\n if (right instanceof Promise) {\n return right.then((right) => handleCodecAResult(right, def, ctx));\n }\n return handleCodecAResult(right, def, ctx);\n }\n };\n});\nfunction handleCodecAResult(result, def, ctx) {\n if (result.issues.length) {\n // prevent further checks\n result.aborted = true;\n return result;\n }\n const direction = ctx.direction || \"forward\";\n if (direction === \"forward\") {\n const transformed = def.transform(result.value, result);\n if (transformed instanceof Promise) {\n return transformed.then((value) => handleCodecTxResult(result, value, def.out, ctx));\n }\n return handleCodecTxResult(result, transformed, def.out, ctx);\n }\n else {\n const transformed = def.reverseTransform(result.value, result);\n if (transformed instanceof Promise) {\n return transformed.then((value) => handleCodecTxResult(result, value, def.in, ctx));\n }\n return handleCodecTxResult(result, transformed, def.in, ctx);\n }\n}\nfunction handleCodecTxResult(left, value, nextSchema, ctx) {\n // Check if transform added any issues\n if (left.issues.length) {\n left.aborted = true;\n return left;\n }\n return nextSchema._zod.run({ value, issues: left.issues }, ctx);\n}\nexport const $ZodPreprocess = /*@__PURE__*/ core.$constructor(\"$ZodPreprocess\", (inst, def) => {\n $ZodPipe.init(inst, def);\n});\nexport const $ZodReadonly = /*@__PURE__*/ core.$constructor(\"$ZodReadonly\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazyInternal(inst, \"propValues\", (zod) => zod.def.innerType._zod.propValues);\n util.defineLazyInternal(inst, \"values\", (zod) => zod.def.innerType._zod.values);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.innerType?._zod?.optin);\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.innerType?._zod?.optout);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then(handleReadonlyResult);\n }\n return handleReadonlyResult(result);\n };\n});\nfunction handleReadonlyResult(payload) {\n // A repeat visit hands back a node that is still being built; freezing it here would make the rest of its keys fail to assign.\n if (!payload.memo)\n payload.value = Object.freeze(payload.value);\n return payload;\n}\n// a leaf's pattern source with its own checks folded in: the last pattern-carrying check wins, else length bounds narrow the catch-all, else an integer format narrows the number form. the fold lives here instead of on `_zod.pattern` so a bundle without template literals never pays for it\nfunction leafPattern(schema) {\n const def = schema._zod.def;\n let pattern = def.pattern;\n let isInt = !!def.format?.includes(\"int\");\n let minimum;\n let maximum;\n for (const ch of def.checks ?? []) {\n const d = ch._zod.def;\n if (d.pattern)\n pattern = d.pattern;\n isInt || (isInt = !!d.format?.includes(\"int\"));\n const lo = d.minimum ?? d.length;\n const hi = d.maximum ?? d.length;\n if (lo !== undefined && (minimum === undefined || lo > minimum))\n minimum = lo;\n if (hi !== undefined && (maximum === undefined || hi < maximum))\n maximum = hi;\n }\n if (pattern)\n return pattern.source;\n // an empty range matches nothing at runtime, and `{8,5}` is not a legal quantifier\n if (minimum !== undefined && maximum !== undefined && minimum > maximum)\n return \"(?!)\";\n if (minimum !== undefined || maximum !== undefined)\n return regexes.string({ minimum, maximum }).source;\n const own = schema._zod.pattern;\n return (isInt && own === regexes.number ? regexes.integer : own)?.source;\n}\n// a part's pattern source. a wrapper's pattern embeds its inner pattern's source verbatim, so the folded form is substituted in place without knowing the wrapper's own composition; a union's options are joined the way the union builds its own pattern\nfunction partPattern(schema) {\n const def = schema._zod.def;\n const own = schema._zod.pattern?.source;\n // lazy resolves its inner on the internals, not the def\n const inner = def.innerType ?? schema._zod.innerType;\n if (inner) {\n const before = inner._zod.pattern?.source;\n const after = partPattern(inner);\n if (own && before && after && after !== before) {\n return own.replace(util.cleanRegex(before), () => util.cleanRegex(after));\n }\n return own;\n }\n if (def.options) {\n const sources = def.options.map(partPattern);\n if (sources.every(Boolean))\n return `^(${sources.map((s) => util.cleanRegex(s)).join(\"|\")})$`;\n }\n return leafPattern(schema);\n}\nexport const $ZodTemplateLiteral = /*@__PURE__*/ core.$constructor(\"$ZodTemplateLiteral\", (inst, def) => {\n $ZodType.init(inst, def);\n const regexParts = [];\n for (const part of def.parts) {\n if (typeof part === \"object\" && part !== null) {\n // is Zod schema\n const source = partPattern(part);\n if (!source) {\n throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`);\n }\n regexParts.push(util.cleanRegex(source));\n }\n else if (part === null || util.primitiveTypes.has(typeof part)) {\n regexParts.push(util.escapeRegex(`${part}`));\n }\n else {\n throw new Error(`Invalid template literal part: ${part}`);\n }\n }\n inst._zod.pattern = new RegExp(`^${regexParts.join(\"\")}$`);\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"string\") {\n payload.issues.push({\n input: payload.value,\n inst,\n expected: \"string\",\n code: \"invalid_type\",\n });\n return payload;\n }\n inst._zod.pattern.lastIndex = 0;\n if (!inst._zod.pattern.test(payload.value)) {\n payload.issues.push({\n input: payload.value,\n inst,\n code: \"invalid_format\",\n format: def.format ?? \"template_literal\",\n pattern: inst._zod.pattern.source,\n });\n return payload;\n }\n return payload;\n };\n});\nexport const $ZodFunction = /*@__PURE__*/ core.$constructor(\"$ZodFunction\", (inst, def) => {\n $ZodType.init(inst, def);\n // Defined, not assigned: the classic prototype exposes `_def` as a getter with no setter.\n Object.defineProperty(inst, \"_def\", { value: def });\n inst._zod.def = def;\n inst.implement = (func) => {\n if (typeof func !== \"function\") {\n throw new Error(\"implement() must be called with a function\");\n }\n // Defined inline so the closure stays anonymous: binding it to a `const` first names it, which costs 256 bytes per implemented function.\n return Object.defineProperty(function (...args) {\n const parsedArgs = inst._def.input ? parse(inst._def.input, args) : args;\n const result = Reflect.apply(func, this, parsedArgs);\n if (inst._def.output) {\n return parse(inst._def.output, result);\n }\n return result;\n }, \"_zod\", { value: inst._zod, enumerable: false });\n };\n inst.implementAsync = (func) => {\n if (typeof func !== \"function\") {\n throw new Error(\"implementAsync() must be called with a function\");\n }\n return Object.defineProperty(async function (...args) {\n const parsedArgs = inst._def.input ? await parseAsync(inst._def.input, args) : args;\n const result = await Reflect.apply(func, this, parsedArgs);\n if (inst._def.output) {\n return await parseAsync(inst._def.output, result);\n }\n return result;\n }, \"_zod\", { value: inst._zod, enumerable: false });\n };\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"function\") {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"function\",\n input: payload.value,\n inst,\n });\n return payload;\n }\n // Check if output is a promise type to determine if we should use async implementation\n const hasPromiseOutput = inst._def.output && inst._def.output._zod.def.type === \"promise\";\n if (hasPromiseOutput) {\n payload.value = inst.implementAsync(payload.value);\n }\n else {\n payload.value = inst.implement(payload.value);\n }\n return payload;\n };\n inst.input = (...args) => {\n const F = inst.constructor;\n if (Array.isArray(args[0])) {\n return new F({\n type: \"function\",\n input: new $ZodTuple({\n type: \"tuple\",\n items: args[0],\n rest: args[1],\n }),\n output: inst._def.output,\n });\n }\n return new F({\n type: \"function\",\n input: args[0],\n output: inst._def.output,\n });\n };\n inst.output = (output) => {\n const F = inst.constructor;\n return new F({\n type: \"function\",\n input: inst._def.input,\n output,\n });\n };\n return inst;\n});\nexport const $ZodPromise = /*@__PURE__*/ core.$constructor(\"$ZodPromise\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n return Promise.resolve(payload.value).then((inner) => def.innerType._zod.run({ value: inner, issues: [] }, ctx));\n };\n});\nexport const $ZodLazy = /*@__PURE__*/ core.$constructor(\"$ZodLazy\", (inst, def) => {\n $ZodType.init(inst, def);\n // Cache the resolved inner type on the shared `def` so all clones of this lazy (e.g. via `.describe()`/`.meta()`) share the same inner instance, preserving identity for cycle detection on recursive schemas.\n util.defineLazy(inst._zod, \"innerType\", () => {\n const d = def;\n if (!d._cachedInner)\n d._cachedInner = def.getter();\n return d._cachedInner;\n });\n util.defineLazyInternal(inst, \"pattern\", (zod) => zod.innerType?._zod?.pattern);\n util.defineLazyInternal(inst, \"propValues\", (zod) => zod.innerType?._zod?.propValues);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.innerType?._zod?.optin ?? undefined);\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.innerType?._zod?.optout ?? undefined);\n inst._zod.parse = (payload, ctx) => {\n const inner = inst._zod.innerType;\n return inner._zod.run(payload, ctx);\n };\n});\nexport const $ZodCustom = /*@__PURE__*/ core.$constructor(\"$ZodCustom\", (inst, def) => {\n checks.$ZodCheck.init(inst, def);\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _) => {\n return payload;\n };\n inst._zod.check = (payload) => {\n const input = payload.value;\n const r = def.fn(input);\n if (r instanceof Promise) {\n return r.then((r) => handleRefineResult(r, payload, input, inst));\n }\n handleRefineResult(r, payload, input, inst);\n return;\n };\n});\nfunction handleRefineResult(result, payload, input, inst) {\n if (!result) {\n const _iss = {\n code: \"custom\",\n input,\n inst, // incorporates params.error into issue reporting\n path: [...(inst._zod.def.path ?? [])], // incorporates params.error into issue reporting\n continue: !inst._zod.def.abort,\n // params: inst._zod.def.params,\n };\n if (inst._zod.def.params)\n _iss.params = inst._zod.def.params;\n payload.issues.push(util.issue(_iss));\n }\n}\n","var _a;\nexport const $output = /*@__PURE__*/ Symbol(\"ZodOutput\");\nexport const $input = /*@__PURE__*/ Symbol(\"ZodInput\");\nexport class $ZodRegistry {\n constructor() {\n this._map = new WeakMap();\n this._idmap = new Map();\n }\n add(schema, ..._meta) {\n const meta = _meta[0];\n this._map.set(schema, meta);\n if (meta && typeof meta === \"object\" && \"id\" in meta) {\n this._idmap.set(meta.id, schema);\n }\n return this;\n }\n clear() {\n this._map = new WeakMap();\n this._idmap = new Map();\n return this;\n }\n remove(schema) {\n const meta = this._map.get(schema);\n if (meta && typeof meta === \"object\" && \"id\" in meta) {\n this._idmap.delete(meta.id);\n }\n this._map.delete(schema);\n return this;\n }\n get(schema) {\n // return this._map.get(schema) as any;\n // inherit metadata\n const p = schema._zod.parent;\n if (p) {\n const pm = { ...(this.get(p) ?? {}) };\n delete pm.id; // do not inherit id\n const f = { ...pm, ...this._map.get(schema) };\n return Object.keys(f).length ? f : undefined;\n }\n return this._map.get(schema);\n }\n has(schema) {\n return this._map.has(schema);\n }\n}\n// registries\nexport function registry() {\n return new $ZodRegistry();\n}\n(_a = globalThis).__zod_globalRegistry ?? (_a.__zod_globalRegistry = registry());\nexport const globalRegistry = globalThis.__zod_globalRegistry;\n","import * as checks from \"./checks.js\";\nimport * as registries from \"./registries.js\";\nimport * as schemas from \"./schemas.js\";\nimport * as util from \"./util.js\";\nfunction snapshotChecks(def) {\n if (def.checks)\n def.checks = [...def.checks];\n return def;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _string(Class, params) {\n return new Class(snapshotChecks({ type: \"string\", ...util.normalizeParams(params) }));\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedString(Class, params) {\n return new Class(snapshotChecks({ type: \"string\", coerce: true, ...util.normalizeParams(params) }));\n}\n// @__NO_SIDE_EFFECTS__\nexport function _email(Class, params) {\n return new Class({\n type: \"string\",\n format: \"email\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _guid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"guid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v4\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v6\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv7(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v7\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _url(Class, params) {\n return new Class({\n type: \"string\",\n format: \"url\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _emoji(Class, params) {\n return new Class({\n type: \"string\",\n format: \"emoji\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nanoid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"nanoid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link _cuid2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\n// @__NO_SIDE_EFFECTS__\nexport function _cuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cuid2(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cuid2\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ulid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ulid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _xid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"xid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ksuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ksuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ipv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ipv4\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ipv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ipv6\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _mac(Class, params) {\n return new Class({\n type: \"string\",\n format: \"mac\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cidrv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cidrv4\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cidrv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cidrv6\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _base64(Class, params) {\n return new Class({\n type: \"string\",\n format: \"base64\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _base64url(Class, params) {\n return new Class({\n type: \"string\",\n format: \"base64url\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _e164(Class, params) {\n return new Class({\n type: \"string\",\n format: \"e164\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _creditCard(Class, params) {\n return new Class({\n type: \"string\",\n format: \"credit_card\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _iban(Class, params) {\n return new Class({\n type: \"string\",\n format: \"iban\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _jwt(Class, params) {\n return new Class({\n type: \"string\",\n format: \"jwt\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\nexport const TimePrecision = {\n Any: null,\n Minute: -1,\n Second: 0,\n Millisecond: 3,\n Microsecond: 6,\n};\n// @__NO_SIDE_EFFECTS__\nexport function _isoDateTime(Class, params) {\n return new Class({\n type: \"string\",\n format: \"datetime\",\n check: \"string_format\",\n offset: false,\n local: false,\n precision: null,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoDate(Class, params) {\n return new Class({\n type: \"string\",\n format: \"date\",\n check: \"string_format\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoTime(Class, params) {\n return new Class({\n type: \"string\",\n format: \"time\",\n check: \"string_format\",\n precision: null,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoDuration(Class, params) {\n return new Class({\n type: \"string\",\n format: \"duration\",\n check: \"string_format\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _number(Class, params) {\n return new Class(snapshotChecks({ type: \"number\", checks: [], ...util.normalizeParams(params) }));\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedNumber(Class, params) {\n return new Class(snapshotChecks({ type: \"number\", coerce: true, checks: [], ...util.normalizeParams(params) }));\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"safeint\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _float32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"float32\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _float64(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"float64\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"int32\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uint32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"uint32\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _boolean(Class, params) {\n return new Class({\n type: \"boolean\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedBoolean(Class, params) {\n return new Class({\n type: \"boolean\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _bigint(Class, params) {\n return new Class({\n type: \"bigint\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedBigint(Class, params) {\n return new Class({\n type: \"bigint\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int64(Class, params) {\n return new Class({\n type: \"bigint\",\n check: \"bigint_format\",\n abort: false,\n format: \"int64\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uint64(Class, params) {\n return new Class({\n type: \"bigint\",\n check: \"bigint_format\",\n abort: false,\n format: \"uint64\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _symbol(Class, params) {\n return new Class({\n type: \"symbol\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _undefined(Class, params) {\n return new Class({\n type: \"undefined\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _null(Class, params) {\n return new Class({\n type: \"null\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _any(Class) {\n return new Class({\n type: \"any\",\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _unknown(Class) {\n return new Class({\n type: \"unknown\",\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _never(Class, params) {\n return new Class({\n type: \"never\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _void(Class, params) {\n return new Class({\n type: \"void\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _date(Class, params) {\n return new Class({\n type: \"date\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedDate(Class, params) {\n return new Class({\n type: \"date\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nan(Class, params) {\n return new Class({\n type: \"nan\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lt(value, params) {\n return new checks.$ZodCheckLessThan({\n check: \"less_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: false,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lte(value, params) {\n return new checks.$ZodCheckLessThan({\n check: \"less_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: true,\n });\n}\nexport { \n/** @deprecated Use `z.lte()` instead. */\n_lte as _max, };\n// @__NO_SIDE_EFFECTS__\nexport function _gt(value, params) {\n return new checks.$ZodCheckGreaterThan({\n check: \"greater_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: false,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _gte(value, params) {\n return new checks.$ZodCheckGreaterThan({\n check: \"greater_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: true,\n });\n}\nexport { \n/** @deprecated Use `z.gte()` instead. */\n_gte as _min, };\n// @__NO_SIDE_EFFECTS__\nexport function _positive(params) {\n return _gt(0, params);\n}\n// negative\n// @__NO_SIDE_EFFECTS__\nexport function _negative(params) {\n return _lt(0, params);\n}\n// nonpositive\n// @__NO_SIDE_EFFECTS__\nexport function _nonpositive(params) {\n return _lte(0, params);\n}\n// nonnegative\n// @__NO_SIDE_EFFECTS__\nexport function _nonnegative(params) {\n return _gte(0, params);\n}\n// @__NO_SIDE_EFFECTS__\nexport function _multipleOf(value, params) {\n return new checks.$ZodCheckMultipleOf({\n check: \"multiple_of\",\n ...util.normalizeParams(params),\n value,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _maxSize(maximum, params) {\n return new checks.$ZodCheckMaxSize({\n check: \"max_size\",\n ...util.normalizeParams(params),\n maximum,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _minSize(minimum, params) {\n return new checks.$ZodCheckMinSize({\n check: \"min_size\",\n ...util.normalizeParams(params),\n minimum,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _size(size, params) {\n return new checks.$ZodCheckSizeEquals({\n check: \"size_equals\",\n ...util.normalizeParams(params),\n size,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _maxLength(maximum, params) {\n const ch = new checks.$ZodCheckMaxLength({\n check: \"max_length\",\n ...util.normalizeParams(params),\n maximum,\n });\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _minLength(minimum, params) {\n return new checks.$ZodCheckMinLength({\n check: \"min_length\",\n ...util.normalizeParams(params),\n minimum,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _length(length, params) {\n return new checks.$ZodCheckLengthEquals({\n check: \"length_equals\",\n ...util.normalizeParams(params),\n length,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _regex(pattern, params) {\n return new checks.$ZodCheckRegex({\n check: \"string_format\",\n format: \"regex\",\n ...util.normalizeParams(params),\n pattern,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lowercase(params) {\n return new checks.$ZodCheckLowerCase({\n check: \"string_format\",\n format: \"lowercase\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uppercase(params) {\n return new checks.$ZodCheckUpperCase({\n check: \"string_format\",\n format: \"uppercase\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _includes(includes, params) {\n return new checks.$ZodCheckIncludes({\n check: \"string_format\",\n format: \"includes\",\n ...util.normalizeParams(params),\n includes,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _startsWith(prefix, params) {\n return new checks.$ZodCheckStartsWith({\n check: \"string_format\",\n format: \"starts_with\",\n ...util.normalizeParams(params),\n prefix,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _endsWith(suffix, params) {\n return new checks.$ZodCheckEndsWith({\n check: \"string_format\",\n format: \"ends_with\",\n ...util.normalizeParams(params),\n suffix,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _property(property, schema, params) {\n return new checks.$ZodCheckProperty({\n check: \"property\",\n property,\n schema,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _properties(shape, params) {\n return new checks.$ZodCheckProperties({\n check: \"properties\",\n shape,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _mime(types, params) {\n return new checks.$ZodCheckMimeType({\n check: \"mime_type\",\n mime: types,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _overwrite(tx) {\n return new checks.$ZodCheckOverwrite({\n check: \"overwrite\",\n tx,\n });\n}\n// normalize\n// @__NO_SIDE_EFFECTS__\nexport function _normalize(form) {\n return _overwrite((input) => input.normalize(form));\n}\n// trim\n// @__NO_SIDE_EFFECTS__\nexport function _trim() {\n return _overwrite((input) => input.trim());\n}\n// toLowerCase\n// @__NO_SIDE_EFFECTS__\nexport function _toLowerCase() {\n return _overwrite((input) => input.toLowerCase());\n}\n// toUpperCase\n// @__NO_SIDE_EFFECTS__\nexport function _toUpperCase() {\n return _overwrite((input) => input.toUpperCase());\n}\n// slugify\n// @__NO_SIDE_EFFECTS__\nexport function _slugify() {\n return _overwrite((input) => util.slugify(input));\n}\n// @__NO_SIDE_EFFECTS__\nexport function _array(Class, element, params) {\n return new Class({\n type: \"array\",\n element,\n // get element() {\n // return element;\n // },\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _union(Class, options, params) {\n return new Class({\n type: \"union\",\n options,\n ...util.normalizeParams(params),\n });\n}\nexport function _xor(Class, options, params) {\n return new Class({\n type: \"union\",\n options,\n inclusive: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _discriminatedUnion(Class, discriminator, options, params) {\n return new Class({\n type: \"union\",\n options: options,\n discriminator,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _intersection(Class, left, right) {\n return new Class({\n type: \"intersection\",\n left,\n right,\n });\n}\n// export function _tuple(\n// Class: util.SchemaClass<schemas.$ZodTuple>,\n// items: [],\n// params?: string | $ZodTupleParams\n// ): schemas.$ZodTuple<[], null>;\n// @__NO_SIDE_EFFECTS__\nexport function _tuple(Class, items, _paramsOrRest, _params) {\n const hasRest = _paramsOrRest instanceof schemas.$ZodType;\n const params = hasRest ? _params : _paramsOrRest;\n const rest = hasRest ? _paramsOrRest : null;\n return new Class({\n type: \"tuple\",\n items,\n rest,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _record(Class, keyType, valueType, params) {\n return new Class({\n type: \"record\",\n keyType,\n valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _map(Class, keyType, valueType, params) {\n return new Class({\n type: \"map\",\n keyType,\n valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _set(Class, valueType, params) {\n return new Class({\n type: \"set\",\n valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _enum(Class, values, params) {\n const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;\n // if (Array.isArray(values)) {\n // for (const value of values) {\n // entries[value] = value;\n // }\n // } else {\n // Object.assign(entries, values);\n // }\n // const entries: util.EnumLike = {};\n // for (const val of values) {\n // entries[val] = val;\n // }\n return new Class({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\n/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead.\n *\n * ```ts\n * enum Colors { red, green, blue }\n * z.enum(Colors);\n * ```\n */\nexport function _nativeEnum(Class, entries, params) {\n return new Class({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _literal(Class, value, params) {\n return new Class({\n type: \"literal\",\n values: Array.isArray(value) ? value : [value],\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _file(Class, params) {\n return new Class({\n type: \"file\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _transform(Class, fn) {\n return new Class({\n type: \"transform\",\n transform: fn,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _optional(Class, innerType) {\n return new Class({\n type: \"optional\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nullable(Class, innerType) {\n return new Class({\n type: \"nullable\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _default(Class, innerType, defaultValue) {\n return new Class({\n type: \"default\",\n innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nonoptional(Class, innerType, params) {\n return new Class({\n type: \"nonoptional\",\n innerType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _success(Class, innerType) {\n return new Class({\n type: \"success\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _catch(Class, innerType, catchValue) {\n return new Class({\n type: \"catch\",\n innerType,\n catchValue: (typeof catchValue === \"function\" ? catchValue : util.constantCatch(catchValue)),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _pipe(Class, in_, out) {\n return new Class({\n type: \"pipe\",\n in: in_,\n out,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _readonly(Class, innerType) {\n return new Class({\n type: \"readonly\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _templateLiteral(Class, parts, params) {\n return new Class({\n type: \"template_literal\",\n parts,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lazy(Class, getter) {\n return new Class({\n type: \"lazy\",\n getter,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _promise(Class, innerType) {\n return new Class({\n type: \"promise\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _custom(Class, fn, _params) {\n const norm = util.normalizeParams(_params);\n norm.abort ?? (norm.abort = true); // default to abort:false\n const schema = new Class({\n type: \"custom\",\n check: \"custom\",\n fn: fn,\n ...norm,\n });\n return schema;\n}\n// same as _custom but defaults to abort:false\n// @__NO_SIDE_EFFECTS__\nexport function _refine(Class, fn, _params) {\n const schema = new Class({\n type: \"custom\",\n check: \"custom\",\n fn: fn,\n ...util.normalizeParams(_params),\n });\n return schema;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _superRefine(fn, params) {\n const ch = _check((payload) => {\n payload.addIssue = (issue) => {\n if (typeof issue === \"string\") {\n payload.issues.push(util.issue(issue, payload.value, ch._zod.def));\n }\n else {\n // for Zod 3 backwards compatibility\n const _issue = issue;\n if (_issue.fatal)\n _issue.continue = false;\n _issue.code ?? (_issue.code = \"custom\");\n if (!(\"input\" in _issue))\n _issue.input = payload.value;\n _issue.inst ?? (_issue.inst = ch);\n _issue.continue ?? (_issue.continue = !ch._zod.def.abort); // abort is always undefined, so this is always true...\n payload.issues.push(util.issue(_issue));\n }\n };\n return fn(payload.value, payload);\n }, params);\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _check(fn, params) {\n const ch = new checks.$ZodCheck({\n check: \"custom\",\n ...util.normalizeParams(params),\n });\n ch._zod.check = fn;\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function describe(description) {\n const ch = new checks.$ZodCheck({ check: \"describe\" });\n ch._zod.onattach = [\n (inst) => {\n const existing = registries.globalRegistry.get(inst) ?? {};\n registries.globalRegistry.add(inst, { ...existing, description });\n },\n ];\n ch._zod.check = () => { }; // no-op check\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function meta(metadata) {\n const ch = new checks.$ZodCheck({ check: \"meta\" });\n ch._zod.onattach = [\n (inst) => {\n const existing = registries.globalRegistry.get(inst) ?? {};\n registries.globalRegistry.add(inst, { ...existing, ...metadata });\n },\n ];\n ch._zod.check = () => { }; // no-op check\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _stringbool(Classes, _params) {\n const params = util.normalizeParams(_params);\n let truthyArray = params.truthy ?? [\"true\", \"1\", \"yes\", \"on\", \"y\", \"enabled\"];\n let falsyArray = params.falsy ?? [\"false\", \"0\", \"no\", \"off\", \"n\", \"disabled\"];\n if (params.case !== \"sensitive\") {\n truthyArray = truthyArray.map((v) => (typeof v === \"string\" ? v.toLowerCase() : v));\n falsyArray = falsyArray.map((v) => (typeof v === \"string\" ? v.toLowerCase() : v));\n }\n const truthySet = new Set(truthyArray);\n const falsySet = new Set(falsyArray);\n const _Codec = Classes.Codec ?? schemas.$ZodCodec;\n const _Boolean = Classes.Boolean ?? schemas.$ZodBoolean;\n const _String = Classes.String ?? schemas.$ZodString;\n const stringSchema = new _String({ type: \"string\", error: params.error });\n const booleanSchema = new _Boolean({ type: \"boolean\", error: params.error });\n const codec = new _Codec({\n type: \"pipe\",\n in: stringSchema,\n out: booleanSchema,\n transform: ((input, payload) => {\n let data = input;\n if (params.case !== \"sensitive\")\n data = data.toLowerCase();\n if (truthySet.has(data)) {\n return true;\n }\n else if (falsySet.has(data)) {\n return false;\n }\n else {\n payload.issues.push({\n code: \"invalid_value\",\n expected: \"stringbool\",\n values: [...truthySet, ...falsySet],\n input: payload.value,\n inst: codec,\n continue: false,\n });\n return {};\n }\n }),\n reverseTransform: ((input, _payload) => {\n if (input === true) {\n return truthyArray[0] || \"true\";\n }\n else {\n return falsyArray[0] || \"false\";\n }\n }),\n error: params.error,\n });\n codec._zod.bag.truthy = truthyArray;\n codec._zod.bag.falsy = falsyArray;\n codec._zod.bag.case = params.case ?? \"insensitive\";\n return codec;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _stringFormat(Class, format, fnOrRegex, _params = {}) {\n const params = util.normalizeParams(_params);\n const def = {\n check: \"string_format\",\n type: \"string\",\n format,\n fn: typeof fnOrRegex === \"function\" ? fnOrRegex : (val) => fnOrRegex.test(val),\n ...params,\n };\n if (fnOrRegex instanceof RegExp) {\n def.pattern = fnOrRegex;\n }\n const inst = new Class(def);\n return inst;\n}\n","import { globalRegistry } from \"./registries.js\";\nimport { assignProp } from \"./util.js\";\nfunction assignProps(target, ...sources) {\n for (const source of sources) {\n for (const key of Reflect.ownKeys(source)) {\n if (Object.prototype.propertyIsEnumerable.call(source, key)) {\n assignProp(target, key, source[key]);\n }\n }\n }\n return target;\n}\n// function initializeContext<T extends schemas.$ZodType>(inputs: JSONSchemaGeneratorParams<T>): ToJSONSchemaContext<T> {\n// return {\n// processor: inputs.processor,\n// metadataRegistry: inputs.metadata ?? globalRegistry,\n// target: inputs.target ?? \"draft-2020-12\",\n// unrepresentable: inputs.unrepresentable ?? \"throw\",\n// };\n// }\nexport function initializeContext(params) {\n // Normalize target: convert old non-hyphenated versions to hyphenated versions\n let target = params?.target ?? \"draft-2020-12\";\n if (target === \"draft-4\")\n target = \"draft-04\";\n if (target === \"draft-7\")\n target = \"draft-07\";\n return {\n processors: params.processors ?? {},\n metadataRegistry: params?.metadata ?? globalRegistry,\n target,\n unrepresentable: params?.unrepresentable ?? \"throw\",\n override: params?.override ?? (() => { }),\n io: params?.io ?? \"output\",\n counter: 0,\n seen: new Map(),\n sharedDefsExtractedFor: undefined,\n sharedEmitDoneFor: undefined,\n cycles: params?.cycles ?? \"ref\",\n reused: params?.reused ?? \"inline\",\n intersections: [],\n deferred: [],\n external: params?.external ?? undefined,\n };\n}\n/**\n * Applies the `unrepresentable` setting at a site that has no JSON Schema equivalent. Throws\n * `message` unless the setting (or the handler's return value) says otherwise. Returns `true` if a\n * custom JSON Schema was written into `json`, in which case the caller must not write its own.\n */\nexport function handleUnrepresentable(schema, ctx, json, params, message) {\n const result = typeof ctx.unrepresentable === \"function\"\n ? ctx.unrepresentable({ zodSchema: schema, path: params.path, message })\n : ctx.unrepresentable;\n if (result === \"any\")\n return false;\n if (result === undefined || result === \"throw\")\n throw new Error(message);\n Object.assign(json, result);\n return true;\n}\n// never rename this back to `process`: bundler polyfills inject a top-level `const process` that a lexical declaration of the same name collides with (#6397)\nexport function processSchema(schema, ctx, _params = { path: [], schemaPath: [] }) {\n var _a;\n const def = schema._zod.def;\n // check for schema in seens\n const seen = ctx.seen.get(schema);\n if (seen) {\n seen.count++;\n // check if cycle\n const isCycle = _params.schemaPath.includes(schema);\n if (isCycle) {\n seen.cycle = _params.path;\n }\n return seen.schema;\n }\n // initialize\n const result = { schema: {}, count: 1, cycle: undefined, path: _params.path };\n ctx.seen.set(schema, result);\n ctx.sharedDefsExtractedFor = undefined;\n ctx.sharedEmitDoneFor = undefined;\n // custom method overrides default behavior\n const overrideSchema = schema._zod.toJSONSchema?.();\n if (overrideSchema) {\n result.schema = overrideSchema;\n }\n else {\n const params = {\n ..._params,\n schemaPath: [..._params.schemaPath, schema],\n path: _params.path,\n };\n if (schema._zod.processJSONSchema) {\n schema._zod.processJSONSchema(ctx, result.schema, params);\n }\n else {\n const _json = result.schema;\n const processor = ctx.processors[def.type];\n if (!processor) {\n throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`);\n }\n processor(schema, ctx, _json, params);\n }\n const parent = schema._zod.parent;\n if (parent) {\n // Also set ref if processor didn't (for inheritance)\n if (!result.ref)\n result.ref = parent;\n processSchema(parent, ctx, params);\n ctx.seen.get(parent).isParent = true;\n }\n }\n // metadata\n const meta = ctx.metadataRegistry.get(schema);\n if (meta)\n assignProps(result.schema, meta);\n if (ctx.io === \"input\" && isTransforming(schema)) {\n // examples/defaults only apply to output type of pipe\n delete result.schema.examples;\n delete result.schema.default;\n }\n // set prefault as default\n if (ctx.io === \"input\" && \"_prefault\" in result.schema)\n (_a = result.schema).default ?? (_a.default = result.schema._prefault);\n delete result.schema._prefault;\n // pulling fresh from ctx.seen in case it was overwritten\n const _result = ctx.seen.get(schema);\n return _result.schema;\n}\n/** @deprecated Renamed to `processSchema`. An export alias declares no binding, so it is safe to keep. */\nexport { processSchema as process };\n// Escape a reference token for use in a JSON Pointer fragment (RFC 6901): `~` becomes `~0` and `/` becomes `~1`. The `~` replacement must run first.\nfunction encodeJSONPointerSegment(segment) {\n return segment.replace(/~/g, \"~0\").replace(/\\//g, \"~1\");\n}\nexport function extractDefs(ctx, schema\n// params: EmitParams\n) {\n // iterate over seen map;\n const root = ctx.seen.get(schema);\n if (!root)\n throw new Error(\"Unprocessed schema. This is a bug in Zod.\");\n // With `external` set, every registered schema resolves through the external branch of `makeURI`, so the root branch below produces the same ref the external branch would — this pass is identical whichever schema it is called with, and only needs to run once.\n if (ctx.external && ctx.sharedDefsExtractedFor === ctx.external)\n return;\n // Track ids to detect duplicates across different schemas\n const idToSchema = new Map();\n for (const entry of ctx.seen.entries()) {\n const id = ctx.metadataRegistry.get(entry[0])?.id;\n if (id) {\n const existing = idToSchema.get(id);\n if (existing && existing !== entry[0]) {\n throw new Error(`Duplicate schema id \"${id}\" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);\n }\n idToSchema.set(id, entry[0]);\n }\n }\n // returns a ref to the schema defId will be empty if the ref points to an external schema (or #)\n const makeURI = (entry) => {\n // comparing the seen objects because sometimes multiple schemas map to the same seen object. e.g. lazy\n // external is configured\n const defsSegment = ctx.target === \"draft-2020-12\" ? \"$defs\" : \"definitions\";\n if (ctx.external) {\n const externalId = ctx.external.registry.get(entry[0])?.id; // ?? \"__shared\";// `__schema${ctx.counter++}`;\n // check if schema is in the external registry\n const uriGenerator = ctx.external.uri ?? ((id) => id);\n if (externalId) {\n return { ref: uriGenerator(externalId) };\n }\n // otherwise, add to __shared\n const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`;\n entry[1].defId = id; // set defId so it will be reused if needed\n return { defId: id, ref: `${uriGenerator(\"__shared\")}#/${defsSegment}/${encodeJSONPointerSegment(id)}` };\n }\n const uriPrefix = `#`;\n const defUriPrefix = `${uriPrefix}/${defsSegment}/`;\n // an id-less root has nowhere to be extracted to, so it stays inline and self-references as `#`\n if (entry[1] === root && !entry[1].schema.id) {\n return { ref: uriPrefix };\n }\n // self-contained schema\n const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`;\n return { defId, ref: defUriPrefix + encodeJSONPointerSegment(defId) };\n };\n // stored cached version in `def` property remove all properties, set $ref\n const extractToDef = (entry) => {\n // if the schema is already a reference, do not extract it\n if (entry[1].schema.$ref) {\n return;\n }\n const seen = entry[1];\n const { ref, defId } = makeURI(entry);\n seen.def = { ...seen.schema };\n // defId won't be set if the schema is a reference to an external schema or if the schema is the root schema\n if (defId)\n seen.defId = defId;\n // wipe away all properties except $ref\n const schema = seen.schema;\n for (const key in schema) {\n delete schema[key];\n }\n schema.$ref = ref;\n };\n // throw on cycles\n // break cycles\n if (ctx.cycles === \"throw\") {\n for (const entry of ctx.seen.entries()) {\n const seen = entry[1];\n if (seen.cycle) {\n throw new Error(\"Cycle detected: \" +\n `#/${seen.cycle?.join(\"/\")}/<root>` +\n '\\n\\nSet the `cycles` parameter to `\"ref\"` to resolve cyclical schemas with defs.');\n }\n }\n }\n // extract schemas into $defs\n for (const entry of ctx.seen.entries()) {\n const seen = entry[1];\n // convert root schema to # $ref\n if (schema === entry[0]) {\n extractToDef(entry); // this has special handling for the root schema\n continue;\n }\n // extract schemas that are in the external registry\n if (ctx.external) {\n const ext = ctx.external.registry.get(entry[0])?.id;\n if (schema !== entry[0] && ext) {\n extractToDef(entry);\n continue;\n }\n }\n // extract schemas with `id` meta\n const id = ctx.metadataRegistry.get(entry[0])?.id;\n if (id) {\n extractToDef(entry);\n continue;\n }\n // break cycles\n if (seen.cycle) {\n // any\n extractToDef(entry);\n continue;\n }\n // extract reused schemas\n if (seen.count > 1) {\n if (ctx.reused === \"ref\") {\n extractToDef(entry);\n }\n }\n }\n if (ctx.external)\n ctx.sharedDefsExtractedFor = ctx.external;\n}\n/** Rewrites `anyOf: [{type: \"a\"}, {type: \"b\"}]` to `type: [\"a\", \"b\"]`, which every JSON Schema draft treats as equivalent and most consumers render far better for the nullable case. Only branches that are a bare type assertion qualify — anything carrying a constraint, `$ref`, `const` or metadata is left alone. Runs after `flattenRef`, so a branch an override decorated or `$defs` extraction turned into a `$ref` is no longer bare and correctly stays in `anyOf`. `oneOf` is excluded: `integer` and `number` overlap, so \"exactly one\" and \"at least one\" are not the same there. OpenAPI 3.0 is excluded: its `type` must be a single string. */\nfunction compactTypeUnion(schema) {\n const options = schema.anyOf;\n if (!Array.isArray(options) || options.length === 0 || schema.type !== undefined)\n return;\n const types = [];\n for (const option of options) {\n if (!option || typeof option !== \"object\")\n return;\n // A branch that is itself a compactible union folds into this one — nested `anyOf` and a flat `type` array say the same thing. Compacting it first also makes the result independent of the order this pass walks the seen map in.\n compactTypeUnion(option);\n const keys = Object.keys(option);\n if (keys.length !== 1 || keys[0] !== \"type\")\n return;\n const type = option.type;\n for (const member of Array.isArray(type) ? type : [type]) {\n if (typeof member !== \"string\")\n return;\n if (!types.includes(member))\n types.push(member);\n }\n }\n delete schema.anyOf;\n // A `type` array must be non-empty and unique (metaschema); a single member is spelled as a bare string.\n schema.type = types.length === 1 ? types[0] : types;\n}\n/** Keywords `foldIntersection` knows how to combine. Anything else — `$ref`, `patternProperties`,\n * an annotation like `description` — makes a member unfoldable, so a constraint this does not\n * understand leaves the `allOf` alone instead of being silently dropped or misattributed. */\nconst FOLDABLE_KEYS = new Set([\"type\", \"properties\", \"required\", \"additionalProperties\"]);\nconst UNION_KEYS = [\"oneOf\", \"anyOf\"];\n/** A member's constraint on a key it does not declare itself. A `catchall` states one; `false`, an absent `additionalProperties`, and the empty schema a loose object emits state nothing. */\nfunction undeclaredConstraint(member) {\n const extra = member.additionalProperties;\n if (extra === undefined || extra === false || typeof extra !== \"object\" || extra === null)\n return null;\n return Object.keys(extra).length ? extra : null;\n}\n/** Combines object members into the single object they describe together, or returns `null` if any of them carries a keyword outside {@link FOLDABLE_KEYS}. */\nfunction foldObjects(members) {\n const objects = [];\n for (const member of members) {\n // A boolean subschema is legal JSON Schema and carries no keywords to fold.\n if (typeof member !== \"object\" || member.type !== \"object\")\n return null;\n for (const key in member) {\n if (!FOLDABLE_KEYS.has(key))\n return null;\n }\n objects.push(member);\n }\n const properties = {};\n const required = new Set();\n for (const object of objects) {\n for (const key in object.properties) {\n // `in` would report a `__proto__` key as already present via the prototype chain and skip it.\n if (Object.prototype.hasOwnProperty.call(properties, key))\n continue;\n // Every member constrains this key: the ones that declare it say how, and a `catchall` member constrains it too even though it does not name it. The key has to satisfy all of them, which is the same intersection one level down.\n const parts = [];\n for (const other of objects) {\n const part = other.properties?.[key] ?? undeclaredConstraint(other);\n if (part === null || part === undefined)\n continue;\n if (!parts.some((seen) => JSON.stringify(seen) === JSON.stringify(part)))\n parts.push(part);\n }\n const merged = parts.length === 1\n ? parts[0]\n : (foldObjects(parts) ?? { allOf: parts });\n assignProp(properties, key, merged);\n }\n for (const key of object.required ?? [])\n required.add(key);\n }\n const folded = { type: \"object\", properties };\n if (required.size)\n folded.required = [...required];\n // A key no member declares is rejected only when every member rejects it, so the fold is closed only when every member is. Otherwise it carries whatever the `catchall` members demand of such a key.\n if (objects.every((object) => object.additionalProperties === false)) {\n folded.additionalProperties = false;\n }\n else {\n const constraints = [];\n for (const object of objects) {\n const constraint = undeclaredConstraint(object);\n if (constraint && !constraints.some((seen) => JSON.stringify(seen) === JSON.stringify(constraint)))\n constraints.push(constraint);\n }\n if (constraints.length === 1)\n folded.additionalProperties = constraints[0];\n else if (constraints.length > 1)\n folded.additionalProperties = { allOf: constraints };\n }\n return folded;\n}\n/** `additionalProperties` in an `allOf` member sees only that member's own `properties`, so two\n * closed object members reject each other's keys and the schema validates nothing. Zod's parser\n * pools the key sets instead — `handleIntersectionResults` reports a key as unrecognized only when\n * *every* side rejects it — so the emitted schema has to pool them too, and folding the members\n * into one object is the encoding that says so on every target.\n *\n * This runs from `finalize`, after `extractDefs`, which is what keeps it clear of the `$ref`\n * machinery: a member extracted into `$defs` is already a `$ref` by now and declines to fold, so it\n * keeps its reference and its own closedness rather than being inlined as a stale copy. */\nfunction foldIntersection(json) {\n const allOf = json.allOf;\n if (!Array.isArray(allOf) || allOf.length < 2)\n return;\n // An `override` runs before this pass and may have written object keywords onto the intersection itself. Those are deliberate, so decline rather than overwrite them.\n for (const key of FOLDABLE_KEYS)\n if (key in json)\n return;\n // An intersection distributes over a union: `A & (X | Y)` is `(A & X) | (A & Y)`. Only the first union is distributed over; a second one stays among the members every branch folds against, where it fails the object check and declines the whole intersection rather than multiplying out.\n const unions = allOf.filter((m) => UNION_KEYS.some((k) => Array.isArray(m[k])));\n let folded = null;\n if (!unions.length) {\n folded = foldObjects(allOf);\n }\n else {\n const union = unions[0];\n const keyword = UNION_KEYS.find((k) => Array.isArray(union[k]));\n if (Object.keys(union).length !== 1)\n return;\n const rest = allOf.filter((m) => m !== union);\n const branches = union[keyword].map((branch) => foldObjects([...rest, branch]));\n if (branches.some((b) => !b))\n return;\n folded = { [keyword]: branches };\n }\n if (!folded)\n return;\n delete json.allOf;\n assignProps(json, folded);\n}\nexport function finalize(ctx, schema) {\n const root = ctx.seen.get(schema);\n if (!root)\n throw new Error(\"Unprocessed schema. This is a bug in Zod.\");\n // flatten refs - inherit properties from parent schemas\n const flattenRef = (zodSchema) => {\n const seen = ctx.seen.get(zodSchema);\n // already processed\n if (seen.ref === null)\n return;\n const schema = seen.def ?? seen.schema;\n const _cached = { ...schema };\n const ref = seen.ref;\n seen.ref = null; // prevent infinite recursion\n if (ref) {\n flattenRef(ref);\n const refSeen = ctx.seen.get(ref);\n const refSchema = refSeen.schema;\n // merge referenced schema into current\n if (refSchema.$ref && (ctx.target === \"draft-07\" || ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\")) {\n // older drafts can't combine $ref with other properties\n schema.allOf = schema.allOf ?? [];\n schema.allOf.push(refSchema);\n }\n else {\n assignProps(schema, refSchema);\n }\n // restore child's own properties (child wins)\n assignProps(schema, _cached);\n const isParentRef = zodSchema._zod.parent === ref;\n // For parent chain, child is a refinement - remove parent-only properties\n if (isParentRef) {\n for (const key in schema) {\n if (key === \"$ref\" || key === \"allOf\")\n continue;\n if (!(key in _cached)) {\n delete schema[key];\n }\n }\n }\n // When ref was extracted to $defs, remove properties that match the definition\n if (refSchema.$ref && refSeen.def) {\n for (const key in schema) {\n if (key === \"$ref\" || key === \"allOf\")\n continue;\n if (key in refSeen.def && JSON.stringify(schema[key]) === JSON.stringify(refSeen.def[key])) {\n delete schema[key];\n }\n }\n }\n }\n // If parent was extracted (has $ref), propagate $ref to this schema. This handles cases like: readonly().meta({id}).describe() where processor sets ref to innerType but parent should be referenced\n const parent = zodSchema._zod.parent;\n if (parent && parent !== ref) {\n // Ensure parent is processed first so its def has inherited properties\n flattenRef(parent);\n const parentSeen = ctx.seen.get(parent);\n if (parentSeen?.schema.$ref) {\n schema.$ref = parentSeen.schema.$ref;\n // De-duplicate with parent's definition\n if (parentSeen.def) {\n for (const key in schema) {\n if (key === \"$ref\" || key === \"allOf\")\n continue;\n if (key in parentSeen.def && JSON.stringify(schema[key]) === JSON.stringify(parentSeen.def[key])) {\n delete schema[key];\n }\n }\n }\n }\n }\n // execute overrides\n ctx.override({\n zodSchema: zodSchema,\n jsonSchema: schema,\n path: seen.path ?? [],\n });\n };\n // Flattening walks the whole map and clears each `ref` as it goes, so a second call over the same map is a no-op scan. Skip it outright once it has run for a registry conversion.\n if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) {\n for (const entry of [...ctx.seen.entries()].reverse()) {\n flattenRef(entry[0]);\n }\n if (ctx.target !== \"openapi-3.0\") {\n for (const entry of ctx.seen.entries()) {\n compactTypeUnion(entry[1].def ?? entry[1].schema);\n }\n }\n for (const rewrite of ctx.deferred)\n rewrite();\n // After flattening, every member that was extracted is a `$ref`, so the fold sees the final shape. A schema that inherits an intersection — through `z.lazy`, or any `ref` chain — holds the same `allOf` array, so fold by array identity to catch every copy.\n if (ctx.intersections.length) {\n const carriers = new Map();\n for (const seen of ctx.seen.values()) {\n for (const json of [seen.schema, seen.def]) {\n const allOf = json?.allOf;\n if (!Array.isArray(allOf))\n continue;\n const existing = carriers.get(allOf);\n if (existing)\n existing.push(json);\n else\n carriers.set(allOf, [json]);\n }\n }\n for (const allOf of ctx.intersections) {\n for (const json of carriers.get(allOf) ?? [])\n foldIntersection(json);\n }\n }\n }\n const result = {};\n if (ctx.target === \"draft-2020-12\") {\n result.$schema = \"https://json-schema.org/draft/2020-12/schema\";\n }\n else if (ctx.target === \"draft-07\") {\n result.$schema = \"http://json-schema.org/draft-07/schema#\";\n }\n else if (ctx.target === \"draft-04\") {\n result.$schema = \"http://json-schema.org/draft-04/schema#\";\n }\n else if (ctx.target === \"openapi-3.0\") {\n // OpenAPI 3.0 schema objects should not include a $schema property\n }\n else {\n // Arbitrary string values are allowed but won't have a $schema property set\n }\n if (ctx.external?.uri) {\n const id = ctx.external.registry.get(schema)?.id;\n if (!id)\n throw new Error(\"Schema is missing an `id` property\");\n result.$id = ctx.external.uri(id);\n }\n // when the root was extracted into $defs, `root.schema` is the `$ref` wrapper and `root.def` is the body that now lives under $defs\n assignProps(result, root.defId ? root.schema : (root.def ?? root.schema));\n // The `id` in `.meta()` is a Zod-specific registration tag used to extract schemas into $defs — it is not user-facing JSON Schema metadata. Strip it from the output body where it would otherwise leak. The id is preserved implicitly via the $defs key (and via $ref paths).\n const rootMetaId = ctx.metadataRegistry.get(schema)?.id;\n if (rootMetaId !== undefined && result.id === rootMetaId)\n delete result.id;\n // build defs object. With `external`, `defs` is the shared object every schema writes into, so the same entries are reassigned on every call. Without it, `defs` is fresh per call and must be rebuilt.\n const defs = ctx.external?.defs ?? {};\n if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) {\n for (const entry of ctx.seen.entries()) {\n const seen = entry[1];\n if (seen.def && seen.defId) {\n if (seen.def.id === seen.defId)\n delete seen.def.id;\n assignProp(defs, seen.defId, seen.def);\n }\n }\n }\n if (ctx.external)\n ctx.sharedEmitDoneFor = ctx.external;\n // set definitions in result\n if (ctx.external) {\n }\n else {\n if (Object.keys(defs).length > 0) {\n if (ctx.target === \"draft-2020-12\") {\n result.$defs = defs;\n }\n else {\n result.definitions = defs;\n }\n }\n }\n try {\n // this \"finalizes\" this schema and ensures all cycles are removed each call to finalize() is functionally independent though the seen map is shared\n const finalized = JSON.parse(JSON.stringify(result));\n Object.defineProperty(finalized, \"~standard\", {\n value: {\n ...schema[\"~standard\"],\n jsonSchema: {\n input: createStandardJSONSchemaMethod(schema, \"input\", ctx.processors),\n output: createStandardJSONSchemaMethod(schema, \"output\", ctx.processors),\n },\n },\n enumerable: false,\n writable: false,\n });\n return finalized;\n }\n catch (_err) {\n throw new Error(\"Error converting schema to JSON.\");\n }\n}\nfunction isTransforming(_schema, _ctx) {\n const ctx = _ctx ?? { seen: new Set() };\n if (ctx.seen.has(_schema))\n return false;\n ctx.seen.add(_schema);\n const def = _schema._zod.def;\n if (def.type === \"transform\")\n return true;\n if (def.type === \"array\")\n return isTransforming(def.element, ctx);\n if (def.type === \"set\")\n return isTransforming(def.valueType, ctx);\n if (def.type === \"lazy\")\n return isTransforming(def.getter(), ctx);\n if (def.type === \"promise\" ||\n def.type === \"optional\" ||\n def.type === \"nonoptional\" ||\n def.type === \"nullable\" ||\n def.type === \"readonly\" ||\n def.type === \"default\" ||\n def.type === \"prefault\" ||\n def.type === \"catch\") {\n return isTransforming(def.innerType, ctx);\n }\n if (def.type === \"intersection\") {\n return isTransforming(def.left, ctx) || isTransforming(def.right, ctx);\n }\n if (def.type === \"record\" || def.type === \"map\") {\n return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx);\n }\n if (def.type === \"pipe\") {\n if (_schema._zod.traits.has(\"$ZodCodec\"))\n return true;\n return isTransforming(def.in, ctx) || isTransforming(def.out, ctx);\n }\n if (def.type === \"object\") {\n for (const key in def.shape) {\n if (isTransforming(def.shape[key], ctx))\n return true;\n }\n return false;\n }\n if (def.type === \"union\") {\n for (const option of def.options) {\n if (isTransforming(option, ctx))\n return true;\n }\n return false;\n }\n if (def.type === \"tuple\") {\n for (const item of def.items) {\n if (isTransforming(item, ctx))\n return true;\n }\n if (def.rest && isTransforming(def.rest, ctx))\n return true;\n return false;\n }\n return false;\n}\n/**\n * Creates a toJSONSchema method for a schema instance.\n * This encapsulates the logic of initializing context, processing, extracting defs, and finalizing.\n */\nexport const createToJSONSchemaMethod = (schema, processors = {}) => (params) => {\n const ctx = initializeContext({ ...params, processors });\n processSchema(schema, ctx);\n extractDefs(ctx, schema);\n return finalize(ctx, schema);\n};\nexport const createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => {\n const { libraryOptions, target } = params ?? {};\n const ctx = initializeContext({ ...(libraryOptions ?? {}), target, io, processors });\n processSchema(schema, ctx);\n extractDefs(ctx, schema);\n return finalize(ctx, schema);\n};\n","import * as regexes from \"./regexes.js\";\nimport { base64Charset, base64urlCharset } from \"./schemas.js\";\nimport { extractDefs, finalize, handleUnrepresentable, initializeContext, processSchema, } from \"./to-json-schema.js\";\nimport { BIGINT_FORMAT_RANGES, NUMBER_FORMAT_RANGES, assignProp, getEnumValues } from \"./util.js\";\nconst narrowMin = (agg, key, value) => {\n if (agg[key] === undefined || value > agg[key])\n agg[key] = value;\n};\nconst narrowMax = (agg, key, value) => {\n if (agg[key] === undefined || value < agg[key])\n agg[key] = value;\n};\nconst narrowBoth = (agg, value) => {\n narrowMin(agg, \"minimum\", value);\n narrowMax(agg, \"maximum\", value);\n};\nconst addDivisor = (agg, value) => {\n agg.multipleOf ?? (agg.multipleOf = []);\n if (!agg.multipleOf.includes(value))\n agg.multipleOf.push(value);\n};\nconst addPattern = (agg, pattern) => {\n agg.patterns ?? (agg.patterns = new Set());\n agg.patterns.add(pattern);\n};\nconst intersectMime = (agg, mime) => {\n agg.mime = agg.mime ? agg.mime.filter((m) => mime.includes(m)) : [...mime];\n};\n// last-wins, matching the bag's historical write order; the flag keeps an integer format from being lost to a later float one\nconst setFormat = (agg, format) => {\n agg.format = format;\n if (format.includes(\"int\"))\n agg.isInt = true;\n};\nconst minContributor = (agg, def) => narrowMin(agg, \"minimum\", def.minimum);\nconst maxContributor = (agg, def) => narrowMax(agg, \"maximum\", def.maximum);\nconst formatContributor = (ranges) => (agg, def) => {\n setFormat(agg, def.format);\n const [minimum, maximum] = ranges[def.format];\n narrowMin(agg, \"minimum\", minimum);\n narrowMax(agg, \"maximum\", maximum);\n};\nconst contributors = {\n greater_than: (agg, def) => narrowMin(agg, def.inclusive ? \"minimum\" : \"exclusiveMinimum\", def.value),\n less_than: (agg, def) => narrowMax(agg, def.inclusive ? \"maximum\" : \"exclusiveMaximum\", def.value),\n multiple_of: (agg, def) => addDivisor(agg, def.value),\n number_format: formatContributor(NUMBER_FORMAT_RANGES),\n bigint_format: formatContributor(BIGINT_FORMAT_RANGES),\n min_length: minContributor,\n max_length: maxContributor,\n length_equals: (agg, def) => narrowBoth(agg, def.length),\n min_size: minContributor,\n max_size: maxContributor,\n size_equals: (agg, def) => narrowBoth(agg, def.size),\n string_format: (agg, def) => {\n setFormat(agg, def.format);\n if (def.pattern)\n addPattern(agg, def.pattern);\n if (def.format === \"base64\" || def.format === \"base64url\")\n agg.contentEncoding = def.format;\n if (def.local || def.precision === -1)\n agg.laxFormat = true;\n },\n mime_type: (agg, def) => intersectMime(agg, def.mime),\n};\nexport function aggregateChecks(schema) {\n const agg = {};\n const def = schema._zod.def;\n // a format schema is its own first check, same rule as $ZodType init\n const list = schema._zod.traits.has(\"$ZodCheck\")\n ? [schema, ...(def.checks ?? [])]\n : (def.checks ?? []);\n for (const ch of list)\n contributors[ch._zod.def.check]?.(agg, ch._zod.def);\n // reconcile with the bag so third-party onattach contributions still land; first-party residue is never tighter than the fold, so merging it back is idempotent for one and additive for the other\n const bag = schema._zod.bag;\n if (bag.minimum !== undefined)\n narrowMin(agg, \"minimum\", bag.minimum);\n if (bag.exclusiveMinimum !== undefined)\n narrowMin(agg, \"exclusiveMinimum\", bag.exclusiveMinimum);\n if (bag.maximum !== undefined)\n narrowMax(agg, \"maximum\", bag.maximum);\n if (bag.exclusiveMaximum !== undefined)\n narrowMax(agg, \"exclusiveMaximum\", bag.exclusiveMaximum);\n if (bag.multipleOf !== undefined)\n addDivisor(agg, bag.multipleOf);\n if (bag.format !== undefined) {\n agg.format ?? (agg.format = bag.format);\n if (bag.format.includes(\"int\"))\n agg.isInt = true;\n }\n if (bag.mime)\n intersectMime(agg, bag.mime);\n for (const pattern of bag.patterns ?? [])\n addPattern(agg, pattern);\n return agg;\n}\nconst formatMap = {\n guid: \"uuid\",\n url: \"uri\",\n datetime: \"date-time\",\n json_string: \"json-string\",\n regex: \"\", // do not set\n};\n// ==================== SIMPLE TYPE PROCESSORS ====================\n// the runtime patterns are lax so parse paths never overflow the regex stack; the emitted schema swaps in the exact block forms, which zod itself never executes\nconst exactPatterns = new Map([\n [base64Charset, regexes.base64],\n [base64urlCharset, regexes.base64url],\n]);\nconst exactPattern = (p) => exactPatterns.get(p) ?? p;\nexport const stringProcessor = (schema, ctx, _json, _params) => {\n const json = _json;\n json.type = \"string\";\n const { minimum, maximum, format, patterns, contentEncoding, laxFormat } = aggregateChecks(schema);\n if (typeof minimum === \"number\")\n json.minLength = minimum;\n if (typeof maximum === \"number\")\n json.maxLength = maximum;\n // custom pattern overrides format\n if (format) {\n json.format = formatMap[format] ?? format;\n if (json.format === \"\")\n delete json.format; // empty format is not valid\n // `z.iso.time()` is never full-time, and `laxFormat` carries the datetime shapes that also accept what their keyword forbids\n if (format === \"time\" || laxFormat) {\n delete json.format;\n }\n }\n if (contentEncoding)\n json.contentEncoding = contentEncoding;\n if (patterns && patterns.size > 0) {\n const patternList = [...patterns].map(exactPattern);\n if (patternList.length === 1)\n json.pattern = patternList[0].source;\n else if (patternList.length > 1) {\n json.allOf = [\n ...patternList.map((regex) => ({\n ...(ctx.target === \"draft-07\" || ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\"\n ? { type: \"string\" }\n : {}),\n pattern: regex.source,\n })),\n ];\n }\n }\n};\nexport const numberProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const { minimum, maximum, multipleOf, exclusiveMaximum, exclusiveMinimum, isInt } = aggregateChecks(schema);\n json.type = isInt ? \"integer\" : \"number\";\n // when both minimum and exclusiveMinimum exist, pick the more restrictive one\n const exMin = typeof exclusiveMinimum === \"number\" && exclusiveMinimum >= (minimum ?? Number.NEGATIVE_INFINITY);\n const exMax = typeof exclusiveMaximum === \"number\" && exclusiveMaximum <= (maximum ?? Number.POSITIVE_INFINITY);\n const legacy = ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\";\n if (exMin) {\n if (legacy) {\n json.minimum = exclusiveMinimum;\n json.exclusiveMinimum = true;\n }\n else {\n json.exclusiveMinimum = exclusiveMinimum;\n }\n }\n else if (typeof minimum === \"number\") {\n json.minimum = minimum;\n }\n if (exMax) {\n if (legacy) {\n json.maximum = exclusiveMaximum;\n json.exclusiveMaximum = true;\n }\n else {\n json.exclusiveMaximum = exclusiveMaximum;\n }\n }\n else if (typeof maximum === \"number\") {\n json.maximum = maximum;\n }\n if (multipleOf) {\n // JSON Schema requires a divisor strictly greater than zero, and a non-finite one does not survive JSON at all. A negative divisor accepts exactly what its absolute value accepts, so it still maps; zero, NaN and Infinity have no keyword form.\n const divisors = new Set();\n for (const divisor of multipleOf) {\n if (Number.isFinite(divisor) && divisor !== 0)\n divisors.add(Math.abs(divisor));\n else\n handleUnrepresentable(schema, ctx, json, params, `A multipleOf divisor of ${divisor} cannot be represented in JSON Schema`);\n }\n // chained divisors are a conjunction the keyword cannot carry alone, so extras ride an allOf, same as stacked patterns\n const [first, ...rest] = divisors;\n if (first !== undefined)\n json.multipleOf = first;\n if (rest.length)\n json.allOf = [...(json.allOf ?? []), ...rest.map((m) => ({ multipleOf: m }))];\n }\n};\nexport const booleanProcessor = (_schema, _ctx, json, _params) => {\n json.type = \"boolean\";\n};\nexport const bigintProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"BigInt cannot be represented in JSON Schema\");\n};\nexport const symbolProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Symbols cannot be represented in JSON Schema\");\n};\nexport const nullProcessor = (_schema, ctx, json, _params) => {\n if (ctx.target === \"openapi-3.0\") {\n json.type = \"string\";\n json.nullable = true;\n json.enum = [null];\n }\n else {\n json.type = \"null\";\n }\n};\nexport const undefinedProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Undefined cannot be represented in JSON Schema\");\n};\nexport const voidProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Void cannot be represented in JSON Schema\");\n};\nexport const neverProcessor = (_schema, _ctx, json, _params) => {\n json.not = {};\n};\nexport const anyProcessor = (_schema, _ctx, _json, _params) => {\n // empty schema accepts anything\n};\nexport const unknownProcessor = (_schema, _ctx, _json, _params) => {\n // empty schema accepts anything\n};\nexport const dateProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Date cannot be represented in JSON Schema\");\n};\nexport const enumProcessor = (schema, _ctx, json, _params) => {\n const def = schema._zod.def;\n const values = getEnumValues(def.entries);\n // an empty enum accepts nothing, same as z.never()\n if (values.length === 0) {\n json.not = {};\n return;\n }\n // Number enums can have both string and number values\n if (values.every((v) => typeof v === \"number\"))\n json.type = \"number\";\n if (values.every((v) => typeof v === \"string\"))\n json.type = \"string\";\n json.enum = values;\n};\nexport const literalProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n // a literal with no values accepts nothing, same as z.never()\n if (def.values.length === 0) {\n json.not = {};\n return;\n }\n const vals = [];\n for (const val of def.values) {\n if (val === undefined) {\n // a custom schema replaces the whole literal, so there is nothing left to accumulate\n if (handleUnrepresentable(schema, ctx, json, params, \"Literal `undefined` cannot be represented in JSON Schema\"))\n return;\n // otherwise do not add to vals\n }\n else if (typeof val === \"bigint\") {\n if (handleUnrepresentable(schema, ctx, json, params, \"BigInt literals cannot be represented in JSON Schema\"))\n return;\n vals.push(Number(val));\n }\n else {\n vals.push(val);\n }\n }\n if (vals.length === 0) {\n // do nothing (an undefined literal was stripped)\n }\n else if (vals.length === 1) {\n const val = vals[0];\n json.type = val === null ? \"null\" : typeof val;\n if (ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\") {\n json.enum = [val];\n }\n else {\n json.const = val;\n }\n }\n else {\n if (vals.every((v) => typeof v === \"number\"))\n json.type = \"number\";\n if (vals.every((v) => typeof v === \"string\"))\n json.type = \"string\";\n if (vals.every((v) => typeof v === \"boolean\"))\n json.type = \"boolean\";\n if (vals.every((v) => v === null))\n json.type = \"null\";\n json.enum = vals;\n }\n};\nexport const nanProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"NaN cannot be represented in JSON Schema\");\n};\nexport const templateLiteralProcessor = (schema, _ctx, json, _params) => {\n const _json = json;\n const pattern = schema._zod.pattern;\n if (!pattern)\n throw new Error(\"Pattern not found in template literal\");\n _json.type = \"string\";\n _json.pattern = pattern.source;\n};\nexport const fileProcessor = (schema, _ctx, json, _params) => {\n const _json = json;\n _json.type = \"string\";\n _json.format = \"binary\";\n _json.contentEncoding = \"binary\";\n const { minimum, maximum, mime } = aggregateChecks(schema);\n if (minimum !== undefined)\n _json.minLength = minimum;\n if (maximum !== undefined)\n _json.maxLength = maximum;\n if (!mime)\n return;\n // an empty intersection means the mime checks share no value, so nothing passes at runtime; `anyOf` must be non-empty, so the false schema is `not: {}`\n if (mime.length === 0)\n _json.not = {};\n else if (mime.length === 1)\n _json.contentMediaType = mime[0];\n // only contentMediaType differs, so the shared props stay at the root\n else\n _json.anyOf = mime.map((m) => ({ contentMediaType: m }));\n};\nexport const successProcessor = (_schema, _ctx, json, _params) => {\n json.type = \"boolean\";\n};\nexport const customProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Custom types cannot be represented in JSON Schema\");\n};\nexport const functionProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Function types cannot be represented in JSON Schema\");\n};\nexport const transformProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Transforms cannot be represented in JSON Schema\");\n};\nexport const mapProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Map cannot be represented in JSON Schema\");\n};\nexport const setProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Set cannot be represented in JSON Schema\");\n};\n// ==================== COMPOSITE TYPE PROCESSORS ====================\nexport const arrayProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n const { minimum, maximum } = aggregateChecks(schema);\n if (typeof minimum === \"number\")\n json.minItems = minimum;\n if (typeof maximum === \"number\")\n json.maxItems = maximum;\n json.type = \"array\";\n json.items = processSchema(def.element, ctx, {\n ...params,\n path: [...params.path, \"items\"],\n });\n};\n// Transform and catch set `optin = \"optional\"` at runtime so the parser lets them observe an\n// absent key, but their declared input type stays required. An input JSON Schema describes the\n// declared type, so resolve past them to the schema that actually carries the optionality.\n// Used by both `objectProcessor` (for `required`) and `tupleProcessor` (for `minItems`); see\n// wiki/optionality.md, \"The JSON Schema emitter reads the *static* value\".\nfunction inputOptin(schema) {\n const def = schema._zod.def;\n if (def.type === \"pipe\" && def.in._zod.traits.has(\"$ZodTransform\")) {\n return inputOptin(def.out);\n }\n if (def.type === \"catch\") {\n return inputOptin(def.innerType);\n }\n return schema._zod.optin;\n}\nexport const objectProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n const shape = def.shape;\n // dropping it while still emitting `additionalProperties: false` would emit a schema that rejects data this one requires\n const symbolKeys = Object.getOwnPropertySymbols(shape);\n if (symbolKeys.length &&\n handleUnrepresentable(schema, ctx, json, params, \"Symbol keys cannot be represented in JSON Schema\")) {\n return;\n }\n json.type = \"object\";\n json.properties = {};\n for (const key in shape) {\n // assignProp so a __proto__ key becomes an own property instead of hitting the inherited setter on the plain {} we build into\n assignProp(json.properties, key, processSchema(shape[key], ctx, {\n ...params,\n path: [...params.path, \"properties\", key],\n }));\n }\n // required keys\n const requiredKeys = [];\n for (const key of Object.keys(shape)) {\n const field = def.shape[key];\n if (ctx.io === \"input\" ? inputOptin(field) === undefined : field._zod.optout === undefined) {\n requiredKeys.push(key);\n }\n }\n if (requiredKeys.length > 0) {\n json.required = requiredKeys;\n }\n // catchall\n if (def.catchall?._zod.def.type === \"never\") {\n // strict\n json.additionalProperties = false;\n }\n else if (!def.catchall) {\n // regular\n if (ctx.io === \"output\")\n json.additionalProperties = false;\n }\n else if (def.catchall) {\n json.additionalProperties = processSchema(def.catchall, ctx, {\n ...params,\n path: [...params.path, \"additionalProperties\"],\n });\n }\n};\nexport const unionProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n // Exclusive unions (inclusive === false) use oneOf (exactly one match) instead of anyOf (one or more matches). This includes both z.xor() and discriminated unions\n const isExclusive = def.inclusive === false;\n const options = def.options.map((x, i) => processSchema(x, ctx, {\n ...params,\n path: [...params.path, isExclusive ? \"oneOf\" : \"anyOf\", i],\n }));\n if (isExclusive) {\n json.oneOf = options;\n }\n else {\n json.anyOf = options;\n }\n};\nexport const intersectionProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n const a = processSchema(def.left, ctx, {\n ...params,\n path: [...params.path, \"allOf\", 0],\n });\n const b = processSchema(def.right, ctx, {\n ...params,\n path: [...params.path, \"allOf\", 1],\n });\n const isSimpleIntersection = (val) => \"allOf\" in val && Object.keys(val).length === 1;\n const allOf = [\n ...(isSimpleIntersection(a) ? a.allOf : [a]),\n ...(isSimpleIntersection(b) ? b.allOf : [b]),\n ];\n json.allOf = allOf;\n // Recorded innermost first, so a nested intersection has already folded by the time this one is considered. The array is the handle rather than the schema, because a wrapper that inherits this schema shares the same array; `finalize` folds every object holding it. See `foldIntersection`.\n ctx.intersections.push(allOf);\n};\nexport const tupleProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n json.type = \"array\";\n const prefixPath = ctx.target === \"draft-2020-12\" ? \"prefixItems\" : \"items\";\n const restPath = ctx.target === \"draft-2020-12\" ? \"items\" : ctx.target === \"openapi-3.0\" ? \"items\" : \"additionalItems\";\n const prefixItems = def.items.map((x, i) => processSchema(x, ctx, {\n ...params,\n path: [...params.path, prefixPath, i],\n }));\n const rest = def.rest\n ? processSchema(def.rest, ctx, {\n ...params,\n path: [...params.path, restPath, ...(ctx.target === \"openapi-3.0\" ? [def.items.length] : [])],\n })\n : null;\n let minItems = def.items.length;\n while (minItems > 0) {\n const item = def.items[minItems - 1];\n const optional = ctx.io === \"input\" ? inputOptin(item) !== undefined : item._zod.optout === \"optional\";\n if (!optional)\n break;\n minItems--;\n }\n const maxItems = def.items.length;\n const isClosed = !def.rest;\n if (ctx.target === \"draft-2020-12\") {\n json.prefixItems = prefixItems;\n if (isClosed) {\n json.items = false;\n }\n else if (rest) {\n json.items = rest;\n }\n if (minItems > 0)\n json.minItems = minItems;\n if (isClosed)\n json.maxItems = maxItems;\n }\n else if (ctx.target === \"openapi-3.0\") {\n json.items = {\n anyOf: prefixItems,\n };\n if (rest) {\n json.items.anyOf.push(rest);\n }\n if (minItems > 0)\n json.minItems = minItems;\n if (isClosed)\n json.maxItems = maxItems;\n }\n else {\n json.items = prefixItems;\n if (isClosed) {\n json.additionalItems = false;\n }\n else if (rest) {\n json.additionalItems = rest;\n }\n if (minItems > 0)\n json.minItems = minItems;\n if (isClosed)\n json.maxItems = maxItems;\n }\n // explicit user-defined length checks take precedence\n const { minimum, maximum } = aggregateChecks(schema);\n if (typeof minimum === \"number\")\n json.minItems = minimum;\n if (typeof maximum === \"number\")\n json.maxItems = maximum;\n};\n/** JSON object keys are always strings, so a numeric record key schema is re-expressed over the\n * numeric-string form the record parser matches. Deferred to `finalize`, after the flatten: a key\n * behind a wrapper only carries its own `type` before then, and a union key only has its branches.\n *\n * A numeric bound cannot apply to a property name, so `minimum` and its siblings are dropped rather\n * than carried over: keeping them beside `type: \"string\"` reproduces the match-nothing schema this\n * exists to fix. A key that carries one therefore emits wider than the record parses — `z.record(z.number().min(5), V)`\n * accepts `\"3\"` — which is the deliberate trade, since throwing on it would reject an ordinary schema\n * outright. */\nfunction stringifyKeyNames(bySchema, json, visited) {\n // an extracted key that rewrites cannot go on sharing its definition — the string form a key position needs is not the number form every other reference wants — so it inlines. One that does not rewrite keeps the `$ref`.\n if (json.$ref) {\n // a recursive key holds its own reference inside its definition, so a node already on the path is left alone rather than resolved again\n if (visited.has(json))\n return json;\n visited.add(json);\n const def = bySchema.get(json)?.def;\n if (!def)\n return json;\n const inlined = stringifyKeyNames(bySchema, def, visited);\n return inlined === def ? json : inlined;\n }\n for (const keyword of [\"anyOf\", \"oneOf\"]) {\n const branches = json[keyword];\n if (!Array.isArray(branches))\n continue;\n const mapped = branches.map((branch) => stringifyKeyNames(bySchema, branch, visited));\n // rebuilding regardless would detach a key that had nothing to re-express, dropping its `$ref` and leaking the internal `id`\n if (mapped.some((branch, i) => branch !== branches[i]))\n json = { ...json, [keyword]: mapped };\n }\n // a member that already admits a string leaves the key unconstrained, so the node's own type re-expresses only when every member is numeric\n const types = Array.isArray(json.type) ? json.type : [json.type];\n const numericType = !types.includes(\"string\") && types.some((t) => t === \"number\" || t === \"integer\");\n // a heterogeneous key carries no type at all, so its numeric members are caught here instead\n const values = json.enum ?? (json.const !== undefined ? [json.const] : undefined);\n if (!numericType && !values?.some((v) => typeof v === \"number\"))\n return json;\n const { minimum, maximum, exclusiveMinimum, exclusiveMaximum, multipleOf, format, id, ...rest } = json;\n if (rest.enum)\n rest.enum = rest.enum.map((v) => (typeof v === \"number\" ? String(v) : v));\n else if (typeof rest.const === \"number\")\n rest.const = String(rest.const);\n // a heterogeneous key keeps its absent type: the stringified members already say what a key may be\n if (!numericType)\n return rest;\n rest.type = \"string\";\n if (!values)\n rest.pattern = (types.includes(\"number\") ? regexes.number : regexes.integer).source;\n return rest;\n}\n/** Every record of one conversion, so the carriers are found in a single pass rather than once per record. */\nconst pendingRecords = new WeakMap();\nfunction rewriteKeyNames(ctx) {\n // an extracted key is resolved by the object `extractToDef` left in its place, so the map is built once rather than searched per reference. `_zod.toJSONSchema` can hand the same object to two schemas, so the first entry carrying a body wins, as a search would have found it.\n const bySchema = new Map();\n for (const entry of ctx.seen.values()) {\n if (entry.def && !bySchema.has(entry.schema))\n bySchema.set(entry.schema, entry);\n }\n const rewrites = new Map();\n for (const record of pendingRecords.get(ctx) ?? []) {\n const seen = ctx.seen.get(record);\n const names = (seen?.def ?? seen?.schema)?.propertyNames;\n if (!names || names === true || rewrites.has(names))\n continue;\n const rewritten = stringifyKeyNames(bySchema, names, new Set());\n if (rewritten !== names)\n rewrites.set(names, rewritten);\n }\n if (!rewrites.size)\n return;\n // the flatten has already copied each record's own properties onto every wrapper by reference, and an extracted body is another such copy, so every carrier holding a rewritten key is updated together\n for (const entry of ctx.seen.values()) {\n for (const carrier of [entry.schema, entry.def]) {\n const rewritten = carrier && rewrites.get(carrier.propertyNames);\n if (rewritten)\n carrier.propertyNames = rewritten;\n }\n }\n}\nexport const recordProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n json.type = \"object\";\n // For looseRecord with regex patterns, use patternProperties. This correctly represents \"only validate keys matching the pattern\" semantics and composes well with allOf (intersections)\n const keyType = def.keyType;\n const patterns = aggregateChecks(keyType).patterns;\n if (def.mode === \"loose\" && patterns && patterns.size > 0) {\n // Use patternProperties for looseRecord with regex patterns\n const valueSchema = processSchema(def.valueType, ctx, {\n ...params,\n path: [...params.path, \"patternProperties\", \"*\"],\n });\n json.patternProperties = {};\n for (const pattern of patterns) {\n assignProp(json.patternProperties, exactPattern(pattern).source, valueSchema);\n }\n }\n else {\n // Default behavior: use propertyNames + additionalProperties\n if (ctx.target === \"draft-07\" || ctx.target === \"draft-2020-12\") {\n json.propertyNames = processSchema(def.keyType, ctx, {\n ...params,\n path: [...params.path, \"propertyNames\"],\n });\n let pending = pendingRecords.get(ctx);\n if (!pending) {\n pending = [];\n pendingRecords.set(ctx, pending);\n ctx.deferred.push(() => rewriteKeyNames(ctx));\n }\n pending.push(schema);\n }\n json.additionalProperties = processSchema(def.valueType, ctx, {\n ...params,\n path: [...params.path, \"additionalProperties\"],\n });\n }\n // Add required for keys with discrete values (enum, literal, etc.)\n const keyValues = keyType._zod.values;\n // Every key shares one value schema, so an optional-in value makes the whole key set omittable on input. Output keeps them: the exhaustive branch assigns every key, even one whose value came back undefined.\n const omittableOnInput = ctx.io === \"input\" && inputOptin(def.valueType) !== undefined;\n if (keyValues && !def.partial && !omittableOnInput) {\n const validKeyValues = [...keyValues].filter((v) => typeof v === \"string\" || typeof v === \"number\");\n if (validKeyValues.length > 0) {\n json.required = validKeyValues.map(String);\n }\n }\n};\nexport const nullableProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n const inner = processSchema(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n if (ctx.target === \"openapi-3.0\") {\n seen.ref = def.innerType;\n json.nullable = true;\n }\n else {\n json.anyOf = [inner, { type: \"null\" }];\n }\n};\nexport const nonoptionalProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n processSchema(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n};\n/** Round-trips a default value through JSON so the emitted schema is guaranteed to be valid JSON.\n * A BigInt has no reliable encoding, so it goes through `unrepresentable` like any other\n * unrepresentable value. Returns a sentinel when the caller must not write a default of its own. */\nconst UNREPRESENTABLE_DEFAULT = Symbol();\nfunction serializeDefaultValue(value, schema, ctx, json, params) {\n let unrepresentable = false;\n const serialized = JSON.stringify(value, (_, val) => {\n if (typeof val !== \"bigint\")\n return val;\n unrepresentable = true;\n return null;\n });\n if (!unrepresentable)\n return JSON.parse(serialized);\n handleUnrepresentable(schema, ctx, json, params, \"BigInt defaults cannot be represented in JSON Schema\");\n return UNREPRESENTABLE_DEFAULT;\n}\nexport const defaultProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n processSchema(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n const value = serializeDefaultValue(def.defaultValue, schema, ctx, json, params);\n if (value !== UNREPRESENTABLE_DEFAULT)\n json.default = value;\n};\nexport const prefaultProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n processSchema(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n if (ctx.io !== \"input\")\n return;\n const value = serializeDefaultValue(def.defaultValue, schema, ctx, json, params);\n if (value !== UNREPRESENTABLE_DEFAULT)\n json._prefault = value;\n};\nexport const catchProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n processSchema(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n let catchValue;\n try {\n catchValue = def.catchValue(undefined);\n }\n catch {\n handleUnrepresentable(schema, ctx, json, params, \"Dynamic catch values are not supported in JSON Schema\");\n return;\n }\n json.default = catchValue;\n};\nexport const pipeProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n const inIsTransform = def.in._zod.traits.has(\"$ZodTransform\");\n const innerType = ctx.io === \"input\" ? (inIsTransform ? def.out : def.in) : def.out;\n processSchema(innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = innerType;\n};\nexport const readonlyProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n processSchema(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n json.readOnly = true;\n};\nexport const promiseProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n processSchema(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n};\nexport const optionalProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n processSchema(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n};\nexport const lazyProcessor = (schema, ctx, _json, params) => {\n const innerType = schema._zod.innerType;\n processSchema(innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = innerType;\n};\n// ==================== ALL PROCESSORS ====================\nexport const allProcessors = {\n string: stringProcessor,\n number: numberProcessor,\n boolean: booleanProcessor,\n bigint: bigintProcessor,\n symbol: symbolProcessor,\n null: nullProcessor,\n undefined: undefinedProcessor,\n void: voidProcessor,\n never: neverProcessor,\n any: anyProcessor,\n unknown: unknownProcessor,\n date: dateProcessor,\n enum: enumProcessor,\n literal: literalProcessor,\n nan: nanProcessor,\n template_literal: templateLiteralProcessor,\n file: fileProcessor,\n success: successProcessor,\n custom: customProcessor,\n function: functionProcessor,\n transform: transformProcessor,\n map: mapProcessor,\n set: setProcessor,\n array: arrayProcessor,\n object: objectProcessor,\n union: unionProcessor,\n intersection: intersectionProcessor,\n tuple: tupleProcessor,\n record: recordProcessor,\n nullable: nullableProcessor,\n nonoptional: nonoptionalProcessor,\n default: defaultProcessor,\n prefault: prefaultProcessor,\n catch: catchProcessor,\n pipe: pipeProcessor,\n readonly: readonlyProcessor,\n promise: promiseProcessor,\n optional: optionalProcessor,\n lazy: lazyProcessor,\n};\nexport function toJSONSchema(input, params) {\n if (\"_idmap\" in input) {\n // Registry case\n const registry = input;\n const ctx = initializeContext({ ...params, processors: allProcessors });\n const defs = {};\n // First pass: process all schemas to build the seen map\n for (const entry of registry._idmap.entries()) {\n const [_, schema] = entry;\n processSchema(schema, ctx);\n }\n const schemas = {};\n const external = {\n registry,\n uri: params?.uri,\n defs,\n };\n // Update the context with external configuration\n ctx.external = external;\n // Second pass: emit each schema\n for (const entry of registry._idmap.entries()) {\n const [key, schema] = entry;\n extractDefs(ctx, schema);\n assignProp(schemas, key, finalize(ctx, schema));\n }\n if (Object.keys(defs).length > 0) {\n const defsSegment = ctx.target === \"draft-2020-12\" ? \"$defs\" : \"definitions\";\n schemas.__shared = {\n [defsSegment]: defs,\n };\n }\n return { schemas };\n }\n // Single schema case\n const ctx = initializeContext({ ...params, processors: allProcessors });\n processSchema(input, ctx);\n extractDefs(ctx, input);\n return finalize(ctx, input);\n}\n","import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"characters\", verb: \"to have\" },\n file: { unit: \"bytes\", verb: \"to have\" },\n array: { unit: \"items\", verb: \"to have\" },\n set: { unit: \"items\", verb: \"to have\" },\n map: { unit: \"entries\", verb: \"to have\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"input\",\n email: \"email address\",\n url: \"URL\",\n emoji: \"emoji\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"ISO datetime\",\n date: \"ISO date\",\n time: \"ISO time\",\n duration: \"ISO duration\",\n ipv4: \"IPv4 address\",\n ipv6: \"IPv6 address\",\n mac: \"MAC address\",\n cidrv4: \"IPv4 range\",\n cidrv6: \"IPv6 range\",\n base64: \"base64-encoded string\",\n base64url: \"base64url-encoded string\",\n json_string: \"JSON string\",\n e164: \"E.164 number\",\n currency_code: \"currency code\",\n credit_card: \"credit card number\",\n iban: \"IBAN\",\n jwt: \"JWT\",\n template_literal: \"input\",\n };\n // type names: missing keys = do not translate (use raw value via ?? fallback)\n const TypeDictionary = {\n // Compatibility: \"nan\" -> \"NaN\" for display\n nan: \"NaN\",\n // All other type names omitted - they fall back to raw values via ?? operator\n };\n function getTypeName(type, input) {\n if (type === \"number\" && typeof input === \"number\" && !Number.isFinite(input)) {\n return String(input);\n }\n return TypeDictionary[type] ?? type;\n }\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = getTypeName(issue.expected);\n const receivedType = util.parsedType(issue.input);\n const received = getTypeName(receivedType, issue.input);\n return `Invalid input: expected ${expected}, received ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `Invalid input: expected ${util.stringifyPrimitive(issue.values[0])}`;\n return `Invalid option: expected one of ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.exact ? \"exactly \" : issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `Too big: expected ${issue.origin ?? \"value\"} to have ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"elements\"}`;\n return `Too big: expected ${issue.origin ?? \"value\"} to be ${adj}${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.exact ? \"exactly \" : issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `Too small: expected ${issue.origin} to have ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n }\n return `Too small: expected ${issue.origin} to be ${adj}${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\") {\n return `Invalid string: must start with \"${_issue.prefix}\"`;\n }\n if (_issue.format === \"ends_with\")\n return `Invalid string: must end with \"${_issue.suffix}\"`;\n if (_issue.format === \"includes\")\n return `Invalid string: must include \"${_issue.includes}\"`;\n if (_issue.format === \"regex\")\n return `Invalid string: must match pattern ${_issue.pattern}`;\n return `Invalid ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `Invalid number: must be a multiple of ${issue.divisor}`;\n case \"unrecognized_keys\":\n return `Unrecognized key${issue.keys.length > 1 ? \"s\" : \"\"}: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `Invalid key in ${issue.origin}`;\n case \"invalid_union\":\n if (issue.options && Array.isArray(issue.options) && issue.options.length > 0) {\n const opts = issue.options.map((o) => `'${o}'`).join(\" | \");\n return `Invalid discriminator value. Expected ${opts}`;\n }\n if (issue.inclusive === false) {\n return \"Invalid input: more than one option matched\";\n }\n return \"Invalid input\";\n case \"invalid_element\":\n return `Invalid value in ${issue.origin}`;\n default:\n return `Invalid input`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n","import { $constructor } from \"./core.js\";\nimport * as util from \"./util.js\";\n/* Computing the message eagerly is expensive (pretty-printed JSON of all\n * issues), so defer it until first read. The accessor functions and\n * descriptors are shared across instances to keep error construction\n * cheap; the computed message is cached on the internals object. The\n * setter preserves plain assignment semantics for consumers that\n * overwrite `message`. */\nfunction _getMessage() {\n const internals = this._zod;\n internals.message ?? (internals.message = JSON.stringify(internals.def, util.jsonStringifyReplacer, 2));\n return internals.message;\n}\nfunction _setMessage(value) {\n this._zod.message = value;\n}\nconst _messageDesc = {\n get: _getMessage,\n set: _setMessage,\n enumerable: true,\n configurable: true,\n};\nconst _issuesDesc = { value: undefined, enumerable: false };\n/* Prototypes that already carry the lazy `toString`. Seeded with the\n * intrinsics so that `init` on a foreign object — it accepts any object —\n * can never install an accessor onto a prototype we do not own. */\nconst _installedToString = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]);\nconst initializer = (inst, def) => {\n inst.name = \"$ZodError\";\n // `_zod` is already non-enumerable: $constructor's init defined it with this same descriptor\n _issuesDesc.value = def;\n Object.defineProperty(inst, \"issues\", _issuesDesc);\n // Clear the shared slot; a retained `value` pins the last error's issues.\n _issuesDesc.value = undefined;\n Object.defineProperty(inst, \"message\", _messageDesc);\n /* `toString` lives as a non-enumerable lazy getter on the shared\n * prototype; on first access it caches a per-instance closure so\n * detached usage still works. */\n const proto = Object.getPrototypeOf(inst);\n if (!_installedToString.has(proto)) {\n _installedToString.add(proto);\n Object.defineProperty(proto, \"toString\", {\n configurable: true,\n enumerable: false,\n get() {\n const value = () => this.message;\n Object.defineProperty(this, \"toString\", { value, configurable: true, writable: true });\n return value;\n },\n set(value) {\n Object.defineProperty(this, \"toString\", { value, configurable: true, writable: true });\n },\n });\n }\n};\nexport const $ZodError = $constructor(\"$ZodError\", initializer);\nexport const $ZodRealError = $constructor(\"$ZodError\", initializer, undefined, {\n Parent: Error,\n});\n/** Get-or-create `obj[key]` as an own data property. A path segment naming an inherited member\n * (\"toString\", \"constructor\") would otherwise read through to the prototype, and assigning\n * \"__proto__\" would hit the setter instead of creating a key. */\nfunction node(obj, key, make) {\n if (!Object.prototype.hasOwnProperty.call(obj, key)) {\n if (key === \"__proto__\") {\n Object.defineProperty(obj, key, { value: make(), writable: true, enumerable: true, configurable: true });\n }\n else {\n obj[key] = make();\n }\n }\n return obj[key];\n}\nexport function flattenError(error, mapper = (issue) => issue.message) {\n const fieldErrors = {};\n const formErrors = [];\n for (const sub of error.issues) {\n if (sub.path.length > 0) {\n node(fieldErrors, sub.path[0], () => []).push(mapper(sub));\n }\n else {\n formErrors.push(mapper(sub));\n }\n }\n return { formErrors, fieldErrors };\n}\nexport function formatError(error, mapper = (issue) => issue.message) {\n const fieldErrors = { _errors: [] };\n const processError = (error, path = []) => {\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\" && issue.errors.length) {\n issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path]));\n }\n else if (issue.code === \"invalid_key\") {\n processError({ issues: issue.issues }, [...path, ...issue.path]);\n }\n else if (issue.code === \"invalid_element\") {\n processError({ issues: issue.issues }, [...path, ...issue.path]);\n }\n else {\n const fullpath = [...path, ...issue.path];\n if (fullpath.length === 0) {\n fieldErrors._errors.push(mapper(issue));\n }\n else {\n let curr = fieldErrors;\n let i = 0;\n while (i < fullpath.length) {\n const el = fullpath[i];\n const terminal = i === fullpath.length - 1;\n // `_errors` is reserved by this legacy format, so merge a matching path segment into the current node instead of treating its array as a child.\n if (el === \"_errors\") {\n if (terminal)\n curr._errors.push(mapper(issue));\n i++;\n continue;\n }\n // A path element may collide with an inherited property name such as\n // \"__proto__\" or \"constructor\". Truthiness checks read the prototype\n // (so no node is created, then ._errors.push throws), and bracket\n // assignment of \"__proto__\" hits the setter instead of creating an\n // own key. Guard the read with hasOwnProperty and create the node\n // with defineProperty so any path element becomes a real own key.\n if (!Object.prototype.hasOwnProperty.call(curr, el)) {\n Object.defineProperty(curr, el, {\n value: { _errors: [] },\n enumerable: true,\n writable: true,\n configurable: true,\n });\n }\n const node = curr[el];\n if (terminal) {\n node._errors.push(mapper(issue));\n }\n curr = node;\n i++;\n }\n }\n }\n }\n };\n processError(error);\n return fieldErrors;\n}\nexport function treeifyError(error, mapper = (issue) => issue.message) {\n const result = { errors: [] };\n const processError = (error, path = []) => {\n var _a;\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\" && issue.errors.length) {\n // regular union error\n issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path]));\n }\n else if (issue.code === \"invalid_key\") {\n processError({ issues: issue.issues }, [...path, ...issue.path]);\n }\n else if (issue.code === \"invalid_element\") {\n processError({ issues: issue.issues }, [...path, ...issue.path]);\n }\n else {\n const fullpath = [...path, ...issue.path];\n if (fullpath.length === 0) {\n result.errors.push(mapper(issue));\n continue;\n }\n let curr = result;\n let i = 0;\n while (i < fullpath.length) {\n const el = fullpath[i];\n const terminal = i === fullpath.length - 1;\n if (typeof el === \"string\") {\n curr.properties ?? (curr.properties = {});\n // el may collide with an inherited property name (\"__proto__\",\n // \"constructor\", ...); ??= reads the prototype so the node is never\n // created and curr.errors.push throws. Guard with hasOwnProperty and\n // create the node with defineProperty so \"__proto__\" becomes a real\n // own key rather than invoking the prototype setter.\n if (!Object.prototype.hasOwnProperty.call(curr.properties, el)) {\n Object.defineProperty(curr.properties, el, {\n value: { errors: [] },\n enumerable: true,\n writable: true,\n configurable: true,\n });\n }\n curr = curr.properties[el];\n }\n else {\n curr.items ?? (curr.items = []);\n (_a = curr.items)[el] ?? (_a[el] = { errors: [] });\n curr = curr.items[el];\n }\n if (terminal) {\n curr.errors.push(mapper(issue));\n }\n i++;\n }\n }\n }\n };\n processError(error);\n return result;\n}\n/** Format a ZodError as a human-readable string in the following form.\n *\n * From\n *\n * ```ts\n * ZodError {\n * issues: [\n * {\n * expected: 'string',\n * code: 'invalid_type',\n * path: [ 'username' ],\n * message: 'Invalid input: expected string'\n * },\n * {\n * expected: 'number',\n * code: 'invalid_type',\n * path: [ 'favoriteNumbers', 1 ],\n * message: 'Invalid input: expected number'\n * }\n * ];\n * }\n * ```\n *\n * to\n *\n * ```\n * username\n * ✖ Expected number, received string at \"username\n * favoriteNumbers[0]\n * ✖ Invalid input: expected number\n * ```\n */\nexport function toDotPath(_path) {\n const segs = [];\n const path = _path.map((seg) => (typeof seg === \"object\" ? seg.key : seg));\n for (const seg of path) {\n if (typeof seg === \"number\")\n segs.push(`[${seg}]`);\n else if (typeof seg === \"symbol\")\n segs.push(`[${JSON.stringify(String(seg))}]`);\n else if (/[^\\w$]/.test(seg))\n segs.push(`[${JSON.stringify(seg)}]`);\n else {\n if (segs.length)\n segs.push(\".\");\n segs.push(seg);\n }\n }\n return segs.join(\"\");\n}\nexport function prettifyError(error) {\n const lines = [];\n // sort by path length\n const issues = [...error.issues].sort((a, b) => (a.path ?? []).length - (b.path ?? []).length);\n // Process each issue\n for (const issue of issues) {\n lines.push(`✖ ${issue.message}`);\n if (issue.path?.length)\n lines.push(` → at ${toDotPath(issue.path)}`);\n }\n // Convert Map to formatted string\n return lines.join(\"\\n\");\n}\n","import * as core from \"./core.js\";\nimport * as errors from \"./errors.js\";\nimport * as util from \"./util.js\";\n// Always both keys, so the `_params` read site in `_parse` sees one object shape rather than two.\nfunction finalizeParams(callee, params) {\n return { callee: params?.callee ?? callee, Err: params?.Err };\n}\nexport const _parse = (_Err) => {\n const fn = (schema, value, _ctx, _params) => {\n const ctx = _ctx ? { ..._ctx, async: false } : { async: false };\n const result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n if (result.issues.length) {\n const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));\n util.captureStackTrace(e, _params?.callee ?? fn);\n throw e;\n }\n return result.value;\n };\n return fn;\n};\nexport const parse = /* @__PURE__*/ _parse(errors.$ZodRealError);\nexport const _parseAsync = (_Err) => {\n const fn = async (schema, value, _ctx, params) => {\n const ctx = _ctx ? { ..._ctx, async: true } : { async: true };\n let result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise)\n result = await result;\n if (result.issues.length) {\n const e = new (params?.Err ?? _Err)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));\n util.captureStackTrace(e, params?.callee ?? fn);\n throw e;\n }\n return result.value;\n };\n return fn;\n};\nexport const parseAsync = /* @__PURE__*/ _parseAsync(errors.$ZodRealError);\nexport const _safeParse = (_Err) => (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, async: false } : { async: false };\n const result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n return result.issues.length ? failure(_Err, result.issues, ctx) : { success: true, data: result.value };\n};\nexport const safeParse = /* @__PURE__*/ _safeParse(errors.$ZodRealError);\n// the error is built on the first read of `error`: finalizing the issues and constructing the instance is most of a failing parse, and a caller that only branches on `success` never pays it. a getter in the literal keeps this small; the alternative, one shared accessor descriptor plus a hidden state slot, reads ~15% faster but costs ~75 B gzipped in every bundle\nfunction failure(Err, issues, ctx) {\n let error;\n return {\n success: false,\n get error() {\n if (!error) {\n error = new Err(issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));\n // finalizeIssue drops `input`, so the built error holds nothing; keeping the raw issues past this point pins the parsed value for the life of the result\n issues = undefined;\n ctx = undefined;\n }\n return error;\n },\n set error(e) {\n error = e;\n // a replacement makes the getter's branch unreachable, so the captures have to go here too\n issues = undefined;\n ctx = undefined;\n },\n };\n}\nexport const _safeParseAsync = (_Err) => async (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, async: true } : { async: true };\n let result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise)\n result = await result;\n return result.issues.length ? failure(_Err, result.issues, ctx) : { success: true, data: result.value };\n};\nexport const safeParseAsync = /* @__PURE__*/ _safeParseAsync(errors.$ZodRealError);\n// registry mirrors of the compiler's sentinels, so this module never imports the compiler\nconst COMPILE_INVALID = /* @__PURE__ */ Symbol.for(\"zod.compile.invalid\");\nconst COMPILE_FALLBACK = /* @__PURE__ */ Symbol.for(\"zod.compile.fallback\");\n// Deliberately tiny, because v8 will not inline a body carrying the fallback's object literals and throw. Everything that is not the compiled happy path lives in validateFallback, and that split is worth ~35% on a compiled schema.\nexport const validate = ((schema, value, _ctx) => {\n const validator = schema._zod.bag.validator;\n if (validator !== undefined) {\n if (validator(value) !== COMPILE_INVALID)\n return true;\n // a definite sentinel means the runtime would reject, so skip the re-parse; a ctx can still change the answer\n if (validator.definite === true && _ctx === undefined)\n return false;\n }\n return validateFallback(schema, value, _ctx);\n});\nfunction validateFallback(schema, value, _ctx) {\n const ctx = _ctx\n ? { ..._ctx, async: false, abortEarly: true }\n : { async: false, abortEarly: true };\n const fallbackRun = schema._zod.bag.fallbackRun;\n let result;\n if (fallbackRun) {\n // skip nested fast paths on the fallback, so user callbacks keep the at-most-twice bound\n ctx[COMPILE_FALLBACK] = true;\n result = fallbackRun({ value, issues: [] }, ctx);\n }\n else {\n result = schema._zod.run({ value, issues: [] }, ctx);\n }\n if (result instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n return result.issues.length === 0;\n}\n// no fast path: the compiler keeps async parses on the runtime, because a promise-returning callback that is not declared async compiles to a throw\nexport const validateAsync = async (schema, value, _ctx) => {\n const ctx = _ctx\n ? { ..._ctx, async: true, abortEarly: true }\n : { async: true, abortEarly: true };\n let result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise)\n result = await result;\n return result.issues.length === 0;\n};\nexport const _encode = (_Err) => {\n const parse = _parse(_Err);\n const fn = (schema, value, _ctx, _params) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return parse(schema, value, ctx, finalizeParams(fn, _params));\n };\n return fn;\n};\nexport const encode = /* @__PURE__*/ _encode(errors.$ZodRealError);\nexport const _decode = (_Err) => {\n const parse = _parse(_Err);\n const fn = (schema, value, _ctx, _params) => {\n return parse(schema, value, _ctx, finalizeParams(fn, _params));\n };\n return fn;\n};\nexport const decode = /* @__PURE__*/ _decode(errors.$ZodRealError);\nexport const _encodeAsync = (_Err) => {\n const parseAsync = _parseAsync(_Err);\n const fn = async (schema, value, _ctx, _params) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return (await parseAsync(schema, value, ctx, finalizeParams(fn, _params)));\n };\n return fn;\n};\nexport const encodeAsync = /* @__PURE__*/ _encodeAsync(errors.$ZodRealError);\nexport const _decodeAsync = (_Err) => {\n const parseAsync = _parseAsync(_Err);\n const fn = async (schema, value, _ctx, _params) => {\n return await parseAsync(schema, value, _ctx, finalizeParams(fn, _params));\n };\n return fn;\n};\nexport const decodeAsync = /* @__PURE__*/ _decodeAsync(errors.$ZodRealError);\nexport const _safeEncode = (_Err) => (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return _safeParse(_Err)(schema, value, ctx);\n};\nexport const safeEncode = /* @__PURE__*/ _safeEncode(errors.$ZodRealError);\nexport const _safeDecode = (_Err) => (schema, value, _ctx) => {\n return _safeParse(_Err)(schema, value, _ctx);\n};\nexport const safeDecode = /* @__PURE__*/ _safeDecode(errors.$ZodRealError);\nexport const _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return _safeParseAsync(_Err)(schema, value, ctx);\n};\nexport const safeEncodeAsync = /* @__PURE__*/ _safeEncodeAsync(errors.$ZodRealError);\nexport const _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => {\n return _safeParseAsync(_Err)(schema, value, _ctx);\n};\nexport const safeDecodeAsync = /* @__PURE__*/ _safeDecodeAsync(errors.$ZodRealError);\n","import * as core from \"../core/index.js\";\nimport { $ZodError } from \"../core/index.js\";\nimport * as util from \"../core/util.js\";\n/* Prototypes that already carry the lazy helper methods. Seeded with the\n * intrinsics so that `init` on a foreign object — it accepts any object —\n * can never install an accessor onto a prototype we do not own. */\nconst _installedErrorProtos = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]);\n/* Helper methods live as non-enumerable lazy getters on the shared\n * prototype instead of own properties on every instance. On first\n * access the getter allocates the per-instance closure and caches it\n * as a non-enumerable own property, so detached usage still works and\n * the allocation only happens for methods actually touched. */\nfunction _lazyMethod(proto, key, make) {\n Object.defineProperty(proto, key, {\n configurable: true,\n enumerable: false,\n get() {\n const value = make(this);\n Object.defineProperty(this, key, { value, configurable: true, writable: true });\n return value;\n },\n set(value) {\n Object.defineProperty(this, key, { value, configurable: true, writable: true });\n },\n });\n}\nconst initializer = (inst, issues) => {\n $ZodError.init(inst, issues);\n inst.name = \"ZodError\";\n const proto = Object.getPrototypeOf(inst);\n if (_installedErrorProtos.has(proto))\n return;\n _installedErrorProtos.add(proto);\n _lazyMethod(proto, \"format\", (self) => (mapper) => core.formatError(self, mapper));\n _lazyMethod(proto, \"flatten\", (self) => (mapper) => core.flattenError(self, mapper));\n _lazyMethod(proto, \"addIssue\", (self) => (issue) => {\n self.issues.push(issue);\n self.message = JSON.stringify(self.issues, util.jsonStringifyReplacer, 2);\n });\n _lazyMethod(proto, \"addIssues\", (self) => (issues) => {\n self.issues.push(...issues);\n self.message = JSON.stringify(self.issues, util.jsonStringifyReplacer, 2);\n });\n Object.defineProperty(proto, \"isEmpty\", {\n configurable: true,\n enumerable: false,\n get() {\n return this.issues.length === 0;\n },\n });\n};\nexport const ZodError = /*@__PURE__*/ core.$constructor(\"ZodError\", initializer);\nexport const ZodRealError = /*@__PURE__*/ core.$constructor(\"ZodError\", initializer, undefined, {\n Parent: Error,\n});\n// /** @deprecated Use `z.core.$ZodErrorMapCtx` instead. */\n// export type ErrorMapCtx = core.$ZodErrorMapCtx;\n","import * as core from \"../core/index.js\";\nimport { ZodRealError } from \"./errors.js\";\nexport const parse = /* @__PURE__ */ core._parse(ZodRealError);\nexport const parseAsync = /* @__PURE__ */ core._parseAsync(ZodRealError);\nexport const safeParse = /* @__PURE__ */ core._safeParse(ZodRealError);\nexport const safeParseAsync = /* @__PURE__ */ core._safeParseAsync(ZodRealError);\nexport { validate, validateAsync } from \"../core/index.js\";\n// Codec functions\nexport const encode = /* @__PURE__ */ core._encode(ZodRealError);\nexport const decode = /* @__PURE__ */ core._decode(ZodRealError);\nexport const encodeAsync = /* @__PURE__ */ core._encodeAsync(ZodRealError);\nexport const decodeAsync = /* @__PURE__ */ core._decodeAsync(ZodRealError);\nexport const safeEncode = /* @__PURE__ */ core._safeEncode(ZodRealError);\nexport const safeDecode = /* @__PURE__ */ core._safeDecode(ZodRealError);\nexport const safeEncodeAsync = /* @__PURE__ */ core._safeEncodeAsync(ZodRealError);\nexport const safeDecodeAsync = /* @__PURE__ */ core._safeDecodeAsync(ZodRealError);\n","import * as core from \"../core/index.js\";\nimport { util } from \"../core/index.js\";\nimport * as processors from \"../core/json-schema-processors.js\";\nimport * as regexes from \"../core/regexes.js\";\nimport { createStandardJSONSchemaMethod, createToJSONSchemaMethod } from \"../core/to-json-schema.js\";\nimport en from \"../locales/en.js\";\nimport * as checks from \"./checks.js\";\nimport * as parse from \"./parse.js\";\n// Register English as the default locale on first ZodType construction. Hooked into the `ZodType` `$constructor` (rather than a top-level `config(en())` in `external.ts`) so bundlers honoring `sideEffects: false` can't tree-shake it out — see #5953, #5725. An explicit `z.config(z.locales.xx())` call wins regardless of order, since this only sets the default when none is present.\nfunction _ensureDefaultLocale() {\n if (!core.globalConfig.localeError)\n core.config(en());\n}\n// the default memoizer is read by the core container init, which runs before `ZodType.init`, so each container calls this first\nfunction _ensureDefaultMemoizer() {\n if (!core.globalConfig.memoizer)\n core.config({ memoizer: core.memoizer() });\n}\nexport const ZodType = /*@__PURE__*/ core.$constructor(\"ZodType\", (inst, def) => {\n _ensureDefaultLocale();\n core.$ZodType.init(inst, def);\n inst.def = def;\n inst.type = def.type;\n return inst;\n}, {\n check(...chks) {\n const def = this.def;\n return this.clone(util.mergeDefs(def, {\n checks: [\n ...(def.checks ?? []),\n ...chks.map((ch) => typeof ch === \"function\" ? { _zod: { check: ch, def: { check: \"custom\" }, onattach: [] } } : ch),\n ],\n }), { parent: true });\n },\n with(...chks) {\n return this.check(...chks);\n },\n clone(def, params) {\n return core.clone(this, def, params);\n },\n brand() {\n return this;\n },\n register(reg, meta) {\n reg.add(this, meta);\n return this;\n },\n refine(check, params) {\n return this.check(refine(check, params));\n },\n superRefine(refinement, params) {\n return this.check(superRefine(refinement, params));\n },\n overwrite(fn) {\n return this.check(checks.overwrite(fn));\n },\n optional() {\n return optional(this);\n },\n exactOptional() {\n return exactOptional(this);\n },\n nullable() {\n return nullable(this);\n },\n nullish() {\n return optional(nullable(this));\n },\n nonoptional(params) {\n return nonoptional(this, params);\n },\n array() {\n return array(this);\n },\n or(arg) {\n return union([this, arg]);\n },\n and(arg) {\n return intersection(this, arg);\n },\n transform(tx) {\n return pipe(this, transform(tx));\n },\n default(d) {\n return _default(this, d);\n },\n prefault(d) {\n return prefault(this, d);\n },\n catch(params) {\n return _catch(this, params);\n },\n pipe(target) {\n return pipe(this, target);\n },\n readonly() {\n return readonly(this);\n },\n describe(description) {\n const cl = this.clone();\n core.globalRegistry.add(cl, { description });\n return cl;\n },\n meta(...args) {\n // overloaded: meta() returns the registered metadata, meta(data) returns a clone with `data` registered. The mapped type picks up the second overload, so we accept variadic any-args and return `any` to satisfy both at runtime.\n if (args.length === 0)\n return core.globalRegistry.get(this);\n const cl = this.clone();\n core.globalRegistry.add(cl, args[0]);\n return cl;\n },\n isOptional() {\n return this.safeParse(undefined).success;\n },\n isNullable() {\n return this.safeParse(null).success;\n },\n apply(fn, ...args) {\n return args.length === 0 ? fn(this) : fn(this, ...args);\n },\n // Overrides core's `~standard` to add `jsonSchema`. Must stay a prototype entry: redefining it per instance demotes instances to dictionary mode.\n get \"~standard\"() {\n return util.hide(this, \"~standard\", {\n ...core.standardProps(this),\n jsonSchema: {\n input: createStandardJSONSchemaMethod(this, \"input\"),\n output: createStandardJSONSchemaMethod(this, \"output\"),\n },\n });\n },\n set \"~standard\"(value) {\n util.own(this, \"~standard\", value);\n },\n parse: function _parse(data, params) {\n return parse.parse(this, data, params, { callee: _parse });\n },\n parseAsync: async function _parseAsync(data, params) {\n return await parse.parseAsync(this, data, params, { callee: _parseAsync });\n },\n safeParse(data, params) {\n return parse.safeParse(this, data, params);\n },\n async safeParseAsync(data, params) {\n return parse.safeParseAsync(this, data, params);\n },\n // `spa` is an alias: same function object as `safeParseAsync`, as before.\n get spa() {\n return this?.safeParseAsync;\n },\n set spa(value) {\n util.own(this, \"spa\", value);\n },\n validate(data, params) {\n return parse.validate(this, data, params);\n },\n validateAsync(data, params) {\n return parse.validateAsync(this, data, params);\n },\n encode: function _encode(data, params) {\n return parse.encode(this, data, params, { callee: _encode });\n },\n decode: function _decode(data, params) {\n return parse.decode(this, data, params, { callee: _decode });\n },\n encodeAsync: async function _encodeAsync(data, params) {\n return await parse.encodeAsync(this, data, params, { callee: _encodeAsync });\n },\n decodeAsync: async function _decodeAsync(data, params) {\n return await parse.decodeAsync(this, data, params, { callee: _decodeAsync });\n },\n safeEncode(data, params) {\n return parse.safeEncode(this, data, params);\n },\n safeDecode(data, params) {\n return parse.safeDecode(this, data, params);\n },\n async safeEncodeAsync(data, params) {\n return parse.safeEncodeAsync(this, data, params);\n },\n async safeDecodeAsync(data, params) {\n return parse.safeDecodeAsync(this, data, params);\n },\n toJSONSchema(params) {\n return createToJSONSchemaMethod(this, {})(params);\n },\n // Reads through to the registry on every access, so it must not cache.\n get description() {\n return core.globalRegistry.get(this)?.description;\n },\n // No setter: `schema._def = x` throws, as it did when `_def` was a non-writable own property.\n get _def() {\n return this._zod.def;\n },\n});\n/** @internal */\nexport const _ZodString = /*@__PURE__*/ core.$constructor(\"_ZodString\", (inst, def) => {\n core.$ZodString.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.stringProcessor(inst, ctx, json, params);\n}, \n/*@__PURE__*/ util.derived({\n format: (inst) => processors.aggregateChecks(inst).format ?? null,\n minLength: (inst) => processors.aggregateChecks(inst).minimum ?? null,\n maxLength: (inst) => processors.aggregateChecks(inst).maximum ?? null,\n}, {\n regex(...args) {\n return this.check(checks.regex(...args));\n },\n includes(...args) {\n return this.check(checks.includes(...args));\n },\n startsWith(...args) {\n return this.check(checks.startsWith(...args));\n },\n endsWith(...args) {\n return this.check(checks.endsWith(...args));\n },\n min(...args) {\n return this.check(checks.minLength(...args));\n },\n max(...args) {\n return this.check(checks.maxLength(...args));\n },\n length(...args) {\n return this.check(checks.length(...args));\n },\n nonempty(...args) {\n return this.check(checks.minLength(1, ...args));\n },\n lowercase(params) {\n return this.check(checks.lowercase(params));\n },\n uppercase(params) {\n return this.check(checks.uppercase(params));\n },\n trim() {\n return this.check(checks.trim());\n },\n normalize(...args) {\n return this.check(checks.normalize(...args));\n },\n toLowerCase() {\n return this.check(checks.toLowerCase());\n },\n toUpperCase() {\n return this.check(checks.toUpperCase());\n },\n slugify() {\n return this.check(checks.slugify());\n },\n}));\nexport const ZodString = /*@__PURE__*/ core.$constructor(\"ZodString\", (inst, def) => {\n core.$ZodString.init(inst, def);\n _ZodString.init(inst, def);\n}, {\n email(params) {\n return this.check(core._email(ZodEmail, params));\n },\n url(params) {\n return this.check(core._url(ZodURL, params));\n },\n jwt(params) {\n return this.check(core._jwt(ZodJWT, params));\n },\n emoji(params) {\n return this.check(core._emoji(ZodEmoji, params));\n },\n guid(params) {\n return this.check(core._guid(ZodGUID, params));\n },\n uuid(params) {\n return this.check(core._uuid(ZodUUID, params));\n },\n uuidv4(params) {\n return this.check(core._uuidv4(ZodUUID, params));\n },\n uuidv6(params) {\n return this.check(core._uuidv6(ZodUUID, params));\n },\n uuidv7(params) {\n return this.check(core._uuidv7(ZodUUID, params));\n },\n nanoid(params) {\n return this.check(core._nanoid(ZodNanoID, params));\n },\n cuid(params) {\n return this.check(core._cuid(ZodCUID, params));\n },\n cuid2(params) {\n return this.check(core._cuid2(ZodCUID2, params));\n },\n ulid(params) {\n return this.check(core._ulid(ZodULID, params));\n },\n base64(params) {\n return this.check(core._base64(ZodBase64, params));\n },\n base64url(params) {\n return this.check(core._base64url(ZodBase64URL, params));\n },\n xid(params) {\n return this.check(core._xid(ZodXID, params));\n },\n ksuid(params) {\n return this.check(core._ksuid(ZodKSUID, params));\n },\n ipv4(params) {\n return this.check(core._ipv4(ZodIPv4, params));\n },\n ipv6(params) {\n return this.check(core._ipv6(ZodIPv6, params));\n },\n cidrv4(params) {\n return this.check(core._cidrv4(ZodCIDRv4, params));\n },\n cidrv6(params) {\n return this.check(core._cidrv6(ZodCIDRv6, params));\n },\n e164(params) {\n return this.check(core._e164(ZodE164, params));\n },\n datetime(params) {\n return this.check(core._isoDateTime(ZodISODateTime, params));\n },\n date(params) {\n return this.check(core._isoDate(ZodISODate, params));\n },\n time(params) {\n return this.check(core._isoTime(ZodISOTime, params));\n },\n duration(params) {\n return this.check(core._isoDuration(ZodISODuration, params));\n },\n});\nexport function string(params) {\n return core._string(ZodString, params);\n}\nexport const ZodStringFormat = /*@__PURE__*/ core.$constructor(\"ZodStringFormat\", (inst, def) => {\n core.$ZodStringFormat.init(inst, def);\n _ZodString.init(inst, def);\n});\nexport const ZodISODateTime = /*@__PURE__*/ core.$constructor(\"ZodISODateTime\", (inst, def) => {\n core.$ZodISODateTime.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport const ZodISODate = /*@__PURE__*/ core.$constructor(\"ZodISODate\", (inst, def) => {\n core.$ZodISODate.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport const ZodISOTime = /*@__PURE__*/ core.$constructor(\"ZodISOTime\", (inst, def) => {\n core.$ZodISOTime.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport const ZodISODuration = /*@__PURE__*/ core.$constructor(\"ZodISODuration\", (inst, def) => {\n core.$ZodISODuration.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport const ZodEmail = /*@__PURE__*/ core.$constructor(\"ZodEmail\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodEmail.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function email(params) {\n return core._email(ZodEmail, params);\n}\nexport const ZodGUID = /*@__PURE__*/ core.$constructor(\"ZodGUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodGUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function guid(params) {\n return core._guid(ZodGUID, params);\n}\nexport const ZodUUID = /*@__PURE__*/ core.$constructor(\"ZodUUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodUUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function uuid(params) {\n return core._uuid(ZodUUID, params);\n}\nexport function uuidv4(params) {\n return core._uuidv4(ZodUUID, params);\n}\n// ZodUUIDv6\nexport function uuidv6(params) {\n return core._uuidv6(ZodUUID, params);\n}\n// ZodUUIDv7\nexport function uuidv7(params) {\n return core._uuidv7(ZodUUID, params);\n}\nexport const ZodURL = /*@__PURE__*/ core.$constructor(\"ZodURL\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodURL.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function url(params) {\n return core._url(ZodURL, params);\n}\nexport function httpUrl(params) {\n return core._url(ZodURL, {\n protocol: regexes.httpProtocol,\n hostname: regexes.domain,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodEmoji = /*@__PURE__*/ core.$constructor(\"ZodEmoji\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodEmoji.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function emoji(params) {\n return core._emoji(ZodEmoji, params);\n}\nexport const ZodNanoID = /*@__PURE__*/ core.$constructor(\"ZodNanoID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodNanoID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function nanoid(params) {\n return core._nanoid(ZodNanoID, params);\n}\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link ZodCUID2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport const ZodCUID = /*@__PURE__*/ core.$constructor(\"ZodCUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodCUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\n/**\n * Validates a CUID v1 string.\n *\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link cuid2 | `z.cuid2()`} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport function cuid(params) {\n return core._cuid(ZodCUID, params);\n}\nexport const ZodCUID2 = /*@__PURE__*/ core.$constructor(\"ZodCUID2\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodCUID2.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function cuid2(params) {\n return core._cuid2(ZodCUID2, params);\n}\nexport const ZodULID = /*@__PURE__*/ core.$constructor(\"ZodULID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodULID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ulid(params) {\n return core._ulid(ZodULID, params);\n}\nexport const ZodXID = /*@__PURE__*/ core.$constructor(\"ZodXID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodXID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function xid(params) {\n return core._xid(ZodXID, params);\n}\nexport const ZodKSUID = /*@__PURE__*/ core.$constructor(\"ZodKSUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodKSUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ksuid(params) {\n return core._ksuid(ZodKSUID, params);\n}\nexport const ZodIPv4 = /*@__PURE__*/ core.$constructor(\"ZodIPv4\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodIPv4.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ipv4(params) {\n return core._ipv4(ZodIPv4, params);\n}\nexport const ZodMAC = /*@__PURE__*/ core.$constructor(\"ZodMAC\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodMAC.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function mac(params) {\n return core._mac(ZodMAC, params);\n}\nexport const ZodIPv6 = /*@__PURE__*/ core.$constructor(\"ZodIPv6\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodIPv6.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ipv6(params) {\n return core._ipv6(ZodIPv6, params);\n}\nexport const ZodCIDRv4 = /*@__PURE__*/ core.$constructor(\"ZodCIDRv4\", (inst, def) => {\n core.$ZodCIDRv4.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function cidrv4(params) {\n return core._cidrv4(ZodCIDRv4, params);\n}\nexport const ZodCIDRv6 = /*@__PURE__*/ core.$constructor(\"ZodCIDRv6\", (inst, def) => {\n core.$ZodCIDRv6.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function cidrv6(params) {\n return core._cidrv6(ZodCIDRv6, params);\n}\nexport const ZodBase64 = /*@__PURE__*/ core.$constructor(\"ZodBase64\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodBase64.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function base64(params) {\n return core._base64(ZodBase64, params);\n}\nexport const ZodBase64URL = /*@__PURE__*/ core.$constructor(\"ZodBase64URL\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodBase64URL.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function base64url(params) {\n return core._base64url(ZodBase64URL, params);\n}\nexport const ZodE164 = /*@__PURE__*/ core.$constructor(\"ZodE164\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodE164.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function e164(params) {\n return core._e164(ZodE164, params);\n}\nexport const ZodCreditCard = /*@__PURE__*/ core.$constructor(\"ZodCreditCard\", (inst, def) => {\n core.$ZodCreditCard.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function creditCard(params) {\n return core._creditCard(ZodCreditCard, params);\n}\nexport const ZodIBAN = /*@__PURE__*/ core.$constructor(\"ZodIBAN\", (inst, def) => {\n core.$ZodIBAN.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function iban(params) {\n return core._iban(ZodIBAN, params);\n}\nexport const ZodJWT = /*@__PURE__*/ core.$constructor(\"ZodJWT\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodJWT.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function jwt(params) {\n return core._jwt(ZodJWT, params);\n}\nexport const ZodCustomStringFormat = /*@__PURE__*/ core.$constructor(\"ZodCustomStringFormat\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodCustomStringFormat.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function stringFormat(format, fnOrRegex, _params = {}) {\n return core._stringFormat(ZodCustomStringFormat, format, fnOrRegex, _params);\n}\nexport function hostname(_params) {\n return core._stringFormat(ZodCustomStringFormat, \"hostname\", regexes.hostname, _params);\n}\nexport function hex(_params) {\n return core._stringFormat(ZodCustomStringFormat, \"hex\", regexes.hex, _params);\n}\nexport function currencyCode(_params) {\n return core._stringFormat(ZodCustomStringFormat, \"currency_code\", regexes.currencyCode, _params);\n}\nexport function hash(alg, params) {\n const enc = params?.enc ?? \"hex\";\n const format = `${alg}_${enc}`;\n const regex = core.regexes[format];\n if (!regex)\n throw new Error(`Unrecognized hash format: ${format}`);\n return core._stringFormat(ZodCustomStringFormat, format, regex, params);\n}\nexport const ZodNumber = /*@__PURE__*/ core.$constructor(\"ZodNumber\", (inst, def) => {\n core.$ZodNumber.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.numberProcessor(inst, ctx, json, params);\n inst.isFinite = true;\n}, \n/*@__PURE__*/ util.derived({\n minValue: (inst) => {\n const { minimum, exclusiveMinimum } = processors.aggregateChecks(inst);\n return Math.max(minimum ?? Number.NEGATIVE_INFINITY, exclusiveMinimum ?? Number.NEGATIVE_INFINITY);\n },\n maxValue: (inst) => {\n const { maximum, exclusiveMaximum } = processors.aggregateChecks(inst);\n return Math.min(maximum ?? Number.POSITIVE_INFINITY, exclusiveMaximum ?? Number.POSITIVE_INFINITY);\n },\n isInt: (inst) => {\n const { isInt, multipleOf } = processors.aggregateChecks(inst);\n return !!isInt || !!multipleOf?.some(Number.isSafeInteger);\n },\n format: (inst) => processors.aggregateChecks(inst).format ?? null,\n}, {\n gt(value, params) {\n return this.check(checks.gt(value, params));\n },\n gte(value, params) {\n return this.check(checks.gte(value, params));\n },\n min(value, params) {\n return this.check(checks.gte(value, params));\n },\n lt(value, params) {\n return this.check(checks.lt(value, params));\n },\n lte(value, params) {\n return this.check(checks.lte(value, params));\n },\n max(value, params) {\n return this.check(checks.lte(value, params));\n },\n int(params) {\n return this.check(int(params));\n },\n safe(params) {\n return this.check(int(params));\n },\n positive(params) {\n return this.check(checks.gt(0, params));\n },\n nonnegative(params) {\n return this.check(checks.gte(0, params));\n },\n negative(params) {\n return this.check(checks.lt(0, params));\n },\n nonpositive(params) {\n return this.check(checks.lte(0, params));\n },\n multipleOf(value, params) {\n return this.check(checks.multipleOf(value, params));\n },\n step(value, params) {\n return this.check(checks.multipleOf(value, params));\n },\n finite() {\n return this;\n },\n}));\nexport function number(params) {\n return core._number(ZodNumber, params);\n}\nexport const ZodNumberFormat = /*@__PURE__*/ core.$constructor(\"ZodNumberFormat\", (inst, def) => {\n core.$ZodNumberFormat.init(inst, def);\n ZodNumber.init(inst, def);\n});\nexport function int(params) {\n return core._int(ZodNumberFormat, params);\n}\nexport function float32(params) {\n return core._float32(ZodNumberFormat, params);\n}\nexport function float64(params) {\n return core._float64(ZodNumberFormat, params);\n}\nexport function int32(params) {\n return core._int32(ZodNumberFormat, params);\n}\nexport function uint32(params) {\n return core._uint32(ZodNumberFormat, params);\n}\nexport const ZodBoolean = /*@__PURE__*/ core.$constructor(\"ZodBoolean\", (inst, def) => {\n core.$ZodBoolean.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.booleanProcessor(inst, ctx, json, params);\n});\nexport function boolean(params) {\n return core._boolean(ZodBoolean, params);\n}\nexport const ZodBigInt = /*@__PURE__*/ core.$constructor(\"ZodBigInt\", (inst, def) => {\n core.$ZodBigInt.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.bigintProcessor(inst, ctx, json, params);\n}, \n/*@__PURE__*/ util.derived({\n minValue: (inst) => processors.aggregateChecks(inst).minimum ?? null,\n maxValue: (inst) => processors.aggregateChecks(inst).maximum ?? null,\n format: (inst) => processors.aggregateChecks(inst).format ?? null,\n}, {\n gte(value, params) {\n return this.check(checks.gte(value, params));\n },\n min(value, params) {\n return this.check(checks.gte(value, params));\n },\n gt(value, params) {\n return this.check(checks.gt(value, params));\n },\n lt(value, params) {\n return this.check(checks.lt(value, params));\n },\n lte(value, params) {\n return this.check(checks.lte(value, params));\n },\n max(value, params) {\n return this.check(checks.lte(value, params));\n },\n positive(params) {\n return this.check(checks.gt(BigInt(0), params));\n },\n negative(params) {\n return this.check(checks.lt(BigInt(0), params));\n },\n nonpositive(params) {\n return this.check(checks.lte(BigInt(0), params));\n },\n nonnegative(params) {\n return this.check(checks.gte(BigInt(0), params));\n },\n multipleOf(value, params) {\n return this.check(checks.multipleOf(value, params));\n },\n}));\nexport function bigint(params) {\n return core._bigint(ZodBigInt, params);\n}\nexport const ZodBigIntFormat = /*@__PURE__*/ core.$constructor(\"ZodBigIntFormat\", (inst, def) => {\n core.$ZodBigIntFormat.init(inst, def);\n ZodBigInt.init(inst, def);\n});\nexport function int64(params) {\n return core._int64(ZodBigIntFormat, params);\n}\nexport function uint64(params) {\n return core._uint64(ZodBigIntFormat, params);\n}\nexport const ZodSymbol = /*@__PURE__*/ core.$constructor(\"ZodSymbol\", (inst, def) => {\n core.$ZodSymbol.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.symbolProcessor(inst, ctx, json, params);\n});\nexport function symbol(params) {\n return core._symbol(ZodSymbol, params);\n}\nexport const ZodUndefined = /*@__PURE__*/ core.$constructor(\"ZodUndefined\", (inst, def) => {\n core.$ZodUndefined.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.undefinedProcessor(inst, ctx, json, params);\n});\nfunction _undefined(params) {\n return core._undefined(ZodUndefined, params);\n}\nexport { _undefined as undefined };\nexport const ZodNull = /*@__PURE__*/ core.$constructor(\"ZodNull\", (inst, def) => {\n core.$ZodNull.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nullProcessor(inst, ctx, json, params);\n});\nfunction _null(params) {\n return core._null(ZodNull, params);\n}\nexport { _null as null };\nexport const ZodAny = /*@__PURE__*/ core.$constructor(\"ZodAny\", (inst, def) => {\n core.$ZodAny.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.anyProcessor(inst, ctx, json, params);\n});\nexport function any() {\n return core._any(ZodAny);\n}\nexport const ZodUnknown = /*@__PURE__*/ core.$constructor(\"ZodUnknown\", (inst, def) => {\n core.$ZodUnknown.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.unknownProcessor(inst, ctx, json, params);\n});\nexport function unknown() {\n return core._unknown(ZodUnknown);\n}\nexport const ZodNever = /*@__PURE__*/ core.$constructor(\"ZodNever\", (inst, def) => {\n core.$ZodNever.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.neverProcessor(inst, ctx, json, params);\n});\nexport function never(params) {\n return core._never(ZodNever, params);\n}\nexport const ZodVoid = /*@__PURE__*/ core.$constructor(\"ZodVoid\", (inst, def) => {\n core.$ZodVoid.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.voidProcessor(inst, ctx, json, params);\n});\nfunction _void(params) {\n return core._void(ZodVoid, params);\n}\nexport { _void as void };\nexport const ZodDate = /*@__PURE__*/ core.$constructor(\"ZodDate\", (inst, def) => {\n core.$ZodDate.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.dateProcessor(inst, ctx, json, params);\n inst.min = (value, params) => inst.check(checks.gte(value, params));\n inst.max = (value, params) => inst.check(checks.lte(value, params));\n}, \n/*@__PURE__*/ util.derived({\n minDate: (inst) => {\n const { minimum } = processors.aggregateChecks(inst);\n return minimum ? new Date(minimum) : null;\n },\n maxDate: (inst) => {\n const { maximum } = processors.aggregateChecks(inst);\n return maximum ? new Date(maximum) : null;\n },\n}, {}));\nexport function date(params) {\n return core._date(ZodDate, params);\n}\nexport const ZodArray = /*@__PURE__*/ core.$constructor(\"ZodArray\", (inst, def) => {\n _ensureDefaultMemoizer();\n core.$ZodArray.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.arrayProcessor(inst, ctx, json, params);\n inst.element = def.element;\n}, {\n min(n, params) {\n return this.check(checks.minLength(n, params));\n },\n nonempty(params) {\n return this.check(checks.minLength(1, params));\n },\n max(n, params) {\n return this.check(checks.maxLength(n, params));\n },\n length(n, params) {\n return this.check(checks.length(n, params));\n },\n unwrap() {\n return this.element;\n },\n});\nexport function array(element, params) {\n return core._array(ZodArray, element, params);\n}\n// .keyof\nexport function keyof(schema) {\n const shape = schema._zod.def.shape;\n return _enum(Object.keys(shape));\n}\nexport const ZodObject = /*@__PURE__*/ core.$constructor(\"ZodObject\", (inst, def) => {\n _ensureDefaultMemoizer();\n core.$ZodObjectJIT.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.objectProcessor(inst, ctx, json, params);\n util.installLazyProp(inst, \"shape\", (self) => self._zod.def.shape, false);\n}, {\n keyof() {\n return _enum(Object.keys(this._zod.def.shape));\n },\n catchall(catchall) {\n // `mergeDefs` rather than a spread: spreading reads `shape`, and resolving it can mint a whole fresh subtree\n return this.clone(util.mergeDefs(this._zod.def, { catchall: catchall }));\n },\n passthrough() {\n return this.clone(util.mergeDefs(this._zod.def, { catchall: unknown() }));\n },\n loose() {\n return this.clone(util.mergeDefs(this._zod.def, { catchall: unknown() }));\n },\n strict() {\n return this.clone(util.mergeDefs(this._zod.def, { catchall: never() }));\n },\n strip() {\n return this.clone(util.mergeDefs(this._zod.def, { catchall: undefined }));\n },\n extend(incoming) {\n return util.extend(this, incoming);\n },\n safeExtend(incoming) {\n return util.safeExtend(this, incoming);\n },\n merge(other) {\n return util.merge(this, other);\n },\n pick(mask) {\n return util.pick(this, mask);\n },\n omit(mask) {\n return util.omit(this, mask);\n },\n partial(...args) {\n return util.partial(ZodOptional, this, args[0]);\n },\n exactPartial(...args) {\n return util.partial(ZodExactOptional, this, args[0], \"exactPartial\");\n },\n required(...args) {\n return util.required(ZodNonOptional, this, args[0]);\n },\n});\nexport function object(shape, params) {\n const def = {\n type: \"object\",\n shape: shape ?? {},\n ...util.normalizeParams(params),\n };\n return new ZodObject(def);\n}\n// strictObject\nexport function strictObject(shape, params) {\n return new ZodObject({\n type: \"object\",\n shape,\n catchall: never(),\n ...util.normalizeParams(params),\n });\n}\n// looseObject\nexport function looseObject(shape, params) {\n return new ZodObject({\n type: \"object\",\n shape,\n catchall: unknown(),\n ...util.normalizeParams(params),\n });\n}\nexport const ZodUnion = /*@__PURE__*/ core.$constructor(\"ZodUnion\", (inst, def) => {\n core.$ZodUnion.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.unionProcessor(inst, ctx, json, params);\n inst.options = def.options;\n});\nexport function union(options, params) {\n return new ZodUnion({\n type: \"union\",\n options: options,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodXor = /*@__PURE__*/ core.$constructor(\"ZodXor\", (inst, def) => {\n ZodUnion.init(inst, def);\n core.$ZodXor.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.unionProcessor(inst, ctx, json, params);\n inst.options = def.options;\n});\n/** Creates an exclusive union (XOR) where exactly one option must match.\n * Unlike regular unions that succeed when any option matches, xor fails if\n * zero or more than one option matches the input. */\nexport function xor(options, params) {\n return new ZodXor({\n type: \"union\",\n options: options,\n inclusive: false,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodDiscriminatedUnion = /*@__PURE__*/ core.$constructor(\"ZodDiscriminatedUnion\", (inst, def) => {\n ZodUnion.init(inst, def);\n core.$ZodDiscriminatedUnion.init(inst, def);\n});\nexport function discriminatedUnion(discriminator, options, params) {\n // const [options, params] = args;\n return new ZodDiscriminatedUnion({\n type: \"union\",\n options: options,\n discriminator,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodIntersection = /*@__PURE__*/ core.$constructor(\"ZodIntersection\", (inst, def) => {\n core.$ZodIntersection.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.intersectionProcessor(inst, ctx, json, params);\n});\nexport function intersection(left, right) {\n return new ZodIntersection({\n type: \"intersection\",\n left: left,\n right: right,\n });\n}\nexport const ZodTuple = /*@__PURE__*/ core.$constructor(\"ZodTuple\", (inst, def) => {\n _ensureDefaultMemoizer();\n core.$ZodTuple.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.tupleProcessor(inst, ctx, json, params);\n}, {\n rest(rest) {\n return this.clone({\n ...this._zod.def,\n rest: rest,\n });\n },\n partial() {\n const def = this._zod.def;\n // a refinement was authored against the full arity; partialing would run it on a shorter array\n if (def.checks?.length)\n throw new Error(\".partial() cannot be used on tuple schemas containing refinements\");\n return this.clone({\n ...def,\n items: def.items.map((item) => new ZodOptional({ type: \"optional\", innerType: item })),\n });\n },\n});\nexport function tuple(items, _paramsOrRest, _params) {\n const hasRest = _paramsOrRest instanceof core.$ZodType;\n const params = hasRest ? _params : _paramsOrRest;\n const rest = hasRest ? _paramsOrRest : null;\n return new ZodTuple({\n type: \"tuple\",\n items: items,\n rest,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodRecord = /*@__PURE__*/ core.$constructor(\"ZodRecord\", (inst, def) => {\n _ensureDefaultMemoizer();\n core.$ZodRecord.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.recordProcessor(inst, ctx, json, params);\n inst.keyType = def.keyType;\n inst.valueType = def.valueType;\n});\nexport function record(keyType, valueType, params) {\n // v3-compat: z.record(valueType, params?) — defaults keyType to z.string()\n if (!valueType || !valueType._zod) {\n return new ZodRecord({\n type: \"record\",\n keyType: string(),\n valueType: keyType,\n ...util.normalizeParams(valueType),\n });\n }\n return new ZodRecord({\n type: \"record\",\n keyType,\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\n// type alksjf = core.output<core.$ZodRecordKey>;\nexport function partialRecord(keyType, valueType, params) {\n return new ZodRecord({\n type: \"record\",\n keyType,\n valueType: valueType,\n ...util.normalizeParams(params),\n partial: true,\n });\n}\nexport function looseRecord(keyType, valueType, params) {\n return new ZodRecord({\n type: \"record\",\n keyType,\n valueType: valueType,\n mode: \"loose\",\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMap = /*@__PURE__*/ core.$constructor(\"ZodMap\", (inst, def) => {\n _ensureDefaultMemoizer();\n core.$ZodMap.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.mapProcessor(inst, ctx, json, params);\n inst.keyType = def.keyType;\n inst.valueType = def.valueType;\n inst.min = (...args) => inst.check(core._minSize(...args));\n inst.nonempty = (params) => inst.check(core._minSize(1, params));\n inst.max = (...args) => inst.check(core._maxSize(...args));\n inst.size = (...args) => inst.check(core._size(...args));\n});\nexport function map(keyType, valueType, params) {\n return new ZodMap({\n type: \"map\",\n keyType: keyType,\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodSet = /*@__PURE__*/ core.$constructor(\"ZodSet\", (inst, def) => {\n _ensureDefaultMemoizer();\n core.$ZodSet.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.setProcessor(inst, ctx, json, params);\n inst.min = (...args) => inst.check(core._minSize(...args));\n inst.nonempty = (params) => inst.check(core._minSize(1, params));\n inst.max = (...args) => inst.check(core._maxSize(...args));\n inst.size = (...args) => inst.check(core._size(...args));\n});\nexport function set(valueType, params) {\n return new ZodSet({\n type: \"set\",\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodEnum = /*@__PURE__*/ core.$constructor(\"ZodEnum\", (inst, def) => {\n core.$ZodEnum.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.enumProcessor(inst, ctx, json, params);\n inst.enum = def.entries;\n // reuse the parsed value set so a numeric TS enum's reverse-mapping keys stay out\n inst.options = [...inst._zod.values];\n const keys = new Set(Object.keys(def.entries));\n inst.extract = (values, params) => {\n const newEntries = {};\n for (const value of values) {\n if (keys.has(value)) {\n newEntries[value] = def.entries[value];\n }\n else\n throw new Error(`Key ${value} not found in enum`);\n }\n return new ZodEnum({\n ...def,\n checks: [],\n ...util.normalizeParams(params),\n entries: newEntries,\n });\n };\n inst.exclude = (values, params) => {\n const newEntries = { ...def.entries };\n for (const value of values) {\n if (keys.has(value)) {\n delete newEntries[value];\n }\n else\n throw new Error(`Key ${value} not found in enum`);\n }\n return new ZodEnum({\n ...def,\n checks: [],\n ...util.normalizeParams(params),\n entries: newEntries,\n });\n };\n});\nfunction _enum(values, params) {\n const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;\n return new ZodEnum({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\nexport { _enum as enum };\n/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead.\n *\n * ```ts\n * enum Colors { red, green, blue }\n * z.enum(Colors);\n * ```\n */\nexport function nativeEnum(entries, params) {\n return new ZodEnum({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodLiteral = /*@__PURE__*/ core.$constructor(\"ZodLiteral\", (inst, def) => {\n core.$ZodLiteral.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.literalProcessor(inst, ctx, json, params);\n inst.values = new Set(def.values);\n Object.defineProperty(inst, \"value\", {\n get() {\n if (def.values.length > 1) {\n throw new Error(\"This schema contains multiple valid literal values. Use `.values` instead.\");\n }\n return def.values[0];\n },\n });\n});\nexport function literal(value, params) {\n return new ZodLiteral({\n type: \"literal\",\n values: Array.isArray(value) ? value : [value],\n ...util.normalizeParams(params),\n });\n}\nexport const ZodFile = /*@__PURE__*/ core.$constructor(\"ZodFile\", (inst, def) => {\n core.$ZodFile.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.fileProcessor(inst, ctx, json, params);\n inst.min = (size, params) => inst.check(core._minSize(size, params));\n inst.max = (size, params) => inst.check(core._maxSize(size, params));\n inst.mime = (types, params) => inst.check(core._mime(Array.isArray(types) ? types : [types], params));\n});\nexport function file(params) {\n return core._file(ZodFile, params);\n}\nexport const ZodTransform = /*@__PURE__*/ core.$constructor(\"ZodTransform\", (inst, def) => {\n _ensureDefaultMemoizer();\n core.$ZodTransform.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.transformProcessor(inst, ctx, json, params);\n inst._zod.parse = (payload, _ctx) => {\n if (_ctx.direction === \"backward\") {\n throw new core.$ZodEncodeError(inst.constructor.name);\n }\n payload.addIssue = (issue) => {\n if (typeof issue === \"string\") {\n payload.issues.push(util.issue(issue, payload.value, def));\n }\n else {\n // for Zod 3 backwards compatibility\n const _issue = issue;\n if (_issue.fatal)\n _issue.continue = false;\n _issue.code ?? (_issue.code = \"custom\");\n if (!(\"input\" in _issue))\n _issue.input = payload.value;\n _issue.inst ?? (_issue.inst = inst);\n // _issue.continue ??= true;\n payload.issues.push(util.issue(_issue));\n }\n };\n const output = def.transform(payload.value, payload);\n if (output instanceof Promise) {\n return output.then((output) => {\n payload.value = output;\n return payload;\n });\n }\n payload.value = output;\n return payload;\n };\n});\nexport function transform(fn) {\n return new ZodTransform({\n type: \"transform\",\n transform: fn,\n });\n}\nexport const ZodOptional = /*@__PURE__*/ core.$constructor(\"ZodOptional\", (inst, def) => {\n core.$ZodOptional.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.optionalProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function optional(innerType) {\n return new ZodOptional({\n type: \"optional\",\n innerType: innerType,\n });\n}\nexport const ZodExactOptional = /*@__PURE__*/ core.$constructor(\"ZodExactOptional\", (inst, def) => {\n core.$ZodExactOptional.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.optionalProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function exactOptional(innerType) {\n return new ZodExactOptional({\n type: \"optional\",\n innerType: innerType,\n });\n}\nexport const ZodNullable = /*@__PURE__*/ core.$constructor(\"ZodNullable\", (inst, def) => {\n core.$ZodNullable.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nullableProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function nullable(innerType) {\n return new ZodNullable({\n type: \"nullable\",\n innerType: innerType,\n });\n}\n// nullish\nexport function nullish(innerType) {\n return optional(nullable(innerType));\n}\nexport const ZodDefault = /*@__PURE__*/ core.$constructor(\"ZodDefault\", (inst, def) => {\n core.$ZodDefault.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.defaultProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n inst.removeDefault = inst.unwrap;\n});\nexport function _default(innerType, defaultValue) {\n return new ZodDefault({\n type: \"default\",\n innerType: innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\nexport const ZodPrefault = /*@__PURE__*/ core.$constructor(\"ZodPrefault\", (inst, def) => {\n core.$ZodPrefault.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.prefaultProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function prefault(innerType, defaultValue) {\n return new ZodPrefault({\n type: \"prefault\",\n innerType: innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\nexport const ZodNonOptional = /*@__PURE__*/ core.$constructor(\"ZodNonOptional\", (inst, def) => {\n core.$ZodNonOptional.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nonoptionalProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function nonoptional(innerType, params) {\n return new ZodNonOptional({\n type: \"nonoptional\",\n innerType: innerType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodSuccess = /*@__PURE__*/ core.$constructor(\"ZodSuccess\", (inst, def) => {\n core.$ZodSuccess.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.successProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function success(innerType) {\n return new ZodSuccess({\n type: \"success\",\n innerType: innerType,\n });\n}\nexport const ZodCatch = /*@__PURE__*/ core.$constructor(\"ZodCatch\", (inst, def) => {\n core.$ZodCatch.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.catchProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n inst.removeCatch = inst.unwrap;\n});\nfunction _catch(innerType, catchValue) {\n return new ZodCatch({\n type: \"catch\",\n innerType: innerType,\n catchValue: (typeof catchValue === \"function\" ? catchValue : core.util.constantCatch(catchValue)),\n });\n}\nexport { _catch as catch };\nexport const ZodNaN = /*@__PURE__*/ core.$constructor(\"ZodNaN\", (inst, def) => {\n core.$ZodNaN.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nanProcessor(inst, ctx, json, params);\n});\nexport function nan(params) {\n return core._nan(ZodNaN, params);\n}\nexport const ZodPipe = /*@__PURE__*/ core.$constructor(\"ZodPipe\", (inst, def) => {\n core.$ZodPipe.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.pipeProcessor(inst, ctx, json, params);\n inst.in = def.in;\n inst.out = def.out;\n});\nexport function pipe(in_, out) {\n return new ZodPipe({\n type: \"pipe\",\n in: in_,\n out: out,\n // ...util.normalizeParams(params),\n });\n}\nexport const ZodCodec = /*@__PURE__*/ core.$constructor(\"ZodCodec\", (inst, def) => {\n ZodPipe.init(inst, def);\n core.$ZodCodec.init(inst, def);\n});\nexport function codec(in_, out, params) {\n return new ZodCodec({\n type: \"pipe\",\n in: in_,\n out: out,\n transform: params.decode,\n reverseTransform: params.encode,\n });\n}\nexport function invertCodec(codec) {\n const def = codec._zod.def;\n return new ZodCodec({\n type: \"pipe\",\n in: def.out,\n out: def.in,\n transform: def.reverseTransform,\n reverseTransform: def.transform,\n });\n}\nexport const ZodPreprocess = /*@__PURE__*/ core.$constructor(\"ZodPreprocess\", (inst, def) => {\n ZodPipe.init(inst, def);\n core.$ZodPreprocess.init(inst, def);\n});\nexport const ZodReadonly = /*@__PURE__*/ core.$constructor(\"ZodReadonly\", (inst, def) => {\n core.$ZodReadonly.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.readonlyProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function readonly(innerType) {\n return new ZodReadonly({\n type: \"readonly\",\n innerType: innerType,\n });\n}\nexport const ZodTemplateLiteral = /*@__PURE__*/ core.$constructor(\"ZodTemplateLiteral\", (inst, def) => {\n core.$ZodTemplateLiteral.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.templateLiteralProcessor(inst, ctx, json, params);\n});\nexport function templateLiteral(parts, params) {\n return new ZodTemplateLiteral({\n type: \"template_literal\",\n parts,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodLazy = /*@__PURE__*/ core.$constructor(\"ZodLazy\", (inst, def) => {\n core.$ZodLazy.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.lazyProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.getter();\n});\nexport function lazy(getter) {\n return new ZodLazy({\n type: \"lazy\",\n getter: getter,\n });\n}\nexport const ZodPromise = /*@__PURE__*/ core.$constructor(\"ZodPromise\", (inst, def) => {\n core.$ZodPromise.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.promiseProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function promise(innerType) {\n return new ZodPromise({\n type: \"promise\",\n innerType: innerType,\n });\n}\nexport const ZodFunction = /*@__PURE__*/ core.$constructor(\"ZodFunction\", (inst, def) => {\n core.$ZodFunction.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.functionProcessor(inst, ctx, json, params);\n});\nexport function _function(params) {\n return new ZodFunction({\n type: \"function\",\n input: Array.isArray(params?.input) ? tuple(params?.input) : (params?.input ?? array(unknown())),\n output: params?.output ?? unknown(),\n });\n}\nexport { _function as function };\nexport const ZodCustom = /*@__PURE__*/ core.$constructor(\"ZodCustom\", (inst, def) => {\n core.$ZodCustom.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.customProcessor(inst, ctx, json, params);\n});\n// custom checks\nexport function check(fn) {\n const ch = new core.$ZodCheck({\n check: \"custom\",\n // ...util.normalizeParams(params),\n });\n ch._zod.check = fn;\n return ch;\n}\nexport function custom(fn, _params) {\n return core._custom(ZodCustom, fn ?? (() => true), _params);\n}\nexport function refine(fn, _params = {}) {\n return core._refine(ZodCustom, fn, _params);\n}\n// superRefine\nexport function superRefine(fn, params) {\n return core._superRefine(fn, params);\n}\n// Re-export describe and meta from core\nexport const describe = core.describe;\nexport const meta = core.meta;\nexport const ZodInstanceOf = /*@__PURE__*/ core.$constructor(\"ZodInstanceOf\", (inst, def) => {\n ZodCustom.init(inst, def);\n}, {\n properties(shape, params) {\n // asserts in place, so the narrowed output type is truthful without a wrapper\n return this.check(core._properties(shape, params));\n },\n});\nfunction _instanceof(cls, params = {}) {\n const inst = new ZodInstanceOf({\n type: \"custom\",\n check: \"custom\",\n fn: (data) => data instanceof cls,\n abort: true,\n ...util.normalizeParams(params),\n });\n inst._zod.bag.Class = cls;\n // Override check to emit invalid_type instead of custom\n inst._zod.check = (payload) => {\n if (!(payload.value instanceof cls)) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: cls.name,\n input: payload.value,\n inst,\n path: [...(inst._zod.def.path ?? [])],\n });\n }\n };\n return inst;\n}\nexport { _instanceof as instanceof };\n// stringbool\nexport const stringbool = (...args) => core._stringbool({\n Codec: ZodCodec,\n Boolean: ZodBoolean,\n String: ZodString,\n}, ...args);\nexport function json(params) {\n const jsonSchema = lazy(() => {\n return union([string(params), number(), boolean(), _null(), array(jsonSchema), record(string(), jsonSchema)]);\n });\n return jsonSchema;\n}\n// preprocess\nexport function preprocess(fn, schema) {\n return new ZodPreprocess({\n type: \"pipe\",\n in: transform(fn),\n out: schema,\n });\n}\n","import { getBackendSrv } from '@grafana/runtime';\n// biome-ignore lint/suspicious/noDeprecatedImports: these calls use current overloads, without schedulers or result selectors\nimport { firstValueFrom, fromEvent, merge, mergeMap, throwError } from 'rxjs';\nimport { z } from 'zod';\nimport { ASSISTANT_PLUGIN_ID } from '../plugin';\nimport type {\n CreatedInvestigation,\n CreateInvestigationInput,\n InvestigationReport,\n InvestigationRequestOptions,\n InvestigationStatus,\n} from './types';\n\nconst baseUrl = `api/plugins/${ASSISTANT_PLUGIN_ID}/resources/api/v2/investigations`;\n\nconst createdSchema = z.object({\n investigationId: z.string().min(1),\n chatId: z.string(),\n}) satisfies z.ZodType<CreatedInvestigation>;\n\nconst statusSchema = z.object({\n investigationId: z.string().min(1),\n chatId: z.string(),\n state: z.string().optional(),\n title: z.string().optional(),\n summary: z.string().optional(),\n failureReason: z.string().optional(),\n errorMessage: z.string().optional(),\n completionQuality: z.string().optional(),\n degradedReason: z.string().optional(),\n}) satisfies z.ZodType<InvestigationStatus>;\n\nconst reportSchema = z.object({\n investigationId: z.string().min(1),\n reportPending: z.boolean(),\n reportContent: z.string().optional(),\n reportSpec: z\n .object({\n root: z.string(),\n elements: z.record(\n z.string(),\n z.object({\n type: z.string(),\n props: z.record(z.string(), z.unknown()),\n children: z.array(z.string()).optional(),\n })\n ),\n })\n .optional(),\n}) satisfies z.ZodType<InvestigationReport>;\n\nasync function request<T>(\n method: 'GET' | 'POST',\n suffix: string,\n schema: z.ZodType<T>,\n options: InvestigationRequestOptions,\n data?: CreateInvestigationInput\n): Promise<T> {\n const signal = options.signal;\n signal?.throwIfAborted();\n const response$ = getBackendSrv().fetch<unknown>({\n url: `${baseUrl}${suffix}`,\n method,\n data,\n abortSignal: options.signal,\n retry: 0,\n showErrorAlert: false,\n showSuccessAlert: false,\n });\n // Unsubscribe on cancellation even on Grafana versions that ignore abortSignal.\n const response = await firstValueFrom(\n signal\n ? merge(response$, fromEvent(signal, 'abort').pipe(mergeMap(() => throwError(() => signal.reason))))\n : response$\n );\n return z.object({ status: z.literal('success'), data: schema }).parse(response.data).data;\n}\n\nfunction resourcePath(investigationId: string): string {\n if (investigationId.trim() === '') {\n throw new Error('An investigation ID is required. Use the ID returned by createInvestigation.');\n }\n return `/${encodeURIComponent(investigationId)}`;\n}\n\n/** Start an investigation. No automatic retries: retrying creation can create duplicates. */\nexport async function createInvestigation(\n input: CreateInvestigationInput,\n options: InvestigationRequestOptions = {}\n): Promise<CreatedInvestigation> {\n if (input.instruction.trim() === '') {\n throw new Error('An investigation instruction must contain non-whitespace text.');\n }\n return request('POST', '', createdSchema, options, input);\n}\n\n/** Read lifecycle state once. The caller controls polling intervals and deadlines. */\nexport async function getInvestigationStatus(\n investigationId: string,\n options: InvestigationRequestOptions = {}\n): Promise<InvestigationStatus> {\n return request('GET', resourcePath(investigationId), statusSchema, options);\n}\n\n/** Read the current report snapshot. A session that has not started can return 404. */\nexport async function getInvestigationReport(\n investigationId: string,\n options: InvestigationRequestOptions = {}\n): Promise<InvestigationReport> {\n return request('GET', `${resourcePath(investigationId)}/snapshot`, reportSchema, options);\n}\n","import { config, isFetchError } from '@grafana/runtime';\nimport { Observable } from 'rxjs';\nimport { z } from 'zod';\nimport { ASSISTANT_PLUGIN_ID } from '../plugin';\nimport { getInvestigationReport, getInvestigationStatus } from './client';\nimport type { InvestigationEvent, InvestigationReport } from './types';\n\nconst refreshIntervalMs = 5000;\nconst connectTimeoutMs = 30000;\nconst envelopeSchema = z.object({ type: z.string(), payload: z.unknown().optional() });\nconst textDeltaSchema = z.object({\n chatId: z.string(),\n messageId: z.string().min(1),\n contentIndex: z.number().int().nonnegative(),\n contentType: z.string(),\n delta: z.string().optional(),\n audience: z.string().optional(),\n});\n\n/**\n * Observe an existing investigation as the signed-in Grafana user.\n * Each subscription owns its requests and event connection. Unsubscribe stops\n * observation, never server-side work. A transport error closes the subscription;\n * resubscribe to recover current snapshots (text deltas are not replayed).\n */\nexport function observeInvestigation(investigationId: string): Observable<InvestigationEvent> {\n return new Observable((subscriber) => {\n const controller = new AbortController();\n let source: EventSource | undefined;\n let connectedChatId: string | undefined;\n let connectTimer: ReturnType<typeof setTimeout> | undefined;\n let refreshTimer: ReturnType<typeof setTimeout> | undefined;\n let eventTimer: ReturnType<typeof setTimeout> | undefined;\n let refreshing = false;\n let refreshRequested = false;\n let previousStatus: string | undefined;\n let previousReport: string | undefined;\n\n const fail = (error: unknown) => subscriber.error(error);\n\n function openStream(chatId: string) {\n // The status API serializes an unassigned Go UUID as the all-zero string.\n if (\n subscriber.closed ||\n !chatId ||\n chatId === '00000000-0000-0000-0000-000000000000' ||\n connectedChatId === chatId\n ) {\n return;\n }\n source?.close();\n clearTimeout(connectTimer);\n connectedChatId = chatId;\n const appSubUrl = config.appSubUrl ?? '';\n const url = `${appSubUrl}/api/plugins/${ASSISTANT_PLUGIN_ID}/resources/api/events/chats/${encodeURIComponent(chatId)}`;\n const connection = new EventSource(url);\n source = connection;\n connectTimer = setTimeout(\n () => fail(new Error('Investigation event stream did not connect. Subscribe again to retry.')),\n connectTimeoutMs\n );\n connection.onopen = () => {\n if (source !== connection || subscriber.closed) {\n return;\n }\n clearTimeout(connectTimer);\n refreshFromEvent();\n };\n connection.onerror = () => {\n if (source !== connection || subscriber.closed) {\n return;\n }\n fail(new Error('Investigation event stream disconnected. Subscribe again to refresh state and retry.'));\n };\n connection.onmessage = (message: MessageEvent<string>) => {\n if (subscriber.closed || source !== connection) {\n return;\n }\n try {\n const event = envelopeSchema.parse(JSON.parse(message.data));\n if (event.type === 'message.content.delta') {\n const data = textDeltaSchema.parse(event.payload);\n if (\n data.chatId === chatId &&\n data.contentType === 'text' &&\n data.delta &&\n (!data.audience || data.audience === 'user')\n ) {\n subscriber.next({\n type: 'progress',\n investigationId,\n messageId: data.messageId,\n contentIndex: data.contentIndex,\n delta: data.delta,\n });\n }\n } else if (\n event.type === 'connection.ready' ||\n event.type === 'lodestone.session.status' ||\n event.type === 'lodestone.report.pending' ||\n event.type === 'lodestone.canvas.update' ||\n event.type === 'message.stream.complete'\n ) {\n // Events are hints: persisted API state owns lifecycle and report truth.\n refreshFromEvent();\n }\n } catch (error) {\n fail(error);\n }\n };\n }\n\n function refreshFromEvent() {\n if (refreshing) {\n refreshRequested = true;\n } else if (eventTimer === undefined) {\n eventTimer = setTimeout(() => {\n eventTimer = undefined;\n requestRefresh();\n }, 250);\n }\n }\n\n async function refresh() {\n if (subscriber.closed) {\n return;\n }\n refreshing = true;\n refreshRequested = false;\n try {\n const status = await getInvestigationStatus(investigationId, { signal: controller.signal });\n if (subscriber.closed) {\n return;\n }\n const serializedStatus = JSON.stringify(status);\n if (serializedStatus !== previousStatus) {\n previousStatus = serializedStatus;\n subscriber.next({ type: 'status', status });\n }\n if (subscriber.closed) {\n return;\n }\n const terminal = status.state === 'completed' || status.state === 'failed' || status.state === 'cancelled';\n // Connect before fetching the snapshot so subsequent events request another read.\n if (!terminal) {\n openStream(status.chatId);\n }\n let report: InvestigationReport | undefined;\n try {\n report = await getInvestigationReport(investigationId, { signal: controller.signal });\n } catch (error) {\n // A readable investigation can exist before its engine session is created.\n if (!isFetchError(error) || error.status !== 404) {\n throw error;\n }\n }\n if (subscriber.closed) {\n return;\n }\n if (report) {\n const serializedReport = JSON.stringify(report);\n if (serializedReport !== previousReport) {\n previousReport = serializedReport;\n subscriber.next({ type: 'report', report });\n }\n }\n // Completed rows can still have an in-flight report fork. Keep observing it.\n if (terminal && !report?.reportPending && !refreshRequested) {\n subscriber.complete();\n } else if (terminal && report?.reportPending) {\n openStream(status.chatId);\n }\n } catch (error) {\n fail(error);\n } finally {\n refreshing = false;\n if (!subscriber.closed) {\n // Coalesce event bursts and serialize reads so older responses cannot win.\n refreshTimer = setTimeout(requestRefresh, refreshRequested ? 250 : refreshIntervalMs);\n }\n }\n }\n\n function requestRefresh() {\n if (subscriber.closed) {\n return;\n }\n if (refreshing) {\n refreshRequested = true;\n return;\n }\n clearTimeout(refreshTimer);\n clearTimeout(eventTimer);\n eventTimer = undefined;\n // refresh owns request failures; this also catches unexpected orchestration errors.\n refresh().catch(fail);\n }\n\n requestRefresh();\n return () => {\n controller.abort();\n clearTimeout(refreshTimer);\n clearTimeout(eventTimer);\n clearTimeout(connectTimer);\n if (source) {\n source.onopen = null;\n source.onmessage = null;\n source.onerror = null;\n source.close();\n }\n };\n });\n}\n","/**\n * Lightweight semantic version comparison utility.\n * Replaces semver library to reduce bundle size.\n *\n * Supports standard semver format: major.minor.patch[-prerelease][+build]\n * Pre-release versions are considered lower than release versions.\n * Build metadata is ignored for comparison purposes.\n */\n\ninterface ParsedVersion {\n major: number;\n minor: number;\n patch: number;\n prerelease?: string;\n}\n\n/**\n * Parses a semantic version string into its components.\n * @param version - Version string (e.g., \"1.2.3\", \"0.0.2-ga\", \"1.2.3+build\")\n * @returns Parsed version object or null if invalid\n */\nfunction parseVersion(version: string): ParsedVersion | null {\n // Remove build metadata (everything after +)\n const withoutBuild = version.split('+')[0];\n\n // Split into version and prerelease parts\n const parts = withoutBuild.split('-');\n const versionPart = parts[0];\n const prerelease = parts.length > 1 ? parts.slice(1).join('-') : undefined;\n\n // Parse major.minor.patch\n const numbers = versionPart.split('.').map(Number);\n if (numbers.length !== 3 || numbers.some(isNaN)) {\n return null;\n }\n\n return {\n major: numbers[0],\n minor: numbers[1],\n patch: numbers[2],\n prerelease,\n };\n}\n\n/**\n * Compares two semantic versions.\n * @param v1 - First version string\n * @param v2 - Second version string\n * @returns -1 if v1 < v2, 0 if v1 === v2, 1 if v1 > v2, or null if either version is invalid\n */\nfunction compareVersions(v1: string, v2: string): number | null {\n const parsed1 = parseVersion(v1);\n const parsed2 = parseVersion(v2);\n\n if (!parsed1 || !parsed2) {\n return null;\n }\n\n // Compare major version\n if (parsed1.major !== parsed2.major) {\n return parsed1.major > parsed2.major ? 1 : -1;\n }\n\n // Compare minor version\n if (parsed1.minor !== parsed2.minor) {\n return parsed1.minor > parsed2.minor ? 1 : -1;\n }\n\n // Compare patch version\n if (parsed1.patch !== parsed2.patch) {\n return parsed1.patch > parsed2.patch ? 1 : -1;\n }\n\n // If both have prerelease, compare lexicographically\n // If only one has prerelease, it's considered lower\n if (parsed1.prerelease && parsed2.prerelease) {\n if (parsed1.prerelease === parsed2.prerelease) {\n return 0;\n }\n return parsed1.prerelease > parsed2.prerelease ? 1 : -1;\n }\n\n if (parsed1.prerelease && !parsed2.prerelease) {\n return -1; // v1 has prerelease, v2 doesn't, so v1 < v2\n }\n\n if (!parsed1.prerelease && parsed2.prerelease) {\n return 1; // v1 doesn't have prerelease, v2 does, so v1 > v2\n }\n\n return 0; // Both are release versions with same major.minor.patch\n}\n\n/**\n * Checks if version v1 is greater than version v2.\n * @param v1 - First version string\n * @param v2 - Second version string\n * @returns true if v1 > v2, false otherwise (including if either version is invalid)\n */\nexport function isVersionGreaterThan(v1: string, v2: string): boolean {\n const result = compareVersions(v1, v2);\n return result === 1;\n}\n","import { getBackendSrv } from '@grafana/runtime';\nimport { lastValueFrom } from 'rxjs';\nimport { useState, useEffect } from 'react';\nimport { ASSISTANT_PLUGIN_ID } from '../plugin';\nimport { isVersionGreaterThan } from './versionCompare';\nimport type { components } from './settings.gen';\n\n/**\n * The type of terms that apply to a tenant.\n * - 'msa': Master Service Agreement - only requires acceptance, no version checking\n * - 'termsAndConditions': Full terms and conditions - requires acceptance AND version checking\n */\nexport type TermsType = components['schemas']['TermsAndConditionsResponse']['termsType'];\n\n/**\n * Internal result type for fetching terms data.\n */\ninterface TermsCheckResult {\n accepted: boolean;\n termsType: TermsType;\n}\n\n/**\n * Event name that is dispatched when terms and conditions are accepted.\n * Other components can listen to this event to refresh their UI.\n */\nexport const TERMS_AND_CONDITIONS_REFRESH_EVENT = 'grafana-assistant-terms-and-conditions-refresh';\n\n/**\n * Internal function that fetches and evaluates terms data.\n * Returns both the acceptance status and the terms type.\n */\nasync function fetchTermsData(): Promise<TermsCheckResult> {\n const backendSrv = getBackendSrv();\n // No appSubUrl prefix: BackendSrv strips the leading `/` so Grafana's\n // `<base href>` adds the subpath (see grafana-assistant-app/issues/6109).\n const apiUrl = `/api/plugins/${ASSISTANT_PLUGIN_ID}/resources/api/v1/settings/terms`;\n\n const response = await lastValueFrom(\n backendSrv.fetch({\n url: apiUrl,\n method: 'GET',\n showErrorAlert: false,\n })\n );\n\n // The API returns { status: \"success\", data: { ... } }, so we need to access response.data.data\n const responseBody = response.data as { data: components['schemas']['TermsAndConditionsResponse'] };\n const termsData = responseBody.data;\n\n const termsAccepted = termsData.acceptedTermsAndConditions ?? false;\n const acceptedVersion = termsData.acceptedVersion;\n const currentVersion = termsData.version;\n const termsType = termsData.termsType;\n\n // For MSA, we only check if terms are accepted\n if (termsType === 'msa') {\n return { accepted: termsAccepted, termsType };\n }\n\n // Check if terms are not accepted, or if no version was recorded or current version is missing\n if (!termsAccepted || !acceptedVersion || !currentVersion) {\n return { accepted: false, termsType };\n }\n\n // Check if the current version is newer than the accepted version\n const needsAcceptance = isVersionGreaterThan(currentVersion, acceptedVersion);\n return { accepted: termsAccepted && !needsAcceptance, termsType };\n}\n\nfunction nonEmptyString(value: unknown): string | undefined {\n return typeof value === 'string' && value.trim() !== '' ? value : undefined;\n}\n\n/**\n * Formats an error thrown by `backendSrv.fetch` (or a network failure) into a\n * concise human-readable reason. BackendSrv rejects with a FetchError-shaped\n * object (`{ status, statusText, data }`) rather than an `Error`, so the raw\n * `message` is usually absent; prefer the server-provided message, then the\n * HTTP status, then any thrown message.\n */\nexport function describeTermsError(err: unknown): string {\n if (err && typeof err === 'object') {\n // The shape is not guaranteed (servers can return any JSON), so only use string fields.\n // Otherwise a non-string `message` would break the return type or render as \"[object Object]\".\n const e = err as {\n status?: unknown;\n statusText?: unknown;\n data?: { message?: unknown; error?: unknown } | null;\n message?: unknown;\n };\n const status = typeof e.status === 'number' ? e.status : undefined;\n const serverMessage = nonEmptyString(e.data?.message) ?? nonEmptyString(e.data?.error);\n if (serverMessage) {\n return status ? `${serverMessage} (HTTP ${status})` : serverMessage;\n }\n if (status !== undefined) {\n const statusText = nonEmptyString(e.statusText);\n return `Request failed with HTTP ${status}${statusText ? ` ${statusText}` : ''}`;\n }\n const message = nonEmptyString(e.message);\n if (message) {\n return message;\n }\n }\n const message = nonEmptyString(err);\n if (message) {\n return message;\n }\n return 'The terms service could not be reached.';\n}\n\n/**\n * Checks whether terms and conditions are accepted and up-to-date.\n * This function verifies that:\n * 1. Terms have been accepted\n * 2. The accepted version matches or exceeds the current version\n *\n * @returns A promise that resolves to `true` if terms are accepted and up-to-date, `false` otherwise\n * @throws Error if the API call fails\n *\n * @example\n * ```typescript\n * import { checkTerms } from '@grafana/assistant';\n *\n * const accepted = await checkTerms();\n * if (!accepted) {\n * // Show terms acceptance UI\n * console.log('Terms need to be accepted');\n * }\n * ```\n */\nexport async function checkTerms(): Promise<boolean> {\n try {\n const result = await fetchTermsData();\n return result.accepted;\n } catch (error) {\n // If API call fails, throw the error so callers can handle it\n // BackendSrv rejects with a FetchError-shaped object, so `String(error)` would render\n // \"[object Object]\". describeTermsError prefers the server message, then the HTTP status.\n throw new Error(`Failed to check terms requirements: ${describeTermsError(error)}`);\n }\n}\n\n/**\n * React hook to check terms and conditions acceptance status.\n * Automatically fetches terms data on mount and re-fetches when terms change\n * (via TERMS_AND_CONDITIONS_REFRESH_EVENT).\n *\n * @returns An object containing whether terms are accepted, the terms type, loading state, and error state\n *\n * @example\n * ```typescript\n * import { useTerms } from '@grafana/assistant';\n *\n * function MyComponent() {\n * const { accepted, termsType, loading, error } = useTerms();\n *\n * if (loading) return <div>Loading...</div>;\n * if (error) return <div>Error: {error}</div>;\n * return <div>Terms accepted</div>;\n * }\n * ```\n */\nexport function useTerms() {\n const [accepted, setAccepted] = useState<boolean>(false);\n const [termsType, setTermsType] = useState<TermsType | null>(null);\n const [loading, setLoading] = useState(true);\n const [error, setError] = useState<string | null>(null);\n\n useEffect(() => {\n async function fetchTerms() {\n try {\n setLoading(true);\n setError(null);\n const result = await fetchTermsData();\n setAccepted(result.accepted);\n setTermsType(result.termsType);\n } catch (err) {\n setError(describeTermsError(err));\n setAccepted(false);\n setTermsType(null);\n } finally {\n setLoading(false);\n }\n }\n\n void fetchTerms();\n\n // Listen for the refresh event to re-fetch when terms change\n const handleTermsRefresh = () => {\n void fetchTerms();\n };\n document.addEventListener(TERMS_AND_CONDITIONS_REFRESH_EVENT, handleTermsRefresh);\n return () => {\n document.removeEventListener(TERMS_AND_CONDITIONS_REFRESH_EVENT, handleTermsRefresh);\n };\n }, []);\n\n return {\n accepted,\n termsType,\n loading,\n error,\n };\n}\n","import type { ToolInvokeOptions, ToolOutput, JSONSchema, JsonObject, InlineToolRunnable } from './types';\n\n/**\n * Creates a tool with the given implementation, schema, and metadata.\n * This is a zod-free implementation that accepts JSON Schema directly and a validation function.\n *\n * @param func The function implementation for the tool\n * @param options Tool configuration options\n * @returns A tool object that can be used in the agent\n */\nexport function createTool<T>(\n func: (input: T, options: ToolInvokeOptions) => Promise<ToolOutput>,\n options: {\n name: string;\n description: string;\n inputSchema: JSONSchema; // JSON Schema directly - no zod dependency!\n validate: (input: JsonObject) => T; // Validation function - replaces zod.parse()\n metadata?: {\n explainer?: (input?: T) => string;\n [key: string]: any;\n };\n verboseParsingErrors?: boolean;\n responseFormat?: 'content_and_artifact' | string;\n }\n): InlineToolRunnable {\n const { explainer, ...metadata } = options.metadata ?? {};\n const toolObj: InlineToolRunnable = {\n name: options.name,\n description: options.description,\n inputSchema: options.inputSchema,\n metadata: explainer\n ? {\n ...metadata,\n explainer: (input: JsonObject) => explainer(input as T),\n }\n : metadata,\n responseFormat: options.responseFormat,\n verboseParsingErrors: options.verboseParsingErrors,\n async invoke(input: JsonObject, invokeOptions: ToolInvokeOptions): Promise<ToolOutput> {\n try {\n if (invokeOptions.signal?.aborted) {\n throw new Error(`Tool ${options.name} execution was aborted`);\n }\n\n // Use the provided validation function instead of zod.parse()\n const parsedInput = options.validate(input);\n const functionPromise = func(parsedInput, invokeOptions);\n const promises = [functionPromise];\n\n if (invokeOptions.signal) {\n promises.push(\n new Promise((_, reject) => {\n invokeOptions.signal?.addEventListener(\n 'abort',\n () => {\n reject(new Error(`Tool ${options.name} execution was aborted`));\n },\n { once: true }\n );\n })\n );\n }\n\n // If we have a timeout, add a promise to handle it\n if (invokeOptions.timeout && invokeOptions.timeout > 0) {\n promises.push(\n new Promise((_, reject) => {\n setTimeout(() => {\n reject(new Error(`Tool ${options.name} execution timed out after ${invokeOptions.timeout}ms`));\n }, invokeOptions.timeout);\n })\n );\n }\n\n // Race the function promise against the abort and timeout promises\n return Promise.race(promises);\n } catch (error) {\n // Handle parsing errors and wrap them in ToolError\n if (options.verboseParsingErrors) {\n console.error(`Error invoking tool ${options.name}:`, error, input);\n }\n throw error;\n }\n },\n };\n\n return toolObj;\n}\n","import { getBackendSrv } from '@grafana/runtime';\nimport { lastValueFrom } from 'rxjs';\nimport { useState, useEffect, useCallback } from 'react';\nimport { ASSISTANT_PLUGIN_ID } from '../plugin';\n\n/**\n * Event name dispatched when limits are updated via SSE.\n * Other components can listen to this event to get real-time updates.\n */\nexport const LIMITS_UPDATED_EVENT = 'grafana-assistant-limits-updated';\n\n/**\n * Detail payload for the LIMITS_UPDATED_EVENT custom event.\n */\nexport interface LimitsUpdatedEventDetail {\n count: number;\n limit: number;\n}\n\n/**\n * Result type for limits data.\n */\nexport interface LimitsData {\n /** Current prompt count for the month */\n count: number;\n /** Monthly prompt limit (0 = unlimited) */\n limit: number;\n /** Current month in YYYY-MM format */\n month: string;\n /** Whether the limit has been reached */\n isLimitReached: boolean;\n}\n\n/**\n * Internal function that fetches limits data from the API.\n */\nasync function fetchLimitsData(): Promise<LimitsData> {\n const backendSrv = getBackendSrv();\n // No appSubUrl prefix: BackendSrv strips the leading `/` so Grafana's\n // `<base href>` adds the subpath (see grafana-assistant-app/issues/6109).\n const apiUrl = `/api/plugins/${ASSISTANT_PLUGIN_ID}/resources/api/v1/usage/limits/prompt`;\n\n const response = await lastValueFrom(\n backendSrv.fetch({\n url: apiUrl,\n method: 'GET',\n showErrorAlert: false,\n })\n );\n\n // The API returns { status: \"success\", data: { total, limit, month } }\n const responseBody = response.data as { data: { total: number; limit: number; month: string } };\n const limitsData = responseBody.data;\n\n const count = limitsData.total ?? 0;\n const limit = limitsData.limit ?? 0;\n const month = limitsData.month ?? '';\n\n return {\n count,\n limit,\n month,\n isLimitReached: limit > 0 && count >= limit,\n };\n}\n\n/**\n * Checks whether the user has reached their monthly prompt limit.\n *\n * @returns A promise that resolves to `true` if limits are reached, `false` otherwise\n * @throws Error if the API call fails\n *\n * @example\n * ```typescript\n * import { checkLimits } from '@grafana/assistant';\n *\n * const data = await checkLimits();\n * if (data.isLimitReached) {\n * console.log('Monthly limit reached');\n * }\n * ```\n */\nexport async function checkLimits(): Promise<LimitsData> {\n try {\n return await fetchLimitsData();\n } catch (error) {\n throw new Error(`Failed to check limits: ${error instanceof Error ? error.message : String(error)}`);\n }\n}\n\n/**\n * React hook to check user prompt limits.\n * Automatically fetches limits data on mount and listens to real-time updates\n * via the LIMITS_UPDATED_EVENT custom event.\n *\n * @returns An object containing limit data, loading state, error state, and refetch function\n *\n * @example\n * ```typescript\n * import { useLimits } from '@grafana/assistant';\n *\n * function MyComponent() {\n * const { count, limit, isLimitReached, loading, error, refetch } = useLimits();\n *\n * if (loading) return <div>Loading...</div>;\n * if (error) return <div>Error: {error}</div>;\n * if (isLimitReached) return <div>Monthly limit reached ({count}/{limit})</div>;\n * return <div>Prompts used: {count}/{limit || 'unlimited'}</div>;\n * }\n * ```\n */\nexport function useLimits() {\n const [count, setCount] = useState<number>(0);\n const [limit, setLimit] = useState<number>(0);\n const [month, setMonth] = useState<string>('');\n const [loading, setLoading] = useState(true);\n const [error, setError] = useState<string | null>(null);\n\n const fetchLimits = useCallback(async () => {\n try {\n setLoading(true);\n setError(null);\n const result = await fetchLimitsData();\n setCount(result.count);\n setLimit(result.limit);\n setMonth(result.month);\n } catch (err) {\n const errorMessage = err instanceof Error ? err.message : 'Failed to fetch limits';\n setError(errorMessage);\n setCount(0);\n setLimit(0);\n setMonth('');\n } finally {\n setLoading(false);\n }\n }, []);\n\n // Fetch on mount\n useEffect(() => {\n void fetchLimits();\n }, [fetchLimits]);\n\n // Listen for real-time updates via custom event\n useEffect(() => {\n const handleLimitsUpdate = (event: Event) => {\n const customEvent = event as CustomEvent<LimitsUpdatedEventDetail>;\n if (customEvent.detail) {\n setCount(customEvent.detail.count);\n setLimit(customEvent.detail.limit);\n // Clear any previous error since we received valid data via SSE\n setError(null);\n }\n };\n\n window.addEventListener(LIMITS_UPDATED_EVENT, handleLimitsUpdate);\n\n return () => {\n window.removeEventListener(LIMITS_UPDATED_EVENT, handleLimitsUpdate);\n };\n }, []);\n\n // Calculate isLimitReached based on current state\n const isLimitReached = limit > 0 && count >= limit;\n\n return {\n count,\n limit,\n month,\n isLimitReached,\n loading,\n error,\n refetch: fetchLimits,\n };\n}\n","import { BusEventWithPayload } from '@grafana/data';\nimport { getAppEvents } from '@grafana/runtime';\n\nexport interface K6SetScriptContentPayload {\n scriptContent: string;\n}\n\n/**\n * Event published by grafana-assistant-app to inject a script into the currently open k6 editor.\n * The k6 app subscribes to this event and updates the editor content in place,\n * avoiding a full page navigation.\n *\n * @example\n * ```typescript\n * import { onK6SetScriptContent } from '@grafana/assistant';\n *\n * const unsubscribe = onK6SetScriptContent(({ scriptContent }) => {\n * editorRef.current?.setValue(scriptContent);\n * });\n *\n * // On unmount\n * unsubscribe();\n * ```\n */\nexport class K6SetScriptContentEvent extends BusEventWithPayload<K6SetScriptContentPayload> {\n static type = 'grafana-assistant:k6-set-script-content';\n}\n\n/**\n * Subscribe to k6 set-script-content events emitted by grafana-assistant-app.\n * Returns an unsubscribe function.\n */\nexport function onK6SetScriptContent(callback: (payload: K6SetScriptContentPayload) => void): () => void {\n const subscription = getAppEvents().subscribe(K6SetScriptContentEvent, (event) => {\n callback(event.payload);\n });\n return () => subscription.unsubscribe();\n}\n","import { BusEventWithPayload } from '@grafana/data';\nimport { getAppEvents } from '@grafana/runtime';\n\n/** Operations Grafana Assistant can ask Pathfinder to perform. */\nexport const PATHFINDER_OPERATIONS = {\n /** Reload the open guide with the given resource name. */\n refreshGuide: 'refresh-guide',\n} as const;\n\nexport type PathfinderOperation = (typeof PATHFINDER_OPERATIONS)[keyof typeof PATHFINDER_OPERATIONS];\n\nexport interface PathfinderEventPayload {\n operation: PathfinderOperation;\n /** App Platform guide resource name, the value used in `doc=api:<name>` links. */\n name: string;\n}\n\n/**\n * Event published by grafana-assistant-app to ask Pathfinder to act on a guide, for example to\n * reload one that is already open after the Assistant saved, published or unpublished it.\n * The event is one-way and only reaches the browser page where the Assistant ran.\n * Receivers should ignore operations they do not know.\n *\n * @example\n * ```typescript\n * import { onPathfinderEvent, PATHFINDER_OPERATIONS } from '@grafana/assistant';\n *\n * const unsubscribe = onPathfinderEvent(({ operation, name }) => {\n * if (operation === PATHFINDER_OPERATIONS.refreshGuide) {\n * reloadGuide(name);\n * }\n * });\n *\n * // On unmount\n * unsubscribe();\n * ```\n */\nexport class PathfinderEvent extends BusEventWithPayload<PathfinderEventPayload> {\n static type = 'grafana-assistant:pathfinder';\n}\n\n/**\n * Subscribe to Pathfinder events emitted by grafana-assistant-app.\n * Returns an unsubscribe function.\n */\nexport function onPathfinderEvent(callback: (payload: PathfinderEventPayload) => void): () => void {\n const subscription = getAppEvents().subscribe(PathfinderEvent, (event) => {\n callback(event.payload);\n });\n return () => subscription.unsubscribe();\n}\n","import type { SuggestionContext } from './suggestionContexts';\nimport type { PluginExtensionAddedFunctionConfig } from '@grafana/data';\nimport type { ComponentType, ReactNode } from 'react';\n\n/**\n * Extension point id consumed by the Grafana Assistant.\n *\n * A contributing app plugin registers a manifest function against this target via\n * `AppPlugin.addFunction()` (declared under `extensions.addedFunctions` in its `plugin.json`).\n * The Assistant discovers registrations with `usePluginFunctions()` and invokes each function to\n * obtain the plugin's {@link AssistantExtensionManifest}.\n *\n * @experimental This API is under active development and may change in future releases.\n */\nexport const ASSISTANT_EXTENSION_POINT = 'grafana-assistant-app/extension/v1';\n\n/**\n * Props passed to a `tool-details` chit component registered via {@link ChitContribution}.\n *\n * These are the normalized props every tool row in the Assistant chat track receives; a\n * registered component renders inside the expanded details area of the standard tool card,\n * in place of the generic expanded content.\n *\n * @experimental This API is under active development and may change in future releases.\n */\nexport interface ToolChitProps {\n /** The fully namespaced tool name that produced this card. */\n toolName: string;\n /** The tool call input, as sent to the tool. */\n input: unknown;\n /** The tool result, once available. `undefined` while the tool is still running. */\n result: unknown;\n /** Execution state of the tool call. */\n status: 'running' | 'success' | 'error';\n}\n\n/** Read-only inputs from tool calls in the message containing an inline component. */\nexport interface InlineChitToolCall {\n readonly toolCallId?: string;\n readonly name: string;\n /** Model-authored input; validate its shape before using it. */\n readonly input: unknown;\n}\n\nexport interface InlineChitTurn {\n /** False also covers stopped turns and history; it does not imply success. */\n readonly isStreaming: boolean;\n readonly tools: readonly InlineChitToolCall[];\n}\n\nexport interface InlineChitProps {\n children?: ReactNode;\n /** Host-supplied context, never taken from model-authored attributes. Absent on older hosts. */\n turn?: InlineChitTurn;\n /** Sanitized `name` attribute, useful for a plugin-defined filter or identifier. */\n name?: string;\n}\n\nexport const InlineChitDisplay = { Inline: 'inline', Block: 'block' } as const;\nexport type InlineChitDisplay = (typeof InlineChitDisplay)[keyof typeof InlineChitDisplay];\n\n/**\n * A contribution to the Assistant chat track (\"chits\"): either an expanded-details renderer\n * keyed by tool name, or a component rendered in place of a tag inside assistant text.\n *\n * - `tool-details`: renders inside the expanded details area of the standard tool card for the\n * listed tool names, replacing the generic expanded content (Query/Result). The compact tool\n * row, its status, and the Allow/Deny confirmation flow are always built in — a plugin never\n * replaces the tool row and never renders while a confirmation is pending. A plugin may only\n * register details for tools it owns (tool names are namespaced by the tool pipeline and\n * checked against the contributing plugin id).\n * - `inline`: registers a component rendered in place of a custom tag inside assistant message\n * text. The full tag name is the plugin id with non-alphanumerics collapsed to underscores,\n * followed by an underscore and `name` — for example plugin `grafana-k6-app` with\n * `name: 'result'` renders `<grafana_k6_app_result>…</grafana_k6_app_result>`. Tag children\n * and allow-listed attributes are passed through as props, alongside host-owned turn context.\n * Optional `prompt` guidance teaches the model when to emit the tag through chat context.\n *\n * Component and function references are the only non-JSON-serializable parts of a manifest —\n * refer to {@link AssistantExtensionManifest} for the serializability contract.\n *\n * @experimental This API is under active development and may change in future releases.\n */\nexport type ChitContribution =\n | {\n kind: 'tool-details';\n /** Fully namespaced tool names this details renderer applies to. Must be owned by the contributing plugin. */\n toolNames: string[];\n /** The details component, rendered inside a per-chit error boundary. */\n component: ComponentType<ToolChitProps>;\n }\n | {\n kind: 'inline';\n /** Plugin-local tag suffix: lowercase, `[a-z][a-z0-9]*`. Namespaced by the plugin id into the full tag name. */\n name: string;\n /** Optional component usage guidance (up to 4096 UTF-8 bytes), sent as attributed chat context, not a system prompt or mode. */\n prompt?: string;\n /** A childless marker. Recover saved bare/backticked opening tags and suppress identical duplicates outside code. */\n selfClosing?: boolean;\n /** Defaults to inline. Block requires selfClosing: true and renders below the message text, outside Markdown paragraphs. */\n display?: InlineChitDisplay;\n /** Rendered in place of the tag, inside a per-chit error boundary. Receives tag children and allow-listed attributes as props. */\n component: ComponentType<InlineChitProps>;\n };\n\n/**\n * The artifact file node handed to plugin artifact renderers and toolbars.\n *\n * Intentionally minimal and forward-compatible: renderers must treat this as the complete\n * artifact surface and must not fetch artifact content from anywhere else.\n *\n * @experimental This API is under active development and may change in future releases.\n */\nexport interface AssistantArtifactNode {\n /** Opaque host identity. Stable across chat draft edits/renames, scoped to the chat.\n * Mounted resources use namespace/path identity. Absent on hosts without identity context.\n * Never use this as authorization or parse its internal format.\n */\n id?: string;\n /** Current, authorized live-resource metadata. Absent for chat-owned drafts. */\n resource?: { namespace: string; revision?: string; url?: string };\n /** File path of the artifact in the conversation's artifact filesystem. */\n path: string;\n /** The artifact kind extension, e.g. `.grafana-k6-app.test`. */\n ext: string;\n /** The artifact content. Shape is owned by the contributing plugin's `validate` contract. */\n data: unknown;\n /**\n * Monotonically increasing per-artifact write counter. Increments on every write to this\n * artifact. Suitable for memoization keys, cache-busting, and change detection. NOT a\n * timestamp — carries no wall-clock meaning.\n */\n revision: number;\n /** Opaque backend revision for mounted files; use for cache keys when present. */\n resourceRevision?: string;\n}\n\n/**\n * Read-only access to every artifact in the conversation, including built-in and other\n * plugins' files. Use this handle and the supplied node for artifact content. Writes and\n * edits go through the Assistant's validated `artifact_files` tool.\n *\n * @experimental This API is under active development and may change in future releases.\n */\nexport interface AssistantArtifactFs {\n /** All artifacts in the conversation, in stable path order. */\n list(): AssistantArtifactNode[];\n /** Read one artifact by exact normalized path. */\n read(path: string): AssistantArtifactNode | undefined;\n /** Whether an artifact exists at the path. */\n has(path: string): boolean;\n}\n\n/**\n * Props passed to a plugin artifact renderer.\n *\n * @experimental This API is under active development and may change in future releases.\n */\n/** Prefills the owning conversation. The user reviews and sends the turn. */\nexport type ArtifactRequestEdit = (input: { message: string }) => void;\n\nexport interface ArtifactRendererProps {\n /** The artifact node to render. */\n node: AssistantArtifactNode;\n /** Read-only handle over the conversation's artifact filesystem. */\n fs: AssistantArtifactFs;\n /** Available in a conversation. Appends text and this artifact's path to the composer,\n * preserves existing input, and focuses it. Never sends or writes automatically.\n * Call only from an explicit user action. Hide edit actions when absent.\n */\n requestEdit?: ArtifactRequestEdit;\n /** Normalized validation for this revision. Recheck readiness before saving or running. */\n validation?: { valid: boolean; ready?: boolean; issues: ArtifactValidationIssue[] };\n}\n\n/**\n * Props passed to an optional plugin artifact toolbar.\n *\n * @experimental This API is under active development and may change in future releases.\n */\nexport interface ArtifactToolbarProps {\n /** The artifact node the toolbar acts on. */\n node: AssistantArtifactNode;\n /** Read-only handle over the conversation's artifact filesystem. */\n fs: AssistantArtifactFs;\n /** Available in a conversation. Appends text and this artifact's path to the composer,\n * preserves existing input, and focuses it. Never sends or writes automatically.\n * Call only from an explicit user action. Hide edit actions when absent.\n */\n requestEdit?: ArtifactRequestEdit;\n /** Normalized validation for this revision. Recheck readiness before saving or running. */\n validation?: { valid: boolean; ready?: boolean; issues: ArtifactValidationIssue[] };\n}\n\n/**\n * A plugin-contributed artifact kind for the Assistant canvas.\n *\n * The `ext` is double-dot namespaced as `.{pluginId}.{kind}`, where `pluginId` is your full,\n * exact plugin id — for example `.grafana-k6-app.test`, not a shortened slug. This keeps plugin\n * kinds out of the built-in single-dot space and keeps orphaned artifacts attributable to their\n * owning plugin without a live registry, since the plugin id is readable from the artifact path.\n *\n * Everything except `validate`, `renderer`, and `toolbar` is JSON-serializable — refer to\n * {@link AssistantExtensionManifest} for the serializability contract.\n *\n * @experimental This API is under active development and may change in future releases.\n */\nexport interface ArtifactValidationIssue {\n /** Field path owned by the plugin, for example steps[2].inputs.channel. */\n path: string;\n /** Actionable feedback. Never include credentials or other sensitive values. */\n message: string;\n}\n\n/** valid controls draft writes/rendering. ready is advisory and never authorizes a save or run. */\nexport type ArtifactValidationResult =\n | boolean\n | {\n valid: boolean;\n ready?: boolean;\n issues: ArtifactValidationIssue[];\n };\n\nexport interface ArtifactKindContribution {\n /** Artifact extension in the form `.{pluginId}.{kind}` (exact plugin id), double-dot namespaced. */\n ext: `.${string}.${string}`;\n /** Human-readable label shown on artifact tabs and cards. */\n label: string;\n /** Icon name. The current host displays a generic plugin icon instead. */\n icon: string;\n /**\n * Sort order among plugin kinds, ascending. The host clamps negative values to zero\n * and places plugin kinds after built-ins. Ties use the most recently updated artifact.\n */\n tabPriority: number;\n /** Content validator. Accept with true or { valid: true, issues: [...] }. */\n validate(data: unknown): ArtifactValidationResult;\n /** Relative paths in this plugin's filesystem, discovered before authoring. */\n instructionsPath?: string;\n schemaPath?: string;\n /** Renders the artifact in the canvas. Receives the artifact node and a read-only conversation filesystem handle. */\n renderer: ComponentType<ArtifactRendererProps>;\n /** Optional toolbar rendered above the artifact. */\n toolbar?: ComponentType<ArtifactToolbarProps>;\n /** Reserved hint. Accepted by the host but not currently sent to the model. */\n promptHint?: string;\n}\n\n/** JSON or text stored by a plugin filesystem. Binary files are not supported. */\nexport type AssistantFileContent =\n | null\n | boolean\n | number\n | string\n | AssistantFileContent[]\n | { [key: string]: AssistantFileContent };\n\n/** Paths are relative to the plugin mount, without a leading slash or traversal segments. */\nexport interface AssistantFilesystemFile {\n path: string;\n content: AssistantFileContent;\n /** Opaque backend revision, used for conditional writes. */\n revision: string;\n title?: string;\n /** Optional Grafana-local native page under /a/<registered-plugin-id>/. */\n url?: string;\n}\n\nexport interface AssistantFilesystemListInput {\n /** Relative directory; empty string lists the mount root. */\n path: string;\n filter?: { type?: string; title?: string };\n limit: number;\n offset: number;\n}\n\nexport interface AssistantFilesystemListResult {\n /** Authorized files only, filtered then sorted by relative path before pagination. */\n items: Array<{ path: string; title?: string }>;\n hasMore: boolean;\n}\n\n/**\n * A live filesystem mounted at /plugins/<registered-plugin-id>/ by the host.\n * All callbacks run in the browser under the current caller. The owning backend must\n * enforce authorization for every operation; chat access grants no resource permission.\n * Paths and namespace are routing context, never authorization assertions.\n * Missing/denied reads reject. No callback may return content from a different namespace.\n * Keep callbacks stable and independent of `this`, like other manifest callbacks.\n *\n * Ordinary text/JSON files are tool-accessible. Files with the plugin's registered artifact\n * extensions can also attach to the canvas. No content is reconstructed from chat inputs.\n * @experimental\n */\nexport interface AssistantFilesystemContribution {\n /** Optional Markdown instructions exposed read-only at the mount's AGENT.md (max 32 KiB). */\n agentGuide?: string;\n read(namespace: string, path: string): Promise<AssistantFilesystemFile>;\n list(namespace: string, input: AssistantFilesystemListInput): Promise<AssistantFilesystemListResult>;\n /** Metadata only; undefined means missing or inaccessible. Other failures reject. */\n metadata(namespace: string, path: string): Promise<{ title?: string } | undefined>;\n /** Atomic create: assign and return a relative path; rejection means nothing was created. */\n create?(namespace: string, content: AssistantFileContent): Promise<AssistantFilesystemFile>;\n /** Update an existing file only, enforcing the supplied revision atomically in storage. */\n write?(\n namespace: string,\n path: string,\n content: AssistantFileContent,\n revision: string\n ): Promise<AssistantFilesystemFile>;\n}\n\n/**\n * Reserved availability conditions for plugin modes.\n * The current plugin-mode adapter does not apply these conditions.\n *\n * @experimental This API is under active development and may change in future releases.\n */\nexport type PromptContributionAvailability = 'not-oss' | 'not-trial';\n\n/**\n * A plugin-contributed Assistant mode (system prompt variant).\n *\n * The contribution is exposed in the mode picker as `${pluginId}:${modeId}` and its prompt text\n * is always rendered inside an attributed `<plugin_contribution>` wrapper, subject to a\n * 16 KiB UTF-8 body limit and an assistant-side allowlist.\n *\n * The current host applies modeId, label, description, compose, and prompt only. Other\n * fields are accepted but not applied; don't use them to enforce tool or access restrictions.\n *\n * All fields are JSON-serializable — refer to {@link AssistantExtensionManifest} for the\n * serializability contract.\n *\n * @experimental This API is under active development and may change in future releases.\n */\nexport interface PromptContribution {\n /** Plugin-local mode id. Exposed to users as `${pluginId}:${modeId}`. */\n modeId: string;\n /** Human-readable mode label shown in the mode picker. */\n label: string;\n /** Short description of the mode shown in the mode picker. */\n description: string;\n /** Intended suggestion guidance. Required by the schema, but not currently applied by the host. */\n whenToUse: string;\n /**\n * How `prompt` composes with the base system prompt.\n *\n * - `prepend` / `append`: `prompt` is added before / after the base guidance, which is\n * otherwise kept intact.\n * - `replace`: the rest of the base guidance is dropped, but the Assistant's identity section\n * is ALWAYS retained — the composed prompt is the identity block, then the current-mode\n * block, then the attributed plugin body. A plugin never controls or replaces the\n * Assistant's identity.\n *\n * Prefer `prepend` or `append` unless the mode is a genuinely self-contained specialist that\n * needs none of the base guidance.\n */\n compose: 'prepend' | 'append' | 'replace';\n /**\n * The prompt snippet (`prepend`/`append`) or specialist body (`replace`). With `replace`, this\n * body is composed after the Assistant's always-retained identity section — refer to\n * {@link PromptContribution.compose}.\n */\n prompt: string;\n /** Reserved first-message text. The current host does not send it. */\n initialMessage?: string;\n /** Reserved switching preference. The current host does not apply it. */\n switchable?: boolean;\n /** Reserved availability conditions. The current host does not evaluate them for plugin modes. */\n availability?: PromptContributionAvailability[];\n /** Reserved tool scoping. The current host does not restrict tools using this field. */\n modeToolNames?: string[];\n /** Reserved icon name. The current host displays a generic plugin icon. */\n icon?: string;\n /** Reserved badge. The current host does not apply it. */\n featureState?: 'preview' | 'experimental';\n}\n\n/**\n * A proposed first message on empty Assistant chats, attributed to your plugin.\n * Selecting it sends `message` as a visible user message. Requires the extensions master\n * flag and an enabled plugin; no prompt flag or allowlist is needed.\n *\n * The host keeps the first 3 valid entries. Over-length entries are dropped, not truncated.\n * Use `contexts` to participate in route-relevant selection, or `provideQuestions`\n * for suggestions tied to a page where your plugin runs.\n *\n * @experimental This API is under active development and may change in future releases.\n */\nexport interface AssistantStarter {\n /** Optional short label shown on the starter; defaults to the message itself. Max 80 characters. */\n label?: string;\n /** The user message sent, visibly and as-is, when the starter is selected. Max 500 characters. */\n message: string;\n /** Eligible on any listed route context. Omitted: only this plugin's /a/<pluginId> routes.\n * An empty list disables the starter. Eligible starters compete with built-in suggestions.\n */\n contexts?: readonly SuggestionContext[];\n}\n\n/**\n * A plugin workflow with a read-only listing on the Assistant's Skills settings page.\n * The catalog and loader that deliver content to the model are not implemented yet.\n * Proposed activation requires trusted server integration and a supported runtime surface.\n * Automatic discovery would also require a short author hint (`whenToUse`), not yet in this\n * interface. Existing manifests remain valid and would be manual-only without a hint once\n * manual activation ships; enabling the builtin runtime does not activate plugin registrations.\n *\n * The host assigns the handle `plugin:{pluginId}:{id}` using the registered plugin ID.\n * Plugin skills are not saved as tenant skills or indexed for search. Removing a\n * registration removes its skills. The prompt flag and allowlist don't gate registration.\n *\n * The host keeps the first 5 valid, unique IDs and drops entries that exceed field limits.\n *\n * @experimental This API is under active development and may change in future releases.\n */\nexport interface SkillContribution {\n /** Plugin-local skill id: `[a-z][a-z0-9-]*`, max 64 characters. Namespaced by the plugin id into the catalog handle. */\n id: string;\n /** Nonblank title shown in settings. Max 80 characters. */\n title: string;\n /** One or two sentences describing what the skill does and when to use it. Max 500 characters. */\n description: string;\n /** Nonblank Markdown body. Model loading is not implemented yet. Max 32768 UTF-8 bytes. */\n content: string;\n}\n\n/**\n * Contributions from one Grafana app plugin to the Assistant sidebar and workspace.\n * Register with {@link getAssistantExtensionConfig} and declare the matching target in\n * `plugin.json`. Keep the manifest stable after registration.\n *\n * Fields must be JSON-serializable except components and callbacks (`component`,\n * `validate`, `renderer`, `toolbar`, and filesystem callbacks). Unknown fields are ignored. Unknown contribution\n * kinds and malformed entries are dropped; an unknown schemaVersion rejects the manifest.\n *\n * @experimental This API is under active development and may change in future releases.\n */\nexport interface AssistantExtensionManifest {\n /** Manifest schema version. Always 1 for this SDK version. */\n schemaVersion: 1;\n /** Chat-track contributions: tool-details renderers and inline components. */\n chits?: ChitContribution[];\n /** Proposed first messages on empty chats, attributed to the plugin. Max 3 valid entries. */\n starters?: AssistantStarter[];\n /** Plugin workflows listed in settings. Model loading is not implemented yet. Max 5 valid entries. */\n skills?: SkillContribution[];\n /** Canvas artifact kinds. */\n artifactKinds?: ArtifactKindContribution[];\n /** Optional persistent filesystem, mounted under the registering plugin ID. */\n filesystem?: AssistantFilesystemContribution;\n /** Assistant mode / system prompt contributions. */\n promptContributions?: PromptContribution[];\n}\n\n/**\n * Builds the function registration for {@link ASSISTANT_EXTENSION_POINT}.\n * Also declare the target in `plugin.json` under `extensions.addedFunctions`. Use\n * `preload: true` for Grafana 12.1 compatibility with function-only contributions.\n *\n * The returned function reuses `manifest`. Don't mutate it after registration; define\n * components and callbacks outside React renders so their references stay stable.\n *\n * @example\n * ```typescript\n * import { AppPlugin } from '@grafana/data';\n * import { getAssistantExtensionConfig } from '@grafana/assistant';\n *\n * export const plugin = new AppPlugin().addFunction(\n * getAssistantExtensionConfig({\n * schemaVersion: 1,\n * starters: [{ message: 'Help me review recent service errors in this stack.' }],\n * })\n * );\n * ```\n *\n * @experimental This API is under active development and may change in future releases.\n */\nexport function getAssistantExtensionConfig(\n manifest: AssistantExtensionManifest\n): PluginExtensionAddedFunctionConfig<() => AssistantExtensionManifest> {\n return {\n title: 'assistant-extension',\n description:\n 'Contributes chits, starters, skills, artifact kinds, and prompt contributions to the Grafana Assistant.',\n targets: [ASSISTANT_EXTENSION_POINT],\n fn: () => manifest,\n };\n}\n","export const SuggestionContext = {\n Home: '/',\n CloudHome: '/a/cloud-home-app',\n Workspace: '/a/grafana-assistant-app/workspace',\n Dashboard: '/d',\n Dashboards: '/dashboards',\n Alerting: '/alerting',\n AlertRules: '/alerting/list',\n AlertRule: '/alerting/grafana/:uid/view',\n Notifications: '/alerting/notifications',\n Silences: '/alerting/silences',\n Connections: '/connections',\n DataSources: '/connections/datasources',\n Explore: '/explore',\n Drilldown: '/drilldown',\n Metrics: '/a/grafana-metricsdrilldown-app/drilldown',\n Logs: '/a/grafana-lokiexplore-app/explore',\n Traces: '/a/grafana-exploretraces-app',\n Profiles: '/a/grafana-pyroscope-app/explore',\n SQL: '/a/grafana-sqldrilldown-app/explore',\n Admin: '/admin',\n Users: '/admin/users',\n Organization: '/org',\n Teams: '/org/teams',\n ServiceAccounts: '/org/serviceaccounts',\n Notebooks: '/notebooks',\n Notebook: '/notebooks/:uid',\n NewNotebook: '/notebooks/new',\n Pages: '/a/grafana-assistant-app/pages',\n Page: '/a/grafana-assistant-app/pages/:id',\n PageTemplates: '/a/grafana-assistant-app/pages/templates',\n NewPage: '/a/grafana-assistant-app/pages/new',\n Costs: '/a/grafana-cmab-app',\n} as const;\n\nexport type SuggestionContext = (typeof SuggestionContext)[keyof typeof SuggestionContext];\n"],"names":["__webpack_require__","exports","definition","key","o","Object","defineProperty","enumerable","get","obj","prop","prototype","hasOwnProperty","call","Symbol","toStringTag","value","hash","input","i","length","charCodeAt","toString","NodeData","constructor","params","text","this","id","type","bypassLimits","formatForLLM","codeElementIds","data","name","equals","other","StructuredNodeData","super","JSON","stringify","agentSkillNodeId","reference","selectionId","AgentSkillNodeData","displayName","providerId","handle","revision","require","GLOBAL_REGISTRY_KEY","REGISTRY_CHANGE_EVENT","LEGACY_REGISTRY_UPDATE_EVENT","LEGACY_REGISTRY_REMOVE_EVENT","LEGACY_REGISTRY_SYNC_EVENT","getPageContextRegistry","window","setPageContextRegistry","newRegistry","skipLegacyEvents","dispatchEvent","CustomEvent","detail","registry","legacyBridgeInitialized","providePageContext","urlPattern","initialContext","pattern","RegExp","source","trim","console","warn","registration","generateRegistrationId","context","setContext","newContext","currentRegistry","index","findIndex","reg","unregister","filter","_","addEventListener","event","existingIndex","r","incomingRegistry","Array","isArray","currentIds","Set","map","newRegistrations","has","empty","useProvidePageContext","setContextRef","useRef","undefined","pendingUpdate","isModified","useEffect","current","contextToUse","useCallback","getActivePageContext","currentUrl","activeContext","matchesUrlPattern","push","usePageContext","options","allowQuestions","allowComponents","location","useLocationService","initialPathname","getLocation","pathname","pageContext","setPageContext","useState","currentPathnameRef","updateContext","handleRegistryChange","locationSub","getLocationObservable","subscribe","loc","unsubscribe","removeEventListener","filteredContext","item","node","prefix","Date","now","Math","random","slice","url","test","regexPattern","replace","ComponentNodeData","namespace","keys","components","join","prompt","usePageComponents","useMemo","allComponents","componentData","componentName","component","entries","provideComponents","flags","createAssistantContextItem","setter","newComponents","newPrompt","globalComponents","promptContext","DashboardNodeData","dashboardUid","dashboardTitle","folderUid","folderTitle","FolderNodeData","DatasourceNodeData","datasourceUid","datasourceType","datasourceName","img","uid","EntityNodeData","scope","env","site","Boolean","title","hidden","icon","entityType","properties","LabelNameNodeData","labelName","LabelValueNodeData","labelValue","operator","getDatasourceMeta","datasourceInstance","getDataSourceSrv","getInstanceSettings","meta","info","logos","small","defaultIcons","datasource","label_name","label_value","dashboard","dashboard_folder","unknown","structured","entity","skill","agent_skill","nodeData","error","createContextByType","defaultTitle","getTitleFromContextNode","getImgFromContextNode","navigable","selectable","occurrences","SkillNodeData","skillId","skillName","provideQuestions","initialQuestions","registrationId","convertQuestionsToContext","questions","question","setQuestions","newQuestions","useProvideQuestions","useQuestions","convertContextToQuestions","contextItems","CALLBACK_EXTENSION_POINT","newFunctionNamespace","functions","getExposeAssistantFunctionsConfig","namespaces","targets","fn","ASSISTANT_PLUGIN_ID","ASSISTANT_PLUGIN_TITLE","MAX_RETRY_ATTEMPTS","INITIAL_RETRY_DELAY","MAX_RETRY_DELAY","isAssistantAvailable","getObservablePluginLinks","defer","extensionPointId","pipe","links","some","link","pluginId","throwError","retry","count","delay","retryCount","errorMessage","message","toLowerCase","includes","delayMs","min","timer","catchError","of","OpenExtensionSidebarEvent","BusEventWithPayload","CloseExtensionSidebarEvent","BusEventBase","ToggleExtensionSidebarEvent","toSidebarProps","props","namesAgentSkill","agentSkillInvocationName","initialRequestId","crypto","getRandomValues","Uint32Array","initialPrompt","initialAutoSend","autoSend","origin","initialMode","mode","chatId","appendContext","initialAgentSkillInvocationName","openAssistant","reportInteraction","from","componentTitle","getAppEvents","publish","openExtensionSidebar","closeAssistant","closeExtensionSidebar","toggleAssistant","toggleExtensionSidebar","useAssistant","available","setAvailable","sub","isAvailable","isLoading","OpenAssistantButton","OpenAssistantButtonView","size","iconOnlyButton","onClick","styles","useStyles2","getStyles","IconButton","variant","className","tooltip","Button","fill","button","theme","baseBackground","colors","secondary","main","elevatedBackground","emphasize","underlyingColor","background","canvas","outerRadius","shape","radius","default","innerRadius","gradientBorderLayer","content","position","inset","borderRadius","cornerShape","zIndex","pointerEvents","solidBackgroundLayer","transition","css","label","width","maxWidth","isolation","border","padding","spacing","defaultDropdownButtonWidths","sm","md","lg","OpenAssistantSplitButton","OpenAssistantSplitButtonView","menuItems","dropdownButtonWidth","hasMenuItems","resolvedDropdownButtonWidth","wrapperContent","wrapper","ButtonGroup","buttonGroup","cx","segmentButton","mainButtonSplit","mainButtonSolo","Dropdown","overlay","dropdownButton","style","minWidth","Tooltip","dividerColor","weak","display","gap","overflow","boxShadow","borderTopLeftRadius","borderBottomLeftRadius","borderTopRightRadius","borderBottomRightRadius","alignItems","justifyContent","margin","getBackgroundGradientColors","defaultGradientColors","isThemeWithoutGradients","matches","gradients","brandHorizontal","match","createBorderAnimation","backgroundColor","color1","color2","animationSteps","animationFrames","gradientColor1","gradientColor2","finalColor1","finalColor2","step","backgroundImage","GLOBAL_FACTORY_KEY","GLOBAL_INITIALIZER_KEY","GLOBAL_INITIALIZATION_PROMISE_KEY","setInlineAssistantFactory","existing","setInlineAssistantInitializer","async","ensureInlineAssistantInitialized","initializer","Error","existingPromise","initPromise","err","getInlineAssistantFactory","factory","nestedErrorKeys","getStringValue","trimmedValue","extractNestedErrorMessage","visited","directString","nestedErrorMessage","cause","fromEntries","add","errorRecord","nestedDataMessage","nestedMessage","status","statusText","nestedMessages","extractErrorMessage","String","useInlineAssistant","config","isGenerating","setIsGenerating","setContent","setError","assistantRef","configRef","reset","cancel","generate","sendPrompt","agentName","agentId","systemPrompt","tools","onStart","onDelta","delta","prev","onComplete","onError","dispose","useAIGeneration","onChange","disabled","autoGenerate","streaming","getUserPrompt","hasAutoGenerated","valueBeforeGeneration","getUserPromptRef","displayValue","isSendDisabled","doGenerate","catch","maybeAutoGenerateRef","handleGenerate","GENERATING_PHRASES","useGeneratingPlaceholder","defaultPlaceholder","phrase","setPhrase","wasGenerating","next","floor","AITextInput","placeholder","dataTestId","activePlaceholder","addonAfter","animatedWrapper","Input","onKeyDown","e","metaKey","ctrlKey","preventDefault","currentTarget","suffix","invalid","primary","borderAnimation","keyframes","backgroundOrigin","backgroundClip","animation","AITextArea","rows","effectiveRows","max","textareaWrapper","TextArea","textarea","sendButton","paddingRight","minHeight","scrollbarWidth","right","top","queryIsEmpty","query","dataQueryProps","QueryWithAssistantButton","currentQuery","queries","dataSourceInstanceSettings","app","datasourceApi","CoreApp","Unknown","hasCurrentQuery","otherQueries","q","refId","queryDisplayText","getQueryDisplayText","isUpdating","actionText","codeBlockLines","actionableSentence","DEFAULT_EXAMPLE_PROMPTS","AssistantPromptCard","AssistantPromptCardView","examplePrompts","animated","onClose","onSubmit","setPrompt","inputRef","staticPlaceholder","animatedPlaceholder","prompts","hasUserInput","setDisplay","indexRef","charRef","phaseRef","timeoutId","schedule","setTimeout","currentPrompt","tick","clearTimeout","useAnimatedPlaceholder","rafId","requestAnimationFrame","focus","cancelAnimationFrame","submit","trimmed","card","cardStatic","role","inputRow","ref","shiftKey","getGlowShadow","isDark","cardBase","flexDirection","transitions","handleMotion","elevated","LENS_ERROR_CODES","InvestigationLensRequestError","code","toInvestigationLensError","GLOBAL_IMPLEMENTATION_KEY","setInvestigationLensImplementation","setInvestigationLensInitializer","ensureInvestigationLensInitialized","getInvestigationLensImplementation","implementation","useInvestigationThroughLens","schema","investigationId","enabled","refreshOnEnable","state","setState","schemaJson","generation","setGeneration","bypassCache","consumedGenerationRef","wasEnabledRef","refresh","g","wasEnabled","cancelled","bypassFromRefresh","parse","getEnumValues","numericValues","values","v","k","indexOf","joinValues","array","separator","val","stringifyPrimitive","jsonStringifyReplacer","Cached","getter","_getter","_value","cached","cleanRegex","start","startsWith","end","endsWith","assignProp","target","writable","configurable","rawShape","def","desc","getOwnPropertyDescriptor","raw","sourceShape","_zod","deferProp","putProp","mirrorShape","wrap","mergeDefs","defs","mergedDescriptors","descriptors","getOwnPropertyDescriptors","assign","defineProperties","esc","str","captureStackTrace","_args","globalConfig","jitless","navigator","userAgent","Function","isPlainObject","ctor","prot","shallowClone","Map","propertyKeyTypes","escapeRegex","clone","inst","cl","constr","parent","normalizeParams","_params","NUMBER_FORMAT_RANGES","safeint","Number","MIN_SAFE_INTEGER","MAX_SAFE_INTEGER","int32","uint32","float32","float64","MAX_VALUE","BIGINT_FORMAT_RANGES","int64","BigInt","uint64","maskedKeys","mask","Reflect","ownKeys","extended","newShape","mirrorProps","partial","Class","checks","selected","innerType","aborted","x","startIndex","issues","continue","explicitlyAborted","prefixIssues","path","iss","_a","unshift","unwrapMessage","sizeCaps","defChecks","caps","ch","d","check","maximum","attachSchema","finalizeIssue","ctx","traits","schemaError","customError","localeError","full","reportInput","highSurrogate","codePointLength","units","getLengthableOrigin","args","own","hide","derived","computes","table","compute","set","defineBound","proto","bind","installing","broke","breaker","defineLazyInternal","getPrototypeOf","outer","constantCatch","_zodDesc","_E","$constructor","Internals","protoMembers","initialized","WeakSet","init","ctorProto","up","Parent","Definition","E","saved","stackTraceLimit","newError","deferred","pp","globalThis","__zod_globalConfig","postProcessor","hasInstance","$ZodAsyncError","$ZodEncodeError","newConfig","$ZodCyclicError","STATE","NO_ISSUES","isRef","cloneIssues","recursive","WeakMap","isRecursive","stack","resolve","result","child","answer","merge","sh","catchall","element","el","items","rest","keyType","valueType","left","in","out","output","inner","_cachedInner","delete","settle","handoff","memo","alloc","_inst","payload","bucket","entry","guard","base","wrapped","direction","backEdges","isBackEdge","run","attach","isRecursiveInst","lastCtx","lastBucket","rechecked","walked","buckets","bucketFor","hit","depth","pop","Promise","then","cuid","cuid2","ulid","xid","ksuid","nanoid","duration","guid","uuid","version","email","ipv4","ipv6","cidrv4","cidrv6","httpProtocol","e164","dateSource","date","timeSource","hhmm","precision","seconds","anyString","integer","number","lowercase","uppercase","$ZodCheck","onattach","_whenHasLength","numericOriginMap","bigint","object","$ZodCheckLessThan","inclusive","getTime","abort","$ZodCheckGreaterThan","minimum","$ZodCheckMultipleOf","ratio","roundedRatio","round","tolerance","EPSILON","abs","divisor","$ZodCheckNumberFormat","format","isInt","isInteger","expected","isSafeInteger","note","$ZodCheckMaxLength","when","$ZodCheckMinLength","$ZodCheckLengthEquals","tooBig","exact","$ZodCheckStringFormat","_b","lastIndex","$ZodCheckRegex","$ZodCheckLowerCase","$ZodCheckUpperCase","$ZodCheckIncludes","escapedRegex","$ZodCheckStartsWith","$ZodCheckEndsWith","$ZodCheckOverwrite","tx","Doc","closed","indent","indented","write","arg","execution","lines","split","minIndent","trimStart","dedented","repeat","line","compile","F","major","minor","patch","$ZodType","bag","runChecks","asyncResult","isAborted","currLen","handleCanaryResult","canary","checkResult","skipChecks","standardProps","toStandardResult","validate","validateAsync","vendor","$ZodString","coerce","$ZodStringFormat","$ZodGUID","$ZodUUID","v1","v2","v3","v4","v5","v6","v7","v8","$ZodEmail","canParseURL","URL","canParse","asciiTabOrNewline","stripTabAndNewline","$ZodURL","normalize","protocol","URLStatic","parseURLObject","validateURL","hostname","urlHostnameOk","urlProtocolOk","href","$ZodEmoji","$ZodNanoID","$ZodCUID","$ZodCUID2","$ZodULID","$ZodXID","$ZodKSUID","$ZodISODateTime","opts","offset","qualified","timeRegex","local","$ZodISODate","$ZodISOTime","$ZodISODuration","$ZodIPv4","ipv6Alphabet","isValidIPv6","$ZodIPv6","$ZodCIDRv4","$ZodCIDRv6","parts","address","prefixNum","isValidCIDRv6","isValidBase64","atob","base64Charset","$ZodBase64","base64urlCharset","$ZodBase64URL","base64","c","padEnd","ceil","isValidBase64URL","$ZodE164","$ZodJWT","token","algorithm","tokensParts","header","parsedHeader","typ","alg","isValidJWT","$ZodNumber","_ctx","isNaN","isFinite","received","$ZodNumberFormat","$ZodBoolean","$ZodUnknown","$ZodNever","arraySize","handleArrayResult","final","$ZodArray","memoizer","proms","abortEarly","all","cap","n","capSize","handlePropertyResult","optin","optout","isPresent","isOptionalOut","NO_SYMBOL_KEYS","normalizeDef","ownSymbols","getOwnPropertySymbols","symbolKeys","allKeys","okeys","keySet","numKeys","optionalKeys","handleCatchall","unrecognized","_catchall","t","seen","$ZodObject","newSh","_normalized","zod","propValues","field","isObject","$ZodObjectJIT","superParse","fastpass","jit","fastEnabled","normalized","syms","doc","parseStr","prefixStr","ids","create","counter","isOptionalIn","generateFastpass","handleUnionResults","results","nonaborted","errors","$ZodUnion","every","flatMap","option","patterns","p","first","$ZodIntersection","handleIntersectionResults","mergeValues","a","b","valid","bKeys","sharedKeys","newObj","__proto__","sharedValue","mergeErrorPath","newArray","unrecKeys","unrecIssue","keyIssues","collect","side","bothKeys","f","l","aggregated","merged","$ZodRecord","recordKeys","keyResult","outKey","propertyIsEnumerable","retryResult","$ZodEnum","valuesSet","patternValues","$ZodLiteral","vals","$ZodTransform","_out","transform","handleOptionalResult","$ZodOptional","$ZodExactOptional","$ZodNullable","$ZodDefault","defaultValue","handleDefaultResult","$ZodPrefault","$ZodNonOptional","handleNonOptionalResult","handleCatchResult","catchValue","$ZodCatch","$ZodPipe","handlePipeResult","$ZodReadonly","handleReadonlyResult","freeze","$ZodCustom","handleRefineResult","_iss","__zod_globalRegistry","_map","_idmap","_meta","clear","remove","pm","globalRegistry","snapshotChecks","_lt","_lte","_gt","_gte","_multipleOf","_maxLength","_minLength","_length","_overwrite","assignProps","sources","initializeContext","processors","metadataRegistry","metadata","unrepresentable","override","io","sharedDefsExtractedFor","sharedEmitDoneFor","cycles","reused","intersections","external","handleUnrepresentable","json","zodSchema","processSchema","schemaPath","cycle","overrideSchema","toJSONSchema","processJSONSchema","_json","processor","isParent","isTransforming","examples","_prefault","encodeJSONPointerSegment","segment","extractDefs","root","idToSchema","extractToDef","$ref","defId","defsSegment","externalId","uriGenerator","uri","defUriPrefix","makeURI","ext","compactTypeUnion","anyOf","types","member","FOLDABLE_KEYS","UNION_KEYS","undeclaredConstraint","extra","additionalProperties","foldObjects","members","objects","required","part","allOf","folded","constraints","constraint","foldIntersection","unions","m","union","keyword","find","branches","branch","finalize","flattenRef","_cached","refSeen","refSchema","parentSeen","jsonSchema","reverse","rewrite","carriers","$schema","$id","rootMetaId","$defs","definitions","finalized","createStandardJSONSchemaMethod","_err","_schema","libraryOptions","narrowMin","agg","narrowMax","narrowBoth","addDivisor","multipleOf","addPattern","intersectMime","mime","setFormat","minContributor","maxContributor","formatContributor","ranges","contributors","greater_than","less_than","multiple_of","number_format","bigint_format","min_length","max_length","length_equals","min_size","max_size","size_equals","string_format","contentEncoding","laxFormat","mime_type","aggregateChecks","list","exclusiveMinimum","exclusiveMaximum","formatMap","datetime","json_string","regex","exactPatterns","exactPattern","inputOptin","stringifyKeyNames","bySchema","inlined","mapped","numericType","enum","const","pendingRecords","UNREPRESENTABLE_DEFAULT","serializeDefaultValue","serialized","optionalProcessor","Sizable","string","unit","verb","file","getSizing","FormatDictionary","emoji","uuidv4","uuidv6","time","mac","base64url","currency_code","credit_card","iban","jwt","template_literal","TypeDictionary","nan","getTypeName","issue","adj","sizing","_issue","_messageDesc","internals","_issuesDesc","_installedToString","$ZodError","make","finalizeParams","callee","Err","_parse","_Err","_parseAsync","_safeParse","failure","success","_safeParseAsync","COMPILE_INVALID","for","COMPILE_FALLBACK","_encode","_decode","_encodeAsync","parseAsync","_decodeAsync","_safeEncode","_safeDecode","_safeEncodeAsync","_safeDecodeAsync","_installedErrorProtos","_lazyMethod","self","mapper","fieldErrors","_errors","processError","fullpath","curr","terminal","formErrors","ZodRealError","_ensureDefaultMemoizer","ZodType","chks","brand","register","refine","ZodCustom","superRefine","refinement","_check","addIssue","fatal","overwrite","optional","exactOptional","ZodExactOptional","nullable","nullish","nonoptional","ZodNonOptional","or","ZodUnion","and","ZodIntersection","ZodTransform","ZodDefault","prefault","ZodPrefault","ZodCatch","readonly","ZodReadonly","describe","description","isOptional","safeParse","isNullable","apply","safeParseAsync","spa","validator","definite","fallbackRun","validateFallback","encode","decode","encodeAsync","decodeAsync","safeEncode","safeDecode","safeEncodeAsync","safeDecodeAsync","createToJSONSchemaMethod","_def","_ZodString","minLength","maxLength","patternList","nonempty","form","toUpperCase","slugify","ZodString","ZodEmail","ZodURL","ZodJWT","ZodEmoji","ZodGUID","ZodUUID","uuidv7","ZodNanoID","ZodCUID","ZodCUID2","ZodULID","ZodBase64","ZodBase64URL","ZodXID","ZodKSUID","ZodIPv4","ZodIPv6","ZodCIDRv4","ZodCIDRv6","ZodE164","ZodISODateTime","ZodISODate","ZodISOTime","ZodISODuration","ZodStringFormat","ZodNumber","exMin","NEGATIVE_INFINITY","exMax","POSITIVE_INFINITY","legacy","divisors","minValue","maxValue","gt","gte","lt","lte","int","safe","positive","nonnegative","negative","nonpositive","finite","ZodNumberFormat","ZodBoolean","ZodUnknown","ZodNever","not","ZodArray","minItems","maxItems","unwrap","ZodObject","requiredKeys","sentinel","claim","keyof","ZodEnum","passthrough","loose","strict","strip","extend","incoming","existingShape","safeExtend","pick","currDef","omit","omitted","ZodOptional","exactPartial","isExclusive","oneOf","isSimpleIntersection","ZodRecord","valueSchema","patternProperties","propertyNames","pending","rewrites","record","names","rewritten","carrier","rewriteKeyNames","keyValues","omittableOnInput","validKeyValues","extract","newEntries","exclude","ZodLiteral","ZodNullable","removeDefault","removeCatch","ZodPipe","inIsTransform","in_","readOnly","baseUrl","createdSchema","statusSchema","summary","failureReason","completionQuality","degradedReason","reportSchema","reportPending","reportContent","reportSpec","elements","children","request","method","signal","throwIfAborted","response$","getBackendSrv","fetch","abortSignal","showErrorAlert","showSuccessAlert","response","firstValueFrom","fromEvent","mergeMap","reason","resourcePath","encodeURIComponent","createInvestigation","instruction","getInvestigationStatus","getInvestigationReport","refreshIntervalMs","connectTimeoutMs","envelopeSchema","textDeltaSchema","messageId","contentIndex","contentType","audience","observeInvestigation","Observable","subscriber","controller","AbortController","connectedChatId","connectTimer","refreshTimer","eventTimer","previousStatus","previousReport","refreshing","refreshRequested","fail","openStream","close","appSubUrl","connection","EventSource","onopen","refreshFromEvent","onerror","onmessage","requestRefresh","serializedStatus","report","isFetchError","serializedReport","complete","parseVersion","versionPart","prerelease","numbers","TERMS_AND_CONDITIONS_REFRESH_EVENT","fetchTermsData","backendSrv","apiUrl","termsData","lastValueFrom","termsAccepted","acceptedTermsAndConditions","acceptedVersion","currentVersion","termsType","accepted","needsAcceptance","parsed1","parsed2","compareVersions","nonEmptyString","describeTermsError","serverMessage","checkTerms","useTerms","setAccepted","setTermsType","loading","setLoading","fetchTerms","handleTermsRefresh","document","createTool","func","explainer","toolObj","inputSchema","responseFormat","verboseParsingErrors","invoke","invokeOptions","parsedInput","promises","reject","once","timeout","race","LIMITS_UPDATED_EVENT","fetchLimitsData","limitsData","total","limit","month","isLimitReached","checkLimits","useLimits","setCount","setLimit","setMonth","fetchLimits","handleLimitsUpdate","customEvent","refetch","K6SetScriptContentEvent","onK6SetScriptContent","callback","subscription","PATHFINDER_OPERATIONS","refreshGuide","PathfinderEvent","onPathfinderEvent","ASSISTANT_EXTENSION_POINT","InlineChitDisplay","Inline","Block","getAssistantExtensionConfig","manifest","SuggestionContext","Home","CloudHome","Workspace","Dashboard","Dashboards","Alerting","AlertRules","AlertRule","Notifications","Silences","Connections","DataSources","Explore","Drilldown","Metrics","Logs","Traces","Profiles","SQL","Admin","Users","Organization","Teams","ServiceAccounts","Notebooks","Notebook","NewNotebook","Pages","Page","PageTemplates","NewPage","Costs"],"sourceRoot":""}
|
|
1
|
+
{"version":3,"file":"index.js","mappings":"mBACA,MAAMA,EAAsB,CCA5BA,EAAwB,CAACC,EAASC,KACjC,IAAI,IAAIC,KAAOD,EACXF,EAAoBI,EAAEF,EAAYC,KAASH,EAAoBI,EAAEH,EAASE,IAC5EE,OAAOC,eAAeL,EAASE,EAAK,CAAEI,YAAY,EAAMC,IAAKN,EAAWC,MCJ3EH,EAAwB,CAACS,EAAKC,IAAUL,OAAOM,UAAUC,eAAeC,KAAKJ,EAAKC,GCClFV,EAAyBC,IACxBI,OAAOC,eAAeL,EAASa,OAAOC,YAAa,CAAEC,MAAO,WAC5DX,OAAOC,eAAeL,EAAS,aAAc,CAAEe,OAAO,M,SCChD,SAASC,EAAKC,GACnB,IAAID,EAAO,KAEX,IAAK,IAAIE,EAAI,EAAGA,EAAID,EAAME,OAAQD,IAChCF,GAAQA,GAAQ,GAAKA,EAAOC,EAAMG,WAAWF,GAI/C,OAAQF,IAAS,GAAGK,SAAS,GAC/B,C,y0ECuBO,MAAMC,EAKX,WAAAC,CAAmBC,GAAA,KAAAA,OAAAA,EAHZ,KAAAC,KAAO,GAIZC,KAAKC,GAAKX,EAAKQ,EAAOG,IACtBD,KAAKE,KAAOJ,EAAOI,IACrB,CAGA,gBAAIC,G,MACF,OAA+B,QAAxB,EAAAH,KAAKF,OAAOK,oBAAY,QACjC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C,QAAS,WACTC,UAAW,aACXC,QAAS,4CACTC,KAAM,qCACNC,OAAQ,+BACRC,SAAU,mCACVC,IAAK,sCACLC,MAAO,SACPC,MAAO,eACPC,aAAc,OACdC,MAAO,aACPC,gBAAiB,uBACjBC,UAAW,aACXC,SAAU,kBACVC,YAAa,iBACbC,MAAO,iCACPC,KAAM,qCACNC,cAAe,2CACfC,QAAS,qCACTC,MAAO,uB","sources":["webpack://@grafana/assistant/webpack/bootstrap","webpack://@grafana/assistant/webpack/runtime/define property getters","webpack://@grafana/assistant/webpack/runtime/hasOwnProperty shorthand","webpack://@grafana/assistant/webpack/runtime/make namespace object","webpack://@grafana/assistant/./src/utils/hash.ts","webpack://@grafana/assistant/./src/context/base.ts","webpack://@grafana/assistant/./src/context/agentSkill.ts","webpack://@grafana/assistant/external commonjs2 \"@grafana/runtime\"","webpack://@grafana/assistant/external commonjs2 \"react\"","webpack://@grafana/assistant/./src/context/page.ts","webpack://@grafana/assistant/./src/context/component.ts","webpack://@grafana/assistant/./src/context/dashboard.ts","webpack://@grafana/assistant/./src/context/datasource.ts","webpack://@grafana/assistant/./src/context/entity.ts","webpack://@grafana/assistant/./src/context/label.ts","webpack://@grafana/assistant/./src/context/factory.ts","webpack://@grafana/assistant/./src/context/chat.ts","webpack://@grafana/assistant/./src/context/skill.ts","webpack://@grafana/assistant/./src/context/questions.ts","webpack://@grafana/assistant/./src/functions.ts","webpack://@grafana/assistant/external commonjs2 \"rxjs\"","webpack://@grafana/assistant/./src/plugin.ts","webpack://@grafana/assistant/external commonjs2 \"@grafana/data\"","webpack://@grafana/assistant/./src/analyticsEvents.ts","webpack://@grafana/assistant/./src/sidebar.ts","webpack://@grafana/assistant/./src/hook.ts","webpack://@grafana/assistant/external commonjs2 \"react/jsx-runtime\"","webpack://@grafana/assistant/external commonjs2 \"@grafana/ui\"","webpack://@grafana/assistant/external commonjs2 \"@emotion/css\"","webpack://@grafana/assistant/./src/components/button/OpenAssistantButton.tsx","webpack://@grafana/assistant/./src/components/button/OpenAssistantSplitButton.tsx","webpack://@grafana/assistant/./src/utils/theme.ts","webpack://@grafana/assistant/./src/inline/inlineAssistant.ts","webpack://@grafana/assistant/./src/utils/errorHandling.ts","webpack://@grafana/assistant/./src/inline/useInlineAssistant.ts","webpack://@grafana/assistant/./src/components/input/useAIGeneration.ts","webpack://@grafana/assistant/./src/components/input/useGeneratingPlaceholder.ts","webpack://@grafana/assistant/./src/components/input/AITextInput.tsx","webpack://@grafana/assistant/./src/components/input/AITextArea.tsx","webpack://@grafana/assistant/./src/components/button/QueryWithAssistantButton.tsx","webpack://@grafana/assistant/./src/components/prompt-card/useAnimatedPlaceholder.ts","webpack://@grafana/assistant/./src/components/prompt-card/AssistantPromptCard.tsx","webpack://@grafana/assistant/./src/grots/avatar/appearance.ts","webpack://@grafana/assistant/./src/grots/avatar/sprite.ts","webpack://@grafana/assistant/./src/components/grots/GrotAvatar.tsx","webpack://@grafana/assistant/./src/components/grots/OpenGrotButton.tsx","webpack://@grafana/assistant/./src/components/grots/GrotTopicView.tsx","webpack://@grafana/assistant/./src/lens/investigationLens.ts","webpack://@grafana/assistant/./src/lens/useInvestigationThroughLens.ts","webpack://@grafana/assistant/../../../node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/util.js","webpack://@grafana/assistant/../../../node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/core.js","webpack://@grafana/assistant/../../../node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/memoizer.js","webpack://@grafana/assistant/../../../node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/regexes.js","webpack://@grafana/assistant/../../../node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/checks.js","webpack://@grafana/assistant/../../../node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/doc.js","webpack://@grafana/assistant/../../../node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/versions.js","webpack://@grafana/assistant/../../../node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/schemas.js","webpack://@grafana/assistant/../../../node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/registries.js","webpack://@grafana/assistant/../../../node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/api.js","webpack://@grafana/assistant/../../../node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/to-json-schema.js","webpack://@grafana/assistant/../../../node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/json-schema-processors.js","webpack://@grafana/assistant/../../../node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/locales/en.js","webpack://@grafana/assistant/../../../node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/errors.js","webpack://@grafana/assistant/../../../node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/parse.js","webpack://@grafana/assistant/../../../node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/errors.js","webpack://@grafana/assistant/../../../node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/parse.js","webpack://@grafana/assistant/../../../node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/classic/schemas.js","webpack://@grafana/assistant/./src/investigations/client.ts","webpack://@grafana/assistant/./src/investigations/observe.ts","webpack://@grafana/assistant/./src/grots/retry.ts","webpack://@grafana/assistant/./src/grots/client.ts","webpack://@grafana/assistant/./src/terms/versionCompare.ts","webpack://@grafana/assistant/./src/terms/index.ts","webpack://@grafana/assistant/./src/tools/toolFactory.ts","webpack://@grafana/assistant/./src/limits/index.ts","webpack://@grafana/assistant/./src/k6.ts","webpack://@grafana/assistant/./src/pathfinder.ts","webpack://@grafana/assistant/./src/extension/extension.ts","webpack://@grafana/assistant/./src/extension/suggestionContexts.ts"],"sourcesContent":["// The require scope\nconst __webpack_require__ = {};\n\n","// define getter/value functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop));","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","/**\n * Simple hash function that generates a deterministic hash for a given input string.\n * Uses the djb2 algorithm for simplicity and good distribution.\n */\nexport function hash(input: string): string {\n let hash = 5381;\n\n for (let i = 0; i < input.length; i++) {\n hash = (hash << 5) + hash + input.charCodeAt(i);\n }\n\n // Convert to positive hex string\n return (hash >>> 0).toString(16);\n}\n","import type { IconName } from '@grafana/ui';\nimport type { ItemDataType, ContextItemData, UnknownItemData } from './types';\nimport { hash } from '../utils/hash';\n\nexport interface BaseParams {\n title?: string;\n // If true, the context item will not be shown in the context pills\n hidden?: boolean;\n // Image to display, if not selected, we fallback to icon\n img?: string;\n // Icon to display, if img is provided, icon is ignored\n icon?: IconName;\n /**\n * When true, bypasses size limits for fixed-size content that doesn't need truncation.\n *\n * Set `bypassLimits: true` for fixed-size content like:\n * - Static instructions or prompts\n * - Configuration that doesn't change\n * - Small, bounded metadata\n *\n * Keep `bypassLimits: false` (default) for variable-size content like:\n * - Query results, data tables, graphs\n * - User-generated content, logs\n * - Any content that could grow unexpectedly large\n *\n * @default false\n */\n bypassLimits?: boolean;\n}\n\nexport interface NodeDataParams extends BaseParams {\n id: string;\n type: ItemDataType;\n text?: string;\n}\n\nexport class NodeData {\n public id: string;\n public text = '';\n public type: ItemDataType;\n\n constructor(public params: NodeDataParams) {\n this.id = hash(params.id);\n this.type = params.type;\n }\n\n /** Whether size limits should be bypassed for this context item. Defaults to false. */\n get bypassLimits(): boolean {\n return this.params.bypassLimits ?? false;\n }\n\n formatForLLM(codeElementIds?: string[]): ContextItemData {\n return {\n type: this.type,\n codeElementIds,\n bypassLimits: this.bypassLimits,\n data: {\n name: this.params.text ?? '',\n text: this.params.text ?? '',\n } satisfies UnknownItemData,\n };\n }\n\n equals(other: unknown): boolean {\n if (!(other instanceof NodeData)) {\n return false;\n }\n return this.id === other.id && this.type === other.type;\n }\n}\n\nexport interface StructuredNodeDataParams extends BaseParams {\n data: Record<string, any>;\n}\n\nexport class StructuredNodeData extends NodeData {\n public data: Record<string, any>;\n constructor(params: StructuredNodeDataParams) {\n super({ ...params, id: hash(JSON.stringify(params.data)), type: 'structured' });\n this.data = params.data;\n }\n\n formatForLLM(codeElementIds?: string[]): ContextItemData {\n return {\n type: this.type,\n codeElementIds,\n bypassLimits: this.bypassLimits,\n data: this.data,\n };\n }\n}\n","import { type BaseParams, NodeData } from './base';\nimport type { AgentSkillItemData, ContextItemData } from './types';\n\n/**\n * Identity of one Agent Skill, as a turn carries it.\n *\n * Every field is supplied verbatim by the backend descriptor. Nothing here is\n * ever parsed to infer type, provider, capability or scope — `selectionId`,\n * `providerId` and `handle` are opaque strings that only ever get compared and\n * echoed back.\n */\nexport interface AgentSkillReference {\n /**\n * Server-issued selection id, copied verbatim from the catalog descriptor's\n * own `selectionId` field.\n *\n * The only identity the backend resolves an attachment by. A client must\n * never compute it: the server issues it as a SHA-256 over facts a client\n * does not own, and re-implementing that formula here would couple every\n * client to the server-side detail the opaque id exists to hide. So the value\n * is only ever read off a descriptor, stored, and sent back unchanged.\n */\n selectionId: string;\n /** Identity of the provider that owns the skill package. */\n providerId: string;\n /** Provider-local handle of the skill package. */\n handle: string;\n /** Content revision the attachment was pinned to. */\n revision: string;\n /** Display name shown on the attachment tag. */\n displayName: string;\n}\n\nexport interface CreateAgentSkillContextParams extends BaseParams, AgentSkillReference {}\n\n/**\n * The node id of an Agent Skill attachment: its `selectionId`, unchanged.\n *\n * Identity here is the server's, not a key composed locally. The backend reads\n * an attachment's identity out of this id, so anything composed on the client\n * is an id it cannot resolve — which is why this returns the selection id\n * rather than deriving one. The result is still never parsed: no reader may\n * take it apart to recover a provider, a handle, or anything else.\n *\n * Re-pinning a moved revision still updates an existing tag instead of adding a\n * second one, because a selection id names the package rather than the content\n * revision it currently serves.\n */\nexport function agentSkillNodeId(reference: Pick<AgentSkillReference, 'selectionId'>): string {\n return reference.selectionId;\n}\n\n/**\n * Context item for an Agent Skill attached to a turn with \"/\".\n *\n * Deliberately a distinct type from {@link SkillNodeData}: that one means a\n * Reference Library item, and attaching one can auto-approve the tools the\n * item declares. An Agent Skill grants no tool permission whatsoever — it\n * carries identity only, and the backend loads the body server-side. The two\n * must never be collapsed into one type, or the Reference Library's\n * allowed-tools behaviour would silently follow Agent Skills.\n */\nexport class AgentSkillNodeData extends NodeData {\n public selectionId: string;\n public providerId: string;\n public handle: string;\n public revision: string;\n public displayName: string;\n\n constructor(params: CreateAgentSkillContextParams) {\n super({\n ...params,\n id: agentSkillNodeId(params),\n type: 'agent_skill',\n text: params.displayName,\n });\n this.selectionId = params.selectionId;\n this.providerId = params.providerId;\n this.handle = params.handle;\n this.revision = params.revision;\n this.displayName = params.displayName;\n this.text = params.displayName;\n }\n\n /** The reference a request carries. Never a skill body — the backend preloads that. */\n get reference(): AgentSkillReference {\n return {\n selectionId: this.selectionId,\n providerId: this.providerId,\n handle: this.handle,\n revision: this.revision,\n displayName: this.displayName,\n };\n }\n\n formatForLLM(codeElementIds?: string[]): ContextItemData {\n return {\n type: this.type,\n codeElementIds,\n bypassLimits: this.bypassLimits,\n data: {\n name: this.displayName,\n text: this.text,\n selectionId: this.selectionId,\n providerId: this.providerId,\n handle: this.handle,\n revision: this.revision,\n displayName: this.displayName,\n } satisfies AgentSkillItemData,\n };\n }\n}\n","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"@grafana/runtime\");","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"react\");","import { useLocationService } from '@grafana/runtime';\nimport type { ChatContextItem } from './types';\nimport { useEffect, useState, useRef, useCallback } from 'react';\n\n// Extend window interface for the global registries. Declare this once for the\n// whole package: TypeScript 7 rejects the same index signature merged twice.\ndeclare global {\n interface Window {\n [key: string]: any;\n }\n}\n\nexport interface PageContextRegistration {\n id: string;\n urlPattern: string | RegExp;\n context: ChatContextItem[];\n}\n\n// Global registry key\nconst GLOBAL_REGISTRY_KEY = '__grafanaAssistantPageContextRegistry__';\n\n// Custom event for registry changes\nconst REGISTRY_CHANGE_EVENT = 'grafana-assistant:page-context-registry-changed';\n\n/**\n * Legacy event names for backward compatibility with the previous implementation.\n * These events are emitted alongside the new REGISTRY_CHANGE_EVENT to ensure\n * any existing code listening to the old events continues to work.\n *\n * @deprecated These event name is maintained for backward compatibility only.\n * TODO: Remove after old event-based approach is fully deprecated\n */\nconst LEGACY_REGISTRY_UPDATE_EVENT = 'grafana-assistant:page-context-update';\n/**\n * @deprecated These event name is maintained for backward compatibility only.\n * TODO: Remove after old event-based approach is fully deprecated\n */\nconst LEGACY_REGISTRY_REMOVE_EVENT = 'grafana-assistant:page-context-remove';\n/**\n * @deprecated These event name is maintained for backward compatibility only.\n * TODO: Remove after old event-based approach is fully deprecated\n */\nconst LEGACY_REGISTRY_SYNC_EVENT = 'grafana-assistant:page-context-sync';\n\n// Ensure global registry exists on window\nif (!window[GLOBAL_REGISTRY_KEY]) {\n window[GLOBAL_REGISTRY_KEY] = [];\n}\n\n// Get reference to the global registry\nfunction getPageContextRegistry(): PageContextRegistration[] {\n return window[GLOBAL_REGISTRY_KEY];\n}\n\n// TODO: Remove skipLegacyEvents parameter after old event-based approach is fully deprecated\nfunction setPageContextRegistry(newRegistry: PageContextRegistration[], skipLegacyEvents = false): void {\n window[GLOBAL_REGISTRY_KEY] = newRegistry;\n // Notify all listeners that the registry has changed\n window.dispatchEvent(new CustomEvent(REGISTRY_CHANGE_EVENT));\n\n // TODO: Remove this legacy event emission after old event-based approach is fully deprecated\n // Emit legacy sync event for backward compatibility (unless we're processing a legacy event)\n if (!skipLegacyEvents) {\n window.dispatchEvent(\n new CustomEvent(LEGACY_REGISTRY_SYNC_EVENT, {\n detail: { registry: newRegistry },\n })\n );\n }\n}\n\n/**\n * Bridge to handle legacy events from external apps using old versions of @grafana/assistant.\n * This ensures that registrations from external apps get synced into our window registry.\n *\n * TODO: Remove this entire bridge after old event-based approach is fully deprecated\n */\nlet legacyBridgeInitialized = false;\n\nfunction initializeLegacyEventBridge(): void {\n if (legacyBridgeInitialized) {\n return;\n }\n legacyBridgeInitialized = true;\n\n // Handle legacy update events (registration added or updated)\n window.addEventListener(LEGACY_REGISTRY_UPDATE_EVENT, (event: Event) => {\n const customEvent = event as CustomEvent;\n const registration = customEvent.detail as PageContextRegistration;\n\n if (!registration?.id) {\n return;\n }\n\n const currentRegistry = getPageContextRegistry();\n const existingIndex = currentRegistry.findIndex((r) => r.id === registration.id);\n\n if (existingIndex !== -1) {\n // Update existing registration\n const newRegistry = [...currentRegistry];\n newRegistry[existingIndex] = registration;\n setPageContextRegistry(newRegistry, true); // Skip legacy events to avoid loops\n } else {\n // Add new registration\n setPageContextRegistry([...currentRegistry, registration], true); // Skip legacy events to avoid loops\n }\n });\n\n // Handle legacy remove events (registration removed)\n window.addEventListener(LEGACY_REGISTRY_REMOVE_EVENT, (event: Event) => {\n const customEvent = event as CustomEvent;\n const id = customEvent.detail?.id;\n\n if (!id) {\n return;\n }\n\n const currentRegistry = getPageContextRegistry();\n const index = currentRegistry.findIndex((r) => r.id === id);\n\n if (index !== -1) {\n const newRegistry = currentRegistry.filter((_, i) => i !== index);\n setPageContextRegistry(newRegistry, true); // Skip legacy events to avoid loops\n }\n });\n\n // Handle legacy sync events (entire registry sync from external app)\n window.addEventListener(LEGACY_REGISTRY_SYNC_EVENT, (event: Event) => {\n const customEvent = event as CustomEvent;\n const incomingRegistry = customEvent.detail?.registry as PageContextRegistration[];\n\n if (!Array.isArray(incomingRegistry)) {\n return;\n }\n\n const currentRegistry = getPageContextRegistry();\n const currentIds = new Set(currentRegistry.map((r) => r.id));\n\n // Merge: add any registrations from external app that we don't have\n const newRegistrations = incomingRegistry.filter((r) => !currentIds.has(r.id));\n\n if (newRegistrations.length > 0) {\n setPageContextRegistry([...currentRegistry, ...newRegistrations], true); // Skip legacy events to avoid loops\n }\n });\n}\n\n// TODO: Remove this initialization after old event-based approach is fully deprecated\n// Initialize the bridge on module load\ninitializeLegacyEventBridge();\n\n/**\n * Registers context items for specific pages based on URL patterns.\n * Returns a setter function to update the context dynamically, similar to useState.\n *\n * Multiple registrations with the same URL pattern are allowed and will all be merged\n * when the pattern matches. Each call creates a new independent registration.\n *\n * @param urlPattern - URL pattern (string or RegExp) to match against page URLs\n * @param initialContext - *Initial* array of ContextItems to provide when the pattern matches. IMPORTANT: will be overwritten when setContext is used to update the context.\n * @returns A setter function to update the context, with an unregister method attached\n */\nexport function providePageContext(\n urlPattern: string | RegExp,\n initialContext: ChatContextItem[]\n): ((context: ChatContextItem[]) => void) & { unregister: () => void } {\n // Validate URL pattern at registration time (only warn once, not on every match)\n validateUrlPattern(urlPattern);\n\n // Always create a new registration to allow multiple providers with the same URL pattern\n const registration: PageContextRegistration = {\n id: generateRegistrationId(),\n urlPattern,\n context: [...initialContext],\n };\n\n const registry = getPageContextRegistry();\n setPageContextRegistry([...registry, registration]);\n\n // TODO: Remove this legacy event emission after old event-based approach is fully deprecated\n // Emit legacy update event for backward compatibility\n window.dispatchEvent(\n new CustomEvent(LEGACY_REGISTRY_UPDATE_EVENT, {\n detail: registration,\n })\n );\n\n // Create setter function that can update the context\n const setContext = (newContext: ChatContextItem[]) => {\n const currentRegistry = getPageContextRegistry();\n const index = currentRegistry.findIndex((reg) => reg.id === registration.id);\n if (index !== -1) {\n const newRegistry = [...currentRegistry];\n newRegistry[index] = { ...newRegistry[index], context: [...newContext] };\n setPageContextRegistry(newRegistry);\n\n // TODO: Remove this legacy event emission after old event-based approach is fully deprecated\n // Emit legacy update event for backward compatibility\n window.dispatchEvent(\n new CustomEvent(LEGACY_REGISTRY_UPDATE_EVENT, {\n detail: newRegistry[index],\n })\n );\n }\n };\n\n // Add unregister method to the setter\n setContext.unregister = () => {\n const currentRegistry = getPageContextRegistry();\n const index = currentRegistry.findIndex((reg) => reg.id === registration.id);\n if (index !== -1) {\n const newRegistry = currentRegistry.filter((_, i) => i !== index);\n setPageContextRegistry(newRegistry);\n\n // TODO: Remove this legacy event emission after old event-based approach is fully deprecated\n // Emit legacy remove event for backward compatibility\n window.dispatchEvent(\n new CustomEvent(LEGACY_REGISTRY_REMOVE_EVENT, {\n detail: { id: registration.id },\n })\n );\n }\n };\n\n return setContext;\n}\n\nconst empty: ChatContextItem[] = [];\n\n/**\n * React hook for providing page context that automatically cleans up on unmount.\n * This is the recommended way to use page context in React components.\n *\n * @param urlPattern - URL pattern (string or RegExp) to match against page URLs\n * @param initialContext - Initial array of ContextItems to provide when the pattern matches. IMPORTANT: will be overwritten when setContext is used to update the context.\n * @returns A setter function to update the context\n */\nexport function useProvidePageContext(\n urlPattern: string | RegExp,\n initialContext: ChatContextItem[] = empty\n): (context: ChatContextItem[]) => void {\n const setContextRef = useRef<ReturnType<typeof providePageContext> | undefined>(undefined);\n const pendingUpdate = useRef<ChatContextItem[] | undefined>(undefined);\n const isModified = useRef(false);\n\n // Create or update the registration when dependencies change\n // biome-ignore lint/correctness/useExhaustiveDependencies: initialContext is intentionally excluded to prevent re-registering on every render; updates are handled by the second effect\n useEffect(() => {\n // Reset isModified flag when urlPattern changes so that initialContext updates\n // are applied to the new registration until manually modified again\n isModified.current = false;\n\n // If we have pending updates, prefer those over initialContext as they represent\n // newer state from child components\n const contextToUse = pendingUpdate.current !== undefined ? pendingUpdate.current : initialContext;\n setContextRef.current = providePageContext(urlPattern, contextToUse);\n\n // Clear pending update as it's now applied\n if (pendingUpdate.current !== undefined) {\n pendingUpdate.current = undefined;\n }\n\n // Cleanup on unmount or dependency change\n return () => {\n setContextRef.current?.unregister();\n setContextRef.current = undefined;\n };\n // We intentionally exclude initialContext from deps to prevent re-registering on every render\n // Updates to initialContext are handled by the second effect\n }, [urlPattern]);\n\n // Update context when initialContext changes, BUT only if we haven't manually modified it.\n // This prevents unstable initialContext props (e.g. passing [] inline) from overwriting\n // updates made via setContext by child components.\n useEffect(() => {\n if (!isModified.current && setContextRef.current) {\n setContextRef.current(initialContext);\n }\n }, [initialContext]);\n\n // Return a stable setter function\n const setContext = useCallback((newContext: ChatContextItem[]) => {\n isModified.current = true;\n if (setContextRef.current) {\n setContextRef.current(newContext);\n } else {\n pendingUpdate.current = newContext;\n }\n }, []);\n\n return setContext;\n}\n\n/**\n * Gets all context items that match the current URL.\n *\n * @param currentUrl - The current page URL to match against\n * @param registrations - Array of registrations to match against\n * @returns Array of ChatContextItem from all matching registrations\n */\nfunction getActivePageContext(currentUrl: string): ChatContextItem[] {\n if (!currentUrl) {\n return [];\n }\n\n const activeContext: ChatContextItem[] = [];\n const registry = getPageContextRegistry();\n\n for (const registration of registry) {\n if (matchesUrlPattern(currentUrl, registration.urlPattern)) {\n activeContext.push(...registration.context);\n }\n }\n\n return activeContext;\n}\n\nexport function usePageContext(\n options: { allowQuestions: boolean; allowComponents: boolean } = { allowQuestions: false, allowComponents: false }\n): ChatContextItem[] {\n const location = useLocationService();\n const initialPathname = location.getLocation().pathname;\n const [pageContext, setPageContext] = useState<ChatContextItem[]>(() => getActivePageContext(initialPathname));\n const currentPathnameRef = useRef(initialPathname);\n\n useEffect(() => {\n // Function to update context based on current location and registry\n const updateContext = () => {\n const pathname = location.getLocation().pathname;\n const context = getActivePageContext(pathname);\n setPageContext(context);\n };\n\n // Handle registry changes\n const handleRegistryChange = () => {\n updateContext();\n };\n\n // Subscribe to location changes\n const locationSub = location.getLocationObservable().subscribe((loc: { pathname: string }) => {\n const pathname = loc.pathname;\n if (pathname !== currentPathnameRef.current) {\n currentPathnameRef.current = pathname;\n updateContext();\n }\n });\n\n // Listen for registry changes\n window.addEventListener(REGISTRY_CHANGE_EVENT, handleRegistryChange);\n\n // TODO: Remove these legacy event listeners after old event-based approach is fully deprecated\n // Listen for legacy events for backward compatibility\n window.addEventListener(LEGACY_REGISTRY_UPDATE_EVENT, handleRegistryChange);\n window.addEventListener(LEGACY_REGISTRY_REMOVE_EVENT, handleRegistryChange);\n window.addEventListener(LEGACY_REGISTRY_SYNC_EVENT, handleRegistryChange);\n\n // Initial update\n updateContext();\n\n return () => {\n locationSub.unsubscribe();\n window.removeEventListener(REGISTRY_CHANGE_EVENT, handleRegistryChange);\n // TODO: Remove these legacy event listener removals after old event-based approach is fully deprecated\n window.removeEventListener(LEGACY_REGISTRY_UPDATE_EVENT, handleRegistryChange);\n window.removeEventListener(LEGACY_REGISTRY_REMOVE_EVENT, handleRegistryChange);\n window.removeEventListener(LEGACY_REGISTRY_SYNC_EVENT, handleRegistryChange);\n };\n }, [location]);\n\n let filteredContext = pageContext;\n\n if (!options.allowQuestions) {\n filteredContext = filteredContext.filter((item) => item.node.data?.type !== 'question');\n }\n\n if (!options.allowComponents) {\n filteredContext = filteredContext.filter((item) => item.node.data?.type !== 'component');\n }\n\n return filteredContext;\n}\n\nexport function generateRegistrationId(prefix = 'page-context'): string {\n return `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;\n}\n\n/**\n * Validates the URL pattern at registration time and logs warnings for problematic patterns.\n * This is called once during registration, not on every URL match.\n */\nfunction validateUrlPattern(pattern: string | RegExp): void {\n if (pattern instanceof RegExp) {\n // Check if RegExp pattern matches everything (e.g., /.*/, /^.*$/)\n // This is intentional for global contexts (e.g., components), so we use a scoped warning\n const source = pattern.source;\n if (source === '.*' || source === '^.*$' || source === '^.*' || source === '.*$') {\n // Note: This is expected for global contexts like provideComponents.\n // The warning is intentionally omitted here since it's a valid use case.\n // If you want to warn for specific cases, filter them here.\n }\n return;\n }\n\n if (typeof pattern === 'string') {\n // Validate urlPattern - log error if empty string is passed\n if (!pattern || pattern.trim() === '') {\n console.warn(\n 'useProvidePageContext: Empty string passed as urlPattern. This will cause the context to not match any pages.'\n );\n return;\n }\n\n // Check if the pattern matches everything (e.g., ** becomes ^.*$)\n if (pattern === '**') {\n // Note: This is expected for global contexts.\n // The warning is intentionally omitted here since it's a valid use case.\n }\n }\n}\n\nfunction matchesUrlPattern(url: string, pattern: string | RegExp): boolean {\n if (pattern instanceof RegExp) {\n return pattern.test(url);\n }\n\n // For string patterns, support simple wildcards\n if (typeof pattern === 'string') {\n // Empty pattern never matches\n if (!pattern || pattern.trim() === '') {\n return false;\n }\n\n // Convert simple wildcard pattern to regex\n // * matches any characters except /, ** matches any path segments\n // Handle ** first with a placeholder to avoid conflicts\n const regexPattern = pattern\n .replace(/\\*\\*/g, '\\u0000DOUBLE_STAR\\u0000') // Temporary placeholder for **\n .replace(/\\*/g, '[^/]*') // * becomes [^/]*\n // biome-ignore lint/suspicious/noControlCharactersInRegex: intentional \\u0000 null byte used as placeholder to avoid glob pattern conflicts\n .replace(/\\u0000DOUBLE_STAR\\u0000/g, '.*') // Replace placeholder with .*\n .replace(/\\?/g, '.'); // ? becomes .\n\n const finalRegex = `^${regexPattern}$`;\n const regex = new RegExp(finalRegex);\n return regex.test(url);\n }\n\n return false;\n}\n\n/**\n * Test utility function to clear all registrations from the registry.\n * This should only be used in tests to ensure a clean slate between test runs.\n *\n * @internal This is for testing purposes only\n */\nexport function __clearPageContextRegistryForTesting(): void {\n setPageContextRegistry([]);\n}\n","import { type ComponentType, useMemo } from 'react';\nimport { type BaseParams, NodeData } from './base';\nimport type { ContextItemData, ComponentItemData } from './types';\nimport { providePageContext, usePageContext } from './page';\nimport { createAssistantContextItem } from './chat';\n\nexport type ComponentImplementation = ComponentType<any>;\nexport type NamedComponents = Record<string, ComponentImplementation>;\n\n/**\n * Type used to create a component context item.\n */\nexport interface CreateComponentContextParams extends BaseParams {\n components: Record<string, ComponentType<any>>;\n prompt: string;\n namespace?: string;\n}\n\nexport class ComponentNodeData extends NodeData {\n public components: Record<string, ComponentType<any>>;\n public prompt: string;\n public namespace: string;\n\n constructor(params: CreateComponentContextParams) {\n const namespace = params.namespace || 'components';\n super({ ...params, id: `${namespace}-${Object.keys(params.components).join('-')}`, type: 'component' });\n this.components = params.components;\n this.prompt = params.prompt;\n this.namespace = namespace;\n }\n\n formatForLLM(codeElementIds?: string[]): ContextItemData {\n return {\n type: this.type,\n codeElementIds,\n data: {\n name: `Custom UI components (${this.namespace})`,\n prompt: this.prompt\n ? this.prompt +\n '\\n\\nIMPORTANT: The instructions and components described above are scoped to this specific context item only. Do not apply them to unrelated queries or components.'\n : '',\n } satisfies Omit<ComponentItemData, 'components' | 'text' | 'namespace'>,\n };\n }\n}\n\n/**\n * React hook that provides all components available globally.\n * Components are available everywhere, regardless of URL patterns.\n *\n * @returns Object containing all components available globally, keyed by namespace.componentName\n */\nexport function usePageComponents(): Record<string, ComponentImplementation> {\n const pageContext = usePageContext({ allowComponents: true, allowQuestions: false });\n\n // Use useMemo to avoid recreating the components object on every render\n const components = useMemo(() => {\n const allComponents: Record<string, ComponentImplementation> = {};\n\n // Filter for component context items and extract their components\n for (const item of pageContext.filter((item) => item.node.data?.components)) {\n const componentData = item.node.data;\n if (componentData?.components && Object.keys(componentData.components).length > 0) {\n const namespace = componentData.namespace || componentData.name || 'components';\n\n // Add each component with namespace_componentName format\n for (const [componentName, component] of Object.entries(componentData.components)) {\n allComponents[`${namespace}_${componentName}`] = component as ComponentImplementation;\n }\n }\n }\n\n return allComponents;\n }, [pageContext]);\n\n return components;\n}\n\n/**\n * Provide components to the assistant.\n *\n * Components are always available globally, but the prompt is only applied when the URL pattern matches.\n *\n * For catch-all URL patterns, returns a setter that takes a context array.\n * For specific URL patterns, returns a setter that takes components and prompt separately.\n *\n * @param prompt - The prompt to use for the components (only applied when URL matches).\n * @param namespace - The namespace to use for the components.\n * @param components - The components to provide (always available).\n * @param urlPattern - The URL pattern to match for the prompt (components are always available).\n * @returns A setter function to update the context, with an unregister method attached\n */\nexport function provideComponents(\n prompt: string,\n namespace: string,\n components: Record<string, ComponentImplementation>,\n urlPattern: string | RegExp = /.*/\n): ((newComponents: Record<string, ComponentImplementation>, newPrompt: string) => void) & { unregister: () => void } {\n // Check if the URL pattern is catch-all (.*) - if so, register everything together\n const isCatchAll = (pattern: string | RegExp) => {\n if (pattern instanceof RegExp) {\n return pattern.source === '.*' && pattern.flags === '';\n }\n return pattern === '.*' || pattern === '/.*/';\n };\n\n if (isCatchAll(urlPattern)) {\n // If pattern is catch-all, register components and prompt together globally\n const setContext = providePageContext(/.*/, [\n createAssistantContextItem('component', {\n components,\n prompt,\n namespace,\n }),\n ]);\n\n // Create a wrapper setter that matches the expected signature\n const setter = (newComponents: Record<string, ComponentImplementation>, newPrompt: string) => {\n setContext([\n createAssistantContextItem('component', {\n components: newComponents,\n prompt: newPrompt,\n namespace,\n }),\n ]);\n };\n\n // Attach unregister method\n setter.unregister = setContext.unregister;\n\n return setter;\n }\n\n // For specific URL patterns, separate components (global) from prompt (URL-specific)\n const globalComponents = providePageContext(/.*/, [\n createAssistantContextItem('component', {\n components,\n prompt: '', // No prompt for global components\n namespace,\n }),\n ]);\n\n // Only register prompt for specific URL pattern\n const promptContext = providePageContext(urlPattern, [\n createAssistantContextItem('component', {\n components: {}, // No components, just prompt\n prompt,\n namespace,\n }),\n ]);\n\n // Return a setter that properly separates components and prompt\n // When updating, we extract components and prompt from the new data and update each registration appropriately\n const setter = (newComponents: Record<string, ComponentImplementation>, newPrompt: string) => {\n // Update global components registration with new components (but empty prompt)\n globalComponents([\n createAssistantContextItem('component', {\n components: newComponents,\n prompt: '', // No prompt for global components\n namespace,\n }),\n ]);\n\n // Update URL-specific registration with new prompt (but empty components)\n promptContext([\n createAssistantContextItem('component', {\n components: {}, // No components, just prompt\n prompt: newPrompt,\n namespace,\n }),\n ]);\n };\n\n // Attach unregister method that cleans up both registrations\n setter.unregister = () => {\n globalComponents.unregister();\n promptContext.unregister();\n };\n\n return setter;\n}\n","import { type BaseParams, NodeData } from './base';\nimport type { ContextItemData, DashboardItemData, FolderItemData } from './types';\n\nexport interface CreateDashboardContextParams extends BaseParams {\n dashboardUid: string;\n dashboardTitle: string;\n folderUid?: string;\n folderTitle?: string;\n}\n\nexport interface CreateFolderContextParams extends BaseParams {\n folderUid: string;\n folderTitle: string;\n}\n\nexport class DashboardNodeData extends NodeData {\n public dashboardUid: string;\n public dashboardTitle: string;\n public folderUid?: string;\n public folderTitle?: string;\n\n constructor(params: CreateDashboardContextParams) {\n super({ ...params, id: params.dashboardUid, type: 'dashboard' });\n this.dashboardUid = params.dashboardUid;\n this.dashboardTitle = params.dashboardTitle;\n this.folderUid = params.folderUid;\n this.folderTitle = params.folderTitle;\n this.text = params.dashboardTitle;\n }\n\n formatForLLM(codeElementIds?: string[]): ContextItemData {\n return {\n type: this.type,\n codeElementIds,\n bypassLimits: this.bypassLimits,\n data: {\n name: this.dashboardTitle,\n dashboardUid: this.dashboardUid,\n dashboardTitle: this.dashboardTitle,\n folderUid: this.folderUid,\n folderTitle: this.folderTitle,\n text: this.text,\n } satisfies DashboardItemData,\n };\n }\n}\n\nexport class FolderNodeData extends NodeData {\n public folderUid: string;\n public folderTitle: string;\n public text = '';\n\n constructor(params: CreateFolderContextParams) {\n super({ ...params, id: params.folderUid, type: 'dashboard_folder' });\n this.folderUid = params.folderUid;\n this.folderTitle = params.folderTitle;\n this.text = params.folderTitle;\n }\n\n formatForLLM(codeElementIds?: string[]): ContextItemData {\n return {\n type: this.type,\n codeElementIds,\n bypassLimits: this.bypassLimits,\n data: {\n name: this.folderTitle,\n folderUid: this.folderUid,\n folderTitle: this.folderTitle,\n text: this.text,\n } satisfies FolderItemData,\n };\n }\n}\n","import { type BaseParams, NodeData } from './base';\nimport type { DatasourceMeta } from './factory';\nimport type { ContextItemData, DatasourceItemData } from './types';\n\n/**\n * Type used to create a datasource context item.\n *\n * All required attributes will be inferred from the datasources uid.\n */\nexport interface CreateDatasourceContextParams extends BaseParams {\n datasourceUid: string;\n}\n\nexport class DatasourceNodeData extends NodeData {\n public datasourceUid: string;\n public datasourceType: string;\n public datasourceName: string;\n public img?: string;\n\n constructor(params: CreateDatasourceContextParams & DatasourceMeta) {\n super({ ...params, id: params.datasourceUid, type: 'datasource' });\n this.datasourceUid = params.datasourceUid;\n this.datasourceType = params.datasourceType;\n this.datasourceName = params.datasourceName;\n this.img = params.img;\n this.text = params.datasourceName;\n }\n\n formatForLLM(codeElementIds?: string[]): ContextItemData {\n return {\n type: this.type,\n codeElementIds,\n bypassLimits: this.bypassLimits,\n data: {\n name: this.datasourceName,\n uid: this.datasourceUid,\n type: this.datasourceType,\n text: this.text,\n } satisfies DatasourceItemData,\n };\n }\n}\n","import { type BaseParams, NodeData } from './base';\nimport type { ContextItemData, EntityItemData } from './types';\n\n/**\n * Type used to create an entity context item.\n */\nexport interface CreateEntityContextParams extends BaseParams {\n type: string;\n name: string;\n scope?: {\n env?: string;\n site?: string;\n namespace?: string;\n };\n properties?: Record<string, any>;\n}\n\nexport class EntityNodeData extends NodeData {\n public entityType: string;\n public name: string;\n public scope?: {\n env?: string;\n site?: string;\n namespace?: string;\n };\n public properties?: Record<string, any>;\n\n constructor(params: CreateEntityContextParams) {\n super({\n id: `${params.type}-${params.name}-${[params.scope?.env, params.scope?.site, params.scope?.namespace].filter(Boolean).join('-')}`,\n type: 'entity',\n title: params.title,\n hidden: params.hidden,\n img: params.img,\n icon: params.icon,\n text: params.name,\n });\n this.entityType = params.type;\n this.name = params.name;\n this.scope = params.scope;\n this.properties = params.properties;\n this.text = params.name;\n }\n\n formatForLLM(codeElementIds?: string[]): ContextItemData {\n return {\n type: 'entity',\n codeElementIds,\n bypassLimits: this.bypassLimits,\n data: {\n name: this.name,\n text: this.text,\n type: this.entityType,\n scope: this.scope,\n properties: this.properties,\n } satisfies EntityItemData,\n };\n }\n}\n","import { type BaseParams, NodeData } from './base';\nimport type { DatasourceMeta } from './factory';\nimport type { ContextItemData, LabelNameItemData, LabelValueItemData } from './types';\n\nexport interface CreateLabelNameContextParams extends BaseParams {\n datasourceUid: string;\n labelName: string;\n}\n\nexport interface CreateLabelValueContextParams extends CreateLabelNameContextParams {\n labelValue: string;\n /** Filter operator (e.g., '=', '!=', '=~', '!~'). Defaults to '=' if not specified */\n operator?: string;\n}\n\nexport class LabelNameNodeData extends NodeData {\n public datasourceUid: string;\n public datasourceType: string;\n public datasourceName: string;\n public labelName: string;\n public img?: string;\n\n constructor(params: CreateLabelNameContextParams & DatasourceMeta) {\n super({ ...params, id: `${params.datasourceUid}-${params.labelName}`, type: 'label_name' });\n this.datasourceUid = params.datasourceUid;\n this.datasourceType = params.datasourceType;\n this.datasourceName = params.datasourceName;\n this.labelName = params.labelName;\n this.text = params.labelName;\n this.img = params.img;\n }\n\n formatForLLM(codeElementIds?: string[]): ContextItemData {\n return {\n type: this.type,\n codeElementIds,\n bypassLimits: this.bypassLimits,\n data: {\n name: this.labelName,\n datasourceUid: this.datasourceUid,\n datasourceType: this.datasourceType,\n datasourceName: this.datasourceName,\n labelName: this.labelName,\n text: this.text,\n } satisfies LabelNameItemData,\n };\n }\n}\n\nexport class LabelValueNodeData extends NodeData {\n public datasourceUid: string;\n public datasourceType: string;\n public datasourceName: string;\n public labelName: string;\n public labelValue: string;\n public img?: string;\n public operator: string;\n\n constructor(params: CreateLabelValueContextParams & DatasourceMeta) {\n super({\n ...params,\n id: `${params.datasourceUid}-${params.labelName}-${params.labelValue}-${params.operator || '='}`,\n type: 'label_value',\n });\n this.datasourceUid = params.datasourceUid;\n this.datasourceType = params.datasourceType;\n this.datasourceName = params.datasourceName;\n this.labelName = params.labelName;\n this.labelValue = params.labelValue;\n this.text = params.labelValue;\n this.img = params.img;\n this.operator = params.operator || '=';\n }\n\n formatForLLM(codeElementIds?: string[]): ContextItemData {\n return {\n type: this.type,\n codeElementIds,\n bypassLimits: this.bypassLimits,\n data: {\n name: this.labelValue,\n datasourceUid: this.datasourceUid,\n datasourceType: this.datasourceType,\n datasourceName: this.datasourceName,\n labelName: this.labelName,\n labelValue: this.labelValue,\n text: this.text,\n operator: this.operator,\n } satisfies LabelValueItemData,\n };\n }\n}\n","import { getDataSourceSrv } from '@grafana/runtime';\nimport { NodeData, type NodeDataParams, StructuredNodeData, type StructuredNodeDataParams } from './base';\nimport { ComponentNodeData, type CreateComponentContextParams } from './component';\nimport {\n DashboardNodeData,\n FolderNodeData,\n type CreateDashboardContextParams,\n type CreateFolderContextParams,\n} from './dashboard';\nimport { DatasourceNodeData, type CreateDatasourceContextParams } from './datasource';\nimport { EntityNodeData, type CreateEntityContextParams } from './entity';\nimport {\n LabelNameNodeData,\n LabelValueNodeData,\n type CreateLabelNameContextParams,\n type CreateLabelValueContextParams,\n} from './label';\n\n/**\n * registry to handle the type mappings between ItemData type, params and node data\n */\nexport type ContextTypeRegistry = {\n datasource: { params: CreateDatasourceContextParams; node: DatasourceNodeData };\n label_name: { params: CreateLabelNameContextParams; node: LabelNameNodeData };\n label_value: { params: CreateLabelValueContextParams; node: LabelValueNodeData };\n dashboard: { params: CreateDashboardContextParams; node: DashboardNodeData };\n dashboard_folder: { params: CreateFolderContextParams; node: FolderNodeData };\n structured: { params: StructuredNodeDataParams; node: StructuredNodeData };\n component: { params: CreateComponentContextParams; node: ComponentNodeData };\n entity: { params: CreateEntityContextParams; node: EntityNodeData };\n unknown: { params: NodeDataParams; node: NodeData };\n};\n\nexport type DatasourceMeta = {\n datasourceType: string;\n datasourceName: string;\n img?: string;\n};\n\n/**\n * Helper function to get datasource type from datasource UID\n */\nfunction getDatasourceMeta(datasourceUid: string): DatasourceMeta {\n // biome-ignore lint/plugin/no-get-datasource-srv: existing use baselined for MT migration (#13386)\n const datasourceInstance = getDataSourceSrv().getInstanceSettings(datasourceUid);\n return {\n datasourceType: datasourceInstance?.type ?? 'unknown',\n datasourceName: datasourceInstance?.name ?? datasourceUid,\n img: datasourceInstance?.meta?.info?.logos?.small,\n };\n}\n\n/**\n * Creates context nodes based on type with full type safety using generics\n */\nexport function createContextByType<T extends keyof ContextTypeRegistry>(\n type: T,\n params: ContextTypeRegistry[T]['params']\n): ContextTypeRegistry[T]['node'] {\n switch (type) {\n case 'datasource':\n return new DatasourceNodeData({\n ...(params as CreateDatasourceContextParams),\n ...getDatasourceMeta((params as CreateDatasourceContextParams).datasourceUid),\n });\n case 'label_name':\n return new LabelNameNodeData({\n ...(params as CreateLabelNameContextParams),\n ...getDatasourceMeta((params as CreateLabelNameContextParams).datasourceUid),\n });\n case 'label_value':\n return new LabelValueNodeData({\n ...(params as CreateLabelValueContextParams),\n ...getDatasourceMeta((params as CreateLabelValueContextParams).datasourceUid),\n });\n case 'dashboard':\n return new DashboardNodeData(params as CreateDashboardContextParams);\n case 'dashboard_folder':\n return new FolderNodeData(params as CreateFolderContextParams);\n case 'structured':\n return new StructuredNodeData(params as StructuredNodeDataParams);\n case 'component':\n return new ComponentNodeData({\n ...(params as CreateComponentContextParams),\n hidden: true,\n });\n case 'entity':\n return new EntityNodeData(params as CreateEntityContextParams);\n case 'unknown':\n return new NodeData(params as NodeDataParams);\n default:\n console.error(`Unknown context type: ${type}`);\n return new NodeData(params as NodeDataParams);\n }\n}\n","import type { IconName } from '@grafana/ui';\nimport { type NodeData, StructuredNodeData } from './base';\nimport { createContextByType, type ContextTypeRegistry } from './factory';\nimport type { ChatContextItem, ItemDataType } from './types';\n\nconst defaultIcons: Record<ItemDataType, IconName> = {\n datasource: 'database',\n label_name: 'database',\n label_value: 'database',\n dashboard: 'dashboard',\n dashboard_folder: 'folder',\n unknown: 'circle-mono',\n structured: 'gf-grid',\n component: 'gf-grid',\n entity: 'asserts',\n skill: 'play',\n agent_skill: 'ai-sparkle',\n};\n\nfunction getTitleFromContextNode(nodeData: NodeData | StructuredNodeData): string {\n return nodeData instanceof StructuredNodeData\n ? nodeData.formatForLLM().data.name\n : (nodeData.text ?? 'Given Context');\n}\n\nfunction getImgFromContextNode(nodeData: NodeData | StructuredNodeData): string | undefined {\n if ('img' in nodeData) {\n return (nodeData as { img?: string }).img;\n }\n return undefined;\n}\n\n/**\n * Creates a new chat context item that can be added to conversations.\n *\n * This function creates structured context items that provide additional information\n * to the AI assistant during conversations. Context items can include:\n * - Datasources (metrics, logs, traces)\n * - Labels and their values\n * - Dashboards and folders\n * - Structured data objects\n *\n * The created context item includes display metadata (title, icon, image) and\n * the underlying data that will be formatted and sent to the LLM when the\n * context is included in a conversation.\n *\n * @param type - The type of context to create (Datasource, Label, Dashboard etc.)\n * @param params - Type-specific parameters for creating the context item\n * @returns A ChatContextItem that can be added to conversation context\n *\n * @example\n * ```typescript\n * // Create a context that will be passed into the function triggering an assistant open\n * openAssistant({\n * ...\n * origin: 'my-feature',\n * context: [\n * createAssistantContextItem('datasource', {\n * datasourceUid: datasource.uid,\n * img: datasource.meta?.info?.logos?.small,\n * }),\n * ],\n * });\n * ```\n */\nexport function createAssistantContextItem<T extends keyof ContextTypeRegistry>(\n type: T,\n params: ContextTypeRegistry[T]['params']\n): ChatContextItem {\n const nodeData = createContextByType(type, params);\n const defaultTitle = params.title ?? getTitleFromContextNode(nodeData);\n const img = params.img ?? getImgFromContextNode(nodeData);\n return {\n node: {\n id: nodeData.id,\n name: defaultTitle,\n img,\n icon: params.icon ?? defaultIcons[type],\n navigable: false,\n selectable: true,\n data: nodeData,\n },\n occurrences: [],\n };\n}\n","import { type BaseParams, NodeData } from './base';\nimport type { ContextItemData, SkillItemData } from './types';\n\nexport interface CreateSkillContextParams extends BaseParams {\n skillId: string;\n skillName: string;\n}\n\nexport class SkillNodeData extends NodeData {\n public skillId: string;\n public skillName: string;\n\n constructor(params: CreateSkillContextParams) {\n super({\n ...params,\n id: params.skillId,\n type: 'skill',\n text: params.skillName,\n });\n this.skillId = params.skillId;\n this.skillName = params.skillName;\n this.text = params.skillName;\n }\n\n formatForLLM(codeElementIds?: string[]): ContextItemData {\n return {\n type: this.type,\n codeElementIds,\n bypassLimits: this.bypassLimits,\n data: {\n name: this.skillName,\n skillId: this.skillId,\n skillName: this.skillName,\n text: this.text,\n } satisfies SkillItemData,\n };\n }\n}\n","import { useMemo } from 'react';\nimport type { ChatContextItem } from './types';\nimport { providePageContext, useProvidePageContext, usePageContext, generateRegistrationId } from './page';\n\nexport interface Question {\n prompt: string;\n title?: string;\n context?: ChatContextItem[];\n}\n\nexport interface QuestionRegistration {\n id: string;\n urlPattern: string | RegExp;\n questions: Question[];\n}\n\n/**\n * Registers questions for specific pages based on URL patterns.\n * Returns a setter function to update the questions dynamically, similar to useState.\n *\n * Multiple registrations with the same URL pattern are allowed and will all be merged\n * when the pattern matches. Each call creates a new independent registration.\n *\n * @param urlPattern - URL pattern (string or RegExp) to match against page URLs\n * @param initialQuestions - Initial array of questions to provide when the pattern matches\n * @returns A setter function to update the questions, with an unregister method attached\n */\nexport function provideQuestions(\n urlPattern: string | RegExp,\n initialQuestions: Question[]\n): ((questions: Question[]) => void) & { unregister: () => void } {\n // Generate a unique registration ID to prevent collisions when multiple registrations exist\n const registrationId = generateRegistrationId('question');\n\n // Convert questions to ChatContextItem format for the underlying system\n const convertQuestionsToContext = (questions: Question[]): ChatContextItem[] => {\n return questions.map((question, index) => ({\n node: {\n id: `question-${registrationId}-${index}`,\n name: question.title || question.prompt,\n navigable: false,\n selectable: true,\n icon: 'question-circle',\n data: {\n type: 'question',\n prompt: question.prompt,\n title: question.title,\n context: question.context || [],\n },\n },\n occurrences: [],\n }));\n };\n\n // Use the existing providePageContext system\n const setContext = providePageContext(urlPattern, convertQuestionsToContext(initialQuestions));\n\n // Create a wrapper that converts between questions and context\n const setQuestions = (newQuestions: Question[]) => {\n setContext(convertQuestionsToContext(newQuestions));\n };\n\n // Add unregister method\n setQuestions.unregister = setContext.unregister;\n\n return setQuestions;\n}\n\n/**\n * React hook for providing questions that automatically cleans up on unmount.\n * This is the recommended way to use questions in React components.\n *\n * @param urlPattern - URL pattern (string or RegExp) to match against page URLs\n * @param initialQuestions - Initial array of questions to provide when the pattern matches\n * @returns A setter function to update the questions\n */\nexport function useProvideQuestions(\n urlPattern: string | RegExp,\n initialQuestions: Question[] = []\n): (questions: Question[]) => void {\n // Generate a stable unique registration ID per component instance to prevent collisions\n const registrationId = useMemo(\n () => generateRegistrationId('question'),\n [] // Empty deps = generated once per component instance\n );\n\n // Convert questions to ChatContextItem format for the underlying system\n const convertQuestionsToContext = (questions: Question[]): ChatContextItem[] => {\n return questions.map((question, index) => ({\n node: {\n id: `question-${registrationId}-${index}`,\n name: question.title ?? question.prompt,\n navigable: false,\n selectable: true,\n icon: 'question-circle',\n data: {\n type: 'question',\n prompt: question.prompt,\n title: question.title,\n context: question.context || [],\n },\n },\n occurrences: [],\n }));\n };\n\n // Use the existing useProvidePageContext system\n const setContext = useProvidePageContext(urlPattern, convertQuestionsToContext(initialQuestions));\n\n // Create a wrapper that converts between questions and context\n const setQuestions = (newQuestions: Question[]) => {\n setContext(convertQuestionsToContext(newQuestions));\n };\n\n return setQuestions;\n}\n\n/**\n * React hook to get all questions that match the current URL.\n * This filters the page context to only return question-type items.\n *\n * @returns Array of questions from all matching registrations\n */\nexport function useQuestions(): Question[] {\n const pageContext = usePageContext({ allowQuestions: true, allowComponents: false });\n\n // Filter and convert context items to questions\n return convertContextToQuestions(pageContext);\n}\n\nconst convertContextToQuestions = (contextItems: ChatContextItem[]): Question[] => {\n return contextItems\n .filter((item) => item.node.data?.type === 'question')\n .map((item) => ({\n prompt: item.node.data?.prompt || item.node.name,\n title: item.node.data?.title,\n context: item.node.data?.context || [],\n }));\n};\n","import type { PluginExtensionAddedFunctionConfig } from '@grafana/data';\n\nexport type CallbackFunction = () => FunctionNamespace[];\nexport type FunctionImplementation = (...args: any[]) => any;\nexport const CALLBACK_EXTENSION_POINT = 'grafana-assistant-app/callback/v0-alpha';\n\nexport type NamedFunctions = Record<string, FunctionImplementation>;\nexport type FunctionNamespace = {\n namespace: string;\n functions: NamedFunctions;\n};\n\nexport function newFunctionNamespace(namespace: string, functions: NamedFunctions): FunctionNamespace {\n return {\n namespace,\n functions,\n };\n}\n\nexport function getExposeAssistantFunctionsConfig(\n namespaces: FunctionNamespace[]\n): PluginExtensionAddedFunctionConfig<() => FunctionNamespace[]> {\n return {\n title: 'callback',\n targets: [CALLBACK_EXTENSION_POINT],\n fn: () => {\n return namespaces.map((namespace) => {\n return {\n namespace: namespace.namespace,\n functions: namespace.functions,\n };\n });\n },\n };\n}\n","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"rxjs\");","import { getObservablePluginLinks } from '@grafana/runtime';\n// biome-ignore lint/suspicious/noDeprecatedImports: throwError and timer have deprecated overloads but we use the non-deprecated factory/single-arg forms\nimport { catchError, defer, map, type Observable, of, retry, throwError, timer } from 'rxjs';\n\nexport const ASSISTANT_PLUGIN_ID = 'grafana-assistant-app';\nexport const ASSISTANT_PLUGIN_TITLE = 'Grafana Assistant';\n\nconst MAX_RETRY_ATTEMPTS = 10;\nconst INITIAL_RETRY_DELAY = 100; // 100ms\nconst MAX_RETRY_DELAY = 5000; // 5 seconds\n\n/**\n * Check if the assistant is available.\n * @returns An observable that emits true if the assistant is available, false otherwise.\n */\nexport function isAssistantAvailable(): Observable<boolean> {\n // this is to avoid crashing in older Grafana versions\n if (!getObservablePluginLinks) {\n return of(false);\n }\n\n // Use defer to make the call lazy and handle both sync and async errors\n return defer(() => {\n try {\n const links = getObservablePluginLinks({\n extensionPointId: 'grafana/extension-sidebar/v0-alpha',\n });\n return links.pipe(\n map((links: Array<{ pluginId: string; title: string }>) =>\n links.some((link) => link.pluginId === ASSISTANT_PLUGIN_ID && link.title === ASSISTANT_PLUGIN_TITLE)\n )\n );\n } catch (error) {\n // If getObservablePluginLinks throws synchronously, convert to observable error\n return throwError(() => error);\n }\n }).pipe(\n retry({\n count: MAX_RETRY_ATTEMPTS,\n delay: (error, retryCount) => {\n // Check if error indicates Grafana hasn't started yet\n const errorMessage = error?.message?.toLowerCase() || '';\n const isGrafanaNotReady =\n errorMessage.includes('can only be used after') ||\n errorMessage.includes('grafana instance has started') ||\n errorMessage.includes('not started');\n\n // Don't retry for non-race-condition errors\n if (!isGrafanaNotReady) {\n throw error;\n }\n\n // Exponential backoff: delay = INITIAL_RETRY_DELAY * 2^retryCount, capped at MAX_RETRY_DELAY\n const delayMs = Math.min(INITIAL_RETRY_DELAY * 2 ** (retryCount - 1), MAX_RETRY_DELAY);\n return timer(delayMs);\n },\n }),\n catchError(() => {\n // After all retries exhausted, return false\n return of(false);\n })\n );\n}\n","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"@grafana/data\");","import { reportInteraction } from '@grafana/runtime';\n\n// The SDK runs in caller plugins, outside Assistant's surface and visit tracking. It can't import the\n// plugin, so the actor is a plain string here; the catalog check rejects any value that isn't one of the\n// plugin's AnalyticsActor values (apps/plugin/src/utils/analyticsEventFactory.ts).\n/** Where an integration opened or showed Assistant, which every SDK event sends. */\ntype SdkEventOrigin = {\n /**\n * The caller's `origin`: a namespaced, slash-separated name for the integration and the place in it, such as\n * `grafana-slo-app/slo-editor-overview`.\n */\n from: string;\n};\n\nfunction defineSdkEvent<Properties extends SdkEventOrigin = SdkEventOrigin>(\n name: string,\n { actor }: { actor: string }\n) {\n return (properties: Properties) => reportInteraction(name, { ...properties, actor });\n}\n\n/**\n * A caller opens the Assistant sidebar. The from field identifies the entry point.\n */\nexport const trackSidebarOpened = defineSdkEvent('grafana_assistant_app_opened_sidebar', { actor: 'user' });\n\n/**\n * A caller toggles the Assistant sidebar and optionally supplies a prompt.\n */\nexport const trackSidebarToggled = defineSdkEvent<\n SdkEventOrigin & {\n /** The prompt the caller asked Assistant to open with, as the caller wrote it; empty when it gave none. */\n prompt: string;\n }\n>('grafana_assistant_app_toggled_sidebar', { actor: 'user' });\n\n/**\n * The SDK renders the Open Assistant button for an integration.\n */\nexport const trackOpenButtonDisplayed = defineSdkEvent('grafana_assistant_app_open_sidebar_button_displayed', {\n actor: 'system',\n});\n\n/**\n * The SDK renders the Open Assistant split button for an integration.\n */\nexport const trackSplitButtonDisplayed = defineSdkEvent('grafana_assistant_app_open_sidebar_split_button_displayed', {\n actor: 'system',\n});\n\n/**\n * The SDK renders an Assistant prompt card for an integration.\n */\nexport const trackPromptCardDisplayed = defineSdkEvent('grafana_assistant_app_prompt_card_displayed', {\n actor: 'system',\n});\n","import { BusEventBase, BusEventWithPayload } from '@grafana/data';\nimport { getAppEvents } from '@grafana/runtime';\nimport { trackSidebarOpened, trackSidebarToggled } from './analyticsEvents';\nimport type { ChatContextItem } from './context/types';\nimport { ASSISTANT_PLUGIN_ID, ASSISTANT_PLUGIN_TITLE } from './plugin';\n\ninterface OpenExtensionSidebarPayload {\n props?: Record<string, unknown>;\n pluginId: string;\n componentTitle: string;\n}\n\nclass OpenExtensionSidebarEvent extends BusEventWithPayload<OpenExtensionSidebarPayload> {\n static type = 'open-extension-sidebar';\n}\n\nclass CloseExtensionSidebarEvent extends BusEventBase {\n static type = 'close-extension-sidebar';\n}\n\nclass ToggleExtensionSidebarEvent extends BusEventWithPayload<OpenExtensionSidebarPayload> {\n static type = 'toggle-extension-sidebar';\n}\n\nfunction openExtensionSidebar(pluginId: string, componentTitle: string, props?: Record<string, unknown>) {\n const event = new OpenExtensionSidebarEvent({\n pluginId,\n componentTitle,\n props,\n });\n getAppEvents().publish(event);\n}\n\nfunction closeExtensionSidebar() {\n const event = new CloseExtensionSidebarEvent();\n getAppEvents().publish(event);\n}\n\nfunction toggleExtensionSidebar(pluginId: string, componentTitle: string, props?: Record<string, unknown>) {\n const event = new ToggleExtensionSidebarEvent({\n pluginId,\n componentTitle,\n props,\n });\n getAppEvents().publish(event);\n}\n\nexport type OpenAssistantProps = {\n origin: string;\n\n prompt?: string;\n context?: ChatContextItem[];\n autoSend?: boolean;\n /** Mode to open the assistant in. Built-in modes: 'assistant', 'investigation', 'dashboarding'. Can also be a backend agent ID. */\n mode?: string;\n /** When set, sends the prompt as a follow-up into this existing conversation instead of creating a new one. */\n chatId?: string;\n /** When true, append context to the chat instead of replacing it. */\n appendContext?: boolean;\n /**\n * One Agent Skill to attach to the new conversation, named by the token a user types\n * after `/` (its invocation name). Never a handle, a canonical name, or the opaque\n * selection id the server issues — those are internal identities and a caller may not\n * carry one.\n *\n * A request, never a grant: the composer resolves it against the catalog the caller's\n * own user may already attach from, so this can only ever reach what typing the same\n * token would reach. Unknown, unavailable and unsupported all attach nothing.\n *\n * Honoured only on a new conversation. Passing it with `chatId` attaches nothing — and still\n * suppresses the send, so a caller cannot get an unshaped turn where it asked for a shaped one.\n */\n agentSkillInvocationName?: string;\n};\n\n/**\n * The prop bag core forwards verbatim to the sidebar component and re-publishes on the app bus.\n *\n * Two normalizations happen here rather than downstream, because this is the one place both\n * consumers of the event see:\n *\n * - a request naming an Agent Skill never auto-sends. A caller shares a link; the person opening\n * it must see what it attached — and be able to remove it — before anything reaches the model.\n * It holds even where the skill cannot be attached, so a surface that drops the request fails\n * by not sending rather than by sending a message the skill was supposed to shape.\n * - a new conversation naming a skill opens in Assistant unless the caller said otherwise. A\n * skill attaches on the assistant surface, and leaving the mode to an instance default that\n * settles a render later would let the attachment land before its routing was known. This one\n * is skipped alongside `chatId`, which would otherwise change an existing conversation's mode.\n *\n * The suppression is *not* skipped for `chatId`, where the skill is ignored: a caller that asked\n * for a skill-shaped turn is better served by no turn than by an unshaped one it did not ask for.\n */\nfunction toSidebarProps(props: OpenAssistantProps): Record<string, unknown> {\n const namesAgentSkill = Boolean(props.agentSkillInvocationName?.trim());\n return {\n // Distinguish intentional repeated calls from rerenders of the same open request.\n // getRandomValues also works on Grafana instances served over plain HTTP.\n initialRequestId: crypto.getRandomValues(new Uint32Array(4)).join('-'),\n initialPrompt: props.prompt,\n initialContext: props.context,\n initialAutoSend: namesAgentSkill ? false : (props.autoSend ?? true),\n origin: props.origin,\n initialMode: props.mode ?? (namesAgentSkill && !props.chatId ? 'assistant' : undefined),\n chatId: props.chatId,\n appendContext: props.appendContext,\n initialAgentSkillInvocationName: props.agentSkillInvocationName,\n };\n}\n\n/**\n * Open the Grafana Assistant sidebar with a given initial prompt.\n *\n * @param props - The props to pass to the assistant.\n * @param props.origin - The origin of the request that opened the assistant. This is used to track the source of the request. Should be a structured string using forward slashes, with the first part as a namespace. Examples: 'grafana-datasources/prometheus/query-builder', 'grafana-slo-app/slo-editor-overview', 'grafana/trace-view-analyzer`.\n * @param props.prompt - The initial prompt to display in the assistant.\n * @param props.context - The initial context to display in the assistant. Created with `createContext`.\n * @param props.autoSend - Whether to automatically send the initial prompt. When true, opens a chat and sends the initial prompt right away. When false, opens chat and updates user message without sending it. Defaults to true.\n * @param props.mode - The mode to open the assistant in. Built-in modes: 'assistant', 'investigation', 'dashboarding'. Can also be a backend agent ID. Defaults to 'assistant'.\n * @param props.chatId - When set, sends the prompt as a follow-up into this existing conversation instead of creating a new one.\n * @param props.agentSkillInvocationName - One Agent Skill to attach to the new conversation, by the token a user types after `/`. Naming one never auto-sends, and pins Assistant mode when no mode and no chatId are given. Attaches nothing with `chatId`, which still does not send.\n */\nexport function openAssistant(props: OpenAssistantProps) {\n trackSidebarOpened({\n from: props.origin,\n });\n\n openExtensionSidebar(ASSISTANT_PLUGIN_ID, ASSISTANT_PLUGIN_TITLE, toSidebarProps(props));\n}\n\n/**\n * Close the Grafana Assistant sidebar.\n */\nexport function closeAssistant() {\n closeExtensionSidebar();\n}\n\nexport function toggleAssistant(props: OpenAssistantProps) {\n trackSidebarToggled({\n from: props.origin,\n prompt: props.prompt ?? '',\n });\n\n toggleExtensionSidebar(ASSISTANT_PLUGIN_ID, ASSISTANT_PLUGIN_TITLE, toSidebarProps(props));\n}\n","import { useEffect, useState } from 'react';\nimport { isAssistantAvailable } from './plugin';\nimport { closeAssistant, openAssistant, toggleAssistant, type OpenAssistantProps } from './sidebar';\n\nexport type AssistantHook = {\n /** Whether the availability check is still in progress. */\n isLoading: boolean;\n isAvailable: boolean;\n openAssistant: ((props: OpenAssistantProps) => void) | undefined;\n closeAssistant: (() => void) | undefined;\n toggleAssistant: ((props: OpenAssistantProps) => void) | undefined;\n};\n/**\n * Hook to check if the assistant is available and return the open, close, and toggle functions.\n * @returns {AssistantHook}\n */\nexport function useAssistant(): AssistantHook {\n const [available, setAvailable] = useState<boolean | undefined>(undefined);\n\n useEffect(() => {\n const sub = isAssistantAvailable().subscribe(setAvailable);\n return () => sub.unsubscribe();\n }, []);\n\n const isAvailable = available ?? false;\n\n return {\n isLoading: available === undefined,\n isAvailable,\n openAssistant: isAvailable ? openAssistant : undefined,\n closeAssistant: isAvailable ? closeAssistant : undefined,\n toggleAssistant: isAvailable ? toggleAssistant : undefined,\n };\n}\n","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"react/jsx-runtime\");","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"@grafana/ui\");","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"@emotion/css\");","import { useEffect } from 'react';\nimport { Button, IconButton, useStyles2 } from '@grafana/ui';\nimport { css } from '@emotion/css';\nimport type { ChatContextItem } from '../../context/types';\nimport { useAssistant } from '../../hook';\nimport type { GrafanaTheme2 } from '@grafana/data';\nimport type { OpenAssistantProps } from '../../sidebar';\nimport { trackOpenButtonDisplayed } from '../../analyticsEvents';\n\nexport interface OpenAssistantButtonProps {\n /** Prompt to pass to the openAssistant function. */\n prompt: string;\n /** Origin of the request that opened the assistant. This is used to track the source of the request. Should be a structured string using forward slashes, with the first part as a namespace. Examples: 'grafana-datasources/prometheus/query-builder', 'grafana-slo-app/slo-editor-overview', 'grafana/trace-view-analyzer`. */\n origin: string;\n /** Context to pass to the openAssistant function. Optional, defaults to undefined. Created with `createAssistantContextItem`. */\n context?: ChatContextItem[];\n /** Whether to automatically send the prompt. Optional, defaults to true. */\n autoSend?: boolean;\n /** Text to display on the button. Optional, defaults to 'Analyze with Assistant' */\n title?: string;\n /** Button size, defaults to sm */\n size?: 'xs' | 'sm' | 'md' | 'lg';\n /** If true, the button will be Assistant icon only with name as title. Defaults to false. */\n iconOnlyButton?: boolean;\n /**\n * Style of the icon-only button. `'ghost'` is borderless; `'bordered'` is a standard secondary `Button`\n * that lines up with other secondary icon buttons. Only applies when `iconOnlyButton` is true. Defaults to `'ghost'`.\n */\n iconOnlyVariant?: 'ghost' | 'bordered';\n /** Function to call when the button is clicked. Optional, defaults to undefined. */\n onClick?: () => void;\n}\n\n/**\n * A button component that opens the Grafana Assistant with configurable prompt and context.\n */\nexport function OpenAssistantButton(props: OpenAssistantButtonProps) {\n // If the assistant is not available, return empty\n const { isAvailable, openAssistant } = useAssistant();\n if (!isAvailable || !openAssistant) {\n return null;\n }\n return <OpenAssistantButtonView {...props} openAssistant={openAssistant} />;\n}\n\n/**\n * Presentational component separated from OpenAssistantButton to avoid hook dependencies in previews.\n * It is not exported for users of the package.\n */\nexport function OpenAssistantButtonView({\n prompt,\n origin,\n context,\n autoSend = true,\n title = 'Analyze with Assistant',\n size = 'sm',\n iconOnlyButton = false,\n iconOnlyVariant = 'ghost',\n openAssistant,\n onClick,\n}: OpenAssistantButtonProps & {\n openAssistant: (props: OpenAssistantProps) => void;\n}) {\n const styles = useStyles2(getStyles);\n\n useEffect(() => {\n trackOpenButtonDisplayed({\n from: origin,\n });\n }, [origin]);\n\n const handleClick = () => {\n onClick?.();\n openAssistant({ prompt, context, autoSend, origin });\n };\n\n if (iconOnlyButton && iconOnlyVariant === 'bordered') {\n return (\n <Button\n icon=\"ai-sparkle\"\n onClick={handleClick}\n variant=\"secondary\"\n fill=\"solid\"\n size={size}\n tooltip={title}\n aria-label={title}\n data-testid=\"assistant-bordered-icon-button\"\n />\n );\n }\n\n return (\n <>\n {iconOnlyButton ? (\n <IconButton\n name=\"ai-sparkle\"\n onClick={handleClick}\n variant=\"secondary\"\n size={size}\n aria-label={title}\n className={styles.icon}\n tooltip={title}\n data-testid=\"assistant-icon-button\"\n />\n ) : (\n <Button\n icon=\"ai-sparkle\"\n onClick={handleClick}\n variant=\"secondary\"\n fill=\"solid\"\n size={size}\n title={title}\n aria-label={title}\n className={styles.button}\n data-testid=\"assistant-button\"\n >\n {title}\n </Button>\n )}\n </>\n );\n}\n\nconst getStyles = (theme: GrafanaTheme2) => {\n const baseBackground = theme.colors.secondary.main;\n const elevatedBackground = theme.colors.emphasize(baseBackground, 0.05);\n\n // Canvas is what's typically underneath buttons\n const underlyingColor = theme.colors.background.canvas;\n\n const borderWidth = 1;\n const outerRadius = theme.shape.radius.default;\n // inner radius = outer radius - border width, but take at least 1px\n const innerRadius = `max(calc(${outerRadius} - ${borderWidth}px), 1px)`;\n\n // Gradient border layer (::before)\n const gradientBorderLayer = {\n content: '\"\"',\n position: 'absolute' as const,\n inset: 0,\n borderRadius: outerRadius,\n cornerShape: 'squircle',\n background: 'linear-gradient(90deg, rgb(168, 85, 247), rgb(249, 115, 22))',\n zIndex: -2,\n pointerEvents: 'none' as const,\n };\n\n // Solid background layer factory (::after)\n // Layer transparent color over canvas to make it opaque and mask the gradient properly\n const solidBackgroundLayer = (background: string) => ({\n content: '\"\"',\n position: 'absolute' as const,\n inset: `${borderWidth}px`,\n borderRadius: innerRadius,\n cornerShape: 'squircle',\n background: `linear-gradient(${background}, ${background}), ${underlyingColor}`,\n zIndex: -1,\n transition: 'none',\n pointerEvents: 'none' as const,\n });\n\n return {\n button: css({\n label: 'assistant-button',\n width: 'fit-content',\n maxWidth: '100%',\n position: 'relative',\n isolation: 'isolate',\n border: 'none',\n transition: 'none !important',\n '&::before': gradientBorderLayer,\n '&::after': {\n ...solidBackgroundLayer(baseBackground),\n transition: 'none',\n },\n '&:hover': {\n transition: 'none !important',\n },\n '&:hover::after': {\n background: `linear-gradient(${elevatedBackground}, ${elevatedBackground}), ${underlyingColor}`,\n },\n }),\n icon: css({\n label: 'assistant-icon',\n position: 'relative',\n isolation: 'isolate',\n border: 'none',\n background: 'none',\n padding: theme.spacing(0.5),\n '&::before': { ...gradientBorderLayer, transition: 'background 0.1s ease' },\n '&:hover::after': {\n ...solidBackgroundLayer(baseBackground),\n background: `linear-gradient(${elevatedBackground}, ${elevatedBackground}), ${underlyingColor}`,\n },\n }),\n };\n};\n","import { type ReactElement, useEffect } from 'react';\nimport { Button, ButtonGroup, Dropdown, Tooltip, useStyles2 } from '@grafana/ui';\nimport { css, cx } from '@emotion/css';\nimport type { ChatContextItem } from '../../context/types';\nimport { useAssistant } from '../../hook';\nimport type { GrafanaTheme2 } from '@grafana/data';\nimport type { OpenAssistantProps } from '../../sidebar';\nimport { trackSplitButtonDisplayed } from '../../analyticsEvents';\n\nexport interface OpenAssistantSplitButtonProps {\n /** Prompt to pass to the openAssistant function. */\n prompt: string;\n /** Origin of the request that opened the assistant. */\n origin: string;\n /** Context to pass to the openAssistant function. Optional, defaults to undefined. */\n context?: ChatContextItem[];\n /** Whether to automatically send the prompt. Optional, defaults to true. */\n autoSend?: boolean;\n /** Text to display on the button. Optional, defaults to 'Chat with Assistant' */\n title?: string;\n /** Button size, defaults to sm */\n size?: 'sm' | 'md' | 'lg';\n /** Function to call when the main button is clicked. Optional. */\n onClick?: () => void;\n /** Additional menu items to show in the dropdown. Optional. */\n menuItems?: ReactElement;\n /** Tooltip text to display on hover. Optional. */\n tooltip?: string;\n /** Width for the dropdown/chevron segment. Accepts pixels as number or any CSS width value. */\n dropdownButtonWidth?: number | string;\n}\n\ntype AssistantButtonSize = NonNullable<OpenAssistantSplitButtonProps['size']>;\n\nconst defaultDropdownButtonWidths: Record<AssistantButtonSize, number> = {\n sm: 32,\n md: 36,\n lg: 40,\n};\n\n/**\n * A split button component that opens the Grafana Assistant with a dropdown for additional actions.\n * The gradient border wraps around both buttons as a unified control.\n */\nexport function OpenAssistantSplitButton(props: OpenAssistantSplitButtonProps) {\n const { isAvailable, openAssistant } = useAssistant();\n if (!isAvailable || !openAssistant) {\n return null;\n }\n return <OpenAssistantSplitButtonView {...props} openAssistant={openAssistant} />;\n}\n\nexport function OpenAssistantSplitButtonView({\n prompt,\n origin,\n context,\n autoSend = true,\n title = 'Chat with Assistant',\n size = 'sm',\n onClick,\n menuItems,\n tooltip,\n dropdownButtonWidth,\n openAssistant,\n}: OpenAssistantSplitButtonProps & {\n openAssistant: (props: OpenAssistantProps) => void;\n}) {\n const styles = useStyles2(getStyles);\n const hasMenuItems = Boolean(menuItems);\n const resolvedDropdownButtonWidth = toCssWidth(dropdownButtonWidth ?? defaultDropdownButtonWidths[size]);\n\n useEffect(() => {\n trackSplitButtonDisplayed({\n from: origin,\n });\n }, [origin]);\n\n const handleMainClick = () => {\n onClick?.();\n openAssistant({ prompt, context, autoSend, origin });\n };\n\n const wrapperContent = (\n <div className={styles.wrapper}>\n <ButtonGroup className={styles.buttonGroup}>\n <Button\n icon=\"ai-sparkle\"\n onClick={handleMainClick}\n variant=\"secondary\"\n fill=\"solid\"\n size={size}\n aria-label={title}\n className={cx(styles.segmentButton, hasMenuItems ? styles.mainButtonSplit : styles.mainButtonSolo)}\n data-testid=\"assistant-split-button-main\"\n >\n {title}\n </Button>\n {menuItems && (\n <Dropdown overlay={menuItems}>\n <Button\n variant=\"secondary\"\n icon=\"angle-down\"\n size={size}\n aria-label=\"More AI actions\"\n className={cx(styles.segmentButton, styles.dropdownButton)}\n style={{ width: resolvedDropdownButtonWidth, minWidth: resolvedDropdownButtonWidth }}\n data-testid=\"assistant-split-button-dropdown\"\n />\n </Dropdown>\n )}\n </ButtonGroup>\n </div>\n );\n\n return tooltip ? <Tooltip content={tooltip}>{wrapperContent}</Tooltip> : wrapperContent;\n}\n\nconst getStyles = (theme: GrafanaTheme2) => {\n const baseBackground = theme.colors.secondary.main;\n const elevatedBackground = theme.colors.emphasize(baseBackground, 0.05);\n const underlyingColor = theme.colors.background.canvas;\n const dividerColor = theme.colors.border.weak;\n const borderWidth = 1;\n const outerRadius = theme.shape.radius.default;\n const innerRadius = `max(calc(${outerRadius} - ${borderWidth}px), 1px)`;\n\n return {\n wrapper: css({\n label: 'assistant-split-button-wrapper',\n position: 'relative',\n isolation: 'isolate',\n display: 'inline-block',\n padding: borderWidth,\n // Gradient border around the entire button group\n '&::before': {\n content: '\"\"',\n position: 'absolute',\n inset: 0,\n borderRadius: outerRadius,\n cornerShape: 'squircle',\n background: 'linear-gradient(90deg, rgb(168, 85, 247), rgb(249, 115, 22))',\n zIndex: -1,\n pointerEvents: 'none',\n },\n // Solid background layer\n '&::after': {\n content: '\"\"',\n position: 'absolute',\n inset: `${borderWidth}px`,\n borderRadius: innerRadius,\n cornerShape: 'squircle',\n background: `linear-gradient(${baseBackground}, ${baseBackground}), ${underlyingColor}`,\n zIndex: -1,\n pointerEvents: 'none',\n },\n }),\n buttonGroup: css({\n label: 'assistant-split-button-group',\n gap: 0,\n position: 'relative',\n zIndex: 1,\n borderRadius: innerRadius,\n overflow: 'hidden',\n // Make buttons transparent to show the wrapper's gradient\n '& button': {\n border: 'none',\n boxShadow: 'none',\n background: 'transparent !important',\n },\n }),\n segmentButton: css({\n label: 'assistant-split-button-segment',\n position: 'relative',\n '&:hover': {\n background: `${elevatedBackground} !important`,\n },\n '&:focus-visible': {\n background: `${elevatedBackground} !important`,\n },\n '&[aria-expanded=\"true\"]': {\n background: `${elevatedBackground} !important`,\n },\n }),\n mainButtonSolo: css({\n label: 'assistant-split-button-main-solo',\n borderRadius: innerRadius,\n }),\n mainButtonSplit: css({\n label: 'assistant-split-button-main-split',\n borderTopLeftRadius: innerRadius,\n borderBottomLeftRadius: innerRadius,\n borderTopRightRadius: 0,\n borderBottomRightRadius: 0,\n }),\n dropdownButton: css({\n label: 'assistant-split-button-dropdown',\n display: 'inline-flex',\n alignItems: 'center',\n justifyContent: 'center',\n gap: 0,\n borderTopLeftRadius: 0,\n borderBottomLeftRadius: 0,\n borderTopRightRadius: innerRadius,\n borderBottomRightRadius: innerRadius,\n padding: '0 !important',\n boxShadow: `inset 1px 0 0 ${dividerColor}`,\n '& svg': {\n margin: 0,\n },\n }),\n };\n};\n\nfunction toCssWidth(width: number | string): string {\n return typeof width === 'number' ? `${width}px` : width;\n}\n","import type { GrafanaTheme2 } from '@grafana/data';\n\n/**\n * Default gradient colors for the assistant\n */\nconst GRADIENT_COLORS = {\n PURPLE: 'rgb(168, 85, 247)',\n ORANGE: 'rgb(249, 115, 22)',\n} as const;\n\n// FIXME: use SDK as single source of truth for these color schemes?\n\n/**\n * Returns the colors of the background gradient based on the theme.\n *\n * @param theme - The Grafana theme object.\n * @returns The colors of the background gradient as tuple.\n */\nexport const getBackgroundGradientColors = (theme: GrafanaTheme2): [string, string] => {\n const defaultGradientColors: [string, string] = [GRADIENT_COLORS.PURPLE, GRADIENT_COLORS.ORANGE];\n\n // Check if the theme does not use gradients by default\n if (isThemeWithoutGradients(theme)) {\n return defaultGradientColors;\n }\n\n // If the theme uses gradients, extract the colors from the gradient string\n const gradientString = theme.colors.gradients.brandHorizontal;\n const hexColorRegex = /#[0-9A-Fa-f]{6}/g;\n const matches = gradientString.match(hexColorRegex);\n if (!matches || matches.length < 2) {\n // Fallback to default colors if extraction fails\n return defaultGradientColors;\n }\n\n return [matches[0], matches[1]];\n};\n\n/**\n * Creates animation keyframes for a rotating gradient border effect.\n * This is used for loading states in inputs and other components.\n *\n * @param theme - The Grafana theme object\n * @param backgroundColor - The background color to use in the animation\n * @param color1 - First gradient color (optional, defaults to theme purple)\n * @param color2 - Second gradient color (optional, defaults to theme orange)\n * @returns Animation keyframes object for use with @emotion/css keyframes\n *\n * @example\n * ```ts\n * const borderAnimation = keyframes({\n * label: 'border-animation',\n * ...createBorderAnimation(theme, theme.colors.background.primary),\n * });\n * ```\n */\nexport const createBorderAnimation = (\n theme: GrafanaTheme2,\n backgroundColor: string,\n color1?: string,\n color2?: string\n): Record<string, { backgroundImage: string }> => {\n const animationSteps = Array.from({ length: 101 }, (_, i) => i);\n const animationFrames: Record<string, { backgroundImage: string }> = {};\n const [gradientColor1, gradientColor2] = getBackgroundGradientColors(theme);\n\n const finalColor1 = color1 ?? gradientColor1;\n const finalColor2 = color2 ?? gradientColor2;\n\n for (const step of animationSteps) {\n animationFrames[`${step}%`] = {\n backgroundImage: `\n linear-gradient(${backgroundColor}, ${backgroundColor}),\n conic-gradient(from ${step * 3.6}deg, transparent 60%, ${finalColor1} 80%, ${finalColor2} 100%, transparent 15%)\n `,\n };\n }\n\n return animationFrames;\n};\n\n/**\n * Checks if the theme is a \"default\" theme (dark or light) that does not use or expose gradients.\n *\n * @param theme - The Grafana theme object.\n * @returns True if the theme does not use gradients, false otherwise.\n */\nconst isThemeWithoutGradients = (theme: GrafanaTheme2) => {\n const name = theme.name.toLowerCase().replace(/^visual refresh \\((.+)\\)$/, '$1');\n return name === 'dark' || name === 'light';\n};\n","import type { InlineToolRunnable } from '../tools/types';\n\nexport interface InlineAssistantPromptOptions {\n prompt: string;\n agentName?: string;\n agentId?: string;\n systemPrompt?: string;\n tools?: InlineToolRunnable[];\n onStart?: () => void;\n onDelta?: (delta: string) => void;\n onComplete?: (text: string) => void;\n onError?: (error: Error) => void;\n}\n\n/** Reasoning effort for each model call of an inline assistant. */\nexport type InlineAssistantReasoningLevel = 'none' | 'low' | 'medium' | 'high' | 'xhigh' | 'max';\n\n/**\n * How the agent behind an inline assistant runs. It is fixed when the instance is created and\n * applies to every prompt sent to it. Omitted fields keep the defaults, which suit short content\n * generation; raise them for agentic work such as multi-step discovery with your own tools.\n * Grafana Assistant releases that predate this config ignore it and run with the defaults.\n */\nexport interface InlineAssistantConfig {\n /** Most model calls per prompt, an integer from 1 to 76. The agent stops after the last one. Default 5. */\n maxSteps?: number;\n /** Use the smaller, faster model. Default true. */\n weak?: boolean;\n /** Reasoning effort per model call. Default 'none'. */\n reasoningLevel?: InlineAssistantReasoningLevel;\n /** Most output tokens per model call, an integer from 1 to 16000. Default 4096. */\n maxTokens?: number;\n}\n\nexport interface InlineAssistant {\n sendPrompt(options: InlineAssistantPromptOptions): Promise<void>;\n cancel(): void;\n dispose(): void;\n}\n\nexport type InlineAssistantFactory = (origin: string, config?: InlineAssistantConfig) => Promise<InlineAssistant>;\nexport type InlineAssistantInitializer = () => Promise<void>;\n\n// Global registry keys for cross-plugin sharing\nconst GLOBAL_FACTORY_KEY = '__grafanaAssistantInlineFactory__';\nconst GLOBAL_INITIALIZER_KEY = '__grafanaAssistantInlineInitializer__';\nconst GLOBAL_INITIALIZATION_PROMISE_KEY = '__grafanaAssistantInlineInitPromise__';\n\nexport function setInlineAssistantFactory(fn: InlineAssistantFactory): void {\n const existing = window[GLOBAL_FACTORY_KEY] as InlineAssistantFactory | undefined;\n if (existing && existing !== fn) {\n console.warn('InlineAssistant factory already set; ignoring subsequent setInlineAssistantFactory call');\n return;\n }\n if (!existing) {\n window[GLOBAL_FACTORY_KEY] = fn;\n }\n}\n\n/**\n * Register a lazy initializer that will be called on first use.\n * The plugin code should register this to enable lazy loading of the inline assistant.\n *\n * This uses global storage (window) so that all plugins share the same initializer,\n * regardless of which plugin instance or package version loads first.\n */\nexport function setInlineAssistantInitializer(fn: InlineAssistantInitializer): void {\n const existing = window[GLOBAL_INITIALIZER_KEY] as InlineAssistantInitializer | undefined;\n if (existing && existing !== fn) {\n console.warn('InlineAssistant initializer already set; ignoring subsequent setInlineAssistantInitializer call');\n return;\n }\n if (!existing) {\n window[GLOBAL_INITIALIZER_KEY] = fn;\n }\n}\n\n/**\n * Ensure the inline assistant is initialized. If an initializer is registered,\n * it will be called on first use. Otherwise, checks if factory is already registered.\n *\n * Uses global storage (window) so that initialization is shared across all plugins.\n */\nexport async function ensureInlineAssistantInitialized(): Promise<void> {\n // If factory is already set, we're good\n const factory = window[GLOBAL_FACTORY_KEY] as InlineAssistantFactory | undefined;\n if (factory) {\n return;\n }\n\n // If no initializer is registered, throw error\n const initializer = window[GLOBAL_INITIALIZER_KEY] as InlineAssistantInitializer | undefined;\n if (!initializer) {\n throw new Error(\n 'InlineAssistant not initialized. Make sure the Grafana Assistant plugin is loaded and initialized.'\n );\n }\n\n // If initialization is in progress, wait for it\n const existingPromise = window[GLOBAL_INITIALIZATION_PROMISE_KEY] as Promise<void> | null | undefined;\n if (existingPromise !== null && existingPromise !== undefined) {\n return existingPromise;\n }\n\n // Start initialization\n const initPromise = (async () => {\n try {\n await initializer();\n } catch (err) {\n // Reset on error so retry is possible\n window[GLOBAL_INITIALIZATION_PROMISE_KEY] = null;\n throw err;\n }\n })();\n\n window[GLOBAL_INITIALIZATION_PROMISE_KEY] = initPromise;\n return initPromise;\n}\n\nexport function getInlineAssistantFactory(): InlineAssistantFactory {\n const factory = window[GLOBAL_FACTORY_KEY] as InlineAssistantFactory | undefined;\n if (!factory) {\n throw new Error('InlineAssistant factory not initialized. Make sure the Grafana Assistant plugin is loaded.');\n }\n return factory;\n}\n","const nestedErrorKeys = ['message', 'error', 'err', 'detail', 'details'] as const;\n\nfunction getStringValue(value: unknown): string | null {\n if (typeof value !== 'string') {\n return null;\n }\n\n const trimmedValue = value.trim();\n return trimmedValue === '' ? null : trimmedValue;\n}\n\nfunction isUnhelpfulErrorMessage(message: string | null): boolean {\n if (!message) {\n return true;\n }\n\n return message === '[object Object]' || message === 'Error' || message === 'Unknown error';\n}\n\nfunction extractNestedErrorMessage(error: unknown, visited = new Set<object>()): string | null {\n const directString = getStringValue(error);\n if (directString) {\n return directString;\n }\n\n if (error instanceof Error) {\n const errorMessage = getStringValue(error.message);\n if (!isUnhelpfulErrorMessage(errorMessage)) {\n return errorMessage;\n }\n\n const nestedErrorMessage = extractNestedErrorMessage(error.cause, visited);\n if (nestedErrorMessage) {\n return nestedErrorMessage;\n }\n\n const ownPropertiesMessage = extractNestedErrorMessage(\n Object.fromEntries(\n Object.entries(error as Error & Record<string, unknown>).filter(([key]) => key !== 'message' && key !== 'name')\n ),\n visited\n );\n if (ownPropertiesMessage) {\n return ownPropertiesMessage;\n }\n\n return errorMessage ?? getStringValue(error.name) ?? null;\n }\n\n if (!error || typeof error !== 'object') {\n return null;\n }\n\n if (visited.has(error)) {\n return null;\n }\n visited.add(error);\n\n const errorRecord = error as Record<string, unknown>;\n\n if ('data' in errorRecord) {\n const nestedDataMessage = extractNestedErrorMessage(errorRecord.data, visited);\n if (nestedDataMessage) {\n return nestedDataMessage;\n }\n }\n\n for (const key of nestedErrorKeys) {\n if (key in errorRecord) {\n const nestedMessage = extractNestedErrorMessage(errorRecord[key], visited);\n if (nestedMessage) {\n return nestedMessage;\n }\n }\n }\n\n const status = errorRecord.status;\n const statusText = getStringValue(errorRecord.statusText);\n if ((typeof status === 'number' || typeof status === 'string') && statusText) {\n return `HTTP ${status}: ${statusText}`;\n }\n\n if (Array.isArray(error)) {\n const nestedMessages = error\n .map((item) => extractNestedErrorMessage(item, visited))\n .filter((message): message is string => Boolean(message));\n\n if (nestedMessages.length > 0) {\n return nestedMessages.join('; ');\n }\n }\n\n return null;\n}\n\n/**\n * Extract error message from backend errors (handles various error formats).\n *\n * @internal SDK-private helper for useInlineAssistant. Not part of the public\n * `@grafana/assistant` surface — do not re-export from `index.ts`.\n */\nexport function extractErrorMessage(error: unknown): string {\n const extractedMessage = extractNestedErrorMessage(error);\n if (extractedMessage) {\n return extractedMessage;\n }\n\n // Objects that expose no message are not serialized: fetch-like errors carry\n // the request URL, headers and body on `config`, which would end up in the\n // messages this helper feeds back to callers.\n if (error && typeof error === 'object') {\n return 'Unknown error';\n }\n\n if (error == null) {\n return 'Unknown error';\n }\n\n return String(error);\n}\n","import { useState, useCallback, useRef, useEffect } from 'react';\nimport type { InlineAssistantOptions, InlineAssistantResult } from './types';\nimport {\n getInlineAssistantFactory,\n type InlineAssistant,\n type InlineAssistantConfig,\n ensureInlineAssistantInitialized,\n} from './inlineAssistant';\nimport { extractErrorMessage } from '../utils/errorHandling';\n\n/**\n * React hook for inline assistant generation with streaming support.\n *\n * This hook enables generating content (like panel titles or descriptions) inline\n * without opening the assistant sidebar. Each hook instance creates its own chat\n * conversation, so all generations from the same instance are grouped together.\n * Generated content is ephemeral - it won't appear in the user's chat history\n * but will be tracked in the admin UI for analytics.\n *\n * Uses the full BaseMultiStepAgent infrastructure for tool execution and multi-step workflows.\n *\n * The implementation is lazy-loaded on first use to reduce initial bundle size.\n *\n * `config` sets how the agent runs (steps, model, reasoning, output tokens). It is read when the\n * first generation creates the conversation; later changes do not apply to it.\n *\n * @example\n * ```typescript\n * function PanelEditor() {\n * const { generate, isGenerating, content, error, reset } = useInlineAssistant();\n * const [title, setTitle] = useState('');\n *\n * const handleGenerate = () => {\n * generate({\n * prompt: 'Generate a panel title for CPU metrics',\n * origin: 'grafana/panel-editor/title',\n * systemPrompt: 'Generate only the title text, no explanation',\n * onComplete: (text) => setTitle(text.trim()),\n * onError: (err) => console.error(err)\n * });\n * };\n *\n * return (\n * <div>\n * <input value={title} onChange={(e) => setTitle(e.target.value)} />\n * <button onClick={handleGenerate} disabled={isGenerating}>\n * {isGenerating ? 'Generating...' : 'Generate with Assistant'}\n * </button>\n * {isGenerating && <div>{content}</div>}\n * </div>\n * );\n * }\n * ```\n *\n * @example\n * ```typescript\n * // Using tools with inline assistant\n * import { lokiQueryHandlerTool } from 'agent/tools';\n *\n * function ComponentWithTools() {\n * const { generate } = useInlineAssistant();\n *\n * const handleGenerate = async () => {\n * await generate({\n * prompt: 'Query Loki for error logs from the last hour',\n * origin: 'my-app/component',\n * tools: [lokiQueryHandlerTool],\n * onComplete: (text) => console.log('Generated:', text),\n * });\n * };\n *\n * return <button onClick={handleGenerate}>Generate</button>;\n * }\n * ```\n */\nexport function useInlineAssistant(config?: InlineAssistantConfig): InlineAssistantResult {\n const [isGenerating, setIsGenerating] = useState(false);\n const [content, setContent] = useState('');\n const [error, setError] = useState<Error | null>(null);\n const assistantRef = useRef<InlineAssistant | null>(null);\n const configRef = useRef(config);\n configRef.current = config;\n\n /**\n * Reset error and content state\n */\n const reset = useCallback(() => {\n setError(null);\n setContent('');\n }, []);\n\n /**\n * Cancel the current generation\n */\n const cancel = useCallback(() => {\n if (assistantRef.current) {\n assistantRef.current.cancel();\n }\n setIsGenerating(false);\n }, []);\n\n /**\n * Generate content with the given options\n */\n const generate = useCallback(async (options: InlineAssistantOptions): Promise<void> => {\n // Reset state\n setError(null);\n setContent('');\n setIsGenerating(true);\n\n try {\n // Ensure the inline assistant is initialized (lazy-loads on first use)\n await ensureInlineAssistantInitialized();\n\n const factory = getInlineAssistantFactory();\n\n // Create or reuse assistant for this origin\n if (!assistantRef.current) {\n assistantRef.current = await factory(options.origin, configRef.current);\n }\n\n await assistantRef.current.sendPrompt({\n prompt: options.prompt,\n agentName: options.agentName,\n agentId: options.agentId,\n systemPrompt: options.systemPrompt,\n tools: options.tools,\n onStart: () => {\n setIsGenerating(true);\n },\n onDelta: (delta) => {\n setContent((prev) => prev + delta);\n options.onDelta?.(delta);\n },\n onComplete: (text) => {\n setContent(text);\n setIsGenerating(false);\n options.onComplete?.(text);\n },\n onError: (err) => {\n setError(err);\n setIsGenerating(false);\n options.onError?.(err);\n },\n });\n } catch (err) {\n const error = new Error(extractErrorMessage(err), { cause: err });\n setError(error);\n setIsGenerating(false);\n options.onError?.(error);\n }\n }, []);\n\n // Cleanup on unmount\n useEffect(() => {\n return () => {\n if (assistantRef.current) {\n assistantRef.current.cancel();\n assistantRef.current.dispose();\n assistantRef.current = null;\n }\n };\n }, []);\n\n return {\n generate,\n isGenerating,\n content,\n error,\n cancel,\n reset,\n };\n}\n","import { useCallback, useEffect, useRef } from 'react';\nimport { useInlineAssistant } from '../../inline/useInlineAssistant';\n\nexport interface UseAIGenerationOptions {\n value: string;\n onChange: (value: string) => void;\n origin: string;\n systemPrompt?: string;\n onComplete?: (text: string) => void;\n onError?: (error: Error) => void;\n onDelta?: (delta: string) => void;\n disabled?: boolean;\n autoGenerate?: boolean;\n streaming?: boolean;\n getUserPrompt?: (textInput: string) => string;\n}\n\nexport function useAIGeneration({\n value,\n onChange,\n origin,\n systemPrompt,\n onComplete,\n onError,\n onDelta,\n disabled = false,\n autoGenerate = false,\n streaming = false,\n getUserPrompt,\n}: UseAIGenerationOptions) {\n const { generate, isGenerating, content, error, reset } = useInlineAssistant();\n const hasAutoGenerated = useRef(false);\n const valueBeforeGeneration = useRef(value);\n const getUserPromptRef = useRef(getUserPrompt);\n getUserPromptRef.current = getUserPrompt;\n\n let displayValue: string;\n if (isGenerating) {\n if (streaming) {\n displayValue = content;\n } else {\n displayValue = '';\n }\n } else {\n displayValue = value;\n }\n const resolvedPrompt = getUserPrompt ? getUserPrompt(value.trim()) : value.trim();\n const isSendDisabled = !resolvedPrompt || disabled || isGenerating;\n\n const doGenerate = useCallback(\n (prompt: string) => {\n valueBeforeGeneration.current = value;\n onChange('');\n reset();\n\n generate({\n prompt,\n origin,\n systemPrompt,\n onDelta,\n onComplete: (text) => {\n onChange(text);\n onComplete?.(text);\n },\n onError: (err) => {\n onChange(valueBeforeGeneration.current);\n onError?.(err);\n },\n }).catch((error: unknown) => {\n console.warn('Failed to handle the AI generation result:', error);\n });\n },\n [value, onChange, origin, systemPrompt, onDelta, onComplete, onError, generate, reset]\n );\n\n // Auto-generate at most once, on mount, evaluating the props as they are at mount.\n const maybeAutoGenerateRef = useRef<() => void>(() => {});\n maybeAutoGenerateRef.current = () => {\n if (autoGenerate && systemPrompt && !value && !hasAutoGenerated.current && !disabled) {\n hasAutoGenerated.current = true;\n doGenerate(systemPrompt);\n }\n };\n useEffect(() => {\n maybeAutoGenerateRef.current();\n }, []);\n\n const handleGenerate = useCallback(() => {\n const fn = getUserPromptRef.current;\n const prompt = fn ? fn(value.trim()) : value.trim();\n if (!prompt || disabled || isGenerating) {\n return;\n }\n doGenerate(prompt);\n }, [value, disabled, isGenerating, doGenerate]);\n\n return {\n displayValue,\n isSendDisabled,\n handleGenerate,\n isGenerating,\n error,\n };\n}\n","import { useRef, useState } from 'react';\n\nconst GENERATING_PHRASES = [\n 'Generating...',\n 'Brewing...',\n 'Cooking...',\n 'Crunching...',\n 'Phrasing...',\n 'Wording...',\n 'Crafting...',\n 'Composing...',\n 'Drafting...',\n 'Shaping...',\n 'Forming...',\n 'Molding...',\n 'Sketching...',\n 'Whipping up...',\n 'Conjuring...',\n 'Stirring...',\n];\n\n/**\n * Returns a random placeholder phrase while generating, or the provided\n * default placeholder when idle. A new phrase is picked each time generation starts.\n */\nexport function useGeneratingPlaceholder(isGenerating: boolean, defaultPlaceholder: string): string {\n const [phrase, setPhrase] = useState('');\n const wasGenerating = useRef(false);\n\n if (isGenerating && !wasGenerating.current) {\n const next = GENERATING_PHRASES[Math.floor(Math.random() * GENERATING_PHRASES.length)];\n setPhrase(next);\n wasGenerating.current = true;\n return next;\n }\n\n if (!isGenerating) {\n wasGenerating.current = false;\n }\n\n return isGenerating ? phrase : defaultPlaceholder;\n}\n","import type { KeyboardEvent } from 'react';\nimport { Input, IconButton, useStyles2 } from '@grafana/ui';\nimport { css, cx, keyframes } from '@emotion/css';\nimport type { GrafanaTheme2 } from '@grafana/data';\nimport { createBorderAnimation, getBackgroundGradientColors } from '../../utils/theme';\nimport type { AIInputProps } from './types';\nimport { useAIGeneration } from './useAIGeneration';\nimport { useGeneratingPlaceholder } from './useGeneratingPlaceholder';\n\nexport interface AITextInputProps extends AIInputProps {}\n\n/**\n * An AI-powered controlled text input component that uses the Grafana Assistant engine to generate content.\n * Features an integrated send button as well as a gradient border animation while generating.\n */\nexport function AITextInput({\n value,\n onChange,\n placeholder,\n origin,\n systemPrompt,\n onComplete,\n onError,\n onDelta,\n disabled = false,\n autoGenerate = false,\n streaming = false,\n getUserPrompt,\n className,\n 'data-testid': dataTestId,\n}: AITextInputProps) {\n const { displayValue, isSendDisabled, handleGenerate, isGenerating, error } = useAIGeneration({\n value,\n onChange,\n origin,\n systemPrompt,\n onComplete,\n onError,\n onDelta,\n disabled,\n autoGenerate,\n streaming,\n getUserPrompt,\n });\n const styles = useStyles2(getStyles);\n const activePlaceholder = useGeneratingPlaceholder(isGenerating, placeholder ?? 'Ask AI to generate...');\n\n const handleKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {\n // Cmd/Ctrl + Enter to send\n if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) {\n e.preventDefault();\n handleGenerate();\n }\n };\n\n const addonAfter = (\n <IconButton\n name=\"ai-sparkle\"\n onClick={handleGenerate}\n disabled={isSendDisabled}\n tooltip={isSendDisabled ? 'Enter text to generate' : 'Generate with AI'}\n data-testid={dataTestId ? `${dataTestId}-send` : undefined}\n />\n );\n\n return (\n <div className={cx(styles.wrapper, { [styles.animatedWrapper]: isGenerating }, className)} data-testid={dataTestId}>\n <Input\n value={displayValue}\n onKeyDown={handleKeyDown}\n onChange={(e) => onChange(e.currentTarget.value)}\n placeholder={activePlaceholder}\n disabled={disabled || isGenerating}\n suffix={addonAfter}\n invalid={!!error}\n data-testid={dataTestId ? `${dataTestId}-input` : undefined}\n />\n </div>\n );\n}\n\nconst getStyles = (theme: GrafanaTheme2) => {\n const backgroundColor = theme.colors.background.primary;\n const borderAnimation = keyframes({\n label: 'ai-input-border-animation',\n ...createBorderAnimation(theme, backgroundColor),\n });\n\n const [gradientColor1, gradientColor2] = getBackgroundGradientColors(theme);\n\n return {\n wrapper: css({\n label: 'ai-text-input-wrapper',\n position: 'relative',\n border: '1px solid transparent',\n borderRadius: theme.shape.radius.default,\n cornerShape: 'squircle',\n }),\n animatedWrapper: css({\n label: 'ai-text-input-animated',\n border: '1px solid transparent',\n // Set initial backgroundImage with both gradients so Chrome can animate properly\n backgroundImage: `\n linear-gradient(${backgroundColor}, ${backgroundColor}),\n conic-gradient(from 0deg, transparent 60%, ${gradientColor1} 80%, ${gradientColor2} 100%, transparent 15%)\n `,\n backgroundOrigin: 'border-box',\n backgroundClip: 'padding-box, border-box',\n animation: `${borderAnimation} 2s linear infinite`,\n '& input': {\n // Remove the default border from the input when animated wrapper is active\n border: 'none !important',\n },\n }),\n };\n};\n","import type { KeyboardEvent } from 'react';\nimport { TextArea, IconButton, useStyles2 } from '@grafana/ui';\nimport { css, cx, keyframes } from '@emotion/css';\nimport type { GrafanaTheme2 } from '@grafana/data';\nimport { createBorderAnimation, getBackgroundGradientColors } from '../../utils/theme';\nimport type { AIInputProps } from './types';\nimport { useAIGeneration } from './useAIGeneration';\nimport { useGeneratingPlaceholder } from './useGeneratingPlaceholder';\n\nexport interface AITextAreaProps extends AIInputProps {\n /** Number of rows for the textarea */\n rows?: number;\n}\n\n/**\n * An AI-powered controlled textarea component that uses the Grafana Assistant engine to generate content.\n * Features an integrated send button as well as a gradient border animation while generating.\n */\nexport function AITextArea({\n value,\n onChange,\n placeholder,\n origin,\n systemPrompt,\n onComplete,\n onError,\n onDelta,\n disabled = false,\n autoGenerate = false,\n streaming = false,\n getUserPrompt,\n rows = 4,\n className,\n 'data-testid': dataTestId,\n}: AITextAreaProps) {\n const { displayValue, isSendDisabled, handleGenerate, isGenerating, error } = useAIGeneration({\n value,\n onChange,\n origin,\n systemPrompt,\n onComplete,\n onError,\n onDelta,\n disabled,\n autoGenerate,\n streaming,\n getUserPrompt,\n });\n const styles = useStyles2(getStyles);\n const activePlaceholder = useGeneratingPlaceholder(\n isGenerating,\n placeholder ?? 'Ask AI to generate... (Cmd/Ctrl+Enter to send)'\n );\n const effectiveRows = Math.max(rows, 2);\n\n const handleKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {\n // Cmd/Ctrl + Enter to send\n if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) {\n e.preventDefault();\n handleGenerate();\n }\n };\n\n return (\n <div\n className={cx(styles.textareaWrapper, { [styles.animatedWrapper]: isGenerating }, className)}\n data-testid={dataTestId}\n >\n <TextArea\n value={displayValue}\n onKeyDown={handleKeyDown}\n onChange={(e) => onChange(e.currentTarget.value)}\n placeholder={activePlaceholder}\n disabled={disabled || isGenerating}\n rows={effectiveRows}\n className={styles.textarea}\n invalid={!!error}\n data-testid={dataTestId ? `${dataTestId}-textarea` : undefined}\n />\n <IconButton\n name=\"ai-sparkle\"\n onClick={handleGenerate}\n disabled={isSendDisabled}\n className={styles.sendButton}\n aria-label=\"Generate with AI\"\n tooltip={isSendDisabled ? 'Enter text to generate' : 'Generate with AI (Cmd/Ctrl+Enter)'}\n data-testid={dataTestId ? `${dataTestId}-send` : undefined}\n />\n </div>\n );\n}\n\nconst getStyles = (theme: GrafanaTheme2) => {\n const backgroundColor = theme.colors.background.primary;\n const borderAnimation = keyframes({\n label: 'ai-textarea-border-animation',\n ...createBorderAnimation(theme, backgroundColor),\n });\n\n const [gradientColor1, gradientColor2] = getBackgroundGradientColors(theme);\n\n return {\n textareaWrapper: css({\n label: 'ai-textarea-wrapper',\n position: 'relative',\n border: '1px solid transparent',\n borderRadius: theme.shape.radius.default,\n cornerShape: 'squircle',\n }),\n animatedWrapper: css({\n label: 'ai-textarea-animated',\n border: '1px solid transparent',\n // Set initial backgroundImage with both gradients so Chrome can animate properly\n backgroundImage: `\n linear-gradient(${backgroundColor}, ${backgroundColor}),\n conic-gradient(from 0deg, transparent 60%, ${gradientColor1} 80%, ${gradientColor2} 100%, transparent 15%)\n `,\n backgroundOrigin: 'border-box',\n backgroundClip: 'padding-box, border-box',\n animation: `${borderAnimation} 2s linear infinite`,\n '& textarea': {\n // Remove the default border from the textarea when animated wrapper is active\n border: 'none !important',\n },\n }),\n textarea: css({\n label: 'ai-textarea',\n // ensures the text does not \"underflow\" the send button\n paddingRight: theme.spacing(4),\n // Keep at least a 2-row visual height even if outer styles try to shrink the control\n minHeight: theme.spacing(6),\n '& textarea': {\n minHeight: theme.spacing(6),\n },\n // Hide scrollbar\n scrollbarWidth: 'none', // Firefox\n '&::-webkit-scrollbar': {\n display: 'none', // Chrome, Safari, Edge\n },\n }),\n sendButton: css({\n label: 'ai-textarea-send',\n position: 'absolute',\n right: theme.spacing(1),\n top: theme.spacing(1),\n }),\n };\n};\n","import { CoreApp, type DataSourceApi, type DataSourceInstanceSettings } from '@grafana/data';\nimport type { DataQuery, DataSourceJsonData } from '@grafana/schema';\nimport type { ComponentSize } from '@grafana/ui';\nimport { createAssistantContextItem } from '../../context';\nimport { useAssistant } from '../../hook';\nimport { OpenAssistantButtonView } from './OpenAssistantButton';\n\nfunction queryIsEmpty(query: DataQuery): boolean {\n const dataQueryProps = ['refId', 'hide', 'key', 'queryType', 'datasource'];\n\n for (const key in query) {\n if (key === 'label') {\n continue;\n }\n if (!dataQueryProps.includes(key)) {\n return false;\n }\n }\n\n return true;\n}\n\nexport interface QueryWithAssistantButtonProps<TQuery extends DataQuery = DataQuery> {\n size?: ComponentSize;\n currentQuery: TQuery;\n queries: TQuery[];\n dataSourceInstanceSettings: DataSourceInstanceSettings;\n app?: CoreApp;\n datasourceApi: DataSourceApi<TQuery, DataSourceJsonData> | null;\n title?: string;\n}\n\nexport function QueryWithAssistantButton<TQuery extends DataQuery = DataQuery>({\n size,\n currentQuery,\n queries,\n dataSourceInstanceSettings,\n app,\n datasourceApi,\n title = 'Query with Assistant',\n}: QueryWithAssistantButtonProps<TQuery>) {\n const { isAvailable, openAssistant } = useAssistant();\n if (!isAvailable || !openAssistant) {\n return null;\n }\n\n const origin = `grafana/query-editor/${dataSourceInstanceSettings.type}/${app ?? CoreApp.Unknown ?? 'unknown'}`;\n\n const hasCurrentQuery = !queryIsEmpty(currentQuery);\n const otherQueries = queries.filter((q) => q.refId !== currentQuery.refId && !queryIsEmpty(q));\n\n const context = [\n createAssistantContextItem('datasource', {\n datasourceUid: dataSourceInstanceSettings.uid,\n }),\n ];\n\n if (hasCurrentQuery) {\n context.push(\n createAssistantContextItem('structured', {\n title: 'Current query',\n data: currentQuery,\n })\n );\n }\n\n if (otherQueries.length > 0) {\n context.push(\n createAssistantContextItem('structured', {\n title: 'Other queries',\n data: {\n queries: otherQueries,\n },\n })\n );\n }\n\n const queryDisplayText =\n hasCurrentQuery && datasourceApi?.getQueryDisplayText ? datasourceApi.getQueryDisplayText(currentQuery) : null;\n\n const isUpdating = !!queryDisplayText;\n const actionText = isUpdating\n ? 'Help me update the current query to answer my questions and provide the insights I need.'\n : 'Help me create a new query to answer my questions and provide the insights I need.';\n\n const codeBlockLines: string[] = [];\n\n if (queryDisplayText) {\n codeBlockLines.push(`Current query: ${queryDisplayText}`);\n }\n\n codeBlockLines.push(`Selected data source: ${dataSourceInstanceSettings.name}`);\n\n const actionableSentence = isUpdating\n ? 'Please describe what you want to change or improve in this query.'\n : \"Please describe what you want to query and what insights you're looking for.\";\n\n const prompt = [actionText, '```', ...codeBlockLines, '```', actionableSentence].join('\\n');\n\n return (\n <OpenAssistantButtonView\n prompt={prompt}\n origin={origin}\n context={context}\n autoSend={false}\n title={title}\n size={size}\n openAssistant={openAssistant}\n />\n );\n}\n","import { useState, useRef, useEffect } from 'react';\n\nconst DEFAULT_EXAMPLE_PROMPTS = [\n 'What does this panel show?',\n 'Explain the trend in this data',\n 'Why is there a spike?',\n 'Add a threshold at 80%',\n 'Change the legend to table mode',\n];\n\nexport { DEFAULT_EXAMPLE_PROMPTS };\n\nexport function useAnimatedPlaceholder(staticPlaceholder: string, prompts: string[], hasUserInput: boolean): string {\n const [display, setDisplay] = useState('');\n const indexRef = useRef(0);\n const charRef = useRef(0);\n const phaseRef = useRef<'typing' | 'pause' | 'erasing'>('typing');\n\n useEffect(() => {\n indexRef.current = 0;\n charRef.current = 0;\n phaseRef.current = 'typing';\n setDisplay('');\n\n if (hasUserInput || prompts.length === 0) {\n return;\n }\n\n const tick = () => {\n const currentPrompt = prompts[indexRef.current];\n\n if (phaseRef.current === 'typing') {\n charRef.current++;\n setDisplay(currentPrompt.slice(0, charRef.current));\n if (charRef.current >= currentPrompt.length) {\n phaseRef.current = 'pause';\n }\n } else if (phaseRef.current === 'pause') {\n phaseRef.current = 'erasing';\n } else if (phaseRef.current === 'erasing') {\n charRef.current--;\n setDisplay(currentPrompt.slice(0, charRef.current));\n if (charRef.current <= 0) {\n phaseRef.current = 'typing';\n indexRef.current = (indexRef.current + 1) % prompts.length;\n }\n }\n };\n\n const getDelay = () => {\n if (phaseRef.current === 'pause') {\n return 800;\n }\n if (phaseRef.current === 'erasing') {\n return 15;\n }\n return 30 + Math.random() * 20;\n };\n\n let timeoutId: ReturnType<typeof setTimeout>;\n const schedule = () => {\n timeoutId = setTimeout(() => {\n tick();\n schedule();\n }, getDelay());\n };\n schedule();\n\n return () => clearTimeout(timeoutId);\n }, [hasUserInput, prompts]);\n\n if (hasUserInput || prompts.length === 0) {\n return staticPlaceholder;\n }\n\n return display;\n}\n","import { type KeyboardEvent, useRef, useState, useEffect, useCallback } from 'react';\nimport { IconButton, Input, useStyles2 } from '@grafana/ui';\nimport { css, cx, keyframes } from '@emotion/css';\nimport type { GrafanaTheme2 } from '@grafana/data';\nimport { trackPromptCardDisplayed } from '../../analyticsEvents';\nimport type { ChatContextItem } from '../../context/types';\nimport { useAssistant } from '../../hook';\nimport type { OpenAssistantProps } from '../../sidebar';\nimport { createBorderAnimation, getBackgroundGradientColors } from '../../utils/theme';\nimport { useAnimatedPlaceholder, DEFAULT_EXAMPLE_PROMPTS } from './useAnimatedPlaceholder';\n\nexport interface AssistantPromptCardProps {\n /** Origin of the request for analytics tracking. Should be a structured string using forward slashes. */\n origin: string;\n /** Context items passed to the assistant on submit. Created with `createAssistantContextItem`. */\n context?: ChatContextItem[];\n /** Assistant mode (e.g. 'dashboarding'). Defaults to 'assistant'. */\n mode?: string;\n /** Placeholder text for the input. */\n placeholder?: string;\n /** Example prompts to cycle through as animated placeholder text. Pass an empty array to disable. */\n examplePrompts?: string[];\n /** Called when the card should close (Escape key, close button). */\n onClose?: () => void;\n /** Called after a prompt is submitted, receives the prompt string. */\n onSubmit?: (prompt: string) => void;\n /** Called when the user clicks the card body. */\n onClick?: () => void;\n /** Whether the card border is animated. Defaults to true. */\n animated?: boolean;\n /** Extra CSS class for the root element. */\n className?: string;\n}\n\n/**\n * A prompt card component that opens the Grafana Assistant with a user-typed prompt and context.\n * Renders nothing if the assistant is not available. Positioning is the consumer's responsibility.\n */\nexport function AssistantPromptCard(props: AssistantPromptCardProps) {\n const { isAvailable, openAssistant } = useAssistant();\n if (!isAvailable || !openAssistant) {\n return null;\n }\n return <AssistantPromptCardView {...props} openAssistant={openAssistant} />;\n}\n\nexport interface AssistantPromptCardViewProps extends AssistantPromptCardProps {\n openAssistant: (props: OpenAssistantProps) => void;\n}\n\nexport function AssistantPromptCardView({\n origin,\n context,\n mode,\n placeholder,\n examplePrompts,\n animated = true,\n onClose,\n onSubmit,\n onClick,\n className,\n openAssistant,\n}: AssistantPromptCardViewProps) {\n const [prompt, setPrompt] = useState('');\n const inputRef = useRef<HTMLInputElement>(null);\n const styles = useStyles2(getStyles);\n const resolvedPrompts = examplePrompts ?? (placeholder !== undefined ? [] : DEFAULT_EXAMPLE_PROMPTS);\n const staticPlaceholder = placeholder ?? 'Ask Assistant...';\n const animatedPlaceholder = useAnimatedPlaceholder(staticPlaceholder, resolvedPrompts, prompt.length > 0);\n\n useEffect(() => {\n trackPromptCardDisplayed({ from: origin });\n }, [origin]);\n\n // biome-ignore lint/correctness/useExhaustiveDependencies: context is an intentional re-trigger to re-focus the input when the context changes\n useEffect(() => {\n const rafId = requestAnimationFrame(() => inputRef.current?.focus());\n return () => cancelAnimationFrame(rafId);\n }, [context]);\n\n const submit = useCallback(\n (text: string) => {\n const trimmed = text.trim();\n if (!trimmed) {\n return;\n }\n\n openAssistant({ prompt: trimmed, context, autoSend: true, origin, mode });\n onSubmit?.(trimmed);\n setPrompt('');\n },\n [openAssistant, context, origin, mode, onSubmit]\n );\n\n const handleKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {\n if (e.key === 'Enter' && !e.shiftKey) {\n e.preventDefault();\n submit(prompt);\n }\n\n if (e.key === 'Escape') {\n e.preventDefault();\n onClose?.();\n }\n };\n\n return (\n <div\n className={cx(animated ? styles.card : styles.cardStatic, className)}\n onClick={onClick}\n role=\"search\"\n aria-label={staticPlaceholder}\n data-testid=\"assistant-prompt-card\"\n >\n <div className={styles.inputRow}>\n <Input\n ref={inputRef}\n value={prompt}\n onChange={(e) => setPrompt(e.currentTarget.value)}\n onKeyDown={handleKeyDown}\n placeholder={animatedPlaceholder}\n suffix={\n <IconButton\n name=\"ai-sparkle\"\n onClick={() => submit(prompt)}\n disabled={!prompt.trim()}\n tooltip=\"Send to assistant\"\n aria-label=\"Send to assistant\"\n data-testid=\"assistant-prompt-card-send\"\n />\n }\n data-testid=\"assistant-prompt-card-input\"\n />\n </div>\n </div>\n );\n}\n\nfunction getGlowShadow(theme: GrafanaTheme2) {\n const baseShadow = theme.isDark ? 'rgb(17 18 23)' : 'rgb(245 245 245)';\n return [\n 'rgba(168, 85, 247, 0.25) 3px -1px 20px',\n 'rgba(249, 115, 22, 0.18) -5px 3px 40px',\n 'rgba(168, 85, 247, 0.12) 7px 4px 60px',\n `${baseShadow} 0 6px 30px`,\n ].join(', ');\n}\n\nconst getStyles = (theme: GrafanaTheme2) => {\n const backgroundColor = theme.colors.background.primary;\n const [gradientColor1, gradientColor2] = getBackgroundGradientColors(theme);\n\n const borderAnimation = keyframes({\n label: 'prompt-card-border',\n ...createBorderAnimation(theme, backgroundColor),\n });\n\n const cardBase = {\n label: 'assistant-prompt-card',\n position: 'relative' as const,\n display: 'flex',\n flexDirection: 'column' as const,\n gap: theme.spacing(1),\n padding: theme.spacing(1),\n borderRadius: theme.shape.radius.lg,\n boxShadow: getGlowShadow(theme),\n };\n\n return {\n card: css({\n ...cardBase,\n cornerShape: 'squircle',\n background: backgroundColor,\n border: '1px solid transparent',\n backgroundImage: `\n linear-gradient(${backgroundColor}, ${backgroundColor}),\n conic-gradient(from 0deg, transparent 60%, ${gradientColor1} 80%, ${gradientColor2} 100%, transparent 15%)\n `,\n backgroundOrigin: 'border-box',\n backgroundClip: 'padding-box, border-box',\n [theme.transitions.handleMotion('no-preference')]: {\n animation: `${borderAnimation} 2s linear infinite`,\n },\n }),\n cardStatic: css({\n ...cardBase,\n label: 'assistant-prompt-card-static',\n background: theme.colors.background.elevated,\n border: `1px solid ${theme.colors.border.weak}`,\n }),\n inputRow: css({\n label: 'prompt-card-input-row',\n display: 'flex',\n alignItems: 'center',\n gap: theme.spacing(0.5),\n '& input': {\n border: 'none !important',\n },\n }),\n };\n};\n","// Trimmed copy of apps/plugin/src/features/grots/appearance.ts (look model, palettes, appearanceOf). Keep in sync.\n/** Local-day drink gestures; independent of the saved appearance. */\nexport type GrotDaypart = 'morning' | 'evening';\n\n/**\n * The parts a Grot's pixel sprite is put together from, with their options in\n * the order its look editor shows them. Each part's first option is the\n * classic Grot.\n */\nconst options = {\n palette: [\n 'classic',\n 'mint',\n 'berry',\n 'glacier',\n 'night',\n 'moss',\n 'handheld',\n 'sunset',\n 'cotton',\n 'grape',\n 'ember',\n 'slate',\n ],\n crest: ['spikes', 'fin', 'mohawk', 'antenna', 'flame', 'sprout', 'horns', 'bald'],\n visor: ['band', 'goggles', 'slim', 'shades'],\n screen: ['bars', 'dots', 'tall', 'big', 'love', 'plus', 'dizzy', 'wink'],\n mouth: ['smile', 'grin', 'flat', 'fang', 'stache', 'wavy'],\n hat: [\n 'nohat',\n 'beanie',\n 'cap',\n 'crown',\n 'party',\n 'headset',\n 'wizard',\n 'cowboy',\n 'chef',\n 'viking',\n 'tophat',\n 'halo',\n 'flower',\n 'copter',\n 'hardhat',\n ],\n held: [\n 'empty',\n 'coffee',\n 'wrench',\n 'magnifier',\n 'chart',\n 'duck',\n 'pager',\n 'laptop',\n 'balloon',\n 'pizza',\n 'flag',\n 'donut',\n 'clip',\n 'bell',\n 'shield',\n 'bug',\n 'key',\n ],\n tail: ['curl', 'spike', 'bolt', 'heart', 'fluff', 'notail'],\n} as const;\n\nexport type GrotPart = keyof typeof options;\nexport type Appearance = { [P in GrotPart]: (typeof options)[P][number] };\nexport type GrotOption = Appearance[GrotPart];\n\n/** Typed per part, so a part's options are its own option type. */\nexport const grotOptions: { [P in GrotPart]: readonly Appearance[P][] } = options;\n\nexport const partLabels = {\n palette: 'Colors',\n crest: 'Crest',\n visor: 'Visor',\n screen: 'Screen',\n mouth: 'Mouth',\n hat: 'Hat',\n held: 'Holding',\n tail: 'Tail',\n} satisfies Record<GrotPart, string>;\n\n/** The parts in editor order, which is also the order an avatar string stores them in. */\n// Safe: `satisfies` forbids extra keys on the literal.\nexport const partOrder = Object.keys(partLabels) as GrotPart[];\n\nexport type GrotPalette = Appearance['palette'];\n\n/**\n * Grot's own illustration palettes. These are mascot colours, not UI colours:\n * they stay the same in light and dark themes, like the mascot artwork does.\n * `accent` is the UI token that stands in for the Grot on its surfaces.\n */\nexport const grotPalette: Record<\n GrotPalette,\n {\n outline: string;\n body: string;\n light: string;\n shade: string;\n crest: string;\n crestShade: string;\n visor: string;\n visorLight: string;\n screen: string;\n glyph: string;\n accent: string;\n }\n> = {\n // The brand guide's Grot colours: yellow body, orange crest, amber arms, purple visor.\n classic: {\n outline: '#2A1A2E',\n body: '#FAC20C',\n light: '#FFE07A',\n shade: '#F99F10',\n crest: '#EF6122',\n crestShade: '#B93A1C',\n visor: '#5545EF',\n visorLight: '#6F66E8',\n screen: '#1D1240',\n glyph: '#D6D3FF',\n accent: 'var(--color-brand-orange-500)',\n },\n mint: {\n outline: '#10222B',\n body: '#6FE0B4',\n light: '#B4F5D9',\n shade: '#3DB88C',\n crest: '#2B9C94',\n crestShade: '#1B6E6D',\n visor: '#143047',\n visorLight: '#1F4766',\n screen: '#0A1725',\n glyph: '#7FF3E6',\n accent: 'var(--color-emerald-600)',\n },\n berry: {\n outline: '#2A1124',\n body: '#F36AA9',\n light: '#FFA9D0',\n shade: '#C9478A',\n crest: '#8E44C9',\n crestShade: '#64289A',\n visor: '#2A1438',\n visorLight: '#43205A',\n screen: '#16081F',\n glyph: '#FF9AD5',\n accent: 'var(--color-pink-500)',\n },\n glacier: {\n outline: '#0E1B33',\n body: '#8CC8F5',\n light: '#CFEAFF',\n shade: '#5A99D8',\n crest: '#3A66D4',\n crestShade: '#26469C',\n visor: '#102B4C',\n visorLight: '#1B4170',\n screen: '#081627',\n glyph: '#A9ECFF',\n accent: 'var(--color-blue-500)',\n },\n night: {\n outline: '#120F1A',\n body: '#5B5472',\n light: '#7F7899',\n shade: '#403A54',\n crest: '#F05A28',\n crestShade: '#B93A1C',\n visor: '#17141F',\n visorLight: '#2A2536',\n screen: '#0B0910',\n glyph: '#FFA13A',\n accent: 'var(--color-brand-orange-600)',\n },\n moss: {\n outline: '#1B220E',\n body: '#B3D96A',\n light: '#D8F29D',\n shade: '#88B446',\n crest: '#4F8A3A',\n crestShade: '#376428',\n visor: '#2C2A14',\n visorLight: '#423F20',\n screen: '#15140A',\n glyph: '#FFD95A',\n accent: 'var(--color-green-500)',\n },\n handheld: {\n outline: '#0F380F',\n body: '#9BBC0F',\n light: '#C2D94A',\n shade: '#7A9A0C',\n crest: '#306230',\n crestShade: '#204A20',\n visor: '#306230',\n visorLight: '#3F7A3F',\n screen: '#0F380F',\n glyph: '#C2D94A',\n accent: 'var(--color-green-700)',\n },\n sunset: {\n outline: '#2B1426',\n body: '#FF9E5E',\n light: '#FFC79E',\n shade: '#F07A3E',\n crest: '#E8457A',\n crestShade: '#B02E5C',\n visor: '#3B2A6B',\n visorLight: '#54408F',\n screen: '#160D2E',\n glyph: '#FFD66B',\n accent: 'var(--color-orange-500)',\n },\n cotton: {\n outline: '#3A2340',\n body: '#F7C6E0',\n light: '#FFE3F1',\n shade: '#E9A3C6',\n crest: '#8FD3F4',\n crestShade: '#5FB3DC',\n visor: '#6A5ACD',\n visorLight: '#8A7CE0',\n screen: '#2A1F4D',\n glyph: '#FFFFFF',\n accent: 'var(--color-pink-400)',\n },\n grape: {\n outline: '#1E1238',\n body: '#9B6BFF',\n light: '#C4A6FF',\n shade: '#7A4FE0',\n crest: '#FFC94A',\n crestShade: '#D99A1E',\n visor: '#2B1A55',\n visorLight: '#3F2A7A',\n screen: '#120A26',\n glyph: '#C8FF6B',\n accent: 'var(--color-violet-500)',\n },\n // Body 3.8:1 against white and 4.9:1 against #111217, so the silhouette reads on light and dark.\n ember: {\n outline: '#2E0F0C',\n body: '#E4502A',\n light: '#FF8A5C',\n shade: '#BF3A1C',\n crest: '#FFB23E',\n crestShade: '#D98414',\n visor: '#3A1A2E',\n visorLight: '#5A2A44',\n screen: '#1A0A12',\n glyph: '#FFD27A',\n accent: 'var(--color-brand-orange-600)',\n },\n slate: {\n outline: '#161B26',\n body: '#6F849E',\n light: '#A3B4C8',\n shade: '#51657F',\n crest: '#4FB0C6',\n crestShade: '#2F7F94',\n visor: '#1B2536',\n visorLight: '#2C3B52',\n screen: '#0C121C',\n glyph: '#9FE8FF',\n accent: 'var(--color-neutral-500)',\n },\n};\n\n/** The classic Grot: every part's first option. */\nexport const classicLook: Appearance = {\n palette: 'classic',\n crest: 'spikes',\n visor: 'band',\n screen: 'bars',\n mouth: 'smile',\n hat: 'nohat',\n held: 'empty',\n tail: 'curl',\n};\n\n/** Options that were removed, by part: the id a saved look may still name, and the option that replaces it. */\nexport const renamedOptions: { [P in GrotPart]?: Record<string, Appearance[P]> } = {\n palette: { ghost: 'glacier' },\n mouth: { teeth: 'fang', blep: 'smile' },\n tail: { stub: 'spike' },\n};\n\ntype Renamed = { [Q in GrotPart]?: Record<string, Appearance[Q]> };\n\nfunction optionOf<P extends GrotPart>(part: P, value: string | undefined, renamed: Renamed): Appearance[P] | undefined {\n const current = grotOptions[part].find((option) => option === value);\n const table = renamed[part];\n // Own properties only: an id like \"constructor\" must not resolve to something inherited from Object.\n const renamedTo = value !== undefined && table && Object.keys(table).includes(value) ? table[value] : undefined;\n return current ?? renamedTo;\n}\n\nfunction withPart<P extends GrotPart>(look: Appearance, part: P, option: Appearance[P]): Appearance {\n return { ...look, [part]: option };\n}\n\nfunction pick<P extends GrotPart>(part: P, index: number): Appearance[P] {\n return grotOptions[part][index % grotOptions[part].length];\n}\n\n/** The colours of the first, two-part avatars (\"blob:yellow\"), as the palette closest to each. */\nconst legacyColors: Record<string, GrotPalette> = {\n yellow: 'classic',\n orange: 'classic',\n blue: 'glacier',\n green: 'mint',\n pink: 'berry',\n red: 'berry',\n};\n\nfunction hash(text: string): number {\n let h = 0;\n for (let i = 0; i < text.length; i++) {\n h = (h * 31 + text.charCodeAt(i)) | 0;\n }\n return Math.abs(h);\n}\n\n/**\n * The stored look, part by part. A part it does not name, such as one added\n * since it was saved, gets a stable option derived from the id. A removed option\n * maps to its replacement in renamedOptions first.\n */\nexport function appearanceWith(agent: { id: string; avatar?: string }, renamed: Renamed): Appearance {\n const avatar = agent.avatar ?? '';\n const stored = avatar.includes(':') ? [legacyColors[avatar.split(':')[1]]] : avatar.split('.');\n const seed = hash(agent.id);\n return partOrder.reduce(\n (look, part, i) =>\n withPart(look, part, optionOf(part, stored[i], renamed) ?? pick(part, Math.floor(seed / (i * 7 + 1)))),\n classicLook\n );\n}\n\n/** The stored look of an agent. Takes one argument, so it is safe to pass to `.map`. */\nexport const appearanceOf = (agent: { id: string; avatar?: string }): Appearance =>\n appearanceWith(agent, renamedOptions);\n","// Trimmed copy of apps/plugin/src/features/grots/sprite.ts: the part tables, screens(), paint() and spriteSvgDataUrl(). Keep in sync.\nimport { grotPalette, type Appearance, type GrotPalette } from './appearance';\n\n/**\n * A Grot is a 32×32 pixel sprite put together from parts, back to front.\n * Each part is rows of pixels from (x, y); `.` is empty and every other\n * character names a colour. A part gets a one-pixel dark outline unless it is\n * bare, so parts in front draw a clean edge over the ones behind.\n */\nexport interface Part {\n x: number;\n y: number;\n rows: readonly string[];\n bare?: boolean;\n}\n\nexport const SPRITE_SIZE = 32;\n\n/** Colours that are the same on every Grot: items, hats and alarms. */\nconst fixedColors: Record<string, string> = {\n w: '#FFFFFF',\n r: '#E5484D',\n R: '#B8333A',\n u: '#3D6FE0',\n U: '#2A4FA8',\n y: '#FFCF3D',\n p: '#FF7AA8',\n t: '#FF7AA8',\n a: '#9AA4B5',\n z: '#BFE6FF',\n x: '#FFB31F',\n e: '#3DBE6E',\n E: '#23824A',\n f: '#B8743A',\n F: '#7A4A22',\n i: '#2B2B36',\n m: '#7B4FE0',\n M: '#5634B0',\n q: '#F4E9C8',\n};\n\nfunction colorsOf(palette: GrotPalette): Record<string, string> {\n const p = grotPalette[palette];\n return {\n ...fixedColors,\n o: p.outline,\n k: p.outline,\n b: p.body,\n l: p.light,\n s: p.shade,\n c: p.crest,\n d: p.crestShade,\n v: p.visor,\n h: p.visorLight,\n n: p.screen,\n g: p.glyph,\n };\n}\n\n/** The classic Grot side on, facing right: a round body, a dorsal crest, a wraparound visor and amber arms. */\nexport const body: Part = {\n x: 6,\n y: 7,\n rows: [\n '.........bbbbbbbb',\n '.....bbbbbbbbbbbbbb',\n '....bbbbbbbbbbbbbbbb',\n '...bbbbbbbbbbbbbbbbbb',\n '..bbbbbbbbbbbbbbbbbbbb',\n '..bbbbbbbbbbbbbbbbbbbb',\n '.bbbbbbbbbbbbbbbbbbbbbb',\n '.bbbbbbbbbbbbbbbbbbbbbb',\n 'bbbbbbbbbbbbbbbbbbbbbbb',\n 'bbbbbbbbbbbbbbbbbbbbbbb',\n 'bbbbbbbbbbbbbbbbbbbbbbb',\n 'bbbbbbbbbbbbbbbbbbbbbbb',\n 'bbbbbbbbbbbbbbbbbbbbbbb',\n // The far arm peeks out in front, edged off from the body and clear of the presence dot's corner.\n 'bbbbbbbbbbbbbbbbbbbbkss',\n 'bbbbbbbbbbbbbbbbbbbksss',\n 'bbbbbbbbbbbbbbbbbbbkssss',\n 'bbbbbbbbbbbbbbbbbbb..ss',\n 'bbbbbbbbbbbbbbbbbbb',\n 'bbbbbbbbbbbbbbbbbbb',\n 'bbbbbbbbbbbbbbbbbbb',\n '.bbbbbbbbbbbbbbbbb',\n ],\n};\n\nexport const feet = {\n back: { x: 11, y: 28, rows: ['bbbbb', 'bbbb', '.bb'] },\n front: { x: 18, y: 28, rows: ['bbbbb', 'bbbb', '.bb'] },\n} satisfies Record<string, Part>;\n\n/** The near arm, which holds things and waves. */\nexport const arms = {\n rest: { x: 12, y: 21, rows: ['.s', 'ss', 'sss', '.ss'] },\n up: { x: 12, y: 17, rows: ['ss', 'sss', '.ss', '.ss'] },\n} satisfies Record<string, Part>;\n\nexport const crests: Record<Appearance['crest'], Part | undefined> = {\n spikes: {\n x: 3,\n y: 1,\n rows: [\n '..........cccc',\n '..........ccccc',\n '..........cccccc',\n '..........ccccccc',\n '...ccc....cccccccc',\n '...ccccc..cccccccc',\n '...ccccccccccccccc',\n '....cccccc',\n '....cccc',\n '...cccc',\n '.ccccc',\n 'ccccc',\n '.ccc',\n 'cccc',\n '.cc',\n 'ccc',\n '.cc',\n 'cc',\n '.c',\n ],\n },\n fin: {\n x: 9,\n y: 1,\n rows: [\n '.......ccc',\n '......cccccc',\n '.....cccccccc',\n '....ccccccccc',\n '...cccccccccc',\n '..ccccccccccc',\n '.cccccccccccc',\n 'cccccccc',\n 'ccccc',\n ],\n },\n mohawk: {\n x: 9,\n y: 3,\n rows: ['.....c...c', '..c..cc..cc..c', '..cc.ccc.ccc.cc', '.cccccccccccccc', 'ccccccccccccccc'],\n },\n antenna: { x: 17, y: 1, rows: ['ccc', 'ccc', '.c', '.c', '.c', '.c', '.c'] },\n flame: {\n x: 12,\n y: 1,\n rows: ['....y', '...yx...y', '..yxx..yx', '.yxrx.yxx', '.xrrxyxrx', 'xrrrxxrrx', 'xrrrrrrrrx', 'rrrrrrrrrr'],\n },\n sprout: { x: 17, y: 1, rows: ['eee.eee', '.eeEee', '...E', '...E', '...E', '...E'] },\n horns: { x: 14, y: 2, rows: ['c.....c', 'cc....cc', '.cc...cc', '.ccc..ccc', '..ccc.ccc'] },\n bald: undefined,\n};\n\n/** Visors: `n` is the screen the eyes and status glyphs show on. They wrap the front of the face. */\nexport const visors: Record<Appearance['visor'], Part> = {\n band: {\n x: 14,\n y: 13,\n rows: ['.vvvvvvvvvvvvvv', 'vvvnnnnnnnnnnnnv', 'vvvnnnnnnnnnnnnv', 'vvvnnnnnnnnnnnnv', '.vvvvvvvvvvvvvv'],\n },\n goggles: {\n x: 12,\n y: 13,\n rows: ['....vvvvv...vvvvv', 'vvvvnnnnnvvvnnnnnv', '...vnnnnnv.vnnnnnv', '...vnnnnnv.vnnnnnv', '....vvvvv...vvvvv'],\n },\n slim: { x: 14, y: 14, rows: ['.vvvvvvvvvvvvvv', 'vvvnnnnnnnnnnnnv', '.vvvvvvvvvvvvvv'] },\n shades: {\n x: 14,\n y: 13,\n rows: ['vvvvvvvvvvvvvvvv', 'vvnnnnnvvvnnnnnv', '.vnnnnnv.vnnnnnv', '..vvvvv...vvvvv'],\n },\n};\n\n/** Where each visor's two eyes sit: their centre columns and row. */\nexport const eyesAt: Record<Appearance['visor'], { x: [number, number]; y: number }> = {\n band: { x: [20, 25], y: 15 },\n goggles: { x: [18, 26], y: 15 },\n slim: { x: [20, 25], y: 15 },\n shades: { x: [18, 26], y: 14 },\n};\n\n/** Pixels of one eye around its centre. */\nconst eyeShapes: Record<Exclude<Appearance['screen'], 'wink'>, readonly [number, number][]> = {\n bars: [\n [-1, 0],\n [0, 0],\n [1, 0],\n ],\n dots: [\n [0, 0],\n [1, 0],\n [0, 1],\n [1, 1],\n ],\n tall: [\n [0, -1],\n [0, 0],\n [0, 1],\n ],\n big: [\n [-1, -1],\n [0, -1],\n [1, -1],\n [-1, 0],\n [0, 0],\n [1, 0],\n [-1, 1],\n [0, 1],\n [1, 1],\n ],\n love: [\n [-1, -1],\n [1, -1],\n [-1, 0],\n [0, 0],\n [1, 0],\n [0, 1],\n ],\n plus: [\n [0, -1],\n [-1, 0],\n [0, 0],\n [1, 0],\n [0, 1],\n ],\n dizzy: [\n [-1, -1],\n [1, -1],\n [0, 0],\n [-1, 1],\n [1, 1],\n ],\n};\n\n/** The mouths people pick, plus the open \"o\" an alarmed Grot makes. The classic one is a smirk. */\nexport const mouths: Record<Appearance['mouth'] | 'o', Part> = {\n smile: { x: 19, y: 19, bare: true, rows: ['kk', '.kkk'] },\n grin: { x: 19, y: 19, bare: true, rows: ['kkkkk', 'kwwwk', '.kkk'] },\n flat: { x: 20, y: 20, bare: true, rows: ['kkk'] },\n fang: { x: 19, y: 19, bare: true, rows: ['kk', '.kkkk', '...w'] },\n stache: { x: 18, y: 19, bare: true, rows: ['.kkkkk', 'kkk.kkk', 'k.....k'] },\n wavy: { x: 19, y: 20, bare: true, rows: ['k.k.k', '.k.k'] },\n o: { x: 20, y: 19, bare: true, rows: ['kk', 'kk'] },\n};\n\nexport const hats: Record<Appearance['hat'], Part | undefined> = {\n nohat: undefined,\n beanie: {\n x: 13,\n y: 2,\n rows: ['......rr', '....rrrr', '...rrrrr', '..rrrrrrr', '.rrrrrrrrr', 'Rrrrrrrrrrr', 'wwwwwwwwwww'],\n },\n cap: { x: 14, y: 5, rows: ['...uuuu', '..uuuuuuu', '.uuuuuuuuu', 'uuuuuuuUUUU'] },\n crown: { x: 16, y: 4, rows: ['y.y.y.y', 'yyyyyyy', 'yryyyry', 'yyyyyyy'] },\n party: { x: 17, y: 1, rows: ['....w', '...pp', '..ppy', '.pypp', 'ppppy', 'pyppp'] },\n // Left of the badges' column, so an alert or waiting Grot keeps both ear cups.\n headset: {\n x: 11,\n y: 3,\n rows: ['....aaaaaa', '..aa......aa', '.a..........a', 'aa..........a', 'aa.........aa', 'aa.........aa'],\n },\n wizard: {\n x: 13,\n y: 1,\n rows: ['.......mm', '......mmM', '.....mmmM', '....mmymM', '...mmmmmmM', '..mmmmymmmM', 'mmmmmmmmmmmm'],\n },\n cowboy: { x: 11, y: 4, rows: ['....ffff', '...ffffff', 'f..FFFFFF...f', 'fffffffffffff'] },\n chef: {\n x: 13,\n y: 1,\n rows: ['..www.www', '.wwwwwwwww', 'wwwwwwwwwww', 'wwwwwwwwwww', '.wwwwwwwww', '..wwwwwww', '..aaaaaaa'],\n },\n viking: {\n x: 12,\n y: 2,\n rows: ['q..........q', 'qq........qq', '.qq.aaaa.qq', '..qaaaaaaq', '..aaaaaaaa', '.ayaaaayaaa'],\n },\n tophat: { x: 15, y: 1, rows: ['..iiiiii', '..iiiiii', '..iiiiii', '..iiiiii', '..rrrrrr', '..iiiiii', 'iiiiiiiiii'] },\n halo: { x: 15, y: 1, rows: ['..yyyyyy', '.y......y', '..yyyyyy'] },\n flower: { x: 19, y: 1, rows: ['.ww', 'wyyw', 'wyyw', '.ww', '..e', '.ee'] },\n // Low like the cap, so the crest behind it stays in view.\n hardhat: { x: 14, y: 5, rows: ['....yy', '..xxyyx', '.xxxyyxxx', 'xxxxxxxxxxx'] },\n copter: { x: 14, y: 1, rows: ['rrrr.uuuu', '....a', '..yyyyy', '.uuuyrrr', 'uuuuyrrrr', 'uuuuyrrrrr'] },\n};\n\n/** Hats tall enough to cover most of a crest: the crest is not drawn under them. */\nexport const crestHidingHats: ReadonlySet<Appearance['hat']> = new Set([\n 'chef',\n 'tophat',\n 'copter',\n 'viking',\n 'wizard',\n 'beanie',\n 'cowboy',\n 'crown',\n 'party',\n]);\n\n/** What a Grot holds in its near hand, in front of its belly. */\nexport const heldItems: Record<Appearance['held'], Part | undefined> = {\n empty: undefined,\n coffee: { x: 11, y: 18, rows: ['..z.z', '...z.z', '..wwww', 'wwwrrw', 'w.wrrw', 'wwwwww', '..wwww'] },\n wrench: { x: 12, y: 17, rows: ['a.a', 'aaa', '.a', '.a', '.a', '.a'] },\n magnifier: { x: 8, y: 15, rows: ['.aaa', 'azzza', 'azzza', 'azzza', '.aaa', '....a', '....a'] },\n chart: { x: 8, y: 16, rows: ['wwwwww', 'w...gw', 'w.g.gw', 'wg.g.w', 'wwwwww', '....a', '....a'] },\n duck: { x: 11, y: 18, rows: ['...www', '..wwkxx', '...ww', 'w.wwwww', 'wwwwwww', '.wwwww'] },\n pager: { x: 13, y: 20, rows: ['....r', 'iiiii', 'ieeei', 'ieeei', 'iiiii'] },\n laptop: { x: 8, y: 18, rows: ['aaaaaaa', 'aiiiiea', 'aiieiia', 'aeiiiia', 'aaaaaaa', 'aaaaaaaa'] },\n // Bare, so the string stays one pixel thin: the balloon draws its own edge.\n balloon: {\n x: 5,\n y: 8,\n bare: true,\n rows: [\n '..kkk',\n '.krrrk',\n 'krwrrrk',\n 'krrrrrk',\n '.krrrk',\n '..kRk',\n '...k',\n '...k',\n '....k',\n '....k',\n '.....k',\n '......k',\n '.......k',\n ],\n },\n pizza: { x: 13, y: 19, rows: ['ffffff', '.yyryy', '.yyyy', '..yry', '..yy', '...y'] },\n flag: {\n x: 8,\n y: 10,\n rows: [\n 'xxxxxa',\n 'xxwxxa',\n '..xxxa',\n '.....a',\n '.....a',\n '.....a',\n '.....a',\n '.....a',\n '.....a',\n '.....a',\n '.....a',\n ],\n },\n donut: { x: 13, y: 20, rows: ['.pyp', 'pu.pp', 'pp.yp', '.fff'] },\n clip: { x: 12, y: 19, rows: ['..a', 'wwwww', 'wuuuw', 'wwwww', 'wuuww', 'wwwww'] },\n bell: { x: 12, y: 19, rows: ['..x', '.yyy', '.yyy', 'yyyyy', 'yyyyy', 'xxxxx', '..r'] },\n shield: { x: 12, y: 19, rows: ['uuuuu', 'uwuUU', 'uwwUU', 'uuUUU', '.uUU', '..U'] },\n bug: { x: 12, y: 19, rows: ['.i.i', '.eee', 'ieEei', 'ieEei', '.eee', 'i.E.i'] },\n key: { x: 10, y: 21, rows: ['.yy', 'y..yyyyy', '.yy.y.y'] },\n};\n\n/** Tails trail behind, at the bottom left. */\nexport const tails: Record<Appearance['tail'], Part | undefined> = {\n curl: { x: 1, y: 21, rows: ['.bb', 'bbbb', 'b..b', 'b..b', 'bb', 'bbb', '.bbbbb', '..bbb'] },\n spike: { x: 1, y: 23, rows: ['b', 'bbb', 'bbbbbb', '.bbbbb'] },\n bolt: { x: 1, y: 18, rows: ['..y', '.yy', 'yy', 'yyyy', '..yy', '.yy', 'yyyyy', '...yyy'] },\n heart: { x: 1, y: 20, rows: ['pp.p', 'pppp', '.ppp', '..pb', '...bbb'] },\n fluff: { x: 1, y: 20, rows: ['.bbb', 'bwbbb', 'bbbwbb', 'bwbbbb', 'bbbwb', '.bbb'] },\n notail: undefined,\n};\n\nfunction pixelsPart(pixels: [number, number][], color: string): Part {\n const keys = new Set(pixels.map(([x, y]) => `${x},${y}`));\n const xs = pixels.map(([x]) => x);\n const ys = pixels.map(([, y]) => y);\n const [x, y] = [Math.min(...xs), Math.min(...ys)];\n const rows = Array.from({ length: Math.max(...ys) - y + 1 }, (_, j) =>\n Array.from({ length: Math.max(...xs) - x + 1 }, (_, i) => (keys.has(`${x + i},${y + j}`) ? color : '.')).join('')\n );\n return { x, y, bare: true, rows };\n}\n\n/** One part per key, so generated parts stay the same object and their paint is cached. */\nfunction memo<K, R>(make: (key: K) => R): (key: K) => R {\n const made = new Map<K, R>();\n return (key) => {\n let result = made.get(key);\n if (result === undefined) {\n result = make(key);\n made.set(key, result);\n }\n return result;\n };\n}\n\n/**\n * What a visor's screen can show, built once per visor: the screen itself to\n * clip to, the eyes in each style, and the glyphs that replace them by mood.\n */\nexport const screens = memo((visor: Appearance['visor']) => {\n const at = eyesAt[visor];\n const screen: [number, number][] = [];\n visors[visor].rows.forEach((row, j) =>\n [...row].forEach((ch, i) => ch === 'n' && screen.push([visors[visor].x + i, visors[visor].y + j]))\n );\n const shown = new Set(screen.map(([x, y]) => `${x},${y}`));\n /** `dy` when that row of the screen shows at column `x`, else flat, so no pixel is clipped away. */\n const onScreen = (x: number, dy: number) => (shown.has(`${x},${at.y + dy}`) ? dy : 0);\n const caret: [number, number][] = [\n [-1, 0],\n [0, -1],\n [1, 0],\n ];\n // The wink's caret lifts only where the screen has a row above, else it flattens to a bar, which still reads as a closed eye.\n const winkCaret = caret.map(([dx, dy]): [number, number] => [dx, dy && onScreen(at.x[0] + dx, dy)]);\n const perEye = (shape: readonly [number, number][]) =>\n pixelsPart(\n at.x.flatMap((cx) => shape.map(([dx, dy]): [number, number] => [cx + dx, at.y + dy])),\n 'g'\n );\n return {\n screen: pixelsPart(screen, 'n'),\n eyes: {\n bars: perEye(eyeShapes.bars),\n dots: perEye(eyeShapes.dots),\n tall: perEye(eyeShapes.tall),\n big: perEye(eyeShapes.big),\n love: perEye(eyeShapes.love),\n plus: perEye(eyeShapes.plus),\n dizzy: perEye(eyeShapes.dizzy),\n // The near eye winks as a caret while the far one stays open.\n wink: pixelsPart(\n [\n ...winkCaret.map(([dx, dy]): [number, number] => [at.x[0] + dx, at.y + dy]),\n ...eyeShapes.dots.map(([dx, dy]): [number, number] => [at.x[1] + dx, at.y + dy]),\n ],\n 'g'\n ),\n } satisfies Record<Appearance['screen'], Part>,\n };\n});\n\nexport interface Paint {\n fill: string;\n d: string;\n}\n\nfunction trace(pixels: Iterable<string>): string {\n // One rectangle per horizontal run of pixels on a row.\n const byRow = new Map<number, number[]>();\n for (const key of pixels) {\n const [x, y] = key.split(',').map(Number);\n byRow.set(y, [...(byRow.get(y) ?? []), x]);\n }\n let d = '';\n for (const [y, xs] of byRow) {\n xs.sort((a, b) => a - b);\n for (let i = 0; i < xs.length; ) {\n let j = i;\n while (j + 1 < xs.length && xs[j + 1] === xs[j] + 1) {\n j++;\n }\n const run = j - i + 1;\n d += `M${xs[i]} ${y}h${run}v1h-${run}z`;\n i = j + 1;\n }\n }\n return d;\n}\n\nconst painted = new WeakMap<Part, Map<GrotPalette, Paint[]>>();\n\n/** A part as one path per colour, on its outline unless it is bare. */\nexport function paint(part: Part | undefined, palette: GrotPalette): Paint[] {\n if (!part) {\n return [];\n }\n const cached = painted.get(part)?.get(palette);\n if (cached) {\n return cached;\n }\n const colors = colorsOf(palette);\n const pixels = new Map<string, string>();\n part.rows.forEach((row, j) =>\n [...row].forEach((ch, i) => ch !== '.' && pixels.set(`${part.x + i},${part.y + j}`, colors[ch] ?? colors.o))\n );\n const byColor = new Map<string, Set<string>>();\n const put = (fill: string, key: string) => byColor.set(fill, (byColor.get(fill) ?? new Set()).add(key));\n if (!part.bare) {\n for (const key of pixels.keys()) {\n const [x, y] = key.split(',').map(Number);\n for (const near of [`${x + 1},${y}`, `${x - 1},${y}`, `${x},${y + 1}`, `${x},${y - 1}`]) {\n if (!pixels.has(near)) {\n put(colors.o, near);\n }\n }\n }\n }\n for (const [key, fill] of pixels) {\n put(fill, key);\n }\n const result = Array.from(byColor, ([fill, keys]) => ({ fill, d: trace(keys) }));\n painted.set(part, (painted.get(part) ?? new Map()).set(palette, result));\n return result;\n}\n\nconst svgDataUrls = new Map<string, string>();\n\n/** An idle Grot sprite as a transparent SVG data URL for surfaces that take an image src (e.g. `@` menu items). */\nexport function spriteSvgDataUrl(look: Appearance): string {\n const key = `${look.palette}|${look.crest}|${look.visor}|${look.screen}|${look.mouth}|${look.tail}|${look.hat}|${look.held}`;\n const cached = svgDataUrls.get(key);\n if (cached) {\n return cached;\n }\n const paths = (...parts: Array<Part | undefined>) =>\n parts\n .flatMap((part) => paint(part, look.palette))\n .map(({ fill, d }) => `<path fill=\"${fill}\" d=\"${d}\"/>`)\n .join('');\n const screen = screens(look.visor);\n const clip = paint(screen.screen, look.palette)\n .map(({ d }) => `<path d=\"${d}\"/>`)\n .join('');\n const svg =\n `<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 ${SPRITE_SIZE} ${SPRITE_SIZE}\" shape-rendering=\"crispEdges\">` +\n `<defs><clipPath id=\"s\">${clip}</clipPath></defs>` +\n paths(\n feet.back,\n feet.front,\n tails[look.tail],\n crestHidingHats.has(look.hat) ? undefined : crests[look.crest],\n body,\n mouths[look.mouth],\n visors[look.visor]\n ) +\n `<g clip-path=\"url(#s)\">${paths(screen.eyes[look.screen])}</g>` +\n paths(hats[look.hat], arms.rest, heldItems[look.held]) +\n '</svg>';\n const url = `data:image/svg+xml;utf8,${encodeURIComponent(svg)}`;\n svgDataUrls.set(key, url);\n return url;\n}\n","import { css } from '@emotion/css';\nimport { useStyles2 } from '@grafana/ui';\nimport { appearanceOf, classicLook, grotOptions, partOrder, type Appearance } from '../../grots/avatar/appearance';\nimport { spriteSvgDataUrl } from '../../grots/avatar/sprite';\n\n/** @experimental This API is under active development and may change in future releases. */\nexport type GrotLook = Partial<Appearance>;\n\n/** @experimental This API is under active development and may change in future releases. */\nexport interface GrotAvatarProps {\n /**\n * The Grot to draw. Its `avatar` string is its look, such as `mint.fin.band.bars.smile.cap.empty.curl`.\n * A Grot without one gets a stable look derived from its `id`.\n */\n grot?: { id: string; name?: string; avatar?: string };\n /**\n * A look to draw instead of `grot`: the dotted avatar string, or some of the parts. A part left out, or one with\n * an unknown option, is the classic Grot's.\n */\n look?: string | GrotLook;\n /** Width and height in pixels. Defaults to 32. */\n size?: number;\n /** Accessible label. Defaults to the Grot's name, else \"Grot\". */\n title?: string;\n}\n\nfunction lookOf({ grot, look }: Pick<GrotAvatarProps, 'grot' | 'look'>): Appearance {\n if (typeof look === 'object') {\n const result: Record<string, string> = { ...classicLook };\n for (const part of partOrder) {\n const option = (grotOptions[part] as readonly string[]).find((o) => o === look[part]);\n if (option) {\n result[part] = option;\n }\n }\n return result as Appearance;\n }\n return appearanceOf({ id: grot?.id ?? '', avatar: look ?? grot?.avatar });\n}\n\n/**\n * A Grot at rest, drawn from its look. It is an image with an accessible name.\n *\n * @experimental This API is under active development and may change in future releases.\n */\nexport function GrotAvatar(props: GrotAvatarProps) {\n const { size = 32, title } = props;\n const styles = useStyles2(getStyles);\n const label = title ?? props.grot?.name ?? 'Grot';\n const src = spriteSvgDataUrl(lookOf(props));\n return <img className={styles.image} src={src} width={size} height={size} alt={label} />;\n}\n\nconst getStyles = () => ({\n image: css({ display: 'block', flexShrink: 0, imageRendering: 'pixelated' }),\n});\n","import type { MouseEvent } from 'react';\nimport { config, locationService } from '@grafana/runtime';\nimport { LinkButton } from '@grafana/ui';\nimport { ASSISTANT_PLUGIN_ID } from '../../plugin';\n\n/** @experimental This API is under active development and may change in future releases. */\nexport interface OpenGrotButtonProps {\n /** ID of the Grot to open. */\n grotId: string;\n /** Number of one of the Grot's topics to open on (`GrotTopic.number`). Without it the Grot opens on its topics. */\n topic?: number;\n /** Button text. Defaults to \"Open Grot\". */\n label?: string;\n variant?: 'primary' | 'secondary';\n size?: 'sm' | 'md' | 'lg';\n}\n\n/**\n * The link the Grots page opens a Grot or topic from: `?assistantGrot=<id>&assistantTopic=<number>` on the Grots page\n * (`WORKSPACE_GROT_PARAM`, `WORKSPACE_TOPIC_PARAM` and `GROTS_BASE_URL` in the plugin's `constants.ts`).\n */\nexport function grotHref(grotId: string, topic?: number): string {\n const params = new URLSearchParams({ assistantGrot: grotId });\n if (topic !== undefined) {\n params.set('assistantTopic', String(topic));\n }\n return `${config.appSubUrl ?? ''}/a/${ASSISTANT_PLUGIN_ID}/lab/grots?${params}`;\n}\n\n/**\n * Opens a Grot, and optionally one of its topics, on the Grafana Assistant's Grots page.\n *\n * @experimental This API is under active development and may change in future releases.\n */\nexport function OpenGrotButton({\n grotId,\n topic,\n label = 'Open Grot',\n variant = 'secondary',\n size = 'md',\n}: OpenGrotButtonProps) {\n const href = grotHref(grotId, topic);\n // LinkButton types onClick for both its anchor and button forms, so take the shared HTMLElement event.\n const onClick = (event: MouseEvent<HTMLElement>) => {\n // Keep new-tab and modified clicks native; navigate in-app otherwise so Grafana does not reload.\n if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) {\n return;\n }\n event.preventDefault();\n locationService.push(href.slice((config.appSubUrl ?? '').length));\n };\n return (\n <LinkButton href={href} onClick={onClick} variant={variant} size={size} icon=\"arrow-right\">\n {label}\n </LinkButton>\n );\n}\n","import { config, usePluginComponent } from '@grafana/runtime';\nimport { Alert, LinkButton, LoadingPlaceholder } from '@grafana/ui';\nimport { ASSISTANT_PLUGIN_ID } from '../../plugin';\n\n/** The Assistant app's exposed component this view renders. Add it to your plugin.json's `dependencies.extensions.exposedComponents`. */\nexport const GROT_TOPIC_COMPONENT_ID = `${ASSISTANT_PLUGIN_ID}/grot-topic/v1`;\n\n/** @experimental This API is under active development and may change in future releases. */\nexport interface GrotTopicViewProps {\n grotId: string;\n /** The topic to show, such as a `GrotTopic`. Its `number` picks it among the signed-in person's topics with the Grot. */\n topic: { number: number };\n}\n\ninterface ExposedProps {\n grotId: string;\n topic: number;\n}\n\n/**\n * One of the signed-in person's topics with a Grot, read only, drawn by the Grafana Assistant app: the Grots page's own\n * conversation, so it changes when that page does. It fills its container's height and scrolls inside it, so give the\n * container a height. Needs read access to the Grot and its direct chats, and an Assistant app that exposes\n * `grafana-assistant-app/grot-topic/v1`.\n * @experimental This API is under active development and may change in future releases.\n */\nexport function GrotTopicView({ grotId, topic }: GrotTopicViewProps) {\n const { component: Topic, isLoading } = usePluginComponent<ExposedProps>(GROT_TOPIC_COMPONENT_ID);\n if (isLoading) {\n return <LoadingPlaceholder text=\"Loading messages\" />;\n }\n if (!Topic) {\n return (\n <Alert severity=\"info\" title=\"Grot topics aren't available\">\n Update Grafana Assistant to show this topic here.{' '}\n <LinkButton href={`${config.appSubUrl ?? ''}/plugins/${ASSISTANT_PLUGIN_ID}`} variant=\"secondary\" size=\"sm\">\n Open the Assistant plugin page\n </LinkButton>\n </Alert>\n );\n }\n return <Topic grotId={grotId} topic={topic.number} />;\n}\n","import { extractErrorMessage } from '../utils/errorHandling';\nimport type { InvestigationLensError, InvestigationLensErrorCode } from './types';\n\n/**\n * Request passed to the lens implementation registered by the Grafana\n * Assistant plugin.\n */\nexport interface InvestigationLensRequest {\n investigationId: string;\n /** JSON Schema describing the shape of the desired structured view. */\n schema: unknown;\n /** Attribution for the generation, e.g. `'grafana-irm/incident-detail'`. */\n origin: string;\n /** When true, bypass the cached result and regenerate. */\n refresh?: boolean;\n}\n\n/**\n * The lens implementation provided by the Grafana Assistant plugin. Resolves\n * with data conforming to the request's schema, or rejects with an error\n * carrying an {@link InvestigationLensErrorCode} `code` property.\n */\nexport type InvestigationLensImplementation = (request: InvestigationLensRequest) => Promise<unknown>;\nexport type InvestigationLensInitializer = () => Promise<void>;\n\nconst LENS_ERROR_CODES: readonly InvestigationLensErrorCode[] = [\n 'unavailable',\n 'no_report',\n 'permission_denied',\n 'validation_failed',\n 'llm_error',\n];\n\nfunction isLensErrorCode(value: unknown): value is InvestigationLensErrorCode {\n return typeof value === 'string' && (LENS_ERROR_CODES as readonly string[]).includes(value);\n}\n\n/**\n * Typed error the lens implementation throws to signal a specific failure\n * mode. Consumers should not need this class — the hook converts failures to\n * plain {@link InvestigationLensError} values. Conversion is structural (it\n * reads the `code` property), so it works even when the host plugin and the\n * assistant plugin bundle different copies of this package.\n */\nexport class InvestigationLensRequestError extends Error {\n constructor(\n public readonly code: InvestigationLensErrorCode,\n message: string\n ) {\n super(message);\n this.name = 'InvestigationLensRequestError';\n }\n}\n\n/** Converts any thrown value into a plain, typed lens error. */\nexport function toInvestigationLensError(err: unknown): InvestigationLensError {\n if (err && typeof err === 'object' && 'code' in err && isLensErrorCode(err.code)) {\n return { code: err.code, message: extractErrorMessage(err) };\n }\n return { code: 'llm_error', message: extractErrorMessage(err) };\n}\n\n// Global registry keys for cross-plugin sharing: all plugins (and all copies\n// of this package) must observe the same implementation, regardless of which\n// bundle loads first.\nconst GLOBAL_IMPLEMENTATION_KEY = '__grafanaAssistantLensImplementation__';\nconst GLOBAL_INITIALIZER_KEY = '__grafanaAssistantLensInitializer__';\nconst GLOBAL_INITIALIZATION_PROMISE_KEY = '__grafanaAssistantLensInitPromise__';\n\nexport function setInvestigationLensImplementation(fn: InvestigationLensImplementation): void {\n const existing = window[GLOBAL_IMPLEMENTATION_KEY] as InvestigationLensImplementation | undefined;\n if (existing && existing !== fn) {\n console.warn('InvestigationLens implementation already set; ignoring subsequent call');\n return;\n }\n if (!existing) {\n window[GLOBAL_IMPLEMENTATION_KEY] = fn;\n }\n}\n\n/**\n * Register a lazy initializer that is called on first use. The Grafana\n * Assistant plugin registers this at bootstrap so the heavy implementation\n * loads only when a consumer actually requests a lens view.\n */\nexport function setInvestigationLensInitializer(fn: InvestigationLensInitializer): void {\n const existing = window[GLOBAL_INITIALIZER_KEY] as InvestigationLensInitializer | undefined;\n if (existing && existing !== fn) {\n console.warn('InvestigationLens initializer already set; ignoring subsequent call');\n return;\n }\n if (!existing) {\n window[GLOBAL_INITIALIZER_KEY] = fn;\n }\n}\n\n/**\n * Ensure the lens implementation is initialized, invoking the registered\n * initializer on first use. Throws an `unavailable` lens error when no\n * initializer is registered (assistant plugin missing or too old).\n */\nexport async function ensureInvestigationLensInitialized(): Promise<void> {\n const implementation = window[GLOBAL_IMPLEMENTATION_KEY] as InvestigationLensImplementation | undefined;\n if (implementation) {\n return;\n }\n\n const initializer = window[GLOBAL_INITIALIZER_KEY] as InvestigationLensInitializer | undefined;\n if (!initializer) {\n throw new InvestigationLensRequestError(\n 'unavailable',\n 'Investigation lens is not available. Make sure the Grafana Assistant plugin is installed and up to date.'\n );\n }\n\n // If initialization is in progress, wait for it\n const existingPromise = window[GLOBAL_INITIALIZATION_PROMISE_KEY] as Promise<void> | null | undefined;\n if (existingPromise !== null && existingPromise !== undefined) {\n return existingPromise;\n }\n\n const initPromise = (async () => {\n try {\n await initializer();\n } catch (err) {\n // Reset on error so retry is possible\n window[GLOBAL_INITIALIZATION_PROMISE_KEY] = null;\n throw err;\n }\n })();\n\n window[GLOBAL_INITIALIZATION_PROMISE_KEY] = initPromise;\n return initPromise;\n}\n\nexport function getInvestigationLensImplementation(): InvestigationLensImplementation {\n const implementation = window[GLOBAL_IMPLEMENTATION_KEY] as InvestigationLensImplementation | undefined;\n if (!implementation) {\n throw new InvestigationLensRequestError(\n 'unavailable',\n 'Investigation lens is not available. Make sure the Grafana Assistant plugin is installed and up to date.'\n );\n }\n return implementation;\n}\n","// biome.json disables noMisusedPromises here: Biome 2.5.14 stack-overflows resolving FromSchema with dependencies installed.\n// Retest after upgrading Biome; see docs/biome-ratchet.md#biome-2514-exception.\n\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport type { FromSchema, JSONSchema } from 'json-schema-to-ts';\n\nimport {\n ensureInvestigationLensInitialized,\n getInvestigationLensImplementation,\n toInvestigationLensError,\n} from './investigationLens';\nimport type {\n InvestigationLensState,\n UseInvestigationThroughLensOptions,\n UseInvestigationThroughLensResult,\n} from './types';\n\n/**\n * Derives a structured, LLM-generated view of an investigation's report,\n * shaped by a caller-provided JSON Schema. Declarative: generation runs on\n * mount and whenever the schema or investigation changes; results are cached\n * by the Grafana Assistant plugin per (investigation, schema, report\n * content), so remounts don't regenerate for an unchanged report.\n *\n * Field `description`s are per-field instructions to the model — that is the\n * steering mechanism. Deterministic facts (ids, titles, statuses, timestamps,\n * links) are provided to the model verbatim and copied through rather than\n * generated, so reserve schema fields for genuine synthesis from the report.\n *\n * Declare the schema with `as const` to get a fully typed `data` inferred\n * from the schema (via `json-schema-to-ts`):\n *\n * @example\n * ```typescript\n * const schema = {\n * type: 'object',\n * properties: {\n * headline: {\n * type: 'string',\n * description: 'One sentence describing the incident for an executive audience, max 80 characters.',\n * },\n * followUps: {\n * type: 'array',\n * description: 'Concrete follow-up actions to prevent recurrence.',\n * items: {\n * type: 'object',\n * properties: {\n * action: { type: 'string' },\n * urgency: { type: 'string', enum: ['now', 'this-week', 'backlog'] },\n * },\n * required: ['action', 'urgency'],\n * additionalProperties: false,\n * },\n * },\n * },\n * required: ['headline', 'followUps'],\n * additionalProperties: false,\n * } as const;\n *\n * function IncidentReview({ investigationId }: { investigationId: string }) {\n * const lens = useInvestigationThroughLens(schema, investigationId, {\n * origin: 'grafana-irm/incident-review',\n * });\n *\n * if (lens.status === 'loading') return <Spinner />;\n * if (lens.status === 'error') return <span>{lens.error.message}</span>;\n * // lens.data.followUps[0].urgency is 'now' | 'this-week' | 'backlog'\n * return <h3>{lens.data.headline}</h3>;\n * }\n * ```\n *\n * Requires the Grafana Assistant plugin; when it is missing or outdated the\n * hook resolves to an `error` state with code `unavailable` — it never throws\n * into the host's render.\n *\n * Note on `enabled` gating: re-enabling serves cached results by default. If\n * the report may have changed while the hook was disabled — e.g. `enabled`\n * gates on the report streaming — set `refreshOnEnable: true` so the fetch\n * triggered by the false → true transition bypasses the caches once.\n */\nexport function useInvestigationThroughLens<S extends JSONSchema, T = FromSchema<S>>(\n schema: S,\n investigationId: string,\n options: UseInvestigationThroughLensOptions\n): UseInvestigationThroughLensResult<T> {\n const { origin, enabled = true, refreshOnEnable = false } = options;\n const [state, setState] = useState<InvestigationLensState<T>>({ status: 'loading' });\n\n // Key generation on the schema's content, not its identity: consumers\n // typically declare the schema inline, so the object is recreated every\n // render even though it never changes.\n const schemaJson = useMemo(() => JSON.stringify(schema), [schema]);\n\n // refresh() bumps the generation to re-run generation with a cache bypass.\n // The bypass is one-shot: the ref records which generation already consumed\n // it, so a later run triggered by a schema/investigation change (same\n // generation, different deps) does not inherit `refresh: true`.\n const [generation, setGeneration] = useState({ id: 0, bypassCache: false });\n const consumedGenerationRef = useRef(0);\n\n // For refreshOnEnable: tracks whether the previous effect run was enabled,\n // so the run triggered by a false → true transition bypasses caches exactly\n // once. Initialized to the mount-time value so a first mount with\n // `enabled: true` takes the normal cached path.\n const wasEnabledRef = useRef(enabled);\n\n const refresh = useCallback(() => {\n setGeneration((g) => ({ id: g.id + 1, bypassCache: true }));\n }, []);\n\n useEffect(() => {\n const wasEnabled = wasEnabledRef.current;\n wasEnabledRef.current = enabled;\n\n if (!enabled) {\n setState({ status: 'loading' });\n return;\n }\n\n let cancelled = false;\n const bypassFromRefresh = generation.bypassCache && consumedGenerationRef.current !== generation.id;\n consumedGenerationRef.current = generation.id;\n const bypassCache = bypassFromRefresh || (refreshOnEnable && !wasEnabled);\n setState({ status: 'loading' });\n\n void (async () => {\n try {\n await ensureInvestigationLensInitialized();\n const implementation = getInvestigationLensImplementation();\n const data = await implementation({\n investigationId,\n schema: JSON.parse(schemaJson),\n origin,\n refresh: bypassCache,\n });\n if (!cancelled) {\n setState({ status: 'success', data: data as T });\n }\n } catch (err) {\n if (!cancelled) {\n setState({ status: 'error', error: toInvestigationLensError(err) });\n }\n }\n })();\n\n return () => {\n cancelled = true;\n };\n }, [schemaJson, investigationId, origin, enabled, refreshOnEnable, generation]);\n\n return { ...state, refresh };\n}\n","import { globalConfig } from \"./core.js\";\n// functions\nexport function assertEqual(val) {\n return val;\n}\nexport function assertNotEqual(val) {\n return val;\n}\nexport function toZod() {\n return (schema) => schema;\n}\nexport function assertIs(_arg) { }\nexport function assertNever(_x) {\n throw new Error(\"Unexpected value in exhaustive check\");\n}\nexport function assert(_) { }\nexport function getEnumValues(entries) {\n const numericValues = Object.values(entries).filter((v) => typeof v === \"number\");\n const values = Object.entries(entries)\n .filter(([k, _]) => numericValues.indexOf(+k) === -1)\n .map(([_, v]) => v);\n return values;\n}\nexport function joinValues(array, separator = \"|\") {\n return array.map((val) => stringifyPrimitive(val)).join(separator);\n}\nexport function jsonStringifyReplacer(_, value) {\n if (typeof value === \"bigint\")\n return value.toString();\n return value;\n}\n// the accessor lives on a shared prototype: an own accessor makes every box a dictionary-mode object (~360 B and a slow load per read against ~100 B and an inlined getter here)\nclass Cached {\n constructor(getter) {\n this._getter = getter;\n this._value = undefined;\n }\n get value() {\n const getter = this._getter;\n if (getter !== undefined) {\n this._value = getter();\n this._getter = undefined;\n }\n return this._value;\n }\n}\nexport function cached(getter) {\n return new Cached(getter);\n}\nexport function nullish(input) {\n return input === null || input === undefined;\n}\nexport function cleanRegex(source) {\n const start = source.startsWith(\"^\") ? 1 : 0;\n const end = source.endsWith(\"$\") ? source.length - 1 : source.length;\n return source.slice(start, end);\n}\nexport function floatSafeRemainder(val, step) {\n const ratio = val / step;\n const roundedRatio = Math.round(ratio);\n // `val` and `step` each round to a double before the division rounds again, so a true decimal multiple's quotient can sit up to 1.5 of these scaled epsilons from the integer. A 1x tolerance therefore rejected 2.03 as a multiple of 0.07; 4x covers the worst case with margin.\n const tolerance = 4 * Number.EPSILON * Math.max(Math.abs(ratio), 1);\n if (Math.abs(ratio - roundedRatio) < tolerance)\n return 0;\n return ratio - roundedRatio;\n}\nconst EVALUATING = /* @__PURE__*/ Symbol(\"evaluating\");\nexport function defineLazy(object, key, getter) {\n let value = undefined;\n Object.defineProperty(object, key, {\n get() {\n if (value === EVALUATING) {\n // Circular reference detected, return undefined to break the cycle\n return undefined;\n }\n if (value === undefined) {\n value = EVALUATING;\n value = getter();\n }\n return value;\n },\n set(v) {\n Object.defineProperty(object, key, {\n value: v,\n // configurable: true,\n });\n // object[key] = v;\n },\n configurable: true,\n });\n}\nexport function objectClone(obj) {\n return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj));\n}\nexport function assignProp(target, prop, value) {\n Object.defineProperty(target, prop, {\n value,\n writable: true,\n enumerable: true,\n configurable: true,\n });\n}\n/**\n * Whichever object a def's `shape` currently answers from: the one the caller passed until the first read, the frozen copy after it.\n *\n * Its keys and descriptors read without invoking anything, which is what lets a discriminated union check its discriminator, and the cycle walk read a shape, without resolving a getter that references the schema being constructed. A def that answers `shape` from an accessor of its own has none.\n */\nexport function rawShape(def) {\n const desc = Object.getOwnPropertyDescriptor(def, \"shape\");\n return desc?.get ? desc.get.raw : desc?.value;\n}\n// where a builder reads its source's keys and descriptors, resolving only a shape a def answers for itself. A shape resolves by object spread, so only its enumerable keys are ever part of it.\nfunction sourceShape(schema) {\n return rawShape(schema._zod.def) ?? schema._zod.def.shape;\n}\n// a key whose value is not settled yet, self-caching so every read after the first gets the same one\nfunction deferProp(target, key, getter) {\n Object.defineProperty(target, key, {\n get() {\n const value = getter();\n assignProp(this, key, value);\n return value;\n },\n enumerable: true,\n configurable: true,\n });\n}\n// Writes a settled key. A plain assignment is much cheaper than `defineProperty` and produces the same descriptor, but it runs whatever setter already answers to the key — an accessor this shape deferred, or an inherited one, which `__proto__` has on every object and prototype pollution can add for any name.\nfunction putProp(target, key, value) {\n if (key in target)\n assignProp(target, key, value);\n else\n target[key] = value;\n}\n/**\n * Copies `keys` of `source`'s shape onto `target`, each value passed through `wrap`.\n *\n * A key the source has resolved is copied through now, so the derived shape states it outright and nothing has to resolve it to learn what it holds. A key the source still defers stays deferred, and reads back through the source's own `shape`, so it resolves once and both shapes get that one schema.\n */\nfunction mirrorShape(target, source, keys, wrap) {\n const raw = sourceShape(source);\n for (const key of keys) {\n const desc = Object.getOwnPropertyDescriptor(raw, key);\n if (!desc.enumerable)\n continue;\n if (desc.get) {\n deferProp(target, key, () => {\n const value = source._zod.def.shape[key];\n return wrap ? wrap(value, key) : value;\n });\n }\n else\n putProp(target, key, wrap ? wrap(desc.value, key) : desc.value);\n }\n}\n// same, for a plain shape a caller passed rather than a schema's\nfunction mirrorProps(target, source) {\n for (const key of Reflect.ownKeys(source)) {\n const desc = Object.getOwnPropertyDescriptor(source, key);\n if (!desc.enumerable)\n continue;\n if (desc.get)\n deferProp(target, key, () => source[key]);\n else\n putProp(target, key, desc.value);\n }\n}\nexport function mergeDefs(...defs) {\n const mergedDescriptors = {};\n for (const def of defs) {\n const descriptors = Object.getOwnPropertyDescriptors(def);\n Object.assign(mergedDescriptors, descriptors);\n }\n return Object.defineProperties({}, mergedDescriptors);\n}\nexport function cloneDef(schema) {\n return mergeDefs(schema._zod.def);\n}\nexport function getElementAtPath(obj, path) {\n if (!path)\n return obj;\n return path.reduce((acc, key) => acc?.[key], obj);\n}\nexport function promiseAllObject(promisesObj) {\n const keys = Object.keys(promisesObj);\n const promises = keys.map((key) => promisesObj[key]);\n return Promise.all(promises).then((results) => {\n const resolvedObj = {};\n for (let i = 0; i < keys.length; i++) {\n resolvedObj[keys[i]] = results[i];\n }\n return resolvedObj;\n });\n}\nexport function randomString(length = 10) {\n const chars = \"abcdefghijklmnopqrstuvwxyz\";\n let str = \"\";\n for (let i = 0; i < length; i++) {\n str += chars[Math.floor(Math.random() * chars.length)];\n }\n return str;\n}\nexport function esc(str) {\n return JSON.stringify(str);\n}\nexport function slugify(input) {\n return input\n .toLowerCase()\n .trim()\n .replace(/[^\\w\\s-]/g, \"\")\n .replace(/[\\s_-]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n}\nexport const captureStackTrace = (\"captureStackTrace\" in Error ? Error.captureStackTrace : (..._args) => { });\nexport function isObject(data) {\n return typeof data === \"object\" && data !== null && !Array.isArray(data);\n}\nexport const allowsEval = /* @__PURE__*/ cached(() => {\n // Skip the probe under `jitless`: strict CSPs report the caught `new Function` as a `securitypolicyviolation` even though the throw is swallowed.\n if (globalConfig.jitless) {\n return false;\n }\n // @ts-ignore\n if (typeof navigator !== \"undefined\" && navigator?.userAgent?.includes(\"Cloudflare\")) {\n return false;\n }\n try {\n const F = Function;\n new F(\"\");\n return true;\n }\n catch (_) {\n return false;\n }\n});\nexport function isPlainObject(o) {\n if (isObject(o) === false)\n return false;\n // modified constructor\n const ctor = o.constructor;\n if (ctor === undefined)\n return true;\n if (typeof ctor !== \"function\")\n return true;\n // modified prototype\n const prot = ctor.prototype;\n if (isObject(prot) === false)\n return false;\n // ctor doesn't have static `isPrototypeOf`\n if (Object.prototype.hasOwnProperty.call(prot, \"isPrototypeOf\") === false) {\n return false;\n }\n return true;\n}\nexport function shallowClone(o) {\n if (isPlainObject(o))\n return { ...o };\n if (Array.isArray(o))\n return [...o];\n if (o instanceof Map)\n return new Map(o);\n if (o instanceof Set)\n return new Set(o);\n return o;\n}\nexport function numKeys(data) {\n let keyCount = 0;\n for (const key in data) {\n if (Object.prototype.hasOwnProperty.call(data, key)) {\n keyCount++;\n }\n }\n return keyCount;\n}\nexport const getParsedType = (data) => {\n const t = typeof data;\n switch (t) {\n case \"undefined\":\n return \"undefined\";\n case \"string\":\n return \"string\";\n case \"number\":\n return Number.isNaN(data) ? \"nan\" : \"number\";\n case \"boolean\":\n return \"boolean\";\n case \"function\":\n return \"function\";\n case \"bigint\":\n return \"bigint\";\n case \"symbol\":\n return \"symbol\";\n case \"object\":\n if (Array.isArray(data)) {\n return \"array\";\n }\n if (data === null) {\n return \"null\";\n }\n if (data.then && typeof data.then === \"function\" && data.catch && typeof data.catch === \"function\") {\n return \"promise\";\n }\n if (typeof Map !== \"undefined\" && data instanceof Map) {\n return \"map\";\n }\n if (typeof Set !== \"undefined\" && data instanceof Set) {\n return \"set\";\n }\n if (typeof Date !== \"undefined\" && data instanceof Date) {\n return \"date\";\n }\n // @ts-ignore\n if (typeof File !== \"undefined\" && data instanceof File) {\n return \"file\";\n }\n return \"object\";\n default:\n throw new Error(`Unknown data type: ${t}`);\n }\n};\nexport const propertyKeyTypes = /* @__PURE__*/ new Set([\"string\", \"number\", \"symbol\"]);\nexport const primitiveTypes = /* @__PURE__*/ new Set([\n \"string\",\n \"number\",\n \"bigint\",\n \"boolean\",\n \"symbol\",\n \"undefined\",\n]);\nexport function escapeRegex(str) {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n// zod-specific utils\nexport function clone(inst, def, params) {\n const cl = new inst._zod.constr(def ?? inst._zod.def);\n if (!def || params?.parent)\n cl._zod.parent = inst;\n return cl;\n}\nexport function normalizeParams(_params) {\n const params = _params;\n if (!params)\n return {};\n if (typeof params === \"string\")\n return { error: () => params };\n if (params?.message !== undefined) {\n if (params?.error !== undefined)\n throw new Error(\"Cannot specify both `message` and `error` params\");\n params.error = params.message;\n }\n delete params.message;\n if (typeof params.error === \"string\")\n return { ...params, error: () => params.error };\n return params;\n}\nexport function createTransparentProxy(getter) {\n let target;\n return new Proxy({}, {\n get(_, prop, receiver) {\n target ?? (target = getter());\n return Reflect.get(target, prop, receiver);\n },\n set(_, prop, value, receiver) {\n target ?? (target = getter());\n return Reflect.set(target, prop, value, receiver);\n },\n has(_, prop) {\n target ?? (target = getter());\n return Reflect.has(target, prop);\n },\n deleteProperty(_, prop) {\n target ?? (target = getter());\n return Reflect.deleteProperty(target, prop);\n },\n ownKeys(_) {\n target ?? (target = getter());\n return Reflect.ownKeys(target);\n },\n getOwnPropertyDescriptor(_, prop) {\n target ?? (target = getter());\n return Reflect.getOwnPropertyDescriptor(target, prop);\n },\n defineProperty(_, prop, descriptor) {\n target ?? (target = getter());\n return Reflect.defineProperty(target, prop, descriptor);\n },\n });\n}\nexport function stringifyPrimitive(value) {\n if (typeof value === \"bigint\")\n return value.toString() + \"n\";\n if (typeof value === \"string\")\n return `\"${value}\"`;\n return `${value}`;\n}\nexport function optionalKeys(shape) {\n return Object.keys(shape).filter((k) => {\n return shape[k]._zod.optin !== undefined && shape[k]._zod.optout === \"optional\";\n });\n}\n// Wrapped in a `@__PURE__` IIFE: esbuild never tree-shakes a top-level initializer that contains a member access on `Number`, so the bare object literal survived into every bundle.\nexport const NUMBER_FORMAT_RANGES = /*@__PURE__*/ (() => ({\n safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],\n int32: [-2147483648, 2147483647],\n uint32: [0, 4294967295],\n float32: [-3.4028234663852886e38, 3.4028234663852886e38],\n float64: [-Number.MAX_VALUE, Number.MAX_VALUE],\n}))();\nexport const BIGINT_FORMAT_RANGES = {\n int64: [/* @__PURE__*/ BigInt(\"-9223372036854775808\"), /* @__PURE__*/ BigInt(\"9223372036854775807\")],\n uint64: [/* @__PURE__*/ BigInt(0), /* @__PURE__*/ BigInt(\"18446744073709551615\")],\n};\nexport function pick(schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".pick() cannot be used on object schemas containing refinements\");\n }\n const newShape = {};\n mirrorShape(newShape, schema, maskedKeys(schema, mask));\n return clone(schema, mergeDefs(currDef, { shape: newShape, checks: [] }));\n}\n// the mask keys that select something, checked against the source's shape without resolving it\nfunction maskedKeys(schema, mask) {\n const raw = sourceShape(schema);\n const keys = [];\n // `for...in` skips symbols, so a symbol in the mask would select nothing\n for (const key of Reflect.ownKeys(mask)) {\n if (!Object.getOwnPropertyDescriptor(raw, key)?.enumerable) {\n throw new Error(`Unrecognized key: \"${String(key)}\"`);\n }\n if (mask[key])\n keys.push(key);\n }\n return keys;\n}\nexport function omit(schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".omit() cannot be used on object schemas containing refinements\");\n }\n const omitted = new Set(maskedKeys(schema, mask));\n const newShape = {};\n mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)).filter((key) => !omitted.has(key)));\n return clone(schema, mergeDefs(currDef, { shape: newShape, checks: [] }));\n}\nexport function extend(schema, shape) {\n if (!isPlainObject(shape)) {\n throw new Error(\"Invalid input to extend: expected a plain object\");\n }\n const checks = schema._zod.def.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n // Only throw if new shape overlaps with existing shape. Use getOwnPropertyDescriptor to check key existence without accessing values\n const existingShape = sourceShape(schema);\n for (const key of Reflect.ownKeys(shape)) {\n if (Object.getOwnPropertyDescriptor(existingShape, key) !== undefined) {\n throw new Error(\"Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.\");\n }\n }\n }\n return clone(schema, mergeDefs(schema._zod.def, { shape: extended(schema, shape) }));\n}\n// the source's keys, then the caller's overlaid on top\nfunction extended(schema, shape) {\n const newShape = {};\n mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)));\n mirrorProps(newShape, shape);\n return newShape;\n}\nexport function safeExtend(schema, shape) {\n if (!isPlainObject(shape)) {\n throw new Error(\"Invalid input to safeExtend: expected a plain object\");\n }\n return clone(schema, mergeDefs(schema._zod.def, { shape: extended(schema, shape) }));\n}\nexport function merge(a, b) {\n if (!b?._zod?.def) {\n throw new Error(\"Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.\");\n }\n if (a._zod.def.checks?.length) {\n throw new Error(\".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.\");\n }\n const newShape = {};\n mirrorShape(newShape, a, Reflect.ownKeys(sourceShape(a)));\n mirrorShape(newShape, b, Reflect.ownKeys(sourceShape(b)));\n const def = mergeDefs(a._zod.def, {\n shape: newShape,\n get catchall() {\n return b._zod.def.catchall;\n },\n checks: b._zod.def.checks ?? [],\n });\n return clone(a, def);\n}\nexport function partial(Class, schema, mask, name = \"partial\") {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(`.${name}() cannot be used on object schemas containing refinements`);\n }\n const selected = mask ? new Set(maskedKeys(schema, mask)) : undefined;\n const newShape = {};\n mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)), Class &&\n ((value, key) => (selected && !selected.has(key) ? value : new Class({ type: \"optional\", innerType: value }))));\n return clone(schema, mergeDefs(schema._zod.def, { shape: newShape, checks: [] }));\n}\nexport function required(Class, schema, mask) {\n const selected = mask ? new Set(maskedKeys(schema, mask)) : undefined;\n const newShape = {};\n mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)), (value, key) => \n // overwrite with non-optional\n selected && !selected.has(key) ? value : new Class({ type: \"nonoptional\", innerType: value }));\n return clone(schema, mergeDefs(schema._zod.def, { shape: newShape }));\n}\n// invalid_type | too_big | too_small | invalid_format | not_multiple_of | unrecognized_keys | invalid_union | invalid_key | invalid_element | invalid_value | custom\nexport function aborted(x, startIndex = 0) {\n if (x.aborted === true)\n return true;\n for (let i = startIndex; i < x.issues.length; i++) {\n if (x.issues[i]?.continue !== true) {\n return true;\n }\n }\n return false;\n}\n// Checks for explicit abort (continue === false), as opposed to implicit abort (continue === undefined). Used to respect `abort: true` in .refine() even for checks that have a `when` function.\nexport function explicitlyAborted(x, startIndex = 0) {\n if (x.aborted === true)\n return true;\n for (let i = startIndex; i < x.issues.length; i++) {\n if (x.issues[i]?.continue === false) {\n return true;\n }\n }\n return false;\n}\nexport function prefixIssues(path, issues) {\n return issues.map((iss) => {\n var _a;\n (_a = iss).path ?? (_a.path = []);\n iss.path.unshift(path);\n return iss;\n });\n}\nexport function unwrapMessage(message) {\n return typeof message === \"string\" ? message : message?.message;\n}\n/* A check holds no link back to the schema it is attached to — the same check instance is shared by every clone of that schema — so the owner is stamped onto the issues a check just raised, at the only point where both are in scope. Runs on the failure path only; `start` is the issue count from before the check ran. */\n/** The leading size checks of `defChecks` that set an upper bound, each paired with it. */\nexport function sizeCaps(defChecks) {\n const caps = [];\n for (const ch of defChecks ?? []) {\n const d = ch._zod.def;\n // a later check may rewrite the value\n if (!/_(length|size)$|_equals$/.test(d.check))\n break;\n const max = d.maximum ?? d.length ?? d.size;\n if (max >= 0)\n caps.push([max, ch]);\n }\n return caps;\n}\nexport function attachSchema(issues, start, inst) {\n var _a;\n for (let i = start; i < issues.length; i++) {\n (_a = issues[i]).schema ?? (_a.schema = inst);\n }\n}\nexport function finalizeIssue(iss, ctx, config) {\n var _a;\n // A schema that raised an issue itself owns it outright, and outranks any stamp an enclosing check left in `attachSchema`. String formats and z.custom() are schema and check at once, so when they act as a check they defer to that stamp instead.\n const traits = iss.inst?._zod?.traits;\n if (traits?.has(\"$ZodType\")) {\n if (traits.has(\"$ZodCheck\"))\n (_a = iss).schema ?? (_a.schema = iss.inst);\n else\n iss.schema = iss.inst;\n }\n // Decreasing specificity, first map to return a message wins. `inst` is whatever raised the issue, so a check's own map outranks the owning schema's.\n const schemaError = iss.schema !== iss.inst ? iss.schema?._zod.def?.error : undefined;\n const message = iss.message\n ? iss.message\n : (unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ??\n unwrapMessage(schemaError?.(iss)) ??\n unwrapMessage(ctx?.error?.(iss)) ??\n unwrapMessage(config.customError?.(iss)) ??\n unwrapMessage(config.localeError?.(iss)) ??\n \"Invalid input\");\n // an explicit own-key copy beats object rest with excluded keys, which v8 routes through a generic runtime call; Object.keys rather than for-in so an issue pushed with a prototype does not leak inherited keys, and an own __proto__ key is dropped rather than assigned through the setter\n const full = {};\n for (const k of Object.keys(iss)) {\n if (k === \"inst\" || k === \"schema\" || k === \"continue\" || k === \"input\" || k === \"__proto__\")\n continue;\n full[k] = iss[k];\n }\n full.path ?? (full.path = []);\n full.message = message;\n if (ctx?.reportInput) {\n full.input = iss.input;\n }\n return full;\n}\nexport function getSizableOrigin(input) {\n if (input instanceof Set)\n return \"set\";\n if (input instanceof Map)\n return \"map\";\n // @ts-ignore\n if (input instanceof File)\n return \"file\";\n return \"unknown\";\n}\nconst highSurrogate = /[\\uD800-\\uDBFF]/;\n// Code points in `str`: a surrogate pair counts once, a lone surrogate as itself. Hand-rolled because the string iterator allocates and runs ~250x slower on this path; the regex probe exits ~50x quicker for a string with no astral characters.\nexport function codePointLength(str) {\n const units = str.length;\n if (!highSurrogate.test(str))\n return units;\n let count = units;\n for (let i = 0; i < units - 1; i++) {\n if ((str.charCodeAt(i) & 0xfc00) === 0xd800 && (str.charCodeAt(i + 1) & 0xfc00) === 0xdc00) {\n count--;\n i++;\n }\n }\n return count;\n}\nexport function getLengthableOrigin(input) {\n if (Array.isArray(input))\n return \"array\";\n if (typeof input === \"string\")\n return \"string\";\n return \"unknown\";\n}\nexport function parsedType(data) {\n const t = typeof data;\n switch (t) {\n case \"number\": {\n return Number.isNaN(data) ? \"nan\" : \"number\";\n }\n case \"object\": {\n if (data === null) {\n return \"null\";\n }\n if (Array.isArray(data)) {\n return \"array\";\n }\n const obj = data;\n if (obj && Object.getPrototypeOf(obj) !== Object.prototype && \"constructor\" in obj && obj.constructor) {\n return obj.constructor.name;\n }\n }\n }\n return t;\n}\nexport function issue(...args) {\n const [iss, input, inst] = args;\n if (typeof iss === \"string\") {\n return {\n message: iss,\n code: \"custom\",\n input,\n inst,\n };\n }\n return { ...iss };\n}\nexport function cleanEnum(obj) {\n return Object.entries(obj)\n .filter(([k, _]) => {\n // return true if NaN, meaning it's not a number, thus a string key\n return Number.isNaN(Number.parseInt(k, 10));\n })\n .map((el) => el[1]);\n}\n// Codec utility functions\nexport function base64ToUint8Array(base64) {\n const binaryString = atob(base64);\n const bytes = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n bytes[i] = binaryString.charCodeAt(i);\n }\n return bytes;\n}\nexport function uint8ArrayToBase64(bytes) {\n let binaryString = \"\";\n for (let i = 0; i < bytes.length; i++) {\n binaryString += String.fromCharCode(bytes[i]);\n }\n return btoa(binaryString);\n}\nexport function base64urlToUint8Array(base64url) {\n const base64 = base64url.replace(/-/g, \"+\").replace(/_/g, \"/\");\n const padding = \"=\".repeat((4 - (base64.length % 4)) % 4);\n return base64ToUint8Array(base64 + padding);\n}\nexport function uint8ArrayToBase64url(bytes) {\n return uint8ArrayToBase64(bytes).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=/g, \"\");\n}\nexport function hexToUint8Array(hex) {\n const cleanHex = hex.replace(/^0x/, \"\");\n if (cleanHex.length % 2 !== 0) {\n throw new Error(\"Invalid hex string length\");\n }\n const bytes = new Uint8Array(cleanHex.length / 2);\n for (let i = 0; i < cleanHex.length; i += 2) {\n bytes[i / 2] = Number.parseInt(cleanHex.slice(i, i + 2), 16);\n }\n return bytes;\n}\nexport function uint8ArrayToHex(bytes) {\n return Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n// instanceof\nexport class Class {\n constructor(..._args) { }\n}\n////////// PROTOTYPE INSTALLERS //////////\n//\n// Members live on the prototype and materialize per instance on first read, which keeps own-property count under the step where V8 stops using inline slots. Changing anything here means re-measuring runtime, memory and bundle size together — see \"The three axes\" in AGENTS.md.\n/**\n * Installs a trait's members on its prototype. Each value builds that member for the instance on first read; the built value shadows the accessor as an own property, so a detached `const { parse } = schema` keeps working.\n *\n * Call this from a `proto` initializer, which runs once per prototype — never per instance.\n */\nexport function members(proto, table) {\n for (const key in table) {\n const desc = Object.getOwnPropertyDescriptor(table, key);\n // a getter installs as written, so it stays live: `description` reads through to the registry on every access. not enumerable: an object literal's is, and a prototype member never was\n if (desc.get)\n Object.defineProperty(proto, key, { ...desc, enumerable: false });\n // a method materializes bound on first read, which is what keeps a detached member working: `const opt = schema.optional; opt()`\n else\n defineBound(proto, key, desc.value);\n }\n}\n/** Shadows a prototype member with an own value, so a getter that builds from the instance runs once. */\nexport function own(inst, key, value, enumerable = true) {\n Object.defineProperty(inst, key, { configurable: true, writable: true, enumerable, value });\n return value;\n}\n/** Like {@link own}, for a member that was never an own data property and has to stay out of `Object.keys`. */\nexport function hide(inst, key, value) {\n return own(inst, key, value, false);\n}\n/** Adds members a table derives from the instance: each builds on first read and shadows as own data, and assignment shadows the same way, as when these were own properties. */\nexport /*@__NO_SIDE_EFFECTS__*/ function derived(computes, table) {\n for (const key in computes) {\n const compute = computes[key];\n // an object literal's accessor is configurable and enumerable, and `members` copies the descriptor as written\n Object.defineProperty(table, key, {\n configurable: true,\n enumerable: true,\n get() {\n return own(this, key, compute(this));\n },\n set(value) {\n own(this, key, value);\n },\n });\n }\n return table;\n}\nfunction defineBound(proto, key, fn) {\n Object.defineProperty(proto, key, {\n configurable: true,\n get() {\n // vitest's spyOn calls a prototype getter bare to find the function it wraps, so a nullish receiver answers the raw method\n return this == null ? fn : own(this, key, fn.bind(this));\n },\n set(value) {\n own(this, key, value);\n },\n });\n}\n/** Returns the prototype to install on, or `undefined` if this group is already installed on it. */\nfunction claim(inst, sentinel) {\n const proto = Object.getPrototypeOf(inst);\n // Runs on every construction, so `in` rather than the costlier `hasOwnProperty.call`. Sentinels are keys the group itself defines.\n return sentinel in proto ? undefined : proto;\n}\n// The internals whose init chain is installing. A second call for the same one is a derived constructor overriding its base, so it must not construct another schema in between or the override is dropped.\nlet installing;\n// Set while a getter is running, so a value that resolved through a recursion break is not memoized. One shared descriptor shadows the key for the duration, which costs no per-key allocation.\nlet broke = false;\nconst breaker = {\n configurable: true,\n get() {\n broke = true;\n return undefined;\n },\n};\n/**\n * Installs a lazily-derived internal on the `_zod` prototype of `inst`'s\n * constructor, computed from the internals object itself and cached there on\n * first read. One accessor per constructor rather than one per instance.\n */\nexport function defineLazyInternal(inst, key, compute) {\n const proto = Object.getPrototypeOf(inst._zod);\n if (key in proto && installing !== inst._zod) {\n // A repeat construction: everything is installed already. Cleared here so the reference is not held past the first construction of every type.\n installing = undefined;\n return;\n }\n installing = inst._zod;\n Object.defineProperty(proto, key, {\n configurable: true,\n get() {\n // Shadowed before computing so a re-entrant read from a recursive schema resolves to undefined instead of running the getter again.\n Object.defineProperty(this, key, breaker);\n const outer = broke;\n broke = false;\n try {\n const value = compute(this);\n // A result that resolved through a recursion break is recomputed once the graph is complete; everything else memoizes, undefined included.\n if (broke)\n delete this[key];\n else\n Object.defineProperty(this, key, { configurable: true, writable: true, value });\n broke = broke || outer;\n return value;\n }\n catch (err) {\n // A compute that threw memoizes nothing, so a later read runs it again and fails the same way. The shadow goes with it, since leaving it installed would answer undefined for every later read.\n delete this[key];\n broke = broke || outer;\n throw err;\n }\n },\n set(value) {\n Object.defineProperty(this, key, { configurable: true, writable: true, value });\n },\n });\n}\n/**\n * Installs `key` on `inst`'s prototype, computed by `make` on first read and cached there as an own\n * data property. One accessor per constructor rather than one per instance, because an own accessor\n * puts every instance after the first into v8 dictionary mode. The key doubles as the sentinel.\n */\nexport function installLazyProp(inst, key, make, enumerable) {\n const proto = claim(inst, key);\n if (!proto)\n return;\n Object.defineProperty(proto, key, {\n configurable: true,\n get() {\n // Shadowed before computing, so a re-entrant read from a self-referential shape resolves to undefined instead of running the getter again. A data property rather than an accessor: an own accessor is the dictionary-mode transition this exists to avoid.\n const desc = { configurable: true, writable: true, enumerable, value: undefined };\n Object.defineProperty(this, key, desc);\n // a compute that throws leaves the shadow behind, so later reads answer undefined instead of re-throwing; `defineLazy` did the same, and `defineLazyInternal`'s delete-on-catch would cost bytes in every bundle for a case only a throwing user getter reaches\n desc.value = make(this);\n Object.defineProperty(this, key, desc);\n return desc.value;\n },\n set(value) {\n Object.defineProperty(this, key, { configurable: true, writable: true, enumerable, value });\n },\n });\n}\n/** Marks the thunk `_catch` synthesises for a constant catch value. `Function.length` cannot tell that thunk from a user callback — rest and defaulted parameters both report arity 0 — and a user callback reads `ctx.error`, whose issues only finalize correctly against the caller's per-parse error map. Provenance can say what arity cannot. A plain string key rather than `Symbol.for`, whose call at module scope no bundler can prove pure — the same shape that anchored `urlCanParse` into every build. */\nexport const CONSTANT_CATCH = \"~constantCatch\";\n/** Wraps a constant catch value in a thunk tagged with {@link CONSTANT_CATCH}. */\nexport function constantCatch(value) {\n const fn = () => value;\n fn[CONSTANT_CATCH] = true;\n return fn;\n}\n","var _a;\nimport { members as installMembers } from \"./util.js\";\n/** A special constant with type `never` */\nexport const NEVER = /*@__PURE__*/ Object.freeze({\n status: \"aborted\",\n});\n/* Shared descriptor for installing `_zod`; defineProperty reads it\n * synchronously, so reusing one object avoids a per-instance allocation. */\nconst _zodDesc = { value: undefined, enumerable: false };\n// null where suppressing the capture would be unrecoverable: `parse()` puts the frames back with `captureStackTrace`, so without it the throw would lose its stack. also latched to null once `stackTraceLimit` proves unassignable, which a realm can do at any point by hardening Error\nlet _E = \"captureStackTrace\" in Error ? Error : null;\n// v8 captures a stack trace inside the Error constructor, which dominates a failed parse; costs only the frames, and parse() restores those. the constructor must RUN: Object.create is cheaper and passes instanceof, but Error.isError and util.types.isNativeError check an internal slot\nfunction newError(Definition) {\n const E = _E;\n if (E) {\n const saved = E.stackTraceLimit;\n if (typeof saved === \"number\") {\n try {\n E.stackTraceLimit = 0;\n }\n catch {\n _E = null;\n return new Definition();\n }\n try {\n return new Definition();\n }\n finally {\n E.stackTraceLimit = saved;\n }\n }\n }\n return new Definition();\n}\nexport /*@__NO_SIDE_EFFECTS__*/ function $constructor(name, initializer, \n/** This trait's members, installed once on every prototype that composes it. They cannot be declared in the initializer above: that runs per instance, and the prototype is shared. */\nproto, params) {\n // Prototype for this constructor's `_zod` internals. Lazily-derived fields (`values`, `pattern`, `optin`, …) install here once rather than as an accessor on every instance.\n const zodProto = {};\n // Assigning the fields in the constructor body is what gives instances in-object slots; building the object literally and reparenting it costs a second allocation and a generic property copy.\n function Internals(def) {\n this.def = def;\n this.constr = _;\n this.traits = new Set();\n }\n Internals.prototype = zodProto;\n const protoMembers = proto;\n // One trait's members land on every prototype whose chain composes it, so the answer is per prototype rather than per trait.\n const initialized = protoMembers && new WeakSet();\n function init(inst, def) {\n if (!inst._zod) {\n _zodDesc.value = new Internals(def);\n try {\n Object.defineProperty(inst, \"_zod\", _zodDesc);\n }\n finally {\n // Cleared even on throw, so the shared descriptor never leaks one instance's internals into the next.\n _zodDesc.value = undefined;\n }\n }\n else if (inst._zod.traits.has(name)) {\n return;\n }\n inst._zod.traits.add(name);\n initializer(inst, def);\n if (initialized) {\n // `super(def)` from a user subclass gives `this` a prototype the subclass owns, and installing there would overwrite whatever the subclass declared. `constr` built the instance, so its prototype is the one below the subclass's that should carry the members. A receiver whose chain never reaches that prototype installs on its own, which for a plain object handed straight to `init` means `Object.prototype` — unchanged from before.\n const own = Object.getPrototypeOf(inst);\n const ctorProto = inst._zod.constr.prototype;\n let up = own;\n while (up && up !== ctorProto)\n up = Object.getPrototypeOf(up);\n const target = up ?? own;\n if (!initialized.has(target)) {\n initialized.add(target);\n installMembers(target, protoMembers);\n }\n }\n // support prototype modifications; for-in avoids the array allocation of Object.keys on the (usually empty) prototype\n const proto = _.prototype;\n for (const k in proto) {\n if (!Object.prototype.hasOwnProperty.call(proto, k))\n continue;\n if (!(k in inst)) {\n inst[k] = proto[k].bind(inst);\n }\n }\n }\n // doesn't work if Parent has a constructor with arguments\n const Parent = params?.Parent ?? Object;\n class Definition extends Parent {\n }\n Object.defineProperty(Definition, \"name\", { value: name });\n function _(def) {\n const inst = params?.Parent ? newError(Definition) : this;\n init(inst, def);\n const deferred = inst._zod.deferred;\n if (deferred) {\n for (const fn of deferred) {\n fn();\n }\n // Released: initializers run once, and the list would otherwise be retained for the schema's lifetime.\n inst._zod.deferred = undefined;\n }\n // Global post-processor hook. Internal: installed by `import \"zod/compile\"` to enable AOT compilation for every constructed schema. Runs last, once the instance is fully built, because it hands the instance to compile(). The post-processor is expected to be reentrancy-guarded by its own implementation.\n const pp = globalThis.__zod_globalConfig?.postProcessor;\n if (pp)\n pp(inst);\n return inst;\n }\n Object.defineProperty(_, \"init\", { value: init });\n Object.defineProperty(_, Symbol.hasInstance, {\n value: (inst) => {\n if (params?.Parent && inst instanceof params.Parent)\n return true;\n return inst?._zod?.traits?.has(name);\n },\n });\n Object.defineProperty(_, \"name\", { value: name });\n return _;\n}\n////////////////////////////// UTILITIES ///////////////////////////////////////\nexport const $brand = /*@__PURE__*/ Symbol(\"zod_brand\");\nexport class $ZodAsyncError extends Error {\n constructor() {\n super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);\n }\n}\nexport class $ZodEncodeError extends Error {\n constructor(name) {\n super(`Encountered unidirectional transform during encode: ${name}`);\n this.name = \"ZodEncodeError\";\n }\n}\n(_a = globalThis).__zod_globalConfig ?? (_a.__zod_globalConfig = {});\nexport const globalConfig = globalThis.__zod_globalConfig;\nexport function config(newConfig) {\n if (newConfig)\n Object.assign(globalConfig, newConfig);\n return globalConfig;\n}\n","import * as util from \"./util.js\";\nexport class $ZodCyclicError extends Error {\n constructor() {\n super(`Cannot parse a reference cycle that closes through a transform`);\n this.name = \"ZodCyclicError\";\n }\n}\n/** Keyed off the context object every schema in one parse call already shares. */\nconst STATE = \"~memo\";\nconst NO_ISSUES = [];\n// a value a cycle can close through\nfunction isRef(value) {\n return value !== null && typeof value === \"object\";\n}\n// Receivers prefix paths in place, so the cache and every hand-out need their own copies.\nfunction cloneIssues(issues) {\n return issues.map((iss) => (iss.path ? { ...iss, path: iss.path.slice() } : { ...iss }));\n}\nconst recursive = /*@__PURE__*/ new WeakMap();\n/** What the walk established, in order of certainty: ordered so the strongest answer among children wins. */\nconst NONE = 0;\nconst ASSUMED = 1;\nconst PROVEN = 2;\n/** Whether this schema's subtree contains a cycle, so one parse can re-enter it. */\nfunction isRecursive(inst, stack, resolve) {\n const cached = recursive.get(inst);\n if (cached !== undefined)\n return cached ? PROVEN : NONE;\n // Relative to the walk in progress, so not cached.\n if (stack.has(inst))\n return PROVEN;\n stack.add(inst);\n let result = NONE;\n const check = (child) => {\n if (result !== PROVEN && child?._zod) {\n const answer = isRecursive(child, stack, resolve);\n if (answer > result)\n result = answer;\n }\n };\n // `Reflect.ownKeys` rather than `Object.keys`, so a cycle through a declared symbol key is still seen\n const shape = (sh, spread) => {\n let answer = NONE;\n for (const key of Reflect.ownKeys(sh)) {\n const desc = Object.getOwnPropertyDescriptor(sh, key);\n // an object resolves its shape by spread, so a key it does not enumerate is never parsed; `z.properties` reads every own key and so keeps them all\n if (spread && !desc.enumerable)\n continue;\n // resolving runs user code, and a factory mints a fresh subtree per read, so an edge the walk can't follow counts as a cycle\n const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve) : NONE;\n if (child > answer)\n answer = child;\n }\n return answer;\n };\n const merge = (answer) => {\n if (answer > result)\n result = answer;\n };\n const def = inst._zod.def;\n const kind = def.type;\n switch (kind) {\n case \"object\": {\n const raw = util.rawShape(def);\n // a def with no raw shape answers `shape` from an accessor of its own, and running that can mint a whole fresh subtree\n merge(raw ? shape(raw, true) : ASSUMED);\n check(def.catchall);\n break;\n }\n case \"array\":\n check(def.element);\n break;\n case \"tuple\":\n for (const el of def.items)\n check(el);\n check(def.rest);\n break;\n case \"record\":\n case \"map\":\n check(def.keyType);\n check(def.valueType);\n break;\n case \"set\":\n check(def.valueType);\n break;\n case \"union\":\n for (const el of def.options)\n check(el);\n break;\n case \"intersection\":\n check(def.left);\n check(def.right);\n break;\n case \"optional\":\n case \"nullable\":\n case \"default\":\n case \"prefault\":\n case \"catch\":\n case \"readonly\":\n case \"nonoptional\":\n case \"promise\":\n case \"success\":\n check(def.innerType);\n break;\n case \"pipe\":\n check(def.in);\n check(def.out);\n break;\n case \"function\":\n check(def.input);\n check(def.output);\n break;\n // `$ZodLazy` caches its inner on the def, so a resolved edge is followed exactly\n case \"lazy\": {\n const inner = def._cachedInner ?? (resolve ? inst._zod.innerType : undefined);\n // walked with resolution off: one hop sees past the deferral, and a lazy that yields only another unresolved lazy is generative, so it stops there\n merge(inner ? isRecursive(inner, stack, false) : ASSUMED);\n break;\n }\n // a leaf by choice: `parts` are regex fragments, not data positions\n case \"template_literal\":\n // leaves\n case \"string\":\n case \"number\":\n case \"int\":\n case \"boolean\":\n case \"bigint\":\n case \"symbol\":\n case \"undefined\":\n case \"null\":\n case \"void\":\n case \"never\":\n case \"any\":\n case \"unknown\":\n case \"date\":\n case \"nan\":\n case \"enum\":\n case \"literal\":\n case \"file\":\n case \"transform\":\n case \"custom\":\n break;\n default: {\n // a new built-in kind becomes a compile error here\n kind;\n // a user-defined kind can still hold children, and only its author knows where, so fall back to scanning the def — skipping accessors, since reading one can run user code\n for (const key in def) {\n const desc = Object.getOwnPropertyDescriptor(def, key);\n if (!desc || desc.get)\n continue;\n const value = desc.value;\n if (!value || typeof value !== \"object\")\n continue;\n if (value._zod)\n check(value);\n else if (Array.isArray(value))\n for (const el of value)\n check(el);\n }\n }\n }\n stack.delete(inst);\n return settle(inst, result);\n}\n/** An assumed answer must not outlive the resolution that settles it, so only a certain one is cached. */\nfunction settle(inst, answer) {\n if (answer !== ASSUMED)\n recursive.set(inst, answer === PROVEN);\n return answer;\n}\n/**\n * Whether one parse can re-enter this schema, i.e. its subtree contains a cycle.\n * Exported for `z.compile`, which refuses to compile such a schema: cycle\n * breaking is driven from here off state keyed on the parse context, and a\n * generated fast path has no context to key on.\n */\nexport function isRecursiveSchema(inst) {\n // z.compile never parses, so nothing would ever resolve a lazy for it; it runs once and already treats a throw here as recursive\n return isRecursive(inst, new Set(), true) !== NONE;\n}\nfunction bucketFor(state, inst) {\n let bucket = state.buckets.get(inst);\n if (!bucket) {\n bucket = new WeakMap();\n state.buckets.set(inst, bucket);\n }\n return bucket;\n}\n// Set immediately before delegating to core and cleared immediately after, so `alloc` registers only for a visit this module is driving.\nlet handoff;\n// Allocated but unfinished entries. `alloc` and the matching pop both happen in the synchronous part of a parse, so they nest even when children are async, and one stack serves every schema.\nconst open = [];\nconst memo = {\n alloc(_inst, payload, empty) {\n const bucket = handoff;\n if (!bucket)\n return empty;\n handoff = undefined;\n const entry = { value: empty, issues: null };\n bucket.set(payload.value, entry);\n open.push(entry);\n return empty;\n },\n guard(inst) {\n var _a;\n (_a = inst._zod).deferred ?? (_a.deferred = []);\n inst._zod.deferred.push(() => {\n const base = inst._zod.parse;\n const wrapped = (payload, ctx) => {\n // The value is a placeholder a back-edge is still waiting on, so the cycle closes through this transform. Its output can't exist in time to bind.\n if (ctx.direction !== \"backward\" && isBackEdge(ctx, payload.value))\n throw new $ZodCyclicError();\n return base(payload, ctx);\n };\n inst._zod.parse = wrapped;\n if (inst._zod.run === base)\n inst._zod.run = wrapped;\n });\n },\n attach(inst) {\n var _a;\n let isRecursiveInst;\n let rechecked = false;\n // a recursive schema is re-entered many times per parse and its bucket never changes\n let lastCtx;\n let lastBucket;\n // Wraps `parse` in a deferred so it sees the container's final parse. Core's own deferred copies `parse` into `run` when there are no checks, and it ran first, so `run` is patched to match; with checks, `run` reads `parse` dynamically.\n (_a = inst._zod).deferred ?? (_a.deferred = []);\n inst._zod.deferred.push(() => {\n const base = inst._zod.parse;\n const wrapped = (payload, ctx) => {\n if (isRecursiveInst === undefined) {\n const walked = isRecursive(inst, new Set(), false);\n if (walked === NONE) {\n // Nothing here can ever fire, so take it back out.\n inst._zod.parse = base;\n if (inst._zod.run === wrapped)\n inst._zod.run = base;\n return base(payload, ctx);\n }\n // this parse resolves the deferred edges on its own path, so ask once more before latching\n if (walked === PROVEN || rechecked)\n isRecursiveInst = true;\n else\n rechecked = true;\n }\n const input = payload.value;\n if (!isRef(input))\n return base(payload, ctx);\n let state = ctx[STATE];\n if (!state) {\n state = { buckets: new WeakMap(), backEdges: undefined };\n ctx[STATE] = state;\n }\n let bucket;\n if (lastCtx === ctx) {\n bucket = lastBucket;\n }\n else {\n bucket = bucketFor(state, inst);\n lastCtx = ctx;\n lastBucket = bucket;\n }\n const hit = bucket.get(input);\n if (hit) {\n payload.value = hit.value;\n if (hit.issues) {\n if (hit.issues.length)\n payload.issues.push(...cloneIssues(hit.issues));\n }\n else {\n // Still being parsed: its own checks cover it, so skip them here.\n payload.memo = true;\n state.backEdges ?? (state.backEdges = new WeakSet());\n state.backEdges.add(hit.value);\n }\n return payload;\n }\n handoff = bucket;\n const depth = open.length;\n const result = base(payload, ctx);\n handoff = undefined;\n // A container that rejected its input outright allocated nothing.\n const entry = open.length > depth ? open.pop() : undefined;\n // Both paths written out so the sync one allocates no closure. It runs once per node, and capturing here cost more than everything else combined.\n if (result instanceof Promise) {\n return result.then((r) => {\n if (entry)\n entry.issues = r.issues.length ? cloneIssues(r.issues) : NO_ISSUES;\n return r;\n });\n }\n if (entry)\n entry.issues = result.issues.length ? cloneIssues(result.issues) : NO_ISSUES;\n return result;\n };\n inst._zod.parse = wrapped;\n if (inst._zod.run === base)\n inst._zod.run = wrapped;\n });\n },\n};\n/** The memoizer that gives containers cycle support. `zod` installs it by default; `zod/mini` opts in with `config({ memoizer: memoizer() })`. */\nexport function memoizer() {\n return memo;\n}\n/** Whether this value is a node a back-edge resolved to before it finished. */\nexport function isBackEdge(ctx, value) {\n const backEdges = ctx[STATE]?.backEdges;\n return backEdges !== undefined && isRef(value) && backEdges.has(value);\n}\n","import * as util from \"./util.js\";\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link cuid2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport const cuid = /^[cC][0-9a-z]{6,}$/;\nexport const cuid2 = /^[0-9a-z]+$/;\nexport const ulid = /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/;\nexport const xid = /^[0-9a-vA-V]{20}$/;\nexport const ksuid = /^[A-Za-z0-9]{27}$/;\nexport const nanoid = /^[a-zA-Z0-9_-]{21}$/;\nexport function nanoidOfLength(length) {\n return new RegExp(`^[a-zA-Z0-9_-]{${length}}$`);\n}\n/** ISO 8601-1 duration regex. Does not support the 8601-2 extensions like negative durations or fractional/negative components. */\nexport const duration = /^P(?:(\\d+W)|(?!.*W)(?=\\d|T\\d)(\\d+Y)?(\\d+M)?(\\d+D)?(T(?=\\d)(\\d+H)?(\\d+M)?(\\d+([.,]\\d+)?S)?)?)$/;\n/** Implements ISO 8601-2 extensions like explicit +- prefixes, mixing weeks with other units, and fractional/negative components. */\nexport const extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\\d+Y)|(?:[-+]?\\d+[.,]\\d+Y$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:(?:[-+]?\\d+W)|(?:[-+]?\\d+[.,]\\d+W$))?(?:(?:[-+]?\\d+D)|(?:[-+]?\\d+[.,]\\d+D$))?(?:T(?=[\\d+-])(?:(?:[-+]?\\d+H)|(?:[-+]?\\d+[.,]\\d+H$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:[-+]?\\d+(?:[.,]\\d+)?S)?)??$/;\n/** A regex for any UUID-like identifier: 8-4-4-4-12 hex pattern */\nexport const guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;\n/** Returns a regex for validating an RFC 9562/4122 UUID.\n *\n * @param version Optionally specify a version 1-8. If no version is specified, all versions are supported. */\nexport const uuid = (version) => {\n if (!version)\n return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;\n return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);\n};\nexport const uuid4 = /*@__PURE__*/ uuid(4);\nexport const uuid6 = /*@__PURE__*/ uuid(6);\nexport const uuid7 = /*@__PURE__*/ uuid(7);\n/** Practical email validation */\nexport const email = /^(?:[A-Za-z0-9_'+\\-]+\\.)*[A-Za-z0-9_'+\\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$/;\n/** Equivalent to the HTML5 input[type=email] validation implemented by browsers. Source: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email */\nexport const html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n/** The classic emailregex.com regex for RFC 5322-compliant emails */\nexport const rfc5322Email = /^(([^<>()\\[\\]\\\\.,;:\\s@\"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/;\n/** A loose regex that allows Unicode characters, enforces length limits, and that's about it. */\nexport const unicodeEmail = /^[^\\s@\"]{1,64}@[^\\s@]{1,255}$/u;\nexport const idnEmail = unicodeEmail;\nexport const browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression\n// Single character class, not an alternation: the two properties overlap (U+1F9B0-U+1F9B3), so `(A|B)+` backtracks exponentially on a failed match. The leading lookahead then demands one anchor — a pictograph, a regional indicator, or the enclosing keycap — because `\\p{Emoji_Component}` on its own covers ASCII digits, `#`, `*`, ZWJ, variation selectors and skin tone modifiers, none of which is an emoji without a base.\nconst _emoji = `^(?=[\\\\s\\\\S]*[\\\\p{Extended_Pictographic}\\\\p{Regional_Indicator}\\\\u20E3])[\\\\p{Extended_Pictographic}\\\\p{Emoji_Component}]+$`;\nexport function emoji() {\n return new RegExp(_emoji, \"u\");\n}\nexport const ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;\nexport const ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;\nexport const mac = (delimiter) => {\n const escapedDelim = util.escapeRegex(delimiter ?? \":\");\n return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`);\n};\nexport const cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\/([0-9]|[1-2][0-9]|3[0-2])$/;\nexport const cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;\n// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript\nexport const base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;\nexport const base64url = /^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/;\n// based on https://stackoverflow.com/questions/106179/regular-expression-to-match-dns-hostname-or-ip-address\n// export const hostname: RegExp = /^([a-zA-Z0-9-]+\\.)*[a-zA-Z0-9-]+$/;\nexport const hostname = /^(?=.{1,253}\\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\\.?$/;\nexport const domain = /^(?=.{1,253}$)([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,63}$/;\nexport const httpProtocol = /^https?$/;\n// https://blog.stevenlevithan.com/archives/validate-phone-number#r4-3 (regex sans spaces) E.164: leading digit must be 1-9; total digits (excluding '+') between 7-15\nexport const e164 = /^\\+[1-9]\\d{6,14}$/;\n// Credit card shape: 12–19 digits, optionally separated by single spaces or single hyphens. ISO/IEC 7812 caps the PAN at 19 digits; 12 is the shortest issued length (Maestro).\nexport const creditCard = /^\\d(?:[ -]?\\d){11,18}$/;\n// ISO 4217 alpha codes from the SIX list, regenerated by scripts/update-iso-4217.ts\nexport const currencyCode = /^(?:AED|AFN|ALL|AMD|AOA|ARS|AUD|AWG|AZN|BAM|BBD|BDT|BHD|BIF|BMD|BND|BOB|BOV|BRL|BSD|BTN|BWP|BYN|BZD|CAD|CDF|CHE|CHF|CHW|CLF|CLP|CNY|COP|COU|CRC|CUP|CVE|CZK|DJF|DKK|DOP|DZD|EGP|ERN|ETB|EUR|FJD|FKP|GBP|GEL|GHS|GIP|GMD|GNF|GTQ|GYD|HKD|HNL|HTG|HUF|IDR|ILS|INR|IQD|IRR|ISK|JMD|JOD|JPY|KES|KGS|KHR|KMF|KPW|KRW|KWD|KYD|KZT|LAK|LBP|LKR|LRD|LSL|LYD|MAD|MDL|MGA|MKD|MMK|MNT|MOP|MRU|MUR|MVR|MWK|MXN|MXV|MYR|MZN|NAD|NGN|NIO|NOK|NPR|NZD|OMR|PAB|PEN|PGK|PHP|PKR|PLN|PYG|QAR|RON|RSD|RUB|RWF|SAR|SBD|SCR|SDG|SEK|SGD|SHP|SLE|SOS|SRD|SSP|STN|SVC|SYP|SZL|THB|TJS|TMT|TND|TOP|TRY|TTD|TWD|TZS|UAH|UGX|USD|USN|UYI|UYU|UYW|UZS|VED|VES|VND|VUV|WST|XAD|XAF|XAG|XAU|XBA|XBB|XBC|XBD|XCD|XCG|XDR|XOF|XPD|XPF|XPT|XSU|XTS|XUA|XXX|YER|ZAR|ZMW|ZWG)$/;\n// iban electronic format: 2-letter country, check digits 02-98 (the only values `98 - remainder` can produce), 11-30 bban characters\nexport const iban = /^[A-Z]{2}(?!00|01|99)\\d{2}[A-Z0-9]{11,30}$/;\nconst dateSource = `(?:(?:\\\\d\\\\d[2468][048]|\\\\d\\\\d[13579][26]|\\\\d\\\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\\\d|30)|(?:02)-(?:0[1-9]|1\\\\d|2[0-8])))`;\n/** Anchors a pattern source. The interpolation lives here rather than at the call site because\n * esbuild will not drop a `@__PURE__` call whose own argument interpolates a variable, but it\n * will drop `anchor(dateSource)`. Keeping it inline pinned `date` into every bundle. */\nfunction anchor(source) {\n return new RegExp(`^${source}$`);\n}\nexport const date = /*@__PURE__*/ anchor(dateSource);\nfunction timeSource(args) {\n const hhmm = `(?:[01]\\\\d|2[0-3]):[0-5]\\\\d`;\n const regex = typeof args.precision === \"number\"\n ? args.precision === -1\n ? `${hhmm}`\n : args.precision === 0\n ? `${hhmm}:[0-5]\\\\d`\n : `${hhmm}:[0-5]\\\\d\\\\.\\\\d{${args.precision}}`\n : args.seconds\n ? `${hhmm}:[0-5]\\\\d(?:\\\\.\\\\d+)?`\n : `${hhmm}(?::[0-5]\\\\d(?:\\\\.\\\\d+)?)?`;\n return regex;\n}\nexport function time(args) {\n return new RegExp(`^${timeSource(args)}$`);\n}\n// Adapted from https://stackoverflow.com/a/3143231\nexport function datetime(args) {\n const opts = [\"Z\"];\n // if (args.offset) opts.push(`([+-]\\\\d{2}:\\\\d{2})`);\n if (args.offset)\n opts.push(`([+-](?:[01]\\\\d|2[0-3]):[0-5]\\\\d)`);\n // RFC 3339 mandates seconds wherever the time carries a `Z` or an offset, so only the unqualified form `local` adds may omit them\n const qualified = `${timeSource({ precision: args.precision, seconds: true })}(?:${opts.join(\"|\")})`;\n const timeRegex = args.local ? `${qualified}|${timeSource({ precision: args.precision })}` : qualified;\n return new RegExp(`^${dateSource}T(?:${timeRegex})$`);\n}\n// the unbounded form of `string()` as a literal, so every plain string shares one instance instead of building its own\nexport const anyString = /^[\\s\\S]{0,}$/;\nexport const string = (params) => {\n const regex = params ? `[\\\\s\\\\S]{${params?.minimum ?? 0},${params?.maximum ?? \"\"}}` : `[\\\\s\\\\S]*`;\n return new RegExp(`^${regex}$`);\n};\nexport const bigint = /^-?\\d+n?$/;\nexport const integer = /^-?\\d+$/;\nexport const number = /^-?\\d+(?:\\.\\d+)?$/;\nexport const boolean = /^(?:true|false)$/i;\nconst _null = /^null$/i;\nexport { _null as null };\nconst _undefined = /^undefined$/i;\nexport { _undefined as undefined };\n// regex for string with no uppercase letters\nexport const lowercase = /^[^A-Z]*$/;\n// regex for string with no lowercase letters\nexport const uppercase = /^[^a-z]*$/;\n// regex for hexadecimal strings (any length)\nexport const hex = /^[0-9a-fA-F]*$/;\n// Hash regexes for different algorithms and encodings\n// Helper function to create base64 regex with exact length and padding\nfunction fixedBase64(bodyLength, padding) {\n return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`);\n}\n// Helper function to create base64url regex with exact length (no padding)\nfunction fixedBase64url(length) {\n return new RegExp(`^[A-Za-z0-9_-]{${length}}$`);\n}\n// MD5 (16 bytes): base64 = 24 chars total (22 + \"==\")\nexport const md5_hex = /^[0-9a-fA-F]{32}$/;\nexport const md5_base64 = /*@__PURE__*/ fixedBase64(22, \"==\");\nexport const md5_base64url = /*@__PURE__*/ fixedBase64url(22);\n// SHA1 (20 bytes): base64 = 28 chars total (27 + \"=\")\nexport const sha1_hex = /^[0-9a-fA-F]{40}$/;\nexport const sha1_base64 = /*@__PURE__*/ fixedBase64(27, \"=\");\nexport const sha1_base64url = /*@__PURE__*/ fixedBase64url(27);\n// SHA256 (32 bytes): base64 = 44 chars total (43 + \"=\")\nexport const sha256_hex = /^[0-9a-fA-F]{64}$/;\nexport const sha256_base64 = /*@__PURE__*/ fixedBase64(43, \"=\");\nexport const sha256_base64url = /*@__PURE__*/ fixedBase64url(43);\n// SHA384 (48 bytes): base64 = 64 chars total (no padding)\nexport const sha384_hex = /^[0-9a-fA-F]{96}$/;\nexport const sha384_base64 = /*@__PURE__*/ fixedBase64(64, \"\");\nexport const sha384_base64url = /*@__PURE__*/ fixedBase64url(64);\n// SHA512 (64 bytes): base64 = 88 chars total (86 + \"==\")\nexport const sha512_hex = /^[0-9a-fA-F]{128}$/;\nexport const sha512_base64 = /*@__PURE__*/ fixedBase64(86, \"==\");\nexport const sha512_base64url = /*@__PURE__*/ fixedBase64url(86);\n","// import { $ZodType } from \"./schemas.js\";\nimport * as core from \"./core.js\";\nimport * as regexes from \"./regexes.js\";\nimport * as util from \"./util.js\";\nexport const $ZodCheck = /*@__PURE__*/ core.$constructor(\"$ZodCheck\", (inst, def) => {\n var _a;\n inst._zod ?? (inst._zod = {});\n inst._zod.def = def;\n (_a = inst._zod).onattach ?? (_a.onattach = []);\n});\n/** Default `when` for size-based checks: run only on non-nullish values with a `size`. */\nconst _whenHasSize = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.size !== undefined;\n};\n/** Default `when` for length-based checks: run only on non-nullish values with a `length`. */\nconst _whenHasLength = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.length !== undefined;\n};\nconst numericOriginMap = {\n number: \"number\",\n bigint: \"bigint\",\n object: \"date\",\n};\nexport const $ZodCheckLessThan = /*@__PURE__*/ core.$constructor(\"$ZodCheckLessThan\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const origin = numericOriginMap[typeof def.value];\n inst._zod.check = (payload) => {\n if (def.inclusive ? payload.value <= def.value : payload.value < def.value) {\n return;\n }\n payload.issues.push({\n origin: numericOriginMap[typeof payload.value] ?? origin,\n code: \"too_big\",\n maximum: typeof def.value === \"object\" ? def.value.getTime() : def.value,\n input: payload.value,\n inclusive: def.inclusive,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckGreaterThan = /*@__PURE__*/ core.$constructor(\"$ZodCheckGreaterThan\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const origin = numericOriginMap[typeof def.value];\n inst._zod.check = (payload) => {\n if (def.inclusive ? payload.value >= def.value : payload.value > def.value) {\n return;\n }\n payload.issues.push({\n origin: numericOriginMap[typeof payload.value] ?? origin,\n code: \"too_small\",\n minimum: typeof def.value === \"object\" ? def.value.getTime() : def.value,\n input: payload.value,\n inclusive: def.inclusive,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMultipleOf = \n/*@__PURE__*/ core.$constructor(\"$ZodCheckMultipleOf\", (inst, def) => {\n $ZodCheck.init(inst, def);\n inst._zod.check = (payload) => {\n if (typeof payload.value !== typeof def.value)\n throw new Error(\"Cannot mix number and bigint in multiple_of check.\");\n const isMultiple = typeof payload.value === \"bigint\"\n ? // `value % 0n` throws, and nothing is a multiple of zero — the number branch already fails this way via NaN\n def.value !== BigInt(0) && payload.value % def.value === BigInt(0)\n : util.floatSafeRemainder(payload.value, def.value) === 0;\n if (isMultiple)\n return;\n payload.issues.push({\n origin: typeof payload.value,\n code: \"not_multiple_of\",\n divisor: def.value,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckNumberFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckNumberFormat\", (inst, def) => {\n $ZodCheck.init(inst, def); // no format checks\n def.format = def.format || \"float64\";\n const isInt = def.format?.includes(\"int\");\n const origin = isInt ? \"int\" : \"number\";\n const [minimum, maximum] = util.NUMBER_FORMAT_RANGES[def.format];\n inst._zod.check = (payload) => {\n const input = payload.value;\n if (isInt) {\n if (!Number.isInteger(input)) {\n // invalid_format issue\n // payload.issues.push({\n // expected: def.format,\n // format: def.format,\n // code: \"invalid_format\",\n // input,\n // inst,\n // });\n // invalid_type issue\n payload.issues.push({\n expected: origin,\n format: def.format,\n code: \"invalid_type\",\n continue: false,\n input,\n inst,\n });\n return;\n // not_multiple_of issue\n // payload.issues.push({\n // code: \"not_multiple_of\",\n // origin: \"number\",\n // input,\n // inst,\n // divisor: 1,\n // });\n }\n if (!Number.isSafeInteger(input)) {\n if (input > 0) {\n // too_big\n payload.issues.push({\n input,\n code: \"too_big\",\n maximum: Number.MAX_SAFE_INTEGER,\n note: \"Integers must be within the safe integer range.\",\n inst,\n origin,\n inclusive: true,\n continue: !def.abort,\n });\n }\n else {\n // too_small\n payload.issues.push({\n input,\n code: \"too_small\",\n minimum: Number.MIN_SAFE_INTEGER,\n note: \"Integers must be within the safe integer range.\",\n inst,\n origin,\n inclusive: true,\n continue: !def.abort,\n });\n }\n return;\n }\n }\n if (input < minimum) {\n payload.issues.push({\n origin: \"number\",\n input,\n code: \"too_small\",\n minimum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n if (input > maximum) {\n payload.issues.push({\n origin: \"number\",\n input,\n code: \"too_big\",\n maximum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodCheckBigIntFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckBigIntFormat\", (inst, def) => {\n $ZodCheck.init(inst, def); // no format checks\n const [minimum, maximum] = util.BIGINT_FORMAT_RANGES[def.format];\n inst._zod.check = (payload) => {\n const input = payload.value;\n if (input < minimum) {\n payload.issues.push({\n origin: \"bigint\",\n input,\n code: \"too_small\",\n minimum: minimum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n if (input > maximum) {\n payload.issues.push({\n origin: \"bigint\",\n input,\n code: \"too_big\",\n maximum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodCheckMaxSize = /*@__PURE__*/ core.$constructor(\"$ZodCheckMaxSize\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = _whenHasSize);\n inst._zod.check = (payload) => {\n const input = payload.value;\n const size = input.size;\n if (size <= def.maximum)\n return;\n payload.issues.push({\n origin: util.getSizableOrigin(input),\n code: \"too_big\",\n maximum: def.maximum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMinSize = /*@__PURE__*/ core.$constructor(\"$ZodCheckMinSize\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = _whenHasSize);\n inst._zod.check = (payload) => {\n const input = payload.value;\n const size = input.size;\n if (size >= def.minimum)\n return;\n payload.issues.push({\n origin: util.getSizableOrigin(input),\n code: \"too_small\",\n minimum: def.minimum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckSizeEquals = /*@__PURE__*/ core.$constructor(\"$ZodCheckSizeEquals\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = _whenHasSize);\n inst._zod.check = (payload) => {\n const input = payload.value;\n const size = input.size;\n if (size === def.size)\n return;\n const tooBig = size > def.size;\n payload.issues.push({\n origin: util.getSizableOrigin(input),\n ...(tooBig ? { code: \"too_big\", maximum: def.size } : { code: \"too_small\", minimum: def.size }),\n inclusive: true,\n exact: true,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMaxLength = /*@__PURE__*/ core.$constructor(\"$ZodCheckMaxLength\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = _whenHasLength);\n inst._zod.check = (payload) => {\n const input = payload.value;\n const units = input.length;\n // Strings are measured in Unicode code points, not UTF-16 units. A code point is at most two units, so a string that already fits in units fits in code points; only an overflow has to be counted.\n const length = typeof input === \"string\" && units > def.maximum ? util.codePointLength(input) : units;\n if (length <= def.maximum)\n return;\n const origin = util.getLengthableOrigin(input);\n payload.issues.push({\n origin,\n code: \"too_big\",\n maximum: def.maximum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMinLength = /*@__PURE__*/ core.$constructor(\"$ZodCheckMinLength\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = _whenHasLength);\n inst._zod.check = (payload) => {\n const input = payload.value;\n const units = input.length;\n // A code point is one or two UTF-16 units, so fewer units than the floor can never reach it and twice the floor always clears it. Only in between is the exact count in doubt.\n const length = typeof input === \"string\" && units >= def.minimum && units < def.minimum * 2\n ? util.codePointLength(input)\n : units;\n if (length >= def.minimum)\n return;\n const origin = util.getLengthableOrigin(input);\n payload.issues.push({\n origin,\n code: \"too_small\",\n minimum: def.minimum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckLengthEquals = /*@__PURE__*/ core.$constructor(\"$ZodCheckLengthEquals\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = _whenHasLength);\n inst._zod.check = (payload) => {\n const input = payload.value;\n const units = input.length;\n // A code point is one or two UTF-16 units, so outside `[length, length * 2]` units the target is missed either way — and missed in the same direction in both measures.\n const length = typeof input === \"string\" && units >= def.length && units <= def.length * 2\n ? util.codePointLength(input)\n : units;\n if (length === def.length)\n return;\n const origin = util.getLengthableOrigin(input);\n const tooBig = length > def.length;\n payload.issues.push({\n origin,\n ...(tooBig ? { code: \"too_big\", maximum: def.length } : { code: \"too_small\", minimum: def.length }),\n inclusive: true,\n exact: true,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckStringFormat\", (inst, def) => {\n var _a, _b;\n $ZodCheck.init(inst, def);\n if (def.pattern)\n (_a = inst._zod).check ?? (_a.check = (payload) => {\n def.pattern.lastIndex = 0;\n if (def.pattern.test(payload.value))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: def.format,\n input: payload.value,\n ...(def.pattern ? { pattern: def.pattern.toString() } : {}),\n inst,\n continue: !def.abort,\n });\n });\n else\n (_b = inst._zod).check ?? (_b.check = () => { });\n});\nexport const $ZodCheckRegex = /*@__PURE__*/ core.$constructor(\"$ZodCheckRegex\", (inst, def) => {\n $ZodCheckStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n def.pattern.lastIndex = 0;\n if (def.pattern.test(payload.value))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"regex\",\n input: payload.value,\n pattern: def.pattern.toString(),\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckLowerCase = /*@__PURE__*/ core.$constructor(\"$ZodCheckLowerCase\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.lowercase);\n $ZodCheckStringFormat.init(inst, def);\n});\nexport const $ZodCheckUpperCase = /*@__PURE__*/ core.$constructor(\"$ZodCheckUpperCase\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.uppercase);\n $ZodCheckStringFormat.init(inst, def);\n});\nexport const $ZodCheckIncludes = /*@__PURE__*/ core.$constructor(\"$ZodCheckIncludes\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const escapedRegex = util.escapeRegex(def.includes);\n // `String.prototype.includes(sub, position)` matches `sub` at `position`\n // OR LATER, so the pattern must allow at least `position` leading chars\n // (`{N,}`), not exactly `position` chars (`{N}`).\n const pattern = new RegExp(typeof def.position === \"number\" ? `^.{${def.position},}${escapedRegex}` : escapedRegex);\n def.pattern = pattern;\n inst._zod.check = (payload) => {\n if (payload.value.includes(def.includes, def.position))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"includes\",\n includes: def.includes,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckStartsWith = /*@__PURE__*/ core.$constructor(\"$ZodCheckStartsWith\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const pattern = new RegExp(`^${util.escapeRegex(def.prefix)}.*`);\n def.pattern ?? (def.pattern = pattern);\n inst._zod.check = (payload) => {\n if (payload.value.startsWith(def.prefix))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"starts_with\",\n prefix: def.prefix,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckEndsWith = /*@__PURE__*/ core.$constructor(\"$ZodCheckEndsWith\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const pattern = new RegExp(`.*${util.escapeRegex(def.suffix)}$`);\n def.pattern ?? (def.pattern = pattern);\n inst._zod.check = (payload) => {\n if (payload.value.endsWith(def.suffix))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"ends_with\",\n suffix: def.suffix,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\n///////////////////////////////////\n///// $ZodCheckProperty /////\n///////////////////////////////////\nfunction handleCheckPropertyResult(result, payload, property) {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(property, result.issues));\n }\n}\nexport const $ZodCheckProperty = /*@__PURE__*/ core.$constructor(\"$ZodCheckProperty\", (inst, def) => {\n $ZodCheck.init(inst, def);\n inst._zod.check = (payload) => {\n const result = def.schema._zod.run({\n value: payload.value[def.property],\n issues: [],\n }, {});\n if (result instanceof Promise) {\n return result.then((result) => handleCheckPropertyResult(result, payload, def.property));\n }\n handleCheckPropertyResult(result, payload, def.property);\n return;\n };\n});\nexport const $ZodCheckProperties = /*@__PURE__*/ core.$constructor(\"$ZodCheckProperties\", (inst, def) => {\n $ZodCheck.init(inst, def);\n util.hide(inst, Symbol.iterator, function* () {\n yield inst;\n });\n // key and schema snapshotted together: reading one live and the other cached lets a later mutation of the caller's shape object pair a stale key with a missing schema\n let entries;\n inst._zod.check = (payload) => {\n // the base schema already typed the value, so only a nullish one is rejected here: the properties read on a primitive too, matching z.property() on a string's length\n if (payload.value == null) {\n payload.issues.push({ expected: \"object\", code: \"invalid_type\", input: payload.value, inst });\n return undefined;\n }\n entries ?? (entries = Reflect.ownKeys(def.shape).map((key) => [key, def.shape[key]]));\n const input = payload.value;\n let proms;\n for (const [key, schema] of entries) {\n const result = schema._zod.run({ value: input[key], issues: [] }, {});\n if (result instanceof Promise) {\n proms ?? (proms = []);\n proms.push(result.then((result) => handleCheckPropertyResult(result, payload, key)));\n }\n else {\n handleCheckPropertyResult(result, payload, key);\n }\n }\n if (proms)\n return Promise.all(proms).then(() => undefined);\n return undefined;\n };\n});\nexport const $ZodCheckMimeType = /*@__PURE__*/ core.$constructor(\"$ZodCheckMimeType\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const mimeSet = new Set(def.mime);\n inst._zod.check = (payload) => {\n if (mimeSet.has(payload.value.type))\n return;\n payload.issues.push({\n code: \"invalid_value\",\n values: def.mime,\n input: payload.value.type,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckOverwrite = /*@__PURE__*/ core.$constructor(\"$ZodCheckOverwrite\", (inst, def) => {\n $ZodCheck.init(inst, def);\n inst._zod.check = (payload) => {\n payload.value = def.tx(payload.value);\n };\n});\n","export class Doc {\n constructor(args = [], closed = {}) {\n this.content = [];\n this.indent = 0;\n this.args = args;\n this.closed = closed;\n }\n // the compiler catches a child's throw and keeps writing into this doc, so the indent has to unwind with it\n indented(fn) {\n this.indent += 1;\n try {\n fn(this);\n }\n finally {\n this.indent -= 1;\n }\n }\n write(arg) {\n if (typeof arg === \"function\") {\n arg(this, { execution: \"sync\" });\n arg(this, { execution: \"async\" });\n return;\n }\n const content = arg;\n const lines = content.split(\"\\n\").filter((x) => x);\n const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length));\n const dedented = lines.map((x) => x.slice(minIndent)).map((x) => \" \".repeat(this.indent * 2) + x);\n for (const line of dedented) {\n this.content.push(line);\n }\n }\n compile() {\n const F = Function;\n const content = this?.content ?? [``];\n const factory = new F(...Object.keys(this.closed), `return function (${this.args.join(\", \")}) {\\n${content.join(\"\\n\")}\\n};`);\n return factory(...Object.values(this.closed));\n }\n}\n","export const version = {\n major: 4,\n minor: 6,\n patch: 6,\n};\n","import * as checks from \"./checks.js\";\nimport * as core from \"./core.js\";\nimport { Doc } from \"./doc.js\";\nimport { parse, parseAsync } from \"./parse.js\";\nimport * as regexes from \"./regexes.js\";\nimport * as util from \"./util.js\";\nimport { version } from \"./versions.js\";\nexport const $ZodType = /*@__PURE__*/ core.$constructor(\"$ZodType\", (inst, def) => {\n var _a;\n inst ?? (inst = {});\n inst._zod.def = def; // set _def property\n inst._zod.bag = inst._zod.bag || {}; // initialize _bag object\n inst._zod.version = version;\n const defChecks = inst._zod.def.checks;\n // if inst is itself a checks.$ZodCheck, run it as a check\n const checks = inst._zod.traits.has(\"$ZodCheck\")\n ? [inst, ...(defChecks ?? [])]\n : defChecks?.length\n ? [...defChecks]\n : [];\n for (const ch of checks) {\n for (const fn of ch._zod.onattach) {\n fn(inst);\n }\n }\n if (checks.length === 0) {\n // deferred initializer inst._zod.parse is not yet defined\n (_a = inst._zod).deferred ?? (_a.deferred = []);\n inst._zod.deferred?.push(() => {\n inst._zod.run = inst._zod.parse;\n });\n }\n else {\n const runChecks = (payload, checks, ctx) => {\n if (payload.memo)\n return payload;\n let isAborted = util.aborted(payload);\n let asyncResult;\n for (const ch of checks) {\n if (ch._zod.def.when) {\n if (util.explicitlyAborted(payload))\n continue;\n const shouldRun = ch._zod.def.when(payload);\n if (!shouldRun)\n continue;\n }\n else if (isAborted) {\n continue;\n }\n const currLen = payload.issues.length;\n const _ = ch._zod.check(payload);\n if (_ instanceof Promise && ctx?.async === false) {\n throw new core.$ZodAsyncError();\n }\n if (asyncResult || _ instanceof Promise) {\n asyncResult = (asyncResult ?? Promise.resolve()).then(async () => {\n await _;\n const nextLen = payload.issues.length;\n if (nextLen === currLen)\n return;\n util.attachSchema(payload.issues, currLen, inst);\n if (!isAborted)\n isAborted = util.aborted(payload, currLen);\n });\n }\n else {\n const nextLen = payload.issues.length;\n if (nextLen === currLen)\n continue;\n util.attachSchema(payload.issues, currLen, inst);\n if (!isAborted)\n isAborted = util.aborted(payload, currLen);\n }\n }\n if (asyncResult) {\n return asyncResult.then(() => {\n return payload;\n });\n }\n return payload;\n };\n const handleCanaryResult = (canary, payload, ctx) => {\n // abort if the canary is aborted\n if (util.aborted(canary)) {\n canary.aborted = true;\n return canary;\n }\n // run checks first, then\n const checkResult = runChecks(payload, checks, ctx);\n if (checkResult instanceof Promise) {\n if (ctx.async === false)\n throw new core.$ZodAsyncError();\n return checkResult.then((checkResult) => inst._zod.parse(checkResult, ctx));\n }\n return inst._zod.parse(checkResult, ctx);\n };\n inst._zod.run = (payload, ctx) => {\n if (ctx.skipChecks) {\n return inst._zod.parse(payload, ctx);\n }\n if (ctx.direction === \"backward\") {\n // run canary initial pass (no checks)\n const canary = inst._zod.parse({ value: payload.value, issues: [] }, { ...ctx, skipChecks: true });\n if (canary instanceof Promise) {\n return canary.then((canary) => {\n return handleCanaryResult(canary, payload, ctx);\n });\n }\n return handleCanaryResult(canary, payload, ctx);\n }\n // forward\n const result = inst._zod.parse(payload, ctx);\n if (result instanceof Promise) {\n if (ctx.async === false)\n throw new core.$ZodAsyncError();\n return result.then((result) => runChecks(result, checks, ctx));\n }\n return runChecks(result, checks, ctx);\n };\n }\n}, {\n // Wrappers extend this by installing a richer factory over it; reading it eagerly would defeat the laziness.\n get \"~standard\"() {\n return util.hide(this, \"~standard\", standardProps(this));\n },\n set \"~standard\"(value) {\n util.own(this, \"~standard\", value);\n },\n});\n/** The Standard Schema surface for `inst`. Shared so wrappers can extend it without forcing it. */\n// a Standard Schema result only reports issues, so a failure finalizes them straight off the raw payload: no ZodError, and no lazy result to read through\nconst toStandardResult = (r, ctx) => r.issues.length ? { issues: r.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())) } : { value: r.value };\nasync function validateAsync(inst, value) {\n const ctx = { async: true };\n return toStandardResult((await inst._zod.run({ value, issues: [] }, ctx)), ctx);\n}\nexport function standardProps(inst) {\n return {\n validate: (value) => {\n const ctx = { async: false };\n try {\n const r = inst._zod.run({ value, issues: [] }, ctx);\n if (!(r instanceof Promise))\n return toStandardResult(r, ctx);\n }\n catch (_) { }\n // async function so a synchronously throwing check rejects instead of escaping validate\n return validateAsync(inst, value);\n },\n vendor: \"zod\",\n version: 1,\n };\n}\nexport { clone } from \"./util.js\";\nexport const $ZodString = /*@__PURE__*/ core.$constructor(\"$ZodString\", (inst, def) => {\n $ZodType.init(inst, def);\n // a format's own pattern, else unbounded; a template literal derives the check-aware form itself\n inst._zod.pattern = def.pattern ?? regexes.anyString;\n inst._zod.parse = (payload, _) => {\n if (def.coerce)\n try {\n payload.value = String(payload.value);\n }\n catch (_) { }\n if (typeof payload.value === \"string\")\n return payload;\n payload.issues.push({\n expected: \"string\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodStringFormat\", (inst, def) => {\n // check initialization must come first\n checks.$ZodCheckStringFormat.init(inst, def);\n $ZodString.init(inst, def);\n});\nexport const $ZodGUID = /*@__PURE__*/ core.$constructor(\"$ZodGUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.guid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodUUID = /*@__PURE__*/ core.$constructor(\"$ZodUUID\", (inst, def) => {\n if (def.version) {\n const versionMap = {\n v1: 1,\n v2: 2,\n v3: 3,\n v4: 4,\n v5: 5,\n v6: 6,\n v7: 7,\n v8: 8,\n };\n const v = versionMap[def.version];\n if (v === undefined)\n throw new Error(`Invalid UUID version: \"${def.version}\"`);\n def.pattern ?? (def.pattern = regexes.uuid(v));\n }\n else\n def.pattern ?? (def.pattern = regexes.uuid());\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodEmail = /*@__PURE__*/ core.$constructor(\"$ZodEmail\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.email);\n $ZodStringFormat.init(inst, def);\n});\n/** The `://` guard rejected the input before the URL constructor saw it. */\nexport const URL_BAD_FORMAT = 1;\n/** The URL parser rejected the input. */\nexport const URL_UNPARSEABLE = 2;\nexport function canParseURL(input) {\n try {\n if (typeof URL !== \"undefined\" && typeof URL.canParse === \"function\")\n return URL.canParse(input);\n new URL(input);\n return true;\n }\n catch {\n return false;\n }\n}\nexport function validateURL(trimmed, def) {\n if (!(\"normalize\" in def) && !(\"hostname\" in def) && !(\"protocol\" in def)) {\n return canParseURL(trimmed) || URL_UNPARSEABLE;\n }\n return parseURLObject(trimmed, def);\n}\n/** Parses a URL while preserving the non-normalizing HTTP guard. */\nexport function parseURLObject(trimmed, def) {\n // When normalize is off, require :// for http/https URLs. This prevents strings like \"http:example.com\" or \"https:/path\" from being silently accepted\n if (!def.normalize && def.protocol?.source === regexes.httpProtocol.source && !/^https?:\\/\\//i.test(trimmed)) {\n return URL_BAD_FORMAT;\n }\n try {\n if (typeof URL !== \"undefined\") {\n const URLStatic = URL;\n if (typeof URLStatic.parse === \"function\")\n return URLStatic.parse(trimmed) ?? URL_UNPARSEABLE;\n }\n // @ts-ignore\n return new URL(trimmed);\n }\n catch {\n return URL_UNPARSEABLE;\n }\n}\nconst asciiTabOrNewline = /[\\t\\n\\r]/g;\n/** The URL parser deletes every ASCII tab, LF and CR from its input before it parses, so `new URL(\"https://exa\\nmple.com\")` reports on `example.com`. Applying the same deletion to the returned value closes the half of that divergence which can move the host; the parser's other rewrite, stripping C0 controls at the edges, cannot. */\nexport function stripTabAndNewline(value) {\n return value.replace(asciiTabOrNewline, \"\");\n}\nexport function urlHostnameOk(url, hostname) {\n hostname.lastIndex = 0;\n return hostname.test(url.hostname);\n}\nexport function urlProtocolOk(url, protocol) {\n protocol.lastIndex = 0;\n return protocol.test(url.protocol.endsWith(\":\") ? url.protocol.slice(0, -1) : url.protocol);\n}\nexport const $ZodURL = /*@__PURE__*/ core.$constructor(\"$ZodURL\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n try {\n // Trim whitespace from input\n const trimmed = payload.value.trim();\n const url = validateURL(trimmed, def);\n if (url === URL_BAD_FORMAT) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n note: \"Invalid URL format\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n return;\n }\n if (url === URL_UNPARSEABLE) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n return;\n }\n if (url === true) {\n payload.value = stripTabAndNewline(trimmed);\n return;\n }\n if (def.hostname && !urlHostnameOk(url, def.hostname)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n note: \"Invalid hostname\",\n pattern: def.hostname.source,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n if (def.protocol && !urlProtocolOk(url, def.protocol)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n note: \"Invalid protocol\",\n pattern: def.protocol.source,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n // Set the output value based on normalize flag\n payload.value = def.normalize ? url.href : stripTabAndNewline(trimmed);\n return;\n }\n catch (_) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodEmoji = /*@__PURE__*/ core.$constructor(\"$ZodEmoji\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.emoji());\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodNanoID = /*@__PURE__*/ core.$constructor(\"$ZodNanoID\", (inst, def) => {\n if (def.length !== undefined && (!Number.isInteger(def.length) || def.length < 1))\n throw new Error(`Invalid nanoid length: ${def.length}`);\n def.pattern ?? (def.pattern = def.length === undefined ? regexes.nanoid : regexes.nanoidOfLength(def.length));\n $ZodStringFormat.init(inst, def);\n});\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link $ZodCUID2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport const $ZodCUID = /*@__PURE__*/ core.$constructor(\"$ZodCUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cuid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodCUID2 = /*@__PURE__*/ core.$constructor(\"$ZodCUID2\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cuid2);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodULID = /*@__PURE__*/ core.$constructor(\"$ZodULID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ulid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodXID = /*@__PURE__*/ core.$constructor(\"$ZodXID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.xid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodKSUID = /*@__PURE__*/ core.$constructor(\"$ZodKSUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ksuid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODateTime = /*@__PURE__*/ core.$constructor(\"$ZodISODateTime\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.datetime(def));\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODate = /*@__PURE__*/ core.$constructor(\"$ZodISODate\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.date);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISOTime = /*@__PURE__*/ core.$constructor(\"$ZodISOTime\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.time(def));\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODuration = /*@__PURE__*/ core.$constructor(\"$ZodISODuration\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.duration);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodIPv4 = /*@__PURE__*/ core.$constructor(\"$ZodIPv4\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ipv4);\n $ZodStringFormat.init(inst, def);\n});\n/** An IPv6 address is written with hex digits, colons and dots, and nothing else. The guard is what makes the check below an IPv6 check: `new URL(\"http://[...]\")` parses an authority, not an address, so `@` and `\\` re-delimit it and `\"::@1\\\\\"` validates against the host `0.0.0.1`. The URL parser also deletes ASCII tab, LF and CR rather than failing, which is how `\"::1\\n\"` validated as `::1`. */\nconst ipv6Alphabet = /^[0-9a-fA-F:.]+$/;\nexport function isValidIPv6(value) {\n if (!ipv6Alphabet.test(value))\n return false;\n return canParseURL(`http://[${value}]`);\n}\nexport const $ZodIPv6 = /*@__PURE__*/ core.$constructor(\"$ZodIPv6\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ipv6);\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (!isValidIPv6(payload.value)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"ipv6\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodMAC = /*@__PURE__*/ core.$constructor(\"$ZodMAC\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.mac(def.delimiter));\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodCIDRv4 = /*@__PURE__*/ core.$constructor(\"$ZodCIDRv4\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cidrv4);\n $ZodStringFormat.init(inst, def);\n});\nexport function isValidCIDRv6(value) {\n const parts = value.split(\"/\");\n if (parts.length !== 2)\n return false;\n const [address, prefix] = parts;\n if (!prefix)\n return false;\n const prefixNum = Number(prefix);\n if (`${prefixNum}` !== prefix)\n return false;\n if (prefixNum < 0 || prefixNum > 128)\n return false;\n return isValidIPv6(address);\n}\nexport const $ZodCIDRv6 = /*@__PURE__*/ core.$constructor(\"$ZodCIDRv6\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cidrv6); // not used for validation\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (!isValidCIDRv6(payload.value)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"cidrv6\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\n////////////////////////////// ZodBase64 //////////////////////////////\nexport function isValidBase64(data) {\n if (data === \"\")\n return true;\n // atob ignores whitespace, so reject it up front.\n if (/\\s/.test(data))\n return false;\n if (data.length % 4 !== 0)\n return false;\n try {\n // @ts-ignore\n atob(data);\n return true;\n }\n catch {\n return false;\n }\n}\n// lax on purpose: the quantified regexes.base64 overflows the regex stack on multi-MB input and its leading ^$| alternation leaks through template-literal composition; isValidBase64 enforces length and padding\nexport const base64Charset = /^[0-9a-zA-Z+/]*={0,2}$/;\nexport const $ZodBase64 = /*@__PURE__*/ core.$constructor(\"$ZodBase64\", (inst, def) => {\n def.pattern ?? (def.pattern = base64Charset);\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (isValidBase64(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"base64\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\n////////////////////////////// ZodBase64URL //////////////////////////////\n// lax on purpose: the quantified regexes.base64url overflows the regex stack on multi-MB input; isValidBase64 enforces length on the padded string\nexport const base64urlCharset = /^[A-Za-z0-9_-]*$/;\nexport function isValidBase64URL(data) {\n if (!base64urlCharset.test(data))\n return false;\n const base64 = data.replace(/[-_]/g, (c) => (c === \"-\" ? \"+\" : \"/\"));\n const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, \"=\");\n return isValidBase64(padded);\n}\nexport const $ZodBase64URL = /*@__PURE__*/ core.$constructor(\"$ZodBase64URL\", (inst, def) => {\n def.pattern ?? (def.pattern = base64urlCharset);\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (isValidBase64URL(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"base64url\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodE164 = /*@__PURE__*/ core.$constructor(\"$ZodE164\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.e164);\n $ZodStringFormat.init(inst, def);\n});\n////////////////////////////// ZodCreditCard //////////////////////////////\nconst CC_SANITIZE = /[- ]/g;\n/** Luhn checksum on a digit-only string. Adapted from valibot (MIT). */\nfunction isLuhnAlgo(digits) {\n let length = digits.length;\n let bit = 1;\n let sum = 0;\n while (length) {\n const value = digits.charCodeAt(--length) - 48;\n bit ^= 1;\n sum += bit ? [0, 2, 4, 6, 8, 1, 3, 5, 7, 9][value] : value;\n }\n return sum % 10 === 0;\n}\nexport function isValidCreditCard(input) {\n if (!regexes.creditCard.test(input))\n return false;\n return isLuhnAlgo(input.replace(CC_SANITIZE, \"\"));\n}\nexport const $ZodCreditCard = /*@__PURE__*/ core.$constructor(\"$ZodCreditCard\", (inst, def) => {\n // Shape only — the Luhn check below is not expressible as a pattern, so consumers of `pattern` (JSON Schema, template literals) get the length and separator rules alone.\n def.pattern ?? (def.pattern = regexes.creditCard);\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (isValidCreditCard(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"credit_card\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\n////////////////////////////// ZodIBAN //////////////////////////////\n// iso 7064 mod 97-10 checksum without BigInt\nfunction isIso7064Mod97(iban) {\n let remainder = 0;\n const len = iban.length;\n for (let i = 4; i < len; i++) {\n const code = iban.charCodeAt(i);\n remainder = (code >= 65 ? remainder * 100 + (code - 55) : remainder * 10 + (code - 48)) % 97;\n }\n for (let i = 0; i < 4; i++) {\n const code = iban.charCodeAt(i);\n remainder = (code >= 65 ? remainder * 100 + (code - 55) : remainder * 10 + (code - 48)) % 97;\n }\n return remainder === 1;\n}\nexport function isValidIBAN(input) {\n if (!regexes.iban.test(input))\n return false;\n return isIso7064Mod97(input);\n}\nexport const $ZodIBAN = /*@__PURE__*/ core.$constructor(\"$ZodIBAN\", (inst, def) => {\n // shape only — checksum is not expressible as a pattern\n def.pattern ?? (def.pattern = regexes.iban);\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (isValidIBAN(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"iban\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\n////////////////////////////// ZodJWT //////////////////////////////\nexport function isValidJWT(token, algorithm = null) {\n try {\n const tokensParts = token.split(\".\");\n if (tokensParts.length !== 3)\n return false;\n const [header] = tokensParts;\n if (!header)\n return false;\n // @ts-ignore\n const parsedHeader = JSON.parse(atob(header));\n if (\"typ\" in parsedHeader && parsedHeader?.typ !== \"JWT\")\n return false;\n if (!parsedHeader.alg)\n return false;\n if (algorithm && (!(\"alg\" in parsedHeader) || parsedHeader.alg !== algorithm))\n return false;\n return true;\n }\n catch {\n return false;\n }\n}\nexport const $ZodJWT = /*@__PURE__*/ core.$constructor(\"$ZodJWT\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (isValidJWT(payload.value, def.alg))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"jwt\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCustomStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodCustomStringFormat\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (def.fn(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: def.format,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodNumber = /*@__PURE__*/ core.$constructor(\"$ZodNumber\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.number;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = Number(payload.value);\n }\n catch (_) { }\n const input = payload.value;\n if (typeof input === \"number\" && !Number.isNaN(input) && Number.isFinite(input)) {\n return payload;\n }\n const received = typeof input === \"number\"\n ? Number.isNaN(input)\n ? \"NaN\"\n : !Number.isFinite(input)\n ? String(input)\n : undefined\n : undefined;\n payload.issues.push({\n expected: \"number\",\n code: \"invalid_type\",\n input,\n inst,\n ...(received ? { received } : {}),\n });\n return payload;\n };\n});\nexport const $ZodNumberFormat = /*@__PURE__*/ core.$constructor(\"$ZodNumberFormat\", (inst, def) => {\n checks.$ZodCheckNumberFormat.init(inst, def);\n $ZodNumber.init(inst, def); // no format checks\n});\nexport const $ZodBoolean = /*@__PURE__*/ core.$constructor(\"$ZodBoolean\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.boolean;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = Boolean(payload.value);\n }\n catch (_) { }\n const input = payload.value;\n if (typeof input === \"boolean\")\n return payload;\n payload.issues.push({\n expected: \"boolean\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodBigInt = /*@__PURE__*/ core.$constructor(\"$ZodBigInt\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.bigint;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = BigInt(payload.value);\n }\n catch (_) { }\n if (typeof payload.value === \"bigint\")\n return payload;\n payload.issues.push({\n expected: \"bigint\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodBigIntFormat = /*@__PURE__*/ core.$constructor(\"$ZodBigIntFormat\", (inst, def) => {\n checks.$ZodCheckBigIntFormat.init(inst, def);\n $ZodBigInt.init(inst, def); // no format checks\n});\nexport const $ZodSymbol = /*@__PURE__*/ core.$constructor(\"$ZodSymbol\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"symbol\")\n return payload;\n payload.issues.push({\n expected: \"symbol\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodUndefined = /*@__PURE__*/ core.$constructor(\"$ZodUndefined\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.undefined;\n inst._zod.values = new Set([undefined]);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"undefined\")\n return payload;\n payload.issues.push({\n expected: \"undefined\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodNull = /*@__PURE__*/ core.$constructor(\"$ZodNull\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.null;\n inst._zod.values = new Set([null]);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (input === null)\n return payload;\n payload.issues.push({\n expected: \"null\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodAny = /*@__PURE__*/ core.$constructor(\"$ZodAny\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload) => payload;\n});\nexport const $ZodUnknown = /*@__PURE__*/ core.$constructor(\"$ZodUnknown\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload) => payload;\n});\nexport const $ZodNever = /*@__PURE__*/ core.$constructor(\"$ZodNever\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n payload.issues.push({\n expected: \"never\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodVoid = /*@__PURE__*/ core.$constructor(\"$ZodVoid\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"undefined\")\n return payload;\n payload.issues.push({\n expected: \"void\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodDate = /*@__PURE__*/ core.$constructor(\"$ZodDate\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce) {\n try {\n payload.value = new Date(payload.value);\n }\n catch (_err) { }\n }\n const input = payload.value;\n const isDate = input instanceof Date;\n const isValidDate = isDate && !Number.isNaN(input.getTime());\n if (isValidDate)\n return payload;\n payload.issues.push({\n expected: \"date\",\n code: \"invalid_type\",\n input,\n ...(isDate ? { received: \"Invalid Date\" } : {}),\n inst,\n });\n return payload;\n };\n});\n// an oversized container fails its leading size checks before any element is parsed\nfunction capSize(inst, size) {\n const caps = util.sizeCaps(inst._zod.def.checks);\n if (!caps.length)\n return;\n const cap = Math.min(...caps.map((c) => c[0]));\n const parse = inst._zod.parse;\n inst._zod.parse = (payload, ctx) => {\n const n = size(payload.value);\n if (n > cap && !ctx?.skipChecks && ctx?.direction !== \"backward\") {\n for (const [max, ch] of util.sizeCaps(inst._zod.def.checks)) {\n if (n > max && ch._zod.def.when(payload)) {\n const start = payload.issues.length;\n ch._zod.check(payload);\n // the value is still the raw input, so no later check may read it\n payload.issues[start].continue = false;\n util.attachSchema(payload.issues, start, inst);\n return payload;\n }\n }\n }\n return parse(payload, ctx);\n };\n}\nconst arraySize = (input) => (Array.isArray(input) ? input.length : -1);\nconst mapSize = (input) => (input instanceof Map ? input.size : -1);\nconst setSize = (input) => (input instanceof Set ? input.size : -1);\nfunction handleArrayResult(result, final, index) {\n if (result.issues.length) {\n final.issues.push(...util.prefixIssues(index, result.issues));\n }\n final.value[index] = result.value;\n}\nexport const $ZodArray = /*@__PURE__*/ core.$constructor(\"$ZodArray\", (inst, def) => {\n $ZodType.init(inst, def);\n const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!Array.isArray(input)) {\n payload.issues.push({\n expected: \"array\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n payload.value = memo ? memo.alloc(inst, payload, Array(input.length), ctx) : Array(input.length);\n const proms = [];\n const abortEarly = ctx?.abortEarly;\n for (let i = 0; i < input.length; i++) {\n const item = input[i];\n const result = def.element._zod.run({\n value: item,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => handleArrayResult(result, payload, i)));\n }\n else {\n handleArrayResult(result, payload, i);\n // the element's payload is authoritative here, since handleArrayResult forwards every issue; an object's is not, because it drops a failed absent optional\n if (abortEarly && result.issues.length !== 0 && util.aborted(result))\n break;\n }\n }\n if (proms.length) {\n return Promise.all(proms).then(() => payload);\n }\n return payload; //handleArrayResultsAsync(parseResults, final);\n };\n capSize(inst, arraySize);\n});\nfunction handlePropertyResult(result, final, key, input, optin, optout) {\n const isPresent = key in input;\n const isOptionalOut = optout === \"optional\";\n // The middle rung means \"absence permitted, nothing supplied in its place\", so an absent key contributes nothing — whatever the schema made of `undefined` is invented, not substituted. Only `optional` reaches this with a value: `defaulted` substitutes, and a schema that isn't optional-out has to keep the key.\n if (!isPresent && isOptionalOut && optin === \"optional\") {\n return;\n }\n if (result.issues.length) {\n // For optional-in/out schemas, ignore errors on absent keys.\n if (optin !== undefined && isOptionalOut && !isPresent) {\n return;\n }\n final.issues.push(...util.prefixIssues(key, result.issues));\n }\n if (!isPresent && optin === undefined) {\n if (!result.issues.length) {\n final.issues.push({\n code: \"invalid_type\",\n expected: \"nonoptional\",\n input: undefined,\n path: [key],\n });\n }\n return;\n }\n if (result.value === undefined) {\n if (isPresent || (optin === \"defaulted\" && !isOptionalOut)) {\n final.value[key] = undefined;\n }\n }\n else {\n final.value[key] = result.value;\n }\n}\n// one shared instance; a fresh [] per schema cost 56 bytes retained\nconst NO_SYMBOL_KEYS = [];\nfunction normalizeDef(def) {\n const keys = Object.keys(def.shape);\n const ownSymbols = Object.getOwnPropertySymbols(def.shape);\n const symbolKeys = ownSymbols.length ? ownSymbols : NO_SYMBOL_KEYS;\n // aliases `keys` when there are no symbols, so a string-only shape keeps one array\n const allKeys = symbolKeys.length ? [...keys, ...symbolKeys] : keys;\n for (const k of allKeys) {\n if (!def.shape?.[k]?._zod?.traits?.has(\"$ZodType\")) {\n throw new Error(`Invalid element at key \"${String(k)}\": expected a Zod schema`);\n }\n }\n const okeys = util.optionalKeys(def.shape);\n return {\n ...def,\n allKeys,\n symbolKeys,\n // string-only: handleCatchall matches it against `for...in`, which never yields a symbol\n keySet: new Set(keys),\n numKeys: keys.length,\n optionalKeys: new Set(okeys),\n };\n}\nfunction handleCatchall(proms, input, payload, ctx, def, inst, abortEarly) {\n const unrecognized = [];\n const keySet = def.keySet;\n const _catchall = def.catchall._zod;\n const t = _catchall.def.type;\n const optin = _catchall.optin;\n const optout = _catchall.optout;\n // starts at 0, not the current length: the shape phase already ran and may have aborted\n let seen = 0;\n for (const key in input) {\n if (abortEarly && payload.issues.length !== seen) {\n if (util.aborted(payload, seen))\n break;\n seen = payload.issues.length;\n }\n // Must precede the __proto__ branch: a declared key is not unrecognized, even though the shape loop deliberately strips __proto__ from the parsed output.\n if (keySet.has(key))\n continue;\n // Don't copy an undeclared __proto__ into the result; assignment to a plain {} would replace the result prototype. But in strict mode it is still an unknown key, so report it before skipping.\n if (key === \"__proto__\") {\n if (t === \"never\")\n unrecognized.push(key);\n continue;\n }\n if (t === \"never\") {\n unrecognized.push(key);\n continue;\n }\n const r = _catchall.run({ value: input[key], issues: [] }, ctx);\n if (r instanceof Promise) {\n proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, optin, optout)));\n }\n else {\n handlePropertyResult(r, payload, key, input, optin, optout);\n }\n }\n if (unrecognized.length) {\n payload.issues.push({\n code: \"unrecognized_keys\",\n keys: unrecognized,\n input,\n inst,\n // Describes the shape of the input, not the validity of the parsed value, so it never aborts. The parse still fails; the schema's own checks just get to run first, and an enclosing intersection can reconcile the key against a sibling operand.\n continue: true,\n });\n }\n if (!proms.length)\n return payload;\n return Promise.all(proms).then(() => {\n return payload;\n });\n}\nexport const $ZodObject = /*@__PURE__*/ core.$constructor(\"$ZodObject\", (inst, def) => {\n // requires cast because technically $ZodObject doesn't extend\n $ZodType.init(inst, def);\n const desc = Object.getOwnPropertyDescriptor(def, \"shape\");\n // a cloned def carries its source's accessor, which knows the shape it answers from; adopting that keeps the clone's keys readable without running it\n const sh = desc?.get ? desc.get.raw : (def.shape ?? {});\n if (sh) {\n // Freezes the shape on first read, so its getters resolve once and every later read sees the same schemas.\n const get = () => {\n const newSh = { ...sh };\n Object.defineProperty(def, \"shape\", { value: newSh });\n get.raw = newSh;\n return newSh;\n };\n get.raw = sh;\n Object.defineProperty(def, \"shape\", { get });\n }\n const _normalized = util.cached(() => normalizeDef(def));\n util.defineLazyInternal(inst, \"propValues\", (zod) => {\n const shape = zod.def.shape;\n const propValues = {};\n for (const key in shape) {\n const field = shape[key]._zod;\n if (field.values) {\n if (!Object.prototype.hasOwnProperty.call(propValues, key)) {\n util.assignProp(propValues, key, new Set());\n }\n for (const v of field.values)\n propValues[key].add(v);\n // An omittable slot reads back as undefined at a discriminator lookup, so it has to claim undefined: two options that can both omit the key are not discriminable on it.\n if (field.optin !== undefined)\n propValues[key].add(undefined);\n }\n }\n return propValues;\n });\n const isObject = util.isObject;\n const catchall = def.catchall;\n let value;\n const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\n inst._zod.parse = (payload, ctx) => {\n value ?? (value = _normalized.value);\n const input = payload.value;\n if (!isObject(input)) {\n payload.issues.push({\n expected: \"object\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {};\n const proms = [];\n const shape = value.shape;\n const abortEarly = ctx?.abortEarly;\n let seen = payload.issues.length;\n for (const key of value.allKeys) {\n if (abortEarly && payload.issues.length !== seen) {\n if (util.aborted(payload, seen))\n break;\n seen = payload.issues.length;\n }\n if (key === \"__proto__\")\n continue;\n const el = shape[key];\n const optin = el._zod.optin;\n const optout = el._zod.optout;\n const r = el._zod.run({ value: input[key], issues: [] }, ctx);\n if (r instanceof Promise) {\n proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, optin, optout)));\n }\n else {\n handlePropertyResult(r, payload, key, input, optin, optout);\n }\n }\n if (!catchall) {\n return proms.length ? Promise.all(proms).then(() => payload) : payload;\n }\n return handleCatchall(proms, input, payload, ctx, _normalized.value, inst, abortEarly === true);\n };\n});\nexport const $ZodObjectJIT = /*@__PURE__*/ core.$constructor(\"$ZodObjectJIT\", (inst, def) => {\n // requires cast because technically $ZodObject doesn't extend\n $ZodObject.init(inst, def);\n const superParse = inst._zod.parse;\n const _normalized = util.cached(() => normalizeDef(def));\n const memo = core.globalConfig.memoizer;\n const generateFastpass = (shape) => {\n const normalized = _normalized.value;\n const syms = normalized.symbolKeys;\n // a symbol has no source literal, so it is read as `syms[i]` off the closed-over scope\n const doc = new Doc([\"payload\", \"ctx\"], { shape, inst, memo, syms });\n const parseStr = (k) => `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;\n // prefixes in place, like util.prefixIssues. newResult must land before the early return: a catchall runs after this and would otherwise write onto the caller's input\n const prefixStr = (id, k) => `\n let ${id}_ab = false;\n for (let i = 0; i < ${id}.issues.length; i++) {\n const iss = ${id}.issues[i];\n iss.path = iss.path ? [${k}, ...iss.path] : [${k}];\n payload.issues.push(iss);\n if (iss.continue !== true) ${id}_ab = true;\n }\n if (${id}_ab && ctx && ctx.abortEarly) {\n payload.value = newResult;\n return payload;\n }`;\n doc.write(`const input = payload.value;`);\n const ids = Object.create(null);\n let counter = 0;\n for (const key of normalized.allKeys) {\n ids[key] = `key_${counter++}`;\n }\n // A: preserve key order {\n doc.write(memo ? `const newResult = memo.alloc(inst, payload, {}, ctx);` : `const newResult = {};`);\n for (const key of normalized.allKeys) {\n if (key === \"__proto__\")\n continue;\n const id = ids[key];\n const k = typeof key === \"symbol\" ? `syms[${syms.indexOf(key)}]` : util.esc(key);\n const isPresent = `${k} in input`;\n const schema = shape[key];\n const optin = schema?._zod?.optin;\n const isOptionalIn = optin !== undefined;\n const isOptionalOut = schema?._zod?.optout === \"optional\";\n doc.write(`const ${id} = ${parseStr(k)};`);\n if (isOptionalIn && isOptionalOut) {\n // For optional-in/out schemas, ignore errors on absent keys — and, like the interpreted path, drop the value produced alongside them. The middle rung goes further: it permits absence without supplying anything in its place, so an absent key contributes nothing at all.\n const assign = optin === \"optional\" ? `${id}_present` : `${id}.value !== undefined || ${id}_present`;\n doc.write(`\n const ${id}_present = ${isPresent};\n if (!${id}.issues.length || ${id}_present) {\n if (${id}.issues.length) {${prefixStr(id, k)}\n }\n\n if (${assign}) {\n newResult[${k}] = ${id}.value;\n }\n }\n\n `);\n }\n else if (!isOptionalIn) {\n doc.write(`\n const ${id}_present = ${isPresent};\n if (${id}.issues.length) {${prefixStr(id, k)}\n }\n if (!${id}_present && !${id}.issues.length) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"nonoptional\",\n input: undefined,\n path: [${k}]\n });\n if (ctx && ctx.abortEarly) {\n payload.value = newResult;\n return payload;\n }\n }\n\n if (${id}_present) {\n newResult[${k}] = ${id}.value;\n }\n\n `);\n }\n else {\n doc.write(`\n if (${id}.issues.length) {${prefixStr(id, k)}\n }\n `);\n if (optin === \"defaulted\") {\n doc.write(`newResult[${k}] = ${id}.value;`);\n }\n else {\n doc.write(`\n if (${id}.value !== undefined || ${isPresent}) {\n newResult[${k}] = ${id}.value;\n }\n `);\n }\n }\n }\n doc.write(`payload.value = newResult;`);\n doc.write(`return payload;`);\n // closing `shape` in is what pays: turbofan specializes the parser against that one shape object, so every `shape[k]._zod.run` folds to a known callee. as a parameter it stays a generic load and measures 13% slower even with the forwarding frame gone\n return doc.compile();\n };\n let fastpass;\n const isObject = util.isObject;\n const jit = !core.globalConfig.jitless;\n const allowsEval = util.allowsEval;\n const fastEnabled = jit && allowsEval.value; // && !def.catchall;\n const catchall = def.catchall;\n let value;\n inst._zod.parse = (payload, ctx) => {\n value ?? (value = _normalized.value);\n const input = payload.value;\n if (!isObject(input)) {\n payload.issues.push({\n expected: \"object\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) {\n // always synchronous\n if (!fastpass)\n fastpass = generateFastpass(def.shape);\n payload = fastpass(payload, ctx);\n if (!catchall)\n return payload;\n return handleCatchall([], input, payload, ctx, value, inst, ctx?.abortEarly === true);\n }\n return superParse(payload, ctx);\n };\n});\nfunction handleUnionResults(results, final, inst, ctx) {\n for (const result of results) {\n if (result.issues.length === 0) {\n final.value = result.value;\n return final;\n }\n }\n const nonaborted = results.filter((r) => !util.aborted(r));\n if (nonaborted.length === 1) {\n final.value = nonaborted[0].value;\n return nonaborted[0];\n }\n final.issues.push({\n code: \"invalid_union\",\n input: final.value,\n inst,\n errors: results.map((result) => result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n });\n return final;\n}\nexport const $ZodUnion = /*@__PURE__*/ core.$constructor(\"$ZodUnion\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.options.some((o) => o._zod.optin === \"defaulted\")\n ? \"defaulted\"\n : zod.def.options.some((o) => o._zod.optin !== undefined)\n ? \"optional\"\n : undefined);\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.options.some((o) => o._zod.optout === \"optional\") ? \"optional\" : undefined);\n util.defineLazyInternal(inst, \"values\", (zod) => {\n if (zod.def.options.every((o) => o._zod.values)) {\n return new Set(zod.def.options.flatMap((option) => Array.from(option._zod.values)));\n }\n return undefined;\n });\n util.defineLazyInternal(inst, \"pattern\", (zod) => {\n if (zod.def.options.every((o) => o._zod.pattern)) {\n const patterns = zod.def.options.map((o) => o._zod.pattern);\n return new RegExp(`^(${patterns.map((p) => util.cleanRegex(p.source)).join(\"|\")})$`);\n }\n return undefined;\n });\n const first = def.options.length === 1 ? def.options[0]._zod.run : null;\n inst._zod.parse = (payload, ctx) => {\n if (first) {\n return first(payload, ctx);\n }\n let async = false;\n const results = [];\n for (const option of def.options) {\n const result = option._zod.run({\n value: payload.value,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n results.push(result);\n async = true;\n }\n else {\n if (result.issues.length === 0)\n return result;\n results.push(result);\n }\n }\n if (!async)\n return handleUnionResults(results, payload, inst, ctx);\n return Promise.all(results).then((results) => {\n return handleUnionResults(results, payload, inst, ctx);\n });\n };\n});\nfunction handleExclusiveUnionResults(results, final, inst, ctx) {\n const matches = [];\n for (let i = 0; i < results.length; i++) {\n if (results[i].issues.length === 0)\n matches.push(i);\n }\n if (matches.length === 1) {\n final.value = results[matches[0]].value;\n return final;\n }\n if (matches.length === 0) {\n // No matches - same as regular union\n final.issues.push({\n code: \"invalid_union\",\n input: final.value,\n inst,\n errors: results.map((result) => result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n });\n }\n else {\n // Multiple matches - exclusive union failure\n final.issues.push({\n code: \"invalid_union\",\n input: final.value,\n inst,\n errors: [],\n inclusive: false,\n matches,\n });\n }\n return final;\n}\nexport const $ZodXor = /*@__PURE__*/ core.$constructor(\"$ZodXor\", (inst, def) => {\n $ZodUnion.init(inst, def);\n def.inclusive = false;\n const first = def.options.length === 1 ? def.options[0]._zod.run : null;\n inst._zod.parse = (payload, ctx) => {\n if (first) {\n return first(payload, ctx);\n }\n let async = false;\n const results = [];\n for (const option of def.options) {\n const result = option._zod.run({\n value: payload.value,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n results.push(result);\n async = true;\n }\n else {\n results.push(result);\n }\n }\n if (!async)\n return handleExclusiveUnionResults(results, payload, inst, ctx);\n return Promise.all(results).then((results) => {\n return handleExclusiveUnionResults(results, payload, inst, ctx);\n });\n };\n});\n/** Returns the option whose discriminator claims `value`, or throws if ambiguous. */\nexport function getDiscriminatedOption(union, value) {\n const internals = union._zod;\n let map = internals.bag.optionsMap;\n if (!map) {\n map = discriminatorMap(internals.def);\n internals.bag.optionsMap = map;\n }\n const option = map.get(value);\n if (option === null)\n throw new Error(`Ambiguous discriminator value \"${String(value)}\"`);\n return option;\n}\nfunction discriminatorMap(def) {\n const map = new Map();\n for (const option of def.options) {\n const values = option._zod.propValues?.[def.discriminator];\n if (!values || values.size === 0)\n throw new Error(`Invalid discriminated union option at index \"${def.options.indexOf(option)}\"`);\n for (const value of values) {\n if (map.has(value)) {\n if (value !== undefined)\n throw new Error(`Duplicate discriminator value \"${String(value)}\"`);\n // keep the collision marked so a later member cannot reclaim it\n map.set(value, null);\n }\n else {\n map.set(value, option);\n }\n }\n }\n return map;\n}\nexport const $ZodDiscriminatedUnion = \n/*@__PURE__*/\ncore.$constructor(\"$ZodDiscriminatedUnion\", (inst, def) => {\n def.inclusive = false;\n $ZodUnion.init(inst, def);\n const _super = inst._zod.parse;\n util.defineLazyInternal(inst, \"propValues\", (zod) => {\n const propValues = {};\n let undefinedCount = 0;\n for (const option of zod.def.options) {\n const pv = option._zod.propValues;\n if (!pv || Object.keys(pv).length === 0)\n throw new Error(`Invalid discriminated union option at index \"${zod.def.options.indexOf(option)}\"`);\n if (pv[zod.def.discriminator]?.has(undefined))\n undefinedCount++;\n for (const [k, v] of Object.entries(pv)) {\n if (!Object.prototype.hasOwnProperty.call(propValues, k)) {\n util.assignProp(propValues, k, new Set());\n }\n for (const val of v) {\n propValues[k].add(val);\n }\n }\n }\n if (!zod.def.unionFallback && undefinedCount > 1)\n propValues[zod.def.discriminator]?.delete(undefined);\n return propValues;\n });\n // Checked now rather than in the lookup map below, so an option that lacks the discriminator fails at the `discriminatedUnion` call instead of on the first object parsed. Options whose shape cannot be enumerated without resolving it — pipes and lazies — are left to the map.\n def.options.forEach((option, i) => {\n const propShape = util.rawShape(option._zod.def);\n if (propShape && !Object.prototype.hasOwnProperty.call(propShape, def.discriminator)) {\n throw new Error(`Invalid discriminated union option at index \"${i}\"`);\n }\n });\n const disc = util.cached(() => discriminatorMap(def));\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!util.isObject(input)) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"object\",\n input,\n inst,\n });\n return payload;\n }\n const value = input?.[def.discriminator];\n const opt = disc.value.get(value);\n // forward metadata cannot choose an encoder for an absent tag\n if (opt && (value !== undefined || ctx.direction !== \"backward\")) {\n return opt._zod.run(payload, ctx);\n }\n // Fall back to union matching when the fast discriminator path fails:\n // - explicitly enabled via unionFallback, or\n // - during backward direction (encode), since codec-based discriminators have different values in forward vs backward directions\n if (def.unionFallback || ctx.direction === \"backward\") {\n return _super(payload, ctx);\n }\n // no matching discriminator\n payload.issues.push({\n code: \"invalid_union\",\n errors: [],\n note: \"No matching discriminator\",\n discriminator: def.discriminator,\n options: Array.from(disc.value.keys()).filter((value) => disc.value.get(value) !== null),\n input,\n path: [def.discriminator],\n inst,\n });\n return payload;\n };\n});\nexport const $ZodIntersection = /*@__PURE__*/ core.$constructor(\"$ZodIntersection\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n const left = def.left._zod.run({ value: input, issues: [] }, ctx);\n const right = def.right._zod.run({ value: input, issues: [] }, ctx);\n const async = left instanceof Promise || right instanceof Promise;\n if (async) {\n return Promise.all([left, right]).then(([left, right]) => {\n return handleIntersectionResults(payload, left, right);\n });\n }\n return handleIntersectionResults(payload, left, right);\n };\n});\nexport function mergeValues(a, b) {\n // const aType = parse.t(a);\n // const bType = parse.t(b);\n if (a === b) {\n return { valid: true, data: a };\n }\n if (a instanceof Date && b instanceof Date && +a === +b) {\n return { valid: true, data: a };\n }\n if (util.isPlainObject(a) && util.isPlainObject(b)) {\n const bKeys = Object.keys(b);\n const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);\n const newObj = { ...a, ...b };\n if (Object.prototype.hasOwnProperty.call(newObj, \"__proto__\"))\n delete newObj.__proto__;\n for (const key of sharedKeys) {\n if (key === \"__proto__\")\n continue;\n const sharedValue = mergeValues(a[key], b[key]);\n if (!sharedValue.valid) {\n return {\n valid: false,\n mergeErrorPath: [key, ...sharedValue.mergeErrorPath],\n };\n }\n newObj[key] = sharedValue.data;\n }\n return { valid: true, data: newObj };\n }\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) {\n return { valid: false, mergeErrorPath: [] };\n }\n const newArray = [];\n for (let index = 0; index < a.length; index++) {\n const itemA = a[index];\n const itemB = b[index];\n const sharedValue = mergeValues(itemA, itemB);\n if (!sharedValue.valid) {\n return {\n valid: false,\n mergeErrorPath: [index, ...sharedValue.mergeErrorPath],\n };\n }\n newArray.push(sharedValue.data);\n }\n return { valid: true, data: newArray };\n }\n return { valid: false, mergeErrorPath: [] };\n}\nfunction handleIntersectionResults(result, left, right) {\n // Track which side(s) reject each key. A key rejection is reported only when BOTH sides reject it, so a key owned by one branch survives the other's key schema. strictObject reports these as unrecognized_keys; a record with an open key schema reports one invalid_key per key.\n const unrecKeys = new Map();\n let unrecIssue;\n const keyIssues = new Map();\n const collect = (iss, side) => {\n let keys;\n if (iss.code === \"unrecognized_keys\" && !iss.path?.length) {\n unrecIssue ?? (unrecIssue = iss);\n keys = iss.keys;\n }\n else if (iss.code === \"invalid_key\" && iss.origin === \"record\" && iss.path?.length === 1) {\n const k = String(iss.path[0]);\n if (!keyIssues.has(k))\n keyIssues.set(k, iss);\n keys = [k];\n }\n else {\n return false;\n }\n for (const k of keys) {\n if (!unrecKeys.has(k))\n unrecKeys.set(k, {});\n unrecKeys.get(k)[side] = true;\n }\n return true;\n };\n for (const iss of left.issues) {\n if (!collect(iss, \"l\"))\n result.issues.push(iss);\n }\n for (const iss of right.issues) {\n if (!collect(iss, \"r\"))\n result.issues.push(iss);\n }\n // Report only keys rejected by BOTH sides\n const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k);\n if (bothKeys.length) {\n const aggregated = unrecIssue ? bothKeys.filter((k) => unrecIssue.keys.includes(k)) : [];\n if (aggregated.length)\n result.issues.push({ ...unrecIssue, keys: aggregated });\n for (const k of bothKeys) {\n if (!aggregated.includes(k) && keyIssues.has(k))\n result.issues.push(keyIssues.get(k));\n }\n }\n const merged = mergeValues(left.value, right.value);\n if (!merged.valid) {\n if (util.aborted(result))\n return result;\n throw new Error(`Unmergable intersection. Error path: ` + `${JSON.stringify(merged.mergeErrorPath)}`);\n }\n result.value = merged.data;\n return result;\n}\nexport const $ZodTuple = /*@__PURE__*/ core.$constructor(\"$ZodTuple\", (inst, def) => {\n $ZodType.init(inst, def);\n const items = def.items;\n const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!Array.isArray(input)) {\n payload.issues.push({\n input,\n inst,\n expected: \"tuple\",\n code: \"invalid_type\",\n });\n return payload;\n }\n payload.value = memo ? memo.alloc(inst, payload, [], ctx) : [];\n const proms = [];\n const optinStart = getTupleOptStart(items, \"optin\");\n const optoutStart = getTupleOptStart(items, \"optout\");\n if (!def.rest) {\n if (input.length < optinStart) {\n payload.issues.push({\n code: \"too_small\",\n minimum: optinStart,\n inclusive: true,\n input,\n inst,\n origin: \"array\",\n });\n return payload;\n }\n if (input.length > items.length) {\n payload.issues.push({\n code: \"too_big\",\n maximum: items.length,\n inclusive: true,\n input,\n inst,\n origin: \"array\",\n });\n }\n }\n // Run every item in parallel, collecting results into an indexed array. The post-processing in `handleTupleResults` walks them in order so it can decide whether an absent optional-output error can truncate the tail or must be reported to preserve required output.\n const itemResults = new Array(items.length);\n // only tracked when there is a rest loop to skip\n const abortEarly = def.rest ? ctx?.abortEarly : undefined;\n let itemAborted = false;\n for (let i = 0; i < items.length; i++) {\n const r = items[i]._zod.run({ value: input[i], issues: [] }, ctx);\n if (r instanceof Promise) {\n proms.push(r.then((rr) => {\n itemResults[i] = rr;\n }));\n }\n else {\n itemResults[i] = r;\n if (abortEarly && !itemAborted && r.issues.length)\n itemAborted = util.aborted(r);\n }\n }\n // sound because rest is non-empty exactly when every fixed index is present, the one case handleTupleResults cannot discard an item's issues\n if (def.rest && !itemAborted) {\n let i = items.length - 1;\n const rest = input.slice(items.length);\n let seen = payload.issues.length;\n for (const el of rest) {\n if (abortEarly && payload.issues.length !== seen) {\n if (util.aborted(payload, seen))\n break;\n seen = payload.issues.length;\n }\n i++;\n const result = def.rest._zod.run({ value: el, issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((r) => handleTupleResult(r, payload, i)));\n }\n else {\n handleTupleResult(result, payload, i);\n }\n }\n }\n if (proms.length) {\n return Promise.all(proms).then(() => handleTupleResults(itemResults, payload, items, input, optoutStart));\n }\n return handleTupleResults(itemResults, payload, items, input, optoutStart);\n };\n});\nfunction getTupleOptStart(items, key) {\n for (let i = items.length - 1; i >= 0; i--) {\n // optin is a three-rung ladder so any rung above `undefined` permits an absent slot; optout stays two-valued.\n const omittable = key === \"optin\" ? items[i]._zod.optin !== undefined : items[i]._zod.optout === \"optional\";\n if (!omittable)\n return i + 1;\n }\n return 0;\n}\nfunction handleTupleResult(result, final, index) {\n if (result.issues.length) {\n final.issues.push(...util.prefixIssues(index, result.issues));\n }\n final.value[index] = result.value;\n}\nfunction handleTupleResults(itemResults, final, items, input, optoutStart) {\n // Walk results in order. Mirror $ZodObject's swallow-on-absent-optional rule, but only after `optoutStart`: the first index where the output tuple tail can be absent.\n for (let i = 0; i < items.length; i++) {\n const r = itemResults[i];\n const isPresent = i < input.length;\n // The array analog of `handlePropertyResult`'s absent-key early return: the middle rung permits absence without supplying anything in its place, so the tail truncates here instead of materializing whatever the item made of `undefined`.\n if (!isPresent && i >= optoutStart && items[i]._zod.optin === \"optional\") {\n final.value.length = i;\n break;\n }\n if (r.issues.length) {\n if (!isPresent && i >= optoutStart) {\n final.value.length = i;\n break;\n }\n final.issues.push(...util.prefixIssues(i, r.issues));\n }\n final.value[i] = r.value;\n }\n // Drop trailing slots that produced `undefined` for absent input\n // (the array analog of an absent optional key on an object). The\n // `i >= input.length` floor is critical: an explicit `undefined`\n // *inside* the input must be preserved even when the schema is\n // optional-out (e.g. `z.string().or(z.undefined())` accepting an\n // explicit undefined value).\n for (let i = final.value.length - 1; i >= input.length; i--) {\n if (items[i]._zod.optout === \"optional\" && final.value[i] === undefined) {\n final.value.length = i;\n }\n else {\n break;\n }\n }\n return final;\n}\nexport const $ZodRecord = /*@__PURE__*/ core.$constructor(\"$ZodRecord\", (inst, def) => {\n $ZodType.init(inst, def);\n const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!util.isPlainObject(input)) {\n payload.issues.push({\n expected: \"record\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n // no guard in either loop below: a record's invalid_key aborts but an enclosing intersection can reconcile it, so a stopped loop hides keys the sibling does not own and the intersection then rejects nothing\n const proms = [];\n const values = def.keyType._zod.values;\n if (values && !def.partial) {\n payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {};\n const recordKeys = new Set();\n for (const key of values) {\n if (typeof key === \"string\" || typeof key === \"number\" || typeof key === \"symbol\") {\n recordKeys.add(typeof key === \"number\" ? key.toString() : key);\n // A declared __proto__ is stripped but is not an unrecognized key.\n if (key === \"__proto__\")\n continue;\n const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n if (keyResult instanceof Promise) {\n throw new Error(\"Async schemas not supported in object keys currently\");\n }\n if (keyResult.issues.length) {\n payload.issues.push({\n code: \"invalid_key\",\n origin: \"record\",\n issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n input: key,\n path: [key],\n inst,\n });\n continue;\n }\n const outKey = keyResult.value;\n if (outKey === \"__proto__\")\n continue;\n const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[outKey] = result.value;\n }));\n }\n else {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[outKey] = result.value;\n }\n }\n }\n let unrecognized;\n for (const key in input) {\n if (!recordKeys.has(key)) {\n if (def.mode === \"loose\") {\n // skip __proto__ so it can't replace the result prototype via the assignment setter on the plain {} we build into\n if (key === \"__proto__\")\n continue;\n payload.value[key] = input[key];\n }\n else {\n unrecognized = unrecognized ?? [];\n unrecognized.push(key);\n }\n }\n }\n if (unrecognized && unrecognized.length > 0) {\n payload.issues.push({\n code: \"unrecognized_keys\",\n input,\n inst,\n keys: unrecognized,\n continue: true,\n });\n }\n }\n else {\n payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {};\n // An enumerable key schema declares which keys the record owns, so a key outside the set is unrecognized. A non-enumerable one (regex, refine) is a constraint every key must satisfy, so a failing key is invalid. Only the former is reconcilable against the other side of an intersection.\n let unrecognized;\n // Reflect.ownKeys for Symbol-key support; filter non-enumerable to match z.object()\n for (const key of Reflect.ownKeys(input)) {\n if (key === \"__proto__\")\n continue;\n if (!Object.prototype.propertyIsEnumerable.call(input, key))\n continue;\n let keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n if (keyResult instanceof Promise) {\n throw new Error(\"Async schemas not supported in object keys currently\");\n }\n // Numeric string fallback: if key is a numeric string and failed, retry with Number(key). This handles z.number(), z.literal([1, 2, 3]), and unions containing numeric literals\n const checkNumericKey = typeof key === \"string\" && regexes.number.test(key) && keyResult.issues.length;\n if (checkNumericKey) {\n const retryResult = def.keyType._zod.run({ value: Number(key), issues: [] }, ctx);\n if (retryResult instanceof Promise) {\n throw new Error(\"Async schemas not supported in object keys currently\");\n }\n if (retryResult.issues.length === 0) {\n keyResult = retryResult;\n }\n }\n if (keyResult.issues.length) {\n if (def.mode === \"loose\") {\n // Pass through unchanged\n payload.value[key] = input[key];\n }\n else if (values) {\n unrecognized = unrecognized ?? [];\n unrecognized.push(key);\n }\n else {\n // Default \"strict\" behavior: error on invalid key\n payload.issues.push({\n code: \"invalid_key\",\n origin: \"record\",\n issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n input: key,\n path: [key],\n inst,\n });\n }\n continue;\n }\n // the guard above tests the raw input key, but the key schema can normalize an ordinary key into __proto__; re-check the key we actually write under\n const outKey = keyResult.value;\n if (outKey === \"__proto__\")\n continue;\n const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[outKey] = result.value;\n }));\n }\n else {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[outKey] = result.value;\n }\n }\n if (unrecognized && unrecognized.length > 0) {\n payload.issues.push({\n code: \"unrecognized_keys\",\n input,\n inst,\n keys: unrecognized,\n continue: true,\n });\n }\n }\n if (proms.length) {\n return Promise.all(proms).then(() => payload);\n }\n return payload;\n };\n});\nexport const $ZodMap = /*@__PURE__*/ core.$constructor(\"$ZodMap\", (inst, def) => {\n $ZodType.init(inst, def);\n const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!(input instanceof Map)) {\n payload.issues.push({\n expected: \"map\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n const proms = [];\n payload.value = memo ? memo.alloc(inst, payload, new Map(), ctx) : new Map();\n const abortEarly = ctx?.abortEarly;\n let seen = payload.issues.length;\n for (const [key, value] of input) {\n if (abortEarly && payload.issues.length !== seen) {\n if (util.aborted(payload, seen))\n break;\n seen = payload.issues.length;\n }\n const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n const valueResult = def.valueType._zod.run({ value: value, issues: [] }, ctx);\n if (keyResult instanceof Promise || valueResult instanceof Promise) {\n proms.push(Promise.all([keyResult, valueResult]).then(([keyResult, valueResult]) => {\n handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx);\n }));\n }\n else {\n handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx);\n }\n }\n if (proms.length)\n return Promise.all(proms).then(() => payload);\n return payload;\n };\n capSize(inst, mapSize);\n});\nfunction handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) {\n if (keyResult.issues.length) {\n if (util.propertyKeyTypes.has(typeof key)) {\n final.issues.push(...util.prefixIssues(key, keyResult.issues));\n }\n else {\n final.issues.push({\n code: \"invalid_key\",\n origin: \"map\",\n input,\n inst,\n issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n });\n }\n }\n if (valueResult.issues.length) {\n if (util.propertyKeyTypes.has(typeof key)) {\n final.issues.push(...util.prefixIssues(key, valueResult.issues));\n }\n else {\n final.issues.push({\n origin: \"map\",\n code: \"invalid_element\",\n input,\n inst,\n key: key,\n issues: valueResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n });\n }\n }\n final.value.set(keyResult.value, valueResult.value);\n}\nexport const $ZodSet = /*@__PURE__*/ core.$constructor(\"$ZodSet\", (inst, def) => {\n $ZodType.init(inst, def);\n const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!(input instanceof Set)) {\n payload.issues.push({\n input,\n inst,\n expected: \"set\",\n code: \"invalid_type\",\n });\n return payload;\n }\n const proms = [];\n payload.value = memo ? memo.alloc(inst, payload, new Set(), ctx) : new Set();\n const abortEarly = ctx?.abortEarly;\n let seen = payload.issues.length;\n for (const item of input) {\n if (abortEarly && payload.issues.length !== seen) {\n if (util.aborted(payload, seen))\n break;\n seen = payload.issues.length;\n }\n const result = def.valueType._zod.run({ value: item, issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => handleSetResult(result, payload)));\n }\n else\n handleSetResult(result, payload);\n }\n if (proms.length)\n return Promise.all(proms).then(() => payload);\n return payload;\n };\n capSize(inst, setSize);\n});\nfunction handleSetResult(result, final) {\n if (result.issues.length) {\n final.issues.push(...result.issues);\n }\n final.value.add(result.value);\n}\nexport const $ZodEnum = /*@__PURE__*/ core.$constructor(\"$ZodEnum\", (inst, def) => {\n $ZodType.init(inst, def);\n const values = util.getEnumValues(def.entries);\n const valuesSet = new Set(values);\n inst._zod.values = valuesSet;\n util.defineLazyInternal(inst, \"pattern\", (zod) => {\n const patternValues = util.getEnumValues(zod.def.entries).filter((k) => util.propertyKeyTypes.has(typeof k));\n // unmatchable fallback, RE2-safe: an empty alternation would compile to /^()$/, which matches \"\"\n return new RegExp(patternValues.length ? `^(${patternValues.map((o) => util.escapeRegex(o.toString())).join(\"|\")})$` : \"^[^\\\\s\\\\S]$\");\n });\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (valuesSet.has(input)) {\n return payload;\n }\n payload.issues.push({\n code: \"invalid_value\",\n values,\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodLiteral = /*@__PURE__*/ core.$constructor(\"$ZodLiteral\", (inst, def) => {\n $ZodType.init(inst, def);\n const values = new Set(def.values);\n inst._zod.values = values;\n util.defineLazyInternal(inst, \"pattern\", (zod) => {\n const vals = zod.def.values;\n // unmatchable fallback, RE2-safe: an empty alternation would compile to /^()$/, which matches \"\"\n return new RegExp(vals.length\n ? `^(${vals\n .map((o) => typeof o === \"string\" ? util.escapeRegex(o) : o ? util.escapeRegex(o.toString()) : String(o))\n .join(\"|\")})$`\n : \"^[^\\\\s\\\\S]$\");\n });\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (values.has(input)) {\n return payload;\n }\n payload.issues.push({\n code: \"invalid_value\",\n values: def.values,\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodFile = /*@__PURE__*/ core.$constructor(\"$ZodFile\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n // @ts-ignore\n if (input instanceof File)\n return payload;\n payload.issues.push({\n expected: \"file\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodTransform = /*@__PURE__*/ core.$constructor(\"$ZodTransform\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.optin = \"optional\";\n core.globalConfig.memoizer?.guard(inst);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n throw new core.$ZodEncodeError(inst.constructor.name);\n }\n const _out = def.transform(payload.value, payload);\n if (ctx.async) {\n const output = _out instanceof Promise ? _out : Promise.resolve(_out);\n return output.then((output) => {\n payload.value = output;\n return payload;\n });\n }\n if (_out instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n payload.value = _out;\n return payload;\n };\n});\nfunction handleOptionalResult(payload, result) {\n // A substituting schema that still failed has no usable answer; yield undefined. Its issues are simply dropped: it ran on a payload of its own, so there is no shared array to truncate and nothing of the caller's to lose with it.\n payload.value = result.issues.length ? undefined : result.value;\n return payload;\n}\nexport const $ZodOptional = /*@__PURE__*/ core.$constructor(\"$ZodOptional\", (inst, def) => {\n $ZodType.init(inst, def);\n // .optional() propagates absence rather than substituting for it, so a defaulted inner keeps its rung.\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.innerType._zod.optin === \"defaulted\" ? \"defaulted\" : \"optional\");\n inst._zod.optout = \"optional\";\n util.defineLazyInternal(inst, \"values\", (zod) => {\n const values = zod.def.innerType._zod.values;\n return values ? new Set([...values, undefined]) : undefined;\n });\n util.defineLazyInternal(inst, \"pattern\", (zod) => {\n const pattern = zod.def.innerType._zod.pattern;\n return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)})?$`) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n if (payload.value === undefined) {\n // Only the top rung substitutes a value for absence; everything else leaves it intact, which is what .optional() means.\n if (def.innerType._zod.optin !== \"defaulted\")\n return payload;\n // Its own payload, for the same reason $ZodCatch gets one: a pipe forwards an unrecognized key through the caller's issues array, and this must not read that as the substituting schema failing and drop it.\n const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx);\n if (result instanceof Promise)\n return result.then((result) => handleOptionalResult(payload, result));\n return handleOptionalResult(payload, result);\n }\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodExactOptional = /*@__PURE__*/ core.$constructor(\"$ZodExactOptional\", (inst, def) => {\n // Call parent init - inherits optin/optout = \"optional\"\n $ZodOptional.init(inst, def);\n // Override values/pattern to NOT add undefined\n util.defineLazyInternal(inst, \"values\", (zod) => zod.def.innerType._zod.values);\n util.defineLazyInternal(inst, \"pattern\", (zod) => zod.def.innerType._zod.pattern);\n // Override parse to just delegate (no undefined handling)\n inst._zod.parse = (payload, ctx) => {\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodNullable = /*@__PURE__*/ core.$constructor(\"$ZodNullable\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.innerType._zod.optin);\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.innerType._zod.optout);\n util.defineLazyInternal(inst, \"pattern\", (zod) => {\n const pattern = zod.def.innerType._zod.pattern;\n return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)}|null)$`) : undefined;\n });\n util.defineLazyInternal(inst, \"values\", (zod) => {\n return zod.def.innerType._zod.values ? new Set([...zod.def.innerType._zod.values, null]) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n // Forward direction (decode): allow null to pass through\n if (payload.value === null)\n return payload;\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodDefault = /*@__PURE__*/ core.$constructor(\"$ZodDefault\", (inst, def) => {\n $ZodType.init(inst, def);\n // inst._zod.qin = \"true\";\n inst._zod.optin = \"defaulted\";\n util.defineLazyInternal(inst, \"values\", (zod) => zod.def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n // Forward direction (decode): apply defaults for undefined input\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n /**\n * $ZodDefault returns the default value immediately in forward direction.\n * It doesn't pass the default value into the validator (\"prefault\"). There's no reason to pass the default value through validation. The validity of the default is enforced by TypeScript statically. Otherwise, it's the responsibility of the user to ensure the default is valid. In the case of pipes with divergent in/out types, you can specify the default on the `in` schema of your ZodPipe to set a \"prefault\" for the pipe. */\n return payload;\n }\n // Forward direction: continue with default handling\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => handleDefaultResult(result, def));\n }\n return handleDefaultResult(result, def);\n };\n});\nfunction handleDefaultResult(payload, def) {\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n }\n return payload;\n}\nexport const $ZodPrefault = /*@__PURE__*/ core.$constructor(\"$ZodPrefault\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.optin = \"defaulted\";\n util.defineLazyInternal(inst, \"values\", (zod) => zod.def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n // Forward direction (decode): apply prefault for undefined input\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n }\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodNonOptional = /*@__PURE__*/ core.$constructor(\"$ZodNonOptional\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazyInternal(inst, \"values\", (zod) => {\n const v = zod.def.innerType._zod.values;\n return v ? new Set([...v].filter((x) => x !== undefined)) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => handleNonOptionalResult(result, inst));\n }\n return handleNonOptionalResult(result, inst);\n };\n});\nfunction handleNonOptionalResult(payload, inst) {\n if (!payload.issues.length && payload.value === undefined) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"nonoptional\",\n input: payload.value,\n inst,\n });\n }\n return payload;\n}\nexport const $ZodSuccess = /*@__PURE__*/ core.$constructor(\"$ZodSuccess\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n throw new core.$ZodEncodeError(\"ZodSuccess\");\n }\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => {\n payload.value = result.issues.length === 0;\n return payload;\n });\n }\n payload.value = result.issues.length === 0;\n return payload;\n };\n});\nfunction handleCatchResult(payload, result, def, ctx) {\n if (!result.issues.length) {\n payload.value = result.value;\n // The value carries up, so the flag describing it has to carry with it: a back-edge into a node still being parsed must not be frozen by an enclosing readonly, and its checks belong to the node itself. Guarded so the ordinary case adds no own property.\n if (result.memo)\n payload.memo = true;\n return payload;\n }\n // Spread the inner's own payload, not ours: `value` has to stay the input the catch was handed, and the inner ran on a payload of its own so its issues are already private to this call.\n payload.value = def.catchValue({\n ...result,\n value: payload.value,\n error: {\n issues: result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n },\n input: payload.value,\n });\n return payload;\n}\nexport const $ZodCatch = /*@__PURE__*/ core.$constructor(\"$ZodCatch\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.innerType._zod.optin === \"defaulted\" ? \"defaulted\" : \"optional\");\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.innerType._zod.optout);\n util.defineLazyInternal(inst, \"values\", (zod) => zod.def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n // Forward direction (decode): apply catch logic\n const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx);\n if (result instanceof Promise) {\n return result.then((result) => handleCatchResult(payload, result, def, ctx));\n }\n return handleCatchResult(payload, result, def, ctx);\n };\n});\nexport const $ZodNaN = /*@__PURE__*/ core.$constructor(\"$ZodNaN\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"number\" || !Number.isNaN(payload.value)) {\n payload.issues.push({\n input: payload.value,\n inst,\n expected: \"nan\",\n code: \"invalid_type\",\n });\n return payload;\n }\n return payload;\n };\n});\nexport const $ZodPipe = /*@__PURE__*/ core.$constructor(\"$ZodPipe\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazyInternal(inst, \"values\", (zod) => zod.def.in._zod.values);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.in._zod.optin);\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.out._zod.optout);\n util.defineLazyInternal(inst, \"propValues\", (zod) => zod.def.in._zod.propValues);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n const right = def.out._zod.run(payload, ctx);\n if (right instanceof Promise) {\n return right.then((right) => handlePipeResult(right, def.in, ctx));\n }\n return handlePipeResult(right, def.in, ctx);\n }\n const left = def.in._zod.run(payload, ctx);\n if (left instanceof Promise) {\n return left.then((left) => handlePipeResult(left, def.out, ctx));\n }\n return handlePipeResult(left, def.out, ctx);\n };\n});\nfunction handlePipeResult(left, next, ctx) {\n // Any issue stops the pipe, so a failing refinement never feeds its transform. An unrecognized key is the exception: it describes the input's extra properties, not the value being piped, and an enclosing intersection may yet reconcile it.\n if (left.issues.some((iss) => iss.code !== \"unrecognized_keys\")) {\n // prevent further checks\n left.aborted = true;\n return left;\n }\n return next._zod.run({ value: left.value, issues: left.issues }, ctx);\n}\nexport const $ZodCodec = /*@__PURE__*/ core.$constructor(\"$ZodCodec\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazyInternal(inst, \"values\", (zod) => zod.def.in._zod.values);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.in._zod.optin);\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.out._zod.optout);\n util.defineLazyInternal(inst, \"propValues\", (zod) => zod.def.in._zod.propValues);\n inst._zod.parse = (payload, ctx) => {\n const direction = ctx.direction || \"forward\";\n if (direction === \"forward\") {\n const left = def.in._zod.run(payload, ctx);\n if (left instanceof Promise) {\n return left.then((left) => handleCodecAResult(left, def, ctx));\n }\n return handleCodecAResult(left, def, ctx);\n }\n else {\n const right = def.out._zod.run(payload, ctx);\n if (right instanceof Promise) {\n return right.then((right) => handleCodecAResult(right, def, ctx));\n }\n return handleCodecAResult(right, def, ctx);\n }\n };\n});\nfunction handleCodecAResult(result, def, ctx) {\n if (result.issues.length) {\n // prevent further checks\n result.aborted = true;\n return result;\n }\n const direction = ctx.direction || \"forward\";\n if (direction === \"forward\") {\n const transformed = def.transform(result.value, result);\n if (transformed instanceof Promise) {\n return transformed.then((value) => handleCodecTxResult(result, value, def.out, ctx));\n }\n return handleCodecTxResult(result, transformed, def.out, ctx);\n }\n else {\n const transformed = def.reverseTransform(result.value, result);\n if (transformed instanceof Promise) {\n return transformed.then((value) => handleCodecTxResult(result, value, def.in, ctx));\n }\n return handleCodecTxResult(result, transformed, def.in, ctx);\n }\n}\nfunction handleCodecTxResult(left, value, nextSchema, ctx) {\n // Check if transform added any issues\n if (left.issues.length) {\n left.aborted = true;\n return left;\n }\n return nextSchema._zod.run({ value, issues: left.issues }, ctx);\n}\nexport const $ZodPreprocess = /*@__PURE__*/ core.$constructor(\"$ZodPreprocess\", (inst, def) => {\n $ZodPipe.init(inst, def);\n});\nexport const $ZodReadonly = /*@__PURE__*/ core.$constructor(\"$ZodReadonly\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazyInternal(inst, \"propValues\", (zod) => zod.def.innerType._zod.propValues);\n util.defineLazyInternal(inst, \"values\", (zod) => zod.def.innerType._zod.values);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.innerType?._zod?.optin);\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.innerType?._zod?.optout);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then(handleReadonlyResult);\n }\n return handleReadonlyResult(result);\n };\n});\nfunction handleReadonlyResult(payload) {\n // A repeat visit hands back a node that is still being built; freezing it here would make the rest of its keys fail to assign.\n if (!payload.memo)\n payload.value = Object.freeze(payload.value);\n return payload;\n}\n// a leaf's pattern source with its own checks folded in: the last pattern-carrying check wins, else length bounds narrow the catch-all, else an integer format narrows the number form. the fold lives here instead of on `_zod.pattern` so a bundle without template literals never pays for it\nfunction leafPattern(schema) {\n const def = schema._zod.def;\n let pattern = def.pattern;\n let isInt = !!def.format?.includes(\"int\");\n let minimum;\n let maximum;\n for (const ch of def.checks ?? []) {\n const d = ch._zod.def;\n if (d.pattern)\n pattern = d.pattern;\n isInt || (isInt = !!d.format?.includes(\"int\"));\n const lo = d.minimum ?? d.length;\n const hi = d.maximum ?? d.length;\n if (lo !== undefined && (minimum === undefined || lo > minimum))\n minimum = lo;\n if (hi !== undefined && (maximum === undefined || hi < maximum))\n maximum = hi;\n }\n if (pattern)\n return pattern.source;\n // an empty range matches nothing at runtime, and `{8,5}` is not a legal quantifier\n if (minimum !== undefined && maximum !== undefined && minimum > maximum)\n return \"(?!)\";\n if (minimum !== undefined || maximum !== undefined)\n return regexes.string({ minimum, maximum }).source;\n const own = schema._zod.pattern;\n return (isInt && own === regexes.number ? regexes.integer : own)?.source;\n}\n// a part's pattern source. a wrapper's pattern embeds its inner pattern's source verbatim, so the folded form is substituted in place without knowing the wrapper's own composition; a union's options are joined the way the union builds its own pattern\nfunction partPattern(schema) {\n const def = schema._zod.def;\n const own = schema._zod.pattern?.source;\n // lazy resolves its inner on the internals, not the def\n const inner = def.innerType ?? schema._zod.innerType;\n if (inner) {\n const before = inner._zod.pattern?.source;\n const after = partPattern(inner);\n if (own && before && after && after !== before) {\n return own.replace(util.cleanRegex(before), () => util.cleanRegex(after));\n }\n return own;\n }\n if (def.options) {\n const sources = def.options.map(partPattern);\n if (sources.every(Boolean))\n return `^(${sources.map((s) => util.cleanRegex(s)).join(\"|\")})$`;\n }\n return leafPattern(schema);\n}\nexport const $ZodTemplateLiteral = /*@__PURE__*/ core.$constructor(\"$ZodTemplateLiteral\", (inst, def) => {\n $ZodType.init(inst, def);\n const regexParts = [];\n for (const part of def.parts) {\n if (typeof part === \"object\" && part !== null) {\n // is Zod schema\n const source = partPattern(part);\n if (!source) {\n throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`);\n }\n regexParts.push(util.cleanRegex(source));\n }\n else if (part === null || util.primitiveTypes.has(typeof part)) {\n regexParts.push(util.escapeRegex(`${part}`));\n }\n else {\n throw new Error(`Invalid template literal part: ${part}`);\n }\n }\n inst._zod.pattern = new RegExp(`^${regexParts.join(\"\")}$`);\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"string\") {\n payload.issues.push({\n input: payload.value,\n inst,\n expected: \"string\",\n code: \"invalid_type\",\n });\n return payload;\n }\n inst._zod.pattern.lastIndex = 0;\n if (!inst._zod.pattern.test(payload.value)) {\n payload.issues.push({\n input: payload.value,\n inst,\n code: \"invalid_format\",\n format: def.format ?? \"template_literal\",\n pattern: inst._zod.pattern.source,\n });\n return payload;\n }\n return payload;\n };\n});\nexport const $ZodFunction = /*@__PURE__*/ core.$constructor(\"$ZodFunction\", (inst, def) => {\n $ZodType.init(inst, def);\n // Defined, not assigned: the classic prototype exposes `_def` as a getter with no setter.\n Object.defineProperty(inst, \"_def\", { value: def });\n inst._zod.def = def;\n inst.implement = (func) => {\n if (typeof func !== \"function\") {\n throw new Error(\"implement() must be called with a function\");\n }\n // Defined inline so the closure stays anonymous: binding it to a `const` first names it, which costs 256 bytes per implemented function.\n return Object.defineProperty(function (...args) {\n const parsedArgs = inst._def.input ? parse(inst._def.input, args) : args;\n const result = Reflect.apply(func, this, parsedArgs);\n if (inst._def.output) {\n return parse(inst._def.output, result);\n }\n return result;\n }, \"_zod\", { value: inst._zod, enumerable: false });\n };\n inst.implementAsync = (func) => {\n if (typeof func !== \"function\") {\n throw new Error(\"implementAsync() must be called with a function\");\n }\n return Object.defineProperty(async function (...args) {\n const parsedArgs = inst._def.input ? await parseAsync(inst._def.input, args) : args;\n const result = await Reflect.apply(func, this, parsedArgs);\n if (inst._def.output) {\n return await parseAsync(inst._def.output, result);\n }\n return result;\n }, \"_zod\", { value: inst._zod, enumerable: false });\n };\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"function\") {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"function\",\n input: payload.value,\n inst,\n });\n return payload;\n }\n // Check if output is a promise type to determine if we should use async implementation\n const hasPromiseOutput = inst._def.output && inst._def.output._zod.def.type === \"promise\";\n if (hasPromiseOutput) {\n payload.value = inst.implementAsync(payload.value);\n }\n else {\n payload.value = inst.implement(payload.value);\n }\n return payload;\n };\n inst.input = (...args) => {\n const F = inst.constructor;\n if (Array.isArray(args[0])) {\n return new F({\n type: \"function\",\n input: new $ZodTuple({\n type: \"tuple\",\n items: args[0],\n rest: args[1],\n }),\n output: inst._def.output,\n });\n }\n return new F({\n type: \"function\",\n input: args[0],\n output: inst._def.output,\n });\n };\n inst.output = (output) => {\n const F = inst.constructor;\n return new F({\n type: \"function\",\n input: inst._def.input,\n output,\n });\n };\n return inst;\n});\nexport const $ZodPromise = /*@__PURE__*/ core.$constructor(\"$ZodPromise\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n return Promise.resolve(payload.value).then((inner) => def.innerType._zod.run({ value: inner, issues: [] }, ctx));\n };\n});\nexport const $ZodLazy = /*@__PURE__*/ core.$constructor(\"$ZodLazy\", (inst, def) => {\n $ZodType.init(inst, def);\n // Cache the resolved inner type on the shared `def` so all clones of this lazy (e.g. via `.describe()`/`.meta()`) share the same inner instance, preserving identity for cycle detection on recursive schemas.\n util.defineLazy(inst._zod, \"innerType\", () => {\n const d = def;\n if (!d._cachedInner)\n d._cachedInner = def.getter();\n return d._cachedInner;\n });\n util.defineLazyInternal(inst, \"pattern\", (zod) => zod.innerType?._zod?.pattern);\n util.defineLazyInternal(inst, \"propValues\", (zod) => zod.innerType?._zod?.propValues);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.innerType?._zod?.optin ?? undefined);\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.innerType?._zod?.optout ?? undefined);\n inst._zod.parse = (payload, ctx) => {\n const inner = inst._zod.innerType;\n return inner._zod.run(payload, ctx);\n };\n});\nexport const $ZodCustom = /*@__PURE__*/ core.$constructor(\"$ZodCustom\", (inst, def) => {\n checks.$ZodCheck.init(inst, def);\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _) => {\n return payload;\n };\n inst._zod.check = (payload) => {\n const input = payload.value;\n const r = def.fn(input);\n if (r instanceof Promise) {\n return r.then((r) => handleRefineResult(r, payload, input, inst));\n }\n handleRefineResult(r, payload, input, inst);\n return;\n };\n});\nfunction handleRefineResult(result, payload, input, inst) {\n if (!result) {\n const _iss = {\n code: \"custom\",\n input,\n inst, // incorporates params.error into issue reporting\n path: [...(inst._zod.def.path ?? [])], // incorporates params.error into issue reporting\n continue: !inst._zod.def.abort,\n // params: inst._zod.def.params,\n };\n if (inst._zod.def.params)\n _iss.params = inst._zod.def.params;\n payload.issues.push(util.issue(_iss));\n }\n}\n","var _a;\nexport const $output = /*@__PURE__*/ Symbol(\"ZodOutput\");\nexport const $input = /*@__PURE__*/ Symbol(\"ZodInput\");\nexport class $ZodRegistry {\n constructor() {\n this._map = new WeakMap();\n this._idmap = new Map();\n }\n add(schema, ..._meta) {\n const meta = _meta[0];\n this._map.set(schema, meta);\n if (meta && typeof meta === \"object\" && \"id\" in meta) {\n this._idmap.set(meta.id, schema);\n }\n return this;\n }\n clear() {\n this._map = new WeakMap();\n this._idmap = new Map();\n return this;\n }\n remove(schema) {\n const meta = this._map.get(schema);\n if (meta && typeof meta === \"object\" && \"id\" in meta) {\n this._idmap.delete(meta.id);\n }\n this._map.delete(schema);\n return this;\n }\n get(schema) {\n // return this._map.get(schema) as any;\n // inherit metadata\n const p = schema._zod.parent;\n if (p) {\n const pm = { ...(this.get(p) ?? {}) };\n delete pm.id; // do not inherit id\n const f = { ...pm, ...this._map.get(schema) };\n return Object.keys(f).length ? f : undefined;\n }\n return this._map.get(schema);\n }\n has(schema) {\n return this._map.has(schema);\n }\n}\n// registries\nexport function registry() {\n return new $ZodRegistry();\n}\n(_a = globalThis).__zod_globalRegistry ?? (_a.__zod_globalRegistry = registry());\nexport const globalRegistry = globalThis.__zod_globalRegistry;\n","import * as checks from \"./checks.js\";\nimport * as registries from \"./registries.js\";\nimport * as schemas from \"./schemas.js\";\nimport * as util from \"./util.js\";\nfunction snapshotChecks(def) {\n if (def.checks)\n def.checks = [...def.checks];\n return def;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _string(Class, params) {\n return new Class(snapshotChecks({ type: \"string\", ...util.normalizeParams(params) }));\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedString(Class, params) {\n return new Class(snapshotChecks({ type: \"string\", coerce: true, ...util.normalizeParams(params) }));\n}\n// @__NO_SIDE_EFFECTS__\nexport function _email(Class, params) {\n return new Class({\n type: \"string\",\n format: \"email\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _guid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"guid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v4\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v6\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv7(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v7\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _url(Class, params) {\n return new Class({\n type: \"string\",\n format: \"url\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _emoji(Class, params) {\n return new Class({\n type: \"string\",\n format: \"emoji\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nanoid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"nanoid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link _cuid2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\n// @__NO_SIDE_EFFECTS__\nexport function _cuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cuid2(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cuid2\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ulid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ulid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _xid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"xid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ksuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ksuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ipv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ipv4\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ipv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ipv6\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _mac(Class, params) {\n return new Class({\n type: \"string\",\n format: \"mac\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cidrv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cidrv4\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cidrv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cidrv6\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _base64(Class, params) {\n return new Class({\n type: \"string\",\n format: \"base64\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _base64url(Class, params) {\n return new Class({\n type: \"string\",\n format: \"base64url\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _e164(Class, params) {\n return new Class({\n type: \"string\",\n format: \"e164\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _creditCard(Class, params) {\n return new Class({\n type: \"string\",\n format: \"credit_card\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _iban(Class, params) {\n return new Class({\n type: \"string\",\n format: \"iban\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _jwt(Class, params) {\n return new Class({\n type: \"string\",\n format: \"jwt\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\nexport const TimePrecision = {\n Any: null,\n Minute: -1,\n Second: 0,\n Millisecond: 3,\n Microsecond: 6,\n};\n// @__NO_SIDE_EFFECTS__\nexport function _isoDateTime(Class, params) {\n return new Class({\n type: \"string\",\n format: \"datetime\",\n check: \"string_format\",\n offset: false,\n local: false,\n precision: null,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoDate(Class, params) {\n return new Class({\n type: \"string\",\n format: \"date\",\n check: \"string_format\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoTime(Class, params) {\n return new Class({\n type: \"string\",\n format: \"time\",\n check: \"string_format\",\n precision: null,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoDuration(Class, params) {\n return new Class({\n type: \"string\",\n format: \"duration\",\n check: \"string_format\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _number(Class, params) {\n return new Class(snapshotChecks({ type: \"number\", checks: [], ...util.normalizeParams(params) }));\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedNumber(Class, params) {\n return new Class(snapshotChecks({ type: \"number\", coerce: true, checks: [], ...util.normalizeParams(params) }));\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"safeint\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _float32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"float32\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _float64(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"float64\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"int32\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uint32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"uint32\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _boolean(Class, params) {\n return new Class({\n type: \"boolean\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedBoolean(Class, params) {\n return new Class({\n type: \"boolean\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _bigint(Class, params) {\n return new Class({\n type: \"bigint\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedBigint(Class, params) {\n return new Class({\n type: \"bigint\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int64(Class, params) {\n return new Class({\n type: \"bigint\",\n check: \"bigint_format\",\n abort: false,\n format: \"int64\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uint64(Class, params) {\n return new Class({\n type: \"bigint\",\n check: \"bigint_format\",\n abort: false,\n format: \"uint64\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _symbol(Class, params) {\n return new Class({\n type: \"symbol\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _undefined(Class, params) {\n return new Class({\n type: \"undefined\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _null(Class, params) {\n return new Class({\n type: \"null\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _any(Class) {\n return new Class({\n type: \"any\",\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _unknown(Class) {\n return new Class({\n type: \"unknown\",\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _never(Class, params) {\n return new Class({\n type: \"never\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _void(Class, params) {\n return new Class({\n type: \"void\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _date(Class, params) {\n return new Class({\n type: \"date\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedDate(Class, params) {\n return new Class({\n type: \"date\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nan(Class, params) {\n return new Class({\n type: \"nan\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lt(value, params) {\n return new checks.$ZodCheckLessThan({\n check: \"less_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: false,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lte(value, params) {\n return new checks.$ZodCheckLessThan({\n check: \"less_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: true,\n });\n}\nexport { \n/** @deprecated Use `z.lte()` instead. */\n_lte as _max, };\n// @__NO_SIDE_EFFECTS__\nexport function _gt(value, params) {\n return new checks.$ZodCheckGreaterThan({\n check: \"greater_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: false,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _gte(value, params) {\n return new checks.$ZodCheckGreaterThan({\n check: \"greater_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: true,\n });\n}\nexport { \n/** @deprecated Use `z.gte()` instead. */\n_gte as _min, };\n// @__NO_SIDE_EFFECTS__\nexport function _positive(params) {\n return _gt(0, params);\n}\n// negative\n// @__NO_SIDE_EFFECTS__\nexport function _negative(params) {\n return _lt(0, params);\n}\n// nonpositive\n// @__NO_SIDE_EFFECTS__\nexport function _nonpositive(params) {\n return _lte(0, params);\n}\n// nonnegative\n// @__NO_SIDE_EFFECTS__\nexport function _nonnegative(params) {\n return _gte(0, params);\n}\n// @__NO_SIDE_EFFECTS__\nexport function _multipleOf(value, params) {\n return new checks.$ZodCheckMultipleOf({\n check: \"multiple_of\",\n ...util.normalizeParams(params),\n value,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _maxSize(maximum, params) {\n return new checks.$ZodCheckMaxSize({\n check: \"max_size\",\n ...util.normalizeParams(params),\n maximum,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _minSize(minimum, params) {\n return new checks.$ZodCheckMinSize({\n check: \"min_size\",\n ...util.normalizeParams(params),\n minimum,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _size(size, params) {\n return new checks.$ZodCheckSizeEquals({\n check: \"size_equals\",\n ...util.normalizeParams(params),\n size,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _maxLength(maximum, params) {\n const ch = new checks.$ZodCheckMaxLength({\n check: \"max_length\",\n ...util.normalizeParams(params),\n maximum,\n });\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _minLength(minimum, params) {\n return new checks.$ZodCheckMinLength({\n check: \"min_length\",\n ...util.normalizeParams(params),\n minimum,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _length(length, params) {\n return new checks.$ZodCheckLengthEquals({\n check: \"length_equals\",\n ...util.normalizeParams(params),\n length,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _regex(pattern, params) {\n return new checks.$ZodCheckRegex({\n check: \"string_format\",\n format: \"regex\",\n ...util.normalizeParams(params),\n pattern,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lowercase(params) {\n return new checks.$ZodCheckLowerCase({\n check: \"string_format\",\n format: \"lowercase\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uppercase(params) {\n return new checks.$ZodCheckUpperCase({\n check: \"string_format\",\n format: \"uppercase\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _includes(includes, params) {\n return new checks.$ZodCheckIncludes({\n check: \"string_format\",\n format: \"includes\",\n ...util.normalizeParams(params),\n includes,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _startsWith(prefix, params) {\n return new checks.$ZodCheckStartsWith({\n check: \"string_format\",\n format: \"starts_with\",\n ...util.normalizeParams(params),\n prefix,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _endsWith(suffix, params) {\n return new checks.$ZodCheckEndsWith({\n check: \"string_format\",\n format: \"ends_with\",\n ...util.normalizeParams(params),\n suffix,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _property(property, schema, params) {\n return new checks.$ZodCheckProperty({\n check: \"property\",\n property,\n schema,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _properties(shape, params) {\n return new checks.$ZodCheckProperties({\n check: \"properties\",\n shape,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _mime(types, params) {\n return new checks.$ZodCheckMimeType({\n check: \"mime_type\",\n mime: types,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _overwrite(tx) {\n return new checks.$ZodCheckOverwrite({\n check: \"overwrite\",\n tx,\n });\n}\n// normalize\n// @__NO_SIDE_EFFECTS__\nexport function _normalize(form) {\n return _overwrite((input) => input.normalize(form));\n}\n// trim\n// @__NO_SIDE_EFFECTS__\nexport function _trim() {\n return _overwrite((input) => input.trim());\n}\n// toLowerCase\n// @__NO_SIDE_EFFECTS__\nexport function _toLowerCase() {\n return _overwrite((input) => input.toLowerCase());\n}\n// toUpperCase\n// @__NO_SIDE_EFFECTS__\nexport function _toUpperCase() {\n return _overwrite((input) => input.toUpperCase());\n}\n// slugify\n// @__NO_SIDE_EFFECTS__\nexport function _slugify() {\n return _overwrite((input) => util.slugify(input));\n}\n// @__NO_SIDE_EFFECTS__\nexport function _array(Class, element, params) {\n return new Class({\n type: \"array\",\n element,\n // get element() {\n // return element;\n // },\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _union(Class, options, params) {\n return new Class({\n type: \"union\",\n options,\n ...util.normalizeParams(params),\n });\n}\nexport function _xor(Class, options, params) {\n return new Class({\n type: \"union\",\n options,\n inclusive: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _discriminatedUnion(Class, discriminator, options, params) {\n return new Class({\n type: \"union\",\n options: options,\n discriminator,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _intersection(Class, left, right) {\n return new Class({\n type: \"intersection\",\n left,\n right,\n });\n}\n// export function _tuple(\n// Class: util.SchemaClass<schemas.$ZodTuple>,\n// items: [],\n// params?: string | $ZodTupleParams\n// ): schemas.$ZodTuple<[], null>;\n// @__NO_SIDE_EFFECTS__\nexport function _tuple(Class, items, _paramsOrRest, _params) {\n const hasRest = _paramsOrRest instanceof schemas.$ZodType;\n const params = hasRest ? _params : _paramsOrRest;\n const rest = hasRest ? _paramsOrRest : null;\n return new Class({\n type: \"tuple\",\n items,\n rest,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _record(Class, keyType, valueType, params) {\n return new Class({\n type: \"record\",\n keyType,\n valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _map(Class, keyType, valueType, params) {\n return new Class({\n type: \"map\",\n keyType,\n valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _set(Class, valueType, params) {\n return new Class({\n type: \"set\",\n valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _enum(Class, values, params) {\n const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;\n // if (Array.isArray(values)) {\n // for (const value of values) {\n // entries[value] = value;\n // }\n // } else {\n // Object.assign(entries, values);\n // }\n // const entries: util.EnumLike = {};\n // for (const val of values) {\n // entries[val] = val;\n // }\n return new Class({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\n/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead.\n *\n * ```ts\n * enum Colors { red, green, blue }\n * z.enum(Colors);\n * ```\n */\nexport function _nativeEnum(Class, entries, params) {\n return new Class({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _literal(Class, value, params) {\n return new Class({\n type: \"literal\",\n values: Array.isArray(value) ? value : [value],\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _file(Class, params) {\n return new Class({\n type: \"file\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _transform(Class, fn) {\n return new Class({\n type: \"transform\",\n transform: fn,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _optional(Class, innerType) {\n return new Class({\n type: \"optional\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nullable(Class, innerType) {\n return new Class({\n type: \"nullable\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _default(Class, innerType, defaultValue) {\n return new Class({\n type: \"default\",\n innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nonoptional(Class, innerType, params) {\n return new Class({\n type: \"nonoptional\",\n innerType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _success(Class, innerType) {\n return new Class({\n type: \"success\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _catch(Class, innerType, catchValue) {\n return new Class({\n type: \"catch\",\n innerType,\n catchValue: (typeof catchValue === \"function\" ? catchValue : util.constantCatch(catchValue)),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _pipe(Class, in_, out) {\n return new Class({\n type: \"pipe\",\n in: in_,\n out,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _readonly(Class, innerType) {\n return new Class({\n type: \"readonly\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _templateLiteral(Class, parts, params) {\n return new Class({\n type: \"template_literal\",\n parts,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lazy(Class, getter) {\n return new Class({\n type: \"lazy\",\n getter,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _promise(Class, innerType) {\n return new Class({\n type: \"promise\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _custom(Class, fn, _params) {\n const norm = util.normalizeParams(_params);\n norm.abort ?? (norm.abort = true); // default to abort:false\n const schema = new Class({\n type: \"custom\",\n check: \"custom\",\n fn: fn,\n ...norm,\n });\n return schema;\n}\n// same as _custom but defaults to abort:false\n// @__NO_SIDE_EFFECTS__\nexport function _refine(Class, fn, _params) {\n const schema = new Class({\n type: \"custom\",\n check: \"custom\",\n fn: fn,\n ...util.normalizeParams(_params),\n });\n return schema;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _superRefine(fn, params) {\n const ch = _check((payload) => {\n payload.addIssue = (issue) => {\n if (typeof issue === \"string\") {\n payload.issues.push(util.issue(issue, payload.value, ch._zod.def));\n }\n else {\n // for Zod 3 backwards compatibility\n const _issue = issue;\n if (_issue.fatal)\n _issue.continue = false;\n _issue.code ?? (_issue.code = \"custom\");\n if (!(\"input\" in _issue))\n _issue.input = payload.value;\n _issue.inst ?? (_issue.inst = ch);\n _issue.continue ?? (_issue.continue = !ch._zod.def.abort); // abort is always undefined, so this is always true...\n payload.issues.push(util.issue(_issue));\n }\n };\n return fn(payload.value, payload);\n }, params);\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _check(fn, params) {\n const ch = new checks.$ZodCheck({\n check: \"custom\",\n ...util.normalizeParams(params),\n });\n ch._zod.check = fn;\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function describe(description) {\n const ch = new checks.$ZodCheck({ check: \"describe\" });\n ch._zod.onattach = [\n (inst) => {\n const existing = registries.globalRegistry.get(inst) ?? {};\n registries.globalRegistry.add(inst, { ...existing, description });\n },\n ];\n ch._zod.check = () => { }; // no-op check\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function meta(metadata) {\n const ch = new checks.$ZodCheck({ check: \"meta\" });\n ch._zod.onattach = [\n (inst) => {\n const existing = registries.globalRegistry.get(inst) ?? {};\n registries.globalRegistry.add(inst, { ...existing, ...metadata });\n },\n ];\n ch._zod.check = () => { }; // no-op check\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _stringbool(Classes, _params) {\n const params = util.normalizeParams(_params);\n let truthyArray = params.truthy ?? [\"true\", \"1\", \"yes\", \"on\", \"y\", \"enabled\"];\n let falsyArray = params.falsy ?? [\"false\", \"0\", \"no\", \"off\", \"n\", \"disabled\"];\n if (params.case !== \"sensitive\") {\n truthyArray = truthyArray.map((v) => (typeof v === \"string\" ? v.toLowerCase() : v));\n falsyArray = falsyArray.map((v) => (typeof v === \"string\" ? v.toLowerCase() : v));\n }\n const truthySet = new Set(truthyArray);\n const falsySet = new Set(falsyArray);\n const _Codec = Classes.Codec ?? schemas.$ZodCodec;\n const _Boolean = Classes.Boolean ?? schemas.$ZodBoolean;\n const _String = Classes.String ?? schemas.$ZodString;\n const stringSchema = new _String({ type: \"string\", error: params.error });\n const booleanSchema = new _Boolean({ type: \"boolean\", error: params.error });\n const codec = new _Codec({\n type: \"pipe\",\n in: stringSchema,\n out: booleanSchema,\n transform: ((input, payload) => {\n let data = input;\n if (params.case !== \"sensitive\")\n data = data.toLowerCase();\n if (truthySet.has(data)) {\n return true;\n }\n else if (falsySet.has(data)) {\n return false;\n }\n else {\n payload.issues.push({\n code: \"invalid_value\",\n expected: \"stringbool\",\n values: [...truthySet, ...falsySet],\n input: payload.value,\n inst: codec,\n continue: false,\n });\n return {};\n }\n }),\n reverseTransform: ((input, _payload) => {\n if (input === true) {\n return truthyArray[0] || \"true\";\n }\n else {\n return falsyArray[0] || \"false\";\n }\n }),\n error: params.error,\n });\n codec._zod.bag.truthy = truthyArray;\n codec._zod.bag.falsy = falsyArray;\n codec._zod.bag.case = params.case ?? \"insensitive\";\n return codec;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _stringFormat(Class, format, fnOrRegex, _params = {}) {\n const params = util.normalizeParams(_params);\n const def = {\n check: \"string_format\",\n type: \"string\",\n format,\n fn: typeof fnOrRegex === \"function\" ? fnOrRegex : (val) => fnOrRegex.test(val),\n ...params,\n };\n if (fnOrRegex instanceof RegExp) {\n def.pattern = fnOrRegex;\n }\n const inst = new Class(def);\n return inst;\n}\n","import { globalRegistry } from \"./registries.js\";\nimport { assignProp } from \"./util.js\";\nfunction assignProps(target, ...sources) {\n for (const source of sources) {\n for (const key of Reflect.ownKeys(source)) {\n if (Object.prototype.propertyIsEnumerable.call(source, key)) {\n assignProp(target, key, source[key]);\n }\n }\n }\n return target;\n}\n// function initializeContext<T extends schemas.$ZodType>(inputs: JSONSchemaGeneratorParams<T>): ToJSONSchemaContext<T> {\n// return {\n// processor: inputs.processor,\n// metadataRegistry: inputs.metadata ?? globalRegistry,\n// target: inputs.target ?? \"draft-2020-12\",\n// unrepresentable: inputs.unrepresentable ?? \"throw\",\n// };\n// }\nexport function initializeContext(params) {\n // Normalize target: convert old non-hyphenated versions to hyphenated versions\n let target = params?.target ?? \"draft-2020-12\";\n if (target === \"draft-4\")\n target = \"draft-04\";\n if (target === \"draft-7\")\n target = \"draft-07\";\n return {\n processors: params.processors ?? {},\n metadataRegistry: params?.metadata ?? globalRegistry,\n target,\n unrepresentable: params?.unrepresentable ?? \"throw\",\n override: params?.override ?? (() => { }),\n io: params?.io ?? \"output\",\n counter: 0,\n seen: new Map(),\n sharedDefsExtractedFor: undefined,\n sharedEmitDoneFor: undefined,\n cycles: params?.cycles ?? \"ref\",\n reused: params?.reused ?? \"inline\",\n intersections: [],\n deferred: [],\n external: params?.external ?? undefined,\n };\n}\n/**\n * Applies the `unrepresentable` setting at a site that has no JSON Schema equivalent. Throws\n * `message` unless the setting (or the handler's return value) says otherwise. Returns `true` if a\n * custom JSON Schema was written into `json`, in which case the caller must not write its own.\n */\nexport function handleUnrepresentable(schema, ctx, json, params, message) {\n const result = typeof ctx.unrepresentable === \"function\"\n ? ctx.unrepresentable({ zodSchema: schema, path: params.path, message })\n : ctx.unrepresentable;\n if (result === \"any\")\n return false;\n if (result === undefined || result === \"throw\")\n throw new Error(message);\n Object.assign(json, result);\n return true;\n}\n// never rename this back to `process`: bundler polyfills inject a top-level `const process` that a lexical declaration of the same name collides with (#6397)\nexport function processSchema(schema, ctx, _params = { path: [], schemaPath: [] }) {\n var _a;\n const def = schema._zod.def;\n // check for schema in seens\n const seen = ctx.seen.get(schema);\n if (seen) {\n seen.count++;\n // check if cycle\n const isCycle = _params.schemaPath.includes(schema);\n if (isCycle) {\n seen.cycle = _params.path;\n }\n return seen.schema;\n }\n // initialize\n const result = { schema: {}, count: 1, cycle: undefined, path: _params.path };\n ctx.seen.set(schema, result);\n ctx.sharedDefsExtractedFor = undefined;\n ctx.sharedEmitDoneFor = undefined;\n // custom method overrides default behavior\n const overrideSchema = schema._zod.toJSONSchema?.();\n if (overrideSchema) {\n result.schema = overrideSchema;\n }\n else {\n const params = {\n ..._params,\n schemaPath: [..._params.schemaPath, schema],\n path: _params.path,\n };\n if (schema._zod.processJSONSchema) {\n schema._zod.processJSONSchema(ctx, result.schema, params);\n }\n else {\n const _json = result.schema;\n const processor = ctx.processors[def.type];\n if (!processor) {\n throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`);\n }\n processor(schema, ctx, _json, params);\n }\n const parent = schema._zod.parent;\n if (parent) {\n // Also set ref if processor didn't (for inheritance)\n if (!result.ref)\n result.ref = parent;\n processSchema(parent, ctx, params);\n ctx.seen.get(parent).isParent = true;\n }\n }\n // metadata\n const meta = ctx.metadataRegistry.get(schema);\n if (meta)\n assignProps(result.schema, meta);\n if (ctx.io === \"input\" && isTransforming(schema)) {\n // examples/defaults only apply to output type of pipe\n delete result.schema.examples;\n delete result.schema.default;\n }\n // set prefault as default\n if (ctx.io === \"input\" && \"_prefault\" in result.schema)\n (_a = result.schema).default ?? (_a.default = result.schema._prefault);\n delete result.schema._prefault;\n // pulling fresh from ctx.seen in case it was overwritten\n const _result = ctx.seen.get(schema);\n return _result.schema;\n}\n/** @deprecated Renamed to `processSchema`. An export alias declares no binding, so it is safe to keep. */\nexport { processSchema as process };\n// Escape a reference token for use in a JSON Pointer fragment (RFC 6901): `~` becomes `~0` and `/` becomes `~1`. The `~` replacement must run first.\nfunction encodeJSONPointerSegment(segment) {\n return segment.replace(/~/g, \"~0\").replace(/\\//g, \"~1\");\n}\nexport function extractDefs(ctx, schema\n// params: EmitParams\n) {\n // iterate over seen map;\n const root = ctx.seen.get(schema);\n if (!root)\n throw new Error(\"Unprocessed schema. This is a bug in Zod.\");\n // With `external` set, every registered schema resolves through the external branch of `makeURI`, so the root branch below produces the same ref the external branch would — this pass is identical whichever schema it is called with, and only needs to run once.\n if (ctx.external && ctx.sharedDefsExtractedFor === ctx.external)\n return;\n // Track ids to detect duplicates across different schemas\n const idToSchema = new Map();\n for (const entry of ctx.seen.entries()) {\n const id = ctx.metadataRegistry.get(entry[0])?.id;\n if (id) {\n const existing = idToSchema.get(id);\n if (existing && existing !== entry[0]) {\n throw new Error(`Duplicate schema id \"${id}\" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);\n }\n idToSchema.set(id, entry[0]);\n }\n }\n // returns a ref to the schema defId will be empty if the ref points to an external schema (or #)\n const makeURI = (entry) => {\n // comparing the seen objects because sometimes multiple schemas map to the same seen object. e.g. lazy\n // external is configured\n const defsSegment = ctx.target === \"draft-2020-12\" ? \"$defs\" : \"definitions\";\n if (ctx.external) {\n const externalId = ctx.external.registry.get(entry[0])?.id; // ?? \"__shared\";// `__schema${ctx.counter++}`;\n // check if schema is in the external registry\n const uriGenerator = ctx.external.uri ?? ((id) => id);\n if (externalId) {\n return { ref: uriGenerator(externalId) };\n }\n // otherwise, add to __shared\n const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`;\n entry[1].defId = id; // set defId so it will be reused if needed\n return { defId: id, ref: `${uriGenerator(\"__shared\")}#/${defsSegment}/${encodeJSONPointerSegment(id)}` };\n }\n const uriPrefix = `#`;\n const defUriPrefix = `${uriPrefix}/${defsSegment}/`;\n // an id-less root has nowhere to be extracted to, so it stays inline and self-references as `#`\n if (entry[1] === root && !entry[1].schema.id) {\n return { ref: uriPrefix };\n }\n // self-contained schema\n const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`;\n return { defId, ref: defUriPrefix + encodeJSONPointerSegment(defId) };\n };\n // stored cached version in `def` property remove all properties, set $ref\n const extractToDef = (entry) => {\n // if the schema is already a reference, do not extract it\n if (entry[1].schema.$ref) {\n return;\n }\n const seen = entry[1];\n const { ref, defId } = makeURI(entry);\n seen.def = { ...seen.schema };\n // defId won't be set if the schema is a reference to an external schema or if the schema is the root schema\n if (defId)\n seen.defId = defId;\n // wipe away all properties except $ref\n const schema = seen.schema;\n for (const key in schema) {\n delete schema[key];\n }\n schema.$ref = ref;\n };\n // throw on cycles\n // break cycles\n if (ctx.cycles === \"throw\") {\n for (const entry of ctx.seen.entries()) {\n const seen = entry[1];\n if (seen.cycle) {\n throw new Error(\"Cycle detected: \" +\n `#/${seen.cycle?.join(\"/\")}/<root>` +\n '\\n\\nSet the `cycles` parameter to `\"ref\"` to resolve cyclical schemas with defs.');\n }\n }\n }\n // extract schemas into $defs\n for (const entry of ctx.seen.entries()) {\n const seen = entry[1];\n // convert root schema to # $ref\n if (schema === entry[0]) {\n extractToDef(entry); // this has special handling for the root schema\n continue;\n }\n // extract schemas that are in the external registry\n if (ctx.external) {\n const ext = ctx.external.registry.get(entry[0])?.id;\n if (schema !== entry[0] && ext) {\n extractToDef(entry);\n continue;\n }\n }\n // extract schemas with `id` meta\n const id = ctx.metadataRegistry.get(entry[0])?.id;\n if (id) {\n extractToDef(entry);\n continue;\n }\n // break cycles\n if (seen.cycle) {\n // any\n extractToDef(entry);\n continue;\n }\n // extract reused schemas\n if (seen.count > 1) {\n if (ctx.reused === \"ref\") {\n extractToDef(entry);\n }\n }\n }\n if (ctx.external)\n ctx.sharedDefsExtractedFor = ctx.external;\n}\n/** Rewrites `anyOf: [{type: \"a\"}, {type: \"b\"}]` to `type: [\"a\", \"b\"]`, which every JSON Schema draft treats as equivalent and most consumers render far better for the nullable case. Only branches that are a bare type assertion qualify — anything carrying a constraint, `$ref`, `const` or metadata is left alone. Runs after `flattenRef`, so a branch an override decorated or `$defs` extraction turned into a `$ref` is no longer bare and correctly stays in `anyOf`. `oneOf` is excluded: `integer` and `number` overlap, so \"exactly one\" and \"at least one\" are not the same there. OpenAPI 3.0 is excluded: its `type` must be a single string. */\nfunction compactTypeUnion(schema) {\n const options = schema.anyOf;\n if (!Array.isArray(options) || options.length === 0 || schema.type !== undefined)\n return;\n const types = [];\n for (const option of options) {\n if (!option || typeof option !== \"object\")\n return;\n // A branch that is itself a compactible union folds into this one — nested `anyOf` and a flat `type` array say the same thing. Compacting it first also makes the result independent of the order this pass walks the seen map in.\n compactTypeUnion(option);\n const keys = Object.keys(option);\n if (keys.length !== 1 || keys[0] !== \"type\")\n return;\n const type = option.type;\n for (const member of Array.isArray(type) ? type : [type]) {\n if (typeof member !== \"string\")\n return;\n if (!types.includes(member))\n types.push(member);\n }\n }\n delete schema.anyOf;\n // A `type` array must be non-empty and unique (metaschema); a single member is spelled as a bare string.\n schema.type = types.length === 1 ? types[0] : types;\n}\n/** Keywords `foldIntersection` knows how to combine. Anything else — `$ref`, `patternProperties`,\n * an annotation like `description` — makes a member unfoldable, so a constraint this does not\n * understand leaves the `allOf` alone instead of being silently dropped or misattributed. */\nconst FOLDABLE_KEYS = new Set([\"type\", \"properties\", \"required\", \"additionalProperties\"]);\nconst UNION_KEYS = [\"oneOf\", \"anyOf\"];\n/** A member's constraint on a key it does not declare itself. A `catchall` states one; `false`, an absent `additionalProperties`, and the empty schema a loose object emits state nothing. */\nfunction undeclaredConstraint(member) {\n const extra = member.additionalProperties;\n if (extra === undefined || extra === false || typeof extra !== \"object\" || extra === null)\n return null;\n return Object.keys(extra).length ? extra : null;\n}\n/** Combines object members into the single object they describe together, or returns `null` if any of them carries a keyword outside {@link FOLDABLE_KEYS}. */\nfunction foldObjects(members) {\n const objects = [];\n for (const member of members) {\n // A boolean subschema is legal JSON Schema and carries no keywords to fold.\n if (typeof member !== \"object\" || member.type !== \"object\")\n return null;\n for (const key in member) {\n if (!FOLDABLE_KEYS.has(key))\n return null;\n }\n objects.push(member);\n }\n const properties = {};\n const required = new Set();\n for (const object of objects) {\n for (const key in object.properties) {\n // `in` would report a `__proto__` key as already present via the prototype chain and skip it.\n if (Object.prototype.hasOwnProperty.call(properties, key))\n continue;\n // Every member constrains this key: the ones that declare it say how, and a `catchall` member constrains it too even though it does not name it. The key has to satisfy all of them, which is the same intersection one level down.\n const parts = [];\n for (const other of objects) {\n const part = other.properties?.[key] ?? undeclaredConstraint(other);\n if (part === null || part === undefined)\n continue;\n if (!parts.some((seen) => JSON.stringify(seen) === JSON.stringify(part)))\n parts.push(part);\n }\n const merged = parts.length === 1\n ? parts[0]\n : (foldObjects(parts) ?? { allOf: parts });\n assignProp(properties, key, merged);\n }\n for (const key of object.required ?? [])\n required.add(key);\n }\n const folded = { type: \"object\", properties };\n if (required.size)\n folded.required = [...required];\n // A key no member declares is rejected only when every member rejects it, so the fold is closed only when every member is. Otherwise it carries whatever the `catchall` members demand of such a key.\n if (objects.every((object) => object.additionalProperties === false)) {\n folded.additionalProperties = false;\n }\n else {\n const constraints = [];\n for (const object of objects) {\n const constraint = undeclaredConstraint(object);\n if (constraint && !constraints.some((seen) => JSON.stringify(seen) === JSON.stringify(constraint)))\n constraints.push(constraint);\n }\n if (constraints.length === 1)\n folded.additionalProperties = constraints[0];\n else if (constraints.length > 1)\n folded.additionalProperties = { allOf: constraints };\n }\n return folded;\n}\n/** `additionalProperties` in an `allOf` member sees only that member's own `properties`, so two\n * closed object members reject each other's keys and the schema validates nothing. Zod's parser\n * pools the key sets instead — `handleIntersectionResults` reports a key as unrecognized only when\n * *every* side rejects it — so the emitted schema has to pool them too, and folding the members\n * into one object is the encoding that says so on every target.\n *\n * This runs from `finalize`, after `extractDefs`, which is what keeps it clear of the `$ref`\n * machinery: a member extracted into `$defs` is already a `$ref` by now and declines to fold, so it\n * keeps its reference and its own closedness rather than being inlined as a stale copy. */\nfunction foldIntersection(json) {\n const allOf = json.allOf;\n if (!Array.isArray(allOf) || allOf.length < 2)\n return;\n // An `override` runs before this pass and may have written object keywords onto the intersection itself. Those are deliberate, so decline rather than overwrite them.\n for (const key of FOLDABLE_KEYS)\n if (key in json)\n return;\n // An intersection distributes over a union: `A & (X | Y)` is `(A & X) | (A & Y)`. Only the first union is distributed over; a second one stays among the members every branch folds against, where it fails the object check and declines the whole intersection rather than multiplying out.\n const unions = allOf.filter((m) => UNION_KEYS.some((k) => Array.isArray(m[k])));\n let folded = null;\n if (!unions.length) {\n folded = foldObjects(allOf);\n }\n else {\n const union = unions[0];\n const keyword = UNION_KEYS.find((k) => Array.isArray(union[k]));\n if (Object.keys(union).length !== 1)\n return;\n const rest = allOf.filter((m) => m !== union);\n const branches = union[keyword].map((branch) => foldObjects([...rest, branch]));\n if (branches.some((b) => !b))\n return;\n folded = { [keyword]: branches };\n }\n if (!folded)\n return;\n delete json.allOf;\n assignProps(json, folded);\n}\nexport function finalize(ctx, schema) {\n const root = ctx.seen.get(schema);\n if (!root)\n throw new Error(\"Unprocessed schema. This is a bug in Zod.\");\n // flatten refs - inherit properties from parent schemas\n const flattenRef = (zodSchema) => {\n const seen = ctx.seen.get(zodSchema);\n // already processed\n if (seen.ref === null)\n return;\n const schema = seen.def ?? seen.schema;\n const _cached = { ...schema };\n const ref = seen.ref;\n seen.ref = null; // prevent infinite recursion\n if (ref) {\n flattenRef(ref);\n const refSeen = ctx.seen.get(ref);\n const refSchema = refSeen.schema;\n // merge referenced schema into current\n if (refSchema.$ref && (ctx.target === \"draft-07\" || ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\")) {\n // older drafts can't combine $ref with other properties\n schema.allOf = schema.allOf ?? [];\n schema.allOf.push(refSchema);\n }\n else {\n assignProps(schema, refSchema);\n }\n // restore child's own properties (child wins)\n assignProps(schema, _cached);\n const isParentRef = zodSchema._zod.parent === ref;\n // For parent chain, child is a refinement - remove parent-only properties\n if (isParentRef) {\n for (const key in schema) {\n if (key === \"$ref\" || key === \"allOf\")\n continue;\n if (!(key in _cached)) {\n delete schema[key];\n }\n }\n }\n // When ref was extracted to $defs, remove properties that match the definition\n if (refSchema.$ref && refSeen.def) {\n for (const key in schema) {\n if (key === \"$ref\" || key === \"allOf\")\n continue;\n if (key in refSeen.def && JSON.stringify(schema[key]) === JSON.stringify(refSeen.def[key])) {\n delete schema[key];\n }\n }\n }\n }\n // If parent was extracted (has $ref), propagate $ref to this schema. This handles cases like: readonly().meta({id}).describe() where processor sets ref to innerType but parent should be referenced\n const parent = zodSchema._zod.parent;\n if (parent && parent !== ref) {\n // Ensure parent is processed first so its def has inherited properties\n flattenRef(parent);\n const parentSeen = ctx.seen.get(parent);\n if (parentSeen?.schema.$ref) {\n schema.$ref = parentSeen.schema.$ref;\n // De-duplicate with parent's definition\n if (parentSeen.def) {\n for (const key in schema) {\n if (key === \"$ref\" || key === \"allOf\")\n continue;\n if (key in parentSeen.def && JSON.stringify(schema[key]) === JSON.stringify(parentSeen.def[key])) {\n delete schema[key];\n }\n }\n }\n }\n }\n // execute overrides\n ctx.override({\n zodSchema: zodSchema,\n jsonSchema: schema,\n path: seen.path ?? [],\n });\n };\n // Flattening walks the whole map and clears each `ref` as it goes, so a second call over the same map is a no-op scan. Skip it outright once it has run for a registry conversion.\n if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) {\n for (const entry of [...ctx.seen.entries()].reverse()) {\n flattenRef(entry[0]);\n }\n if (ctx.target !== \"openapi-3.0\") {\n for (const entry of ctx.seen.entries()) {\n compactTypeUnion(entry[1].def ?? entry[1].schema);\n }\n }\n for (const rewrite of ctx.deferred)\n rewrite();\n // After flattening, every member that was extracted is a `$ref`, so the fold sees the final shape. A schema that inherits an intersection — through `z.lazy`, or any `ref` chain — holds the same `allOf` array, so fold by array identity to catch every copy.\n if (ctx.intersections.length) {\n const carriers = new Map();\n for (const seen of ctx.seen.values()) {\n for (const json of [seen.schema, seen.def]) {\n const allOf = json?.allOf;\n if (!Array.isArray(allOf))\n continue;\n const existing = carriers.get(allOf);\n if (existing)\n existing.push(json);\n else\n carriers.set(allOf, [json]);\n }\n }\n for (const allOf of ctx.intersections) {\n for (const json of carriers.get(allOf) ?? [])\n foldIntersection(json);\n }\n }\n }\n const result = {};\n if (ctx.target === \"draft-2020-12\") {\n result.$schema = \"https://json-schema.org/draft/2020-12/schema\";\n }\n else if (ctx.target === \"draft-07\") {\n result.$schema = \"http://json-schema.org/draft-07/schema#\";\n }\n else if (ctx.target === \"draft-04\") {\n result.$schema = \"http://json-schema.org/draft-04/schema#\";\n }\n else if (ctx.target === \"openapi-3.0\") {\n // OpenAPI 3.0 schema objects should not include a $schema property\n }\n else {\n // Arbitrary string values are allowed but won't have a $schema property set\n }\n if (ctx.external?.uri) {\n const id = ctx.external.registry.get(schema)?.id;\n if (!id)\n throw new Error(\"Schema is missing an `id` property\");\n result.$id = ctx.external.uri(id);\n }\n // when the root was extracted into $defs, `root.schema` is the `$ref` wrapper and `root.def` is the body that now lives under $defs\n assignProps(result, root.defId ? root.schema : (root.def ?? root.schema));\n // The `id` in `.meta()` is a Zod-specific registration tag used to extract schemas into $defs — it is not user-facing JSON Schema metadata. Strip it from the output body where it would otherwise leak. The id is preserved implicitly via the $defs key (and via $ref paths).\n const rootMetaId = ctx.metadataRegistry.get(schema)?.id;\n if (rootMetaId !== undefined && result.id === rootMetaId)\n delete result.id;\n // build defs object. With `external`, `defs` is the shared object every schema writes into, so the same entries are reassigned on every call. Without it, `defs` is fresh per call and must be rebuilt.\n const defs = ctx.external?.defs ?? {};\n if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) {\n for (const entry of ctx.seen.entries()) {\n const seen = entry[1];\n if (seen.def && seen.defId) {\n if (seen.def.id === seen.defId)\n delete seen.def.id;\n assignProp(defs, seen.defId, seen.def);\n }\n }\n }\n if (ctx.external)\n ctx.sharedEmitDoneFor = ctx.external;\n // set definitions in result\n if (ctx.external) {\n }\n else {\n if (Object.keys(defs).length > 0) {\n if (ctx.target === \"draft-2020-12\") {\n result.$defs = defs;\n }\n else {\n result.definitions = defs;\n }\n }\n }\n try {\n // this \"finalizes\" this schema and ensures all cycles are removed each call to finalize() is functionally independent though the seen map is shared\n const finalized = JSON.parse(JSON.stringify(result));\n Object.defineProperty(finalized, \"~standard\", {\n value: {\n ...schema[\"~standard\"],\n jsonSchema: {\n input: createStandardJSONSchemaMethod(schema, \"input\", ctx.processors),\n output: createStandardJSONSchemaMethod(schema, \"output\", ctx.processors),\n },\n },\n enumerable: false,\n writable: false,\n });\n return finalized;\n }\n catch (_err) {\n throw new Error(\"Error converting schema to JSON.\");\n }\n}\nfunction isTransforming(_schema, _ctx) {\n const ctx = _ctx ?? { seen: new Set() };\n if (ctx.seen.has(_schema))\n return false;\n ctx.seen.add(_schema);\n const def = _schema._zod.def;\n if (def.type === \"transform\")\n return true;\n if (def.type === \"array\")\n return isTransforming(def.element, ctx);\n if (def.type === \"set\")\n return isTransforming(def.valueType, ctx);\n if (def.type === \"lazy\")\n return isTransforming(def.getter(), ctx);\n if (def.type === \"promise\" ||\n def.type === \"optional\" ||\n def.type === \"nonoptional\" ||\n def.type === \"nullable\" ||\n def.type === \"readonly\" ||\n def.type === \"default\" ||\n def.type === \"prefault\" ||\n def.type === \"catch\") {\n return isTransforming(def.innerType, ctx);\n }\n if (def.type === \"intersection\") {\n return isTransforming(def.left, ctx) || isTransforming(def.right, ctx);\n }\n if (def.type === \"record\" || def.type === \"map\") {\n return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx);\n }\n if (def.type === \"pipe\") {\n if (_schema._zod.traits.has(\"$ZodCodec\"))\n return true;\n return isTransforming(def.in, ctx) || isTransforming(def.out, ctx);\n }\n if (def.type === \"object\") {\n for (const key in def.shape) {\n if (isTransforming(def.shape[key], ctx))\n return true;\n }\n return false;\n }\n if (def.type === \"union\") {\n for (const option of def.options) {\n if (isTransforming(option, ctx))\n return true;\n }\n return false;\n }\n if (def.type === \"tuple\") {\n for (const item of def.items) {\n if (isTransforming(item, ctx))\n return true;\n }\n if (def.rest && isTransforming(def.rest, ctx))\n return true;\n return false;\n }\n return false;\n}\n/**\n * Creates a toJSONSchema method for a schema instance.\n * This encapsulates the logic of initializing context, processing, extracting defs, and finalizing.\n */\nexport const createToJSONSchemaMethod = (schema, processors = {}) => (params) => {\n const ctx = initializeContext({ ...params, processors });\n processSchema(schema, ctx);\n extractDefs(ctx, schema);\n return finalize(ctx, schema);\n};\nexport const createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => {\n const { libraryOptions, target } = params ?? {};\n const ctx = initializeContext({ ...(libraryOptions ?? {}), target, io, processors });\n processSchema(schema, ctx);\n extractDefs(ctx, schema);\n return finalize(ctx, schema);\n};\n","import * as regexes from \"./regexes.js\";\nimport { base64Charset, base64urlCharset } from \"./schemas.js\";\nimport { extractDefs, finalize, handleUnrepresentable, initializeContext, processSchema, } from \"./to-json-schema.js\";\nimport { BIGINT_FORMAT_RANGES, NUMBER_FORMAT_RANGES, assignProp, getEnumValues } from \"./util.js\";\nconst narrowMin = (agg, key, value) => {\n if (agg[key] === undefined || value > agg[key])\n agg[key] = value;\n};\nconst narrowMax = (agg, key, value) => {\n if (agg[key] === undefined || value < agg[key])\n agg[key] = value;\n};\nconst narrowBoth = (agg, value) => {\n narrowMin(agg, \"minimum\", value);\n narrowMax(agg, \"maximum\", value);\n};\nconst addDivisor = (agg, value) => {\n agg.multipleOf ?? (agg.multipleOf = []);\n if (!agg.multipleOf.includes(value))\n agg.multipleOf.push(value);\n};\nconst addPattern = (agg, pattern) => {\n agg.patterns ?? (agg.patterns = new Set());\n agg.patterns.add(pattern);\n};\nconst intersectMime = (agg, mime) => {\n agg.mime = agg.mime ? agg.mime.filter((m) => mime.includes(m)) : [...mime];\n};\n// last-wins, matching the bag's historical write order; the flag keeps an integer format from being lost to a later float one\nconst setFormat = (agg, format) => {\n agg.format = format;\n if (format.includes(\"int\"))\n agg.isInt = true;\n};\nconst minContributor = (agg, def) => narrowMin(agg, \"minimum\", def.minimum);\nconst maxContributor = (agg, def) => narrowMax(agg, \"maximum\", def.maximum);\nconst formatContributor = (ranges) => (agg, def) => {\n setFormat(agg, def.format);\n const [minimum, maximum] = ranges[def.format];\n narrowMin(agg, \"minimum\", minimum);\n narrowMax(agg, \"maximum\", maximum);\n};\nconst contributors = {\n greater_than: (agg, def) => narrowMin(agg, def.inclusive ? \"minimum\" : \"exclusiveMinimum\", def.value),\n less_than: (agg, def) => narrowMax(agg, def.inclusive ? \"maximum\" : \"exclusiveMaximum\", def.value),\n multiple_of: (agg, def) => addDivisor(agg, def.value),\n number_format: formatContributor(NUMBER_FORMAT_RANGES),\n bigint_format: formatContributor(BIGINT_FORMAT_RANGES),\n min_length: minContributor,\n max_length: maxContributor,\n length_equals: (agg, def) => narrowBoth(agg, def.length),\n min_size: minContributor,\n max_size: maxContributor,\n size_equals: (agg, def) => narrowBoth(agg, def.size),\n string_format: (agg, def) => {\n setFormat(agg, def.format);\n if (def.pattern)\n addPattern(agg, def.pattern);\n if (def.format === \"base64\" || def.format === \"base64url\")\n agg.contentEncoding = def.format;\n if (def.local || def.precision === -1)\n agg.laxFormat = true;\n },\n mime_type: (agg, def) => intersectMime(agg, def.mime),\n};\nexport function aggregateChecks(schema) {\n const agg = {};\n const def = schema._zod.def;\n // a format schema is its own first check, same rule as $ZodType init\n const list = schema._zod.traits.has(\"$ZodCheck\")\n ? [schema, ...(def.checks ?? [])]\n : (def.checks ?? []);\n for (const ch of list)\n contributors[ch._zod.def.check]?.(agg, ch._zod.def);\n // reconcile with the bag so third-party onattach contributions still land; first-party residue is never tighter than the fold, so merging it back is idempotent for one and additive for the other\n const bag = schema._zod.bag;\n if (bag.minimum !== undefined)\n narrowMin(agg, \"minimum\", bag.minimum);\n if (bag.exclusiveMinimum !== undefined)\n narrowMin(agg, \"exclusiveMinimum\", bag.exclusiveMinimum);\n if (bag.maximum !== undefined)\n narrowMax(agg, \"maximum\", bag.maximum);\n if (bag.exclusiveMaximum !== undefined)\n narrowMax(agg, \"exclusiveMaximum\", bag.exclusiveMaximum);\n if (bag.multipleOf !== undefined)\n addDivisor(agg, bag.multipleOf);\n if (bag.format !== undefined) {\n agg.format ?? (agg.format = bag.format);\n if (bag.format.includes(\"int\"))\n agg.isInt = true;\n }\n if (bag.mime)\n intersectMime(agg, bag.mime);\n for (const pattern of bag.patterns ?? [])\n addPattern(agg, pattern);\n return agg;\n}\nconst formatMap = {\n guid: \"uuid\",\n url: \"uri\",\n datetime: \"date-time\",\n json_string: \"json-string\",\n regex: \"\", // do not set\n};\n// ==================== SIMPLE TYPE PROCESSORS ====================\n// the runtime patterns are lax so parse paths never overflow the regex stack; the emitted schema swaps in the exact block forms, which zod itself never executes\nconst exactPatterns = new Map([\n [base64Charset, regexes.base64],\n [base64urlCharset, regexes.base64url],\n]);\nconst exactPattern = (p) => exactPatterns.get(p) ?? p;\nexport const stringProcessor = (schema, ctx, _json, _params) => {\n const json = _json;\n json.type = \"string\";\n const { minimum, maximum, format, patterns, contentEncoding, laxFormat } = aggregateChecks(schema);\n if (typeof minimum === \"number\")\n json.minLength = minimum;\n if (typeof maximum === \"number\")\n json.maxLength = maximum;\n // custom pattern overrides format\n if (format) {\n json.format = formatMap[format] ?? format;\n if (json.format === \"\")\n delete json.format; // empty format is not valid\n // `z.iso.time()` is never full-time, and `laxFormat` carries the datetime shapes that also accept what their keyword forbids\n if (format === \"time\" || laxFormat) {\n delete json.format;\n }\n }\n if (contentEncoding)\n json.contentEncoding = contentEncoding;\n if (patterns && patterns.size > 0) {\n const patternList = [...patterns].map(exactPattern);\n if (patternList.length === 1)\n json.pattern = patternList[0].source;\n else if (patternList.length > 1) {\n json.allOf = [\n ...patternList.map((regex) => ({\n ...(ctx.target === \"draft-07\" || ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\"\n ? { type: \"string\" }\n : {}),\n pattern: regex.source,\n })),\n ];\n }\n }\n};\nexport const numberProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const { minimum, maximum, multipleOf, exclusiveMaximum, exclusiveMinimum, isInt } = aggregateChecks(schema);\n json.type = isInt ? \"integer\" : \"number\";\n // when both minimum and exclusiveMinimum exist, pick the more restrictive one\n const exMin = typeof exclusiveMinimum === \"number\" && exclusiveMinimum >= (minimum ?? Number.NEGATIVE_INFINITY);\n const exMax = typeof exclusiveMaximum === \"number\" && exclusiveMaximum <= (maximum ?? Number.POSITIVE_INFINITY);\n const legacy = ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\";\n if (exMin) {\n if (legacy) {\n json.minimum = exclusiveMinimum;\n json.exclusiveMinimum = true;\n }\n else {\n json.exclusiveMinimum = exclusiveMinimum;\n }\n }\n else if (typeof minimum === \"number\") {\n json.minimum = minimum;\n }\n if (exMax) {\n if (legacy) {\n json.maximum = exclusiveMaximum;\n json.exclusiveMaximum = true;\n }\n else {\n json.exclusiveMaximum = exclusiveMaximum;\n }\n }\n else if (typeof maximum === \"number\") {\n json.maximum = maximum;\n }\n if (multipleOf) {\n // JSON Schema requires a divisor strictly greater than zero, and a non-finite one does not survive JSON at all. A negative divisor accepts exactly what its absolute value accepts, so it still maps; zero, NaN and Infinity have no keyword form.\n const divisors = new Set();\n for (const divisor of multipleOf) {\n if (Number.isFinite(divisor) && divisor !== 0)\n divisors.add(Math.abs(divisor));\n else\n handleUnrepresentable(schema, ctx, json, params, `A multipleOf divisor of ${divisor} cannot be represented in JSON Schema`);\n }\n // chained divisors are a conjunction the keyword cannot carry alone, so extras ride an allOf, same as stacked patterns\n const [first, ...rest] = divisors;\n if (first !== undefined)\n json.multipleOf = first;\n if (rest.length)\n json.allOf = [...(json.allOf ?? []), ...rest.map((m) => ({ multipleOf: m }))];\n }\n};\nexport const booleanProcessor = (_schema, _ctx, json, _params) => {\n json.type = \"boolean\";\n};\nexport const bigintProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"BigInt cannot be represented in JSON Schema\");\n};\nexport const symbolProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Symbols cannot be represented in JSON Schema\");\n};\nexport const nullProcessor = (_schema, ctx, json, _params) => {\n if (ctx.target === \"openapi-3.0\") {\n json.type = \"string\";\n json.nullable = true;\n json.enum = [null];\n }\n else {\n json.type = \"null\";\n }\n};\nexport const undefinedProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Undefined cannot be represented in JSON Schema\");\n};\nexport const voidProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Void cannot be represented in JSON Schema\");\n};\nexport const neverProcessor = (_schema, _ctx, json, _params) => {\n json.not = {};\n};\nexport const anyProcessor = (_schema, _ctx, _json, _params) => {\n // empty schema accepts anything\n};\nexport const unknownProcessor = (_schema, _ctx, _json, _params) => {\n // empty schema accepts anything\n};\nexport const dateProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Date cannot be represented in JSON Schema\");\n};\nexport const enumProcessor = (schema, _ctx, json, _params) => {\n const def = schema._zod.def;\n const values = getEnumValues(def.entries);\n // an empty enum accepts nothing, same as z.never()\n if (values.length === 0) {\n json.not = {};\n return;\n }\n // Number enums can have both string and number values\n if (values.every((v) => typeof v === \"number\"))\n json.type = \"number\";\n if (values.every((v) => typeof v === \"string\"))\n json.type = \"string\";\n json.enum = values;\n};\nexport const literalProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n // a literal with no values accepts nothing, same as z.never()\n if (def.values.length === 0) {\n json.not = {};\n return;\n }\n const vals = [];\n for (const val of def.values) {\n if (val === undefined) {\n // a custom schema replaces the whole literal, so there is nothing left to accumulate\n if (handleUnrepresentable(schema, ctx, json, params, \"Literal `undefined` cannot be represented in JSON Schema\"))\n return;\n // otherwise do not add to vals\n }\n else if (typeof val === \"bigint\") {\n if (handleUnrepresentable(schema, ctx, json, params, \"BigInt literals cannot be represented in JSON Schema\"))\n return;\n vals.push(Number(val));\n }\n else {\n vals.push(val);\n }\n }\n if (vals.length === 0) {\n // do nothing (an undefined literal was stripped)\n }\n else if (vals.length === 1) {\n const val = vals[0];\n json.type = val === null ? \"null\" : typeof val;\n if (ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\") {\n json.enum = [val];\n }\n else {\n json.const = val;\n }\n }\n else {\n if (vals.every((v) => typeof v === \"number\"))\n json.type = \"number\";\n if (vals.every((v) => typeof v === \"string\"))\n json.type = \"string\";\n if (vals.every((v) => typeof v === \"boolean\"))\n json.type = \"boolean\";\n if (vals.every((v) => v === null))\n json.type = \"null\";\n json.enum = vals;\n }\n};\nexport const nanProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"NaN cannot be represented in JSON Schema\");\n};\nexport const templateLiteralProcessor = (schema, _ctx, json, _params) => {\n const _json = json;\n const pattern = schema._zod.pattern;\n if (!pattern)\n throw new Error(\"Pattern not found in template literal\");\n _json.type = \"string\";\n _json.pattern = pattern.source;\n};\nexport const fileProcessor = (schema, _ctx, json, _params) => {\n const _json = json;\n _json.type = \"string\";\n _json.format = \"binary\";\n _json.contentEncoding = \"binary\";\n const { minimum, maximum, mime } = aggregateChecks(schema);\n if (minimum !== undefined)\n _json.minLength = minimum;\n if (maximum !== undefined)\n _json.maxLength = maximum;\n if (!mime)\n return;\n // an empty intersection means the mime checks share no value, so nothing passes at runtime; `anyOf` must be non-empty, so the false schema is `not: {}`\n if (mime.length === 0)\n _json.not = {};\n else if (mime.length === 1)\n _json.contentMediaType = mime[0];\n // only contentMediaType differs, so the shared props stay at the root\n else\n _json.anyOf = mime.map((m) => ({ contentMediaType: m }));\n};\nexport const successProcessor = (_schema, _ctx, json, _params) => {\n json.type = \"boolean\";\n};\nexport const customProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Custom types cannot be represented in JSON Schema\");\n};\nexport const functionProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Function types cannot be represented in JSON Schema\");\n};\nexport const transformProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Transforms cannot be represented in JSON Schema\");\n};\nexport const mapProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Map cannot be represented in JSON Schema\");\n};\nexport const setProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Set cannot be represented in JSON Schema\");\n};\n// ==================== COMPOSITE TYPE PROCESSORS ====================\nexport const arrayProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n const { minimum, maximum } = aggregateChecks(schema);\n if (typeof minimum === \"number\")\n json.minItems = minimum;\n if (typeof maximum === \"number\")\n json.maxItems = maximum;\n json.type = \"array\";\n json.items = processSchema(def.element, ctx, {\n ...params,\n path: [...params.path, \"items\"],\n });\n};\n// Transform and catch set `optin = \"optional\"` at runtime so the parser lets them observe an\n// absent key, but their declared input type stays required. An input JSON Schema describes the\n// declared type, so resolve past them to the schema that actually carries the optionality.\n// Used by both `objectProcessor` (for `required`) and `tupleProcessor` (for `minItems`); see\n// wiki/optionality.md, \"The JSON Schema emitter reads the *static* value\".\nfunction inputOptin(schema) {\n const def = schema._zod.def;\n if (def.type === \"pipe\" && def.in._zod.traits.has(\"$ZodTransform\")) {\n return inputOptin(def.out);\n }\n if (def.type === \"catch\") {\n return inputOptin(def.innerType);\n }\n return schema._zod.optin;\n}\nexport const objectProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n const shape = def.shape;\n // dropping it while still emitting `additionalProperties: false` would emit a schema that rejects data this one requires\n const symbolKeys = Object.getOwnPropertySymbols(shape);\n if (symbolKeys.length &&\n handleUnrepresentable(schema, ctx, json, params, \"Symbol keys cannot be represented in JSON Schema\")) {\n return;\n }\n json.type = \"object\";\n json.properties = {};\n for (const key in shape) {\n // assignProp so a __proto__ key becomes an own property instead of hitting the inherited setter on the plain {} we build into\n assignProp(json.properties, key, processSchema(shape[key], ctx, {\n ...params,\n path: [...params.path, \"properties\", key],\n }));\n }\n // required keys\n const requiredKeys = [];\n for (const key of Object.keys(shape)) {\n const field = def.shape[key];\n if (ctx.io === \"input\" ? inputOptin(field) === undefined : field._zod.optout === undefined) {\n requiredKeys.push(key);\n }\n }\n if (requiredKeys.length > 0) {\n json.required = requiredKeys;\n }\n // catchall\n if (def.catchall?._zod.def.type === \"never\") {\n // strict\n json.additionalProperties = false;\n }\n else if (!def.catchall) {\n // regular\n if (ctx.io === \"output\")\n json.additionalProperties = false;\n }\n else if (def.catchall) {\n json.additionalProperties = processSchema(def.catchall, ctx, {\n ...params,\n path: [...params.path, \"additionalProperties\"],\n });\n }\n};\nexport const unionProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n // Exclusive unions (inclusive === false) use oneOf (exactly one match) instead of anyOf (one or more matches). This includes both z.xor() and discriminated unions\n const isExclusive = def.inclusive === false;\n const options = def.options.map((x, i) => processSchema(x, ctx, {\n ...params,\n path: [...params.path, isExclusive ? \"oneOf\" : \"anyOf\", i],\n }));\n if (isExclusive) {\n json.oneOf = options;\n }\n else {\n json.anyOf = options;\n }\n};\nexport const intersectionProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n const a = processSchema(def.left, ctx, {\n ...params,\n path: [...params.path, \"allOf\", 0],\n });\n const b = processSchema(def.right, ctx, {\n ...params,\n path: [...params.path, \"allOf\", 1],\n });\n const isSimpleIntersection = (val) => \"allOf\" in val && Object.keys(val).length === 1;\n const allOf = [\n ...(isSimpleIntersection(a) ? a.allOf : [a]),\n ...(isSimpleIntersection(b) ? b.allOf : [b]),\n ];\n json.allOf = allOf;\n // Recorded innermost first, so a nested intersection has already folded by the time this one is considered. The array is the handle rather than the schema, because a wrapper that inherits this schema shares the same array; `finalize` folds every object holding it. See `foldIntersection`.\n ctx.intersections.push(allOf);\n};\nexport const tupleProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n json.type = \"array\";\n const prefixPath = ctx.target === \"draft-2020-12\" ? \"prefixItems\" : \"items\";\n const restPath = ctx.target === \"draft-2020-12\" ? \"items\" : ctx.target === \"openapi-3.0\" ? \"items\" : \"additionalItems\";\n const prefixItems = def.items.map((x, i) => processSchema(x, ctx, {\n ...params,\n path: [...params.path, prefixPath, i],\n }));\n const rest = def.rest\n ? processSchema(def.rest, ctx, {\n ...params,\n path: [...params.path, restPath, ...(ctx.target === \"openapi-3.0\" ? [def.items.length] : [])],\n })\n : null;\n let minItems = def.items.length;\n while (minItems > 0) {\n const item = def.items[minItems - 1];\n const optional = ctx.io === \"input\" ? inputOptin(item) !== undefined : item._zod.optout === \"optional\";\n if (!optional)\n break;\n minItems--;\n }\n const maxItems = def.items.length;\n const isClosed = !def.rest;\n if (ctx.target === \"draft-2020-12\") {\n json.prefixItems = prefixItems;\n if (isClosed) {\n json.items = false;\n }\n else if (rest) {\n json.items = rest;\n }\n if (minItems > 0)\n json.minItems = minItems;\n if (isClosed)\n json.maxItems = maxItems;\n }\n else if (ctx.target === \"openapi-3.0\") {\n json.items = {\n anyOf: prefixItems,\n };\n if (rest) {\n json.items.anyOf.push(rest);\n }\n if (minItems > 0)\n json.minItems = minItems;\n if (isClosed)\n json.maxItems = maxItems;\n }\n else {\n json.items = prefixItems;\n if (isClosed) {\n json.additionalItems = false;\n }\n else if (rest) {\n json.additionalItems = rest;\n }\n if (minItems > 0)\n json.minItems = minItems;\n if (isClosed)\n json.maxItems = maxItems;\n }\n // explicit user-defined length checks take precedence\n const { minimum, maximum } = aggregateChecks(schema);\n if (typeof minimum === \"number\")\n json.minItems = minimum;\n if (typeof maximum === \"number\")\n json.maxItems = maximum;\n};\n/** JSON object keys are always strings, so a numeric record key schema is re-expressed over the\n * numeric-string form the record parser matches. Deferred to `finalize`, after the flatten: a key\n * behind a wrapper only carries its own `type` before then, and a union key only has its branches.\n *\n * A numeric bound cannot apply to a property name, so `minimum` and its siblings are dropped rather\n * than carried over: keeping them beside `type: \"string\"` reproduces the match-nothing schema this\n * exists to fix. A key that carries one therefore emits wider than the record parses — `z.record(z.number().min(5), V)`\n * accepts `\"3\"` — which is the deliberate trade, since throwing on it would reject an ordinary schema\n * outright. */\nfunction stringifyKeyNames(bySchema, json, visited) {\n // an extracted key that rewrites cannot go on sharing its definition — the string form a key position needs is not the number form every other reference wants — so it inlines. One that does not rewrite keeps the `$ref`.\n if (json.$ref) {\n // a recursive key holds its own reference inside its definition, so a node already on the path is left alone rather than resolved again\n if (visited.has(json))\n return json;\n visited.add(json);\n const def = bySchema.get(json)?.def;\n if (!def)\n return json;\n const inlined = stringifyKeyNames(bySchema, def, visited);\n return inlined === def ? json : inlined;\n }\n for (const keyword of [\"anyOf\", \"oneOf\"]) {\n const branches = json[keyword];\n if (!Array.isArray(branches))\n continue;\n const mapped = branches.map((branch) => stringifyKeyNames(bySchema, branch, visited));\n // rebuilding regardless would detach a key that had nothing to re-express, dropping its `$ref` and leaking the internal `id`\n if (mapped.some((branch, i) => branch !== branches[i]))\n json = { ...json, [keyword]: mapped };\n }\n // a member that already admits a string leaves the key unconstrained, so the node's own type re-expresses only when every member is numeric\n const types = Array.isArray(json.type) ? json.type : [json.type];\n const numericType = !types.includes(\"string\") && types.some((t) => t === \"number\" || t === \"integer\");\n // a heterogeneous key carries no type at all, so its numeric members are caught here instead\n const values = json.enum ?? (json.const !== undefined ? [json.const] : undefined);\n if (!numericType && !values?.some((v) => typeof v === \"number\"))\n return json;\n const { minimum, maximum, exclusiveMinimum, exclusiveMaximum, multipleOf, format, id, ...rest } = json;\n if (rest.enum)\n rest.enum = rest.enum.map((v) => (typeof v === \"number\" ? String(v) : v));\n else if (typeof rest.const === \"number\")\n rest.const = String(rest.const);\n // a heterogeneous key keeps its absent type: the stringified members already say what a key may be\n if (!numericType)\n return rest;\n rest.type = \"string\";\n if (!values)\n rest.pattern = (types.includes(\"number\") ? regexes.number : regexes.integer).source;\n return rest;\n}\n/** Every record of one conversion, so the carriers are found in a single pass rather than once per record. */\nconst pendingRecords = new WeakMap();\nfunction rewriteKeyNames(ctx) {\n // an extracted key is resolved by the object `extractToDef` left in its place, so the map is built once rather than searched per reference. `_zod.toJSONSchema` can hand the same object to two schemas, so the first entry carrying a body wins, as a search would have found it.\n const bySchema = new Map();\n for (const entry of ctx.seen.values()) {\n if (entry.def && !bySchema.has(entry.schema))\n bySchema.set(entry.schema, entry);\n }\n const rewrites = new Map();\n for (const record of pendingRecords.get(ctx) ?? []) {\n const seen = ctx.seen.get(record);\n const names = (seen?.def ?? seen?.schema)?.propertyNames;\n if (!names || names === true || rewrites.has(names))\n continue;\n const rewritten = stringifyKeyNames(bySchema, names, new Set());\n if (rewritten !== names)\n rewrites.set(names, rewritten);\n }\n if (!rewrites.size)\n return;\n // the flatten has already copied each record's own properties onto every wrapper by reference, and an extracted body is another such copy, so every carrier holding a rewritten key is updated together\n for (const entry of ctx.seen.values()) {\n for (const carrier of [entry.schema, entry.def]) {\n const rewritten = carrier && rewrites.get(carrier.propertyNames);\n if (rewritten)\n carrier.propertyNames = rewritten;\n }\n }\n}\nexport const recordProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n json.type = \"object\";\n // For looseRecord with regex patterns, use patternProperties. This correctly represents \"only validate keys matching the pattern\" semantics and composes well with allOf (intersections)\n const keyType = def.keyType;\n const patterns = aggregateChecks(keyType).patterns;\n if (def.mode === \"loose\" && patterns && patterns.size > 0) {\n // Use patternProperties for looseRecord with regex patterns\n const valueSchema = processSchema(def.valueType, ctx, {\n ...params,\n path: [...params.path, \"patternProperties\", \"*\"],\n });\n json.patternProperties = {};\n for (const pattern of patterns) {\n assignProp(json.patternProperties, exactPattern(pattern).source, valueSchema);\n }\n }\n else {\n // Default behavior: use propertyNames + additionalProperties\n if (ctx.target === \"draft-07\" || ctx.target === \"draft-2020-12\") {\n json.propertyNames = processSchema(def.keyType, ctx, {\n ...params,\n path: [...params.path, \"propertyNames\"],\n });\n let pending = pendingRecords.get(ctx);\n if (!pending) {\n pending = [];\n pendingRecords.set(ctx, pending);\n ctx.deferred.push(() => rewriteKeyNames(ctx));\n }\n pending.push(schema);\n }\n json.additionalProperties = processSchema(def.valueType, ctx, {\n ...params,\n path: [...params.path, \"additionalProperties\"],\n });\n }\n // Add required for keys with discrete values (enum, literal, etc.)\n const keyValues = keyType._zod.values;\n // Every key shares one value schema, so an optional-in value makes the whole key set omittable on input. Output keeps them: the exhaustive branch assigns every key, even one whose value came back undefined.\n const omittableOnInput = ctx.io === \"input\" && inputOptin(def.valueType) !== undefined;\n if (keyValues && !def.partial && !omittableOnInput) {\n const validKeyValues = [...keyValues].filter((v) => typeof v === \"string\" || typeof v === \"number\");\n if (validKeyValues.length > 0) {\n json.required = validKeyValues.map(String);\n }\n }\n};\nexport const nullableProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n const inner = processSchema(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n if (ctx.target === \"openapi-3.0\") {\n seen.ref = def.innerType;\n json.nullable = true;\n }\n else {\n json.anyOf = [inner, { type: \"null\" }];\n }\n};\nexport const nonoptionalProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n processSchema(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n};\n/** Round-trips a default value through JSON so the emitted schema is guaranteed to be valid JSON.\n * A BigInt has no reliable encoding, so it goes through `unrepresentable` like any other\n * unrepresentable value. Returns a sentinel when the caller must not write a default of its own. */\nconst UNREPRESENTABLE_DEFAULT = Symbol();\nfunction serializeDefaultValue(value, schema, ctx, json, params) {\n let unrepresentable = false;\n const serialized = JSON.stringify(value, (_, val) => {\n if (typeof val !== \"bigint\")\n return val;\n unrepresentable = true;\n return null;\n });\n if (!unrepresentable)\n return JSON.parse(serialized);\n handleUnrepresentable(schema, ctx, json, params, \"BigInt defaults cannot be represented in JSON Schema\");\n return UNREPRESENTABLE_DEFAULT;\n}\nexport const defaultProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n processSchema(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n const value = serializeDefaultValue(def.defaultValue, schema, ctx, json, params);\n if (value !== UNREPRESENTABLE_DEFAULT)\n json.default = value;\n};\nexport const prefaultProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n processSchema(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n if (ctx.io !== \"input\")\n return;\n const value = serializeDefaultValue(def.defaultValue, schema, ctx, json, params);\n if (value !== UNREPRESENTABLE_DEFAULT)\n json._prefault = value;\n};\nexport const catchProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n processSchema(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n let catchValue;\n try {\n catchValue = def.catchValue(undefined);\n }\n catch {\n handleUnrepresentable(schema, ctx, json, params, \"Dynamic catch values are not supported in JSON Schema\");\n return;\n }\n json.default = catchValue;\n};\nexport const pipeProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n const inIsTransform = def.in._zod.traits.has(\"$ZodTransform\");\n const innerType = ctx.io === \"input\" ? (inIsTransform ? def.out : def.in) : def.out;\n processSchema(innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = innerType;\n};\nexport const readonlyProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n processSchema(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n json.readOnly = true;\n};\nexport const promiseProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n processSchema(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n};\nexport const optionalProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n processSchema(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n};\nexport const lazyProcessor = (schema, ctx, _json, params) => {\n const innerType = schema._zod.innerType;\n processSchema(innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = innerType;\n};\n// ==================== ALL PROCESSORS ====================\nexport const allProcessors = {\n string: stringProcessor,\n number: numberProcessor,\n boolean: booleanProcessor,\n bigint: bigintProcessor,\n symbol: symbolProcessor,\n null: nullProcessor,\n undefined: undefinedProcessor,\n void: voidProcessor,\n never: neverProcessor,\n any: anyProcessor,\n unknown: unknownProcessor,\n date: dateProcessor,\n enum: enumProcessor,\n literal: literalProcessor,\n nan: nanProcessor,\n template_literal: templateLiteralProcessor,\n file: fileProcessor,\n success: successProcessor,\n custom: customProcessor,\n function: functionProcessor,\n transform: transformProcessor,\n map: mapProcessor,\n set: setProcessor,\n array: arrayProcessor,\n object: objectProcessor,\n union: unionProcessor,\n intersection: intersectionProcessor,\n tuple: tupleProcessor,\n record: recordProcessor,\n nullable: nullableProcessor,\n nonoptional: nonoptionalProcessor,\n default: defaultProcessor,\n prefault: prefaultProcessor,\n catch: catchProcessor,\n pipe: pipeProcessor,\n readonly: readonlyProcessor,\n promise: promiseProcessor,\n optional: optionalProcessor,\n lazy: lazyProcessor,\n};\nexport function toJSONSchema(input, params) {\n if (\"_idmap\" in input) {\n // Registry case\n const registry = input;\n const ctx = initializeContext({ ...params, processors: allProcessors });\n const defs = {};\n // First pass: process all schemas to build the seen map\n for (const entry of registry._idmap.entries()) {\n const [_, schema] = entry;\n processSchema(schema, ctx);\n }\n const schemas = {};\n const external = {\n registry,\n uri: params?.uri,\n defs,\n };\n // Update the context with external configuration\n ctx.external = external;\n // Second pass: emit each schema\n for (const entry of registry._idmap.entries()) {\n const [key, schema] = entry;\n extractDefs(ctx, schema);\n assignProp(schemas, key, finalize(ctx, schema));\n }\n if (Object.keys(defs).length > 0) {\n const defsSegment = ctx.target === \"draft-2020-12\" ? \"$defs\" : \"definitions\";\n schemas.__shared = {\n [defsSegment]: defs,\n };\n }\n return { schemas };\n }\n // Single schema case\n const ctx = initializeContext({ ...params, processors: allProcessors });\n processSchema(input, ctx);\n extractDefs(ctx, input);\n return finalize(ctx, input);\n}\n","import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"characters\", verb: \"to have\" },\n file: { unit: \"bytes\", verb: \"to have\" },\n array: { unit: \"items\", verb: \"to have\" },\n set: { unit: \"items\", verb: \"to have\" },\n map: { unit: \"entries\", verb: \"to have\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"input\",\n email: \"email address\",\n url: \"URL\",\n emoji: \"emoji\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"ISO datetime\",\n date: \"ISO date\",\n time: \"ISO time\",\n duration: \"ISO duration\",\n ipv4: \"IPv4 address\",\n ipv6: \"IPv6 address\",\n mac: \"MAC address\",\n cidrv4: \"IPv4 range\",\n cidrv6: \"IPv6 range\",\n base64: \"base64-encoded string\",\n base64url: \"base64url-encoded string\",\n json_string: \"JSON string\",\n e164: \"E.164 number\",\n currency_code: \"currency code\",\n credit_card: \"credit card number\",\n iban: \"IBAN\",\n jwt: \"JWT\",\n template_literal: \"input\",\n };\n // type names: missing keys = do not translate (use raw value via ?? fallback)\n const TypeDictionary = {\n // Compatibility: \"nan\" -> \"NaN\" for display\n nan: \"NaN\",\n // All other type names omitted - they fall back to raw values via ?? operator\n };\n function getTypeName(type, input) {\n if (type === \"number\" && typeof input === \"number\" && !Number.isFinite(input)) {\n return String(input);\n }\n return TypeDictionary[type] ?? type;\n }\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = getTypeName(issue.expected);\n const receivedType = util.parsedType(issue.input);\n const received = getTypeName(receivedType, issue.input);\n return `Invalid input: expected ${expected}, received ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `Invalid input: expected ${util.stringifyPrimitive(issue.values[0])}`;\n return `Invalid option: expected one of ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.exact ? \"exactly \" : issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `Too big: expected ${issue.origin ?? \"value\"} to have ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"elements\"}`;\n return `Too big: expected ${issue.origin ?? \"value\"} to be ${adj}${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.exact ? \"exactly \" : issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `Too small: expected ${issue.origin} to have ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n }\n return `Too small: expected ${issue.origin} to be ${adj}${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\") {\n return `Invalid string: must start with \"${_issue.prefix}\"`;\n }\n if (_issue.format === \"ends_with\")\n return `Invalid string: must end with \"${_issue.suffix}\"`;\n if (_issue.format === \"includes\")\n return `Invalid string: must include \"${_issue.includes}\"`;\n if (_issue.format === \"regex\")\n return `Invalid string: must match pattern ${_issue.pattern}`;\n return `Invalid ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `Invalid number: must be a multiple of ${issue.divisor}`;\n case \"unrecognized_keys\":\n return `Unrecognized key${issue.keys.length > 1 ? \"s\" : \"\"}: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `Invalid key in ${issue.origin}`;\n case \"invalid_union\":\n if (issue.options && Array.isArray(issue.options) && issue.options.length > 0) {\n const opts = issue.options.map((o) => `'${o}'`).join(\" | \");\n return `Invalid discriminator value. Expected ${opts}`;\n }\n if (issue.inclusive === false) {\n return \"Invalid input: more than one option matched\";\n }\n return \"Invalid input\";\n case \"invalid_element\":\n return `Invalid value in ${issue.origin}`;\n default:\n return `Invalid input`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n","import { $constructor } from \"./core.js\";\nimport * as util from \"./util.js\";\n/* Computing the message eagerly is expensive (pretty-printed JSON of all\n * issues), so defer it until first read. The accessor functions and\n * descriptors are shared across instances to keep error construction\n * cheap; the computed message is cached on the internals object. The\n * setter preserves plain assignment semantics for consumers that\n * overwrite `message`. */\nfunction _getMessage() {\n const internals = this._zod;\n internals.message ?? (internals.message = JSON.stringify(internals.def, util.jsonStringifyReplacer, 2));\n return internals.message;\n}\nfunction _setMessage(value) {\n this._zod.message = value;\n}\nconst _messageDesc = {\n get: _getMessage,\n set: _setMessage,\n enumerable: true,\n configurable: true,\n};\nconst _issuesDesc = { value: undefined, enumerable: false };\n/* Prototypes that already carry the lazy `toString`. Seeded with the\n * intrinsics so that `init` on a foreign object — it accepts any object —\n * can never install an accessor onto a prototype we do not own. */\nconst _installedToString = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]);\nconst initializer = (inst, def) => {\n inst.name = \"$ZodError\";\n // `_zod` is already non-enumerable: $constructor's init defined it with this same descriptor\n _issuesDesc.value = def;\n Object.defineProperty(inst, \"issues\", _issuesDesc);\n // Clear the shared slot; a retained `value` pins the last error's issues.\n _issuesDesc.value = undefined;\n Object.defineProperty(inst, \"message\", _messageDesc);\n /* `toString` lives as a non-enumerable lazy getter on the shared\n * prototype; on first access it caches a per-instance closure so\n * detached usage still works. */\n const proto = Object.getPrototypeOf(inst);\n if (!_installedToString.has(proto)) {\n _installedToString.add(proto);\n Object.defineProperty(proto, \"toString\", {\n configurable: true,\n enumerable: false,\n get() {\n const value = () => this.message;\n Object.defineProperty(this, \"toString\", { value, configurable: true, writable: true });\n return value;\n },\n set(value) {\n Object.defineProperty(this, \"toString\", { value, configurable: true, writable: true });\n },\n });\n }\n};\nexport const $ZodError = $constructor(\"$ZodError\", initializer);\nexport const $ZodRealError = $constructor(\"$ZodError\", initializer, undefined, {\n Parent: Error,\n});\n/** Get-or-create `obj[key]` as an own data property. A path segment naming an inherited member\n * (\"toString\", \"constructor\") would otherwise read through to the prototype, and assigning\n * \"__proto__\" would hit the setter instead of creating a key. */\nfunction node(obj, key, make) {\n if (!Object.prototype.hasOwnProperty.call(obj, key)) {\n if (key === \"__proto__\") {\n Object.defineProperty(obj, key, { value: make(), writable: true, enumerable: true, configurable: true });\n }\n else {\n obj[key] = make();\n }\n }\n return obj[key];\n}\nexport function flattenError(error, mapper = (issue) => issue.message) {\n const fieldErrors = {};\n const formErrors = [];\n for (const sub of error.issues) {\n if (sub.path.length > 0) {\n node(fieldErrors, sub.path[0], () => []).push(mapper(sub));\n }\n else {\n formErrors.push(mapper(sub));\n }\n }\n return { formErrors, fieldErrors };\n}\nexport function formatError(error, mapper = (issue) => issue.message) {\n const fieldErrors = { _errors: [] };\n const processError = (error, path = []) => {\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\" && issue.errors.length) {\n issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path]));\n }\n else if (issue.code === \"invalid_key\") {\n processError({ issues: issue.issues }, [...path, ...issue.path]);\n }\n else if (issue.code === \"invalid_element\") {\n processError({ issues: issue.issues }, [...path, ...issue.path]);\n }\n else {\n const fullpath = [...path, ...issue.path];\n if (fullpath.length === 0) {\n fieldErrors._errors.push(mapper(issue));\n }\n else {\n let curr = fieldErrors;\n let i = 0;\n while (i < fullpath.length) {\n const el = fullpath[i];\n const terminal = i === fullpath.length - 1;\n // `_errors` is reserved by this legacy format, so merge a matching path segment into the current node instead of treating its array as a child.\n if (el === \"_errors\") {\n if (terminal)\n curr._errors.push(mapper(issue));\n i++;\n continue;\n }\n // A path element may collide with an inherited property name such as\n // \"__proto__\" or \"constructor\". Truthiness checks read the prototype\n // (so no node is created, then ._errors.push throws), and bracket\n // assignment of \"__proto__\" hits the setter instead of creating an\n // own key. Guard the read with hasOwnProperty and create the node\n // with defineProperty so any path element becomes a real own key.\n if (!Object.prototype.hasOwnProperty.call(curr, el)) {\n Object.defineProperty(curr, el, {\n value: { _errors: [] },\n enumerable: true,\n writable: true,\n configurable: true,\n });\n }\n const node = curr[el];\n if (terminal) {\n node._errors.push(mapper(issue));\n }\n curr = node;\n i++;\n }\n }\n }\n }\n };\n processError(error);\n return fieldErrors;\n}\nexport function treeifyError(error, mapper = (issue) => issue.message) {\n const result = { errors: [] };\n const processError = (error, path = []) => {\n var _a;\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\" && issue.errors.length) {\n // regular union error\n issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path]));\n }\n else if (issue.code === \"invalid_key\") {\n processError({ issues: issue.issues }, [...path, ...issue.path]);\n }\n else if (issue.code === \"invalid_element\") {\n processError({ issues: issue.issues }, [...path, ...issue.path]);\n }\n else {\n const fullpath = [...path, ...issue.path];\n if (fullpath.length === 0) {\n result.errors.push(mapper(issue));\n continue;\n }\n let curr = result;\n let i = 0;\n while (i < fullpath.length) {\n const el = fullpath[i];\n const terminal = i === fullpath.length - 1;\n if (typeof el === \"string\") {\n curr.properties ?? (curr.properties = {});\n // el may collide with an inherited property name (\"__proto__\",\n // \"constructor\", ...); ??= reads the prototype so the node is never\n // created and curr.errors.push throws. Guard with hasOwnProperty and\n // create the node with defineProperty so \"__proto__\" becomes a real\n // own key rather than invoking the prototype setter.\n if (!Object.prototype.hasOwnProperty.call(curr.properties, el)) {\n Object.defineProperty(curr.properties, el, {\n value: { errors: [] },\n enumerable: true,\n writable: true,\n configurable: true,\n });\n }\n curr = curr.properties[el];\n }\n else {\n curr.items ?? (curr.items = []);\n (_a = curr.items)[el] ?? (_a[el] = { errors: [] });\n curr = curr.items[el];\n }\n if (terminal) {\n curr.errors.push(mapper(issue));\n }\n i++;\n }\n }\n }\n };\n processError(error);\n return result;\n}\n/** Format a ZodError as a human-readable string in the following form.\n *\n * From\n *\n * ```ts\n * ZodError {\n * issues: [\n * {\n * expected: 'string',\n * code: 'invalid_type',\n * path: [ 'username' ],\n * message: 'Invalid input: expected string'\n * },\n * {\n * expected: 'number',\n * code: 'invalid_type',\n * path: [ 'favoriteNumbers', 1 ],\n * message: 'Invalid input: expected number'\n * }\n * ];\n * }\n * ```\n *\n * to\n *\n * ```\n * username\n * ✖ Expected number, received string at \"username\n * favoriteNumbers[0]\n * ✖ Invalid input: expected number\n * ```\n */\nexport function toDotPath(_path) {\n const segs = [];\n const path = _path.map((seg) => (typeof seg === \"object\" ? seg.key : seg));\n for (const seg of path) {\n if (typeof seg === \"number\")\n segs.push(`[${seg}]`);\n else if (typeof seg === \"symbol\")\n segs.push(`[${JSON.stringify(String(seg))}]`);\n else if (/[^\\w$]/.test(seg))\n segs.push(`[${JSON.stringify(seg)}]`);\n else {\n if (segs.length)\n segs.push(\".\");\n segs.push(seg);\n }\n }\n return segs.join(\"\");\n}\nexport function prettifyError(error) {\n const lines = [];\n // sort by path length\n const issues = [...error.issues].sort((a, b) => (a.path ?? []).length - (b.path ?? []).length);\n // Process each issue\n for (const issue of issues) {\n lines.push(`✖ ${issue.message}`);\n if (issue.path?.length)\n lines.push(` → at ${toDotPath(issue.path)}`);\n }\n // Convert Map to formatted string\n return lines.join(\"\\n\");\n}\n","import * as core from \"./core.js\";\nimport * as errors from \"./errors.js\";\nimport * as util from \"./util.js\";\n// Always both keys, so the `_params` read site in `_parse` sees one object shape rather than two.\nfunction finalizeParams(callee, params) {\n return { callee: params?.callee ?? callee, Err: params?.Err };\n}\nexport const _parse = (_Err) => {\n const fn = (schema, value, _ctx, _params) => {\n const ctx = _ctx ? { ..._ctx, async: false } : { async: false };\n const result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n if (result.issues.length) {\n const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));\n util.captureStackTrace(e, _params?.callee ?? fn);\n throw e;\n }\n return result.value;\n };\n return fn;\n};\nexport const parse = /* @__PURE__*/ _parse(errors.$ZodRealError);\nexport const _parseAsync = (_Err) => {\n const fn = async (schema, value, _ctx, params) => {\n const ctx = _ctx ? { ..._ctx, async: true } : { async: true };\n let result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise)\n result = await result;\n if (result.issues.length) {\n const e = new (params?.Err ?? _Err)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));\n util.captureStackTrace(e, params?.callee ?? fn);\n throw e;\n }\n return result.value;\n };\n return fn;\n};\nexport const parseAsync = /* @__PURE__*/ _parseAsync(errors.$ZodRealError);\nexport const _safeParse = (_Err) => (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, async: false } : { async: false };\n const result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n return result.issues.length ? failure(_Err, result.issues, ctx) : { success: true, data: result.value };\n};\nexport const safeParse = /* @__PURE__*/ _safeParse(errors.$ZodRealError);\n// the error is built on the first read of `error`: finalizing the issues and constructing the instance is most of a failing parse, and a caller that only branches on `success` never pays it. a getter in the literal keeps this small; the alternative, one shared accessor descriptor plus a hidden state slot, reads ~15% faster but costs ~75 B gzipped in every bundle\nfunction failure(Err, issues, ctx) {\n let error;\n return {\n success: false,\n get error() {\n if (!error) {\n error = new Err(issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));\n // finalizeIssue drops `input`, so the built error holds nothing; keeping the raw issues past this point pins the parsed value for the life of the result\n issues = undefined;\n ctx = undefined;\n }\n return error;\n },\n set error(e) {\n error = e;\n // a replacement makes the getter's branch unreachable, so the captures have to go here too\n issues = undefined;\n ctx = undefined;\n },\n };\n}\nexport const _safeParseAsync = (_Err) => async (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, async: true } : { async: true };\n let result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise)\n result = await result;\n return result.issues.length ? failure(_Err, result.issues, ctx) : { success: true, data: result.value };\n};\nexport const safeParseAsync = /* @__PURE__*/ _safeParseAsync(errors.$ZodRealError);\n// registry mirrors of the compiler's sentinels, so this module never imports the compiler\nconst COMPILE_INVALID = /* @__PURE__ */ Symbol.for(\"zod.compile.invalid\");\nconst COMPILE_FALLBACK = /* @__PURE__ */ Symbol.for(\"zod.compile.fallback\");\n// Deliberately tiny, because v8 will not inline a body carrying the fallback's object literals and throw. Everything that is not the compiled happy path lives in validateFallback, and that split is worth ~35% on a compiled schema.\nexport const validate = ((schema, value, _ctx) => {\n const validator = schema._zod.bag.validator;\n if (validator !== undefined) {\n if (validator(value) !== COMPILE_INVALID)\n return true;\n // a definite sentinel means the runtime would reject, so skip the re-parse; a ctx can still change the answer\n if (validator.definite === true && _ctx === undefined)\n return false;\n }\n return validateFallback(schema, value, _ctx);\n});\nfunction validateFallback(schema, value, _ctx) {\n const ctx = _ctx\n ? { ..._ctx, async: false, abortEarly: true }\n : { async: false, abortEarly: true };\n const fallbackRun = schema._zod.bag.fallbackRun;\n let result;\n if (fallbackRun) {\n // skip nested fast paths on the fallback, so user callbacks keep the at-most-twice bound\n ctx[COMPILE_FALLBACK] = true;\n result = fallbackRun({ value, issues: [] }, ctx);\n }\n else {\n result = schema._zod.run({ value, issues: [] }, ctx);\n }\n if (result instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n return result.issues.length === 0;\n}\n// no fast path: the compiler keeps async parses on the runtime, because a promise-returning callback that is not declared async compiles to a throw\nexport const validateAsync = async (schema, value, _ctx) => {\n const ctx = _ctx\n ? { ..._ctx, async: true, abortEarly: true }\n : { async: true, abortEarly: true };\n let result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise)\n result = await result;\n return result.issues.length === 0;\n};\nexport const _encode = (_Err) => {\n const parse = _parse(_Err);\n const fn = (schema, value, _ctx, _params) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return parse(schema, value, ctx, finalizeParams(fn, _params));\n };\n return fn;\n};\nexport const encode = /* @__PURE__*/ _encode(errors.$ZodRealError);\nexport const _decode = (_Err) => {\n const parse = _parse(_Err);\n const fn = (schema, value, _ctx, _params) => {\n return parse(schema, value, _ctx, finalizeParams(fn, _params));\n };\n return fn;\n};\nexport const decode = /* @__PURE__*/ _decode(errors.$ZodRealError);\nexport const _encodeAsync = (_Err) => {\n const parseAsync = _parseAsync(_Err);\n const fn = async (schema, value, _ctx, _params) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return (await parseAsync(schema, value, ctx, finalizeParams(fn, _params)));\n };\n return fn;\n};\nexport const encodeAsync = /* @__PURE__*/ _encodeAsync(errors.$ZodRealError);\nexport const _decodeAsync = (_Err) => {\n const parseAsync = _parseAsync(_Err);\n const fn = async (schema, value, _ctx, _params) => {\n return await parseAsync(schema, value, _ctx, finalizeParams(fn, _params));\n };\n return fn;\n};\nexport const decodeAsync = /* @__PURE__*/ _decodeAsync(errors.$ZodRealError);\nexport const _safeEncode = (_Err) => (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return _safeParse(_Err)(schema, value, ctx);\n};\nexport const safeEncode = /* @__PURE__*/ _safeEncode(errors.$ZodRealError);\nexport const _safeDecode = (_Err) => (schema, value, _ctx) => {\n return _safeParse(_Err)(schema, value, _ctx);\n};\nexport const safeDecode = /* @__PURE__*/ _safeDecode(errors.$ZodRealError);\nexport const _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return _safeParseAsync(_Err)(schema, value, ctx);\n};\nexport const safeEncodeAsync = /* @__PURE__*/ _safeEncodeAsync(errors.$ZodRealError);\nexport const _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => {\n return _safeParseAsync(_Err)(schema, value, _ctx);\n};\nexport const safeDecodeAsync = /* @__PURE__*/ _safeDecodeAsync(errors.$ZodRealError);\n","import * as core from \"../core/index.js\";\nimport { $ZodError } from \"../core/index.js\";\nimport * as util from \"../core/util.js\";\n/* Prototypes that already carry the lazy helper methods. Seeded with the\n * intrinsics so that `init` on a foreign object — it accepts any object —\n * can never install an accessor onto a prototype we do not own. */\nconst _installedErrorProtos = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]);\n/* Helper methods live as non-enumerable lazy getters on the shared\n * prototype instead of own properties on every instance. On first\n * access the getter allocates the per-instance closure and caches it\n * as a non-enumerable own property, so detached usage still works and\n * the allocation only happens for methods actually touched. */\nfunction _lazyMethod(proto, key, make) {\n Object.defineProperty(proto, key, {\n configurable: true,\n enumerable: false,\n get() {\n const value = make(this);\n Object.defineProperty(this, key, { value, configurable: true, writable: true });\n return value;\n },\n set(value) {\n Object.defineProperty(this, key, { value, configurable: true, writable: true });\n },\n });\n}\nconst initializer = (inst, issues) => {\n $ZodError.init(inst, issues);\n inst.name = \"ZodError\";\n const proto = Object.getPrototypeOf(inst);\n if (_installedErrorProtos.has(proto))\n return;\n _installedErrorProtos.add(proto);\n _lazyMethod(proto, \"format\", (self) => (mapper) => core.formatError(self, mapper));\n _lazyMethod(proto, \"flatten\", (self) => (mapper) => core.flattenError(self, mapper));\n _lazyMethod(proto, \"addIssue\", (self) => (issue) => {\n self.issues.push(issue);\n self.message = JSON.stringify(self.issues, util.jsonStringifyReplacer, 2);\n });\n _lazyMethod(proto, \"addIssues\", (self) => (issues) => {\n self.issues.push(...issues);\n self.message = JSON.stringify(self.issues, util.jsonStringifyReplacer, 2);\n });\n Object.defineProperty(proto, \"isEmpty\", {\n configurable: true,\n enumerable: false,\n get() {\n return this.issues.length === 0;\n },\n });\n};\nexport const ZodError = /*@__PURE__*/ core.$constructor(\"ZodError\", initializer);\nexport const ZodRealError = /*@__PURE__*/ core.$constructor(\"ZodError\", initializer, undefined, {\n Parent: Error,\n});\n// /** @deprecated Use `z.core.$ZodErrorMapCtx` instead. */\n// export type ErrorMapCtx = core.$ZodErrorMapCtx;\n","import * as core from \"../core/index.js\";\nimport { ZodRealError } from \"./errors.js\";\nexport const parse = /* @__PURE__ */ core._parse(ZodRealError);\nexport const parseAsync = /* @__PURE__ */ core._parseAsync(ZodRealError);\nexport const safeParse = /* @__PURE__ */ core._safeParse(ZodRealError);\nexport const safeParseAsync = /* @__PURE__ */ core._safeParseAsync(ZodRealError);\nexport { validate, validateAsync } from \"../core/index.js\";\n// Codec functions\nexport const encode = /* @__PURE__ */ core._encode(ZodRealError);\nexport const decode = /* @__PURE__ */ core._decode(ZodRealError);\nexport const encodeAsync = /* @__PURE__ */ core._encodeAsync(ZodRealError);\nexport const decodeAsync = /* @__PURE__ */ core._decodeAsync(ZodRealError);\nexport const safeEncode = /* @__PURE__ */ core._safeEncode(ZodRealError);\nexport const safeDecode = /* @__PURE__ */ core._safeDecode(ZodRealError);\nexport const safeEncodeAsync = /* @__PURE__ */ core._safeEncodeAsync(ZodRealError);\nexport const safeDecodeAsync = /* @__PURE__ */ core._safeDecodeAsync(ZodRealError);\n","import * as core from \"../core/index.js\";\nimport { util } from \"../core/index.js\";\nimport * as processors from \"../core/json-schema-processors.js\";\nimport * as regexes from \"../core/regexes.js\";\nimport { createStandardJSONSchemaMethod, createToJSONSchemaMethod } from \"../core/to-json-schema.js\";\nimport en from \"../locales/en.js\";\nimport * as checks from \"./checks.js\";\nimport * as parse from \"./parse.js\";\n// Register English as the default locale on first ZodType construction. Hooked into the `ZodType` `$constructor` (rather than a top-level `config(en())` in `external.ts`) so bundlers honoring `sideEffects: false` can't tree-shake it out — see #5953, #5725. An explicit `z.config(z.locales.xx())` call wins regardless of order, since this only sets the default when none is present.\nfunction _ensureDefaultLocale() {\n if (!core.globalConfig.localeError)\n core.config(en());\n}\n// the default memoizer is read by the core container init, which runs before `ZodType.init`, so each container calls this first\nfunction _ensureDefaultMemoizer() {\n if (!core.globalConfig.memoizer)\n core.config({ memoizer: core.memoizer() });\n}\nexport const ZodType = /*@__PURE__*/ core.$constructor(\"ZodType\", (inst, def) => {\n _ensureDefaultLocale();\n core.$ZodType.init(inst, def);\n inst.def = def;\n inst.type = def.type;\n return inst;\n}, {\n check(...chks) {\n const def = this.def;\n return this.clone(util.mergeDefs(def, {\n checks: [\n ...(def.checks ?? []),\n ...chks.map((ch) => typeof ch === \"function\" ? { _zod: { check: ch, def: { check: \"custom\" }, onattach: [] } } : ch),\n ],\n }), { parent: true });\n },\n with(...chks) {\n return this.check(...chks);\n },\n clone(def, params) {\n return core.clone(this, def, params);\n },\n brand() {\n return this;\n },\n register(reg, meta) {\n reg.add(this, meta);\n return this;\n },\n refine(check, params) {\n return this.check(refine(check, params));\n },\n superRefine(refinement, params) {\n return this.check(superRefine(refinement, params));\n },\n overwrite(fn) {\n return this.check(checks.overwrite(fn));\n },\n optional() {\n return optional(this);\n },\n exactOptional() {\n return exactOptional(this);\n },\n nullable() {\n return nullable(this);\n },\n nullish() {\n return optional(nullable(this));\n },\n nonoptional(params) {\n return nonoptional(this, params);\n },\n array() {\n return array(this);\n },\n or(arg) {\n return union([this, arg]);\n },\n and(arg) {\n return intersection(this, arg);\n },\n transform(tx) {\n return pipe(this, transform(tx));\n },\n default(d) {\n return _default(this, d);\n },\n prefault(d) {\n return prefault(this, d);\n },\n catch(params) {\n return _catch(this, params);\n },\n pipe(target) {\n return pipe(this, target);\n },\n readonly() {\n return readonly(this);\n },\n describe(description) {\n const cl = this.clone();\n core.globalRegistry.add(cl, { description });\n return cl;\n },\n meta(...args) {\n // overloaded: meta() returns the registered metadata, meta(data) returns a clone with `data` registered. The mapped type picks up the second overload, so we accept variadic any-args and return `any` to satisfy both at runtime.\n if (args.length === 0)\n return core.globalRegistry.get(this);\n const cl = this.clone();\n core.globalRegistry.add(cl, args[0]);\n return cl;\n },\n isOptional() {\n return this.safeParse(undefined).success;\n },\n isNullable() {\n return this.safeParse(null).success;\n },\n apply(fn, ...args) {\n return args.length === 0 ? fn(this) : fn(this, ...args);\n },\n // Overrides core's `~standard` to add `jsonSchema`. Must stay a prototype entry: redefining it per instance demotes instances to dictionary mode.\n get \"~standard\"() {\n return util.hide(this, \"~standard\", {\n ...core.standardProps(this),\n jsonSchema: {\n input: createStandardJSONSchemaMethod(this, \"input\"),\n output: createStandardJSONSchemaMethod(this, \"output\"),\n },\n });\n },\n set \"~standard\"(value) {\n util.own(this, \"~standard\", value);\n },\n parse: function _parse(data, params) {\n return parse.parse(this, data, params, { callee: _parse });\n },\n parseAsync: async function _parseAsync(data, params) {\n return await parse.parseAsync(this, data, params, { callee: _parseAsync });\n },\n safeParse(data, params) {\n return parse.safeParse(this, data, params);\n },\n async safeParseAsync(data, params) {\n return parse.safeParseAsync(this, data, params);\n },\n // `spa` is an alias: same function object as `safeParseAsync`, as before.\n get spa() {\n return this?.safeParseAsync;\n },\n set spa(value) {\n util.own(this, \"spa\", value);\n },\n validate(data, params) {\n return parse.validate(this, data, params);\n },\n validateAsync(data, params) {\n return parse.validateAsync(this, data, params);\n },\n encode: function _encode(data, params) {\n return parse.encode(this, data, params, { callee: _encode });\n },\n decode: function _decode(data, params) {\n return parse.decode(this, data, params, { callee: _decode });\n },\n encodeAsync: async function _encodeAsync(data, params) {\n return await parse.encodeAsync(this, data, params, { callee: _encodeAsync });\n },\n decodeAsync: async function _decodeAsync(data, params) {\n return await parse.decodeAsync(this, data, params, { callee: _decodeAsync });\n },\n safeEncode(data, params) {\n return parse.safeEncode(this, data, params);\n },\n safeDecode(data, params) {\n return parse.safeDecode(this, data, params);\n },\n async safeEncodeAsync(data, params) {\n return parse.safeEncodeAsync(this, data, params);\n },\n async safeDecodeAsync(data, params) {\n return parse.safeDecodeAsync(this, data, params);\n },\n toJSONSchema(params) {\n return createToJSONSchemaMethod(this, {})(params);\n },\n // Reads through to the registry on every access, so it must not cache.\n get description() {\n return core.globalRegistry.get(this)?.description;\n },\n // No setter: `schema._def = x` throws, as it did when `_def` was a non-writable own property.\n get _def() {\n return this._zod.def;\n },\n});\n/** @internal */\nexport const _ZodString = /*@__PURE__*/ core.$constructor(\"_ZodString\", (inst, def) => {\n core.$ZodString.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.stringProcessor(inst, ctx, json, params);\n}, \n/*@__PURE__*/ util.derived({\n format: (inst) => processors.aggregateChecks(inst).format ?? null,\n minLength: (inst) => processors.aggregateChecks(inst).minimum ?? null,\n maxLength: (inst) => processors.aggregateChecks(inst).maximum ?? null,\n}, {\n regex(...args) {\n return this.check(checks.regex(...args));\n },\n includes(...args) {\n return this.check(checks.includes(...args));\n },\n startsWith(...args) {\n return this.check(checks.startsWith(...args));\n },\n endsWith(...args) {\n return this.check(checks.endsWith(...args));\n },\n min(...args) {\n return this.check(checks.minLength(...args));\n },\n max(...args) {\n return this.check(checks.maxLength(...args));\n },\n length(...args) {\n return this.check(checks.length(...args));\n },\n nonempty(...args) {\n return this.check(checks.minLength(1, ...args));\n },\n lowercase(params) {\n return this.check(checks.lowercase(params));\n },\n uppercase(params) {\n return this.check(checks.uppercase(params));\n },\n trim() {\n return this.check(checks.trim());\n },\n normalize(...args) {\n return this.check(checks.normalize(...args));\n },\n toLowerCase() {\n return this.check(checks.toLowerCase());\n },\n toUpperCase() {\n return this.check(checks.toUpperCase());\n },\n slugify() {\n return this.check(checks.slugify());\n },\n}));\nexport const ZodString = /*@__PURE__*/ core.$constructor(\"ZodString\", (inst, def) => {\n core.$ZodString.init(inst, def);\n _ZodString.init(inst, def);\n}, {\n email(params) {\n return this.check(core._email(ZodEmail, params));\n },\n url(params) {\n return this.check(core._url(ZodURL, params));\n },\n jwt(params) {\n return this.check(core._jwt(ZodJWT, params));\n },\n emoji(params) {\n return this.check(core._emoji(ZodEmoji, params));\n },\n guid(params) {\n return this.check(core._guid(ZodGUID, params));\n },\n uuid(params) {\n return this.check(core._uuid(ZodUUID, params));\n },\n uuidv4(params) {\n return this.check(core._uuidv4(ZodUUID, params));\n },\n uuidv6(params) {\n return this.check(core._uuidv6(ZodUUID, params));\n },\n uuidv7(params) {\n return this.check(core._uuidv7(ZodUUID, params));\n },\n nanoid(params) {\n return this.check(core._nanoid(ZodNanoID, params));\n },\n cuid(params) {\n return this.check(core._cuid(ZodCUID, params));\n },\n cuid2(params) {\n return this.check(core._cuid2(ZodCUID2, params));\n },\n ulid(params) {\n return this.check(core._ulid(ZodULID, params));\n },\n base64(params) {\n return this.check(core._base64(ZodBase64, params));\n },\n base64url(params) {\n return this.check(core._base64url(ZodBase64URL, params));\n },\n xid(params) {\n return this.check(core._xid(ZodXID, params));\n },\n ksuid(params) {\n return this.check(core._ksuid(ZodKSUID, params));\n },\n ipv4(params) {\n return this.check(core._ipv4(ZodIPv4, params));\n },\n ipv6(params) {\n return this.check(core._ipv6(ZodIPv6, params));\n },\n cidrv4(params) {\n return this.check(core._cidrv4(ZodCIDRv4, params));\n },\n cidrv6(params) {\n return this.check(core._cidrv6(ZodCIDRv6, params));\n },\n e164(params) {\n return this.check(core._e164(ZodE164, params));\n },\n datetime(params) {\n return this.check(core._isoDateTime(ZodISODateTime, params));\n },\n date(params) {\n return this.check(core._isoDate(ZodISODate, params));\n },\n time(params) {\n return this.check(core._isoTime(ZodISOTime, params));\n },\n duration(params) {\n return this.check(core._isoDuration(ZodISODuration, params));\n },\n});\nexport function string(params) {\n return core._string(ZodString, params);\n}\nexport const ZodStringFormat = /*@__PURE__*/ core.$constructor(\"ZodStringFormat\", (inst, def) => {\n core.$ZodStringFormat.init(inst, def);\n _ZodString.init(inst, def);\n});\nexport const ZodISODateTime = /*@__PURE__*/ core.$constructor(\"ZodISODateTime\", (inst, def) => {\n core.$ZodISODateTime.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport const ZodISODate = /*@__PURE__*/ core.$constructor(\"ZodISODate\", (inst, def) => {\n core.$ZodISODate.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport const ZodISOTime = /*@__PURE__*/ core.$constructor(\"ZodISOTime\", (inst, def) => {\n core.$ZodISOTime.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport const ZodISODuration = /*@__PURE__*/ core.$constructor(\"ZodISODuration\", (inst, def) => {\n core.$ZodISODuration.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport const ZodEmail = /*@__PURE__*/ core.$constructor(\"ZodEmail\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodEmail.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function email(params) {\n return core._email(ZodEmail, params);\n}\nexport const ZodGUID = /*@__PURE__*/ core.$constructor(\"ZodGUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodGUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function guid(params) {\n return core._guid(ZodGUID, params);\n}\nexport const ZodUUID = /*@__PURE__*/ core.$constructor(\"ZodUUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodUUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function uuid(params) {\n return core._uuid(ZodUUID, params);\n}\nexport function uuidv4(params) {\n return core._uuidv4(ZodUUID, params);\n}\n// ZodUUIDv6\nexport function uuidv6(params) {\n return core._uuidv6(ZodUUID, params);\n}\n// ZodUUIDv7\nexport function uuidv7(params) {\n return core._uuidv7(ZodUUID, params);\n}\nexport const ZodURL = /*@__PURE__*/ core.$constructor(\"ZodURL\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodURL.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function url(params) {\n return core._url(ZodURL, params);\n}\nexport function httpUrl(params) {\n return core._url(ZodURL, {\n protocol: regexes.httpProtocol,\n hostname: regexes.domain,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodEmoji = /*@__PURE__*/ core.$constructor(\"ZodEmoji\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodEmoji.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function emoji(params) {\n return core._emoji(ZodEmoji, params);\n}\nexport const ZodNanoID = /*@__PURE__*/ core.$constructor(\"ZodNanoID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodNanoID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function nanoid(params) {\n return core._nanoid(ZodNanoID, params);\n}\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link ZodCUID2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport const ZodCUID = /*@__PURE__*/ core.$constructor(\"ZodCUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodCUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\n/**\n * Validates a CUID v1 string.\n *\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link cuid2 | `z.cuid2()`} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport function cuid(params) {\n return core._cuid(ZodCUID, params);\n}\nexport const ZodCUID2 = /*@__PURE__*/ core.$constructor(\"ZodCUID2\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodCUID2.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function cuid2(params) {\n return core._cuid2(ZodCUID2, params);\n}\nexport const ZodULID = /*@__PURE__*/ core.$constructor(\"ZodULID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodULID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ulid(params) {\n return core._ulid(ZodULID, params);\n}\nexport const ZodXID = /*@__PURE__*/ core.$constructor(\"ZodXID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodXID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function xid(params) {\n return core._xid(ZodXID, params);\n}\nexport const ZodKSUID = /*@__PURE__*/ core.$constructor(\"ZodKSUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodKSUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ksuid(params) {\n return core._ksuid(ZodKSUID, params);\n}\nexport const ZodIPv4 = /*@__PURE__*/ core.$constructor(\"ZodIPv4\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodIPv4.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ipv4(params) {\n return core._ipv4(ZodIPv4, params);\n}\nexport const ZodMAC = /*@__PURE__*/ core.$constructor(\"ZodMAC\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodMAC.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function mac(params) {\n return core._mac(ZodMAC, params);\n}\nexport const ZodIPv6 = /*@__PURE__*/ core.$constructor(\"ZodIPv6\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodIPv6.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ipv6(params) {\n return core._ipv6(ZodIPv6, params);\n}\nexport const ZodCIDRv4 = /*@__PURE__*/ core.$constructor(\"ZodCIDRv4\", (inst, def) => {\n core.$ZodCIDRv4.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function cidrv4(params) {\n return core._cidrv4(ZodCIDRv4, params);\n}\nexport const ZodCIDRv6 = /*@__PURE__*/ core.$constructor(\"ZodCIDRv6\", (inst, def) => {\n core.$ZodCIDRv6.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function cidrv6(params) {\n return core._cidrv6(ZodCIDRv6, params);\n}\nexport const ZodBase64 = /*@__PURE__*/ core.$constructor(\"ZodBase64\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodBase64.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function base64(params) {\n return core._base64(ZodBase64, params);\n}\nexport const ZodBase64URL = /*@__PURE__*/ core.$constructor(\"ZodBase64URL\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodBase64URL.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function base64url(params) {\n return core._base64url(ZodBase64URL, params);\n}\nexport const ZodE164 = /*@__PURE__*/ core.$constructor(\"ZodE164\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodE164.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function e164(params) {\n return core._e164(ZodE164, params);\n}\nexport const ZodCreditCard = /*@__PURE__*/ core.$constructor(\"ZodCreditCard\", (inst, def) => {\n core.$ZodCreditCard.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function creditCard(params) {\n return core._creditCard(ZodCreditCard, params);\n}\nexport const ZodIBAN = /*@__PURE__*/ core.$constructor(\"ZodIBAN\", (inst, def) => {\n core.$ZodIBAN.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function iban(params) {\n return core._iban(ZodIBAN, params);\n}\nexport const ZodJWT = /*@__PURE__*/ core.$constructor(\"ZodJWT\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodJWT.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function jwt(params) {\n return core._jwt(ZodJWT, params);\n}\nexport const ZodCustomStringFormat = /*@__PURE__*/ core.$constructor(\"ZodCustomStringFormat\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodCustomStringFormat.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function stringFormat(format, fnOrRegex, _params = {}) {\n return core._stringFormat(ZodCustomStringFormat, format, fnOrRegex, _params);\n}\nexport function hostname(_params) {\n return core._stringFormat(ZodCustomStringFormat, \"hostname\", regexes.hostname, _params);\n}\nexport function hex(_params) {\n return core._stringFormat(ZodCustomStringFormat, \"hex\", regexes.hex, _params);\n}\nexport function currencyCode(_params) {\n return core._stringFormat(ZodCustomStringFormat, \"currency_code\", regexes.currencyCode, _params);\n}\nexport function hash(alg, params) {\n const enc = params?.enc ?? \"hex\";\n const format = `${alg}_${enc}`;\n const regex = core.regexes[format];\n if (!regex)\n throw new Error(`Unrecognized hash format: ${format}`);\n return core._stringFormat(ZodCustomStringFormat, format, regex, params);\n}\nexport const ZodNumber = /*@__PURE__*/ core.$constructor(\"ZodNumber\", (inst, def) => {\n core.$ZodNumber.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.numberProcessor(inst, ctx, json, params);\n inst.isFinite = true;\n}, \n/*@__PURE__*/ util.derived({\n minValue: (inst) => {\n const { minimum, exclusiveMinimum } = processors.aggregateChecks(inst);\n return Math.max(minimum ?? Number.NEGATIVE_INFINITY, exclusiveMinimum ?? Number.NEGATIVE_INFINITY);\n },\n maxValue: (inst) => {\n const { maximum, exclusiveMaximum } = processors.aggregateChecks(inst);\n return Math.min(maximum ?? Number.POSITIVE_INFINITY, exclusiveMaximum ?? Number.POSITIVE_INFINITY);\n },\n isInt: (inst) => {\n const { isInt, multipleOf } = processors.aggregateChecks(inst);\n return !!isInt || !!multipleOf?.some(Number.isSafeInteger);\n },\n format: (inst) => processors.aggregateChecks(inst).format ?? null,\n}, {\n gt(value, params) {\n return this.check(checks.gt(value, params));\n },\n gte(value, params) {\n return this.check(checks.gte(value, params));\n },\n min(value, params) {\n return this.check(checks.gte(value, params));\n },\n lt(value, params) {\n return this.check(checks.lt(value, params));\n },\n lte(value, params) {\n return this.check(checks.lte(value, params));\n },\n max(value, params) {\n return this.check(checks.lte(value, params));\n },\n int(params) {\n return this.check(int(params));\n },\n safe(params) {\n return this.check(int(params));\n },\n positive(params) {\n return this.check(checks.gt(0, params));\n },\n nonnegative(params) {\n return this.check(checks.gte(0, params));\n },\n negative(params) {\n return this.check(checks.lt(0, params));\n },\n nonpositive(params) {\n return this.check(checks.lte(0, params));\n },\n multipleOf(value, params) {\n return this.check(checks.multipleOf(value, params));\n },\n step(value, params) {\n return this.check(checks.multipleOf(value, params));\n },\n finite() {\n return this;\n },\n}));\nexport function number(params) {\n return core._number(ZodNumber, params);\n}\nexport const ZodNumberFormat = /*@__PURE__*/ core.$constructor(\"ZodNumberFormat\", (inst, def) => {\n core.$ZodNumberFormat.init(inst, def);\n ZodNumber.init(inst, def);\n});\nexport function int(params) {\n return core._int(ZodNumberFormat, params);\n}\nexport function float32(params) {\n return core._float32(ZodNumberFormat, params);\n}\nexport function float64(params) {\n return core._float64(ZodNumberFormat, params);\n}\nexport function int32(params) {\n return core._int32(ZodNumberFormat, params);\n}\nexport function uint32(params) {\n return core._uint32(ZodNumberFormat, params);\n}\nexport const ZodBoolean = /*@__PURE__*/ core.$constructor(\"ZodBoolean\", (inst, def) => {\n core.$ZodBoolean.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.booleanProcessor(inst, ctx, json, params);\n});\nexport function boolean(params) {\n return core._boolean(ZodBoolean, params);\n}\nexport const ZodBigInt = /*@__PURE__*/ core.$constructor(\"ZodBigInt\", (inst, def) => {\n core.$ZodBigInt.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.bigintProcessor(inst, ctx, json, params);\n}, \n/*@__PURE__*/ util.derived({\n minValue: (inst) => processors.aggregateChecks(inst).minimum ?? null,\n maxValue: (inst) => processors.aggregateChecks(inst).maximum ?? null,\n format: (inst) => processors.aggregateChecks(inst).format ?? null,\n}, {\n gte(value, params) {\n return this.check(checks.gte(value, params));\n },\n min(value, params) {\n return this.check(checks.gte(value, params));\n },\n gt(value, params) {\n return this.check(checks.gt(value, params));\n },\n lt(value, params) {\n return this.check(checks.lt(value, params));\n },\n lte(value, params) {\n return this.check(checks.lte(value, params));\n },\n max(value, params) {\n return this.check(checks.lte(value, params));\n },\n positive(params) {\n return this.check(checks.gt(BigInt(0), params));\n },\n negative(params) {\n return this.check(checks.lt(BigInt(0), params));\n },\n nonpositive(params) {\n return this.check(checks.lte(BigInt(0), params));\n },\n nonnegative(params) {\n return this.check(checks.gte(BigInt(0), params));\n },\n multipleOf(value, params) {\n return this.check(checks.multipleOf(value, params));\n },\n}));\nexport function bigint(params) {\n return core._bigint(ZodBigInt, params);\n}\nexport const ZodBigIntFormat = /*@__PURE__*/ core.$constructor(\"ZodBigIntFormat\", (inst, def) => {\n core.$ZodBigIntFormat.init(inst, def);\n ZodBigInt.init(inst, def);\n});\nexport function int64(params) {\n return core._int64(ZodBigIntFormat, params);\n}\nexport function uint64(params) {\n return core._uint64(ZodBigIntFormat, params);\n}\nexport const ZodSymbol = /*@__PURE__*/ core.$constructor(\"ZodSymbol\", (inst, def) => {\n core.$ZodSymbol.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.symbolProcessor(inst, ctx, json, params);\n});\nexport function symbol(params) {\n return core._symbol(ZodSymbol, params);\n}\nexport const ZodUndefined = /*@__PURE__*/ core.$constructor(\"ZodUndefined\", (inst, def) => {\n core.$ZodUndefined.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.undefinedProcessor(inst, ctx, json, params);\n});\nfunction _undefined(params) {\n return core._undefined(ZodUndefined, params);\n}\nexport { _undefined as undefined };\nexport const ZodNull = /*@__PURE__*/ core.$constructor(\"ZodNull\", (inst, def) => {\n core.$ZodNull.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nullProcessor(inst, ctx, json, params);\n});\nfunction _null(params) {\n return core._null(ZodNull, params);\n}\nexport { _null as null };\nexport const ZodAny = /*@__PURE__*/ core.$constructor(\"ZodAny\", (inst, def) => {\n core.$ZodAny.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.anyProcessor(inst, ctx, json, params);\n});\nexport function any() {\n return core._any(ZodAny);\n}\nexport const ZodUnknown = /*@__PURE__*/ core.$constructor(\"ZodUnknown\", (inst, def) => {\n core.$ZodUnknown.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.unknownProcessor(inst, ctx, json, params);\n});\nexport function unknown() {\n return core._unknown(ZodUnknown);\n}\nexport const ZodNever = /*@__PURE__*/ core.$constructor(\"ZodNever\", (inst, def) => {\n core.$ZodNever.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.neverProcessor(inst, ctx, json, params);\n});\nexport function never(params) {\n return core._never(ZodNever, params);\n}\nexport const ZodVoid = /*@__PURE__*/ core.$constructor(\"ZodVoid\", (inst, def) => {\n core.$ZodVoid.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.voidProcessor(inst, ctx, json, params);\n});\nfunction _void(params) {\n return core._void(ZodVoid, params);\n}\nexport { _void as void };\nexport const ZodDate = /*@__PURE__*/ core.$constructor(\"ZodDate\", (inst, def) => {\n core.$ZodDate.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.dateProcessor(inst, ctx, json, params);\n inst.min = (value, params) => inst.check(checks.gte(value, params));\n inst.max = (value, params) => inst.check(checks.lte(value, params));\n}, \n/*@__PURE__*/ util.derived({\n minDate: (inst) => {\n const { minimum } = processors.aggregateChecks(inst);\n return minimum ? new Date(minimum) : null;\n },\n maxDate: (inst) => {\n const { maximum } = processors.aggregateChecks(inst);\n return maximum ? new Date(maximum) : null;\n },\n}, {}));\nexport function date(params) {\n return core._date(ZodDate, params);\n}\nexport const ZodArray = /*@__PURE__*/ core.$constructor(\"ZodArray\", (inst, def) => {\n _ensureDefaultMemoizer();\n core.$ZodArray.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.arrayProcessor(inst, ctx, json, params);\n inst.element = def.element;\n}, {\n min(n, params) {\n return this.check(checks.minLength(n, params));\n },\n nonempty(params) {\n return this.check(checks.minLength(1, params));\n },\n max(n, params) {\n return this.check(checks.maxLength(n, params));\n },\n length(n, params) {\n return this.check(checks.length(n, params));\n },\n unwrap() {\n return this.element;\n },\n});\nexport function array(element, params) {\n return core._array(ZodArray, element, params);\n}\n// .keyof\nexport function keyof(schema) {\n const shape = schema._zod.def.shape;\n return _enum(Object.keys(shape));\n}\nexport const ZodObject = /*@__PURE__*/ core.$constructor(\"ZodObject\", (inst, def) => {\n _ensureDefaultMemoizer();\n core.$ZodObjectJIT.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.objectProcessor(inst, ctx, json, params);\n util.installLazyProp(inst, \"shape\", (self) => self._zod.def.shape, false);\n}, {\n keyof() {\n return _enum(Object.keys(this._zod.def.shape));\n },\n catchall(catchall) {\n // `mergeDefs` rather than a spread: spreading reads `shape`, and resolving it can mint a whole fresh subtree\n return this.clone(util.mergeDefs(this._zod.def, { catchall: catchall }));\n },\n passthrough() {\n return this.clone(util.mergeDefs(this._zod.def, { catchall: unknown() }));\n },\n loose() {\n return this.clone(util.mergeDefs(this._zod.def, { catchall: unknown() }));\n },\n strict() {\n return this.clone(util.mergeDefs(this._zod.def, { catchall: never() }));\n },\n strip() {\n return this.clone(util.mergeDefs(this._zod.def, { catchall: undefined }));\n },\n extend(incoming) {\n return util.extend(this, incoming);\n },\n safeExtend(incoming) {\n return util.safeExtend(this, incoming);\n },\n merge(other) {\n return util.merge(this, other);\n },\n pick(mask) {\n return util.pick(this, mask);\n },\n omit(mask) {\n return util.omit(this, mask);\n },\n partial(...args) {\n return util.partial(ZodOptional, this, args[0]);\n },\n exactPartial(...args) {\n return util.partial(ZodExactOptional, this, args[0], \"exactPartial\");\n },\n required(...args) {\n return util.required(ZodNonOptional, this, args[0]);\n },\n});\nexport function object(shape, params) {\n const def = {\n type: \"object\",\n shape: shape ?? {},\n ...util.normalizeParams(params),\n };\n return new ZodObject(def);\n}\n// strictObject\nexport function strictObject(shape, params) {\n return new ZodObject({\n type: \"object\",\n shape,\n catchall: never(),\n ...util.normalizeParams(params),\n });\n}\n// looseObject\nexport function looseObject(shape, params) {\n return new ZodObject({\n type: \"object\",\n shape,\n catchall: unknown(),\n ...util.normalizeParams(params),\n });\n}\nexport const ZodUnion = /*@__PURE__*/ core.$constructor(\"ZodUnion\", (inst, def) => {\n core.$ZodUnion.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.unionProcessor(inst, ctx, json, params);\n inst.options = def.options;\n});\nexport function union(options, params) {\n return new ZodUnion({\n type: \"union\",\n options: options,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodXor = /*@__PURE__*/ core.$constructor(\"ZodXor\", (inst, def) => {\n ZodUnion.init(inst, def);\n core.$ZodXor.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.unionProcessor(inst, ctx, json, params);\n inst.options = def.options;\n});\n/** Creates an exclusive union (XOR) where exactly one option must match.\n * Unlike regular unions that succeed when any option matches, xor fails if\n * zero or more than one option matches the input. */\nexport function xor(options, params) {\n return new ZodXor({\n type: \"union\",\n options: options,\n inclusive: false,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodDiscriminatedUnion = /*@__PURE__*/ core.$constructor(\"ZodDiscriminatedUnion\", (inst, def) => {\n ZodUnion.init(inst, def);\n core.$ZodDiscriminatedUnion.init(inst, def);\n});\nexport function discriminatedUnion(discriminator, options, params) {\n // const [options, params] = args;\n return new ZodDiscriminatedUnion({\n type: \"union\",\n options: options,\n discriminator,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodIntersection = /*@__PURE__*/ core.$constructor(\"ZodIntersection\", (inst, def) => {\n core.$ZodIntersection.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.intersectionProcessor(inst, ctx, json, params);\n});\nexport function intersection(left, right) {\n return new ZodIntersection({\n type: \"intersection\",\n left: left,\n right: right,\n });\n}\nexport const ZodTuple = /*@__PURE__*/ core.$constructor(\"ZodTuple\", (inst, def) => {\n _ensureDefaultMemoizer();\n core.$ZodTuple.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.tupleProcessor(inst, ctx, json, params);\n}, {\n rest(rest) {\n return this.clone({\n ...this._zod.def,\n rest: rest,\n });\n },\n partial() {\n const def = this._zod.def;\n // a refinement was authored against the full arity; partialing would run it on a shorter array\n if (def.checks?.length)\n throw new Error(\".partial() cannot be used on tuple schemas containing refinements\");\n return this.clone({\n ...def,\n items: def.items.map((item) => new ZodOptional({ type: \"optional\", innerType: item })),\n });\n },\n});\nexport function tuple(items, _paramsOrRest, _params) {\n const hasRest = _paramsOrRest instanceof core.$ZodType;\n const params = hasRest ? _params : _paramsOrRest;\n const rest = hasRest ? _paramsOrRest : null;\n return new ZodTuple({\n type: \"tuple\",\n items: items,\n rest,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodRecord = /*@__PURE__*/ core.$constructor(\"ZodRecord\", (inst, def) => {\n _ensureDefaultMemoizer();\n core.$ZodRecord.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.recordProcessor(inst, ctx, json, params);\n inst.keyType = def.keyType;\n inst.valueType = def.valueType;\n});\nexport function record(keyType, valueType, params) {\n // v3-compat: z.record(valueType, params?) — defaults keyType to z.string()\n if (!valueType || !valueType._zod) {\n return new ZodRecord({\n type: \"record\",\n keyType: string(),\n valueType: keyType,\n ...util.normalizeParams(valueType),\n });\n }\n return new ZodRecord({\n type: \"record\",\n keyType,\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\n// type alksjf = core.output<core.$ZodRecordKey>;\nexport function partialRecord(keyType, valueType, params) {\n return new ZodRecord({\n type: \"record\",\n keyType,\n valueType: valueType,\n ...util.normalizeParams(params),\n partial: true,\n });\n}\nexport function looseRecord(keyType, valueType, params) {\n return new ZodRecord({\n type: \"record\",\n keyType,\n valueType: valueType,\n mode: \"loose\",\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMap = /*@__PURE__*/ core.$constructor(\"ZodMap\", (inst, def) => {\n _ensureDefaultMemoizer();\n core.$ZodMap.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.mapProcessor(inst, ctx, json, params);\n inst.keyType = def.keyType;\n inst.valueType = def.valueType;\n inst.min = (...args) => inst.check(core._minSize(...args));\n inst.nonempty = (params) => inst.check(core._minSize(1, params));\n inst.max = (...args) => inst.check(core._maxSize(...args));\n inst.size = (...args) => inst.check(core._size(...args));\n});\nexport function map(keyType, valueType, params) {\n return new ZodMap({\n type: \"map\",\n keyType: keyType,\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodSet = /*@__PURE__*/ core.$constructor(\"ZodSet\", (inst, def) => {\n _ensureDefaultMemoizer();\n core.$ZodSet.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.setProcessor(inst, ctx, json, params);\n inst.min = (...args) => inst.check(core._minSize(...args));\n inst.nonempty = (params) => inst.check(core._minSize(1, params));\n inst.max = (...args) => inst.check(core._maxSize(...args));\n inst.size = (...args) => inst.check(core._size(...args));\n});\nexport function set(valueType, params) {\n return new ZodSet({\n type: \"set\",\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodEnum = /*@__PURE__*/ core.$constructor(\"ZodEnum\", (inst, def) => {\n core.$ZodEnum.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.enumProcessor(inst, ctx, json, params);\n inst.enum = def.entries;\n // reuse the parsed value set so a numeric TS enum's reverse-mapping keys stay out\n inst.options = [...inst._zod.values];\n const keys = new Set(Object.keys(def.entries));\n inst.extract = (values, params) => {\n const newEntries = {};\n for (const value of values) {\n if (keys.has(value)) {\n newEntries[value] = def.entries[value];\n }\n else\n throw new Error(`Key ${value} not found in enum`);\n }\n return new ZodEnum({\n ...def,\n checks: [],\n ...util.normalizeParams(params),\n entries: newEntries,\n });\n };\n inst.exclude = (values, params) => {\n const newEntries = { ...def.entries };\n for (const value of values) {\n if (keys.has(value)) {\n delete newEntries[value];\n }\n else\n throw new Error(`Key ${value} not found in enum`);\n }\n return new ZodEnum({\n ...def,\n checks: [],\n ...util.normalizeParams(params),\n entries: newEntries,\n });\n };\n});\nfunction _enum(values, params) {\n const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;\n return new ZodEnum({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\nexport { _enum as enum };\n/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead.\n *\n * ```ts\n * enum Colors { red, green, blue }\n * z.enum(Colors);\n * ```\n */\nexport function nativeEnum(entries, params) {\n return new ZodEnum({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodLiteral = /*@__PURE__*/ core.$constructor(\"ZodLiteral\", (inst, def) => {\n core.$ZodLiteral.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.literalProcessor(inst, ctx, json, params);\n inst.values = new Set(def.values);\n Object.defineProperty(inst, \"value\", {\n get() {\n if (def.values.length > 1) {\n throw new Error(\"This schema contains multiple valid literal values. Use `.values` instead.\");\n }\n return def.values[0];\n },\n });\n});\nexport function literal(value, params) {\n return new ZodLiteral({\n type: \"literal\",\n values: Array.isArray(value) ? value : [value],\n ...util.normalizeParams(params),\n });\n}\nexport const ZodFile = /*@__PURE__*/ core.$constructor(\"ZodFile\", (inst, def) => {\n core.$ZodFile.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.fileProcessor(inst, ctx, json, params);\n inst.min = (size, params) => inst.check(core._minSize(size, params));\n inst.max = (size, params) => inst.check(core._maxSize(size, params));\n inst.mime = (types, params) => inst.check(core._mime(Array.isArray(types) ? types : [types], params));\n});\nexport function file(params) {\n return core._file(ZodFile, params);\n}\nexport const ZodTransform = /*@__PURE__*/ core.$constructor(\"ZodTransform\", (inst, def) => {\n _ensureDefaultMemoizer();\n core.$ZodTransform.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.transformProcessor(inst, ctx, json, params);\n inst._zod.parse = (payload, _ctx) => {\n if (_ctx.direction === \"backward\") {\n throw new core.$ZodEncodeError(inst.constructor.name);\n }\n payload.addIssue = (issue) => {\n if (typeof issue === \"string\") {\n payload.issues.push(util.issue(issue, payload.value, def));\n }\n else {\n // for Zod 3 backwards compatibility\n const _issue = issue;\n if (_issue.fatal)\n _issue.continue = false;\n _issue.code ?? (_issue.code = \"custom\");\n if (!(\"input\" in _issue))\n _issue.input = payload.value;\n _issue.inst ?? (_issue.inst = inst);\n // _issue.continue ??= true;\n payload.issues.push(util.issue(_issue));\n }\n };\n const output = def.transform(payload.value, payload);\n if (output instanceof Promise) {\n return output.then((output) => {\n payload.value = output;\n return payload;\n });\n }\n payload.value = output;\n return payload;\n };\n});\nexport function transform(fn) {\n return new ZodTransform({\n type: \"transform\",\n transform: fn,\n });\n}\nexport const ZodOptional = /*@__PURE__*/ core.$constructor(\"ZodOptional\", (inst, def) => {\n core.$ZodOptional.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.optionalProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function optional(innerType) {\n return new ZodOptional({\n type: \"optional\",\n innerType: innerType,\n });\n}\nexport const ZodExactOptional = /*@__PURE__*/ core.$constructor(\"ZodExactOptional\", (inst, def) => {\n core.$ZodExactOptional.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.optionalProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function exactOptional(innerType) {\n return new ZodExactOptional({\n type: \"optional\",\n innerType: innerType,\n });\n}\nexport const ZodNullable = /*@__PURE__*/ core.$constructor(\"ZodNullable\", (inst, def) => {\n core.$ZodNullable.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nullableProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function nullable(innerType) {\n return new ZodNullable({\n type: \"nullable\",\n innerType: innerType,\n });\n}\n// nullish\nexport function nullish(innerType) {\n return optional(nullable(innerType));\n}\nexport const ZodDefault = /*@__PURE__*/ core.$constructor(\"ZodDefault\", (inst, def) => {\n core.$ZodDefault.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.defaultProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n inst.removeDefault = inst.unwrap;\n});\nexport function _default(innerType, defaultValue) {\n return new ZodDefault({\n type: \"default\",\n innerType: innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\nexport const ZodPrefault = /*@__PURE__*/ core.$constructor(\"ZodPrefault\", (inst, def) => {\n core.$ZodPrefault.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.prefaultProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function prefault(innerType, defaultValue) {\n return new ZodPrefault({\n type: \"prefault\",\n innerType: innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\nexport const ZodNonOptional = /*@__PURE__*/ core.$constructor(\"ZodNonOptional\", (inst, def) => {\n core.$ZodNonOptional.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nonoptionalProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function nonoptional(innerType, params) {\n return new ZodNonOptional({\n type: \"nonoptional\",\n innerType: innerType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodSuccess = /*@__PURE__*/ core.$constructor(\"ZodSuccess\", (inst, def) => {\n core.$ZodSuccess.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.successProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function success(innerType) {\n return new ZodSuccess({\n type: \"success\",\n innerType: innerType,\n });\n}\nexport const ZodCatch = /*@__PURE__*/ core.$constructor(\"ZodCatch\", (inst, def) => {\n core.$ZodCatch.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.catchProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n inst.removeCatch = inst.unwrap;\n});\nfunction _catch(innerType, catchValue) {\n return new ZodCatch({\n type: \"catch\",\n innerType: innerType,\n catchValue: (typeof catchValue === \"function\" ? catchValue : core.util.constantCatch(catchValue)),\n });\n}\nexport { _catch as catch };\nexport const ZodNaN = /*@__PURE__*/ core.$constructor(\"ZodNaN\", (inst, def) => {\n core.$ZodNaN.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nanProcessor(inst, ctx, json, params);\n});\nexport function nan(params) {\n return core._nan(ZodNaN, params);\n}\nexport const ZodPipe = /*@__PURE__*/ core.$constructor(\"ZodPipe\", (inst, def) => {\n core.$ZodPipe.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.pipeProcessor(inst, ctx, json, params);\n inst.in = def.in;\n inst.out = def.out;\n});\nexport function pipe(in_, out) {\n return new ZodPipe({\n type: \"pipe\",\n in: in_,\n out: out,\n // ...util.normalizeParams(params),\n });\n}\nexport const ZodCodec = /*@__PURE__*/ core.$constructor(\"ZodCodec\", (inst, def) => {\n ZodPipe.init(inst, def);\n core.$ZodCodec.init(inst, def);\n});\nexport function codec(in_, out, params) {\n return new ZodCodec({\n type: \"pipe\",\n in: in_,\n out: out,\n transform: params.decode,\n reverseTransform: params.encode,\n });\n}\nexport function invertCodec(codec) {\n const def = codec._zod.def;\n return new ZodCodec({\n type: \"pipe\",\n in: def.out,\n out: def.in,\n transform: def.reverseTransform,\n reverseTransform: def.transform,\n });\n}\nexport const ZodPreprocess = /*@__PURE__*/ core.$constructor(\"ZodPreprocess\", (inst, def) => {\n ZodPipe.init(inst, def);\n core.$ZodPreprocess.init(inst, def);\n});\nexport const ZodReadonly = /*@__PURE__*/ core.$constructor(\"ZodReadonly\", (inst, def) => {\n core.$ZodReadonly.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.readonlyProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function readonly(innerType) {\n return new ZodReadonly({\n type: \"readonly\",\n innerType: innerType,\n });\n}\nexport const ZodTemplateLiteral = /*@__PURE__*/ core.$constructor(\"ZodTemplateLiteral\", (inst, def) => {\n core.$ZodTemplateLiteral.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.templateLiteralProcessor(inst, ctx, json, params);\n});\nexport function templateLiteral(parts, params) {\n return new ZodTemplateLiteral({\n type: \"template_literal\",\n parts,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodLazy = /*@__PURE__*/ core.$constructor(\"ZodLazy\", (inst, def) => {\n core.$ZodLazy.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.lazyProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.getter();\n});\nexport function lazy(getter) {\n return new ZodLazy({\n type: \"lazy\",\n getter: getter,\n });\n}\nexport const ZodPromise = /*@__PURE__*/ core.$constructor(\"ZodPromise\", (inst, def) => {\n core.$ZodPromise.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.promiseProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function promise(innerType) {\n return new ZodPromise({\n type: \"promise\",\n innerType: innerType,\n });\n}\nexport const ZodFunction = /*@__PURE__*/ core.$constructor(\"ZodFunction\", (inst, def) => {\n core.$ZodFunction.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.functionProcessor(inst, ctx, json, params);\n});\nexport function _function(params) {\n return new ZodFunction({\n type: \"function\",\n input: Array.isArray(params?.input) ? tuple(params?.input) : (params?.input ?? array(unknown())),\n output: params?.output ?? unknown(),\n });\n}\nexport { _function as function };\nexport const ZodCustom = /*@__PURE__*/ core.$constructor(\"ZodCustom\", (inst, def) => {\n core.$ZodCustom.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.customProcessor(inst, ctx, json, params);\n});\n// custom checks\nexport function check(fn) {\n const ch = new core.$ZodCheck({\n check: \"custom\",\n // ...util.normalizeParams(params),\n });\n ch._zod.check = fn;\n return ch;\n}\nexport function custom(fn, _params) {\n return core._custom(ZodCustom, fn ?? (() => true), _params);\n}\nexport function refine(fn, _params = {}) {\n return core._refine(ZodCustom, fn, _params);\n}\n// superRefine\nexport function superRefine(fn, params) {\n return core._superRefine(fn, params);\n}\n// Re-export describe and meta from core\nexport const describe = core.describe;\nexport const meta = core.meta;\nexport const ZodInstanceOf = /*@__PURE__*/ core.$constructor(\"ZodInstanceOf\", (inst, def) => {\n ZodCustom.init(inst, def);\n}, {\n properties(shape, params) {\n // asserts in place, so the narrowed output type is truthful without a wrapper\n return this.check(core._properties(shape, params));\n },\n});\nfunction _instanceof(cls, params = {}) {\n const inst = new ZodInstanceOf({\n type: \"custom\",\n check: \"custom\",\n fn: (data) => data instanceof cls,\n abort: true,\n ...util.normalizeParams(params),\n });\n inst._zod.bag.Class = cls;\n // Override check to emit invalid_type instead of custom\n inst._zod.check = (payload) => {\n if (!(payload.value instanceof cls)) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: cls.name,\n input: payload.value,\n inst,\n path: [...(inst._zod.def.path ?? [])],\n });\n }\n };\n return inst;\n}\nexport { _instanceof as instanceof };\n// stringbool\nexport const stringbool = (...args) => core._stringbool({\n Codec: ZodCodec,\n Boolean: ZodBoolean,\n String: ZodString,\n}, ...args);\nexport function json(params) {\n const jsonSchema = lazy(() => {\n return union([string(params), number(), boolean(), _null(), array(jsonSchema), record(string(), jsonSchema)]);\n });\n return jsonSchema;\n}\n// preprocess\nexport function preprocess(fn, schema) {\n return new ZodPreprocess({\n type: \"pipe\",\n in: transform(fn),\n out: schema,\n });\n}\n","import { getBackendSrv } from '@grafana/runtime';\n// biome-ignore lint/suspicious/noDeprecatedImports: these calls use current overloads, without schedulers or result selectors\nimport { firstValueFrom, fromEvent, merge, mergeMap, throwError } from 'rxjs';\nimport { z } from 'zod';\nimport { ASSISTANT_PLUGIN_ID } from '../plugin';\nimport type {\n CreatedInvestigation,\n CreateInvestigationInput,\n InvestigationReport,\n InvestigationRequestOptions,\n InvestigationStatus,\n} from './types';\n\nconst baseUrl = `api/plugins/${ASSISTANT_PLUGIN_ID}/resources/api/v2/investigations`;\n\nconst createdSchema = z.object({\n investigationId: z.string().min(1),\n chatId: z.string(),\n}) satisfies z.ZodType<CreatedInvestigation>;\n\nconst statusSchema = z.object({\n investigationId: z.string().min(1),\n chatId: z.string(),\n state: z.string().optional(),\n title: z.string().optional(),\n summary: z.string().optional(),\n failureReason: z.string().optional(),\n errorMessage: z.string().optional(),\n completionQuality: z.string().optional(),\n degradedReason: z.string().optional(),\n}) satisfies z.ZodType<InvestigationStatus>;\n\nconst reportSchema = z.object({\n investigationId: z.string().min(1),\n reportPending: z.boolean(),\n reportContent: z.string().optional(),\n reportSpec: z\n .object({\n root: z.string(),\n elements: z.record(\n z.string(),\n z.object({\n type: z.string(),\n props: z.record(z.string(), z.unknown()),\n children: z.array(z.string()).optional(),\n })\n ),\n })\n .optional(),\n}) satisfies z.ZodType<InvestigationReport>;\n\nasync function request<T>(\n method: 'GET' | 'POST',\n suffix: string,\n schema: z.ZodType<T>,\n options: InvestigationRequestOptions,\n data?: CreateInvestigationInput\n): Promise<T> {\n const signal = options.signal;\n signal?.throwIfAborted();\n const response$ = getBackendSrv().fetch<unknown>({\n url: `${baseUrl}${suffix}`,\n method,\n data,\n abortSignal: options.signal,\n retry: 0,\n showErrorAlert: false,\n showSuccessAlert: false,\n });\n // Unsubscribe on cancellation even on Grafana versions that ignore abortSignal.\n const response = await firstValueFrom(\n signal\n ? merge(response$, fromEvent(signal, 'abort').pipe(mergeMap(() => throwError(() => signal.reason))))\n : response$\n );\n return z.object({ status: z.literal('success'), data: schema }).parse(response.data).data;\n}\n\nfunction resourcePath(investigationId: string): string {\n if (investigationId.trim() === '') {\n throw new Error('An investigation ID is required. Use the ID returned by createInvestigation.');\n }\n return `/${encodeURIComponent(investigationId)}`;\n}\n\n/** Start an investigation. No automatic retries: retrying creation can create duplicates. */\nexport async function createInvestigation(\n input: CreateInvestigationInput,\n options: InvestigationRequestOptions = {}\n): Promise<CreatedInvestigation> {\n if (input.instruction.trim() === '') {\n throw new Error('An investigation instruction must contain non-whitespace text.');\n }\n return request('POST', '', createdSchema, options, input);\n}\n\n/** Read lifecycle state once. The caller controls polling intervals and deadlines. */\nexport async function getInvestigationStatus(\n investigationId: string,\n options: InvestigationRequestOptions = {}\n): Promise<InvestigationStatus> {\n return request('GET', resourcePath(investigationId), statusSchema, options);\n}\n\n/** Read the current report snapshot. A session that has not started can return 404. */\nexport async function getInvestigationReport(\n investigationId: string,\n options: InvestigationRequestOptions = {}\n): Promise<InvestigationReport> {\n return request('GET', `${resourcePath(investigationId)}/snapshot`, reportSchema, options);\n}\n","import { config, isFetchError } from '@grafana/runtime';\nimport { Observable } from 'rxjs';\nimport { z } from 'zod';\nimport { ASSISTANT_PLUGIN_ID } from '../plugin';\nimport { getInvestigationReport, getInvestigationStatus } from './client';\nimport type { InvestigationEvent, InvestigationReport } from './types';\n\nconst refreshIntervalMs = 5000;\nconst connectTimeoutMs = 30000;\nconst envelopeSchema = z.object({ type: z.string(), payload: z.unknown().optional() });\nconst textDeltaSchema = z.object({\n chatId: z.string(),\n messageId: z.string().min(1),\n contentIndex: z.number().int().nonnegative(),\n contentType: z.string(),\n delta: z.string().optional(),\n audience: z.string().optional(),\n});\n\n/**\n * Observe an existing investigation as the signed-in Grafana user.\n * Each subscription owns its requests and event connection. Unsubscribe stops\n * observation, never server-side work. A transport error closes the subscription;\n * resubscribe to recover current snapshots (text deltas are not replayed).\n */\nexport function observeInvestigation(investigationId: string): Observable<InvestigationEvent> {\n return new Observable((subscriber) => {\n const controller = new AbortController();\n let source: EventSource | undefined;\n let connectedChatId: string | undefined;\n let connectTimer: ReturnType<typeof setTimeout> | undefined;\n let refreshTimer: ReturnType<typeof setTimeout> | undefined;\n let eventTimer: ReturnType<typeof setTimeout> | undefined;\n let refreshing = false;\n let refreshRequested = false;\n let previousStatus: string | undefined;\n let previousReport: string | undefined;\n\n const fail = (error: unknown) => subscriber.error(error);\n\n function openStream(chatId: string) {\n // The status API serializes an unassigned Go UUID as the all-zero string.\n if (\n subscriber.closed ||\n !chatId ||\n chatId === '00000000-0000-0000-0000-000000000000' ||\n connectedChatId === chatId\n ) {\n return;\n }\n source?.close();\n clearTimeout(connectTimer);\n connectedChatId = chatId;\n const appSubUrl = config.appSubUrl ?? '';\n const url = `${appSubUrl}/api/plugins/${ASSISTANT_PLUGIN_ID}/resources/api/events/chats/${encodeURIComponent(chatId)}`;\n const connection = new EventSource(url);\n source = connection;\n connectTimer = setTimeout(\n () => fail(new Error('Investigation event stream did not connect. Subscribe again to retry.')),\n connectTimeoutMs\n );\n connection.onopen = () => {\n if (source !== connection || subscriber.closed) {\n return;\n }\n clearTimeout(connectTimer);\n refreshFromEvent();\n };\n connection.onerror = () => {\n if (source !== connection || subscriber.closed) {\n return;\n }\n fail(new Error('Investigation event stream disconnected. Subscribe again to refresh state and retry.'));\n };\n connection.onmessage = (message: MessageEvent<string>) => {\n if (subscriber.closed || source !== connection) {\n return;\n }\n try {\n const event = envelopeSchema.parse(JSON.parse(message.data));\n if (event.type === 'message.content.delta') {\n const data = textDeltaSchema.parse(event.payload);\n if (\n data.chatId === chatId &&\n data.contentType === 'text' &&\n data.delta &&\n (!data.audience || data.audience === 'user')\n ) {\n subscriber.next({\n type: 'progress',\n investigationId,\n messageId: data.messageId,\n contentIndex: data.contentIndex,\n delta: data.delta,\n });\n }\n } else if (\n event.type === 'connection.ready' ||\n event.type === 'lodestone.session.status' ||\n event.type === 'lodestone.report.pending' ||\n event.type === 'lodestone.canvas.update' ||\n event.type === 'message.stream.complete'\n ) {\n // Events are hints: persisted API state owns lifecycle and report truth.\n refreshFromEvent();\n }\n } catch (error) {\n fail(error);\n }\n };\n }\n\n function refreshFromEvent() {\n if (refreshing) {\n refreshRequested = true;\n } else if (eventTimer === undefined) {\n eventTimer = setTimeout(() => {\n eventTimer = undefined;\n requestRefresh();\n }, 250);\n }\n }\n\n async function refresh() {\n if (subscriber.closed) {\n return;\n }\n refreshing = true;\n refreshRequested = false;\n try {\n const status = await getInvestigationStatus(investigationId, { signal: controller.signal });\n if (subscriber.closed) {\n return;\n }\n const serializedStatus = JSON.stringify(status);\n if (serializedStatus !== previousStatus) {\n previousStatus = serializedStatus;\n subscriber.next({ type: 'status', status });\n }\n if (subscriber.closed) {\n return;\n }\n const terminal = status.state === 'completed' || status.state === 'failed' || status.state === 'cancelled';\n // Connect before fetching the snapshot so subsequent events request another read.\n if (!terminal) {\n openStream(status.chatId);\n }\n let report: InvestigationReport | undefined;\n try {\n report = await getInvestigationReport(investigationId, { signal: controller.signal });\n } catch (error) {\n // A readable investigation can exist before its engine session is created.\n if (!isFetchError(error) || error.status !== 404) {\n throw error;\n }\n }\n if (subscriber.closed) {\n return;\n }\n if (report) {\n const serializedReport = JSON.stringify(report);\n if (serializedReport !== previousReport) {\n previousReport = serializedReport;\n subscriber.next({ type: 'report', report });\n }\n }\n // Completed rows can still have an in-flight report fork. Keep observing it.\n if (terminal && !report?.reportPending && !refreshRequested) {\n subscriber.complete();\n } else if (terminal && report?.reportPending) {\n openStream(status.chatId);\n }\n } catch (error) {\n fail(error);\n } finally {\n refreshing = false;\n if (!subscriber.closed) {\n // Coalesce event bursts and serialize reads so older responses cannot win.\n refreshTimer = setTimeout(requestRefresh, refreshRequested ? 250 : refreshIntervalMs);\n }\n }\n }\n\n function requestRefresh() {\n if (subscriber.closed) {\n return;\n }\n if (refreshing) {\n refreshRequested = true;\n return;\n }\n clearTimeout(refreshTimer);\n clearTimeout(eventTimer);\n eventTimer = undefined;\n // refresh owns request failures; this also catches unexpected orchestration errors.\n refresh().catch(fail);\n }\n\n requestRefresh();\n return () => {\n controller.abort();\n clearTimeout(refreshTimer);\n clearTimeout(eventTimer);\n clearTimeout(connectTimer);\n if (source) {\n source.onopen = null;\n source.onmessage = null;\n source.onerror = null;\n source.close();\n }\n };\n });\n}\n","import type { GrotRetryOptions } from './types';\n\n/**\n * Retry policy copied from the Go SDK's `defaultRetryPolicy` (packages/assistant-go/retry.go): 3 attempts,\n * 500 ms initial backoff, factor 2, 10 s cap, 10% jitter. The statuses are those of `IsRetryable` (errors.go):\n * 429, 502, 503 and 504. Go also retries timeouts; a browser fetch error has no stable timeout marker, so those\n * are not retried here.\n */\nconst defaults = { maxAttempts: 3, initialBackoffMs: 500, maxBackoffMs: 10_000, factor: 2, jitter: 0.1 };\nconst maxTimeoutMs = 2_147_483_647;\nconst retryableStatuses = new Set([429, 502, 503, 504]);\n\n/** `value` when it is a whole number of at least 1, else `fallback`. Guards NaN, Infinity and fractions. */\nfunction positiveInteger(value: number | undefined, fallback: number): number {\n return typeof value === 'number' && Number.isSafeInteger(value) && value >= 1 ? value : fallback;\n}\n\n/** `value` when it is a finite number of at least 0, else `fallback`. Guards NaN and Infinity. */\nfunction finiteNonNegative(value: number | undefined, fallback: number): number {\n return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : fallback;\n}\n\nexport function isRetryableStatus(error: unknown): boolean {\n const status = typeof error === 'object' && error !== null ? (error as { status?: unknown }).status : undefined;\n return typeof status === 'number' && retryableStatuses.has(status);\n}\n\n/** Wait before retry number `attempt` (1 is the wait after the first failure). `random` is injectable for tests. */\nexport function backoffMs(attempt: number, options: GrotRetryOptions = {}, random = Math.random): number {\n const initial = finiteNonNegative(options.initialBackoffMs, defaults.initialBackoffMs);\n const max = finiteNonNegative(options.maxBackoffMs, defaults.maxBackoffMs);\n // 0 * 2 ** 1024 is NaN, and setTimeout fires at once past 2^31 - 1 ms, so clamp both (after jitter too).\n const grown = initial * defaults.factor ** (attempt - 1);\n const base = Math.min(Number.isNaN(grown) ? 0 : grown, max, maxTimeoutMs);\n return Math.min(base * (1 + (random() * 2 - 1) * defaults.jitter), maxTimeoutMs);\n}\n\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal?.aborted) {\n reject(signal.reason);\n return;\n }\n const onAbort = () => {\n clearTimeout(timer);\n reject(signal?.reason);\n };\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n}\n\n/** Run `attempt`, repeating it on a retryable status when `retry` is enabled. Aborting stops the wait. */\nexport async function withRetry<T>(\n attempt: () => Promise<T>,\n retry: boolean | GrotRetryOptions | undefined,\n signal?: AbortSignal\n): Promise<T> {\n if (!retry) {\n return attempt();\n }\n const options = retry === true ? {} : retry;\n const maxAttempts = positiveInteger(options.maxAttempts, defaults.maxAttempts);\n for (let n = 1; ; n++) {\n try {\n return await attempt();\n } catch (error) {\n if (n >= maxAttempts || signal?.aborted || !isRetryableStatus(error)) {\n throw error;\n }\n await sleep(backoffMs(n, options), signal);\n }\n }\n}\n","import { getBackendSrv } from '@grafana/runtime';\nimport { firstValueFrom, fromEvent, merge, mergeMap, throwError } from 'rxjs';\nimport { z } from 'zod';\nimport { ASSISTANT_PLUGIN_ID } from '../plugin';\nimport { withRetry } from './retry';\nimport type {\n BindGrotInput,\n CreateGrotInput,\n CreateGrotTopicInput,\n Grot,\n GrotDirectTopic,\n GrotEvent,\n GrotLane,\n GrotLaneClosed,\n GrotMessage,\n GrotMessagePart,\n GrotMessagesPage,\n GrotRequestOptions,\n GrotTopic,\n GrotTopicAccepted,\n GrotTopicList,\n GrotTopicMessageInput,\n GrotWork,\n ListGrotsOptions,\n ListGrotTopicMessagesOptions,\n ListGrotTopicsOptions,\n ParsedGrotMessage,\n ReadGrotLaneOptions,\n UpdateGrotInput,\n UpdateGrotTopicInput,\n} from './types';\n\nconst baseUrl = `api/plugins/${ASSISTANT_PLUGIN_ID}/resources/api/v1/durable-agents`;\n\nconst grotSchema = z.object({\n id: z.string().min(1),\n name: z.string(),\n purpose: z.string().optional(),\n role: z.string().optional(),\n scope: z.string().optional(),\n teamId: z.string().optional(),\n status: z.string().optional(),\n avatar: z.string().optional(),\n revision: z.number(),\n labels: z.record(z.string(), z.string()).optional(),\n}) satisfies z.ZodType<Grot>;\n\nconst grotListSchema = z.object({ agents: z.array(grotSchema) });\n\nconst workSchema = z.object({ id: z.string().min(1), state: z.string() }) satisfies z.ZodType<GrotWork>;\n\nconst laneClosedSchema = z.object({\n laneKey: z.string(),\n closed: z.boolean(),\n cancelledFollowUps: z.number(),\n}) satisfies z.ZodType<GrotLaneClosed>;\n\nconst messagesFields = {\n messages: z.array(z.record(z.string(), z.unknown())),\n total: z.number().optional(),\n from: z.number().optional(),\n reset: z.boolean().optional(),\n};\n\nconst messagesPageSchema = z.object(messagesFields) satisfies z.ZodType<GrotMessagesPage>;\n\nconst laneSchema = z.object({\n ...messagesFields,\n laneKey: z.string(),\n topicId: z.string(),\n chatId: z.string(),\n title: z.string(),\n settled: z.boolean(),\n runningWorkId: z.string().optional(),\n pendingWork: z.number(),\n busy: z.boolean(),\n}) satisfies z.ZodType<GrotLane>;\n\nconst topicSchema = z.object({\n id: z.string().min(1),\n agentId: z.string(),\n threadId: z.string(),\n number: z.number(),\n title: z.string(),\n chatId: z.string(),\n revision: z.number(),\n createdBy: z.string(),\n archivedAt: z.string().optional(),\n pinnedAt: z.string().optional(),\n}) satisfies z.ZodType<GrotTopic>;\n\nconst topicAcceptedSchema = z.object({\n topic: topicSchema,\n work: workSchema,\n}) satisfies z.ZodType<GrotTopicAccepted>;\n\nconst directTopicSchema = topicSchema.extend({\n runningWorkId: z.string().optional(),\n helpersWorking: z.boolean().optional(),\n}) satisfies z.ZodType<GrotDirectTopic>;\n\nconst topicListSchema = z.object({\n thread: z.object({ id: z.string(), agentId: z.string(), title: z.string() }).optional(),\n topics: z.array(directTopicSchema),\n settledCount: z.number().optional(),\n}) satisfies z.ZodType<GrotTopicList>;\n\nasync function request<T>(\n method: 'GET' | 'POST' | 'PUT',\n path: string,\n schema: z.ZodType<T>,\n options: GrotRequestOptions,\n data?: unknown,\n query?: Record<string, string>,\n retryable = false\n): Promise<T> {\n return withRetry(\n () => requestOnce(method, path, schema, options, data, query),\n retryable ? options.retry : undefined,\n options.signal\n );\n}\n\nasync function requestOnce<T>(\n method: 'GET' | 'POST' | 'PUT',\n path: string,\n schema: z.ZodType<T>,\n options: GrotRequestOptions,\n data?: unknown,\n query?: Record<string, string>\n): Promise<T> {\n const signal = options.signal;\n signal?.throwIfAborted();\n const search = query && Object.keys(query).length > 0 ? `?${new URLSearchParams(query).toString()}` : '';\n const response$ = getBackendSrv().fetch<unknown>({\n url: `${baseUrl}${path}${search}`,\n method,\n data,\n abortSignal: signal,\n retry: 0,\n showErrorAlert: false,\n showSuccessAlert: false,\n });\n // Unsubscribe on cancellation even on Grafana versions that ignore abortSignal.\n const response = await firstValueFrom(\n signal\n ? merge(response$, fromEvent(signal, 'abort').pipe(mergeMap(() => throwError(() => signal.reason))))\n : response$\n );\n return z.object({ data: schema }).parse(response.data).data;\n}\n\n/** Copy the named fields that are set, so extra properties a caller passes never reach the backend. */\nfunction pick<T extends object, K extends keyof T>(source: T, keys: readonly K[]): Pick<T, K> {\n const out: Partial<Pick<T, K>> = {};\n for (const key of keys) {\n if (source[key] !== undefined) {\n out[key] = source[key];\n }\n }\n return out as Pick<T, K>;\n}\n\nfunction requireValue(value: string, name: string): string {\n if (value.trim() === '') {\n throw new Error(`${name} is required.`);\n }\n return encodeURIComponent(value);\n}\n\nfunction grotPath(grotId: string, suffix = ''): string {\n return `/${requireValue(grotId, 'A Grot ID')}${suffix}`;\n}\n\nfunction requireMessage(input: { content: string; dedupeKey: string }): void {\n if (input.content.trim() === '') {\n throw new Error('content must contain non-whitespace text.');\n }\n if (input.dedupeKey === '') {\n throw new Error('dedupeKey is required.');\n }\n}\n\n/**\n * List the Grots the signed-in user may use (newest 100, newest first).\n * Needs `durable-agents.<scope>:read` for each scope listed.\n * @experimental This API is under active development and may change in future releases.\n */\nexport async function listGrots(options: ListGrotsOptions = {}): Promise<Grot[]> {\n const query = options.labelSelector ? { labelSelector: options.labelSelector } : undefined;\n const list = await request('GET', '', grotListSchema, options, undefined, query, true);\n return list.agents;\n}\n\n/**\n * Read one Grot. Another user's private Grot returns 404.\n *\n * @experimental This API is under active development and may change in future releases.\n */\nexport async function getGrot(grotId: string, options: GrotRequestOptions = {}): Promise<Grot> {\n return request('GET', grotPath(grotId), grotSchema, options, undefined, undefined, true);\n}\n\n/**\n * Create a Grot. Needs `durable-agents.<scope>:create` for the new Grot's scope. Never retried, even with\n * `retry` set: retrying creation can create duplicates.\n *\n * The call sends exactly the fields of {@link CreateGrotInput} and nothing else. A private Grot (the default scope)\n * needs `ownerDelegation: true`, the creator's explicit consent for background work with their own Grafana\n * permissions. On a `team` Grot the backend refuses it, so it is dropped from the request.\n *\n * Without `executionBinding` and `grant` the Grot is created as a `draft` and cannot run: a run, such as\n * `createGrotTopic`, fails with 400 until you call {@link bindGrot}. Pass both to create a Grot that can run at\n * once. That turns on its background work and gives it tool access, so it also needs `durable-agents:configure`\n * and `durable-agents.<scope>:execute`. `grant: { allowAllTools: true }` lets the Grot call every tool. Set these\n * only when the person using your code has explicitly agreed; they are never defaulted.\n * @experimental This API is under active development and may change in future releases.\n */\nexport async function createGrot(input: CreateGrotInput, options: GrotRequestOptions = {}): Promise<Grot> {\n if (input.name.trim() === '') {\n throw new Error('A Grot name is required.');\n }\n const body = pick(input, [\n 'name',\n 'purpose',\n 'role',\n 'scope',\n 'teamId',\n 'ownerDelegation',\n 'executionBinding',\n 'grant',\n 'labels',\n ] as const);\n if (body.scope === 'team') {\n // The backend refuses ownerDelegation on a team Grot with a 400, so never send it.\n delete body.ownerDelegation;\n }\n return request('POST', '', grotSchema, options, body);\n}\n\n/**\n * Give an existing Grot access so it can run (`PUT /durable-agents/{id}/binding`; the Go SDK has no such call). On\n * a `draft` Grot this also activates it and turns on its background work; on an active one it replaces the tool\n * grant. Needs `durable-agents:configure` and `durable-agents.<scope>:write`, plus `:execute` for a draft. A stale\n * `expectedRevision` returns 409, as does a Grot with a run in progress; wait for it to finish, re-read the Grot\n * and call again. Never retried, even with `retry` set. Returns the updated Grot.\n *\n * `grant: { allowAllTools: true }` lets the Grot call every tool. Only call this when the person using your code\n * has explicitly agreed to give the Grot that access.\n * @experimental This API is under active development and may change in future releases.\n */\nexport async function bindGrot(grotId: string, input: BindGrotInput, options: GrotRequestOptions = {}): Promise<Grot> {\n const path = grotPath(grotId, '/binding');\n requireRevision(input.expectedRevision);\n return request(\n 'PUT',\n path,\n grotSchema,\n options,\n pick(input, ['expectedRevision', 'executionBinding', 'grant'] as const)\n );\n}\n\n/**\n * Wake a Grot with a workflow event in its own conversation. Needs `durable-agents.<scope>:execute`.\n * Retry only with the same workflow, laneKey, dedupeKey and body. The API limits `workflow` to 253 characters,\n * `title`, `dedupeKey`, `runId` and `stepId` to 256, and `content` to 16000. Unlike direct-topic keys, a workflow\n * `dedupeKey` may contain \":\".\n * @experimental This API is under active development and may change in future releases.\n */\nexport async function wakeGrot(grotId: string, event: GrotEvent, options: GrotRequestOptions = {}): Promise<GrotWork> {\n if (event.workflow.trim() === '' || event.content.trim() === '') {\n throw new Error('workflow and content must contain non-whitespace text.');\n }\n if (event.dedupeKey === '') {\n throw new Error('dedupeKey is required.');\n }\n return request(\n 'POST',\n grotPath(grotId, '/workflow-events'),\n workSchema,\n options,\n pick(event, ['workflow', 'title', 'dedupeKey', 'content', 'runId', 'stepId', 'laneKey'] as const),\n undefined,\n true\n );\n}\n\n/** Close a lane to free one of the Grot's 50 open lanes. An unknown lane returns `closed: false`. Never retried, even\n * with `retry`: a repeat after a lost response would report `closed: false` for a lane the first call closed.\n *\n * @experimental This API is under active development and may change in future releases.\n */\nexport async function closeGrotLane(\n grotId: string,\n laneKey: string,\n options: GrotRequestOptions = {}\n): Promise<GrotLaneClosed> {\n requireValue(laneKey, 'laneKey'); // Validation only: the key goes in the JSON body as is.\n return request('POST', grotPath(grotId, '/workflow-events/lanes/close'), laneClosedSchema, options, { laneKey });\n}\n\n/**\n * Read a lane you opened with `wakeGrot`. Needs `durable-agents.<scope>:execute` and `:read`, plus\n * `conversations.tenant:read`. A key you never sent returns 404.\n * @experimental This API is under active development and may change in future releases.\n */\nexport async function readGrotLane(\n grotId: string,\n laneKey: string,\n options: ReadGrotLaneOptions = {}\n): Promise<GrotLane> {\n requireValue(laneKey, 'laneKey'); // Validation only: the key goes in the query string, percent-encoded.\n const query: Record<string, string> = { laneKey };\n if (options.after) {\n query.after = options.after;\n }\n return request('GET', grotPath(grotId, '/workflow-events/lanes'), laneSchema, options, undefined, query, true);\n}\n\n/**\n * Open a topic in the signed-in user's direct conversation with a Grot and send its first message.\n * Needs `durable-agents.<scope>:execute`, plus `conversations.user:create` for the first topic and\n * `conversations.user:write` for later topics and for retries. Retries only with `retry`\n * (the `dedupeKey` makes that safe); otherwise retry by hand with the same `dedupeKey`.\n * @experimental This API is under active development and may change in future releases.\n */\nexport async function createGrotTopic(\n grotId: string,\n input: CreateGrotTopicInput,\n options: GrotRequestOptions = {}\n): Promise<GrotTopicAccepted> {\n requireMessage(input);\n return request(\n 'POST',\n grotPath(grotId, '/direct/topics'),\n topicAcceptedSchema,\n options,\n pick(input, ['title', 'content', 'dedupeKey'] as const),\n undefined,\n true\n );\n}\n\n/**\n * Send a follow-up message in an existing topic. Posting to an archived topic restores it.\n * Needs `durable-agents.<scope>:execute` and `conversations.user:write`.\n * @experimental This API is under active development and may change in future releases.\n */\nexport async function postGrotTopicMessage(\n grotId: string,\n topicId: string,\n message: GrotTopicMessageInput,\n options: GrotRequestOptions = {}\n): Promise<GrotTopicAccepted> {\n const topic = requireValue(topicId, 'A topic ID');\n requireMessage(message);\n return request(\n 'POST',\n grotPath(grotId, `/direct/topics/${topic}/messages`),\n topicAcceptedSchema,\n options,\n pick(message, ['content', 'dedupeKey'] as const),\n undefined,\n true\n );\n}\n\n/**\n * List the topics in the signed-in user's direct conversation with a Grot. 404 before the first topic.\n * Needs `durable-agents.<scope>:read` and `conversations.user:read`.\n * @experimental This API is under active development and may change in future releases.\n */\nexport async function listGrotTopics(grotId: string, options: ListGrotTopicsOptions = {}): Promise<GrotTopicList> {\n const query = options.excludeSettled ? { settled: 'false' } : undefined;\n return request('GET', grotPath(grotId, '/direct'), topicListSchema, options, undefined, query, true);\n}\n\n/**\n * Read a topic's messages, oldest first. Pass the topic's `chatId`, not its `id`.\n * Needs `durable-agents.<scope>:read` and read access on that chat (`conversations.user:read` for your direct\n * topics).\n * @experimental This API is under active development and may change in future releases.\n */\nexport async function listGrotTopicMessages(\n grotId: string,\n chatId: string,\n options: ListGrotTopicMessagesOptions = {}\n): Promise<GrotMessagesPage> {\n const chat = requireValue(chatId, 'A chat ID');\n const query = options.after ? { after: options.after } : undefined;\n return request(\n 'GET',\n grotPath(grotId, `/conversations/${chat}/messages`),\n messagesPageSchema,\n options,\n undefined,\n query,\n true\n );\n}\n\n/**\n * Thrown by `updateGrot` when you sent `labels` and the response has no `labels` key: a backend that predates\n * labels (grafana-assistant-app #17893) applied the other fields and ignored the labels, so even `{}` did not clear\n * them. Mirrors the Go SDK's `ErrLabelsNotSupported`. `grot` is the updated Grot.\n * @experimental This API is under active development and may change in future releases.\n */\nexport class GrotLabelsNotSupportedError extends Error {\n constructor(readonly grot: Grot) {\n super(`Grot ${grot.id}: labels were not updated because the backend does not support labels.`);\n this.name = 'GrotLabelsNotSupportedError';\n }\n}\n\n/**\n * Change a Grot's name, purpose, role or labels (Go: `UpdateGrot`, `PUT /durable-agents/{id}`). A stale\n * `expectedRevision` returns 409. Needs `durable-agents.<scope>:write`. Never retried. Throws {@link GrotLabelsNotSupportedError} (carrying the updated Grot)\n * when `labels` was sent and the backend did not return labels.\n *\n * The body is built from `expectedRevision`, `name`, `purpose`, `role` and `labels` only. The backend's update body\n * also accepts avatar, budget, parallel runs and memory mode, which the Go SDK leaves out and so does this client;\n * the tool grant and execution binding have their own route, {@link bindGrot}, and cannot be sent from here.\n * @experimental This API is under active development and may change in future releases.\n */\nexport async function updateGrot(\n grotId: string,\n input: UpdateGrotInput,\n options: GrotRequestOptions = {}\n): Promise<Grot> {\n const id = grotPath(grotId);\n requireRevision(input.expectedRevision);\n const updated = await request(\n 'PUT',\n id,\n grotSchema,\n options,\n pick(input, ['expectedRevision', 'name', 'purpose', 'role', 'labels'] as const)\n );\n if (input.labels !== undefined && updated.labels === undefined) {\n throw new GrotLabelsNotSupportedError(updated);\n }\n return updated;\n}\n\n/**\n * Rename, archive, restore, pin or unpin a topic (Go: `UpdateTopic`,\n * `PUT /durable-agents/{id}/direct/topics/{topicId}`). A stale `expectedRevision` returns 409. Needs\n * `durable-agents.<scope>:execute` and `conversations.user:write`. Never retried.\n * @experimental This API is under active development and may change in future releases.\n */\nexport async function updateGrotTopic(\n grotId: string,\n topicId: string,\n input: UpdateGrotTopicInput,\n options: GrotRequestOptions = {}\n): Promise<GrotTopic> {\n const path = grotPath(grotId, `/direct/topics/${requireValue(topicId, 'A topic ID')}`);\n requireRevision(input.expectedRevision);\n return request(\n 'PUT',\n path,\n topicSchema,\n options,\n pick(input, ['expectedRevision', 'title', 'archived', 'pinned'] as const)\n );\n}\n\n/**\n * Archive a topic (Go: `ArchiveTopic`). Same route and RBAC as {@link updateGrotTopic}; post a message to restore it.\n *\n * @experimental This API is under active development and may change in future releases.\n */\nexport async function archiveGrotTopic(\n grotId: string,\n topicId: string,\n expectedRevision: number,\n options: GrotRequestOptions = {}\n): Promise<GrotTopic> {\n return updateGrotTopic(grotId, topicId, { expectedRevision, archived: true }, options);\n}\n\nfunction requireRevision(revision: number): void {\n if (!Number.isInteger(revision) || revision < 1) {\n throw new Error('expectedRevision must be a whole number of at least 1.');\n }\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> | undefined {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined;\n}\n\nfunction parsePart(value: unknown): GrotMessagePart {\n const part = asRecord(value);\n const type = typeof part?.type === 'string' ? part.type : '';\n const text = typeof part?.text === 'string' ? part.text : '';\n if (!part) {\n return { kind: 'unknown', type, raw: {} };\n }\n if (type === 'text' || type === 'reasoning') {\n return { kind: type, text };\n }\n if (type.startsWith('tool-') || type === 'dynamic-tool') {\n return {\n kind: 'tool',\n type,\n ...(typeof part.toolName === 'string' ? { toolName: part.toolName } : {}),\n ...(typeof part.state === 'string' ? { state: part.state } : {}),\n };\n }\n return { kind: 'unknown', type, raw: part };\n}\n\n/**\n * Decode a raw message from `listGrotTopicMessages` or `readGrotLane` (Go: `ParseTopicMessage`). Like Go it throws\n * when the value is not an object or `id` / `role` is not a string. Unlike Go it keeps unknown roles and part types\n * readable (`kind: 'unknown'`) instead of failing. `GrotMessage` itself is unchanged.\n * @experimental This API is under active development and may change in future releases.\n */\nexport function parseGrotTopicMessage(raw: GrotMessage): ParsedGrotMessage {\n const msg = asRecord(raw);\n if (!msg) {\n throw new Error('A topic message must be an object.');\n }\n const { id, role, created, parts, metadata } = msg;\n if (typeof id !== 'string' || (role !== undefined && typeof role !== 'string')) {\n throw new Error('A topic message needs a string id and role.');\n }\n const parsed = Array.isArray(parts) ? parts.map(parsePart) : [];\n const base = {\n id,\n parts: parsed,\n raw: msg,\n text: parsed.flatMap((p) => (p.kind === 'text' && p.text !== '' ? [p.text] : [])).join('\\n'),\n ...(typeof created === 'string' ? { created } : {}),\n ...(metadata !== undefined ? { metadata } : {}),\n };\n if (role === 'user' || role === 'assistant' || role === 'system') {\n return { ...base, kind: role };\n }\n return { ...base, kind: 'unknown', role: role ?? '' };\n}\n","/**\n * Lightweight semantic version comparison utility.\n * Replaces semver library to reduce bundle size.\n *\n * Supports standard semver format: major.minor.patch[-prerelease][+build]\n * Pre-release versions are considered lower than release versions.\n * Build metadata is ignored for comparison purposes.\n */\n\ninterface ParsedVersion {\n major: number;\n minor: number;\n patch: number;\n prerelease?: string;\n}\n\n/**\n * Parses a semantic version string into its components.\n * @param version - Version string (e.g., \"1.2.3\", \"0.0.2-ga\", \"1.2.3+build\")\n * @returns Parsed version object or null if invalid\n */\nfunction parseVersion(version: string): ParsedVersion | null {\n // Remove build metadata (everything after +)\n const withoutBuild = version.split('+')[0];\n\n // Split into version and prerelease parts\n const parts = withoutBuild.split('-');\n const versionPart = parts[0];\n const prerelease = parts.length > 1 ? parts.slice(1).join('-') : undefined;\n\n // Parse major.minor.patch\n const numbers = versionPart.split('.').map(Number);\n if (numbers.length !== 3 || numbers.some(isNaN)) {\n return null;\n }\n\n return {\n major: numbers[0],\n minor: numbers[1],\n patch: numbers[2],\n prerelease,\n };\n}\n\n/**\n * Compares two semantic versions.\n * @param v1 - First version string\n * @param v2 - Second version string\n * @returns -1 if v1 < v2, 0 if v1 === v2, 1 if v1 > v2, or null if either version is invalid\n */\nfunction compareVersions(v1: string, v2: string): number | null {\n const parsed1 = parseVersion(v1);\n const parsed2 = parseVersion(v2);\n\n if (!parsed1 || !parsed2) {\n return null;\n }\n\n // Compare major version\n if (parsed1.major !== parsed2.major) {\n return parsed1.major > parsed2.major ? 1 : -1;\n }\n\n // Compare minor version\n if (parsed1.minor !== parsed2.minor) {\n return parsed1.minor > parsed2.minor ? 1 : -1;\n }\n\n // Compare patch version\n if (parsed1.patch !== parsed2.patch) {\n return parsed1.patch > parsed2.patch ? 1 : -1;\n }\n\n // If both have prerelease, compare lexicographically\n // If only one has prerelease, it's considered lower\n if (parsed1.prerelease && parsed2.prerelease) {\n if (parsed1.prerelease === parsed2.prerelease) {\n return 0;\n }\n return parsed1.prerelease > parsed2.prerelease ? 1 : -1;\n }\n\n if (parsed1.prerelease && !parsed2.prerelease) {\n return -1; // v1 has prerelease, v2 doesn't, so v1 < v2\n }\n\n if (!parsed1.prerelease && parsed2.prerelease) {\n return 1; // v1 doesn't have prerelease, v2 does, so v1 > v2\n }\n\n return 0; // Both are release versions with same major.minor.patch\n}\n\n/**\n * Checks if version v1 is greater than version v2.\n * @param v1 - First version string\n * @param v2 - Second version string\n * @returns true if v1 > v2, false otherwise (including if either version is invalid)\n */\nexport function isVersionGreaterThan(v1: string, v2: string): boolean {\n const result = compareVersions(v1, v2);\n return result === 1;\n}\n","import { getBackendSrv } from '@grafana/runtime';\nimport { lastValueFrom } from 'rxjs';\nimport { useState, useEffect } from 'react';\nimport { ASSISTANT_PLUGIN_ID } from '../plugin';\nimport { isVersionGreaterThan } from './versionCompare';\nimport type { components } from './settings.gen';\n\n/**\n * The type of terms that apply to a tenant.\n * - 'msa': Master Service Agreement - only requires acceptance, no version checking\n * - 'termsAndConditions': Full terms and conditions - requires acceptance AND version checking\n */\nexport type TermsType = components['schemas']['TermsAndConditionsResponse']['termsType'];\n\n/**\n * Internal result type for fetching terms data.\n */\ninterface TermsCheckResult {\n accepted: boolean;\n termsType: TermsType;\n}\n\n/**\n * Event name that is dispatched when terms and conditions are accepted.\n * Other components can listen to this event to refresh their UI.\n */\nexport const TERMS_AND_CONDITIONS_REFRESH_EVENT = 'grafana-assistant-terms-and-conditions-refresh';\n\n/**\n * Internal function that fetches and evaluates terms data.\n * Returns both the acceptance status and the terms type.\n */\nasync function fetchTermsData(): Promise<TermsCheckResult> {\n const backendSrv = getBackendSrv();\n // No appSubUrl prefix: BackendSrv strips the leading `/` so Grafana's\n // `<base href>` adds the subpath (see grafana-assistant-app/issues/6109).\n const apiUrl = `/api/plugins/${ASSISTANT_PLUGIN_ID}/resources/api/v1/settings/terms`;\n\n const response = await lastValueFrom(\n backendSrv.fetch({\n url: apiUrl,\n method: 'GET',\n showErrorAlert: false,\n })\n );\n\n // The API returns { status: \"success\", data: { ... } }, so we need to access response.data.data\n const responseBody = response.data as { data: components['schemas']['TermsAndConditionsResponse'] };\n const termsData = responseBody.data;\n\n const termsAccepted = termsData.acceptedTermsAndConditions ?? false;\n const acceptedVersion = termsData.acceptedVersion;\n const currentVersion = termsData.version;\n const termsType = termsData.termsType;\n\n // For MSA, we only check if terms are accepted\n if (termsType === 'msa') {\n return { accepted: termsAccepted, termsType };\n }\n\n // Check if terms are not accepted, or if no version was recorded or current version is missing\n if (!termsAccepted || !acceptedVersion || !currentVersion) {\n return { accepted: false, termsType };\n }\n\n // Check if the current version is newer than the accepted version\n const needsAcceptance = isVersionGreaterThan(currentVersion, acceptedVersion);\n return { accepted: termsAccepted && !needsAcceptance, termsType };\n}\n\nfunction nonEmptyString(value: unknown): string | undefined {\n return typeof value === 'string' && value.trim() !== '' ? value : undefined;\n}\n\n/**\n * Formats an error thrown by `backendSrv.fetch` (or a network failure) into a\n * concise human-readable reason. BackendSrv rejects with a FetchError-shaped\n * object (`{ status, statusText, data }`) rather than an `Error`, so the raw\n * `message` is usually absent; prefer the server-provided message, then the\n * HTTP status, then any thrown message.\n */\nexport function describeTermsError(err: unknown): string {\n if (err && typeof err === 'object') {\n // The shape is not guaranteed (servers can return any JSON), so only use string fields.\n // Otherwise a non-string `message` would break the return type or render as \"[object Object]\".\n const e = err as {\n status?: unknown;\n statusText?: unknown;\n data?: { message?: unknown; error?: unknown } | null;\n message?: unknown;\n };\n const status = typeof e.status === 'number' ? e.status : undefined;\n const serverMessage = nonEmptyString(e.data?.message) ?? nonEmptyString(e.data?.error);\n if (serverMessage) {\n return status ? `${serverMessage} (HTTP ${status})` : serverMessage;\n }\n if (status !== undefined) {\n const statusText = nonEmptyString(e.statusText);\n return `Request failed with HTTP ${status}${statusText ? ` ${statusText}` : ''}`;\n }\n const message = nonEmptyString(e.message);\n if (message) {\n return message;\n }\n }\n const message = nonEmptyString(err);\n if (message) {\n return message;\n }\n return 'The terms service could not be reached.';\n}\n\n/**\n * Checks whether terms and conditions are accepted and up-to-date.\n * This function verifies that:\n * 1. Terms have been accepted\n * 2. The accepted version matches or exceeds the current version\n *\n * @returns A promise that resolves to `true` if terms are accepted and up-to-date, `false` otherwise\n * @throws Error if the API call fails\n *\n * @example\n * ```typescript\n * import { checkTerms } from '@grafana/assistant';\n *\n * const accepted = await checkTerms();\n * if (!accepted) {\n * // Show terms acceptance UI\n * console.log('Terms need to be accepted');\n * }\n * ```\n */\nexport async function checkTerms(): Promise<boolean> {\n try {\n const result = await fetchTermsData();\n return result.accepted;\n } catch (error) {\n // If API call fails, throw the error so callers can handle it\n // BackendSrv rejects with a FetchError-shaped object, so `String(error)` would render\n // \"[object Object]\". describeTermsError prefers the server message, then the HTTP status.\n throw new Error(`Failed to check terms requirements: ${describeTermsError(error)}`);\n }\n}\n\n/**\n * React hook to check terms and conditions acceptance status.\n * Automatically fetches terms data on mount and re-fetches when terms change\n * (via TERMS_AND_CONDITIONS_REFRESH_EVENT).\n *\n * @returns An object containing whether terms are accepted, the terms type, loading state, and error state\n *\n * @example\n * ```typescript\n * import { useTerms } from '@grafana/assistant';\n *\n * function MyComponent() {\n * const { accepted, termsType, loading, error } = useTerms();\n *\n * if (loading) return <div>Loading...</div>;\n * if (error) return <div>Error: {error}</div>;\n * return <div>Terms accepted</div>;\n * }\n * ```\n */\nexport function useTerms() {\n const [accepted, setAccepted] = useState<boolean>(false);\n const [termsType, setTermsType] = useState<TermsType | null>(null);\n const [loading, setLoading] = useState(true);\n const [error, setError] = useState<string | null>(null);\n\n useEffect(() => {\n async function fetchTerms() {\n try {\n setLoading(true);\n setError(null);\n const result = await fetchTermsData();\n setAccepted(result.accepted);\n setTermsType(result.termsType);\n } catch (err) {\n setError(describeTermsError(err));\n setAccepted(false);\n setTermsType(null);\n } finally {\n setLoading(false);\n }\n }\n\n void fetchTerms();\n\n // Listen for the refresh event to re-fetch when terms change\n const handleTermsRefresh = () => {\n void fetchTerms();\n };\n document.addEventListener(TERMS_AND_CONDITIONS_REFRESH_EVENT, handleTermsRefresh);\n return () => {\n document.removeEventListener(TERMS_AND_CONDITIONS_REFRESH_EVENT, handleTermsRefresh);\n };\n }, []);\n\n return {\n accepted,\n termsType,\n loading,\n error,\n };\n}\n","import type { ToolInvokeOptions, ToolOutput, JSONSchema, JsonObject, InlineToolRunnable } from './types';\n\n/**\n * Creates a tool with the given implementation, schema, and metadata.\n * This is a zod-free implementation that accepts JSON Schema directly and a validation function.\n *\n * @param func The function implementation for the tool\n * @param options Tool configuration options\n * @returns A tool object that can be used in the agent\n */\nexport function createTool<T>(\n func: (input: T, options: ToolInvokeOptions) => Promise<ToolOutput>,\n options: {\n name: string;\n description: string;\n inputSchema: JSONSchema; // JSON Schema directly - no zod dependency!\n validate: (input: JsonObject) => T; // Validation function - replaces zod.parse()\n metadata?: {\n explainer?: (input?: T) => string;\n [key: string]: any;\n };\n verboseParsingErrors?: boolean;\n responseFormat?: 'content_and_artifact' | string;\n }\n): InlineToolRunnable {\n const { explainer, ...metadata } = options.metadata ?? {};\n const toolObj: InlineToolRunnable = {\n name: options.name,\n description: options.description,\n inputSchema: options.inputSchema,\n metadata: explainer\n ? {\n ...metadata,\n explainer: (input: JsonObject) => explainer(input as T),\n }\n : metadata,\n responseFormat: options.responseFormat,\n verboseParsingErrors: options.verboseParsingErrors,\n async invoke(input: JsonObject, invokeOptions: ToolInvokeOptions): Promise<ToolOutput> {\n try {\n if (invokeOptions.signal?.aborted) {\n throw new Error(`Tool ${options.name} execution was aborted`);\n }\n\n // Use the provided validation function instead of zod.parse()\n const parsedInput = options.validate(input);\n const functionPromise = func(parsedInput, invokeOptions);\n const promises = [functionPromise];\n\n if (invokeOptions.signal) {\n promises.push(\n new Promise((_, reject) => {\n invokeOptions.signal?.addEventListener(\n 'abort',\n () => {\n reject(new Error(`Tool ${options.name} execution was aborted`));\n },\n { once: true }\n );\n })\n );\n }\n\n // If we have a timeout, add a promise to handle it\n if (invokeOptions.timeout && invokeOptions.timeout > 0) {\n promises.push(\n new Promise((_, reject) => {\n setTimeout(() => {\n reject(new Error(`Tool ${options.name} execution timed out after ${invokeOptions.timeout}ms`));\n }, invokeOptions.timeout);\n })\n );\n }\n\n // Race the function promise against the abort and timeout promises\n return Promise.race(promises);\n } catch (error) {\n // Handle parsing errors and wrap them in ToolError\n if (options.verboseParsingErrors) {\n console.error(`Error invoking tool ${options.name}:`, error, input);\n }\n throw error;\n }\n },\n };\n\n return toolObj;\n}\n","import { getBackendSrv } from '@grafana/runtime';\nimport { lastValueFrom } from 'rxjs';\nimport { useState, useEffect, useCallback } from 'react';\nimport { ASSISTANT_PLUGIN_ID } from '../plugin';\n\n/**\n * Event name dispatched when limits are updated via SSE.\n * Other components can listen to this event to get real-time updates.\n */\nexport const LIMITS_UPDATED_EVENT = 'grafana-assistant-limits-updated';\n\n/**\n * Detail payload for the LIMITS_UPDATED_EVENT custom event.\n */\nexport interface LimitsUpdatedEventDetail {\n count: number;\n limit: number;\n}\n\n/**\n * Result type for limits data.\n */\nexport interface LimitsData {\n /** Current prompt count for the month */\n count: number;\n /** Monthly prompt limit (0 = unlimited) */\n limit: number;\n /** Current month in YYYY-MM format */\n month: string;\n /** Whether the limit has been reached */\n isLimitReached: boolean;\n}\n\n/**\n * Internal function that fetches limits data from the API.\n */\nasync function fetchLimitsData(): Promise<LimitsData> {\n const backendSrv = getBackendSrv();\n // No appSubUrl prefix: BackendSrv strips the leading `/` so Grafana's\n // `<base href>` adds the subpath (see grafana-assistant-app/issues/6109).\n const apiUrl = `/api/plugins/${ASSISTANT_PLUGIN_ID}/resources/api/v1/usage/limits/prompt`;\n\n const response = await lastValueFrom(\n backendSrv.fetch({\n url: apiUrl,\n method: 'GET',\n showErrorAlert: false,\n })\n );\n\n // The API returns { status: \"success\", data: { total, limit, month } }\n const responseBody = response.data as { data: { total: number; limit: number; month: string } };\n const limitsData = responseBody.data;\n\n const count = limitsData.total ?? 0;\n const limit = limitsData.limit ?? 0;\n const month = limitsData.month ?? '';\n\n return {\n count,\n limit,\n month,\n isLimitReached: limit > 0 && count >= limit,\n };\n}\n\n/**\n * Checks whether the user has reached their monthly prompt limit.\n *\n * @returns A promise that resolves to `true` if limits are reached, `false` otherwise\n * @throws Error if the API call fails\n *\n * @example\n * ```typescript\n * import { checkLimits } from '@grafana/assistant';\n *\n * const data = await checkLimits();\n * if (data.isLimitReached) {\n * console.log('Monthly limit reached');\n * }\n * ```\n */\nexport async function checkLimits(): Promise<LimitsData> {\n try {\n return await fetchLimitsData();\n } catch (error) {\n throw new Error(`Failed to check limits: ${error instanceof Error ? error.message : String(error)}`);\n }\n}\n\n/**\n * React hook to check user prompt limits.\n * Automatically fetches limits data on mount and listens to real-time updates\n * via the LIMITS_UPDATED_EVENT custom event.\n *\n * @returns An object containing limit data, loading state, error state, and refetch function\n *\n * @example\n * ```typescript\n * import { useLimits } from '@grafana/assistant';\n *\n * function MyComponent() {\n * const { count, limit, isLimitReached, loading, error, refetch } = useLimits();\n *\n * if (loading) return <div>Loading...</div>;\n * if (error) return <div>Error: {error}</div>;\n * if (isLimitReached) return <div>Monthly limit reached ({count}/{limit})</div>;\n * return <div>Prompts used: {count}/{limit || 'unlimited'}</div>;\n * }\n * ```\n */\nexport function useLimits() {\n const [count, setCount] = useState<number>(0);\n const [limit, setLimit] = useState<number>(0);\n const [month, setMonth] = useState<string>('');\n const [loading, setLoading] = useState(true);\n const [error, setError] = useState<string | null>(null);\n\n const fetchLimits = useCallback(async () => {\n try {\n setLoading(true);\n setError(null);\n const result = await fetchLimitsData();\n setCount(result.count);\n setLimit(result.limit);\n setMonth(result.month);\n } catch (err) {\n const errorMessage = err instanceof Error ? err.message : 'Failed to fetch limits';\n setError(errorMessage);\n setCount(0);\n setLimit(0);\n setMonth('');\n } finally {\n setLoading(false);\n }\n }, []);\n\n // Fetch on mount\n useEffect(() => {\n void fetchLimits();\n }, [fetchLimits]);\n\n // Listen for real-time updates via custom event\n useEffect(() => {\n const handleLimitsUpdate = (event: Event) => {\n const customEvent = event as CustomEvent<LimitsUpdatedEventDetail>;\n if (customEvent.detail) {\n setCount(customEvent.detail.count);\n setLimit(customEvent.detail.limit);\n // Clear any previous error since we received valid data via SSE\n setError(null);\n }\n };\n\n window.addEventListener(LIMITS_UPDATED_EVENT, handleLimitsUpdate);\n\n return () => {\n window.removeEventListener(LIMITS_UPDATED_EVENT, handleLimitsUpdate);\n };\n }, []);\n\n // Calculate isLimitReached based on current state\n const isLimitReached = limit > 0 && count >= limit;\n\n return {\n count,\n limit,\n month,\n isLimitReached,\n loading,\n error,\n refetch: fetchLimits,\n };\n}\n","import { BusEventWithPayload } from '@grafana/data';\nimport { getAppEvents } from '@grafana/runtime';\n\nexport interface K6SetScriptContentPayload {\n scriptContent: string;\n}\n\n/**\n * Event published by grafana-assistant-app to inject a script into the currently open k6 editor.\n * The k6 app subscribes to this event and updates the editor content in place,\n * avoiding a full page navigation.\n *\n * @example\n * ```typescript\n * import { onK6SetScriptContent } from '@grafana/assistant';\n *\n * const unsubscribe = onK6SetScriptContent(({ scriptContent }) => {\n * editorRef.current?.setValue(scriptContent);\n * });\n *\n * // On unmount\n * unsubscribe();\n * ```\n */\nexport class K6SetScriptContentEvent extends BusEventWithPayload<K6SetScriptContentPayload> {\n static type = 'grafana-assistant:k6-set-script-content';\n}\n\n/**\n * Subscribe to k6 set-script-content events emitted by grafana-assistant-app.\n * Returns an unsubscribe function.\n */\nexport function onK6SetScriptContent(callback: (payload: K6SetScriptContentPayload) => void): () => void {\n const subscription = getAppEvents().subscribe(K6SetScriptContentEvent, (event) => {\n callback(event.payload);\n });\n return () => subscription.unsubscribe();\n}\n","import { BusEventWithPayload } from '@grafana/data';\nimport { getAppEvents } from '@grafana/runtime';\n\n/** Operations Grafana Assistant can ask Pathfinder to perform. */\nexport const PATHFINDER_OPERATIONS = {\n /** Reload the open guide with the given resource name. */\n refreshGuide: 'refresh-guide',\n} as const;\n\nexport type PathfinderOperation = (typeof PATHFINDER_OPERATIONS)[keyof typeof PATHFINDER_OPERATIONS];\n\nexport interface PathfinderEventPayload {\n operation: PathfinderOperation;\n /** App Platform guide resource name, the value used in `doc=api:<name>` links. */\n name: string;\n}\n\n/**\n * Event published by grafana-assistant-app to ask Pathfinder to act on a guide, for example to\n * reload one that is already open after the Assistant saved, published or unpublished it.\n * The event is one-way and only reaches the browser page where the Assistant ran.\n * Receivers should ignore operations they do not know.\n *\n * @example\n * ```typescript\n * import { onPathfinderEvent, PATHFINDER_OPERATIONS } from '@grafana/assistant';\n *\n * const unsubscribe = onPathfinderEvent(({ operation, name }) => {\n * if (operation === PATHFINDER_OPERATIONS.refreshGuide) {\n * reloadGuide(name);\n * }\n * });\n *\n * // On unmount\n * unsubscribe();\n * ```\n */\nexport class PathfinderEvent extends BusEventWithPayload<PathfinderEventPayload> {\n static type = 'grafana-assistant:pathfinder';\n}\n\n/**\n * Subscribe to Pathfinder events emitted by grafana-assistant-app.\n * Returns an unsubscribe function.\n */\nexport function onPathfinderEvent(callback: (payload: PathfinderEventPayload) => void): () => void {\n const subscription = getAppEvents().subscribe(PathfinderEvent, (event) => {\n callback(event.payload);\n });\n return () => subscription.unsubscribe();\n}\n","import type { SuggestionContext } from './suggestionContexts';\nimport type { PluginExtensionAddedFunctionConfig } from '@grafana/data';\nimport type { ComponentType, ReactNode } from 'react';\n\n/**\n * Extension point id consumed by the Grafana Assistant.\n *\n * A contributing app plugin registers a manifest function against this target via\n * `AppPlugin.addFunction()` (declared under `extensions.addedFunctions` in its `plugin.json`).\n * The Assistant discovers registrations with `usePluginFunctions()` and invokes each function to\n * obtain the plugin's {@link AssistantExtensionManifest}.\n *\n * @experimental This API is under active development and may change in future releases.\n */\nexport const ASSISTANT_EXTENSION_POINT = 'grafana-assistant-app/extension/v1';\n\n/**\n * Props passed to a `tool-details` chit component registered via {@link ChitContribution}.\n *\n * These are the normalized props every tool row in the Assistant chat track receives; a\n * registered component renders inside the expanded details area of the standard tool card,\n * in place of the generic expanded content.\n *\n * @experimental This API is under active development and may change in future releases.\n */\nexport interface ToolChitProps {\n /** The fully namespaced tool name that produced this card. */\n toolName: string;\n /** The tool call input, as sent to the tool. */\n input: unknown;\n /** The tool result, once available. `undefined` while the tool is still running. */\n result: unknown;\n /** Execution state of the tool call. */\n status: 'running' | 'success' | 'error';\n}\n\n/** Read-only inputs from tool calls in the message containing an inline component. */\nexport interface InlineChitToolCall {\n readonly toolCallId?: string;\n readonly name: string;\n /** Model-authored input; validate its shape before using it. */\n readonly input: unknown;\n}\n\nexport interface InlineChitTurn {\n /** False also covers stopped turns and history; it does not imply success. */\n readonly isStreaming: boolean;\n readonly tools: readonly InlineChitToolCall[];\n}\n\nexport interface InlineChitProps {\n children?: ReactNode;\n /** Host-supplied context, never taken from model-authored attributes. Absent on older hosts. */\n turn?: InlineChitTurn;\n /** Sanitized `name` attribute, useful for a plugin-defined filter or identifier. */\n name?: string;\n}\n\nexport const InlineChitDisplay = { Inline: 'inline', Block: 'block' } as const;\nexport type InlineChitDisplay = (typeof InlineChitDisplay)[keyof typeof InlineChitDisplay];\n\n/**\n * A contribution to the Assistant chat track (\"chits\"): either an expanded-details renderer\n * keyed by tool name, or a component rendered in place of a tag inside assistant text.\n *\n * - `tool-details`: renders inside the expanded details area of the standard tool card for the\n * listed tool names, replacing the generic expanded content (Query/Result). The compact tool\n * row, its status, and the Allow/Deny confirmation flow are always built in — a plugin never\n * replaces the tool row and never renders while a confirmation is pending. A plugin may only\n * register details for tools it owns (tool names are namespaced by the tool pipeline and\n * checked against the contributing plugin id).\n * - `inline`: registers a component rendered in place of a custom tag inside assistant message\n * text. The full tag name is the plugin id with non-alphanumerics collapsed to underscores,\n * followed by an underscore and `name` — for example plugin `grafana-k6-app` with\n * `name: 'result'` renders `<grafana_k6_app_result>…</grafana_k6_app_result>`. Tag children\n * and allow-listed attributes are passed through as props, alongside host-owned turn context.\n * Optional `prompt` guidance teaches the model when to emit the tag through chat context.\n *\n * Component and function references are the only non-JSON-serializable parts of a manifest —\n * refer to {@link AssistantExtensionManifest} for the serializability contract.\n *\n * @experimental This API is under active development and may change in future releases.\n */\nexport type ChitContribution =\n | {\n kind: 'tool-details';\n /** Fully namespaced tool names this details renderer applies to. Must be owned by the contributing plugin. */\n toolNames: string[];\n /** The details component, rendered inside a per-chit error boundary. */\n component: ComponentType<ToolChitProps>;\n }\n | {\n kind: 'inline';\n /** Plugin-local tag suffix: lowercase, `[a-z][a-z0-9]*`. Namespaced by the plugin id into the full tag name. */\n name: string;\n /** Optional component usage guidance (up to 4096 UTF-8 bytes), sent as attributed chat context, not a system prompt or mode. */\n prompt?: string;\n /** A childless marker. Recover saved bare/backticked opening tags and suppress identical duplicates outside code. */\n selfClosing?: boolean;\n /** Defaults to inline. Block requires selfClosing: true and renders below the message text, outside Markdown paragraphs. */\n display?: InlineChitDisplay;\n /** Rendered in place of the tag, inside a per-chit error boundary. Receives tag children and allow-listed attributes as props. */\n component: ComponentType<InlineChitProps>;\n };\n\n/**\n * The artifact file node handed to plugin artifact renderers and toolbars.\n *\n * Intentionally minimal and forward-compatible: renderers must treat this as the complete\n * artifact surface and must not fetch artifact content from anywhere else.\n *\n * @experimental This API is under active development and may change in future releases.\n */\nexport interface AssistantArtifactNode {\n /** Opaque host identity. Stable across chat draft edits/renames, scoped to the chat.\n * Mounted resources use namespace/path identity. Absent on hosts without identity context.\n * Never use this as authorization or parse its internal format.\n */\n id?: string;\n /** Current, authorized live-resource metadata. Absent for chat-owned drafts. */\n resource?: { namespace: string; revision?: string; url?: string };\n /** File path of the artifact in the conversation's artifact filesystem. */\n path: string;\n /** The artifact kind extension, e.g. `.grafana-k6-app.test`. */\n ext: string;\n /** The artifact content. Shape is owned by the contributing plugin's `validate` contract. */\n data: unknown;\n /**\n * Monotonically increasing per-artifact write counter. Increments on every write to this\n * artifact. Suitable for memoization keys, cache-busting, and change detection. NOT a\n * timestamp — carries no wall-clock meaning.\n */\n revision: number;\n /** Opaque backend revision for mounted files; use for cache keys when present. */\n resourceRevision?: string;\n}\n\n/**\n * Read-only access to every artifact in the conversation, including built-in and other\n * plugins' files. Use this handle and the supplied node for artifact content. Writes and\n * edits go through the Assistant's validated `artifact_files` tool.\n *\n * @experimental This API is under active development and may change in future releases.\n */\nexport interface AssistantArtifactFs {\n /** All artifacts in the conversation, in stable path order. */\n list(): AssistantArtifactNode[];\n /** Read one artifact by exact normalized path. */\n read(path: string): AssistantArtifactNode | undefined;\n /** Whether an artifact exists at the path. */\n has(path: string): boolean;\n}\n\n/**\n * Props passed to a plugin artifact renderer.\n *\n * @experimental This API is under active development and may change in future releases.\n */\n/** Prefills the owning conversation. The user reviews and sends the turn. */\nexport type ArtifactRequestEdit = (input: { message: string }) => void;\n\nexport interface ArtifactRendererProps {\n /** The artifact node to render. */\n node: AssistantArtifactNode;\n /** Read-only handle over the conversation's artifact filesystem. */\n fs: AssistantArtifactFs;\n /** Available in a conversation. Appends text and this artifact's path to the composer,\n * preserves existing input, and focuses it. Never sends or writes automatically.\n * Call only from an explicit user action. Hide edit actions when absent.\n */\n requestEdit?: ArtifactRequestEdit;\n /** Normalized validation for this revision. Recheck readiness before saving or running. */\n validation?: { valid: boolean; ready?: boolean; issues: ArtifactValidationIssue[] };\n}\n\n/**\n * Props passed to an optional plugin artifact toolbar.\n *\n * @experimental This API is under active development and may change in future releases.\n */\nexport interface ArtifactToolbarProps {\n /** The artifact node the toolbar acts on. */\n node: AssistantArtifactNode;\n /** Read-only handle over the conversation's artifact filesystem. */\n fs: AssistantArtifactFs;\n /** Available in a conversation. Appends text and this artifact's path to the composer,\n * preserves existing input, and focuses it. Never sends or writes automatically.\n * Call only from an explicit user action. Hide edit actions when absent.\n */\n requestEdit?: ArtifactRequestEdit;\n /** Normalized validation for this revision. Recheck readiness before saving or running. */\n validation?: { valid: boolean; ready?: boolean; issues: ArtifactValidationIssue[] };\n}\n\n/**\n * A plugin-contributed artifact kind for the Assistant canvas.\n *\n * The `ext` is double-dot namespaced as `.{pluginId}.{kind}`, where `pluginId` is your full,\n * exact plugin id — for example `.grafana-k6-app.test`, not a shortened slug. This keeps plugin\n * kinds out of the built-in single-dot space and keeps orphaned artifacts attributable to their\n * owning plugin without a live registry, since the plugin id is readable from the artifact path.\n *\n * Everything except `validate`, `renderer`, and `toolbar` is JSON-serializable — refer to\n * {@link AssistantExtensionManifest} for the serializability contract.\n *\n * @experimental This API is under active development and may change in future releases.\n */\nexport interface ArtifactValidationIssue {\n /** Field path owned by the plugin, for example steps[2].inputs.channel. */\n path: string;\n /** Actionable feedback. Never include credentials or other sensitive values. */\n message: string;\n}\n\n/** valid controls draft writes/rendering. ready is advisory and never authorizes a save or run. */\nexport type ArtifactValidationResult =\n | boolean\n | {\n valid: boolean;\n ready?: boolean;\n issues: ArtifactValidationIssue[];\n };\n\nexport interface ArtifactKindContribution {\n /** Artifact extension in the form `.{pluginId}.{kind}` (exact plugin id), double-dot namespaced. */\n ext: `.${string}.${string}`;\n /** Human-readable label shown on artifact tabs and cards. */\n label: string;\n /** Icon name. The current host displays a generic plugin icon instead. */\n icon: string;\n /**\n * Sort order among plugin kinds, ascending. The host clamps negative values to zero\n * and places plugin kinds after built-ins. Ties use the most recently updated artifact.\n */\n tabPriority: number;\n /** Content validator. Accept with true or { valid: true, issues: [...] }. */\n validate(data: unknown): ArtifactValidationResult;\n /** Relative paths in this plugin's filesystem, discovered before authoring. */\n instructionsPath?: string;\n schemaPath?: string;\n /** Renders the artifact in the canvas. Receives the artifact node and a read-only conversation filesystem handle. */\n renderer: ComponentType<ArtifactRendererProps>;\n /** Optional toolbar rendered above the artifact. */\n toolbar?: ComponentType<ArtifactToolbarProps>;\n /** Reserved hint. Accepted by the host but not currently sent to the model. */\n promptHint?: string;\n}\n\n/** JSON or text stored by a plugin filesystem. Binary files are not supported. */\nexport type AssistantFileContent =\n | null\n | boolean\n | number\n | string\n | AssistantFileContent[]\n | { [key: string]: AssistantFileContent };\n\n/** Paths are relative to the plugin mount, without a leading slash or traversal segments. */\nexport interface AssistantFilesystemFile {\n path: string;\n content: AssistantFileContent;\n /** Opaque backend revision, used for conditional writes. */\n revision: string;\n title?: string;\n /** Optional Grafana-local native page under /a/<registered-plugin-id>/. */\n url?: string;\n}\n\nexport interface AssistantFilesystemListInput {\n /** Relative directory; empty string lists the mount root. */\n path: string;\n filter?: { type?: string; title?: string };\n limit: number;\n offset: number;\n}\n\nexport interface AssistantFilesystemListResult {\n /** Authorized files only, filtered then sorted by relative path before pagination. */\n items: Array<{ path: string; title?: string }>;\n hasMore: boolean;\n}\n\n/**\n * A live filesystem mounted at /plugins/<registered-plugin-id>/ by the host.\n * All callbacks run in the browser under the current caller. The owning backend must\n * enforce authorization for every operation; chat access grants no resource permission.\n * Paths and namespace are routing context, never authorization assertions.\n * Missing/denied reads reject. No callback may return content from a different namespace.\n * Keep callbacks stable and independent of `this`, like other manifest callbacks.\n *\n * Ordinary text/JSON files are tool-accessible. Files with the plugin's registered artifact\n * extensions can also attach to the canvas. No content is reconstructed from chat inputs.\n * @experimental\n */\nexport interface AssistantFilesystemContribution {\n /** Optional Markdown instructions exposed read-only at the mount's AGENT.md (max 32 KiB). */\n agentGuide?: string;\n read(namespace: string, path: string): Promise<AssistantFilesystemFile>;\n list(namespace: string, input: AssistantFilesystemListInput): Promise<AssistantFilesystemListResult>;\n /** Metadata only; undefined means missing or inaccessible. Other failures reject. */\n metadata(namespace: string, path: string): Promise<{ title?: string } | undefined>;\n /** Atomic create: assign and return a relative path; rejection means nothing was created. */\n create?(namespace: string, content: AssistantFileContent): Promise<AssistantFilesystemFile>;\n /** Update an existing file only, enforcing the supplied revision atomically in storage. */\n write?(\n namespace: string,\n path: string,\n content: AssistantFileContent,\n revision: string\n ): Promise<AssistantFilesystemFile>;\n}\n\n/**\n * Reserved availability conditions for plugin modes.\n * The current plugin-mode adapter does not apply these conditions.\n *\n * @experimental This API is under active development and may change in future releases.\n */\nexport type PromptContributionAvailability = 'not-oss' | 'not-trial';\n\n/**\n * A plugin-contributed Assistant mode (system prompt variant).\n *\n * The contribution is exposed in the mode picker as `${pluginId}:${modeId}` and its prompt text\n * is always rendered inside an attributed `<plugin_contribution>` wrapper, subject to a\n * 16 KiB UTF-8 body limit and an assistant-side allowlist.\n *\n * The current host applies modeId, label, description, compose, and prompt only. Other\n * fields are accepted but not applied; don't use them to enforce tool or access restrictions.\n *\n * All fields are JSON-serializable — refer to {@link AssistantExtensionManifest} for the\n * serializability contract.\n *\n * @experimental This API is under active development and may change in future releases.\n */\nexport interface PromptContribution {\n /** Plugin-local mode id. Exposed to users as `${pluginId}:${modeId}`. */\n modeId: string;\n /** Human-readable mode label shown in the mode picker. */\n label: string;\n /** Short description of the mode shown in the mode picker. */\n description: string;\n /** Intended suggestion guidance. Required by the schema, but not currently applied by the host. */\n whenToUse: string;\n /**\n * How `prompt` composes with the base system prompt.\n *\n * - `prepend` / `append`: `prompt` is added before / after the base guidance, which is\n * otherwise kept intact.\n * - `replace`: the rest of the base guidance is dropped, but the Assistant's identity section\n * is ALWAYS retained — the composed prompt is the identity block, then the current-mode\n * block, then the attributed plugin body. A plugin never controls or replaces the\n * Assistant's identity.\n *\n * Prefer `prepend` or `append` unless the mode is a genuinely self-contained specialist that\n * needs none of the base guidance.\n */\n compose: 'prepend' | 'append' | 'replace';\n /**\n * The prompt snippet (`prepend`/`append`) or specialist body (`replace`). With `replace`, this\n * body is composed after the Assistant's always-retained identity section — refer to\n * {@link PromptContribution.compose}.\n */\n prompt: string;\n /** Reserved first-message text. The current host does not send it. */\n initialMessage?: string;\n /** Reserved switching preference. The current host does not apply it. */\n switchable?: boolean;\n /** Reserved availability conditions. The current host does not evaluate them for plugin modes. */\n availability?: PromptContributionAvailability[];\n /** Reserved tool scoping. The current host does not restrict tools using this field. */\n modeToolNames?: string[];\n /** Reserved icon name. The current host displays a generic plugin icon. */\n icon?: string;\n /** Reserved badge. The current host does not apply it. */\n featureState?: 'preview' | 'experimental';\n}\n\n/**\n * A proposed first message on empty Assistant chats, attributed to your plugin.\n * Selecting it sends `message` as a visible user message. Requires the extensions master\n * flag and an enabled plugin; no prompt flag or allowlist is needed.\n *\n * The host keeps the first 3 valid entries. Over-length entries are dropped, not truncated.\n * Use `contexts` to participate in route-relevant selection, or `provideQuestions`\n * for suggestions tied to a page where your plugin runs.\n *\n * @experimental This API is under active development and may change in future releases.\n */\nexport interface AssistantStarter {\n /** Optional short label shown on the starter; defaults to the message itself. Max 80 characters. */\n label?: string;\n /** The user message sent, visibly and as-is, when the starter is selected. Max 500 characters. */\n message: string;\n /** Eligible on any listed route context. Omitted: only this plugin's /a/<pluginId> routes.\n * An empty list disables the starter. Eligible starters compete with built-in suggestions.\n */\n contexts?: readonly SuggestionContext[];\n}\n\n/**\n * A plugin workflow with a read-only listing on the Assistant's Skills settings page.\n * The catalog and loader that deliver content to the model are not implemented yet.\n * Proposed activation requires trusted server integration and a supported runtime surface.\n * Automatic discovery would also require a short author hint (`whenToUse`), not yet in this\n * interface. Existing manifests remain valid and would be manual-only without a hint once\n * manual activation ships; enabling the builtin runtime does not activate plugin registrations.\n *\n * The host assigns the handle `plugin:{pluginId}:{id}` using the registered plugin ID.\n * Plugin skills are not saved as tenant skills or indexed for search. Removing a\n * registration removes its skills. The prompt flag and allowlist don't gate registration.\n *\n * The host keeps the first 5 valid, unique IDs and drops entries that exceed field limits.\n *\n * @experimental This API is under active development and may change in future releases.\n */\nexport interface SkillContribution {\n /** Plugin-local skill id: `[a-z][a-z0-9-]*`, max 64 characters. Namespaced by the plugin id into the catalog handle. */\n id: string;\n /** Nonblank title shown in settings. Max 80 characters. */\n title: string;\n /** One or two sentences describing what the skill does and when to use it. Max 500 characters. */\n description: string;\n /** Nonblank Markdown body. Model loading is not implemented yet. Max 32768 UTF-8 bytes. */\n content: string;\n}\n\n/**\n * Contributions from one Grafana app plugin to the Assistant sidebar and workspace.\n * Register with {@link getAssistantExtensionConfig} and declare the matching target in\n * `plugin.json`. Keep the manifest stable after registration.\n *\n * Fields must be JSON-serializable except components and callbacks (`component`,\n * `validate`, `renderer`, `toolbar`, and filesystem callbacks). Unknown fields are ignored. Unknown contribution\n * kinds and malformed entries are dropped; an unknown schemaVersion rejects the manifest.\n *\n * @experimental This API is under active development and may change in future releases.\n */\nexport interface AssistantExtensionManifest {\n /** Manifest schema version. Always 1 for this SDK version. */\n schemaVersion: 1;\n /** Chat-track contributions: tool-details renderers and inline components. */\n chits?: ChitContribution[];\n /** Proposed first messages on empty chats, attributed to the plugin. Max 3 valid entries. */\n starters?: AssistantStarter[];\n /** Plugin workflows listed in settings. Model loading is not implemented yet. Max 5 valid entries. */\n skills?: SkillContribution[];\n /** Canvas artifact kinds. */\n artifactKinds?: ArtifactKindContribution[];\n /** Optional persistent filesystem, mounted under the registering plugin ID. */\n filesystem?: AssistantFilesystemContribution;\n /** Assistant mode / system prompt contributions. */\n promptContributions?: PromptContribution[];\n}\n\n/**\n * Builds the function registration for {@link ASSISTANT_EXTENSION_POINT}.\n * Also declare the target in `plugin.json` under `extensions.addedFunctions`. Use\n * `preload: true` for Grafana 12.1 compatibility with function-only contributions.\n *\n * The returned function reuses `manifest`. Don't mutate it after registration; define\n * components and callbacks outside React renders so their references stay stable.\n *\n * @example\n * ```typescript\n * import { AppPlugin } from '@grafana/data';\n * import { getAssistantExtensionConfig } from '@grafana/assistant';\n *\n * export const plugin = new AppPlugin().addFunction(\n * getAssistantExtensionConfig({\n * schemaVersion: 1,\n * starters: [{ message: 'Help me review recent service errors in this stack.' }],\n * })\n * );\n * ```\n *\n * @experimental This API is under active development and may change in future releases.\n */\nexport function getAssistantExtensionConfig(\n manifest: AssistantExtensionManifest\n): PluginExtensionAddedFunctionConfig<() => AssistantExtensionManifest> {\n return {\n title: 'assistant-extension',\n description:\n 'Contributes chits, starters, skills, artifact kinds, and prompt contributions to the Grafana Assistant.',\n targets: [ASSISTANT_EXTENSION_POINT],\n fn: () => manifest,\n };\n}\n","export const SuggestionContext = {\n Home: '/',\n CloudHome: '/a/cloud-home-app',\n Workspace: '/a/grafana-assistant-app/workspace',\n Dashboard: '/d',\n Dashboards: '/dashboards',\n Alerting: '/alerting',\n AlertRules: '/alerting/list',\n AlertRule: '/alerting/grafana/:uid/view',\n Notifications: '/alerting/notifications',\n Silences: '/alerting/silences',\n Connections: '/connections',\n DataSources: '/connections/datasources',\n Explore: '/explore',\n Drilldown: '/drilldown',\n Metrics: '/a/grafana-metricsdrilldown-app/drilldown',\n Logs: '/a/grafana-lokiexplore-app/explore',\n Traces: '/a/grafana-exploretraces-app',\n Profiles: '/a/grafana-pyroscope-app/explore',\n SQL: '/a/grafana-sqldrilldown-app/explore',\n Admin: '/admin',\n Users: '/admin/users',\n Organization: '/org',\n Teams: '/org/teams',\n ServiceAccounts: '/org/serviceaccounts',\n Notebooks: '/notebooks',\n Notebook: '/notebooks/:uid',\n NewNotebook: '/notebooks/new',\n Pages: '/a/grafana-assistant-app/pages',\n Page: '/a/grafana-assistant-app/pages/:id',\n PageTemplates: '/a/grafana-assistant-app/pages/templates',\n NewPage: '/a/grafana-assistant-app/pages/new',\n Costs: '/a/grafana-cmab-app',\n} as const;\n\nexport type SuggestionContext = (typeof SuggestionContext)[keyof typeof SuggestionContext];\n"],"names":["__webpack_require__","exports","definition","key","o","Object","defineProperty","enumerable","get","obj","prop","prototype","hasOwnProperty","call","Symbol","toStringTag","value","hash","input","i","length","charCodeAt","toString","NodeData","constructor","params","text","this","id","type","bypassLimits","formatForLLM","codeElementIds","data","name","equals","other","StructuredNodeData","super","JSON","stringify","agentSkillNodeId","reference","selectionId","AgentSkillNodeData","displayName","providerId","handle","revision","require","GLOBAL_REGISTRY_KEY","REGISTRY_CHANGE_EVENT","LEGACY_REGISTRY_UPDATE_EVENT","LEGACY_REGISTRY_REMOVE_EVENT","LEGACY_REGISTRY_SYNC_EVENT","getPageContextRegistry","window","setPageContextRegistry","newRegistry","skipLegacyEvents","dispatchEvent","CustomEvent","detail","registry","legacyBridgeInitialized","providePageContext","urlPattern","initialContext","pattern","RegExp","source","trim","console","warn","registration","generateRegistrationId","context","setContext","newContext","currentRegistry","index","findIndex","reg","unregister","filter","_","addEventListener","event","existingIndex","r","incomingRegistry","Array","isArray","currentIds","Set","map","newRegistrations","has","empty","useProvidePageContext","setContextRef","useRef","undefined","pendingUpdate","isModified","useEffect","current","contextToUse","useCallback","getActivePageContext","currentUrl","activeContext","matchesUrlPattern","push","usePageContext","options","allowQuestions","allowComponents","location","useLocationService","initialPathname","getLocation","pathname","pageContext","setPageContext","useState","currentPathnameRef","updateContext","handleRegistryChange","locationSub","getLocationObservable","subscribe","loc","unsubscribe","removeEventListener","filteredContext","item","node","prefix","Date","now","Math","random","slice","url","test","regexPattern","replace","ComponentNodeData","namespace","keys","components","join","prompt","usePageComponents","useMemo","allComponents","componentData","componentName","component","entries","provideComponents","flags","createAssistantContextItem","setter","newComponents","newPrompt","globalComponents","promptContext","DashboardNodeData","dashboardUid","dashboardTitle","folderUid","folderTitle","FolderNodeData","DatasourceNodeData","datasourceUid","datasourceType","datasourceName","img","uid","EntityNodeData","scope","env","site","Boolean","title","hidden","icon","entityType","properties","LabelNameNodeData","labelName","LabelValueNodeData","labelValue","operator","getDatasourceMeta","datasourceInstance","getDataSourceSrv","getInstanceSettings","meta","info","logos","small","defaultIcons","datasource","label_name","label_value","dashboard","dashboard_folder","unknown","structured","entity","skill","agent_skill","nodeData","error","createContextByType","defaultTitle","getTitleFromContextNode","getImgFromContextNode","navigable","selectable","occurrences","SkillNodeData","skillId","skillName","provideQuestions","initialQuestions","registrationId","convertQuestionsToContext","questions","question","setQuestions","newQuestions","useProvideQuestions","useQuestions","convertContextToQuestions","contextItems","CALLBACK_EXTENSION_POINT","newFunctionNamespace","functions","getExposeAssistantFunctionsConfig","namespaces","targets","fn","ASSISTANT_PLUGIN_ID","ASSISTANT_PLUGIN_TITLE","MAX_RETRY_ATTEMPTS","INITIAL_RETRY_DELAY","MAX_RETRY_DELAY","isAssistantAvailable","getObservablePluginLinks","defer","extensionPointId","pipe","links","some","link","pluginId","throwError","retry","count","delay","retryCount","errorMessage","message","toLowerCase","includes","delayMs","min","timer","catchError","of","defineSdkEvent","actor","reportInteraction","trackSidebarOpened","trackSidebarToggled","trackOpenButtonDisplayed","trackSplitButtonDisplayed","trackPromptCardDisplayed","OpenExtensionSidebarEvent","BusEventWithPayload","CloseExtensionSidebarEvent","BusEventBase","ToggleExtensionSidebarEvent","toSidebarProps","props","namesAgentSkill","agentSkillInvocationName","initialRequestId","crypto","getRandomValues","Uint32Array","initialPrompt","initialAutoSend","autoSend","origin","initialMode","mode","chatId","appendContext","initialAgentSkillInvocationName","openAssistant","from","componentTitle","getAppEvents","publish","openExtensionSidebar","closeAssistant","closeExtensionSidebar","toggleAssistant","toggleExtensionSidebar","useAssistant","available","setAvailable","sub","isAvailable","isLoading","OpenAssistantButton","OpenAssistantButtonView","size","iconOnlyButton","iconOnlyVariant","onClick","styles","useStyles2","getStyles","handleClick","Button","variant","fill","tooltip","IconButton","className","button","theme","baseBackground","colors","secondary","main","elevatedBackground","emphasize","underlyingColor","background","canvas","outerRadius","shape","radius","default","innerRadius","gradientBorderLayer","content","position","inset","borderRadius","cornerShape","zIndex","pointerEvents","solidBackgroundLayer","transition","css","label","width","maxWidth","isolation","border","padding","spacing","defaultDropdownButtonWidths","sm","md","lg","OpenAssistantSplitButton","OpenAssistantSplitButtonView","menuItems","dropdownButtonWidth","hasMenuItems","resolvedDropdownButtonWidth","wrapperContent","wrapper","ButtonGroup","buttonGroup","cx","segmentButton","mainButtonSplit","mainButtonSolo","Dropdown","overlay","dropdownButton","style","minWidth","Tooltip","dividerColor","weak","display","gap","overflow","boxShadow","borderTopLeftRadius","borderBottomLeftRadius","borderTopRightRadius","borderBottomRightRadius","alignItems","justifyContent","margin","getBackgroundGradientColors","defaultGradientColors","isThemeWithoutGradients","matches","gradients","brandHorizontal","match","createBorderAnimation","backgroundColor","color1","color2","animationSteps","animationFrames","gradientColor1","gradientColor2","finalColor1","finalColor2","step","backgroundImage","GLOBAL_FACTORY_KEY","GLOBAL_INITIALIZER_KEY","GLOBAL_INITIALIZATION_PROMISE_KEY","setInlineAssistantFactory","existing","setInlineAssistantInitializer","async","ensureInlineAssistantInitialized","initializer","Error","existingPromise","initPromise","err","getInlineAssistantFactory","factory","nestedErrorKeys","getStringValue","trimmedValue","extractNestedErrorMessage","visited","directString","nestedErrorMessage","cause","fromEntries","add","errorRecord","nestedDataMessage","nestedMessage","status","statusText","nestedMessages","extractErrorMessage","String","useInlineAssistant","config","isGenerating","setIsGenerating","setContent","setError","assistantRef","configRef","reset","cancel","generate","sendPrompt","agentName","agentId","systemPrompt","tools","onStart","onDelta","delta","prev","onComplete","onError","dispose","useAIGeneration","onChange","disabled","autoGenerate","streaming","getUserPrompt","hasAutoGenerated","valueBeforeGeneration","getUserPromptRef","displayValue","isSendDisabled","doGenerate","catch","maybeAutoGenerateRef","handleGenerate","GENERATING_PHRASES","useGeneratingPlaceholder","defaultPlaceholder","phrase","setPhrase","wasGenerating","next","floor","AITextInput","placeholder","dataTestId","activePlaceholder","addonAfter","animatedWrapper","Input","onKeyDown","e","metaKey","ctrlKey","preventDefault","currentTarget","suffix","invalid","primary","borderAnimation","keyframes","backgroundOrigin","backgroundClip","animation","AITextArea","rows","effectiveRows","max","textareaWrapper","TextArea","textarea","sendButton","paddingRight","minHeight","scrollbarWidth","right","top","queryIsEmpty","query","dataQueryProps","QueryWithAssistantButton","currentQuery","queries","dataSourceInstanceSettings","app","datasourceApi","CoreApp","Unknown","hasCurrentQuery","otherQueries","q","refId","queryDisplayText","getQueryDisplayText","isUpdating","actionText","codeBlockLines","actionableSentence","DEFAULT_EXAMPLE_PROMPTS","AssistantPromptCard","AssistantPromptCardView","examplePrompts","animated","onClose","onSubmit","setPrompt","inputRef","staticPlaceholder","animatedPlaceholder","prompts","hasUserInput","setDisplay","indexRef","charRef","phaseRef","timeoutId","schedule","setTimeout","currentPrompt","tick","clearTimeout","useAnimatedPlaceholder","rafId","requestAnimationFrame","focus","cancelAnimationFrame","submit","trimmed","card","cardStatic","role","inputRow","ref","shiftKey","getGlowShadow","isDark","cardBase","flexDirection","transitions","handleMotion","elevated","grotOptions","palette","crest","visor","screen","mouth","hat","held","tail","partOrder","grotPalette","classic","outline","body","light","shade","crestShade","visorLight","glyph","accent","mint","berry","glacier","night","moss","handheld","sunset","cotton","grape","ember","slate","classicLook","renamedOptions","ghost","teeth","blep","stub","legacyColors","yellow","orange","blue","green","pink","red","appearanceOf","agent","renamed","avatar","stored","split","seed","h","abs","reduce","look","part","option","withPart","find","table","renamedTo","optionOf","pick","appearanceWith","SPRITE_SIZE","fixedColors","w","R","u","U","y","p","t","a","z","x","E","f","F","m","M","feet","back","front","arms","rest","up","crests","spikes","fin","mohawk","antenna","flame","sprout","horns","bald","visors","band","goggles","slim","shades","eyesAt","eyeShapes","bars","dots","tall","big","love","plus","dizzy","mouths","smile","bare","grin","flat","fang","stache","wavy","hats","nohat","beanie","cap","crown","party","headset","wizard","cowboy","chef","viking","tophat","halo","flower","hardhat","copter","crestHidingHats","heldItems","coffee","wrench","magnifier","chart","duck","pager","laptop","balloon","pizza","flag","donut","clip","bell","shield","bug","tails","curl","spike","bolt","heart","fluff","notail","pixelsPart","pixels","color","xs","ys","j","screens","made","Map","result","at","forEach","row","ch","shown","onScreen","dy","winkCaret","dx","perEye","flatMap","eyes","wink","make","set","memo","trace","byRow","Number","d","sort","b","run","painted","WeakMap","paint","cached","k","l","s","c","v","n","g","colorsOf","byColor","put","near","svgDataUrls","GrotAvatar","grot","src","paths","parts","svg","encodeURIComponent","spriteSvgDataUrl","lookOf","image","height","alt","flexShrink","imageRendering","OpenGrotButton","grotId","topic","href","URLSearchParams","assistantGrot","appSubUrl","grotHref","LinkButton","altKey","locationService","GROT_TOPIC_COMPONENT_ID","GrotTopicView","Topic","usePluginComponent","LoadingPlaceholder","number","Alert","severity","LENS_ERROR_CODES","InvestigationLensRequestError","code","toInvestigationLensError","GLOBAL_IMPLEMENTATION_KEY","setInvestigationLensImplementation","setInvestigationLensInitializer","ensureInvestigationLensInitialized","getInvestigationLensImplementation","implementation","useInvestigationThroughLens","schema","investigationId","enabled","refreshOnEnable","state","setState","schemaJson","generation","setGeneration","bypassCache","consumedGenerationRef","wasEnabledRef","refresh","wasEnabled","cancelled","bypassFromRefresh","parse","getEnumValues","numericValues","values","indexOf","joinValues","array","separator","val","stringifyPrimitive","jsonStringifyReplacer","Cached","getter","_getter","_value","cleanRegex","start","startsWith","end","endsWith","assignProp","target","writable","configurable","rawShape","def","desc","getOwnPropertyDescriptor","raw","sourceShape","_zod","deferProp","putProp","mirrorShape","wrap","mergeDefs","defs","mergedDescriptors","descriptors","getOwnPropertyDescriptors","assign","defineProperties","esc","str","captureStackTrace","_args","globalConfig","jitless","navigator","userAgent","Function","isPlainObject","ctor","prot","shallowClone","propertyKeyTypes","escapeRegex","clone","inst","cl","constr","parent","normalizeParams","_params","NUMBER_FORMAT_RANGES","safeint","MIN_SAFE_INTEGER","MAX_SAFE_INTEGER","int32","uint32","float32","float64","MAX_VALUE","BIGINT_FORMAT_RANGES","int64","BigInt","uint64","maskedKeys","mask","Reflect","ownKeys","extended","newShape","mirrorProps","partial","Class","checks","selected","innerType","aborted","startIndex","issues","continue","explicitlyAborted","prefixIssues","path","iss","_a","unshift","unwrapMessage","sizeCaps","defChecks","caps","check","maximum","attachSchema","finalizeIssue","ctx","traits","schemaError","customError","localeError","full","reportInput","highSurrogate","codePointLength","units","getLengthableOrigin","args","own","hide","derived","computes","compute","defineBound","proto","bind","installing","broke","breaker","defineLazyInternal","getPrototypeOf","outer","constantCatch","_zodDesc","_E","$constructor","Internals","protoMembers","initialized","WeakSet","init","ctorProto","Parent","Definition","saved","stackTraceLimit","newError","deferred","pp","globalThis","__zod_globalConfig","postProcessor","hasInstance","$ZodAsyncError","$ZodEncodeError","newConfig","$ZodCyclicError","STATE","NO_ISSUES","isRef","cloneIssues","recursive","isRecursive","stack","resolve","child","answer","merge","sh","catchall","element","el","items","keyType","valueType","left","in","out","output","inner","_cachedInner","delete","settle","handoff","alloc","_inst","payload","bucket","entry","guard","base","wrapped","direction","backEdges","isBackEdge","attach","isRecursiveInst","lastCtx","lastBucket","rechecked","walked","buckets","bucketFor","hit","depth","pop","Promise","then","cuid","cuid2","ulid","xid","ksuid","nanoid","duration","guid","uuid","version","email","ipv4","ipv6","cidrv4","cidrv6","httpProtocol","e164","dateSource","date","timeSource","hhmm","precision","seconds","anyString","integer","lowercase","uppercase","$ZodCheck","onattach","_whenHasLength","numericOriginMap","bigint","object","$ZodCheckLessThan","inclusive","getTime","abort","$ZodCheckGreaterThan","minimum","$ZodCheckMultipleOf","ratio","roundedRatio","round","tolerance","EPSILON","divisor","$ZodCheckNumberFormat","format","isInt","isInteger","expected","isSafeInteger","note","$ZodCheckMaxLength","when","$ZodCheckMinLength","$ZodCheckLengthEquals","tooBig","exact","$ZodCheckStringFormat","_b","lastIndex","$ZodCheckRegex","$ZodCheckLowerCase","$ZodCheckUpperCase","$ZodCheckIncludes","escapedRegex","$ZodCheckStartsWith","$ZodCheckEndsWith","$ZodCheckOverwrite","tx","Doc","closed","indent","indented","write","arg","execution","lines","minIndent","trimStart","dedented","repeat","line","compile","major","minor","patch","$ZodType","bag","runChecks","asyncResult","isAborted","currLen","handleCanaryResult","canary","checkResult","skipChecks","standardProps","toStandardResult","validate","validateAsync","vendor","$ZodString","coerce","$ZodStringFormat","$ZodGUID","$ZodUUID","v1","v2","v3","v4","v5","v6","v7","v8","$ZodEmail","canParseURL","URL","canParse","asciiTabOrNewline","stripTabAndNewline","$ZodURL","normalize","protocol","URLStatic","parseURLObject","validateURL","hostname","urlHostnameOk","urlProtocolOk","$ZodEmoji","$ZodNanoID","$ZodCUID","$ZodCUID2","$ZodULID","$ZodXID","$ZodKSUID","$ZodISODateTime","opts","offset","qualified","timeRegex","local","$ZodISODate","$ZodISOTime","$ZodISODuration","$ZodIPv4","ipv6Alphabet","isValidIPv6","$ZodIPv6","$ZodCIDRv4","$ZodCIDRv6","address","prefixNum","isValidCIDRv6","isValidBase64","atob","base64Charset","$ZodBase64","base64urlCharset","$ZodBase64URL","base64","padEnd","ceil","isValidBase64URL","$ZodE164","$ZodJWT","token","algorithm","tokensParts","header","parsedHeader","typ","alg","isValidJWT","$ZodNumber","_ctx","isNaN","isFinite","received","$ZodNumberFormat","$ZodBoolean","$ZodUnknown","$ZodNever","arraySize","handleArrayResult","final","$ZodArray","memoizer","proms","abortEarly","all","capSize","handlePropertyResult","optin","optout","isPresent","isOptionalOut","NO_SYMBOL_KEYS","normalizeDef","ownSymbols","getOwnPropertySymbols","symbolKeys","allKeys","okeys","keySet","numKeys","optionalKeys","handleCatchall","unrecognized","_catchall","seen","$ZodObject","newSh","_normalized","zod","propValues","field","isObject","$ZodObjectJIT","superParse","fastpass","jit","fastEnabled","normalized","syms","doc","parseStr","prefixStr","ids","create","counter","isOptionalIn","generateFastpass","handleUnionResults","results","nonaborted","errors","$ZodUnion","every","patterns","first","$ZodIntersection","handleIntersectionResults","mergeValues","valid","bKeys","sharedKeys","newObj","__proto__","sharedValue","mergeErrorPath","newArray","unrecKeys","unrecIssue","keyIssues","collect","side","bothKeys","aggregated","merged","$ZodRecord","recordKeys","keyResult","outKey","propertyIsEnumerable","retryResult","$ZodEnum","valuesSet","patternValues","$ZodLiteral","vals","$ZodTransform","_out","transform","handleOptionalResult","$ZodOptional","$ZodExactOptional","$ZodNullable","$ZodDefault","defaultValue","handleDefaultResult","$ZodPrefault","$ZodNonOptional","handleNonOptionalResult","handleCatchResult","catchValue","$ZodCatch","$ZodPipe","handlePipeResult","$ZodReadonly","handleReadonlyResult","freeze","$ZodCustom","handleRefineResult","_iss","__zod_globalRegistry","_map","_idmap","_meta","clear","remove","pm","globalRegistry","snapshotChecks","_lt","_lte","_gt","_gte","_multipleOf","_maxLength","_minLength","_length","_overwrite","assignProps","sources","initializeContext","processors","metadataRegistry","metadata","unrepresentable","override","io","sharedDefsExtractedFor","sharedEmitDoneFor","cycles","reused","intersections","external","handleUnrepresentable","json","zodSchema","processSchema","schemaPath","cycle","overrideSchema","toJSONSchema","processJSONSchema","_json","processor","isParent","isTransforming","examples","_prefault","encodeJSONPointerSegment","segment","extractDefs","root","idToSchema","extractToDef","$ref","defId","defsSegment","externalId","uriGenerator","uri","defUriPrefix","makeURI","ext","compactTypeUnion","anyOf","types","member","FOLDABLE_KEYS","UNION_KEYS","undeclaredConstraint","extra","additionalProperties","foldObjects","members","objects","required","allOf","folded","constraints","constraint","foldIntersection","unions","union","keyword","branches","branch","finalize","flattenRef","_cached","refSeen","refSchema","parentSeen","jsonSchema","reverse","rewrite","carriers","$schema","$id","rootMetaId","$defs","definitions","finalized","createStandardJSONSchemaMethod","_err","_schema","libraryOptions","narrowMin","agg","narrowMax","narrowBoth","addDivisor","multipleOf","addPattern","intersectMime","mime","setFormat","minContributor","maxContributor","formatContributor","ranges","contributors","greater_than","less_than","multiple_of","number_format","bigint_format","min_length","max_length","length_equals","min_size","max_size","size_equals","string_format","contentEncoding","laxFormat","mime_type","aggregateChecks","list","exclusiveMinimum","exclusiveMaximum","formatMap","datetime","json_string","regex","exactPatterns","exactPattern","inputOptin","stringifyKeyNames","bySchema","inlined","mapped","numericType","enum","const","pendingRecords","UNREPRESENTABLE_DEFAULT","serializeDefaultValue","serialized","optionalProcessor","Sizable","string","unit","verb","file","getSizing","FormatDictionary","emoji","uuidv4","uuidv6","time","mac","base64url","currency_code","credit_card","iban","jwt","template_literal","TypeDictionary","nan","getTypeName","issue","adj","sizing","_issue","_messageDesc","internals","_issuesDesc","_installedToString","$ZodError","finalizeParams","callee","Err","_parse","_Err","_parseAsync","_safeParse","failure","success","_safeParseAsync","COMPILE_INVALID","for","COMPILE_FALLBACK","_encode","_decode","_encodeAsync","parseAsync","_decodeAsync","_safeEncode","_safeDecode","_safeEncodeAsync","_safeDecodeAsync","_installedErrorProtos","_lazyMethod","self","mapper","fieldErrors","_errors","processError","fullpath","curr","terminal","formErrors","ZodRealError","_ensureDefaultMemoizer","ZodType","chks","brand","register","refine","ZodCustom","superRefine","refinement","_check","addIssue","fatal","overwrite","optional","exactOptional","ZodExactOptional","nullable","nullish","nonoptional","ZodNonOptional","or","ZodUnion","and","ZodIntersection","ZodTransform","ZodDefault","prefault","ZodPrefault","ZodCatch","readonly","ZodReadonly","describe","description","isOptional","safeParse","isNullable","apply","safeParseAsync","spa","validator","definite","fallbackRun","validateFallback","encode","decode","encodeAsync","decodeAsync","safeEncode","safeDecode","safeEncodeAsync","safeDecodeAsync","createToJSONSchemaMethod","_def","_ZodString","minLength","maxLength","patternList","nonempty","form","toUpperCase","slugify","ZodString","ZodEmail","ZodURL","ZodJWT","ZodEmoji","ZodGUID","ZodUUID","uuidv7","ZodNanoID","ZodCUID","ZodCUID2","ZodULID","ZodBase64","ZodBase64URL","ZodXID","ZodKSUID","ZodIPv4","ZodIPv6","ZodCIDRv4","ZodCIDRv6","ZodE164","ZodISODateTime","ZodISODate","ZodISOTime","ZodISODuration","ZodStringFormat","ZodNumber","exMin","NEGATIVE_INFINITY","exMax","POSITIVE_INFINITY","legacy","divisors","minValue","maxValue","gt","gte","lt","lte","int","safe","positive","nonnegative","negative","nonpositive","finite","ZodNumberFormat","ZodBoolean","ZodUnknown","ZodNever","not","ZodArray","minItems","maxItems","unwrap","ZodObject","requiredKeys","sentinel","claim","keyof","ZodEnum","passthrough","loose","strict","strip","extend","incoming","existingShape","safeExtend","currDef","omit","omitted","ZodOptional","exactPartial","isExclusive","oneOf","isSimpleIntersection","ZodRecord","valueSchema","patternProperties","propertyNames","pending","rewrites","record","names","rewritten","carrier","rewriteKeyNames","keyValues","omittableOnInput","validKeyValues","extract","newEntries","exclude","ZodLiteral","ZodNullable","removeDefault","removeCatch","ZodPipe","inIsTransform","in_","readOnly","baseUrl","createdSchema","statusSchema","summary","failureReason","completionQuality","degradedReason","reportSchema","reportPending","reportContent","reportSpec","elements","children","request","method","signal","throwIfAborted","response$","getBackendSrv","fetch","abortSignal","showErrorAlert","showSuccessAlert","response","firstValueFrom","fromEvent","mergeMap","reason","resourcePath","createInvestigation","instruction","getInvestigationStatus","getInvestigationReport","refreshIntervalMs","connectTimeoutMs","envelopeSchema","textDeltaSchema","messageId","contentIndex","contentType","audience","observeInvestigation","Observable","subscriber","controller","AbortController","connectedChatId","connectTimer","refreshTimer","eventTimer","previousStatus","previousReport","refreshing","refreshRequested","fail","openStream","close","connection","EventSource","onopen","refreshFromEvent","onerror","onmessage","requestRefresh","serializedStatus","report","isFetchError","serializedReport","complete","defaults","maxAttempts","initialBackoffMs","maxBackoffMs","factor","jitter","maxTimeoutMs","retryableStatuses","finiteNonNegative","fallback","isRetryableStatus","backoffMs","attempt","initial","grown","sleep","ms","reject","onAbort","once","grotSchema","purpose","teamId","labels","grotListSchema","agents","workSchema","laneClosedSchema","laneKey","cancelledFollowUps","messagesFields","messages","total","messagesPageSchema","laneSchema","topicId","settled","runningWorkId","pendingWork","busy","topicSchema","threadId","createdBy","archivedAt","pinnedAt","topicAcceptedSchema","work","directTopicSchema","helpersWorking","topicListSchema","thread","topics","settledCount","retryable","withRetry","search","requestOnce","requireValue","grotPath","requireMessage","dedupeKey","listGrots","labelSelector","getGrot","createGrot","ownerDelegation","bindGrot","requireRevision","expectedRevision","wakeGrot","workflow","closeGrotLane","readGrotLane","after","createGrotTopic","postGrotTopicMessage","listGrotTopics","excludeSettled","listGrotTopicMessages","chat","GrotLabelsNotSupportedError","updateGrot","updated","updateGrotTopic","archiveGrotTopic","archived","asRecord","parsePart","kind","toolName","parseGrotTopicMessage","msg","created","parsed","parseVersion","versionPart","prerelease","numbers","TERMS_AND_CONDITIONS_REFRESH_EVENT","fetchTermsData","backendSrv","apiUrl","termsData","lastValueFrom","termsAccepted","acceptedTermsAndConditions","acceptedVersion","currentVersion","termsType","accepted","needsAcceptance","parsed1","parsed2","compareVersions","nonEmptyString","describeTermsError","serverMessage","checkTerms","useTerms","setAccepted","setTermsType","loading","setLoading","fetchTerms","handleTermsRefresh","document","createTool","func","explainer","toolObj","inputSchema","responseFormat","verboseParsingErrors","invoke","invokeOptions","parsedInput","promises","timeout","race","LIMITS_UPDATED_EVENT","fetchLimitsData","limitsData","limit","month","isLimitReached","checkLimits","useLimits","setCount","setLimit","setMonth","fetchLimits","handleLimitsUpdate","customEvent","refetch","K6SetScriptContentEvent","onK6SetScriptContent","callback","subscription","PATHFINDER_OPERATIONS","refreshGuide","PathfinderEvent","onPathfinderEvent","ASSISTANT_EXTENSION_POINT","InlineChitDisplay","Inline","Block","getAssistantExtensionConfig","manifest","SuggestionContext","Home","CloudHome","Workspace","Dashboard","Dashboards","Alerting","AlertRules","AlertRule","Notifications","Silences","Connections","DataSources","Explore","Drilldown","Metrics","Logs","Traces","Profiles","SQL","Admin","Users","Organization","Teams","ServiceAccounts","Notebooks","Notebook","NewNotebook","Pages","Page","PageTemplates","NewPage","Costs"],"sourceRoot":""}
|