@powerhousedao/reactor-workflow 6.2.3-dev.78 → 6.2.3-dev.80

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.
@@ -1 +1 @@
1
- {"version":3,"file":"worker-entry.js","names":["isObject","util.jsonStringifyReplacer","core.$ZodAsyncError","util.finalizeIssue","core.config","errors.$ZodRealError","number","boolean","util.nullish","util.codePointLength","util.getLengthableOrigin","util.aborted","util.explicitlyAborted","core.$ZodAsyncError","util.hide","util.finalizeIssue","core.config","regexes.anyString","regexes.number","regexes.boolean","util.prefixIssues","util.optionalKeys","util.cached","util.isObject","util.cleanRegex","util.rawShape","util.isPlainObject","util.getEnumValues","util.escapeRegex","core.$ZodEncodeError","util.issue","util.normalizeParams","_void","checks.$ZodCheckMinLength","checks.$ZodCheckRegex","parse.parse","parse.parseAsync","parse.safeParse","parse.safeParseAsync","core.clone","core._string","core._url","number","core._number","core._boolean","core._any","core._unknown","core._void","util.normalizeParams","optional","core._custom","core._coercedNumber","schemas.ZodMiniNumber","z.object","z.string","z.optional","z.boolean","z.enum","z.literal","z.any","z.unknown","z.array","z.number","z.void","z.object","z.optional","z.boolean","z.unknown","z.array","z.string","z.union","z.record","Property","z.object","z.enum","z.optional","z.string","z.boolean","z.record","z.union","z.unknown","z.array","z.literal","z.any","z.object","z.optional","z.number","z.unknown","z.record","z.string","z.literal","z.enum","z.regex","z.pipe","z.transform","z.nullable","z.array","z.minLength","z.discriminatedUnion","z.url","z.union","z.boolean","z.coerce.number","z.custom","fromWire","ipaddr","utc","timezone","dayjs","MIME_EXTENSIONS","isRecord","isRecord","installed"],"sources":["../src/pieces/activepieces/context/stubs.ts","../src/pieces/activepieces/worker/json-safe.ts","../../../node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/core/util.js","../../../node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/core/core.js","../../../node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/core/errors.js","../../../node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/core/parse.js","../../../node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/core/regexes.js","../../../node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/core/checks.js","../../../node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/core/versions.js","../../../node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/core/schemas.js","../../../node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/core/api.js","../../../node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/mini/schemas.js","../../../node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/mini/coerce.js","../../pieces-framework/dist/markdown-property-DMfHjEiL.js","../../pieces-framework/dist/input-BHkj_oP5.js","../../pieces-framework/dist/authentication-o-4CdAPR.js","../../../node_modules/.pnpm/nanoid@3.3.17/node_modules/nanoid/index.js","../../pieces-framework/dist/index.js","../src/pieces/activepieces/context/store-scope.ts","../src/pieces/activepieces/context/action.ts","../src/pieces/activepieces/worker/protocol.ts","../src/pieces/activepieces/indeterminate.ts","../src/pieces/activepieces/worker/host-call.ts","../src/pieces/activepieces/context/remote-store.ts","../src/pieces/activepieces/context/remote-output.ts","../src/pieces/activepieces/worker/logs.ts","../src/pieces/activepieces/worker/reactor-provider.ts","../../../node_modules/.pnpm/ipaddr.js@2.3.0/node_modules/ipaddr.js/lib/ipaddr.js","../../../node_modules/.pnpm/dayjs@1.11.9/node_modules/dayjs/dayjs.min.js","../../../node_modules/.pnpm/dayjs@1.11.9/node_modules/dayjs/plugin/timezone.js","../../../node_modules/.pnpm/dayjs@1.11.9/node_modules/dayjs/plugin/utc.js","../../pieces-framework/dist/host.js","../src/pieces/activepieces/worker/redact.ts","../src/pieces/activepieces/context/check.ts","../src/pieces/activepieces/context/limits.ts","../src/pieces/activepieces/context/files.ts","../src/pieces/activepieces/context/normalize.ts","../src/pieces/activepieces/types.ts","../src/pieces/activepieces/context/props.ts","../src/pieces/activepieces/context/trigger.ts","../../pieces-framework/dist/workflow.js","../src/pieces/activepieces/unsupported.ts","../src/pieces/activepieces/descriptor.ts","../src/pieces/activepieces/loader.ts","../src/pieces/activepieces/worker/egress.ts","../src/pieces/activepieces/worker/timings.ts","../src/pieces/activepieces/worker/entry.ts","../src/pieces/activepieces/worker/reactor-rpc.ts","../src/worker/reactor.ts","../src/worker/entry.ts"],"sourcesContent":["export class UnsupportedContextMemberError extends Error {\n readonly member: string;\n\n constructor(member: string) {\n super(\n `Piece used unimplemented context member \"${member}\". ` +\n `Implement it in the adapter or reject the piece at conformance time.`,\n );\n this.name = \"UnsupportedContextMemberError\";\n this.member = member;\n }\n}\n\n// Traps calls and member reads so both `ctx.files.write(...)` and\n// `ctx.server.apiUrl` throw with the full member path.\nexport function throwingStub(memberPath: string): unknown {\n return new Proxy(function stub() {}, {\n get(_target, prop) {\n // `then` and symbols stay inert so `await`/inspection don't false-trip.\n if (typeof prop !== \"string\" || prop === \"then\") return undefined;\n throw new UnsupportedContextMemberError(`${memberPath}.${prop}`);\n },\n apply() {\n throw new UnsupportedContextMemberError(memberPath);\n },\n });\n}\n\n// Wraps a context object so every top-level read is recorded; reads of\n// members outside the documented surface are flagged as UNDOCUMENTED.\nexport function withTouchTracking<T extends object>(\n base: T,\n touched: Set<string>,\n onTouch?: (member: string) => void,\n): T {\n return new Proxy(base, {\n get(target, prop, receiver) {\n if (typeof prop === \"string\" && prop !== \"then\") {\n const member = prop in target ? prop : `UNDOCUMENTED:${prop}`;\n touched.add(member);\n onTouch?.(member);\n }\n return Reflect.get(target, prop, receiver) as unknown;\n },\n });\n}\n","// Everything the child sends crosses a structured-clone boundary. A piece's\n// own objects routinely do not survive it, so they are flattened first.\nexport function jsonSafe(value: unknown): unknown {\n try {\n return JSON.parse(JSON.stringify(value)) as unknown;\n } catch {\n return String(value);\n }\n}\n","import { globalConfig } from \"./core.js\";\n// functions\nexport function assertEqual(val) {\n return val;\n}\nexport function assertNotEqual(val) {\n return val;\n}\nexport function toZod() {\n return (schema) => schema;\n}\nexport function assertIs(_arg) { }\nexport function assertNever(_x) {\n throw new Error(\"Unexpected value in exhaustive check\");\n}\nexport function assert(_) { }\nexport function getEnumValues(entries) {\n const numericValues = Object.values(entries).filter((v) => typeof v === \"number\");\n const values = Object.entries(entries)\n .filter(([k, _]) => numericValues.indexOf(+k) === -1)\n .map(([_, v]) => v);\n return values;\n}\nexport function joinValues(array, separator = \"|\") {\n return array.map((val) => stringifyPrimitive(val)).join(separator);\n}\nexport function jsonStringifyReplacer(_, value) {\n if (typeof value === \"bigint\")\n return value.toString();\n return value;\n}\n// the accessor lives on a shared prototype: an own accessor makes every box a dictionary-mode object (~360 B and a slow load per read against ~100 B and an inlined getter here)\nclass Cached {\n constructor(getter) {\n this._getter = getter;\n this._value = undefined;\n }\n get value() {\n const getter = this._getter;\n if (getter !== undefined) {\n this._value = getter();\n this._getter = undefined;\n }\n return this._value;\n }\n}\nexport function cached(getter) {\n return new Cached(getter);\n}\nexport function nullish(input) {\n return input === null || input === undefined;\n}\nexport function cleanRegex(source) {\n const start = source.startsWith(\"^\") ? 1 : 0;\n const end = source.endsWith(\"$\") ? source.length - 1 : source.length;\n return source.slice(start, end);\n}\nexport function floatSafeRemainder(val, step) {\n const ratio = val / step;\n const roundedRatio = Math.round(ratio);\n // `val` and `step` each round to a double before the division rounds again, so a true decimal multiple's quotient can sit up to 1.5 of these scaled epsilons from the integer. A 1x tolerance therefore rejected 2.03 as a multiple of 0.07; 4x covers the worst case with margin.\n const tolerance = 4 * Number.EPSILON * Math.max(Math.abs(ratio), 1);\n if (Math.abs(ratio - roundedRatio) < tolerance)\n return 0;\n return ratio - roundedRatio;\n}\nconst EVALUATING = /* @__PURE__*/ Symbol(\"evaluating\");\nexport function defineLazy(object, key, getter) {\n let value = undefined;\n Object.defineProperty(object, key, {\n get() {\n if (value === EVALUATING) {\n // Circular reference detected, return undefined to break the cycle\n return undefined;\n }\n if (value === undefined) {\n value = EVALUATING;\n value = getter();\n }\n return value;\n },\n set(v) {\n Object.defineProperty(object, key, {\n value: v,\n // configurable: true,\n });\n // object[key] = v;\n },\n configurable: true,\n });\n}\nexport function objectClone(obj) {\n return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj));\n}\nexport function assignProp(target, prop, value) {\n Object.defineProperty(target, prop, {\n value,\n writable: true,\n enumerable: true,\n configurable: true,\n });\n}\n/**\n * Whichever object a def's `shape` currently answers from: the one the caller passed until the first read, the frozen copy after it.\n *\n * Its keys and descriptors read without invoking anything, which is what lets a discriminated union check its discriminator, and the cycle walk read a shape, without resolving a getter that references the schema being constructed. A def that answers `shape` from an accessor of its own has none.\n */\nexport function rawShape(def) {\n const desc = Object.getOwnPropertyDescriptor(def, \"shape\");\n return desc?.get ? desc.get.raw : desc?.value;\n}\n// where a builder reads its source's keys and descriptors, resolving only a shape a def answers for itself. A shape resolves by object spread, so only its enumerable keys are ever part of it.\nfunction sourceShape(schema) {\n return rawShape(schema._zod.def) ?? schema._zod.def.shape;\n}\n// a key whose value is not settled yet, self-caching so every read after the first gets the same one\nfunction deferProp(target, key, getter) {\n Object.defineProperty(target, key, {\n get() {\n const value = getter();\n assignProp(this, key, value);\n return value;\n },\n enumerable: true,\n configurable: true,\n });\n}\n// Writes a settled key. A plain assignment is much cheaper than `defineProperty` and produces the same descriptor, but it runs whatever setter already answers to the key — an accessor this shape deferred, or an inherited one, which `__proto__` has on every object and prototype pollution can add for any name.\nfunction putProp(target, key, value) {\n if (key in target)\n assignProp(target, key, value);\n else\n target[key] = value;\n}\n/**\n * Copies `keys` of `source`'s shape onto `target`, each value passed through `wrap`.\n *\n * A key the source has resolved is copied through now, so the derived shape states it outright and nothing has to resolve it to learn what it holds. A key the source still defers stays deferred, and reads back through the source's own `shape`, so it resolves once and both shapes get that one schema.\n */\nfunction mirrorShape(target, source, keys, wrap) {\n const raw = sourceShape(source);\n for (const key of keys) {\n const desc = Object.getOwnPropertyDescriptor(raw, key);\n if (!desc.enumerable)\n continue;\n if (desc.get) {\n deferProp(target, key, () => {\n const value = source._zod.def.shape[key];\n return wrap ? wrap(value, key) : value;\n });\n }\n else\n putProp(target, key, wrap ? wrap(desc.value, key) : desc.value);\n }\n}\n// same, for a plain shape a caller passed rather than a schema's\nfunction mirrorProps(target, source) {\n for (const key of Reflect.ownKeys(source)) {\n const desc = Object.getOwnPropertyDescriptor(source, key);\n if (!desc.enumerable)\n continue;\n if (desc.get)\n deferProp(target, key, () => source[key]);\n else\n putProp(target, key, desc.value);\n }\n}\nexport function mergeDefs(...defs) {\n const mergedDescriptors = {};\n for (const def of defs) {\n const descriptors = Object.getOwnPropertyDescriptors(def);\n Object.assign(mergedDescriptors, descriptors);\n }\n return Object.defineProperties({}, mergedDescriptors);\n}\nexport function cloneDef(schema) {\n return mergeDefs(schema._zod.def);\n}\nexport function getElementAtPath(obj, path) {\n if (!path)\n return obj;\n return path.reduce((acc, key) => acc?.[key], obj);\n}\nexport function promiseAllObject(promisesObj) {\n const keys = Object.keys(promisesObj);\n const promises = keys.map((key) => promisesObj[key]);\n return Promise.all(promises).then((results) => {\n const resolvedObj = {};\n for (let i = 0; i < keys.length; i++) {\n resolvedObj[keys[i]] = results[i];\n }\n return resolvedObj;\n });\n}\nexport function randomString(length = 10) {\n const chars = \"abcdefghijklmnopqrstuvwxyz\";\n let str = \"\";\n for (let i = 0; i < length; i++) {\n str += chars[Math.floor(Math.random() * chars.length)];\n }\n return str;\n}\nexport function esc(str) {\n return JSON.stringify(str);\n}\nexport function slugify(input) {\n return input\n .toLowerCase()\n .trim()\n .replace(/[^\\w\\s-]/g, \"\")\n .replace(/[\\s_-]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n}\nexport const captureStackTrace = (\"captureStackTrace\" in Error ? Error.captureStackTrace : (..._args) => { });\nexport function isObject(data) {\n return typeof data === \"object\" && data !== null && !Array.isArray(data);\n}\nexport const allowsEval = /* @__PURE__*/ cached(() => {\n // Skip the probe under `jitless`: strict CSPs report the caught `new Function` as a `securitypolicyviolation` even though the throw is swallowed.\n if (globalConfig.jitless) {\n return false;\n }\n // @ts-ignore\n if (typeof navigator !== \"undefined\" && navigator?.userAgent?.includes(\"Cloudflare\")) {\n return false;\n }\n try {\n const F = Function;\n new F(\"\");\n return true;\n }\n catch (_) {\n return false;\n }\n});\nexport function isPlainObject(o) {\n if (isObject(o) === false)\n return false;\n // modified constructor\n const ctor = o.constructor;\n if (ctor === undefined)\n return true;\n if (typeof ctor !== \"function\")\n return true;\n // modified prototype\n const prot = ctor.prototype;\n if (isObject(prot) === false)\n return false;\n // ctor doesn't have static `isPrototypeOf`\n if (Object.prototype.hasOwnProperty.call(prot, \"isPrototypeOf\") === false) {\n return false;\n }\n return true;\n}\nexport function shallowClone(o) {\n if (isPlainObject(o))\n return { ...o };\n if (Array.isArray(o))\n return [...o];\n if (o instanceof Map)\n return new Map(o);\n if (o instanceof Set)\n return new Set(o);\n return o;\n}\nexport function numKeys(data) {\n let keyCount = 0;\n for (const key in data) {\n if (Object.prototype.hasOwnProperty.call(data, key)) {\n keyCount++;\n }\n }\n return keyCount;\n}\nexport const getParsedType = (data) => {\n const t = typeof data;\n switch (t) {\n case \"undefined\":\n return \"undefined\";\n case \"string\":\n return \"string\";\n case \"number\":\n return Number.isNaN(data) ? \"nan\" : \"number\";\n case \"boolean\":\n return \"boolean\";\n case \"function\":\n return \"function\";\n case \"bigint\":\n return \"bigint\";\n case \"symbol\":\n return \"symbol\";\n case \"object\":\n if (Array.isArray(data)) {\n return \"array\";\n }\n if (data === null) {\n return \"null\";\n }\n if (data.then && typeof data.then === \"function\" && data.catch && typeof data.catch === \"function\") {\n return \"promise\";\n }\n if (typeof Map !== \"undefined\" && data instanceof Map) {\n return \"map\";\n }\n if (typeof Set !== \"undefined\" && data instanceof Set) {\n return \"set\";\n }\n if (typeof Date !== \"undefined\" && data instanceof Date) {\n return \"date\";\n }\n // @ts-ignore\n if (typeof File !== \"undefined\" && data instanceof File) {\n return \"file\";\n }\n return \"object\";\n default:\n throw new Error(`Unknown data type: ${t}`);\n }\n};\nexport const propertyKeyTypes = /* @__PURE__*/ new Set([\"string\", \"number\", \"symbol\"]);\nexport const primitiveTypes = /* @__PURE__*/ new Set([\n \"string\",\n \"number\",\n \"bigint\",\n \"boolean\",\n \"symbol\",\n \"undefined\",\n]);\nexport function escapeRegex(str) {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n// zod-specific utils\nexport function clone(inst, def, params) {\n const cl = new inst._zod.constr(def ?? inst._zod.def);\n if (!def || params?.parent)\n cl._zod.parent = inst;\n return cl;\n}\nexport function normalizeParams(_params) {\n const params = _params;\n if (!params)\n return {};\n if (typeof params === \"string\")\n return { error: () => params };\n if (params?.message !== undefined) {\n if (params?.error !== undefined)\n throw new Error(\"Cannot specify both `message` and `error` params\");\n params.error = params.message;\n }\n delete params.message;\n if (typeof params.error === \"string\")\n return { ...params, error: () => params.error };\n return params;\n}\nexport function createTransparentProxy(getter) {\n let target;\n return new Proxy({}, {\n get(_, prop, receiver) {\n target ?? (target = getter());\n return Reflect.get(target, prop, receiver);\n },\n set(_, prop, value, receiver) {\n target ?? (target = getter());\n return Reflect.set(target, prop, value, receiver);\n },\n has(_, prop) {\n target ?? (target = getter());\n return Reflect.has(target, prop);\n },\n deleteProperty(_, prop) {\n target ?? (target = getter());\n return Reflect.deleteProperty(target, prop);\n },\n ownKeys(_) {\n target ?? (target = getter());\n return Reflect.ownKeys(target);\n },\n getOwnPropertyDescriptor(_, prop) {\n target ?? (target = getter());\n return Reflect.getOwnPropertyDescriptor(target, prop);\n },\n defineProperty(_, prop, descriptor) {\n target ?? (target = getter());\n return Reflect.defineProperty(target, prop, descriptor);\n },\n });\n}\nexport function stringifyPrimitive(value) {\n if (typeof value === \"bigint\")\n return value.toString() + \"n\";\n if (typeof value === \"string\")\n return `\"${value}\"`;\n return `${value}`;\n}\nexport function optionalKeys(shape) {\n return Object.keys(shape).filter((k) => {\n return shape[k]._zod.optin !== undefined && shape[k]._zod.optout === \"optional\";\n });\n}\n// Wrapped in a `@__PURE__` IIFE: esbuild never tree-shakes a top-level initializer that contains a member access on `Number`, so the bare object literal survived into every bundle.\nexport const NUMBER_FORMAT_RANGES = /*@__PURE__*/ (() => ({\n safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],\n int32: [-2147483648, 2147483647],\n uint32: [0, 4294967295],\n float32: [-3.4028234663852886e38, 3.4028234663852886e38],\n float64: [-Number.MAX_VALUE, Number.MAX_VALUE],\n}))();\nexport const BIGINT_FORMAT_RANGES = {\n int64: [/* @__PURE__*/ BigInt(\"-9223372036854775808\"), /* @__PURE__*/ BigInt(\"9223372036854775807\")],\n uint64: [/* @__PURE__*/ BigInt(0), /* @__PURE__*/ BigInt(\"18446744073709551615\")],\n};\nexport function pick(schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".pick() cannot be used on object schemas containing refinements\");\n }\n const newShape = {};\n mirrorShape(newShape, schema, maskedKeys(schema, mask));\n return clone(schema, mergeDefs(currDef, { shape: newShape, checks: [] }));\n}\n// the mask keys that select something, checked against the source's shape without resolving it\nfunction maskedKeys(schema, mask) {\n const raw = sourceShape(schema);\n const keys = [];\n // `for...in` skips symbols, so a symbol in the mask would select nothing\n for (const key of Reflect.ownKeys(mask)) {\n if (!Object.getOwnPropertyDescriptor(raw, key)?.enumerable) {\n throw new Error(`Unrecognized key: \"${String(key)}\"`);\n }\n if (mask[key])\n keys.push(key);\n }\n return keys;\n}\nexport function omit(schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".omit() cannot be used on object schemas containing refinements\");\n }\n const omitted = new Set(maskedKeys(schema, mask));\n const newShape = {};\n mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)).filter((key) => !omitted.has(key)));\n return clone(schema, mergeDefs(currDef, { shape: newShape, checks: [] }));\n}\nexport function extend(schema, shape) {\n if (!isPlainObject(shape)) {\n throw new Error(\"Invalid input to extend: expected a plain object\");\n }\n const checks = schema._zod.def.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n // Only throw if new shape overlaps with existing shape. Use getOwnPropertyDescriptor to check key existence without accessing values\n const existingShape = sourceShape(schema);\n for (const key of Reflect.ownKeys(shape)) {\n if (Object.getOwnPropertyDescriptor(existingShape, key) !== undefined) {\n throw new Error(\"Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.\");\n }\n }\n }\n return clone(schema, mergeDefs(schema._zod.def, { shape: extended(schema, shape) }));\n}\n// the source's keys, then the caller's overlaid on top\nfunction extended(schema, shape) {\n const newShape = {};\n mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)));\n mirrorProps(newShape, shape);\n return newShape;\n}\nexport function safeExtend(schema, shape) {\n if (!isPlainObject(shape)) {\n throw new Error(\"Invalid input to safeExtend: expected a plain object\");\n }\n return clone(schema, mergeDefs(schema._zod.def, { shape: extended(schema, shape) }));\n}\nexport function merge(a, b) {\n if (!b?._zod?.def) {\n throw new Error(\"Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.\");\n }\n if (a._zod.def.checks?.length) {\n throw new Error(\".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.\");\n }\n const newShape = {};\n mirrorShape(newShape, a, Reflect.ownKeys(sourceShape(a)));\n mirrorShape(newShape, b, Reflect.ownKeys(sourceShape(b)));\n const def = mergeDefs(a._zod.def, {\n shape: newShape,\n get catchall() {\n return b._zod.def.catchall;\n },\n checks: b._zod.def.checks ?? [],\n });\n return clone(a, def);\n}\nexport function partial(Class, schema, mask, name = \"partial\") {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(`.${name}() cannot be used on object schemas containing refinements`);\n }\n const selected = mask ? new Set(maskedKeys(schema, mask)) : undefined;\n const newShape = {};\n mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)), Class &&\n ((value, key) => (selected && !selected.has(key) ? value : new Class({ type: \"optional\", innerType: value }))));\n return clone(schema, mergeDefs(schema._zod.def, { shape: newShape, checks: [] }));\n}\nexport function required(Class, schema, mask) {\n const selected = mask ? new Set(maskedKeys(schema, mask)) : undefined;\n const newShape = {};\n mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)), (value, key) => \n // overwrite with non-optional\n selected && !selected.has(key) ? value : new Class({ type: \"nonoptional\", innerType: value }));\n return clone(schema, mergeDefs(schema._zod.def, { shape: newShape }));\n}\n// invalid_type | too_big | too_small | invalid_format | not_multiple_of | unrecognized_keys | invalid_union | invalid_key | invalid_element | invalid_value | custom\nexport function aborted(x, startIndex = 0) {\n if (x.aborted === true)\n return true;\n for (let i = startIndex; i < x.issues.length; i++) {\n if (x.issues[i]?.continue !== true) {\n return true;\n }\n }\n return false;\n}\n// Checks for explicit abort (continue === false), as opposed to implicit abort (continue === undefined). Used to respect `abort: true` in .refine() even for checks that have a `when` function.\nexport function explicitlyAborted(x, startIndex = 0) {\n if (x.aborted === true)\n return true;\n for (let i = startIndex; i < x.issues.length; i++) {\n if (x.issues[i]?.continue === false) {\n return true;\n }\n }\n return false;\n}\nexport function prefixIssues(path, issues) {\n return issues.map((iss) => {\n var _a;\n (_a = iss).path ?? (_a.path = []);\n iss.path.unshift(path);\n return iss;\n });\n}\nexport function unwrapMessage(message) {\n return typeof message === \"string\" ? message : message?.message;\n}\n/* A check holds no link back to the schema it is attached to — the same check instance is shared by every clone of that schema — so the owner is stamped onto the issues a check just raised, at the only point where both are in scope. Runs on the failure path only; `start` is the issue count from before the check ran. */\nexport function attachSchema(issues, start, inst) {\n var _a;\n for (let i = start; i < issues.length; i++) {\n (_a = issues[i]).schema ?? (_a.schema = inst);\n }\n}\nexport function finalizeIssue(iss, ctx, config) {\n var _a;\n // A schema that raised an issue itself owns it outright, and outranks any stamp an enclosing check left in `attachSchema`. String formats and z.custom() are schema and check at once, so when they act as a check they defer to that stamp instead.\n const traits = iss.inst?._zod?.traits;\n if (traits?.has(\"$ZodType\")) {\n if (traits.has(\"$ZodCheck\"))\n (_a = iss).schema ?? (_a.schema = iss.inst);\n else\n iss.schema = iss.inst;\n }\n // Decreasing specificity, first map to return a message wins. `inst` is whatever raised the issue, so a check's own map outranks the owning schema's.\n const schemaError = iss.schema !== iss.inst ? iss.schema?._zod.def?.error : undefined;\n const message = iss.message\n ? iss.message\n : (unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ??\n unwrapMessage(schemaError?.(iss)) ??\n unwrapMessage(ctx?.error?.(iss)) ??\n unwrapMessage(config.customError?.(iss)) ??\n unwrapMessage(config.localeError?.(iss)) ??\n \"Invalid input\");\n // an explicit own-key copy beats object rest with excluded keys, which v8 routes through a generic runtime call; Object.keys rather than for-in so an issue pushed with a prototype does not leak inherited keys, and an own __proto__ key is dropped rather than assigned through the setter\n const full = {};\n for (const k of Object.keys(iss)) {\n if (k === \"inst\" || k === \"schema\" || k === \"continue\" || k === \"input\" || k === \"__proto__\")\n continue;\n full[k] = iss[k];\n }\n full.path ?? (full.path = []);\n full.message = message;\n if (ctx?.reportInput) {\n full.input = iss.input;\n }\n return full;\n}\nexport function getSizableOrigin(input) {\n if (input instanceof Set)\n return \"set\";\n if (input instanceof Map)\n return \"map\";\n // @ts-ignore\n if (input instanceof File)\n return \"file\";\n return \"unknown\";\n}\nconst highSurrogate = /[\\uD800-\\uDBFF]/;\n// Code points in `str`: a surrogate pair counts once, a lone surrogate as itself. Hand-rolled because the string iterator allocates and runs ~250x slower on this path; the regex probe exits ~50x quicker for a string with no astral characters.\nexport function codePointLength(str) {\n const units = str.length;\n if (!highSurrogate.test(str))\n return units;\n let count = units;\n for (let i = 0; i < units - 1; i++) {\n if ((str.charCodeAt(i) & 0xfc00) === 0xd800 && (str.charCodeAt(i + 1) & 0xfc00) === 0xdc00) {\n count--;\n i++;\n }\n }\n return count;\n}\nexport function getLengthableOrigin(input) {\n if (Array.isArray(input))\n return \"array\";\n if (typeof input === \"string\")\n return \"string\";\n return \"unknown\";\n}\nexport function parsedType(data) {\n const t = typeof data;\n switch (t) {\n case \"number\": {\n return Number.isNaN(data) ? \"nan\" : \"number\";\n }\n case \"object\": {\n if (data === null) {\n return \"null\";\n }\n if (Array.isArray(data)) {\n return \"array\";\n }\n const obj = data;\n if (obj && Object.getPrototypeOf(obj) !== Object.prototype && \"constructor\" in obj && obj.constructor) {\n return obj.constructor.name;\n }\n }\n }\n return t;\n}\nexport function issue(...args) {\n const [iss, input, inst] = args;\n if (typeof iss === \"string\") {\n return {\n message: iss,\n code: \"custom\",\n input,\n inst,\n };\n }\n return { ...iss };\n}\nexport function cleanEnum(obj) {\n return Object.entries(obj)\n .filter(([k, _]) => {\n // return true if NaN, meaning it's not a number, thus a string key\n return Number.isNaN(Number.parseInt(k, 10));\n })\n .map((el) => el[1]);\n}\n// Codec utility functions\nexport function base64ToUint8Array(base64) {\n const binaryString = atob(base64);\n const bytes = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n bytes[i] = binaryString.charCodeAt(i);\n }\n return bytes;\n}\nexport function uint8ArrayToBase64(bytes) {\n let binaryString = \"\";\n for (let i = 0; i < bytes.length; i++) {\n binaryString += String.fromCharCode(bytes[i]);\n }\n return btoa(binaryString);\n}\nexport function base64urlToUint8Array(base64url) {\n const base64 = base64url.replace(/-/g, \"+\").replace(/_/g, \"/\");\n const padding = \"=\".repeat((4 - (base64.length % 4)) % 4);\n return base64ToUint8Array(base64 + padding);\n}\nexport function uint8ArrayToBase64url(bytes) {\n return uint8ArrayToBase64(bytes).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=/g, \"\");\n}\nexport function hexToUint8Array(hex) {\n const cleanHex = hex.replace(/^0x/, \"\");\n if (cleanHex.length % 2 !== 0) {\n throw new Error(\"Invalid hex string length\");\n }\n const bytes = new Uint8Array(cleanHex.length / 2);\n for (let i = 0; i < cleanHex.length; i += 2) {\n bytes[i / 2] = Number.parseInt(cleanHex.slice(i, i + 2), 16);\n }\n return bytes;\n}\nexport function uint8ArrayToHex(bytes) {\n return Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n// instanceof\nexport class Class {\n constructor(..._args) { }\n}\n////////// PROTOTYPE INSTALLERS //////////\n//\n// Members live on the prototype and materialize per instance on first read, which keeps own-property count under the step where V8 stops using inline slots. Changing anything here means re-measuring runtime, memory and bundle size together — see \"The three axes\" in AGENTS.md.\n/**\n * Installs a trait's members on its prototype. Each value builds that member for the instance on first read; the built value shadows the accessor as an own property, so a detached `const { parse } = schema` keeps working.\n *\n * Call this from a `proto` initializer, which runs once per prototype — never per instance.\n */\nexport function members(proto, table) {\n for (const key in table) {\n const desc = Object.getOwnPropertyDescriptor(table, key);\n // a getter installs as written, so it stays live: `description` reads through to the registry on every access. not enumerable: an object literal's is, and a prototype member never was\n if (desc.get)\n Object.defineProperty(proto, key, { ...desc, enumerable: false });\n // a method materializes bound on first read, which is what keeps a detached member working: `const opt = schema.optional; opt()`\n else\n defineBound(proto, key, desc.value);\n }\n}\n/** Shadows a prototype member with an own value, so a getter that builds from the instance runs once. */\nexport function own(inst, key, value, enumerable = true) {\n Object.defineProperty(inst, key, { configurable: true, writable: true, enumerable, value });\n return value;\n}\n/** Like {@link own}, for a member that was never an own data property and has to stay out of `Object.keys`. */\nexport function hide(inst, key, value) {\n return own(inst, key, value, false);\n}\n/** Adds members a table derives from the instance: each builds on first read and shadows as own data, and assignment shadows the same way, as when these were own properties. */\nexport /*@__NO_SIDE_EFFECTS__*/ function derived(computes, table) {\n for (const key in computes) {\n const compute = computes[key];\n // an object literal's accessor is configurable and enumerable, and `members` copies the descriptor as written\n Object.defineProperty(table, key, {\n configurable: true,\n enumerable: true,\n get() {\n return own(this, key, compute(this));\n },\n set(value) {\n own(this, key, value);\n },\n });\n }\n return table;\n}\nfunction defineBound(proto, key, fn) {\n Object.defineProperty(proto, key, {\n configurable: true,\n get() {\n // vitest's spyOn calls a prototype getter bare to find the function it wraps, so a nullish receiver answers the raw method\n return this == null ? fn : own(this, key, fn.bind(this));\n },\n set(value) {\n own(this, key, value);\n },\n });\n}\n/** Returns the prototype to install on, or `undefined` if this group is already installed on it. */\nfunction claim(inst, sentinel) {\n const proto = Object.getPrototypeOf(inst);\n // Runs on every construction, so `in` rather than the costlier `hasOwnProperty.call`. Sentinels are keys the group itself defines.\n return sentinel in proto ? undefined : proto;\n}\n// The internals whose init chain is installing. A second call for the same one is a derived constructor overriding its base, so it must not construct another schema in between or the override is dropped.\nlet installing;\n// Set while a getter is running, so a value that resolved through a recursion break is not memoized. One shared descriptor shadows the key for the duration, which costs no per-key allocation.\nlet broke = false;\nconst breaker = {\n configurable: true,\n get() {\n broke = true;\n return undefined;\n },\n};\n/**\n * Installs a lazily-derived internal on the `_zod` prototype of `inst`'s\n * constructor, computed from the internals object itself and cached there on\n * first read. One accessor per constructor rather than one per instance.\n */\nexport function defineLazyInternal(inst, key, compute) {\n const proto = Object.getPrototypeOf(inst._zod);\n if (key in proto && installing !== inst._zod) {\n // A repeat construction: everything is installed already. Cleared here so the reference is not held past the first construction of every type.\n installing = undefined;\n return;\n }\n installing = inst._zod;\n Object.defineProperty(proto, key, {\n configurable: true,\n get() {\n // Shadowed before computing so a re-entrant read from a recursive schema resolves to undefined instead of running the getter again.\n Object.defineProperty(this, key, breaker);\n const outer = broke;\n broke = false;\n try {\n const value = compute(this);\n // A result that resolved through a recursion break is recomputed once the graph is complete; everything else memoizes, undefined included.\n if (broke)\n delete this[key];\n else\n Object.defineProperty(this, key, { configurable: true, writable: true, value });\n broke = broke || outer;\n return value;\n }\n catch (err) {\n // A compute that threw memoizes nothing, so a later read runs it again and fails the same way. The shadow goes with it, since leaving it installed would answer undefined for every later read.\n delete this[key];\n broke = broke || outer;\n throw err;\n }\n },\n set(value) {\n Object.defineProperty(this, key, { configurable: true, writable: true, value });\n },\n });\n}\n/**\n * Installs `key` on `inst`'s prototype, computed by `make` on first read and cached there as an own\n * data property. One accessor per constructor rather than one per instance, because an own accessor\n * puts every instance after the first into v8 dictionary mode. The key doubles as the sentinel.\n */\nexport function installLazyProp(inst, key, make, enumerable) {\n const proto = claim(inst, key);\n if (!proto)\n return;\n Object.defineProperty(proto, key, {\n configurable: true,\n get() {\n // Shadowed before computing, so a re-entrant read from a self-referential shape resolves to undefined instead of running the getter again. A data property rather than an accessor: an own accessor is the dictionary-mode transition this exists to avoid.\n const desc = { configurable: true, writable: true, enumerable, value: undefined };\n Object.defineProperty(this, key, desc);\n // a compute that throws leaves the shadow behind, so later reads answer undefined instead of re-throwing; `defineLazy` did the same, and `defineLazyInternal`'s delete-on-catch would cost bytes in every bundle for a case only a throwing user getter reaches\n desc.value = make(this);\n Object.defineProperty(this, key, desc);\n return desc.value;\n },\n set(value) {\n Object.defineProperty(this, key, { configurable: true, writable: true, enumerable, value });\n },\n });\n}\n/** Marks the thunk `_catch` synthesises for a constant catch value. `Function.length` cannot tell that thunk from a user callback — rest and defaulted parameters both report arity 0 — and a user callback reads `ctx.error`, whose issues only finalize correctly against the caller's per-parse error map. Provenance can say what arity cannot. A plain string key rather than `Symbol.for`, whose call at module scope no bundler can prove pure — the same shape that anchored `urlCanParse` into every build. */\nexport const CONSTANT_CATCH = \"~constantCatch\";\n/** Wraps a constant catch value in a thunk tagged with {@link CONSTANT_CATCH}. */\nexport function constantCatch(value) {\n const fn = () => value;\n fn[CONSTANT_CATCH] = true;\n return fn;\n}\n","var _a;\nimport { members as installMembers } from \"./util.js\";\n/** A special constant with type `never` */\nexport const NEVER = /*@__PURE__*/ Object.freeze({\n status: \"aborted\",\n});\n/* Shared descriptor for installing `_zod`; defineProperty reads it\n * synchronously, so reusing one object avoids a per-instance allocation. */\nconst _zodDesc = { value: undefined, enumerable: false };\n// null where suppressing the capture would be unrecoverable: `parse()` puts the frames back with `captureStackTrace`, so without it the throw would lose its stack. also latched to null once `stackTraceLimit` proves unassignable, which a realm can do at any point by hardening Error\nlet _E = \"captureStackTrace\" in Error ? Error : null;\n// v8 captures a stack trace inside the Error constructor, which dominates a failed parse; costs only the frames, and parse() restores those. the constructor must RUN: Object.create is cheaper and passes instanceof, but Error.isError and util.types.isNativeError check an internal slot\nfunction newError(Definition) {\n const E = _E;\n if (E) {\n const saved = E.stackTraceLimit;\n if (typeof saved === \"number\") {\n try {\n E.stackTraceLimit = 0;\n }\n catch {\n _E = null;\n return new Definition();\n }\n try {\n return new Definition();\n }\n finally {\n E.stackTraceLimit = saved;\n }\n }\n }\n return new Definition();\n}\nexport /*@__NO_SIDE_EFFECTS__*/ function $constructor(name, initializer, \n/** This trait's members, installed once on every prototype that composes it. They cannot be declared in the initializer above: that runs per instance, and the prototype is shared. */\nproto, params) {\n // Prototype for this constructor's `_zod` internals. Lazily-derived fields (`values`, `pattern`, `optin`, …) install here once rather than as an accessor on every instance.\n const zodProto = {};\n // Assigning the fields in the constructor body is what gives instances in-object slots; building the object literally and reparenting it costs a second allocation and a generic property copy.\n function Internals(def) {\n this.def = def;\n this.constr = _;\n this.traits = new Set();\n }\n Internals.prototype = zodProto;\n const protoMembers = proto;\n // One trait's members land on every prototype whose chain composes it, so the answer is per prototype rather than per trait.\n const initialized = protoMembers && new WeakSet();\n function init(inst, def) {\n if (!inst._zod) {\n _zodDesc.value = new Internals(def);\n try {\n Object.defineProperty(inst, \"_zod\", _zodDesc);\n }\n finally {\n // Cleared even on throw, so the shared descriptor never leaks one instance's internals into the next.\n _zodDesc.value = undefined;\n }\n }\n else if (inst._zod.traits.has(name)) {\n return;\n }\n inst._zod.traits.add(name);\n initializer(inst, def);\n if (initialized) {\n // `super(def)` from a user subclass gives `this` a prototype the subclass owns, and installing there would overwrite whatever the subclass declared. `constr` built the instance, so its prototype is the one below the subclass's that should carry the members. A receiver whose chain never reaches that prototype installs on its own, which for a plain object handed straight to `init` means `Object.prototype` — unchanged from before.\n const own = Object.getPrototypeOf(inst);\n const ctorProto = inst._zod.constr.prototype;\n let up = own;\n while (up && up !== ctorProto)\n up = Object.getPrototypeOf(up);\n const target = up ?? own;\n if (!initialized.has(target)) {\n initialized.add(target);\n installMembers(target, protoMembers);\n }\n }\n // support prototype modifications; for-in avoids the array allocation of Object.keys on the (usually empty) prototype\n const proto = _.prototype;\n for (const k in proto) {\n if (!Object.prototype.hasOwnProperty.call(proto, k))\n continue;\n if (!(k in inst)) {\n inst[k] = proto[k].bind(inst);\n }\n }\n }\n // doesn't work if Parent has a constructor with arguments\n const Parent = params?.Parent ?? Object;\n class Definition extends Parent {\n }\n Object.defineProperty(Definition, \"name\", { value: name });\n function _(def) {\n const inst = params?.Parent ? newError(Definition) : this;\n init(inst, def);\n const deferred = inst._zod.deferred;\n if (deferred) {\n for (const fn of deferred) {\n fn();\n }\n // Released: initializers run once, and the list would otherwise be retained for the schema's lifetime.\n inst._zod.deferred = undefined;\n }\n // Global post-processor hook. Internal: installed by `import \"zod/compile\"` to enable AOT compilation for every constructed schema. Runs last, once the instance is fully built, because it hands the instance to compile(). The post-processor is expected to be reentrancy-guarded by its own implementation.\n const pp = globalThis.__zod_globalConfig?.postProcessor;\n if (pp)\n pp(inst);\n return inst;\n }\n Object.defineProperty(_, \"init\", { value: init });\n Object.defineProperty(_, Symbol.hasInstance, {\n value: (inst) => {\n if (params?.Parent && inst instanceof params.Parent)\n return true;\n return inst?._zod?.traits?.has(name);\n },\n });\n Object.defineProperty(_, \"name\", { value: name });\n return _;\n}\n////////////////////////////// UTILITIES ///////////////////////////////////////\nexport const $brand = /*@__PURE__*/ Symbol(\"zod_brand\");\nexport class $ZodAsyncError extends Error {\n constructor() {\n super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);\n }\n}\nexport class $ZodEncodeError extends Error {\n constructor(name) {\n super(`Encountered unidirectional transform during encode: ${name}`);\n this.name = \"ZodEncodeError\";\n }\n}\n(_a = globalThis).__zod_globalConfig ?? (_a.__zod_globalConfig = {});\nexport const globalConfig = globalThis.__zod_globalConfig;\nexport function config(newConfig) {\n if (newConfig)\n Object.assign(globalConfig, newConfig);\n return globalConfig;\n}\n","import { $constructor } from \"./core.js\";\nimport * as util from \"./util.js\";\n/* Computing the message eagerly is expensive (pretty-printed JSON of all\n * issues), so defer it until first read. The accessor functions and\n * descriptors are shared across instances to keep error construction\n * cheap; the computed message is cached on the internals object. The\n * setter preserves plain assignment semantics for consumers that\n * overwrite `message`. */\nfunction _getMessage() {\n const internals = this._zod;\n internals.message ?? (internals.message = JSON.stringify(internals.def, util.jsonStringifyReplacer, 2));\n return internals.message;\n}\nfunction _setMessage(value) {\n this._zod.message = value;\n}\nconst _messageDesc = {\n get: _getMessage,\n set: _setMessage,\n enumerable: true,\n configurable: true,\n};\nconst _issuesDesc = { value: undefined, enumerable: false };\n/* Prototypes that already carry the lazy `toString`. Seeded with the\n * intrinsics so that `init` on a foreign object — it accepts any object —\n * can never install an accessor onto a prototype we do not own. */\nconst _installedToString = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]);\nconst initializer = (inst, def) => {\n inst.name = \"$ZodError\";\n // `_zod` is already non-enumerable: $constructor's init defined it with this same descriptor\n _issuesDesc.value = def;\n Object.defineProperty(inst, \"issues\", _issuesDesc);\n // Clear the shared slot; a retained `value` pins the last error's issues.\n _issuesDesc.value = undefined;\n Object.defineProperty(inst, \"message\", _messageDesc);\n /* `toString` lives as a non-enumerable lazy getter on the shared\n * prototype; on first access it caches a per-instance closure so\n * detached usage still works. */\n const proto = Object.getPrototypeOf(inst);\n if (!_installedToString.has(proto)) {\n _installedToString.add(proto);\n Object.defineProperty(proto, \"toString\", {\n configurable: true,\n enumerable: false,\n get() {\n const value = () => this.message;\n Object.defineProperty(this, \"toString\", { value, configurable: true, writable: true });\n return value;\n },\n set(value) {\n Object.defineProperty(this, \"toString\", { value, configurable: true, writable: true });\n },\n });\n }\n};\nexport const $ZodError = $constructor(\"$ZodError\", initializer);\nexport const $ZodRealError = $constructor(\"$ZodError\", initializer, undefined, {\n Parent: Error,\n});\n/** Get-or-create `obj[key]` as an own data property. A path segment naming an inherited member\n * (\"toString\", \"constructor\") would otherwise read through to the prototype, and assigning\n * \"__proto__\" would hit the setter instead of creating a key. */\nfunction node(obj, key, make) {\n if (!Object.prototype.hasOwnProperty.call(obj, key)) {\n if (key === \"__proto__\") {\n Object.defineProperty(obj, key, { value: make(), writable: true, enumerable: true, configurable: true });\n }\n else {\n obj[key] = make();\n }\n }\n return obj[key];\n}\nexport function flattenError(error, mapper = (issue) => issue.message) {\n const fieldErrors = {};\n const formErrors = [];\n for (const sub of error.issues) {\n if (sub.path.length > 0) {\n node(fieldErrors, sub.path[0], () => []).push(mapper(sub));\n }\n else {\n formErrors.push(mapper(sub));\n }\n }\n return { formErrors, fieldErrors };\n}\nexport function formatError(error, mapper = (issue) => issue.message) {\n const fieldErrors = { _errors: [] };\n const processError = (error, path = []) => {\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\" && issue.errors.length) {\n issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path]));\n }\n else if (issue.code === \"invalid_key\") {\n processError({ issues: issue.issues }, [...path, ...issue.path]);\n }\n else if (issue.code === \"invalid_element\") {\n processError({ issues: issue.issues }, [...path, ...issue.path]);\n }\n else {\n const fullpath = [...path, ...issue.path];\n if (fullpath.length === 0) {\n fieldErrors._errors.push(mapper(issue));\n }\n else {\n let curr = fieldErrors;\n let i = 0;\n while (i < fullpath.length) {\n const el = fullpath[i];\n const terminal = i === fullpath.length - 1;\n // `_errors` is reserved by this legacy format, so merge a matching path segment into the current node instead of treating its array as a child.\n if (el === \"_errors\") {\n if (terminal)\n curr._errors.push(mapper(issue));\n i++;\n continue;\n }\n // A path element may collide with an inherited property name such as\n // \"__proto__\" or \"constructor\". Truthiness checks read the prototype\n // (so no node is created, then ._errors.push throws), and bracket\n // assignment of \"__proto__\" hits the setter instead of creating an\n // own key. Guard the read with hasOwnProperty and create the node\n // with defineProperty so any path element becomes a real own key.\n if (!Object.prototype.hasOwnProperty.call(curr, el)) {\n Object.defineProperty(curr, el, {\n value: { _errors: [] },\n enumerable: true,\n writable: true,\n configurable: true,\n });\n }\n const node = curr[el];\n if (terminal) {\n node._errors.push(mapper(issue));\n }\n curr = node;\n i++;\n }\n }\n }\n }\n };\n processError(error);\n return fieldErrors;\n}\nexport function treeifyError(error, mapper = (issue) => issue.message) {\n const result = { errors: [] };\n const processError = (error, path = []) => {\n var _a;\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\" && issue.errors.length) {\n // regular union error\n issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path]));\n }\n else if (issue.code === \"invalid_key\") {\n processError({ issues: issue.issues }, [...path, ...issue.path]);\n }\n else if (issue.code === \"invalid_element\") {\n processError({ issues: issue.issues }, [...path, ...issue.path]);\n }\n else {\n const fullpath = [...path, ...issue.path];\n if (fullpath.length === 0) {\n result.errors.push(mapper(issue));\n continue;\n }\n let curr = result;\n let i = 0;\n while (i < fullpath.length) {\n const el = fullpath[i];\n const terminal = i === fullpath.length - 1;\n if (typeof el === \"string\") {\n curr.properties ?? (curr.properties = {});\n // el may collide with an inherited property name (\"__proto__\",\n // \"constructor\", ...); ??= reads the prototype so the node is never\n // created and curr.errors.push throws. Guard with hasOwnProperty and\n // create the node with defineProperty so \"__proto__\" becomes a real\n // own key rather than invoking the prototype setter.\n if (!Object.prototype.hasOwnProperty.call(curr.properties, el)) {\n Object.defineProperty(curr.properties, el, {\n value: { errors: [] },\n enumerable: true,\n writable: true,\n configurable: true,\n });\n }\n curr = curr.properties[el];\n }\n else {\n curr.items ?? (curr.items = []);\n (_a = curr.items)[el] ?? (_a[el] = { errors: [] });\n curr = curr.items[el];\n }\n if (terminal) {\n curr.errors.push(mapper(issue));\n }\n i++;\n }\n }\n }\n };\n processError(error);\n return result;\n}\n/** Format a ZodError as a human-readable string in the following form.\n *\n * From\n *\n * ```ts\n * ZodError {\n * issues: [\n * {\n * expected: 'string',\n * code: 'invalid_type',\n * path: [ 'username' ],\n * message: 'Invalid input: expected string'\n * },\n * {\n * expected: 'number',\n * code: 'invalid_type',\n * path: [ 'favoriteNumbers', 1 ],\n * message: 'Invalid input: expected number'\n * }\n * ];\n * }\n * ```\n *\n * to\n *\n * ```\n * username\n * ✖ Expected number, received string at \"username\n * favoriteNumbers[0]\n * ✖ Invalid input: expected number\n * ```\n */\nexport function toDotPath(_path) {\n const segs = [];\n const path = _path.map((seg) => (typeof seg === \"object\" ? seg.key : seg));\n for (const seg of path) {\n if (typeof seg === \"number\")\n segs.push(`[${seg}]`);\n else if (typeof seg === \"symbol\")\n segs.push(`[${JSON.stringify(String(seg))}]`);\n else if (/[^\\w$]/.test(seg))\n segs.push(`[${JSON.stringify(seg)}]`);\n else {\n if (segs.length)\n segs.push(\".\");\n segs.push(seg);\n }\n }\n return segs.join(\"\");\n}\nexport function prettifyError(error) {\n const lines = [];\n // sort by path length\n const issues = [...error.issues].sort((a, b) => (a.path ?? []).length - (b.path ?? []).length);\n // Process each issue\n for (const issue of issues) {\n lines.push(`✖ ${issue.message}`);\n if (issue.path?.length)\n lines.push(` → at ${toDotPath(issue.path)}`);\n }\n // Convert Map to formatted string\n return lines.join(\"\\n\");\n}\n","import * as core from \"./core.js\";\nimport * as errors from \"./errors.js\";\nimport * as util from \"./util.js\";\n// Always both keys, so the `_params` read site in `_parse` sees one object shape rather than two.\nfunction finalizeParams(callee, params) {\n return { callee: params?.callee ?? callee, Err: params?.Err };\n}\nexport const _parse = (_Err) => {\n const fn = (schema, value, _ctx, _params) => {\n const ctx = _ctx ? { ..._ctx, async: false } : { async: false };\n const result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n if (result.issues.length) {\n const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));\n util.captureStackTrace(e, _params?.callee ?? fn);\n throw e;\n }\n return result.value;\n };\n return fn;\n};\nexport const parse = /* @__PURE__*/ _parse(errors.$ZodRealError);\nexport const _parseAsync = (_Err) => {\n const fn = async (schema, value, _ctx, params) => {\n const ctx = _ctx ? { ..._ctx, async: true } : { async: true };\n let result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise)\n result = await result;\n if (result.issues.length) {\n const e = new (params?.Err ?? _Err)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));\n util.captureStackTrace(e, params?.callee ?? fn);\n throw e;\n }\n return result.value;\n };\n return fn;\n};\nexport const parseAsync = /* @__PURE__*/ _parseAsync(errors.$ZodRealError);\nexport const _safeParse = (_Err) => (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, async: false } : { async: false };\n const result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n return result.issues.length ? failure(_Err, result.issues, ctx) : { success: true, data: result.value };\n};\nexport const safeParse = /* @__PURE__*/ _safeParse(errors.$ZodRealError);\n// the error is built on the first read of `error`: finalizing the issues and constructing the instance is most of a failing parse, and a caller that only branches on `success` never pays it. a getter in the literal keeps this small; the alternative, one shared accessor descriptor plus a hidden state slot, reads ~15% faster but costs ~75 B gzipped in every bundle\nfunction failure(Err, issues, ctx) {\n let error;\n return {\n success: false,\n get error() {\n if (!error) {\n error = new Err(issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));\n // finalizeIssue drops `input`, so the built error holds nothing; keeping the raw issues past this point pins the parsed value for the life of the result\n issues = undefined;\n ctx = undefined;\n }\n return error;\n },\n set error(e) {\n error = e;\n // a replacement makes the getter's branch unreachable, so the captures have to go here too\n issues = undefined;\n ctx = undefined;\n },\n };\n}\nexport const _safeParseAsync = (_Err) => async (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, async: true } : { async: true };\n let result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise)\n result = await result;\n return result.issues.length ? failure(_Err, result.issues, ctx) : { success: true, data: result.value };\n};\nexport const safeParseAsync = /* @__PURE__*/ _safeParseAsync(errors.$ZodRealError);\n// registry mirrors of the compiler's sentinels, so this module never imports the compiler\nconst COMPILE_INVALID = /* @__PURE__ */ Symbol.for(\"zod.compile.invalid\");\nconst COMPILE_FALLBACK = /* @__PURE__ */ Symbol.for(\"zod.compile.fallback\");\n// Deliberately tiny, because v8 will not inline a body carrying the fallback's object literals and throw. Everything that is not the compiled happy path lives in validateFallback, and that split is worth ~35% on a compiled schema.\nexport const validate = ((schema, value, _ctx) => {\n const validator = schema._zod.bag.validator;\n if (validator !== undefined) {\n if (validator(value) !== COMPILE_INVALID)\n return true;\n // a definite sentinel means the runtime would reject, so skip the re-parse; a ctx can still change the answer\n if (validator.definite === true && _ctx === undefined)\n return false;\n }\n return validateFallback(schema, value, _ctx);\n});\nfunction validateFallback(schema, value, _ctx) {\n const ctx = _ctx\n ? { ..._ctx, async: false, abortEarly: true }\n : { async: false, abortEarly: true };\n const fallbackRun = schema._zod.bag.fallbackRun;\n let result;\n if (fallbackRun) {\n // skip nested fast paths on the fallback, so user callbacks keep the at-most-twice bound\n ctx[COMPILE_FALLBACK] = true;\n result = fallbackRun({ value, issues: [] }, ctx);\n }\n else {\n result = schema._zod.run({ value, issues: [] }, ctx);\n }\n if (result instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n return result.issues.length === 0;\n}\n// no fast path: the compiler keeps async parses on the runtime, because a promise-returning callback that is not declared async compiles to a throw\nexport const validateAsync = async (schema, value, _ctx) => {\n const ctx = _ctx\n ? { ..._ctx, async: true, abortEarly: true }\n : { async: true, abortEarly: true };\n let result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise)\n result = await result;\n return result.issues.length === 0;\n};\nexport const _encode = (_Err) => {\n const parse = _parse(_Err);\n const fn = (schema, value, _ctx, _params) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return parse(schema, value, ctx, finalizeParams(fn, _params));\n };\n return fn;\n};\nexport const encode = /* @__PURE__*/ _encode(errors.$ZodRealError);\nexport const _decode = (_Err) => {\n const parse = _parse(_Err);\n const fn = (schema, value, _ctx, _params) => {\n return parse(schema, value, _ctx, finalizeParams(fn, _params));\n };\n return fn;\n};\nexport const decode = /* @__PURE__*/ _decode(errors.$ZodRealError);\nexport const _encodeAsync = (_Err) => {\n const parseAsync = _parseAsync(_Err);\n const fn = async (schema, value, _ctx, _params) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return (await parseAsync(schema, value, ctx, finalizeParams(fn, _params)));\n };\n return fn;\n};\nexport const encodeAsync = /* @__PURE__*/ _encodeAsync(errors.$ZodRealError);\nexport const _decodeAsync = (_Err) => {\n const parseAsync = _parseAsync(_Err);\n const fn = async (schema, value, _ctx, _params) => {\n return await parseAsync(schema, value, _ctx, finalizeParams(fn, _params));\n };\n return fn;\n};\nexport const decodeAsync = /* @__PURE__*/ _decodeAsync(errors.$ZodRealError);\nexport const _safeEncode = (_Err) => (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return _safeParse(_Err)(schema, value, ctx);\n};\nexport const safeEncode = /* @__PURE__*/ _safeEncode(errors.$ZodRealError);\nexport const _safeDecode = (_Err) => (schema, value, _ctx) => {\n return _safeParse(_Err)(schema, value, _ctx);\n};\nexport const safeDecode = /* @__PURE__*/ _safeDecode(errors.$ZodRealError);\nexport const _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return _safeParseAsync(_Err)(schema, value, ctx);\n};\nexport const safeEncodeAsync = /* @__PURE__*/ _safeEncodeAsync(errors.$ZodRealError);\nexport const _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => {\n return _safeParseAsync(_Err)(schema, value, _ctx);\n};\nexport const safeDecodeAsync = /* @__PURE__*/ _safeDecodeAsync(errors.$ZodRealError);\n","import * as util from \"./util.js\";\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link cuid2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport const cuid = /^[cC][0-9a-z]{6,}$/;\nexport const cuid2 = /^[0-9a-z]+$/;\nexport const ulid = /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/;\nexport const xid = /^[0-9a-vA-V]{20}$/;\nexport const ksuid = /^[A-Za-z0-9]{27}$/;\nexport const nanoid = /^[a-zA-Z0-9_-]{21}$/;\nexport function nanoidOfLength(length) {\n return new RegExp(`^[a-zA-Z0-9_-]{${length}}$`);\n}\n/** ISO 8601-1 duration regex. Does not support the 8601-2 extensions like negative durations or fractional/negative components. */\nexport const duration = /^P(?:(\\d+W)|(?!.*W)(?=\\d|T\\d)(\\d+Y)?(\\d+M)?(\\d+D)?(T(?=\\d)(\\d+H)?(\\d+M)?(\\d+([.,]\\d+)?S)?)?)$/;\n/** Implements ISO 8601-2 extensions like explicit +- prefixes, mixing weeks with other units, and fractional/negative components. */\nexport const extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\\d+Y)|(?:[-+]?\\d+[.,]\\d+Y$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:(?:[-+]?\\d+W)|(?:[-+]?\\d+[.,]\\d+W$))?(?:(?:[-+]?\\d+D)|(?:[-+]?\\d+[.,]\\d+D$))?(?:T(?=[\\d+-])(?:(?:[-+]?\\d+H)|(?:[-+]?\\d+[.,]\\d+H$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:[-+]?\\d+(?:[.,]\\d+)?S)?)??$/;\n/** A regex for any UUID-like identifier: 8-4-4-4-12 hex pattern */\nexport const guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;\n/** Returns a regex for validating an RFC 9562/4122 UUID.\n *\n * @param version Optionally specify a version 1-8. If no version is specified, all versions are supported. */\nexport const uuid = (version) => {\n if (!version)\n return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;\n return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);\n};\nexport const uuid4 = /*@__PURE__*/ uuid(4);\nexport const uuid6 = /*@__PURE__*/ uuid(6);\nexport const uuid7 = /*@__PURE__*/ uuid(7);\n/** Practical email validation */\nexport const email = /^(?:[A-Za-z0-9_'+\\-]+\\.)*[A-Za-z0-9_'+\\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$/;\n/** Equivalent to the HTML5 input[type=email] validation implemented by browsers. Source: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email */\nexport const html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n/** The classic emailregex.com regex for RFC 5322-compliant emails */\nexport const rfc5322Email = /^(([^<>()\\[\\]\\\\.,;:\\s@\"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/;\n/** A loose regex that allows Unicode characters, enforces length limits, and that's about it. */\nexport const unicodeEmail = /^[^\\s@\"]{1,64}@[^\\s@]{1,255}$/u;\nexport const idnEmail = unicodeEmail;\nexport const browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression\n// Single character class, not an alternation: the two properties overlap (U+1F9B0-U+1F9B3), so `(A|B)+` backtracks exponentially on a failed match. The leading lookahead then demands one anchor — a pictograph, a regional indicator, or the enclosing keycap — because `\\p{Emoji_Component}` on its own covers ASCII digits, `#`, `*`, ZWJ, variation selectors and skin tone modifiers, none of which is an emoji without a base.\nconst _emoji = `^(?=[\\\\s\\\\S]*[\\\\p{Extended_Pictographic}\\\\p{Regional_Indicator}\\\\u20E3])[\\\\p{Extended_Pictographic}\\\\p{Emoji_Component}]+$`;\nexport function emoji() {\n return new RegExp(_emoji, \"u\");\n}\nexport const ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;\nexport const ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;\nexport const mac = (delimiter) => {\n const escapedDelim = util.escapeRegex(delimiter ?? \":\");\n return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`);\n};\nexport const cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\/([0-9]|[1-2][0-9]|3[0-2])$/;\nexport const cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;\n// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript\nexport const base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;\nexport const base64url = /^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/;\n// based on https://stackoverflow.com/questions/106179/regular-expression-to-match-dns-hostname-or-ip-address\n// export const hostname: RegExp = /^([a-zA-Z0-9-]+\\.)*[a-zA-Z0-9-]+$/;\nexport const hostname = /^(?=.{1,253}\\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\\.?$/;\nexport const domain = /^(?=.{1,253}$)([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,63}$/;\nexport const httpProtocol = /^https?$/;\n// https://blog.stevenlevithan.com/archives/validate-phone-number#r4-3 (regex sans spaces) E.164: leading digit must be 1-9; total digits (excluding '+') between 7-15\nexport const e164 = /^\\+[1-9]\\d{6,14}$/;\n// Credit card shape: 12–19 digits, optionally separated by single spaces or single hyphens. ISO/IEC 7812 caps the PAN at 19 digits; 12 is the shortest issued length (Maestro).\nexport const creditCard = /^\\d(?:[ -]?\\d){11,18}$/;\n// ISO 4217 alpha codes from the SIX list, regenerated by scripts/update-iso-4217.ts\nexport const currencyCode = /^(?:AED|AFN|ALL|AMD|AOA|ARS|AUD|AWG|AZN|BAM|BBD|BDT|BHD|BIF|BMD|BND|BOB|BOV|BRL|BSD|BTN|BWP|BYN|BZD|CAD|CDF|CHE|CHF|CHW|CLF|CLP|CNY|COP|COU|CRC|CUP|CVE|CZK|DJF|DKK|DOP|DZD|EGP|ERN|ETB|EUR|FJD|FKP|GBP|GEL|GHS|GIP|GMD|GNF|GTQ|GYD|HKD|HNL|HTG|HUF|IDR|ILS|INR|IQD|IRR|ISK|JMD|JOD|JPY|KES|KGS|KHR|KMF|KPW|KRW|KWD|KYD|KZT|LAK|LBP|LKR|LRD|LSL|LYD|MAD|MDL|MGA|MKD|MMK|MNT|MOP|MRU|MUR|MVR|MWK|MXN|MXV|MYR|MZN|NAD|NGN|NIO|NOK|NPR|NZD|OMR|PAB|PEN|PGK|PHP|PKR|PLN|PYG|QAR|RON|RSD|RUB|RWF|SAR|SBD|SCR|SDG|SEK|SGD|SHP|SLE|SOS|SRD|SSP|STN|SVC|SYP|SZL|THB|TJS|TMT|TND|TOP|TRY|TTD|TWD|TZS|UAH|UGX|USD|USN|UYI|UYU|UYW|UZS|VED|VES|VND|VUV|WST|XAD|XAF|XAG|XAU|XBA|XBB|XBC|XBD|XCD|XCG|XDR|XOF|XPD|XPF|XPT|XSU|XTS|XUA|XXX|YER|ZAR|ZMW|ZWG)$/;\n// iban electronic format: 2-letter country, check digits 02-98 (the only values `98 - remainder` can produce), 11-30 bban characters\nexport const iban = /^[A-Z]{2}(?!00|01|99)\\d{2}[A-Z0-9]{11,30}$/;\nconst dateSource = `(?:(?:\\\\d\\\\d[2468][048]|\\\\d\\\\d[13579][26]|\\\\d\\\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\\\d|30)|(?:02)-(?:0[1-9]|1\\\\d|2[0-8])))`;\n/** Anchors a pattern source. The interpolation lives here rather than at the call site because\n * esbuild will not drop a `@__PURE__` call whose own argument interpolates a variable, but it\n * will drop `anchor(dateSource)`. Keeping it inline pinned `date` into every bundle. */\nfunction anchor(source) {\n return new RegExp(`^${source}$`);\n}\nexport const date = /*@__PURE__*/ anchor(dateSource);\nfunction timeSource(args) {\n const hhmm = `(?:[01]\\\\d|2[0-3]):[0-5]\\\\d`;\n const regex = typeof args.precision === \"number\"\n ? args.precision === -1\n ? `${hhmm}`\n : args.precision === 0\n ? `${hhmm}:[0-5]\\\\d`\n : `${hhmm}:[0-5]\\\\d\\\\.\\\\d{${args.precision}}`\n : args.seconds\n ? `${hhmm}:[0-5]\\\\d(?:\\\\.\\\\d+)?`\n : `${hhmm}(?::[0-5]\\\\d(?:\\\\.\\\\d+)?)?`;\n return regex;\n}\nexport function time(args) {\n return new RegExp(`^${timeSource(args)}$`);\n}\n// Adapted from https://stackoverflow.com/a/3143231\nexport function datetime(args) {\n const opts = [\"Z\"];\n // if (args.offset) opts.push(`([+-]\\\\d{2}:\\\\d{2})`);\n if (args.offset)\n opts.push(`([+-](?:[01]\\\\d|2[0-3]):[0-5]\\\\d)`);\n // RFC 3339 mandates seconds wherever the time carries a `Z` or an offset, so only the unqualified form `local` adds may omit them\n const qualified = `${timeSource({ precision: args.precision, seconds: true })}(?:${opts.join(\"|\")})`;\n const timeRegex = args.local ? `${qualified}|${timeSource({ precision: args.precision })}` : qualified;\n return new RegExp(`^${dateSource}T(?:${timeRegex})$`);\n}\n// the unbounded form of `string()` as a literal, so every plain string shares one instance instead of building its own\nexport const anyString = /^[\\s\\S]{0,}$/;\nexport const string = (params) => {\n const regex = params ? `[\\\\s\\\\S]{${params?.minimum ?? 0},${params?.maximum ?? \"\"}}` : `[\\\\s\\\\S]*`;\n return new RegExp(`^${regex}$`);\n};\nexport const bigint = /^-?\\d+n?$/;\nexport const integer = /^-?\\d+$/;\nexport const number = /^-?\\d+(?:\\.\\d+)?$/;\nexport const boolean = /^(?:true|false)$/i;\nconst _null = /^null$/i;\nexport { _null as null };\nconst _undefined = /^undefined$/i;\nexport { _undefined as undefined };\n// regex for string with no uppercase letters\nexport const lowercase = /^[^A-Z]*$/;\n// regex for string with no lowercase letters\nexport const uppercase = /^[^a-z]*$/;\n// regex for hexadecimal strings (any length)\nexport const hex = /^[0-9a-fA-F]*$/;\n// Hash regexes for different algorithms and encodings\n// Helper function to create base64 regex with exact length and padding\nfunction fixedBase64(bodyLength, padding) {\n return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`);\n}\n// Helper function to create base64url regex with exact length (no padding)\nfunction fixedBase64url(length) {\n return new RegExp(`^[A-Za-z0-9_-]{${length}}$`);\n}\n// MD5 (16 bytes): base64 = 24 chars total (22 + \"==\")\nexport const md5_hex = /^[0-9a-fA-F]{32}$/;\nexport const md5_base64 = /*@__PURE__*/ fixedBase64(22, \"==\");\nexport const md5_base64url = /*@__PURE__*/ fixedBase64url(22);\n// SHA1 (20 bytes): base64 = 28 chars total (27 + \"=\")\nexport const sha1_hex = /^[0-9a-fA-F]{40}$/;\nexport const sha1_base64 = /*@__PURE__*/ fixedBase64(27, \"=\");\nexport const sha1_base64url = /*@__PURE__*/ fixedBase64url(27);\n// SHA256 (32 bytes): base64 = 44 chars total (43 + \"=\")\nexport const sha256_hex = /^[0-9a-fA-F]{64}$/;\nexport const sha256_base64 = /*@__PURE__*/ fixedBase64(43, \"=\");\nexport const sha256_base64url = /*@__PURE__*/ fixedBase64url(43);\n// SHA384 (48 bytes): base64 = 64 chars total (no padding)\nexport const sha384_hex = /^[0-9a-fA-F]{96}$/;\nexport const sha384_base64 = /*@__PURE__*/ fixedBase64(64, \"\");\nexport const sha384_base64url = /*@__PURE__*/ fixedBase64url(64);\n// SHA512 (64 bytes): base64 = 88 chars total (86 + \"==\")\nexport const sha512_hex = /^[0-9a-fA-F]{128}$/;\nexport const sha512_base64 = /*@__PURE__*/ fixedBase64(86, \"==\");\nexport const sha512_base64url = /*@__PURE__*/ fixedBase64url(86);\n","// import { $ZodType } from \"./schemas.js\";\nimport * as core from \"./core.js\";\nimport * as regexes from \"./regexes.js\";\nimport * as util from \"./util.js\";\nexport const $ZodCheck = /*@__PURE__*/ core.$constructor(\"$ZodCheck\", (inst, def) => {\n var _a;\n inst._zod ?? (inst._zod = {});\n inst._zod.def = def;\n (_a = inst._zod).onattach ?? (_a.onattach = []);\n});\n/** Default `when` for size-based checks: run only on non-nullish values with a `size`. */\nconst _whenHasSize = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.size !== undefined;\n};\n/** Default `when` for length-based checks: run only on non-nullish values with a `length`. */\nconst _whenHasLength = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.length !== undefined;\n};\nconst numericOriginMap = {\n number: \"number\",\n bigint: \"bigint\",\n object: \"date\",\n};\nexport const $ZodCheckLessThan = /*@__PURE__*/ core.$constructor(\"$ZodCheckLessThan\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const origin = numericOriginMap[typeof def.value];\n inst._zod.check = (payload) => {\n if (def.inclusive ? payload.value <= def.value : payload.value < def.value) {\n return;\n }\n payload.issues.push({\n origin: numericOriginMap[typeof payload.value] ?? origin,\n code: \"too_big\",\n maximum: typeof def.value === \"object\" ? def.value.getTime() : def.value,\n input: payload.value,\n inclusive: def.inclusive,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckGreaterThan = /*@__PURE__*/ core.$constructor(\"$ZodCheckGreaterThan\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const origin = numericOriginMap[typeof def.value];\n inst._zod.check = (payload) => {\n if (def.inclusive ? payload.value >= def.value : payload.value > def.value) {\n return;\n }\n payload.issues.push({\n origin: numericOriginMap[typeof payload.value] ?? origin,\n code: \"too_small\",\n minimum: typeof def.value === \"object\" ? def.value.getTime() : def.value,\n input: payload.value,\n inclusive: def.inclusive,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMultipleOf = \n/*@__PURE__*/ core.$constructor(\"$ZodCheckMultipleOf\", (inst, def) => {\n $ZodCheck.init(inst, def);\n inst._zod.check = (payload) => {\n if (typeof payload.value !== typeof def.value)\n throw new Error(\"Cannot mix number and bigint in multiple_of check.\");\n const isMultiple = typeof payload.value === \"bigint\"\n ? // `value % 0n` throws, and nothing is a multiple of zero — the number branch already fails this way via NaN\n def.value !== BigInt(0) && payload.value % def.value === BigInt(0)\n : util.floatSafeRemainder(payload.value, def.value) === 0;\n if (isMultiple)\n return;\n payload.issues.push({\n origin: typeof payload.value,\n code: \"not_multiple_of\",\n divisor: def.value,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckNumberFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckNumberFormat\", (inst, def) => {\n $ZodCheck.init(inst, def); // no format checks\n def.format = def.format || \"float64\";\n const isInt = def.format?.includes(\"int\");\n const origin = isInt ? \"int\" : \"number\";\n const [minimum, maximum] = util.NUMBER_FORMAT_RANGES[def.format];\n inst._zod.check = (payload) => {\n const input = payload.value;\n if (isInt) {\n if (!Number.isInteger(input)) {\n // invalid_format issue\n // payload.issues.push({\n // expected: def.format,\n // format: def.format,\n // code: \"invalid_format\",\n // input,\n // inst,\n // });\n // invalid_type issue\n payload.issues.push({\n expected: origin,\n format: def.format,\n code: \"invalid_type\",\n continue: false,\n input,\n inst,\n });\n return;\n // not_multiple_of issue\n // payload.issues.push({\n // code: \"not_multiple_of\",\n // origin: \"number\",\n // input,\n // inst,\n // divisor: 1,\n // });\n }\n if (!Number.isSafeInteger(input)) {\n if (input > 0) {\n // too_big\n payload.issues.push({\n input,\n code: \"too_big\",\n maximum: Number.MAX_SAFE_INTEGER,\n note: \"Integers must be within the safe integer range.\",\n inst,\n origin,\n inclusive: true,\n continue: !def.abort,\n });\n }\n else {\n // too_small\n payload.issues.push({\n input,\n code: \"too_small\",\n minimum: Number.MIN_SAFE_INTEGER,\n note: \"Integers must be within the safe integer range.\",\n inst,\n origin,\n inclusive: true,\n continue: !def.abort,\n });\n }\n return;\n }\n }\n if (input < minimum) {\n payload.issues.push({\n origin: \"number\",\n input,\n code: \"too_small\",\n minimum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n if (input > maximum) {\n payload.issues.push({\n origin: \"number\",\n input,\n code: \"too_big\",\n maximum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodCheckBigIntFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckBigIntFormat\", (inst, def) => {\n $ZodCheck.init(inst, def); // no format checks\n const [minimum, maximum] = util.BIGINT_FORMAT_RANGES[def.format];\n inst._zod.check = (payload) => {\n const input = payload.value;\n if (input < minimum) {\n payload.issues.push({\n origin: \"bigint\",\n input,\n code: \"too_small\",\n minimum: minimum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n if (input > maximum) {\n payload.issues.push({\n origin: \"bigint\",\n input,\n code: \"too_big\",\n maximum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodCheckMaxSize = /*@__PURE__*/ core.$constructor(\"$ZodCheckMaxSize\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = _whenHasSize);\n inst._zod.check = (payload) => {\n const input = payload.value;\n const size = input.size;\n if (size <= def.maximum)\n return;\n payload.issues.push({\n origin: util.getSizableOrigin(input),\n code: \"too_big\",\n maximum: def.maximum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMinSize = /*@__PURE__*/ core.$constructor(\"$ZodCheckMinSize\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = _whenHasSize);\n inst._zod.check = (payload) => {\n const input = payload.value;\n const size = input.size;\n if (size >= def.minimum)\n return;\n payload.issues.push({\n origin: util.getSizableOrigin(input),\n code: \"too_small\",\n minimum: def.minimum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckSizeEquals = /*@__PURE__*/ core.$constructor(\"$ZodCheckSizeEquals\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = _whenHasSize);\n inst._zod.check = (payload) => {\n const input = payload.value;\n const size = input.size;\n if (size === def.size)\n return;\n const tooBig = size > def.size;\n payload.issues.push({\n origin: util.getSizableOrigin(input),\n ...(tooBig ? { code: \"too_big\", maximum: def.size } : { code: \"too_small\", minimum: def.size }),\n inclusive: true,\n exact: true,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMaxLength = /*@__PURE__*/ core.$constructor(\"$ZodCheckMaxLength\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = _whenHasLength);\n inst._zod.check = (payload) => {\n const input = payload.value;\n const units = input.length;\n // Strings are measured in Unicode code points, not UTF-16 units. A code point is at most two units, so a string that already fits in units fits in code points; only an overflow has to be counted.\n const length = typeof input === \"string\" && units > def.maximum ? util.codePointLength(input) : units;\n if (length <= def.maximum)\n return;\n const origin = util.getLengthableOrigin(input);\n payload.issues.push({\n origin,\n code: \"too_big\",\n maximum: def.maximum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMinLength = /*@__PURE__*/ core.$constructor(\"$ZodCheckMinLength\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = _whenHasLength);\n inst._zod.check = (payload) => {\n const input = payload.value;\n const units = input.length;\n // A code point is one or two UTF-16 units, so fewer units than the floor can never reach it and twice the floor always clears it. Only in between is the exact count in doubt.\n const length = typeof input === \"string\" && units >= def.minimum && units < def.minimum * 2\n ? util.codePointLength(input)\n : units;\n if (length >= def.minimum)\n return;\n const origin = util.getLengthableOrigin(input);\n payload.issues.push({\n origin,\n code: \"too_small\",\n minimum: def.minimum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckLengthEquals = /*@__PURE__*/ core.$constructor(\"$ZodCheckLengthEquals\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = _whenHasLength);\n inst._zod.check = (payload) => {\n const input = payload.value;\n const units = input.length;\n // A code point is one or two UTF-16 units, so outside `[length, length * 2]` units the target is missed either way — and missed in the same direction in both measures.\n const length = typeof input === \"string\" && units >= def.length && units <= def.length * 2\n ? util.codePointLength(input)\n : units;\n if (length === def.length)\n return;\n const origin = util.getLengthableOrigin(input);\n const tooBig = length > def.length;\n payload.issues.push({\n origin,\n ...(tooBig ? { code: \"too_big\", maximum: def.length } : { code: \"too_small\", minimum: def.length }),\n inclusive: true,\n exact: true,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckStringFormat\", (inst, def) => {\n var _a, _b;\n $ZodCheck.init(inst, def);\n if (def.pattern)\n (_a = inst._zod).check ?? (_a.check = (payload) => {\n def.pattern.lastIndex = 0;\n if (def.pattern.test(payload.value))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: def.format,\n input: payload.value,\n ...(def.pattern ? { pattern: def.pattern.toString() } : {}),\n inst,\n continue: !def.abort,\n });\n });\n else\n (_b = inst._zod).check ?? (_b.check = () => { });\n});\nexport const $ZodCheckRegex = /*@__PURE__*/ core.$constructor(\"$ZodCheckRegex\", (inst, def) => {\n $ZodCheckStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n def.pattern.lastIndex = 0;\n if (def.pattern.test(payload.value))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"regex\",\n input: payload.value,\n pattern: def.pattern.toString(),\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckLowerCase = /*@__PURE__*/ core.$constructor(\"$ZodCheckLowerCase\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.lowercase);\n $ZodCheckStringFormat.init(inst, def);\n});\nexport const $ZodCheckUpperCase = /*@__PURE__*/ core.$constructor(\"$ZodCheckUpperCase\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.uppercase);\n $ZodCheckStringFormat.init(inst, def);\n});\nexport const $ZodCheckIncludes = /*@__PURE__*/ core.$constructor(\"$ZodCheckIncludes\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const escapedRegex = util.escapeRegex(def.includes);\n // `String.prototype.includes(sub, position)` matches `sub` at `position`\n // OR LATER, so the pattern must allow at least `position` leading chars\n // (`{N,}`), not exactly `position` chars (`{N}`).\n const pattern = new RegExp(typeof def.position === \"number\" ? `^.{${def.position},}${escapedRegex}` : escapedRegex);\n def.pattern = pattern;\n inst._zod.check = (payload) => {\n if (payload.value.includes(def.includes, def.position))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"includes\",\n includes: def.includes,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckStartsWith = /*@__PURE__*/ core.$constructor(\"$ZodCheckStartsWith\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const pattern = new RegExp(`^${util.escapeRegex(def.prefix)}.*`);\n def.pattern ?? (def.pattern = pattern);\n inst._zod.check = (payload) => {\n if (payload.value.startsWith(def.prefix))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"starts_with\",\n prefix: def.prefix,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckEndsWith = /*@__PURE__*/ core.$constructor(\"$ZodCheckEndsWith\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const pattern = new RegExp(`.*${util.escapeRegex(def.suffix)}$`);\n def.pattern ?? (def.pattern = pattern);\n inst._zod.check = (payload) => {\n if (payload.value.endsWith(def.suffix))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"ends_with\",\n suffix: def.suffix,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\n///////////////////////////////////\n///// $ZodCheckProperty /////\n///////////////////////////////////\nfunction handleCheckPropertyResult(result, payload, property) {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(property, result.issues));\n }\n}\nexport const $ZodCheckProperty = /*@__PURE__*/ core.$constructor(\"$ZodCheckProperty\", (inst, def) => {\n $ZodCheck.init(inst, def);\n inst._zod.check = (payload) => {\n const result = def.schema._zod.run({\n value: payload.value[def.property],\n issues: [],\n }, {});\n if (result instanceof Promise) {\n return result.then((result) => handleCheckPropertyResult(result, payload, def.property));\n }\n handleCheckPropertyResult(result, payload, def.property);\n return;\n };\n});\nexport const $ZodCheckProperties = /*@__PURE__*/ core.$constructor(\"$ZodCheckProperties\", (inst, def) => {\n $ZodCheck.init(inst, def);\n util.hide(inst, Symbol.iterator, function* () {\n yield inst;\n });\n // key and schema snapshotted together: reading one live and the other cached lets a later mutation of the caller's shape object pair a stale key with a missing schema\n let entries;\n inst._zod.check = (payload) => {\n // the base schema already typed the value, so only a nullish one is rejected here: the properties read on a primitive too, matching z.property() on a string's length\n if (payload.value == null) {\n payload.issues.push({ expected: \"object\", code: \"invalid_type\", input: payload.value, inst });\n return undefined;\n }\n entries ?? (entries = Reflect.ownKeys(def.shape).map((key) => [key, def.shape[key]]));\n const input = payload.value;\n let proms;\n for (const [key, schema] of entries) {\n const result = schema._zod.run({ value: input[key], issues: [] }, {});\n if (result instanceof Promise) {\n proms ?? (proms = []);\n proms.push(result.then((result) => handleCheckPropertyResult(result, payload, key)));\n }\n else {\n handleCheckPropertyResult(result, payload, key);\n }\n }\n if (proms)\n return Promise.all(proms).then(() => undefined);\n return undefined;\n };\n});\nexport const $ZodCheckMimeType = /*@__PURE__*/ core.$constructor(\"$ZodCheckMimeType\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const mimeSet = new Set(def.mime);\n inst._zod.check = (payload) => {\n if (mimeSet.has(payload.value.type))\n return;\n payload.issues.push({\n code: \"invalid_value\",\n values: def.mime,\n input: payload.value.type,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckOverwrite = /*@__PURE__*/ core.$constructor(\"$ZodCheckOverwrite\", (inst, def) => {\n $ZodCheck.init(inst, def);\n inst._zod.check = (payload) => {\n payload.value = def.tx(payload.value);\n };\n});\n","export const version = {\n major: 4,\n minor: 6,\n patch: 5,\n};\n","import * as checks from \"./checks.js\";\nimport * as core from \"./core.js\";\nimport { Doc } from \"./doc.js\";\nimport { parse, parseAsync } from \"./parse.js\";\nimport * as regexes from \"./regexes.js\";\nimport * as util from \"./util.js\";\nimport { version } from \"./versions.js\";\nexport const $ZodType = /*@__PURE__*/ core.$constructor(\"$ZodType\", (inst, def) => {\n var _a;\n inst ?? (inst = {});\n inst._zod.def = def; // set _def property\n inst._zod.bag = inst._zod.bag || {}; // initialize _bag object\n inst._zod.version = version;\n const defChecks = inst._zod.def.checks;\n // if inst is itself a checks.$ZodCheck, run it as a check\n const checks = inst._zod.traits.has(\"$ZodCheck\")\n ? [inst, ...(defChecks ?? [])]\n : defChecks?.length\n ? [...defChecks]\n : [];\n for (const ch of checks) {\n for (const fn of ch._zod.onattach) {\n fn(inst);\n }\n }\n if (checks.length === 0) {\n // deferred initializer inst._zod.parse is not yet defined\n (_a = inst._zod).deferred ?? (_a.deferred = []);\n inst._zod.deferred?.push(() => {\n inst._zod.run = inst._zod.parse;\n });\n }\n else {\n const runChecks = (payload, checks, ctx) => {\n if (payload.memo)\n return payload;\n let isAborted = util.aborted(payload);\n let asyncResult;\n for (const ch of checks) {\n if (ch._zod.def.when) {\n if (util.explicitlyAborted(payload))\n continue;\n const shouldRun = ch._zod.def.when(payload);\n if (!shouldRun)\n continue;\n }\n else if (isAborted) {\n continue;\n }\n const currLen = payload.issues.length;\n const _ = ch._zod.check(payload);\n if (_ instanceof Promise && ctx?.async === false) {\n throw new core.$ZodAsyncError();\n }\n if (asyncResult || _ instanceof Promise) {\n asyncResult = (asyncResult ?? Promise.resolve()).then(async () => {\n await _;\n const nextLen = payload.issues.length;\n if (nextLen === currLen)\n return;\n util.attachSchema(payload.issues, currLen, inst);\n if (!isAborted)\n isAborted = util.aborted(payload, currLen);\n });\n }\n else {\n const nextLen = payload.issues.length;\n if (nextLen === currLen)\n continue;\n util.attachSchema(payload.issues, currLen, inst);\n if (!isAborted)\n isAborted = util.aborted(payload, currLen);\n }\n }\n if (asyncResult) {\n return asyncResult.then(() => {\n return payload;\n });\n }\n return payload;\n };\n const handleCanaryResult = (canary, payload, ctx) => {\n // abort if the canary is aborted\n if (util.aborted(canary)) {\n canary.aborted = true;\n return canary;\n }\n // run checks first, then\n const checkResult = runChecks(payload, checks, ctx);\n if (checkResult instanceof Promise) {\n if (ctx.async === false)\n throw new core.$ZodAsyncError();\n return checkResult.then((checkResult) => inst._zod.parse(checkResult, ctx));\n }\n return inst._zod.parse(checkResult, ctx);\n };\n inst._zod.run = (payload, ctx) => {\n if (ctx.skipChecks) {\n return inst._zod.parse(payload, ctx);\n }\n if (ctx.direction === \"backward\") {\n // run canary initial pass (no checks)\n const canary = inst._zod.parse({ value: payload.value, issues: [] }, { ...ctx, skipChecks: true });\n if (canary instanceof Promise) {\n return canary.then((canary) => {\n return handleCanaryResult(canary, payload, ctx);\n });\n }\n return handleCanaryResult(canary, payload, ctx);\n }\n // forward\n const result = inst._zod.parse(payload, ctx);\n if (result instanceof Promise) {\n if (ctx.async === false)\n throw new core.$ZodAsyncError();\n return result.then((result) => runChecks(result, checks, ctx));\n }\n return runChecks(result, checks, ctx);\n };\n }\n}, {\n // Wrappers extend this by installing a richer factory over it; reading it eagerly would defeat the laziness.\n get \"~standard\"() {\n return util.hide(this, \"~standard\", standardProps(this));\n },\n set \"~standard\"(value) {\n util.own(this, \"~standard\", value);\n },\n});\n/** The Standard Schema surface for `inst`. Shared so wrappers can extend it without forcing it. */\n// a Standard Schema result only reports issues, so a failure finalizes them straight off the raw payload: no ZodError, and no lazy result to read through\nconst toStandardResult = (r, ctx) => r.issues.length ? { issues: r.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())) } : { value: r.value };\nasync function validateAsync(inst, value) {\n const ctx = { async: true };\n return toStandardResult((await inst._zod.run({ value, issues: [] }, ctx)), ctx);\n}\nexport function standardProps(inst) {\n return {\n validate: (value) => {\n const ctx = { async: false };\n try {\n const r = inst._zod.run({ value, issues: [] }, ctx);\n if (!(r instanceof Promise))\n return toStandardResult(r, ctx);\n }\n catch (_) { }\n // async function so a synchronously throwing check rejects instead of escaping validate\n return validateAsync(inst, value);\n },\n vendor: \"zod\",\n version: 1,\n };\n}\nexport { clone } from \"./util.js\";\nexport const $ZodString = /*@__PURE__*/ core.$constructor(\"$ZodString\", (inst, def) => {\n $ZodType.init(inst, def);\n // a format's own pattern, else unbounded; a template literal derives the check-aware form itself\n inst._zod.pattern = def.pattern ?? regexes.anyString;\n inst._zod.parse = (payload, _) => {\n if (def.coerce)\n try {\n payload.value = String(payload.value);\n }\n catch (_) { }\n if (typeof payload.value === \"string\")\n return payload;\n payload.issues.push({\n expected: \"string\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodStringFormat\", (inst, def) => {\n // check initialization must come first\n checks.$ZodCheckStringFormat.init(inst, def);\n $ZodString.init(inst, def);\n});\nexport const $ZodGUID = /*@__PURE__*/ core.$constructor(\"$ZodGUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.guid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodUUID = /*@__PURE__*/ core.$constructor(\"$ZodUUID\", (inst, def) => {\n if (def.version) {\n const versionMap = {\n v1: 1,\n v2: 2,\n v3: 3,\n v4: 4,\n v5: 5,\n v6: 6,\n v7: 7,\n v8: 8,\n };\n const v = versionMap[def.version];\n if (v === undefined)\n throw new Error(`Invalid UUID version: \"${def.version}\"`);\n def.pattern ?? (def.pattern = regexes.uuid(v));\n }\n else\n def.pattern ?? (def.pattern = regexes.uuid());\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodEmail = /*@__PURE__*/ core.$constructor(\"$ZodEmail\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.email);\n $ZodStringFormat.init(inst, def);\n});\n/** The `://` guard rejected the input before the URL constructor saw it. */\nexport const URL_BAD_FORMAT = 1;\n/** The URL parser rejected the input. */\nexport const URL_UNPARSEABLE = 2;\nexport function canParseURL(input) {\n try {\n if (typeof URL !== \"undefined\" && typeof URL.canParse === \"function\")\n return URL.canParse(input);\n new URL(input);\n return true;\n }\n catch {\n return false;\n }\n}\nexport function validateURL(trimmed, def) {\n if (!(\"normalize\" in def) && !(\"hostname\" in def) && !(\"protocol\" in def)) {\n return canParseURL(trimmed) || URL_UNPARSEABLE;\n }\n return parseURLObject(trimmed, def);\n}\n/** Parses a URL while preserving the non-normalizing HTTP guard. */\nexport function parseURLObject(trimmed, def) {\n // When normalize is off, require :// for http/https URLs. This prevents strings like \"http:example.com\" or \"https:/path\" from being silently accepted\n if (!def.normalize && def.protocol?.source === regexes.httpProtocol.source && !/^https?:\\/\\//i.test(trimmed)) {\n return URL_BAD_FORMAT;\n }\n try {\n if (typeof URL !== \"undefined\") {\n const URLStatic = URL;\n if (typeof URLStatic.parse === \"function\")\n return URLStatic.parse(trimmed) ?? URL_UNPARSEABLE;\n }\n // @ts-ignore\n return new URL(trimmed);\n }\n catch {\n return URL_UNPARSEABLE;\n }\n}\nconst asciiTabOrNewline = /[\\t\\n\\r]/g;\n/** The URL parser deletes every ASCII tab, LF and CR from its input before it parses, so `new URL(\"https://exa\\nmple.com\")` reports on `example.com`. Applying the same deletion to the returned value closes the half of that divergence which can move the host; the parser's other rewrite, stripping C0 controls at the edges, cannot. */\nexport function stripTabAndNewline(value) {\n return value.replace(asciiTabOrNewline, \"\");\n}\nexport function urlHostnameOk(url, hostname) {\n hostname.lastIndex = 0;\n return hostname.test(url.hostname);\n}\nexport function urlProtocolOk(url, protocol) {\n protocol.lastIndex = 0;\n return protocol.test(url.protocol.endsWith(\":\") ? url.protocol.slice(0, -1) : url.protocol);\n}\nexport const $ZodURL = /*@__PURE__*/ core.$constructor(\"$ZodURL\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n try {\n // Trim whitespace from input\n const trimmed = payload.value.trim();\n const url = validateURL(trimmed, def);\n if (url === URL_BAD_FORMAT) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n note: \"Invalid URL format\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n return;\n }\n if (url === URL_UNPARSEABLE) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n return;\n }\n if (url === true) {\n payload.value = stripTabAndNewline(trimmed);\n return;\n }\n if (def.hostname && !urlHostnameOk(url, def.hostname)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n note: \"Invalid hostname\",\n pattern: def.hostname.source,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n if (def.protocol && !urlProtocolOk(url, def.protocol)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n note: \"Invalid protocol\",\n pattern: def.protocol.source,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n // Set the output value based on normalize flag\n payload.value = def.normalize ? url.href : stripTabAndNewline(trimmed);\n return;\n }\n catch (_) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodEmoji = /*@__PURE__*/ core.$constructor(\"$ZodEmoji\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.emoji());\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodNanoID = /*@__PURE__*/ core.$constructor(\"$ZodNanoID\", (inst, def) => {\n if (def.length !== undefined && (!Number.isInteger(def.length) || def.length < 1))\n throw new Error(`Invalid nanoid length: ${def.length}`);\n def.pattern ?? (def.pattern = def.length === undefined ? regexes.nanoid : regexes.nanoidOfLength(def.length));\n $ZodStringFormat.init(inst, def);\n});\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link $ZodCUID2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport const $ZodCUID = /*@__PURE__*/ core.$constructor(\"$ZodCUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cuid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodCUID2 = /*@__PURE__*/ core.$constructor(\"$ZodCUID2\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cuid2);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodULID = /*@__PURE__*/ core.$constructor(\"$ZodULID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ulid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodXID = /*@__PURE__*/ core.$constructor(\"$ZodXID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.xid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodKSUID = /*@__PURE__*/ core.$constructor(\"$ZodKSUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ksuid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODateTime = /*@__PURE__*/ core.$constructor(\"$ZodISODateTime\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.datetime(def));\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODate = /*@__PURE__*/ core.$constructor(\"$ZodISODate\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.date);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISOTime = /*@__PURE__*/ core.$constructor(\"$ZodISOTime\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.time(def));\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODuration = /*@__PURE__*/ core.$constructor(\"$ZodISODuration\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.duration);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodIPv4 = /*@__PURE__*/ core.$constructor(\"$ZodIPv4\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ipv4);\n $ZodStringFormat.init(inst, def);\n});\n/** An IPv6 address is written with hex digits, colons and dots, and nothing else. The guard is what makes the check below an IPv6 check: `new URL(\"http://[...]\")` parses an authority, not an address, so `@` and `\\` re-delimit it and `\"::@1\\\\\"` validates against the host `0.0.0.1`. The URL parser also deletes ASCII tab, LF and CR rather than failing, which is how `\"::1\\n\"` validated as `::1`. */\nconst ipv6Alphabet = /^[0-9a-fA-F:.]+$/;\nexport function isValidIPv6(value) {\n if (!ipv6Alphabet.test(value))\n return false;\n return canParseURL(`http://[${value}]`);\n}\nexport const $ZodIPv6 = /*@__PURE__*/ core.$constructor(\"$ZodIPv6\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ipv6);\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (!isValidIPv6(payload.value)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"ipv6\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodMAC = /*@__PURE__*/ core.$constructor(\"$ZodMAC\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.mac(def.delimiter));\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodCIDRv4 = /*@__PURE__*/ core.$constructor(\"$ZodCIDRv4\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cidrv4);\n $ZodStringFormat.init(inst, def);\n});\nexport function isValidCIDRv6(value) {\n const parts = value.split(\"/\");\n if (parts.length !== 2)\n return false;\n const [address, prefix] = parts;\n if (!prefix)\n return false;\n const prefixNum = Number(prefix);\n if (`${prefixNum}` !== prefix)\n return false;\n if (prefixNum < 0 || prefixNum > 128)\n return false;\n return isValidIPv6(address);\n}\nexport const $ZodCIDRv6 = /*@__PURE__*/ core.$constructor(\"$ZodCIDRv6\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cidrv6); // not used for validation\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (!isValidCIDRv6(payload.value)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"cidrv6\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\n////////////////////////////// ZodBase64 //////////////////////////////\nexport function isValidBase64(data) {\n if (data === \"\")\n return true;\n // atob ignores whitespace, so reject it up front.\n if (/\\s/.test(data))\n return false;\n if (data.length % 4 !== 0)\n return false;\n try {\n // @ts-ignore\n atob(data);\n return true;\n }\n catch {\n return false;\n }\n}\n// lax on purpose: the quantified regexes.base64 overflows the regex stack on multi-MB input and its leading ^$| alternation leaks through template-literal composition; isValidBase64 enforces length and padding\nexport const base64Charset = /^[0-9a-zA-Z+/]*={0,2}$/;\nexport const $ZodBase64 = /*@__PURE__*/ core.$constructor(\"$ZodBase64\", (inst, def) => {\n def.pattern ?? (def.pattern = base64Charset);\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (isValidBase64(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"base64\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\n////////////////////////////// ZodBase64URL //////////////////////////////\n// lax on purpose: the quantified regexes.base64url overflows the regex stack on multi-MB input; isValidBase64 enforces length on the padded string\nexport const base64urlCharset = /^[A-Za-z0-9_-]*$/;\nexport function isValidBase64URL(data) {\n if (!base64urlCharset.test(data))\n return false;\n const base64 = data.replace(/[-_]/g, (c) => (c === \"-\" ? \"+\" : \"/\"));\n const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, \"=\");\n return isValidBase64(padded);\n}\nexport const $ZodBase64URL = /*@__PURE__*/ core.$constructor(\"$ZodBase64URL\", (inst, def) => {\n def.pattern ?? (def.pattern = base64urlCharset);\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (isValidBase64URL(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"base64url\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodE164 = /*@__PURE__*/ core.$constructor(\"$ZodE164\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.e164);\n $ZodStringFormat.init(inst, def);\n});\n////////////////////////////// ZodCreditCard //////////////////////////////\nconst CC_SANITIZE = /[- ]/g;\n/** Luhn checksum on a digit-only string. Adapted from valibot (MIT). */\nfunction isLuhnAlgo(digits) {\n let length = digits.length;\n let bit = 1;\n let sum = 0;\n while (length) {\n const value = digits.charCodeAt(--length) - 48;\n bit ^= 1;\n sum += bit ? [0, 2, 4, 6, 8, 1, 3, 5, 7, 9][value] : value;\n }\n return sum % 10 === 0;\n}\nexport function isValidCreditCard(input) {\n if (!regexes.creditCard.test(input))\n return false;\n return isLuhnAlgo(input.replace(CC_SANITIZE, \"\"));\n}\nexport const $ZodCreditCard = /*@__PURE__*/ core.$constructor(\"$ZodCreditCard\", (inst, def) => {\n // Shape only — the Luhn check below is not expressible as a pattern, so consumers of `pattern` (JSON Schema, template literals) get the length and separator rules alone.\n def.pattern ?? (def.pattern = regexes.creditCard);\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (isValidCreditCard(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"credit_card\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\n////////////////////////////// ZodIBAN //////////////////////////////\n// iso 7064 mod 97-10 checksum without BigInt\nfunction isIso7064Mod97(iban) {\n let remainder = 0;\n const len = iban.length;\n for (let i = 4; i < len; i++) {\n const code = iban.charCodeAt(i);\n remainder = (code >= 65 ? remainder * 100 + (code - 55) : remainder * 10 + (code - 48)) % 97;\n }\n for (let i = 0; i < 4; i++) {\n const code = iban.charCodeAt(i);\n remainder = (code >= 65 ? remainder * 100 + (code - 55) : remainder * 10 + (code - 48)) % 97;\n }\n return remainder === 1;\n}\nexport function isValidIBAN(input) {\n if (!regexes.iban.test(input))\n return false;\n return isIso7064Mod97(input);\n}\nexport const $ZodIBAN = /*@__PURE__*/ core.$constructor(\"$ZodIBAN\", (inst, def) => {\n // shape only — checksum is not expressible as a pattern\n def.pattern ?? (def.pattern = regexes.iban);\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (isValidIBAN(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"iban\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\n////////////////////////////// ZodJWT //////////////////////////////\nexport function isValidJWT(token, algorithm = null) {\n try {\n const tokensParts = token.split(\".\");\n if (tokensParts.length !== 3)\n return false;\n const [header] = tokensParts;\n if (!header)\n return false;\n // @ts-ignore\n const parsedHeader = JSON.parse(atob(header));\n if (\"typ\" in parsedHeader && parsedHeader?.typ !== \"JWT\")\n return false;\n if (!parsedHeader.alg)\n return false;\n if (algorithm && (!(\"alg\" in parsedHeader) || parsedHeader.alg !== algorithm))\n return false;\n return true;\n }\n catch {\n return false;\n }\n}\nexport const $ZodJWT = /*@__PURE__*/ core.$constructor(\"$ZodJWT\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (isValidJWT(payload.value, def.alg))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"jwt\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCustomStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodCustomStringFormat\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (def.fn(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: def.format,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodNumber = /*@__PURE__*/ core.$constructor(\"$ZodNumber\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.number;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = Number(payload.value);\n }\n catch (_) { }\n const input = payload.value;\n if (typeof input === \"number\" && !Number.isNaN(input) && Number.isFinite(input)) {\n return payload;\n }\n const received = typeof input === \"number\"\n ? Number.isNaN(input)\n ? \"NaN\"\n : !Number.isFinite(input)\n ? String(input)\n : undefined\n : undefined;\n payload.issues.push({\n expected: \"number\",\n code: \"invalid_type\",\n input,\n inst,\n ...(received ? { received } : {}),\n });\n return payload;\n };\n});\nexport const $ZodNumberFormat = /*@__PURE__*/ core.$constructor(\"$ZodNumberFormat\", (inst, def) => {\n checks.$ZodCheckNumberFormat.init(inst, def);\n $ZodNumber.init(inst, def); // no format checks\n});\nexport const $ZodBoolean = /*@__PURE__*/ core.$constructor(\"$ZodBoolean\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.boolean;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = Boolean(payload.value);\n }\n catch (_) { }\n const input = payload.value;\n if (typeof input === \"boolean\")\n return payload;\n payload.issues.push({\n expected: \"boolean\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodBigInt = /*@__PURE__*/ core.$constructor(\"$ZodBigInt\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.bigint;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = BigInt(payload.value);\n }\n catch (_) { }\n if (typeof payload.value === \"bigint\")\n return payload;\n payload.issues.push({\n expected: \"bigint\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodBigIntFormat = /*@__PURE__*/ core.$constructor(\"$ZodBigIntFormat\", (inst, def) => {\n checks.$ZodCheckBigIntFormat.init(inst, def);\n $ZodBigInt.init(inst, def); // no format checks\n});\nexport const $ZodSymbol = /*@__PURE__*/ core.$constructor(\"$ZodSymbol\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"symbol\")\n return payload;\n payload.issues.push({\n expected: \"symbol\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodUndefined = /*@__PURE__*/ core.$constructor(\"$ZodUndefined\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.undefined;\n inst._zod.values = new Set([undefined]);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"undefined\")\n return payload;\n payload.issues.push({\n expected: \"undefined\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodNull = /*@__PURE__*/ core.$constructor(\"$ZodNull\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.null;\n inst._zod.values = new Set([null]);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (input === null)\n return payload;\n payload.issues.push({\n expected: \"null\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodAny = /*@__PURE__*/ core.$constructor(\"$ZodAny\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload) => payload;\n});\nexport const $ZodUnknown = /*@__PURE__*/ core.$constructor(\"$ZodUnknown\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload) => payload;\n});\nexport const $ZodNever = /*@__PURE__*/ core.$constructor(\"$ZodNever\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n payload.issues.push({\n expected: \"never\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodVoid = /*@__PURE__*/ core.$constructor(\"$ZodVoid\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"undefined\")\n return payload;\n payload.issues.push({\n expected: \"void\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodDate = /*@__PURE__*/ core.$constructor(\"$ZodDate\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce) {\n try {\n payload.value = new Date(payload.value);\n }\n catch (_err) { }\n }\n const input = payload.value;\n const isDate = input instanceof Date;\n const isValidDate = isDate && !Number.isNaN(input.getTime());\n if (isValidDate)\n return payload;\n payload.issues.push({\n expected: \"date\",\n code: \"invalid_type\",\n input,\n ...(isDate ? { received: \"Invalid Date\" } : {}),\n inst,\n });\n return payload;\n };\n});\nfunction handleArrayResult(result, final, index) {\n if (result.issues.length) {\n final.issues.push(...util.prefixIssues(index, result.issues));\n }\n final.value[index] = result.value;\n}\nexport const $ZodArray = /*@__PURE__*/ core.$constructor(\"$ZodArray\", (inst, def) => {\n $ZodType.init(inst, def);\n const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!Array.isArray(input)) {\n payload.issues.push({\n expected: \"array\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n payload.value = memo ? memo.alloc(inst, payload, Array(input.length), ctx) : Array(input.length);\n const proms = [];\n const abortEarly = ctx?.abortEarly;\n for (let i = 0; i < input.length; i++) {\n const item = input[i];\n const result = def.element._zod.run({\n value: item,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => handleArrayResult(result, payload, i)));\n }\n else {\n handleArrayResult(result, payload, i);\n // the element's payload is authoritative here, since handleArrayResult forwards every issue; an object's is not, because it drops a failed absent optional\n if (abortEarly && result.issues.length !== 0 && util.aborted(result))\n break;\n }\n }\n if (proms.length) {\n return Promise.all(proms).then(() => payload);\n }\n return payload; //handleArrayResultsAsync(parseResults, final);\n };\n});\nfunction handlePropertyResult(result, final, key, input, optin, optout) {\n const isPresent = key in input;\n const isOptionalOut = optout === \"optional\";\n // The middle rung means \"absence permitted, nothing supplied in its place\", so an absent key contributes nothing — whatever the schema made of `undefined` is invented, not substituted. Only `optional` reaches this with a value: `defaulted` substitutes, and a schema that isn't optional-out has to keep the key.\n if (!isPresent && isOptionalOut && optin === \"optional\") {\n return;\n }\n if (result.issues.length) {\n // For optional-in/out schemas, ignore errors on absent keys.\n if (optin !== undefined && isOptionalOut && !isPresent) {\n return;\n }\n final.issues.push(...util.prefixIssues(key, result.issues));\n }\n if (!isPresent && optin === undefined) {\n if (!result.issues.length) {\n final.issues.push({\n code: \"invalid_type\",\n expected: \"nonoptional\",\n input: undefined,\n path: [key],\n });\n }\n return;\n }\n if (result.value === undefined) {\n if (isPresent || (optin === \"defaulted\" && !isOptionalOut)) {\n final.value[key] = undefined;\n }\n }\n else {\n final.value[key] = result.value;\n }\n}\n// one shared instance; a fresh [] per schema cost 56 bytes retained\nconst NO_SYMBOL_KEYS = [];\nfunction normalizeDef(def) {\n const keys = Object.keys(def.shape);\n const ownSymbols = Object.getOwnPropertySymbols(def.shape);\n const symbolKeys = ownSymbols.length ? ownSymbols : NO_SYMBOL_KEYS;\n // aliases `keys` when there are no symbols, so a string-only shape keeps one array\n const allKeys = symbolKeys.length ? [...keys, ...symbolKeys] : keys;\n for (const k of allKeys) {\n if (!def.shape?.[k]?._zod?.traits?.has(\"$ZodType\")) {\n throw new Error(`Invalid element at key \"${String(k)}\": expected a Zod schema`);\n }\n }\n const okeys = util.optionalKeys(def.shape);\n return {\n ...def,\n allKeys,\n symbolKeys,\n // string-only: handleCatchall matches it against `for...in`, which never yields a symbol\n keySet: new Set(keys),\n numKeys: keys.length,\n optionalKeys: new Set(okeys),\n };\n}\nfunction handleCatchall(proms, input, payload, ctx, def, inst, abortEarly) {\n const unrecognized = [];\n const keySet = def.keySet;\n const _catchall = def.catchall._zod;\n const t = _catchall.def.type;\n const optin = _catchall.optin;\n const optout = _catchall.optout;\n // starts at 0, not the current length: the shape phase already ran and may have aborted\n let seen = 0;\n for (const key in input) {\n if (abortEarly && payload.issues.length !== seen) {\n if (util.aborted(payload, seen))\n break;\n seen = payload.issues.length;\n }\n // Must precede the __proto__ branch: a declared key is not unrecognized, even though the shape loop deliberately strips __proto__ from the parsed output.\n if (keySet.has(key))\n continue;\n // Don't copy an undeclared __proto__ into the result; assignment to a plain {} would replace the result prototype. But in strict mode it is still an unknown key, so report it before skipping.\n if (key === \"__proto__\") {\n if (t === \"never\")\n unrecognized.push(key);\n continue;\n }\n if (t === \"never\") {\n unrecognized.push(key);\n continue;\n }\n const r = _catchall.run({ value: input[key], issues: [] }, ctx);\n if (r instanceof Promise) {\n proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, optin, optout)));\n }\n else {\n handlePropertyResult(r, payload, key, input, optin, optout);\n }\n }\n if (unrecognized.length) {\n payload.issues.push({\n code: \"unrecognized_keys\",\n keys: unrecognized,\n input,\n inst,\n // Describes the shape of the input, not the validity of the parsed value, so it never aborts. The parse still fails; the schema's own checks just get to run first, and an enclosing intersection can reconcile the key against a sibling operand.\n continue: true,\n });\n }\n if (!proms.length)\n return payload;\n return Promise.all(proms).then(() => {\n return payload;\n });\n}\nexport const $ZodObject = /*@__PURE__*/ core.$constructor(\"$ZodObject\", (inst, def) => {\n // requires cast because technically $ZodObject doesn't extend\n $ZodType.init(inst, def);\n const desc = Object.getOwnPropertyDescriptor(def, \"shape\");\n // a cloned def carries its source's accessor, which knows the shape it answers from; adopting that keeps the clone's keys readable without running it\n const sh = desc?.get ? desc.get.raw : (def.shape ?? {});\n if (sh) {\n // Freezes the shape on first read, so its getters resolve once and every later read sees the same schemas.\n const get = () => {\n const newSh = { ...sh };\n Object.defineProperty(def, \"shape\", { value: newSh });\n get.raw = newSh;\n return newSh;\n };\n get.raw = sh;\n Object.defineProperty(def, \"shape\", { get });\n }\n const _normalized = util.cached(() => normalizeDef(def));\n util.defineLazyInternal(inst, \"propValues\", (zod) => {\n const shape = zod.def.shape;\n const propValues = {};\n for (const key in shape) {\n const field = shape[key]._zod;\n if (field.values) {\n if (!Object.prototype.hasOwnProperty.call(propValues, key)) {\n util.assignProp(propValues, key, new Set());\n }\n for (const v of field.values)\n propValues[key].add(v);\n // An omittable slot reads back as undefined at a discriminator lookup, so it has to claim undefined: two options that can both omit the key are not discriminable on it.\n if (field.optin !== undefined)\n propValues[key].add(undefined);\n }\n }\n return propValues;\n });\n const isObject = util.isObject;\n const catchall = def.catchall;\n let value;\n const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\n inst._zod.parse = (payload, ctx) => {\n value ?? (value = _normalized.value);\n const input = payload.value;\n if (!isObject(input)) {\n payload.issues.push({\n expected: \"object\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {};\n const proms = [];\n const shape = value.shape;\n const abortEarly = ctx?.abortEarly;\n let seen = payload.issues.length;\n for (const key of value.allKeys) {\n if (abortEarly && payload.issues.length !== seen) {\n if (util.aborted(payload, seen))\n break;\n seen = payload.issues.length;\n }\n if (key === \"__proto__\")\n continue;\n const el = shape[key];\n const optin = el._zod.optin;\n const optout = el._zod.optout;\n const r = el._zod.run({ value: input[key], issues: [] }, ctx);\n if (r instanceof Promise) {\n proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, optin, optout)));\n }\n else {\n handlePropertyResult(r, payload, key, input, optin, optout);\n }\n }\n if (!catchall) {\n return proms.length ? Promise.all(proms).then(() => payload) : payload;\n }\n return handleCatchall(proms, input, payload, ctx, _normalized.value, inst, abortEarly === true);\n };\n});\nexport const $ZodObjectJIT = /*@__PURE__*/ core.$constructor(\"$ZodObjectJIT\", (inst, def) => {\n // requires cast because technically $ZodObject doesn't extend\n $ZodObject.init(inst, def);\n const superParse = inst._zod.parse;\n const _normalized = util.cached(() => normalizeDef(def));\n const memo = core.globalConfig.memoizer;\n const generateFastpass = (shape) => {\n const normalized = _normalized.value;\n const syms = normalized.symbolKeys;\n // a symbol has no source literal, so it is read as `syms[i]` off the closed-over scope\n const doc = new Doc([\"payload\", \"ctx\"], { shape, inst, memo, syms });\n const parseStr = (k) => `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;\n // prefixes in place, like util.prefixIssues. newResult must land before the early return: a catchall runs after this and would otherwise write onto the caller's input\n const prefixStr = (id, k) => `\n let ${id}_ab = false;\n for (let i = 0; i < ${id}.issues.length; i++) {\n const iss = ${id}.issues[i];\n iss.path = iss.path ? [${k}, ...iss.path] : [${k}];\n payload.issues.push(iss);\n if (iss.continue !== true) ${id}_ab = true;\n }\n if (${id}_ab && ctx && ctx.abortEarly) {\n payload.value = newResult;\n return payload;\n }`;\n doc.write(`const input = payload.value;`);\n const ids = Object.create(null);\n let counter = 0;\n for (const key of normalized.allKeys) {\n ids[key] = `key_${counter++}`;\n }\n // A: preserve key order {\n doc.write(memo ? `const newResult = memo.alloc(inst, payload, {}, ctx);` : `const newResult = {};`);\n for (const key of normalized.allKeys) {\n if (key === \"__proto__\")\n continue;\n const id = ids[key];\n const k = typeof key === \"symbol\" ? `syms[${syms.indexOf(key)}]` : util.esc(key);\n const isPresent = `${k} in input`;\n const schema = shape[key];\n const optin = schema?._zod?.optin;\n const isOptionalIn = optin !== undefined;\n const isOptionalOut = schema?._zod?.optout === \"optional\";\n doc.write(`const ${id} = ${parseStr(k)};`);\n if (isOptionalIn && isOptionalOut) {\n // For optional-in/out schemas, ignore errors on absent keys — and, like the interpreted path, drop the value produced alongside them. The middle rung goes further: it permits absence without supplying anything in its place, so an absent key contributes nothing at all.\n const assign = optin === \"optional\" ? `${id}_present` : `${id}.value !== undefined || ${id}_present`;\n doc.write(`\n const ${id}_present = ${isPresent};\n if (!${id}.issues.length || ${id}_present) {\n if (${id}.issues.length) {${prefixStr(id, k)}\n }\n\n if (${assign}) {\n newResult[${k}] = ${id}.value;\n }\n }\n\n `);\n }\n else if (!isOptionalIn) {\n doc.write(`\n const ${id}_present = ${isPresent};\n if (${id}.issues.length) {${prefixStr(id, k)}\n }\n if (!${id}_present && !${id}.issues.length) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"nonoptional\",\n input: undefined,\n path: [${k}]\n });\n if (ctx && ctx.abortEarly) {\n payload.value = newResult;\n return payload;\n }\n }\n\n if (${id}_present) {\n newResult[${k}] = ${id}.value;\n }\n\n `);\n }\n else {\n doc.write(`\n if (${id}.issues.length) {${prefixStr(id, k)}\n }\n `);\n if (optin === \"defaulted\") {\n doc.write(`newResult[${k}] = ${id}.value;`);\n }\n else {\n doc.write(`\n if (${id}.value !== undefined || ${isPresent}) {\n newResult[${k}] = ${id}.value;\n }\n `);\n }\n }\n }\n doc.write(`payload.value = newResult;`);\n doc.write(`return payload;`);\n // closing `shape` in is what pays: turbofan specializes the parser against that one shape object, so every `shape[k]._zod.run` folds to a known callee. as a parameter it stays a generic load and measures 13% slower even with the forwarding frame gone\n return doc.compile();\n };\n let fastpass;\n const isObject = util.isObject;\n const jit = !core.globalConfig.jitless;\n const allowsEval = util.allowsEval;\n const fastEnabled = jit && allowsEval.value; // && !def.catchall;\n const catchall = def.catchall;\n let value;\n inst._zod.parse = (payload, ctx) => {\n value ?? (value = _normalized.value);\n const input = payload.value;\n if (!isObject(input)) {\n payload.issues.push({\n expected: \"object\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) {\n // always synchronous\n if (!fastpass)\n fastpass = generateFastpass(def.shape);\n payload = fastpass(payload, ctx);\n if (!catchall)\n return payload;\n return handleCatchall([], input, payload, ctx, value, inst, ctx?.abortEarly === true);\n }\n return superParse(payload, ctx);\n };\n});\nfunction handleUnionResults(results, final, inst, ctx) {\n for (const result of results) {\n if (result.issues.length === 0) {\n final.value = result.value;\n return final;\n }\n }\n const nonaborted = results.filter((r) => !util.aborted(r));\n if (nonaborted.length === 1) {\n final.value = nonaborted[0].value;\n return nonaborted[0];\n }\n final.issues.push({\n code: \"invalid_union\",\n input: final.value,\n inst,\n errors: results.map((result) => result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n });\n return final;\n}\nexport const $ZodUnion = /*@__PURE__*/ core.$constructor(\"$ZodUnion\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.options.some((o) => o._zod.optin === \"defaulted\")\n ? \"defaulted\"\n : zod.def.options.some((o) => o._zod.optin !== undefined)\n ? \"optional\"\n : undefined);\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.options.some((o) => o._zod.optout === \"optional\") ? \"optional\" : undefined);\n util.defineLazyInternal(inst, \"values\", (zod) => {\n if (zod.def.options.every((o) => o._zod.values)) {\n return new Set(zod.def.options.flatMap((option) => Array.from(option._zod.values)));\n }\n return undefined;\n });\n util.defineLazyInternal(inst, \"pattern\", (zod) => {\n if (zod.def.options.every((o) => o._zod.pattern)) {\n const patterns = zod.def.options.map((o) => o._zod.pattern);\n return new RegExp(`^(${patterns.map((p) => util.cleanRegex(p.source)).join(\"|\")})$`);\n }\n return undefined;\n });\n const first = def.options.length === 1 ? def.options[0]._zod.run : null;\n inst._zod.parse = (payload, ctx) => {\n if (first) {\n return first(payload, ctx);\n }\n let async = false;\n const results = [];\n for (const option of def.options) {\n const result = option._zod.run({\n value: payload.value,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n results.push(result);\n async = true;\n }\n else {\n if (result.issues.length === 0)\n return result;\n results.push(result);\n }\n }\n if (!async)\n return handleUnionResults(results, payload, inst, ctx);\n return Promise.all(results).then((results) => {\n return handleUnionResults(results, payload, inst, ctx);\n });\n };\n});\nfunction handleExclusiveUnionResults(results, final, inst, ctx) {\n const matches = [];\n for (let i = 0; i < results.length; i++) {\n if (results[i].issues.length === 0)\n matches.push(i);\n }\n if (matches.length === 1) {\n final.value = results[matches[0]].value;\n return final;\n }\n if (matches.length === 0) {\n // No matches - same as regular union\n final.issues.push({\n code: \"invalid_union\",\n input: final.value,\n inst,\n errors: results.map((result) => result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n });\n }\n else {\n // Multiple matches - exclusive union failure\n final.issues.push({\n code: \"invalid_union\",\n input: final.value,\n inst,\n errors: [],\n inclusive: false,\n matches,\n });\n }\n return final;\n}\nexport const $ZodXor = /*@__PURE__*/ core.$constructor(\"$ZodXor\", (inst, def) => {\n $ZodUnion.init(inst, def);\n def.inclusive = false;\n const first = def.options.length === 1 ? def.options[0]._zod.run : null;\n inst._zod.parse = (payload, ctx) => {\n if (first) {\n return first(payload, ctx);\n }\n let async = false;\n const results = [];\n for (const option of def.options) {\n const result = option._zod.run({\n value: payload.value,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n results.push(result);\n async = true;\n }\n else {\n results.push(result);\n }\n }\n if (!async)\n return handleExclusiveUnionResults(results, payload, inst, ctx);\n return Promise.all(results).then((results) => {\n return handleExclusiveUnionResults(results, payload, inst, ctx);\n });\n };\n});\n/** Returns the option whose discriminator claims `value`, or throws if ambiguous. */\nexport function getDiscriminatedOption(union, value) {\n const internals = union._zod;\n let map = internals.bag.optionsMap;\n if (!map) {\n map = discriminatorMap(internals.def);\n internals.bag.optionsMap = map;\n }\n const option = map.get(value);\n if (option === null)\n throw new Error(`Ambiguous discriminator value \"${String(value)}\"`);\n return option;\n}\nfunction discriminatorMap(def) {\n const map = new Map();\n for (const option of def.options) {\n const values = option._zod.propValues?.[def.discriminator];\n if (!values || values.size === 0)\n throw new Error(`Invalid discriminated union option at index \"${def.options.indexOf(option)}\"`);\n for (const value of values) {\n if (map.has(value)) {\n if (value !== undefined)\n throw new Error(`Duplicate discriminator value \"${String(value)}\"`);\n // keep the collision marked so a later member cannot reclaim it\n map.set(value, null);\n }\n else {\n map.set(value, option);\n }\n }\n }\n return map;\n}\nexport const $ZodDiscriminatedUnion = \n/*@__PURE__*/\ncore.$constructor(\"$ZodDiscriminatedUnion\", (inst, def) => {\n def.inclusive = false;\n $ZodUnion.init(inst, def);\n const _super = inst._zod.parse;\n util.defineLazyInternal(inst, \"propValues\", (zod) => {\n const propValues = {};\n let undefinedCount = 0;\n for (const option of zod.def.options) {\n const pv = option._zod.propValues;\n if (!pv || Object.keys(pv).length === 0)\n throw new Error(`Invalid discriminated union option at index \"${zod.def.options.indexOf(option)}\"`);\n if (pv[zod.def.discriminator]?.has(undefined))\n undefinedCount++;\n for (const [k, v] of Object.entries(pv)) {\n if (!Object.prototype.hasOwnProperty.call(propValues, k)) {\n util.assignProp(propValues, k, new Set());\n }\n for (const val of v) {\n propValues[k].add(val);\n }\n }\n }\n if (!zod.def.unionFallback && undefinedCount > 1)\n propValues[zod.def.discriminator]?.delete(undefined);\n return propValues;\n });\n // Checked now rather than in the lookup map below, so an option that lacks the discriminator fails at the `discriminatedUnion` call instead of on the first object parsed. Options whose shape cannot be enumerated without resolving it — pipes and lazies — are left to the map.\n def.options.forEach((option, i) => {\n const propShape = util.rawShape(option._zod.def);\n if (propShape && !Object.prototype.hasOwnProperty.call(propShape, def.discriminator)) {\n throw new Error(`Invalid discriminated union option at index \"${i}\"`);\n }\n });\n const disc = util.cached(() => discriminatorMap(def));\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!util.isObject(input)) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"object\",\n input,\n inst,\n });\n return payload;\n }\n const value = input?.[def.discriminator];\n const opt = disc.value.get(value);\n // forward metadata cannot choose an encoder for an absent tag\n if (opt && (value !== undefined || ctx.direction !== \"backward\")) {\n return opt._zod.run(payload, ctx);\n }\n // Fall back to union matching when the fast discriminator path fails:\n // - explicitly enabled via unionFallback, or\n // - during backward direction (encode), since codec-based discriminators have different values in forward vs backward directions\n if (def.unionFallback || ctx.direction === \"backward\") {\n return _super(payload, ctx);\n }\n // no matching discriminator\n payload.issues.push({\n code: \"invalid_union\",\n errors: [],\n note: \"No matching discriminator\",\n discriminator: def.discriminator,\n options: Array.from(disc.value.keys()).filter((value) => disc.value.get(value) !== null),\n input,\n path: [def.discriminator],\n inst,\n });\n return payload;\n };\n});\nexport const $ZodIntersection = /*@__PURE__*/ core.$constructor(\"$ZodIntersection\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n const left = def.left._zod.run({ value: input, issues: [] }, ctx);\n const right = def.right._zod.run({ value: input, issues: [] }, ctx);\n const async = left instanceof Promise || right instanceof Promise;\n if (async) {\n return Promise.all([left, right]).then(([left, right]) => {\n return handleIntersectionResults(payload, left, right);\n });\n }\n return handleIntersectionResults(payload, left, right);\n };\n});\nexport function mergeValues(a, b) {\n // const aType = parse.t(a);\n // const bType = parse.t(b);\n if (a === b) {\n return { valid: true, data: a };\n }\n if (a instanceof Date && b instanceof Date && +a === +b) {\n return { valid: true, data: a };\n }\n if (util.isPlainObject(a) && util.isPlainObject(b)) {\n const bKeys = Object.keys(b);\n const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);\n const newObj = { ...a, ...b };\n if (Object.prototype.hasOwnProperty.call(newObj, \"__proto__\"))\n delete newObj.__proto__;\n for (const key of sharedKeys) {\n if (key === \"__proto__\")\n continue;\n const sharedValue = mergeValues(a[key], b[key]);\n if (!sharedValue.valid) {\n return {\n valid: false,\n mergeErrorPath: [key, ...sharedValue.mergeErrorPath],\n };\n }\n newObj[key] = sharedValue.data;\n }\n return { valid: true, data: newObj };\n }\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) {\n return { valid: false, mergeErrorPath: [] };\n }\n const newArray = [];\n for (let index = 0; index < a.length; index++) {\n const itemA = a[index];\n const itemB = b[index];\n const sharedValue = mergeValues(itemA, itemB);\n if (!sharedValue.valid) {\n return {\n valid: false,\n mergeErrorPath: [index, ...sharedValue.mergeErrorPath],\n };\n }\n newArray.push(sharedValue.data);\n }\n return { valid: true, data: newArray };\n }\n return { valid: false, mergeErrorPath: [] };\n}\nfunction handleIntersectionResults(result, left, right) {\n // Track which side(s) reject each key. A key rejection is reported only when BOTH sides reject it, so a key owned by one branch survives the other's key schema. strictObject reports these as unrecognized_keys; a record with an open key schema reports one invalid_key per key.\n const unrecKeys = new Map();\n let unrecIssue;\n const keyIssues = new Map();\n const collect = (iss, side) => {\n let keys;\n if (iss.code === \"unrecognized_keys\" && !iss.path?.length) {\n unrecIssue ?? (unrecIssue = iss);\n keys = iss.keys;\n }\n else if (iss.code === \"invalid_key\" && iss.origin === \"record\" && iss.path?.length === 1) {\n const k = String(iss.path[0]);\n if (!keyIssues.has(k))\n keyIssues.set(k, iss);\n keys = [k];\n }\n else {\n return false;\n }\n for (const k of keys) {\n if (!unrecKeys.has(k))\n unrecKeys.set(k, {});\n unrecKeys.get(k)[side] = true;\n }\n return true;\n };\n for (const iss of left.issues) {\n if (!collect(iss, \"l\"))\n result.issues.push(iss);\n }\n for (const iss of right.issues) {\n if (!collect(iss, \"r\"))\n result.issues.push(iss);\n }\n // Report only keys rejected by BOTH sides\n const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k);\n if (bothKeys.length) {\n const aggregated = unrecIssue ? bothKeys.filter((k) => unrecIssue.keys.includes(k)) : [];\n if (aggregated.length)\n result.issues.push({ ...unrecIssue, keys: aggregated });\n for (const k of bothKeys) {\n if (!aggregated.includes(k) && keyIssues.has(k))\n result.issues.push(keyIssues.get(k));\n }\n }\n const merged = mergeValues(left.value, right.value);\n if (!merged.valid) {\n if (util.aborted(result))\n return result;\n throw new Error(`Unmergable intersection. Error path: ` + `${JSON.stringify(merged.mergeErrorPath)}`);\n }\n result.value = merged.data;\n return result;\n}\nexport const $ZodTuple = /*@__PURE__*/ core.$constructor(\"$ZodTuple\", (inst, def) => {\n $ZodType.init(inst, def);\n const items = def.items;\n const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!Array.isArray(input)) {\n payload.issues.push({\n input,\n inst,\n expected: \"tuple\",\n code: \"invalid_type\",\n });\n return payload;\n }\n payload.value = memo ? memo.alloc(inst, payload, [], ctx) : [];\n const proms = [];\n const optinStart = getTupleOptStart(items, \"optin\");\n const optoutStart = getTupleOptStart(items, \"optout\");\n if (!def.rest) {\n if (input.length < optinStart) {\n payload.issues.push({\n code: \"too_small\",\n minimum: optinStart,\n inclusive: true,\n input,\n inst,\n origin: \"array\",\n });\n return payload;\n }\n if (input.length > items.length) {\n payload.issues.push({\n code: \"too_big\",\n maximum: items.length,\n inclusive: true,\n input,\n inst,\n origin: \"array\",\n });\n }\n }\n // Run every item in parallel, collecting results into an indexed array. The post-processing in `handleTupleResults` walks them in order so it can decide whether an absent optional-output error can truncate the tail or must be reported to preserve required output.\n const itemResults = new Array(items.length);\n // only tracked when there is a rest loop to skip\n const abortEarly = def.rest ? ctx?.abortEarly : undefined;\n let itemAborted = false;\n for (let i = 0; i < items.length; i++) {\n const r = items[i]._zod.run({ value: input[i], issues: [] }, ctx);\n if (r instanceof Promise) {\n proms.push(r.then((rr) => {\n itemResults[i] = rr;\n }));\n }\n else {\n itemResults[i] = r;\n if (abortEarly && !itemAborted && r.issues.length)\n itemAborted = util.aborted(r);\n }\n }\n // sound because rest is non-empty exactly when every fixed index is present, the one case handleTupleResults cannot discard an item's issues\n if (def.rest && !itemAborted) {\n let i = items.length - 1;\n const rest = input.slice(items.length);\n let seen = payload.issues.length;\n for (const el of rest) {\n if (abortEarly && payload.issues.length !== seen) {\n if (util.aborted(payload, seen))\n break;\n seen = payload.issues.length;\n }\n i++;\n const result = def.rest._zod.run({ value: el, issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((r) => handleTupleResult(r, payload, i)));\n }\n else {\n handleTupleResult(result, payload, i);\n }\n }\n }\n if (proms.length) {\n return Promise.all(proms).then(() => handleTupleResults(itemResults, payload, items, input, optoutStart));\n }\n return handleTupleResults(itemResults, payload, items, input, optoutStart);\n };\n});\nfunction getTupleOptStart(items, key) {\n for (let i = items.length - 1; i >= 0; i--) {\n // optin is a three-rung ladder so any rung above `undefined` permits an absent slot; optout stays two-valued.\n const omittable = key === \"optin\" ? items[i]._zod.optin !== undefined : items[i]._zod.optout === \"optional\";\n if (!omittable)\n return i + 1;\n }\n return 0;\n}\nfunction handleTupleResult(result, final, index) {\n if (result.issues.length) {\n final.issues.push(...util.prefixIssues(index, result.issues));\n }\n final.value[index] = result.value;\n}\nfunction handleTupleResults(itemResults, final, items, input, optoutStart) {\n // Walk results in order. Mirror $ZodObject's swallow-on-absent-optional rule, but only after `optoutStart`: the first index where the output tuple tail can be absent.\n for (let i = 0; i < items.length; i++) {\n const r = itemResults[i];\n const isPresent = i < input.length;\n // The array analog of `handlePropertyResult`'s absent-key early return: the middle rung permits absence without supplying anything in its place, so the tail truncates here instead of materializing whatever the item made of `undefined`.\n if (!isPresent && i >= optoutStart && items[i]._zod.optin === \"optional\") {\n final.value.length = i;\n break;\n }\n if (r.issues.length) {\n if (!isPresent && i >= optoutStart) {\n final.value.length = i;\n break;\n }\n final.issues.push(...util.prefixIssues(i, r.issues));\n }\n final.value[i] = r.value;\n }\n // Drop trailing slots that produced `undefined` for absent input\n // (the array analog of an absent optional key on an object). The\n // `i >= input.length` floor is critical: an explicit `undefined`\n // *inside* the input must be preserved even when the schema is\n // optional-out (e.g. `z.string().or(z.undefined())` accepting an\n // explicit undefined value).\n for (let i = final.value.length - 1; i >= input.length; i--) {\n if (items[i]._zod.optout === \"optional\" && final.value[i] === undefined) {\n final.value.length = i;\n }\n else {\n break;\n }\n }\n return final;\n}\nexport const $ZodRecord = /*@__PURE__*/ core.$constructor(\"$ZodRecord\", (inst, def) => {\n $ZodType.init(inst, def);\n const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!util.isPlainObject(input)) {\n payload.issues.push({\n expected: \"record\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n // no guard in either loop below: a record's invalid_key aborts but an enclosing intersection can reconcile it, so a stopped loop hides keys the sibling does not own and the intersection then rejects nothing\n const proms = [];\n const values = def.keyType._zod.values;\n if (values && !def.partial) {\n payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {};\n const recordKeys = new Set();\n for (const key of values) {\n if (typeof key === \"string\" || typeof key === \"number\" || typeof key === \"symbol\") {\n recordKeys.add(typeof key === \"number\" ? key.toString() : key);\n // A declared __proto__ is stripped but is not an unrecognized key.\n if (key === \"__proto__\")\n continue;\n const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n if (keyResult instanceof Promise) {\n throw new Error(\"Async schemas not supported in object keys currently\");\n }\n if (keyResult.issues.length) {\n payload.issues.push({\n code: \"invalid_key\",\n origin: \"record\",\n issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n input: key,\n path: [key],\n inst,\n });\n continue;\n }\n const outKey = keyResult.value;\n if (outKey === \"__proto__\")\n continue;\n const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[outKey] = result.value;\n }));\n }\n else {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[outKey] = result.value;\n }\n }\n }\n let unrecognized;\n for (const key in input) {\n if (!recordKeys.has(key)) {\n if (def.mode === \"loose\") {\n // skip __proto__ so it can't replace the result prototype via the assignment setter on the plain {} we build into\n if (key === \"__proto__\")\n continue;\n payload.value[key] = input[key];\n }\n else {\n unrecognized = unrecognized ?? [];\n unrecognized.push(key);\n }\n }\n }\n if (unrecognized && unrecognized.length > 0) {\n payload.issues.push({\n code: \"unrecognized_keys\",\n input,\n inst,\n keys: unrecognized,\n continue: true,\n });\n }\n }\n else {\n payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {};\n // An enumerable key schema declares which keys the record owns, so a key outside the set is unrecognized. A non-enumerable one (regex, refine) is a constraint every key must satisfy, so a failing key is invalid. Only the former is reconcilable against the other side of an intersection.\n let unrecognized;\n // Reflect.ownKeys for Symbol-key support; filter non-enumerable to match z.object()\n for (const key of Reflect.ownKeys(input)) {\n if (key === \"__proto__\")\n continue;\n if (!Object.prototype.propertyIsEnumerable.call(input, key))\n continue;\n let keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n if (keyResult instanceof Promise) {\n throw new Error(\"Async schemas not supported in object keys currently\");\n }\n // Numeric string fallback: if key is a numeric string and failed, retry with Number(key). This handles z.number(), z.literal([1, 2, 3]), and unions containing numeric literals\n const checkNumericKey = typeof key === \"string\" && regexes.number.test(key) && keyResult.issues.length;\n if (checkNumericKey) {\n const retryResult = def.keyType._zod.run({ value: Number(key), issues: [] }, ctx);\n if (retryResult instanceof Promise) {\n throw new Error(\"Async schemas not supported in object keys currently\");\n }\n if (retryResult.issues.length === 0) {\n keyResult = retryResult;\n }\n }\n if (keyResult.issues.length) {\n if (def.mode === \"loose\") {\n // Pass through unchanged\n payload.value[key] = input[key];\n }\n else if (values) {\n unrecognized = unrecognized ?? [];\n unrecognized.push(key);\n }\n else {\n // Default \"strict\" behavior: error on invalid key\n payload.issues.push({\n code: \"invalid_key\",\n origin: \"record\",\n issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n input: key,\n path: [key],\n inst,\n });\n }\n continue;\n }\n // the guard above tests the raw input key, but the key schema can normalize an ordinary key into __proto__; re-check the key we actually write under\n const outKey = keyResult.value;\n if (outKey === \"__proto__\")\n continue;\n const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[outKey] = result.value;\n }));\n }\n else {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[outKey] = result.value;\n }\n }\n if (unrecognized && unrecognized.length > 0) {\n payload.issues.push({\n code: \"unrecognized_keys\",\n input,\n inst,\n keys: unrecognized,\n continue: true,\n });\n }\n }\n if (proms.length) {\n return Promise.all(proms).then(() => payload);\n }\n return payload;\n };\n});\nexport const $ZodMap = /*@__PURE__*/ core.$constructor(\"$ZodMap\", (inst, def) => {\n $ZodType.init(inst, def);\n const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!(input instanceof Map)) {\n payload.issues.push({\n expected: \"map\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n const proms = [];\n payload.value = memo ? memo.alloc(inst, payload, new Map(), ctx) : new Map();\n const abortEarly = ctx?.abortEarly;\n let seen = payload.issues.length;\n for (const [key, value] of input) {\n if (abortEarly && payload.issues.length !== seen) {\n if (util.aborted(payload, seen))\n break;\n seen = payload.issues.length;\n }\n const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n const valueResult = def.valueType._zod.run({ value: value, issues: [] }, ctx);\n if (keyResult instanceof Promise || valueResult instanceof Promise) {\n proms.push(Promise.all([keyResult, valueResult]).then(([keyResult, valueResult]) => {\n handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx);\n }));\n }\n else {\n handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx);\n }\n }\n if (proms.length)\n return Promise.all(proms).then(() => payload);\n return payload;\n };\n});\nfunction handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) {\n if (keyResult.issues.length) {\n if (util.propertyKeyTypes.has(typeof key)) {\n final.issues.push(...util.prefixIssues(key, keyResult.issues));\n }\n else {\n final.issues.push({\n code: \"invalid_key\",\n origin: \"map\",\n input,\n inst,\n issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n });\n }\n }\n if (valueResult.issues.length) {\n if (util.propertyKeyTypes.has(typeof key)) {\n final.issues.push(...util.prefixIssues(key, valueResult.issues));\n }\n else {\n final.issues.push({\n origin: \"map\",\n code: \"invalid_element\",\n input,\n inst,\n key: key,\n issues: valueResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n });\n }\n }\n final.value.set(keyResult.value, valueResult.value);\n}\nexport const $ZodSet = /*@__PURE__*/ core.$constructor(\"$ZodSet\", (inst, def) => {\n $ZodType.init(inst, def);\n const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!(input instanceof Set)) {\n payload.issues.push({\n input,\n inst,\n expected: \"set\",\n code: \"invalid_type\",\n });\n return payload;\n }\n const proms = [];\n payload.value = memo ? memo.alloc(inst, payload, new Set(), ctx) : new Set();\n const abortEarly = ctx?.abortEarly;\n let seen = payload.issues.length;\n for (const item of input) {\n if (abortEarly && payload.issues.length !== seen) {\n if (util.aborted(payload, seen))\n break;\n seen = payload.issues.length;\n }\n const result = def.valueType._zod.run({ value: item, issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => handleSetResult(result, payload)));\n }\n else\n handleSetResult(result, payload);\n }\n if (proms.length)\n return Promise.all(proms).then(() => payload);\n return payload;\n };\n});\nfunction handleSetResult(result, final) {\n if (result.issues.length) {\n final.issues.push(...result.issues);\n }\n final.value.add(result.value);\n}\nexport const $ZodEnum = /*@__PURE__*/ core.$constructor(\"$ZodEnum\", (inst, def) => {\n $ZodType.init(inst, def);\n const values = util.getEnumValues(def.entries);\n const valuesSet = new Set(values);\n inst._zod.values = valuesSet;\n util.defineLazyInternal(inst, \"pattern\", (zod) => {\n const patternValues = util.getEnumValues(zod.def.entries).filter((k) => util.propertyKeyTypes.has(typeof k));\n // unmatchable fallback, RE2-safe: an empty alternation would compile to /^()$/, which matches \"\"\n return new RegExp(patternValues.length ? `^(${patternValues.map((o) => util.escapeRegex(o.toString())).join(\"|\")})$` : \"^[^\\\\s\\\\S]$\");\n });\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (valuesSet.has(input)) {\n return payload;\n }\n payload.issues.push({\n code: \"invalid_value\",\n values,\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodLiteral = /*@__PURE__*/ core.$constructor(\"$ZodLiteral\", (inst, def) => {\n $ZodType.init(inst, def);\n const values = new Set(def.values);\n inst._zod.values = values;\n util.defineLazyInternal(inst, \"pattern\", (zod) => {\n const vals = zod.def.values;\n // unmatchable fallback, RE2-safe: an empty alternation would compile to /^()$/, which matches \"\"\n return new RegExp(vals.length\n ? `^(${vals\n .map((o) => typeof o === \"string\" ? util.escapeRegex(o) : o ? util.escapeRegex(o.toString()) : String(o))\n .join(\"|\")})$`\n : \"^[^\\\\s\\\\S]$\");\n });\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (values.has(input)) {\n return payload;\n }\n payload.issues.push({\n code: \"invalid_value\",\n values: def.values,\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodFile = /*@__PURE__*/ core.$constructor(\"$ZodFile\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n // @ts-ignore\n if (input instanceof File)\n return payload;\n payload.issues.push({\n expected: \"file\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodTransform = /*@__PURE__*/ core.$constructor(\"$ZodTransform\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.optin = \"optional\";\n core.globalConfig.memoizer?.guard(inst);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n throw new core.$ZodEncodeError(inst.constructor.name);\n }\n const _out = def.transform(payload.value, payload);\n if (ctx.async) {\n const output = _out instanceof Promise ? _out : Promise.resolve(_out);\n return output.then((output) => {\n payload.value = output;\n return payload;\n });\n }\n if (_out instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n payload.value = _out;\n return payload;\n };\n});\nfunction handleOptionalResult(payload, result) {\n // A substituting schema that still failed has no usable answer; yield undefined. Its issues are simply dropped: it ran on a payload of its own, so there is no shared array to truncate and nothing of the caller's to lose with it.\n payload.value = result.issues.length ? undefined : result.value;\n return payload;\n}\nexport const $ZodOptional = /*@__PURE__*/ core.$constructor(\"$ZodOptional\", (inst, def) => {\n $ZodType.init(inst, def);\n // .optional() propagates absence rather than substituting for it, so a defaulted inner keeps its rung.\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.innerType._zod.optin === \"defaulted\" ? \"defaulted\" : \"optional\");\n inst._zod.optout = \"optional\";\n util.defineLazyInternal(inst, \"values\", (zod) => {\n const values = zod.def.innerType._zod.values;\n return values ? new Set([...values, undefined]) : undefined;\n });\n util.defineLazyInternal(inst, \"pattern\", (zod) => {\n const pattern = zod.def.innerType._zod.pattern;\n return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)})?$`) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n if (payload.value === undefined) {\n // Only the top rung substitutes a value for absence; everything else leaves it intact, which is what .optional() means.\n if (def.innerType._zod.optin !== \"defaulted\")\n return payload;\n // Its own payload, for the same reason $ZodCatch gets one: a pipe forwards an unrecognized key through the caller's issues array, and this must not read that as the substituting schema failing and drop it.\n const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx);\n if (result instanceof Promise)\n return result.then((result) => handleOptionalResult(payload, result));\n return handleOptionalResult(payload, result);\n }\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodExactOptional = /*@__PURE__*/ core.$constructor(\"$ZodExactOptional\", (inst, def) => {\n // Call parent init - inherits optin/optout = \"optional\"\n $ZodOptional.init(inst, def);\n // Override values/pattern to NOT add undefined\n util.defineLazyInternal(inst, \"values\", (zod) => zod.def.innerType._zod.values);\n util.defineLazyInternal(inst, \"pattern\", (zod) => zod.def.innerType._zod.pattern);\n // Override parse to just delegate (no undefined handling)\n inst._zod.parse = (payload, ctx) => {\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodNullable = /*@__PURE__*/ core.$constructor(\"$ZodNullable\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.innerType._zod.optin);\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.innerType._zod.optout);\n util.defineLazyInternal(inst, \"pattern\", (zod) => {\n const pattern = zod.def.innerType._zod.pattern;\n return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)}|null)$`) : undefined;\n });\n util.defineLazyInternal(inst, \"values\", (zod) => {\n return zod.def.innerType._zod.values ? new Set([...zod.def.innerType._zod.values, null]) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n // Forward direction (decode): allow null to pass through\n if (payload.value === null)\n return payload;\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodDefault = /*@__PURE__*/ core.$constructor(\"$ZodDefault\", (inst, def) => {\n $ZodType.init(inst, def);\n // inst._zod.qin = \"true\";\n inst._zod.optin = \"defaulted\";\n util.defineLazyInternal(inst, \"values\", (zod) => zod.def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n // Forward direction (decode): apply defaults for undefined input\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n /**\n * $ZodDefault returns the default value immediately in forward direction.\n * It doesn't pass the default value into the validator (\"prefault\"). There's no reason to pass the default value through validation. The validity of the default is enforced by TypeScript statically. Otherwise, it's the responsibility of the user to ensure the default is valid. In the case of pipes with divergent in/out types, you can specify the default on the `in` schema of your ZodPipe to set a \"prefault\" for the pipe. */\n return payload;\n }\n // Forward direction: continue with default handling\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => handleDefaultResult(result, def));\n }\n return handleDefaultResult(result, def);\n };\n});\nfunction handleDefaultResult(payload, def) {\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n }\n return payload;\n}\nexport const $ZodPrefault = /*@__PURE__*/ core.$constructor(\"$ZodPrefault\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.optin = \"defaulted\";\n util.defineLazyInternal(inst, \"values\", (zod) => zod.def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n // Forward direction (decode): apply prefault for undefined input\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n }\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodNonOptional = /*@__PURE__*/ core.$constructor(\"$ZodNonOptional\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazyInternal(inst, \"values\", (zod) => {\n const v = zod.def.innerType._zod.values;\n return v ? new Set([...v].filter((x) => x !== undefined)) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => handleNonOptionalResult(result, inst));\n }\n return handleNonOptionalResult(result, inst);\n };\n});\nfunction handleNonOptionalResult(payload, inst) {\n if (!payload.issues.length && payload.value === undefined) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"nonoptional\",\n input: payload.value,\n inst,\n });\n }\n return payload;\n}\nexport const $ZodSuccess = /*@__PURE__*/ core.$constructor(\"$ZodSuccess\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n throw new core.$ZodEncodeError(\"ZodSuccess\");\n }\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => {\n payload.value = result.issues.length === 0;\n return payload;\n });\n }\n payload.value = result.issues.length === 0;\n return payload;\n };\n});\nfunction handleCatchResult(payload, result, def, ctx) {\n if (!result.issues.length) {\n payload.value = result.value;\n // The value carries up, so the flag describing it has to carry with it: a back-edge into a node still being parsed must not be frozen by an enclosing readonly, and its checks belong to the node itself. Guarded so the ordinary case adds no own property.\n if (result.memo)\n payload.memo = true;\n return payload;\n }\n // Spread the inner's own payload, not ours: `value` has to stay the input the catch was handed, and the inner ran on a payload of its own so its issues are already private to this call.\n payload.value = def.catchValue({\n ...result,\n value: payload.value,\n error: {\n issues: result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n },\n input: payload.value,\n });\n return payload;\n}\nexport const $ZodCatch = /*@__PURE__*/ core.$constructor(\"$ZodCatch\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.innerType._zod.optin === \"defaulted\" ? \"defaulted\" : \"optional\");\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.innerType._zod.optout);\n util.defineLazyInternal(inst, \"values\", (zod) => zod.def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n // Forward direction (decode): apply catch logic\n const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx);\n if (result instanceof Promise) {\n return result.then((result) => handleCatchResult(payload, result, def, ctx));\n }\n return handleCatchResult(payload, result, def, ctx);\n };\n});\nexport const $ZodNaN = /*@__PURE__*/ core.$constructor(\"$ZodNaN\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"number\" || !Number.isNaN(payload.value)) {\n payload.issues.push({\n input: payload.value,\n inst,\n expected: \"nan\",\n code: \"invalid_type\",\n });\n return payload;\n }\n return payload;\n };\n});\nexport const $ZodPipe = /*@__PURE__*/ core.$constructor(\"$ZodPipe\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazyInternal(inst, \"values\", (zod) => zod.def.in._zod.values);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.in._zod.optin);\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.out._zod.optout);\n util.defineLazyInternal(inst, \"propValues\", (zod) => zod.def.in._zod.propValues);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n const right = def.out._zod.run(payload, ctx);\n if (right instanceof Promise) {\n return right.then((right) => handlePipeResult(right, def.in, ctx));\n }\n return handlePipeResult(right, def.in, ctx);\n }\n const left = def.in._zod.run(payload, ctx);\n if (left instanceof Promise) {\n return left.then((left) => handlePipeResult(left, def.out, ctx));\n }\n return handlePipeResult(left, def.out, ctx);\n };\n});\nfunction handlePipeResult(left, next, ctx) {\n // Any issue stops the pipe, so a failing refinement never feeds its transform. An unrecognized key is the exception: it describes the input's extra properties, not the value being piped, and an enclosing intersection may yet reconcile it.\n if (left.issues.some((iss) => iss.code !== \"unrecognized_keys\")) {\n // prevent further checks\n left.aborted = true;\n return left;\n }\n return next._zod.run({ value: left.value, issues: left.issues }, ctx);\n}\nexport const $ZodCodec = /*@__PURE__*/ core.$constructor(\"$ZodCodec\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazyInternal(inst, \"values\", (zod) => zod.def.in._zod.values);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.in._zod.optin);\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.out._zod.optout);\n util.defineLazyInternal(inst, \"propValues\", (zod) => zod.def.in._zod.propValues);\n inst._zod.parse = (payload, ctx) => {\n const direction = ctx.direction || \"forward\";\n if (direction === \"forward\") {\n const left = def.in._zod.run(payload, ctx);\n if (left instanceof Promise) {\n return left.then((left) => handleCodecAResult(left, def, ctx));\n }\n return handleCodecAResult(left, def, ctx);\n }\n else {\n const right = def.out._zod.run(payload, ctx);\n if (right instanceof Promise) {\n return right.then((right) => handleCodecAResult(right, def, ctx));\n }\n return handleCodecAResult(right, def, ctx);\n }\n };\n});\nfunction handleCodecAResult(result, def, ctx) {\n if (result.issues.length) {\n // prevent further checks\n result.aborted = true;\n return result;\n }\n const direction = ctx.direction || \"forward\";\n if (direction === \"forward\") {\n const transformed = def.transform(result.value, result);\n if (transformed instanceof Promise) {\n return transformed.then((value) => handleCodecTxResult(result, value, def.out, ctx));\n }\n return handleCodecTxResult(result, transformed, def.out, ctx);\n }\n else {\n const transformed = def.reverseTransform(result.value, result);\n if (transformed instanceof Promise) {\n return transformed.then((value) => handleCodecTxResult(result, value, def.in, ctx));\n }\n return handleCodecTxResult(result, transformed, def.in, ctx);\n }\n}\nfunction handleCodecTxResult(left, value, nextSchema, ctx) {\n // Check if transform added any issues\n if (left.issues.length) {\n left.aborted = true;\n return left;\n }\n return nextSchema._zod.run({ value, issues: left.issues }, ctx);\n}\nexport const $ZodPreprocess = /*@__PURE__*/ core.$constructor(\"$ZodPreprocess\", (inst, def) => {\n $ZodPipe.init(inst, def);\n});\nexport const $ZodReadonly = /*@__PURE__*/ core.$constructor(\"$ZodReadonly\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazyInternal(inst, \"propValues\", (zod) => zod.def.innerType._zod.propValues);\n util.defineLazyInternal(inst, \"values\", (zod) => zod.def.innerType._zod.values);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.innerType?._zod?.optin);\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.innerType?._zod?.optout);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then(handleReadonlyResult);\n }\n return handleReadonlyResult(result);\n };\n});\nfunction handleReadonlyResult(payload) {\n // A repeat visit hands back a node that is still being built; freezing it here would make the rest of its keys fail to assign.\n if (!payload.memo)\n payload.value = Object.freeze(payload.value);\n return payload;\n}\n// a leaf's pattern source with its own checks folded in: the last pattern-carrying check wins, else length bounds narrow the catch-all, else an integer format narrows the number form. the fold lives here instead of on `_zod.pattern` so a bundle without template literals never pays for it\nfunction leafPattern(schema) {\n const def = schema._zod.def;\n let pattern = def.pattern;\n let isInt = !!def.format?.includes(\"int\");\n let minimum;\n let maximum;\n for (const ch of def.checks ?? []) {\n const d = ch._zod.def;\n if (d.pattern)\n pattern = d.pattern;\n isInt || (isInt = !!d.format?.includes(\"int\"));\n const lo = d.minimum ?? d.length;\n const hi = d.maximum ?? d.length;\n if (lo !== undefined && (minimum === undefined || lo > minimum))\n minimum = lo;\n if (hi !== undefined && (maximum === undefined || hi < maximum))\n maximum = hi;\n }\n if (pattern)\n return pattern.source;\n // an empty range matches nothing at runtime, and `{8,5}` is not a legal quantifier\n if (minimum !== undefined && maximum !== undefined && minimum > maximum)\n return \"(?!)\";\n if (minimum !== undefined || maximum !== undefined)\n return regexes.string({ minimum, maximum }).source;\n const own = schema._zod.pattern;\n return (isInt && own === regexes.number ? regexes.integer : own)?.source;\n}\n// a part's pattern source. a wrapper's pattern embeds its inner pattern's source verbatim, so the folded form is substituted in place without knowing the wrapper's own composition; a union's options are joined the way the union builds its own pattern\nfunction partPattern(schema) {\n const def = schema._zod.def;\n const own = schema._zod.pattern?.source;\n // lazy resolves its inner on the internals, not the def\n const inner = def.innerType ?? schema._zod.innerType;\n if (inner) {\n const before = inner._zod.pattern?.source;\n const after = partPattern(inner);\n if (own && before && after && after !== before) {\n return own.replace(util.cleanRegex(before), () => util.cleanRegex(after));\n }\n return own;\n }\n if (def.options) {\n const sources = def.options.map(partPattern);\n if (sources.every(Boolean))\n return `^(${sources.map((s) => util.cleanRegex(s)).join(\"|\")})$`;\n }\n return leafPattern(schema);\n}\nexport const $ZodTemplateLiteral = /*@__PURE__*/ core.$constructor(\"$ZodTemplateLiteral\", (inst, def) => {\n $ZodType.init(inst, def);\n const regexParts = [];\n for (const part of def.parts) {\n if (typeof part === \"object\" && part !== null) {\n // is Zod schema\n const source = partPattern(part);\n if (!source) {\n throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`);\n }\n regexParts.push(util.cleanRegex(source));\n }\n else if (part === null || util.primitiveTypes.has(typeof part)) {\n regexParts.push(util.escapeRegex(`${part}`));\n }\n else {\n throw new Error(`Invalid template literal part: ${part}`);\n }\n }\n inst._zod.pattern = new RegExp(`^${regexParts.join(\"\")}$`);\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"string\") {\n payload.issues.push({\n input: payload.value,\n inst,\n expected: \"string\",\n code: \"invalid_type\",\n });\n return payload;\n }\n inst._zod.pattern.lastIndex = 0;\n if (!inst._zod.pattern.test(payload.value)) {\n payload.issues.push({\n input: payload.value,\n inst,\n code: \"invalid_format\",\n format: def.format ?? \"template_literal\",\n pattern: inst._zod.pattern.source,\n });\n return payload;\n }\n return payload;\n };\n});\nexport const $ZodFunction = /*@__PURE__*/ core.$constructor(\"$ZodFunction\", (inst, def) => {\n $ZodType.init(inst, def);\n // Defined, not assigned: the classic prototype exposes `_def` as a getter with no setter.\n Object.defineProperty(inst, \"_def\", { value: def });\n inst._zod.def = def;\n inst.implement = (func) => {\n if (typeof func !== \"function\") {\n throw new Error(\"implement() must be called with a function\");\n }\n // Defined inline so the closure stays anonymous: binding it to a `const` first names it, which costs 256 bytes per implemented function.\n return Object.defineProperty(function (...args) {\n const parsedArgs = inst._def.input ? parse(inst._def.input, args) : args;\n const result = Reflect.apply(func, this, parsedArgs);\n if (inst._def.output) {\n return parse(inst._def.output, result);\n }\n return result;\n }, \"_zod\", { value: inst._zod, enumerable: false });\n };\n inst.implementAsync = (func) => {\n if (typeof func !== \"function\") {\n throw new Error(\"implementAsync() must be called with a function\");\n }\n return Object.defineProperty(async function (...args) {\n const parsedArgs = inst._def.input ? await parseAsync(inst._def.input, args) : args;\n const result = await Reflect.apply(func, this, parsedArgs);\n if (inst._def.output) {\n return await parseAsync(inst._def.output, result);\n }\n return result;\n }, \"_zod\", { value: inst._zod, enumerable: false });\n };\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"function\") {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"function\",\n input: payload.value,\n inst,\n });\n return payload;\n }\n // Check if output is a promise type to determine if we should use async implementation\n const hasPromiseOutput = inst._def.output && inst._def.output._zod.def.type === \"promise\";\n if (hasPromiseOutput) {\n payload.value = inst.implementAsync(payload.value);\n }\n else {\n payload.value = inst.implement(payload.value);\n }\n return payload;\n };\n inst.input = (...args) => {\n const F = inst.constructor;\n if (Array.isArray(args[0])) {\n return new F({\n type: \"function\",\n input: new $ZodTuple({\n type: \"tuple\",\n items: args[0],\n rest: args[1],\n }),\n output: inst._def.output,\n });\n }\n return new F({\n type: \"function\",\n input: args[0],\n output: inst._def.output,\n });\n };\n inst.output = (output) => {\n const F = inst.constructor;\n return new F({\n type: \"function\",\n input: inst._def.input,\n output,\n });\n };\n return inst;\n});\nexport const $ZodPromise = /*@__PURE__*/ core.$constructor(\"$ZodPromise\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n return Promise.resolve(payload.value).then((inner) => def.innerType._zod.run({ value: inner, issues: [] }, ctx));\n };\n});\nexport const $ZodLazy = /*@__PURE__*/ core.$constructor(\"$ZodLazy\", (inst, def) => {\n $ZodType.init(inst, def);\n // Cache the resolved inner type on the shared `def` so all clones of this lazy (e.g. via `.describe()`/`.meta()`) share the same inner instance, preserving identity for cycle detection on recursive schemas.\n util.defineLazy(inst._zod, \"innerType\", () => {\n const d = def;\n if (!d._cachedInner)\n d._cachedInner = def.getter();\n return d._cachedInner;\n });\n util.defineLazyInternal(inst, \"pattern\", (zod) => zod.innerType?._zod?.pattern);\n util.defineLazyInternal(inst, \"propValues\", (zod) => zod.innerType?._zod?.propValues);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.innerType?._zod?.optin ?? undefined);\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.innerType?._zod?.optout ?? undefined);\n inst._zod.parse = (payload, ctx) => {\n const inner = inst._zod.innerType;\n return inner._zod.run(payload, ctx);\n };\n});\nexport const $ZodCustom = /*@__PURE__*/ core.$constructor(\"$ZodCustom\", (inst, def) => {\n checks.$ZodCheck.init(inst, def);\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _) => {\n return payload;\n };\n inst._zod.check = (payload) => {\n const input = payload.value;\n const r = def.fn(input);\n if (r instanceof Promise) {\n return r.then((r) => handleRefineResult(r, payload, input, inst));\n }\n handleRefineResult(r, payload, input, inst);\n return;\n };\n});\nfunction handleRefineResult(result, payload, input, inst) {\n if (!result) {\n const _iss = {\n code: \"custom\",\n input,\n inst, // incorporates params.error into issue reporting\n path: [...(inst._zod.def.path ?? [])], // incorporates params.error into issue reporting\n continue: !inst._zod.def.abort,\n // params: inst._zod.def.params,\n };\n if (inst._zod.def.params)\n _iss.params = inst._zod.def.params;\n payload.issues.push(util.issue(_iss));\n }\n}\n","import * as checks from \"./checks.js\";\nimport * as registries from \"./registries.js\";\nimport * as schemas from \"./schemas.js\";\nimport * as util from \"./util.js\";\nfunction snapshotChecks(def) {\n if (def.checks)\n def.checks = [...def.checks];\n return def;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _string(Class, params) {\n return new Class(snapshotChecks({ type: \"string\", ...util.normalizeParams(params) }));\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedString(Class, params) {\n return new Class(snapshotChecks({ type: \"string\", coerce: true, ...util.normalizeParams(params) }));\n}\n// @__NO_SIDE_EFFECTS__\nexport function _email(Class, params) {\n return new Class({\n type: \"string\",\n format: \"email\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _guid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"guid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v4\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v6\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv7(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v7\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _url(Class, params) {\n return new Class({\n type: \"string\",\n format: \"url\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _emoji(Class, params) {\n return new Class({\n type: \"string\",\n format: \"emoji\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nanoid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"nanoid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link _cuid2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\n// @__NO_SIDE_EFFECTS__\nexport function _cuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cuid2(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cuid2\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ulid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ulid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _xid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"xid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ksuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ksuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ipv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ipv4\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ipv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ipv6\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _mac(Class, params) {\n return new Class({\n type: \"string\",\n format: \"mac\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cidrv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cidrv4\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cidrv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cidrv6\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _base64(Class, params) {\n return new Class({\n type: \"string\",\n format: \"base64\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _base64url(Class, params) {\n return new Class({\n type: \"string\",\n format: \"base64url\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _e164(Class, params) {\n return new Class({\n type: \"string\",\n format: \"e164\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _creditCard(Class, params) {\n return new Class({\n type: \"string\",\n format: \"credit_card\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _iban(Class, params) {\n return new Class({\n type: \"string\",\n format: \"iban\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _jwt(Class, params) {\n return new Class({\n type: \"string\",\n format: \"jwt\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\nexport const TimePrecision = {\n Any: null,\n Minute: -1,\n Second: 0,\n Millisecond: 3,\n Microsecond: 6,\n};\n// @__NO_SIDE_EFFECTS__\nexport function _isoDateTime(Class, params) {\n return new Class({\n type: \"string\",\n format: \"datetime\",\n check: \"string_format\",\n offset: false,\n local: false,\n precision: null,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoDate(Class, params) {\n return new Class({\n type: \"string\",\n format: \"date\",\n check: \"string_format\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoTime(Class, params) {\n return new Class({\n type: \"string\",\n format: \"time\",\n check: \"string_format\",\n precision: null,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoDuration(Class, params) {\n return new Class({\n type: \"string\",\n format: \"duration\",\n check: \"string_format\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _number(Class, params) {\n return new Class(snapshotChecks({ type: \"number\", checks: [], ...util.normalizeParams(params) }));\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedNumber(Class, params) {\n return new Class(snapshotChecks({ type: \"number\", coerce: true, checks: [], ...util.normalizeParams(params) }));\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"safeint\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _float32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"float32\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _float64(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"float64\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"int32\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uint32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"uint32\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _boolean(Class, params) {\n return new Class({\n type: \"boolean\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedBoolean(Class, params) {\n return new Class({\n type: \"boolean\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _bigint(Class, params) {\n return new Class({\n type: \"bigint\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedBigint(Class, params) {\n return new Class({\n type: \"bigint\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int64(Class, params) {\n return new Class({\n type: \"bigint\",\n check: \"bigint_format\",\n abort: false,\n format: \"int64\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uint64(Class, params) {\n return new Class({\n type: \"bigint\",\n check: \"bigint_format\",\n abort: false,\n format: \"uint64\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _symbol(Class, params) {\n return new Class({\n type: \"symbol\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _undefined(Class, params) {\n return new Class({\n type: \"undefined\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _null(Class, params) {\n return new Class({\n type: \"null\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _any(Class) {\n return new Class({\n type: \"any\",\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _unknown(Class) {\n return new Class({\n type: \"unknown\",\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _never(Class, params) {\n return new Class({\n type: \"never\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _void(Class, params) {\n return new Class({\n type: \"void\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _date(Class, params) {\n return new Class({\n type: \"date\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedDate(Class, params) {\n return new Class({\n type: \"date\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nan(Class, params) {\n return new Class({\n type: \"nan\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lt(value, params) {\n return new checks.$ZodCheckLessThan({\n check: \"less_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: false,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lte(value, params) {\n return new checks.$ZodCheckLessThan({\n check: \"less_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: true,\n });\n}\nexport { \n/** @deprecated Use `z.lte()` instead. */\n_lte as _max, };\n// @__NO_SIDE_EFFECTS__\nexport function _gt(value, params) {\n return new checks.$ZodCheckGreaterThan({\n check: \"greater_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: false,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _gte(value, params) {\n return new checks.$ZodCheckGreaterThan({\n check: \"greater_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: true,\n });\n}\nexport { \n/** @deprecated Use `z.gte()` instead. */\n_gte as _min, };\n// @__NO_SIDE_EFFECTS__\nexport function _positive(params) {\n return _gt(0, params);\n}\n// negative\n// @__NO_SIDE_EFFECTS__\nexport function _negative(params) {\n return _lt(0, params);\n}\n// nonpositive\n// @__NO_SIDE_EFFECTS__\nexport function _nonpositive(params) {\n return _lte(0, params);\n}\n// nonnegative\n// @__NO_SIDE_EFFECTS__\nexport function _nonnegative(params) {\n return _gte(0, params);\n}\n// @__NO_SIDE_EFFECTS__\nexport function _multipleOf(value, params) {\n return new checks.$ZodCheckMultipleOf({\n check: \"multiple_of\",\n ...util.normalizeParams(params),\n value,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _maxSize(maximum, params) {\n return new checks.$ZodCheckMaxSize({\n check: \"max_size\",\n ...util.normalizeParams(params),\n maximum,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _minSize(minimum, params) {\n return new checks.$ZodCheckMinSize({\n check: \"min_size\",\n ...util.normalizeParams(params),\n minimum,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _size(size, params) {\n return new checks.$ZodCheckSizeEquals({\n check: \"size_equals\",\n ...util.normalizeParams(params),\n size,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _maxLength(maximum, params) {\n const ch = new checks.$ZodCheckMaxLength({\n check: \"max_length\",\n ...util.normalizeParams(params),\n maximum,\n });\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _minLength(minimum, params) {\n return new checks.$ZodCheckMinLength({\n check: \"min_length\",\n ...util.normalizeParams(params),\n minimum,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _length(length, params) {\n return new checks.$ZodCheckLengthEquals({\n check: \"length_equals\",\n ...util.normalizeParams(params),\n length,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _regex(pattern, params) {\n return new checks.$ZodCheckRegex({\n check: \"string_format\",\n format: \"regex\",\n ...util.normalizeParams(params),\n pattern,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lowercase(params) {\n return new checks.$ZodCheckLowerCase({\n check: \"string_format\",\n format: \"lowercase\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uppercase(params) {\n return new checks.$ZodCheckUpperCase({\n check: \"string_format\",\n format: \"uppercase\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _includes(includes, params) {\n return new checks.$ZodCheckIncludes({\n check: \"string_format\",\n format: \"includes\",\n ...util.normalizeParams(params),\n includes,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _startsWith(prefix, params) {\n return new checks.$ZodCheckStartsWith({\n check: \"string_format\",\n format: \"starts_with\",\n ...util.normalizeParams(params),\n prefix,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _endsWith(suffix, params) {\n return new checks.$ZodCheckEndsWith({\n check: \"string_format\",\n format: \"ends_with\",\n ...util.normalizeParams(params),\n suffix,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _property(property, schema, params) {\n return new checks.$ZodCheckProperty({\n check: \"property\",\n property,\n schema,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _properties(shape, params) {\n return new checks.$ZodCheckProperties({\n check: \"properties\",\n shape,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _mime(types, params) {\n return new checks.$ZodCheckMimeType({\n check: \"mime_type\",\n mime: types,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _overwrite(tx) {\n return new checks.$ZodCheckOverwrite({\n check: \"overwrite\",\n tx,\n });\n}\n// normalize\n// @__NO_SIDE_EFFECTS__\nexport function _normalize(form) {\n return _overwrite((input) => input.normalize(form));\n}\n// trim\n// @__NO_SIDE_EFFECTS__\nexport function _trim() {\n return _overwrite((input) => input.trim());\n}\n// toLowerCase\n// @__NO_SIDE_EFFECTS__\nexport function _toLowerCase() {\n return _overwrite((input) => input.toLowerCase());\n}\n// toUpperCase\n// @__NO_SIDE_EFFECTS__\nexport function _toUpperCase() {\n return _overwrite((input) => input.toUpperCase());\n}\n// slugify\n// @__NO_SIDE_EFFECTS__\nexport function _slugify() {\n return _overwrite((input) => util.slugify(input));\n}\n// @__NO_SIDE_EFFECTS__\nexport function _array(Class, element, params) {\n return new Class({\n type: \"array\",\n element,\n // get element() {\n // return element;\n // },\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _union(Class, options, params) {\n return new Class({\n type: \"union\",\n options,\n ...util.normalizeParams(params),\n });\n}\nexport function _xor(Class, options, params) {\n return new Class({\n type: \"union\",\n options,\n inclusive: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _discriminatedUnion(Class, discriminator, options, params) {\n return new Class({\n type: \"union\",\n options: options,\n discriminator,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _intersection(Class, left, right) {\n return new Class({\n type: \"intersection\",\n left,\n right,\n });\n}\n// export function _tuple(\n// Class: util.SchemaClass<schemas.$ZodTuple>,\n// items: [],\n// params?: string | $ZodTupleParams\n// ): schemas.$ZodTuple<[], null>;\n// @__NO_SIDE_EFFECTS__\nexport function _tuple(Class, items, _paramsOrRest, _params) {\n const hasRest = _paramsOrRest instanceof schemas.$ZodType;\n const params = hasRest ? _params : _paramsOrRest;\n const rest = hasRest ? _paramsOrRest : null;\n return new Class({\n type: \"tuple\",\n items,\n rest,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _record(Class, keyType, valueType, params) {\n return new Class({\n type: \"record\",\n keyType,\n valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _map(Class, keyType, valueType, params) {\n return new Class({\n type: \"map\",\n keyType,\n valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _set(Class, valueType, params) {\n return new Class({\n type: \"set\",\n valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _enum(Class, values, params) {\n const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;\n // if (Array.isArray(values)) {\n // for (const value of values) {\n // entries[value] = value;\n // }\n // } else {\n // Object.assign(entries, values);\n // }\n // const entries: util.EnumLike = {};\n // for (const val of values) {\n // entries[val] = val;\n // }\n return new Class({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\n/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead.\n *\n * ```ts\n * enum Colors { red, green, blue }\n * z.enum(Colors);\n * ```\n */\nexport function _nativeEnum(Class, entries, params) {\n return new Class({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _literal(Class, value, params) {\n return new Class({\n type: \"literal\",\n values: Array.isArray(value) ? value : [value],\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _file(Class, params) {\n return new Class({\n type: \"file\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _transform(Class, fn) {\n return new Class({\n type: \"transform\",\n transform: fn,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _optional(Class, innerType) {\n return new Class({\n type: \"optional\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nullable(Class, innerType) {\n return new Class({\n type: \"nullable\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _default(Class, innerType, defaultValue) {\n return new Class({\n type: \"default\",\n innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nonoptional(Class, innerType, params) {\n return new Class({\n type: \"nonoptional\",\n innerType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _success(Class, innerType) {\n return new Class({\n type: \"success\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _catch(Class, innerType, catchValue) {\n return new Class({\n type: \"catch\",\n innerType,\n catchValue: (typeof catchValue === \"function\" ? catchValue : util.constantCatch(catchValue)),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _pipe(Class, in_, out) {\n return new Class({\n type: \"pipe\",\n in: in_,\n out,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _readonly(Class, innerType) {\n return new Class({\n type: \"readonly\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _templateLiteral(Class, parts, params) {\n return new Class({\n type: \"template_literal\",\n parts,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lazy(Class, getter) {\n return new Class({\n type: \"lazy\",\n getter,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _promise(Class, innerType) {\n return new Class({\n type: \"promise\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _custom(Class, fn, _params) {\n const norm = util.normalizeParams(_params);\n norm.abort ?? (norm.abort = true); // default to abort:false\n const schema = new Class({\n type: \"custom\",\n check: \"custom\",\n fn: fn,\n ...norm,\n });\n return schema;\n}\n// same as _custom but defaults to abort:false\n// @__NO_SIDE_EFFECTS__\nexport function _refine(Class, fn, _params) {\n const schema = new Class({\n type: \"custom\",\n check: \"custom\",\n fn: fn,\n ...util.normalizeParams(_params),\n });\n return schema;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _superRefine(fn, params) {\n const ch = _check((payload) => {\n payload.addIssue = (issue) => {\n if (typeof issue === \"string\") {\n payload.issues.push(util.issue(issue, payload.value, ch._zod.def));\n }\n else {\n // for Zod 3 backwards compatibility\n const _issue = issue;\n if (_issue.fatal)\n _issue.continue = false;\n _issue.code ?? (_issue.code = \"custom\");\n if (!(\"input\" in _issue))\n _issue.input = payload.value;\n _issue.inst ?? (_issue.inst = ch);\n _issue.continue ?? (_issue.continue = !ch._zod.def.abort); // abort is always undefined, so this is always true...\n payload.issues.push(util.issue(_issue));\n }\n };\n return fn(payload.value, payload);\n }, params);\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _check(fn, params) {\n const ch = new checks.$ZodCheck({\n check: \"custom\",\n ...util.normalizeParams(params),\n });\n ch._zod.check = fn;\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function describe(description) {\n const ch = new checks.$ZodCheck({ check: \"describe\" });\n ch._zod.onattach = [\n (inst) => {\n const existing = registries.globalRegistry.get(inst) ?? {};\n registries.globalRegistry.add(inst, { ...existing, description });\n },\n ];\n ch._zod.check = () => { }; // no-op check\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function meta(metadata) {\n const ch = new checks.$ZodCheck({ check: \"meta\" });\n ch._zod.onattach = [\n (inst) => {\n const existing = registries.globalRegistry.get(inst) ?? {};\n registries.globalRegistry.add(inst, { ...existing, ...metadata });\n },\n ];\n ch._zod.check = () => { }; // no-op check\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _stringbool(Classes, _params) {\n const params = util.normalizeParams(_params);\n let truthyArray = params.truthy ?? [\"true\", \"1\", \"yes\", \"on\", \"y\", \"enabled\"];\n let falsyArray = params.falsy ?? [\"false\", \"0\", \"no\", \"off\", \"n\", \"disabled\"];\n if (params.case !== \"sensitive\") {\n truthyArray = truthyArray.map((v) => (typeof v === \"string\" ? v.toLowerCase() : v));\n falsyArray = falsyArray.map((v) => (typeof v === \"string\" ? v.toLowerCase() : v));\n }\n const truthySet = new Set(truthyArray);\n const falsySet = new Set(falsyArray);\n const _Codec = Classes.Codec ?? schemas.$ZodCodec;\n const _Boolean = Classes.Boolean ?? schemas.$ZodBoolean;\n const _String = Classes.String ?? schemas.$ZodString;\n const stringSchema = new _String({ type: \"string\", error: params.error });\n const booleanSchema = new _Boolean({ type: \"boolean\", error: params.error });\n const codec = new _Codec({\n type: \"pipe\",\n in: stringSchema,\n out: booleanSchema,\n transform: ((input, payload) => {\n let data = input;\n if (params.case !== \"sensitive\")\n data = data.toLowerCase();\n if (truthySet.has(data)) {\n return true;\n }\n else if (falsySet.has(data)) {\n return false;\n }\n else {\n payload.issues.push({\n code: \"invalid_value\",\n expected: \"stringbool\",\n values: [...truthySet, ...falsySet],\n input: payload.value,\n inst: codec,\n continue: false,\n });\n return {};\n }\n }),\n reverseTransform: ((input, _payload) => {\n if (input === true) {\n return truthyArray[0] || \"true\";\n }\n else {\n return falsyArray[0] || \"false\";\n }\n }),\n error: params.error,\n });\n codec._zod.bag.truthy = truthyArray;\n codec._zod.bag.falsy = falsyArray;\n codec._zod.bag.case = params.case ?? \"insensitive\";\n return codec;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _stringFormat(Class, format, fnOrRegex, _params = {}) {\n const params = util.normalizeParams(_params);\n const def = {\n check: \"string_format\",\n type: \"string\",\n format,\n fn: typeof fnOrRegex === \"function\" ? fnOrRegex : (val) => fnOrRegex.test(val),\n ...params,\n };\n if (fnOrRegex instanceof RegExp) {\n def.pattern = fnOrRegex;\n }\n const inst = new Class(def);\n return inst;\n}\n","import * as core from \"../core/index.js\";\nimport * as regexes from \"../core/regexes.js\";\nimport * as util from \"../core/util.js\";\nimport * as parse from \"./parse.js\";\nexport const ZodMiniType = /*@__PURE__*/ core.$constructor(\"ZodMiniType\", (inst, def) => {\n if (!inst._zod)\n throw new Error(\"Uninitialized schema in ZodMiniType.\");\n core.$ZodType.init(inst, def);\n inst.def = def;\n inst.type = def.type;\n}, {\n // `with` is an alias for `check`: the same function object, not a wrapper.\n get with() {\n return this.check;\n },\n set with(value) {\n util.own(this, \"with\", value);\n },\n parse(data, params) {\n return parse.parse(this, data, params, { callee: this.parse });\n },\n parseAsync(data, params) {\n return parse.parseAsync(this, data, params, { callee: this.parseAsync });\n },\n safeParse(data, params) {\n return parse.safeParse(this, data, params);\n },\n safeParseAsync(data, params) {\n return parse.safeParseAsync(this, data, params);\n },\n check(...checks) {\n const def = this.def;\n return this.clone({\n ...def,\n checks: [\n ...(def.checks ?? []),\n ...checks.map((ch) => typeof ch === \"function\" ? { _zod: { check: ch, def: { check: \"custom\" }, onattach: [] } } : ch),\n ],\n }, { parent: true });\n },\n clone(_def, params) {\n return core.clone(this, _def, params);\n },\n brand() {\n return this;\n },\n register(reg, meta) {\n reg.add(this, meta);\n return this;\n },\n apply(fn, ...args) {\n return args.length === 0 ? fn(this) : fn(this, ...args);\n },\n});\nexport const ZodMiniString = /*@__PURE__*/ core.$constructor(\"ZodMiniString\", (inst, def) => {\n core.$ZodString.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function string(params) {\n return core._string(ZodMiniString, params);\n}\nexport const ZodMiniStringFormat = /*@__PURE__*/ core.$constructor(\"ZodMiniStringFormat\", (inst, def) => {\n core.$ZodStringFormat.init(inst, def);\n ZodMiniString.init(inst, def);\n});\nexport const ZodMiniEmail = /*@__PURE__*/ core.$constructor(\"ZodMiniEmail\", (inst, def) => {\n core.$ZodEmail.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function email(params) {\n return core._email(ZodMiniEmail, params);\n}\nexport const ZodMiniGUID = /*@__PURE__*/ core.$constructor(\"ZodMiniGUID\", (inst, def) => {\n core.$ZodGUID.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function guid(params) {\n return core._guid(ZodMiniGUID, params);\n}\nexport const ZodMiniUUID = /*@__PURE__*/ core.$constructor(\"ZodMiniUUID\", (inst, def) => {\n core.$ZodUUID.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function uuid(params) {\n return core._uuid(ZodMiniUUID, params);\n}\n// @__NO_SIDE_EFFECTS__\nexport function uuidv4(params) {\n return core._uuidv4(ZodMiniUUID, params);\n}\n// ZodMiniUUIDv6\n// @__NO_SIDE_EFFECTS__\nexport function uuidv6(params) {\n return core._uuidv6(ZodMiniUUID, params);\n}\n// ZodMiniUUIDv7\n// @__NO_SIDE_EFFECTS__\nexport function uuidv7(params) {\n return core._uuidv7(ZodMiniUUID, params);\n}\nexport const ZodMiniURL = /*@__PURE__*/ core.$constructor(\"ZodMiniURL\", (inst, def) => {\n core.$ZodURL.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function url(params) {\n return core._url(ZodMiniURL, params);\n}\n// @__NO_SIDE_EFFECTS__\nexport function httpUrl(params) {\n return core._url(ZodMiniURL, {\n protocol: regexes.httpProtocol,\n hostname: regexes.domain,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniEmoji = /*@__PURE__*/ core.$constructor(\"ZodMiniEmoji\", (inst, def) => {\n core.$ZodEmoji.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function emoji(params) {\n return core._emoji(ZodMiniEmoji, params);\n}\nexport const ZodMiniNanoID = /*@__PURE__*/ core.$constructor(\"ZodMiniNanoID\", (inst, def) => {\n core.$ZodNanoID.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function nanoid(params) {\n return core._nanoid(ZodMiniNanoID, params);\n}\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link ZodMiniCUID2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport const ZodMiniCUID = /*@__PURE__*/ core.$constructor(\"ZodMiniCUID\", (inst, def) => {\n core.$ZodCUID.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n/**\n * Validates a CUID v1 string.\n *\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link cuid2 | `z.cuid2()`} instead.\n * See https://github.com/paralleldrive/cuid.\n */\n// @__NO_SIDE_EFFECTS__\nexport function cuid(params) {\n return core._cuid(ZodMiniCUID, params);\n}\nexport const ZodMiniCUID2 = /*@__PURE__*/ core.$constructor(\"ZodMiniCUID2\", (inst, def) => {\n core.$ZodCUID2.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function cuid2(params) {\n return core._cuid2(ZodMiniCUID2, params);\n}\nexport const ZodMiniULID = /*@__PURE__*/ core.$constructor(\"ZodMiniULID\", (inst, def) => {\n core.$ZodULID.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function ulid(params) {\n return core._ulid(ZodMiniULID, params);\n}\nexport const ZodMiniXID = /*@__PURE__*/ core.$constructor(\"ZodMiniXID\", (inst, def) => {\n core.$ZodXID.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function xid(params) {\n return core._xid(ZodMiniXID, params);\n}\nexport const ZodMiniKSUID = /*@__PURE__*/ core.$constructor(\"ZodMiniKSUID\", (inst, def) => {\n core.$ZodKSUID.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function ksuid(params) {\n return core._ksuid(ZodMiniKSUID, params);\n}\nexport const ZodMiniIPv4 = /*@__PURE__*/ core.$constructor(\"ZodMiniIPv4\", (inst, def) => {\n core.$ZodIPv4.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function ipv4(params) {\n return core._ipv4(ZodMiniIPv4, params);\n}\nexport const ZodMiniIPv6 = /*@__PURE__*/ core.$constructor(\"ZodMiniIPv6\", (inst, def) => {\n core.$ZodIPv6.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function ipv6(params) {\n return core._ipv6(ZodMiniIPv6, params);\n}\nexport const ZodMiniCIDRv4 = /*@__PURE__*/ core.$constructor(\"ZodMiniCIDRv4\", (inst, def) => {\n core.$ZodCIDRv4.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function cidrv4(params) {\n return core._cidrv4(ZodMiniCIDRv4, params);\n}\nexport const ZodMiniCIDRv6 = /*@__PURE__*/ core.$constructor(\"ZodMiniCIDRv6\", (inst, def) => {\n core.$ZodCIDRv6.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function cidrv6(params) {\n return core._cidrv6(ZodMiniCIDRv6, params);\n}\nexport const ZodMiniMAC = /*@__PURE__*/ core.$constructor(\"ZodMiniMAC\", (inst, def) => {\n core.$ZodMAC.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function mac(params) {\n return core._mac(ZodMiniMAC, params);\n}\nexport const ZodMiniBase64 = /*@__PURE__*/ core.$constructor(\"ZodMiniBase64\", (inst, def) => {\n core.$ZodBase64.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function base64(params) {\n return core._base64(ZodMiniBase64, params);\n}\nexport const ZodMiniBase64URL = /*@__PURE__*/ core.$constructor(\"ZodMiniBase64URL\", (inst, def) => {\n core.$ZodBase64URL.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function base64url(params) {\n return core._base64url(ZodMiniBase64URL, params);\n}\nexport const ZodMiniE164 = /*@__PURE__*/ core.$constructor(\"ZodMiniE164\", (inst, def) => {\n core.$ZodE164.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function e164(params) {\n return core._e164(ZodMiniE164, params);\n}\nexport const ZodMiniCreditCard = /*@__PURE__*/ core.$constructor(\"ZodMiniCreditCard\", (inst, def) => {\n core.$ZodCreditCard.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function creditCard(params) {\n return core._creditCard(ZodMiniCreditCard, params);\n}\nexport const ZodMiniIBAN = /*@__PURE__*/ core.$constructor(\"ZodMiniIBAN\", (inst, def) => {\n core.$ZodIBAN.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function iban(params) {\n return core._iban(ZodMiniIBAN, params);\n}\nexport const ZodMiniJWT = /*@__PURE__*/ core.$constructor(\"ZodMiniJWT\", (inst, def) => {\n core.$ZodJWT.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function jwt(params) {\n return core._jwt(ZodMiniJWT, params);\n}\nexport const ZodMiniCustomStringFormat = /*@__PURE__*/ core.$constructor(\"ZodMiniCustomStringFormat\", (inst, def) => {\n core.$ZodCustomStringFormat.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function stringFormat(format, fnOrRegex, _params = {}) {\n return core._stringFormat(ZodMiniCustomStringFormat, format, fnOrRegex, _params);\n}\n// @__NO_SIDE_EFFECTS__\nexport function hostname(_params) {\n return core._stringFormat(ZodMiniCustomStringFormat, \"hostname\", regexes.hostname, _params);\n}\n// @__NO_SIDE_EFFECTS__\nexport function hex(_params) {\n return core._stringFormat(ZodMiniCustomStringFormat, \"hex\", regexes.hex, _params);\n}\n// @__NO_SIDE_EFFECTS__\nexport function currencyCode(_params) {\n return core._stringFormat(ZodMiniCustomStringFormat, \"currency_code\", regexes.currencyCode, _params);\n}\n// @__NO_SIDE_EFFECTS__\nexport function hash(alg, params) {\n const enc = params?.enc ?? \"hex\";\n const format = `${alg}_${enc}`;\n const regex = core.regexes[format];\n // check for unrecognized format\n if (!regex)\n throw new Error(`Unrecognized hash format: ${format}`);\n return core._stringFormat(ZodMiniCustomStringFormat, format, regex, params);\n}\nexport const ZodMiniNumber = /*@__PURE__*/ core.$constructor(\"ZodMiniNumber\", (inst, def) => {\n core.$ZodNumber.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function number(params) {\n return core._number(ZodMiniNumber, params);\n}\nexport const ZodMiniNumberFormat = /*@__PURE__*/ core.$constructor(\"ZodMiniNumberFormat\", (inst, def) => {\n core.$ZodNumberFormat.init(inst, def);\n ZodMiniNumber.init(inst, def);\n});\nexport function int(params) {\n return core._int(ZodMiniNumberFormat, params);\n}\nexport function float32(params) {\n return core._float32(ZodMiniNumberFormat, params);\n}\nexport function float64(params) {\n return core._float64(ZodMiniNumberFormat, params);\n}\nexport function int32(params) {\n return core._int32(ZodMiniNumberFormat, params);\n}\nexport function uint32(params) {\n return core._uint32(ZodMiniNumberFormat, params);\n}\nexport const ZodMiniBoolean = /*@__PURE__*/ core.$constructor(\"ZodMiniBoolean\", (inst, def) => {\n core.$ZodBoolean.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function boolean(params) {\n return core._boolean(ZodMiniBoolean, params);\n}\nexport const ZodMiniBigInt = /*@__PURE__*/ core.$constructor(\"ZodMiniBigInt\", (inst, def) => {\n core.$ZodBigInt.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function bigint(params) {\n return core._bigint(ZodMiniBigInt, params);\n}\nexport const ZodMiniBigIntFormat = /*@__PURE__*/ core.$constructor(\"ZodMiniBigIntFormat\", (inst, def) => {\n core.$ZodBigIntFormat.init(inst, def);\n ZodMiniBigInt.init(inst, def);\n});\nexport function int64(params) {\n return core._int64(ZodMiniBigIntFormat, params);\n}\nexport function uint64(params) {\n return core._uint64(ZodMiniBigIntFormat, params);\n}\nexport const ZodMiniSymbol = /*@__PURE__*/ core.$constructor(\"ZodMiniSymbol\", (inst, def) => {\n core.$ZodSymbol.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function symbol(params) {\n return core._symbol(ZodMiniSymbol, params);\n}\nexport const ZodMiniUndefined = /*@__PURE__*/ core.$constructor(\"ZodMiniUndefined\", (inst, def) => {\n core.$ZodUndefined.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nfunction _undefined(params) {\n return core._undefined(ZodMiniUndefined, params);\n}\nexport { _undefined as undefined };\nexport const ZodMiniNull = /*@__PURE__*/ core.$constructor(\"ZodMiniNull\", (inst, def) => {\n core.$ZodNull.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nfunction _null(params) {\n return core._null(ZodMiniNull, params);\n}\nexport { _null as null };\nexport const ZodMiniAny = /*@__PURE__*/ core.$constructor(\"ZodMiniAny\", (inst, def) => {\n core.$ZodAny.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function any() {\n return core._any(ZodMiniAny);\n}\nexport const ZodMiniUnknown = /*@__PURE__*/ core.$constructor(\"ZodMiniUnknown\", (inst, def) => {\n core.$ZodUnknown.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function unknown() {\n return core._unknown(ZodMiniUnknown);\n}\nexport const ZodMiniNever = /*@__PURE__*/ core.$constructor(\"ZodMiniNever\", (inst, def) => {\n core.$ZodNever.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function never(params) {\n return core._never(ZodMiniNever, params);\n}\nexport const ZodMiniVoid = /*@__PURE__*/ core.$constructor(\"ZodMiniVoid\", (inst, def) => {\n core.$ZodVoid.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nfunction _void(params) {\n return core._void(ZodMiniVoid, params);\n}\nexport { _void as void };\nexport const ZodMiniDate = /*@__PURE__*/ core.$constructor(\"ZodMiniDate\", (inst, def) => {\n core.$ZodDate.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function date(params) {\n return core._date(ZodMiniDate, params);\n}\nexport const ZodMiniArray = /*@__PURE__*/ core.$constructor(\"ZodMiniArray\", (inst, def) => {\n core.$ZodArray.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function array(element, params) {\n return new ZodMiniArray({\n type: \"array\",\n element: element,\n ...util.normalizeParams(params),\n });\n}\n// .keyof\n// @__NO_SIDE_EFFECTS__\nexport function keyof(schema) {\n const shape = schema._zod.def.shape;\n return _enum(Object.keys(shape));\n}\nexport const ZodMiniObject = /*@__PURE__*/ core.$constructor(\"ZodMiniObject\", (inst, def) => {\n core.$ZodObject.init(inst, def);\n ZodMiniType.init(inst, def);\n util.installLazyProp(inst, \"shape\", (self) => self._zod.def.shape, false);\n});\n// @__NO_SIDE_EFFECTS__\nexport function object(shape, params) {\n const def = {\n type: \"object\",\n shape: shape ?? {},\n ...util.normalizeParams(params),\n };\n return new ZodMiniObject(def);\n}\n// strictObject\n// @__NO_SIDE_EFFECTS__\nexport function strictObject(shape, params) {\n return new ZodMiniObject({\n type: \"object\",\n shape,\n catchall: never(),\n ...util.normalizeParams(params),\n });\n}\n// looseObject\n// @__NO_SIDE_EFFECTS__\nexport function looseObject(shape, params) {\n return new ZodMiniObject({\n type: \"object\",\n shape,\n catchall: unknown(),\n ...util.normalizeParams(params),\n });\n}\n// object methods\n// @__NO_SIDE_EFFECTS__\nexport function extend(schema, shape) {\n return util.extend(schema, shape);\n}\n// @__NO_SIDE_EFFECTS__\nexport function safeExtend(schema, shape) {\n return util.safeExtend(schema, shape);\n}\n/**\n * @deprecated Use [`z.extend(A, B.shape)`](https://zod.dev/api?id=extend) instead.\n */\n// @__NO_SIDE_EFFECTS__\nexport function merge(a, b) {\n return util.merge(a, b);\n}\n// @__NO_SIDE_EFFECTS__\nexport function pick(schema, mask) {\n return util.pick(schema, mask);\n}\n// .omit\n// @__NO_SIDE_EFFECTS__\nexport function omit(schema, mask) {\n return util.omit(schema, mask);\n}\n// @__NO_SIDE_EFFECTS__\nexport function partial(schema, mask) {\n const def = schema._zod.def;\n if (def.type !== \"tuple\")\n return util.partial(ZodMiniOptional, schema, mask);\n // a refinement was authored against the full arity; partialing would run it on a shorter array\n if (def.checks?.length)\n throw new Error(\".partial() cannot be used on tuple schemas containing refinements\");\n return util.clone(schema, {\n ...def,\n items: def.items.map((item) => new ZodMiniOptional({ type: \"optional\", innerType: item })),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function exactPartial(schema, mask) {\n return util.partial(ZodMiniExactOptional, schema, mask, \"exactPartial\");\n}\n// @__NO_SIDE_EFFECTS__\nexport function required(schema, mask) {\n return util.required(ZodMiniNonOptional, schema, mask);\n}\n// @__NO_SIDE_EFFECTS__\nexport function catchall(inst, catchall) {\n // `mergeDefs` rather than a spread: spreading reads `shape`, and resolving it can mint a whole fresh subtree\n return inst.clone(util.mergeDefs(inst._zod.def, { catchall: catchall }));\n}\nexport const ZodMiniUnion = /*@__PURE__*/ core.$constructor(\"ZodMiniUnion\", (inst, def) => {\n core.$ZodUnion.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function union(options, params) {\n return new ZodMiniUnion({\n type: \"union\",\n options: options,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniXor = /*@__PURE__*/ core.$constructor(\"ZodMiniXor\", (inst, def) => {\n ZodMiniUnion.init(inst, def);\n core.$ZodXor.init(inst, def);\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 ZodMiniXor({\n type: \"union\",\n options: options,\n inclusive: false,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniDiscriminatedUnion = /*@__PURE__*/ core.$constructor(\"ZodMiniDiscriminatedUnion\", (inst, def) => {\n core.$ZodDiscriminatedUnion.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function discriminatedUnion(discriminator, options, params) {\n return new ZodMiniDiscriminatedUnion({\n type: \"union\",\n options: options,\n discriminator,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniIntersection = /*@__PURE__*/ core.$constructor(\"ZodMiniIntersection\", (inst, def) => {\n core.$ZodIntersection.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function intersection(left, right) {\n return new ZodMiniIntersection({\n type: \"intersection\",\n left: left,\n right: right,\n });\n}\nexport const ZodMiniTuple = /*@__PURE__*/ core.$constructor(\"ZodMiniTuple\", (inst, def) => {\n core.$ZodTuple.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\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 ZodMiniTuple({\n type: \"tuple\",\n items: items,\n rest,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniRecord = /*@__PURE__*/ core.$constructor(\"ZodMiniRecord\", (inst, def) => {\n core.$ZodRecord.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function record(keyType, valueType, params) {\n // v3-compat: z.record(valueType, params?) — defaults keyType to z.string()\n if (!valueType || !valueType._zod) {\n return new ZodMiniRecord({\n type: \"record\",\n keyType: string(),\n valueType: keyType,\n ...util.normalizeParams(valueType),\n });\n }\n return new ZodMiniRecord({\n type: \"record\",\n keyType,\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function partialRecord(keyType, valueType, params) {\n return new ZodMiniRecord({\n type: \"record\",\n keyType,\n valueType: valueType,\n ...util.normalizeParams(params),\n partial: true,\n });\n}\nexport function looseRecord(keyType, valueType, params) {\n return new ZodMiniRecord({\n type: \"record\",\n keyType,\n valueType: valueType,\n mode: \"loose\",\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniMap = /*@__PURE__*/ core.$constructor(\"ZodMiniMap\", (inst, def) => {\n core.$ZodMap.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function map(keyType, valueType, params) {\n return new ZodMiniMap({\n type: \"map\",\n keyType: keyType,\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniSet = /*@__PURE__*/ core.$constructor(\"ZodMiniSet\", (inst, def) => {\n core.$ZodSet.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function set(valueType, params) {\n return new ZodMiniSet({\n type: \"set\",\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniEnum = /*@__PURE__*/ core.$constructor(\"ZodMiniEnum\", (inst, def) => {\n core.$ZodEnum.init(inst, def);\n ZodMiniType.init(inst, def);\n // reuse the parsed value set so a numeric TS enum's reverse-mapping keys stay out\n inst.options = [...inst._zod.values];\n});\n// @__NO_SIDE_EFFECTS__\nfunction _enum(values, params) {\n const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;\n return new ZodMiniEnum({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\nexport { _enum as enum };\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(entries, params) {\n return new ZodMiniEnum({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniLiteral = /*@__PURE__*/ core.$constructor(\"ZodMiniLiteral\", (inst, def) => {\n core.$ZodLiteral.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function literal(value, params) {\n return new ZodMiniLiteral({\n type: \"literal\",\n values: Array.isArray(value) ? value : [value],\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniFile = /*@__PURE__*/ core.$constructor(\"ZodMiniFile\", (inst, def) => {\n core.$ZodFile.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function file(params) {\n return core._file(ZodMiniFile, params);\n}\nexport const ZodMiniTransform = /*@__PURE__*/ core.$constructor(\"ZodMiniTransform\", (inst, def) => {\n core.$ZodTransform.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function transform(fn) {\n return new ZodMiniTransform({\n type: \"transform\",\n transform: fn,\n });\n}\nexport const ZodMiniOptional = /*@__PURE__*/ core.$constructor(\"ZodMiniOptional\", (inst, def) => {\n core.$ZodOptional.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function optional(innerType) {\n return new ZodMiniOptional({\n type: \"optional\",\n innerType: innerType,\n });\n}\nexport const ZodMiniExactOptional = /*@__PURE__*/ core.$constructor(\"ZodMiniExactOptional\", (inst, def) => {\n core.$ZodExactOptional.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function exactOptional(innerType) {\n return new ZodMiniExactOptional({\n type: \"optional\",\n innerType: innerType,\n });\n}\nexport const ZodMiniNullable = /*@__PURE__*/ core.$constructor(\"ZodMiniNullable\", (inst, def) => {\n core.$ZodNullable.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function nullable(innerType) {\n return new ZodMiniNullable({\n type: \"nullable\",\n innerType: innerType,\n });\n}\n// nullish\n// @__NO_SIDE_EFFECTS__\nexport function nullish(innerType) {\n return optional(nullable(innerType));\n}\nexport const ZodMiniDefault = /*@__PURE__*/ core.$constructor(\"ZodMiniDefault\", (inst, def) => {\n core.$ZodDefault.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function _default(innerType, defaultValue) {\n return new ZodMiniDefault({\n type: \"default\",\n innerType: innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\nexport const ZodMiniPrefault = /*@__PURE__*/ core.$constructor(\"ZodMiniPrefault\", (inst, def) => {\n core.$ZodPrefault.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function prefault(innerType, defaultValue) {\n return new ZodMiniPrefault({\n type: \"prefault\",\n innerType: innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\nexport const ZodMiniNonOptional = /*@__PURE__*/ core.$constructor(\"ZodMiniNonOptional\", (inst, def) => {\n core.$ZodNonOptional.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function nonoptional(innerType, params) {\n return new ZodMiniNonOptional({\n type: \"nonoptional\",\n innerType: innerType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniSuccess = /*@__PURE__*/ core.$constructor(\"ZodMiniSuccess\", (inst, def) => {\n core.$ZodSuccess.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function success(innerType) {\n return new ZodMiniSuccess({\n type: \"success\",\n innerType: innerType,\n });\n}\nexport const ZodMiniCatch = /*@__PURE__*/ core.$constructor(\"ZodMiniCatch\", (inst, def) => {\n core.$ZodCatch.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nfunction _catch(innerType, catchValue) {\n return new ZodMiniCatch({\n type: \"catch\",\n innerType: innerType,\n catchValue: (typeof catchValue === \"function\" ? catchValue : core.util.constantCatch(catchValue)),\n });\n}\nexport { _catch as catch };\nexport const ZodMiniNaN = /*@__PURE__*/ core.$constructor(\"ZodMiniNaN\", (inst, def) => {\n core.$ZodNaN.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function nan(params) {\n return core._nan(ZodMiniNaN, params);\n}\nexport const ZodMiniPipe = /*@__PURE__*/ core.$constructor(\"ZodMiniPipe\", (inst, def) => {\n core.$ZodPipe.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function pipe(in_, out) {\n return new ZodMiniPipe({\n type: \"pipe\",\n in: in_,\n out: out,\n });\n}\nexport const ZodMiniCodec = /*@__PURE__*/ core.$constructor(\"ZodMiniCodec\", (inst, def) => {\n ZodMiniPipe.init(inst, def);\n core.$ZodCodec.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function codec(in_, out, params) {\n return new ZodMiniCodec({\n type: \"pipe\",\n in: in_,\n out: out,\n transform: params.decode,\n reverseTransform: params.encode,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function invertCodec(codec) {\n const def = codec._zod.def;\n return new ZodMiniCodec({\n type: \"pipe\",\n in: def.out,\n out: def.in,\n transform: def.reverseTransform,\n reverseTransform: def.transform,\n });\n}\nexport const ZodMiniReadonly = /*@__PURE__*/ core.$constructor(\"ZodMiniReadonly\", (inst, def) => {\n core.$ZodReadonly.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function readonly(innerType) {\n return new ZodMiniReadonly({\n type: \"readonly\",\n innerType: innerType,\n });\n}\nexport const ZodMiniTemplateLiteral = /*@__PURE__*/ core.$constructor(\"ZodMiniTemplateLiteral\", (inst, def) => {\n core.$ZodTemplateLiteral.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function templateLiteral(parts, params) {\n return new ZodMiniTemplateLiteral({\n type: \"template_literal\",\n parts,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniLazy = /*@__PURE__*/ core.$constructor(\"ZodMiniLazy\", (inst, def) => {\n core.$ZodLazy.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// export function lazy<T extends object>(getter: () => T): T {\n// return util.createTransparentProxy<T>(getter);\n// }\n// @__NO_SIDE_EFFECTS__\nfunction _lazy(getter) {\n return new ZodMiniLazy({\n type: \"lazy\",\n getter: getter,\n });\n}\nexport { _lazy as lazy };\nexport const ZodMiniPromise = /*@__PURE__*/ core.$constructor(\"ZodMiniPromise\", (inst, def) => {\n core.$ZodPromise.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function promise(innerType) {\n return new ZodMiniPromise({\n type: \"promise\",\n innerType: innerType,\n });\n}\nexport const ZodMiniCustom = /*@__PURE__*/ core.$constructor(\"ZodMiniCustom\", (inst, def) => {\n core.$ZodCustom.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// custom checks\n// @__NO_SIDE_EFFECTS__\nexport function check(fn, params) {\n const ch = new core.$ZodCheck({\n check: \"custom\",\n ...util.normalizeParams(params),\n });\n ch._zod.check = fn;\n return ch;\n}\n// ZodCustom custom schema\n// @__NO_SIDE_EFFECTS__\nexport function custom(fn, _params) {\n return core._custom(ZodMiniCustom, fn ?? (() => true), _params);\n}\n// refine\n// @__NO_SIDE_EFFECTS__\nexport function refine(fn, _params = {}) {\n return core._refine(ZodMiniCustom, fn, _params);\n}\n// superRefine\n// @__NO_SIDE_EFFECTS__\nexport function superRefine(fn, params) {\n return core._superRefine(fn, params);\n}\n// Re-export describe and meta from core\nexport const describe = core.describe;\nexport const meta = core.meta;\n// instanceof\nclass Class {\n constructor(..._args) { }\n}\n// @__NO_SIDE_EFFECTS__\nfunction _instanceof(cls, params = {}) {\n const inst = custom((data) => data instanceof cls, params);\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: ZodMiniCodec,\n Boolean: ZodMiniBoolean,\n String: ZodMiniString,\n}, ...args);\n// @__NO_SIDE_EFFECTS__\nexport function json() {\n const jsonSchema = _lazy(() => {\n return union([string(), number(), boolean(), _null(), array(jsonSchema), record(string(), jsonSchema)]);\n });\n return jsonSchema;\n}\nexport const ZodMiniFunction = /*@__PURE__*/ core.$constructor(\"ZodMiniFunction\", (inst, def) => {\n core.$ZodFunction.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function _function(params) {\n return new ZodMiniFunction({\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 };\n","import * as core from \"../core/index.js\";\nimport * as schemas from \"./schemas.js\";\n// @__NO_SIDE_EFFECTS__\nexport function string(params) {\n return core._coercedString(schemas.ZodMiniString, params);\n}\n// @__NO_SIDE_EFFECTS__\nexport function number(params) {\n return core._coercedNumber(schemas.ZodMiniNumber, params);\n}\n// @__NO_SIDE_EFFECTS__\nexport function boolean(params) {\n return core._coercedBoolean(schemas.ZodMiniBoolean, params);\n}\n// @__NO_SIDE_EFFECTS__\nexport function bigint(params) {\n return core._coercedBigint(schemas.ZodMiniBigInt, params);\n}\n// @__NO_SIDE_EFFECTS__\nexport function date(params) {\n return core._coercedDate(schemas.ZodMiniDate, params);\n}\n","import * as z from \"zod/mini\";\n\n//#region upstream/framework/lib/property/input/common.ts\nconst BasePropertySchema = z.object({\n\tdisplayName: z.string(),\n\tdescription: z.optional(z.string()),\n\tadvanced: z.optional(z.boolean()),\n\twidth: z.optional(z.enum([\"half\", \"full\"])),\n\ticon: z.optional(z.string()),\n\tplaceholder: z.optional(z.string())\n});\nconst TPropertyValue = (_T, propertyType) => z.object({\n\ttype: z.literal(propertyType),\n\trequired: z.boolean(),\n\tdefaultValue: z.optional(z.any())\n});\n\n//#endregion\n//#region upstream/framework/lib/property/input/property-type.ts\nlet PropertyType = /* @__PURE__ */ function(PropertyType) {\n\tPropertyType[\"SHORT_TEXT\"] = \"SHORT_TEXT\";\n\tPropertyType[\"LONG_TEXT\"] = \"LONG_TEXT\";\n\tPropertyType[\"RICH_TEXT\"] = \"RICH_TEXT\";\n\tPropertyType[\"MARKDOWN\"] = \"MARKDOWN\";\n\tPropertyType[\"DROPDOWN\"] = \"DROPDOWN\";\n\tPropertyType[\"STATIC_DROPDOWN\"] = \"STATIC_DROPDOWN\";\n\tPropertyType[\"NUMBER\"] = \"NUMBER\";\n\tPropertyType[\"CHECKBOX\"] = \"CHECKBOX\";\n\tPropertyType[\"OAUTH2\"] = \"OAUTH2\";\n\tPropertyType[\"SECRET_TEXT\"] = \"SECRET_TEXT\";\n\tPropertyType[\"ARRAY\"] = \"ARRAY\";\n\tPropertyType[\"OBJECT\"] = \"OBJECT\";\n\tPropertyType[\"BASIC_AUTH\"] = \"BASIC_AUTH\";\n\tPropertyType[\"JSON\"] = \"JSON\";\n\tPropertyType[\"MULTI_SELECT_DROPDOWN\"] = \"MULTI_SELECT_DROPDOWN\";\n\tPropertyType[\"STATIC_MULTI_SELECT_DROPDOWN\"] = \"STATIC_MULTI_SELECT_DROPDOWN\";\n\tPropertyType[\"DYNAMIC\"] = \"DYNAMIC\";\n\tPropertyType[\"CUSTOM_AUTH\"] = \"CUSTOM_AUTH\";\n\tPropertyType[\"OIDC\"] = \"OIDC\";\n\tPropertyType[\"DATE_TIME\"] = \"DATE_TIME\";\n\tPropertyType[\"DATE_RANGE\"] = \"DATE_RANGE\";\n\tPropertyType[\"FILE\"] = \"FILE\";\n\tPropertyType[\"CUSTOM\"] = \"CUSTOM\";\n\tPropertyType[\"COLOR\"] = \"COLOR\";\n\treturn PropertyType;\n}({});\n\n//#endregion\n//#region upstream/framework/lib/property/input/text-property.ts\nconst ShortTextProperty = z.object({\n\t...BasePropertySchema.shape,\n\t...TPropertyValue(z.string(), \"SHORT_TEXT\").shape\n});\nconst LongTextProperty = z.object({\n\t...BasePropertySchema.shape,\n\t...TPropertyValue(z.string(), \"LONG_TEXT\").shape\n});\n\n//#endregion\n//#region upstream/framework/lib/property/input/dropdown/common.ts\nconst DropdownOption = z.object({\n\tlabel: z.string(),\n\tvalue: z.unknown(),\n\tdescription: z.optional(z.string()),\n\ticon: z.optional(z.string())\n});\nconst DropdownState = z.object({\n\tdisabled: z.optional(z.boolean()),\n\tplaceholder: z.optional(z.string()),\n\toptions: z.array(DropdownOption)\n});\n\n//#endregion\n//#region upstream/framework/lib/property/input/dropdown/static-dropdown.ts\nconst StaticDropdownDisplay = z.enum([\"cards\"]);\nconst StaticDropdownProperty = z.object({\n\t...BasePropertySchema.shape,\n\toptions: DropdownState,\n\tdisplay: z.optional(StaticDropdownDisplay),\n\t...TPropertyValue(z.unknown(), \"STATIC_DROPDOWN\").shape\n});\nconst StaticMultiSelectDropdownProperty = z.object({\n\t...BasePropertySchema.shape,\n\toptions: DropdownState,\n\t...TPropertyValue(z.array(z.unknown()), \"STATIC_MULTI_SELECT_DROPDOWN\").shape\n});\n\n//#endregion\n//#region upstream/framework/lib/property/input/checkbox-property.ts\nconst CheckboxProperty = z.object({\n\t...BasePropertySchema.shape,\n\treveals: z.optional(z.array(z.string())),\n\t...TPropertyValue(z.boolean(), \"CHECKBOX\").shape\n});\n\n//#endregion\n//#region upstream/framework/lib/property/input/number-property.ts\nconst NumberProperty = z.object({\n\t...BasePropertySchema.shape,\n\tdisplay: z.optional(z.enum([\"stepper\"])),\n\tmin: z.optional(z.number()),\n\tmax: z.optional(z.number()),\n\tstep: z.optional(z.number()),\n\t...TPropertyValue(z.number(), \"NUMBER\").shape\n});\n\n//#endregion\n//#region upstream/framework/lib/property/input/file-property.ts\nvar ApFile = class {\n\tfilename;\n\tdata;\n\textension;\n\tconstructor(filename, data, extension) {\n\t\tthis.filename = filename;\n\t\tthis.data = data;\n\t\tthis.extension = extension;\n\t}\n\tget base64() {\n\t\treturn this.data.toString(\"base64\");\n\t}\n};\nconst FileProperty = z.object({\n\t...BasePropertySchema.shape,\n\tstreaming: z.optional(z.boolean()),\n\t...TPropertyValue(z.unknown(), \"FILE\").shape\n});\n\n//#endregion\n//#region upstream/framework/lib/property/input/date-range-property.ts\nconst DateRangePreset = z.enum([\n\t\"any_time\",\n\t\"last_24_hours\",\n\t\"last_7_days\",\n\t\"last_30_days\",\n\t\"last_90_days\",\n\t\"this_month\",\n\t\"custom\"\n]);\nconst DateRangeValue = z.object({\n\tpreset: z.optional(DateRangePreset),\n\tafter: z.optional(z.string()),\n\tbefore: z.optional(z.string())\n});\nconst DateRangeProperty = z.object({\n\t...BasePropertySchema.shape,\n\tdisplay: z.optional(z.enum([\"dropdown\"])),\n\t...TPropertyValue(DateRangeValue, \"DATE_RANGE\").shape\n});\nfunction isoDaysAgo(days) {\n\treturn (/* @__PURE__ */ new Date(Date.now() - days * 24 * 60 * 60 * 1e3)).toISOString();\n}\nfunction startOfThisMonth() {\n\tconst now = /* @__PURE__ */ new Date();\n\treturn new Date(now.getFullYear(), now.getMonth(), 1).toISOString();\n}\nfunction resolve(value) {\n\tif (!value || !value.preset || value.preset === \"any_time\") return {};\n\tswitch (value.preset) {\n\t\tcase \"last_24_hours\": return { after: isoDaysAgo(1) };\n\t\tcase \"last_7_days\": return { after: isoDaysAgo(7) };\n\t\tcase \"last_30_days\": return { after: isoDaysAgo(30) };\n\t\tcase \"last_90_days\": return { after: isoDaysAgo(90) };\n\t\tcase \"this_month\": return { after: startOfThisMonth() };\n\t\tcase \"custom\": return {\n\t\t\tafter: value.after && value.after.length > 0 ? value.after : void 0,\n\t\t\tbefore: value.before && value.before.length > 0 ? value.before : void 0\n\t\t};\n\t\tdefault: return {};\n\t}\n}\nconst dateRangeUtils = { resolve };\n\n//#endregion\n//#region upstream/core-piece-types/lib/markdown.ts\nlet MarkdownVariant = /* @__PURE__ */ function(MarkdownVariant) {\n\tMarkdownVariant[\"BORDERLESS\"] = \"BORDERLESS\";\n\tMarkdownVariant[\"INFO\"] = \"INFO\";\n\tMarkdownVariant[\"WARNING\"] = \"WARNING\";\n\tMarkdownVariant[\"TIP\"] = \"TIP\";\n\treturn MarkdownVariant;\n}({});\n\n//#endregion\n//#region upstream/core-utils/lib/utils.ts\nfunction isString(str) {\n\treturn str != null && typeof str === \"string\";\n}\nfunction isNil(value) {\n\treturn value === null || value === void 0;\n}\nfunction kebabCase(str) {\n\treturn str.replace(/([a-z])([A-Z])/g, \"$1-$2\").replace(/\\s+/g, \"-\").replace(/_/g, \"-\").toLowerCase().replace(/^-+|-+$/g, \"\");\n}\nfunction isEmpty(value) {\n\tif (value == null) return true;\n\tif (typeof value === \"string\" || Array.isArray(value)) return value.length === 0;\n\tif (typeof value === \"object\") return Object.keys(value).length === 0;\n\treturn false;\n}\nfunction startCase(str) {\n\treturn str.replace(/([a-z])([A-Z])/g, \"$1 $2\").replace(/[_-]+/g, \" \").replace(/\\s+/g, \" \").replace(/^[a-z]/, (match) => match.toUpperCase()).replace(/\\b[a-z]/g, (match) => match.toUpperCase());\n}\nfunction camelCase(str) {\n\treturn str.replace(/([-_][a-z])/g, (group) => group.toUpperCase().replace(\"-\", \"\").replace(\"_\", \"\"));\n}\nfunction parseToJsonIfPossible(str) {\n\ttry {\n\t\treturn JSON.parse(str);\n\t} catch (e) {\n\t\treturn str;\n\t}\n}\nfunction pickBy(object, predicate) {\n\treturn Object.keys(object).reduce((result, key) => {\n\t\tif (predicate(object[key], key)) result[key] = object[key];\n\t\treturn result;\n\t}, {});\n}\nfunction chunk(records, size) {\n\tconst chunks = [];\n\tfor (let i = 0; i < records.length; i += size) chunks.push(records.slice(i, i + size));\n\treturn chunks;\n}\nfunction unique(array) {\n\tconst seen = /* @__PURE__ */ new Set();\n\treturn array.filter((item) => {\n\t\tconst key = JSON.stringify(item);\n\t\tif (seen.has(key)) return false;\n\t\tseen.add(key);\n\t\treturn true;\n\t});\n}\nconst INVALID_BASE64_CHARS = /[^A-Za-z0-9+/=]/;\nfunction isBase64(value, options) {\n\tif (!isString(value) || value.length === 0) return false;\n\tif (options?.allowMime) {\n\t\tconst base64MarkerIndex = value.indexOf(\";base64,\");\n\t\tif (base64MarkerIndex !== -1 && value.startsWith(\"data:\")) return _isValidBase64String(value.slice(base64MarkerIndex + 8));\n\t}\n\treturn _isValidBase64String(value);\n}\nfunction _isValidBase64String(str) {\n\tconst len = str.length;\n\tif (len === 0 || len % 4 !== 0 || INVALID_BASE64_CHARS.test(str)) return false;\n\tconst firstPaddingIndex = str.indexOf(\"=\");\n\treturn firstPaddingIndex === -1 || firstPaddingIndex === len - 1 || firstPaddingIndex === len - 2 && str[len - 1] === \"=\";\n}\n\n//#endregion\n//#region upstream/core-utils/lib/try-catch.ts\nasync function tryCatch(fn) {\n\ttry {\n\t\treturn {\n\t\t\tdata: await fn(),\n\t\t\terror: null\n\t\t};\n\t} catch (error) {\n\t\treturn {\n\t\t\tdata: null,\n\t\t\terror\n\t\t};\n\t}\n}\nfunction tryCatchSync(fn) {\n\ttry {\n\t\treturn {\n\t\t\tdata: fn(),\n\t\t\terror: null\n\t\t};\n\t} catch (error) {\n\t\treturn {\n\t\t\tdata: null,\n\t\t\terror\n\t\t};\n\t}\n}\n\n//#endregion\n//#region upstream/framework/lib/property/input/markdown-property.ts\nconst MarkDownProperty = z.object({\n\t...BasePropertySchema.shape,\n\t...TPropertyValue(z.void(), \"MARKDOWN\").shape,\n\tvariant: z.optional(z.enum(MarkdownVariant))\n});\n\n//#endregion\nexport { PropertyType as A, CheckboxProperty as C, DropdownState as D, DropdownOption as E, TPropertyValue as M, LongTextProperty as O, NumberProperty as S, StaticMultiSelectDropdownProperty as T, DateRangeProperty as _, chunk as a, ApFile as b, isNil as c, parseToJsonIfPossible as d, pickBy as f, DateRangePreset as g, MarkdownVariant as h, camelCase as i, BasePropertySchema as j, ShortTextProperty as k, isString as l, unique as m, tryCatch as n, isBase64 as o, startCase as p, tryCatchSync as r, isEmpty as s, MarkDownProperty as t, kebabCase as u, DateRangeValue as v, StaticDropdownProperty as w, FileProperty as x, dateRangeUtils as y };\n//# sourceMappingURL=markdown-property-DMfHjEiL.js.map","import { A as PropertyType, C as CheckboxProperty, M as TPropertyValue, O as LongTextProperty, S as NumberProperty, T as StaticMultiSelectDropdownProperty, _ as DateRangeProperty, h as MarkdownVariant, j as BasePropertySchema, k as ShortTextProperty, t as MarkDownProperty, w as StaticDropdownProperty, x as FileProperty } from \"./markdown-property-DMfHjEiL.js\";\nimport * as z from \"zod/mini\";\n\n//#region upstream/framework/lib/action/action.ts\nconst ErrorHandlingOptionsParam = z.object({\n\tretryOnFailure: z.object({\n\t\tdefaultValue: z.optional(z.boolean()),\n\t\thide: z.optional(z.boolean())\n\t}),\n\tcontinueOnFailure: z.object({\n\t\tdefaultValue: z.optional(z.boolean()),\n\t\thide: z.optional(z.boolean())\n\t})\n});\nvar IAction = class {\n\tname;\n\tdisplayName;\n\tdescription;\n\tprops;\n\tpropertyGroups;\n\trun;\n\ttest;\n\trequireAuth;\n\terrorHandlingOptions;\n\toutputSchema;\n\taudience;\n\taiMetadata;\n\tclassification;\n\tconstructor(name, displayName, description, props, propertyGroups, run, test, requireAuth, errorHandlingOptions, outputSchema, audience, aiMetadata, classification) {\n\t\tthis.name = name;\n\t\tthis.displayName = displayName;\n\t\tthis.description = description;\n\t\tthis.props = props;\n\t\tthis.propertyGroups = propertyGroups;\n\t\tthis.run = run;\n\t\tthis.test = test;\n\t\tthis.requireAuth = requireAuth;\n\t\tthis.errorHandlingOptions = errorHandlingOptions;\n\t\tthis.outputSchema = outputSchema;\n\t\tthis.audience = audience;\n\t\tthis.aiMetadata = aiMetadata;\n\t\tthis.classification = classification;\n\t}\n};\nconst createAction = (params) => {\n\treturn new IAction(params.name, params.displayName, params.description, params.props, params.propertyGroups, params.run, params.test ?? params.run, params.requireAuth ?? true, params.errorHandlingOptions ?? {\n\t\tcontinueOnFailure: { defaultValue: false },\n\t\tretryOnFailure: { defaultValue: false }\n\t}, params.outputSchema, params.audience, params.aiMetadata, params.classification);\n};\n\n//#endregion\n//#region upstream/framework/lib/property/input/dropdown/dropdown-prop.ts\nconst DropdownProperty = z.object({\n\t...BasePropertySchema.shape,\n\t...TPropertyValue(z.unknown(), \"DROPDOWN\").shape,\n\trefreshers: z.array(z.string())\n});\nconst MultiSelectDropdownProperty = z.object({\n\t...BasePropertySchema.shape,\n\t...TPropertyValue(z.array(z.unknown()), \"MULTI_SELECT_DROPDOWN\").shape,\n\trefreshers: z.array(z.string())\n});\n\n//#endregion\n//#region upstream/framework/lib/property/input/json-property.ts\nconst JsonProperty = z.object({\n\t...BasePropertySchema.shape,\n\t...TPropertyValue(z.union([z.record(z.string(), z.unknown())]), \"JSON\").shape\n});\n\n//#endregion\n//#region upstream/framework/lib/property/input/color-property.ts\nconst ColorProperty = z.object({\n\t...BasePropertySchema.shape,\n\t...TPropertyValue(z.string(), \"COLOR\").shape\n});\n\n//#endregion\n//#region upstream/framework/lib/property/input/date-time-property.ts\nconst DateTimeProperty = z.object({\n\t...BasePropertySchema.shape,\n\t...TPropertyValue(z.string(), \"DATE_TIME\").shape\n});\n\n//#endregion\n//#region upstream/framework/lib/property/input/array-property.ts\nconst ArraySubProps = z.record(z.string(), z.union([\n\tShortTextProperty,\n\tLongTextProperty,\n\tStaticDropdownProperty,\n\tMultiSelectDropdownProperty,\n\tStaticMultiSelectDropdownProperty,\n\tCheckboxProperty,\n\tNumberProperty,\n\tFileProperty,\n\tJsonProperty,\n\tColorProperty,\n\tDateTimeProperty\n]));\nconst ArrayProperty = z.object({\n\t...BasePropertySchema.shape,\n\tproperties: z.optional(ArraySubProps),\n\t...TPropertyValue(z.array(z.unknown()), \"ARRAY\").shape\n});\n\n//#endregion\n//#region upstream/framework/lib/property/input/dynamic-prop.ts\nconst DynamicProp = z.union([\n\tShortTextProperty,\n\tStaticDropdownProperty,\n\tJsonProperty,\n\tArrayProperty,\n\tStaticMultiSelectDropdownProperty\n]);\nconst DynamicPropsValue = z.record(z.string(), DynamicProp);\nconst DynamicProperties = z.object({\n\trefreshers: z.array(z.string()),\n\t...BasePropertySchema.shape,\n\t...TPropertyValue(z.unknown(), \"DYNAMIC\").shape\n});\n\n//#endregion\n//#region upstream/core-utils/lib/assertions.ts\nfunction assertNotNullOrUndefined(value, fieldName) {\n\tif (value === null || value === void 0) throw new Error(`${fieldName} is null or undefined`);\n}\nconst isNotUndefined = (value) => {\n\treturn value !== void 0;\n};\n\n//#endregion\n//#region upstream/framework/lib/property/input/object-property.ts\nconst ObjectProperty = z.object({\n\t...BasePropertySchema.shape,\n\t...TPropertyValue(z.record(z.string(), z.unknown()), \"OBJECT\").shape\n});\n\n//#endregion\n//#region upstream/framework/lib/property/input/rich-text-property.ts\nconst RichTextProperty = z.object({\n\t...BasePropertySchema.shape,\n\tformatProperty: z.optional(z.string()),\n\t...TPropertyValue(z.string(), \"RICH_TEXT\").shape\n});\n\n//#endregion\n//#region upstream/framework/lib/property/input/custom-property.ts\nconst CustomProperty = z.object({\n\t...BasePropertySchema.shape,\n\t...TPropertyValue(z.unknown(), \"CUSTOM\").shape,\n\tcode: z.string()\n});\n\n//#endregion\n//#region upstream/framework/lib/property/input/index.ts\nconst InputProperty = z.union([\n\tShortTextProperty,\n\tLongTextProperty,\n\tRichTextProperty,\n\tMarkDownProperty,\n\tCheckboxProperty,\n\tStaticDropdownProperty,\n\tStaticMultiSelectDropdownProperty,\n\tDropdownProperty,\n\tMultiSelectDropdownProperty,\n\tDynamicProperties,\n\tNumberProperty,\n\tArrayProperty,\n\tObjectProperty,\n\tJsonProperty,\n\tDateTimeProperty,\n\tDateRangeProperty,\n\tFileProperty,\n\tCustomProperty,\n\tColorProperty\n]);\nconst Property = {\n\tShortText(request) {\n\t\treturn {\n\t\t\t...request,\n\t\t\tvalueSchema: void 0,\n\t\t\ttype: \"SHORT_TEXT\"\n\t\t};\n\t},\n\tCheckbox(request) {\n\t\treturn {\n\t\t\t...request,\n\t\t\tvalueSchema: void 0,\n\t\t\ttype: \"CHECKBOX\"\n\t\t};\n\t},\n\tLongText(request) {\n\t\treturn {\n\t\t\t...request,\n\t\t\tvalueSchema: void 0,\n\t\t\ttype: \"LONG_TEXT\"\n\t\t};\n\t},\n\tRichText(request) {\n\t\treturn {\n\t\t\t...request,\n\t\t\tvalueSchema: void 0,\n\t\t\ttype: \"RICH_TEXT\"\n\t\t};\n\t},\n\tMarkDown(request) {\n\t\treturn {\n\t\t\tdisplayName: \"Markdown\",\n\t\t\trequired: false,\n\t\t\tdescription: request.value,\n\t\t\ttype: \"MARKDOWN\",\n\t\t\tvalueSchema: void 0,\n\t\t\tvariant: request.variant ?? \"INFO\"\n\t\t};\n\t},\n\tNumber(request) {\n\t\treturn {\n\t\t\t...request,\n\t\t\tvalueSchema: void 0,\n\t\t\ttype: \"NUMBER\"\n\t\t};\n\t},\n\tJson(request) {\n\t\treturn {\n\t\t\t...request,\n\t\t\tvalueSchema: void 0,\n\t\t\ttype: \"JSON\"\n\t\t};\n\t},\n\tArray(request) {\n\t\treturn {\n\t\t\t...request,\n\t\t\tvalueSchema: void 0,\n\t\t\ttype: \"ARRAY\"\n\t\t};\n\t},\n\tObject(request) {\n\t\treturn {\n\t\t\t...request,\n\t\t\tvalueSchema: void 0,\n\t\t\ttype: \"OBJECT\"\n\t\t};\n\t},\n\tDropdown(request) {\n\t\treturn {\n\t\t\t...request,\n\t\t\tvalueSchema: void 0,\n\t\t\ttype: \"DROPDOWN\"\n\t\t};\n\t},\n\tStaticDropdown(request) {\n\t\treturn {\n\t\t\t...request,\n\t\t\tvalueSchema: void 0,\n\t\t\ttype: \"STATIC_DROPDOWN\"\n\t\t};\n\t},\n\tMultiSelectDropdown(request) {\n\t\treturn {\n\t\t\t...request,\n\t\t\tvalueSchema: void 0,\n\t\t\ttype: \"MULTI_SELECT_DROPDOWN\"\n\t\t};\n\t},\n\tDynamicProperties(request) {\n\t\treturn {\n\t\t\t...request,\n\t\t\tvalueSchema: void 0,\n\t\t\ttype: \"DYNAMIC\"\n\t\t};\n\t},\n\tStaticMultiSelectDropdown(request) {\n\t\treturn {\n\t\t\t...request,\n\t\t\tvalueSchema: void 0,\n\t\t\ttype: \"STATIC_MULTI_SELECT_DROPDOWN\"\n\t\t};\n\t},\n\tDateTime(request) {\n\t\treturn {\n\t\t\t...request,\n\t\t\tvalueSchema: void 0,\n\t\t\ttype: \"DATE_TIME\"\n\t\t};\n\t},\n\tDateRange(request) {\n\t\treturn {\n\t\t\t...request,\n\t\t\tvalueSchema: void 0,\n\t\t\ttype: \"DATE_RANGE\"\n\t\t};\n\t},\n\tFile(request) {\n\t\treturn {\n\t\t\t...request,\n\t\t\tvalueSchema: void 0,\n\t\t\ttype: \"FILE\"\n\t\t};\n\t},\n\tCustom(request) {\n\t\tconst code = request.code.toString();\n\t\treturn {\n\t\t\t...request,\n\t\t\tcode,\n\t\t\tvalueSchema: void 0,\n\t\t\ttype: \"CUSTOM\"\n\t\t};\n\t},\n\tColor(request) {\n\t\treturn {\n\t\t\t...request,\n\t\t\tvalueSchema: void 0,\n\t\t\ttype: \"COLOR\"\n\t\t};\n\t}\n};\n\n//#endregion\nexport { ErrorHandlingOptionsParam as _, ObjectProperty as a, DynamicProp as c, ArrayProperty as d, ArraySubProps as f, MultiSelectDropdownProperty as g, DropdownProperty as h, RichTextProperty as i, DynamicProperties as l, JsonProperty as m, Property as n, assertNotNullOrUndefined as o, DateTimeProperty as p, CustomProperty as r, isNotUndefined as s, InputProperty as t, DynamicPropsValue as u, IAction as v, createAction as y };\n//# sourceMappingURL=input-BHkj_oP5.js.map","import { A as PropertyType, C as CheckboxProperty, M as TPropertyValue, O as LongTextProperty, S as NumberProperty, T as StaticMultiSelectDropdownProperty, c as isNil, k as ShortTextProperty, t as MarkDownProperty, w as StaticDropdownProperty } from \"./markdown-property-DMfHjEiL.js\";\nimport * as z from \"zod/mini\";\n\n//#region upstream/core-piece-types/lib/app-connection.ts\nlet AppConnectionType = /* @__PURE__ */ function(AppConnectionType) {\n\tAppConnectionType[\"OAUTH2\"] = \"OAUTH2\";\n\tAppConnectionType[\"PLATFORM_OAUTH2\"] = \"PLATFORM_OAUTH2\";\n\tAppConnectionType[\"CLOUD_OAUTH2\"] = \"CLOUD_OAUTH2\";\n\tAppConnectionType[\"SECRET_TEXT\"] = \"SECRET_TEXT\";\n\tAppConnectionType[\"BASIC_AUTH\"] = \"BASIC_AUTH\";\n\tAppConnectionType[\"CUSTOM_AUTH\"] = \"CUSTOM_AUTH\";\n\tAppConnectionType[\"OIDC\"] = \"OIDC\";\n\tAppConnectionType[\"NO_AUTH\"] = \"NO_AUTH\";\n\treturn AppConnectionType;\n}({});\nlet OAuth2GrantType = /* @__PURE__ */ function(OAuth2GrantType) {\n\tOAuth2GrantType[\"AUTHORIZATION_CODE\"] = \"authorization_code\";\n\tOAuth2GrantType[\"CLIENT_CREDENTIALS\"] = \"client_credentials\";\n\treturn OAuth2GrantType;\n}({});\nconst BOTH_CLIENT_CREDENTIALS_AND_AUTHORIZATION_CODE = \"both_client_credentials_and_authorization_code\";\n\n//#endregion\n//#region upstream/core-piece-types/lib/trigger.ts\nlet TriggerStrategy = /* @__PURE__ */ function(TriggerStrategy) {\n\tTriggerStrategy[\"POLLING\"] = \"POLLING\";\n\tTriggerStrategy[\"WEBHOOK\"] = \"WEBHOOK\";\n\tTriggerStrategy[\"APP_WEBHOOK\"] = \"APP_WEBHOOK\";\n\tTriggerStrategy[\"MANUAL\"] = \"MANUAL\";\n\treturn TriggerStrategy;\n}({});\nlet WebhookHandshakeStrategy = /* @__PURE__ */ function(WebhookHandshakeStrategy) {\n\tWebhookHandshakeStrategy[\"NONE\"] = \"NONE\";\n\tWebhookHandshakeStrategy[\"HEADER_PRESENT\"] = \"HEADER_PRESENT\";\n\tWebhookHandshakeStrategy[\"QUERY_PRESENT\"] = \"QUERY_PRESENT\";\n\tWebhookHandshakeStrategy[\"BODY_PARAM_PRESENT\"] = \"BODY_PARAM_PRESENT\";\n\tWebhookHandshakeStrategy[\"HEAD_REQUEST\"] = \"HEAD_REQUEST\";\n\treturn WebhookHandshakeStrategy;\n}({});\nconst WebhookHandshakeConfiguration = z.object({\n\tstrategy: z.enum(WebhookHandshakeStrategy),\n\tparamName: z.optional(z.string())\n});\nlet TriggerTestStrategy = /* @__PURE__ */ function(TriggerTestStrategy) {\n\tTriggerTestStrategy[\"SIMULATION\"] = \"SIMULATION\";\n\tTriggerTestStrategy[\"TEST_FUNCTION\"] = \"TEST_FUNCTION\";\n\treturn TriggerTestStrategy;\n}({});\nconst AUTHENTICATION_PROPERTY_NAME = \"auth\";\n\n//#endregion\n//#region upstream/core-utils/lib/object-utils.ts\nconst spreadIfDefined = (key, value) => {\n\tif (isNil(value)) return {};\n\treturn { [key]: value };\n};\nconst isObject = (obj) => {\n\treturn typeof obj === \"object\" && obj !== null && !Array.isArray(obj);\n};\n\n//#endregion\n//#region upstream/framework/lib/property/authentication/common.ts\nconst BasePieceAuthSchema = z.object({\n\tdisplayName: z.string(),\n\tdescription: z.optional(z.string()),\n\thasConnectionIdentifier: z.optional(z.boolean())\n});\n\n//#endregion\n//#region upstream/framework/lib/property/authentication/basic-auth-prop.ts\nconst BasicAuthPropertyValue = z.object({\n\tusername: z.string(),\n\tpassword: z.string()\n});\nconst BasicAuthProperty = z.object({\n\t...BasePieceAuthSchema.shape,\n\tusername: z.object({\n\t\tdisplayName: z.string(),\n\t\tdescription: z.optional(z.string())\n\t}),\n\tpassword: z.object({\n\t\tdisplayName: z.string(),\n\t\tdescription: z.optional(z.string())\n\t}),\n\t...TPropertyValue(BasicAuthPropertyValue, \"BASIC_AUTH\").shape\n});\n\n//#endregion\n//#region upstream/framework/lib/property/authentication/secret-text-property.ts\nconst SecretTextProperty = z.object({\n\t...BasePieceAuthSchema.shape,\n\t...TPropertyValue(z.object({ auth: z.string() }), \"SECRET_TEXT\").shape\n});\n\n//#endregion\n//#region upstream/framework/lib/property/authentication/custom-auth-prop.ts\nconst CustomAuthProps = z.record(z.string(), z.union([\n\tShortTextProperty,\n\tLongTextProperty,\n\tSecretTextProperty,\n\tNumberProperty,\n\tStaticDropdownProperty,\n\tCheckboxProperty,\n\tMarkDownProperty,\n\tStaticMultiSelectDropdownProperty\n]));\nconst CustomAuthProperty = z.object({\n\t...BasePieceAuthSchema.shape,\n\tprops: CustomAuthProps,\n\t...TPropertyValue(z.unknown(), \"CUSTOM_AUTH\").shape\n});\n\n//#endregion\n//#region upstream/framework/lib/property/authentication/oidc-prop.ts\nconst OIDCAuthProps = z.record(z.string(), z.union([\n\tShortTextProperty,\n\tLongTextProperty,\n\tSecretTextProperty,\n\tNumberProperty,\n\tCheckboxProperty,\n\tStaticDropdownProperty,\n\tStaticMultiSelectDropdownProperty,\n\tMarkDownProperty\n]));\nconst OIDCProperty = z.object({\n\t...BasePieceAuthSchema.shape,\n\tprops: OIDCAuthProps,\n\t...TPropertyValue(z.unknown(), \"OIDC\").shape\n});\n\n//#endregion\n//#region upstream/framework/lib/property/authentication/oauth2-prop.ts\nlet OAuth2AuthorizationMethod = /* @__PURE__ */ function(OAuth2AuthorizationMethod) {\n\tOAuth2AuthorizationMethod[\"HEADER\"] = \"HEADER\";\n\tOAuth2AuthorizationMethod[\"BODY\"] = \"BODY\";\n\treturn OAuth2AuthorizationMethod;\n}({});\nconst OAuthProp = z.union([\n\tShortTextProperty,\n\tSecretTextProperty,\n\tStaticDropdownProperty\n]);\nconst OAuth2Props = z.record(z.string(), OAuthProp);\nconst OAuth2ExtraProps = z.object({\n\tprops: z.optional(z.record(z.string(), OAuthProp)),\n\tauthUrl: z.string(),\n\ttokenUrl: z.string(),\n\tscope: z.array(z.string()),\n\tprompt: z.optional(z.union([\n\t\tz.literal(\"none\"),\n\t\tz.literal(\"consent\"),\n\t\tz.literal(\"login\"),\n\t\tz.literal(\"omit\")\n\t])),\n\tpkce: z.optional(z.boolean()),\n\tpkceMethod: z.optional(z.union([z.literal(\"plain\"), z.literal(\"S256\")])),\n\tauthorizationMethod: z.optional(z.enum(OAuth2AuthorizationMethod)),\n\tgrantType: z.optional(z.union([z.enum(OAuth2GrantType), z.literal(BOTH_CLIENT_CREDENTIALS_AND_AUTHORIZATION_CODE)])),\n\textra: z.optional(z.record(z.string(), z.string()))\n});\nconst OAuth2PropertyValue = z.object({\n\taccess_token: z.string(),\n\tprops: z.optional(OAuth2Props),\n\tdata: z.record(z.string(), z.any())\n});\nconst OAuth2Property = z.object({\n\t...BasePieceAuthSchema.shape,\n\t...OAuth2ExtraProps.shape,\n\t...TPropertyValue(OAuth2PropertyValue, \"OAUTH2\").shape\n});\n\n//#endregion\n//#region upstream/framework/lib/property/authentication/index.ts\nconst PieceAuthProperty = z.union([\n\tBasicAuthProperty,\n\tCustomAuthProperty,\n\tOIDCProperty,\n\tOAuth2Property,\n\tSecretTextProperty\n]);\nconst DEFAULT_CONNECTION_DISPLAY_NAME = \"Connection\";\nconst PieceAuth = {\n\tSecretText(request) {\n\t\treturn {\n\t\t\t...request,\n\t\t\tvalueSchema: void 0,\n\t\t\ttype: \"SECRET_TEXT\"\n\t\t};\n\t},\n\tOAuth2(request) {\n\t\treturn {\n\t\t\t...request,\n\t\t\tvalueSchema: void 0,\n\t\t\ttype: \"OAUTH2\",\n\t\t\tdisplayName: request.displayName || \"Connection\"\n\t\t};\n\t},\n\tBasicAuth(request) {\n\t\treturn {\n\t\t\t...request,\n\t\t\tvalueSchema: void 0,\n\t\t\ttype: \"BASIC_AUTH\",\n\t\t\tdisplayName: request.displayName || \"Connection\",\n\t\t\trequired: true\n\t\t};\n\t},\n\tCustomAuth(request) {\n\t\treturn {\n\t\t\t...request,\n\t\t\tvalueSchema: void 0,\n\t\t\ttype: \"CUSTOM_AUTH\",\n\t\t\tdisplayName: request.displayName || \"Connection\"\n\t\t};\n\t},\n\tOIDC(request) {\n\t\treturn {\n\t\t\t...request,\n\t\t\tvalueSchema: void 0,\n\t\t\ttype: \"OIDC\",\n\t\t\tdisplayName: request.displayName || \"Connection\"\n\t\t};\n\t},\n\tNone() {}\n};\nfunction getAuthPropertyForValue({ authValueType, pieceAuth }) {\n\tif (!Array.isArray(pieceAuth) || isNil(pieceAuth)) return pieceAuth;\n\treturn pieceAuth.find((auth) => authConnectionTypeToPropertyType[authValueType] === auth.type) ?? pieceAuth.at(0);\n}\nconst authConnectionTypeToPropertyType = {\n\t[\"OAUTH2\"]: \"OAUTH2\",\n\t[\"CLOUD_OAUTH2\"]: \"OAUTH2\",\n\t[\"PLATFORM_OAUTH2\"]: \"OAUTH2\",\n\t[\"BASIC_AUTH\"]: \"BASIC_AUTH\",\n\t[\"CUSTOM_AUTH\"]: \"CUSTOM_AUTH\",\n\t[\"OIDC\"]: \"OIDC\",\n\t[\"SECRET_TEXT\"]: \"SECRET_TEXT\",\n\t[\"NO_AUTH\"]: void 0\n};\n\n//#endregion\nexport { TriggerStrategy as _, OAuth2AuthorizationMethod as a, AppConnectionType as b, OAuth2Props as c, SecretTextProperty as d, BasicAuthProperty as f, AUTHENTICATION_PROPERTY_NAME as g, spreadIfDefined as h, getAuthPropertyForValue as i, OIDCProperty as l, isObject as m, PieceAuth as n, OAuth2Property as o, BasicAuthPropertyValue as p, PieceAuthProperty as r, OAuth2PropertyValue as s, DEFAULT_CONNECTION_DISPLAY_NAME as t, CustomAuthProperty as u, TriggerTestStrategy as v, OAuth2GrantType as x, WebhookHandshakeStrategy as y };\n//# sourceMappingURL=authentication-o-4CdAPR.js.map","import crypto from 'crypto'\n\nimport { urlAlphabet } from './url-alphabet/index.js'\n\nconst POOL_SIZE_MULTIPLIER = 128\nlet pool, poolOffset\n\nlet fillPool = bytes => {\n if (bytes < 0) throw new RangeError('Wrong ID size')\n try {\n if (!pool || pool.length < bytes) {\n pool = Buffer.allocUnsafe(bytes * POOL_SIZE_MULTIPLIER)\n crypto.randomFillSync(pool)\n poolOffset = 0\n } else if (poolOffset + bytes > pool.length) {\n crypto.randomFillSync(pool)\n poolOffset = 0\n }\n } catch (e) {\n pool = undefined\n throw e\n }\n poolOffset += bytes\n}\n\nlet random = bytes => {\n fillPool((bytes |= 0))\n return pool.subarray(poolOffset - bytes, poolOffset)\n}\n\nlet customRandom = (alphabet, defaultSize, getRandom) => {\n let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1\n\n\n let step = Math.ceil((1.6 * mask * defaultSize) / alphabet.length)\n\n return (size = defaultSize) => {\n if (size <= 0) return ''\n let id = ''\n while (true) {\n let bytes = getRandom(step)\n let i = step\n while (i--) {\n id += alphabet[bytes[i] & mask] || ''\n if (id.length === size) return id\n }\n }\n }\n}\n\nlet customAlphabet = (alphabet, size = 21) =>\n customRandom(alphabet, size, random)\n\nlet nanoid = (size = 21) => {\n fillPool((size |= 0))\n let id = ''\n for (let i = poolOffset - size; i < poolOffset; i++) {\n id += urlAlphabet[pool[i] & 63]\n }\n return id\n}\n\nexport { nanoid, customAlphabet, customRandom, urlAlphabet, random }\n","import { _ as ErrorHandlingOptionsParam, a as ObjectProperty, c as DynamicProp, d as ArrayProperty, f as ArraySubProps, g as MultiSelectDropdownProperty, h as DropdownProperty, i as RichTextProperty, l as DynamicProperties, m as JsonProperty, n as Property$1, o as assertNotNullOrUndefined, p as DateTimeProperty, r as CustomProperty, s as isNotUndefined, t as InputProperty, u as DynamicPropsValue, v as IAction, y as createAction$1 } from \"./input-BHkj_oP5.js\";\nimport { A as PropertyType, C as CheckboxProperty, D as DropdownState, E as DropdownOption, O as LongTextProperty, S as NumberProperty, T as StaticMultiSelectDropdownProperty, _ as DateRangeProperty, a as chunk, b as ApFile, c as isNil, f as pickBy, g as DateRangePreset, h as MarkdownVariant, i as camelCase, j as BasePropertySchema, k as ShortTextProperty, l as isString, m as unique, n as tryCatch, p as startCase, s as isEmpty, u as kebabCase, v as DateRangeValue, w as StaticDropdownProperty, x as FileProperty, y as dateRangeUtils } from \"./markdown-property-DMfHjEiL.js\";\nimport { _ as TriggerStrategy, a as OAuth2AuthorizationMethod, b as AppConnectionType, c as OAuth2Props, d as SecretTextProperty, f as BasicAuthProperty, g as AUTHENTICATION_PROPERTY_NAME, h as spreadIfDefined, i as getAuthPropertyForValue, l as OIDCProperty, n as PieceAuth, o as OAuth2Property, p as BasicAuthPropertyValue, r as PieceAuthProperty, s as OAuth2PropertyValue, t as DEFAULT_CONNECTION_DISPLAY_NAME, u as CustomAuthProperty, v as TriggerTestStrategy, x as OAuth2GrantType, y as WebhookHandshakeStrategy } from \"./authentication-o-4CdAPR.js\";\nimport * as z from \"zod/mini\";\nimport { customAlphabet } from \"nanoid\";\nimport path from \"node:path\";\nimport fs from \"node:fs/promises\";\n\n//#region upstream/core-piece-types/lib/piece.ts\nlet PackageType = /* @__PURE__ */ function(PackageType) {\n\tPackageType[\"ARCHIVE\"] = \"ARCHIVE\";\n\tPackageType[\"REGISTRY\"] = \"REGISTRY\";\n\treturn PackageType;\n}({});\nlet PieceType = /* @__PURE__ */ function(PieceType) {\n\tPieceType[\"CUSTOM\"] = \"CUSTOM\";\n\tPieceType[\"OFFICIAL\"] = \"OFFICIAL\";\n\treturn PieceType;\n}({});\nlet PieceCategory = /* @__PURE__ */ function(PieceCategory) {\n\tPieceCategory[\"ARTIFICIAL_INTELLIGENCE\"] = \"ARTIFICIAL_INTELLIGENCE\";\n\tPieceCategory[\"COMMUNICATION\"] = \"COMMUNICATION\";\n\tPieceCategory[\"COMMERCE\"] = \"COMMERCE\";\n\tPieceCategory[\"CORE\"] = \"CORE\";\n\tPieceCategory[\"UNIVERSAL_AI\"] = \"UNIVERSAL_AI\";\n\tPieceCategory[\"FLOW_CONTROL\"] = \"FLOW_CONTROL\";\n\tPieceCategory[\"BUSINESS_INTELLIGENCE\"] = \"BUSINESS_INTELLIGENCE\";\n\tPieceCategory[\"ACCOUNTING\"] = \"ACCOUNTING\";\n\tPieceCategory[\"PRODUCTIVITY\"] = \"PRODUCTIVITY\";\n\tPieceCategory[\"CONTENT_AND_FILES\"] = \"CONTENT_AND_FILES\";\n\tPieceCategory[\"DEVELOPER_TOOLS\"] = \"DEVELOPER_TOOLS\";\n\tPieceCategory[\"CUSTOMER_SUPPORT\"] = \"CUSTOMER_SUPPORT\";\n\tPieceCategory[\"FORMS_AND_SURVEYS\"] = \"FORMS_AND_SURVEYS\";\n\tPieceCategory[\"HUMAN_RESOURCES\"] = \"HUMAN_RESOURCES\";\n\tPieceCategory[\"PAYMENT_PROCESSING\"] = \"PAYMENT_PROCESSING\";\n\tPieceCategory[\"MARKETING\"] = \"MARKETING\";\n\tPieceCategory[\"SALES_AND_CRM\"] = \"SALES_AND_CRM\";\n\treturn PieceCategory;\n}({});\n\n//#endregion\n//#region upstream/core-piece-types/lib/execution.ts\nlet ExecutionType = /* @__PURE__ */ function(ExecutionType) {\n\tExecutionType[\"BEGIN\"] = \"BEGIN\";\n\tExecutionType[\"RESUME\"] = \"RESUME\";\n\treturn ExecutionType;\n}({});\nlet StreamStepProgress = /* @__PURE__ */ function(StreamStepProgress) {\n\tStreamStepProgress[\"WEBSOCKET\"] = \"WEBSOCKET\";\n\tStreamStepProgress[\"NONE\"] = \"NONE\";\n\treturn StreamStepProgress;\n}({});\nconst RespondResponse = z.object({\n\tstatus: z.optional(z.number()),\n\tbody: z.optional(z.unknown()),\n\theaders: z.optional(z.record(z.string(), z.string()))\n});\nconst DelayPauseMetadata = z.object({\n\ttype: z.literal(\"DELAY\"),\n\tresumeDateTime: z.string(),\n\trequestIdToReply: z.optional(z.string()),\n\thandlerId: z.optional(z.string()),\n\tstreamStepProgress: z.optional(z.enum(StreamStepProgress))\n});\nconst WebhookPauseMetadata = z.object({\n\ttype: z.literal(\"WEBHOOK\"),\n\trequestId: z.string(),\n\trequestIdToReply: z.optional(z.string()),\n\tresponse: RespondResponse,\n\thandlerId: z.optional(z.string()),\n\tstreamStepProgress: z.optional(z.enum(StreamStepProgress))\n});\nconst PauseMetadata = z.union([DelayPauseMetadata, WebhookPauseMetadata]);\n\n//#endregion\n//#region upstream/core-utils/lib/id-generator.ts\nconst ALPHABET = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\";\nconst ID_LENGTH = 21;\nconst ApId = z.string().check(z.regex(new RegExp(`^[0-9a-zA-Z]{${ID_LENGTH}}$`)));\nconst apId = customAlphabet(ALPHABET, ID_LENGTH);\n\n//#endregion\n//#region upstream/core-utils/lib/base-model.ts\nconst DateOrString = z.pipe(z.transform((val) => val instanceof Date ? val.toISOString() : val), z.string());\nconst BaseModelSchema = {\n\tid: z.string(),\n\tcreated: DateOrString,\n\tupdated: DateOrString\n};\nconst Nullable = (schema) => z.optional(z.nullable(schema));\nfunction NullableEnum(enumObj) {\n\treturn z.optional(z.nullable(z.enum(enumObj)));\n}\nconst OptionalBooleanFromQuery = z.pipe(z.transform((val) => val === \"true\" || val === true ? true : val === \"false\" || val === false ? false : void 0), z.optional(z.boolean()));\nconst OptionalArrayFromQuery = (schema) => z.pipe(z.transform((val) => Array.isArray(val) ? val : val !== void 0 ? [val] : void 0), z.optional(z.array(schema)));\n\n//#endregion\n//#region upstream/core-utils/lib/seek-page.ts\nconst SeekPage = (t) => z.object({\n\tdata: z.array(t),\n\tnext: Nullable(z.string()),\n\tprevious: Nullable(z.string())\n});\n\n//#endregion\n//#region upstream/core-utils/lib/locale.ts\nlet LocalesEnum = /* @__PURE__ */ function(LocalesEnum) {\n\tLocalesEnum[\"DUTCH\"] = \"nl\";\n\tLocalesEnum[\"ENGLISH\"] = \"en\";\n\tLocalesEnum[\"GERMAN\"] = \"de\";\n\tLocalesEnum[\"FRENCH\"] = \"fr\";\n\tLocalesEnum[\"SPANISH\"] = \"es\";\n\tLocalesEnum[\"JAPANESE\"] = \"ja\";\n\tLocalesEnum[\"CHINESE_SIMPLIFIED\"] = \"zh\";\n\tLocalesEnum[\"PORTUGUESE\"] = \"pt\";\n\tLocalesEnum[\"ARABIC\"] = \"ar\";\n\tLocalesEnum[\"CHINESE_TRADITIONAL\"] = \"zh-TW\";\n\treturn LocalesEnum;\n}({});\n\n//#endregion\n//#region upstream/core-utils/lib/permission.ts\nlet AIProviderName = /* @__PURE__ */ function(AIProviderName) {\n\tAIProviderName[\"OPENAI\"] = \"openai\";\n\tAIProviderName[\"OPENROUTER\"] = \"openrouter\";\n\tAIProviderName[\"ANTHROPIC\"] = \"anthropic\";\n\tAIProviderName[\"AZURE\"] = \"azure\";\n\tAIProviderName[\"GOOGLE\"] = \"google\";\n\tAIProviderName[\"ACTIVEPIECES\"] = \"activepieces\";\n\tAIProviderName[\"CLOUDFLARE_GATEWAY\"] = \"cloudflare-gateway\";\n\tAIProviderName[\"CUSTOM\"] = \"custom\";\n\tAIProviderName[\"BEDROCK\"] = \"bedrock\";\n\tAIProviderName[\"VERTEX\"] = \"vertex\";\n\tAIProviderName[\"MISTRAL\"] = \"mistral\";\n\tAIProviderName[\"XAI\"] = \"xai\";\n\tAIProviderName[\"DEEPSEEK\"] = \"deepseek\";\n\tAIProviderName[\"ZAI\"] = \"zai\";\n\tAIProviderName[\"QWEN\"] = \"qwen\";\n\tAIProviderName[\"MINIMAX\"] = \"minimax\";\n\tAIProviderName[\"MOONSHOT\"] = \"moonshot\";\n\treturn AIProviderName;\n}({});\n\n//#endregion\n//#region upstream/core-piece-types/lib/agents.ts\nconst TASK_COMPLETION_TOOL_NAME = \"updateTaskStatus\";\nlet AgentToolType = /* @__PURE__ */ function(AgentToolType) {\n\tAgentToolType[\"PIECE\"] = \"PIECE\";\n\tAgentToolType[\"FLOW\"] = \"FLOW\";\n\tAgentToolType[\"MCP\"] = \"MCP\";\n\tAgentToolType[\"KNOWLEDGE_BASE\"] = \"KNOWLEDGE_BASE\";\n\treturn AgentToolType;\n}({});\nlet FieldControlMode = /* @__PURE__ */ function(FieldControlMode) {\n\tFieldControlMode[\"AGENT_DECIDE\"] = \"agent-decide\";\n\tFieldControlMode[\"CHOOSE_YOURSELF\"] = \"choose-yourself\";\n\tFieldControlMode[\"LEAVE_EMPTY\"] = \"leave-empty\";\n\treturn FieldControlMode;\n}({});\nlet KnowledgeBaseSourceType = /* @__PURE__ */ function(KnowledgeBaseSourceType) {\n\tKnowledgeBaseSourceType[\"FILE\"] = \"FILE\";\n\tKnowledgeBaseSourceType[\"TABLE\"] = \"TABLE\";\n\treturn KnowledgeBaseSourceType;\n}({});\nlet McpProtocol = /* @__PURE__ */ function(McpProtocol) {\n\tMcpProtocol[\"SSE\"] = \"sse\";\n\tMcpProtocol[\"STREAMABLE_HTTP\"] = \"streamable-http\";\n\tMcpProtocol[\"SIMPLE_HTTP\"] = \"http\";\n\treturn McpProtocol;\n}({});\nlet McpAuthType = /* @__PURE__ */ function(McpAuthType) {\n\tMcpAuthType[\"NONE\"] = \"none\";\n\tMcpAuthType[\"ACCESS_TOKEN\"] = \"access_token\";\n\tMcpAuthType[\"API_KEY\"] = \"api_key\";\n\tMcpAuthType[\"HEADERS\"] = \"headers\";\n\treturn McpAuthType;\n}({});\nlet AgentOutputFieldType = /* @__PURE__ */ function(AgentOutputFieldType) {\n\tAgentOutputFieldType[\"TEXT\"] = \"text\";\n\tAgentOutputFieldType[\"NUMBER\"] = \"number\";\n\tAgentOutputFieldType[\"BOOLEAN\"] = \"boolean\";\n\treturn AgentOutputFieldType;\n}({});\nlet AgentTaskStatus = /* @__PURE__ */ function(AgentTaskStatus) {\n\tAgentTaskStatus[\"COMPLETED\"] = \"COMPLETED\";\n\tAgentTaskStatus[\"FAILED\"] = \"FAILED\";\n\tAgentTaskStatus[\"IN_PROGRESS\"] = \"IN_PROGRESS\";\n\treturn AgentTaskStatus;\n}({});\nlet ContentBlockType = /* @__PURE__ */ function(ContentBlockType) {\n\tContentBlockType[\"MARKDOWN\"] = \"MARKDOWN\";\n\tContentBlockType[\"TOOL_CALL\"] = \"TOOL_CALL\";\n\treturn ContentBlockType;\n}({});\nlet ToolCallStatus = /* @__PURE__ */ function(ToolCallStatus) {\n\tToolCallStatus[\"IN_PROGRESS\"] = \"in-progress\";\n\tToolCallStatus[\"COMPLETED\"] = \"completed\";\n\treturn ToolCallStatus;\n}({});\nlet ExecutionToolStatus = /* @__PURE__ */ function(ExecutionToolStatus) {\n\tExecutionToolStatus[\"SUCCESS\"] = \"SUCCESS\";\n\tExecutionToolStatus[\"FAILED\"] = \"FAILED\";\n\treturn ExecutionToolStatus;\n}({});\nlet ToolCallType = /* @__PURE__ */ function(ToolCallType) {\n\tToolCallType[\"PIECE\"] = \"PIECE\";\n\tToolCallType[\"FLOW\"] = \"FLOW\";\n\tToolCallType[\"MCP\"] = \"MCP\";\n\tToolCallType[\"KNOWLEDGE_BASE\"] = \"KNOWLEDGE_BASE\";\n\tToolCallType[\"UNKNOWN\"] = \"UNKNOWN\";\n\treturn ToolCallType;\n}({});\nlet AgentPieceProps = /* @__PURE__ */ function(AgentPieceProps) {\n\tAgentPieceProps[\"AGENT_ID\"] = \"agentId\";\n\tAgentPieceProps[\"AGENT_TOOLS\"] = \"agentTools\";\n\tAgentPieceProps[\"STRUCTURED_OUTPUT\"] = \"structuredOutput\";\n\tAgentPieceProps[\"PROMPT\"] = \"prompt\";\n\tAgentPieceProps[\"MAX_STEPS\"] = \"maxSteps\";\n\tAgentPieceProps[\"AI_PROVIDER_MODEL\"] = \"aiProviderModel\";\n\tAgentPieceProps[\"WEB_SEARCH\"] = \"webSearch\";\n\tAgentPieceProps[\"WEB_SEARCH_OPTIONS\"] = \"webSearchOptions\";\n\treturn AgentPieceProps;\n}({});\nconst PredefinedInputField = z.object({\n\tmode: z.enum(FieldControlMode),\n\tvalue: z.unknown()\n});\nconst PredefinedInputsStructure = z.object({\n\tauth: z.optional(z.string()),\n\tfields: z.record(z.string(), PredefinedInputField)\n});\nconst AgentPieceToolMetadata = z.object({\n\tpieceName: z.string(),\n\tpieceVersion: z.string(),\n\tactionName: z.string(),\n\tpredefinedInput: z.optional(PredefinedInputsStructure)\n});\nconst AgentPieceTool = z.object({\n\ttype: z.literal(\"PIECE\"),\n\ttoolName: z.string().check(z.minLength(1)),\n\tpieceMetadata: AgentPieceToolMetadata\n});\nconst McpAuthNone = z.object({ type: z.literal(\"none\") });\nconst McpAuthAccessToken = z.object({\n\ttype: z.literal(\"access_token\"),\n\taccessToken: z.string()\n});\nconst McpAuthApiKey = z.object({\n\ttype: z.literal(\"api_key\"),\n\tapiKey: z.string(),\n\tapiKeyHeader: z.string()\n});\nconst McpAuthHeaders = z.object({\n\ttype: z.literal(\"headers\"),\n\theaders: z.record(z.string(), z.string())\n});\nconst McpAuthConfig = z.discriminatedUnion(\"type\", [\n\tMcpAuthNone,\n\tMcpAuthAccessToken,\n\tMcpAuthApiKey,\n\tMcpAuthHeaders\n]);\nconst AgentFlowTool = z.object({\n\ttype: z.literal(\"FLOW\"),\n\ttoolName: z.string().check(z.minLength(1)),\n\texternalFlowId: z.string(),\n\tflowDisplayName: z.optional(z.string())\n});\nconst AgentMcpTool = z.object({\n\ttype: z.literal(\"MCP\"),\n\ttoolName: z.string().check(z.minLength(1)),\n\tserverUrl: z.url(),\n\tprotocol: z.enum(McpProtocol),\n\tauth: McpAuthConfig\n});\nconst AgentKnowledgeBaseTool = z.object({\n\ttype: z.literal(\"KNOWLEDGE_BASE\"),\n\ttoolName: z.string().check(z.minLength(1)),\n\tsourceType: z.enum(KnowledgeBaseSourceType),\n\tsourceId: z.string(),\n\tsourceName: z.string()\n});\nconst AgentTool = z.discriminatedUnion(\"type\", [\n\tAgentPieceTool,\n\tAgentFlowTool,\n\tAgentMcpTool,\n\tAgentKnowledgeBaseTool\n]);\nconst AgentOutputField = z.object({\n\tdisplayName: z.string(),\n\tdescription: z.optional(z.string()),\n\ttype: z.enum(AgentOutputFieldType)\n});\nconst MarkdownContentBlock = z.object({\n\ttype: z.literal(\"MARKDOWN\"),\n\tmarkdown: z.string()\n});\nconst toolCallBaseShape = {\n\ttype: z.literal(\"TOOL_CALL\"),\n\tinput: Nullable(z.record(z.string(), z.unknown())),\n\toutput: z.optional(z.unknown()),\n\ttoolName: z.string(),\n\tstatus: z.enum(ToolCallStatus),\n\ttoolCallId: z.string(),\n\tstartTime: z.string(),\n\tendTime: z.optional(z.string())\n};\nz.object(toolCallBaseShape);\nconst ToolCallContentBlock = z.discriminatedUnion(\"toolCallType\", [\n\tz.object({\n\t\t...toolCallBaseShape,\n\t\ttoolCallType: z.literal(\"PIECE\"),\n\t\tpieceName: z.string(),\n\t\tpieceVersion: z.string(),\n\t\tactionName: z.string()\n\t}),\n\tz.object({\n\t\t...toolCallBaseShape,\n\t\ttoolCallType: z.literal(\"FLOW\"),\n\t\tdisplayName: z.string(),\n\t\texternalFlowId: z.string()\n\t}),\n\tz.object({\n\t\t...toolCallBaseShape,\n\t\ttoolCallType: z.literal(\"MCP\"),\n\t\tdisplayName: z.string(),\n\t\tserverUrl: z.string()\n\t}),\n\tz.object({\n\t\t...toolCallBaseShape,\n\t\ttoolCallType: z.literal(\"KNOWLEDGE_BASE\"),\n\t\tdisplayName: z.string(),\n\t\tsourceType: z.string()\n\t}),\n\tz.object({\n\t\t...toolCallBaseShape,\n\t\ttoolCallType: z.literal(\"UNKNOWN\"),\n\t\tdisplayName: z.string()\n\t})\n]);\nconst AgentStepBlock = z.union([MarkdownContentBlock, ToolCallContentBlock]);\nfunction buildAuthHeaders(authConfig) {\n\tlet headers = {};\n\tswitch (authConfig.type) {\n\t\tcase \"none\": break;\n\t\tcase \"headers\":\n\t\t\theaders = authConfig.headers;\n\t\t\tbreak;\n\t\tcase \"access_token\":\n\t\t\theaders[\"Authorization\"] = `Bearer ${authConfig.accessToken}`;\n\t\t\tbreak;\n\t\tcase \"api_key\": {\n\t\t\tconst headerName = authConfig.apiKeyHeader;\n\t\t\theaders[headerName] = authConfig.apiKey;\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn headers;\n}\nfunction shortHash(str) {\n\tlet h = 5381;\n\tfor (let i = 0; i < str.length; i++) h = (Math.imul(h, 33) ^ str.charCodeAt(i)) >>> 0;\n\treturn h.toString(36).padStart(6, \"0\").slice(-6);\n}\nfunction sanitizeToolName(name) {\n\treturn name.toLowerCase().replace(/[^a-z0-9_-]/g, \"_\").replace(/_+/g, \"_\").replace(/^_+|_+$/g, \"\");\n}\nfunction createToolName(name) {\n\tconst sanitized = sanitizeToolName(name);\n\treturn `${sanitized.slice(0, MAX_PREFIX_LENGTH)}_${shortHash(sanitized.length > 0 ? sanitized : name)}_mcp`;\n}\nfunction toValidToolName(name) {\n\tif (PROVIDER_TOOL_NAME_PATTERN.test(name)) return name;\n\tconst generated = createToolName(name);\n\treturn PROVIDER_TOOL_NAME_PATTERN.test(generated) ? generated : createToolName(`tool_${name}`);\n}\nfunction suggestToolName(sourceName) {\n\treturn toValidToolName(sanitizeToolName(sourceName));\n}\nfunction isProviderSafeIdentifier(name) {\n\treturn PROVIDER_TOOL_NAME_PATTERN.test(name);\n}\nfunction toProviderSafeIdentifier({ name, fallback }) {\n\tif (isProviderSafeIdentifier(name)) return name;\n\tconst sanitized = sanitizeToolName(name).slice(0, MAX_IDENTIFIER_LENGTH);\n\tif (sanitized.length === 0) return fallback;\n\tconst seeded = /^[a-z_]/.test(sanitized) ? sanitized : `_${sanitized}`;\n\treturn isProviderSafeIdentifier(seeded) ? seeded : fallback;\n}\nfunction createPieceToolName(pieceName, actionName) {\n\tconst idx = pieceName.indexOf(\"piece-\");\n\treturn createToolName(`${idx >= 0 ? pieceName.substring(idx + 6) : pieceName}-${actionName}`);\n}\nconst MAX_PREFIX_LENGTH = 53;\nconst MAX_IDENTIFIER_LENGTH = 64;\nconst PROVIDER_TOOL_NAME_PATTERN = /^[a-zA-Z_][a-zA-Z0-9_-]{0,63}$/;\nconst mcpToolNameUtils = {\n\tcreateToolName,\n\tcreatePieceToolName,\n\ttoValidToolName,\n\tsuggestToolName,\n\tisProviderSafeIdentifier,\n\ttoProviderSafeIdentifier\n};\nconst AGENT_STEP_TIMEOUT_MS = 108e5;\nconst AGENT_STEP_TEST_TIMEOUT_MS = 9e5;\n\n//#endregion\n//#region upstream/core-piece-types/lib/ai-providers.ts\nlet AIProviderModelType = /* @__PURE__ */ function(AIProviderModelType) {\n\tAIProviderModelType[\"IMAGE\"] = \"image\";\n\tAIProviderModelType[\"TEXT\"] = \"text\";\n\treturn AIProviderModelType;\n}({});\nconst BaseAIProviderAuthConfig = z.object({ apiKey: z.string() });\nconst AnthropicProviderAuthConfig = BaseAIProviderAuthConfig;\nconst ActivePiecesProviderAuthConfig = z.object({\n\tapiKey: z.string(),\n\tapiKeyHash: z.string()\n});\nconst OpenAICompatibleProviderAuthConfig = BaseAIProviderAuthConfig;\nconst CloudflareGatewayProviderAuthConfig = BaseAIProviderAuthConfig;\nconst AzureProviderAuthConfig = BaseAIProviderAuthConfig;\nconst GoogleProviderAuthConfig = BaseAIProviderAuthConfig;\nconst OpenAIProviderAuthConfig = BaseAIProviderAuthConfig;\nconst OpenRouterProviderAuthConfig = BaseAIProviderAuthConfig;\nconst MistralProviderAuthConfig = BaseAIProviderAuthConfig;\nconst VertexProviderAuthConfig = z.object({ serviceAccountJson: z.string().check(z.minLength(1)) });\nconst BedrockProviderAuthConfig = z.object({\n\taccessKeyId: z.string().check(z.minLength(1)),\n\tsecretAccessKey: z.string().check(z.minLength(1))\n});\nconst AnthropicProviderConfig = z.object({});\nconst ActivePiecesProviderConfig = z.object({});\nconst GoogleProviderConfig = z.object({});\nconst OpenAIProviderConfig = z.object({});\nconst OpenRouterProviderConfig = z.object({});\nconst MistralProviderConfig = z.object({});\nconst ProviderModelConfig = z.object({\n\tmodelId: z.string(),\n\tmodelName: z.string(),\n\tmodelType: z.enum(AIProviderModelType)\n});\nconst OpenAICompatibleProviderConfig = z.object({\n\tapiKeyHeader: z.string(),\n\tbaseUrl: z.string(),\n\tmodels: z.array(ProviderModelConfig),\n\tdefaultHeaders: z.optional(z.record(z.string(), z.string())),\n\tapiStyle: z.optional(z.enum([\"chat\", \"responses\"]))\n});\nconst CloudflareGatewayProviderConfig = z.object({\n\taccountId: z.string(),\n\tgatewayId: z.string(),\n\tmodels: z.array(ProviderModelConfig),\n\tvertexProject: z.optional(z.string()),\n\tvertexRegion: z.optional(z.string())\n});\nconst AzureProviderConfig = z.object({\n\tresourceName: z.string(),\n\tapiVersion: z.pipe(z.transform((v) => typeof v === \"string\" && v.trim().length === 0 ? void 0 : v), z.optional(z.string()))\n});\nconst BedrockProviderConfig = z.object({ region: z.string().check(z.minLength(1)) });\nconst VertexProviderConfig = z.object({\n\tproject: z.string().check(z.regex(/^[a-z0-9][a-z0-9-]{0,62}$/)),\n\tregion: z.string().check(z.regex(/^[a-z0-9][a-z0-9-]{0,62}$/)),\n\tmodels: z.array(ProviderModelConfig)\n});\nconst OpenAiCompatibleVendorConfig = z.object({});\nconst AIProviderAuthConfig = z.union([\n\tAnthropicProviderAuthConfig,\n\tAzureProviderAuthConfig,\n\tGoogleProviderAuthConfig,\n\tOpenAIProviderAuthConfig,\n\tOpenRouterProviderAuthConfig,\n\tCloudflareGatewayProviderAuthConfig,\n\tOpenAICompatibleProviderAuthConfig,\n\tActivePiecesProviderAuthConfig,\n\tBedrockProviderAuthConfig,\n\tVertexProviderAuthConfig,\n\tMistralProviderAuthConfig\n]);\nconst AIProviderConfig = z.union([\n\tOpenAICompatibleProviderConfig,\n\tCloudflareGatewayProviderConfig,\n\tAzureProviderConfig,\n\tVertexProviderConfig,\n\tBedrockProviderConfig,\n\tAnthropicProviderConfig,\n\tGoogleProviderConfig,\n\tOpenAIProviderConfig,\n\tOpenRouterProviderConfig,\n\tActivePiecesProviderConfig,\n\tMistralProviderConfig,\n\tOpenAiCompatibleVendorConfig\n]);\nconst AIProviderModel = z.object({\n\tid: z.string(),\n\tname: z.string(),\n\ttype: z.enum(AIProviderModelType)\n});\nconst AIProviderWithoutSensitiveData = z.object({\n\tid: z.string(),\n\tname: z.string(),\n\tprovider: z.enum(AIProviderName),\n\tconfig: AIProviderConfig,\n\tenabledForChat: z.boolean()\n});\nconst ProjectAIProvider = z.object({\n\tprovider: z.enum(AIProviderName),\n\tname: z.string(),\n\tenabledForChat: z.boolean(),\n\tkeys: z.array(z.object({\n\t\tid: z.string(),\n\t\tname: z.string()\n\t}))\n});\nconst GetProviderConfigResponse = z.object({\n\tprovider: z.enum(AIProviderName),\n\tconfigId: z.string(),\n\tconfig: AIProviderConfig,\n\tauth: AIProviderAuthConfig,\n\tplatformId: z.string()\n});\nfunction splitCloudflareGatewayModelId(modelId) {\n\tconst slashIndex = modelId.indexOf(\"/\");\n\tif (slashIndex === -1) return {\n\t\tprovider: void 0,\n\t\tmodel: modelId,\n\t\tpublisher: void 0\n\t};\n\tconst provider = modelId.substring(0, slashIndex).trim().toLowerCase();\n\tconst rest = modelId.substring(slashIndex + 1);\n\tif (provider === \"google-vertex-ai\") {\n\t\tconst secondSlashIndex = rest.indexOf(\"/\");\n\t\tif (secondSlashIndex === -1) return {\n\t\t\tprovider: void 0,\n\t\t\tmodel: modelId,\n\t\t\tpublisher: void 0\n\t\t};\n\t\treturn {\n\t\t\tprovider: \"google-vertex-ai\",\n\t\t\tpublisher: rest.substring(0, secondSlashIndex),\n\t\t\tmodel: rest.substring(secondSlashIndex + 1)\n\t\t};\n\t}\n\treturn {\n\t\tprovider,\n\t\tmodel: rest,\n\t\tpublisher: void 0\n\t};\n}\nfunction getEffectiveProviderAndModel({ provider, model }) {\n\tif (provider !== \"cloudflare-gateway\" || !model) return {\n\t\tprovider,\n\t\tmodel\n\t};\n\tconst split = splitCloudflareGatewayModelId(model);\n\tconst gatewaySubmodelPrefix = (split.provider ?? \"\").trim().toLowerCase();\n\tconst mapped = CF_GATEWAY_SUBMODEL_TO_PROVIDER[gatewaySubmodelPrefix];\n\tif (!mapped) return {\n\t\tprovider,\n\t\tmodel\n\t};\n\treturn {\n\t\tprovider: mapped,\n\t\tmodel: split.model\n\t};\n}\nconst CF_GATEWAY_SUBMODEL_TO_PROVIDER = {\n\topenai: \"openai\",\n\tanthropic: \"anthropic\",\n\t\"google-ai-studio\": \"google\",\n\t\"google-vertex-ai\": \"google\"\n};\nconst OPENAI_CHAT_MODELS = [\n\t\"gpt-5.5\",\n\t\"gpt-5.4-mini\",\n\t\"gpt-5.4-nano\",\n\t\"gpt-4.1\",\n\t\"gpt-4.1-mini\"\n];\nconst ANTHROPIC_CHAT_MODELS = [\n\t\"claude-sonnet-4-6\",\n\t\"claude-opus-4-7\",\n\t\"claude-haiku-4-5\"\n];\nconst ANTHROPIC_OPENROUTER_CHAT_MODELS = [\n\t\"claude-sonnet-4.6\",\n\t\"claude-opus-4.7\",\n\t\"claude-opus-4.8\",\n\t\"claude-haiku-4.5\"\n];\nconst GOOGLE_CHAT_MODELS = [\n\t\"gemini-2.5-pro\",\n\t\"gemini-2.5-flash\",\n\t\"gemini-3.7-flash\",\n\t\"gemini-3.1-pro-preview\",\n\t\"gemini-3-flash-preview\"\n];\nconst X_AI_OPENROUTER_CHAT_MODELS = [\"grok-4.20\"];\nconst REASONING_OPTIONAL_CHAT_MODELS = ANTHROPIC_OPENROUTER_CHAT_MODELS.map((model) => `${\"anthropic\"}/${model}`);\nconst ALLOWED_CHAT_MODELS_BY_PROVIDER = {\n\t[\"openai\"]: OPENAI_CHAT_MODELS,\n\t[\"anthropic\"]: ANTHROPIC_CHAT_MODELS,\n\t[\"google\"]: GOOGLE_CHAT_MODELS,\n\t[\"vertex\"]: GOOGLE_CHAT_MODELS,\n\t[\"activepieces\"]: [\n\t\t...ANTHROPIC_OPENROUTER_CHAT_MODELS.map((m) => `${\"anthropic\"}/${m}`),\n\t\t...OPENAI_CHAT_MODELS.map((m) => `${\"openai\"}/${m}`),\n\t\t...GOOGLE_CHAT_MODELS.map((m) => `${\"google\"}/${m}`),\n\t\t...X_AI_OPENROUTER_CHAT_MODELS.map((m) => `x-ai/${m}`)\n\t]\n};\nconst DEFAULT_MAX_CONTEXT_TOKENS = 128e3;\nconst PROVIDER_MAX_CONTEXT_TOKENS = {\n\t[\"openai\"]: 128e3,\n\t[\"anthropic\"]: 2e5,\n\t[\"google\"]: 1048576,\n\t[\"bedrock\"]: 2e5,\n\t[\"vertex\"]: 1048576,\n\t[\"azure\"]: 128e3,\n\t[\"openrouter\"]: 128e3,\n\t[\"activepieces\"]: 2e5,\n\t[\"mistral\"]: 128e3\n};\nfunction getMaxContextTokens({ provider }) {\n\tif (!provider) return DEFAULT_MAX_CONTEXT_TOKENS;\n\treturn PROVIDER_MAX_CONTEXT_TOKENS[provider] ?? DEFAULT_MAX_CONTEXT_TOKENS;\n}\nconst DEFAULT_EMBEDDING_MODELS = {\n\t[\"openai\"]: \"text-embedding-3-small\",\n\t[\"google\"]: \"text-embedding-004\",\n\t[\"azure\"]: \"text-embedding-3-small\",\n\t[\"activepieces\"]: \"text-embedding-3-small\",\n\t[\"openrouter\"]: \"openai/text-embedding-3-small\"\n};\nconst WEB_SEARCH_MODE_BY_PROVIDER = {\n\t[\"anthropic\"]: \"native\",\n\t[\"google\"]: \"native\",\n\t[\"openrouter\"]: \"plugin\",\n\t[\"activepieces\"]: \"plugin\"\n};\nconst NO_IMAGE_GENERATION_PROVIDERS = /* @__PURE__ */ new Set([\n\t\"anthropic\",\n\t\"mistral\",\n\t\"xai\",\n\t\"deepseek\",\n\t\"zai\",\n\t\"qwen\",\n\t\"minimax\",\n\t\"moonshot\"\n]);\nconst OPENAI_COMPATIBLE_VENDOR_BASE_URLS = {\n\t[\"xai\"]: \"https://api.x.ai/v1\",\n\t[\"deepseek\"]: \"https://api.deepseek.com/v1\",\n\t[\"zai\"]: \"https://api.z.ai/api/paas/v4\",\n\t[\"qwen\"]: \"https://dashscope-intl.aliyuncs.com/compatible-mode/v1\",\n\t[\"minimax\"]: \"https://api.minimax.io/v1\",\n\t[\"moonshot\"]: \"https://api.moonshot.ai/v1\"\n};\nfunction buildProviderCapabilities(provider) {\n\treturn {\n\t\tchatModels: ALLOWED_CHAT_MODELS_BY_PROVIDER[provider],\n\t\tmaxContextTokens: getMaxContextTokens({ provider }),\n\t\tdefaultEmbeddingModel: DEFAULT_EMBEDDING_MODELS[provider],\n\t\tsupportsEmbedding: DEFAULT_EMBEDDING_MODELS[provider] !== void 0,\n\t\tsupportsImageGeneration: !NO_IMAGE_GENERATION_PROVIDERS.has(provider),\n\t\twebSearch: WEB_SEARCH_MODE_BY_PROVIDER[provider]\n\t};\n}\nconst ACTIVEPIECES_CHAT_TIERS = [\n\t{\n\t\tid: \"fast\",\n\t\tlabel: \"Fast\",\n\t\tmodelId: \"anthropic/claude-haiku-4.5\",\n\t\tnativeModelId: \"claude-haiku-4-5\",\n\t\tthinkingBudget: 5e3,\n\t\tcreditWeight: 2\n\t},\n\t{\n\t\tid: \"smart\",\n\t\tlabel: \"Expert\",\n\t\tmodelId: \"anthropic/claude-sonnet-4.6\",\n\t\tnativeModelId: \"claude-sonnet-4-6\",\n\t\tthinkingBudget: 1e4,\n\t\tcreditWeight: 10\n\t},\n\t{\n\t\tid: \"premium\",\n\t\tlabel: \"Heavy\",\n\t\tmodelId: \"anthropic/claude-opus-4.8\",\n\t\tnativeModelId: \"claude-opus-4-7\",\n\t\tthinkingBudget: 2e4,\n\t\tcreditWeight: 20\n\t}\n];\nconst DEFAULT_CHAT_TIER_ID = \"smart\";\nconst AI_PROVIDER_CAPABILITIES = {\n\t[\"openai\"]: buildProviderCapabilities(\"openai\"),\n\t[\"anthropic\"]: buildProviderCapabilities(\"anthropic\"),\n\t[\"openrouter\"]: buildProviderCapabilities(\"openrouter\"),\n\t[\"azure\"]: buildProviderCapabilities(\"azure\"),\n\t[\"google\"]: buildProviderCapabilities(\"google\"),\n\t[\"cloudflare-gateway\"]: buildProviderCapabilities(\"cloudflare-gateway\"),\n\t[\"custom\"]: buildProviderCapabilities(\"custom\"),\n\t[\"bedrock\"]: buildProviderCapabilities(\"bedrock\"),\n\t[\"vertex\"]: buildProviderCapabilities(\"vertex\"),\n\t[\"mistral\"]: buildProviderCapabilities(\"mistral\"),\n\t[\"activepieces\"]: buildProviderCapabilities(\"activepieces\"),\n\t[\"xai\"]: buildProviderCapabilities(\"xai\"),\n\t[\"deepseek\"]: buildProviderCapabilities(\"deepseek\"),\n\t[\"zai\"]: buildProviderCapabilities(\"zai\"),\n\t[\"qwen\"]: buildProviderCapabilities(\"qwen\"),\n\t[\"minimax\"]: buildProviderCapabilities(\"minimax\"),\n\t[\"moonshot\"]: buildProviderCapabilities(\"moonshot\")\n};\n\n//#endregion\n//#region upstream/core-piece-types/lib/forms.ts\nconst FileResponseInterfaceV1 = z.object({\n\tbase64Url: z.string(),\n\tfileName: z.string(),\n\textension: z.optional(z.string())\n});\nconst FileResponseInterfaceV2 = z.object({\n\tmimeType: z.string(),\n\turl: z.string(),\n\tfileName: z.optional(z.string())\n});\nconst FileResponseInterface = z.union([FileResponseInterfaceV1, FileResponseInterfaceV2]);\nlet HumanInputFormResultTypes = /* @__PURE__ */ function(HumanInputFormResultTypes) {\n\tHumanInputFormResultTypes[\"FILE\"] = \"file\";\n\tHumanInputFormResultTypes[\"MARKDOWN\"] = \"markdown\";\n\treturn HumanInputFormResultTypes;\n}({});\nfunction createKeyForFormInput(displayName) {\n\t/**We do this because react form inputs must not contain quotes */\n\treturn displayName.toLowerCase().replace(/\\s+(\\w)/g, (_, letter) => letter.toUpperCase()).replace(/^(.)/, (letter) => letter.toLowerCase()).replaceAll(/[\\\\\"''\\n\\r\\t]/g, \"\");\n}\nconst HumanInputFormResult = z.union([z.object({\n\ttype: z.literal(\"file\"),\n\tvalue: FileResponseInterface\n}), z.object({\n\ttype: z.literal(\"markdown\"),\n\tvalue: z.string(),\n\tfiles: z.optional(z.array(FileResponseInterface))\n})]);\nconst ChatFormResponse = z.object({\n\tsessionId: z.string(),\n\tmessage: z.string(),\n\tfiles: z.optional(z.array(z.string()))\n});\n\n//#endregion\n//#region upstream/core-piece-types/lib/tables.ts\nlet FieldType = /* @__PURE__ */ function(FieldType) {\n\tFieldType[\"TEXT\"] = \"TEXT\";\n\tFieldType[\"NUMBER\"] = \"NUMBER\";\n\tFieldType[\"DATE\"] = \"DATE\";\n\tFieldType[\"DATETIME\"] = \"DATETIME\";\n\tFieldType[\"STATIC_DROPDOWN\"] = \"STATIC_DROPDOWN\";\n\treturn FieldType;\n}({});\nlet TableAutomationTrigger = /* @__PURE__ */ function(TableAutomationTrigger) {\n\tTableAutomationTrigger[\"ON_NEW_RECORD\"] = \"ON_NEW_RECORD\";\n\tTableAutomationTrigger[\"ON_UPDATE_RECORD\"] = \"ON_UPDATE_RECORD\";\n\treturn TableAutomationTrigger;\n}({});\nlet TableAutomationStatus = /* @__PURE__ */ function(TableAutomationStatus) {\n\tTableAutomationStatus[\"ENABLED\"] = \"ENABLED\";\n\tTableAutomationStatus[\"DISABLED\"] = \"DISABLED\";\n\treturn TableAutomationStatus;\n}({});\nlet TableWebhookEventType = /* @__PURE__ */ function(TableWebhookEventType) {\n\tTableWebhookEventType[\"RECORD_CREATED\"] = \"RECORD_CREATED\";\n\tTableWebhookEventType[\"RECORD_UPDATED\"] = \"RECORD_UPDATED\";\n\tTableWebhookEventType[\"RECORD_DELETED\"] = \"RECORD_DELETED\";\n\treturn TableWebhookEventType;\n}({});\nlet FilterOperator = /* @__PURE__ */ function(FilterOperator) {\n\tFilterOperator[\"EQ\"] = \"eq\";\n\tFilterOperator[\"NEQ\"] = \"neq\";\n\tFilterOperator[\"GT\"] = \"gt\";\n\tFilterOperator[\"GTE\"] = \"gte\";\n\tFilterOperator[\"LT\"] = \"lt\";\n\tFilterOperator[\"LTE\"] = \"lte\";\n\tFilterOperator[\"CO\"] = \"co\";\n\tFilterOperator[\"EXISTS\"] = \"exists\";\n\tFilterOperator[\"NOT_EXISTS\"] = \"not_exists\";\n\treturn FilterOperator;\n}({});\nconst Field = z.union([z.object({\n\t...BaseModelSchema,\n\tname: z.string(),\n\texternalId: z.string(),\n\ttype: z.literal(\"STATIC_DROPDOWN\"),\n\ttableId: z.string(),\n\tprojectId: z.string(),\n\tdata: z.object({ options: z.array(z.object({ value: z.string() })) })\n}), z.object({\n\t...BaseModelSchema,\n\tname: z.string(),\n\texternalId: z.string(),\n\ttype: z.union([\n\t\tz.literal(\"TEXT\"),\n\t\tz.literal(\"NUMBER\"),\n\t\tz.literal(\"DATE\"),\n\t\tz.literal(\"DATETIME\")\n\t]),\n\ttableId: z.string(),\n\tprojectId: z.string()\n})]);\nconst Table = z.object({\n\t...BaseModelSchema,\n\tname: z.string(),\n\tfolderId: Nullable(z.string()),\n\tprojectId: z.string(),\n\texternalId: z.string(),\n\tstatus: NullableEnum(TableAutomationStatus),\n\ttrigger: NullableEnum(TableAutomationTrigger)\n});\nconst PopulatedRecord = z.object({\n\t...BaseModelSchema,\n\ttableId: z.string(),\n\tprojectId: z.string(),\n\tcells: z.record(z.string(), z.object({\n\t\tupdated: z.string(),\n\t\tcreated: z.string(),\n\t\tvalue: z.unknown(),\n\t\tfieldName: z.string()\n\t}))\n});\nconst CreateTableWebhookRequest = z.object({\n\tevents: z.array(z.enum(TableWebhookEventType)),\n\twebhookUrl: z.string(),\n\tflowId: z.string()\n});\nconst ExportTableResponse = z.object({\n\tfields: z.array(z.object({\n\t\tid: z.string(),\n\t\tname: z.string()\n\t})),\n\trows: z.array(z.record(z.string(), z.string())),\n\tname: z.string()\n});\nconst ListTablesRequest = z.object({\n\tprojectId: z.string(),\n\tlimit: z.optional(z.coerce.number()),\n\tcursor: z.optional(z.string()),\n\tname: z.optional(z.string()),\n\texternalIds: OptionalArrayFromQuery(z.string()),\n\tfolderId: z.optional(z.string()),\n\tfolderIds: OptionalArrayFromQuery(z.string())\n});\nconst CreateRecordsRequest = z.object({\n\trecords: z.array(z.array(z.object({\n\t\tfieldId: z.string(),\n\t\tvalue: coerceToString()\n\t}))),\n\ttableId: z.string()\n});\nconst UpdateRecordRequest = z.object({\n\tcells: z.optional(z.array(z.object({\n\t\tfieldId: z.string(),\n\t\tvalue: coerceToString()\n\t}))),\n\ttableId: z.string(),\n\tagentUpdate: z.optional(z.boolean())\n});\nconst Filter = z.discriminatedUnion(\"operator\", [\n\tvalueFilter(\"eq\"),\n\tvalueFilter(\"neq\"),\n\tvalueFilter(\"gt\"),\n\tvalueFilter(\"gte\"),\n\tvalueFilter(\"lt\"),\n\tvalueFilter(\"lte\"),\n\tvalueFilter(\"co\"),\n\texistenceFilter(\"exists\"),\n\texistenceFilter(\"not_exists\")\n]);\nconst ListRecordsRequest = z.object({\n\ttableId: z.string(),\n\tlimit: z.optional(z.coerce.number()),\n\tcursor: z.optional(z.string()),\n\tfilters: OptionalArrayFromQuery(Filter)\n});\nconst StaticDropdownEmptyOption = {\n\tlabel: \"\",\n\tvalue: \"\"\n};\nfunction coerceToString() {\n\treturn z.pipe(z.transform((v) => v === null || v === void 0 ? v : String(v)), z.nullable(z.string()));\n}\nfunction valueFilter(op) {\n\treturn z.object({\n\t\tfieldId: z.string(),\n\t\toperator: z.literal(op),\n\t\tvalue: z.string()\n\t});\n}\nfunction existenceFilter(op) {\n\treturn z.object({\n\t\tfieldId: z.string(),\n\t\toperator: z.literal(op)\n\t});\n}\n\n//#endregion\n//#region upstream/core-piece-types/lib/flow-contracts.ts\nlet FlowStatus = /* @__PURE__ */ function(FlowStatus) {\n\tFlowStatus[\"ENABLED\"] = \"ENABLED\";\n\tFlowStatus[\"DISABLED\"] = \"DISABLED\";\n\treturn FlowStatus;\n}({});\nlet FlowTriggerType = /* @__PURE__ */ function(FlowTriggerType) {\n\tFlowTriggerType[\"EMPTY\"] = \"EMPTY\";\n\tFlowTriggerType[\"PIECE\"] = \"PIECE_TRIGGER\";\n\treturn FlowTriggerType;\n}({});\nconst StopResponse = z.object({\n\tstatus: z.optional(z.number()),\n\tbody: z.optional(z.unknown()),\n\theaders: z.optional(z.record(z.string(), z.string()))\n});\nconst Project = z.object({\n\t...BaseModelSchema,\n\tdeleted: Nullable(DateOrString),\n\townerId: z.string(),\n\tdisplayName: z.string(),\n\tplatformId: z.string(),\n\texternalId: Nullable(z.string())\n});\nconst USE_DRAFT_QUERY_PARAM_NAME = \"useDraft\";\nconst PARENT_RUN_ID_HEADER = \"ap-parent-run-id\";\nconst FAIL_PARENT_ON_FAILURE_HEADER = \"ap-fail-parent-on-failure\";\nconst RAW_PAYLOAD_HEADER = \"ap-raw-payload\";\n\n//#endregion\n//#region upstream/core-piece-types/lib/mcp-piece.ts\nlet McpPropertyType = /* @__PURE__ */ function(McpPropertyType) {\n\tMcpPropertyType[\"TEXT\"] = \"Text\";\n\tMcpPropertyType[\"BOOLEAN\"] = \"Boolean\";\n\tMcpPropertyType[\"DATE\"] = \"Date\";\n\tMcpPropertyType[\"NUMBER\"] = \"Number\";\n\tMcpPropertyType[\"ARRAY\"] = \"Array\";\n\tMcpPropertyType[\"OBJECT\"] = \"Object\";\n\treturn McpPropertyType;\n}({});\nconst McpProperty = z.object({\n\tname: z.string(),\n\tdescription: z.optional(z.string()),\n\ttype: z.string(),\n\trequired: z.boolean()\n});\nconst McpTrigger = z.object({\n\tpieceName: z.string(),\n\ttriggerName: z.string(),\n\tinput: z.object({\n\t\ttoolName: z.string(),\n\t\ttoolDescription: z.string(),\n\t\tinputSchema: z.array(McpProperty),\n\t\treturnsResponse: z.boolean()\n\t})\n});\n\n//#endregion\n//#region upstream/core-piece-types/lib/engine-tools.ts\nfunction normalizeToolOutputToExecuteResponse(raw) {\n\tif (raw === null || typeof raw !== \"object\") return {\n\t\tstatus: \"FAILED\",\n\t\toutput: raw,\n\t\tresolvedInput: {},\n\t\terrorMessage: \"Invalid tool output\"\n\t};\n\tconst o = raw;\n\tif (o[\"status\"] === \"SUCCESS\" || o[\"status\"] === \"FAILED\") return {\n\t\tstatus: o[\"status\"],\n\t\toutput: o[\"output\"],\n\t\tresolvedInput: o[\"resolvedInput\"] ?? {},\n\t\terrorMessage: o[\"errorMessage\"]\n\t};\n\tconst isError = o[\"isError\"] === true;\n\tlet output = o[\"structuredContent\"];\n\tif (output === void 0 && Array.isArray(o[\"content\"])) {\n\t\tconst parts = o[\"content\"].map((c) => c?.text).filter(Boolean);\n\t\toutput = parts.length === 1 ? parts[0] : parts.length ? { text: parts.join(\"\") } : o[\"content\"];\n\t}\n\tif (output === void 0) output = o;\n\treturn {\n\t\tstatus: isError ? \"FAILED\" : \"SUCCESS\",\n\t\toutput,\n\t\tresolvedInput: {},\n\t\terrorMessage: isError ? o[\"content\"]?.[0]?.text ?? o[\"message\"] ?? \"Tool failed\" : void 0\n\t};\n}\n\n//#endregion\n//#region upstream/framework/lib/property/util.ts\nfunction buildSchema(props, auth, requireAuth = true) {\n\tconst entries = Object.entries(props);\n\tconst propsSchema = {};\n\tfor (const [name, property] of entries) {\n\t\tswitch (property.type) {\n\t\t\tcase \"MARKDOWN\":\n\t\t\t\tpropsSchema[name] = z.optional(z.union([\n\t\t\t\t\tz.null(),\n\t\t\t\t\tz.undefined(),\n\t\t\t\t\tz.never(),\n\t\t\t\t\tz.unknown()\n\t\t\t\t]));\n\t\t\t\tbreak;\n\t\t\tcase \"DATE_TIME\":\n\t\t\tcase \"SHORT_TEXT\":\n\t\t\tcase \"LONG_TEXT\":\n\t\t\tcase \"RICH_TEXT\":\n\t\t\tcase \"COLOR\":\n\t\t\tcase \"FILE\":\n\t\t\t\tpropsSchema[name] = property.required ? z.string().check(z.minLength(1)) : z.string();\n\t\t\t\tbreak;\n\t\t\tcase \"CHECKBOX\":\n\t\t\t\tpropsSchema[name] = z.union([z.boolean(), z.string()]);\n\t\t\t\tbreak;\n\t\t\tcase \"NUMBER\":\n\t\t\t\tpropsSchema[name] = z.union([property.required ? z.string().check(z.minLength(1)) : z.string(), z.number()]);\n\t\t\t\tbreak;\n\t\t\tcase \"STATIC_DROPDOWN\":\n\t\t\tcase \"DROPDOWN\":\n\t\t\t\tpropsSchema[name] = z.unknown().check(z.refine((val) => val !== null && val !== void 0, { error: \"Value must not be null or undefined\" }));\n\t\t\t\tbreak;\n\t\t\tcase \"SECRET_TEXT\":\n\t\t\t\tpropsSchema[name] = property.required ? z.string().check(z.minLength(1)) : z.string();\n\t\t\t\tbreak;\n\t\t\tcase \"BASIC_AUTH\":\n\t\t\tcase \"CUSTOM_AUTH\":\n\t\t\tcase \"OAUTH2\": break;\n\t\t\tcase \"ARRAY\": {\n\t\t\t\tconst arrayItemSchema = isNil(property.properties) ? property.required ? z.string().check(z.minLength(1)) : z.string() : buildSchema(property.properties, void 0);\n\t\t\t\tpropsSchema[name] = z.union([\n\t\t\t\t\tproperty.required ? z.array(arrayItemSchema).check(z.minLength(1)) : z.array(arrayItemSchema),\n\t\t\t\t\tz.record(z.string(), z.unknown()),\n\t\t\t\t\tproperty.required ? z.string().check(z.minLength(1)) : z.string()\n\t\t\t\t]);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"OBJECT\":\n\t\t\t\tpropsSchema[name] = z.union([z.record(z.string(), z.any()), property.required ? z.string().check(z.minLength(1)) : z.string()]);\n\t\t\t\tbreak;\n\t\t\tcase \"DATE_RANGE\":\n\t\t\t\tpropsSchema[name] = z.union([z.record(z.string(), z.any()), z.string()]);\n\t\t\t\tbreak;\n\t\t\tcase \"JSON\":\n\t\t\t\tpropsSchema[name] = z.union([\n\t\t\t\t\tz.record(z.string(), z.any()),\n\t\t\t\t\tz.array(z.any()),\n\t\t\t\t\tproperty.required ? z.string().check(z.minLength(1)) : z.string()\n\t\t\t\t]);\n\t\t\t\tbreak;\n\t\t\tcase \"MULTI_SELECT_DROPDOWN\":\n\t\t\tcase \"STATIC_MULTI_SELECT_DROPDOWN\":\n\t\t\t\tpropsSchema[name] = z.union([property.required ? z.array(z.any()).check(z.minLength(1)) : z.array(z.any()), property.required ? z.string().check(z.minLength(1)) : z.string()]);\n\t\t\t\tbreak;\n\t\t\tcase \"DYNAMIC\":\n\t\t\t\tpropsSchema[name] = z.record(z.string(), z.any());\n\t\t\t\tbreak;\n\t\t\tcase \"CUSTOM\": propsSchema[name] = z.unknown();\n\t\t}\n\t\tif (!property.required && property.type !== \"ARRAY\") propsSchema[name] = z.optional(z.union(isEmpty(propsSchema[name]) ? [\n\t\t\tz.any(),\n\t\t\tz.null(),\n\t\t\tz.undefined()\n\t\t] : [\n\t\t\tpropsSchema[name],\n\t\t\tz.null(),\n\t\t\tz.undefined()\n\t\t]));\n\t}\n\tif (auth && requireAuth) propsSchema[AUTHENTICATION_PROPERTY_NAME] = z.string().check(z.minLength(1));\n\treturn z.object(propsSchema);\n}\nconst piecePropertiesUtils = { buildSchema };\n\n//#endregion\n//#region upstream/framework/lib/property/index.ts\nconst PieceProperty = z.union([InputProperty, PieceAuthProperty]);\nconst PiecePropertyMap = z.record(z.string(), PieceProperty);\nconst InputPropertyMap = z.record(z.string(), InputProperty);\n\n//#endregion\n//#region upstream/framework/lib/trigger/trigger.ts\nconst DEDUPE_KEY_PROPERTY = \"_dedupe_key\";\nlet WebhookRenewStrategy = /* @__PURE__ */ function(WebhookRenewStrategy) {\n\tWebhookRenewStrategy[\"CRON\"] = \"CRON\";\n\tWebhookRenewStrategy[\"NONE\"] = \"NONE\";\n\treturn WebhookRenewStrategy;\n}({});\nconst WebhookRenewConfiguration = z.union([z.object({\n\tstrategy: z.literal(\"CRON\"),\n\tcronExpression: z.string()\n}), z.object({ strategy: z.literal(\"NONE\") })]);\nvar ITrigger = class {\n\tname;\n\tdisplayName;\n\tdescription;\n\trequireAuth;\n\tprops;\n\ttype;\n\thandshakeConfiguration;\n\tonHandshake;\n\trenewConfiguration;\n\tonRenew;\n\tonEnable;\n\tonDisable;\n\tonStart;\n\trun;\n\ttest;\n\tsampleData;\n\ttestStrategy;\n\toutputSchema;\n\taiMetadata;\n\tclassification;\n\tpropertyGroups;\n\tconstructor(name, displayName, description, requireAuth, props, type, handshakeConfiguration, onHandshake, renewConfiguration, onRenew, onEnable, onDisable, onStart, run, test, sampleData, testStrategy, outputSchema, aiMetadata, classification, propertyGroups) {\n\t\tthis.name = name;\n\t\tthis.displayName = displayName;\n\t\tthis.description = description;\n\t\tthis.requireAuth = requireAuth;\n\t\tthis.props = props;\n\t\tthis.type = type;\n\t\tthis.handshakeConfiguration = handshakeConfiguration;\n\t\tthis.onHandshake = onHandshake;\n\t\tthis.renewConfiguration = renewConfiguration;\n\t\tthis.onRenew = onRenew;\n\t\tthis.onEnable = onEnable;\n\t\tthis.onDisable = onDisable;\n\t\tthis.onStart = onStart;\n\t\tthis.run = run;\n\t\tthis.test = test;\n\t\tthis.sampleData = sampleData;\n\t\tthis.testStrategy = testStrategy;\n\t\tthis.outputSchema = outputSchema;\n\t\tthis.aiMetadata = aiMetadata;\n\t\tthis.classification = classification;\n\t\tthis.propertyGroups = propertyGroups;\n\t}\n};\nconst createTrigger$1 = (params) => {\n\tswitch (params.type) {\n\t\tcase \"WEBHOOK\": return new ITrigger(params.name, params.displayName, params.description, params.requireAuth ?? true, params.props, params.type, params.handshakeConfiguration ?? { strategy: \"NONE\" }, params.onHandshake ?? (async () => ({ status: 200 })), params.renewConfiguration ?? { strategy: \"NONE\" }, params.onRenew ?? (async () => Promise.resolve()), params.onEnable, params.onDisable, params.onStart ?? (async () => Promise.resolve()), params.run, params.test ?? (() => Promise.resolve([params.sampleData])), params.sampleData, params.test ? \"TEST_FUNCTION\" : \"SIMULATION\", params.outputSchema, params.aiMetadata, params.classification, params.propertyGroups);\n\t\tcase \"POLLING\": return new ITrigger(params.name, params.displayName, params.description, params.requireAuth ?? true, params.props, params.type, { strategy: \"NONE\" }, async () => ({ status: 200 }), { strategy: \"NONE\" }, async () => Promise.resolve(), params.onEnable, params.onDisable, params.onStart ?? (async () => Promise.resolve()), params.run, params.test ?? (() => Promise.resolve([params.sampleData])), params.sampleData, \"TEST_FUNCTION\", params.outputSchema, params.aiMetadata, params.classification, params.propertyGroups);\n\t\tcase \"MANUAL\": return new ITrigger(params.name, params.displayName, params.description, params.requireAuth ?? true, params.props, params.type, { strategy: \"NONE\" }, async () => ({ status: 200 }), { strategy: \"NONE\" }, async () => Promise.resolve(), params.onEnable, params.onDisable, params.onStart ?? (async () => Promise.resolve()), params.run, params.test ?? (() => Promise.resolve([params.sampleData])), params.sampleData, \"TEST_FUNCTION\", params.outputSchema, params.aiMetadata, params.classification, params.propertyGroups);\n\t\tcase \"APP_WEBHOOK\": return new ITrigger(params.name, params.displayName, params.description, params.requireAuth ?? true, params.props, params.type, { strategy: \"NONE\" }, async () => ({ status: 200 }), { strategy: \"NONE\" }, async () => Promise.resolve(), params.onEnable, params.onDisable, params.onStart ?? (async () => Promise.resolve()), params.run, params.test ?? (() => Promise.resolve([params.sampleData])), params.sampleData, isNil(params.sampleData) && isNil(params.test) ? \"SIMULATION\" : \"TEST_FUNCTION\", params.outputSchema, params.aiMetadata, params.classification, params.propertyGroups);\n\t\tdefault: {\n\t\t\tconst { name, type, strategy } = params;\n\t\t\tthrow new Error(type === void 0 && strategy !== void 0 ? `createTrigger: trigger ${JSON.stringify(name)} sets \\`strategy\\`; the field is \\`type\\`, e.g. type: TriggerStrategy.POLLING` : `createTrigger: trigger ${JSON.stringify(name)} has \\`type\\` ${JSON.stringify(type)}; set type: TriggerStrategy.POLLING or TriggerStrategy.WEBHOOK`);\n\t\t}\n\t}\n};\n\n//#endregion\n//#region upstream/framework/lib/context/index.ts\nvar PieceServerContextError = class extends Error {\n\tconstructor(message) {\n\t\tsuper(message);\n\t\tthis.name = \"PieceServerContextError\";\n\t}\n};\nfunction isPieceServerContextError(error) {\n\treturn error instanceof Error && error.name === \"PieceServerContextError\";\n}\nlet StoreScope = /* @__PURE__ */ function(StoreScope) {\n\tStoreScope[\"PROJECT\"] = \"COLLECTION\";\n\tStoreScope[\"FLOW\"] = \"FLOW\";\n\treturn StoreScope;\n}({});\n\n//#endregion\n//#region upstream/framework/lib/context/versioning.ts\nlet ContextVersion = /* @__PURE__ */ function(ContextVersion) {\n\tContextVersion[\"V1\"] = \"1\";\n\tContextVersion[\"V2\"] = \"2\";\n\treturn ContextVersion;\n}({});\nconst LATEST_CONTEXT_VERSION = \"2\";\nconst MINIMUM_SUPPORTED_RELEASE_AFTER_LATEST_CONTEXT_VERSION = \"0.82.0\";\nconst backwardCompatabilityContextUtils = { makeActionContextBackwardCompatible({ context, contextVersion }) {\n\tswitch (contextVersion) {\n\t\tcase \"2\": return context;\n\t\tcase \"1\": return addLegacyMethods({ context });\n\t\tcase void 0: return addLegacyMethodsAndServerUrl({ context });\n\t}\n} };\nfunction addLegacyMethods({ context }) {\n\treturn {\n\t\t...context,\n\t\tgenerateResumeUrl: buildLegacyGenerateResumeUrl({ context }),\n\t\trun: {\n\t\t\t...context.run,\n\t\t\tpause: buildLegacyPauseHook({ context })\n\t\t}\n\t};\n}\nfunction addLegacyMethodsAndServerUrl({ context }) {\n\treturn {\n\t\t...addLegacyMethods({ context }),\n\t\tserverUrl: context.server.publicUrl\n\t};\n}\n/**\n* @deprecated Since 2026-04-12. Remove after 2026-10-12 once all pieces migrate to createWaitpoint/waitForWaitpoint.\n*/\nfunction buildLegacyPauseHook({ context }) {\n\treturn (req) => {\n\t\tconst type = req.pauseMetadata.type === \"DELAY\" ? \"DELAY\" : \"WEBHOOK\";\n\t\tconst responseToSend = req.pauseMetadata.type === \"WEBHOOK\" ? req.pauseMetadata.response : void 0;\n\t\tconst resumeDateTime = req.pauseMetadata.type === \"DELAY\" ? req.pauseMetadata.resumeDateTime : void 0;\n\t\tcontext.run.createWaitpoint({\n\t\t\ttype,\n\t\t\tversion: \"V0\",\n\t\t\tresumeDateTime,\n\t\t\tresponseToSend\n\t\t}).catch((e) => {\n\t\t\tconsole.error(\"[buildLegacyPauseHook] Failed to create waitpoint\", e);\n\t\t\tprocess.exit(1);\n\t\t});\n\t\tcontext.run.waitForWaitpoint(\"\");\n\t};\n}\n/**\n* @deprecated Since 2026-04-12. Remove after 2026-10-12 once all pieces migrate to createWaitpoint/waitForWaitpoint.\n*/\nfunction buildLegacyGenerateResumeUrl({ context }) {\n\treturn (params) => {\n\t\tconst randomId = Math.random().toString(36).substring(2);\n\t\tconst url = new URL(`${context.server.publicUrl}v1/flow-runs/${context.run.id}/requests/${randomId}${params.sync ? \"/sync\" : \"\"}`);\n\t\turl.search = new URLSearchParams(params.queryParams).toString();\n\t\treturn url.toString();\n\t};\n}\n\n//#endregion\n//#region upstream/framework/lib/piece.ts\nvar Piece = class {\n\tdisplayName;\n\tlogoUrl;\n\tauthors;\n\tevents;\n\tcategories;\n\tauth;\n\tminimumSupportedRelease;\n\tmaximumSupportedRelease;\n\tdescription;\n\tdeprecated;\n\t_actions = {};\n\t_triggers = {};\n\tgetContextInfo = () => ({ version: \"2\" });\n\tconstructor(displayName, logoUrl, authors, events, actions, triggers, categories, auth, minimumSupportedRelease = MINIMUM_SUPPORTED_RELEASE_AFTER_LATEST_CONTEXT_VERSION, maximumSupportedRelease, description = \"\", deprecated) {\n\t\tthis.displayName = displayName;\n\t\tthis.logoUrl = logoUrl;\n\t\tthis.authors = authors;\n\t\tthis.events = events;\n\t\tthis.categories = categories;\n\t\tthis.auth = auth;\n\t\tthis.minimumSupportedRelease = minimumSupportedRelease;\n\t\tthis.maximumSupportedRelease = maximumSupportedRelease;\n\t\tthis.description = description;\n\t\tthis.deprecated = deprecated;\n\t\tif (!isValidSimpleSemver(minimumSupportedRelease) || isSemverLessThan(minimumSupportedRelease, \"0.82.0\")) this.minimumSupportedRelease = MINIMUM_SUPPORTED_RELEASE_AFTER_LATEST_CONTEXT_VERSION;\n\t\tactions.forEach((action) => this._actions[action.name] = action);\n\t\ttriggers.forEach((trigger) => this._triggers[trigger.name] = trigger);\n\t}\n\tmetadata() {\n\t\treturn {\n\t\t\tdisplayName: this.displayName,\n\t\t\tlogoUrl: this.logoUrl,\n\t\t\tactions: this._actions,\n\t\t\ttriggers: this._triggers,\n\t\t\tcategories: this.categories,\n\t\t\tdescription: this.description,\n\t\t\tauthors: this.authors,\n\t\t\tauth: withConnectionIdentifierFlag(this.auth),\n\t\t\tminimumSupportedRelease: this.minimumSupportedRelease,\n\t\t\tmaximumSupportedRelease: this.maximumSupportedRelease,\n\t\t\tdeprecated: this.deprecated,\n\t\t\tcontextInfo: this.getContextInfo?.()\n\t\t};\n\t}\n\tgetAction(actionName) {\n\t\treturn this._actions[actionName];\n\t}\n\tgetTrigger(triggerName) {\n\t\treturn this._triggers[triggerName];\n\t}\n\tactions() {\n\t\treturn this._actions;\n\t}\n\ttriggers() {\n\t\treturn this._triggers;\n\t}\n};\nconst createPiece = (params) => {\n\tif (params.auth && Array.isArray(params.auth)) {\n\t\tif (!params.auth.every((auth, index, self) => index === self.findIndex((t) => t.type === auth.type))) throw new Error(\"Auth properties must be unique by type\");\n\t}\n\treturn new Piece(params.displayName, params.logoUrl, params.authors ?? [], params.events, params.actions, params.triggers, params.categories ?? [], params.auth, params.minimumSupportedRelease, params.maximumSupportedRelease, params.description, params.deprecated);\n};\nfunction withConnectionIdentifierFlag(auth) {\n\tif (auth === void 0) return;\n\treturn Array.isArray(auth) ? auth.map(flagConnectionIdentifier) : flagConnectionIdentifier(auth);\n}\nfunction flagConnectionIdentifier(auth) {\n\treturn {\n\t\t...auth,\n\t\thasConnectionIdentifier: auth.getConnectionIdentifier !== void 0\n\t};\n}\nfunction isValidSimpleSemver(version) {\n\treturn /^\\d+\\.\\d+\\.\\d+$/.test(version);\n}\nfunction isSemverLessThan(a, b) {\n\tconst [a1, a2, a3] = a.split(\".\").map(Number);\n\tconst [b1, b2, b3] = b.split(\".\").map(Number);\n\tif (a1 !== b1) return a1 < b1;\n\tif (a2 !== b2) return a2 < b2;\n\treturn a3 < b3;\n}\n\n//#endregion\n//#region upstream/framework/lib/piece-metadata.ts\nconst I18nForPiece = z.optional(z.record(z.string(), z.record(z.string(), z.string())));\nconst PieceBase = z.object({\n\tid: z.optional(z.string()),\n\tname: z.string(),\n\tdisplayName: z.string(),\n\tlogoUrl: z.string(),\n\tdescription: z.string(),\n\tauthors: z.array(z.string()),\n\tplatformId: z.optional(z.string()),\n\tdirectoryPath: z.optional(z.string()),\n\tauth: z.optional(z.union([PieceAuthProperty, z.array(PieceAuthProperty)])),\n\tversion: z.string(),\n\tcategories: z.optional(z.array(z.enum(PieceCategory))),\n\tminimumSupportedRelease: z.optional(z.string()),\n\tmaximumSupportedRelease: z.optional(z.string()),\n\tdeprecated: z.optional(z.boolean()),\n\ti18n: I18nForPiece\n});\nconst Audience = z.enum([\n\t\"human\",\n\t\"ai\",\n\t\"both\"\n]);\nconst AiMetadata = z.object({\n\tdescription: z.optional(z.string()),\n\tidempotent: z.optional(z.boolean())\n});\nconst ActionClassification = z.enum([\n\t\"READ\",\n\t\"SEARCH\",\n\t\"WRITE\",\n\t\"DESTRUCTIVE\"\n]);\nconst READ_ONLY_CLASSIFICATIONS = [\"READ\", \"SEARCH\"];\nconst isReadOnlyClassification = (classification) => classification !== void 0 && READ_ONLY_CLASSIFICATIONS.includes(classification);\nconst PropertyGroupDisplay = z.enum([\n\t\"tabs\",\n\t\"section\",\n\t\"summary\",\n\t\"builder\",\n\t\"footer\"\n]);\nconst PropertyGroup = z.object({\n\tkey: z.string(),\n\tdisplay: PropertyGroupDisplay,\n\tlabel: z.optional(z.string()),\n\tdescription: z.optional(z.string()),\n\ticon: z.optional(z.string()),\n\tprops: z.array(z.string())\n});\nconst ActionBase = z.object({\n\tname: z.string(),\n\tdisplayName: z.string(),\n\tdescription: z.string(),\n\tprops: PiecePropertyMap,\n\tpropertyGroups: z.optional(z.array(PropertyGroup)),\n\trequireAuth: z.boolean(),\n\terrorHandlingOptions: z.optional(ErrorHandlingOptionsParam),\n\toutputSchema: z.optional(z.custom()),\n\taudience: z.optional(Audience),\n\taiMetadata: z.optional(AiMetadata),\n\tclassification: z.optional(ActionClassification)\n});\nconst TriggerBase = z.object({\n\tname: z.string(),\n\tdisplayName: z.string(),\n\tdescription: z.string(),\n\tprops: PiecePropertyMap,\n\tpropertyGroups: z.optional(z.array(PropertyGroup)),\n\terrorHandlingOptions: z.optional(ErrorHandlingOptionsParam),\n\ttype: z.enum(TriggerStrategy),\n\tsampleData: z.unknown(),\n\thandshakeConfiguration: z.optional(z.custom()),\n\trenewConfiguration: z.optional(WebhookRenewConfiguration),\n\ttestStrategy: z.enum(TriggerTestStrategy),\n\toutputSchema: z.optional(z.custom()),\n\taiMetadata: z.optional(AiMetadata),\n\tclassification: z.optional(ActionClassification)\n});\nconst PieceMetadata = z.object({\n\t...PieceBase.shape,\n\tactions: z.record(z.string(), ActionBase),\n\ttriggers: z.record(z.string(), TriggerBase)\n});\nconst PieceMetadataSummary = z.object({\n\t...PieceBase.shape,\n\tactions: z.number(),\n\ttriggers: z.number(),\n\tsuggestedActions: z.optional(z.array(ActionBase)),\n\tsuggestedTriggers: z.optional(z.array(TriggerBase))\n});\nconst PiecePackageMetadata = z.object({\n\tprojectUsage: z.number(),\n\tpieceType: z.enum(PieceType),\n\tpackageType: z.enum(PackageType),\n\tplatformId: z.optional(z.string()),\n\tarchiveId: z.optional(z.string())\n});\nconst PieceMetadataModel = z.object({\n\t...PieceMetadata.shape,\n\t...PiecePackageMetadata.shape\n});\nconst PieceMetadataModelSummary = z.object({\n\t...PieceMetadataSummary.shape,\n\t...PiecePackageMetadata.shape\n});\nconst PiecePackageInformation = z.object({\n\tname: z.string(),\n\tversion: z.string()\n});\n\n//#endregion\n//#region upstream/framework/lib/i18n.ts\nconst pieceTranslation = {\n\ttranslatePiece: (params) => {\n\t\tconst { piece, locale, mutate = false } = params;\n\t\tif (!locale) return piece;\n\t\ttry {\n\t\t\tconst target = piece.i18n?.[locale];\n\t\t\tif (!target) return piece;\n\t\t\tconst translatedPiece = mutate ? piece : JSON.parse(JSON.stringify(piece));\n\t\t\tpieceTranslation.pathsToValuesToTranslate.forEach((key) => {\n\t\t\t\ttranslateProperty(translatedPiece, key, target);\n\t\t\t});\n\t\t\treturn translatedPiece;\n\t\t} catch (err) {\n\t\t\tconsole.error(`error translating piece ${piece.name}:`, err);\n\t\t\treturn piece;\n\t\t}\n\t},\n\t/**Gets the piece metadata regardles of piece location (node_modules or dist), wasn't included inside piece.metadata() for backwards compatibility issues (if an old ap version installs a new piece it would fail)*/\n\tinitializeI18n: async (pieceOutputPath) => {\n\t\ttry {\n\t\t\tconst locales = Object.values(LocalesEnum);\n\t\t\tconst i18n = {};\n\t\t\tfor (const locale of locales) {\n\t\t\t\tconst translations = await readLocaleFile(locale, pieceOutputPath);\n\t\t\t\tif (translations) i18n[locale] = translations;\n\t\t\t}\n\t\t\treturn Object.keys(i18n).length > 0 ? i18n : void 0;\n\t\t} catch (err) {\n\t\t\tconsole.log(`Error initializing i18n for ${pieceOutputPath}:`, err);\n\t\t\treturn;\n\t\t}\n\t},\n\tpathsToValuesToTranslate: [\n\t\t\"description\",\n\t\t\"auth.username.displayName\",\n\t\t\"auth.username.description\",\n\t\t\"auth.password.displayName\",\n\t\t\"auth.password.description\",\n\t\t\"auth.props.*.displayName\",\n\t\t\"auth.props.*.description\",\n\t\t\"auth.props.*.options.options.*.label\",\n\t\t\"auth.description\",\n\t\t\"actions.*.displayName\",\n\t\t\"actions.*.description\",\n\t\t\"actions.*.props.*.displayName\",\n\t\t\"actions.*.props.*.description\",\n\t\t\"actions.*.props.*.options.options.*.label\",\n\t\t\"triggers.*.displayName\",\n\t\t\"triggers.*.description\",\n\t\t\"triggers.*.props.*.displayName\",\n\t\t\"triggers.*.props.*.description\",\n\t\t\"triggers.*.props.*.options.options.*.label\"\n\t]\n};\n/**This function translates a property inside a piece, i.e description, displayName, etc...\n*\n* @param pieceModelOrProperty - The piece model or property to translate\n* @param path - The path to the property to translate, i.e auth.username.displayName\n* @param i18n - The i18n object\n*/\nfunction translateProperty(pieceModelOrProperty, path, i18n) {\n\tconst parsedKeys = path.split(\".\");\n\tif (parsedKeys[0] === \"*\") return Object.values(pieceModelOrProperty).forEach((item) => translateProperty(item, parsedKeys.slice(1).join(\".\"), i18n));\n\tconst nextObject = pieceModelOrProperty[parsedKeys[0]];\n\tif (!nextObject) return;\n\tif (parsedKeys.length > 1) return translateProperty(nextObject, parsedKeys.slice(1).join(\".\"), i18n);\n\tconst valueInI18n = i18n[pieceModelOrProperty[parsedKeys[0]].slice(0, 512)];\n\tif (valueInI18n) pieceModelOrProperty[parsedKeys[0]] = valueInI18n;\n}\nasync function fileExists(filePath) {\n\ttry {\n\t\tawait fs.access(filePath);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\nconst readLocaleFile = async (locale, pieceOutputPath) => {\n\tconst filePath = path.join(pieceOutputPath, \"src\", \"i18n\", `${locale}.json`);\n\tif (!await fileExists(filePath)) return null;\n\ttry {\n\t\tconst fileContent = await fs.readFile(filePath, \"utf8\");\n\t\tconst translations = JSON.parse(fileContent);\n\t\tif (typeof translations === \"object\" && translations !== null) return translations;\n\t\tthrow new Error(`Invalid i18n file format for ${locale} in piece ${pieceOutputPath}`);\n\t} catch (error) {\n\t\tconsole.error(`Error reading i18n file for ${locale} in piece ${pieceOutputPath}:`, error);\n\t\treturn null;\n\t}\n};\n\n//#endregion\n//#region upstream/framework/lib/test/index.ts\nfunction createMockActionContext(params) {\n\treturn {\n\t\texecutionType: \"BEGIN\",\n\t\tauth: void 0,\n\t\tpropsValue: params.propsValue,\n\t\tstore: {\n\t\t\tput: async (key, value) => value,\n\t\t\tget: async () => null,\n\t\t\tdelete: async () => {}\n\t\t},\n\t\tconnections: { get: async () => null },\n\t\ttags: { add: async () => {} },\n\t\tserver: {\n\t\t\tapiUrl: \"http://localhost:3000\",\n\t\t\tpublicUrl: \"http://localhost:4200\",\n\t\t\ttoken: \"test-token\"\n\t\t},\n\t\tfiles: { write: async () => \"test-file-url\" },\n\t\toutput: { update: async () => {} },\n\t\tagent: { tools: async () => ({}) },\n\t\trun: {\n\t\t\tid: \"test-run-id\",\n\t\t\tstop: () => {},\n\t\t\tpause: () => {},\n\t\t\trespond: () => {}\n\t\t},\n\t\tproject: {\n\t\t\tid: \"test-project-id\",\n\t\t\texternalId: async () => void 0\n\t\t},\n\t\tflows: {\n\t\t\tlist: async () => ({\n\t\t\t\tdata: [],\n\t\t\t\tnext: null,\n\t\t\t\tprevious: null\n\t\t\t}),\n\t\t\tcurrent: {\n\t\t\t\tid: \"test-flow-id\",\n\t\t\t\tversion: { id: \"test-flow-version-id\" }\n\t\t\t}\n\t\t},\n\t\tstep: { name: \"test-step\" },\n\t\tgenerateResumeUrl: () => \"http://localhost:3000/resume\"\n\t};\n}\nfunction createMockPollingTriggerContext(params) {\n\treturn {\n\t\t...createMockActionContext({ propsValue: params.propsValue }),\n\t\tsetSchedule: (schedule) => {\n\t\t\tparams.onSetSchedule?.(schedule);\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/powerhouse/create.ts\nfunction createAction(params) {\n\tconst { requireReactor, ...rest } = params;\n\treturn withDeclaration(createAction$1(rest), requireReactor);\n}\nfunction createTrigger(params) {\n\tconst { requireReactor, ...rest } = params;\n\treturn withDeclaration(createTrigger$1(rest), requireReactor);\n}\nfunction withDeclaration(block, requireReactor) {\n\tif (requireReactor === void 0 || requireReactor === false) return block;\n\tif (requireReactor !== \"read\" && requireReactor !== \"write\") throw new Error(`requireReactor must be \"read\", \"write\" or false, got ${JSON.stringify(requireReactor)}`);\n\treturn Object.assign(block, { requireReactor });\n}\n\n//#endregion\n//#region src/powerhouse/property.ts\nconst Property = {\n\t...Property$1,\n\tDropdown(request) {\n\t\treturn Property$1.Dropdown(request);\n\t},\n\tMultiSelectDropdown(request) {\n\t\treturn Property$1.MultiSelectDropdown(request);\n\t},\n\tDynamicProperties(request) {\n\t\treturn Property$1.DynamicProperties(request);\n\t}\n};\n\n//#endregion\n//#region src/powerhouse/errors.ts\nconst ReactorJobPendingError = \"ReactorJobPendingError\";\nconst ReactorJobFailedError = \"ReactorJobFailedError\";\nconst ReactorActionsFailedError = \"ReactorActionsFailedError\";\nconst ReactorAccessDeniedError = \"ReactorAccessDeniedError\";\nconst ReactorRequestClosedError = \"ReactorRequestClosedError\";\nconst DocumentModelUnavailableError = \"DocumentModelUnavailableError\";\n\n//#endregion\nexport { ACTIVEPIECES_CHAT_TIERS, AGENT_STEP_TEST_TIMEOUT_MS, AGENT_STEP_TIMEOUT_MS, AIProviderModel, AIProviderName, AIProviderWithoutSensitiveData, AI_PROVIDER_CAPABILITIES, ActionBase, ActionClassification, AgentFlowTool, AgentKnowledgeBaseTool, AgentMcpTool, AgentOutputField, AgentOutputFieldType, AgentPieceProps, AgentStepBlock, AgentTaskStatus, AgentTool, AgentToolType, AiMetadata, ApFile, AppConnectionType, ArrayProperty, ArraySubProps, Audience, AzureProviderConfig, BaseAIProviderAuthConfig, BasePropertySchema, BasicAuthProperty, BasicAuthPropertyValue, BedrockProviderAuthConfig, BedrockProviderConfig, ChatFormResponse, CheckboxProperty, CloudflareGatewayProviderConfig, ContentBlockType, ContextVersion, CreateRecordsRequest, CreateTableWebhookRequest, CustomAuthProperty, CustomProperty, DEDUPE_KEY_PROPERTY, DEFAULT_CHAT_TIER_ID, DEFAULT_CONNECTION_DISPLAY_NAME, DateRangePreset, DateRangeProperty, DateRangeValue, DateTimeProperty, DocumentModelUnavailableError, DropdownOption, DropdownProperty, DropdownState, DynamicProp, DynamicProperties, DynamicPropsValue, ErrorHandlingOptionsParam, ExecutionToolStatus, ExecutionType, ExportTableResponse, FAIL_PARENT_ON_FAILURE_HEADER, Field, FieldType, FileProperty, FileResponseInterface, Filter, FilterOperator, FlowStatus, FlowTriggerType, GetProviderConfigResponse, HumanInputFormResult, HumanInputFormResultTypes, IAction, ITrigger, InputProperty, InputPropertyMap, JsonProperty, KnowledgeBaseSourceType, LATEST_CONTEXT_VERSION, ListRecordsRequest, ListTablesRequest, LongTextProperty, MINIMUM_SUPPORTED_RELEASE_AFTER_LATEST_CONTEXT_VERSION, MarkdownContentBlock, MarkdownVariant, McpAuthConfig, McpAuthType, McpProperty, McpPropertyType, McpProtocol, McpTrigger, MultiSelectDropdownProperty, NumberProperty, OAuth2AuthorizationMethod, OAuth2GrantType, OAuth2Property, OAuth2PropertyValue, OAuth2Props, OIDCProperty, OPENAI_COMPATIBLE_VENDOR_BASE_URLS, ObjectProperty, OpenAICompatibleProviderConfig, OpenAiCompatibleVendorConfig, PARENT_RUN_ID_HEADER, Piece, PieceAuth, PieceAuthProperty, PieceBase, PieceCategory, PieceMetadata, PieceMetadataModel, PieceMetadataModelSummary, PieceMetadataSummary, PiecePackageInformation, PieceProperty, PiecePropertyMap, PieceServerContextError, PopulatedRecord, Project, ProjectAIProvider, Property, PropertyGroup, PropertyGroupDisplay, PropertyType, RAW_PAYLOAD_HEADER, READ_ONLY_CLASSIFICATIONS, ReactorAccessDeniedError, ReactorActionsFailedError, ReactorJobFailedError, ReactorJobPendingError, ReactorRequestClosedError, RichTextProperty, SecretTextProperty, SeekPage, ShortTextProperty, StaticDropdownEmptyOption, StaticDropdownProperty, StaticMultiSelectDropdownProperty, StopResponse, StoreScope, TASK_COMPLETION_TOOL_NAME, Table, TableWebhookEventType, ToolCallContentBlock, ToolCallStatus, ToolCallType, TriggerBase, TriggerStrategy, USE_DRAFT_QUERY_PARAM_NAME, UpdateRecordRequest, VertexProviderAuthConfig, VertexProviderConfig, WebhookHandshakeStrategy, WebhookRenewConfiguration, WebhookRenewStrategy, apId, assertNotNullOrUndefined, backwardCompatabilityContextUtils, buildAuthHeaders, camelCase, chunk, createAction, createKeyForFormInput, createMockActionContext, createMockPollingTriggerContext, createPiece, createTrigger, dateRangeUtils, getAuthPropertyForValue, getEffectiveProviderAndModel, isEmpty, isNil, isNotUndefined, isPieceServerContextError, isReadOnlyClassification, isString, kebabCase, mcpToolNameUtils, normalizeToolOutputToExecuteResponse, pickBy, piecePropertiesUtils, pieceTranslation, splitCloudflareGatewayModelId, spreadIfDefined, startCase, tryCatch, unique };\n//# sourceMappingURL=index.js.map","// Their StoreScope, as a name the host can partition on.\nimport { StoreScope } from \"@powerhousedao/pieces-framework\";\n\n// The enum's PROJECT member carries the legacy value \"COLLECTION\", and an\n// omitted scope means FLOW, so both are folded to one name here.\nexport type StoreScopeName = keyof typeof StoreScope;\n\n// Compared by value, never by enum identity: a piece bundle inlines its own\n// copy of StoreScope, and some pass the member name instead of its value.\nexport function normalizeStoreScope(scope?: unknown): StoreScopeName {\n return scope === StoreScope.PROJECT || scope === \"PROJECT\"\n ? \"PROJECT\"\n : \"FLOW\";\n}\n","// Our ActionContext → their ActionContext (doc 06 §2.8). Implements the top usage\n// tier (propsValue, auth, store, connections); the rest throws loudly, named.\nimport { throwingStub, withTouchTracking } from \"./stubs.js\";\nimport { jsonSafe } from \"../worker/json-safe.js\";\nimport { normalizeStoreScope, type StoreScopeName } from \"./store-scope.js\";\nimport type { ApFilesService } from \"./files.js\";\nimport type { ConnectionsProvider } from \"./props.js\";\nimport type { ReactorOption } from \"./reactor-option.js\";\nimport type {\n BaseContext,\n ConnectionsManager,\n ExecutionType,\n FilesService,\n FlowsContext,\n InputPropertyMap,\n OutputContext,\n ReactorClient,\n ReactorReadClient,\n RunContext,\n ServerContext,\n StepContext,\n Store,\n TagsManager,\n} from \"@powerhousedao/pieces-framework\";\n\nexport { UnsupportedContextMemberError } from \"./stubs.js\";\n\n// The scope travels beside the key rather than inside it: which partition a\n// key belongs to is the host's decision, not a naming convention.\n\n// The host's half of the framework's Store, with its generics dropped: a\n// durable store round-trips through JSON, so nothing comes back as the T put in.\nexport interface KeyValueStore {\n put(key: string, value: unknown, scope?: StoreScopeName): Promise<unknown>;\n get(key: string, scope?: StoreScopeName): Promise<unknown>;\n delete(key: string, scope?: StoreScopeName): Promise<void>;\n}\n\n// In-memory connection registry: key → resolved connection value.\nexport class InMemoryConnectionsProvider implements ConnectionsProvider {\n private readonly values: Map<string, unknown>;\n\n constructor(values: Record<string, unknown> = {}) {\n this.values = new Map(Object.entries(values));\n }\n\n set(key: string, value: unknown): void {\n this.values.set(key, value);\n }\n\n get(key: string): Promise<unknown> {\n return Promise.resolve(this.values.get(key) ?? null);\n }\n}\n\nexport class InMemoryKeyValueStore implements KeyValueStore {\n private readonly entries: Map<string, unknown>;\n\n constructor(seed: Record<string, unknown> = {}) {\n this.entries = new Map(Object.entries(seed));\n }\n\n snapshot(): Record<string, unknown> {\n return Object.fromEntries(this.entries);\n }\n\n // Flattened like the durable store, so the heap fallback is not the one\n // place a Date survives a put.\n put(key: string, value: unknown, scope?: StoreScopeName): Promise<unknown> {\n const stored = jsonSafe(value);\n this.entries.set(this.scoped(key, scope), stored);\n return Promise.resolve(stored);\n }\n\n get(key: string, scope?: StoreScopeName): Promise<unknown> {\n return Promise.resolve(this.entries.get(this.scoped(key, scope)) ?? null);\n }\n\n delete(key: string, scope?: StoreScopeName): Promise<void> {\n this.entries.delete(this.scoped(key, scope));\n return Promise.resolve();\n }\n\n // One heap, so the scopes share it and are kept apart by name.\n private scoped(key: string, scope?: StoreScopeName): string {\n return scope === \"PROJECT\" ? `PROJECT:${key}` : key;\n }\n}\n\nexport interface ActionContextIdentity {\n runId?: string;\n projectId?: string;\n flowId?: string;\n flowVersionId?: string;\n stepName?: string;\n}\n\nexport type ActionContextOptions = ActionContextBaseOptions & ReactorOption;\n\ninterface ActionContextBaseOptions {\n propsValue: Record<string, unknown>;\n auth?: unknown;\n store?: KeyValueStore;\n // ctx.files for actions. Mirrors the option triggers already accept; when\n // omitted the member keeps throwing, so a piece that needs files fails\n // loudly rather than silently dropping them.\n files?: ApFilesService;\n connections?: ConnectionsProvider;\n // ctx.output.update, the piece's own progress report. Omitted, the member\n // throws, so a piece that depends on it fails by name rather than silently.\n output?: { update(output: unknown): Promise<void> };\n // ctx.resumePayload, the delivery that woke a RESUME run. This engine never\n // suspends a run, so no request carries one yet; omitted, the member throws\n // by name instead of reading as undefined.\n resumePayload?: unknown;\n executionType?: `${ExecutionType}`;\n identity?: ActionContextIdentity;\n onTouch?: (member: string) => void;\n}\n\n// Shape of the context we hand to `action.run()`: the framework's ActionContext\n// member for member. Those beyond the implemented tier throw, named.\nexport interface BuiltApActionContext {\n executionType: `${ExecutionType}`;\n auth: unknown;\n propsValue: Record<string, unknown>;\n store: Store;\n connections: ConnectionsManager;\n tags: TagsManager;\n server: ServerContext;\n files: FilesService;\n output: OutputContext;\n reactor: ReactorClient | ReactorReadClient;\n // The RESUME branch of the framework's ActionContext promises this\n // (ResumePayload there, a type its entry does not export). Always present,\n // real or throwing, like `reactor`.\n resumePayload: unknown;\n // Carried by the framework's own test double but absent from its types.\n agent: { tools: unknown[] };\n run: RunContext;\n project: BaseContext<undefined, InputPropertyMap>[\"project\"];\n flows: FlowsContext;\n step: StepContext;\n generateResumeUrl(params: {\n queryParams: Record<string, string>;\n sync?: boolean;\n }): string;\n}\n\nexport interface ActionContextHandle {\n context: BuiltApActionContext;\n // Top-level members the piece read; `UNDOCUMENTED:<name>` marks unknown reads.\n touched: ReadonlySet<string>;\n}\n\nexport function buildActionContext(\n options: ActionContextOptions,\n): ActionContextHandle {\n const { identity = {} } = options;\n const store = options.store ?? new InMemoryKeyValueStore();\n const touched = new Set<string>();\n\n const base: Record<string, unknown> = {\n executionType: options.executionType ?? \"BEGIN\",\n auth: options.auth,\n propsValue: options.propsValue,\n store: {\n put: (key: string, value: unknown, scope?: unknown) =>\n store.put(key, value, normalizeStoreScope(scope)),\n get: (key: string, scope?: unknown) =>\n store.get(key, normalizeStoreScope(scope)),\n delete: (key: string, scope?: unknown) =>\n store.delete(key, normalizeStoreScope(scope)),\n },\n connections: options.connections ?? throwingStub(\"connections\"),\n tags: throwingStub(\"tags\"),\n server: throwingStub(\"server\"),\n files: options.files ?? throwingStub(\"files\"),\n output: options.output ?? throwingStub(\"output\"),\n reactor: options.reactor ?? throwingStub(\"reactor\"),\n resumePayload: options.resumePayload ?? throwingStub(\"resumePayload\"),\n agent: throwingStub(\"agent\"),\n run: {\n id: identity.runId ?? \"run\",\n stop: throwingStub(\"run.stop\"),\n pause: throwingStub(\"run.pause\"),\n respond: throwingStub(\"run.respond\"),\n createWaitpoint: throwingStub(\"run.createWaitpoint\"),\n waitForWaitpoint: throwingStub(\"run.waitForWaitpoint\"),\n },\n project: {\n id: identity.projectId ?? \"project\",\n externalId: () => Promise.resolve(identity.projectId ?? \"project\"),\n },\n flows: {\n list: throwingStub(\"flows.list\"),\n current: {\n id: identity.flowId ?? \"flow\",\n version: { id: identity.flowVersionId ?? \"flow-version\" },\n },\n },\n step: { name: identity.stepName ?? \"step\" },\n generateResumeUrl: throwingStub(\"generateResumeUrl\"),\n };\n\n const context = withTouchTracking(base, touched, options.onTouch);\n return { context: context as unknown as BuiltApActionContext, touched };\n}\n","import type { ActionContextIdentity } from \"../context/action.js\";\nimport type { StagedFile } from \"../context/files.js\";\nimport type { PropsValidationErrors } from \"../context/normalize.js\";\nimport type {\n ExecutionType,\n ServerContext,\n} from \"@powerhousedao/pieces-framework\";\nimport type { RecordedListener, RecordedSchedule } from \"../context/trigger.js\";\n\n// One FILE-prop value the host resolved to a path before the run, so the\n// bytes reach the worker through the shared filesystem instead of JSON IPC.\nexport interface StagedInput {\n ref: string;\n path: string;\n fileName?: string;\n contentType?: string;\n // Why the host could not stage it; a FILE prop that needs it fails with this.\n error?: string;\n}\n\n// Where a piece may connect to while this request runs. Enforced in the child\n// at socket-connect time; absent means unrestricted, which is the old behaviour.\nexport interface EgressPolicy {\n // Hostnames (or literal IPs) the piece may reach; a leading \"*.\" matches\n // subdomains. Omitted or empty allows any host the address rules permit.\n allowHosts?: string[];\n // Addresses or CIDRs reachable even though they are private — a service on\n // the operator's own network, say.\n allowAddresses?: string[];\n // Lifts the private-address block, for an operator whose isolation lives\n // elsewhere. Local sockets, UDP and listening stay refused under any policy.\n allowPrivateAddresses?: boolean;\n // TCP ports the piece may reach; omitted or empty allows any.\n allowPorts?: number[];\n}\n\n// The child is forked with an empty env, so what the host's environment decides\n// can only arrive on the wire: every request carries what is in force for the\n// work it asks for.\nexport interface HostScopedRequest {\n egress?: EgressPolicy;\n // Ceiling for FILE-prop hydration and ctx.files.write, from the host's\n // PH_WORKFLOWS_PIECE_MAX_FILE_BYTES. Absent leaves the built-in default.\n maxFileBytes?: number;\n // Epoch ms at which the host kills the worker for this request.\n deadline?: number;\n // Cap on each host call. Absent leaves the built-in default.\n hostCallTimeoutMs?: number;\n}\n\n// `ctx.reactor` for one request: its RPC messages carry `requestId`, and the\n// host serves them only while the request is in flight.\nexport interface ReactorRequestBinding {\n requestId: string;\n requireReactor: \"read\" | \"write\";\n}\n\nexport interface ReactorScopedRequest {\n // Stamped by PieceWorker when the caller serves the reactor.\n reactor?: ReactorRequestBinding;\n}\n\nexport const REACTOR_RPC = \"reactor-rpc\";\nexport const MODEL_MANIFEST = \"model-manifest\";\n// Host call: a type's entries, or every entry the host knows without one.\nexport const MODEL_ENTRIES = \"model-entries\";\n\n// One reactor RPC message (`@powerhousedao/reactor/rpc`), either direction.\nexport interface ReactorRpcEnvelope {\n type: typeof REACTOR_RPC;\n requestId: string;\n message: unknown;\n}\n\n// Importable document models (the reactor's ModelManifestEntry), host to child\n// on fork. A type loaded later is looked up through MODEL_ENTRIES.\nexport interface ModelEntriesPayload {\n documentType?: string;\n}\n\nexport interface ModelManifestMessage {\n type: typeof MODEL_MANIFEST;\n entries: unknown[];\n}\n\n// Where the worker finds the piece module: a bundle directory in npm shape, as\n// a registry fetch extracts it, or the module file of an installed package.\n\n// Exactly one is set; a request carrying neither is refused before any load.\nexport interface PieceModuleRef {\n bundleDir?: string;\n entryPath?: string;\n}\n\nexport interface RunActionRequest\n extends HostScopedRequest, PieceModuleRef, ReactorScopedRequest {\n actionName: string;\n propsValue: Record<string, unknown>;\n auth?: unknown;\n // Where ctx.files.write() puts bytes for the host to ingest. Without it the\n // action gets the data-URI service instead.\n stagingDir?: string;\n // Attachment refs in propsValue, already materialized by the host.\n stagedInputs?: StagedInput[];\n // Resolved connection values served to ctx.connections.get(key).\n connections?: Record<string, unknown>;\n // Store partition; runs sharing a scope share state for the worker's lifetime.\n storeScope?: string;\n // Serve `ctx.store` from the host over the call channel instead of the\n // in-memory partition above, so a write survives this worker.\n durableStore?: boolean;\n // Forward the piece's console output to the host as it is written. Off by\n // default: a chatty piece would otherwise pay IPC for logs nobody reads.\n captureLogs?: boolean;\n // Implement `ctx.output.update`, which reports progress mid-step. Without\n // it the member keeps throwing, so a piece that needs it fails loudly.\n liveOutput?: boolean;\n executionType?: `${ExecutionType}`;\n // The delivery that woke a RESUME run, served as ctx.resumePayload. This\n // engine never suspends a run, so nothing sets it yet; absent, the context\n // member keeps throwing by name.\n resumePayload?: unknown;\n // Call the action's test method instead of run, as a single-step test does.\n stepTest?: boolean;\n identity?: ActionContextIdentity;\n // Concrete secret values resolved for this step, so the child can strip them\n // from an error before it crosses back; they already travel inside `auth`.\n redactValues?: string[];\n}\n\nexport interface RunMessage {\n id: number;\n type: \"run\";\n request: RunActionRequest;\n}\n\n// Design-time resolution of a DROPDOWN options() / DYNAMIC props() resolver.\nexport interface ResolveOptionsRequest\n extends HostScopedRequest, PieceModuleRef, ReactorScopedRequest {\n // Action or trigger name, per kind (default \"action\").\n actionName: string;\n kind?: \"action\" | \"trigger\";\n propName: string;\n refresherValues?: Record<string, unknown>;\n auth?: unknown;\n searchValue?: string;\n // ctx.project.id, the same one a run of the piece is handed.\n projectId?: string;\n}\n\nexport interface ResolveOptionsMessage {\n id: number;\n type: \"resolve-options\";\n request: ResolveOptionsRequest;\n}\n\n// One trigger lifecycle hook. With `durableStore` its `ctx.store` is the same\n// host-served store an action gets, so a write lands as the hook makes it.\n\n// Without one it runs statelessly: `storeState` seeds an in-memory store and\n// the whole snapshot comes back in the response for the caller to persist.\nexport interface TriggerHookRequest\n extends HostScopedRequest, PieceModuleRef, ReactorScopedRequest {\n triggerName: string;\n hook: \"onEnable\" | \"onDisable\" | \"run\" | \"test\" | \"onHandshake\" | \"onRenew\";\n propsValue: Record<string, unknown>;\n auth?: unknown;\n storeState?: Record<string, unknown>;\n // Serve `ctx.store` from the host over the call channel, exactly as\n // RunActionRequest does, instead of seeding and returning the snapshot above.\n durableStore?: boolean;\n identity?: ActionContextIdentity;\n // onEnable of an unchanged trigger; pollingHelper keeps its cursor.\n isRepublish?: boolean;\n // WEBHOOK payloads; also handed to test runs.\n payload?: unknown;\n webhookUrl?: string;\n server?: ServerContext;\n // As on a run request: secrets stripped from errors before they cross back.\n redactValues?: string[];\n}\n\nexport interface TriggerHookMessage {\n id: number;\n type: \"trigger-hook\";\n request: TriggerHookRequest;\n}\n\n// A connection credential check. Auth crosses into the worker and stays\n// there: the piece code that reads it never runs in the host process.\nexport interface CheckConnectionRequest\n extends HostScopedRequest, PieceModuleRef {\n auth?: unknown;\n}\n\nexport interface CheckConnectionMessage {\n id: number;\n type: \"check-connection\";\n request: CheckConnectionRequest;\n}\n\n// `output` of a check-connection result.\nexport interface CheckConnectionOutcome {\n // False when the piece's auth declares no validate.\n declared: boolean;\n // validate's verdict; true when none is declared.\n valid: boolean;\n // Why validate failed, when it said so.\n detail?: string;\n // getConnectionIdentifier's label; it runs only once the check passes.\n accountLabel?: string;\n // Why getConnectionIdentifier threw. The check still passes.\n identifierError?: string;\n}\n\n// Design-time descriptor of a piece: its actions, triggers and auth shape.\n// Building one requires the piece module, whose top-level code runs on load,\n// so it is built in the worker and only the plain descriptor crosses back.\nexport interface DescribePieceRequest\n extends HostScopedRequest, PieceModuleRef {\n // Carried through into the descriptor's `source` and its resolver ids.\n packageName: string;\n version: string;\n}\n\nexport interface DescribePieceMessage {\n id: number;\n type: \"describe\";\n request: DescribePieceRequest;\n}\n\nexport type WorkerRequestMessage =\n | RunMessage\n | ResolveOptionsMessage\n | TriggerHookMessage\n | CheckConnectionMessage\n | DescribePieceMessage;\n\n// Piece errors cross the IPC boundary as data; classify on these fields.\nexport interface SerializedPieceError {\n name: string;\n message: string;\n // The error's own enumerable properties, plus the HTTP status, request and\n // response the framework's error formatter recovered from it.\n properties: Record<string, unknown>;\n // Set when the piece hit an unimplemented context member.\n unsupportedMember?: string;\n // Set when the piece or trigger uses a feature this engine does not run.\n unsupportedFeature?: string;\n // Set when the props failed validation, before piece code ran.\n invalidProps?: PropsValidationErrors;\n}\n\nexport interface ResultResponse {\n id: number;\n type: \"result\";\n output: unknown;\n touched: string[];\n // True when the piece set NODE_TLS_REJECT_UNAUTHORIZED=0 (contained to the worker).\n tlsPoisoned: boolean;\n // Files the piece wrote through ctx.files during this request. The host\n // ingests each one, then rewrites its provisional token in `output`.\n files?: StagedFile[];\n // trigger-hook only: final store contents plus captured context calls.\n storeState?: Record<string, unknown>;\n schedules?: RecordedSchedule[];\n listeners?: RecordedListener[];\n timings?: WorkerTimings;\n}\n\nexport interface ErrorResponse {\n id: number;\n type: \"error\";\n error: SerializedPieceError;\n tlsPoisoned: boolean;\n timings?: WorkerTimings;\n}\n\n// One part of serving a request, in epoch ms: piece.load, reactor.open,\n// models, action.\nexport interface WorkerPhaseTiming {\n name: string;\n start: number;\n end: number;\n // The phase this one ran inside, e.g. \"action\" for a model loaded mid-action.\n parent?: string;\n attributes?: Record<string, string | boolean>;\n}\n\n// Where a request's time went inside the child, in epoch ms.\nexport interface WorkerTimings {\n received: number;\n sent: number;\n phases: WorkerPhaseTiming[];\n // When the child's entry finished loading; on its first response only.\n ready?: number;\n // The child's process.memoryUsage() as it answered, in bytes.\n memory?: WorkerMemory;\n}\n\nexport interface WorkerMemory {\n rss: number;\n heapUsed: number;\n heapTotal: number;\n external: number;\n}\n\nexport type WorkerResponse = ResultResponse | ErrorResponse;\n\n// A request the child makes of its host while a step is running: the reverse\n// direction of everything above, and the only way a piece reaches durable state.\n\n// Ids are the child's own counter, a separate space from the host's, which is\n// why every handler dispatches on `type` before comparing an id.\nexport interface HostCallMessage {\n id: number;\n type: \"host-call\";\n method: string;\n payload: unknown;\n}\n\n// `error` carries the failure as data: a rejected promise cannot cross IPC,\n// so the reply always arrives and the child rethrows.\nexport interface HostCallResponse {\n id: number;\n type: \"host-result\";\n value?: unknown;\n error?: string;\n}\n\n// What the host will answer for the request in flight. Registered per request,\n// so a call arriving after the step returned finds nothing and is refused.\nexport type HostCallHandlers = Record<\n string,\n (payload: unknown) => Promise<unknown>\n>;\n\n// The one-way half of the channel: a report the host may act on, with no\n// answer to wait for. Their engine splits the same way (rpc vs rpc-notify).\n\n// A tap must never stall the step, so these carry no id and no reply. Node's\n// IPC preserves order, which is what drains them before the result lands.\nexport interface HostNotifyMessage {\n type: \"host-notify\";\n method: string;\n payload: unknown;\n}\n\n// Handlers registered per request, like HostCallHandlers. A throw here is\n// swallowed: a failed tap must not fail the step it was reporting on.\nexport type HostNotifyHandlers = Record<string, (payload: unknown) => void>;\n\n// One console call the piece made, already flattened to a string in the child.\nexport interface PieceLogEntry {\n level: \"log\" | \"info\" | \"warn\" | \"error\" | \"debug\";\n message: string;\n at: number;\n}\n\nexport const LOG_WRITE = \"log.write\";\nexport const OUTPUT_UPDATE = \"output.update\";\n\n// A store call carries `{ key, value?, scope }`. The scope is a name the host\n// partitions on, never a prefix the child bakes into the key.\nexport const STORE_GET = \"store.get\";\nexport const STORE_PUT = \"store.put\";\nexport const STORE_DELETE = \"store.delete\";\n","// \"Nobody knows whether that write landed\", as a property an error carries.\n//\n// A step whose host call wrote something and then did not get an answer in\n// time is neither a success nor a failure, and reporting it as FAILED is a\n// claim nobody can stand behind — which is what the 10s host-call cap was\n// doing to a reactor dispatch under load (backlog item 6).\n//\n// The marker is an ENUMERABLE OWN PROPERTY rather than a class, because the\n// error is usually thrown in the forked child and reaches the coordinator as a\n// `SerializedPieceError`: a name, a message, and the error's own enumerable\n// properties. The class does not survive; the property does.\n//\n// The reactor RPC keeps only an error's name and message, so a reactor job\n// still unfinished at the step deadline is recognised by its name.\nimport { ReactorJobPendingError } from \"@powerhousedao/pieces-framework\";\n\n/** The property name, so both sides spell it once. */\nexport const INDETERMINATE_FLAG = \"indeterminate\";\n\n/** Marks an error as indeterminate, in place. */\nexport function markIndeterminate<T extends Error>(error: T): T {\n Object.defineProperty(error, INDETERMINATE_FLAG, {\n value: true,\n enumerable: true,\n writable: false,\n configurable: false,\n });\n return error;\n}\n\nconst INDETERMINATE_NAMES: ReadonlySet<string> = new Set([\n ReactorJobPendingError,\n]);\n\nfunction named(value: unknown): boolean {\n if (typeof value !== \"object\" || value === null) return false;\n const name = (value as { name?: unknown }).name;\n return typeof name === \"string\" && INDETERMINATE_NAMES.has(name);\n}\n\nfunction flagged(value: unknown): boolean {\n if (typeof value !== \"object\" || value === null) return false;\n return (value as Record<string, unknown>)[INDETERMINATE_FLAG] === true;\n}\n\n/**\n * Whether this error means \"the write may have landed\".\n *\n * Three places to look, in the order the error can reach us: the error itself\n * (thrown in the reactor process), the `properties` record of the\n * `SerializedPieceError` a `PieceWorkerError` carries (thrown in the child),\n * and the `cause` chain (a piece that wrapped it).\n */\nexport function isIndeterminateError(error: unknown): boolean {\n if (flagged(error) || named(error)) return true;\n const serialized = (\n error as { serialized?: { name?: unknown; properties?: unknown } }\n )?.serialized;\n if (flagged(serialized?.properties) || named(serialized)) return true;\n const cause = (error as { cause?: unknown })?.cause;\n return (\n cause !== undefined && cause !== error && (flagged(cause) || named(cause))\n );\n}\n","// The child's half of the call channel: how piece code reaches durable host\n// state mid-step, instead of handing everything back when the step returns.\n\n// Modelled on their engine RPC (createRpcClient): a method name, a payload, an\n// id, and failures returned as data rather than thrown across the boundary.\nimport { markIndeterminate } from \"../indeterminate.js\";\nimport { STORE_DELETE, STORE_PUT, type HostCallResponse } from \"./protocol.js\";\n\n// A host call is a local IPC round trip, so ten seconds is pathological in the\n// ordinary case. It was not in the field: a reactor dispatch under load, or a\n// store write behind a saturated PGlite, outran it and the step was reported\n// FAILED for a write that had in fact been committed (backlog item 6). The cap\n// is now the host's to set (PH_WORKFLOWS_HOST_CALL_TIMEOUT_MS, and never\n// shorter than the step's own timeoutSeconds), and a mutating call that does\n// time out is INDETERMINATE rather than failed.\nexport const DEFAULT_HOST_CALL_TIMEOUT_MS = 10_000;\n\n/**\n * The host calls that may have committed something by the time they time out.\n *\n * A read that times out is just a read that did not answer. A write is not:\n * the host may have written and simply not got the answer back in time, so\n * reporting it as a failure is a claim nobody can stand behind. Reactor writes\n * go over the reactor RPC, not a host call; their unconfirmed outcome is\n * recognised by error name instead (`../indeterminate.ts`).\n */\nexport const MUTATING_HOST_CALLS: readonly string[] = [STORE_PUT, STORE_DELETE];\n\n// Set per request from the wire; requests are serialized per worker.\nlet fromWire: number | undefined;\n// The request's kill deadline, less a margin to report a timeout before it.\nlet stopAt: number | undefined;\n\nconst MIN_DEADLINE_MARGIN_MS = 250;\nconst MAX_DEADLINE_MARGIN_MS = 2_000;\n\nfunction deadlineMargin(budgetMs: number): number {\n return Math.min(\n Math.max(Math.floor(budgetMs / 10), MIN_DEADLINE_MARGIN_MS),\n MAX_DEADLINE_MARGIN_MS,\n );\n}\n\nexport function setHostCallTimeout(\n timeoutMs: number | undefined,\n deadline?: number,\n): void {\n fromWire = timeoutMs;\n stopAt =\n deadline === undefined\n ? undefined\n : deadline - deadlineMargin(deadline - Date.now());\n}\n\nexport function hostCallTimeoutMs(): number {\n return fromWire ?? DEFAULT_HOST_CALL_TIMEOUT_MS;\n}\n\ninterface Pending {\n method: string;\n resolve: (value: unknown) => void;\n reject: (error: Error) => void;\n timer: NodeJS.Timeout;\n}\n\nconst pending = new Map<number, Pending>();\nlet nextId = 1;\nlet listening = false;\n\nexport class HostCallError extends Error {\n constructor(method: string, detail: string) {\n super(`Host call \"${method}\" failed: ${detail}`);\n this.name = \"HostCallError\";\n }\n}\n\n/** A read-ish host call that did not answer. An ordinary failure. */\nexport class HostCallTimeoutError extends Error {\n constructor(method: string, timeoutMs: number) {\n super(`Host call \"${method}\" got no answer within ${timeoutMs}ms`);\n this.name = \"HostCallTimeoutError\";\n }\n}\n\n/**\n * A WRITING host call that did not answer: the write may have landed.\n *\n * Marked indeterminate (`../indeterminate.ts`), which is what survives the\n * worker boundary — this is thrown in the forked child, where the class does\n * not cross but the error's own enumerable properties do.\n */\nexport const INDETERMINATE_ERROR_NAME = \"HostCallIndeterminateError\";\n\nexport class HostCallIndeterminateError extends Error {\n constructor(method: string, timeoutMs: number) {\n super(\n `Host call \"${method}\" got no answer within ${timeoutMs}ms; it writes, ` +\n \"so whether it was committed is unknown and the step is neither a \" +\n \"success nor a failure\",\n );\n this.name = INDETERMINATE_ERROR_NAME;\n markIndeterminate(this);\n }\n}\n\nfunction timeoutError(method: string, timeoutMs: number): Error {\n return MUTATING_HOST_CALLS.includes(method)\n ? new HostCallIndeterminateError(method, timeoutMs)\n : new HostCallTimeoutError(method, timeoutMs);\n}\n\nfunction isHostCallResponse(value: unknown): value is HostCallResponse {\n return (\n typeof value === \"object\" &&\n value !== null &&\n (value as { type?: unknown }).type === \"host-result\"\n );\n}\n\n// Registered once, on the same channel the job messages arrive on. The job\n// dispatcher ignores `host-result` because it only knows its own request types.\nfunction ensureListening(): void {\n if (listening) return;\n listening = true;\n process.on(\"message\", (message: unknown) => {\n if (!isHostCallResponse(message)) return;\n const entry = pending.get(message.id);\n if (!entry) return;\n pending.delete(message.id);\n clearTimeout(entry.timer);\n if (message.error !== undefined) {\n entry.reject(new HostCallError(entry.method, message.error));\n return;\n }\n entry.resolve(message.value);\n });\n}\n\nexport function callHost<T = unknown>(\n method: string,\n payload: unknown,\n timeoutMs: number = hostCallTimeoutMs(),\n): Promise<T> {\n if (!process.send) {\n return Promise.reject(\n new HostCallError(method, \"the worker has no channel to its host\"),\n );\n }\n // Clipped to the step deadline: a call still waiting when the worker is\n // killed would surface as a retryable worker timeout, even for a write.\n const budgetMs =\n stopAt === undefined ? timeoutMs : Math.min(timeoutMs, stopAt - Date.now());\n if (budgetMs <= 0) {\n return Promise.reject(new HostCallTimeoutError(method, 0));\n }\n ensureListening();\n const id = nextId++;\n return new Promise<T>((resolve, reject) => {\n const timer = setTimeout(() => {\n pending.delete(id);\n reject(timeoutError(method, budgetMs));\n }, budgetMs);\n pending.set(id, {\n method,\n resolve: resolve as (value: unknown) => void,\n reject,\n timer,\n });\n process.send?.({ id, type: \"host-call\", method, payload });\n });\n}\n\n// Test seam: a worker replaced between suites must not inherit pending calls.\nexport function resetHostCalls(): void {\n for (const entry of pending.values()) clearTimeout(entry.timer);\n pending.clear();\n}\n\n// The one-way half: a report with no answer to wait for. It cannot fail from\n// the piece's side, so a missing channel is dropped rather than raised.\nexport function notifyHost(method: string, payload: unknown): void {\n try {\n process.send?.({ type: \"host-notify\", method, payload });\n } catch {\n // `process.send` stays defined after the channel closes and throws. A tap\n // that threw here would be a tap that changed the step.\n }\n}\n","// `ctx.store` served by the host, one call per operation, so a value a piece\n// writes is durable the moment it writes it rather than when the step ends.\n\n// This is the semantic Activepieces pieces are written against — theirs is an\n// HTTP call per get/put/delete — so a loop that checkpoints its cursor resumes.\nimport type { KeyValueStore } from \"./action.js\";\nimport type { StoreScopeName } from \"./store-scope.js\";\nimport { STORE_DELETE, STORE_GET, STORE_PUT } from \"../worker/protocol.js\";\nimport { callHost } from \"../worker/host-call.js\";\nimport { jsonSafe } from \"../worker/json-safe.js\";\n\n// The host writes JSON, so a value is flattened here rather than at the point\n// it lands. A piece that stores a Date reads back a string either way, whether\n// or not a durable store is configured — and whatever carries the message.\nexport class RemoteKeyValueStore implements KeyValueStore {\n async put(\n key: string,\n value: unknown,\n scope?: StoreScopeName,\n timeoutMs?: number,\n ): Promise<unknown> {\n const stored = jsonSafe(value);\n await callHost(STORE_PUT, { key, value: stored, scope }, timeoutMs);\n return stored;\n }\n\n get(key: string, scope?: StoreScopeName): Promise<unknown> {\n return callHost(STORE_GET, { key, scope });\n }\n\n async delete(key: string, scope?: StoreScopeName): Promise<void> {\n await callHost(STORE_DELETE, { key, scope });\n }\n}\n","// ctx.output.update: the piece reporting progress before it returns. A long\n// step is otherwise opaque until the moment it finishes.\nimport { notifyHost } from \"../worker/host-call.js\";\nimport { jsonSafe } from \"../worker/json-safe.js\";\nimport { OUTPUT_UPDATE } from \"../worker/protocol.js\";\n\nexport interface PartialOutput {\n update(output: unknown): Promise<void>;\n}\n\n// Resolves immediately: a tap the step waits on is a tap that can stall it,\n// which is the one thing plan/08 §7.8 rules out.\n\n// A notification carries no request id, and the worker is reused. A piece that\n// keeps `ctx` and updates from a timer would otherwise report progress against\n// whichever step is running by then, so the tap is closed when its step ends.\nexport class RemoteOutput implements PartialOutput {\n private open = true;\n\n update(output: unknown): Promise<void> {\n if (this.open) notifyHost(OUTPUT_UPDATE, jsonSafe(output));\n return Promise.resolve();\n }\n\n close(): void {\n this.open = false;\n }\n}\n","// Piece console output, forwarded to the host while the step runs. The child\n// is forked with its stdio discarded, so without this a piece's logs vanish.\nimport { format } from \"node:util\";\nimport { notifyHost } from \"./host-call.js\";\nimport { LOG_WRITE, type PieceLogEntry } from \"./protocol.js\";\n\n// A runaway piece can log in a loop; the channel is shared with the step's own\n// result, so both the size of an entry and the number of them are capped.\n\n// Without the count, a loop enqueues IPC messages faster than the host drains\n// them and the result waits behind the backlog until the step times out.\nconst MAX_MESSAGE_LENGTH = 8_192;\nconst MAX_ENTRIES_PER_REQUEST = 1_000;\n\nconst LEVELS = [\"log\", \"info\", \"warn\", \"error\", \"debug\"] as const;\n\ntype Level = (typeof LEVELS)[number];\n\n// Installs the patch for one request and returns its undo. Logs written after\n// the step returned belong to no step, which is why the scope is this narrow.\nexport function captureConsole(): () => void {\n const original = new Map<Level, (...args: unknown[]) => void>();\n let sent = 0;\n\n for (const level of LEVELS) {\n const previous = console[level] as (...args: unknown[]) => void;\n original.set(level, previous);\n console[level] = (...args: unknown[]) => {\n if (sent > MAX_ENTRIES_PER_REQUEST) return;\n sent += 1;\n // The last one says why the rest are missing, so a truncated log does\n // not read as a step that fell silent.\n const message =\n sent > MAX_ENTRIES_PER_REQUEST\n ? `[log truncated after ${MAX_ENTRIES_PER_REQUEST} entries]`\n : format(...args).slice(0, MAX_MESSAGE_LENGTH);\n notifyHost(LOG_WRITE, {\n level,\n message,\n at: Date.now(),\n } satisfies PieceLogEntry);\n };\n }\n\n return () => {\n for (const [level, previous] of original) {\n console[level] = previous as typeof console.log;\n }\n };\n}\n","// The child's seam for `ctx.reactor`. The worker entry outside this layer\n// installs the reactor RPC client; this layer imports no reactor code.\nimport type {\n ReactorClientFor,\n RequireReactor,\n} from \"@powerhousedao/pieces-framework\";\nimport type { ReactorRequestBinding } from \"./protocol.js\";\n\n// The piece's ctx.reactor, typed by the block's declaration.\nexport type WorkerReactorSession = {\n [R in RequireReactor]: {\n readonly requireReactor: R;\n readonly client: ReactorClientFor<R>;\n // Run when the request settles; later calls throw ReactorRequestClosedError.\n close(): void;\n };\n}[RequireReactor];\n\nexport type WorkerReactorProvider = (\n binding: ReactorRequestBinding,\n requireReactor: RequireReactor,\n) => Promise<WorkerReactorSession>;\n\nlet provider: WorkerReactorProvider | undefined;\n\nexport function installReactorProvider(next: WorkerReactorProvider): void {\n provider = next;\n}\n\n// A session only when the host serves the request and the block declares access.\nexport function openWorkerReactor(\n binding: ReactorRequestBinding | undefined,\n declared: unknown,\n): Promise<WorkerReactorSession | undefined> {\n if (!binding || !provider) return Promise.resolve(undefined);\n if (declared !== \"read\" && declared !== \"write\") {\n return Promise.resolve(undefined);\n }\n return provider(binding, declared);\n}\n","(function (root) {\n 'use strict';\n // A list of regular expressions that match arbitrary IPv4 addresses,\n // for which a number of weird notations exist.\n // Note that an address like 0010.0xa5.1.1 is considered legal.\n const ipv4Part = '(0?\\\\d+|0x[a-f0-9]+)';\n const ipv4Regexes = {\n fourOctet: new RegExp(`^${ipv4Part}\\\\.${ipv4Part}\\\\.${ipv4Part}\\\\.${ipv4Part}$`, 'i'),\n threeOctet: new RegExp(`^${ipv4Part}\\\\.${ipv4Part}\\\\.${ipv4Part}$`, 'i'),\n twoOctet: new RegExp(`^${ipv4Part}\\\\.${ipv4Part}$`, 'i'),\n longValue: new RegExp(`^${ipv4Part}$`, 'i')\n };\n\n // Regular Expression for checking Octal numbers\n const octalRegex = new RegExp(`^0[0-7]+$`, 'i');\n const hexRegex = new RegExp(`^0x[a-f0-9]+$`, 'i');\n\n const zoneIndex = '%[0-9a-z]{1,}';\n\n // IPv6-matching regular expressions.\n // For IPv6, the task is simpler: it is enough to match the colon-delimited\n // hexadecimal IPv6 and a transitional variant with dotted-decimal IPv4 at\n // the end.\n const ipv6Part = '(?:[0-9a-f]+::?)+';\n const ipv6Regexes = {\n zoneIndex: new RegExp(zoneIndex, 'i'),\n 'native': new RegExp(`^(::)?(${ipv6Part})?([0-9a-f]+)?(::)?(${zoneIndex})?$`, 'i'),\n deprecatedTransitional: new RegExp(`^(?:::)(${ipv4Part}\\\\.${ipv4Part}\\\\.${ipv4Part}\\\\.${ipv4Part}(${zoneIndex})?)$`, 'i'),\n transitional: new RegExp(`^((?:${ipv6Part})|(?:::)(?:${ipv6Part})?)${ipv4Part}\\\\.${ipv4Part}\\\\.${ipv4Part}\\\\.${ipv4Part}(${zoneIndex})?$`, 'i')\n };\n\n // Expand :: in an IPv6 address or address part consisting of `parts` groups.\n function expandIPv6 (string, parts) {\n // More than one '::' means invalid adddress\n if (string.indexOf('::') !== string.lastIndexOf('::')) {\n return null;\n }\n\n let colonCount = 0;\n let lastColon = -1;\n let zoneId = (string.match(ipv6Regexes.zoneIndex) || [])[0];\n let replacement, replacementCount;\n\n // Remove zone index and save it for later\n if (zoneId) {\n zoneId = zoneId.substring(1);\n string = string.replace(/%.+$/, '');\n }\n\n // How many parts do we already have?\n while ((lastColon = string.indexOf(':', lastColon + 1)) >= 0) {\n colonCount++;\n }\n\n // 0::0 is two parts more than ::\n if (string.substr(0, 2) === '::') {\n colonCount--;\n }\n\n if (string.substr(-2, 2) === '::') {\n colonCount--;\n }\n\n // The following loop would hang if colonCount > parts\n if (colonCount > parts) {\n return null;\n }\n\n // replacement = ':' + '0:' * (parts - colonCount)\n replacementCount = parts - colonCount;\n replacement = ':';\n while (replacementCount--) {\n replacement += '0:';\n }\n\n // Insert the missing zeroes\n string = string.replace('::', replacement);\n\n // Trim any garbage which may be hanging around if :: was at the edge in\n // the source strin\n if (string[0] === ':') {\n string = string.slice(1);\n }\n\n if (string[string.length - 1] === ':') {\n string = string.slice(0, -1);\n }\n\n parts = (function () {\n const ref = string.split(':');\n const results = [];\n\n for (let i = 0; i < ref.length; i++) {\n results.push(parseInt(ref[i], 16));\n }\n\n return results;\n })();\n\n return {\n parts: parts,\n zoneId: zoneId\n };\n }\n\n // A generic CIDR (Classless Inter-Domain Routing) RFC1518 range matcher.\n function matchCIDR (first, second, partSize, cidrBits) {\n if (first.length !== second.length) {\n throw new Error('ipaddr: cannot match CIDR for objects with different lengths');\n }\n\n let part = 0;\n let shift;\n\n while (cidrBits > 0) {\n shift = partSize - cidrBits;\n if (shift < 0) {\n shift = 0;\n }\n\n if (first[part] >> shift !== second[part] >> shift) {\n return false;\n }\n\n cidrBits -= partSize;\n part += 1;\n }\n\n return true;\n }\n\n function parseIntAuto (string) {\n // Hexadedimal base 16 (0x#)\n if (hexRegex.test(string)) {\n return parseInt(string, 16);\n }\n // While octal representation is discouraged by ECMAScript 3\n // and forbidden by ECMAScript 5, we silently allow it to\n // work only if the rest of the string has numbers less than 8.\n if (string[0] === '0' && !isNaN(parseInt(string[1], 10))) {\n if (octalRegex.test(string)) {\n return parseInt(string, 8);\n }\n throw new Error(`ipaddr: cannot parse ${string} as octal`);\n }\n // Always include the base 10 radix!\n return parseInt(string, 10);\n }\n\n function padPart (part, length) {\n while (part.length < length) {\n part = `0${part}`;\n }\n\n return part;\n }\n\n const ipaddr = {};\n\n // An IPv4 address (RFC791).\n ipaddr.IPv4 = (function () {\n // Constructs a new IPv4 address from an array of four octets\n // in network order (MSB first)\n // Verifies the input.\n function IPv4 (octets) {\n if (octets.length !== 4) {\n throw new Error('ipaddr: ipv4 octet count should be 4');\n }\n\n let i, octet;\n\n for (i = 0; i < octets.length; i++) {\n octet = octets[i];\n if (!((0 <= octet && octet <= 255))) {\n throw new Error('ipaddr: ipv4 octet should fit in 8 bits');\n }\n }\n\n this.octets = octets;\n }\n\n // Special IPv4 address ranges.\n // See also https://en.wikipedia.org/wiki/Reserved_IP_addresses\n IPv4.prototype.SpecialRanges = {\n unspecified: [[new IPv4([0, 0, 0, 0]), 8]],\n broadcast: [[new IPv4([255, 255, 255, 255]), 32]],\n // RFC3171\n multicast: [[new IPv4([224, 0, 0, 0]), 4]],\n // RFC3927\n linkLocal: [[new IPv4([169, 254, 0, 0]), 16]],\n // RFC5735\n loopback: [[new IPv4([127, 0, 0, 0]), 8]],\n // RFC6598\n carrierGradeNat: [[new IPv4([100, 64, 0, 0]), 10]],\n // RFC1918\n 'private': [\n [new IPv4([10, 0, 0, 0]), 8],\n [new IPv4([172, 16, 0, 0]), 12],\n [new IPv4([192, 168, 0, 0]), 16]\n ],\n // Reserved and testing-only ranges; RFCs 5735, 5737, 2544, 1700\n reserved: [\n [new IPv4([192, 0, 0, 0]), 24],\n [new IPv4([192, 0, 2, 0]), 24],\n [new IPv4([192, 88, 99, 0]), 24],\n [new IPv4([198, 18, 0, 0]), 15],\n [new IPv4([198, 51, 100, 0]), 24],\n [new IPv4([203, 0, 113, 0]), 24],\n [new IPv4([240, 0, 0, 0]), 4]\n ],\n // RFC7534, RFC7535\n as112: [\n [new IPv4([192, 175, 48, 0]), 24],\n [new IPv4([192, 31, 196, 0]), 24],\n ],\n // RFC7450\n amt: [\n [new IPv4([192, 52, 193, 0]), 24],\n ],\n };\n\n // The 'kind' method exists on both IPv4 and IPv6 classes.\n IPv4.prototype.kind = function () {\n return 'ipv4';\n };\n\n // Checks if this address matches other one within given CIDR range.\n IPv4.prototype.match = function (other, cidrRange) {\n let ref;\n if (cidrRange === undefined) {\n ref = other;\n other = ref[0];\n cidrRange = ref[1];\n }\n\n if (other.kind() !== 'ipv4') {\n throw new Error('ipaddr: cannot match ipv4 address with non-ipv4 one');\n }\n\n return matchCIDR(this.octets, other.octets, 8, cidrRange);\n };\n\n // returns a number of leading ones in IPv4 address, making sure that\n // the rest is a solid sequence of 0's (valid netmask)\n // returns either the CIDR length or null if mask is not valid\n IPv4.prototype.prefixLengthFromSubnetMask = function () {\n let cidr = 0;\n // non-zero encountered stop scanning for zeroes\n let stop = false;\n // number of zeroes in octet\n const zerotable = {\n 0: 8,\n 128: 7,\n 192: 6,\n 224: 5,\n 240: 4,\n 248: 3,\n 252: 2,\n 254: 1,\n 255: 0\n };\n let i, octet, zeros;\n\n for (i = 3; i >= 0; i -= 1) {\n octet = this.octets[i];\n if (octet in zerotable) {\n zeros = zerotable[octet];\n if (stop && zeros !== 0) {\n return null;\n }\n\n if (zeros !== 8) {\n stop = true;\n }\n\n cidr += zeros;\n } else {\n return null;\n }\n }\n\n return 32 - cidr;\n };\n\n // Checks if the address corresponds to one of the special ranges.\n IPv4.prototype.range = function () {\n return ipaddr.subnetMatch(this, this.SpecialRanges);\n };\n\n // Returns an array of byte-sized values in network order (MSB first)\n IPv4.prototype.toByteArray = function () {\n return this.octets.slice(0);\n };\n\n // Converts this IPv4 address to an IPv4-mapped IPv6 address.\n IPv4.prototype.toIPv4MappedAddress = function () {\n return ipaddr.IPv6.parse(`::ffff:${this.toString()}`);\n };\n\n // Symmetrical method strictly for aligning with the IPv6 methods.\n IPv4.prototype.toNormalizedString = function () {\n return this.toString();\n };\n\n // Returns the address in convenient, decimal-dotted format.\n IPv4.prototype.toString = function () {\n return this.octets.join('.');\n };\n\n return IPv4;\n })();\n\n // A utility function to return broadcast address given the IPv4 interface and prefix length in CIDR notation\n ipaddr.IPv4.broadcastAddressFromCIDR = function (string) {\n\n try {\n const cidr = this.parseCIDR(string);\n const ipInterfaceOctets = cidr[0].toByteArray();\n const subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray();\n const octets = [];\n let i = 0;\n while (i < 4) {\n // Broadcast address is bitwise OR between ip interface and inverted mask\n octets.push(parseInt(ipInterfaceOctets[i], 10) | parseInt(subnetMaskOctets[i], 10) ^ 255);\n i++;\n }\n\n return new this(octets);\n } catch (e) {\n throw new Error('ipaddr: the address does not have IPv4 CIDR format');\n }\n };\n\n // Checks if a given string is formatted like IPv4 address.\n ipaddr.IPv4.isIPv4 = function (string) {\n return this.parser(string) !== null;\n };\n\n // Checks if a given string is a valid IPv4 address.\n ipaddr.IPv4.isValid = function (string) {\n try {\n new this(this.parser(string));\n return true;\n } catch (e) {\n return false;\n }\n };\n\n // Checks if a given string is a valid IPv4 address in CIDR notation.\n ipaddr.IPv4.isValidCIDR = function (string) {\n try {\n this.parseCIDR(string);\n return true;\n } catch (e) {\n return false;\n }\n };\n\n // Checks if a given string is a full four-part IPv4 Address.\n ipaddr.IPv4.isValidFourPartDecimal = function (string) {\n if (ipaddr.IPv4.isValid(string) && string.match(/^(0|[1-9]\\d*)(\\.(0|[1-9]\\d*)){3}$/)) {\n return true;\n } else {\n return false;\n }\n };\n\n // Checks if a given string is a full four-part IPv4 Address with CIDR prefix.\n ipaddr.IPv4.isValidCIDRFourPartDecimal = function (string) {\n const match = string.match(/^(.+)\\/(\\d+)$/);\n\n if (!ipaddr.IPv4.isValidCIDR(string) || !match) {\n return false;\n }\n\n return ipaddr.IPv4.isValidFourPartDecimal(match[1]);\n };\n\n // A utility function to return network address given the IPv4 interface and prefix length in CIDR notation\n ipaddr.IPv4.networkAddressFromCIDR = function (string) {\n let cidr, i, ipInterfaceOctets, octets, subnetMaskOctets;\n\n try {\n cidr = this.parseCIDR(string);\n ipInterfaceOctets = cidr[0].toByteArray();\n subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray();\n octets = [];\n i = 0;\n while (i < 4) {\n // Network address is bitwise AND between ip interface and mask\n octets.push(parseInt(ipInterfaceOctets[i], 10) & parseInt(subnetMaskOctets[i], 10));\n i++;\n }\n\n return new this(octets);\n } catch (e) {\n throw new Error('ipaddr: the address does not have IPv4 CIDR format');\n }\n };\n\n // Tries to parse and validate a string with IPv4 address.\n // Throws an error if it fails.\n ipaddr.IPv4.parse = function (string) {\n const parts = this.parser(string);\n\n if (parts === null) {\n throw new Error('ipaddr: string is not formatted like an IPv4 Address');\n }\n\n return new this(parts);\n };\n\n // Parses the string as an IPv4 Address with CIDR Notation.\n ipaddr.IPv4.parseCIDR = function (string) {\n let match;\n\n if ((match = string.match(/^(.+)\\/(\\d+)$/))) {\n const maskLength = parseInt(match[2]);\n if (maskLength >= 0 && maskLength <= 32) {\n const parsed = [this.parse(match[1]), maskLength];\n Object.defineProperty(parsed, 'toString', {\n value: function () {\n return this.join('/');\n }\n });\n return parsed;\n }\n }\n\n throw new Error('ipaddr: string is not formatted like an IPv4 CIDR range');\n };\n\n // Classful variants (like a.b, where a is an octet, and b is a 24-bit\n // value representing last three octets; this corresponds to a class C\n // address) are omitted due to classless nature of modern Internet.\n ipaddr.IPv4.parser = function (string) {\n let match, part, value;\n\n // parseInt recognizes all that octal & hexadecimal weirdness for us\n if ((match = string.match(ipv4Regexes.fourOctet))) {\n return (function () {\n const ref = match.slice(1, 6);\n const results = [];\n\n for (let i = 0; i < ref.length; i++) {\n part = ref[i];\n results.push(parseIntAuto(part));\n }\n\n return results;\n })();\n } else if ((match = string.match(ipv4Regexes.longValue))) {\n value = parseIntAuto(match[1]);\n if (value > 0xffffffff || value < 0) {\n throw new Error('ipaddr: address outside defined range');\n }\n\n return ((function () {\n const results = [];\n let shift;\n\n for (shift = 0; shift <= 24; shift += 8) {\n results.push((value >> shift) & 0xff);\n }\n\n return results;\n })()).reverse();\n } else if ((match = string.match(ipv4Regexes.twoOctet))) {\n return (function () {\n const ref = match.slice(1, 4);\n const results = [];\n\n value = parseIntAuto(ref[1]);\n if (value > 0xffffff || value < 0) {\n throw new Error('ipaddr: address outside defined range');\n }\n\n results.push(parseIntAuto(ref[0]));\n results.push((value >> 16) & 0xff);\n results.push((value >> 8) & 0xff);\n results.push( value & 0xff);\n\n return results;\n })();\n } else if ((match = string.match(ipv4Regexes.threeOctet))) {\n return (function () {\n const ref = match.slice(1, 5);\n const results = [];\n\n value = parseIntAuto(ref[2]);\n if (value > 0xffff || value < 0) {\n throw new Error('ipaddr: address outside defined range');\n }\n\n results.push(parseIntAuto(ref[0]));\n results.push(parseIntAuto(ref[1]));\n results.push((value >> 8) & 0xff);\n results.push( value & 0xff);\n\n return results;\n })();\n } else {\n return null;\n }\n };\n\n // A utility function to return subnet mask in IPv4 format given the prefix length\n ipaddr.IPv4.subnetMaskFromPrefixLength = function (prefix) {\n prefix = parseInt(prefix);\n if (prefix < 0 || prefix > 32) {\n throw new Error('ipaddr: invalid IPv4 prefix length');\n }\n\n const octets = [0, 0, 0, 0];\n let j = 0;\n const filledOctetCount = Math.floor(prefix / 8);\n\n while (j < filledOctetCount) {\n octets[j] = 255;\n j++;\n }\n\n if (filledOctetCount < 4) {\n octets[filledOctetCount] = Math.pow(2, prefix % 8) - 1 << 8 - (prefix % 8);\n }\n\n return new this(octets);\n };\n\n // An IPv6 address (RFC2460)\n ipaddr.IPv6 = (function () {\n // Constructs an IPv6 address from an array of eight 16 - bit parts\n // or sixteen 8 - bit parts in network order(MSB first).\n // Throws an error if the input is invalid.\n function IPv6 (parts, zoneId) {\n let i, part;\n\n if (parts.length === 16) {\n this.parts = [];\n for (i = 0; i <= 14; i += 2) {\n this.parts.push((parts[i] << 8) | parts[i + 1]);\n }\n } else if (parts.length === 8) {\n this.parts = parts;\n } else {\n throw new Error('ipaddr: ipv6 part count should be 8 or 16');\n }\n\n for (i = 0; i < this.parts.length; i++) {\n part = this.parts[i];\n if (!((0 <= part && part <= 0xffff))) {\n throw new Error('ipaddr: ipv6 part should fit in 16 bits');\n }\n }\n\n if (zoneId) {\n this.zoneId = zoneId;\n }\n }\n\n // Special IPv6 ranges\n IPv6.prototype.SpecialRanges = {\n // RFC4291, here and after\n unspecified: [new IPv6([0, 0, 0, 0, 0, 0, 0, 0]), 128],\n linkLocal: [new IPv6([0xfe80, 0, 0, 0, 0, 0, 0, 0]), 10],\n multicast: [new IPv6([0xff00, 0, 0, 0, 0, 0, 0, 0]), 8],\n loopback: [new IPv6([0, 0, 0, 0, 0, 0, 0, 1]), 128],\n uniqueLocal: [new IPv6([0xfc00, 0, 0, 0, 0, 0, 0, 0]), 7],\n ipv4Mapped: [new IPv6([0, 0, 0, 0, 0, 0xffff, 0, 0]), 96],\n // RFC6666\n discard: [new IPv6([0x100, 0, 0, 0, 0, 0, 0, 0]), 64],\n // RFC6145\n rfc6145: [new IPv6([0, 0, 0, 0, 0xffff, 0, 0, 0]), 96],\n // RFC6052\n rfc6052: [new IPv6([0x64, 0xff9b, 0, 0, 0, 0, 0, 0]), 96],\n // RFC3056\n '6to4': [new IPv6([0x2002, 0, 0, 0, 0, 0, 0, 0]), 16],\n // RFC6052, RFC6146\n teredo: [new IPv6([0x2001, 0, 0, 0, 0, 0, 0, 0]), 32],\n // RFC5180\n benchmarking: [new IPv6([0x2001, 0x2, 0, 0, 0, 0, 0, 0]), 48],\n // RFC7450\n amt: [new IPv6([0x2001, 0x3, 0, 0, 0, 0, 0, 0]), 32],\n as112v6: [\n [new IPv6([0x2001, 0x4, 0x112, 0, 0, 0, 0, 0]), 48],\n [new IPv6([0x2620, 0x4f, 0x8000, 0, 0, 0, 0, 0]), 48],\n ],\n deprecated: [new IPv6([0x2001, 0x10, 0, 0, 0, 0, 0, 0]), 28],\n orchid2: [new IPv6([0x2001, 0x20, 0, 0, 0, 0, 0, 0]), 28],\n droneRemoteIdProtocolEntityTags: [new IPv6([0x2001, 0x30, 0, 0, 0, 0, 0, 0]), 28],\n reserved: [\n // RFC3849\n [new IPv6([0x2001, 0, 0, 0, 0, 0, 0, 0]), 23],\n // RFC2928\n [new IPv6([0x2001, 0xdb8, 0, 0, 0, 0, 0, 0]), 32],\n ],\n };\n\n // Checks if this address is an IPv4-mapped IPv6 address.\n IPv6.prototype.isIPv4MappedAddress = function () {\n return this.range() === 'ipv4Mapped';\n };\n\n // The 'kind' method exists on both IPv4 and IPv6 classes.\n IPv6.prototype.kind = function () {\n return 'ipv6';\n };\n\n // Checks if this address matches other one within given CIDR range.\n IPv6.prototype.match = function (other, cidrRange) {\n let ref;\n\n if (cidrRange === undefined) {\n ref = other;\n other = ref[0];\n cidrRange = ref[1];\n }\n\n if (other.kind() !== 'ipv6') {\n throw new Error('ipaddr: cannot match ipv6 address with non-ipv6 one');\n }\n\n return matchCIDR(this.parts, other.parts, 16, cidrRange);\n };\n\n // returns a number of leading ones in IPv6 address, making sure that\n // the rest is a solid sequence of 0's (valid netmask)\n // returns either the CIDR length or null if mask is not valid\n IPv6.prototype.prefixLengthFromSubnetMask = function () {\n let cidr = 0;\n // non-zero encountered stop scanning for zeroes\n let stop = false;\n // number of zeroes in octet\n const zerotable = {\n 0: 16,\n 32768: 15,\n 49152: 14,\n 57344: 13,\n 61440: 12,\n 63488: 11,\n 64512: 10,\n 65024: 9,\n 65280: 8,\n 65408: 7,\n 65472: 6,\n 65504: 5,\n 65520: 4,\n 65528: 3,\n 65532: 2,\n 65534: 1,\n 65535: 0\n };\n let part, zeros;\n\n for (let i = 7; i >= 0; i -= 1) {\n part = this.parts[i];\n if (part in zerotable) {\n zeros = zerotable[part];\n if (stop && zeros !== 0) {\n return null;\n }\n\n if (zeros !== 16) {\n stop = true;\n }\n\n cidr += zeros;\n } else {\n return null;\n }\n }\n\n return 128 - cidr;\n };\n\n\n // Checks if the address corresponds to one of the special ranges.\n IPv6.prototype.range = function () {\n return ipaddr.subnetMatch(this, this.SpecialRanges);\n };\n\n // Returns an array of byte-sized values in network order (MSB first)\n IPv6.prototype.toByteArray = function () {\n let part;\n const bytes = [];\n const ref = this.parts;\n for (let i = 0; i < ref.length; i++) {\n part = ref[i];\n bytes.push(part >> 8);\n bytes.push(part & 0xff);\n }\n\n return bytes;\n };\n\n // Returns the address in expanded format with all zeroes included, like\n // 2001:0db8:0008:0066:0000:0000:0000:0001\n IPv6.prototype.toFixedLengthString = function () {\n const addr = ((function () {\n const results = [];\n for (let i = 0; i < this.parts.length; i++) {\n results.push(padPart(this.parts[i].toString(16), 4));\n }\n\n return results;\n }).call(this)).join(':');\n\n let suffix = '';\n\n if (this.zoneId) {\n suffix = `%${this.zoneId}`;\n }\n\n return addr + suffix;\n };\n\n // Converts this address to IPv4 address if it is an IPv4-mapped IPv6 address.\n // Throws an error otherwise.\n IPv6.prototype.toIPv4Address = function () {\n if (!this.isIPv4MappedAddress()) {\n throw new Error('ipaddr: trying to convert a generic ipv6 address to ipv4');\n }\n\n const ref = this.parts.slice(-2);\n const high = ref[0];\n const low = ref[1];\n\n return new ipaddr.IPv4([high >> 8, high & 0xff, low >> 8, low & 0xff]);\n };\n\n // Returns the address in expanded format with all zeroes included, like\n // 2001:db8:8:66:0:0:0:1\n //\n // Deprecated: use toFixedLengthString() instead.\n IPv6.prototype.toNormalizedString = function () {\n const addr = ((function () {\n const results = [];\n\n for (let i = 0; i < this.parts.length; i++) {\n results.push(this.parts[i].toString(16));\n }\n\n return results;\n }).call(this)).join(':');\n\n let suffix = '';\n\n if (this.zoneId) {\n suffix = `%${this.zoneId}`;\n }\n\n return addr + suffix;\n };\n\n // Returns the address in compact, human-readable format like\n // 2001:db8:8:66::1\n // in line with RFC 5952 (see https://tools.ietf.org/html/rfc5952#section-4)\n IPv6.prototype.toRFC5952String = function () {\n const regex = /((^|:)(0(:|$)){2,})/g;\n const string = this.toNormalizedString();\n let bestMatchIndex = 0;\n let bestMatchLength = -1;\n let match;\n\n while ((match = regex.exec(string))) {\n if (match[0].length > bestMatchLength) {\n bestMatchIndex = match.index;\n bestMatchLength = match[0].length;\n }\n }\n\n if (bestMatchLength < 0) {\n return string;\n }\n\n return `${string.substring(0, bestMatchIndex)}::${string.substring(bestMatchIndex + bestMatchLength)}`;\n };\n\n // Returns the address in compact, human-readable format like\n // 2001:db8:8:66::1\n // Calls toRFC5952String under the hood.\n IPv6.prototype.toString = function () {\n return this.toRFC5952String();\n };\n\n return IPv6;\n\n })();\n\n // A utility function to return broadcast address given the IPv6 interface and prefix length in CIDR notation\n ipaddr.IPv6.broadcastAddressFromCIDR = function (string) {\n try {\n const cidr = this.parseCIDR(string);\n const ipInterfaceOctets = cidr[0].toByteArray();\n const subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray();\n const octets = [];\n let i = 0;\n while (i < 16) {\n // Broadcast address is bitwise OR between ip interface and inverted mask\n octets.push(parseInt(ipInterfaceOctets[i], 10) | parseInt(subnetMaskOctets[i], 10) ^ 255);\n i++;\n }\n\n return new this(octets);\n } catch (e) {\n throw new Error(`ipaddr: the address does not have IPv6 CIDR format (${e})`);\n }\n };\n\n // Checks if a given string is formatted like IPv6 address.\n ipaddr.IPv6.isIPv6 = function (string) {\n return this.parser(string) !== null;\n };\n\n // Checks to see if string is a valid IPv6 Address\n ipaddr.IPv6.isValid = function (string) {\n\n // Since IPv6.isValid is always called first, this shortcut\n // provides a substantial performance gain.\n if (typeof string === 'string' && string.indexOf(':') === -1) {\n return false;\n }\n\n try {\n const addr = this.parser(string);\n new this(addr.parts, addr.zoneId);\n return true;\n } catch (e) {\n return false;\n }\n };\n\n // Checks if a given string is a valid IPv6 address in CIDR notation.\n ipaddr.IPv6.isValidCIDR = function (string) {\n\n // See note in IPv6.isValid\n if (typeof string === 'string' && string.indexOf(':') === -1) {\n return false;\n }\n\n try {\n this.parseCIDR(string);\n return true;\n } catch (e) {\n return false;\n }\n };\n\n // A utility function to return network address given the IPv6 interface and prefix length in CIDR notation\n ipaddr.IPv6.networkAddressFromCIDR = function (string) {\n let cidr, i, ipInterfaceOctets, octets, subnetMaskOctets;\n\n try {\n cidr = this.parseCIDR(string);\n ipInterfaceOctets = cidr[0].toByteArray();\n subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray();\n octets = [];\n i = 0;\n while (i < 16) {\n // Network address is bitwise AND between ip interface and mask\n octets.push(parseInt(ipInterfaceOctets[i], 10) & parseInt(subnetMaskOctets[i], 10));\n i++;\n }\n\n return new this(octets);\n } catch (e) {\n throw new Error(`ipaddr: the address does not have IPv6 CIDR format (${e})`);\n }\n };\n\n // Tries to parse and validate a string with IPv6 address.\n // Throws an error if it fails.\n ipaddr.IPv6.parse = function (string) {\n const addr = this.parser(string);\n\n if (addr.parts === null) {\n throw new Error('ipaddr: string is not formatted like an IPv6 Address');\n }\n\n return new this(addr.parts, addr.zoneId);\n };\n\n ipaddr.IPv6.parseCIDR = function (string) {\n let maskLength, match, parsed;\n\n if ((match = string.match(/^(.+)\\/(\\d+)$/))) {\n maskLength = parseInt(match[2]);\n if (maskLength >= 0 && maskLength <= 128) {\n parsed = [this.parse(match[1]), maskLength];\n Object.defineProperty(parsed, 'toString', {\n value: function () {\n return this.join('/');\n }\n });\n return parsed;\n }\n }\n\n throw new Error('ipaddr: string is not formatted like an IPv6 CIDR range');\n };\n\n // Parse an IPv6 address.\n ipaddr.IPv6.parser = function (string) {\n let addr, i, match, octet, octets, zoneId;\n\n if ((match = string.match(ipv6Regexes.deprecatedTransitional))) {\n return this.parser(`::ffff:${match[1]}`);\n }\n if (ipv6Regexes.native.test(string)) {\n return expandIPv6(string, 8);\n }\n if ((match = string.match(ipv6Regexes.transitional))) {\n zoneId = match[6] || '';\n addr = match[1]\n if (!match[1].endsWith('::')) {\n addr = addr.slice(0, -1)\n }\n addr = expandIPv6(addr + zoneId, 6);\n if (addr.parts) {\n octets = [\n parseInt(match[2]),\n parseInt(match[3]),\n parseInt(match[4]),\n parseInt(match[5])\n ];\n for (i = 0; i < octets.length; i++) {\n octet = octets[i];\n if (!((0 <= octet && octet <= 255))) {\n return null;\n }\n }\n\n addr.parts.push(octets[0] << 8 | octets[1]);\n addr.parts.push(octets[2] << 8 | octets[3]);\n return {\n parts: addr.parts,\n zoneId: addr.zoneId\n };\n }\n }\n\n return null;\n };\n\n // A utility function to return subnet mask in IPv6 format given the prefix length\n ipaddr.IPv6.subnetMaskFromPrefixLength = function (prefix) {\n prefix = parseInt(prefix);\n if (prefix < 0 || prefix > 128) {\n throw new Error('ipaddr: invalid IPv6 prefix length');\n }\n\n const octets = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];\n let j = 0;\n const filledOctetCount = Math.floor(prefix / 8);\n\n while (j < filledOctetCount) {\n octets[j] = 255;\n j++;\n }\n\n if (filledOctetCount < 16) {\n octets[filledOctetCount] = Math.pow(2, prefix % 8) - 1 << 8 - (prefix % 8);\n }\n\n return new this(octets);\n };\n\n // Try to parse an array in network order (MSB first) for IPv4 and IPv6\n ipaddr.fromByteArray = function (bytes) {\n const length = bytes.length;\n\n if (length === 4) {\n return new ipaddr.IPv4(bytes);\n } else if (length === 16) {\n return new ipaddr.IPv6(bytes);\n } else {\n throw new Error('ipaddr: the binary input is neither an IPv6 nor IPv4 address');\n }\n };\n\n // Checks if the address is valid IP address\n ipaddr.isValid = function (string) {\n return ipaddr.IPv6.isValid(string) || ipaddr.IPv4.isValid(string);\n };\n\n // Checks if the address is valid IP address in CIDR notation\n ipaddr.isValidCIDR = function (string) {\n return ipaddr.IPv6.isValidCIDR(string) || ipaddr.IPv4.isValidCIDR(string);\n };\n\n\n // Attempts to parse an IP Address, first through IPv6 then IPv4.\n // Throws an error if it could not be parsed.\n ipaddr.parse = function (string) {\n if (ipaddr.IPv6.isValid(string)) {\n return ipaddr.IPv6.parse(string);\n } else if (ipaddr.IPv4.isValid(string)) {\n return ipaddr.IPv4.parse(string);\n } else {\n throw new Error('ipaddr: the address has neither IPv6 nor IPv4 format');\n }\n };\n\n // Attempt to parse CIDR notation, first through IPv6 then IPv4.\n // Throws an error if it could not be parsed.\n ipaddr.parseCIDR = function (string) {\n try {\n return ipaddr.IPv6.parseCIDR(string);\n } catch (e) {\n try {\n return ipaddr.IPv4.parseCIDR(string);\n } catch (e2) {\n throw new Error('ipaddr: the address has neither IPv6 nor IPv4 CIDR format');\n }\n }\n };\n\n // Parse an address and return plain IPv4 address if it is an IPv4-mapped address\n ipaddr.process = function (string) {\n const addr = this.parse(string);\n\n if (addr.kind() === 'ipv6' && addr.isIPv4MappedAddress()) {\n return addr.toIPv4Address();\n } else {\n return addr;\n }\n };\n\n // An utility function to ease named range matching. See examples below.\n // rangeList can contain both IPv4 and IPv6 subnet entries and will not throw errors\n // on matching IPv4 addresses to IPv6 ranges or vice versa.\n ipaddr.subnetMatch = function (address, rangeList, defaultName) {\n let i, rangeName, rangeSubnets, subnet;\n\n if (defaultName === undefined || defaultName === null) {\n defaultName = 'unicast';\n }\n\n for (rangeName in rangeList) {\n if (Object.prototype.hasOwnProperty.call(rangeList, rangeName)) {\n rangeSubnets = rangeList[rangeName];\n // ECMA5 Array.isArray isn't available everywhere\n if (rangeSubnets[0] && !(rangeSubnets[0] instanceof Array)) {\n rangeSubnets = [rangeSubnets];\n }\n\n for (i = 0; i < rangeSubnets.length; i++) {\n subnet = rangeSubnets[i];\n if (address.kind() === subnet[0].kind() && address.match.apply(address, subnet)) {\n return rangeName;\n }\n }\n }\n }\n\n return defaultName;\n };\n\n // Export for both the CommonJS and browser-like environment\n if (typeof module !== 'undefined' && module.exports) {\n module.exports = ipaddr;\n\n } else {\n root.ipaddr = ipaddr;\n }\n\n}(this));\n","!function(t,e){\"object\"==typeof exports&&\"undefined\"!=typeof module?module.exports=e():\"function\"==typeof define&&define.amd?define(e):(t=\"undefined\"!=typeof globalThis?globalThis:t||self).dayjs=e()}(this,(function(){\"use strict\";var t=1e3,e=6e4,n=36e5,r=\"millisecond\",i=\"second\",s=\"minute\",u=\"hour\",a=\"day\",o=\"week\",c=\"month\",f=\"quarter\",h=\"year\",d=\"date\",l=\"Invalid Date\",$=/^(\\d{4})[-/]?(\\d{1,2})?[-/]?(\\d{0,2})[Tt\\s]*(\\d{1,2})?:?(\\d{1,2})?:?(\\d{1,2})?[.:]?(\\d+)?$/,y=/\\[([^\\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,M={name:\"en\",weekdays:\"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday\".split(\"_\"),months:\"January_February_March_April_May_June_July_August_September_October_November_December\".split(\"_\"),ordinal:function(t){var e=[\"th\",\"st\",\"nd\",\"rd\"],n=t%100;return\"[\"+t+(e[(n-20)%10]||e[n]||e[0])+\"]\"}},m=function(t,e,n){var r=String(t);return!r||r.length>=e?t:\"\"+Array(e+1-r.length).join(n)+t},v={s:m,z:function(t){var e=-t.utcOffset(),n=Math.abs(e),r=Math.floor(n/60),i=n%60;return(e<=0?\"+\":\"-\")+m(r,2,\"0\")+\":\"+m(i,2,\"0\")},m:function t(e,n){if(e.date()<n.date())return-t(n,e);var r=12*(n.year()-e.year())+(n.month()-e.month()),i=e.clone().add(r,c),s=n-i<0,u=e.clone().add(r+(s?-1:1),c);return+(-(r+(n-i)/(s?i-u:u-i))||0)},a:function(t){return t<0?Math.ceil(t)||0:Math.floor(t)},p:function(t){return{M:c,y:h,w:o,d:a,D:d,h:u,m:s,s:i,ms:r,Q:f}[t]||String(t||\"\").toLowerCase().replace(/s$/,\"\")},u:function(t){return void 0===t}},g=\"en\",D={};D[g]=M;var p=function(t){return t instanceof b},S=function t(e,n,r){var i;if(!e)return g;if(\"string\"==typeof e){var s=e.toLowerCase();D[s]&&(i=s),n&&(D[s]=n,i=s);var u=e.split(\"-\");if(!i&&u.length>1)return t(u[0])}else{var a=e.name;D[a]=e,i=a}return!r&&i&&(g=i),i||!r&&g},w=function(t,e){if(p(t))return t.clone();var n=\"object\"==typeof e?e:{};return n.date=t,n.args=arguments,new b(n)},O=v;O.l=S,O.i=p,O.w=function(t,e){return w(t,{locale:e.$L,utc:e.$u,x:e.$x,$offset:e.$offset})};var b=function(){function M(t){this.$L=S(t.locale,null,!0),this.parse(t)}var m=M.prototype;return m.parse=function(t){this.$d=function(t){var e=t.date,n=t.utc;if(null===e)return new Date(NaN);if(O.u(e))return new Date;if(e instanceof Date)return new Date(e);if(\"string\"==typeof e&&!/Z$/i.test(e)){var r=e.match($);if(r){var i=r[2]-1||0,s=(r[7]||\"0\").substring(0,3);return n?new Date(Date.UTC(r[1],i,r[3]||1,r[4]||0,r[5]||0,r[6]||0,s)):new Date(r[1],i,r[3]||1,r[4]||0,r[5]||0,r[6]||0,s)}}return new Date(e)}(t),this.$x=t.x||{},this.init()},m.init=function(){var t=this.$d;this.$y=t.getFullYear(),this.$M=t.getMonth(),this.$D=t.getDate(),this.$W=t.getDay(),this.$H=t.getHours(),this.$m=t.getMinutes(),this.$s=t.getSeconds(),this.$ms=t.getMilliseconds()},m.$utils=function(){return O},m.isValid=function(){return!(this.$d.toString()===l)},m.isSame=function(t,e){var n=w(t);return this.startOf(e)<=n&&n<=this.endOf(e)},m.isAfter=function(t,e){return w(t)<this.startOf(e)},m.isBefore=function(t,e){return this.endOf(e)<w(t)},m.$g=function(t,e,n){return O.u(t)?this[e]:this.set(n,t)},m.unix=function(){return Math.floor(this.valueOf()/1e3)},m.valueOf=function(){return this.$d.getTime()},m.startOf=function(t,e){var n=this,r=!!O.u(e)||e,f=O.p(t),l=function(t,e){var i=O.w(n.$u?Date.UTC(n.$y,e,t):new Date(n.$y,e,t),n);return r?i:i.endOf(a)},$=function(t,e){return O.w(n.toDate()[t].apply(n.toDate(\"s\"),(r?[0,0,0,0]:[23,59,59,999]).slice(e)),n)},y=this.$W,M=this.$M,m=this.$D,v=\"set\"+(this.$u?\"UTC\":\"\");switch(f){case h:return r?l(1,0):l(31,11);case c:return r?l(1,M):l(0,M+1);case o:var g=this.$locale().weekStart||0,D=(y<g?y+7:y)-g;return l(r?m-D:m+(6-D),M);case a:case d:return $(v+\"Hours\",0);case u:return $(v+\"Minutes\",1);case s:return $(v+\"Seconds\",2);case i:return $(v+\"Milliseconds\",3);default:return this.clone()}},m.endOf=function(t){return this.startOf(t,!1)},m.$set=function(t,e){var n,o=O.p(t),f=\"set\"+(this.$u?\"UTC\":\"\"),l=(n={},n[a]=f+\"Date\",n[d]=f+\"Date\",n[c]=f+\"Month\",n[h]=f+\"FullYear\",n[u]=f+\"Hours\",n[s]=f+\"Minutes\",n[i]=f+\"Seconds\",n[r]=f+\"Milliseconds\",n)[o],$=o===a?this.$D+(e-this.$W):e;if(o===c||o===h){var y=this.clone().set(d,1);y.$d[l]($),y.init(),this.$d=y.set(d,Math.min(this.$D,y.daysInMonth())).$d}else l&&this.$d[l]($);return this.init(),this},m.set=function(t,e){return this.clone().$set(t,e)},m.get=function(t){return this[O.p(t)]()},m.add=function(r,f){var d,l=this;r=Number(r);var $=O.p(f),y=function(t){var e=w(l);return O.w(e.date(e.date()+Math.round(t*r)),l)};if($===c)return this.set(c,this.$M+r);if($===h)return this.set(h,this.$y+r);if($===a)return y(1);if($===o)return y(7);var M=(d={},d[s]=e,d[u]=n,d[i]=t,d)[$]||1,m=this.$d.getTime()+r*M;return O.w(m,this)},m.subtract=function(t,e){return this.add(-1*t,e)},m.format=function(t){var e=this,n=this.$locale();if(!this.isValid())return n.invalidDate||l;var r=t||\"YYYY-MM-DDTHH:mm:ssZ\",i=O.z(this),s=this.$H,u=this.$m,a=this.$M,o=n.weekdays,c=n.months,f=n.meridiem,h=function(t,n,i,s){return t&&(t[n]||t(e,r))||i[n].slice(0,s)},d=function(t){return O.s(s%12||12,t,\"0\")},$=f||function(t,e,n){var r=t<12?\"AM\":\"PM\";return n?r.toLowerCase():r};return r.replace(y,(function(t,r){return r||function(t){switch(t){case\"YY\":return String(e.$y).slice(-2);case\"YYYY\":return O.s(e.$y,4,\"0\");case\"M\":return a+1;case\"MM\":return O.s(a+1,2,\"0\");case\"MMM\":return h(n.monthsShort,a,c,3);case\"MMMM\":return h(c,a);case\"D\":return e.$D;case\"DD\":return O.s(e.$D,2,\"0\");case\"d\":return String(e.$W);case\"dd\":return h(n.weekdaysMin,e.$W,o,2);case\"ddd\":return h(n.weekdaysShort,e.$W,o,3);case\"dddd\":return o[e.$W];case\"H\":return String(s);case\"HH\":return O.s(s,2,\"0\");case\"h\":return d(1);case\"hh\":return d(2);case\"a\":return $(s,u,!0);case\"A\":return $(s,u,!1);case\"m\":return String(u);case\"mm\":return O.s(u,2,\"0\");case\"s\":return String(e.$s);case\"ss\":return O.s(e.$s,2,\"0\");case\"SSS\":return O.s(e.$ms,3,\"0\");case\"Z\":return i}return null}(t)||i.replace(\":\",\"\")}))},m.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},m.diff=function(r,d,l){var $,y=this,M=O.p(d),m=w(r),v=(m.utcOffset()-this.utcOffset())*e,g=this-m,D=function(){return O.m(y,m)};switch(M){case h:$=D()/12;break;case c:$=D();break;case f:$=D()/3;break;case o:$=(g-v)/6048e5;break;case a:$=(g-v)/864e5;break;case u:$=g/n;break;case s:$=g/e;break;case i:$=g/t;break;default:$=g}return l?$:O.a($)},m.daysInMonth=function(){return this.endOf(c).$D},m.$locale=function(){return D[this.$L]},m.locale=function(t,e){if(!t)return this.$L;var n=this.clone(),r=S(t,e,!0);return r&&(n.$L=r),n},m.clone=function(){return O.w(this.$d,this)},m.toDate=function(){return new Date(this.valueOf())},m.toJSON=function(){return this.isValid()?this.toISOString():null},m.toISOString=function(){return this.$d.toISOString()},m.toString=function(){return this.$d.toUTCString()},M}(),_=b.prototype;return w.prototype=_,[[\"$ms\",r],[\"$s\",i],[\"$m\",s],[\"$H\",u],[\"$W\",a],[\"$M\",c],[\"$y\",h],[\"$D\",d]].forEach((function(t){_[t[1]]=function(e){return this.$g(e,t[0],t[1])}})),w.extend=function(t,e){return t.$i||(t(e,b,w),t.$i=!0),w},w.locale=S,w.isDayjs=p,w.unix=function(t){return w(1e3*t)},w.en=D[g],w.Ls=D,w.p={},w}));","!function(t,e){\"object\"==typeof exports&&\"undefined\"!=typeof module?module.exports=e():\"function\"==typeof define&&define.amd?define(e):(t=\"undefined\"!=typeof globalThis?globalThis:t||self).dayjs_plugin_timezone=e()}(this,(function(){\"use strict\";var t={year:0,month:1,day:2,hour:3,minute:4,second:5},e={};return function(n,i,o){var r,a=function(t,n,i){void 0===i&&(i={});var o=new Date(t),r=function(t,n){void 0===n&&(n={});var i=n.timeZoneName||\"short\",o=t+\"|\"+i,r=e[o];return r||(r=new Intl.DateTimeFormat(\"en-US\",{hour12:!1,timeZone:t,year:\"numeric\",month:\"2-digit\",day:\"2-digit\",hour:\"2-digit\",minute:\"2-digit\",second:\"2-digit\",timeZoneName:i}),e[o]=r),r}(n,i);return r.formatToParts(o)},u=function(e,n){for(var i=a(e,n),r=[],u=0;u<i.length;u+=1){var f=i[u],s=f.type,m=f.value,c=t[s];c>=0&&(r[c]=parseInt(m,10))}var d=r[3],l=24===d?0:d,v=r[0]+\"-\"+r[1]+\"-\"+r[2]+\" \"+l+\":\"+r[4]+\":\"+r[5]+\":000\",h=+e;return(o.utc(v).valueOf()-(h-=h%1e3))/6e4},f=i.prototype;f.tz=function(t,e){void 0===t&&(t=r);var n=this.utcOffset(),i=this.toDate(),a=i.toLocaleString(\"en-US\",{timeZone:t}),u=Math.round((i-new Date(a))/1e3/60),f=o(a).$set(\"millisecond\",this.$ms).utcOffset(15*-Math.round(i.getTimezoneOffset()/15)-u,!0);if(e){var s=f.utcOffset();f=f.add(n-s,\"minute\")}return f.$x.$timezone=t,f},f.offsetName=function(t){var e=this.$x.$timezone||o.tz.guess(),n=a(this.valueOf(),e,{timeZoneName:t}).find((function(t){return\"timezonename\"===t.type.toLowerCase()}));return n&&n.value};var s=f.startOf;f.startOf=function(t,e){if(!this.$x||!this.$x.$timezone)return s.call(this,t,e);var n=o(this.format(\"YYYY-MM-DD HH:mm:ss:SSS\"));return s.call(n,t,e).tz(this.$x.$timezone,!0)},o.tz=function(t,e,n){var i=n&&e,a=n||e||r,f=u(+o(),a);if(\"string\"!=typeof t)return o(t).tz(a);var s=function(t,e,n){var i=t-60*e*1e3,o=u(i,n);if(e===o)return[i,e];var r=u(i-=60*(o-e)*1e3,n);return o===r?[i,o]:[t-60*Math.min(o,r)*1e3,Math.max(o,r)]}(o.utc(t,i).valueOf(),f,a),m=s[0],c=s[1],d=o(m).utcOffset(c);return d.$x.$timezone=a,d},o.tz.guess=function(){return Intl.DateTimeFormat().resolvedOptions().timeZone},o.tz.setDefault=function(t){r=t}}}));","!function(t,i){\"object\"==typeof exports&&\"undefined\"!=typeof module?module.exports=i():\"function\"==typeof define&&define.amd?define(i):(t=\"undefined\"!=typeof globalThis?globalThis:t||self).dayjs_plugin_utc=i()}(this,(function(){\"use strict\";var t=\"minute\",i=/[+-]\\d\\d(?::?\\d\\d)?/g,e=/([+-]|\\d\\d)/g;return function(s,f,n){var u=f.prototype;n.utc=function(t){var i={date:t,utc:!0,args:arguments};return new f(i)},u.utc=function(i){var e=n(this.toDate(),{locale:this.$L,utc:!0});return i?e.add(this.utcOffset(),t):e},u.local=function(){return n(this.toDate(),{locale:this.$L,utc:!1})};var o=u.parse;u.parse=function(t){t.utc&&(this.$u=!0),this.$utils().u(t.$offset)||(this.$offset=t.$offset),o.call(this,t)};var r=u.init;u.init=function(){if(this.$u){var t=this.$d;this.$y=t.getUTCFullYear(),this.$M=t.getUTCMonth(),this.$D=t.getUTCDate(),this.$W=t.getUTCDay(),this.$H=t.getUTCHours(),this.$m=t.getUTCMinutes(),this.$s=t.getUTCSeconds(),this.$ms=t.getUTCMilliseconds()}else r.call(this)};var a=u.utcOffset;u.utcOffset=function(s,f){var n=this.$utils().u;if(n(s))return this.$u?0:n(this.$offset)?a.call(this):this.$offset;if(\"string\"==typeof s&&(s=function(t){void 0===t&&(t=\"\");var s=t.match(i);if(!s)return null;var f=(\"\"+s[0]).match(e)||[\"-\",0,0],n=f[0],u=60*+f[1]+ +f[2];return 0===u?0:\"+\"===n?u:-u}(s),null===s))return this;var u=Math.abs(s)<=16?60*s:s,o=this;if(f)return o.$offset=u,o.$u=0===s,o;if(0!==s){var r=this.$u?this.toDate().getTimezoneOffset():-1*this.utcOffset();(o=this.local().add(u+r,t)).$offset=u,o.$x.$localOffset=r}else o=this.utc();return o};var h=u.format;u.format=function(t){var i=t||(this.$u?\"YYYY-MM-DDTHH:mm:ss[Z]\":\"\");return h.call(this,i)},u.valueOf=function(){var t=this.$utils().u(this.$offset)?0:this.$offset+(this.$x.$localOffset||this.$d.getTimezoneOffset());return this.$d.valueOf()-6e4*t},u.isUTC=function(){return!!this.$u},u.toISOString=function(){return this.toDate().toISOString()},u.toString=function(){return this.toDate().toUTCString()};var l=u.toDate;u.toDate=function(t){return\"s\"===t&&this.$offset?n(this.format(\"YYYY-MM-DD HH:mm:ss:SSS\")).toDate():l.call(this)};var c=u.diff;u.diff=function(t,i,e){if(t&&this.$u===t.$u)return c.call(this,t,i,e);var s=this.local(),f=n(t).local();return c.call(s,f,i,e)}}}));","import { A as PropertyType, b as ApFile, c as isNil, d as parseToJsonIfPossible, l as isString, o as isBase64, r as tryCatchSync, v as DateRangeValue } from \"./markdown-property-DMfHjEiL.js\";\nimport { g as AUTHENTICATION_PROPERTY_NAME, i as getAuthPropertyForValue, m as isObject } from \"./authentication-o-4CdAPR.js\";\nimport ipaddr from \"ipaddr.js\";\nimport { Readable } from \"node:stream\";\nimport dayjs from \"dayjs\";\nimport timezone from \"dayjs/plugin/timezone.js\";\nimport utc from \"dayjs/plugin/utc.js\";\n\n//#region upstream/core-utils/lib/friendly-piece-error.ts\nconst FRIENDLY_PIECE_ERROR_VERSION = 1;\nconst STACK_LINE_REGEX = /\\n\\s*at\\s+.+$/gm;\nconst HTTP_ERROR_MESSAGE_MAX_LENGTH = 2e3;\nconst RAW_ERROR_MAX_LENGTH = 16e3;\nconst HTTP_STATUS_MIN = 100;\nconst HTTP_STATUS_MAX = 599;\nconst MAX_MESSAGE_DEPTH = 12;\nconst MAX_SERIALIZED_DEPTH = 64;\nconst CIRCULAR_PLACEHOLDER = \"[Circular]\";\nconst TOO_DEEP_PLACEHOLDER = \"[Too deep]\";\nconst UNSERIALIZABLE_PLACEHOLDER = \"[Unserializable]\";\nconst isObjectRecord = (value) => {\n\treturn !isNil(value) && typeof value === \"object\" && !Array.isArray(value);\n};\nconst safeJsonParse = (value) => {\n\ttry {\n\t\treturn JSON.parse(value);\n\t} catch {\n\t\treturn value;\n\t}\n};\nconst stripStack = (value) => {\n\treturn value.replace(STACK_LINE_REGEX, \"\").trim();\n};\nconst truncate = (value) => {\n\tif (value.length <= HTTP_ERROR_MESSAGE_MAX_LENGTH) return value;\n\treturn `${value.slice(0, HTTP_ERROR_MESSAGE_MAX_LENGTH)}…`;\n};\nconst truncateRaw = (value) => {\n\tif (value.length <= RAW_ERROR_MAX_LENGTH) return value;\n\treturn `${value.slice(0, RAW_ERROR_MAX_LENGTH)}\\n…[truncated]`;\n};\nconst HTML_DOC_REGEX = /^\\s*(<!doctype\\s+html|<html\\b|<\\?xml)/i;\nconst HTML_TAG_LIKE_REGEX = /<\\s*(html|body|head|title|meta|p|div|span|h[1-6]|table|script|style)\\b/i;\nconst isLikelyMarkupBody = (value) => {\n\tif (HTML_DOC_REGEX.test(value)) return true;\n\tif (!value.includes(\"<\") || !value.includes(\">\")) return false;\n\treturn HTML_TAG_LIKE_REGEX.test(value);\n};\nconst decodeHtmlEntities = (value) => {\n\treturn value.replace(/&nbsp;/g, \" \").replace(/&amp;/g, \"&\").replace(/&lt;/g, \"<\").replace(/&gt;/g, \">\").replace(/&quot;/g, \"\\\"\").replace(/&#39;/g, \"'\").replace(/&apos;/g, \"'\");\n};\nconst stripMarkup = (value) => {\n\tconst titleMatch = value.match(/<title[^>]*>([\\s\\S]*?)<\\/title>/i);\n\tconst title = titleMatch ? decodeHtmlEntities(titleMatch[1]).replace(/\\s+/g, \" \").trim() : \"\";\n\tconst withoutNoise = value.replace(/<script[\\s\\S]*?<\\/script>/gi, \" \").replace(/<style[\\s\\S]*?<\\/style>/gi, \" \").replace(/<head[\\s\\S]*?<\\/head>/gi, \" \");\n\tconst textOnly = decodeHtmlEntities(withoutNoise.replace(/<[^>]+>/g, \" \")).replace(/\\s+/g, \" \").trim();\n\tif (textOnly.length > 0 && title.length > 0 && !textOnly.startsWith(title)) return `${title} — ${textOnly}`;\n\treturn textOnly.length > 0 ? textOnly : title;\n};\nconst readString = (record, key) => {\n\tconst value = record[key];\n\treturn isString(value) ? value : void 0;\n};\nconst collectMessageFrom = ({ value, depth, seen }) => {\n\tif (isNil(value) || depth > MAX_MESSAGE_DEPTH) return;\n\tif (isString(value)) {\n\t\tconst trimmed = value.trim();\n\t\tif (trimmed.length === 0) return;\n\t\tif (isLikelyMarkupBody(trimmed)) {\n\t\t\tconst stripped = stripMarkup(trimmed);\n\t\t\treturn stripped.length > 0 ? stripped : void 0;\n\t\t}\n\t\treturn trimmed;\n\t}\n\tif (Array.isArray(value)) {\n\t\tif (seen.has(value)) return;\n\t\tseen.add(value);\n\t\tconst parts = value.map((entry) => collectMessageFrom({\n\t\t\tvalue: entry,\n\t\t\tdepth: depth + 1,\n\t\t\tseen\n\t\t})).filter((entry) => isString(entry) && entry.length > 0);\n\t\treturn parts.length > 0 ? parts.join(\"; \") : void 0;\n\t}\n\tif (isObjectRecord(value)) {\n\t\tif (seen.has(value)) return;\n\t\tseen.add(value);\n\t\tconst nested = value[\"message\"] ?? value[\"detail\"] ?? value[\"description\"] ?? value[\"reason\"] ?? value[\"error\"];\n\t\treturn collectMessageFrom({\n\t\t\tvalue: nested,\n\t\t\tdepth: depth + 1,\n\t\t\tseen\n\t\t});\n\t}\n};\nconst collectMessage = (value) => {\n\treturn collectMessageFrom({\n\t\tvalue,\n\t\tdepth: 0,\n\t\tseen: /* @__PURE__ */ new WeakSet()\n\t});\n};\nconst extractApiMessage = (responseBody) => {\n\tif (isNil(responseBody)) return;\n\tif (isString(responseBody) || Array.isArray(responseBody)) {\n\t\tconst collected = collectMessage(responseBody);\n\t\treturn collected ? truncate(collected) : void 0;\n\t}\n\tif (!isObjectRecord(responseBody)) return truncate(String(responseBody));\n\tconst candidates = [\n\t\tresponseBody[\"message\"],\n\t\tresponseBody[\"error_description\"],\n\t\tresponseBody[\"errorDescription\"],\n\t\tresponseBody[\"detail\"],\n\t\tresponseBody[\"title\"],\n\t\tresponseBody[\"error_message\"],\n\t\tresponseBody[\"errorMessage\"],\n\t\tresponseBody[\"errorMessages\"],\n\t\tresponseBody[\"errors\"],\n\t\tresponseBody[\"error\"],\n\t\tresponseBody[\"faultstring\"],\n\t\tresponseBody[\"fault\"],\n\t\tresponseBody[\"reason\"],\n\t\tresponseBody[\"description\"]\n\t];\n\tfor (const candidate of candidates) {\n\t\tconst collected = collectMessage(candidate);\n\t\tif (collected) return truncate(collected);\n\t}\n};\nconst toHttpStatus = (value) => {\n\treturn typeof value === \"number\" && value >= HTTP_STATUS_MIN && value <= HTTP_STATUS_MAX ? value : void 0;\n};\nconst extractResponseHttpDetails = (error) => {\n\tconst response = error[\"response\"];\n\tif (!isObjectRecord(response)) return null;\n\tconst statusValue = response[\"status\"];\n\tconst status = typeof statusValue === \"number\" ? statusValue : void 0;\n\tconst responseBody = response[\"body\"];\n\tconst headersValue = response[\"headers\"];\n\tconst headers = isObjectRecord(headersValue) ? headersValue : void 0;\n\tconst requestRaw = error[\"request\"];\n\tconst request = isObjectRecord(requestRaw) ? requestRaw : void 0;\n\tconst requestBody = request?.[\"body\"];\n\tconst requestUrl = request === void 0 ? void 0 : readString(request, \"url\");\n\tconst requestMethod = request === void 0 ? void 0 : readString(request, \"method\");\n\tif (isNil(status) && isNil(responseBody) && isNil(requestBody)) return null;\n\treturn {\n\t\tstatus,\n\t\tresponseBody,\n\t\tresponseHeaders: headers,\n\t\trequestBody,\n\t\trequestUrl,\n\t\trequestMethod,\n\t\tapiMessage: extractApiMessage(responseBody)\n\t};\n};\nconst extractClientHttpDetails = (error) => {\n\tconst status = toHttpStatus(error[\"status\"]);\n\tif (isNil(status)) return null;\n\tconst responseBody = error[\"error\"] ?? error[\"body\"];\n\tconst headersValue = error[\"headers\"];\n\treturn {\n\t\tstatus,\n\t\tresponseBody,\n\t\tresponseHeaders: isObjectRecord(headersValue) ? headersValue : void 0,\n\t\tapiMessage: extractApiMessage(responseBody)\n\t};\n};\nconst extractHttpDetails = (error) => {\n\treturn extractResponseHttpDetails(error) ?? extractClientHttpDetails(error);\n};\nconst rebuildSerializable = ({ value, depth, seen }) => {\n\tif (isNil(value) || isString(value) || typeof value === \"number\" || typeof value === \"boolean\") return value;\n\tif (Array.isArray(value) || isObjectRecord(value)) {\n\t\tif (seen.has(value)) return CIRCULAR_PLACEHOLDER;\n\t\tif (depth >= MAX_SERIALIZED_DEPTH) return TOO_DEEP_PLACEHOLDER;\n\t\tseen.add(value);\n\t\tif (Array.isArray(value)) return value.map((entry) => rebuildSerializable({\n\t\t\tvalue: entry,\n\t\t\tdepth: depth + 1,\n\t\t\tseen\n\t\t}));\n\t\treturn Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, rebuildSerializable({\n\t\t\tvalue: entry,\n\t\t\tdepth: depth + 1,\n\t\t\tseen\n\t\t})]));\n\t}\n\treturn String(value);\n};\nconst toSerializable = (value) => {\n\tif (isNil(value)) return value;\n\tconst { error } = tryCatchSync(() => JSON.stringify(value));\n\tif (isNil(error)) return value;\n\tconst rebuilt = tryCatchSync(() => rebuildSerializable({\n\t\tvalue,\n\t\tdepth: 0,\n\t\tseen: /* @__PURE__ */ new WeakSet()\n\t}));\n\treturn isNil(rebuilt.error) ? rebuilt.data : UNSERIALIZABLE_PLACEHOLDER;\n};\nconst toSerializableHttpDetails = (httpDetails) => {\n\tif (isNil(httpDetails)) return null;\n\tconst { responseBody, requestBody, responseHeaders } = httpDetails;\n\treturn {\n\t\t...httpDetails,\n\t\tresponseBody: toSerializable(responseBody),\n\t\trequestBody: toSerializable(requestBody),\n\t\tresponseHeaders: isNil(responseHeaders) ? void 0 : Object.fromEntries(Object.entries(responseHeaders).map(([key, value]) => [key, toSerializable(value)]))\n\t};\n};\nconst readErrorName = (error) => {\n\tconst name = readString(error, \"name\");\n\tif (!isNil(name) && name.length > 0 && name !== \"Error\") return name;\n\tconst ctor = error[\"constructor\"];\n\tif (typeof ctor === \"function\" && isString(ctor.name) && ctor.name.length > 0 && ctor.name !== \"Object\" && ctor.name !== \"Error\") return ctor.name;\n};\nconst readErrorMessage = (error) => {\n\tconst messageString = readString(error, \"message\");\n\tif (!isNil(messageString)) return messageString;\n\tconst stringified = String(error);\n\tif (stringified.length > 0 && stringified !== \"[object Object]\") return stringified;\n\treturn \"Unknown error\";\n};\nconst pickPlainMessage = ({ httpDetails, rawMessage }) => {\n\tif (httpDetails?.apiMessage) return httpDetails.apiMessage;\n\tconst cleaned = stripStack(rawMessage);\n\tif (cleaned.length > 0) return truncate(cleaned);\n\treturn \"Unknown error\";\n};\nconst isFriendlyPieceError = (value) => {\n\tif (!isObjectRecord(value)) return false;\n\treturn value[\"__apErrorVersion\"] === FRIENDLY_PIECE_ERROR_VERSION && typeof value[\"message\"] === \"string\";\n};\nconst formatPieceError = (error, options) => {\n\tconst raw = options?.raw;\n\tconst withRaw = (base) => {\n\t\tif (isNil(raw) || raw.length === 0 || !isNil(base.raw)) return base;\n\t\treturn {\n\t\t\t...base,\n\t\t\traw: truncateRaw(raw)\n\t\t};\n\t};\n\tif (isNil(error)) return withRaw({\n\t\t__apErrorVersion: FRIENDLY_PIECE_ERROR_VERSION,\n\t\tmessage: \"Unknown error\"\n\t});\n\tif (isString(error)) {\n\t\tconst cleaned = stripStack(error);\n\t\treturn withRaw({\n\t\t\t__apErrorVersion: FRIENDLY_PIECE_ERROR_VERSION,\n\t\t\tmessage: cleaned.length > 0 ? cleaned : \"Unknown error\"\n\t\t});\n\t}\n\tif (!isObjectRecord(error)) return withRaw({\n\t\t__apErrorVersion: FRIENDLY_PIECE_ERROR_VERSION,\n\t\tmessage: truncate(String(error))\n\t});\n\tif (isFriendlyPieceError(error)) return withRaw(error);\n\tconst httpDetails = extractHttpDetails(error);\n\tconst errorName = readErrorName(error);\n\tconst rawMessage = readErrorMessage(error);\n\tconst message = pickPlainMessage({\n\t\thttpDetails,\n\t\trawMessage\n\t});\n\treturn withRaw({\n\t\t__apErrorVersion: FRIENDLY_PIECE_ERROR_VERSION,\n\t\tmessage,\n\t\terrorName,\n\t\t...toSerializableHttpDetails(httpDetails) ?? {}\n\t});\n};\nconst tryParseFriendlyPieceError = (value) => {\n\tif (isNil(value)) return null;\n\tconst candidate = isString(value) ? safeJsonParse(value) : value;\n\treturn isFriendlyPieceError(candidate) ? candidate : null;\n};\n\n//#endregion\n//#region upstream/core-utils/lib/ssrf-ip-classifier.ts\nfunction parseOrNull(ip) {\n\ttry {\n\t\treturn ipaddr.parse(ip);\n\t} catch {\n\t\treturn null;\n\t}\n}\nfunction isInAllowList({ ip, allowList }) {\n\tif (allowList.includes(ip)) return true;\n\tconst addr = parseOrNull(ip);\n\tif (!addr) return false;\n\treturn allowList.some((entry) => entry.includes(\"/\") && matchesCidr({\n\t\taddr,\n\t\tcidr: entry\n\t}));\n}\nfunction matchesCidr({ addr, cidr }) {\n\ttry {\n\t\tconst range = ipaddr.parseCIDR(cidr);\n\t\tif (addr.kind() !== range[0].kind()) return false;\n\t\treturn addr.match(range);\n\t} catch {\n\t\treturn false;\n\t}\n}\nfunction isBlockedRange(addr) {\n\tif (addr.kind() === \"ipv6\") {\n\t\tconst v6 = addr;\n\t\tif (v6.isIPv4MappedAddress()) return isBlockedRange(v6.toIPv4Address());\n\t}\n\treturn addr.range() !== \"unicast\";\n}\nfunction isBlockedIp({ ip, allowList }) {\n\tif (isInAllowList({\n\t\tip,\n\t\tallowList\n\t})) return false;\n\tconst addr = parseOrNull(ip);\n\tif (!addr) return true;\n\treturn isBlockedRange(addr);\n}\nconst ssrfIpClassifier = { isBlockedIp };\n\n//#endregion\n//#region upstream/engine/lib/helper/dynamic-prop-keys.ts\nfunction escapePropsKeys(props) {\n\treturn Object.fromEntries(Object.entries(props).map(([key, property]) => [escapeKey(key), property]));\n}\nfunction unescapePropsKeys(props) {\n\treturn Object.fromEntries(Object.entries(props).map(([key, property]) => [unescapeKey(key), property]));\n}\nfunction unescapeInputKeys(value) {\n\tif (!isObject(value)) return value;\n\treturn Object.fromEntries(Object.entries(value).map(([key, child]) => [unescapeKey(key), child]));\n}\nfunction escapeKey(key) {\n\tif (!RESERVED_CHARS.test(key)) return key;\n\treturn ESCAPED_KEY_MARKER + key.replace(/[~.[\\]\"']/g, (char) => ESCAPE_SEQUENCES[char]);\n}\nfunction unescapeKey(key) {\n\tif (!key.startsWith(ESCAPED_KEY_MARKER)) return key;\n\treturn key.slice(ESCAPED_KEY_MARKER.length).replace(/~[0-5]/g, (sequence) => UNESCAPE_SEQUENCES[sequence]);\n}\nconst ESCAPED_KEY_MARKER = \"~ap~\";\nconst RESERVED_CHARS = /[~.[\\]\"']/;\nconst ESCAPE_SEQUENCES = {\n\t\"~\": \"~0\",\n\t\".\": \"~1\",\n\t\"[\": \"~2\",\n\t\"]\": \"~3\",\n\t\"\\\"\": \"~4\",\n\t\"'\": \"~5\"\n};\nconst UNESCAPE_SEQUENCES = Object.fromEntries(Object.entries(ESCAPE_SEQUENCES).map(([char, sequence]) => [sequence, char]));\nconst dynamicPropKeys = {\n\tescapePropsKeys,\n\tunescapePropsKeys,\n\tunescapeInputKeys\n};\n\n//#endregion\n//#region upstream/engine/lib/variables/processors/array-zipper.ts\nfunction getLongestArrayLengthInObject(props) {\n\treturn Math.max(...Object.values(props).map((value) => Array.isArray(value) ? value.length : 1));\n}\nfunction constructResultForIndex(props, index) {\n\treturn Object.entries(props).reduce((result, [key, value]) => {\n\t\tresult[key] = Array.isArray(value) ? value[index] : value;\n\t\treturn result;\n\t}, {});\n}\nconst arrayZipperProcessor = (_property, value) => {\n\tif (Array.isArray(value) || !isObject(value)) return value;\n\treturn Array.from({ length: getLongestArrayLengthInObject(value) }, (_, index) => constructResultForIndex(value, index));\n};\n\n//#endregion\n//#region upstream/engine/lib/variables/processors/checkbox.ts\nconst checkboxProcessor = (_property, value) => {\n\tif (isNil(value) || typeof value === \"boolean\") return value;\n\tif (typeof value === \"string\" && value.trim().length === 0) return;\n\tconst parsed = parseToJsonIfPossible(value);\n\treturn typeof parsed === \"boolean\" ? parsed : value;\n};\n\n//#endregion\n//#region upstream/engine/lib/variables/processors/date-time.ts\nconst dateTimeProcessor = (_property, value) => {\n\tdayjs.extend(utc);\n\tdayjs.extend(timezone);\n\tconst dateTimeString = value;\n\ttry {\n\t\tif (!dateTimeString) throw Error(\"Undefined input\");\n\t\treturn dayjs.tz(dateTimeString, \"UTC\").toISOString();\n\t} catch (error) {\n\t\tconsole.error(error);\n\t\treturn;\n\t}\n};\n\n//#endregion\n//#region upstream/engine/lib/variables/processors/file.ts\nconst fileProcessor = async (property, urlOrBase64) => {\n\tif (isNil(urlOrBase64) || !isString(urlOrBase64)) return null;\n\tconst streaming = property.type === \"FILE\" && property.streaming === true;\n\ttry {\n\t\tif (streaming) return await handleStreamingFile(urlOrBase64);\n\t\tconst file = handleBase64File(urlOrBase64);\n\t\tif (!isNil(file)) return file;\n\t\treturn await handleUrlFile(urlOrBase64);\n\t} catch (e) {\n\t\tconsole.error(e);\n\t\treturn null;\n\t}\n};\nfunction parseBase64File(propertyValue) {\n\tif (!isBase64(propertyValue, { allowMime: true })) return null;\n\tconst matches = propertyValue.match(/^data:([A-Za-z-+/]+);base64,(.+)$/);\n\tif (!matches || matches?.length !== 3) return null;\n\treturn {\n\t\textension: mimeExtension(matches[1]) || \"bin\",\n\t\tbuffer: Buffer.from(matches[2], \"base64\")\n\t};\n}\nfunction handleBase64File(propertyValue) {\n\tconst parsed = parseBase64File(propertyValue);\n\tif (isNil(parsed)) return null;\n\treturn new ApFile(`unknown.${parsed.extension}`, parsed.buffer, parsed.extension);\n}\nasync function handleUrlFile(path) {\n\tconst fileResponse = await fetch(path);\n\tif (!fileResponse.ok) return null;\n\tconst filename = getFileName(path, fileResponse.headers.get(\"content-disposition\"), fileResponse.headers.get(\"content-type\") ?? void 0) ?? \"unknown\";\n\tconst extension = extensionFromFilename(filename);\n\treturn new ApFile(filename, Buffer.from(await fileResponse.arrayBuffer()), extension);\n}\nasync function handleStreamingFile(propertyValue) {\n\tconst parsed = parseBase64File(propertyValue);\n\tif (!isNil(parsed)) return {\n\t\tfilename: `unknown.${parsed.extension}`,\n\t\textension: parsed.extension,\n\t\tsize: parsed.buffer.length,\n\t\tbody: Readable.from(parsed.buffer)\n\t};\n\tconst fileResponse = await fetch(propertyValue);\n\tif (!fileResponse.ok || isNil(fileResponse.body)) {\n\t\tawait fileResponse.body?.cancel();\n\t\treturn null;\n\t}\n\tconst filename = getFileName(propertyValue, fileResponse.headers.get(\"content-disposition\"), fileResponse.headers.get(\"content-type\") ?? void 0) ?? \"unknown\";\n\tconst extension = extensionFromFilename(filename);\n\tconst contentEncoding = fileResponse.headers.get(\"content-encoding\");\n\tconst contentLength = Number(fileResponse.headers.get(\"content-length\"));\n\treturn {\n\t\tfilename,\n\t\textension,\n\t\tsize: (isNil(contentEncoding) || contentEncoding.toLowerCase() === \"identity\") && Number.isInteger(contentLength) && contentLength > 0 ? contentLength : void 0,\n\t\tbody: Readable.fromWeb(fileResponse.body)\n\t};\n}\nfunction extensionFromFilename(filename) {\n\tconst parts = filename.split(\".\");\n\tconst last = parts.length > 1 ? parts.pop() : void 0;\n\treturn last ? last : void 0;\n}\nfunction getFileName(path, disposition, mimeType) {\n\tconst url = new URL(path);\n\tif (isNil(disposition)) {\n\t\tconst fileNameFromUrl = url.pathname.includes(\"/\") && url.pathname.split(\"/\").pop()?.includes(\".\") ? url.pathname.split(\"/\").pop() : null;\n\t\tif (!isNil(fileNameFromUrl)) return fileNameFromUrl;\n\t\treturn `unknown.${(mimeType ? mimeExtension(mimeType) : null) ?? \"bin\"}`;\n\t}\n\tconst utf8FilenameRegex = /filename\\*=UTF-8''([\\w%\\-.]+)(?:; ?|$)/i;\n\tif (utf8FilenameRegex.test(disposition)) {\n\t\tconst result = utf8FilenameRegex.exec(disposition);\n\t\tif (result && result.length > 1) return decodeURIComponent(result[1]);\n\t}\n\tconst filenameStart = disposition.toLowerCase().indexOf(\"filename=\");\n\tconst asciiFilenameRegex = /^filename=([\"']?)(.*?[^\\\\])\\1(?:; ?|$)/i;\n\tif (filenameStart >= 0) {\n\t\tconst partialDisposition = disposition.slice(filenameStart);\n\t\tconst matches = asciiFilenameRegex.exec(partialDisposition);\n\t\tif (matches != null && matches[2]) return matches[2];\n\t}\n\treturn null;\n}\nfunction mimeExtension(mimeType) {\n\tconst normalized = mimeType.split(\";\")[0].trim().toLowerCase();\n\treturn MIME_EXTENSIONS[normalized] ?? null;\n}\nconst MIME_EXTENSIONS = {\n\t\"application/json\": \"json\",\n\t\"application/pdf\": \"pdf\",\n\t\"application/xml\": \"xml\",\n\t\"application/zip\": \"zip\",\n\t\"application/gzip\": \"gz\",\n\t\"application/x-7z-compressed\": \"7z\",\n\t\"application/x-tar\": \"tar\",\n\t\"application/octet-stream\": \"bin\",\n\t\"application/msword\": \"doc\",\n\t\"application/vnd.openxmlformats-officedocument.wordprocessingml.document\": \"docx\",\n\t\"application/vnd.ms-excel\": \"xls\",\n\t\"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\": \"xlsx\",\n\t\"application/vnd.ms-powerpoint\": \"ppt\",\n\t\"application/vnd.openxmlformats-officedocument.presentationml.presentation\": \"pptx\",\n\t\"application/rtf\": \"rtf\",\n\t\"application/javascript\": \"js\",\n\t\"application/x-javascript\": \"js\",\n\t\"application/x-yaml\": \"yaml\",\n\t\"application/yaml\": \"yaml\",\n\t\"application/x-httpd-php\": \"php\",\n\t\"application/x-sh\": \"sh\",\n\t\"image/png\": \"png\",\n\t\"image/jpeg\": \"jpg\",\n\t\"image/jpg\": \"jpg\",\n\t\"image/gif\": \"gif\",\n\t\"image/webp\": \"webp\",\n\t\"image/svg+xml\": \"svg\",\n\t\"image/bmp\": \"bmp\",\n\t\"image/tiff\": \"tiff\",\n\t\"image/x-icon\": \"ico\",\n\t\"image/vnd.microsoft.icon\": \"ico\",\n\t\"image/heic\": \"heic\",\n\t\"image/heif\": \"heif\",\n\t\"image/avif\": \"avif\",\n\t\"text/plain\": \"txt\",\n\t\"text/html\": \"html\",\n\t\"text/css\": \"css\",\n\t\"text/csv\": \"csv\",\n\t\"text/javascript\": \"js\",\n\t\"text/markdown\": \"md\",\n\t\"text/xml\": \"xml\",\n\t\"text/tab-separated-values\": \"tsv\",\n\t\"text/yaml\": \"yaml\",\n\t\"audio/mpeg\": \"mp3\",\n\t\"audio/mp3\": \"mp3\",\n\t\"audio/mp4\": \"m4a\",\n\t\"audio/wav\": \"wav\",\n\t\"audio/x-wav\": \"wav\",\n\t\"audio/ogg\": \"ogg\",\n\t\"audio/webm\": \"weba\",\n\t\"audio/flac\": \"flac\",\n\t\"audio/aac\": \"aac\",\n\t\"video/mp4\": \"mp4\",\n\t\"video/mpeg\": \"mpeg\",\n\t\"video/webm\": \"webm\",\n\t\"video/quicktime\": \"mov\",\n\t\"video/x-msvideo\": \"avi\",\n\t\"video/ogg\": \"ogv\",\n\t\"font/woff\": \"woff\",\n\t\"font/woff2\": \"woff2\",\n\t\"font/ttf\": \"ttf\",\n\t\"font/otf\": \"otf\"\n};\n\n//#endregion\n//#region upstream/engine/lib/variables/processors/json.ts\nconst jsonProcessor = (_property, value) => {\n\tif (isNil(value)) return value;\n\ttry {\n\t\tif (typeof value === \"object\") return value;\n\t\treturn JSON.parse(value);\n\t} catch (error) {\n\t\tconsole.error(error);\n\t\treturn;\n\t}\n};\n\n//#endregion\n//#region upstream/engine/lib/variables/processors/multi-select.ts\nconst multiSelectProcessor = (_property, value) => {\n\tif (isNil(value) || Array.isArray(value)) return value;\n\tif (typeof value === \"string\" && value.trim().length === 0) return;\n\tconst parsed = parseToJsonIfPossible(value);\n\treturn Array.isArray(parsed) ? parsed : [value];\n};\n\n//#endregion\n//#region upstream/engine/lib/variables/processors/number.ts\nconst numberProcessor = (_property, value) => {\n\tif (isNil(value)) return value;\n\tif (value === \"\") return;\n\treturn Number(value);\n};\n\n//#endregion\n//#region upstream/engine/lib/variables/processors/object.ts\nconst objectProcessor = (_property, value) => {\n\tif (isNil(value)) return value;\n\tif (typeof value === \"string\") try {\n\t\treturn JSON.parse(value);\n\t} catch (e) {\n\t\treturn;\n\t}\n\tif (typeof value === \"object\" && !Array.isArray(value)) return value;\n};\n\n//#endregion\n//#region upstream/engine/lib/variables/processors/text.ts\nconst textProcessor = (property, value) => {\n\tif (isNil(value)) return value;\n\tif (typeof value === \"object\") return JSON.stringify(value);\n\tconst result = value.toString();\n\tif (result.length === 0 && !property.required) return;\n\treturn result;\n};\n\n//#endregion\n//#region upstream/engine/lib/variables/processors/index.ts\nconst processors = {\n\tJSON: jsonProcessor,\n\tOBJECT: objectProcessor,\n\tNUMBER: numberProcessor,\n\tLONG_TEXT: textProcessor,\n\tSHORT_TEXT: textProcessor,\n\tSECRET_TEXT: textProcessor,\n\tDATE_TIME: dateTimeProcessor,\n\tFILE: fileProcessor,\n\tMULTI_SELECT_DROPDOWN: multiSelectProcessor,\n\tSTATIC_MULTI_SELECT_DROPDOWN: multiSelectProcessor,\n\tCHECKBOX: checkboxProcessor\n};\n\n//#endregion\n//#region upstream/engine/lib/variables/props-processor.ts\nconst propsProcessor = { applyProcessorsAndValidators: async (resolvedInput, props, auth, requireAuth, propertySettings) => {\n\tlet dynamaicPropertiesSchema = void 0;\n\tif (Object.keys(propertySettings).length > 0) dynamaicPropertiesSchema = Object.fromEntries(Object.entries(propertySettings).map(([key, propertySetting]) => [key, propertySetting.schema]));\n\tconst processedInput = { ...resolvedInput };\n\tconst errors = {};\n\tconst authValue = resolvedInput[AUTHENTICATION_PROPERTY_NAME];\n\tif (authValue && requireAuth) {\n\t\tconst authPropsToProcess = getAuthPropsToProcess(authValue, auth);\n\t\tif (authPropsToProcess) {\n\t\t\tconst { processedInput: authProcessedInput, errors: authErrors } = await propsProcessor.applyProcessorsAndValidators(resolvedInput[AUTHENTICATION_PROPERTY_NAME], authPropsToProcess, void 0, false, {});\n\t\t\tprocessedInput[AUTHENTICATION_PROPERTY_NAME] = authProcessedInput;\n\t\t\tif (Object.keys(authErrors).length > 0) errors[AUTHENTICATION_PROPERTY_NAME] = authErrors;\n\t\t}\n\t}\n\tfor (const [key, value] of Object.entries(resolvedInput)) {\n\t\tconst property = props[key];\n\t\tif (isNil(property)) continue;\n\t\tif (property.type === \"DYNAMIC\") {\n\t\t\tconst valueWithOriginalKeys = dynamicPropKeys.unescapeInputKeys(value);\n\t\t\tprocessedInput[key] = valueWithOriginalKeys;\n\t\t\tif (!isNil(dynamaicPropertiesSchema?.[key])) {\n\t\t\t\tconst { processedInput: itemProcessedInput, errors: itemErrors } = await propsProcessor.applyProcessorsAndValidators(valueWithOriginalKeys, dynamicPropKeys.unescapePropsKeys(dynamaicPropertiesSchema[key]), void 0, false, {});\n\t\t\t\tprocessedInput[key] = itemProcessedInput;\n\t\t\t\tif (Object.keys(itemErrors).length > 0) errors[key] = itemErrors;\n\t\t\t}\n\t\t}\n\t\tif (property.type === \"ARRAY\" && property.properties) {\n\t\t\tconst arrayOfObjects = arrayZipperProcessor(property, value) ?? [];\n\t\t\tconst processedArray = [];\n\t\t\tconst processedErrors = [];\n\t\t\tfor (const item of arrayOfObjects) {\n\t\t\t\tconst { processedInput: itemProcessedInput, errors: itemErrors } = await propsProcessor.applyProcessorsAndValidators(item, property.properties, void 0, false, {});\n\t\t\t\tprocessedArray.push(itemProcessedInput);\n\t\t\t\tprocessedErrors.push(itemErrors);\n\t\t\t}\n\t\t\tprocessedInput[key] = processedArray;\n\t\t\tif (processedErrors.some((error) => Object.keys(error).length > 0)) errors[key] = { properties: processedErrors };\n\t\t}\n\t\tif (!property.required && isNil(processedInput[key])) processedInput[key] = void 0;\n\t\tconst processor = processors[property.type];\n\t\tif (processor) processedInput[key] = await processor(property, processedInput[key]);\n\t\tif (!(key !== \"auth\" && property.type !== \"MARKDOWN\")) continue;\n\t}\n\tfor (const [key, value] of Object.entries(processedInput)) {\n\t\tconst property = props[key];\n\t\tif (isNil(property)) continue;\n\t\tconst validationErrors = validateProperty(property, value, resolvedInput[key]);\n\t\tif (validationErrors.length > 0) errors[key] = validationErrors;\n\t}\n\tif (Object.keys(errors).length > 0) destroyOpenStreams(processedInput);\n\treturn {\n\t\tprocessedInput,\n\t\terrors\n\t};\n} };\nfunction destroyOpenStreams(value) {\n\tif (isNil(value) || typeof value !== \"object\" || Buffer.isBuffer(value)) return;\n\tif (value instanceof Readable) {\n\t\tvalue.destroy();\n\t\treturn;\n\t}\n\tfor (const child of Object.values(value)) destroyOpenStreams(child);\n}\nconst validateProperty = (property, value, originalValue) => {\n\tif (property.type === \"JSON\") {\n\t\tif (!property.required && originalValue === \"\") return [];\n\t\tif (!isNil(originalValue) && isNil(value)) return [`Expected JSON, received: ${originalValue}`];\n\t\tif (!property.required && isNil(value)) return [];\n\t\tif (!isObject(value) && !Array.isArray(value)) return [`Expected JSON, received: ${originalValue}`];\n\t\treturn [];\n\t}\n\tif (!property.required && isNil(value)) return [];\n\tswitch (property.type) {\n\t\tcase \"SHORT_TEXT\":\n\t\tcase \"LONG_TEXT\":\n\t\tcase \"RICH_TEXT\": return typeof value === \"string\" ? [] : [`Expected string, received: ${originalValue}`];\n\t\tcase \"NUMBER\": return typeof value === \"number\" && !Number.isNaN(value) ? [] : [`Expected number, received: ${originalValue}`];\n\t\tcase \"CHECKBOX\": return typeof value === \"boolean\" ? [] : [`Expected boolean, received: ${originalValue}`];\n\t\tcase \"DATE_TIME\": return typeof value === \"string\" ? [] : [`Invalid datetime format. Expected ISO format (e.g. 2024-03-14T12:00:00.000Z), received: ${originalValue}`];\n\t\tcase \"DATE_RANGE\": return DateRangeValue.safeParse(value).success ? [] : [`Expected date range, received: ${originalValue}`];\n\t\tcase \"ARRAY\":\n\t\tcase \"MULTI_SELECT_DROPDOWN\":\n\t\tcase \"STATIC_MULTI_SELECT_DROPDOWN\": return Array.isArray(value) ? [] : [`Expected array, received: ${originalValue}`];\n\t\tcase \"OBJECT\": return isObject(value) ? [] : [`Expected object, received: ${originalValue}`];\n\t\tcase \"FILE\": return isObject(value) ? [] : [`Expected file url or base64 with mimeType, received: ${originalValue}`];\n\t\tdefault: return [];\n\t}\n};\nfunction getAuthPropsToProcess(authValue, auth) {\n\tif (isNil(auth)) return null;\n\tconst usedAuthProperty = getAuthPropertyForValue({\n\t\tauthValueType: authValue.type,\n\t\tpieceAuth: auth\n\t});\n\tif ((usedAuthProperty?.type === \"CUSTOM_AUTH\" || usedAuthProperty?.type === \"OAUTH2\" || usedAuthProperty?.type === \"OIDC\") && !isNil(usedAuthProperty?.props)) return usedAuthProperty.props;\n\treturn null;\n}\n\n//#endregion\nexport { arrayZipperProcessor, checkboxProcessor, dateTimeProcessor, dynamicPropKeys, fileProcessor, formatPieceError, jsonProcessor, multiSelectProcessor, numberProcessor, objectProcessor, processors, propsProcessor, ssrfIpClassifier, textProcessor, tryParseFriendlyPieceError, validateProperty };\n//# sourceMappingURL=host.js.map","// Credential redaction for anything that gets journaled or shown to a user.\n// Two independent passes, because each catches what the other misses.\n\n// Key-based catches a credential the run never knew about: a piece's own\n// hardcoded key, a token it fetched mid-step.\n\n// Value-based catches a secret the run did resolve, wherever a piece spliced\n// it — into a message, a URL, a header it composed itself.\n\nexport const REDACTED_PREFIX = \"[redacted:\";\nexport const SECRET_MARKER = \"[redacted:secret]\";\nexport const CIRCULAR_MARKER = \"[circular]\";\nexport const TRUNCATED_MARKER = \"[truncated]\";\n\n// Bounds for the hostile-error path only. Ordinary step output is data a user\n// asked for, so it is redacted whole rather than truncated.\nconst ERROR_MAX_DEPTH = 8;\nconst ERROR_MAX_NODES = 1000;\n\n// Deep enough never to be reached by real data, shallow enough that the\n// recursive walk cannot overflow the stack on a self-nesting object.\nconst STACK_GUARD_DEPTH = 200;\n\n// Exact names, matched after stripping separators and case: \"X-Api-Key\",\n// \"x_api_key\" and \"apiKey\" are one name.\nconst SENSITIVE_NAMES = new Set([\n \"auth\",\n \"authorization\",\n \"proxyauthorization\",\n \"wwwauthenticate\",\n \"authtoken\",\n \"xauthtoken\",\n \"apikey\",\n \"xapikey\",\n \"apisecret\",\n \"bearer\",\n \"cookie\",\n \"setcookie\",\n \"credential\",\n \"credentials\",\n \"password\",\n \"passwd\",\n \"passphrase\",\n \"pwd\",\n \"privatekey\",\n \"secret\",\n \"secrettext\",\n \"sessionid\",\n \"signature\",\n \"token\",\n]);\n\n// A name ending in one of these is sensitive whatever prefixes it, which is\n// what catches githubToken, client_secret and the rest of the long tail.\nconst SENSITIVE_SUFFIXES = [\n \"apikey\",\n \"credentials\",\n \"password\",\n \"privatekey\",\n \"secret\",\n \"token\",\n];\n\n// Header and field names worth redacting inside a free-form string, where\n// there is no key to walk.\n\n// Deliberately a fixed list: a loose pattern over prose eats more of the\n// message than it saves.\n\n// Signature is the one alternative that carries its own affixes, because a\n// webhook MAC header wraps the word: x-hub-signature-256.\n\n// The affixed form is anchored on the literal \"signature\", with the prefix\n// matched by a lookbehind placed after it. A leading prefix pattern\n// ((?:[a-z0-9]+[-_])*signature) retries from every segment of a long\n// hyphen-separated run that never ends in \"signature\", which is quadratic:\n// whole seconds over a few hundred kilobytes of journaled text. The\n// lookbehind runs once per occurrence of the literal instead, and captures\n// the prefix so the marker still names the whole header.\nconst TEXT_FIELD = new RegExp(\n String.raw`(\\b(?:authorization|proxy-authorization|api[-_]?key|x-api-key|access[-_]?token|refresh[-_]?token|client[-_]?secret|set-cookie|cookie|password|secret|token)|signature(?<=\\b((?:[a-z0-9]+[-_])*)signature)(?:[-_][a-z0-9]+)*)\\b([\"']?)(\\s*[:=]\\s*)([\"']?)((?:(?:Bearer|Basic|Token)\\s+)?[^\\s\",;&)}]+)\\5`,\n \"gi\",\n);\n\nconst AUTH_SCHEME = /\\b(Bearer|Basic|Token)\\s+([A-Za-z0-9._~+/=-]{8,})/g;\n\nconst QUERY_PARAM = /([?&])([A-Za-z0-9_.%[\\]-]+)=([^&\\s\"'<>]+)/g;\n\n// The password half of a URL's userinfo, which no header or query pattern\n// reaches: https://user:s3cret@host/api.\n\n// Anchored on \"://\" with the scheme checked by the lookbehind behind it: a\n// leading scheme pattern ([a-z][a-z0-9+.-]*) rescans a long unbroken\n// alphanumeric run from every offset, which is quadratic — tens of seconds\n// over a 256 KiB run. The scheme is not consumed, and not rewritten either\n// way; only the password half is replaced.\nconst URL_USERINFO =\n /:\\/\\/(?<=[a-z][a-z0-9+.-]*:\\/\\/)([^/\\s:@]+):([^/\\s@]+)@/gi;\n\nexport function normalizeName(name: string): string {\n return name.toLowerCase().replace(/[^a-z0-9]/g, \"\");\n}\n\nexport function isSensitiveName(name: string): boolean {\n const normalized = normalizeName(name);\n if (!normalized) return false;\n if (SENSITIVE_NAMES.has(normalized)) return true;\n // Anywhere in the name, because a webhook MAC header carries its algorithm\n // after it: x-hub-signature-256.\n if (normalized.includes(\"signature\")) return true;\n return SENSITIVE_SUFFIXES.some(\n (suffix) =>\n normalized.length > suffix.length && normalized.endsWith(suffix),\n );\n}\n\nfunction marker(name: string): string {\n return `[redacted:${name.toLowerCase()}]`;\n}\n\nfunction shannonEntropy(text: string): number {\n const counts = new Map<string, number>();\n for (const char of text) counts.set(char, (counts.get(char) ?? 0) + 1);\n let entropy = 0;\n for (const count of counts.values()) {\n const p = count / text.length;\n entropy -= p * Math.log2(p);\n }\n return entropy;\n}\n\n// The bar a *guessed* secret must clear before its value is matched anywhere.\n\n// A short or repetitive guess (\"admin\", \"8080\", \"aaaaaaaa\") would hit unrelated\n// text and leave an error nobody can read; the key-based pass still covers it.\nconst MIN_VALUE_LENGTH = 8;\nconst MIN_DISTINCT_CHARS = 5;\nconst MIN_ENTROPY_BITS = 2;\n\n// A value the host hands over is a declaration, not a guess, so \"hunter2\" is\n// redacted. Only a value too short to be a credential is refused.\nconst MIN_DECLARED_LENGTH = 4;\n\nexport function isRedactableValue(value: unknown): value is string {\n if (typeof value !== \"string\") return false;\n if (value.length < MIN_VALUE_LENGTH) return false;\n if (new Set(value).size < MIN_DISTINCT_CHARS) return false;\n return shannonEntropy(value) >= MIN_ENTROPY_BITS;\n}\n\nexport function isDeclaredValue(value: unknown): value is string {\n return typeof value === \"string\" && value.length >= MIN_DECLARED_LENGTH;\n}\n\n// The AppConnectionValue discriminator, and anything shaped like an endpoint.\n\n// Both are configuration rather than credentials, and a URL is usually the\n// most useful thing left in a failed request's error.\nconst STRUCTURAL_NAMES = new Set([\"type\", \"authtype\"]);\nconst URL_LIKE = /^[a-z][a-z0-9+.-]*:\\/\\//i;\n\n// Every credential-shaped string leaf of a resolved connection. The fallback\n// for a host resolver that cannot say which of its values are secret.\nexport function collectSecretValues(\n value: unknown,\n into: Set<string> = new Set(),\n depth = 0,\n): Set<string> {\n if (depth > ERROR_MAX_DEPTH) return into;\n if (isRedactableValue(value)) {\n if (!URL_LIKE.test(value)) into.add(value);\n return into;\n }\n if (Array.isArray(value)) {\n for (const entry of value) collectSecretValues(entry, into, depth + 1);\n return into;\n }\n if (typeof value === \"object\" && value !== null) {\n for (const [key, entry] of Object.entries(value)) {\n if (STRUCTURAL_NAMES.has(normalizeName(key))) continue;\n collectSecretValues(entry, into, depth + 1);\n }\n }\n return into;\n}\n\nexport interface RedactOptions {\n // Concrete secret values resolved for this step; each occurrence is replaced.\n values?: Iterable<string>;\n maxDepth?: number;\n maxNodes?: number;\n}\n\n// A host-side handle from a thrown error to the secrets its step ran with, so\n// a catch far from the connection can still redact by value.\nconst thrownSecrets = new WeakMap<object, string[]>();\n\nexport function rememberSecrets<T>(error: T, values: string[]): T {\n if (typeof error === \"object\" && error !== null && values.length > 0) {\n thrownSecrets.set(error, values);\n }\n return error;\n}\n\nexport function secretsFor(error: unknown): string[] {\n if (typeof error !== \"object\" || error === null) return [];\n return thrownSecrets.get(error) ?? [];\n}\n\ninterface Pass {\n values: string[];\n maxDepth: number;\n maxNodes: number;\n nodes: number;\n}\n\n// Longest first, so a secret that contains another is replaced whole rather\n// than leaving its tail behind.\nfunction preparePass(options: RedactOptions | undefined): Pass {\n const values = [...(options?.values ?? [])]\n .filter(isDeclaredValue)\n .sort((a, b) => b.length - a.length);\n return {\n values,\n maxDepth: options?.maxDepth ?? STACK_GUARD_DEPTH,\n maxNodes: options?.maxNodes ?? Number.POSITIVE_INFINITY,\n nodes: 0,\n };\n}\n\nfunction safeDecode(name: string): string {\n try {\n return decodeURIComponent(name);\n } catch {\n return name;\n }\n}\n\nfunction replaceValues(text: string, values: string[]): string {\n let result = text;\n for (const value of values) {\n if (result.includes(value)) {\n result = result.split(value).join(SECRET_MARKER);\n }\n const encoded = encodeURIComponent(value);\n if (encoded !== value && result.includes(encoded)) {\n result = result.split(encoded).join(SECRET_MARKER);\n }\n }\n return result;\n}\n\nfunction redactText(text: string, pass: Pass): string {\n let result = replaceValues(text, pass.values);\n result = result.replace(\n URL_USERINFO,\n (_match, user: string) => `://${user}:${marker(\"password\")}@`,\n );\n result = result.replace(QUERY_PARAM, (match, sep: string, name: string) =>\n isSensitiveName(safeDecode(name)) ? `${sep}${name}=${marker(name)}` : match,\n );\n result = result.replace(\n AUTH_SCHEME,\n (_match, scheme: string) => `${scheme} ${marker(scheme)}`,\n );\n\n // Skipping a value that is already a marker keeps this pass from re-matching\n // what the query pass just wrote and swallowing the rest of the string.\n\n // signaturePrefix is the lookbehind's capture: the affixes before\n // \"signature\" sit outside the match, so they are stitched back onto the\n // name only for the marker — the text keeps them where they were.\n return result.replace(\n TEXT_FIELD,\n (\n match,\n name: string,\n signaturePrefix: string | undefined,\n nameQuote: string,\n sep: string,\n quote: string,\n value: string,\n ) =>\n value.startsWith(REDACTED_PREFIX)\n ? match\n : `${name}${nameQuote}${sep}${quote}${marker(`${signaturePrefix ?? \"\"}${name}`)}${quote}`,\n );\n}\n\n// A document header's or reference's operation counts per scope. Scope names\n// such as \"auth\" are not credentials, and the counts are numbers.\nfunction isScopeRevision(\n parent: Record<string, unknown>,\n key: string,\n entry: unknown,\n): boolean {\n return (\n key === \"revision\" &&\n typeof parent.documentType === \"string\" &&\n typeof entry === \"object\" &&\n entry !== null &&\n !Array.isArray(entry) &&\n Object.values(entry).every(\n (count) => typeof count === \"number\" && Number.isFinite(count),\n )\n );\n}\n\nfunction walk(\n value: unknown,\n pass: Pass,\n depth: number,\n seen: Set<object>,\n): unknown {\n if (typeof value === \"string\") return redactText(value, pass);\n if (typeof value !== \"object\" || value === null) return value;\n if (seen.has(value)) return CIRCULAR_MARKER;\n if (depth >= pass.maxDepth) return TRUNCATED_MARKER;\n if (pass.nodes >= pass.maxNodes) return TRUNCATED_MARKER;\n pass.nodes += 1;\n\n // Tracked per path, not globally: the same object appearing twice in a tree\n // is not a cycle, and calling it one would drop data a user needs.\n seen.add(value);\n try {\n if (Array.isArray(value)) {\n return value.map((entry) => walk(entry, pass, depth + 1, seen));\n }\n const result: Record<string, unknown> = {};\n const record = value as Record<string, unknown>;\n for (const [key, entry] of Object.entries(record)) {\n result[key] = isSensitiveName(key)\n ? marker(key)\n : isScopeRevision(record, key, entry)\n ? { ...(entry as Record<string, number>) }\n : walk(entry, pass, depth + 1, seen);\n }\n return result;\n } finally {\n seen.delete(value);\n }\n}\n\n// Redacts credentials from an arbitrary value: sensitive keys by name, known\n// secret values wherever they appear, sensitive URL query parameters.\n\n// Cycles are collapsed; nothing else is dropped, because this also runs over\n// step output a user asked to see.\nexport function redact(value: unknown, options?: RedactOptions): unknown {\n return walk(value, preparePass(options), 0, new Set());\n}\n\n// The same pass for an error object, which is attacker-shaped: depth and node\n// count are capped so a hostile error cannot make redaction expensive.\nexport function redactError(value: unknown, options?: RedactOptions): unknown {\n return redact(value, {\n maxDepth: ERROR_MAX_DEPTH,\n maxNodes: ERROR_MAX_NODES,\n ...options,\n });\n}\n\n// True when a value carries a marker this module wrote. Rerun uses it to\n// refuse a journaled output it cannot faithfully replay.\n\n// TRUNCATED_MARKER is matched whole, not as a substring: walk() only ever\n// writes it in place of an entire capped node, so prose that merely mentions\n// the word keeps replaying.\nexport function containsRedactedMarker(value: unknown, depth = 0): boolean {\n if (typeof value === \"string\") {\n return value.includes(REDACTED_PREFIX) || value === TRUNCATED_MARKER;\n }\n if (typeof value !== \"object\" || value === null) return false;\n if (depth >= STACK_GUARD_DEPTH) return false;\n return Object.values(value).some((entry) =>\n containsRedactedMarker(entry, depth + 1),\n );\n}\n\n// The string-only form, for a message that is already flat text.\nexport function redactMessage(text: string, options?: RedactOptions): string {\n return redactText(text, preparePass(options));\n}\n","// Context handed to a piece's auth.validate and auth.getConnectionIdentifier:\n// `{ auth, server }`, with auth as the flat property value.\nimport { throwingStub, withTouchTracking } from \"./stubs.js\";\nimport type { AuthValidationServerContext } from \"@powerhousedao/pieces-framework\";\n\nexport interface CheckConnectionContextOptions {\n auth?: unknown;\n // apiUrl / publicUrl when the host serves them; mintOidcToken always throws,\n // since no reactor mints tokens for a piece's connection check.\n server?: Omit<AuthValidationServerContext, \"mintOidcToken\">;\n onTouch?: (member: string) => void;\n}\n\nexport interface BuiltApCheckConnectionContext {\n auth: unknown;\n server: AuthValidationServerContext;\n}\n\nexport interface CheckConnectionContextHandle {\n context: BuiltApCheckConnectionContext;\n // Top-level members the check read; `UNDOCUMENTED:<name>` marks unknown reads.\n touched: ReadonlySet<string>;\n}\n\nexport function buildCheckConnectionContext(\n options: CheckConnectionContextOptions = {},\n): CheckConnectionContextHandle {\n const touched = new Set<string>();\n const base: Record<string, unknown> = {\n auth: options.auth,\n server: options.server\n ? {\n ...options.server,\n mintOidcToken: throwingStub(\"server.mintOidcToken\"),\n }\n : throwingStub(\"server\"),\n };\n const context = withTouchTracking(base, touched, options.onTouch);\n return {\n context: context as unknown as BuiltApCheckConnectionContext,\n touched,\n };\n}\n","// One file-size ceiling for both directions. Inbound hydration (a FILE prop\n// that arrives as a URL, a data URI or an attachment ref) and outbound\n// ctx.files.write share it, because a piece that can emit a file the next step\n// cannot ingest is worse than a piece that refuses both.\nimport { Transform, type TransformCallback } from \"node:stream\";\nimport { DEFAULT_HOST_CALL_TIMEOUT_MS } from \"../worker/host-call.js\";\n\nexport const DEFAULT_MAX_FILE_BYTES = 8 * 1024 * 1024;\n\n// What the environment asks for, or undefined when it asks for nothing usable.\n// Read per call: a host may set it after this module is loaded.\nexport function configuredMaxFileBytes(): number | undefined {\n const raw = process.env.PH_WORKFLOWS_PIECE_MAX_FILE_BYTES;\n if (raw === undefined) return undefined;\n const parsed = Number(raw);\n return Number.isFinite(parsed) && parsed > 0 ? Math.floor(parsed) : undefined;\n}\n\n// The worker child is forked without an environment, so its limit arrives on\n// the wire instead. Requests are serialized per worker: one value at a time.\nlet fromWire: number | undefined;\n\nexport function setMaxFileBytes(limit: number | undefined): void {\n fromWire = limit;\n}\n\nexport function maxFileBytes(): number {\n return fromWire ?? configuredMaxFileBytes() ?? DEFAULT_MAX_FILE_BYTES;\n}\n\n/** How long a piece's call of its host may take before the step gives up on\n * it. Read per call, like the file ceiling, and travelling on the wire for the\n * same reason: the child is forked with no environment. */\nexport const HOST_CALL_TIMEOUT_ENV = \"PH_WORKFLOWS_HOST_CALL_TIMEOUT_MS\";\n\n/**\n * The host-call cap for one step.\n *\n * The 10s default outran reality for a reactor dispatch under load and the\n * step was reported FAILED for a write that had been committed (backlog item\n * 6). So it is configurable, and it is never shorter than the step's OWN\n * timeout: a step the author gave two minutes should not have its host calls\n * cut off after ten seconds. The child still clips each call to end before\n * the step's kill deadline (`worker/host-call.ts`).\n */\nexport function hostCallTimeoutForStep(\n stepTimeoutMs: number | undefined,\n env: Record<string, string | undefined> = process.env,\n): number {\n const configured = Number(env[HOST_CALL_TIMEOUT_ENV]);\n const base =\n Number.isFinite(configured) && configured > 0\n ? Math.floor(configured)\n : DEFAULT_HOST_CALL_TIMEOUT_MS;\n return Math.max(base, stepTimeoutMs ?? 0);\n}\n\nexport class FileTooLargeError extends Error {\n readonly size: number;\n readonly limit: number;\n\n constructor(size: number, limit: number = maxFileBytes()) {\n super(\n `File of ${size} bytes exceeds the ${limit} byte limit ` +\n `(raise PH_WORKFLOWS_PIECE_MAX_FILE_BYTES to allow more)`,\n );\n this.name = \"FileTooLargeError\";\n this.size = size;\n this.limit = limit;\n }\n}\n\nexport function assertWithinLimit(size: number): void {\n const limit = maxFileBytes();\n if (size > limit) throw new FileTooLargeError(size, limit);\n}\n\n// Counts bytes as they pass and fails the stream past the cap, so an\n// undeclared or understated body never lands whole in memory or on disk.\nexport function byteCap(limit: number = maxFileBytes()): Transform {\n let seen = 0;\n return new Transform({\n transform(chunk: Buffer, _encoding, done: TransformCallback) {\n seen += chunk.byteLength;\n if (seen > limit) done(new FileTooLargeError(seen, limit));\n else done(null, chunk);\n },\n });\n}\n","// Two FilesService implementations plus the staged-file contract that carries\n// bytes back to the host.\n//\n// `ctx.files.write()` is called *during* action.run(), inside the forked\n// worker, and the worker protocol has no worker-to-host request channel. So\n// this follows the pattern storeState already establishes — push in, return\n// whole — using the one thing a fork shares with its parent: the filesystem.\n// The worker writes bytes to a staging directory and returns a provisional\n// `apfile://<token>`; the host ingests each staged file after the step returns\n// and rewrites the tokens in the output before journalling it.\nimport { randomUUID } from \"node:crypto\";\nimport { createWriteStream } from \"node:fs\";\nimport { mkdir, rm, stat, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { Readable } from \"node:stream\";\nimport { pipeline } from \"node:stream/promises\";\nimport {\n assertWithinLimit,\n byteCap,\n FileTooLargeError,\n maxFileBytes,\n} from \"./limits.js\";\n\nexport { FileTooLargeError, maxFileBytes };\n\nexport const APFILE_SCHEME = \"apfile://\";\n\n// One file the piece wrote, as it crosses back on ResultResponse.files.\nexport interface StagedFile {\n // The provisional ref handed to the piece; the host rewrites it in place.\n token: string;\n path: string;\n fileName: string;\n size: number;\n contentType?: string;\n}\n\n// What a piece may hand ctx.files.write: upstream takes a Buffer or a Readable.\nexport type ApFileData = Buffer | Uint8Array | Readable;\n\n// The framework's FilesService for both actions and triggers, with fileName\n// optional.\nexport interface ApFilesService {\n write(file: { fileName?: string; data: ApFileData }): Promise<string>;\n}\n\n// A Readable drained into memory under the cap, for the inline fallback.\nasync function drain(data: Readable): Promise<Buffer> {\n const chunks: Buffer[] = [];\n for await (const chunk of data.pipe(byteCap())) chunks.push(chunk as Buffer);\n return Buffer.concat(chunks);\n}\n\n// Default for both actions and triggers when the host injects nothing: inline\n// the bytes as a data URI so the payload stays self-contained. Bounded by the\n// shared cap, since a data URI lands in the run journal.\nexport class DataUriFilesService implements ApFilesService {\n async write(file: { fileName?: string; data: ApFileData }): Promise<string> {\n const data =\n file.data instanceof Readable\n ? await drain(file.data)\n : Buffer.isBuffer(file.data)\n ? file.data\n : Buffer.from(file.data);\n if (data.byteLength > maxFileBytes()) {\n throw new FileTooLargeError(data.byteLength);\n }\n return `data:application/octet-stream;base64,${data.toString(\"base64\")}`;\n }\n}\n\nconst EXTENSION_TYPES: Record<string, string> = {\n pdf: \"application/pdf\",\n png: \"image/png\",\n jpg: \"image/jpeg\",\n jpeg: \"image/jpeg\",\n webp: \"image/webp\",\n tif: \"image/tiff\",\n tiff: \"image/tiff\",\n txt: \"text/plain\",\n json: \"application/json\",\n csv: \"text/csv\",\n};\n\nfunction contentTypeFor(fileName: string): string | undefined {\n const extension = fileName.split(\".\").pop()?.toLowerCase();\n return extension ? EXTENSION_TYPES[extension] : undefined;\n}\n\n// Worker-side service: writes into `<stagingDir>/<uuid>` and remembers what it\n// wrote so the worker can report it on the response.\nexport class StagedFilesService implements ApFilesService {\n private readonly files: StagedFile[] = [];\n\n constructor(private readonly stagingDir: string) {}\n\n staged(): StagedFile[] {\n return [...this.files];\n }\n\n async write(file: { fileName?: string; data: ApFileData }): Promise<string> {\n const token = randomUUID();\n const fileName =\n file.fileName && file.fileName !== \"\" ? file.fileName : token;\n const target = path.join(this.stagingDir, token);\n let size: number;\n if (file.data instanceof Readable) {\n // Capped while it streams to disk: a piece cannot fill the disk with a\n // file the host would refuse anyway.\n await mkdir(this.stagingDir, { recursive: true });\n try {\n await pipeline(file.data, byteCap(), createWriteStream(target));\n } catch (error) {\n await rm(target, { force: true });\n throw error;\n }\n size = (await stat(target)).size;\n } else {\n const data = Buffer.isBuffer(file.data)\n ? file.data\n : Buffer.from(file.data);\n // Checked before anything touches the disk, for the same reason.\n assertWithinLimit(data.byteLength);\n await mkdir(this.stagingDir, { recursive: true });\n await writeFile(target, data);\n size = data.byteLength;\n }\n this.files.push({\n token: `${APFILE_SCHEME}${token}`,\n path: target,\n fileName,\n size,\n contentType: contentTypeFor(fileName),\n });\n return `${APFILE_SCHEME}${token}`;\n }\n}\n\n// Replaces every provisional token in a step output with the real ref the host\n// got back from its attachment store. Walks the whole value: a piece may nest\n// the ref anywhere, and a plain string replace over the serialized JSON would\n// corrupt any base64 that happens to contain the token.\nexport function rewriteFileRefs(\n value: unknown,\n refs: Map<string, string>,\n): unknown {\n if (refs.size === 0) return value;\n if (typeof value === \"string\") return refs.get(value) ?? value;\n if (Array.isArray(value)) {\n return value.map((entry) => rewriteFileRefs(entry, refs));\n }\n if (typeof value === \"object\" && value !== null) {\n const out: Record<string, unknown> = {};\n for (const [key, entry] of Object.entries(value)) {\n out[key] = rewriteFileRefs(entry, refs);\n }\n return out;\n }\n return value;\n}\n","// Run-time coercion of stored config values into the shapes pieces expect: the\n// engine's own property processors, with our file hydration in front of theirs.\nimport type { PieceProperty } from \"@powerhousedao/pieces-framework\";\nimport { createReadStream } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { Readable } from \"node:stream\";\nimport type { ReadableStream as WebReadableStream } from \"node:stream/web\";\nimport {\n arrayZipperProcessor,\n processors,\n validateProperty,\n type ProcessorFn,\n} from \"@powerhousedao/pieces-framework/host\";\nimport type { ApProperty } from \"../types.js\";\nimport {\n assertWithinLimit,\n byteCap,\n DEFAULT_MAX_FILE_BYTES,\n maxFileBytes,\n} from \"./limits.js\";\n\n// Framework ApFile (filename, data, extension, base64) as a plain object so\n// it survives IPC and structured cloning.\nexport interface ApFileValue {\n filename: string;\n extension?: string;\n base64: string;\n data: Buffer;\n}\n\n// Framework ApStreamingFile: what a `streaming: true` FILE prop receives.\nexport interface ApStreamingFileValue {\n filename: string;\n extension?: string;\n size?: number;\n body: Readable;\n // Set only when the bytes are a staged file on local disk.\n path?: string;\n}\n\n// Opens the file on first read: a piece that reads `path` never opens a descriptor.\nfunction lazyFileStream(filePath: string): Readable {\n return Readable.from(\n (async function* () {\n yield* createReadStream(filePath);\n })(),\n { objectMode: false },\n );\n}\n\n// A staged attachment on disk, for a streaming FILE prop.\nexport interface OpenedFile {\n path: string;\n size: number;\n filename?: string;\n contentType?: string;\n}\n\nexport interface FetchedFile {\n data: Buffer;\n filename?: string;\n contentType?: string;\n}\n\nexport interface NormalizeOptions {\n // Resolves a URL-valued FILE prop; defaults to fetch() with a size cap.\n fetchFile?: (url: string) => Promise<FetchedFile>;\n // Resolves a reference-valued FILE prop (attachment:// or apfile://). The\n // worker resolves these from files the host staged on disk, so the bytes\n // never cross IPC.\n resolveRef?: (ref: string) => Promise<FetchedFile>;\n // The staged file itself, for a streaming FILE prop.\n openRef?: (ref: string) => Promise<OpenedFile>;\n}\n\n// Re-exported for compatibility; the ceiling itself lives in limits.ts so the\n// inbound and outbound paths cannot drift apart.\nexport const MAX_FILE_BYTES = DEFAULT_MAX_FILE_BYTES;\nconst FETCH_TIMEOUT_MS = 30_000;\n\n// A FILE prop whose value is a reference the host has to resolve.\nconst FILE_REF = /^(?:attachment|apfile):\\/\\//i;\n\nexport class FileFetchError extends Error {\n constructor(url: string, reason: string) {\n super(`Could not fetch FILE prop \"${url}\": ${reason}`);\n this.name = \"FileFetchError\";\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\nconst DATA_URI = /^data:([^;,]*)((?:;[^;,]*)*),([\\s\\S]*)$/;\n\nfunction extensionOf(filename: string): string | undefined {\n const dot = filename.lastIndexOf(\".\");\n return dot > 0 && dot < filename.length - 1\n ? filename.slice(dot + 1)\n : undefined;\n}\n\nconst MIME_EXTENSIONS: Record<string, string> = {\n \"image/png\": \"png\",\n \"image/jpeg\": \"jpg\",\n \"image/gif\": \"gif\",\n \"image/webp\": \"webp\",\n \"image/svg+xml\": \"svg\",\n \"application/pdf\": \"pdf\",\n \"application/json\": \"json\",\n \"text/plain\": \"txt\",\n \"text/csv\": \"csv\",\n};\n\n// base64 is computed on first read and kept, like upstream's ApFile getter:\n// a piece that only reads `data` never pays for a second copy of the file.\nfunction fileValue(\n filename: string,\n extension: string | undefined,\n data: Buffer,\n base64?: string,\n): ApFileValue {\n const file = { filename, ...(extension ? { extension } : {}), data };\n let encoded = base64;\n Object.defineProperty(file, \"base64\", {\n enumerable: true,\n configurable: true,\n get: () => (encoded ??= data.toString(\"base64\")),\n set: (value: string) => {\n encoded = value;\n },\n });\n return file as ApFileValue;\n}\n\nfunction fileName(\n filename: string | undefined,\n contentType: string | undefined,\n): { name: string; extension: string | undefined } {\n const mime = contentType?.split(\";\")[0].trim().toLowerCase();\n const mimeExtension = mime ? MIME_EXTENSIONS[mime] : undefined;\n const name =\n filename && filename !== \"\"\n ? filename\n : `file${mimeExtension ? `.${mimeExtension}` : \"\"}`;\n return { name, extension: extensionOf(name) ?? mimeExtension };\n}\n\nfunction toFileValue(\n data: Buffer,\n filename: string | undefined,\n contentType: string | undefined,\n): ApFileValue {\n const { name, extension } = fileName(filename, contentType);\n return fileValue(name, extension, data);\n}\n\nfunction filenameFromDisposition(header: string | null): string | undefined {\n if (!header) return undefined;\n const utf8 = /filename\\*=(?:UTF-8'')?([^;]+)/i.exec(header);\n if (utf8) {\n try {\n return decodeURIComponent(utf8[1].trim().replace(/^\"|\"$/g, \"\"));\n } catch {\n // fall through to the plain form\n }\n }\n const plain = /filename=\"?([^\";]+)\"?/i.exec(header);\n return plain ? plain[1].trim() : undefined;\n}\n\nasync function openUrl(url: string): Promise<{\n response: Response;\n declared: number | undefined;\n filename: string | undefined;\n}> {\n let response: Response;\n try {\n response = await fetch(url, {\n signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),\n });\n } catch (error) {\n throw new FileFetchError(\n url,\n error instanceof Error ? error.message : String(error),\n );\n }\n if (!response.ok) throw new FileFetchError(url, `HTTP ${response.status}`);\n const limit = maxFileBytes();\n // Content-Length counts the encoded body; only an identity body has the\n // file's own size.\n const header = response.headers.get(\"content-length\");\n const declared =\n header !== null && !response.headers.get(\"content-encoding\")\n ? Number(header)\n : undefined;\n if (declared !== undefined && Number.isFinite(declared) && declared > limit) {\n await response.body?.cancel().catch(() => undefined);\n throw new FileFetchError(url, `${declared} bytes exceeds ${limit}`);\n }\n let filename = filenameFromDisposition(\n response.headers.get(\"content-disposition\"),\n );\n if (!filename) {\n const segment = new URL(url).pathname.split(\"/\").filter(Boolean).pop();\n if (segment) filename = decodeURIComponent(segment);\n }\n return {\n response,\n declared:\n declared !== undefined && Number.isFinite(declared)\n ? declared\n : undefined,\n filename,\n };\n}\n\nfunction cappedBody(response: Response): Readable {\n const body = response.body\n ? Readable.fromWeb(response.body as WebReadableStream<Uint8Array>)\n : Readable.from([]);\n const cap = byteCap();\n body.on(\"error\", (error) => cap.destroy(error));\n return body.pipe(cap);\n}\n\nasync function defaultFetchFile(url: string): Promise<FetchedFile> {\n const { response, filename } = await openUrl(url);\n const chunks: Buffer[] = [];\n try {\n for await (const chunk of cappedBody(response))\n chunks.push(chunk as Buffer);\n } catch (error) {\n throw new FileFetchError(\n url,\n error instanceof Error ? error.message : String(error),\n );\n }\n return {\n data: Buffer.concat(chunks),\n filename,\n contentType: response.headers.get(\"content-type\") ?? undefined,\n };\n}\n\nconst FILE_KEYS = new Set([\"filename\", \"extension\", \"base64\", \"data\"]);\n\nfunction isFileShaped(value: unknown): value is ApFileValue {\n return (\n isRecord(value) &&\n typeof value.filename === \"string\" &&\n (typeof value.base64 === \"string\" || Buffer.isBuffer(value.data))\n );\n}\n\n// URL or data URI → ApFile shape; already-shaped objects are completed\n// (data/base64 derived from each other); anything else passes through.\nexport async function toApFile(\n value: unknown,\n options: NormalizeOptions = {},\n): Promise<unknown> {\n if (isFileShaped(value)) {\n const data = Buffer.isBuffer(value.data)\n ? value.data\n : Buffer.from(value.base64, \"base64\");\n // The cap applies to every branch, not just the fetched one: an oversized\n // data URI or file-shaped object would otherwise slip past it.\n assertWithinLimit(data.byteLength);\n const extension = value.extension ?? extensionOf(value.filename);\n const rest = Object.fromEntries(\n Object.entries(value).filter(([key]) => !FILE_KEYS.has(key)),\n );\n return Object.assign(\n fileValue(\n value.filename,\n extension,\n data,\n typeof value.base64 === \"string\" ? value.base64 : undefined,\n ),\n rest,\n );\n }\n if (typeof value !== \"string\") return value;\n const trimmed = value.trim();\n if (trimmed === \"\") return undefined;\n const dataUri = DATA_URI.exec(trimmed);\n if (dataUri) {\n const decoded = decodeDataUri(dataUri);\n return toFileValue(decoded.data, decoded.name, decoded.mime);\n }\n if (FILE_REF.test(trimmed)) {\n if (!options.resolveRef) {\n throw new FileFetchError(\n trimmed,\n \"no attachment resolver is available in this context\",\n );\n }\n const resolved = await options.resolveRef(trimmed);\n assertWithinLimit(resolved.data.byteLength);\n return toFileValue(resolved.data, resolved.filename, resolved.contentType);\n }\n if (/^https?:\\/\\//i.test(trimmed)) {\n const fetched = await (options.fetchFile ?? defaultFetchFile)(trimmed);\n return toFileValue(fetched.data, fetched.filename, fetched.contentType);\n }\n return value;\n}\n\nfunction decodeDataUri(match: RegExpExecArray): {\n data: Buffer;\n name: string | undefined;\n mime: string | undefined;\n} {\n const [, mime, params, payload] = match;\n const data = /;base64/i.test(params)\n ? Buffer.from(payload, \"base64\")\n : Buffer.from(decodeURIComponent(payload), \"utf8\");\n assertWithinLimit(data.byteLength);\n const nameParam = /;name=([^;]+)/i.exec(params)?.[1];\n return {\n data,\n name: nameParam ? decodeURIComponent(nameParam) : undefined,\n mime: mime || undefined,\n };\n}\n\nfunction streamingValue(\n name: string,\n extension: string | undefined,\n size: number | undefined,\n body: Readable,\n path?: string,\n): ApStreamingFileValue {\n return {\n filename: name,\n ...(extension ? { extension } : {}),\n ...(size !== undefined ? { size } : {}),\n body,\n ...(path ? { path } : {}),\n };\n}\n\n// Streaming FILE prop: the piece reads the body itself, so nothing is held in\n// memory. A staged reference streams from disk, a URL from the network.\nexport async function toApStreamingFile(\n value: unknown,\n options: NormalizeOptions = {},\n): Promise<unknown> {\n if (isRecord(value) && value.body instanceof Readable) return value;\n if (isFileShaped(value)) {\n const file = (await toApFile(value, options)) as ApFileValue;\n return streamingValue(\n file.filename,\n file.extension,\n file.data.byteLength,\n Readable.from([file.data]),\n );\n }\n if (typeof value !== \"string\") return value;\n const trimmed = value.trim();\n if (trimmed === \"\") return undefined;\n const dataUri = DATA_URI.exec(trimmed);\n if (dataUri) {\n const decoded = decodeDataUri(dataUri);\n const { name, extension } = fileName(decoded.name, decoded.mime);\n return streamingValue(\n name,\n extension,\n decoded.data.byteLength,\n Readable.from([decoded.data]),\n );\n }\n if (FILE_REF.test(trimmed)) {\n if (!options.openRef) {\n throw new FileFetchError(\n trimmed,\n \"no attachment resolver is available in this context\",\n );\n }\n const opened = await options.openRef(trimmed);\n assertWithinLimit(opened.size);\n const { name, extension } = fileName(opened.filename, opened.contentType);\n const filePath = resolve(opened.path);\n return streamingValue(\n name,\n extension,\n opened.size,\n lazyFileStream(filePath),\n filePath,\n );\n }\n if (/^https?:\\/\\//i.test(trimmed)) {\n const { response, declared, filename } = await openUrl(trimmed);\n const { name, extension } = fileName(\n filename,\n response.headers.get(\"content-type\") ?? undefined,\n );\n return streamingValue(name, extension, declared, cappedBody(response));\n }\n return value;\n}\n\n// ARRAY has no entry in the processor table: the engine zips an object of\n// parallel arrays into rows itself, then processes each row's own props.\nasync function normalizeArray(\n prop: ApProperty,\n value: unknown,\n options: NormalizeOptions,\n): Promise<unknown> {\n const fields = prop.properties;\n if (!fields) return value;\n const zipped: unknown = arrayZipperProcessor(prop as PieceProperty, value);\n if (!Array.isArray(zipped)) return value;\n return Promise.all(\n (zipped as unknown[]).map((item) =>\n isRecord(item) ? normalizePropsValue(fields, item, options) : item,\n ),\n );\n}\n\n// An ApFile is a class instance whose base64 is a prototype getter, and no\n// structured clone carries either; flatten it at the boundary (see ApFileValue).\nfunction plainFile(value: unknown): unknown {\n if (!isRecord(value) || typeof value.filename !== \"string\") return value;\n const { data } = value;\n if (!Buffer.isBuffer(data)) return value;\n const extension =\n typeof value.extension === \"string\"\n ? value.extension\n : extensionOf(value.filename);\n return fileValue(value.filename, extension, data);\n}\n\nconst table = processors as Record<string, ProcessorFn | undefined>;\n\n// The types whose processor failing means \"not JSON\", not \"not usable\".\nconst JSON_LIKE = new Set([\"JSON\", \"OBJECT\"]);\n\nexport async function normalizeValue(\n prop: ApProperty,\n value: unknown,\n options: NormalizeOptions = {},\n): Promise<unknown> {\n if (value === undefined || value === null) return value;\n if (prop.type === \"ARRAY\") return normalizeArray(prop, value, options);\n if (prop.type === \"FILE\") {\n if (prop.streaming === true) return toApStreamingFile(value, options);\n // Our hydration owns the forms the engine's own processor cannot resolve:\n // attachment and apfile refs, the size cap, and a host-injected fetcher.\n const hydrated = await toApFile(value, options);\n if (typeof hydrated !== \"string\") return hydrated;\n return plainFile(await table.FILE?.(prop as PieceProperty, hydrated));\n }\n const type = prop.type;\n const processor = type ? table[type] : undefined;\n if (!processor) return value;\n // Unreadable JSON drops here like any other type; validation names it.\n const processed = plainFile(await processor(prop as PieceProperty, value));\n return type === \"OBJECT\" && !isRecord(processed) ? undefined : processed;\n}\n\n// Normalises every configured value with a matching prop schema; keys\n// without a schema (or props without a value) pass through untouched.\nexport async function normalizePropsValue(\n props: Record<string, ApProperty> | undefined,\n values: Record<string, unknown>,\n options: NormalizeOptions = {},\n): Promise<Record<string, unknown>> {\n if (!props || !isRecord(values)) return values;\n const out: Record<string, unknown> = { ...values };\n for (const [name, prop] of Object.entries(props)) {\n if (!(name in out) || !isRecord(prop)) continue;\n const normalized = await normalizeValue(prop, out[name], options);\n if (normalized === undefined) delete out[name];\n else out[name] = normalized;\n }\n return out;\n}\n\n// Upstream's error shape: a field's messages, or an ARRAY's per-row errors.\nexport interface PropsValidationErrors {\n [key: string]: string[] | { properties: PropsValidationErrors[] };\n}\n\nfunction hasErrors(errors: PropsValidationErrors): boolean {\n return Object.keys(errors).length > 0;\n}\n\nfunction preview(value: unknown): string {\n const text = typeof value === \"string\" ? value : JSON.stringify(value);\n return text.length > 60 ? `${text.slice(0, 57)}...` : text;\n}\n\n// A JSON or OBJECT value its processor could not read: an optional prop would\n// otherwise pass the validator as simply absent.\nfunction unreadableJson(\n prop: ApProperty,\n value: unknown,\n original: unknown,\n): string | undefined {\n if (prop.type === undefined || !JSON_LIKE.has(prop.type)) return undefined;\n if (value !== undefined || original === undefined || original === null) {\n return undefined;\n }\n if (original === \"\") return undefined;\n return prop.type === \"OBJECT\"\n ? `expects a JSON object, received: ${preview(original)}`\n : `is not valid JSON, received: ${preview(original)}`;\n}\n\n// Upstream's validator over values our processors already coerced. Every\n// declared prop is checked, so a required one that is absent fails too.\nexport function validatePropsValue(\n props: Record<string, ApProperty> | undefined,\n processed: Record<string, unknown>,\n original: Record<string, unknown>,\n): PropsValidationErrors {\n const errors: PropsValidationErrors = {};\n if (!props) return errors;\n for (const [name, prop] of Object.entries(props)) {\n if (!isRecord(prop)) continue;\n const value = processed[name];\n const raw = original[name];\n if (prop.type === \"ARRAY\" && prop.properties && Array.isArray(value)) {\n const zipped: unknown = arrayZipperProcessor(prop as PieceProperty, raw);\n const rawRows = Array.isArray(zipped) ? (zipped as unknown[]) : [];\n const rows = (value as unknown[]).map((row, index) => {\n const rawRow = rawRows[index];\n return isRecord(row)\n ? validatePropsValue(\n prop.properties,\n row,\n isRecord(rawRow) ? rawRow : row,\n )\n : {};\n });\n if (rows.some(hasErrors)) errors[name] = { properties: rows };\n continue;\n }\n const unreadable = unreadableJson(prop, value, raw);\n if (unreadable) {\n errors[name] = [unreadable];\n continue;\n }\n const messages = validateProperty(prop as PieceProperty, value, raw);\n if (messages.length > 0) errors[name] = messages;\n }\n return errors;\n}\n\nfunction describeErrors(\n errors: PropsValidationErrors,\n props: Record<string, ApProperty> | undefined,\n path = \"\",\n): string[] {\n return Object.entries(errors).flatMap(([name, entry]) => {\n const label = path\n ? `${path}.${name}`\n : `${props?.[name]?.displayName ?? name} (${name})`;\n if (Array.isArray(entry)) return [`${label}: ${entry.join(\", \")}`];\n const rowProps = props?.[name]?.properties;\n return entry.properties.flatMap((row, index) =>\n describeErrors(row, rowProps, `${path ? label : name}[${index}]`),\n );\n });\n}\n\n// Thrown before piece code runs; `errors` carries upstream's shape.\nexport class PropsValidationError extends Error {\n constructor(\n owner: string,\n readonly errors: PropsValidationErrors,\n props: Record<string, ApProperty> | undefined,\n ) {\n super(\n `Invalid input for ${owner}: ${describeErrors(errors, props).join(\"; \")}`,\n );\n this.name = \"PropsValidationError\";\n }\n}\n\n// What the builder writes into a step upstream: a prop left unset takes its\n// defaultValue, the value the editor shows for it.\nfunction withDefaults(\n props: Record<string, ApProperty>,\n values: Record<string, unknown>,\n): Record<string, unknown> {\n const out = { ...values };\n for (const [name, prop] of Object.entries(props)) {\n if (!isRecord(prop)) continue;\n if (!(name in out)) {\n if (prop.defaultValue !== undefined) out[name] = prop.defaultValue;\n continue;\n }\n const fields = prop.properties;\n if (prop.type !== \"ARRAY\" || !fields) continue;\n const rows: unknown = arrayZipperProcessor(\n prop as PieceProperty,\n out[name],\n );\n if (Array.isArray(rows)) {\n out[name] = (rows as unknown[]).map((row) =>\n isRecord(row) ? withDefaults(fields, row) : row,\n );\n }\n }\n return out;\n}\n\n// Defaults, coercion, then validation: the values run() receives, or a\n// PropsValidationError naming each field that failed.\nexport async function preparePropsValue(\n owner: string,\n props: Record<string, ApProperty> | undefined,\n values: Record<string, unknown>,\n options: NormalizeOptions = {},\n): Promise<Record<string, unknown>> {\n if (!props || !isRecord(values)) return values;\n const original = withDefaults(props, values);\n const processed = await normalizePropsValue(props, original, options);\n const errors = validatePropsValue(props, processed, original);\n if (hasErrors(errors)) {\n throw new PropsValidationError(owner, errors, props);\n }\n return processed;\n}\n","// Structural types for published Activepieces bundles (Path B). Bundles inline\n// their framework, so all typing is duck-typed — see ../../10-spike-notes-s6a.md.\nimport type {\n ActionBase,\n BasePropertySchema,\n DropdownOption,\n DropdownProperty,\n DropdownState,\n PieceBase,\n TriggerBase,\n WebhookHandshakeConfiguration,\n} from \"@powerhousedao/pieces-framework\";\n\nexport { DEDUPE_KEY_PROPERTY } from \"@powerhousedao/pieces-framework\";\n\n// Widened from the framework's PropertyType: a bundle inlines its own copy of\n// the enum, so a value read off one is compared as a string, never by identity.\nexport type ApPropertyType = string;\n\nexport type ApDropdownOption = Pick<\n DropdownOption<unknown>,\n \"label\" | \"value\"\n> &\n Partial<Pick<DropdownOption<unknown>, \"description\" | \"icon\">>;\n\n// STATIC_DROPDOWN options are plain data; DROPDOWN options is a resolver function.\nexport type ApStaticDropdownState = Pick<\n DropdownState<unknown>,\n \"disabled\" | \"placeholder\"\n> & { options: ApDropdownOption[] };\n\n// Every field optional: an unknown bundle version may omit any of them, and a\n// missing field must read as absent rather than fail the descriptor.\nexport type ApProperty = Partial<\n Pick<\n BasePropertySchema,\n \"displayName\" | \"description\" | \"placeholder\" | \"advanced\"\n >\n> &\n Partial<Pick<DropdownProperty<unknown, boolean>, \"refreshers\">> & {\n type?: ApPropertyType;\n required?: boolean;\n defaultValue?: unknown;\n options?: ApStaticDropdownState | ((...args: unknown[]) => unknown);\n // Resolver function on DYNAMIC properties.\n props?: (...args: unknown[]) => unknown;\n // FILE: hand the piece a stream instead of the bytes.\n streaming?: boolean;\n // ARRAY: schema of each item's fields; absent for plain value arrays.\n properties?: Record<string, ApProperty>;\n // Layout and control hints, each read off only the types that declare it.\n width?: string;\n icon?: string;\n reveals?: string[];\n variant?: string;\n display?: string;\n min?: number;\n max?: number;\n step?: number;\n refreshOnSearch?: boolean;\n formatProperty?: string;\n // The core piece's form hints; see PiecePropDescriptor.\n showWhen?: unknown;\n emptyChoice?: unknown;\n };\n\n// Widened from PropertyGroupDisplay: tabs | section | summary | builder | footer.\nexport interface ApPropertyGroup {\n key?: string;\n display?: string;\n label?: string;\n description?: string;\n icon?: string;\n props?: string[];\n}\n\nexport interface ApErrorHandlingOption {\n defaultValue?: boolean;\n hide?: boolean;\n}\n\n// requireAuth is UI metadata only — pieces run without auth despite it (spike finding).\nexport type ApAction = Partial<\n Pick<ActionBase, \"name\" | \"displayName\" | \"description\" | \"requireAuth\">\n> & {\n props?: Record<string, ApProperty>;\n // Authored shape of run()'s return, for the expression picker. Plain data,\n // and never validated against — a piece may return whatever it likes.\n outputSchema?: unknown;\n // \"human\" | \"ai\" | \"both\"; absent counts as human-visible.\n audience?: string;\n propertyGroups?: ApPropertyGroup[];\n // READ | SEARCH | WRITE | DESTRUCTIVE, widened for the cross-bundle reason.\n classification?: string;\n errorHandlingOptions?: {\n retryOnFailure?: ApErrorHandlingOption;\n continueOnFailure?: ApErrorHandlingOption;\n };\n // Output ports, read only off a piece the host runs in process.\n ports?: unknown;\n // \"read\" | \"write\"; anything else reads as undeclared.\n requireReactor?: unknown;\n run: (ctx: unknown) => Promise<unknown>;\n // Called instead of run by a single-step test.\n test?: (ctx: unknown) => Promise<unknown>;\n};\n\n// Widened from TriggerStrategy for the same reason as ApPropertyType:\n// WEBHOOK | POLLING | MANUAL | APP_WEBHOOK, read off a foreign bundle's enum.\nexport type ApTriggerStrategy = string;\n\n// strategy widened from WebhookHandshakeStrategy: NONE | HEADER_PRESENT |\n// QUERY_PRESENT | BODY_PARAM_PRESENT | HEAD_REQUEST.\nexport type ApHandshakeConfiguration = Partial<\n Omit<WebhookHandshakeConfiguration, \"strategy\">\n> & { strategy?: string };\n\nexport type ApTrigger = Partial<\n Pick<\n TriggerBase,\n \"name\" | \"displayName\" | \"description\" | \"requireAuth\" | \"sampleData\"\n >\n> & {\n type?: ApTriggerStrategy;\n // Widened from TriggerTestStrategy: SIMULATION | TEST_FUNCTION.\n testStrategy?: string;\n // A form the editor draws instead of the props, e.g. \"schedule\".\n display?: unknown;\n requireReactor?: unknown;\n props?: Record<string, ApProperty>;\n propertyGroups?: ApPropertyGroup[];\n outputSchema?: unknown;\n handshakeConfiguration?: ApHandshakeConfiguration;\n // Widened from WebhookRenewConfiguration: CRON | NONE.\n renewConfiguration?: { strategy?: string; cronExpression?: string };\n onEnable?: (ctx: unknown) => Promise<void>;\n onDisable?: (ctx: unknown) => Promise<void>;\n onStart?: (ctx: unknown) => Promise<unknown>;\n run?: (ctx: unknown) => Promise<unknown[]>;\n test?: (ctx: unknown) => Promise<unknown[]>;\n onHandshake?: (ctx: unknown) => Promise<unknown>;\n onRenew?: (ctx: unknown) => Promise<void>;\n};\n\n// `categories` is widened from PieceCategory[] for the cross-bundle reason\n// above; `auth` is the raw property, not the framework's PieceAuthProperty.\nexport type ApPiece = Pick<PieceBase, \"displayName\"> &\n Partial<\n Pick<\n PieceBase,\n | \"description\"\n | \"logoUrl\"\n | \"authors\"\n | \"minimumSupportedRelease\"\n | \"maximumSupportedRelease\"\n >\n > & {\n categories?: string[];\n deprecated?: boolean;\n // An array when the piece offers several auth methods.\n auth?: ApProperty | ApProperty[];\n // A bundle exposes these as the built record or as a zero-arg method; the\n // framework's own Piece class only ever has the method.\n actions?: Record<string, ApAction> | (() => Record<string, ApAction>);\n triggers?: Record<string, ApTrigger> | (() => Record<string, ApTrigger>);\n getAction?: (name: string) => ApAction | undefined;\n getTrigger?: (name: string) => ApTrigger | undefined;\n metadata?: () => Record<string, unknown>;\n };\n\n// Normalizes the record-vs-method variants of `piece.actions`.\nexport function getActions(piece: ApPiece): Record<string, ApAction> {\n const actions =\n typeof piece.actions === \"function\" ? piece.actions() : piece.actions;\n return actions ?? {};\n}\n\n// Normalizes the record-vs-method variants of `piece.triggers`.\nexport function getTriggers(piece: ApPiece): Record<string, ApTrigger> {\n const triggers =\n typeof piece.triggers === \"function\" ? piece.triggers() : piece.triggers;\n return triggers ?? {};\n}\n","// Design-time channel (doc 06 §2.5): builds the PropertyContext handed to\n// DROPDOWN options() / DYNAMIC props() resolvers, and invokes them out-of-band.\nimport {\n getActions,\n getTriggers,\n type ApPiece,\n type ApProperty,\n} from \"../types.js\";\nimport { throwingStub, withTouchTracking } from \"./stubs.js\";\nimport type {\n ConnectionsManager,\n FlowsContext,\n PropertyContext,\n ReactorReadClient,\n ServerContext,\n} from \"@powerhousedao/pieces-framework\";\n\n// The framework's FlowsContext.list, minus the SeekPage cursors the host does\n// not serve: a resolver only ever reads `data`.\nexport interface FlowsProvider {\n list(\n ...params: Parameters<FlowsContext[\"list\"]>\n ): Promise<{ data: unknown[] }>;\n}\n\n// The framework's ConnectionsManager with its return widened: the host serves\n// whatever a connection resolved to, not only the shapes upstream enumerates.\nexport interface ConnectionsProvider {\n get(...params: Parameters<ConnectionsManager[\"get\"]>): Promise<unknown>;\n}\n\nexport type BuiltApPropertyContext = Omit<\n PropertyContext,\n \"flows\" | \"connections\"\n> & {\n flows: FlowsProvider;\n connections: ConnectionsProvider;\n // Read-only at design time, whatever the block declares (ADR 0005 §10).\n reactor: ReactorReadClient;\n};\n\nexport interface PropertyContextOptions {\n searchValue?: string;\n // Injected capabilities; anything omitted throws with its member path.\n flows?: FlowsProvider;\n connections?: ConnectionsProvider;\n server?: ServerContext;\n projectId?: string;\n // ctx.reactor for a resolver whose block declares requireReactor. Absent,\n // the member throws by name.\n reactor?: ReactorReadClient;\n onTouch?: (member: string) => void;\n}\n\nexport interface PropertyContextHandle {\n context: BuiltApPropertyContext;\n // Top-level members the resolver read; `UNDOCUMENTED:<name>` marks unknown reads.\n touched: ReadonlySet<string>;\n}\n\nexport function buildPropertyContext(\n options: PropertyContextOptions = {},\n): PropertyContextHandle {\n const touched = new Set<string>();\n const base: Record<string, unknown> = {\n searchValue: options.searchValue,\n reactor: options.reactor ?? throwingStub(\"reactor\"),\n server: options.server ?? throwingStub(\"server\"),\n project: {\n id: options.projectId ?? \"project\",\n externalId: () => Promise.resolve(options.projectId ?? \"project\"),\n },\n flows: options.flows ?? { list: throwingStub(\"flows.list\") },\n connections: options.connections ?? {\n get: throwingStub(\"connections.get\"),\n },\n };\n const context = withTouchTracking(base, touched, options.onTouch);\n return { context: context as unknown as BuiltApPropertyContext, touched };\n}\n\nexport class NotDynamicPropertyError extends Error {\n constructor(actionName: string, propName: string) {\n super(`Property \"${actionName}.${propName}\" has no dynamic resolver`);\n this.name = \"NotDynamicPropertyError\";\n }\n}\n\nfunction pickResolver(\n prop: ApProperty,\n): ((...args: unknown[]) => unknown) | undefined {\n if (typeof prop.options === \"function\") return prop.options;\n if (typeof prop.props === \"function\") return prop.props;\n return undefined;\n}\n\nexport interface ResolveDynamicPropertyParams {\n piece: ApPiece;\n // Action or trigger name, per kind (default \"action\").\n actionName: string;\n kind?: \"action\" | \"trigger\";\n propName: string;\n // Resolved values of the prop's refresher inputs (auth and sibling props).\n refresherValues?: Record<string, unknown>;\n context: BuiltApPropertyContext;\n}\n\n// Props map of an action or trigger; throws when the owner is unknown.\nexport function ownerProps(\n piece: ApPiece,\n actionName: string,\n kind: \"action\" | \"trigger\" = \"action\",\n): Record<string, ApProperty> {\n const owner =\n kind === \"trigger\"\n ? (getTriggers(piece)[actionName] as\n | { props?: Record<string, ApProperty> }\n | undefined)\n : (getActions(piece)[actionName] as\n | { props?: Record<string, ApProperty> }\n | undefined);\n if (!owner) throw new Error(`No ${kind} \"${actionName}\" on piece`);\n return owner.props ?? {};\n}\n\nexport function findProperty(\n piece: ApPiece,\n actionName: string,\n propName: string,\n kind: \"action\" | \"trigger\" = \"action\",\n): ApProperty {\n const prop = ownerProps(piece, actionName, kind)[propName] as\n | ApProperty\n | undefined;\n if (!prop)\n throw new Error(`No prop \"${propName}\" on ${kind} \"${actionName}\"`);\n return prop;\n}\n\n// Invokes a DROPDOWN options() or DYNAMIC props() resolver. The result is\n// returned untouched: pieces may soft-fail with a disabled DropdownState.\nexport async function resolveDynamicProperty(\n params: ResolveDynamicPropertyParams,\n): Promise<unknown> {\n const { piece, actionName, propName, kind = \"action\" } = params;\n const prop = findProperty(piece, actionName, propName, kind);\n const resolver = pickResolver(prop);\n if (!resolver) throw new NotDynamicPropertyError(actionName, propName);\n return await resolver(params.refresherValues ?? {}, params.context);\n}\n\nexport interface ParsedResolverId {\n packageName: string;\n actionName: string;\n propName: string;\n}\n\n// Inverse of the descriptor's id scheme: activepieces:<pkg>#<action>.<prop>.\nexport function parseDynamicResolverId(id: string): ParsedResolverId {\n const match = /^activepieces:(.+)#(.+)\\.([^.]+)$/.exec(id);\n if (!match) throw new Error(`Invalid dynamic resolver id: ${id}`);\n return { packageName: match[1], actionName: match[2], propName: match[3] };\n}\n\nexport async function resolveByResolverId(\n piece: ApPiece,\n resolverId: string,\n refresherValues: Record<string, unknown>,\n context: BuiltApPropertyContext,\n): Promise<unknown> {\n const { actionName, propName } = parseDynamicResolverId(resolverId);\n return resolveDynamicProperty({\n piece,\n actionName,\n propName,\n refresherValues,\n context,\n });\n}\n","// Our TriggerHookContext → theirs (doc 06 §2.8): one builder covering the\n// strategy variants; identity/payload as data, capabilities injected or stubbed.\nimport { Cron } from \"croner\";\nimport { DEDUPE_KEY_PROPERTY, type ApTrigger } from \"../types.js\";\nimport {\n InMemoryKeyValueStore,\n type ActionContextIdentity,\n type KeyValueStore,\n} from \"./action.js\";\nimport type { ConnectionsProvider, FlowsProvider } from \"./props.js\";\nimport type { ReactorOption } from \"./reactor-option.js\";\nimport { normalizeStoreScope, type StoreScopeName } from \"./store-scope.js\";\nimport { throwingStub, withTouchTracking } from \"./stubs.js\";\nimport type { ApFilesService } from \"./files.js\";\nimport type {\n TriggerStrategy,\n InputPropertyMap,\n ServerContext,\n SetScheduleRequest,\n TestOrRunHookContext,\n} from \"@powerhousedao/pieces-framework\";\n\n// Both branches of the framework's SetScheduleRequest, as the piece asked.\nexport type RecordedSchedule = SetScheduleRequest;\n\ntype HookContextFor<S extends TriggerStrategy> = TestOrRunHookContext<\n undefined,\n InputPropertyMap,\n S\n>;\n\nexport type RecordedListener = Parameters<\n HookContextFor<TriggerStrategy.APP_WEBHOOK>[\"app\"][\"createListeners\"]\n>[0];\n\n// The floor for an interval schedule; a cron is validated the way upstream's\n// engine does, by handing the expression to a parser. Upstream sets this at a\n// minute, a fair default for a hosted multi-tenant scheduler and too coarse\n// here, where a polling trigger is the reactor's own loop against a service it\n// owns. See MIN_SCHEDULE_INTERVAL_MS in reactor/schedule.ts, the floor the\n// supervisor actually clamps to.\nexport const MIN_SCHEDULE_INTERVAL_MS = 1_000;\n\nexport class InvalidCronExpressionError extends Error {\n constructor(cronExpression: string) {\n super(`Invalid cron expression \"${cronExpression}\"`);\n this.name = \"InvalidCronExpressionError\";\n }\n}\n\nexport class InvalidScheduleIntervalError extends Error {\n constructor(intervalMs: unknown) {\n super(\n `Invalid schedule interval ${String(intervalMs)}: expected a whole number of milliseconds, at least ${MIN_SCHEDULE_INTERVAL_MS}`,\n );\n this.name = \"InvalidScheduleIntervalError\";\n }\n}\n\n// setSchedule's own validation, as the engine's trigger helper performs it: an\n// interval is a whole number at or above the floor, a cron has to parse.\nexport function validateSchedule(request: RecordedSchedule): RecordedSchedule {\n if (\"intervalMs\" in request) {\n const { intervalMs } = request;\n if (\n !Number.isInteger(intervalMs) ||\n intervalMs < MIN_SCHEDULE_INTERVAL_MS\n ) {\n throw new InvalidScheduleIntervalError(intervalMs);\n }\n return { intervalMs };\n }\n const timezone = request.timezone ?? \"UTC\";\n let parsed: Cron;\n try {\n parsed = new Cron(request.cronExpression, { timezone, legacyMode: false });\n } catch {\n throw new InvalidCronExpressionError(request.cronExpression);\n }\n if (!parsed.nextRun()) {\n throw new InvalidCronExpressionError(request.cronExpression);\n }\n return { cronExpression: request.cronExpression, timezone };\n}\n\nexport type TriggerContextOptions = TriggerContextBaseOptions & ReactorOption;\n\ninterface TriggerContextBaseOptions {\n propsValue: Record<string, unknown>;\n auth?: unknown;\n store?: KeyValueStore;\n // \"test\" for test hooks so they never touch the live cursor; \"\" otherwise.\n // Ignored when hostPartitionedStore is set — the host separates them there.\n storePrefix?: string;\n // The store partitions on (scope, key) itself, so the key reaches it\n // verbatim instead of carrying the scope as a name prefix. See scopedKey.\n hostPartitionedStore?: boolean;\n identity?: ActionContextIdentity;\n // onEnable: an unchanged trigger re-enabling; pollingHelper keeps its cursor.\n isRepublish?: boolean;\n // WEBHOOK / APP_WEBHOOK: the incoming request; also handed to test runs.\n payload?: unknown;\n webhookUrl?: string;\n flows?: FlowsProvider;\n connections?: ConnectionsProvider;\n server?: ServerContext;\n // run/test hooks only per the AP contract; omitted members throw, named.\n files?: ApFilesService;\n onTouch?: (member: string) => void;\n}\n\n// One shape for every strategy: the framework splits TriggerHookContext by\n// TriggerStrategy, but a bundle's declared strategy is not known at build time.\nexport type BuiltApTriggerContext = HookContextFor<TriggerStrategy.POLLING> &\n HookContextFor<TriggerStrategy.WEBHOOK> &\n HookContextFor<TriggerStrategy.APP_WEBHOOK>;\n\nexport interface TriggerContextHandle {\n context: BuiltApTriggerContext;\n touched: ReadonlySet<string>;\n // setSchedule / app.createListeners calls, for the supervisor to arm.\n schedules: RecordedSchedule[];\n listeners: RecordedListener[];\n}\n\nexport function buildTriggerContext(\n options: TriggerContextOptions,\n): TriggerContextHandle {\n const { identity = {} } = options;\n const store = options.store ?? new InMemoryKeyValueStore();\n const touched = new Set<string>();\n const schedules: RecordedSchedule[] = [];\n const listeners: RecordedListener[] = [];\n\n // AP's engine store layout, for a store that is one flat map: FLOW scope\n // (the default) nests under the flow id; PROJECT scope uses the bare key.\n\n // Matching the enum's \"COLLECTION\" value alone missed a piece that passes\n // the name instead, which then silently got flow scope.\n const prefix = options.storePrefix ?? \"\";\n const flowId = identity.flowId ?? \"flow\";\n const scopedKey = (key: string, scope?: unknown) =>\n normalizeStoreScope(scope) === \"PROJECT\"\n ? `${prefix}${key}`\n : `${prefix}flow_${flowId}/${key}`;\n\n // A host-partitioned store owns the layout, so the scope travels beside the\n // key rather than inside it, exactly as buildActionContext passes it.\n\n // No \"test\" prefix on that path: a prefix aliases, so a live key named\n // \"testMode\" is a sample's \"Mode\" once both share one flat partition.\n\n // Separating a sample is then the host's job, by partition — which a prefix\n // could not do anyway, since nothing can enumerate a sample's keys to drop.\n const address = (\n key: string,\n scope?: unknown,\n ): [string, StoreScopeName | undefined] =>\n options.hostPartitionedStore\n ? [key, normalizeStoreScope(scope)]\n : [scopedKey(key, scope), undefined];\n\n const base: Record<string, unknown> = {\n auth: options.auth,\n propsValue: options.propsValue,\n isRepublish: options.isRepublish ?? false,\n store: {\n put: (key: string, value: unknown, scope?: unknown) => {\n const [at, partition] = address(key, scope);\n return store.put(at, value, partition);\n },\n get: (key: string, scope?: unknown) => store.get(...address(key, scope)),\n delete: (key: string, scope?: unknown) =>\n store.delete(...address(key, scope)),\n },\n flows: {\n list:\n options.flows?.list.bind(options.flows) ?? throwingStub(\"flows.list\"),\n current: {\n id: identity.flowId ?? \"flow\",\n version: { id: identity.flowVersionId ?? \"flow-version\" },\n },\n },\n step: { name: identity.stepName ?? \"trigger\" },\n project: {\n id: identity.projectId ?? \"project\",\n externalId: () => Promise.resolve(identity.projectId ?? \"project\"),\n },\n connections: options.connections ?? {\n get: throwingStub(\"connections.get\"),\n },\n server: options.server ?? throwingStub(\"server\"),\n webhookUrl: options.webhookUrl ?? \"http://localhost:0/webhook\",\n payload: options.payload,\n setSchedule: (schedule: RecordedSchedule) => {\n schedules.push(validateSchedule(schedule));\n },\n app: {\n createListeners: (listener: RecordedListener) => {\n listeners.push(listener);\n },\n },\n files: options.files ?? throwingStub(\"files\"),\n reactor: options.reactor ?? throwingStub(\"reactor\"),\n };\n\n const context = withTouchTracking(base, touched, options.onTouch);\n return {\n context: context as unknown as BuiltApTriggerContext,\n touched,\n schedules,\n listeners,\n };\n}\n\n// Dedup key per doc 08 §4.4: the payload's own _dedupe_key wins; the caller\n// falls back to its own synthesis when absent.\nexport function extractDedupeKey(payload: unknown): string | undefined {\n if (typeof payload !== \"object\" || payload === null) return undefined;\n const value = (payload as Record<string, unknown>)[DEDUPE_KEY_PROPERTY];\n return typeof value === \"string\" ? value : undefined;\n}\n\nexport class TriggerHookNotImplementedError extends Error {\n constructor(triggerName: string, hook: string) {\n super(`Trigger \"${triggerName}\" does not implement ${hook}()`);\n this.name = \"TriggerHookNotImplementedError\";\n }\n}\n\nexport type TriggerLifecycleHook =\n | \"onEnable\"\n | \"onDisable\"\n | \"run\"\n | \"test\"\n | \"onHandshake\"\n | \"onRenew\";\n\n// Invokes one lifecycle hook with the built context; result is returned untouched.\nexport async function runTriggerHook(\n trigger: ApTrigger,\n hook: TriggerLifecycleHook,\n handle: TriggerContextHandle,\n): Promise<unknown> {\n const fn = trigger[hook];\n if (typeof fn !== \"function\") {\n throw new TriggerHookNotImplementedError(trigger.name ?? \"unknown\", hook);\n }\n return await fn.call(trigger, handle.context);\n}\n","//#region src/workflow/strategy.ts\nconst DELIVERIES = {\n\tPOLLING: \"poll\",\n\tWEBHOOK: \"webhook\",\n\tMANUAL: \"manual\"\n};\nconst APP_WEBHOOK_UNSUPPORTED = \"TriggerStrategy.APP_WEBHOOK (app-level webhooks) is not supported\";\nvar TriggerStrategyError = class extends Error {\n\tstrategy;\n\tconstructor(strategy, issue) {\n\t\tsuper(issue);\n\t\tthis.name = \"TriggerStrategyError\";\n\t\tthis.strategy = strategy;\n\t}\n};\nfunction checkTriggerStrategy(strategy) {\n\tif (typeof strategy === \"string\" && Object.hasOwn(DELIVERIES, strategy)) return { delivery: DELIVERIES[strategy] };\n\tif (strategy === \"APP_WEBHOOK\") return { issue: APP_WEBHOOK_UNSUPPORTED };\n\treturn { issue: strategy === void 0 || strategy === null || strategy === \"\" ? \"The trigger declares no strategy\" : `Unknown trigger strategy ${JSON.stringify(strategy)}` };\n}\nfunction triggerDelivery(strategy) {\n\tconst check = checkTriggerStrategy(strategy);\n\tif (\"issue\" in check) throw new TriggerStrategyError(strategy, check.issue);\n\treturn check.delivery;\n}\n\n//#endregion\n//#region src/workflow/schedule.ts\nconst DEFAULT_TIMEZONE = \"UTC\";\nconst SCHEDULE_UNIT_MS = {\n\tminutes: 6e4,\n\thours: 36e5,\n\tdays: 864e5\n};\nconst SCHEDULE_MODES = [\"cron\", \"interval\"];\nvar ScheduleConfigError = class extends Error {\n\tconstructor(message) {\n\t\tsuper(`Schedule: ${message}`);\n\t\tthis.name = \"ScheduleConfigError\";\n\t}\n};\nconst CRON_FIELD = /^[\\d*?A-Za-z]+(?:[-/][\\dA-Za-z]+)*(?:,[\\d*?A-Za-z]+(?:[-/][\\dA-Za-z]+)*)*$/;\nfunction isRecord(value) {\n\treturn value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\nfunction parseTimezone(value) {\n\tif (value === void 0 || value === null || value === \"\") return \"UTC\";\n\tif (typeof value !== \"string\") throw new ScheduleConfigError(\"\\\"timezone\\\" must be an IANA name\");\n\ttry {\n\t\tnew Intl.DateTimeFormat(\"en-US\", { timeZone: value });\n\t} catch {\n\t\tthrow new ScheduleConfigError(`unknown timezone \"${value}\" (use an IANA name such as Europe/Lisbon)`);\n\t}\n\treturn value;\n}\nfunction parseCronText(cron) {\n\tif (typeof cron !== \"string\" || cron.trim() === \"\") throw new ScheduleConfigError(\"\\\"cron\\\" is required in cron mode\");\n\tconst pattern = cron.trim().replace(/\\s+/g, \" \");\n\tconst fields = pattern.split(\" \");\n\tif (fields.length !== 5) throw new ScheduleConfigError(`cron \"${pattern}\" must have exactly five fields (minute hour day month weekday)`);\n\tconst bad = fields.find((field) => !CRON_FIELD.test(field));\n\tif (bad !== void 0) throw new ScheduleConfigError(`cron \"${pattern}\" has an invalid field \"${bad}\"`);\n\treturn pattern;\n}\nfunction parseInterval(record) {\n\tconst { every, unit } = record;\n\tif (typeof every !== \"number\" || !Number.isInteger(every) || every < 1) throw new ScheduleConfigError(\"\\\"every\\\" must be a whole number of at least 1 in interval mode\");\n\tif (typeof unit !== \"string\" || !Object.hasOwn(SCHEDULE_UNIT_MS, unit)) throw new ScheduleConfigError(`\"unit\" must be one of ${Object.keys(SCHEDULE_UNIT_MS).join(\", \")}`);\n\tconst key = unit;\n\treturn {\n\t\tevery,\n\t\tunit: key,\n\t\teveryMs: every * SCHEDULE_UNIT_MS[key]\n\t};\n}\nfunction parseScheduleConfig(config) {\n\tif (!isRecord(config)) throw new ScheduleConfigError(\"the config must be an object\");\n\tconst timezone = parseTimezone(config.timezone);\n\tif (config.mode === \"cron\") return {\n\t\tmode: \"cron\",\n\t\tcron: parseCronText(config.cron),\n\t\ttimezone\n\t};\n\tif (config.mode === \"interval\") return {\n\t\tmode: \"interval\",\n\t\t...parseInterval(config),\n\t\ttimezone\n\t};\n\tthrow new ScheduleConfigError(config.mode === void 0 ? \"\\\"mode\\\" is required (\\\"cron\\\" or \\\"interval\\\")\" : `\"mode\" must be \"cron\" or \"interval\", not ${JSON.stringify(config.mode)}`);\n}\nfunction scheduleConfigIssue(config) {\n\ttry {\n\t\tparseScheduleConfig(config);\n\t\treturn;\n\t} catch (error) {\n\t\treturn error instanceof Error ? error.message : String(error);\n\t}\n}\n\n//#endregion\n//#region src/workflow/ports.ts\nconst NEXT_PORT = \"next\";\nconst ERROR_PORT = \"error\";\nconst PIECE_ACTION_PORTS = [NEXT_PORT, ERROR_PORT];\nconst TRIGGER_PORTS = [NEXT_PORT];\nfunction flowPorts(ports) {\n\treturn ports.filter((port) => port !== ERROR_PORT);\n}\nfunction undeclaredPortEdges(edges, portsOf) {\n\treturn edges.filter((edge) => {\n\t\tconst ports = portsOf(edge.from);\n\t\treturn ports !== void 0 && !ports.includes(edge.port);\n\t});\n}\n\n//#endregion\n//#region src/workflow/core.ts\nconst CORE_PIECE_NAME = \"@powerhousedao/piece-core\";\nconst BRANCH_PORTS = [\n\t\"true\",\n\t\"false\",\n\tERROR_PORT\n];\nfunction knownPorts(block) {\n\tif (block.kind === \"trigger\") return TRIGGER_PORTS;\n\treturn block.pieceName === \"@powerhousedao/piece-core\" && block.name === \"branch\" ? BRANCH_PORTS : PIECE_ACTION_PORTS;\n}\n\n//#endregion\n//#region src/workflow/document-reference.ts\nconst DOCUMENT_REF_KEY = \"$documentRef\";\nconst DOCUMENT_KEYS = /* @__PURE__ */ new Set([\n\t\"header\",\n\t\"state\",\n\t\"initialState\",\n\t\"operations\",\n\t\"clipboard\"\n]);\nconst MAX_DEPTH = 64;\nfunction isPlainObject(value) {\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) return false;\n\tconst proto = Object.getPrototypeOf(value);\n\treturn proto === Object.prototype || proto === null;\n}\nfunction isRevision(value) {\n\treturn isPlainObject(value) && Object.values(value).every((entry) => typeof entry === \"number\" && Number.isFinite(entry));\n}\nfunction documentReference(header) {\n\treturn {\n\t\tdocumentId: header.id,\n\t\tdocumentType: header.documentType,\n\t\tbranch: header.branch,\n\t\trevision: { ...header.revision }\n\t};\n}\nfunction isDocumentReference(value) {\n\treturn isPlainObject(value) && typeof value.documentId === \"string\" && typeof value.documentType === \"string\" && typeof value.branch === \"string\" && isRevision(value.revision);\n}\nfunction isDocumentHeader(value) {\n\treturn isPlainObject(value) && typeof value.id === \"string\" && value.id !== \"\" && typeof value.documentType === \"string\" && value.documentType !== \"\" && typeof value.branch === \"string\" && isRevision(value.revision) && typeof value.createdAtUtcIso === \"string\" && typeof value.lastModifiedAtUtcIso === \"string\";\n}\nfunction isReactorDocument(value) {\n\treturn isPlainObject(value) && isDocumentHeader(value.header) && isPlainObject(value.state);\n}\nfunction isDocumentRefMarker(value) {\n\treturn isPlainObject(value) && isDocumentReference(value[\"$documentRef\"]);\n}\nfunction walk(value, visit, depth, seen) {\n\tif (depth > MAX_DEPTH || typeof value !== \"object\" || value === null) return value;\n\tif (seen.has(value)) return value;\n\tif (Array.isArray(value)) {\n\t\tseen.add(value);\n\t\tconst mapped = value.map((item) => walk(item, visit, depth + 1, seen));\n\t\tseen.delete(value);\n\t\treturn mapped;\n\t}\n\tif (!isPlainObject(value)) return value;\n\tseen.add(value);\n\tconst replaced = visit(value);\n\tconst result = Object.fromEntries(Object.entries(replaced ?? value).map(([key, entry]) => [key, replaced && !(key in value) ? entry : walk(entry, visit, depth + 1, seen)]));\n\tseen.delete(value);\n\treturn result;\n}\nfunction referenceDocuments(value) {\n\treturn walk(value, (node) => {\n\t\tif (!isReactorDocument(node)) return void 0;\n\t\tconst rest = Object.entries(node).filter(([key]) => !DOCUMENT_KEYS.has(key));\n\t\treturn {\n\t\t\t[DOCUMENT_REF_KEY]: documentReference(node.header),\n\t\t\t...Object.fromEntries(rest)\n\t\t};\n\t}, 0, /* @__PURE__ */ new WeakSet());\n}\nfunction documentRefsIn(value) {\n\tconst found = [];\n\twalk(value, (node) => {\n\t\tif (isDocumentRefMarker(node)) found.push(node[DOCUMENT_REF_KEY]);\n\t}, 0, /* @__PURE__ */ new WeakSet());\n\treturn found;\n}\nfunction containsDocumentRef(value) {\n\treturn documentRefsIn(value).length > 0;\n}\nfunction expandDocumentRefs(value, expand) {\n\treturn walk(value, (node) => {\n\t\tif (!isDocumentRefMarker(node)) return void 0;\n\t\tconst { [DOCUMENT_REF_KEY]: reference, ...rest } = node;\n\t\treturn {\n\t\t\t...rest,\n\t\t\t...expand(reference)\n\t\t};\n\t}, 0, /* @__PURE__ */ new WeakSet());\n}\n\n//#endregion\nexport { APP_WEBHOOK_UNSUPPORTED, BRANCH_PORTS, CORE_PIECE_NAME, DEFAULT_TIMEZONE, DOCUMENT_REF_KEY, ERROR_PORT, NEXT_PORT, PIECE_ACTION_PORTS, SCHEDULE_MODES, SCHEDULE_UNIT_MS, ScheduleConfigError, TRIGGER_PORTS, TriggerStrategyError, checkTriggerStrategy, containsDocumentRef, documentReference, documentRefsIn, expandDocumentRefs, flowPorts, isDocumentRefMarker, isDocumentReference, isReactorDocument, knownPorts, parseCronText, parseScheduleConfig, referenceDocuments, scheduleConfigIssue, triggerDelivery, undeclaredPortEdges };\n//# sourceMappingURL=workflow.js.map","import { checkTriggerStrategy } from \"@powerhousedao/pieces-framework/workflow\";\nimport { Cron } from \"croner\";\n\n// Piece features this engine cannot run. Read off a loaded piece or off its\n// published listing alike, since both carry auth and triggers as data.\nconst ISSUES_URL = \"https://github.com/powerhouse-inc/powerhouse/issues/\";\n\nexport interface UnsupportedFeature {\n feature: string;\n issue: number;\n // \"<feature> is not supported yet (<issue url>)\", what a listing shows.\n reason: string;\n}\n\nfunction unsupported(feature: string, issue: number): UnsupportedFeature {\n return {\n feature,\n issue,\n reason: `${feature} is not supported yet (${ISSUES_URL}${issue})`,\n };\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\n// A piece's auth, from the bundle or the listing. With several methods the\n// piece runs if any one does; the connection picks which.\nexport function unsupportedAuth(auth: unknown): UnsupportedFeature | undefined {\n if (Array.isArray(auth)) {\n const reasons = auth.map(unsupportedMethod);\n return reasons.some((reason) => reason === undefined)\n ? undefined\n : reasons[0];\n }\n return unsupportedMethod(auth);\n}\n\n// The method a connection of `type` signs in with: the piece's only auth,\n// or the entry of that type among several (upstream's getAuthPropertyForValue).\nexport function authMethodFor(auth: unknown, type: unknown): unknown {\n if (!Array.isArray(auth)) return auth;\n return auth.find((entry) => isRecord(entry) && entry.type === type);\n}\n\nfunction unsupportedMethod(auth: unknown): UnsupportedFeature | undefined {\n if (!isRecord(auth)) return undefined;\n if (auth.type === \"OAUTH2\" && auth.grantType === \"client_credentials\") {\n return unsupported(\"OAuth2 client credentials\", 3091);\n }\n if (auth.type === \"OIDC\") return unsupported(\"OIDC auth\", 3091);\n if (auth.type === \"CUSTOM_AUTH\" && auth.refresh != null) {\n return unsupported(\"CustomAuth refresh\", 3091);\n }\n return undefined;\n}\n\n// A piece trigger; the core piece's triggers are fed by the host and never pass here.\nexport function unsupportedTrigger(trigger: {\n type?: unknown;\n renewConfiguration?: unknown;\n}): UnsupportedFeature | undefined {\n if (trigger.type === \"MANUAL\") {\n return unsupported(\"TriggerStrategy.MANUAL\", 3091);\n }\n const strategy = checkTriggerStrategy(trigger.type);\n if (\"issue\" in strategy) {\n const issue = trigger.type === \"APP_WEBHOOK\" ? 3081 : 3091;\n return {\n feature: `TriggerStrategy ${String(trigger.type)}`,\n issue,\n reason: `${strategy.issue} (${ISSUES_URL}${issue})`,\n };\n }\n const problem = renewProblem(trigger.renewConfiguration);\n if (problem) {\n return {\n feature: \"renewConfiguration\",\n issue: 3090,\n reason: `renewConfiguration ${problem} (${ISSUES_URL}3090)`,\n };\n }\n return undefined;\n}\n\n// A subscription the supervisor renews on a UTC cron by calling onRenew.\nexport interface TriggerRenew {\n strategy: \"CRON\";\n cronExpression: string;\n}\n\nfunction cronFires(cron: string): boolean {\n try {\n return (\n new Cron(cron, { timezone: \"UTC\", legacyMode: false }).nextRun() !== null\n );\n } catch {\n return false;\n }\n}\n\n// createTrigger fills in { strategy: \"NONE\" } for every trigger.\nfunction renewProblem(renew: unknown): string | undefined {\n if (renew === undefined || renew === null) return undefined;\n if (!isRecord(renew)) return \"is not an object\";\n if (renew.strategy === \"NONE\") return undefined;\n if (renew.strategy !== \"CRON\") {\n return `strategy ${String(renew.strategy)} is not supported`;\n }\n const cron = renew.cronExpression;\n if (typeof cron !== \"string\" || !cronFires(cron)) {\n return `cron ${JSON.stringify(cron)} is invalid`;\n }\n return undefined;\n}\n\n// The trigger's renewal, when it declares a valid CRON one.\nexport function triggerRenew(trigger: {\n renewConfiguration?: unknown;\n}): TriggerRenew | undefined {\n const renew = trigger.renewConfiguration;\n if (!isRecord(renew) || renew.strategy !== \"CRON\") return undefined;\n if (renewProblem(renew)) return undefined;\n return { strategy: \"CRON\", cronExpression: renew.cronExpression as string };\n}\n\nexport class UnsupportedPieceFeatureError extends Error {\n readonly feature: string;\n readonly issue: number;\n\n constructor(subject: string, unsupportedFeature: UnsupportedFeature) {\n super(`${subject}: ${unsupportedFeature.reason}`);\n this.name = \"UnsupportedPieceFeatureError\";\n this.feature = unsupportedFeature.feature;\n this.issue = unsupportedFeature.issue;\n }\n}\n","import type { RequireReactor } from \"@powerhousedao/pieces-framework\";\nimport {\n PIECE_ACTION_PORTS,\n TRIGGER_PORTS,\n} from \"@powerhousedao/pieces-framework/workflow\";\nimport {\n getActions,\n getTriggers,\n type ApPiece,\n type ApProperty,\n type ApPropertyType,\n type ApDropdownOption,\n type ApPropertyGroup,\n type ApTrigger,\n type ApTriggerStrategy,\n} from \"./types.js\";\nimport {\n triggerRenew,\n unsupportedAuth,\n unsupportedTrigger,\n type TriggerRenew,\n type UnsupportedFeature,\n} from \"./unsupported.js\";\n\nexport interface PiecePropDescriptor {\n name: string;\n displayName: string;\n description?: string;\n placeholder?: string;\n type: ApPropertyType;\n required: boolean;\n defaultValue?: unknown;\n // STATIC_DROPDOWN choices, extracted so the editor needs no runtime call.\n staticOptions?: ApDropdownOption[];\n // True when the prop carries a design-time resolver (DROPDOWN options() / DYNAMIC props()).\n hasDynamicResolver: boolean;\n // Synthesised domain-provider id: activepieces:<pkg>#<action>.<prop> (doc 08 §6.3).\n // Only top-level props get one; nested resolvers are not addressable yet.\n dynamicResolverId?: string;\n // Sibling prop names whose values feed the resolver; the editor re-runs\n // it when any of them changes.\n refreshers?: string[];\n // Nested shape: an ARRAY item's fields, or the props a DYNAMIC resolver\n // produced (see describeProperties). OBJECT props are free-form and carry none.\n properties?: PiecePropDescriptor[];\n // Activepieces' layout hint: rendered in the collapsed advanced section.\n advanced?: boolean;\n // Layout and control hints (see describeHints); absent when not declared.\n width?: \"half\" | \"full\";\n icon?: string;\n reveals?: string[];\n variant?: string;\n display?: string;\n min?: number;\n max?: number;\n step?: number;\n refreshOnSearch?: boolean;\n formatProperty?: string;\n // A STATIC_DROPDOWN's own state, beside its options.\n staticDisabled?: boolean;\n staticPlaceholder?: string;\n // Shown while a sibling holds one of `oneOf`.\n showWhen?: { prop: string; oneOf: unknown[] };\n // A checkbox with this label that stores \"\" on purpose.\n emptyChoice?: string;\n}\n\nexport interface PiecePropertyGroupDescriptor {\n key: string;\n display: string;\n label?: string;\n description?: string;\n icon?: string;\n props: string[];\n}\n\nexport interface PieceErrorHandlingDescriptor {\n retryOnFailure?: { defaultValue?: boolean; hide?: boolean };\n continueOnFailure?: { defaultValue?: boolean; hide?: boolean };\n}\n\nexport interface PieceActionDescriptor {\n name: string;\n displayName: string;\n description?: string;\n // UI metadata only — not a credential contract (spike finding).\n requireAuth: boolean;\n // The reactor access the step asks for; absent when it asks for none.\n requireReactor?: RequireReactor;\n props: PiecePropDescriptor[];\n // Output ports the step can leave on; the editor draws only these.\n ports: readonly string[];\n // Carried verbatim: it is what the expression picker builds a later step's\n // field list from, and a package piece has no published listing to read.\n outputSchema?: unknown;\n // Orders the action picker, so a package piece that declares it must be\n // ordered by it too rather than counting as unset.\n audience?: string;\n propertyGroups?: PiecePropertyGroupDescriptor[];\n classification?: string;\n errorHandlingOptions?: PieceErrorHandlingDescriptor;\n}\n\nexport interface PieceTriggerDescriptor {\n name: string;\n displayName: string;\n description?: string;\n strategy: ApTriggerStrategy;\n testStrategy?: string;\n // A form the editor draws instead of the props, e.g. \"schedule\".\n display?: string;\n requireAuth: boolean;\n requireReactor?: RequireReactor;\n props: PiecePropDescriptor[];\n ports: readonly string[];\n propertyGroups?: PiecePropertyGroupDescriptor[];\n outputSchema?: unknown;\n hasSampleData: boolean;\n // The sample itself, not just whether there is one: a trigger that declares\n // no outputSchema is read for its shape instead.\n sampleData?: unknown;\n // How the sender proves the endpoint exists before it will register it.\n // Absent when the trigger declares no handshake, or declares NONE.\n handshake?: { strategy: string; paramName?: string };\n // When the provider's subscription must be renewed; absent for NONE.\n renew?: TriggerRenew;\n // A trigger feature the engine cannot run; the piece's own is on the piece.\n unsupported?: UnsupportedFeature;\n}\n\nexport interface PieceAuthDescriptor {\n type: ApPropertyType;\n displayName?: string;\n description?: string;\n required?: boolean;\n // CUSTOM_AUTH's own fields. Without them a connection form has nothing to\n // ask for, which is what a piece read from a package rather than a published\n // listing would otherwise leave the editor with.\n props?: PiecePropDescriptor[];\n // OAUTH2 only: where and how the provider signs a user in.\n oauth2?: OAuth2MethodDescriptor;\n // Set when this engine can't sign in this way (OIDC, for one).\n unsupported?: UnsupportedFeature;\n}\n\nexport interface OAuth2MethodDescriptor {\n // May hold `{prop}` placeholders, filled from the connection's props.\n authUrl: string;\n tokenUrl: string;\n scope: string[];\n prompt?: \"none\" | \"consent\" | \"login\" | \"omit\";\n pkce?: boolean;\n pkceMethod?: \"plain\" | \"S256\";\n authorizationMethod?: \"HEADER\" | \"BODY\";\n grantType?: string;\n // Extra authorize-URL parameters, e.g. access_type=offline.\n extra?: Record<string, string>;\n}\n\nfunction describeOAuth2(\n raw: Record<string, unknown>,\n): OAuth2MethodDescriptor | undefined {\n if (typeof raw.authUrl !== \"string\" || typeof raw.tokenUrl !== \"string\") {\n return undefined;\n }\n const strings = (value: unknown) =>\n Array.isArray(value)\n ? value.filter((entry): entry is string => typeof entry === \"string\")\n : [];\n const extra =\n raw.extra && typeof raw.extra === \"object\"\n ? Object.fromEntries(\n Object.entries(raw.extra).filter(\n (entry): entry is [string, string] => typeof entry[1] === \"string\",\n ),\n )\n : undefined;\n return {\n authUrl: raw.authUrl,\n tokenUrl: raw.tokenUrl,\n scope: strings(raw.scope),\n ...(typeof raw.prompt === \"string\"\n ? { prompt: raw.prompt as OAuth2MethodDescriptor[\"prompt\"] }\n : {}),\n ...(typeof raw.pkce === \"boolean\" ? { pkce: raw.pkce } : {}),\n ...(raw.pkceMethod === \"plain\" || raw.pkceMethod === \"S256\"\n ? { pkceMethod: raw.pkceMethod }\n : {}),\n ...(raw.authorizationMethod === \"HEADER\" ||\n raw.authorizationMethod === \"BODY\"\n ? { authorizationMethod: raw.authorizationMethod }\n : {}),\n ...(typeof raw.grantType === \"string\" ? { grantType: raw.grantType } : {}),\n ...(extra && Object.keys(extra).length > 0 ? { extra } : {}),\n };\n}\n\n// NONE is how the framework spells \"no handshake\", so it is not carried:\n// a caller checking the field would otherwise have to know that too.\nfunction describeHandshake(\n trigger: ApTrigger,\n): { strategy: string; paramName?: string } | undefined {\n const strategy = trigger.handshakeConfiguration?.strategy;\n if (!strategy || strategy === \"NONE\") return undefined;\n return { strategy, paramName: trigger.handshakeConfiguration?.paramName };\n}\n\nexport interface PieceSource {\n packageName: string;\n version: string;\n}\n\n// Serializable descriptor of an adapted piece; the engine never learns\n// Activepieces exists (doc 08 §6.2).\nexport interface PieceDescriptor {\n id: string;\n source: PieceSource;\n displayName: string;\n description?: string;\n logoUrl?: string;\n categories?: string[];\n deprecated?: boolean;\n // A list when the piece offers several sign-in methods.\n auth?: PieceAuthDescriptor | PieceAuthDescriptor[];\n minimumSupportedRelease?: string;\n maximumSupportedRelease?: string;\n actions: PieceActionDescriptor[];\n triggers: PieceTriggerDescriptor[];\n // Set when no block of the piece can run here, e.g. an OAuth2 piece.\n unsupported?: UnsupportedFeature;\n}\n\nfunction optional<K extends string, V>(\n key: K,\n value: V | undefined,\n): Partial<Record<K, V>> {\n return value === undefined ? {} : ({ [key]: value } as Record<K, V>);\n}\n\nexport function describeOption(option: ApDropdownOption): ApDropdownOption {\n return {\n label: option.label,\n value: option.value,\n ...(typeof option.description === \"string\" && option.description\n ? { description: option.description }\n : {}),\n ...(typeof option.icon === \"string\" && option.icon\n ? { icon: option.icon }\n : {}),\n };\n}\n\n// Copied only when well-formed: a foreign bundle may carry anything here.\nfunction describeHints(prop: ApProperty): Partial<PiecePropDescriptor> {\n const hints: Partial<PiecePropDescriptor> = {};\n if (prop.width === \"half\" || prop.width === \"full\") hints.width = prop.width;\n const strings = [\"icon\", \"variant\", \"display\", \"formatProperty\"] as const;\n for (const key of strings) {\n const value = prop[key];\n if (typeof value === \"string\" && value !== \"\") hints[key] = value;\n }\n const numbers = [\"min\", \"max\", \"step\"] as const;\n for (const key of numbers) {\n const value = prop[key];\n if (typeof value === \"number\" && Number.isFinite(value)) hints[key] = value;\n }\n if (Array.isArray(prop.reveals)) {\n const reveals = prop.reveals.filter(\n (name): name is string => typeof name === \"string\",\n );\n if (reveals.length > 0) hints.reveals = reveals;\n }\n if (prop.refreshOnSearch === true) hints.refreshOnSearch = true;\n const showWhen = prop.showWhen as { prop?: unknown; oneOf?: unknown } | null;\n if (typeof showWhen?.prop === \"string\" && Array.isArray(showWhen.oneOf)) {\n const oneOf: unknown[] = showWhen.oneOf;\n hints.showWhen = { prop: showWhen.prop, oneOf: [...oneOf] };\n }\n if (typeof prop.emptyChoice === \"string\" && prop.emptyChoice !== \"\") {\n hints.emptyChoice = prop.emptyChoice;\n }\n return hints;\n}\n\nfunction describeGroups(\n groups: ApPropertyGroup[] | undefined,\n): PiecePropertyGroupDescriptor[] | undefined {\n if (!Array.isArray(groups)) return undefined;\n const described = groups\n .filter(\n (group) =>\n typeof group.key === \"string\" &&\n typeof group.display === \"string\" &&\n Array.isArray(group.props),\n )\n .map((group) => ({\n key: group.key!,\n display: group.display!,\n ...(group.label ? { label: group.label } : {}),\n ...(group.description ? { description: group.description } : {}),\n ...(group.icon ? { icon: group.icon } : {}),\n props: group.props!.filter(\n (name): name is string => typeof name === \"string\",\n ),\n }));\n return described.length > 0 ? described : undefined;\n}\n\nfunction hasResolver(prop: ApProperty): boolean {\n return typeof prop.options === \"function\" || typeof prop.props === \"function\";\n}\n\nfunction toPropDescriptor(\n name: string,\n prop: ApProperty,\n resolverId?: string,\n): PiecePropDescriptor {\n const dynamic = hasResolver(prop);\n const descriptor: PiecePropDescriptor = {\n name,\n displayName: prop.displayName ?? name,\n type: prop.type ?? \"UNKNOWN\",\n required: prop.required ?? false,\n hasDynamicResolver: dynamic,\n };\n if (typeof prop.description === \"string\" && prop.description !== \"\") {\n descriptor.description = prop.description;\n }\n if (typeof prop.placeholder === \"string\" && prop.placeholder !== \"\") {\n descriptor.placeholder = prop.placeholder;\n }\n if (prop.defaultValue !== undefined) {\n descriptor.defaultValue = prop.defaultValue;\n }\n if (prop.advanced === true) descriptor.advanced = true;\n if (dynamic && resolverId) {\n descriptor.dynamicResolverId = resolverId;\n }\n if (dynamic && Array.isArray(prop.refreshers)) {\n descriptor.refreshers = prop.refreshers.filter(\n (entry): entry is string => typeof entry === \"string\",\n );\n }\n if (typeof prop.options === \"object\" && Array.isArray(prop.options.options)) {\n descriptor.staticOptions = prop.options.options.map(describeOption);\n if (prop.options.disabled === true) descriptor.staticDisabled = true;\n if (typeof prop.options.placeholder === \"string\") {\n descriptor.staticPlaceholder = prop.options.placeholder;\n }\n }\n Object.assign(descriptor, describeHints(prop));\n if (prop.properties && typeof prop.properties === \"object\") {\n const nested = describeProperties(prop.properties);\n if (nested.length > 0) descriptor.properties = nested;\n }\n return descriptor;\n}\n\n// Descriptor list for a props map: nested ARRAY items and what a DYNAMIC\n// resolver returns, so the editor never sees raw piece properties.\nexport function describeProperties(\n props: Record<string, ApProperty> | null | undefined,\n resolverIdFor?: (propName: string) => string,\n): PiecePropDescriptor[] {\n if (!props || typeof props !== \"object\") return [];\n return Object.entries(props)\n .filter((entry): entry is [string, ApProperty] =>\n isPropertyObject(entry[1]),\n )\n .map(([propName, prop]) =>\n toPropDescriptor(propName, prop, resolverIdFor?.(propName)),\n );\n}\n\n// Bundles are duck-typed; a props map may carry non-object junk.\nfunction isPropertyObject(value: unknown): value is ApProperty {\n return value !== null && typeof value === \"object\";\n}\n\nfunction withUnsupported(feature: UnsupportedFeature | undefined): {\n unsupported?: UnsupportedFeature;\n} {\n return feature ? { unsupported: feature } : {};\n}\n\n// Pure translation over a loaded piece; performs no I/O and never executes\n// piece code beyond the actions()/triggers() accessors.\nfunction describeAuthMethod(auth: unknown): PieceAuthDescriptor | undefined {\n if (!auth || typeof auth !== \"object\") return undefined;\n const method = auth as ApProperty;\n // CUSTOM_AUTH carries a record here; a DYNAMIC prop would carry a\n // resolver function, which is not an auth shape at all.\n const props =\n method.props && typeof method.props === \"object\"\n ? describeProperties(method.props)\n : [];\n const oauth2 =\n method.type === \"OAUTH2\"\n ? describeOAuth2(auth as Record<string, unknown>)\n : undefined;\n return {\n type: method.type ?? \"UNKNOWN\",\n displayName: method.displayName,\n description: method.description,\n required: method.required,\n ...(props.length > 0 ? { props } : {}),\n ...(oauth2 ? { oauth2 } : {}),\n ...withUnsupported(unsupportedAuth(method)),\n };\n}\n\nfunction declaredPorts(ports: unknown): readonly string[] | undefined {\n if (!Array.isArray(ports) || ports.length === 0) return undefined;\n return ports.every((port) => typeof port === \"string\")\n ? (ports as string[])\n : undefined;\n}\n\n// Only a well-formed declaration is carried: a foreign bundle may hold anything.\nfunction declaredReactor(value: unknown): RequireReactor | undefined {\n return value === \"read\" || value === \"write\" ? value : undefined;\n}\n\nexport interface BuildDescriptorOptions {\n // Read each action's own `ports`: only a piece whose results the host routes.\n routed?: boolean;\n // The host feeds the triggers itself, so no trigger strategy is refused.\n hostFed?: boolean;\n}\n\nexport function buildDescriptor(\n piece: ApPiece,\n source: PieceSource,\n options: BuildDescriptorOptions = {},\n): PieceDescriptor {\n const actions = Object.entries(getActions(piece)).map(\n ([actionName, action]): PieceActionDescriptor => ({\n name: action.name ?? actionName,\n displayName: action.displayName ?? actionName,\n description: action.description,\n requireAuth: action.requireAuth ?? false,\n ...optional(\"requireReactor\", declaredReactor(action.requireReactor)),\n ports:\n (options.routed ? declaredPorts(action.ports) : undefined) ??\n PIECE_ACTION_PORTS,\n props: describeProperties(\n action.props,\n (propName) =>\n `activepieces:${source.packageName}#${actionName}.${propName}`,\n ),\n ...(action.outputSchema !== undefined\n ? { outputSchema: action.outputSchema }\n : {}),\n ...(action.audience !== undefined ? { audience: action.audience } : {}),\n ...optional(\"propertyGroups\", describeGroups(action.propertyGroups)),\n ...optional(\n \"classification\",\n typeof action.classification === \"string\"\n ? action.classification\n : undefined,\n ),\n ...optional(\"errorHandlingOptions\", action.errorHandlingOptions),\n }),\n );\n\n const triggers = Object.entries(getTriggers(piece)).map(\n ([triggerName, trigger]): PieceTriggerDescriptor => ({\n name: trigger.name ?? triggerName,\n displayName: trigger.displayName ?? triggerName,\n description: trigger.description,\n strategy: trigger.type ?? \"UNKNOWN\",\n testStrategy: trigger.testStrategy,\n ...(typeof trigger.display === \"string\" && trigger.display !== \"\"\n ? { display: trigger.display }\n : {}),\n requireAuth: trigger.requireAuth ?? false,\n ...optional(\"requireReactor\", declaredReactor(trigger.requireReactor)),\n ports: TRIGGER_PORTS,\n props: describeProperties(\n trigger.props,\n (propName) =>\n `activepieces:${source.packageName}#${triggerName}.${propName}`,\n ),\n ...(trigger.outputSchema !== undefined\n ? { outputSchema: trigger.outputSchema }\n : {}),\n hasSampleData:\n trigger.sampleData !== undefined && trigger.sampleData !== null,\n ...(trigger.sampleData !== undefined && trigger.sampleData !== null\n ? { sampleData: trigger.sampleData }\n : {}),\n handshake: describeHandshake(trigger),\n ...optional(\"renew\", triggerRenew(trigger)),\n ...optional(\"propertyGroups\", describeGroups(trigger.propertyGroups)),\n ...(options.hostFed ? {} : withUnsupported(unsupportedTrigger(trigger))),\n }),\n );\n\n const descriptor: PieceDescriptor = {\n id: `activepieces:${source.packageName}`,\n source,\n displayName: piece.displayName,\n description: piece.description,\n logoUrl: piece.logoUrl,\n categories: piece.categories,\n ...(piece.deprecated === true ? { deprecated: true } : {}),\n minimumSupportedRelease: piece.minimumSupportedRelease,\n maximumSupportedRelease: piece.maximumSupportedRelease,\n actions,\n triggers,\n ...withUnsupported(unsupportedAuth(piece.auth)),\n };\n // Several methods stay a list, in the piece's order; each says whether this\n // engine can run it.\n if (Array.isArray(piece.auth)) {\n const methods = piece.auth\n .map(describeAuthMethod)\n .filter((method) => method !== undefined);\n if (methods.length > 0) descriptor.auth = methods;\n } else {\n const method = describeAuthMethod(piece.auth);\n if (method) descriptor.auth = method;\n }\n return descriptor;\n}\n","import { readFileSync, realpathSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport type { ApPiece } from \"./types.js\";\n\nexport interface LoadedPiece {\n piece: ApPiece;\n entryPath: string;\n // Which duck-type check identified the export.\n check: \"constructor-name\" | \"structural\";\n}\n\n// Resolves a bundle's entry file. Published bundles typically carry only\n// `main` (no `exports`, no `type` — they are CJS).\nexport function resolveEntry(pieceDir: string): string {\n const raw = readFileSync(path.join(pieceDir, \"package.json\"), \"utf8\");\n const pkg = JSON.parse(raw) as {\n main?: string;\n module?: string;\n exports?: Record<string, unknown>;\n };\n const dotExport = pkg.exports?.[\".\"];\n const candidates: (string | undefined)[] = [];\n if (typeof dotExport === \"string\") candidates.push(dotExport);\n if (dotExport && typeof dotExport === \"object\") {\n const cond = dotExport as Record<string, unknown>;\n for (const key of [\"import\", \"require\", \"default\"]) {\n const value = cond[key];\n if (typeof value === \"string\") candidates.push(value);\n }\n }\n candidates.push(pkg.main, pkg.module, \"src/index.js\", \"index.js\", \"main.js\");\n // A bundle's manifest (or a symlink inside it) must not point the entry\n // outside pieceDir; realpath so a symlink can't launder the escape.\n const root = realpathSync(pieceDir);\n const rootWithSep = root + path.sep;\n for (const candidate of candidates) {\n if (!candidate) continue;\n const abs = path.resolve(pieceDir, candidate);\n let real: string;\n try {\n real = realpathSync(abs);\n } catch {\n continue; // candidate doesn't exist; try the next one\n }\n if (real !== root && !real.startsWith(rootWithSep)) continue;\n return abs;\n }\n throw new Error(`No entry file found for piece bundle at ${pieceDir}`);\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null;\n}\n\n// Identify the piece by constructor name (their own loader's check), falling\n// back to structure for bundles minified without keepNames. No `instanceof`.\nfunction findPiece(\n mod: Record<string, unknown>,\n): Pick<LoadedPiece, \"piece\" | \"check\"> | undefined {\n const candidates: unknown[] = [\n ...Object.values(mod),\n ...(isRecord(mod.default) ? Object.values(mod.default) : []),\n mod.default,\n ];\n for (const candidate of candidates) {\n // `constructor?.name`: a bundle may export an Object.create(null), and the\n // real piece is usually beside it in the same module.\n if (isRecord(candidate) && candidate.constructor?.name === \"Piece\") {\n return {\n piece: candidate as unknown as ApPiece,\n check: \"constructor-name\",\n };\n }\n }\n for (const candidate of candidates) {\n if (\n isRecord(candidate) &&\n typeof candidate.displayName === \"string\" &&\n (isRecord(candidate.actions) ||\n typeof candidate.actions === \"function\" ||\n typeof candidate.getAction === \"function\")\n ) {\n return { piece: candidate as unknown as ApPiece, check: \"structural\" };\n }\n }\n return undefined;\n}\n\n// A module the piece names and node cannot find. Dependencies are installed\n// with scripts disabled, so a native or downloaded one looks like this.\nfunction missingModule(entryPath: string, error: unknown): Error | undefined {\n const code = (error as { code?: unknown } | null)?.code;\n if (code !== \"ERR_MODULE_NOT_FOUND\" && code !== \"MODULE_NOT_FOUND\") {\n return undefined;\n }\n const detail = error instanceof Error ? error.message : String(error);\n return new Error(\n `Piece at ${entryPath} could not be loaded: it imports a module that is ` +\n `not there. Its dependencies are installed with lifecycle scripts ` +\n `disabled, so one that compiles or downloads on install -- a native ` +\n `addon, a browser download -- cannot be prepared here. ${detail}`,\n );\n}\n\n// ESM-first `import()` — Node's CJS interop handles the typical CJS bundle —\n// with a `require` fallback.\nexport async function loadPiece(entryPath: string): Promise<LoadedPiece> {\n let mod: Record<string, unknown>;\n try {\n mod = (await import(\n /* @vite-ignore */ pathToFileURL(entryPath).href\n )) as Record<string, unknown>;\n } catch (imported) {\n try {\n const require = createRequire(import.meta.url);\n mod = require(entryPath) as Record<string, unknown>;\n } catch (required) {\n // The import's error names the missing module; require's often names\n // only the entry it was handed.\n throw (\n missingModule(entryPath, imported) ??\n missingModule(entryPath, required) ??\n required\n );\n }\n }\n const found = findPiece(mod);\n if (!found) {\n throw new Error(\n `No Piece export found in ${entryPath}. Export keys: ${Object.keys(mod).join(\", \")}`,\n );\n }\n return { ...found, entryPath };\n}\n\nexport async function loadPieceFromDir(pieceDir: string): Promise<LoadedPiece> {\n return loadPiece(resolveEntry(pieceDir));\n}\n","// Network egress policy, enforced inside the worker child. Pieces bundle their\n// own HTTP clients, so hooking one of them — or `fetch` — is bypassable.\n\n// Every TCP connection in Node ends at `net.Socket.prototype.connect`, whatever\n// the client, so that is the choke point installed here.\n\n// This hardens SSRF inside a cooperative process; it is not a boundary against\n// hostile code — see installEgressGuard.\nimport dgram from \"node:dgram\";\nimport dns from \"node:dns\";\nimport net, { isIP } from \"node:net\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { ssrfIpClassifier } from \"@powerhousedao/pieces-framework/host\";\nimport type { EgressPolicy } from \"./protocol.js\";\n\nexport const EGRESS_DENIED_CODE = \"EGRESS_DENIED\";\n\n// What a host applies when it expresses no preference: every public host is\n// reachable, private space and the metadata endpoint are not.\nexport const DEFAULT_EGRESS_POLICY: EgressPolicy = {};\n\n// Raised at connect time and delivered to the piece the way Node delivers a\n// failed DNS lookup — an error on the socket — so any client surfaces it.\nexport class EgressDeniedError extends Error {\n readonly code = EGRESS_DENIED_CODE;\n readonly host: string;\n readonly port: number | undefined;\n readonly address: string | undefined;\n\n constructor(\n reason: string,\n where: { host: string; port?: number; address?: string },\n ) {\n super(`Egress denied: ${reason}`);\n this.name = \"EgressDeniedError\";\n this.host = where.host;\n this.port = where.port;\n this.address = where.address;\n }\n}\n\n// The SSRF surface (loopback, RFC1918, link-local incl. the metadata endpoint,\n// multicast, and the IPv6 equivalents) is the framework's classifier table.\n\n// ipaddr.js reads a deprecated IPv4-compatible address (::a.b.c.d) as unicast,\n// so ::169.254.169.254 would walk past it; the whole block is refused here.\nconst IPV4_COMPATIBLE = new net.BlockList();\nIPV4_COMPATIBLE.addSubnet(\"::\", 96, \"ipv6\");\n\nfunction familyOf(address: string): \"ipv4\" | \"ipv6\" {\n return isIP(address) === 6 ? \"ipv6\" : \"ipv4\";\n}\n\n// The address without its zone, or undefined when it is not one at all.\nexport function parseAddress(value: string): string | undefined {\n const bare = value.split(\"%\")[0];\n return isIP(bare) === 0 ? undefined : bare;\n}\n\n// Compiled eagerly so a malformed entry fails the request rather than\n// degrading it to no enforcement.\nfunction addAllowedAddress(list: net.BlockList, spec: string): void {\n const slash = spec.indexOf(\"/\");\n const mask = slash === -1 ? \"\" : spec.slice(slash + 1);\n const address = parseAddress(slash === -1 ? spec : spec.slice(0, slash));\n if (!address) {\n throw new Error(`Egress policy entry \"${spec}\" is not an IP address`);\n }\n const family = familyOf(address);\n const width = family === \"ipv6\" ? 128 : 32;\n const prefix = mask === \"\" ? width : Number(mask);\n if (!Number.isInteger(prefix) || prefix < 1 || prefix > width) {\n throw new Error(`Egress policy entry \"${spec}\" has an invalid prefix`);\n }\n list.addSubnet(address, prefix, family);\n}\n\ntype NativeLookup = (\n hostname: string,\n options: dns.LookupOneOptions,\n callback: (error: Error | null, address: unknown, family?: number) => void,\n) => void;\n\n// getaddrinfo, taken before anything is patched: the guard resolves through\n// this so its own lookups never meet the refusal it installs below.\nconst nativeLookup = originalOf<NativeLookup>(dns, \"lookup\");\n\n// c-ares, which owns its sockets and never passes through dgram or connect.\n\n// A query is a channel out on its own — the data rides in the name — so the\n// answer is irrelevant and the whole surface is refused under a policy.\nconst RESOLVER_METHODS = [\n \"resolve\",\n \"resolve4\",\n \"resolve6\",\n \"resolveAny\",\n \"resolveCaa\",\n \"resolveCname\",\n \"resolveMx\",\n \"resolveNaptr\",\n \"resolveNs\",\n \"resolvePtr\",\n \"resolveSoa\",\n \"resolveSrv\",\n \"resolveTxt\",\n \"reverse\",\n];\n\nexport function isPrivateAddress(value: string): boolean {\n const address = parseAddress(value);\n // An address we cannot classify counts as private: fail closed.\n if (!address) return true;\n if (IPV4_COMPATIBLE.check(address, familyOf(address))) return true;\n return ssrfIpClassifier.isBlockedIp({ ip: address, allowList: [] });\n}\n\ninterface CompiledPolicy {\n hosts: string[] | undefined;\n addresses: net.BlockList | undefined;\n ports: number[] | undefined;\n allowPrivate: boolean;\n}\n\nfunction compile(policy: EgressPolicy): CompiledPolicy {\n const hosts = policy.allowHosts?.map((host) => host.trim().toLowerCase());\n const ports = policy.allowPorts?.map((port) => {\n if (!Number.isInteger(port) || port < 0 || port > 65535) {\n throw new Error(`Egress policy port ${String(port)} is out of range`);\n }\n return port;\n });\n const specs = policy.allowAddresses ?? [];\n const addresses = new net.BlockList();\n for (const spec of specs) addAllowedAddress(addresses, spec);\n return {\n hosts: hosts && hosts.length > 0 ? hosts : undefined,\n addresses: specs.length > 0 ? addresses : undefined,\n ports: ports && ports.length > 0 ? ports : undefined,\n allowPrivate: policy.allowPrivateAddresses === true,\n };\n}\n\nfunction hostAllowed(policy: CompiledPolicy, host: string): boolean {\n if (!policy.hosts) return true;\n const name = host.toLowerCase();\n return policy.hosts.some((entry) =>\n entry.startsWith(\"*.\")\n ? name.length > entry.length - 1 && name.endsWith(entry.slice(1))\n : entry === name,\n );\n}\n\nfunction addressAllowed(policy: CompiledPolicy, address: string): boolean {\n const ip = parseAddress(address);\n if (!ip) return false;\n if (policy.addresses?.check(ip, familyOf(ip))) return true;\n return policy.allowPrivate || !isPrivateAddress(ip);\n}\n\n// The policy of the request in flight, and the one the work started under: both\n// apply, so a pooled client's callback chain cannot borrow a laxer context.\n\n// A piece's leftover timer keeps the policy it was created with rather than\n// whatever the next request brings.\nlet inFlight: CompiledPolicy | undefined;\nconst started = new AsyncLocalStorage<CompiledPolicy | undefined>();\n\nfunction policiesInForce(): CompiledPolicy[] {\n const inherited = started.getStore();\n const policies: CompiledPolicy[] = [];\n if (inFlight) policies.push(inFlight);\n if (inherited && inherited !== inFlight) policies.push(inherited);\n return policies;\n}\n\n// Runs one request under its policy. Compiling first means a malformed policy\n// fails the request rather than degrading it to no enforcement.\nexport async function runWithEgressPolicy<T>(\n policy: EgressPolicy | undefined,\n work: () => Promise<T>,\n): Promise<T> {\n const compiled = policy ? compile(policy) : undefined;\n installEgressGuard();\n inFlight = compiled;\n try {\n return await started.run(compiled, work);\n } finally {\n // The request is over; what it left running keeps the policy it inherited,\n // so it can never become less restricted than it started.\n if (inFlight === compiled) inFlight = undefined;\n }\n}\n\ninterface ConnectOptions {\n path?: string;\n port?: number | string;\n host?: string;\n lookup?: unknown;\n [key: string]: unknown;\n}\n\n// Node's own connect-argument shapes: (options) | (port[, host]) | (path), plus\n// the pre-normalized [options, callback] array net.createConnection hands over.\nfunction normalizeConnectArgs(args: unknown[]): {\n options: ConnectOptions;\n callback: unknown;\n} {\n if (Array.isArray(args[0])) {\n const [options, callback] = args[0] as [ConnectOptions, unknown];\n return { options: { ...options }, callback };\n }\n const first = args[0];\n let options: ConnectOptions = {};\n if (typeof first === \"object\" && first !== null) {\n options = { ...(first as ConnectOptions) };\n } else if (typeof first === \"string\" && Number.isNaN(Number(first))) {\n options.path = first;\n } else {\n options.port = first as number;\n if (typeof args[1] === \"string\") options.host = args[1];\n }\n const last = args[args.length - 1];\n return { options, callback: typeof last === \"function\" ? last : undefined };\n}\n\ntype LookupResult = { address: string; family: number }[];\n\ntype LookupCallback = (\n error: Error | null,\n address?: string | LookupResult,\n family?: number,\n) => void;\n\n// Classifies the address the socket is about to use, not the name the piece\n// asked for: a name check alone loses to DNS rebinding.\nfunction guardedLookup(\n policies: CompiledPolicy[],\n host: string,\n port: number | undefined,\n): (hostname: string, options: unknown, callback: LookupCallback) => void {\n return (hostname, options, callback) => {\n const asked = options as { all?: boolean };\n nativeLookup(\n hostname,\n options as dns.LookupOneOptions,\n (error: Error | null, result: unknown, family?: number) => {\n if (error) {\n callback(error);\n return;\n }\n try {\n const entries: LookupResult = asked.all\n ? (result as LookupResult)\n : [{ address: result as string, family: family ?? 0 }];\n const permitted = entries.filter((entry) =>\n policies.every((policy) => addressAllowed(policy, entry.address)),\n );\n if (permitted.length === 0) {\n const seen = entries.map((entry) => entry.address).join(\", \");\n callback(\n new EgressDeniedError(\n `host \"${host}\" resolves to ${seen || \"nothing\"}, which the policy does not permit`,\n { host, port, address: entries[0]?.address },\n ),\n );\n return;\n }\n if (asked.all) callback(null, permitted);\n else callback(null, permitted[0].address, permitted[0].family);\n } catch (failure) {\n // A defect in the guard denies the connection, never opens it.\n callback(\n failure instanceof Error ? failure : new Error(String(failure)),\n );\n }\n },\n );\n };\n}\n\nfunction denyReason(\n policies: CompiledPolicy[],\n options: ConnectOptions,\n): EgressDeniedError | undefined {\n if (typeof options.path === \"string\") {\n return new EgressDeniedError(\n `connections to local socket \"${options.path}\" are not permitted`,\n { host: options.path },\n );\n }\n const host = typeof options.host === \"string\" ? options.host : \"\";\n const port = options.port === undefined ? undefined : Number(options.port);\n for (const policy of policies) {\n if (policy.ports && (port === undefined || !policy.ports.includes(port))) {\n return new EgressDeniedError(\n `port ${String(port)} on host \"${host}\" is not permitted`,\n { host, port },\n );\n }\n if (!hostAllowed(policy, host)) {\n return new EgressDeniedError(`host \"${host}\" is not on the allowlist`, {\n host,\n port,\n });\n }\n if (isIP(host) && !addressAllowed(policy, host)) {\n return new EgressDeniedError(`address ${host} is not permitted`, {\n host,\n port,\n address: host,\n });\n }\n }\n return undefined;\n}\n\n// Reports a denial the way Node reports an asynchronous socket failure, so a\n// piece catches it from its client rather than from a synchronous throw.\nfunction failLater(\n emitter: { emit: (event: string, error: Error) => boolean },\n error: EgressDeniedError,\n callback: unknown,\n): void {\n process.nextTick(() => {\n if (typeof callback === \"function\") (callback as (e: Error) => void)(error);\n else emitter.emit(\"error\", error);\n });\n}\n\n// Takes a method off its descriptor rather than as a method reference: what is\n// wanted is the original implementation, re-applied with an explicit `this`.\nfunction originalOf<T>(target: object, name: string): T {\n return Object.getOwnPropertyDescriptor(target, name)?.value as T;\n}\n\nfunction resolverDenial(method: string, args: unknown[]): EgressDeniedError {\n const host = typeof args[0] === \"string\" ? args[0] : \"\";\n return new EgressDeniedError(\n `DNS ${method}(\"${host}\") is not permitted; use a hostname in a request instead`,\n { host },\n );\n}\n\n// Refuses every c-ares entry point on one object, in the shape its callers\n// expect: a rejected promise here, a callback error there.\nfunction refuseResolvers(target: object, promised: boolean): void {\n for (const method of RESOLVER_METHODS) {\n const original = originalOf<(this: unknown, ...args: unknown[]) => unknown>(\n target,\n method,\n );\n if (typeof original !== \"function\") continue;\n function refused(this: unknown, ...args: unknown[]): unknown {\n if (policiesInForce().length === 0) return original.apply(this, args);\n const denied = resolverDenial(method, args);\n if (promised) return Promise.reject(denied);\n const callback = args[args.length - 1];\n // No callback is a programming error Node would throw on anyway.\n if (typeof callback !== \"function\") throw denied;\n process.nextTick(() => (callback as (error: Error) => void)(denied));\n return undefined;\n }\n seal(target, method, refused);\n }\n}\n\n// Sealed so a piece holding the pristine implementation cannot put it back, and\n// so a later assignment cannot quietly unhook the guard.\nfunction seal(target: object, name: string, value: unknown): void {\n Object.defineProperty(target, name, {\n value,\n writable: false,\n configurable: false,\n enumerable: false,\n });\n}\n\nlet installed = false;\n\n// Installed when the worker child starts, before any piece code can run, and a\n// no-op while no policy is in force.\n\n// Not a boundary against hostile code: a child process or a worker thread gets\n// its own copy of these modules. Isolation is a network namespace, not this.\nexport function installEgressGuard(): void {\n if (installed) return;\n installed = true;\n\n const connect = originalOf<\n (this: net.Socket, ...args: unknown[]) => net.Socket\n >(net.Socket.prototype, \"connect\");\n\n function patchedConnect(this: net.Socket, ...args: unknown[]): net.Socket {\n const policies = policiesInForce();\n if (policies.length === 0) return connect.apply(this, args);\n const { options, callback } = normalizeConnectArgs(args);\n // Node defaults a missing host to localhost; write it back so the checks\n // and the guarded lookup below both see what will be dialled.\n if (typeof options.path !== \"string\" && !options.host) {\n options.host = \"localhost\";\n }\n const denied = denyReason(policies, options);\n if (denied) {\n process.nextTick(() => this.destroy(denied));\n return this;\n }\n if (typeof options.host === \"string\" && !isIP(options.host)) {\n options.lookup = guardedLookup(\n policies,\n options.host,\n options.port === undefined ? undefined : Number(options.port),\n );\n }\n return connect.call(this, options, callback);\n }\n seal(net.Socket.prototype, \"connect\", patchedConnect);\n\n // The dgram surface carries no destination a policy can usefully allow — a\n // piece's work is HTTP — so it is refused whole, as is c-ares further down.\n const send = originalOf<(this: dgram.Socket, ...args: unknown[]) => void>(\n dgram.Socket.prototype,\n \"send\",\n );\n function patchedSend(this: dgram.Socket, ...args: unknown[]): void {\n if (policiesInForce().length === 0) {\n send.apply(this, args);\n return;\n }\n const host = args.find(\n (arg, index) => index > 0 && typeof arg === \"string\",\n ) as string | undefined;\n const last = args[args.length - 1];\n failLater(\n this,\n new EgressDeniedError(\n `UDP to \"${host ?? \"the requested address\"}\" is not permitted`,\n { host: host ?? \"\" },\n ),\n typeof last === \"function\" ? last : undefined,\n );\n }\n seal(dgram.Socket.prototype, \"send\", patchedSend);\n\n // Inbound is refused for the same reason: a delivery reaches a workflow\n // through the host's webhook endpoint, never a port the piece opened.\n const bind = originalOf<\n (this: dgram.Socket, ...args: unknown[]) => dgram.Socket\n >(dgram.Socket.prototype, \"bind\");\n function patchedBind(this: dgram.Socket, ...args: unknown[]): dgram.Socket {\n if (policiesInForce().length === 0) return bind.apply(this, args);\n failLater(\n this,\n new EgressDeniedError(\"binding a UDP socket is not permitted\", {\n host: \"\",\n }),\n undefined,\n );\n return this;\n }\n seal(dgram.Socket.prototype, \"bind\", patchedBind);\n\n const listen = originalOf<\n (this: net.Server, ...args: unknown[]) => net.Server\n >(net.Server.prototype, \"listen\");\n function patchedListen(this: net.Server, ...args: unknown[]): net.Server {\n if (policiesInForce().length === 0) return listen.apply(this, args);\n failLater(\n this,\n new EgressDeniedError(\"listening for connections is not permitted\", {\n host: \"\",\n }),\n undefined,\n );\n return this;\n }\n seal(net.Server.prototype, \"listen\", patchedListen);\n\n // The four objects a piece can reach c-ares through; dns.lookup is\n // getaddrinfo and stays open, guarded per connect instead.\n refuseResolvers(dns, false);\n refuseResolvers(dns.Resolver.prototype, false);\n refuseResolvers(dns.promises, true);\n refuseResolvers(dns.promises.Resolver.prototype, true);\n}\n\n// True for a denial raised in the child, including one a piece's client\n// re-wrapped: axios copies `code`, undici keeps the original as `cause`.\nexport function isEgressDenied(error: unknown): boolean {\n const seen = new Set<unknown>();\n let candidate: unknown = error;\n // Wrappers nest, and some of them produce a cycle; the walk is bounded by\n // the seen set and by a depth no honest chain reaches.\n for (let depth = 0; depth < 16; depth++) {\n if (candidate instanceof EgressDeniedError) return true;\n if (typeof candidate !== \"object\" || candidate === null) return false;\n if (seen.has(candidate)) return false;\n seen.add(candidate);\n const fields = candidate as {\n name?: unknown;\n code?: unknown;\n message?: unknown;\n cause?: unknown;\n properties?: { code?: unknown };\n serialized?: { name?: unknown; properties?: { code?: unknown } };\n };\n const codes = [\n fields.code,\n fields.properties?.code,\n fields.serialized?.properties?.code,\n ];\n if (codes.includes(EGRESS_DENIED_CODE)) return true;\n if (fields.name === \"EgressDeniedError\") return true;\n if (fields.serialized?.name === \"EgressDeniedError\") return true;\n if (\n typeof fields.message === \"string\" &&\n fields.message.includes(\"Egress denied:\")\n ) {\n return true;\n }\n candidate = fields.cause;\n }\n return false;\n}\n","// Wall-clock marks a child takes while serving one request, sent back with its\n// response so the host can draw them as spans. The child carries no tracer.\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport type { WorkerPhaseTiming, WorkerTimings } from \"./protocol.js\";\n\nconst ANCHOR_MS = 1_000;\n// Date.now() rounds to the ms: a smaller drift is that, not a clock step, and\n// following it would step time backwards.\nconst STEP_MS = 5;\n\n// Epoch ms, sub-ms precise, comparable across processes. Re-anchored each second:\n// timeOrigin is fixed at start, so a clock step would skew host against child.\nexport function wallClock(): () => number {\n let anchoredAt = performance.now();\n let anchor = Date.now() - anchoredAt;\n return () => {\n const now = performance.now();\n if (now - anchoredAt >= ANCHOR_MS) {\n anchoredAt = now;\n const next = Date.now() - now;\n if (Math.abs(next - anchor) > STEP_MS) anchor = next;\n }\n return anchor + now;\n };\n}\n\nexport const epochNow = wallClock();\n\nlet readyAt: number | undefined;\nlet bootReported = false;\n\n// When the entry finished loading; reported once, with the first response.\nexport function markWorkerReady(): void {\n readyAt ??= epochNow();\n}\n\nexport interface RequestTimings {\n received: number;\n phases: WorkerPhaseTiming[];\n}\n\nconst current = new AsyncLocalStorage<RequestTimings>();\n// The phase `fn` runs inside, so a nested one (models in action) names its parent.\nconst currentPhase = new AsyncLocalStorage<string>();\n\nexport function startRequestTimings(): RequestTimings {\n return { received: epochNow(), phases: [] };\n}\n\nexport function withRequestTimings<T>(\n timings: RequestTimings,\n fn: () => Promise<T>,\n): Promise<T> {\n return current.run(timings, fn);\n}\n\n// Records `fn` as a phase of the request being served, if any.\nexport async function timed<T>(\n name: string,\n fn: () => Promise<T>,\n attributes?: Record<string, string | boolean>,\n): Promise<T> {\n const timings = current.getStore();\n if (!timings) return fn();\n const parent = currentPhase.getStore();\n const start = epochNow();\n try {\n return await currentPhase.run(name, fn);\n } finally {\n timings.phases.push({\n name,\n start,\n end: epochNow(),\n ...(parent ? { parent } : {}),\n ...(attributes ? { attributes } : {}),\n });\n }\n}\n\nexport function finishRequestTimings(timings: RequestTimings): WorkerTimings {\n const boot = !bootReported && readyAt !== undefined;\n bootReported = true;\n const { rss, heapUsed, heapTotal, external } = process.memoryUsage();\n return {\n received: timings.received,\n sent: epochNow(),\n phases: timings.phases,\n memory: { rss, heapUsed, heapTotal, external },\n ...(boot ? { ready: readyAt } : {}),\n };\n}\n","// Worker child: loads piece bundles and executes actions in an isolated\n// process, so piece side-effects (TLS env poisoning, crashes) never reach the host.\nimport {\n buildActionContext,\n InMemoryConnectionsProvider,\n InMemoryKeyValueStore,\n UnsupportedContextMemberError,\n} from \"../context/action.js\";\nimport { RemoteKeyValueStore } from \"../context/remote-store.js\";\nimport { RemoteOutput } from \"../context/remote-output.js\";\nimport { captureConsole } from \"./logs.js\";\nimport { setHostCallTimeout } from \"./host-call.js\";\nimport {\n openWorkerReactor,\n type WorkerReactorSession,\n} from \"./reactor-provider.js\";\nimport type { ReactorOption } from \"../context/reactor-option.js\";\nimport {\n DocumentModelUnavailableError,\n ReactorAccessDeniedError,\n ReactorActionsFailedError,\n ReactorJobFailedError,\n ReactorJobPendingError,\n ReactorRequestClosedError,\n} from \"@powerhousedao/pieces-framework\";\nimport { jsonSafe } from \"./json-safe.js\";\nimport { formatPieceError } from \"@powerhousedao/pieces-framework/host\";\nimport { redactError, redactMessage } from \"./redact.js\";\nimport { readFile, stat } from \"node:fs/promises\";\nimport { buildCheckConnectionContext } from \"../context/check.js\";\nimport { DataUriFilesService, StagedFilesService } from \"../context/files.js\";\nimport { setMaxFileBytes } from \"../context/limits.js\";\nimport {\n normalizePropsValue,\n preparePropsValue,\n PropsValidationError,\n type NormalizeOptions,\n type PropsValidationErrors,\n} from \"../context/normalize.js\";\nimport {\n buildPropertyContext,\n findProperty,\n resolveDynamicProperty,\n} from \"../context/props.js\";\nimport { buildTriggerContext, runTriggerHook } from \"../context/trigger.js\";\nimport { buildDescriptor, describeProperties } from \"../descriptor.js\";\nimport { loadPiece, loadPieceFromDir, type LoadedPiece } from \"../loader.js\";\nimport {\n getActions,\n getTriggers,\n type ApPiece,\n type ApProperty,\n type ApTrigger,\n} from \"../types.js\";\nimport {\n authMethodFor,\n unsupportedAuth,\n unsupportedTrigger,\n UnsupportedPieceFeatureError,\n} from \"../unsupported.js\";\nimport { installEgressGuard, runWithEgressPolicy } from \"./egress.js\";\nimport {\n finishRequestTimings,\n markWorkerReady,\n startRequestTimings,\n timed,\n withRequestTimings,\n} from \"./timings.js\";\nimport type {\n StagedInput,\n PieceModuleRef,\n CheckConnectionMessage,\n CheckConnectionOutcome,\n DescribePieceMessage,\n ResolveOptionsMessage,\n RunMessage,\n SerializedPieceError,\n TriggerHookMessage,\n WorkerRequestMessage,\n WorkerResponse,\n} from \"./protocol.js\";\n\nconst loadedPieces = new Map<string, Promise<LoadedPiece>>();\n// One store per scope, alive for the worker's lifetime (in-memory phase:\n// state survives runs but not worker replacement).\nconst stores = new Map<string, InMemoryKeyValueStore>();\n\nfunction storeForScope(scope: string): InMemoryKeyValueStore {\n let store = stores.get(scope);\n if (!store) {\n store = new InMemoryKeyValueStore();\n stores.set(scope, store);\n }\n return store;\n}\n\n// The module this request names, and the cache key for it. A package piece\n// arrives as one file; a fetched bundle as the directory holding it.\nfunction pieceRefKey(ref: PieceModuleRef): string {\n const key = ref.entryPath ?? ref.bundleDir;\n if (!key) {\n throw new Error(\"Request names no piece module (entryPath or bundleDir)\");\n }\n return key;\n}\n\nfunction loadCached(ref: PieceModuleRef): Promise<LoadedPiece> {\n const key = pieceRefKey(ref);\n let loading = loadedPieces.get(key);\n const cached = loading !== undefined;\n if (!loading) {\n loading = ref.entryPath ? loadPiece(key) : loadPieceFromDir(key);\n loadedPieces.set(key, loading);\n }\n const loaded = loading;\n return timed(\"piece.load\", () => loaded, { \"piece.cached\": cached });\n}\n\n// The secret values this request carried, if any. Redacting here rather than\n// on the host means the host process never holds them in an error object.\nfunction redactValuesOf(message: WorkerRequestMessage): string[] {\n const request = message.request as { redactValues?: string[] };\n return request.redactValues ?? [];\n}\n\n// Reactor errors cross the RPC as plain Errors told apart by `name`.\nconst REACTOR_ERROR_NAMES = new Set<string>([\n DocumentModelUnavailableError,\n ReactorAccessDeniedError,\n ReactorActionsFailedError,\n ReactorJobFailedError,\n ReactorJobPendingError,\n ReactorRequestClosedError,\n]);\n\nfunction errorName(error: unknown, fallback: string | undefined): string {\n if (typeof error !== \"object\" || error === null) return fallback || \"Error\";\n const named = (error as { name?: unknown }).name;\n if (typeof named === \"string\" && REACTOR_ERROR_NAMES.has(named)) return named;\n return error.constructor.name || fallback || \"Error\";\n}\n\nfunction serializeError(\n error: unknown,\n values: string[] = [],\n): SerializedPieceError {\n const properties: Record<string, unknown> = {};\n if (typeof error === \"object\" && error !== null) {\n for (const key of Object.keys(error)) {\n properties[key] = jsonSafe((error as Record<string, unknown>)[key]);\n }\n }\n // The framework's own formatter first: it lifts an HTTP status, the request\n // and response, and a message out of an HTML error page. Redaction stays last.\n const {\n __apErrorVersion,\n message,\n errorName: formattedName,\n ...http\n } = formatPieceError(error);\n return {\n name: errorName(error, formattedName),\n message: redactMessage(message, { values }),\n properties: redactError(\n { ...properties, ...(jsonSafe(http) as Record<string, unknown>) },\n { values },\n ) as Record<string, unknown>,\n unsupportedMember:\n error instanceof UnsupportedContextMemberError ? error.member : undefined,\n ...(error instanceof UnsupportedPieceFeatureError\n ? { unsupportedFeature: error.feature }\n : {}),\n ...(error instanceof PropsValidationError\n ? { invalidProps: jsonSafe(error.errors) as PropsValidationErrors }\n : {}),\n };\n}\n\n// Read-and-clear the piece-set TLS override so each run reports its own poisoning.\nfunction consumeTlsFlag(): boolean {\n const poisoned = process.env.NODE_TLS_REJECT_UNAUTHORIZED === \"0\";\n delete process.env.NODE_TLS_REJECT_UNAUTHORIZED;\n return poisoned;\n}\n\n// The session's client under its declaration, for a run-time context.\nfunction reactorOption(\n session: WorkerReactorSession | undefined,\n): ReactorOption {\n if (!session) return {};\n return session.requireReactor === \"write\"\n ? { requireReactor: \"write\", reactor: session.client }\n : { requireReactor: \"read\", reactor: session.client };\n}\n\nasync function handleResolveOptions(\n message: ResolveOptionsMessage,\n): Promise<WorkerResponse> {\n const { request } = message;\n const { piece } = await loadCached(request);\n const block =\n request.kind === \"trigger\"\n ? getTriggers(piece)[request.actionName]\n : getActions(piece)[request.actionName];\n const session = await openWorkerReactor(\n request.reactor,\n (block as { requireReactor?: unknown } | undefined)?.requireReactor,\n );\n try {\n return await resolveOptions(message, piece, session);\n } finally {\n session?.close();\n }\n}\n\nasync function resolveOptions(\n message: ResolveOptionsMessage,\n piece: ApPiece,\n session: WorkerReactorSession | undefined,\n): Promise<WorkerResponse> {\n const { request } = message;\n const { context, touched } = buildPropertyContext({\n searchValue: request.searchValue,\n projectId: request.projectId,\n // Design-time default: an empty flows listing instead of a throwing stub.\n flows: { list: () => Promise.resolve({ data: [] }) },\n ...(session ? { reactor: session.client } : {}),\n });\n const refresherValues = {\n ...(request.auth !== undefined ? { auth: request.auth } : {}),\n ...request.refresherValues,\n };\n const prop = findProperty(\n piece,\n request.actionName,\n request.propName,\n request.kind,\n );\n const output = await resolveDynamicProperty({\n piece,\n actionName: request.actionName,\n kind: request.kind,\n propName: request.propName,\n refresherValues,\n context,\n });\n // DYNAMIC props() yields raw piece properties (with resolver functions);\n // the editor only ever sees descriptors, so translate before crossing IPC.\n const isDynamic =\n typeof prop.props === \"function\" && typeof prop.options !== \"function\";\n return {\n id: message.id,\n type: \"result\",\n output: isDynamic\n ? describeProperties(output as Record<string, ApProperty> | undefined)\n : jsonSafe(output),\n touched: [...touched],\n tlsPoisoned: consumeTlsFlag(),\n };\n}\n\n// Reads a FILE prop's attachment ref from the copy the host staged on disk.\n// The fork shares the filesystem with its parent, so this is what keeps a\n// 50 MB scan out of the IPC channel in both directions.\nfunction stagedInputOptions(\n inputs: StagedInput[] | undefined,\n): Pick<NormalizeOptions, \"resolveRef\" | \"openRef\"> {\n // An empty list is not the same as no list: it means the host has a store\n // and tried, so a FILE prop that still comes up short is told which\n // reference failed rather than that the context has no resolver.\n if (!inputs) return {};\n const byRef = new Map(inputs.map((input) => [input.ref, input]));\n const staged = (ref: string): StagedInput => {\n const input = byRef.get(ref);\n if (!input) throw new Error(`No staged file for reference \"${ref}\"`);\n if (input.error !== undefined) {\n throw new Error(`Could not read \"${ref}\": ${input.error}`);\n }\n return input;\n };\n return {\n resolveRef: async (ref: string) => {\n const input = staged(ref);\n return {\n data: await readFile(input.path),\n filename: input.fileName,\n contentType: input.contentType,\n };\n },\n openRef: async (ref: string) => {\n const input = staged(ref);\n return {\n path: input.path,\n size: (await stat(input.path)).size,\n filename: input.fileName,\n contentType: input.contentType,\n };\n },\n };\n}\n\n// The same refusal describe records, for a step or hook that reaches the\n// worker anyway: a workflow saved before the check, or built over the API.\nfunction assertRunnable(\n piece: ApPiece,\n pieceName: string,\n auth: unknown,\n trigger?: { name: string; trigger: ApTrigger },\n): void {\n // With several methods, the one this connection signs in with decides.\n const type = (auth as { type?: unknown } | null | undefined)?.type;\n const method =\n Array.isArray(piece.auth) && type !== undefined\n ? authMethodFor(piece.auth, type)\n : piece.auth;\n if (Array.isArray(piece.auth) && type !== undefined && !method) {\n throw new Error(\n `Piece \"${pieceName}\" has no ${String(type)} sign-in method for this connection`,\n );\n }\n const pieceFeature = unsupportedAuth(method);\n if (pieceFeature) {\n throw new UnsupportedPieceFeatureError(\n `Piece \"${pieceName}\"`,\n pieceFeature,\n );\n }\n const triggerFeature = trigger && unsupportedTrigger(trigger.trigger);\n if (triggerFeature) {\n throw new UnsupportedPieceFeatureError(\n `Trigger \"${trigger.name}\" of \"${pieceName}\"`,\n triggerFeature,\n );\n }\n}\n\nasync function handleRun(message: RunMessage): Promise<WorkerResponse> {\n const { request } = message;\n const { piece } = await loadCached(request);\n const action = getActions(piece)[request.actionName] as\n | ReturnType<typeof getActions>[string]\n | undefined;\n if (!action) {\n throw new Error(\n `No action \"${request.actionName}\" in ${pieceRefKey(request)}`,\n );\n }\n assertRunnable(piece, piece.displayName, request.auth);\n const files = request.stagingDir\n ? new StagedFilesService(request.stagingDir)\n : new DataUriFilesService();\n // A durable store answers every get/put over the call channel, so a write\n // survives this worker; without one the value lives only in this heap.\n const durableStore = request.durableStore\n ? new RemoteKeyValueStore()\n : undefined;\n const liveOutput = request.liveOutput ? new RemoteOutput() : undefined;\n const session = await timed(\"reactor.open\", () =>\n openWorkerReactor(request.reactor, action.requireReactor),\n );\n try {\n return await runAction(message, action, {\n files,\n durableStore,\n liveOutput,\n reactor: reactorOption(session),\n });\n } finally {\n session?.close();\n }\n}\n\nasync function runAction(\n message: RunMessage,\n action: ReturnType<typeof getActions>[string],\n services: {\n files: StagedFilesService | DataUriFilesService;\n durableStore: RemoteKeyValueStore | undefined;\n liveOutput: RemoteOutput | undefined;\n reactor: ReactorOption;\n },\n): Promise<WorkerResponse> {\n const { request } = message;\n const { files, durableStore, liveOutput, reactor } = services;\n // Before the props are normalised, not after: a processor that cannot coerce\n // says so on console.error, and the worker's stdio goes nowhere.\n const restoreConsole = request.captureLogs ? captureConsole() : undefined;\n const { context, touched } = buildActionContext({\n propsValue: await preparePropsValue(\n `action \"${request.actionName}\"`,\n action.props,\n request.propsValue,\n stagedInputOptions(request.stagedInputs),\n ),\n auth: request.auth,\n store:\n durableStore ??\n (request.storeScope ? storeForScope(request.storeScope) : undefined),\n files,\n connections: request.connections\n ? new InMemoryConnectionsProvider(request.connections)\n : undefined,\n output: liveOutput,\n ...reactor,\n resumePayload: request.resumePayload,\n executionType: request.executionType,\n identity: request.identity,\n });\n let output: unknown;\n try {\n // createAction defaults test to run; a plain-object action may have none.\n const method =\n request.stepTest && typeof action.test === \"function\"\n ? action.test\n : action.run;\n output = await timed(\"action\", () => method.call(action, context));\n } finally {\n restoreConsole?.();\n liveOutput?.close();\n }\n return {\n id: message.id,\n type: \"result\",\n output: jsonSafe(output),\n ...(files instanceof StagedFilesService && files.staged().length > 0\n ? { files: files.staged() }\n : {}),\n touched: [...touched],\n tlsPoisoned: consumeTlsFlag(),\n };\n}\n\nasync function handleTriggerHook(\n message: TriggerHookMessage,\n): Promise<WorkerResponse> {\n const { request } = message;\n const { piece } = await loadCached(request);\n const trigger = getTriggers(piece)[request.triggerName] as\n | ReturnType<typeof getTriggers>[string]\n | undefined;\n if (!trigger) {\n throw new Error(\n `No trigger \"${request.triggerName}\" in bundle ${request.bundleDir}`,\n );\n }\n // Teardown still runs, so a registration made before the check is released.\n if (request.hook !== \"onDisable\") {\n assertRunnable(piece, piece.displayName, request.auth, {\n name: request.triggerName,\n trigger,\n });\n }\n // The durable store answers every get/put over the call channel, so a long\n // onEnable checkpoints: registration ids survive a crash mid-hook.\n const snapshot = request.durableStore\n ? undefined\n : new InMemoryKeyValueStore(request.storeState);\n const runsPiece = request.hook === \"run\" || request.hook === \"test\";\n // Teardown is never refused: a config that no longer validates must still\n // release what onEnable registered.\n const propsValue =\n request.hook === \"onDisable\"\n ? await normalizePropsValue(trigger.props, request.propsValue)\n : await preparePropsValue(\n `trigger \"${request.triggerName}\"`,\n trigger.props,\n request.propsValue,\n );\n const session = await openWorkerReactor(\n request.reactor,\n trigger.requireReactor,\n );\n const handle = buildTriggerContext({\n propsValue,\n auth: request.auth,\n store: snapshot ?? new RemoteKeyValueStore(),\n hostPartitionedStore: request.durableStore,\n // Test hooks write under a separate prefix, never the live cursor.\n storePrefix: request.hook === \"test\" ? \"test\" : \"\",\n identity: request.identity,\n isRepublish: request.isRepublish,\n payload: request.payload,\n webhookUrl: request.webhookUrl,\n server: request.server,\n files: runsPiece ? new DataUriFilesService() : undefined,\n ...reactorOption(session),\n });\n let output: unknown;\n try {\n output = await runTriggerHook(trigger, request.hook, handle);\n } finally {\n session?.close();\n }\n return {\n id: message.id,\n type: \"result\",\n output: jsonSafe(output),\n touched: [...handle.touched],\n tlsPoisoned: consumeTlsFlag(),\n // Only the snapshot path has state to hand back; a durable store already\n // committed everything the hook wrote.\n ...(snapshot\n ? { storeState: jsonSafe(snapshot.snapshot()) as Record<string, unknown> }\n : {}),\n schedules: handle.schedules,\n listeners: handle.listeners,\n };\n}\n\n// What auth.validate and auth.getConnectionIdentifier are handed upstream: the\n// property values themselves, not the connection envelope an action receives.\nfunction authForValidate(auth: unknown): unknown {\n if (auth === null || typeof auth !== \"object\") return auth;\n const value = auth as Record<string, unknown>;\n switch (value.type) {\n case \"CUSTOM_AUTH\":\n return value.props;\n case \"SECRET_TEXT\":\n return value.secret_text;\n case \"BASIC_AUTH\":\n return { username: value.username, password: value.password };\n default:\n return auth;\n }\n}\n\n// `{ valid: false, error }` (or a bare `false`) fails the check.\nfunction fromValidateResult(\n result: unknown,\n): Pick<CheckConnectionOutcome, \"valid\" | \"detail\"> {\n if (result === false) return { valid: false };\n if (result === null || typeof result !== \"object\") return { valid: true };\n const value = result as { valid?: unknown; error?: unknown };\n if (value.valid !== false) return { valid: true };\n return {\n valid: false,\n ...(typeof value.error === \"string\" && value.error\n ? { detail: value.error }\n : {}),\n };\n}\n\n// Best-effort: a label failure is reported beside a passing check.\nasync function connectionIdentifier(\n getConnectionIdentifier: (context: unknown) => unknown,\n context: unknown,\n): Promise<Pick<CheckConnectionOutcome, \"accountLabel\" | \"identifierError\">> {\n try {\n const label = await getConnectionIdentifier(context);\n return typeof label === \"string\" && label !== \"\"\n ? { accountLabel: label }\n : {};\n } catch (error) {\n return {\n identifierError: error instanceof Error ? error.message : String(error),\n };\n }\n}\n\nasync function handleCheckConnection(\n message: CheckConnectionMessage,\n): Promise<WorkerResponse> {\n const { request } = message;\n const { piece } = await loadCached(request);\n // With several methods, the hooks are the ones of the connection's method.\n const auth = authMethodFor(\n (piece as { auth?: unknown }).auth,\n (request.auth as { type?: unknown } | null | undefined)?.type,\n ) as\n | {\n validate?: (context: unknown) => unknown;\n getConnectionIdentifier?: (context: unknown) => unknown;\n }\n | undefined;\n const validate = auth?.validate;\n const getConnectionIdentifier = auth?.getConnectionIdentifier;\n const { context, touched } = buildCheckConnectionContext({\n auth: authForValidate(request.auth),\n });\n let outcome: CheckConnectionOutcome =\n typeof validate === \"function\"\n ? { declared: true, ...fromValidateResult(await validate(context)) }\n : { declared: false, valid: true };\n if (outcome.valid && typeof getConnectionIdentifier === \"function\") {\n outcome = {\n ...outcome,\n ...(await connectionIdentifier(getConnectionIdentifier, context)),\n };\n }\n return {\n id: message.id,\n type: \"result\",\n output: outcome,\n touched: [...touched],\n tlsPoisoned: consumeTlsFlag(),\n };\n}\n\nasync function handleDescribe(\n message: DescribePieceMessage,\n): Promise<WorkerResponse> {\n const { request } = message;\n const { piece } = await loadCached(request);\n const descriptor = buildDescriptor(piece, {\n packageName: request.packageName,\n version: request.version,\n });\n return {\n id: message.id,\n type: \"result\",\n // A prop's defaultValue is piece-authored; jsonSafe keeps a non-cloneable\n // one from failing the IPC send.\n output: jsonSafe(descriptor),\n touched: [],\n tlsPoisoned: consumeTlsFlag(),\n };\n}\n\nfunction isWorkerMessage(value: unknown): value is WorkerRequestMessage {\n if (typeof value !== \"object\" || value === null) return false;\n const type = (value as { type?: unknown }).type;\n return (\n type === \"run\" ||\n type === \"resolve-options\" ||\n type === \"trigger-hook\" ||\n type === \"check-connection\" ||\n type === \"describe\"\n );\n}\n\nfunction dispatch(message: WorkerRequestMessage): Promise<WorkerResponse> {\n switch (message.type) {\n case \"run\":\n return handleRun(message);\n case \"resolve-options\":\n return handleResolveOptions(message);\n case \"trigger-hook\":\n return handleTriggerHook(message);\n case \"check-connection\":\n return handleCheckConnection(message);\n case \"describe\":\n return handleDescribe(message);\n }\n}\n\n// Called once by the child's entry, before any piece module is loaded.\nexport function startPieceWorker(): void {\n // A piece cannot then keep a pristine copy of the socket layer.\n installEgressGuard();\n process.on(\"message\", onMessage);\n markWorkerReady();\n}\n\nfunction onMessage(message: unknown): void {\n if (!isWorkerMessage(message)) return;\n const timings = startRequestTimings();\n // Deferred so a synchronous throw — a malformed egress policy — becomes a\n // rejection the handler below reports, instead of killing the child.\n const handler = Promise.resolve().then(() => {\n setMaxFileBytes(message.request.maxFileBytes);\n setHostCallTimeout(\n message.request.hostCallTimeoutMs,\n message.request.deadline,\n );\n return withRequestTimings(timings, () =>\n runWithEgressPolicy(message.request.egress, () => dispatch(message)),\n );\n });\n handler\n .catch((error: unknown): WorkerResponse => ({\n id: message.id,\n type: \"error\",\n error: serializeError(error, redactValuesOf(message)),\n tlsPoisoned: consumeTlsFlag(),\n }))\n .then((response) =>\n process.send?.({ ...response, timings: finishRequestTimings(timings) }),\n )\n .catch(() => process.exit(1));\n}\n","// The reactor RPC on a piece child's IPC channel, bound to one request. It owns\n// only `reactor-rpc` envelopes carrying that request's id.\nimport {\n REACTOR_RPC,\n type ReactorRpcEnvelope,\n type ReactorRequestBinding,\n} from \"./protocol.js\";\nimport type { IPieceWorkerTransport } from \"./transport.js\";\n\n// Structurally `IRpcTransport` from `@powerhousedao/reactor/rpc`.\nexport interface ReactorRpcTransport {\n post(message: never): void;\n onMessage(listener: (message: never) => void): () => void;\n close(): void;\n}\n\n// Serves ctx.reactor for one request; `open` returns the stop run when it settles.\nexport interface ReactorTap {\n requireReactor: ReactorRequestBinding[\"requireReactor\"];\n open(\n transport: ReactorRpcTransport,\n request: { requestId: string; deadline: number },\n ): () => void;\n}\n\nexport function isReactorRpcEnvelope(\n value: unknown,\n requestId: string,\n): value is ReactorRpcEnvelope {\n if (typeof value !== \"object\" || value === null) return false;\n const envelope = value as Partial<ReactorRpcEnvelope>;\n return envelope.type === REACTOR_RPC && envelope.requestId === requestId;\n}\n\nfunction isRpcMessage(value: unknown): boolean {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as { k?: unknown }).k === \"string\"\n );\n}\n\n// The host's end. The child runs piece code: another request's id, or a\n// message without a kind, is dropped.\nexport function createIpcTransport(\n worker: IPieceWorkerTransport,\n requestId: string,\n): ReactorRpcTransport {\n let closed = false;\n const detachers = new Set<() => void>();\n return {\n post(message: unknown) {\n if (closed || !worker.connected) return;\n worker.send({ type: REACTOR_RPC, requestId, message });\n },\n onMessage(listener: (message: never) => void) {\n const handler = (value: unknown) => {\n if (closed || !isReactorRpcEnvelope(value, requestId)) return;\n if (!isRpcMessage(value.message)) return;\n listener(value.message as never);\n };\n worker.on(\"message\", handler);\n const detach = () => {\n worker.off(\"message\", handler);\n detachers.delete(detach);\n };\n detachers.add(detach);\n return detach;\n },\n close() {\n closed = true;\n for (const detach of [...detachers]) detach();\n },\n };\n}\n","// `ctx.reactor` in the piece child: a reactor RPC proxy per request, with a\n// local registry fed by the host's manifest and, on a miss, a host lookup.\nimport {\n DocumentModelUnavailableError,\n ReactorAccessDeniedError,\n ReactorRequestClosedError,\n type DriveReadMethods,\n type DriveWriteMethods,\n type ReactorClient,\n type ReactorReadClient,\n type RefusedDriveMethods,\n type RequireReactor,\n} from \"@powerhousedao/pieces-framework\";\nimport type {\n IDocumentModelRegistry,\n IReactorClient,\n ModelManifestEntry,\n} from \"@powerhousedao/reactor\";\nimport type {\n createReactorClientProxy,\n IRpcTransport,\n MessageRouter,\n RpcMessage,\n} from \"@powerhousedao/reactor/rpc\";\nimport type { DocumentModelModule, PHDocument } from \"document-model\";\nimport { flushCompileCache } from \"node:module\";\nimport { callHost } from \"../pieces/activepieces/worker/host-call.js\";\nimport {\n MODEL_ENTRIES,\n MODEL_MANIFEST,\n REACTOR_RPC,\n type ModelEntriesPayload,\n type ModelManifestMessage,\n type ReactorRequestBinding,\n} from \"../pieces/activepieces/worker/protocol.js\";\nimport {\n installReactorProvider,\n type WorkerReactorSession,\n} from \"../pieces/activepieces/worker/reactor-provider.js\";\nimport { isReactorRpcEnvelope } from \"../pieces/activepieces/worker/reactor-rpc.js\";\nimport { timed } from \"../pieces/activepieces/worker/timings.js\";\n\nfunction named(name: string, message: string, cause?: unknown): Error {\n const error = new Error(message, cause === undefined ? {} : { cause });\n error.name = name;\n return error;\n}\n\n// --- Model manifest ------------------------------------------------------\n\nconst manifest = new Map<string, ModelManifestEntry[]>();\n// Per document type; dropped when a new entry for the type arrives.\nconst loading = new Map<string, Promise<void>>();\n// Host lookups in flight, per type; `undefined` asks for every entry.\nconst lookups = new Map<string | undefined, Promise<void>>();\n\nfunction isManifestEntry(value: unknown): value is ModelManifestEntry {\n if (typeof value !== \"object\" || value === null) return false;\n const entry = value as Record<string, unknown>;\n return (\n typeof entry.documentType === \"string\" &&\n typeof entry.spec === \"object\" &&\n entry.spec !== null\n );\n}\n\nexport function addManifestEntries(entries: unknown[]): void {\n for (const entry of entries) {\n if (!isManifestEntry(entry)) continue;\n const known = manifest.get(entry.documentType) ?? [];\n if (known.some((other) => other.version === entry.version)) continue;\n manifest.set(entry.documentType, [...known, entry]);\n loading.delete(entry.documentType);\n }\n}\n\n// Misses are not cached: the host may load the type before the next lookup.\nfunction lookUpEntries(documentType?: string): Promise<void> {\n let pending = lookups.get(documentType);\n if (!pending) {\n const payload: ModelEntriesPayload =\n documentType === undefined ? {} : { documentType };\n pending = callHost<unknown>(MODEL_ENTRIES, payload)\n .then((entries) => {\n if (Array.isArray(entries)) addManifestEntries(entries);\n })\n .finally(() => lookups.delete(documentType));\n lookups.set(documentType, pending);\n }\n return pending;\n}\n\nfunction isManifestMessage(value: unknown): value is ModelManifestMessage {\n return (\n typeof value === \"object\" &&\n value !== null &&\n (value as { type?: unknown }).type === MODEL_MANIFEST &&\n Array.isArray((value as { entries?: unknown }).entries)\n );\n}\n\n// --- Reactor runtime, imported on first use ------------------------------\n\nexport interface Runtime {\n rpc: {\n MessageRouter: typeof MessageRouter;\n createReactorClientProxy: typeof createReactorClientProxy;\n };\n loadSpec: (spec: ModelManifestEntry[\"spec\"]) => Promise<DocumentModelModule>;\n registry: IDocumentModelRegistry;\n versionOf: (document: PHDocument) => number;\n}\n\nlet runtime: Promise<Runtime> | undefined;\n\nfunction reactorRuntime(): Promise<Runtime> {\n // Deep entries, not the package barrels, which load storage, zod and crypto.\n runtime ??= Promise.all([\n import(\"@powerhousedao/reactor/rpc\"),\n import(\"@powerhousedao/shared/document-model/version\"),\n ]).then(([rpc, model]) => {\n // Persisted now: the child is SIGKILLed, never exiting cleanly.\n flushCompileCache();\n return {\n rpc,\n loadSpec: rpc.loadDocumentModelSpec,\n registry: new rpc.DocumentModelRegistry(),\n // The version the reactor resolves a document's module by.\n versionOf: (document: PHDocument) =>\n model.normalizeDocumentModelVersion(\n (document.state as Partial<PHDocument[\"state\"]>).document?.version,\n ),\n };\n });\n return runtime;\n}\n\nfunction unavailable(documentType: string, cause?: unknown): Error {\n return named(\n DocumentModelUnavailableError,\n cause === undefined\n ? `No document model for \"${documentType}\" is available to this piece`\n : `The document model for \"${documentType}\" could not be loaded: ${cause instanceof Error ? cause.message : JSON.stringify(cause)}`,\n cause,\n );\n}\n\n// Asks the host when the type, or the version a document needs, is not local.\n// Timed only when it starts a lookup or an import, not on every call.\nfunction ensureType(\n rt: Runtime,\n documentType: string,\n version?: number,\n): Promise<void> {\n const load = () => loadType(rt, documentType, version);\n return missingLocally(documentType, version) || !loading.has(documentType)\n ? timed(\"models\", load, { \"document.type\": documentType })\n : load();\n}\n\nfunction missingLocally(documentType: string, version?: number): boolean {\n const local = manifest.get(documentType) ?? [];\n return (\n local.length === 0 ||\n (version !== undefined &&\n !local.some((entry) => entry.version === String(version)))\n );\n}\n\nasync function loadType(\n rt: Runtime,\n documentType: string,\n version?: number,\n): Promise<void> {\n if (missingLocally(documentType, version)) {\n try {\n await lookUpEntries(documentType);\n } catch (error) {\n throw unavailable(documentType, error);\n }\n }\n const entries = manifest.get(documentType);\n if (!entries || entries.length === 0) throw unavailable(documentType);\n let pending = loading.get(documentType);\n if (!pending) {\n pending = Promise.all(entries.map((entry) => rt.loadSpec(entry.spec))).then(\n (modules) => {\n // Duplicates of versions already registered are skipped.\n rt.registry.registerModules(...modules);\n },\n );\n loading.set(documentType, pending);\n pending.catch(() => {\n if (loading.get(documentType) === pending) loading.delete(documentType);\n });\n }\n try {\n await pending;\n } catch (error) {\n throw unavailable(documentType, error);\n }\n}\n\nfunction moduleOf(\n documentType: string,\n lookup: () => Promise<DocumentModelModule>,\n): Promise<DocumentModelModule> {\n return lookup().catch((error: unknown) => {\n if (error instanceof Error && error.name === \"ModuleNotFoundError\") {\n throw unavailable(documentType);\n }\n throw error;\n });\n}\n\n// --- One request ---------------------------------------------------------\n\nfunction processTransport(requestId: string): IRpcTransport {\n let closed = false;\n const detachers = new Set<() => void>();\n return {\n post(message: RpcMessage) {\n if (closed) throw requestClosed();\n process.send?.({ type: REACTOR_RPC, requestId, message });\n },\n onMessage(listener) {\n const handler = (value: unknown) => {\n if (closed || !isReactorRpcEnvelope(value, requestId)) return;\n listener(value.message as RpcMessage);\n };\n process.on(\"message\", handler);\n const detach = () => {\n process.off(\"message\", handler);\n detachers.delete(detach);\n };\n detachers.add(detach);\n return detach;\n },\n close() {\n closed = true;\n for (const detach of [...detachers]) detach();\n },\n };\n}\n\nfunction requestClosed(): Error {\n return named(\n ReactorRequestClosedError,\n \"This ctx.reactor belongs to a step that has finished; use the ctx.reactor of the running step\",\n );\n}\n\ntype AnyMethod = (...args: unknown[]) => unknown;\n\n// Calls fail with ReactorRequestClosedError once the request settles, pages too.\nexport class RequestGuard {\n private closed = false;\n private rejectClosed: (error: Error) => void = () => undefined;\n private readonly whenClosed = new Promise<never>((_, reject) => {\n this.rejectClosed = reject;\n });\n\n constructor() {\n this.whenClosed.catch(() => undefined);\n }\n\n call<T>(run: () => Promise<T> | T): Promise<T> {\n if (this.closed) return Promise.reject(requestClosed());\n let result: Promise<T>;\n try {\n result = Promise.resolve(run());\n } catch (error) {\n return Promise.reject(error as Error);\n }\n return Promise.race([\n result.then((value) => this.paged(value)),\n this.whenClosed,\n ]);\n }\n\n close(): void {\n this.closed = true;\n this.rejectClosed(requestClosed());\n }\n\n private paged<T>(value: T): T {\n if (typeof value !== \"object\" || value === null) return value;\n const next = (value as { next?: unknown }).next;\n if (typeof next !== \"function\") return value;\n return {\n ...value,\n next: () => this.call(() => (next as AnyMethod).call(value)),\n };\n }\n}\n\nconst SERVED_DRIVES: Record<DriveReadMethods | DriveWriteMethods, true> = {\n getNode: true,\n listNodes: true,\n addFile: true,\n addFolder: true,\n};\n\nconst REFUSED_DRIVES: Record<RefusedDriveMethods, true> = {\n create: true,\n removeNode: true,\n renameNode: true,\n moveNode: true,\n copyNode: true,\n setPreferredEditorOnNode: true,\n};\n\n// As the host's served facade: the served methods go over RPC as `drives.*`,\n// the refused ones throw here with the error the host would answer.\nfunction sessionDrives(\n proxy: IReactorClient,\n guard: RequestGuard,\n): ReactorClient[\"drives\"] {\n const remote = proxy.drives as unknown as Record<string, AnyMethod>;\n const drives = Object.create(null) as Record<string, AnyMethod>;\n for (const name of Object.keys(SERVED_DRIVES)) {\n drives[name] = (...args) => guard.call(() => remote[name](...args));\n }\n for (const name of Object.keys(REFUSED_DRIVES)) {\n drives[name] = () => {\n throw named(\n ReactorAccessDeniedError,\n `drives.${name} is not available to workflow pieces`,\n );\n };\n }\n return drives as unknown as ReactorClient[\"drives\"];\n}\n\nexport function sessionClient(\n rt: Runtime,\n proxy: IReactorClient,\n guard: RequestGuard,\n): ReactorClient {\n const local: Record<string, AnyMethod> = {\n getDocumentModelModule: (documentType) =>\n guard.call(async () => {\n const type = String(documentType);\n await ensureType(rt, type);\n return moduleOf(type, () => proxy.getDocumentModelModule(type));\n }),\n getDocumentModelModuleForDocument: (document) =>\n guard.call(async () => {\n const type = (document as PHDocument).header.documentType;\n await ensureType(rt, type, rt.versionOf(document as PHDocument));\n return moduleOf(type, () =>\n proxy.getDocumentModelModuleForDocument(document as PHDocument),\n );\n }),\n getDocumentModelModules: (namespace, paging) =>\n guard.call(async () => {\n await lookUpEntries();\n // A type that fails to load is left out of the listing, not fatal.\n for (const documentType of manifest.keys()) {\n await ensureType(rt, documentType).catch((error: unknown) => {\n console.warn(error instanceof Error ? error.message : error);\n });\n }\n return proxy.getDocumentModelModules(\n namespace as string | undefined,\n paging as never,\n );\n }),\n subscribe: () => {\n throw named(\n ReactorAccessDeniedError,\n 'Reactor method \"subscribe\" is not offered to pieces',\n );\n },\n };\n const drives = sessionDrives(proxy, guard);\n // Every listed method resolves through `get`.\n return new Proxy({} as ReactorClient, {\n get: (_target, prop) => {\n if (typeof prop !== \"string\" || prop === \"then\") return undefined;\n if (prop === \"drives\") return drives;\n if (prop in local) return local[prop];\n return (...args: unknown[]) =>\n guard.call(() =>\n (proxy as unknown as Record<string, AnyMethod>)[prop](...args),\n );\n },\n });\n}\n\nasync function openSession(\n binding: ReactorRequestBinding,\n requireReactor: RequireReactor,\n): Promise<WorkerReactorSession> {\n const rt = await reactorRuntime();\n const transport = processTransport(binding.requestId);\n const router = new rt.rpc.MessageRouter(\"w\");\n router.attach(transport);\n const proxy = rt.rpc.createReactorClientProxy(router, {\n registry: rt.registry,\n });\n const guard = new RequestGuard();\n const client = sessionClient(rt, proxy, guard);\n const close = () => {\n guard.close();\n router.detach();\n transport.close();\n };\n // The host refuses a write a read declaration makes; the type says so first.\n return requireReactor === \"write\"\n ? { requireReactor, client, close }\n : { requireReactor, client: client as ReactorReadClient, close };\n}\n\nlet installed = false;\n\n// Before the first request: the boot manifest is sent as the child forks.\nexport function installWorkerReactor(): void {\n if (installed) return;\n installed = true;\n process.on(\"message\", (message: unknown) => {\n if (isManifestMessage(message)) addManifestEntries(message.entries);\n });\n installReactorProvider(openSession);\n}\n","// The piece child's entry: the piece worker, plus ctx.reactor over the reactor\n// RPC. Both listeners go on in this one synchronous evaluation.\nimport { flushCompileCache } from \"node:module\";\nimport { startPieceWorker } from \"../pieces/activepieces/worker/entry.js\";\nimport { installWorkerReactor } from \"./reactor.js\";\n\nstartPieceWorker();\ninstallWorkerReactor();\n// The host SIGKILLs a child, which skips the exit that writes NODE_COMPILE_CACHE.\nflushCompileCache();\n\n// --cpu-prof writes on exit, which SIGTERM's default action skips.\nif (process.execArgv.includes(\"--cpu-prof\")) {\n process.once(\"SIGTERM\", () => process.exit(0));\n}\n"],"x_google_ignoreList":[2,3,4,5,6,7,8,9,10,11,12,16,27,28,29,30],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,IAAa,gCAAb,cAAmD,MAAM;CACvD;CAEA,YAAY,QAAgB;EAC1B,MACE,4CAA4C,OAAO,wEAErD;EACA,KAAK,OAAO;EACZ,KAAK,SAAS;CAChB;AACF;AAIA,SAAgB,aAAa,YAA6B;CACxD,OAAO,IAAI,MAAM,SAAS,OAAO,CAAC,GAAG;EACnC,IAAI,SAAS,MAAM;GAEjB,IAAI,OAAO,SAAS,YAAY,SAAS,QAAQ,OAAO,KAAA;GACxD,MAAM,IAAI,8BAA8B,GAAG,WAAW,GAAG,MAAM;EACjE;EACA,QAAQ;GACN,MAAM,IAAI,8BAA8B,UAAU;EACpD;CACF,CAAC;AACH;AAIA,SAAgB,kBACd,MACA,SACA,SACG;CACH,OAAO,IAAI,MAAM,MAAM,EACrB,IAAI,QAAQ,MAAM,UAAU;EAC1B,IAAI,OAAO,SAAS,YAAY,SAAS,QAAQ;GAC/C,MAAM,SAAS,QAAQ,SAAS,OAAO,gBAAgB;GACvD,QAAQ,IAAI,MAAM;GAClB,UAAU,MAAM;EAClB;EACA,OAAO,QAAQ,IAAI,QAAQ,MAAM,QAAQ;CAC3C,EACF,CAAC;AACH;;;AC3CA,SAAgB,SAAS,OAAyB;CAChD,IAAI;EACF,OAAO,KAAK,MAAM,KAAK,UAAU,KAAK,CAAC;CACzC,QAAQ;EACN,OAAO,OAAO,KAAK;CACrB;AACF;;;ACQA,SAAgB,cAAc,SAAS;CACnC,MAAM,gBAAgB,OAAO,OAA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e,YACb,SACA,gBAC+B;CAC/B,MAAM,KAAK,MAAM,eAAe;CAChC,MAAM,YAAY,iBAAiB,QAAQ,SAAS;CACpD,MAAM,SAAS,IAAI,GAAG,IAAI,cAAc,GAAG;CAC3C,OAAO,OAAO,SAAS;CACvB,MAAM,QAAQ,GAAG,IAAI,yBAAyB,QAAQ,EACpD,UAAU,GAAG,SACf,CAAC;CACD,MAAM,QAAQ,IAAI,aAAa;CAC/B,MAAM,SAAS,cAAc,IAAI,OAAO,KAAK;CAC7C,MAAM,cAAc;EAClB,MAAM,MAAM;EACZ,OAAO,OAAO;EACd,UAAU,MAAM;CAClB;CAEA,OAAO,mBAAmB,UACtB;EAAE;EAAgB;EAAQ;CAAM,IAChC;EAAE;EAAwB;EAA6B;CAAM;AACnE;AAEA,IAAI,YAAY;AAGhB,SAAgB,uBAA6B;CAC3C,IAAI,WAAW;CACf,YAAY;CACZ,QAAQ,GAAG,YAAY,YAAqB;EAC1C,IAAI,kBAAkB,OAAO,GAAG,mBAAmB,QAAQ,OAAO;CACpE,CAAC;CACD,uBAAuB,WAAW;AACpC;;;AClaA,iBAAiB;AACjB,qBAAqB;AAErB,kBAAkB;AAGlB,IAAI,QAAQ,SAAS,SAAS,YAAY,GACxC,QAAQ,KAAK,iBAAiB,QAAQ,KAAK,CAAC,CAAC"}
1
+ {"version":3,"file":"worker-entry.js","names":["isObject","util.jsonStringifyReplacer","core.$ZodAsyncError","util.finalizeIssue","core.config","errors.$ZodRealError","number","boolean","util.nullish","util.codePointLength","util.getLengthableOrigin","util.aborted","util.explicitlyAborted","core.$ZodAsyncError","util.hide","util.finalizeIssue","core.config","regexes.anyString","regexes.number","regexes.boolean","util.prefixIssues","util.optionalKeys","util.cached","util.isObject","util.cleanRegex","util.rawShape","util.isPlainObject","util.getEnumValues","util.escapeRegex","core.$ZodEncodeError","util.issue","util.normalizeParams","_void","checks.$ZodCheckMinLength","checks.$ZodCheckRegex","parse.parse","parse.parseAsync","parse.safeParse","parse.safeParseAsync","core.clone","core._string","core._url","number","core._number","core._boolean","core._any","core._unknown","core._void","util.normalizeParams","optional","core._custom","core._coercedNumber","schemas.ZodMiniNumber","z.object","z.string","z.optional","z.boolean","z.enum","z.literal","z.any","z.unknown","z.array","z.number","z.void","z.object","z.optional","z.boolean","z.unknown","z.array","z.string","z.union","z.record","Property","z.object","z.enum","z.optional","z.string","z.boolean","z.record","z.union","z.unknown","z.array","z.literal","z.any","z.object","z.optional","z.number","z.unknown","z.record","z.string","z.literal","z.enum","z.regex","z.pipe","z.transform","z.nullable","z.array","z.minLength","z.discriminatedUnion","z.url","z.union","z.boolean","z.coerce.number","z.custom","fromWire","ipaddr","utc","timezone","dayjs","MIME_EXTENSIONS","isRecord","isRecord","installed"],"sources":["../src/pieces/activepieces/context/stubs.ts","../src/pieces/activepieces/worker/json-safe.ts","../../../node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/core/util.js","../../../node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/core/core.js","../../../node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/core/errors.js","../../../node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/core/parse.js","../../../node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/core/regexes.js","../../../node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/core/checks.js","../../../node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/core/versions.js","../../../node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/core/schemas.js","../../../node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/core/api.js","../../../node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/mini/schemas.js","../../../node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/mini/coerce.js","../../pieces-framework/dist/markdown-property-DMfHjEiL.js","../../pieces-framework/dist/input-BHkj_oP5.js","../../pieces-framework/dist/authentication-o-4CdAPR.js","../../../node_modules/.pnpm/nanoid@3.3.17/node_modules/nanoid/index.js","../../pieces-framework/dist/index.js","../src/pieces/activepieces/context/store-scope.ts","../src/pieces/activepieces/context/action.ts","../src/pieces/activepieces/worker/protocol.ts","../src/pieces/activepieces/indeterminate.ts","../src/pieces/activepieces/worker/host-call.ts","../src/pieces/activepieces/context/remote-store.ts","../src/pieces/activepieces/context/remote-output.ts","../src/pieces/activepieces/worker/logs.ts","../src/pieces/activepieces/worker/reactor-provider.ts","../../../node_modules/.pnpm/ipaddr.js@2.3.0/node_modules/ipaddr.js/lib/ipaddr.js","../../../node_modules/.pnpm/dayjs@1.11.9/node_modules/dayjs/dayjs.min.js","../../../node_modules/.pnpm/dayjs@1.11.9/node_modules/dayjs/plugin/timezone.js","../../../node_modules/.pnpm/dayjs@1.11.9/node_modules/dayjs/plugin/utc.js","../../pieces-framework/dist/host.js","../src/pieces/activepieces/worker/redact.ts","../src/pieces/activepieces/context/check.ts","../src/pieces/activepieces/context/limits.ts","../src/pieces/activepieces/context/files.ts","../src/pieces/activepieces/context/normalize.ts","../src/pieces/activepieces/types.ts","../src/pieces/activepieces/context/props.ts","../src/pieces/activepieces/context/trigger.ts","../../pieces-framework/dist/workflow.js","../src/pieces/activepieces/unsupported.ts","../src/pieces/activepieces/descriptor.ts","../src/pieces/activepieces/loader.ts","../src/pieces/activepieces/worker/egress.ts","../src/pieces/activepieces/worker/tls-guard.ts","../src/pieces/activepieces/worker/timings.ts","../src/pieces/activepieces/worker/entry.ts","../src/pieces/activepieces/worker/reactor-rpc.ts","../src/worker/reactor.ts","../src/worker/entry.ts"],"sourcesContent":["export class UnsupportedContextMemberError extends Error {\n readonly member: string;\n\n constructor(member: string) {\n super(\n `Piece used unimplemented context member \"${member}\". ` +\n `Implement it in the adapter or reject the piece at conformance time.`,\n );\n this.name = \"UnsupportedContextMemberError\";\n this.member = member;\n }\n}\n\n// Traps calls and member reads so both `ctx.files.write(...)` and\n// `ctx.server.apiUrl` throw with the full member path.\nexport function throwingStub(memberPath: string): unknown {\n return new Proxy(function stub() {}, {\n get(_target, prop) {\n // `then` and symbols stay inert so `await`/inspection don't false-trip.\n if (typeof prop !== \"string\" || prop === \"then\") return undefined;\n throw new UnsupportedContextMemberError(`${memberPath}.${prop}`);\n },\n apply() {\n throw new UnsupportedContextMemberError(memberPath);\n },\n });\n}\n\n// Wraps a context object so every top-level read is recorded; reads of\n// members outside the documented surface are flagged as UNDOCUMENTED.\nexport function withTouchTracking<T extends object>(\n base: T,\n touched: Set<string>,\n onTouch?: (member: string) => void,\n): T {\n return new Proxy(base, {\n get(target, prop, receiver) {\n if (typeof prop === \"string\" && prop !== \"then\") {\n const member = prop in target ? prop : `UNDOCUMENTED:${prop}`;\n touched.add(member);\n onTouch?.(member);\n }\n return Reflect.get(target, prop, receiver) as unknown;\n },\n });\n}\n","// Everything the child sends crosses a structured-clone boundary. A piece's\n// own objects routinely do not survive it, so they are flattened first.\nexport function jsonSafe(value: unknown): unknown {\n try {\n return JSON.parse(JSON.stringify(value)) as unknown;\n } catch {\n return String(value);\n }\n}\n","import { globalConfig } from \"./core.js\";\n// functions\nexport function assertEqual(val) {\n return val;\n}\nexport function assertNotEqual(val) {\n return val;\n}\nexport function toZod() {\n return (schema) => schema;\n}\nexport function assertIs(_arg) { }\nexport function assertNever(_x) {\n throw new Error(\"Unexpected value in exhaustive check\");\n}\nexport function assert(_) { }\nexport function getEnumValues(entries) {\n const numericValues = Object.values(entries).filter((v) => typeof v === \"number\");\n const values = Object.entries(entries)\n .filter(([k, _]) => numericValues.indexOf(+k) === -1)\n .map(([_, v]) => v);\n return values;\n}\nexport function joinValues(array, separator = \"|\") {\n return array.map((val) => stringifyPrimitive(val)).join(separator);\n}\nexport function jsonStringifyReplacer(_, value) {\n if (typeof value === \"bigint\")\n return value.toString();\n return value;\n}\n// the accessor lives on a shared prototype: an own accessor makes every box a dictionary-mode object (~360 B and a slow load per read against ~100 B and an inlined getter here)\nclass Cached {\n constructor(getter) {\n this._getter = getter;\n this._value = undefined;\n }\n get value() {\n const getter = this._getter;\n if (getter !== undefined) {\n this._value = getter();\n this._getter = undefined;\n }\n return this._value;\n }\n}\nexport function cached(getter) {\n return new Cached(getter);\n}\nexport function nullish(input) {\n return input === null || input === undefined;\n}\nexport function cleanRegex(source) {\n const start = source.startsWith(\"^\") ? 1 : 0;\n const end = source.endsWith(\"$\") ? source.length - 1 : source.length;\n return source.slice(start, end);\n}\nexport function floatSafeRemainder(val, step) {\n const ratio = val / step;\n const roundedRatio = Math.round(ratio);\n // `val` and `step` each round to a double before the division rounds again, so a true decimal multiple's quotient can sit up to 1.5 of these scaled epsilons from the integer. A 1x tolerance therefore rejected 2.03 as a multiple of 0.07; 4x covers the worst case with margin.\n const tolerance = 4 * Number.EPSILON * Math.max(Math.abs(ratio), 1);\n if (Math.abs(ratio - roundedRatio) < tolerance)\n return 0;\n return ratio - roundedRatio;\n}\nconst EVALUATING = /* @__PURE__*/ Symbol(\"evaluating\");\nexport function defineLazy(object, key, getter) {\n let value = undefined;\n Object.defineProperty(object, key, {\n get() {\n if (value === EVALUATING) {\n // Circular reference detected, return undefined to break the cycle\n return undefined;\n }\n if (value === undefined) {\n value = EVALUATING;\n value = getter();\n }\n return value;\n },\n set(v) {\n Object.defineProperty(object, key, {\n value: v,\n // configurable: true,\n });\n // object[key] = v;\n },\n configurable: true,\n });\n}\nexport function objectClone(obj) {\n return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj));\n}\nexport function assignProp(target, prop, value) {\n Object.defineProperty(target, prop, {\n value,\n writable: true,\n enumerable: true,\n configurable: true,\n });\n}\n/**\n * Whichever object a def's `shape` currently answers from: the one the caller passed until the first read, the frozen copy after it.\n *\n * Its keys and descriptors read without invoking anything, which is what lets a discriminated union check its discriminator, and the cycle walk read a shape, without resolving a getter that references the schema being constructed. A def that answers `shape` from an accessor of its own has none.\n */\nexport function rawShape(def) {\n const desc = Object.getOwnPropertyDescriptor(def, \"shape\");\n return desc?.get ? desc.get.raw : desc?.value;\n}\n// where a builder reads its source's keys and descriptors, resolving only a shape a def answers for itself. A shape resolves by object spread, so only its enumerable keys are ever part of it.\nfunction sourceShape(schema) {\n return rawShape(schema._zod.def) ?? schema._zod.def.shape;\n}\n// a key whose value is not settled yet, self-caching so every read after the first gets the same one\nfunction deferProp(target, key, getter) {\n Object.defineProperty(target, key, {\n get() {\n const value = getter();\n assignProp(this, key, value);\n return value;\n },\n enumerable: true,\n configurable: true,\n });\n}\n// Writes a settled key. A plain assignment is much cheaper than `defineProperty` and produces the same descriptor, but it runs whatever setter already answers to the key — an accessor this shape deferred, or an inherited one, which `__proto__` has on every object and prototype pollution can add for any name.\nfunction putProp(target, key, value) {\n if (key in target)\n assignProp(target, key, value);\n else\n target[key] = value;\n}\n/**\n * Copies `keys` of `source`'s shape onto `target`, each value passed through `wrap`.\n *\n * A key the source has resolved is copied through now, so the derived shape states it outright and nothing has to resolve it to learn what it holds. A key the source still defers stays deferred, and reads back through the source's own `shape`, so it resolves once and both shapes get that one schema.\n */\nfunction mirrorShape(target, source, keys, wrap) {\n const raw = sourceShape(source);\n for (const key of keys) {\n const desc = Object.getOwnPropertyDescriptor(raw, key);\n if (!desc.enumerable)\n continue;\n if (desc.get) {\n deferProp(target, key, () => {\n const value = source._zod.def.shape[key];\n return wrap ? wrap(value, key) : value;\n });\n }\n else\n putProp(target, key, wrap ? wrap(desc.value, key) : desc.value);\n }\n}\n// same, for a plain shape a caller passed rather than a schema's\nfunction mirrorProps(target, source) {\n for (const key of Reflect.ownKeys(source)) {\n const desc = Object.getOwnPropertyDescriptor(source, key);\n if (!desc.enumerable)\n continue;\n if (desc.get)\n deferProp(target, key, () => source[key]);\n else\n putProp(target, key, desc.value);\n }\n}\nexport function mergeDefs(...defs) {\n const mergedDescriptors = {};\n for (const def of defs) {\n const descriptors = Object.getOwnPropertyDescriptors(def);\n Object.assign(mergedDescriptors, descriptors);\n }\n return Object.defineProperties({}, mergedDescriptors);\n}\nexport function cloneDef(schema) {\n return mergeDefs(schema._zod.def);\n}\nexport function getElementAtPath(obj, path) {\n if (!path)\n return obj;\n return path.reduce((acc, key) => acc?.[key], obj);\n}\nexport function promiseAllObject(promisesObj) {\n const keys = Object.keys(promisesObj);\n const promises = keys.map((key) => promisesObj[key]);\n return Promise.all(promises).then((results) => {\n const resolvedObj = {};\n for (let i = 0; i < keys.length; i++) {\n resolvedObj[keys[i]] = results[i];\n }\n return resolvedObj;\n });\n}\nexport function randomString(length = 10) {\n const chars = \"abcdefghijklmnopqrstuvwxyz\";\n let str = \"\";\n for (let i = 0; i < length; i++) {\n str += chars[Math.floor(Math.random() * chars.length)];\n }\n return str;\n}\nexport function esc(str) {\n return JSON.stringify(str);\n}\nexport function slugify(input) {\n return input\n .toLowerCase()\n .trim()\n .replace(/[^\\w\\s-]/g, \"\")\n .replace(/[\\s_-]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n}\nexport const captureStackTrace = (\"captureStackTrace\" in Error ? Error.captureStackTrace : (..._args) => { });\nexport function isObject(data) {\n return typeof data === \"object\" && data !== null && !Array.isArray(data);\n}\nexport const allowsEval = /* @__PURE__*/ cached(() => {\n // Skip the probe under `jitless`: strict CSPs report the caught `new Function` as a `securitypolicyviolation` even though the throw is swallowed.\n if (globalConfig.jitless) {\n return false;\n }\n // @ts-ignore\n if (typeof navigator !== \"undefined\" && navigator?.userAgent?.includes(\"Cloudflare\")) {\n return false;\n }\n try {\n const F = Function;\n new F(\"\");\n return true;\n }\n catch (_) {\n return false;\n }\n});\nexport function isPlainObject(o) {\n if (isObject(o) === false)\n return false;\n // modified constructor\n const ctor = o.constructor;\n if (ctor === undefined)\n return true;\n if (typeof ctor !== \"function\")\n return true;\n // modified prototype\n const prot = ctor.prototype;\n if (isObject(prot) === false)\n return false;\n // ctor doesn't have static `isPrototypeOf`\n if (Object.prototype.hasOwnProperty.call(prot, \"isPrototypeOf\") === false) {\n return false;\n }\n return true;\n}\nexport function shallowClone(o) {\n if (isPlainObject(o))\n return { ...o };\n if (Array.isArray(o))\n return [...o];\n if (o instanceof Map)\n return new Map(o);\n if (o instanceof Set)\n return new Set(o);\n return o;\n}\nexport function numKeys(data) {\n let keyCount = 0;\n for (const key in data) {\n if (Object.prototype.hasOwnProperty.call(data, key)) {\n keyCount++;\n }\n }\n return keyCount;\n}\nexport const getParsedType = (data) => {\n const t = typeof data;\n switch (t) {\n case \"undefined\":\n return \"undefined\";\n case \"string\":\n return \"string\";\n case \"number\":\n return Number.isNaN(data) ? \"nan\" : \"number\";\n case \"boolean\":\n return \"boolean\";\n case \"function\":\n return \"function\";\n case \"bigint\":\n return \"bigint\";\n case \"symbol\":\n return \"symbol\";\n case \"object\":\n if (Array.isArray(data)) {\n return \"array\";\n }\n if (data === null) {\n return \"null\";\n }\n if (data.then && typeof data.then === \"function\" && data.catch && typeof data.catch === \"function\") {\n return \"promise\";\n }\n if (typeof Map !== \"undefined\" && data instanceof Map) {\n return \"map\";\n }\n if (typeof Set !== \"undefined\" && data instanceof Set) {\n return \"set\";\n }\n if (typeof Date !== \"undefined\" && data instanceof Date) {\n return \"date\";\n }\n // @ts-ignore\n if (typeof File !== \"undefined\" && data instanceof File) {\n return \"file\";\n }\n return \"object\";\n default:\n throw new Error(`Unknown data type: ${t}`);\n }\n};\nexport const propertyKeyTypes = /* @__PURE__*/ new Set([\"string\", \"number\", \"symbol\"]);\nexport const primitiveTypes = /* @__PURE__*/ new Set([\n \"string\",\n \"number\",\n \"bigint\",\n \"boolean\",\n \"symbol\",\n \"undefined\",\n]);\nexport function escapeRegex(str) {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n// zod-specific utils\nexport function clone(inst, def, params) {\n const cl = new inst._zod.constr(def ?? inst._zod.def);\n if (!def || params?.parent)\n cl._zod.parent = inst;\n return cl;\n}\nexport function normalizeParams(_params) {\n const params = _params;\n if (!params)\n return {};\n if (typeof params === \"string\")\n return { error: () => params };\n if (params?.message !== undefined) {\n if (params?.error !== undefined)\n throw new Error(\"Cannot specify both `message` and `error` params\");\n params.error = params.message;\n }\n delete params.message;\n if (typeof params.error === \"string\")\n return { ...params, error: () => params.error };\n return params;\n}\nexport function createTransparentProxy(getter) {\n let target;\n return new Proxy({}, {\n get(_, prop, receiver) {\n target ?? (target = getter());\n return Reflect.get(target, prop, receiver);\n },\n set(_, prop, value, receiver) {\n target ?? (target = getter());\n return Reflect.set(target, prop, value, receiver);\n },\n has(_, prop) {\n target ?? (target = getter());\n return Reflect.has(target, prop);\n },\n deleteProperty(_, prop) {\n target ?? (target = getter());\n return Reflect.deleteProperty(target, prop);\n },\n ownKeys(_) {\n target ?? (target = getter());\n return Reflect.ownKeys(target);\n },\n getOwnPropertyDescriptor(_, prop) {\n target ?? (target = getter());\n return Reflect.getOwnPropertyDescriptor(target, prop);\n },\n defineProperty(_, prop, descriptor) {\n target ?? (target = getter());\n return Reflect.defineProperty(target, prop, descriptor);\n },\n });\n}\nexport function stringifyPrimitive(value) {\n if (typeof value === \"bigint\")\n return value.toString() + \"n\";\n if (typeof value === \"string\")\n return `\"${value}\"`;\n return `${value}`;\n}\nexport function optionalKeys(shape) {\n return Object.keys(shape).filter((k) => {\n return shape[k]._zod.optin !== undefined && shape[k]._zod.optout === \"optional\";\n });\n}\n// Wrapped in a `@__PURE__` IIFE: esbuild never tree-shakes a top-level initializer that contains a member access on `Number`, so the bare object literal survived into every bundle.\nexport const NUMBER_FORMAT_RANGES = /*@__PURE__*/ (() => ({\n safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],\n int32: [-2147483648, 2147483647],\n uint32: [0, 4294967295],\n float32: [-3.4028234663852886e38, 3.4028234663852886e38],\n float64: [-Number.MAX_VALUE, Number.MAX_VALUE],\n}))();\nexport const BIGINT_FORMAT_RANGES = {\n int64: [/* @__PURE__*/ BigInt(\"-9223372036854775808\"), /* @__PURE__*/ BigInt(\"9223372036854775807\")],\n uint64: [/* @__PURE__*/ BigInt(0), /* @__PURE__*/ BigInt(\"18446744073709551615\")],\n};\nexport function pick(schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".pick() cannot be used on object schemas containing refinements\");\n }\n const newShape = {};\n mirrorShape(newShape, schema, maskedKeys(schema, mask));\n return clone(schema, mergeDefs(currDef, { shape: newShape, checks: [] }));\n}\n// the mask keys that select something, checked against the source's shape without resolving it\nfunction maskedKeys(schema, mask) {\n const raw = sourceShape(schema);\n const keys = [];\n // `for...in` skips symbols, so a symbol in the mask would select nothing\n for (const key of Reflect.ownKeys(mask)) {\n if (!Object.getOwnPropertyDescriptor(raw, key)?.enumerable) {\n throw new Error(`Unrecognized key: \"${String(key)}\"`);\n }\n if (mask[key])\n keys.push(key);\n }\n return keys;\n}\nexport function omit(schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".omit() cannot be used on object schemas containing refinements\");\n }\n const omitted = new Set(maskedKeys(schema, mask));\n const newShape = {};\n mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)).filter((key) => !omitted.has(key)));\n return clone(schema, mergeDefs(currDef, { shape: newShape, checks: [] }));\n}\nexport function extend(schema, shape) {\n if (!isPlainObject(shape)) {\n throw new Error(\"Invalid input to extend: expected a plain object\");\n }\n const checks = schema._zod.def.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n // Only throw if new shape overlaps with existing shape. Use getOwnPropertyDescriptor to check key existence without accessing values\n const existingShape = sourceShape(schema);\n for (const key of Reflect.ownKeys(shape)) {\n if (Object.getOwnPropertyDescriptor(existingShape, key) !== undefined) {\n throw new Error(\"Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.\");\n }\n }\n }\n return clone(schema, mergeDefs(schema._zod.def, { shape: extended(schema, shape) }));\n}\n// the source's keys, then the caller's overlaid on top\nfunction extended(schema, shape) {\n const newShape = {};\n mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)));\n mirrorProps(newShape, shape);\n return newShape;\n}\nexport function safeExtend(schema, shape) {\n if (!isPlainObject(shape)) {\n throw new Error(\"Invalid input to safeExtend: expected a plain object\");\n }\n return clone(schema, mergeDefs(schema._zod.def, { shape: extended(schema, shape) }));\n}\nexport function merge(a, b) {\n if (!b?._zod?.def) {\n throw new Error(\"Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.\");\n }\n if (a._zod.def.checks?.length) {\n throw new Error(\".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.\");\n }\n const newShape = {};\n mirrorShape(newShape, a, Reflect.ownKeys(sourceShape(a)));\n mirrorShape(newShape, b, Reflect.ownKeys(sourceShape(b)));\n const def = mergeDefs(a._zod.def, {\n shape: newShape,\n get catchall() {\n return b._zod.def.catchall;\n },\n checks: b._zod.def.checks ?? [],\n });\n return clone(a, def);\n}\nexport function partial(Class, schema, mask, name = \"partial\") {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(`.${name}() cannot be used on object schemas containing refinements`);\n }\n const selected = mask ? new Set(maskedKeys(schema, mask)) : undefined;\n const newShape = {};\n mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)), Class &&\n ((value, key) => (selected && !selected.has(key) ? value : new Class({ type: \"optional\", innerType: value }))));\n return clone(schema, mergeDefs(schema._zod.def, { shape: newShape, checks: [] }));\n}\nexport function required(Class, schema, mask) {\n const selected = mask ? new Set(maskedKeys(schema, mask)) : undefined;\n const newShape = {};\n mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)), (value, key) => \n // overwrite with non-optional\n selected && !selected.has(key) ? value : new Class({ type: \"nonoptional\", innerType: value }));\n return clone(schema, mergeDefs(schema._zod.def, { shape: newShape }));\n}\n// invalid_type | too_big | too_small | invalid_format | not_multiple_of | unrecognized_keys | invalid_union | invalid_key | invalid_element | invalid_value | custom\nexport function aborted(x, startIndex = 0) {\n if (x.aborted === true)\n return true;\n for (let i = startIndex; i < x.issues.length; i++) {\n if (x.issues[i]?.continue !== true) {\n return true;\n }\n }\n return false;\n}\n// Checks for explicit abort (continue === false), as opposed to implicit abort (continue === undefined). Used to respect `abort: true` in .refine() even for checks that have a `when` function.\nexport function explicitlyAborted(x, startIndex = 0) {\n if (x.aborted === true)\n return true;\n for (let i = startIndex; i < x.issues.length; i++) {\n if (x.issues[i]?.continue === false) {\n return true;\n }\n }\n return false;\n}\nexport function prefixIssues(path, issues) {\n return issues.map((iss) => {\n var _a;\n (_a = iss).path ?? (_a.path = []);\n iss.path.unshift(path);\n return iss;\n });\n}\nexport function unwrapMessage(message) {\n return typeof message === \"string\" ? message : message?.message;\n}\n/* A check holds no link back to the schema it is attached to — the same check instance is shared by every clone of that schema — so the owner is stamped onto the issues a check just raised, at the only point where both are in scope. Runs on the failure path only; `start` is the issue count from before the check ran. */\nexport function attachSchema(issues, start, inst) {\n var _a;\n for (let i = start; i < issues.length; i++) {\n (_a = issues[i]).schema ?? (_a.schema = inst);\n }\n}\nexport function finalizeIssue(iss, ctx, config) {\n var _a;\n // A schema that raised an issue itself owns it outright, and outranks any stamp an enclosing check left in `attachSchema`. String formats and z.custom() are schema and check at once, so when they act as a check they defer to that stamp instead.\n const traits = iss.inst?._zod?.traits;\n if (traits?.has(\"$ZodType\")) {\n if (traits.has(\"$ZodCheck\"))\n (_a = iss).schema ?? (_a.schema = iss.inst);\n else\n iss.schema = iss.inst;\n }\n // Decreasing specificity, first map to return a message wins. `inst` is whatever raised the issue, so a check's own map outranks the owning schema's.\n const schemaError = iss.schema !== iss.inst ? iss.schema?._zod.def?.error : undefined;\n const message = iss.message\n ? iss.message\n : (unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ??\n unwrapMessage(schemaError?.(iss)) ??\n unwrapMessage(ctx?.error?.(iss)) ??\n unwrapMessage(config.customError?.(iss)) ??\n unwrapMessage(config.localeError?.(iss)) ??\n \"Invalid input\");\n // an explicit own-key copy beats object rest with excluded keys, which v8 routes through a generic runtime call; Object.keys rather than for-in so an issue pushed with a prototype does not leak inherited keys, and an own __proto__ key is dropped rather than assigned through the setter\n const full = {};\n for (const k of Object.keys(iss)) {\n if (k === \"inst\" || k === \"schema\" || k === \"continue\" || k === \"input\" || k === \"__proto__\")\n continue;\n full[k] = iss[k];\n }\n full.path ?? (full.path = []);\n full.message = message;\n if (ctx?.reportInput) {\n full.input = iss.input;\n }\n return full;\n}\nexport function getSizableOrigin(input) {\n if (input instanceof Set)\n return \"set\";\n if (input instanceof Map)\n return \"map\";\n // @ts-ignore\n if (input instanceof File)\n return \"file\";\n return \"unknown\";\n}\nconst highSurrogate = /[\\uD800-\\uDBFF]/;\n// Code points in `str`: a surrogate pair counts once, a lone surrogate as itself. Hand-rolled because the string iterator allocates and runs ~250x slower on this path; the regex probe exits ~50x quicker for a string with no astral characters.\nexport function codePointLength(str) {\n const units = str.length;\n if (!highSurrogate.test(str))\n return units;\n let count = units;\n for (let i = 0; i < units - 1; i++) {\n if ((str.charCodeAt(i) & 0xfc00) === 0xd800 && (str.charCodeAt(i + 1) & 0xfc00) === 0xdc00) {\n count--;\n i++;\n }\n }\n return count;\n}\nexport function getLengthableOrigin(input) {\n if (Array.isArray(input))\n return \"array\";\n if (typeof input === \"string\")\n return \"string\";\n return \"unknown\";\n}\nexport function parsedType(data) {\n const t = typeof data;\n switch (t) {\n case \"number\": {\n return Number.isNaN(data) ? \"nan\" : \"number\";\n }\n case \"object\": {\n if (data === null) {\n return \"null\";\n }\n if (Array.isArray(data)) {\n return \"array\";\n }\n const obj = data;\n if (obj && Object.getPrototypeOf(obj) !== Object.prototype && \"constructor\" in obj && obj.constructor) {\n return obj.constructor.name;\n }\n }\n }\n return t;\n}\nexport function issue(...args) {\n const [iss, input, inst] = args;\n if (typeof iss === \"string\") {\n return {\n message: iss,\n code: \"custom\",\n input,\n inst,\n };\n }\n return { ...iss };\n}\nexport function cleanEnum(obj) {\n return Object.entries(obj)\n .filter(([k, _]) => {\n // return true if NaN, meaning it's not a number, thus a string key\n return Number.isNaN(Number.parseInt(k, 10));\n })\n .map((el) => el[1]);\n}\n// Codec utility functions\nexport function base64ToUint8Array(base64) {\n const binaryString = atob(base64);\n const bytes = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n bytes[i] = binaryString.charCodeAt(i);\n }\n return bytes;\n}\nexport function uint8ArrayToBase64(bytes) {\n let binaryString = \"\";\n for (let i = 0; i < bytes.length; i++) {\n binaryString += String.fromCharCode(bytes[i]);\n }\n return btoa(binaryString);\n}\nexport function base64urlToUint8Array(base64url) {\n const base64 = base64url.replace(/-/g, \"+\").replace(/_/g, \"/\");\n const padding = \"=\".repeat((4 - (base64.length % 4)) % 4);\n return base64ToUint8Array(base64 + padding);\n}\nexport function uint8ArrayToBase64url(bytes) {\n return uint8ArrayToBase64(bytes).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=/g, \"\");\n}\nexport function hexToUint8Array(hex) {\n const cleanHex = hex.replace(/^0x/, \"\");\n if (cleanHex.length % 2 !== 0) {\n throw new Error(\"Invalid hex string length\");\n }\n const bytes = new Uint8Array(cleanHex.length / 2);\n for (let i = 0; i < cleanHex.length; i += 2) {\n bytes[i / 2] = Number.parseInt(cleanHex.slice(i, i + 2), 16);\n }\n return bytes;\n}\nexport function uint8ArrayToHex(bytes) {\n return Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n// instanceof\nexport class Class {\n constructor(..._args) { }\n}\n////////// PROTOTYPE INSTALLERS //////////\n//\n// Members live on the prototype and materialize per instance on first read, which keeps own-property count under the step where V8 stops using inline slots. Changing anything here means re-measuring runtime, memory and bundle size together — see \"The three axes\" in AGENTS.md.\n/**\n * Installs a trait's members on its prototype. Each value builds that member for the instance on first read; the built value shadows the accessor as an own property, so a detached `const { parse } = schema` keeps working.\n *\n * Call this from a `proto` initializer, which runs once per prototype — never per instance.\n */\nexport function members(proto, table) {\n for (const key in table) {\n const desc = Object.getOwnPropertyDescriptor(table, key);\n // a getter installs as written, so it stays live: `description` reads through to the registry on every access. not enumerable: an object literal's is, and a prototype member never was\n if (desc.get)\n Object.defineProperty(proto, key, { ...desc, enumerable: false });\n // a method materializes bound on first read, which is what keeps a detached member working: `const opt = schema.optional; opt()`\n else\n defineBound(proto, key, desc.value);\n }\n}\n/** Shadows a prototype member with an own value, so a getter that builds from the instance runs once. */\nexport function own(inst, key, value, enumerable = true) {\n Object.defineProperty(inst, key, { configurable: true, writable: true, enumerable, value });\n return value;\n}\n/** Like {@link own}, for a member that was never an own data property and has to stay out of `Object.keys`. */\nexport function hide(inst, key, value) {\n return own(inst, key, value, false);\n}\n/** Adds members a table derives from the instance: each builds on first read and shadows as own data, and assignment shadows the same way, as when these were own properties. */\nexport /*@__NO_SIDE_EFFECTS__*/ function derived(computes, table) {\n for (const key in computes) {\n const compute = computes[key];\n // an object literal's accessor is configurable and enumerable, and `members` copies the descriptor as written\n Object.defineProperty(table, key, {\n configurable: true,\n enumerable: true,\n get() {\n return own(this, key, compute(this));\n },\n set(value) {\n own(this, key, value);\n },\n });\n }\n return table;\n}\nfunction defineBound(proto, key, fn) {\n Object.defineProperty(proto, key, {\n configurable: true,\n get() {\n // vitest's spyOn calls a prototype getter bare to find the function it wraps, so a nullish receiver answers the raw method\n return this == null ? fn : own(this, key, fn.bind(this));\n },\n set(value) {\n own(this, key, value);\n },\n });\n}\n/** Returns the prototype to install on, or `undefined` if this group is already installed on it. */\nfunction claim(inst, sentinel) {\n const proto = Object.getPrototypeOf(inst);\n // Runs on every construction, so `in` rather than the costlier `hasOwnProperty.call`. Sentinels are keys the group itself defines.\n return sentinel in proto ? undefined : proto;\n}\n// The internals whose init chain is installing. A second call for the same one is a derived constructor overriding its base, so it must not construct another schema in between or the override is dropped.\nlet installing;\n// Set while a getter is running, so a value that resolved through a recursion break is not memoized. One shared descriptor shadows the key for the duration, which costs no per-key allocation.\nlet broke = false;\nconst breaker = {\n configurable: true,\n get() {\n broke = true;\n return undefined;\n },\n};\n/**\n * Installs a lazily-derived internal on the `_zod` prototype of `inst`'s\n * constructor, computed from the internals object itself and cached there on\n * first read. One accessor per constructor rather than one per instance.\n */\nexport function defineLazyInternal(inst, key, compute) {\n const proto = Object.getPrototypeOf(inst._zod);\n if (key in proto && installing !== inst._zod) {\n // A repeat construction: everything is installed already. Cleared here so the reference is not held past the first construction of every type.\n installing = undefined;\n return;\n }\n installing = inst._zod;\n Object.defineProperty(proto, key, {\n configurable: true,\n get() {\n // Shadowed before computing so a re-entrant read from a recursive schema resolves to undefined instead of running the getter again.\n Object.defineProperty(this, key, breaker);\n const outer = broke;\n broke = false;\n try {\n const value = compute(this);\n // A result that resolved through a recursion break is recomputed once the graph is complete; everything else memoizes, undefined included.\n if (broke)\n delete this[key];\n else\n Object.defineProperty(this, key, { configurable: true, writable: true, value });\n broke = broke || outer;\n return value;\n }\n catch (err) {\n // A compute that threw memoizes nothing, so a later read runs it again and fails the same way. The shadow goes with it, since leaving it installed would answer undefined for every later read.\n delete this[key];\n broke = broke || outer;\n throw err;\n }\n },\n set(value) {\n Object.defineProperty(this, key, { configurable: true, writable: true, value });\n },\n });\n}\n/**\n * Installs `key` on `inst`'s prototype, computed by `make` on first read and cached there as an own\n * data property. One accessor per constructor rather than one per instance, because an own accessor\n * puts every instance after the first into v8 dictionary mode. The key doubles as the sentinel.\n */\nexport function installLazyProp(inst, key, make, enumerable) {\n const proto = claim(inst, key);\n if (!proto)\n return;\n Object.defineProperty(proto, key, {\n configurable: true,\n get() {\n // Shadowed before computing, so a re-entrant read from a self-referential shape resolves to undefined instead of running the getter again. A data property rather than an accessor: an own accessor is the dictionary-mode transition this exists to avoid.\n const desc = { configurable: true, writable: true, enumerable, value: undefined };\n Object.defineProperty(this, key, desc);\n // a compute that throws leaves the shadow behind, so later reads answer undefined instead of re-throwing; `defineLazy` did the same, and `defineLazyInternal`'s delete-on-catch would cost bytes in every bundle for a case only a throwing user getter reaches\n desc.value = make(this);\n Object.defineProperty(this, key, desc);\n return desc.value;\n },\n set(value) {\n Object.defineProperty(this, key, { configurable: true, writable: true, enumerable, value });\n },\n });\n}\n/** Marks the thunk `_catch` synthesises for a constant catch value. `Function.length` cannot tell that thunk from a user callback — rest and defaulted parameters both report arity 0 — and a user callback reads `ctx.error`, whose issues only finalize correctly against the caller's per-parse error map. Provenance can say what arity cannot. A plain string key rather than `Symbol.for`, whose call at module scope no bundler can prove pure — the same shape that anchored `urlCanParse` into every build. */\nexport const CONSTANT_CATCH = \"~constantCatch\";\n/** Wraps a constant catch value in a thunk tagged with {@link CONSTANT_CATCH}. */\nexport function constantCatch(value) {\n const fn = () => value;\n fn[CONSTANT_CATCH] = true;\n return fn;\n}\n","var _a;\nimport { members as installMembers } from \"./util.js\";\n/** A special constant with type `never` */\nexport const NEVER = /*@__PURE__*/ Object.freeze({\n status: \"aborted\",\n});\n/* Shared descriptor for installing `_zod`; defineProperty reads it\n * synchronously, so reusing one object avoids a per-instance allocation. */\nconst _zodDesc = { value: undefined, enumerable: false };\n// null where suppressing the capture would be unrecoverable: `parse()` puts the frames back with `captureStackTrace`, so without it the throw would lose its stack. also latched to null once `stackTraceLimit` proves unassignable, which a realm can do at any point by hardening Error\nlet _E = \"captureStackTrace\" in Error ? Error : null;\n// v8 captures a stack trace inside the Error constructor, which dominates a failed parse; costs only the frames, and parse() restores those. the constructor must RUN: Object.create is cheaper and passes instanceof, but Error.isError and util.types.isNativeError check an internal slot\nfunction newError(Definition) {\n const E = _E;\n if (E) {\n const saved = E.stackTraceLimit;\n if (typeof saved === \"number\") {\n try {\n E.stackTraceLimit = 0;\n }\n catch {\n _E = null;\n return new Definition();\n }\n try {\n return new Definition();\n }\n finally {\n E.stackTraceLimit = saved;\n }\n }\n }\n return new Definition();\n}\nexport /*@__NO_SIDE_EFFECTS__*/ function $constructor(name, initializer, \n/** This trait's members, installed once on every prototype that composes it. They cannot be declared in the initializer above: that runs per instance, and the prototype is shared. */\nproto, params) {\n // Prototype for this constructor's `_zod` internals. Lazily-derived fields (`values`, `pattern`, `optin`, …) install here once rather than as an accessor on every instance.\n const zodProto = {};\n // Assigning the fields in the constructor body is what gives instances in-object slots; building the object literally and reparenting it costs a second allocation and a generic property copy.\n function Internals(def) {\n this.def = def;\n this.constr = _;\n this.traits = new Set();\n }\n Internals.prototype = zodProto;\n const protoMembers = proto;\n // One trait's members land on every prototype whose chain composes it, so the answer is per prototype rather than per trait.\n const initialized = protoMembers && new WeakSet();\n function init(inst, def) {\n if (!inst._zod) {\n _zodDesc.value = new Internals(def);\n try {\n Object.defineProperty(inst, \"_zod\", _zodDesc);\n }\n finally {\n // Cleared even on throw, so the shared descriptor never leaks one instance's internals into the next.\n _zodDesc.value = undefined;\n }\n }\n else if (inst._zod.traits.has(name)) {\n return;\n }\n inst._zod.traits.add(name);\n initializer(inst, def);\n if (initialized) {\n // `super(def)` from a user subclass gives `this` a prototype the subclass owns, and installing there would overwrite whatever the subclass declared. `constr` built the instance, so its prototype is the one below the subclass's that should carry the members. A receiver whose chain never reaches that prototype installs on its own, which for a plain object handed straight to `init` means `Object.prototype` — unchanged from before.\n const own = Object.getPrototypeOf(inst);\n const ctorProto = inst._zod.constr.prototype;\n let up = own;\n while (up && up !== ctorProto)\n up = Object.getPrototypeOf(up);\n const target = up ?? own;\n if (!initialized.has(target)) {\n initialized.add(target);\n installMembers(target, protoMembers);\n }\n }\n // support prototype modifications; for-in avoids the array allocation of Object.keys on the (usually empty) prototype\n const proto = _.prototype;\n for (const k in proto) {\n if (!Object.prototype.hasOwnProperty.call(proto, k))\n continue;\n if (!(k in inst)) {\n inst[k] = proto[k].bind(inst);\n }\n }\n }\n // doesn't work if Parent has a constructor with arguments\n const Parent = params?.Parent ?? Object;\n class Definition extends Parent {\n }\n Object.defineProperty(Definition, \"name\", { value: name });\n function _(def) {\n const inst = params?.Parent ? newError(Definition) : this;\n init(inst, def);\n const deferred = inst._zod.deferred;\n if (deferred) {\n for (const fn of deferred) {\n fn();\n }\n // Released: initializers run once, and the list would otherwise be retained for the schema's lifetime.\n inst._zod.deferred = undefined;\n }\n // Global post-processor hook. Internal: installed by `import \"zod/compile\"` to enable AOT compilation for every constructed schema. Runs last, once the instance is fully built, because it hands the instance to compile(). The post-processor is expected to be reentrancy-guarded by its own implementation.\n const pp = globalThis.__zod_globalConfig?.postProcessor;\n if (pp)\n pp(inst);\n return inst;\n }\n Object.defineProperty(_, \"init\", { value: init });\n Object.defineProperty(_, Symbol.hasInstance, {\n value: (inst) => {\n if (params?.Parent && inst instanceof params.Parent)\n return true;\n return inst?._zod?.traits?.has(name);\n },\n });\n Object.defineProperty(_, \"name\", { value: name });\n return _;\n}\n////////////////////////////// UTILITIES ///////////////////////////////////////\nexport const $brand = /*@__PURE__*/ Symbol(\"zod_brand\");\nexport class $ZodAsyncError extends Error {\n constructor() {\n super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);\n }\n}\nexport class $ZodEncodeError extends Error {\n constructor(name) {\n super(`Encountered unidirectional transform during encode: ${name}`);\n this.name = \"ZodEncodeError\";\n }\n}\n(_a = globalThis).__zod_globalConfig ?? (_a.__zod_globalConfig = {});\nexport const globalConfig = globalThis.__zod_globalConfig;\nexport function config(newConfig) {\n if (newConfig)\n Object.assign(globalConfig, newConfig);\n return globalConfig;\n}\n","import { $constructor } from \"./core.js\";\nimport * as util from \"./util.js\";\n/* Computing the message eagerly is expensive (pretty-printed JSON of all\n * issues), so defer it until first read. The accessor functions and\n * descriptors are shared across instances to keep error construction\n * cheap; the computed message is cached on the internals object. The\n * setter preserves plain assignment semantics for consumers that\n * overwrite `message`. */\nfunction _getMessage() {\n const internals = this._zod;\n internals.message ?? (internals.message = JSON.stringify(internals.def, util.jsonStringifyReplacer, 2));\n return internals.message;\n}\nfunction _setMessage(value) {\n this._zod.message = value;\n}\nconst _messageDesc = {\n get: _getMessage,\n set: _setMessage,\n enumerable: true,\n configurable: true,\n};\nconst _issuesDesc = { value: undefined, enumerable: false };\n/* Prototypes that already carry the lazy `toString`. Seeded with the\n * intrinsics so that `init` on a foreign object — it accepts any object —\n * can never install an accessor onto a prototype we do not own. */\nconst _installedToString = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]);\nconst initializer = (inst, def) => {\n inst.name = \"$ZodError\";\n // `_zod` is already non-enumerable: $constructor's init defined it with this same descriptor\n _issuesDesc.value = def;\n Object.defineProperty(inst, \"issues\", _issuesDesc);\n // Clear the shared slot; a retained `value` pins the last error's issues.\n _issuesDesc.value = undefined;\n Object.defineProperty(inst, \"message\", _messageDesc);\n /* `toString` lives as a non-enumerable lazy getter on the shared\n * prototype; on first access it caches a per-instance closure so\n * detached usage still works. */\n const proto = Object.getPrototypeOf(inst);\n if (!_installedToString.has(proto)) {\n _installedToString.add(proto);\n Object.defineProperty(proto, \"toString\", {\n configurable: true,\n enumerable: false,\n get() {\n const value = () => this.message;\n Object.defineProperty(this, \"toString\", { value, configurable: true, writable: true });\n return value;\n },\n set(value) {\n Object.defineProperty(this, \"toString\", { value, configurable: true, writable: true });\n },\n });\n }\n};\nexport const $ZodError = $constructor(\"$ZodError\", initializer);\nexport const $ZodRealError = $constructor(\"$ZodError\", initializer, undefined, {\n Parent: Error,\n});\n/** Get-or-create `obj[key]` as an own data property. A path segment naming an inherited member\n * (\"toString\", \"constructor\") would otherwise read through to the prototype, and assigning\n * \"__proto__\" would hit the setter instead of creating a key. */\nfunction node(obj, key, make) {\n if (!Object.prototype.hasOwnProperty.call(obj, key)) {\n if (key === \"__proto__\") {\n Object.defineProperty(obj, key, { value: make(), writable: true, enumerable: true, configurable: true });\n }\n else {\n obj[key] = make();\n }\n }\n return obj[key];\n}\nexport function flattenError(error, mapper = (issue) => issue.message) {\n const fieldErrors = {};\n const formErrors = [];\n for (const sub of error.issues) {\n if (sub.path.length > 0) {\n node(fieldErrors, sub.path[0], () => []).push(mapper(sub));\n }\n else {\n formErrors.push(mapper(sub));\n }\n }\n return { formErrors, fieldErrors };\n}\nexport function formatError(error, mapper = (issue) => issue.message) {\n const fieldErrors = { _errors: [] };\n const processError = (error, path = []) => {\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\" && issue.errors.length) {\n issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path]));\n }\n else if (issue.code === \"invalid_key\") {\n processError({ issues: issue.issues }, [...path, ...issue.path]);\n }\n else if (issue.code === \"invalid_element\") {\n processError({ issues: issue.issues }, [...path, ...issue.path]);\n }\n else {\n const fullpath = [...path, ...issue.path];\n if (fullpath.length === 0) {\n fieldErrors._errors.push(mapper(issue));\n }\n else {\n let curr = fieldErrors;\n let i = 0;\n while (i < fullpath.length) {\n const el = fullpath[i];\n const terminal = i === fullpath.length - 1;\n // `_errors` is reserved by this legacy format, so merge a matching path segment into the current node instead of treating its array as a child.\n if (el === \"_errors\") {\n if (terminal)\n curr._errors.push(mapper(issue));\n i++;\n continue;\n }\n // A path element may collide with an inherited property name such as\n // \"__proto__\" or \"constructor\". Truthiness checks read the prototype\n // (so no node is created, then ._errors.push throws), and bracket\n // assignment of \"__proto__\" hits the setter instead of creating an\n // own key. Guard the read with hasOwnProperty and create the node\n // with defineProperty so any path element becomes a real own key.\n if (!Object.prototype.hasOwnProperty.call(curr, el)) {\n Object.defineProperty(curr, el, {\n value: { _errors: [] },\n enumerable: true,\n writable: true,\n configurable: true,\n });\n }\n const node = curr[el];\n if (terminal) {\n node._errors.push(mapper(issue));\n }\n curr = node;\n i++;\n }\n }\n }\n }\n };\n processError(error);\n return fieldErrors;\n}\nexport function treeifyError(error, mapper = (issue) => issue.message) {\n const result = { errors: [] };\n const processError = (error, path = []) => {\n var _a;\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\" && issue.errors.length) {\n // regular union error\n issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path]));\n }\n else if (issue.code === \"invalid_key\") {\n processError({ issues: issue.issues }, [...path, ...issue.path]);\n }\n else if (issue.code === \"invalid_element\") {\n processError({ issues: issue.issues }, [...path, ...issue.path]);\n }\n else {\n const fullpath = [...path, ...issue.path];\n if (fullpath.length === 0) {\n result.errors.push(mapper(issue));\n continue;\n }\n let curr = result;\n let i = 0;\n while (i < fullpath.length) {\n const el = fullpath[i];\n const terminal = i === fullpath.length - 1;\n if (typeof el === \"string\") {\n curr.properties ?? (curr.properties = {});\n // el may collide with an inherited property name (\"__proto__\",\n // \"constructor\", ...); ??= reads the prototype so the node is never\n // created and curr.errors.push throws. Guard with hasOwnProperty and\n // create the node with defineProperty so \"__proto__\" becomes a real\n // own key rather than invoking the prototype setter.\n if (!Object.prototype.hasOwnProperty.call(curr.properties, el)) {\n Object.defineProperty(curr.properties, el, {\n value: { errors: [] },\n enumerable: true,\n writable: true,\n configurable: true,\n });\n }\n curr = curr.properties[el];\n }\n else {\n curr.items ?? (curr.items = []);\n (_a = curr.items)[el] ?? (_a[el] = { errors: [] });\n curr = curr.items[el];\n }\n if (terminal) {\n curr.errors.push(mapper(issue));\n }\n i++;\n }\n }\n }\n };\n processError(error);\n return result;\n}\n/** Format a ZodError as a human-readable string in the following form.\n *\n * From\n *\n * ```ts\n * ZodError {\n * issues: [\n * {\n * expected: 'string',\n * code: 'invalid_type',\n * path: [ 'username' ],\n * message: 'Invalid input: expected string'\n * },\n * {\n * expected: 'number',\n * code: 'invalid_type',\n * path: [ 'favoriteNumbers', 1 ],\n * message: 'Invalid input: expected number'\n * }\n * ];\n * }\n * ```\n *\n * to\n *\n * ```\n * username\n * ✖ Expected number, received string at \"username\n * favoriteNumbers[0]\n * ✖ Invalid input: expected number\n * ```\n */\nexport function toDotPath(_path) {\n const segs = [];\n const path = _path.map((seg) => (typeof seg === \"object\" ? seg.key : seg));\n for (const seg of path) {\n if (typeof seg === \"number\")\n segs.push(`[${seg}]`);\n else if (typeof seg === \"symbol\")\n segs.push(`[${JSON.stringify(String(seg))}]`);\n else if (/[^\\w$]/.test(seg))\n segs.push(`[${JSON.stringify(seg)}]`);\n else {\n if (segs.length)\n segs.push(\".\");\n segs.push(seg);\n }\n }\n return segs.join(\"\");\n}\nexport function prettifyError(error) {\n const lines = [];\n // sort by path length\n const issues = [...error.issues].sort((a, b) => (a.path ?? []).length - (b.path ?? []).length);\n // Process each issue\n for (const issue of issues) {\n lines.push(`✖ ${issue.message}`);\n if (issue.path?.length)\n lines.push(` → at ${toDotPath(issue.path)}`);\n }\n // Convert Map to formatted string\n return lines.join(\"\\n\");\n}\n","import * as core from \"./core.js\";\nimport * as errors from \"./errors.js\";\nimport * as util from \"./util.js\";\n// Always both keys, so the `_params` read site in `_parse` sees one object shape rather than two.\nfunction finalizeParams(callee, params) {\n return { callee: params?.callee ?? callee, Err: params?.Err };\n}\nexport const _parse = (_Err) => {\n const fn = (schema, value, _ctx, _params) => {\n const ctx = _ctx ? { ..._ctx, async: false } : { async: false };\n const result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n if (result.issues.length) {\n const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));\n util.captureStackTrace(e, _params?.callee ?? fn);\n throw e;\n }\n return result.value;\n };\n return fn;\n};\nexport const parse = /* @__PURE__*/ _parse(errors.$ZodRealError);\nexport const _parseAsync = (_Err) => {\n const fn = async (schema, value, _ctx, params) => {\n const ctx = _ctx ? { ..._ctx, async: true } : { async: true };\n let result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise)\n result = await result;\n if (result.issues.length) {\n const e = new (params?.Err ?? _Err)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));\n util.captureStackTrace(e, params?.callee ?? fn);\n throw e;\n }\n return result.value;\n };\n return fn;\n};\nexport const parseAsync = /* @__PURE__*/ _parseAsync(errors.$ZodRealError);\nexport const _safeParse = (_Err) => (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, async: false } : { async: false };\n const result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n return result.issues.length ? failure(_Err, result.issues, ctx) : { success: true, data: result.value };\n};\nexport const safeParse = /* @__PURE__*/ _safeParse(errors.$ZodRealError);\n// the error is built on the first read of `error`: finalizing the issues and constructing the instance is most of a failing parse, and a caller that only branches on `success` never pays it. a getter in the literal keeps this small; the alternative, one shared accessor descriptor plus a hidden state slot, reads ~15% faster but costs ~75 B gzipped in every bundle\nfunction failure(Err, issues, ctx) {\n let error;\n return {\n success: false,\n get error() {\n if (!error) {\n error = new Err(issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));\n // finalizeIssue drops `input`, so the built error holds nothing; keeping the raw issues past this point pins the parsed value for the life of the result\n issues = undefined;\n ctx = undefined;\n }\n return error;\n },\n set error(e) {\n error = e;\n // a replacement makes the getter's branch unreachable, so the captures have to go here too\n issues = undefined;\n ctx = undefined;\n },\n };\n}\nexport const _safeParseAsync = (_Err) => async (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, async: true } : { async: true };\n let result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise)\n result = await result;\n return result.issues.length ? failure(_Err, result.issues, ctx) : { success: true, data: result.value };\n};\nexport const safeParseAsync = /* @__PURE__*/ _safeParseAsync(errors.$ZodRealError);\n// registry mirrors of the compiler's sentinels, so this module never imports the compiler\nconst COMPILE_INVALID = /* @__PURE__ */ Symbol.for(\"zod.compile.invalid\");\nconst COMPILE_FALLBACK = /* @__PURE__ */ Symbol.for(\"zod.compile.fallback\");\n// Deliberately tiny, because v8 will not inline a body carrying the fallback's object literals and throw. Everything that is not the compiled happy path lives in validateFallback, and that split is worth ~35% on a compiled schema.\nexport const validate = ((schema, value, _ctx) => {\n const validator = schema._zod.bag.validator;\n if (validator !== undefined) {\n if (validator(value) !== COMPILE_INVALID)\n return true;\n // a definite sentinel means the runtime would reject, so skip the re-parse; a ctx can still change the answer\n if (validator.definite === true && _ctx === undefined)\n return false;\n }\n return validateFallback(schema, value, _ctx);\n});\nfunction validateFallback(schema, value, _ctx) {\n const ctx = _ctx\n ? { ..._ctx, async: false, abortEarly: true }\n : { async: false, abortEarly: true };\n const fallbackRun = schema._zod.bag.fallbackRun;\n let result;\n if (fallbackRun) {\n // skip nested fast paths on the fallback, so user callbacks keep the at-most-twice bound\n ctx[COMPILE_FALLBACK] = true;\n result = fallbackRun({ value, issues: [] }, ctx);\n }\n else {\n result = schema._zod.run({ value, issues: [] }, ctx);\n }\n if (result instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n return result.issues.length === 0;\n}\n// no fast path: the compiler keeps async parses on the runtime, because a promise-returning callback that is not declared async compiles to a throw\nexport const validateAsync = async (schema, value, _ctx) => {\n const ctx = _ctx\n ? { ..._ctx, async: true, abortEarly: true }\n : { async: true, abortEarly: true };\n let result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise)\n result = await result;\n return result.issues.length === 0;\n};\nexport const _encode = (_Err) => {\n const parse = _parse(_Err);\n const fn = (schema, value, _ctx, _params) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return parse(schema, value, ctx, finalizeParams(fn, _params));\n };\n return fn;\n};\nexport const encode = /* @__PURE__*/ _encode(errors.$ZodRealError);\nexport const _decode = (_Err) => {\n const parse = _parse(_Err);\n const fn = (schema, value, _ctx, _params) => {\n return parse(schema, value, _ctx, finalizeParams(fn, _params));\n };\n return fn;\n};\nexport const decode = /* @__PURE__*/ _decode(errors.$ZodRealError);\nexport const _encodeAsync = (_Err) => {\n const parseAsync = _parseAsync(_Err);\n const fn = async (schema, value, _ctx, _params) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return (await parseAsync(schema, value, ctx, finalizeParams(fn, _params)));\n };\n return fn;\n};\nexport const encodeAsync = /* @__PURE__*/ _encodeAsync(errors.$ZodRealError);\nexport const _decodeAsync = (_Err) => {\n const parseAsync = _parseAsync(_Err);\n const fn = async (schema, value, _ctx, _params) => {\n return await parseAsync(schema, value, _ctx, finalizeParams(fn, _params));\n };\n return fn;\n};\nexport const decodeAsync = /* @__PURE__*/ _decodeAsync(errors.$ZodRealError);\nexport const _safeEncode = (_Err) => (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return _safeParse(_Err)(schema, value, ctx);\n};\nexport const safeEncode = /* @__PURE__*/ _safeEncode(errors.$ZodRealError);\nexport const _safeDecode = (_Err) => (schema, value, _ctx) => {\n return _safeParse(_Err)(schema, value, _ctx);\n};\nexport const safeDecode = /* @__PURE__*/ _safeDecode(errors.$ZodRealError);\nexport const _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return _safeParseAsync(_Err)(schema, value, ctx);\n};\nexport const safeEncodeAsync = /* @__PURE__*/ _safeEncodeAsync(errors.$ZodRealError);\nexport const _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => {\n return _safeParseAsync(_Err)(schema, value, _ctx);\n};\nexport const safeDecodeAsync = /* @__PURE__*/ _safeDecodeAsync(errors.$ZodRealError);\n","import * as util from \"./util.js\";\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link cuid2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport const cuid = /^[cC][0-9a-z]{6,}$/;\nexport const cuid2 = /^[0-9a-z]+$/;\nexport const ulid = /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/;\nexport const xid = /^[0-9a-vA-V]{20}$/;\nexport const ksuid = /^[A-Za-z0-9]{27}$/;\nexport const nanoid = /^[a-zA-Z0-9_-]{21}$/;\nexport function nanoidOfLength(length) {\n return new RegExp(`^[a-zA-Z0-9_-]{${length}}$`);\n}\n/** ISO 8601-1 duration regex. Does not support the 8601-2 extensions like negative durations or fractional/negative components. */\nexport const duration = /^P(?:(\\d+W)|(?!.*W)(?=\\d|T\\d)(\\d+Y)?(\\d+M)?(\\d+D)?(T(?=\\d)(\\d+H)?(\\d+M)?(\\d+([.,]\\d+)?S)?)?)$/;\n/** Implements ISO 8601-2 extensions like explicit +- prefixes, mixing weeks with other units, and fractional/negative components. */\nexport const extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\\d+Y)|(?:[-+]?\\d+[.,]\\d+Y$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:(?:[-+]?\\d+W)|(?:[-+]?\\d+[.,]\\d+W$))?(?:(?:[-+]?\\d+D)|(?:[-+]?\\d+[.,]\\d+D$))?(?:T(?=[\\d+-])(?:(?:[-+]?\\d+H)|(?:[-+]?\\d+[.,]\\d+H$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:[-+]?\\d+(?:[.,]\\d+)?S)?)??$/;\n/** A regex for any UUID-like identifier: 8-4-4-4-12 hex pattern */\nexport const guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;\n/** Returns a regex for validating an RFC 9562/4122 UUID.\n *\n * @param version Optionally specify a version 1-8. If no version is specified, all versions are supported. */\nexport const uuid = (version) => {\n if (!version)\n return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;\n return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);\n};\nexport const uuid4 = /*@__PURE__*/ uuid(4);\nexport const uuid6 = /*@__PURE__*/ uuid(6);\nexport const uuid7 = /*@__PURE__*/ uuid(7);\n/** Practical email validation */\nexport const email = /^(?:[A-Za-z0-9_'+\\-]+\\.)*[A-Za-z0-9_'+\\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$/;\n/** Equivalent to the HTML5 input[type=email] validation implemented by browsers. Source: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email */\nexport const html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n/** The classic emailregex.com regex for RFC 5322-compliant emails */\nexport const rfc5322Email = /^(([^<>()\\[\\]\\\\.,;:\\s@\"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/;\n/** A loose regex that allows Unicode characters, enforces length limits, and that's about it. */\nexport const unicodeEmail = /^[^\\s@\"]{1,64}@[^\\s@]{1,255}$/u;\nexport const idnEmail = unicodeEmail;\nexport const browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression\n// Single character class, not an alternation: the two properties overlap (U+1F9B0-U+1F9B3), so `(A|B)+` backtracks exponentially on a failed match. The leading lookahead then demands one anchor — a pictograph, a regional indicator, or the enclosing keycap — because `\\p{Emoji_Component}` on its own covers ASCII digits, `#`, `*`, ZWJ, variation selectors and skin tone modifiers, none of which is an emoji without a base.\nconst _emoji = `^(?=[\\\\s\\\\S]*[\\\\p{Extended_Pictographic}\\\\p{Regional_Indicator}\\\\u20E3])[\\\\p{Extended_Pictographic}\\\\p{Emoji_Component}]+$`;\nexport function emoji() {\n return new RegExp(_emoji, \"u\");\n}\nexport const ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;\nexport const ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;\nexport const mac = (delimiter) => {\n const escapedDelim = util.escapeRegex(delimiter ?? \":\");\n return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`);\n};\nexport const cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\/([0-9]|[1-2][0-9]|3[0-2])$/;\nexport const cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;\n// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript\nexport const base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;\nexport const base64url = /^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/;\n// based on https://stackoverflow.com/questions/106179/regular-expression-to-match-dns-hostname-or-ip-address\n// export const hostname: RegExp = /^([a-zA-Z0-9-]+\\.)*[a-zA-Z0-9-]+$/;\nexport const hostname = /^(?=.{1,253}\\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\\.?$/;\nexport const domain = /^(?=.{1,253}$)([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,63}$/;\nexport const httpProtocol = /^https?$/;\n// https://blog.stevenlevithan.com/archives/validate-phone-number#r4-3 (regex sans spaces) E.164: leading digit must be 1-9; total digits (excluding '+') between 7-15\nexport const e164 = /^\\+[1-9]\\d{6,14}$/;\n// Credit card shape: 12–19 digits, optionally separated by single spaces or single hyphens. ISO/IEC 7812 caps the PAN at 19 digits; 12 is the shortest issued length (Maestro).\nexport const creditCard = /^\\d(?:[ -]?\\d){11,18}$/;\n// ISO 4217 alpha codes from the SIX list, regenerated by scripts/update-iso-4217.ts\nexport const currencyCode = /^(?:AED|AFN|ALL|AMD|AOA|ARS|AUD|AWG|AZN|BAM|BBD|BDT|BHD|BIF|BMD|BND|BOB|BOV|BRL|BSD|BTN|BWP|BYN|BZD|CAD|CDF|CHE|CHF|CHW|CLF|CLP|CNY|COP|COU|CRC|CUP|CVE|CZK|DJF|DKK|DOP|DZD|EGP|ERN|ETB|EUR|FJD|FKP|GBP|GEL|GHS|GIP|GMD|GNF|GTQ|GYD|HKD|HNL|HTG|HUF|IDR|ILS|INR|IQD|IRR|ISK|JMD|JOD|JPY|KES|KGS|KHR|KMF|KPW|KRW|KWD|KYD|KZT|LAK|LBP|LKR|LRD|LSL|LYD|MAD|MDL|MGA|MKD|MMK|MNT|MOP|MRU|MUR|MVR|MWK|MXN|MXV|MYR|MZN|NAD|NGN|NIO|NOK|NPR|NZD|OMR|PAB|PEN|PGK|PHP|PKR|PLN|PYG|QAR|RON|RSD|RUB|RWF|SAR|SBD|SCR|SDG|SEK|SGD|SHP|SLE|SOS|SRD|SSP|STN|SVC|SYP|SZL|THB|TJS|TMT|TND|TOP|TRY|TTD|TWD|TZS|UAH|UGX|USD|USN|UYI|UYU|UYW|UZS|VED|VES|VND|VUV|WST|XAD|XAF|XAG|XAU|XBA|XBB|XBC|XBD|XCD|XCG|XDR|XOF|XPD|XPF|XPT|XSU|XTS|XUA|XXX|YER|ZAR|ZMW|ZWG)$/;\n// iban electronic format: 2-letter country, check digits 02-98 (the only values `98 - remainder` can produce), 11-30 bban characters\nexport const iban = /^[A-Z]{2}(?!00|01|99)\\d{2}[A-Z0-9]{11,30}$/;\nconst dateSource = `(?:(?:\\\\d\\\\d[2468][048]|\\\\d\\\\d[13579][26]|\\\\d\\\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\\\d|30)|(?:02)-(?:0[1-9]|1\\\\d|2[0-8])))`;\n/** Anchors a pattern source. The interpolation lives here rather than at the call site because\n * esbuild will not drop a `@__PURE__` call whose own argument interpolates a variable, but it\n * will drop `anchor(dateSource)`. Keeping it inline pinned `date` into every bundle. */\nfunction anchor(source) {\n return new RegExp(`^${source}$`);\n}\nexport const date = /*@__PURE__*/ anchor(dateSource);\nfunction timeSource(args) {\n const hhmm = `(?:[01]\\\\d|2[0-3]):[0-5]\\\\d`;\n const regex = typeof args.precision === \"number\"\n ? args.precision === -1\n ? `${hhmm}`\n : args.precision === 0\n ? `${hhmm}:[0-5]\\\\d`\n : `${hhmm}:[0-5]\\\\d\\\\.\\\\d{${args.precision}}`\n : args.seconds\n ? `${hhmm}:[0-5]\\\\d(?:\\\\.\\\\d+)?`\n : `${hhmm}(?::[0-5]\\\\d(?:\\\\.\\\\d+)?)?`;\n return regex;\n}\nexport function time(args) {\n return new RegExp(`^${timeSource(args)}$`);\n}\n// Adapted from https://stackoverflow.com/a/3143231\nexport function datetime(args) {\n const opts = [\"Z\"];\n // if (args.offset) opts.push(`([+-]\\\\d{2}:\\\\d{2})`);\n if (args.offset)\n opts.push(`([+-](?:[01]\\\\d|2[0-3]):[0-5]\\\\d)`);\n // RFC 3339 mandates seconds wherever the time carries a `Z` or an offset, so only the unqualified form `local` adds may omit them\n const qualified = `${timeSource({ precision: args.precision, seconds: true })}(?:${opts.join(\"|\")})`;\n const timeRegex = args.local ? `${qualified}|${timeSource({ precision: args.precision })}` : qualified;\n return new RegExp(`^${dateSource}T(?:${timeRegex})$`);\n}\n// the unbounded form of `string()` as a literal, so every plain string shares one instance instead of building its own\nexport const anyString = /^[\\s\\S]{0,}$/;\nexport const string = (params) => {\n const regex = params ? `[\\\\s\\\\S]{${params?.minimum ?? 0},${params?.maximum ?? \"\"}}` : `[\\\\s\\\\S]*`;\n return new RegExp(`^${regex}$`);\n};\nexport const bigint = /^-?\\d+n?$/;\nexport const integer = /^-?\\d+$/;\nexport const number = /^-?\\d+(?:\\.\\d+)?$/;\nexport const boolean = /^(?:true|false)$/i;\nconst _null = /^null$/i;\nexport { _null as null };\nconst _undefined = /^undefined$/i;\nexport { _undefined as undefined };\n// regex for string with no uppercase letters\nexport const lowercase = /^[^A-Z]*$/;\n// regex for string with no lowercase letters\nexport const uppercase = /^[^a-z]*$/;\n// regex for hexadecimal strings (any length)\nexport const hex = /^[0-9a-fA-F]*$/;\n// Hash regexes for different algorithms and encodings\n// Helper function to create base64 regex with exact length and padding\nfunction fixedBase64(bodyLength, padding) {\n return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`);\n}\n// Helper function to create base64url regex with exact length (no padding)\nfunction fixedBase64url(length) {\n return new RegExp(`^[A-Za-z0-9_-]{${length}}$`);\n}\n// MD5 (16 bytes): base64 = 24 chars total (22 + \"==\")\nexport const md5_hex = /^[0-9a-fA-F]{32}$/;\nexport const md5_base64 = /*@__PURE__*/ fixedBase64(22, \"==\");\nexport const md5_base64url = /*@__PURE__*/ fixedBase64url(22);\n// SHA1 (20 bytes): base64 = 28 chars total (27 + \"=\")\nexport const sha1_hex = /^[0-9a-fA-F]{40}$/;\nexport const sha1_base64 = /*@__PURE__*/ fixedBase64(27, \"=\");\nexport const sha1_base64url = /*@__PURE__*/ fixedBase64url(27);\n// SHA256 (32 bytes): base64 = 44 chars total (43 + \"=\")\nexport const sha256_hex = /^[0-9a-fA-F]{64}$/;\nexport const sha256_base64 = /*@__PURE__*/ fixedBase64(43, \"=\");\nexport const sha256_base64url = /*@__PURE__*/ fixedBase64url(43);\n// SHA384 (48 bytes): base64 = 64 chars total (no padding)\nexport const sha384_hex = /^[0-9a-fA-F]{96}$/;\nexport const sha384_base64 = /*@__PURE__*/ fixedBase64(64, \"\");\nexport const sha384_base64url = /*@__PURE__*/ fixedBase64url(64);\n// SHA512 (64 bytes): base64 = 88 chars total (86 + \"==\")\nexport const sha512_hex = /^[0-9a-fA-F]{128}$/;\nexport const sha512_base64 = /*@__PURE__*/ fixedBase64(86, \"==\");\nexport const sha512_base64url = /*@__PURE__*/ fixedBase64url(86);\n","// import { $ZodType } from \"./schemas.js\";\nimport * as core from \"./core.js\";\nimport * as regexes from \"./regexes.js\";\nimport * as util from \"./util.js\";\nexport const $ZodCheck = /*@__PURE__*/ core.$constructor(\"$ZodCheck\", (inst, def) => {\n var _a;\n inst._zod ?? (inst._zod = {});\n inst._zod.def = def;\n (_a = inst._zod).onattach ?? (_a.onattach = []);\n});\n/** Default `when` for size-based checks: run only on non-nullish values with a `size`. */\nconst _whenHasSize = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.size !== undefined;\n};\n/** Default `when` for length-based checks: run only on non-nullish values with a `length`. */\nconst _whenHasLength = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.length !== undefined;\n};\nconst numericOriginMap = {\n number: \"number\",\n bigint: \"bigint\",\n object: \"date\",\n};\nexport const $ZodCheckLessThan = /*@__PURE__*/ core.$constructor(\"$ZodCheckLessThan\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const origin = numericOriginMap[typeof def.value];\n inst._zod.check = (payload) => {\n if (def.inclusive ? payload.value <= def.value : payload.value < def.value) {\n return;\n }\n payload.issues.push({\n origin: numericOriginMap[typeof payload.value] ?? origin,\n code: \"too_big\",\n maximum: typeof def.value === \"object\" ? def.value.getTime() : def.value,\n input: payload.value,\n inclusive: def.inclusive,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckGreaterThan = /*@__PURE__*/ core.$constructor(\"$ZodCheckGreaterThan\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const origin = numericOriginMap[typeof def.value];\n inst._zod.check = (payload) => {\n if (def.inclusive ? payload.value >= def.value : payload.value > def.value) {\n return;\n }\n payload.issues.push({\n origin: numericOriginMap[typeof payload.value] ?? origin,\n code: \"too_small\",\n minimum: typeof def.value === \"object\" ? def.value.getTime() : def.value,\n input: payload.value,\n inclusive: def.inclusive,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMultipleOf = \n/*@__PURE__*/ core.$constructor(\"$ZodCheckMultipleOf\", (inst, def) => {\n $ZodCheck.init(inst, def);\n inst._zod.check = (payload) => {\n if (typeof payload.value !== typeof def.value)\n throw new Error(\"Cannot mix number and bigint in multiple_of check.\");\n const isMultiple = typeof payload.value === \"bigint\"\n ? // `value % 0n` throws, and nothing is a multiple of zero — the number branch already fails this way via NaN\n def.value !== BigInt(0) && payload.value % def.value === BigInt(0)\n : util.floatSafeRemainder(payload.value, def.value) === 0;\n if (isMultiple)\n return;\n payload.issues.push({\n origin: typeof payload.value,\n code: \"not_multiple_of\",\n divisor: def.value,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckNumberFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckNumberFormat\", (inst, def) => {\n $ZodCheck.init(inst, def); // no format checks\n def.format = def.format || \"float64\";\n const isInt = def.format?.includes(\"int\");\n const origin = isInt ? \"int\" : \"number\";\n const [minimum, maximum] = util.NUMBER_FORMAT_RANGES[def.format];\n inst._zod.check = (payload) => {\n const input = payload.value;\n if (isInt) {\n if (!Number.isInteger(input)) {\n // invalid_format issue\n // payload.issues.push({\n // expected: def.format,\n // format: def.format,\n // code: \"invalid_format\",\n // input,\n // inst,\n // });\n // invalid_type issue\n payload.issues.push({\n expected: origin,\n format: def.format,\n code: \"invalid_type\",\n continue: false,\n input,\n inst,\n });\n return;\n // not_multiple_of issue\n // payload.issues.push({\n // code: \"not_multiple_of\",\n // origin: \"number\",\n // input,\n // inst,\n // divisor: 1,\n // });\n }\n if (!Number.isSafeInteger(input)) {\n if (input > 0) {\n // too_big\n payload.issues.push({\n input,\n code: \"too_big\",\n maximum: Number.MAX_SAFE_INTEGER,\n note: \"Integers must be within the safe integer range.\",\n inst,\n origin,\n inclusive: true,\n continue: !def.abort,\n });\n }\n else {\n // too_small\n payload.issues.push({\n input,\n code: \"too_small\",\n minimum: Number.MIN_SAFE_INTEGER,\n note: \"Integers must be within the safe integer range.\",\n inst,\n origin,\n inclusive: true,\n continue: !def.abort,\n });\n }\n return;\n }\n }\n if (input < minimum) {\n payload.issues.push({\n origin: \"number\",\n input,\n code: \"too_small\",\n minimum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n if (input > maximum) {\n payload.issues.push({\n origin: \"number\",\n input,\n code: \"too_big\",\n maximum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodCheckBigIntFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckBigIntFormat\", (inst, def) => {\n $ZodCheck.init(inst, def); // no format checks\n const [minimum, maximum] = util.BIGINT_FORMAT_RANGES[def.format];\n inst._zod.check = (payload) => {\n const input = payload.value;\n if (input < minimum) {\n payload.issues.push({\n origin: \"bigint\",\n input,\n code: \"too_small\",\n minimum: minimum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n if (input > maximum) {\n payload.issues.push({\n origin: \"bigint\",\n input,\n code: \"too_big\",\n maximum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodCheckMaxSize = /*@__PURE__*/ core.$constructor(\"$ZodCheckMaxSize\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = _whenHasSize);\n inst._zod.check = (payload) => {\n const input = payload.value;\n const size = input.size;\n if (size <= def.maximum)\n return;\n payload.issues.push({\n origin: util.getSizableOrigin(input),\n code: \"too_big\",\n maximum: def.maximum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMinSize = /*@__PURE__*/ core.$constructor(\"$ZodCheckMinSize\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = _whenHasSize);\n inst._zod.check = (payload) => {\n const input = payload.value;\n const size = input.size;\n if (size >= def.minimum)\n return;\n payload.issues.push({\n origin: util.getSizableOrigin(input),\n code: \"too_small\",\n minimum: def.minimum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckSizeEquals = /*@__PURE__*/ core.$constructor(\"$ZodCheckSizeEquals\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = _whenHasSize);\n inst._zod.check = (payload) => {\n const input = payload.value;\n const size = input.size;\n if (size === def.size)\n return;\n const tooBig = size > def.size;\n payload.issues.push({\n origin: util.getSizableOrigin(input),\n ...(tooBig ? { code: \"too_big\", maximum: def.size } : { code: \"too_small\", minimum: def.size }),\n inclusive: true,\n exact: true,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMaxLength = /*@__PURE__*/ core.$constructor(\"$ZodCheckMaxLength\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = _whenHasLength);\n inst._zod.check = (payload) => {\n const input = payload.value;\n const units = input.length;\n // Strings are measured in Unicode code points, not UTF-16 units. A code point is at most two units, so a string that already fits in units fits in code points; only an overflow has to be counted.\n const length = typeof input === \"string\" && units > def.maximum ? util.codePointLength(input) : units;\n if (length <= def.maximum)\n return;\n const origin = util.getLengthableOrigin(input);\n payload.issues.push({\n origin,\n code: \"too_big\",\n maximum: def.maximum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMinLength = /*@__PURE__*/ core.$constructor(\"$ZodCheckMinLength\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = _whenHasLength);\n inst._zod.check = (payload) => {\n const input = payload.value;\n const units = input.length;\n // A code point is one or two UTF-16 units, so fewer units than the floor can never reach it and twice the floor always clears it. Only in between is the exact count in doubt.\n const length = typeof input === \"string\" && units >= def.minimum && units < def.minimum * 2\n ? util.codePointLength(input)\n : units;\n if (length >= def.minimum)\n return;\n const origin = util.getLengthableOrigin(input);\n payload.issues.push({\n origin,\n code: \"too_small\",\n minimum: def.minimum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckLengthEquals = /*@__PURE__*/ core.$constructor(\"$ZodCheckLengthEquals\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = _whenHasLength);\n inst._zod.check = (payload) => {\n const input = payload.value;\n const units = input.length;\n // A code point is one or two UTF-16 units, so outside `[length, length * 2]` units the target is missed either way — and missed in the same direction in both measures.\n const length = typeof input === \"string\" && units >= def.length && units <= def.length * 2\n ? util.codePointLength(input)\n : units;\n if (length === def.length)\n return;\n const origin = util.getLengthableOrigin(input);\n const tooBig = length > def.length;\n payload.issues.push({\n origin,\n ...(tooBig ? { code: \"too_big\", maximum: def.length } : { code: \"too_small\", minimum: def.length }),\n inclusive: true,\n exact: true,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckStringFormat\", (inst, def) => {\n var _a, _b;\n $ZodCheck.init(inst, def);\n if (def.pattern)\n (_a = inst._zod).check ?? (_a.check = (payload) => {\n def.pattern.lastIndex = 0;\n if (def.pattern.test(payload.value))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: def.format,\n input: payload.value,\n ...(def.pattern ? { pattern: def.pattern.toString() } : {}),\n inst,\n continue: !def.abort,\n });\n });\n else\n (_b = inst._zod).check ?? (_b.check = () => { });\n});\nexport const $ZodCheckRegex = /*@__PURE__*/ core.$constructor(\"$ZodCheckRegex\", (inst, def) => {\n $ZodCheckStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n def.pattern.lastIndex = 0;\n if (def.pattern.test(payload.value))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"regex\",\n input: payload.value,\n pattern: def.pattern.toString(),\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckLowerCase = /*@__PURE__*/ core.$constructor(\"$ZodCheckLowerCase\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.lowercase);\n $ZodCheckStringFormat.init(inst, def);\n});\nexport const $ZodCheckUpperCase = /*@__PURE__*/ core.$constructor(\"$ZodCheckUpperCase\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.uppercase);\n $ZodCheckStringFormat.init(inst, def);\n});\nexport const $ZodCheckIncludes = /*@__PURE__*/ core.$constructor(\"$ZodCheckIncludes\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const escapedRegex = util.escapeRegex(def.includes);\n // `String.prototype.includes(sub, position)` matches `sub` at `position`\n // OR LATER, so the pattern must allow at least `position` leading chars\n // (`{N,}`), not exactly `position` chars (`{N}`).\n const pattern = new RegExp(typeof def.position === \"number\" ? `^.{${def.position},}${escapedRegex}` : escapedRegex);\n def.pattern = pattern;\n inst._zod.check = (payload) => {\n if (payload.value.includes(def.includes, def.position))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"includes\",\n includes: def.includes,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckStartsWith = /*@__PURE__*/ core.$constructor(\"$ZodCheckStartsWith\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const pattern = new RegExp(`^${util.escapeRegex(def.prefix)}.*`);\n def.pattern ?? (def.pattern = pattern);\n inst._zod.check = (payload) => {\n if (payload.value.startsWith(def.prefix))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"starts_with\",\n prefix: def.prefix,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckEndsWith = /*@__PURE__*/ core.$constructor(\"$ZodCheckEndsWith\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const pattern = new RegExp(`.*${util.escapeRegex(def.suffix)}$`);\n def.pattern ?? (def.pattern = pattern);\n inst._zod.check = (payload) => {\n if (payload.value.endsWith(def.suffix))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"ends_with\",\n suffix: def.suffix,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\n///////////////////////////////////\n///// $ZodCheckProperty /////\n///////////////////////////////////\nfunction handleCheckPropertyResult(result, payload, property) {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(property, result.issues));\n }\n}\nexport const $ZodCheckProperty = /*@__PURE__*/ core.$constructor(\"$ZodCheckProperty\", (inst, def) => {\n $ZodCheck.init(inst, def);\n inst._zod.check = (payload) => {\n const result = def.schema._zod.run({\n value: payload.value[def.property],\n issues: [],\n }, {});\n if (result instanceof Promise) {\n return result.then((result) => handleCheckPropertyResult(result, payload, def.property));\n }\n handleCheckPropertyResult(result, payload, def.property);\n return;\n };\n});\nexport const $ZodCheckProperties = /*@__PURE__*/ core.$constructor(\"$ZodCheckProperties\", (inst, def) => {\n $ZodCheck.init(inst, def);\n util.hide(inst, Symbol.iterator, function* () {\n yield inst;\n });\n // key and schema snapshotted together: reading one live and the other cached lets a later mutation of the caller's shape object pair a stale key with a missing schema\n let entries;\n inst._zod.check = (payload) => {\n // the base schema already typed the value, so only a nullish one is rejected here: the properties read on a primitive too, matching z.property() on a string's length\n if (payload.value == null) {\n payload.issues.push({ expected: \"object\", code: \"invalid_type\", input: payload.value, inst });\n return undefined;\n }\n entries ?? (entries = Reflect.ownKeys(def.shape).map((key) => [key, def.shape[key]]));\n const input = payload.value;\n let proms;\n for (const [key, schema] of entries) {\n const result = schema._zod.run({ value: input[key], issues: [] }, {});\n if (result instanceof Promise) {\n proms ?? (proms = []);\n proms.push(result.then((result) => handleCheckPropertyResult(result, payload, key)));\n }\n else {\n handleCheckPropertyResult(result, payload, key);\n }\n }\n if (proms)\n return Promise.all(proms).then(() => undefined);\n return undefined;\n };\n});\nexport const $ZodCheckMimeType = /*@__PURE__*/ core.$constructor(\"$ZodCheckMimeType\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const mimeSet = new Set(def.mime);\n inst._zod.check = (payload) => {\n if (mimeSet.has(payload.value.type))\n return;\n payload.issues.push({\n code: \"invalid_value\",\n values: def.mime,\n input: payload.value.type,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckOverwrite = /*@__PURE__*/ core.$constructor(\"$ZodCheckOverwrite\", (inst, def) => {\n $ZodCheck.init(inst, def);\n inst._zod.check = (payload) => {\n payload.value = def.tx(payload.value);\n };\n});\n","export const version = {\n major: 4,\n minor: 6,\n patch: 5,\n};\n","import * as checks from \"./checks.js\";\nimport * as core from \"./core.js\";\nimport { Doc } from \"./doc.js\";\nimport { parse, parseAsync } from \"./parse.js\";\nimport * as regexes from \"./regexes.js\";\nimport * as util from \"./util.js\";\nimport { version } from \"./versions.js\";\nexport const $ZodType = /*@__PURE__*/ core.$constructor(\"$ZodType\", (inst, def) => {\n var _a;\n inst ?? (inst = {});\n inst._zod.def = def; // set _def property\n inst._zod.bag = inst._zod.bag || {}; // initialize _bag object\n inst._zod.version = version;\n const defChecks = inst._zod.def.checks;\n // if inst is itself a checks.$ZodCheck, run it as a check\n const checks = inst._zod.traits.has(\"$ZodCheck\")\n ? [inst, ...(defChecks ?? [])]\n : defChecks?.length\n ? [...defChecks]\n : [];\n for (const ch of checks) {\n for (const fn of ch._zod.onattach) {\n fn(inst);\n }\n }\n if (checks.length === 0) {\n // deferred initializer inst._zod.parse is not yet defined\n (_a = inst._zod).deferred ?? (_a.deferred = []);\n inst._zod.deferred?.push(() => {\n inst._zod.run = inst._zod.parse;\n });\n }\n else {\n const runChecks = (payload, checks, ctx) => {\n if (payload.memo)\n return payload;\n let isAborted = util.aborted(payload);\n let asyncResult;\n for (const ch of checks) {\n if (ch._zod.def.when) {\n if (util.explicitlyAborted(payload))\n continue;\n const shouldRun = ch._zod.def.when(payload);\n if (!shouldRun)\n continue;\n }\n else if (isAborted) {\n continue;\n }\n const currLen = payload.issues.length;\n const _ = ch._zod.check(payload);\n if (_ instanceof Promise && ctx?.async === false) {\n throw new core.$ZodAsyncError();\n }\n if (asyncResult || _ instanceof Promise) {\n asyncResult = (asyncResult ?? Promise.resolve()).then(async () => {\n await _;\n const nextLen = payload.issues.length;\n if (nextLen === currLen)\n return;\n util.attachSchema(payload.issues, currLen, inst);\n if (!isAborted)\n isAborted = util.aborted(payload, currLen);\n });\n }\n else {\n const nextLen = payload.issues.length;\n if (nextLen === currLen)\n continue;\n util.attachSchema(payload.issues, currLen, inst);\n if (!isAborted)\n isAborted = util.aborted(payload, currLen);\n }\n }\n if (asyncResult) {\n return asyncResult.then(() => {\n return payload;\n });\n }\n return payload;\n };\n const handleCanaryResult = (canary, payload, ctx) => {\n // abort if the canary is aborted\n if (util.aborted(canary)) {\n canary.aborted = true;\n return canary;\n }\n // run checks first, then\n const checkResult = runChecks(payload, checks, ctx);\n if (checkResult instanceof Promise) {\n if (ctx.async === false)\n throw new core.$ZodAsyncError();\n return checkResult.then((checkResult) => inst._zod.parse(checkResult, ctx));\n }\n return inst._zod.parse(checkResult, ctx);\n };\n inst._zod.run = (payload, ctx) => {\n if (ctx.skipChecks) {\n return inst._zod.parse(payload, ctx);\n }\n if (ctx.direction === \"backward\") {\n // run canary initial pass (no checks)\n const canary = inst._zod.parse({ value: payload.value, issues: [] }, { ...ctx, skipChecks: true });\n if (canary instanceof Promise) {\n return canary.then((canary) => {\n return handleCanaryResult(canary, payload, ctx);\n });\n }\n return handleCanaryResult(canary, payload, ctx);\n }\n // forward\n const result = inst._zod.parse(payload, ctx);\n if (result instanceof Promise) {\n if (ctx.async === false)\n throw new core.$ZodAsyncError();\n return result.then((result) => runChecks(result, checks, ctx));\n }\n return runChecks(result, checks, ctx);\n };\n }\n}, {\n // Wrappers extend this by installing a richer factory over it; reading it eagerly would defeat the laziness.\n get \"~standard\"() {\n return util.hide(this, \"~standard\", standardProps(this));\n },\n set \"~standard\"(value) {\n util.own(this, \"~standard\", value);\n },\n});\n/** The Standard Schema surface for `inst`. Shared so wrappers can extend it without forcing it. */\n// a Standard Schema result only reports issues, so a failure finalizes them straight off the raw payload: no ZodError, and no lazy result to read through\nconst toStandardResult = (r, ctx) => r.issues.length ? { issues: r.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())) } : { value: r.value };\nasync function validateAsync(inst, value) {\n const ctx = { async: true };\n return toStandardResult((await inst._zod.run({ value, issues: [] }, ctx)), ctx);\n}\nexport function standardProps(inst) {\n return {\n validate: (value) => {\n const ctx = { async: false };\n try {\n const r = inst._zod.run({ value, issues: [] }, ctx);\n if (!(r instanceof Promise))\n return toStandardResult(r, ctx);\n }\n catch (_) { }\n // async function so a synchronously throwing check rejects instead of escaping validate\n return validateAsync(inst, value);\n },\n vendor: \"zod\",\n version: 1,\n };\n}\nexport { clone } from \"./util.js\";\nexport const $ZodString = /*@__PURE__*/ core.$constructor(\"$ZodString\", (inst, def) => {\n $ZodType.init(inst, def);\n // a format's own pattern, else unbounded; a template literal derives the check-aware form itself\n inst._zod.pattern = def.pattern ?? regexes.anyString;\n inst._zod.parse = (payload, _) => {\n if (def.coerce)\n try {\n payload.value = String(payload.value);\n }\n catch (_) { }\n if (typeof payload.value === \"string\")\n return payload;\n payload.issues.push({\n expected: \"string\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodStringFormat\", (inst, def) => {\n // check initialization must come first\n checks.$ZodCheckStringFormat.init(inst, def);\n $ZodString.init(inst, def);\n});\nexport const $ZodGUID = /*@__PURE__*/ core.$constructor(\"$ZodGUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.guid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodUUID = /*@__PURE__*/ core.$constructor(\"$ZodUUID\", (inst, def) => {\n if (def.version) {\n const versionMap = {\n v1: 1,\n v2: 2,\n v3: 3,\n v4: 4,\n v5: 5,\n v6: 6,\n v7: 7,\n v8: 8,\n };\n const v = versionMap[def.version];\n if (v === undefined)\n throw new Error(`Invalid UUID version: \"${def.version}\"`);\n def.pattern ?? (def.pattern = regexes.uuid(v));\n }\n else\n def.pattern ?? (def.pattern = regexes.uuid());\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodEmail = /*@__PURE__*/ core.$constructor(\"$ZodEmail\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.email);\n $ZodStringFormat.init(inst, def);\n});\n/** The `://` guard rejected the input before the URL constructor saw it. */\nexport const URL_BAD_FORMAT = 1;\n/** The URL parser rejected the input. */\nexport const URL_UNPARSEABLE = 2;\nexport function canParseURL(input) {\n try {\n if (typeof URL !== \"undefined\" && typeof URL.canParse === \"function\")\n return URL.canParse(input);\n new URL(input);\n return true;\n }\n catch {\n return false;\n }\n}\nexport function validateURL(trimmed, def) {\n if (!(\"normalize\" in def) && !(\"hostname\" in def) && !(\"protocol\" in def)) {\n return canParseURL(trimmed) || URL_UNPARSEABLE;\n }\n return parseURLObject(trimmed, def);\n}\n/** Parses a URL while preserving the non-normalizing HTTP guard. */\nexport function parseURLObject(trimmed, def) {\n // When normalize is off, require :// for http/https URLs. This prevents strings like \"http:example.com\" or \"https:/path\" from being silently accepted\n if (!def.normalize && def.protocol?.source === regexes.httpProtocol.source && !/^https?:\\/\\//i.test(trimmed)) {\n return URL_BAD_FORMAT;\n }\n try {\n if (typeof URL !== \"undefined\") {\n const URLStatic = URL;\n if (typeof URLStatic.parse === \"function\")\n return URLStatic.parse(trimmed) ?? URL_UNPARSEABLE;\n }\n // @ts-ignore\n return new URL(trimmed);\n }\n catch {\n return URL_UNPARSEABLE;\n }\n}\nconst asciiTabOrNewline = /[\\t\\n\\r]/g;\n/** The URL parser deletes every ASCII tab, LF and CR from its input before it parses, so `new URL(\"https://exa\\nmple.com\")` reports on `example.com`. Applying the same deletion to the returned value closes the half of that divergence which can move the host; the parser's other rewrite, stripping C0 controls at the edges, cannot. */\nexport function stripTabAndNewline(value) {\n return value.replace(asciiTabOrNewline, \"\");\n}\nexport function urlHostnameOk(url, hostname) {\n hostname.lastIndex = 0;\n return hostname.test(url.hostname);\n}\nexport function urlProtocolOk(url, protocol) {\n protocol.lastIndex = 0;\n return protocol.test(url.protocol.endsWith(\":\") ? url.protocol.slice(0, -1) : url.protocol);\n}\nexport const $ZodURL = /*@__PURE__*/ core.$constructor(\"$ZodURL\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n try {\n // Trim whitespace from input\n const trimmed = payload.value.trim();\n const url = validateURL(trimmed, def);\n if (url === URL_BAD_FORMAT) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n note: \"Invalid URL format\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n return;\n }\n if (url === URL_UNPARSEABLE) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n return;\n }\n if (url === true) {\n payload.value = stripTabAndNewline(trimmed);\n return;\n }\n if (def.hostname && !urlHostnameOk(url, def.hostname)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n note: \"Invalid hostname\",\n pattern: def.hostname.source,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n if (def.protocol && !urlProtocolOk(url, def.protocol)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n note: \"Invalid protocol\",\n pattern: def.protocol.source,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n // Set the output value based on normalize flag\n payload.value = def.normalize ? url.href : stripTabAndNewline(trimmed);\n return;\n }\n catch (_) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodEmoji = /*@__PURE__*/ core.$constructor(\"$ZodEmoji\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.emoji());\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodNanoID = /*@__PURE__*/ core.$constructor(\"$ZodNanoID\", (inst, def) => {\n if (def.length !== undefined && (!Number.isInteger(def.length) || def.length < 1))\n throw new Error(`Invalid nanoid length: ${def.length}`);\n def.pattern ?? (def.pattern = def.length === undefined ? regexes.nanoid : regexes.nanoidOfLength(def.length));\n $ZodStringFormat.init(inst, def);\n});\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link $ZodCUID2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport const $ZodCUID = /*@__PURE__*/ core.$constructor(\"$ZodCUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cuid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodCUID2 = /*@__PURE__*/ core.$constructor(\"$ZodCUID2\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cuid2);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodULID = /*@__PURE__*/ core.$constructor(\"$ZodULID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ulid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodXID = /*@__PURE__*/ core.$constructor(\"$ZodXID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.xid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodKSUID = /*@__PURE__*/ core.$constructor(\"$ZodKSUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ksuid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODateTime = /*@__PURE__*/ core.$constructor(\"$ZodISODateTime\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.datetime(def));\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODate = /*@__PURE__*/ core.$constructor(\"$ZodISODate\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.date);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISOTime = /*@__PURE__*/ core.$constructor(\"$ZodISOTime\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.time(def));\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODuration = /*@__PURE__*/ core.$constructor(\"$ZodISODuration\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.duration);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodIPv4 = /*@__PURE__*/ core.$constructor(\"$ZodIPv4\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ipv4);\n $ZodStringFormat.init(inst, def);\n});\n/** An IPv6 address is written with hex digits, colons and dots, and nothing else. The guard is what makes the check below an IPv6 check: `new URL(\"http://[...]\")` parses an authority, not an address, so `@` and `\\` re-delimit it and `\"::@1\\\\\"` validates against the host `0.0.0.1`. The URL parser also deletes ASCII tab, LF and CR rather than failing, which is how `\"::1\\n\"` validated as `::1`. */\nconst ipv6Alphabet = /^[0-9a-fA-F:.]+$/;\nexport function isValidIPv6(value) {\n if (!ipv6Alphabet.test(value))\n return false;\n return canParseURL(`http://[${value}]`);\n}\nexport const $ZodIPv6 = /*@__PURE__*/ core.$constructor(\"$ZodIPv6\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ipv6);\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (!isValidIPv6(payload.value)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"ipv6\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodMAC = /*@__PURE__*/ core.$constructor(\"$ZodMAC\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.mac(def.delimiter));\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodCIDRv4 = /*@__PURE__*/ core.$constructor(\"$ZodCIDRv4\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cidrv4);\n $ZodStringFormat.init(inst, def);\n});\nexport function isValidCIDRv6(value) {\n const parts = value.split(\"/\");\n if (parts.length !== 2)\n return false;\n const [address, prefix] = parts;\n if (!prefix)\n return false;\n const prefixNum = Number(prefix);\n if (`${prefixNum}` !== prefix)\n return false;\n if (prefixNum < 0 || prefixNum > 128)\n return false;\n return isValidIPv6(address);\n}\nexport const $ZodCIDRv6 = /*@__PURE__*/ core.$constructor(\"$ZodCIDRv6\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cidrv6); // not used for validation\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (!isValidCIDRv6(payload.value)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"cidrv6\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\n////////////////////////////// ZodBase64 //////////////////////////////\nexport function isValidBase64(data) {\n if (data === \"\")\n return true;\n // atob ignores whitespace, so reject it up front.\n if (/\\s/.test(data))\n return false;\n if (data.length % 4 !== 0)\n return false;\n try {\n // @ts-ignore\n atob(data);\n return true;\n }\n catch {\n return false;\n }\n}\n// lax on purpose: the quantified regexes.base64 overflows the regex stack on multi-MB input and its leading ^$| alternation leaks through template-literal composition; isValidBase64 enforces length and padding\nexport const base64Charset = /^[0-9a-zA-Z+/]*={0,2}$/;\nexport const $ZodBase64 = /*@__PURE__*/ core.$constructor(\"$ZodBase64\", (inst, def) => {\n def.pattern ?? (def.pattern = base64Charset);\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (isValidBase64(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"base64\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\n////////////////////////////// ZodBase64URL //////////////////////////////\n// lax on purpose: the quantified regexes.base64url overflows the regex stack on multi-MB input; isValidBase64 enforces length on the padded string\nexport const base64urlCharset = /^[A-Za-z0-9_-]*$/;\nexport function isValidBase64URL(data) {\n if (!base64urlCharset.test(data))\n return false;\n const base64 = data.replace(/[-_]/g, (c) => (c === \"-\" ? \"+\" : \"/\"));\n const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, \"=\");\n return isValidBase64(padded);\n}\nexport const $ZodBase64URL = /*@__PURE__*/ core.$constructor(\"$ZodBase64URL\", (inst, def) => {\n def.pattern ?? (def.pattern = base64urlCharset);\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (isValidBase64URL(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"base64url\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodE164 = /*@__PURE__*/ core.$constructor(\"$ZodE164\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.e164);\n $ZodStringFormat.init(inst, def);\n});\n////////////////////////////// ZodCreditCard //////////////////////////////\nconst CC_SANITIZE = /[- ]/g;\n/** Luhn checksum on a digit-only string. Adapted from valibot (MIT). */\nfunction isLuhnAlgo(digits) {\n let length = digits.length;\n let bit = 1;\n let sum = 0;\n while (length) {\n const value = digits.charCodeAt(--length) - 48;\n bit ^= 1;\n sum += bit ? [0, 2, 4, 6, 8, 1, 3, 5, 7, 9][value] : value;\n }\n return sum % 10 === 0;\n}\nexport function isValidCreditCard(input) {\n if (!regexes.creditCard.test(input))\n return false;\n return isLuhnAlgo(input.replace(CC_SANITIZE, \"\"));\n}\nexport const $ZodCreditCard = /*@__PURE__*/ core.$constructor(\"$ZodCreditCard\", (inst, def) => {\n // Shape only — the Luhn check below is not expressible as a pattern, so consumers of `pattern` (JSON Schema, template literals) get the length and separator rules alone.\n def.pattern ?? (def.pattern = regexes.creditCard);\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (isValidCreditCard(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"credit_card\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\n////////////////////////////// ZodIBAN //////////////////////////////\n// iso 7064 mod 97-10 checksum without BigInt\nfunction isIso7064Mod97(iban) {\n let remainder = 0;\n const len = iban.length;\n for (let i = 4; i < len; i++) {\n const code = iban.charCodeAt(i);\n remainder = (code >= 65 ? remainder * 100 + (code - 55) : remainder * 10 + (code - 48)) % 97;\n }\n for (let i = 0; i < 4; i++) {\n const code = iban.charCodeAt(i);\n remainder = (code >= 65 ? remainder * 100 + (code - 55) : remainder * 10 + (code - 48)) % 97;\n }\n return remainder === 1;\n}\nexport function isValidIBAN(input) {\n if (!regexes.iban.test(input))\n return false;\n return isIso7064Mod97(input);\n}\nexport const $ZodIBAN = /*@__PURE__*/ core.$constructor(\"$ZodIBAN\", (inst, def) => {\n // shape only — checksum is not expressible as a pattern\n def.pattern ?? (def.pattern = regexes.iban);\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (isValidIBAN(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"iban\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\n////////////////////////////// ZodJWT //////////////////////////////\nexport function isValidJWT(token, algorithm = null) {\n try {\n const tokensParts = token.split(\".\");\n if (tokensParts.length !== 3)\n return false;\n const [header] = tokensParts;\n if (!header)\n return false;\n // @ts-ignore\n const parsedHeader = JSON.parse(atob(header));\n if (\"typ\" in parsedHeader && parsedHeader?.typ !== \"JWT\")\n return false;\n if (!parsedHeader.alg)\n return false;\n if (algorithm && (!(\"alg\" in parsedHeader) || parsedHeader.alg !== algorithm))\n return false;\n return true;\n }\n catch {\n return false;\n }\n}\nexport const $ZodJWT = /*@__PURE__*/ core.$constructor(\"$ZodJWT\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (isValidJWT(payload.value, def.alg))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"jwt\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCustomStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodCustomStringFormat\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (def.fn(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: def.format,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodNumber = /*@__PURE__*/ core.$constructor(\"$ZodNumber\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.number;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = Number(payload.value);\n }\n catch (_) { }\n const input = payload.value;\n if (typeof input === \"number\" && !Number.isNaN(input) && Number.isFinite(input)) {\n return payload;\n }\n const received = typeof input === \"number\"\n ? Number.isNaN(input)\n ? \"NaN\"\n : !Number.isFinite(input)\n ? String(input)\n : undefined\n : undefined;\n payload.issues.push({\n expected: \"number\",\n code: \"invalid_type\",\n input,\n inst,\n ...(received ? { received } : {}),\n });\n return payload;\n };\n});\nexport const $ZodNumberFormat = /*@__PURE__*/ core.$constructor(\"$ZodNumberFormat\", (inst, def) => {\n checks.$ZodCheckNumberFormat.init(inst, def);\n $ZodNumber.init(inst, def); // no format checks\n});\nexport const $ZodBoolean = /*@__PURE__*/ core.$constructor(\"$ZodBoolean\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.boolean;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = Boolean(payload.value);\n }\n catch (_) { }\n const input = payload.value;\n if (typeof input === \"boolean\")\n return payload;\n payload.issues.push({\n expected: \"boolean\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodBigInt = /*@__PURE__*/ core.$constructor(\"$ZodBigInt\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.bigint;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = BigInt(payload.value);\n }\n catch (_) { }\n if (typeof payload.value === \"bigint\")\n return payload;\n payload.issues.push({\n expected: \"bigint\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodBigIntFormat = /*@__PURE__*/ core.$constructor(\"$ZodBigIntFormat\", (inst, def) => {\n checks.$ZodCheckBigIntFormat.init(inst, def);\n $ZodBigInt.init(inst, def); // no format checks\n});\nexport const $ZodSymbol = /*@__PURE__*/ core.$constructor(\"$ZodSymbol\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"symbol\")\n return payload;\n payload.issues.push({\n expected: \"symbol\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodUndefined = /*@__PURE__*/ core.$constructor(\"$ZodUndefined\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.undefined;\n inst._zod.values = new Set([undefined]);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"undefined\")\n return payload;\n payload.issues.push({\n expected: \"undefined\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodNull = /*@__PURE__*/ core.$constructor(\"$ZodNull\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.null;\n inst._zod.values = new Set([null]);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (input === null)\n return payload;\n payload.issues.push({\n expected: \"null\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodAny = /*@__PURE__*/ core.$constructor(\"$ZodAny\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload) => payload;\n});\nexport const $ZodUnknown = /*@__PURE__*/ core.$constructor(\"$ZodUnknown\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload) => payload;\n});\nexport const $ZodNever = /*@__PURE__*/ core.$constructor(\"$ZodNever\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n payload.issues.push({\n expected: \"never\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodVoid = /*@__PURE__*/ core.$constructor(\"$ZodVoid\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"undefined\")\n return payload;\n payload.issues.push({\n expected: \"void\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodDate = /*@__PURE__*/ core.$constructor(\"$ZodDate\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce) {\n try {\n payload.value = new Date(payload.value);\n }\n catch (_err) { }\n }\n const input = payload.value;\n const isDate = input instanceof Date;\n const isValidDate = isDate && !Number.isNaN(input.getTime());\n if (isValidDate)\n return payload;\n payload.issues.push({\n expected: \"date\",\n code: \"invalid_type\",\n input,\n ...(isDate ? { received: \"Invalid Date\" } : {}),\n inst,\n });\n return payload;\n };\n});\nfunction handleArrayResult(result, final, index) {\n if (result.issues.length) {\n final.issues.push(...util.prefixIssues(index, result.issues));\n }\n final.value[index] = result.value;\n}\nexport const $ZodArray = /*@__PURE__*/ core.$constructor(\"$ZodArray\", (inst, def) => {\n $ZodType.init(inst, def);\n const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!Array.isArray(input)) {\n payload.issues.push({\n expected: \"array\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n payload.value = memo ? memo.alloc(inst, payload, Array(input.length), ctx) : Array(input.length);\n const proms = [];\n const abortEarly = ctx?.abortEarly;\n for (let i = 0; i < input.length; i++) {\n const item = input[i];\n const result = def.element._zod.run({\n value: item,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => handleArrayResult(result, payload, i)));\n }\n else {\n handleArrayResult(result, payload, i);\n // the element's payload is authoritative here, since handleArrayResult forwards every issue; an object's is not, because it drops a failed absent optional\n if (abortEarly && result.issues.length !== 0 && util.aborted(result))\n break;\n }\n }\n if (proms.length) {\n return Promise.all(proms).then(() => payload);\n }\n return payload; //handleArrayResultsAsync(parseResults, final);\n };\n});\nfunction handlePropertyResult(result, final, key, input, optin, optout) {\n const isPresent = key in input;\n const isOptionalOut = optout === \"optional\";\n // The middle rung means \"absence permitted, nothing supplied in its place\", so an absent key contributes nothing — whatever the schema made of `undefined` is invented, not substituted. Only `optional` reaches this with a value: `defaulted` substitutes, and a schema that isn't optional-out has to keep the key.\n if (!isPresent && isOptionalOut && optin === \"optional\") {\n return;\n }\n if (result.issues.length) {\n // For optional-in/out schemas, ignore errors on absent keys.\n if (optin !== undefined && isOptionalOut && !isPresent) {\n return;\n }\n final.issues.push(...util.prefixIssues(key, result.issues));\n }\n if (!isPresent && optin === undefined) {\n if (!result.issues.length) {\n final.issues.push({\n code: \"invalid_type\",\n expected: \"nonoptional\",\n input: undefined,\n path: [key],\n });\n }\n return;\n }\n if (result.value === undefined) {\n if (isPresent || (optin === \"defaulted\" && !isOptionalOut)) {\n final.value[key] = undefined;\n }\n }\n else {\n final.value[key] = result.value;\n }\n}\n// one shared instance; a fresh [] per schema cost 56 bytes retained\nconst NO_SYMBOL_KEYS = [];\nfunction normalizeDef(def) {\n const keys = Object.keys(def.shape);\n const ownSymbols = Object.getOwnPropertySymbols(def.shape);\n const symbolKeys = ownSymbols.length ? ownSymbols : NO_SYMBOL_KEYS;\n // aliases `keys` when there are no symbols, so a string-only shape keeps one array\n const allKeys = symbolKeys.length ? [...keys, ...symbolKeys] : keys;\n for (const k of allKeys) {\n if (!def.shape?.[k]?._zod?.traits?.has(\"$ZodType\")) {\n throw new Error(`Invalid element at key \"${String(k)}\": expected a Zod schema`);\n }\n }\n const okeys = util.optionalKeys(def.shape);\n return {\n ...def,\n allKeys,\n symbolKeys,\n // string-only: handleCatchall matches it against `for...in`, which never yields a symbol\n keySet: new Set(keys),\n numKeys: keys.length,\n optionalKeys: new Set(okeys),\n };\n}\nfunction handleCatchall(proms, input, payload, ctx, def, inst, abortEarly) {\n const unrecognized = [];\n const keySet = def.keySet;\n const _catchall = def.catchall._zod;\n const t = _catchall.def.type;\n const optin = _catchall.optin;\n const optout = _catchall.optout;\n // starts at 0, not the current length: the shape phase already ran and may have aborted\n let seen = 0;\n for (const key in input) {\n if (abortEarly && payload.issues.length !== seen) {\n if (util.aborted(payload, seen))\n break;\n seen = payload.issues.length;\n }\n // Must precede the __proto__ branch: a declared key is not unrecognized, even though the shape loop deliberately strips __proto__ from the parsed output.\n if (keySet.has(key))\n continue;\n // Don't copy an undeclared __proto__ into the result; assignment to a plain {} would replace the result prototype. But in strict mode it is still an unknown key, so report it before skipping.\n if (key === \"__proto__\") {\n if (t === \"never\")\n unrecognized.push(key);\n continue;\n }\n if (t === \"never\") {\n unrecognized.push(key);\n continue;\n }\n const r = _catchall.run({ value: input[key], issues: [] }, ctx);\n if (r instanceof Promise) {\n proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, optin, optout)));\n }\n else {\n handlePropertyResult(r, payload, key, input, optin, optout);\n }\n }\n if (unrecognized.length) {\n payload.issues.push({\n code: \"unrecognized_keys\",\n keys: unrecognized,\n input,\n inst,\n // Describes the shape of the input, not the validity of the parsed value, so it never aborts. The parse still fails; the schema's own checks just get to run first, and an enclosing intersection can reconcile the key against a sibling operand.\n continue: true,\n });\n }\n if (!proms.length)\n return payload;\n return Promise.all(proms).then(() => {\n return payload;\n });\n}\nexport const $ZodObject = /*@__PURE__*/ core.$constructor(\"$ZodObject\", (inst, def) => {\n // requires cast because technically $ZodObject doesn't extend\n $ZodType.init(inst, def);\n const desc = Object.getOwnPropertyDescriptor(def, \"shape\");\n // a cloned def carries its source's accessor, which knows the shape it answers from; adopting that keeps the clone's keys readable without running it\n const sh = desc?.get ? desc.get.raw : (def.shape ?? {});\n if (sh) {\n // Freezes the shape on first read, so its getters resolve once and every later read sees the same schemas.\n const get = () => {\n const newSh = { ...sh };\n Object.defineProperty(def, \"shape\", { value: newSh });\n get.raw = newSh;\n return newSh;\n };\n get.raw = sh;\n Object.defineProperty(def, \"shape\", { get });\n }\n const _normalized = util.cached(() => normalizeDef(def));\n util.defineLazyInternal(inst, \"propValues\", (zod) => {\n const shape = zod.def.shape;\n const propValues = {};\n for (const key in shape) {\n const field = shape[key]._zod;\n if (field.values) {\n if (!Object.prototype.hasOwnProperty.call(propValues, key)) {\n util.assignProp(propValues, key, new Set());\n }\n for (const v of field.values)\n propValues[key].add(v);\n // An omittable slot reads back as undefined at a discriminator lookup, so it has to claim undefined: two options that can both omit the key are not discriminable on it.\n if (field.optin !== undefined)\n propValues[key].add(undefined);\n }\n }\n return propValues;\n });\n const isObject = util.isObject;\n const catchall = def.catchall;\n let value;\n const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\n inst._zod.parse = (payload, ctx) => {\n value ?? (value = _normalized.value);\n const input = payload.value;\n if (!isObject(input)) {\n payload.issues.push({\n expected: \"object\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {};\n const proms = [];\n const shape = value.shape;\n const abortEarly = ctx?.abortEarly;\n let seen = payload.issues.length;\n for (const key of value.allKeys) {\n if (abortEarly && payload.issues.length !== seen) {\n if (util.aborted(payload, seen))\n break;\n seen = payload.issues.length;\n }\n if (key === \"__proto__\")\n continue;\n const el = shape[key];\n const optin = el._zod.optin;\n const optout = el._zod.optout;\n const r = el._zod.run({ value: input[key], issues: [] }, ctx);\n if (r instanceof Promise) {\n proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, optin, optout)));\n }\n else {\n handlePropertyResult(r, payload, key, input, optin, optout);\n }\n }\n if (!catchall) {\n return proms.length ? Promise.all(proms).then(() => payload) : payload;\n }\n return handleCatchall(proms, input, payload, ctx, _normalized.value, inst, abortEarly === true);\n };\n});\nexport const $ZodObjectJIT = /*@__PURE__*/ core.$constructor(\"$ZodObjectJIT\", (inst, def) => {\n // requires cast because technically $ZodObject doesn't extend\n $ZodObject.init(inst, def);\n const superParse = inst._zod.parse;\n const _normalized = util.cached(() => normalizeDef(def));\n const memo = core.globalConfig.memoizer;\n const generateFastpass = (shape) => {\n const normalized = _normalized.value;\n const syms = normalized.symbolKeys;\n // a symbol has no source literal, so it is read as `syms[i]` off the closed-over scope\n const doc = new Doc([\"payload\", \"ctx\"], { shape, inst, memo, syms });\n const parseStr = (k) => `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;\n // prefixes in place, like util.prefixIssues. newResult must land before the early return: a catchall runs after this and would otherwise write onto the caller's input\n const prefixStr = (id, k) => `\n let ${id}_ab = false;\n for (let i = 0; i < ${id}.issues.length; i++) {\n const iss = ${id}.issues[i];\n iss.path = iss.path ? [${k}, ...iss.path] : [${k}];\n payload.issues.push(iss);\n if (iss.continue !== true) ${id}_ab = true;\n }\n if (${id}_ab && ctx && ctx.abortEarly) {\n payload.value = newResult;\n return payload;\n }`;\n doc.write(`const input = payload.value;`);\n const ids = Object.create(null);\n let counter = 0;\n for (const key of normalized.allKeys) {\n ids[key] = `key_${counter++}`;\n }\n // A: preserve key order {\n doc.write(memo ? `const newResult = memo.alloc(inst, payload, {}, ctx);` : `const newResult = {};`);\n for (const key of normalized.allKeys) {\n if (key === \"__proto__\")\n continue;\n const id = ids[key];\n const k = typeof key === \"symbol\" ? `syms[${syms.indexOf(key)}]` : util.esc(key);\n const isPresent = `${k} in input`;\n const schema = shape[key];\n const optin = schema?._zod?.optin;\n const isOptionalIn = optin !== undefined;\n const isOptionalOut = schema?._zod?.optout === \"optional\";\n doc.write(`const ${id} = ${parseStr(k)};`);\n if (isOptionalIn && isOptionalOut) {\n // For optional-in/out schemas, ignore errors on absent keys — and, like the interpreted path, drop the value produced alongside them. The middle rung goes further: it permits absence without supplying anything in its place, so an absent key contributes nothing at all.\n const assign = optin === \"optional\" ? `${id}_present` : `${id}.value !== undefined || ${id}_present`;\n doc.write(`\n const ${id}_present = ${isPresent};\n if (!${id}.issues.length || ${id}_present) {\n if (${id}.issues.length) {${prefixStr(id, k)}\n }\n\n if (${assign}) {\n newResult[${k}] = ${id}.value;\n }\n }\n\n `);\n }\n else if (!isOptionalIn) {\n doc.write(`\n const ${id}_present = ${isPresent};\n if (${id}.issues.length) {${prefixStr(id, k)}\n }\n if (!${id}_present && !${id}.issues.length) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"nonoptional\",\n input: undefined,\n path: [${k}]\n });\n if (ctx && ctx.abortEarly) {\n payload.value = newResult;\n return payload;\n }\n }\n\n if (${id}_present) {\n newResult[${k}] = ${id}.value;\n }\n\n `);\n }\n else {\n doc.write(`\n if (${id}.issues.length) {${prefixStr(id, k)}\n }\n `);\n if (optin === \"defaulted\") {\n doc.write(`newResult[${k}] = ${id}.value;`);\n }\n else {\n doc.write(`\n if (${id}.value !== undefined || ${isPresent}) {\n newResult[${k}] = ${id}.value;\n }\n `);\n }\n }\n }\n doc.write(`payload.value = newResult;`);\n doc.write(`return payload;`);\n // closing `shape` in is what pays: turbofan specializes the parser against that one shape object, so every `shape[k]._zod.run` folds to a known callee. as a parameter it stays a generic load and measures 13% slower even with the forwarding frame gone\n return doc.compile();\n };\n let fastpass;\n const isObject = util.isObject;\n const jit = !core.globalConfig.jitless;\n const allowsEval = util.allowsEval;\n const fastEnabled = jit && allowsEval.value; // && !def.catchall;\n const catchall = def.catchall;\n let value;\n inst._zod.parse = (payload, ctx) => {\n value ?? (value = _normalized.value);\n const input = payload.value;\n if (!isObject(input)) {\n payload.issues.push({\n expected: \"object\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) {\n // always synchronous\n if (!fastpass)\n fastpass = generateFastpass(def.shape);\n payload = fastpass(payload, ctx);\n if (!catchall)\n return payload;\n return handleCatchall([], input, payload, ctx, value, inst, ctx?.abortEarly === true);\n }\n return superParse(payload, ctx);\n };\n});\nfunction handleUnionResults(results, final, inst, ctx) {\n for (const result of results) {\n if (result.issues.length === 0) {\n final.value = result.value;\n return final;\n }\n }\n const nonaborted = results.filter((r) => !util.aborted(r));\n if (nonaborted.length === 1) {\n final.value = nonaborted[0].value;\n return nonaborted[0];\n }\n final.issues.push({\n code: \"invalid_union\",\n input: final.value,\n inst,\n errors: results.map((result) => result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n });\n return final;\n}\nexport const $ZodUnion = /*@__PURE__*/ core.$constructor(\"$ZodUnion\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.options.some((o) => o._zod.optin === \"defaulted\")\n ? \"defaulted\"\n : zod.def.options.some((o) => o._zod.optin !== undefined)\n ? \"optional\"\n : undefined);\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.options.some((o) => o._zod.optout === \"optional\") ? \"optional\" : undefined);\n util.defineLazyInternal(inst, \"values\", (zod) => {\n if (zod.def.options.every((o) => o._zod.values)) {\n return new Set(zod.def.options.flatMap((option) => Array.from(option._zod.values)));\n }\n return undefined;\n });\n util.defineLazyInternal(inst, \"pattern\", (zod) => {\n if (zod.def.options.every((o) => o._zod.pattern)) {\n const patterns = zod.def.options.map((o) => o._zod.pattern);\n return new RegExp(`^(${patterns.map((p) => util.cleanRegex(p.source)).join(\"|\")})$`);\n }\n return undefined;\n });\n const first = def.options.length === 1 ? def.options[0]._zod.run : null;\n inst._zod.parse = (payload, ctx) => {\n if (first) {\n return first(payload, ctx);\n }\n let async = false;\n const results = [];\n for (const option of def.options) {\n const result = option._zod.run({\n value: payload.value,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n results.push(result);\n async = true;\n }\n else {\n if (result.issues.length === 0)\n return result;\n results.push(result);\n }\n }\n if (!async)\n return handleUnionResults(results, payload, inst, ctx);\n return Promise.all(results).then((results) => {\n return handleUnionResults(results, payload, inst, ctx);\n });\n };\n});\nfunction handleExclusiveUnionResults(results, final, inst, ctx) {\n const matches = [];\n for (let i = 0; i < results.length; i++) {\n if (results[i].issues.length === 0)\n matches.push(i);\n }\n if (matches.length === 1) {\n final.value = results[matches[0]].value;\n return final;\n }\n if (matches.length === 0) {\n // No matches - same as regular union\n final.issues.push({\n code: \"invalid_union\",\n input: final.value,\n inst,\n errors: results.map((result) => result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n });\n }\n else {\n // Multiple matches - exclusive union failure\n final.issues.push({\n code: \"invalid_union\",\n input: final.value,\n inst,\n errors: [],\n inclusive: false,\n matches,\n });\n }\n return final;\n}\nexport const $ZodXor = /*@__PURE__*/ core.$constructor(\"$ZodXor\", (inst, def) => {\n $ZodUnion.init(inst, def);\n def.inclusive = false;\n const first = def.options.length === 1 ? def.options[0]._zod.run : null;\n inst._zod.parse = (payload, ctx) => {\n if (first) {\n return first(payload, ctx);\n }\n let async = false;\n const results = [];\n for (const option of def.options) {\n const result = option._zod.run({\n value: payload.value,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n results.push(result);\n async = true;\n }\n else {\n results.push(result);\n }\n }\n if (!async)\n return handleExclusiveUnionResults(results, payload, inst, ctx);\n return Promise.all(results).then((results) => {\n return handleExclusiveUnionResults(results, payload, inst, ctx);\n });\n };\n});\n/** Returns the option whose discriminator claims `value`, or throws if ambiguous. */\nexport function getDiscriminatedOption(union, value) {\n const internals = union._zod;\n let map = internals.bag.optionsMap;\n if (!map) {\n map = discriminatorMap(internals.def);\n internals.bag.optionsMap = map;\n }\n const option = map.get(value);\n if (option === null)\n throw new Error(`Ambiguous discriminator value \"${String(value)}\"`);\n return option;\n}\nfunction discriminatorMap(def) {\n const map = new Map();\n for (const option of def.options) {\n const values = option._zod.propValues?.[def.discriminator];\n if (!values || values.size === 0)\n throw new Error(`Invalid discriminated union option at index \"${def.options.indexOf(option)}\"`);\n for (const value of values) {\n if (map.has(value)) {\n if (value !== undefined)\n throw new Error(`Duplicate discriminator value \"${String(value)}\"`);\n // keep the collision marked so a later member cannot reclaim it\n map.set(value, null);\n }\n else {\n map.set(value, option);\n }\n }\n }\n return map;\n}\nexport const $ZodDiscriminatedUnion = \n/*@__PURE__*/\ncore.$constructor(\"$ZodDiscriminatedUnion\", (inst, def) => {\n def.inclusive = false;\n $ZodUnion.init(inst, def);\n const _super = inst._zod.parse;\n util.defineLazyInternal(inst, \"propValues\", (zod) => {\n const propValues = {};\n let undefinedCount = 0;\n for (const option of zod.def.options) {\n const pv = option._zod.propValues;\n if (!pv || Object.keys(pv).length === 0)\n throw new Error(`Invalid discriminated union option at index \"${zod.def.options.indexOf(option)}\"`);\n if (pv[zod.def.discriminator]?.has(undefined))\n undefinedCount++;\n for (const [k, v] of Object.entries(pv)) {\n if (!Object.prototype.hasOwnProperty.call(propValues, k)) {\n util.assignProp(propValues, k, new Set());\n }\n for (const val of v) {\n propValues[k].add(val);\n }\n }\n }\n if (!zod.def.unionFallback && undefinedCount > 1)\n propValues[zod.def.discriminator]?.delete(undefined);\n return propValues;\n });\n // Checked now rather than in the lookup map below, so an option that lacks the discriminator fails at the `discriminatedUnion` call instead of on the first object parsed. Options whose shape cannot be enumerated without resolving it — pipes and lazies — are left to the map.\n def.options.forEach((option, i) => {\n const propShape = util.rawShape(option._zod.def);\n if (propShape && !Object.prototype.hasOwnProperty.call(propShape, def.discriminator)) {\n throw new Error(`Invalid discriminated union option at index \"${i}\"`);\n }\n });\n const disc = util.cached(() => discriminatorMap(def));\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!util.isObject(input)) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"object\",\n input,\n inst,\n });\n return payload;\n }\n const value = input?.[def.discriminator];\n const opt = disc.value.get(value);\n // forward metadata cannot choose an encoder for an absent tag\n if (opt && (value !== undefined || ctx.direction !== \"backward\")) {\n return opt._zod.run(payload, ctx);\n }\n // Fall back to union matching when the fast discriminator path fails:\n // - explicitly enabled via unionFallback, or\n // - during backward direction (encode), since codec-based discriminators have different values in forward vs backward directions\n if (def.unionFallback || ctx.direction === \"backward\") {\n return _super(payload, ctx);\n }\n // no matching discriminator\n payload.issues.push({\n code: \"invalid_union\",\n errors: [],\n note: \"No matching discriminator\",\n discriminator: def.discriminator,\n options: Array.from(disc.value.keys()).filter((value) => disc.value.get(value) !== null),\n input,\n path: [def.discriminator],\n inst,\n });\n return payload;\n };\n});\nexport const $ZodIntersection = /*@__PURE__*/ core.$constructor(\"$ZodIntersection\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n const left = def.left._zod.run({ value: input, issues: [] }, ctx);\n const right = def.right._zod.run({ value: input, issues: [] }, ctx);\n const async = left instanceof Promise || right instanceof Promise;\n if (async) {\n return Promise.all([left, right]).then(([left, right]) => {\n return handleIntersectionResults(payload, left, right);\n });\n }\n return handleIntersectionResults(payload, left, right);\n };\n});\nexport function mergeValues(a, b) {\n // const aType = parse.t(a);\n // const bType = parse.t(b);\n if (a === b) {\n return { valid: true, data: a };\n }\n if (a instanceof Date && b instanceof Date && +a === +b) {\n return { valid: true, data: a };\n }\n if (util.isPlainObject(a) && util.isPlainObject(b)) {\n const bKeys = Object.keys(b);\n const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);\n const newObj = { ...a, ...b };\n if (Object.prototype.hasOwnProperty.call(newObj, \"__proto__\"))\n delete newObj.__proto__;\n for (const key of sharedKeys) {\n if (key === \"__proto__\")\n continue;\n const sharedValue = mergeValues(a[key], b[key]);\n if (!sharedValue.valid) {\n return {\n valid: false,\n mergeErrorPath: [key, ...sharedValue.mergeErrorPath],\n };\n }\n newObj[key] = sharedValue.data;\n }\n return { valid: true, data: newObj };\n }\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) {\n return { valid: false, mergeErrorPath: [] };\n }\n const newArray = [];\n for (let index = 0; index < a.length; index++) {\n const itemA = a[index];\n const itemB = b[index];\n const sharedValue = mergeValues(itemA, itemB);\n if (!sharedValue.valid) {\n return {\n valid: false,\n mergeErrorPath: [index, ...sharedValue.mergeErrorPath],\n };\n }\n newArray.push(sharedValue.data);\n }\n return { valid: true, data: newArray };\n }\n return { valid: false, mergeErrorPath: [] };\n}\nfunction handleIntersectionResults(result, left, right) {\n // Track which side(s) reject each key. A key rejection is reported only when BOTH sides reject it, so a key owned by one branch survives the other's key schema. strictObject reports these as unrecognized_keys; a record with an open key schema reports one invalid_key per key.\n const unrecKeys = new Map();\n let unrecIssue;\n const keyIssues = new Map();\n const collect = (iss, side) => {\n let keys;\n if (iss.code === \"unrecognized_keys\" && !iss.path?.length) {\n unrecIssue ?? (unrecIssue = iss);\n keys = iss.keys;\n }\n else if (iss.code === \"invalid_key\" && iss.origin === \"record\" && iss.path?.length === 1) {\n const k = String(iss.path[0]);\n if (!keyIssues.has(k))\n keyIssues.set(k, iss);\n keys = [k];\n }\n else {\n return false;\n }\n for (const k of keys) {\n if (!unrecKeys.has(k))\n unrecKeys.set(k, {});\n unrecKeys.get(k)[side] = true;\n }\n return true;\n };\n for (const iss of left.issues) {\n if (!collect(iss, \"l\"))\n result.issues.push(iss);\n }\n for (const iss of right.issues) {\n if (!collect(iss, \"r\"))\n result.issues.push(iss);\n }\n // Report only keys rejected by BOTH sides\n const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k);\n if (bothKeys.length) {\n const aggregated = unrecIssue ? bothKeys.filter((k) => unrecIssue.keys.includes(k)) : [];\n if (aggregated.length)\n result.issues.push({ ...unrecIssue, keys: aggregated });\n for (const k of bothKeys) {\n if (!aggregated.includes(k) && keyIssues.has(k))\n result.issues.push(keyIssues.get(k));\n }\n }\n const merged = mergeValues(left.value, right.value);\n if (!merged.valid) {\n if (util.aborted(result))\n return result;\n throw new Error(`Unmergable intersection. Error path: ` + `${JSON.stringify(merged.mergeErrorPath)}`);\n }\n result.value = merged.data;\n return result;\n}\nexport const $ZodTuple = /*@__PURE__*/ core.$constructor(\"$ZodTuple\", (inst, def) => {\n $ZodType.init(inst, def);\n const items = def.items;\n const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!Array.isArray(input)) {\n payload.issues.push({\n input,\n inst,\n expected: \"tuple\",\n code: \"invalid_type\",\n });\n return payload;\n }\n payload.value = memo ? memo.alloc(inst, payload, [], ctx) : [];\n const proms = [];\n const optinStart = getTupleOptStart(items, \"optin\");\n const optoutStart = getTupleOptStart(items, \"optout\");\n if (!def.rest) {\n if (input.length < optinStart) {\n payload.issues.push({\n code: \"too_small\",\n minimum: optinStart,\n inclusive: true,\n input,\n inst,\n origin: \"array\",\n });\n return payload;\n }\n if (input.length > items.length) {\n payload.issues.push({\n code: \"too_big\",\n maximum: items.length,\n inclusive: true,\n input,\n inst,\n origin: \"array\",\n });\n }\n }\n // Run every item in parallel, collecting results into an indexed array. The post-processing in `handleTupleResults` walks them in order so it can decide whether an absent optional-output error can truncate the tail or must be reported to preserve required output.\n const itemResults = new Array(items.length);\n // only tracked when there is a rest loop to skip\n const abortEarly = def.rest ? ctx?.abortEarly : undefined;\n let itemAborted = false;\n for (let i = 0; i < items.length; i++) {\n const r = items[i]._zod.run({ value: input[i], issues: [] }, ctx);\n if (r instanceof Promise) {\n proms.push(r.then((rr) => {\n itemResults[i] = rr;\n }));\n }\n else {\n itemResults[i] = r;\n if (abortEarly && !itemAborted && r.issues.length)\n itemAborted = util.aborted(r);\n }\n }\n // sound because rest is non-empty exactly when every fixed index is present, the one case handleTupleResults cannot discard an item's issues\n if (def.rest && !itemAborted) {\n let i = items.length - 1;\n const rest = input.slice(items.length);\n let seen = payload.issues.length;\n for (const el of rest) {\n if (abortEarly && payload.issues.length !== seen) {\n if (util.aborted(payload, seen))\n break;\n seen = payload.issues.length;\n }\n i++;\n const result = def.rest._zod.run({ value: el, issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((r) => handleTupleResult(r, payload, i)));\n }\n else {\n handleTupleResult(result, payload, i);\n }\n }\n }\n if (proms.length) {\n return Promise.all(proms).then(() => handleTupleResults(itemResults, payload, items, input, optoutStart));\n }\n return handleTupleResults(itemResults, payload, items, input, optoutStart);\n };\n});\nfunction getTupleOptStart(items, key) {\n for (let i = items.length - 1; i >= 0; i--) {\n // optin is a three-rung ladder so any rung above `undefined` permits an absent slot; optout stays two-valued.\n const omittable = key === \"optin\" ? items[i]._zod.optin !== undefined : items[i]._zod.optout === \"optional\";\n if (!omittable)\n return i + 1;\n }\n return 0;\n}\nfunction handleTupleResult(result, final, index) {\n if (result.issues.length) {\n final.issues.push(...util.prefixIssues(index, result.issues));\n }\n final.value[index] = result.value;\n}\nfunction handleTupleResults(itemResults, final, items, input, optoutStart) {\n // Walk results in order. Mirror $ZodObject's swallow-on-absent-optional rule, but only after `optoutStart`: the first index where the output tuple tail can be absent.\n for (let i = 0; i < items.length; i++) {\n const r = itemResults[i];\n const isPresent = i < input.length;\n // The array analog of `handlePropertyResult`'s absent-key early return: the middle rung permits absence without supplying anything in its place, so the tail truncates here instead of materializing whatever the item made of `undefined`.\n if (!isPresent && i >= optoutStart && items[i]._zod.optin === \"optional\") {\n final.value.length = i;\n break;\n }\n if (r.issues.length) {\n if (!isPresent && i >= optoutStart) {\n final.value.length = i;\n break;\n }\n final.issues.push(...util.prefixIssues(i, r.issues));\n }\n final.value[i] = r.value;\n }\n // Drop trailing slots that produced `undefined` for absent input\n // (the array analog of an absent optional key on an object). The\n // `i >= input.length` floor is critical: an explicit `undefined`\n // *inside* the input must be preserved even when the schema is\n // optional-out (e.g. `z.string().or(z.undefined())` accepting an\n // explicit undefined value).\n for (let i = final.value.length - 1; i >= input.length; i--) {\n if (items[i]._zod.optout === \"optional\" && final.value[i] === undefined) {\n final.value.length = i;\n }\n else {\n break;\n }\n }\n return final;\n}\nexport const $ZodRecord = /*@__PURE__*/ core.$constructor(\"$ZodRecord\", (inst, def) => {\n $ZodType.init(inst, def);\n const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!util.isPlainObject(input)) {\n payload.issues.push({\n expected: \"record\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n // no guard in either loop below: a record's invalid_key aborts but an enclosing intersection can reconcile it, so a stopped loop hides keys the sibling does not own and the intersection then rejects nothing\n const proms = [];\n const values = def.keyType._zod.values;\n if (values && !def.partial) {\n payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {};\n const recordKeys = new Set();\n for (const key of values) {\n if (typeof key === \"string\" || typeof key === \"number\" || typeof key === \"symbol\") {\n recordKeys.add(typeof key === \"number\" ? key.toString() : key);\n // A declared __proto__ is stripped but is not an unrecognized key.\n if (key === \"__proto__\")\n continue;\n const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n if (keyResult instanceof Promise) {\n throw new Error(\"Async schemas not supported in object keys currently\");\n }\n if (keyResult.issues.length) {\n payload.issues.push({\n code: \"invalid_key\",\n origin: \"record\",\n issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n input: key,\n path: [key],\n inst,\n });\n continue;\n }\n const outKey = keyResult.value;\n if (outKey === \"__proto__\")\n continue;\n const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[outKey] = result.value;\n }));\n }\n else {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[outKey] = result.value;\n }\n }\n }\n let unrecognized;\n for (const key in input) {\n if (!recordKeys.has(key)) {\n if (def.mode === \"loose\") {\n // skip __proto__ so it can't replace the result prototype via the assignment setter on the plain {} we build into\n if (key === \"__proto__\")\n continue;\n payload.value[key] = input[key];\n }\n else {\n unrecognized = unrecognized ?? [];\n unrecognized.push(key);\n }\n }\n }\n if (unrecognized && unrecognized.length > 0) {\n payload.issues.push({\n code: \"unrecognized_keys\",\n input,\n inst,\n keys: unrecognized,\n continue: true,\n });\n }\n }\n else {\n payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {};\n // An enumerable key schema declares which keys the record owns, so a key outside the set is unrecognized. A non-enumerable one (regex, refine) is a constraint every key must satisfy, so a failing key is invalid. Only the former is reconcilable against the other side of an intersection.\n let unrecognized;\n // Reflect.ownKeys for Symbol-key support; filter non-enumerable to match z.object()\n for (const key of Reflect.ownKeys(input)) {\n if (key === \"__proto__\")\n continue;\n if (!Object.prototype.propertyIsEnumerable.call(input, key))\n continue;\n let keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n if (keyResult instanceof Promise) {\n throw new Error(\"Async schemas not supported in object keys currently\");\n }\n // Numeric string fallback: if key is a numeric string and failed, retry with Number(key). This handles z.number(), z.literal([1, 2, 3]), and unions containing numeric literals\n const checkNumericKey = typeof key === \"string\" && regexes.number.test(key) && keyResult.issues.length;\n if (checkNumericKey) {\n const retryResult = def.keyType._zod.run({ value: Number(key), issues: [] }, ctx);\n if (retryResult instanceof Promise) {\n throw new Error(\"Async schemas not supported in object keys currently\");\n }\n if (retryResult.issues.length === 0) {\n keyResult = retryResult;\n }\n }\n if (keyResult.issues.length) {\n if (def.mode === \"loose\") {\n // Pass through unchanged\n payload.value[key] = input[key];\n }\n else if (values) {\n unrecognized = unrecognized ?? [];\n unrecognized.push(key);\n }\n else {\n // Default \"strict\" behavior: error on invalid key\n payload.issues.push({\n code: \"invalid_key\",\n origin: \"record\",\n issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n input: key,\n path: [key],\n inst,\n });\n }\n continue;\n }\n // the guard above tests the raw input key, but the key schema can normalize an ordinary key into __proto__; re-check the key we actually write under\n const outKey = keyResult.value;\n if (outKey === \"__proto__\")\n continue;\n const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[outKey] = result.value;\n }));\n }\n else {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[outKey] = result.value;\n }\n }\n if (unrecognized && unrecognized.length > 0) {\n payload.issues.push({\n code: \"unrecognized_keys\",\n input,\n inst,\n keys: unrecognized,\n continue: true,\n });\n }\n }\n if (proms.length) {\n return Promise.all(proms).then(() => payload);\n }\n return payload;\n };\n});\nexport const $ZodMap = /*@__PURE__*/ core.$constructor(\"$ZodMap\", (inst, def) => {\n $ZodType.init(inst, def);\n const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!(input instanceof Map)) {\n payload.issues.push({\n expected: \"map\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n const proms = [];\n payload.value = memo ? memo.alloc(inst, payload, new Map(), ctx) : new Map();\n const abortEarly = ctx?.abortEarly;\n let seen = payload.issues.length;\n for (const [key, value] of input) {\n if (abortEarly && payload.issues.length !== seen) {\n if (util.aborted(payload, seen))\n break;\n seen = payload.issues.length;\n }\n const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n const valueResult = def.valueType._zod.run({ value: value, issues: [] }, ctx);\n if (keyResult instanceof Promise || valueResult instanceof Promise) {\n proms.push(Promise.all([keyResult, valueResult]).then(([keyResult, valueResult]) => {\n handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx);\n }));\n }\n else {\n handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx);\n }\n }\n if (proms.length)\n return Promise.all(proms).then(() => payload);\n return payload;\n };\n});\nfunction handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) {\n if (keyResult.issues.length) {\n if (util.propertyKeyTypes.has(typeof key)) {\n final.issues.push(...util.prefixIssues(key, keyResult.issues));\n }\n else {\n final.issues.push({\n code: \"invalid_key\",\n origin: \"map\",\n input,\n inst,\n issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n });\n }\n }\n if (valueResult.issues.length) {\n if (util.propertyKeyTypes.has(typeof key)) {\n final.issues.push(...util.prefixIssues(key, valueResult.issues));\n }\n else {\n final.issues.push({\n origin: \"map\",\n code: \"invalid_element\",\n input,\n inst,\n key: key,\n issues: valueResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n });\n }\n }\n final.value.set(keyResult.value, valueResult.value);\n}\nexport const $ZodSet = /*@__PURE__*/ core.$constructor(\"$ZodSet\", (inst, def) => {\n $ZodType.init(inst, def);\n const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!(input instanceof Set)) {\n payload.issues.push({\n input,\n inst,\n expected: \"set\",\n code: \"invalid_type\",\n });\n return payload;\n }\n const proms = [];\n payload.value = memo ? memo.alloc(inst, payload, new Set(), ctx) : new Set();\n const abortEarly = ctx?.abortEarly;\n let seen = payload.issues.length;\n for (const item of input) {\n if (abortEarly && payload.issues.length !== seen) {\n if (util.aborted(payload, seen))\n break;\n seen = payload.issues.length;\n }\n const result = def.valueType._zod.run({ value: item, issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => handleSetResult(result, payload)));\n }\n else\n handleSetResult(result, payload);\n }\n if (proms.length)\n return Promise.all(proms).then(() => payload);\n return payload;\n };\n});\nfunction handleSetResult(result, final) {\n if (result.issues.length) {\n final.issues.push(...result.issues);\n }\n final.value.add(result.value);\n}\nexport const $ZodEnum = /*@__PURE__*/ core.$constructor(\"$ZodEnum\", (inst, def) => {\n $ZodType.init(inst, def);\n const values = util.getEnumValues(def.entries);\n const valuesSet = new Set(values);\n inst._zod.values = valuesSet;\n util.defineLazyInternal(inst, \"pattern\", (zod) => {\n const patternValues = util.getEnumValues(zod.def.entries).filter((k) => util.propertyKeyTypes.has(typeof k));\n // unmatchable fallback, RE2-safe: an empty alternation would compile to /^()$/, which matches \"\"\n return new RegExp(patternValues.length ? `^(${patternValues.map((o) => util.escapeRegex(o.toString())).join(\"|\")})$` : \"^[^\\\\s\\\\S]$\");\n });\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (valuesSet.has(input)) {\n return payload;\n }\n payload.issues.push({\n code: \"invalid_value\",\n values,\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodLiteral = /*@__PURE__*/ core.$constructor(\"$ZodLiteral\", (inst, def) => {\n $ZodType.init(inst, def);\n const values = new Set(def.values);\n inst._zod.values = values;\n util.defineLazyInternal(inst, \"pattern\", (zod) => {\n const vals = zod.def.values;\n // unmatchable fallback, RE2-safe: an empty alternation would compile to /^()$/, which matches \"\"\n return new RegExp(vals.length\n ? `^(${vals\n .map((o) => typeof o === \"string\" ? util.escapeRegex(o) : o ? util.escapeRegex(o.toString()) : String(o))\n .join(\"|\")})$`\n : \"^[^\\\\s\\\\S]$\");\n });\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (values.has(input)) {\n return payload;\n }\n payload.issues.push({\n code: \"invalid_value\",\n values: def.values,\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodFile = /*@__PURE__*/ core.$constructor(\"$ZodFile\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n // @ts-ignore\n if (input instanceof File)\n return payload;\n payload.issues.push({\n expected: \"file\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodTransform = /*@__PURE__*/ core.$constructor(\"$ZodTransform\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.optin = \"optional\";\n core.globalConfig.memoizer?.guard(inst);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n throw new core.$ZodEncodeError(inst.constructor.name);\n }\n const _out = def.transform(payload.value, payload);\n if (ctx.async) {\n const output = _out instanceof Promise ? _out : Promise.resolve(_out);\n return output.then((output) => {\n payload.value = output;\n return payload;\n });\n }\n if (_out instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n payload.value = _out;\n return payload;\n };\n});\nfunction handleOptionalResult(payload, result) {\n // A substituting schema that still failed has no usable answer; yield undefined. Its issues are simply dropped: it ran on a payload of its own, so there is no shared array to truncate and nothing of the caller's to lose with it.\n payload.value = result.issues.length ? undefined : result.value;\n return payload;\n}\nexport const $ZodOptional = /*@__PURE__*/ core.$constructor(\"$ZodOptional\", (inst, def) => {\n $ZodType.init(inst, def);\n // .optional() propagates absence rather than substituting for it, so a defaulted inner keeps its rung.\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.innerType._zod.optin === \"defaulted\" ? \"defaulted\" : \"optional\");\n inst._zod.optout = \"optional\";\n util.defineLazyInternal(inst, \"values\", (zod) => {\n const values = zod.def.innerType._zod.values;\n return values ? new Set([...values, undefined]) : undefined;\n });\n util.defineLazyInternal(inst, \"pattern\", (zod) => {\n const pattern = zod.def.innerType._zod.pattern;\n return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)})?$`) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n if (payload.value === undefined) {\n // Only the top rung substitutes a value for absence; everything else leaves it intact, which is what .optional() means.\n if (def.innerType._zod.optin !== \"defaulted\")\n return payload;\n // Its own payload, for the same reason $ZodCatch gets one: a pipe forwards an unrecognized key through the caller's issues array, and this must not read that as the substituting schema failing and drop it.\n const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx);\n if (result instanceof Promise)\n return result.then((result) => handleOptionalResult(payload, result));\n return handleOptionalResult(payload, result);\n }\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodExactOptional = /*@__PURE__*/ core.$constructor(\"$ZodExactOptional\", (inst, def) => {\n // Call parent init - inherits optin/optout = \"optional\"\n $ZodOptional.init(inst, def);\n // Override values/pattern to NOT add undefined\n util.defineLazyInternal(inst, \"values\", (zod) => zod.def.innerType._zod.values);\n util.defineLazyInternal(inst, \"pattern\", (zod) => zod.def.innerType._zod.pattern);\n // Override parse to just delegate (no undefined handling)\n inst._zod.parse = (payload, ctx) => {\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodNullable = /*@__PURE__*/ core.$constructor(\"$ZodNullable\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.innerType._zod.optin);\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.innerType._zod.optout);\n util.defineLazyInternal(inst, \"pattern\", (zod) => {\n const pattern = zod.def.innerType._zod.pattern;\n return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)}|null)$`) : undefined;\n });\n util.defineLazyInternal(inst, \"values\", (zod) => {\n return zod.def.innerType._zod.values ? new Set([...zod.def.innerType._zod.values, null]) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n // Forward direction (decode): allow null to pass through\n if (payload.value === null)\n return payload;\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodDefault = /*@__PURE__*/ core.$constructor(\"$ZodDefault\", (inst, def) => {\n $ZodType.init(inst, def);\n // inst._zod.qin = \"true\";\n inst._zod.optin = \"defaulted\";\n util.defineLazyInternal(inst, \"values\", (zod) => zod.def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n // Forward direction (decode): apply defaults for undefined input\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n /**\n * $ZodDefault returns the default value immediately in forward direction.\n * It doesn't pass the default value into the validator (\"prefault\"). There's no reason to pass the default value through validation. The validity of the default is enforced by TypeScript statically. Otherwise, it's the responsibility of the user to ensure the default is valid. In the case of pipes with divergent in/out types, you can specify the default on the `in` schema of your ZodPipe to set a \"prefault\" for the pipe. */\n return payload;\n }\n // Forward direction: continue with default handling\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => handleDefaultResult(result, def));\n }\n return handleDefaultResult(result, def);\n };\n});\nfunction handleDefaultResult(payload, def) {\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n }\n return payload;\n}\nexport const $ZodPrefault = /*@__PURE__*/ core.$constructor(\"$ZodPrefault\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.optin = \"defaulted\";\n util.defineLazyInternal(inst, \"values\", (zod) => zod.def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n // Forward direction (decode): apply prefault for undefined input\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n }\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodNonOptional = /*@__PURE__*/ core.$constructor(\"$ZodNonOptional\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazyInternal(inst, \"values\", (zod) => {\n const v = zod.def.innerType._zod.values;\n return v ? new Set([...v].filter((x) => x !== undefined)) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => handleNonOptionalResult(result, inst));\n }\n return handleNonOptionalResult(result, inst);\n };\n});\nfunction handleNonOptionalResult(payload, inst) {\n if (!payload.issues.length && payload.value === undefined) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"nonoptional\",\n input: payload.value,\n inst,\n });\n }\n return payload;\n}\nexport const $ZodSuccess = /*@__PURE__*/ core.$constructor(\"$ZodSuccess\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n throw new core.$ZodEncodeError(\"ZodSuccess\");\n }\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => {\n payload.value = result.issues.length === 0;\n return payload;\n });\n }\n payload.value = result.issues.length === 0;\n return payload;\n };\n});\nfunction handleCatchResult(payload, result, def, ctx) {\n if (!result.issues.length) {\n payload.value = result.value;\n // The value carries up, so the flag describing it has to carry with it: a back-edge into a node still being parsed must not be frozen by an enclosing readonly, and its checks belong to the node itself. Guarded so the ordinary case adds no own property.\n if (result.memo)\n payload.memo = true;\n return payload;\n }\n // Spread the inner's own payload, not ours: `value` has to stay the input the catch was handed, and the inner ran on a payload of its own so its issues are already private to this call.\n payload.value = def.catchValue({\n ...result,\n value: payload.value,\n error: {\n issues: result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n },\n input: payload.value,\n });\n return payload;\n}\nexport const $ZodCatch = /*@__PURE__*/ core.$constructor(\"$ZodCatch\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.innerType._zod.optin === \"defaulted\" ? \"defaulted\" : \"optional\");\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.innerType._zod.optout);\n util.defineLazyInternal(inst, \"values\", (zod) => zod.def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n // Forward direction (decode): apply catch logic\n const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx);\n if (result instanceof Promise) {\n return result.then((result) => handleCatchResult(payload, result, def, ctx));\n }\n return handleCatchResult(payload, result, def, ctx);\n };\n});\nexport const $ZodNaN = /*@__PURE__*/ core.$constructor(\"$ZodNaN\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"number\" || !Number.isNaN(payload.value)) {\n payload.issues.push({\n input: payload.value,\n inst,\n expected: \"nan\",\n code: \"invalid_type\",\n });\n return payload;\n }\n return payload;\n };\n});\nexport const $ZodPipe = /*@__PURE__*/ core.$constructor(\"$ZodPipe\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazyInternal(inst, \"values\", (zod) => zod.def.in._zod.values);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.in._zod.optin);\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.out._zod.optout);\n util.defineLazyInternal(inst, \"propValues\", (zod) => zod.def.in._zod.propValues);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n const right = def.out._zod.run(payload, ctx);\n if (right instanceof Promise) {\n return right.then((right) => handlePipeResult(right, def.in, ctx));\n }\n return handlePipeResult(right, def.in, ctx);\n }\n const left = def.in._zod.run(payload, ctx);\n if (left instanceof Promise) {\n return left.then((left) => handlePipeResult(left, def.out, ctx));\n }\n return handlePipeResult(left, def.out, ctx);\n };\n});\nfunction handlePipeResult(left, next, ctx) {\n // Any issue stops the pipe, so a failing refinement never feeds its transform. An unrecognized key is the exception: it describes the input's extra properties, not the value being piped, and an enclosing intersection may yet reconcile it.\n if (left.issues.some((iss) => iss.code !== \"unrecognized_keys\")) {\n // prevent further checks\n left.aborted = true;\n return left;\n }\n return next._zod.run({ value: left.value, issues: left.issues }, ctx);\n}\nexport const $ZodCodec = /*@__PURE__*/ core.$constructor(\"$ZodCodec\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazyInternal(inst, \"values\", (zod) => zod.def.in._zod.values);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.in._zod.optin);\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.out._zod.optout);\n util.defineLazyInternal(inst, \"propValues\", (zod) => zod.def.in._zod.propValues);\n inst._zod.parse = (payload, ctx) => {\n const direction = ctx.direction || \"forward\";\n if (direction === \"forward\") {\n const left = def.in._zod.run(payload, ctx);\n if (left instanceof Promise) {\n return left.then((left) => handleCodecAResult(left, def, ctx));\n }\n return handleCodecAResult(left, def, ctx);\n }\n else {\n const right = def.out._zod.run(payload, ctx);\n if (right instanceof Promise) {\n return right.then((right) => handleCodecAResult(right, def, ctx));\n }\n return handleCodecAResult(right, def, ctx);\n }\n };\n});\nfunction handleCodecAResult(result, def, ctx) {\n if (result.issues.length) {\n // prevent further checks\n result.aborted = true;\n return result;\n }\n const direction = ctx.direction || \"forward\";\n if (direction === \"forward\") {\n const transformed = def.transform(result.value, result);\n if (transformed instanceof Promise) {\n return transformed.then((value) => handleCodecTxResult(result, value, def.out, ctx));\n }\n return handleCodecTxResult(result, transformed, def.out, ctx);\n }\n else {\n const transformed = def.reverseTransform(result.value, result);\n if (transformed instanceof Promise) {\n return transformed.then((value) => handleCodecTxResult(result, value, def.in, ctx));\n }\n return handleCodecTxResult(result, transformed, def.in, ctx);\n }\n}\nfunction handleCodecTxResult(left, value, nextSchema, ctx) {\n // Check if transform added any issues\n if (left.issues.length) {\n left.aborted = true;\n return left;\n }\n return nextSchema._zod.run({ value, issues: left.issues }, ctx);\n}\nexport const $ZodPreprocess = /*@__PURE__*/ core.$constructor(\"$ZodPreprocess\", (inst, def) => {\n $ZodPipe.init(inst, def);\n});\nexport const $ZodReadonly = /*@__PURE__*/ core.$constructor(\"$ZodReadonly\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazyInternal(inst, \"propValues\", (zod) => zod.def.innerType._zod.propValues);\n util.defineLazyInternal(inst, \"values\", (zod) => zod.def.innerType._zod.values);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.innerType?._zod?.optin);\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.innerType?._zod?.optout);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then(handleReadonlyResult);\n }\n return handleReadonlyResult(result);\n };\n});\nfunction handleReadonlyResult(payload) {\n // A repeat visit hands back a node that is still being built; freezing it here would make the rest of its keys fail to assign.\n if (!payload.memo)\n payload.value = Object.freeze(payload.value);\n return payload;\n}\n// a leaf's pattern source with its own checks folded in: the last pattern-carrying check wins, else length bounds narrow the catch-all, else an integer format narrows the number form. the fold lives here instead of on `_zod.pattern` so a bundle without template literals never pays for it\nfunction leafPattern(schema) {\n const def = schema._zod.def;\n let pattern = def.pattern;\n let isInt = !!def.format?.includes(\"int\");\n let minimum;\n let maximum;\n for (const ch of def.checks ?? []) {\n const d = ch._zod.def;\n if (d.pattern)\n pattern = d.pattern;\n isInt || (isInt = !!d.format?.includes(\"int\"));\n const lo = d.minimum ?? d.length;\n const hi = d.maximum ?? d.length;\n if (lo !== undefined && (minimum === undefined || lo > minimum))\n minimum = lo;\n if (hi !== undefined && (maximum === undefined || hi < maximum))\n maximum = hi;\n }\n if (pattern)\n return pattern.source;\n // an empty range matches nothing at runtime, and `{8,5}` is not a legal quantifier\n if (minimum !== undefined && maximum !== undefined && minimum > maximum)\n return \"(?!)\";\n if (minimum !== undefined || maximum !== undefined)\n return regexes.string({ minimum, maximum }).source;\n const own = schema._zod.pattern;\n return (isInt && own === regexes.number ? regexes.integer : own)?.source;\n}\n// a part's pattern source. a wrapper's pattern embeds its inner pattern's source verbatim, so the folded form is substituted in place without knowing the wrapper's own composition; a union's options are joined the way the union builds its own pattern\nfunction partPattern(schema) {\n const def = schema._zod.def;\n const own = schema._zod.pattern?.source;\n // lazy resolves its inner on the internals, not the def\n const inner = def.innerType ?? schema._zod.innerType;\n if (inner) {\n const before = inner._zod.pattern?.source;\n const after = partPattern(inner);\n if (own && before && after && after !== before) {\n return own.replace(util.cleanRegex(before), () => util.cleanRegex(after));\n }\n return own;\n }\n if (def.options) {\n const sources = def.options.map(partPattern);\n if (sources.every(Boolean))\n return `^(${sources.map((s) => util.cleanRegex(s)).join(\"|\")})$`;\n }\n return leafPattern(schema);\n}\nexport const $ZodTemplateLiteral = /*@__PURE__*/ core.$constructor(\"$ZodTemplateLiteral\", (inst, def) => {\n $ZodType.init(inst, def);\n const regexParts = [];\n for (const part of def.parts) {\n if (typeof part === \"object\" && part !== null) {\n // is Zod schema\n const source = partPattern(part);\n if (!source) {\n throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`);\n }\n regexParts.push(util.cleanRegex(source));\n }\n else if (part === null || util.primitiveTypes.has(typeof part)) {\n regexParts.push(util.escapeRegex(`${part}`));\n }\n else {\n throw new Error(`Invalid template literal part: ${part}`);\n }\n }\n inst._zod.pattern = new RegExp(`^${regexParts.join(\"\")}$`);\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"string\") {\n payload.issues.push({\n input: payload.value,\n inst,\n expected: \"string\",\n code: \"invalid_type\",\n });\n return payload;\n }\n inst._zod.pattern.lastIndex = 0;\n if (!inst._zod.pattern.test(payload.value)) {\n payload.issues.push({\n input: payload.value,\n inst,\n code: \"invalid_format\",\n format: def.format ?? \"template_literal\",\n pattern: inst._zod.pattern.source,\n });\n return payload;\n }\n return payload;\n };\n});\nexport const $ZodFunction = /*@__PURE__*/ core.$constructor(\"$ZodFunction\", (inst, def) => {\n $ZodType.init(inst, def);\n // Defined, not assigned: the classic prototype exposes `_def` as a getter with no setter.\n Object.defineProperty(inst, \"_def\", { value: def });\n inst._zod.def = def;\n inst.implement = (func) => {\n if (typeof func !== \"function\") {\n throw new Error(\"implement() must be called with a function\");\n }\n // Defined inline so the closure stays anonymous: binding it to a `const` first names it, which costs 256 bytes per implemented function.\n return Object.defineProperty(function (...args) {\n const parsedArgs = inst._def.input ? parse(inst._def.input, args) : args;\n const result = Reflect.apply(func, this, parsedArgs);\n if (inst._def.output) {\n return parse(inst._def.output, result);\n }\n return result;\n }, \"_zod\", { value: inst._zod, enumerable: false });\n };\n inst.implementAsync = (func) => {\n if (typeof func !== \"function\") {\n throw new Error(\"implementAsync() must be called with a function\");\n }\n return Object.defineProperty(async function (...args) {\n const parsedArgs = inst._def.input ? await parseAsync(inst._def.input, args) : args;\n const result = await Reflect.apply(func, this, parsedArgs);\n if (inst._def.output) {\n return await parseAsync(inst._def.output, result);\n }\n return result;\n }, \"_zod\", { value: inst._zod, enumerable: false });\n };\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"function\") {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"function\",\n input: payload.value,\n inst,\n });\n return payload;\n }\n // Check if output is a promise type to determine if we should use async implementation\n const hasPromiseOutput = inst._def.output && inst._def.output._zod.def.type === \"promise\";\n if (hasPromiseOutput) {\n payload.value = inst.implementAsync(payload.value);\n }\n else {\n payload.value = inst.implement(payload.value);\n }\n return payload;\n };\n inst.input = (...args) => {\n const F = inst.constructor;\n if (Array.isArray(args[0])) {\n return new F({\n type: \"function\",\n input: new $ZodTuple({\n type: \"tuple\",\n items: args[0],\n rest: args[1],\n }),\n output: inst._def.output,\n });\n }\n return new F({\n type: \"function\",\n input: args[0],\n output: inst._def.output,\n });\n };\n inst.output = (output) => {\n const F = inst.constructor;\n return new F({\n type: \"function\",\n input: inst._def.input,\n output,\n });\n };\n return inst;\n});\nexport const $ZodPromise = /*@__PURE__*/ core.$constructor(\"$ZodPromise\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n return Promise.resolve(payload.value).then((inner) => def.innerType._zod.run({ value: inner, issues: [] }, ctx));\n };\n});\nexport const $ZodLazy = /*@__PURE__*/ core.$constructor(\"$ZodLazy\", (inst, def) => {\n $ZodType.init(inst, def);\n // Cache the resolved inner type on the shared `def` so all clones of this lazy (e.g. via `.describe()`/`.meta()`) share the same inner instance, preserving identity for cycle detection on recursive schemas.\n util.defineLazy(inst._zod, \"innerType\", () => {\n const d = def;\n if (!d._cachedInner)\n d._cachedInner = def.getter();\n return d._cachedInner;\n });\n util.defineLazyInternal(inst, \"pattern\", (zod) => zod.innerType?._zod?.pattern);\n util.defineLazyInternal(inst, \"propValues\", (zod) => zod.innerType?._zod?.propValues);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.innerType?._zod?.optin ?? undefined);\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.innerType?._zod?.optout ?? undefined);\n inst._zod.parse = (payload, ctx) => {\n const inner = inst._zod.innerType;\n return inner._zod.run(payload, ctx);\n };\n});\nexport const $ZodCustom = /*@__PURE__*/ core.$constructor(\"$ZodCustom\", (inst, def) => {\n checks.$ZodCheck.init(inst, def);\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _) => {\n return payload;\n };\n inst._zod.check = (payload) => {\n const input = payload.value;\n const r = def.fn(input);\n if (r instanceof Promise) {\n return r.then((r) => handleRefineResult(r, payload, input, inst));\n }\n handleRefineResult(r, payload, input, inst);\n return;\n };\n});\nfunction handleRefineResult(result, payload, input, inst) {\n if (!result) {\n const _iss = {\n code: \"custom\",\n input,\n inst, // incorporates params.error into issue reporting\n path: [...(inst._zod.def.path ?? [])], // incorporates params.error into issue reporting\n continue: !inst._zod.def.abort,\n // params: inst._zod.def.params,\n };\n if (inst._zod.def.params)\n _iss.params = inst._zod.def.params;\n payload.issues.push(util.issue(_iss));\n }\n}\n","import * as checks from \"./checks.js\";\nimport * as registries from \"./registries.js\";\nimport * as schemas from \"./schemas.js\";\nimport * as util from \"./util.js\";\nfunction snapshotChecks(def) {\n if (def.checks)\n def.checks = [...def.checks];\n return def;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _string(Class, params) {\n return new Class(snapshotChecks({ type: \"string\", ...util.normalizeParams(params) }));\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedString(Class, params) {\n return new Class(snapshotChecks({ type: \"string\", coerce: true, ...util.normalizeParams(params) }));\n}\n// @__NO_SIDE_EFFECTS__\nexport function _email(Class, params) {\n return new Class({\n type: \"string\",\n format: \"email\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _guid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"guid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v4\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v6\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv7(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v7\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _url(Class, params) {\n return new Class({\n type: \"string\",\n format: \"url\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _emoji(Class, params) {\n return new Class({\n type: \"string\",\n format: \"emoji\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nanoid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"nanoid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link _cuid2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\n// @__NO_SIDE_EFFECTS__\nexport function _cuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cuid2(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cuid2\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ulid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ulid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _xid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"xid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ksuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ksuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ipv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ipv4\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ipv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ipv6\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _mac(Class, params) {\n return new Class({\n type: \"string\",\n format: \"mac\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cidrv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cidrv4\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cidrv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cidrv6\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _base64(Class, params) {\n return new Class({\n type: \"string\",\n format: \"base64\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _base64url(Class, params) {\n return new Class({\n type: \"string\",\n format: \"base64url\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _e164(Class, params) {\n return new Class({\n type: \"string\",\n format: \"e164\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _creditCard(Class, params) {\n return new Class({\n type: \"string\",\n format: \"credit_card\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _iban(Class, params) {\n return new Class({\n type: \"string\",\n format: \"iban\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _jwt(Class, params) {\n return new Class({\n type: \"string\",\n format: \"jwt\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\nexport const TimePrecision = {\n Any: null,\n Minute: -1,\n Second: 0,\n Millisecond: 3,\n Microsecond: 6,\n};\n// @__NO_SIDE_EFFECTS__\nexport function _isoDateTime(Class, params) {\n return new Class({\n type: \"string\",\n format: \"datetime\",\n check: \"string_format\",\n offset: false,\n local: false,\n precision: null,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoDate(Class, params) {\n return new Class({\n type: \"string\",\n format: \"date\",\n check: \"string_format\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoTime(Class, params) {\n return new Class({\n type: \"string\",\n format: \"time\",\n check: \"string_format\",\n precision: null,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoDuration(Class, params) {\n return new Class({\n type: \"string\",\n format: \"duration\",\n check: \"string_format\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _number(Class, params) {\n return new Class(snapshotChecks({ type: \"number\", checks: [], ...util.normalizeParams(params) }));\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedNumber(Class, params) {\n return new Class(snapshotChecks({ type: \"number\", coerce: true, checks: [], ...util.normalizeParams(params) }));\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"safeint\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _float32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"float32\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _float64(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"float64\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"int32\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uint32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"uint32\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _boolean(Class, params) {\n return new Class({\n type: \"boolean\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedBoolean(Class, params) {\n return new Class({\n type: \"boolean\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _bigint(Class, params) {\n return new Class({\n type: \"bigint\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedBigint(Class, params) {\n return new Class({\n type: \"bigint\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int64(Class, params) {\n return new Class({\n type: \"bigint\",\n check: \"bigint_format\",\n abort: false,\n format: \"int64\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uint64(Class, params) {\n return new Class({\n type: \"bigint\",\n check: \"bigint_format\",\n abort: false,\n format: \"uint64\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _symbol(Class, params) {\n return new Class({\n type: \"symbol\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _undefined(Class, params) {\n return new Class({\n type: \"undefined\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _null(Class, params) {\n return new Class({\n type: \"null\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _any(Class) {\n return new Class({\n type: \"any\",\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _unknown(Class) {\n return new Class({\n type: \"unknown\",\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _never(Class, params) {\n return new Class({\n type: \"never\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _void(Class, params) {\n return new Class({\n type: \"void\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _date(Class, params) {\n return new Class({\n type: \"date\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedDate(Class, params) {\n return new Class({\n type: \"date\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nan(Class, params) {\n return new Class({\n type: \"nan\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lt(value, params) {\n return new checks.$ZodCheckLessThan({\n check: \"less_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: false,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lte(value, params) {\n return new checks.$ZodCheckLessThan({\n check: \"less_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: true,\n });\n}\nexport { \n/** @deprecated Use `z.lte()` instead. */\n_lte as _max, };\n// @__NO_SIDE_EFFECTS__\nexport function _gt(value, params) {\n return new checks.$ZodCheckGreaterThan({\n check: \"greater_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: false,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _gte(value, params) {\n return new checks.$ZodCheckGreaterThan({\n check: \"greater_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: true,\n });\n}\nexport { \n/** @deprecated Use `z.gte()` instead. */\n_gte as _min, };\n// @__NO_SIDE_EFFECTS__\nexport function _positive(params) {\n return _gt(0, params);\n}\n// negative\n// @__NO_SIDE_EFFECTS__\nexport function _negative(params) {\n return _lt(0, params);\n}\n// nonpositive\n// @__NO_SIDE_EFFECTS__\nexport function _nonpositive(params) {\n return _lte(0, params);\n}\n// nonnegative\n// @__NO_SIDE_EFFECTS__\nexport function _nonnegative(params) {\n return _gte(0, params);\n}\n// @__NO_SIDE_EFFECTS__\nexport function _multipleOf(value, params) {\n return new checks.$ZodCheckMultipleOf({\n check: \"multiple_of\",\n ...util.normalizeParams(params),\n value,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _maxSize(maximum, params) {\n return new checks.$ZodCheckMaxSize({\n check: \"max_size\",\n ...util.normalizeParams(params),\n maximum,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _minSize(minimum, params) {\n return new checks.$ZodCheckMinSize({\n check: \"min_size\",\n ...util.normalizeParams(params),\n minimum,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _size(size, params) {\n return new checks.$ZodCheckSizeEquals({\n check: \"size_equals\",\n ...util.normalizeParams(params),\n size,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _maxLength(maximum, params) {\n const ch = new checks.$ZodCheckMaxLength({\n check: \"max_length\",\n ...util.normalizeParams(params),\n maximum,\n });\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _minLength(minimum, params) {\n return new checks.$ZodCheckMinLength({\n check: \"min_length\",\n ...util.normalizeParams(params),\n minimum,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _length(length, params) {\n return new checks.$ZodCheckLengthEquals({\n check: \"length_equals\",\n ...util.normalizeParams(params),\n length,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _regex(pattern, params) {\n return new checks.$ZodCheckRegex({\n check: \"string_format\",\n format: \"regex\",\n ...util.normalizeParams(params),\n pattern,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lowercase(params) {\n return new checks.$ZodCheckLowerCase({\n check: \"string_format\",\n format: \"lowercase\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uppercase(params) {\n return new checks.$ZodCheckUpperCase({\n check: \"string_format\",\n format: \"uppercase\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _includes(includes, params) {\n return new checks.$ZodCheckIncludes({\n check: \"string_format\",\n format: \"includes\",\n ...util.normalizeParams(params),\n includes,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _startsWith(prefix, params) {\n return new checks.$ZodCheckStartsWith({\n check: \"string_format\",\n format: \"starts_with\",\n ...util.normalizeParams(params),\n prefix,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _endsWith(suffix, params) {\n return new checks.$ZodCheckEndsWith({\n check: \"string_format\",\n format: \"ends_with\",\n ...util.normalizeParams(params),\n suffix,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _property(property, schema, params) {\n return new checks.$ZodCheckProperty({\n check: \"property\",\n property,\n schema,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _properties(shape, params) {\n return new checks.$ZodCheckProperties({\n check: \"properties\",\n shape,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _mime(types, params) {\n return new checks.$ZodCheckMimeType({\n check: \"mime_type\",\n mime: types,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _overwrite(tx) {\n return new checks.$ZodCheckOverwrite({\n check: \"overwrite\",\n tx,\n });\n}\n// normalize\n// @__NO_SIDE_EFFECTS__\nexport function _normalize(form) {\n return _overwrite((input) => input.normalize(form));\n}\n// trim\n// @__NO_SIDE_EFFECTS__\nexport function _trim() {\n return _overwrite((input) => input.trim());\n}\n// toLowerCase\n// @__NO_SIDE_EFFECTS__\nexport function _toLowerCase() {\n return _overwrite((input) => input.toLowerCase());\n}\n// toUpperCase\n// @__NO_SIDE_EFFECTS__\nexport function _toUpperCase() {\n return _overwrite((input) => input.toUpperCase());\n}\n// slugify\n// @__NO_SIDE_EFFECTS__\nexport function _slugify() {\n return _overwrite((input) => util.slugify(input));\n}\n// @__NO_SIDE_EFFECTS__\nexport function _array(Class, element, params) {\n return new Class({\n type: \"array\",\n element,\n // get element() {\n // return element;\n // },\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _union(Class, options, params) {\n return new Class({\n type: \"union\",\n options,\n ...util.normalizeParams(params),\n });\n}\nexport function _xor(Class, options, params) {\n return new Class({\n type: \"union\",\n options,\n inclusive: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _discriminatedUnion(Class, discriminator, options, params) {\n return new Class({\n type: \"union\",\n options: options,\n discriminator,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _intersection(Class, left, right) {\n return new Class({\n type: \"intersection\",\n left,\n right,\n });\n}\n// export function _tuple(\n// Class: util.SchemaClass<schemas.$ZodTuple>,\n// items: [],\n// params?: string | $ZodTupleParams\n// ): schemas.$ZodTuple<[], null>;\n// @__NO_SIDE_EFFECTS__\nexport function _tuple(Class, items, _paramsOrRest, _params) {\n const hasRest = _paramsOrRest instanceof schemas.$ZodType;\n const params = hasRest ? _params : _paramsOrRest;\n const rest = hasRest ? _paramsOrRest : null;\n return new Class({\n type: \"tuple\",\n items,\n rest,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _record(Class, keyType, valueType, params) {\n return new Class({\n type: \"record\",\n keyType,\n valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _map(Class, keyType, valueType, params) {\n return new Class({\n type: \"map\",\n keyType,\n valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _set(Class, valueType, params) {\n return new Class({\n type: \"set\",\n valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _enum(Class, values, params) {\n const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;\n // if (Array.isArray(values)) {\n // for (const value of values) {\n // entries[value] = value;\n // }\n // } else {\n // Object.assign(entries, values);\n // }\n // const entries: util.EnumLike = {};\n // for (const val of values) {\n // entries[val] = val;\n // }\n return new Class({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\n/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead.\n *\n * ```ts\n * enum Colors { red, green, blue }\n * z.enum(Colors);\n * ```\n */\nexport function _nativeEnum(Class, entries, params) {\n return new Class({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _literal(Class, value, params) {\n return new Class({\n type: \"literal\",\n values: Array.isArray(value) ? value : [value],\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _file(Class, params) {\n return new Class({\n type: \"file\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _transform(Class, fn) {\n return new Class({\n type: \"transform\",\n transform: fn,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _optional(Class, innerType) {\n return new Class({\n type: \"optional\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nullable(Class, innerType) {\n return new Class({\n type: \"nullable\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _default(Class, innerType, defaultValue) {\n return new Class({\n type: \"default\",\n innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nonoptional(Class, innerType, params) {\n return new Class({\n type: \"nonoptional\",\n innerType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _success(Class, innerType) {\n return new Class({\n type: \"success\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _catch(Class, innerType, catchValue) {\n return new Class({\n type: \"catch\",\n innerType,\n catchValue: (typeof catchValue === \"function\" ? catchValue : util.constantCatch(catchValue)),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _pipe(Class, in_, out) {\n return new Class({\n type: \"pipe\",\n in: in_,\n out,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _readonly(Class, innerType) {\n return new Class({\n type: \"readonly\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _templateLiteral(Class, parts, params) {\n return new Class({\n type: \"template_literal\",\n parts,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lazy(Class, getter) {\n return new Class({\n type: \"lazy\",\n getter,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _promise(Class, innerType) {\n return new Class({\n type: \"promise\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _custom(Class, fn, _params) {\n const norm = util.normalizeParams(_params);\n norm.abort ?? (norm.abort = true); // default to abort:false\n const schema = new Class({\n type: \"custom\",\n check: \"custom\",\n fn: fn,\n ...norm,\n });\n return schema;\n}\n// same as _custom but defaults to abort:false\n// @__NO_SIDE_EFFECTS__\nexport function _refine(Class, fn, _params) {\n const schema = new Class({\n type: \"custom\",\n check: \"custom\",\n fn: fn,\n ...util.normalizeParams(_params),\n });\n return schema;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _superRefine(fn, params) {\n const ch = _check((payload) => {\n payload.addIssue = (issue) => {\n if (typeof issue === \"string\") {\n payload.issues.push(util.issue(issue, payload.value, ch._zod.def));\n }\n else {\n // for Zod 3 backwards compatibility\n const _issue = issue;\n if (_issue.fatal)\n _issue.continue = false;\n _issue.code ?? (_issue.code = \"custom\");\n if (!(\"input\" in _issue))\n _issue.input = payload.value;\n _issue.inst ?? (_issue.inst = ch);\n _issue.continue ?? (_issue.continue = !ch._zod.def.abort); // abort is always undefined, so this is always true...\n payload.issues.push(util.issue(_issue));\n }\n };\n return fn(payload.value, payload);\n }, params);\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _check(fn, params) {\n const ch = new checks.$ZodCheck({\n check: \"custom\",\n ...util.normalizeParams(params),\n });\n ch._zod.check = fn;\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function describe(description) {\n const ch = new checks.$ZodCheck({ check: \"describe\" });\n ch._zod.onattach = [\n (inst) => {\n const existing = registries.globalRegistry.get(inst) ?? {};\n registries.globalRegistry.add(inst, { ...existing, description });\n },\n ];\n ch._zod.check = () => { }; // no-op check\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function meta(metadata) {\n const ch = new checks.$ZodCheck({ check: \"meta\" });\n ch._zod.onattach = [\n (inst) => {\n const existing = registries.globalRegistry.get(inst) ?? {};\n registries.globalRegistry.add(inst, { ...existing, ...metadata });\n },\n ];\n ch._zod.check = () => { }; // no-op check\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _stringbool(Classes, _params) {\n const params = util.normalizeParams(_params);\n let truthyArray = params.truthy ?? [\"true\", \"1\", \"yes\", \"on\", \"y\", \"enabled\"];\n let falsyArray = params.falsy ?? [\"false\", \"0\", \"no\", \"off\", \"n\", \"disabled\"];\n if (params.case !== \"sensitive\") {\n truthyArray = truthyArray.map((v) => (typeof v === \"string\" ? v.toLowerCase() : v));\n falsyArray = falsyArray.map((v) => (typeof v === \"string\" ? v.toLowerCase() : v));\n }\n const truthySet = new Set(truthyArray);\n const falsySet = new Set(falsyArray);\n const _Codec = Classes.Codec ?? schemas.$ZodCodec;\n const _Boolean = Classes.Boolean ?? schemas.$ZodBoolean;\n const _String = Classes.String ?? schemas.$ZodString;\n const stringSchema = new _String({ type: \"string\", error: params.error });\n const booleanSchema = new _Boolean({ type: \"boolean\", error: params.error });\n const codec = new _Codec({\n type: \"pipe\",\n in: stringSchema,\n out: booleanSchema,\n transform: ((input, payload) => {\n let data = input;\n if (params.case !== \"sensitive\")\n data = data.toLowerCase();\n if (truthySet.has(data)) {\n return true;\n }\n else if (falsySet.has(data)) {\n return false;\n }\n else {\n payload.issues.push({\n code: \"invalid_value\",\n expected: \"stringbool\",\n values: [...truthySet, ...falsySet],\n input: payload.value,\n inst: codec,\n continue: false,\n });\n return {};\n }\n }),\n reverseTransform: ((input, _payload) => {\n if (input === true) {\n return truthyArray[0] || \"true\";\n }\n else {\n return falsyArray[0] || \"false\";\n }\n }),\n error: params.error,\n });\n codec._zod.bag.truthy = truthyArray;\n codec._zod.bag.falsy = falsyArray;\n codec._zod.bag.case = params.case ?? \"insensitive\";\n return codec;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _stringFormat(Class, format, fnOrRegex, _params = {}) {\n const params = util.normalizeParams(_params);\n const def = {\n check: \"string_format\",\n type: \"string\",\n format,\n fn: typeof fnOrRegex === \"function\" ? fnOrRegex : (val) => fnOrRegex.test(val),\n ...params,\n };\n if (fnOrRegex instanceof RegExp) {\n def.pattern = fnOrRegex;\n }\n const inst = new Class(def);\n return inst;\n}\n","import * as core from \"../core/index.js\";\nimport * as regexes from \"../core/regexes.js\";\nimport * as util from \"../core/util.js\";\nimport * as parse from \"./parse.js\";\nexport const ZodMiniType = /*@__PURE__*/ core.$constructor(\"ZodMiniType\", (inst, def) => {\n if (!inst._zod)\n throw new Error(\"Uninitialized schema in ZodMiniType.\");\n core.$ZodType.init(inst, def);\n inst.def = def;\n inst.type = def.type;\n}, {\n // `with` is an alias for `check`: the same function object, not a wrapper.\n get with() {\n return this.check;\n },\n set with(value) {\n util.own(this, \"with\", value);\n },\n parse(data, params) {\n return parse.parse(this, data, params, { callee: this.parse });\n },\n parseAsync(data, params) {\n return parse.parseAsync(this, data, params, { callee: this.parseAsync });\n },\n safeParse(data, params) {\n return parse.safeParse(this, data, params);\n },\n safeParseAsync(data, params) {\n return parse.safeParseAsync(this, data, params);\n },\n check(...checks) {\n const def = this.def;\n return this.clone({\n ...def,\n checks: [\n ...(def.checks ?? []),\n ...checks.map((ch) => typeof ch === \"function\" ? { _zod: { check: ch, def: { check: \"custom\" }, onattach: [] } } : ch),\n ],\n }, { parent: true });\n },\n clone(_def, params) {\n return core.clone(this, _def, params);\n },\n brand() {\n return this;\n },\n register(reg, meta) {\n reg.add(this, meta);\n return this;\n },\n apply(fn, ...args) {\n return args.length === 0 ? fn(this) : fn(this, ...args);\n },\n});\nexport const ZodMiniString = /*@__PURE__*/ core.$constructor(\"ZodMiniString\", (inst, def) => {\n core.$ZodString.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function string(params) {\n return core._string(ZodMiniString, params);\n}\nexport const ZodMiniStringFormat = /*@__PURE__*/ core.$constructor(\"ZodMiniStringFormat\", (inst, def) => {\n core.$ZodStringFormat.init(inst, def);\n ZodMiniString.init(inst, def);\n});\nexport const ZodMiniEmail = /*@__PURE__*/ core.$constructor(\"ZodMiniEmail\", (inst, def) => {\n core.$ZodEmail.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function email(params) {\n return core._email(ZodMiniEmail, params);\n}\nexport const ZodMiniGUID = /*@__PURE__*/ core.$constructor(\"ZodMiniGUID\", (inst, def) => {\n core.$ZodGUID.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function guid(params) {\n return core._guid(ZodMiniGUID, params);\n}\nexport const ZodMiniUUID = /*@__PURE__*/ core.$constructor(\"ZodMiniUUID\", (inst, def) => {\n core.$ZodUUID.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function uuid(params) {\n return core._uuid(ZodMiniUUID, params);\n}\n// @__NO_SIDE_EFFECTS__\nexport function uuidv4(params) {\n return core._uuidv4(ZodMiniUUID, params);\n}\n// ZodMiniUUIDv6\n// @__NO_SIDE_EFFECTS__\nexport function uuidv6(params) {\n return core._uuidv6(ZodMiniUUID, params);\n}\n// ZodMiniUUIDv7\n// @__NO_SIDE_EFFECTS__\nexport function uuidv7(params) {\n return core._uuidv7(ZodMiniUUID, params);\n}\nexport const ZodMiniURL = /*@__PURE__*/ core.$constructor(\"ZodMiniURL\", (inst, def) => {\n core.$ZodURL.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function url(params) {\n return core._url(ZodMiniURL, params);\n}\n// @__NO_SIDE_EFFECTS__\nexport function httpUrl(params) {\n return core._url(ZodMiniURL, {\n protocol: regexes.httpProtocol,\n hostname: regexes.domain,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniEmoji = /*@__PURE__*/ core.$constructor(\"ZodMiniEmoji\", (inst, def) => {\n core.$ZodEmoji.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function emoji(params) {\n return core._emoji(ZodMiniEmoji, params);\n}\nexport const ZodMiniNanoID = /*@__PURE__*/ core.$constructor(\"ZodMiniNanoID\", (inst, def) => {\n core.$ZodNanoID.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function nanoid(params) {\n return core._nanoid(ZodMiniNanoID, params);\n}\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link ZodMiniCUID2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport const ZodMiniCUID = /*@__PURE__*/ core.$constructor(\"ZodMiniCUID\", (inst, def) => {\n core.$ZodCUID.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n/**\n * Validates a CUID v1 string.\n *\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link cuid2 | `z.cuid2()`} instead.\n * See https://github.com/paralleldrive/cuid.\n */\n// @__NO_SIDE_EFFECTS__\nexport function cuid(params) {\n return core._cuid(ZodMiniCUID, params);\n}\nexport const ZodMiniCUID2 = /*@__PURE__*/ core.$constructor(\"ZodMiniCUID2\", (inst, def) => {\n core.$ZodCUID2.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function cuid2(params) {\n return core._cuid2(ZodMiniCUID2, params);\n}\nexport const ZodMiniULID = /*@__PURE__*/ core.$constructor(\"ZodMiniULID\", (inst, def) => {\n core.$ZodULID.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function ulid(params) {\n return core._ulid(ZodMiniULID, params);\n}\nexport const ZodMiniXID = /*@__PURE__*/ core.$constructor(\"ZodMiniXID\", (inst, def) => {\n core.$ZodXID.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function xid(params) {\n return core._xid(ZodMiniXID, params);\n}\nexport const ZodMiniKSUID = /*@__PURE__*/ core.$constructor(\"ZodMiniKSUID\", (inst, def) => {\n core.$ZodKSUID.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function ksuid(params) {\n return core._ksuid(ZodMiniKSUID, params);\n}\nexport const ZodMiniIPv4 = /*@__PURE__*/ core.$constructor(\"ZodMiniIPv4\", (inst, def) => {\n core.$ZodIPv4.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function ipv4(params) {\n return core._ipv4(ZodMiniIPv4, params);\n}\nexport const ZodMiniIPv6 = /*@__PURE__*/ core.$constructor(\"ZodMiniIPv6\", (inst, def) => {\n core.$ZodIPv6.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function ipv6(params) {\n return core._ipv6(ZodMiniIPv6, params);\n}\nexport const ZodMiniCIDRv4 = /*@__PURE__*/ core.$constructor(\"ZodMiniCIDRv4\", (inst, def) => {\n core.$ZodCIDRv4.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function cidrv4(params) {\n return core._cidrv4(ZodMiniCIDRv4, params);\n}\nexport const ZodMiniCIDRv6 = /*@__PURE__*/ core.$constructor(\"ZodMiniCIDRv6\", (inst, def) => {\n core.$ZodCIDRv6.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function cidrv6(params) {\n return core._cidrv6(ZodMiniCIDRv6, params);\n}\nexport const ZodMiniMAC = /*@__PURE__*/ core.$constructor(\"ZodMiniMAC\", (inst, def) => {\n core.$ZodMAC.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function mac(params) {\n return core._mac(ZodMiniMAC, params);\n}\nexport const ZodMiniBase64 = /*@__PURE__*/ core.$constructor(\"ZodMiniBase64\", (inst, def) => {\n core.$ZodBase64.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function base64(params) {\n return core._base64(ZodMiniBase64, params);\n}\nexport const ZodMiniBase64URL = /*@__PURE__*/ core.$constructor(\"ZodMiniBase64URL\", (inst, def) => {\n core.$ZodBase64URL.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function base64url(params) {\n return core._base64url(ZodMiniBase64URL, params);\n}\nexport const ZodMiniE164 = /*@__PURE__*/ core.$constructor(\"ZodMiniE164\", (inst, def) => {\n core.$ZodE164.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function e164(params) {\n return core._e164(ZodMiniE164, params);\n}\nexport const ZodMiniCreditCard = /*@__PURE__*/ core.$constructor(\"ZodMiniCreditCard\", (inst, def) => {\n core.$ZodCreditCard.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function creditCard(params) {\n return core._creditCard(ZodMiniCreditCard, params);\n}\nexport const ZodMiniIBAN = /*@__PURE__*/ core.$constructor(\"ZodMiniIBAN\", (inst, def) => {\n core.$ZodIBAN.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function iban(params) {\n return core._iban(ZodMiniIBAN, params);\n}\nexport const ZodMiniJWT = /*@__PURE__*/ core.$constructor(\"ZodMiniJWT\", (inst, def) => {\n core.$ZodJWT.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function jwt(params) {\n return core._jwt(ZodMiniJWT, params);\n}\nexport const ZodMiniCustomStringFormat = /*@__PURE__*/ core.$constructor(\"ZodMiniCustomStringFormat\", (inst, def) => {\n core.$ZodCustomStringFormat.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function stringFormat(format, fnOrRegex, _params = {}) {\n return core._stringFormat(ZodMiniCustomStringFormat, format, fnOrRegex, _params);\n}\n// @__NO_SIDE_EFFECTS__\nexport function hostname(_params) {\n return core._stringFormat(ZodMiniCustomStringFormat, \"hostname\", regexes.hostname, _params);\n}\n// @__NO_SIDE_EFFECTS__\nexport function hex(_params) {\n return core._stringFormat(ZodMiniCustomStringFormat, \"hex\", regexes.hex, _params);\n}\n// @__NO_SIDE_EFFECTS__\nexport function currencyCode(_params) {\n return core._stringFormat(ZodMiniCustomStringFormat, \"currency_code\", regexes.currencyCode, _params);\n}\n// @__NO_SIDE_EFFECTS__\nexport function hash(alg, params) {\n const enc = params?.enc ?? \"hex\";\n const format = `${alg}_${enc}`;\n const regex = core.regexes[format];\n // check for unrecognized format\n if (!regex)\n throw new Error(`Unrecognized hash format: ${format}`);\n return core._stringFormat(ZodMiniCustomStringFormat, format, regex, params);\n}\nexport const ZodMiniNumber = /*@__PURE__*/ core.$constructor(\"ZodMiniNumber\", (inst, def) => {\n core.$ZodNumber.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function number(params) {\n return core._number(ZodMiniNumber, params);\n}\nexport const ZodMiniNumberFormat = /*@__PURE__*/ core.$constructor(\"ZodMiniNumberFormat\", (inst, def) => {\n core.$ZodNumberFormat.init(inst, def);\n ZodMiniNumber.init(inst, def);\n});\nexport function int(params) {\n return core._int(ZodMiniNumberFormat, params);\n}\nexport function float32(params) {\n return core._float32(ZodMiniNumberFormat, params);\n}\nexport function float64(params) {\n return core._float64(ZodMiniNumberFormat, params);\n}\nexport function int32(params) {\n return core._int32(ZodMiniNumberFormat, params);\n}\nexport function uint32(params) {\n return core._uint32(ZodMiniNumberFormat, params);\n}\nexport const ZodMiniBoolean = /*@__PURE__*/ core.$constructor(\"ZodMiniBoolean\", (inst, def) => {\n core.$ZodBoolean.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function boolean(params) {\n return core._boolean(ZodMiniBoolean, params);\n}\nexport const ZodMiniBigInt = /*@__PURE__*/ core.$constructor(\"ZodMiniBigInt\", (inst, def) => {\n core.$ZodBigInt.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function bigint(params) {\n return core._bigint(ZodMiniBigInt, params);\n}\nexport const ZodMiniBigIntFormat = /*@__PURE__*/ core.$constructor(\"ZodMiniBigIntFormat\", (inst, def) => {\n core.$ZodBigIntFormat.init(inst, def);\n ZodMiniBigInt.init(inst, def);\n});\nexport function int64(params) {\n return core._int64(ZodMiniBigIntFormat, params);\n}\nexport function uint64(params) {\n return core._uint64(ZodMiniBigIntFormat, params);\n}\nexport const ZodMiniSymbol = /*@__PURE__*/ core.$constructor(\"ZodMiniSymbol\", (inst, def) => {\n core.$ZodSymbol.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function symbol(params) {\n return core._symbol(ZodMiniSymbol, params);\n}\nexport const ZodMiniUndefined = /*@__PURE__*/ core.$constructor(\"ZodMiniUndefined\", (inst, def) => {\n core.$ZodUndefined.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nfunction _undefined(params) {\n return core._undefined(ZodMiniUndefined, params);\n}\nexport { _undefined as undefined };\nexport const ZodMiniNull = /*@__PURE__*/ core.$constructor(\"ZodMiniNull\", (inst, def) => {\n core.$ZodNull.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nfunction _null(params) {\n return core._null(ZodMiniNull, params);\n}\nexport { _null as null };\nexport const ZodMiniAny = /*@__PURE__*/ core.$constructor(\"ZodMiniAny\", (inst, def) => {\n core.$ZodAny.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function any() {\n return core._any(ZodMiniAny);\n}\nexport const ZodMiniUnknown = /*@__PURE__*/ core.$constructor(\"ZodMiniUnknown\", (inst, def) => {\n core.$ZodUnknown.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function unknown() {\n return core._unknown(ZodMiniUnknown);\n}\nexport const ZodMiniNever = /*@__PURE__*/ core.$constructor(\"ZodMiniNever\", (inst, def) => {\n core.$ZodNever.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function never(params) {\n return core._never(ZodMiniNever, params);\n}\nexport const ZodMiniVoid = /*@__PURE__*/ core.$constructor(\"ZodMiniVoid\", (inst, def) => {\n core.$ZodVoid.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nfunction _void(params) {\n return core._void(ZodMiniVoid, params);\n}\nexport { _void as void };\nexport const ZodMiniDate = /*@__PURE__*/ core.$constructor(\"ZodMiniDate\", (inst, def) => {\n core.$ZodDate.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function date(params) {\n return core._date(ZodMiniDate, params);\n}\nexport const ZodMiniArray = /*@__PURE__*/ core.$constructor(\"ZodMiniArray\", (inst, def) => {\n core.$ZodArray.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function array(element, params) {\n return new ZodMiniArray({\n type: \"array\",\n element: element,\n ...util.normalizeParams(params),\n });\n}\n// .keyof\n// @__NO_SIDE_EFFECTS__\nexport function keyof(schema) {\n const shape = schema._zod.def.shape;\n return _enum(Object.keys(shape));\n}\nexport const ZodMiniObject = /*@__PURE__*/ core.$constructor(\"ZodMiniObject\", (inst, def) => {\n core.$ZodObject.init(inst, def);\n ZodMiniType.init(inst, def);\n util.installLazyProp(inst, \"shape\", (self) => self._zod.def.shape, false);\n});\n// @__NO_SIDE_EFFECTS__\nexport function object(shape, params) {\n const def = {\n type: \"object\",\n shape: shape ?? {},\n ...util.normalizeParams(params),\n };\n return new ZodMiniObject(def);\n}\n// strictObject\n// @__NO_SIDE_EFFECTS__\nexport function strictObject(shape, params) {\n return new ZodMiniObject({\n type: \"object\",\n shape,\n catchall: never(),\n ...util.normalizeParams(params),\n });\n}\n// looseObject\n// @__NO_SIDE_EFFECTS__\nexport function looseObject(shape, params) {\n return new ZodMiniObject({\n type: \"object\",\n shape,\n catchall: unknown(),\n ...util.normalizeParams(params),\n });\n}\n// object methods\n// @__NO_SIDE_EFFECTS__\nexport function extend(schema, shape) {\n return util.extend(schema, shape);\n}\n// @__NO_SIDE_EFFECTS__\nexport function safeExtend(schema, shape) {\n return util.safeExtend(schema, shape);\n}\n/**\n * @deprecated Use [`z.extend(A, B.shape)`](https://zod.dev/api?id=extend) instead.\n */\n// @__NO_SIDE_EFFECTS__\nexport function merge(a, b) {\n return util.merge(a, b);\n}\n// @__NO_SIDE_EFFECTS__\nexport function pick(schema, mask) {\n return util.pick(schema, mask);\n}\n// .omit\n// @__NO_SIDE_EFFECTS__\nexport function omit(schema, mask) {\n return util.omit(schema, mask);\n}\n// @__NO_SIDE_EFFECTS__\nexport function partial(schema, mask) {\n const def = schema._zod.def;\n if (def.type !== \"tuple\")\n return util.partial(ZodMiniOptional, schema, mask);\n // a refinement was authored against the full arity; partialing would run it on a shorter array\n if (def.checks?.length)\n throw new Error(\".partial() cannot be used on tuple schemas containing refinements\");\n return util.clone(schema, {\n ...def,\n items: def.items.map((item) => new ZodMiniOptional({ type: \"optional\", innerType: item })),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function exactPartial(schema, mask) {\n return util.partial(ZodMiniExactOptional, schema, mask, \"exactPartial\");\n}\n// @__NO_SIDE_EFFECTS__\nexport function required(schema, mask) {\n return util.required(ZodMiniNonOptional, schema, mask);\n}\n// @__NO_SIDE_EFFECTS__\nexport function catchall(inst, catchall) {\n // `mergeDefs` rather than a spread: spreading reads `shape`, and resolving it can mint a whole fresh subtree\n return inst.clone(util.mergeDefs(inst._zod.def, { catchall: catchall }));\n}\nexport const ZodMiniUnion = /*@__PURE__*/ core.$constructor(\"ZodMiniUnion\", (inst, def) => {\n core.$ZodUnion.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function union(options, params) {\n return new ZodMiniUnion({\n type: \"union\",\n options: options,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniXor = /*@__PURE__*/ core.$constructor(\"ZodMiniXor\", (inst, def) => {\n ZodMiniUnion.init(inst, def);\n core.$ZodXor.init(inst, def);\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 ZodMiniXor({\n type: \"union\",\n options: options,\n inclusive: false,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniDiscriminatedUnion = /*@__PURE__*/ core.$constructor(\"ZodMiniDiscriminatedUnion\", (inst, def) => {\n core.$ZodDiscriminatedUnion.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function discriminatedUnion(discriminator, options, params) {\n return new ZodMiniDiscriminatedUnion({\n type: \"union\",\n options: options,\n discriminator,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniIntersection = /*@__PURE__*/ core.$constructor(\"ZodMiniIntersection\", (inst, def) => {\n core.$ZodIntersection.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function intersection(left, right) {\n return new ZodMiniIntersection({\n type: \"intersection\",\n left: left,\n right: right,\n });\n}\nexport const ZodMiniTuple = /*@__PURE__*/ core.$constructor(\"ZodMiniTuple\", (inst, def) => {\n core.$ZodTuple.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\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 ZodMiniTuple({\n type: \"tuple\",\n items: items,\n rest,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniRecord = /*@__PURE__*/ core.$constructor(\"ZodMiniRecord\", (inst, def) => {\n core.$ZodRecord.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function record(keyType, valueType, params) {\n // v3-compat: z.record(valueType, params?) — defaults keyType to z.string()\n if (!valueType || !valueType._zod) {\n return new ZodMiniRecord({\n type: \"record\",\n keyType: string(),\n valueType: keyType,\n ...util.normalizeParams(valueType),\n });\n }\n return new ZodMiniRecord({\n type: \"record\",\n keyType,\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function partialRecord(keyType, valueType, params) {\n return new ZodMiniRecord({\n type: \"record\",\n keyType,\n valueType: valueType,\n ...util.normalizeParams(params),\n partial: true,\n });\n}\nexport function looseRecord(keyType, valueType, params) {\n return new ZodMiniRecord({\n type: \"record\",\n keyType,\n valueType: valueType,\n mode: \"loose\",\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniMap = /*@__PURE__*/ core.$constructor(\"ZodMiniMap\", (inst, def) => {\n core.$ZodMap.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function map(keyType, valueType, params) {\n return new ZodMiniMap({\n type: \"map\",\n keyType: keyType,\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniSet = /*@__PURE__*/ core.$constructor(\"ZodMiniSet\", (inst, def) => {\n core.$ZodSet.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function set(valueType, params) {\n return new ZodMiniSet({\n type: \"set\",\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniEnum = /*@__PURE__*/ core.$constructor(\"ZodMiniEnum\", (inst, def) => {\n core.$ZodEnum.init(inst, def);\n ZodMiniType.init(inst, def);\n // reuse the parsed value set so a numeric TS enum's reverse-mapping keys stay out\n inst.options = [...inst._zod.values];\n});\n// @__NO_SIDE_EFFECTS__\nfunction _enum(values, params) {\n const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;\n return new ZodMiniEnum({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\nexport { _enum as enum };\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(entries, params) {\n return new ZodMiniEnum({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniLiteral = /*@__PURE__*/ core.$constructor(\"ZodMiniLiteral\", (inst, def) => {\n core.$ZodLiteral.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function literal(value, params) {\n return new ZodMiniLiteral({\n type: \"literal\",\n values: Array.isArray(value) ? value : [value],\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniFile = /*@__PURE__*/ core.$constructor(\"ZodMiniFile\", (inst, def) => {\n core.$ZodFile.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function file(params) {\n return core._file(ZodMiniFile, params);\n}\nexport const ZodMiniTransform = /*@__PURE__*/ core.$constructor(\"ZodMiniTransform\", (inst, def) => {\n core.$ZodTransform.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function transform(fn) {\n return new ZodMiniTransform({\n type: \"transform\",\n transform: fn,\n });\n}\nexport const ZodMiniOptional = /*@__PURE__*/ core.$constructor(\"ZodMiniOptional\", (inst, def) => {\n core.$ZodOptional.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function optional(innerType) {\n return new ZodMiniOptional({\n type: \"optional\",\n innerType: innerType,\n });\n}\nexport const ZodMiniExactOptional = /*@__PURE__*/ core.$constructor(\"ZodMiniExactOptional\", (inst, def) => {\n core.$ZodExactOptional.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function exactOptional(innerType) {\n return new ZodMiniExactOptional({\n type: \"optional\",\n innerType: innerType,\n });\n}\nexport const ZodMiniNullable = /*@__PURE__*/ core.$constructor(\"ZodMiniNullable\", (inst, def) => {\n core.$ZodNullable.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function nullable(innerType) {\n return new ZodMiniNullable({\n type: \"nullable\",\n innerType: innerType,\n });\n}\n// nullish\n// @__NO_SIDE_EFFECTS__\nexport function nullish(innerType) {\n return optional(nullable(innerType));\n}\nexport const ZodMiniDefault = /*@__PURE__*/ core.$constructor(\"ZodMiniDefault\", (inst, def) => {\n core.$ZodDefault.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function _default(innerType, defaultValue) {\n return new ZodMiniDefault({\n type: \"default\",\n innerType: innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\nexport const ZodMiniPrefault = /*@__PURE__*/ core.$constructor(\"ZodMiniPrefault\", (inst, def) => {\n core.$ZodPrefault.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function prefault(innerType, defaultValue) {\n return new ZodMiniPrefault({\n type: \"prefault\",\n innerType: innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\nexport const ZodMiniNonOptional = /*@__PURE__*/ core.$constructor(\"ZodMiniNonOptional\", (inst, def) => {\n core.$ZodNonOptional.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function nonoptional(innerType, params) {\n return new ZodMiniNonOptional({\n type: \"nonoptional\",\n innerType: innerType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniSuccess = /*@__PURE__*/ core.$constructor(\"ZodMiniSuccess\", (inst, def) => {\n core.$ZodSuccess.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function success(innerType) {\n return new ZodMiniSuccess({\n type: \"success\",\n innerType: innerType,\n });\n}\nexport const ZodMiniCatch = /*@__PURE__*/ core.$constructor(\"ZodMiniCatch\", (inst, def) => {\n core.$ZodCatch.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nfunction _catch(innerType, catchValue) {\n return new ZodMiniCatch({\n type: \"catch\",\n innerType: innerType,\n catchValue: (typeof catchValue === \"function\" ? catchValue : core.util.constantCatch(catchValue)),\n });\n}\nexport { _catch as catch };\nexport const ZodMiniNaN = /*@__PURE__*/ core.$constructor(\"ZodMiniNaN\", (inst, def) => {\n core.$ZodNaN.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function nan(params) {\n return core._nan(ZodMiniNaN, params);\n}\nexport const ZodMiniPipe = /*@__PURE__*/ core.$constructor(\"ZodMiniPipe\", (inst, def) => {\n core.$ZodPipe.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function pipe(in_, out) {\n return new ZodMiniPipe({\n type: \"pipe\",\n in: in_,\n out: out,\n });\n}\nexport const ZodMiniCodec = /*@__PURE__*/ core.$constructor(\"ZodMiniCodec\", (inst, def) => {\n ZodMiniPipe.init(inst, def);\n core.$ZodCodec.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function codec(in_, out, params) {\n return new ZodMiniCodec({\n type: \"pipe\",\n in: in_,\n out: out,\n transform: params.decode,\n reverseTransform: params.encode,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function invertCodec(codec) {\n const def = codec._zod.def;\n return new ZodMiniCodec({\n type: \"pipe\",\n in: def.out,\n out: def.in,\n transform: def.reverseTransform,\n reverseTransform: def.transform,\n });\n}\nexport const ZodMiniReadonly = /*@__PURE__*/ core.$constructor(\"ZodMiniReadonly\", (inst, def) => {\n core.$ZodReadonly.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function readonly(innerType) {\n return new ZodMiniReadonly({\n type: \"readonly\",\n innerType: innerType,\n });\n}\nexport const ZodMiniTemplateLiteral = /*@__PURE__*/ core.$constructor(\"ZodMiniTemplateLiteral\", (inst, def) => {\n core.$ZodTemplateLiteral.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function templateLiteral(parts, params) {\n return new ZodMiniTemplateLiteral({\n type: \"template_literal\",\n parts,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniLazy = /*@__PURE__*/ core.$constructor(\"ZodMiniLazy\", (inst, def) => {\n core.$ZodLazy.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// export function lazy<T extends object>(getter: () => T): T {\n// return util.createTransparentProxy<T>(getter);\n// }\n// @__NO_SIDE_EFFECTS__\nfunction _lazy(getter) {\n return new ZodMiniLazy({\n type: \"lazy\",\n getter: getter,\n });\n}\nexport { _lazy as lazy };\nexport const ZodMiniPromise = /*@__PURE__*/ core.$constructor(\"ZodMiniPromise\", (inst, def) => {\n core.$ZodPromise.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function promise(innerType) {\n return new ZodMiniPromise({\n type: \"promise\",\n innerType: innerType,\n });\n}\nexport const ZodMiniCustom = /*@__PURE__*/ core.$constructor(\"ZodMiniCustom\", (inst, def) => {\n core.$ZodCustom.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// custom checks\n// @__NO_SIDE_EFFECTS__\nexport function check(fn, params) {\n const ch = new core.$ZodCheck({\n check: \"custom\",\n ...util.normalizeParams(params),\n });\n ch._zod.check = fn;\n return ch;\n}\n// ZodCustom custom schema\n// @__NO_SIDE_EFFECTS__\nexport function custom(fn, _params) {\n return core._custom(ZodMiniCustom, fn ?? (() => true), _params);\n}\n// refine\n// @__NO_SIDE_EFFECTS__\nexport function refine(fn, _params = {}) {\n return core._refine(ZodMiniCustom, fn, _params);\n}\n// superRefine\n// @__NO_SIDE_EFFECTS__\nexport function superRefine(fn, params) {\n return core._superRefine(fn, params);\n}\n// Re-export describe and meta from core\nexport const describe = core.describe;\nexport const meta = core.meta;\n// instanceof\nclass Class {\n constructor(..._args) { }\n}\n// @__NO_SIDE_EFFECTS__\nfunction _instanceof(cls, params = {}) {\n const inst = custom((data) => data instanceof cls, params);\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: ZodMiniCodec,\n Boolean: ZodMiniBoolean,\n String: ZodMiniString,\n}, ...args);\n// @__NO_SIDE_EFFECTS__\nexport function json() {\n const jsonSchema = _lazy(() => {\n return union([string(), number(), boolean(), _null(), array(jsonSchema), record(string(), jsonSchema)]);\n });\n return jsonSchema;\n}\nexport const ZodMiniFunction = /*@__PURE__*/ core.$constructor(\"ZodMiniFunction\", (inst, def) => {\n core.$ZodFunction.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function _function(params) {\n return new ZodMiniFunction({\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 };\n","import * as core from \"../core/index.js\";\nimport * as schemas from \"./schemas.js\";\n// @__NO_SIDE_EFFECTS__\nexport function string(params) {\n return core._coercedString(schemas.ZodMiniString, params);\n}\n// @__NO_SIDE_EFFECTS__\nexport function number(params) {\n return core._coercedNumber(schemas.ZodMiniNumber, params);\n}\n// @__NO_SIDE_EFFECTS__\nexport function boolean(params) {\n return core._coercedBoolean(schemas.ZodMiniBoolean, params);\n}\n// @__NO_SIDE_EFFECTS__\nexport function bigint(params) {\n return core._coercedBigint(schemas.ZodMiniBigInt, params);\n}\n// @__NO_SIDE_EFFECTS__\nexport function date(params) {\n return core._coercedDate(schemas.ZodMiniDate, params);\n}\n","import * as z from \"zod/mini\";\n\n//#region upstream/framework/lib/property/input/common.ts\nconst BasePropertySchema = z.object({\n\tdisplayName: z.string(),\n\tdescription: z.optional(z.string()),\n\tadvanced: z.optional(z.boolean()),\n\twidth: z.optional(z.enum([\"half\", \"full\"])),\n\ticon: z.optional(z.string()),\n\tplaceholder: z.optional(z.string())\n});\nconst TPropertyValue = (_T, propertyType) => z.object({\n\ttype: z.literal(propertyType),\n\trequired: z.boolean(),\n\tdefaultValue: z.optional(z.any())\n});\n\n//#endregion\n//#region upstream/framework/lib/property/input/property-type.ts\nlet PropertyType = /* @__PURE__ */ function(PropertyType) {\n\tPropertyType[\"SHORT_TEXT\"] = \"SHORT_TEXT\";\n\tPropertyType[\"LONG_TEXT\"] = \"LONG_TEXT\";\n\tPropertyType[\"RICH_TEXT\"] = \"RICH_TEXT\";\n\tPropertyType[\"MARKDOWN\"] = \"MARKDOWN\";\n\tPropertyType[\"DROPDOWN\"] = \"DROPDOWN\";\n\tPropertyType[\"STATIC_DROPDOWN\"] = \"STATIC_DROPDOWN\";\n\tPropertyType[\"NUMBER\"] = \"NUMBER\";\n\tPropertyType[\"CHECKBOX\"] = \"CHECKBOX\";\n\tPropertyType[\"OAUTH2\"] = \"OAUTH2\";\n\tPropertyType[\"SECRET_TEXT\"] = \"SECRET_TEXT\";\n\tPropertyType[\"ARRAY\"] = \"ARRAY\";\n\tPropertyType[\"OBJECT\"] = \"OBJECT\";\n\tPropertyType[\"BASIC_AUTH\"] = \"BASIC_AUTH\";\n\tPropertyType[\"JSON\"] = \"JSON\";\n\tPropertyType[\"MULTI_SELECT_DROPDOWN\"] = \"MULTI_SELECT_DROPDOWN\";\n\tPropertyType[\"STATIC_MULTI_SELECT_DROPDOWN\"] = \"STATIC_MULTI_SELECT_DROPDOWN\";\n\tPropertyType[\"DYNAMIC\"] = \"DYNAMIC\";\n\tPropertyType[\"CUSTOM_AUTH\"] = \"CUSTOM_AUTH\";\n\tPropertyType[\"OIDC\"] = \"OIDC\";\n\tPropertyType[\"DATE_TIME\"] = \"DATE_TIME\";\n\tPropertyType[\"DATE_RANGE\"] = \"DATE_RANGE\";\n\tPropertyType[\"FILE\"] = \"FILE\";\n\tPropertyType[\"CUSTOM\"] = \"CUSTOM\";\n\tPropertyType[\"COLOR\"] = \"COLOR\";\n\treturn PropertyType;\n}({});\n\n//#endregion\n//#region upstream/framework/lib/property/input/text-property.ts\nconst ShortTextProperty = z.object({\n\t...BasePropertySchema.shape,\n\t...TPropertyValue(z.string(), \"SHORT_TEXT\").shape\n});\nconst LongTextProperty = z.object({\n\t...BasePropertySchema.shape,\n\t...TPropertyValue(z.string(), \"LONG_TEXT\").shape\n});\n\n//#endregion\n//#region upstream/framework/lib/property/input/dropdown/common.ts\nconst DropdownOption = z.object({\n\tlabel: z.string(),\n\tvalue: z.unknown(),\n\tdescription: z.optional(z.string()),\n\ticon: z.optional(z.string())\n});\nconst DropdownState = z.object({\n\tdisabled: z.optional(z.boolean()),\n\tplaceholder: z.optional(z.string()),\n\toptions: z.array(DropdownOption)\n});\n\n//#endregion\n//#region upstream/framework/lib/property/input/dropdown/static-dropdown.ts\nconst StaticDropdownDisplay = z.enum([\"cards\"]);\nconst StaticDropdownProperty = z.object({\n\t...BasePropertySchema.shape,\n\toptions: DropdownState,\n\tdisplay: z.optional(StaticDropdownDisplay),\n\t...TPropertyValue(z.unknown(), \"STATIC_DROPDOWN\").shape\n});\nconst StaticMultiSelectDropdownProperty = z.object({\n\t...BasePropertySchema.shape,\n\toptions: DropdownState,\n\t...TPropertyValue(z.array(z.unknown()), \"STATIC_MULTI_SELECT_DROPDOWN\").shape\n});\n\n//#endregion\n//#region upstream/framework/lib/property/input/checkbox-property.ts\nconst CheckboxProperty = z.object({\n\t...BasePropertySchema.shape,\n\treveals: z.optional(z.array(z.string())),\n\t...TPropertyValue(z.boolean(), \"CHECKBOX\").shape\n});\n\n//#endregion\n//#region upstream/framework/lib/property/input/number-property.ts\nconst NumberProperty = z.object({\n\t...BasePropertySchema.shape,\n\tdisplay: z.optional(z.enum([\"stepper\"])),\n\tmin: z.optional(z.number()),\n\tmax: z.optional(z.number()),\n\tstep: z.optional(z.number()),\n\t...TPropertyValue(z.number(), \"NUMBER\").shape\n});\n\n//#endregion\n//#region upstream/framework/lib/property/input/file-property.ts\nvar ApFile = class {\n\tfilename;\n\tdata;\n\textension;\n\tconstructor(filename, data, extension) {\n\t\tthis.filename = filename;\n\t\tthis.data = data;\n\t\tthis.extension = extension;\n\t}\n\tget base64() {\n\t\treturn this.data.toString(\"base64\");\n\t}\n};\nconst FileProperty = z.object({\n\t...BasePropertySchema.shape,\n\tstreaming: z.optional(z.boolean()),\n\t...TPropertyValue(z.unknown(), \"FILE\").shape\n});\n\n//#endregion\n//#region upstream/framework/lib/property/input/date-range-property.ts\nconst DateRangePreset = z.enum([\n\t\"any_time\",\n\t\"last_24_hours\",\n\t\"last_7_days\",\n\t\"last_30_days\",\n\t\"last_90_days\",\n\t\"this_month\",\n\t\"custom\"\n]);\nconst DateRangeValue = z.object({\n\tpreset: z.optional(DateRangePreset),\n\tafter: z.optional(z.string()),\n\tbefore: z.optional(z.string())\n});\nconst DateRangeProperty = z.object({\n\t...BasePropertySchema.shape,\n\tdisplay: z.optional(z.enum([\"dropdown\"])),\n\t...TPropertyValue(DateRangeValue, \"DATE_RANGE\").shape\n});\nfunction isoDaysAgo(days) {\n\treturn (/* @__PURE__ */ new Date(Date.now() - days * 24 * 60 * 60 * 1e3)).toISOString();\n}\nfunction startOfThisMonth() {\n\tconst now = /* @__PURE__ */ new Date();\n\treturn new Date(now.getFullYear(), now.getMonth(), 1).toISOString();\n}\nfunction resolve(value) {\n\tif (!value || !value.preset || value.preset === \"any_time\") return {};\n\tswitch (value.preset) {\n\t\tcase \"last_24_hours\": return { after: isoDaysAgo(1) };\n\t\tcase \"last_7_days\": return { after: isoDaysAgo(7) };\n\t\tcase \"last_30_days\": return { after: isoDaysAgo(30) };\n\t\tcase \"last_90_days\": return { after: isoDaysAgo(90) };\n\t\tcase \"this_month\": return { after: startOfThisMonth() };\n\t\tcase \"custom\": return {\n\t\t\tafter: value.after && value.after.length > 0 ? value.after : void 0,\n\t\t\tbefore: value.before && value.before.length > 0 ? value.before : void 0\n\t\t};\n\t\tdefault: return {};\n\t}\n}\nconst dateRangeUtils = { resolve };\n\n//#endregion\n//#region upstream/core-piece-types/lib/markdown.ts\nlet MarkdownVariant = /* @__PURE__ */ function(MarkdownVariant) {\n\tMarkdownVariant[\"BORDERLESS\"] = \"BORDERLESS\";\n\tMarkdownVariant[\"INFO\"] = \"INFO\";\n\tMarkdownVariant[\"WARNING\"] = \"WARNING\";\n\tMarkdownVariant[\"TIP\"] = \"TIP\";\n\treturn MarkdownVariant;\n}({});\n\n//#endregion\n//#region upstream/core-utils/lib/utils.ts\nfunction isString(str) {\n\treturn str != null && typeof str === \"string\";\n}\nfunction isNil(value) {\n\treturn value === null || value === void 0;\n}\nfunction kebabCase(str) {\n\treturn str.replace(/([a-z])([A-Z])/g, \"$1-$2\").replace(/\\s+/g, \"-\").replace(/_/g, \"-\").toLowerCase().replace(/^-+|-+$/g, \"\");\n}\nfunction isEmpty(value) {\n\tif (value == null) return true;\n\tif (typeof value === \"string\" || Array.isArray(value)) return value.length === 0;\n\tif (typeof value === \"object\") return Object.keys(value).length === 0;\n\treturn false;\n}\nfunction startCase(str) {\n\treturn str.replace(/([a-z])([A-Z])/g, \"$1 $2\").replace(/[_-]+/g, \" \").replace(/\\s+/g, \" \").replace(/^[a-z]/, (match) => match.toUpperCase()).replace(/\\b[a-z]/g, (match) => match.toUpperCase());\n}\nfunction camelCase(str) {\n\treturn str.replace(/([-_][a-z])/g, (group) => group.toUpperCase().replace(\"-\", \"\").replace(\"_\", \"\"));\n}\nfunction parseToJsonIfPossible(str) {\n\ttry {\n\t\treturn JSON.parse(str);\n\t} catch (e) {\n\t\treturn str;\n\t}\n}\nfunction pickBy(object, predicate) {\n\treturn Object.keys(object).reduce((result, key) => {\n\t\tif (predicate(object[key], key)) result[key] = object[key];\n\t\treturn result;\n\t}, {});\n}\nfunction chunk(records, size) {\n\tconst chunks = [];\n\tfor (let i = 0; i < records.length; i += size) chunks.push(records.slice(i, i + size));\n\treturn chunks;\n}\nfunction unique(array) {\n\tconst seen = /* @__PURE__ */ new Set();\n\treturn array.filter((item) => {\n\t\tconst key = JSON.stringify(item);\n\t\tif (seen.has(key)) return false;\n\t\tseen.add(key);\n\t\treturn true;\n\t});\n}\nconst INVALID_BASE64_CHARS = /[^A-Za-z0-9+/=]/;\nfunction isBase64(value, options) {\n\tif (!isString(value) || value.length === 0) return false;\n\tif (options?.allowMime) {\n\t\tconst base64MarkerIndex = value.indexOf(\";base64,\");\n\t\tif (base64MarkerIndex !== -1 && value.startsWith(\"data:\")) return _isValidBase64String(value.slice(base64MarkerIndex + 8));\n\t}\n\treturn _isValidBase64String(value);\n}\nfunction _isValidBase64String(str) {\n\tconst len = str.length;\n\tif (len === 0 || len % 4 !== 0 || INVALID_BASE64_CHARS.test(str)) return false;\n\tconst firstPaddingIndex = str.indexOf(\"=\");\n\treturn firstPaddingIndex === -1 || firstPaddingIndex === len - 1 || firstPaddingIndex === len - 2 && str[len - 1] === \"=\";\n}\n\n//#endregion\n//#region upstream/core-utils/lib/try-catch.ts\nasync function tryCatch(fn) {\n\ttry {\n\t\treturn {\n\t\t\tdata: await fn(),\n\t\t\terror: null\n\t\t};\n\t} catch (error) {\n\t\treturn {\n\t\t\tdata: null,\n\t\t\terror\n\t\t};\n\t}\n}\nfunction tryCatchSync(fn) {\n\ttry {\n\t\treturn {\n\t\t\tdata: fn(),\n\t\t\terror: null\n\t\t};\n\t} catch (error) {\n\t\treturn {\n\t\t\tdata: null,\n\t\t\terror\n\t\t};\n\t}\n}\n\n//#endregion\n//#region upstream/framework/lib/property/input/markdown-property.ts\nconst MarkDownProperty = z.object({\n\t...BasePropertySchema.shape,\n\t...TPropertyValue(z.void(), \"MARKDOWN\").shape,\n\tvariant: z.optional(z.enum(MarkdownVariant))\n});\n\n//#endregion\nexport { PropertyType as A, CheckboxProperty as C, DropdownState as D, DropdownOption as E, TPropertyValue as M, LongTextProperty as O, NumberProperty as S, StaticMultiSelectDropdownProperty as T, DateRangeProperty as _, chunk as a, ApFile as b, isNil as c, parseToJsonIfPossible as d, pickBy as f, DateRangePreset as g, MarkdownVariant as h, camelCase as i, BasePropertySchema as j, ShortTextProperty as k, isString as l, unique as m, tryCatch as n, isBase64 as o, startCase as p, tryCatchSync as r, isEmpty as s, MarkDownProperty as t, kebabCase as u, DateRangeValue as v, StaticDropdownProperty as w, FileProperty as x, dateRangeUtils as y };\n//# sourceMappingURL=markdown-property-DMfHjEiL.js.map","import { A as PropertyType, C as CheckboxProperty, M as TPropertyValue, O as LongTextProperty, S as NumberProperty, T as StaticMultiSelectDropdownProperty, _ as DateRangeProperty, h as MarkdownVariant, j as BasePropertySchema, k as ShortTextProperty, t as MarkDownProperty, w as StaticDropdownProperty, x as FileProperty } from \"./markdown-property-DMfHjEiL.js\";\nimport * as z from \"zod/mini\";\n\n//#region upstream/framework/lib/action/action.ts\nconst ErrorHandlingOptionsParam = z.object({\n\tretryOnFailure: z.object({\n\t\tdefaultValue: z.optional(z.boolean()),\n\t\thide: z.optional(z.boolean())\n\t}),\n\tcontinueOnFailure: z.object({\n\t\tdefaultValue: z.optional(z.boolean()),\n\t\thide: z.optional(z.boolean())\n\t})\n});\nvar IAction = class {\n\tname;\n\tdisplayName;\n\tdescription;\n\tprops;\n\tpropertyGroups;\n\trun;\n\ttest;\n\trequireAuth;\n\terrorHandlingOptions;\n\toutputSchema;\n\taudience;\n\taiMetadata;\n\tclassification;\n\tconstructor(name, displayName, description, props, propertyGroups, run, test, requireAuth, errorHandlingOptions, outputSchema, audience, aiMetadata, classification) {\n\t\tthis.name = name;\n\t\tthis.displayName = displayName;\n\t\tthis.description = description;\n\t\tthis.props = props;\n\t\tthis.propertyGroups = propertyGroups;\n\t\tthis.run = run;\n\t\tthis.test = test;\n\t\tthis.requireAuth = requireAuth;\n\t\tthis.errorHandlingOptions = errorHandlingOptions;\n\t\tthis.outputSchema = outputSchema;\n\t\tthis.audience = audience;\n\t\tthis.aiMetadata = aiMetadata;\n\t\tthis.classification = classification;\n\t}\n};\nconst createAction = (params) => {\n\treturn new IAction(params.name, params.displayName, params.description, params.props, params.propertyGroups, params.run, params.test ?? params.run, params.requireAuth ?? true, params.errorHandlingOptions ?? {\n\t\tcontinueOnFailure: { defaultValue: false },\n\t\tretryOnFailure: { defaultValue: false }\n\t}, params.outputSchema, params.audience, params.aiMetadata, params.classification);\n};\n\n//#endregion\n//#region upstream/framework/lib/property/input/dropdown/dropdown-prop.ts\nconst DropdownProperty = z.object({\n\t...BasePropertySchema.shape,\n\t...TPropertyValue(z.unknown(), \"DROPDOWN\").shape,\n\trefreshers: z.array(z.string())\n});\nconst MultiSelectDropdownProperty = z.object({\n\t...BasePropertySchema.shape,\n\t...TPropertyValue(z.array(z.unknown()), \"MULTI_SELECT_DROPDOWN\").shape,\n\trefreshers: z.array(z.string())\n});\n\n//#endregion\n//#region upstream/framework/lib/property/input/json-property.ts\nconst JsonProperty = z.object({\n\t...BasePropertySchema.shape,\n\t...TPropertyValue(z.union([z.record(z.string(), z.unknown())]), \"JSON\").shape\n});\n\n//#endregion\n//#region upstream/framework/lib/property/input/color-property.ts\nconst ColorProperty = z.object({\n\t...BasePropertySchema.shape,\n\t...TPropertyValue(z.string(), \"COLOR\").shape\n});\n\n//#endregion\n//#region upstream/framework/lib/property/input/date-time-property.ts\nconst DateTimeProperty = z.object({\n\t...BasePropertySchema.shape,\n\t...TPropertyValue(z.string(), \"DATE_TIME\").shape\n});\n\n//#endregion\n//#region upstream/framework/lib/property/input/array-property.ts\nconst ArraySubProps = z.record(z.string(), z.union([\n\tShortTextProperty,\n\tLongTextProperty,\n\tStaticDropdownProperty,\n\tMultiSelectDropdownProperty,\n\tStaticMultiSelectDropdownProperty,\n\tCheckboxProperty,\n\tNumberProperty,\n\tFileProperty,\n\tJsonProperty,\n\tColorProperty,\n\tDateTimeProperty\n]));\nconst ArrayProperty = z.object({\n\t...BasePropertySchema.shape,\n\tproperties: z.optional(ArraySubProps),\n\t...TPropertyValue(z.array(z.unknown()), \"ARRAY\").shape\n});\n\n//#endregion\n//#region upstream/framework/lib/property/input/dynamic-prop.ts\nconst DynamicProp = z.union([\n\tShortTextProperty,\n\tStaticDropdownProperty,\n\tJsonProperty,\n\tArrayProperty,\n\tStaticMultiSelectDropdownProperty\n]);\nconst DynamicPropsValue = z.record(z.string(), DynamicProp);\nconst DynamicProperties = z.object({\n\trefreshers: z.array(z.string()),\n\t...BasePropertySchema.shape,\n\t...TPropertyValue(z.unknown(), \"DYNAMIC\").shape\n});\n\n//#endregion\n//#region upstream/core-utils/lib/assertions.ts\nfunction assertNotNullOrUndefined(value, fieldName) {\n\tif (value === null || value === void 0) throw new Error(`${fieldName} is null or undefined`);\n}\nconst isNotUndefined = (value) => {\n\treturn value !== void 0;\n};\n\n//#endregion\n//#region upstream/framework/lib/property/input/object-property.ts\nconst ObjectProperty = z.object({\n\t...BasePropertySchema.shape,\n\t...TPropertyValue(z.record(z.string(), z.unknown()), \"OBJECT\").shape\n});\n\n//#endregion\n//#region upstream/framework/lib/property/input/rich-text-property.ts\nconst RichTextProperty = z.object({\n\t...BasePropertySchema.shape,\n\tformatProperty: z.optional(z.string()),\n\t...TPropertyValue(z.string(), \"RICH_TEXT\").shape\n});\n\n//#endregion\n//#region upstream/framework/lib/property/input/custom-property.ts\nconst CustomProperty = z.object({\n\t...BasePropertySchema.shape,\n\t...TPropertyValue(z.unknown(), \"CUSTOM\").shape,\n\tcode: z.string()\n});\n\n//#endregion\n//#region upstream/framework/lib/property/input/index.ts\nconst InputProperty = z.union([\n\tShortTextProperty,\n\tLongTextProperty,\n\tRichTextProperty,\n\tMarkDownProperty,\n\tCheckboxProperty,\n\tStaticDropdownProperty,\n\tStaticMultiSelectDropdownProperty,\n\tDropdownProperty,\n\tMultiSelectDropdownProperty,\n\tDynamicProperties,\n\tNumberProperty,\n\tArrayProperty,\n\tObjectProperty,\n\tJsonProperty,\n\tDateTimeProperty,\n\tDateRangeProperty,\n\tFileProperty,\n\tCustomProperty,\n\tColorProperty\n]);\nconst Property = {\n\tShortText(request) {\n\t\treturn {\n\t\t\t...request,\n\t\t\tvalueSchema: void 0,\n\t\t\ttype: \"SHORT_TEXT\"\n\t\t};\n\t},\n\tCheckbox(request) {\n\t\treturn {\n\t\t\t...request,\n\t\t\tvalueSchema: void 0,\n\t\t\ttype: \"CHECKBOX\"\n\t\t};\n\t},\n\tLongText(request) {\n\t\treturn {\n\t\t\t...request,\n\t\t\tvalueSchema: void 0,\n\t\t\ttype: \"LONG_TEXT\"\n\t\t};\n\t},\n\tRichText(request) {\n\t\treturn {\n\t\t\t...request,\n\t\t\tvalueSchema: void 0,\n\t\t\ttype: \"RICH_TEXT\"\n\t\t};\n\t},\n\tMarkDown(request) {\n\t\treturn {\n\t\t\tdisplayName: \"Markdown\",\n\t\t\trequired: false,\n\t\t\tdescription: request.value,\n\t\t\ttype: \"MARKDOWN\",\n\t\t\tvalueSchema: void 0,\n\t\t\tvariant: request.variant ?? \"INFO\"\n\t\t};\n\t},\n\tNumber(request) {\n\t\treturn {\n\t\t\t...request,\n\t\t\tvalueSchema: void 0,\n\t\t\ttype: \"NUMBER\"\n\t\t};\n\t},\n\tJson(request) {\n\t\treturn {\n\t\t\t...request,\n\t\t\tvalueSchema: void 0,\n\t\t\ttype: \"JSON\"\n\t\t};\n\t},\n\tArray(request) {\n\t\treturn {\n\t\t\t...request,\n\t\t\tvalueSchema: void 0,\n\t\t\ttype: \"ARRAY\"\n\t\t};\n\t},\n\tObject(request) {\n\t\treturn {\n\t\t\t...request,\n\t\t\tvalueSchema: void 0,\n\t\t\ttype: \"OBJECT\"\n\t\t};\n\t},\n\tDropdown(request) {\n\t\treturn {\n\t\t\t...request,\n\t\t\tvalueSchema: void 0,\n\t\t\ttype: \"DROPDOWN\"\n\t\t};\n\t},\n\tStaticDropdown(request) {\n\t\treturn {\n\t\t\t...request,\n\t\t\tvalueSchema: void 0,\n\t\t\ttype: \"STATIC_DROPDOWN\"\n\t\t};\n\t},\n\tMultiSelectDropdown(request) {\n\t\treturn {\n\t\t\t...request,\n\t\t\tvalueSchema: void 0,\n\t\t\ttype: \"MULTI_SELECT_DROPDOWN\"\n\t\t};\n\t},\n\tDynamicProperties(request) {\n\t\treturn {\n\t\t\t...request,\n\t\t\tvalueSchema: void 0,\n\t\t\ttype: \"DYNAMIC\"\n\t\t};\n\t},\n\tStaticMultiSelectDropdown(request) {\n\t\treturn {\n\t\t\t...request,\n\t\t\tvalueSchema: void 0,\n\t\t\ttype: \"STATIC_MULTI_SELECT_DROPDOWN\"\n\t\t};\n\t},\n\tDateTime(request) {\n\t\treturn {\n\t\t\t...request,\n\t\t\tvalueSchema: void 0,\n\t\t\ttype: \"DATE_TIME\"\n\t\t};\n\t},\n\tDateRange(request) {\n\t\treturn {\n\t\t\t...request,\n\t\t\tvalueSchema: void 0,\n\t\t\ttype: \"DATE_RANGE\"\n\t\t};\n\t},\n\tFile(request) {\n\t\treturn {\n\t\t\t...request,\n\t\t\tvalueSchema: void 0,\n\t\t\ttype: \"FILE\"\n\t\t};\n\t},\n\tCustom(request) {\n\t\tconst code = request.code.toString();\n\t\treturn {\n\t\t\t...request,\n\t\t\tcode,\n\t\t\tvalueSchema: void 0,\n\t\t\ttype: \"CUSTOM\"\n\t\t};\n\t},\n\tColor(request) {\n\t\treturn {\n\t\t\t...request,\n\t\t\tvalueSchema: void 0,\n\t\t\ttype: \"COLOR\"\n\t\t};\n\t}\n};\n\n//#endregion\nexport { ErrorHandlingOptionsParam as _, ObjectProperty as a, DynamicProp as c, ArrayProperty as d, ArraySubProps as f, MultiSelectDropdownProperty as g, DropdownProperty as h, RichTextProperty as i, DynamicProperties as l, JsonProperty as m, Property as n, assertNotNullOrUndefined as o, DateTimeProperty as p, CustomProperty as r, isNotUndefined as s, InputProperty as t, DynamicPropsValue as u, IAction as v, createAction as y };\n//# sourceMappingURL=input-BHkj_oP5.js.map","import { A as PropertyType, C as CheckboxProperty, M as TPropertyValue, O as LongTextProperty, S as NumberProperty, T as StaticMultiSelectDropdownProperty, c as isNil, k as ShortTextProperty, t as MarkDownProperty, w as StaticDropdownProperty } from \"./markdown-property-DMfHjEiL.js\";\nimport * as z from \"zod/mini\";\n\n//#region upstream/core-piece-types/lib/app-connection.ts\nlet AppConnectionType = /* @__PURE__ */ function(AppConnectionType) {\n\tAppConnectionType[\"OAUTH2\"] = \"OAUTH2\";\n\tAppConnectionType[\"PLATFORM_OAUTH2\"] = \"PLATFORM_OAUTH2\";\n\tAppConnectionType[\"CLOUD_OAUTH2\"] = \"CLOUD_OAUTH2\";\n\tAppConnectionType[\"SECRET_TEXT\"] = \"SECRET_TEXT\";\n\tAppConnectionType[\"BASIC_AUTH\"] = \"BASIC_AUTH\";\n\tAppConnectionType[\"CUSTOM_AUTH\"] = \"CUSTOM_AUTH\";\n\tAppConnectionType[\"OIDC\"] = \"OIDC\";\n\tAppConnectionType[\"NO_AUTH\"] = \"NO_AUTH\";\n\treturn AppConnectionType;\n}({});\nlet OAuth2GrantType = /* @__PURE__ */ function(OAuth2GrantType) {\n\tOAuth2GrantType[\"AUTHORIZATION_CODE\"] = \"authorization_code\";\n\tOAuth2GrantType[\"CLIENT_CREDENTIALS\"] = \"client_credentials\";\n\treturn OAuth2GrantType;\n}({});\nconst BOTH_CLIENT_CREDENTIALS_AND_AUTHORIZATION_CODE = \"both_client_credentials_and_authorization_code\";\n\n//#endregion\n//#region upstream/core-piece-types/lib/trigger.ts\nlet TriggerStrategy = /* @__PURE__ */ function(TriggerStrategy) {\n\tTriggerStrategy[\"POLLING\"] = \"POLLING\";\n\tTriggerStrategy[\"WEBHOOK\"] = \"WEBHOOK\";\n\tTriggerStrategy[\"APP_WEBHOOK\"] = \"APP_WEBHOOK\";\n\tTriggerStrategy[\"MANUAL\"] = \"MANUAL\";\n\treturn TriggerStrategy;\n}({});\nlet WebhookHandshakeStrategy = /* @__PURE__ */ function(WebhookHandshakeStrategy) {\n\tWebhookHandshakeStrategy[\"NONE\"] = \"NONE\";\n\tWebhookHandshakeStrategy[\"HEADER_PRESENT\"] = \"HEADER_PRESENT\";\n\tWebhookHandshakeStrategy[\"QUERY_PRESENT\"] = \"QUERY_PRESENT\";\n\tWebhookHandshakeStrategy[\"BODY_PARAM_PRESENT\"] = \"BODY_PARAM_PRESENT\";\n\tWebhookHandshakeStrategy[\"HEAD_REQUEST\"] = \"HEAD_REQUEST\";\n\treturn WebhookHandshakeStrategy;\n}({});\nconst WebhookHandshakeConfiguration = z.object({\n\tstrategy: z.enum(WebhookHandshakeStrategy),\n\tparamName: z.optional(z.string())\n});\nlet TriggerTestStrategy = /* @__PURE__ */ function(TriggerTestStrategy) {\n\tTriggerTestStrategy[\"SIMULATION\"] = \"SIMULATION\";\n\tTriggerTestStrategy[\"TEST_FUNCTION\"] = \"TEST_FUNCTION\";\n\treturn TriggerTestStrategy;\n}({});\nconst AUTHENTICATION_PROPERTY_NAME = \"auth\";\n\n//#endregion\n//#region upstream/core-utils/lib/object-utils.ts\nconst spreadIfDefined = (key, value) => {\n\tif (isNil(value)) return {};\n\treturn { [key]: value };\n};\nconst isObject = (obj) => {\n\treturn typeof obj === \"object\" && obj !== null && !Array.isArray(obj);\n};\n\n//#endregion\n//#region upstream/framework/lib/property/authentication/common.ts\nconst BasePieceAuthSchema = z.object({\n\tdisplayName: z.string(),\n\tdescription: z.optional(z.string()),\n\thasConnectionIdentifier: z.optional(z.boolean())\n});\n\n//#endregion\n//#region upstream/framework/lib/property/authentication/basic-auth-prop.ts\nconst BasicAuthPropertyValue = z.object({\n\tusername: z.string(),\n\tpassword: z.string()\n});\nconst BasicAuthProperty = z.object({\n\t...BasePieceAuthSchema.shape,\n\tusername: z.object({\n\t\tdisplayName: z.string(),\n\t\tdescription: z.optional(z.string())\n\t}),\n\tpassword: z.object({\n\t\tdisplayName: z.string(),\n\t\tdescription: z.optional(z.string())\n\t}),\n\t...TPropertyValue(BasicAuthPropertyValue, \"BASIC_AUTH\").shape\n});\n\n//#endregion\n//#region upstream/framework/lib/property/authentication/secret-text-property.ts\nconst SecretTextProperty = z.object({\n\t...BasePieceAuthSchema.shape,\n\t...TPropertyValue(z.object({ auth: z.string() }), \"SECRET_TEXT\").shape\n});\n\n//#endregion\n//#region upstream/framework/lib/property/authentication/custom-auth-prop.ts\nconst CustomAuthProps = z.record(z.string(), z.union([\n\tShortTextProperty,\n\tLongTextProperty,\n\tSecretTextProperty,\n\tNumberProperty,\n\tStaticDropdownProperty,\n\tCheckboxProperty,\n\tMarkDownProperty,\n\tStaticMultiSelectDropdownProperty\n]));\nconst CustomAuthProperty = z.object({\n\t...BasePieceAuthSchema.shape,\n\tprops: CustomAuthProps,\n\t...TPropertyValue(z.unknown(), \"CUSTOM_AUTH\").shape\n});\n\n//#endregion\n//#region upstream/framework/lib/property/authentication/oidc-prop.ts\nconst OIDCAuthProps = z.record(z.string(), z.union([\n\tShortTextProperty,\n\tLongTextProperty,\n\tSecretTextProperty,\n\tNumberProperty,\n\tCheckboxProperty,\n\tStaticDropdownProperty,\n\tStaticMultiSelectDropdownProperty,\n\tMarkDownProperty\n]));\nconst OIDCProperty = z.object({\n\t...BasePieceAuthSchema.shape,\n\tprops: OIDCAuthProps,\n\t...TPropertyValue(z.unknown(), \"OIDC\").shape\n});\n\n//#endregion\n//#region upstream/framework/lib/property/authentication/oauth2-prop.ts\nlet OAuth2AuthorizationMethod = /* @__PURE__ */ function(OAuth2AuthorizationMethod) {\n\tOAuth2AuthorizationMethod[\"HEADER\"] = \"HEADER\";\n\tOAuth2AuthorizationMethod[\"BODY\"] = \"BODY\";\n\treturn OAuth2AuthorizationMethod;\n}({});\nconst OAuthProp = z.union([\n\tShortTextProperty,\n\tSecretTextProperty,\n\tStaticDropdownProperty\n]);\nconst OAuth2Props = z.record(z.string(), OAuthProp);\nconst OAuth2ExtraProps = z.object({\n\tprops: z.optional(z.record(z.string(), OAuthProp)),\n\tauthUrl: z.string(),\n\ttokenUrl: z.string(),\n\tscope: z.array(z.string()),\n\tprompt: z.optional(z.union([\n\t\tz.literal(\"none\"),\n\t\tz.literal(\"consent\"),\n\t\tz.literal(\"login\"),\n\t\tz.literal(\"omit\")\n\t])),\n\tpkce: z.optional(z.boolean()),\n\tpkceMethod: z.optional(z.union([z.literal(\"plain\"), z.literal(\"S256\")])),\n\tauthorizationMethod: z.optional(z.enum(OAuth2AuthorizationMethod)),\n\tgrantType: z.optional(z.union([z.enum(OAuth2GrantType), z.literal(BOTH_CLIENT_CREDENTIALS_AND_AUTHORIZATION_CODE)])),\n\textra: z.optional(z.record(z.string(), z.string()))\n});\nconst OAuth2PropertyValue = z.object({\n\taccess_token: z.string(),\n\tprops: z.optional(OAuth2Props),\n\tdata: z.record(z.string(), z.any())\n});\nconst OAuth2Property = z.object({\n\t...BasePieceAuthSchema.shape,\n\t...OAuth2ExtraProps.shape,\n\t...TPropertyValue(OAuth2PropertyValue, \"OAUTH2\").shape\n});\n\n//#endregion\n//#region upstream/framework/lib/property/authentication/index.ts\nconst PieceAuthProperty = z.union([\n\tBasicAuthProperty,\n\tCustomAuthProperty,\n\tOIDCProperty,\n\tOAuth2Property,\n\tSecretTextProperty\n]);\nconst DEFAULT_CONNECTION_DISPLAY_NAME = \"Connection\";\nconst PieceAuth = {\n\tSecretText(request) {\n\t\treturn {\n\t\t\t...request,\n\t\t\tvalueSchema: void 0,\n\t\t\ttype: \"SECRET_TEXT\"\n\t\t};\n\t},\n\tOAuth2(request) {\n\t\treturn {\n\t\t\t...request,\n\t\t\tvalueSchema: void 0,\n\t\t\ttype: \"OAUTH2\",\n\t\t\tdisplayName: request.displayName || \"Connection\"\n\t\t};\n\t},\n\tBasicAuth(request) {\n\t\treturn {\n\t\t\t...request,\n\t\t\tvalueSchema: void 0,\n\t\t\ttype: \"BASIC_AUTH\",\n\t\t\tdisplayName: request.displayName || \"Connection\",\n\t\t\trequired: true\n\t\t};\n\t},\n\tCustomAuth(request) {\n\t\treturn {\n\t\t\t...request,\n\t\t\tvalueSchema: void 0,\n\t\t\ttype: \"CUSTOM_AUTH\",\n\t\t\tdisplayName: request.displayName || \"Connection\"\n\t\t};\n\t},\n\tOIDC(request) {\n\t\treturn {\n\t\t\t...request,\n\t\t\tvalueSchema: void 0,\n\t\t\ttype: \"OIDC\",\n\t\t\tdisplayName: request.displayName || \"Connection\"\n\t\t};\n\t},\n\tNone() {}\n};\nfunction getAuthPropertyForValue({ authValueType, pieceAuth }) {\n\tif (!Array.isArray(pieceAuth) || isNil(pieceAuth)) return pieceAuth;\n\treturn pieceAuth.find((auth) => authConnectionTypeToPropertyType[authValueType] === auth.type) ?? pieceAuth.at(0);\n}\nconst authConnectionTypeToPropertyType = {\n\t[\"OAUTH2\"]: \"OAUTH2\",\n\t[\"CLOUD_OAUTH2\"]: \"OAUTH2\",\n\t[\"PLATFORM_OAUTH2\"]: \"OAUTH2\",\n\t[\"BASIC_AUTH\"]: \"BASIC_AUTH\",\n\t[\"CUSTOM_AUTH\"]: \"CUSTOM_AUTH\",\n\t[\"OIDC\"]: \"OIDC\",\n\t[\"SECRET_TEXT\"]: \"SECRET_TEXT\",\n\t[\"NO_AUTH\"]: void 0\n};\n\n//#endregion\nexport { TriggerStrategy as _, OAuth2AuthorizationMethod as a, AppConnectionType as b, OAuth2Props as c, SecretTextProperty as d, BasicAuthProperty as f, AUTHENTICATION_PROPERTY_NAME as g, spreadIfDefined as h, getAuthPropertyForValue as i, OIDCProperty as l, isObject as m, PieceAuth as n, OAuth2Property as o, BasicAuthPropertyValue as p, PieceAuthProperty as r, OAuth2PropertyValue as s, DEFAULT_CONNECTION_DISPLAY_NAME as t, CustomAuthProperty as u, TriggerTestStrategy as v, OAuth2GrantType as x, WebhookHandshakeStrategy as y };\n//# sourceMappingURL=authentication-o-4CdAPR.js.map","import crypto from 'crypto'\n\nimport { urlAlphabet } from './url-alphabet/index.js'\n\nconst POOL_SIZE_MULTIPLIER = 128\nlet pool, poolOffset\n\nlet fillPool = bytes => {\n if (bytes < 0) throw new RangeError('Wrong ID size')\n try {\n if (!pool || pool.length < bytes) {\n pool = Buffer.allocUnsafe(bytes * POOL_SIZE_MULTIPLIER)\n crypto.randomFillSync(pool)\n poolOffset = 0\n } else if (poolOffset + bytes > pool.length) {\n crypto.randomFillSync(pool)\n poolOffset = 0\n }\n } catch (e) {\n pool = undefined\n throw e\n }\n poolOffset += bytes\n}\n\nlet random = bytes => {\n fillPool((bytes |= 0))\n return pool.subarray(poolOffset - bytes, poolOffset)\n}\n\nlet customRandom = (alphabet, defaultSize, getRandom) => {\n let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1\n\n\n let step = Math.ceil((1.6 * mask * defaultSize) / alphabet.length)\n\n return (size = defaultSize) => {\n if (size <= 0) return ''\n let id = ''\n while (true) {\n let bytes = getRandom(step)\n let i = step\n while (i--) {\n id += alphabet[bytes[i] & mask] || ''\n if (id.length === size) return id\n }\n }\n }\n}\n\nlet customAlphabet = (alphabet, size = 21) =>\n customRandom(alphabet, size, random)\n\nlet nanoid = (size = 21) => {\n fillPool((size |= 0))\n let id = ''\n for (let i = poolOffset - size; i < poolOffset; i++) {\n id += urlAlphabet[pool[i] & 63]\n }\n return id\n}\n\nexport { nanoid, customAlphabet, customRandom, urlAlphabet, random }\n","import { _ as ErrorHandlingOptionsParam, a as ObjectProperty, c as DynamicProp, d as ArrayProperty, f as ArraySubProps, g as MultiSelectDropdownProperty, h as DropdownProperty, i as RichTextProperty, l as DynamicProperties, m as JsonProperty, n as Property$1, o as assertNotNullOrUndefined, p as DateTimeProperty, r as CustomProperty, s as isNotUndefined, t as InputProperty, u as DynamicPropsValue, v as IAction, y as createAction$1 } from \"./input-BHkj_oP5.js\";\nimport { A as PropertyType, C as CheckboxProperty, D as DropdownState, E as DropdownOption, O as LongTextProperty, S as NumberProperty, T as StaticMultiSelectDropdownProperty, _ as DateRangeProperty, a as chunk, b as ApFile, c as isNil, f as pickBy, g as DateRangePreset, h as MarkdownVariant, i as camelCase, j as BasePropertySchema, k as ShortTextProperty, l as isString, m as unique, n as tryCatch, p as startCase, s as isEmpty, u as kebabCase, v as DateRangeValue, w as StaticDropdownProperty, x as FileProperty, y as dateRangeUtils } from \"./markdown-property-DMfHjEiL.js\";\nimport { _ as TriggerStrategy, a as OAuth2AuthorizationMethod, b as AppConnectionType, c as OAuth2Props, d as SecretTextProperty, f as BasicAuthProperty, g as AUTHENTICATION_PROPERTY_NAME, h as spreadIfDefined, i as getAuthPropertyForValue, l as OIDCProperty, n as PieceAuth, o as OAuth2Property, p as BasicAuthPropertyValue, r as PieceAuthProperty, s as OAuth2PropertyValue, t as DEFAULT_CONNECTION_DISPLAY_NAME, u as CustomAuthProperty, v as TriggerTestStrategy, x as OAuth2GrantType, y as WebhookHandshakeStrategy } from \"./authentication-o-4CdAPR.js\";\nimport * as z from \"zod/mini\";\nimport { customAlphabet } from \"nanoid\";\nimport path from \"node:path\";\nimport fs from \"node:fs/promises\";\n\n//#region upstream/core-piece-types/lib/piece.ts\nlet PackageType = /* @__PURE__ */ function(PackageType) {\n\tPackageType[\"ARCHIVE\"] = \"ARCHIVE\";\n\tPackageType[\"REGISTRY\"] = \"REGISTRY\";\n\treturn PackageType;\n}({});\nlet PieceType = /* @__PURE__ */ function(PieceType) {\n\tPieceType[\"CUSTOM\"] = \"CUSTOM\";\n\tPieceType[\"OFFICIAL\"] = \"OFFICIAL\";\n\treturn PieceType;\n}({});\nlet PieceCategory = /* @__PURE__ */ function(PieceCategory) {\n\tPieceCategory[\"ARTIFICIAL_INTELLIGENCE\"] = \"ARTIFICIAL_INTELLIGENCE\";\n\tPieceCategory[\"COMMUNICATION\"] = \"COMMUNICATION\";\n\tPieceCategory[\"COMMERCE\"] = \"COMMERCE\";\n\tPieceCategory[\"CORE\"] = \"CORE\";\n\tPieceCategory[\"UNIVERSAL_AI\"] = \"UNIVERSAL_AI\";\n\tPieceCategory[\"FLOW_CONTROL\"] = \"FLOW_CONTROL\";\n\tPieceCategory[\"BUSINESS_INTELLIGENCE\"] = \"BUSINESS_INTELLIGENCE\";\n\tPieceCategory[\"ACCOUNTING\"] = \"ACCOUNTING\";\n\tPieceCategory[\"PRODUCTIVITY\"] = \"PRODUCTIVITY\";\n\tPieceCategory[\"CONTENT_AND_FILES\"] = \"CONTENT_AND_FILES\";\n\tPieceCategory[\"DEVELOPER_TOOLS\"] = \"DEVELOPER_TOOLS\";\n\tPieceCategory[\"CUSTOMER_SUPPORT\"] = \"CUSTOMER_SUPPORT\";\n\tPieceCategory[\"FORMS_AND_SURVEYS\"] = \"FORMS_AND_SURVEYS\";\n\tPieceCategory[\"HUMAN_RESOURCES\"] = \"HUMAN_RESOURCES\";\n\tPieceCategory[\"PAYMENT_PROCESSING\"] = \"PAYMENT_PROCESSING\";\n\tPieceCategory[\"MARKETING\"] = \"MARKETING\";\n\tPieceCategory[\"SALES_AND_CRM\"] = \"SALES_AND_CRM\";\n\treturn PieceCategory;\n}({});\n\n//#endregion\n//#region upstream/core-piece-types/lib/execution.ts\nlet ExecutionType = /* @__PURE__ */ function(ExecutionType) {\n\tExecutionType[\"BEGIN\"] = \"BEGIN\";\n\tExecutionType[\"RESUME\"] = \"RESUME\";\n\treturn ExecutionType;\n}({});\nlet StreamStepProgress = /* @__PURE__ */ function(StreamStepProgress) {\n\tStreamStepProgress[\"WEBSOCKET\"] = \"WEBSOCKET\";\n\tStreamStepProgress[\"NONE\"] = \"NONE\";\n\treturn StreamStepProgress;\n}({});\nconst RespondResponse = z.object({\n\tstatus: z.optional(z.number()),\n\tbody: z.optional(z.unknown()),\n\theaders: z.optional(z.record(z.string(), z.string()))\n});\nconst DelayPauseMetadata = z.object({\n\ttype: z.literal(\"DELAY\"),\n\tresumeDateTime: z.string(),\n\trequestIdToReply: z.optional(z.string()),\n\thandlerId: z.optional(z.string()),\n\tstreamStepProgress: z.optional(z.enum(StreamStepProgress))\n});\nconst WebhookPauseMetadata = z.object({\n\ttype: z.literal(\"WEBHOOK\"),\n\trequestId: z.string(),\n\trequestIdToReply: z.optional(z.string()),\n\tresponse: RespondResponse,\n\thandlerId: z.optional(z.string()),\n\tstreamStepProgress: z.optional(z.enum(StreamStepProgress))\n});\nconst PauseMetadata = z.union([DelayPauseMetadata, WebhookPauseMetadata]);\n\n//#endregion\n//#region upstream/core-utils/lib/id-generator.ts\nconst ALPHABET = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\";\nconst ID_LENGTH = 21;\nconst ApId = z.string().check(z.regex(new RegExp(`^[0-9a-zA-Z]{${ID_LENGTH}}$`)));\nconst apId = customAlphabet(ALPHABET, ID_LENGTH);\n\n//#endregion\n//#region upstream/core-utils/lib/base-model.ts\nconst DateOrString = z.pipe(z.transform((val) => val instanceof Date ? val.toISOString() : val), z.string());\nconst BaseModelSchema = {\n\tid: z.string(),\n\tcreated: DateOrString,\n\tupdated: DateOrString\n};\nconst Nullable = (schema) => z.optional(z.nullable(schema));\nfunction NullableEnum(enumObj) {\n\treturn z.optional(z.nullable(z.enum(enumObj)));\n}\nconst OptionalBooleanFromQuery = z.pipe(z.transform((val) => val === \"true\" || val === true ? true : val === \"false\" || val === false ? false : void 0), z.optional(z.boolean()));\nconst OptionalArrayFromQuery = (schema) => z.pipe(z.transform((val) => Array.isArray(val) ? val : val !== void 0 ? [val] : void 0), z.optional(z.array(schema)));\n\n//#endregion\n//#region upstream/core-utils/lib/seek-page.ts\nconst SeekPage = (t) => z.object({\n\tdata: z.array(t),\n\tnext: Nullable(z.string()),\n\tprevious: Nullable(z.string())\n});\n\n//#endregion\n//#region upstream/core-utils/lib/locale.ts\nlet LocalesEnum = /* @__PURE__ */ function(LocalesEnum) {\n\tLocalesEnum[\"DUTCH\"] = \"nl\";\n\tLocalesEnum[\"ENGLISH\"] = \"en\";\n\tLocalesEnum[\"GERMAN\"] = \"de\";\n\tLocalesEnum[\"FRENCH\"] = \"fr\";\n\tLocalesEnum[\"SPANISH\"] = \"es\";\n\tLocalesEnum[\"JAPANESE\"] = \"ja\";\n\tLocalesEnum[\"CHINESE_SIMPLIFIED\"] = \"zh\";\n\tLocalesEnum[\"PORTUGUESE\"] = \"pt\";\n\tLocalesEnum[\"ARABIC\"] = \"ar\";\n\tLocalesEnum[\"CHINESE_TRADITIONAL\"] = \"zh-TW\";\n\treturn LocalesEnum;\n}({});\n\n//#endregion\n//#region upstream/core-utils/lib/permission.ts\nlet AIProviderName = /* @__PURE__ */ function(AIProviderName) {\n\tAIProviderName[\"OPENAI\"] = \"openai\";\n\tAIProviderName[\"OPENROUTER\"] = \"openrouter\";\n\tAIProviderName[\"ANTHROPIC\"] = \"anthropic\";\n\tAIProviderName[\"AZURE\"] = \"azure\";\n\tAIProviderName[\"GOOGLE\"] = \"google\";\n\tAIProviderName[\"ACTIVEPIECES\"] = \"activepieces\";\n\tAIProviderName[\"CLOUDFLARE_GATEWAY\"] = \"cloudflare-gateway\";\n\tAIProviderName[\"CUSTOM\"] = \"custom\";\n\tAIProviderName[\"BEDROCK\"] = \"bedrock\";\n\tAIProviderName[\"VERTEX\"] = \"vertex\";\n\tAIProviderName[\"MISTRAL\"] = \"mistral\";\n\tAIProviderName[\"XAI\"] = \"xai\";\n\tAIProviderName[\"DEEPSEEK\"] = \"deepseek\";\n\tAIProviderName[\"ZAI\"] = \"zai\";\n\tAIProviderName[\"QWEN\"] = \"qwen\";\n\tAIProviderName[\"MINIMAX\"] = \"minimax\";\n\tAIProviderName[\"MOONSHOT\"] = \"moonshot\";\n\treturn AIProviderName;\n}({});\n\n//#endregion\n//#region upstream/core-piece-types/lib/agents.ts\nconst TASK_COMPLETION_TOOL_NAME = \"updateTaskStatus\";\nlet AgentToolType = /* @__PURE__ */ function(AgentToolType) {\n\tAgentToolType[\"PIECE\"] = \"PIECE\";\n\tAgentToolType[\"FLOW\"] = \"FLOW\";\n\tAgentToolType[\"MCP\"] = \"MCP\";\n\tAgentToolType[\"KNOWLEDGE_BASE\"] = \"KNOWLEDGE_BASE\";\n\treturn AgentToolType;\n}({});\nlet FieldControlMode = /* @__PURE__ */ function(FieldControlMode) {\n\tFieldControlMode[\"AGENT_DECIDE\"] = \"agent-decide\";\n\tFieldControlMode[\"CHOOSE_YOURSELF\"] = \"choose-yourself\";\n\tFieldControlMode[\"LEAVE_EMPTY\"] = \"leave-empty\";\n\treturn FieldControlMode;\n}({});\nlet KnowledgeBaseSourceType = /* @__PURE__ */ function(KnowledgeBaseSourceType) {\n\tKnowledgeBaseSourceType[\"FILE\"] = \"FILE\";\n\tKnowledgeBaseSourceType[\"TABLE\"] = \"TABLE\";\n\treturn KnowledgeBaseSourceType;\n}({});\nlet McpProtocol = /* @__PURE__ */ function(McpProtocol) {\n\tMcpProtocol[\"SSE\"] = \"sse\";\n\tMcpProtocol[\"STREAMABLE_HTTP\"] = \"streamable-http\";\n\tMcpProtocol[\"SIMPLE_HTTP\"] = \"http\";\n\treturn McpProtocol;\n}({});\nlet McpAuthType = /* @__PURE__ */ function(McpAuthType) {\n\tMcpAuthType[\"NONE\"] = \"none\";\n\tMcpAuthType[\"ACCESS_TOKEN\"] = \"access_token\";\n\tMcpAuthType[\"API_KEY\"] = \"api_key\";\n\tMcpAuthType[\"HEADERS\"] = \"headers\";\n\treturn McpAuthType;\n}({});\nlet AgentOutputFieldType = /* @__PURE__ */ function(AgentOutputFieldType) {\n\tAgentOutputFieldType[\"TEXT\"] = \"text\";\n\tAgentOutputFieldType[\"NUMBER\"] = \"number\";\n\tAgentOutputFieldType[\"BOOLEAN\"] = \"boolean\";\n\treturn AgentOutputFieldType;\n}({});\nlet AgentTaskStatus = /* @__PURE__ */ function(AgentTaskStatus) {\n\tAgentTaskStatus[\"COMPLETED\"] = \"COMPLETED\";\n\tAgentTaskStatus[\"FAILED\"] = \"FAILED\";\n\tAgentTaskStatus[\"IN_PROGRESS\"] = \"IN_PROGRESS\";\n\treturn AgentTaskStatus;\n}({});\nlet ContentBlockType = /* @__PURE__ */ function(ContentBlockType) {\n\tContentBlockType[\"MARKDOWN\"] = \"MARKDOWN\";\n\tContentBlockType[\"TOOL_CALL\"] = \"TOOL_CALL\";\n\treturn ContentBlockType;\n}({});\nlet ToolCallStatus = /* @__PURE__ */ function(ToolCallStatus) {\n\tToolCallStatus[\"IN_PROGRESS\"] = \"in-progress\";\n\tToolCallStatus[\"COMPLETED\"] = \"completed\";\n\treturn ToolCallStatus;\n}({});\nlet ExecutionToolStatus = /* @__PURE__ */ function(ExecutionToolStatus) {\n\tExecutionToolStatus[\"SUCCESS\"] = \"SUCCESS\";\n\tExecutionToolStatus[\"FAILED\"] = \"FAILED\";\n\treturn ExecutionToolStatus;\n}({});\nlet ToolCallType = /* @__PURE__ */ function(ToolCallType) {\n\tToolCallType[\"PIECE\"] = \"PIECE\";\n\tToolCallType[\"FLOW\"] = \"FLOW\";\n\tToolCallType[\"MCP\"] = \"MCP\";\n\tToolCallType[\"KNOWLEDGE_BASE\"] = \"KNOWLEDGE_BASE\";\n\tToolCallType[\"UNKNOWN\"] = \"UNKNOWN\";\n\treturn ToolCallType;\n}({});\nlet AgentPieceProps = /* @__PURE__ */ function(AgentPieceProps) {\n\tAgentPieceProps[\"AGENT_ID\"] = \"agentId\";\n\tAgentPieceProps[\"AGENT_TOOLS\"] = \"agentTools\";\n\tAgentPieceProps[\"STRUCTURED_OUTPUT\"] = \"structuredOutput\";\n\tAgentPieceProps[\"PROMPT\"] = \"prompt\";\n\tAgentPieceProps[\"MAX_STEPS\"] = \"maxSteps\";\n\tAgentPieceProps[\"AI_PROVIDER_MODEL\"] = \"aiProviderModel\";\n\tAgentPieceProps[\"WEB_SEARCH\"] = \"webSearch\";\n\tAgentPieceProps[\"WEB_SEARCH_OPTIONS\"] = \"webSearchOptions\";\n\treturn AgentPieceProps;\n}({});\nconst PredefinedInputField = z.object({\n\tmode: z.enum(FieldControlMode),\n\tvalue: z.unknown()\n});\nconst PredefinedInputsStructure = z.object({\n\tauth: z.optional(z.string()),\n\tfields: z.record(z.string(), PredefinedInputField)\n});\nconst AgentPieceToolMetadata = z.object({\n\tpieceName: z.string(),\n\tpieceVersion: z.string(),\n\tactionName: z.string(),\n\tpredefinedInput: z.optional(PredefinedInputsStructure)\n});\nconst AgentPieceTool = z.object({\n\ttype: z.literal(\"PIECE\"),\n\ttoolName: z.string().check(z.minLength(1)),\n\tpieceMetadata: AgentPieceToolMetadata\n});\nconst McpAuthNone = z.object({ type: z.literal(\"none\") });\nconst McpAuthAccessToken = z.object({\n\ttype: z.literal(\"access_token\"),\n\taccessToken: z.string()\n});\nconst McpAuthApiKey = z.object({\n\ttype: z.literal(\"api_key\"),\n\tapiKey: z.string(),\n\tapiKeyHeader: z.string()\n});\nconst McpAuthHeaders = z.object({\n\ttype: z.literal(\"headers\"),\n\theaders: z.record(z.string(), z.string())\n});\nconst McpAuthConfig = z.discriminatedUnion(\"type\", [\n\tMcpAuthNone,\n\tMcpAuthAccessToken,\n\tMcpAuthApiKey,\n\tMcpAuthHeaders\n]);\nconst AgentFlowTool = z.object({\n\ttype: z.literal(\"FLOW\"),\n\ttoolName: z.string().check(z.minLength(1)),\n\texternalFlowId: z.string(),\n\tflowDisplayName: z.optional(z.string())\n});\nconst AgentMcpTool = z.object({\n\ttype: z.literal(\"MCP\"),\n\ttoolName: z.string().check(z.minLength(1)),\n\tserverUrl: z.url(),\n\tprotocol: z.enum(McpProtocol),\n\tauth: McpAuthConfig\n});\nconst AgentKnowledgeBaseTool = z.object({\n\ttype: z.literal(\"KNOWLEDGE_BASE\"),\n\ttoolName: z.string().check(z.minLength(1)),\n\tsourceType: z.enum(KnowledgeBaseSourceType),\n\tsourceId: z.string(),\n\tsourceName: z.string()\n});\nconst AgentTool = z.discriminatedUnion(\"type\", [\n\tAgentPieceTool,\n\tAgentFlowTool,\n\tAgentMcpTool,\n\tAgentKnowledgeBaseTool\n]);\nconst AgentOutputField = z.object({\n\tdisplayName: z.string(),\n\tdescription: z.optional(z.string()),\n\ttype: z.enum(AgentOutputFieldType)\n});\nconst MarkdownContentBlock = z.object({\n\ttype: z.literal(\"MARKDOWN\"),\n\tmarkdown: z.string()\n});\nconst toolCallBaseShape = {\n\ttype: z.literal(\"TOOL_CALL\"),\n\tinput: Nullable(z.record(z.string(), z.unknown())),\n\toutput: z.optional(z.unknown()),\n\ttoolName: z.string(),\n\tstatus: z.enum(ToolCallStatus),\n\ttoolCallId: z.string(),\n\tstartTime: z.string(),\n\tendTime: z.optional(z.string())\n};\nz.object(toolCallBaseShape);\nconst ToolCallContentBlock = z.discriminatedUnion(\"toolCallType\", [\n\tz.object({\n\t\t...toolCallBaseShape,\n\t\ttoolCallType: z.literal(\"PIECE\"),\n\t\tpieceName: z.string(),\n\t\tpieceVersion: z.string(),\n\t\tactionName: z.string()\n\t}),\n\tz.object({\n\t\t...toolCallBaseShape,\n\t\ttoolCallType: z.literal(\"FLOW\"),\n\t\tdisplayName: z.string(),\n\t\texternalFlowId: z.string()\n\t}),\n\tz.object({\n\t\t...toolCallBaseShape,\n\t\ttoolCallType: z.literal(\"MCP\"),\n\t\tdisplayName: z.string(),\n\t\tserverUrl: z.string()\n\t}),\n\tz.object({\n\t\t...toolCallBaseShape,\n\t\ttoolCallType: z.literal(\"KNOWLEDGE_BASE\"),\n\t\tdisplayName: z.string(),\n\t\tsourceType: z.string()\n\t}),\n\tz.object({\n\t\t...toolCallBaseShape,\n\t\ttoolCallType: z.literal(\"UNKNOWN\"),\n\t\tdisplayName: z.string()\n\t})\n]);\nconst AgentStepBlock = z.union([MarkdownContentBlock, ToolCallContentBlock]);\nfunction buildAuthHeaders(authConfig) {\n\tlet headers = {};\n\tswitch (authConfig.type) {\n\t\tcase \"none\": break;\n\t\tcase \"headers\":\n\t\t\theaders = authConfig.headers;\n\t\t\tbreak;\n\t\tcase \"access_token\":\n\t\t\theaders[\"Authorization\"] = `Bearer ${authConfig.accessToken}`;\n\t\t\tbreak;\n\t\tcase \"api_key\": {\n\t\t\tconst headerName = authConfig.apiKeyHeader;\n\t\t\theaders[headerName] = authConfig.apiKey;\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn headers;\n}\nfunction shortHash(str) {\n\tlet h = 5381;\n\tfor (let i = 0; i < str.length; i++) h = (Math.imul(h, 33) ^ str.charCodeAt(i)) >>> 0;\n\treturn h.toString(36).padStart(6, \"0\").slice(-6);\n}\nfunction sanitizeToolName(name) {\n\treturn name.toLowerCase().replace(/[^a-z0-9_-]/g, \"_\").replace(/_+/g, \"_\").replace(/^_+|_+$/g, \"\");\n}\nfunction createToolName(name) {\n\tconst sanitized = sanitizeToolName(name);\n\treturn `${sanitized.slice(0, MAX_PREFIX_LENGTH)}_${shortHash(sanitized.length > 0 ? sanitized : name)}_mcp`;\n}\nfunction toValidToolName(name) {\n\tif (PROVIDER_TOOL_NAME_PATTERN.test(name)) return name;\n\tconst generated = createToolName(name);\n\treturn PROVIDER_TOOL_NAME_PATTERN.test(generated) ? generated : createToolName(`tool_${name}`);\n}\nfunction suggestToolName(sourceName) {\n\treturn toValidToolName(sanitizeToolName(sourceName));\n}\nfunction isProviderSafeIdentifier(name) {\n\treturn PROVIDER_TOOL_NAME_PATTERN.test(name);\n}\nfunction toProviderSafeIdentifier({ name, fallback }) {\n\tif (isProviderSafeIdentifier(name)) return name;\n\tconst sanitized = sanitizeToolName(name).slice(0, MAX_IDENTIFIER_LENGTH);\n\tif (sanitized.length === 0) return fallback;\n\tconst seeded = /^[a-z_]/.test(sanitized) ? sanitized : `_${sanitized}`;\n\treturn isProviderSafeIdentifier(seeded) ? seeded : fallback;\n}\nfunction createPieceToolName(pieceName, actionName) {\n\tconst idx = pieceName.indexOf(\"piece-\");\n\treturn createToolName(`${idx >= 0 ? pieceName.substring(idx + 6) : pieceName}-${actionName}`);\n}\nconst MAX_PREFIX_LENGTH = 53;\nconst MAX_IDENTIFIER_LENGTH = 64;\nconst PROVIDER_TOOL_NAME_PATTERN = /^[a-zA-Z_][a-zA-Z0-9_-]{0,63}$/;\nconst mcpToolNameUtils = {\n\tcreateToolName,\n\tcreatePieceToolName,\n\ttoValidToolName,\n\tsuggestToolName,\n\tisProviderSafeIdentifier,\n\ttoProviderSafeIdentifier\n};\nconst AGENT_STEP_TIMEOUT_MS = 108e5;\nconst AGENT_STEP_TEST_TIMEOUT_MS = 9e5;\n\n//#endregion\n//#region upstream/core-piece-types/lib/ai-providers.ts\nlet AIProviderModelType = /* @__PURE__ */ function(AIProviderModelType) {\n\tAIProviderModelType[\"IMAGE\"] = \"image\";\n\tAIProviderModelType[\"TEXT\"] = \"text\";\n\treturn AIProviderModelType;\n}({});\nconst BaseAIProviderAuthConfig = z.object({ apiKey: z.string() });\nconst AnthropicProviderAuthConfig = BaseAIProviderAuthConfig;\nconst ActivePiecesProviderAuthConfig = z.object({\n\tapiKey: z.string(),\n\tapiKeyHash: z.string()\n});\nconst OpenAICompatibleProviderAuthConfig = BaseAIProviderAuthConfig;\nconst CloudflareGatewayProviderAuthConfig = BaseAIProviderAuthConfig;\nconst AzureProviderAuthConfig = BaseAIProviderAuthConfig;\nconst GoogleProviderAuthConfig = BaseAIProviderAuthConfig;\nconst OpenAIProviderAuthConfig = BaseAIProviderAuthConfig;\nconst OpenRouterProviderAuthConfig = BaseAIProviderAuthConfig;\nconst MistralProviderAuthConfig = BaseAIProviderAuthConfig;\nconst VertexProviderAuthConfig = z.object({ serviceAccountJson: z.string().check(z.minLength(1)) });\nconst BedrockProviderAuthConfig = z.object({\n\taccessKeyId: z.string().check(z.minLength(1)),\n\tsecretAccessKey: z.string().check(z.minLength(1))\n});\nconst AnthropicProviderConfig = z.object({});\nconst ActivePiecesProviderConfig = z.object({});\nconst GoogleProviderConfig = z.object({});\nconst OpenAIProviderConfig = z.object({});\nconst OpenRouterProviderConfig = z.object({});\nconst MistralProviderConfig = z.object({});\nconst ProviderModelConfig = z.object({\n\tmodelId: z.string(),\n\tmodelName: z.string(),\n\tmodelType: z.enum(AIProviderModelType)\n});\nconst OpenAICompatibleProviderConfig = z.object({\n\tapiKeyHeader: z.string(),\n\tbaseUrl: z.string(),\n\tmodels: z.array(ProviderModelConfig),\n\tdefaultHeaders: z.optional(z.record(z.string(), z.string())),\n\tapiStyle: z.optional(z.enum([\"chat\", \"responses\"]))\n});\nconst CloudflareGatewayProviderConfig = z.object({\n\taccountId: z.string(),\n\tgatewayId: z.string(),\n\tmodels: z.array(ProviderModelConfig),\n\tvertexProject: z.optional(z.string()),\n\tvertexRegion: z.optional(z.string())\n});\nconst AzureProviderConfig = z.object({\n\tresourceName: z.string(),\n\tapiVersion: z.pipe(z.transform((v) => typeof v === \"string\" && v.trim().length === 0 ? void 0 : v), z.optional(z.string()))\n});\nconst BedrockProviderConfig = z.object({ region: z.string().check(z.minLength(1)) });\nconst VertexProviderConfig = z.object({\n\tproject: z.string().check(z.regex(/^[a-z0-9][a-z0-9-]{0,62}$/)),\n\tregion: z.string().check(z.regex(/^[a-z0-9][a-z0-9-]{0,62}$/)),\n\tmodels: z.array(ProviderModelConfig)\n});\nconst OpenAiCompatibleVendorConfig = z.object({});\nconst AIProviderAuthConfig = z.union([\n\tAnthropicProviderAuthConfig,\n\tAzureProviderAuthConfig,\n\tGoogleProviderAuthConfig,\n\tOpenAIProviderAuthConfig,\n\tOpenRouterProviderAuthConfig,\n\tCloudflareGatewayProviderAuthConfig,\n\tOpenAICompatibleProviderAuthConfig,\n\tActivePiecesProviderAuthConfig,\n\tBedrockProviderAuthConfig,\n\tVertexProviderAuthConfig,\n\tMistralProviderAuthConfig\n]);\nconst AIProviderConfig = z.union([\n\tOpenAICompatibleProviderConfig,\n\tCloudflareGatewayProviderConfig,\n\tAzureProviderConfig,\n\tVertexProviderConfig,\n\tBedrockProviderConfig,\n\tAnthropicProviderConfig,\n\tGoogleProviderConfig,\n\tOpenAIProviderConfig,\n\tOpenRouterProviderConfig,\n\tActivePiecesProviderConfig,\n\tMistralProviderConfig,\n\tOpenAiCompatibleVendorConfig\n]);\nconst AIProviderModel = z.object({\n\tid: z.string(),\n\tname: z.string(),\n\ttype: z.enum(AIProviderModelType)\n});\nconst AIProviderWithoutSensitiveData = z.object({\n\tid: z.string(),\n\tname: z.string(),\n\tprovider: z.enum(AIProviderName),\n\tconfig: AIProviderConfig,\n\tenabledForChat: z.boolean()\n});\nconst ProjectAIProvider = z.object({\n\tprovider: z.enum(AIProviderName),\n\tname: z.string(),\n\tenabledForChat: z.boolean(),\n\tkeys: z.array(z.object({\n\t\tid: z.string(),\n\t\tname: z.string()\n\t}))\n});\nconst GetProviderConfigResponse = z.object({\n\tprovider: z.enum(AIProviderName),\n\tconfigId: z.string(),\n\tconfig: AIProviderConfig,\n\tauth: AIProviderAuthConfig,\n\tplatformId: z.string()\n});\nfunction splitCloudflareGatewayModelId(modelId) {\n\tconst slashIndex = modelId.indexOf(\"/\");\n\tif (slashIndex === -1) return {\n\t\tprovider: void 0,\n\t\tmodel: modelId,\n\t\tpublisher: void 0\n\t};\n\tconst provider = modelId.substring(0, slashIndex).trim().toLowerCase();\n\tconst rest = modelId.substring(slashIndex + 1);\n\tif (provider === \"google-vertex-ai\") {\n\t\tconst secondSlashIndex = rest.indexOf(\"/\");\n\t\tif (secondSlashIndex === -1) return {\n\t\t\tprovider: void 0,\n\t\t\tmodel: modelId,\n\t\t\tpublisher: void 0\n\t\t};\n\t\treturn {\n\t\t\tprovider: \"google-vertex-ai\",\n\t\t\tpublisher: rest.substring(0, secondSlashIndex),\n\t\t\tmodel: rest.substring(secondSlashIndex + 1)\n\t\t};\n\t}\n\treturn {\n\t\tprovider,\n\t\tmodel: rest,\n\t\tpublisher: void 0\n\t};\n}\nfunction getEffectiveProviderAndModel({ provider, model }) {\n\tif (provider !== \"cloudflare-gateway\" || !model) return {\n\t\tprovider,\n\t\tmodel\n\t};\n\tconst split = splitCloudflareGatewayModelId(model);\n\tconst gatewaySubmodelPrefix = (split.provider ?? \"\").trim().toLowerCase();\n\tconst mapped = CF_GATEWAY_SUBMODEL_TO_PROVIDER[gatewaySubmodelPrefix];\n\tif (!mapped) return {\n\t\tprovider,\n\t\tmodel\n\t};\n\treturn {\n\t\tprovider: mapped,\n\t\tmodel: split.model\n\t};\n}\nconst CF_GATEWAY_SUBMODEL_TO_PROVIDER = {\n\topenai: \"openai\",\n\tanthropic: \"anthropic\",\n\t\"google-ai-studio\": \"google\",\n\t\"google-vertex-ai\": \"google\"\n};\nconst OPENAI_CHAT_MODELS = [\n\t\"gpt-5.5\",\n\t\"gpt-5.4-mini\",\n\t\"gpt-5.4-nano\",\n\t\"gpt-4.1\",\n\t\"gpt-4.1-mini\"\n];\nconst ANTHROPIC_CHAT_MODELS = [\n\t\"claude-sonnet-4-6\",\n\t\"claude-opus-4-7\",\n\t\"claude-haiku-4-5\"\n];\nconst ANTHROPIC_OPENROUTER_CHAT_MODELS = [\n\t\"claude-sonnet-4.6\",\n\t\"claude-opus-4.7\",\n\t\"claude-opus-4.8\",\n\t\"claude-haiku-4.5\"\n];\nconst GOOGLE_CHAT_MODELS = [\n\t\"gemini-2.5-pro\",\n\t\"gemini-2.5-flash\",\n\t\"gemini-3.7-flash\",\n\t\"gemini-3.1-pro-preview\",\n\t\"gemini-3-flash-preview\"\n];\nconst X_AI_OPENROUTER_CHAT_MODELS = [\"grok-4.20\"];\nconst REASONING_OPTIONAL_CHAT_MODELS = ANTHROPIC_OPENROUTER_CHAT_MODELS.map((model) => `${\"anthropic\"}/${model}`);\nconst ALLOWED_CHAT_MODELS_BY_PROVIDER = {\n\t[\"openai\"]: OPENAI_CHAT_MODELS,\n\t[\"anthropic\"]: ANTHROPIC_CHAT_MODELS,\n\t[\"google\"]: GOOGLE_CHAT_MODELS,\n\t[\"vertex\"]: GOOGLE_CHAT_MODELS,\n\t[\"activepieces\"]: [\n\t\t...ANTHROPIC_OPENROUTER_CHAT_MODELS.map((m) => `${\"anthropic\"}/${m}`),\n\t\t...OPENAI_CHAT_MODELS.map((m) => `${\"openai\"}/${m}`),\n\t\t...GOOGLE_CHAT_MODELS.map((m) => `${\"google\"}/${m}`),\n\t\t...X_AI_OPENROUTER_CHAT_MODELS.map((m) => `x-ai/${m}`)\n\t]\n};\nconst DEFAULT_MAX_CONTEXT_TOKENS = 128e3;\nconst PROVIDER_MAX_CONTEXT_TOKENS = {\n\t[\"openai\"]: 128e3,\n\t[\"anthropic\"]: 2e5,\n\t[\"google\"]: 1048576,\n\t[\"bedrock\"]: 2e5,\n\t[\"vertex\"]: 1048576,\n\t[\"azure\"]: 128e3,\n\t[\"openrouter\"]: 128e3,\n\t[\"activepieces\"]: 2e5,\n\t[\"mistral\"]: 128e3\n};\nfunction getMaxContextTokens({ provider }) {\n\tif (!provider) return DEFAULT_MAX_CONTEXT_TOKENS;\n\treturn PROVIDER_MAX_CONTEXT_TOKENS[provider] ?? DEFAULT_MAX_CONTEXT_TOKENS;\n}\nconst DEFAULT_EMBEDDING_MODELS = {\n\t[\"openai\"]: \"text-embedding-3-small\",\n\t[\"google\"]: \"text-embedding-004\",\n\t[\"azure\"]: \"text-embedding-3-small\",\n\t[\"activepieces\"]: \"text-embedding-3-small\",\n\t[\"openrouter\"]: \"openai/text-embedding-3-small\"\n};\nconst WEB_SEARCH_MODE_BY_PROVIDER = {\n\t[\"anthropic\"]: \"native\",\n\t[\"google\"]: \"native\",\n\t[\"openrouter\"]: \"plugin\",\n\t[\"activepieces\"]: \"plugin\"\n};\nconst NO_IMAGE_GENERATION_PROVIDERS = /* @__PURE__ */ new Set([\n\t\"anthropic\",\n\t\"mistral\",\n\t\"xai\",\n\t\"deepseek\",\n\t\"zai\",\n\t\"qwen\",\n\t\"minimax\",\n\t\"moonshot\"\n]);\nconst OPENAI_COMPATIBLE_VENDOR_BASE_URLS = {\n\t[\"xai\"]: \"https://api.x.ai/v1\",\n\t[\"deepseek\"]: \"https://api.deepseek.com/v1\",\n\t[\"zai\"]: \"https://api.z.ai/api/paas/v4\",\n\t[\"qwen\"]: \"https://dashscope-intl.aliyuncs.com/compatible-mode/v1\",\n\t[\"minimax\"]: \"https://api.minimax.io/v1\",\n\t[\"moonshot\"]: \"https://api.moonshot.ai/v1\"\n};\nfunction buildProviderCapabilities(provider) {\n\treturn {\n\t\tchatModels: ALLOWED_CHAT_MODELS_BY_PROVIDER[provider],\n\t\tmaxContextTokens: getMaxContextTokens({ provider }),\n\t\tdefaultEmbeddingModel: DEFAULT_EMBEDDING_MODELS[provider],\n\t\tsupportsEmbedding: DEFAULT_EMBEDDING_MODELS[provider] !== void 0,\n\t\tsupportsImageGeneration: !NO_IMAGE_GENERATION_PROVIDERS.has(provider),\n\t\twebSearch: WEB_SEARCH_MODE_BY_PROVIDER[provider]\n\t};\n}\nconst ACTIVEPIECES_CHAT_TIERS = [\n\t{\n\t\tid: \"fast\",\n\t\tlabel: \"Fast\",\n\t\tmodelId: \"anthropic/claude-haiku-4.5\",\n\t\tnativeModelId: \"claude-haiku-4-5\",\n\t\tthinkingBudget: 5e3,\n\t\tcreditWeight: 2\n\t},\n\t{\n\t\tid: \"smart\",\n\t\tlabel: \"Expert\",\n\t\tmodelId: \"anthropic/claude-sonnet-4.6\",\n\t\tnativeModelId: \"claude-sonnet-4-6\",\n\t\tthinkingBudget: 1e4,\n\t\tcreditWeight: 10\n\t},\n\t{\n\t\tid: \"premium\",\n\t\tlabel: \"Heavy\",\n\t\tmodelId: \"anthropic/claude-opus-4.8\",\n\t\tnativeModelId: \"claude-opus-4-7\",\n\t\tthinkingBudget: 2e4,\n\t\tcreditWeight: 20\n\t}\n];\nconst DEFAULT_CHAT_TIER_ID = \"smart\";\nconst AI_PROVIDER_CAPABILITIES = {\n\t[\"openai\"]: buildProviderCapabilities(\"openai\"),\n\t[\"anthropic\"]: buildProviderCapabilities(\"anthropic\"),\n\t[\"openrouter\"]: buildProviderCapabilities(\"openrouter\"),\n\t[\"azure\"]: buildProviderCapabilities(\"azure\"),\n\t[\"google\"]: buildProviderCapabilities(\"google\"),\n\t[\"cloudflare-gateway\"]: buildProviderCapabilities(\"cloudflare-gateway\"),\n\t[\"custom\"]: buildProviderCapabilities(\"custom\"),\n\t[\"bedrock\"]: buildProviderCapabilities(\"bedrock\"),\n\t[\"vertex\"]: buildProviderCapabilities(\"vertex\"),\n\t[\"mistral\"]: buildProviderCapabilities(\"mistral\"),\n\t[\"activepieces\"]: buildProviderCapabilities(\"activepieces\"),\n\t[\"xai\"]: buildProviderCapabilities(\"xai\"),\n\t[\"deepseek\"]: buildProviderCapabilities(\"deepseek\"),\n\t[\"zai\"]: buildProviderCapabilities(\"zai\"),\n\t[\"qwen\"]: buildProviderCapabilities(\"qwen\"),\n\t[\"minimax\"]: buildProviderCapabilities(\"minimax\"),\n\t[\"moonshot\"]: buildProviderCapabilities(\"moonshot\")\n};\n\n//#endregion\n//#region upstream/core-piece-types/lib/forms.ts\nconst FileResponseInterfaceV1 = z.object({\n\tbase64Url: z.string(),\n\tfileName: z.string(),\n\textension: z.optional(z.string())\n});\nconst FileResponseInterfaceV2 = z.object({\n\tmimeType: z.string(),\n\turl: z.string(),\n\tfileName: z.optional(z.string())\n});\nconst FileResponseInterface = z.union([FileResponseInterfaceV1, FileResponseInterfaceV2]);\nlet HumanInputFormResultTypes = /* @__PURE__ */ function(HumanInputFormResultTypes) {\n\tHumanInputFormResultTypes[\"FILE\"] = \"file\";\n\tHumanInputFormResultTypes[\"MARKDOWN\"] = \"markdown\";\n\treturn HumanInputFormResultTypes;\n}({});\nfunction createKeyForFormInput(displayName) {\n\t/**We do this because react form inputs must not contain quotes */\n\treturn displayName.toLowerCase().replace(/\\s+(\\w)/g, (_, letter) => letter.toUpperCase()).replace(/^(.)/, (letter) => letter.toLowerCase()).replaceAll(/[\\\\\"''\\n\\r\\t]/g, \"\");\n}\nconst HumanInputFormResult = z.union([z.object({\n\ttype: z.literal(\"file\"),\n\tvalue: FileResponseInterface\n}), z.object({\n\ttype: z.literal(\"markdown\"),\n\tvalue: z.string(),\n\tfiles: z.optional(z.array(FileResponseInterface))\n})]);\nconst ChatFormResponse = z.object({\n\tsessionId: z.string(),\n\tmessage: z.string(),\n\tfiles: z.optional(z.array(z.string()))\n});\n\n//#endregion\n//#region upstream/core-piece-types/lib/tables.ts\nlet FieldType = /* @__PURE__ */ function(FieldType) {\n\tFieldType[\"TEXT\"] = \"TEXT\";\n\tFieldType[\"NUMBER\"] = \"NUMBER\";\n\tFieldType[\"DATE\"] = \"DATE\";\n\tFieldType[\"DATETIME\"] = \"DATETIME\";\n\tFieldType[\"STATIC_DROPDOWN\"] = \"STATIC_DROPDOWN\";\n\treturn FieldType;\n}({});\nlet TableAutomationTrigger = /* @__PURE__ */ function(TableAutomationTrigger) {\n\tTableAutomationTrigger[\"ON_NEW_RECORD\"] = \"ON_NEW_RECORD\";\n\tTableAutomationTrigger[\"ON_UPDATE_RECORD\"] = \"ON_UPDATE_RECORD\";\n\treturn TableAutomationTrigger;\n}({});\nlet TableAutomationStatus = /* @__PURE__ */ function(TableAutomationStatus) {\n\tTableAutomationStatus[\"ENABLED\"] = \"ENABLED\";\n\tTableAutomationStatus[\"DISABLED\"] = \"DISABLED\";\n\treturn TableAutomationStatus;\n}({});\nlet TableWebhookEventType = /* @__PURE__ */ function(TableWebhookEventType) {\n\tTableWebhookEventType[\"RECORD_CREATED\"] = \"RECORD_CREATED\";\n\tTableWebhookEventType[\"RECORD_UPDATED\"] = \"RECORD_UPDATED\";\n\tTableWebhookEventType[\"RECORD_DELETED\"] = \"RECORD_DELETED\";\n\treturn TableWebhookEventType;\n}({});\nlet FilterOperator = /* @__PURE__ */ function(FilterOperator) {\n\tFilterOperator[\"EQ\"] = \"eq\";\n\tFilterOperator[\"NEQ\"] = \"neq\";\n\tFilterOperator[\"GT\"] = \"gt\";\n\tFilterOperator[\"GTE\"] = \"gte\";\n\tFilterOperator[\"LT\"] = \"lt\";\n\tFilterOperator[\"LTE\"] = \"lte\";\n\tFilterOperator[\"CO\"] = \"co\";\n\tFilterOperator[\"EXISTS\"] = \"exists\";\n\tFilterOperator[\"NOT_EXISTS\"] = \"not_exists\";\n\treturn FilterOperator;\n}({});\nconst Field = z.union([z.object({\n\t...BaseModelSchema,\n\tname: z.string(),\n\texternalId: z.string(),\n\ttype: z.literal(\"STATIC_DROPDOWN\"),\n\ttableId: z.string(),\n\tprojectId: z.string(),\n\tdata: z.object({ options: z.array(z.object({ value: z.string() })) })\n}), z.object({\n\t...BaseModelSchema,\n\tname: z.string(),\n\texternalId: z.string(),\n\ttype: z.union([\n\t\tz.literal(\"TEXT\"),\n\t\tz.literal(\"NUMBER\"),\n\t\tz.literal(\"DATE\"),\n\t\tz.literal(\"DATETIME\")\n\t]),\n\ttableId: z.string(),\n\tprojectId: z.string()\n})]);\nconst Table = z.object({\n\t...BaseModelSchema,\n\tname: z.string(),\n\tfolderId: Nullable(z.string()),\n\tprojectId: z.string(),\n\texternalId: z.string(),\n\tstatus: NullableEnum(TableAutomationStatus),\n\ttrigger: NullableEnum(TableAutomationTrigger)\n});\nconst PopulatedRecord = z.object({\n\t...BaseModelSchema,\n\ttableId: z.string(),\n\tprojectId: z.string(),\n\tcells: z.record(z.string(), z.object({\n\t\tupdated: z.string(),\n\t\tcreated: z.string(),\n\t\tvalue: z.unknown(),\n\t\tfieldName: z.string()\n\t}))\n});\nconst CreateTableWebhookRequest = z.object({\n\tevents: z.array(z.enum(TableWebhookEventType)),\n\twebhookUrl: z.string(),\n\tflowId: z.string()\n});\nconst ExportTableResponse = z.object({\n\tfields: z.array(z.object({\n\t\tid: z.string(),\n\t\tname: z.string()\n\t})),\n\trows: z.array(z.record(z.string(), z.string())),\n\tname: z.string()\n});\nconst ListTablesRequest = z.object({\n\tprojectId: z.string(),\n\tlimit: z.optional(z.coerce.number()),\n\tcursor: z.optional(z.string()),\n\tname: z.optional(z.string()),\n\texternalIds: OptionalArrayFromQuery(z.string()),\n\tfolderId: z.optional(z.string()),\n\tfolderIds: OptionalArrayFromQuery(z.string())\n});\nconst CreateRecordsRequest = z.object({\n\trecords: z.array(z.array(z.object({\n\t\tfieldId: z.string(),\n\t\tvalue: coerceToString()\n\t}))),\n\ttableId: z.string()\n});\nconst UpdateRecordRequest = z.object({\n\tcells: z.optional(z.array(z.object({\n\t\tfieldId: z.string(),\n\t\tvalue: coerceToString()\n\t}))),\n\ttableId: z.string(),\n\tagentUpdate: z.optional(z.boolean())\n});\nconst Filter = z.discriminatedUnion(\"operator\", [\n\tvalueFilter(\"eq\"),\n\tvalueFilter(\"neq\"),\n\tvalueFilter(\"gt\"),\n\tvalueFilter(\"gte\"),\n\tvalueFilter(\"lt\"),\n\tvalueFilter(\"lte\"),\n\tvalueFilter(\"co\"),\n\texistenceFilter(\"exists\"),\n\texistenceFilter(\"not_exists\")\n]);\nconst ListRecordsRequest = z.object({\n\ttableId: z.string(),\n\tlimit: z.optional(z.coerce.number()),\n\tcursor: z.optional(z.string()),\n\tfilters: OptionalArrayFromQuery(Filter)\n});\nconst StaticDropdownEmptyOption = {\n\tlabel: \"\",\n\tvalue: \"\"\n};\nfunction coerceToString() {\n\treturn z.pipe(z.transform((v) => v === null || v === void 0 ? v : String(v)), z.nullable(z.string()));\n}\nfunction valueFilter(op) {\n\treturn z.object({\n\t\tfieldId: z.string(),\n\t\toperator: z.literal(op),\n\t\tvalue: z.string()\n\t});\n}\nfunction existenceFilter(op) {\n\treturn z.object({\n\t\tfieldId: z.string(),\n\t\toperator: z.literal(op)\n\t});\n}\n\n//#endregion\n//#region upstream/core-piece-types/lib/flow-contracts.ts\nlet FlowStatus = /* @__PURE__ */ function(FlowStatus) {\n\tFlowStatus[\"ENABLED\"] = \"ENABLED\";\n\tFlowStatus[\"DISABLED\"] = \"DISABLED\";\n\treturn FlowStatus;\n}({});\nlet FlowTriggerType = /* @__PURE__ */ function(FlowTriggerType) {\n\tFlowTriggerType[\"EMPTY\"] = \"EMPTY\";\n\tFlowTriggerType[\"PIECE\"] = \"PIECE_TRIGGER\";\n\treturn FlowTriggerType;\n}({});\nconst StopResponse = z.object({\n\tstatus: z.optional(z.number()),\n\tbody: z.optional(z.unknown()),\n\theaders: z.optional(z.record(z.string(), z.string()))\n});\nconst Project = z.object({\n\t...BaseModelSchema,\n\tdeleted: Nullable(DateOrString),\n\townerId: z.string(),\n\tdisplayName: z.string(),\n\tplatformId: z.string(),\n\texternalId: Nullable(z.string())\n});\nconst USE_DRAFT_QUERY_PARAM_NAME = \"useDraft\";\nconst PARENT_RUN_ID_HEADER = \"ap-parent-run-id\";\nconst FAIL_PARENT_ON_FAILURE_HEADER = \"ap-fail-parent-on-failure\";\nconst RAW_PAYLOAD_HEADER = \"ap-raw-payload\";\n\n//#endregion\n//#region upstream/core-piece-types/lib/mcp-piece.ts\nlet McpPropertyType = /* @__PURE__ */ function(McpPropertyType) {\n\tMcpPropertyType[\"TEXT\"] = \"Text\";\n\tMcpPropertyType[\"BOOLEAN\"] = \"Boolean\";\n\tMcpPropertyType[\"DATE\"] = \"Date\";\n\tMcpPropertyType[\"NUMBER\"] = \"Number\";\n\tMcpPropertyType[\"ARRAY\"] = \"Array\";\n\tMcpPropertyType[\"OBJECT\"] = \"Object\";\n\treturn McpPropertyType;\n}({});\nconst McpProperty = z.object({\n\tname: z.string(),\n\tdescription: z.optional(z.string()),\n\ttype: z.string(),\n\trequired: z.boolean()\n});\nconst McpTrigger = z.object({\n\tpieceName: z.string(),\n\ttriggerName: z.string(),\n\tinput: z.object({\n\t\ttoolName: z.string(),\n\t\ttoolDescription: z.string(),\n\t\tinputSchema: z.array(McpProperty),\n\t\treturnsResponse: z.boolean()\n\t})\n});\n\n//#endregion\n//#region upstream/core-piece-types/lib/engine-tools.ts\nfunction normalizeToolOutputToExecuteResponse(raw) {\n\tif (raw === null || typeof raw !== \"object\") return {\n\t\tstatus: \"FAILED\",\n\t\toutput: raw,\n\t\tresolvedInput: {},\n\t\terrorMessage: \"Invalid tool output\"\n\t};\n\tconst o = raw;\n\tif (o[\"status\"] === \"SUCCESS\" || o[\"status\"] === \"FAILED\") return {\n\t\tstatus: o[\"status\"],\n\t\toutput: o[\"output\"],\n\t\tresolvedInput: o[\"resolvedInput\"] ?? {},\n\t\terrorMessage: o[\"errorMessage\"]\n\t};\n\tconst isError = o[\"isError\"] === true;\n\tlet output = o[\"structuredContent\"];\n\tif (output === void 0 && Array.isArray(o[\"content\"])) {\n\t\tconst parts = o[\"content\"].map((c) => c?.text).filter(Boolean);\n\t\toutput = parts.length === 1 ? parts[0] : parts.length ? { text: parts.join(\"\") } : o[\"content\"];\n\t}\n\tif (output === void 0) output = o;\n\treturn {\n\t\tstatus: isError ? \"FAILED\" : \"SUCCESS\",\n\t\toutput,\n\t\tresolvedInput: {},\n\t\terrorMessage: isError ? o[\"content\"]?.[0]?.text ?? o[\"message\"] ?? \"Tool failed\" : void 0\n\t};\n}\n\n//#endregion\n//#region upstream/framework/lib/property/util.ts\nfunction buildSchema(props, auth, requireAuth = true) {\n\tconst entries = Object.entries(props);\n\tconst propsSchema = {};\n\tfor (const [name, property] of entries) {\n\t\tswitch (property.type) {\n\t\t\tcase \"MARKDOWN\":\n\t\t\t\tpropsSchema[name] = z.optional(z.union([\n\t\t\t\t\tz.null(),\n\t\t\t\t\tz.undefined(),\n\t\t\t\t\tz.never(),\n\t\t\t\t\tz.unknown()\n\t\t\t\t]));\n\t\t\t\tbreak;\n\t\t\tcase \"DATE_TIME\":\n\t\t\tcase \"SHORT_TEXT\":\n\t\t\tcase \"LONG_TEXT\":\n\t\t\tcase \"RICH_TEXT\":\n\t\t\tcase \"COLOR\":\n\t\t\tcase \"FILE\":\n\t\t\t\tpropsSchema[name] = property.required ? z.string().check(z.minLength(1)) : z.string();\n\t\t\t\tbreak;\n\t\t\tcase \"CHECKBOX\":\n\t\t\t\tpropsSchema[name] = z.union([z.boolean(), z.string()]);\n\t\t\t\tbreak;\n\t\t\tcase \"NUMBER\":\n\t\t\t\tpropsSchema[name] = z.union([property.required ? z.string().check(z.minLength(1)) : z.string(), z.number()]);\n\t\t\t\tbreak;\n\t\t\tcase \"STATIC_DROPDOWN\":\n\t\t\tcase \"DROPDOWN\":\n\t\t\t\tpropsSchema[name] = z.unknown().check(z.refine((val) => val !== null && val !== void 0, { error: \"Value must not be null or undefined\" }));\n\t\t\t\tbreak;\n\t\t\tcase \"SECRET_TEXT\":\n\t\t\t\tpropsSchema[name] = property.required ? z.string().check(z.minLength(1)) : z.string();\n\t\t\t\tbreak;\n\t\t\tcase \"BASIC_AUTH\":\n\t\t\tcase \"CUSTOM_AUTH\":\n\t\t\tcase \"OAUTH2\": break;\n\t\t\tcase \"ARRAY\": {\n\t\t\t\tconst arrayItemSchema = isNil(property.properties) ? property.required ? z.string().check(z.minLength(1)) : z.string() : buildSchema(property.properties, void 0);\n\t\t\t\tpropsSchema[name] = z.union([\n\t\t\t\t\tproperty.required ? z.array(arrayItemSchema).check(z.minLength(1)) : z.array(arrayItemSchema),\n\t\t\t\t\tz.record(z.string(), z.unknown()),\n\t\t\t\t\tproperty.required ? z.string().check(z.minLength(1)) : z.string()\n\t\t\t\t]);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"OBJECT\":\n\t\t\t\tpropsSchema[name] = z.union([z.record(z.string(), z.any()), property.required ? z.string().check(z.minLength(1)) : z.string()]);\n\t\t\t\tbreak;\n\t\t\tcase \"DATE_RANGE\":\n\t\t\t\tpropsSchema[name] = z.union([z.record(z.string(), z.any()), z.string()]);\n\t\t\t\tbreak;\n\t\t\tcase \"JSON\":\n\t\t\t\tpropsSchema[name] = z.union([\n\t\t\t\t\tz.record(z.string(), z.any()),\n\t\t\t\t\tz.array(z.any()),\n\t\t\t\t\tproperty.required ? z.string().check(z.minLength(1)) : z.string()\n\t\t\t\t]);\n\t\t\t\tbreak;\n\t\t\tcase \"MULTI_SELECT_DROPDOWN\":\n\t\t\tcase \"STATIC_MULTI_SELECT_DROPDOWN\":\n\t\t\t\tpropsSchema[name] = z.union([property.required ? z.array(z.any()).check(z.minLength(1)) : z.array(z.any()), property.required ? z.string().check(z.minLength(1)) : z.string()]);\n\t\t\t\tbreak;\n\t\t\tcase \"DYNAMIC\":\n\t\t\t\tpropsSchema[name] = z.record(z.string(), z.any());\n\t\t\t\tbreak;\n\t\t\tcase \"CUSTOM\": propsSchema[name] = z.unknown();\n\t\t}\n\t\tif (!property.required && property.type !== \"ARRAY\") propsSchema[name] = z.optional(z.union(isEmpty(propsSchema[name]) ? [\n\t\t\tz.any(),\n\t\t\tz.null(),\n\t\t\tz.undefined()\n\t\t] : [\n\t\t\tpropsSchema[name],\n\t\t\tz.null(),\n\t\t\tz.undefined()\n\t\t]));\n\t}\n\tif (auth && requireAuth) propsSchema[AUTHENTICATION_PROPERTY_NAME] = z.string().check(z.minLength(1));\n\treturn z.object(propsSchema);\n}\nconst piecePropertiesUtils = { buildSchema };\n\n//#endregion\n//#region upstream/framework/lib/property/index.ts\nconst PieceProperty = z.union([InputProperty, PieceAuthProperty]);\nconst PiecePropertyMap = z.record(z.string(), PieceProperty);\nconst InputPropertyMap = z.record(z.string(), InputProperty);\n\n//#endregion\n//#region upstream/framework/lib/trigger/trigger.ts\nconst DEDUPE_KEY_PROPERTY = \"_dedupe_key\";\nlet WebhookRenewStrategy = /* @__PURE__ */ function(WebhookRenewStrategy) {\n\tWebhookRenewStrategy[\"CRON\"] = \"CRON\";\n\tWebhookRenewStrategy[\"NONE\"] = \"NONE\";\n\treturn WebhookRenewStrategy;\n}({});\nconst WebhookRenewConfiguration = z.union([z.object({\n\tstrategy: z.literal(\"CRON\"),\n\tcronExpression: z.string()\n}), z.object({ strategy: z.literal(\"NONE\") })]);\nvar ITrigger = class {\n\tname;\n\tdisplayName;\n\tdescription;\n\trequireAuth;\n\tprops;\n\ttype;\n\thandshakeConfiguration;\n\tonHandshake;\n\trenewConfiguration;\n\tonRenew;\n\tonEnable;\n\tonDisable;\n\tonStart;\n\trun;\n\ttest;\n\tsampleData;\n\ttestStrategy;\n\toutputSchema;\n\taiMetadata;\n\tclassification;\n\tpropertyGroups;\n\tconstructor(name, displayName, description, requireAuth, props, type, handshakeConfiguration, onHandshake, renewConfiguration, onRenew, onEnable, onDisable, onStart, run, test, sampleData, testStrategy, outputSchema, aiMetadata, classification, propertyGroups) {\n\t\tthis.name = name;\n\t\tthis.displayName = displayName;\n\t\tthis.description = description;\n\t\tthis.requireAuth = requireAuth;\n\t\tthis.props = props;\n\t\tthis.type = type;\n\t\tthis.handshakeConfiguration = handshakeConfiguration;\n\t\tthis.onHandshake = onHandshake;\n\t\tthis.renewConfiguration = renewConfiguration;\n\t\tthis.onRenew = onRenew;\n\t\tthis.onEnable = onEnable;\n\t\tthis.onDisable = onDisable;\n\t\tthis.onStart = onStart;\n\t\tthis.run = run;\n\t\tthis.test = test;\n\t\tthis.sampleData = sampleData;\n\t\tthis.testStrategy = testStrategy;\n\t\tthis.outputSchema = outputSchema;\n\t\tthis.aiMetadata = aiMetadata;\n\t\tthis.classification = classification;\n\t\tthis.propertyGroups = propertyGroups;\n\t}\n};\nconst createTrigger$1 = (params) => {\n\tswitch (params.type) {\n\t\tcase \"WEBHOOK\": return new ITrigger(params.name, params.displayName, params.description, params.requireAuth ?? true, params.props, params.type, params.handshakeConfiguration ?? { strategy: \"NONE\" }, params.onHandshake ?? (async () => ({ status: 200 })), params.renewConfiguration ?? { strategy: \"NONE\" }, params.onRenew ?? (async () => Promise.resolve()), params.onEnable, params.onDisable, params.onStart ?? (async () => Promise.resolve()), params.run, params.test ?? (() => Promise.resolve([params.sampleData])), params.sampleData, params.test ? \"TEST_FUNCTION\" : \"SIMULATION\", params.outputSchema, params.aiMetadata, params.classification, params.propertyGroups);\n\t\tcase \"POLLING\": return new ITrigger(params.name, params.displayName, params.description, params.requireAuth ?? true, params.props, params.type, { strategy: \"NONE\" }, async () => ({ status: 200 }), { strategy: \"NONE\" }, async () => Promise.resolve(), params.onEnable, params.onDisable, params.onStart ?? (async () => Promise.resolve()), params.run, params.test ?? (() => Promise.resolve([params.sampleData])), params.sampleData, \"TEST_FUNCTION\", params.outputSchema, params.aiMetadata, params.classification, params.propertyGroups);\n\t\tcase \"MANUAL\": return new ITrigger(params.name, params.displayName, params.description, params.requireAuth ?? true, params.props, params.type, { strategy: \"NONE\" }, async () => ({ status: 200 }), { strategy: \"NONE\" }, async () => Promise.resolve(), params.onEnable, params.onDisable, params.onStart ?? (async () => Promise.resolve()), params.run, params.test ?? (() => Promise.resolve([params.sampleData])), params.sampleData, \"TEST_FUNCTION\", params.outputSchema, params.aiMetadata, params.classification, params.propertyGroups);\n\t\tcase \"APP_WEBHOOK\": return new ITrigger(params.name, params.displayName, params.description, params.requireAuth ?? true, params.props, params.type, { strategy: \"NONE\" }, async () => ({ status: 200 }), { strategy: \"NONE\" }, async () => Promise.resolve(), params.onEnable, params.onDisable, params.onStart ?? (async () => Promise.resolve()), params.run, params.test ?? (() => Promise.resolve([params.sampleData])), params.sampleData, isNil(params.sampleData) && isNil(params.test) ? \"SIMULATION\" : \"TEST_FUNCTION\", params.outputSchema, params.aiMetadata, params.classification, params.propertyGroups);\n\t\tdefault: {\n\t\t\tconst { name, type, strategy } = params;\n\t\t\tthrow new Error(type === void 0 && strategy !== void 0 ? `createTrigger: trigger ${JSON.stringify(name)} sets \\`strategy\\`; the field is \\`type\\`, e.g. type: TriggerStrategy.POLLING` : `createTrigger: trigger ${JSON.stringify(name)} has \\`type\\` ${JSON.stringify(type)}; set type: TriggerStrategy.POLLING or TriggerStrategy.WEBHOOK`);\n\t\t}\n\t}\n};\n\n//#endregion\n//#region upstream/framework/lib/context/index.ts\nvar PieceServerContextError = class extends Error {\n\tconstructor(message) {\n\t\tsuper(message);\n\t\tthis.name = \"PieceServerContextError\";\n\t}\n};\nfunction isPieceServerContextError(error) {\n\treturn error instanceof Error && error.name === \"PieceServerContextError\";\n}\nlet StoreScope = /* @__PURE__ */ function(StoreScope) {\n\tStoreScope[\"PROJECT\"] = \"COLLECTION\";\n\tStoreScope[\"FLOW\"] = \"FLOW\";\n\treturn StoreScope;\n}({});\n\n//#endregion\n//#region upstream/framework/lib/context/versioning.ts\nlet ContextVersion = /* @__PURE__ */ function(ContextVersion) {\n\tContextVersion[\"V1\"] = \"1\";\n\tContextVersion[\"V2\"] = \"2\";\n\treturn ContextVersion;\n}({});\nconst LATEST_CONTEXT_VERSION = \"2\";\nconst MINIMUM_SUPPORTED_RELEASE_AFTER_LATEST_CONTEXT_VERSION = \"0.82.0\";\nconst backwardCompatabilityContextUtils = { makeActionContextBackwardCompatible({ context, contextVersion }) {\n\tswitch (contextVersion) {\n\t\tcase \"2\": return context;\n\t\tcase \"1\": return addLegacyMethods({ context });\n\t\tcase void 0: return addLegacyMethodsAndServerUrl({ context });\n\t}\n} };\nfunction addLegacyMethods({ context }) {\n\treturn {\n\t\t...context,\n\t\tgenerateResumeUrl: buildLegacyGenerateResumeUrl({ context }),\n\t\trun: {\n\t\t\t...context.run,\n\t\t\tpause: buildLegacyPauseHook({ context })\n\t\t}\n\t};\n}\nfunction addLegacyMethodsAndServerUrl({ context }) {\n\treturn {\n\t\t...addLegacyMethods({ context }),\n\t\tserverUrl: context.server.publicUrl\n\t};\n}\n/**\n* @deprecated Since 2026-04-12. Remove after 2026-10-12 once all pieces migrate to createWaitpoint/waitForWaitpoint.\n*/\nfunction buildLegacyPauseHook({ context }) {\n\treturn (req) => {\n\t\tconst type = req.pauseMetadata.type === \"DELAY\" ? \"DELAY\" : \"WEBHOOK\";\n\t\tconst responseToSend = req.pauseMetadata.type === \"WEBHOOK\" ? req.pauseMetadata.response : void 0;\n\t\tconst resumeDateTime = req.pauseMetadata.type === \"DELAY\" ? req.pauseMetadata.resumeDateTime : void 0;\n\t\tcontext.run.createWaitpoint({\n\t\t\ttype,\n\t\t\tversion: \"V0\",\n\t\t\tresumeDateTime,\n\t\t\tresponseToSend\n\t\t}).catch((e) => {\n\t\t\tconsole.error(\"[buildLegacyPauseHook] Failed to create waitpoint\", e);\n\t\t\tprocess.exit(1);\n\t\t});\n\t\tcontext.run.waitForWaitpoint(\"\");\n\t};\n}\n/**\n* @deprecated Since 2026-04-12. Remove after 2026-10-12 once all pieces migrate to createWaitpoint/waitForWaitpoint.\n*/\nfunction buildLegacyGenerateResumeUrl({ context }) {\n\treturn (params) => {\n\t\tconst randomId = Math.random().toString(36).substring(2);\n\t\tconst url = new URL(`${context.server.publicUrl}v1/flow-runs/${context.run.id}/requests/${randomId}${params.sync ? \"/sync\" : \"\"}`);\n\t\turl.search = new URLSearchParams(params.queryParams).toString();\n\t\treturn url.toString();\n\t};\n}\n\n//#endregion\n//#region upstream/framework/lib/piece.ts\nvar Piece = class {\n\tdisplayName;\n\tlogoUrl;\n\tauthors;\n\tevents;\n\tcategories;\n\tauth;\n\tminimumSupportedRelease;\n\tmaximumSupportedRelease;\n\tdescription;\n\tdeprecated;\n\t_actions = {};\n\t_triggers = {};\n\tgetContextInfo = () => ({ version: \"2\" });\n\tconstructor(displayName, logoUrl, authors, events, actions, triggers, categories, auth, minimumSupportedRelease = MINIMUM_SUPPORTED_RELEASE_AFTER_LATEST_CONTEXT_VERSION, maximumSupportedRelease, description = \"\", deprecated) {\n\t\tthis.displayName = displayName;\n\t\tthis.logoUrl = logoUrl;\n\t\tthis.authors = authors;\n\t\tthis.events = events;\n\t\tthis.categories = categories;\n\t\tthis.auth = auth;\n\t\tthis.minimumSupportedRelease = minimumSupportedRelease;\n\t\tthis.maximumSupportedRelease = maximumSupportedRelease;\n\t\tthis.description = description;\n\t\tthis.deprecated = deprecated;\n\t\tif (!isValidSimpleSemver(minimumSupportedRelease) || isSemverLessThan(minimumSupportedRelease, \"0.82.0\")) this.minimumSupportedRelease = MINIMUM_SUPPORTED_RELEASE_AFTER_LATEST_CONTEXT_VERSION;\n\t\tactions.forEach((action) => this._actions[action.name] = action);\n\t\ttriggers.forEach((trigger) => this._triggers[trigger.name] = trigger);\n\t}\n\tmetadata() {\n\t\treturn {\n\t\t\tdisplayName: this.displayName,\n\t\t\tlogoUrl: this.logoUrl,\n\t\t\tactions: this._actions,\n\t\t\ttriggers: this._triggers,\n\t\t\tcategories: this.categories,\n\t\t\tdescription: this.description,\n\t\t\tauthors: this.authors,\n\t\t\tauth: withConnectionIdentifierFlag(this.auth),\n\t\t\tminimumSupportedRelease: this.minimumSupportedRelease,\n\t\t\tmaximumSupportedRelease: this.maximumSupportedRelease,\n\t\t\tdeprecated: this.deprecated,\n\t\t\tcontextInfo: this.getContextInfo?.()\n\t\t};\n\t}\n\tgetAction(actionName) {\n\t\treturn this._actions[actionName];\n\t}\n\tgetTrigger(triggerName) {\n\t\treturn this._triggers[triggerName];\n\t}\n\tactions() {\n\t\treturn this._actions;\n\t}\n\ttriggers() {\n\t\treturn this._triggers;\n\t}\n};\nconst createPiece = (params) => {\n\tif (params.auth && Array.isArray(params.auth)) {\n\t\tif (!params.auth.every((auth, index, self) => index === self.findIndex((t) => t.type === auth.type))) throw new Error(\"Auth properties must be unique by type\");\n\t}\n\treturn new Piece(params.displayName, params.logoUrl, params.authors ?? [], params.events, params.actions, params.triggers, params.categories ?? [], params.auth, params.minimumSupportedRelease, params.maximumSupportedRelease, params.description, params.deprecated);\n};\nfunction withConnectionIdentifierFlag(auth) {\n\tif (auth === void 0) return;\n\treturn Array.isArray(auth) ? auth.map(flagConnectionIdentifier) : flagConnectionIdentifier(auth);\n}\nfunction flagConnectionIdentifier(auth) {\n\treturn {\n\t\t...auth,\n\t\thasConnectionIdentifier: auth.getConnectionIdentifier !== void 0\n\t};\n}\nfunction isValidSimpleSemver(version) {\n\treturn /^\\d+\\.\\d+\\.\\d+$/.test(version);\n}\nfunction isSemverLessThan(a, b) {\n\tconst [a1, a2, a3] = a.split(\".\").map(Number);\n\tconst [b1, b2, b3] = b.split(\".\").map(Number);\n\tif (a1 !== b1) return a1 < b1;\n\tif (a2 !== b2) return a2 < b2;\n\treturn a3 < b3;\n}\n\n//#endregion\n//#region upstream/framework/lib/piece-metadata.ts\nconst I18nForPiece = z.optional(z.record(z.string(), z.record(z.string(), z.string())));\nconst PieceBase = z.object({\n\tid: z.optional(z.string()),\n\tname: z.string(),\n\tdisplayName: z.string(),\n\tlogoUrl: z.string(),\n\tdescription: z.string(),\n\tauthors: z.array(z.string()),\n\tplatformId: z.optional(z.string()),\n\tdirectoryPath: z.optional(z.string()),\n\tauth: z.optional(z.union([PieceAuthProperty, z.array(PieceAuthProperty)])),\n\tversion: z.string(),\n\tcategories: z.optional(z.array(z.enum(PieceCategory))),\n\tminimumSupportedRelease: z.optional(z.string()),\n\tmaximumSupportedRelease: z.optional(z.string()),\n\tdeprecated: z.optional(z.boolean()),\n\ti18n: I18nForPiece\n});\nconst Audience = z.enum([\n\t\"human\",\n\t\"ai\",\n\t\"both\"\n]);\nconst AiMetadata = z.object({\n\tdescription: z.optional(z.string()),\n\tidempotent: z.optional(z.boolean())\n});\nconst ActionClassification = z.enum([\n\t\"READ\",\n\t\"SEARCH\",\n\t\"WRITE\",\n\t\"DESTRUCTIVE\"\n]);\nconst READ_ONLY_CLASSIFICATIONS = [\"READ\", \"SEARCH\"];\nconst isReadOnlyClassification = (classification) => classification !== void 0 && READ_ONLY_CLASSIFICATIONS.includes(classification);\nconst PropertyGroupDisplay = z.enum([\n\t\"tabs\",\n\t\"section\",\n\t\"summary\",\n\t\"builder\",\n\t\"footer\"\n]);\nconst PropertyGroup = z.object({\n\tkey: z.string(),\n\tdisplay: PropertyGroupDisplay,\n\tlabel: z.optional(z.string()),\n\tdescription: z.optional(z.string()),\n\ticon: z.optional(z.string()),\n\tprops: z.array(z.string())\n});\nconst ActionBase = z.object({\n\tname: z.string(),\n\tdisplayName: z.string(),\n\tdescription: z.string(),\n\tprops: PiecePropertyMap,\n\tpropertyGroups: z.optional(z.array(PropertyGroup)),\n\trequireAuth: z.boolean(),\n\terrorHandlingOptions: z.optional(ErrorHandlingOptionsParam),\n\toutputSchema: z.optional(z.custom()),\n\taudience: z.optional(Audience),\n\taiMetadata: z.optional(AiMetadata),\n\tclassification: z.optional(ActionClassification)\n});\nconst TriggerBase = z.object({\n\tname: z.string(),\n\tdisplayName: z.string(),\n\tdescription: z.string(),\n\tprops: PiecePropertyMap,\n\tpropertyGroups: z.optional(z.array(PropertyGroup)),\n\terrorHandlingOptions: z.optional(ErrorHandlingOptionsParam),\n\ttype: z.enum(TriggerStrategy),\n\tsampleData: z.unknown(),\n\thandshakeConfiguration: z.optional(z.custom()),\n\trenewConfiguration: z.optional(WebhookRenewConfiguration),\n\ttestStrategy: z.enum(TriggerTestStrategy),\n\toutputSchema: z.optional(z.custom()),\n\taiMetadata: z.optional(AiMetadata),\n\tclassification: z.optional(ActionClassification)\n});\nconst PieceMetadata = z.object({\n\t...PieceBase.shape,\n\tactions: z.record(z.string(), ActionBase),\n\ttriggers: z.record(z.string(), TriggerBase)\n});\nconst PieceMetadataSummary = z.object({\n\t...PieceBase.shape,\n\tactions: z.number(),\n\ttriggers: z.number(),\n\tsuggestedActions: z.optional(z.array(ActionBase)),\n\tsuggestedTriggers: z.optional(z.array(TriggerBase))\n});\nconst PiecePackageMetadata = z.object({\n\tprojectUsage: z.number(),\n\tpieceType: z.enum(PieceType),\n\tpackageType: z.enum(PackageType),\n\tplatformId: z.optional(z.string()),\n\tarchiveId: z.optional(z.string())\n});\nconst PieceMetadataModel = z.object({\n\t...PieceMetadata.shape,\n\t...PiecePackageMetadata.shape\n});\nconst PieceMetadataModelSummary = z.object({\n\t...PieceMetadataSummary.shape,\n\t...PiecePackageMetadata.shape\n});\nconst PiecePackageInformation = z.object({\n\tname: z.string(),\n\tversion: z.string()\n});\n\n//#endregion\n//#region upstream/framework/lib/i18n.ts\nconst pieceTranslation = {\n\ttranslatePiece: (params) => {\n\t\tconst { piece, locale, mutate = false } = params;\n\t\tif (!locale) return piece;\n\t\ttry {\n\t\t\tconst target = piece.i18n?.[locale];\n\t\t\tif (!target) return piece;\n\t\t\tconst translatedPiece = mutate ? piece : JSON.parse(JSON.stringify(piece));\n\t\t\tpieceTranslation.pathsToValuesToTranslate.forEach((key) => {\n\t\t\t\ttranslateProperty(translatedPiece, key, target);\n\t\t\t});\n\t\t\treturn translatedPiece;\n\t\t} catch (err) {\n\t\t\tconsole.error(`error translating piece ${piece.name}:`, err);\n\t\t\treturn piece;\n\t\t}\n\t},\n\t/**Gets the piece metadata regardles of piece location (node_modules or dist), wasn't included inside piece.metadata() for backwards compatibility issues (if an old ap version installs a new piece it would fail)*/\n\tinitializeI18n: async (pieceOutputPath) => {\n\t\ttry {\n\t\t\tconst locales = Object.values(LocalesEnum);\n\t\t\tconst i18n = {};\n\t\t\tfor (const locale of locales) {\n\t\t\t\tconst translations = await readLocaleFile(locale, pieceOutputPath);\n\t\t\t\tif (translations) i18n[locale] = translations;\n\t\t\t}\n\t\t\treturn Object.keys(i18n).length > 0 ? i18n : void 0;\n\t\t} catch (err) {\n\t\t\tconsole.log(`Error initializing i18n for ${pieceOutputPath}:`, err);\n\t\t\treturn;\n\t\t}\n\t},\n\tpathsToValuesToTranslate: [\n\t\t\"description\",\n\t\t\"auth.username.displayName\",\n\t\t\"auth.username.description\",\n\t\t\"auth.password.displayName\",\n\t\t\"auth.password.description\",\n\t\t\"auth.props.*.displayName\",\n\t\t\"auth.props.*.description\",\n\t\t\"auth.props.*.options.options.*.label\",\n\t\t\"auth.description\",\n\t\t\"actions.*.displayName\",\n\t\t\"actions.*.description\",\n\t\t\"actions.*.props.*.displayName\",\n\t\t\"actions.*.props.*.description\",\n\t\t\"actions.*.props.*.options.options.*.label\",\n\t\t\"triggers.*.displayName\",\n\t\t\"triggers.*.description\",\n\t\t\"triggers.*.props.*.displayName\",\n\t\t\"triggers.*.props.*.description\",\n\t\t\"triggers.*.props.*.options.options.*.label\"\n\t]\n};\n/**This function translates a property inside a piece, i.e description, displayName, etc...\n*\n* @param pieceModelOrProperty - The piece model or property to translate\n* @param path - The path to the property to translate, i.e auth.username.displayName\n* @param i18n - The i18n object\n*/\nfunction translateProperty(pieceModelOrProperty, path, i18n) {\n\tconst parsedKeys = path.split(\".\");\n\tif (parsedKeys[0] === \"*\") return Object.values(pieceModelOrProperty).forEach((item) => translateProperty(item, parsedKeys.slice(1).join(\".\"), i18n));\n\tconst nextObject = pieceModelOrProperty[parsedKeys[0]];\n\tif (!nextObject) return;\n\tif (parsedKeys.length > 1) return translateProperty(nextObject, parsedKeys.slice(1).join(\".\"), i18n);\n\tconst valueInI18n = i18n[pieceModelOrProperty[parsedKeys[0]].slice(0, 512)];\n\tif (valueInI18n) pieceModelOrProperty[parsedKeys[0]] = valueInI18n;\n}\nasync function fileExists(filePath) {\n\ttry {\n\t\tawait fs.access(filePath);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\nconst readLocaleFile = async (locale, pieceOutputPath) => {\n\tconst filePath = path.join(pieceOutputPath, \"src\", \"i18n\", `${locale}.json`);\n\tif (!await fileExists(filePath)) return null;\n\ttry {\n\t\tconst fileContent = await fs.readFile(filePath, \"utf8\");\n\t\tconst translations = JSON.parse(fileContent);\n\t\tif (typeof translations === \"object\" && translations !== null) return translations;\n\t\tthrow new Error(`Invalid i18n file format for ${locale} in piece ${pieceOutputPath}`);\n\t} catch (error) {\n\t\tconsole.error(`Error reading i18n file for ${locale} in piece ${pieceOutputPath}:`, error);\n\t\treturn null;\n\t}\n};\n\n//#endregion\n//#region upstream/framework/lib/test/index.ts\nfunction createMockActionContext(params) {\n\treturn {\n\t\texecutionType: \"BEGIN\",\n\t\tauth: void 0,\n\t\tpropsValue: params.propsValue,\n\t\tstore: {\n\t\t\tput: async (key, value) => value,\n\t\t\tget: async () => null,\n\t\t\tdelete: async () => {}\n\t\t},\n\t\tconnections: { get: async () => null },\n\t\ttags: { add: async () => {} },\n\t\tserver: {\n\t\t\tapiUrl: \"http://localhost:3000\",\n\t\t\tpublicUrl: \"http://localhost:4200\",\n\t\t\ttoken: \"test-token\"\n\t\t},\n\t\tfiles: { write: async () => \"test-file-url\" },\n\t\toutput: { update: async () => {} },\n\t\tagent: { tools: async () => ({}) },\n\t\trun: {\n\t\t\tid: \"test-run-id\",\n\t\t\tstop: () => {},\n\t\t\tpause: () => {},\n\t\t\trespond: () => {}\n\t\t},\n\t\tproject: {\n\t\t\tid: \"test-project-id\",\n\t\t\texternalId: async () => void 0\n\t\t},\n\t\tflows: {\n\t\t\tlist: async () => ({\n\t\t\t\tdata: [],\n\t\t\t\tnext: null,\n\t\t\t\tprevious: null\n\t\t\t}),\n\t\t\tcurrent: {\n\t\t\t\tid: \"test-flow-id\",\n\t\t\t\tversion: { id: \"test-flow-version-id\" }\n\t\t\t}\n\t\t},\n\t\tstep: { name: \"test-step\" },\n\t\tgenerateResumeUrl: () => \"http://localhost:3000/resume\"\n\t};\n}\nfunction createMockPollingTriggerContext(params) {\n\treturn {\n\t\t...createMockActionContext({ propsValue: params.propsValue }),\n\t\tsetSchedule: (schedule) => {\n\t\t\tparams.onSetSchedule?.(schedule);\n\t\t}\n\t};\n}\n\n//#endregion\n//#region src/powerhouse/create.ts\nfunction createAction(params) {\n\tconst { requireReactor, ...rest } = params;\n\treturn withDeclaration(createAction$1(rest), requireReactor);\n}\nfunction createTrigger(params) {\n\tconst { requireReactor, ...rest } = params;\n\treturn withDeclaration(createTrigger$1(rest), requireReactor);\n}\nfunction withDeclaration(block, requireReactor) {\n\tif (requireReactor === void 0 || requireReactor === false) return block;\n\tif (requireReactor !== \"read\" && requireReactor !== \"write\") throw new Error(`requireReactor must be \"read\", \"write\" or false, got ${JSON.stringify(requireReactor)}`);\n\treturn Object.assign(block, { requireReactor });\n}\n\n//#endregion\n//#region src/powerhouse/property.ts\nconst Property = {\n\t...Property$1,\n\tDropdown(request) {\n\t\treturn Property$1.Dropdown(request);\n\t},\n\tMultiSelectDropdown(request) {\n\t\treturn Property$1.MultiSelectDropdown(request);\n\t},\n\tDynamicProperties(request) {\n\t\treturn Property$1.DynamicProperties(request);\n\t}\n};\n\n//#endregion\n//#region src/powerhouse/errors.ts\nconst ReactorJobPendingError = \"ReactorJobPendingError\";\nconst ReactorJobFailedError = \"ReactorJobFailedError\";\nconst ReactorActionsFailedError = \"ReactorActionsFailedError\";\nconst ReactorAccessDeniedError = \"ReactorAccessDeniedError\";\nconst ReactorRequestClosedError = \"ReactorRequestClosedError\";\nconst DocumentModelUnavailableError = \"DocumentModelUnavailableError\";\n\n//#endregion\nexport { ACTIVEPIECES_CHAT_TIERS, AGENT_STEP_TEST_TIMEOUT_MS, AGENT_STEP_TIMEOUT_MS, AIProviderModel, AIProviderName, AIProviderWithoutSensitiveData, AI_PROVIDER_CAPABILITIES, ActionBase, ActionClassification, AgentFlowTool, AgentKnowledgeBaseTool, AgentMcpTool, AgentOutputField, AgentOutputFieldType, AgentPieceProps, AgentStepBlock, AgentTaskStatus, AgentTool, AgentToolType, AiMetadata, ApFile, AppConnectionType, ArrayProperty, ArraySubProps, Audience, AzureProviderConfig, BaseAIProviderAuthConfig, BasePropertySchema, BasicAuthProperty, BasicAuthPropertyValue, BedrockProviderAuthConfig, BedrockProviderConfig, ChatFormResponse, CheckboxProperty, CloudflareGatewayProviderConfig, ContentBlockType, ContextVersion, CreateRecordsRequest, CreateTableWebhookRequest, CustomAuthProperty, CustomProperty, DEDUPE_KEY_PROPERTY, DEFAULT_CHAT_TIER_ID, DEFAULT_CONNECTION_DISPLAY_NAME, DateRangePreset, DateRangeProperty, DateRangeValue, DateTimeProperty, DocumentModelUnavailableError, DropdownOption, DropdownProperty, DropdownState, DynamicProp, DynamicProperties, DynamicPropsValue, ErrorHandlingOptionsParam, ExecutionToolStatus, ExecutionType, ExportTableResponse, FAIL_PARENT_ON_FAILURE_HEADER, Field, FieldType, FileProperty, FileResponseInterface, Filter, FilterOperator, FlowStatus, FlowTriggerType, GetProviderConfigResponse, HumanInputFormResult, HumanInputFormResultTypes, IAction, ITrigger, InputProperty, InputPropertyMap, JsonProperty, KnowledgeBaseSourceType, LATEST_CONTEXT_VERSION, ListRecordsRequest, ListTablesRequest, LongTextProperty, MINIMUM_SUPPORTED_RELEASE_AFTER_LATEST_CONTEXT_VERSION, MarkdownContentBlock, MarkdownVariant, McpAuthConfig, McpAuthType, McpProperty, McpPropertyType, McpProtocol, McpTrigger, MultiSelectDropdownProperty, NumberProperty, OAuth2AuthorizationMethod, OAuth2GrantType, OAuth2Property, OAuth2PropertyValue, OAuth2Props, OIDCProperty, OPENAI_COMPATIBLE_VENDOR_BASE_URLS, ObjectProperty, OpenAICompatibleProviderConfig, OpenAiCompatibleVendorConfig, PARENT_RUN_ID_HEADER, Piece, PieceAuth, PieceAuthProperty, PieceBase, PieceCategory, PieceMetadata, PieceMetadataModel, PieceMetadataModelSummary, PieceMetadataSummary, PiecePackageInformation, PieceProperty, PiecePropertyMap, PieceServerContextError, PopulatedRecord, Project, ProjectAIProvider, Property, PropertyGroup, PropertyGroupDisplay, PropertyType, RAW_PAYLOAD_HEADER, READ_ONLY_CLASSIFICATIONS, ReactorAccessDeniedError, ReactorActionsFailedError, ReactorJobFailedError, ReactorJobPendingError, ReactorRequestClosedError, RichTextProperty, SecretTextProperty, SeekPage, ShortTextProperty, StaticDropdownEmptyOption, StaticDropdownProperty, StaticMultiSelectDropdownProperty, StopResponse, StoreScope, TASK_COMPLETION_TOOL_NAME, Table, TableWebhookEventType, ToolCallContentBlock, ToolCallStatus, ToolCallType, TriggerBase, TriggerStrategy, USE_DRAFT_QUERY_PARAM_NAME, UpdateRecordRequest, VertexProviderAuthConfig, VertexProviderConfig, WebhookHandshakeStrategy, WebhookRenewConfiguration, WebhookRenewStrategy, apId, assertNotNullOrUndefined, backwardCompatabilityContextUtils, buildAuthHeaders, camelCase, chunk, createAction, createKeyForFormInput, createMockActionContext, createMockPollingTriggerContext, createPiece, createTrigger, dateRangeUtils, getAuthPropertyForValue, getEffectiveProviderAndModel, isEmpty, isNil, isNotUndefined, isPieceServerContextError, isReadOnlyClassification, isString, kebabCase, mcpToolNameUtils, normalizeToolOutputToExecuteResponse, pickBy, piecePropertiesUtils, pieceTranslation, splitCloudflareGatewayModelId, spreadIfDefined, startCase, tryCatch, unique };\n//# sourceMappingURL=index.js.map","// Their StoreScope, as a name the host can partition on.\nimport { StoreScope } from \"@powerhousedao/pieces-framework\";\n\n// The enum's PROJECT member carries the legacy value \"COLLECTION\", and an\n// omitted scope means FLOW, so both are folded to one name here.\nexport type StoreScopeName = keyof typeof StoreScope;\n\n// Compared by value, never by enum identity: a piece bundle inlines its own\n// copy of StoreScope, and some pass the member name instead of its value.\nexport function normalizeStoreScope(scope?: unknown): StoreScopeName {\n return scope === StoreScope.PROJECT || scope === \"PROJECT\"\n ? \"PROJECT\"\n : \"FLOW\";\n}\n","// Our ActionContext → their ActionContext (doc 06 §2.8). Implements the top usage\n// tier (propsValue, auth, store, connections); the rest throws loudly, named.\nimport { throwingStub, withTouchTracking } from \"./stubs.js\";\nimport { jsonSafe } from \"../worker/json-safe.js\";\nimport { normalizeStoreScope, type StoreScopeName } from \"./store-scope.js\";\nimport type { ApFilesService } from \"./files.js\";\nimport type { ConnectionsProvider } from \"./props.js\";\nimport type { ReactorOption } from \"./reactor-option.js\";\nimport type {\n BaseContext,\n ConnectionsManager,\n ExecutionType,\n FilesService,\n FlowsContext,\n InputPropertyMap,\n OutputContext,\n ReactorClient,\n ReactorReadClient,\n RunContext,\n ServerContext,\n StepContext,\n Store,\n TagsManager,\n} from \"@powerhousedao/pieces-framework\";\n\nexport { UnsupportedContextMemberError } from \"./stubs.js\";\n\n// The scope travels beside the key rather than inside it: which partition a\n// key belongs to is the host's decision, not a naming convention.\n\n// The host's half of the framework's Store, with its generics dropped: a\n// durable store round-trips through JSON, so nothing comes back as the T put in.\nexport interface KeyValueStore {\n put(key: string, value: unknown, scope?: StoreScopeName): Promise<unknown>;\n get(key: string, scope?: StoreScopeName): Promise<unknown>;\n delete(key: string, scope?: StoreScopeName): Promise<void>;\n}\n\n// In-memory connection registry: key → resolved connection value.\nexport class InMemoryConnectionsProvider implements ConnectionsProvider {\n private readonly values: Map<string, unknown>;\n\n constructor(values: Record<string, unknown> = {}) {\n this.values = new Map(Object.entries(values));\n }\n\n set(key: string, value: unknown): void {\n this.values.set(key, value);\n }\n\n get(key: string): Promise<unknown> {\n return Promise.resolve(this.values.get(key) ?? null);\n }\n}\n\nexport class InMemoryKeyValueStore implements KeyValueStore {\n private readonly entries: Map<string, unknown>;\n\n constructor(seed: Record<string, unknown> = {}) {\n this.entries = new Map(Object.entries(seed));\n }\n\n snapshot(): Record<string, unknown> {\n return Object.fromEntries(this.entries);\n }\n\n // Flattened like the durable store, so the heap fallback is not the one\n // place a Date survives a put.\n put(key: string, value: unknown, scope?: StoreScopeName): Promise<unknown> {\n const stored = jsonSafe(value);\n this.entries.set(this.scoped(key, scope), stored);\n return Promise.resolve(stored);\n }\n\n get(key: string, scope?: StoreScopeName): Promise<unknown> {\n return Promise.resolve(this.entries.get(this.scoped(key, scope)) ?? null);\n }\n\n delete(key: string, scope?: StoreScopeName): Promise<void> {\n this.entries.delete(this.scoped(key, scope));\n return Promise.resolve();\n }\n\n // One heap, so the scopes share it and are kept apart by name.\n private scoped(key: string, scope?: StoreScopeName): string {\n return scope === \"PROJECT\" ? `PROJECT:${key}` : key;\n }\n}\n\nexport interface ActionContextIdentity {\n runId?: string;\n projectId?: string;\n flowId?: string;\n flowVersionId?: string;\n stepName?: string;\n}\n\nexport type ActionContextOptions = ActionContextBaseOptions & ReactorOption;\n\ninterface ActionContextBaseOptions {\n propsValue: Record<string, unknown>;\n auth?: unknown;\n store?: KeyValueStore;\n // ctx.files for actions. Mirrors the option triggers already accept; when\n // omitted the member keeps throwing, so a piece that needs files fails\n // loudly rather than silently dropping them.\n files?: ApFilesService;\n connections?: ConnectionsProvider;\n // ctx.output.update, the piece's own progress report. Omitted, the member\n // throws, so a piece that depends on it fails by name rather than silently.\n output?: { update(output: unknown): Promise<void> };\n // ctx.resumePayload, the delivery that woke a RESUME run. This engine never\n // suspends a run, so no request carries one yet; omitted, the member throws\n // by name instead of reading as undefined.\n resumePayload?: unknown;\n executionType?: `${ExecutionType}`;\n identity?: ActionContextIdentity;\n onTouch?: (member: string) => void;\n}\n\n// Shape of the context we hand to `action.run()`: the framework's ActionContext\n// member for member. Those beyond the implemented tier throw, named.\nexport interface BuiltApActionContext {\n executionType: `${ExecutionType}`;\n auth: unknown;\n propsValue: Record<string, unknown>;\n store: Store;\n connections: ConnectionsManager;\n tags: TagsManager;\n server: ServerContext;\n files: FilesService;\n output: OutputContext;\n reactor: ReactorClient | ReactorReadClient;\n // The RESUME branch of the framework's ActionContext promises this\n // (ResumePayload there, a type its entry does not export). Always present,\n // real or throwing, like `reactor`.\n resumePayload: unknown;\n // Carried by the framework's own test double but absent from its types.\n agent: { tools: unknown[] };\n run: RunContext;\n project: BaseContext<undefined, InputPropertyMap>[\"project\"];\n flows: FlowsContext;\n step: StepContext;\n generateResumeUrl(params: {\n queryParams: Record<string, string>;\n sync?: boolean;\n }): string;\n}\n\nexport interface ActionContextHandle {\n context: BuiltApActionContext;\n // Top-level members the piece read; `UNDOCUMENTED:<name>` marks unknown reads.\n touched: ReadonlySet<string>;\n}\n\nexport function buildActionContext(\n options: ActionContextOptions,\n): ActionContextHandle {\n const { identity = {} } = options;\n const store = options.store ?? new InMemoryKeyValueStore();\n const touched = new Set<string>();\n\n const base: Record<string, unknown> = {\n executionType: options.executionType ?? \"BEGIN\",\n auth: options.auth,\n propsValue: options.propsValue,\n store: {\n put: (key: string, value: unknown, scope?: unknown) =>\n store.put(key, value, normalizeStoreScope(scope)),\n get: (key: string, scope?: unknown) =>\n store.get(key, normalizeStoreScope(scope)),\n delete: (key: string, scope?: unknown) =>\n store.delete(key, normalizeStoreScope(scope)),\n },\n connections: options.connections ?? throwingStub(\"connections\"),\n tags: throwingStub(\"tags\"),\n server: throwingStub(\"server\"),\n files: options.files ?? throwingStub(\"files\"),\n output: options.output ?? throwingStub(\"output\"),\n reactor: options.reactor ?? throwingStub(\"reactor\"),\n resumePayload: options.resumePayload ?? throwingStub(\"resumePayload\"),\n agent: throwingStub(\"agent\"),\n run: {\n id: identity.runId ?? \"run\",\n stop: throwingStub(\"run.stop\"),\n pause: throwingStub(\"run.pause\"),\n respond: throwingStub(\"run.respond\"),\n createWaitpoint: throwingStub(\"run.createWaitpoint\"),\n waitForWaitpoint: throwingStub(\"run.waitForWaitpoint\"),\n },\n project: {\n id: identity.projectId ?? \"project\",\n externalId: () => Promise.resolve(identity.projectId ?? \"project\"),\n },\n flows: {\n list: throwingStub(\"flows.list\"),\n current: {\n id: identity.flowId ?? \"flow\",\n version: { id: identity.flowVersionId ?? \"flow-version\" },\n },\n },\n step: { name: identity.stepName ?? \"step\" },\n generateResumeUrl: throwingStub(\"generateResumeUrl\"),\n };\n\n const context = withTouchTracking(base, touched, options.onTouch);\n return { context: context as unknown as BuiltApActionContext, touched };\n}\n","import type { ActionContextIdentity } from \"../context/action.js\";\nimport type { StagedFile } from \"../context/files.js\";\nimport type { PropsValidationErrors } from \"../context/normalize.js\";\nimport type {\n ExecutionType,\n ServerContext,\n} from \"@powerhousedao/pieces-framework\";\nimport type { RecordedListener, RecordedSchedule } from \"../context/trigger.js\";\n\n// One FILE-prop value the host resolved to a path before the run, so the\n// bytes reach the worker through the shared filesystem instead of JSON IPC.\nexport interface StagedInput {\n ref: string;\n path: string;\n fileName?: string;\n contentType?: string;\n // Why the host could not stage it; a FILE prop that needs it fails with this.\n error?: string;\n}\n\n// Where a piece may connect to while this request runs. Enforced in the child\n// at socket-connect time; absent means unrestricted, which is the old behaviour.\nexport interface EgressPolicy {\n // Hostnames (or literal IPs) the piece may reach; a leading \"*.\" matches\n // subdomains. Omitted or empty allows any host the address rules permit.\n allowHosts?: string[];\n // Addresses or CIDRs reachable even though they are private — a service on\n // the operator's own network, say.\n allowAddresses?: string[];\n // Lifts the private-address block, for an operator whose isolation lives\n // elsewhere. Local sockets, UDP and listening stay refused under any policy.\n allowPrivateAddresses?: boolean;\n // TCP ports the piece may reach; omitted or empty allows any.\n allowPorts?: number[];\n}\n\n// The child is forked with an empty env, so what the host's environment decides\n// can only arrive on the wire: every request carries what is in force for the\n// work it asks for.\nexport interface HostScopedRequest {\n egress?: EgressPolicy;\n // Ceiling for FILE-prop hydration and ctx.files.write, from the host's\n // PH_WORKFLOWS_PIECE_MAX_FILE_BYTES. Absent leaves the built-in default.\n maxFileBytes?: number;\n // Epoch ms at which the host kills the worker for this request.\n deadline?: number;\n // Cap on each host call. Absent leaves the built-in default.\n hostCallTimeoutMs?: number;\n}\n\n// `ctx.reactor` for one request: its RPC messages carry `requestId`, and the\n// host serves them only while the request is in flight.\nexport interface ReactorRequestBinding {\n requestId: string;\n requireReactor: \"read\" | \"write\";\n}\n\nexport interface ReactorScopedRequest {\n // Stamped by PieceWorker when the caller serves the reactor.\n reactor?: ReactorRequestBinding;\n}\n\nexport const REACTOR_RPC = \"reactor-rpc\";\nexport const MODEL_MANIFEST = \"model-manifest\";\n// Host call: a type's entries, or every entry the host knows without one.\nexport const MODEL_ENTRIES = \"model-entries\";\n\n// One reactor RPC message (`@powerhousedao/reactor/rpc`), either direction.\nexport interface ReactorRpcEnvelope {\n type: typeof REACTOR_RPC;\n requestId: string;\n message: unknown;\n}\n\n// Importable document models (the reactor's ModelManifestEntry), host to child\n// on fork. A type loaded later is looked up through MODEL_ENTRIES.\nexport interface ModelEntriesPayload {\n documentType?: string;\n}\n\nexport interface ModelManifestMessage {\n type: typeof MODEL_MANIFEST;\n entries: unknown[];\n}\n\n// Where the worker finds the piece module: a bundle directory in npm shape, as\n// a registry fetch extracts it, or the module file of an installed package.\n\n// Exactly one is set; a request carrying neither is refused before any load.\nexport interface PieceModuleRef {\n bundleDir?: string;\n entryPath?: string;\n}\n\nexport interface RunActionRequest\n extends HostScopedRequest, PieceModuleRef, ReactorScopedRequest {\n actionName: string;\n propsValue: Record<string, unknown>;\n auth?: unknown;\n // Where ctx.files.write() puts bytes for the host to ingest. Without it the\n // action gets the data-URI service instead.\n stagingDir?: string;\n // Attachment refs in propsValue, already materialized by the host.\n stagedInputs?: StagedInput[];\n // Resolved connection values served to ctx.connections.get(key).\n connections?: Record<string, unknown>;\n // Store partition; runs sharing a scope share state for the worker's lifetime.\n storeScope?: string;\n // Serve `ctx.store` from the host over the call channel instead of the\n // in-memory partition above, so a write survives this worker.\n durableStore?: boolean;\n // Forward the piece's console output to the host as it is written. Off by\n // default: a chatty piece would otherwise pay IPC for logs nobody reads.\n captureLogs?: boolean;\n // Implement `ctx.output.update`, which reports progress mid-step. Without\n // it the member keeps throwing, so a piece that needs it fails loudly.\n liveOutput?: boolean;\n executionType?: `${ExecutionType}`;\n // The delivery that woke a RESUME run, served as ctx.resumePayload. This\n // engine never suspends a run, so nothing sets it yet; absent, the context\n // member keeps throwing by name.\n resumePayload?: unknown;\n // Call the action's test method instead of run, as a single-step test does.\n stepTest?: boolean;\n identity?: ActionContextIdentity;\n // Concrete secret values resolved for this step, so the child can strip them\n // from an error before it crosses back; they already travel inside `auth`.\n redactValues?: string[];\n}\n\nexport interface RunMessage {\n id: number;\n type: \"run\";\n request: RunActionRequest;\n}\n\n// Design-time resolution of a DROPDOWN options() / DYNAMIC props() resolver.\nexport interface ResolveOptionsRequest\n extends HostScopedRequest, PieceModuleRef, ReactorScopedRequest {\n // Action or trigger name, per kind (default \"action\").\n actionName: string;\n kind?: \"action\" | \"trigger\";\n propName: string;\n refresherValues?: Record<string, unknown>;\n auth?: unknown;\n searchValue?: string;\n // ctx.project.id, the same one a run of the piece is handed.\n projectId?: string;\n}\n\nexport interface ResolveOptionsMessage {\n id: number;\n type: \"resolve-options\";\n request: ResolveOptionsRequest;\n}\n\n// One trigger lifecycle hook. With `durableStore` its `ctx.store` is the same\n// host-served store an action gets, so a write lands as the hook makes it.\n\n// Without one it runs statelessly: `storeState` seeds an in-memory store and\n// the whole snapshot comes back in the response for the caller to persist.\nexport interface TriggerHookRequest\n extends HostScopedRequest, PieceModuleRef, ReactorScopedRequest {\n triggerName: string;\n hook: \"onEnable\" | \"onDisable\" | \"run\" | \"test\" | \"onHandshake\" | \"onRenew\";\n propsValue: Record<string, unknown>;\n auth?: unknown;\n storeState?: Record<string, unknown>;\n // Serve `ctx.store` from the host over the call channel, exactly as\n // RunActionRequest does, instead of seeding and returning the snapshot above.\n durableStore?: boolean;\n identity?: ActionContextIdentity;\n // onEnable of an unchanged trigger; pollingHelper keeps its cursor.\n isRepublish?: boolean;\n // WEBHOOK payloads; also handed to test runs.\n payload?: unknown;\n webhookUrl?: string;\n server?: ServerContext;\n // As on a run request: secrets stripped from errors before they cross back.\n redactValues?: string[];\n}\n\nexport interface TriggerHookMessage {\n id: number;\n type: \"trigger-hook\";\n request: TriggerHookRequest;\n}\n\n// A connection credential check. Auth crosses into the worker and stays\n// there: the piece code that reads it never runs in the host process.\nexport interface CheckConnectionRequest\n extends HostScopedRequest, PieceModuleRef {\n auth?: unknown;\n}\n\nexport interface CheckConnectionMessage {\n id: number;\n type: \"check-connection\";\n request: CheckConnectionRequest;\n}\n\n// `output` of a check-connection result.\nexport interface CheckConnectionOutcome {\n // False when the piece's auth declares no validate.\n declared: boolean;\n // validate's verdict; true when none is declared.\n valid: boolean;\n // Why validate failed, when it said so.\n detail?: string;\n // getConnectionIdentifier's label; it runs only once the check passes.\n accountLabel?: string;\n // Why getConnectionIdentifier threw. The check still passes.\n identifierError?: string;\n}\n\n// Design-time descriptor of a piece: its actions, triggers and auth shape.\n// Building one requires the piece module, whose top-level code runs on load,\n// so it is built in the worker and only the plain descriptor crosses back.\nexport interface DescribePieceRequest\n extends HostScopedRequest, PieceModuleRef {\n // Carried through into the descriptor's `source` and its resolver ids.\n packageName: string;\n version: string;\n}\n\nexport interface DescribePieceMessage {\n id: number;\n type: \"describe\";\n request: DescribePieceRequest;\n}\n\nexport type WorkerRequestMessage =\n | RunMessage\n | ResolveOptionsMessage\n | TriggerHookMessage\n | CheckConnectionMessage\n | DescribePieceMessage;\n\n// Piece errors cross the IPC boundary as data; classify on these fields.\nexport interface SerializedPieceError {\n name: string;\n message: string;\n // The error's own enumerable properties, plus the HTTP status, request and\n // response the framework's error formatter recovered from it.\n properties: Record<string, unknown>;\n // Set when the piece hit an unimplemented context member.\n unsupportedMember?: string;\n // Set when the piece or trigger uses a feature this engine does not run.\n unsupportedFeature?: string;\n // Set when the props failed validation, before piece code ran.\n invalidProps?: PropsValidationErrors;\n}\n\nexport interface ResultResponse {\n id: number;\n type: \"result\";\n output: unknown;\n touched: string[];\n // True when the piece set NODE_TLS_REJECT_UNAUTHORIZED=0 (contained to the worker).\n tlsPoisoned: boolean;\n // Files the piece wrote through ctx.files during this request. The host\n // ingests each one, then rewrites its provisional token in `output`.\n files?: StagedFile[];\n // trigger-hook only: final store contents plus captured context calls.\n storeState?: Record<string, unknown>;\n schedules?: RecordedSchedule[];\n listeners?: RecordedListener[];\n timings?: WorkerTimings;\n}\n\nexport interface ErrorResponse {\n id: number;\n type: \"error\";\n error: SerializedPieceError;\n tlsPoisoned: boolean;\n timings?: WorkerTimings;\n}\n\n// One part of serving a request, in epoch ms: piece.load, reactor.open,\n// models, action.\nexport interface WorkerPhaseTiming {\n name: string;\n start: number;\n end: number;\n // The phase this one ran inside, e.g. \"action\" for a model loaded mid-action.\n parent?: string;\n attributes?: Record<string, string | boolean>;\n}\n\n// Where a request's time went inside the child, in epoch ms.\nexport interface WorkerTimings {\n received: number;\n sent: number;\n phases: WorkerPhaseTiming[];\n // When the child's entry finished loading; on its first response only.\n ready?: number;\n // The child's process.memoryUsage() as it answered, in bytes.\n memory?: WorkerMemory;\n}\n\nexport interface WorkerMemory {\n rss: number;\n heapUsed: number;\n heapTotal: number;\n external: number;\n}\n\nexport type WorkerResponse = ResultResponse | ErrorResponse;\n\n// A request the child makes of its host while a step is running: the reverse\n// direction of everything above, and the only way a piece reaches durable state.\n\n// Ids are the child's own counter, a separate space from the host's, which is\n// why every handler dispatches on `type` before comparing an id.\nexport interface HostCallMessage {\n id: number;\n type: \"host-call\";\n method: string;\n payload: unknown;\n}\n\n// `error` carries the failure as data: a rejected promise cannot cross IPC,\n// so the reply always arrives and the child rethrows.\nexport interface HostCallResponse {\n id: number;\n type: \"host-result\";\n value?: unknown;\n error?: string;\n}\n\n// What the host will answer for the request in flight. Registered per request,\n// so a call arriving after the step returned finds nothing and is refused.\nexport type HostCallHandlers = Record<\n string,\n (payload: unknown) => Promise<unknown>\n>;\n\n// The one-way half of the channel: a report the host may act on, with no\n// answer to wait for. Their engine splits the same way (rpc vs rpc-notify).\n\n// A tap must never stall the step, so these carry no id and no reply. Node's\n// IPC preserves order, which is what drains them before the result lands.\nexport interface HostNotifyMessage {\n type: \"host-notify\";\n method: string;\n payload: unknown;\n}\n\n// Handlers registered per request, like HostCallHandlers. A throw here is\n// swallowed: a failed tap must not fail the step it was reporting on.\nexport type HostNotifyHandlers = Record<string, (payload: unknown) => void>;\n\n// One console call the piece made, already flattened to a string in the child.\nexport interface PieceLogEntry {\n level: \"log\" | \"info\" | \"warn\" | \"error\" | \"debug\";\n message: string;\n at: number;\n}\n\nexport const LOG_WRITE = \"log.write\";\nexport const OUTPUT_UPDATE = \"output.update\";\n\n// A store call carries `{ key, value?, scope }`. The scope is a name the host\n// partitions on, never a prefix the child bakes into the key.\nexport const STORE_GET = \"store.get\";\nexport const STORE_PUT = \"store.put\";\nexport const STORE_DELETE = \"store.delete\";\n","// \"Nobody knows whether that write landed\", as a property an error carries.\n//\n// A step whose host call wrote something and then did not get an answer in\n// time is neither a success nor a failure, and reporting it as FAILED is a\n// claim nobody can stand behind — which is what the 10s host-call cap was\n// doing to a reactor dispatch under load (backlog item 6).\n//\n// The marker is an ENUMERABLE OWN PROPERTY rather than a class, because the\n// error is usually thrown in the forked child and reaches the coordinator as a\n// `SerializedPieceError`: a name, a message, and the error's own enumerable\n// properties. The class does not survive; the property does.\n//\n// The reactor RPC keeps only an error's name and message, so a reactor job\n// still unfinished at the step deadline is recognised by its name.\nimport { ReactorJobPendingError } from \"@powerhousedao/pieces-framework\";\n\n/** The property name, so both sides spell it once. */\nexport const INDETERMINATE_FLAG = \"indeterminate\";\n\n/** Marks an error as indeterminate, in place. */\nexport function markIndeterminate<T extends Error>(error: T): T {\n Object.defineProperty(error, INDETERMINATE_FLAG, {\n value: true,\n enumerable: true,\n writable: false,\n configurable: false,\n });\n return error;\n}\n\nconst INDETERMINATE_NAMES: ReadonlySet<string> = new Set([\n ReactorJobPendingError,\n]);\n\nfunction named(value: unknown): boolean {\n if (typeof value !== \"object\" || value === null) return false;\n const name = (value as { name?: unknown }).name;\n return typeof name === \"string\" && INDETERMINATE_NAMES.has(name);\n}\n\nfunction flagged(value: unknown): boolean {\n if (typeof value !== \"object\" || value === null) return false;\n return (value as Record<string, unknown>)[INDETERMINATE_FLAG] === true;\n}\n\n/**\n * Whether this error means \"the write may have landed\".\n *\n * Three places to look, in the order the error can reach us: the error itself\n * (thrown in the reactor process), the `properties` record of the\n * `SerializedPieceError` a `PieceWorkerError` carries (thrown in the child),\n * and the `cause` chain (a piece that wrapped it).\n */\nexport function isIndeterminateError(error: unknown): boolean {\n if (flagged(error) || named(error)) return true;\n const serialized = (\n error as { serialized?: { name?: unknown; properties?: unknown } }\n )?.serialized;\n if (flagged(serialized?.properties) || named(serialized)) return true;\n const cause = (error as { cause?: unknown })?.cause;\n return (\n cause !== undefined && cause !== error && (flagged(cause) || named(cause))\n );\n}\n","// The child's half of the call channel: how piece code reaches durable host\n// state mid-step, instead of handing everything back when the step returns.\n\n// Modelled on their engine RPC (createRpcClient): a method name, a payload, an\n// id, and failures returned as data rather than thrown across the boundary.\nimport { markIndeterminate } from \"../indeterminate.js\";\nimport { STORE_DELETE, STORE_PUT, type HostCallResponse } from \"./protocol.js\";\n\n// A host call is a local IPC round trip, so ten seconds is pathological in the\n// ordinary case. It was not in the field: a reactor dispatch under load, or a\n// store write behind a saturated PGlite, outran it and the step was reported\n// FAILED for a write that had in fact been committed (backlog item 6). The cap\n// is now the host's to set (PH_WORKFLOWS_HOST_CALL_TIMEOUT_MS, and never\n// shorter than the step's own timeoutSeconds), and a mutating call that does\n// time out is INDETERMINATE rather than failed.\nexport const DEFAULT_HOST_CALL_TIMEOUT_MS = 10_000;\n\n/**\n * The host calls that may have committed something by the time they time out.\n *\n * A read that times out is just a read that did not answer. A write is not:\n * the host may have written and simply not got the answer back in time, so\n * reporting it as a failure is a claim nobody can stand behind. Reactor writes\n * go over the reactor RPC, not a host call; their unconfirmed outcome is\n * recognised by error name instead (`../indeterminate.ts`).\n */\nexport const MUTATING_HOST_CALLS: readonly string[] = [STORE_PUT, STORE_DELETE];\n\n// Set per request from the wire; requests are serialized per worker.\nlet fromWire: number | undefined;\n// The request's kill deadline, less a margin to report a timeout before it.\nlet stopAt: number | undefined;\n\nconst MIN_DEADLINE_MARGIN_MS = 250;\nconst MAX_DEADLINE_MARGIN_MS = 2_000;\n\nfunction deadlineMargin(budgetMs: number): number {\n return Math.min(\n Math.max(Math.floor(budgetMs / 10), MIN_DEADLINE_MARGIN_MS),\n MAX_DEADLINE_MARGIN_MS,\n );\n}\n\nexport function setHostCallTimeout(\n timeoutMs: number | undefined,\n deadline?: number,\n): void {\n fromWire = timeoutMs;\n stopAt =\n deadline === undefined\n ? undefined\n : deadline - deadlineMargin(deadline - Date.now());\n}\n\nexport function hostCallTimeoutMs(): number {\n return fromWire ?? DEFAULT_HOST_CALL_TIMEOUT_MS;\n}\n\ninterface Pending {\n method: string;\n resolve: (value: unknown) => void;\n reject: (error: Error) => void;\n timer: NodeJS.Timeout;\n}\n\nconst pending = new Map<number, Pending>();\nlet nextId = 1;\nlet listening = false;\n\nexport class HostCallError extends Error {\n constructor(method: string, detail: string) {\n super(`Host call \"${method}\" failed: ${detail}`);\n this.name = \"HostCallError\";\n }\n}\n\n/** A read-ish host call that did not answer. An ordinary failure. */\nexport class HostCallTimeoutError extends Error {\n constructor(method: string, timeoutMs: number) {\n super(`Host call \"${method}\" got no answer within ${timeoutMs}ms`);\n this.name = \"HostCallTimeoutError\";\n }\n}\n\n/**\n * A WRITING host call that did not answer: the write may have landed.\n *\n * Marked indeterminate (`../indeterminate.ts`), which is what survives the\n * worker boundary — this is thrown in the forked child, where the class does\n * not cross but the error's own enumerable properties do.\n */\nexport const INDETERMINATE_ERROR_NAME = \"HostCallIndeterminateError\";\n\nexport class HostCallIndeterminateError extends Error {\n constructor(method: string, timeoutMs: number) {\n super(\n `Host call \"${method}\" got no answer within ${timeoutMs}ms; it writes, ` +\n \"so whether it was committed is unknown and the step is neither a \" +\n \"success nor a failure\",\n );\n this.name = INDETERMINATE_ERROR_NAME;\n markIndeterminate(this);\n }\n}\n\nfunction timeoutError(method: string, timeoutMs: number): Error {\n return MUTATING_HOST_CALLS.includes(method)\n ? new HostCallIndeterminateError(method, timeoutMs)\n : new HostCallTimeoutError(method, timeoutMs);\n}\n\nfunction isHostCallResponse(value: unknown): value is HostCallResponse {\n return (\n typeof value === \"object\" &&\n value !== null &&\n (value as { type?: unknown }).type === \"host-result\"\n );\n}\n\n// Registered once, on the same channel the job messages arrive on. The job\n// dispatcher ignores `host-result` because it only knows its own request types.\nfunction ensureListening(): void {\n if (listening) return;\n listening = true;\n process.on(\"message\", (message: unknown) => {\n if (!isHostCallResponse(message)) return;\n const entry = pending.get(message.id);\n if (!entry) return;\n pending.delete(message.id);\n clearTimeout(entry.timer);\n if (message.error !== undefined) {\n entry.reject(new HostCallError(entry.method, message.error));\n return;\n }\n entry.resolve(message.value);\n });\n}\n\nexport function callHost<T = unknown>(\n method: string,\n payload: unknown,\n timeoutMs: number = hostCallTimeoutMs(),\n): Promise<T> {\n if (!process.send) {\n return Promise.reject(\n new HostCallError(method, \"the worker has no channel to its host\"),\n );\n }\n // Clipped to the step deadline: a call still waiting when the worker is\n // killed would surface as a retryable worker timeout, even for a write.\n const budgetMs =\n stopAt === undefined ? timeoutMs : Math.min(timeoutMs, stopAt - Date.now());\n if (budgetMs <= 0) {\n return Promise.reject(new HostCallTimeoutError(method, 0));\n }\n ensureListening();\n const id = nextId++;\n return new Promise<T>((resolve, reject) => {\n const timer = setTimeout(() => {\n pending.delete(id);\n reject(timeoutError(method, budgetMs));\n }, budgetMs);\n pending.set(id, {\n method,\n resolve: resolve as (value: unknown) => void,\n reject,\n timer,\n });\n process.send?.({ id, type: \"host-call\", method, payload });\n });\n}\n\n// Test seam: a worker replaced between suites must not inherit pending calls.\nexport function resetHostCalls(): void {\n for (const entry of pending.values()) clearTimeout(entry.timer);\n pending.clear();\n}\n\n// The one-way half: a report with no answer to wait for. It cannot fail from\n// the piece's side, so a missing channel is dropped rather than raised.\nexport function notifyHost(method: string, payload: unknown): void {\n try {\n process.send?.({ type: \"host-notify\", method, payload });\n } catch {\n // `process.send` stays defined after the channel closes and throws. A tap\n // that threw here would be a tap that changed the step.\n }\n}\n","// `ctx.store` served by the host, one call per operation, so a value a piece\n// writes is durable the moment it writes it rather than when the step ends.\n\n// This is the semantic Activepieces pieces are written against — theirs is an\n// HTTP call per get/put/delete — so a loop that checkpoints its cursor resumes.\nimport type { KeyValueStore } from \"./action.js\";\nimport type { StoreScopeName } from \"./store-scope.js\";\nimport { STORE_DELETE, STORE_GET, STORE_PUT } from \"../worker/protocol.js\";\nimport { callHost } from \"../worker/host-call.js\";\nimport { jsonSafe } from \"../worker/json-safe.js\";\n\n// The host writes JSON, so a value is flattened here rather than at the point\n// it lands. A piece that stores a Date reads back a string either way, whether\n// or not a durable store is configured — and whatever carries the message.\nexport class RemoteKeyValueStore implements KeyValueStore {\n async put(\n key: string,\n value: unknown,\n scope?: StoreScopeName,\n timeoutMs?: number,\n ): Promise<unknown> {\n const stored = jsonSafe(value);\n await callHost(STORE_PUT, { key, value: stored, scope }, timeoutMs);\n return stored;\n }\n\n get(key: string, scope?: StoreScopeName): Promise<unknown> {\n return callHost(STORE_GET, { key, scope });\n }\n\n async delete(key: string, scope?: StoreScopeName): Promise<void> {\n await callHost(STORE_DELETE, { key, scope });\n }\n}\n","// ctx.output.update: the piece reporting progress before it returns. A long\n// step is otherwise opaque until the moment it finishes.\nimport { notifyHost } from \"../worker/host-call.js\";\nimport { jsonSafe } from \"../worker/json-safe.js\";\nimport { OUTPUT_UPDATE } from \"../worker/protocol.js\";\n\nexport interface PartialOutput {\n update(output: unknown): Promise<void>;\n}\n\n// Resolves immediately: a tap the step waits on is a tap that can stall it,\n// which is the one thing plan/08 §7.8 rules out.\n\n// A notification carries no request id, and the worker is reused. A piece that\n// keeps `ctx` and updates from a timer would otherwise report progress against\n// whichever step is running by then, so the tap is closed when its step ends.\nexport class RemoteOutput implements PartialOutput {\n private open = true;\n\n update(output: unknown): Promise<void> {\n if (this.open) notifyHost(OUTPUT_UPDATE, jsonSafe(output));\n return Promise.resolve();\n }\n\n close(): void {\n this.open = false;\n }\n}\n","// Piece console output, forwarded to the host while the step runs. The child\n// is forked with its stdio discarded, so without this a piece's logs vanish.\nimport { format } from \"node:util\";\nimport { notifyHost } from \"./host-call.js\";\nimport { LOG_WRITE, type PieceLogEntry } from \"./protocol.js\";\n\n// A runaway piece can log in a loop; the channel is shared with the step's own\n// result, so both the size of an entry and the number of them are capped.\n\n// Without the count, a loop enqueues IPC messages faster than the host drains\n// them and the result waits behind the backlog until the step times out.\nconst MAX_MESSAGE_LENGTH = 8_192;\nconst MAX_ENTRIES_PER_REQUEST = 1_000;\n\nconst LEVELS = [\"log\", \"info\", \"warn\", \"error\", \"debug\"] as const;\n\ntype Level = (typeof LEVELS)[number];\n\n// Installs the patch for one request and returns its undo. Logs written after\n// the step returned belong to no step, which is why the scope is this narrow.\nexport function captureConsole(): () => void {\n const original = new Map<Level, (...args: unknown[]) => void>();\n let sent = 0;\n\n for (const level of LEVELS) {\n const previous = console[level] as (...args: unknown[]) => void;\n original.set(level, previous);\n console[level] = (...args: unknown[]) => {\n if (sent > MAX_ENTRIES_PER_REQUEST) return;\n sent += 1;\n // The last one says why the rest are missing, so a truncated log does\n // not read as a step that fell silent.\n const message =\n sent > MAX_ENTRIES_PER_REQUEST\n ? `[log truncated after ${MAX_ENTRIES_PER_REQUEST} entries]`\n : format(...args).slice(0, MAX_MESSAGE_LENGTH);\n notifyHost(LOG_WRITE, {\n level,\n message,\n at: Date.now(),\n } satisfies PieceLogEntry);\n };\n }\n\n return () => {\n for (const [level, previous] of original) {\n console[level] = previous as typeof console.log;\n }\n };\n}\n","// The child's seam for `ctx.reactor`. The worker entry outside this layer\n// installs the reactor RPC client; this layer imports no reactor code.\nimport type {\n ReactorClientFor,\n RequireReactor,\n} from \"@powerhousedao/pieces-framework\";\nimport type { ReactorRequestBinding } from \"./protocol.js\";\n\n// The piece's ctx.reactor, typed by the block's declaration.\nexport type WorkerReactorSession = {\n [R in RequireReactor]: {\n readonly requireReactor: R;\n readonly client: ReactorClientFor<R>;\n // Run when the request settles; later calls throw ReactorRequestClosedError.\n close(): void;\n };\n}[RequireReactor];\n\nexport type WorkerReactorProvider = (\n binding: ReactorRequestBinding,\n requireReactor: RequireReactor,\n) => Promise<WorkerReactorSession>;\n\nlet provider: WorkerReactorProvider | undefined;\n\nexport function installReactorProvider(next: WorkerReactorProvider): void {\n provider = next;\n}\n\n// A session only when the host serves the request and the block declares access.\nexport function openWorkerReactor(\n binding: ReactorRequestBinding | undefined,\n declared: unknown,\n): Promise<WorkerReactorSession | undefined> {\n if (!binding || !provider) return Promise.resolve(undefined);\n if (declared !== \"read\" && declared !== \"write\") {\n return Promise.resolve(undefined);\n }\n return provider(binding, declared);\n}\n","(function (root) {\n 'use strict';\n // A list of regular expressions that match arbitrary IPv4 addresses,\n // for which a number of weird notations exist.\n // Note that an address like 0010.0xa5.1.1 is considered legal.\n const ipv4Part = '(0?\\\\d+|0x[a-f0-9]+)';\n const ipv4Regexes = {\n fourOctet: new RegExp(`^${ipv4Part}\\\\.${ipv4Part}\\\\.${ipv4Part}\\\\.${ipv4Part}$`, 'i'),\n threeOctet: new RegExp(`^${ipv4Part}\\\\.${ipv4Part}\\\\.${ipv4Part}$`, 'i'),\n twoOctet: new RegExp(`^${ipv4Part}\\\\.${ipv4Part}$`, 'i'),\n longValue: new RegExp(`^${ipv4Part}$`, 'i')\n };\n\n // Regular Expression for checking Octal numbers\n const octalRegex = new RegExp(`^0[0-7]+$`, 'i');\n const hexRegex = new RegExp(`^0x[a-f0-9]+$`, 'i');\n\n const zoneIndex = '%[0-9a-z]{1,}';\n\n // IPv6-matching regular expressions.\n // For IPv6, the task is simpler: it is enough to match the colon-delimited\n // hexadecimal IPv6 and a transitional variant with dotted-decimal IPv4 at\n // the end.\n const ipv6Part = '(?:[0-9a-f]+::?)+';\n const ipv6Regexes = {\n zoneIndex: new RegExp(zoneIndex, 'i'),\n 'native': new RegExp(`^(::)?(${ipv6Part})?([0-9a-f]+)?(::)?(${zoneIndex})?$`, 'i'),\n deprecatedTransitional: new RegExp(`^(?:::)(${ipv4Part}\\\\.${ipv4Part}\\\\.${ipv4Part}\\\\.${ipv4Part}(${zoneIndex})?)$`, 'i'),\n transitional: new RegExp(`^((?:${ipv6Part})|(?:::)(?:${ipv6Part})?)${ipv4Part}\\\\.${ipv4Part}\\\\.${ipv4Part}\\\\.${ipv4Part}(${zoneIndex})?$`, 'i')\n };\n\n // Expand :: in an IPv6 address or address part consisting of `parts` groups.\n function expandIPv6 (string, parts) {\n // More than one '::' means invalid adddress\n if (string.indexOf('::') !== string.lastIndexOf('::')) {\n return null;\n }\n\n let colonCount = 0;\n let lastColon = -1;\n let zoneId = (string.match(ipv6Regexes.zoneIndex) || [])[0];\n let replacement, replacementCount;\n\n // Remove zone index and save it for later\n if (zoneId) {\n zoneId = zoneId.substring(1);\n string = string.replace(/%.+$/, '');\n }\n\n // How many parts do we already have?\n while ((lastColon = string.indexOf(':', lastColon + 1)) >= 0) {\n colonCount++;\n }\n\n // 0::0 is two parts more than ::\n if (string.substr(0, 2) === '::') {\n colonCount--;\n }\n\n if (string.substr(-2, 2) === '::') {\n colonCount--;\n }\n\n // The following loop would hang if colonCount > parts\n if (colonCount > parts) {\n return null;\n }\n\n // replacement = ':' + '0:' * (parts - colonCount)\n replacementCount = parts - colonCount;\n replacement = ':';\n while (replacementCount--) {\n replacement += '0:';\n }\n\n // Insert the missing zeroes\n string = string.replace('::', replacement);\n\n // Trim any garbage which may be hanging around if :: was at the edge in\n // the source strin\n if (string[0] === ':') {\n string = string.slice(1);\n }\n\n if (string[string.length - 1] === ':') {\n string = string.slice(0, -1);\n }\n\n parts = (function () {\n const ref = string.split(':');\n const results = [];\n\n for (let i = 0; i < ref.length; i++) {\n results.push(parseInt(ref[i], 16));\n }\n\n return results;\n })();\n\n return {\n parts: parts,\n zoneId: zoneId\n };\n }\n\n // A generic CIDR (Classless Inter-Domain Routing) RFC1518 range matcher.\n function matchCIDR (first, second, partSize, cidrBits) {\n if (first.length !== second.length) {\n throw new Error('ipaddr: cannot match CIDR for objects with different lengths');\n }\n\n let part = 0;\n let shift;\n\n while (cidrBits > 0) {\n shift = partSize - cidrBits;\n if (shift < 0) {\n shift = 0;\n }\n\n if (first[part] >> shift !== second[part] >> shift) {\n return false;\n }\n\n cidrBits -= partSize;\n part += 1;\n }\n\n return true;\n }\n\n function parseIntAuto (string) {\n // Hexadedimal base 16 (0x#)\n if (hexRegex.test(string)) {\n return parseInt(string, 16);\n }\n // While octal representation is discouraged by ECMAScript 3\n // and forbidden by ECMAScript 5, we silently allow it to\n // work only if the rest of the string has numbers less than 8.\n if (string[0] === '0' && !isNaN(parseInt(string[1], 10))) {\n if (octalRegex.test(string)) {\n return parseInt(string, 8);\n }\n throw new Error(`ipaddr: cannot parse ${string} as octal`);\n }\n // Always include the base 10 radix!\n return parseInt(string, 10);\n }\n\n function padPart (part, length) {\n while (part.length < length) {\n part = `0${part}`;\n }\n\n return part;\n }\n\n const ipaddr = {};\n\n // An IPv4 address (RFC791).\n ipaddr.IPv4 = (function () {\n // Constructs a new IPv4 address from an array of four octets\n // in network order (MSB first)\n // Verifies the input.\n function IPv4 (octets) {\n if (octets.length !== 4) {\n throw new Error('ipaddr: ipv4 octet count should be 4');\n }\n\n let i, octet;\n\n for (i = 0; i < octets.length; i++) {\n octet = octets[i];\n if (!((0 <= octet && octet <= 255))) {\n throw new Error('ipaddr: ipv4 octet should fit in 8 bits');\n }\n }\n\n this.octets = octets;\n }\n\n // Special IPv4 address ranges.\n // See also https://en.wikipedia.org/wiki/Reserved_IP_addresses\n IPv4.prototype.SpecialRanges = {\n unspecified: [[new IPv4([0, 0, 0, 0]), 8]],\n broadcast: [[new IPv4([255, 255, 255, 255]), 32]],\n // RFC3171\n multicast: [[new IPv4([224, 0, 0, 0]), 4]],\n // RFC3927\n linkLocal: [[new IPv4([169, 254, 0, 0]), 16]],\n // RFC5735\n loopback: [[new IPv4([127, 0, 0, 0]), 8]],\n // RFC6598\n carrierGradeNat: [[new IPv4([100, 64, 0, 0]), 10]],\n // RFC1918\n 'private': [\n [new IPv4([10, 0, 0, 0]), 8],\n [new IPv4([172, 16, 0, 0]), 12],\n [new IPv4([192, 168, 0, 0]), 16]\n ],\n // Reserved and testing-only ranges; RFCs 5735, 5737, 2544, 1700\n reserved: [\n [new IPv4([192, 0, 0, 0]), 24],\n [new IPv4([192, 0, 2, 0]), 24],\n [new IPv4([192, 88, 99, 0]), 24],\n [new IPv4([198, 18, 0, 0]), 15],\n [new IPv4([198, 51, 100, 0]), 24],\n [new IPv4([203, 0, 113, 0]), 24],\n [new IPv4([240, 0, 0, 0]), 4]\n ],\n // RFC7534, RFC7535\n as112: [\n [new IPv4([192, 175, 48, 0]), 24],\n [new IPv4([192, 31, 196, 0]), 24],\n ],\n // RFC7450\n amt: [\n [new IPv4([192, 52, 193, 0]), 24],\n ],\n };\n\n // The 'kind' method exists on both IPv4 and IPv6 classes.\n IPv4.prototype.kind = function () {\n return 'ipv4';\n };\n\n // Checks if this address matches other one within given CIDR range.\n IPv4.prototype.match = function (other, cidrRange) {\n let ref;\n if (cidrRange === undefined) {\n ref = other;\n other = ref[0];\n cidrRange = ref[1];\n }\n\n if (other.kind() !== 'ipv4') {\n throw new Error('ipaddr: cannot match ipv4 address with non-ipv4 one');\n }\n\n return matchCIDR(this.octets, other.octets, 8, cidrRange);\n };\n\n // returns a number of leading ones in IPv4 address, making sure that\n // the rest is a solid sequence of 0's (valid netmask)\n // returns either the CIDR length or null if mask is not valid\n IPv4.prototype.prefixLengthFromSubnetMask = function () {\n let cidr = 0;\n // non-zero encountered stop scanning for zeroes\n let stop = false;\n // number of zeroes in octet\n const zerotable = {\n 0: 8,\n 128: 7,\n 192: 6,\n 224: 5,\n 240: 4,\n 248: 3,\n 252: 2,\n 254: 1,\n 255: 0\n };\n let i, octet, zeros;\n\n for (i = 3; i >= 0; i -= 1) {\n octet = this.octets[i];\n if (octet in zerotable) {\n zeros = zerotable[octet];\n if (stop && zeros !== 0) {\n return null;\n }\n\n if (zeros !== 8) {\n stop = true;\n }\n\n cidr += zeros;\n } else {\n return null;\n }\n }\n\n return 32 - cidr;\n };\n\n // Checks if the address corresponds to one of the special ranges.\n IPv4.prototype.range = function () {\n return ipaddr.subnetMatch(this, this.SpecialRanges);\n };\n\n // Returns an array of byte-sized values in network order (MSB first)\n IPv4.prototype.toByteArray = function () {\n return this.octets.slice(0);\n };\n\n // Converts this IPv4 address to an IPv4-mapped IPv6 address.\n IPv4.prototype.toIPv4MappedAddress = function () {\n return ipaddr.IPv6.parse(`::ffff:${this.toString()}`);\n };\n\n // Symmetrical method strictly for aligning with the IPv6 methods.\n IPv4.prototype.toNormalizedString = function () {\n return this.toString();\n };\n\n // Returns the address in convenient, decimal-dotted format.\n IPv4.prototype.toString = function () {\n return this.octets.join('.');\n };\n\n return IPv4;\n })();\n\n // A utility function to return broadcast address given the IPv4 interface and prefix length in CIDR notation\n ipaddr.IPv4.broadcastAddressFromCIDR = function (string) {\n\n try {\n const cidr = this.parseCIDR(string);\n const ipInterfaceOctets = cidr[0].toByteArray();\n const subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray();\n const octets = [];\n let i = 0;\n while (i < 4) {\n // Broadcast address is bitwise OR between ip interface and inverted mask\n octets.push(parseInt(ipInterfaceOctets[i], 10) | parseInt(subnetMaskOctets[i], 10) ^ 255);\n i++;\n }\n\n return new this(octets);\n } catch (e) {\n throw new Error('ipaddr: the address does not have IPv4 CIDR format');\n }\n };\n\n // Checks if a given string is formatted like IPv4 address.\n ipaddr.IPv4.isIPv4 = function (string) {\n return this.parser(string) !== null;\n };\n\n // Checks if a given string is a valid IPv4 address.\n ipaddr.IPv4.isValid = function (string) {\n try {\n new this(this.parser(string));\n return true;\n } catch (e) {\n return false;\n }\n };\n\n // Checks if a given string is a valid IPv4 address in CIDR notation.\n ipaddr.IPv4.isValidCIDR = function (string) {\n try {\n this.parseCIDR(string);\n return true;\n } catch (e) {\n return false;\n }\n };\n\n // Checks if a given string is a full four-part IPv4 Address.\n ipaddr.IPv4.isValidFourPartDecimal = function (string) {\n if (ipaddr.IPv4.isValid(string) && string.match(/^(0|[1-9]\\d*)(\\.(0|[1-9]\\d*)){3}$/)) {\n return true;\n } else {\n return false;\n }\n };\n\n // Checks if a given string is a full four-part IPv4 Address with CIDR prefix.\n ipaddr.IPv4.isValidCIDRFourPartDecimal = function (string) {\n const match = string.match(/^(.+)\\/(\\d+)$/);\n\n if (!ipaddr.IPv4.isValidCIDR(string) || !match) {\n return false;\n }\n\n return ipaddr.IPv4.isValidFourPartDecimal(match[1]);\n };\n\n // A utility function to return network address given the IPv4 interface and prefix length in CIDR notation\n ipaddr.IPv4.networkAddressFromCIDR = function (string) {\n let cidr, i, ipInterfaceOctets, octets, subnetMaskOctets;\n\n try {\n cidr = this.parseCIDR(string);\n ipInterfaceOctets = cidr[0].toByteArray();\n subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray();\n octets = [];\n i = 0;\n while (i < 4) {\n // Network address is bitwise AND between ip interface and mask\n octets.push(parseInt(ipInterfaceOctets[i], 10) & parseInt(subnetMaskOctets[i], 10));\n i++;\n }\n\n return new this(octets);\n } catch (e) {\n throw new Error('ipaddr: the address does not have IPv4 CIDR format');\n }\n };\n\n // Tries to parse and validate a string with IPv4 address.\n // Throws an error if it fails.\n ipaddr.IPv4.parse = function (string) {\n const parts = this.parser(string);\n\n if (parts === null) {\n throw new Error('ipaddr: string is not formatted like an IPv4 Address');\n }\n\n return new this(parts);\n };\n\n // Parses the string as an IPv4 Address with CIDR Notation.\n ipaddr.IPv4.parseCIDR = function (string) {\n let match;\n\n if ((match = string.match(/^(.+)\\/(\\d+)$/))) {\n const maskLength = parseInt(match[2]);\n if (maskLength >= 0 && maskLength <= 32) {\n const parsed = [this.parse(match[1]), maskLength];\n Object.defineProperty(parsed, 'toString', {\n value: function () {\n return this.join('/');\n }\n });\n return parsed;\n }\n }\n\n throw new Error('ipaddr: string is not formatted like an IPv4 CIDR range');\n };\n\n // Classful variants (like a.b, where a is an octet, and b is a 24-bit\n // value representing last three octets; this corresponds to a class C\n // address) are omitted due to classless nature of modern Internet.\n ipaddr.IPv4.parser = function (string) {\n let match, part, value;\n\n // parseInt recognizes all that octal & hexadecimal weirdness for us\n if ((match = string.match(ipv4Regexes.fourOctet))) {\n return (function () {\n const ref = match.slice(1, 6);\n const results = [];\n\n for (let i = 0; i < ref.length; i++) {\n part = ref[i];\n results.push(parseIntAuto(part));\n }\n\n return results;\n })();\n } else if ((match = string.match(ipv4Regexes.longValue))) {\n value = parseIntAuto(match[1]);\n if (value > 0xffffffff || value < 0) {\n throw new Error('ipaddr: address outside defined range');\n }\n\n return ((function () {\n const results = [];\n let shift;\n\n for (shift = 0; shift <= 24; shift += 8) {\n results.push((value >> shift) & 0xff);\n }\n\n return results;\n })()).reverse();\n } else if ((match = string.match(ipv4Regexes.twoOctet))) {\n return (function () {\n const ref = match.slice(1, 4);\n const results = [];\n\n value = parseIntAuto(ref[1]);\n if (value > 0xffffff || value < 0) {\n throw new Error('ipaddr: address outside defined range');\n }\n\n results.push(parseIntAuto(ref[0]));\n results.push((value >> 16) & 0xff);\n results.push((value >> 8) & 0xff);\n results.push( value & 0xff);\n\n return results;\n })();\n } else if ((match = string.match(ipv4Regexes.threeOctet))) {\n return (function () {\n const ref = match.slice(1, 5);\n const results = [];\n\n value = parseIntAuto(ref[2]);\n if (value > 0xffff || value < 0) {\n throw new Error('ipaddr: address outside defined range');\n }\n\n results.push(parseIntAuto(ref[0]));\n results.push(parseIntAuto(ref[1]));\n results.push((value >> 8) & 0xff);\n results.push( value & 0xff);\n\n return results;\n })();\n } else {\n return null;\n }\n };\n\n // A utility function to return subnet mask in IPv4 format given the prefix length\n ipaddr.IPv4.subnetMaskFromPrefixLength = function (prefix) {\n prefix = parseInt(prefix);\n if (prefix < 0 || prefix > 32) {\n throw new Error('ipaddr: invalid IPv4 prefix length');\n }\n\n const octets = [0, 0, 0, 0];\n let j = 0;\n const filledOctetCount = Math.floor(prefix / 8);\n\n while (j < filledOctetCount) {\n octets[j] = 255;\n j++;\n }\n\n if (filledOctetCount < 4) {\n octets[filledOctetCount] = Math.pow(2, prefix % 8) - 1 << 8 - (prefix % 8);\n }\n\n return new this(octets);\n };\n\n // An IPv6 address (RFC2460)\n ipaddr.IPv6 = (function () {\n // Constructs an IPv6 address from an array of eight 16 - bit parts\n // or sixteen 8 - bit parts in network order(MSB first).\n // Throws an error if the input is invalid.\n function IPv6 (parts, zoneId) {\n let i, part;\n\n if (parts.length === 16) {\n this.parts = [];\n for (i = 0; i <= 14; i += 2) {\n this.parts.push((parts[i] << 8) | parts[i + 1]);\n }\n } else if (parts.length === 8) {\n this.parts = parts;\n } else {\n throw new Error('ipaddr: ipv6 part count should be 8 or 16');\n }\n\n for (i = 0; i < this.parts.length; i++) {\n part = this.parts[i];\n if (!((0 <= part && part <= 0xffff))) {\n throw new Error('ipaddr: ipv6 part should fit in 16 bits');\n }\n }\n\n if (zoneId) {\n this.zoneId = zoneId;\n }\n }\n\n // Special IPv6 ranges\n IPv6.prototype.SpecialRanges = {\n // RFC4291, here and after\n unspecified: [new IPv6([0, 0, 0, 0, 0, 0, 0, 0]), 128],\n linkLocal: [new IPv6([0xfe80, 0, 0, 0, 0, 0, 0, 0]), 10],\n multicast: [new IPv6([0xff00, 0, 0, 0, 0, 0, 0, 0]), 8],\n loopback: [new IPv6([0, 0, 0, 0, 0, 0, 0, 1]), 128],\n uniqueLocal: [new IPv6([0xfc00, 0, 0, 0, 0, 0, 0, 0]), 7],\n ipv4Mapped: [new IPv6([0, 0, 0, 0, 0, 0xffff, 0, 0]), 96],\n // RFC6666\n discard: [new IPv6([0x100, 0, 0, 0, 0, 0, 0, 0]), 64],\n // RFC6145\n rfc6145: [new IPv6([0, 0, 0, 0, 0xffff, 0, 0, 0]), 96],\n // RFC6052\n rfc6052: [new IPv6([0x64, 0xff9b, 0, 0, 0, 0, 0, 0]), 96],\n // RFC3056\n '6to4': [new IPv6([0x2002, 0, 0, 0, 0, 0, 0, 0]), 16],\n // RFC6052, RFC6146\n teredo: [new IPv6([0x2001, 0, 0, 0, 0, 0, 0, 0]), 32],\n // RFC5180\n benchmarking: [new IPv6([0x2001, 0x2, 0, 0, 0, 0, 0, 0]), 48],\n // RFC7450\n amt: [new IPv6([0x2001, 0x3, 0, 0, 0, 0, 0, 0]), 32],\n as112v6: [\n [new IPv6([0x2001, 0x4, 0x112, 0, 0, 0, 0, 0]), 48],\n [new IPv6([0x2620, 0x4f, 0x8000, 0, 0, 0, 0, 0]), 48],\n ],\n deprecated: [new IPv6([0x2001, 0x10, 0, 0, 0, 0, 0, 0]), 28],\n orchid2: [new IPv6([0x2001, 0x20, 0, 0, 0, 0, 0, 0]), 28],\n droneRemoteIdProtocolEntityTags: [new IPv6([0x2001, 0x30, 0, 0, 0, 0, 0, 0]), 28],\n reserved: [\n // RFC3849\n [new IPv6([0x2001, 0, 0, 0, 0, 0, 0, 0]), 23],\n // RFC2928\n [new IPv6([0x2001, 0xdb8, 0, 0, 0, 0, 0, 0]), 32],\n ],\n };\n\n // Checks if this address is an IPv4-mapped IPv6 address.\n IPv6.prototype.isIPv4MappedAddress = function () {\n return this.range() === 'ipv4Mapped';\n };\n\n // The 'kind' method exists on both IPv4 and IPv6 classes.\n IPv6.prototype.kind = function () {\n return 'ipv6';\n };\n\n // Checks if this address matches other one within given CIDR range.\n IPv6.prototype.match = function (other, cidrRange) {\n let ref;\n\n if (cidrRange === undefined) {\n ref = other;\n other = ref[0];\n cidrRange = ref[1];\n }\n\n if (other.kind() !== 'ipv6') {\n throw new Error('ipaddr: cannot match ipv6 address with non-ipv6 one');\n }\n\n return matchCIDR(this.parts, other.parts, 16, cidrRange);\n };\n\n // returns a number of leading ones in IPv6 address, making sure that\n // the rest is a solid sequence of 0's (valid netmask)\n // returns either the CIDR length or null if mask is not valid\n IPv6.prototype.prefixLengthFromSubnetMask = function () {\n let cidr = 0;\n // non-zero encountered stop scanning for zeroes\n let stop = false;\n // number of zeroes in octet\n const zerotable = {\n 0: 16,\n 32768: 15,\n 49152: 14,\n 57344: 13,\n 61440: 12,\n 63488: 11,\n 64512: 10,\n 65024: 9,\n 65280: 8,\n 65408: 7,\n 65472: 6,\n 65504: 5,\n 65520: 4,\n 65528: 3,\n 65532: 2,\n 65534: 1,\n 65535: 0\n };\n let part, zeros;\n\n for (let i = 7; i >= 0; i -= 1) {\n part = this.parts[i];\n if (part in zerotable) {\n zeros = zerotable[part];\n if (stop && zeros !== 0) {\n return null;\n }\n\n if (zeros !== 16) {\n stop = true;\n }\n\n cidr += zeros;\n } else {\n return null;\n }\n }\n\n return 128 - cidr;\n };\n\n\n // Checks if the address corresponds to one of the special ranges.\n IPv6.prototype.range = function () {\n return ipaddr.subnetMatch(this, this.SpecialRanges);\n };\n\n // Returns an array of byte-sized values in network order (MSB first)\n IPv6.prototype.toByteArray = function () {\n let part;\n const bytes = [];\n const ref = this.parts;\n for (let i = 0; i < ref.length; i++) {\n part = ref[i];\n bytes.push(part >> 8);\n bytes.push(part & 0xff);\n }\n\n return bytes;\n };\n\n // Returns the address in expanded format with all zeroes included, like\n // 2001:0db8:0008:0066:0000:0000:0000:0001\n IPv6.prototype.toFixedLengthString = function () {\n const addr = ((function () {\n const results = [];\n for (let i = 0; i < this.parts.length; i++) {\n results.push(padPart(this.parts[i].toString(16), 4));\n }\n\n return results;\n }).call(this)).join(':');\n\n let suffix = '';\n\n if (this.zoneId) {\n suffix = `%${this.zoneId}`;\n }\n\n return addr + suffix;\n };\n\n // Converts this address to IPv4 address if it is an IPv4-mapped IPv6 address.\n // Throws an error otherwise.\n IPv6.prototype.toIPv4Address = function () {\n if (!this.isIPv4MappedAddress()) {\n throw new Error('ipaddr: trying to convert a generic ipv6 address to ipv4');\n }\n\n const ref = this.parts.slice(-2);\n const high = ref[0];\n const low = ref[1];\n\n return new ipaddr.IPv4([high >> 8, high & 0xff, low >> 8, low & 0xff]);\n };\n\n // Returns the address in expanded format with all zeroes included, like\n // 2001:db8:8:66:0:0:0:1\n //\n // Deprecated: use toFixedLengthString() instead.\n IPv6.prototype.toNormalizedString = function () {\n const addr = ((function () {\n const results = [];\n\n for (let i = 0; i < this.parts.length; i++) {\n results.push(this.parts[i].toString(16));\n }\n\n return results;\n }).call(this)).join(':');\n\n let suffix = '';\n\n if (this.zoneId) {\n suffix = `%${this.zoneId}`;\n }\n\n return addr + suffix;\n };\n\n // Returns the address in compact, human-readable format like\n // 2001:db8:8:66::1\n // in line with RFC 5952 (see https://tools.ietf.org/html/rfc5952#section-4)\n IPv6.prototype.toRFC5952String = function () {\n const regex = /((^|:)(0(:|$)){2,})/g;\n const string = this.toNormalizedString();\n let bestMatchIndex = 0;\n let bestMatchLength = -1;\n let match;\n\n while ((match = regex.exec(string))) {\n if (match[0].length > bestMatchLength) {\n bestMatchIndex = match.index;\n bestMatchLength = match[0].length;\n }\n }\n\n if (bestMatchLength < 0) {\n return string;\n }\n\n return `${string.substring(0, bestMatchIndex)}::${string.substring(bestMatchIndex + bestMatchLength)}`;\n };\n\n // Returns the address in compact, human-readable format like\n // 2001:db8:8:66::1\n // Calls toRFC5952String under the hood.\n IPv6.prototype.toString = function () {\n return this.toRFC5952String();\n };\n\n return IPv6;\n\n })();\n\n // A utility function to return broadcast address given the IPv6 interface and prefix length in CIDR notation\n ipaddr.IPv6.broadcastAddressFromCIDR = function (string) {\n try {\n const cidr = this.parseCIDR(string);\n const ipInterfaceOctets = cidr[0].toByteArray();\n const subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray();\n const octets = [];\n let i = 0;\n while (i < 16) {\n // Broadcast address is bitwise OR between ip interface and inverted mask\n octets.push(parseInt(ipInterfaceOctets[i], 10) | parseInt(subnetMaskOctets[i], 10) ^ 255);\n i++;\n }\n\n return new this(octets);\n } catch (e) {\n throw new Error(`ipaddr: the address does not have IPv6 CIDR format (${e})`);\n }\n };\n\n // Checks if a given string is formatted like IPv6 address.\n ipaddr.IPv6.isIPv6 = function (string) {\n return this.parser(string) !== null;\n };\n\n // Checks to see if string is a valid IPv6 Address\n ipaddr.IPv6.isValid = function (string) {\n\n // Since IPv6.isValid is always called first, this shortcut\n // provides a substantial performance gain.\n if (typeof string === 'string' && string.indexOf(':') === -1) {\n return false;\n }\n\n try {\n const addr = this.parser(string);\n new this(addr.parts, addr.zoneId);\n return true;\n } catch (e) {\n return false;\n }\n };\n\n // Checks if a given string is a valid IPv6 address in CIDR notation.\n ipaddr.IPv6.isValidCIDR = function (string) {\n\n // See note in IPv6.isValid\n if (typeof string === 'string' && string.indexOf(':') === -1) {\n return false;\n }\n\n try {\n this.parseCIDR(string);\n return true;\n } catch (e) {\n return false;\n }\n };\n\n // A utility function to return network address given the IPv6 interface and prefix length in CIDR notation\n ipaddr.IPv6.networkAddressFromCIDR = function (string) {\n let cidr, i, ipInterfaceOctets, octets, subnetMaskOctets;\n\n try {\n cidr = this.parseCIDR(string);\n ipInterfaceOctets = cidr[0].toByteArray();\n subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray();\n octets = [];\n i = 0;\n while (i < 16) {\n // Network address is bitwise AND between ip interface and mask\n octets.push(parseInt(ipInterfaceOctets[i], 10) & parseInt(subnetMaskOctets[i], 10));\n i++;\n }\n\n return new this(octets);\n } catch (e) {\n throw new Error(`ipaddr: the address does not have IPv6 CIDR format (${e})`);\n }\n };\n\n // Tries to parse and validate a string with IPv6 address.\n // Throws an error if it fails.\n ipaddr.IPv6.parse = function (string) {\n const addr = this.parser(string);\n\n if (addr.parts === null) {\n throw new Error('ipaddr: string is not formatted like an IPv6 Address');\n }\n\n return new this(addr.parts, addr.zoneId);\n };\n\n ipaddr.IPv6.parseCIDR = function (string) {\n let maskLength, match, parsed;\n\n if ((match = string.match(/^(.+)\\/(\\d+)$/))) {\n maskLength = parseInt(match[2]);\n if (maskLength >= 0 && maskLength <= 128) {\n parsed = [this.parse(match[1]), maskLength];\n Object.defineProperty(parsed, 'toString', {\n value: function () {\n return this.join('/');\n }\n });\n return parsed;\n }\n }\n\n throw new Error('ipaddr: string is not formatted like an IPv6 CIDR range');\n };\n\n // Parse an IPv6 address.\n ipaddr.IPv6.parser = function (string) {\n let addr, i, match, octet, octets, zoneId;\n\n if ((match = string.match(ipv6Regexes.deprecatedTransitional))) {\n return this.parser(`::ffff:${match[1]}`);\n }\n if (ipv6Regexes.native.test(string)) {\n return expandIPv6(string, 8);\n }\n if ((match = string.match(ipv6Regexes.transitional))) {\n zoneId = match[6] || '';\n addr = match[1]\n if (!match[1].endsWith('::')) {\n addr = addr.slice(0, -1)\n }\n addr = expandIPv6(addr + zoneId, 6);\n if (addr.parts) {\n octets = [\n parseInt(match[2]),\n parseInt(match[3]),\n parseInt(match[4]),\n parseInt(match[5])\n ];\n for (i = 0; i < octets.length; i++) {\n octet = octets[i];\n if (!((0 <= octet && octet <= 255))) {\n return null;\n }\n }\n\n addr.parts.push(octets[0] << 8 | octets[1]);\n addr.parts.push(octets[2] << 8 | octets[3]);\n return {\n parts: addr.parts,\n zoneId: addr.zoneId\n };\n }\n }\n\n return null;\n };\n\n // A utility function to return subnet mask in IPv6 format given the prefix length\n ipaddr.IPv6.subnetMaskFromPrefixLength = function (prefix) {\n prefix = parseInt(prefix);\n if (prefix < 0 || prefix > 128) {\n throw new Error('ipaddr: invalid IPv6 prefix length');\n }\n\n const octets = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];\n let j = 0;\n const filledOctetCount = Math.floor(prefix / 8);\n\n while (j < filledOctetCount) {\n octets[j] = 255;\n j++;\n }\n\n if (filledOctetCount < 16) {\n octets[filledOctetCount] = Math.pow(2, prefix % 8) - 1 << 8 - (prefix % 8);\n }\n\n return new this(octets);\n };\n\n // Try to parse an array in network order (MSB first) for IPv4 and IPv6\n ipaddr.fromByteArray = function (bytes) {\n const length = bytes.length;\n\n if (length === 4) {\n return new ipaddr.IPv4(bytes);\n } else if (length === 16) {\n return new ipaddr.IPv6(bytes);\n } else {\n throw new Error('ipaddr: the binary input is neither an IPv6 nor IPv4 address');\n }\n };\n\n // Checks if the address is valid IP address\n ipaddr.isValid = function (string) {\n return ipaddr.IPv6.isValid(string) || ipaddr.IPv4.isValid(string);\n };\n\n // Checks if the address is valid IP address in CIDR notation\n ipaddr.isValidCIDR = function (string) {\n return ipaddr.IPv6.isValidCIDR(string) || ipaddr.IPv4.isValidCIDR(string);\n };\n\n\n // Attempts to parse an IP Address, first through IPv6 then IPv4.\n // Throws an error if it could not be parsed.\n ipaddr.parse = function (string) {\n if (ipaddr.IPv6.isValid(string)) {\n return ipaddr.IPv6.parse(string);\n } else if (ipaddr.IPv4.isValid(string)) {\n return ipaddr.IPv4.parse(string);\n } else {\n throw new Error('ipaddr: the address has neither IPv6 nor IPv4 format');\n }\n };\n\n // Attempt to parse CIDR notation, first through IPv6 then IPv4.\n // Throws an error if it could not be parsed.\n ipaddr.parseCIDR = function (string) {\n try {\n return ipaddr.IPv6.parseCIDR(string);\n } catch (e) {\n try {\n return ipaddr.IPv4.parseCIDR(string);\n } catch (e2) {\n throw new Error('ipaddr: the address has neither IPv6 nor IPv4 CIDR format');\n }\n }\n };\n\n // Parse an address and return plain IPv4 address if it is an IPv4-mapped address\n ipaddr.process = function (string) {\n const addr = this.parse(string);\n\n if (addr.kind() === 'ipv6' && addr.isIPv4MappedAddress()) {\n return addr.toIPv4Address();\n } else {\n return addr;\n }\n };\n\n // An utility function to ease named range matching. See examples below.\n // rangeList can contain both IPv4 and IPv6 subnet entries and will not throw errors\n // on matching IPv4 addresses to IPv6 ranges or vice versa.\n ipaddr.subnetMatch = function (address, rangeList, defaultName) {\n let i, rangeName, rangeSubnets, subnet;\n\n if (defaultName === undefined || defaultName === null) {\n defaultName = 'unicast';\n }\n\n for (rangeName in rangeList) {\n if (Object.prototype.hasOwnProperty.call(rangeList, rangeName)) {\n rangeSubnets = rangeList[rangeName];\n // ECMA5 Array.isArray isn't available everywhere\n if (rangeSubnets[0] && !(rangeSubnets[0] instanceof Array)) {\n rangeSubnets = [rangeSubnets];\n }\n\n for (i = 0; i < rangeSubnets.length; i++) {\n subnet = rangeSubnets[i];\n if (address.kind() === subnet[0].kind() && address.match.apply(address, subnet)) {\n return rangeName;\n }\n }\n }\n }\n\n return defaultName;\n };\n\n // Export for both the CommonJS and browser-like environment\n if (typeof module !== 'undefined' && module.exports) {\n module.exports = ipaddr;\n\n } else {\n root.ipaddr = ipaddr;\n }\n\n}(this));\n","!function(t,e){\"object\"==typeof exports&&\"undefined\"!=typeof module?module.exports=e():\"function\"==typeof define&&define.amd?define(e):(t=\"undefined\"!=typeof globalThis?globalThis:t||self).dayjs=e()}(this,(function(){\"use strict\";var t=1e3,e=6e4,n=36e5,r=\"millisecond\",i=\"second\",s=\"minute\",u=\"hour\",a=\"day\",o=\"week\",c=\"month\",f=\"quarter\",h=\"year\",d=\"date\",l=\"Invalid Date\",$=/^(\\d{4})[-/]?(\\d{1,2})?[-/]?(\\d{0,2})[Tt\\s]*(\\d{1,2})?:?(\\d{1,2})?:?(\\d{1,2})?[.:]?(\\d+)?$/,y=/\\[([^\\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,M={name:\"en\",weekdays:\"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday\".split(\"_\"),months:\"January_February_March_April_May_June_July_August_September_October_November_December\".split(\"_\"),ordinal:function(t){var e=[\"th\",\"st\",\"nd\",\"rd\"],n=t%100;return\"[\"+t+(e[(n-20)%10]||e[n]||e[0])+\"]\"}},m=function(t,e,n){var r=String(t);return!r||r.length>=e?t:\"\"+Array(e+1-r.length).join(n)+t},v={s:m,z:function(t){var e=-t.utcOffset(),n=Math.abs(e),r=Math.floor(n/60),i=n%60;return(e<=0?\"+\":\"-\")+m(r,2,\"0\")+\":\"+m(i,2,\"0\")},m:function t(e,n){if(e.date()<n.date())return-t(n,e);var r=12*(n.year()-e.year())+(n.month()-e.month()),i=e.clone().add(r,c),s=n-i<0,u=e.clone().add(r+(s?-1:1),c);return+(-(r+(n-i)/(s?i-u:u-i))||0)},a:function(t){return t<0?Math.ceil(t)||0:Math.floor(t)},p:function(t){return{M:c,y:h,w:o,d:a,D:d,h:u,m:s,s:i,ms:r,Q:f}[t]||String(t||\"\").toLowerCase().replace(/s$/,\"\")},u:function(t){return void 0===t}},g=\"en\",D={};D[g]=M;var p=function(t){return t instanceof b},S=function t(e,n,r){var i;if(!e)return g;if(\"string\"==typeof e){var s=e.toLowerCase();D[s]&&(i=s),n&&(D[s]=n,i=s);var u=e.split(\"-\");if(!i&&u.length>1)return t(u[0])}else{var a=e.name;D[a]=e,i=a}return!r&&i&&(g=i),i||!r&&g},w=function(t,e){if(p(t))return t.clone();var n=\"object\"==typeof e?e:{};return n.date=t,n.args=arguments,new b(n)},O=v;O.l=S,O.i=p,O.w=function(t,e){return w(t,{locale:e.$L,utc:e.$u,x:e.$x,$offset:e.$offset})};var b=function(){function M(t){this.$L=S(t.locale,null,!0),this.parse(t)}var m=M.prototype;return m.parse=function(t){this.$d=function(t){var e=t.date,n=t.utc;if(null===e)return new Date(NaN);if(O.u(e))return new Date;if(e instanceof Date)return new Date(e);if(\"string\"==typeof e&&!/Z$/i.test(e)){var r=e.match($);if(r){var i=r[2]-1||0,s=(r[7]||\"0\").substring(0,3);return n?new Date(Date.UTC(r[1],i,r[3]||1,r[4]||0,r[5]||0,r[6]||0,s)):new Date(r[1],i,r[3]||1,r[4]||0,r[5]||0,r[6]||0,s)}}return new Date(e)}(t),this.$x=t.x||{},this.init()},m.init=function(){var t=this.$d;this.$y=t.getFullYear(),this.$M=t.getMonth(),this.$D=t.getDate(),this.$W=t.getDay(),this.$H=t.getHours(),this.$m=t.getMinutes(),this.$s=t.getSeconds(),this.$ms=t.getMilliseconds()},m.$utils=function(){return O},m.isValid=function(){return!(this.$d.toString()===l)},m.isSame=function(t,e){var n=w(t);return this.startOf(e)<=n&&n<=this.endOf(e)},m.isAfter=function(t,e){return w(t)<this.startOf(e)},m.isBefore=function(t,e){return this.endOf(e)<w(t)},m.$g=function(t,e,n){return O.u(t)?this[e]:this.set(n,t)},m.unix=function(){return Math.floor(this.valueOf()/1e3)},m.valueOf=function(){return this.$d.getTime()},m.startOf=function(t,e){var n=this,r=!!O.u(e)||e,f=O.p(t),l=function(t,e){var i=O.w(n.$u?Date.UTC(n.$y,e,t):new Date(n.$y,e,t),n);return r?i:i.endOf(a)},$=function(t,e){return O.w(n.toDate()[t].apply(n.toDate(\"s\"),(r?[0,0,0,0]:[23,59,59,999]).slice(e)),n)},y=this.$W,M=this.$M,m=this.$D,v=\"set\"+(this.$u?\"UTC\":\"\");switch(f){case h:return r?l(1,0):l(31,11);case c:return r?l(1,M):l(0,M+1);case o:var g=this.$locale().weekStart||0,D=(y<g?y+7:y)-g;return l(r?m-D:m+(6-D),M);case a:case d:return $(v+\"Hours\",0);case u:return $(v+\"Minutes\",1);case s:return $(v+\"Seconds\",2);case i:return $(v+\"Milliseconds\",3);default:return this.clone()}},m.endOf=function(t){return this.startOf(t,!1)},m.$set=function(t,e){var n,o=O.p(t),f=\"set\"+(this.$u?\"UTC\":\"\"),l=(n={},n[a]=f+\"Date\",n[d]=f+\"Date\",n[c]=f+\"Month\",n[h]=f+\"FullYear\",n[u]=f+\"Hours\",n[s]=f+\"Minutes\",n[i]=f+\"Seconds\",n[r]=f+\"Milliseconds\",n)[o],$=o===a?this.$D+(e-this.$W):e;if(o===c||o===h){var y=this.clone().set(d,1);y.$d[l]($),y.init(),this.$d=y.set(d,Math.min(this.$D,y.daysInMonth())).$d}else l&&this.$d[l]($);return this.init(),this},m.set=function(t,e){return this.clone().$set(t,e)},m.get=function(t){return this[O.p(t)]()},m.add=function(r,f){var d,l=this;r=Number(r);var $=O.p(f),y=function(t){var e=w(l);return O.w(e.date(e.date()+Math.round(t*r)),l)};if($===c)return this.set(c,this.$M+r);if($===h)return this.set(h,this.$y+r);if($===a)return y(1);if($===o)return y(7);var M=(d={},d[s]=e,d[u]=n,d[i]=t,d)[$]||1,m=this.$d.getTime()+r*M;return O.w(m,this)},m.subtract=function(t,e){return this.add(-1*t,e)},m.format=function(t){var e=this,n=this.$locale();if(!this.isValid())return n.invalidDate||l;var r=t||\"YYYY-MM-DDTHH:mm:ssZ\",i=O.z(this),s=this.$H,u=this.$m,a=this.$M,o=n.weekdays,c=n.months,f=n.meridiem,h=function(t,n,i,s){return t&&(t[n]||t(e,r))||i[n].slice(0,s)},d=function(t){return O.s(s%12||12,t,\"0\")},$=f||function(t,e,n){var r=t<12?\"AM\":\"PM\";return n?r.toLowerCase():r};return r.replace(y,(function(t,r){return r||function(t){switch(t){case\"YY\":return String(e.$y).slice(-2);case\"YYYY\":return O.s(e.$y,4,\"0\");case\"M\":return a+1;case\"MM\":return O.s(a+1,2,\"0\");case\"MMM\":return h(n.monthsShort,a,c,3);case\"MMMM\":return h(c,a);case\"D\":return e.$D;case\"DD\":return O.s(e.$D,2,\"0\");case\"d\":return String(e.$W);case\"dd\":return h(n.weekdaysMin,e.$W,o,2);case\"ddd\":return h(n.weekdaysShort,e.$W,o,3);case\"dddd\":return o[e.$W];case\"H\":return String(s);case\"HH\":return O.s(s,2,\"0\");case\"h\":return d(1);case\"hh\":return d(2);case\"a\":return $(s,u,!0);case\"A\":return $(s,u,!1);case\"m\":return String(u);case\"mm\":return O.s(u,2,\"0\");case\"s\":return String(e.$s);case\"ss\":return O.s(e.$s,2,\"0\");case\"SSS\":return O.s(e.$ms,3,\"0\");case\"Z\":return i}return null}(t)||i.replace(\":\",\"\")}))},m.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},m.diff=function(r,d,l){var $,y=this,M=O.p(d),m=w(r),v=(m.utcOffset()-this.utcOffset())*e,g=this-m,D=function(){return O.m(y,m)};switch(M){case h:$=D()/12;break;case c:$=D();break;case f:$=D()/3;break;case o:$=(g-v)/6048e5;break;case a:$=(g-v)/864e5;break;case u:$=g/n;break;case s:$=g/e;break;case i:$=g/t;break;default:$=g}return l?$:O.a($)},m.daysInMonth=function(){return this.endOf(c).$D},m.$locale=function(){return D[this.$L]},m.locale=function(t,e){if(!t)return this.$L;var n=this.clone(),r=S(t,e,!0);return r&&(n.$L=r),n},m.clone=function(){return O.w(this.$d,this)},m.toDate=function(){return new Date(this.valueOf())},m.toJSON=function(){return this.isValid()?this.toISOString():null},m.toISOString=function(){return this.$d.toISOString()},m.toString=function(){return this.$d.toUTCString()},M}(),_=b.prototype;return w.prototype=_,[[\"$ms\",r],[\"$s\",i],[\"$m\",s],[\"$H\",u],[\"$W\",a],[\"$M\",c],[\"$y\",h],[\"$D\",d]].forEach((function(t){_[t[1]]=function(e){return this.$g(e,t[0],t[1])}})),w.extend=function(t,e){return t.$i||(t(e,b,w),t.$i=!0),w},w.locale=S,w.isDayjs=p,w.unix=function(t){return w(1e3*t)},w.en=D[g],w.Ls=D,w.p={},w}));","!function(t,e){\"object\"==typeof exports&&\"undefined\"!=typeof module?module.exports=e():\"function\"==typeof define&&define.amd?define(e):(t=\"undefined\"!=typeof globalThis?globalThis:t||self).dayjs_plugin_timezone=e()}(this,(function(){\"use strict\";var t={year:0,month:1,day:2,hour:3,minute:4,second:5},e={};return function(n,i,o){var r,a=function(t,n,i){void 0===i&&(i={});var o=new Date(t),r=function(t,n){void 0===n&&(n={});var i=n.timeZoneName||\"short\",o=t+\"|\"+i,r=e[o];return r||(r=new Intl.DateTimeFormat(\"en-US\",{hour12:!1,timeZone:t,year:\"numeric\",month:\"2-digit\",day:\"2-digit\",hour:\"2-digit\",minute:\"2-digit\",second:\"2-digit\",timeZoneName:i}),e[o]=r),r}(n,i);return r.formatToParts(o)},u=function(e,n){for(var i=a(e,n),r=[],u=0;u<i.length;u+=1){var f=i[u],s=f.type,m=f.value,c=t[s];c>=0&&(r[c]=parseInt(m,10))}var d=r[3],l=24===d?0:d,v=r[0]+\"-\"+r[1]+\"-\"+r[2]+\" \"+l+\":\"+r[4]+\":\"+r[5]+\":000\",h=+e;return(o.utc(v).valueOf()-(h-=h%1e3))/6e4},f=i.prototype;f.tz=function(t,e){void 0===t&&(t=r);var n=this.utcOffset(),i=this.toDate(),a=i.toLocaleString(\"en-US\",{timeZone:t}),u=Math.round((i-new Date(a))/1e3/60),f=o(a).$set(\"millisecond\",this.$ms).utcOffset(15*-Math.round(i.getTimezoneOffset()/15)-u,!0);if(e){var s=f.utcOffset();f=f.add(n-s,\"minute\")}return f.$x.$timezone=t,f},f.offsetName=function(t){var e=this.$x.$timezone||o.tz.guess(),n=a(this.valueOf(),e,{timeZoneName:t}).find((function(t){return\"timezonename\"===t.type.toLowerCase()}));return n&&n.value};var s=f.startOf;f.startOf=function(t,e){if(!this.$x||!this.$x.$timezone)return s.call(this,t,e);var n=o(this.format(\"YYYY-MM-DD HH:mm:ss:SSS\"));return s.call(n,t,e).tz(this.$x.$timezone,!0)},o.tz=function(t,e,n){var i=n&&e,a=n||e||r,f=u(+o(),a);if(\"string\"!=typeof t)return o(t).tz(a);var s=function(t,e,n){var i=t-60*e*1e3,o=u(i,n);if(e===o)return[i,e];var r=u(i-=60*(o-e)*1e3,n);return o===r?[i,o]:[t-60*Math.min(o,r)*1e3,Math.max(o,r)]}(o.utc(t,i).valueOf(),f,a),m=s[0],c=s[1],d=o(m).utcOffset(c);return d.$x.$timezone=a,d},o.tz.guess=function(){return Intl.DateTimeFormat().resolvedOptions().timeZone},o.tz.setDefault=function(t){r=t}}}));","!function(t,i){\"object\"==typeof exports&&\"undefined\"!=typeof module?module.exports=i():\"function\"==typeof define&&define.amd?define(i):(t=\"undefined\"!=typeof globalThis?globalThis:t||self).dayjs_plugin_utc=i()}(this,(function(){\"use strict\";var t=\"minute\",i=/[+-]\\d\\d(?::?\\d\\d)?/g,e=/([+-]|\\d\\d)/g;return function(s,f,n){var u=f.prototype;n.utc=function(t){var i={date:t,utc:!0,args:arguments};return new f(i)},u.utc=function(i){var e=n(this.toDate(),{locale:this.$L,utc:!0});return i?e.add(this.utcOffset(),t):e},u.local=function(){return n(this.toDate(),{locale:this.$L,utc:!1})};var o=u.parse;u.parse=function(t){t.utc&&(this.$u=!0),this.$utils().u(t.$offset)||(this.$offset=t.$offset),o.call(this,t)};var r=u.init;u.init=function(){if(this.$u){var t=this.$d;this.$y=t.getUTCFullYear(),this.$M=t.getUTCMonth(),this.$D=t.getUTCDate(),this.$W=t.getUTCDay(),this.$H=t.getUTCHours(),this.$m=t.getUTCMinutes(),this.$s=t.getUTCSeconds(),this.$ms=t.getUTCMilliseconds()}else r.call(this)};var a=u.utcOffset;u.utcOffset=function(s,f){var n=this.$utils().u;if(n(s))return this.$u?0:n(this.$offset)?a.call(this):this.$offset;if(\"string\"==typeof s&&(s=function(t){void 0===t&&(t=\"\");var s=t.match(i);if(!s)return null;var f=(\"\"+s[0]).match(e)||[\"-\",0,0],n=f[0],u=60*+f[1]+ +f[2];return 0===u?0:\"+\"===n?u:-u}(s),null===s))return this;var u=Math.abs(s)<=16?60*s:s,o=this;if(f)return o.$offset=u,o.$u=0===s,o;if(0!==s){var r=this.$u?this.toDate().getTimezoneOffset():-1*this.utcOffset();(o=this.local().add(u+r,t)).$offset=u,o.$x.$localOffset=r}else o=this.utc();return o};var h=u.format;u.format=function(t){var i=t||(this.$u?\"YYYY-MM-DDTHH:mm:ss[Z]\":\"\");return h.call(this,i)},u.valueOf=function(){var t=this.$utils().u(this.$offset)?0:this.$offset+(this.$x.$localOffset||this.$d.getTimezoneOffset());return this.$d.valueOf()-6e4*t},u.isUTC=function(){return!!this.$u},u.toISOString=function(){return this.toDate().toISOString()},u.toString=function(){return this.toDate().toUTCString()};var l=u.toDate;u.toDate=function(t){return\"s\"===t&&this.$offset?n(this.format(\"YYYY-MM-DD HH:mm:ss:SSS\")).toDate():l.call(this)};var c=u.diff;u.diff=function(t,i,e){if(t&&this.$u===t.$u)return c.call(this,t,i,e);var s=this.local(),f=n(t).local();return c.call(s,f,i,e)}}}));","import { A as PropertyType, b as ApFile, c as isNil, d as parseToJsonIfPossible, l as isString, o as isBase64, r as tryCatchSync, v as DateRangeValue } from \"./markdown-property-DMfHjEiL.js\";\nimport { g as AUTHENTICATION_PROPERTY_NAME, i as getAuthPropertyForValue, m as isObject } from \"./authentication-o-4CdAPR.js\";\nimport ipaddr from \"ipaddr.js\";\nimport { Readable } from \"node:stream\";\nimport dayjs from \"dayjs\";\nimport timezone from \"dayjs/plugin/timezone.js\";\nimport utc from \"dayjs/plugin/utc.js\";\n\n//#region upstream/core-utils/lib/friendly-piece-error.ts\nconst FRIENDLY_PIECE_ERROR_VERSION = 1;\nconst STACK_LINE_REGEX = /\\n\\s*at\\s+.+$/gm;\nconst HTTP_ERROR_MESSAGE_MAX_LENGTH = 2e3;\nconst RAW_ERROR_MAX_LENGTH = 16e3;\nconst HTTP_STATUS_MIN = 100;\nconst HTTP_STATUS_MAX = 599;\nconst MAX_MESSAGE_DEPTH = 12;\nconst MAX_SERIALIZED_DEPTH = 64;\nconst CIRCULAR_PLACEHOLDER = \"[Circular]\";\nconst TOO_DEEP_PLACEHOLDER = \"[Too deep]\";\nconst UNSERIALIZABLE_PLACEHOLDER = \"[Unserializable]\";\nconst isObjectRecord = (value) => {\n\treturn !isNil(value) && typeof value === \"object\" && !Array.isArray(value);\n};\nconst safeJsonParse = (value) => {\n\ttry {\n\t\treturn JSON.parse(value);\n\t} catch {\n\t\treturn value;\n\t}\n};\nconst stripStack = (value) => {\n\treturn value.replace(STACK_LINE_REGEX, \"\").trim();\n};\nconst truncate = (value) => {\n\tif (value.length <= HTTP_ERROR_MESSAGE_MAX_LENGTH) return value;\n\treturn `${value.slice(0, HTTP_ERROR_MESSAGE_MAX_LENGTH)}…`;\n};\nconst truncateRaw = (value) => {\n\tif (value.length <= RAW_ERROR_MAX_LENGTH) return value;\n\treturn `${value.slice(0, RAW_ERROR_MAX_LENGTH)}\\n…[truncated]`;\n};\nconst HTML_DOC_REGEX = /^\\s*(<!doctype\\s+html|<html\\b|<\\?xml)/i;\nconst HTML_TAG_LIKE_REGEX = /<\\s*(html|body|head|title|meta|p|div|span|h[1-6]|table|script|style)\\b/i;\nconst isLikelyMarkupBody = (value) => {\n\tif (HTML_DOC_REGEX.test(value)) return true;\n\tif (!value.includes(\"<\") || !value.includes(\">\")) return false;\n\treturn HTML_TAG_LIKE_REGEX.test(value);\n};\nconst decodeHtmlEntities = (value) => {\n\treturn value.replace(/&nbsp;/g, \" \").replace(/&amp;/g, \"&\").replace(/&lt;/g, \"<\").replace(/&gt;/g, \">\").replace(/&quot;/g, \"\\\"\").replace(/&#39;/g, \"'\").replace(/&apos;/g, \"'\");\n};\nconst stripMarkup = (value) => {\n\tconst titleMatch = value.match(/<title[^>]*>([\\s\\S]*?)<\\/title>/i);\n\tconst title = titleMatch ? decodeHtmlEntities(titleMatch[1]).replace(/\\s+/g, \" \").trim() : \"\";\n\tconst withoutNoise = value.replace(/<script[\\s\\S]*?<\\/script>/gi, \" \").replace(/<style[\\s\\S]*?<\\/style>/gi, \" \").replace(/<head[\\s\\S]*?<\\/head>/gi, \" \");\n\tconst textOnly = decodeHtmlEntities(withoutNoise.replace(/<[^>]+>/g, \" \")).replace(/\\s+/g, \" \").trim();\n\tif (textOnly.length > 0 && title.length > 0 && !textOnly.startsWith(title)) return `${title} — ${textOnly}`;\n\treturn textOnly.length > 0 ? textOnly : title;\n};\nconst readString = (record, key) => {\n\tconst value = record[key];\n\treturn isString(value) ? value : void 0;\n};\nconst collectMessageFrom = ({ value, depth, seen }) => {\n\tif (isNil(value) || depth > MAX_MESSAGE_DEPTH) return;\n\tif (isString(value)) {\n\t\tconst trimmed = value.trim();\n\t\tif (trimmed.length === 0) return;\n\t\tif (isLikelyMarkupBody(trimmed)) {\n\t\t\tconst stripped = stripMarkup(trimmed);\n\t\t\treturn stripped.length > 0 ? stripped : void 0;\n\t\t}\n\t\treturn trimmed;\n\t}\n\tif (Array.isArray(value)) {\n\t\tif (seen.has(value)) return;\n\t\tseen.add(value);\n\t\tconst parts = value.map((entry) => collectMessageFrom({\n\t\t\tvalue: entry,\n\t\t\tdepth: depth + 1,\n\t\t\tseen\n\t\t})).filter((entry) => isString(entry) && entry.length > 0);\n\t\treturn parts.length > 0 ? parts.join(\"; \") : void 0;\n\t}\n\tif (isObjectRecord(value)) {\n\t\tif (seen.has(value)) return;\n\t\tseen.add(value);\n\t\tconst nested = value[\"message\"] ?? value[\"detail\"] ?? value[\"description\"] ?? value[\"reason\"] ?? value[\"error\"];\n\t\treturn collectMessageFrom({\n\t\t\tvalue: nested,\n\t\t\tdepth: depth + 1,\n\t\t\tseen\n\t\t});\n\t}\n};\nconst collectMessage = (value) => {\n\treturn collectMessageFrom({\n\t\tvalue,\n\t\tdepth: 0,\n\t\tseen: /* @__PURE__ */ new WeakSet()\n\t});\n};\nconst extractApiMessage = (responseBody) => {\n\tif (isNil(responseBody)) return;\n\tif (isString(responseBody) || Array.isArray(responseBody)) {\n\t\tconst collected = collectMessage(responseBody);\n\t\treturn collected ? truncate(collected) : void 0;\n\t}\n\tif (!isObjectRecord(responseBody)) return truncate(String(responseBody));\n\tconst candidates = [\n\t\tresponseBody[\"message\"],\n\t\tresponseBody[\"error_description\"],\n\t\tresponseBody[\"errorDescription\"],\n\t\tresponseBody[\"detail\"],\n\t\tresponseBody[\"title\"],\n\t\tresponseBody[\"error_message\"],\n\t\tresponseBody[\"errorMessage\"],\n\t\tresponseBody[\"errorMessages\"],\n\t\tresponseBody[\"errors\"],\n\t\tresponseBody[\"error\"],\n\t\tresponseBody[\"faultstring\"],\n\t\tresponseBody[\"fault\"],\n\t\tresponseBody[\"reason\"],\n\t\tresponseBody[\"description\"]\n\t];\n\tfor (const candidate of candidates) {\n\t\tconst collected = collectMessage(candidate);\n\t\tif (collected) return truncate(collected);\n\t}\n};\nconst toHttpStatus = (value) => {\n\treturn typeof value === \"number\" && value >= HTTP_STATUS_MIN && value <= HTTP_STATUS_MAX ? value : void 0;\n};\nconst extractResponseHttpDetails = (error) => {\n\tconst response = error[\"response\"];\n\tif (!isObjectRecord(response)) return null;\n\tconst statusValue = response[\"status\"];\n\tconst status = typeof statusValue === \"number\" ? statusValue : void 0;\n\tconst responseBody = response[\"body\"];\n\tconst headersValue = response[\"headers\"];\n\tconst headers = isObjectRecord(headersValue) ? headersValue : void 0;\n\tconst requestRaw = error[\"request\"];\n\tconst request = isObjectRecord(requestRaw) ? requestRaw : void 0;\n\tconst requestBody = request?.[\"body\"];\n\tconst requestUrl = request === void 0 ? void 0 : readString(request, \"url\");\n\tconst requestMethod = request === void 0 ? void 0 : readString(request, \"method\");\n\tif (isNil(status) && isNil(responseBody) && isNil(requestBody)) return null;\n\treturn {\n\t\tstatus,\n\t\tresponseBody,\n\t\tresponseHeaders: headers,\n\t\trequestBody,\n\t\trequestUrl,\n\t\trequestMethod,\n\t\tapiMessage: extractApiMessage(responseBody)\n\t};\n};\nconst extractClientHttpDetails = (error) => {\n\tconst status = toHttpStatus(error[\"status\"]);\n\tif (isNil(status)) return null;\n\tconst responseBody = error[\"error\"] ?? error[\"body\"];\n\tconst headersValue = error[\"headers\"];\n\treturn {\n\t\tstatus,\n\t\tresponseBody,\n\t\tresponseHeaders: isObjectRecord(headersValue) ? headersValue : void 0,\n\t\tapiMessage: extractApiMessage(responseBody)\n\t};\n};\nconst extractHttpDetails = (error) => {\n\treturn extractResponseHttpDetails(error) ?? extractClientHttpDetails(error);\n};\nconst rebuildSerializable = ({ value, depth, seen }) => {\n\tif (isNil(value) || isString(value) || typeof value === \"number\" || typeof value === \"boolean\") return value;\n\tif (Array.isArray(value) || isObjectRecord(value)) {\n\t\tif (seen.has(value)) return CIRCULAR_PLACEHOLDER;\n\t\tif (depth >= MAX_SERIALIZED_DEPTH) return TOO_DEEP_PLACEHOLDER;\n\t\tseen.add(value);\n\t\tif (Array.isArray(value)) return value.map((entry) => rebuildSerializable({\n\t\t\tvalue: entry,\n\t\t\tdepth: depth + 1,\n\t\t\tseen\n\t\t}));\n\t\treturn Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, rebuildSerializable({\n\t\t\tvalue: entry,\n\t\t\tdepth: depth + 1,\n\t\t\tseen\n\t\t})]));\n\t}\n\treturn String(value);\n};\nconst toSerializable = (value) => {\n\tif (isNil(value)) return value;\n\tconst { error } = tryCatchSync(() => JSON.stringify(value));\n\tif (isNil(error)) return value;\n\tconst rebuilt = tryCatchSync(() => rebuildSerializable({\n\t\tvalue,\n\t\tdepth: 0,\n\t\tseen: /* @__PURE__ */ new WeakSet()\n\t}));\n\treturn isNil(rebuilt.error) ? rebuilt.data : UNSERIALIZABLE_PLACEHOLDER;\n};\nconst toSerializableHttpDetails = (httpDetails) => {\n\tif (isNil(httpDetails)) return null;\n\tconst { responseBody, requestBody, responseHeaders } = httpDetails;\n\treturn {\n\t\t...httpDetails,\n\t\tresponseBody: toSerializable(responseBody),\n\t\trequestBody: toSerializable(requestBody),\n\t\tresponseHeaders: isNil(responseHeaders) ? void 0 : Object.fromEntries(Object.entries(responseHeaders).map(([key, value]) => [key, toSerializable(value)]))\n\t};\n};\nconst readErrorName = (error) => {\n\tconst name = readString(error, \"name\");\n\tif (!isNil(name) && name.length > 0 && name !== \"Error\") return name;\n\tconst ctor = error[\"constructor\"];\n\tif (typeof ctor === \"function\" && isString(ctor.name) && ctor.name.length > 0 && ctor.name !== \"Object\" && ctor.name !== \"Error\") return ctor.name;\n};\nconst readErrorMessage = (error) => {\n\tconst messageString = readString(error, \"message\");\n\tif (!isNil(messageString)) return messageString;\n\tconst stringified = String(error);\n\tif (stringified.length > 0 && stringified !== \"[object Object]\") return stringified;\n\treturn \"Unknown error\";\n};\nconst pickPlainMessage = ({ httpDetails, rawMessage }) => {\n\tif (httpDetails?.apiMessage) return httpDetails.apiMessage;\n\tconst cleaned = stripStack(rawMessage);\n\tif (cleaned.length > 0) return truncate(cleaned);\n\treturn \"Unknown error\";\n};\nconst isFriendlyPieceError = (value) => {\n\tif (!isObjectRecord(value)) return false;\n\treturn value[\"__apErrorVersion\"] === FRIENDLY_PIECE_ERROR_VERSION && typeof value[\"message\"] === \"string\";\n};\nconst formatPieceError = (error, options) => {\n\tconst raw = options?.raw;\n\tconst withRaw = (base) => {\n\t\tif (isNil(raw) || raw.length === 0 || !isNil(base.raw)) return base;\n\t\treturn {\n\t\t\t...base,\n\t\t\traw: truncateRaw(raw)\n\t\t};\n\t};\n\tif (isNil(error)) return withRaw({\n\t\t__apErrorVersion: FRIENDLY_PIECE_ERROR_VERSION,\n\t\tmessage: \"Unknown error\"\n\t});\n\tif (isString(error)) {\n\t\tconst cleaned = stripStack(error);\n\t\treturn withRaw({\n\t\t\t__apErrorVersion: FRIENDLY_PIECE_ERROR_VERSION,\n\t\t\tmessage: cleaned.length > 0 ? cleaned : \"Unknown error\"\n\t\t});\n\t}\n\tif (!isObjectRecord(error)) return withRaw({\n\t\t__apErrorVersion: FRIENDLY_PIECE_ERROR_VERSION,\n\t\tmessage: truncate(String(error))\n\t});\n\tif (isFriendlyPieceError(error)) return withRaw(error);\n\tconst httpDetails = extractHttpDetails(error);\n\tconst errorName = readErrorName(error);\n\tconst rawMessage = readErrorMessage(error);\n\tconst message = pickPlainMessage({\n\t\thttpDetails,\n\t\trawMessage\n\t});\n\treturn withRaw({\n\t\t__apErrorVersion: FRIENDLY_PIECE_ERROR_VERSION,\n\t\tmessage,\n\t\terrorName,\n\t\t...toSerializableHttpDetails(httpDetails) ?? {}\n\t});\n};\nconst tryParseFriendlyPieceError = (value) => {\n\tif (isNil(value)) return null;\n\tconst candidate = isString(value) ? safeJsonParse(value) : value;\n\treturn isFriendlyPieceError(candidate) ? candidate : null;\n};\n\n//#endregion\n//#region upstream/core-utils/lib/ssrf-ip-classifier.ts\nfunction parseOrNull(ip) {\n\ttry {\n\t\treturn ipaddr.parse(ip);\n\t} catch {\n\t\treturn null;\n\t}\n}\nfunction isInAllowList({ ip, allowList }) {\n\tif (allowList.includes(ip)) return true;\n\tconst addr = parseOrNull(ip);\n\tif (!addr) return false;\n\treturn allowList.some((entry) => entry.includes(\"/\") && matchesCidr({\n\t\taddr,\n\t\tcidr: entry\n\t}));\n}\nfunction matchesCidr({ addr, cidr }) {\n\ttry {\n\t\tconst range = ipaddr.parseCIDR(cidr);\n\t\tif (addr.kind() !== range[0].kind()) return false;\n\t\treturn addr.match(range);\n\t} catch {\n\t\treturn false;\n\t}\n}\nfunction isBlockedRange(addr) {\n\tif (addr.kind() === \"ipv6\") {\n\t\tconst v6 = addr;\n\t\tif (v6.isIPv4MappedAddress()) return isBlockedRange(v6.toIPv4Address());\n\t}\n\treturn addr.range() !== \"unicast\";\n}\nfunction isBlockedIp({ ip, allowList }) {\n\tif (isInAllowList({\n\t\tip,\n\t\tallowList\n\t})) return false;\n\tconst addr = parseOrNull(ip);\n\tif (!addr) return true;\n\treturn isBlockedRange(addr);\n}\nconst ssrfIpClassifier = { isBlockedIp };\n\n//#endregion\n//#region upstream/engine/lib/helper/dynamic-prop-keys.ts\nfunction escapePropsKeys(props) {\n\treturn Object.fromEntries(Object.entries(props).map(([key, property]) => [escapeKey(key), property]));\n}\nfunction unescapePropsKeys(props) {\n\treturn Object.fromEntries(Object.entries(props).map(([key, property]) => [unescapeKey(key), property]));\n}\nfunction unescapeInputKeys(value) {\n\tif (!isObject(value)) return value;\n\treturn Object.fromEntries(Object.entries(value).map(([key, child]) => [unescapeKey(key), child]));\n}\nfunction escapeKey(key) {\n\tif (!RESERVED_CHARS.test(key)) return key;\n\treturn ESCAPED_KEY_MARKER + key.replace(/[~.[\\]\"']/g, (char) => ESCAPE_SEQUENCES[char]);\n}\nfunction unescapeKey(key) {\n\tif (!key.startsWith(ESCAPED_KEY_MARKER)) return key;\n\treturn key.slice(ESCAPED_KEY_MARKER.length).replace(/~[0-5]/g, (sequence) => UNESCAPE_SEQUENCES[sequence]);\n}\nconst ESCAPED_KEY_MARKER = \"~ap~\";\nconst RESERVED_CHARS = /[~.[\\]\"']/;\nconst ESCAPE_SEQUENCES = {\n\t\"~\": \"~0\",\n\t\".\": \"~1\",\n\t\"[\": \"~2\",\n\t\"]\": \"~3\",\n\t\"\\\"\": \"~4\",\n\t\"'\": \"~5\"\n};\nconst UNESCAPE_SEQUENCES = Object.fromEntries(Object.entries(ESCAPE_SEQUENCES).map(([char, sequence]) => [sequence, char]));\nconst dynamicPropKeys = {\n\tescapePropsKeys,\n\tunescapePropsKeys,\n\tunescapeInputKeys\n};\n\n//#endregion\n//#region upstream/engine/lib/variables/processors/array-zipper.ts\nfunction getLongestArrayLengthInObject(props) {\n\treturn Math.max(...Object.values(props).map((value) => Array.isArray(value) ? value.length : 1));\n}\nfunction constructResultForIndex(props, index) {\n\treturn Object.entries(props).reduce((result, [key, value]) => {\n\t\tresult[key] = Array.isArray(value) ? value[index] : value;\n\t\treturn result;\n\t}, {});\n}\nconst arrayZipperProcessor = (_property, value) => {\n\tif (Array.isArray(value) || !isObject(value)) return value;\n\treturn Array.from({ length: getLongestArrayLengthInObject(value) }, (_, index) => constructResultForIndex(value, index));\n};\n\n//#endregion\n//#region upstream/engine/lib/variables/processors/checkbox.ts\nconst checkboxProcessor = (_property, value) => {\n\tif (isNil(value) || typeof value === \"boolean\") return value;\n\tif (typeof value === \"string\" && value.trim().length === 0) return;\n\tconst parsed = parseToJsonIfPossible(value);\n\treturn typeof parsed === \"boolean\" ? parsed : value;\n};\n\n//#endregion\n//#region upstream/engine/lib/variables/processors/date-time.ts\nconst dateTimeProcessor = (_property, value) => {\n\tdayjs.extend(utc);\n\tdayjs.extend(timezone);\n\tconst dateTimeString = value;\n\ttry {\n\t\tif (!dateTimeString) throw Error(\"Undefined input\");\n\t\treturn dayjs.tz(dateTimeString, \"UTC\").toISOString();\n\t} catch (error) {\n\t\tconsole.error(error);\n\t\treturn;\n\t}\n};\n\n//#endregion\n//#region upstream/engine/lib/variables/processors/file.ts\nconst fileProcessor = async (property, urlOrBase64) => {\n\tif (isNil(urlOrBase64) || !isString(urlOrBase64)) return null;\n\tconst streaming = property.type === \"FILE\" && property.streaming === true;\n\ttry {\n\t\tif (streaming) return await handleStreamingFile(urlOrBase64);\n\t\tconst file = handleBase64File(urlOrBase64);\n\t\tif (!isNil(file)) return file;\n\t\treturn await handleUrlFile(urlOrBase64);\n\t} catch (e) {\n\t\tconsole.error(e);\n\t\treturn null;\n\t}\n};\nfunction parseBase64File(propertyValue) {\n\tif (!isBase64(propertyValue, { allowMime: true })) return null;\n\tconst matches = propertyValue.match(/^data:([A-Za-z-+/]+);base64,(.+)$/);\n\tif (!matches || matches?.length !== 3) return null;\n\treturn {\n\t\textension: mimeExtension(matches[1]) || \"bin\",\n\t\tbuffer: Buffer.from(matches[2], \"base64\")\n\t};\n}\nfunction handleBase64File(propertyValue) {\n\tconst parsed = parseBase64File(propertyValue);\n\tif (isNil(parsed)) return null;\n\treturn new ApFile(`unknown.${parsed.extension}`, parsed.buffer, parsed.extension);\n}\nasync function handleUrlFile(path) {\n\tconst fileResponse = await fetch(path);\n\tif (!fileResponse.ok) return null;\n\tconst filename = getFileName(path, fileResponse.headers.get(\"content-disposition\"), fileResponse.headers.get(\"content-type\") ?? void 0) ?? \"unknown\";\n\tconst extension = extensionFromFilename(filename);\n\treturn new ApFile(filename, Buffer.from(await fileResponse.arrayBuffer()), extension);\n}\nasync function handleStreamingFile(propertyValue) {\n\tconst parsed = parseBase64File(propertyValue);\n\tif (!isNil(parsed)) return {\n\t\tfilename: `unknown.${parsed.extension}`,\n\t\textension: parsed.extension,\n\t\tsize: parsed.buffer.length,\n\t\tbody: Readable.from(parsed.buffer)\n\t};\n\tconst fileResponse = await fetch(propertyValue);\n\tif (!fileResponse.ok || isNil(fileResponse.body)) {\n\t\tawait fileResponse.body?.cancel();\n\t\treturn null;\n\t}\n\tconst filename = getFileName(propertyValue, fileResponse.headers.get(\"content-disposition\"), fileResponse.headers.get(\"content-type\") ?? void 0) ?? \"unknown\";\n\tconst extension = extensionFromFilename(filename);\n\tconst contentEncoding = fileResponse.headers.get(\"content-encoding\");\n\tconst contentLength = Number(fileResponse.headers.get(\"content-length\"));\n\treturn {\n\t\tfilename,\n\t\textension,\n\t\tsize: (isNil(contentEncoding) || contentEncoding.toLowerCase() === \"identity\") && Number.isInteger(contentLength) && contentLength > 0 ? contentLength : void 0,\n\t\tbody: Readable.fromWeb(fileResponse.body)\n\t};\n}\nfunction extensionFromFilename(filename) {\n\tconst parts = filename.split(\".\");\n\tconst last = parts.length > 1 ? parts.pop() : void 0;\n\treturn last ? last : void 0;\n}\nfunction getFileName(path, disposition, mimeType) {\n\tconst url = new URL(path);\n\tif (isNil(disposition)) {\n\t\tconst fileNameFromUrl = url.pathname.includes(\"/\") && url.pathname.split(\"/\").pop()?.includes(\".\") ? url.pathname.split(\"/\").pop() : null;\n\t\tif (!isNil(fileNameFromUrl)) return fileNameFromUrl;\n\t\treturn `unknown.${(mimeType ? mimeExtension(mimeType) : null) ?? \"bin\"}`;\n\t}\n\tconst utf8FilenameRegex = /filename\\*=UTF-8''([\\w%\\-.]+)(?:; ?|$)/i;\n\tif (utf8FilenameRegex.test(disposition)) {\n\t\tconst result = utf8FilenameRegex.exec(disposition);\n\t\tif (result && result.length > 1) return decodeURIComponent(result[1]);\n\t}\n\tconst filenameStart = disposition.toLowerCase().indexOf(\"filename=\");\n\tconst asciiFilenameRegex = /^filename=([\"']?)(.*?[^\\\\])\\1(?:; ?|$)/i;\n\tif (filenameStart >= 0) {\n\t\tconst partialDisposition = disposition.slice(filenameStart);\n\t\tconst matches = asciiFilenameRegex.exec(partialDisposition);\n\t\tif (matches != null && matches[2]) return matches[2];\n\t}\n\treturn null;\n}\nfunction mimeExtension(mimeType) {\n\tconst normalized = mimeType.split(\";\")[0].trim().toLowerCase();\n\treturn MIME_EXTENSIONS[normalized] ?? null;\n}\nconst MIME_EXTENSIONS = {\n\t\"application/json\": \"json\",\n\t\"application/pdf\": \"pdf\",\n\t\"application/xml\": \"xml\",\n\t\"application/zip\": \"zip\",\n\t\"application/gzip\": \"gz\",\n\t\"application/x-7z-compressed\": \"7z\",\n\t\"application/x-tar\": \"tar\",\n\t\"application/octet-stream\": \"bin\",\n\t\"application/msword\": \"doc\",\n\t\"application/vnd.openxmlformats-officedocument.wordprocessingml.document\": \"docx\",\n\t\"application/vnd.ms-excel\": \"xls\",\n\t\"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\": \"xlsx\",\n\t\"application/vnd.ms-powerpoint\": \"ppt\",\n\t\"application/vnd.openxmlformats-officedocument.presentationml.presentation\": \"pptx\",\n\t\"application/rtf\": \"rtf\",\n\t\"application/javascript\": \"js\",\n\t\"application/x-javascript\": \"js\",\n\t\"application/x-yaml\": \"yaml\",\n\t\"application/yaml\": \"yaml\",\n\t\"application/x-httpd-php\": \"php\",\n\t\"application/x-sh\": \"sh\",\n\t\"image/png\": \"png\",\n\t\"image/jpeg\": \"jpg\",\n\t\"image/jpg\": \"jpg\",\n\t\"image/gif\": \"gif\",\n\t\"image/webp\": \"webp\",\n\t\"image/svg+xml\": \"svg\",\n\t\"image/bmp\": \"bmp\",\n\t\"image/tiff\": \"tiff\",\n\t\"image/x-icon\": \"ico\",\n\t\"image/vnd.microsoft.icon\": \"ico\",\n\t\"image/heic\": \"heic\",\n\t\"image/heif\": \"heif\",\n\t\"image/avif\": \"avif\",\n\t\"text/plain\": \"txt\",\n\t\"text/html\": \"html\",\n\t\"text/css\": \"css\",\n\t\"text/csv\": \"csv\",\n\t\"text/javascript\": \"js\",\n\t\"text/markdown\": \"md\",\n\t\"text/xml\": \"xml\",\n\t\"text/tab-separated-values\": \"tsv\",\n\t\"text/yaml\": \"yaml\",\n\t\"audio/mpeg\": \"mp3\",\n\t\"audio/mp3\": \"mp3\",\n\t\"audio/mp4\": \"m4a\",\n\t\"audio/wav\": \"wav\",\n\t\"audio/x-wav\": \"wav\",\n\t\"audio/ogg\": \"ogg\",\n\t\"audio/webm\": \"weba\",\n\t\"audio/flac\": \"flac\",\n\t\"audio/aac\": \"aac\",\n\t\"video/mp4\": \"mp4\",\n\t\"video/mpeg\": \"mpeg\",\n\t\"video/webm\": \"webm\",\n\t\"video/quicktime\": \"mov\",\n\t\"video/x-msvideo\": \"avi\",\n\t\"video/ogg\": \"ogv\",\n\t\"font/woff\": \"woff\",\n\t\"font/woff2\": \"woff2\",\n\t\"font/ttf\": \"ttf\",\n\t\"font/otf\": \"otf\"\n};\n\n//#endregion\n//#region upstream/engine/lib/variables/processors/json.ts\nconst jsonProcessor = (_property, value) => {\n\tif (isNil(value)) return value;\n\ttry {\n\t\tif (typeof value === \"object\") return value;\n\t\treturn JSON.parse(value);\n\t} catch (error) {\n\t\tconsole.error(error);\n\t\treturn;\n\t}\n};\n\n//#endregion\n//#region upstream/engine/lib/variables/processors/multi-select.ts\nconst multiSelectProcessor = (_property, value) => {\n\tif (isNil(value) || Array.isArray(value)) return value;\n\tif (typeof value === \"string\" && value.trim().length === 0) return;\n\tconst parsed = parseToJsonIfPossible(value);\n\treturn Array.isArray(parsed) ? parsed : [value];\n};\n\n//#endregion\n//#region upstream/engine/lib/variables/processors/number.ts\nconst numberProcessor = (_property, value) => {\n\tif (isNil(value)) return value;\n\tif (value === \"\") return;\n\treturn Number(value);\n};\n\n//#endregion\n//#region upstream/engine/lib/variables/processors/object.ts\nconst objectProcessor = (_property, value) => {\n\tif (isNil(value)) return value;\n\tif (typeof value === \"string\") try {\n\t\treturn JSON.parse(value);\n\t} catch (e) {\n\t\treturn;\n\t}\n\tif (typeof value === \"object\" && !Array.isArray(value)) return value;\n};\n\n//#endregion\n//#region upstream/engine/lib/variables/processors/text.ts\nconst textProcessor = (property, value) => {\n\tif (isNil(value)) return value;\n\tif (typeof value === \"object\") return JSON.stringify(value);\n\tconst result = value.toString();\n\tif (result.length === 0 && !property.required) return;\n\treturn result;\n};\n\n//#endregion\n//#region upstream/engine/lib/variables/processors/index.ts\nconst processors = {\n\tJSON: jsonProcessor,\n\tOBJECT: objectProcessor,\n\tNUMBER: numberProcessor,\n\tLONG_TEXT: textProcessor,\n\tSHORT_TEXT: textProcessor,\n\tSECRET_TEXT: textProcessor,\n\tDATE_TIME: dateTimeProcessor,\n\tFILE: fileProcessor,\n\tMULTI_SELECT_DROPDOWN: multiSelectProcessor,\n\tSTATIC_MULTI_SELECT_DROPDOWN: multiSelectProcessor,\n\tCHECKBOX: checkboxProcessor\n};\n\n//#endregion\n//#region upstream/engine/lib/variables/props-processor.ts\nconst propsProcessor = { applyProcessorsAndValidators: async (resolvedInput, props, auth, requireAuth, propertySettings) => {\n\tlet dynamaicPropertiesSchema = void 0;\n\tif (Object.keys(propertySettings).length > 0) dynamaicPropertiesSchema = Object.fromEntries(Object.entries(propertySettings).map(([key, propertySetting]) => [key, propertySetting.schema]));\n\tconst processedInput = { ...resolvedInput };\n\tconst errors = {};\n\tconst authValue = resolvedInput[AUTHENTICATION_PROPERTY_NAME];\n\tif (authValue && requireAuth) {\n\t\tconst authPropsToProcess = getAuthPropsToProcess(authValue, auth);\n\t\tif (authPropsToProcess) {\n\t\t\tconst { processedInput: authProcessedInput, errors: authErrors } = await propsProcessor.applyProcessorsAndValidators(resolvedInput[AUTHENTICATION_PROPERTY_NAME], authPropsToProcess, void 0, false, {});\n\t\t\tprocessedInput[AUTHENTICATION_PROPERTY_NAME] = authProcessedInput;\n\t\t\tif (Object.keys(authErrors).length > 0) errors[AUTHENTICATION_PROPERTY_NAME] = authErrors;\n\t\t}\n\t}\n\tfor (const [key, value] of Object.entries(resolvedInput)) {\n\t\tconst property = props[key];\n\t\tif (isNil(property)) continue;\n\t\tif (property.type === \"DYNAMIC\") {\n\t\t\tconst valueWithOriginalKeys = dynamicPropKeys.unescapeInputKeys(value);\n\t\t\tprocessedInput[key] = valueWithOriginalKeys;\n\t\t\tif (!isNil(dynamaicPropertiesSchema?.[key])) {\n\t\t\t\tconst { processedInput: itemProcessedInput, errors: itemErrors } = await propsProcessor.applyProcessorsAndValidators(valueWithOriginalKeys, dynamicPropKeys.unescapePropsKeys(dynamaicPropertiesSchema[key]), void 0, false, {});\n\t\t\t\tprocessedInput[key] = itemProcessedInput;\n\t\t\t\tif (Object.keys(itemErrors).length > 0) errors[key] = itemErrors;\n\t\t\t}\n\t\t}\n\t\tif (property.type === \"ARRAY\" && property.properties) {\n\t\t\tconst arrayOfObjects = arrayZipperProcessor(property, value) ?? [];\n\t\t\tconst processedArray = [];\n\t\t\tconst processedErrors = [];\n\t\t\tfor (const item of arrayOfObjects) {\n\t\t\t\tconst { processedInput: itemProcessedInput, errors: itemErrors } = await propsProcessor.applyProcessorsAndValidators(item, property.properties, void 0, false, {});\n\t\t\t\tprocessedArray.push(itemProcessedInput);\n\t\t\t\tprocessedErrors.push(itemErrors);\n\t\t\t}\n\t\t\tprocessedInput[key] = processedArray;\n\t\t\tif (processedErrors.some((error) => Object.keys(error).length > 0)) errors[key] = { properties: processedErrors };\n\t\t}\n\t\tif (!property.required && isNil(processedInput[key])) processedInput[key] = void 0;\n\t\tconst processor = processors[property.type];\n\t\tif (processor) processedInput[key] = await processor(property, processedInput[key]);\n\t\tif (!(key !== \"auth\" && property.type !== \"MARKDOWN\")) continue;\n\t}\n\tfor (const [key, value] of Object.entries(processedInput)) {\n\t\tconst property = props[key];\n\t\tif (isNil(property)) continue;\n\t\tconst validationErrors = validateProperty(property, value, resolvedInput[key]);\n\t\tif (validationErrors.length > 0) errors[key] = validationErrors;\n\t}\n\tif (Object.keys(errors).length > 0) destroyOpenStreams(processedInput);\n\treturn {\n\t\tprocessedInput,\n\t\terrors\n\t};\n} };\nfunction destroyOpenStreams(value) {\n\tif (isNil(value) || typeof value !== \"object\" || Buffer.isBuffer(value)) return;\n\tif (value instanceof Readable) {\n\t\tvalue.destroy();\n\t\treturn;\n\t}\n\tfor (const child of Object.values(value)) destroyOpenStreams(child);\n}\nconst validateProperty = (property, value, originalValue) => {\n\tif (property.type === \"JSON\") {\n\t\tif (!property.required && originalValue === \"\") return [];\n\t\tif (!isNil(originalValue) && isNil(value)) return [`Expected JSON, received: ${originalValue}`];\n\t\tif (!property.required && isNil(value)) return [];\n\t\tif (!isObject(value) && !Array.isArray(value)) return [`Expected JSON, received: ${originalValue}`];\n\t\treturn [];\n\t}\n\tif (!property.required && isNil(value)) return [];\n\tswitch (property.type) {\n\t\tcase \"SHORT_TEXT\":\n\t\tcase \"LONG_TEXT\":\n\t\tcase \"RICH_TEXT\": return typeof value === \"string\" ? [] : [`Expected string, received: ${originalValue}`];\n\t\tcase \"NUMBER\": return typeof value === \"number\" && !Number.isNaN(value) ? [] : [`Expected number, received: ${originalValue}`];\n\t\tcase \"CHECKBOX\": return typeof value === \"boolean\" ? [] : [`Expected boolean, received: ${originalValue}`];\n\t\tcase \"DATE_TIME\": return typeof value === \"string\" ? [] : [`Invalid datetime format. Expected ISO format (e.g. 2024-03-14T12:00:00.000Z), received: ${originalValue}`];\n\t\tcase \"DATE_RANGE\": return DateRangeValue.safeParse(value).success ? [] : [`Expected date range, received: ${originalValue}`];\n\t\tcase \"ARRAY\":\n\t\tcase \"MULTI_SELECT_DROPDOWN\":\n\t\tcase \"STATIC_MULTI_SELECT_DROPDOWN\": return Array.isArray(value) ? [] : [`Expected array, received: ${originalValue}`];\n\t\tcase \"OBJECT\": return isObject(value) ? [] : [`Expected object, received: ${originalValue}`];\n\t\tcase \"FILE\": return isObject(value) ? [] : [`Expected file url or base64 with mimeType, received: ${originalValue}`];\n\t\tdefault: return [];\n\t}\n};\nfunction getAuthPropsToProcess(authValue, auth) {\n\tif (isNil(auth)) return null;\n\tconst usedAuthProperty = getAuthPropertyForValue({\n\t\tauthValueType: authValue.type,\n\t\tpieceAuth: auth\n\t});\n\tif ((usedAuthProperty?.type === \"CUSTOM_AUTH\" || usedAuthProperty?.type === \"OAUTH2\" || usedAuthProperty?.type === \"OIDC\") && !isNil(usedAuthProperty?.props)) return usedAuthProperty.props;\n\treturn null;\n}\n\n//#endregion\nexport { arrayZipperProcessor, checkboxProcessor, dateTimeProcessor, dynamicPropKeys, fileProcessor, formatPieceError, jsonProcessor, multiSelectProcessor, numberProcessor, objectProcessor, processors, propsProcessor, ssrfIpClassifier, textProcessor, tryParseFriendlyPieceError, validateProperty };\n//# sourceMappingURL=host.js.map","// Credential redaction for anything that gets journaled or shown to a user.\n// Two independent passes, because each catches what the other misses.\n\n// Key-based catches a credential the run never knew about: a piece's own\n// hardcoded key, a token it fetched mid-step.\n\n// Value-based catches a secret the run did resolve, wherever a piece spliced\n// it — into a message, a URL, a header it composed itself.\n\nexport const REDACTED_PREFIX = \"[redacted:\";\nexport const SECRET_MARKER = \"[redacted:secret]\";\nexport const CIRCULAR_MARKER = \"[circular]\";\nexport const TRUNCATED_MARKER = \"[truncated]\";\n\n// Bounds for the hostile-error path only. Ordinary step output is data a user\n// asked for, so it is redacted whole rather than truncated.\nconst ERROR_MAX_DEPTH = 8;\nconst ERROR_MAX_NODES = 1000;\n\n// Deep enough never to be reached by real data, shallow enough that the\n// recursive walk cannot overflow the stack on a self-nesting object.\nconst STACK_GUARD_DEPTH = 200;\n\n// Exact names, matched after stripping separators and case: \"X-Api-Key\",\n// \"x_api_key\" and \"apiKey\" are one name.\nconst SENSITIVE_NAMES = new Set([\n \"auth\",\n \"authorization\",\n \"proxyauthorization\",\n \"wwwauthenticate\",\n \"authtoken\",\n \"xauthtoken\",\n \"apikey\",\n \"xapikey\",\n \"apisecret\",\n \"bearer\",\n \"cookie\",\n \"setcookie\",\n \"credential\",\n \"credentials\",\n \"password\",\n \"passwd\",\n \"passphrase\",\n \"pwd\",\n \"privatekey\",\n \"secret\",\n \"secrettext\",\n \"sessionid\",\n \"signature\",\n \"token\",\n]);\n\n// A name ending in one of these is sensitive whatever prefixes it, which is\n// what catches githubToken, client_secret and the rest of the long tail.\nconst SENSITIVE_SUFFIXES = [\n \"apikey\",\n \"credentials\",\n \"password\",\n \"privatekey\",\n \"secret\",\n \"token\",\n];\n\n// Header and field names worth redacting inside a free-form string, where\n// there is no key to walk.\n\n// Deliberately a fixed list: a loose pattern over prose eats more of the\n// message than it saves.\n\n// Signature is the one alternative that carries its own affixes, because a\n// webhook MAC header wraps the word: x-hub-signature-256.\n\n// The affixed form is anchored on the literal \"signature\", with the prefix\n// matched by a lookbehind placed after it. A leading prefix pattern\n// ((?:[a-z0-9]+[-_])*signature) retries from every segment of a long\n// hyphen-separated run that never ends in \"signature\", which is quadratic:\n// whole seconds over a few hundred kilobytes of journaled text. The\n// lookbehind runs once per occurrence of the literal instead, and captures\n// the prefix so the marker still names the whole header.\nconst TEXT_FIELD = new RegExp(\n String.raw`(\\b(?:authorization|proxy-authorization|api[-_]?key|x-api-key|access[-_]?token|refresh[-_]?token|client[-_]?secret|set-cookie|cookie|password|secret|token)|signature(?<=\\b((?:[a-z0-9]+[-_])*)signature)(?:[-_][a-z0-9]+)*)\\b([\"']?)(\\s*[:=]\\s*)([\"']?)((?:(?:Bearer|Basic|Token)\\s+)?[^\\s\",;&)}]+)\\5`,\n \"gi\",\n);\n\nconst AUTH_SCHEME = /\\b(Bearer|Basic|Token)\\s+([A-Za-z0-9._~+/=-]{8,})/g;\n\nconst QUERY_PARAM = /([?&])([A-Za-z0-9_.%[\\]-]+)=([^&\\s\"'<>]+)/g;\n\n// The password half of a URL's userinfo, which no header or query pattern\n// reaches: https://user:s3cret@host/api.\n\n// Anchored on \"://\" with the scheme checked by the lookbehind behind it: a\n// leading scheme pattern ([a-z][a-z0-9+.-]*) rescans a long unbroken\n// alphanumeric run from every offset, which is quadratic — tens of seconds\n// over a 256 KiB run. The scheme is not consumed, and not rewritten either\n// way; only the password half is replaced.\nconst URL_USERINFO =\n /:\\/\\/(?<=[a-z][a-z0-9+.-]*:\\/\\/)([^/\\s:@]+):([^/\\s@]+)@/gi;\n\nexport function normalizeName(name: string): string {\n return name.toLowerCase().replace(/[^a-z0-9]/g, \"\");\n}\n\nexport function isSensitiveName(name: string): boolean {\n const normalized = normalizeName(name);\n if (!normalized) return false;\n if (SENSITIVE_NAMES.has(normalized)) return true;\n // Anywhere in the name, because a webhook MAC header carries its algorithm\n // after it: x-hub-signature-256.\n if (normalized.includes(\"signature\")) return true;\n return SENSITIVE_SUFFIXES.some(\n (suffix) =>\n normalized.length > suffix.length && normalized.endsWith(suffix),\n );\n}\n\nfunction marker(name: string): string {\n return `[redacted:${name.toLowerCase()}]`;\n}\n\nfunction shannonEntropy(text: string): number {\n const counts = new Map<string, number>();\n for (const char of text) counts.set(char, (counts.get(char) ?? 0) + 1);\n let entropy = 0;\n for (const count of counts.values()) {\n const p = count / text.length;\n entropy -= p * Math.log2(p);\n }\n return entropy;\n}\n\n// The bar a *guessed* secret must clear before its value is matched anywhere.\n\n// A short or repetitive guess (\"admin\", \"8080\", \"aaaaaaaa\") would hit unrelated\n// text and leave an error nobody can read; the key-based pass still covers it.\nconst MIN_VALUE_LENGTH = 8;\nconst MIN_DISTINCT_CHARS = 5;\nconst MIN_ENTROPY_BITS = 2;\n\n// A value the host hands over is a declaration, not a guess, so \"hunter2\" is\n// redacted. Only a value too short to be a credential is refused.\nconst MIN_DECLARED_LENGTH = 4;\n\nexport function isRedactableValue(value: unknown): value is string {\n if (typeof value !== \"string\") return false;\n if (value.length < MIN_VALUE_LENGTH) return false;\n if (new Set(value).size < MIN_DISTINCT_CHARS) return false;\n return shannonEntropy(value) >= MIN_ENTROPY_BITS;\n}\n\nexport function isDeclaredValue(value: unknown): value is string {\n return typeof value === \"string\" && value.length >= MIN_DECLARED_LENGTH;\n}\n\n// The AppConnectionValue discriminator, and anything shaped like an endpoint.\n\n// Both are configuration rather than credentials, and a URL is usually the\n// most useful thing left in a failed request's error.\nconst STRUCTURAL_NAMES = new Set([\"type\", \"authtype\"]);\nconst URL_LIKE = /^[a-z][a-z0-9+.-]*:\\/\\//i;\n\n// Every credential-shaped string leaf of a resolved connection. The fallback\n// for a host resolver that cannot say which of its values are secret.\nexport function collectSecretValues(\n value: unknown,\n into: Set<string> = new Set(),\n depth = 0,\n): Set<string> {\n if (depth > ERROR_MAX_DEPTH) return into;\n if (isRedactableValue(value)) {\n if (!URL_LIKE.test(value)) into.add(value);\n return into;\n }\n if (Array.isArray(value)) {\n for (const entry of value) collectSecretValues(entry, into, depth + 1);\n return into;\n }\n if (typeof value === \"object\" && value !== null) {\n for (const [key, entry] of Object.entries(value)) {\n if (STRUCTURAL_NAMES.has(normalizeName(key))) continue;\n collectSecretValues(entry, into, depth + 1);\n }\n }\n return into;\n}\n\nexport interface RedactOptions {\n // Concrete secret values resolved for this step; each occurrence is replaced.\n values?: Iterable<string>;\n maxDepth?: number;\n maxNodes?: number;\n}\n\n// A host-side handle from a thrown error to the secrets its step ran with, so\n// a catch far from the connection can still redact by value.\nconst thrownSecrets = new WeakMap<object, string[]>();\n\nexport function rememberSecrets<T>(error: T, values: string[]): T {\n if (typeof error === \"object\" && error !== null && values.length > 0) {\n thrownSecrets.set(error, values);\n }\n return error;\n}\n\nexport function secretsFor(error: unknown): string[] {\n if (typeof error !== \"object\" || error === null) return [];\n return thrownSecrets.get(error) ?? [];\n}\n\ninterface Pass {\n values: string[];\n maxDepth: number;\n maxNodes: number;\n nodes: number;\n}\n\n// Longest first, so a secret that contains another is replaced whole rather\n// than leaving its tail behind.\nfunction preparePass(options: RedactOptions | undefined): Pass {\n const values = [...(options?.values ?? [])]\n .filter(isDeclaredValue)\n .sort((a, b) => b.length - a.length);\n return {\n values,\n maxDepth: options?.maxDepth ?? STACK_GUARD_DEPTH,\n maxNodes: options?.maxNodes ?? Number.POSITIVE_INFINITY,\n nodes: 0,\n };\n}\n\nfunction safeDecode(name: string): string {\n try {\n return decodeURIComponent(name);\n } catch {\n return name;\n }\n}\n\nfunction replaceValues(text: string, values: string[]): string {\n let result = text;\n for (const value of values) {\n if (result.includes(value)) {\n result = result.split(value).join(SECRET_MARKER);\n }\n const encoded = encodeURIComponent(value);\n if (encoded !== value && result.includes(encoded)) {\n result = result.split(encoded).join(SECRET_MARKER);\n }\n }\n return result;\n}\n\nfunction redactText(text: string, pass: Pass): string {\n let result = replaceValues(text, pass.values);\n result = result.replace(\n URL_USERINFO,\n (_match, user: string) => `://${user}:${marker(\"password\")}@`,\n );\n result = result.replace(QUERY_PARAM, (match, sep: string, name: string) =>\n isSensitiveName(safeDecode(name)) ? `${sep}${name}=${marker(name)}` : match,\n );\n result = result.replace(\n AUTH_SCHEME,\n (_match, scheme: string) => `${scheme} ${marker(scheme)}`,\n );\n\n // Skipping a value that is already a marker keeps this pass from re-matching\n // what the query pass just wrote and swallowing the rest of the string.\n\n // signaturePrefix is the lookbehind's capture: the affixes before\n // \"signature\" sit outside the match, so they are stitched back onto the\n // name only for the marker — the text keeps them where they were.\n return result.replace(\n TEXT_FIELD,\n (\n match,\n name: string,\n signaturePrefix: string | undefined,\n nameQuote: string,\n sep: string,\n quote: string,\n value: string,\n ) =>\n value.startsWith(REDACTED_PREFIX)\n ? match\n : `${name}${nameQuote}${sep}${quote}${marker(`${signaturePrefix ?? \"\"}${name}`)}${quote}`,\n );\n}\n\n// A document header's or reference's operation counts per scope. Scope names\n// such as \"auth\" are not credentials, and the counts are numbers.\nfunction isScopeRevision(\n parent: Record<string, unknown>,\n key: string,\n entry: unknown,\n): boolean {\n return (\n key === \"revision\" &&\n typeof parent.documentType === \"string\" &&\n typeof entry === \"object\" &&\n entry !== null &&\n !Array.isArray(entry) &&\n Object.values(entry).every(\n (count) => typeof count === \"number\" && Number.isFinite(count),\n )\n );\n}\n\nfunction walk(\n value: unknown,\n pass: Pass,\n depth: number,\n seen: Set<object>,\n): unknown {\n if (typeof value === \"string\") return redactText(value, pass);\n if (typeof value !== \"object\" || value === null) return value;\n if (seen.has(value)) return CIRCULAR_MARKER;\n if (depth >= pass.maxDepth) return TRUNCATED_MARKER;\n if (pass.nodes >= pass.maxNodes) return TRUNCATED_MARKER;\n pass.nodes += 1;\n\n // Tracked per path, not globally: the same object appearing twice in a tree\n // is not a cycle, and calling it one would drop data a user needs.\n seen.add(value);\n try {\n if (Array.isArray(value)) {\n return value.map((entry) => walk(entry, pass, depth + 1, seen));\n }\n const result: Record<string, unknown> = {};\n const record = value as Record<string, unknown>;\n for (const [key, entry] of Object.entries(record)) {\n result[key] = isSensitiveName(key)\n ? marker(key)\n : isScopeRevision(record, key, entry)\n ? { ...(entry as Record<string, number>) }\n : walk(entry, pass, depth + 1, seen);\n }\n return result;\n } finally {\n seen.delete(value);\n }\n}\n\n// Redacts credentials from an arbitrary value: sensitive keys by name, known\n// secret values wherever they appear, sensitive URL query parameters.\n\n// Cycles are collapsed; nothing else is dropped, because this also runs over\n// step output a user asked to see.\nexport function redact(value: unknown, options?: RedactOptions): unknown {\n return walk(value, preparePass(options), 0, new Set());\n}\n\n// The same pass for an error object, which is attacker-shaped: depth and node\n// count are capped so a hostile error cannot make redaction expensive.\nexport function redactError(value: unknown, options?: RedactOptions): unknown {\n return redact(value, {\n maxDepth: ERROR_MAX_DEPTH,\n maxNodes: ERROR_MAX_NODES,\n ...options,\n });\n}\n\n// True when a value carries a marker this module wrote. Rerun uses it to\n// refuse a journaled output it cannot faithfully replay.\n\n// TRUNCATED_MARKER is matched whole, not as a substring: walk() only ever\n// writes it in place of an entire capped node, so prose that merely mentions\n// the word keeps replaying.\nexport function containsRedactedMarker(value: unknown, depth = 0): boolean {\n if (typeof value === \"string\") {\n return value.includes(REDACTED_PREFIX) || value === TRUNCATED_MARKER;\n }\n if (typeof value !== \"object\" || value === null) return false;\n if (depth >= STACK_GUARD_DEPTH) return false;\n return Object.values(value).some((entry) =>\n containsRedactedMarker(entry, depth + 1),\n );\n}\n\n// The string-only form, for a message that is already flat text.\nexport function redactMessage(text: string, options?: RedactOptions): string {\n return redactText(text, preparePass(options));\n}\n","// Context handed to a piece's auth.validate and auth.getConnectionIdentifier:\n// `{ auth, server }`, with auth as the flat property value.\nimport { throwingStub, withTouchTracking } from \"./stubs.js\";\nimport type { AuthValidationServerContext } from \"@powerhousedao/pieces-framework\";\n\nexport interface CheckConnectionContextOptions {\n auth?: unknown;\n // apiUrl / publicUrl when the host serves them; mintOidcToken always throws,\n // since no reactor mints tokens for a piece's connection check.\n server?: Omit<AuthValidationServerContext, \"mintOidcToken\">;\n onTouch?: (member: string) => void;\n}\n\nexport interface BuiltApCheckConnectionContext {\n auth: unknown;\n server: AuthValidationServerContext;\n}\n\nexport interface CheckConnectionContextHandle {\n context: BuiltApCheckConnectionContext;\n // Top-level members the check read; `UNDOCUMENTED:<name>` marks unknown reads.\n touched: ReadonlySet<string>;\n}\n\nexport function buildCheckConnectionContext(\n options: CheckConnectionContextOptions = {},\n): CheckConnectionContextHandle {\n const touched = new Set<string>();\n const base: Record<string, unknown> = {\n auth: options.auth,\n server: options.server\n ? {\n ...options.server,\n mintOidcToken: throwingStub(\"server.mintOidcToken\"),\n }\n : throwingStub(\"server\"),\n };\n const context = withTouchTracking(base, touched, options.onTouch);\n return {\n context: context as unknown as BuiltApCheckConnectionContext,\n touched,\n };\n}\n","// One file-size ceiling for both directions. Inbound hydration (a FILE prop\n// that arrives as a URL, a data URI or an attachment ref) and outbound\n// ctx.files.write share it, because a piece that can emit a file the next step\n// cannot ingest is worse than a piece that refuses both.\nimport { Transform, type TransformCallback } from \"node:stream\";\nimport { DEFAULT_HOST_CALL_TIMEOUT_MS } from \"../worker/host-call.js\";\n\nexport const DEFAULT_MAX_FILE_BYTES = 8 * 1024 * 1024;\n\n// What the environment asks for, or undefined when it asks for nothing usable.\n// Read per call: a host may set it after this module is loaded.\nexport function configuredMaxFileBytes(): number | undefined {\n const raw = process.env.PH_WORKFLOWS_PIECE_MAX_FILE_BYTES;\n if (raw === undefined) return undefined;\n const parsed = Number(raw);\n return Number.isFinite(parsed) && parsed > 0 ? Math.floor(parsed) : undefined;\n}\n\n// The worker child is forked without an environment, so its limit arrives on\n// the wire instead. Requests are serialized per worker: one value at a time.\nlet fromWire: number | undefined;\n\nexport function setMaxFileBytes(limit: number | undefined): void {\n fromWire = limit;\n}\n\nexport function maxFileBytes(): number {\n return fromWire ?? configuredMaxFileBytes() ?? DEFAULT_MAX_FILE_BYTES;\n}\n\n/** How long a piece's call of its host may take before the step gives up on\n * it. Read per call, like the file ceiling, and travelling on the wire for the\n * same reason: the child is forked with no environment. */\nexport const HOST_CALL_TIMEOUT_ENV = \"PH_WORKFLOWS_HOST_CALL_TIMEOUT_MS\";\n\n/**\n * The host-call cap for one step.\n *\n * The 10s default outran reality for a reactor dispatch under load and the\n * step was reported FAILED for a write that had been committed (backlog item\n * 6). So it is configurable, and it is never shorter than the step's OWN\n * timeout: a step the author gave two minutes should not have its host calls\n * cut off after ten seconds. The child still clips each call to end before\n * the step's kill deadline (`worker/host-call.ts`).\n */\nexport function hostCallTimeoutForStep(\n stepTimeoutMs: number | undefined,\n env: Record<string, string | undefined> = process.env,\n): number {\n const configured = Number(env[HOST_CALL_TIMEOUT_ENV]);\n const base =\n Number.isFinite(configured) && configured > 0\n ? Math.floor(configured)\n : DEFAULT_HOST_CALL_TIMEOUT_MS;\n return Math.max(base, stepTimeoutMs ?? 0);\n}\n\nexport class FileTooLargeError extends Error {\n readonly size: number;\n readonly limit: number;\n\n constructor(size: number, limit: number = maxFileBytes()) {\n super(\n `File of ${size} bytes exceeds the ${limit} byte limit ` +\n `(raise PH_WORKFLOWS_PIECE_MAX_FILE_BYTES to allow more)`,\n );\n this.name = \"FileTooLargeError\";\n this.size = size;\n this.limit = limit;\n }\n}\n\nexport function assertWithinLimit(size: number): void {\n const limit = maxFileBytes();\n if (size > limit) throw new FileTooLargeError(size, limit);\n}\n\n// Counts bytes as they pass and fails the stream past the cap, so an\n// undeclared or understated body never lands whole in memory or on disk.\nexport function byteCap(limit: number = maxFileBytes()): Transform {\n let seen = 0;\n return new Transform({\n transform(chunk: Buffer, _encoding, done: TransformCallback) {\n seen += chunk.byteLength;\n if (seen > limit) done(new FileTooLargeError(seen, limit));\n else done(null, chunk);\n },\n });\n}\n","// Two FilesService implementations plus the staged-file contract that carries\n// bytes back to the host.\n//\n// `ctx.files.write()` is called *during* action.run(), inside the forked\n// worker, and the worker protocol has no worker-to-host request channel. So\n// this follows the pattern storeState already establishes — push in, return\n// whole — using the one thing a fork shares with its parent: the filesystem.\n// The worker writes bytes to a staging directory and returns a provisional\n// `apfile://<token>`; the host ingests each staged file after the step returns\n// and rewrites the tokens in the output before journalling it.\nimport { randomUUID } from \"node:crypto\";\nimport { createWriteStream } from \"node:fs\";\nimport { mkdir, rm, stat, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { Readable } from \"node:stream\";\nimport { pipeline } from \"node:stream/promises\";\nimport {\n assertWithinLimit,\n byteCap,\n FileTooLargeError,\n maxFileBytes,\n} from \"./limits.js\";\n\nexport { FileTooLargeError, maxFileBytes };\n\nexport const APFILE_SCHEME = \"apfile://\";\n\n// One file the piece wrote, as it crosses back on ResultResponse.files.\nexport interface StagedFile {\n // The provisional ref handed to the piece; the host rewrites it in place.\n token: string;\n path: string;\n fileName: string;\n size: number;\n contentType?: string;\n}\n\n// What a piece may hand ctx.files.write: upstream takes a Buffer or a Readable.\nexport type ApFileData = Buffer | Uint8Array | Readable;\n\n// The framework's FilesService for both actions and triggers, with fileName\n// optional.\nexport interface ApFilesService {\n write(file: { fileName?: string; data: ApFileData }): Promise<string>;\n}\n\n// A Readable drained into memory under the cap, for the inline fallback.\nasync function drain(data: Readable): Promise<Buffer> {\n const chunks: Buffer[] = [];\n for await (const chunk of data.pipe(byteCap())) chunks.push(chunk as Buffer);\n return Buffer.concat(chunks);\n}\n\n// Default for both actions and triggers when the host injects nothing: inline\n// the bytes as a data URI so the payload stays self-contained. Bounded by the\n// shared cap, since a data URI lands in the run journal.\nexport class DataUriFilesService implements ApFilesService {\n async write(file: { fileName?: string; data: ApFileData }): Promise<string> {\n const data =\n file.data instanceof Readable\n ? await drain(file.data)\n : Buffer.isBuffer(file.data)\n ? file.data\n : Buffer.from(file.data);\n if (data.byteLength > maxFileBytes()) {\n throw new FileTooLargeError(data.byteLength);\n }\n return `data:application/octet-stream;base64,${data.toString(\"base64\")}`;\n }\n}\n\nconst EXTENSION_TYPES: Record<string, string> = {\n pdf: \"application/pdf\",\n png: \"image/png\",\n jpg: \"image/jpeg\",\n jpeg: \"image/jpeg\",\n webp: \"image/webp\",\n tif: \"image/tiff\",\n tiff: \"image/tiff\",\n txt: \"text/plain\",\n json: \"application/json\",\n csv: \"text/csv\",\n};\n\nfunction contentTypeFor(fileName: string): string | undefined {\n const extension = fileName.split(\".\").pop()?.toLowerCase();\n return extension ? EXTENSION_TYPES[extension] : undefined;\n}\n\n// Worker-side service: writes into `<stagingDir>/<uuid>` and remembers what it\n// wrote so the worker can report it on the response.\nexport class StagedFilesService implements ApFilesService {\n private readonly files: StagedFile[] = [];\n\n constructor(private readonly stagingDir: string) {}\n\n staged(): StagedFile[] {\n return [...this.files];\n }\n\n async write(file: { fileName?: string; data: ApFileData }): Promise<string> {\n const token = randomUUID();\n const fileName =\n file.fileName && file.fileName !== \"\" ? file.fileName : token;\n const target = path.join(this.stagingDir, token);\n let size: number;\n if (file.data instanceof Readable) {\n // Capped while it streams to disk: a piece cannot fill the disk with a\n // file the host would refuse anyway.\n await mkdir(this.stagingDir, { recursive: true });\n try {\n await pipeline(file.data, byteCap(), createWriteStream(target));\n } catch (error) {\n await rm(target, { force: true });\n throw error;\n }\n size = (await stat(target)).size;\n } else {\n const data = Buffer.isBuffer(file.data)\n ? file.data\n : Buffer.from(file.data);\n // Checked before anything touches the disk, for the same reason.\n assertWithinLimit(data.byteLength);\n await mkdir(this.stagingDir, { recursive: true });\n await writeFile(target, data);\n size = data.byteLength;\n }\n this.files.push({\n token: `${APFILE_SCHEME}${token}`,\n path: target,\n fileName,\n size,\n contentType: contentTypeFor(fileName),\n });\n return `${APFILE_SCHEME}${token}`;\n }\n}\n\n// Replaces every provisional token in a step output with the real ref the host\n// got back from its attachment store. Walks the whole value: a piece may nest\n// the ref anywhere, and a plain string replace over the serialized JSON would\n// corrupt any base64 that happens to contain the token.\nexport function rewriteFileRefs(\n value: unknown,\n refs: Map<string, string>,\n): unknown {\n if (refs.size === 0) return value;\n if (typeof value === \"string\") return refs.get(value) ?? value;\n if (Array.isArray(value)) {\n return value.map((entry) => rewriteFileRefs(entry, refs));\n }\n if (typeof value === \"object\" && value !== null) {\n const out: Record<string, unknown> = {};\n for (const [key, entry] of Object.entries(value)) {\n out[key] = rewriteFileRefs(entry, refs);\n }\n return out;\n }\n return value;\n}\n","// Run-time coercion of stored config values into the shapes pieces expect: the\n// engine's own property processors, with our file hydration in front of theirs.\nimport type { PieceProperty } from \"@powerhousedao/pieces-framework\";\nimport { createReadStream } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { Readable } from \"node:stream\";\nimport type { ReadableStream as WebReadableStream } from \"node:stream/web\";\nimport {\n arrayZipperProcessor,\n processors,\n validateProperty,\n type ProcessorFn,\n} from \"@powerhousedao/pieces-framework/host\";\nimport type { ApProperty } from \"../types.js\";\nimport {\n assertWithinLimit,\n byteCap,\n DEFAULT_MAX_FILE_BYTES,\n maxFileBytes,\n} from \"./limits.js\";\n\n// Framework ApFile (filename, data, extension, base64) as a plain object so\n// it survives IPC and structured cloning.\nexport interface ApFileValue {\n filename: string;\n extension?: string;\n base64: string;\n data: Buffer;\n}\n\n// Framework ApStreamingFile: what a `streaming: true` FILE prop receives.\nexport interface ApStreamingFileValue {\n filename: string;\n extension?: string;\n size?: number;\n body: Readable;\n // Set only when the bytes are a staged file on local disk.\n path?: string;\n}\n\n// Opens the file on first read: a piece that reads `path` never opens a descriptor.\nfunction lazyFileStream(filePath: string): Readable {\n return Readable.from(\n (async function* () {\n yield* createReadStream(filePath);\n })(),\n { objectMode: false },\n );\n}\n\n// A staged attachment on disk, for a streaming FILE prop.\nexport interface OpenedFile {\n path: string;\n size: number;\n filename?: string;\n contentType?: string;\n}\n\nexport interface FetchedFile {\n data: Buffer;\n filename?: string;\n contentType?: string;\n}\n\nexport interface NormalizeOptions {\n // Resolves a URL-valued FILE prop; defaults to fetch() with a size cap.\n fetchFile?: (url: string) => Promise<FetchedFile>;\n // Resolves a reference-valued FILE prop (attachment:// or apfile://). The\n // worker resolves these from files the host staged on disk, so the bytes\n // never cross IPC.\n resolveRef?: (ref: string) => Promise<FetchedFile>;\n // The staged file itself, for a streaming FILE prop.\n openRef?: (ref: string) => Promise<OpenedFile>;\n}\n\n// Re-exported for compatibility; the ceiling itself lives in limits.ts so the\n// inbound and outbound paths cannot drift apart.\nexport const MAX_FILE_BYTES = DEFAULT_MAX_FILE_BYTES;\nconst FETCH_TIMEOUT_MS = 30_000;\n\n// A FILE prop whose value is a reference the host has to resolve.\nconst FILE_REF = /^(?:attachment|apfile):\\/\\//i;\n\nexport class FileFetchError extends Error {\n constructor(url: string, reason: string) {\n super(`Could not fetch FILE prop \"${url}\": ${reason}`);\n this.name = \"FileFetchError\";\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\nconst DATA_URI = /^data:([^;,]*)((?:;[^;,]*)*),([\\s\\S]*)$/;\n\nfunction extensionOf(filename: string): string | undefined {\n const dot = filename.lastIndexOf(\".\");\n return dot > 0 && dot < filename.length - 1\n ? filename.slice(dot + 1)\n : undefined;\n}\n\nconst MIME_EXTENSIONS: Record<string, string> = {\n \"image/png\": \"png\",\n \"image/jpeg\": \"jpg\",\n \"image/gif\": \"gif\",\n \"image/webp\": \"webp\",\n \"image/svg+xml\": \"svg\",\n \"application/pdf\": \"pdf\",\n \"application/json\": \"json\",\n \"text/plain\": \"txt\",\n \"text/csv\": \"csv\",\n};\n\n// base64 is computed on first read and kept, like upstream's ApFile getter:\n// a piece that only reads `data` never pays for a second copy of the file.\nfunction fileValue(\n filename: string,\n extension: string | undefined,\n data: Buffer,\n base64?: string,\n): ApFileValue {\n const file = { filename, ...(extension ? { extension } : {}), data };\n let encoded = base64;\n Object.defineProperty(file, \"base64\", {\n enumerable: true,\n configurable: true,\n get: () => (encoded ??= data.toString(\"base64\")),\n set: (value: string) => {\n encoded = value;\n },\n });\n return file as ApFileValue;\n}\n\nfunction fileName(\n filename: string | undefined,\n contentType: string | undefined,\n): { name: string; extension: string | undefined } {\n const mime = contentType?.split(\";\")[0].trim().toLowerCase();\n const mimeExtension = mime ? MIME_EXTENSIONS[mime] : undefined;\n const name =\n filename && filename !== \"\"\n ? filename\n : `file${mimeExtension ? `.${mimeExtension}` : \"\"}`;\n return { name, extension: extensionOf(name) ?? mimeExtension };\n}\n\nfunction toFileValue(\n data: Buffer,\n filename: string | undefined,\n contentType: string | undefined,\n): ApFileValue {\n const { name, extension } = fileName(filename, contentType);\n return fileValue(name, extension, data);\n}\n\nfunction filenameFromDisposition(header: string | null): string | undefined {\n if (!header) return undefined;\n const utf8 = /filename\\*=(?:UTF-8'')?([^;]+)/i.exec(header);\n if (utf8) {\n try {\n return decodeURIComponent(utf8[1].trim().replace(/^\"|\"$/g, \"\"));\n } catch {\n // fall through to the plain form\n }\n }\n const plain = /filename=\"?([^\";]+)\"?/i.exec(header);\n return plain ? plain[1].trim() : undefined;\n}\n\nasync function openUrl(url: string): Promise<{\n response: Response;\n declared: number | undefined;\n filename: string | undefined;\n}> {\n let response: Response;\n try {\n response = await fetch(url, {\n signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),\n });\n } catch (error) {\n throw new FileFetchError(\n url,\n error instanceof Error ? error.message : String(error),\n );\n }\n if (!response.ok) throw new FileFetchError(url, `HTTP ${response.status}`);\n const limit = maxFileBytes();\n // Content-Length counts the encoded body; only an identity body has the\n // file's own size.\n const header = response.headers.get(\"content-length\");\n const declared =\n header !== null && !response.headers.get(\"content-encoding\")\n ? Number(header)\n : undefined;\n if (declared !== undefined && Number.isFinite(declared) && declared > limit) {\n await response.body?.cancel().catch(() => undefined);\n throw new FileFetchError(url, `${declared} bytes exceeds ${limit}`);\n }\n let filename = filenameFromDisposition(\n response.headers.get(\"content-disposition\"),\n );\n if (!filename) {\n const segment = new URL(url).pathname.split(\"/\").filter(Boolean).pop();\n if (segment) filename = decodeURIComponent(segment);\n }\n return {\n response,\n declared:\n declared !== undefined && Number.isFinite(declared)\n ? declared\n : undefined,\n filename,\n };\n}\n\nfunction cappedBody(response: Response): Readable {\n const body = response.body\n ? Readable.fromWeb(response.body as WebReadableStream<Uint8Array>)\n : Readable.from([]);\n const cap = byteCap();\n body.on(\"error\", (error) => cap.destroy(error));\n return body.pipe(cap);\n}\n\nasync function defaultFetchFile(url: string): Promise<FetchedFile> {\n const { response, filename } = await openUrl(url);\n const chunks: Buffer[] = [];\n try {\n for await (const chunk of cappedBody(response))\n chunks.push(chunk as Buffer);\n } catch (error) {\n throw new FileFetchError(\n url,\n error instanceof Error ? error.message : String(error),\n );\n }\n return {\n data: Buffer.concat(chunks),\n filename,\n contentType: response.headers.get(\"content-type\") ?? undefined,\n };\n}\n\nconst FILE_KEYS = new Set([\"filename\", \"extension\", \"base64\", \"data\"]);\n\nfunction isFileShaped(value: unknown): value is ApFileValue {\n return (\n isRecord(value) &&\n typeof value.filename === \"string\" &&\n (typeof value.base64 === \"string\" || Buffer.isBuffer(value.data))\n );\n}\n\n// URL or data URI → ApFile shape; already-shaped objects are completed\n// (data/base64 derived from each other); anything else passes through.\nexport async function toApFile(\n value: unknown,\n options: NormalizeOptions = {},\n): Promise<unknown> {\n if (isFileShaped(value)) {\n const data = Buffer.isBuffer(value.data)\n ? value.data\n : Buffer.from(value.base64, \"base64\");\n // The cap applies to every branch, not just the fetched one: an oversized\n // data URI or file-shaped object would otherwise slip past it.\n assertWithinLimit(data.byteLength);\n const extension = value.extension ?? extensionOf(value.filename);\n const rest = Object.fromEntries(\n Object.entries(value).filter(([key]) => !FILE_KEYS.has(key)),\n );\n return Object.assign(\n fileValue(\n value.filename,\n extension,\n data,\n typeof value.base64 === \"string\" ? value.base64 : undefined,\n ),\n rest,\n );\n }\n if (typeof value !== \"string\") return value;\n const trimmed = value.trim();\n if (trimmed === \"\") return undefined;\n const dataUri = DATA_URI.exec(trimmed);\n if (dataUri) {\n const decoded = decodeDataUri(dataUri);\n return toFileValue(decoded.data, decoded.name, decoded.mime);\n }\n if (FILE_REF.test(trimmed)) {\n if (!options.resolveRef) {\n throw new FileFetchError(\n trimmed,\n \"no attachment resolver is available in this context\",\n );\n }\n const resolved = await options.resolveRef(trimmed);\n assertWithinLimit(resolved.data.byteLength);\n return toFileValue(resolved.data, resolved.filename, resolved.contentType);\n }\n if (/^https?:\\/\\//i.test(trimmed)) {\n const fetched = await (options.fetchFile ?? defaultFetchFile)(trimmed);\n return toFileValue(fetched.data, fetched.filename, fetched.contentType);\n }\n return value;\n}\n\nfunction decodeDataUri(match: RegExpExecArray): {\n data: Buffer;\n name: string | undefined;\n mime: string | undefined;\n} {\n const [, mime, params, payload] = match;\n const data = /;base64/i.test(params)\n ? Buffer.from(payload, \"base64\")\n : Buffer.from(decodeURIComponent(payload), \"utf8\");\n assertWithinLimit(data.byteLength);\n const nameParam = /;name=([^;]+)/i.exec(params)?.[1];\n return {\n data,\n name: nameParam ? decodeURIComponent(nameParam) : undefined,\n mime: mime || undefined,\n };\n}\n\nfunction streamingValue(\n name: string,\n extension: string | undefined,\n size: number | undefined,\n body: Readable,\n path?: string,\n): ApStreamingFileValue {\n return {\n filename: name,\n ...(extension ? { extension } : {}),\n ...(size !== undefined ? { size } : {}),\n body,\n ...(path ? { path } : {}),\n };\n}\n\n// Streaming FILE prop: the piece reads the body itself, so nothing is held in\n// memory. A staged reference streams from disk, a URL from the network.\nexport async function toApStreamingFile(\n value: unknown,\n options: NormalizeOptions = {},\n): Promise<unknown> {\n if (isRecord(value) && value.body instanceof Readable) return value;\n if (isFileShaped(value)) {\n const file = (await toApFile(value, options)) as ApFileValue;\n return streamingValue(\n file.filename,\n file.extension,\n file.data.byteLength,\n Readable.from([file.data]),\n );\n }\n if (typeof value !== \"string\") return value;\n const trimmed = value.trim();\n if (trimmed === \"\") return undefined;\n const dataUri = DATA_URI.exec(trimmed);\n if (dataUri) {\n const decoded = decodeDataUri(dataUri);\n const { name, extension } = fileName(decoded.name, decoded.mime);\n return streamingValue(\n name,\n extension,\n decoded.data.byteLength,\n Readable.from([decoded.data]),\n );\n }\n if (FILE_REF.test(trimmed)) {\n if (!options.openRef) {\n throw new FileFetchError(\n trimmed,\n \"no attachment resolver is available in this context\",\n );\n }\n const opened = await options.openRef(trimmed);\n assertWithinLimit(opened.size);\n const { name, extension } = fileName(opened.filename, opened.contentType);\n const filePath = resolve(opened.path);\n return streamingValue(\n name,\n extension,\n opened.size,\n lazyFileStream(filePath),\n filePath,\n );\n }\n if (/^https?:\\/\\//i.test(trimmed)) {\n const { response, declared, filename } = await openUrl(trimmed);\n const { name, extension } = fileName(\n filename,\n response.headers.get(\"content-type\") ?? undefined,\n );\n return streamingValue(name, extension, declared, cappedBody(response));\n }\n return value;\n}\n\n// ARRAY has no entry in the processor table: the engine zips an object of\n// parallel arrays into rows itself, then processes each row's own props.\nasync function normalizeArray(\n prop: ApProperty,\n value: unknown,\n options: NormalizeOptions,\n): Promise<unknown> {\n const fields = prop.properties;\n if (!fields) return value;\n const zipped: unknown = arrayZipperProcessor(prop as PieceProperty, value);\n if (!Array.isArray(zipped)) return value;\n return Promise.all(\n (zipped as unknown[]).map((item) =>\n isRecord(item) ? normalizePropsValue(fields, item, options) : item,\n ),\n );\n}\n\n// An ApFile is a class instance whose base64 is a prototype getter, and no\n// structured clone carries either; flatten it at the boundary (see ApFileValue).\nfunction plainFile(value: unknown): unknown {\n if (!isRecord(value) || typeof value.filename !== \"string\") return value;\n const { data } = value;\n if (!Buffer.isBuffer(data)) return value;\n const extension =\n typeof value.extension === \"string\"\n ? value.extension\n : extensionOf(value.filename);\n return fileValue(value.filename, extension, data);\n}\n\nconst table = processors as Record<string, ProcessorFn | undefined>;\n\n// The types whose processor failing means \"not JSON\", not \"not usable\".\nconst JSON_LIKE = new Set([\"JSON\", \"OBJECT\"]);\n\nexport async function normalizeValue(\n prop: ApProperty,\n value: unknown,\n options: NormalizeOptions = {},\n): Promise<unknown> {\n if (value === undefined || value === null) return value;\n if (prop.type === \"ARRAY\") return normalizeArray(prop, value, options);\n if (prop.type === \"FILE\") {\n if (prop.streaming === true) return toApStreamingFile(value, options);\n // Our hydration owns the forms the engine's own processor cannot resolve:\n // attachment and apfile refs, the size cap, and a host-injected fetcher.\n const hydrated = await toApFile(value, options);\n if (typeof hydrated !== \"string\") return hydrated;\n return plainFile(await table.FILE?.(prop as PieceProperty, hydrated));\n }\n const type = prop.type;\n const processor = type ? table[type] : undefined;\n if (!processor) return value;\n // Unreadable JSON drops here like any other type; validation names it.\n const processed = plainFile(await processor(prop as PieceProperty, value));\n return type === \"OBJECT\" && !isRecord(processed) ? undefined : processed;\n}\n\n// Normalises every configured value with a matching prop schema; keys\n// without a schema (or props without a value) pass through untouched.\nexport async function normalizePropsValue(\n props: Record<string, ApProperty> | undefined,\n values: Record<string, unknown>,\n options: NormalizeOptions = {},\n): Promise<Record<string, unknown>> {\n if (!props || !isRecord(values)) return values;\n const out: Record<string, unknown> = { ...values };\n for (const [name, prop] of Object.entries(props)) {\n if (!(name in out) || !isRecord(prop)) continue;\n const normalized = await normalizeValue(prop, out[name], options);\n if (normalized === undefined) delete out[name];\n else out[name] = normalized;\n }\n return out;\n}\n\n// Upstream's error shape: a field's messages, or an ARRAY's per-row errors.\nexport interface PropsValidationErrors {\n [key: string]: string[] | { properties: PropsValidationErrors[] };\n}\n\nfunction hasErrors(errors: PropsValidationErrors): boolean {\n return Object.keys(errors).length > 0;\n}\n\nfunction preview(value: unknown): string {\n const text = typeof value === \"string\" ? value : JSON.stringify(value);\n return text.length > 60 ? `${text.slice(0, 57)}...` : text;\n}\n\n// A JSON or OBJECT value its processor could not read: an optional prop would\n// otherwise pass the validator as simply absent.\nfunction unreadableJson(\n prop: ApProperty,\n value: unknown,\n original: unknown,\n): string | undefined {\n if (prop.type === undefined || !JSON_LIKE.has(prop.type)) return undefined;\n if (value !== undefined || original === undefined || original === null) {\n return undefined;\n }\n if (original === \"\") return undefined;\n return prop.type === \"OBJECT\"\n ? `expects a JSON object, received: ${preview(original)}`\n : `is not valid JSON, received: ${preview(original)}`;\n}\n\n// Upstream's validator over values our processors already coerced. Every\n// declared prop is checked, so a required one that is absent fails too.\nexport function validatePropsValue(\n props: Record<string, ApProperty> | undefined,\n processed: Record<string, unknown>,\n original: Record<string, unknown>,\n): PropsValidationErrors {\n const errors: PropsValidationErrors = {};\n if (!props) return errors;\n for (const [name, prop] of Object.entries(props)) {\n if (!isRecord(prop)) continue;\n const value = processed[name];\n const raw = original[name];\n if (prop.type === \"ARRAY\" && prop.properties && Array.isArray(value)) {\n const zipped: unknown = arrayZipperProcessor(prop as PieceProperty, raw);\n const rawRows = Array.isArray(zipped) ? (zipped as unknown[]) : [];\n const rows = (value as unknown[]).map((row, index) => {\n const rawRow = rawRows[index];\n return isRecord(row)\n ? validatePropsValue(\n prop.properties,\n row,\n isRecord(rawRow) ? rawRow : row,\n )\n : {};\n });\n if (rows.some(hasErrors)) errors[name] = { properties: rows };\n continue;\n }\n const unreadable = unreadableJson(prop, value, raw);\n if (unreadable) {\n errors[name] = [unreadable];\n continue;\n }\n const messages = validateProperty(prop as PieceProperty, value, raw);\n if (messages.length > 0) errors[name] = messages;\n }\n return errors;\n}\n\nfunction describeErrors(\n errors: PropsValidationErrors,\n props: Record<string, ApProperty> | undefined,\n path = \"\",\n): string[] {\n return Object.entries(errors).flatMap(([name, entry]) => {\n const label = path\n ? `${path}.${name}`\n : `${props?.[name]?.displayName ?? name} (${name})`;\n if (Array.isArray(entry)) return [`${label}: ${entry.join(\", \")}`];\n const rowProps = props?.[name]?.properties;\n return entry.properties.flatMap((row, index) =>\n describeErrors(row, rowProps, `${path ? label : name}[${index}]`),\n );\n });\n}\n\n// Thrown before piece code runs; `errors` carries upstream's shape.\nexport class PropsValidationError extends Error {\n constructor(\n owner: string,\n readonly errors: PropsValidationErrors,\n props: Record<string, ApProperty> | undefined,\n ) {\n super(\n `Invalid input for ${owner}: ${describeErrors(errors, props).join(\"; \")}`,\n );\n this.name = \"PropsValidationError\";\n }\n}\n\n// What the builder writes into a step upstream: a prop left unset takes its\n// defaultValue, the value the editor shows for it.\nfunction withDefaults(\n props: Record<string, ApProperty>,\n values: Record<string, unknown>,\n): Record<string, unknown> {\n const out = { ...values };\n for (const [name, prop] of Object.entries(props)) {\n if (!isRecord(prop)) continue;\n if (!(name in out)) {\n if (prop.defaultValue !== undefined) out[name] = prop.defaultValue;\n continue;\n }\n const fields = prop.properties;\n if (prop.type !== \"ARRAY\" || !fields) continue;\n const rows: unknown = arrayZipperProcessor(\n prop as PieceProperty,\n out[name],\n );\n if (Array.isArray(rows)) {\n out[name] = (rows as unknown[]).map((row) =>\n isRecord(row) ? withDefaults(fields, row) : row,\n );\n }\n }\n return out;\n}\n\n// Defaults, coercion, then validation: the values run() receives, or a\n// PropsValidationError naming each field that failed.\nexport async function preparePropsValue(\n owner: string,\n props: Record<string, ApProperty> | undefined,\n values: Record<string, unknown>,\n options: NormalizeOptions = {},\n): Promise<Record<string, unknown>> {\n if (!props || !isRecord(values)) return values;\n const original = withDefaults(props, values);\n const processed = await normalizePropsValue(props, original, options);\n const errors = validatePropsValue(props, processed, original);\n if (hasErrors(errors)) {\n throw new PropsValidationError(owner, errors, props);\n }\n return processed;\n}\n","// Structural types for published Activepieces bundles (Path B). Bundles inline\n// their framework, so all typing is duck-typed — see ../../10-spike-notes-s6a.md.\nimport type {\n ActionBase,\n BasePropertySchema,\n DropdownOption,\n DropdownProperty,\n DropdownState,\n PieceBase,\n TriggerBase,\n WebhookHandshakeConfiguration,\n} from \"@powerhousedao/pieces-framework\";\n\nexport { DEDUPE_KEY_PROPERTY } from \"@powerhousedao/pieces-framework\";\n\n// Widened from the framework's PropertyType: a bundle inlines its own copy of\n// the enum, so a value read off one is compared as a string, never by identity.\nexport type ApPropertyType = string;\n\nexport type ApDropdownOption = Pick<\n DropdownOption<unknown>,\n \"label\" | \"value\"\n> &\n Partial<Pick<DropdownOption<unknown>, \"description\" | \"icon\">>;\n\n// STATIC_DROPDOWN options are plain data; DROPDOWN options is a resolver function.\nexport type ApStaticDropdownState = Pick<\n DropdownState<unknown>,\n \"disabled\" | \"placeholder\"\n> & { options: ApDropdownOption[] };\n\n// Every field optional: an unknown bundle version may omit any of them, and a\n// missing field must read as absent rather than fail the descriptor.\nexport type ApProperty = Partial<\n Pick<\n BasePropertySchema,\n \"displayName\" | \"description\" | \"placeholder\" | \"advanced\"\n >\n> &\n Partial<Pick<DropdownProperty<unknown, boolean>, \"refreshers\">> & {\n type?: ApPropertyType;\n required?: boolean;\n defaultValue?: unknown;\n options?: ApStaticDropdownState | ((...args: unknown[]) => unknown);\n // Resolver function on DYNAMIC properties.\n props?: (...args: unknown[]) => unknown;\n // FILE: hand the piece a stream instead of the bytes.\n streaming?: boolean;\n // ARRAY: schema of each item's fields; absent for plain value arrays.\n properties?: Record<string, ApProperty>;\n // Layout and control hints, each read off only the types that declare it.\n width?: string;\n icon?: string;\n reveals?: string[];\n variant?: string;\n display?: string;\n min?: number;\n max?: number;\n step?: number;\n refreshOnSearch?: boolean;\n formatProperty?: string;\n // The core piece's form hints; see PiecePropDescriptor.\n showWhen?: unknown;\n emptyChoice?: unknown;\n };\n\n// Widened from PropertyGroupDisplay: tabs | section | summary | builder | footer.\nexport interface ApPropertyGroup {\n key?: string;\n display?: string;\n label?: string;\n description?: string;\n icon?: string;\n props?: string[];\n}\n\nexport interface ApErrorHandlingOption {\n defaultValue?: boolean;\n hide?: boolean;\n}\n\n// requireAuth is UI metadata only — pieces run without auth despite it (spike finding).\nexport type ApAction = Partial<\n Pick<ActionBase, \"name\" | \"displayName\" | \"description\" | \"requireAuth\">\n> & {\n props?: Record<string, ApProperty>;\n // Authored shape of run()'s return, for the expression picker. Plain data,\n // and never validated against — a piece may return whatever it likes.\n outputSchema?: unknown;\n // \"human\" | \"ai\" | \"both\"; absent counts as human-visible.\n audience?: string;\n propertyGroups?: ApPropertyGroup[];\n // READ | SEARCH | WRITE | DESTRUCTIVE, widened for the cross-bundle reason.\n classification?: string;\n errorHandlingOptions?: {\n retryOnFailure?: ApErrorHandlingOption;\n continueOnFailure?: ApErrorHandlingOption;\n };\n // Output ports, read only off a piece the host runs in process.\n ports?: unknown;\n // \"read\" | \"write\"; anything else reads as undeclared.\n requireReactor?: unknown;\n run: (ctx: unknown) => Promise<unknown>;\n // Called instead of run by a single-step test.\n test?: (ctx: unknown) => Promise<unknown>;\n};\n\n// Widened from TriggerStrategy for the same reason as ApPropertyType:\n// WEBHOOK | POLLING | MANUAL | APP_WEBHOOK, read off a foreign bundle's enum.\nexport type ApTriggerStrategy = string;\n\n// strategy widened from WebhookHandshakeStrategy: NONE | HEADER_PRESENT |\n// QUERY_PRESENT | BODY_PARAM_PRESENT | HEAD_REQUEST.\nexport type ApHandshakeConfiguration = Partial<\n Omit<WebhookHandshakeConfiguration, \"strategy\">\n> & { strategy?: string };\n\nexport type ApTrigger = Partial<\n Pick<\n TriggerBase,\n \"name\" | \"displayName\" | \"description\" | \"requireAuth\" | \"sampleData\"\n >\n> & {\n type?: ApTriggerStrategy;\n // Widened from TriggerTestStrategy: SIMULATION | TEST_FUNCTION.\n testStrategy?: string;\n // A form the editor draws instead of the props, e.g. \"schedule\".\n display?: unknown;\n requireReactor?: unknown;\n props?: Record<string, ApProperty>;\n propertyGroups?: ApPropertyGroup[];\n outputSchema?: unknown;\n handshakeConfiguration?: ApHandshakeConfiguration;\n // Widened from WebhookRenewConfiguration: CRON | NONE.\n renewConfiguration?: { strategy?: string; cronExpression?: string };\n onEnable?: (ctx: unknown) => Promise<void>;\n onDisable?: (ctx: unknown) => Promise<void>;\n onStart?: (ctx: unknown) => Promise<unknown>;\n run?: (ctx: unknown) => Promise<unknown[]>;\n test?: (ctx: unknown) => Promise<unknown[]>;\n onHandshake?: (ctx: unknown) => Promise<unknown>;\n onRenew?: (ctx: unknown) => Promise<void>;\n};\n\n// `categories` is widened from PieceCategory[] for the cross-bundle reason\n// above; `auth` is the raw property, not the framework's PieceAuthProperty.\nexport type ApPiece = Pick<PieceBase, \"displayName\"> &\n Partial<\n Pick<\n PieceBase,\n | \"description\"\n | \"logoUrl\"\n | \"authors\"\n | \"minimumSupportedRelease\"\n | \"maximumSupportedRelease\"\n >\n > & {\n categories?: string[];\n deprecated?: boolean;\n // An array when the piece offers several auth methods.\n auth?: ApProperty | ApProperty[];\n // A bundle exposes these as the built record or as a zero-arg method; the\n // framework's own Piece class only ever has the method.\n actions?: Record<string, ApAction> | (() => Record<string, ApAction>);\n triggers?: Record<string, ApTrigger> | (() => Record<string, ApTrigger>);\n getAction?: (name: string) => ApAction | undefined;\n getTrigger?: (name: string) => ApTrigger | undefined;\n metadata?: () => Record<string, unknown>;\n };\n\n// Normalizes the record-vs-method variants of `piece.actions`.\nexport function getActions(piece: ApPiece): Record<string, ApAction> {\n const actions =\n typeof piece.actions === \"function\" ? piece.actions() : piece.actions;\n return actions ?? {};\n}\n\n// Normalizes the record-vs-method variants of `piece.triggers`.\nexport function getTriggers(piece: ApPiece): Record<string, ApTrigger> {\n const triggers =\n typeof piece.triggers === \"function\" ? piece.triggers() : piece.triggers;\n return triggers ?? {};\n}\n","// Design-time channel (doc 06 §2.5): builds the PropertyContext handed to\n// DROPDOWN options() / DYNAMIC props() resolvers, and invokes them out-of-band.\nimport {\n getActions,\n getTriggers,\n type ApPiece,\n type ApProperty,\n} from \"../types.js\";\nimport { throwingStub, withTouchTracking } from \"./stubs.js\";\nimport type {\n ConnectionsManager,\n FlowsContext,\n PropertyContext,\n ReactorReadClient,\n ServerContext,\n} from \"@powerhousedao/pieces-framework\";\n\n// The framework's FlowsContext.list, minus the SeekPage cursors the host does\n// not serve: a resolver only ever reads `data`.\nexport interface FlowsProvider {\n list(\n ...params: Parameters<FlowsContext[\"list\"]>\n ): Promise<{ data: unknown[] }>;\n}\n\n// The framework's ConnectionsManager with its return widened: the host serves\n// whatever a connection resolved to, not only the shapes upstream enumerates.\nexport interface ConnectionsProvider {\n get(...params: Parameters<ConnectionsManager[\"get\"]>): Promise<unknown>;\n}\n\nexport type BuiltApPropertyContext = Omit<\n PropertyContext,\n \"flows\" | \"connections\"\n> & {\n flows: FlowsProvider;\n connections: ConnectionsProvider;\n // Read-only at design time, whatever the block declares (ADR 0005 §10).\n reactor: ReactorReadClient;\n};\n\nexport interface PropertyContextOptions {\n searchValue?: string;\n // Injected capabilities; anything omitted throws with its member path.\n flows?: FlowsProvider;\n connections?: ConnectionsProvider;\n server?: ServerContext;\n projectId?: string;\n // ctx.reactor for a resolver whose block declares requireReactor. Absent,\n // the member throws by name.\n reactor?: ReactorReadClient;\n onTouch?: (member: string) => void;\n}\n\nexport interface PropertyContextHandle {\n context: BuiltApPropertyContext;\n // Top-level members the resolver read; `UNDOCUMENTED:<name>` marks unknown reads.\n touched: ReadonlySet<string>;\n}\n\nexport function buildPropertyContext(\n options: PropertyContextOptions = {},\n): PropertyContextHandle {\n const touched = new Set<string>();\n const base: Record<string, unknown> = {\n searchValue: options.searchValue,\n reactor: options.reactor ?? throwingStub(\"reactor\"),\n server: options.server ?? throwingStub(\"server\"),\n project: {\n id: options.projectId ?? \"project\",\n externalId: () => Promise.resolve(options.projectId ?? \"project\"),\n },\n flows: options.flows ?? { list: throwingStub(\"flows.list\") },\n connections: options.connections ?? {\n get: throwingStub(\"connections.get\"),\n },\n };\n const context = withTouchTracking(base, touched, options.onTouch);\n return { context: context as unknown as BuiltApPropertyContext, touched };\n}\n\nexport class NotDynamicPropertyError extends Error {\n constructor(actionName: string, propName: string) {\n super(`Property \"${actionName}.${propName}\" has no dynamic resolver`);\n this.name = \"NotDynamicPropertyError\";\n }\n}\n\nfunction pickResolver(\n prop: ApProperty,\n): ((...args: unknown[]) => unknown) | undefined {\n if (typeof prop.options === \"function\") return prop.options;\n if (typeof prop.props === \"function\") return prop.props;\n return undefined;\n}\n\nexport interface ResolveDynamicPropertyParams {\n piece: ApPiece;\n // Action or trigger name, per kind (default \"action\").\n actionName: string;\n kind?: \"action\" | \"trigger\";\n propName: string;\n // Resolved values of the prop's refresher inputs (auth and sibling props).\n refresherValues?: Record<string, unknown>;\n context: BuiltApPropertyContext;\n}\n\n// Props map of an action or trigger; throws when the owner is unknown.\nexport function ownerProps(\n piece: ApPiece,\n actionName: string,\n kind: \"action\" | \"trigger\" = \"action\",\n): Record<string, ApProperty> {\n const owner =\n kind === \"trigger\"\n ? (getTriggers(piece)[actionName] as\n | { props?: Record<string, ApProperty> }\n | undefined)\n : (getActions(piece)[actionName] as\n | { props?: Record<string, ApProperty> }\n | undefined);\n if (!owner) throw new Error(`No ${kind} \"${actionName}\" on piece`);\n return owner.props ?? {};\n}\n\nexport function findProperty(\n piece: ApPiece,\n actionName: string,\n propName: string,\n kind: \"action\" | \"trigger\" = \"action\",\n): ApProperty {\n const prop = ownerProps(piece, actionName, kind)[propName] as\n | ApProperty\n | undefined;\n if (!prop)\n throw new Error(`No prop \"${propName}\" on ${kind} \"${actionName}\"`);\n return prop;\n}\n\n// Invokes a DROPDOWN options() or DYNAMIC props() resolver. The result is\n// returned untouched: pieces may soft-fail with a disabled DropdownState.\nexport async function resolveDynamicProperty(\n params: ResolveDynamicPropertyParams,\n): Promise<unknown> {\n const { piece, actionName, propName, kind = \"action\" } = params;\n const prop = findProperty(piece, actionName, propName, kind);\n const resolver = pickResolver(prop);\n if (!resolver) throw new NotDynamicPropertyError(actionName, propName);\n return await resolver(params.refresherValues ?? {}, params.context);\n}\n\nexport interface ParsedResolverId {\n packageName: string;\n actionName: string;\n propName: string;\n}\n\n// Inverse of the descriptor's id scheme: activepieces:<pkg>#<action>.<prop>.\nexport function parseDynamicResolverId(id: string): ParsedResolverId {\n const match = /^activepieces:(.+)#(.+)\\.([^.]+)$/.exec(id);\n if (!match) throw new Error(`Invalid dynamic resolver id: ${id}`);\n return { packageName: match[1], actionName: match[2], propName: match[3] };\n}\n\nexport async function resolveByResolverId(\n piece: ApPiece,\n resolverId: string,\n refresherValues: Record<string, unknown>,\n context: BuiltApPropertyContext,\n): Promise<unknown> {\n const { actionName, propName } = parseDynamicResolverId(resolverId);\n return resolveDynamicProperty({\n piece,\n actionName,\n propName,\n refresherValues,\n context,\n });\n}\n","// Our TriggerHookContext → theirs (doc 06 §2.8): one builder covering the\n// strategy variants; identity/payload as data, capabilities injected or stubbed.\nimport { Cron } from \"croner\";\nimport { DEDUPE_KEY_PROPERTY, type ApTrigger } from \"../types.js\";\nimport {\n InMemoryKeyValueStore,\n type ActionContextIdentity,\n type KeyValueStore,\n} from \"./action.js\";\nimport type { ConnectionsProvider, FlowsProvider } from \"./props.js\";\nimport type { ReactorOption } from \"./reactor-option.js\";\nimport { normalizeStoreScope, type StoreScopeName } from \"./store-scope.js\";\nimport { throwingStub, withTouchTracking } from \"./stubs.js\";\nimport type { ApFilesService } from \"./files.js\";\nimport type {\n TriggerStrategy,\n InputPropertyMap,\n ServerContext,\n SetScheduleRequest,\n TestOrRunHookContext,\n} from \"@powerhousedao/pieces-framework\";\n\n// Both branches of the framework's SetScheduleRequest, as the piece asked.\nexport type RecordedSchedule = SetScheduleRequest;\n\ntype HookContextFor<S extends TriggerStrategy> = TestOrRunHookContext<\n undefined,\n InputPropertyMap,\n S\n>;\n\nexport type RecordedListener = Parameters<\n HookContextFor<TriggerStrategy.APP_WEBHOOK>[\"app\"][\"createListeners\"]\n>[0];\n\n// The floor for an interval schedule; a cron is validated the way upstream's\n// engine does, by handing the expression to a parser. Upstream sets this at a\n// minute, a fair default for a hosted multi-tenant scheduler and too coarse\n// here, where a polling trigger is the reactor's own loop against a service it\n// owns. See MIN_SCHEDULE_INTERVAL_MS in reactor/schedule.ts, the floor the\n// supervisor actually clamps to.\nexport const MIN_SCHEDULE_INTERVAL_MS = 1_000;\n\nexport class InvalidCronExpressionError extends Error {\n constructor(cronExpression: string) {\n super(`Invalid cron expression \"${cronExpression}\"`);\n this.name = \"InvalidCronExpressionError\";\n }\n}\n\nexport class InvalidScheduleIntervalError extends Error {\n constructor(intervalMs: unknown) {\n super(\n `Invalid schedule interval ${String(intervalMs)}: expected a whole number of milliseconds, at least ${MIN_SCHEDULE_INTERVAL_MS}`,\n );\n this.name = \"InvalidScheduleIntervalError\";\n }\n}\n\n// setSchedule's own validation, as the engine's trigger helper performs it: an\n// interval is a whole number at or above the floor, a cron has to parse.\nexport function validateSchedule(request: RecordedSchedule): RecordedSchedule {\n if (\"intervalMs\" in request) {\n const { intervalMs } = request;\n if (\n !Number.isInteger(intervalMs) ||\n intervalMs < MIN_SCHEDULE_INTERVAL_MS\n ) {\n throw new InvalidScheduleIntervalError(intervalMs);\n }\n return { intervalMs };\n }\n const timezone = request.timezone ?? \"UTC\";\n let parsed: Cron;\n try {\n parsed = new Cron(request.cronExpression, { timezone, legacyMode: false });\n } catch {\n throw new InvalidCronExpressionError(request.cronExpression);\n }\n if (!parsed.nextRun()) {\n throw new InvalidCronExpressionError(request.cronExpression);\n }\n return { cronExpression: request.cronExpression, timezone };\n}\n\nexport type TriggerContextOptions = TriggerContextBaseOptions & ReactorOption;\n\ninterface TriggerContextBaseOptions {\n propsValue: Record<string, unknown>;\n auth?: unknown;\n store?: KeyValueStore;\n // \"test\" for test hooks so they never touch the live cursor; \"\" otherwise.\n // Ignored when hostPartitionedStore is set — the host separates them there.\n storePrefix?: string;\n // The store partitions on (scope, key) itself, so the key reaches it\n // verbatim instead of carrying the scope as a name prefix. See scopedKey.\n hostPartitionedStore?: boolean;\n identity?: ActionContextIdentity;\n // onEnable: an unchanged trigger re-enabling; pollingHelper keeps its cursor.\n isRepublish?: boolean;\n // WEBHOOK / APP_WEBHOOK: the incoming request; also handed to test runs.\n payload?: unknown;\n webhookUrl?: string;\n flows?: FlowsProvider;\n connections?: ConnectionsProvider;\n server?: ServerContext;\n // run/test hooks only per the AP contract; omitted members throw, named.\n files?: ApFilesService;\n onTouch?: (member: string) => void;\n}\n\n// One shape for every strategy: the framework splits TriggerHookContext by\n// TriggerStrategy, but a bundle's declared strategy is not known at build time.\nexport type BuiltApTriggerContext = HookContextFor<TriggerStrategy.POLLING> &\n HookContextFor<TriggerStrategy.WEBHOOK> &\n HookContextFor<TriggerStrategy.APP_WEBHOOK>;\n\nexport interface TriggerContextHandle {\n context: BuiltApTriggerContext;\n touched: ReadonlySet<string>;\n // setSchedule / app.createListeners calls, for the supervisor to arm.\n schedules: RecordedSchedule[];\n listeners: RecordedListener[];\n}\n\nexport function buildTriggerContext(\n options: TriggerContextOptions,\n): TriggerContextHandle {\n const { identity = {} } = options;\n const store = options.store ?? new InMemoryKeyValueStore();\n const touched = new Set<string>();\n const schedules: RecordedSchedule[] = [];\n const listeners: RecordedListener[] = [];\n\n // AP's engine store layout, for a store that is one flat map: FLOW scope\n // (the default) nests under the flow id; PROJECT scope uses the bare key.\n\n // Matching the enum's \"COLLECTION\" value alone missed a piece that passes\n // the name instead, which then silently got flow scope.\n const prefix = options.storePrefix ?? \"\";\n const flowId = identity.flowId ?? \"flow\";\n const scopedKey = (key: string, scope?: unknown) =>\n normalizeStoreScope(scope) === \"PROJECT\"\n ? `${prefix}${key}`\n : `${prefix}flow_${flowId}/${key}`;\n\n // A host-partitioned store owns the layout, so the scope travels beside the\n // key rather than inside it, exactly as buildActionContext passes it.\n\n // No \"test\" prefix on that path: a prefix aliases, so a live key named\n // \"testMode\" is a sample's \"Mode\" once both share one flat partition.\n\n // Separating a sample is then the host's job, by partition — which a prefix\n // could not do anyway, since nothing can enumerate a sample's keys to drop.\n const address = (\n key: string,\n scope?: unknown,\n ): [string, StoreScopeName | undefined] =>\n options.hostPartitionedStore\n ? [key, normalizeStoreScope(scope)]\n : [scopedKey(key, scope), undefined];\n\n const base: Record<string, unknown> = {\n auth: options.auth,\n propsValue: options.propsValue,\n isRepublish: options.isRepublish ?? false,\n store: {\n put: (key: string, value: unknown, scope?: unknown) => {\n const [at, partition] = address(key, scope);\n return store.put(at, value, partition);\n },\n get: (key: string, scope?: unknown) => store.get(...address(key, scope)),\n delete: (key: string, scope?: unknown) =>\n store.delete(...address(key, scope)),\n },\n flows: {\n list:\n options.flows?.list.bind(options.flows) ?? throwingStub(\"flows.list\"),\n current: {\n id: identity.flowId ?? \"flow\",\n version: { id: identity.flowVersionId ?? \"flow-version\" },\n },\n },\n step: { name: identity.stepName ?? \"trigger\" },\n project: {\n id: identity.projectId ?? \"project\",\n externalId: () => Promise.resolve(identity.projectId ?? \"project\"),\n },\n connections: options.connections ?? {\n get: throwingStub(\"connections.get\"),\n },\n server: options.server ?? throwingStub(\"server\"),\n webhookUrl: options.webhookUrl ?? \"http://localhost:0/webhook\",\n payload: options.payload,\n setSchedule: (schedule: RecordedSchedule) => {\n schedules.push(validateSchedule(schedule));\n },\n app: {\n createListeners: (listener: RecordedListener) => {\n listeners.push(listener);\n },\n },\n files: options.files ?? throwingStub(\"files\"),\n reactor: options.reactor ?? throwingStub(\"reactor\"),\n };\n\n const context = withTouchTracking(base, touched, options.onTouch);\n return {\n context: context as unknown as BuiltApTriggerContext,\n touched,\n schedules,\n listeners,\n };\n}\n\n// Dedup key per doc 08 §4.4: the payload's own _dedupe_key wins; the caller\n// falls back to its own synthesis when absent.\nexport function extractDedupeKey(payload: unknown): string | undefined {\n if (typeof payload !== \"object\" || payload === null) return undefined;\n const value = (payload as Record<string, unknown>)[DEDUPE_KEY_PROPERTY];\n return typeof value === \"string\" ? value : undefined;\n}\n\nexport class TriggerHookNotImplementedError extends Error {\n constructor(triggerName: string, hook: string) {\n super(`Trigger \"${triggerName}\" does not implement ${hook}()`);\n this.name = \"TriggerHookNotImplementedError\";\n }\n}\n\nexport type TriggerLifecycleHook =\n | \"onEnable\"\n | \"onDisable\"\n | \"run\"\n | \"test\"\n | \"onHandshake\"\n | \"onRenew\";\n\n// Invokes one lifecycle hook with the built context; result is returned untouched.\nexport async function runTriggerHook(\n trigger: ApTrigger,\n hook: TriggerLifecycleHook,\n handle: TriggerContextHandle,\n): Promise<unknown> {\n const fn = trigger[hook];\n if (typeof fn !== \"function\") {\n throw new TriggerHookNotImplementedError(trigger.name ?? \"unknown\", hook);\n }\n return await fn.call(trigger, handle.context);\n}\n","//#region src/workflow/strategy.ts\nconst DELIVERIES = {\n\tPOLLING: \"poll\",\n\tWEBHOOK: \"webhook\",\n\tMANUAL: \"manual\"\n};\nconst APP_WEBHOOK_UNSUPPORTED = \"TriggerStrategy.APP_WEBHOOK (app-level webhooks) is not supported\";\nvar TriggerStrategyError = class extends Error {\n\tstrategy;\n\tconstructor(strategy, issue) {\n\t\tsuper(issue);\n\t\tthis.name = \"TriggerStrategyError\";\n\t\tthis.strategy = strategy;\n\t}\n};\nfunction checkTriggerStrategy(strategy) {\n\tif (typeof strategy === \"string\" && Object.hasOwn(DELIVERIES, strategy)) return { delivery: DELIVERIES[strategy] };\n\tif (strategy === \"APP_WEBHOOK\") return { issue: APP_WEBHOOK_UNSUPPORTED };\n\treturn { issue: strategy === void 0 || strategy === null || strategy === \"\" ? \"The trigger declares no strategy\" : `Unknown trigger strategy ${JSON.stringify(strategy)}` };\n}\nfunction triggerDelivery(strategy) {\n\tconst check = checkTriggerStrategy(strategy);\n\tif (\"issue\" in check) throw new TriggerStrategyError(strategy, check.issue);\n\treturn check.delivery;\n}\n\n//#endregion\n//#region src/workflow/schedule.ts\nconst DEFAULT_TIMEZONE = \"UTC\";\nconst SCHEDULE_UNIT_MS = {\n\tminutes: 6e4,\n\thours: 36e5,\n\tdays: 864e5\n};\nconst SCHEDULE_MODES = [\"cron\", \"interval\"];\nvar ScheduleConfigError = class extends Error {\n\tconstructor(message) {\n\t\tsuper(`Schedule: ${message}`);\n\t\tthis.name = \"ScheduleConfigError\";\n\t}\n};\nconst CRON_FIELD = /^[\\d*?A-Za-z]+(?:[-/][\\dA-Za-z]+)*(?:,[\\d*?A-Za-z]+(?:[-/][\\dA-Za-z]+)*)*$/;\nfunction isRecord(value) {\n\treturn value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\nfunction parseTimezone(value) {\n\tif (value === void 0 || value === null || value === \"\") return \"UTC\";\n\tif (typeof value !== \"string\") throw new ScheduleConfigError(\"\\\"timezone\\\" must be an IANA name\");\n\ttry {\n\t\tnew Intl.DateTimeFormat(\"en-US\", { timeZone: value });\n\t} catch {\n\t\tthrow new ScheduleConfigError(`unknown timezone \"${value}\" (use an IANA name such as Europe/Lisbon)`);\n\t}\n\treturn value;\n}\nfunction parseCronText(cron) {\n\tif (typeof cron !== \"string\" || cron.trim() === \"\") throw new ScheduleConfigError(\"\\\"cron\\\" is required in cron mode\");\n\tconst pattern = cron.trim().replace(/\\s+/g, \" \");\n\tconst fields = pattern.split(\" \");\n\tif (fields.length !== 5) throw new ScheduleConfigError(`cron \"${pattern}\" must have exactly five fields (minute hour day month weekday)`);\n\tconst bad = fields.find((field) => !CRON_FIELD.test(field));\n\tif (bad !== void 0) throw new ScheduleConfigError(`cron \"${pattern}\" has an invalid field \"${bad}\"`);\n\treturn pattern;\n}\nfunction parseInterval(record) {\n\tconst { every, unit } = record;\n\tif (typeof every !== \"number\" || !Number.isInteger(every) || every < 1) throw new ScheduleConfigError(\"\\\"every\\\" must be a whole number of at least 1 in interval mode\");\n\tif (typeof unit !== \"string\" || !Object.hasOwn(SCHEDULE_UNIT_MS, unit)) throw new ScheduleConfigError(`\"unit\" must be one of ${Object.keys(SCHEDULE_UNIT_MS).join(\", \")}`);\n\tconst key = unit;\n\treturn {\n\t\tevery,\n\t\tunit: key,\n\t\teveryMs: every * SCHEDULE_UNIT_MS[key]\n\t};\n}\nfunction parseScheduleConfig(config) {\n\tif (!isRecord(config)) throw new ScheduleConfigError(\"the config must be an object\");\n\tconst timezone = parseTimezone(config.timezone);\n\tif (config.mode === \"cron\") return {\n\t\tmode: \"cron\",\n\t\tcron: parseCronText(config.cron),\n\t\ttimezone\n\t};\n\tif (config.mode === \"interval\") return {\n\t\tmode: \"interval\",\n\t\t...parseInterval(config),\n\t\ttimezone\n\t};\n\tthrow new ScheduleConfigError(config.mode === void 0 ? \"\\\"mode\\\" is required (\\\"cron\\\" or \\\"interval\\\")\" : `\"mode\" must be \"cron\" or \"interval\", not ${JSON.stringify(config.mode)}`);\n}\nfunction scheduleConfigIssue(config) {\n\ttry {\n\t\tparseScheduleConfig(config);\n\t\treturn;\n\t} catch (error) {\n\t\treturn error instanceof Error ? error.message : String(error);\n\t}\n}\n\n//#endregion\n//#region src/workflow/ports.ts\nconst NEXT_PORT = \"next\";\nconst ERROR_PORT = \"error\";\nconst PIECE_ACTION_PORTS = [NEXT_PORT, ERROR_PORT];\nconst TRIGGER_PORTS = [NEXT_PORT];\nfunction flowPorts(ports) {\n\treturn ports.filter((port) => port !== ERROR_PORT);\n}\nfunction undeclaredPortEdges(edges, portsOf) {\n\treturn edges.filter((edge) => {\n\t\tconst ports = portsOf(edge.from);\n\t\treturn ports !== void 0 && !ports.includes(edge.port);\n\t});\n}\n\n//#endregion\n//#region src/workflow/core.ts\nconst CORE_PIECE_NAME = \"@powerhousedao/piece-core\";\nconst BRANCH_PORTS = [\n\t\"true\",\n\t\"false\",\n\tERROR_PORT\n];\nfunction knownPorts(block) {\n\tif (block.kind === \"trigger\") return TRIGGER_PORTS;\n\treturn block.pieceName === \"@powerhousedao/piece-core\" && block.name === \"branch\" ? BRANCH_PORTS : PIECE_ACTION_PORTS;\n}\n\n//#endregion\n//#region src/workflow/document-reference.ts\nconst DOCUMENT_REF_KEY = \"$documentRef\";\nconst DOCUMENT_KEYS = /* @__PURE__ */ new Set([\n\t\"header\",\n\t\"state\",\n\t\"initialState\",\n\t\"operations\",\n\t\"clipboard\"\n]);\nconst MAX_DEPTH = 64;\nfunction isPlainObject(value) {\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) return false;\n\tconst proto = Object.getPrototypeOf(value);\n\treturn proto === Object.prototype || proto === null;\n}\nfunction isRevision(value) {\n\treturn isPlainObject(value) && Object.values(value).every((entry) => typeof entry === \"number\" && Number.isFinite(entry));\n}\nfunction documentReference(header) {\n\treturn {\n\t\tdocumentId: header.id,\n\t\tdocumentType: header.documentType,\n\t\tbranch: header.branch,\n\t\trevision: { ...header.revision }\n\t};\n}\nfunction isDocumentReference(value) {\n\treturn isPlainObject(value) && typeof value.documentId === \"string\" && typeof value.documentType === \"string\" && typeof value.branch === \"string\" && isRevision(value.revision);\n}\nfunction isDocumentHeader(value) {\n\treturn isPlainObject(value) && typeof value.id === \"string\" && value.id !== \"\" && typeof value.documentType === \"string\" && value.documentType !== \"\" && typeof value.branch === \"string\" && isRevision(value.revision) && typeof value.createdAtUtcIso === \"string\" && typeof value.lastModifiedAtUtcIso === \"string\";\n}\nfunction isReactorDocument(value) {\n\treturn isPlainObject(value) && isDocumentHeader(value.header) && isPlainObject(value.state);\n}\nfunction isDocumentRefMarker(value) {\n\treturn isPlainObject(value) && isDocumentReference(value[\"$documentRef\"]);\n}\nfunction walk(value, visit, depth, seen) {\n\tif (depth > MAX_DEPTH || typeof value !== \"object\" || value === null) return value;\n\tif (seen.has(value)) return value;\n\tif (Array.isArray(value)) {\n\t\tseen.add(value);\n\t\tconst mapped = value.map((item) => walk(item, visit, depth + 1, seen));\n\t\tseen.delete(value);\n\t\treturn mapped;\n\t}\n\tif (!isPlainObject(value)) return value;\n\tseen.add(value);\n\tconst replaced = visit(value);\n\tconst result = Object.fromEntries(Object.entries(replaced ?? value).map(([key, entry]) => [key, replaced && !(key in value) ? entry : walk(entry, visit, depth + 1, seen)]));\n\tseen.delete(value);\n\treturn result;\n}\nfunction referenceDocuments(value) {\n\treturn walk(value, (node) => {\n\t\tif (!isReactorDocument(node)) return void 0;\n\t\tconst rest = Object.entries(node).filter(([key]) => !DOCUMENT_KEYS.has(key));\n\t\treturn {\n\t\t\t[DOCUMENT_REF_KEY]: documentReference(node.header),\n\t\t\t...Object.fromEntries(rest)\n\t\t};\n\t}, 0, /* @__PURE__ */ new WeakSet());\n}\nfunction documentRefsIn(value) {\n\tconst found = [];\n\twalk(value, (node) => {\n\t\tif (isDocumentRefMarker(node)) found.push(node[DOCUMENT_REF_KEY]);\n\t}, 0, /* @__PURE__ */ new WeakSet());\n\treturn found;\n}\nfunction containsDocumentRef(value) {\n\treturn documentRefsIn(value).length > 0;\n}\nfunction expandDocumentRefs(value, expand) {\n\treturn walk(value, (node) => {\n\t\tif (!isDocumentRefMarker(node)) return void 0;\n\t\tconst { [DOCUMENT_REF_KEY]: reference, ...rest } = node;\n\t\treturn {\n\t\t\t...rest,\n\t\t\t...expand(reference)\n\t\t};\n\t}, 0, /* @__PURE__ */ new WeakSet());\n}\n\n//#endregion\nexport { APP_WEBHOOK_UNSUPPORTED, BRANCH_PORTS, CORE_PIECE_NAME, DEFAULT_TIMEZONE, DOCUMENT_REF_KEY, ERROR_PORT, NEXT_PORT, PIECE_ACTION_PORTS, SCHEDULE_MODES, SCHEDULE_UNIT_MS, ScheduleConfigError, TRIGGER_PORTS, TriggerStrategyError, checkTriggerStrategy, containsDocumentRef, documentReference, documentRefsIn, expandDocumentRefs, flowPorts, isDocumentRefMarker, isDocumentReference, isReactorDocument, knownPorts, parseCronText, parseScheduleConfig, referenceDocuments, scheduleConfigIssue, triggerDelivery, undeclaredPortEdges };\n//# sourceMappingURL=workflow.js.map","import { checkTriggerStrategy } from \"@powerhousedao/pieces-framework/workflow\";\nimport { Cron } from \"croner\";\n\n// Piece features this engine cannot run. Read off a loaded piece or off its\n// published listing alike, since both carry auth and triggers as data.\nconst ISSUES_URL = \"https://github.com/powerhouse-inc/powerhouse/issues/\";\n\nexport interface UnsupportedFeature {\n feature: string;\n issue: number;\n // \"<feature> is not supported yet (<issue url>)\", what a listing shows.\n reason: string;\n}\n\nfunction unsupported(feature: string, issue: number): UnsupportedFeature {\n return {\n feature,\n issue,\n reason: `${feature} is not supported yet (${ISSUES_URL}${issue})`,\n };\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\n// A piece's auth, from the bundle or the listing. With several methods the\n// piece runs if any one does; the connection picks which.\nexport function unsupportedAuth(auth: unknown): UnsupportedFeature | undefined {\n if (Array.isArray(auth)) {\n const reasons = auth.map(unsupportedMethod);\n return reasons.some((reason) => reason === undefined)\n ? undefined\n : reasons[0];\n }\n return unsupportedMethod(auth);\n}\n\n// The method a connection of `type` signs in with: the piece's only auth,\n// or the entry of that type among several (upstream's getAuthPropertyForValue).\nexport function authMethodFor(auth: unknown, type: unknown): unknown {\n if (!Array.isArray(auth)) return auth;\n return auth.find((entry) => isRecord(entry) && entry.type === type);\n}\n\nfunction unsupportedMethod(auth: unknown): UnsupportedFeature | undefined {\n if (!isRecord(auth)) return undefined;\n if (auth.type === \"OAUTH2\" && auth.grantType === \"client_credentials\") {\n return unsupported(\"OAuth2 client credentials\", 3091);\n }\n if (auth.type === \"OIDC\") return unsupported(\"OIDC auth\", 3091);\n if (auth.type === \"CUSTOM_AUTH\" && auth.refresh != null) {\n return unsupported(\"CustomAuth refresh\", 3091);\n }\n return undefined;\n}\n\n// A piece trigger; the core piece's triggers are fed by the host and never pass here.\nexport function unsupportedTrigger(trigger: {\n type?: unknown;\n renewConfiguration?: unknown;\n}): UnsupportedFeature | undefined {\n if (trigger.type === \"MANUAL\") {\n return unsupported(\"TriggerStrategy.MANUAL\", 3091);\n }\n const strategy = checkTriggerStrategy(trigger.type);\n if (\"issue\" in strategy) {\n const issue = trigger.type === \"APP_WEBHOOK\" ? 3081 : 3091;\n return {\n feature: `TriggerStrategy ${String(trigger.type)}`,\n issue,\n reason: `${strategy.issue} (${ISSUES_URL}${issue})`,\n };\n }\n const problem = renewProblem(trigger.renewConfiguration);\n if (problem) {\n return {\n feature: \"renewConfiguration\",\n issue: 3090,\n reason: `renewConfiguration ${problem} (${ISSUES_URL}3090)`,\n };\n }\n return undefined;\n}\n\n// A subscription the supervisor renews on a UTC cron by calling onRenew.\nexport interface TriggerRenew {\n strategy: \"CRON\";\n cronExpression: string;\n}\n\nfunction cronFires(cron: string): boolean {\n try {\n return (\n new Cron(cron, { timezone: \"UTC\", legacyMode: false }).nextRun() !== null\n );\n } catch {\n return false;\n }\n}\n\n// createTrigger fills in { strategy: \"NONE\" } for every trigger.\nfunction renewProblem(renew: unknown): string | undefined {\n if (renew === undefined || renew === null) return undefined;\n if (!isRecord(renew)) return \"is not an object\";\n if (renew.strategy === \"NONE\") return undefined;\n if (renew.strategy !== \"CRON\") {\n return `strategy ${String(renew.strategy)} is not supported`;\n }\n const cron = renew.cronExpression;\n if (typeof cron !== \"string\" || !cronFires(cron)) {\n return `cron ${JSON.stringify(cron)} is invalid`;\n }\n return undefined;\n}\n\n// The trigger's renewal, when it declares a valid CRON one.\nexport function triggerRenew(trigger: {\n renewConfiguration?: unknown;\n}): TriggerRenew | undefined {\n const renew = trigger.renewConfiguration;\n if (!isRecord(renew) || renew.strategy !== \"CRON\") return undefined;\n if (renewProblem(renew)) return undefined;\n return { strategy: \"CRON\", cronExpression: renew.cronExpression as string };\n}\n\nexport class UnsupportedPieceFeatureError extends Error {\n readonly feature: string;\n readonly issue: number;\n\n constructor(subject: string, unsupportedFeature: UnsupportedFeature) {\n super(`${subject}: ${unsupportedFeature.reason}`);\n this.name = \"UnsupportedPieceFeatureError\";\n this.feature = unsupportedFeature.feature;\n this.issue = unsupportedFeature.issue;\n }\n}\n","import type { RequireReactor } from \"@powerhousedao/pieces-framework\";\nimport {\n PIECE_ACTION_PORTS,\n TRIGGER_PORTS,\n} from \"@powerhousedao/pieces-framework/workflow\";\nimport {\n getActions,\n getTriggers,\n type ApPiece,\n type ApProperty,\n type ApPropertyType,\n type ApDropdownOption,\n type ApPropertyGroup,\n type ApTrigger,\n type ApTriggerStrategy,\n} from \"./types.js\";\nimport {\n triggerRenew,\n unsupportedAuth,\n unsupportedTrigger,\n type TriggerRenew,\n type UnsupportedFeature,\n} from \"./unsupported.js\";\n\nexport interface PiecePropDescriptor {\n name: string;\n displayName: string;\n description?: string;\n placeholder?: string;\n type: ApPropertyType;\n required: boolean;\n defaultValue?: unknown;\n // STATIC_DROPDOWN choices, extracted so the editor needs no runtime call.\n staticOptions?: ApDropdownOption[];\n // True when the prop carries a design-time resolver (DROPDOWN options() / DYNAMIC props()).\n hasDynamicResolver: boolean;\n // Synthesised domain-provider id: activepieces:<pkg>#<action>.<prop> (doc 08 §6.3).\n // Only top-level props get one; nested resolvers are not addressable yet.\n dynamicResolverId?: string;\n // Sibling prop names whose values feed the resolver; the editor re-runs\n // it when any of them changes.\n refreshers?: string[];\n // Nested shape: an ARRAY item's fields, or the props a DYNAMIC resolver\n // produced (see describeProperties). OBJECT props are free-form and carry none.\n properties?: PiecePropDescriptor[];\n // Activepieces' layout hint: rendered in the collapsed advanced section.\n advanced?: boolean;\n // Layout and control hints (see describeHints); absent when not declared.\n width?: \"half\" | \"full\";\n icon?: string;\n reveals?: string[];\n variant?: string;\n display?: string;\n min?: number;\n max?: number;\n step?: number;\n refreshOnSearch?: boolean;\n formatProperty?: string;\n // A STATIC_DROPDOWN's own state, beside its options.\n staticDisabled?: boolean;\n staticPlaceholder?: string;\n // Shown while a sibling holds one of `oneOf`.\n showWhen?: { prop: string; oneOf: unknown[] };\n // A checkbox with this label that stores \"\" on purpose.\n emptyChoice?: string;\n}\n\nexport interface PiecePropertyGroupDescriptor {\n key: string;\n display: string;\n label?: string;\n description?: string;\n icon?: string;\n props: string[];\n}\n\nexport interface PieceErrorHandlingDescriptor {\n retryOnFailure?: { defaultValue?: boolean; hide?: boolean };\n continueOnFailure?: { defaultValue?: boolean; hide?: boolean };\n}\n\nexport interface PieceActionDescriptor {\n name: string;\n displayName: string;\n description?: string;\n // UI metadata only — not a credential contract (spike finding).\n requireAuth: boolean;\n // The reactor access the step asks for; absent when it asks for none.\n requireReactor?: RequireReactor;\n props: PiecePropDescriptor[];\n // Output ports the step can leave on; the editor draws only these.\n ports: readonly string[];\n // Carried verbatim: it is what the expression picker builds a later step's\n // field list from, and a package piece has no published listing to read.\n outputSchema?: unknown;\n // Orders the action picker, so a package piece that declares it must be\n // ordered by it too rather than counting as unset.\n audience?: string;\n propertyGroups?: PiecePropertyGroupDescriptor[];\n classification?: string;\n errorHandlingOptions?: PieceErrorHandlingDescriptor;\n}\n\nexport interface PieceTriggerDescriptor {\n name: string;\n displayName: string;\n description?: string;\n strategy: ApTriggerStrategy;\n testStrategy?: string;\n // A form the editor draws instead of the props, e.g. \"schedule\".\n display?: string;\n requireAuth: boolean;\n requireReactor?: RequireReactor;\n props: PiecePropDescriptor[];\n ports: readonly string[];\n propertyGroups?: PiecePropertyGroupDescriptor[];\n outputSchema?: unknown;\n hasSampleData: boolean;\n // The sample itself, not just whether there is one: a trigger that declares\n // no outputSchema is read for its shape instead.\n sampleData?: unknown;\n // How the sender proves the endpoint exists before it will register it.\n // Absent when the trigger declares no handshake, or declares NONE.\n handshake?: { strategy: string; paramName?: string };\n // When the provider's subscription must be renewed; absent for NONE.\n renew?: TriggerRenew;\n // A trigger feature the engine cannot run; the piece's own is on the piece.\n unsupported?: UnsupportedFeature;\n}\n\nexport interface PieceAuthDescriptor {\n type: ApPropertyType;\n displayName?: string;\n description?: string;\n required?: boolean;\n // CUSTOM_AUTH's own fields. Without them a connection form has nothing to\n // ask for, which is what a piece read from a package rather than a published\n // listing would otherwise leave the editor with.\n props?: PiecePropDescriptor[];\n // OAUTH2 only: where and how the provider signs a user in.\n oauth2?: OAuth2MethodDescriptor;\n // Set when this engine can't sign in this way (OIDC, for one).\n unsupported?: UnsupportedFeature;\n}\n\nexport interface OAuth2MethodDescriptor {\n // May hold `{prop}` placeholders, filled from the connection's props.\n authUrl: string;\n tokenUrl: string;\n scope: string[];\n prompt?: \"none\" | \"consent\" | \"login\" | \"omit\";\n pkce?: boolean;\n pkceMethod?: \"plain\" | \"S256\";\n authorizationMethod?: \"HEADER\" | \"BODY\";\n grantType?: string;\n // Extra authorize-URL parameters, e.g. access_type=offline.\n extra?: Record<string, string>;\n}\n\nfunction describeOAuth2(\n raw: Record<string, unknown>,\n): OAuth2MethodDescriptor | undefined {\n if (typeof raw.authUrl !== \"string\" || typeof raw.tokenUrl !== \"string\") {\n return undefined;\n }\n const strings = (value: unknown) =>\n Array.isArray(value)\n ? value.filter((entry): entry is string => typeof entry === \"string\")\n : [];\n const extra =\n raw.extra && typeof raw.extra === \"object\"\n ? Object.fromEntries(\n Object.entries(raw.extra).filter(\n (entry): entry is [string, string] => typeof entry[1] === \"string\",\n ),\n )\n : undefined;\n return {\n authUrl: raw.authUrl,\n tokenUrl: raw.tokenUrl,\n scope: strings(raw.scope),\n ...(typeof raw.prompt === \"string\"\n ? { prompt: raw.prompt as OAuth2MethodDescriptor[\"prompt\"] }\n : {}),\n ...(typeof raw.pkce === \"boolean\" ? { pkce: raw.pkce } : {}),\n ...(raw.pkceMethod === \"plain\" || raw.pkceMethod === \"S256\"\n ? { pkceMethod: raw.pkceMethod }\n : {}),\n ...(raw.authorizationMethod === \"HEADER\" ||\n raw.authorizationMethod === \"BODY\"\n ? { authorizationMethod: raw.authorizationMethod }\n : {}),\n ...(typeof raw.grantType === \"string\" ? { grantType: raw.grantType } : {}),\n ...(extra && Object.keys(extra).length > 0 ? { extra } : {}),\n };\n}\n\n// NONE is how the framework spells \"no handshake\", so it is not carried:\n// a caller checking the field would otherwise have to know that too.\nfunction describeHandshake(\n trigger: ApTrigger,\n): { strategy: string; paramName?: string } | undefined {\n const strategy = trigger.handshakeConfiguration?.strategy;\n if (!strategy || strategy === \"NONE\") return undefined;\n return { strategy, paramName: trigger.handshakeConfiguration?.paramName };\n}\n\nexport interface PieceSource {\n packageName: string;\n version: string;\n}\n\n// Serializable descriptor of an adapted piece; the engine never learns\n// Activepieces exists (doc 08 §6.2).\nexport interface PieceDescriptor {\n id: string;\n source: PieceSource;\n displayName: string;\n description?: string;\n logoUrl?: string;\n categories?: string[];\n deprecated?: boolean;\n // A list when the piece offers several sign-in methods.\n auth?: PieceAuthDescriptor | PieceAuthDescriptor[];\n minimumSupportedRelease?: string;\n maximumSupportedRelease?: string;\n actions: PieceActionDescriptor[];\n triggers: PieceTriggerDescriptor[];\n // Set when no block of the piece can run here, e.g. an OAuth2 piece.\n unsupported?: UnsupportedFeature;\n}\n\nfunction optional<K extends string, V>(\n key: K,\n value: V | undefined,\n): Partial<Record<K, V>> {\n return value === undefined ? {} : ({ [key]: value } as Record<K, V>);\n}\n\nexport function describeOption(option: ApDropdownOption): ApDropdownOption {\n return {\n label: option.label,\n value: option.value,\n ...(typeof option.description === \"string\" && option.description\n ? { description: option.description }\n : {}),\n ...(typeof option.icon === \"string\" && option.icon\n ? { icon: option.icon }\n : {}),\n };\n}\n\n// Copied only when well-formed: a foreign bundle may carry anything here.\nfunction describeHints(prop: ApProperty): Partial<PiecePropDescriptor> {\n const hints: Partial<PiecePropDescriptor> = {};\n if (prop.width === \"half\" || prop.width === \"full\") hints.width = prop.width;\n const strings = [\"icon\", \"variant\", \"display\", \"formatProperty\"] as const;\n for (const key of strings) {\n const value = prop[key];\n if (typeof value === \"string\" && value !== \"\") hints[key] = value;\n }\n const numbers = [\"min\", \"max\", \"step\"] as const;\n for (const key of numbers) {\n const value = prop[key];\n if (typeof value === \"number\" && Number.isFinite(value)) hints[key] = value;\n }\n if (Array.isArray(prop.reveals)) {\n const reveals = prop.reveals.filter(\n (name): name is string => typeof name === \"string\",\n );\n if (reveals.length > 0) hints.reveals = reveals;\n }\n if (prop.refreshOnSearch === true) hints.refreshOnSearch = true;\n const showWhen = prop.showWhen as { prop?: unknown; oneOf?: unknown } | null;\n if (typeof showWhen?.prop === \"string\" && Array.isArray(showWhen.oneOf)) {\n const oneOf: unknown[] = showWhen.oneOf;\n hints.showWhen = { prop: showWhen.prop, oneOf: [...oneOf] };\n }\n if (typeof prop.emptyChoice === \"string\" && prop.emptyChoice !== \"\") {\n hints.emptyChoice = prop.emptyChoice;\n }\n return hints;\n}\n\nfunction describeGroups(\n groups: ApPropertyGroup[] | undefined,\n): PiecePropertyGroupDescriptor[] | undefined {\n if (!Array.isArray(groups)) return undefined;\n const described = groups\n .filter(\n (group) =>\n typeof group.key === \"string\" &&\n typeof group.display === \"string\" &&\n Array.isArray(group.props),\n )\n .map((group) => ({\n key: group.key!,\n display: group.display!,\n ...(group.label ? { label: group.label } : {}),\n ...(group.description ? { description: group.description } : {}),\n ...(group.icon ? { icon: group.icon } : {}),\n props: group.props!.filter(\n (name): name is string => typeof name === \"string\",\n ),\n }));\n return described.length > 0 ? described : undefined;\n}\n\nfunction hasResolver(prop: ApProperty): boolean {\n return typeof prop.options === \"function\" || typeof prop.props === \"function\";\n}\n\nfunction toPropDescriptor(\n name: string,\n prop: ApProperty,\n resolverId?: string,\n): PiecePropDescriptor {\n const dynamic = hasResolver(prop);\n const descriptor: PiecePropDescriptor = {\n name,\n displayName: prop.displayName ?? name,\n type: prop.type ?? \"UNKNOWN\",\n required: prop.required ?? false,\n hasDynamicResolver: dynamic,\n };\n if (typeof prop.description === \"string\" && prop.description !== \"\") {\n descriptor.description = prop.description;\n }\n if (typeof prop.placeholder === \"string\" && prop.placeholder !== \"\") {\n descriptor.placeholder = prop.placeholder;\n }\n if (prop.defaultValue !== undefined) {\n descriptor.defaultValue = prop.defaultValue;\n }\n if (prop.advanced === true) descriptor.advanced = true;\n if (dynamic && resolverId) {\n descriptor.dynamicResolverId = resolverId;\n }\n if (dynamic && Array.isArray(prop.refreshers)) {\n descriptor.refreshers = prop.refreshers.filter(\n (entry): entry is string => typeof entry === \"string\",\n );\n }\n if (typeof prop.options === \"object\" && Array.isArray(prop.options.options)) {\n descriptor.staticOptions = prop.options.options.map(describeOption);\n if (prop.options.disabled === true) descriptor.staticDisabled = true;\n if (typeof prop.options.placeholder === \"string\") {\n descriptor.staticPlaceholder = prop.options.placeholder;\n }\n }\n Object.assign(descriptor, describeHints(prop));\n if (prop.properties && typeof prop.properties === \"object\") {\n const nested = describeProperties(prop.properties);\n if (nested.length > 0) descriptor.properties = nested;\n }\n return descriptor;\n}\n\n// Descriptor list for a props map: nested ARRAY items and what a DYNAMIC\n// resolver returns, so the editor never sees raw piece properties.\nexport function describeProperties(\n props: Record<string, ApProperty> | null | undefined,\n resolverIdFor?: (propName: string) => string,\n): PiecePropDescriptor[] {\n if (!props || typeof props !== \"object\") return [];\n return Object.entries(props)\n .filter((entry): entry is [string, ApProperty] =>\n isPropertyObject(entry[1]),\n )\n .map(([propName, prop]) =>\n toPropDescriptor(propName, prop, resolverIdFor?.(propName)),\n );\n}\n\n// Bundles are duck-typed; a props map may carry non-object junk.\nfunction isPropertyObject(value: unknown): value is ApProperty {\n return value !== null && typeof value === \"object\";\n}\n\nfunction withUnsupported(feature: UnsupportedFeature | undefined): {\n unsupported?: UnsupportedFeature;\n} {\n return feature ? { unsupported: feature } : {};\n}\n\n// Pure translation over a loaded piece; performs no I/O and never executes\n// piece code beyond the actions()/triggers() accessors.\nfunction describeAuthMethod(auth: unknown): PieceAuthDescriptor | undefined {\n if (!auth || typeof auth !== \"object\") return undefined;\n const method = auth as ApProperty;\n // CUSTOM_AUTH carries a record here; a DYNAMIC prop would carry a\n // resolver function, which is not an auth shape at all.\n const props =\n method.props && typeof method.props === \"object\"\n ? describeProperties(method.props)\n : [];\n const oauth2 =\n method.type === \"OAUTH2\"\n ? describeOAuth2(auth as Record<string, unknown>)\n : undefined;\n return {\n type: method.type ?? \"UNKNOWN\",\n displayName: method.displayName,\n description: method.description,\n required: method.required,\n ...(props.length > 0 ? { props } : {}),\n ...(oauth2 ? { oauth2 } : {}),\n ...withUnsupported(unsupportedAuth(method)),\n };\n}\n\nfunction declaredPorts(ports: unknown): readonly string[] | undefined {\n if (!Array.isArray(ports) || ports.length === 0) return undefined;\n return ports.every((port) => typeof port === \"string\")\n ? (ports as string[])\n : undefined;\n}\n\n// Only a well-formed declaration is carried: a foreign bundle may hold anything.\nfunction declaredReactor(value: unknown): RequireReactor | undefined {\n return value === \"read\" || value === \"write\" ? value : undefined;\n}\n\nexport interface BuildDescriptorOptions {\n // Read each action's own `ports`: only a piece whose results the host routes.\n routed?: boolean;\n // The host feeds the triggers itself, so no trigger strategy is refused.\n hostFed?: boolean;\n}\n\nexport function buildDescriptor(\n piece: ApPiece,\n source: PieceSource,\n options: BuildDescriptorOptions = {},\n): PieceDescriptor {\n const actions = Object.entries(getActions(piece)).map(\n ([actionName, action]): PieceActionDescriptor => ({\n name: action.name ?? actionName,\n displayName: action.displayName ?? actionName,\n description: action.description,\n requireAuth: action.requireAuth ?? false,\n ...optional(\"requireReactor\", declaredReactor(action.requireReactor)),\n ports:\n (options.routed ? declaredPorts(action.ports) : undefined) ??\n PIECE_ACTION_PORTS,\n props: describeProperties(\n action.props,\n (propName) =>\n `activepieces:${source.packageName}#${actionName}.${propName}`,\n ),\n ...(action.outputSchema !== undefined\n ? { outputSchema: action.outputSchema }\n : {}),\n ...(action.audience !== undefined ? { audience: action.audience } : {}),\n ...optional(\"propertyGroups\", describeGroups(action.propertyGroups)),\n ...optional(\n \"classification\",\n typeof action.classification === \"string\"\n ? action.classification\n : undefined,\n ),\n ...optional(\"errorHandlingOptions\", action.errorHandlingOptions),\n }),\n );\n\n const triggers = Object.entries(getTriggers(piece)).map(\n ([triggerName, trigger]): PieceTriggerDescriptor => ({\n name: trigger.name ?? triggerName,\n displayName: trigger.displayName ?? triggerName,\n description: trigger.description,\n strategy: trigger.type ?? \"UNKNOWN\",\n testStrategy: trigger.testStrategy,\n ...(typeof trigger.display === \"string\" && trigger.display !== \"\"\n ? { display: trigger.display }\n : {}),\n requireAuth: trigger.requireAuth ?? false,\n ...optional(\"requireReactor\", declaredReactor(trigger.requireReactor)),\n ports: TRIGGER_PORTS,\n props: describeProperties(\n trigger.props,\n (propName) =>\n `activepieces:${source.packageName}#${triggerName}.${propName}`,\n ),\n ...(trigger.outputSchema !== undefined\n ? { outputSchema: trigger.outputSchema }\n : {}),\n hasSampleData:\n trigger.sampleData !== undefined && trigger.sampleData !== null,\n ...(trigger.sampleData !== undefined && trigger.sampleData !== null\n ? { sampleData: trigger.sampleData }\n : {}),\n handshake: describeHandshake(trigger),\n ...optional(\"renew\", triggerRenew(trigger)),\n ...optional(\"propertyGroups\", describeGroups(trigger.propertyGroups)),\n ...(options.hostFed ? {} : withUnsupported(unsupportedTrigger(trigger))),\n }),\n );\n\n const descriptor: PieceDescriptor = {\n id: `activepieces:${source.packageName}`,\n source,\n displayName: piece.displayName,\n description: piece.description,\n logoUrl: piece.logoUrl,\n categories: piece.categories,\n ...(piece.deprecated === true ? { deprecated: true } : {}),\n minimumSupportedRelease: piece.minimumSupportedRelease,\n maximumSupportedRelease: piece.maximumSupportedRelease,\n actions,\n triggers,\n ...withUnsupported(unsupportedAuth(piece.auth)),\n };\n // Several methods stay a list, in the piece's order; each says whether this\n // engine can run it.\n if (Array.isArray(piece.auth)) {\n const methods = piece.auth\n .map(describeAuthMethod)\n .filter((method) => method !== undefined);\n if (methods.length > 0) descriptor.auth = methods;\n } else {\n const method = describeAuthMethod(piece.auth);\n if (method) descriptor.auth = method;\n }\n return descriptor;\n}\n","import { readFileSync, realpathSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport type { ApPiece } from \"./types.js\";\n\nexport interface LoadedPiece {\n piece: ApPiece;\n entryPath: string;\n // Which duck-type check identified the export.\n check: \"constructor-name\" | \"structural\";\n}\n\n// Resolves a bundle's entry file. Published bundles typically carry only\n// `main` (no `exports`, no `type` — they are CJS).\nexport function resolveEntry(pieceDir: string): string {\n const raw = readFileSync(path.join(pieceDir, \"package.json\"), \"utf8\");\n const pkg = JSON.parse(raw) as {\n main?: string;\n module?: string;\n exports?: Record<string, unknown>;\n };\n const dotExport = pkg.exports?.[\".\"];\n const candidates: (string | undefined)[] = [];\n if (typeof dotExport === \"string\") candidates.push(dotExport);\n if (dotExport && typeof dotExport === \"object\") {\n const cond = dotExport as Record<string, unknown>;\n for (const key of [\"import\", \"require\", \"default\"]) {\n const value = cond[key];\n if (typeof value === \"string\") candidates.push(value);\n }\n }\n candidates.push(pkg.main, pkg.module, \"src/index.js\", \"index.js\", \"main.js\");\n // A bundle's manifest (or a symlink inside it) must not point the entry\n // outside pieceDir; realpath so a symlink can't launder the escape.\n const root = realpathSync(pieceDir);\n const rootWithSep = root + path.sep;\n for (const candidate of candidates) {\n if (!candidate) continue;\n const abs = path.resolve(pieceDir, candidate);\n let real: string;\n try {\n real = realpathSync(abs);\n } catch {\n continue; // candidate doesn't exist; try the next one\n }\n if (real !== root && !real.startsWith(rootWithSep)) continue;\n return abs;\n }\n throw new Error(`No entry file found for piece bundle at ${pieceDir}`);\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null;\n}\n\n// Identify the piece by constructor name (their own loader's check), falling\n// back to structure for bundles minified without keepNames. No `instanceof`.\nfunction findPiece(\n mod: Record<string, unknown>,\n): Pick<LoadedPiece, \"piece\" | \"check\"> | undefined {\n const candidates: unknown[] = [\n ...Object.values(mod),\n ...(isRecord(mod.default) ? Object.values(mod.default) : []),\n mod.default,\n ];\n for (const candidate of candidates) {\n // `constructor?.name`: a bundle may export an Object.create(null), and the\n // real piece is usually beside it in the same module.\n if (isRecord(candidate) && candidate.constructor?.name === \"Piece\") {\n return {\n piece: candidate as unknown as ApPiece,\n check: \"constructor-name\",\n };\n }\n }\n for (const candidate of candidates) {\n if (\n isRecord(candidate) &&\n typeof candidate.displayName === \"string\" &&\n (isRecord(candidate.actions) ||\n typeof candidate.actions === \"function\" ||\n typeof candidate.getAction === \"function\")\n ) {\n return { piece: candidate as unknown as ApPiece, check: \"structural\" };\n }\n }\n return undefined;\n}\n\n// A module the piece names and node cannot find. Dependencies are installed\n// with scripts disabled, so a native or downloaded one looks like this.\nfunction missingModule(entryPath: string, error: unknown): Error | undefined {\n const code = (error as { code?: unknown } | null)?.code;\n if (code !== \"ERR_MODULE_NOT_FOUND\" && code !== \"MODULE_NOT_FOUND\") {\n return undefined;\n }\n const detail = error instanceof Error ? error.message : String(error);\n return new Error(\n `Piece at ${entryPath} could not be loaded: it imports a module that is ` +\n `not there. Its dependencies are installed with lifecycle scripts ` +\n `disabled, so one that compiles or downloads on install -- a native ` +\n `addon, a browser download -- cannot be prepared here. ${detail}`,\n );\n}\n\n// ESM-first `import()` — Node's CJS interop handles the typical CJS bundle —\n// with a `require` fallback.\nexport async function loadPiece(entryPath: string): Promise<LoadedPiece> {\n let mod: Record<string, unknown>;\n try {\n mod = (await import(\n /* @vite-ignore */ pathToFileURL(entryPath).href\n )) as Record<string, unknown>;\n } catch (imported) {\n try {\n const require = createRequire(import.meta.url);\n mod = require(entryPath) as Record<string, unknown>;\n } catch (required) {\n // The import's error names the missing module; require's often names\n // only the entry it was handed.\n throw (\n missingModule(entryPath, imported) ??\n missingModule(entryPath, required) ??\n required\n );\n }\n }\n const found = findPiece(mod);\n if (!found) {\n throw new Error(\n `No Piece export found in ${entryPath}. Export keys: ${Object.keys(mod).join(\", \")}`,\n );\n }\n return { ...found, entryPath };\n}\n\nexport async function loadPieceFromDir(pieceDir: string): Promise<LoadedPiece> {\n return loadPiece(resolveEntry(pieceDir));\n}\n","// Network egress policy, enforced inside the worker child. Pieces bundle their\n// own HTTP clients, so hooking one of them — or `fetch` — is bypassable.\n\n// Every TCP connection in Node ends at `net.Socket.prototype.connect`, whatever\n// the client, so that is the choke point installed here.\n\n// This hardens SSRF inside a cooperative process; it is not a boundary against\n// hostile code — see installEgressGuard.\nimport dgram from \"node:dgram\";\nimport dns from \"node:dns\";\nimport net, { isIP } from \"node:net\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { ssrfIpClassifier } from \"@powerhousedao/pieces-framework/host\";\nimport type { EgressPolicy } from \"./protocol.js\";\n\nexport const EGRESS_DENIED_CODE = \"EGRESS_DENIED\";\n\n// What a host applies when it expresses no preference: every public host is\n// reachable, private space and the metadata endpoint are not.\nexport const DEFAULT_EGRESS_POLICY: EgressPolicy = {};\n\n// Raised at connect time and delivered to the piece the way Node delivers a\n// failed DNS lookup — an error on the socket — so any client surfaces it.\nexport class EgressDeniedError extends Error {\n readonly code = EGRESS_DENIED_CODE;\n readonly host: string;\n readonly port: number | undefined;\n readonly address: string | undefined;\n\n constructor(\n reason: string,\n where: { host: string; port?: number; address?: string },\n ) {\n super(`Egress denied: ${reason}`);\n this.name = \"EgressDeniedError\";\n this.host = where.host;\n this.port = where.port;\n this.address = where.address;\n }\n}\n\n// The SSRF surface (loopback, RFC1918, link-local incl. the metadata endpoint,\n// multicast, and the IPv6 equivalents) is the framework's classifier table.\n\n// ipaddr.js reads a deprecated IPv4-compatible address (::a.b.c.d) as unicast,\n// so ::169.254.169.254 would walk past it; the whole block is refused here.\nconst IPV4_COMPATIBLE = new net.BlockList();\nIPV4_COMPATIBLE.addSubnet(\"::\", 96, \"ipv6\");\n\nfunction familyOf(address: string): \"ipv4\" | \"ipv6\" {\n return isIP(address) === 6 ? \"ipv6\" : \"ipv4\";\n}\n\n// The address without its zone, or undefined when it is not one at all.\nexport function parseAddress(value: string): string | undefined {\n const bare = value.split(\"%\")[0];\n return isIP(bare) === 0 ? undefined : bare;\n}\n\n// Compiled eagerly so a malformed entry fails the request rather than\n// degrading it to no enforcement.\nfunction addAllowedAddress(list: net.BlockList, spec: string): void {\n const slash = spec.indexOf(\"/\");\n const mask = slash === -1 ? \"\" : spec.slice(slash + 1);\n const address = parseAddress(slash === -1 ? spec : spec.slice(0, slash));\n if (!address) {\n throw new Error(`Egress policy entry \"${spec}\" is not an IP address`);\n }\n const family = familyOf(address);\n const width = family === \"ipv6\" ? 128 : 32;\n const prefix = mask === \"\" ? width : Number(mask);\n if (!Number.isInteger(prefix) || prefix < 1 || prefix > width) {\n throw new Error(`Egress policy entry \"${spec}\" has an invalid prefix`);\n }\n list.addSubnet(address, prefix, family);\n}\n\ntype NativeLookup = (\n hostname: string,\n options: dns.LookupOneOptions,\n callback: (error: Error | null, address: unknown, family?: number) => void,\n) => void;\n\n// getaddrinfo, taken before anything is patched: the guard resolves through\n// this so its own lookups never meet the refusal it installs below.\nconst nativeLookup = originalOf<NativeLookup>(dns, \"lookup\");\n\n// c-ares, which owns its sockets and never passes through dgram or connect.\n\n// A query is a channel out on its own — the data rides in the name — so the\n// answer is irrelevant and the whole surface is refused under a policy.\nconst RESOLVER_METHODS = [\n \"resolve\",\n \"resolve4\",\n \"resolve6\",\n \"resolveAny\",\n \"resolveCaa\",\n \"resolveCname\",\n \"resolveMx\",\n \"resolveNaptr\",\n \"resolveNs\",\n \"resolvePtr\",\n \"resolveSoa\",\n \"resolveSrv\",\n \"resolveTxt\",\n \"reverse\",\n];\n\nexport function isPrivateAddress(value: string): boolean {\n const address = parseAddress(value);\n // An address we cannot classify counts as private: fail closed.\n if (!address) return true;\n if (IPV4_COMPATIBLE.check(address, familyOf(address))) return true;\n return ssrfIpClassifier.isBlockedIp({ ip: address, allowList: [] });\n}\n\ninterface CompiledPolicy {\n hosts: string[] | undefined;\n addresses: net.BlockList | undefined;\n ports: number[] | undefined;\n allowPrivate: boolean;\n}\n\nfunction compile(policy: EgressPolicy): CompiledPolicy {\n const hosts = policy.allowHosts?.map((host) => host.trim().toLowerCase());\n const ports = policy.allowPorts?.map((port) => {\n if (!Number.isInteger(port) || port < 0 || port > 65535) {\n throw new Error(`Egress policy port ${String(port)} is out of range`);\n }\n return port;\n });\n const specs = policy.allowAddresses ?? [];\n const addresses = new net.BlockList();\n for (const spec of specs) addAllowedAddress(addresses, spec);\n return {\n hosts: hosts && hosts.length > 0 ? hosts : undefined,\n addresses: specs.length > 0 ? addresses : undefined,\n ports: ports && ports.length > 0 ? ports : undefined,\n allowPrivate: policy.allowPrivateAddresses === true,\n };\n}\n\nfunction hostAllowed(policy: CompiledPolicy, host: string): boolean {\n if (!policy.hosts) return true;\n const name = host.toLowerCase();\n return policy.hosts.some((entry) =>\n entry.startsWith(\"*.\")\n ? name.length > entry.length - 1 && name.endsWith(entry.slice(1))\n : entry === name,\n );\n}\n\nfunction addressAllowed(policy: CompiledPolicy, address: string): boolean {\n const ip = parseAddress(address);\n if (!ip) return false;\n if (policy.addresses?.check(ip, familyOf(ip))) return true;\n return policy.allowPrivate || !isPrivateAddress(ip);\n}\n\n// The policy of the request in flight, and the one the work started under: both\n// apply, so a pooled client's callback chain cannot borrow a laxer context.\n\n// A piece's leftover timer keeps the policy it was created with rather than\n// whatever the next request brings.\nlet inFlight: CompiledPolicy | undefined;\nconst started = new AsyncLocalStorage<CompiledPolicy | undefined>();\n\nfunction policiesInForce(): CompiledPolicy[] {\n const inherited = started.getStore();\n const policies: CompiledPolicy[] = [];\n if (inFlight) policies.push(inFlight);\n if (inherited && inherited !== inFlight) policies.push(inherited);\n return policies;\n}\n\n// Runs one request under its policy. Compiling first means a malformed policy\n// fails the request rather than degrading it to no enforcement.\nexport async function runWithEgressPolicy<T>(\n policy: EgressPolicy | undefined,\n work: () => Promise<T>,\n): Promise<T> {\n const compiled = policy ? compile(policy) : undefined;\n installEgressGuard();\n inFlight = compiled;\n try {\n return await started.run(compiled, work);\n } finally {\n // The request is over; what it left running keeps the policy it inherited,\n // so it can never become less restricted than it started.\n if (inFlight === compiled) inFlight = undefined;\n }\n}\n\ninterface ConnectOptions {\n path?: string;\n port?: number | string;\n host?: string;\n lookup?: unknown;\n [key: string]: unknown;\n}\n\n// Node's own connect-argument shapes: (options) | (port[, host]) | (path), plus\n// the pre-normalized [options, callback] array net.createConnection hands over.\nfunction normalizeConnectArgs(args: unknown[]): {\n options: ConnectOptions;\n callback: unknown;\n} {\n if (Array.isArray(args[0])) {\n const [options, callback] = args[0] as [ConnectOptions, unknown];\n return { options: { ...options }, callback };\n }\n const first = args[0];\n let options: ConnectOptions = {};\n if (typeof first === \"object\" && first !== null) {\n options = { ...(first as ConnectOptions) };\n } else if (typeof first === \"string\" && Number.isNaN(Number(first))) {\n options.path = first;\n } else {\n options.port = first as number;\n if (typeof args[1] === \"string\") options.host = args[1];\n }\n const last = args[args.length - 1];\n return { options, callback: typeof last === \"function\" ? last : undefined };\n}\n\ntype LookupResult = { address: string; family: number }[];\n\ntype LookupCallback = (\n error: Error | null,\n address?: string | LookupResult,\n family?: number,\n) => void;\n\n// Classifies the address the socket is about to use, not the name the piece\n// asked for: a name check alone loses to DNS rebinding.\nfunction guardedLookup(\n policies: CompiledPolicy[],\n host: string,\n port: number | undefined,\n): (hostname: string, options: unknown, callback: LookupCallback) => void {\n return (hostname, options, callback) => {\n const asked = options as { all?: boolean };\n nativeLookup(\n hostname,\n options as dns.LookupOneOptions,\n (error: Error | null, result: unknown, family?: number) => {\n if (error) {\n callback(error);\n return;\n }\n try {\n const entries: LookupResult = asked.all\n ? (result as LookupResult)\n : [{ address: result as string, family: family ?? 0 }];\n const permitted = entries.filter((entry) =>\n policies.every((policy) => addressAllowed(policy, entry.address)),\n );\n if (permitted.length === 0) {\n const seen = entries.map((entry) => entry.address).join(\", \");\n callback(\n new EgressDeniedError(\n `host \"${host}\" resolves to ${seen || \"nothing\"}, which the policy does not permit`,\n { host, port, address: entries[0]?.address },\n ),\n );\n return;\n }\n if (asked.all) callback(null, permitted);\n else callback(null, permitted[0].address, permitted[0].family);\n } catch (failure) {\n // A defect in the guard denies the connection, never opens it.\n callback(\n failure instanceof Error ? failure : new Error(String(failure)),\n );\n }\n },\n );\n };\n}\n\nfunction denyReason(\n policies: CompiledPolicy[],\n options: ConnectOptions,\n): EgressDeniedError | undefined {\n if (typeof options.path === \"string\") {\n return new EgressDeniedError(\n `connections to local socket \"${options.path}\" are not permitted`,\n { host: options.path },\n );\n }\n const host = typeof options.host === \"string\" ? options.host : \"\";\n const port = options.port === undefined ? undefined : Number(options.port);\n for (const policy of policies) {\n if (policy.ports && (port === undefined || !policy.ports.includes(port))) {\n return new EgressDeniedError(\n `port ${String(port)} on host \"${host}\" is not permitted`,\n { host, port },\n );\n }\n if (!hostAllowed(policy, host)) {\n return new EgressDeniedError(`host \"${host}\" is not on the allowlist`, {\n host,\n port,\n });\n }\n if (isIP(host) && !addressAllowed(policy, host)) {\n return new EgressDeniedError(`address ${host} is not permitted`, {\n host,\n port,\n address: host,\n });\n }\n }\n return undefined;\n}\n\n// Reports a denial the way Node reports an asynchronous socket failure, so a\n// piece catches it from its client rather than from a synchronous throw.\nfunction failLater(\n emitter: { emit: (event: string, error: Error) => boolean },\n error: EgressDeniedError,\n callback: unknown,\n): void {\n process.nextTick(() => {\n if (typeof callback === \"function\") (callback as (e: Error) => void)(error);\n else emitter.emit(\"error\", error);\n });\n}\n\n// Takes a method off its descriptor rather than as a method reference: what is\n// wanted is the original implementation, re-applied with an explicit `this`.\nfunction originalOf<T>(target: object, name: string): T {\n return Object.getOwnPropertyDescriptor(target, name)?.value as T;\n}\n\nfunction resolverDenial(method: string, args: unknown[]): EgressDeniedError {\n const host = typeof args[0] === \"string\" ? args[0] : \"\";\n return new EgressDeniedError(\n `DNS ${method}(\"${host}\") is not permitted; use a hostname in a request instead`,\n { host },\n );\n}\n\n// Refuses every c-ares entry point on one object, in the shape its callers\n// expect: a rejected promise here, a callback error there.\nfunction refuseResolvers(target: object, promised: boolean): void {\n for (const method of RESOLVER_METHODS) {\n const original = originalOf<(this: unknown, ...args: unknown[]) => unknown>(\n target,\n method,\n );\n if (typeof original !== \"function\") continue;\n function refused(this: unknown, ...args: unknown[]): unknown {\n if (policiesInForce().length === 0) return original.apply(this, args);\n const denied = resolverDenial(method, args);\n if (promised) return Promise.reject(denied);\n const callback = args[args.length - 1];\n // No callback is a programming error Node would throw on anyway.\n if (typeof callback !== \"function\") throw denied;\n process.nextTick(() => (callback as (error: Error) => void)(denied));\n return undefined;\n }\n seal(target, method, refused);\n }\n}\n\n// Sealed so a piece holding the pristine implementation cannot put it back, and\n// so a later assignment cannot quietly unhook the guard.\nfunction seal(target: object, name: string, value: unknown): void {\n Object.defineProperty(target, name, {\n value,\n writable: false,\n configurable: false,\n enumerable: false,\n });\n}\n\nlet installed = false;\n\n// Installed when the worker child starts, before any piece code can run, and a\n// no-op while no policy is in force.\n\n// Not a boundary against hostile code: a child process or a worker thread gets\n// its own copy of these modules. Isolation is a network namespace, not this.\nexport function installEgressGuard(): void {\n if (installed) return;\n installed = true;\n\n const connect = originalOf<\n (this: net.Socket, ...args: unknown[]) => net.Socket\n >(net.Socket.prototype, \"connect\");\n\n function patchedConnect(this: net.Socket, ...args: unknown[]): net.Socket {\n const policies = policiesInForce();\n if (policies.length === 0) return connect.apply(this, args);\n const { options, callback } = normalizeConnectArgs(args);\n // Node defaults a missing host to localhost; write it back so the checks\n // and the guarded lookup below both see what will be dialled.\n if (typeof options.path !== \"string\" && !options.host) {\n options.host = \"localhost\";\n }\n const denied = denyReason(policies, options);\n if (denied) {\n process.nextTick(() => this.destroy(denied));\n return this;\n }\n if (typeof options.host === \"string\" && !isIP(options.host)) {\n options.lookup = guardedLookup(\n policies,\n options.host,\n options.port === undefined ? undefined : Number(options.port),\n );\n }\n return connect.call(this, options, callback);\n }\n seal(net.Socket.prototype, \"connect\", patchedConnect);\n\n // The dgram surface carries no destination a policy can usefully allow — a\n // piece's work is HTTP — so it is refused whole, as is c-ares further down.\n const send = originalOf<(this: dgram.Socket, ...args: unknown[]) => void>(\n dgram.Socket.prototype,\n \"send\",\n );\n function patchedSend(this: dgram.Socket, ...args: unknown[]): void {\n if (policiesInForce().length === 0) {\n send.apply(this, args);\n return;\n }\n const host = args.find(\n (arg, index) => index > 0 && typeof arg === \"string\",\n ) as string | undefined;\n const last = args[args.length - 1];\n failLater(\n this,\n new EgressDeniedError(\n `UDP to \"${host ?? \"the requested address\"}\" is not permitted`,\n { host: host ?? \"\" },\n ),\n typeof last === \"function\" ? last : undefined,\n );\n }\n seal(dgram.Socket.prototype, \"send\", patchedSend);\n\n // Inbound is refused for the same reason: a delivery reaches a workflow\n // through the host's webhook endpoint, never a port the piece opened.\n const bind = originalOf<\n (this: dgram.Socket, ...args: unknown[]) => dgram.Socket\n >(dgram.Socket.prototype, \"bind\");\n function patchedBind(this: dgram.Socket, ...args: unknown[]): dgram.Socket {\n if (policiesInForce().length === 0) return bind.apply(this, args);\n failLater(\n this,\n new EgressDeniedError(\"binding a UDP socket is not permitted\", {\n host: \"\",\n }),\n undefined,\n );\n return this;\n }\n seal(dgram.Socket.prototype, \"bind\", patchedBind);\n\n const listen = originalOf<\n (this: net.Server, ...args: unknown[]) => net.Server\n >(net.Server.prototype, \"listen\");\n function patchedListen(this: net.Server, ...args: unknown[]): net.Server {\n if (policiesInForce().length === 0) return listen.apply(this, args);\n failLater(\n this,\n new EgressDeniedError(\"listening for connections is not permitted\", {\n host: \"\",\n }),\n undefined,\n );\n return this;\n }\n seal(net.Server.prototype, \"listen\", patchedListen);\n\n // The four objects a piece can reach c-ares through; dns.lookup is\n // getaddrinfo and stays open, guarded per connect instead.\n refuseResolvers(dns, false);\n refuseResolvers(dns.Resolver.prototype, false);\n refuseResolvers(dns.promises, true);\n refuseResolvers(dns.promises.Resolver.prototype, true);\n}\n\n// True for a denial raised in the child, including one a piece's client\n// re-wrapped: axios copies `code`, undici keeps the original as `cause`.\nexport function isEgressDenied(error: unknown): boolean {\n const seen = new Set<unknown>();\n let candidate: unknown = error;\n // Wrappers nest, and some of them produce a cycle; the walk is bounded by\n // the seen set and by a depth no honest chain reaches.\n for (let depth = 0; depth < 16; depth++) {\n if (candidate instanceof EgressDeniedError) return true;\n if (typeof candidate !== \"object\" || candidate === null) return false;\n if (seen.has(candidate)) return false;\n seen.add(candidate);\n const fields = candidate as {\n name?: unknown;\n code?: unknown;\n message?: unknown;\n cause?: unknown;\n properties?: { code?: unknown };\n serialized?: { name?: unknown; properties?: { code?: unknown } };\n };\n const codes = [\n fields.code,\n fields.properties?.code,\n fields.serialized?.properties?.code,\n ];\n if (codes.includes(EGRESS_DENIED_CODE)) return true;\n if (fields.name === \"EgressDeniedError\") return true;\n if (fields.serialized?.name === \"EgressDeniedError\") return true;\n if (\n typeof fields.message === \"string\" &&\n fields.message.includes(\"Egress denied:\")\n ) {\n return true;\n }\n candidate = fields.cause;\n }\n return false;\n}\n","// Certificate checks a piece cannot switch off for the worker.\n//\n// Activepieces pieces published on npm bundle an old pieces-common whose\n// FetchHttpClient sets process.env.NODE_TLS_REJECT_UNAUTHORIZED = \"0\" before\n// every request (pieces-framework's own copy has the line removed; the\n// bundles inline theirs). The variable is process-wide: while it is \"0\",\n// every TLS connection Node opens without an explicit rejectUnauthorized\n// skips certificate verification, Google's and the bank's included.\n//\n// Node consults the variable only when a connection does not say: tls.connect\n// takes rejectUnauthorized from its options and falls back to the variable.\n// So the guard gives every connection an explicit rejectUnauthorized: true\n// unless its caller asked otherwise. fetch (undici), https, and the HTTP\n// clients pieces bundle all connect through tls.connect, so the variable no\n// longer decides anything, without timing races. A caller that explicitly\n// asks for rejectUnauthorized: false (an HTTP piece's \"ignore SSL errors\")\n// still gets it: that is a choice, not pollution.\nimport tls from \"node:tls\";\n\ntype Connect = typeof tls.connect;\n\n/** Defaults rejectUnauthorized to true on every tls.connect; returns the undo. */\nexport function installTlsGuard(): () => void {\n const original: Connect = tls.connect;\n const guarded = function (this: unknown, ...args: unknown[]) {\n // tls.connect(options[, cb]), (port[, host][, options][, cb]) or (path[, options][, cb])\n const index = args.findIndex(\n (a) => a !== null && typeof a === \"object\" && !Array.isArray(a),\n );\n if (index === -1) {\n const at = args.findIndex((a) => typeof a === \"function\");\n args.splice(at === -1 ? args.length : at, 0, {\n rejectUnauthorized: true,\n });\n } else {\n const options = args[index] as { rejectUnauthorized?: boolean };\n if (options.rejectUnauthorized === undefined) {\n args[index] = { ...options, rejectUnauthorized: true };\n }\n }\n return (original as (...a: unknown[]) => tls.TLSSocket).apply(this, args);\n } as Connect;\n tls.connect = guarded;\n return () => {\n if (tls.connect === guarded) tls.connect = original;\n };\n}\n","// Wall-clock marks a child takes while serving one request, sent back with its\n// response so the host can draw them as spans. The child carries no tracer.\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport type { WorkerPhaseTiming, WorkerTimings } from \"./protocol.js\";\n\nconst ANCHOR_MS = 1_000;\n// Date.now() rounds to the ms: a smaller drift is that, not a clock step, and\n// following it would step time backwards.\nconst STEP_MS = 5;\n\n// Epoch ms, sub-ms precise, comparable across processes. Re-anchored each second:\n// timeOrigin is fixed at start, so a clock step would skew host against child.\nexport function wallClock(): () => number {\n let anchoredAt = performance.now();\n let anchor = Date.now() - anchoredAt;\n return () => {\n const now = performance.now();\n if (now - anchoredAt >= ANCHOR_MS) {\n anchoredAt = now;\n const next = Date.now() - now;\n if (Math.abs(next - anchor) > STEP_MS) anchor = next;\n }\n return anchor + now;\n };\n}\n\nexport const epochNow = wallClock();\n\nlet readyAt: number | undefined;\nlet bootReported = false;\n\n// When the entry finished loading; reported once, with the first response.\nexport function markWorkerReady(): void {\n readyAt ??= epochNow();\n}\n\nexport interface RequestTimings {\n received: number;\n phases: WorkerPhaseTiming[];\n}\n\nconst current = new AsyncLocalStorage<RequestTimings>();\n// The phase `fn` runs inside, so a nested one (models in action) names its parent.\nconst currentPhase = new AsyncLocalStorage<string>();\n\nexport function startRequestTimings(): RequestTimings {\n return { received: epochNow(), phases: [] };\n}\n\nexport function withRequestTimings<T>(\n timings: RequestTimings,\n fn: () => Promise<T>,\n): Promise<T> {\n return current.run(timings, fn);\n}\n\n// Records `fn` as a phase of the request being served, if any.\nexport async function timed<T>(\n name: string,\n fn: () => Promise<T>,\n attributes?: Record<string, string | boolean>,\n): Promise<T> {\n const timings = current.getStore();\n if (!timings) return fn();\n const parent = currentPhase.getStore();\n const start = epochNow();\n try {\n return await currentPhase.run(name, fn);\n } finally {\n timings.phases.push({\n name,\n start,\n end: epochNow(),\n ...(parent ? { parent } : {}),\n ...(attributes ? { attributes } : {}),\n });\n }\n}\n\nexport function finishRequestTimings(timings: RequestTimings): WorkerTimings {\n const boot = !bootReported && readyAt !== undefined;\n bootReported = true;\n const { rss, heapUsed, heapTotal, external } = process.memoryUsage();\n return {\n received: timings.received,\n sent: epochNow(),\n phases: timings.phases,\n memory: { rss, heapUsed, heapTotal, external },\n ...(boot ? { ready: readyAt } : {}),\n };\n}\n","// Worker child: loads piece bundles and executes actions in an isolated\n// process, so piece side-effects (TLS env poisoning, crashes) never reach the host.\nimport {\n buildActionContext,\n InMemoryConnectionsProvider,\n InMemoryKeyValueStore,\n UnsupportedContextMemberError,\n} from \"../context/action.js\";\nimport { RemoteKeyValueStore } from \"../context/remote-store.js\";\nimport { RemoteOutput } from \"../context/remote-output.js\";\nimport { captureConsole } from \"./logs.js\";\nimport { setHostCallTimeout } from \"./host-call.js\";\nimport {\n openWorkerReactor,\n type WorkerReactorSession,\n} from \"./reactor-provider.js\";\nimport type { ReactorOption } from \"../context/reactor-option.js\";\nimport {\n DocumentModelUnavailableError,\n ReactorAccessDeniedError,\n ReactorActionsFailedError,\n ReactorJobFailedError,\n ReactorJobPendingError,\n ReactorRequestClosedError,\n} from \"@powerhousedao/pieces-framework\";\nimport { jsonSafe } from \"./json-safe.js\";\nimport { formatPieceError } from \"@powerhousedao/pieces-framework/host\";\nimport { redactError, redactMessage } from \"./redact.js\";\nimport { readFile, stat } from \"node:fs/promises\";\nimport { buildCheckConnectionContext } from \"../context/check.js\";\nimport { DataUriFilesService, StagedFilesService } from \"../context/files.js\";\nimport { setMaxFileBytes } from \"../context/limits.js\";\nimport {\n normalizePropsValue,\n preparePropsValue,\n PropsValidationError,\n type NormalizeOptions,\n type PropsValidationErrors,\n} from \"../context/normalize.js\";\nimport {\n buildPropertyContext,\n findProperty,\n resolveDynamicProperty,\n} from \"../context/props.js\";\nimport { buildTriggerContext, runTriggerHook } from \"../context/trigger.js\";\nimport { buildDescriptor, describeProperties } from \"../descriptor.js\";\nimport { loadPiece, loadPieceFromDir, type LoadedPiece } from \"../loader.js\";\nimport {\n getActions,\n getTriggers,\n type ApPiece,\n type ApProperty,\n type ApTrigger,\n} from \"../types.js\";\nimport {\n authMethodFor,\n unsupportedAuth,\n unsupportedTrigger,\n UnsupportedPieceFeatureError,\n} from \"../unsupported.js\";\nimport { installEgressGuard, runWithEgressPolicy } from \"./egress.js\";\nimport { installTlsGuard } from \"./tls-guard.js\";\nimport {\n finishRequestTimings,\n markWorkerReady,\n startRequestTimings,\n timed,\n withRequestTimings,\n} from \"./timings.js\";\nimport type {\n StagedInput,\n PieceModuleRef,\n CheckConnectionMessage,\n CheckConnectionOutcome,\n DescribePieceMessage,\n ResolveOptionsMessage,\n RunMessage,\n SerializedPieceError,\n TriggerHookMessage,\n WorkerRequestMessage,\n WorkerResponse,\n} from \"./protocol.js\";\n\nconst loadedPieces = new Map<string, Promise<LoadedPiece>>();\n// One store per scope, alive for the worker's lifetime (in-memory phase:\n// state survives runs but not worker replacement).\nconst stores = new Map<string, InMemoryKeyValueStore>();\n\nfunction storeForScope(scope: string): InMemoryKeyValueStore {\n let store = stores.get(scope);\n if (!store) {\n store = new InMemoryKeyValueStore();\n stores.set(scope, store);\n }\n return store;\n}\n\n// The module this request names, and the cache key for it. A package piece\n// arrives as one file; a fetched bundle as the directory holding it.\nfunction pieceRefKey(ref: PieceModuleRef): string {\n const key = ref.entryPath ?? ref.bundleDir;\n if (!key) {\n throw new Error(\"Request names no piece module (entryPath or bundleDir)\");\n }\n return key;\n}\n\nfunction loadCached(ref: PieceModuleRef): Promise<LoadedPiece> {\n const key = pieceRefKey(ref);\n let loading = loadedPieces.get(key);\n const cached = loading !== undefined;\n if (!loading) {\n loading = ref.entryPath ? loadPiece(key) : loadPieceFromDir(key);\n loadedPieces.set(key, loading);\n }\n const loaded = loading;\n return timed(\"piece.load\", () => loaded, { \"piece.cached\": cached });\n}\n\n// The secret values this request carried, if any. Redacting here rather than\n// on the host means the host process never holds them in an error object.\nfunction redactValuesOf(message: WorkerRequestMessage): string[] {\n const request = message.request as { redactValues?: string[] };\n return request.redactValues ?? [];\n}\n\n// Reactor errors cross the RPC as plain Errors told apart by `name`.\nconst REACTOR_ERROR_NAMES = new Set<string>([\n DocumentModelUnavailableError,\n ReactorAccessDeniedError,\n ReactorActionsFailedError,\n ReactorJobFailedError,\n ReactorJobPendingError,\n ReactorRequestClosedError,\n]);\n\nfunction errorName(error: unknown, fallback: string | undefined): string {\n if (typeof error !== \"object\" || error === null) return fallback || \"Error\";\n const named = (error as { name?: unknown }).name;\n if (typeof named === \"string\" && REACTOR_ERROR_NAMES.has(named)) return named;\n return error.constructor.name || fallback || \"Error\";\n}\n\nfunction serializeError(\n error: unknown,\n values: string[] = [],\n): SerializedPieceError {\n const properties: Record<string, unknown> = {};\n if (typeof error === \"object\" && error !== null) {\n for (const key of Object.keys(error)) {\n properties[key] = jsonSafe((error as Record<string, unknown>)[key]);\n }\n }\n // The framework's own formatter first: it lifts an HTTP status, the request\n // and response, and a message out of an HTML error page. Redaction stays last.\n const {\n __apErrorVersion,\n message,\n errorName: formattedName,\n ...http\n } = formatPieceError(error);\n return {\n name: errorName(error, formattedName),\n message: redactMessage(message, { values }),\n properties: redactError(\n { ...properties, ...(jsonSafe(http) as Record<string, unknown>) },\n { values },\n ) as Record<string, unknown>,\n unsupportedMember:\n error instanceof UnsupportedContextMemberError ? error.member : undefined,\n ...(error instanceof UnsupportedPieceFeatureError\n ? { unsupportedFeature: error.feature }\n : {}),\n ...(error instanceof PropsValidationError\n ? { invalidProps: jsonSafe(error.errors) as PropsValidationErrors }\n : {}),\n };\n}\n\n// Read-and-clear the piece-set TLS override so each run reports its own poisoning.\nfunction consumeTlsFlag(): boolean {\n const poisoned = process.env.NODE_TLS_REJECT_UNAUTHORIZED === \"0\";\n delete process.env.NODE_TLS_REJECT_UNAUTHORIZED;\n return poisoned;\n}\n\n// The session's client under its declaration, for a run-time context.\nfunction reactorOption(\n session: WorkerReactorSession | undefined,\n): ReactorOption {\n if (!session) return {};\n return session.requireReactor === \"write\"\n ? { requireReactor: \"write\", reactor: session.client }\n : { requireReactor: \"read\", reactor: session.client };\n}\n\nasync function handleResolveOptions(\n message: ResolveOptionsMessage,\n): Promise<WorkerResponse> {\n const { request } = message;\n const { piece } = await loadCached(request);\n const block =\n request.kind === \"trigger\"\n ? getTriggers(piece)[request.actionName]\n : getActions(piece)[request.actionName];\n const session = await openWorkerReactor(\n request.reactor,\n (block as { requireReactor?: unknown } | undefined)?.requireReactor,\n );\n try {\n return await resolveOptions(message, piece, session);\n } finally {\n session?.close();\n }\n}\n\nasync function resolveOptions(\n message: ResolveOptionsMessage,\n piece: ApPiece,\n session: WorkerReactorSession | undefined,\n): Promise<WorkerResponse> {\n const { request } = message;\n const { context, touched } = buildPropertyContext({\n searchValue: request.searchValue,\n projectId: request.projectId,\n // Design-time default: an empty flows listing instead of a throwing stub.\n flows: { list: () => Promise.resolve({ data: [] }) },\n ...(session ? { reactor: session.client } : {}),\n });\n const refresherValues = {\n ...(request.auth !== undefined ? { auth: request.auth } : {}),\n ...request.refresherValues,\n };\n const prop = findProperty(\n piece,\n request.actionName,\n request.propName,\n request.kind,\n );\n const output = await resolveDynamicProperty({\n piece,\n actionName: request.actionName,\n kind: request.kind,\n propName: request.propName,\n refresherValues,\n context,\n });\n // DYNAMIC props() yields raw piece properties (with resolver functions);\n // the editor only ever sees descriptors, so translate before crossing IPC.\n const isDynamic =\n typeof prop.props === \"function\" && typeof prop.options !== \"function\";\n return {\n id: message.id,\n type: \"result\",\n output: isDynamic\n ? describeProperties(output as Record<string, ApProperty> | undefined)\n : jsonSafe(output),\n touched: [...touched],\n tlsPoisoned: consumeTlsFlag(),\n };\n}\n\n// Reads a FILE prop's attachment ref from the copy the host staged on disk.\n// The fork shares the filesystem with its parent, so this is what keeps a\n// 50 MB scan out of the IPC channel in both directions.\nfunction stagedInputOptions(\n inputs: StagedInput[] | undefined,\n): Pick<NormalizeOptions, \"resolveRef\" | \"openRef\"> {\n // An empty list is not the same as no list: it means the host has a store\n // and tried, so a FILE prop that still comes up short is told which\n // reference failed rather than that the context has no resolver.\n if (!inputs) return {};\n const byRef = new Map(inputs.map((input) => [input.ref, input]));\n const staged = (ref: string): StagedInput => {\n const input = byRef.get(ref);\n if (!input) throw new Error(`No staged file for reference \"${ref}\"`);\n if (input.error !== undefined) {\n throw new Error(`Could not read \"${ref}\": ${input.error}`);\n }\n return input;\n };\n return {\n resolveRef: async (ref: string) => {\n const input = staged(ref);\n return {\n data: await readFile(input.path),\n filename: input.fileName,\n contentType: input.contentType,\n };\n },\n openRef: async (ref: string) => {\n const input = staged(ref);\n return {\n path: input.path,\n size: (await stat(input.path)).size,\n filename: input.fileName,\n contentType: input.contentType,\n };\n },\n };\n}\n\n// The same refusal describe records, for a step or hook that reaches the\n// worker anyway: a workflow saved before the check, or built over the API.\nfunction assertRunnable(\n piece: ApPiece,\n pieceName: string,\n auth: unknown,\n trigger?: { name: string; trigger: ApTrigger },\n): void {\n // With several methods, the one this connection signs in with decides.\n const type = (auth as { type?: unknown } | null | undefined)?.type;\n const method =\n Array.isArray(piece.auth) && type !== undefined\n ? authMethodFor(piece.auth, type)\n : piece.auth;\n if (Array.isArray(piece.auth) && type !== undefined && !method) {\n throw new Error(\n `Piece \"${pieceName}\" has no ${String(type)} sign-in method for this connection`,\n );\n }\n const pieceFeature = unsupportedAuth(method);\n if (pieceFeature) {\n throw new UnsupportedPieceFeatureError(\n `Piece \"${pieceName}\"`,\n pieceFeature,\n );\n }\n const triggerFeature = trigger && unsupportedTrigger(trigger.trigger);\n if (triggerFeature) {\n throw new UnsupportedPieceFeatureError(\n `Trigger \"${trigger.name}\" of \"${pieceName}\"`,\n triggerFeature,\n );\n }\n}\n\nasync function handleRun(message: RunMessage): Promise<WorkerResponse> {\n const { request } = message;\n const { piece } = await loadCached(request);\n const action = getActions(piece)[request.actionName] as\n | ReturnType<typeof getActions>[string]\n | undefined;\n if (!action) {\n throw new Error(\n `No action \"${request.actionName}\" in ${pieceRefKey(request)}`,\n );\n }\n assertRunnable(piece, piece.displayName, request.auth);\n const files = request.stagingDir\n ? new StagedFilesService(request.stagingDir)\n : new DataUriFilesService();\n // A durable store answers every get/put over the call channel, so a write\n // survives this worker; without one the value lives only in this heap.\n const durableStore = request.durableStore\n ? new RemoteKeyValueStore()\n : undefined;\n const liveOutput = request.liveOutput ? new RemoteOutput() : undefined;\n const session = await timed(\"reactor.open\", () =>\n openWorkerReactor(request.reactor, action.requireReactor),\n );\n try {\n return await runAction(message, action, {\n files,\n durableStore,\n liveOutput,\n reactor: reactorOption(session),\n });\n } finally {\n session?.close();\n }\n}\n\nasync function runAction(\n message: RunMessage,\n action: ReturnType<typeof getActions>[string],\n services: {\n files: StagedFilesService | DataUriFilesService;\n durableStore: RemoteKeyValueStore | undefined;\n liveOutput: RemoteOutput | undefined;\n reactor: ReactorOption;\n },\n): Promise<WorkerResponse> {\n const { request } = message;\n const { files, durableStore, liveOutput, reactor } = services;\n // Before the props are normalised, not after: a processor that cannot coerce\n // says so on console.error, and the worker's stdio goes nowhere.\n const restoreConsole = request.captureLogs ? captureConsole() : undefined;\n const { context, touched } = buildActionContext({\n propsValue: await preparePropsValue(\n `action \"${request.actionName}\"`,\n action.props,\n request.propsValue,\n stagedInputOptions(request.stagedInputs),\n ),\n auth: request.auth,\n store:\n durableStore ??\n (request.storeScope ? storeForScope(request.storeScope) : undefined),\n files,\n connections: request.connections\n ? new InMemoryConnectionsProvider(request.connections)\n : undefined,\n output: liveOutput,\n ...reactor,\n resumePayload: request.resumePayload,\n executionType: request.executionType,\n identity: request.identity,\n });\n let output: unknown;\n try {\n // createAction defaults test to run; a plain-object action may have none.\n const method =\n request.stepTest && typeof action.test === \"function\"\n ? action.test\n : action.run;\n output = await timed(\"action\", () => method.call(action, context));\n } finally {\n restoreConsole?.();\n liveOutput?.close();\n }\n return {\n id: message.id,\n type: \"result\",\n output: jsonSafe(output),\n ...(files instanceof StagedFilesService && files.staged().length > 0\n ? { files: files.staged() }\n : {}),\n touched: [...touched],\n tlsPoisoned: consumeTlsFlag(),\n };\n}\n\nasync function handleTriggerHook(\n message: TriggerHookMessage,\n): Promise<WorkerResponse> {\n const { request } = message;\n const { piece } = await loadCached(request);\n const trigger = getTriggers(piece)[request.triggerName] as\n | ReturnType<typeof getTriggers>[string]\n | undefined;\n if (!trigger) {\n throw new Error(\n `No trigger \"${request.triggerName}\" in bundle ${request.bundleDir}`,\n );\n }\n // Teardown still runs, so a registration made before the check is released.\n if (request.hook !== \"onDisable\") {\n assertRunnable(piece, piece.displayName, request.auth, {\n name: request.triggerName,\n trigger,\n });\n }\n // The durable store answers every get/put over the call channel, so a long\n // onEnable checkpoints: registration ids survive a crash mid-hook.\n const snapshot = request.durableStore\n ? undefined\n : new InMemoryKeyValueStore(request.storeState);\n const runsPiece = request.hook === \"run\" || request.hook === \"test\";\n // Teardown is never refused: a config that no longer validates must still\n // release what onEnable registered.\n const propsValue =\n request.hook === \"onDisable\"\n ? await normalizePropsValue(trigger.props, request.propsValue)\n : await preparePropsValue(\n `trigger \"${request.triggerName}\"`,\n trigger.props,\n request.propsValue,\n );\n const session = await openWorkerReactor(\n request.reactor,\n trigger.requireReactor,\n );\n const handle = buildTriggerContext({\n propsValue,\n auth: request.auth,\n store: snapshot ?? new RemoteKeyValueStore(),\n hostPartitionedStore: request.durableStore,\n // Test hooks write under a separate prefix, never the live cursor.\n storePrefix: request.hook === \"test\" ? \"test\" : \"\",\n identity: request.identity,\n isRepublish: request.isRepublish,\n payload: request.payload,\n webhookUrl: request.webhookUrl,\n server: request.server,\n files: runsPiece ? new DataUriFilesService() : undefined,\n ...reactorOption(session),\n });\n let output: unknown;\n try {\n output = await runTriggerHook(trigger, request.hook, handle);\n } finally {\n session?.close();\n }\n return {\n id: message.id,\n type: \"result\",\n output: jsonSafe(output),\n touched: [...handle.touched],\n tlsPoisoned: consumeTlsFlag(),\n // Only the snapshot path has state to hand back; a durable store already\n // committed everything the hook wrote.\n ...(snapshot\n ? { storeState: jsonSafe(snapshot.snapshot()) as Record<string, unknown> }\n : {}),\n schedules: handle.schedules,\n listeners: handle.listeners,\n };\n}\n\n// What auth.validate and auth.getConnectionIdentifier are handed upstream: the\n// property values themselves, not the connection envelope an action receives.\nfunction authForValidate(auth: unknown): unknown {\n if (auth === null || typeof auth !== \"object\") return auth;\n const value = auth as Record<string, unknown>;\n switch (value.type) {\n case \"CUSTOM_AUTH\":\n return value.props;\n case \"SECRET_TEXT\":\n return value.secret_text;\n case \"BASIC_AUTH\":\n return { username: value.username, password: value.password };\n default:\n return auth;\n }\n}\n\n// `{ valid: false, error }` (or a bare `false`) fails the check.\nfunction fromValidateResult(\n result: unknown,\n): Pick<CheckConnectionOutcome, \"valid\" | \"detail\"> {\n if (result === false) return { valid: false };\n if (result === null || typeof result !== \"object\") return { valid: true };\n const value = result as { valid?: unknown; error?: unknown };\n if (value.valid !== false) return { valid: true };\n return {\n valid: false,\n ...(typeof value.error === \"string\" && value.error\n ? { detail: value.error }\n : {}),\n };\n}\n\n// Best-effort: a label failure is reported beside a passing check.\nasync function connectionIdentifier(\n getConnectionIdentifier: (context: unknown) => unknown,\n context: unknown,\n): Promise<Pick<CheckConnectionOutcome, \"accountLabel\" | \"identifierError\">> {\n try {\n const label = await getConnectionIdentifier(context);\n return typeof label === \"string\" && label !== \"\"\n ? { accountLabel: label }\n : {};\n } catch (error) {\n return {\n identifierError: error instanceof Error ? error.message : String(error),\n };\n }\n}\n\nasync function handleCheckConnection(\n message: CheckConnectionMessage,\n): Promise<WorkerResponse> {\n const { request } = message;\n const { piece } = await loadCached(request);\n // With several methods, the hooks are the ones of the connection's method.\n const auth = authMethodFor(\n (piece as { auth?: unknown }).auth,\n (request.auth as { type?: unknown } | null | undefined)?.type,\n ) as\n | {\n validate?: (context: unknown) => unknown;\n getConnectionIdentifier?: (context: unknown) => unknown;\n }\n | undefined;\n const validate = auth?.validate;\n const getConnectionIdentifier = auth?.getConnectionIdentifier;\n const { context, touched } = buildCheckConnectionContext({\n auth: authForValidate(request.auth),\n });\n let outcome: CheckConnectionOutcome =\n typeof validate === \"function\"\n ? { declared: true, ...fromValidateResult(await validate(context)) }\n : { declared: false, valid: true };\n if (outcome.valid && typeof getConnectionIdentifier === \"function\") {\n outcome = {\n ...outcome,\n ...(await connectionIdentifier(getConnectionIdentifier, context)),\n };\n }\n return {\n id: message.id,\n type: \"result\",\n output: outcome,\n touched: [...touched],\n tlsPoisoned: consumeTlsFlag(),\n };\n}\n\nasync function handleDescribe(\n message: DescribePieceMessage,\n): Promise<WorkerResponse> {\n const { request } = message;\n const { piece } = await loadCached(request);\n const descriptor = buildDescriptor(piece, {\n packageName: request.packageName,\n version: request.version,\n });\n return {\n id: message.id,\n type: \"result\",\n // A prop's defaultValue is piece-authored; jsonSafe keeps a non-cloneable\n // one from failing the IPC send.\n output: jsonSafe(descriptor),\n touched: [],\n tlsPoisoned: consumeTlsFlag(),\n };\n}\n\nfunction isWorkerMessage(value: unknown): value is WorkerRequestMessage {\n if (typeof value !== \"object\" || value === null) return false;\n const type = (value as { type?: unknown }).type;\n return (\n type === \"run\" ||\n type === \"resolve-options\" ||\n type === \"trigger-hook\" ||\n type === \"check-connection\" ||\n type === \"describe\"\n );\n}\n\nfunction dispatch(message: WorkerRequestMessage): Promise<WorkerResponse> {\n switch (message.type) {\n case \"run\":\n return handleRun(message);\n case \"resolve-options\":\n return handleResolveOptions(message);\n case \"trigger-hook\":\n return handleTriggerHook(message);\n case \"check-connection\":\n return handleCheckConnection(message);\n case \"describe\":\n return handleDescribe(message);\n }\n}\n\n// Called once by the child's entry, before any piece module is loaded.\nexport function startPieceWorker(): void {\n // A piece cannot then keep a pristine copy of the socket layer.\n installEgressGuard();\n // Nor switch certificate checks off for everyone (NODE_TLS_REJECT_UNAUTHORIZED=0)\n installTlsGuard();\n process.on(\"message\", onMessage);\n markWorkerReady();\n}\n\nfunction onMessage(message: unknown): void {\n if (!isWorkerMessage(message)) return;\n const timings = startRequestTimings();\n // Deferred so a synchronous throw — a malformed egress policy — becomes a\n // rejection the handler below reports, instead of killing the child.\n const handler = Promise.resolve().then(() => {\n setMaxFileBytes(message.request.maxFileBytes);\n setHostCallTimeout(\n message.request.hostCallTimeoutMs,\n message.request.deadline,\n );\n return withRequestTimings(timings, () =>\n runWithEgressPolicy(message.request.egress, () => dispatch(message)),\n );\n });\n handler\n .catch((error: unknown): WorkerResponse => ({\n id: message.id,\n type: \"error\",\n error: serializeError(error, redactValuesOf(message)),\n tlsPoisoned: consumeTlsFlag(),\n }))\n .then((response) =>\n process.send?.({ ...response, timings: finishRequestTimings(timings) }),\n )\n .catch(() => process.exit(1));\n}\n","// The reactor RPC on a piece child's IPC channel, bound to one request. It owns\n// only `reactor-rpc` envelopes carrying that request's id.\nimport {\n REACTOR_RPC,\n type ReactorRpcEnvelope,\n type ReactorRequestBinding,\n} from \"./protocol.js\";\nimport type { IPieceWorkerTransport } from \"./transport.js\";\n\n// Structurally `IRpcTransport` from `@powerhousedao/reactor/rpc`.\nexport interface ReactorRpcTransport {\n post(message: never): void;\n onMessage(listener: (message: never) => void): () => void;\n close(): void;\n}\n\n// Serves ctx.reactor for one request; `open` returns the stop run when it settles.\nexport interface ReactorTap {\n requireReactor: ReactorRequestBinding[\"requireReactor\"];\n open(\n transport: ReactorRpcTransport,\n request: { requestId: string; deadline: number },\n ): () => void;\n}\n\nexport function isReactorRpcEnvelope(\n value: unknown,\n requestId: string,\n): value is ReactorRpcEnvelope {\n if (typeof value !== \"object\" || value === null) return false;\n const envelope = value as Partial<ReactorRpcEnvelope>;\n return envelope.type === REACTOR_RPC && envelope.requestId === requestId;\n}\n\nfunction isRpcMessage(value: unknown): boolean {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as { k?: unknown }).k === \"string\"\n );\n}\n\n// The host's end. The child runs piece code: another request's id, or a\n// message without a kind, is dropped.\nexport function createIpcTransport(\n worker: IPieceWorkerTransport,\n requestId: string,\n): ReactorRpcTransport {\n let closed = false;\n const detachers = new Set<() => void>();\n return {\n post(message: unknown) {\n if (closed || !worker.connected) return;\n worker.send({ type: REACTOR_RPC, requestId, message });\n },\n onMessage(listener: (message: never) => void) {\n const handler = (value: unknown) => {\n if (closed || !isReactorRpcEnvelope(value, requestId)) return;\n if (!isRpcMessage(value.message)) return;\n listener(value.message as never);\n };\n worker.on(\"message\", handler);\n const detach = () => {\n worker.off(\"message\", handler);\n detachers.delete(detach);\n };\n detachers.add(detach);\n return detach;\n },\n close() {\n closed = true;\n for (const detach of [...detachers]) detach();\n },\n };\n}\n","// `ctx.reactor` in the piece child: a reactor RPC proxy per request, with a\n// local registry fed by the host's manifest and, on a miss, a host lookup.\nimport {\n DocumentModelUnavailableError,\n ReactorAccessDeniedError,\n ReactorRequestClosedError,\n type DriveReadMethods,\n type DriveWriteMethods,\n type ReactorClient,\n type ReactorReadClient,\n type RefusedDriveMethods,\n type RequireReactor,\n} from \"@powerhousedao/pieces-framework\";\nimport type {\n IDocumentModelRegistry,\n IReactorClient,\n ModelManifestEntry,\n} from \"@powerhousedao/reactor\";\nimport type {\n createReactorClientProxy,\n IRpcTransport,\n MessageRouter,\n RpcMessage,\n} from \"@powerhousedao/reactor/rpc\";\nimport type { DocumentModelModule, PHDocument } from \"document-model\";\nimport { flushCompileCache } from \"node:module\";\nimport { callHost } from \"../pieces/activepieces/worker/host-call.js\";\nimport {\n MODEL_ENTRIES,\n MODEL_MANIFEST,\n REACTOR_RPC,\n type ModelEntriesPayload,\n type ModelManifestMessage,\n type ReactorRequestBinding,\n} from \"../pieces/activepieces/worker/protocol.js\";\nimport {\n installReactorProvider,\n type WorkerReactorSession,\n} from \"../pieces/activepieces/worker/reactor-provider.js\";\nimport { isReactorRpcEnvelope } from \"../pieces/activepieces/worker/reactor-rpc.js\";\nimport { timed } from \"../pieces/activepieces/worker/timings.js\";\n\nfunction named(name: string, message: string, cause?: unknown): Error {\n const error = new Error(message, cause === undefined ? {} : { cause });\n error.name = name;\n return error;\n}\n\n// --- Model manifest ------------------------------------------------------\n\nconst manifest = new Map<string, ModelManifestEntry[]>();\n// Per document type; dropped when a new entry for the type arrives.\nconst loading = new Map<string, Promise<void>>();\n// Host lookups in flight, per type; `undefined` asks for every entry.\nconst lookups = new Map<string | undefined, Promise<void>>();\n\nfunction isManifestEntry(value: unknown): value is ModelManifestEntry {\n if (typeof value !== \"object\" || value === null) return false;\n const entry = value as Record<string, unknown>;\n return (\n typeof entry.documentType === \"string\" &&\n typeof entry.spec === \"object\" &&\n entry.spec !== null\n );\n}\n\nexport function addManifestEntries(entries: unknown[]): void {\n for (const entry of entries) {\n if (!isManifestEntry(entry)) continue;\n const known = manifest.get(entry.documentType) ?? [];\n if (known.some((other) => other.version === entry.version)) continue;\n manifest.set(entry.documentType, [...known, entry]);\n loading.delete(entry.documentType);\n }\n}\n\n// Misses are not cached: the host may load the type before the next lookup.\nfunction lookUpEntries(documentType?: string): Promise<void> {\n let pending = lookups.get(documentType);\n if (!pending) {\n const payload: ModelEntriesPayload =\n documentType === undefined ? {} : { documentType };\n pending = callHost<unknown>(MODEL_ENTRIES, payload)\n .then((entries) => {\n if (Array.isArray(entries)) addManifestEntries(entries);\n })\n .finally(() => lookups.delete(documentType));\n lookups.set(documentType, pending);\n }\n return pending;\n}\n\nfunction isManifestMessage(value: unknown): value is ModelManifestMessage {\n return (\n typeof value === \"object\" &&\n value !== null &&\n (value as { type?: unknown }).type === MODEL_MANIFEST &&\n Array.isArray((value as { entries?: unknown }).entries)\n );\n}\n\n// --- Reactor runtime, imported on first use ------------------------------\n\nexport interface Runtime {\n rpc: {\n MessageRouter: typeof MessageRouter;\n createReactorClientProxy: typeof createReactorClientProxy;\n };\n loadSpec: (spec: ModelManifestEntry[\"spec\"]) => Promise<DocumentModelModule>;\n registry: IDocumentModelRegistry;\n versionOf: (document: PHDocument) => number;\n}\n\nlet runtime: Promise<Runtime> | undefined;\n\nfunction reactorRuntime(): Promise<Runtime> {\n // Deep entries, not the package barrels, which load storage, zod and crypto.\n runtime ??= Promise.all([\n import(\"@powerhousedao/reactor/rpc\"),\n import(\"@powerhousedao/shared/document-model/version\"),\n ]).then(([rpc, model]) => {\n // Persisted now: the child is SIGKILLed, never exiting cleanly.\n flushCompileCache();\n return {\n rpc,\n loadSpec: rpc.loadDocumentModelSpec,\n registry: new rpc.DocumentModelRegistry(),\n // The version the reactor resolves a document's module by.\n versionOf: (document: PHDocument) =>\n model.normalizeDocumentModelVersion(\n (document.state as Partial<PHDocument[\"state\"]>).document?.version,\n ),\n };\n });\n return runtime;\n}\n\nfunction unavailable(documentType: string, cause?: unknown): Error {\n return named(\n DocumentModelUnavailableError,\n cause === undefined\n ? `No document model for \"${documentType}\" is available to this piece`\n : `The document model for \"${documentType}\" could not be loaded: ${cause instanceof Error ? cause.message : JSON.stringify(cause)}`,\n cause,\n );\n}\n\n// Asks the host when the type, or the version a document needs, is not local.\n// Timed only when it starts a lookup or an import, not on every call.\nfunction ensureType(\n rt: Runtime,\n documentType: string,\n version?: number,\n): Promise<void> {\n const load = () => loadType(rt, documentType, version);\n return missingLocally(documentType, version) || !loading.has(documentType)\n ? timed(\"models\", load, { \"document.type\": documentType })\n : load();\n}\n\nfunction missingLocally(documentType: string, version?: number): boolean {\n const local = manifest.get(documentType) ?? [];\n return (\n local.length === 0 ||\n (version !== undefined &&\n !local.some((entry) => entry.version === String(version)))\n );\n}\n\nasync function loadType(\n rt: Runtime,\n documentType: string,\n version?: number,\n): Promise<void> {\n if (missingLocally(documentType, version)) {\n try {\n await lookUpEntries(documentType);\n } catch (error) {\n throw unavailable(documentType, error);\n }\n }\n const entries = manifest.get(documentType);\n if (!entries || entries.length === 0) throw unavailable(documentType);\n let pending = loading.get(documentType);\n if (!pending) {\n pending = Promise.all(entries.map((entry) => rt.loadSpec(entry.spec))).then(\n (modules) => {\n // Duplicates of versions already registered are skipped.\n rt.registry.registerModules(...modules);\n },\n );\n loading.set(documentType, pending);\n pending.catch(() => {\n if (loading.get(documentType) === pending) loading.delete(documentType);\n });\n }\n try {\n await pending;\n } catch (error) {\n throw unavailable(documentType, error);\n }\n}\n\nfunction moduleOf(\n documentType: string,\n lookup: () => Promise<DocumentModelModule>,\n): Promise<DocumentModelModule> {\n return lookup().catch((error: unknown) => {\n if (error instanceof Error && error.name === \"ModuleNotFoundError\") {\n throw unavailable(documentType);\n }\n throw error;\n });\n}\n\n// --- One request ---------------------------------------------------------\n\nfunction processTransport(requestId: string): IRpcTransport {\n let closed = false;\n const detachers = new Set<() => void>();\n return {\n post(message: RpcMessage) {\n if (closed) throw requestClosed();\n process.send?.({ type: REACTOR_RPC, requestId, message });\n },\n onMessage(listener) {\n const handler = (value: unknown) => {\n if (closed || !isReactorRpcEnvelope(value, requestId)) return;\n listener(value.message as RpcMessage);\n };\n process.on(\"message\", handler);\n const detach = () => {\n process.off(\"message\", handler);\n detachers.delete(detach);\n };\n detachers.add(detach);\n return detach;\n },\n close() {\n closed = true;\n for (const detach of [...detachers]) detach();\n },\n };\n}\n\nfunction requestClosed(): Error {\n return named(\n ReactorRequestClosedError,\n \"This ctx.reactor belongs to a step that has finished; use the ctx.reactor of the running step\",\n );\n}\n\ntype AnyMethod = (...args: unknown[]) => unknown;\n\n// Calls fail with ReactorRequestClosedError once the request settles, pages too.\nexport class RequestGuard {\n private closed = false;\n private rejectClosed: (error: Error) => void = () => undefined;\n private readonly whenClosed = new Promise<never>((_, reject) => {\n this.rejectClosed = reject;\n });\n\n constructor() {\n this.whenClosed.catch(() => undefined);\n }\n\n call<T>(run: () => Promise<T> | T): Promise<T> {\n if (this.closed) return Promise.reject(requestClosed());\n let result: Promise<T>;\n try {\n result = Promise.resolve(run());\n } catch (error) {\n return Promise.reject(error as Error);\n }\n return Promise.race([\n result.then((value) => this.paged(value)),\n this.whenClosed,\n ]);\n }\n\n close(): void {\n this.closed = true;\n this.rejectClosed(requestClosed());\n }\n\n private paged<T>(value: T): T {\n if (typeof value !== \"object\" || value === null) return value;\n const next = (value as { next?: unknown }).next;\n if (typeof next !== \"function\") return value;\n return {\n ...value,\n next: () => this.call(() => (next as AnyMethod).call(value)),\n };\n }\n}\n\nconst SERVED_DRIVES: Record<DriveReadMethods | DriveWriteMethods, true> = {\n getNode: true,\n listNodes: true,\n addFile: true,\n addFolder: true,\n};\n\nconst REFUSED_DRIVES: Record<RefusedDriveMethods, true> = {\n create: true,\n removeNode: true,\n renameNode: true,\n moveNode: true,\n copyNode: true,\n setPreferredEditorOnNode: true,\n};\n\n// As the host's served facade: the served methods go over RPC as `drives.*`,\n// the refused ones throw here with the error the host would answer.\nfunction sessionDrives(\n proxy: IReactorClient,\n guard: RequestGuard,\n): ReactorClient[\"drives\"] {\n const remote = proxy.drives as unknown as Record<string, AnyMethod>;\n const drives = Object.create(null) as Record<string, AnyMethod>;\n for (const name of Object.keys(SERVED_DRIVES)) {\n drives[name] = (...args) => guard.call(() => remote[name](...args));\n }\n for (const name of Object.keys(REFUSED_DRIVES)) {\n drives[name] = () => {\n throw named(\n ReactorAccessDeniedError,\n `drives.${name} is not available to workflow pieces`,\n );\n };\n }\n return drives as unknown as ReactorClient[\"drives\"];\n}\n\nexport function sessionClient(\n rt: Runtime,\n proxy: IReactorClient,\n guard: RequestGuard,\n): ReactorClient {\n const local: Record<string, AnyMethod> = {\n getDocumentModelModule: (documentType) =>\n guard.call(async () => {\n const type = String(documentType);\n await ensureType(rt, type);\n return moduleOf(type, () => proxy.getDocumentModelModule(type));\n }),\n getDocumentModelModuleForDocument: (document) =>\n guard.call(async () => {\n const type = (document as PHDocument).header.documentType;\n await ensureType(rt, type, rt.versionOf(document as PHDocument));\n return moduleOf(type, () =>\n proxy.getDocumentModelModuleForDocument(document as PHDocument),\n );\n }),\n getDocumentModelModules: (namespace, paging) =>\n guard.call(async () => {\n await lookUpEntries();\n // A type that fails to load is left out of the listing, not fatal.\n for (const documentType of manifest.keys()) {\n await ensureType(rt, documentType).catch((error: unknown) => {\n console.warn(error instanceof Error ? error.message : error);\n });\n }\n return proxy.getDocumentModelModules(\n namespace as string | undefined,\n paging as never,\n );\n }),\n subscribe: () => {\n throw named(\n ReactorAccessDeniedError,\n 'Reactor method \"subscribe\" is not offered to pieces',\n );\n },\n };\n const drives = sessionDrives(proxy, guard);\n // Every listed method resolves through `get`.\n return new Proxy({} as ReactorClient, {\n get: (_target, prop) => {\n if (typeof prop !== \"string\" || prop === \"then\") return undefined;\n if (prop === \"drives\") return drives;\n if (prop in local) return local[prop];\n return (...args: unknown[]) =>\n guard.call(() =>\n (proxy as unknown as Record<string, AnyMethod>)[prop](...args),\n );\n },\n });\n}\n\nasync function openSession(\n binding: ReactorRequestBinding,\n requireReactor: RequireReactor,\n): Promise<WorkerReactorSession> {\n const rt = await reactorRuntime();\n const transport = processTransport(binding.requestId);\n const router = new rt.rpc.MessageRouter(\"w\");\n router.attach(transport);\n const proxy = rt.rpc.createReactorClientProxy(router, {\n registry: rt.registry,\n });\n const guard = new RequestGuard();\n const client = sessionClient(rt, proxy, guard);\n const close = () => {\n guard.close();\n router.detach();\n transport.close();\n };\n // The host refuses a write a read declaration makes; the type says so first.\n return requireReactor === \"write\"\n ? { requireReactor, client, close }\n : { requireReactor, client: client as ReactorReadClient, close };\n}\n\nlet installed = false;\n\n// Before the first request: the boot manifest is sent as the child forks.\nexport function installWorkerReactor(): void {\n if (installed) return;\n installed = true;\n process.on(\"message\", (message: unknown) => {\n if (isManifestMessage(message)) addManifestEntries(message.entries);\n });\n installReactorProvider(openSession);\n}\n","// The piece child's entry: the piece worker, plus ctx.reactor over the reactor\n// RPC. Both listeners go on in this one synchronous evaluation.\nimport { flushCompileCache } from \"node:module\";\nimport { startPieceWorker } from \"../pieces/activepieces/worker/entry.js\";\nimport { installWorkerReactor } from \"./reactor.js\";\n\nstartPieceWorker();\ninstallWorkerReactor();\n// The host SIGKILLs a child, which skips the exit that writes NODE_COMPILE_CACHE.\nflushCompileCache();\n\n// --cpu-prof writes on exit, which SIGTERM's default action skips.\nif (process.execArgv.includes(\"--cpu-prof\")) {\n process.once(\"SIGTERM\", () => process.exit(0));\n}\n"],"x_google_ignoreList":[2,3,4,5,6,7,8,9,10,11,12,16,27,28,29,30],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,IAAa,gCAAb,cAAmD,MAAM;CACvD;CAEA,YAAY,QAAgB;EAC1B,MACE,4CAA4C,OAAO,wEAErD;EACA,KAAK,OAAO;EACZ,KAAK,SAAS;CAChB;AACF;AAIA,SAAgB,aAAa,YAA6B;CACxD,OAAO,IAAI,MAAM,SAAS,OAAO,CAAC,GAAG;EACnC,IAAI,SAAS,MAAM;GAEjB,IAAI,OAAO,SAAS,YAAY,SAAS,QAAQ,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