@codemation/core-nodes 0.4.3 → 0.6.0
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/CHANGELOG.md +215 -0
- package/dist/index.cjs +3485 -474
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1763 -685
- package/dist/index.d.ts +1763 -685
- package/dist/index.js +3452 -479
- package/dist/index.js.map +1 -1
- package/package.json +8 -5
- package/src/authoring/defineRestNode.types.ts +204 -0
- package/src/chatModels/OpenAIChatModelFactory.ts +17 -8
- package/src/chatModels/OpenAiStrictJsonSchemaFactory.ts +123 -0
- package/src/credentials/ApiKeyCredentialType.ts +60 -0
- package/src/credentials/BasicAuthCredentialType.ts +51 -0
- package/src/credentials/BearerTokenCredentialType.ts +40 -0
- package/src/credentials/OAuth2ClientCredentialsTypeFactory.ts +117 -0
- package/src/credentials/OAuth2TokenExchangeFactory.ts +52 -0
- package/src/credentials/index.ts +4 -0
- package/src/http/HttpBodyBuilder.ts +90 -0
- package/src/http/HttpRequestExecutor.ts +150 -0
- package/src/http/HttpUrlBuilder.ts +22 -0
- package/src/http/httpRequest.types.ts +69 -0
- package/src/index.ts +10 -1
- package/src/nodes/AIAgentExecutionHelpersFactory.ts +45 -59
- package/src/nodes/AIAgentNode.ts +391 -288
- package/src/nodes/AgentMessageFactory.ts +57 -49
- package/src/nodes/AgentStructuredOutputRunner.ts +65 -71
- package/src/nodes/AgentToolExecutionCoordinator.ts +31 -16
- package/src/nodes/AssertionNode.ts +42 -0
- package/src/nodes/CronTriggerFactory.ts +45 -0
- package/src/nodes/CronTriggerNode.ts +40 -0
- package/src/nodes/HttpRequestNodeFactory.ts +99 -23
- package/src/nodes/IsTestRunNode.ts +25 -0
- package/src/nodes/NodeBackedToolRuntime.ts +40 -4
- package/src/nodes/TestTriggerNode.ts +33 -0
- package/src/nodes/WebhookTriggerFactory.ts +1 -1
- package/src/nodes/aggregate.ts +1 -1
- package/src/nodes/aiAgentSupport.types.ts +22 -2
- package/src/nodes/assertion.ts +42 -0
- package/src/nodes/collections/collectionDeleteNode.types.ts +23 -0
- package/src/nodes/collections/collectionFindOneNode.types.ts +26 -0
- package/src/nodes/collections/collectionGetNode.types.ts +26 -0
- package/src/nodes/collections/collectionInsertNode.types.ts +22 -0
- package/src/nodes/collections/collectionListNode.types.ts +30 -0
- package/src/nodes/collections/collectionUpdateNode.types.ts +23 -0
- package/src/nodes/collections/index.ts +6 -0
- package/src/nodes/httpRequest.ts +62 -1
- package/src/nodes/if.ts +1 -1
- package/src/nodes/isTestRun.ts +24 -0
- package/src/nodes/mapData.ts +1 -0
- package/src/nodes/merge.ts +1 -1
- package/src/nodes/noOp.ts +1 -0
- package/src/nodes/split.ts +1 -1
- package/src/nodes/testTrigger.ts +72 -0
- package/src/nodes/wait.ts +1 -0
- package/src/chatModels/OpenAIStructuredOutputMethodFactory.ts +0 -46
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["OpenAIChatModelFactory","ChatOpenAI","OpenAIStructuredOutputMethodFactory","name: string","model: string","credentialSlotKey: string","options?: Readonly<{\n temperature?: number;\n maxTokens?: number;\n }>","SystemMessage","HumanMessage","AIMessage","ToolMessage","_a","_a","config","initializer","util.jsonStringifyReplacer","issue","error","core.$ZodAsyncError","util.finalizeIssue","core.config","parse","errors.$ZodRealError","parseAsync","errors.$ZodError","safeParse","safeParseAsync","encode","decode","encodeAsync","decodeAsync","safeEncode","safeDecode","safeEncodeAsync","safeDecodeAsync","_a","util.nullish","inst","util.getLengthableOrigin","_a","util.aborted","checks","core.$ZodAsyncError","checkResult","canary","result","safeParse","safeParseAsync","util.prefixIssues","util.finalizeIssue","core.config","util.cleanRegex","results","left","right","util.isPlainObject","core.$ZodEncodeError","r","util.issue","meta","checks.$ZodCheckMaxLength","util.normalizeParams","checks.$ZodCheckMinLength","checks.$ZodCheckLengthEquals","checks.$ZodCheckOverwrite","issue","util.issue","checks.$ZodCheck","describe","meta","_a","meta","id","schema","registry","ctx","CredentialResolverFactory","AIAgentExecutionHelpersFactory","DynamicStructuredTool","converted: unknown","node","AgentStructuredOutputRepairPromptFactory","executionHelpers: AIAgentExecutionHelpersFactory","core.formatError","core.flattenError","issue","util.jsonStringifyReplacer","issues","core.$constructor","util.mergeDefs","core.clone","def","meta","parse.parse","parse.safeParse","parse.parseAsync","parse.safeParseAsync","parse.encode","parse.decode","parse.encodeAsync","parse.decodeAsync","parse.safeEncode","parse.safeDecode","parse.safeEncodeAsync","parse.safeDecodeAsync","checks.overwrite","processors.unknownProcessor","core._unknown","processors.arrayProcessor","checks.minLength","checks.maxLength","checks.length","core._array","processors.unionProcessor","util.normalizeParams","processors.intersectionProcessor","processors.transformProcessor","core.$ZodEncodeError","issue","util.issue","output","processors.optionalProcessor","processors.nullableProcessor","processors.defaultProcessor","util.shallowClone","processors.prefaultProcessor","processors.nonoptionalProcessor","processors.catchProcessor","processors.pipeProcessor","processors.readonlyProcessor","processors.customProcessor","core._refine","core._superRefine","core.describe","core.meta","AgentStructuredOutputRunner","repairPromptFactory: AgentStructuredOutputRepairPromptFactory","openAiStructuredOutputMethodFactory: OpenAIStructuredOutputMethodFactory","lastFailure: ParsedStructuredOutputFailure | undefined","issue","AgentToolErrorClassifier","issue","details: Record<string, JsonValue>","issue","result: Record<string, JsonValue>","AgentToolRepairPolicy","AgentToolExecutionCoordinator","errorClassifier: AgentToolErrorClassifier","repairPolicy: AgentToolRepairPolicy","ConnectionInvocationIdFactory","CodemationTelemetryAttributeNames","payload: Record<string, JsonValue>","details: Record<string, JsonValue>","issue","result: Record<string, JsonValue>","NodeBackedToolRuntime","nodeResolver: NodeResolver","itemExprResolver: ItemExprResolver","outputNormalizer: NodeOutputNormalizer","outputBehaviorResolver: RunnableOutputBehaviorResolver","config","z.unknown","execArgs: RunnableNodeExecuteArgs","CoreTokens","ItemExprResolver","NodeOutputNormalizer","RunnableOutputBehaviorResolver","AIAgentNode","z.unknown","nodeResolver: NodeResolver","credentialSessions: CredentialSessionService","nodeBackedToolRuntime: NodeBackedToolRuntime","executionHelpers: AIAgentExecutionHelpersFactory","structuredOutputRunner: AgentStructuredOutputRunner","toolExecutionCoordinator: AgentToolExecutionCoordinator","ConnectionNodeIdFactory","conversation: BaseMessage[]","CodemationTelemetryMetricNames","finalResponse: AIMessage | undefined","config","ConnectionInvocationIdFactory","CodemationTelemetryAttributeNames","GenAiTelemetryAttributeNames","chatModel","current: unknown","AgentMessageConfigNormalizer","NodeBackedToolConfig","CallableToolConfig","AgentGuardrailDefaults","CoreTokens","RetryPolicy","CallbackNode","config","result","name: string","callback: CallbackHandler<TInputJson, TOutputJson>","HttpRequestNode","outputItem: Item","values: Record<string, string>","name: string","args: Readonly<{\n method?: string;\n urlField?: string;\n binaryName?: string;\n downloadMode?: HttpRequestDownloadMode;\n id?: string;\n }>","retryPolicy: RetryPolicySpec","RetryPolicy","AggregateNode","name: string","aggregate: (\n items: Items<TIn>,\n ctx: NodeExecutionContext<Aggregate<TIn, TOut>>,\n ) => TOut | Promise<TOut>","id?: string","FilterNode","name: string","predicate: (\n item: Item<TIn>,\n index: number,\n items: Items<TIn>,\n ctx: NodeExecutionContext<Filter<TIn>>,\n ) => boolean","id?: string","IfNode","name: string","predicate: (\n item: Item<TInputJson>,\n index: number,\n items: Items<TInputJson>,\n ctx: NodeExecutionContext<If<TInputJson>>,\n ) => boolean","id?: string","SwitchNode","name: string","cfg: Readonly<{\n cases: readonly string[];\n defaultCase: string;\n resolveCaseKey: SwitchCaseKeyResolver<TInputJson>;\n }>","id?: string","SplitNode","name: string","getElements: (item: Item<TIn>, ctx: NodeExecutionContext<Split<TIn, TElem>>) => readonly TElem[]","id?: string","ManualTriggerNode","config","ItemsInputNormalizer","name: string","MapDataNode","z.unknown","name: string","map: (\n item: Item<TInputJson>,\n ctx: NodeExecutionContext<MapData<TInputJson, TOutputJson>>,\n ) => TOutputJson","options: MapDataOptions","MergeNode","out: Item[]","out","json: Record<string, unknown>","paired: any[]","meta: Record<string, unknown> | undefined","meta","merged: any","fallback: Item[]","name: string","cfg: Readonly<{\n mode: MergeMode;\n /**\n * Deterministic input precedence order (only used for passThrough/append).\n * Any inputs not listed are appended in lexicographic order.\n */\n prefer?: ReadonlyArray<InputPortKey>;\n }>","id?: string","NoOpNode","name: string","id?: string","SubWorkflowNode","workflows: WorkflowRunnerService","out: Item[]","CoreTokens","name: string","workflowId: string","upstreamRefs?: Array<{ nodeId: NodeId } | UpstreamRefPlaceholder>","startAt?: NodeId","id?: string","WaitNode","name: string","milliseconds: number","id?: string","responseItems: Items","continueItems: Items","responseItems: Items","WebhookTriggerNode","name: string","args: Readonly<{\n endpointKey: string;\n methods: ReadonlyArray<HttpMethod>;\n inputSchema?: TSchema;\n }>","handler: WebhookTriggerHandler<\n WebhookTrigger<TSchema>\n >","id?: string","ConnectionCredentialNode","WorkflowBuilder","meta","DefinedNodeRegistry","steps: ReadonlyArray<AnyRunnableNodeConfig>","config","chain: ChainCursor<TCurrentJson>","config","id: string","workflowName: string","connectionCredentialNodeConfigFactory: ConnectionCredentialNodeConfigFactory","workflow","extraNodes: NodeDefinition[]","node","AgentConfigInspector","AgentConnectionNodeCollector","name: string","credentialSource: { getCredentialRequirements?: () => ReadonlyArray<CredentialRequirement> }"],"sources":["../src/chatModels/OpenAIChatModelFactory.ts","../src/chatModels/OpenAIStructuredOutputMethodFactory.ts","../src/chatModels/openAiChatModelConfig.ts","../src/chatModels/OpenAiChatModelPresetsFactory.ts","../src/nodes/AgentMessageFactory.ts","../src/nodes/AgentOutputFactory.ts","../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/core.js","../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/util.js","../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/errors.js","../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/parse.js","../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/checks.js","../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/versions.js","../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/schemas.js","../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/registries.js","../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/api.js","../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/to-json-schema.js","../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/json-schema-processors.js","../src/nodes/ConnectionCredentialExecutionContextFactory.ts","../src/nodes/AIAgentExecutionHelpersFactory.ts","../src/nodes/AgentStructuredOutputRepairPromptFactory.ts","../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/errors.js","../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/parse.js","../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/schemas.js","../src/nodes/AgentStructuredOutputRunner.ts","../src/nodes/AgentToolCallPortMapFactory.ts","../src/nodes/AgentToolErrorClassifier.ts","../src/nodes/AgentToolRepairExhaustedError.ts","../src/nodes/AgentToolRepairPolicy.ts","../src/nodes/AgentToolExecutionCoordinator.ts","../src/nodes/NodeBackedToolRuntime.ts","../src/nodes/aiAgentSupport.types.ts","../src/nodes/AIAgentNode.ts","../src/nodes/AIAgentConfig.ts","../src/nodes/CallbackResultNormalizerFactory.ts","../src/nodes/CallbackNode.ts","../src/nodes/CallbackNodeFactory.ts","../src/nodes/HttpRequestNodeFactory.ts","../src/nodes/httpRequest.ts","../src/nodes/AggregateNode.ts","../src/nodes/aggregate.ts","../src/nodes/FilterNode.ts","../src/nodes/filter.ts","../src/nodes/mergeExecutionUtils.types.ts","../src/nodes/IfNode.ts","../src/nodes/if.ts","../src/nodes/SwitchNode.ts","../src/nodes/switch.ts","../src/nodes/SplitNode.ts","../src/nodes/split.ts","../src/nodes/ManualTriggerNode.ts","../src/nodes/ManualTriggerFactory.ts","../src/nodes/MapDataNode.ts","../src/nodes/mapData.ts","../src/nodes/MergeNode.ts","../src/nodes/merge.ts","../src/nodes/NoOpNode.ts","../src/nodes/noOp.ts","../src/nodes/SubWorkflowNode.ts","../src/nodes/subWorkflow.ts","../src/nodes/WaitDurationFactory.ts","../src/nodes/WaitNode.ts","../src/nodes/wait.ts","../src/nodes/webhookRespondNowAndContinueError.ts","../src/nodes/webhookRespondNowError.ts","../src/nodes/webhookTriggerNode.ts","../src/nodes/WebhookTriggerFactory.ts","../src/nodes/ConnectionCredentialNode.ts","../src/register.types.ts","../src/workflowBuilder.types.ts","../src/workflowAuthoring/WorkflowChatModelFactory.types.ts","../src/workflowAuthoring/WorkflowAgentNodeFactory.types.ts","../src/workflowAuthoring/WorkflowDefinedNodeResolver.types.ts","../src/workflowAuthoring/WorkflowDurationParser.types.ts","../src/workflowAuthoring/WorkflowBranchBuilder.types.ts","../src/workflowAuthoring/WorkflowChain.types.ts","../src/workflowAuthoring/WorkflowAuthoringBuilder.types.ts","../src/workflowAuthoring.types.ts","../src/workflows/AIAgentConnectionWorkflowExpander.ts","../src/nodes/ConnectionCredentialNodeConfig.ts","../src/nodes/ConnectionCredentialNodeConfigFactory.ts"],"sourcesContent":["import type { ChatModelFactory, LangChainChatModelLike, NodeExecutionContext } from \"@codemation/core\";\nimport { chatModel } from \"@codemation/core\";\nimport { ChatOpenAI } from \"@langchain/openai\";\nimport type { OpenAiCredentialSession } from \"./OpenAiCredentialSession\";\nimport type { OpenAIChatModelConfig } from \"./openAiChatModelConfig\";\n\n@chatModel({ packageName: \"@codemation/core-nodes\" })\nexport class OpenAIChatModelFactory implements ChatModelFactory<OpenAIChatModelConfig> {\n async create(\n args: Readonly<{ config: OpenAIChatModelConfig; ctx: NodeExecutionContext<any> }>,\n ): Promise<LangChainChatModelLike> {\n const session = await args.ctx.getCredential<OpenAiCredentialSession>(args.config.credentialSlotKey);\n return new ChatOpenAI({\n apiKey: session.apiKey,\n model: args.config.model,\n temperature: args.config.options?.temperature,\n maxTokens: args.config.options?.maxTokens,\n configuration: session.baseUrl ? { baseURL: session.baseUrl } : undefined,\n });\n }\n}\n","import type { ChatModelConfig, ChatModelStructuredOutputOptions } from \"@codemation/core\";\nimport { injectable } from \"@codemation/core\";\n\nimport { OpenAIChatModelFactory } from \"./OpenAIChatModelFactory\";\n\n@injectable()\nexport class OpenAIStructuredOutputMethodFactory {\n private static readonly isoDatePattern = /^\\d{4}-\\d{2}-\\d{2}$/;\n\n create(chatModelConfig: ChatModelConfig): ChatModelStructuredOutputOptions | undefined {\n if (chatModelConfig.type !== OpenAIChatModelFactory) {\n return undefined;\n }\n const model = this.readModelName(chatModelConfig);\n if (!model) {\n return { method: \"functionCalling\", strict: true };\n }\n return {\n method: this.supportsJsonSchema(model) ? \"jsonSchema\" : \"functionCalling\",\n strict: true,\n };\n }\n\n private readModelName(chatModelConfig: ChatModelConfig): string | undefined {\n const candidate = chatModelConfig as Readonly<{ model?: unknown }>;\n return typeof candidate.model === \"string\" ? candidate.model : undefined;\n }\n\n private supportsJsonSchema(model: string): boolean {\n if (model === \"gpt-4o\" || model === \"gpt-4o-mini\") {\n return true;\n }\n return (\n this.supportsSnapshotAtOrAfter(model, \"gpt-4o-\", \"2024-08-06\") ||\n this.supportsSnapshotAtOrAfter(model, \"gpt-4o-mini-\", \"2024-07-18\")\n );\n }\n\n private supportsSnapshotAtOrAfter(model: string, prefix: string, minimumSnapshotDate: string): boolean {\n if (!model.startsWith(prefix)) {\n return false;\n }\n const snapshotDate = model.slice(prefix.length);\n return OpenAIStructuredOutputMethodFactory.isoDatePattern.test(snapshotDate) && snapshotDate >= minimumSnapshotDate;\n }\n}\n","import type { AgentCanvasPresentation, ChatModelConfig, CredentialRequirement } from \"@codemation/core\";\n\nimport type { CanvasIconName } from \"../canvasIconName\";\nimport { OpenAIChatModelFactory } from \"./OpenAIChatModelFactory\";\n\nexport class OpenAIChatModelConfig implements ChatModelConfig {\n readonly type = OpenAIChatModelFactory;\n readonly presentation: AgentCanvasPresentation<CanvasIconName>;\n readonly provider = \"openai\";\n readonly modelName: string;\n\n constructor(\n public readonly name: string,\n public readonly model: string,\n public readonly credentialSlotKey: string = \"openai\",\n presentationIn?: AgentCanvasPresentation<CanvasIconName>,\n public readonly options?: Readonly<{\n temperature?: number;\n maxTokens?: number;\n }>,\n ) {\n this.modelName = model;\n this.presentation = presentationIn ?? { icon: \"builtin:openai\", label: name };\n }\n\n getCredentialRequirements(): ReadonlyArray<CredentialRequirement> {\n return [\n {\n slotKey: this.credentialSlotKey,\n label: \"OpenAI API key\",\n acceptedTypes: [\"openai.apiKey\"],\n },\n ];\n }\n}\n","import { OpenAIChatModelConfig } from \"./openAiChatModelConfig\";\n\n/**\n * Default OpenAI chat model configs for scaffolds and demos (icon + label match {@link OpenAIChatModelConfig} defaults).\n * Prefer importing {@link openAiChatModelPresets} from here or from the consumer template re-export\n * instead of repeating {@link OpenAIChatModelConfig} construction in app workflows.\n */\nexport class OpenAiChatModelPresets {\n readonly demoGpt4oMini = new OpenAIChatModelConfig(\"OpenAI\", \"gpt-4o-mini\");\n\n readonly demoGpt41 = new OpenAIChatModelConfig(\"OpenAI\", \"gpt-4.1\");\n}\n\nexport const openAiChatModelPresets = new OpenAiChatModelPresets();\n","import type { AgentMessageDto, AgentToolCall } from \"@codemation/core\";\n\nimport { AIMessage, HumanMessage, SystemMessage, ToolMessage, type BaseMessage } from \"@langchain/core/messages\";\n\nexport class AgentMessageFactory {\n static createPromptMessages(messages: ReadonlyArray<AgentMessageDto>): ReadonlyArray<BaseMessage> {\n return messages.map((message) => this.createPromptMessage(message));\n }\n\n static createSystemPrompt(systemMessage: string): SystemMessage {\n return new SystemMessage(systemMessage);\n }\n\n static createUserPrompt(prompt: string): HumanMessage {\n return new HumanMessage(prompt);\n }\n\n static createAssistantPrompt(prompt: string): AIMessage {\n return new AIMessage(prompt);\n }\n\n static createToolMessage(toolCallId: string, content: string): ToolMessage {\n return new ToolMessage({ tool_call_id: toolCallId, content });\n }\n\n static extractContent(message: unknown): string {\n if (typeof message === \"string\") return message;\n if (!this.isRecord(message)) return String(message);\n const content = message.content;\n if (typeof content === \"string\") return content;\n if (Array.isArray(content)) {\n return content\n .map((part) => {\n if (typeof part === \"string\") return part;\n if (this.isRecord(part) && typeof part.text === \"string\") return part.text;\n return JSON.stringify(part);\n })\n .join(\"\\n\");\n }\n return JSON.stringify(content);\n }\n\n static extractToolCalls(message: unknown): ReadonlyArray<AgentToolCall> {\n if (!this.isRecord(message)) return [];\n const toolCalls = message.tool_calls;\n if (!Array.isArray(toolCalls)) return [];\n return toolCalls\n .filter((toolCall) => this.isRecord(toolCall) && typeof toolCall.name === \"string\")\n .map((toolCall) => ({\n id: typeof toolCall.id === \"string\" ? toolCall.id : undefined,\n name: toolCall.name as string,\n input: this.isRecord(toolCall) && \"args\" in toolCall ? toolCall.args : undefined,\n }));\n }\n\n private static isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null;\n }\n\n private static createPromptMessage(message: AgentMessageDto): BaseMessage {\n if (message.role === \"system\") {\n return this.createSystemPrompt(message.content);\n }\n if (message.role === \"assistant\") {\n return this.createAssistantPrompt(message.content);\n }\n return this.createUserPrompt(message.content);\n }\n}\n","import type { Item, NodeOutputs } from \"@codemation/core\";\n\nexport class AgentOutputFactory {\n static fromUnknown(value: unknown): NodeOutputs {\n return { main: [{ json: value }] };\n }\n\n static replaceJson(item: Item, value: unknown): Item {\n return {\n ...item,\n json: value,\n };\n }\n\n static fromAgentContent(content: string): unknown {\n try {\n return JSON.parse(content) as unknown;\n } catch {\n return { output: content };\n }\n }\n}\n","/** A special constant with type `never` */\nexport const NEVER = Object.freeze({\n status: \"aborted\",\n});\nexport /*@__NO_SIDE_EFFECTS__*/ function $constructor(name, initializer, params) {\n function init(inst, def) {\n if (!inst._zod) {\n Object.defineProperty(inst, \"_zod\", {\n value: {\n def,\n constr: _,\n traits: new Set(),\n },\n enumerable: false,\n });\n }\n if (inst._zod.traits.has(name)) {\n return;\n }\n inst._zod.traits.add(name);\n initializer(inst, def);\n // support prototype modifications\n const proto = _.prototype;\n const keys = Object.keys(proto);\n for (let i = 0; i < keys.length; i++) {\n const k = keys[i];\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 var _a;\n const inst = params?.Parent ? new Definition() : this;\n init(inst, def);\n (_a = inst._zod).deferred ?? (_a.deferred = []);\n for (const fn of inst._zod.deferred) {\n fn();\n }\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 = 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}\nexport const globalConfig = {};\nexport function config(newConfig) {\n if (newConfig)\n Object.assign(globalConfig, newConfig);\n return globalConfig;\n}\n","// functions\nexport function assertEqual(val) {\n return val;\n}\nexport function assertNotEqual(val) {\n return val;\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}\nexport function cached(getter) {\n const set = false;\n return {\n get value() {\n if (!set) {\n const value = getter();\n Object.defineProperty(this, \"value\", { value });\n return value;\n }\n throw new Error(\"cached value already set\");\n },\n };\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 valDecCount = (val.toString().split(\".\")[1] || \"\").length;\n const stepString = step.toString();\n let stepDecCount = (stepString.split(\".\")[1] || \"\").length;\n if (stepDecCount === 0 && /\\d?e-\\d?/.test(stepString)) {\n const match = stepString.match(/\\d?e-(\\d?)/);\n if (match?.[1]) {\n stepDecCount = Number.parseInt(match[1]);\n }\n }\n const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;\n const valInt = Number.parseInt(val.toFixed(decCount).replace(\".\", \"\"));\n const stepInt = Number.parseInt(step.toFixed(decCount).replace(\".\", \"\"));\n return (valInt % stepInt) / 10 ** decCount;\n}\nconst EVALUATING = 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}\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 = cached(() => {\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 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 = new Set([\"string\", \"number\", \"symbol\"]);\nexport const primitiveTypes = new Set([\"string\", \"number\", \"bigint\", \"boolean\", \"symbol\", \"undefined\"]);\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 === \"optional\" && shape[k]._zod.optout === \"optional\";\n });\n}\nexport const NUMBER_FORMAT_RANGES = {\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 def = mergeDefs(schema._zod.def, {\n get shape() {\n const newShape = {};\n for (const key in mask) {\n if (!(key in currDef.shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n newShape[key] = currDef.shape[key];\n }\n assignProp(this, \"shape\", newShape); // self-caching\n return newShape;\n },\n checks: [],\n });\n return clone(schema, def);\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 def = mergeDefs(schema._zod.def, {\n get shape() {\n const newShape = { ...schema._zod.def.shape };\n for (const key in mask) {\n if (!(key in currDef.shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n delete newShape[key];\n }\n assignProp(this, \"shape\", newShape); // self-caching\n return newShape;\n },\n checks: [],\n });\n return clone(schema, def);\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\n // Use getOwnPropertyDescriptor to check key existence without accessing values\n const existingShape = schema._zod.def.shape;\n for (const key in 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 const def = mergeDefs(schema._zod.def, {\n get shape() {\n const _shape = { ...schema._zod.def.shape, ...shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n });\n return clone(schema, def);\n}\nexport function safeExtend(schema, shape) {\n if (!isPlainObject(shape)) {\n throw new Error(\"Invalid input to safeExtend: expected a plain object\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const _shape = { ...schema._zod.def.shape, ...shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n });\n return clone(schema, def);\n}\nexport function merge(a, b) {\n const def = mergeDefs(a._zod.def, {\n get shape() {\n const _shape = { ...a._zod.def.shape, ...b._zod.def.shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n get catchall() {\n return b._zod.def.catchall;\n },\n checks: [], // delete existing checks\n });\n return clone(a, def);\n}\nexport function partial(Class, 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(\".partial() cannot be used on object schemas containing refinements\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const oldShape = schema._zod.def.shape;\n const shape = { ...oldShape };\n if (mask) {\n for (const key in mask) {\n if (!(key in oldShape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n // if (oldShape[key]!._zod.optin === \"optional\") continue;\n shape[key] = Class\n ? new Class({\n type: \"optional\",\n innerType: oldShape[key],\n })\n : oldShape[key];\n }\n }\n else {\n for (const key in oldShape) {\n // if (oldShape[key]!._zod.optin === \"optional\") continue;\n shape[key] = Class\n ? new Class({\n type: \"optional\",\n innerType: oldShape[key],\n })\n : oldShape[key];\n }\n }\n assignProp(this, \"shape\", shape); // self-caching\n return shape;\n },\n checks: [],\n });\n return clone(schema, def);\n}\nexport function required(Class, schema, mask) {\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const oldShape = schema._zod.def.shape;\n const shape = { ...oldShape };\n if (mask) {\n for (const key in mask) {\n if (!(key in shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n // overwrite with non-optional\n shape[key] = new Class({\n type: \"nonoptional\",\n innerType: oldShape[key],\n });\n }\n }\n else {\n for (const key in oldShape) {\n // overwrite with non-optional\n shape[key] = new Class({\n type: \"nonoptional\",\n innerType: oldShape[key],\n });\n }\n }\n assignProp(this, \"shape\", shape); // self-caching\n return shape;\n },\n });\n return clone(schema, def);\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}\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}\nexport function finalizeIssue(iss, ctx, config) {\n const full = { ...iss, path: iss.path ?? [] };\n // for backwards compatibility\n if (!iss.message) {\n const message = unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ??\n unwrapMessage(ctx?.error?.(iss)) ??\n unwrapMessage(config.customError?.(iss)) ??\n unwrapMessage(config.localeError?.(iss)) ??\n \"Invalid input\";\n full.message = message;\n }\n // delete (full as any).def;\n delete full.inst;\n delete full.continue;\n if (!ctx?.reportInput) {\n delete full.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}\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","import { $constructor } from \"./core.js\";\nimport * as util from \"./util.js\";\nconst initializer = (inst, def) => {\n inst.name = \"$ZodError\";\n Object.defineProperty(inst, \"_zod\", {\n value: inst._zod,\n enumerable: false,\n });\n Object.defineProperty(inst, \"issues\", {\n value: def,\n enumerable: false,\n });\n inst.message = JSON.stringify(def, util.jsonStringifyReplacer, 2);\n Object.defineProperty(inst, \"toString\", {\n value: () => inst.message,\n enumerable: false,\n });\n};\nexport const $ZodError = $constructor(\"$ZodError\", initializer);\nexport const $ZodRealError = $constructor(\"$ZodError\", initializer, { Parent: Error });\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 fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];\n 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) => {\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\" && issue.errors.length) {\n issue.errors.map((issues) => processError({ issues }));\n }\n else if (issue.code === \"invalid_key\") {\n processError({ issues: issue.issues });\n }\n else if (issue.code === \"invalid_element\") {\n processError({ issues: issue.issues });\n }\n else if (issue.path.length === 0) {\n fieldErrors._errors.push(mapper(issue));\n }\n else {\n let curr = fieldErrors;\n let i = 0;\n while (i < issue.path.length) {\n const el = issue.path[i];\n const terminal = i === issue.path.length - 1;\n if (!terminal) {\n curr[el] = curr[el] || { _errors: [] };\n }\n else {\n curr[el] = curr[el] || { _errors: [] };\n curr[el]._errors.push(mapper(issue));\n }\n curr = curr[el];\n i++;\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, _b;\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 }, issue.path));\n }\n else if (issue.code === \"invalid_key\") {\n processError({ issues: issue.issues }, issue.path);\n }\n else if (issue.code === \"invalid_element\") {\n processError({ issues: issue.issues }, 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 (_a = curr.properties)[el] ?? (_a[el] = { errors: [] });\n curr = curr.properties[el];\n }\n else {\n curr.items ?? (curr.items = []);\n (_b = curr.items)[el] ?? (_b[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\";\nexport const _parse = (_Err) => (schema, value, _ctx, _params) => {\n const ctx = _ctx ? Object.assign(_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);\n throw e;\n }\n return result.value;\n};\nexport const parse = /* @__PURE__*/ _parse(errors.$ZodRealError);\nexport const _parseAsync = (_Err) => async (schema, value, _ctx, params) => {\n const ctx = _ctx ? Object.assign(_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);\n throw e;\n }\n return result.value;\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\n ? {\n success: false,\n error: new (_Err ?? errors.$ZodError)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n }\n : { success: true, data: result.value };\n};\nexport const safeParse = /* @__PURE__*/ _safeParse(errors.$ZodRealError);\nexport const _safeParseAsync = (_Err) => async (schema, value, _ctx) => {\n const ctx = _ctx ? Object.assign(_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\n ? {\n success: false,\n error: new _Err(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n }\n : { success: true, data: result.value };\n};\nexport const safeParseAsync = /* @__PURE__*/ _safeParseAsync(errors.$ZodRealError);\nexport const _encode = (_Err) => (schema, value, _ctx) => {\n const ctx = _ctx ? Object.assign(_ctx, { direction: \"backward\" }) : { direction: \"backward\" };\n return _parse(_Err)(schema, value, ctx);\n};\nexport const encode = /* @__PURE__*/ _encode(errors.$ZodRealError);\nexport const _decode = (_Err) => (schema, value, _ctx) => {\n return _parse(_Err)(schema, value, _ctx);\n};\nexport const decode = /* @__PURE__*/ _decode(errors.$ZodRealError);\nexport const _encodeAsync = (_Err) => async (schema, value, _ctx) => {\n const ctx = _ctx ? Object.assign(_ctx, { direction: \"backward\" }) : { direction: \"backward\" };\n return _parseAsync(_Err)(schema, value, ctx);\n};\nexport const encodeAsync = /* @__PURE__*/ _encodeAsync(errors.$ZodRealError);\nexport const _decodeAsync = (_Err) => async (schema, value, _ctx) => {\n return _parseAsync(_Err)(schema, value, _ctx);\n};\nexport const decodeAsync = /* @__PURE__*/ _decodeAsync(errors.$ZodRealError);\nexport const _safeEncode = (_Err) => (schema, value, _ctx) => {\n const ctx = _ctx ? Object.assign(_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 ? Object.assign(_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 { $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});\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.onattach.push((inst) => {\n const bag = inst._zod.bag;\n const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY;\n if (def.value < curr) {\n if (def.inclusive)\n bag.maximum = def.value;\n else\n bag.exclusiveMaximum = def.value;\n }\n });\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,\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.onattach.push((inst) => {\n const bag = inst._zod.bag;\n const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY;\n if (def.value > curr) {\n if (def.inclusive)\n bag.minimum = def.value;\n else\n bag.exclusiveMinimum = def.value;\n }\n });\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,\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.onattach.push((inst) => {\n var _a;\n (_a = inst._zod.bag).multipleOf ?? (_a.multipleOf = def.value);\n });\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 ? 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.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.format = def.format;\n bag.minimum = minimum;\n bag.maximum = maximum;\n if (isInt)\n bag.pattern = regexes.integer;\n });\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.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.format = def.format;\n bag.minimum = minimum;\n bag.maximum = maximum;\n });\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 = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.size !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY);\n if (def.maximum < curr)\n inst._zod.bag.maximum = def.maximum;\n });\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 = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.size !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY);\n if (def.minimum > curr)\n inst._zod.bag.minimum = def.minimum;\n });\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 = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.size !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.minimum = def.size;\n bag.maximum = def.size;\n bag.size = def.size;\n });\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 = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.length !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY);\n if (def.maximum < curr)\n inst._zod.bag.maximum = def.maximum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const length = input.length;\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 = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.length !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY);\n if (def.minimum > curr)\n inst._zod.bag.minimum = def.minimum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const length = input.length;\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 = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.length !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.minimum = def.length;\n bag.maximum = def.length;\n bag.length = def.length;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const length = input.length;\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 inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.format = def.format;\n if (def.pattern) {\n bag.patterns ?? (bag.patterns = new Set());\n bag.patterns.add(def.pattern);\n }\n });\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 const pattern = new RegExp(typeof def.position === \"number\" ? `^.{${def.position}}${escapedRegex}` : escapedRegex);\n def.pattern = pattern;\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.patterns ?? (bag.patterns = new Set());\n bag.patterns.add(pattern);\n });\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.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.patterns ?? (bag.patterns = new Set());\n bag.patterns.add(pattern);\n });\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.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.patterns ?? (bag.patterns = new Set());\n bag.patterns.add(pattern);\n });\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 $ZodCheckMimeType = /*@__PURE__*/ core.$constructor(\"$ZodCheckMimeType\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const mimeSet = new Set(def.mime);\n inst._zod.onattach.push((inst) => {\n inst._zod.bag.mime = def.mime;\n });\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 const version = {\n major: 4,\n minor: 3,\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, safeParse, safeParseAsync } 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 checks = [...(inst._zod.def.checks ?? [])];\n // if inst is itself a checks.$ZodCheck, run it as a check\n if (inst._zod.traits.has(\"$ZodCheck\")) {\n checks.unshift(inst);\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\n // 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 let isAborted = util.aborted(payload);\n let asyncResult;\n for (const ch of checks) {\n if (ch._zod.def.when) {\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 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 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\n // 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 // Lazy initialize ~standard to avoid creating objects for every schema\n util.defineLazy(inst, \"~standard\", () => ({\n validate: (value) => {\n try {\n const r = safeParse(inst, value);\n return r.success ? { value: r.data } : { issues: r.error?.issues };\n }\n catch (_) {\n return safeParseAsync(inst, value).then((r) => (r.success ? { value: r.data } : { issues: r.error?.issues }));\n }\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 inst._zod.pattern = [...(inst?._zod.bag?.patterns ?? [])].pop() ?? regexes.string(inst._zod.bag);\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});\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 // @ts-ignore\n const url = new URL(trimmed);\n if (def.hostname) {\n def.hostname.lastIndex = 0;\n if (!def.hostname.test(url.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 }\n if (def.protocol) {\n def.protocol.lastIndex = 0;\n if (!def.protocol.test(url.protocol.endsWith(\":\") ? url.protocol.slice(0, -1) : url.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 }\n // Set the output value based on normalize flag\n if (def.normalize) {\n // Use normalized URL\n payload.value = url.href;\n }\n else {\n // Preserve the original input (trimmed)\n payload.value = trimmed;\n }\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 def.pattern ?? (def.pattern = regexes.nanoid);\n $ZodStringFormat.init(inst, def);\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 inst._zod.bag.format = `ipv4`;\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.bag.format = `ipv6`;\n inst._zod.check = (payload) => {\n try {\n // @ts-ignore\n new URL(`http://[${payload.value}]`);\n // return;\n }\n catch {\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 inst._zod.bag.format = `mac`;\n});\nexport const $ZodCIDRv4 = /*@__PURE__*/ core.$constructor(\"$ZodCIDRv4\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cidrv4);\n $ZodStringFormat.init(inst, def);\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 const parts = payload.value.split(\"/\");\n try {\n if (parts.length !== 2)\n throw new Error();\n const [address, prefix] = parts;\n if (!prefix)\n throw new Error();\n const prefixNum = Number(prefix);\n if (`${prefixNum}` !== prefix)\n throw new Error();\n if (prefixNum < 0 || prefixNum > 128)\n throw new Error();\n // @ts-ignore\n new URL(`http://[${address}]`);\n }\n catch {\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 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}\nexport const $ZodBase64 = /*@__PURE__*/ core.$constructor(\"$ZodBase64\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.base64);\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.contentEncoding = \"base64\";\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////////////////////////////// ZodBase64 //////////////////////////////\nexport function isValidBase64URL(data) {\n if (!regexes.base64url.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 = regexes.base64url);\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.contentEncoding = \"base64url\";\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////////////////////////////// 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 = inst._zod.bag.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 ? \"Infinity\"\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.optin = \"optional\";\n inst._zod.optout = \"optional\";\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});\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 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 = Array(input.length);\n const proms = [];\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 }\n }\n if (proms.length) {\n return Promise.all(proms).then(() => payload);\n }\n return payload; //handleArrayResultsAsync(parseResults, final);\n };\n});\nfunction handlePropertyResult(result, final, key, input, isOptionalOut) {\n if (result.issues.length) {\n // For optional-out schemas, ignore errors on absent keys\n if (isOptionalOut && !(key in input)) {\n return;\n }\n final.issues.push(...util.prefixIssues(key, result.issues));\n }\n if (result.value === undefined) {\n if (key in input) {\n final.value[key] = undefined;\n }\n }\n else {\n final.value[key] = result.value;\n }\n}\nfunction normalizeDef(def) {\n const keys = Object.keys(def.shape);\n for (const k of keys) {\n if (!def.shape?.[k]?._zod?.traits?.has(\"$ZodType\")) {\n throw new Error(`Invalid element at key \"${k}\": expected a Zod schema`);\n }\n }\n const okeys = util.optionalKeys(def.shape);\n return {\n ...def,\n keys,\n keySet: new Set(keys),\n numKeys: keys.length,\n optionalKeys: new Set(okeys),\n };\n}\nfunction handleCatchall(proms, input, payload, ctx, def, inst) {\n const unrecognized = [];\n // iterate over input keys\n const keySet = def.keySet;\n const _catchall = def.catchall._zod;\n const t = _catchall.def.type;\n const isOptionalOut = _catchall.optout === \"optional\";\n for (const key in input) {\n if (keySet.has(key))\n continue;\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, isOptionalOut)));\n }\n else {\n handlePropertyResult(r, payload, key, input, isOptionalOut);\n }\n }\n if (unrecognized.length) {\n payload.issues.push({\n code: \"unrecognized_keys\",\n keys: unrecognized,\n input,\n inst,\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 sh = def.shape;\n const desc = Object.getOwnPropertyDescriptor(def, \"shape\");\n if (!desc?.get) {\n const sh = def.shape;\n Object.defineProperty(def, \"shape\", {\n get: () => {\n const newSh = { ...sh };\n Object.defineProperty(def, \"shape\", {\n value: newSh,\n });\n return newSh;\n },\n });\n }\n const _normalized = util.cached(() => normalizeDef(def));\n util.defineLazy(inst._zod, \"propValues\", () => {\n const shape = def.shape;\n const propValues = {};\n for (const key in shape) {\n const field = shape[key]._zod;\n if (field.values) {\n propValues[key] ?? (propValues[key] = new Set());\n for (const v of field.values)\n propValues[key].add(v);\n }\n }\n return propValues;\n });\n const isObject = util.isObject;\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 payload.value = {};\n const proms = [];\n const shape = value.shape;\n for (const key of value.keys) {\n const el = shape[key];\n const isOptionalOut = el._zod.optout === \"optional\";\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, isOptionalOut)));\n }\n else {\n handlePropertyResult(r, payload, key, input, isOptionalOut);\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);\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 generateFastpass = (shape) => {\n const doc = new Doc([\"shape\", \"payload\", \"ctx\"]);\n const normalized = _normalized.value;\n const parseStr = (key) => {\n const k = util.esc(key);\n return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;\n };\n doc.write(`const input = payload.value;`);\n const ids = Object.create(null);\n let counter = 0;\n for (const key of normalized.keys) {\n ids[key] = `key_${counter++}`;\n }\n // A: preserve key order {\n doc.write(`const newResult = {};`);\n for (const key of normalized.keys) {\n const id = ids[key];\n const k = util.esc(key);\n const schema = shape[key];\n const isOptionalOut = schema?._zod?.optout === \"optional\";\n doc.write(`const ${id} = ${parseStr(key)};`);\n if (isOptionalOut) {\n // For optional-out schemas, ignore errors on absent keys\n doc.write(`\n if (${id}.issues.length) {\n if (${k} in input) {\n payload.issues = payload.issues.concat(${id}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${k}, ...iss.path] : [${k}]\n })));\n }\n }\n \n if (${id}.value === undefined) {\n if (${k} in input) {\n newResult[${k}] = undefined;\n }\n } else {\n newResult[${k}] = ${id}.value;\n }\n \n `);\n }\n else {\n doc.write(`\n if (${id}.issues.length) {\n payload.issues = payload.issues.concat(${id}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${k}, ...iss.path] : [${k}]\n })));\n }\n \n if (${id}.value === undefined) {\n if (${k} in input) {\n newResult[${k}] = undefined;\n }\n } else {\n newResult[${k}] = ${id}.value;\n }\n \n `);\n }\n }\n doc.write(`payload.value = newResult;`);\n doc.write(`return payload;`);\n const fn = doc.compile();\n return (payload, ctx) => fn(shape, payload, ctx);\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);\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.defineLazy(inst._zod, \"optin\", () => def.options.some((o) => o._zod.optin === \"optional\") ? \"optional\" : undefined);\n util.defineLazy(inst._zod, \"optout\", () => def.options.some((o) => o._zod.optout === \"optional\") ? \"optional\" : undefined);\n util.defineLazy(inst._zod, \"values\", () => {\n if (def.options.every((o) => o._zod.values)) {\n return new Set(def.options.flatMap((option) => Array.from(option._zod.values)));\n }\n return undefined;\n });\n util.defineLazy(inst._zod, \"pattern\", () => {\n if (def.options.every((o) => o._zod.pattern)) {\n const patterns = 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 single = def.options.length === 1;\n const first = def.options[0]._zod.run;\n inst._zod.parse = (payload, ctx) => {\n if (single) {\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 successes = results.filter((r) => r.issues.length === 0);\n if (successes.length === 1) {\n final.value = successes[0].value;\n return final;\n }\n if (successes.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 });\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 single = def.options.length === 1;\n const first = def.options[0]._zod.run;\n inst._zod.parse = (payload, ctx) => {\n if (single) {\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});\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.defineLazy(inst._zod, \"propValues\", () => {\n const propValues = {};\n for (const option of 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 \"${def.options.indexOf(option)}\"`);\n for (const [k, v] of Object.entries(pv)) {\n if (!propValues[k])\n propValues[k] = new Set();\n for (const val of v) {\n propValues[k].add(val);\n }\n }\n }\n return propValues;\n });\n const disc = util.cached(() => {\n const opts = def.options;\n const map = new Map();\n for (const o of opts) {\n const values = o._zod.propValues?.[def.discriminator];\n if (!values || values.size === 0)\n throw new Error(`Invalid discriminated union option at index \"${def.options.indexOf(o)}\"`);\n for (const v of values) {\n if (map.has(v)) {\n throw new Error(`Duplicate discriminator value \"${String(v)}\"`);\n }\n map.set(v, o);\n }\n }\n return map;\n });\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 opt = disc.value.get(input?.[def.discriminator]);\n if (opt) {\n return opt._zod.run(payload, ctx);\n }\n if (def.unionFallback) {\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 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});\nfunction 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 for (const key of sharedKeys) {\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) report each key as unrecognized\n const unrecKeys = new Map();\n let unrecIssue;\n for (const iss of left.issues) {\n if (iss.code === \"unrecognized_keys\") {\n unrecIssue ?? (unrecIssue = iss);\n for (const k of iss.keys) {\n if (!unrecKeys.has(k))\n unrecKeys.set(k, {});\n unrecKeys.get(k).l = true;\n }\n }\n else {\n result.issues.push(iss);\n }\n }\n for (const iss of right.issues) {\n if (iss.code === \"unrecognized_keys\") {\n for (const k of iss.keys) {\n if (!unrecKeys.has(k))\n unrecKeys.set(k, {});\n unrecKeys.get(k).r = true;\n }\n }\n else {\n result.issues.push(iss);\n }\n }\n // Report only keys unrecognized by BOTH sides\n const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k);\n if (bothKeys.length && unrecIssue) {\n result.issues.push({ ...unrecIssue, keys: bothKeys });\n }\n if (util.aborted(result))\n return result;\n const merged = mergeValues(left.value, right.value);\n if (!merged.valid) {\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 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 = [];\n const proms = [];\n const reversedIndex = [...items].reverse().findIndex((item) => item._zod.optin !== \"optional\");\n const optStart = reversedIndex === -1 ? 0 : items.length - reversedIndex;\n if (!def.rest) {\n const tooBig = input.length > items.length;\n const tooSmall = input.length < optStart - 1;\n if (tooBig || tooSmall) {\n payload.issues.push({\n ...(tooBig\n ? { code: \"too_big\", maximum: items.length, inclusive: true }\n : { code: \"too_small\", minimum: items.length }),\n input,\n inst,\n origin: \"array\",\n });\n return payload;\n }\n }\n let i = -1;\n for (const item of items) {\n i++;\n if (i >= input.length)\n if (i >= optStart)\n continue;\n const result = item._zod.run({\n value: input[i],\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => handleTupleResult(result, payload, i)));\n }\n else {\n handleTupleResult(result, payload, i);\n }\n }\n if (def.rest) {\n const rest = input.slice(items.length);\n for (const el of rest) {\n i++;\n const result = def.rest._zod.run({\n value: el,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => handleTupleResult(result, payload, i)));\n }\n else {\n handleTupleResult(result, payload, i);\n }\n }\n }\n if (proms.length)\n return Promise.all(proms).then(() => payload);\n return payload;\n };\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}\nexport const $ZodRecord = /*@__PURE__*/ core.$constructor(\"$ZodRecord\", (inst, def) => {\n $ZodType.init(inst, def);\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 const proms = [];\n const values = def.keyType._zod.values;\n if (values) {\n payload.value = {};\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 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[key] = result.value;\n }));\n }\n else {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[key] = result.value;\n }\n }\n }\n let unrecognized;\n for (const key in input) {\n if (!recordKeys.has(key)) {\n unrecognized = unrecognized ?? [];\n unrecognized.push(key);\n }\n }\n if (unrecognized && unrecognized.length > 0) {\n payload.issues.push({\n code: \"unrecognized_keys\",\n input,\n inst,\n keys: unrecognized,\n });\n }\n }\n else {\n payload.value = {};\n for (const key of Reflect.ownKeys(input)) {\n if (key === \"__proto__\")\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)\n // 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 {\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 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[keyResult.value] = result.value;\n }));\n }\n else {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[keyResult.value] = result.value;\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 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 = new Map();\n for (const [key, value] of input) {\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});\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 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 = new Set();\n for (const item of input) {\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});\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 inst._zod.pattern = new RegExp(`^(${values\n .filter((k) => util.propertyKeyTypes.has(typeof k))\n .map((o) => (typeof o === \"string\" ? util.escapeRegex(o) : o.toString()))\n .join(\"|\")})$`);\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 if (def.values.length === 0) {\n throw new Error(\"Cannot create literal schema with no valid values\");\n }\n const values = new Set(def.values);\n inst._zod.values = values;\n inst._zod.pattern = new RegExp(`^(${def.values\n .map((o) => (typeof o === \"string\" ? util.escapeRegex(o) : o ? util.escapeRegex(o.toString()) : String(o)))\n .join(\"|\")})$`);\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.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(result, input) {\n if (result.issues.length && input === undefined) {\n return { issues: [], value: undefined };\n }\n return result;\n}\nexport const $ZodOptional = /*@__PURE__*/ core.$constructor(\"$ZodOptional\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.optin = \"optional\";\n inst._zod.optout = \"optional\";\n util.defineLazy(inst._zod, \"values\", () => {\n return def.innerType._zod.values ? new Set([...def.innerType._zod.values, undefined]) : undefined;\n });\n util.defineLazy(inst._zod, \"pattern\", () => {\n const pattern = def.innerType._zod.pattern;\n return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)})?$`) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n if (def.innerType._zod.optin === \"optional\") {\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise)\n return result.then((r) => handleOptionalResult(r, payload.value));\n return handleOptionalResult(result, payload.value);\n }\n if (payload.value === undefined) {\n return payload;\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.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n util.defineLazy(inst._zod, \"pattern\", () => 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.defineLazy(inst._zod, \"optin\", () => def.innerType._zod.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.innerType._zod.optout);\n util.defineLazy(inst._zod, \"pattern\", () => {\n const pattern = def.innerType._zod.pattern;\n return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)}|null)$`) : undefined;\n });\n util.defineLazy(inst._zod, \"values\", () => {\n return def.innerType._zod.values ? new Set([...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 = \"optional\";\n util.defineLazy(inst._zod, \"values\", () => 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 = \"optional\";\n util.defineLazy(inst._zod, \"values\", () => 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.defineLazy(inst._zod, \"values\", () => {\n const v = 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});\nexport const $ZodCatch = /*@__PURE__*/ core.$constructor(\"$ZodCatch\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"optin\", () => def.innerType._zod.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.innerType._zod.optout);\n util.defineLazy(inst._zod, \"values\", () => 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(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => {\n payload.value = result.value;\n if (result.issues.length) {\n payload.value = def.catchValue({\n ...payload,\n error: {\n issues: result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n },\n input: payload.value,\n });\n payload.issues = [];\n }\n return payload;\n });\n }\n payload.value = result.value;\n if (result.issues.length) {\n payload.value = def.catchValue({\n ...payload,\n error: {\n issues: result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n },\n input: payload.value,\n });\n payload.issues = [];\n }\n return payload;\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.defineLazy(inst._zod, \"values\", () => def.in._zod.values);\n util.defineLazy(inst._zod, \"optin\", () => def.in._zod.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.out._zod.optout);\n util.defineLazy(inst._zod, \"propValues\", () => 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 if (left.issues.length) {\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.defineLazy(inst._zod, \"values\", () => def.in._zod.values);\n util.defineLazy(inst._zod, \"optin\", () => def.in._zod.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.out._zod.optout);\n util.defineLazy(inst._zod, \"propValues\", () => 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 $ZodReadonly = /*@__PURE__*/ core.$constructor(\"$ZodReadonly\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"propValues\", () => def.innerType._zod.propValues);\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n util.defineLazy(inst._zod, \"optin\", () => def.innerType?._zod?.optin);\n util.defineLazy(inst._zod, \"optout\", () => 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 payload.value = Object.freeze(payload.value);\n return payload;\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 if (!part._zod.pattern) {\n // if (!source)\n throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`);\n }\n const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern;\n if (!source)\n throw new Error(`Invalid template literal part: ${part._zod.traits}`);\n const start = source.startsWith(\"^\") ? 1 : 0;\n const end = source.endsWith(\"$\") ? source.length - 1 : source.length;\n regexParts.push(source.slice(start, end));\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 inst._def = 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 return 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 };\n };\n inst.implementAsync = (func) => {\n if (typeof func !== \"function\") {\n throw new Error(\"implementAsync() must be called with a function\");\n }\n return 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 };\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 // let _innerType!: any;\n // util.defineLazy(def, \"getter\", () => {\n // if (!_innerType) {\n // _innerType = def.getter();\n // }\n // return () => _innerType;\n // });\n util.defineLazy(inst._zod, \"innerType\", () => def.getter());\n util.defineLazy(inst._zod, \"pattern\", () => inst._zod.innerType?._zod?.pattern);\n util.defineLazy(inst._zod, \"propValues\", () => inst._zod.innerType?._zod?.propValues);\n util.defineLazy(inst._zod, \"optin\", () => inst._zod.innerType?._zod?.optin ?? undefined);\n util.defineLazy(inst._zod, \"optout\", () => inst._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 = Symbol(\"ZodOutput\");\nexport const $input = 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\";\n// @__NO_SIDE_EFFECTS__\nexport function _string(Class, params) {\n return new Class({\n type: \"string\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedString(Class, params) {\n return new Class({\n type: \"string\",\n coerce: true,\n ...util.normalizeParams(params),\n });\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// @__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 _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({\n type: \"number\",\n checks: [],\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedNumber(Class, params) {\n return new Class({\n type: \"number\",\n coerce: true,\n checks: [],\n ...util.normalizeParams(params),\n });\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 _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,\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 : () => 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) {\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 _issue.input ?? (_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 });\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 return codec;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _stringFormat(Class, format, fnOrRegex, _params = {}) {\n const params = util.normalizeParams(_params);\n const def = {\n ...util.normalizeParams(_params),\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\";\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 cycles: params?.cycles ?? \"ref\",\n reused: params?.reused ?? \"inline\",\n external: params?.external ?? undefined,\n };\n}\nexport function process(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 // 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 process(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 Object.assign(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\" && result.schema._prefault)\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}\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 // 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\n // defId will be empty if the ref points to an external schema (or #)\n const makeURI = (entry) => {\n // comparing the seen objects because sometimes\n // multiple schemas map to the same seen object.\n // 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}/${id}` };\n }\n if (entry[1] === root) {\n return { ref: \"#\" };\n }\n // self-contained schema\n const uriPrefix = `#`;\n const defUriPrefix = `${uriPrefix}/${defsSegment}/`;\n const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`;\n return { defId, ref: defUriPrefix + defId };\n };\n // stored cached version in `def` property\n // 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\n // 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 // biome-ignore lint:\n continue;\n }\n }\n }\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 Object.assign(schema, refSchema);\n }\n // restore child's own properties (child wins)\n Object.assign(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\n // This handles cases like: readonly().meta({id}).describe()\n // 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 for (const entry of [...ctx.seen.entries()].reverse()) {\n flattenRef(entry[0]);\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 Object.assign(result, root.def ?? root.schema);\n // build defs object\n const defs = ctx.external?.defs ?? {};\n for (const entry of ctx.seen.entries()) {\n const seen = entry[1];\n if (seen.def && seen.defId) {\n defs[seen.defId] = seen.def;\n }\n }\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\n // each call to finalize() is functionally independent\n // 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 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 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 process(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 process(schema, ctx);\n extractDefs(ctx, schema);\n return finalize(ctx, schema);\n};\n","import { extractDefs, finalize, initializeContext, process, } from \"./to-json-schema.js\";\nimport { getEnumValues } from \"./util.js\";\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 ====================\nexport const stringProcessor = (schema, ctx, _json, _params) => {\n const json = _json;\n json.type = \"string\";\n const { minimum, maximum, format, patterns, contentEncoding } = schema._zod\n .bag;\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 // JSON Schema format: \"time\" requires a full time with offset or Z\n // z.iso.time() does not include timezone information, so format: \"time\" should never be used\n if (format === \"time\") {\n delete json.format;\n }\n }\n if (contentEncoding)\n json.contentEncoding = contentEncoding;\n if (patterns && patterns.size > 0) {\n const regexes = [...patterns];\n if (regexes.length === 1)\n json.pattern = regexes[0].source;\n else if (regexes.length > 1) {\n json.allOf = [\n ...regexes.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, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag;\n if (typeof format === \"string\" && format.includes(\"int\"))\n json.type = \"integer\";\n else\n json.type = \"number\";\n if (typeof exclusiveMinimum === \"number\") {\n if (ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\") {\n json.minimum = exclusiveMinimum;\n json.exclusiveMinimum = true;\n }\n else {\n json.exclusiveMinimum = exclusiveMinimum;\n }\n }\n if (typeof minimum === \"number\") {\n json.minimum = minimum;\n if (typeof exclusiveMinimum === \"number\" && ctx.target !== \"draft-04\") {\n if (exclusiveMinimum >= minimum)\n delete json.minimum;\n else\n delete json.exclusiveMinimum;\n }\n }\n if (typeof exclusiveMaximum === \"number\") {\n if (ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\") {\n json.maximum = exclusiveMaximum;\n json.exclusiveMaximum = true;\n }\n else {\n json.exclusiveMaximum = exclusiveMaximum;\n }\n }\n if (typeof maximum === \"number\") {\n json.maximum = maximum;\n if (typeof exclusiveMaximum === \"number\" && ctx.target !== \"draft-04\") {\n if (exclusiveMaximum <= maximum)\n delete json.maximum;\n else\n delete json.exclusiveMaximum;\n }\n }\n if (typeof multipleOf === \"number\")\n json.multipleOf = multipleOf;\n};\nexport const booleanProcessor = (_schema, _ctx, json, _params) => {\n json.type = \"boolean\";\n};\nexport const bigintProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"BigInt cannot be represented in JSON Schema\");\n }\n};\nexport const symbolProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Symbols cannot be represented in JSON Schema\");\n }\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 if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Undefined cannot be represented in JSON Schema\");\n }\n};\nexport const voidProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Void cannot be represented in JSON Schema\");\n }\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 if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Date cannot be represented in JSON Schema\");\n }\n};\nexport const enumProcessor = (schema, _ctx, json, _params) => {\n const def = schema._zod.def;\n const values = getEnumValues(def.entries);\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 const vals = [];\n for (const val of def.values) {\n if (val === undefined) {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Literal `undefined` cannot be represented in JSON Schema\");\n }\n else {\n // do not add to vals\n }\n }\n else if (typeof val === \"bigint\") {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"BigInt literals cannot be represented in JSON Schema\");\n }\n else {\n vals.push(Number(val));\n }\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 if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"NaN cannot be represented in JSON Schema\");\n }\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 const file = {\n type: \"string\",\n format: \"binary\",\n contentEncoding: \"binary\",\n };\n const { minimum, maximum, mime } = schema._zod.bag;\n if (minimum !== undefined)\n file.minLength = minimum;\n if (maximum !== undefined)\n file.maxLength = maximum;\n if (mime) {\n if (mime.length === 1) {\n file.contentMediaType = mime[0];\n Object.assign(_json, file);\n }\n else {\n Object.assign(_json, file); // shared props at root\n _json.anyOf = mime.map((m) => ({ contentMediaType: m })); // only contentMediaType differs\n }\n }\n else {\n Object.assign(_json, file);\n }\n};\nexport const successProcessor = (_schema, _ctx, json, _params) => {\n json.type = \"boolean\";\n};\nexport const customProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Custom types cannot be represented in JSON Schema\");\n }\n};\nexport const functionProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Function types cannot be represented in JSON Schema\");\n }\n};\nexport const transformProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Transforms cannot be represented in JSON Schema\");\n }\n};\nexport const mapProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Map cannot be represented in JSON Schema\");\n }\n};\nexport const setProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Set cannot be represented in JSON Schema\");\n }\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 } = schema._zod.bag;\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 = process(def.element, ctx, { ...params, path: [...params.path, \"items\"] });\n};\nexport const objectProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n json.type = \"object\";\n json.properties = {};\n const shape = def.shape;\n for (const key in shape) {\n json.properties[key] = process(shape[key], ctx, {\n ...params,\n path: [...params.path, \"properties\", key],\n });\n }\n // required keys\n const allKeys = new Set(Object.keys(shape));\n const requiredKeys = new Set([...allKeys].filter((key) => {\n const v = def.shape[key]._zod;\n if (ctx.io === \"input\") {\n return v.optin === undefined;\n }\n else {\n return v.optout === undefined;\n }\n }));\n if (requiredKeys.size > 0) {\n json.required = Array.from(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 = process(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)\n // This includes both z.xor() and discriminated unions\n const isExclusive = def.inclusive === false;\n const options = def.options.map((x, i) => process(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 = process(def.left, ctx, {\n ...params,\n path: [...params.path, \"allOf\", 0],\n });\n const b = process(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};\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) => process(x, ctx, {\n ...params,\n path: [...params.path, prefixPath, i],\n }));\n const rest = def.rest\n ? process(def.rest, ctx, {\n ...params,\n path: [...params.path, restPath, ...(ctx.target === \"openapi-3.0\" ? [def.items.length] : [])],\n })\n : null;\n if (ctx.target === \"draft-2020-12\") {\n json.prefixItems = prefixItems;\n if (rest) {\n json.items = rest;\n }\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 json.minItems = prefixItems.length;\n if (!rest) {\n json.maxItems = prefixItems.length;\n }\n }\n else {\n json.items = prefixItems;\n if (rest) {\n json.additionalItems = rest;\n }\n }\n // length\n const { minimum, maximum } = schema._zod.bag;\n if (typeof minimum === \"number\")\n json.minItems = minimum;\n if (typeof maximum === \"number\")\n json.maxItems = maximum;\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\n // This correctly represents \"only validate keys matching the pattern\" semantics\n // and composes well with allOf (intersections)\n const keyType = def.keyType;\n const keyBag = keyType._zod.bag;\n const patterns = keyBag?.patterns;\n if (def.mode === \"loose\" && patterns && patterns.size > 0) {\n // Use patternProperties for looseRecord with regex patterns\n const valueSchema = process(def.valueType, ctx, {\n ...params,\n path: [...params.path, \"patternProperties\", \"*\"],\n });\n json.patternProperties = {};\n for (const pattern of patterns) {\n json.patternProperties[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 = process(def.keyType, ctx, {\n ...params,\n path: [...params.path, \"propertyNames\"],\n });\n }\n json.additionalProperties = process(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 if (keyValues) {\n const validKeyValues = [...keyValues].filter((v) => typeof v === \"string\" || typeof v === \"number\");\n if (validKeyValues.length > 0) {\n json.required = validKeyValues;\n }\n }\n};\nexport const nullableProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n const inner = process(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 process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n};\nexport const defaultProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n json.default = JSON.parse(JSON.stringify(def.defaultValue));\n};\nexport const prefaultProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n if (ctx.io === \"input\")\n json._prefault = JSON.parse(JSON.stringify(def.defaultValue));\n};\nexport const catchProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n process(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 throw new Error(\"Dynamic catch values are not supported in JSON Schema\");\n }\n json.default = catchValue;\n};\nexport const pipeProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n const innerType = ctx.io === \"input\" ? (def.in._zod.def.type === \"transform\" ? def.out : def.in) : def.out;\n process(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 process(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 process(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 process(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 process(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 process(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 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 process(input, ctx);\n extractDefs(ctx, input);\n return finalize(ctx, input);\n}\n","import type {\n CredentialRequirement,\n CredentialSessionService,\n NodeConfigBase,\n NodeExecutionContext,\n NodeId,\n} from \"@codemation/core\";\n\nimport { CredentialResolverFactory } from \"@codemation/core/bootstrap\";\n\n/**\n * Builds a {@link NodeExecutionContext} whose identity for credential binding and `getCredential`\n * is a **connection-owned** workflow node id (`ConnectionNodeIdFactory` in `@codemation/core`),\n * not the executing parent node. Use for LLM slots, tool slots, or any connection-scoped owner.\n */\nexport class ConnectionCredentialExecutionContextFactory {\n private readonly credentialResolverFactory: CredentialResolverFactory;\n\n constructor(credentialSessions: CredentialSessionService) {\n this.credentialResolverFactory = new CredentialResolverFactory(credentialSessions);\n }\n\n forConnectionNode<TConfig extends NodeConfigBase>(\n ctx: NodeExecutionContext<TConfig>,\n args: Readonly<{\n connectionNodeId: NodeId;\n getCredentialRequirements: () => ReadonlyArray<CredentialRequirement>;\n }>,\n ): NodeExecutionContext<TConfig> {\n const stubConfig = { getCredentialRequirements: args.getCredentialRequirements } as NodeConfigBase;\n const getCredential = this.credentialResolverFactory.create(ctx.workflowId, args.connectionNodeId, stubConfig);\n return {\n ...ctx,\n nodeId: args.connectionNodeId,\n getCredential,\n };\n }\n}\n","import type { CredentialSessionService, Item, Items, NodeExecutionContext, ZodSchemaAny } from \"@codemation/core\";\nimport { injectable } from \"@codemation/core\";\n\nimport { isInteropZodSchema } from \"@langchain/core/utils/types\";\nimport { toJsonSchema } from \"@langchain/core/utils/json_schema\";\nimport { DynamicStructuredTool } from \"@langchain/core/tools\";\nimport { toJSONSchema } from \"zod/v4/core\";\n\nimport { ConnectionCredentialExecutionContextFactory } from \"./ConnectionCredentialExecutionContextFactory\";\nimport type { ResolvedTool } from \"./aiAgentSupport.types\";\n\n/**\n * LangChain adapters and credential context wiring for {@link AIAgentNode}.\n * Lives in a `*Factory.ts` composition-root module so construction stays explicit and testable.\n */\n@injectable()\nexport class AIAgentExecutionHelpersFactory {\n createConnectionCredentialExecutionContextFactory(\n credentialSessions: CredentialSessionService,\n ): ConnectionCredentialExecutionContextFactory {\n return new ConnectionCredentialExecutionContextFactory(credentialSessions);\n }\n\n createDynamicStructuredTool(\n entry: ResolvedTool,\n toolCredentialContext: NodeExecutionContext<any>,\n item: Item,\n itemIndex: number,\n items: Items,\n ): DynamicStructuredTool {\n if (entry.runtime.inputSchema == null) {\n throw new Error(\n `Cannot create LangChain tool \"${entry.config.name}\": missing inputSchema (broken tool runtime resolution).`,\n );\n }\n const schemaForOpenAi = this.createJsonSchemaRecord(entry.runtime.inputSchema, {\n schemaName: entry.config.name,\n requireObjectRoot: true,\n });\n return new DynamicStructuredTool({\n name: entry.config.name,\n description: entry.config.description ?? entry.runtime.defaultDescription,\n schema: schemaForOpenAi as unknown as ZodSchemaAny,\n func: async (input) => {\n const result = await entry.runtime.execute({\n config: entry.config,\n input,\n ctx: toolCredentialContext,\n item,\n itemIndex,\n items,\n });\n return JSON.stringify(result);\n },\n });\n }\n\n /**\n * Produces a plain JSON Schema object for OpenAI tool parameters and LangChain tool invocation:\n * - **Zod** → `toJSONSchema(..., { target: \"draft-07\" })` so shapes match what `@cfworker/json-schema`\n * expects (`required` must be an array; draft 2020-12 output can break validation).\n * - Otherwise LangChain `toJsonSchema` (Standard Schema + JSON passthrough); if the result is still Zod\n * (duplicate `zod` copies), fall back to Zod `toJSONSchema` with draft-07.\n * - Strip root `$schema` for OpenAI; normalize invalid `required` keywords for cfworker; ensure `properties`.\n */\n createJsonSchemaRecord(\n inputSchema: ZodSchemaAny,\n options: Readonly<{\n schemaName: string;\n requireObjectRoot: boolean;\n }>,\n ): Record<string, unknown> {\n const draft07Params = { target: \"draft-07\" as const };\n let converted: unknown;\n if (isInteropZodSchema(inputSchema)) {\n converted = toJSONSchema(inputSchema as unknown as Parameters<typeof toJSONSchema>[0], draft07Params);\n } else {\n converted = toJsonSchema(inputSchema);\n if (isInteropZodSchema(converted)) {\n converted = toJSONSchema(inputSchema as unknown as Parameters<typeof toJSONSchema>[0], draft07Params);\n }\n }\n const record = converted as Record<string, unknown>;\n const { $schema: _draftSchemaOmitted, ...rest } = record;\n if (options.requireObjectRoot && rest.type !== \"object\") {\n throw new Error(\n `Cannot create LangChain tool \"${options.schemaName}\": tool input schema must be a JSON Schema object type (got type=${String(rest.type)}).`,\n );\n }\n if (\n options.requireObjectRoot &&\n rest.properties !== undefined &&\n (typeof rest.properties !== \"object\" || Array.isArray(rest.properties))\n ) {\n throw new Error(\n `Cannot create LangChain tool \"${options.schemaName}\": tool input schema \"properties\" must be an object (got ${JSON.stringify(rest.properties)}).`,\n );\n }\n if (options.requireObjectRoot && rest.properties === undefined) {\n rest.properties = {};\n }\n this.sanitizeJsonSchemaRequiredKeywordsForCfworker(rest);\n return rest;\n }\n\n /**\n * `@cfworker/json-schema` iterates `schema.required` with `for...of`; it must be a string array or absent.\n */\n private sanitizeJsonSchemaRequiredKeywordsForCfworker(node: unknown): void {\n if (!node || typeof node !== \"object\" || Array.isArray(node)) {\n return;\n }\n const o = node as Record<string, unknown>;\n const req = o.required;\n if (req !== undefined && !Array.isArray(req)) {\n delete o.required;\n } else if (Array.isArray(req)) {\n const strings = req.filter((x): x is string => typeof x === \"string\");\n if (strings.length === 0) {\n delete o.required;\n } else if (strings.length !== req.length) {\n o.required = strings;\n }\n }\n const props = o.properties;\n if (props && typeof props === \"object\" && !Array.isArray(props)) {\n for (const v of Object.values(props)) {\n this.sanitizeJsonSchemaRequiredKeywordsForCfworker(v);\n }\n }\n for (const key of [\"allOf\", \"anyOf\", \"oneOf\"] as const) {\n const branch = o[key];\n if (Array.isArray(branch)) {\n for (const sub of branch) {\n this.sanitizeJsonSchemaRequiredKeywordsForCfworker(sub);\n }\n }\n }\n if (o.if) this.sanitizeJsonSchemaRequiredKeywordsForCfworker(o.if);\n if (o.then) this.sanitizeJsonSchemaRequiredKeywordsForCfworker(o.then);\n if (o.else) this.sanitizeJsonSchemaRequiredKeywordsForCfworker(o.else);\n if (o.not) this.sanitizeJsonSchemaRequiredKeywordsForCfworker(o.not);\n if (o.items) this.sanitizeJsonSchemaRequiredKeywordsForCfworker(o.items);\n if (Array.isArray(o.prefixItems)) {\n for (const sub of o.prefixItems) {\n this.sanitizeJsonSchemaRequiredKeywordsForCfworker(sub);\n }\n }\n }\n}\n","import type { AgentMessageDto, ZodSchemaAny } from \"@codemation/core\";\nimport { inject, injectable } from \"@codemation/core\";\n\nimport { AIAgentExecutionHelpersFactory } from \"./AIAgentExecutionHelpersFactory\";\n\n@injectable()\nexport class AgentStructuredOutputRepairPromptFactory {\n private static readonly maxSchemaLength = 8000;\n private static readonly maxInvalidContentLength = 4000;\n private static readonly maxValidationErrorLength = 4000;\n\n constructor(\n @inject(AIAgentExecutionHelpersFactory)\n private readonly executionHelpers: AIAgentExecutionHelpersFactory,\n ) {}\n\n create(\n args: Readonly<{\n schema: ZodSchemaAny;\n invalidContent: string;\n validationError: string;\n }>,\n ): ReadonlyArray<AgentMessageDto> {\n return [\n {\n role: \"system\",\n content:\n \"Return only JSON that matches the required schema exactly. Do not include markdown fences, commentary, or prose.\",\n },\n {\n role: \"user\",\n content: JSON.stringify({\n requiredSchema: this.truncate(\n JSON.stringify(\n this.executionHelpers.createJsonSchemaRecord(args.schema, {\n schemaName: \"agent_output\",\n requireObjectRoot: false,\n }),\n ),\n AgentStructuredOutputRepairPromptFactory.maxSchemaLength,\n ),\n invalidModelOutput: this.truncate(\n args.invalidContent,\n AgentStructuredOutputRepairPromptFactory.maxInvalidContentLength,\n ),\n validationError: this.truncate(\n args.validationError,\n AgentStructuredOutputRepairPromptFactory.maxValidationErrorLength,\n ),\n }),\n },\n ];\n }\n\n private truncate(value: string, maxLength: number): string {\n if (value.length <= maxLength) {\n return value;\n }\n return `${value.slice(0, maxLength)}...(truncated)`;\n }\n}\n","import * as core from \"../core/index.js\";\nimport { $ZodError } from \"../core/index.js\";\nimport * as util from \"../core/util.js\";\nconst initializer = (inst, issues) => {\n $ZodError.init(inst, issues);\n inst.name = \"ZodError\";\n Object.defineProperties(inst, {\n format: {\n value: (mapper) => core.formatError(inst, mapper),\n // enumerable: false,\n },\n flatten: {\n value: (mapper) => core.flattenError(inst, mapper),\n // enumerable: false,\n },\n addIssue: {\n value: (issue) => {\n inst.issues.push(issue);\n inst.message = JSON.stringify(inst.issues, util.jsonStringifyReplacer, 2);\n },\n // enumerable: false,\n },\n addIssues: {\n value: (issues) => {\n inst.issues.push(...issues);\n inst.message = JSON.stringify(inst.issues, util.jsonStringifyReplacer, 2);\n },\n // enumerable: false,\n },\n isEmpty: {\n get() {\n return inst.issues.length === 0;\n },\n // enumerable: false,\n },\n });\n // Object.defineProperty(inst, \"isEmpty\", {\n // get() {\n // return inst.issues.length === 0;\n // },\n // });\n};\nexport const ZodError = core.$constructor(\"ZodError\", initializer);\nexport const ZodRealError = core.$constructor(\"ZodError\", initializer, {\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);\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 { createStandardJSONSchemaMethod, createToJSONSchemaMethod } from \"../core/to-json-schema.js\";\nimport * as checks from \"./checks.js\";\nimport * as iso from \"./iso.js\";\nimport * as parse from \"./parse.js\";\nexport const ZodType = /*@__PURE__*/ core.$constructor(\"ZodType\", (inst, def) => {\n core.$ZodType.init(inst, def);\n Object.assign(inst[\"~standard\"], {\n jsonSchema: {\n input: createStandardJSONSchemaMethod(inst, \"input\"),\n output: createStandardJSONSchemaMethod(inst, \"output\"),\n },\n });\n inst.toJSONSchema = createToJSONSchemaMethod(inst, {});\n inst.def = def;\n inst.type = def.type;\n Object.defineProperty(inst, \"_def\", { value: def });\n // base methods\n inst.check = (...checks) => {\n return inst.clone(util.mergeDefs(def, {\n checks: [\n ...(def.checks ?? []),\n ...checks.map((ch) => typeof ch === \"function\" ? { _zod: { check: ch, def: { check: \"custom\" }, onattach: [] } } : ch),\n ],\n }), {\n parent: true,\n });\n };\n inst.with = inst.check;\n inst.clone = (def, params) => core.clone(inst, def, params);\n inst.brand = () => inst;\n inst.register = ((reg, meta) => {\n reg.add(inst, meta);\n return inst;\n });\n // parsing\n inst.parse = (data, params) => parse.parse(inst, data, params, { callee: inst.parse });\n inst.safeParse = (data, params) => parse.safeParse(inst, data, params);\n inst.parseAsync = async (data, params) => parse.parseAsync(inst, data, params, { callee: inst.parseAsync });\n inst.safeParseAsync = async (data, params) => parse.safeParseAsync(inst, data, params);\n inst.spa = inst.safeParseAsync;\n // encoding/decoding\n inst.encode = (data, params) => parse.encode(inst, data, params);\n inst.decode = (data, params) => parse.decode(inst, data, params);\n inst.encodeAsync = async (data, params) => parse.encodeAsync(inst, data, params);\n inst.decodeAsync = async (data, params) => parse.decodeAsync(inst, data, params);\n inst.safeEncode = (data, params) => parse.safeEncode(inst, data, params);\n inst.safeDecode = (data, params) => parse.safeDecode(inst, data, params);\n inst.safeEncodeAsync = async (data, params) => parse.safeEncodeAsync(inst, data, params);\n inst.safeDecodeAsync = async (data, params) => parse.safeDecodeAsync(inst, data, params);\n // refinements\n inst.refine = (check, params) => inst.check(refine(check, params));\n inst.superRefine = (refinement) => inst.check(superRefine(refinement));\n inst.overwrite = (fn) => inst.check(checks.overwrite(fn));\n // wrappers\n inst.optional = () => optional(inst);\n inst.exactOptional = () => exactOptional(inst);\n inst.nullable = () => nullable(inst);\n inst.nullish = () => optional(nullable(inst));\n inst.nonoptional = (params) => nonoptional(inst, params);\n inst.array = () => array(inst);\n inst.or = (arg) => union([inst, arg]);\n inst.and = (arg) => intersection(inst, arg);\n inst.transform = (tx) => pipe(inst, transform(tx));\n inst.default = (def) => _default(inst, def);\n inst.prefault = (def) => prefault(inst, def);\n // inst.coalesce = (def, params) => coalesce(inst, def, params);\n inst.catch = (params) => _catch(inst, params);\n inst.pipe = (target) => pipe(inst, target);\n inst.readonly = () => readonly(inst);\n // meta\n inst.describe = (description) => {\n const cl = inst.clone();\n core.globalRegistry.add(cl, { description });\n return cl;\n };\n Object.defineProperty(inst, \"description\", {\n get() {\n return core.globalRegistry.get(inst)?.description;\n },\n configurable: true,\n });\n inst.meta = (...args) => {\n if (args.length === 0) {\n return core.globalRegistry.get(inst);\n }\n const cl = inst.clone();\n core.globalRegistry.add(cl, args[0]);\n return cl;\n };\n // helpers\n inst.isOptional = () => inst.safeParse(undefined).success;\n inst.isNullable = () => inst.safeParse(null).success;\n inst.apply = (fn) => fn(inst);\n return inst;\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 const bag = inst._zod.bag;\n inst.format = bag.format ?? null;\n inst.minLength = bag.minimum ?? null;\n inst.maxLength = bag.maximum ?? null;\n // validations\n inst.regex = (...args) => inst.check(checks.regex(...args));\n inst.includes = (...args) => inst.check(checks.includes(...args));\n inst.startsWith = (...args) => inst.check(checks.startsWith(...args));\n inst.endsWith = (...args) => inst.check(checks.endsWith(...args));\n inst.min = (...args) => inst.check(checks.minLength(...args));\n inst.max = (...args) => inst.check(checks.maxLength(...args));\n inst.length = (...args) => inst.check(checks.length(...args));\n inst.nonempty = (...args) => inst.check(checks.minLength(1, ...args));\n inst.lowercase = (params) => inst.check(checks.lowercase(params));\n inst.uppercase = (params) => inst.check(checks.uppercase(params));\n // transforms\n inst.trim = () => inst.check(checks.trim());\n inst.normalize = (...args) => inst.check(checks.normalize(...args));\n inst.toLowerCase = () => inst.check(checks.toLowerCase());\n inst.toUpperCase = () => inst.check(checks.toUpperCase());\n inst.slugify = () => inst.check(checks.slugify());\n});\nexport const ZodString = /*@__PURE__*/ core.$constructor(\"ZodString\", (inst, def) => {\n core.$ZodString.init(inst, def);\n _ZodString.init(inst, def);\n inst.email = (params) => inst.check(core._email(ZodEmail, params));\n inst.url = (params) => inst.check(core._url(ZodURL, params));\n inst.jwt = (params) => inst.check(core._jwt(ZodJWT, params));\n inst.emoji = (params) => inst.check(core._emoji(ZodEmoji, params));\n inst.guid = (params) => inst.check(core._guid(ZodGUID, params));\n inst.uuid = (params) => inst.check(core._uuid(ZodUUID, params));\n inst.uuidv4 = (params) => inst.check(core._uuidv4(ZodUUID, params));\n inst.uuidv6 = (params) => inst.check(core._uuidv6(ZodUUID, params));\n inst.uuidv7 = (params) => inst.check(core._uuidv7(ZodUUID, params));\n inst.nanoid = (params) => inst.check(core._nanoid(ZodNanoID, params));\n inst.guid = (params) => inst.check(core._guid(ZodGUID, params));\n inst.cuid = (params) => inst.check(core._cuid(ZodCUID, params));\n inst.cuid2 = (params) => inst.check(core._cuid2(ZodCUID2, params));\n inst.ulid = (params) => inst.check(core._ulid(ZodULID, params));\n inst.base64 = (params) => inst.check(core._base64(ZodBase64, params));\n inst.base64url = (params) => inst.check(core._base64url(ZodBase64URL, params));\n inst.xid = (params) => inst.check(core._xid(ZodXID, params));\n inst.ksuid = (params) => inst.check(core._ksuid(ZodKSUID, params));\n inst.ipv4 = (params) => inst.check(core._ipv4(ZodIPv4, params));\n inst.ipv6 = (params) => inst.check(core._ipv6(ZodIPv6, params));\n inst.cidrv4 = (params) => inst.check(core._cidrv4(ZodCIDRv4, params));\n inst.cidrv6 = (params) => inst.check(core._cidrv6(ZodCIDRv6, params));\n inst.e164 = (params) => inst.check(core._e164(ZodE164, params));\n // iso\n inst.datetime = (params) => inst.check(iso.datetime(params));\n inst.date = (params) => inst.check(iso.date(params));\n inst.time = (params) => inst.check(iso.time(params));\n inst.duration = (params) => inst.check(iso.duration(params));\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 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: /^https?$/,\n hostname: core.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}\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});\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 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\", core.regexes.hostname, _params);\n}\nexport function hex(_params) {\n return core._stringFormat(ZodCustomStringFormat, \"hex\", core.regexes.hex, _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.gt = (value, params) => inst.check(checks.gt(value, params));\n inst.gte = (value, params) => inst.check(checks.gte(value, params));\n inst.min = (value, params) => inst.check(checks.gte(value, params));\n inst.lt = (value, params) => inst.check(checks.lt(value, params));\n inst.lte = (value, params) => inst.check(checks.lte(value, params));\n inst.max = (value, params) => inst.check(checks.lte(value, params));\n inst.int = (params) => inst.check(int(params));\n inst.safe = (params) => inst.check(int(params));\n inst.positive = (params) => inst.check(checks.gt(0, params));\n inst.nonnegative = (params) => inst.check(checks.gte(0, params));\n inst.negative = (params) => inst.check(checks.lt(0, params));\n inst.nonpositive = (params) => inst.check(checks.lte(0, params));\n inst.multipleOf = (value, params) => inst.check(checks.multipleOf(value, params));\n inst.step = (value, params) => inst.check(checks.multipleOf(value, params));\n // inst.finite = (params) => inst.check(core.finite(params));\n inst.finite = () => inst;\n const bag = inst._zod.bag;\n inst.minValue =\n Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null;\n inst.maxValue =\n Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null;\n inst.isInt = (bag.format ?? \"\").includes(\"int\") || Number.isSafeInteger(bag.multipleOf ?? 0.5);\n inst.isFinite = true;\n inst.format = bag.format ?? null;\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 inst.gte = (value, params) => inst.check(checks.gte(value, params));\n inst.min = (value, params) => inst.check(checks.gte(value, params));\n inst.gt = (value, params) => inst.check(checks.gt(value, params));\n inst.gte = (value, params) => inst.check(checks.gte(value, params));\n inst.min = (value, params) => inst.check(checks.gte(value, params));\n inst.lt = (value, params) => inst.check(checks.lt(value, params));\n inst.lte = (value, params) => inst.check(checks.lte(value, params));\n inst.max = (value, params) => inst.check(checks.lte(value, params));\n inst.positive = (params) => inst.check(checks.gt(BigInt(0), params));\n inst.negative = (params) => inst.check(checks.lt(BigInt(0), params));\n inst.nonpositive = (params) => inst.check(checks.lte(BigInt(0), params));\n inst.nonnegative = (params) => inst.check(checks.gte(BigInt(0), params));\n inst.multipleOf = (value, params) => inst.check(checks.multipleOf(value, params));\n const bag = inst._zod.bag;\n inst.minValue = bag.minimum ?? null;\n inst.maxValue = bag.maximum ?? null;\n inst.format = bag.format ?? null;\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});\n// int64\nexport function int64(params) {\n return core._int64(ZodBigIntFormat, params);\n}\n// uint64\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 const c = inst._zod.bag;\n inst.minDate = c.minimum ? new Date(c.minimum) : null;\n inst.maxDate = c.maximum ? new Date(c.maximum) : null;\n});\nexport function date(params) {\n return core._date(ZodDate, params);\n}\nexport const ZodArray = /*@__PURE__*/ core.$constructor(\"ZodArray\", (inst, def) => {\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 inst.min = (minLength, params) => inst.check(checks.minLength(minLength, params));\n inst.nonempty = (params) => inst.check(checks.minLength(1, params));\n inst.max = (maxLength, params) => inst.check(checks.maxLength(maxLength, params));\n inst.length = (len, params) => inst.check(checks.length(len, params));\n inst.unwrap = () => inst.element;\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 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.defineLazy(inst, \"shape\", () => {\n return def.shape;\n });\n inst.keyof = () => _enum(Object.keys(inst._zod.def.shape));\n inst.catchall = (catchall) => inst.clone({ ...inst._zod.def, catchall: catchall });\n inst.passthrough = () => inst.clone({ ...inst._zod.def, catchall: unknown() });\n inst.loose = () => inst.clone({ ...inst._zod.def, catchall: unknown() });\n inst.strict = () => inst.clone({ ...inst._zod.def, catchall: never() });\n inst.strip = () => inst.clone({ ...inst._zod.def, catchall: undefined });\n inst.extend = (incoming) => {\n return util.extend(inst, incoming);\n };\n inst.safeExtend = (incoming) => {\n return util.safeExtend(inst, incoming);\n };\n inst.merge = (other) => util.merge(inst, other);\n inst.pick = (mask) => util.pick(inst, mask);\n inst.omit = (mask) => util.omit(inst, mask);\n inst.partial = (...args) => util.partial(ZodOptional, inst, args[0]);\n inst.required = (...args) => util.required(ZodNonOptional, inst, args[0]);\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,\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 core.$ZodTuple.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.tupleProcessor(inst, ctx, json, params);\n inst.rest = (rest) => inst.clone({\n ...inst._zod.def,\n rest: rest,\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 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 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 const k = core.clone(keyType);\n k._zod.values = undefined;\n return new ZodRecord({\n type: \"record\",\n keyType: k,\n valueType: valueType,\n ...util.normalizeParams(params),\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 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 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 inst.options = Object.values(def.entries);\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 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 _issue.input ?? (_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 : () => 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 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) {\n return core._superRefine(fn);\n}\n// Re-export describe and meta from core\nexport const describe = core.describe;\nexport const meta = core.meta;\nfunction _instanceof(cls, params = {}) {\n const inst = new ZodCustom({\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\n// /** @deprecated Use `z.pipe()` and `z.transform()` instead. */\nexport function preprocess(fn, schema) {\n return pipe(transform(fn), schema);\n}\n","import type {\n ChatModelConfig,\n ChatModelStructuredOutputOptions,\n LangChainChatModelLike,\n LangChainStructuredOutputModelLike,\n ZodSchemaAny,\n} from \"@codemation/core\";\nimport { inject, injectable } from \"@codemation/core\";\n\nimport { AIMessage, type BaseMessage } from \"@langchain/core/messages\";\nimport { ZodError } from \"zod\";\n\nimport { OpenAIStructuredOutputMethodFactory } from \"../chatModels/OpenAIStructuredOutputMethodFactory\";\nimport { AgentMessageFactory } from \"./AgentMessageFactory\";\nimport { AgentStructuredOutputRepairPromptFactory } from \"./AgentStructuredOutputRepairPromptFactory\";\n\ninterface ParsedStructuredOutputSuccess<TValue> {\n readonly ok: true;\n readonly value: TValue;\n}\n\ninterface ParsedStructuredOutputFailure {\n readonly ok: false;\n readonly invalidContent: string;\n readonly validationError: string;\n}\n\ntype ParsedStructuredOutputResult<TValue> = ParsedStructuredOutputSuccess<TValue> | ParsedStructuredOutputFailure;\n\n@injectable()\nexport class AgentStructuredOutputRunner {\n private static readonly repairAttemptCount = 2;\n\n constructor(\n @inject(AgentStructuredOutputRepairPromptFactory)\n private readonly repairPromptFactory: AgentStructuredOutputRepairPromptFactory,\n @inject(OpenAIStructuredOutputMethodFactory)\n private readonly openAiStructuredOutputMethodFactory: OpenAIStructuredOutputMethodFactory,\n ) {}\n\n async resolve<TOutput>(\n args: Readonly<{\n model: LangChainChatModelLike;\n chatModelConfig: ChatModelConfig;\n schema: ZodSchemaAny;\n conversation: ReadonlyArray<BaseMessage>;\n rawFinalResponse?: AIMessage;\n agentName: string;\n nodeId: string;\n invokeTextModel: (messages: ReadonlyArray<BaseMessage>) => Promise<AIMessage>;\n invokeStructuredModel: (\n model: LangChainStructuredOutputModelLike,\n messages: ReadonlyArray<BaseMessage>,\n ) => Promise<unknown>;\n }>,\n ): Promise<TOutput> {\n let lastFailure: ParsedStructuredOutputFailure | undefined;\n\n if (args.rawFinalResponse) {\n const directResult = this.tryParseAndValidate<TOutput>(\n AgentMessageFactory.extractContent(args.rawFinalResponse),\n args.schema,\n );\n if (directResult.ok) {\n return directResult.value;\n }\n lastFailure = directResult;\n } else if (!this.supportsNativeStructuredOutput(args.model)) {\n const rawResponse = await args.invokeTextModel(args.conversation);\n const directResult = this.tryParseAndValidate<TOutput>(\n AgentMessageFactory.extractContent(rawResponse),\n args.schema,\n );\n if (directResult.ok) {\n return directResult.value;\n }\n lastFailure = directResult;\n }\n\n try {\n const nativeStructuredModel = this.createStructuredOutputModel(args.model, args.chatModelConfig, args.schema);\n if (nativeStructuredModel) {\n const nativeResult = this.tryValidateStructuredValue<TOutput>(\n await args.invokeStructuredModel(nativeStructuredModel, args.conversation),\n args.schema,\n );\n if (nativeResult.ok) {\n return nativeResult.value;\n }\n lastFailure = nativeResult;\n }\n } catch (error) {\n lastFailure = {\n ok: false,\n invalidContent: \"\",\n validationError: `Native structured output failed: ${this.summarizeError(error)}`,\n };\n }\n\n return await this.retryWithRepairPrompt<TOutput>({\n ...args,\n lastFailure:\n lastFailure ??\n ({\n ok: false,\n invalidContent: \"\",\n validationError: \"Structured output was required but no valid structured response was produced.\",\n } satisfies ParsedStructuredOutputFailure),\n });\n }\n\n private async retryWithRepairPrompt<TOutput>(\n args: Readonly<{\n schema: ZodSchemaAny;\n conversation: ReadonlyArray<BaseMessage>;\n lastFailure: ParsedStructuredOutputFailure;\n agentName: string;\n nodeId: string;\n invokeTextModel: (messages: ReadonlyArray<BaseMessage>) => Promise<AIMessage>;\n }>,\n ): Promise<TOutput> {\n let failure = args.lastFailure;\n for (let attempt = 1; attempt <= AgentStructuredOutputRunner.repairAttemptCount; attempt++) {\n const repairMessages = [\n ...args.conversation,\n ...AgentMessageFactory.createPromptMessages(\n this.repairPromptFactory.create({\n schema: args.schema,\n invalidContent: failure.invalidContent,\n validationError: failure.validationError,\n }),\n ),\n ];\n const repairResponse = await args.invokeTextModel(repairMessages);\n const repairResult = this.tryParseAndValidate<TOutput>(\n AgentMessageFactory.extractContent(repairResponse),\n args.schema,\n );\n if (repairResult.ok) {\n return repairResult.value;\n }\n failure = repairResult;\n }\n throw new Error(\n `Structured output required for AIAgent \"${args.agentName}\" (${args.nodeId}) but validation still failed after ${AgentStructuredOutputRunner.repairAttemptCount} repair attempts: ${failure.validationError}`,\n );\n }\n\n private createStructuredOutputModel(\n model: LangChainChatModelLike,\n chatModelConfig: ChatModelConfig,\n schema: ZodSchemaAny,\n ): LangChainStructuredOutputModelLike | undefined {\n if (!this.supportsNativeStructuredOutput(model)) {\n return undefined;\n }\n const options = this.getStructuredOutputOptions(chatModelConfig);\n return model.withStructuredOutput(schema, options);\n }\n\n private getStructuredOutputOptions(chatModelConfig: ChatModelConfig): ChatModelStructuredOutputOptions | undefined {\n return this.openAiStructuredOutputMethodFactory.create(chatModelConfig) ?? { strict: true };\n }\n\n private supportsNativeStructuredOutput(model: LangChainChatModelLike): model is LangChainChatModelLike & {\n withStructuredOutput: (\n outputSchema: ZodSchemaAny,\n config?: ChatModelStructuredOutputOptions,\n ) => LangChainStructuredOutputModelLike;\n } {\n return typeof model.withStructuredOutput === \"function\";\n }\n\n private tryParseAndValidate<TOutput>(content: string, schema: ZodSchemaAny): ParsedStructuredOutputResult<TOutput> {\n try {\n return this.tryValidateStructuredValue<TOutput>(JSON.parse(content) as unknown, schema, content);\n } catch (error) {\n return {\n ok: false,\n invalidContent: content,\n validationError: `Response was not valid JSON: ${this.summarizeError(error)}`,\n };\n }\n }\n\n private tryValidateStructuredValue<TOutput>(\n value: unknown,\n schema: ZodSchemaAny,\n invalidContent?: string,\n ): ParsedStructuredOutputResult<TOutput> {\n try {\n return {\n ok: true,\n value: schema.parse(value) as TOutput,\n };\n } catch (error) {\n return {\n ok: false,\n invalidContent: invalidContent ?? this.toJson(value),\n validationError: this.summarizeError(error),\n };\n }\n }\n\n private summarizeError(error: unknown): string {\n if (error instanceof ZodError) {\n return error.issues.map((issue) => `${issue.path.join(\".\") || \"<root>\"}: ${issue.message}`).join(\"; \");\n }\n if (error instanceof Error) {\n return error.message;\n }\n return String(error);\n }\n\n private toJson(value: unknown): string {\n try {\n return JSON.stringify(value);\n } catch (error) {\n return `<<unserializable: ${this.summarizeError(error)}>>`;\n }\n }\n}\n","import type { NodeInputsByPort } from \"@codemation/core\";\n\nexport class AgentToolCallPortMap {\n static fromInput(input: unknown): NodeInputsByPort {\n return {\n in: [\n {\n json: input,\n },\n ],\n };\n }\n}\n","import type { JsonValue } from \"@codemation/core\";\nimport { injectable } from \"@codemation/core\";\nimport { ZodError } from \"zod\";\n\nimport type { AgentToolFailureClassification, AgentToolValidationIssue } from \"./AgentToolRepair.types\";\n\n@injectable()\nexport class AgentToolErrorClassifier {\n classify(\n args: Readonly<{\n error: unknown;\n toolName: string;\n schema?: unknown;\n }>,\n ): AgentToolFailureClassification {\n const effectiveError = this.toError(args.error);\n if (this.isRepairableValidationError(args.error, effectiveError)) {\n return {\n kind: \"repairable_validation_error\",\n effectiveError,\n issues: this.extractIssues(args.error, effectiveError, args.toolName),\n requiredSchemaReminder: this.toJsonValue(args.schema),\n };\n }\n if (this.isTransientExecutionError(effectiveError)) {\n return {\n kind: \"transient_execution_error\",\n effectiveError,\n };\n }\n return {\n kind: \"non_repairable_error\",\n effectiveError,\n };\n }\n\n private isRepairableValidationError(rawError: unknown, effectiveError: Error): boolean {\n if (rawError instanceof ZodError) {\n const stage = (rawError as ZodError & { codemationToolValidationStage?: \"input\" | \"output\" })\n .codemationToolValidationStage;\n return stage !== \"output\";\n }\n if (effectiveError.name === \"ZodError\") {\n return true;\n }\n return effectiveError.message.includes(\"Received tool input did not match expected schema\");\n }\n\n private extractIssues(\n rawError: unknown,\n effectiveError: Error,\n toolName: string,\n ): ReadonlyArray<AgentToolValidationIssue> | undefined {\n if (rawError instanceof ZodError) {\n return rawError.issues.map((issue) => ({\n path: issue.path.map((segment) => (typeof segment === \"number\" ? segment : String(segment))),\n code: issue.code,\n message: issue.message,\n expected: this.toOptionalString(\"expected\" in issue ? issue.expected : undefined),\n received: this.toOptionalString(\"received\" in issue ? issue.received : undefined),\n }));\n }\n if (effectiveError.name !== \"ZodError\") {\n return undefined;\n }\n return [\n {\n path: [],\n code: \"invalid_tool_input\",\n message: `Tool \"${toolName}\" input was invalid: ${effectiveError.message}`,\n },\n ];\n }\n\n private isTransientExecutionError(error: Error): boolean {\n const summary = `${error.name} ${error.message}`.toLowerCase();\n return (\n summary.includes(\"timeout\") ||\n summary.includes(\"timed out\") ||\n summary.includes(\"rate limit\") ||\n summary.includes(\"too many requests\") ||\n summary.includes(\"temporarily unavailable\") ||\n summary.includes(\"econnreset\") ||\n summary.includes(\"etimedout\") ||\n summary.includes(\"503\")\n );\n }\n\n private toError(error: unknown): Error {\n return error instanceof Error ? error : new Error(String(error));\n }\n\n private toJsonValue(value: unknown): JsonValue | undefined {\n if (value === undefined) {\n return undefined;\n }\n return JSON.parse(JSON.stringify(value)) as JsonValue;\n }\n\n private toOptionalString(value: unknown): string | undefined {\n if (value === undefined) {\n return undefined;\n }\n return String(value);\n }\n}\n","import type { JsonValue } from \"@codemation/core\";\n\nimport type { AgentToolValidationIssue } from \"./AgentToolRepair.types\";\n\nexport class AgentToolRepairExhaustedError extends Error {\n readonly details: JsonValue;\n\n constructor(\n args: Readonly<{\n agentName: string;\n nodeId: string;\n toolName: string;\n maxAttempts: number;\n lastManagedInput?: JsonValue;\n lastValidationIssues?: ReadonlyArray<AgentToolValidationIssue>;\n }>,\n ) {\n super(\n `AIAgent \"${args.agentName}\" (${args.nodeId}) could not recover from invalid tool calls for \"${args.toolName}\" after ${args.maxAttempts} repair attempt(s).`,\n );\n this.name = \"AgentToolRepairExhaustedError\";\n const details: Record<string, JsonValue> = {\n toolName: args.toolName,\n maxAttempts: args.maxAttempts,\n recommendation:\n \"Check tool schema, tool description, or inject known values in code instead of asking the model to infer them.\",\n };\n if (args.lastManagedInput !== undefined) {\n details[\"lastManagedInput\"] = args.lastManagedInput;\n }\n if (args.lastValidationIssues && args.lastValidationIssues.length > 0) {\n details[\"lastValidationIssues\"] = args.lastValidationIssues.map((issue) => this.serializeIssue(issue));\n }\n this.details = details;\n }\n\n private serializeIssue(issue: AgentToolValidationIssue): JsonValue {\n const result: Record<string, JsonValue> = {\n path: [...issue.path],\n code: issue.code,\n message: issue.message,\n };\n if (issue.expected !== undefined) {\n result[\"expected\"] = issue.expected;\n }\n if (issue.received !== undefined) {\n result[\"received\"] = issue.received;\n }\n return result;\n }\n}\n","import { injectable } from \"@codemation/core\";\n\nimport type { AgentToolRepairDecision } from \"./AgentToolRepair.types\";\n\n@injectable()\nexport class AgentToolRepairPolicy {\n private static readonly maxRepairAttemptsPerTool = 2;\n\n createDecision(toolName: string, attemptsByToolName: Map<string, number>): AgentToolRepairDecision {\n const attempt = (attemptsByToolName.get(toolName) ?? 0) + 1;\n attemptsByToolName.set(toolName, attempt);\n return {\n attempt,\n maxAttempts: AgentToolRepairPolicy.maxRepairAttemptsPerTool,\n nextAction:\n attempt < AgentToolRepairPolicy.maxRepairAttemptsPerTool\n ? \"model_retry_with_tool_error_message\"\n : \"fail_agent_run\",\n };\n }\n}\n","import type { JsonValue, NodeExecutionContext } from \"@codemation/core\";\nimport { CodemationTelemetryAttributeNames, ConnectionInvocationIdFactory, inject, injectable } from \"@codemation/core\";\n\nimport type { AIAgent } from \"./AIAgentConfig\";\nimport { AgentOutputFactory } from \"./AgentOutputFactory\";\nimport { AgentToolCallPortMap } from \"./AgentToolCallPortMapFactory\";\nimport { AgentToolErrorClassifier } from \"./AgentToolErrorClassifier\";\nimport { AgentToolRepairExhaustedError } from \"./AgentToolRepairExhaustedError\";\nimport { AgentToolRepairPolicy } from \"./AgentToolRepairPolicy\";\nimport type { AgentToolRepairDecision, AgentToolValidationIssue } from \"./AgentToolRepair.types\";\nimport type { ExecutedToolCall, PlannedToolCall } from \"./aiAgentSupport.types\";\n\n@injectable()\nexport class AgentToolExecutionCoordinator {\n constructor(\n @inject(AgentToolErrorClassifier)\n private readonly errorClassifier: AgentToolErrorClassifier,\n @inject(AgentToolRepairPolicy)\n private readonly repairPolicy: AgentToolRepairPolicy,\n ) {}\n\n async execute(\n args: Readonly<{\n plannedToolCalls: ReadonlyArray<PlannedToolCall>;\n ctx: NodeExecutionContext<AIAgent<any, any>>;\n agentName: string;\n repairAttemptsByToolName: Map<string, number>;\n }>,\n ): Promise<ReadonlyArray<ExecutedToolCall>> {\n const results = await Promise.allSettled(\n args.plannedToolCalls.map(\n async (plannedToolCall) => await this.executePlannedToolCall({ ...args, plannedToolCall }),\n ),\n );\n\n const rejected = results.find((result) => result.status === \"rejected\");\n if (rejected?.status === \"rejected\") {\n throw rejected.reason instanceof Error ? rejected.reason : new Error(String(rejected.reason));\n }\n\n return results\n .filter((result): result is PromiseFulfilledResult<ExecutedToolCall> => result.status === \"fulfilled\")\n .map((result) => result.value);\n }\n\n private async executePlannedToolCall(\n args: Readonly<{\n plannedToolCall: PlannedToolCall;\n ctx: NodeExecutionContext<AIAgent<any, any>>;\n agentName: string;\n repairAttemptsByToolName: Map<string, number>;\n }>,\n ): Promise<ExecutedToolCall> {\n const { plannedToolCall, ctx } = args;\n const toolCallInputsByPort = AgentToolCallPortMap.fromInput(plannedToolCall.toolCall.input ?? {});\n const invocationId = ConnectionInvocationIdFactory.create();\n const startedAt = new Date();\n const span = ctx.telemetry.startChildSpan({\n name: \"agent.tool.call\",\n kind: \"client\",\n startedAt,\n attributes: {\n [CodemationTelemetryAttributeNames.connectionInvocationId]: invocationId,\n [CodemationTelemetryAttributeNames.toolName]: plannedToolCall.binding.config.name,\n },\n });\n await ctx.nodeState?.markRunning({\n nodeId: plannedToolCall.nodeId,\n activationId: ctx.activationId,\n inputsByPort: toolCallInputsByPort,\n });\n\n try {\n const serialized = await plannedToolCall.binding.langChainTool.invoke(plannedToolCall.toolCall.input ?? {});\n const result = this.parseToolOutput(serialized);\n const finishedAt = new Date();\n await ctx.nodeState?.markCompleted({\n nodeId: plannedToolCall.nodeId,\n activationId: ctx.activationId,\n inputsByPort: toolCallInputsByPort,\n outputs: AgentOutputFactory.fromUnknown(result),\n });\n await span.attachArtifact({\n kind: \"tool.input\",\n contentType: \"application/json\",\n previewJson: this.toJsonValue(plannedToolCall.toolCall.input),\n });\n await span.attachArtifact({\n kind: \"tool.output\",\n contentType: \"application/json\",\n previewJson: this.toJsonValue(result),\n });\n await span.end({ status: \"ok\", endedAt: finishedAt });\n await ctx.nodeState?.appendConnectionInvocation({\n invocationId,\n connectionNodeId: plannedToolCall.nodeId,\n parentAgentNodeId: ctx.nodeId,\n parentAgentActivationId: ctx.activationId,\n status: \"completed\",\n managedInput: this.toJsonValue(plannedToolCall.toolCall.input),\n managedOutput: this.toJsonValue(result),\n queuedAt: startedAt.toISOString(),\n startedAt: startedAt.toISOString(),\n finishedAt: finishedAt.toISOString(),\n });\n return {\n toolName: plannedToolCall.binding.config.name,\n toolCallId: plannedToolCall.toolCall.id ?? plannedToolCall.binding.config.name,\n serialized: typeof serialized === \"string\" ? serialized : JSON.stringify(serialized),\n result,\n } satisfies ExecutedToolCall;\n } catch (error) {\n const classification = this.errorClassifier.classify({\n error,\n toolName: plannedToolCall.binding.config.name,\n schema: plannedToolCall.binding.langChainTool.schema,\n });\n\n if (classification.kind !== \"repairable_validation_error\") {\n const effectiveError = classification.effectiveError;\n await this.recordFailedInvocation({\n invocationId,\n plannedToolCall,\n ctx,\n startedAt,\n inputsByPort: toolCallInputsByPort,\n managedInput: this.toJsonValue(plannedToolCall.toolCall.input),\n error: effectiveError,\n });\n await span.attachArtifact({\n kind: \"tool.input\",\n contentType: \"application/json\",\n previewJson: this.toJsonValue(plannedToolCall.toolCall.input),\n });\n await span.end({\n status: \"error\",\n statusMessage: effectiveError.message,\n endedAt: new Date(),\n });\n throw effectiveError;\n }\n\n const repairDecision = this.repairPolicy.createDecision(\n plannedToolCall.binding.config.name,\n args.repairAttemptsByToolName,\n );\n\n if (repairDecision.nextAction === \"fail_agent_run\") {\n const exhaustedError = new AgentToolRepairExhaustedError({\n agentName: args.agentName,\n nodeId: ctx.nodeId,\n toolName: plannedToolCall.binding.config.name,\n maxAttempts: repairDecision.maxAttempts,\n lastManagedInput: this.toJsonValue(plannedToolCall.toolCall.input),\n lastValidationIssues: classification.issues,\n });\n await this.recordFailedInvocation({\n invocationId,\n plannedToolCall,\n ctx,\n startedAt,\n inputsByPort: toolCallInputsByPort,\n managedInput: this.toJsonValue(plannedToolCall.toolCall.input),\n error: exhaustedError,\n errorDetails: exhaustedError.details,\n });\n await span.attachArtifact({\n kind: \"tool.input\",\n contentType: \"application/json\",\n previewJson: this.toJsonValue(plannedToolCall.toolCall.input),\n });\n await span.attachArtifact({\n kind: \"tool.error\",\n contentType: \"application/json\",\n previewJson: exhaustedError.details,\n });\n await span.end({\n status: \"error\",\n statusMessage: exhaustedError.message,\n endedAt: new Date(),\n });\n throw exhaustedError;\n }\n\n const repairPayload = this.createRepairPayload({\n toolName: plannedToolCall.binding.config.name,\n issues: classification.issues,\n requiredSchemaReminder: classification.requiredSchemaReminder,\n });\n const repairDetails = this.createRepairDetails({\n toolName: plannedToolCall.binding.config.name,\n issues: classification.issues,\n requiredSchemaReminder: classification.requiredSchemaReminder,\n repairDecision,\n });\n await this.recordFailedInvocation({\n invocationId,\n plannedToolCall,\n ctx,\n startedAt,\n inputsByPort: toolCallInputsByPort,\n managedInput: this.toJsonValue(plannedToolCall.toolCall.input),\n error: classification.effectiveError,\n errorDetails: repairDetails,\n });\n await span.attachArtifact({\n kind: \"tool.input\",\n contentType: \"application/json\",\n previewJson: this.toJsonValue(plannedToolCall.toolCall.input),\n });\n await span.attachArtifact({\n kind: \"tool.error\",\n contentType: \"application/json\",\n previewJson: repairPayload,\n });\n await span.end({\n status: \"error\",\n statusMessage: classification.effectiveError.message,\n endedAt: new Date(),\n });\n return {\n toolName: plannedToolCall.binding.config.name,\n toolCallId: plannedToolCall.toolCall.id ?? plannedToolCall.binding.config.name,\n serialized: JSON.stringify(repairPayload),\n result: repairPayload,\n } satisfies ExecutedToolCall;\n }\n }\n\n private async recordFailedInvocation(\n args: Readonly<{\n invocationId: string;\n plannedToolCall: PlannedToolCall;\n ctx: NodeExecutionContext<AIAgent<any, any>>;\n startedAt: Date;\n inputsByPort: ReturnType<typeof AgentToolCallPortMap.fromInput>;\n managedInput?: JsonValue;\n error: Error;\n errorDetails?: JsonValue;\n }>,\n ): Promise<void> {\n const finishedAt = new Date();\n await args.ctx.nodeState?.markFailed({\n nodeId: args.plannedToolCall.nodeId,\n activationId: args.ctx.activationId,\n inputsByPort: args.inputsByPort,\n error: args.error,\n });\n await args.ctx.nodeState?.appendConnectionInvocation({\n invocationId: args.invocationId,\n connectionNodeId: args.plannedToolCall.nodeId,\n parentAgentNodeId: args.ctx.nodeId,\n parentAgentActivationId: args.ctx.activationId,\n status: \"failed\",\n managedInput: args.managedInput,\n error: {\n message: args.error.message,\n name: args.error.name,\n stack: args.error.stack,\n details: args.errorDetails ?? this.extractErrorDetails(args.error),\n },\n queuedAt: args.startedAt.toISOString(),\n startedAt: args.startedAt.toISOString(),\n finishedAt: finishedAt.toISOString(),\n });\n }\n\n private createRepairPayload(\n args: Readonly<{\n toolName: string;\n issues?: ReadonlyArray<AgentToolValidationIssue>;\n requiredSchemaReminder?: JsonValue;\n }>,\n ): JsonValue {\n const payload: Record<string, JsonValue> = {\n status: \"error\",\n errorType: \"validation\",\n toolName: args.toolName,\n message: this.createValidationMessage(args.toolName, args.issues),\n instruction: \"Call the tool again with all required fields present and correctly typed.\",\n };\n if (args.requiredSchemaReminder !== undefined) {\n payload[\"requiredSchemaReminder\"] = args.requiredSchemaReminder;\n }\n return payload;\n }\n\n private createRepairDetails(\n args: Readonly<{\n toolName: string;\n issues?: ReadonlyArray<AgentToolValidationIssue>;\n requiredSchemaReminder?: JsonValue;\n repairDecision: AgentToolRepairDecision;\n }>,\n ): JsonValue {\n const details: Record<string, JsonValue> = {\n errorType: \"validation\",\n toolName: args.toolName,\n recoveryHint: \"Call the same tool again with every required field present and correctly typed.\",\n repair: {\n attempt: args.repairDecision.attempt,\n maxAttempts: args.repairDecision.maxAttempts,\n nextAction: args.repairDecision.nextAction,\n },\n };\n if (args.issues && args.issues.length > 0) {\n details[\"issues\"] = args.issues.map((issue) => this.serializeIssue(issue));\n }\n if (args.requiredSchemaReminder !== undefined) {\n details[\"requiredSchemaReminder\"] = args.requiredSchemaReminder;\n }\n return details;\n }\n\n private createValidationMessage(\n toolName: string,\n issues: ReadonlyArray<AgentToolValidationIssue> | undefined,\n ): string {\n const firstIssue = issues?.[0];\n if (!firstIssue) {\n return `Your previous tool call for \"${toolName}\" was invalid and did not match the expected schema.`;\n }\n const fieldPath = firstIssue.path.length > 0 ? firstIssue.path.join(\".\") : \"<root>\";\n return `Your previous tool call for \"${toolName}\" was invalid because field \"${fieldPath}\" failed validation: ${firstIssue.message}`;\n }\n\n private parseToolOutput(serialized: unknown): unknown {\n if (typeof serialized !== \"string\") {\n return serialized;\n }\n try {\n return JSON.parse(serialized) as unknown;\n } catch {\n return serialized;\n }\n }\n\n private toJsonValue(value: unknown): JsonValue | undefined {\n if (value === undefined) {\n return undefined;\n }\n return JSON.parse(JSON.stringify(value)) as JsonValue;\n }\n\n private extractErrorDetails(error: Error): JsonValue | undefined {\n const candidate = error as Error & { details?: JsonValue };\n return candidate.details;\n }\n\n private serializeIssue(issue: AgentToolValidationIssue): JsonValue {\n const result: Record<string, JsonValue> = {\n path: [...issue.path],\n code: issue.code,\n message: issue.message,\n };\n if (issue.expected !== undefined) {\n result[\"expected\"] = issue.expected;\n }\n if (issue.received !== undefined) {\n result[\"received\"] = issue.received;\n }\n return result;\n }\n}\n","import type {\n MultiInputNode,\n NodeExecutionContext,\n NodeOutputs,\n NodeResolver,\n RunnableNode,\n RunnableNodeConfig,\n RunnableNodeExecuteArgs,\n NodeBackedToolConfig,\n ToolExecuteArgs,\n ZodSchemaAny,\n} from \"@codemation/core\";\nimport {\n CoreTokens,\n inject,\n injectable,\n ItemExprResolver,\n NodeOutputNormalizer,\n RunnableOutputBehaviorResolver,\n} from \"@codemation/core\";\nimport { z } from \"zod\";\n\n@injectable()\nexport class NodeBackedToolRuntime {\n constructor(\n @inject(CoreTokens.NodeResolver)\n private readonly nodeResolver: NodeResolver,\n @inject(ItemExprResolver)\n private readonly itemExprResolver: ItemExprResolver,\n @inject(NodeOutputNormalizer)\n private readonly outputNormalizer: NodeOutputNormalizer,\n @inject(RunnableOutputBehaviorResolver)\n private readonly outputBehaviorResolver: RunnableOutputBehaviorResolver,\n ) {}\n\n async execute(\n config: NodeBackedToolConfig<any, ZodSchemaAny, ZodSchemaAny>,\n args: ToolExecuteArgs,\n ): Promise<unknown> {\n const nodeInput = config.toNodeItem({\n input: args.input,\n item: args.item,\n itemIndex: args.itemIndex,\n items: args.items,\n ctx: args.ctx,\n node: config.node,\n });\n const nodeCtx = {\n ...args.ctx,\n config: config.node,\n } as NodeExecutionContext<RunnableNodeConfig>;\n const resolvedNode = this.nodeResolver.resolve(config.node.type);\n const outputs = await this.executeResolvedNode(resolvedNode, nodeInput, nodeCtx);\n return config.toToolOutput({\n input: args.input,\n item: args.item,\n itemIndex: args.itemIndex,\n items: args.items,\n ctx: args.ctx,\n node: config.node,\n outputs,\n });\n }\n\n private async executeResolvedNode(\n resolvedNode: unknown,\n nodeInput: ToolExecuteArgs[\"item\"],\n ctx: NodeExecutionContext<RunnableNodeConfig>,\n ): Promise<NodeOutputs> {\n if (this.isMultiInputNode(resolvedNode)) {\n return await resolvedNode.executeMulti({ in: [nodeInput] }, ctx);\n }\n if (this.isRunnableNode(resolvedNode)) {\n const runnable = resolvedNode;\n const runnableConfig = ctx.config;\n const behavior = this.outputBehaviorResolver.resolve(runnableConfig);\n const inputSchema = runnable.inputSchema ?? runnableConfig.inputSchema ?? z.unknown();\n const parsed = inputSchema.parse(nodeInput.json);\n const items = [nodeInput];\n const resolvedCtx = await this.itemExprResolver.resolveConfigForItem(ctx, nodeInput, 0, items);\n const execArgs: RunnableNodeExecuteArgs = {\n input: parsed,\n item: nodeInput,\n itemIndex: 0,\n items,\n ctx: resolvedCtx,\n };\n const raw = await Promise.resolve(runnable.execute(execArgs));\n return this.outputNormalizer.normalizeExecuteResult({\n baseItem: nodeInput,\n raw,\n behavior,\n });\n }\n throw new Error(`Node-backed tool expected a runnable node instance for \"${ctx.config.name ?? ctx.nodeId}\".`);\n }\n\n private isRunnableNode(value: unknown): value is RunnableNode {\n return (\n typeof value === \"object\" &&\n value !== null &&\n (value as { kind?: string }).kind === \"node\" &&\n typeof (value as { execute?: unknown }).execute === \"function\" &&\n typeof (value as { executeMulti?: unknown }).executeMulti !== \"function\"\n );\n }\n\n private isMultiInputNode(value: unknown): value is MultiInputNode<any> {\n return typeof value === \"object\" && value !== null && \"executeMulti\" in value;\n }\n}\n","import type {\n AgentToolCall,\n Item,\n NodeInputsByPort,\n ToolConfig,\n ToolExecuteArgs,\n ZodSchemaAny,\n} from \"@codemation/core\";\nimport type { DynamicStructuredTool } from \"@langchain/core/tools\";\n\nexport class AgentItemPortMap {\n static fromItem(item: Item): NodeInputsByPort {\n return { in: [item] };\n }\n}\n\nexport type ResolvedTool = Readonly<{\n config: ToolConfig;\n runtime: Readonly<{\n defaultDescription: string;\n inputSchema: ZodSchemaAny;\n execute(args: ToolExecuteArgs<ToolConfig, unknown>): Promise<unknown>;\n }>;\n}>;\n\nexport type ItemScopedToolBinding = Readonly<{\n config: ToolConfig;\n langChainTool: DynamicStructuredTool;\n}>;\n\nexport type PlannedToolCall = Readonly<{\n binding: ItemScopedToolBinding;\n toolCall: AgentToolCall;\n invocationIndex: number;\n nodeId: string;\n}>;\n\nexport type ExecutedToolCall = Readonly<{\n toolName: string;\n toolCallId: string;\n result: unknown;\n serialized: string;\n}>;\n","import type {\n AgentGuardrailConfig,\n AgentToolCall,\n ChatModelConfig,\n ChatModelFactory,\n Item,\n Items,\n JsonValue,\n LangChainChatModelLike,\n NodeExecutionContext,\n NodeInputsByPort,\n RunnableNode,\n RunnableNodeExecuteArgs,\n Tool,\n ToolConfig,\n LangChainStructuredOutputModelLike,\n ZodSchemaAny,\n} from \"@codemation/core\";\n\nimport type { CredentialSessionService } from \"@codemation/core\";\nimport {\n AgentGuardrailDefaults,\n AgentMessageConfigNormalizer,\n CallableToolConfig,\n CodemationTelemetryAttributeNames,\n CodemationTelemetryMetricNames,\n ConnectionInvocationIdFactory,\n ConnectionNodeIdFactory,\n CoreTokens,\n GenAiTelemetryAttributeNames,\n NodeBackedToolConfig,\n inject,\n node,\n type NodeResolver,\n} from \"@codemation/core\";\n\nimport { AIMessage, type BaseMessage } from \"@langchain/core/messages\";\nimport { z } from \"zod\";\n\nimport type { AIAgent } from \"./AIAgentConfig\";\nimport { AIAgentExecutionHelpersFactory } from \"./AIAgentExecutionHelpersFactory\";\nimport { AgentToolExecutionCoordinator } from \"./AgentToolExecutionCoordinator\";\nimport { ConnectionCredentialExecutionContextFactory } from \"./ConnectionCredentialExecutionContextFactory\";\nimport { AgentMessageFactory } from \"./AgentMessageFactory\";\nimport { AgentOutputFactory } from \"./AgentOutputFactory\";\nimport { AgentStructuredOutputRunner } from \"./AgentStructuredOutputRunner\";\nimport { AgentToolCallPortMap } from \"./AgentToolCallPortMapFactory\";\nimport { NodeBackedToolRuntime } from \"./NodeBackedToolRuntime\";\nimport {\n AgentItemPortMap,\n type ExecutedToolCall,\n type ItemScopedToolBinding,\n type PlannedToolCall,\n type ResolvedTool,\n} from \"./aiAgentSupport.types\";\n\ntype ResolvedGuardrails = Required<Pick<AgentGuardrailConfig, \"maxTurns\" | \"onTurnLimitReached\">> &\n Pick<AgentGuardrailConfig, \"modelInvocationOptions\">;\n\n/** Everything needed to run the agent loop for one item (shared across items in the same activation). */\ninterface PreparedAgentExecution {\n readonly ctx: NodeExecutionContext<AIAgent<any, any>>;\n readonly model: LangChainChatModelLike;\n readonly resolvedTools: ReadonlyArray<ResolvedTool>;\n readonly guardrails: ResolvedGuardrails;\n readonly languageModelConnectionNodeId: string;\n}\n\n@node({ packageName: \"@codemation/core-nodes\" })\nexport class AIAgentNode implements RunnableNode<AIAgent<any, any>> {\n kind = \"node\" as const;\n outputPorts = [\"main\"] as const;\n /**\n * Engine validates {@link RunnableNodeConfig.inputSchema} (Zod) on {@code item.json} before enqueue, then resolves\n * per-item **`itemExpr`** leaves on config before {@link #execute}. Prefer modeling prompts as\n * {@code { messages: [{ role, content }, ...] }} (on input or config) so persisted inputs are visible in the UI.\n */\n readonly inputSchema = z.unknown();\n\n private readonly connectionCredentialExecutionContextFactory: ConnectionCredentialExecutionContextFactory;\n /** One resolved model/tools bundle per activation context (same ctx across items in a batch). */\n private readonly preparedByExecutionContext = new WeakMap<\n NodeExecutionContext<AIAgent<any, any>>,\n Promise<PreparedAgentExecution>\n >();\n\n constructor(\n @inject(CoreTokens.NodeResolver)\n private readonly nodeResolver: NodeResolver,\n @inject(CoreTokens.CredentialSessionService)\n credentialSessions: CredentialSessionService,\n @inject(NodeBackedToolRuntime)\n private readonly nodeBackedToolRuntime: NodeBackedToolRuntime,\n @inject(AIAgentExecutionHelpersFactory)\n private readonly executionHelpers: AIAgentExecutionHelpersFactory,\n @inject(AgentStructuredOutputRunner)\n private readonly structuredOutputRunner: AgentStructuredOutputRunner,\n @inject(AgentToolExecutionCoordinator)\n private readonly toolExecutionCoordinator: AgentToolExecutionCoordinator,\n ) {\n this.connectionCredentialExecutionContextFactory =\n this.executionHelpers.createConnectionCredentialExecutionContextFactory(credentialSessions);\n }\n\n async execute(args: RunnableNodeExecuteArgs<AIAgent<any, any>>): Promise<unknown> {\n const prepared = await this.getOrPrepareExecution(args.ctx);\n const itemWithMappedJson = { ...args.item, json: args.input };\n const resultItem = await this.runAgentForItem(prepared, itemWithMappedJson, args.itemIndex, args.items);\n return resultItem.json;\n }\n\n private async getOrPrepareExecution(ctx: NodeExecutionContext<AIAgent<any, any>>): Promise<PreparedAgentExecution> {\n let pending = this.preparedByExecutionContext.get(ctx);\n if (!pending) {\n pending = this.prepareExecution(ctx);\n this.preparedByExecutionContext.set(ctx, pending);\n }\n try {\n return await pending;\n } catch (error) {\n this.preparedByExecutionContext.delete(ctx);\n throw error;\n }\n }\n\n /**\n * Resolves the chat model and tools once per activation, then reuses for every item in the batch.\n */\n private async prepareExecution(ctx: NodeExecutionContext<AIAgent<any, any>>): Promise<PreparedAgentExecution> {\n const chatModelFactory = this.nodeResolver.resolve(ctx.config.chatModel.type) as ChatModelFactory<ChatModelConfig>;\n const languageModelCredentialContext = this.connectionCredentialExecutionContextFactory.forConnectionNode(ctx, {\n connectionNodeId: ConnectionNodeIdFactory.languageModelConnectionNodeId(ctx.nodeId),\n getCredentialRequirements: () => ctx.config.chatModel.getCredentialRequirements?.() ?? [],\n });\n const model = await Promise.resolve(\n chatModelFactory.create({ config: ctx.config.chatModel, ctx: languageModelCredentialContext }),\n );\n return {\n ctx,\n model,\n resolvedTools: this.resolveTools(ctx.config.tools ?? []),\n guardrails: this.resolveGuardrails(ctx.config.guardrails),\n languageModelConnectionNodeId: ConnectionNodeIdFactory.languageModelConnectionNodeId(ctx.nodeId),\n };\n }\n\n /**\n * One item: build prompts, optionally bind tools, run the multi-turn loop, map the final model message to workflow JSON.\n */\n private async runAgentForItem(\n prepared: PreparedAgentExecution,\n item: Item,\n itemIndex: number,\n items: Items,\n ): Promise<Item> {\n const { ctx } = prepared;\n const itemInputsByPort = AgentItemPortMap.fromItem(item);\n const itemScopedTools = this.createItemScopedTools(prepared.resolvedTools, ctx, item, itemIndex, items);\n const conversation: BaseMessage[] = [...this.createPromptMessages(item, itemIndex, items, ctx)];\n if (ctx.config.outputSchema && itemScopedTools.length === 0) {\n const structuredOutput = await this.structuredOutputRunner.resolve({\n model: prepared.model,\n chatModelConfig: ctx.config.chatModel,\n schema: ctx.config.outputSchema,\n conversation,\n agentName: this.getAgentDisplayName(ctx),\n nodeId: ctx.nodeId,\n invokeTextModel: async (messages) =>\n await this.invokeModel(\n prepared.model,\n prepared.languageModelConnectionNodeId,\n messages,\n ctx,\n itemInputsByPort,\n prepared.guardrails.modelInvocationOptions,\n ),\n invokeStructuredModel: async (structuredModel, messages) =>\n await this.invokeStructuredModel(\n structuredModel,\n prepared.languageModelConnectionNodeId,\n messages,\n ctx,\n itemInputsByPort,\n prepared.guardrails.modelInvocationOptions,\n ),\n });\n await ctx.telemetry.recordMetric({ name: CodemationTelemetryMetricNames.agentTurns, value: 1 });\n await ctx.telemetry.recordMetric({ name: CodemationTelemetryMetricNames.agentToolCalls, value: 0 });\n return this.buildOutputItem(item, structuredOutput);\n }\n const modelWithTools = this.bindToolsToModel(prepared.model, itemScopedTools);\n const loopResult = await this.runTurnLoopUntilFinalAnswer({\n prepared,\n itemInputsByPort,\n itemScopedTools,\n conversation,\n modelWithTools,\n });\n await ctx.telemetry.recordMetric({ name: CodemationTelemetryMetricNames.agentTurns, value: loopResult.turnCount });\n await ctx.telemetry.recordMetric({\n name: CodemationTelemetryMetricNames.agentToolCalls,\n value: loopResult.toolCallCount,\n });\n const outputJson = await this.resolveFinalOutputJson(\n prepared,\n itemInputsByPort,\n conversation,\n loopResult.finalResponse,\n itemScopedTools.length > 0,\n );\n return this.buildOutputItem(item, outputJson);\n }\n\n /**\n * Repeatedly invokes the model until it returns without tool calls, or guardrails end the loop.\n */\n private async runTurnLoopUntilFinalAnswer(args: {\n prepared: PreparedAgentExecution;\n itemInputsByPort: NodeInputsByPort;\n itemScopedTools: ReadonlyArray<ItemScopedToolBinding>;\n conversation: BaseMessage[];\n modelWithTools: LangChainChatModelLike;\n }): Promise<Readonly<{ finalResponse: AIMessage; turnCount: number; toolCallCount: number }>> {\n const { prepared, itemInputsByPort, itemScopedTools, conversation, modelWithTools } = args;\n const { ctx, guardrails, languageModelConnectionNodeId } = prepared;\n\n let finalResponse: AIMessage | undefined;\n let toolCallCount = 0;\n let turnCount = 0;\n const repairAttemptsByToolName = new Map<string, number>();\n\n for (let turn = 1; turn <= guardrails.maxTurns; turn++) {\n turnCount = turn;\n const response = await this.invokeModel(\n modelWithTools,\n languageModelConnectionNodeId,\n conversation,\n ctx,\n itemInputsByPort,\n guardrails.modelInvocationOptions,\n );\n finalResponse = response;\n\n const toolCalls = AgentMessageFactory.extractToolCalls(response);\n if (toolCalls.length === 0) {\n break;\n }\n\n if (this.cannotExecuteAnotherToolRound(turn, guardrails)) {\n this.finishOrThrowWhenTurnCapHitWithToolCalls(ctx, guardrails);\n break;\n }\n\n const plannedToolCalls = this.planToolCalls(itemScopedTools, toolCalls, ctx.nodeId);\n toolCallCount += plannedToolCalls.length;\n await this.markQueuedTools(plannedToolCalls, ctx);\n const executedToolCalls = await this.toolExecutionCoordinator.execute({\n plannedToolCalls,\n ctx,\n agentName: this.getAgentDisplayName(ctx),\n repairAttemptsByToolName,\n });\n this.appendAssistantAndToolMessages(conversation, response, executedToolCalls);\n }\n\n if (!finalResponse) {\n throw new Error(`AIAgent \"${ctx.config.name ?? ctx.nodeId}\" did not produce a model response.`);\n }\n return {\n finalResponse,\n turnCount,\n toolCallCount,\n };\n }\n\n private cannotExecuteAnotherToolRound(turn: number, guardrails: ResolvedGuardrails): boolean {\n return turn >= guardrails.maxTurns;\n }\n\n private finishOrThrowWhenTurnCapHitWithToolCalls(\n ctx: NodeExecutionContext<AIAgent<any, any>>,\n guardrails: ResolvedGuardrails,\n ): void {\n if (guardrails.onTurnLimitReached === \"respondWithLastMessage\") {\n return;\n }\n throw new Error(\n `AIAgent \"${ctx.config.name ?? ctx.nodeId}\" reached maxTurns=${guardrails.maxTurns} before producing a final response.`,\n );\n }\n\n private appendAssistantAndToolMessages(\n conversation: BaseMessage[],\n assistantMessage: AIMessage,\n executedToolCalls: ReadonlyArray<ExecutedToolCall>,\n ): void {\n conversation.push(\n assistantMessage,\n ...executedToolCalls.map((toolCall) =>\n AgentMessageFactory.createToolMessage(toolCall.toolCallId, toolCall.serialized),\n ),\n );\n }\n\n private async resolveFinalOutputJson(\n prepared: PreparedAgentExecution,\n itemInputsByPort: NodeInputsByPort,\n conversation: ReadonlyArray<BaseMessage>,\n finalResponse: AIMessage,\n wasToolEnabledRun: boolean,\n ): Promise<unknown> {\n if (!prepared.ctx.config.outputSchema) {\n return AgentOutputFactory.fromAgentContent(AgentMessageFactory.extractContent(finalResponse));\n }\n return await this.structuredOutputRunner.resolve({\n model: prepared.model,\n chatModelConfig: prepared.ctx.config.chatModel,\n schema: prepared.ctx.config.outputSchema,\n conversation: wasToolEnabledRun ? [...conversation, finalResponse] : conversation,\n rawFinalResponse: finalResponse,\n agentName: this.getAgentDisplayName(prepared.ctx),\n nodeId: prepared.ctx.nodeId,\n invokeTextModel: async (messages) =>\n await this.invokeModel(\n prepared.model,\n prepared.languageModelConnectionNodeId,\n messages,\n prepared.ctx,\n itemInputsByPort,\n prepared.guardrails.modelInvocationOptions,\n ),\n invokeStructuredModel: async (structuredModel, messages) =>\n await this.invokeStructuredModel(\n structuredModel,\n prepared.languageModelConnectionNodeId,\n messages,\n prepared.ctx,\n itemInputsByPort,\n prepared.guardrails.modelInvocationOptions,\n ),\n });\n }\n\n private buildOutputItem(item: Item, outputJson: unknown): Item {\n return AgentOutputFactory.replaceJson(item, outputJson);\n }\n\n private bindToolsToModel(\n model: LangChainChatModelLike,\n itemScopedTools: ReadonlyArray<ItemScopedToolBinding>,\n ): LangChainChatModelLike {\n if (itemScopedTools.length === 0 || !model.bindTools) {\n return model;\n }\n return model.bindTools(itemScopedTools.map((entry) => entry.langChainTool));\n }\n\n private resolveTools(toolConfigs: ReadonlyArray<ToolConfig>): ReadonlyArray<ResolvedTool> {\n const resolvedTools = toolConfigs.map((config) => ({\n config,\n runtime: this.resolveToolRuntime(config),\n }));\n\n const names = new Set<string>();\n for (const entry of resolvedTools) {\n if (names.has(entry.config.name)) throw new Error(`Duplicate tool name on AIAgent: ${entry.config.name}`);\n names.add(entry.config.name);\n }\n return resolvedTools;\n }\n\n private createItemScopedTools(\n tools: ReadonlyArray<ResolvedTool>,\n ctx: NodeExecutionContext<AIAgent<any, any>>,\n item: Item,\n itemIndex: number,\n items: Items,\n ): ReadonlyArray<ItemScopedToolBinding> {\n return tools.map((entry) => {\n const toolCredentialContext = this.connectionCredentialExecutionContextFactory.forConnectionNode(ctx, {\n connectionNodeId: ConnectionNodeIdFactory.toolConnectionNodeId(ctx.nodeId, entry.config.name),\n getCredentialRequirements: () => entry.config.getCredentialRequirements?.() ?? [],\n });\n const langChainTool = this.executionHelpers.createDynamicStructuredTool(\n entry,\n toolCredentialContext,\n item,\n itemIndex,\n items,\n );\n\n return { config: entry.config, langChainTool };\n });\n }\n\n private async invokeModel(\n model: LangChainChatModelLike,\n nodeId: string,\n messages: ReadonlyArray<BaseMessage>,\n ctx: NodeExecutionContext<AIAgent<any, any>>,\n inputsByPort: NodeInputsByPort,\n options?: AgentGuardrailConfig[\"modelInvocationOptions\"],\n ): Promise<AIMessage> {\n const invocationId = ConnectionInvocationIdFactory.create();\n const startedAt = new Date();\n const summarizedInput = this.summarizeLlmMessages(messages);\n const span = this.createModelInvocationSpan(ctx, invocationId, startedAt);\n await ctx.nodeState?.markQueued({ nodeId, activationId: ctx.activationId, inputsByPort });\n await ctx.nodeState?.markRunning({ nodeId, activationId: ctx.activationId, inputsByPort });\n try {\n const response = (await model.invoke(messages, options)) as AIMessage;\n const finishedAt = new Date();\n await ctx.nodeState?.markCompleted({\n nodeId,\n activationId: ctx.activationId,\n inputsByPort,\n outputs: AgentOutputFactory.fromUnknown({\n content: AgentMessageFactory.extractContent(response),\n }),\n });\n const content = AgentMessageFactory.extractContent(response);\n await span.attachArtifact({\n kind: \"ai.messages\",\n contentType: \"application/json\",\n previewJson: summarizedInput,\n });\n await span.attachArtifact({\n kind: \"ai.response\",\n contentType: \"application/json\",\n previewJson: content,\n });\n await this.recordModelUsageMetrics(span, response, ctx);\n await span.end({ status: \"ok\", endedAt: finishedAt });\n await ctx.nodeState?.appendConnectionInvocation({\n invocationId,\n connectionNodeId: nodeId,\n parentAgentNodeId: ctx.nodeId,\n parentAgentActivationId: ctx.activationId,\n status: \"completed\",\n managedInput: summarizedInput,\n managedOutput: content,\n queuedAt: startedAt.toISOString(),\n startedAt: startedAt.toISOString(),\n finishedAt: finishedAt.toISOString(),\n });\n return response;\n } catch (error) {\n await span.end({\n status: \"error\",\n statusMessage: error instanceof Error ? error.message : String(error),\n endedAt: new Date(),\n });\n throw await this.failTrackedNodeInvocation({\n error,\n invocationId,\n startedAt,\n nodeId,\n ctx,\n inputsByPort,\n managedInput: this.summarizeLlmMessages(messages),\n });\n }\n }\n\n private async invokeStructuredModel(\n model: LangChainStructuredOutputModelLike,\n nodeId: string,\n messages: ReadonlyArray<BaseMessage>,\n ctx: NodeExecutionContext<AIAgent<any, any>>,\n inputsByPort: NodeInputsByPort,\n options?: AgentGuardrailConfig[\"modelInvocationOptions\"],\n ): Promise<unknown> {\n const invocationId = ConnectionInvocationIdFactory.create();\n const startedAt = new Date();\n const summarizedInput = this.summarizeLlmMessages(messages);\n const span = this.createModelInvocationSpan(ctx, invocationId, startedAt);\n await ctx.nodeState?.markQueued({ nodeId, activationId: ctx.activationId, inputsByPort });\n await ctx.nodeState?.markRunning({ nodeId, activationId: ctx.activationId, inputsByPort });\n try {\n const response = await model.invoke(messages, options);\n const finishedAt = new Date();\n await ctx.nodeState?.markCompleted({\n nodeId,\n activationId: ctx.activationId,\n inputsByPort,\n outputs: AgentOutputFactory.fromUnknown(response),\n });\n await span.attachArtifact({\n kind: \"ai.messages\",\n contentType: \"application/json\",\n previewJson: summarizedInput,\n });\n await span.attachArtifact({\n kind: \"ai.response.structured\",\n contentType: \"application/json\",\n previewJson: this.resultToJsonValue(response),\n });\n await this.recordModelUsageMetrics(span, response, ctx);\n await span.end({ status: \"ok\", endedAt: finishedAt });\n await ctx.nodeState?.appendConnectionInvocation({\n invocationId,\n connectionNodeId: nodeId,\n parentAgentNodeId: ctx.nodeId,\n parentAgentActivationId: ctx.activationId,\n status: \"completed\",\n managedInput: summarizedInput,\n managedOutput: this.resultToJsonValue(response),\n queuedAt: startedAt.toISOString(),\n startedAt: startedAt.toISOString(),\n finishedAt: finishedAt.toISOString(),\n });\n return response;\n } catch (error) {\n await span.end({\n status: \"error\",\n statusMessage: error instanceof Error ? error.message : String(error),\n endedAt: new Date(),\n });\n throw await this.failTrackedNodeInvocation({\n error,\n invocationId,\n startedAt,\n nodeId,\n ctx,\n inputsByPort,\n managedInput: this.summarizeLlmMessages(messages),\n });\n }\n }\n\n private createModelInvocationSpan(\n ctx: NodeExecutionContext<AIAgent<any, any>>,\n invocationId: string,\n startedAt: Date,\n ) {\n return ctx.telemetry.startChildSpan({\n name: \"gen_ai.chat.completion\",\n kind: \"client\",\n startedAt,\n attributes: {\n [CodemationTelemetryAttributeNames.connectionInvocationId]: invocationId,\n [GenAiTelemetryAttributeNames.operationName]: \"chat\",\n [GenAiTelemetryAttributeNames.requestModel]: this.resolveChatModelName(ctx.config.chatModel),\n },\n });\n }\n\n private async recordModelUsageMetrics(\n span: ReturnType<NodeExecutionContext[\"telemetry\"][\"startChildSpan\"]>,\n response: unknown,\n ctx: NodeExecutionContext<AIAgent<any, any>>,\n ) {\n const usage = this.extractModelUsageMetrics(response);\n for (const [name, value] of Object.entries(usage)) {\n if (value === undefined) {\n continue;\n }\n await span.recordMetric({ name, value });\n }\n await this.captureCostTrackingUsage(span, ctx, usage);\n }\n\n private async captureCostTrackingUsage(\n span: ReturnType<NodeExecutionContext[\"telemetry\"][\"startChildSpan\"]>,\n ctx: NodeExecutionContext<AIAgent<any, any>>,\n usage: Readonly<Record<string, number | undefined>>,\n ): Promise<void> {\n const costTracking = span.costTracking;\n if (!costTracking) {\n return;\n }\n const provider = ctx.config.chatModel.provider;\n const pricingKey = ctx.config.chatModel.modelName;\n if (!provider || !pricingKey) {\n return;\n }\n const inputTokens = usage[GenAiTelemetryAttributeNames.usageInputTokens];\n const outputTokens = usage[GenAiTelemetryAttributeNames.usageOutputTokens];\n if (inputTokens !== undefined) {\n await costTracking.captureUsage({\n component: \"chat\",\n provider,\n operation: \"completion.input\",\n pricingKey,\n usageUnit: \"input_tokens\",\n quantity: inputTokens,\n modelName: pricingKey,\n });\n }\n if (outputTokens !== undefined) {\n await costTracking.captureUsage({\n component: \"chat\",\n provider,\n operation: \"completion.output\",\n pricingKey,\n usageUnit: \"output_tokens\",\n quantity: outputTokens,\n modelName: pricingKey,\n });\n }\n }\n\n private resolveChatModelName(chatModel: ChatModelConfig): string {\n return chatModel.modelName ?? chatModel.name;\n }\n\n private extractModelUsageMetrics(response: unknown): Readonly<Record<string, number | undefined>> {\n const usage = this.extractUsageObject(response);\n const inputTokens = this.readUsageNumber(usage, [\"input_tokens\", \"inputTokens\", \"prompt_tokens\", \"promptTokens\"]);\n const outputTokens = this.readUsageNumber(usage, [\n \"output_tokens\",\n \"outputTokens\",\n \"completion_tokens\",\n \"completionTokens\",\n ]);\n const totalTokens =\n this.readUsageNumber(usage, [\"total_tokens\", \"totalTokens\"]) ??\n (inputTokens !== undefined && outputTokens !== undefined ? inputTokens + outputTokens : undefined);\n const cachedInputTokens = this.readUsageNumber(usage, [\n \"cache_read_input_tokens\",\n \"cacheReadInputTokens\",\n \"input_token_details.cached_tokens\",\n ]);\n const reasoningTokens = this.readUsageNumber(usage, [\n \"reasoning_tokens\",\n \"reasoningTokens\",\n \"output_token_details.reasoning_tokens\",\n ]);\n return {\n [GenAiTelemetryAttributeNames.usageInputTokens]: inputTokens,\n [GenAiTelemetryAttributeNames.usageOutputTokens]: outputTokens,\n [GenAiTelemetryAttributeNames.usageTotalTokens]: totalTokens,\n [GenAiTelemetryAttributeNames.usageCacheReadInputTokens]: cachedInputTokens,\n [GenAiTelemetryAttributeNames.usageReasoningTokens]: reasoningTokens,\n };\n }\n\n private extractUsageObject(response: unknown): Readonly<Record<string, unknown>> | undefined {\n if (!this.isRecord(response)) {\n return undefined;\n }\n const usageMetadata = response[\"usage_metadata\"];\n if (this.isRecord(usageMetadata)) {\n return usageMetadata;\n }\n const responseMetadata = response[\"response_metadata\"];\n if (this.isRecord(responseMetadata)) {\n const tokenUsage = responseMetadata[\"tokenUsage\"];\n if (this.isRecord(tokenUsage)) {\n return tokenUsage;\n }\n const usage = responseMetadata[\"usage\"];\n if (this.isRecord(usage)) {\n return usage;\n }\n }\n return undefined;\n }\n\n private readUsageNumber(\n source: Readonly<Record<string, unknown>> | undefined,\n keys: ReadonlyArray<string>,\n ): number | undefined {\n for (const key of keys) {\n const value = this.readNestedUsageValue(source, key);\n if (typeof value === \"number\" && Number.isFinite(value)) {\n return value;\n }\n }\n return undefined;\n }\n\n private readNestedUsageValue(source: Readonly<Record<string, unknown>> | undefined, dottedKey: string): unknown {\n if (!source) {\n return undefined;\n }\n let current: unknown = source;\n for (const segment of dottedKey.split(\".\")) {\n if (!this.isRecord(current)) {\n return undefined;\n }\n current = current[segment];\n }\n return current;\n }\n\n private isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null;\n }\n\n private async markQueuedTools(\n plannedToolCalls: ReadonlyArray<PlannedToolCall>,\n ctx: NodeExecutionContext<AIAgent<any, any>>,\n ): Promise<void> {\n for (const plannedToolCall of plannedToolCalls) {\n await ctx.nodeState?.markQueued({\n nodeId: plannedToolCall.nodeId,\n activationId: ctx.activationId,\n inputsByPort: AgentToolCallPortMap.fromInput(plannedToolCall.toolCall.input ?? {}),\n });\n }\n }\n\n private planToolCalls(\n bindings: ReadonlyArray<ItemScopedToolBinding>,\n toolCalls: ReadonlyArray<AgentToolCall>,\n parentNodeId: string,\n ): ReadonlyArray<PlannedToolCall> {\n const invocationCountByToolName = new Map<string, number>();\n return toolCalls.map((toolCall) => {\n const binding = bindings.find((entry) => entry.config.name === toolCall.name);\n if (!binding) throw new Error(`Unknown tool requested by model: ${toolCall.name}`);\n const invocationIndex = (invocationCountByToolName.get(binding.config.name) ?? 0) + 1;\n invocationCountByToolName.set(binding.config.name, invocationIndex);\n return {\n binding,\n toolCall,\n invocationIndex,\n nodeId: ConnectionNodeIdFactory.toolConnectionNodeId(parentNodeId, binding.config.name),\n } satisfies PlannedToolCall;\n });\n }\n\n private async failTrackedNodeInvocation(\n args: Readonly<{\n error: unknown;\n invocationId: string;\n startedAt: Date;\n nodeId: string;\n ctx: NodeExecutionContext<AIAgent<any, any>>;\n inputsByPort: NodeInputsByPort;\n managedInput?: JsonValue;\n }>,\n ): Promise<Error> {\n const effectiveError = args.error instanceof Error ? args.error : new Error(String(args.error));\n const finishedAt = new Date();\n await args.ctx.nodeState?.markFailed({\n nodeId: args.nodeId,\n activationId: args.ctx.activationId,\n inputsByPort: args.inputsByPort,\n error: effectiveError,\n });\n await args.ctx.nodeState?.appendConnectionInvocation({\n invocationId: args.invocationId,\n connectionNodeId: args.nodeId,\n parentAgentNodeId: args.ctx.nodeId,\n parentAgentActivationId: args.ctx.activationId,\n status: \"failed\",\n managedInput: args.managedInput,\n error: {\n message: effectiveError.message,\n name: effectiveError.name,\n stack: effectiveError.stack,\n details: this.extractErrorDetails(effectiveError),\n },\n queuedAt: args.startedAt.toISOString(),\n startedAt: args.startedAt.toISOString(),\n finishedAt: finishedAt.toISOString(),\n });\n return effectiveError;\n }\n\n private summarizeLlmMessages(messages: ReadonlyArray<BaseMessage>): JsonValue {\n const last = messages[messages.length - 1];\n const preview =\n typeof last?.content === \"string\"\n ? last.content\n : last?.content !== undefined\n ? JSON.stringify(last.content)\n : \"\";\n return {\n messageCount: messages.length,\n lastMessagePreview: preview.slice(0, 4000),\n };\n }\n\n private resultToJsonValue(value: unknown): JsonValue | undefined {\n if (value === undefined) {\n return undefined;\n }\n const json = JSON.stringify(value);\n return JSON.parse(json) as JsonValue;\n }\n\n private createPromptMessages(\n item: Item,\n itemIndex: number,\n items: Items,\n ctx: NodeExecutionContext<AIAgent<any, any>>,\n ): ReadonlyArray<BaseMessage> {\n return AgentMessageFactory.createPromptMessages(\n AgentMessageConfigNormalizer.resolveFromInputOrConfig(item.json, ctx.config, {\n item,\n itemIndex,\n items,\n ctx,\n }),\n );\n }\n\n private resolveToolRuntime(config: ToolConfig): ResolvedTool[\"runtime\"] {\n if (this.isNodeBackedToolConfig(config)) {\n const inputSchema = config.getInputSchema();\n if (inputSchema == null) {\n throw new Error(\n `AIAgent tool \"${config.name}\": node-backed tool is missing inputSchema (cannot build LangChain tool).`,\n );\n }\n return {\n defaultDescription: `Run workflow node \"${config.node.name ?? config.name}\" as an AI tool.`,\n inputSchema,\n execute: async (args) => await this.nodeBackedToolRuntime.execute(config, args),\n };\n }\n if (this.isCallableToolConfig(config)) {\n const inputSchema = config.getInputSchema();\n if (inputSchema == null) {\n throw new Error(\n `AIAgent tool \"${config.name}\": callable tool is missing inputSchema (cannot build LangChain tool).`,\n );\n }\n return {\n defaultDescription: config.description ?? `Callable tool \"${config.name}\".`,\n inputSchema,\n execute: async (args) =>\n await config.executeTool({ ...args, config: config as CallableToolConfig<ZodSchemaAny, ZodSchemaAny> }),\n };\n }\n const tool = this.nodeResolver.resolve(config.type) as Tool<ToolConfig, ZodSchemaAny, ZodSchemaAny>;\n if (tool.inputSchema == null) {\n throw new Error(`AIAgent tool \"${config.name}\": plugin tool \"${String(config.type)}\" is missing inputSchema.`);\n }\n return {\n defaultDescription: tool.defaultDescription,\n inputSchema: tool.inputSchema,\n execute: async (args) => await Promise.resolve(tool.execute(args)),\n };\n }\n\n /**\n * Consumer apps can resolve two copies of `@codemation/core`, breaking `instanceof NodeBackedToolConfig` and\n * sending node-backed tools down the plugin-tool branch with `inputSchema: undefined` (LangChain then crashes in\n * json-schema validation). {@link NodeBackedToolConfig#toolKind} is stable across copies.\n */\n private isNodeBackedToolConfig(config: ToolConfig): config is NodeBackedToolConfig<any, any, any> {\n return (\n config instanceof NodeBackedToolConfig ||\n (typeof config === \"object\" && config !== null && (config as { toolKind?: unknown }).toolKind === \"nodeBacked\")\n );\n }\n\n /**\n * Callable tools use {@link CallableToolConfig#toolKind} for cross-package / JSON round-trip safety.\n */\n private isCallableToolConfig(config: ToolConfig): config is CallableToolConfig<ZodSchemaAny, ZodSchemaAny> {\n return (\n config instanceof CallableToolConfig ||\n (typeof config === \"object\" && config !== null && (config as { toolKind?: unknown }).toolKind === \"callable\")\n );\n }\n\n private resolveGuardrails(guardrails: AgentGuardrailConfig | undefined): ResolvedGuardrails {\n const maxTurns = guardrails?.maxTurns ?? AgentGuardrailDefaults.maxTurns;\n if (!Number.isInteger(maxTurns) || maxTurns < 1) {\n throw new Error(`AIAgent maxTurns must be a positive integer. Received: ${String(maxTurns)}`);\n }\n return {\n maxTurns,\n onTurnLimitReached: guardrails?.onTurnLimitReached ?? AgentGuardrailDefaults.onTurnLimitReached,\n modelInvocationOptions: guardrails?.modelInvocationOptions,\n };\n }\n\n private getAgentDisplayName(ctx: NodeExecutionContext<AIAgent<any, any>>): string {\n return ctx.config.name ?? ctx.nodeId;\n }\n\n private extractErrorDetails(error: Error): JsonValue | undefined {\n const candidate = error as Error & { details?: JsonValue };\n return candidate.details;\n }\n}\n","import {\n RetryPolicy,\n type AgentGuardrailConfig,\n type AgentMessageConfig,\n type AgentNodeConfig,\n type ChatModelConfig,\n type RetryPolicySpec,\n type RunnableNodeConfig,\n type ToolConfig,\n type TypeToken,\n} from \"@codemation/core\";\nimport type { ZodType } from \"zod\";\n\nimport { AIAgentNode } from \"./AIAgentNode\";\n\nexport interface AIAgentOptions<TInputJson = unknown, _TOutputJson = unknown> {\n readonly name: string;\n readonly messages: AgentMessageConfig<TInputJson>;\n readonly chatModel: ChatModelConfig;\n readonly tools?: ReadonlyArray<ToolConfig>;\n readonly id?: string;\n readonly retryPolicy?: RetryPolicySpec;\n readonly guardrails?: AgentGuardrailConfig;\n /** Engine applies with {@link RunnableNodeConfig.inputSchema} before {@link AIAgentNode.execute}. */\n readonly inputSchema?: ZodType<TInputJson>;\n readonly outputSchema?: ZodType<_TOutputJson>;\n}\n\n/**\n * AI agent: credential bindings are keyed to connection-owned LLM/tool node ids (ConnectionNodeIdFactory),\n * not to the agent workflow node id.\n */\nexport class AIAgent<TInputJson = unknown, TOutputJson = unknown>\n implements RunnableNodeConfig<TInputJson, TOutputJson>, AgentNodeConfig<TInputJson, TOutputJson>\n{\n readonly kind = \"node\" as const;\n readonly type: TypeToken<unknown> = AIAgentNode;\n readonly execution = { hint: \"local\" } as const;\n readonly icon = \"lucide:bot\" as const;\n readonly name: string;\n readonly messages: AgentMessageConfig<TInputJson>;\n readonly chatModel: ChatModelConfig;\n readonly tools: ReadonlyArray<ToolConfig>;\n readonly id?: string;\n readonly retryPolicy: RetryPolicySpec;\n readonly guardrails?: AgentGuardrailConfig;\n readonly inputSchema?: ZodType<TInputJson>;\n readonly outputSchema?: ZodType<TOutputJson>;\n\n constructor(options: AIAgentOptions<TInputJson, TOutputJson>) {\n this.name = options.name;\n this.messages = options.messages;\n this.chatModel = options.chatModel;\n this.tools = options.tools ?? [];\n this.id = options.id;\n this.retryPolicy = options.retryPolicy ?? RetryPolicy.defaultForAiAgent;\n this.guardrails = options.guardrails;\n this.inputSchema = options.inputSchema;\n this.outputSchema = options.outputSchema;\n }\n}\n","import type { Items, PortsEmission } from \"@codemation/core\";\nimport { emitPorts, isPortsEmission } from \"@codemation/core\";\n\nexport class CallbackResultNormalizer {\n static toPortsEmission(result: Items | PortsEmission | void, items: Items): PortsEmission {\n if (isPortsEmission(result)) {\n return result;\n }\n return emitPorts({ main: result ?? items });\n }\n}\n","import type { RunnableNode, RunnableNodeExecuteArgs } from \"@codemation/core\";\nimport { node } from \"@codemation/core\";\n\nimport { Callback } from \"./CallbackNodeFactory\";\nimport { CallbackResultNormalizer } from \"./CallbackResultNormalizerFactory\";\n\n@node({ packageName: \"@codemation/core-nodes\" })\nexport class CallbackNode implements RunnableNode<Callback<any, any>> {\n kind = \"node\" as const;\n outputPorts = [\"main\"] as const;\n\n async execute(args: RunnableNodeExecuteArgs<Callback<any, any>>): Promise<unknown> {\n const items = args.items ?? [];\n const ctx = args.ctx;\n const config = ctx.config;\n if (config == null) {\n throw new Error(\"CallbackNode: missing ctx.config (engine should always pass runnable config)\");\n }\n if (items.length === 0) {\n const result = await config.callback(items, ctx);\n return CallbackResultNormalizer.toPortsEmission(result, items);\n }\n if (args.itemIndex !== items.length - 1) {\n return [];\n }\n const result = await config.callback(items, ctx);\n return CallbackResultNormalizer.toPortsEmission(result, items);\n }\n}\n","import type {\n Items,\n NodeExecutionContext,\n NodeErrorHandlerSpec,\n PortsEmission,\n RetryPolicySpec,\n RunnableNodeConfig,\n TypeToken,\n} from \"@codemation/core\";\n\nimport { CallbackNode } from \"./CallbackNode\";\n\nexport type CallbackHandler<\n TInputJson = unknown,\n TOutputJson = TInputJson,\n TConfig extends Callback<TInputJson, TOutputJson> = Callback<TInputJson, TOutputJson>,\n> = (\n items: Items<TInputJson>,\n ctx: NodeExecutionContext<TConfig>,\n) => Promise<Items<TOutputJson> | PortsEmission | void> | Items<TOutputJson> | PortsEmission | void;\n\nexport type CallbackOptions = Readonly<{\n id?: string;\n retryPolicy?: RetryPolicySpec;\n nodeErrorHandler?: NodeErrorHandlerSpec;\n declaredOutputPorts?: ReadonlyArray<string>;\n}>;\n\nexport class Callback<TInputJson = unknown, TOutputJson = TInputJson> implements RunnableNodeConfig<\n TInputJson,\n TOutputJson\n> {\n readonly kind = \"node\" as const;\n readonly type: TypeToken<unknown> = CallbackNode;\n readonly execution = { hint: \"local\" } as const;\n readonly icon = \"lucide:braces\" as const;\n readonly emptyBatchExecution = \"runOnce\" as const;\n readonly id?: string;\n readonly retryPolicy?: RetryPolicySpec;\n readonly nodeErrorHandler?: NodeErrorHandlerSpec;\n readonly declaredOutputPorts?: ReadonlyArray<string>;\n\n constructor(\n public readonly name: string = \"Callback\",\n public readonly callback: CallbackHandler<TInputJson, TOutputJson> = Callback.defaultCallback as CallbackHandler<\n TInputJson,\n TOutputJson\n >,\n idOrOptions?: string | CallbackOptions,\n options?: CallbackOptions,\n ) {\n const resolvedOptions = typeof idOrOptions === \"string\" ? { ...options, id: idOrOptions } : idOrOptions;\n this.id = resolvedOptions?.id;\n this.retryPolicy = resolvedOptions?.retryPolicy;\n this.nodeErrorHandler = resolvedOptions?.nodeErrorHandler;\n this.declaredOutputPorts = resolvedOptions?.declaredOutputPorts;\n }\n\n private static defaultCallback<TItemJson>(items: Items<TItemJson>): Items<TItemJson> {\n return items;\n }\n}\n\nexport { CallbackNode } from \"./CallbackNode\";\nexport { CallbackResultNormalizer } from \"./CallbackResultNormalizerFactory\";\n","import type { Item, NodeExecutionContext, RunnableNode, RunnableNodeExecuteArgs } from \"@codemation/core\";\n\nimport { node } from \"@codemation/core\";\n\nimport type { HttpRequestDownloadMode } from \"./httpRequest\";\nimport { HttpRequest } from \"./httpRequest\";\n\n@node({ packageName: \"@codemation/core-nodes\" })\nexport class HttpRequestNode implements RunnableNode<HttpRequest<any, any>> {\n readonly kind = \"node\" as const;\n readonly outputPorts = [\"main\"] as const;\n\n async execute(args: RunnableNodeExecuteArgs<HttpRequest<any, any>>): Promise<unknown> {\n return await this.executeItem(args.item, args.ctx);\n }\n\n private async executeItem(item: Item, ctx: NodeExecutionContext<HttpRequest<any, any>>): Promise<Item> {\n const url = this.resolveUrl(item, ctx);\n const response = await fetch(url, {\n method: ctx.config.method,\n });\n const headers = this.readHeaders(response.headers);\n const mimeType = this.resolveMimeType(headers);\n const bodyBinaryName = ctx.config.binaryName;\n const shouldAttachBody = this.shouldAttachBody(ctx.config.downloadMode, mimeType);\n const outputJson: Readonly<Record<string, unknown>> = {\n url,\n method: ctx.config.method,\n ok: response.ok,\n status: response.status,\n statusText: response.statusText,\n mimeType,\n headers,\n ...(shouldAttachBody ? { bodyBinaryName } : {}),\n };\n\n let outputItem: Item = {\n json: outputJson,\n };\n if (!shouldAttachBody) {\n return outputItem;\n }\n\n const attachment = await ctx.binary.attach({\n name: bodyBinaryName,\n body: response.body\n ? (response.body as unknown as Parameters<typeof ctx.binary.attach>[0][\"body\"])\n : new Uint8Array(await response.arrayBuffer()),\n mimeType,\n filename: this.resolveFilename(url, headers),\n });\n outputItem = ctx.binary.withAttachment(outputItem, bodyBinaryName, attachment);\n return outputItem;\n }\n\n private resolveUrl(item: Item, ctx: NodeExecutionContext<HttpRequest<any, any>>): string {\n const json = this.asRecord(item.json);\n const candidate = json[ctx.config.urlField];\n if (typeof candidate !== \"string\" || candidate.trim() === \"\") {\n throw new Error(`HttpRequest node expected item.json.${ctx.config.urlField} to contain a URL string.`);\n }\n return candidate;\n }\n\n private asRecord(value: unknown): Readonly<Record<string, unknown>> {\n if (value && typeof value === \"object\" && !Array.isArray(value)) {\n return value as Readonly<Record<string, unknown>>;\n }\n return { input: value };\n }\n\n private readHeaders(headers: Headers): Readonly<Record<string, string>> {\n const values: Record<string, string> = {};\n headers.forEach((value, key) => {\n values[key] = value;\n });\n return values;\n }\n\n private resolveMimeType(headers: Readonly<Record<string, string>>): string {\n const contentType = headers[\"content-type\"];\n if (!contentType) {\n return \"application/octet-stream\";\n }\n return contentType.split(\";\")[0]?.trim() || \"application/octet-stream\";\n }\n\n private shouldAttachBody(mode: HttpRequestDownloadMode, mimeType: string): boolean {\n if (mode === \"always\") {\n return true;\n }\n if (mode === \"never\") {\n return false;\n }\n return mimeType.startsWith(\"image/\") || mimeType.startsWith(\"audio/\") || mimeType.startsWith(\"video/\");\n }\n\n private resolveFilename(url: string, headers: Readonly<Record<string, string>>): string | undefined {\n const contentDisposition = headers[\"content-disposition\"];\n const fromDisposition = this.readFilenameFromContentDisposition(contentDisposition);\n if (fromDisposition) {\n return fromDisposition;\n }\n const pathname = new URL(url).pathname;\n const value = pathname.split(\"/\").at(-1);\n return value && value.trim() ? value : undefined;\n }\n\n private readFilenameFromContentDisposition(value: string | undefined): string | undefined {\n if (!value) {\n return undefined;\n }\n const parts = value.split(\";\");\n for (const part of parts) {\n const trimmed = part.trim();\n if (!trimmed.startsWith(\"filename=\")) {\n continue;\n }\n return trimmed.slice(\"filename=\".length).replace(/^\"|\"$/g, \"\");\n }\n return undefined;\n }\n}\n","import { RetryPolicy, type RetryPolicySpec, type RunnableNodeConfig, type TypeToken } from \"@codemation/core\";\n\nimport { HttpRequestNode } from \"./HttpRequestNodeFactory\";\n\nexport type HttpRequestDownloadMode = \"auto\" | \"always\" | \"never\";\n\n/** JSON emitted by {@link HttpRequest} — response metadata only (input item fields are not passed through). */\nexport type HttpRequestOutputJson = Readonly<{\n url: string;\n method: string;\n ok: boolean;\n status: number;\n statusText: string;\n mimeType: string;\n headers: Readonly<Record<string, string>>;\n bodyBinaryName?: string;\n}>;\n\nexport class HttpRequest<\n TInputJson = Readonly<{ url?: string }>,\n TOutputJson = HttpRequestOutputJson,\n> implements RunnableNodeConfig<TInputJson, TOutputJson> {\n readonly kind = \"node\" as const;\n readonly type: TypeToken<unknown> = HttpRequestNode;\n readonly execution = { hint: \"local\" } as const;\n\n constructor(\n public readonly name: string,\n public readonly args: Readonly<{\n method?: string;\n urlField?: string;\n binaryName?: string;\n downloadMode?: HttpRequestDownloadMode;\n id?: string;\n }> = {},\n public readonly retryPolicy: RetryPolicySpec = RetryPolicy.defaultForHttp,\n ) {}\n\n get id(): string | undefined {\n return this.args.id;\n }\n\n get method(): string {\n return (this.args.method ?? \"GET\").toUpperCase();\n }\n\n get urlField(): string {\n return this.args.urlField ?? \"url\";\n }\n\n get binaryName(): string {\n return this.args.binaryName ?? \"body\";\n }\n\n get downloadMode(): HttpRequestDownloadMode {\n return this.args.downloadMode ?? \"auto\";\n }\n}\n\nexport { HttpRequestNode } from \"./HttpRequestNodeFactory\";\n","import type { RunnableNode, RunnableNodeExecuteArgs } from \"@codemation/core\";\n\nimport { node } from \"@codemation/core\";\n\nimport type { Aggregate } from \"./aggregate\";\n\n@node({ packageName: \"@codemation/core-nodes\" })\nexport class AggregateNode implements RunnableNode<Aggregate<any, any>> {\n kind = \"node\" as const;\n outputPorts = [\"main\"] as const;\n\n async execute(args: RunnableNodeExecuteArgs<Aggregate<any, any>>): Promise<unknown> {\n if (args.itemIndex !== args.items.length - 1) {\n return [];\n }\n return Promise.resolve(args.ctx.config.aggregate(args.items, args.ctx));\n }\n}\n","import type { Items, NodeExecutionContext, RunnableNodeConfig, TypeToken } from \"@codemation/core\";\n\nimport { AggregateNode } from \"./AggregateNode\";\n\nexport class Aggregate<TIn = unknown, TOut = unknown> implements RunnableNodeConfig<TIn, TOut> {\n readonly kind = \"node\" as const;\n readonly type: TypeToken<unknown> = AggregateNode;\n readonly execution = { hint: \"local\" } as const;\n readonly keepBinaries = true as const;\n readonly icon = \"lucide:layers\" as const;\n\n constructor(\n public readonly name: string,\n public readonly aggregate: (\n items: Items<TIn>,\n ctx: NodeExecutionContext<Aggregate<TIn, TOut>>,\n ) => TOut | Promise<TOut>,\n public readonly id?: string,\n ) {}\n}\n\nexport { AggregateNode } from \"./AggregateNode\";\n","import type { Item, RunnableNode, RunnableNodeExecuteArgs } from \"@codemation/core\";\n\nimport { node } from \"@codemation/core\";\n\nimport type { Filter } from \"./filter\";\n\n@node({ packageName: \"@codemation/core-nodes\" })\nexport class FilterNode implements RunnableNode<Filter<any>> {\n kind = \"node\" as const;\n outputPorts = [\"main\"] as const;\n\n execute(args: RunnableNodeExecuteArgs<Filter<any>>): unknown {\n if (args.ctx.config.predicate(args.item as Item, args.itemIndex, args.items, args.ctx)) {\n return args.item;\n }\n return [];\n }\n}\n","import type { Item, Items, NodeExecutionContext, RunnableNodeConfig, TypeToken } from \"@codemation/core\";\n\nimport { FilterNode } from \"./FilterNode\";\n\nexport class Filter<TIn = unknown> implements RunnableNodeConfig<TIn, TIn> {\n readonly kind = \"node\" as const;\n readonly type: TypeToken<unknown> = FilterNode;\n readonly execution = { hint: \"local\" } as const;\n readonly icon = \"lucide:filter\" as const;\n\n constructor(\n public readonly name: string,\n public readonly predicate: (\n item: Item<TIn>,\n index: number,\n items: Items<TIn>,\n ctx: NodeExecutionContext<Filter<TIn>>,\n ) => boolean,\n public readonly id?: string,\n ) {}\n}\n\nexport { FilterNode } from \"./FilterNode\";\n","import type { InputPortKey, Item, Items, NodeId } from \"@codemation/core\";\nimport { getOriginIndexFromItem } from \"@codemation/core\";\n\nexport function getOriginIndex(item: Item): number | undefined {\n return getOriginIndexFromItem(item);\n}\n\n/**\n * Tags items routed to fan-in merge-by-origin (same contract as {@link IfNode} / {@link SwitchNode}).\n */\nexport function tagItemForRouterFanIn<TJson>(\n args: Readonly<{\n item: Item<TJson>;\n itemIndex: number;\n nodeId: NodeId;\n inputPortLabel?: string;\n }>,\n): Item<TJson> {\n const { item, itemIndex, nodeId, inputPortLabel = \"$in\" } = args;\n const metaBase = (item.meta && typeof item.meta === \"object\" ? (item.meta as Record<string, unknown>) : {}) as Record<\n string,\n unknown\n >;\n const cmBase =\n metaBase._cm && typeof metaBase._cm === \"object\"\n ? (metaBase._cm as Record<string, unknown>)\n : ({} as Record<string, unknown>);\n const originIndex = typeof cmBase.originIndex === \"number\" ? (cmBase.originIndex as number) : itemIndex;\n return {\n ...item,\n meta: { ...metaBase, _cm: { ...cmBase, originIndex } },\n paired: [{ nodeId, output: inputPortLabel, itemIndex: originIndex }, ...(item.paired ?? [])],\n };\n}\n\nexport function orderedInputs(\n inputsByPort: Readonly<Record<InputPortKey, Items>>,\n prefer?: ReadonlyArray<InputPortKey>,\n): InputPortKey[] {\n const keys = Object.keys(inputsByPort);\n const preferred = (prefer ?? []).filter((k) => keys.includes(k));\n const rest = keys.filter((k) => !preferred.includes(k)).sort();\n return [...preferred, ...rest];\n}\n","import type { RunnableNode, RunnableNodeExecuteArgs } from \"@codemation/core\";\nimport { emitPorts, node } from \"@codemation/core\";\n\nimport { If } from \"./if\";\nimport { tagItemForRouterFanIn } from \"./mergeExecutionUtils.types\";\n\n@node({ packageName: \"@codemation/core-nodes\" })\nexport class IfNode implements RunnableNode<If<any>> {\n kind = \"node\" as const;\n\n execute(args: RunnableNodeExecuteArgs<If<any>>): unknown {\n const tagged = tagItemForRouterFanIn({\n item: args.item,\n itemIndex: args.itemIndex,\n nodeId: args.ctx.nodeId,\n });\n const ok = args.ctx.config.predicate(args.item, args.itemIndex, args.items, args.ctx);\n return emitPorts({\n true: ok ? [tagged] : [],\n false: ok ? [] : [tagged],\n });\n }\n}\n","import type { Item, Items, NodeExecutionContext, RunnableNodeConfig, TypeToken } from \"@codemation/core\";\n\nimport { IfNode } from \"./IfNode\";\n\nexport class If<TInputJson = unknown> implements RunnableNodeConfig<TInputJson, TInputJson> {\n readonly kind = \"node\" as const;\n readonly type: TypeToken<unknown> = IfNode;\n readonly execution = { hint: \"local\" } as const;\n readonly icon = \"lucide:split\" as const;\n readonly declaredOutputPorts = [\"true\", \"false\"] as const;\n constructor(\n public readonly name: string,\n public readonly predicate: (\n item: Item<TInputJson>,\n index: number,\n items: Items<TInputJson>,\n ctx: NodeExecutionContext<If<TInputJson>>,\n ) => boolean,\n public readonly id?: string,\n ) {}\n}\n\nexport { IfNode } from \"./IfNode\";\n","import type { RunnableNode, RunnableNodeExecuteArgs } from \"@codemation/core\";\nimport { emitPorts, node } from \"@codemation/core\";\n\nimport type { Switch } from \"./switch\";\nimport { tagItemForRouterFanIn } from \"./mergeExecutionUtils.types\";\n\n/**\n * Routes each item to exactly one output port. Port names must match workflow edges (see {@link Switch} config).\n */\n@node({ packageName: \"@codemation/core-nodes\" })\nexport class SwitchNode implements RunnableNode<Switch<any>> {\n kind = \"node\" as const;\n\n async execute(args: RunnableNodeExecuteArgs<Switch<any>>): Promise<unknown> {\n const tagged = tagItemForRouterFanIn({\n item: args.item,\n itemIndex: args.itemIndex,\n nodeId: args.ctx.nodeId,\n });\n const key = await Promise.resolve(\n args.ctx.config.cfg.resolveCaseKey(args.item, args.itemIndex, args.items, args.ctx),\n );\n const { cases, defaultCase } = args.ctx.config.cfg;\n const port = cases.includes(key) ? key : defaultCase;\n return emitPorts({\n [port]: [tagged],\n });\n }\n}\n","import type { Item, Items, NodeExecutionContext, RunnableNodeConfig, TypeToken } from \"@codemation/core\";\n\nimport { SwitchNode } from \"./SwitchNode\";\n\nexport type SwitchCaseKeyResolver<TInputJson = unknown> = (\n item: Item<TInputJson>,\n index: number,\n items: Items<TInputJson>,\n ctx: NodeExecutionContext<Switch<TInputJson>>,\n) => string | Promise<string>;\n\nexport class Switch<TInputJson = unknown> implements RunnableNodeConfig<TInputJson, TInputJson> {\n readonly kind = \"node\" as const;\n readonly type: TypeToken<unknown> = SwitchNode;\n readonly execution = { hint: \"local\" } as const;\n readonly icon = \"lucide:git-branch-plus\" as const;\n readonly declaredOutputPorts: ReadonlyArray<string>;\n\n constructor(\n public readonly name: string,\n public readonly cfg: Readonly<{\n cases: readonly string[];\n defaultCase: string;\n resolveCaseKey: SwitchCaseKeyResolver<TInputJson>;\n }>,\n public readonly id?: string,\n ) {\n this.declaredOutputPorts = [...new Set([...cfg.cases, cfg.defaultCase])].sort();\n }\n}\n\nexport { SwitchNode } from \"./SwitchNode\";\n","import type { Item, RunnableNode, RunnableNodeExecuteArgs } from \"@codemation/core\";\n\nimport { node } from \"@codemation/core\";\n\nimport type { Split } from \"./split\";\n\n@node({ packageName: \"@codemation/core-nodes\" })\nexport class SplitNode implements RunnableNode<Split<any, any>> {\n kind = \"node\" as const;\n outputPorts = [\"main\"] as const;\n\n execute(args: RunnableNodeExecuteArgs<Split<any, any>>): unknown {\n const elements = args.ctx.config.getElements(args.item as Item, args.ctx);\n return elements;\n }\n}\n","import type { Item, NodeExecutionContext, RunnableNodeConfig, TypeToken } from \"@codemation/core\";\n\nimport { SplitNode } from \"./SplitNode\";\n\nexport class Split<TIn = unknown, TElem = unknown> implements RunnableNodeConfig<TIn, TElem> {\n readonly kind = \"node\" as const;\n readonly type: TypeToken<unknown> = SplitNode;\n readonly execution = { hint: \"local\" } as const;\n readonly keepBinaries = true as const;\n /**\n * When splitting yields zero items for a batch, downstream single-input nodes still run once with an empty batch.\n * Mirrors {@link MapData}'s empty-output behavior.\n */\n readonly continueWhenEmptyOutput = true as const;\n readonly icon = \"lucide:ungroup\" as const;\n\n constructor(\n public readonly name: string,\n public readonly getElements: (item: Item<TIn>, ctx: NodeExecutionContext<Split<TIn, TElem>>) => readonly TElem[],\n public readonly id?: string,\n ) {}\n}\n\nexport { SplitNode } from \"./SplitNode\";\n","import type {\n Items,\n NodeExecutionContext,\n NodeOutputs,\n TestableTriggerNode,\n TriggerSetupContext,\n TriggerTestItemsContext,\n} from \"@codemation/core\";\n\nimport { node } from \"@codemation/core\";\n\nimport { ManualTrigger } from \"./ManualTriggerFactory\";\n\n/**\n * Setup is intentionally a no-op: the engine host can run workflows manually\n * by calling `engine.runWorkflow(workflow, triggerNodeId, items)`.\n */\n@node({ packageName: \"@codemation/core-nodes\" })\nexport class ManualTriggerNode implements TestableTriggerNode<ManualTrigger<any>> {\n kind = \"trigger\" as const;\n outputPorts = [\"main\"] as const;\n async setup(_ctx: TriggerSetupContext<ManualTrigger<any>>): Promise<undefined> {\n return undefined;\n }\n\n async getTestItems(ctx: TriggerTestItemsContext<ManualTrigger<any>>): Promise<Items> {\n return this.resolveManualItems([], ctx.config);\n }\n\n async execute(items: Items, ctx: NodeExecutionContext<ManualTrigger<any>>): Promise<NodeOutputs> {\n return { main: this.resolveManualItems(items, ctx.config) };\n }\n\n private resolveManualItems(items: Items, config: ManualTrigger<any>): Items {\n return items.length > 0 ? items : (config.defaultItems ?? []);\n }\n}\n","import type { Items, TriggerNodeConfig, TypeToken } from \"@codemation/core\";\n\nimport { ItemsInputNormalizer } from \"@codemation/core\";\n\nimport { ManualTriggerNode } from \"./ManualTriggerNode\";\n\ntype ManualTriggerDefaultValue<TOutputJson> = Items<TOutputJson> | ReadonlyArray<TOutputJson> | TOutputJson;\n\nexport class ManualTrigger<TOutputJson = unknown> implements TriggerNodeConfig<TOutputJson> {\n private static readonly itemsInputNormalizer = new ItemsInputNormalizer();\n readonly kind = \"trigger\" as const;\n readonly type: TypeToken<unknown> = ManualTriggerNode;\n readonly icon = \"lucide:play\" as const;\n readonly defaultItems?: Items<TOutputJson>;\n readonly id?: string;\n /** Manual runs often emit an empty batch; still schedule downstream by default. */\n readonly continueWhenEmptyOutput = true as const;\n\n constructor(name?: string, id?: string);\n constructor(name: string, defaultItems: ManualTriggerDefaultValue<TOutputJson>, id?: string);\n constructor(\n public readonly name: string = \"Manual trigger\",\n defaultItemsOrId?: ManualTriggerDefaultValue<TOutputJson> | string,\n id?: string,\n ) {\n this.defaultItems = ManualTrigger.resolveDefaultItems(defaultItemsOrId);\n this.id = ManualTrigger.resolveId(defaultItemsOrId, id);\n }\n\n private static resolveDefaultItems<TOutputJson>(\n value: ManualTriggerDefaultValue<TOutputJson> | string | undefined,\n ): Items<TOutputJson> | undefined {\n if (typeof value === \"string\" || value === undefined) {\n return undefined;\n }\n return this.itemsInputNormalizer.normalize(value) as Items<TOutputJson>;\n }\n\n private static resolveId<TOutputJson>(\n value: ManualTriggerDefaultValue<TOutputJson> | string | undefined,\n id: string | undefined,\n ): string | undefined {\n return typeof value === \"string\" ? value : id;\n }\n}\n\nexport { ManualTriggerNode } from \"./ManualTriggerNode\";\n","import type { RunnableNode, RunnableNodeExecuteArgs } from \"@codemation/core\";\n\nimport { node } from \"@codemation/core\";\nimport { z } from \"zod\";\n\nimport { MapData } from \"./mapData\";\n\n@node({ packageName: \"@codemation/core-nodes\" })\nexport class MapDataNode implements RunnableNode<MapData<any, any>> {\n kind = \"node\" as const;\n outputPorts = [\"main\"] as const;\n readonly inputSchema = z.unknown();\n\n async execute(args: RunnableNodeExecuteArgs<MapData<any, any>>): Promise<unknown> {\n return args.ctx.config.map(args.item, args.ctx);\n }\n}\n","import type { Item, NodeExecutionContext, RunnableNodeConfig, TypeToken } from \"@codemation/core\";\n\nimport { MapDataNode } from \"./MapDataNode\";\n\nexport interface MapDataOptions {\n readonly id?: string;\n readonly keepBinaries?: boolean;\n}\n\nexport class MapData<TInputJson = unknown, TOutputJson = unknown> implements RunnableNodeConfig<\n TInputJson,\n TOutputJson\n> {\n readonly kind = \"node\" as const;\n readonly type: TypeToken<unknown> = MapDataNode;\n readonly execution = { hint: \"local\" } as const;\n /** Zero mapped items should still allow downstream nodes to run. */\n readonly continueWhenEmptyOutput = true as const;\n readonly keepBinaries: boolean;\n\n constructor(\n public readonly name: string,\n public readonly map: (\n item: Item<TInputJson>,\n ctx: NodeExecutionContext<MapData<TInputJson, TOutputJson>>,\n ) => TOutputJson,\n private readonly options: MapDataOptions = {},\n ) {\n this.keepBinaries = options.keepBinaries ?? true;\n }\n\n get id(): string | undefined {\n return this.options.id;\n }\n}\n\nexport { MapDataNode } from \"./MapDataNode\";\n","import type { InputPortKey, Item, Items, MultiInputNode, NodeExecutionContext, NodeOutputs } from \"@codemation/core\";\n\nimport { node } from \"@codemation/core\";\n\nimport type { Merge } from \"./merge\";\nimport { getOriginIndex, orderedInputs } from \"./mergeExecutionUtils.types\";\n\n@node({ packageName: \"@codemation/core-nodes\" })\nexport class MergeNode implements MultiInputNode<Merge<any, any>> {\n kind = \"node\" as const;\n outputPorts = [\"main\"] as const;\n\n async executeMulti(\n inputsByPort: Readonly<Record<InputPortKey, Items>>,\n ctx: NodeExecutionContext<Merge<any, any>>,\n ): Promise<NodeOutputs> {\n const order = orderedInputs(inputsByPort, ctx.config.cfg.prefer);\n\n if (ctx.config.cfg.mode === \"append\") {\n const out: Item[] = [];\n for (const k of order) out.push(...(inputsByPort[k] ?? []));\n return { main: out };\n }\n\n if (ctx.config.cfg.mode === \"mergeByPosition\") {\n let maxLen = 0;\n for (const k of order) maxLen = Math.max(maxLen, (inputsByPort[k] ?? []).length);\n\n const out: Item[] = [];\n for (let i = 0; i < maxLen; i++) {\n const json: Record<string, unknown> = {};\n const paired: any[] = [];\n let meta: Record<string, unknown> | undefined;\n\n for (const k of order) {\n const item = (inputsByPort[k] ?? [])[i];\n json[k] = item?.json;\n if (item?.paired) paired.push(...item.paired);\n if (!meta && item?.meta) meta = { ...(item.meta as any) };\n }\n\n const merged: any = { json };\n if (paired.length > 0) merged.paired = paired;\n if (meta) merged.meta = meta;\n out.push(merged as Item);\n }\n\n return { main: out };\n }\n\n // passThrough (default): for each origin index, take first available input (deterministic input precedence).\n const chosenByOrigin = new Map<number, Item>();\n const fallback: Item[] = [];\n\n for (const k of order) {\n for (const item of inputsByPort[k] ?? []) {\n const origin = getOriginIndex(item);\n if (origin === undefined) {\n fallback.push(item);\n continue;\n }\n if (!chosenByOrigin.has(origin)) chosenByOrigin.set(origin, item);\n }\n }\n\n const out: Item[] = [];\n const origins = Array.from(chosenByOrigin.keys()).sort((a, b) => a - b);\n for (const o of origins) out.push(chosenByOrigin.get(o)!);\n out.push(...fallback);\n\n return { main: out };\n }\n}\n","import type { InputPortKey, RunnableNodeConfig, TypeToken } from \"@codemation/core\";\n\nimport { MergeNode } from \"./MergeNode\";\n\nexport type MergeMode = \"passThrough\" | \"append\" | \"mergeByPosition\";\n\nexport class Merge<TInputJson = unknown, TOutputJson = TInputJson> implements RunnableNodeConfig<\n TInputJson,\n TOutputJson\n> {\n readonly kind = \"node\" as const;\n readonly type: TypeToken<unknown> = MergeNode;\n readonly icon = \"lucide:git-merge\" as const;\n\n constructor(\n public readonly name: string,\n public readonly cfg: Readonly<{\n mode: MergeMode;\n /**\n * Deterministic input precedence order (only used for passThrough/append).\n * Any inputs not listed are appended in lexicographic order.\n */\n prefer?: ReadonlyArray<InputPortKey>;\n }> = { mode: \"passThrough\" },\n public readonly id?: string,\n ) {}\n}\n\nexport { MergeNode } from \"./MergeNode\";\n","import type { RunnableNode, RunnableNodeExecuteArgs } from \"@codemation/core\";\n\nimport { node } from \"@codemation/core\";\n\nimport { NoOp } from \"./noOp\";\n\n@node({ packageName: \"@codemation/core-nodes\" })\nexport class NoOpNode implements RunnableNode<NoOp<any>> {\n kind = \"node\" as const;\n outputPorts = [\"main\"] as const;\n\n execute(args: RunnableNodeExecuteArgs<NoOp<any>>): unknown {\n return args.item;\n }\n}\n","import type { RunnableNodeConfig, TypeToken } from \"@codemation/core\";\n\nimport { NoOpNode } from \"./NoOpNode\";\n\nexport class NoOp<TItemJson = unknown> implements RunnableNodeConfig<TItemJson, TItemJson> {\n readonly kind = \"node\" as const;\n readonly type: TypeToken<unknown> = NoOpNode;\n readonly execution = { hint: \"local\" } as const;\n\n constructor(\n public readonly name: string = \"NoOp\",\n public readonly id?: string,\n ) {}\n}\n\nexport { NoOpNode } from \"./NoOpNode\";\n","import type { Item, RunnableNode, RunnableNodeExecuteArgs, WorkflowRunnerService } from \"@codemation/core\";\nimport { CoreTokens, emitPorts, inject, node } from \"@codemation/core\";\n\nimport { SubWorkflow } from \"./subWorkflow\";\n\n@node({ packageName: \"@codemation/core-nodes\" })\nexport class SubWorkflowNode implements RunnableNode<SubWorkflow<any, any>> {\n kind = \"node\" as const;\n outputPorts = [\"main\"] as const;\n\n constructor(\n @inject(CoreTokens.WorkflowRunnerService)\n private readonly workflows: WorkflowRunnerService,\n ) {}\n\n async execute(args: RunnableNodeExecuteArgs<SubWorkflow<any, any>>): Promise<unknown> {\n const current = args.item as Item;\n const metaBase = (\n current.meta && typeof current.meta === \"object\" ? (current.meta as Record<string, unknown>) : {}\n ) as Record<string, unknown>;\n const cmBase =\n metaBase._cm && typeof metaBase._cm === \"object\"\n ? (metaBase._cm as Record<string, unknown>)\n : ({} as Record<string, unknown>);\n const originIndex = typeof cmBase.originIndex === \"number\" ? (cmBase.originIndex as number) : undefined;\n\n const result = await this.workflows.runById({\n workflowId: args.ctx.config.workflowId,\n startAt: args.ctx.config.startAt,\n items: [current],\n parent: {\n runId: args.ctx.runId,\n workflowId: args.ctx.workflowId,\n nodeId: args.ctx.nodeId,\n subworkflowDepth: args.ctx.subworkflowDepth,\n engineMaxNodeActivations: args.ctx.engineMaxNodeActivations,\n engineMaxSubworkflowDepth: args.ctx.engineMaxSubworkflowDepth,\n },\n });\n if (result.status !== \"completed\") {\n throw new Error(`Subworkflow ${args.ctx.config.workflowId} did not complete (status=${result.status})`);\n }\n const out: Item[] = [];\n for (const produced of result.outputs) {\n const childMetaBase =\n produced.meta && typeof produced.meta === \"object\"\n ? (produced.meta as Record<string, unknown>)\n : ({} as Record<string, unknown>);\n const childCmBase =\n childMetaBase._cm && typeof childMetaBase._cm === \"object\"\n ? (childMetaBase._cm as Record<string, unknown>)\n : ({} as Record<string, unknown>);\n\n out.push({\n ...produced,\n meta: originIndex === undefined ? childMetaBase : { ...childMetaBase, _cm: { ...childCmBase, originIndex } },\n paired: current.paired ?? produced.paired,\n });\n }\n\n return emitPorts({ main: out });\n }\n}\n","import type { NodeId, RunnableNodeConfig, TypeToken, UpstreamRefPlaceholder } from \"@codemation/core\";\n\nimport { SubWorkflowNode } from \"./SubWorkflowNode\";\n\nexport class SubWorkflow<TInputJson = unknown, TOutputJson = unknown> implements RunnableNodeConfig<\n TInputJson,\n TOutputJson\n> {\n readonly kind = \"node\" as const;\n readonly type: TypeToken<unknown> = SubWorkflowNode;\n constructor(\n public readonly name: string,\n public readonly workflowId: string,\n public upstreamRefs?: Array<{ nodeId: NodeId } | UpstreamRefPlaceholder>,\n public readonly startAt?: NodeId,\n public readonly id?: string,\n ) {}\n}\n\nexport { SubWorkflowNode } from \"./SubWorkflowNode\";\n","export class WaitDuration {\n static normalize(milliseconds: number): number {\n return Number.isFinite(milliseconds) && milliseconds > 0 ? Math.floor(milliseconds) : 0;\n }\n}\n","import type { RunnableNode, RunnableNodeExecuteArgs } from \"@codemation/core\";\n\nimport { node } from \"@codemation/core\";\n\nimport { Wait } from \"./wait\";\nimport { WaitDuration } from \"./WaitDurationFactory\";\n\n@node({ packageName: \"@codemation/core-nodes\" })\nexport class WaitNode implements RunnableNode<Wait<any>> {\n kind = \"node\" as const;\n outputPorts = [\"main\"] as const;\n\n async execute(args: RunnableNodeExecuteArgs<Wait<any>>): Promise<unknown> {\n if (args.itemIndex === 0) {\n const milliseconds = WaitDuration.normalize(args.ctx.config.milliseconds);\n if (milliseconds > 0) {\n await new Promise<void>((resolve) => {\n setTimeout(resolve, milliseconds);\n });\n }\n }\n return args.item;\n }\n}\n","import type { RunnableNodeConfig, TypeToken } from \"@codemation/core\";\n\nimport { WaitNode } from \"./WaitNode\";\n\nexport class Wait<TItemJson = unknown> implements RunnableNodeConfig<TItemJson, TItemJson> {\n readonly kind = \"node\" as const;\n readonly type: TypeToken<unknown> = WaitNode;\n readonly execution = { hint: \"local\" } as const;\n /** Pass-through empty batches should still advance to downstream nodes. */\n readonly continueWhenEmptyOutput = true as const;\n\n constructor(\n public readonly name: string,\n public readonly milliseconds: number,\n public readonly id?: string,\n ) {}\n}\n\nexport { WaitDuration } from \"./WaitDurationFactory\";\nexport { WaitNode } from \"./WaitNode\";\n","import type { Items, WebhookControlSignal } from \"@codemation/core\";\n\nexport class WebhookRespondNowAndContinueError extends Error implements WebhookControlSignal {\n readonly __webhookControl = true as const;\n readonly kind = \"respondNowAndContinue\" as const;\n\n constructor(\n public readonly responseItems: Items,\n public readonly continueItems: Items,\n message: string = \"Webhook responded immediately and continued the run.\",\n ) {\n super(message);\n this.name = \"WebhookRespondNowAndContinueError\";\n }\n}\n","import type { Items, WebhookControlSignal } from \"@codemation/core\";\n\nexport class WebhookRespondNowError extends Error implements WebhookControlSignal {\n readonly __webhookControl = true as const;\n readonly kind = \"respondNow\" as const;\n\n constructor(\n public readonly responseItems: Items,\n message: string = \"Webhook responded immediately.\",\n ) {\n super(message);\n this.name = \"WebhookRespondNowError\";\n }\n}\n","import type {\n ExecutableTriggerNode,\n Items,\n NodeExecutionContext,\n NodeOutputs,\n TriggerSetupContext,\n} from \"@codemation/core\";\nimport { node } from \"@codemation/core\";\nimport { WebhookTrigger } from \"./WebhookTriggerFactory\";\n\n/**\n * HTTP webhooks are not registered in trigger setup. The host exposes a single catch-all route\n * (e.g. `/api/webhooks/:endpointPath`); the engine's catalog-backed webhook matcher resolves the\n * user-defined endpoint path to this workflow + node, then runs the workflow from this trigger.\n */\n@node({ packageName: \"@codemation/core-nodes\" })\nexport class WebhookTriggerNode implements ExecutableTriggerNode<WebhookTrigger<any>> {\n readonly kind = \"trigger\" as const;\n readonly outputPorts = [\"main\"] as const;\n\n async setup(_ctx: TriggerSetupContext<WebhookTrigger<any>>): Promise<undefined> {\n return undefined;\n }\n\n async execute(items: Items, _ctx: NodeExecutionContext<WebhookTrigger<any>>): Promise<NodeOutputs> {\n if (items.length === 0) {\n throw new Error(\n `Webhook trigger \"${_ctx.config.name}\" requires a webhook request. Invoke this workflow through its webhook endpoint until manual request simulation is supported.`,\n );\n }\n const result = await _ctx.config.handler(items, _ctx);\n return { main: result ?? items };\n }\n}\n","import type { HttpMethod, Items, NodeExecutionContext, TriggerNodeConfig, TypeToken } from \"@codemation/core\";\nimport type { ZodType } from \"zod\";\nimport { WebhookTriggerNode } from \"./webhookTriggerNode\";\n\ntype WebhookInputSchema = ZodType<any, any, any>;\ntype WebhookTriggerHandler<TConfig extends WebhookTrigger<any> = WebhookTrigger<any>> = (\n items: Items,\n ctx: NodeExecutionContext<TConfig>,\n) => Promise<Items | void> | Items | void;\n\nexport class WebhookTrigger<\n TSchema extends WebhookInputSchema | undefined = undefined,\n> implements TriggerNodeConfig<unknown> {\n readonly kind = \"trigger\" as const;\n readonly type: TypeToken<unknown> = WebhookTriggerNode;\n readonly icon = \"lucide:globe\";\n\n constructor(\n public readonly name: string,\n private readonly args: Readonly<{\n endpointKey: string;\n methods: ReadonlyArray<HttpMethod>;\n inputSchema?: TSchema;\n }>,\n public readonly handler: WebhookTriggerHandler<\n WebhookTrigger<TSchema>\n > = WebhookTrigger.defaultHandler as WebhookTriggerHandler<WebhookTrigger<TSchema>>,\n public readonly id?: string,\n ) {}\n\n get endpointKey(): string {\n return this.args.endpointKey;\n }\n\n get methods(): ReadonlyArray<HttpMethod> {\n return this.args.methods;\n }\n\n get inputSchema(): TSchema | undefined {\n return this.args.inputSchema;\n }\n\n parseJsonBody(body: unknown): unknown {\n if (!this.args.inputSchema) return body;\n return this.args.inputSchema.parse(body);\n }\n\n private static defaultHandler(items: Items): Items {\n return items;\n }\n}\n","import type { RunnableNode, RunnableNodeExecuteArgs } from \"@codemation/core\";\nimport { node } from \"@codemation/core\";\n\nimport type { ConnectionCredentialNodeConfig } from \"./ConnectionCredentialNodeConfig\";\n\n/**\n * Placeholder runnable node for connection-owned workflow nodes (LLM/tool slots).\n * The engine does not schedule these; they exist for credentials, tokens, and UI identity.\n */\n@node({ packageName: \"@codemation/core-nodes\" })\nexport class ConnectionCredentialNode implements RunnableNode<ConnectionCredentialNodeConfig> {\n kind = \"node\" as const;\n outputPorts = [\"main\"] as const;\n\n execute(_args: RunnableNodeExecuteArgs<ConnectionCredentialNodeConfig>): unknown {\n return [];\n }\n}\n","import type { Container } from \"@codemation/core\";\nimport { AIAgentExecutionHelpersFactory, AIAgentNode } from \"./nodes/aiAgent\";\nimport { CallbackNode } from \"./nodes/CallbackNodeFactory\";\nimport { HttpRequestNode } from \"./nodes/httpRequest\";\nimport { IfNode } from \"./nodes/if\";\nimport { ManualTriggerNode } from \"./nodes/ManualTriggerFactory\";\nimport { MapDataNode } from \"./nodes/mapData\";\nimport { NoOpNode } from \"./nodes/noOp\";\nimport { SubWorkflowNode } from \"./nodes/subWorkflow\";\nimport { WaitNode } from \"./nodes/wait\";\nimport { ConnectionCredentialNode } from \"./nodes/ConnectionCredentialNode\";\nimport { AggregateNode } from \"./nodes/aggregate\";\nimport { FilterNode } from \"./nodes/filter\";\nimport { SplitNode } from \"./nodes/split\";\nimport { SwitchNode } from \"./nodes/switch\";\n\n/**\n * Registrar for built-in nodes. In a real project, this would use tsyringe's\n * container.registerSingleton(...). For the skeleton we keep it token-based:\n * the engine resolves node implementations by class token.\n */\nexport function registerCoreNodes(container: Container): void {\n // With class tokens, resolving registers happen via the DI container setup.\n // This function exists as the standardized extension point.\n void container;\n\n // Example: if using tsyringe, you'd do:\n // tsyringeContainer.registerSingleton(IfNode, IfNode);\n // ...\n void IfNode;\n void HttpRequestNode;\n void CallbackNode;\n void MapDataNode;\n void NoOpNode;\n void SubWorkflowNode;\n void ManualTriggerNode;\n void AIAgentNode;\n void AIAgentExecutionHelpersFactory;\n void WaitNode;\n void ConnectionCredentialNode;\n void SplitNode;\n void FilterNode;\n void AggregateNode;\n void SwitchNode;\n}\n","import type { WorkflowId } from \"@codemation/core\";\nimport { WorkflowBuilder } from \"@codemation/core\";\n\nexport function createWorkflowBuilder(meta: Readonly<{ id: WorkflowId; name: string }>): WorkflowBuilder {\n return new WorkflowBuilder(meta);\n}\n","import type { ChatModelConfig } from \"@codemation/core\";\nimport { OpenAIChatModelConfig } from \"../chatModels/openAiChatModelConfig\";\n\nexport class WorkflowChatModelFactory {\n static create(model: string | ChatModelConfig): ChatModelConfig {\n if (typeof model !== \"string\") {\n return model;\n }\n const [provider, resolvedModel] = model.includes(\":\") ? model.split(\":\", 2) : [\"openai\", model];\n if (provider !== \"openai\") {\n throw new Error(`Unsupported workflow().agent() model provider \"${provider}\".`);\n }\n return new OpenAIChatModelConfig(\"OpenAI\", resolvedModel);\n }\n}\n","import { z } from \"zod\";\nimport { AIAgent } from \"../nodes/AIAgentConfig\";\nimport type { WorkflowAgentOptions } from \"./WorkflowAuthoringOptions.types\";\nimport { WorkflowChatModelFactory } from \"./WorkflowChatModelFactory.types\";\n\nexport class WorkflowAgentNodeFactory {\n static create<TCurrentJson, TOutputSchema extends z.ZodTypeAny | undefined>(\n nameOrOptions: string | WorkflowAgentOptions<TCurrentJson, TOutputSchema>,\n optionsOrUndefined?: WorkflowAgentOptions<TCurrentJson, TOutputSchema>,\n ): AIAgent<TCurrentJson, TOutputSchema extends z.ZodTypeAny ? z.output<TOutputSchema> : Record<string, unknown>> {\n const options = typeof nameOrOptions === \"string\" ? optionsOrUndefined! : nameOrOptions;\n const name = typeof nameOrOptions === \"string\" ? nameOrOptions : \"AI agent\";\n const outputSchema = options.outputSchema as\n | z.ZodType<TOutputSchema extends z.ZodTypeAny ? z.output<TOutputSchema> : Record<string, unknown>>\n | undefined;\n return new AIAgent<\n TCurrentJson,\n TOutputSchema extends z.ZodTypeAny ? z.output<TOutputSchema> : Record<string, unknown>\n >({\n name,\n messages: options.messages,\n chatModel: WorkflowChatModelFactory.create(options.model),\n tools: options.tools,\n outputSchema,\n id: options.id,\n retryPolicy: options.retryPolicy,\n guardrails: options.guardrails,\n });\n }\n}\n","import { DefinedNodeRegistry, type DefinedNode } from \"@codemation/core\";\n\nexport class WorkflowDefinedNodeResolver {\n static resolve(\n definitionOrKey: DefinedNode<string, Record<string, unknown>, unknown, unknown> | string,\n ): DefinedNode<string, Record<string, unknown>, unknown, unknown> {\n if (typeof definitionOrKey !== \"string\") {\n return definitionOrKey;\n }\n const definition = DefinedNodeRegistry.resolve(definitionOrKey);\n if (!definition) {\n throw new Error(`No helper-defined node with key \"${definitionOrKey}\" is registered in this module graph.`);\n }\n return definition;\n }\n}\n","export class WorkflowDurationParser {\n static parse(duration: number | string): number {\n if (typeof duration === \"number\") {\n return Number.isFinite(duration) && duration > 0 ? Math.floor(duration) : 0;\n }\n const normalized = duration.trim().toLowerCase();\n const match = normalized.match(/^(\\d+)(ms|s|m|h)$/);\n if (!match) {\n throw new Error(\n `Unsupported wait duration \"${duration}\". Use a number of milliseconds or values like \"500ms\", \"2s\", \"5m\".`,\n );\n }\n const value = Number(match[1]);\n const unit = match[2];\n if (unit === \"ms\") {\n return value;\n }\n if (unit === \"s\") {\n return value * 1000;\n }\n if (unit === \"m\") {\n return value * 60_000;\n }\n return value * 3_600_000;\n }\n}\n","import type {\n AnyRunnableNodeConfig,\n CredentialJsonRecord,\n DefinedNode,\n DefinedNodeConfigInput,\n Item,\n Items,\n NodeExecutionContext,\n RunnableNodeConfig,\n RunnableNodeOutputJson,\n} from \"@codemation/core\";\nimport { z } from \"zod\";\nimport { Aggregate } from \"../nodes/aggregate\";\nimport { Filter } from \"../nodes/filter\";\nimport type { MapDataOptions } from \"../nodes/mapData\";\nimport { MapData } from \"../nodes/mapData\";\nimport { Split } from \"../nodes/split\";\nimport { Wait } from \"../nodes/wait\";\nimport type { WorkflowAgentOptions } from \"./WorkflowAuthoringOptions.types\";\nimport { WorkflowAgentNodeFactory } from \"./WorkflowAgentNodeFactory.types\";\nimport { WorkflowDefinedNodeResolver } from \"./WorkflowDefinedNodeResolver.types\";\nimport { WorkflowDurationParser } from \"./WorkflowDurationParser.types\";\n\ntype WorkflowMapCallback<TCurrentJson, TNextJson> = (\n item: Item<TCurrentJson>,\n ctx: NodeExecutionContext<MapData<TCurrentJson, TNextJson>>,\n) => TNextJson;\n\nexport class WorkflowBranchBuilder<TCurrentJson> {\n constructor(private readonly steps: ReadonlyArray<AnyRunnableNodeConfig> = []) {}\n\n then<TOutputJson, TConfig extends RunnableNodeConfig<TCurrentJson, TOutputJson>>(\n config: TConfig,\n ): WorkflowBranchBuilder<RunnableNodeOutputJson<TConfig>> {\n return new WorkflowBranchBuilder<RunnableNodeOutputJson<TConfig>>([...this.steps, config]);\n }\n\n map<TNextJson>(mapper: WorkflowMapCallback<TCurrentJson, TNextJson>): WorkflowBranchBuilder<TNextJson>;\n map<TNextJson>(\n name: string,\n mapper: WorkflowMapCallback<TCurrentJson, TNextJson>,\n options?: MapDataOptions,\n ): WorkflowBranchBuilder<TNextJson>;\n map<TNextJson>(\n nameOrMapper: string | WorkflowMapCallback<TCurrentJson, TNextJson>,\n mapperOrUndefined?: WorkflowMapCallback<TCurrentJson, TNextJson>,\n options?: MapDataOptions,\n ): WorkflowBranchBuilder<TNextJson> {\n const name = typeof nameOrMapper === \"string\" ? nameOrMapper : \"Map data\";\n const mapper = typeof nameOrMapper === \"string\" ? mapperOrUndefined! : nameOrMapper;\n return this.then(new MapData<TCurrentJson, TNextJson>(name, mapper, options)) as WorkflowBranchBuilder<TNextJson>;\n }\n\n wait(duration: number | string): WorkflowBranchBuilder<TCurrentJson>;\n wait(name: string, duration: number | string, id?: string): WorkflowBranchBuilder<TCurrentJson>;\n wait(\n nameOrDuration: string | number,\n durationOrUndefined?: string | number,\n id?: string,\n ): WorkflowBranchBuilder<TCurrentJson> {\n const name = typeof nameOrDuration === \"string\" && durationOrUndefined !== undefined ? nameOrDuration : \"Wait\";\n const duration = durationOrUndefined ?? nameOrDuration;\n return this.then(\n new Wait<TCurrentJson>(name, WorkflowDurationParser.parse(duration), id),\n ) as WorkflowBranchBuilder<TCurrentJson>;\n }\n\n split<TElem>(\n getElements: (item: Item<TCurrentJson>, ctx: NodeExecutionContext<Split<TCurrentJson, TElem>>) => readonly TElem[],\n ): WorkflowBranchBuilder<TElem>;\n split<TElem>(\n name: string,\n getElements: (item: Item<TCurrentJson>, ctx: NodeExecutionContext<Split<TCurrentJson, TElem>>) => readonly TElem[],\n id?: string,\n ): WorkflowBranchBuilder<TElem>;\n split<TElem>(\n nameOrGetter:\n | string\n | ((item: Item<TCurrentJson>, ctx: NodeExecutionContext<Split<TCurrentJson, TElem>>) => readonly TElem[]),\n getElementsOrUndefined?: (\n item: Item<TCurrentJson>,\n ctx: NodeExecutionContext<Split<TCurrentJson, TElem>>,\n ) => readonly TElem[],\n id?: string,\n ): WorkflowBranchBuilder<TElem> {\n const name = typeof nameOrGetter === \"string\" ? nameOrGetter : \"Split\";\n const getElements = typeof nameOrGetter === \"string\" ? getElementsOrUndefined! : nameOrGetter;\n return this.then(new Split<TCurrentJson, TElem>(name, getElements, id)) as WorkflowBranchBuilder<TElem>;\n }\n\n filter(\n predicate: (\n item: Item<TCurrentJson>,\n index: number,\n items: Items<TCurrentJson>,\n ctx: NodeExecutionContext<Filter<TCurrentJson>>,\n ) => boolean,\n ): WorkflowBranchBuilder<TCurrentJson>;\n filter(\n name: string,\n predicate: (\n item: Item<TCurrentJson>,\n index: number,\n items: Items<TCurrentJson>,\n ctx: NodeExecutionContext<Filter<TCurrentJson>>,\n ) => boolean,\n id?: string,\n ): WorkflowBranchBuilder<TCurrentJson>;\n filter(\n nameOrPredicate:\n | string\n | ((\n item: Item<TCurrentJson>,\n index: number,\n items: Items<TCurrentJson>,\n ctx: NodeExecutionContext<Filter<TCurrentJson>>,\n ) => boolean),\n predicateOrUndefined?: (\n item: Item<TCurrentJson>,\n index: number,\n items: Items<TCurrentJson>,\n ctx: NodeExecutionContext<Filter<TCurrentJson>>,\n ) => boolean,\n id?: string,\n ): WorkflowBranchBuilder<TCurrentJson> {\n const name = typeof nameOrPredicate === \"string\" ? nameOrPredicate : \"Filter\";\n const predicate = typeof nameOrPredicate === \"string\" ? predicateOrUndefined! : nameOrPredicate;\n return this.then(new Filter<TCurrentJson>(name, predicate, id)) as WorkflowBranchBuilder<TCurrentJson>;\n }\n\n aggregate<TOut>(\n aggregateFn: (\n items: Items<TCurrentJson>,\n ctx: NodeExecutionContext<Aggregate<TCurrentJson, TOut>>,\n ) => TOut | Promise<TOut>,\n ): WorkflowBranchBuilder<TOut>;\n aggregate<TOut>(\n name: string,\n aggregateFn: (\n items: Items<TCurrentJson>,\n ctx: NodeExecutionContext<Aggregate<TCurrentJson, TOut>>,\n ) => TOut | Promise<TOut>,\n id?: string,\n ): WorkflowBranchBuilder<TOut>;\n aggregate<TOut>(\n nameOrFn:\n | string\n | ((\n items: Items<TCurrentJson>,\n ctx: NodeExecutionContext<Aggregate<TCurrentJson, TOut>>,\n ) => TOut | Promise<TOut>),\n aggregateFnOrUndefined?: (\n items: Items<TCurrentJson>,\n ctx: NodeExecutionContext<Aggregate<TCurrentJson, TOut>>,\n ) => TOut | Promise<TOut>,\n id?: string,\n ): WorkflowBranchBuilder<TOut> {\n const name = typeof nameOrFn === \"string\" ? nameOrFn : \"Aggregate\";\n const aggregateFn = typeof nameOrFn === \"string\" ? aggregateFnOrUndefined! : nameOrFn;\n return this.then(new Aggregate<TCurrentJson, TOut>(name, aggregateFn, id)) as WorkflowBranchBuilder<TOut>;\n }\n\n agent<TOutputSchema extends z.ZodTypeAny>(\n options: WorkflowAgentOptions<TCurrentJson, TOutputSchema>,\n ): WorkflowBranchBuilder<z.output<TOutputSchema>>;\n agent(options: WorkflowAgentOptions<TCurrentJson, undefined>): WorkflowBranchBuilder<Record<string, unknown>>;\n agent<TOutputSchema extends z.ZodTypeAny>(\n name: string,\n options: WorkflowAgentOptions<TCurrentJson, TOutputSchema | undefined>,\n ): WorkflowBranchBuilder<TOutputSchema extends z.ZodTypeAny ? z.output<TOutputSchema> : Record<string, unknown>>;\n agent<TOutputSchema extends z.ZodTypeAny>(\n nameOrOptions: string | WorkflowAgentOptions<TCurrentJson, TOutputSchema | undefined>,\n optionsOrUndefined?: WorkflowAgentOptions<TCurrentJson, TOutputSchema | undefined>,\n ): WorkflowBranchBuilder<TOutputSchema extends z.ZodTypeAny ? z.output<TOutputSchema> : Record<string, unknown>> {\n return this.then(WorkflowAgentNodeFactory.create(nameOrOptions, optionsOrUndefined)) as WorkflowBranchBuilder<\n TOutputSchema extends z.ZodTypeAny ? z.output<TOutputSchema> : Record<string, unknown>\n >;\n }\n\n node<TConfig extends CredentialJsonRecord, TInputJson, TOutputJson>(\n definitionOrKey: DefinedNode<string, TConfig, TInputJson, TOutputJson> | string,\n config: DefinedNodeConfigInput<TConfig, TCurrentJson>,\n name?: string,\n id?: string,\n ): TCurrentJson extends TInputJson ? WorkflowBranchBuilder<TOutputJson> : never {\n const definition = WorkflowDefinedNodeResolver.resolve(\n definitionOrKey as DefinedNode<string, Record<string, unknown>, unknown, unknown> | string,\n ) as DefinedNode<string, TConfig, TInputJson, TOutputJson>;\n return this.then(\n definition.create(config, name, id) as unknown as RunnableNodeConfig<TCurrentJson, TOutputJson>,\n ) as TCurrentJson extends TInputJson ? WorkflowBranchBuilder<TOutputJson> : never;\n }\n\n getSteps(): ReadonlyArray<AnyRunnableNodeConfig> {\n return this.steps;\n }\n}\n","import type {\n CredentialJsonRecord,\n DefinedNode,\n DefinedNodeConfigInput,\n Item,\n Items,\n NodeExecutionContext,\n RunnableNodeConfig,\n RunnableNodeOutputJson,\n WorkflowDefinition,\n} from \"@codemation/core\";\nimport { ChainCursor } from \"@codemation/core\";\nimport { z } from \"zod\";\nimport { Aggregate } from \"../nodes/aggregate\";\nimport { Filter } from \"../nodes/filter\";\nimport { If } from \"../nodes/if\";\nimport type { MapDataOptions } from \"../nodes/mapData\";\nimport { MapData } from \"../nodes/mapData\";\nimport { Merge, type MergeMode } from \"../nodes/merge\";\nimport { Split } from \"../nodes/split\";\nimport { Switch } from \"../nodes/switch\";\nimport { Wait } from \"../nodes/wait\";\nimport type { WorkflowAgentOptions } from \"./WorkflowAuthoringOptions.types\";\nimport { WorkflowAgentNodeFactory } from \"./WorkflowAgentNodeFactory.types\";\nimport { WorkflowBranchBuilder } from \"./WorkflowBranchBuilder.types\";\nimport { WorkflowDefinedNodeResolver } from \"./WorkflowDefinedNodeResolver.types\";\nimport { WorkflowDurationParser } from \"./WorkflowDurationParser.types\";\n\ntype BranchCallback<TCurrentJson, TNextJson> = (\n branch: WorkflowBranchBuilder<TCurrentJson>,\n) => WorkflowBranchBuilder<TNextJson>;\ntype RouteBranchCallback<TCurrentJson, TNextJson> = (branch: WorkflowChain<TCurrentJson>) => WorkflowChain<TNextJson>;\ntype BranchOutputMatch<TLeft, TRight> = [TLeft] extends [TRight] ? ([TRight] extends [TLeft] ? true : false) : false;\ntype WorkflowMapCallback<TCurrentJson, TNextJson> = (\n item: Item<TCurrentJson>,\n ctx: NodeExecutionContext<MapData<TCurrentJson, TNextJson>>,\n) => TNextJson;\ntype WorkflowIfPredicate<TCurrentJson> = (\n item: Item<TCurrentJson>,\n ctx: NodeExecutionContext<If<TCurrentJson>>,\n) => boolean;\ntype WorkflowSwitchCaseKeyResolver<TCurrentJson> = (\n item: Item<TCurrentJson>,\n ctx: NodeExecutionContext<Switch<TCurrentJson>>,\n) => string | Promise<string>;\n\nexport class WorkflowChain<TCurrentJson> {\n constructor(private readonly chain: ChainCursor<TCurrentJson>) {}\n\n then<TOutputJson, TConfig extends RunnableNodeConfig<TCurrentJson, TOutputJson>>(\n config: TConfig,\n ): WorkflowChain<RunnableNodeOutputJson<TConfig>> {\n return new WorkflowChain(this.chain.then(config));\n }\n\n map<TNextJson>(mapper: WorkflowMapCallback<TCurrentJson, TNextJson>): WorkflowChain<TNextJson>;\n map<TNextJson>(\n name: string,\n mapper: WorkflowMapCallback<TCurrentJson, TNextJson>,\n options?: MapDataOptions,\n ): WorkflowChain<TNextJson>;\n map<TNextJson>(\n nameOrMapper: string | WorkflowMapCallback<TCurrentJson, TNextJson>,\n mapperOrUndefined?: WorkflowMapCallback<TCurrentJson, TNextJson>,\n options?: MapDataOptions,\n ): WorkflowChain<TNextJson> {\n const name = typeof nameOrMapper === \"string\" ? nameOrMapper : \"Map data\";\n const mapper = typeof nameOrMapper === \"string\" ? mapperOrUndefined! : nameOrMapper;\n return this.then(new MapData<TCurrentJson, TNextJson>(name, mapper, options)) as WorkflowChain<TNextJson>;\n }\n\n wait(duration: number | string): WorkflowChain<TCurrentJson>;\n wait(name: string, duration: number | string, id?: string): WorkflowChain<TCurrentJson>;\n wait(\n nameOrDuration: string | number,\n durationOrUndefined?: string | number,\n id?: string,\n ): WorkflowChain<TCurrentJson> {\n const name = typeof nameOrDuration === \"string\" && durationOrUndefined !== undefined ? nameOrDuration : \"Wait\";\n const duration = durationOrUndefined ?? nameOrDuration;\n return this.then(\n new Wait<TCurrentJson>(name, WorkflowDurationParser.parse(duration), id),\n ) as WorkflowChain<TCurrentJson>;\n }\n\n split<TElem>(\n getElements: (item: Item<TCurrentJson>, ctx: NodeExecutionContext<Split<TCurrentJson, TElem>>) => readonly TElem[],\n ): WorkflowChain<TElem>;\n split<TElem>(\n name: string,\n getElements: (item: Item<TCurrentJson>, ctx: NodeExecutionContext<Split<TCurrentJson, TElem>>) => readonly TElem[],\n id?: string,\n ): WorkflowChain<TElem>;\n split<TElem>(\n nameOrGetter:\n | string\n | ((item: Item<TCurrentJson>, ctx: NodeExecutionContext<Split<TCurrentJson, TElem>>) => readonly TElem[]),\n getElementsOrUndefined?: (\n item: Item<TCurrentJson>,\n ctx: NodeExecutionContext<Split<TCurrentJson, TElem>>,\n ) => readonly TElem[],\n id?: string,\n ): WorkflowChain<TElem> {\n const name = typeof nameOrGetter === \"string\" ? nameOrGetter : \"Split\";\n const getElements = typeof nameOrGetter === \"string\" ? getElementsOrUndefined! : nameOrGetter;\n return this.then(new Split<TCurrentJson, TElem>(name, getElements, id)) as WorkflowChain<TElem>;\n }\n\n filter(\n predicate: (\n item: Item<TCurrentJson>,\n index: number,\n items: Items<TCurrentJson>,\n ctx: NodeExecutionContext<Filter<TCurrentJson>>,\n ) => boolean,\n ): WorkflowChain<TCurrentJson>;\n filter(\n name: string,\n predicate: (\n item: Item<TCurrentJson>,\n index: number,\n items: Items<TCurrentJson>,\n ctx: NodeExecutionContext<Filter<TCurrentJson>>,\n ) => boolean,\n id?: string,\n ): WorkflowChain<TCurrentJson>;\n filter(\n nameOrPredicate:\n | string\n | ((\n item: Item<TCurrentJson>,\n index: number,\n items: Items<TCurrentJson>,\n ctx: NodeExecutionContext<Filter<TCurrentJson>>,\n ) => boolean),\n predicateOrUndefined?: (\n item: Item<TCurrentJson>,\n index: number,\n items: Items<TCurrentJson>,\n ctx: NodeExecutionContext<Filter<TCurrentJson>>,\n ) => boolean,\n id?: string,\n ): WorkflowChain<TCurrentJson> {\n const name = typeof nameOrPredicate === \"string\" ? nameOrPredicate : \"Filter\";\n const predicate = typeof nameOrPredicate === \"string\" ? predicateOrUndefined! : nameOrPredicate;\n return this.then(new Filter<TCurrentJson>(name, predicate, id)) as WorkflowChain<TCurrentJson>;\n }\n\n aggregate<TOut>(\n aggregateFn: (\n items: Items<TCurrentJson>,\n ctx: NodeExecutionContext<Aggregate<TCurrentJson, TOut>>,\n ) => TOut | Promise<TOut>,\n ): WorkflowChain<TOut>;\n aggregate<TOut>(\n name: string,\n aggregateFn: (\n items: Items<TCurrentJson>,\n ctx: NodeExecutionContext<Aggregate<TCurrentJson, TOut>>,\n ) => TOut | Promise<TOut>,\n id?: string,\n ): WorkflowChain<TOut>;\n aggregate<TOut>(\n nameOrFn:\n | string\n | ((\n items: Items<TCurrentJson>,\n ctx: NodeExecutionContext<Aggregate<TCurrentJson, TOut>>,\n ) => TOut | Promise<TOut>),\n aggregateFnOrUndefined?: (\n items: Items<TCurrentJson>,\n ctx: NodeExecutionContext<Aggregate<TCurrentJson, TOut>>,\n ) => TOut | Promise<TOut>,\n id?: string,\n ): WorkflowChain<TOut> {\n const name = typeof nameOrFn === \"string\" ? nameOrFn : \"Aggregate\";\n const aggregateFn = typeof nameOrFn === \"string\" ? aggregateFnOrUndefined! : nameOrFn;\n return this.then(new Aggregate<TCurrentJson, TOut>(name, aggregateFn, id)) as WorkflowChain<TOut>;\n }\n\n merge(): WorkflowChain<TCurrentJson>;\n merge(cfg: Readonly<{ mode: MergeMode; prefer?: ReadonlyArray<string> }>, id?: string): WorkflowChain<TCurrentJson>;\n merge(\n name: string,\n cfg?: Readonly<{ mode: MergeMode; prefer?: ReadonlyArray<string> }>,\n id?: string,\n ): WorkflowChain<TCurrentJson>;\n merge(\n nameOrCfg?: string | Readonly<{ mode: MergeMode; prefer?: ReadonlyArray<string> }>,\n cfgOrId?: Readonly<{ mode: MergeMode; prefer?: ReadonlyArray<string> }> | string,\n id?: string,\n ): WorkflowChain<TCurrentJson> {\n const name = typeof nameOrCfg === \"string\" ? nameOrCfg : \"Merge\";\n const cfg =\n typeof nameOrCfg === \"string\"\n ? ((typeof cfgOrId === \"string\" ? undefined : cfgOrId) ?? { mode: \"passThrough\" as const })\n : (nameOrCfg ?? { mode: \"passThrough\" as const });\n const mergeId = typeof cfgOrId === \"string\" ? cfgOrId : id;\n return new WorkflowChain(\n this.chain.thenIntoInputHints(new Merge<TCurrentJson>(name, cfg, mergeId)),\n ) as WorkflowChain<TCurrentJson>;\n }\n\n if<TBranchJson>(\n predicate: WorkflowIfPredicate<TCurrentJson>,\n branches: Readonly<{\n true?: BranchCallback<TCurrentJson, TBranchJson>;\n false?: BranchCallback<TCurrentJson, TBranchJson>;\n }>,\n ): WorkflowChain<TBranchJson>;\n if<TBranchJson>(\n name: string,\n predicate: WorkflowIfPredicate<TCurrentJson>,\n branches: Readonly<{\n true?: BranchCallback<TCurrentJson, TBranchJson>;\n false?: BranchCallback<TCurrentJson, TBranchJson>;\n }>,\n ): WorkflowChain<TBranchJson>;\n if<TTrueJson, TFalseJson>(\n nameOrPredicate: string | WorkflowIfPredicate<TCurrentJson>,\n predicateOrBranches:\n | WorkflowIfPredicate<TCurrentJson>\n | Readonly<{ true?: BranchCallback<TCurrentJson, TTrueJson>; false?: BranchCallback<TCurrentJson, TFalseJson> }>,\n branchesOrUndefined?: Readonly<{\n true?: BranchCallback<TCurrentJson, TTrueJson>;\n false?: BranchCallback<TCurrentJson, TFalseJson>;\n }>,\n ): WorkflowChain<BranchOutputMatch<TTrueJson, TFalseJson> extends true ? TTrueJson : never> {\n const name = typeof nameOrPredicate === \"string\" ? nameOrPredicate : \"If\";\n const predicate =\n typeof nameOrPredicate === \"string\"\n ? (predicateOrBranches as WorkflowIfPredicate<TCurrentJson>)\n : nameOrPredicate;\n const branches = (typeof nameOrPredicate === \"string\" ? branchesOrUndefined : predicateOrBranches) as Readonly<{\n true?: BranchCallback<TCurrentJson, TTrueJson>;\n false?: BranchCallback<TCurrentJson, TFalseJson>;\n }>;\n const cursor = this.chain.then(new If<TCurrentJson>(name, (item, _index, _items, ctx) => predicate(item, ctx)));\n const trueSteps = branches.true?.(new WorkflowBranchBuilder<TCurrentJson>()).getSteps();\n const falseSteps = branches.false?.(new WorkflowBranchBuilder<TCurrentJson>()).getSteps();\n return new WorkflowChain(\n cursor.when({\n true: trueSteps,\n false: falseSteps,\n }),\n ) as WorkflowChain<BranchOutputMatch<TTrueJson, TFalseJson> extends true ? TTrueJson : never>;\n }\n\n route<TBranchJson>(\n branches: Readonly<Record<string, RouteBranchCallback<TCurrentJson, TBranchJson> | undefined>>,\n ): WorkflowChain<TBranchJson> {\n const mappedBranches = Object.fromEntries(\n Object.entries(branches).map(([port, branchFactory]) => [\n port,\n branchFactory\n ? (branch: ChainCursor<TCurrentJson>) => branchFactory(new WorkflowChain(branch)).chain\n : undefined,\n ]),\n ) as Readonly<\n Record<string, ((branch: ChainCursor<TCurrentJson>) => ChainCursor<TBranchJson> | undefined) | undefined>\n >;\n return new WorkflowChain(\n this.chain.route(\n mappedBranches as Readonly<\n Record<string, (branch: ChainCursor<TCurrentJson>) => ChainCursor<TBranchJson> | undefined>\n >,\n ),\n ) as WorkflowChain<TBranchJson>;\n }\n\n switch<TBranchJson>(\n cfg: Readonly<{\n cases: readonly string[];\n defaultCase: string;\n resolveCaseKey: WorkflowSwitchCaseKeyResolver<TCurrentJson>;\n branches: Readonly<Record<string, RouteBranchCallback<TCurrentJson, TBranchJson> | undefined>>;\n }>,\n ): WorkflowChain<TBranchJson>;\n switch<TBranchJson>(\n name: string,\n cfg: Readonly<{\n cases: readonly string[];\n defaultCase: string;\n resolveCaseKey: WorkflowSwitchCaseKeyResolver<TCurrentJson>;\n branches: Readonly<Record<string, RouteBranchCallback<TCurrentJson, TBranchJson> | undefined>>;\n }>,\n id?: string,\n ): WorkflowChain<TBranchJson>;\n switch<TBranchJson>(\n nameOrCfg:\n | string\n | Readonly<{\n cases: readonly string[];\n defaultCase: string;\n resolveCaseKey: WorkflowSwitchCaseKeyResolver<TCurrentJson>;\n branches: Readonly<Record<string, RouteBranchCallback<TCurrentJson, TBranchJson> | undefined>>;\n }>,\n cfgOrUndefined?: Readonly<{\n cases: readonly string[];\n defaultCase: string;\n resolveCaseKey: WorkflowSwitchCaseKeyResolver<TCurrentJson>;\n branches: Readonly<Record<string, RouteBranchCallback<TCurrentJson, TBranchJson> | undefined>>;\n }>,\n id?: string,\n ): WorkflowChain<TBranchJson> {\n const name = typeof nameOrCfg === \"string\" ? nameOrCfg : \"Switch\";\n const cfg = (typeof nameOrCfg === \"string\" ? cfgOrUndefined : nameOrCfg)!;\n const switched = this.then(\n new Switch<TCurrentJson>(\n name,\n {\n cases: cfg.cases,\n defaultCase: cfg.defaultCase,\n resolveCaseKey: (item, _index, _items, ctx) => cfg.resolveCaseKey(item, ctx),\n },\n id,\n ),\n ) as WorkflowChain<TCurrentJson>;\n return switched.route(cfg.branches);\n }\n\n agent<TOutputSchema extends z.ZodTypeAny>(\n options: WorkflowAgentOptions<TCurrentJson, TOutputSchema>,\n ): WorkflowChain<z.output<TOutputSchema>>;\n agent(options: WorkflowAgentOptions<TCurrentJson, undefined>): WorkflowChain<Record<string, unknown>>;\n agent<TOutputSchema extends z.ZodTypeAny>(\n name: string,\n options: WorkflowAgentOptions<TCurrentJson, TOutputSchema | undefined>,\n ): WorkflowChain<TOutputSchema extends z.ZodTypeAny ? z.output<TOutputSchema> : Record<string, unknown>>;\n agent<TOutputSchema extends z.ZodTypeAny>(\n nameOrOptions: string | WorkflowAgentOptions<TCurrentJson, TOutputSchema | undefined>,\n optionsOrUndefined?: WorkflowAgentOptions<TCurrentJson, TOutputSchema | undefined>,\n ): WorkflowChain<TOutputSchema extends z.ZodTypeAny ? z.output<TOutputSchema> : Record<string, unknown>> {\n return this.then(WorkflowAgentNodeFactory.create(nameOrOptions, optionsOrUndefined)) as WorkflowChain<\n TOutputSchema extends z.ZodTypeAny ? z.output<TOutputSchema> : Record<string, unknown>\n >;\n }\n\n node<TConfig extends CredentialJsonRecord, TInputJson, TOutputJson>(\n definitionOrKey: DefinedNode<string, TConfig, TInputJson, TOutputJson> | string,\n config: DefinedNodeConfigInput<TConfig, TCurrentJson>,\n name?: string,\n id?: string,\n ): TCurrentJson extends TInputJson ? WorkflowChain<TOutputJson> : never {\n const definition = WorkflowDefinedNodeResolver.resolve(\n definitionOrKey as DefinedNode<string, Record<string, unknown>, unknown, unknown> | string,\n ) as DefinedNode<string, TConfig, TInputJson, TOutputJson>;\n return this.then(\n definition.create(config, name, id) as unknown as RunnableNodeConfig<TCurrentJson, TOutputJson>,\n ) as TCurrentJson extends TInputJson ? WorkflowChain<TOutputJson> : never;\n }\n\n build(): WorkflowDefinition {\n return this.chain.build();\n }\n}\n","import { ChainCursor } from \"@codemation/core\";\nimport { ManualTrigger } from \"../nodes/ManualTriggerFactory\";\nimport { createWorkflowBuilder } from \"../workflowBuilder.types\";\nimport { WorkflowChain } from \"./WorkflowChain.types\";\n\nexport class WorkflowAuthoringBuilder {\n constructor(\n private readonly id: string,\n private readonly workflowName: string = id,\n ) {}\n\n name(name: string): WorkflowAuthoringBuilder {\n return new WorkflowAuthoringBuilder(this.id, name);\n }\n\n manualTrigger<TOutputJson>(defaultItems: TOutputJson | ReadonlyArray<TOutputJson>): WorkflowChain<TOutputJson>;\n manualTrigger<TOutputJson>(\n name: string,\n defaultItems?: TOutputJson | ReadonlyArray<TOutputJson>,\n id?: string,\n ): WorkflowChain<TOutputJson>;\n manualTrigger<TOutputJson>(\n nameOrDefaultItems: string | TOutputJson | ReadonlyArray<TOutputJson>,\n defaultItemsOrUndefined?: TOutputJson | ReadonlyArray<TOutputJson>,\n id?: string,\n ): WorkflowChain<TOutputJson> {\n const builder = createWorkflowBuilder({ id: this.id, name: this.workflowName });\n if (typeof nameOrDefaultItems === \"string\") {\n return new WorkflowChain(\n builder.trigger(\n new ManualTrigger<TOutputJson>(\n nameOrDefaultItems,\n defaultItemsOrUndefined as TOutputJson | ReadonlyArray<TOutputJson>,\n id,\n ),\n ) as ChainCursor<TOutputJson>,\n );\n }\n return new WorkflowChain(\n builder.trigger(new ManualTrigger<TOutputJson>(\"Manual trigger\", nameOrDefaultItems)) as ChainCursor<TOutputJson>,\n );\n }\n}\n","export type { WorkflowAgentMessages, WorkflowAgentOptions } from \"./workflowAuthoring/WorkflowAuthoringOptions.types\";\nexport { WorkflowAuthoringBuilder } from \"./workflowAuthoring/WorkflowAuthoringBuilder.types\";\nexport { WorkflowBranchBuilder } from \"./workflowAuthoring/WorkflowBranchBuilder.types\";\nexport { WorkflowChain } from \"./workflowAuthoring/WorkflowChain.types\";\n\nimport { WorkflowAuthoringBuilder } from \"./workflowAuthoring/WorkflowAuthoringBuilder.types\";\n\nexport function workflow(id: string): WorkflowAuthoringBuilder {\n return new WorkflowAuthoringBuilder(id);\n}\n","import type { NodeDefinition, WorkflowDefinition, WorkflowNodeConnection } from \"@codemation/core\";\nimport { AgentConfigInspector, AgentConnectionNodeCollector } from \"@codemation/core\";\n\nimport { AIAgentNode } from \"../nodes/AIAgentNode\";\nimport { ConnectionCredentialNode } from \"../nodes/ConnectionCredentialNode\";\nimport { ConnectionCredentialNodeConfigFactory } from \"../nodes/ConnectionCredentialNodeConfigFactory\";\n\n/**\n * Materializes connection-owned child nodes and {@link WorkflowDefinition.connections} for AI agent nodes.\n */\nexport class AIAgentConnectionWorkflowExpander {\n constructor(private readonly connectionCredentialNodeConfigFactory: ConnectionCredentialNodeConfigFactory) {}\n\n expand(workflow: WorkflowDefinition): WorkflowDefinition {\n const existingChildIds = this.collectExistingChildIds(workflow);\n const connectionsByParentAndName = this.createConnectionsByParentAndName(workflow);\n const extraNodes: NodeDefinition[] = [];\n let connectionsChanged = false;\n\n for (const node of workflow.nodes) {\n if (node.type !== AIAgentNode || !AgentConfigInspector.isAgentNodeConfig(node.config)) {\n continue;\n }\n for (const connectionNode of AgentConnectionNodeCollector.collect(node.id, node.config)) {\n if (!existingChildIds.has(connectionNode.nodeId)) {\n this.assertNoIdCollision(workflow, extraNodes, existingChildIds, connectionNode.nodeId);\n extraNodes.push({\n id: connectionNode.nodeId,\n kind: \"node\",\n type: ConnectionCredentialNode,\n name: connectionNode.name,\n config: this.connectionCredentialNodeConfigFactory.create(\n connectionNode.typeName,\n connectionNode.credentialSource,\n ),\n });\n }\n const connectionKey = this.connectionKey(connectionNode.parentNodeId, connectionNode.connectionName);\n const existingConnection = connectionsByParentAndName.get(connectionKey);\n if (!existingConnection) {\n connectionsByParentAndName.set(connectionKey, {\n parentNodeId: connectionNode.parentNodeId,\n connectionName: connectionNode.connectionName,\n childNodeIds: [connectionNode.nodeId],\n });\n connectionsChanged = true;\n continue;\n }\n if (!existingConnection.childNodeIds.includes(connectionNode.nodeId)) {\n connectionsByParentAndName.set(connectionKey, {\n ...existingConnection,\n childNodeIds: [...existingConnection.childNodeIds, connectionNode.nodeId],\n });\n connectionsChanged = true;\n }\n }\n }\n\n if (extraNodes.length === 0 && !connectionsChanged) {\n return workflow;\n }\n\n return {\n ...workflow,\n nodes: [...workflow.nodes, ...extraNodes],\n connections: [...connectionsByParentAndName.values()],\n };\n }\n\n private createConnectionsByParentAndName(workflow: WorkflowDefinition): Map<string, WorkflowNodeConnection> {\n const existingByParentAndName = new Map<string, WorkflowNodeConnection>();\n for (const connection of workflow.connections ?? []) {\n existingByParentAndName.set(this.connectionKey(connection.parentNodeId, connection.connectionName), connection);\n }\n return existingByParentAndName;\n }\n\n private collectExistingChildIds(workflow: WorkflowDefinition): ReadonlySet<string> {\n const ids = new Set<string>();\n for (const connection of workflow.connections ?? []) {\n for (const childId of connection.childNodeIds) {\n ids.add(childId);\n }\n }\n return ids;\n }\n\n private connectionKey(parentNodeId: string, connectionName: string): string {\n return `${parentNodeId}\\0${connectionName}`;\n }\n\n private assertNoIdCollision(\n workflow: WorkflowDefinition,\n pending: ReadonlyArray<NodeDefinition>,\n existingChildIds: ReadonlySet<string>,\n id: string,\n ): void {\n if (pending.some((n) => n.id === id)) {\n throw new Error(\n `AIAgent connection expansion: node id \"${id}\" already exists. Rename the conflicting node or adjust the workflow.`,\n );\n }\n if (workflow.nodes.some((n) => n.id === id) && !existingChildIds.has(id)) {\n throw new Error(\n `AIAgent connection expansion: node id \"${id}\" already exists. Rename the conflicting node or adjust the workflow.`,\n );\n }\n }\n}\n","import type { CredentialRequirement, RunnableNodeConfig } from \"@codemation/core\";\n\nimport { ConnectionCredentialNode } from \"./ConnectionCredentialNode\";\n\nexport class ConnectionCredentialNodeConfig implements RunnableNodeConfig {\n readonly kind = \"node\" as const;\n readonly type = ConnectionCredentialNode;\n\n constructor(\n public readonly name: string,\n private readonly credentialSource: { getCredentialRequirements?: () => ReadonlyArray<CredentialRequirement> },\n ) {}\n\n getCredentialRequirements(): ReadonlyArray<CredentialRequirement> {\n return this.credentialSource.getCredentialRequirements?.() ?? [];\n }\n}\n","import type { CredentialRequirement } from \"@codemation/core\";\n\nimport { ConnectionCredentialNodeConfig } from \"./ConnectionCredentialNodeConfig\";\n\nexport class ConnectionCredentialNodeConfigFactory {\n create(\n name: string,\n credentialSource: { getCredentialRequirements?: () => ReadonlyArray<CredentialRequirement> },\n ): ConnectionCredentialNodeConfig {\n return new ConnectionCredentialNodeConfig(name, credentialSource);\n }\n}\n"],"x_google_ignoreList":[6,7,8,9,10,11,12,13,14,15,16,20,21,22],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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cA,WAAS,eAAe,EAAE,CACjD,yBAAwB,IAAI,KAAK,cAAc,WAAW,cAAc,WAAW,eAAe,EAAE,WAAW;AAEjH,SAAO;;CAGT,AAAQ,wBAAwB,YAAmD;EACjF,MAAM,sBAAM,IAAI,KAAa;AAC7B,OAAK,MAAM,cAAcA,WAAS,eAAe,EAAE,CACjD,MAAK,MAAM,WAAW,WAAW,aAC/B,KAAI,IAAI,QAAQ;AAGpB,SAAO;;CAGT,AAAQ,cAAc,cAAsB,gBAAgC;AAC1E,SAAO,GAAG,aAAa,IAAI;;CAG7B,AAAQ,oBACN,YACA,SACA,kBACA,IACM;AACN,MAAI,QAAQ,MAAM,MAAM,EAAE,OAAO,GAAG,CAClC,OAAM,IAAI,MACR,0CAA0C,GAAG,uEAC9C;AAEH,MAAIA,WAAS,MAAM,MAAM,MAAM,EAAE,OAAO,GAAG,IAAI,CAAC,iBAAiB,IAAI,GAAG,CACtE,OAAM,IAAI,MACR,0CAA0C,GAAG,uEAC9C;;;;;;ACrGP,IAAa,iCAAb,MAA0E;CACxE,AAAS,OAAO;CAChB,AAAS,OAAO;CAEhB,YACE,AAAgBK,MAChB,AAAiBC,kBACjB;EAFgB;EACC;;CAGnB,4BAAkE;AAChE,SAAO,KAAK,iBAAiB,6BAA6B,IAAI,EAAE;;;;;;ACVpE,IAAa,wCAAb,MAAmD;CACjD,OACE,MACA,kBACgC;AAChC,SAAO,IAAI,+BAA+B,MAAM,iBAAiB"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["fetchFn: typeof globalThis.fetch","bodyBuilder: HttpBodyBuilder","urlBuilder: HttpUrlBuilder","mergedHeaders: Record<string, string>","mergedQuery: Record<string, string | string[]>","json: unknown | undefined","text: string | undefined","bodyBinaryName: string | undefined","values: Record<string, string>","chunks: Uint8Array[]","responseCtx: RestNodeResponseContext","OpenAIChatModelFactory","_a","object","_a","config","initializer","util.jsonStringifyReplacer","issue","error","core.$ZodAsyncError","util.finalizeIssue","core.config","parse","errors.$ZodRealError","parseAsync","errors.$ZodError","safeParse","safeParseAsync","encode","decode","encodeAsync","decodeAsync","safeEncode","safeDecode","safeEncodeAsync","safeDecodeAsync","duration","version","_emoji","date","time","datetime","string","number","_a","inst","util.floatSafeRemainder","util.NUMBER_FORMAT_RANGES","regexes.integer","util.nullish","util.getLengthableOrigin","regexes.lowercase","regexes.uppercase","util.escapeRegex","_a","util.aborted","checks","core.$ZodAsyncError","checkResult","canary","result","safeParse","safeParseAsync","regexes.string","_","regexes.guid","regexes.uuid","regexes.email","regexes.emoji","regexes.nanoid","regexes.cuid","regexes.cuid2","regexes.ulid","regexes.xid","regexes.ksuid","regexes.datetime","regexes.date","regexes.time","regexes.duration","regexes.ipv4","regexes.ipv6","regexes.cidrv4","regexes.cidrv6","regexes.base64","base64","regexes.base64url","regexes.e164","regexes.number","util.prefixIssues","util.optionalKeys","r","util.cached","isObject","util.isObject","util.esc","allowsEval","util.allowsEval","util.finalizeIssue","core.config","util.cleanRegex","results","left","right","util.isPlainObject","util.getEnumValues","util.escapeRegex","core.$ZodEncodeError","util.issue","meta","util.normalizeParams","checks.$ZodCheckLessThan","checks.$ZodCheckGreaterThan","checks.$ZodCheckMultipleOf","checks.$ZodCheckMaxLength","checks.$ZodCheckMinLength","checks.$ZodCheckLengthEquals","checks.$ZodCheckRegex","checks.$ZodCheckLowerCase","checks.$ZodCheckUpperCase","checks.$ZodCheckIncludes","checks.$ZodCheckStartsWith","checks.$ZodCheckEndsWith","checks.$ZodCheckOverwrite","util.slugify","issue","util.issue","checks.$ZodCheck","describe","meta","_a","meta","id","schema","registry","ctx","CredentialResolverFactory","AIAgentExecutionHelpersFactory","frameworkToJSONSchema","node","OpenAiStrictJsonSchemaFactory","executionHelpers: AIAgentExecutionHelpersFactory","record","node","name: string","model: string","credentialSlotKey: string","options?: Readonly<{\n temperature?: number;\n maxTokens?: number;\n }>","content: AssistantModelMessage[\"content\"]","AgentStructuredOutputRepairPromptFactory","executionHelpers: AIAgentExecutionHelpersFactory","core._isoDateTime","core._isoDate","core._isoTime","core._isoDuration","core.formatError","core.flattenError","issue","util.jsonStringifyReplacer","issues","core.$constructor","util.mergeDefs","core.clone","def","meta","parse.parse","parse.safeParse","parse.parseAsync","parse.safeParseAsync","parse.encode","parse.decode","parse.encodeAsync","parse.decodeAsync","parse.safeEncode","parse.safeDecode","parse.safeEncodeAsync","parse.safeDecodeAsync","checks.overwrite","processors.stringProcessor","checks.regex","checks.includes","checks.startsWith","checks.endsWith","checks.minLength","checks.maxLength","checks.length","checks.lowercase","checks.uppercase","checks.trim","checks.normalize","checks.toLowerCase","checks.toUpperCase","checks.slugify","core._email","core._url","core._jwt","core._emoji","core._guid","core._uuid","core._uuidv4","core._uuidv6","core._uuidv7","core._nanoid","core._cuid","core._cuid2","core._ulid","core._base64","core._base64url","core._xid","core._ksuid","core._ipv4","core._ipv6","core._cidrv4","core._cidrv6","core._e164","iso.datetime","iso.date","iso.time","iso.duration","core._string","processors.numberProcessor","checks.gt","checks.gte","checks.lt","checks.lte","checks.multipleOf","core._number","core._int","processors.unknownProcessor","core._unknown","processors.neverProcessor","core._never","processors.arrayProcessor","core._array","processors.objectProcessor","util.extend","util.safeExtend","util.merge","util.pick","util.omit","util.partial","util.required","util.normalizeParams","processors.unionProcessor","processors.intersectionProcessor","processors.recordProcessor","processors.enumProcessor","processors.transformProcessor","core.$ZodEncodeError","issue","util.issue","output","processors.optionalProcessor","processors.nullableProcessor","processors.defaultProcessor","util.shallowClone","processors.prefaultProcessor","processors.nonoptionalProcessor","processors.catchProcessor","processors.pipeProcessor","processors.readonlyProcessor","processors.customProcessor","core._refine","core._superRefine","core.describe","core.meta","AgentStructuredOutputRunner","repairPromptFactory: AgentStructuredOutputRepairPromptFactory","openAiStrictJsonSchemaFactory: OpenAiStrictJsonSchemaFactory","lastFailure: ParsedStructuredOutputFailure | undefined","repairMessages: ReadonlyArray<ModelMessage>","issue","AgentToolErrorClassifier","issue","details: Record<string, JsonValue>","issue","result: Record<string, JsonValue>","AgentToolRepairPolicy","AgentToolExecutionCoordinator","errorClassifier: AgentToolErrorClassifier","repairPolicy: AgentToolRepairPolicy","CodemationTelemetryAttributeNames","payload: Record<string, JsonValue>","details: Record<string, JsonValue>","issue","result: Record<string, JsonValue>","NodeBackedToolRuntime","nodeResolver: NodeResolver","itemExprResolver: ItemExprResolver","outputNormalizer: NodeOutputNormalizer","outputBehaviorResolver: RunnableOutputBehaviorResolver","childExecutionScopeFactory: ChildExecutionScopeFactory","config","AgentConfigInspector","z.unknown","execArgs: RunnableNodeExecuteArgs","CoreTokens","ItemExprResolver","NodeOutputNormalizer","RunnableOutputBehaviorResolver","ChildExecutionScopeFactory","AIAgentNode","z.unknown","nodeResolver: NodeResolver","credentialSessions: CredentialSessionService","nodeBackedToolRuntime: NodeBackedToolRuntime","executionHelpers: AIAgentExecutionHelpersFactory","structuredOutputRunner: AgentStructuredOutputRunner","toolExecutionCoordinator: AgentToolExecutionCoordinator","ConnectionNodeIdFactory","conversation: ModelMessage[]","CodemationTelemetryMetricNames","conversationWithFinal: ReadonlyArray<ModelMessage>","config","toolSet: Record<string, { description?: string; inputSchema: ReturnType<typeof jsonSchema> }>","ConnectionInvocationIdFactory","Output","toolCalls: ReadonlyArray<AgentToolCall>","CodemationTelemetryAttributeNames","GenAiTelemetryAttributeNames","entries: ReadonlyArray<readonly [string, number | undefined]>","chatModel","AgentMessageConfigNormalizer","NodeBackedToolConfig","CallableToolConfig","AgentGuardrailDefaults","CoreTokens","RetryPolicy","AssertionNode","config","CallbackNode","config","result","name: string","callback: CallbackHandler<TInputJson, TOutputJson>","HttpRequestNode","spec: HttpRequestSpec","outputJson: Readonly<Record<string, unknown>>","outputItem: Item","json: unknown | undefined","text: string | undefined","values: Record<string, string>","HTTP_REQUEST_ACCEPTED_CREDENTIAL_TYPES: ReadonlyArray<string>","name: string","args: Readonly<{\n /** HTTP method (default: GET). */\n method?: string;\n /**\n * Legacy: field name on item.json to read the URL from.\n * Use `url` for a literal/templated URL instead.\n */\n urlField?: string;\n /** Literal or templated URL. When present, takes precedence over `urlField`. */\n url?: string;\n /** Extra headers to add to every request. */\n headers?: Readonly<Record<string, string>>;\n /** Query parameters to append to the URL. */\n query?: Readonly<Record<string, string>>;\n /** Request body specification. For canvas use, pass a JSON string in `body.data`. */\n body?: HttpBodySpec;\n /**\n * Credential slot key. When set, the node resolves a credential via\n * `ctx.getCredential(credentialSlot)` and applies it to the request.\n * The slot must be declared in `getCredentialRequirements()`.\n */\n credentialSlot?: string;\n binaryName?: string;\n downloadMode?: HttpRequestDownloadMode;\n id?: string;\n }>","retryPolicy: RetryPolicySpec","RetryPolicy","AggregateNode","name: string","aggregate: (\n items: Items<TIn>,\n ctx: NodeExecutionContext<Aggregate<TIn, TOut>>,\n ) => TOut | Promise<TOut>","id?: string","FilterNode","name: string","predicate: (\n item: Item<TIn>,\n index: number,\n items: Items<TIn>,\n ctx: NodeExecutionContext<Filter<TIn>>,\n ) => boolean","id?: string","IfNode","name: string","predicate: (\n item: Item<TInputJson>,\n index: number,\n items: Items<TInputJson>,\n ctx: NodeExecutionContext<If<TInputJson>>,\n ) => boolean","id?: string","IsTestRunNode","SwitchNode","name: string","cfg: Readonly<{\n cases: readonly string[];\n defaultCase: string;\n resolveCaseKey: SwitchCaseKeyResolver<TInputJson>;\n }>","id?: string","SplitNode","name: string","getElements: (item: Item<TIn>, ctx: NodeExecutionContext<Split<TIn, TElem>>) => readonly TElem[]","id?: string","CronTriggerNode","name: string","args: Readonly<{ schedule: string; timezone?: string }>","Cron","ManualTriggerNode","config","ItemsInputNormalizer","name: string","MapDataNode","z.unknown","name: string","map: (\n item: Item<TInputJson>,\n ctx: NodeExecutionContext<MapData<TInputJson, TOutputJson>>,\n ) => TOutputJson","options: MapDataOptions","MergeNode","out: Item[]","out","json: Record<string, unknown>","paired: any[]","meta: Record<string, unknown> | undefined","meta","merged: any","fallback: Item[]","name: string","cfg: Readonly<{\n mode: MergeMode;\n /**\n * Deterministic input precedence order (only used for passThrough/append).\n * Any inputs not listed are appended in lexicographic order.\n */\n prefer?: ReadonlyArray<InputPortKey>;\n }>","id?: string","NoOpNode","name: string","id?: string","SubWorkflowNode","workflows: WorkflowRunnerService","out: Item[]","CoreTokens","name: string","workflowId: string","upstreamRefs?: Array<{ nodeId: NodeId } | UpstreamRefPlaceholder>","startAt?: NodeId","id?: string","TestTriggerNode","WaitNode","name: string","milliseconds: number","id?: string","responseItems: Items","continueItems: Items","responseItems: Items","WebhookTriggerNode","name: string","args: Readonly<{\n endpointKey: string;\n methods: ReadonlyArray<HttpMethod>;\n inputSchema?: TSchema;\n }>","handler: WebhookTriggerHandler<\n WebhookTrigger<TSchema>\n >","id?: string","ConnectionCredentialNode","WorkflowBuilder","meta","DefinedNodeRegistry","duration","steps: ReadonlyArray<AnyRunnableNodeConfig>","config","duration","chain: ChainCursor<TCurrentJson>","config","duration","id: string","workflowName: string","connectionCredentialNodeConfigFactory: ConnectionCredentialNodeConfigFactory","workflow","extraNodes: NodeDefinition[]","node","AgentConfigInspector","AgentConnectionNodeCollector","name: string","credentialSource: { getCredentialRequirements?: () => ReadonlyArray<CredentialRequirement> }","z.object","z.string","z.record","z.unknown","config","z.object","z.string","config","z.object","z.string","z.record","z.unknown","config","z.object","z.string","z.number","z.record","z.unknown","config","z.object","z.string","z.record","z.unknown","config","z.object","z.string","config"],"sources":["../src/credentials/ApiKeyCredentialType.ts","../src/credentials/BasicAuthCredentialType.ts","../src/credentials/BearerTokenCredentialType.ts","../src/credentials/OAuth2TokenExchangeFactory.ts","../src/credentials/OAuth2ClientCredentialsTypeFactory.ts","../src/http/HttpRequestExecutor.ts","../src/http/HttpBodyBuilder.ts","../src/http/HttpUrlBuilder.ts","../src/authoring/defineRestNode.types.ts","../src/chatModels/OpenAIChatModelFactory.ts","../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/core.js","../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/util.js","../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/errors.js","../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/parse.js","../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/regexes.js","../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/checks.js","../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/doc.js","../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/versions.js","../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/schemas.js","../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/registries.js","../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/api.js","../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/to-json-schema.js","../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/json-schema-processors.js","../src/nodes/ConnectionCredentialExecutionContextFactory.ts","../src/nodes/AIAgentExecutionHelpersFactory.ts","../src/chatModels/OpenAiStrictJsonSchemaFactory.ts","../src/chatModels/openAiChatModelConfig.ts","../src/chatModels/OpenAiChatModelPresetsFactory.ts","../src/nodes/AgentMessageFactory.ts","../src/nodes/AgentOutputFactory.ts","../src/nodes/AgentStructuredOutputRepairPromptFactory.ts","../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/iso.js","../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/errors.js","../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/parse.js","../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/schemas.js","../src/nodes/AgentStructuredOutputRunner.ts","../src/nodes/AgentToolCallPortMapFactory.ts","../src/nodes/AgentToolErrorClassifier.ts","../src/nodes/AgentToolRepairExhaustedError.ts","../src/nodes/AgentToolRepairPolicy.ts","../src/nodes/AgentToolExecutionCoordinator.ts","../src/nodes/NodeBackedToolRuntime.ts","../src/nodes/aiAgentSupport.types.ts","../src/nodes/AIAgentNode.ts","../src/nodes/AIAgentConfig.ts","../src/nodes/AssertionNode.ts","../src/nodes/assertion.ts","../src/nodes/CallbackResultNormalizerFactory.ts","../src/nodes/CallbackNode.ts","../src/nodes/CallbackNodeFactory.ts","../src/nodes/HttpRequestNodeFactory.ts","../src/nodes/httpRequest.ts","../src/nodes/AggregateNode.ts","../src/nodes/aggregate.ts","../src/nodes/FilterNode.ts","../src/nodes/filter.ts","../src/nodes/mergeExecutionUtils.types.ts","../src/nodes/IfNode.ts","../src/nodes/if.ts","../src/nodes/IsTestRunNode.ts","../src/nodes/isTestRun.ts","../src/nodes/SwitchNode.ts","../src/nodes/switch.ts","../src/nodes/SplitNode.ts","../src/nodes/split.ts","../src/nodes/CronTriggerNode.ts","../src/nodes/CronTriggerFactory.ts","../src/nodes/ManualTriggerNode.ts","../src/nodes/ManualTriggerFactory.ts","../src/nodes/MapDataNode.ts","../src/nodes/mapData.ts","../src/nodes/MergeNode.ts","../src/nodes/merge.ts","../src/nodes/NoOpNode.ts","../src/nodes/noOp.ts","../src/nodes/SubWorkflowNode.ts","../src/nodes/subWorkflow.ts","../src/nodes/TestTriggerNode.ts","../src/nodes/testTrigger.ts","../src/nodes/WaitDurationFactory.ts","../src/nodes/WaitNode.ts","../src/nodes/wait.ts","../src/nodes/webhookRespondNowAndContinueError.ts","../src/nodes/webhookRespondNowError.ts","../src/nodes/webhookTriggerNode.ts","../src/nodes/WebhookTriggerFactory.ts","../src/nodes/ConnectionCredentialNode.ts","../src/register.types.ts","../src/workflowBuilder.types.ts","../src/workflowAuthoring/WorkflowChatModelFactory.types.ts","../src/workflowAuthoring/WorkflowAgentNodeFactory.types.ts","../src/workflowAuthoring/WorkflowDefinedNodeResolver.types.ts","../src/workflowAuthoring/WorkflowDurationParser.types.ts","../src/workflowAuthoring/WorkflowBranchBuilder.types.ts","../src/workflowAuthoring/WorkflowChain.types.ts","../src/workflowAuthoring/WorkflowAuthoringBuilder.types.ts","../src/workflowAuthoring.types.ts","../src/workflows/AIAgentConnectionWorkflowExpander.ts","../src/nodes/ConnectionCredentialNodeConfig.ts","../src/nodes/ConnectionCredentialNodeConfigFactory.ts","../src/nodes/collections/collectionInsertNode.types.ts","../src/nodes/collections/collectionGetNode.types.ts","../src/nodes/collections/collectionFindOneNode.types.ts","../src/nodes/collections/collectionListNode.types.ts","../src/nodes/collections/collectionUpdateNode.types.ts","../src/nodes/collections/collectionDeleteNode.types.ts"],"sourcesContent":["import { defineCredential } from \"@codemation/core\";\nimport type { CredentialSession, HttpCredentialDelta } from \"../http/httpRequest.types\";\n\n/**\n * API key credential that injects a key either as an HTTP header or a query parameter.\n */\nexport const apiKeyCredentialType = defineCredential({\n key: \"core-nodes.api-key\",\n label: \"API Key\",\n description: \"Authenticates requests by injecting an API key into a header or query parameter.\",\n public: {\n placement: {\n label: \"Placement\",\n type: \"string\",\n helpText: 'Where to send the key: \"header\" (default) or \"query\".',\n placeholder: \"header\",\n },\n name: {\n label: \"Parameter name\",\n type: \"string\",\n helpText: 'Header or query param name. Defaults to \"X-API-Key\" for headers, \"api_key\" for query.',\n placeholder: \"X-API-Key\",\n },\n },\n secret: {\n apiKey: {\n label: \"API Key\",\n type: \"password\",\n required: true,\n helpText: \"The secret API key value.\",\n },\n },\n async createSession(args): Promise<CredentialSession> {\n const apiKey = String(args.material.apiKey ?? \"\");\n if (!apiKey) {\n throw new Error(\"API key credential material is incomplete: apiKey is required.\");\n }\n const placement = String(args.publicConfig.placement ?? \"header\").toLowerCase();\n const isQuery = placement === \"query\";\n const defaultName = isQuery ? \"api_key\" : \"X-API-Key\";\n const paramName = String(args.publicConfig.name ?? \"\").trim() || defaultName;\n\n return {\n applyToRequest: (_spec): HttpCredentialDelta => {\n if (isQuery) {\n return { query: { [paramName]: apiKey } };\n }\n return { headers: { [paramName]: apiKey } };\n },\n };\n },\n async test(args) {\n const apiKey = String(args.material.apiKey ?? \"\");\n return {\n status: apiKey.length > 0 ? \"healthy\" : \"failing\",\n message: apiKey.length > 0 ? \"API key is configured.\" : \"API key is missing.\",\n testedAt: new Date().toISOString(),\n };\n },\n});\n","import { defineCredential } from \"@codemation/core\";\nimport type { CredentialSession, HttpCredentialDelta } from \"../http/httpRequest.types\";\n\n/**\n * HTTP Basic authentication credential.\n * Session sets `Authorization: Basic <base64(username:password)>`.\n */\nexport const basicAuthCredentialType = defineCredential({\n key: \"core-nodes.basic-auth\",\n label: \"Basic Auth\",\n description: \"Authenticates requests using HTTP Basic Authentication (username + password).\",\n public: {\n username: {\n label: \"Username\",\n type: \"string\",\n required: true,\n helpText: \"The username for HTTP Basic Authentication.\",\n },\n },\n secret: {\n password: {\n label: \"Password\",\n type: \"password\",\n required: true,\n helpText: \"The password for HTTP Basic Authentication.\",\n },\n },\n async createSession(args): Promise<CredentialSession> {\n const username = String(args.publicConfig.username ?? \"\");\n const password = String(args.material.password ?? \"\");\n if (!username) {\n throw new Error(\"Basic Auth credential is incomplete: username is required.\");\n }\n const encoded = Buffer.from(`${username}:${password}`).toString(\"base64\");\n return {\n applyToRequest: (_spec): HttpCredentialDelta => ({\n headers: { authorization: `Basic ${encoded}` },\n }),\n };\n },\n async test(args) {\n const username = String(args.publicConfig.username ?? \"\");\n const password = String(args.material.password ?? \"\");\n const ok = username.length > 0 && password.length > 0;\n return {\n status: ok ? \"healthy\" : \"failing\",\n message: ok ? \"Basic Auth credentials are configured.\" : \"Username or password is missing.\",\n testedAt: new Date().toISOString(),\n };\n },\n});\n","import { defineCredential } from \"@codemation/core\";\nimport type { CredentialSession, HttpCredentialDelta } from \"../http/httpRequest.types\";\n\n/**\n * Simple Bearer token credential.\n * Session sets `Authorization: Bearer <token>` on every request.\n */\nexport const bearerTokenCredentialType = defineCredential({\n key: \"core-nodes.bearer-token\",\n label: \"Bearer Token\",\n description: \"Authenticates requests using a static Bearer token in the Authorization header.\",\n public: {},\n secret: {\n token: {\n label: \"Token\",\n type: \"password\",\n required: true,\n helpText: \"The Bearer token to include in the Authorization header.\",\n },\n },\n async createSession(args): Promise<CredentialSession> {\n const token = String(args.material.token ?? \"\");\n if (!token) {\n throw new Error(\"Bearer token credential material is incomplete: token is required.\");\n }\n return {\n applyToRequest: (_spec): HttpCredentialDelta => ({\n headers: { authorization: `Bearer ${token}` },\n }),\n };\n },\n async test(args) {\n const token = String(args.material.token ?? \"\");\n return {\n status: token.length > 0 ? \"healthy\" : \"failing\",\n message: token.length > 0 ? \"Bearer token is configured.\" : \"Token is missing.\",\n testedAt: new Date().toISOString(),\n };\n },\n});\n","/**\n * Performs an OAuth2 `client_credentials` token exchange against a token endpoint\n * and returns the resulting access token.\n *\n * Lives in a Factory file so the body URLSearchParams construction is allowed at\n * the composition root.\n */\nexport type OAuth2ClientCredentialsArgs = Readonly<{\n tokenUrl: string;\n clientId: string;\n clientSecret: string;\n scopes: string;\n audience: string;\n}>;\n\nexport class OAuth2TokenExchangeFactory {\n async create(args: OAuth2ClientCredentialsArgs): Promise<string> {\n const body = new URLSearchParams({\n grant_type: \"client_credentials\",\n client_id: args.clientId,\n });\n if (args.scopes) {\n body.set(\"scope\", args.scopes);\n }\n if (args.audience) {\n body.set(\"audience\", args.audience);\n }\n\n const encoded = Buffer.from(`${args.clientId}:${args.clientSecret}`).toString(\"base64\");\n\n const response = await globalThis.fetch(args.tokenUrl, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/x-www-form-urlencoded\",\n authorization: `Basic ${encoded}`,\n },\n body: body.toString(),\n });\n\n if (!response.ok) {\n const text = await response.text().catch(() => \"\");\n throw new Error(`Token exchange failed (${response.status} ${response.statusText}): ${text}`);\n }\n\n const json = (await response.json()) as Record<string, unknown>;\n const token = String(json[\"access_token\"] ?? \"\");\n if (!token) {\n throw new Error(\"Token exchange response did not include an access_token.\");\n }\n return token;\n }\n}\n","import { defineCredential } from \"@codemation/core\";\nimport type { CredentialSession, HttpCredentialDelta } from \"../http/httpRequest.types\";\nimport { OAuth2TokenExchangeFactory } from \"./OAuth2TokenExchangeFactory\";\n\n/**\n * OAuth2 client-credentials flow credential.\n *\n * This is a machine-to-machine flow: no user redirect occurs. The session\n * POSTs to the configured `tokenUrl` with `client_credentials` grant, caches\n * the resulting access token for the duration of the session, and injects it\n * as `Authorization: Bearer <token>` on each request.\n *\n * Token caching is per-session only (one createSession call = one token fetch\n * at most). Cross-session caching would require host-level state and is out of\n * scope here. Because the engine creates a fresh session per execution, a new\n * token is fetched once per node activation.\n *\n * NOTE: `auth` is intentionally omitted from the definition. The OAuth2\n * `auth: { kind: \"oauth2\" }` shape signals an authorization-code / user-redirect\n * flow; using it here would cause the host UI to render an OAuth consent button\n * that goes nowhere. Client-credentials is a purely server-side flow.\n */\nexport const oauth2ClientCredentialsType = defineCredential({\n key: \"core-nodes.oauth2-client-credentials\",\n label: \"OAuth2 Client Credentials\",\n description:\n \"Machine-to-machine OAuth2 using the client_credentials grant. Exchanges client ID and secret for a bearer token before each workflow execution.\",\n public: {\n tokenUrl: {\n label: \"Token URL\",\n type: \"string\",\n required: true,\n helpText: \"The token endpoint URL, e.g. https://auth.example.com/oauth/token.\",\n },\n scopes: {\n label: \"Scopes\",\n type: \"string\",\n helpText: \"Space-separated list of OAuth2 scopes to request (optional).\",\n },\n audience: {\n label: \"Audience\",\n type: \"string\",\n helpText: \"Optional audience parameter sent to the token endpoint.\",\n visibility: \"advanced\",\n },\n },\n secret: {\n clientId: {\n label: \"Client ID\",\n type: \"string\",\n required: true,\n },\n clientSecret: {\n label: \"Client Secret\",\n type: \"password\",\n required: true,\n },\n },\n async createSession(args): Promise<CredentialSession> {\n const tokenUrl = String(args.publicConfig.tokenUrl ?? \"\");\n const clientId = String(args.material.clientId ?? \"\");\n const clientSecret = String(args.material.clientSecret ?? \"\");\n\n if (!tokenUrl || !clientId || !clientSecret) {\n throw new Error(\"OAuth2 client credentials are incomplete: tokenUrl, clientId, and clientSecret are required.\");\n }\n\n // Fetch the token eagerly so any failure surfaces at session creation time.\n const accessToken = await new OAuth2TokenExchangeFactory().create({\n tokenUrl,\n clientId,\n clientSecret,\n scopes: String(args.publicConfig.scopes ?? \"\"),\n audience: String(args.publicConfig.audience ?? \"\"),\n });\n\n return {\n applyToRequest: (_spec): HttpCredentialDelta => ({\n headers: { authorization: `Bearer ${accessToken}` },\n }),\n };\n },\n async test(args) {\n const tokenUrl = String(args.publicConfig.tokenUrl ?? \"\");\n const clientId = String(args.material.clientId ?? \"\");\n const clientSecret = String(args.material.clientSecret ?? \"\");\n\n if (!tokenUrl || !clientId || !clientSecret) {\n return {\n status: \"failing\",\n message: \"tokenUrl, clientId, and clientSecret are all required.\",\n testedAt: new Date().toISOString(),\n };\n }\n\n try {\n await new OAuth2TokenExchangeFactory().create({\n tokenUrl,\n clientId,\n clientSecret,\n scopes: String(args.publicConfig.scopes ?? \"\"),\n audience: String(args.publicConfig.audience ?? \"\"),\n });\n return {\n status: \"healthy\",\n message: \"Token exchange succeeded.\",\n testedAt: new Date().toISOString(),\n };\n } catch (error) {\n return {\n status: \"failing\",\n message: error instanceof Error ? error.message : String(error),\n testedAt: new Date().toISOString(),\n };\n }\n },\n});\n","import type { Item } from \"@codemation/core\";\nimport type { HttpRequestResult, HttpRequestSpec } from \"./httpRequest.types\";\nimport type { HttpBodyBuilder } from \"./HttpBodyBuilder\";\nimport type { HttpUrlBuilder } from \"./HttpUrlBuilder\";\n\n/**\n * Executes a single HTTP request described by {@link HttpRequestSpec}.\n *\n * - Credential sessions provide header/query deltas via `applyToRequest`.\n * - Body encoding is delegated to {@link HttpBodyBuilder}.\n * - URL query merging is delegated to {@link HttpUrlBuilder}.\n * - Binary response bodies: when `download.mode` triggers binary attach, the\n * `bodyBinaryName` field is set in the result but the body is NOT read here.\n * Callers that need binary attachment should use `buildRequest` to get the\n * resolved URL + init and make the fetch + binary attach themselves.\n *\n * Collaborators (`fetch`, body builder, url builder) are injected so callers\n * own construction at composition roots and tests can supply deterministic stubs.\n */\nexport class HttpRequestExecutor {\n constructor(\n private readonly fetchFn: typeof globalThis.fetch,\n private readonly bodyBuilder: HttpBodyBuilder,\n private readonly urlBuilder: HttpUrlBuilder,\n ) {}\n\n /**\n * Builds the fetch init (headers, query, body) from the spec + credential delta,\n * returning both the resolved URL and the RequestInit so callers can make the\n * actual fetch call themselves (useful for streaming / binary attach).\n */\n async buildRequest(spec: HttpRequestSpec, item: Item): Promise<Readonly<{ url: string; init: RequestInit }>> {\n const credentialDelta = spec.credential?.applyToRequest(spec) ?? {};\n\n const mergedHeaders: Record<string, string> = {\n ...(spec.headers ?? {}),\n ...(credentialDelta.headers ?? {}),\n };\n\n const mergedQuery: Record<string, string | string[]> = {\n ...(spec.query ?? {}),\n ...(credentialDelta.query ?? {}),\n };\n\n const encodedBody = await this.bodyBuilder.build(spec.body, item, spec.ctx);\n\n // Only set Content-Type from the encoded body when it is non-empty\n // (empty string = FormData will set it automatically).\n if (encodedBody && encodedBody.contentType) {\n mergedHeaders[\"content-type\"] = encodedBody.contentType;\n }\n\n const resolvedUrl = this.urlBuilder.build(spec.url, mergedQuery);\n\n const init: RequestInit = {\n method: spec.method,\n headers: mergedHeaders,\n ...(encodedBody ? { body: encodedBody.body } : {}),\n };\n\n return { url: resolvedUrl, init };\n }\n\n /**\n * Executes an HTTP request and returns parsed result.\n * For binary downloads (when `shouldAttachBody` is true), the body is NOT consumed\n * and callers must call `ctx.binary.attach` directly using the resolved URL + init\n * (available via `buildRequest`).\n */\n async execute(spec: HttpRequestSpec, item: Item): Promise<HttpRequestResult> {\n const { url: resolvedUrl, init } = await this.buildRequest(spec, item);\n\n const response = await this.fetchFn(resolvedUrl, init);\n\n const responseHeaders = this.readHeaders(response.headers);\n const mimeType = this.resolveMimeType(responseHeaders);\n\n const downloadMode = spec.download?.mode ?? \"auto\";\n const binaryName = spec.download?.binaryName ?? \"body\";\n const shouldDownload = this.shouldAttachBody(downloadMode, mimeType);\n\n const isJson = this.isJsonMimeType(mimeType);\n\n let json: unknown | undefined;\n let text: string | undefined;\n let bodyBinaryName: string | undefined;\n\n if (shouldDownload) {\n // Signal to caller that binary attachment is needed.\n bodyBinaryName = binaryName;\n // Do NOT read the body here — the caller must handle binary attach separately.\n } else if (isJson) {\n try {\n json = await response.json();\n } catch {\n text = await response.text();\n }\n } else {\n text = await response.text();\n }\n\n return {\n url: resolvedUrl,\n method: spec.method.toUpperCase(),\n status: response.status,\n ok: response.ok,\n statusText: response.statusText,\n mimeType,\n headers: responseHeaders,\n ...(json !== undefined ? { json } : {}),\n ...(text !== undefined ? { text } : {}),\n ...(bodyBinaryName !== undefined ? { bodyBinaryName } : {}),\n };\n }\n\n private readHeaders(headers: Headers): Readonly<Record<string, string>> {\n const values: Record<string, string> = {};\n headers.forEach((value, key) => {\n values[key] = value;\n });\n return values;\n }\n\n private resolveMimeType(headers: Readonly<Record<string, string>>): string {\n const contentType = headers[\"content-type\"];\n if (!contentType) {\n return \"application/octet-stream\";\n }\n return contentType.split(\";\")[0]?.trim() || \"application/octet-stream\";\n }\n\n private isJsonMimeType(mimeType: string): boolean {\n return mimeType === \"application/json\" || mimeType.endsWith(\"+json\");\n }\n\n private shouldAttachBody(mode: \"auto\" | \"always\" | \"never\", mimeType: string): boolean {\n if (mode === \"always\") {\n return true;\n }\n if (mode === \"never\") {\n return false;\n }\n return (\n mimeType.startsWith(\"image/\") ||\n mimeType.startsWith(\"audio/\") ||\n mimeType.startsWith(\"video/\") ||\n mimeType === \"application/pdf\"\n );\n }\n}\n","import type { Item, NodeExecutionContext } from \"@codemation/core\";\nimport type { RunnableNodeConfig } from \"@codemation/core\";\nimport type { HttpBodySpec } from \"./httpRequest.types\";\n\nexport type EncodedBody = Readonly<{\n body: NonNullable<RequestInit[\"body\"]>;\n /**\n * Desired Content-Type header. Empty string means `fetch` should set it automatically\n * (used for multipart/form-data so the boundary is set correctly by the browser/Node runtime).\n */\n contentType: string;\n}>;\n\n/**\n * Builds a fetch-compatible `BodyInit` + Content-Type pair from an {@link HttpBodySpec}.\n * Multipart binaries are read from `item.binary` via `ctx.binary.openReadStream`.\n */\nexport class HttpBodyBuilder {\n async build(\n spec: HttpBodySpec | undefined,\n item: Item,\n ctx: NodeExecutionContext<RunnableNodeConfig<unknown, unknown>>,\n ): Promise<EncodedBody | undefined> {\n if (!spec || spec.kind === \"none\") {\n return undefined;\n }\n\n if (spec.kind === \"json\") {\n return {\n body: JSON.stringify(spec.data),\n contentType: \"application/json\",\n };\n }\n\n if (spec.kind === \"form\") {\n const params = new URLSearchParams();\n for (const [key, value] of Object.entries(spec.data)) {\n params.append(key, value);\n }\n return {\n body: params.toString(),\n contentType: \"application/x-www-form-urlencoded\",\n };\n }\n\n if (spec.kind === \"multipart\") {\n const formData = new FormData();\n for (const [key, value] of Object.entries(spec.fields)) {\n formData.append(key, value);\n }\n if (spec.binaries) {\n for (const [fieldName, binaryRef] of Object.entries(spec.binaries)) {\n const attachment = item.binary?.[binaryRef];\n if (attachment) {\n const readResult = await ctx.binary.openReadStream(attachment);\n if (readResult) {\n const reader = readResult.body.getReader();\n const chunks: Uint8Array[] = [];\n let done = false;\n while (!done) {\n const result = await reader.read();\n done = result.done;\n if (result.value) {\n chunks.push(result.value);\n }\n }\n const totalLength = chunks.reduce((acc, chunk) => acc + chunk.length, 0);\n const merged = new Uint8Array(totalLength);\n let offset = 0;\n for (const chunk of chunks) {\n merged.set(chunk, offset);\n offset += chunk.length;\n }\n const blob = new Blob([merged], { type: attachment.mimeType });\n formData.append(fieldName, blob, attachment.filename ?? binaryRef);\n }\n }\n }\n }\n // FormData sets its own Content-Type with boundary; empty string signals that\n // fetch should set it automatically.\n return {\n body: formData,\n contentType: \"\",\n };\n }\n\n return undefined;\n }\n}\n","/**\n * Merges query parameters into a base URL.\n * Handles both scalar and array values, and preserves any existing params.\n */\nexport class HttpUrlBuilder {\n build(baseUrl: string, query?: Readonly<Record<string, string | string[]>>): string {\n if (!query || Object.keys(query).length === 0) {\n return baseUrl;\n }\n const parsed = new URL(baseUrl);\n for (const [key, value] of Object.entries(query)) {\n if (Array.isArray(value)) {\n for (const entry of value) {\n parsed.searchParams.append(key, entry);\n }\n } else {\n parsed.searchParams.append(key, value);\n }\n }\n return parsed.toString();\n }\n}\n","import { defineNode } from \"@codemation/core\";\nimport type { DefinedNode, DefinedNodeCredentialBindings } from \"@codemation/core\";\nimport type { ZodType } from \"zod\";\nimport type { HttpBodySpec } from \"../http/httpRequest.types\";\nimport { HttpRequestExecutor } from \"../http/HttpRequestExecutor\";\nimport { HttpBodyBuilder } from \"../http/HttpBodyBuilder\";\nimport { HttpUrlBuilder } from \"../http/HttpUrlBuilder\";\n\ntype MaybePromise<T> = T | Promise<T>;\n\n/**\n * API endpoint descriptor.\n */\nexport type RestNodeApi = Readonly<{\n /**\n * Base URL, e.g. `\"https://api.slack.com\"`.\n */\n baseUrl: string;\n /**\n * Path relative to `baseUrl`. May contain `{paramName}` placeholders that\n * are substituted from `input` keys before the request is made.\n * Example: `\"/users/{userId}/profile\"`\n */\n path: string;\n /** HTTP method (default: GET). */\n method?: string;\n}>;\n\n/**\n * The HTTP result shape passed into the `response` mapper.\n */\nexport type RestNodeResponseContext = Readonly<{\n status: number;\n ok: boolean;\n statusText: string;\n mimeType: string;\n headers: Readonly<Record<string, string>>;\n json?: unknown;\n text?: string;\n}>;\n\n/**\n * What the `request` callback may return to customise the request.\n */\nexport type RestNodeRequestShape = Readonly<{\n /** Additional path parameters to substitute (merged with `input`). */\n pathParams?: Readonly<Record<string, string>>;\n /** Extra query params. */\n query?: Readonly<Record<string, string>>;\n /** Extra headers. */\n headers?: Readonly<Record<string, string>>;\n /** Request body. */\n body?: HttpBodySpec;\n}>;\n\n/**\n * Error handling policy for non-2xx responses.\n * - `\"throw\"` (default) — throws an `Error` for non-2xx responses.\n * - `\"passthrough\"` — returns the result regardless of status.\n */\nexport type RestNodeErrorPolicy = \"throw\" | \"passthrough\";\n\nexport interface DefineRestNodeOptions<\n TKey extends string,\n TCredentials extends DefinedNodeCredentialBindings | undefined,\n TInputJson,\n TOutputJson,\n> {\n readonly key: TKey;\n readonly title: string;\n readonly description?: string;\n readonly icon?: string;\n readonly api: RestNodeApi;\n /**\n * Credential bindings keyed by slot. Use the built-in credential types from\n * `@codemation/core-nodes` (e.g. `bearerTokenCredentialType`) or any custom one.\n * The slot key must match what the `request` callback's context uses.\n */\n readonly credentials?: TCredentials;\n /**\n * Zod schema for per-item input. Validated before `execute`.\n */\n readonly inputSchema?: ZodType<TInputJson>;\n /**\n * Builds the per-request customisations from the item input.\n * Return `body`, `query`, `headers`, and/or `pathParams`.\n */\n request?(context: Readonly<{ input: TInputJson }>): MaybePromise<RestNodeRequestShape>;\n /**\n * Maps the HTTP response to the node's output JSON.\n * When omitted, the output is `{ status, ok, statusText, mimeType, headers, json, text }`.\n */\n response?(context: RestNodeResponseContext & Readonly<{ input: TInputJson }>): MaybePromise<TOutputJson>;\n /**\n * How to handle non-2xx responses.\n * @default \"throw\"\n */\n readonly errorPolicy?: RestNodeErrorPolicy;\n}\n\n/**\n * Substitutes `{name}` placeholders in a path template using values from `params`.\n */\nfunction substitutePath(template: string, params: Readonly<Record<string, unknown>>): string {\n return template.replace(/\\{([^}]+)}/g, (_match, key: string) => {\n const value = params[key];\n return value !== undefined ? String(value) : `{${key}}`;\n });\n}\n\n/**\n * Declarative helper for creating thin API-wrapper nodes.\n *\n * Usage:\n * ```ts\n * export const postMessage = defineRestNode({\n * key: \"slack.post-message\",\n * title: \"Send Slack message\",\n * icon: \"si:slack\",\n * api: { baseUrl: \"https://slack.com/api\", path: \"/chat.postMessage\", method: \"POST\" },\n * credentials: { auth: bearerTokenCredentialType },\n * inputSchema: z.object({ channel: z.string(), text: z.string() }),\n * request: ({ input }) => ({\n * body: { kind: \"json\", data: { channel: input.channel, text: input.text } },\n * }),\n * response: ({ json }) => ({ messageTs: (json as any).ts }),\n * });\n * ```\n *\n * - `defineRestNode` is a thin wrapper over `defineNode`; it does not introduce a new runtime kind.\n * - Credential sessions are resolved via the `credentials` binding map (same as `defineNode`).\n * - Path `{placeholder}` substitution is applied from `input` keys before the request is made.\n * - Non-2xx responses throw an `Error` by default (`errorPolicy: \"throw\"`).\n */\nexport function defineRestNode<\n TKey extends string,\n TCredentials extends DefinedNodeCredentialBindings | undefined,\n TInputJson,\n TOutputJson = RestNodeResponseContext,\n>(\n options: DefineRestNodeOptions<TKey, TCredentials, TInputJson, TOutputJson>,\n): DefinedNode<TKey, Record<string, never>, TInputJson, TOutputJson, TCredentials> {\n const errorPolicy = options.errorPolicy ?? \"throw\";\n\n return defineNode<TKey, Record<string, never>, TInputJson, TOutputJson, TCredentials>({\n key: options.key,\n title: options.title,\n description: options.description,\n icon: options.icon,\n credentials: options.credentials,\n inputSchema: options.inputSchema,\n async execute({ input, item, ctx }, { credentials }) {\n // Resolve credential if one is bound.\n const credentialSlot = options.credentials ? Object.keys(options.credentials)[0] : undefined;\n const credential = credentialSlot\n ? await (credentials as Record<string, () => Promise<unknown>>)[credentialSlot]?.()\n : undefined;\n\n // Build path by substituting `{name}` placeholders from input.\n const inputRecord = (input as Record<string, unknown>) ?? {};\n const requestShape = options.request ? await options.request({ input }) : {};\n const pathParams = { ...inputRecord, ...(requestShape.pathParams ?? {}) };\n const resolvedPath = substitutePath(options.api.path, pathParams);\n const resolvedUrl = `${options.api.baseUrl}${resolvedPath}`;\n\n const executor = new HttpRequestExecutor(globalThis.fetch, new HttpBodyBuilder(), new HttpUrlBuilder());\n const result = await executor.execute(\n {\n url: resolvedUrl,\n method: (options.api.method ?? \"GET\").toUpperCase(),\n headers: requestShape.headers,\n query: requestShape.query,\n body: requestShape.body,\n credential: credential as Parameters<typeof executor.execute>[0][\"credential\"],\n ctx: ctx as unknown as Parameters<typeof executor.execute>[0][\"ctx\"],\n },\n item,\n );\n\n if (errorPolicy === \"throw\" && !result.ok) {\n throw new Error(`HTTP ${result.status} ${result.statusText} for ${result.method} ${result.url}`);\n }\n\n const responseCtx: RestNodeResponseContext = {\n status: result.status,\n ok: result.ok,\n statusText: result.statusText,\n mimeType: result.mimeType,\n headers: result.headers,\n ...(result.json !== undefined ? { json: result.json } : {}),\n ...(result.text !== undefined ? { text: result.text } : {}),\n };\n\n if (options.response) {\n return await options.response({ ...responseCtx, input });\n }\n\n // Wrap in `{ json: ... }` so the engine's Item-shape detection unwraps once\n // and the response context becomes the item's payload as-is (preserving the\n // inner `json` field on the response for callers).\n return { json: responseCtx } as unknown as TOutputJson;\n },\n }) as unknown as DefinedNode<TKey, Record<string, never>, TInputJson, TOutputJson, TCredentials>;\n}\n","import type { ChatLanguageModel, ChatModelFactory, NodeExecutionContext } from \"@codemation/core\";\nimport { chatModel } from \"@codemation/core\";\n\nimport { createOpenAI } from \"@ai-sdk/openai\";\n\nimport type { OpenAiCredentialSession } from \"./OpenAiCredentialSession\";\nimport type { OpenAIChatModelConfig } from \"./openAiChatModelConfig\";\n\n@chatModel({ packageName: \"@codemation/core-nodes\" })\nexport class OpenAIChatModelFactory implements ChatModelFactory<OpenAIChatModelConfig> {\n async create(\n args: Readonly<{ config: OpenAIChatModelConfig; ctx: NodeExecutionContext<any> }>,\n ): Promise<ChatLanguageModel> {\n const session = await args.ctx.getCredential<OpenAiCredentialSession>(args.config.credentialSlotKey);\n const provider = createOpenAI({\n apiKey: session.apiKey,\n baseURL: session.baseUrl,\n });\n const languageModel = provider.chat(args.config.model);\n return {\n languageModel,\n modelName: args.config.model,\n provider: \"openai\",\n defaultCallOptions: {\n maxOutputTokens: args.config.options?.maxTokens,\n temperature: args.config.options?.temperature,\n },\n };\n }\n}\n","/** A special constant with type `never` */\nexport const NEVER = Object.freeze({\n status: \"aborted\",\n});\nexport /*@__NO_SIDE_EFFECTS__*/ function $constructor(name, initializer, params) {\n function init(inst, def) {\n if (!inst._zod) {\n Object.defineProperty(inst, \"_zod\", {\n value: {\n def,\n constr: _,\n traits: new Set(),\n },\n enumerable: false,\n });\n }\n if (inst._zod.traits.has(name)) {\n return;\n }\n inst._zod.traits.add(name);\n initializer(inst, def);\n // support prototype modifications\n const proto = _.prototype;\n const keys = Object.keys(proto);\n for (let i = 0; i < keys.length; i++) {\n const k = keys[i];\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 var _a;\n const inst = params?.Parent ? new Definition() : this;\n init(inst, def);\n (_a = inst._zod).deferred ?? (_a.deferred = []);\n for (const fn of inst._zod.deferred) {\n fn();\n }\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 = 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}\nexport const globalConfig = {};\nexport function config(newConfig) {\n if (newConfig)\n Object.assign(globalConfig, newConfig);\n return globalConfig;\n}\n","// functions\nexport function assertEqual(val) {\n return val;\n}\nexport function assertNotEqual(val) {\n return val;\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}\nexport function cached(getter) {\n const set = false;\n return {\n get value() {\n if (!set) {\n const value = getter();\n Object.defineProperty(this, \"value\", { value });\n return value;\n }\n throw new Error(\"cached value already set\");\n },\n };\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 valDecCount = (val.toString().split(\".\")[1] || \"\").length;\n const stepString = step.toString();\n let stepDecCount = (stepString.split(\".\")[1] || \"\").length;\n if (stepDecCount === 0 && /\\d?e-\\d?/.test(stepString)) {\n const match = stepString.match(/\\d?e-(\\d?)/);\n if (match?.[1]) {\n stepDecCount = Number.parseInt(match[1]);\n }\n }\n const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;\n const valInt = Number.parseInt(val.toFixed(decCount).replace(\".\", \"\"));\n const stepInt = Number.parseInt(step.toFixed(decCount).replace(\".\", \"\"));\n return (valInt % stepInt) / 10 ** decCount;\n}\nconst EVALUATING = 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}\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 = cached(() => {\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 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 = new Set([\"string\", \"number\", \"symbol\"]);\nexport const primitiveTypes = new Set([\"string\", \"number\", \"bigint\", \"boolean\", \"symbol\", \"undefined\"]);\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 === \"optional\" && shape[k]._zod.optout === \"optional\";\n });\n}\nexport const NUMBER_FORMAT_RANGES = {\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 def = mergeDefs(schema._zod.def, {\n get shape() {\n const newShape = {};\n for (const key in mask) {\n if (!(key in currDef.shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n newShape[key] = currDef.shape[key];\n }\n assignProp(this, \"shape\", newShape); // self-caching\n return newShape;\n },\n checks: [],\n });\n return clone(schema, def);\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 def = mergeDefs(schema._zod.def, {\n get shape() {\n const newShape = { ...schema._zod.def.shape };\n for (const key in mask) {\n if (!(key in currDef.shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n delete newShape[key];\n }\n assignProp(this, \"shape\", newShape); // self-caching\n return newShape;\n },\n checks: [],\n });\n return clone(schema, def);\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\n // Use getOwnPropertyDescriptor to check key existence without accessing values\n const existingShape = schema._zod.def.shape;\n for (const key in 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 const def = mergeDefs(schema._zod.def, {\n get shape() {\n const _shape = { ...schema._zod.def.shape, ...shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n });\n return clone(schema, def);\n}\nexport function safeExtend(schema, shape) {\n if (!isPlainObject(shape)) {\n throw new Error(\"Invalid input to safeExtend: expected a plain object\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const _shape = { ...schema._zod.def.shape, ...shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n });\n return clone(schema, def);\n}\nexport function merge(a, b) {\n const def = mergeDefs(a._zod.def, {\n get shape() {\n const _shape = { ...a._zod.def.shape, ...b._zod.def.shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n get catchall() {\n return b._zod.def.catchall;\n },\n checks: [], // delete existing checks\n });\n return clone(a, def);\n}\nexport function partial(Class, 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(\".partial() cannot be used on object schemas containing refinements\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const oldShape = schema._zod.def.shape;\n const shape = { ...oldShape };\n if (mask) {\n for (const key in mask) {\n if (!(key in oldShape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n // if (oldShape[key]!._zod.optin === \"optional\") continue;\n shape[key] = Class\n ? new Class({\n type: \"optional\",\n innerType: oldShape[key],\n })\n : oldShape[key];\n }\n }\n else {\n for (const key in oldShape) {\n // if (oldShape[key]!._zod.optin === \"optional\") continue;\n shape[key] = Class\n ? new Class({\n type: \"optional\",\n innerType: oldShape[key],\n })\n : oldShape[key];\n }\n }\n assignProp(this, \"shape\", shape); // self-caching\n return shape;\n },\n checks: [],\n });\n return clone(schema, def);\n}\nexport function required(Class, schema, mask) {\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const oldShape = schema._zod.def.shape;\n const shape = { ...oldShape };\n if (mask) {\n for (const key in mask) {\n if (!(key in shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n // overwrite with non-optional\n shape[key] = new Class({\n type: \"nonoptional\",\n innerType: oldShape[key],\n });\n }\n }\n else {\n for (const key in oldShape) {\n // overwrite with non-optional\n shape[key] = new Class({\n type: \"nonoptional\",\n innerType: oldShape[key],\n });\n }\n }\n assignProp(this, \"shape\", shape); // self-caching\n return shape;\n },\n });\n return clone(schema, def);\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}\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}\nexport function finalizeIssue(iss, ctx, config) {\n const full = { ...iss, path: iss.path ?? [] };\n // for backwards compatibility\n if (!iss.message) {\n const message = unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ??\n unwrapMessage(ctx?.error?.(iss)) ??\n unwrapMessage(config.customError?.(iss)) ??\n unwrapMessage(config.localeError?.(iss)) ??\n \"Invalid input\";\n full.message = message;\n }\n // delete (full as any).def;\n delete full.inst;\n delete full.continue;\n if (!ctx?.reportInput) {\n delete full.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}\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","import { $constructor } from \"./core.js\";\nimport * as util from \"./util.js\";\nconst initializer = (inst, def) => {\n inst.name = \"$ZodError\";\n Object.defineProperty(inst, \"_zod\", {\n value: inst._zod,\n enumerable: false,\n });\n Object.defineProperty(inst, \"issues\", {\n value: def,\n enumerable: false,\n });\n inst.message = JSON.stringify(def, util.jsonStringifyReplacer, 2);\n Object.defineProperty(inst, \"toString\", {\n value: () => inst.message,\n enumerable: false,\n });\n};\nexport const $ZodError = $constructor(\"$ZodError\", initializer);\nexport const $ZodRealError = $constructor(\"$ZodError\", initializer, { Parent: Error });\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 fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];\n 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) => {\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\" && issue.errors.length) {\n issue.errors.map((issues) => processError({ issues }));\n }\n else if (issue.code === \"invalid_key\") {\n processError({ issues: issue.issues });\n }\n else if (issue.code === \"invalid_element\") {\n processError({ issues: issue.issues });\n }\n else if (issue.path.length === 0) {\n fieldErrors._errors.push(mapper(issue));\n }\n else {\n let curr = fieldErrors;\n let i = 0;\n while (i < issue.path.length) {\n const el = issue.path[i];\n const terminal = i === issue.path.length - 1;\n if (!terminal) {\n curr[el] = curr[el] || { _errors: [] };\n }\n else {\n curr[el] = curr[el] || { _errors: [] };\n curr[el]._errors.push(mapper(issue));\n }\n curr = curr[el];\n i++;\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, _b;\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 }, issue.path));\n }\n else if (issue.code === \"invalid_key\") {\n processError({ issues: issue.issues }, issue.path);\n }\n else if (issue.code === \"invalid_element\") {\n processError({ issues: issue.issues }, 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 (_a = curr.properties)[el] ?? (_a[el] = { errors: [] });\n curr = curr.properties[el];\n }\n else {\n curr.items ?? (curr.items = []);\n (_b = curr.items)[el] ?? (_b[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\";\nexport const _parse = (_Err) => (schema, value, _ctx, _params) => {\n const ctx = _ctx ? Object.assign(_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);\n throw e;\n }\n return result.value;\n};\nexport const parse = /* @__PURE__*/ _parse(errors.$ZodRealError);\nexport const _parseAsync = (_Err) => async (schema, value, _ctx, params) => {\n const ctx = _ctx ? Object.assign(_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);\n throw e;\n }\n return result.value;\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\n ? {\n success: false,\n error: new (_Err ?? errors.$ZodError)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n }\n : { success: true, data: result.value };\n};\nexport const safeParse = /* @__PURE__*/ _safeParse(errors.$ZodRealError);\nexport const _safeParseAsync = (_Err) => async (schema, value, _ctx) => {\n const ctx = _ctx ? Object.assign(_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\n ? {\n success: false,\n error: new _Err(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n }\n : { success: true, data: result.value };\n};\nexport const safeParseAsync = /* @__PURE__*/ _safeParseAsync(errors.$ZodRealError);\nexport const _encode = (_Err) => (schema, value, _ctx) => {\n const ctx = _ctx ? Object.assign(_ctx, { direction: \"backward\" }) : { direction: \"backward\" };\n return _parse(_Err)(schema, value, ctx);\n};\nexport const encode = /* @__PURE__*/ _encode(errors.$ZodRealError);\nexport const _decode = (_Err) => (schema, value, _ctx) => {\n return _parse(_Err)(schema, value, _ctx);\n};\nexport const decode = /* @__PURE__*/ _decode(errors.$ZodRealError);\nexport const _encodeAsync = (_Err) => async (schema, value, _ctx) => {\n const ctx = _ctx ? Object.assign(_ctx, { direction: \"backward\" }) : { direction: \"backward\" };\n return _parseAsync(_Err)(schema, value, ctx);\n};\nexport const encodeAsync = /* @__PURE__*/ _encodeAsync(errors.$ZodRealError);\nexport const _decodeAsync = (_Err) => async (schema, value, _ctx) => {\n return _parseAsync(_Err)(schema, value, _ctx);\n};\nexport const decodeAsync = /* @__PURE__*/ _decodeAsync(errors.$ZodRealError);\nexport const _safeEncode = (_Err) => (schema, value, _ctx) => {\n const ctx = _ctx ? Object.assign(_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 ? Object.assign(_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 util from \"./util.js\";\nexport const cuid = /^[cC][^\\s-]{8,}$/;\nexport const cuid2 = /^[0-9a-z]+$/;\nexport const ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/;\nexport const xid = /^[0-9a-vA-V]{20}$/;\nexport const ksuid = /^[A-Za-z0-9]{27}$/;\nexport const nanoid = /^[a-zA-Z0-9_-]{21}$/;\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-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\nconst _emoji = `^(\\\\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})?::([0-9a-fA-F]{1,4}:?){0,6})\\/(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_-]*$/;\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 = /^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,}$/;\n// https://blog.stevenlevithan.com/archives/validate-phone-number#r4-3 (regex sans spaces)\n// E.164: leading digit must be 1-9; total digits (excluding '+') between 7-15\nexport const e164 = /^\\+[1-9]\\d{6,14}$/;\n// const 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])))`;\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])))`;\nexport const date = /*@__PURE__*/ new RegExp(`^${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 : `${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 time = timeSource({ precision: args.precision });\n const opts = [\"Z\"];\n if (args.local)\n opts.push(\"\");\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 const timeRegex = `${time}(?:${opts.join(\"|\")})`;\n return new RegExp(`^${dateSource}T(?:${timeRegex})$`);\n}\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});\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.onattach.push((inst) => {\n const bag = inst._zod.bag;\n const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY;\n if (def.value < curr) {\n if (def.inclusive)\n bag.maximum = def.value;\n else\n bag.exclusiveMaximum = def.value;\n }\n });\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,\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.onattach.push((inst) => {\n const bag = inst._zod.bag;\n const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY;\n if (def.value > curr) {\n if (def.inclusive)\n bag.minimum = def.value;\n else\n bag.exclusiveMinimum = def.value;\n }\n });\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,\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.onattach.push((inst) => {\n var _a;\n (_a = inst._zod.bag).multipleOf ?? (_a.multipleOf = def.value);\n });\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 ? 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.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.format = def.format;\n bag.minimum = minimum;\n bag.maximum = maximum;\n if (isInt)\n bag.pattern = regexes.integer;\n });\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.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.format = def.format;\n bag.minimum = minimum;\n bag.maximum = maximum;\n });\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 = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.size !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY);\n if (def.maximum < curr)\n inst._zod.bag.maximum = def.maximum;\n });\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 = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.size !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY);\n if (def.minimum > curr)\n inst._zod.bag.minimum = def.minimum;\n });\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 = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.size !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.minimum = def.size;\n bag.maximum = def.size;\n bag.size = def.size;\n });\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 = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.length !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY);\n if (def.maximum < curr)\n inst._zod.bag.maximum = def.maximum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const length = input.length;\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 = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.length !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY);\n if (def.minimum > curr)\n inst._zod.bag.minimum = def.minimum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const length = input.length;\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 = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.length !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.minimum = def.length;\n bag.maximum = def.length;\n bag.length = def.length;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const length = input.length;\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 inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.format = def.format;\n if (def.pattern) {\n bag.patterns ?? (bag.patterns = new Set());\n bag.patterns.add(def.pattern);\n }\n });\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 const pattern = new RegExp(typeof def.position === \"number\" ? `^.{${def.position}}${escapedRegex}` : escapedRegex);\n def.pattern = pattern;\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.patterns ?? (bag.patterns = new Set());\n bag.patterns.add(pattern);\n });\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.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.patterns ?? (bag.patterns = new Set());\n bag.patterns.add(pattern);\n });\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.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.patterns ?? (bag.patterns = new Set());\n bag.patterns.add(pattern);\n });\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 $ZodCheckMimeType = /*@__PURE__*/ core.$constructor(\"$ZodCheckMimeType\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const mimeSet = new Set(def.mime);\n inst._zod.onattach.push((inst) => {\n inst._zod.bag.mime = def.mime;\n });\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 = []) {\n this.content = [];\n this.indent = 0;\n if (this)\n this.args = args;\n }\n indented(fn) {\n this.indent += 1;\n fn(this);\n this.indent -= 1;\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 args = this?.args;\n const content = this?.content ?? [``];\n const lines = [...content.map((x) => ` ${x}`)];\n // console.log(lines.join(\"\\n\"));\n return new F(...args, lines.join(\"\\n\"));\n }\n}\n","export const version = {\n major: 4,\n minor: 3,\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, safeParse, safeParseAsync } 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 checks = [...(inst._zod.def.checks ?? [])];\n // if inst is itself a checks.$ZodCheck, run it as a check\n if (inst._zod.traits.has(\"$ZodCheck\")) {\n checks.unshift(inst);\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\n // 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 let isAborted = util.aborted(payload);\n let asyncResult;\n for (const ch of checks) {\n if (ch._zod.def.when) {\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 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 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\n // 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 // Lazy initialize ~standard to avoid creating objects for every schema\n util.defineLazy(inst, \"~standard\", () => ({\n validate: (value) => {\n try {\n const r = safeParse(inst, value);\n return r.success ? { value: r.data } : { issues: r.error?.issues };\n }\n catch (_) {\n return safeParseAsync(inst, value).then((r) => (r.success ? { value: r.data } : { issues: r.error?.issues }));\n }\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 inst._zod.pattern = [...(inst?._zod.bag?.patterns ?? [])].pop() ?? regexes.string(inst._zod.bag);\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});\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 // @ts-ignore\n const url = new URL(trimmed);\n if (def.hostname) {\n def.hostname.lastIndex = 0;\n if (!def.hostname.test(url.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 }\n if (def.protocol) {\n def.protocol.lastIndex = 0;\n if (!def.protocol.test(url.protocol.endsWith(\":\") ? url.protocol.slice(0, -1) : url.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 }\n // Set the output value based on normalize flag\n if (def.normalize) {\n // Use normalized URL\n payload.value = url.href;\n }\n else {\n // Preserve the original input (trimmed)\n payload.value = trimmed;\n }\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 def.pattern ?? (def.pattern = regexes.nanoid);\n $ZodStringFormat.init(inst, def);\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 inst._zod.bag.format = `ipv4`;\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.bag.format = `ipv6`;\n inst._zod.check = (payload) => {\n try {\n // @ts-ignore\n new URL(`http://[${payload.value}]`);\n // return;\n }\n catch {\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 inst._zod.bag.format = `mac`;\n});\nexport const $ZodCIDRv4 = /*@__PURE__*/ core.$constructor(\"$ZodCIDRv4\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cidrv4);\n $ZodStringFormat.init(inst, def);\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 const parts = payload.value.split(\"/\");\n try {\n if (parts.length !== 2)\n throw new Error();\n const [address, prefix] = parts;\n if (!prefix)\n throw new Error();\n const prefixNum = Number(prefix);\n if (`${prefixNum}` !== prefix)\n throw new Error();\n if (prefixNum < 0 || prefixNum > 128)\n throw new Error();\n // @ts-ignore\n new URL(`http://[${address}]`);\n }\n catch {\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 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}\nexport const $ZodBase64 = /*@__PURE__*/ core.$constructor(\"$ZodBase64\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.base64);\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.contentEncoding = \"base64\";\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////////////////////////////// ZodBase64 //////////////////////////////\nexport function isValidBase64URL(data) {\n if (!regexes.base64url.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 = regexes.base64url);\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.contentEncoding = \"base64url\";\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////////////////////////////// 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 = inst._zod.bag.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 ? \"Infinity\"\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.optin = \"optional\";\n inst._zod.optout = \"optional\";\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});\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 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 = Array(input.length);\n const proms = [];\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 }\n }\n if (proms.length) {\n return Promise.all(proms).then(() => payload);\n }\n return payload; //handleArrayResultsAsync(parseResults, final);\n };\n});\nfunction handlePropertyResult(result, final, key, input, isOptionalOut) {\n if (result.issues.length) {\n // For optional-out schemas, ignore errors on absent keys\n if (isOptionalOut && !(key in input)) {\n return;\n }\n final.issues.push(...util.prefixIssues(key, result.issues));\n }\n if (result.value === undefined) {\n if (key in input) {\n final.value[key] = undefined;\n }\n }\n else {\n final.value[key] = result.value;\n }\n}\nfunction normalizeDef(def) {\n const keys = Object.keys(def.shape);\n for (const k of keys) {\n if (!def.shape?.[k]?._zod?.traits?.has(\"$ZodType\")) {\n throw new Error(`Invalid element at key \"${k}\": expected a Zod schema`);\n }\n }\n const okeys = util.optionalKeys(def.shape);\n return {\n ...def,\n keys,\n keySet: new Set(keys),\n numKeys: keys.length,\n optionalKeys: new Set(okeys),\n };\n}\nfunction handleCatchall(proms, input, payload, ctx, def, inst) {\n const unrecognized = [];\n // iterate over input keys\n const keySet = def.keySet;\n const _catchall = def.catchall._zod;\n const t = _catchall.def.type;\n const isOptionalOut = _catchall.optout === \"optional\";\n for (const key in input) {\n if (keySet.has(key))\n continue;\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, isOptionalOut)));\n }\n else {\n handlePropertyResult(r, payload, key, input, isOptionalOut);\n }\n }\n if (unrecognized.length) {\n payload.issues.push({\n code: \"unrecognized_keys\",\n keys: unrecognized,\n input,\n inst,\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 sh = def.shape;\n const desc = Object.getOwnPropertyDescriptor(def, \"shape\");\n if (!desc?.get) {\n const sh = def.shape;\n Object.defineProperty(def, \"shape\", {\n get: () => {\n const newSh = { ...sh };\n Object.defineProperty(def, \"shape\", {\n value: newSh,\n });\n return newSh;\n },\n });\n }\n const _normalized = util.cached(() => normalizeDef(def));\n util.defineLazy(inst._zod, \"propValues\", () => {\n const shape = def.shape;\n const propValues = {};\n for (const key in shape) {\n const field = shape[key]._zod;\n if (field.values) {\n propValues[key] ?? (propValues[key] = new Set());\n for (const v of field.values)\n propValues[key].add(v);\n }\n }\n return propValues;\n });\n const isObject = util.isObject;\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 payload.value = {};\n const proms = [];\n const shape = value.shape;\n for (const key of value.keys) {\n const el = shape[key];\n const isOptionalOut = el._zod.optout === \"optional\";\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, isOptionalOut)));\n }\n else {\n handlePropertyResult(r, payload, key, input, isOptionalOut);\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);\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 generateFastpass = (shape) => {\n const doc = new Doc([\"shape\", \"payload\", \"ctx\"]);\n const normalized = _normalized.value;\n const parseStr = (key) => {\n const k = util.esc(key);\n return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;\n };\n doc.write(`const input = payload.value;`);\n const ids = Object.create(null);\n let counter = 0;\n for (const key of normalized.keys) {\n ids[key] = `key_${counter++}`;\n }\n // A: preserve key order {\n doc.write(`const newResult = {};`);\n for (const key of normalized.keys) {\n const id = ids[key];\n const k = util.esc(key);\n const schema = shape[key];\n const isOptionalOut = schema?._zod?.optout === \"optional\";\n doc.write(`const ${id} = ${parseStr(key)};`);\n if (isOptionalOut) {\n // For optional-out schemas, ignore errors on absent keys\n doc.write(`\n if (${id}.issues.length) {\n if (${k} in input) {\n payload.issues = payload.issues.concat(${id}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${k}, ...iss.path] : [${k}]\n })));\n }\n }\n \n if (${id}.value === undefined) {\n if (${k} in input) {\n newResult[${k}] = undefined;\n }\n } else {\n newResult[${k}] = ${id}.value;\n }\n \n `);\n }\n else {\n doc.write(`\n if (${id}.issues.length) {\n payload.issues = payload.issues.concat(${id}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${k}, ...iss.path] : [${k}]\n })));\n }\n \n if (${id}.value === undefined) {\n if (${k} in input) {\n newResult[${k}] = undefined;\n }\n } else {\n newResult[${k}] = ${id}.value;\n }\n \n `);\n }\n }\n doc.write(`payload.value = newResult;`);\n doc.write(`return payload;`);\n const fn = doc.compile();\n return (payload, ctx) => fn(shape, payload, ctx);\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);\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.defineLazy(inst._zod, \"optin\", () => def.options.some((o) => o._zod.optin === \"optional\") ? \"optional\" : undefined);\n util.defineLazy(inst._zod, \"optout\", () => def.options.some((o) => o._zod.optout === \"optional\") ? \"optional\" : undefined);\n util.defineLazy(inst._zod, \"values\", () => {\n if (def.options.every((o) => o._zod.values)) {\n return new Set(def.options.flatMap((option) => Array.from(option._zod.values)));\n }\n return undefined;\n });\n util.defineLazy(inst._zod, \"pattern\", () => {\n if (def.options.every((o) => o._zod.pattern)) {\n const patterns = 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 single = def.options.length === 1;\n const first = def.options[0]._zod.run;\n inst._zod.parse = (payload, ctx) => {\n if (single) {\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 successes = results.filter((r) => r.issues.length === 0);\n if (successes.length === 1) {\n final.value = successes[0].value;\n return final;\n }\n if (successes.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 });\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 single = def.options.length === 1;\n const first = def.options[0]._zod.run;\n inst._zod.parse = (payload, ctx) => {\n if (single) {\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});\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.defineLazy(inst._zod, \"propValues\", () => {\n const propValues = {};\n for (const option of 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 \"${def.options.indexOf(option)}\"`);\n for (const [k, v] of Object.entries(pv)) {\n if (!propValues[k])\n propValues[k] = new Set();\n for (const val of v) {\n propValues[k].add(val);\n }\n }\n }\n return propValues;\n });\n const disc = util.cached(() => {\n const opts = def.options;\n const map = new Map();\n for (const o of opts) {\n const values = o._zod.propValues?.[def.discriminator];\n if (!values || values.size === 0)\n throw new Error(`Invalid discriminated union option at index \"${def.options.indexOf(o)}\"`);\n for (const v of values) {\n if (map.has(v)) {\n throw new Error(`Duplicate discriminator value \"${String(v)}\"`);\n }\n map.set(v, o);\n }\n }\n return map;\n });\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 opt = disc.value.get(input?.[def.discriminator]);\n if (opt) {\n return opt._zod.run(payload, ctx);\n }\n if (def.unionFallback) {\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 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});\nfunction 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 for (const key of sharedKeys) {\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) report each key as unrecognized\n const unrecKeys = new Map();\n let unrecIssue;\n for (const iss of left.issues) {\n if (iss.code === \"unrecognized_keys\") {\n unrecIssue ?? (unrecIssue = iss);\n for (const k of iss.keys) {\n if (!unrecKeys.has(k))\n unrecKeys.set(k, {});\n unrecKeys.get(k).l = true;\n }\n }\n else {\n result.issues.push(iss);\n }\n }\n for (const iss of right.issues) {\n if (iss.code === \"unrecognized_keys\") {\n for (const k of iss.keys) {\n if (!unrecKeys.has(k))\n unrecKeys.set(k, {});\n unrecKeys.get(k).r = true;\n }\n }\n else {\n result.issues.push(iss);\n }\n }\n // Report only keys unrecognized by BOTH sides\n const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k);\n if (bothKeys.length && unrecIssue) {\n result.issues.push({ ...unrecIssue, keys: bothKeys });\n }\n if (util.aborted(result))\n return result;\n const merged = mergeValues(left.value, right.value);\n if (!merged.valid) {\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 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 = [];\n const proms = [];\n const reversedIndex = [...items].reverse().findIndex((item) => item._zod.optin !== \"optional\");\n const optStart = reversedIndex === -1 ? 0 : items.length - reversedIndex;\n if (!def.rest) {\n const tooBig = input.length > items.length;\n const tooSmall = input.length < optStart - 1;\n if (tooBig || tooSmall) {\n payload.issues.push({\n ...(tooBig\n ? { code: \"too_big\", maximum: items.length, inclusive: true }\n : { code: \"too_small\", minimum: items.length }),\n input,\n inst,\n origin: \"array\",\n });\n return payload;\n }\n }\n let i = -1;\n for (const item of items) {\n i++;\n if (i >= input.length)\n if (i >= optStart)\n continue;\n const result = item._zod.run({\n value: input[i],\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => handleTupleResult(result, payload, i)));\n }\n else {\n handleTupleResult(result, payload, i);\n }\n }\n if (def.rest) {\n const rest = input.slice(items.length);\n for (const el of rest) {\n i++;\n const result = def.rest._zod.run({\n value: el,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => handleTupleResult(result, payload, i)));\n }\n else {\n handleTupleResult(result, payload, i);\n }\n }\n }\n if (proms.length)\n return Promise.all(proms).then(() => payload);\n return payload;\n };\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}\nexport const $ZodRecord = /*@__PURE__*/ core.$constructor(\"$ZodRecord\", (inst, def) => {\n $ZodType.init(inst, def);\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 const proms = [];\n const values = def.keyType._zod.values;\n if (values) {\n payload.value = {};\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 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[key] = result.value;\n }));\n }\n else {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[key] = result.value;\n }\n }\n }\n let unrecognized;\n for (const key in input) {\n if (!recordKeys.has(key)) {\n unrecognized = unrecognized ?? [];\n unrecognized.push(key);\n }\n }\n if (unrecognized && unrecognized.length > 0) {\n payload.issues.push({\n code: \"unrecognized_keys\",\n input,\n inst,\n keys: unrecognized,\n });\n }\n }\n else {\n payload.value = {};\n for (const key of Reflect.ownKeys(input)) {\n if (key === \"__proto__\")\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)\n // 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 {\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 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[keyResult.value] = result.value;\n }));\n }\n else {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[keyResult.value] = result.value;\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 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 = new Map();\n for (const [key, value] of input) {\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});\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 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 = new Set();\n for (const item of input) {\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});\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 inst._zod.pattern = new RegExp(`^(${values\n .filter((k) => util.propertyKeyTypes.has(typeof k))\n .map((o) => (typeof o === \"string\" ? util.escapeRegex(o) : o.toString()))\n .join(\"|\")})$`);\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 if (def.values.length === 0) {\n throw new Error(\"Cannot create literal schema with no valid values\");\n }\n const values = new Set(def.values);\n inst._zod.values = values;\n inst._zod.pattern = new RegExp(`^(${def.values\n .map((o) => (typeof o === \"string\" ? util.escapeRegex(o) : o ? util.escapeRegex(o.toString()) : String(o)))\n .join(\"|\")})$`);\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.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(result, input) {\n if (result.issues.length && input === undefined) {\n return { issues: [], value: undefined };\n }\n return result;\n}\nexport const $ZodOptional = /*@__PURE__*/ core.$constructor(\"$ZodOptional\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.optin = \"optional\";\n inst._zod.optout = \"optional\";\n util.defineLazy(inst._zod, \"values\", () => {\n return def.innerType._zod.values ? new Set([...def.innerType._zod.values, undefined]) : undefined;\n });\n util.defineLazy(inst._zod, \"pattern\", () => {\n const pattern = def.innerType._zod.pattern;\n return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)})?$`) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n if (def.innerType._zod.optin === \"optional\") {\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise)\n return result.then((r) => handleOptionalResult(r, payload.value));\n return handleOptionalResult(result, payload.value);\n }\n if (payload.value === undefined) {\n return payload;\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.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n util.defineLazy(inst._zod, \"pattern\", () => 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.defineLazy(inst._zod, \"optin\", () => def.innerType._zod.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.innerType._zod.optout);\n util.defineLazy(inst._zod, \"pattern\", () => {\n const pattern = def.innerType._zod.pattern;\n return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)}|null)$`) : undefined;\n });\n util.defineLazy(inst._zod, \"values\", () => {\n return def.innerType._zod.values ? new Set([...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 = \"optional\";\n util.defineLazy(inst._zod, \"values\", () => 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 = \"optional\";\n util.defineLazy(inst._zod, \"values\", () => 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.defineLazy(inst._zod, \"values\", () => {\n const v = 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});\nexport const $ZodCatch = /*@__PURE__*/ core.$constructor(\"$ZodCatch\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"optin\", () => def.innerType._zod.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.innerType._zod.optout);\n util.defineLazy(inst._zod, \"values\", () => 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(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => {\n payload.value = result.value;\n if (result.issues.length) {\n payload.value = def.catchValue({\n ...payload,\n error: {\n issues: result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n },\n input: payload.value,\n });\n payload.issues = [];\n }\n return payload;\n });\n }\n payload.value = result.value;\n if (result.issues.length) {\n payload.value = def.catchValue({\n ...payload,\n error: {\n issues: result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n },\n input: payload.value,\n });\n payload.issues = [];\n }\n return payload;\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.defineLazy(inst._zod, \"values\", () => def.in._zod.values);\n util.defineLazy(inst._zod, \"optin\", () => def.in._zod.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.out._zod.optout);\n util.defineLazy(inst._zod, \"propValues\", () => 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 if (left.issues.length) {\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.defineLazy(inst._zod, \"values\", () => def.in._zod.values);\n util.defineLazy(inst._zod, \"optin\", () => def.in._zod.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.out._zod.optout);\n util.defineLazy(inst._zod, \"propValues\", () => 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 $ZodReadonly = /*@__PURE__*/ core.$constructor(\"$ZodReadonly\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"propValues\", () => def.innerType._zod.propValues);\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n util.defineLazy(inst._zod, \"optin\", () => def.innerType?._zod?.optin);\n util.defineLazy(inst._zod, \"optout\", () => 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 payload.value = Object.freeze(payload.value);\n return payload;\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 if (!part._zod.pattern) {\n // if (!source)\n throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`);\n }\n const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern;\n if (!source)\n throw new Error(`Invalid template literal part: ${part._zod.traits}`);\n const start = source.startsWith(\"^\") ? 1 : 0;\n const end = source.endsWith(\"$\") ? source.length - 1 : source.length;\n regexParts.push(source.slice(start, end));\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 inst._def = 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 return 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 };\n };\n inst.implementAsync = (func) => {\n if (typeof func !== \"function\") {\n throw new Error(\"implementAsync() must be called with a function\");\n }\n return 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 };\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 // let _innerType!: any;\n // util.defineLazy(def, \"getter\", () => {\n // if (!_innerType) {\n // _innerType = def.getter();\n // }\n // return () => _innerType;\n // });\n util.defineLazy(inst._zod, \"innerType\", () => def.getter());\n util.defineLazy(inst._zod, \"pattern\", () => inst._zod.innerType?._zod?.pattern);\n util.defineLazy(inst._zod, \"propValues\", () => inst._zod.innerType?._zod?.propValues);\n util.defineLazy(inst._zod, \"optin\", () => inst._zod.innerType?._zod?.optin ?? undefined);\n util.defineLazy(inst._zod, \"optout\", () => inst._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 = Symbol(\"ZodOutput\");\nexport const $input = 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\";\n// @__NO_SIDE_EFFECTS__\nexport function _string(Class, params) {\n return new Class({\n type: \"string\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedString(Class, params) {\n return new Class({\n type: \"string\",\n coerce: true,\n ...util.normalizeParams(params),\n });\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// @__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 _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({\n type: \"number\",\n checks: [],\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedNumber(Class, params) {\n return new Class({\n type: \"number\",\n coerce: true,\n checks: [],\n ...util.normalizeParams(params),\n });\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 _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,\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 : () => 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) {\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 _issue.input ?? (_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 });\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 return codec;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _stringFormat(Class, format, fnOrRegex, _params = {}) {\n const params = util.normalizeParams(_params);\n const def = {\n ...util.normalizeParams(_params),\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\";\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 cycles: params?.cycles ?? \"ref\",\n reused: params?.reused ?? \"inline\",\n external: params?.external ?? undefined,\n };\n}\nexport function process(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 // 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 process(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 Object.assign(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\" && result.schema._prefault)\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}\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 // 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\n // defId will be empty if the ref points to an external schema (or #)\n const makeURI = (entry) => {\n // comparing the seen objects because sometimes\n // multiple schemas map to the same seen object.\n // 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}/${id}` };\n }\n if (entry[1] === root) {\n return { ref: \"#\" };\n }\n // self-contained schema\n const uriPrefix = `#`;\n const defUriPrefix = `${uriPrefix}/${defsSegment}/`;\n const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`;\n return { defId, ref: defUriPrefix + defId };\n };\n // stored cached version in `def` property\n // 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\n // 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 // biome-ignore lint:\n continue;\n }\n }\n }\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 Object.assign(schema, refSchema);\n }\n // restore child's own properties (child wins)\n Object.assign(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\n // This handles cases like: readonly().meta({id}).describe()\n // 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 for (const entry of [...ctx.seen.entries()].reverse()) {\n flattenRef(entry[0]);\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 Object.assign(result, root.def ?? root.schema);\n // build defs object\n const defs = ctx.external?.defs ?? {};\n for (const entry of ctx.seen.entries()) {\n const seen = entry[1];\n if (seen.def && seen.defId) {\n defs[seen.defId] = seen.def;\n }\n }\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\n // each call to finalize() is functionally independent\n // 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 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 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 process(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 process(schema, ctx);\n extractDefs(ctx, schema);\n return finalize(ctx, schema);\n};\n","import { extractDefs, finalize, initializeContext, process, } from \"./to-json-schema.js\";\nimport { getEnumValues } from \"./util.js\";\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 ====================\nexport const stringProcessor = (schema, ctx, _json, _params) => {\n const json = _json;\n json.type = \"string\";\n const { minimum, maximum, format, patterns, contentEncoding } = schema._zod\n .bag;\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 // JSON Schema format: \"time\" requires a full time with offset or Z\n // z.iso.time() does not include timezone information, so format: \"time\" should never be used\n if (format === \"time\") {\n delete json.format;\n }\n }\n if (contentEncoding)\n json.contentEncoding = contentEncoding;\n if (patterns && patterns.size > 0) {\n const regexes = [...patterns];\n if (regexes.length === 1)\n json.pattern = regexes[0].source;\n else if (regexes.length > 1) {\n json.allOf = [\n ...regexes.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, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag;\n if (typeof format === \"string\" && format.includes(\"int\"))\n json.type = \"integer\";\n else\n json.type = \"number\";\n if (typeof exclusiveMinimum === \"number\") {\n if (ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\") {\n json.minimum = exclusiveMinimum;\n json.exclusiveMinimum = true;\n }\n else {\n json.exclusiveMinimum = exclusiveMinimum;\n }\n }\n if (typeof minimum === \"number\") {\n json.minimum = minimum;\n if (typeof exclusiveMinimum === \"number\" && ctx.target !== \"draft-04\") {\n if (exclusiveMinimum >= minimum)\n delete json.minimum;\n else\n delete json.exclusiveMinimum;\n }\n }\n if (typeof exclusiveMaximum === \"number\") {\n if (ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\") {\n json.maximum = exclusiveMaximum;\n json.exclusiveMaximum = true;\n }\n else {\n json.exclusiveMaximum = exclusiveMaximum;\n }\n }\n if (typeof maximum === \"number\") {\n json.maximum = maximum;\n if (typeof exclusiveMaximum === \"number\" && ctx.target !== \"draft-04\") {\n if (exclusiveMaximum <= maximum)\n delete json.maximum;\n else\n delete json.exclusiveMaximum;\n }\n }\n if (typeof multipleOf === \"number\")\n json.multipleOf = multipleOf;\n};\nexport const booleanProcessor = (_schema, _ctx, json, _params) => {\n json.type = \"boolean\";\n};\nexport const bigintProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"BigInt cannot be represented in JSON Schema\");\n }\n};\nexport const symbolProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Symbols cannot be represented in JSON Schema\");\n }\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 if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Undefined cannot be represented in JSON Schema\");\n }\n};\nexport const voidProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Void cannot be represented in JSON Schema\");\n }\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 if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Date cannot be represented in JSON Schema\");\n }\n};\nexport const enumProcessor = (schema, _ctx, json, _params) => {\n const def = schema._zod.def;\n const values = getEnumValues(def.entries);\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 const vals = [];\n for (const val of def.values) {\n if (val === undefined) {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Literal `undefined` cannot be represented in JSON Schema\");\n }\n else {\n // do not add to vals\n }\n }\n else if (typeof val === \"bigint\") {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"BigInt literals cannot be represented in JSON Schema\");\n }\n else {\n vals.push(Number(val));\n }\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 if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"NaN cannot be represented in JSON Schema\");\n }\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 const file = {\n type: \"string\",\n format: \"binary\",\n contentEncoding: \"binary\",\n };\n const { minimum, maximum, mime } = schema._zod.bag;\n if (minimum !== undefined)\n file.minLength = minimum;\n if (maximum !== undefined)\n file.maxLength = maximum;\n if (mime) {\n if (mime.length === 1) {\n file.contentMediaType = mime[0];\n Object.assign(_json, file);\n }\n else {\n Object.assign(_json, file); // shared props at root\n _json.anyOf = mime.map((m) => ({ contentMediaType: m })); // only contentMediaType differs\n }\n }\n else {\n Object.assign(_json, file);\n }\n};\nexport const successProcessor = (_schema, _ctx, json, _params) => {\n json.type = \"boolean\";\n};\nexport const customProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Custom types cannot be represented in JSON Schema\");\n }\n};\nexport const functionProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Function types cannot be represented in JSON Schema\");\n }\n};\nexport const transformProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Transforms cannot be represented in JSON Schema\");\n }\n};\nexport const mapProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Map cannot be represented in JSON Schema\");\n }\n};\nexport const setProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Set cannot be represented in JSON Schema\");\n }\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 } = schema._zod.bag;\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 = process(def.element, ctx, { ...params, path: [...params.path, \"items\"] });\n};\nexport const objectProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n json.type = \"object\";\n json.properties = {};\n const shape = def.shape;\n for (const key in shape) {\n json.properties[key] = process(shape[key], ctx, {\n ...params,\n path: [...params.path, \"properties\", key],\n });\n }\n // required keys\n const allKeys = new Set(Object.keys(shape));\n const requiredKeys = new Set([...allKeys].filter((key) => {\n const v = def.shape[key]._zod;\n if (ctx.io === \"input\") {\n return v.optin === undefined;\n }\n else {\n return v.optout === undefined;\n }\n }));\n if (requiredKeys.size > 0) {\n json.required = Array.from(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 = process(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)\n // This includes both z.xor() and discriminated unions\n const isExclusive = def.inclusive === false;\n const options = def.options.map((x, i) => process(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 = process(def.left, ctx, {\n ...params,\n path: [...params.path, \"allOf\", 0],\n });\n const b = process(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};\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) => process(x, ctx, {\n ...params,\n path: [...params.path, prefixPath, i],\n }));\n const rest = def.rest\n ? process(def.rest, ctx, {\n ...params,\n path: [...params.path, restPath, ...(ctx.target === \"openapi-3.0\" ? [def.items.length] : [])],\n })\n : null;\n if (ctx.target === \"draft-2020-12\") {\n json.prefixItems = prefixItems;\n if (rest) {\n json.items = rest;\n }\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 json.minItems = prefixItems.length;\n if (!rest) {\n json.maxItems = prefixItems.length;\n }\n }\n else {\n json.items = prefixItems;\n if (rest) {\n json.additionalItems = rest;\n }\n }\n // length\n const { minimum, maximum } = schema._zod.bag;\n if (typeof minimum === \"number\")\n json.minItems = minimum;\n if (typeof maximum === \"number\")\n json.maxItems = maximum;\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\n // This correctly represents \"only validate keys matching the pattern\" semantics\n // and composes well with allOf (intersections)\n const keyType = def.keyType;\n const keyBag = keyType._zod.bag;\n const patterns = keyBag?.patterns;\n if (def.mode === \"loose\" && patterns && patterns.size > 0) {\n // Use patternProperties for looseRecord with regex patterns\n const valueSchema = process(def.valueType, ctx, {\n ...params,\n path: [...params.path, \"patternProperties\", \"*\"],\n });\n json.patternProperties = {};\n for (const pattern of patterns) {\n json.patternProperties[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 = process(def.keyType, ctx, {\n ...params,\n path: [...params.path, \"propertyNames\"],\n });\n }\n json.additionalProperties = process(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 if (keyValues) {\n const validKeyValues = [...keyValues].filter((v) => typeof v === \"string\" || typeof v === \"number\");\n if (validKeyValues.length > 0) {\n json.required = validKeyValues;\n }\n }\n};\nexport const nullableProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n const inner = process(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 process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n};\nexport const defaultProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n json.default = JSON.parse(JSON.stringify(def.defaultValue));\n};\nexport const prefaultProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n if (ctx.io === \"input\")\n json._prefault = JSON.parse(JSON.stringify(def.defaultValue));\n};\nexport const catchProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n process(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 throw new Error(\"Dynamic catch values are not supported in JSON Schema\");\n }\n json.default = catchValue;\n};\nexport const pipeProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n const innerType = ctx.io === \"input\" ? (def.in._zod.def.type === \"transform\" ? def.out : def.in) : def.out;\n process(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 process(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 process(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 process(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 process(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 process(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 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 process(input, ctx);\n extractDefs(ctx, input);\n return finalize(ctx, input);\n}\n","import type {\n CredentialRequirement,\n CredentialSessionService,\n NodeConfigBase,\n NodeExecutionContext,\n NodeId,\n} from \"@codemation/core\";\n\nimport { CredentialResolverFactory } from \"@codemation/core/bootstrap\";\n\n/**\n * Builds a {@link NodeExecutionContext} whose identity for credential binding and `getCredential`\n * is a **connection-owned** workflow node id (`ConnectionNodeIdFactory` in `@codemation/core`),\n * not the executing parent node. Use for LLM slots, tool slots, or any connection-scoped owner.\n */\nexport class ConnectionCredentialExecutionContextFactory {\n private readonly credentialResolverFactory: CredentialResolverFactory;\n\n constructor(credentialSessions: CredentialSessionService) {\n this.credentialResolverFactory = new CredentialResolverFactory(credentialSessions);\n }\n\n forConnectionNode<TConfig extends NodeConfigBase>(\n ctx: NodeExecutionContext<TConfig>,\n args: Readonly<{\n connectionNodeId: NodeId;\n getCredentialRequirements: () => ReadonlyArray<CredentialRequirement>;\n }>,\n ): NodeExecutionContext<TConfig> {\n const stubConfig = { getCredentialRequirements: args.getCredentialRequirements } as NodeConfigBase;\n const getCredential = this.credentialResolverFactory.create(ctx.workflowId, args.connectionNodeId, stubConfig);\n return {\n ...ctx,\n nodeId: args.connectionNodeId,\n getCredential,\n };\n }\n}\n","import type { CredentialSessionService, ZodSchemaAny } from \"@codemation/core\";\nimport { injectable } from \"@codemation/core\";\n\nimport { toJSONSchema as frameworkToJSONSchema } from \"zod/v4/core\";\n\nimport { ConnectionCredentialExecutionContextFactory } from \"./ConnectionCredentialExecutionContextFactory\";\n\n/**\n * Shape of the instance-level `toJSONSchema` method that Zod v4 schemas expose. Conversions must go\n * through this instance method (see {@link AIAgentExecutionHelpersFactory#createJsonSchemaRecord})\n * rather than the module-level `toJSONSchema` import because the consumer's workflow-loader (see\n * `CodemationConsumerConfigLoader.toNamespace`) can load Zod under a separate tsx namespace. That\n * produces two runtime copies of Zod whose internal class / symbol identities don't overlap, so the\n * framework-side module-level `toJSONSchema` throws \"Cannot read properties of undefined (reading\n * 'def')\" on consumer-created schemas. The instance method is bound inside the schema's own module\n * and therefore uses the matching Zod internals.\n */\ntype ZodInstanceToJsonSchema = (params?: Readonly<{ target: \"draft-07\" | \"draft-7\" | \"draft-2020-12\" }>) => unknown;\n\n/**\n * Helper utilities shared by {@link AIAgentNode} and supporting runners.\n *\n * Responsibilities:\n * - {@link #createConnectionCredentialExecutionContextFactory} centralizes credential-context wiring.\n * - {@link #createJsonSchemaRecord} is a pure Zod → draft-07 converter used by both\n * `OpenAiStrictJsonSchemaFactory` (to feed OpenAI-strict structured output) and the\n * `AgentStructuredOutputRepairPromptFactory` (to show a required-schema reminder).\n */\n@injectable()\nexport class AIAgentExecutionHelpersFactory {\n createConnectionCredentialExecutionContextFactory(\n credentialSessions: CredentialSessionService,\n ): ConnectionCredentialExecutionContextFactory {\n return new ConnectionCredentialExecutionContextFactory(credentialSessions);\n }\n\n /**\n * Produces a plain JSON Schema object (`draft-07`) from a Zod schema, as needed by\n * OpenAI tool-parameter schemas and the structured-output repair prompt.\n * - Prefers the schema's **instance** `toJSONSchema(...)` method so we stay inside the Zod\n * instance that created the schema (works across consumer/framework tsx namespaces — see\n * {@link ZodInstanceToJsonSchema}). Falls back to the framework-imported module function.\n * - Strips root `$schema` (OpenAI ignores it).\n * - Sanitizes `required` for cfworker json-schema compatibility (must be a string array or absent).\n */\n createJsonSchemaRecord(\n inputSchema: ZodSchemaAny,\n options: Readonly<{\n schemaName: string;\n requireObjectRoot: boolean;\n }>,\n ): Record<string, unknown> {\n const draft07Params = { target: \"draft-07\" as const };\n const converted = this.convertZodSchemaToJsonSchema(inputSchema, draft07Params);\n const record = converted as Record<string, unknown>;\n const { $schema: _draftSchemaOmitted, ...rest } = record;\n if (options.requireObjectRoot && rest.type !== \"object\") {\n throw new Error(\n `Cannot create tool \"${options.schemaName}\": tool input schema must be a JSON Schema object type (got type=${String(rest.type)}).`,\n );\n }\n if (\n options.requireObjectRoot &&\n rest.properties !== undefined &&\n (typeof rest.properties !== \"object\" || Array.isArray(rest.properties))\n ) {\n throw new Error(\n `Cannot create tool \"${options.schemaName}\": tool input schema \"properties\" must be an object (got ${JSON.stringify(rest.properties)}).`,\n );\n }\n if (options.requireObjectRoot && rest.properties === undefined) {\n rest.properties = {};\n }\n this.sanitizeJsonSchemaRequiredKeywordsForCfworker(rest);\n return rest;\n }\n\n /**\n * Runs Zod's `toJSONSchema` via the schema's own instance method when available, so consumer\n * schemas loaded under a different tsx namespace still convert correctly. If the caller handed us\n * a payload that lacks that method (e.g. a plain JSON Schema record or a Zod instance whose\n * prototype was stripped), we fall back to the framework-bundled module function.\n */\n private convertZodSchemaToJsonSchema(inputSchema: ZodSchemaAny, params: Readonly<{ target: \"draft-07\" }>): unknown {\n const candidate = (inputSchema as unknown as { toJSONSchema?: ZodInstanceToJsonSchema }).toJSONSchema;\n if (typeof candidate === \"function\") {\n return candidate.call(inputSchema, params);\n }\n return frameworkToJSONSchema(inputSchema as unknown as Parameters<typeof frameworkToJSONSchema>[0], params);\n }\n\n /**\n * `@cfworker/json-schema` iterates `schema.required` with `for...of`; it must be a string array or absent.\n */\n private sanitizeJsonSchemaRequiredKeywordsForCfworker(node: unknown): void {\n if (!node || typeof node !== \"object\" || Array.isArray(node)) {\n return;\n }\n const o = node as Record<string, unknown>;\n const req = o.required;\n if (req !== undefined && !Array.isArray(req)) {\n delete o.required;\n } else if (Array.isArray(req)) {\n const strings = req.filter((x): x is string => typeof x === \"string\");\n if (strings.length === 0) {\n delete o.required;\n } else if (strings.length !== req.length) {\n o.required = strings;\n }\n }\n const props = o.properties;\n if (props && typeof props === \"object\" && !Array.isArray(props)) {\n for (const v of Object.values(props)) {\n this.sanitizeJsonSchemaRequiredKeywordsForCfworker(v);\n }\n }\n for (const key of [\"allOf\", \"anyOf\", \"oneOf\"] as const) {\n const branch = o[key];\n if (Array.isArray(branch)) {\n for (const sub of branch) {\n this.sanitizeJsonSchemaRequiredKeywordsForCfworker(sub);\n }\n }\n }\n if (o.if) this.sanitizeJsonSchemaRequiredKeywordsForCfworker(o.if);\n if (o.then) this.sanitizeJsonSchemaRequiredKeywordsForCfworker(o.then);\n if (o.else) this.sanitizeJsonSchemaRequiredKeywordsForCfworker(o.else);\n if (o.not) this.sanitizeJsonSchemaRequiredKeywordsForCfworker(o.not);\n if (o.items) this.sanitizeJsonSchemaRequiredKeywordsForCfworker(o.items);\n if (Array.isArray(o.prefixItems)) {\n for (const sub of o.prefixItems) {\n this.sanitizeJsonSchemaRequiredKeywordsForCfworker(sub);\n }\n }\n }\n}\n","import type { ZodSchemaAny } from \"@codemation/core\";\nimport { inject, injectable } from \"@codemation/core\";\n\nimport { AIAgentExecutionHelpersFactory } from \"../nodes/AIAgentExecutionHelpersFactory\";\n\n/**\n * Produces an OpenAI **strict mode**–compliant JSON Schema for an AIAgent `outputSchema`.\n *\n * Why this exists: AI SDK's default Zod → JSON Schema conversion (Zod v4's `toJSONSchema`) can\n * emit `unevaluatedProperties: false` or skip `additionalProperties: false` on object branches.\n * OpenAI's strict-mode validator rejects anything missing `additionalProperties: false` at\n * `context=()` (the root) and requires **all properties** in `required`. We convert here so all\n * legal Zod root shapes work (object, union, discriminated union, nullable-object wrapper, array,\n * intersection, …) and hand AI SDK a pre-tagged `jsonSchema(...)` record that passes straight\n * through to the provider.\n *\n * Rules enforced on the produced JSON Schema record:\n * - Every `type: \"object\"` node (root and nested under `allOf`/`anyOf`/`oneOf`/`items`/`prefixItems`/`$defs`):\n * - `additionalProperties: false`\n * - `required` lists **every** key in `properties` (OpenAI strict requires all properties required;\n * express optionality via `.nullable()` / `z.union([..., z.null()])`).\n * - `properties` is always an object (empty object allowed).\n * - `$schema`, `unevaluatedProperties`, and `default` are stripped (OpenAI rejects / ignores them).\n * - `sanitizeJsonSchemaRequiredKeywordsForCfworker` invariants from\n * {@link AIAgentExecutionHelpersFactory.createJsonSchemaRecord} are preserved as a starting point.\n */\n@injectable()\nexport class OpenAiStrictJsonSchemaFactory {\n constructor(\n @inject(AIAgentExecutionHelpersFactory)\n private readonly executionHelpers: AIAgentExecutionHelpersFactory,\n ) {}\n\n createStructuredOutputRecord(\n schema: ZodSchemaAny,\n options: Readonly<{ schemaName: string; title?: string }>,\n ): Record<string, unknown> {\n const record = this.executionHelpers.createJsonSchemaRecord(schema, {\n schemaName: options.schemaName,\n requireObjectRoot: false,\n });\n this.strictifyRecursive(record);\n if (options.title !== undefined) {\n record.title = options.title;\n }\n return record;\n }\n\n private strictifyRecursive(node: unknown): void {\n if (!node || typeof node !== \"object\" || Array.isArray(node)) {\n return;\n }\n const o = node as Record<string, unknown>;\n this.stripOpenAiRejectedKeywords(o);\n if (this.isObjectNode(o)) {\n const props = this.readPropertiesObject(o);\n o.properties = props;\n o.additionalProperties = false;\n o.required = Object.keys(props);\n for (const value of Object.values(props)) {\n this.strictifyRecursive(value);\n }\n }\n this.recurseIntoComposites(o);\n }\n\n private stripOpenAiRejectedKeywords(o: Record<string, unknown>): void {\n delete o[\"$schema\"];\n delete o[\"unevaluatedProperties\"];\n delete o[\"default\"];\n }\n\n private isObjectNode(o: Record<string, unknown>): boolean {\n const typeIsObject =\n o.type === \"object\" || (Array.isArray(o.type) && (o.type as ReadonlyArray<unknown>).includes(\"object\"));\n const hasObjectProperties =\n o.properties !== undefined && typeof o.properties === \"object\" && !Array.isArray(o.properties);\n return typeIsObject || hasObjectProperties;\n }\n\n private readPropertiesObject(o: Record<string, unknown>): Record<string, unknown> {\n if (o.properties && typeof o.properties === \"object\" && !Array.isArray(o.properties)) {\n return o.properties as Record<string, unknown>;\n }\n return {};\n }\n\n private recurseIntoComposites(o: Record<string, unknown>): void {\n for (const key of [\"allOf\", \"anyOf\", \"oneOf\", \"prefixItems\"] as const) {\n const branch = o[key];\n if (Array.isArray(branch)) {\n for (const sub of branch) {\n this.strictifyRecursive(sub);\n }\n }\n }\n if (o.not) {\n this.strictifyRecursive(o.not);\n }\n if (o.items) {\n if (Array.isArray(o.items)) {\n for (const sub of o.items) {\n this.strictifyRecursive(sub);\n }\n } else {\n this.strictifyRecursive(o.items);\n }\n }\n for (const key of [\"if\", \"then\", \"else\"] as const) {\n if (o[key]) {\n this.strictifyRecursive(o[key]);\n }\n }\n for (const key of [\"$defs\", \"definitions\"] as const) {\n const defs = o[key];\n if (defs && typeof defs === \"object\" && !Array.isArray(defs)) {\n for (const sub of Object.values(defs as Record<string, unknown>)) {\n this.strictifyRecursive(sub);\n }\n }\n }\n }\n}\n","import type { AgentCanvasPresentation, ChatModelConfig, CredentialRequirement } from \"@codemation/core\";\n\nimport type { CanvasIconName } from \"../canvasIconName\";\nimport { OpenAIChatModelFactory } from \"./OpenAIChatModelFactory\";\n\nexport class OpenAIChatModelConfig implements ChatModelConfig {\n readonly type = OpenAIChatModelFactory;\n readonly presentation: AgentCanvasPresentation<CanvasIconName>;\n readonly provider = \"openai\";\n readonly modelName: string;\n\n constructor(\n public readonly name: string,\n public readonly model: string,\n public readonly credentialSlotKey: string = \"openai\",\n presentationIn?: AgentCanvasPresentation<CanvasIconName>,\n public readonly options?: Readonly<{\n temperature?: number;\n maxTokens?: number;\n }>,\n ) {\n this.modelName = model;\n this.presentation = presentationIn ?? { icon: \"builtin:openai\", label: name };\n }\n\n getCredentialRequirements(): ReadonlyArray<CredentialRequirement> {\n return [\n {\n slotKey: this.credentialSlotKey,\n label: \"OpenAI API key\",\n acceptedTypes: [\"openai.apiKey\"],\n },\n ];\n }\n}\n","import { OpenAIChatModelConfig } from \"./openAiChatModelConfig\";\n\n/**\n * Default OpenAI chat model configs for scaffolds and demos (icon + label match {@link OpenAIChatModelConfig} defaults).\n * Prefer importing {@link openAiChatModelPresets} from here or from the consumer template re-export\n * instead of repeating {@link OpenAIChatModelConfig} construction in app workflows.\n */\nexport class OpenAiChatModelPresets {\n readonly demoGpt4oMini = new OpenAIChatModelConfig(\"OpenAI\", \"gpt-4o-mini\");\n\n readonly demoGpt41 = new OpenAIChatModelConfig(\"OpenAI\", \"gpt-4.1\");\n}\n\nexport const openAiChatModelPresets = new OpenAiChatModelPresets();\n","import type { AgentMessageDto, AgentToolCall } from \"@codemation/core\";\n\nimport type { AssistantModelMessage, ModelMessage, ToolModelMessage } from \"ai\";\n\nimport type { ExecutedToolCall } from \"./aiAgentSupport.types\";\n\n/**\n * AI-SDK-shaped message construction for the AIAgent stack. Emits plain `ModelMessage[]`\n * ( `{ role: 'system' | 'user' | 'assistant' | 'tool', content: ... }` ) as consumed by\n * `generateText({ messages })` from the `ai` package.\n */\nexport class AgentMessageFactory {\n static createPromptMessages(messages: ReadonlyArray<AgentMessageDto>): ReadonlyArray<ModelMessage> {\n return messages.map((message) => this.createPromptMessage(message));\n }\n\n /**\n * Builds the assistant message that contains optional text plus one or more tool-call parts,\n * matching the shape AI SDK emits between steps.\n */\n static createAssistantWithToolCalls(\n text: string | undefined,\n toolCalls: ReadonlyArray<AgentToolCall>,\n ): AssistantModelMessage {\n const content: AssistantModelMessage[\"content\"] = [];\n if (text && text.length > 0) {\n content.push({ type: \"text\", text });\n }\n for (const toolCall of toolCalls) {\n content.push({\n type: \"tool-call\",\n toolCallId: toolCall.id ?? toolCall.name,\n toolName: toolCall.name,\n input: toolCall.input ?? {},\n });\n }\n return { role: \"assistant\", content };\n }\n\n /**\n * Builds the `{ role: \"tool\", content: [{ type: \"tool-result\", ... }, ...] }` message returned\n * to the model after each tool round.\n */\n static createToolResultsMessage(executedToolCalls: ReadonlyArray<ExecutedToolCall>): ToolModelMessage {\n return {\n role: \"tool\",\n content: executedToolCalls.map((executed) => ({\n type: \"tool-result\",\n toolCallId: executed.toolCallId,\n toolName: executed.toolName,\n output: {\n type: \"json\",\n value: AgentMessageFactory.toToolResultJson(executed.result),\n },\n })),\n };\n }\n\n private static toToolResultJson(value: unknown): import(\"ai\").JSONValue {\n if (value === undefined) return null;\n try {\n return JSON.parse(JSON.stringify(value)) as import(\"ai\").JSONValue;\n } catch {\n return String(value);\n }\n }\n\n private static createPromptMessage(message: AgentMessageDto): ModelMessage {\n if (message.role === \"system\") {\n return { role: \"system\", content: message.content };\n }\n if (message.role === \"assistant\") {\n return { role: \"assistant\", content: message.content };\n }\n return { role: \"user\", content: message.content };\n }\n}\n","import type { Item, NodeOutputs } from \"@codemation/core\";\n\nexport class AgentOutputFactory {\n static fromUnknown(value: unknown): NodeOutputs {\n return { main: [{ json: value }] };\n }\n\n static replaceJson(item: Item, value: unknown): Item {\n return {\n ...item,\n json: value,\n };\n }\n\n static fromAgentContent(content: string): unknown {\n try {\n return JSON.parse(content) as unknown;\n } catch {\n return { output: content };\n }\n }\n}\n","import type { AgentMessageDto, ZodSchemaAny } from \"@codemation/core\";\nimport { inject, injectable } from \"@codemation/core\";\n\nimport { AIAgentExecutionHelpersFactory } from \"./AIAgentExecutionHelpersFactory\";\n\n@injectable()\nexport class AgentStructuredOutputRepairPromptFactory {\n private static readonly maxSchemaLength = 8000;\n private static readonly maxInvalidContentLength = 4000;\n private static readonly maxValidationErrorLength = 4000;\n\n constructor(\n @inject(AIAgentExecutionHelpersFactory)\n private readonly executionHelpers: AIAgentExecutionHelpersFactory,\n ) {}\n\n create(\n args: Readonly<{\n schema: ZodSchemaAny;\n invalidContent: string;\n validationError: string;\n }>,\n ): ReadonlyArray<AgentMessageDto> {\n return [\n {\n role: \"system\",\n content:\n \"Return only JSON that matches the required schema exactly. Do not include markdown fences, commentary, or prose.\",\n },\n {\n role: \"user\",\n content: JSON.stringify({\n requiredSchema: this.truncate(\n JSON.stringify(\n this.executionHelpers.createJsonSchemaRecord(args.schema, {\n schemaName: \"agent_output\",\n requireObjectRoot: false,\n }),\n ),\n AgentStructuredOutputRepairPromptFactory.maxSchemaLength,\n ),\n invalidModelOutput: this.truncate(\n args.invalidContent,\n AgentStructuredOutputRepairPromptFactory.maxInvalidContentLength,\n ),\n validationError: this.truncate(\n args.validationError,\n AgentStructuredOutputRepairPromptFactory.maxValidationErrorLength,\n ),\n }),\n },\n ];\n }\n\n private truncate(value: string, maxLength: number): string {\n if (value.length <= maxLength) {\n return value;\n }\n return `${value.slice(0, maxLength)}...(truncated)`;\n }\n}\n","import * as core from \"../core/index.js\";\nimport * as schemas from \"./schemas.js\";\nexport const ZodISODateTime = /*@__PURE__*/ core.$constructor(\"ZodISODateTime\", (inst, def) => {\n core.$ZodISODateTime.init(inst, def);\n schemas.ZodStringFormat.init(inst, def);\n});\nexport function datetime(params) {\n return core._isoDateTime(ZodISODateTime, params);\n}\nexport const ZodISODate = /*@__PURE__*/ core.$constructor(\"ZodISODate\", (inst, def) => {\n core.$ZodISODate.init(inst, def);\n schemas.ZodStringFormat.init(inst, def);\n});\nexport function date(params) {\n return core._isoDate(ZodISODate, params);\n}\nexport const ZodISOTime = /*@__PURE__*/ core.$constructor(\"ZodISOTime\", (inst, def) => {\n core.$ZodISOTime.init(inst, def);\n schemas.ZodStringFormat.init(inst, def);\n});\nexport function time(params) {\n return core._isoTime(ZodISOTime, params);\n}\nexport const ZodISODuration = /*@__PURE__*/ core.$constructor(\"ZodISODuration\", (inst, def) => {\n core.$ZodISODuration.init(inst, def);\n schemas.ZodStringFormat.init(inst, def);\n});\nexport function duration(params) {\n return core._isoDuration(ZodISODuration, params);\n}\n","import * as core from \"../core/index.js\";\nimport { $ZodError } from \"../core/index.js\";\nimport * as util from \"../core/util.js\";\nconst initializer = (inst, issues) => {\n $ZodError.init(inst, issues);\n inst.name = \"ZodError\";\n Object.defineProperties(inst, {\n format: {\n value: (mapper) => core.formatError(inst, mapper),\n // enumerable: false,\n },\n flatten: {\n value: (mapper) => core.flattenError(inst, mapper),\n // enumerable: false,\n },\n addIssue: {\n value: (issue) => {\n inst.issues.push(issue);\n inst.message = JSON.stringify(inst.issues, util.jsonStringifyReplacer, 2);\n },\n // enumerable: false,\n },\n addIssues: {\n value: (issues) => {\n inst.issues.push(...issues);\n inst.message = JSON.stringify(inst.issues, util.jsonStringifyReplacer, 2);\n },\n // enumerable: false,\n },\n isEmpty: {\n get() {\n return inst.issues.length === 0;\n },\n // enumerable: false,\n },\n });\n // Object.defineProperty(inst, \"isEmpty\", {\n // get() {\n // return inst.issues.length === 0;\n // },\n // });\n};\nexport const ZodError = core.$constructor(\"ZodError\", initializer);\nexport const ZodRealError = core.$constructor(\"ZodError\", initializer, {\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);\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 { createStandardJSONSchemaMethod, createToJSONSchemaMethod } from \"../core/to-json-schema.js\";\nimport * as checks from \"./checks.js\";\nimport * as iso from \"./iso.js\";\nimport * as parse from \"./parse.js\";\nexport const ZodType = /*@__PURE__*/ core.$constructor(\"ZodType\", (inst, def) => {\n core.$ZodType.init(inst, def);\n Object.assign(inst[\"~standard\"], {\n jsonSchema: {\n input: createStandardJSONSchemaMethod(inst, \"input\"),\n output: createStandardJSONSchemaMethod(inst, \"output\"),\n },\n });\n inst.toJSONSchema = createToJSONSchemaMethod(inst, {});\n inst.def = def;\n inst.type = def.type;\n Object.defineProperty(inst, \"_def\", { value: def });\n // base methods\n inst.check = (...checks) => {\n return inst.clone(util.mergeDefs(def, {\n checks: [\n ...(def.checks ?? []),\n ...checks.map((ch) => typeof ch === \"function\" ? { _zod: { check: ch, def: { check: \"custom\" }, onattach: [] } } : ch),\n ],\n }), {\n parent: true,\n });\n };\n inst.with = inst.check;\n inst.clone = (def, params) => core.clone(inst, def, params);\n inst.brand = () => inst;\n inst.register = ((reg, meta) => {\n reg.add(inst, meta);\n return inst;\n });\n // parsing\n inst.parse = (data, params) => parse.parse(inst, data, params, { callee: inst.parse });\n inst.safeParse = (data, params) => parse.safeParse(inst, data, params);\n inst.parseAsync = async (data, params) => parse.parseAsync(inst, data, params, { callee: inst.parseAsync });\n inst.safeParseAsync = async (data, params) => parse.safeParseAsync(inst, data, params);\n inst.spa = inst.safeParseAsync;\n // encoding/decoding\n inst.encode = (data, params) => parse.encode(inst, data, params);\n inst.decode = (data, params) => parse.decode(inst, data, params);\n inst.encodeAsync = async (data, params) => parse.encodeAsync(inst, data, params);\n inst.decodeAsync = async (data, params) => parse.decodeAsync(inst, data, params);\n inst.safeEncode = (data, params) => parse.safeEncode(inst, data, params);\n inst.safeDecode = (data, params) => parse.safeDecode(inst, data, params);\n inst.safeEncodeAsync = async (data, params) => parse.safeEncodeAsync(inst, data, params);\n inst.safeDecodeAsync = async (data, params) => parse.safeDecodeAsync(inst, data, params);\n // refinements\n inst.refine = (check, params) => inst.check(refine(check, params));\n inst.superRefine = (refinement) => inst.check(superRefine(refinement));\n inst.overwrite = (fn) => inst.check(checks.overwrite(fn));\n // wrappers\n inst.optional = () => optional(inst);\n inst.exactOptional = () => exactOptional(inst);\n inst.nullable = () => nullable(inst);\n inst.nullish = () => optional(nullable(inst));\n inst.nonoptional = (params) => nonoptional(inst, params);\n inst.array = () => array(inst);\n inst.or = (arg) => union([inst, arg]);\n inst.and = (arg) => intersection(inst, arg);\n inst.transform = (tx) => pipe(inst, transform(tx));\n inst.default = (def) => _default(inst, def);\n inst.prefault = (def) => prefault(inst, def);\n // inst.coalesce = (def, params) => coalesce(inst, def, params);\n inst.catch = (params) => _catch(inst, params);\n inst.pipe = (target) => pipe(inst, target);\n inst.readonly = () => readonly(inst);\n // meta\n inst.describe = (description) => {\n const cl = inst.clone();\n core.globalRegistry.add(cl, { description });\n return cl;\n };\n Object.defineProperty(inst, \"description\", {\n get() {\n return core.globalRegistry.get(inst)?.description;\n },\n configurable: true,\n });\n inst.meta = (...args) => {\n if (args.length === 0) {\n return core.globalRegistry.get(inst);\n }\n const cl = inst.clone();\n core.globalRegistry.add(cl, args[0]);\n return cl;\n };\n // helpers\n inst.isOptional = () => inst.safeParse(undefined).success;\n inst.isNullable = () => inst.safeParse(null).success;\n inst.apply = (fn) => fn(inst);\n return inst;\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 const bag = inst._zod.bag;\n inst.format = bag.format ?? null;\n inst.minLength = bag.minimum ?? null;\n inst.maxLength = bag.maximum ?? null;\n // validations\n inst.regex = (...args) => inst.check(checks.regex(...args));\n inst.includes = (...args) => inst.check(checks.includes(...args));\n inst.startsWith = (...args) => inst.check(checks.startsWith(...args));\n inst.endsWith = (...args) => inst.check(checks.endsWith(...args));\n inst.min = (...args) => inst.check(checks.minLength(...args));\n inst.max = (...args) => inst.check(checks.maxLength(...args));\n inst.length = (...args) => inst.check(checks.length(...args));\n inst.nonempty = (...args) => inst.check(checks.minLength(1, ...args));\n inst.lowercase = (params) => inst.check(checks.lowercase(params));\n inst.uppercase = (params) => inst.check(checks.uppercase(params));\n // transforms\n inst.trim = () => inst.check(checks.trim());\n inst.normalize = (...args) => inst.check(checks.normalize(...args));\n inst.toLowerCase = () => inst.check(checks.toLowerCase());\n inst.toUpperCase = () => inst.check(checks.toUpperCase());\n inst.slugify = () => inst.check(checks.slugify());\n});\nexport const ZodString = /*@__PURE__*/ core.$constructor(\"ZodString\", (inst, def) => {\n core.$ZodString.init(inst, def);\n _ZodString.init(inst, def);\n inst.email = (params) => inst.check(core._email(ZodEmail, params));\n inst.url = (params) => inst.check(core._url(ZodURL, params));\n inst.jwt = (params) => inst.check(core._jwt(ZodJWT, params));\n inst.emoji = (params) => inst.check(core._emoji(ZodEmoji, params));\n inst.guid = (params) => inst.check(core._guid(ZodGUID, params));\n inst.uuid = (params) => inst.check(core._uuid(ZodUUID, params));\n inst.uuidv4 = (params) => inst.check(core._uuidv4(ZodUUID, params));\n inst.uuidv6 = (params) => inst.check(core._uuidv6(ZodUUID, params));\n inst.uuidv7 = (params) => inst.check(core._uuidv7(ZodUUID, params));\n inst.nanoid = (params) => inst.check(core._nanoid(ZodNanoID, params));\n inst.guid = (params) => inst.check(core._guid(ZodGUID, params));\n inst.cuid = (params) => inst.check(core._cuid(ZodCUID, params));\n inst.cuid2 = (params) => inst.check(core._cuid2(ZodCUID2, params));\n inst.ulid = (params) => inst.check(core._ulid(ZodULID, params));\n inst.base64 = (params) => inst.check(core._base64(ZodBase64, params));\n inst.base64url = (params) => inst.check(core._base64url(ZodBase64URL, params));\n inst.xid = (params) => inst.check(core._xid(ZodXID, params));\n inst.ksuid = (params) => inst.check(core._ksuid(ZodKSUID, params));\n inst.ipv4 = (params) => inst.check(core._ipv4(ZodIPv4, params));\n inst.ipv6 = (params) => inst.check(core._ipv6(ZodIPv6, params));\n inst.cidrv4 = (params) => inst.check(core._cidrv4(ZodCIDRv4, params));\n inst.cidrv6 = (params) => inst.check(core._cidrv6(ZodCIDRv6, params));\n inst.e164 = (params) => inst.check(core._e164(ZodE164, params));\n // iso\n inst.datetime = (params) => inst.check(iso.datetime(params));\n inst.date = (params) => inst.check(iso.date(params));\n inst.time = (params) => inst.check(iso.time(params));\n inst.duration = (params) => inst.check(iso.duration(params));\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 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: /^https?$/,\n hostname: core.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}\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});\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 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\", core.regexes.hostname, _params);\n}\nexport function hex(_params) {\n return core._stringFormat(ZodCustomStringFormat, \"hex\", core.regexes.hex, _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.gt = (value, params) => inst.check(checks.gt(value, params));\n inst.gte = (value, params) => inst.check(checks.gte(value, params));\n inst.min = (value, params) => inst.check(checks.gte(value, params));\n inst.lt = (value, params) => inst.check(checks.lt(value, params));\n inst.lte = (value, params) => inst.check(checks.lte(value, params));\n inst.max = (value, params) => inst.check(checks.lte(value, params));\n inst.int = (params) => inst.check(int(params));\n inst.safe = (params) => inst.check(int(params));\n inst.positive = (params) => inst.check(checks.gt(0, params));\n inst.nonnegative = (params) => inst.check(checks.gte(0, params));\n inst.negative = (params) => inst.check(checks.lt(0, params));\n inst.nonpositive = (params) => inst.check(checks.lte(0, params));\n inst.multipleOf = (value, params) => inst.check(checks.multipleOf(value, params));\n inst.step = (value, params) => inst.check(checks.multipleOf(value, params));\n // inst.finite = (params) => inst.check(core.finite(params));\n inst.finite = () => inst;\n const bag = inst._zod.bag;\n inst.minValue =\n Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null;\n inst.maxValue =\n Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null;\n inst.isInt = (bag.format ?? \"\").includes(\"int\") || Number.isSafeInteger(bag.multipleOf ?? 0.5);\n inst.isFinite = true;\n inst.format = bag.format ?? null;\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 inst.gte = (value, params) => inst.check(checks.gte(value, params));\n inst.min = (value, params) => inst.check(checks.gte(value, params));\n inst.gt = (value, params) => inst.check(checks.gt(value, params));\n inst.gte = (value, params) => inst.check(checks.gte(value, params));\n inst.min = (value, params) => inst.check(checks.gte(value, params));\n inst.lt = (value, params) => inst.check(checks.lt(value, params));\n inst.lte = (value, params) => inst.check(checks.lte(value, params));\n inst.max = (value, params) => inst.check(checks.lte(value, params));\n inst.positive = (params) => inst.check(checks.gt(BigInt(0), params));\n inst.negative = (params) => inst.check(checks.lt(BigInt(0), params));\n inst.nonpositive = (params) => inst.check(checks.lte(BigInt(0), params));\n inst.nonnegative = (params) => inst.check(checks.gte(BigInt(0), params));\n inst.multipleOf = (value, params) => inst.check(checks.multipleOf(value, params));\n const bag = inst._zod.bag;\n inst.minValue = bag.minimum ?? null;\n inst.maxValue = bag.maximum ?? null;\n inst.format = bag.format ?? null;\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});\n// int64\nexport function int64(params) {\n return core._int64(ZodBigIntFormat, params);\n}\n// uint64\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 const c = inst._zod.bag;\n inst.minDate = c.minimum ? new Date(c.minimum) : null;\n inst.maxDate = c.maximum ? new Date(c.maximum) : null;\n});\nexport function date(params) {\n return core._date(ZodDate, params);\n}\nexport const ZodArray = /*@__PURE__*/ core.$constructor(\"ZodArray\", (inst, def) => {\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 inst.min = (minLength, params) => inst.check(checks.minLength(minLength, params));\n inst.nonempty = (params) => inst.check(checks.minLength(1, params));\n inst.max = (maxLength, params) => inst.check(checks.maxLength(maxLength, params));\n inst.length = (len, params) => inst.check(checks.length(len, params));\n inst.unwrap = () => inst.element;\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 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.defineLazy(inst, \"shape\", () => {\n return def.shape;\n });\n inst.keyof = () => _enum(Object.keys(inst._zod.def.shape));\n inst.catchall = (catchall) => inst.clone({ ...inst._zod.def, catchall: catchall });\n inst.passthrough = () => inst.clone({ ...inst._zod.def, catchall: unknown() });\n inst.loose = () => inst.clone({ ...inst._zod.def, catchall: unknown() });\n inst.strict = () => inst.clone({ ...inst._zod.def, catchall: never() });\n inst.strip = () => inst.clone({ ...inst._zod.def, catchall: undefined });\n inst.extend = (incoming) => {\n return util.extend(inst, incoming);\n };\n inst.safeExtend = (incoming) => {\n return util.safeExtend(inst, incoming);\n };\n inst.merge = (other) => util.merge(inst, other);\n inst.pick = (mask) => util.pick(inst, mask);\n inst.omit = (mask) => util.omit(inst, mask);\n inst.partial = (...args) => util.partial(ZodOptional, inst, args[0]);\n inst.required = (...args) => util.required(ZodNonOptional, inst, args[0]);\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,\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 core.$ZodTuple.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.tupleProcessor(inst, ctx, json, params);\n inst.rest = (rest) => inst.clone({\n ...inst._zod.def,\n rest: rest,\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 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 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 const k = core.clone(keyType);\n k._zod.values = undefined;\n return new ZodRecord({\n type: \"record\",\n keyType: k,\n valueType: valueType,\n ...util.normalizeParams(params),\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 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 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 inst.options = Object.values(def.entries);\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 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 _issue.input ?? (_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 : () => 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 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) {\n return core._superRefine(fn);\n}\n// Re-export describe and meta from core\nexport const describe = core.describe;\nexport const meta = core.meta;\nfunction _instanceof(cls, params = {}) {\n const inst = new ZodCustom({\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\n// /** @deprecated Use `z.pipe()` and `z.transform()` instead. */\nexport function preprocess(fn, schema) {\n return pipe(transform(fn), schema);\n}\n","import type { ChatLanguageModel, ChatModelConfig, StructuredOutputOptions, ZodSchemaAny } from \"@codemation/core\";\nimport { inject, injectable } from \"@codemation/core\";\n\nimport type { ModelMessage } from \"ai\";\nimport { ZodError } from \"zod\";\n\nimport { OpenAIChatModelFactory } from \"../chatModels/OpenAIChatModelFactory\";\nimport { OpenAiStrictJsonSchemaFactory } from \"../chatModels/OpenAiStrictJsonSchemaFactory\";\nimport { AgentStructuredOutputRepairPromptFactory } from \"./AgentStructuredOutputRepairPromptFactory\";\nimport { AgentMessageFactory } from \"./AgentMessageFactory\";\n\ninterface ParsedStructuredOutputSuccess<TValue> {\n readonly ok: true;\n readonly value: TValue;\n}\n\ninterface ParsedStructuredOutputFailure {\n readonly ok: false;\n readonly invalidContent: string;\n readonly validationError: string;\n}\n\ntype ParsedStructuredOutputResult<TValue> = ParsedStructuredOutputSuccess<TValue> | ParsedStructuredOutputFailure;\n\nexport type StructuredOutputSchemaForModel = ZodSchemaAny | Readonly<Record<string, unknown>>;\n\n/**\n * Orchestrates a 2-attempt repair loop on top of `generateText({ output: Output.object(...) })`.\n *\n * Strategy:\n * 1. If the caller already has a raw final text (from a prior tool-calling turn), try parsing it\n * directly against the schema — fast path for models that already emit strict JSON.\n * 2. Otherwise, run a native structured-output call via {@link invokeStructuredModel}. For the\n * OpenAI-strict path, a {@link OpenAiStrictJsonSchemaFactory}-built JSON Schema record is\n * handed to AI SDK's `jsonSchema(...)` wrapper (preserves `additionalProperties: false` at\n * every object depth).\n * 3. If the structured call fails (AI_NoObjectGeneratedError / ZodError / schema reject), run a\n * text-mode repair prompt with the validation error appended, up to 2 attempts.\n */\n@injectable()\nexport class AgentStructuredOutputRunner {\n private static readonly repairAttemptCount = 2;\n private static readonly structuredOutputSchemaName = \"agent_output\";\n\n constructor(\n @inject(AgentStructuredOutputRepairPromptFactory)\n private readonly repairPromptFactory: AgentStructuredOutputRepairPromptFactory,\n @inject(OpenAiStrictJsonSchemaFactory)\n private readonly openAiStrictJsonSchemaFactory: OpenAiStrictJsonSchemaFactory,\n ) {}\n\n async resolve<TOutput>(\n args: Readonly<{\n model: ChatLanguageModel;\n chatModelConfig: ChatModelConfig;\n schema: ZodSchemaAny;\n conversation: ReadonlyArray<ModelMessage>;\n rawFinalText?: string;\n agentName: string;\n nodeId: string;\n invokeTextModel: (messages: ReadonlyArray<ModelMessage>) => Promise<{ text: string }>;\n invokeStructuredModel: (\n schema: StructuredOutputSchemaForModel,\n messages: ReadonlyArray<ModelMessage>,\n options: StructuredOutputOptions | undefined,\n ) => Promise<unknown>;\n }>,\n ): Promise<TOutput> {\n let lastFailure: ParsedStructuredOutputFailure | undefined;\n\n if (args.rawFinalText !== undefined) {\n const directResult = this.tryParseAndValidate<TOutput>(args.rawFinalText, args.schema);\n if (directResult.ok) {\n return directResult.value;\n }\n lastFailure = directResult;\n }\n\n try {\n const structuredOptions = this.resolveStructuredOutputOptions(args.chatModelConfig);\n const schemaForModel = this.resolveOutputSchemaForModel(args.schema, structuredOptions);\n const nativeResult = this.tryValidateStructuredValue<TOutput>(\n await args.invokeStructuredModel(schemaForModel, args.conversation, structuredOptions),\n args.schema,\n );\n if (nativeResult.ok) {\n return nativeResult.value;\n }\n lastFailure = nativeResult;\n } catch (error) {\n lastFailure = lastFailure ?? {\n ok: false,\n invalidContent: \"\",\n validationError: `Native structured output failed: ${this.summarizeError(error)}`,\n };\n }\n\n return await this.retryWithRepairPrompt<TOutput>({\n ...args,\n lastFailure:\n lastFailure ??\n ({\n ok: false,\n invalidContent: \"\",\n validationError: \"Structured output was required but no valid structured response was produced.\",\n } satisfies ParsedStructuredOutputFailure),\n });\n }\n\n private async retryWithRepairPrompt<TOutput>(\n args: Readonly<{\n schema: ZodSchemaAny;\n conversation: ReadonlyArray<ModelMessage>;\n lastFailure: ParsedStructuredOutputFailure;\n agentName: string;\n nodeId: string;\n invokeTextModel: (messages: ReadonlyArray<ModelMessage>) => Promise<{ text: string }>;\n }>,\n ): Promise<TOutput> {\n let failure = args.lastFailure;\n for (let attempt = 1; attempt <= AgentStructuredOutputRunner.repairAttemptCount; attempt++) {\n const repairMessages: ReadonlyArray<ModelMessage> = [\n ...args.conversation,\n ...AgentMessageFactory.createPromptMessages(\n this.repairPromptFactory.create({\n schema: args.schema,\n invalidContent: failure.invalidContent,\n validationError: failure.validationError,\n }),\n ),\n ];\n const repairResponse = await args.invokeTextModel(repairMessages);\n const repairResult = this.tryParseAndValidate<TOutput>(repairResponse.text, args.schema);\n if (repairResult.ok) {\n return repairResult.value;\n }\n failure = repairResult;\n }\n throw new Error(\n `Structured output required for AIAgent \"${args.agentName}\" (${args.nodeId}) but validation still failed after ${AgentStructuredOutputRunner.repairAttemptCount} repair attempts: ${failure.validationError}`,\n );\n }\n\n /**\n * Chooses strict mode for OpenAI chat-model configs, off otherwise. Extendable in future for\n * other providers that adopt the same \"supply a JSON Schema record directly\" contract.\n */\n private resolveStructuredOutputOptions(chatModelConfig: ChatModelConfig): StructuredOutputOptions | undefined {\n if (chatModelConfig.type !== OpenAIChatModelFactory) {\n return undefined;\n }\n return { strict: true, schemaName: AgentStructuredOutputRunner.structuredOutputSchemaName };\n }\n\n private resolveOutputSchemaForModel(\n schema: ZodSchemaAny,\n options: StructuredOutputOptions | undefined,\n ): StructuredOutputSchemaForModel {\n if (!options?.strict) {\n return schema;\n }\n return this.openAiStrictJsonSchemaFactory.createStructuredOutputRecord(schema, {\n schemaName: options.schemaName ?? AgentStructuredOutputRunner.structuredOutputSchemaName,\n });\n }\n\n private tryParseAndValidate<TOutput>(content: string, schema: ZodSchemaAny): ParsedStructuredOutputResult<TOutput> {\n try {\n return this.tryValidateStructuredValue<TOutput>(JSON.parse(content) as unknown, schema, content);\n } catch (error) {\n return {\n ok: false,\n invalidContent: content,\n validationError: `Response was not valid JSON: ${this.summarizeError(error)}`,\n };\n }\n }\n\n private tryValidateStructuredValue<TOutput>(\n value: unknown,\n schema: ZodSchemaAny,\n invalidContent?: string,\n ): ParsedStructuredOutputResult<TOutput> {\n try {\n return {\n ok: true,\n value: schema.parse(value) as TOutput,\n };\n } catch (error) {\n return {\n ok: false,\n invalidContent: invalidContent ?? this.toJson(value),\n validationError: this.summarizeError(error),\n };\n }\n }\n\n private summarizeError(error: unknown): string {\n if (error instanceof ZodError) {\n return error.issues.map((issue) => `${issue.path.join(\".\") || \"<root>\"}: ${issue.message}`).join(\"; \");\n }\n if (error instanceof Error) {\n return error.message;\n }\n return String(error);\n }\n\n private toJson(value: unknown): string {\n try {\n const serialized = JSON.stringify(value);\n return serialized ?? String(value);\n } catch (error) {\n return `<<unserializable: ${this.summarizeError(error)}>>`;\n }\n }\n}\n","import type { NodeInputsByPort } from \"@codemation/core\";\n\nexport class AgentToolCallPortMap {\n static fromInput(input: unknown): NodeInputsByPort {\n return {\n in: [\n {\n json: input,\n },\n ],\n };\n }\n}\n","import type { JsonValue } from \"@codemation/core\";\nimport { injectable } from \"@codemation/core\";\nimport { ZodError } from \"zod\";\n\nimport type { AgentToolFailureClassification, AgentToolValidationIssue } from \"./AgentToolRepair.types\";\n\n@injectable()\nexport class AgentToolErrorClassifier {\n classify(\n args: Readonly<{\n error: unknown;\n toolName: string;\n schema?: unknown;\n }>,\n ): AgentToolFailureClassification {\n const effectiveError = this.toError(args.error);\n if (this.isRepairableValidationError(args.error, effectiveError)) {\n return {\n kind: \"repairable_validation_error\",\n effectiveError,\n issues: this.extractIssues(args.error, effectiveError, args.toolName),\n requiredSchemaReminder: this.toJsonValue(args.schema),\n };\n }\n if (this.isTransientExecutionError(effectiveError)) {\n return {\n kind: \"transient_execution_error\",\n effectiveError,\n };\n }\n return {\n kind: \"non_repairable_error\",\n effectiveError,\n };\n }\n\n private isRepairableValidationError(rawError: unknown, effectiveError: Error): boolean {\n if (rawError instanceof ZodError) {\n const stage = (rawError as ZodError & { codemationToolValidationStage?: \"input\" | \"output\" })\n .codemationToolValidationStage;\n return stage !== \"output\";\n }\n if (effectiveError.name === \"ZodError\") {\n return true;\n }\n return effectiveError.message.includes(\"Received tool input did not match expected schema\");\n }\n\n private extractIssues(\n rawError: unknown,\n effectiveError: Error,\n toolName: string,\n ): ReadonlyArray<AgentToolValidationIssue> | undefined {\n if (rawError instanceof ZodError) {\n return rawError.issues.map((issue) => ({\n path: issue.path.map((segment) => (typeof segment === \"number\" ? segment : String(segment))),\n code: issue.code,\n message: issue.message,\n expected: this.toOptionalString(\"expected\" in issue ? issue.expected : undefined),\n received: this.toOptionalString(\"received\" in issue ? issue.received : undefined),\n }));\n }\n if (effectiveError.name !== \"ZodError\") {\n return undefined;\n }\n return [\n {\n path: [],\n code: \"invalid_tool_input\",\n message: `Tool \"${toolName}\" input was invalid: ${effectiveError.message}`,\n },\n ];\n }\n\n private isTransientExecutionError(error: Error): boolean {\n const summary = `${error.name} ${error.message}`.toLowerCase();\n return (\n summary.includes(\"timeout\") ||\n summary.includes(\"timed out\") ||\n summary.includes(\"rate limit\") ||\n summary.includes(\"too many requests\") ||\n summary.includes(\"temporarily unavailable\") ||\n summary.includes(\"econnreset\") ||\n summary.includes(\"etimedout\") ||\n summary.includes(\"503\")\n );\n }\n\n private toError(error: unknown): Error {\n return error instanceof Error ? error : new Error(String(error));\n }\n\n private toJsonValue(value: unknown): JsonValue | undefined {\n if (value === undefined) {\n return undefined;\n }\n return JSON.parse(JSON.stringify(value)) as JsonValue;\n }\n\n private toOptionalString(value: unknown): string | undefined {\n if (value === undefined) {\n return undefined;\n }\n return String(value);\n }\n}\n","import type { JsonValue } from \"@codemation/core\";\n\nimport type { AgentToolValidationIssue } from \"./AgentToolRepair.types\";\n\nexport class AgentToolRepairExhaustedError extends Error {\n readonly details: JsonValue;\n\n constructor(\n args: Readonly<{\n agentName: string;\n nodeId: string;\n toolName: string;\n maxAttempts: number;\n lastManagedInput?: JsonValue;\n lastValidationIssues?: ReadonlyArray<AgentToolValidationIssue>;\n }>,\n ) {\n super(\n `AIAgent \"${args.agentName}\" (${args.nodeId}) could not recover from invalid tool calls for \"${args.toolName}\" after ${args.maxAttempts} repair attempt(s).`,\n );\n this.name = \"AgentToolRepairExhaustedError\";\n const details: Record<string, JsonValue> = {\n toolName: args.toolName,\n maxAttempts: args.maxAttempts,\n recommendation:\n \"Check tool schema, tool description, or inject known values in code instead of asking the model to infer them.\",\n };\n if (args.lastManagedInput !== undefined) {\n details[\"lastManagedInput\"] = args.lastManagedInput;\n }\n if (args.lastValidationIssues && args.lastValidationIssues.length > 0) {\n details[\"lastValidationIssues\"] = args.lastValidationIssues.map((issue) => this.serializeIssue(issue));\n }\n this.details = details;\n }\n\n private serializeIssue(issue: AgentToolValidationIssue): JsonValue {\n const result: Record<string, JsonValue> = {\n path: [...issue.path],\n code: issue.code,\n message: issue.message,\n };\n if (issue.expected !== undefined) {\n result[\"expected\"] = issue.expected;\n }\n if (issue.received !== undefined) {\n result[\"received\"] = issue.received;\n }\n return result;\n }\n}\n","import { injectable } from \"@codemation/core\";\n\nimport type { AgentToolRepairDecision } from \"./AgentToolRepair.types\";\n\n@injectable()\nexport class AgentToolRepairPolicy {\n private static readonly maxRepairAttemptsPerTool = 2;\n\n createDecision(toolName: string, attemptsByToolName: Map<string, number>): AgentToolRepairDecision {\n const attempt = (attemptsByToolName.get(toolName) ?? 0) + 1;\n attemptsByToolName.set(toolName, attempt);\n return {\n attempt,\n maxAttempts: AgentToolRepairPolicy.maxRepairAttemptsPerTool,\n nextAction:\n attempt < AgentToolRepairPolicy.maxRepairAttemptsPerTool\n ? \"model_retry_with_tool_error_message\"\n : \"fail_agent_run\",\n };\n }\n}\n","import type { JsonValue, NodeExecutionContext } from \"@codemation/core\";\nimport { CodemationTelemetryAttributeNames, inject, injectable } from \"@codemation/core\";\n\nimport type { AIAgent } from \"./AIAgentConfig\";\nimport { AgentOutputFactory } from \"./AgentOutputFactory\";\nimport { AgentToolCallPortMap } from \"./AgentToolCallPortMapFactory\";\nimport { AgentToolErrorClassifier } from \"./AgentToolErrorClassifier\";\nimport { AgentToolRepairExhaustedError } from \"./AgentToolRepairExhaustedError\";\nimport { AgentToolRepairPolicy } from \"./AgentToolRepairPolicy\";\nimport type { AgentToolRepairDecision, AgentToolValidationIssue } from \"./AgentToolRepair.types\";\nimport type { ExecutedToolCall, PlannedToolCall } from \"./aiAgentSupport.types\";\n\n@injectable()\nexport class AgentToolExecutionCoordinator {\n constructor(\n @inject(AgentToolErrorClassifier)\n private readonly errorClassifier: AgentToolErrorClassifier,\n @inject(AgentToolRepairPolicy)\n private readonly repairPolicy: AgentToolRepairPolicy,\n ) {}\n\n async execute(\n args: Readonly<{\n plannedToolCalls: ReadonlyArray<PlannedToolCall>;\n ctx: NodeExecutionContext<AIAgent<any, any>>;\n agentName: string;\n repairAttemptsByToolName: Map<string, number>;\n }>,\n ): Promise<ReadonlyArray<ExecutedToolCall>> {\n const results = await Promise.allSettled(\n args.plannedToolCalls.map(\n async (plannedToolCall) => await this.executePlannedToolCall({ ...args, plannedToolCall }),\n ),\n );\n\n const rejected = results.find((result) => result.status === \"rejected\");\n if (rejected?.status === \"rejected\") {\n throw rejected.reason instanceof Error ? rejected.reason : new Error(String(rejected.reason));\n }\n\n return results\n .filter((result): result is PromiseFulfilledResult<ExecutedToolCall> => result.status === \"fulfilled\")\n .map((result) => result.value);\n }\n\n private async executePlannedToolCall(\n args: Readonly<{\n plannedToolCall: PlannedToolCall;\n ctx: NodeExecutionContext<AIAgent<any, any>>;\n agentName: string;\n repairAttemptsByToolName: Map<string, number>;\n }>,\n ): Promise<ExecutedToolCall> {\n const { plannedToolCall, ctx } = args;\n const toolCallInputsByPort = AgentToolCallPortMap.fromInput(plannedToolCall.toolCall.input ?? {});\n const invocationId = plannedToolCall.invocationId;\n const startedAt = new Date();\n const span = ctx.telemetry.startChildSpan({\n name: \"agent.tool.call\",\n kind: \"client\",\n startedAt,\n attributes: {\n [CodemationTelemetryAttributeNames.connectionInvocationId]: invocationId,\n [CodemationTelemetryAttributeNames.toolName]: plannedToolCall.binding.config.name,\n ...(ctx.iterationId ? { [CodemationTelemetryAttributeNames.iterationId]: ctx.iterationId } : {}),\n ...(typeof ctx.itemIndex === \"number\"\n ? { [CodemationTelemetryAttributeNames.iterationIndex]: ctx.itemIndex }\n : {}),\n ...(ctx.parentInvocationId\n ? { [CodemationTelemetryAttributeNames.parentInvocationId]: ctx.parentInvocationId }\n : {}),\n },\n });\n await ctx.nodeState?.markRunning({\n nodeId: plannedToolCall.nodeId,\n activationId: ctx.activationId,\n inputsByPort: toolCallInputsByPort,\n });\n await ctx.nodeState?.appendConnectionInvocation({\n invocationId,\n connectionNodeId: plannedToolCall.nodeId,\n parentAgentNodeId: ctx.nodeId,\n parentAgentActivationId: ctx.activationId,\n status: \"running\",\n managedInput: this.toJsonValue(plannedToolCall.toolCall.input),\n queuedAt: startedAt.toISOString(),\n startedAt: startedAt.toISOString(),\n iterationId: ctx.iterationId,\n parentInvocationId: ctx.parentInvocationId,\n });\n\n try {\n const result = await plannedToolCall.binding.execute(plannedToolCall.toolCall.input ?? {}, {\n parentSpan: span,\n parentInvocationId: invocationId,\n });\n const serialized = typeof result === \"string\" ? result : JSON.stringify(result);\n const finishedAt = new Date();\n await ctx.nodeState?.markCompleted({\n nodeId: plannedToolCall.nodeId,\n activationId: ctx.activationId,\n inputsByPort: toolCallInputsByPort,\n outputs: AgentOutputFactory.fromUnknown(result),\n });\n await span.attachArtifact({\n kind: \"tool.input\",\n contentType: \"application/json\",\n previewJson: this.toJsonValue(plannedToolCall.toolCall.input),\n });\n await span.attachArtifact({\n kind: \"tool.output\",\n contentType: \"application/json\",\n previewJson: this.toJsonValue(result),\n });\n await span.end({ status: \"ok\", endedAt: finishedAt });\n await ctx.nodeState?.appendConnectionInvocation({\n invocationId,\n connectionNodeId: plannedToolCall.nodeId,\n parentAgentNodeId: ctx.nodeId,\n parentAgentActivationId: ctx.activationId,\n status: \"completed\",\n managedInput: this.toJsonValue(plannedToolCall.toolCall.input),\n managedOutput: this.toJsonValue(result),\n queuedAt: startedAt.toISOString(),\n startedAt: startedAt.toISOString(),\n finishedAt: finishedAt.toISOString(),\n iterationId: ctx.iterationId,\n parentInvocationId: ctx.parentInvocationId,\n });\n return {\n toolName: plannedToolCall.binding.config.name,\n toolCallId: plannedToolCall.toolCall.id ?? plannedToolCall.binding.config.name,\n serialized: typeof serialized === \"string\" ? serialized : JSON.stringify(serialized),\n result,\n } satisfies ExecutedToolCall;\n } catch (error) {\n const classification = this.errorClassifier.classify({\n error,\n toolName: plannedToolCall.binding.config.name,\n schema: plannedToolCall.binding.inputSchema,\n });\n\n if (classification.kind !== \"repairable_validation_error\") {\n const effectiveError = classification.effectiveError;\n await this.recordFailedInvocation({\n invocationId,\n plannedToolCall,\n ctx,\n startedAt,\n inputsByPort: toolCallInputsByPort,\n managedInput: this.toJsonValue(plannedToolCall.toolCall.input),\n error: effectiveError,\n });\n await span.attachArtifact({\n kind: \"tool.input\",\n contentType: \"application/json\",\n previewJson: this.toJsonValue(plannedToolCall.toolCall.input),\n });\n await span.end({\n status: \"error\",\n statusMessage: effectiveError.message,\n endedAt: new Date(),\n });\n throw effectiveError;\n }\n\n const repairDecision = this.repairPolicy.createDecision(\n plannedToolCall.binding.config.name,\n args.repairAttemptsByToolName,\n );\n\n if (repairDecision.nextAction === \"fail_agent_run\") {\n const exhaustedError = new AgentToolRepairExhaustedError({\n agentName: args.agentName,\n nodeId: ctx.nodeId,\n toolName: plannedToolCall.binding.config.name,\n maxAttempts: repairDecision.maxAttempts,\n lastManagedInput: this.toJsonValue(plannedToolCall.toolCall.input),\n lastValidationIssues: classification.issues,\n });\n await this.recordFailedInvocation({\n invocationId,\n plannedToolCall,\n ctx,\n startedAt,\n inputsByPort: toolCallInputsByPort,\n managedInput: this.toJsonValue(plannedToolCall.toolCall.input),\n error: exhaustedError,\n errorDetails: exhaustedError.details,\n });\n await span.attachArtifact({\n kind: \"tool.input\",\n contentType: \"application/json\",\n previewJson: this.toJsonValue(plannedToolCall.toolCall.input),\n });\n await span.attachArtifact({\n kind: \"tool.error\",\n contentType: \"application/json\",\n previewJson: exhaustedError.details,\n });\n await span.end({\n status: \"error\",\n statusMessage: exhaustedError.message,\n endedAt: new Date(),\n });\n throw exhaustedError;\n }\n\n const repairPayload = this.createRepairPayload({\n toolName: plannedToolCall.binding.config.name,\n issues: classification.issues,\n requiredSchemaReminder: classification.requiredSchemaReminder,\n });\n const repairDetails = this.createRepairDetails({\n toolName: plannedToolCall.binding.config.name,\n issues: classification.issues,\n requiredSchemaReminder: classification.requiredSchemaReminder,\n repairDecision,\n });\n await this.recordFailedInvocation({\n invocationId,\n plannedToolCall,\n ctx,\n startedAt,\n inputsByPort: toolCallInputsByPort,\n managedInput: this.toJsonValue(plannedToolCall.toolCall.input),\n error: classification.effectiveError,\n errorDetails: repairDetails,\n });\n await span.attachArtifact({\n kind: \"tool.input\",\n contentType: \"application/json\",\n previewJson: this.toJsonValue(plannedToolCall.toolCall.input),\n });\n await span.attachArtifact({\n kind: \"tool.error\",\n contentType: \"application/json\",\n previewJson: repairPayload,\n });\n await span.end({\n status: \"error\",\n statusMessage: classification.effectiveError.message,\n endedAt: new Date(),\n });\n return {\n toolName: plannedToolCall.binding.config.name,\n toolCallId: plannedToolCall.toolCall.id ?? plannedToolCall.binding.config.name,\n serialized: JSON.stringify(repairPayload),\n result: repairPayload,\n } satisfies ExecutedToolCall;\n }\n }\n\n private async recordFailedInvocation(\n args: Readonly<{\n invocationId: string;\n plannedToolCall: PlannedToolCall;\n ctx: NodeExecutionContext<AIAgent<any, any>>;\n startedAt: Date;\n inputsByPort: ReturnType<typeof AgentToolCallPortMap.fromInput>;\n managedInput?: JsonValue;\n error: Error;\n errorDetails?: JsonValue;\n }>,\n ): Promise<void> {\n const finishedAt = new Date();\n await args.ctx.nodeState?.markFailed({\n nodeId: args.plannedToolCall.nodeId,\n activationId: args.ctx.activationId,\n inputsByPort: args.inputsByPort,\n error: args.error,\n });\n await args.ctx.nodeState?.appendConnectionInvocation({\n invocationId: args.invocationId,\n connectionNodeId: args.plannedToolCall.nodeId,\n parentAgentNodeId: args.ctx.nodeId,\n parentAgentActivationId: args.ctx.activationId,\n status: \"failed\",\n managedInput: args.managedInput,\n error: {\n message: args.error.message,\n name: args.error.name,\n stack: args.error.stack,\n details: args.errorDetails ?? this.extractErrorDetails(args.error),\n },\n queuedAt: args.startedAt.toISOString(),\n startedAt: args.startedAt.toISOString(),\n finishedAt: finishedAt.toISOString(),\n iterationId: args.ctx.iterationId,\n parentInvocationId: args.ctx.parentInvocationId,\n });\n }\n\n private createRepairPayload(\n args: Readonly<{\n toolName: string;\n issues?: ReadonlyArray<AgentToolValidationIssue>;\n requiredSchemaReminder?: JsonValue;\n }>,\n ): JsonValue {\n const payload: Record<string, JsonValue> = {\n status: \"error\",\n errorType: \"validation\",\n toolName: args.toolName,\n message: this.createValidationMessage(args.toolName, args.issues),\n instruction: \"Call the tool again with all required fields present and correctly typed.\",\n };\n if (args.requiredSchemaReminder !== undefined) {\n payload[\"requiredSchemaReminder\"] = args.requiredSchemaReminder;\n }\n return payload;\n }\n\n private createRepairDetails(\n args: Readonly<{\n toolName: string;\n issues?: ReadonlyArray<AgentToolValidationIssue>;\n requiredSchemaReminder?: JsonValue;\n repairDecision: AgentToolRepairDecision;\n }>,\n ): JsonValue {\n const details: Record<string, JsonValue> = {\n errorType: \"validation\",\n toolName: args.toolName,\n recoveryHint: \"Call the same tool again with every required field present and correctly typed.\",\n repair: {\n attempt: args.repairDecision.attempt,\n maxAttempts: args.repairDecision.maxAttempts,\n nextAction: args.repairDecision.nextAction,\n },\n };\n if (args.issues && args.issues.length > 0) {\n details[\"issues\"] = args.issues.map((issue) => this.serializeIssue(issue));\n }\n if (args.requiredSchemaReminder !== undefined) {\n details[\"requiredSchemaReminder\"] = args.requiredSchemaReminder;\n }\n return details;\n }\n\n private createValidationMessage(\n toolName: string,\n issues: ReadonlyArray<AgentToolValidationIssue> | undefined,\n ): string {\n const firstIssue = issues?.[0];\n if (!firstIssue) {\n return `Your previous tool call for \"${toolName}\" was invalid and did not match the expected schema.`;\n }\n const fieldPath = firstIssue.path.length > 0 ? firstIssue.path.join(\".\") : \"<root>\";\n return `Your previous tool call for \"${toolName}\" was invalid because field \"${fieldPath}\" failed validation: ${firstIssue.message}`;\n }\n\n private toJsonValue(value: unknown): JsonValue | undefined {\n if (value === undefined) {\n return undefined;\n }\n return JSON.parse(JSON.stringify(value)) as JsonValue;\n }\n\n private extractErrorDetails(error: Error): JsonValue | undefined {\n const candidate = error as Error & { details?: JsonValue };\n return candidate.details;\n }\n\n private serializeIssue(issue: AgentToolValidationIssue): JsonValue {\n const result: Record<string, JsonValue> = {\n path: [...issue.path],\n code: issue.code,\n message: issue.message,\n };\n if (issue.expected !== undefined) {\n result[\"expected\"] = issue.expected;\n }\n if (issue.received !== undefined) {\n result[\"received\"] = issue.received;\n }\n return result;\n }\n}\n","import type {\n MultiInputNode,\n NodeExecutionContext,\n NodeOutputs,\n NodeResolver,\n RunnableNode,\n RunnableNodeConfig,\n RunnableNodeExecuteArgs,\n NodeBackedToolConfig,\n ToolExecuteArgs,\n ZodSchemaAny,\n} from \"@codemation/core\";\nimport {\n AgentConfigInspector,\n ChildExecutionScopeFactory,\n CoreTokens,\n inject,\n injectable,\n ItemExprResolver,\n NodeOutputNormalizer,\n RunnableOutputBehaviorResolver,\n} from \"@codemation/core\";\nimport { z } from \"zod\";\n\n@injectable()\nexport class NodeBackedToolRuntime {\n constructor(\n @inject(CoreTokens.NodeResolver)\n private readonly nodeResolver: NodeResolver,\n @inject(ItemExprResolver)\n private readonly itemExprResolver: ItemExprResolver,\n @inject(NodeOutputNormalizer)\n private readonly outputNormalizer: NodeOutputNormalizer,\n @inject(RunnableOutputBehaviorResolver)\n private readonly outputBehaviorResolver: RunnableOutputBehaviorResolver,\n @inject(ChildExecutionScopeFactory)\n private readonly childExecutionScopeFactory: ChildExecutionScopeFactory,\n ) {}\n\n async execute(\n config: NodeBackedToolConfig<any, ZodSchemaAny, ZodSchemaAny>,\n args: ToolExecuteArgs,\n ): Promise<unknown> {\n const nodeInput = config.toNodeItem({\n input: args.input,\n item: args.item,\n itemIndex: args.itemIndex,\n items: args.items,\n ctx: args.ctx,\n node: config.node,\n });\n const nodeCtx = this.resolveNodeCtx(config, args);\n const resolvedNode = this.nodeResolver.resolve(config.node.type);\n const outputs = await this.executeResolvedNode(resolvedNode, nodeInput, nodeCtx);\n return config.toToolOutput({\n input: args.input,\n item: args.item,\n itemIndex: args.itemIndex,\n items: args.items,\n ctx: args.ctx,\n node: config.node,\n outputs,\n });\n }\n\n /**\n * Returns a re-rooted child ctx for nested-agent tools (so their LLM/tool connection ids derive\n * from the tool connection node, telemetry parents under the tool-call span, and connection\n * invocations carry `parentInvocationId`). Plain runnable tools (non-agent) keep the orchestrator\n * ctx with only `config` swapped — no nesting concern.\n *\n * The caller (`AIAgentNode.createItemScopedTools`) already wraps the orchestrator ctx via\n * `ConnectionCredentialExecutionContextFactory.forConnectionNode`, so `args.ctx.nodeId` is the\n * tool's own connection node id (e.g. `AIAgentNode:2__conn__tool__searchInMail`). We pass that\n * through as the sub-agent's `nodeId`; deriving another `toolConnectionNodeId(args.ctx.nodeId,\n * config.name)` here would prepend a duplicate `__conn__tool__<name>` segment and exponentially\n * deepen ids on each invocation, which also breaks credential resolution because user-provided\n * bindings sit on the single-level connection node id.\n */\n private resolveNodeCtx(\n config: NodeBackedToolConfig<any, ZodSchemaAny, ZodSchemaAny>,\n args: ToolExecuteArgs,\n ): NodeExecutionContext<RunnableNodeConfig> {\n const isNestedAgent = AgentConfigInspector.isAgentNodeConfig(config.node);\n const hooks = args.hooks;\n if (!isNestedAgent || !hooks?.parentSpan || !hooks.parentInvocationId) {\n return {\n ...args.ctx,\n config: config.node,\n } as NodeExecutionContext<RunnableNodeConfig>;\n }\n return this.childExecutionScopeFactory.forSubAgent({\n parentCtx: args.ctx as NodeExecutionContext<RunnableNodeConfig>,\n childNodeId: args.ctx.nodeId,\n childConfig: config.node as unknown as RunnableNodeConfig,\n parentInvocationId: hooks.parentInvocationId,\n parentSpan: hooks.parentSpan,\n });\n }\n\n private async executeResolvedNode(\n resolvedNode: unknown,\n nodeInput: ToolExecuteArgs[\"item\"],\n ctx: NodeExecutionContext<RunnableNodeConfig>,\n ): Promise<NodeOutputs> {\n if (this.isMultiInputNode(resolvedNode)) {\n return await resolvedNode.executeMulti({ in: [nodeInput] }, ctx);\n }\n if (this.isRunnableNode(resolvedNode)) {\n const runnable = resolvedNode;\n const runnableConfig = ctx.config;\n const behavior = this.outputBehaviorResolver.resolve(runnableConfig);\n const inputSchema = runnable.inputSchema ?? runnableConfig.inputSchema ?? z.unknown();\n const parsed = inputSchema.parse(nodeInput.json);\n const items = [nodeInput];\n const resolvedCtx = await this.itemExprResolver.resolveConfigForItem(ctx, nodeInput, 0, items);\n const execArgs: RunnableNodeExecuteArgs = {\n input: parsed,\n item: nodeInput,\n itemIndex: 0,\n items,\n ctx: resolvedCtx,\n };\n const raw = await Promise.resolve(runnable.execute(execArgs));\n return this.outputNormalizer.normalizeExecuteResult({\n baseItem: nodeInput,\n raw,\n behavior,\n });\n }\n throw new Error(`Node-backed tool expected a runnable node instance for \"${ctx.config.name ?? ctx.nodeId}\".`);\n }\n\n private isRunnableNode(value: unknown): value is RunnableNode {\n return (\n typeof value === \"object\" &&\n value !== null &&\n (value as { kind?: string }).kind === \"node\" &&\n typeof (value as { execute?: unknown }).execute === \"function\" &&\n typeof (value as { executeMulti?: unknown }).executeMulti !== \"function\"\n );\n }\n\n private isMultiInputNode(value: unknown): value is MultiInputNode<any> {\n return typeof value === \"object\" && value !== null && \"executeMulti\" in value;\n }\n}\n","import type {\n AgentToolCall,\n ConnectionInvocationId,\n Item,\n NodeInputsByPort,\n TelemetrySpanScope,\n ToolConfig,\n ToolExecuteArgs,\n ZodSchemaAny,\n} from \"@codemation/core\";\n\nexport class AgentItemPortMap {\n static fromItem(item: Item): NodeInputsByPort {\n return { in: [item] };\n }\n}\n\nexport type ResolvedTool = Readonly<{\n config: ToolConfig;\n runtime: Readonly<{\n defaultDescription: string;\n inputSchema: ZodSchemaAny;\n execute(args: ToolExecuteArgs<ToolConfig, unknown>): Promise<unknown>;\n }>;\n}>;\n\n/**\n * Per-item binding of a tool: the user config plus the resolved runtime and a snapshot of the\n * original Zod `inputSchema`.\n *\n * `execute` accepts optional `hooks` so the agent coordinator can pass the live `agent.tool.call`\n * span and the planned tool-call's `invocationId`. Node-backed sub-agent tools use these hooks\n * via {@link ChildExecutionScopeFactory} to re-root their runtime ctx under the tool-call boundary\n * (fresh activationId, telemetry parented at the tool-call span, `parentInvocationId` set).\n */\nexport type ItemScopedToolBinding = Readonly<{\n config: ToolConfig;\n inputSchema: ZodSchemaAny;\n execute(input: unknown, hooks?: ItemScopedToolCallHooks): Promise<unknown>;\n}>;\n\nexport type ItemScopedToolCallHooks = Readonly<{\n /** Live agent.tool.call span (used to parent sub-agent telemetry). */\n parentSpan?: TelemetrySpanScope;\n /** invocationId of the parent tool call (used to thread `parentInvocationId` through ctx). */\n parentInvocationId?: ConnectionInvocationId;\n}>;\n\nexport type PlannedToolCall = Readonly<{\n binding: ItemScopedToolBinding;\n toolCall: AgentToolCall;\n invocationIndex: number;\n nodeId: string;\n /** Stable id reused across queued / running / completed connection invocation rows for this tool call. */\n invocationId: string;\n}>;\n\nexport type ExecutedToolCall = Readonly<{\n toolName: string;\n toolCallId: string;\n result: unknown;\n serialized: string;\n}>;\n","import type {\n AgentGuardrailConfig,\n AgentToolCall,\n ChatLanguageModel,\n ChatLanguageModelCallOptions,\n ChatModelConfig,\n ChatModelFactory,\n Item,\n Items,\n JsonValue,\n NodeExecutionContext,\n NodeInputsByPort,\n RunnableNode,\n RunnableNodeExecuteArgs,\n Tool,\n ToolConfig,\n ZodSchemaAny,\n} from \"@codemation/core\";\n\nimport type { CredentialSessionService } from \"@codemation/core\";\nimport {\n AgentGuardrailDefaults,\n AgentMessageConfigNormalizer,\n CallableToolConfig,\n CodemationTelemetryAttributeNames,\n CodemationTelemetryMetricNames,\n ConnectionInvocationIdFactory,\n ConnectionNodeIdFactory,\n CoreTokens,\n GenAiTelemetryAttributeNames,\n NodeBackedToolConfig,\n inject,\n node,\n type NodeResolver,\n} from \"@codemation/core\";\n\nimport type { AssistantModelMessage, GenerateTextResult, LanguageModel, ModelMessage, ToolSet } from \"ai\";\nimport { Output, generateText, jsonSchema } from \"ai\";\n\n/**\n * OUTPUT generic must extend AI SDK's `Output<OUTPUT, PARTIAL, ELEMENT>` which is parametric on\n * `any`; there is no narrower concrete type we can substitute that accepts both text-only and\n * structured turns uniformly.\n */\ntype AnyGenerateTextResult = GenerateTextResult<ToolSet, any>;\nimport { z } from \"zod\";\n\nimport type { AIAgent } from \"./AIAgentConfig\";\nimport { AIAgentExecutionHelpersFactory } from \"./AIAgentExecutionHelpersFactory\";\nimport { AgentToolExecutionCoordinator } from \"./AgentToolExecutionCoordinator\";\nimport { ConnectionCredentialExecutionContextFactory } from \"./ConnectionCredentialExecutionContextFactory\";\nimport { AgentMessageFactory } from \"./AgentMessageFactory\";\nimport { AgentOutputFactory } from \"./AgentOutputFactory\";\nimport { AgentStructuredOutputRunner } from \"./AgentStructuredOutputRunner\";\nimport { AgentToolCallPortMap } from \"./AgentToolCallPortMapFactory\";\nimport { NodeBackedToolRuntime } from \"./NodeBackedToolRuntime\";\nimport {\n AgentItemPortMap,\n type ExecutedToolCall,\n type ItemScopedToolBinding,\n type PlannedToolCall,\n type ResolvedTool,\n} from \"./aiAgentSupport.types\";\n\ntype ResolvedGuardrails = Required<Pick<AgentGuardrailConfig, \"maxTurns\" | \"onTurnLimitReached\">> &\n Pick<AgentGuardrailConfig, \"modelInvocationOptions\">;\n\n/** Everything needed to run the agent loop for one item (shared across items in the same activation). */\ninterface PreparedAgentExecution {\n readonly ctx: NodeExecutionContext<AIAgent<any, any>>;\n readonly model: ChatLanguageModel;\n readonly resolvedTools: ReadonlyArray<ResolvedTool>;\n readonly guardrails: ResolvedGuardrails;\n readonly languageModelConnectionNodeId: string;\n}\n\n/** Result of one `generateText` turn with tools disabled for auto-execution. */\ninterface TurnResult {\n readonly assistantMessage: AssistantModelMessage | undefined;\n readonly text: string;\n readonly toolCalls: ReadonlyArray<AgentToolCall>;\n readonly usage: ModelUsage;\n}\n\ninterface ModelUsage {\n readonly inputTokens?: number;\n readonly outputTokens?: number;\n readonly totalTokens?: number;\n readonly cachedInputTokens?: number;\n readonly reasoningTokens?: number;\n}\n\n@node({ packageName: \"@codemation/core-nodes\" })\nexport class AIAgentNode implements RunnableNode<AIAgent<any, any>> {\n kind = \"node\" as const;\n outputPorts = [\"main\"] as const;\n readonly inputSchema = z.unknown();\n\n private readonly connectionCredentialExecutionContextFactory: ConnectionCredentialExecutionContextFactory;\n private readonly preparedByExecutionContext = new WeakMap<\n NodeExecutionContext<AIAgent<any, any>>,\n Promise<PreparedAgentExecution>\n >();\n\n constructor(\n @inject(CoreTokens.NodeResolver)\n private readonly nodeResolver: NodeResolver,\n @inject(CoreTokens.CredentialSessionService)\n credentialSessions: CredentialSessionService,\n @inject(NodeBackedToolRuntime)\n private readonly nodeBackedToolRuntime: NodeBackedToolRuntime,\n @inject(AIAgentExecutionHelpersFactory)\n private readonly executionHelpers: AIAgentExecutionHelpersFactory,\n @inject(AgentStructuredOutputRunner)\n private readonly structuredOutputRunner: AgentStructuredOutputRunner,\n @inject(AgentToolExecutionCoordinator)\n private readonly toolExecutionCoordinator: AgentToolExecutionCoordinator,\n ) {\n this.connectionCredentialExecutionContextFactory =\n this.executionHelpers.createConnectionCredentialExecutionContextFactory(credentialSessions);\n }\n\n async execute(args: RunnableNodeExecuteArgs<AIAgent<any, any>>): Promise<unknown> {\n const prepared = await this.getOrPrepareExecution(args.ctx);\n const itemWithMappedJson = { ...args.item, json: args.input };\n const resultItem = await this.runAgentForItem(prepared, itemWithMappedJson, args.itemIndex, args.items);\n return resultItem.json;\n }\n\n private async getOrPrepareExecution(ctx: NodeExecutionContext<AIAgent<any, any>>): Promise<PreparedAgentExecution> {\n let pending = this.preparedByExecutionContext.get(ctx);\n if (!pending) {\n pending = this.prepareExecution(ctx);\n this.preparedByExecutionContext.set(ctx, pending);\n }\n try {\n return await pending;\n } catch (error) {\n this.preparedByExecutionContext.delete(ctx);\n throw error;\n }\n }\n\n private async prepareExecution(ctx: NodeExecutionContext<AIAgent<any, any>>): Promise<PreparedAgentExecution> {\n const chatModelFactory = this.nodeResolver.resolve(ctx.config.chatModel.type) as ChatModelFactory<ChatModelConfig>;\n const languageModelCredentialContext = this.connectionCredentialExecutionContextFactory.forConnectionNode(ctx, {\n connectionNodeId: ConnectionNodeIdFactory.languageModelConnectionNodeId(ctx.nodeId),\n getCredentialRequirements: () => ctx.config.chatModel.getCredentialRequirements?.() ?? [],\n });\n const model = await Promise.resolve(\n chatModelFactory.create({ config: ctx.config.chatModel, ctx: languageModelCredentialContext }),\n );\n return {\n ctx,\n model,\n resolvedTools: this.resolveTools(ctx.config.tools ?? []),\n guardrails: this.resolveGuardrails(ctx.config.guardrails),\n languageModelConnectionNodeId: ConnectionNodeIdFactory.languageModelConnectionNodeId(ctx.nodeId),\n };\n }\n\n private async runAgentForItem(\n prepared: PreparedAgentExecution,\n item: Item,\n itemIndex: number,\n items: Items,\n ): Promise<Item> {\n const { ctx } = prepared;\n const itemInputsByPort = AgentItemPortMap.fromItem(item);\n const itemScopedTools = this.createItemScopedTools(prepared.resolvedTools, ctx, item, itemIndex, items);\n const conversation: ModelMessage[] = [...this.createPromptMessages(item, itemIndex, items, ctx)];\n if (ctx.config.outputSchema && itemScopedTools.length === 0) {\n const structuredOutput = await this.structuredOutputRunner.resolve({\n model: prepared.model,\n chatModelConfig: ctx.config.chatModel,\n schema: ctx.config.outputSchema,\n conversation,\n agentName: this.getAgentDisplayName(ctx),\n nodeId: ctx.nodeId,\n invokeTextModel: async (messages) => await this.invokeTextTurn(prepared, itemInputsByPort, messages, []),\n invokeStructuredModel: async (schema, messages, structuredOptions) =>\n await this.invokeStructuredTurn(prepared, itemInputsByPort, schema, messages, structuredOptions),\n });\n await ctx.telemetry.recordMetric({ name: CodemationTelemetryMetricNames.agentTurns, value: 1 });\n await ctx.telemetry.recordMetric({ name: CodemationTelemetryMetricNames.agentToolCalls, value: 0 });\n return this.buildOutputItem(item, structuredOutput);\n }\n const loopResult = await this.runTurnLoopUntilFinalAnswer({\n prepared,\n itemInputsByPort,\n itemScopedTools,\n conversation,\n });\n await ctx.telemetry.recordMetric({ name: CodemationTelemetryMetricNames.agentTurns, value: loopResult.turnCount });\n await ctx.telemetry.recordMetric({\n name: CodemationTelemetryMetricNames.agentToolCalls,\n value: loopResult.toolCallCount,\n });\n const outputJson = await this.resolveFinalOutputJson(\n prepared,\n itemInputsByPort,\n conversation,\n loopResult.finalText,\n itemScopedTools.length > 0,\n );\n return this.buildOutputItem(item, outputJson);\n }\n\n /**\n * Multi-turn loop:\n * - Each turn is a single `generateText` call with tools exposed but **not auto-executed**\n * (we control tool dispatch so that {@link AgentToolExecutionCoordinator} drives repair /\n * connection-invocation recording / transient-error handling exactly like before).\n * - When the model returns no tool calls the loop ends with the model's text as the final answer.\n * - Respects `guardrails.maxTurns` and `guardrails.onTurnLimitReached`.\n */\n private async runTurnLoopUntilFinalAnswer(args: {\n prepared: PreparedAgentExecution;\n itemInputsByPort: NodeInputsByPort;\n itemScopedTools: ReadonlyArray<ItemScopedToolBinding>;\n conversation: ModelMessage[];\n }): Promise<Readonly<{ finalText: string; turnCount: number; toolCallCount: number }>> {\n const { prepared, itemInputsByPort, itemScopedTools, conversation } = args;\n const { ctx, guardrails } = prepared;\n\n let finalText = \"\";\n let toolCallCount = 0;\n let turnCount = 0;\n const repairAttemptsByToolName = new Map<string, number>();\n\n for (let turn = 1; turn <= guardrails.maxTurns; turn++) {\n turnCount = turn;\n const result = await this.invokeTextTurn(prepared, itemInputsByPort, conversation, itemScopedTools);\n finalText = result.text;\n\n if (result.toolCalls.length === 0) {\n break;\n }\n\n if (this.cannotExecuteAnotherToolRound(turn, guardrails)) {\n this.finishOrThrowWhenTurnCapHitWithToolCalls(ctx, guardrails);\n break;\n }\n\n const plannedToolCalls = this.planToolCalls(itemScopedTools, result.toolCalls, ctx.nodeId);\n toolCallCount += plannedToolCalls.length;\n await this.markQueuedTools(plannedToolCalls, ctx);\n const executedToolCalls = await this.toolExecutionCoordinator.execute({\n plannedToolCalls,\n ctx,\n agentName: this.getAgentDisplayName(ctx),\n repairAttemptsByToolName,\n });\n this.appendAssistantAndToolMessages(\n conversation,\n result.assistantMessage,\n result.text,\n result.toolCalls,\n executedToolCalls,\n );\n }\n\n return {\n finalText,\n turnCount,\n toolCallCount,\n };\n }\n\n private cannotExecuteAnotherToolRound(turn: number, guardrails: ResolvedGuardrails): boolean {\n return turn >= guardrails.maxTurns;\n }\n\n private finishOrThrowWhenTurnCapHitWithToolCalls(\n ctx: NodeExecutionContext<AIAgent<any, any>>,\n guardrails: ResolvedGuardrails,\n ): void {\n if (guardrails.onTurnLimitReached === \"respondWithLastMessage\") {\n return;\n }\n throw new Error(\n `AIAgent \"${ctx.config.name ?? ctx.nodeId}\" reached maxTurns=${guardrails.maxTurns} before producing a final response.`,\n );\n }\n\n private appendAssistantAndToolMessages(\n conversation: ModelMessage[],\n assistantMessage: AssistantModelMessage | undefined,\n text: string,\n toolCalls: ReadonlyArray<AgentToolCall>,\n executedToolCalls: ReadonlyArray<ExecutedToolCall>,\n ): void {\n conversation.push(\n assistantMessage ?? AgentMessageFactory.createAssistantWithToolCalls(text, toolCalls),\n AgentMessageFactory.createToolResultsMessage(executedToolCalls),\n );\n }\n\n private async resolveFinalOutputJson(\n prepared: PreparedAgentExecution,\n itemInputsByPort: NodeInputsByPort,\n conversation: ReadonlyArray<ModelMessage>,\n finalText: string,\n wasToolEnabledRun: boolean,\n ): Promise<unknown> {\n if (!prepared.ctx.config.outputSchema) {\n return AgentOutputFactory.fromAgentContent(finalText);\n }\n const conversationWithFinal: ReadonlyArray<ModelMessage> = wasToolEnabledRun\n ? [...conversation, { role: \"assistant\", content: finalText }]\n : conversation;\n return await this.structuredOutputRunner.resolve({\n model: prepared.model,\n chatModelConfig: prepared.ctx.config.chatModel,\n schema: prepared.ctx.config.outputSchema,\n conversation: conversationWithFinal,\n rawFinalText: finalText,\n agentName: this.getAgentDisplayName(prepared.ctx),\n nodeId: prepared.ctx.nodeId,\n invokeTextModel: async (messages) => await this.invokeTextTurn(prepared, itemInputsByPort, messages, []),\n invokeStructuredModel: async (schema, messages, structuredOptions) =>\n await this.invokeStructuredTurn(prepared, itemInputsByPort, schema, messages, structuredOptions),\n });\n }\n\n private buildOutputItem(item: Item, outputJson: unknown): Item {\n return AgentOutputFactory.replaceJson(item, outputJson);\n }\n\n private resolveTools(toolConfigs: ReadonlyArray<ToolConfig>): ReadonlyArray<ResolvedTool> {\n const resolvedTools = toolConfigs.map((config) => ({\n config,\n runtime: this.resolveToolRuntime(config),\n }));\n\n const names = new Set<string>();\n for (const entry of resolvedTools) {\n if (names.has(entry.config.name)) throw new Error(`Duplicate tool name on AIAgent: ${entry.config.name}`);\n names.add(entry.config.name);\n }\n return resolvedTools;\n }\n\n private createItemScopedTools(\n tools: ReadonlyArray<ResolvedTool>,\n ctx: NodeExecutionContext<AIAgent<any, any>>,\n item: Item,\n itemIndex: number,\n items: Items,\n ): ReadonlyArray<ItemScopedToolBinding> {\n return tools.map((entry) => {\n const toolCredentialContext = this.connectionCredentialExecutionContextFactory.forConnectionNode(ctx, {\n connectionNodeId: ConnectionNodeIdFactory.toolConnectionNodeId(ctx.nodeId, entry.config.name),\n getCredentialRequirements: () => entry.config.getCredentialRequirements?.() ?? [],\n });\n return {\n config: entry.config,\n inputSchema: entry.runtime.inputSchema,\n execute: async (input, hooks): Promise<unknown> => {\n const validated = entry.runtime.inputSchema.parse(input) as unknown;\n return await entry.runtime.execute({\n config: entry.config,\n input: validated,\n ctx: toolCredentialContext,\n item,\n itemIndex,\n items,\n hooks,\n });\n },\n } satisfies ItemScopedToolBinding;\n });\n }\n\n /**\n * Builds an AI SDK {@link ToolSet} where every tool ships a pre-converted JSON Schema (via\n * {@link jsonSchema}) — not the raw Zod schema — and carries **no** `execute`. Two reasons:\n *\n * 1. Codemation owns tool dispatch + the per-tool repair loop (see {@link AgentToolExecutionCoordinator}),\n * so the AI SDK must surface tool calls back to us instead of auto-running them.\n * 2. The AI SDK's `asSchema` helper discriminates between Zod v3 / Zod v4 / Standard Schema via\n * runtime feature-detection (`~standard`, `_zod`, etc.). Handing it a pre-built\n * {@link jsonSchema} record — which is tagged with `Symbol.for('vercel.ai.schema')` — skips all\n * of that detection and guarantees the provider receives a draft-07 JSON Schema with\n * `additionalProperties: false` at every object depth (see {@link OpenAiStrictJsonSchemaFactory}\n * for the same logic applied to structured-output schemas). Codemation still runs its own Zod\n * validation on tool inputs before execute — the schema handed to the model is advisory.\n */\n private buildToolSet(itemScopedTools: ReadonlyArray<ItemScopedToolBinding>): ToolSet | undefined {\n if (itemScopedTools.length === 0) return undefined;\n const toolSet: Record<string, { description?: string; inputSchema: ReturnType<typeof jsonSchema> }> = {};\n for (const entry of itemScopedTools) {\n const schemaRecord = this.executionHelpers.createJsonSchemaRecord(entry.inputSchema, {\n schemaName: entry.config.name,\n requireObjectRoot: true,\n });\n toolSet[entry.config.name] = {\n description: entry.config.description,\n inputSchema: jsonSchema(schemaRecord as Parameters<typeof jsonSchema>[0]),\n };\n }\n return toolSet as unknown as ToolSet;\n }\n\n /**\n * One `generateText` turn (no auto tool execution) with Codemation-owned child-span telemetry\n * and connection-invocation state recording.\n */\n private async invokeTextTurn(\n prepared: PreparedAgentExecution,\n itemInputsByPort: NodeInputsByPort,\n messages: ReadonlyArray<ModelMessage>,\n itemScopedTools: ReadonlyArray<ItemScopedToolBinding>,\n ): Promise<TurnResult> {\n const invocationId = ConnectionInvocationIdFactory.create();\n const startedAt = new Date();\n const summarizedInput = this.summarizeLlmMessages(messages);\n const { ctx, model, languageModelConnectionNodeId, guardrails } = prepared;\n const span = this.createModelInvocationSpan(ctx, invocationId, startedAt);\n await ctx.nodeState?.markQueued({\n nodeId: languageModelConnectionNodeId,\n activationId: ctx.activationId,\n inputsByPort: itemInputsByPort,\n });\n await ctx.nodeState?.appendConnectionInvocation({\n invocationId,\n connectionNodeId: languageModelConnectionNodeId,\n parentAgentNodeId: ctx.nodeId,\n parentAgentActivationId: ctx.activationId,\n status: \"queued\",\n managedInput: summarizedInput,\n queuedAt: startedAt.toISOString(),\n iterationId: ctx.iterationId,\n itemIndex: ctx.itemIndex,\n parentInvocationId: ctx.parentInvocationId,\n });\n await ctx.nodeState?.markRunning({\n nodeId: languageModelConnectionNodeId,\n activationId: ctx.activationId,\n inputsByPort: itemInputsByPort,\n });\n await ctx.nodeState?.appendConnectionInvocation({\n invocationId,\n connectionNodeId: languageModelConnectionNodeId,\n parentAgentNodeId: ctx.nodeId,\n parentAgentActivationId: ctx.activationId,\n status: \"running\",\n managedInput: summarizedInput,\n queuedAt: startedAt.toISOString(),\n startedAt: startedAt.toISOString(),\n iterationId: ctx.iterationId,\n itemIndex: ctx.itemIndex,\n parentInvocationId: ctx.parentInvocationId,\n });\n try {\n const tools = this.buildToolSet(itemScopedTools);\n const callOptions = this.resolveCallOptions(model, guardrails.modelInvocationOptions);\n const result = await generateText({\n model: model.languageModel as LanguageModel,\n messages: [...messages],\n tools,\n toolChoice: tools ? \"auto\" : undefined,\n maxOutputTokens: callOptions.maxOutputTokens,\n temperature: callOptions.temperature,\n providerOptions: callOptions.providerOptions as Record<string, Record<string, never>>,\n maxRetries: 0,\n });\n const turnResult = this.extractTurnResult(result as AnyGenerateTextResult);\n const finishedAt = new Date();\n const managedOutput = this.summarizeTurnOutput(turnResult);\n await ctx.nodeState?.markCompleted({\n nodeId: languageModelConnectionNodeId,\n activationId: ctx.activationId,\n inputsByPort: itemInputsByPort,\n outputs: AgentOutputFactory.fromUnknown(managedOutput),\n });\n await span.attachArtifact({ kind: \"ai.messages\", contentType: \"application/json\", previewJson: summarizedInput });\n await span.attachArtifact({ kind: \"ai.response\", contentType: \"application/json\", previewJson: turnResult.text });\n await this.recordModelUsageMetrics(span, turnResult.usage, ctx);\n await span.end({ status: \"ok\", endedAt: finishedAt });\n await ctx.nodeState?.appendConnectionInvocation({\n invocationId,\n connectionNodeId: languageModelConnectionNodeId,\n parentAgentNodeId: ctx.nodeId,\n parentAgentActivationId: ctx.activationId,\n status: \"completed\",\n managedInput: summarizedInput,\n managedOutput,\n queuedAt: startedAt.toISOString(),\n startedAt: startedAt.toISOString(),\n finishedAt: finishedAt.toISOString(),\n iterationId: ctx.iterationId,\n itemIndex: ctx.itemIndex,\n parentInvocationId: ctx.parentInvocationId,\n });\n return turnResult;\n } catch (error) {\n await span.end({\n status: \"error\",\n statusMessage: error instanceof Error ? error.message : String(error),\n endedAt: new Date(),\n });\n throw await this.failTrackedNodeInvocation({\n error,\n invocationId,\n startedAt,\n nodeId: languageModelConnectionNodeId,\n ctx,\n inputsByPort: itemInputsByPort,\n managedInput: summarizedInput,\n });\n }\n }\n\n /**\n * Structured-output turn: runs `generateText({ output: Output.object({ schema }) })` via the\n * structured-output runner. We keep this as a separate helper because the runner needs the raw\n * validated value (not just text) back, and must be able to retry on Zod failures.\n */\n private async invokeStructuredTurn(\n prepared: PreparedAgentExecution,\n itemInputsByPort: NodeInputsByPort,\n schema: ZodSchemaAny | Readonly<Record<string, unknown>>,\n messages: ReadonlyArray<ModelMessage>,\n structuredOptions: { readonly strict?: boolean; readonly schemaName?: string } | undefined,\n ): Promise<unknown> {\n const invocationId = ConnectionInvocationIdFactory.create();\n const startedAt = new Date();\n const summarizedInput = this.summarizeLlmMessages(messages);\n const { ctx, model, languageModelConnectionNodeId, guardrails } = prepared;\n const span = this.createModelInvocationSpan(ctx, invocationId, startedAt);\n await ctx.nodeState?.markQueued({\n nodeId: languageModelConnectionNodeId,\n activationId: ctx.activationId,\n inputsByPort: itemInputsByPort,\n });\n await ctx.nodeState?.appendConnectionInvocation({\n invocationId,\n connectionNodeId: languageModelConnectionNodeId,\n parentAgentNodeId: ctx.nodeId,\n parentAgentActivationId: ctx.activationId,\n status: \"queued\",\n managedInput: summarizedInput,\n queuedAt: startedAt.toISOString(),\n iterationId: ctx.iterationId,\n itemIndex: ctx.itemIndex,\n parentInvocationId: ctx.parentInvocationId,\n });\n await ctx.nodeState?.markRunning({\n nodeId: languageModelConnectionNodeId,\n activationId: ctx.activationId,\n inputsByPort: itemInputsByPort,\n });\n await ctx.nodeState?.appendConnectionInvocation({\n invocationId,\n connectionNodeId: languageModelConnectionNodeId,\n parentAgentNodeId: ctx.nodeId,\n parentAgentActivationId: ctx.activationId,\n status: \"running\",\n managedInput: summarizedInput,\n queuedAt: startedAt.toISOString(),\n startedAt: startedAt.toISOString(),\n iterationId: ctx.iterationId,\n itemIndex: ctx.itemIndex,\n parentInvocationId: ctx.parentInvocationId,\n });\n try {\n const callOptions = this.resolveCallOptions(model, guardrails.modelInvocationOptions);\n const outputSchema =\n structuredOptions?.strict && !this.isZodSchema(schema)\n ? Output.object({ schema: jsonSchema(schema as Parameters<typeof jsonSchema>[0]) as never })\n : Output.object({ schema: schema as ZodSchemaAny });\n const result = await generateText({\n model: model.languageModel as LanguageModel,\n messages: [...messages],\n experimental_output: outputSchema,\n maxOutputTokens: callOptions.maxOutputTokens,\n temperature: callOptions.temperature,\n providerOptions: callOptions.providerOptions as Record<string, Record<string, never>>,\n maxRetries: 0,\n });\n const turnResult = this.extractTurnResult(result as AnyGenerateTextResult);\n const finishedAt = new Date();\n await ctx.nodeState?.markCompleted({\n nodeId: languageModelConnectionNodeId,\n activationId: ctx.activationId,\n inputsByPort: itemInputsByPort,\n outputs: AgentOutputFactory.fromUnknown(result.experimental_output),\n });\n await span.attachArtifact({ kind: \"ai.messages\", contentType: \"application/json\", previewJson: summarizedInput });\n await span.attachArtifact({\n kind: \"ai.response.structured\",\n contentType: \"application/json\",\n previewJson: this.resultToJsonValue(result.experimental_output),\n });\n await this.recordModelUsageMetrics(span, turnResult.usage, ctx);\n await span.end({ status: \"ok\", endedAt: finishedAt });\n await ctx.nodeState?.appendConnectionInvocation({\n invocationId,\n connectionNodeId: languageModelConnectionNodeId,\n parentAgentNodeId: ctx.nodeId,\n parentAgentActivationId: ctx.activationId,\n status: \"completed\",\n managedInput: summarizedInput,\n managedOutput: this.resultToJsonValue(result.experimental_output),\n queuedAt: startedAt.toISOString(),\n startedAt: startedAt.toISOString(),\n finishedAt: finishedAt.toISOString(),\n iterationId: ctx.iterationId,\n itemIndex: ctx.itemIndex,\n parentInvocationId: ctx.parentInvocationId,\n });\n return result.experimental_output;\n } catch (error) {\n await span.end({\n status: \"error\",\n statusMessage: error instanceof Error ? error.message : String(error),\n endedAt: new Date(),\n });\n throw await this.failTrackedNodeInvocation({\n error,\n invocationId,\n startedAt,\n nodeId: languageModelConnectionNodeId,\n ctx,\n inputsByPort: itemInputsByPort,\n managedInput: summarizedInput,\n });\n }\n }\n\n private isZodSchema(schema: ZodSchemaAny | Readonly<Record<string, unknown>>): schema is ZodSchemaAny {\n const candidate = schema as { parse?: unknown };\n return typeof candidate.parse === \"function\";\n }\n\n private resolveCallOptions(\n model: ChatLanguageModel,\n overrides: AgentGuardrailConfig[\"modelInvocationOptions\"] | undefined,\n ): ChatLanguageModelCallOptions {\n const defaults = model.defaultCallOptions ?? {};\n return {\n maxOutputTokens: overrides?.maxTokens ?? defaults.maxOutputTokens,\n temperature: defaults.temperature,\n providerOptions: (overrides?.providerOptions ??\n defaults.providerOptions) as ChatLanguageModelCallOptions[\"providerOptions\"],\n };\n }\n\n /**\n * Build a no-code-friendly output payload for an LLM round.\n *\n * Always includes `content` (matching the canvas snapshot shape used elsewhere) and adds a\n * `toolCalls` array when the round produced tool calls so the execution inspector surfaces the\n * planned calls instead of just an empty `\"\"` for tool-only rounds.\n */\n private summarizeTurnOutput(turnResult: TurnResult): JsonValue {\n if (turnResult.toolCalls.length === 0) return { content: turnResult.text };\n const toolCalls = turnResult.toolCalls.map((toolCall) => ({\n name: toolCall.name,\n args: this.resultToJsonValue(toolCall.input) ?? null,\n }));\n return { content: turnResult.text, toolCalls };\n }\n\n private extractTurnResult(result: AnyGenerateTextResult): TurnResult {\n const usage = this.extractUsageFromResult(result);\n const text = result.text;\n const toolCalls: ReadonlyArray<AgentToolCall> = result.toolCalls.map((toolCall) => ({\n id: toolCall.toolCallId,\n name: toolCall.toolName,\n input: (toolCall as { input?: unknown }).input,\n }));\n const assistantMessage = this.extractAssistantMessage(result);\n return {\n assistantMessage,\n text,\n toolCalls,\n usage,\n };\n }\n\n private extractAssistantMessage(result: AnyGenerateTextResult): AssistantModelMessage | undefined {\n const responseMessages: ReadonlyArray<ModelMessage> = result.response.messages;\n const assistantMessages = responseMessages.filter((m) => m.role === \"assistant\");\n return assistantMessages[assistantMessages.length - 1];\n }\n\n private extractUsageFromResult(result: AnyGenerateTextResult): ModelUsage {\n const usage = result.usage;\n const inputTokens = this.toFiniteNumber(usage.inputTokens);\n const outputTokens = this.toFiniteNumber(usage.outputTokens);\n const totalTokens =\n this.toFiniteNumber(usage.totalTokens) ??\n (inputTokens !== undefined && outputTokens !== undefined ? inputTokens + outputTokens : undefined);\n const cachedInputTokens = this.toFiniteNumber(usage.cachedInputTokens);\n const reasoningTokens = this.toFiniteNumber(usage.reasoningTokens);\n return { inputTokens, outputTokens, totalTokens, cachedInputTokens, reasoningTokens };\n }\n\n private toFiniteNumber(value: unknown): number | undefined {\n if (typeof value !== \"number\" || !Number.isFinite(value)) return undefined;\n return value;\n }\n\n private createModelInvocationSpan(\n ctx: NodeExecutionContext<AIAgent<any, any>>,\n invocationId: string,\n startedAt: Date,\n ) {\n return ctx.telemetry.startChildSpan({\n name: \"gen_ai.chat.completion\",\n kind: \"client\",\n startedAt,\n attributes: {\n [CodemationTelemetryAttributeNames.connectionInvocationId]: invocationId,\n [GenAiTelemetryAttributeNames.operationName]: \"chat\",\n [GenAiTelemetryAttributeNames.requestModel]: this.resolveChatModelName(ctx.config.chatModel),\n ...(ctx.iterationId ? { [CodemationTelemetryAttributeNames.iterationId]: ctx.iterationId } : {}),\n ...(typeof ctx.itemIndex === \"number\"\n ? { [CodemationTelemetryAttributeNames.iterationIndex]: ctx.itemIndex }\n : {}),\n ...(ctx.parentInvocationId\n ? { [CodemationTelemetryAttributeNames.parentInvocationId]: ctx.parentInvocationId }\n : {}),\n },\n });\n }\n\n private async recordModelUsageMetrics(\n span: ReturnType<NodeExecutionContext[\"telemetry\"][\"startChildSpan\"]>,\n usage: ModelUsage,\n ctx: NodeExecutionContext<AIAgent<any, any>>,\n ) {\n const entries: ReadonlyArray<readonly [string, number | undefined]> = [\n [GenAiTelemetryAttributeNames.usageInputTokens, usage.inputTokens],\n [GenAiTelemetryAttributeNames.usageOutputTokens, usage.outputTokens],\n [GenAiTelemetryAttributeNames.usageTotalTokens, usage.totalTokens],\n [GenAiTelemetryAttributeNames.usageCacheReadInputTokens, usage.cachedInputTokens],\n [GenAiTelemetryAttributeNames.usageReasoningTokens, usage.reasoningTokens],\n ];\n for (const [name, value] of entries) {\n if (value === undefined) continue;\n await span.recordMetric({ name, value });\n }\n await this.captureCostTrackingUsage(span, ctx, usage);\n }\n\n private async captureCostTrackingUsage(\n span: ReturnType<NodeExecutionContext[\"telemetry\"][\"startChildSpan\"]>,\n ctx: NodeExecutionContext<AIAgent<any, any>>,\n usage: ModelUsage,\n ): Promise<void> {\n const costTracking = span.costTracking;\n if (!costTracking) return;\n const provider = ctx.config.chatModel.provider;\n const pricingKey = ctx.config.chatModel.modelName;\n if (!provider || !pricingKey) return;\n if (usage.inputTokens !== undefined) {\n await costTracking.captureUsage({\n component: \"chat\",\n provider,\n operation: \"completion.input\",\n pricingKey,\n usageUnit: \"input_tokens\",\n quantity: usage.inputTokens,\n modelName: pricingKey,\n });\n }\n if (usage.outputTokens !== undefined) {\n await costTracking.captureUsage({\n component: \"chat\",\n provider,\n operation: \"completion.output\",\n pricingKey,\n usageUnit: \"output_tokens\",\n quantity: usage.outputTokens,\n modelName: pricingKey,\n });\n }\n }\n\n private resolveChatModelName(chatModel: ChatModelConfig): string {\n return chatModel.modelName ?? chatModel.name;\n }\n\n private async markQueuedTools(\n plannedToolCalls: ReadonlyArray<PlannedToolCall>,\n ctx: NodeExecutionContext<AIAgent<any, any>>,\n ): Promise<void> {\n const queuedAt = new Date().toISOString();\n for (const plannedToolCall of plannedToolCalls) {\n await ctx.nodeState?.markQueued({\n nodeId: plannedToolCall.nodeId,\n activationId: ctx.activationId,\n inputsByPort: AgentToolCallPortMap.fromInput(plannedToolCall.toolCall.input ?? {}),\n });\n await ctx.nodeState?.appendConnectionInvocation({\n invocationId: plannedToolCall.invocationId,\n connectionNodeId: plannedToolCall.nodeId,\n parentAgentNodeId: ctx.nodeId,\n parentAgentActivationId: ctx.activationId,\n status: \"queued\",\n managedInput: this.resultToJsonValue(plannedToolCall.toolCall.input),\n queuedAt,\n iterationId: ctx.iterationId,\n itemIndex: ctx.itemIndex,\n parentInvocationId: ctx.parentInvocationId,\n });\n }\n }\n\n private planToolCalls(\n bindings: ReadonlyArray<ItemScopedToolBinding>,\n toolCalls: ReadonlyArray<AgentToolCall>,\n parentNodeId: string,\n ): ReadonlyArray<PlannedToolCall> {\n const invocationCountByToolName = new Map<string, number>();\n return toolCalls.map((toolCall) => {\n const binding = bindings.find((entry) => entry.config.name === toolCall.name);\n if (!binding) throw new Error(`Unknown tool requested by model: ${toolCall.name}`);\n const invocationIndex = (invocationCountByToolName.get(binding.config.name) ?? 0) + 1;\n invocationCountByToolName.set(binding.config.name, invocationIndex);\n return {\n binding,\n toolCall,\n invocationIndex,\n nodeId: ConnectionNodeIdFactory.toolConnectionNodeId(parentNodeId, binding.config.name),\n invocationId: ConnectionInvocationIdFactory.create(),\n } satisfies PlannedToolCall;\n });\n }\n\n private async failTrackedNodeInvocation(\n args: Readonly<{\n error: unknown;\n invocationId: string;\n startedAt: Date;\n nodeId: string;\n ctx: NodeExecutionContext<AIAgent<any, any>>;\n inputsByPort: NodeInputsByPort;\n managedInput?: JsonValue;\n }>,\n ): Promise<Error> {\n const effectiveError = args.error instanceof Error ? args.error : new Error(String(args.error));\n const finishedAt = new Date();\n await args.ctx.nodeState?.markFailed({\n nodeId: args.nodeId,\n activationId: args.ctx.activationId,\n inputsByPort: args.inputsByPort,\n error: effectiveError,\n });\n await args.ctx.nodeState?.appendConnectionInvocation({\n invocationId: args.invocationId,\n connectionNodeId: args.nodeId,\n parentAgentNodeId: args.ctx.nodeId,\n parentAgentActivationId: args.ctx.activationId,\n status: \"failed\",\n managedInput: args.managedInput,\n error: {\n message: effectiveError.message,\n name: effectiveError.name,\n stack: effectiveError.stack,\n details: this.extractErrorDetails(effectiveError),\n },\n queuedAt: args.startedAt.toISOString(),\n startedAt: args.startedAt.toISOString(),\n finishedAt: finishedAt.toISOString(),\n iterationId: args.ctx.iterationId,\n itemIndex: args.ctx.itemIndex,\n parentInvocationId: args.ctx.parentInvocationId,\n });\n return effectiveError;\n }\n\n private summarizeLlmMessages(messages: ReadonlyArray<ModelMessage>): JsonValue {\n const last = messages[messages.length - 1];\n const preview =\n typeof last?.content === \"string\"\n ? last.content\n : last?.content !== undefined\n ? JSON.stringify(last.content)\n : \"\";\n return {\n messageCount: messages.length,\n lastMessagePreview: preview.slice(0, 4000),\n };\n }\n\n private resultToJsonValue(value: unknown): JsonValue | undefined {\n if (value === undefined) return undefined;\n const json = JSON.stringify(value);\n return JSON.parse(json) as JsonValue;\n }\n\n private createPromptMessages(\n item: Item,\n itemIndex: number,\n items: Items,\n ctx: NodeExecutionContext<AIAgent<any, any>>,\n ): ReadonlyArray<ModelMessage> {\n return AgentMessageFactory.createPromptMessages(\n AgentMessageConfigNormalizer.resolveFromInputOrConfig(item.json, ctx.config, {\n item,\n itemIndex,\n items,\n ctx,\n }),\n );\n }\n\n private resolveToolRuntime(config: ToolConfig): ResolvedTool[\"runtime\"] {\n if (this.isNodeBackedToolConfig(config)) {\n const inputSchema = config.getInputSchema();\n if (inputSchema == null) {\n throw new Error(\n `AIAgent tool \"${config.name}\": node-backed tool is missing inputSchema (cannot build AI SDK tool).`,\n );\n }\n return {\n defaultDescription: `Run workflow node \"${config.node.name ?? config.name}\" as an AI tool.`,\n inputSchema,\n execute: async (args) => await this.nodeBackedToolRuntime.execute(config, args),\n };\n }\n if (this.isCallableToolConfig(config)) {\n const inputSchema = config.getInputSchema();\n if (inputSchema == null) {\n throw new Error(\n `AIAgent tool \"${config.name}\": callable tool is missing inputSchema (cannot build AI SDK tool).`,\n );\n }\n return {\n defaultDescription: config.description ?? `Callable tool \"${config.name}\".`,\n inputSchema,\n execute: async (args) =>\n await config.executeTool({ ...args, config: config as CallableToolConfig<ZodSchemaAny, ZodSchemaAny> }),\n };\n }\n const tool = this.nodeResolver.resolve(config.type) as Tool<ToolConfig, ZodSchemaAny, ZodSchemaAny>;\n if (tool.inputSchema == null) {\n throw new Error(`AIAgent tool \"${config.name}\": plugin tool \"${String(config.type)}\" is missing inputSchema.`);\n }\n return {\n defaultDescription: tool.defaultDescription,\n inputSchema: tool.inputSchema,\n execute: async (args) => await Promise.resolve(tool.execute(args)),\n };\n }\n\n private isNodeBackedToolConfig(config: ToolConfig): config is NodeBackedToolConfig<any, any, any> {\n return (\n config instanceof NodeBackedToolConfig ||\n (typeof config === \"object\" && config !== null && (config as { toolKind?: unknown }).toolKind === \"nodeBacked\")\n );\n }\n\n private isCallableToolConfig(config: ToolConfig): config is CallableToolConfig<ZodSchemaAny, ZodSchemaAny> {\n return (\n config instanceof CallableToolConfig ||\n (typeof config === \"object\" && config !== null && (config as { toolKind?: unknown }).toolKind === \"callable\")\n );\n }\n\n private resolveGuardrails(guardrails: AgentGuardrailConfig | undefined): ResolvedGuardrails {\n const maxTurns = guardrails?.maxTurns ?? AgentGuardrailDefaults.maxTurns;\n if (!Number.isInteger(maxTurns) || maxTurns < 1) {\n throw new Error(`AIAgent maxTurns must be a positive integer. Received: ${String(maxTurns)}`);\n }\n return {\n maxTurns,\n onTurnLimitReached: guardrails?.onTurnLimitReached ?? AgentGuardrailDefaults.onTurnLimitReached,\n modelInvocationOptions: guardrails?.modelInvocationOptions,\n };\n }\n\n private getAgentDisplayName(ctx: NodeExecutionContext<AIAgent<any, any>>): string {\n return ctx.config.name ?? ctx.nodeId;\n }\n\n private extractErrorDetails(error: Error): JsonValue | undefined {\n const candidate = error as Error & { details?: JsonValue };\n return candidate.details;\n }\n}\n","import {\n RetryPolicy,\n type AgentGuardrailConfig,\n type AgentMessageConfig,\n type AgentNodeConfig,\n type ChatModelConfig,\n type RetryPolicySpec,\n type RunnableNodeConfig,\n type ToolConfig,\n type TypeToken,\n} from \"@codemation/core\";\nimport type { ZodType } from \"zod\";\n\nimport { AIAgentNode } from \"./AIAgentNode\";\n\nexport interface AIAgentOptions<TInputJson = unknown, _TOutputJson = unknown> {\n readonly name: string;\n readonly messages: AgentMessageConfig<TInputJson>;\n readonly chatModel: ChatModelConfig;\n readonly tools?: ReadonlyArray<ToolConfig>;\n readonly id?: string;\n readonly retryPolicy?: RetryPolicySpec;\n readonly guardrails?: AgentGuardrailConfig;\n /** Engine applies with {@link RunnableNodeConfig.inputSchema} before {@link AIAgentNode.execute}. */\n readonly inputSchema?: ZodType<TInputJson>;\n readonly outputSchema?: ZodType<_TOutputJson>;\n}\n\n/**\n * AI agent: credential bindings are keyed to connection-owned LLM/tool node ids (ConnectionNodeIdFactory),\n * not to the agent workflow node id.\n */\nexport class AIAgent<TInputJson = unknown, TOutputJson = unknown>\n implements RunnableNodeConfig<TInputJson, TOutputJson>, AgentNodeConfig<TInputJson, TOutputJson>\n{\n readonly kind = \"node\" as const;\n readonly type: TypeToken<unknown> = AIAgentNode;\n readonly execution = { hint: \"local\" } as const;\n readonly icon = \"lucide:bot\" as const;\n readonly name: string;\n readonly messages: AgentMessageConfig<TInputJson>;\n readonly chatModel: ChatModelConfig;\n readonly tools: ReadonlyArray<ToolConfig>;\n readonly id?: string;\n readonly retryPolicy: RetryPolicySpec;\n readonly guardrails?: AgentGuardrailConfig;\n readonly inputSchema?: ZodType<TInputJson>;\n readonly outputSchema?: ZodType<TOutputJson>;\n\n constructor(options: AIAgentOptions<TInputJson, TOutputJson>) {\n this.name = options.name;\n this.messages = options.messages;\n this.chatModel = options.chatModel;\n this.tools = options.tools ?? [];\n this.id = options.id;\n this.retryPolicy = options.retryPolicy ?? RetryPolicy.defaultForAiAgent;\n this.guardrails = options.guardrails;\n this.inputSchema = options.inputSchema;\n this.outputSchema = options.outputSchema;\n }\n}\n","import type { AssertionResult, RunnableNode, RunnableNodeExecuteArgs } from \"@codemation/core\";\nimport { node } from \"@codemation/core\";\n\nimport { Assertion } from \"./assertion\";\n\n/**\n * Runs the author's `assertions` callback for each input item and emits one workflow `Item` per\n * returned {@link AssertionResult} on `main`. Persistence is handled by a host-side subscriber\n * to `nodeCompleted` events that filters on `config.emitsAssertions === true`; this node does\n * not write to any store on its own.\n *\n * If the author callback throws, we emit a single synthetic AssertionResult with `errored: true`\n * and `score: 0`. Without this catch the whole node would fail and no assertion row would be\n * persisted — making the rollup blind to \"the assertion code itself is broken.\" The synthetic\n * row keeps `failedAssertionsByRunId` consistent and gives the UI something to surface.\n */\n@node({ packageName: \"@codemation/core-nodes\" })\nexport class AssertionNode implements RunnableNode<Assertion<any>> {\n kind = \"node\" as const;\n outputPorts = [\"main\"] as const;\n\n async execute(args: RunnableNodeExecuteArgs<Assertion<any>>): Promise<unknown> {\n const ctx = args.ctx;\n const config = ctx.config;\n try {\n const results: ReadonlyArray<AssertionResult> = await config.assertions(args.item, ctx);\n // Engine \"array → fan-out on main, each element is item.json\" — returning the plain results\n // makes downstream `item.json` exactly an AssertionResult. Wrapping in `{ json: result }`\n // would double-wrap (engine would see `Item`-shaped values but treat them as JSON values).\n return [...results];\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n const erroredResult: AssertionResult = {\n name: config.name ?? \"assertion\",\n score: 0,\n errored: true,\n message,\n };\n return [erroredResult];\n }\n }\n}\n","import type { AssertionResult, Item, NodeExecutionContext, RunnableNodeConfig, TypeToken } from \"@codemation/core\";\n\nimport { AssertionNode } from \"./AssertionNode\";\n\nexport interface AssertionOptions<TInputJson> {\n readonly name?: string;\n readonly id?: string;\n readonly icon?: string;\n /**\n * Author callback. Returns one or more {@link AssertionResult}s per input item. Each becomes\n * one emitted output item — useful for per-row reporting in the Tests tab. Return `[]` to\n * emit nothing for this case (rare; usually you want at least a \"no-op\" pass).\n */\n assertions(\n item: Item<TInputJson>,\n ctx: NodeExecutionContext<Assertion<TInputJson>>,\n ): Promise<ReadonlyArray<AssertionResult>> | ReadonlyArray<AssertionResult>;\n}\n\n/**\n * Generic assertion node — the \"callback\" form. For declarative shorthands (StringEquals,\n * JudgeByAgent) compose this with helpers added in later phases. Sets `emitsAssertions: true`\n * so host-side persisters know to record its outputs as `TestAssertion` rows.\n */\nexport class Assertion<TInputJson = unknown> implements RunnableNodeConfig<TInputJson, AssertionResult> {\n readonly kind = \"node\" as const;\n readonly type: TypeToken<unknown> = AssertionNode;\n readonly icon: string;\n readonly name: string;\n readonly id?: string;\n readonly emitsAssertions = true as const;\n readonly assertions: AssertionOptions<TInputJson>[\"assertions\"];\n\n constructor(options: AssertionOptions<TInputJson>) {\n this.name = options.name ?? \"Assertion\";\n this.id = options.id;\n this.icon = options.icon ?? \"lucide:check-circle\";\n this.assertions = options.assertions;\n }\n}\n\nexport { AssertionNode } from \"./AssertionNode\";\n","import type { Items, PortsEmission } from \"@codemation/core\";\nimport { emitPorts, isPortsEmission } from \"@codemation/core\";\n\nexport class CallbackResultNormalizer {\n static toPortsEmission(result: Items | PortsEmission | void, items: Items): PortsEmission {\n if (isPortsEmission(result)) {\n return result;\n }\n return emitPorts({ main: result ?? items });\n }\n}\n","import type { RunnableNode, RunnableNodeExecuteArgs } from \"@codemation/core\";\nimport { node } from \"@codemation/core\";\n\nimport { Callback } from \"./CallbackNodeFactory\";\nimport { CallbackResultNormalizer } from \"./CallbackResultNormalizerFactory\";\n\n@node({ packageName: \"@codemation/core-nodes\" })\nexport class CallbackNode implements RunnableNode<Callback<any, any>> {\n kind = \"node\" as const;\n outputPorts = [\"main\"] as const;\n\n async execute(args: RunnableNodeExecuteArgs<Callback<any, any>>): Promise<unknown> {\n const items = args.items ?? [];\n const ctx = args.ctx;\n const config = ctx.config;\n if (config == null) {\n throw new Error(\"CallbackNode: missing ctx.config (engine should always pass runnable config)\");\n }\n if (items.length === 0) {\n const result = await config.callback(items, ctx);\n return CallbackResultNormalizer.toPortsEmission(result, items);\n }\n if (args.itemIndex !== items.length - 1) {\n return [];\n }\n const result = await config.callback(items, ctx);\n return CallbackResultNormalizer.toPortsEmission(result, items);\n }\n}\n","import type {\n Items,\n NodeExecutionContext,\n NodeErrorHandlerSpec,\n PortsEmission,\n RetryPolicySpec,\n RunnableNodeConfig,\n TypeToken,\n} from \"@codemation/core\";\n\nimport { CallbackNode } from \"./CallbackNode\";\n\nexport type CallbackHandler<\n TInputJson = unknown,\n TOutputJson = TInputJson,\n TConfig extends Callback<TInputJson, TOutputJson> = Callback<TInputJson, TOutputJson>,\n> = (\n items: Items<TInputJson>,\n ctx: NodeExecutionContext<TConfig>,\n) => Promise<Items<TOutputJson> | PortsEmission | void> | Items<TOutputJson> | PortsEmission | void;\n\nexport type CallbackOptions = Readonly<{\n id?: string;\n retryPolicy?: RetryPolicySpec;\n nodeErrorHandler?: NodeErrorHandlerSpec;\n declaredOutputPorts?: ReadonlyArray<string>;\n}>;\n\nexport class Callback<TInputJson = unknown, TOutputJson = TInputJson> implements RunnableNodeConfig<\n TInputJson,\n TOutputJson\n> {\n readonly kind = \"node\" as const;\n readonly type: TypeToken<unknown> = CallbackNode;\n readonly execution = { hint: \"local\" } as const;\n readonly icon = \"lucide:braces\" as const;\n readonly emptyBatchExecution = \"runOnce\" as const;\n readonly id?: string;\n readonly retryPolicy?: RetryPolicySpec;\n readonly nodeErrorHandler?: NodeErrorHandlerSpec;\n readonly declaredOutputPorts?: ReadonlyArray<string>;\n\n constructor(\n public readonly name: string = \"Callback\",\n public readonly callback: CallbackHandler<TInputJson, TOutputJson> = Callback.defaultCallback as CallbackHandler<\n TInputJson,\n TOutputJson\n >,\n idOrOptions?: string | CallbackOptions,\n options?: CallbackOptions,\n ) {\n const resolvedOptions = typeof idOrOptions === \"string\" ? { ...options, id: idOrOptions } : idOrOptions;\n this.id = resolvedOptions?.id;\n this.retryPolicy = resolvedOptions?.retryPolicy;\n this.nodeErrorHandler = resolvedOptions?.nodeErrorHandler;\n this.declaredOutputPorts = resolvedOptions?.declaredOutputPorts;\n }\n\n private static defaultCallback<TItemJson>(items: Items<TItemJson>): Items<TItemJson> {\n return items;\n }\n}\n\nexport { CallbackNode } from \"./CallbackNode\";\nexport { CallbackResultNormalizer } from \"./CallbackResultNormalizerFactory\";\n","import type { Item, NodeExecutionContext, RunnableNode, RunnableNodeExecuteArgs } from \"@codemation/core\";\n\nimport { node } from \"@codemation/core\";\nimport type { CredentialSession, HttpRequestSpec } from \"../http/httpRequest.types\";\nimport { HttpRequestExecutor } from \"../http/HttpRequestExecutor\";\nimport { HttpBodyBuilder } from \"../http/HttpBodyBuilder\";\nimport { HttpUrlBuilder } from \"../http/HttpUrlBuilder\";\nimport type { HttpRequestDownloadMode } from \"./httpRequest\";\nimport { HttpRequest } from \"./httpRequest\";\n\n@node({ packageName: \"@codemation/core-nodes\" })\nexport class HttpRequestNode implements RunnableNode<HttpRequest<any, any>> {\n readonly kind = \"node\" as const;\n readonly outputPorts = [\"main\"] as const;\n\n async execute(args: RunnableNodeExecuteArgs<HttpRequest<any, any>>): Promise<unknown> {\n return await this.executeItem(args.item, args.ctx);\n }\n\n private async executeItem(item: Item, ctx: NodeExecutionContext<HttpRequest<any, any>>): Promise<Item> {\n const url = this.resolveUrl(item, ctx);\n const credential = await this.resolveCredential(ctx);\n\n const spec: HttpRequestSpec = {\n url,\n method: ctx.config.method,\n headers: ctx.config.args.headers,\n query: ctx.config.args.query,\n body: ctx.config.args.body,\n credential,\n download: {\n mode: ctx.config.downloadMode,\n binaryName: ctx.config.binaryName,\n },\n ctx: ctx as unknown as HttpRequestSpec[\"ctx\"],\n };\n\n // Build the request (headers, body encoding, URL query merge) once,\n // then make a SINGLE fetch call and decide what to do with the response.\n // This avoids a double-fetch regression for auto-mode binary responses.\n const executor = new HttpRequestExecutor(globalThis.fetch, new HttpBodyBuilder(), new HttpUrlBuilder());\n const { url: resolvedUrl, init } = await executor.buildRequest(spec, item);\n\n const response = await globalThis.fetch(resolvedUrl, init);\n\n const headers = this.readHeaders(response.headers);\n const mimeType = this.resolveMimeType(headers);\n const binaryName = ctx.config.binaryName;\n const shouldAttach = this.shouldAttachBody(ctx.config.downloadMode, mimeType);\n\n if (shouldAttach) {\n const outputJson: Readonly<Record<string, unknown>> = {\n url: resolvedUrl,\n method: ctx.config.method,\n ok: response.ok,\n status: response.status,\n statusText: response.statusText,\n mimeType,\n headers,\n bodyBinaryName: binaryName,\n };\n\n const attachment = await ctx.binary.attach({\n name: binaryName,\n body: response.body\n ? (response.body as unknown as Parameters<typeof ctx.binary.attach>[0][\"body\"])\n : new Uint8Array(await response.arrayBuffer()),\n mimeType,\n filename: this.resolveFilename(resolvedUrl, headers),\n });\n\n let outputItem: Item = { json: outputJson };\n outputItem = ctx.binary.withAttachment(outputItem, binaryName, attachment);\n return outputItem;\n }\n\n // Non-binary path: parse JSON or read text.\n const isJson = this.isJsonMimeType(mimeType);\n let json: unknown | undefined;\n let text: string | undefined;\n\n if (isJson) {\n try {\n json = await response.json();\n } catch {\n text = await response.text();\n }\n } else {\n text = await response.text();\n }\n\n const outputJson: Readonly<Record<string, unknown>> = {\n url: resolvedUrl,\n method: ctx.config.method,\n ok: response.ok,\n status: response.status,\n statusText: response.statusText,\n mimeType,\n headers,\n ...(json !== undefined ? { json } : {}),\n ...(text !== undefined ? { text } : {}),\n };\n\n return { json: outputJson };\n }\n\n private async resolveCredential(\n ctx: NodeExecutionContext<HttpRequest<any, any>>,\n ): Promise<CredentialSession | undefined> {\n const slotKey = ctx.config.args.credentialSlot;\n if (!slotKey) {\n return undefined;\n }\n try {\n return await ctx.getCredential<CredentialSession>(slotKey);\n } catch {\n // Credential slot configured but not bound — treat as no credential.\n return undefined;\n }\n }\n\n private resolveUrl(item: Item, ctx: NodeExecutionContext<HttpRequest<any, any>>): string {\n // Literal URL in args takes precedence over the legacy urlField approach.\n const literalUrl = ctx.config.args.url;\n if (literalUrl && literalUrl.trim().length > 0) {\n return literalUrl.trim();\n }\n\n const json = this.asRecord(item.json);\n const candidate = json[ctx.config.urlField];\n if (typeof candidate !== \"string\" || candidate.trim() === \"\") {\n throw new Error(`HttpRequest node expected item.json.${ctx.config.urlField} to contain a URL string.`);\n }\n return candidate;\n }\n\n private asRecord(value: unknown): Readonly<Record<string, unknown>> {\n if (value && typeof value === \"object\" && !Array.isArray(value)) {\n return value as Readonly<Record<string, unknown>>;\n }\n return { input: value };\n }\n\n private readHeaders(headers: Headers): Readonly<Record<string, string>> {\n const values: Record<string, string> = {};\n headers.forEach((value, key) => {\n values[key] = value;\n });\n return values;\n }\n\n private resolveMimeType(headers: Readonly<Record<string, string>>): string {\n const contentType = headers[\"content-type\"];\n if (!contentType) {\n return \"application/octet-stream\";\n }\n return contentType.split(\";\")[0]?.trim() || \"application/octet-stream\";\n }\n\n private isJsonMimeType(mimeType: string): boolean {\n return mimeType === \"application/json\" || mimeType.endsWith(\"+json\");\n }\n\n private shouldAttachBody(mode: HttpRequestDownloadMode, mimeType: string): boolean {\n if (mode === \"always\") {\n return true;\n }\n if (mode === \"never\") {\n return false;\n }\n return mimeType.startsWith(\"image/\") || mimeType.startsWith(\"audio/\") || mimeType.startsWith(\"video/\");\n }\n\n private resolveFilename(url: string, headers: Readonly<Record<string, string>>): string | undefined {\n const contentDisposition = headers[\"content-disposition\"];\n const fromDisposition = this.readFilenameFromContentDisposition(contentDisposition);\n if (fromDisposition) {\n return fromDisposition;\n }\n const pathname = new URL(url).pathname;\n const value = pathname.split(\"/\").at(-1);\n return value && value.trim() ? value : undefined;\n }\n\n private readFilenameFromContentDisposition(value: string | undefined): string | undefined {\n if (!value) {\n return undefined;\n }\n const parts = value.split(\";\");\n for (const part of parts) {\n const trimmed = part.trim();\n if (!trimmed.startsWith(\"filename=\")) {\n continue;\n }\n return trimmed.slice(\"filename=\".length).replace(/^\"|\"$/g, \"\");\n }\n return undefined;\n }\n}\n","import {\n RetryPolicy,\n type CredentialRequirement,\n type RetryPolicySpec,\n type RunnableNodeConfig,\n type TypeToken,\n} from \"@codemation/core\";\n\nimport type { HttpBodySpec } from \"../http/httpRequest.types\";\nimport {\n apiKeyCredentialType,\n basicAuthCredentialType,\n bearerTokenCredentialType,\n oauth2ClientCredentialsType,\n} from \"../credentials/index\";\nimport { HttpRequestNode } from \"./HttpRequestNodeFactory\";\n\nexport type HttpRequestDownloadMode = \"auto\" | \"always\" | \"never\";\n\n/** JSON emitted by {@link HttpRequest} — response metadata only (input item fields are not passed through). */\nexport type HttpRequestOutputJson = Readonly<{\n url: string;\n method: string;\n ok: boolean;\n status: number;\n statusText: string;\n mimeType: string;\n headers: Readonly<Record<string, string>>;\n json?: unknown;\n text?: string;\n bodyBinaryName?: string;\n}>;\n\n/**\n * The built-in HTTP request credential type IDs accepted by the `HttpRequest` node.\n * These match the four generic credential types shipped with `@codemation/core-nodes`.\n */\nexport const HTTP_REQUEST_ACCEPTED_CREDENTIAL_TYPES: ReadonlyArray<string> = [\n bearerTokenCredentialType.definition.typeId,\n apiKeyCredentialType.definition.typeId,\n basicAuthCredentialType.definition.typeId,\n oauth2ClientCredentialsType.definition.typeId,\n] as const;\n\nexport class HttpRequest<\n TInputJson = Readonly<{ url?: string }>,\n TOutputJson = HttpRequestOutputJson,\n> implements RunnableNodeConfig<TInputJson, TOutputJson> {\n readonly kind = \"node\" as const;\n readonly type: TypeToken<unknown> = HttpRequestNode;\n readonly execution = { hint: \"local\" } as const;\n readonly icon = \"lucide:globe\" as const;\n\n constructor(\n public readonly name: string,\n public readonly args: Readonly<{\n /** HTTP method (default: GET). */\n method?: string;\n /**\n * Legacy: field name on item.json to read the URL from.\n * Use `url` for a literal/templated URL instead.\n */\n urlField?: string;\n /** Literal or templated URL. When present, takes precedence over `urlField`. */\n url?: string;\n /** Extra headers to add to every request. */\n headers?: Readonly<Record<string, string>>;\n /** Query parameters to append to the URL. */\n query?: Readonly<Record<string, string>>;\n /** Request body specification. For canvas use, pass a JSON string in `body.data`. */\n body?: HttpBodySpec;\n /**\n * Credential slot key. When set, the node resolves a credential via\n * `ctx.getCredential(credentialSlot)` and applies it to the request.\n * The slot must be declared in `getCredentialRequirements()`.\n */\n credentialSlot?: string;\n binaryName?: string;\n downloadMode?: HttpRequestDownloadMode;\n id?: string;\n }> = {},\n public readonly retryPolicy: RetryPolicySpec = RetryPolicy.defaultForHttp,\n ) {}\n\n get id(): string | undefined {\n return this.args.id;\n }\n\n get method(): string {\n return (this.args.method ?? \"GET\").toUpperCase();\n }\n\n get urlField(): string {\n return this.args.urlField ?? \"url\";\n }\n\n get binaryName(): string {\n return this.args.binaryName ?? \"body\";\n }\n\n get downloadMode(): HttpRequestDownloadMode {\n return this.args.downloadMode ?? \"auto\";\n }\n\n getCredentialRequirements(): ReadonlyArray<CredentialRequirement> {\n if (!this.args.credentialSlot) {\n return [];\n }\n return [\n {\n slotKey: this.args.credentialSlot,\n label: \"Authentication\",\n acceptedTypes: HTTP_REQUEST_ACCEPTED_CREDENTIAL_TYPES,\n optional: true,\n helpText: \"Optional credential for authenticating the HTTP request.\",\n },\n ];\n }\n}\n\nexport { HttpRequestNode } from \"./HttpRequestNodeFactory\";\n","import type { RunnableNode, RunnableNodeExecuteArgs } from \"@codemation/core\";\n\nimport { node } from \"@codemation/core\";\n\nimport type { Aggregate } from \"./aggregate\";\n\n@node({ packageName: \"@codemation/core-nodes\" })\nexport class AggregateNode implements RunnableNode<Aggregate<any, any>> {\n kind = \"node\" as const;\n outputPorts = [\"main\"] as const;\n\n async execute(args: RunnableNodeExecuteArgs<Aggregate<any, any>>): Promise<unknown> {\n if (args.itemIndex !== args.items.length - 1) {\n return [];\n }\n return Promise.resolve(args.ctx.config.aggregate(args.items, args.ctx));\n }\n}\n","import type { Items, NodeExecutionContext, RunnableNodeConfig, TypeToken } from \"@codemation/core\";\n\nimport { AggregateNode } from \"./AggregateNode\";\n\nexport class Aggregate<TIn = unknown, TOut = unknown> implements RunnableNodeConfig<TIn, TOut> {\n readonly kind = \"node\" as const;\n readonly type: TypeToken<unknown> = AggregateNode;\n readonly execution = { hint: \"local\" } as const;\n readonly keepBinaries = true as const;\n readonly icon = \"builtin:aggregate-rows\" as const;\n\n constructor(\n public readonly name: string,\n public readonly aggregate: (\n items: Items<TIn>,\n ctx: NodeExecutionContext<Aggregate<TIn, TOut>>,\n ) => TOut | Promise<TOut>,\n public readonly id?: string,\n ) {}\n}\n\nexport { AggregateNode } from \"./AggregateNode\";\n","import type { Item, RunnableNode, RunnableNodeExecuteArgs } from \"@codemation/core\";\n\nimport { node } from \"@codemation/core\";\n\nimport type { Filter } from \"./filter\";\n\n@node({ packageName: \"@codemation/core-nodes\" })\nexport class FilterNode implements RunnableNode<Filter<any>> {\n kind = \"node\" as const;\n outputPorts = [\"main\"] as const;\n\n execute(args: RunnableNodeExecuteArgs<Filter<any>>): unknown {\n if (args.ctx.config.predicate(args.item as Item, args.itemIndex, args.items, args.ctx)) {\n return args.item;\n }\n return [];\n }\n}\n","import type { Item, Items, NodeExecutionContext, RunnableNodeConfig, TypeToken } from \"@codemation/core\";\n\nimport { FilterNode } from \"./FilterNode\";\n\nexport class Filter<TIn = unknown> implements RunnableNodeConfig<TIn, TIn> {\n readonly kind = \"node\" as const;\n readonly type: TypeToken<unknown> = FilterNode;\n readonly execution = { hint: \"local\" } as const;\n readonly icon = \"lucide:filter\" as const;\n\n constructor(\n public readonly name: string,\n public readonly predicate: (\n item: Item<TIn>,\n index: number,\n items: Items<TIn>,\n ctx: NodeExecutionContext<Filter<TIn>>,\n ) => boolean,\n public readonly id?: string,\n ) {}\n}\n\nexport { FilterNode } from \"./FilterNode\";\n","import type { InputPortKey, Item, Items, NodeId } from \"@codemation/core\";\nimport { getOriginIndexFromItem } from \"@codemation/core\";\n\nexport function getOriginIndex(item: Item): number | undefined {\n return getOriginIndexFromItem(item);\n}\n\n/**\n * Tags items routed to fan-in merge-by-origin (same contract as {@link IfNode} / {@link SwitchNode}).\n */\nexport function tagItemForRouterFanIn<TJson>(\n args: Readonly<{\n item: Item<TJson>;\n itemIndex: number;\n nodeId: NodeId;\n inputPortLabel?: string;\n }>,\n): Item<TJson> {\n const { item, itemIndex, nodeId, inputPortLabel = \"$in\" } = args;\n const metaBase = (item.meta && typeof item.meta === \"object\" ? (item.meta as Record<string, unknown>) : {}) as Record<\n string,\n unknown\n >;\n const cmBase =\n metaBase._cm && typeof metaBase._cm === \"object\"\n ? (metaBase._cm as Record<string, unknown>)\n : ({} as Record<string, unknown>);\n const originIndex = typeof cmBase.originIndex === \"number\" ? (cmBase.originIndex as number) : itemIndex;\n return {\n ...item,\n meta: { ...metaBase, _cm: { ...cmBase, originIndex } },\n paired: [{ nodeId, output: inputPortLabel, itemIndex: originIndex }, ...(item.paired ?? [])],\n };\n}\n\nexport function orderedInputs(\n inputsByPort: Readonly<Record<InputPortKey, Items>>,\n prefer?: ReadonlyArray<InputPortKey>,\n): InputPortKey[] {\n const keys = Object.keys(inputsByPort);\n const preferred = (prefer ?? []).filter((k) => keys.includes(k));\n const rest = keys.filter((k) => !preferred.includes(k)).sort();\n return [...preferred, ...rest];\n}\n","import type { RunnableNode, RunnableNodeExecuteArgs } from \"@codemation/core\";\nimport { emitPorts, node } from \"@codemation/core\";\n\nimport { If } from \"./if\";\nimport { tagItemForRouterFanIn } from \"./mergeExecutionUtils.types\";\n\n@node({ packageName: \"@codemation/core-nodes\" })\nexport class IfNode implements RunnableNode<If<any>> {\n kind = \"node\" as const;\n\n execute(args: RunnableNodeExecuteArgs<If<any>>): unknown {\n const tagged = tagItemForRouterFanIn({\n item: args.item,\n itemIndex: args.itemIndex,\n nodeId: args.ctx.nodeId,\n });\n const ok = args.ctx.config.predicate(args.item, args.itemIndex, args.items, args.ctx);\n return emitPorts({\n true: ok ? [tagged] : [],\n false: ok ? [] : [tagged],\n });\n }\n}\n","import type { Item, Items, NodeExecutionContext, RunnableNodeConfig, TypeToken } from \"@codemation/core\";\n\nimport { IfNode } from \"./IfNode\";\n\nexport class If<TInputJson = unknown> implements RunnableNodeConfig<TInputJson, TInputJson> {\n readonly kind = \"node\" as const;\n readonly type: TypeToken<unknown> = IfNode;\n readonly execution = { hint: \"local\" } as const;\n readonly icon = \"lucide:split@rot=90\" as const;\n readonly declaredOutputPorts = [\"true\", \"false\"] as const;\n constructor(\n public readonly name: string,\n public readonly predicate: (\n item: Item<TInputJson>,\n index: number,\n items: Items<TInputJson>,\n ctx: NodeExecutionContext<If<TInputJson>>,\n ) => boolean,\n public readonly id?: string,\n ) {}\n}\n\nexport { IfNode } from \"./IfNode\";\n","import type { RunnableNode, RunnableNodeExecuteArgs } from \"@codemation/core\";\nimport { emitPorts, node } from \"@codemation/core\";\n\nimport { IsTestRun } from \"./isTestRun\";\n\n/**\n * Routes each item to the `true` port if `ctx.testContext` is set (the run was started by the\n * TestSuiteOrchestrator), else to `false`. Lets workflow authors guard real side-effects:\n *\n * GmailTrigger / TestTrigger → ClassifyAgent → IsTestRun\n * ├── true → AssertionNode\n * └── false → SendReply\n */\n@node({ packageName: \"@codemation/core-nodes\" })\nexport class IsTestRunNode implements RunnableNode<IsTestRun<unknown>> {\n kind = \"node\" as const;\n\n execute(args: RunnableNodeExecuteArgs<IsTestRun<unknown>>): unknown {\n const isTest = args.ctx.testContext !== undefined;\n return emitPorts({\n true: isTest ? [args.item] : [],\n false: isTest ? [] : [args.item],\n });\n }\n}\n","import type { RunnableNodeConfig, TypeToken } from \"@codemation/core\";\n\nimport { IsTestRunNode } from \"./IsTestRunNode\";\n\n/**\n * Branches per-item on whether the current run is a test run. Output ports: `true`, `false`.\n * The wire payload is unchanged — this is a router, not a transform.\n */\nexport class IsTestRun<TInputJson = unknown> implements RunnableNodeConfig<TInputJson, TInputJson> {\n readonly kind = \"node\" as const;\n readonly type: TypeToken<unknown> = IsTestRunNode;\n readonly execution = { hint: \"local\" } as const;\n readonly icon = \"lucide:flask-conical\" as const;\n readonly declaredOutputPorts = [\"true\", \"false\"] as const;\n readonly name: string;\n readonly id?: string;\n\n constructor(name: string = \"Is test run?\", id?: string) {\n this.name = name;\n this.id = id;\n }\n}\n\nexport { IsTestRunNode } from \"./IsTestRunNode\";\n","import type { RunnableNode, RunnableNodeExecuteArgs } from \"@codemation/core\";\nimport { emitPorts, node } from \"@codemation/core\";\n\nimport type { Switch } from \"./switch\";\nimport { tagItemForRouterFanIn } from \"./mergeExecutionUtils.types\";\n\n/**\n * Routes each item to exactly one output port. Port names must match workflow edges (see {@link Switch} config).\n */\n@node({ packageName: \"@codemation/core-nodes\" })\nexport class SwitchNode implements RunnableNode<Switch<any>> {\n kind = \"node\" as const;\n\n async execute(args: RunnableNodeExecuteArgs<Switch<any>>): Promise<unknown> {\n const tagged = tagItemForRouterFanIn({\n item: args.item,\n itemIndex: args.itemIndex,\n nodeId: args.ctx.nodeId,\n });\n const key = await Promise.resolve(\n args.ctx.config.cfg.resolveCaseKey(args.item, args.itemIndex, args.items, args.ctx),\n );\n const { cases, defaultCase } = args.ctx.config.cfg;\n const port = cases.includes(key) ? key : defaultCase;\n return emitPorts({\n [port]: [tagged],\n });\n }\n}\n","import type { Item, Items, NodeExecutionContext, RunnableNodeConfig, TypeToken } from \"@codemation/core\";\n\nimport { SwitchNode } from \"./SwitchNode\";\n\nexport type SwitchCaseKeyResolver<TInputJson = unknown> = (\n item: Item<TInputJson>,\n index: number,\n items: Items<TInputJson>,\n ctx: NodeExecutionContext<Switch<TInputJson>>,\n) => string | Promise<string>;\n\nexport class Switch<TInputJson = unknown> implements RunnableNodeConfig<TInputJson, TInputJson> {\n readonly kind = \"node\" as const;\n readonly type: TypeToken<unknown> = SwitchNode;\n readonly execution = { hint: \"local\" } as const;\n readonly icon = \"lucide:git-branch-plus\" as const;\n readonly declaredOutputPorts: ReadonlyArray<string>;\n\n constructor(\n public readonly name: string,\n public readonly cfg: Readonly<{\n cases: readonly string[];\n defaultCase: string;\n resolveCaseKey: SwitchCaseKeyResolver<TInputJson>;\n }>,\n public readonly id?: string,\n ) {\n this.declaredOutputPorts = [...new Set([...cfg.cases, cfg.defaultCase])].sort();\n }\n}\n\nexport { SwitchNode } from \"./SwitchNode\";\n","import type { Item, RunnableNode, RunnableNodeExecuteArgs } from \"@codemation/core\";\n\nimport { node } from \"@codemation/core\";\n\nimport type { Split } from \"./split\";\n\n@node({ packageName: \"@codemation/core-nodes\" })\nexport class SplitNode implements RunnableNode<Split<any, any>> {\n kind = \"node\" as const;\n outputPorts = [\"main\"] as const;\n\n execute(args: RunnableNodeExecuteArgs<Split<any, any>>): unknown {\n const elements = args.ctx.config.getElements(args.item as Item, args.ctx);\n return elements;\n }\n}\n","import type { Item, NodeExecutionContext, RunnableNodeConfig, TypeToken } from \"@codemation/core\";\n\nimport { SplitNode } from \"./SplitNode\";\n\nexport class Split<TIn = unknown, TElem = unknown> implements RunnableNodeConfig<TIn, TElem> {\n readonly kind = \"node\" as const;\n readonly type: TypeToken<unknown> = SplitNode;\n readonly execution = { hint: \"local\" } as const;\n readonly keepBinaries = true as const;\n /**\n * When splitting yields zero items for a batch, downstream single-input nodes still run once with an empty batch.\n * Mirrors {@link MapData}'s empty-output behavior.\n */\n readonly continueWhenEmptyOutput = true as const;\n readonly icon = \"builtin:split-rows\" as const;\n\n constructor(\n public readonly name: string,\n public readonly getElements: (item: Item<TIn>, ctx: NodeExecutionContext<Split<TIn, TElem>>) => readonly TElem[],\n public readonly id?: string,\n ) {}\n}\n\nexport { SplitNode } from \"./SplitNode\";\n","import type {\n Items,\n NodeExecutionContext,\n NodeOutputs,\n TestableTriggerNode,\n TriggerSetupContext,\n TriggerTestItemsContext,\n} from \"@codemation/core\";\n\nimport { node } from \"@codemation/core\";\n\nimport { CronTrigger } from \"./CronTriggerFactory\";\n\n@node({ packageName: \"@codemation/core-nodes\" })\nexport class CronTriggerNode implements TestableTriggerNode<CronTrigger> {\n readonly kind = \"trigger\" as const;\n readonly outputPorts = [\"main\"] as const;\n\n async setup(ctx: TriggerSetupContext<CronTrigger>): Promise<undefined> {\n const job = ctx.config.createJob(async (self) => {\n const scheduledFor = self.currentRun()?.toISOString() ?? ctx.now().toISOString();\n await ctx.emit([{ json: { firedAt: ctx.now().toISOString(), scheduledFor } }]);\n });\n ctx.registerCleanup({\n stop: () => {\n job.stop();\n },\n });\n return undefined;\n }\n\n async execute(items: Items, _ctx: NodeExecutionContext<CronTrigger>): Promise<NodeOutputs> {\n return { main: items };\n }\n\n async getTestItems(ctx: TriggerTestItemsContext<CronTrigger>): Promise<Items> {\n const nowIso = ctx.now().toISOString();\n return [{ json: { firedAt: nowIso, scheduledFor: nowIso } }];\n }\n}\n","import type { TriggerNodeConfig, TypeToken } from \"@codemation/core\";\n\nimport { Cron } from \"croner\";\nimport type { CronCallback } from \"croner\";\n\nimport { CronTriggerNode } from \"./CronTriggerNode\";\n\nexport type CronTickJson = { firedAt: string; scheduledFor: string };\n\n/**\n * Schedules a workflow on a standard cron expression.\n *\n * Each tick emits one item: `{ firedAt: string, scheduledFor: string }` — both ISO-8601 timestamps.\n * `firedAt` is the wall-clock moment the callback ran; `scheduledFor` is the cron-computed\n * firing instant (these differ when the job was delayed).\n *\n * Timezone defaults to UTC when omitted — cron without an explicit TZ is a DST footgun.\n */\nexport class CronTrigger implements TriggerNodeConfig<CronTickJson> {\n readonly kind = \"trigger\" as const;\n readonly type: TypeToken<unknown> = CronTriggerNode;\n readonly icon = \"lucide:clock\" as const;\n readonly id?: string;\n\n constructor(\n public readonly name: string,\n private readonly args: Readonly<{ schedule: string; timezone?: string }>,\n id?: string,\n ) {\n new Cron(args.schedule, { paused: true, timezone: args.timezone });\n this.id = id;\n }\n\n get schedule(): string {\n return this.args.schedule;\n }\n\n get timezone(): string | undefined {\n return this.args.timezone;\n }\n\n createJob(callback: CronCallback): Cron {\n return new Cron(this.args.schedule, { timezone: this.args.timezone, protect: true }, callback);\n }\n}\n","import type {\n Items,\n NodeExecutionContext,\n NodeOutputs,\n TestableTriggerNode,\n TriggerSetupContext,\n TriggerTestItemsContext,\n} from \"@codemation/core\";\n\nimport { node } from \"@codemation/core\";\n\nimport { ManualTrigger } from \"./ManualTriggerFactory\";\n\n/**\n * Setup is intentionally a no-op: the engine host can run workflows manually\n * by calling `engine.runWorkflow(workflow, triggerNodeId, items)`.\n */\n@node({ packageName: \"@codemation/core-nodes\" })\nexport class ManualTriggerNode implements TestableTriggerNode<ManualTrigger<any>> {\n kind = \"trigger\" as const;\n outputPorts = [\"main\"] as const;\n async setup(_ctx: TriggerSetupContext<ManualTrigger<any>>): Promise<undefined> {\n return undefined;\n }\n\n async getTestItems(ctx: TriggerTestItemsContext<ManualTrigger<any>>): Promise<Items> {\n return this.resolveManualItems([], ctx.config);\n }\n\n async execute(items: Items, ctx: NodeExecutionContext<ManualTrigger<any>>): Promise<NodeOutputs> {\n return { main: this.resolveManualItems(items, ctx.config) };\n }\n\n private resolveManualItems(items: Items, config: ManualTrigger<any>): Items {\n return items.length > 0 ? items : (config.defaultItems ?? []);\n }\n}\n","import type { Items, TriggerNodeConfig, TypeToken } from \"@codemation/core\";\n\nimport { ItemsInputNormalizer } from \"@codemation/core\";\n\nimport { ManualTriggerNode } from \"./ManualTriggerNode\";\n\ntype ManualTriggerDefaultValue<TOutputJson> = Items<TOutputJson> | ReadonlyArray<TOutputJson> | TOutputJson;\n\nexport class ManualTrigger<TOutputJson = unknown> implements TriggerNodeConfig<TOutputJson> {\n private static readonly itemsInputNormalizer = new ItemsInputNormalizer();\n readonly kind = \"trigger\" as const;\n readonly type: TypeToken<unknown> = ManualTriggerNode;\n readonly icon = \"lucide:play\" as const;\n readonly defaultItems?: Items<TOutputJson>;\n readonly id?: string;\n /** Manual runs often emit an empty batch; still schedule downstream by default. */\n readonly continueWhenEmptyOutput = true as const;\n\n constructor(name?: string, id?: string);\n constructor(name: string, defaultItems: ManualTriggerDefaultValue<TOutputJson>, id?: string);\n constructor(\n public readonly name: string = \"Manual trigger\",\n defaultItemsOrId?: ManualTriggerDefaultValue<TOutputJson> | string,\n id?: string,\n ) {\n this.defaultItems = ManualTrigger.resolveDefaultItems(defaultItemsOrId);\n this.id = ManualTrigger.resolveId(defaultItemsOrId, id);\n }\n\n private static resolveDefaultItems<TOutputJson>(\n value: ManualTriggerDefaultValue<TOutputJson> | string | undefined,\n ): Items<TOutputJson> | undefined {\n if (typeof value === \"string\" || value === undefined) {\n return undefined;\n }\n return this.itemsInputNormalizer.normalize(value) as Items<TOutputJson>;\n }\n\n private static resolveId<TOutputJson>(\n value: ManualTriggerDefaultValue<TOutputJson> | string | undefined,\n id: string | undefined,\n ): string | undefined {\n return typeof value === \"string\" ? value : id;\n }\n}\n\nexport { ManualTriggerNode } from \"./ManualTriggerNode\";\n","import type { RunnableNode, RunnableNodeExecuteArgs } from \"@codemation/core\";\n\nimport { node } from \"@codemation/core\";\nimport { z } from \"zod\";\n\nimport { MapData } from \"./mapData\";\n\n@node({ packageName: \"@codemation/core-nodes\" })\nexport class MapDataNode implements RunnableNode<MapData<any, any>> {\n kind = \"node\" as const;\n outputPorts = [\"main\"] as const;\n readonly inputSchema = z.unknown();\n\n async execute(args: RunnableNodeExecuteArgs<MapData<any, any>>): Promise<unknown> {\n return args.ctx.config.map(args.item, args.ctx);\n }\n}\n","import type { Item, NodeExecutionContext, RunnableNodeConfig, TypeToken } from \"@codemation/core\";\n\nimport { MapDataNode } from \"./MapDataNode\";\n\nexport interface MapDataOptions {\n readonly id?: string;\n readonly keepBinaries?: boolean;\n}\n\nexport class MapData<TInputJson = unknown, TOutputJson = unknown> implements RunnableNodeConfig<\n TInputJson,\n TOutputJson\n> {\n readonly kind = \"node\" as const;\n readonly type: TypeToken<unknown> = MapDataNode;\n readonly execution = { hint: \"local\" } as const;\n /** Zero mapped items should still allow downstream nodes to run. */\n readonly continueWhenEmptyOutput = true as const;\n readonly icon = \"lucide:square-pen\" as const;\n readonly keepBinaries: boolean;\n\n constructor(\n public readonly name: string,\n public readonly map: (\n item: Item<TInputJson>,\n ctx: NodeExecutionContext<MapData<TInputJson, TOutputJson>>,\n ) => TOutputJson,\n private readonly options: MapDataOptions = {},\n ) {\n this.keepBinaries = options.keepBinaries ?? true;\n }\n\n get id(): string | undefined {\n return this.options.id;\n }\n}\n\nexport { MapDataNode } from \"./MapDataNode\";\n","import type { InputPortKey, Item, Items, MultiInputNode, NodeExecutionContext, NodeOutputs } from \"@codemation/core\";\n\nimport { node } from \"@codemation/core\";\n\nimport type { Merge } from \"./merge\";\nimport { getOriginIndex, orderedInputs } from \"./mergeExecutionUtils.types\";\n\n@node({ packageName: \"@codemation/core-nodes\" })\nexport class MergeNode implements MultiInputNode<Merge<any, any>> {\n kind = \"node\" as const;\n outputPorts = [\"main\"] as const;\n\n async executeMulti(\n inputsByPort: Readonly<Record<InputPortKey, Items>>,\n ctx: NodeExecutionContext<Merge<any, any>>,\n ): Promise<NodeOutputs> {\n const order = orderedInputs(inputsByPort, ctx.config.cfg.prefer);\n\n if (ctx.config.cfg.mode === \"append\") {\n const out: Item[] = [];\n for (const k of order) out.push(...(inputsByPort[k] ?? []));\n return { main: out };\n }\n\n if (ctx.config.cfg.mode === \"mergeByPosition\") {\n let maxLen = 0;\n for (const k of order) maxLen = Math.max(maxLen, (inputsByPort[k] ?? []).length);\n\n const out: Item[] = [];\n for (let i = 0; i < maxLen; i++) {\n const json: Record<string, unknown> = {};\n const paired: any[] = [];\n let meta: Record<string, unknown> | undefined;\n\n for (const k of order) {\n const item = (inputsByPort[k] ?? [])[i];\n json[k] = item?.json;\n if (item?.paired) paired.push(...item.paired);\n if (!meta && item?.meta) meta = { ...(item.meta as any) };\n }\n\n const merged: any = { json };\n if (paired.length > 0) merged.paired = paired;\n if (meta) merged.meta = meta;\n out.push(merged as Item);\n }\n\n return { main: out };\n }\n\n // passThrough (default): for each origin index, take first available input (deterministic input precedence).\n const chosenByOrigin = new Map<number, Item>();\n const fallback: Item[] = [];\n\n for (const k of order) {\n for (const item of inputsByPort[k] ?? []) {\n const origin = getOriginIndex(item);\n if (origin === undefined) {\n fallback.push(item);\n continue;\n }\n if (!chosenByOrigin.has(origin)) chosenByOrigin.set(origin, item);\n }\n }\n\n const out: Item[] = [];\n const origins = Array.from(chosenByOrigin.keys()).sort((a, b) => a - b);\n for (const o of origins) out.push(chosenByOrigin.get(o)!);\n out.push(...fallback);\n\n return { main: out };\n }\n}\n","import type { InputPortKey, RunnableNodeConfig, TypeToken } from \"@codemation/core\";\n\nimport { MergeNode } from \"./MergeNode\";\n\nexport type MergeMode = \"passThrough\" | \"append\" | \"mergeByPosition\";\n\nexport class Merge<TInputJson = unknown, TOutputJson = TInputJson> implements RunnableNodeConfig<\n TInputJson,\n TOutputJson\n> {\n readonly kind = \"node\" as const;\n readonly type: TypeToken<unknown> = MergeNode;\n readonly icon = \"lucide:merge@rot=90\" as const;\n\n constructor(\n public readonly name: string,\n public readonly cfg: Readonly<{\n mode: MergeMode;\n /**\n * Deterministic input precedence order (only used for passThrough/append).\n * Any inputs not listed are appended in lexicographic order.\n */\n prefer?: ReadonlyArray<InputPortKey>;\n }> = { mode: \"passThrough\" },\n public readonly id?: string,\n ) {}\n}\n\nexport { MergeNode } from \"./MergeNode\";\n","import type { RunnableNode, RunnableNodeExecuteArgs } from \"@codemation/core\";\n\nimport { node } from \"@codemation/core\";\n\nimport { NoOp } from \"./noOp\";\n\n@node({ packageName: \"@codemation/core-nodes\" })\nexport class NoOpNode implements RunnableNode<NoOp<any>> {\n kind = \"node\" as const;\n outputPorts = [\"main\"] as const;\n\n execute(args: RunnableNodeExecuteArgs<NoOp<any>>): unknown {\n return args.item;\n }\n}\n","import type { RunnableNodeConfig, TypeToken } from \"@codemation/core\";\n\nimport { NoOpNode } from \"./NoOpNode\";\n\nexport class NoOp<TItemJson = unknown> implements RunnableNodeConfig<TItemJson, TItemJson> {\n readonly kind = \"node\" as const;\n readonly type: TypeToken<unknown> = NoOpNode;\n readonly execution = { hint: \"local\" } as const;\n readonly icon = \"lucide:circle-dashed\" as const;\n\n constructor(\n public readonly name: string = \"NoOp\",\n public readonly id?: string,\n ) {}\n}\n\nexport { NoOpNode } from \"./NoOpNode\";\n","import type { Item, RunnableNode, RunnableNodeExecuteArgs, WorkflowRunnerService } from \"@codemation/core\";\nimport { CoreTokens, emitPorts, inject, node } from \"@codemation/core\";\n\nimport { SubWorkflow } from \"./subWorkflow\";\n\n@node({ packageName: \"@codemation/core-nodes\" })\nexport class SubWorkflowNode implements RunnableNode<SubWorkflow<any, any>> {\n kind = \"node\" as const;\n outputPorts = [\"main\"] as const;\n\n constructor(\n @inject(CoreTokens.WorkflowRunnerService)\n private readonly workflows: WorkflowRunnerService,\n ) {}\n\n async execute(args: RunnableNodeExecuteArgs<SubWorkflow<any, any>>): Promise<unknown> {\n const current = args.item as Item;\n const metaBase = (\n current.meta && typeof current.meta === \"object\" ? (current.meta as Record<string, unknown>) : {}\n ) as Record<string, unknown>;\n const cmBase =\n metaBase._cm && typeof metaBase._cm === \"object\"\n ? (metaBase._cm as Record<string, unknown>)\n : ({} as Record<string, unknown>);\n const originIndex = typeof cmBase.originIndex === \"number\" ? (cmBase.originIndex as number) : undefined;\n\n const result = await this.workflows.runById({\n workflowId: args.ctx.config.workflowId,\n startAt: args.ctx.config.startAt,\n items: [current],\n parent: {\n runId: args.ctx.runId,\n workflowId: args.ctx.workflowId,\n nodeId: args.ctx.nodeId,\n subworkflowDepth: args.ctx.subworkflowDepth,\n engineMaxNodeActivations: args.ctx.engineMaxNodeActivations,\n engineMaxSubworkflowDepth: args.ctx.engineMaxSubworkflowDepth,\n },\n });\n if (result.status !== \"completed\") {\n throw new Error(`Subworkflow ${args.ctx.config.workflowId} did not complete (status=${result.status})`);\n }\n const out: Item[] = [];\n for (const produced of result.outputs) {\n const childMetaBase =\n produced.meta && typeof produced.meta === \"object\"\n ? (produced.meta as Record<string, unknown>)\n : ({} as Record<string, unknown>);\n const childCmBase =\n childMetaBase._cm && typeof childMetaBase._cm === \"object\"\n ? (childMetaBase._cm as Record<string, unknown>)\n : ({} as Record<string, unknown>);\n\n out.push({\n ...produced,\n meta: originIndex === undefined ? childMetaBase : { ...childMetaBase, _cm: { ...childCmBase, originIndex } },\n paired: current.paired ?? produced.paired,\n });\n }\n\n return emitPorts({ main: out });\n }\n}\n","import type { NodeId, RunnableNodeConfig, TypeToken, UpstreamRefPlaceholder } from \"@codemation/core\";\n\nimport { SubWorkflowNode } from \"./SubWorkflowNode\";\n\nexport class SubWorkflow<TInputJson = unknown, TOutputJson = unknown> implements RunnableNodeConfig<\n TInputJson,\n TOutputJson\n> {\n readonly kind = \"node\" as const;\n readonly type: TypeToken<unknown> = SubWorkflowNode;\n constructor(\n public readonly name: string,\n public readonly workflowId: string,\n public upstreamRefs?: Array<{ nodeId: NodeId } | UpstreamRefPlaceholder>,\n public readonly startAt?: NodeId,\n public readonly id?: string,\n ) {}\n}\n\nexport { SubWorkflowNode } from \"./SubWorkflowNode\";\n","import type {\n Items,\n NodeExecutionContext,\n NodeOutputs,\n TestTriggerNodeConfig,\n TriggerNode,\n TriggerSetupContext,\n} from \"@codemation/core\";\n\nimport { node } from \"@codemation/core\";\n\n/**\n * Author-defined test-fixture trigger. Live activation skips this trigger (filtered by\n * `triggerKind === \"test\"` in `TriggerRuntimeService`); the `TestSuiteOrchestrator` drives its\n * `generateItems` callback during a TestSuiteRun and dispatches one workflow run per yielded item.\n *\n * `setup` is intentionally a no-op for symmetry with other trigger nodes — the real work happens\n * in the orchestrator. `execute` is a passthrough so items provided to `engine.runWorkflow(...)`\n * (one per case) flow downstream unchanged on `main`.\n */\n@node({ packageName: \"@codemation/core-nodes\" })\nexport class TestTriggerNode implements TriggerNode<TestTriggerNodeConfig<any>> {\n kind = \"trigger\" as const;\n outputPorts = [\"main\"] as const;\n\n async setup(_ctx: TriggerSetupContext<TestTriggerNodeConfig<any>>): Promise<undefined> {\n return undefined;\n }\n\n async execute(items: Items, _ctx: NodeExecutionContext<TestTriggerNodeConfig<any>>): Promise<NodeOutputs> {\n return { main: items };\n }\n}\n","import type {\n CredentialRequirement,\n Item,\n TestTriggerNodeConfig,\n TestTriggerSetupContext,\n TypeToken,\n} from \"@codemation/core\";\n\nimport { TestTriggerNode } from \"./TestTriggerNode\";\n\nexport interface TestTriggerOptions<TOutputJson> {\n readonly name?: string;\n readonly id?: string;\n readonly icon?: string;\n /** Cap on simultaneous in-flight test cases for one suite run. Default: 4 (orchestrator). */\n readonly concurrency?: number;\n readonly credentialRequirements?: ReadonlyArray<CredentialRequirement>;\n /**\n * Free-form description of where the test cases come from. Shown in the node properties\n * panel and the Tests-tab suite-detail header so authors revisiting the workflow six months\n * later remember which mailbox / folder / fixture file the cases originate from.\n */\n readonly description?: string;\n /**\n * Author callback that yields one item per test case. Items are dispatched as separate\n * workflow runs by the TestSuiteOrchestrator, with `executionOptions.testContext` set.\n * The provided context exposes credential resolution and an AbortSignal for cancellation.\n */\n generateItems(ctx: TestTriggerSetupContext<TestTrigger<TOutputJson>>): AsyncIterable<Item<TOutputJson>>;\n /**\n * Optional resolver: extract a human-readable label from a yielded item. The orchestrator\n * persists this on the run, so the Tests-tab tree-table shows e.g. \"RFQ for batch 14\"\n * instead of an opaque runId. Typical use: `(item) => item.json.subject` for mailbox tests.\n */\n caseLabel?(item: Item<TOutputJson>): string | undefined;\n}\n\n/**\n * Trigger config for a test fixture source. Drop one (or more) of these on the canvas alongside\n * a workflow's live triggers; clicking \"Run tests\" on the Tests tab invokes\n * {@link TestTriggerOptions.generateItems} via the TestSuiteOrchestrator.\n */\nexport class TestTrigger<TOutputJson = unknown> implements TestTriggerNodeConfig<TOutputJson> {\n readonly kind = \"trigger\" as const;\n readonly triggerKind = \"test\" as const;\n readonly type: TypeToken<unknown> = TestTriggerNode;\n readonly icon: string;\n readonly name: string;\n readonly id?: string;\n readonly concurrency?: number;\n readonly description?: string;\n readonly generateItems: TestTriggerOptions<TOutputJson>[\"generateItems\"];\n readonly caseLabel?: TestTriggerOptions<TOutputJson>[\"caseLabel\"];\n private readonly credentialRequirements: ReadonlyArray<CredentialRequirement>;\n\n constructor(options: TestTriggerOptions<TOutputJson>) {\n this.name = options.name ?? \"Test trigger\";\n this.id = options.id;\n this.icon = options.icon ?? \"lucide:flask-conical\";\n this.concurrency = options.concurrency;\n this.description = options.description;\n this.credentialRequirements = options.credentialRequirements ?? [];\n this.generateItems = options.generateItems;\n this.caseLabel = options.caseLabel;\n }\n\n getCredentialRequirements(): ReadonlyArray<CredentialRequirement> {\n return this.credentialRequirements;\n }\n}\n\nexport { TestTriggerNode } from \"./TestTriggerNode\";\n","export class WaitDuration {\n static normalize(milliseconds: number): number {\n return Number.isFinite(milliseconds) && milliseconds > 0 ? Math.floor(milliseconds) : 0;\n }\n}\n","import type { RunnableNode, RunnableNodeExecuteArgs } from \"@codemation/core\";\n\nimport { node } from \"@codemation/core\";\n\nimport { Wait } from \"./wait\";\nimport { WaitDuration } from \"./WaitDurationFactory\";\n\n@node({ packageName: \"@codemation/core-nodes\" })\nexport class WaitNode implements RunnableNode<Wait<any>> {\n kind = \"node\" as const;\n outputPorts = [\"main\"] as const;\n\n async execute(args: RunnableNodeExecuteArgs<Wait<any>>): Promise<unknown> {\n if (args.itemIndex === 0) {\n const milliseconds = WaitDuration.normalize(args.ctx.config.milliseconds);\n if (milliseconds > 0) {\n await new Promise<void>((resolve) => {\n setTimeout(resolve, milliseconds);\n });\n }\n }\n return args.item;\n }\n}\n","import type { RunnableNodeConfig, TypeToken } from \"@codemation/core\";\n\nimport { WaitNode } from \"./WaitNode\";\n\nexport class Wait<TItemJson = unknown> implements RunnableNodeConfig<TItemJson, TItemJson> {\n readonly kind = \"node\" as const;\n readonly type: TypeToken<unknown> = WaitNode;\n readonly execution = { hint: \"local\" } as const;\n /** Pass-through empty batches should still advance to downstream nodes. */\n readonly continueWhenEmptyOutput = true as const;\n readonly icon = \"lucide:hourglass\" as const;\n\n constructor(\n public readonly name: string,\n public readonly milliseconds: number,\n public readonly id?: string,\n ) {}\n}\n\nexport { WaitDuration } from \"./WaitDurationFactory\";\nexport { WaitNode } from \"./WaitNode\";\n","import type { Items, WebhookControlSignal } from \"@codemation/core\";\n\nexport class WebhookRespondNowAndContinueError extends Error implements WebhookControlSignal {\n readonly __webhookControl = true as const;\n readonly kind = \"respondNowAndContinue\" as const;\n\n constructor(\n public readonly responseItems: Items,\n public readonly continueItems: Items,\n message: string = \"Webhook responded immediately and continued the run.\",\n ) {\n super(message);\n this.name = \"WebhookRespondNowAndContinueError\";\n }\n}\n","import type { Items, WebhookControlSignal } from \"@codemation/core\";\n\nexport class WebhookRespondNowError extends Error implements WebhookControlSignal {\n readonly __webhookControl = true as const;\n readonly kind = \"respondNow\" as const;\n\n constructor(\n public readonly responseItems: Items,\n message: string = \"Webhook responded immediately.\",\n ) {\n super(message);\n this.name = \"WebhookRespondNowError\";\n }\n}\n","import type {\n ExecutableTriggerNode,\n Items,\n NodeExecutionContext,\n NodeOutputs,\n TriggerSetupContext,\n} from \"@codemation/core\";\nimport { node } from \"@codemation/core\";\nimport { WebhookTrigger } from \"./WebhookTriggerFactory\";\n\n/**\n * HTTP webhooks are not registered in trigger setup. The host exposes a single catch-all route\n * (e.g. `/api/webhooks/:endpointPath`); the engine's catalog-backed webhook matcher resolves the\n * user-defined endpoint path to this workflow + node, then runs the workflow from this trigger.\n */\n@node({ packageName: \"@codemation/core-nodes\" })\nexport class WebhookTriggerNode implements ExecutableTriggerNode<WebhookTrigger<any>> {\n readonly kind = \"trigger\" as const;\n readonly outputPorts = [\"main\"] as const;\n\n async setup(_ctx: TriggerSetupContext<WebhookTrigger<any>>): Promise<undefined> {\n return undefined;\n }\n\n async execute(items: Items, _ctx: NodeExecutionContext<WebhookTrigger<any>>): Promise<NodeOutputs> {\n if (items.length === 0) {\n throw new Error(\n `Webhook trigger \"${_ctx.config.name}\" requires a webhook request. Invoke this workflow through its webhook endpoint until manual request simulation is supported.`,\n );\n }\n const result = await _ctx.config.handler(items, _ctx);\n return { main: result ?? items };\n }\n}\n","import type { HttpMethod, Items, NodeExecutionContext, TriggerNodeConfig, TypeToken } from \"@codemation/core\";\nimport type { ZodType } from \"zod\";\nimport { WebhookTriggerNode } from \"./webhookTriggerNode\";\n\ntype WebhookInputSchema = ZodType<any, any, any>;\ntype WebhookTriggerHandler<TConfig extends WebhookTrigger<any> = WebhookTrigger<any>> = (\n items: Items,\n ctx: NodeExecutionContext<TConfig>,\n) => Promise<Items | void> | Items | void;\n\nexport class WebhookTrigger<\n TSchema extends WebhookInputSchema | undefined = undefined,\n> implements TriggerNodeConfig<unknown> {\n readonly kind = \"trigger\" as const;\n readonly type: TypeToken<unknown> = WebhookTriggerNode;\n readonly icon = \"lucide:webhook\";\n\n constructor(\n public readonly name: string,\n private readonly args: Readonly<{\n endpointKey: string;\n methods: ReadonlyArray<HttpMethod>;\n inputSchema?: TSchema;\n }>,\n public readonly handler: WebhookTriggerHandler<\n WebhookTrigger<TSchema>\n > = WebhookTrigger.defaultHandler as WebhookTriggerHandler<WebhookTrigger<TSchema>>,\n public readonly id?: string,\n ) {}\n\n get endpointKey(): string {\n return this.args.endpointKey;\n }\n\n get methods(): ReadonlyArray<HttpMethod> {\n return this.args.methods;\n }\n\n get inputSchema(): TSchema | undefined {\n return this.args.inputSchema;\n }\n\n parseJsonBody(body: unknown): unknown {\n if (!this.args.inputSchema) return body;\n return this.args.inputSchema.parse(body);\n }\n\n private static defaultHandler(items: Items): Items {\n return items;\n }\n}\n","import type { RunnableNode, RunnableNodeExecuteArgs } from \"@codemation/core\";\nimport { node } from \"@codemation/core\";\n\nimport type { ConnectionCredentialNodeConfig } from \"./ConnectionCredentialNodeConfig\";\n\n/**\n * Placeholder runnable node for connection-owned workflow nodes (LLM/tool slots).\n * The engine does not schedule these; they exist for credentials, tokens, and UI identity.\n */\n@node({ packageName: \"@codemation/core-nodes\" })\nexport class ConnectionCredentialNode implements RunnableNode<ConnectionCredentialNodeConfig> {\n kind = \"node\" as const;\n outputPorts = [\"main\"] as const;\n\n execute(_args: RunnableNodeExecuteArgs<ConnectionCredentialNodeConfig>): unknown {\n return [];\n }\n}\n","import type { Container } from \"@codemation/core\";\nimport { AIAgentExecutionHelpersFactory, AIAgentNode } from \"./nodes/aiAgent\";\nimport { CallbackNode } from \"./nodes/CallbackNodeFactory\";\nimport { HttpRequestNode } from \"./nodes/httpRequest\";\nimport { IfNode } from \"./nodes/if\";\nimport { ManualTriggerNode } from \"./nodes/ManualTriggerFactory\";\nimport { MapDataNode } from \"./nodes/mapData\";\nimport { NoOpNode } from \"./nodes/noOp\";\nimport { SubWorkflowNode } from \"./nodes/subWorkflow\";\nimport { WaitNode } from \"./nodes/wait\";\nimport { ConnectionCredentialNode } from \"./nodes/ConnectionCredentialNode\";\nimport { AggregateNode } from \"./nodes/aggregate\";\nimport { FilterNode } from \"./nodes/filter\";\nimport { SplitNode } from \"./nodes/split\";\nimport { SwitchNode } from \"./nodes/switch\";\n\n/**\n * Registrar for built-in nodes. In a real project, this would use tsyringe's\n * container.registerSingleton(...). For the skeleton we keep it token-based:\n * the engine resolves node implementations by class token.\n */\nexport function registerCoreNodes(container: Container): void {\n // With class tokens, resolving registers happen via the DI container setup.\n // This function exists as the standardized extension point.\n void container;\n\n // Example: if using tsyringe, you'd do:\n // tsyringeContainer.registerSingleton(IfNode, IfNode);\n // ...\n void IfNode;\n void HttpRequestNode;\n void CallbackNode;\n void MapDataNode;\n void NoOpNode;\n void SubWorkflowNode;\n void ManualTriggerNode;\n void AIAgentNode;\n void AIAgentExecutionHelpersFactory;\n void WaitNode;\n void ConnectionCredentialNode;\n void SplitNode;\n void FilterNode;\n void AggregateNode;\n void SwitchNode;\n}\n","import type { WorkflowId } from \"@codemation/core\";\nimport { WorkflowBuilder } from \"@codemation/core\";\n\nexport function createWorkflowBuilder(meta: Readonly<{ id: WorkflowId; name: string }>): WorkflowBuilder {\n return new WorkflowBuilder(meta);\n}\n","import type { ChatModelConfig } from \"@codemation/core\";\nimport { OpenAIChatModelConfig } from \"../chatModels/openAiChatModelConfig\";\n\nexport class WorkflowChatModelFactory {\n static create(model: string | ChatModelConfig): ChatModelConfig {\n if (typeof model !== \"string\") {\n return model;\n }\n const [provider, resolvedModel] = model.includes(\":\") ? model.split(\":\", 2) : [\"openai\", model];\n if (provider !== \"openai\") {\n throw new Error(`Unsupported workflow().agent() model provider \"${provider}\".`);\n }\n return new OpenAIChatModelConfig(\"OpenAI\", resolvedModel);\n }\n}\n","import { z } from \"zod\";\nimport { AIAgent } from \"../nodes/AIAgentConfig\";\nimport type { WorkflowAgentOptions } from \"./WorkflowAuthoringOptions.types\";\nimport { WorkflowChatModelFactory } from \"./WorkflowChatModelFactory.types\";\n\nexport class WorkflowAgentNodeFactory {\n static create<TCurrentJson, TOutputSchema extends z.ZodTypeAny | undefined>(\n nameOrOptions: string | WorkflowAgentOptions<TCurrentJson, TOutputSchema>,\n optionsOrUndefined?: WorkflowAgentOptions<TCurrentJson, TOutputSchema>,\n ): AIAgent<TCurrentJson, TOutputSchema extends z.ZodTypeAny ? z.output<TOutputSchema> : Record<string, unknown>> {\n const options = typeof nameOrOptions === \"string\" ? optionsOrUndefined! : nameOrOptions;\n const name = typeof nameOrOptions === \"string\" ? nameOrOptions : \"AI agent\";\n const outputSchema = options.outputSchema as\n | z.ZodType<TOutputSchema extends z.ZodTypeAny ? z.output<TOutputSchema> : Record<string, unknown>>\n | undefined;\n return new AIAgent<\n TCurrentJson,\n TOutputSchema extends z.ZodTypeAny ? z.output<TOutputSchema> : Record<string, unknown>\n >({\n name,\n messages: options.messages,\n chatModel: WorkflowChatModelFactory.create(options.model),\n tools: options.tools,\n outputSchema,\n id: options.id,\n retryPolicy: options.retryPolicy,\n guardrails: options.guardrails,\n });\n }\n}\n","import { DefinedNodeRegistry, type DefinedNode } from \"@codemation/core\";\n\nexport class WorkflowDefinedNodeResolver {\n static resolve(\n definitionOrKey: DefinedNode<string, Record<string, unknown>, unknown, unknown> | string,\n ): DefinedNode<string, Record<string, unknown>, unknown, unknown> {\n if (typeof definitionOrKey !== \"string\") {\n return definitionOrKey;\n }\n const definition = DefinedNodeRegistry.resolve(definitionOrKey);\n if (!definition) {\n throw new Error(`No helper-defined node with key \"${definitionOrKey}\" is registered in this module graph.`);\n }\n return definition;\n }\n}\n","export class WorkflowDurationParser {\n static parse(duration: number | string): number {\n if (typeof duration === \"number\") {\n return Number.isFinite(duration) && duration > 0 ? Math.floor(duration) : 0;\n }\n const normalized = duration.trim().toLowerCase();\n const match = normalized.match(/^(\\d+)(ms|s|m|h)$/);\n if (!match) {\n throw new Error(\n `Unsupported wait duration \"${duration}\". Use a number of milliseconds or values like \"500ms\", \"2s\", \"5m\".`,\n );\n }\n const value = Number(match[1]);\n const unit = match[2];\n if (unit === \"ms\") {\n return value;\n }\n if (unit === \"s\") {\n return value * 1000;\n }\n if (unit === \"m\") {\n return value * 60_000;\n }\n return value * 3_600_000;\n }\n}\n","import type {\n AnyRunnableNodeConfig,\n CredentialJsonRecord,\n DefinedNode,\n DefinedNodeConfigInput,\n Item,\n Items,\n NodeExecutionContext,\n RunnableNodeConfig,\n RunnableNodeOutputJson,\n} from \"@codemation/core\";\nimport { z } from \"zod\";\nimport { Aggregate } from \"../nodes/aggregate\";\nimport { Filter } from \"../nodes/filter\";\nimport type { MapDataOptions } from \"../nodes/mapData\";\nimport { MapData } from \"../nodes/mapData\";\nimport { Split } from \"../nodes/split\";\nimport { Wait } from \"../nodes/wait\";\nimport type { WorkflowAgentOptions } from \"./WorkflowAuthoringOptions.types\";\nimport { WorkflowAgentNodeFactory } from \"./WorkflowAgentNodeFactory.types\";\nimport { WorkflowDefinedNodeResolver } from \"./WorkflowDefinedNodeResolver.types\";\nimport { WorkflowDurationParser } from \"./WorkflowDurationParser.types\";\n\ntype WorkflowMapCallback<TCurrentJson, TNextJson> = (\n item: Item<TCurrentJson>,\n ctx: NodeExecutionContext<MapData<TCurrentJson, TNextJson>>,\n) => TNextJson;\n\nexport class WorkflowBranchBuilder<TCurrentJson> {\n constructor(private readonly steps: ReadonlyArray<AnyRunnableNodeConfig> = []) {}\n\n then<TOutputJson, TConfig extends RunnableNodeConfig<TCurrentJson, TOutputJson>>(\n config: TConfig,\n ): WorkflowBranchBuilder<RunnableNodeOutputJson<TConfig>> {\n return new WorkflowBranchBuilder<RunnableNodeOutputJson<TConfig>>([...this.steps, config]);\n }\n\n map<TNextJson>(mapper: WorkflowMapCallback<TCurrentJson, TNextJson>): WorkflowBranchBuilder<TNextJson>;\n map<TNextJson>(\n name: string,\n mapper: WorkflowMapCallback<TCurrentJson, TNextJson>,\n options?: MapDataOptions,\n ): WorkflowBranchBuilder<TNextJson>;\n map<TNextJson>(\n nameOrMapper: string | WorkflowMapCallback<TCurrentJson, TNextJson>,\n mapperOrUndefined?: WorkflowMapCallback<TCurrentJson, TNextJson>,\n options?: MapDataOptions,\n ): WorkflowBranchBuilder<TNextJson> {\n const name = typeof nameOrMapper === \"string\" ? nameOrMapper : \"Map data\";\n const mapper = typeof nameOrMapper === \"string\" ? mapperOrUndefined! : nameOrMapper;\n return this.then(new MapData<TCurrentJson, TNextJson>(name, mapper, options)) as WorkflowBranchBuilder<TNextJson>;\n }\n\n wait(duration: number | string): WorkflowBranchBuilder<TCurrentJson>;\n wait(name: string, duration: number | string, id?: string): WorkflowBranchBuilder<TCurrentJson>;\n wait(\n nameOrDuration: string | number,\n durationOrUndefined?: string | number,\n id?: string,\n ): WorkflowBranchBuilder<TCurrentJson> {\n const name = typeof nameOrDuration === \"string\" && durationOrUndefined !== undefined ? nameOrDuration : \"Wait\";\n const duration = durationOrUndefined ?? nameOrDuration;\n return this.then(\n new Wait<TCurrentJson>(name, WorkflowDurationParser.parse(duration), id),\n ) as WorkflowBranchBuilder<TCurrentJson>;\n }\n\n split<TElem>(\n getElements: (item: Item<TCurrentJson>, ctx: NodeExecutionContext<Split<TCurrentJson, TElem>>) => readonly TElem[],\n ): WorkflowBranchBuilder<TElem>;\n split<TElem>(\n name: string,\n getElements: (item: Item<TCurrentJson>, ctx: NodeExecutionContext<Split<TCurrentJson, TElem>>) => readonly TElem[],\n id?: string,\n ): WorkflowBranchBuilder<TElem>;\n split<TElem>(\n nameOrGetter:\n | string\n | ((item: Item<TCurrentJson>, ctx: NodeExecutionContext<Split<TCurrentJson, TElem>>) => readonly TElem[]),\n getElementsOrUndefined?: (\n item: Item<TCurrentJson>,\n ctx: NodeExecutionContext<Split<TCurrentJson, TElem>>,\n ) => readonly TElem[],\n id?: string,\n ): WorkflowBranchBuilder<TElem> {\n const name = typeof nameOrGetter === \"string\" ? nameOrGetter : \"Split\";\n const getElements = typeof nameOrGetter === \"string\" ? getElementsOrUndefined! : nameOrGetter;\n return this.then(new Split<TCurrentJson, TElem>(name, getElements, id)) as WorkflowBranchBuilder<TElem>;\n }\n\n filter(\n predicate: (\n item: Item<TCurrentJson>,\n index: number,\n items: Items<TCurrentJson>,\n ctx: NodeExecutionContext<Filter<TCurrentJson>>,\n ) => boolean,\n ): WorkflowBranchBuilder<TCurrentJson>;\n filter(\n name: string,\n predicate: (\n item: Item<TCurrentJson>,\n index: number,\n items: Items<TCurrentJson>,\n ctx: NodeExecutionContext<Filter<TCurrentJson>>,\n ) => boolean,\n id?: string,\n ): WorkflowBranchBuilder<TCurrentJson>;\n filter(\n nameOrPredicate:\n | string\n | ((\n item: Item<TCurrentJson>,\n index: number,\n items: Items<TCurrentJson>,\n ctx: NodeExecutionContext<Filter<TCurrentJson>>,\n ) => boolean),\n predicateOrUndefined?: (\n item: Item<TCurrentJson>,\n index: number,\n items: Items<TCurrentJson>,\n ctx: NodeExecutionContext<Filter<TCurrentJson>>,\n ) => boolean,\n id?: string,\n ): WorkflowBranchBuilder<TCurrentJson> {\n const name = typeof nameOrPredicate === \"string\" ? nameOrPredicate : \"Filter\";\n const predicate = typeof nameOrPredicate === \"string\" ? predicateOrUndefined! : nameOrPredicate;\n return this.then(new Filter<TCurrentJson>(name, predicate, id)) as WorkflowBranchBuilder<TCurrentJson>;\n }\n\n aggregate<TOut>(\n aggregateFn: (\n items: Items<TCurrentJson>,\n ctx: NodeExecutionContext<Aggregate<TCurrentJson, TOut>>,\n ) => TOut | Promise<TOut>,\n ): WorkflowBranchBuilder<TOut>;\n aggregate<TOut>(\n name: string,\n aggregateFn: (\n items: Items<TCurrentJson>,\n ctx: NodeExecutionContext<Aggregate<TCurrentJson, TOut>>,\n ) => TOut | Promise<TOut>,\n id?: string,\n ): WorkflowBranchBuilder<TOut>;\n aggregate<TOut>(\n nameOrFn:\n | string\n | ((\n items: Items<TCurrentJson>,\n ctx: NodeExecutionContext<Aggregate<TCurrentJson, TOut>>,\n ) => TOut | Promise<TOut>),\n aggregateFnOrUndefined?: (\n items: Items<TCurrentJson>,\n ctx: NodeExecutionContext<Aggregate<TCurrentJson, TOut>>,\n ) => TOut | Promise<TOut>,\n id?: string,\n ): WorkflowBranchBuilder<TOut> {\n const name = typeof nameOrFn === \"string\" ? nameOrFn : \"Aggregate\";\n const aggregateFn = typeof nameOrFn === \"string\" ? aggregateFnOrUndefined! : nameOrFn;\n return this.then(new Aggregate<TCurrentJson, TOut>(name, aggregateFn, id)) as WorkflowBranchBuilder<TOut>;\n }\n\n agent<TOutputSchema extends z.ZodTypeAny>(\n options: WorkflowAgentOptions<TCurrentJson, TOutputSchema>,\n ): WorkflowBranchBuilder<z.output<TOutputSchema>>;\n agent(options: WorkflowAgentOptions<TCurrentJson, undefined>): WorkflowBranchBuilder<Record<string, unknown>>;\n agent<TOutputSchema extends z.ZodTypeAny>(\n name: string,\n options: WorkflowAgentOptions<TCurrentJson, TOutputSchema | undefined>,\n ): WorkflowBranchBuilder<TOutputSchema extends z.ZodTypeAny ? z.output<TOutputSchema> : Record<string, unknown>>;\n agent<TOutputSchema extends z.ZodTypeAny>(\n nameOrOptions: string | WorkflowAgentOptions<TCurrentJson, TOutputSchema | undefined>,\n optionsOrUndefined?: WorkflowAgentOptions<TCurrentJson, TOutputSchema | undefined>,\n ): WorkflowBranchBuilder<TOutputSchema extends z.ZodTypeAny ? z.output<TOutputSchema> : Record<string, unknown>> {\n return this.then(WorkflowAgentNodeFactory.create(nameOrOptions, optionsOrUndefined)) as WorkflowBranchBuilder<\n TOutputSchema extends z.ZodTypeAny ? z.output<TOutputSchema> : Record<string, unknown>\n >;\n }\n\n node<TConfig extends CredentialJsonRecord, TInputJson, TOutputJson>(\n definitionOrKey: DefinedNode<string, TConfig, TInputJson, TOutputJson> | string,\n config: DefinedNodeConfigInput<TConfig, TCurrentJson>,\n name?: string,\n id?: string,\n ): TCurrentJson extends TInputJson ? WorkflowBranchBuilder<TOutputJson> : never {\n const definition = WorkflowDefinedNodeResolver.resolve(\n definitionOrKey as DefinedNode<string, Record<string, unknown>, unknown, unknown> | string,\n ) as DefinedNode<string, TConfig, TInputJson, TOutputJson>;\n return this.then(\n definition.create(config, name, id) as unknown as RunnableNodeConfig<TCurrentJson, TOutputJson>,\n ) as TCurrentJson extends TInputJson ? WorkflowBranchBuilder<TOutputJson> : never;\n }\n\n getSteps(): ReadonlyArray<AnyRunnableNodeConfig> {\n return this.steps;\n }\n}\n","import type {\n CredentialJsonRecord,\n DefinedNode,\n DefinedNodeConfigInput,\n Item,\n Items,\n NodeExecutionContext,\n RunnableNodeConfig,\n RunnableNodeOutputJson,\n WorkflowDefinition,\n} from \"@codemation/core\";\nimport { ChainCursor } from \"@codemation/core\";\nimport { z } from \"zod\";\nimport { Aggregate } from \"../nodes/aggregate\";\nimport { Filter } from \"../nodes/filter\";\nimport { If } from \"../nodes/if\";\nimport type { MapDataOptions } from \"../nodes/mapData\";\nimport { MapData } from \"../nodes/mapData\";\nimport { Merge, type MergeMode } from \"../nodes/merge\";\nimport { Split } from \"../nodes/split\";\nimport { Switch } from \"../nodes/switch\";\nimport { Wait } from \"../nodes/wait\";\nimport type { WorkflowAgentOptions } from \"./WorkflowAuthoringOptions.types\";\nimport { WorkflowAgentNodeFactory } from \"./WorkflowAgentNodeFactory.types\";\nimport { WorkflowBranchBuilder } from \"./WorkflowBranchBuilder.types\";\nimport { WorkflowDefinedNodeResolver } from \"./WorkflowDefinedNodeResolver.types\";\nimport { WorkflowDurationParser } from \"./WorkflowDurationParser.types\";\n\ntype BranchCallback<TCurrentJson, TNextJson> = (\n branch: WorkflowBranchBuilder<TCurrentJson>,\n) => WorkflowBranchBuilder<TNextJson>;\ntype RouteBranchCallback<TCurrentJson, TNextJson> = (branch: WorkflowChain<TCurrentJson>) => WorkflowChain<TNextJson>;\ntype BranchOutputMatch<TLeft, TRight> = [TLeft] extends [TRight] ? ([TRight] extends [TLeft] ? true : false) : false;\ntype WorkflowMapCallback<TCurrentJson, TNextJson> = (\n item: Item<TCurrentJson>,\n ctx: NodeExecutionContext<MapData<TCurrentJson, TNextJson>>,\n) => TNextJson;\ntype WorkflowIfPredicate<TCurrentJson> = (\n item: Item<TCurrentJson>,\n ctx: NodeExecutionContext<If<TCurrentJson>>,\n) => boolean;\ntype WorkflowSwitchCaseKeyResolver<TCurrentJson> = (\n item: Item<TCurrentJson>,\n ctx: NodeExecutionContext<Switch<TCurrentJson>>,\n) => string | Promise<string>;\n\nexport class WorkflowChain<TCurrentJson> {\n constructor(private readonly chain: ChainCursor<TCurrentJson>) {}\n\n then<TOutputJson, TConfig extends RunnableNodeConfig<TCurrentJson, TOutputJson>>(\n config: TConfig,\n ): WorkflowChain<RunnableNodeOutputJson<TConfig>> {\n return new WorkflowChain(this.chain.then(config));\n }\n\n map<TNextJson>(mapper: WorkflowMapCallback<TCurrentJson, TNextJson>): WorkflowChain<TNextJson>;\n map<TNextJson>(\n name: string,\n mapper: WorkflowMapCallback<TCurrentJson, TNextJson>,\n options?: MapDataOptions,\n ): WorkflowChain<TNextJson>;\n map<TNextJson>(\n nameOrMapper: string | WorkflowMapCallback<TCurrentJson, TNextJson>,\n mapperOrUndefined?: WorkflowMapCallback<TCurrentJson, TNextJson>,\n options?: MapDataOptions,\n ): WorkflowChain<TNextJson> {\n const name = typeof nameOrMapper === \"string\" ? nameOrMapper : \"Map data\";\n const mapper = typeof nameOrMapper === \"string\" ? mapperOrUndefined! : nameOrMapper;\n return this.then(new MapData<TCurrentJson, TNextJson>(name, mapper, options)) as WorkflowChain<TNextJson>;\n }\n\n wait(duration: number | string): WorkflowChain<TCurrentJson>;\n wait(name: string, duration: number | string, id?: string): WorkflowChain<TCurrentJson>;\n wait(\n nameOrDuration: string | number,\n durationOrUndefined?: string | number,\n id?: string,\n ): WorkflowChain<TCurrentJson> {\n const name = typeof nameOrDuration === \"string\" && durationOrUndefined !== undefined ? nameOrDuration : \"Wait\";\n const duration = durationOrUndefined ?? nameOrDuration;\n return this.then(\n new Wait<TCurrentJson>(name, WorkflowDurationParser.parse(duration), id),\n ) as WorkflowChain<TCurrentJson>;\n }\n\n split<TElem>(\n getElements: (item: Item<TCurrentJson>, ctx: NodeExecutionContext<Split<TCurrentJson, TElem>>) => readonly TElem[],\n ): WorkflowChain<TElem>;\n split<TElem>(\n name: string,\n getElements: (item: Item<TCurrentJson>, ctx: NodeExecutionContext<Split<TCurrentJson, TElem>>) => readonly TElem[],\n id?: string,\n ): WorkflowChain<TElem>;\n split<TElem>(\n nameOrGetter:\n | string\n | ((item: Item<TCurrentJson>, ctx: NodeExecutionContext<Split<TCurrentJson, TElem>>) => readonly TElem[]),\n getElementsOrUndefined?: (\n item: Item<TCurrentJson>,\n ctx: NodeExecutionContext<Split<TCurrentJson, TElem>>,\n ) => readonly TElem[],\n id?: string,\n ): WorkflowChain<TElem> {\n const name = typeof nameOrGetter === \"string\" ? nameOrGetter : \"Split\";\n const getElements = typeof nameOrGetter === \"string\" ? getElementsOrUndefined! : nameOrGetter;\n return this.then(new Split<TCurrentJson, TElem>(name, getElements, id)) as WorkflowChain<TElem>;\n }\n\n filter(\n predicate: (\n item: Item<TCurrentJson>,\n index: number,\n items: Items<TCurrentJson>,\n ctx: NodeExecutionContext<Filter<TCurrentJson>>,\n ) => boolean,\n ): WorkflowChain<TCurrentJson>;\n filter(\n name: string,\n predicate: (\n item: Item<TCurrentJson>,\n index: number,\n items: Items<TCurrentJson>,\n ctx: NodeExecutionContext<Filter<TCurrentJson>>,\n ) => boolean,\n id?: string,\n ): WorkflowChain<TCurrentJson>;\n filter(\n nameOrPredicate:\n | string\n | ((\n item: Item<TCurrentJson>,\n index: number,\n items: Items<TCurrentJson>,\n ctx: NodeExecutionContext<Filter<TCurrentJson>>,\n ) => boolean),\n predicateOrUndefined?: (\n item: Item<TCurrentJson>,\n index: number,\n items: Items<TCurrentJson>,\n ctx: NodeExecutionContext<Filter<TCurrentJson>>,\n ) => boolean,\n id?: string,\n ): WorkflowChain<TCurrentJson> {\n const name = typeof nameOrPredicate === \"string\" ? nameOrPredicate : \"Filter\";\n const predicate = typeof nameOrPredicate === \"string\" ? predicateOrUndefined! : nameOrPredicate;\n return this.then(new Filter<TCurrentJson>(name, predicate, id)) as WorkflowChain<TCurrentJson>;\n }\n\n aggregate<TOut>(\n aggregateFn: (\n items: Items<TCurrentJson>,\n ctx: NodeExecutionContext<Aggregate<TCurrentJson, TOut>>,\n ) => TOut | Promise<TOut>,\n ): WorkflowChain<TOut>;\n aggregate<TOut>(\n name: string,\n aggregateFn: (\n items: Items<TCurrentJson>,\n ctx: NodeExecutionContext<Aggregate<TCurrentJson, TOut>>,\n ) => TOut | Promise<TOut>,\n id?: string,\n ): WorkflowChain<TOut>;\n aggregate<TOut>(\n nameOrFn:\n | string\n | ((\n items: Items<TCurrentJson>,\n ctx: NodeExecutionContext<Aggregate<TCurrentJson, TOut>>,\n ) => TOut | Promise<TOut>),\n aggregateFnOrUndefined?: (\n items: Items<TCurrentJson>,\n ctx: NodeExecutionContext<Aggregate<TCurrentJson, TOut>>,\n ) => TOut | Promise<TOut>,\n id?: string,\n ): WorkflowChain<TOut> {\n const name = typeof nameOrFn === \"string\" ? nameOrFn : \"Aggregate\";\n const aggregateFn = typeof nameOrFn === \"string\" ? aggregateFnOrUndefined! : nameOrFn;\n return this.then(new Aggregate<TCurrentJson, TOut>(name, aggregateFn, id)) as WorkflowChain<TOut>;\n }\n\n merge(): WorkflowChain<TCurrentJson>;\n merge(cfg: Readonly<{ mode: MergeMode; prefer?: ReadonlyArray<string> }>, id?: string): WorkflowChain<TCurrentJson>;\n merge(\n name: string,\n cfg?: Readonly<{ mode: MergeMode; prefer?: ReadonlyArray<string> }>,\n id?: string,\n ): WorkflowChain<TCurrentJson>;\n merge(\n nameOrCfg?: string | Readonly<{ mode: MergeMode; prefer?: ReadonlyArray<string> }>,\n cfgOrId?: Readonly<{ mode: MergeMode; prefer?: ReadonlyArray<string> }> | string,\n id?: string,\n ): WorkflowChain<TCurrentJson> {\n const name = typeof nameOrCfg === \"string\" ? nameOrCfg : \"Merge\";\n const cfg =\n typeof nameOrCfg === \"string\"\n ? ((typeof cfgOrId === \"string\" ? undefined : cfgOrId) ?? { mode: \"passThrough\" as const })\n : (nameOrCfg ?? { mode: \"passThrough\" as const });\n const mergeId = typeof cfgOrId === \"string\" ? cfgOrId : id;\n return new WorkflowChain(\n this.chain.thenIntoInputHints(new Merge<TCurrentJson>(name, cfg, mergeId)),\n ) as WorkflowChain<TCurrentJson>;\n }\n\n if<TBranchJson>(\n predicate: WorkflowIfPredicate<TCurrentJson>,\n branches: Readonly<{\n true?: BranchCallback<TCurrentJson, TBranchJson>;\n false?: BranchCallback<TCurrentJson, TBranchJson>;\n }>,\n ): WorkflowChain<TBranchJson>;\n if<TBranchJson>(\n name: string,\n predicate: WorkflowIfPredicate<TCurrentJson>,\n branches: Readonly<{\n true?: BranchCallback<TCurrentJson, TBranchJson>;\n false?: BranchCallback<TCurrentJson, TBranchJson>;\n }>,\n ): WorkflowChain<TBranchJson>;\n if<TTrueJson, TFalseJson>(\n nameOrPredicate: string | WorkflowIfPredicate<TCurrentJson>,\n predicateOrBranches:\n | WorkflowIfPredicate<TCurrentJson>\n | Readonly<{ true?: BranchCallback<TCurrentJson, TTrueJson>; false?: BranchCallback<TCurrentJson, TFalseJson> }>,\n branchesOrUndefined?: Readonly<{\n true?: BranchCallback<TCurrentJson, TTrueJson>;\n false?: BranchCallback<TCurrentJson, TFalseJson>;\n }>,\n ): WorkflowChain<BranchOutputMatch<TTrueJson, TFalseJson> extends true ? TTrueJson : never> {\n const name = typeof nameOrPredicate === \"string\" ? nameOrPredicate : \"If\";\n const predicate =\n typeof nameOrPredicate === \"string\"\n ? (predicateOrBranches as WorkflowIfPredicate<TCurrentJson>)\n : nameOrPredicate;\n const branches = (typeof nameOrPredicate === \"string\" ? branchesOrUndefined : predicateOrBranches) as Readonly<{\n true?: BranchCallback<TCurrentJson, TTrueJson>;\n false?: BranchCallback<TCurrentJson, TFalseJson>;\n }>;\n const cursor = this.chain.then(new If<TCurrentJson>(name, (item, _index, _items, ctx) => predicate(item, ctx)));\n const trueSteps = branches.true?.(new WorkflowBranchBuilder<TCurrentJson>()).getSteps();\n const falseSteps = branches.false?.(new WorkflowBranchBuilder<TCurrentJson>()).getSteps();\n return new WorkflowChain(\n cursor.when({\n true: trueSteps,\n false: falseSteps,\n }),\n ) as WorkflowChain<BranchOutputMatch<TTrueJson, TFalseJson> extends true ? TTrueJson : never>;\n }\n\n route<TBranchJson>(\n branches: Readonly<Record<string, RouteBranchCallback<TCurrentJson, TBranchJson> | undefined>>,\n ): WorkflowChain<TBranchJson> {\n const mappedBranches = Object.fromEntries(\n Object.entries(branches).map(([port, branchFactory]) => [\n port,\n branchFactory\n ? (branch: ChainCursor<TCurrentJson>) => branchFactory(new WorkflowChain(branch)).chain\n : undefined,\n ]),\n ) as Readonly<\n Record<string, ((branch: ChainCursor<TCurrentJson>) => ChainCursor<TBranchJson> | undefined) | undefined>\n >;\n return new WorkflowChain(\n this.chain.route(\n mappedBranches as Readonly<\n Record<string, (branch: ChainCursor<TCurrentJson>) => ChainCursor<TBranchJson> | undefined>\n >,\n ),\n ) as WorkflowChain<TBranchJson>;\n }\n\n switch<TBranchJson>(\n cfg: Readonly<{\n cases: readonly string[];\n defaultCase: string;\n resolveCaseKey: WorkflowSwitchCaseKeyResolver<TCurrentJson>;\n branches: Readonly<Record<string, RouteBranchCallback<TCurrentJson, TBranchJson> | undefined>>;\n }>,\n ): WorkflowChain<TBranchJson>;\n switch<TBranchJson>(\n name: string,\n cfg: Readonly<{\n cases: readonly string[];\n defaultCase: string;\n resolveCaseKey: WorkflowSwitchCaseKeyResolver<TCurrentJson>;\n branches: Readonly<Record<string, RouteBranchCallback<TCurrentJson, TBranchJson> | undefined>>;\n }>,\n id?: string,\n ): WorkflowChain<TBranchJson>;\n switch<TBranchJson>(\n nameOrCfg:\n | string\n | Readonly<{\n cases: readonly string[];\n defaultCase: string;\n resolveCaseKey: WorkflowSwitchCaseKeyResolver<TCurrentJson>;\n branches: Readonly<Record<string, RouteBranchCallback<TCurrentJson, TBranchJson> | undefined>>;\n }>,\n cfgOrUndefined?: Readonly<{\n cases: readonly string[];\n defaultCase: string;\n resolveCaseKey: WorkflowSwitchCaseKeyResolver<TCurrentJson>;\n branches: Readonly<Record<string, RouteBranchCallback<TCurrentJson, TBranchJson> | undefined>>;\n }>,\n id?: string,\n ): WorkflowChain<TBranchJson> {\n const name = typeof nameOrCfg === \"string\" ? nameOrCfg : \"Switch\";\n const cfg = (typeof nameOrCfg === \"string\" ? cfgOrUndefined : nameOrCfg)!;\n const switched = this.then(\n new Switch<TCurrentJson>(\n name,\n {\n cases: cfg.cases,\n defaultCase: cfg.defaultCase,\n resolveCaseKey: (item, _index, _items, ctx) => cfg.resolveCaseKey(item, ctx),\n },\n id,\n ),\n ) as WorkflowChain<TCurrentJson>;\n return switched.route(cfg.branches);\n }\n\n agent<TOutputSchema extends z.ZodTypeAny>(\n options: WorkflowAgentOptions<TCurrentJson, TOutputSchema>,\n ): WorkflowChain<z.output<TOutputSchema>>;\n agent(options: WorkflowAgentOptions<TCurrentJson, undefined>): WorkflowChain<Record<string, unknown>>;\n agent<TOutputSchema extends z.ZodTypeAny>(\n name: string,\n options: WorkflowAgentOptions<TCurrentJson, TOutputSchema | undefined>,\n ): WorkflowChain<TOutputSchema extends z.ZodTypeAny ? z.output<TOutputSchema> : Record<string, unknown>>;\n agent<TOutputSchema extends z.ZodTypeAny>(\n nameOrOptions: string | WorkflowAgentOptions<TCurrentJson, TOutputSchema | undefined>,\n optionsOrUndefined?: WorkflowAgentOptions<TCurrentJson, TOutputSchema | undefined>,\n ): WorkflowChain<TOutputSchema extends z.ZodTypeAny ? z.output<TOutputSchema> : Record<string, unknown>> {\n return this.then(WorkflowAgentNodeFactory.create(nameOrOptions, optionsOrUndefined)) as WorkflowChain<\n TOutputSchema extends z.ZodTypeAny ? z.output<TOutputSchema> : Record<string, unknown>\n >;\n }\n\n node<TConfig extends CredentialJsonRecord, TInputJson, TOutputJson>(\n definitionOrKey: DefinedNode<string, TConfig, TInputJson, TOutputJson> | string,\n config: DefinedNodeConfigInput<TConfig, TCurrentJson>,\n name?: string,\n id?: string,\n ): TCurrentJson extends TInputJson ? WorkflowChain<TOutputJson> : never {\n const definition = WorkflowDefinedNodeResolver.resolve(\n definitionOrKey as DefinedNode<string, Record<string, unknown>, unknown, unknown> | string,\n ) as DefinedNode<string, TConfig, TInputJson, TOutputJson>;\n return this.then(\n definition.create(config, name, id) as unknown as RunnableNodeConfig<TCurrentJson, TOutputJson>,\n ) as TCurrentJson extends TInputJson ? WorkflowChain<TOutputJson> : never;\n }\n\n build(): WorkflowDefinition {\n return this.chain.build();\n }\n}\n","import { ChainCursor } from \"@codemation/core\";\nimport { ManualTrigger } from \"../nodes/ManualTriggerFactory\";\nimport { createWorkflowBuilder } from \"../workflowBuilder.types\";\nimport { WorkflowChain } from \"./WorkflowChain.types\";\n\nexport class WorkflowAuthoringBuilder {\n constructor(\n private readonly id: string,\n private readonly workflowName: string = id,\n ) {}\n\n name(name: string): WorkflowAuthoringBuilder {\n return new WorkflowAuthoringBuilder(this.id, name);\n }\n\n manualTrigger<TOutputJson>(defaultItems: TOutputJson | ReadonlyArray<TOutputJson>): WorkflowChain<TOutputJson>;\n manualTrigger<TOutputJson>(\n name: string,\n defaultItems?: TOutputJson | ReadonlyArray<TOutputJson>,\n id?: string,\n ): WorkflowChain<TOutputJson>;\n manualTrigger<TOutputJson>(\n nameOrDefaultItems: string | TOutputJson | ReadonlyArray<TOutputJson>,\n defaultItemsOrUndefined?: TOutputJson | ReadonlyArray<TOutputJson>,\n id?: string,\n ): WorkflowChain<TOutputJson> {\n const builder = createWorkflowBuilder({ id: this.id, name: this.workflowName });\n if (typeof nameOrDefaultItems === \"string\") {\n return new WorkflowChain(\n builder.trigger(\n new ManualTrigger<TOutputJson>(\n nameOrDefaultItems,\n defaultItemsOrUndefined as TOutputJson | ReadonlyArray<TOutputJson>,\n id,\n ),\n ) as ChainCursor<TOutputJson>,\n );\n }\n return new WorkflowChain(\n builder.trigger(new ManualTrigger<TOutputJson>(\"Manual trigger\", nameOrDefaultItems)) as ChainCursor<TOutputJson>,\n );\n }\n}\n","export type { WorkflowAgentMessages, WorkflowAgentOptions } from \"./workflowAuthoring/WorkflowAuthoringOptions.types\";\nexport { WorkflowAuthoringBuilder } from \"./workflowAuthoring/WorkflowAuthoringBuilder.types\";\nexport { WorkflowBranchBuilder } from \"./workflowAuthoring/WorkflowBranchBuilder.types\";\nexport { WorkflowChain } from \"./workflowAuthoring/WorkflowChain.types\";\n\nimport { WorkflowAuthoringBuilder } from \"./workflowAuthoring/WorkflowAuthoringBuilder.types\";\n\nexport function workflow(id: string): WorkflowAuthoringBuilder {\n return new WorkflowAuthoringBuilder(id);\n}\n","import type { NodeDefinition, WorkflowDefinition, WorkflowNodeConnection } from \"@codemation/core\";\nimport { AgentConfigInspector, AgentConnectionNodeCollector } from \"@codemation/core\";\n\nimport { AIAgentNode } from \"../nodes/AIAgentNode\";\nimport { ConnectionCredentialNode } from \"../nodes/ConnectionCredentialNode\";\nimport { ConnectionCredentialNodeConfigFactory } from \"../nodes/ConnectionCredentialNodeConfigFactory\";\n\n/**\n * Materializes connection-owned child nodes and {@link WorkflowDefinition.connections} for AI agent nodes.\n */\nexport class AIAgentConnectionWorkflowExpander {\n constructor(private readonly connectionCredentialNodeConfigFactory: ConnectionCredentialNodeConfigFactory) {}\n\n expand(workflow: WorkflowDefinition): WorkflowDefinition {\n const existingChildIds = this.collectExistingChildIds(workflow);\n const connectionsByParentAndName = this.createConnectionsByParentAndName(workflow);\n const extraNodes: NodeDefinition[] = [];\n let connectionsChanged = false;\n\n for (const node of workflow.nodes) {\n if (node.type !== AIAgentNode || !AgentConfigInspector.isAgentNodeConfig(node.config)) {\n continue;\n }\n for (const connectionNode of AgentConnectionNodeCollector.collect(node.id, node.config)) {\n if (!existingChildIds.has(connectionNode.nodeId)) {\n this.assertNoIdCollision(workflow, extraNodes, existingChildIds, connectionNode.nodeId);\n extraNodes.push({\n id: connectionNode.nodeId,\n kind: \"node\",\n type: ConnectionCredentialNode,\n name: connectionNode.name,\n config: this.connectionCredentialNodeConfigFactory.create(\n connectionNode.typeName,\n connectionNode.credentialSource,\n ),\n });\n }\n const connectionKey = this.connectionKey(connectionNode.parentNodeId, connectionNode.connectionName);\n const existingConnection = connectionsByParentAndName.get(connectionKey);\n if (!existingConnection) {\n connectionsByParentAndName.set(connectionKey, {\n parentNodeId: connectionNode.parentNodeId,\n connectionName: connectionNode.connectionName,\n childNodeIds: [connectionNode.nodeId],\n });\n connectionsChanged = true;\n continue;\n }\n if (!existingConnection.childNodeIds.includes(connectionNode.nodeId)) {\n connectionsByParentAndName.set(connectionKey, {\n ...existingConnection,\n childNodeIds: [...existingConnection.childNodeIds, connectionNode.nodeId],\n });\n connectionsChanged = true;\n }\n }\n }\n\n if (extraNodes.length === 0 && !connectionsChanged) {\n return workflow;\n }\n\n return {\n ...workflow,\n nodes: [...workflow.nodes, ...extraNodes],\n connections: [...connectionsByParentAndName.values()],\n };\n }\n\n private createConnectionsByParentAndName(workflow: WorkflowDefinition): Map<string, WorkflowNodeConnection> {\n const existingByParentAndName = new Map<string, WorkflowNodeConnection>();\n for (const connection of workflow.connections ?? []) {\n existingByParentAndName.set(this.connectionKey(connection.parentNodeId, connection.connectionName), connection);\n }\n return existingByParentAndName;\n }\n\n private collectExistingChildIds(workflow: WorkflowDefinition): ReadonlySet<string> {\n const ids = new Set<string>();\n for (const connection of workflow.connections ?? []) {\n for (const childId of connection.childNodeIds) {\n ids.add(childId);\n }\n }\n return ids;\n }\n\n private connectionKey(parentNodeId: string, connectionName: string): string {\n return `${parentNodeId}\\0${connectionName}`;\n }\n\n private assertNoIdCollision(\n workflow: WorkflowDefinition,\n pending: ReadonlyArray<NodeDefinition>,\n existingChildIds: ReadonlySet<string>,\n id: string,\n ): void {\n if (pending.some((n) => n.id === id)) {\n throw new Error(\n `AIAgent connection expansion: node id \"${id}\" already exists. Rename the conflicting node or adjust the workflow.`,\n );\n }\n if (workflow.nodes.some((n) => n.id === id) && !existingChildIds.has(id)) {\n throw new Error(\n `AIAgent connection expansion: node id \"${id}\" already exists. Rename the conflicting node or adjust the workflow.`,\n );\n }\n }\n}\n","import type { CredentialRequirement, RunnableNodeConfig } from \"@codemation/core\";\n\nimport { ConnectionCredentialNode } from \"./ConnectionCredentialNode\";\n\nexport class ConnectionCredentialNodeConfig implements RunnableNodeConfig {\n readonly kind = \"node\" as const;\n readonly type = ConnectionCredentialNode;\n\n constructor(\n public readonly name: string,\n private readonly credentialSource: { getCredentialRequirements?: () => ReadonlyArray<CredentialRequirement> },\n ) {}\n\n getCredentialRequirements(): ReadonlyArray<CredentialRequirement> {\n return this.credentialSource.getCredentialRequirements?.() ?? [];\n }\n}\n","import type { CredentialRequirement } from \"@codemation/core\";\n\nimport { ConnectionCredentialNodeConfig } from \"./ConnectionCredentialNodeConfig\";\n\nexport class ConnectionCredentialNodeConfigFactory {\n create(\n name: string,\n credentialSource: { getCredentialRequirements?: () => ReadonlyArray<CredentialRequirement> },\n ): ConnectionCredentialNodeConfig {\n return new ConnectionCredentialNodeConfig(name, credentialSource);\n }\n}\n","import { defineNode } from \"@codemation/core\";\nimport { z } from \"zod\";\n\nexport const collectionInsertNode = defineNode({\n key: \"collection-insert\",\n title: \"Collection: Insert\",\n description: \"Insert a new row into a collection.\",\n icon: \"lucide:boxes\",\n configSchema: z.object({\n collectionName: z.string(),\n data: z.record(z.string(), z.unknown()),\n }),\n async execute(_args, { config, execution }) {\n const store = execution.collections?.[config.collectionName];\n if (!store) {\n throw new Error(\n `Collection \"${config.collectionName}\" is not registered. Add defineCollection to your codemation config.`,\n );\n }\n return await store.insert(config.data);\n },\n});\n","import { defineNode } from \"@codemation/core\";\nimport { z } from \"zod\";\n\nexport const collectionGetNode = defineNode({\n key: \"collection-get\",\n title: \"Collection: Get\",\n description: \"Get a single row by id from a collection.\",\n icon: \"lucide:layers\",\n configSchema: z.object({\n collectionName: z.string(),\n id: z.string(),\n }),\n async execute(_args, { config, execution }) {\n const store = execution.collections?.[config.collectionName];\n if (!store) {\n throw new Error(\n `Collection \"${config.collectionName}\" is not registered. Add defineCollection to your codemation config.`,\n );\n }\n const row = await store.get(config.id);\n if (row === null) {\n return [];\n }\n return row;\n },\n});\n","import { defineNode } from \"@codemation/core\";\nimport { z } from \"zod\";\n\nexport const collectionFindOneNode = defineNode({\n key: \"collection-find-one\",\n title: \"Collection: Find One\",\n description: \"Find a single row matching a filter in a collection.\",\n icon: \"lucide:filter\",\n configSchema: z.object({\n collectionName: z.string(),\n where: z.record(z.string(), z.unknown()),\n }),\n async execute(_args, { config, execution }) {\n const store = execution.collections?.[config.collectionName];\n if (!store) {\n throw new Error(\n `Collection \"${config.collectionName}\" is not registered. Add defineCollection to your codemation config.`,\n );\n }\n const row = await store.findOne(config.where);\n if (row === null) {\n return [];\n }\n return row;\n },\n});\n","import { defineNode } from \"@codemation/core\";\nimport { z } from \"zod\";\n\nexport const collectionListNode = defineNode({\n key: \"collection-list\",\n title: \"Collection: List\",\n description: \"List rows from a collection with optional pagination and filtering.\",\n icon: \"lucide:split\",\n configSchema: z.object({\n collectionName: z.string(),\n limit: z.number().int().positive().optional(),\n offset: z.number().int().nonnegative().optional(),\n where: z.record(z.string(), z.unknown()).optional(),\n }),\n async execute(_args, { config, execution }) {\n const store = execution.collections?.[config.collectionName];\n if (!store) {\n throw new Error(\n `Collection \"${config.collectionName}\" is not registered. Add defineCollection to your codemation config.`,\n );\n }\n const { rows } = await store.list({\n limit: config.limit,\n offset: config.offset,\n where: config.where,\n });\n // Emit one item per row per AGENTS.md engine/node contract.\n return [...rows];\n },\n});\n","import { defineNode } from \"@codemation/core\";\nimport { z } from \"zod\";\n\nexport const collectionUpdateNode = defineNode({\n key: \"collection-update\",\n title: \"Collection: Update\",\n description: \"Update a row by id in a collection.\",\n icon: \"lucide:square-pen\",\n configSchema: z.object({\n collectionName: z.string(),\n id: z.string(),\n patch: z.record(z.string(), z.unknown()),\n }),\n async execute(_args, { config, execution }) {\n const store = execution.collections?.[config.collectionName];\n if (!store) {\n throw new Error(\n `Collection \"${config.collectionName}\" is not registered. Add defineCollection to your codemation config.`,\n );\n }\n return await store.update(config.id, config.patch);\n },\n});\n","import { defineNode } from \"@codemation/core\";\nimport { z } from \"zod\";\n\nexport const collectionDeleteNode = defineNode({\n key: \"collection-delete\",\n title: \"Collection: Delete\",\n description: \"Delete a row by id from a collection.\",\n icon: \"lucide:braces\",\n configSchema: z.object({\n collectionName: z.string(),\n id: z.string(),\n }),\n async execute(_args, { config, execution }) {\n const store = execution.collections?.[config.collectionName];\n if (!store) {\n throw new Error(\n `Collection \"${config.collectionName}\" is not registered. Add defineCollection to your codemation config.`,\n );\n }\n const result = await store.delete(config.id);\n return { deleted: result.deleted, id: config.id };\n },\n});\n"],"x_google_ignoreList":[10,11,12,13,14,15,16,17,18,19,20,21,22,31,32,33,34],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAMA,MAAa,+DAAwC;CACnD,KAAK;CACL,OAAO;CACP,aAAa;CACb,QAAQ;EACN,WAAW;GACT,OAAO;GACP,MAAM;GACN,UAAU;GACV,aAAa;GACd;EACD,MAAM;GACJ,OAAO;GACP,MAAM;GACN,UAAU;GACV,aAAa;GACd;EACF;CACD,QAAQ,EACN,QAAQ;EACN,OAAO;EACP,MAAM;EACN,UAAU;EACV,UAAU;EACX,EACF;CACD,MAAM,cAAc,MAAkC;EACpD,MAAM,SAAS,OAAO,KAAK,SAAS,UAAU,GAAG;AACjD,MAAI,CAAC,OACH,OAAM,IAAI,MAAM,iEAAiE;EAGnF,MAAM,UADY,OAAO,KAAK,aAAa,aAAa,SAAS,CAAC,aAAa,KACjD;EAC9B,MAAM,cAAc,UAAU,YAAY;EAC1C,MAAM,YAAY,OAAO,KAAK,aAAa,QAAQ,GAAG,CAAC,MAAM,IAAI;AAEjE,SAAO,EACL,iBAAiB,UAA+B;AAC9C,OAAI,QACF,QAAO,EAAE,OAAO,GAAG,YAAY,QAAQ,EAAE;AAE3C,UAAO,EAAE,SAAS,GAAG,YAAY,QAAQ,EAAE;KAE9C;;CAEH,MAAM,KAAK,MAAM;EACf,MAAM,SAAS,OAAO,KAAK,SAAS,UAAU,GAAG;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