@go-labs-sg/bb 3.19.0 → 3.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../node_modules/.bun/dotenv@18.0.10/node_modules/dotenv/dist/index.cjs", "../src/load-env.ts", "../../../cli-auth/src/client/credential-store.ts", "../../../cli-auth/src/protocol/constants.ts", "../../../cli-auth/src/protocol/crypto.ts", "../../../../node_modules/.bun/zod@4.6.7/node_modules/zod/v4/core/util.js", "../../../../node_modules/.bun/zod@4.6.7/node_modules/zod/v4/core/core.js", "../../../../node_modules/.bun/zod@4.6.7/node_modules/zod/v4/core/errors.js", "../../../../node_modules/.bun/zod@4.6.7/node_modules/zod/v4/core/parse.js", "../../../../node_modules/.bun/zod@4.6.7/node_modules/zod/v4/core/regexes.js", "../../../../node_modules/.bun/zod@4.6.7/node_modules/zod/v4/core/checks.js", "../../../../node_modules/.bun/zod@4.6.7/node_modules/zod/v4/core/doc.js", "../../../../node_modules/.bun/zod@4.6.7/node_modules/zod/v4/core/versions.js", "../../../../node_modules/.bun/zod@4.6.7/node_modules/zod/v4/core/schemas.js", "../../../../node_modules/.bun/zod@4.6.7/node_modules/zod/v4/core/memoizer.js", "../../../../node_modules/.bun/zod@4.6.7/node_modules/zod/v4/locales/en.js", "../../../../node_modules/.bun/zod@4.6.7/node_modules/zod/v4/core/registries.js", "../../../../node_modules/.bun/zod@4.6.7/node_modules/zod/v4/core/api.js", "../../../../node_modules/.bun/zod@4.6.7/node_modules/zod/v4/core/to-json-schema.js", "../../../../node_modules/.bun/zod@4.6.7/node_modules/zod/v4/core/json-schema-processors.js", "../../../../node_modules/.bun/zod@4.6.7/node_modules/zod/v4/classic/errors.js", "../../../../node_modules/.bun/zod@4.6.7/node_modules/zod/v4/classic/parse.js", "../../../../node_modules/.bun/zod@4.6.7/node_modules/zod/v4/classic/schemas.js", "../../../cli-auth/src/protocol/schemas.ts", "../../../cli-auth/src/client/secret-backend.ts", "../../../cli-auth/src/client/runtime.ts", "../../../cli-auth/src/client/storage-error.ts", "../../../cli-auth/src/client/login.ts", "../src/cli.ts", "../../utils/src/data-table-sort-keys.ts", "../../db/src/generated/prisma/enums.ts", "../../utils/src/filter-enums.ts", "../src/cli-trace.ts", "../src/config.ts", "../../../../node_modules/.bun/@trpc+server@11.28.3+431a08decb845963/node_modules/@trpc/server/dist/observable-CodTG6Sf.mjs", "../../../../node_modules/.bun/@trpc+server@11.28.3+431a08decb845963/node_modules/@trpc/server/dist/observable-BjUZYMQq.mjs", "../../../../node_modules/.bun/@trpc+client@11.28.3+82479501839ae062/node_modules/@trpc/client/dist/splitLink-PFsRy7Mf.mjs", "../../../../node_modules/.bun/@trpc+client@11.28.3+82479501839ae062/node_modules/@trpc/client/dist/objectSpread2-pyA4QVO4.mjs", "../../../../node_modules/.bun/@trpc+server@11.28.3+431a08decb845963/node_modules/@trpc/server/dist/codes-BCsCCyMj.mjs", "../../../../node_modules/.bun/@trpc+server@11.28.3+431a08decb845963/node_modules/@trpc/server/dist/getErrorShape-CVrl8_-w.mjs", "../../../../node_modules/.bun/@trpc+server@11.28.3+431a08decb845963/node_modules/@trpc/server/dist/asyncGeneratorDelegate-BRQGtkYG.mjs", "../../../../node_modules/.bun/@trpc+client@11.28.3+82479501839ae062/node_modules/@trpc/client/dist/TRPCClientError-DE6-fd1n.mjs", "../../../../node_modules/.bun/@trpc+client@11.28.3+82479501839ae062/node_modules/@trpc/client/dist/unstable-internals.mjs", "../../../../node_modules/.bun/@trpc+client@11.28.3+82479501839ae062/node_modules/@trpc/client/dist/httpUtils-CtMuyl9j.mjs", "../../../../node_modules/.bun/@trpc+client@11.28.3+82479501839ae062/node_modules/@trpc/client/dist/httpBatchLink-BkVNtNND.mjs", "../../../../node_modules/.bun/@trpc+client@11.28.3+82479501839ae062/node_modules/@trpc/client/dist/links/loggerLink.mjs", "../../../../node_modules/.bun/@trpc+client@11.28.3+82479501839ae062/node_modules/@trpc/client/dist/wsLink-BiIe_j6D.mjs", "../../../../node_modules/.bun/@trpc+client@11.28.3+82479501839ae062/node_modules/@trpc/client/dist/index.mjs", "../src/api-client.ts", "../src/prisma-enums.ts", "../src/commands/index.ts", "../src/runtime/error.ts", "../src/budget-create-outcome.ts", "../src/commands/invoice-splits.ts", "../../utils/src/customer-invoice-approval-policy.ts", "../../utils/src/customer-invoice-lifecycle.ts", "../src/parse-cli-enums.ts", "../../validators/src/quickbooks/qbo-name.ts", "../../utils/src/rich-text.ts", "../src/rich-text.ts", "../src/parse-mutation-payload.ts", "../src/runtime/confirmation.ts", "../src/runtime/sanitize.ts", "../src/runtime/output.ts", "../src/runtime/process-runtime.ts", "../src/runtime/session.ts", "../src/parse-args.ts", "../src/parse-json-flag.ts", "../src/registry/payload-help.ts", "../src/registry/index.ts", "../src/index.ts"],
4
+ "sourcesContent": ["var j=(e,n)=>()=>{try{return n||e((n={exports:{}}).exports,n),n.exports}catch(t){throw n=0,t}};var R=j((Z,N)=>{function T(e){return typeof e==\"string\"?![\"false\",\"0\",\"no\",\"off\",\"\"].includes(e.toLowerCase()):!!e}function U(e=process.env){let n={};for(let t of[\"ENCODING\",\"PATH\",\"QUIET\",\"DEBUG\",\"OVERRIDE\",\"FAST\"]){let r=e[`DOTENV_${t}`]!=null?e[`DOTENV_${t}`]:e[`DOTENV_CONFIG_${t}`];r!=null&&(n[t.toLowerCase()]=t===\"ENCODING\"||t===\"PATH\"?r:T(r))}return n}N.exports={parseBoolean:T,optionsFromEnv:U}});var P=j((ee,b)=>{var F=require(\"fs\"),_=require(\"path\"),B=require(\"os\"),{URL:L,fileURLToPath:Q}=require(\"url\"),{parseBoolean:$,optionsFromEnv:I}=R(),G=/(?:^|^)\\s*(?:export\\s+)?([\\w.-]+)(?:\\s*=\\s*?|:\\s+?)(\\s*'(?:\\\\'|[^'])*'|\\s*\"(?:\\\\\"|[^\"])*\"|\\s*`(?:\\\\`|[^`])*`|[^#\\r\\n]+)?\\s*(?:#.*)?(?:$|$)/mg,y=new Uint8Array(256);for(let e=48;e<=57;e++)y[e]=1;for(let e=65;e<=90;e++)y[e]=1;for(let e=97;e<=122;e++)y[e]=1;y[45]=1;y[46]=1;y[95]=1;function H(e){let n={},t=e.toString();t=t.replace(/\\r\\n?/mg,`\n`);let r;for(;(r=G.exec(t))!=null;){let o=r[1],i=r[2]||\"\";i=i.trim();let c=i[0];i=i.replace(/^(['\"`])([\\s\\S]*)\\1$/mg,\"$2\"),c==='\"'&&(i=i.replace(/\\\\n/g,`\n`),i=i.replace(/\\\\r/g,\"\\r\")),n[o]=i}return n}function g(e){return e<=32?e===32||e>=9&&e<=13:e>=160&&(e===160||e===5760||e>=8192&&e<=8202||e===8232||e===8233||e===8239||e===8287||e===12288||e===65279)}function O(e){return e===10||e===8232||e===8233}function V(e){let n={},t=typeof e==\"string\"?e:e.toString();t.indexOf(\"\\r\")!==-1&&(t=t.replace(/\\r\\n?/g,`\n`));let r=t.length,o=0;for(;o<r;){let i=t.charCodeAt(o);for(;o<r&&g(i);)o++,i=t.charCodeAt(o);if(o>=r)break;if(i===35){for(;o<r&&!O(t.charCodeAt(o));)o++;continue}let c=-1;if(i===101&&o+6<r&&t.charCodeAt(o+1)===120&&t.charCodeAt(o+2)===112&&t.charCodeAt(o+3)===111&&t.charCodeAt(o+4)===114&&t.charCodeAt(o+5)===116){let u=t.charCodeAt(o+6);if(g(u)){let s=o+7;for(;s<r&&g(t.charCodeAt(s));)s++;y[t.charCodeAt(s)]&&(c=o+6,o=s)}else i=t.charCodeAt(o)}let E=o,p=0;for(;o<r&&(p=t.charCodeAt(o),y[p]);)o++;if(o===E){for(;o<r&&!O(t.charCodeAt(o));)o++;continue}let k=t.slice(E,o),D=o;if(o>=r&&(p=0),g(p))do o++,p=o<r?t.charCodeAt(o):0;while(g(p));if(p===61)o++;else if(p===58&&o===D&&o+1<r&&g(t.charCodeAt(o+1)))o+=2;else{for(o=c===-1?D:c;o<r&&!O(t.charCodeAt(o));)o++;continue}let d=o,l=o;for(;l<r&&g(t.charCodeAt(l));)l++;let C=t.charCodeAt(l),a,q=!1;if(C===39||C===34||C===96){let u=t[l],s=t.indexOf(u,l+1),f=-1,h=-1;for(;s!==-1;){let x=t.charCodeAt(s-1)===92,w=s+1;for(;w<r&&!O(t.charCodeAt(w))&&g(t.charCodeAt(w));)w++;if((w===r||O(t.charCodeAt(w))||t.charCodeAt(w)===35)&&(f=s,h=w),!x)break;s=t.indexOf(u,s+1)}if(f!==-1){if(a=t.slice(l+1,f),o=h,t.charCodeAt(o)===35)for(;o<r&&!O(t.charCodeAt(o));)o++;q=!0}}if(!q){let u=t.indexOf(`\n`,d);u===-1&&(u=r);let s;if(r<4096)s=t.indexOf(\"#\",d),(s===-1||s>u)&&(s=u);else for(s=d;s<u&&t.charCodeAt(s)!==35;)s++;let f=d,h=s;for(;f<h&&g(t.charCodeAt(f));)f++;for(;h>f&&g(t.charCodeAt(h-1));)h--;let x=t.charCodeAt(f);if(a=t.slice(f,h),a.includes(\"\\u2028\")||a.includes(\"\\u2029\")?a=a.replace(/^(['\"`])([\\s\\S]*)\\1$/mg,\"$2\"):h-f>=2&&(x===39||x===34||x===96)&&t.charCodeAt(h-1)===x&&(a=t.slice(f+1,h-1)),o=s,s<u)for(;o<r&&!O(t.charCodeAt(o));)o++}C===34&&(q||l<o)&&a.indexOf(\"\\\\\")!==-1&&(a=a.replace(/\\\\n/g,`\n`).replace(/\\\\r/g,\"\\r\")),n[k]=a}return n}function J(e,n){return n&&$(n.fast)?V(e):H(e)}function v(e){console.log(`\\u2506 ${e}`)}function W(e){console.error(`\\u25C7 ${e}`)}function S(e){return e[0]===\"~\"?_.join(B.homedir(),e.slice(1)):e}function K(e={}){let n={...e};for(let t of Object.keys(n))n[t]===void 0&&delete n[t];return{...I(),...n}}function M(e){e=K(e);let n=_.resolve(process.cwd(),\".env\"),t=\"utf8\",r=process.env;e&&e.processEnv!=null&&(r=e.processEnv);let o=$(e&&e.debug);e&&e.encoding?t=e.encoding:o&&v(\"no encoding is specified (UTF-8 is used by default)\");let i=[n];if(e&&e.path)if(!Array.isArray(e.path))i=[S(e.path)];else{i=[];for(let d of e.path)i.push(S(d))}let c,E={},p={fast:e.fast};for(let d of i)try{let l=A.parse(F.readFileSync(d,{encoding:t}),p);A.populate(E,l,e)}catch(l){o&&v(`failed to load ${d} ${l.message}`),c=l}let k=A.populate(r,E,e),D=$(Object.prototype.hasOwnProperty.call(e,\"quiet\")?e.quiet:I(r).quiet);if(o||!D){let d=Object.keys(k).length,l=[];for(let C of i)try{let a=_.relative(process.cwd(),C instanceof L?Q(C):C);l.push(a)}catch(a){o&&v(`failed to load ${C} ${a.message}`),c=a}W(`injected env (${d}) from ${l.join(\",\")}`)}return c?{parsed:E,error:c}:{parsed:E}}function Y(e){return A.configDotenv(e)}function z(e,n,t={}){let r=$(t&&t.debug),o=$(t&&t.override),i={};if(e===null||typeof e!=\"object\"||n===null||typeof n!=\"object\"){let c=new Error(\"OBJECT_REQUIRED: Please check the processEnv argument being passed to populate\");throw c.code=\"OBJECT_REQUIRED\",c}for(let c of Object.keys(n))Object.prototype.hasOwnProperty.call(e,c)?(o===!0&&(e[c]=n[c],i[c]=n[c]),r&&v(o===!0?`\"${c}\" is already defined and WAS overwritten`:`\"${c}\" is already defined and was NOT overwritten`)):(e[c]=n[c],i[c]=n[c]);return i}var A={configDotenv:M,config:Y,parse:J,populate:z};b.exports.configDotenv=A.configDotenv;b.exports.config=A.config;b.exports.parse=A.parse;b.exports.populate=A.populate;b.exports=A});var m=P();module.exports=m;module.exports.config=m.config;module.exports.configDotenv=m.configDotenv;module.exports.parse=m.parse;module.exports.populate=m.populate;\n", "/**\n * Load .env from current working directory so BB_API_KEY is available.\n */\nimport path from \"node:path\";\nimport { config } from \"dotenv\";\n\nif (process.env.GO_LABS_CLI_SKIP_DOTENV !== \"1\") {\n\tconfig({ path: path.resolve(process.cwd(), \".env\"), quiet: true });\n}\n", "import { createHash, randomUUID } from \"node:crypto\";\nimport {\n\tchmod,\n\tlstat,\n\tmkdir,\n\topen,\n\treadFile,\n\tstat,\n\tunlink,\n} from \"node:fs/promises\";\nimport { userInfo } from \"node:os\";\nimport { join } from \"node:path\";\nimport type {\n\tCliProduct,\n\tStoredCliCredentials,\n} from \"@go-labs/cli-auth/protocol\";\nimport { storedCliCredentialsSchema } from \"@go-labs/cli-auth/protocol\";\nimport { createIsolatedBunSecrets } from \"./secret-backend\";\nimport {\n\tCliCredentialStoreUnavailableError,\n\ttype CredentialStoreFailure,\n\tclassifyCredentialStoreFailure,\n} from \"./storage-error\";\n\nexport { CliCredentialStoreUnavailableError } from \"./storage-error\";\n\nexport interface SecretsApi {\n\tdelete(input: { name: string; service: string }): Promise<boolean>;\n\tget(input: { name: string; service: string }): Promise<string | null>;\n\tset(input: { name: string; service: string; value: string }): Promise<void>;\n}\n\nexport interface CliCredentialStore {\n\tpreflight?(): Promise<void>;\n\tdelete(): Promise<void>;\n\tget(): Promise<StoredCliCredentials | null>;\n\tset(credentials: StoredCliCredentials): Promise<void>;\n\twithCredentialLock?<Result>(\n\t\toperation: () => Promise<Result>,\n\t): Promise<Result>;\n}\n\nconst runSecretOperation = async <Result>(\n\tproduct: CliProduct,\n\toperation: () => Promise<Result>,\n\tfallback: CredentialStoreFailure = \"read-failed\",\n): Promise<Result> => {\n\ttry {\n\t\treturn await operation();\n\t} catch (cause) {\n\t\tif (cause instanceof CliCredentialStoreUnavailableError) throw cause;\n\t\tthrow new CliCredentialStoreUnavailableError(\n\t\t\tproduct,\n\t\t\tclassifyCredentialStoreFailure(\n\t\t\t\tcause instanceof Error ? cause.message : \"\",\n\t\t\t\tfallback,\n\t\t\t),\n\t\t);\n\t}\n};\n\nconst refreshLockTimeoutMs = 5 * 60 * 1000;\nconst refreshLockRetryMs = 50;\n\nconst getCredentialLockDirectoryPath = (): string => {\n\treturn join(userInfo().homedir, \".cache\", \"go-labs-cli\", \"locks\");\n};\n\nconst ensurePrivateCredentialLockDirectory = async (): Promise<string> => {\n\tconst directory = getCredentialLockDirectoryPath();\n\tawait mkdir(directory, { mode: 0o700, recursive: true });\n\n\tconst inspectDirectory = async () => {\n\t\tconst directoryStat = await lstat(directory);\n\t\tif (directoryStat.isSymbolicLink() || !directoryStat.isDirectory()) {\n\t\t\tthrow new Error(\n\t\t\t\t\"The CLI credential lock path is not a private directory.\",\n\t\t\t);\n\t\t}\n\t\tconst uid = process.getuid?.();\n\t\tif (uid !== undefined && directoryStat.uid !== uid) {\n\t\t\tthrow new Error(\n\t\t\t\t\"The CLI credential lock directory belongs to another user.\",\n\t\t\t);\n\t\t}\n\t\treturn directoryStat;\n\t};\n\n\tconst directoryStat = await inspectDirectory();\n\t// Windows mode bits do not describe NTFS ACLs, and chmod cannot enforce 0700.\n\t// Lock files contain only random ownership markers; credentials stay in Bun.secrets.\n\tif (process.platform !== \"win32\" && (directoryStat.mode & 0o077) !== 0) {\n\t\tawait chmod(directory, 0o700);\n\t\tconst securedDirectoryStat = await inspectDirectory();\n\t\tif ((securedDirectoryStat.mode & 0o077) !== 0) {\n\t\t\tthrow new Error(\"Unable to secure the CLI credential lock directory.\");\n\t\t}\n\t}\n\n\treturn directory;\n};\n\nconst getCredentialLockPath = async (\n\tproduct: CliProduct,\n\taccount: string,\n): Promise<string> => {\n\tconst key = createHash(\"sha256\")\n\t\t.update(`${product}:${account}`)\n\t\t.digest(\"hex\");\n\treturn join(await ensurePrivateCredentialLockDirectory(), `${key}.lock`);\n};\n\nconst hasErrorCode = (cause: unknown, code: string): boolean =>\n\tcause instanceof Error && \"code\" in cause && cause.code === code;\n\nconst createRefreshLockFile = async (path: string) => {\n\tconst handle = await open(path, \"wx\");\n\tconst owner = randomUUID();\n\ttry {\n\t\tawait handle.writeFile(owner);\n\t} catch (cause) {\n\t\tawait handle.close().catch(() => undefined);\n\t\tawait unlink(path).catch(() => undefined);\n\t\tthrow cause;\n\t}\n\treturn { handle, owner };\n};\n\n/** Resolves true when the lock vanished (retry now); throws when stale. */\nconst refreshLockVanished = async (path: string): Promise<boolean> => {\n\ttry {\n\t\tconst lock = await stat(path);\n\t\tif (Date.now() - lock.mtimeMs > refreshLockTimeoutMs) {\n\t\t\tthrow new Error(\n\t\t\t\t`The CLI credential lock appears stale at ${path}. Ensure no CLI authentication command is running, remove that lock file, and retry.`,\n\t\t\t);\n\t\t}\n\t} catch (statCause) {\n\t\tif (hasErrorCode(statCause, \"ENOENT\")) {\n\t\t\treturn true;\n\t\t}\n\t\tthrow statCause;\n\t}\n\treturn false;\n};\n\nconst acquireRefreshLock = async (path: string) => {\n\tconst deadline = Date.now() + refreshLockTimeoutMs;\n\twhile (Date.now() < deadline) {\n\t\ttry {\n\t\t\treturn await createRefreshLockFile(path);\n\t\t} catch (cause) {\n\t\t\tif (!hasErrorCode(cause, \"EEXIST\")) {\n\t\t\t\tthrow cause;\n\t\t\t}\n\t\t\tif (await refreshLockVanished(path)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tawait Bun.sleep(refreshLockRetryMs);\n\t\t}\n\t}\n\tthrow new Error(\n\t\t\"Timed out waiting for another CLI process to refresh credentials. Retry the command.\",\n\t);\n};\n\n/** Select the native credential-store account; staging launchers set `staging`. */\nexport const resolveCliCredentialAccount = (\n\tenvironment: Readonly<Record<string, string | undefined>> = process.env,\n) => environment.GO_LABS_CLI_CREDENTIAL_ACCOUNT?.trim() || \"default\";\n\nexport const createBunCredentialStore = ({\n\taccount = resolveCliCredentialAccount(),\n\tproduct,\n\tsecrets = createIsolatedBunSecrets(product),\n}: {\n\taccount?: string;\n\tproduct: CliProduct;\n\tsecrets?: SecretsApi;\n}): CliCredentialStore => {\n\tconst service = `go-labs-cli:${product}`;\n\treturn {\n\t\tpreflight: async () => {\n\t\t\tconst input = { name: `probe-${randomUUID()}`, service };\n\t\t\tconst value = `go-labs-non-secret-probe:${randomUUID()}`;\n\t\t\ttry {\n\t\t\t\tawait runSecretOperation(\n\t\t\t\t\tproduct,\n\t\t\t\t\t() => secrets.set({ ...input, value }),\n\t\t\t\t\t\"write-failed\",\n\t\t\t\t);\n\t\t\t\tif (\n\t\t\t\t\t(await runSecretOperation(product, () => secrets.get(input))) !==\n\t\t\t\t\tvalue\n\t\t\t\t) {\n\t\t\t\t\tthrow new CliCredentialStoreUnavailableError(product, \"write-failed\");\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\t// Cleanup must not hide the original capability diagnosis.\n\t\t\t\tawait secrets.delete(input).catch(() => undefined);\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tawait runSecretOperation(\n\t\t\t\tproduct,\n\t\t\t\t() => secrets.delete(input),\n\t\t\t\t\"delete-failed\",\n\t\t\t);\n\t\t\tif (\n\t\t\t\t(await runSecretOperation(product, () => secrets.get(input))) !== null\n\t\t\t) {\n\t\t\t\tthrow new CliCredentialStoreUnavailableError(product, \"delete-failed\");\n\t\t\t}\n\t\t},\n\t\tdelete: async () => {\n\t\t\tawait runSecretOperation(\n\t\t\t\tproduct,\n\t\t\t\t() => secrets.delete({ name: account, service }),\n\t\t\t\t\"delete-failed\",\n\t\t\t);\n\t\t},\n\t\tget: async () => {\n\t\t\tconst value = await runSecretOperation(product, () =>\n\t\t\t\tsecrets.get({ name: account, service }),\n\t\t\t);\n\t\t\tif (value === null) return null;\n\t\t\ttry {\n\t\t\t\treturn storedCliCredentialsSchema.parse(JSON.parse(value));\n\t\t\t} catch {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`The ${product} CLI credential-store entry contains invalid credentials. Run auth logout and sign in again.`,\n\t\t\t\t);\n\t\t\t}\n\t\t},\n\t\tset: async (credentials) => {\n\t\t\tconst parsed = storedCliCredentialsSchema.parse(credentials);\n\t\t\tawait runSecretOperation(\n\t\t\t\tproduct,\n\t\t\t\t() =>\n\t\t\t\t\tsecrets.set({\n\t\t\t\t\t\tname: account,\n\t\t\t\t\t\tservice,\n\t\t\t\t\t\tvalue: JSON.stringify(parsed),\n\t\t\t\t\t}),\n\t\t\t\t\"write-failed\",\n\t\t\t);\n\t\t},\n\t\twithCredentialLock: async <Result>(operation: () => Promise<Result>) => {\n\t\t\tconst refreshLockPath = await getCredentialLockPath(product, account);\n\t\t\tconst lock = await acquireRefreshLock(refreshLockPath);\n\t\t\ttry {\n\t\t\t\treturn await operation();\n\t\t\t} finally {\n\t\t\t\tawait lock.handle.close();\n\t\t\t\tconst owner = await readFile(refreshLockPath, \"utf8\").catch(() => null);\n\t\t\t\tif (owner === lock.owner) {\n\t\t\t\t\tawait unlink(refreshLockPath).catch(() => undefined);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t};\n};\n", "export const CLI_ACCESS_TOKEN_TTL_MS = 15 * 60 * 1000;\nexport const CLI_DEVICE_AUTHORIZATION_TTL_MS = 10 * 60 * 1000;\nexport const CLI_DEVICE_POLL_INTERVAL_SECONDS = 5;\nexport const CLI_DEVICE_BOOTSTRAP_LIMIT_PER_SOURCE = 20;\nexport const CLI_REFRESH_ABSOLUTE_TTL_MS = 180 * 24 * 60 * 60 * 1000;\nexport const CLI_REFRESH_INACTIVITY_TTL_MS = 30 * 24 * 60 * 60 * 1000;\n\nexport const cliProducts = [\n\t\"budget-builder\",\n\t\"event-tech\",\n\t\"rsvp\",\n\t\"gosh\",\n] as const;\nexport type CliProduct = (typeof cliProducts)[number];\n", "import { createHash, randomBytes, timingSafeEqual } from \"node:crypto\";\n\nconst base64Url = (value: Uint8Array) =>\n\tBuffer.from(value).toString(\"base64url\");\nconst USER_CODE_ALPHABET = \"ABCDEFGHJKLMNPQRSTUVWXYZ23456789\";\n\nexport const generateOpaqueSecret = (prefix: string): string =>\n\t`${prefix}${base64Url(randomBytes(32))}`;\n\nexport const generateDeviceCode = (): string => generateOpaqueSecret(\"dc_\");\n\nexport const generateUserCode = (): string => {\n\tconst bytes = randomBytes(8);\n\tconst characters = Array.from(\n\t\tbytes,\n\t\t(byte) => USER_CODE_ALPHABET[byte % USER_CODE_ALPHABET.length],\n\t);\n\treturn `${characters.slice(0, 4).join(\"\")}-${characters.slice(4).join(\"\")}`;\n};\n\nexport const hashSecret = (value: string): string =>\n\tcreateHash(\"sha256\").update(value, \"utf8\").digest(\"hex\");\n\nexport interface PkcePair {\n\tchallenge: string;\n\tmethod: \"S256\";\n\tverifier: string;\n}\n\nexport const createPkcePair = (): PkcePair => {\n\tconst verifier = base64Url(randomBytes(32));\n\treturn {\n\t\tchallenge: base64Url(\n\t\t\tcreateHash(\"sha256\").update(verifier, \"ascii\").digest(),\n\t\t),\n\t\tmethod: \"S256\",\n\t\tverifier,\n\t};\n};\n\nexport const verifyPkce = (\n\tverifier: string,\n\texpectedChallenge: string,\n): boolean => {\n\tconst actual = base64Url(\n\t\tcreateHash(\"sha256\").update(verifier, \"ascii\").digest(),\n\t);\n\tconst actualBytes = Buffer.from(actual, \"utf8\");\n\tconst expectedBytes = Buffer.from(expectedChallenge, \"utf8\");\n\treturn (\n\t\tactualBytes.length === expectedBytes.length &&\n\t\ttimingSafeEqual(actualBytes, expectedBytes)\n\t);\n};\n", "import { globalConfig } from \"./core.js\";\n// functions\nexport function assertEqual(val) {\n return val;\n}\nexport function assertNotEqual(val) {\n return val;\n}\nexport function toZod() {\n return (schema) => schema;\n}\nexport function assertIs(_arg) { }\nexport function assertNever(_x) {\n throw new Error(\"Unexpected value in exhaustive check\");\n}\nexport function assert(_) { }\nexport function getEnumValues(entries) {\n const numericValues = Object.values(entries).filter((v) => typeof v === \"number\");\n const values = Object.entries(entries)\n .filter(([k, _]) => numericValues.indexOf(+k) === -1)\n .map(([_, v]) => v);\n return values;\n}\nexport function joinValues(array, separator = \"|\") {\n return array.map((val) => stringifyPrimitive(val)).join(separator);\n}\nexport function jsonStringifyReplacer(_, value) {\n if (typeof value === \"bigint\")\n return value.toString();\n return value;\n}\n// the accessor lives on a shared prototype: an own accessor makes every box a dictionary-mode object (~360 B and a slow load per read against ~100 B and an inlined getter here)\nclass Cached {\n constructor(getter) {\n this._getter = getter;\n this._value = undefined;\n }\n get value() {\n const getter = this._getter;\n if (getter !== undefined) {\n this._value = getter();\n this._getter = undefined;\n }\n return this._value;\n }\n}\nexport function cached(getter) {\n return new Cached(getter);\n}\nexport function nullish(input) {\n return input === null || input === undefined;\n}\nexport function cleanRegex(source) {\n const start = source.startsWith(\"^\") ? 1 : 0;\n const end = source.endsWith(\"$\") ? source.length - 1 : source.length;\n return source.slice(start, end);\n}\nexport function floatSafeRemainder(val, step) {\n const ratio = val / step;\n const roundedRatio = Math.round(ratio);\n // `val` and `step` each round to a double before the division rounds again, so a true decimal multiple's quotient can sit up to 1.5 of these scaled epsilons from the integer. A 1x tolerance therefore rejected 2.03 as a multiple of 0.07; 4x covers the worst case with margin.\n const tolerance = 4 * Number.EPSILON * Math.max(Math.abs(ratio), 1);\n if (Math.abs(ratio - roundedRatio) < tolerance)\n return 0;\n return ratio - roundedRatio;\n}\nconst EVALUATING = /* @__PURE__*/ Symbol(\"evaluating\");\nexport function defineLazy(object, key, getter) {\n let value = undefined;\n Object.defineProperty(object, key, {\n get() {\n if (value === EVALUATING) {\n // Circular reference detected, return undefined to break the cycle\n return undefined;\n }\n if (value === undefined) {\n value = EVALUATING;\n value = getter();\n }\n return value;\n },\n set(v) {\n Object.defineProperty(object, key, {\n value: v,\n // configurable: true,\n });\n // object[key] = v;\n },\n configurable: true,\n });\n}\nexport function objectClone(obj) {\n return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj));\n}\nexport function assignProp(target, prop, value) {\n Object.defineProperty(target, prop, {\n value,\n writable: true,\n enumerable: true,\n configurable: true,\n });\n}\n/**\n * Whichever object a def's `shape` currently answers from: the one the caller passed until the first read, the frozen copy after it.\n *\n * Its keys and descriptors read without invoking anything, which is what lets a discriminated union check its discriminator, and the cycle walk read a shape, without resolving a getter that references the schema being constructed. A def that answers `shape` from an accessor of its own has none.\n */\nexport function rawShape(def) {\n const desc = Object.getOwnPropertyDescriptor(def, \"shape\");\n return desc?.get ? desc.get.raw : desc?.value;\n}\n// where a builder reads its source's keys and descriptors, resolving only a shape a def answers for itself. A shape resolves by object spread, so only its enumerable keys are ever part of it.\nfunction sourceShape(schema) {\n return rawShape(schema._zod.def) ?? schema._zod.def.shape;\n}\n// a key whose value is not settled yet, self-caching so every read after the first gets the same one\nfunction deferProp(target, key, getter) {\n Object.defineProperty(target, key, {\n get() {\n const value = getter();\n assignProp(this, key, value);\n return value;\n },\n enumerable: true,\n configurable: true,\n });\n}\n// Writes a settled key. A plain assignment is much cheaper than `defineProperty` and produces the same descriptor, but it runs whatever setter already answers to the key — an accessor this shape deferred, or an inherited one, which `__proto__` has on every object and prototype pollution can add for any name.\nfunction putProp(target, key, value) {\n if (key in target)\n assignProp(target, key, value);\n else\n target[key] = value;\n}\n/**\n * Copies `keys` of `source`'s shape onto `target`, each value passed through `wrap`.\n *\n * A key the source has resolved is copied through now, so the derived shape states it outright and nothing has to resolve it to learn what it holds. A key the source still defers stays deferred, and reads back through the source's own `shape`, so it resolves once and both shapes get that one schema.\n */\nfunction mirrorShape(target, source, keys, wrap) {\n const raw = sourceShape(source);\n for (const key of keys) {\n const desc = Object.getOwnPropertyDescriptor(raw, key);\n if (!desc.enumerable)\n continue;\n if (desc.get) {\n deferProp(target, key, () => {\n const value = source._zod.def.shape[key];\n return wrap ? wrap(value, key) : value;\n });\n }\n else\n putProp(target, key, wrap ? wrap(desc.value, key) : desc.value);\n }\n}\n// same, for a plain shape a caller passed rather than a schema's\nfunction mirrorProps(target, source) {\n for (const key of Reflect.ownKeys(source)) {\n const desc = Object.getOwnPropertyDescriptor(source, key);\n if (!desc.enumerable)\n continue;\n if (desc.get)\n deferProp(target, key, () => source[key]);\n else\n putProp(target, key, desc.value);\n }\n}\nexport function mergeDefs(...defs) {\n const mergedDescriptors = {};\n for (const def of defs) {\n const descriptors = Object.getOwnPropertyDescriptors(def);\n Object.assign(mergedDescriptors, descriptors);\n }\n return Object.defineProperties({}, mergedDescriptors);\n}\nexport function cloneDef(schema) {\n return mergeDefs(schema._zod.def);\n}\nexport function getElementAtPath(obj, path) {\n if (!path)\n return obj;\n return path.reduce((acc, key) => acc?.[key], obj);\n}\nexport function promiseAllObject(promisesObj) {\n const keys = Object.keys(promisesObj);\n const promises = keys.map((key) => promisesObj[key]);\n return Promise.all(promises).then((results) => {\n const resolvedObj = {};\n for (let i = 0; i < keys.length; i++) {\n resolvedObj[keys[i]] = results[i];\n }\n return resolvedObj;\n });\n}\nexport function randomString(length = 10) {\n const chars = \"abcdefghijklmnopqrstuvwxyz\";\n let str = \"\";\n for (let i = 0; i < length; i++) {\n str += chars[Math.floor(Math.random() * chars.length)];\n }\n return str;\n}\nexport function esc(str) {\n return JSON.stringify(str);\n}\nexport function slugify(input) {\n return input\n .toLowerCase()\n .trim()\n .replace(/[^\\w\\s-]/g, \"\")\n .replace(/[\\s_-]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n}\nexport const captureStackTrace = (\"captureStackTrace\" in Error ? Error.captureStackTrace : (..._args) => { });\nexport function isObject(data) {\n return typeof data === \"object\" && data !== null && !Array.isArray(data);\n}\nexport const allowsEval = /* @__PURE__*/ cached(() => {\n // Skip the probe under `jitless`: strict CSPs report the caught `new Function` as a `securitypolicyviolation` even though the throw is swallowed.\n if (globalConfig.jitless) {\n return false;\n }\n // @ts-ignore\n if (typeof navigator !== \"undefined\" && navigator?.userAgent?.includes(\"Cloudflare\")) {\n return false;\n }\n try {\n const F = Function;\n new F(\"\");\n return true;\n }\n catch (_) {\n return false;\n }\n});\nexport function isPlainObject(o) {\n if (isObject(o) === false)\n return false;\n // modified constructor\n const ctor = o.constructor;\n if (ctor === undefined)\n return true;\n if (typeof ctor !== \"function\")\n return true;\n // modified prototype\n const prot = ctor.prototype;\n if (isObject(prot) === false)\n return false;\n // ctor doesn't have static `isPrototypeOf`\n if (Object.prototype.hasOwnProperty.call(prot, \"isPrototypeOf\") === false) {\n return false;\n }\n return true;\n}\nexport function shallowClone(o) {\n if (isPlainObject(o))\n return { ...o };\n if (Array.isArray(o))\n return [...o];\n if (o instanceof Map)\n return new Map(o);\n if (o instanceof Set)\n return new Set(o);\n return o;\n}\nexport function numKeys(data) {\n let keyCount = 0;\n for (const key in data) {\n if (Object.prototype.hasOwnProperty.call(data, key)) {\n keyCount++;\n }\n }\n return keyCount;\n}\nexport const getParsedType = (data) => {\n const t = typeof data;\n switch (t) {\n case \"undefined\":\n return \"undefined\";\n case \"string\":\n return \"string\";\n case \"number\":\n return Number.isNaN(data) ? \"nan\" : \"number\";\n case \"boolean\":\n return \"boolean\";\n case \"function\":\n return \"function\";\n case \"bigint\":\n return \"bigint\";\n case \"symbol\":\n return \"symbol\";\n case \"object\":\n if (Array.isArray(data)) {\n return \"array\";\n }\n if (data === null) {\n return \"null\";\n }\n if (data.then && typeof data.then === \"function\" && data.catch && typeof data.catch === \"function\") {\n return \"promise\";\n }\n if (typeof Map !== \"undefined\" && data instanceof Map) {\n return \"map\";\n }\n if (typeof Set !== \"undefined\" && data instanceof Set) {\n return \"set\";\n }\n if (typeof Date !== \"undefined\" && data instanceof Date) {\n return \"date\";\n }\n // @ts-ignore\n if (typeof File !== \"undefined\" && data instanceof File) {\n return \"file\";\n }\n return \"object\";\n default:\n throw new Error(`Unknown data type: ${t}`);\n }\n};\nexport const propertyKeyTypes = /* @__PURE__*/ new Set([\"string\", \"number\", \"symbol\"]);\nexport const primitiveTypes = /* @__PURE__*/ new Set([\n \"string\",\n \"number\",\n \"bigint\",\n \"boolean\",\n \"symbol\",\n \"undefined\",\n]);\nexport function escapeRegex(str) {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n// zod-specific utils\nexport function clone(inst, def, params) {\n const cl = new inst._zod.constr(def ?? inst._zod.def);\n if (!def || params?.parent)\n cl._zod.parent = inst;\n return cl;\n}\nexport function normalizeParams(_params) {\n const params = _params;\n if (!params)\n return {};\n if (typeof params === \"string\")\n return { error: () => params };\n if (params?.message !== undefined) {\n if (params?.error !== undefined)\n throw new Error(\"Cannot specify both `message` and `error` params\");\n params.error = params.message;\n }\n delete params.message;\n if (typeof params.error === \"string\")\n return { ...params, error: () => params.error };\n return params;\n}\nexport function createTransparentProxy(getter) {\n let target;\n return new Proxy({}, {\n get(_, prop, receiver) {\n target ?? (target = getter());\n return Reflect.get(target, prop, receiver);\n },\n set(_, prop, value, receiver) {\n target ?? (target = getter());\n return Reflect.set(target, prop, value, receiver);\n },\n has(_, prop) {\n target ?? (target = getter());\n return Reflect.has(target, prop);\n },\n deleteProperty(_, prop) {\n target ?? (target = getter());\n return Reflect.deleteProperty(target, prop);\n },\n ownKeys(_) {\n target ?? (target = getter());\n return Reflect.ownKeys(target);\n },\n getOwnPropertyDescriptor(_, prop) {\n target ?? (target = getter());\n return Reflect.getOwnPropertyDescriptor(target, prop);\n },\n defineProperty(_, prop, descriptor) {\n target ?? (target = getter());\n return Reflect.defineProperty(target, prop, descriptor);\n },\n });\n}\nexport function stringifyPrimitive(value) {\n if (typeof value === \"bigint\")\n return value.toString() + \"n\";\n if (typeof value === \"string\")\n return `\"${value}\"`;\n return `${value}`;\n}\nexport function optionalKeys(shape) {\n return Object.keys(shape).filter((k) => {\n return shape[k]._zod.optin !== undefined && shape[k]._zod.optout === \"optional\";\n });\n}\n// Wrapped in a `@__PURE__` IIFE: esbuild never tree-shakes a top-level initializer that contains a member access on `Number`, so the bare object literal survived into every bundle.\nexport const NUMBER_FORMAT_RANGES = /*@__PURE__*/ (() => ({\n safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],\n int32: [-2147483648, 2147483647],\n uint32: [0, 4294967295],\n float32: [-3.4028234663852886e38, 3.4028234663852886e38],\n float64: [-Number.MAX_VALUE, Number.MAX_VALUE],\n}))();\nexport const BIGINT_FORMAT_RANGES = {\n int64: [/* @__PURE__*/ BigInt(\"-9223372036854775808\"), /* @__PURE__*/ BigInt(\"9223372036854775807\")],\n uint64: [/* @__PURE__*/ BigInt(0), /* @__PURE__*/ BigInt(\"18446744073709551615\")],\n};\nexport function pick(schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".pick() cannot be used on object schemas containing refinements\");\n }\n const newShape = {};\n mirrorShape(newShape, schema, maskedKeys(schema, mask));\n return clone(schema, mergeDefs(currDef, { shape: newShape, checks: [] }));\n}\n// the mask keys that select something, checked against the source's shape without resolving it\nfunction maskedKeys(schema, mask) {\n const raw = sourceShape(schema);\n const keys = [];\n // `for...in` skips symbols, so a symbol in the mask would select nothing\n for (const key of Reflect.ownKeys(mask)) {\n if (!Object.getOwnPropertyDescriptor(raw, key)?.enumerable) {\n throw new Error(`Unrecognized key: \"${String(key)}\"`);\n }\n if (mask[key])\n keys.push(key);\n }\n return keys;\n}\nexport function omit(schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".omit() cannot be used on object schemas containing refinements\");\n }\n const omitted = new Set(maskedKeys(schema, mask));\n const newShape = {};\n mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)).filter((key) => !omitted.has(key)));\n return clone(schema, mergeDefs(currDef, { shape: newShape, checks: [] }));\n}\nexport function extend(schema, shape) {\n if (!isPlainObject(shape)) {\n throw new Error(\"Invalid input to extend: expected a plain object\");\n }\n const checks = schema._zod.def.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n // Only throw if new shape overlaps with existing shape. Use getOwnPropertyDescriptor to check key existence without accessing values\n const existingShape = sourceShape(schema);\n for (const key of Reflect.ownKeys(shape)) {\n if (Object.getOwnPropertyDescriptor(existingShape, key) !== undefined) {\n throw new Error(\"Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.\");\n }\n }\n }\n return clone(schema, mergeDefs(schema._zod.def, { shape: extended(schema, shape) }));\n}\n// the source's keys, then the caller's overlaid on top\nfunction extended(schema, shape) {\n const newShape = {};\n mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)));\n mirrorProps(newShape, shape);\n return newShape;\n}\nexport function safeExtend(schema, shape) {\n if (!isPlainObject(shape)) {\n throw new Error(\"Invalid input to safeExtend: expected a plain object\");\n }\n return clone(schema, mergeDefs(schema._zod.def, { shape: extended(schema, shape) }));\n}\nexport function merge(a, b) {\n if (!b?._zod?.def) {\n throw new Error(\"Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.\");\n }\n if (a._zod.def.checks?.length) {\n throw new Error(\".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.\");\n }\n const newShape = {};\n mirrorShape(newShape, a, Reflect.ownKeys(sourceShape(a)));\n mirrorShape(newShape, b, Reflect.ownKeys(sourceShape(b)));\n const def = mergeDefs(a._zod.def, {\n shape: newShape,\n get catchall() {\n return b._zod.def.catchall;\n },\n checks: b._zod.def.checks ?? [],\n });\n return clone(a, def);\n}\nexport function partial(Class, schema, mask, name = \"partial\") {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(`.${name}() cannot be used on object schemas containing refinements`);\n }\n const selected = mask ? new Set(maskedKeys(schema, mask)) : undefined;\n const newShape = {};\n mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)), Class &&\n ((value, key) => (selected && !selected.has(key) ? value : new Class({ type: \"optional\", innerType: value }))));\n return clone(schema, mergeDefs(schema._zod.def, { shape: newShape, checks: [] }));\n}\nexport function required(Class, schema, mask) {\n const selected = mask ? new Set(maskedKeys(schema, mask)) : undefined;\n const newShape = {};\n mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)), (value, key) => \n // overwrite with non-optional\n selected && !selected.has(key) ? value : new Class({ type: \"nonoptional\", innerType: value }));\n return clone(schema, mergeDefs(schema._zod.def, { shape: newShape }));\n}\n// invalid_type | too_big | too_small | invalid_format | not_multiple_of | unrecognized_keys | invalid_union | invalid_key | invalid_element | invalid_value | custom\nexport function aborted(x, startIndex = 0) {\n if (x.aborted === true)\n return true;\n for (let i = startIndex; i < x.issues.length; i++) {\n if (x.issues[i]?.continue !== true) {\n return true;\n }\n }\n return false;\n}\n// Checks for explicit abort (continue === false), as opposed to implicit abort (continue === undefined). Used to respect `abort: true` in .refine() even for checks that have a `when` function.\nexport function explicitlyAborted(x, startIndex = 0) {\n if (x.aborted === true)\n return true;\n for (let i = startIndex; i < x.issues.length; i++) {\n if (x.issues[i]?.continue === false) {\n return true;\n }\n }\n return false;\n}\nexport function prefixIssues(path, issues) {\n return issues.map((iss) => {\n var _a;\n (_a = iss).path ?? (_a.path = []);\n iss.path.unshift(path);\n return iss;\n });\n}\nexport function unwrapMessage(message) {\n return typeof message === \"string\" ? message : message?.message;\n}\n/* A check holds no link back to the schema it is attached to — the same check instance is shared by every clone of that schema — so the owner is stamped onto the issues a check just raised, at the only point where both are in scope. Runs on the failure path only; `start` is the issue count from before the check ran. */\n/** The leading size checks of `defChecks` that set an upper bound, each paired with it. */\nexport function sizeCaps(defChecks) {\n const caps = [];\n for (const ch of defChecks ?? []) {\n const d = ch._zod.def;\n // a later check may rewrite the value\n if (!/_(length|size)$|_equals$/.test(d.check))\n break;\n const max = d.maximum ?? d.length ?? d.size;\n if (max >= 0)\n caps.push([max, ch]);\n }\n return caps;\n}\nexport function attachSchema(issues, start, inst) {\n var _a;\n for (let i = start; i < issues.length; i++) {\n (_a = issues[i]).schema ?? (_a.schema = inst);\n }\n}\nexport function finalizeIssue(iss, ctx, config) {\n var _a;\n // A schema that raised an issue itself owns it outright, and outranks any stamp an enclosing check left in `attachSchema`. String formats and z.custom() are schema and check at once, so when they act as a check they defer to that stamp instead.\n const traits = iss.inst?._zod?.traits;\n if (traits?.has(\"$ZodType\")) {\n if (traits.has(\"$ZodCheck\"))\n (_a = iss).schema ?? (_a.schema = iss.inst);\n else\n iss.schema = iss.inst;\n }\n // Decreasing specificity, first map to return a message wins. `inst` is whatever raised the issue, so a check's own map outranks the owning schema's.\n const schemaError = iss.schema !== iss.inst ? iss.schema?._zod.def?.error : undefined;\n const message = iss.message\n ? iss.message\n : (unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ??\n unwrapMessage(schemaError?.(iss)) ??\n unwrapMessage(ctx?.error?.(iss)) ??\n unwrapMessage(config.customError?.(iss)) ??\n unwrapMessage(config.localeError?.(iss)) ??\n \"Invalid input\");\n // an explicit own-key copy beats object rest with excluded keys, which v8 routes through a generic runtime call; Object.keys rather than for-in so an issue pushed with a prototype does not leak inherited keys, and an own __proto__ key is dropped rather than assigned through the setter\n const full = {};\n for (const k of Object.keys(iss)) {\n if (k === \"inst\" || k === \"schema\" || k === \"continue\" || k === \"input\" || k === \"__proto__\")\n continue;\n full[k] = iss[k];\n }\n full.path ?? (full.path = []);\n full.message = message;\n if (ctx?.reportInput) {\n full.input = iss.input;\n }\n return full;\n}\nexport function getSizableOrigin(input) {\n if (input instanceof Set)\n return \"set\";\n if (input instanceof Map)\n return \"map\";\n // @ts-ignore\n if (input instanceof File)\n return \"file\";\n return \"unknown\";\n}\nconst highSurrogate = /[\\uD800-\\uDBFF]/;\n// Code points in `str`: a surrogate pair counts once, a lone surrogate as itself. Hand-rolled because the string iterator allocates and runs ~250x slower on this path; the regex probe exits ~50x quicker for a string with no astral characters.\nexport function codePointLength(str) {\n const units = str.length;\n if (!highSurrogate.test(str))\n return units;\n let count = units;\n for (let i = 0; i < units - 1; i++) {\n if ((str.charCodeAt(i) & 0xfc00) === 0xd800 && (str.charCodeAt(i + 1) & 0xfc00) === 0xdc00) {\n count--;\n i++;\n }\n }\n return count;\n}\nexport function getLengthableOrigin(input) {\n if (Array.isArray(input))\n return \"array\";\n if (typeof input === \"string\")\n return \"string\";\n return \"unknown\";\n}\nexport function parsedType(data) {\n const t = typeof data;\n switch (t) {\n case \"number\": {\n return Number.isNaN(data) ? \"nan\" : \"number\";\n }\n case \"object\": {\n if (data === null) {\n return \"null\";\n }\n if (Array.isArray(data)) {\n return \"array\";\n }\n const obj = data;\n if (obj && Object.getPrototypeOf(obj) !== Object.prototype && \"constructor\" in obj && obj.constructor) {\n return obj.constructor.name;\n }\n }\n }\n return t;\n}\nexport function issue(...args) {\n const [iss, input, inst] = args;\n if (typeof iss === \"string\") {\n return {\n message: iss,\n code: \"custom\",\n input,\n inst,\n };\n }\n return { ...iss };\n}\nexport function cleanEnum(obj) {\n return Object.entries(obj)\n .filter(([k, _]) => {\n // return true if NaN, meaning it's not a number, thus a string key\n return Number.isNaN(Number.parseInt(k, 10));\n })\n .map((el) => el[1]);\n}\n// Codec utility functions\nexport function base64ToUint8Array(base64) {\n const binaryString = atob(base64);\n const bytes = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n bytes[i] = binaryString.charCodeAt(i);\n }\n return bytes;\n}\nexport function uint8ArrayToBase64(bytes) {\n let binaryString = \"\";\n for (let i = 0; i < bytes.length; i++) {\n binaryString += String.fromCharCode(bytes[i]);\n }\n return btoa(binaryString);\n}\nexport function base64urlToUint8Array(base64url) {\n const base64 = base64url.replace(/-/g, \"+\").replace(/_/g, \"/\");\n const padding = \"=\".repeat((4 - (base64.length % 4)) % 4);\n return base64ToUint8Array(base64 + padding);\n}\nexport function uint8ArrayToBase64url(bytes) {\n return uint8ArrayToBase64(bytes).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=/g, \"\");\n}\nexport function hexToUint8Array(hex) {\n const cleanHex = hex.replace(/^0x/, \"\");\n if (cleanHex.length % 2 !== 0) {\n throw new Error(\"Invalid hex string length\");\n }\n const bytes = new Uint8Array(cleanHex.length / 2);\n for (let i = 0; i < cleanHex.length; i += 2) {\n bytes[i / 2] = Number.parseInt(cleanHex.slice(i, i + 2), 16);\n }\n return bytes;\n}\nexport function uint8ArrayToHex(bytes) {\n return Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n// instanceof\nexport class Class {\n constructor(..._args) { }\n}\n////////// PROTOTYPE INSTALLERS //////////\n//\n// Members live on the prototype and materialize per instance on first read, which keeps own-property count under the step where V8 stops using inline slots. Changing anything here means re-measuring runtime, memory and bundle size together — see \"The three axes\" in AGENTS.md.\n/**\n * Installs a trait's members on its prototype. Each value builds that member for the instance on first read; the built value shadows the accessor as an own property, so a detached `const { parse } = schema` keeps working.\n *\n * Call this from a `proto` initializer, which runs once per prototype — never per instance.\n */\nexport function members(proto, table) {\n for (const key in table) {\n const desc = Object.getOwnPropertyDescriptor(table, key);\n // a getter installs as written, so it stays live: `description` reads through to the registry on every access. not enumerable: an object literal's is, and a prototype member never was\n if (desc.get)\n Object.defineProperty(proto, key, { ...desc, enumerable: false });\n // a method materializes bound on first read, which is what keeps a detached member working: `const opt = schema.optional; opt()`\n else\n defineBound(proto, key, desc.value);\n }\n}\n/** Shadows a prototype member with an own value, so a getter that builds from the instance runs once. */\nexport function own(inst, key, value, enumerable = true) {\n Object.defineProperty(inst, key, { configurable: true, writable: true, enumerable, value });\n return value;\n}\n/** Like {@link own}, for a member that was never an own data property and has to stay out of `Object.keys`. */\nexport function hide(inst, key, value) {\n return own(inst, key, value, false);\n}\n/** Adds members a table derives from the instance: each builds on first read and shadows as own data, and assignment shadows the same way, as when these were own properties. */\nexport /*@__NO_SIDE_EFFECTS__*/ function derived(computes, table) {\n for (const key in computes) {\n const compute = computes[key];\n // an object literal's accessor is configurable and enumerable, and `members` copies the descriptor as written\n Object.defineProperty(table, key, {\n configurable: true,\n enumerable: true,\n get() {\n return own(this, key, compute(this));\n },\n set(value) {\n own(this, key, value);\n },\n });\n }\n return table;\n}\nfunction defineBound(proto, key, fn) {\n Object.defineProperty(proto, key, {\n configurable: true,\n get() {\n // vitest's spyOn calls a prototype getter bare to find the function it wraps, so a nullish receiver answers the raw method\n return this == null ? fn : own(this, key, fn.bind(this));\n },\n set(value) {\n own(this, key, value);\n },\n });\n}\n/** Returns the prototype to install on, or `undefined` if this group is already installed on it. */\nfunction claim(inst, sentinel) {\n const proto = Object.getPrototypeOf(inst);\n // Runs on every construction, so `in` rather than the costlier `hasOwnProperty.call`. Sentinels are keys the group itself defines.\n return sentinel in proto ? undefined : proto;\n}\n// The internals whose init chain is installing. A second call for the same one is a derived constructor overriding its base, so it must not construct another schema in between or the override is dropped.\nlet installing;\n// Set while a getter is running, so a value that resolved through a recursion break is not memoized. One shared descriptor shadows the key for the duration, which costs no per-key allocation.\nlet broke = false;\nconst breaker = {\n configurable: true,\n get() {\n broke = true;\n return undefined;\n },\n};\n/**\n * Installs a lazily-derived internal on the `_zod` prototype of `inst`'s\n * constructor, computed from the internals object itself and cached there on\n * first read. One accessor per constructor rather than one per instance.\n */\nexport function defineLazyInternal(inst, key, compute) {\n const proto = Object.getPrototypeOf(inst._zod);\n if (key in proto && installing !== inst._zod) {\n // A repeat construction: everything is installed already. Cleared here so the reference is not held past the first construction of every type.\n installing = undefined;\n return;\n }\n installing = inst._zod;\n Object.defineProperty(proto, key, {\n configurable: true,\n get() {\n // Shadowed before computing so a re-entrant read from a recursive schema resolves to undefined instead of running the getter again.\n Object.defineProperty(this, key, breaker);\n const outer = broke;\n broke = false;\n try {\n const value = compute(this);\n // A result that resolved through a recursion break is recomputed once the graph is complete; everything else memoizes, undefined included.\n if (broke)\n delete this[key];\n else\n Object.defineProperty(this, key, { configurable: true, writable: true, value });\n broke = broke || outer;\n return value;\n }\n catch (err) {\n // A compute that threw memoizes nothing, so a later read runs it again and fails the same way. The shadow goes with it, since leaving it installed would answer undefined for every later read.\n delete this[key];\n broke = broke || outer;\n throw err;\n }\n },\n set(value) {\n Object.defineProperty(this, key, { configurable: true, writable: true, value });\n },\n });\n}\n/**\n * Installs `key` on `inst`'s prototype, computed by `make` on first read and cached there as an own\n * data property. One accessor per constructor rather than one per instance, because an own accessor\n * puts every instance after the first into v8 dictionary mode. The key doubles as the sentinel.\n */\nexport function installLazyProp(inst, key, make, enumerable) {\n const proto = claim(inst, key);\n if (!proto)\n return;\n Object.defineProperty(proto, key, {\n configurable: true,\n get() {\n // Shadowed before computing, so a re-entrant read from a self-referential shape resolves to undefined instead of running the getter again. A data property rather than an accessor: an own accessor is the dictionary-mode transition this exists to avoid.\n const desc = { configurable: true, writable: true, enumerable, value: undefined };\n Object.defineProperty(this, key, desc);\n // a compute that throws leaves the shadow behind, so later reads answer undefined instead of re-throwing; `defineLazy` did the same, and `defineLazyInternal`'s delete-on-catch would cost bytes in every bundle for a case only a throwing user getter reaches\n desc.value = make(this);\n Object.defineProperty(this, key, desc);\n return desc.value;\n },\n set(value) {\n Object.defineProperty(this, key, { configurable: true, writable: true, enumerable, value });\n },\n });\n}\n/** Marks the thunk `_catch` synthesises for a constant catch value. `Function.length` cannot tell that thunk from a user callback — rest and defaulted parameters both report arity 0 — and a user callback reads `ctx.error`, whose issues only finalize correctly against the caller's per-parse error map. Provenance can say what arity cannot. A plain string key rather than `Symbol.for`, whose call at module scope no bundler can prove pure — the same shape that anchored `urlCanParse` into every build. */\nexport const CONSTANT_CATCH = \"~constantCatch\";\n/** Wraps a constant catch value in a thunk tagged with {@link CONSTANT_CATCH}. */\nexport function constantCatch(value) {\n const fn = () => value;\n fn[CONSTANT_CATCH] = true;\n return fn;\n}\n", "var _a;\nimport { members as installMembers } from \"./util.js\";\n/** A special constant with type `never` */\nexport const NEVER = /*@__PURE__*/ Object.freeze({\n status: \"aborted\",\n});\n/* Shared descriptor for installing `_zod`; defineProperty reads it\n * synchronously, so reusing one object avoids a per-instance allocation. */\nconst _zodDesc = { value: undefined, enumerable: false };\n// null where suppressing the capture would be unrecoverable: `parse()` puts the frames back with `captureStackTrace`, so without it the throw would lose its stack. also latched to null once `stackTraceLimit` proves unassignable, which a realm can do at any point by hardening Error\nlet _E = \"captureStackTrace\" in Error ? Error : null;\n// v8 captures a stack trace inside the Error constructor, which dominates a failed parse; costs only the frames, and parse() restores those. the constructor must RUN: Object.create is cheaper and passes instanceof, but Error.isError and util.types.isNativeError check an internal slot\nfunction newError(Definition) {\n const E = _E;\n if (E) {\n const saved = E.stackTraceLimit;\n if (typeof saved === \"number\") {\n try {\n E.stackTraceLimit = 0;\n }\n catch {\n _E = null;\n return new Definition();\n }\n try {\n return new Definition();\n }\n finally {\n E.stackTraceLimit = saved;\n }\n }\n }\n return new Definition();\n}\nexport /*@__NO_SIDE_EFFECTS__*/ function $constructor(name, initializer, \n/** This trait's members, installed once on every prototype that composes it. They cannot be declared in the initializer above: that runs per instance, and the prototype is shared. */\nproto, params) {\n // Prototype for this constructor's `_zod` internals. Lazily-derived fields (`values`, `pattern`, `optin`, …) install here once rather than as an accessor on every instance.\n const zodProto = {};\n // Assigning the fields in the constructor body is what gives instances in-object slots; building the object literally and reparenting it costs a second allocation and a generic property copy.\n function Internals(def) {\n this.def = def;\n this.constr = _;\n this.traits = new Set();\n }\n Internals.prototype = zodProto;\n const protoMembers = proto;\n // One trait's members land on every prototype whose chain composes it, so the answer is per prototype rather than per trait.\n const initialized = protoMembers && new WeakSet();\n function init(inst, def) {\n if (!inst._zod) {\n _zodDesc.value = new Internals(def);\n try {\n Object.defineProperty(inst, \"_zod\", _zodDesc);\n }\n finally {\n // Cleared even on throw, so the shared descriptor never leaks one instance's internals into the next.\n _zodDesc.value = undefined;\n }\n }\n else if (inst._zod.traits.has(name)) {\n return;\n }\n inst._zod.traits.add(name);\n initializer(inst, def);\n if (initialized) {\n // `super(def)` from a user subclass gives `this` a prototype the subclass owns, and installing there would overwrite whatever the subclass declared. `constr` built the instance, so its prototype is the one below the subclass's that should carry the members. A receiver whose chain never reaches that prototype installs on its own, which for a plain object handed straight to `init` means `Object.prototype` — unchanged from before.\n const own = Object.getPrototypeOf(inst);\n const ctorProto = inst._zod.constr.prototype;\n let up = own;\n while (up && up !== ctorProto)\n up = Object.getPrototypeOf(up);\n const target = up ?? own;\n if (!initialized.has(target)) {\n initialized.add(target);\n installMembers(target, protoMembers);\n }\n }\n // support prototype modifications; for-in avoids the array allocation of Object.keys on the (usually empty) prototype\n const proto = _.prototype;\n for (const k in proto) {\n if (!Object.prototype.hasOwnProperty.call(proto, k))\n continue;\n if (!(k in inst)) {\n inst[k] = proto[k].bind(inst);\n }\n }\n }\n // doesn't work if Parent has a constructor with arguments\n const Parent = params?.Parent ?? Object;\n class Definition extends Parent {\n }\n Object.defineProperty(Definition, \"name\", { value: name });\n function _(def) {\n const inst = params?.Parent ? newError(Definition) : this;\n init(inst, def);\n const deferred = inst._zod.deferred;\n if (deferred) {\n for (const fn of deferred) {\n fn();\n }\n // Released: initializers run once, and the list would otherwise be retained for the schema's lifetime.\n inst._zod.deferred = undefined;\n }\n // Global post-processor hook. Internal: installed by `import \"zod/compile\"` to enable AOT compilation for every constructed schema. Runs last, once the instance is fully built, because it hands the instance to compile(). The post-processor is expected to be reentrancy-guarded by its own implementation.\n const pp = globalThis.__zod_globalConfig?.postProcessor;\n if (pp)\n pp(inst);\n return inst;\n }\n Object.defineProperty(_, \"init\", { value: init });\n Object.defineProperty(_, Symbol.hasInstance, {\n value: (inst) => {\n if (params?.Parent && inst instanceof params.Parent)\n return true;\n return inst?._zod?.traits?.has(name);\n },\n });\n Object.defineProperty(_, \"name\", { value: name });\n return _;\n}\n////////////////////////////// UTILITIES ///////////////////////////////////////\nexport const $brand = /*@__PURE__*/ Symbol(\"zod_brand\");\nexport class $ZodAsyncError extends Error {\n constructor() {\n super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);\n }\n}\nexport class $ZodEncodeError extends Error {\n constructor(name) {\n super(`Encountered unidirectional transform during encode: ${name}`);\n this.name = \"ZodEncodeError\";\n }\n}\n(_a = globalThis).__zod_globalConfig ?? (_a.__zod_globalConfig = {});\nexport const globalConfig = globalThis.__zod_globalConfig;\nexport function config(newConfig) {\n if (newConfig)\n Object.assign(globalConfig, newConfig);\n return globalConfig;\n}\n", "import { $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 class Doc {\n constructor(args = [], closed = {}) {\n this.content = [];\n this.indent = 0;\n this.args = args;\n this.closed = closed;\n }\n // the compiler catches a child's throw and keeps writing into this doc, so the indent has to unwind with it\n indented(fn) {\n this.indent += 1;\n try {\n fn(this);\n }\n finally {\n this.indent -= 1;\n }\n }\n write(arg) {\n if (typeof arg === \"function\") {\n arg(this, { execution: \"sync\" });\n arg(this, { execution: \"async\" });\n return;\n }\n const content = arg;\n const lines = content.split(\"\\n\").filter((x) => x);\n const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length));\n const dedented = lines.map((x) => x.slice(minIndent)).map((x) => \" \".repeat(this.indent * 2) + x);\n for (const line of dedented) {\n this.content.push(line);\n }\n }\n compile() {\n const F = Function;\n const content = this?.content ?? [``];\n const factory = new F(...Object.keys(this.closed), `return function (${this.args.join(\", \")}) {\\n${content.join(\"\\n\")}\\n};`);\n return factory(...Object.values(this.closed));\n }\n}\n", "export const version = {\n major: 4,\n minor: 6,\n patch: 7,\n};\n", "import * as checks from \"./checks.js\";\nimport * as core from \"./core.js\";\nimport { Doc } from \"./doc.js\";\nimport { parse, parseAsync } from \"./parse.js\";\nimport * as regexes from \"./regexes.js\";\nimport * as util from \"./util.js\";\nimport { version } from \"./versions.js\";\nexport const $ZodType = /*@__PURE__*/ core.$constructor(\"$ZodType\", (inst, def) => {\n var _a;\n inst ?? (inst = {});\n inst._zod.def = def; // set _def property\n inst._zod.bag = inst._zod.bag || {}; // initialize _bag object\n inst._zod.version = version;\n const defChecks = inst._zod.def.checks;\n // if inst is itself a checks.$ZodCheck, run it as a check\n const checks = inst._zod.traits.has(\"$ZodCheck\")\n ? [inst, ...(defChecks ?? [])]\n : defChecks?.length\n ? [...defChecks]\n : [];\n for (const ch of checks) {\n for (const fn of ch._zod.onattach) {\n fn(inst);\n }\n }\n if (checks.length === 0) {\n // deferred initializer inst._zod.parse is not yet defined\n (_a = inst._zod).deferred ?? (_a.deferred = []);\n inst._zod.deferred?.push(() => {\n inst._zod.run = inst._zod.parse;\n });\n }\n else {\n const runChecks = (payload, checks, ctx) => {\n if (payload.memo)\n return payload;\n let isAborted = util.aborted(payload);\n let asyncResult;\n for (const ch of checks) {\n if (ch._zod.def.when) {\n if (util.explicitlyAborted(payload))\n continue;\n const shouldRun = ch._zod.def.when(payload);\n if (!shouldRun)\n continue;\n }\n else if (isAborted) {\n continue;\n }\n const currLen = payload.issues.length;\n const _ = ch._zod.check(payload);\n if (_ instanceof Promise && ctx?.async === false) {\n throw new core.$ZodAsyncError();\n }\n if (asyncResult || _ instanceof Promise) {\n asyncResult = (asyncResult ?? Promise.resolve()).then(async () => {\n await _;\n const nextLen = payload.issues.length;\n if (nextLen === currLen)\n return;\n util.attachSchema(payload.issues, currLen, inst);\n if (!isAborted)\n isAborted = util.aborted(payload, currLen);\n });\n }\n else {\n const nextLen = payload.issues.length;\n if (nextLen === currLen)\n continue;\n util.attachSchema(payload.issues, currLen, inst);\n if (!isAborted)\n isAborted = util.aborted(payload, currLen);\n }\n }\n if (asyncResult) {\n return asyncResult.then(() => {\n return payload;\n });\n }\n return payload;\n };\n const handleCanaryResult = (canary, payload, ctx) => {\n // abort if the canary is aborted\n if (util.aborted(canary)) {\n canary.aborted = true;\n return canary;\n }\n // run checks first, then\n const checkResult = runChecks(payload, checks, ctx);\n if (checkResult instanceof Promise) {\n if (ctx.async === false)\n throw new core.$ZodAsyncError();\n return checkResult.then((checkResult) => inst._zod.parse(checkResult, ctx));\n }\n return inst._zod.parse(checkResult, ctx);\n };\n inst._zod.run = (payload, ctx) => {\n if (ctx.skipChecks) {\n return inst._zod.parse(payload, ctx);\n }\n if (ctx.direction === \"backward\") {\n // run canary initial pass (no checks)\n const canary = inst._zod.parse({ value: payload.value, issues: [] }, { ...ctx, skipChecks: true });\n if (canary instanceof Promise) {\n return canary.then((canary) => {\n return handleCanaryResult(canary, payload, ctx);\n });\n }\n return handleCanaryResult(canary, payload, ctx);\n }\n // forward\n const result = inst._zod.parse(payload, ctx);\n if (result instanceof Promise) {\n if (ctx.async === false)\n throw new core.$ZodAsyncError();\n return result.then((result) => runChecks(result, checks, ctx));\n }\n return runChecks(result, checks, ctx);\n };\n }\n}, {\n // Wrappers extend this by installing a richer factory over it; reading it eagerly would defeat the laziness.\n get \"~standard\"() {\n return util.hide(this, \"~standard\", standardProps(this));\n },\n set \"~standard\"(value) {\n util.own(this, \"~standard\", value);\n },\n});\n/** The Standard Schema surface for `inst`. Shared so wrappers can extend it without forcing it. */\n// a Standard Schema result only reports issues, so a failure finalizes them straight off the raw payload: no ZodError, and no lazy result to read through\nconst toStandardResult = (r, ctx) => r.issues.length ? { issues: r.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())) } : { value: r.value };\nasync function validateAsync(inst, value) {\n const ctx = { async: true };\n return toStandardResult((await inst._zod.run({ value, issues: [] }, ctx)), ctx);\n}\nexport function standardProps(inst) {\n return {\n validate: (value) => {\n const ctx = { async: false };\n try {\n const r = inst._zod.run({ value, issues: [] }, ctx);\n if (!(r instanceof Promise))\n return toStandardResult(r, ctx);\n }\n catch (_) { }\n // async function so a synchronously throwing check rejects instead of escaping validate\n return validateAsync(inst, value);\n },\n vendor: \"zod\",\n version: 1,\n };\n}\nexport { clone } from \"./util.js\";\nexport const $ZodString = /*@__PURE__*/ core.$constructor(\"$ZodString\", (inst, def) => {\n $ZodType.init(inst, def);\n // a format's own pattern, else unbounded; a template literal derives the check-aware form itself\n inst._zod.pattern = def.pattern ?? regexes.anyString;\n inst._zod.parse = (payload, _) => {\n if (def.coerce)\n try {\n payload.value = String(payload.value);\n }\n catch (_) { }\n if (typeof payload.value === \"string\")\n return payload;\n payload.issues.push({\n expected: \"string\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodStringFormat\", (inst, def) => {\n // check initialization must come first\n checks.$ZodCheckStringFormat.init(inst, def);\n $ZodString.init(inst, def);\n});\nexport const $ZodGUID = /*@__PURE__*/ core.$constructor(\"$ZodGUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.guid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodUUID = /*@__PURE__*/ core.$constructor(\"$ZodUUID\", (inst, def) => {\n if (def.version) {\n const versionMap = {\n v1: 1,\n v2: 2,\n v3: 3,\n v4: 4,\n v5: 5,\n v6: 6,\n v7: 7,\n v8: 8,\n };\n const v = versionMap[def.version];\n if (v === undefined)\n throw new Error(`Invalid UUID version: \"${def.version}\"`);\n def.pattern ?? (def.pattern = regexes.uuid(v));\n }\n else\n def.pattern ?? (def.pattern = regexes.uuid());\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodEmail = /*@__PURE__*/ core.$constructor(\"$ZodEmail\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.email);\n $ZodStringFormat.init(inst, def);\n});\n/** The `://` guard rejected the input before the URL constructor saw it. */\nexport const URL_BAD_FORMAT = 1;\n/** The URL parser rejected the input. */\nexport const URL_UNPARSEABLE = 2;\nexport function canParseURL(input) {\n try {\n if (typeof URL !== \"undefined\" && typeof URL.canParse === \"function\")\n return URL.canParse(input);\n new URL(input);\n return true;\n }\n catch {\n return false;\n }\n}\nexport function validateURL(trimmed, def) {\n if (!(\"normalize\" in def) && !(\"hostname\" in def) && !(\"protocol\" in def)) {\n return canParseURL(trimmed) || URL_UNPARSEABLE;\n }\n return parseURLObject(trimmed, def);\n}\n/** Parses a URL while preserving the non-normalizing HTTP guard. */\nexport function parseURLObject(trimmed, def) {\n // When normalize is off, require :// for http/https URLs. This prevents strings like \"http:example.com\" or \"https:/path\" from being silently accepted\n if (!def.normalize && def.protocol?.source === regexes.httpProtocol.source && !/^https?:\\/\\//i.test(trimmed)) {\n return URL_BAD_FORMAT;\n }\n try {\n if (typeof URL !== \"undefined\") {\n const URLStatic = URL;\n if (typeof URLStatic.parse === \"function\")\n return URLStatic.parse(trimmed) ?? URL_UNPARSEABLE;\n }\n // @ts-ignore\n return new URL(trimmed);\n }\n catch {\n return URL_UNPARSEABLE;\n }\n}\nconst asciiTabOrNewline = /[\\t\\n\\r]/g;\n/** The URL parser deletes every ASCII tab, LF and CR from its input before it parses, so `new URL(\"https://exa\\nmple.com\")` reports on `example.com`. Applying the same deletion to the returned value closes the half of that divergence which can move the host; the parser's other rewrite, stripping C0 controls at the edges, cannot. */\nexport function stripTabAndNewline(value) {\n return value.replace(asciiTabOrNewline, \"\");\n}\nexport function urlHostnameOk(url, hostname) {\n hostname.lastIndex = 0;\n return hostname.test(url.hostname);\n}\nexport function urlProtocolOk(url, protocol) {\n protocol.lastIndex = 0;\n return protocol.test(url.protocol.endsWith(\":\") ? url.protocol.slice(0, -1) : url.protocol);\n}\nexport const $ZodURL = /*@__PURE__*/ core.$constructor(\"$ZodURL\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n try {\n // Trim whitespace from input\n const trimmed = payload.value.trim();\n const url = validateURL(trimmed, def);\n if (url === URL_BAD_FORMAT) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n note: \"Invalid URL format\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n return;\n }\n if (url === URL_UNPARSEABLE) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n return;\n }\n if (url === true) {\n payload.value = stripTabAndNewline(trimmed);\n return;\n }\n if (def.hostname && !urlHostnameOk(url, def.hostname)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n note: \"Invalid hostname\",\n pattern: def.hostname.source,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n if (def.protocol && !urlProtocolOk(url, def.protocol)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n note: \"Invalid protocol\",\n pattern: def.protocol.source,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n // Set the output value based on normalize flag\n payload.value = def.normalize ? url.href : stripTabAndNewline(trimmed);\n return;\n }\n catch (_) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodEmoji = /*@__PURE__*/ core.$constructor(\"$ZodEmoji\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.emoji());\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodNanoID = /*@__PURE__*/ core.$constructor(\"$ZodNanoID\", (inst, def) => {\n if (def.length !== undefined && (!Number.isInteger(def.length) || def.length < 1))\n throw new Error(`Invalid nanoid length: ${def.length}`);\n def.pattern ?? (def.pattern = def.length === undefined ? regexes.nanoid : regexes.nanoidOfLength(def.length));\n $ZodStringFormat.init(inst, def);\n});\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link $ZodCUID2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport const $ZodCUID = /*@__PURE__*/ core.$constructor(\"$ZodCUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cuid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodCUID2 = /*@__PURE__*/ core.$constructor(\"$ZodCUID2\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cuid2);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodULID = /*@__PURE__*/ core.$constructor(\"$ZodULID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ulid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodXID = /*@__PURE__*/ core.$constructor(\"$ZodXID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.xid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodKSUID = /*@__PURE__*/ core.$constructor(\"$ZodKSUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ksuid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODateTime = /*@__PURE__*/ core.$constructor(\"$ZodISODateTime\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.datetime(def));\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODate = /*@__PURE__*/ core.$constructor(\"$ZodISODate\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.date);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISOTime = /*@__PURE__*/ core.$constructor(\"$ZodISOTime\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.time(def));\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODuration = /*@__PURE__*/ core.$constructor(\"$ZodISODuration\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.duration);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodIPv4 = /*@__PURE__*/ core.$constructor(\"$ZodIPv4\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ipv4);\n $ZodStringFormat.init(inst, def);\n});\n/** An IPv6 address is written with hex digits, colons and dots, and nothing else. The guard is what makes the check below an IPv6 check: `new URL(\"http://[...]\")` parses an authority, not an address, so `@` and `\\` re-delimit it and `\"::@1\\\\\"` validates against the host `0.0.0.1`. The URL parser also deletes ASCII tab, LF and CR rather than failing, which is how `\"::1\\n\"` validated as `::1`. */\nconst ipv6Alphabet = /^[0-9a-fA-F:.]+$/;\nexport function isValidIPv6(value) {\n if (!ipv6Alphabet.test(value))\n return false;\n return canParseURL(`http://[${value}]`);\n}\nexport const $ZodIPv6 = /*@__PURE__*/ core.$constructor(\"$ZodIPv6\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ipv6);\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (!isValidIPv6(payload.value)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"ipv6\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodMAC = /*@__PURE__*/ core.$constructor(\"$ZodMAC\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.mac(def.delimiter));\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodCIDRv4 = /*@__PURE__*/ core.$constructor(\"$ZodCIDRv4\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cidrv4);\n $ZodStringFormat.init(inst, def);\n});\nexport function isValidCIDRv6(value) {\n const parts = value.split(\"/\");\n if (parts.length !== 2)\n return false;\n const [address, prefix] = parts;\n if (!prefix)\n return false;\n const prefixNum = Number(prefix);\n if (`${prefixNum}` !== prefix)\n return false;\n if (prefixNum < 0 || prefixNum > 128)\n return false;\n return isValidIPv6(address);\n}\nexport const $ZodCIDRv6 = /*@__PURE__*/ core.$constructor(\"$ZodCIDRv6\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cidrv6); // not used for validation\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (!isValidCIDRv6(payload.value)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"cidrv6\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\n////////////////////////////// ZodBase64 //////////////////////////////\nexport function isValidBase64(data) {\n if (data === \"\")\n return true;\n // atob ignores whitespace, so reject it up front.\n if (/\\s/.test(data))\n return false;\n if (data.length % 4 !== 0)\n return false;\n try {\n // @ts-ignore\n atob(data);\n return true;\n }\n catch {\n return false;\n }\n}\n// lax on purpose: the quantified regexes.base64 overflows the regex stack on multi-MB input and its leading ^$| alternation leaks through template-literal composition; isValidBase64 enforces length and padding\nexport const base64Charset = /^[0-9a-zA-Z+/]*={0,2}$/;\nexport const $ZodBase64 = /*@__PURE__*/ core.$constructor(\"$ZodBase64\", (inst, def) => {\n def.pattern ?? (def.pattern = base64Charset);\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (isValidBase64(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"base64\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\n////////////////////////////// ZodBase64URL //////////////////////////////\n// lax on purpose: the quantified regexes.base64url overflows the regex stack on multi-MB input; isValidBase64 enforces length on the padded string\nexport const base64urlCharset = /^[A-Za-z0-9_-]*$/;\nexport function isValidBase64URL(data) {\n if (!base64urlCharset.test(data))\n return false;\n const base64 = data.replace(/[-_]/g, (c) => (c === \"-\" ? \"+\" : \"/\"));\n const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, \"=\");\n return isValidBase64(padded);\n}\nexport const $ZodBase64URL = /*@__PURE__*/ core.$constructor(\"$ZodBase64URL\", (inst, def) => {\n def.pattern ?? (def.pattern = base64urlCharset);\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (isValidBase64URL(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"base64url\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodE164 = /*@__PURE__*/ core.$constructor(\"$ZodE164\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.e164);\n $ZodStringFormat.init(inst, def);\n});\n////////////////////////////// ZodCreditCard //////////////////////////////\nconst CC_SANITIZE = /[- ]/g;\n/** Luhn checksum on a digit-only string. Adapted from valibot (MIT). */\nfunction isLuhnAlgo(digits) {\n let length = digits.length;\n let bit = 1;\n let sum = 0;\n while (length) {\n const value = digits.charCodeAt(--length) - 48;\n bit ^= 1;\n sum += bit ? [0, 2, 4, 6, 8, 1, 3, 5, 7, 9][value] : value;\n }\n return sum % 10 === 0;\n}\nexport function isValidCreditCard(input) {\n if (!regexes.creditCard.test(input))\n return false;\n return isLuhnAlgo(input.replace(CC_SANITIZE, \"\"));\n}\nexport const $ZodCreditCard = /*@__PURE__*/ core.$constructor(\"$ZodCreditCard\", (inst, def) => {\n // Shape only — the Luhn check below is not expressible as a pattern, so consumers of `pattern` (JSON Schema, template literals) get the length and separator rules alone.\n def.pattern ?? (def.pattern = regexes.creditCard);\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (isValidCreditCard(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"credit_card\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\n////////////////////////////// ZodIBAN //////////////////////////////\n// iso 7064 mod 97-10 checksum without BigInt\nfunction isIso7064Mod97(iban) {\n let remainder = 0;\n const len = iban.length;\n for (let i = 4; i < len; i++) {\n const code = iban.charCodeAt(i);\n remainder = (code >= 65 ? remainder * 100 + (code - 55) : remainder * 10 + (code - 48)) % 97;\n }\n for (let i = 0; i < 4; i++) {\n const code = iban.charCodeAt(i);\n remainder = (code >= 65 ? remainder * 100 + (code - 55) : remainder * 10 + (code - 48)) % 97;\n }\n return remainder === 1;\n}\nexport function isValidIBAN(input) {\n if (!regexes.iban.test(input))\n return false;\n return isIso7064Mod97(input);\n}\nexport const $ZodIBAN = /*@__PURE__*/ core.$constructor(\"$ZodIBAN\", (inst, def) => {\n // shape only — checksum is not expressible as a pattern\n def.pattern ?? (def.pattern = regexes.iban);\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (isValidIBAN(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"iban\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\n////////////////////////////// ZodJWT //////////////////////////////\nexport function isValidJWT(token, algorithm = null) {\n try {\n const tokensParts = token.split(\".\");\n if (tokensParts.length !== 3)\n return false;\n const [header] = tokensParts;\n if (!header)\n return false;\n // @ts-ignore\n const parsedHeader = JSON.parse(atob(header));\n if (\"typ\" in parsedHeader && parsedHeader?.typ !== \"JWT\")\n return false;\n if (!parsedHeader.alg)\n return false;\n if (algorithm && (!(\"alg\" in parsedHeader) || parsedHeader.alg !== algorithm))\n return false;\n return true;\n }\n catch {\n return false;\n }\n}\nexport const $ZodJWT = /*@__PURE__*/ core.$constructor(\"$ZodJWT\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (isValidJWT(payload.value, def.alg))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"jwt\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCustomStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodCustomStringFormat\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (def.fn(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: def.format,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodNumber = /*@__PURE__*/ core.$constructor(\"$ZodNumber\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.number;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = Number(payload.value);\n }\n catch (_) { }\n const input = payload.value;\n if (typeof input === \"number\" && !Number.isNaN(input) && Number.isFinite(input)) {\n return payload;\n }\n const received = typeof input === \"number\"\n ? Number.isNaN(input)\n ? \"NaN\"\n : !Number.isFinite(input)\n ? String(input)\n : undefined\n : undefined;\n payload.issues.push({\n expected: \"number\",\n code: \"invalid_type\",\n input,\n inst,\n ...(received ? { received } : {}),\n });\n return payload;\n };\n});\nexport const $ZodNumberFormat = /*@__PURE__*/ core.$constructor(\"$ZodNumberFormat\", (inst, def) => {\n checks.$ZodCheckNumberFormat.init(inst, def);\n $ZodNumber.init(inst, def); // no format checks\n});\nexport const $ZodBoolean = /*@__PURE__*/ core.$constructor(\"$ZodBoolean\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.boolean;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = Boolean(payload.value);\n }\n catch (_) { }\n const input = payload.value;\n if (typeof input === \"boolean\")\n return payload;\n payload.issues.push({\n expected: \"boolean\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodBigInt = /*@__PURE__*/ core.$constructor(\"$ZodBigInt\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.bigint;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = BigInt(payload.value);\n }\n catch (_) { }\n if (typeof payload.value === \"bigint\")\n return payload;\n payload.issues.push({\n expected: \"bigint\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodBigIntFormat = /*@__PURE__*/ core.$constructor(\"$ZodBigIntFormat\", (inst, def) => {\n checks.$ZodCheckBigIntFormat.init(inst, def);\n $ZodBigInt.init(inst, def); // no format checks\n});\nexport const $ZodSymbol = /*@__PURE__*/ core.$constructor(\"$ZodSymbol\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"symbol\")\n return payload;\n payload.issues.push({\n expected: \"symbol\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodUndefined = /*@__PURE__*/ core.$constructor(\"$ZodUndefined\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.undefined;\n inst._zod.values = new Set([undefined]);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"undefined\")\n return payload;\n payload.issues.push({\n expected: \"undefined\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodNull = /*@__PURE__*/ core.$constructor(\"$ZodNull\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.null;\n inst._zod.values = new Set([null]);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (input === null)\n return payload;\n payload.issues.push({\n expected: \"null\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodAny = /*@__PURE__*/ core.$constructor(\"$ZodAny\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload) => payload;\n});\nexport const $ZodUnknown = /*@__PURE__*/ core.$constructor(\"$ZodUnknown\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload) => payload;\n});\nexport const $ZodNever = /*@__PURE__*/ core.$constructor(\"$ZodNever\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n payload.issues.push({\n expected: \"never\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodVoid = /*@__PURE__*/ core.$constructor(\"$ZodVoid\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"undefined\")\n return payload;\n payload.issues.push({\n expected: \"void\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodDate = /*@__PURE__*/ core.$constructor(\"$ZodDate\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce) {\n try {\n payload.value = new Date(payload.value);\n }\n catch (_err) { }\n }\n const input = payload.value;\n const isDate = input instanceof Date;\n const isValidDate = isDate && !Number.isNaN(input.getTime());\n if (isValidDate)\n return payload;\n payload.issues.push({\n expected: \"date\",\n code: \"invalid_type\",\n input,\n ...(isDate ? { received: \"Invalid Date\" } : {}),\n inst,\n });\n return payload;\n };\n});\n// an oversized container fails its leading size checks before any element is parsed\nfunction capSize(inst, size) {\n const caps = util.sizeCaps(inst._zod.def.checks);\n if (!caps.length)\n return;\n const cap = Math.min(...caps.map((c) => c[0]));\n const parse = inst._zod.parse;\n inst._zod.parse = (payload, ctx) => {\n const n = size(payload.value);\n if (n > cap && !ctx?.skipChecks && ctx?.direction !== \"backward\") {\n for (const [max, ch] of util.sizeCaps(inst._zod.def.checks)) {\n if (n > max && ch._zod.def.when(payload)) {\n const start = payload.issues.length;\n ch._zod.check(payload);\n // the value is still the raw input, so no later check may read it\n payload.issues[start].continue = false;\n util.attachSchema(payload.issues, start, inst);\n return payload;\n }\n }\n }\n return parse(payload, ctx);\n };\n}\nconst arraySize = (input) => (Array.isArray(input) ? input.length : -1);\nconst mapSize = (input) => (input instanceof Map ? input.size : -1);\nconst setSize = (input) => (input instanceof Set ? input.size : -1);\nfunction handleArrayResult(result, final, index) {\n if (result.issues.length) {\n final.issues.push(...util.prefixIssues(index, result.issues));\n }\n final.value[index] = result.value;\n}\nexport const $ZodArray = /*@__PURE__*/ core.$constructor(\"$ZodArray\", (inst, def) => {\n $ZodType.init(inst, def);\n const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!Array.isArray(input)) {\n payload.issues.push({\n expected: \"array\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n payload.value = memo ? memo.alloc(inst, payload, Array(input.length), ctx) : Array(input.length);\n const proms = [];\n const abortEarly = ctx?.abortEarly;\n for (let i = 0; i < input.length; i++) {\n const item = input[i];\n const result = def.element._zod.run({\n value: item,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => handleArrayResult(result, payload, i)));\n }\n else {\n handleArrayResult(result, payload, i);\n // the element's payload is authoritative here, since handleArrayResult forwards every issue; an object's is not, because it drops a failed absent optional\n if (abortEarly && result.issues.length !== 0 && util.aborted(result))\n break;\n }\n }\n if (proms.length) {\n return Promise.all(proms).then(() => payload);\n }\n return payload; //handleArrayResultsAsync(parseResults, final);\n };\n capSize(inst, arraySize);\n});\nfunction handlePropertyResult(result, final, key, input, optin, optout) {\n const isPresent = key in input;\n const isOptionalOut = optout === \"optional\";\n // The middle rung means \"absence permitted, nothing supplied in its place\", so an absent key contributes nothing — whatever the schema made of `undefined` is invented, not substituted. Only `optional` reaches this with a value: `defaulted` substitutes, and a schema that isn't optional-out has to keep the key.\n if (!isPresent && isOptionalOut && optin === \"optional\") {\n return;\n }\n if (result.issues.length) {\n // For optional-in/out schemas, ignore errors on absent keys.\n if (optin !== undefined && isOptionalOut && !isPresent) {\n return;\n }\n final.issues.push(...util.prefixIssues(key, result.issues));\n }\n if (!isPresent && optin === undefined) {\n if (!result.issues.length) {\n final.issues.push({\n code: \"invalid_type\",\n expected: \"nonoptional\",\n input: undefined,\n path: [key],\n });\n }\n return;\n }\n if (result.value === undefined) {\n if (isPresent || (optin === \"defaulted\" && !isOptionalOut)) {\n final.value[key] = undefined;\n }\n }\n else {\n final.value[key] = result.value;\n }\n}\n// one shared instance; a fresh [] per schema cost 56 bytes retained\nconst NO_SYMBOL_KEYS = [];\nfunction normalizeDef(def) {\n const keys = Object.keys(def.shape);\n const ownSymbols = Object.getOwnPropertySymbols(def.shape);\n const symbolKeys = ownSymbols.length ? ownSymbols : NO_SYMBOL_KEYS;\n // aliases `keys` when there are no symbols, so a string-only shape keeps one array\n const allKeys = symbolKeys.length ? [...keys, ...symbolKeys] : keys;\n for (const k of allKeys) {\n if (!def.shape?.[k]?._zod?.traits?.has(\"$ZodType\")) {\n throw new Error(`Invalid element at key \"${String(k)}\": expected a Zod schema`);\n }\n }\n const okeys = util.optionalKeys(def.shape);\n return {\n ...def,\n allKeys,\n symbolKeys,\n // string-only: handleCatchall matches it against `for...in`, which never yields a symbol\n keySet: new Set(keys),\n numKeys: keys.length,\n optionalKeys: new Set(okeys),\n };\n}\nfunction handleCatchall(proms, input, payload, ctx, def, inst, abortEarly) {\n const unrecognized = [];\n const keySet = def.keySet;\n const _catchall = def.catchall._zod;\n const t = _catchall.def.type;\n const optin = _catchall.optin;\n const optout = _catchall.optout;\n // starts at 0, not the current length: the shape phase already ran and may have aborted\n let seen = 0;\n for (const key in input) {\n if (abortEarly && payload.issues.length !== seen) {\n if (util.aborted(payload, seen))\n break;\n seen = payload.issues.length;\n }\n // Must precede the __proto__ branch: a declared key is not unrecognized, even though the shape loop deliberately strips __proto__ from the parsed output.\n if (keySet.has(key))\n continue;\n // Don't copy an undeclared __proto__ into the result; assignment to a plain {} would replace the result prototype. But in strict mode it is still an unknown key, so report it before skipping.\n if (key === \"__proto__\") {\n if (t === \"never\")\n unrecognized.push(key);\n continue;\n }\n if (t === \"never\") {\n unrecognized.push(key);\n continue;\n }\n const r = _catchall.run({ value: input[key], issues: [] }, ctx);\n if (r instanceof Promise) {\n proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, optin, optout)));\n }\n else {\n handlePropertyResult(r, payload, key, input, optin, optout);\n }\n }\n if (unrecognized.length) {\n payload.issues.push({\n code: \"unrecognized_keys\",\n keys: unrecognized,\n input,\n inst,\n // Describes the shape of the input, not the validity of the parsed value, so it never aborts. The parse still fails; the schema's own checks just get to run first, and an enclosing intersection can reconcile the key against a sibling operand.\n continue: true,\n });\n }\n if (!proms.length)\n return payload;\n return Promise.all(proms).then(() => {\n return payload;\n });\n}\nexport const $ZodObject = /*@__PURE__*/ core.$constructor(\"$ZodObject\", (inst, def) => {\n // requires cast because technically $ZodObject doesn't extend\n $ZodType.init(inst, def);\n const desc = Object.getOwnPropertyDescriptor(def, \"shape\");\n // a cloned def carries its source's accessor, which knows the shape it answers from; adopting that keeps the clone's keys readable without running it\n const sh = desc?.get ? desc.get.raw : (def.shape ?? {});\n if (sh) {\n // Freezes the shape on first read, so its getters resolve once and every later read sees the same schemas.\n const get = () => {\n const newSh = { ...sh };\n Object.defineProperty(def, \"shape\", { value: newSh });\n get.raw = newSh;\n return newSh;\n };\n get.raw = sh;\n Object.defineProperty(def, \"shape\", { get });\n }\n const _normalized = util.cached(() => normalizeDef(def));\n util.defineLazyInternal(inst, \"propValues\", (zod) => {\n const shape = zod.def.shape;\n const propValues = {};\n for (const key in shape) {\n const field = shape[key]._zod;\n if (field.values) {\n if (!Object.prototype.hasOwnProperty.call(propValues, key)) {\n util.assignProp(propValues, key, new Set());\n }\n for (const v of field.values)\n propValues[key].add(v);\n // An omittable slot reads back as undefined at a discriminator lookup, so it has to claim undefined: two options that can both omit the key are not discriminable on it.\n if (field.optin !== undefined)\n propValues[key].add(undefined);\n }\n }\n return propValues;\n });\n const isObject = util.isObject;\n const catchall = def.catchall;\n let value;\n const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\n inst._zod.parse = (payload, ctx) => {\n value ?? (value = _normalized.value);\n const input = payload.value;\n if (!isObject(input)) {\n payload.issues.push({\n expected: \"object\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {};\n const proms = [];\n const shape = value.shape;\n const abortEarly = ctx?.abortEarly;\n let seen = payload.issues.length;\n for (const key of value.allKeys) {\n if (abortEarly && payload.issues.length !== seen) {\n if (util.aborted(payload, seen))\n break;\n seen = payload.issues.length;\n }\n if (key === \"__proto__\")\n continue;\n const el = shape[key];\n const optin = el._zod.optin;\n const optout = el._zod.optout;\n const r = el._zod.run({ value: input[key], issues: [] }, ctx);\n if (r instanceof Promise) {\n proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, optin, optout)));\n }\n else {\n handlePropertyResult(r, payload, key, input, optin, optout);\n }\n }\n if (!catchall) {\n return proms.length ? Promise.all(proms).then(() => payload) : payload;\n }\n return handleCatchall(proms, input, payload, ctx, _normalized.value, inst, abortEarly === true);\n };\n});\nexport const $ZodObjectJIT = /*@__PURE__*/ core.$constructor(\"$ZodObjectJIT\", (inst, def) => {\n // requires cast because technically $ZodObject doesn't extend\n $ZodObject.init(inst, def);\n const superParse = inst._zod.parse;\n const _normalized = util.cached(() => normalizeDef(def));\n const memo = core.globalConfig.memoizer;\n const generateFastpass = (shape) => {\n const normalized = _normalized.value;\n const syms = normalized.symbolKeys;\n // a symbol has no source literal, so it is read as `syms[i]` off the closed-over scope\n const doc = new Doc([\"payload\", \"ctx\"], { shape, inst, memo, syms });\n const parseStr = (k) => `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;\n // prefixes in place, like util.prefixIssues. newResult must land before the early return: a catchall runs after this and would otherwise write onto the caller's input\n const prefixStr = (id, k) => `\n let ${id}_ab = false;\n for (let i = 0; i < ${id}.issues.length; i++) {\n const iss = ${id}.issues[i];\n iss.path = iss.path ? [${k}, ...iss.path] : [${k}];\n payload.issues.push(iss);\n if (iss.continue !== true) ${id}_ab = true;\n }\n if (${id}_ab && ctx && ctx.abortEarly) {\n payload.value = newResult;\n return payload;\n }`;\n doc.write(`const input = payload.value;`);\n const ids = Object.create(null);\n let counter = 0;\n for (const key of normalized.allKeys) {\n ids[key] = `key_${counter++}`;\n }\n // A: preserve key order {\n doc.write(memo ? `const newResult = memo.alloc(inst, payload, {}, ctx);` : `const newResult = {};`);\n for (const key of normalized.allKeys) {\n if (key === \"__proto__\")\n continue;\n const id = ids[key];\n const k = typeof key === \"symbol\" ? `syms[${syms.indexOf(key)}]` : util.esc(key);\n const isPresent = `${k} in input`;\n const schema = shape[key];\n const optin = schema?._zod?.optin;\n const isOptionalIn = optin !== undefined;\n const isOptionalOut = schema?._zod?.optout === \"optional\";\n doc.write(`const ${id} = ${parseStr(k)};`);\n if (isOptionalIn && isOptionalOut) {\n // For optional-in/out schemas, ignore errors on absent keys — and, like the interpreted path, drop the value produced alongside them. The middle rung goes further: it permits absence without supplying anything in its place, so an absent key contributes nothing at all.\n const assign = optin === \"optional\" ? `${id}_present` : `${id}.value !== undefined || ${id}_present`;\n doc.write(`\n const ${id}_present = ${isPresent};\n if (!${id}.issues.length || ${id}_present) {\n if (${id}.issues.length) {${prefixStr(id, k)}\n }\n\n if (${assign}) {\n newResult[${k}] = ${id}.value;\n }\n }\n\n `);\n }\n else if (!isOptionalIn) {\n doc.write(`\n const ${id}_present = ${isPresent};\n if (${id}.issues.length) {${prefixStr(id, k)}\n }\n if (!${id}_present && !${id}.issues.length) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"nonoptional\",\n input: undefined,\n path: [${k}]\n });\n if (ctx && ctx.abortEarly) {\n payload.value = newResult;\n return payload;\n }\n }\n\n if (${id}_present) {\n newResult[${k}] = ${id}.value;\n }\n\n `);\n }\n else {\n doc.write(`\n if (${id}.issues.length) {${prefixStr(id, k)}\n }\n `);\n if (optin === \"defaulted\") {\n doc.write(`newResult[${k}] = ${id}.value;`);\n }\n else {\n doc.write(`\n if (${id}.value !== undefined || ${isPresent}) {\n newResult[${k}] = ${id}.value;\n }\n `);\n }\n }\n }\n doc.write(`payload.value = newResult;`);\n doc.write(`return payload;`);\n // closing `shape` in is what pays: turbofan specializes the parser against that one shape object, so every `shape[k]._zod.run` folds to a known callee. as a parameter it stays a generic load and measures 13% slower even with the forwarding frame gone\n return doc.compile();\n };\n let fastpass;\n const isObject = util.isObject;\n const jit = !core.globalConfig.jitless;\n const allowsEval = util.allowsEval;\n const fastEnabled = jit && allowsEval.value; // && !def.catchall;\n const catchall = def.catchall;\n let value;\n inst._zod.parse = (payload, ctx) => {\n value ?? (value = _normalized.value);\n const input = payload.value;\n if (!isObject(input)) {\n payload.issues.push({\n expected: \"object\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) {\n // always synchronous\n if (!fastpass)\n fastpass = generateFastpass(def.shape);\n payload = fastpass(payload, ctx);\n if (!catchall)\n return payload;\n return handleCatchall([], input, payload, ctx, value, inst, ctx?.abortEarly === true);\n }\n return superParse(payload, ctx);\n };\n});\nfunction handleUnionResults(results, final, inst, ctx) {\n for (const result of results) {\n if (result.issues.length === 0) {\n final.value = result.value;\n return final;\n }\n }\n const nonaborted = results.filter((r) => !util.aborted(r));\n if (nonaborted.length === 1) {\n final.value = nonaborted[0].value;\n return nonaborted[0];\n }\n final.issues.push({\n code: \"invalid_union\",\n input: final.value,\n inst,\n errors: results.map((result) => result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n });\n return final;\n}\nexport const $ZodUnion = /*@__PURE__*/ core.$constructor(\"$ZodUnion\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.options.some((o) => o._zod.optin === \"defaulted\")\n ? \"defaulted\"\n : zod.def.options.some((o) => o._zod.optin !== undefined)\n ? \"optional\"\n : undefined);\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.options.some((o) => o._zod.optout === \"optional\") ? \"optional\" : undefined);\n util.defineLazyInternal(inst, \"values\", (zod) => {\n if (zod.def.options.every((o) => o._zod.values)) {\n return new Set(zod.def.options.flatMap((option) => Array.from(option._zod.values)));\n }\n return undefined;\n });\n util.defineLazyInternal(inst, \"pattern\", (zod) => {\n if (zod.def.options.every((o) => o._zod.pattern)) {\n const patterns = zod.def.options.map((o) => o._zod.pattern);\n return new RegExp(`^(${patterns.map((p) => util.cleanRegex(p.source)).join(\"|\")})$`);\n }\n return undefined;\n });\n const first = def.options.length === 1 ? def.options[0]._zod.run : null;\n inst._zod.parse = (payload, ctx) => {\n if (first) {\n return first(payload, ctx);\n }\n let async = false;\n const results = [];\n for (const option of def.options) {\n const result = option._zod.run({\n value: payload.value,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n results.push(result);\n async = true;\n }\n else {\n if (result.issues.length === 0)\n return result;\n results.push(result);\n }\n }\n if (!async)\n return handleUnionResults(results, payload, inst, ctx);\n return Promise.all(results).then((results) => {\n return handleUnionResults(results, payload, inst, ctx);\n });\n };\n});\nfunction handleExclusiveUnionResults(results, final, inst, ctx) {\n const matches = [];\n for (let i = 0; i < results.length; i++) {\n if (results[i].issues.length === 0)\n matches.push(i);\n }\n if (matches.length === 1) {\n final.value = results[matches[0]].value;\n return final;\n }\n if (matches.length === 0) {\n // No matches - same as regular union\n final.issues.push({\n code: \"invalid_union\",\n input: final.value,\n inst,\n errors: results.map((result) => result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n });\n }\n else {\n // Multiple matches - exclusive union failure\n final.issues.push({\n code: \"invalid_union\",\n input: final.value,\n inst,\n errors: [],\n inclusive: false,\n matches,\n });\n }\n return final;\n}\nexport const $ZodXor = /*@__PURE__*/ core.$constructor(\"$ZodXor\", (inst, def) => {\n $ZodUnion.init(inst, def);\n def.inclusive = false;\n const first = def.options.length === 1 ? def.options[0]._zod.run : null;\n inst._zod.parse = (payload, ctx) => {\n if (first) {\n return first(payload, ctx);\n }\n let async = false;\n const results = [];\n for (const option of def.options) {\n const result = option._zod.run({\n value: payload.value,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n results.push(result);\n async = true;\n }\n else {\n results.push(result);\n }\n }\n if (!async)\n return handleExclusiveUnionResults(results, payload, inst, ctx);\n return Promise.all(results).then((results) => {\n return handleExclusiveUnionResults(results, payload, inst, ctx);\n });\n };\n});\n/** Returns the option whose discriminator claims `value`, or throws if ambiguous. */\nexport function getDiscriminatedOption(union, value) {\n const internals = union._zod;\n let map = internals.bag.optionsMap;\n if (!map) {\n map = discriminatorMap(internals.def);\n internals.bag.optionsMap = map;\n }\n const option = map.get(value);\n if (option === null)\n throw new Error(`Ambiguous discriminator value \"${String(value)}\"`);\n return option;\n}\nfunction discriminatorMap(def) {\n const map = new Map();\n for (const option of def.options) {\n const values = option._zod.propValues?.[def.discriminator];\n if (!values || values.size === 0)\n throw new Error(`Invalid discriminated union option at index \"${def.options.indexOf(option)}\"`);\n for (const value of values) {\n if (map.has(value)) {\n if (value !== undefined)\n throw new Error(`Duplicate discriminator value \"${String(value)}\"`);\n // keep the collision marked so a later member cannot reclaim it\n map.set(value, null);\n }\n else {\n map.set(value, option);\n }\n }\n }\n return map;\n}\nexport const $ZodDiscriminatedUnion = \n/*@__PURE__*/\ncore.$constructor(\"$ZodDiscriminatedUnion\", (inst, def) => {\n def.inclusive = false;\n $ZodUnion.init(inst, def);\n const _super = inst._zod.parse;\n util.defineLazyInternal(inst, \"propValues\", (zod) => {\n const propValues = {};\n let undefinedCount = 0;\n for (const option of zod.def.options) {\n const pv = option._zod.propValues;\n if (!pv || Object.keys(pv).length === 0)\n throw new Error(`Invalid discriminated union option at index \"${zod.def.options.indexOf(option)}\"`);\n if (pv[zod.def.discriminator]?.has(undefined))\n undefinedCount++;\n for (const [k, v] of Object.entries(pv)) {\n if (!Object.prototype.hasOwnProperty.call(propValues, k)) {\n util.assignProp(propValues, k, new Set());\n }\n for (const val of v) {\n propValues[k].add(val);\n }\n }\n }\n if (!zod.def.unionFallback && undefinedCount > 1)\n propValues[zod.def.discriminator]?.delete(undefined);\n return propValues;\n });\n // Checked now rather than in the lookup map below, so an option that lacks the discriminator fails at the `discriminatedUnion` call instead of on the first object parsed. Options whose shape cannot be enumerated without resolving it — pipes and lazies — are left to the map.\n def.options.forEach((option, i) => {\n const propShape = util.rawShape(option._zod.def);\n if (propShape && !Object.prototype.hasOwnProperty.call(propShape, def.discriminator)) {\n throw new Error(`Invalid discriminated union option at index \"${i}\"`);\n }\n });\n const disc = util.cached(() => discriminatorMap(def));\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!util.isObject(input)) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"object\",\n input,\n inst,\n });\n return payload;\n }\n const value = input?.[def.discriminator];\n const opt = disc.value.get(value);\n // forward metadata cannot choose an encoder for an absent tag\n if (opt && (value !== undefined || ctx.direction !== \"backward\")) {\n return opt._zod.run(payload, ctx);\n }\n // Fall back to union matching when the fast discriminator path fails:\n // - explicitly enabled via unionFallback, or\n // - during backward direction (encode), since codec-based discriminators have different values in forward vs backward directions\n if (def.unionFallback || ctx.direction === \"backward\") {\n return _super(payload, ctx);\n }\n // no matching discriminator\n payload.issues.push({\n code: \"invalid_union\",\n errors: [],\n note: \"No matching discriminator\",\n discriminator: def.discriminator,\n options: Array.from(disc.value.keys()).filter((value) => disc.value.get(value) !== null),\n input,\n path: [def.discriminator],\n inst,\n });\n return payload;\n };\n});\nexport const $ZodIntersection = /*@__PURE__*/ core.$constructor(\"$ZodIntersection\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n const left = def.left._zod.run({ value: input, issues: [] }, ctx);\n const right = def.right._zod.run({ value: input, issues: [] }, ctx);\n const async = left instanceof Promise || right instanceof Promise;\n if (async) {\n return Promise.all([left, right]).then(([left, right]) => {\n return handleIntersectionResults(payload, left, right);\n });\n }\n return handleIntersectionResults(payload, left, right);\n };\n});\nexport function mergeValues(a, b) {\n // const aType = parse.t(a);\n // const bType = parse.t(b);\n if (a === b) {\n return { valid: true, data: a };\n }\n if (a instanceof Date && b instanceof Date && +a === +b) {\n return { valid: true, data: a };\n }\n if (util.isPlainObject(a) && util.isPlainObject(b)) {\n const bKeys = Object.keys(b);\n const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);\n const newObj = { ...a, ...b };\n if (Object.prototype.hasOwnProperty.call(newObj, \"__proto__\"))\n delete newObj.__proto__;\n for (const key of sharedKeys) {\n if (key === \"__proto__\")\n continue;\n const sharedValue = mergeValues(a[key], b[key]);\n if (!sharedValue.valid) {\n return {\n valid: false,\n mergeErrorPath: [key, ...sharedValue.mergeErrorPath],\n };\n }\n newObj[key] = sharedValue.data;\n }\n return { valid: true, data: newObj };\n }\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) {\n return { valid: false, mergeErrorPath: [] };\n }\n const newArray = [];\n for (let index = 0; index < a.length; index++) {\n const itemA = a[index];\n const itemB = b[index];\n const sharedValue = mergeValues(itemA, itemB);\n if (!sharedValue.valid) {\n return {\n valid: false,\n mergeErrorPath: [index, ...sharedValue.mergeErrorPath],\n };\n }\n newArray.push(sharedValue.data);\n }\n return { valid: true, data: newArray };\n }\n return { valid: false, mergeErrorPath: [] };\n}\nfunction handleIntersectionResults(result, left, right) {\n // Track which side(s) reject each key. A key rejection is reported only when BOTH sides reject it, so a key owned by one branch survives the other's key schema. strictObject reports these as unrecognized_keys; a record with an open key schema reports one invalid_key per key.\n const unrecKeys = new Map();\n let unrecIssue;\n const keyIssues = new Map();\n const collect = (iss, side) => {\n let keys;\n if (iss.code === \"unrecognized_keys\" && !iss.path?.length) {\n unrecIssue ?? (unrecIssue = iss);\n keys = iss.keys;\n }\n else if (iss.code === \"invalid_key\" && iss.origin === \"record\" && iss.path?.length === 1) {\n const k = String(iss.path[0]);\n if (!keyIssues.has(k))\n keyIssues.set(k, iss);\n keys = [k];\n }\n else {\n return false;\n }\n for (const k of keys) {\n if (!unrecKeys.has(k))\n unrecKeys.set(k, {});\n unrecKeys.get(k)[side] = true;\n }\n return true;\n };\n for (const iss of left.issues) {\n if (!collect(iss, \"l\"))\n result.issues.push(iss);\n }\n for (const iss of right.issues) {\n if (!collect(iss, \"r\"))\n result.issues.push(iss);\n }\n // Report only keys rejected by BOTH sides\n const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k);\n if (bothKeys.length) {\n const aggregated = unrecIssue ? bothKeys.filter((k) => unrecIssue.keys.includes(k)) : [];\n if (aggregated.length)\n result.issues.push({ ...unrecIssue, keys: aggregated });\n for (const k of bothKeys) {\n if (!aggregated.includes(k) && keyIssues.has(k))\n result.issues.push(keyIssues.get(k));\n }\n }\n const merged = mergeValues(left.value, right.value);\n if (!merged.valid) {\n if (util.aborted(result))\n return result;\n throw new Error(`Unmergable intersection. Error path: ` + `${JSON.stringify(merged.mergeErrorPath)}`);\n }\n result.value = merged.data;\n return result;\n}\nexport const $ZodTuple = /*@__PURE__*/ core.$constructor(\"$ZodTuple\", (inst, def) => {\n $ZodType.init(inst, def);\n const items = def.items;\n const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!Array.isArray(input)) {\n payload.issues.push({\n input,\n inst,\n expected: \"tuple\",\n code: \"invalid_type\",\n });\n return payload;\n }\n payload.value = memo ? memo.alloc(inst, payload, [], ctx) : [];\n const proms = [];\n const optinStart = getTupleOptStart(items, \"optin\");\n const optoutStart = getTupleOptStart(items, \"optout\");\n if (!def.rest) {\n if (input.length < optinStart) {\n payload.issues.push({\n code: \"too_small\",\n minimum: optinStart,\n inclusive: true,\n input,\n inst,\n origin: \"array\",\n });\n return payload;\n }\n if (input.length > items.length) {\n payload.issues.push({\n code: \"too_big\",\n maximum: items.length,\n inclusive: true,\n input,\n inst,\n origin: \"array\",\n });\n }\n }\n // Run every item in parallel, collecting results into an indexed array. The post-processing in `handleTupleResults` walks them in order so it can decide whether an absent optional-output error can truncate the tail or must be reported to preserve required output.\n const itemResults = new Array(items.length);\n // only tracked when there is a rest loop to skip\n const abortEarly = def.rest ? ctx?.abortEarly : undefined;\n let itemAborted = false;\n for (let i = 0; i < items.length; i++) {\n const r = items[i]._zod.run({ value: input[i], issues: [] }, ctx);\n if (r instanceof Promise) {\n proms.push(r.then((rr) => {\n itemResults[i] = rr;\n }));\n }\n else {\n itemResults[i] = r;\n if (abortEarly && !itemAborted && r.issues.length)\n itemAborted = util.aborted(r);\n }\n }\n // sound because rest is non-empty exactly when every fixed index is present, the one case handleTupleResults cannot discard an item's issues\n if (def.rest && !itemAborted) {\n let i = items.length - 1;\n const rest = input.slice(items.length);\n let seen = payload.issues.length;\n for (const el of rest) {\n if (abortEarly && payload.issues.length !== seen) {\n if (util.aborted(payload, seen))\n break;\n seen = payload.issues.length;\n }\n i++;\n const result = def.rest._zod.run({ value: el, issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((r) => handleTupleResult(r, payload, i)));\n }\n else {\n handleTupleResult(result, payload, i);\n }\n }\n }\n if (proms.length) {\n return Promise.all(proms).then(() => handleTupleResults(itemResults, payload, items, input, optoutStart));\n }\n return handleTupleResults(itemResults, payload, items, input, optoutStart);\n };\n});\nfunction getTupleOptStart(items, key) {\n for (let i = items.length - 1; i >= 0; i--) {\n // optin is a three-rung ladder so any rung above `undefined` permits an absent slot; optout stays two-valued.\n const omittable = key === \"optin\" ? items[i]._zod.optin !== undefined : items[i]._zod.optout === \"optional\";\n if (!omittable)\n return i + 1;\n }\n return 0;\n}\nfunction handleTupleResult(result, final, index) {\n if (result.issues.length) {\n final.issues.push(...util.prefixIssues(index, result.issues));\n }\n final.value[index] = result.value;\n}\nfunction handleTupleResults(itemResults, final, items, input, optoutStart) {\n // Walk results in order. Mirror $ZodObject's swallow-on-absent-optional rule, but only after `optoutStart`: the first index where the output tuple tail can be absent.\n for (let i = 0; i < items.length; i++) {\n const r = itemResults[i];\n const isPresent = i < input.length;\n // The array analog of `handlePropertyResult`'s absent-key early return: the middle rung permits absence without supplying anything in its place, so the tail truncates here instead of materializing whatever the item made of `undefined`.\n if (!isPresent && i >= optoutStart && items[i]._zod.optin === \"optional\") {\n final.value.length = i;\n break;\n }\n if (r.issues.length) {\n if (!isPresent && i >= optoutStart) {\n final.value.length = i;\n break;\n }\n final.issues.push(...util.prefixIssues(i, r.issues));\n }\n final.value[i] = r.value;\n }\n // Drop trailing slots that produced `undefined` for absent input\n // (the array analog of an absent optional key on an object). The\n // `i >= input.length` floor is critical: an explicit `undefined`\n // *inside* the input must be preserved even when the schema is\n // optional-out (e.g. `z.string().or(z.undefined())` accepting an\n // explicit undefined value).\n for (let i = final.value.length - 1; i >= input.length; i--) {\n if (items[i]._zod.optout === \"optional\" && final.value[i] === undefined) {\n final.value.length = i;\n }\n else {\n break;\n }\n }\n return final;\n}\nexport const $ZodRecord = /*@__PURE__*/ core.$constructor(\"$ZodRecord\", (inst, def) => {\n $ZodType.init(inst, def);\n const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!util.isPlainObject(input)) {\n payload.issues.push({\n expected: \"record\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n // no guard in either loop below: a record's invalid_key aborts but an enclosing intersection can reconcile it, so a stopped loop hides keys the sibling does not own and the intersection then rejects nothing\n const proms = [];\n const values = def.keyType._zod.values;\n if (values && !def.partial) {\n payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {};\n const recordKeys = new Set();\n for (const key of values) {\n if (typeof key === \"string\" || typeof key === \"number\" || typeof key === \"symbol\") {\n recordKeys.add(typeof key === \"number\" ? key.toString() : key);\n // A declared __proto__ is stripped but is not an unrecognized key.\n if (key === \"__proto__\")\n continue;\n const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n if (keyResult instanceof Promise) {\n throw new Error(\"Async schemas not supported in object keys currently\");\n }\n if (keyResult.issues.length) {\n payload.issues.push({\n code: \"invalid_key\",\n origin: \"record\",\n issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n input: key,\n path: [key],\n inst,\n });\n continue;\n }\n const outKey = keyResult.value;\n if (outKey === \"__proto__\")\n continue;\n const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[outKey] = result.value;\n }));\n }\n else {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[outKey] = result.value;\n }\n }\n }\n let unrecognized;\n for (const key in input) {\n if (!recordKeys.has(key)) {\n if (def.mode === \"loose\") {\n // skip __proto__ so it can't replace the result prototype via the assignment setter on the plain {} we build into\n if (key === \"__proto__\")\n continue;\n payload.value[key] = input[key];\n }\n else {\n unrecognized = unrecognized ?? [];\n unrecognized.push(key);\n }\n }\n }\n if (unrecognized && unrecognized.length > 0) {\n payload.issues.push({\n code: \"unrecognized_keys\",\n input,\n inst,\n keys: unrecognized,\n continue: true,\n });\n }\n }\n else {\n payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {};\n // An enumerable key schema declares which keys the record owns, so a key outside the set is unrecognized. A non-enumerable one (regex, refine) is a constraint every key must satisfy, so a failing key is invalid. Only the former is reconcilable against the other side of an intersection.\n let unrecognized;\n // Reflect.ownKeys for Symbol-key support; filter non-enumerable to match z.object()\n for (const key of Reflect.ownKeys(input)) {\n if (key === \"__proto__\")\n continue;\n if (!Object.prototype.propertyIsEnumerable.call(input, key))\n continue;\n let keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n if (keyResult instanceof Promise) {\n throw new Error(\"Async schemas not supported in object keys currently\");\n }\n // Numeric string fallback: if key is a numeric string and failed, retry with Number(key). This handles z.number(), z.literal([1, 2, 3]), and unions containing numeric literals\n const checkNumericKey = typeof key === \"string\" && regexes.number.test(key) && keyResult.issues.length;\n if (checkNumericKey) {\n const retryResult = def.keyType._zod.run({ value: Number(key), issues: [] }, ctx);\n if (retryResult instanceof Promise) {\n throw new Error(\"Async schemas not supported in object keys currently\");\n }\n if (retryResult.issues.length === 0) {\n keyResult = retryResult;\n }\n }\n if (keyResult.issues.length) {\n if (def.mode === \"loose\") {\n // Pass through unchanged\n payload.value[key] = input[key];\n }\n else if (values) {\n unrecognized = unrecognized ?? [];\n unrecognized.push(key);\n }\n else {\n // Default \"strict\" behavior: error on invalid key\n payload.issues.push({\n code: \"invalid_key\",\n origin: \"record\",\n issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n input: key,\n path: [key],\n inst,\n });\n }\n continue;\n }\n // the guard above tests the raw input key, but the key schema can normalize an ordinary key into __proto__; re-check the key we actually write under\n const outKey = keyResult.value;\n if (outKey === \"__proto__\")\n continue;\n const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[outKey] = result.value;\n }));\n }\n else {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[outKey] = result.value;\n }\n }\n if (unrecognized && unrecognized.length > 0) {\n payload.issues.push({\n code: \"unrecognized_keys\",\n input,\n inst,\n keys: unrecognized,\n continue: true,\n });\n }\n }\n if (proms.length) {\n return Promise.all(proms).then(() => payload);\n }\n return payload;\n };\n});\nexport const $ZodMap = /*@__PURE__*/ core.$constructor(\"$ZodMap\", (inst, def) => {\n $ZodType.init(inst, def);\n const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!(input instanceof Map)) {\n payload.issues.push({\n expected: \"map\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n const proms = [];\n payload.value = memo ? memo.alloc(inst, payload, new Map(), ctx) : new Map();\n const abortEarly = ctx?.abortEarly;\n let seen = payload.issues.length;\n for (const [key, value] of input) {\n if (abortEarly && payload.issues.length !== seen) {\n if (util.aborted(payload, seen))\n break;\n seen = payload.issues.length;\n }\n const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n const valueResult = def.valueType._zod.run({ value: value, issues: [] }, ctx);\n if (keyResult instanceof Promise || valueResult instanceof Promise) {\n proms.push(Promise.all([keyResult, valueResult]).then(([keyResult, valueResult]) => {\n handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx);\n }));\n }\n else {\n handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx);\n }\n }\n if (proms.length)\n return Promise.all(proms).then(() => payload);\n return payload;\n };\n capSize(inst, mapSize);\n});\nfunction handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) {\n if (keyResult.issues.length) {\n if (util.propertyKeyTypes.has(typeof key)) {\n final.issues.push(...util.prefixIssues(key, keyResult.issues));\n }\n else {\n final.issues.push({\n code: \"invalid_key\",\n origin: \"map\",\n input,\n inst,\n issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n });\n }\n }\n if (valueResult.issues.length) {\n if (util.propertyKeyTypes.has(typeof key)) {\n final.issues.push(...util.prefixIssues(key, valueResult.issues));\n }\n else {\n final.issues.push({\n origin: \"map\",\n code: \"invalid_element\",\n input,\n inst,\n key: key,\n issues: valueResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n });\n }\n }\n final.value.set(keyResult.value, valueResult.value);\n}\nexport const $ZodSet = /*@__PURE__*/ core.$constructor(\"$ZodSet\", (inst, def) => {\n $ZodType.init(inst, def);\n const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!(input instanceof Set)) {\n payload.issues.push({\n input,\n inst,\n expected: \"set\",\n code: \"invalid_type\",\n });\n return payload;\n }\n const proms = [];\n payload.value = memo ? memo.alloc(inst, payload, new Set(), ctx) : new Set();\n const abortEarly = ctx?.abortEarly;\n let seen = payload.issues.length;\n for (const item of input) {\n if (abortEarly && payload.issues.length !== seen) {\n if (util.aborted(payload, seen))\n break;\n seen = payload.issues.length;\n }\n const result = def.valueType._zod.run({ value: item, issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => handleSetResult(result, payload)));\n }\n else\n handleSetResult(result, payload);\n }\n if (proms.length)\n return Promise.all(proms).then(() => payload);\n return payload;\n };\n capSize(inst, setSize);\n});\nfunction handleSetResult(result, final) {\n if (result.issues.length) {\n final.issues.push(...result.issues);\n }\n final.value.add(result.value);\n}\nexport const $ZodEnum = /*@__PURE__*/ core.$constructor(\"$ZodEnum\", (inst, def) => {\n $ZodType.init(inst, def);\n const values = util.getEnumValues(def.entries);\n const valuesSet = new Set(values);\n inst._zod.values = valuesSet;\n util.defineLazyInternal(inst, \"pattern\", (zod) => {\n const patternValues = util.getEnumValues(zod.def.entries).filter((k) => util.propertyKeyTypes.has(typeof k));\n // unmatchable fallback, RE2-safe: an empty alternation would compile to /^()$/, which matches \"\"\n return new RegExp(patternValues.length ? `^(${patternValues.map((o) => util.escapeRegex(o.toString())).join(\"|\")})$` : \"^[^\\\\s\\\\S]$\");\n });\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (valuesSet.has(input)) {\n return payload;\n }\n payload.issues.push({\n code: \"invalid_value\",\n values,\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodLiteral = /*@__PURE__*/ core.$constructor(\"$ZodLiteral\", (inst, def) => {\n $ZodType.init(inst, def);\n const values = new Set(def.values);\n inst._zod.values = values;\n util.defineLazyInternal(inst, \"pattern\", (zod) => {\n const vals = zod.def.values;\n // unmatchable fallback, RE2-safe: an empty alternation would compile to /^()$/, which matches \"\"\n return new RegExp(vals.length\n ? `^(${vals\n .map((o) => typeof o === \"string\" ? util.escapeRegex(o) : o ? util.escapeRegex(o.toString()) : String(o))\n .join(\"|\")})$`\n : \"^[^\\\\s\\\\S]$\");\n });\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (values.has(input)) {\n return payload;\n }\n payload.issues.push({\n code: \"invalid_value\",\n values: def.values,\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodFile = /*@__PURE__*/ core.$constructor(\"$ZodFile\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n // @ts-ignore\n if (input instanceof File)\n return payload;\n payload.issues.push({\n expected: \"file\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodTransform = /*@__PURE__*/ core.$constructor(\"$ZodTransform\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.optin = \"optional\";\n core.globalConfig.memoizer?.guard(inst);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n throw new core.$ZodEncodeError(inst.constructor.name);\n }\n const _out = def.transform(payload.value, payload);\n if (ctx.async) {\n const output = _out instanceof Promise ? _out : Promise.resolve(_out);\n return output.then((output) => {\n payload.value = output;\n return payload;\n });\n }\n if (_out instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n payload.value = _out;\n return payload;\n };\n});\nfunction handleOptionalResult(payload, result) {\n // A substituting schema that still failed has no usable answer; yield undefined. Its issues are simply dropped: it ran on a payload of its own, so there is no shared array to truncate and nothing of the caller's to lose with it.\n payload.value = result.issues.length ? undefined : result.value;\n return payload;\n}\nexport const $ZodOptional = /*@__PURE__*/ core.$constructor(\"$ZodOptional\", (inst, def) => {\n $ZodType.init(inst, def);\n // .optional() propagates absence rather than substituting for it, so a defaulted inner keeps its rung.\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.innerType._zod.optin === \"defaulted\" ? \"defaulted\" : \"optional\");\n inst._zod.optout = \"optional\";\n util.defineLazyInternal(inst, \"values\", (zod) => {\n const values = zod.def.innerType._zod.values;\n return values ? new Set([...values, undefined]) : undefined;\n });\n util.defineLazyInternal(inst, \"pattern\", (zod) => {\n const pattern = zod.def.innerType._zod.pattern;\n return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)})?$`) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n if (payload.value === undefined) {\n // Only the top rung substitutes a value for absence; everything else leaves it intact, which is what .optional() means.\n if (def.innerType._zod.optin !== \"defaulted\")\n return payload;\n // Its own payload, for the same reason $ZodCatch gets one: a pipe forwards an unrecognized key through the caller's issues array, and this must not read that as the substituting schema failing and drop it.\n const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx);\n if (result instanceof Promise)\n return result.then((result) => handleOptionalResult(payload, result));\n return handleOptionalResult(payload, result);\n }\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodExactOptional = /*@__PURE__*/ core.$constructor(\"$ZodExactOptional\", (inst, def) => {\n // Call parent init - inherits optin/optout = \"optional\"\n $ZodOptional.init(inst, def);\n // Override values/pattern to NOT add undefined\n util.defineLazyInternal(inst, \"values\", (zod) => zod.def.innerType._zod.values);\n util.defineLazyInternal(inst, \"pattern\", (zod) => zod.def.innerType._zod.pattern);\n // Override parse to just delegate (no undefined handling)\n inst._zod.parse = (payload, ctx) => {\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodNullable = /*@__PURE__*/ core.$constructor(\"$ZodNullable\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.innerType._zod.optin);\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.innerType._zod.optout);\n util.defineLazyInternal(inst, \"pattern\", (zod) => {\n const pattern = zod.def.innerType._zod.pattern;\n return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)}|null)$`) : undefined;\n });\n util.defineLazyInternal(inst, \"values\", (zod) => {\n return zod.def.innerType._zod.values ? new Set([...zod.def.innerType._zod.values, null]) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n // Forward direction (decode): allow null to pass through\n if (payload.value === null)\n return payload;\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodDefault = /*@__PURE__*/ core.$constructor(\"$ZodDefault\", (inst, def) => {\n $ZodType.init(inst, def);\n // inst._zod.qin = \"true\";\n inst._zod.optin = \"defaulted\";\n util.defineLazyInternal(inst, \"values\", (zod) => zod.def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n // Forward direction (decode): apply defaults for undefined input\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n /**\n * $ZodDefault returns the default value immediately in forward direction.\n * It doesn't pass the default value into the validator (\"prefault\"). There's no reason to pass the default value through validation. The validity of the default is enforced by TypeScript statically. Otherwise, it's the responsibility of the user to ensure the default is valid. In the case of pipes with divergent in/out types, you can specify the default on the `in` schema of your ZodPipe to set a \"prefault\" for the pipe. */\n return payload;\n }\n // Forward direction: continue with default handling\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => handleDefaultResult(result, def));\n }\n return handleDefaultResult(result, def);\n };\n});\nfunction handleDefaultResult(payload, def) {\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n }\n return payload;\n}\nexport const $ZodPrefault = /*@__PURE__*/ core.$constructor(\"$ZodPrefault\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.optin = \"defaulted\";\n util.defineLazyInternal(inst, \"values\", (zod) => zod.def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n // Forward direction (decode): apply prefault for undefined input\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n }\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodNonOptional = /*@__PURE__*/ core.$constructor(\"$ZodNonOptional\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazyInternal(inst, \"values\", (zod) => {\n const v = zod.def.innerType._zod.values;\n return v ? new Set([...v].filter((x) => x !== undefined)) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => handleNonOptionalResult(result, inst));\n }\n return handleNonOptionalResult(result, inst);\n };\n});\nfunction handleNonOptionalResult(payload, inst) {\n if (!payload.issues.length && payload.value === undefined) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"nonoptional\",\n input: payload.value,\n inst,\n });\n }\n return payload;\n}\nexport const $ZodSuccess = /*@__PURE__*/ core.$constructor(\"$ZodSuccess\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n throw new core.$ZodEncodeError(\"ZodSuccess\");\n }\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => {\n payload.value = result.issues.length === 0;\n return payload;\n });\n }\n payload.value = result.issues.length === 0;\n return payload;\n };\n});\nfunction handleCatchResult(payload, result, def, ctx) {\n if (!result.issues.length) {\n payload.value = result.value;\n // The value carries up, so the flag describing it has to carry with it: a back-edge into a node still being parsed must not be frozen by an enclosing readonly, and its checks belong to the node itself. Guarded so the ordinary case adds no own property.\n if (result.memo)\n payload.memo = true;\n return payload;\n }\n // Spread the inner's own payload, not ours: `value` has to stay the input the catch was handed, and the inner ran on a payload of its own so its issues are already private to this call.\n payload.value = def.catchValue({\n ...result,\n value: payload.value,\n error: {\n issues: result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n },\n input: payload.value,\n });\n return payload;\n}\nexport const $ZodCatch = /*@__PURE__*/ core.$constructor(\"$ZodCatch\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.innerType._zod.optin === \"defaulted\" ? \"defaulted\" : \"optional\");\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.innerType._zod.optout);\n util.defineLazyInternal(inst, \"values\", (zod) => zod.def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n // Forward direction (decode): apply catch logic\n const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx);\n if (result instanceof Promise) {\n return result.then((result) => handleCatchResult(payload, result, def, ctx));\n }\n return handleCatchResult(payload, result, def, ctx);\n };\n});\nexport const $ZodNaN = /*@__PURE__*/ core.$constructor(\"$ZodNaN\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"number\" || !Number.isNaN(payload.value)) {\n payload.issues.push({\n input: payload.value,\n inst,\n expected: \"nan\",\n code: \"invalid_type\",\n });\n return payload;\n }\n return payload;\n };\n});\nexport const $ZodPipe = /*@__PURE__*/ core.$constructor(\"$ZodPipe\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazyInternal(inst, \"values\", (zod) => zod.def.in._zod.values);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.in._zod.optin);\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.out._zod.optout);\n util.defineLazyInternal(inst, \"propValues\", (zod) => zod.def.in._zod.propValues);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n const right = def.out._zod.run(payload, ctx);\n if (right instanceof Promise) {\n return right.then((right) => handlePipeResult(right, def.in, ctx));\n }\n return handlePipeResult(right, def.in, ctx);\n }\n const left = def.in._zod.run(payload, ctx);\n if (left instanceof Promise) {\n return left.then((left) => handlePipeResult(left, def.out, ctx));\n }\n return handlePipeResult(left, def.out, ctx);\n };\n});\nfunction handlePipeResult(left, next, ctx) {\n // Any issue stops the pipe, so a failing refinement never feeds its transform. An unrecognized key is the exception: it describes the input's extra properties, not the value being piped, and an enclosing intersection may yet reconcile it.\n if (left.issues.some((iss) => iss.code !== \"unrecognized_keys\")) {\n // prevent further checks\n left.aborted = true;\n return left;\n }\n return next._zod.run({ value: left.value, issues: left.issues }, ctx);\n}\nexport const $ZodCodec = /*@__PURE__*/ core.$constructor(\"$ZodCodec\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazyInternal(inst, \"values\", (zod) => zod.def.in._zod.values);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.in._zod.optin);\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.out._zod.optout);\n util.defineLazyInternal(inst, \"propValues\", (zod) => zod.def.in._zod.propValues);\n inst._zod.parse = (payload, ctx) => {\n const direction = ctx.direction || \"forward\";\n if (direction === \"forward\") {\n const left = def.in._zod.run(payload, ctx);\n if (left instanceof Promise) {\n return left.then((left) => handleCodecAResult(left, def, ctx));\n }\n return handleCodecAResult(left, def, ctx);\n }\n else {\n const right = def.out._zod.run(payload, ctx);\n if (right instanceof Promise) {\n return right.then((right) => handleCodecAResult(right, def, ctx));\n }\n return handleCodecAResult(right, def, ctx);\n }\n };\n});\nfunction handleCodecAResult(result, def, ctx) {\n if (result.issues.length) {\n // prevent further checks\n result.aborted = true;\n return result;\n }\n const direction = ctx.direction || \"forward\";\n if (direction === \"forward\") {\n const transformed = def.transform(result.value, result);\n if (transformed instanceof Promise) {\n return transformed.then((value) => handleCodecTxResult(result, value, def.out, ctx));\n }\n return handleCodecTxResult(result, transformed, def.out, ctx);\n }\n else {\n const transformed = def.reverseTransform(result.value, result);\n if (transformed instanceof Promise) {\n return transformed.then((value) => handleCodecTxResult(result, value, def.in, ctx));\n }\n return handleCodecTxResult(result, transformed, def.in, ctx);\n }\n}\nfunction handleCodecTxResult(left, value, nextSchema, ctx) {\n // Check if transform added any issues\n if (left.issues.length) {\n left.aborted = true;\n return left;\n }\n return nextSchema._zod.run({ value, issues: left.issues }, ctx);\n}\nexport const $ZodPreprocess = /*@__PURE__*/ core.$constructor(\"$ZodPreprocess\", (inst, def) => {\n $ZodPipe.init(inst, def);\n});\nexport const $ZodReadonly = /*@__PURE__*/ core.$constructor(\"$ZodReadonly\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazyInternal(inst, \"propValues\", (zod) => zod.def.innerType._zod.propValues);\n util.defineLazyInternal(inst, \"values\", (zod) => zod.def.innerType._zod.values);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.innerType?._zod?.optin);\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.innerType?._zod?.optout);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then(handleReadonlyResult);\n }\n return handleReadonlyResult(result);\n };\n});\nfunction handleReadonlyResult(payload) {\n // A repeat visit hands back a node that is still being built; freezing it here would make the rest of its keys fail to assign.\n if (!payload.memo)\n payload.value = Object.freeze(payload.value);\n return payload;\n}\n// a leaf's pattern source with its own checks folded in: the last pattern-carrying check wins, else length bounds narrow the catch-all, else an integer format narrows the number form. the fold lives here instead of on `_zod.pattern` so a bundle without template literals never pays for it\nfunction leafPattern(schema) {\n const def = schema._zod.def;\n let pattern = def.pattern;\n let isInt = !!def.format?.includes(\"int\");\n let minimum;\n let maximum;\n for (const ch of def.checks ?? []) {\n const d = ch._zod.def;\n if (d.pattern)\n pattern = d.pattern;\n isInt || (isInt = !!d.format?.includes(\"int\"));\n const lo = d.minimum ?? d.length;\n const hi = d.maximum ?? d.length;\n if (lo !== undefined && (minimum === undefined || lo > minimum))\n minimum = lo;\n if (hi !== undefined && (maximum === undefined || hi < maximum))\n maximum = hi;\n }\n if (pattern)\n return pattern.source;\n // an empty range matches nothing at runtime, and `{8,5}` is not a legal quantifier\n if (minimum !== undefined && maximum !== undefined && minimum > maximum)\n return \"(?!)\";\n if (minimum !== undefined || maximum !== undefined)\n return regexes.string({ minimum, maximum }).source;\n const own = schema._zod.pattern;\n return (isInt && own === regexes.number ? regexes.integer : own)?.source;\n}\n// a part's pattern source. a wrapper's pattern embeds its inner pattern's source verbatim, so the folded form is substituted in place without knowing the wrapper's own composition; a union's options are joined the way the union builds its own pattern\nfunction partPattern(schema) {\n const def = schema._zod.def;\n const own = schema._zod.pattern?.source;\n // lazy resolves its inner on the internals, not the def\n const inner = def.innerType ?? schema._zod.innerType;\n if (inner) {\n const before = inner._zod.pattern?.source;\n const after = partPattern(inner);\n if (own && before && after && after !== before) {\n return own.replace(util.cleanRegex(before), () => util.cleanRegex(after));\n }\n return own;\n }\n if (def.options) {\n const sources = def.options.map(partPattern);\n if (sources.every(Boolean))\n return `^(${sources.map((s) => util.cleanRegex(s)).join(\"|\")})$`;\n }\n return leafPattern(schema);\n}\nexport const $ZodTemplateLiteral = /*@__PURE__*/ core.$constructor(\"$ZodTemplateLiteral\", (inst, def) => {\n $ZodType.init(inst, def);\n const regexParts = [];\n for (const part of def.parts) {\n if (typeof part === \"object\" && part !== null) {\n // is Zod schema\n const source = partPattern(part);\n if (!source) {\n throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`);\n }\n regexParts.push(util.cleanRegex(source));\n }\n else if (part === null || util.primitiveTypes.has(typeof part)) {\n regexParts.push(util.escapeRegex(`${part}`));\n }\n else {\n throw new Error(`Invalid template literal part: ${part}`);\n }\n }\n inst._zod.pattern = new RegExp(`^${regexParts.join(\"\")}$`);\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"string\") {\n payload.issues.push({\n input: payload.value,\n inst,\n expected: \"string\",\n code: \"invalid_type\",\n });\n return payload;\n }\n inst._zod.pattern.lastIndex = 0;\n if (!inst._zod.pattern.test(payload.value)) {\n payload.issues.push({\n input: payload.value,\n inst,\n code: \"invalid_format\",\n format: def.format ?? \"template_literal\",\n pattern: inst._zod.pattern.source,\n });\n return payload;\n }\n return payload;\n };\n});\nexport const $ZodFunction = /*@__PURE__*/ core.$constructor(\"$ZodFunction\", (inst, def) => {\n $ZodType.init(inst, def);\n // Defined, not assigned: the classic prototype exposes `_def` as a getter with no setter.\n Object.defineProperty(inst, \"_def\", { value: def });\n inst._zod.def = def;\n inst.implement = (func) => {\n if (typeof func !== \"function\") {\n throw new Error(\"implement() must be called with a function\");\n }\n // Defined inline so the closure stays anonymous: binding it to a `const` first names it, which costs 256 bytes per implemented function.\n return Object.defineProperty(function (...args) {\n const parsedArgs = inst._def.input ? parse(inst._def.input, args) : args;\n const result = Reflect.apply(func, this, parsedArgs);\n if (inst._def.output) {\n return parse(inst._def.output, result);\n }\n return result;\n }, \"_zod\", { value: inst._zod, enumerable: false });\n };\n inst.implementAsync = (func) => {\n if (typeof func !== \"function\") {\n throw new Error(\"implementAsync() must be called with a function\");\n }\n return Object.defineProperty(async function (...args) {\n const parsedArgs = inst._def.input ? await parseAsync(inst._def.input, args) : args;\n const result = await Reflect.apply(func, this, parsedArgs);\n if (inst._def.output) {\n return await parseAsync(inst._def.output, result);\n }\n return result;\n }, \"_zod\", { value: inst._zod, enumerable: false });\n };\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"function\") {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"function\",\n input: payload.value,\n inst,\n });\n return payload;\n }\n // Check if output is a promise type to determine if we should use async implementation\n const hasPromiseOutput = inst._def.output && inst._def.output._zod.def.type === \"promise\";\n if (hasPromiseOutput) {\n payload.value = inst.implementAsync(payload.value);\n }\n else {\n payload.value = inst.implement(payload.value);\n }\n return payload;\n };\n inst.input = (...args) => {\n const F = inst.constructor;\n if (Array.isArray(args[0])) {\n return new F({\n type: \"function\",\n input: new $ZodTuple({\n type: \"tuple\",\n items: args[0],\n rest: args[1],\n }),\n output: inst._def.output,\n });\n }\n return new F({\n type: \"function\",\n input: args[0],\n output: inst._def.output,\n });\n };\n inst.output = (output) => {\n const F = inst.constructor;\n return new F({\n type: \"function\",\n input: inst._def.input,\n output,\n });\n };\n return inst;\n});\nexport const $ZodPromise = /*@__PURE__*/ core.$constructor(\"$ZodPromise\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n return Promise.resolve(payload.value).then((inner) => def.innerType._zod.run({ value: inner, issues: [] }, ctx));\n };\n});\nexport const $ZodLazy = /*@__PURE__*/ core.$constructor(\"$ZodLazy\", (inst, def) => {\n $ZodType.init(inst, def);\n // Cache the resolved inner type on the shared `def` so all clones of this lazy (e.g. via `.describe()`/`.meta()`) share the same inner instance, preserving identity for cycle detection on recursive schemas.\n util.defineLazy(inst._zod, \"innerType\", () => {\n const d = def;\n if (!d._cachedInner)\n d._cachedInner = def.getter();\n return d._cachedInner;\n });\n util.defineLazyInternal(inst, \"pattern\", (zod) => zod.innerType?._zod?.pattern);\n util.defineLazyInternal(inst, \"propValues\", (zod) => zod.innerType?._zod?.propValues);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.innerType?._zod?.optin ?? undefined);\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.innerType?._zod?.optout ?? undefined);\n inst._zod.parse = (payload, ctx) => {\n const inner = inst._zod.innerType;\n return inner._zod.run(payload, ctx);\n };\n});\nexport const $ZodCustom = /*@__PURE__*/ core.$constructor(\"$ZodCustom\", (inst, def) => {\n checks.$ZodCheck.init(inst, def);\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _) => {\n return payload;\n };\n inst._zod.check = (payload) => {\n const input = payload.value;\n const r = def.fn(input);\n if (r instanceof Promise) {\n return r.then((r) => handleRefineResult(r, payload, input, inst));\n }\n handleRefineResult(r, payload, input, inst);\n return;\n };\n});\nfunction handleRefineResult(result, payload, input, inst) {\n if (!result) {\n const _iss = {\n code: \"custom\",\n input,\n inst, // incorporates params.error into issue reporting\n path: [...(inst._zod.def.path ?? [])], // incorporates params.error into issue reporting\n continue: !inst._zod.def.abort,\n // params: inst._zod.def.params,\n };\n if (inst._zod.def.params)\n _iss.params = inst._zod.def.params;\n payload.issues.push(util.issue(_iss));\n }\n}\n", "import * as util from \"./util.js\";\nexport class $ZodCyclicError extends Error {\n constructor() {\n super(`Cannot parse a reference cycle that closes through a transform`);\n this.name = \"ZodCyclicError\";\n }\n}\n/** Keyed off the context object every schema in one parse call already shares. */\nconst STATE = \"~memo\";\nconst NO_ISSUES = [];\n// a value a cycle can close through\nfunction isRef(value) {\n return value !== null && typeof value === \"object\";\n}\n// Receivers prefix paths in place, so the cache and every hand-out need their own copies.\nfunction cloneIssues(issues) {\n return issues.map((iss) => (iss.path ? { ...iss, path: iss.path.slice() } : { ...iss }));\n}\nconst recursive = /*@__PURE__*/ new WeakMap();\n/** What the walk established, in order of certainty: ordered so the strongest answer among children wins. */\nconst NONE = 0;\nconst ASSUMED = 1;\nconst PROVEN = 2;\n/** Whether this schema's subtree contains a cycle, so one parse can re-enter it. */\nfunction isRecursive(inst, stack, resolve) {\n const cached = recursive.get(inst);\n if (cached !== undefined)\n return cached ? PROVEN : NONE;\n // Relative to the walk in progress, so not cached.\n if (stack.has(inst))\n return PROVEN;\n stack.add(inst);\n let result = NONE;\n const check = (child) => {\n if (result !== PROVEN && child?._zod) {\n const answer = isRecursive(child, stack, resolve);\n if (answer > result)\n result = answer;\n }\n };\n // `Reflect.ownKeys` rather than `Object.keys`, so a cycle through a declared symbol key is still seen\n const shape = (sh, spread) => {\n let answer = NONE;\n for (const key of Reflect.ownKeys(sh)) {\n const desc = Object.getOwnPropertyDescriptor(sh, key);\n // an object resolves its shape by spread, so a key it does not enumerate is never parsed; `z.properties` reads every own key and so keeps them all\n if (spread && !desc.enumerable)\n continue;\n // resolving runs user code, and a factory mints a fresh subtree per read, so an edge the walk can't follow counts as a cycle\n const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve) : NONE;\n if (child > answer)\n answer = child;\n }\n return answer;\n };\n const merge = (answer) => {\n if (answer > result)\n result = answer;\n };\n const def = inst._zod.def;\n const kind = def.type;\n switch (kind) {\n case \"object\": {\n const raw = util.rawShape(def);\n // a def with no raw shape answers `shape` from an accessor of its own, and running that can mint a whole fresh subtree\n merge(raw ? shape(raw, true) : ASSUMED);\n check(def.catchall);\n break;\n }\n case \"array\":\n check(def.element);\n break;\n case \"tuple\":\n for (const el of def.items)\n check(el);\n check(def.rest);\n break;\n case \"record\":\n case \"map\":\n check(def.keyType);\n check(def.valueType);\n break;\n case \"set\":\n check(def.valueType);\n break;\n case \"union\":\n for (const el of def.options)\n check(el);\n break;\n case \"intersection\":\n check(def.left);\n check(def.right);\n break;\n case \"optional\":\n case \"nullable\":\n case \"default\":\n case \"prefault\":\n case \"catch\":\n case \"readonly\":\n case \"nonoptional\":\n case \"promise\":\n case \"success\":\n check(def.innerType);\n break;\n case \"pipe\":\n check(def.in);\n check(def.out);\n break;\n case \"function\":\n check(def.input);\n check(def.output);\n break;\n // `$ZodLazy` caches its inner on the def, so a resolved edge is followed exactly\n case \"lazy\": {\n const inner = def._cachedInner ?? (resolve ? inst._zod.innerType : undefined);\n // walked with resolution off: one hop sees past the deferral, and a lazy that yields only another unresolved lazy is generative, so it stops there\n merge(inner ? isRecursive(inner, stack, false) : ASSUMED);\n break;\n }\n // a leaf by choice: `parts` are regex fragments, not data positions\n case \"template_literal\":\n // leaves\n case \"string\":\n case \"number\":\n case \"int\":\n case \"boolean\":\n case \"bigint\":\n case \"symbol\":\n case \"undefined\":\n case \"null\":\n case \"void\":\n case \"never\":\n case \"any\":\n case \"unknown\":\n case \"date\":\n case \"nan\":\n case \"enum\":\n case \"literal\":\n case \"file\":\n case \"transform\":\n case \"custom\":\n break;\n default: {\n // a new built-in kind becomes a compile error here\n kind;\n // a user-defined kind can still hold children, and only its author knows where, so fall back to scanning the def — skipping accessors, since reading one can run user code\n for (const key in def) {\n const desc = Object.getOwnPropertyDescriptor(def, key);\n if (!desc || desc.get)\n continue;\n const value = desc.value;\n if (!value || typeof value !== \"object\")\n continue;\n if (value._zod)\n check(value);\n else if (Array.isArray(value))\n for (const el of value)\n check(el);\n }\n }\n }\n stack.delete(inst);\n return settle(inst, result);\n}\n/** An assumed answer must not outlive the resolution that settles it, so only a certain one is cached. */\nfunction settle(inst, answer) {\n if (answer !== ASSUMED)\n recursive.set(inst, answer === PROVEN);\n return answer;\n}\n/**\n * Whether one parse can re-enter this schema, i.e. its subtree contains a cycle.\n * Exported for `z.compile`, which refuses to compile such a schema: cycle\n * breaking is driven from here off state keyed on the parse context, and a\n * generated fast path has no context to key on.\n */\nexport function isRecursiveSchema(inst) {\n // z.compile never parses, so nothing would ever resolve a lazy for it; it runs once and already treats a throw here as recursive\n return isRecursive(inst, new Set(), true) !== NONE;\n}\nfunction bucketFor(state, inst) {\n let bucket = state.buckets.get(inst);\n if (!bucket) {\n bucket = new WeakMap();\n state.buckets.set(inst, bucket);\n }\n return bucket;\n}\n// Set immediately before delegating to core and cleared immediately after, so `alloc` registers only for a visit this module is driving.\nlet handoff;\n// Allocated but unfinished entries. `alloc` and the matching pop both happen in the synchronous part of a parse, so they nest even when children are async, and one stack serves every schema.\nconst open = [];\nconst memo = {\n alloc(_inst, payload, empty) {\n const bucket = handoff;\n if (!bucket)\n return empty;\n handoff = undefined;\n const entry = { value: empty, issues: null };\n bucket.set(payload.value, entry);\n open.push(entry);\n return empty;\n },\n guard(inst) {\n var _a;\n (_a = inst._zod).deferred ?? (_a.deferred = []);\n inst._zod.deferred.push(() => {\n const base = inst._zod.parse;\n const wrapped = (payload, ctx) => {\n // The value is a placeholder a back-edge is still waiting on, so the cycle closes through this transform. Its output can't exist in time to bind.\n if (ctx.direction !== \"backward\" && isBackEdge(ctx, payload.value))\n throw new $ZodCyclicError();\n return base(payload, ctx);\n };\n inst._zod.parse = wrapped;\n if (inst._zod.run === base)\n inst._zod.run = wrapped;\n });\n },\n attach(inst) {\n var _a;\n let isRecursiveInst;\n let rechecked = false;\n // a recursive schema is re-entered many times per parse and its bucket never changes\n let lastCtx;\n let lastBucket;\n // Wraps `parse` in a deferred so it sees the container's final parse. Core's own deferred copies `parse` into `run` when there are no checks, and it ran first, so `run` is patched to match; with checks, `run` reads `parse` dynamically.\n (_a = inst._zod).deferred ?? (_a.deferred = []);\n inst._zod.deferred.push(() => {\n const base = inst._zod.parse;\n const wrapped = (payload, ctx) => {\n if (isRecursiveInst === undefined) {\n const walked = isRecursive(inst, new Set(), false);\n if (walked === NONE) {\n // Nothing here can ever fire, so take it back out.\n inst._zod.parse = base;\n if (inst._zod.run === wrapped)\n inst._zod.run = base;\n return base(payload, ctx);\n }\n // this parse resolves the deferred edges on its own path, so ask once more before latching\n if (walked === PROVEN || rechecked)\n isRecursiveInst = true;\n else\n rechecked = true;\n }\n const input = payload.value;\n if (!isRef(input))\n return base(payload, ctx);\n let state = ctx[STATE];\n if (!state) {\n state = { buckets: new WeakMap(), backEdges: undefined };\n ctx[STATE] = state;\n }\n let bucket;\n if (lastCtx === ctx) {\n bucket = lastBucket;\n }\n else {\n bucket = bucketFor(state, inst);\n lastCtx = ctx;\n lastBucket = bucket;\n }\n const hit = bucket.get(input);\n if (hit) {\n payload.value = hit.value;\n if (hit.issues) {\n if (hit.issues.length)\n payload.issues.push(...cloneIssues(hit.issues));\n }\n else {\n // Still being parsed: its own checks cover it, so skip them here.\n payload.memo = true;\n state.backEdges ?? (state.backEdges = new WeakSet());\n state.backEdges.add(hit.value);\n }\n return payload;\n }\n handoff = bucket;\n const depth = open.length;\n const result = base(payload, ctx);\n handoff = undefined;\n // A container that rejected its input outright allocated nothing.\n const entry = open.length > depth ? open.pop() : undefined;\n // Both paths written out so the sync one allocates no closure. It runs once per node, and capturing here cost more than everything else combined.\n if (result instanceof Promise) {\n return result.then((r) => {\n if (entry)\n entry.issues = r.issues.length ? cloneIssues(r.issues) : NO_ISSUES;\n return r;\n });\n }\n if (entry)\n entry.issues = result.issues.length ? cloneIssues(result.issues) : NO_ISSUES;\n return result;\n };\n inst._zod.parse = wrapped;\n if (inst._zod.run === base)\n inst._zod.run = wrapped;\n });\n },\n};\n/** The memoizer that gives containers cycle support. `zod` installs it by default; `zod/mini` opts in with `config({ memoizer: memoizer() })`. */\nexport function memoizer() {\n return memo;\n}\n/** Whether this value is a node a back-edge resolved to before it finished. */\nexport function isBackEdge(ctx, value) {\n const backEdges = ctx[STATE]?.backEdges;\n return backEdges !== undefined && isRef(value) && backEdges.has(value);\n}\n", "import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"characters\", verb: \"to have\" },\n file: { unit: \"bytes\", verb: \"to have\" },\n array: { unit: \"items\", verb: \"to have\" },\n set: { unit: \"items\", verb: \"to have\" },\n map: { unit: \"entries\", verb: \"to have\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"input\",\n email: \"email address\",\n url: \"URL\",\n emoji: \"emoji\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"ISO datetime\",\n date: \"ISO date\",\n time: \"ISO time\",\n duration: \"ISO duration\",\n ipv4: \"IPv4 address\",\n ipv6: \"IPv6 address\",\n mac: \"MAC address\",\n cidrv4: \"IPv4 range\",\n cidrv6: \"IPv6 range\",\n base64: \"base64-encoded string\",\n base64url: \"base64url-encoded string\",\n json_string: \"JSON string\",\n e164: \"E.164 number\",\n currency_code: \"currency code\",\n credit_card: \"credit card number\",\n iban: \"IBAN\",\n jwt: \"JWT\",\n template_literal: \"input\",\n };\n // type names: missing keys = do not translate (use raw value via ?? fallback)\n const TypeDictionary = {\n // Compatibility: \"nan\" -> \"NaN\" for display\n nan: \"NaN\",\n // All other type names omitted - they fall back to raw values via ?? operator\n };\n function getTypeName(type, input) {\n if (type === \"number\" && typeof input === \"number\" && !Number.isFinite(input)) {\n return String(input);\n }\n return TypeDictionary[type] ?? type;\n }\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = getTypeName(issue.expected);\n const receivedType = util.parsedType(issue.input);\n const received = getTypeName(receivedType, issue.input);\n return `Invalid input: expected ${expected}, received ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `Invalid input: expected ${util.stringifyPrimitive(issue.values[0])}`;\n return `Invalid option: expected one of ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.exact ? \"exactly \" : issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `Too big: expected ${issue.origin ?? \"value\"} to have ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"elements\"}`;\n return `Too big: expected ${issue.origin ?? \"value\"} to be ${adj}${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.exact ? \"exactly \" : issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `Too small: expected ${issue.origin} to have ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n }\n return `Too small: expected ${issue.origin} to be ${adj}${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\") {\n return `Invalid string: must start with \"${_issue.prefix}\"`;\n }\n if (_issue.format === \"ends_with\")\n return `Invalid string: must end with \"${_issue.suffix}\"`;\n if (_issue.format === \"includes\")\n return `Invalid string: must include \"${_issue.includes}\"`;\n if (_issue.format === \"regex\")\n return `Invalid string: must match pattern ${_issue.pattern}`;\n return `Invalid ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `Invalid number: must be a multiple of ${issue.divisor}`;\n case \"unrecognized_keys\":\n return `Unrecognized key${issue.keys.length > 1 ? \"s\" : \"\"}: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `Invalid key in ${issue.origin}`;\n case \"invalid_union\":\n if (issue.options && Array.isArray(issue.options) && issue.options.length > 0) {\n const opts = issue.options.map((o) => `'${o}'`).join(\" | \");\n return `Invalid discriminator value. Expected ${opts}`;\n }\n if (issue.inclusive === false) {\n return \"Invalid input: more than one option matched\";\n }\n return \"Invalid input\";\n case \"invalid_element\":\n return `Invalid value in ${issue.origin}`;\n default:\n return `Invalid input`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n", "var _a;\nexport const $output = /*@__PURE__*/ Symbol(\"ZodOutput\");\nexport const $input = /*@__PURE__*/ Symbol(\"ZodInput\");\nexport class $ZodRegistry {\n constructor() {\n this._map = new WeakMap();\n this._idmap = new Map();\n }\n add(schema, ..._meta) {\n const meta = _meta[0];\n this._map.set(schema, meta);\n if (meta && typeof meta === \"object\" && \"id\" in meta) {\n this._idmap.set(meta.id, schema);\n }\n return this;\n }\n clear() {\n this._map = new WeakMap();\n this._idmap = new Map();\n return this;\n }\n remove(schema) {\n const meta = this._map.get(schema);\n if (meta && typeof meta === \"object\" && \"id\" in meta) {\n this._idmap.delete(meta.id);\n }\n this._map.delete(schema);\n return this;\n }\n get(schema) {\n // return this._map.get(schema) as any;\n // inherit metadata\n const p = schema._zod.parent;\n if (p) {\n const pm = { ...(this.get(p) ?? {}) };\n delete pm.id; // do not inherit id\n const f = { ...pm, ...this._map.get(schema) };\n return Object.keys(f).length ? f : undefined;\n }\n return this._map.get(schema);\n }\n has(schema) {\n return this._map.has(schema);\n }\n}\n// registries\nexport function registry() {\n return new $ZodRegistry();\n}\n(_a = globalThis).__zod_globalRegistry ?? (_a.__zod_globalRegistry = registry());\nexport const globalRegistry = globalThis.__zod_globalRegistry;\n", "import * as checks from \"./checks.js\";\nimport * as registries from \"./registries.js\";\nimport * as schemas from \"./schemas.js\";\nimport * as util from \"./util.js\";\nfunction snapshotChecks(def) {\n if (def.checks)\n def.checks = [...def.checks];\n return def;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _string(Class, params) {\n return new Class(snapshotChecks({ type: \"string\", ...util.normalizeParams(params) }));\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedString(Class, params) {\n return new Class(snapshotChecks({ type: \"string\", coerce: true, ...util.normalizeParams(params) }));\n}\n// @__NO_SIDE_EFFECTS__\nexport function _email(Class, params) {\n return new Class({\n type: \"string\",\n format: \"email\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _guid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"guid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v4\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v6\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv7(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v7\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _url(Class, params) {\n return new Class({\n type: \"string\",\n format: \"url\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _emoji(Class, params) {\n return new Class({\n type: \"string\",\n format: \"emoji\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nanoid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"nanoid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link _cuid2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\n// @__NO_SIDE_EFFECTS__\nexport function _cuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cuid2(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cuid2\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ulid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ulid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _xid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"xid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ksuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ksuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ipv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ipv4\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ipv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ipv6\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _mac(Class, params) {\n return new Class({\n type: \"string\",\n format: \"mac\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cidrv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cidrv4\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cidrv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cidrv6\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _base64(Class, params) {\n return new Class({\n type: \"string\",\n format: \"base64\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _base64url(Class, params) {\n return new Class({\n type: \"string\",\n format: \"base64url\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _e164(Class, params) {\n return new Class({\n type: \"string\",\n format: \"e164\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _creditCard(Class, params) {\n return new Class({\n type: \"string\",\n format: \"credit_card\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _iban(Class, params) {\n return new Class({\n type: \"string\",\n format: \"iban\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _jwt(Class, params) {\n return new Class({\n type: \"string\",\n format: \"jwt\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\nexport const TimePrecision = {\n Any: null,\n Minute: -1,\n Second: 0,\n Millisecond: 3,\n Microsecond: 6,\n};\n// @__NO_SIDE_EFFECTS__\nexport function _isoDateTime(Class, params) {\n return new Class({\n type: \"string\",\n format: \"datetime\",\n check: \"string_format\",\n offset: false,\n local: false,\n precision: null,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoDate(Class, params) {\n return new Class({\n type: \"string\",\n format: \"date\",\n check: \"string_format\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoTime(Class, params) {\n return new Class({\n type: \"string\",\n format: \"time\",\n check: \"string_format\",\n precision: null,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoDuration(Class, params) {\n return new Class({\n type: \"string\",\n format: \"duration\",\n check: \"string_format\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _number(Class, params) {\n return new Class(snapshotChecks({ type: \"number\", checks: [], ...util.normalizeParams(params) }));\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedNumber(Class, params) {\n return new Class(snapshotChecks({ type: \"number\", coerce: true, checks: [], ...util.normalizeParams(params) }));\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"safeint\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _float32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"float32\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _float64(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"float64\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"int32\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uint32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"uint32\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _boolean(Class, params) {\n return new Class({\n type: \"boolean\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedBoolean(Class, params) {\n return new Class({\n type: \"boolean\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _bigint(Class, params) {\n return new Class({\n type: \"bigint\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedBigint(Class, params) {\n return new Class({\n type: \"bigint\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int64(Class, params) {\n return new Class({\n type: \"bigint\",\n check: \"bigint_format\",\n abort: false,\n format: \"int64\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uint64(Class, params) {\n return new Class({\n type: \"bigint\",\n check: \"bigint_format\",\n abort: false,\n format: \"uint64\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _symbol(Class, params) {\n return new Class({\n type: \"symbol\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _undefined(Class, params) {\n return new Class({\n type: \"undefined\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _null(Class, params) {\n return new Class({\n type: \"null\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _any(Class) {\n return new Class({\n type: \"any\",\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _unknown(Class) {\n return new Class({\n type: \"unknown\",\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _never(Class, params) {\n return new Class({\n type: \"never\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _void(Class, params) {\n return new Class({\n type: \"void\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _date(Class, params) {\n return new Class({\n type: \"date\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedDate(Class, params) {\n return new Class({\n type: \"date\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nan(Class, params) {\n return new Class({\n type: \"nan\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lt(value, params) {\n return new checks.$ZodCheckLessThan({\n check: \"less_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: false,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lte(value, params) {\n return new checks.$ZodCheckLessThan({\n check: \"less_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: true,\n });\n}\nexport { \n/** @deprecated Use `z.lte()` instead. */\n_lte as _max, };\n// @__NO_SIDE_EFFECTS__\nexport function _gt(value, params) {\n return new checks.$ZodCheckGreaterThan({\n check: \"greater_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: false,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _gte(value, params) {\n return new checks.$ZodCheckGreaterThan({\n check: \"greater_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: true,\n });\n}\nexport { \n/** @deprecated Use `z.gte()` instead. */\n_gte as _min, };\n// @__NO_SIDE_EFFECTS__\nexport function _positive(params) {\n return _gt(0, params);\n}\n// negative\n// @__NO_SIDE_EFFECTS__\nexport function _negative(params) {\n return _lt(0, params);\n}\n// nonpositive\n// @__NO_SIDE_EFFECTS__\nexport function _nonpositive(params) {\n return _lte(0, params);\n}\n// nonnegative\n// @__NO_SIDE_EFFECTS__\nexport function _nonnegative(params) {\n return _gte(0, params);\n}\n// @__NO_SIDE_EFFECTS__\nexport function _multipleOf(value, params) {\n return new checks.$ZodCheckMultipleOf({\n check: \"multiple_of\",\n ...util.normalizeParams(params),\n value,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _maxSize(maximum, params) {\n return new checks.$ZodCheckMaxSize({\n check: \"max_size\",\n ...util.normalizeParams(params),\n maximum,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _minSize(minimum, params) {\n return new checks.$ZodCheckMinSize({\n check: \"min_size\",\n ...util.normalizeParams(params),\n minimum,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _size(size, params) {\n return new checks.$ZodCheckSizeEquals({\n check: \"size_equals\",\n ...util.normalizeParams(params),\n size,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _maxLength(maximum, params) {\n const ch = new checks.$ZodCheckMaxLength({\n check: \"max_length\",\n ...util.normalizeParams(params),\n maximum,\n });\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _minLength(minimum, params) {\n return new checks.$ZodCheckMinLength({\n check: \"min_length\",\n ...util.normalizeParams(params),\n minimum,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _length(length, params) {\n return new checks.$ZodCheckLengthEquals({\n check: \"length_equals\",\n ...util.normalizeParams(params),\n length,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _regex(pattern, params) {\n return new checks.$ZodCheckRegex({\n check: \"string_format\",\n format: \"regex\",\n ...util.normalizeParams(params),\n pattern,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lowercase(params) {\n return new checks.$ZodCheckLowerCase({\n check: \"string_format\",\n format: \"lowercase\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uppercase(params) {\n return new checks.$ZodCheckUpperCase({\n check: \"string_format\",\n format: \"uppercase\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _includes(includes, params) {\n return new checks.$ZodCheckIncludes({\n check: \"string_format\",\n format: \"includes\",\n ...util.normalizeParams(params),\n includes,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _startsWith(prefix, params) {\n return new checks.$ZodCheckStartsWith({\n check: \"string_format\",\n format: \"starts_with\",\n ...util.normalizeParams(params),\n prefix,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _endsWith(suffix, params) {\n return new checks.$ZodCheckEndsWith({\n check: \"string_format\",\n format: \"ends_with\",\n ...util.normalizeParams(params),\n suffix,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _property(property, schema, params) {\n return new checks.$ZodCheckProperty({\n check: \"property\",\n property,\n schema,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _properties(shape, params) {\n return new checks.$ZodCheckProperties({\n check: \"properties\",\n shape,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _mime(types, params) {\n return new checks.$ZodCheckMimeType({\n check: \"mime_type\",\n mime: types,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _overwrite(tx) {\n return new checks.$ZodCheckOverwrite({\n check: \"overwrite\",\n tx,\n });\n}\n// normalize\n// @__NO_SIDE_EFFECTS__\nexport function _normalize(form) {\n return _overwrite((input) => input.normalize(form));\n}\n// trim\n// @__NO_SIDE_EFFECTS__\nexport function _trim() {\n return _overwrite((input) => input.trim());\n}\n// toLowerCase\n// @__NO_SIDE_EFFECTS__\nexport function _toLowerCase() {\n return _overwrite((input) => input.toLowerCase());\n}\n// toUpperCase\n// @__NO_SIDE_EFFECTS__\nexport function _toUpperCase() {\n return _overwrite((input) => input.toUpperCase());\n}\n// slugify\n// @__NO_SIDE_EFFECTS__\nexport function _slugify() {\n return _overwrite((input) => util.slugify(input));\n}\n// @__NO_SIDE_EFFECTS__\nexport function _array(Class, element, params) {\n return new Class({\n type: \"array\",\n element,\n // get element() {\n // return element;\n // },\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _union(Class, options, params) {\n return new Class({\n type: \"union\",\n options,\n ...util.normalizeParams(params),\n });\n}\nexport function _xor(Class, options, params) {\n return new Class({\n type: \"union\",\n options,\n inclusive: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _discriminatedUnion(Class, discriminator, options, params) {\n return new Class({\n type: \"union\",\n options: options,\n discriminator,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _intersection(Class, left, right) {\n return new Class({\n type: \"intersection\",\n left,\n right,\n });\n}\n// export function _tuple(\n// Class: util.SchemaClass<schemas.$ZodTuple>,\n// items: [],\n// params?: string | $ZodTupleParams\n// ): schemas.$ZodTuple<[], null>;\n// @__NO_SIDE_EFFECTS__\nexport function _tuple(Class, items, _paramsOrRest, _params) {\n const hasRest = _paramsOrRest instanceof schemas.$ZodType;\n const params = hasRest ? _params : _paramsOrRest;\n const rest = hasRest ? _paramsOrRest : null;\n return new Class({\n type: \"tuple\",\n items,\n rest,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _record(Class, keyType, valueType, params) {\n return new Class({\n type: \"record\",\n keyType,\n valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _map(Class, keyType, valueType, params) {\n return new Class({\n type: \"map\",\n keyType,\n valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _set(Class, valueType, params) {\n return new Class({\n type: \"set\",\n valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _enum(Class, values, params) {\n const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;\n // if (Array.isArray(values)) {\n // for (const value of values) {\n // entries[value] = value;\n // }\n // } else {\n // Object.assign(entries, values);\n // }\n // const entries: util.EnumLike = {};\n // for (const val of values) {\n // entries[val] = val;\n // }\n return new Class({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\n/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead.\n *\n * ```ts\n * enum Colors { red, green, blue }\n * z.enum(Colors);\n * ```\n */\nexport function _nativeEnum(Class, entries, params) {\n return new Class({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _literal(Class, value, params) {\n return new Class({\n type: \"literal\",\n values: Array.isArray(value) ? value : [value],\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _file(Class, params) {\n return new Class({\n type: \"file\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _transform(Class, fn) {\n return new Class({\n type: \"transform\",\n transform: fn,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _optional(Class, innerType) {\n return new Class({\n type: \"optional\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nullable(Class, innerType) {\n return new Class({\n type: \"nullable\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _default(Class, innerType, defaultValue) {\n return new Class({\n type: \"default\",\n innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nonoptional(Class, innerType, params) {\n return new Class({\n type: \"nonoptional\",\n innerType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _success(Class, innerType) {\n return new Class({\n type: \"success\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _catch(Class, innerType, catchValue) {\n return new Class({\n type: \"catch\",\n innerType,\n catchValue: (typeof catchValue === \"function\" ? catchValue : util.constantCatch(catchValue)),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _pipe(Class, in_, out) {\n return new Class({\n type: \"pipe\",\n in: in_,\n out,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _readonly(Class, innerType) {\n return new Class({\n type: \"readonly\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _templateLiteral(Class, parts, params) {\n return new Class({\n type: \"template_literal\",\n parts,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lazy(Class, getter) {\n return new Class({\n type: \"lazy\",\n getter,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _promise(Class, innerType) {\n return new Class({\n type: \"promise\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _custom(Class, fn, _params) {\n const norm = util.normalizeParams(_params);\n norm.abort ?? (norm.abort = true); // default to abort:false\n const schema = new Class({\n type: \"custom\",\n check: \"custom\",\n fn: fn,\n ...norm,\n });\n return schema;\n}\n// same as _custom but defaults to abort:false\n// @__NO_SIDE_EFFECTS__\nexport function _refine(Class, fn, _params) {\n const schema = new Class({\n type: \"custom\",\n check: \"custom\",\n fn: fn,\n ...util.normalizeParams(_params),\n });\n return schema;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _superRefine(fn, params) {\n const ch = _check((payload) => {\n payload.addIssue = (issue) => {\n if (typeof issue === \"string\") {\n payload.issues.push(util.issue(issue, payload.value, ch._zod.def));\n }\n else {\n // for Zod 3 backwards compatibility\n const _issue = issue;\n if (_issue.fatal)\n _issue.continue = false;\n _issue.code ?? (_issue.code = \"custom\");\n if (!(\"input\" in _issue))\n _issue.input = payload.value;\n _issue.inst ?? (_issue.inst = ch);\n _issue.continue ?? (_issue.continue = !ch._zod.def.abort); // abort is always undefined, so this is always true...\n payload.issues.push(util.issue(_issue));\n }\n };\n return fn(payload.value, payload);\n }, params);\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _check(fn, params) {\n const ch = new checks.$ZodCheck({\n check: \"custom\",\n ...util.normalizeParams(params),\n });\n ch._zod.check = fn;\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function describe(description) {\n const ch = new checks.$ZodCheck({ check: \"describe\" });\n ch._zod.onattach = [\n (inst) => {\n const existing = registries.globalRegistry.get(inst) ?? {};\n registries.globalRegistry.add(inst, { ...existing, description });\n },\n ];\n ch._zod.check = () => { }; // no-op check\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function meta(metadata) {\n const ch = new checks.$ZodCheck({ check: \"meta\" });\n ch._zod.onattach = [\n (inst) => {\n const existing = registries.globalRegistry.get(inst) ?? {};\n registries.globalRegistry.add(inst, { ...existing, ...metadata });\n },\n ];\n ch._zod.check = () => { }; // no-op check\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _stringbool(Classes, _params) {\n const params = util.normalizeParams(_params);\n let truthyArray = params.truthy ?? [\"true\", \"1\", \"yes\", \"on\", \"y\", \"enabled\"];\n let falsyArray = params.falsy ?? [\"false\", \"0\", \"no\", \"off\", \"n\", \"disabled\"];\n if (params.case !== \"sensitive\") {\n truthyArray = truthyArray.map((v) => (typeof v === \"string\" ? v.toLowerCase() : v));\n falsyArray = falsyArray.map((v) => (typeof v === \"string\" ? v.toLowerCase() : v));\n }\n const truthySet = new Set(truthyArray);\n const falsySet = new Set(falsyArray);\n const _Codec = Classes.Codec ?? schemas.$ZodCodec;\n const _Boolean = Classes.Boolean ?? schemas.$ZodBoolean;\n const _String = Classes.String ?? schemas.$ZodString;\n const stringSchema = new _String({ type: \"string\", error: params.error });\n const booleanSchema = new _Boolean({ type: \"boolean\", error: params.error });\n const codec = new _Codec({\n type: \"pipe\",\n in: stringSchema,\n out: booleanSchema,\n transform: ((input, payload) => {\n let data = input;\n if (params.case !== \"sensitive\")\n data = data.toLowerCase();\n if (truthySet.has(data)) {\n return true;\n }\n else if (falsySet.has(data)) {\n return false;\n }\n else {\n payload.issues.push({\n code: \"invalid_value\",\n expected: \"stringbool\",\n values: [...truthySet, ...falsySet],\n input: payload.value,\n inst: codec,\n continue: false,\n });\n return {};\n }\n }),\n reverseTransform: ((input, _payload) => {\n if (input === true) {\n return truthyArray[0] || \"true\";\n }\n else {\n return falsyArray[0] || \"false\";\n }\n }),\n error: params.error,\n });\n codec._zod.bag.truthy = truthyArray;\n codec._zod.bag.falsy = falsyArray;\n codec._zod.bag.case = params.case ?? \"insensitive\";\n return codec;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _stringFormat(Class, format, fnOrRegex, _params = {}) {\n const params = util.normalizeParams(_params);\n const def = {\n check: \"string_format\",\n type: \"string\",\n format,\n fn: typeof fnOrRegex === \"function\" ? fnOrRegex : (val) => fnOrRegex.test(val),\n ...params,\n };\n if (fnOrRegex instanceof RegExp) {\n def.pattern = fnOrRegex;\n }\n const inst = new Class(def);\n return inst;\n}\n", "import { globalRegistry } from \"./registries.js\";\nimport { assignProp } from \"./util.js\";\nfunction assignProps(target, ...sources) {\n for (const source of sources) {\n for (const key of Reflect.ownKeys(source)) {\n if (Object.prototype.propertyIsEnumerable.call(source, key)) {\n assignProp(target, key, source[key]);\n }\n }\n }\n return target;\n}\n// function initializeContext<T extends schemas.$ZodType>(inputs: JSONSchemaGeneratorParams<T>): ToJSONSchemaContext<T> {\n// return {\n// processor: inputs.processor,\n// metadataRegistry: inputs.metadata ?? globalRegistry,\n// target: inputs.target ?? \"draft-2020-12\",\n// unrepresentable: inputs.unrepresentable ?? \"throw\",\n// };\n// }\nexport function initializeContext(params) {\n // Normalize target: convert old non-hyphenated versions to hyphenated versions\n let target = params?.target ?? \"draft-2020-12\";\n if (target === \"draft-4\")\n target = \"draft-04\";\n if (target === \"draft-7\")\n target = \"draft-07\";\n return {\n processors: params.processors ?? {},\n metadataRegistry: params?.metadata ?? globalRegistry,\n target,\n unrepresentable: params?.unrepresentable ?? \"throw\",\n override: params?.override ?? (() => { }),\n io: params?.io ?? \"output\",\n counter: 0,\n seen: new Map(),\n sharedDefsExtractedFor: undefined,\n sharedEmitDoneFor: undefined,\n cycles: params?.cycles ?? \"ref\",\n reused: params?.reused ?? \"inline\",\n intersections: [],\n deferred: [],\n external: params?.external ?? undefined,\n };\n}\n/**\n * Applies the `unrepresentable` setting at a site that has no JSON Schema equivalent. Throws\n * `message` unless the setting (or the handler's return value) says otherwise. Returns `true` if a\n * custom JSON Schema was written into `json`, in which case the caller must not write its own.\n */\nexport function handleUnrepresentable(schema, ctx, json, params, message) {\n const result = typeof ctx.unrepresentable === \"function\"\n ? ctx.unrepresentable({ zodSchema: schema, path: params.path, message })\n : ctx.unrepresentable;\n if (result === \"any\")\n return false;\n if (result === undefined || result === \"throw\")\n throw new Error(message);\n Object.assign(json, result);\n return true;\n}\n// never rename this back to `process`: bundler polyfills inject a top-level `const process` that a lexical declaration of the same name collides with (#6397)\nexport function processSchema(schema, ctx, _params = { path: [], schemaPath: [] }) {\n var _a;\n const def = schema._zod.def;\n // check for schema in seens\n const seen = ctx.seen.get(schema);\n if (seen) {\n seen.count++;\n // check if cycle\n const isCycle = _params.schemaPath.includes(schema);\n if (isCycle) {\n seen.cycle = _params.path;\n }\n return seen.schema;\n }\n // initialize\n const result = { schema: {}, count: 1, cycle: undefined, path: _params.path };\n ctx.seen.set(schema, result);\n ctx.sharedDefsExtractedFor = undefined;\n ctx.sharedEmitDoneFor = undefined;\n // custom method overrides default behavior\n const overrideSchema = schema._zod.toJSONSchema?.();\n if (overrideSchema) {\n result.schema = overrideSchema;\n }\n else {\n const params = {\n ..._params,\n schemaPath: [..._params.schemaPath, schema],\n path: _params.path,\n };\n if (schema._zod.processJSONSchema) {\n schema._zod.processJSONSchema(ctx, result.schema, params);\n }\n else {\n const _json = result.schema;\n const processor = ctx.processors[def.type];\n if (!processor) {\n throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`);\n }\n processor(schema, ctx, _json, params);\n }\n const parent = schema._zod.parent;\n if (parent) {\n // Also set ref if processor didn't (for inheritance)\n if (!result.ref)\n result.ref = parent;\n processSchema(parent, ctx, params);\n ctx.seen.get(parent).isParent = true;\n }\n }\n // metadata\n const meta = ctx.metadataRegistry.get(schema);\n if (meta)\n assignProps(result.schema, meta);\n if (ctx.io === \"input\" && isTransforming(schema)) {\n // examples/defaults only apply to output type of pipe\n delete result.schema.examples;\n delete result.schema.default;\n }\n // set prefault as default\n if (ctx.io === \"input\" && \"_prefault\" in result.schema)\n (_a = result.schema).default ?? (_a.default = result.schema._prefault);\n delete result.schema._prefault;\n // pulling fresh from ctx.seen in case it was overwritten\n const _result = ctx.seen.get(schema);\n return _result.schema;\n}\n/** @deprecated Renamed to `processSchema`. An export alias declares no binding, so it is safe to keep. */\nexport { processSchema as process };\n// Escape a reference token for use in a JSON Pointer fragment (RFC 6901): `~` becomes `~0` and `/` becomes `~1`. The `~` replacement must run first.\nfunction encodeJSONPointerSegment(segment) {\n return segment.replace(/~/g, \"~0\").replace(/\\//g, \"~1\");\n}\nexport function extractDefs(ctx, schema\n// params: EmitParams\n) {\n // iterate over seen map;\n const root = ctx.seen.get(schema);\n if (!root)\n throw new Error(\"Unprocessed schema. This is a bug in Zod.\");\n // With `external` set, every registered schema resolves through the external branch of `makeURI`, so the root branch below produces the same ref the external branch would — this pass is identical whichever schema it is called with, and only needs to run once.\n if (ctx.external && ctx.sharedDefsExtractedFor === ctx.external)\n return;\n // Track ids to detect duplicates across different schemas\n const idToSchema = new Map();\n for (const entry of ctx.seen.entries()) {\n const id = ctx.metadataRegistry.get(entry[0])?.id;\n if (id) {\n const existing = idToSchema.get(id);\n if (existing && existing !== entry[0]) {\n throw new Error(`Duplicate schema id \"${id}\" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);\n }\n idToSchema.set(id, entry[0]);\n }\n }\n // returns a ref to the schema defId will be empty if the ref points to an external schema (or #)\n const makeURI = (entry) => {\n // comparing the seen objects because sometimes multiple schemas map to the same seen object. e.g. lazy\n // external is configured\n const defsSegment = ctx.target === \"draft-2020-12\" ? \"$defs\" : \"definitions\";\n if (ctx.external) {\n const externalId = ctx.external.registry.get(entry[0])?.id; // ?? \"__shared\";// `__schema${ctx.counter++}`;\n // check if schema is in the external registry\n const uriGenerator = ctx.external.uri ?? ((id) => id);\n if (externalId) {\n return { ref: uriGenerator(externalId) };\n }\n // otherwise, add to __shared\n const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`;\n entry[1].defId = id; // set defId so it will be reused if needed\n return { defId: id, ref: `${uriGenerator(\"__shared\")}#/${defsSegment}/${encodeJSONPointerSegment(id)}` };\n }\n const uriPrefix = `#`;\n const defUriPrefix = `${uriPrefix}/${defsSegment}/`;\n // an id-less root has nowhere to be extracted to, so it stays inline and self-references as `#`\n if (entry[1] === root && !entry[1].schema.id) {\n return { ref: uriPrefix };\n }\n // self-contained schema\n const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`;\n return { defId, ref: defUriPrefix + encodeJSONPointerSegment(defId) };\n };\n // stored cached version in `def` property remove all properties, set $ref\n const extractToDef = (entry) => {\n // if the schema is already a reference, do not extract it\n if (entry[1].schema.$ref) {\n return;\n }\n const seen = entry[1];\n const { ref, defId } = makeURI(entry);\n seen.def = { ...seen.schema };\n // defId won't be set if the schema is a reference to an external schema or if the schema is the root schema\n if (defId)\n seen.defId = defId;\n // wipe away all properties except $ref\n const schema = seen.schema;\n for (const key in schema) {\n delete schema[key];\n }\n schema.$ref = ref;\n };\n // throw on cycles\n // break cycles\n if (ctx.cycles === \"throw\") {\n for (const entry of ctx.seen.entries()) {\n const seen = entry[1];\n if (seen.cycle) {\n throw new Error(\"Cycle detected: \" +\n `#/${seen.cycle?.join(\"/\")}/<root>` +\n '\\n\\nSet the `cycles` parameter to `\"ref\"` to resolve cyclical schemas with defs.');\n }\n }\n }\n // extract schemas into $defs\n for (const entry of ctx.seen.entries()) {\n const seen = entry[1];\n // convert root schema to # $ref\n if (schema === entry[0]) {\n extractToDef(entry); // this has special handling for the root schema\n continue;\n }\n // extract schemas that are in the external registry\n if (ctx.external) {\n const ext = ctx.external.registry.get(entry[0])?.id;\n if (schema !== entry[0] && ext) {\n extractToDef(entry);\n continue;\n }\n }\n // extract schemas with `id` meta\n const id = ctx.metadataRegistry.get(entry[0])?.id;\n if (id) {\n extractToDef(entry);\n continue;\n }\n // break cycles\n if (seen.cycle) {\n // any\n extractToDef(entry);\n continue;\n }\n // extract reused schemas\n if (seen.count > 1) {\n if (ctx.reused === \"ref\") {\n extractToDef(entry);\n }\n }\n }\n if (ctx.external)\n ctx.sharedDefsExtractedFor = ctx.external;\n}\n/** Rewrites `anyOf: [{type: \"a\"}, {type: \"b\"}]` to `type: [\"a\", \"b\"]`, which every JSON Schema draft treats as equivalent and most consumers render far better for the nullable case. Only branches that are a bare type assertion qualify — anything carrying a constraint, `$ref`, `const` or metadata is left alone. Runs after `flattenRef`, so a branch an override decorated or `$defs` extraction turned into a `$ref` is no longer bare and correctly stays in `anyOf`. `oneOf` is excluded: `integer` and `number` overlap, so \"exactly one\" and \"at least one\" are not the same there. OpenAPI 3.0 is excluded: its `type` must be a single string. */\nfunction compactTypeUnion(schema) {\n const options = schema.anyOf;\n if (!Array.isArray(options) || options.length === 0 || schema.type !== undefined)\n return;\n const types = [];\n for (const option of options) {\n if (!option || typeof option !== \"object\")\n return;\n // A branch that is itself a compactible union folds into this one — nested `anyOf` and a flat `type` array say the same thing. Compacting it first also makes the result independent of the order this pass walks the seen map in.\n compactTypeUnion(option);\n const keys = Object.keys(option);\n if (keys.length !== 1 || keys[0] !== \"type\")\n return;\n const type = option.type;\n for (const member of Array.isArray(type) ? type : [type]) {\n if (typeof member !== \"string\")\n return;\n if (!types.includes(member))\n types.push(member);\n }\n }\n delete schema.anyOf;\n // A `type` array must be non-empty and unique (metaschema); a single member is spelled as a bare string.\n schema.type = types.length === 1 ? types[0] : types;\n}\n/** Keywords `foldIntersection` knows how to combine. Anything else — `$ref`, `patternProperties`,\n * an annotation like `description` — makes a member unfoldable, so a constraint this does not\n * understand leaves the `allOf` alone instead of being silently dropped or misattributed. */\nconst FOLDABLE_KEYS = new Set([\"type\", \"properties\", \"required\", \"additionalProperties\"]);\nconst UNION_KEYS = [\"oneOf\", \"anyOf\"];\n/** A member's constraint on a key it does not declare itself. A `catchall` states one; `false`, an absent `additionalProperties`, and the empty schema a loose object emits state nothing. */\nfunction undeclaredConstraint(member) {\n const extra = member.additionalProperties;\n if (extra === undefined || extra === false || typeof extra !== \"object\" || extra === null)\n return null;\n return Object.keys(extra).length ? extra : null;\n}\n/** Combines object members into the single object they describe together, or returns `null` if any of them carries a keyword outside {@link FOLDABLE_KEYS}. */\nfunction foldObjects(members) {\n const objects = [];\n for (const member of members) {\n // A boolean subschema is legal JSON Schema and carries no keywords to fold.\n if (typeof member !== \"object\" || member.type !== \"object\")\n return null;\n for (const key in member) {\n if (!FOLDABLE_KEYS.has(key))\n return null;\n }\n objects.push(member);\n }\n const properties = {};\n const required = new Set();\n for (const object of objects) {\n for (const key in object.properties) {\n // `in` would report a `__proto__` key as already present via the prototype chain and skip it.\n if (Object.prototype.hasOwnProperty.call(properties, key))\n continue;\n // Every member constrains this key: the ones that declare it say how, and a `catchall` member constrains it too even though it does not name it. The key has to satisfy all of them, which is the same intersection one level down.\n const parts = [];\n for (const other of objects) {\n const part = other.properties?.[key] ?? undeclaredConstraint(other);\n if (part === null || part === undefined)\n continue;\n if (!parts.some((seen) => JSON.stringify(seen) === JSON.stringify(part)))\n parts.push(part);\n }\n const merged = parts.length === 1\n ? parts[0]\n : (foldObjects(parts) ?? { allOf: parts });\n assignProp(properties, key, merged);\n }\n for (const key of object.required ?? [])\n required.add(key);\n }\n const folded = { type: \"object\", properties };\n if (required.size)\n folded.required = [...required];\n // A key no member declares is rejected only when every member rejects it, so the fold is closed only when every member is. Otherwise it carries whatever the `catchall` members demand of such a key.\n if (objects.every((object) => object.additionalProperties === false)) {\n folded.additionalProperties = false;\n }\n else {\n const constraints = [];\n for (const object of objects) {\n const constraint = undeclaredConstraint(object);\n if (constraint && !constraints.some((seen) => JSON.stringify(seen) === JSON.stringify(constraint)))\n constraints.push(constraint);\n }\n if (constraints.length === 1)\n folded.additionalProperties = constraints[0];\n else if (constraints.length > 1)\n folded.additionalProperties = { allOf: constraints };\n }\n return folded;\n}\n/** `additionalProperties` in an `allOf` member sees only that member's own `properties`, so two\n * closed object members reject each other's keys and the schema validates nothing. Zod's parser\n * pools the key sets instead — `handleIntersectionResults` reports a key as unrecognized only when\n * *every* side rejects it — so the emitted schema has to pool them too, and folding the members\n * into one object is the encoding that says so on every target.\n *\n * This runs from `finalize`, after `extractDefs`, which is what keeps it clear of the `$ref`\n * machinery: a member extracted into `$defs` is already a `$ref` by now and declines to fold, so it\n * keeps its reference and its own closedness rather than being inlined as a stale copy. */\nfunction foldIntersection(json) {\n const allOf = json.allOf;\n if (!Array.isArray(allOf) || allOf.length < 2)\n return;\n // An `override` runs before this pass and may have written object keywords onto the intersection itself. Those are deliberate, so decline rather than overwrite them.\n for (const key of FOLDABLE_KEYS)\n if (key in json)\n return;\n // An intersection distributes over a union: `A & (X | Y)` is `(A & X) | (A & Y)`. Only the first union is distributed over; a second one stays among the members every branch folds against, where it fails the object check and declines the whole intersection rather than multiplying out.\n const unions = allOf.filter((m) => UNION_KEYS.some((k) => Array.isArray(m[k])));\n let folded = null;\n if (!unions.length) {\n folded = foldObjects(allOf);\n }\n else {\n const union = unions[0];\n const keyword = UNION_KEYS.find((k) => Array.isArray(union[k]));\n if (Object.keys(union).length !== 1)\n return;\n const rest = allOf.filter((m) => m !== union);\n const branches = union[keyword].map((branch) => foldObjects([...rest, branch]));\n if (branches.some((b) => !b))\n return;\n folded = { [keyword]: branches };\n }\n if (!folded)\n return;\n delete json.allOf;\n assignProps(json, folded);\n}\nexport function finalize(ctx, schema) {\n const root = ctx.seen.get(schema);\n if (!root)\n throw new Error(\"Unprocessed schema. This is a bug in Zod.\");\n // flatten refs - inherit properties from parent schemas\n const flattenRef = (zodSchema) => {\n const seen = ctx.seen.get(zodSchema);\n // already processed\n if (seen.ref === null)\n return;\n const schema = seen.def ?? seen.schema;\n const _cached = { ...schema };\n const ref = seen.ref;\n seen.ref = null; // prevent infinite recursion\n if (ref) {\n flattenRef(ref);\n const refSeen = ctx.seen.get(ref);\n const refSchema = refSeen.schema;\n // merge referenced schema into current\n if (refSchema.$ref && (ctx.target === \"draft-07\" || ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\")) {\n // older drafts can't combine $ref with other properties\n schema.allOf = schema.allOf ?? [];\n schema.allOf.push(refSchema);\n }\n else {\n assignProps(schema, refSchema);\n }\n // restore child's own properties (child wins)\n assignProps(schema, _cached);\n const isParentRef = zodSchema._zod.parent === ref;\n // For parent chain, child is a refinement - remove parent-only properties\n if (isParentRef) {\n for (const key in schema) {\n if (key === \"$ref\" || key === \"allOf\")\n continue;\n if (!(key in _cached)) {\n delete schema[key];\n }\n }\n }\n // When ref was extracted to $defs, remove properties that match the definition\n if (refSchema.$ref && refSeen.def) {\n for (const key in schema) {\n if (key === \"$ref\" || key === \"allOf\")\n continue;\n if (key in refSeen.def && JSON.stringify(schema[key]) === JSON.stringify(refSeen.def[key])) {\n delete schema[key];\n }\n }\n }\n }\n // If parent was extracted (has $ref), propagate $ref to this schema. This handles cases like: readonly().meta({id}).describe() where processor sets ref to innerType but parent should be referenced\n const parent = zodSchema._zod.parent;\n if (parent && parent !== ref) {\n // Ensure parent is processed first so its def has inherited properties\n flattenRef(parent);\n const parentSeen = ctx.seen.get(parent);\n if (parentSeen?.schema.$ref) {\n schema.$ref = parentSeen.schema.$ref;\n // De-duplicate with parent's definition\n if (parentSeen.def) {\n for (const key in schema) {\n if (key === \"$ref\" || key === \"allOf\")\n continue;\n if (key in parentSeen.def && JSON.stringify(schema[key]) === JSON.stringify(parentSeen.def[key])) {\n delete schema[key];\n }\n }\n }\n }\n }\n // execute overrides\n ctx.override({\n zodSchema: zodSchema,\n jsonSchema: schema,\n path: seen.path ?? [],\n });\n };\n // Flattening walks the whole map and clears each `ref` as it goes, so a second call over the same map is a no-op scan. Skip it outright once it has run for a registry conversion.\n if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) {\n for (const entry of [...ctx.seen.entries()].reverse()) {\n flattenRef(entry[0]);\n }\n if (ctx.target !== \"openapi-3.0\") {\n for (const entry of ctx.seen.entries()) {\n compactTypeUnion(entry[1].def ?? entry[1].schema);\n }\n }\n for (const rewrite of ctx.deferred)\n rewrite();\n // After flattening, every member that was extracted is a `$ref`, so the fold sees the final shape. A schema that inherits an intersection — through `z.lazy`, or any `ref` chain — holds the same `allOf` array, so fold by array identity to catch every copy.\n if (ctx.intersections.length) {\n const carriers = new Map();\n for (const seen of ctx.seen.values()) {\n for (const json of [seen.schema, seen.def]) {\n const allOf = json?.allOf;\n if (!Array.isArray(allOf))\n continue;\n const existing = carriers.get(allOf);\n if (existing)\n existing.push(json);\n else\n carriers.set(allOf, [json]);\n }\n }\n for (const allOf of ctx.intersections) {\n for (const json of carriers.get(allOf) ?? [])\n foldIntersection(json);\n }\n }\n }\n const result = {};\n if (ctx.target === \"draft-2020-12\") {\n result.$schema = \"https://json-schema.org/draft/2020-12/schema\";\n }\n else if (ctx.target === \"draft-07\") {\n result.$schema = \"http://json-schema.org/draft-07/schema#\";\n }\n else if (ctx.target === \"draft-04\") {\n result.$schema = \"http://json-schema.org/draft-04/schema#\";\n }\n else if (ctx.target === \"openapi-3.0\") {\n // OpenAPI 3.0 schema objects should not include a $schema property\n }\n else {\n // Arbitrary string values are allowed but won't have a $schema property set\n }\n if (ctx.external?.uri) {\n const id = ctx.external.registry.get(schema)?.id;\n if (!id)\n throw new Error(\"Schema is missing an `id` property\");\n result.$id = ctx.external.uri(id);\n }\n // when the root was extracted into $defs, `root.schema` is the `$ref` wrapper and `root.def` is the body that now lives under $defs\n assignProps(result, root.defId ? root.schema : (root.def ?? root.schema));\n // The `id` in `.meta()` is a Zod-specific registration tag used to extract schemas into $defs — it is not user-facing JSON Schema metadata. Strip it from the output body where it would otherwise leak. The id is preserved implicitly via the $defs key (and via $ref paths).\n const rootMetaId = ctx.metadataRegistry.get(schema)?.id;\n if (rootMetaId !== undefined && result.id === rootMetaId)\n delete result.id;\n // build defs object. With `external`, `defs` is the shared object every schema writes into, so the same entries are reassigned on every call. Without it, `defs` is fresh per call and must be rebuilt.\n const defs = ctx.external?.defs ?? {};\n if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) {\n for (const entry of ctx.seen.entries()) {\n const seen = entry[1];\n if (seen.def && seen.defId) {\n if (seen.def.id === seen.defId)\n delete seen.def.id;\n assignProp(defs, seen.defId, seen.def);\n }\n }\n }\n if (ctx.external)\n ctx.sharedEmitDoneFor = ctx.external;\n // set definitions in result\n if (ctx.external) {\n }\n else {\n if (Object.keys(defs).length > 0) {\n if (ctx.target === \"draft-2020-12\") {\n result.$defs = defs;\n }\n else {\n result.definitions = defs;\n }\n }\n }\n try {\n // this \"finalizes\" this schema and ensures all cycles are removed each call to finalize() is functionally independent though the seen map is shared\n const finalized = JSON.parse(JSON.stringify(result));\n Object.defineProperty(finalized, \"~standard\", {\n value: {\n ...schema[\"~standard\"],\n jsonSchema: {\n input: createStandardJSONSchemaMethod(schema, \"input\", ctx.processors),\n output: createStandardJSONSchemaMethod(schema, \"output\", ctx.processors),\n },\n },\n enumerable: false,\n writable: false,\n });\n return finalized;\n }\n catch (_err) {\n throw new Error(\"Error converting schema to JSON.\");\n }\n}\nfunction isTransforming(_schema, _ctx) {\n const ctx = _ctx ?? { seen: new Set() };\n if (ctx.seen.has(_schema))\n return false;\n ctx.seen.add(_schema);\n const def = _schema._zod.def;\n if (def.type === \"transform\")\n return true;\n if (def.type === \"array\")\n return isTransforming(def.element, ctx);\n if (def.type === \"set\")\n return isTransforming(def.valueType, ctx);\n if (def.type === \"lazy\")\n return isTransforming(def.getter(), ctx);\n if (def.type === \"promise\" ||\n def.type === \"optional\" ||\n def.type === \"nonoptional\" ||\n def.type === \"nullable\" ||\n def.type === \"readonly\" ||\n def.type === \"default\" ||\n def.type === \"prefault\" ||\n def.type === \"catch\") {\n return isTransforming(def.innerType, ctx);\n }\n if (def.type === \"intersection\") {\n return isTransforming(def.left, ctx) || isTransforming(def.right, ctx);\n }\n if (def.type === \"record\" || def.type === \"map\") {\n return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx);\n }\n if (def.type === \"pipe\") {\n if (_schema._zod.traits.has(\"$ZodCodec\"))\n return true;\n return isTransforming(def.in, ctx) || isTransforming(def.out, ctx);\n }\n if (def.type === \"object\") {\n for (const key in def.shape) {\n if (isTransforming(def.shape[key], ctx))\n return true;\n }\n return false;\n }\n if (def.type === \"union\") {\n for (const option of def.options) {\n if (isTransforming(option, ctx))\n return true;\n }\n return false;\n }\n if (def.type === \"tuple\") {\n for (const item of def.items) {\n if (isTransforming(item, ctx))\n return true;\n }\n if (def.rest && isTransforming(def.rest, ctx))\n return true;\n return false;\n }\n return false;\n}\n/**\n * Creates a toJSONSchema method for a schema instance.\n * This encapsulates the logic of initializing context, processing, extracting defs, and finalizing.\n */\nexport const createToJSONSchemaMethod = (schema, processors = {}) => (params) => {\n const ctx = initializeContext({ ...params, processors });\n processSchema(schema, ctx);\n extractDefs(ctx, schema);\n return finalize(ctx, schema);\n};\nexport const createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => {\n const { libraryOptions, target } = params ?? {};\n const ctx = initializeContext({ ...(libraryOptions ?? {}), target, io, processors });\n processSchema(schema, ctx);\n extractDefs(ctx, schema);\n return finalize(ctx, schema);\n};\n", "import * as regexes from \"./regexes.js\";\nimport { base64Charset, base64urlCharset } from \"./schemas.js\";\nimport { extractDefs, finalize, handleUnrepresentable, initializeContext, processSchema, } from \"./to-json-schema.js\";\nimport { BIGINT_FORMAT_RANGES, NUMBER_FORMAT_RANGES, assignProp, getEnumValues } from \"./util.js\";\nconst narrowMin = (agg, key, value) => {\n if (agg[key] === undefined || value > agg[key])\n agg[key] = value;\n};\nconst narrowMax = (agg, key, value) => {\n if (agg[key] === undefined || value < agg[key])\n agg[key] = value;\n};\nconst narrowBoth = (agg, value) => {\n narrowMin(agg, \"minimum\", value);\n narrowMax(agg, \"maximum\", value);\n};\nconst addDivisor = (agg, value) => {\n agg.multipleOf ?? (agg.multipleOf = []);\n if (!agg.multipleOf.includes(value))\n agg.multipleOf.push(value);\n};\nconst addPattern = (agg, pattern) => {\n agg.patterns ?? (agg.patterns = new Set());\n agg.patterns.add(pattern);\n};\nconst intersectMime = (agg, mime) => {\n agg.mime = agg.mime ? agg.mime.filter((m) => mime.includes(m)) : [...mime];\n};\n// last-wins, matching the bag's historical write order; the flag keeps an integer format from being lost to a later float one\nconst setFormat = (agg, format) => {\n agg.format = format;\n if (format.includes(\"int\"))\n agg.isInt = true;\n};\nconst minContributor = (agg, def) => narrowMin(agg, \"minimum\", def.minimum);\nconst maxContributor = (agg, def) => narrowMax(agg, \"maximum\", def.maximum);\nconst formatContributor = (ranges) => (agg, def) => {\n setFormat(agg, def.format);\n const [minimum, maximum] = ranges[def.format];\n narrowMin(agg, \"minimum\", minimum);\n narrowMax(agg, \"maximum\", maximum);\n};\nconst contributors = {\n greater_than: (agg, def) => narrowMin(agg, def.inclusive ? \"minimum\" : \"exclusiveMinimum\", def.value),\n less_than: (agg, def) => narrowMax(agg, def.inclusive ? \"maximum\" : \"exclusiveMaximum\", def.value),\n multiple_of: (agg, def) => addDivisor(agg, def.value),\n number_format: formatContributor(NUMBER_FORMAT_RANGES),\n bigint_format: formatContributor(BIGINT_FORMAT_RANGES),\n min_length: minContributor,\n max_length: maxContributor,\n length_equals: (agg, def) => narrowBoth(agg, def.length),\n min_size: minContributor,\n max_size: maxContributor,\n size_equals: (agg, def) => narrowBoth(agg, def.size),\n string_format: (agg, def) => {\n setFormat(agg, def.format);\n if (def.pattern)\n addPattern(agg, def.pattern);\n if (def.format === \"base64\" || def.format === \"base64url\")\n agg.contentEncoding = def.format;\n if (def.local || def.precision === -1)\n agg.laxFormat = true;\n },\n mime_type: (agg, def) => intersectMime(agg, def.mime),\n};\nexport function aggregateChecks(schema) {\n const agg = {};\n const def = schema._zod.def;\n // a format schema is its own first check, same rule as $ZodType init\n const list = schema._zod.traits.has(\"$ZodCheck\")\n ? [schema, ...(def.checks ?? [])]\n : (def.checks ?? []);\n for (const ch of list)\n contributors[ch._zod.def.check]?.(agg, ch._zod.def);\n // reconcile with the bag so third-party onattach contributions still land; first-party residue is never tighter than the fold, so merging it back is idempotent for one and additive for the other\n const bag = schema._zod.bag;\n if (bag.minimum !== undefined)\n narrowMin(agg, \"minimum\", bag.minimum);\n if (bag.exclusiveMinimum !== undefined)\n narrowMin(agg, \"exclusiveMinimum\", bag.exclusiveMinimum);\n if (bag.maximum !== undefined)\n narrowMax(agg, \"maximum\", bag.maximum);\n if (bag.exclusiveMaximum !== undefined)\n narrowMax(agg, \"exclusiveMaximum\", bag.exclusiveMaximum);\n if (bag.multipleOf !== undefined)\n addDivisor(agg, bag.multipleOf);\n if (bag.format !== undefined) {\n agg.format ?? (agg.format = bag.format);\n if (bag.format.includes(\"int\"))\n agg.isInt = true;\n }\n if (bag.mime)\n intersectMime(agg, bag.mime);\n for (const pattern of bag.patterns ?? [])\n addPattern(agg, pattern);\n return agg;\n}\nconst formatMap = {\n guid: \"uuid\",\n url: \"uri\",\n datetime: \"date-time\",\n json_string: \"json-string\",\n regex: \"\", // do not set\n};\n// ==================== SIMPLE TYPE PROCESSORS ====================\n// the runtime patterns are lax so parse paths never overflow the regex stack; the emitted schema swaps in the exact block forms, which zod itself never executes\nconst exactPatterns = new Map([\n [base64Charset, regexes.base64],\n [base64urlCharset, regexes.base64url],\n]);\nconst exactPattern = (p) => exactPatterns.get(p) ?? p;\nexport const stringProcessor = (schema, ctx, _json, _params) => {\n const json = _json;\n json.type = \"string\";\n const { minimum, maximum, format, patterns, contentEncoding, laxFormat } = aggregateChecks(schema);\n if (typeof minimum === \"number\")\n json.minLength = minimum;\n if (typeof maximum === \"number\")\n json.maxLength = maximum;\n // custom pattern overrides format\n if (format) {\n json.format = formatMap[format] ?? format;\n if (json.format === \"\")\n delete json.format; // empty format is not valid\n // `z.iso.time()` is never full-time, and `laxFormat` carries the datetime shapes that also accept what their keyword forbids\n if (format === \"time\" || laxFormat) {\n delete json.format;\n }\n }\n if (contentEncoding)\n json.contentEncoding = contentEncoding;\n if (patterns && patterns.size > 0) {\n const patternList = [...patterns].map(exactPattern);\n if (patternList.length === 1)\n json.pattern = patternList[0].source;\n else if (patternList.length > 1) {\n json.allOf = [\n ...patternList.map((regex) => ({\n ...(ctx.target === \"draft-07\" || ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\"\n ? { type: \"string\" }\n : {}),\n pattern: regex.source,\n })),\n ];\n }\n }\n};\nexport const numberProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const { minimum, maximum, multipleOf, exclusiveMaximum, exclusiveMinimum, isInt } = aggregateChecks(schema);\n json.type = isInt ? \"integer\" : \"number\";\n // when both minimum and exclusiveMinimum exist, pick the more restrictive one\n const exMin = typeof exclusiveMinimum === \"number\" && exclusiveMinimum >= (minimum ?? Number.NEGATIVE_INFINITY);\n const exMax = typeof exclusiveMaximum === \"number\" && exclusiveMaximum <= (maximum ?? Number.POSITIVE_INFINITY);\n const legacy = ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\";\n if (exMin) {\n if (legacy) {\n json.minimum = exclusiveMinimum;\n json.exclusiveMinimum = true;\n }\n else {\n json.exclusiveMinimum = exclusiveMinimum;\n }\n }\n else if (typeof minimum === \"number\") {\n json.minimum = minimum;\n }\n if (exMax) {\n if (legacy) {\n json.maximum = exclusiveMaximum;\n json.exclusiveMaximum = true;\n }\n else {\n json.exclusiveMaximum = exclusiveMaximum;\n }\n }\n else if (typeof maximum === \"number\") {\n json.maximum = maximum;\n }\n if (multipleOf) {\n // JSON Schema requires a divisor strictly greater than zero, and a non-finite one does not survive JSON at all. A negative divisor accepts exactly what its absolute value accepts, so it still maps; zero, NaN and Infinity have no keyword form.\n const divisors = new Set();\n for (const divisor of multipleOf) {\n if (Number.isFinite(divisor) && divisor !== 0)\n divisors.add(Math.abs(divisor));\n else\n handleUnrepresentable(schema, ctx, json, params, `A multipleOf divisor of ${divisor} cannot be represented in JSON Schema`);\n }\n // chained divisors are a conjunction the keyword cannot carry alone, so extras ride an allOf, same as stacked patterns\n const [first, ...rest] = divisors;\n if (first !== undefined)\n json.multipleOf = first;\n if (rest.length)\n json.allOf = [...(json.allOf ?? []), ...rest.map((m) => ({ multipleOf: m }))];\n }\n};\nexport const booleanProcessor = (_schema, _ctx, json, _params) => {\n json.type = \"boolean\";\n};\nexport const bigintProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"BigInt cannot be represented in JSON Schema\");\n};\nexport const symbolProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Symbols cannot be represented in JSON Schema\");\n};\nexport const nullProcessor = (_schema, ctx, json, _params) => {\n if (ctx.target === \"openapi-3.0\") {\n json.type = \"string\";\n json.nullable = true;\n json.enum = [null];\n }\n else {\n json.type = \"null\";\n }\n};\nexport const undefinedProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Undefined cannot be represented in JSON Schema\");\n};\nexport const voidProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Void cannot be represented in JSON Schema\");\n};\nexport const neverProcessor = (_schema, _ctx, json, _params) => {\n json.not = {};\n};\nexport const anyProcessor = (_schema, _ctx, _json, _params) => {\n // empty schema accepts anything\n};\nexport const unknownProcessor = (_schema, _ctx, _json, _params) => {\n // empty schema accepts anything\n};\nexport const dateProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Date cannot be represented in JSON Schema\");\n};\nexport const enumProcessor = (schema, _ctx, json, _params) => {\n const def = schema._zod.def;\n const values = getEnumValues(def.entries);\n // an empty enum accepts nothing, same as z.never()\n if (values.length === 0) {\n json.not = {};\n return;\n }\n // Number enums can have both string and number values\n if (values.every((v) => typeof v === \"number\"))\n json.type = \"number\";\n if (values.every((v) => typeof v === \"string\"))\n json.type = \"string\";\n json.enum = values;\n};\nexport const literalProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n // a literal with no values accepts nothing, same as z.never()\n if (def.values.length === 0) {\n json.not = {};\n return;\n }\n const vals = [];\n for (const val of def.values) {\n if (val === undefined) {\n // a custom schema replaces the whole literal, so there is nothing left to accumulate\n if (handleUnrepresentable(schema, ctx, json, params, \"Literal `undefined` cannot be represented in JSON Schema\"))\n return;\n // otherwise do not add to vals\n }\n else if (typeof val === \"bigint\") {\n if (handleUnrepresentable(schema, ctx, json, params, \"BigInt literals cannot be represented in JSON Schema\"))\n return;\n vals.push(Number(val));\n }\n else {\n vals.push(val);\n }\n }\n if (vals.length === 0) {\n // do nothing (an undefined literal was stripped)\n }\n else if (vals.length === 1) {\n const val = vals[0];\n json.type = val === null ? \"null\" : typeof val;\n if (ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\") {\n json.enum = [val];\n }\n else {\n json.const = val;\n }\n }\n else {\n if (vals.every((v) => typeof v === \"number\"))\n json.type = \"number\";\n if (vals.every((v) => typeof v === \"string\"))\n json.type = \"string\";\n if (vals.every((v) => typeof v === \"boolean\"))\n json.type = \"boolean\";\n if (vals.every((v) => v === null))\n json.type = \"null\";\n json.enum = vals;\n }\n};\nexport const nanProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"NaN cannot be represented in JSON Schema\");\n};\nexport const templateLiteralProcessor = (schema, _ctx, json, _params) => {\n const _json = json;\n const pattern = schema._zod.pattern;\n if (!pattern)\n throw new Error(\"Pattern not found in template literal\");\n _json.type = \"string\";\n _json.pattern = pattern.source;\n};\nexport const fileProcessor = (schema, _ctx, json, _params) => {\n const _json = json;\n _json.type = \"string\";\n _json.format = \"binary\";\n _json.contentEncoding = \"binary\";\n const { minimum, maximum, mime } = aggregateChecks(schema);\n if (minimum !== undefined)\n _json.minLength = minimum;\n if (maximum !== undefined)\n _json.maxLength = maximum;\n if (!mime)\n return;\n // an empty intersection means the mime checks share no value, so nothing passes at runtime; `anyOf` must be non-empty, so the false schema is `not: {}`\n if (mime.length === 0)\n _json.not = {};\n else if (mime.length === 1)\n _json.contentMediaType = mime[0];\n // only contentMediaType differs, so the shared props stay at the root\n else\n _json.anyOf = mime.map((m) => ({ contentMediaType: m }));\n};\nexport const successProcessor = (_schema, _ctx, json, _params) => {\n json.type = \"boolean\";\n};\nexport const customProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Custom types cannot be represented in JSON Schema\");\n};\nexport const functionProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Function types cannot be represented in JSON Schema\");\n};\nexport const transformProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Transforms cannot be represented in JSON Schema\");\n};\nexport const mapProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Map cannot be represented in JSON Schema\");\n};\nexport const setProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Set cannot be represented in JSON Schema\");\n};\n// ==================== COMPOSITE TYPE PROCESSORS ====================\nexport const arrayProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n const { minimum, maximum } = aggregateChecks(schema);\n if (typeof minimum === \"number\")\n json.minItems = minimum;\n if (typeof maximum === \"number\")\n json.maxItems = maximum;\n json.type = \"array\";\n json.items = processSchema(def.element, ctx, {\n ...params,\n path: [...params.path, \"items\"],\n });\n};\n// Transform and catch set `optin = \"optional\"` at runtime so the parser lets them observe an\n// absent key, but their declared input type stays required. An input JSON Schema describes the\n// declared type, so resolve past them to the schema that actually carries the optionality.\n// Used by both `objectProcessor` (for `required`) and `tupleProcessor` (for `minItems`); see\n// wiki/optionality.md, \"The JSON Schema emitter reads the *static* value\".\nfunction inputOptin(schema) {\n const def = schema._zod.def;\n if (def.type === \"pipe\" && def.in._zod.traits.has(\"$ZodTransform\")) {\n return inputOptin(def.out);\n }\n if (def.type === \"catch\") {\n return inputOptin(def.innerType);\n }\n return schema._zod.optin;\n}\nexport const objectProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n const shape = def.shape;\n // dropping it while still emitting `additionalProperties: false` would emit a schema that rejects data this one requires\n const symbolKeys = Object.getOwnPropertySymbols(shape);\n if (symbolKeys.length &&\n handleUnrepresentable(schema, ctx, json, params, \"Symbol keys cannot be represented in JSON Schema\")) {\n return;\n }\n json.type = \"object\";\n json.properties = {};\n for (const key in shape) {\n // assignProp so a __proto__ key becomes an own property instead of hitting the inherited setter on the plain {} we build into\n assignProp(json.properties, key, processSchema(shape[key], ctx, {\n ...params,\n path: [...params.path, \"properties\", key],\n }));\n }\n // required keys\n const requiredKeys = [];\n for (const key of Object.keys(shape)) {\n const field = def.shape[key];\n if (ctx.io === \"input\" ? inputOptin(field) === undefined : field._zod.optout === undefined) {\n requiredKeys.push(key);\n }\n }\n if (requiredKeys.length > 0) {\n json.required = requiredKeys;\n }\n // catchall\n if (def.catchall?._zod.def.type === \"never\") {\n // strict\n json.additionalProperties = false;\n }\n else if (!def.catchall) {\n // regular\n if (ctx.io === \"output\")\n json.additionalProperties = false;\n }\n else if (def.catchall) {\n json.additionalProperties = processSchema(def.catchall, ctx, {\n ...params,\n path: [...params.path, \"additionalProperties\"],\n });\n }\n};\nexport const unionProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n // Exclusive unions (inclusive === false) use oneOf (exactly one match) instead of anyOf (one or more matches). This includes both z.xor() and discriminated unions\n const isExclusive = def.inclusive === false;\n const options = def.options.map((x, i) => processSchema(x, ctx, {\n ...params,\n path: [...params.path, isExclusive ? \"oneOf\" : \"anyOf\", i],\n }));\n if (isExclusive) {\n json.oneOf = options;\n }\n else {\n json.anyOf = options;\n }\n};\nexport const intersectionProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n const a = processSchema(def.left, ctx, {\n ...params,\n path: [...params.path, \"allOf\", 0],\n });\n const b = processSchema(def.right, ctx, {\n ...params,\n path: [...params.path, \"allOf\", 1],\n });\n const isSimpleIntersection = (val) => \"allOf\" in val && Object.keys(val).length === 1;\n const allOf = [\n ...(isSimpleIntersection(a) ? a.allOf : [a]),\n ...(isSimpleIntersection(b) ? b.allOf : [b]),\n ];\n json.allOf = allOf;\n // Recorded innermost first, so a nested intersection has already folded by the time this one is considered. The array is the handle rather than the schema, because a wrapper that inherits this schema shares the same array; `finalize` folds every object holding it. See `foldIntersection`.\n ctx.intersections.push(allOf);\n};\nexport const tupleProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n json.type = \"array\";\n const prefixPath = ctx.target === \"draft-2020-12\" ? \"prefixItems\" : \"items\";\n const restPath = ctx.target === \"draft-2020-12\" ? \"items\" : ctx.target === \"openapi-3.0\" ? \"items\" : \"additionalItems\";\n const prefixItems = def.items.map((x, i) => processSchema(x, ctx, {\n ...params,\n path: [...params.path, prefixPath, i],\n }));\n const rest = def.rest\n ? processSchema(def.rest, ctx, {\n ...params,\n path: [...params.path, restPath, ...(ctx.target === \"openapi-3.0\" ? [def.items.length] : [])],\n })\n : null;\n let minItems = def.items.length;\n while (minItems > 0) {\n const item = def.items[minItems - 1];\n const optional = ctx.io === \"input\" ? inputOptin(item) !== undefined : item._zod.optout === \"optional\";\n if (!optional)\n break;\n minItems--;\n }\n const maxItems = def.items.length;\n const isClosed = !def.rest;\n if (ctx.target === \"draft-2020-12\") {\n json.prefixItems = prefixItems;\n if (isClosed) {\n json.items = false;\n }\n else if (rest) {\n json.items = rest;\n }\n if (minItems > 0)\n json.minItems = minItems;\n if (isClosed)\n json.maxItems = maxItems;\n }\n else if (ctx.target === \"openapi-3.0\") {\n json.items = {\n anyOf: prefixItems,\n };\n if (rest) {\n json.items.anyOf.push(rest);\n }\n if (minItems > 0)\n json.minItems = minItems;\n if (isClosed)\n json.maxItems = maxItems;\n }\n else {\n json.items = prefixItems;\n if (isClosed) {\n json.additionalItems = false;\n }\n else if (rest) {\n json.additionalItems = rest;\n }\n if (minItems > 0)\n json.minItems = minItems;\n if (isClosed)\n json.maxItems = maxItems;\n }\n // explicit user-defined length checks take precedence\n const { minimum, maximum } = aggregateChecks(schema);\n if (typeof minimum === \"number\")\n json.minItems = minimum;\n if (typeof maximum === \"number\")\n json.maxItems = maximum;\n};\n/** JSON object keys are always strings, so a numeric record key schema is re-expressed over the\n * numeric-string form the record parser matches. Deferred to `finalize`, after the flatten: a key\n * behind a wrapper only carries its own `type` before then, and a union key only has its branches.\n *\n * A numeric bound cannot apply to a property name, so `minimum` and its siblings are dropped rather\n * than carried over: keeping them beside `type: \"string\"` reproduces the match-nothing schema this\n * exists to fix. A key that carries one therefore emits wider than the record parses — `z.record(z.number().min(5), V)`\n * accepts `\"3\"` — which is the deliberate trade, since throwing on it would reject an ordinary schema\n * outright. */\nfunction stringifyKeyNames(bySchema, json, visited) {\n // an extracted key that rewrites cannot go on sharing its definition — the string form a key position needs is not the number form every other reference wants — so it inlines. One that does not rewrite keeps the `$ref`.\n if (json.$ref) {\n // a recursive key holds its own reference inside its definition, so a node already on the path is left alone rather than resolved again\n if (visited.has(json))\n return json;\n visited.add(json);\n const def = bySchema.get(json)?.def;\n if (!def)\n return json;\n const inlined = stringifyKeyNames(bySchema, def, visited);\n return inlined === def ? json : inlined;\n }\n for (const keyword of [\"anyOf\", \"oneOf\"]) {\n const branches = json[keyword];\n if (!Array.isArray(branches))\n continue;\n const mapped = branches.map((branch) => stringifyKeyNames(bySchema, branch, visited));\n // rebuilding regardless would detach a key that had nothing to re-express, dropping its `$ref` and leaking the internal `id`\n if (mapped.some((branch, i) => branch !== branches[i]))\n json = { ...json, [keyword]: mapped };\n }\n // a member that already admits a string leaves the key unconstrained, so the node's own type re-expresses only when every member is numeric\n const types = Array.isArray(json.type) ? json.type : [json.type];\n const numericType = !types.includes(\"string\") && types.some((t) => t === \"number\" || t === \"integer\");\n // a heterogeneous key carries no type at all, so its numeric members are caught here instead\n const values = json.enum ?? (json.const !== undefined ? [json.const] : undefined);\n if (!numericType && !values?.some((v) => typeof v === \"number\"))\n return json;\n const { minimum, maximum, exclusiveMinimum, exclusiveMaximum, multipleOf, format, id, ...rest } = json;\n if (rest.enum)\n rest.enum = rest.enum.map((v) => (typeof v === \"number\" ? String(v) : v));\n else if (typeof rest.const === \"number\")\n rest.const = String(rest.const);\n // a heterogeneous key keeps its absent type: the stringified members already say what a key may be\n if (!numericType)\n return rest;\n rest.type = \"string\";\n if (!values)\n rest.pattern = (types.includes(\"number\") ? regexes.number : regexes.integer).source;\n return rest;\n}\n/** Every record of one conversion, so the carriers are found in a single pass rather than once per record. */\nconst pendingRecords = new WeakMap();\nfunction rewriteKeyNames(ctx) {\n // an extracted key is resolved by the object `extractToDef` left in its place, so the map is built once rather than searched per reference. `_zod.toJSONSchema` can hand the same object to two schemas, so the first entry carrying a body wins, as a search would have found it.\n const bySchema = new Map();\n for (const entry of ctx.seen.values()) {\n if (entry.def && !bySchema.has(entry.schema))\n bySchema.set(entry.schema, entry);\n }\n const rewrites = new Map();\n for (const record of pendingRecords.get(ctx) ?? []) {\n const seen = ctx.seen.get(record);\n const names = (seen?.def ?? seen?.schema)?.propertyNames;\n if (!names || names === true || rewrites.has(names))\n continue;\n const rewritten = stringifyKeyNames(bySchema, names, new Set());\n if (rewritten !== names)\n rewrites.set(names, rewritten);\n }\n if (!rewrites.size)\n return;\n // the flatten has already copied each record's own properties onto every wrapper by reference, and an extracted body is another such copy, so every carrier holding a rewritten key is updated together\n for (const entry of ctx.seen.values()) {\n for (const carrier of [entry.schema, entry.def]) {\n const rewritten = carrier && rewrites.get(carrier.propertyNames);\n if (rewritten)\n carrier.propertyNames = rewritten;\n }\n }\n}\nexport const recordProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n json.type = \"object\";\n // For looseRecord with regex patterns, use patternProperties. This correctly represents \"only validate keys matching the pattern\" semantics and composes well with allOf (intersections)\n const keyType = def.keyType;\n const patterns = aggregateChecks(keyType).patterns;\n if (def.mode === \"loose\" && patterns && patterns.size > 0) {\n // Use patternProperties for looseRecord with regex patterns\n const valueSchema = processSchema(def.valueType, ctx, {\n ...params,\n path: [...params.path, \"patternProperties\", \"*\"],\n });\n json.patternProperties = {};\n for (const pattern of patterns) {\n assignProp(json.patternProperties, exactPattern(pattern).source, valueSchema);\n }\n }\n else {\n // Default behavior: use propertyNames + additionalProperties\n if (ctx.target === \"draft-07\" || ctx.target === \"draft-2020-12\") {\n json.propertyNames = processSchema(def.keyType, ctx, {\n ...params,\n path: [...params.path, \"propertyNames\"],\n });\n let pending = pendingRecords.get(ctx);\n if (!pending) {\n pending = [];\n pendingRecords.set(ctx, pending);\n ctx.deferred.push(() => rewriteKeyNames(ctx));\n }\n pending.push(schema);\n }\n json.additionalProperties = processSchema(def.valueType, ctx, {\n ...params,\n path: [...params.path, \"additionalProperties\"],\n });\n }\n // Add required for keys with discrete values (enum, literal, etc.)\n const keyValues = keyType._zod.values;\n // Every key shares one value schema, so an optional-in value makes the whole key set omittable on input. Output keeps them: the exhaustive branch assigns every key, even one whose value came back undefined.\n const omittableOnInput = ctx.io === \"input\" && inputOptin(def.valueType) !== undefined;\n if (keyValues && !def.partial && !omittableOnInput) {\n const validKeyValues = [...keyValues].filter((v) => typeof v === \"string\" || typeof v === \"number\");\n if (validKeyValues.length > 0) {\n json.required = validKeyValues.map(String);\n }\n }\n};\nexport const nullableProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n const inner = processSchema(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n if (ctx.target === \"openapi-3.0\") {\n seen.ref = def.innerType;\n json.nullable = true;\n }\n else {\n json.anyOf = [inner, { type: \"null\" }];\n }\n};\nexport const nonoptionalProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n processSchema(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n};\n/** Round-trips a default value through JSON so the emitted schema is guaranteed to be valid JSON.\n * A BigInt has no reliable encoding, so it goes through `unrepresentable` like any other\n * unrepresentable value. Returns a sentinel when the caller must not write a default of its own. */\nconst UNREPRESENTABLE_DEFAULT = Symbol();\nfunction serializeDefaultValue(value, schema, ctx, json, params) {\n let unrepresentable = false;\n const serialized = JSON.stringify(value, (_, val) => {\n if (typeof val !== \"bigint\")\n return val;\n unrepresentable = true;\n return null;\n });\n if (!unrepresentable)\n return JSON.parse(serialized);\n handleUnrepresentable(schema, ctx, json, params, \"BigInt defaults cannot be represented in JSON Schema\");\n return UNREPRESENTABLE_DEFAULT;\n}\nexport const defaultProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n processSchema(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n const value = serializeDefaultValue(def.defaultValue, schema, ctx, json, params);\n if (value !== UNREPRESENTABLE_DEFAULT)\n json.default = value;\n};\nexport const prefaultProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n processSchema(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n if (ctx.io !== \"input\")\n return;\n const value = serializeDefaultValue(def.defaultValue, schema, ctx, json, params);\n if (value !== UNREPRESENTABLE_DEFAULT)\n json._prefault = value;\n};\nexport const catchProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n processSchema(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n let catchValue;\n try {\n catchValue = def.catchValue(undefined);\n }\n catch {\n handleUnrepresentable(schema, ctx, json, params, \"Dynamic catch values are not supported in JSON Schema\");\n return;\n }\n json.default = catchValue;\n};\nexport const pipeProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n const inIsTransform = def.in._zod.traits.has(\"$ZodTransform\");\n const innerType = ctx.io === \"input\" ? (inIsTransform ? def.out : def.in) : def.out;\n processSchema(innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = innerType;\n};\nexport const readonlyProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n processSchema(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n json.readOnly = true;\n};\nexport const promiseProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n processSchema(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n};\nexport const optionalProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n processSchema(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n};\nexport const lazyProcessor = (schema, ctx, _json, params) => {\n const innerType = schema._zod.innerType;\n processSchema(innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = innerType;\n};\n// ==================== ALL PROCESSORS ====================\nexport const allProcessors = {\n string: stringProcessor,\n number: numberProcessor,\n boolean: booleanProcessor,\n bigint: bigintProcessor,\n symbol: symbolProcessor,\n null: nullProcessor,\n undefined: undefinedProcessor,\n void: voidProcessor,\n never: neverProcessor,\n any: anyProcessor,\n unknown: unknownProcessor,\n date: dateProcessor,\n enum: enumProcessor,\n literal: literalProcessor,\n nan: nanProcessor,\n template_literal: templateLiteralProcessor,\n file: fileProcessor,\n success: successProcessor,\n custom: customProcessor,\n function: functionProcessor,\n transform: transformProcessor,\n map: mapProcessor,\n set: setProcessor,\n array: arrayProcessor,\n object: objectProcessor,\n union: unionProcessor,\n intersection: intersectionProcessor,\n tuple: tupleProcessor,\n record: recordProcessor,\n nullable: nullableProcessor,\n nonoptional: nonoptionalProcessor,\n default: defaultProcessor,\n prefault: prefaultProcessor,\n catch: catchProcessor,\n pipe: pipeProcessor,\n readonly: readonlyProcessor,\n promise: promiseProcessor,\n optional: optionalProcessor,\n lazy: lazyProcessor,\n};\nexport function toJSONSchema(input, params) {\n if (\"_idmap\" in input) {\n // Registry case\n const registry = input;\n const ctx = initializeContext({ ...params, processors: allProcessors });\n const defs = {};\n // First pass: process all schemas to build the seen map\n for (const entry of registry._idmap.entries()) {\n const [_, schema] = entry;\n processSchema(schema, ctx);\n }\n const schemas = {};\n const external = {\n registry,\n uri: params?.uri,\n defs,\n };\n // Update the context with external configuration\n ctx.external = external;\n // Second pass: emit each schema\n for (const entry of registry._idmap.entries()) {\n const [key, schema] = entry;\n extractDefs(ctx, schema);\n assignProp(schemas, key, finalize(ctx, schema));\n }\n if (Object.keys(defs).length > 0) {\n const defsSegment = ctx.target === \"draft-2020-12\" ? \"$defs\" : \"definitions\";\n schemas.__shared = {\n [defsSegment]: defs,\n };\n }\n return { schemas };\n }\n // Single schema case\n const ctx = initializeContext({ ...params, processors: allProcessors });\n processSchema(input, ctx);\n extractDefs(ctx, input);\n return finalize(ctx, input);\n}\n", "import * as core from \"../core/index.js\";\nimport { $ZodError } from \"../core/index.js\";\nimport * as util from \"../core/util.js\";\n/* Prototypes that already carry the lazy helper methods. Seeded with the\n * intrinsics so that `init` on a foreign object — it accepts any object —\n * can never install an accessor onto a prototype we do not own. */\nconst _installedErrorProtos = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]);\n/* Helper methods live as non-enumerable lazy getters on the shared\n * prototype instead of own properties on every instance. On first\n * access the getter allocates the per-instance closure and caches it\n * as a non-enumerable own property, so detached usage still works and\n * the allocation only happens for methods actually touched. */\nfunction _lazyMethod(proto, key, make) {\n Object.defineProperty(proto, key, {\n configurable: true,\n enumerable: false,\n get() {\n const value = make(this);\n Object.defineProperty(this, key, { value, configurable: true, writable: true });\n return value;\n },\n set(value) {\n Object.defineProperty(this, key, { value, configurable: true, writable: true });\n },\n });\n}\nconst initializer = (inst, issues) => {\n $ZodError.init(inst, issues);\n inst.name = \"ZodError\";\n const proto = Object.getPrototypeOf(inst);\n if (_installedErrorProtos.has(proto))\n return;\n _installedErrorProtos.add(proto);\n _lazyMethod(proto, \"format\", (self) => (mapper) => core.formatError(self, mapper));\n _lazyMethod(proto, \"flatten\", (self) => (mapper) => core.flattenError(self, mapper));\n _lazyMethod(proto, \"addIssue\", (self) => (issue) => {\n self.issues.push(issue);\n self.message = JSON.stringify(self.issues, util.jsonStringifyReplacer, 2);\n });\n _lazyMethod(proto, \"addIssues\", (self) => (issues) => {\n self.issues.push(...issues);\n self.message = JSON.stringify(self.issues, util.jsonStringifyReplacer, 2);\n });\n Object.defineProperty(proto, \"isEmpty\", {\n configurable: true,\n enumerable: false,\n get() {\n return this.issues.length === 0;\n },\n });\n};\nexport const ZodError = /*@__PURE__*/ core.$constructor(\"ZodError\", initializer);\nexport const ZodRealError = /*@__PURE__*/ core.$constructor(\"ZodError\", initializer, undefined, {\n Parent: Error,\n});\n// /** @deprecated Use `z.core.$ZodErrorMapCtx` instead. */\n// export type ErrorMapCtx = core.$ZodErrorMapCtx;\n", "import * as core from \"../core/index.js\";\nimport { ZodRealError } from \"./errors.js\";\nexport const parse = /* @__PURE__ */ core._parse(ZodRealError);\nexport const parseAsync = /* @__PURE__ */ core._parseAsync(ZodRealError);\nexport const safeParse = /* @__PURE__ */ core._safeParse(ZodRealError);\nexport const safeParseAsync = /* @__PURE__ */ core._safeParseAsync(ZodRealError);\nexport { validate, validateAsync } from \"../core/index.js\";\n// Codec functions\nexport const encode = /* @__PURE__ */ core._encode(ZodRealError);\nexport const decode = /* @__PURE__ */ core._decode(ZodRealError);\nexport const encodeAsync = /* @__PURE__ */ core._encodeAsync(ZodRealError);\nexport const decodeAsync = /* @__PURE__ */ core._decodeAsync(ZodRealError);\nexport const safeEncode = /* @__PURE__ */ core._safeEncode(ZodRealError);\nexport const safeDecode = /* @__PURE__ */ core._safeDecode(ZodRealError);\nexport const safeEncodeAsync = /* @__PURE__ */ core._safeEncodeAsync(ZodRealError);\nexport const safeDecodeAsync = /* @__PURE__ */ core._safeDecodeAsync(ZodRealError);\n", "import * as core from \"../core/index.js\";\nimport { util } from \"../core/index.js\";\nimport * as processors from \"../core/json-schema-processors.js\";\nimport * as regexes from \"../core/regexes.js\";\nimport { createStandardJSONSchemaMethod, createToJSONSchemaMethod } from \"../core/to-json-schema.js\";\nimport en from \"../locales/en.js\";\nimport * as checks from \"./checks.js\";\nimport * as parse from \"./parse.js\";\n// Register English as the default locale on first ZodType construction. Hooked into the `ZodType` `$constructor` (rather than a top-level `config(en())` in `external.ts`) so bundlers honoring `sideEffects: false` can't tree-shake it out — see #5953, #5725. An explicit `z.config(z.locales.xx())` call wins regardless of order, since this only sets the default when none is present.\nfunction _ensureDefaultLocale() {\n if (!core.globalConfig.localeError)\n core.config(en());\n}\n// the default memoizer is read by the core container init, which runs before `ZodType.init`, so each container calls this first\nfunction _ensureDefaultMemoizer() {\n if (!core.globalConfig.memoizer)\n core.config({ memoizer: core.memoizer() });\n}\nexport const ZodType = /*@__PURE__*/ core.$constructor(\"ZodType\", (inst, def) => {\n _ensureDefaultLocale();\n core.$ZodType.init(inst, def);\n inst.def = def;\n inst.type = def.type;\n return inst;\n}, {\n check(...chks) {\n const def = this.def;\n return this.clone(util.mergeDefs(def, {\n checks: [\n ...(def.checks ?? []),\n ...chks.map((ch) => typeof ch === \"function\" ? { _zod: { check: ch, def: { check: \"custom\" }, onattach: [] } } : ch),\n ],\n }), { parent: true });\n },\n with(...chks) {\n return this.check(...chks);\n },\n clone(def, params) {\n return core.clone(this, def, params);\n },\n brand() {\n return this;\n },\n register(reg, meta) {\n reg.add(this, meta);\n return this;\n },\n refine(check, params) {\n return this.check(refine(check, params));\n },\n superRefine(refinement, params) {\n return this.check(superRefine(refinement, params));\n },\n overwrite(fn) {\n return this.check(checks.overwrite(fn));\n },\n optional() {\n return optional(this);\n },\n exactOptional() {\n return exactOptional(this);\n },\n nullable() {\n return nullable(this);\n },\n nullish() {\n return optional(nullable(this));\n },\n nonoptional(params) {\n return nonoptional(this, params);\n },\n array() {\n return array(this);\n },\n or(arg) {\n return union([this, arg]);\n },\n and(arg) {\n return intersection(this, arg);\n },\n transform(tx) {\n return pipe(this, transform(tx));\n },\n default(d) {\n return _default(this, d);\n },\n prefault(d) {\n return prefault(this, d);\n },\n catch(params) {\n return _catch(this, params);\n },\n pipe(target) {\n return pipe(this, target);\n },\n readonly() {\n return readonly(this);\n },\n describe(description) {\n const cl = this.clone();\n core.globalRegistry.add(cl, { description });\n return cl;\n },\n meta(...args) {\n // overloaded: meta() returns the registered metadata, meta(data) returns a clone with `data` registered. The mapped type picks up the second overload, so we accept variadic any-args and return `any` to satisfy both at runtime.\n if (args.length === 0)\n return core.globalRegistry.get(this);\n const cl = this.clone();\n core.globalRegistry.add(cl, args[0]);\n return cl;\n },\n isOptional() {\n return this.safeParse(undefined).success;\n },\n isNullable() {\n return this.safeParse(null).success;\n },\n apply(fn, ...args) {\n return args.length === 0 ? fn(this) : fn(this, ...args);\n },\n // Overrides core's `~standard` to add `jsonSchema`. Must stay a prototype entry: redefining it per instance demotes instances to dictionary mode.\n get \"~standard\"() {\n return util.hide(this, \"~standard\", {\n ...core.standardProps(this),\n jsonSchema: {\n input: createStandardJSONSchemaMethod(this, \"input\"),\n output: createStandardJSONSchemaMethod(this, \"output\"),\n },\n });\n },\n set \"~standard\"(value) {\n util.own(this, \"~standard\", value);\n },\n parse: function _parse(data, params) {\n return parse.parse(this, data, params, { callee: _parse });\n },\n parseAsync: async function _parseAsync(data, params) {\n return await parse.parseAsync(this, data, params, { callee: _parseAsync });\n },\n safeParse(data, params) {\n return parse.safeParse(this, data, params);\n },\n async safeParseAsync(data, params) {\n return parse.safeParseAsync(this, data, params);\n },\n // `spa` is an alias: same function object as `safeParseAsync`, as before.\n get spa() {\n return this?.safeParseAsync;\n },\n set spa(value) {\n util.own(this, \"spa\", value);\n },\n validate(data, params) {\n return parse.validate(this, data, params);\n },\n validateAsync(data, params) {\n return parse.validateAsync(this, data, params);\n },\n encode: function _encode(data, params) {\n return parse.encode(this, data, params, { callee: _encode });\n },\n decode: function _decode(data, params) {\n return parse.decode(this, data, params, { callee: _decode });\n },\n encodeAsync: async function _encodeAsync(data, params) {\n return await parse.encodeAsync(this, data, params, { callee: _encodeAsync });\n },\n decodeAsync: async function _decodeAsync(data, params) {\n return await parse.decodeAsync(this, data, params, { callee: _decodeAsync });\n },\n safeEncode(data, params) {\n return parse.safeEncode(this, data, params);\n },\n safeDecode(data, params) {\n return parse.safeDecode(this, data, params);\n },\n async safeEncodeAsync(data, params) {\n return parse.safeEncodeAsync(this, data, params);\n },\n async safeDecodeAsync(data, params) {\n return parse.safeDecodeAsync(this, data, params);\n },\n toJSONSchema(params) {\n return createToJSONSchemaMethod(this, {})(params);\n },\n // Reads through to the registry on every access, so it must not cache.\n get description() {\n return core.globalRegistry.get(this)?.description;\n },\n // No setter: `schema._def = x` throws, as it did when `_def` was a non-writable own property.\n get _def() {\n return this._zod.def;\n },\n});\n/** @internal */\nexport const _ZodString = /*@__PURE__*/ core.$constructor(\"_ZodString\", (inst, def) => {\n core.$ZodString.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.stringProcessor(inst, ctx, json, params);\n}, \n/*@__PURE__*/ util.derived({\n format: (inst) => processors.aggregateChecks(inst).format ?? null,\n minLength: (inst) => processors.aggregateChecks(inst).minimum ?? null,\n maxLength: (inst) => processors.aggregateChecks(inst).maximum ?? null,\n}, {\n regex(...args) {\n return this.check(checks.regex(...args));\n },\n includes(...args) {\n return this.check(checks.includes(...args));\n },\n startsWith(...args) {\n return this.check(checks.startsWith(...args));\n },\n endsWith(...args) {\n return this.check(checks.endsWith(...args));\n },\n min(...args) {\n return this.check(checks.minLength(...args));\n },\n max(...args) {\n return this.check(checks.maxLength(...args));\n },\n length(...args) {\n return this.check(checks.length(...args));\n },\n nonempty(...args) {\n return this.check(checks.minLength(1, ...args));\n },\n lowercase(params) {\n return this.check(checks.lowercase(params));\n },\n uppercase(params) {\n return this.check(checks.uppercase(params));\n },\n trim() {\n return this.check(checks.trim());\n },\n normalize(...args) {\n return this.check(checks.normalize(...args));\n },\n toLowerCase() {\n return this.check(checks.toLowerCase());\n },\n toUpperCase() {\n return this.check(checks.toUpperCase());\n },\n slugify() {\n return this.check(checks.slugify());\n },\n}));\nexport const ZodString = /*@__PURE__*/ core.$constructor(\"ZodString\", (inst, def) => {\n core.$ZodString.init(inst, def);\n _ZodString.init(inst, def);\n}, {\n email(params) {\n return this.check(core._email(ZodEmail, params));\n },\n url(params) {\n return this.check(core._url(ZodURL, params));\n },\n jwt(params) {\n return this.check(core._jwt(ZodJWT, params));\n },\n emoji(params) {\n return this.check(core._emoji(ZodEmoji, params));\n },\n guid(params) {\n return this.check(core._guid(ZodGUID, params));\n },\n uuid(params) {\n return this.check(core._uuid(ZodUUID, params));\n },\n uuidv4(params) {\n return this.check(core._uuidv4(ZodUUID, params));\n },\n uuidv6(params) {\n return this.check(core._uuidv6(ZodUUID, params));\n },\n uuidv7(params) {\n return this.check(core._uuidv7(ZodUUID, params));\n },\n nanoid(params) {\n return this.check(core._nanoid(ZodNanoID, params));\n },\n cuid(params) {\n return this.check(core._cuid(ZodCUID, params));\n },\n cuid2(params) {\n return this.check(core._cuid2(ZodCUID2, params));\n },\n ulid(params) {\n return this.check(core._ulid(ZodULID, params));\n },\n base64(params) {\n return this.check(core._base64(ZodBase64, params));\n },\n base64url(params) {\n return this.check(core._base64url(ZodBase64URL, params));\n },\n xid(params) {\n return this.check(core._xid(ZodXID, params));\n },\n ksuid(params) {\n return this.check(core._ksuid(ZodKSUID, params));\n },\n ipv4(params) {\n return this.check(core._ipv4(ZodIPv4, params));\n },\n ipv6(params) {\n return this.check(core._ipv6(ZodIPv6, params));\n },\n cidrv4(params) {\n return this.check(core._cidrv4(ZodCIDRv4, params));\n },\n cidrv6(params) {\n return this.check(core._cidrv6(ZodCIDRv6, params));\n },\n e164(params) {\n return this.check(core._e164(ZodE164, params));\n },\n datetime(params) {\n return this.check(core._isoDateTime(ZodISODateTime, params));\n },\n date(params) {\n return this.check(core._isoDate(ZodISODate, params));\n },\n time(params) {\n return this.check(core._isoTime(ZodISOTime, params));\n },\n duration(params) {\n return this.check(core._isoDuration(ZodISODuration, params));\n },\n});\nexport function string(params) {\n return core._string(ZodString, params);\n}\nexport const ZodStringFormat = /*@__PURE__*/ core.$constructor(\"ZodStringFormat\", (inst, def) => {\n core.$ZodStringFormat.init(inst, def);\n _ZodString.init(inst, def);\n});\nexport const ZodISODateTime = /*@__PURE__*/ core.$constructor(\"ZodISODateTime\", (inst, def) => {\n core.$ZodISODateTime.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport const ZodISODate = /*@__PURE__*/ core.$constructor(\"ZodISODate\", (inst, def) => {\n core.$ZodISODate.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport const ZodISOTime = /*@__PURE__*/ core.$constructor(\"ZodISOTime\", (inst, def) => {\n core.$ZodISOTime.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport const ZodISODuration = /*@__PURE__*/ core.$constructor(\"ZodISODuration\", (inst, def) => {\n core.$ZodISODuration.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport const ZodEmail = /*@__PURE__*/ core.$constructor(\"ZodEmail\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodEmail.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function email(params) {\n return core._email(ZodEmail, params);\n}\nexport const ZodGUID = /*@__PURE__*/ core.$constructor(\"ZodGUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodGUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function guid(params) {\n return core._guid(ZodGUID, params);\n}\nexport const ZodUUID = /*@__PURE__*/ core.$constructor(\"ZodUUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodUUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function uuid(params) {\n return core._uuid(ZodUUID, params);\n}\nexport function uuidv4(params) {\n return core._uuidv4(ZodUUID, params);\n}\n// ZodUUIDv6\nexport function uuidv6(params) {\n return core._uuidv6(ZodUUID, params);\n}\n// ZodUUIDv7\nexport function uuidv7(params) {\n return core._uuidv7(ZodUUID, params);\n}\nexport const ZodURL = /*@__PURE__*/ core.$constructor(\"ZodURL\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodURL.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function url(params) {\n return core._url(ZodURL, params);\n}\nexport function httpUrl(params) {\n return core._url(ZodURL, {\n protocol: regexes.httpProtocol,\n hostname: regexes.domain,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodEmoji = /*@__PURE__*/ core.$constructor(\"ZodEmoji\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodEmoji.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function emoji(params) {\n return core._emoji(ZodEmoji, params);\n}\nexport const ZodNanoID = /*@__PURE__*/ core.$constructor(\"ZodNanoID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodNanoID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function nanoid(params) {\n return core._nanoid(ZodNanoID, params);\n}\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link ZodCUID2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport const ZodCUID = /*@__PURE__*/ core.$constructor(\"ZodCUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodCUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\n/**\n * Validates a CUID v1 string.\n *\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link cuid2 | `z.cuid2()`} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport function cuid(params) {\n return core._cuid(ZodCUID, params);\n}\nexport const ZodCUID2 = /*@__PURE__*/ core.$constructor(\"ZodCUID2\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodCUID2.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function cuid2(params) {\n return core._cuid2(ZodCUID2, params);\n}\nexport const ZodULID = /*@__PURE__*/ core.$constructor(\"ZodULID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodULID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ulid(params) {\n return core._ulid(ZodULID, params);\n}\nexport const ZodXID = /*@__PURE__*/ core.$constructor(\"ZodXID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodXID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function xid(params) {\n return core._xid(ZodXID, params);\n}\nexport const ZodKSUID = /*@__PURE__*/ core.$constructor(\"ZodKSUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodKSUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ksuid(params) {\n return core._ksuid(ZodKSUID, params);\n}\nexport const ZodIPv4 = /*@__PURE__*/ core.$constructor(\"ZodIPv4\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodIPv4.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ipv4(params) {\n return core._ipv4(ZodIPv4, params);\n}\nexport const ZodMAC = /*@__PURE__*/ core.$constructor(\"ZodMAC\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodMAC.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function mac(params) {\n return core._mac(ZodMAC, params);\n}\nexport const ZodIPv6 = /*@__PURE__*/ core.$constructor(\"ZodIPv6\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodIPv6.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ipv6(params) {\n return core._ipv6(ZodIPv6, params);\n}\nexport const ZodCIDRv4 = /*@__PURE__*/ core.$constructor(\"ZodCIDRv4\", (inst, def) => {\n core.$ZodCIDRv4.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function cidrv4(params) {\n return core._cidrv4(ZodCIDRv4, params);\n}\nexport const ZodCIDRv6 = /*@__PURE__*/ core.$constructor(\"ZodCIDRv6\", (inst, def) => {\n core.$ZodCIDRv6.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function cidrv6(params) {\n return core._cidrv6(ZodCIDRv6, params);\n}\nexport const ZodBase64 = /*@__PURE__*/ core.$constructor(\"ZodBase64\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodBase64.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function base64(params) {\n return core._base64(ZodBase64, params);\n}\nexport const ZodBase64URL = /*@__PURE__*/ core.$constructor(\"ZodBase64URL\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodBase64URL.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function base64url(params) {\n return core._base64url(ZodBase64URL, params);\n}\nexport const ZodE164 = /*@__PURE__*/ core.$constructor(\"ZodE164\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodE164.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function e164(params) {\n return core._e164(ZodE164, params);\n}\nexport const ZodCreditCard = /*@__PURE__*/ core.$constructor(\"ZodCreditCard\", (inst, def) => {\n core.$ZodCreditCard.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function creditCard(params) {\n return core._creditCard(ZodCreditCard, params);\n}\nexport const ZodIBAN = /*@__PURE__*/ core.$constructor(\"ZodIBAN\", (inst, def) => {\n core.$ZodIBAN.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function iban(params) {\n return core._iban(ZodIBAN, params);\n}\nexport const ZodJWT = /*@__PURE__*/ core.$constructor(\"ZodJWT\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodJWT.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function jwt(params) {\n return core._jwt(ZodJWT, params);\n}\nexport const ZodCustomStringFormat = /*@__PURE__*/ core.$constructor(\"ZodCustomStringFormat\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodCustomStringFormat.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function stringFormat(format, fnOrRegex, _params = {}) {\n return core._stringFormat(ZodCustomStringFormat, format, fnOrRegex, _params);\n}\nexport function hostname(_params) {\n return core._stringFormat(ZodCustomStringFormat, \"hostname\", regexes.hostname, _params);\n}\nexport function hex(_params) {\n return core._stringFormat(ZodCustomStringFormat, \"hex\", regexes.hex, _params);\n}\nexport function currencyCode(_params) {\n return core._stringFormat(ZodCustomStringFormat, \"currency_code\", regexes.currencyCode, _params);\n}\nexport function hash(alg, params) {\n const enc = params?.enc ?? \"hex\";\n const format = `${alg}_${enc}`;\n const regex = core.regexes[format];\n if (!regex)\n throw new Error(`Unrecognized hash format: ${format}`);\n return core._stringFormat(ZodCustomStringFormat, format, regex, params);\n}\nexport const ZodNumber = /*@__PURE__*/ core.$constructor(\"ZodNumber\", (inst, def) => {\n core.$ZodNumber.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.numberProcessor(inst, ctx, json, params);\n inst.isFinite = true;\n}, \n/*@__PURE__*/ util.derived({\n minValue: (inst) => {\n const { minimum, exclusiveMinimum } = processors.aggregateChecks(inst);\n return Math.max(minimum ?? Number.NEGATIVE_INFINITY, exclusiveMinimum ?? Number.NEGATIVE_INFINITY);\n },\n maxValue: (inst) => {\n const { maximum, exclusiveMaximum } = processors.aggregateChecks(inst);\n return Math.min(maximum ?? Number.POSITIVE_INFINITY, exclusiveMaximum ?? Number.POSITIVE_INFINITY);\n },\n isInt: (inst) => {\n const { isInt, multipleOf } = processors.aggregateChecks(inst);\n return !!isInt || !!multipleOf?.some(Number.isSafeInteger);\n },\n format: (inst) => processors.aggregateChecks(inst).format ?? null,\n}, {\n gt(value, params) {\n return this.check(checks.gt(value, params));\n },\n gte(value, params) {\n return this.check(checks.gte(value, params));\n },\n min(value, params) {\n return this.check(checks.gte(value, params));\n },\n lt(value, params) {\n return this.check(checks.lt(value, params));\n },\n lte(value, params) {\n return this.check(checks.lte(value, params));\n },\n max(value, params) {\n return this.check(checks.lte(value, params));\n },\n int(params) {\n return this.check(int(params));\n },\n safe(params) {\n return this.check(int(params));\n },\n positive(params) {\n return this.check(checks.gt(0, params));\n },\n nonnegative(params) {\n return this.check(checks.gte(0, params));\n },\n negative(params) {\n return this.check(checks.lt(0, params));\n },\n nonpositive(params) {\n return this.check(checks.lte(0, params));\n },\n multipleOf(value, params) {\n return this.check(checks.multipleOf(value, params));\n },\n step(value, params) {\n return this.check(checks.multipleOf(value, params));\n },\n finite() {\n return this;\n },\n}));\nexport function number(params) {\n return core._number(ZodNumber, params);\n}\nexport const ZodNumberFormat = /*@__PURE__*/ core.$constructor(\"ZodNumberFormat\", (inst, def) => {\n core.$ZodNumberFormat.init(inst, def);\n ZodNumber.init(inst, def);\n});\nexport function int(params) {\n return core._int(ZodNumberFormat, params);\n}\nexport function float32(params) {\n return core._float32(ZodNumberFormat, params);\n}\nexport function float64(params) {\n return core._float64(ZodNumberFormat, params);\n}\nexport function int32(params) {\n return core._int32(ZodNumberFormat, params);\n}\nexport function uint32(params) {\n return core._uint32(ZodNumberFormat, params);\n}\nexport const ZodBoolean = /*@__PURE__*/ core.$constructor(\"ZodBoolean\", (inst, def) => {\n core.$ZodBoolean.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.booleanProcessor(inst, ctx, json, params);\n});\nexport function boolean(params) {\n return core._boolean(ZodBoolean, params);\n}\nexport const ZodBigInt = /*@__PURE__*/ core.$constructor(\"ZodBigInt\", (inst, def) => {\n core.$ZodBigInt.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.bigintProcessor(inst, ctx, json, params);\n}, \n/*@__PURE__*/ util.derived({\n minValue: (inst) => processors.aggregateChecks(inst).minimum ?? null,\n maxValue: (inst) => processors.aggregateChecks(inst).maximum ?? null,\n format: (inst) => processors.aggregateChecks(inst).format ?? null,\n}, {\n gte(value, params) {\n return this.check(checks.gte(value, params));\n },\n min(value, params) {\n return this.check(checks.gte(value, params));\n },\n gt(value, params) {\n return this.check(checks.gt(value, params));\n },\n lt(value, params) {\n return this.check(checks.lt(value, params));\n },\n lte(value, params) {\n return this.check(checks.lte(value, params));\n },\n max(value, params) {\n return this.check(checks.lte(value, params));\n },\n positive(params) {\n return this.check(checks.gt(BigInt(0), params));\n },\n negative(params) {\n return this.check(checks.lt(BigInt(0), params));\n },\n nonpositive(params) {\n return this.check(checks.lte(BigInt(0), params));\n },\n nonnegative(params) {\n return this.check(checks.gte(BigInt(0), params));\n },\n multipleOf(value, params) {\n return this.check(checks.multipleOf(value, params));\n },\n}));\nexport function bigint(params) {\n return core._bigint(ZodBigInt, params);\n}\nexport const ZodBigIntFormat = /*@__PURE__*/ core.$constructor(\"ZodBigIntFormat\", (inst, def) => {\n core.$ZodBigIntFormat.init(inst, def);\n ZodBigInt.init(inst, def);\n});\nexport function int64(params) {\n return core._int64(ZodBigIntFormat, params);\n}\nexport function uint64(params) {\n return core._uint64(ZodBigIntFormat, params);\n}\nexport const ZodSymbol = /*@__PURE__*/ core.$constructor(\"ZodSymbol\", (inst, def) => {\n core.$ZodSymbol.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.symbolProcessor(inst, ctx, json, params);\n});\nexport function symbol(params) {\n return core._symbol(ZodSymbol, params);\n}\nexport const ZodUndefined = /*@__PURE__*/ core.$constructor(\"ZodUndefined\", (inst, def) => {\n core.$ZodUndefined.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.undefinedProcessor(inst, ctx, json, params);\n});\nfunction _undefined(params) {\n return core._undefined(ZodUndefined, params);\n}\nexport { _undefined as undefined };\nexport const ZodNull = /*@__PURE__*/ core.$constructor(\"ZodNull\", (inst, def) => {\n core.$ZodNull.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nullProcessor(inst, ctx, json, params);\n});\nfunction _null(params) {\n return core._null(ZodNull, params);\n}\nexport { _null as null };\nexport const ZodAny = /*@__PURE__*/ core.$constructor(\"ZodAny\", (inst, def) => {\n core.$ZodAny.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.anyProcessor(inst, ctx, json, params);\n});\nexport function any() {\n return core._any(ZodAny);\n}\nexport const ZodUnknown = /*@__PURE__*/ core.$constructor(\"ZodUnknown\", (inst, def) => {\n core.$ZodUnknown.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.unknownProcessor(inst, ctx, json, params);\n});\nexport function unknown() {\n return core._unknown(ZodUnknown);\n}\nexport const ZodNever = /*@__PURE__*/ core.$constructor(\"ZodNever\", (inst, def) => {\n core.$ZodNever.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.neverProcessor(inst, ctx, json, params);\n});\nexport function never(params) {\n return core._never(ZodNever, params);\n}\nexport const ZodVoid = /*@__PURE__*/ core.$constructor(\"ZodVoid\", (inst, def) => {\n core.$ZodVoid.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.voidProcessor(inst, ctx, json, params);\n});\nfunction _void(params) {\n return core._void(ZodVoid, params);\n}\nexport { _void as void };\nexport const ZodDate = /*@__PURE__*/ core.$constructor(\"ZodDate\", (inst, def) => {\n core.$ZodDate.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.dateProcessor(inst, ctx, json, params);\n inst.min = (value, params) => inst.check(checks.gte(value, params));\n inst.max = (value, params) => inst.check(checks.lte(value, params));\n}, \n/*@__PURE__*/ util.derived({\n minDate: (inst) => {\n const { minimum } = processors.aggregateChecks(inst);\n return minimum ? new Date(minimum) : null;\n },\n maxDate: (inst) => {\n const { maximum } = processors.aggregateChecks(inst);\n return maximum ? new Date(maximum) : null;\n },\n}, {}));\nexport function date(params) {\n return core._date(ZodDate, params);\n}\nexport const ZodArray = /*@__PURE__*/ core.$constructor(\"ZodArray\", (inst, def) => {\n _ensureDefaultMemoizer();\n core.$ZodArray.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.arrayProcessor(inst, ctx, json, params);\n inst.element = def.element;\n}, {\n min(n, params) {\n return this.check(checks.minLength(n, params));\n },\n nonempty(params) {\n return this.check(checks.minLength(1, params));\n },\n max(n, params) {\n return this.check(checks.maxLength(n, params));\n },\n length(n, params) {\n return this.check(checks.length(n, params));\n },\n unwrap() {\n return this.element;\n },\n});\nexport function array(element, params) {\n return core._array(ZodArray, element, params);\n}\n// .keyof\nexport function keyof(schema) {\n const shape = schema._zod.def.shape;\n return _enum(Object.keys(shape));\n}\nexport const ZodObject = /*@__PURE__*/ core.$constructor(\"ZodObject\", (inst, def) => {\n _ensureDefaultMemoizer();\n core.$ZodObjectJIT.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.objectProcessor(inst, ctx, json, params);\n util.installLazyProp(inst, \"shape\", (self) => self._zod.def.shape, false);\n}, {\n keyof() {\n return _enum(Object.keys(this._zod.def.shape));\n },\n catchall(catchall) {\n // `mergeDefs` rather than a spread: spreading reads `shape`, and resolving it can mint a whole fresh subtree\n return this.clone(util.mergeDefs(this._zod.def, { catchall: catchall }));\n },\n passthrough() {\n return this.clone(util.mergeDefs(this._zod.def, { catchall: unknown() }));\n },\n loose() {\n return this.clone(util.mergeDefs(this._zod.def, { catchall: unknown() }));\n },\n strict() {\n return this.clone(util.mergeDefs(this._zod.def, { catchall: never() }));\n },\n strip() {\n return this.clone(util.mergeDefs(this._zod.def, { catchall: undefined }));\n },\n extend(incoming) {\n return util.extend(this, incoming);\n },\n safeExtend(incoming) {\n return util.safeExtend(this, incoming);\n },\n merge(other) {\n return util.merge(this, other);\n },\n pick(mask) {\n return util.pick(this, mask);\n },\n omit(mask) {\n return util.omit(this, mask);\n },\n partial(...args) {\n return util.partial(ZodOptional, this, args[0]);\n },\n exactPartial(...args) {\n return util.partial(ZodExactOptional, this, args[0], \"exactPartial\");\n },\n required(...args) {\n return util.required(ZodNonOptional, this, args[0]);\n },\n});\nexport function object(shape, params) {\n const def = {\n type: \"object\",\n shape: shape ?? {},\n ...util.normalizeParams(params),\n };\n return new ZodObject(def);\n}\n// strictObject\nexport function strictObject(shape, params) {\n return new ZodObject({\n type: \"object\",\n shape,\n catchall: never(),\n ...util.normalizeParams(params),\n });\n}\n// looseObject\nexport function looseObject(shape, params) {\n return new ZodObject({\n type: \"object\",\n shape,\n catchall: unknown(),\n ...util.normalizeParams(params),\n });\n}\nexport const ZodUnion = /*@__PURE__*/ core.$constructor(\"ZodUnion\", (inst, def) => {\n core.$ZodUnion.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.unionProcessor(inst, ctx, json, params);\n inst.options = def.options;\n});\nexport function union(options, params) {\n return new ZodUnion({\n type: \"union\",\n options: options,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodXor = /*@__PURE__*/ core.$constructor(\"ZodXor\", (inst, def) => {\n ZodUnion.init(inst, def);\n core.$ZodXor.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.unionProcessor(inst, ctx, json, params);\n inst.options = def.options;\n});\n/** Creates an exclusive union (XOR) where exactly one option must match.\n * Unlike regular unions that succeed when any option matches, xor fails if\n * zero or more than one option matches the input. */\nexport function xor(options, params) {\n return new ZodXor({\n type: \"union\",\n options: options,\n inclusive: false,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodDiscriminatedUnion = /*@__PURE__*/ core.$constructor(\"ZodDiscriminatedUnion\", (inst, def) => {\n ZodUnion.init(inst, def);\n core.$ZodDiscriminatedUnion.init(inst, def);\n});\nexport function discriminatedUnion(discriminator, options, params) {\n // const [options, params] = args;\n return new ZodDiscriminatedUnion({\n type: \"union\",\n options: options,\n discriminator,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodIntersection = /*@__PURE__*/ core.$constructor(\"ZodIntersection\", (inst, def) => {\n core.$ZodIntersection.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.intersectionProcessor(inst, ctx, json, params);\n});\nexport function intersection(left, right) {\n return new ZodIntersection({\n type: \"intersection\",\n left: left,\n right: right,\n });\n}\nexport const ZodTuple = /*@__PURE__*/ core.$constructor(\"ZodTuple\", (inst, def) => {\n _ensureDefaultMemoizer();\n core.$ZodTuple.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.tupleProcessor(inst, ctx, json, params);\n}, {\n rest(rest) {\n return this.clone({\n ...this._zod.def,\n rest: rest,\n });\n },\n partial() {\n const def = this._zod.def;\n // a refinement was authored against the full arity; partialing would run it on a shorter array\n if (def.checks?.length)\n throw new Error(\".partial() cannot be used on tuple schemas containing refinements\");\n return this.clone({\n ...def,\n items: def.items.map((item) => new ZodOptional({ type: \"optional\", innerType: item })),\n });\n },\n});\nexport function tuple(items, _paramsOrRest, _params) {\n const hasRest = _paramsOrRest instanceof core.$ZodType;\n const params = hasRest ? _params : _paramsOrRest;\n const rest = hasRest ? _paramsOrRest : null;\n return new ZodTuple({\n type: \"tuple\",\n items: items,\n rest,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodRecord = /*@__PURE__*/ core.$constructor(\"ZodRecord\", (inst, def) => {\n _ensureDefaultMemoizer();\n core.$ZodRecord.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.recordProcessor(inst, ctx, json, params);\n inst.keyType = def.keyType;\n inst.valueType = def.valueType;\n});\nexport function record(keyType, valueType, params) {\n // v3-compat: z.record(valueType, params?) — defaults keyType to z.string()\n if (!valueType || !valueType._zod) {\n return new ZodRecord({\n type: \"record\",\n keyType: string(),\n valueType: keyType,\n ...util.normalizeParams(valueType),\n });\n }\n return new ZodRecord({\n type: \"record\",\n keyType,\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\n// type alksjf = core.output<core.$ZodRecordKey>;\nexport function partialRecord(keyType, valueType, params) {\n return new ZodRecord({\n type: \"record\",\n keyType,\n valueType: valueType,\n ...util.normalizeParams(params),\n partial: true,\n });\n}\nexport function looseRecord(keyType, valueType, params) {\n return new ZodRecord({\n type: \"record\",\n keyType,\n valueType: valueType,\n mode: \"loose\",\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMap = /*@__PURE__*/ core.$constructor(\"ZodMap\", (inst, def) => {\n _ensureDefaultMemoizer();\n core.$ZodMap.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.mapProcessor(inst, ctx, json, params);\n inst.keyType = def.keyType;\n inst.valueType = def.valueType;\n inst.min = (...args) => inst.check(core._minSize(...args));\n inst.nonempty = (params) => inst.check(core._minSize(1, params));\n inst.max = (...args) => inst.check(core._maxSize(...args));\n inst.size = (...args) => inst.check(core._size(...args));\n});\nexport function map(keyType, valueType, params) {\n return new ZodMap({\n type: \"map\",\n keyType: keyType,\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodSet = /*@__PURE__*/ core.$constructor(\"ZodSet\", (inst, def) => {\n _ensureDefaultMemoizer();\n core.$ZodSet.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.setProcessor(inst, ctx, json, params);\n inst.min = (...args) => inst.check(core._minSize(...args));\n inst.nonempty = (params) => inst.check(core._minSize(1, params));\n inst.max = (...args) => inst.check(core._maxSize(...args));\n inst.size = (...args) => inst.check(core._size(...args));\n});\nexport function set(valueType, params) {\n return new ZodSet({\n type: \"set\",\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodEnum = /*@__PURE__*/ core.$constructor(\"ZodEnum\", (inst, def) => {\n core.$ZodEnum.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.enumProcessor(inst, ctx, json, params);\n inst.enum = def.entries;\n // reuse the parsed value set so a numeric TS enum's reverse-mapping keys stay out\n inst.options = [...inst._zod.values];\n const keys = new Set(Object.keys(def.entries));\n inst.extract = (values, params) => {\n const newEntries = {};\n for (const value of values) {\n if (keys.has(value)) {\n newEntries[value] = def.entries[value];\n }\n else\n throw new Error(`Key ${value} not found in enum`);\n }\n return new ZodEnum({\n ...def,\n checks: [],\n ...util.normalizeParams(params),\n entries: newEntries,\n });\n };\n inst.exclude = (values, params) => {\n const newEntries = { ...def.entries };\n for (const value of values) {\n if (keys.has(value)) {\n delete newEntries[value];\n }\n else\n throw new Error(`Key ${value} not found in enum`);\n }\n return new ZodEnum({\n ...def,\n checks: [],\n ...util.normalizeParams(params),\n entries: newEntries,\n });\n };\n});\nfunction _enum(values, params) {\n const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;\n return new ZodEnum({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\nexport { _enum as enum };\n/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead.\n *\n * ```ts\n * enum Colors { red, green, blue }\n * z.enum(Colors);\n * ```\n */\nexport function nativeEnum(entries, params) {\n return new ZodEnum({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodLiteral = /*@__PURE__*/ core.$constructor(\"ZodLiteral\", (inst, def) => {\n core.$ZodLiteral.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.literalProcessor(inst, ctx, json, params);\n inst.values = new Set(def.values);\n Object.defineProperty(inst, \"value\", {\n get() {\n if (def.values.length > 1) {\n throw new Error(\"This schema contains multiple valid literal values. Use `.values` instead.\");\n }\n return def.values[0];\n },\n });\n});\nexport function literal(value, params) {\n return new ZodLiteral({\n type: \"literal\",\n values: Array.isArray(value) ? value : [value],\n ...util.normalizeParams(params),\n });\n}\nexport const ZodFile = /*@__PURE__*/ core.$constructor(\"ZodFile\", (inst, def) => {\n core.$ZodFile.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.fileProcessor(inst, ctx, json, params);\n inst.min = (size, params) => inst.check(core._minSize(size, params));\n inst.max = (size, params) => inst.check(core._maxSize(size, params));\n inst.mime = (types, params) => inst.check(core._mime(Array.isArray(types) ? types : [types], params));\n});\nexport function file(params) {\n return core._file(ZodFile, params);\n}\nexport const ZodTransform = /*@__PURE__*/ core.$constructor(\"ZodTransform\", (inst, def) => {\n _ensureDefaultMemoizer();\n core.$ZodTransform.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.transformProcessor(inst, ctx, json, params);\n inst._zod.parse = (payload, _ctx) => {\n if (_ctx.direction === \"backward\") {\n throw new core.$ZodEncodeError(inst.constructor.name);\n }\n payload.addIssue = (issue) => {\n if (typeof issue === \"string\") {\n payload.issues.push(util.issue(issue, payload.value, def));\n }\n else {\n // for Zod 3 backwards compatibility\n const _issue = issue;\n if (_issue.fatal)\n _issue.continue = false;\n _issue.code ?? (_issue.code = \"custom\");\n if (!(\"input\" in _issue))\n _issue.input = payload.value;\n _issue.inst ?? (_issue.inst = inst);\n // _issue.continue ??= true;\n payload.issues.push(util.issue(_issue));\n }\n };\n const output = def.transform(payload.value, payload);\n if (output instanceof Promise) {\n return output.then((output) => {\n payload.value = output;\n return payload;\n });\n }\n payload.value = output;\n return payload;\n };\n});\nexport function transform(fn) {\n return new ZodTransform({\n type: \"transform\",\n transform: fn,\n });\n}\nexport const ZodOptional = /*@__PURE__*/ core.$constructor(\"ZodOptional\", (inst, def) => {\n core.$ZodOptional.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.optionalProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function optional(innerType) {\n return new ZodOptional({\n type: \"optional\",\n innerType: innerType,\n });\n}\nexport const ZodExactOptional = /*@__PURE__*/ core.$constructor(\"ZodExactOptional\", (inst, def) => {\n core.$ZodExactOptional.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.optionalProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function exactOptional(innerType) {\n return new ZodExactOptional({\n type: \"optional\",\n innerType: innerType,\n });\n}\nexport const ZodNullable = /*@__PURE__*/ core.$constructor(\"ZodNullable\", (inst, def) => {\n core.$ZodNullable.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nullableProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function nullable(innerType) {\n return new ZodNullable({\n type: \"nullable\",\n innerType: innerType,\n });\n}\n// nullish\nexport function nullish(innerType) {\n return optional(nullable(innerType));\n}\nexport const ZodDefault = /*@__PURE__*/ core.$constructor(\"ZodDefault\", (inst, def) => {\n core.$ZodDefault.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.defaultProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n inst.removeDefault = inst.unwrap;\n});\nexport function _default(innerType, defaultValue) {\n return new ZodDefault({\n type: \"default\",\n innerType: innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\nexport const ZodPrefault = /*@__PURE__*/ core.$constructor(\"ZodPrefault\", (inst, def) => {\n core.$ZodPrefault.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.prefaultProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function prefault(innerType, defaultValue) {\n return new ZodPrefault({\n type: \"prefault\",\n innerType: innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\nexport const ZodNonOptional = /*@__PURE__*/ core.$constructor(\"ZodNonOptional\", (inst, def) => {\n core.$ZodNonOptional.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nonoptionalProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function nonoptional(innerType, params) {\n return new ZodNonOptional({\n type: \"nonoptional\",\n innerType: innerType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodSuccess = /*@__PURE__*/ core.$constructor(\"ZodSuccess\", (inst, def) => {\n core.$ZodSuccess.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.successProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function success(innerType) {\n return new ZodSuccess({\n type: \"success\",\n innerType: innerType,\n });\n}\nexport const ZodCatch = /*@__PURE__*/ core.$constructor(\"ZodCatch\", (inst, def) => {\n core.$ZodCatch.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.catchProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n inst.removeCatch = inst.unwrap;\n});\nfunction _catch(innerType, catchValue) {\n return new ZodCatch({\n type: \"catch\",\n innerType: innerType,\n catchValue: (typeof catchValue === \"function\" ? catchValue : core.util.constantCatch(catchValue)),\n });\n}\nexport { _catch as catch };\nexport const ZodNaN = /*@__PURE__*/ core.$constructor(\"ZodNaN\", (inst, def) => {\n core.$ZodNaN.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nanProcessor(inst, ctx, json, params);\n});\nexport function nan(params) {\n return core._nan(ZodNaN, params);\n}\nexport const ZodPipe = /*@__PURE__*/ core.$constructor(\"ZodPipe\", (inst, def) => {\n core.$ZodPipe.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.pipeProcessor(inst, ctx, json, params);\n inst.in = def.in;\n inst.out = def.out;\n});\nexport function pipe(in_, out) {\n return new ZodPipe({\n type: \"pipe\",\n in: in_,\n out: out,\n // ...util.normalizeParams(params),\n });\n}\nexport const ZodCodec = /*@__PURE__*/ core.$constructor(\"ZodCodec\", (inst, def) => {\n ZodPipe.init(inst, def);\n core.$ZodCodec.init(inst, def);\n});\nexport function codec(in_, out, params) {\n return new ZodCodec({\n type: \"pipe\",\n in: in_,\n out: out,\n transform: params.decode,\n reverseTransform: params.encode,\n });\n}\nexport function invertCodec(codec) {\n const def = codec._zod.def;\n return new ZodCodec({\n type: \"pipe\",\n in: def.out,\n out: def.in,\n transform: def.reverseTransform,\n reverseTransform: def.transform,\n });\n}\nexport const ZodPreprocess = /*@__PURE__*/ core.$constructor(\"ZodPreprocess\", (inst, def) => {\n ZodPipe.init(inst, def);\n core.$ZodPreprocess.init(inst, def);\n});\nexport const ZodReadonly = /*@__PURE__*/ core.$constructor(\"ZodReadonly\", (inst, def) => {\n core.$ZodReadonly.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.readonlyProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function readonly(innerType) {\n return new ZodReadonly({\n type: \"readonly\",\n innerType: innerType,\n });\n}\nexport const ZodTemplateLiteral = /*@__PURE__*/ core.$constructor(\"ZodTemplateLiteral\", (inst, def) => {\n core.$ZodTemplateLiteral.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.templateLiteralProcessor(inst, ctx, json, params);\n});\nexport function templateLiteral(parts, params) {\n return new ZodTemplateLiteral({\n type: \"template_literal\",\n parts,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodLazy = /*@__PURE__*/ core.$constructor(\"ZodLazy\", (inst, def) => {\n core.$ZodLazy.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.lazyProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.getter();\n});\nexport function lazy(getter) {\n return new ZodLazy({\n type: \"lazy\",\n getter: getter,\n });\n}\nexport const ZodPromise = /*@__PURE__*/ core.$constructor(\"ZodPromise\", (inst, def) => {\n core.$ZodPromise.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.promiseProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function promise(innerType) {\n return new ZodPromise({\n type: \"promise\",\n innerType: innerType,\n });\n}\nexport const ZodFunction = /*@__PURE__*/ core.$constructor(\"ZodFunction\", (inst, def) => {\n core.$ZodFunction.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.functionProcessor(inst, ctx, json, params);\n});\nexport function _function(params) {\n return new ZodFunction({\n type: \"function\",\n input: Array.isArray(params?.input) ? tuple(params?.input) : (params?.input ?? array(unknown())),\n output: params?.output ?? unknown(),\n });\n}\nexport { _function as function };\nexport const ZodCustom = /*@__PURE__*/ core.$constructor(\"ZodCustom\", (inst, def) => {\n core.$ZodCustom.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.customProcessor(inst, ctx, json, params);\n});\n// custom checks\nexport function check(fn) {\n const ch = new core.$ZodCheck({\n check: \"custom\",\n // ...util.normalizeParams(params),\n });\n ch._zod.check = fn;\n return ch;\n}\nexport function custom(fn, _params) {\n return core._custom(ZodCustom, fn ?? (() => true), _params);\n}\nexport function refine(fn, _params = {}) {\n return core._refine(ZodCustom, fn, _params);\n}\n// superRefine\nexport function superRefine(fn, params) {\n return core._superRefine(fn, params);\n}\n// Re-export describe and meta from core\nexport const describe = core.describe;\nexport const meta = core.meta;\nexport const ZodInstanceOf = /*@__PURE__*/ core.$constructor(\"ZodInstanceOf\", (inst, def) => {\n ZodCustom.init(inst, def);\n}, {\n properties(shape, params) {\n // asserts in place, so the narrowed output type is truthful without a wrapper\n return this.check(core._properties(shape, params));\n },\n});\nfunction _instanceof(cls, params = {}) {\n const inst = new ZodInstanceOf({\n type: \"custom\",\n check: \"custom\",\n fn: (data) => data instanceof cls,\n abort: true,\n ...util.normalizeParams(params),\n });\n inst._zod.bag.Class = cls;\n // Override check to emit invalid_type instead of custom\n inst._zod.check = (payload) => {\n if (!(payload.value instanceof cls)) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: cls.name,\n input: payload.value,\n inst,\n path: [...(inst._zod.def.path ?? [])],\n });\n }\n };\n return inst;\n}\nexport { _instanceof as instanceof };\n// stringbool\nexport const stringbool = (...args) => core._stringbool({\n Codec: ZodCodec,\n Boolean: ZodBoolean,\n String: ZodString,\n}, ...args);\nexport function json(params) {\n const jsonSchema = lazy(() => {\n return union([string(params), number(), boolean(), _null(), array(jsonSchema), record(string(), jsonSchema)]);\n });\n return jsonSchema;\n}\n// preprocess\nexport function preprocess(fn, schema) {\n return new ZodPreprocess({\n type: \"pipe\",\n in: transform(fn),\n out: schema,\n });\n}\n", "import { z } from \"zod\";\nimport { cliProducts } from \"./constants\";\n\nconst dateTimeString = z\n\t.string()\n\t.refine((value) => Number.isFinite(Date.parse(value)), \"Invalid datetime\");\nconst base64Url = z\n\t.string()\n\t.min(43)\n\t.max(128)\n\t.regex(/^[A-Za-z0-9_-]+$/);\n\nexport const beginDeviceAuthorizationRequestSchema = z\n\t.object({\n\t\tclientName: z.string().trim().min(1).max(120),\n\t\tclientVersion: z.string().trim().min(1).max(64),\n\t\tcodeChallenge: base64Url,\n\t\tcodeChallengeMethod: z.literal(\"S256\"),\n\t\tplatform: z.string().trim().min(1).max(64),\n\t})\n\t.strict();\n\nexport const beginDeviceAuthorizationResponseSchema = z\n\t.object({\n\t\tdeviceCode: z.string().min(40).max(128),\n\t\texpiresIn: z.number().int().min(60).max(1800),\n\t\tinterval: z.number().int().min(1).max(30),\n\t\tuserCode: z.string().regex(/^[A-HJ-NP-Z2-9]{4}-[A-HJ-NP-Z2-9]{4}$/),\n\t\tverificationUri: z.string().url(),\n\t\tverificationUriComplete: z.string().url(),\n\t})\n\t.strict();\n\nexport const tokenRequestSchema = z\n\t.object({\n\t\tcodeVerifier: base64Url,\n\t\tdeviceCode: z.string().min(40).max(128),\n\t})\n\t.strict();\n\nexport const cliSessionIdentitySchema = z\n\t.object({\n\t\temail: z.string().email(),\n\t\tid: z.string().min(1),\n\t\tname: z.string().min(1).max(120),\n\t\tuserId: z.string().min(1),\n\t})\n\t.strict();\n\nexport const tokenResponseSchema = z\n\t.object({\n\t\taccessToken: z.string().min(40),\n\t\texpiresIn: z.number().int().positive(),\n\t\trefreshExpiresIn: z.number().int().positive(),\n\t\trefreshToken: z.string().min(40),\n\t\tsession: cliSessionIdentitySchema,\n\t\ttokenType: z.literal(\"Bearer\"),\n\t})\n\t.strict();\n\nexport const deviceTokenErrorSchema = z\n\t.object({\n\t\terror: z.enum([\n\t\t\t\"authorization_pending\",\n\t\t\t\"slow_down\",\n\t\t\t\"access_denied\",\n\t\t\t\"expired_token\",\n\t\t\t\"invalid_grant\",\n\t\t]),\n\t})\n\t.strict();\n\nexport const refreshRequestSchema = z\n\t.object({ refreshToken: z.string().min(40) })\n\t.strict();\nexport const revokeRequestSchema = refreshRequestSchema;\n\nexport const storedCliCredentialsSchema = z\n\t.object({\n\t\taccessToken: z.string().min(1),\n\t\taccessTokenExpiresAt: dateTimeString,\n\t\t// Credentials written before issuer binding was introduced are accepted only\n\t\t// so the client can direct the user to sign in again. They are never sent.\n\t\tissuer: z.string().url().optional(),\n\t\trefreshToken: z.string().min(1),\n\t\trefreshTokenExpiresAt: dateTimeString,\n\t\tsession: cliSessionIdentitySchema,\n\t})\n\t.strict();\nexport type StoredCliCredentials = z.infer<typeof storedCliCredentialsSchema>;\n\nexport const cliProductSchema = z.enum(cliProducts);\n", "import { execFile } from \"node:child_process\";\nimport type { CliProduct } from \"@go-labs/cli-auth/protocol\";\nimport { z } from \"zod\";\nimport type { SecretsApi } from \"./credential-store\";\nimport { assertBunRuntime } from \"./runtime\";\nimport {\n\tCliCredentialStoreUnavailableError,\n\ttype CredentialStoreFailure,\n\tclassifyCredentialStoreFailure,\n} from \"./storage-error\";\n\nconst timeoutMs = 10_000;\nconst maxBuffer = 64 * 1024;\n\n// No shell, secret argv, inherited stdin, raw backend errors, or unbounded output.\nconst runBackend = (\n\tproduct: CliProduct,\n\texecutable: string,\n\targs: string[],\n\tinput: string,\n\tfailure: CredentialStoreFailure,\n): Promise<string> =>\n\tnew Promise((resolve, reject) => {\n\t\tconst child = execFile(\n\t\t\texecutable,\n\t\t\targs,\n\t\t\t{\n\t\t\t\ttimeout: timeoutMs,\n\t\t\t\tkillSignal: \"SIGKILL\",\n\t\t\t\tmaxBuffer,\n\t\t\t\twindowsHide: true,\n\t\t\t},\n\t\t\t(error, stdout, stderr) => {\n\t\t\t\tif (error) {\n\t\t\t\t\tconst reason =\n\t\t\t\t\t\terror.code === \"ERR_CHILD_PROCESS_STDIO_MAXBUFFER\"\n\t\t\t\t\t\t\t? \"invalid-response\"\n\t\t\t\t\t\t\t: error.killed\n\t\t\t\t\t\t\t\t? \"timeout\"\n\t\t\t\t\t\t\t\t: classifyCredentialStoreFailure(\n\t\t\t\t\t\t\t\t\t\t`${stdout}\\n${stderr}`,\n\t\t\t\t\t\t\t\t\t\tfailure,\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\treject(new CliCredentialStoreUnavailableError(product, reason));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tresolve(stdout);\n\t\t\t},\n\t\t);\n\t\tchild.stdin?.on(\"error\", () => {\n\t\t\t/* Completion callback owns diagnostics. */\n\t\t});\n\t\tchild.stdin?.end(input);\n\t});\n\n// Run Bun.secrets in a cancellable child. A Promise.race cannot stop native calls\n// or a desktop unlock prompt from keeping the CLI alive after its timeout.\nconst nativeWorker = `\ntry {\n const { operation, input } = JSON.parse(await Bun.stdin.text());\n const value = await Bun.secrets[operation](input);\n process.stdout.write(JSON.stringify({ value: value ?? null }));\n} catch (error) {\n const message = error instanceof Error ? error.message : \"Credential backend failed\";\n // libsecret's bus transport errors can omit the D-Bus context.\n const context = process.platform === \"linux\" && /^Could not connect:/i.test(message) ? \"D-Bus: \" : \"\";\n process.stderr.write(context + message);\n process.exitCode = 1;\n}\n`;\nconst nativeResponse = z\n\t.object({ value: z.union([z.string(), z.boolean(), z.null()]) })\n\t.strict();\n\nexport const createIsolatedBunSecrets = (product: CliProduct): SecretsApi => {\n\tconst run = async (\n\t\toperation: \"get\" | \"set\" | \"delete\",\n\t\tinput: { name: string; service: string; value?: string },\n\t) => {\n\t\tassertBunRuntime();\n\t\tconst output = await runBackend(\n\t\t\tproduct,\n\t\t\tprocess.execPath,\n\t\t\t[\"--no-env-file\", \"--eval\", nativeWorker],\n\t\t\tJSON.stringify({ operation, input }),\n\t\t\toperation === \"set\"\n\t\t\t\t? \"write-failed\"\n\t\t\t\t: operation === \"delete\"\n\t\t\t\t\t? \"delete-failed\"\n\t\t\t\t\t: \"read-failed\",\n\t\t);\n\t\ttry {\n\t\t\treturn nativeResponse.parse(JSON.parse(output)).value;\n\t\t} catch {\n\t\t\tthrow new CliCredentialStoreUnavailableError(product, \"invalid-response\");\n\t\t}\n\t};\n\treturn {\n\t\tget: async (input) => {\n\t\t\tconst value = await run(\"get\", input);\n\t\t\tif (value === null || typeof value === \"string\") return value;\n\t\t\tthrow new CliCredentialStoreUnavailableError(product, \"invalid-response\");\n\t\t},\n\t\tset: async (input) => {\n\t\t\tawait run(\"set\", input);\n\t\t},\n\t\tdelete: async (input) => (await run(\"delete\", input)) === true,\n\t};\n};\n", "export const MINIMUM_BUN_VERSION = [1, 4, 0] as const;\n\nexport const parseBunVersion = (version: string): [number, number, number] => {\n\tconst match = /^(\\d+)\\.(\\d+)\\.(\\d+)/.exec(version);\n\tif (!match) throw new Error(`Unable to parse Bun version: ${version}`);\n\treturn [Number(match[1]), Number(match[2]), Number(match[3])];\n};\n\nconst compareVersions = (left: readonly number[], right: readonly number[]) => {\n\tfor (let index = 0; index < 3; index += 1) {\n\t\tconst difference = (left[index] ?? 0) - (right[index] ?? 0);\n\t\tif (difference !== 0) return difference;\n\t}\n\treturn 0;\n};\n\nexport const assertBunRuntime = (\n\truntime: { version: string } | undefined = globalThis.Bun,\n): void => {\n\tif (!runtime) {\n\t\tthrow new Error(\n\t\t\t\"This CLI requires Bun 1.4.0 or newer. Install it with `npm install --global bun`, then retry the command.\",\n\t\t);\n\t}\n\tif (\n\t\tcompareVersions(parseBunVersion(runtime.version), MINIMUM_BUN_VERSION) < 0\n\t) {\n\t\tthrow new Error(\n\t\t\t`This CLI requires Bun 1.4.0 or newer (found ${runtime.version}). Run \\`bun upgrade\\`, then retry the command.`,\n\t\t);\n\t}\n};\n", "import type { CliProduct } from \"@go-labs/cli-auth/protocol\";\n\nexport type CredentialStoreFailure =\n\t| \"missing-library\"\n\t| \"bus-unavailable\"\n\t| \"bus-denied\"\n\t| \"service-unavailable\"\n\t| \"locked\"\n\t| \"timeout\"\n\t| \"invalid-response\"\n\t| \"read-failed\"\n\t| \"write-failed\"\n\t| \"delete-failed\";\n\nconst guidance: Record<CredentialStoreFailure, string> = {\n\t\"missing-library\":\n\t\t\"Install the runtime's native credential-store library and ensure your own native keyring/session is accessible and unlocked; Linux desktop storage requires libsecret AND an accessible, unlocked Secret Service.\",\n\t\"bus-unavailable\":\n\t\t\"The Linux user D-Bus session is absent or unreachable. --no-browser does not provide storage. Start or repair your own user session and native keyring before retrying.\",\n\t\"bus-denied\":\n\t\t\"Access to the Linux user bus was denied. Fix your own native keyring/session permissions or host policy; do not change bus/socket permissions or borrow another user's bus.\",\n\t\"service-unavailable\":\n\t\t\"The user bus is reachable but your own Secret Service is unavailable. Start or repair your own native keyring session; do not expose another user's store.\",\n\tlocked:\n\t\t\"Unlock your own native credential collection/session before retrying. The CLI will not wait indefinitely for an unlock prompt.\",\n\ttimeout:\n\t\t\"The native credential backend did not finish within 10 seconds and its process was terminated. Fix or unlock your own native keyring/session outside the CLI; the CLI will not bypass host permissions.\",\n\t\"invalid-response\":\n\t\t\"The native credential backend returned an invalid response. Check your own keyring/session and configuration; no credential output was disclosed.\",\n\t\"read-failed\":\n\t\t\"The native credential backend could not read credentials. Check your own keyring/session availability and permissions; this is not evidence that you are logged out.\",\n\t\"write-failed\":\n\t\t\"The native credential backend could not persist credentials. Check your own keyring/session write permissions and availability; no plaintext fallback is used.\",\n\t\"delete-failed\":\n\t\t\"The native credential backend could not delete its entry. Check your own keyring/session permissions and remove any non-secret preflight probe through that backend if necessary.\",\n};\n\nexport class CliCredentialStoreUnavailableError extends Error {\n\treadonly code = \"CLI_CREDENTIAL_STORE_UNAVAILABLE\";\n\treadonly reason: CredentialStoreFailure;\n\n\tconstructor(\n\t\tproduct: CliProduct,\n\t\treason: CredentialStoreFailure = \"read-failed\",\n\t) {\n\t\tsuper(\n\t\t\t`Secure credential storage is unavailable for the ${product} CLI [CLI_CREDENTIAL_STORE_UNAVAILABLE:${reason}]. ${guidance[reason]}`,\n\t\t);\n\t\tthis.name = \"CliCredentialStoreUnavailableError\";\n\t\tthis.reason = reason;\n\t}\n}\n\n// Classify only; never attach backend output/causes, which may contain secrets.\nexport const classifyCredentialStoreFailure = (\n\tmessage: string,\n\tfallback: CredentialStoreFailure,\n): CredentialStoreFailure => {\n\tif (\n\t\t/libsecret.*(not found|not available|cannot open|load)|dlopen|shared (object|library).*not found/i.test(\n\t\t\tmessage,\n\t\t)\n\t)\n\t\treturn \"missing-library\";\n\tif (\n\t\t/(d-?bus|user bus|session bus).*(denied|not permitted)|(?:denied|not permitted).*(d-?bus|user bus|session bus)/i.test(\n\t\t\tmessage,\n\t\t)\n\t)\n\t\treturn \"bus-denied\";\n\tif (/locked|interaction.*not allowed|user.*cancel/i.test(message))\n\t\treturn \"locked\";\n\tif (\n\t\t/ServiceUnknown|org\\.freedesktop\\.secrets.*(not provided|no owner|not available)|secret.?service.*(unavailable|not running)/i.test(\n\t\t\tmessage,\n\t\t)\n\t)\n\t\treturn \"service-unavailable\";\n\tif (/d-?bus|user bus|session bus|autolaunch/i.test(message))\n\t\treturn \"bus-unavailable\";\n\treturn fallback;\n};\n\nexport class CliCredentialPersistenceError extends Error {\n\treadonly code = \"CLI_CREDENTIAL_PERSISTENCE_FAILED\";\n\tconstructor(\n\t\treadonly remoteRevoked: boolean,\n\t\treadonly localRestored: boolean,\n\t\treadonly phase: \"login\" | \"refresh\",\n\t) {\n\t\tsuper(\n\t\t\t`CLI credentials could not be saved after ${phase} [CLI_CREDENTIAL_PERSISTENCE_FAILED]. ${remoteRevoked ? \"The newly issued session was revoked.\" : \"Remote revocation could not be confirmed; revoke the session in the product's session management before retrying.\"} ${localRestored ? (phase === \"login\" ? \"The previous local credentials were preserved.\" : \"The unusable rotated local credentials were removed; sign in again.\") : \"Local cleanup could not be confirmed. Inspect your own native credential backend before retrying.\"}`,\n\t\t);\n\t\tthis.name = \"CliCredentialPersistenceError\";\n\t}\n}\n\nexport interface CliStorageErrorPayload {\n\tcode:\n\t\t| \"CLI_CREDENTIAL_STORE_UNAVAILABLE\"\n\t\t| \"CLI_CREDENTIAL_PERSISTENCE_FAILED\";\n\tmessage: string;\n\tdetails: Record<string, string | boolean>;\n}\n\nexport const getCliStorageError = (\n\terror: unknown,\n): CliStorageErrorPayload | undefined => {\n\tif (error instanceof CliCredentialStoreUnavailableError)\n\t\treturn {\n\t\t\tcode: error.code,\n\t\t\tmessage: error.message,\n\t\t\tdetails: { reason: error.reason },\n\t\t};\n\tif (error instanceof CliCredentialPersistenceError)\n\t\treturn {\n\t\t\tcode: error.code,\n\t\t\tmessage: error.message,\n\t\t\tdetails: {\n\t\t\t\tremoteRevoked: error.remoteRevoked,\n\t\t\t\tlocalRestored: error.localRestored,\n\t\t\t\tphase: error.phase,\n\t\t\t},\n\t\t};\n\treturn undefined;\n};\n", "import { hostname } from \"node:os\";\nimport { isDeepStrictEqual } from \"node:util\";\nimport {\n\tbeginDeviceAuthorizationResponseSchema,\n\tcreatePkcePair,\n\tdeviceTokenErrorSchema,\n\ttype StoredCliCredentials,\n\ttokenResponseSchema,\n} from \"@go-labs/cli-auth/protocol\";\nimport type { CliCredentialStore } from \"./credential-store\";\nimport { assertBunRuntime } from \"./runtime\";\nimport { CliCredentialPersistenceError } from \"./storage-error\";\n\nexport type FetchLike = (\n\tinput: string | URL | Request,\n\tinit?: RequestInit,\n) => Promise<Response>;\n\nexport const normalizeCliAuthIssuer = (value: string): string => {\n\tconst url = new URL(value);\n\turl.hash = \"\";\n\turl.search = \"\";\n\turl.pathname = url.pathname.replace(/\\/+$/, \"\");\n\treturn url.toString().replace(/\\/+$/, \"\");\n};\n\nexport const isCliCredentialForIssuer = (\n\tcredentials: StoredCliCredentials,\n\tapiBaseUrl: string,\n): boolean => credentials.issuer === normalizeCliAuthIssuer(apiBaseUrl);\n\nconst credentialIssuerError = (issuer: string | undefined): Error =>\n\tissuer\n\t\t? new Error(\n\t\t\t\t\"These CLI credentials belong to a different API URL. Run auth login for this API URL before retrying.\",\n\t\t\t)\n\t\t: new Error(\n\t\t\t\t\"These CLI credentials were created by an older CLI and are not bound to an API URL. Run auth login again.\",\n\t\t\t);\n\nconst assertCredentialIssuer = (\n\tcredentials: StoredCliCredentials,\n\tapiBaseUrl: string,\n): void => {\n\tconst expectedIssuer = normalizeCliAuthIssuer(apiBaseUrl);\n\tif (!credentials.issuer || credentials.issuer !== expectedIssuer) {\n\t\tthrow credentialIssuerError(credentials.issuer);\n\t}\n};\n\nconst postJson = async (\n\tfetchImplementation: FetchLike,\n\turl: string,\n\tbody: unknown,\n\toptions: Pick<RequestInit, \"signal\"> = {},\n): Promise<Response> =>\n\tfetchImplementation(url, {\n\t\tbody: JSON.stringify(body),\n\t\theaders: { \"content-type\": \"application/json\" },\n\t\tmethod: \"POST\",\n\t\t...options,\n\t});\n\nconst readJson = async (response: Response): Promise<unknown> => {\n\ttry {\n\t\treturn await response.json();\n\t} catch {\n\t\tthrow new Error(\n\t\t\t`CLI authentication returned HTTP ${response.status} without valid JSON.`,\n\t\t);\n\t}\n};\n\nconst localCredentialLocks = new WeakMap<CliCredentialStore, Promise<void>>();\n\nconst withCredentialLock = <Result>(\n\tstore: CliCredentialStore,\n\toperation: () => Promise<Result>,\n): Promise<Result> => {\n\tif (store.withCredentialLock) {\n\t\treturn store.withCredentialLock(operation);\n\t}\n\n\tconst previous = localCredentialLocks.get(store) ?? Promise.resolve();\n\tconst pending = previous.then(operation, operation);\n\tconst tail = pending.then(\n\t\t() => undefined,\n\t\t() => undefined,\n\t);\n\tlocalCredentialLocks.set(store, tail);\n\treturn pending.finally(() => {\n\t\tif (localCredentialLocks.get(store) === tail) {\n\t\t\tlocalCredentialLocks.delete(store);\n\t\t}\n\t});\n};\n\nconst toStoredCredentials = (\n\tresponse: ReturnType<typeof tokenResponseSchema.parse>,\n\tissuer: string,\n\tnow: Date,\n): StoredCliCredentials => ({\n\taccessToken: response.accessToken,\n\taccessTokenExpiresAt: new Date(\n\t\tnow.getTime() + response.expiresIn * 1000,\n\t).toISOString(),\n\tissuer,\n\trefreshToken: response.refreshToken,\n\trefreshTokenExpiresAt: new Date(\n\t\tnow.getTime() + response.refreshExpiresIn * 1000,\n\t).toISOString(),\n\tsession: response.session,\n});\n\nexport const openSystemBrowser = async (url: string): Promise<boolean> => {\n\tassertBunRuntime();\n\tconst command =\n\t\tprocess.platform === \"darwin\"\n\t\t\t? [\"open\", url]\n\t\t\t: process.platform === \"win32\"\n\t\t\t\t? [\n\t\t\t\t\t\t\"powershell.exe\",\n\t\t\t\t\t\t\"-NoProfile\",\n\t\t\t\t\t\t\"-NonInteractive\",\n\t\t\t\t\t\t\"-Command\",\n\t\t\t\t\t\t\"Start-Process -FilePath $env:GO_LABS_CLI_VERIFICATION_URI -ErrorAction Stop\",\n\t\t\t\t\t]\n\t\t\t\t: [\"xdg-open\", url];\n\ttry {\n\t\t// PowerShell -Command treats trailing arguments as script text, not $args.\n\t\t// Pass the verification URL as data without interpreting it as code.\n\t\tconst browserProcess = Bun.spawn(command, {\n\t\t\tenv:\n\t\t\t\tprocess.platform === \"win32\"\n\t\t\t\t\t? { ...process.env, GO_LABS_CLI_VERIFICATION_URI: url }\n\t\t\t\t\t: process.env,\n\t\t\tstderr: \"ignore\",\n\t\t\tstdout: \"ignore\",\n\t\t});\n\t\treturn (await browserProcess.exited) === 0;\n\t} catch {\n\t\treturn false;\n\t}\n};\n\nexport interface VerificationDetails {\n\tbrowserOpened: boolean;\n\tuserCode: string;\n\tverificationUriComplete: string;\n}\n\nconst persistLoginCredentials = async ({\n\tstore,\n\tcredentials,\n\tbaseUrl,\n\tfetchImplementation,\n}: {\n\tstore: CliCredentialStore;\n\tcredentials: StoredCliCredentials;\n\tbaseUrl: string;\n\tfetchImplementation: FetchLike;\n}): Promise<void> => {\n\ttry {\n\t\tawait withCredentialLock(store, () =>\n\t\t\tpersistIssuedCredentials({\n\t\t\t\tstore,\n\t\t\t\tcredentials,\n\t\t\t\tapiBaseUrl: baseUrl,\n\t\t\t\tfetch: fetchImplementation,\n\t\t\t\tphase: \"login\",\n\t\t\t}),\n\t\t);\n\t} catch (error) {\n\t\tif (error instanceof CliCredentialPersistenceError) throw error;\n\t\t// Lock acquisition/release may fail after issuance too. Do not\n\t\t// abandon the new session or mutate local state without the lock.\n\t\tthrow new CliCredentialPersistenceError(\n\t\t\tawait revokeIssuedCredentials(fetchImplementation, baseUrl, credentials),\n\t\t\tfalse,\n\t\t\t\"login\",\n\t\t);\n\t}\n};\n\n/** Next polling interval for a device-token error, or throws when terminal. */\nconst nextPollIntervalMs = (errorCode: string, intervalMs: number): number => {\n\tif (errorCode === \"authorization_pending\") return intervalMs;\n\tif (errorCode === \"slow_down\") return intervalMs + 5000;\n\tif (errorCode === \"access_denied\") {\n\t\tthrow new Error(\"CLI authentication was denied in the browser.\");\n\t}\n\tthrow new Error(\"CLI authentication expired. Run auth login again.\");\n};\n\nexport const loginWithBrowser = async ({\n\tapiBaseUrl,\n\tclientName = hostname(),\n\tclientVersion,\n\tfetch: fetchImplementation = globalThis.fetch,\n\tnow = () => new Date(),\n\tonVerification,\n\topenBrowser = openSystemBrowser,\n\tplatform = `${process.platform}-${process.arch}`,\n\tsleep = (milliseconds: number) => Bun.sleep(milliseconds),\n\tstore,\n}: {\n\tapiBaseUrl: string;\n\tclientName?: string;\n\tclientVersion: string;\n\tfetch?: FetchLike;\n\tnow?: () => Date;\n\tonVerification: (details: VerificationDetails) => void;\n\topenBrowser?: (url: string) => Promise<boolean>;\n\tplatform?: string;\n\tsleep?: (milliseconds: number) => Promise<void>;\n\tstore: CliCredentialStore;\n}): Promise<StoredCliCredentials> => {\n\tconst baseUrl = normalizeCliAuthIssuer(apiBaseUrl);\n\t// A read alone cannot establish persistence/rotation/delete capability.\n\tif (store.preflight)\n\t\tawait withCredentialLock(\n\t\t\tstore,\n\t\t\t() => store.preflight?.() ?? Promise.resolve(),\n\t\t);\n\tconst pkce = createPkcePair();\n\tconst beginResponse = await postJson(\n\t\tfetchImplementation,\n\t\t`${baseUrl}/api/cli-auth/device`,\n\t\t{\n\t\t\tclientName,\n\t\t\tclientVersion,\n\t\t\tcodeChallenge: pkce.challenge,\n\t\t\tcodeChallengeMethod: pkce.method,\n\t\t\tplatform,\n\t\t},\n\t);\n\tif (!beginResponse.ok) {\n\t\tthrow new Error(\n\t\t\t`Unable to start CLI browser authentication (HTTP ${beginResponse.status}).`,\n\t\t);\n\t}\n\tconst authorization = beginDeviceAuthorizationResponseSchema.parse(\n\t\tawait readJson(beginResponse),\n\t);\n\tconst browserOpened = await openBrowser(\n\t\tauthorization.verificationUriComplete,\n\t);\n\tonVerification({\n\t\tbrowserOpened,\n\t\tuserCode: authorization.userCode,\n\t\tverificationUriComplete: authorization.verificationUriComplete,\n\t});\n\n\tconst deadline = now().getTime() + authorization.expiresIn * 1000;\n\tlet intervalMs = authorization.interval * 1000;\n\twhile (now().getTime() < deadline) {\n\t\tawait sleep(intervalMs);\n\t\tconst response = await postJson(\n\t\t\tfetchImplementation,\n\t\t\t`${baseUrl}/api/cli-auth/token`,\n\t\t\t{ codeVerifier: pkce.verifier, deviceCode: authorization.deviceCode },\n\t\t);\n\t\tconst payload = await readJson(response);\n\t\tif (response.ok) {\n\t\t\tconst issued = tokenResponseSchema.parse(payload);\n\t\t\tconst credentials = toStoredCredentials(issued, baseUrl, now());\n\t\t\tawait persistLoginCredentials({\n\t\t\t\tstore,\n\t\t\t\tcredentials,\n\t\t\t\tbaseUrl,\n\t\t\t\tfetchImplementation,\n\t\t\t});\n\t\t\treturn credentials;\n\t\t}\n\t\tconst error = deviceTokenErrorSchema.safeParse(payload);\n\t\tif (!error.success) {\n\t\t\tthrow new Error(\n\t\t\t\t`CLI authentication failed with HTTP ${response.status}.`,\n\t\t\t);\n\t\t}\n\t\tintervalMs = nextPollIntervalMs(error.data.error, intervalMs);\n\t}\n\tthrow new Error(\"CLI authentication expired. Run auth login again.\");\n};\n\nconst revokeIssuedCredentials = async (\n\tfetchImplementation: FetchLike,\n\tapiBaseUrl: string,\n\tcredentials: StoredCliCredentials,\n): Promise<boolean> => {\n\ttry {\n\t\tconst response = await postJson(\n\t\t\tfetchImplementation,\n\t\t\t`${normalizeCliAuthIssuer(apiBaseUrl)}/api/cli-auth/revoke`,\n\t\t\t{ refreshToken: credentials.refreshToken },\n\t\t\t{ signal: AbortSignal.timeout(refreshRequestTimeoutMs) },\n\t\t);\n\t\treturn response.ok;\n\t} catch {\n\t\treturn false;\n\t}\n};\n\nconst restoreLoginSnapshot = async (\n\tstore: CliCredentialStore,\n\tcredentials: StoredCliCredentials,\n\tcurrent: StoredCliCredentials | null,\n\tprior: StoredCliCredentials | null,\n): Promise<boolean> => {\n\tif (isDeepStrictEqual(current, prior)) return true;\n\tif (current !== null && current.refreshToken !== credentials.refreshToken) {\n\t\treturn false;\n\t}\n\tif (prior) await store.set(prior);\n\telse await store.delete();\n\treturn isDeepStrictEqual(await store.get(), prior);\n};\n\nconst removeRefreshedCredentials = async (\n\tstore: CliCredentialStore,\n\tcurrent: StoredCliCredentials | null,\n): Promise<boolean> => {\n\tif (current) await store.delete();\n\treturn (await store.get()) === null;\n};\n\nconst restoreLocalCredentials = async ({\n\tstore,\n\tcredentials,\n\tphase,\n\tprior,\n}: {\n\tstore: CliCredentialStore;\n\tcredentials: StoredCliCredentials;\n\tphase: \"login\" | \"refresh\";\n\tprior?: StoredCliCredentials | null;\n}): Promise<boolean> => {\n\ttry {\n\t\tconst current = await store.get();\n\t\tif (phase === \"login\" && prior !== undefined) {\n\t\t\treturn await restoreLoginSnapshot(store, credentials, current, prior);\n\t\t}\n\t\tif (\n\t\t\tphase === \"refresh\" &&\n\t\t\t(!current ||\n\t\t\t\tcurrent.refreshToken === credentials.refreshToken ||\n\t\t\t\tcurrent.refreshToken === prior?.refreshToken)\n\t\t) {\n\t\t\treturn await removeRefreshedCredentials(store, current);\n\t\t}\n\t} catch {\n\t\t/* The backend may still be unavailable. */\n\t}\n\treturn false;\n};\n\n// This operation runs under the credential lock. On login, restore only the\n// snapshot read under that lock. A rotated refresh token can NEVER be restored:\n// its predecessor has been consumed, so remove it to prevent a replay.\nconst persistIssuedCredentials = async ({\n\tstore,\n\tcredentials,\n\tprevious,\n\tapiBaseUrl,\n\tfetch: fetchImplementation,\n\tphase,\n}: {\n\tstore: CliCredentialStore;\n\tcredentials: StoredCliCredentials;\n\tprevious?: StoredCliCredentials | null;\n\tapiBaseUrl: string;\n\tfetch: FetchLike;\n\tphase: \"login\" | \"refresh\";\n}): Promise<void> => {\n\tlet prior = previous;\n\ttry {\n\t\tif (phase === \"login\") prior = await store.get();\n\t\tawait store.set(credentials);\n\t\tconst saved = await store.get();\n\t\tif (!isDeepStrictEqual(saved, credentials))\n\t\t\tthrow new Error(\"Credential write could not be verified\");\n\t\treturn;\n\t} catch {\n\t\tconst remoteRevoked = await revokeIssuedCredentials(\n\t\t\tfetchImplementation,\n\t\t\tapiBaseUrl,\n\t\t\tcredentials,\n\t\t);\n\t\tconst localRestored = await restoreLocalCredentials({\n\t\t\tstore,\n\t\t\tcredentials,\n\t\t\tphase,\n\t\t\tprior,\n\t\t});\n\t\tthrow new CliCredentialPersistenceError(\n\t\t\tremoteRevoked,\n\t\t\tlocalRestored,\n\t\t\tphase,\n\t\t);\n\t}\n};\n\nconst refreshes = new WeakMap<CliCredentialStore, Promise<string>>();\nconst refreshRequestTimeoutMs = 30_000;\n\nconst isInvalidGrantResponse = (payload: unknown): boolean => {\n\tconst parsed = deviceTokenErrorSchema.safeParse(payload);\n\treturn parsed.success && parsed.data.error === \"invalid_grant\";\n};\n\nconst readJsonOrNull = async (response: Response): Promise<unknown | null> => {\n\ttry {\n\t\treturn await response.json();\n\t} catch {\n\t\treturn null;\n\t}\n};\n\nconst deleteInvalidCredentials = async (\n\tstore: CliCredentialStore,\n\tcredentials: StoredCliCredentials,\n): Promise<void> => {\n\tconst current = await store.get();\n\tif (!current) return;\n\tif (\n\t\tcurrent.issuer === credentials.issuer &&\n\t\tcurrent.refreshToken === credentials.refreshToken\n\t) {\n\t\tawait store.delete();\n\t}\n};\n\nconst refreshAccessToken = async ({\n\tapiBaseUrl,\n\tcredentials,\n\tfetch: fetchImplementation,\n\tnow,\n\tstore,\n}: {\n\tapiBaseUrl: string;\n\tcredentials: StoredCliCredentials;\n\tfetch: FetchLike;\n\tnow: () => Date;\n\tstore: CliCredentialStore;\n}): Promise<string> => {\n\tassertCredentialIssuer(credentials, apiBaseUrl);\n\tlet response: Response;\n\ttry {\n\t\tresponse = await postJson(\n\t\t\tfetchImplementation,\n\t\t\t`${normalizeCliAuthIssuer(apiBaseUrl)}/api/cli-auth/refresh`,\n\t\t\t{ refreshToken: credentials.refreshToken },\n\t\t\t{ signal: AbortSignal.timeout(refreshRequestTimeoutMs) },\n\t\t);\n\t} catch {\n\t\tthrow new Error(\n\t\t\t\"Unable to refresh the CLI session because the API could not be reached. Credentials were kept; retry the command.\",\n\t\t);\n\t}\n\tif (!response.ok) {\n\t\tconst payload = await readJsonOrNull(response);\n\t\tif (isInvalidGrantResponse(payload)) {\n\t\t\tawait deleteInvalidCredentials(store, credentials);\n\t\t\tthrow new Error(\n\t\t\t\t\"The CLI session expired or was revoked. Run auth login again.\",\n\t\t\t);\n\t\t}\n\t\tthrow new Error(\n\t\t\t`Unable to refresh the CLI session (HTTP ${response.status}). Credentials were kept; retry the command.`,\n\t\t);\n\t}\n\tconst payload = await readJsonOrNull(response);\n\tif (payload === null) {\n\t\tthrow new Error(\n\t\t\t\"Unable to refresh the CLI session because the API returned malformed JSON. Credentials were kept; retry the command.\",\n\t\t);\n\t}\n\tlet issued: ReturnType<typeof tokenResponseSchema.parse>;\n\ttry {\n\t\tissued = tokenResponseSchema.parse(payload);\n\t} catch {\n\t\tthrow new Error(\n\t\t\t\"Unable to refresh the CLI session because the API returned invalid credentials. Credentials were kept; retry the command.\",\n\t\t);\n\t}\n\tconst stored = toStoredCredentials(\n\t\tissued,\n\t\tnormalizeCliAuthIssuer(apiBaseUrl),\n\t\tnow(),\n\t);\n\tawait persistIssuedCredentials({\n\t\tstore,\n\t\tcredentials: stored,\n\t\tprevious: credentials,\n\t\tapiBaseUrl,\n\t\tfetch: fetchImplementation,\n\t\tphase: \"refresh\",\n\t});\n\treturn stored.accessToken;\n};\n\nconst refreshWithCurrentCredentials = async ({\n\tapiBaseUrl,\n\tfetch: fetchImplementation,\n\tnow,\n\tstore,\n}: {\n\tapiBaseUrl: string;\n\tfetch: FetchLike;\n\tnow: () => Date;\n\tstore: CliCredentialStore;\n}): Promise<string> => {\n\tconst credentials = await store.get();\n\tif (!credentials) throw new Error(\"Not authenticated. Run auth login first.\");\n\tassertCredentialIssuer(credentials, apiBaseUrl);\n\tif (Date.parse(credentials.accessTokenExpiresAt) - now().getTime() > 60_000) {\n\t\treturn credentials.accessToken;\n\t}\n\treturn refreshAccessToken({\n\t\tapiBaseUrl,\n\t\tcredentials,\n\t\tfetch: fetchImplementation,\n\t\tnow,\n\t\tstore,\n\t});\n};\n\nexport const getAuthenticatedAccessToken = async ({\n\tapiBaseUrl,\n\tfetch: fetchImplementation = globalThis.fetch,\n\tnow = () => new Date(),\n\tstore,\n}: {\n\tapiBaseUrl: string;\n\tfetch?: FetchLike;\n\tnow?: () => Date;\n\tstore: CliCredentialStore;\n}): Promise<string> => {\n\tconst credentials = await store.get();\n\tif (!credentials) throw new Error(\"Not authenticated. Run auth login first.\");\n\tassertCredentialIssuer(credentials, apiBaseUrl);\n\tif (Date.parse(credentials.accessTokenExpiresAt) - now().getTime() > 60_000) {\n\t\treturn credentials.accessToken;\n\t}\n\tconst existing = refreshes.get(store);\n\tif (existing) return existing;\n\tconst refreshOperation = () =>\n\t\twithCredentialLock(store, () =>\n\t\t\trefreshWithCurrentCredentials({\n\t\t\t\tapiBaseUrl,\n\t\t\t\tfetch: fetchImplementation,\n\t\t\t\tnow,\n\t\t\t\tstore,\n\t\t\t}),\n\t\t);\n\tconst refresh = refreshOperation().finally(() => refreshes.delete(store));\n\trefreshes.set(store, refresh);\n\treturn refresh;\n};\n\nexport const logoutCliSession = async ({\n\tapiBaseUrl,\n\tfetch: fetchImplementation = globalThis.fetch,\n\tstore,\n}: {\n\tapiBaseUrl: string;\n\tfetch?: FetchLike;\n\tstore: CliCredentialStore;\n}): Promise<{ remoteRevoked: boolean }> => {\n\tconst issuer = normalizeCliAuthIssuer(apiBaseUrl);\n\treturn withCredentialLock(store, async () => {\n\t\tconst credentials = await store.get();\n\t\tlet remoteRevoked = credentials === null;\n\t\tif (credentials) {\n\t\t\ttry {\n\t\t\t\tassertCredentialIssuer(credentials, apiBaseUrl);\n\t\t\t\tconst response = await postJson(\n\t\t\t\t\tfetchImplementation,\n\t\t\t\t\t`${issuer}/api/cli-auth/revoke`,\n\t\t\t\t\t{ refreshToken: credentials.refreshToken },\n\t\t\t\t\t{ signal: AbortSignal.timeout(refreshRequestTimeoutMs) },\n\t\t\t\t);\n\t\t\t\tremoteRevoked = response.ok;\n\t\t\t} catch {\n\t\t\t\tremoteRevoked = false;\n\t\t\t}\n\t\t}\n\t\tawait store.delete();\n\t\treturn { remoteRevoked };\n\t});\n};\n", "import { readFileSync } from \"node:fs\";\nimport type { RouterInputs } from \"@go-labs/budget-builder-api\";\nimport {\n\tINVENTORY_SORT_IDS,\n\tITEM_CATEGORY_SORT_IDS,\n} from \"@go-labs/budget-builder-utils/data-table-sort-keys\";\nimport { ChartTimeFrame } from \"@go-labs/budget-builder-utils/filter-enums\";\nimport {\n\ttype CliCredentialStore,\n\tcreateBunCredentialStore,\n\tgetAuthenticatedAccessToken,\n\tgetCliStorageError,\n\tisCliCredentialForIssuer,\n\tloginWithBrowser,\n\tlogoutCliSession,\n\tresolveCliCredentialAccount,\n} from \"@go-labs/cli-auth/client\";\nimport {\n\tBUDGET_BUILDER_API_BASE_URL,\n\tconfigureBudgetBuilderAccessToken,\n\tconfigureBudgetBuilderApiBaseUrl,\n\tDEFAULT_BUDGET_BUILDER_API_BASE_URL,\n} from \"@go-labs-sg/bb/api-client\";\nimport {\n\tAttachmentType,\n\tInboundProcessingMode,\n\tSupplierQuotationFileRole,\n} from \"@go-labs-sg/bb/prisma-enums\";\n\ntype GetAllBudgetsInput = RouterInputs[\"budget\"][\"getAllBudgets\"];\ntype CustomerInvoiceListInput = RouterInputs[\"customerInvoice\"][\"list\"];\ntype SupplierListInput = RouterInputs[\"supplier\"][\"getSuppliers\"];\ntype CompanyListInput = RouterInputs[\"company\"][\"getCompanies\"];\ntype CompanyCountInput = RouterInputs[\"company\"][\"getCompanyCounts\"];\ntype ProjectListInput = RouterInputs[\"project\"][\"getAllProjects\"];\ntype ProjectCountInput = RouterInputs[\"project\"][\"getProjectCounts\"];\ntype SupplierListSort = NonNullable<SupplierListInput[\"sort\"]>;\ntype SupplierSortId = SupplierListSort[number][\"id\"];\n\nimport {\n\tconsumeCliQuietFlags,\n\tlogCliAction,\n\tsanitizeFlagsForTrace,\n\tsetCliQuiet,\n\tshouldLogCliActions,\n} from \"@go-labs-sg/bb/cli-trace\";\nimport {\n\taddBudgetItems,\n\tapproveBill,\n\tapproveBudget,\n\tapproveCustomerInvoice,\n\tapproveQuotation,\n\tapproveSupplier,\n\tapproveUnavailableItemException,\n\tarchiveItemsByIds,\n\tcheckCustomerInvoiceReadiness,\n\tcheckProjectReconciliation,\n\tcleanupStagedBillAttachments,\n\tcleanupStagedQuotationAttachments,\n\tcompleteProject,\n\tcountBills,\n\tcountBudgets,\n\tcountCompanies,\n\tcountCustomerInvoices,\n\tcountErrors,\n\tcountInboundSources,\n\tcountInboundSubmissions,\n\tcountIntegrationOperations,\n\tcountItemCategories,\n\tcountItems,\n\tcountProjectHubs,\n\tcountProjects,\n\tcountQuotations,\n\tcountSupplierAnalytics,\n\tcountSuppliers,\n\tcountUsers,\n\tcreateApiKeyForUser,\n\tcreateBillApproval,\n\tcreateBillFromPayload,\n\tcreateBudgetApproval,\n\tcreateBudgetCategory,\n\tcreateBudgetFromPayload,\n\tcreateCompany,\n\tcreateContactPersonFromPayload,\n\tcreateCustomerInvoice,\n\tcreateEstimate,\n\tcreateInboundSource,\n\tcreateItemCategory,\n\tcreateItemFromPayload,\n\tcreatePlaceholderBillForBudgetItem,\n\tcreateProject,\n\tcreateQuotationFromPayload,\n\tcreateSupplierCertification,\n\tcreateSupplierFromPayload,\n\tcreateSupplierPaymentMethod,\n\tcreateSupplierRoleOption,\n\tcreateSupplierTagOption,\n\tcreateUser,\n\tcreateWebhookEndpoint,\n\tdeleteBillById,\n\tdeleteBudgetById,\n\tdeleteBudgetCategory,\n\tdeleteBudgetCommission,\n\tdeleteBudgetDiscount,\n\tdeleteCompanyById,\n\tdeleteCustomerInvoice,\n\tdeleteItemById,\n\tdeleteItemCategoriesByIds,\n\tdeleteProjectById,\n\tdeleteQuotationById,\n\tdeleteSuppliersByIds,\n\tdeleteWebhookEndpoint,\n\tdiscardCreatingCustomerInvoice,\n\tdownloadCustomerInvoicePdf,\n\tdownloadQuotationPdf,\n\tgetApprovedBudgets,\n\tgetBillApprovals,\n\tgetBillAttachments,\n\tgetBillDetails,\n\tgetBillLineItems,\n\tgetBillPayment,\n\tgetBudget,\n\tgetBudgetCategories,\n\tgetBudgetCategoryBenchmarks,\n\tgetBudgetDetails,\n\tgetBudgetItemsOnly,\n\tgetBudgetVersions,\n\tgetCompany,\n\tgetCompanyQuickBooksSyncStatus,\n\tgetCustomerInvoice,\n\tgetCustomerInvoiceApprovals,\n\tgetCustomerInvoiceEmailContext,\n\tgetCustomerInvoiceHistory,\n\tgetCustomerInvoiceInvoices,\n\tgetCustomerInvoiceLines,\n\tgetCustomerInvoicePayments,\n\tgetDashboard,\n\tgetError,\n\tgetErrorMetrics,\n\tgetEstimatePerformance,\n\tgetFinancialOverview,\n\tgetInboundSource,\n\tgetInboundSubmission,\n\tgetIntegrationOperation,\n\tgetItem,\n\tgetItemPricingHistory,\n\tgetItemQuickBooksSyncStatus,\n\tgetMonthlyMetrics,\n\tgetProject,\n\tgetProjectHubStatus,\n\tgetQuotationDetails,\n\tgetQuotationLineItems,\n\tgetRecentErrors,\n\tgetSupplierAnalytics,\n\tgetSupplierDetails,\n\tgetSupplierItems,\n\tgetSupplierOverview,\n\tgetSupplierPricingHistory,\n\tgetSupplierUsage,\n\tgetSystemOverview,\n\tgetUserPerformance,\n\tgetWebhookDelivery,\n\tgetWebhookEndpoint,\n\timportQboCustomerInvoice,\n\timportQuickBooksProjectId,\n\tlinkBillQuotations,\n\tlistApiKeysForUser,\n\tlistApprovals,\n\tlistAvailableQboCustomerInvoices,\n\tlistBills,\n\tlistBudgets,\n\tlistCompanies,\n\tlistContacts,\n\tlistCustomerInvoices,\n\tlistEligibleCustomerInvoiceBudgets,\n\tlistExternalBillPaymentAccounts,\n\tlistInboundSources,\n\tlistInboundSubmissions,\n\tlistIntegrationOperations,\n\tlistItemCategories,\n\tlistItems,\n\tlistProjectHubs,\n\tlistProjects,\n\tlistQuotations,\n\tlistSuppliers,\n\tlistUsers,\n\tlistWebhookDeliveries,\n\tlistWebhookEndpoints,\n\tlistWebhookEventTypes,\n\tmarkBudgetWonWithProof,\n\tmarkCustomerInvoiceSentExternally,\n\tpatchBillInvoiceNumber,\n\tpatchBillPayment,\n\tpreviewCustomerInvoiceAmount,\n\tpreviewQboCustomerInvoice,\n\treactivateSuppliersByIds,\n\treconcileProject,\n\treconcileResourceOperation,\n\trecordExternalBillPayment,\n\trefreshExternalBillPaymentAccounts,\n\trejectBill,\n\trejectBudget,\n\trejectCustomerInvoice,\n\trejectQuotation,\n\trejectSupplier,\n\tremoveBudgetItem,\n\trenameBudgetVersion,\n\treorderBudgetItemsCli,\n\treplaceBudgetItem,\n\treplayWebhookDelivery,\n\trestoreBudgetVersion,\n\tresubmitCustomerInvoice,\n\tretryIntegrationOperation,\n\treuseExistingCompany,\n\trevokeApiKeyForUser,\n\trotateWebhookSecret,\n\tsaveInboundAutomationConfig,\n\tsaveInboundMappingVersion,\n\tsearchExistingCompanies,\n\tsendCustomerInvoiceToContactPersonFromPayload,\n\tsendEstimateToContactPersonFromPayload,\n\tsendWebhookTestEvent,\n\tsetBudgetItemsNotUtilized,\n\tsetupProjectHub,\n\tstageBillAttachmentsFromPaths,\n\tsubmitQuotation,\n\tsyncCustomerInvoice,\n\tsyncProjectHubCommercialDocuments,\n\tupdateBillFromPayload,\n\tupdateBillPaymentEvidenceFromPayload,\n\tupdateBillStatus,\n\tupdateBudgetCategory,\n\tupdateBudgetCommissionFromPayload,\n\tupdateBudgetDiscountFromPayload,\n\tupdateBudgetFromPayload,\n\tupdateBudgetItem,\n\tupdateBudgetItemSupplierCli,\n\tupdateBudgetStatus,\n\tupdateCompanyFromPayload,\n\tupdateContactPersonFromPayload,\n\tupdateCustomerInvoiceDetails,\n\tupdateCustomerInvoiceQboDrift,\n\tupdateInboundProcessing,\n\tupdateInboundSource,\n\tupdateItemCategory,\n\tupdateItemFromPayload,\n\tupdateProjectFromPayload,\n\tupdateProjectStatus,\n\tupdateQuotationFromPayload,\n\tupdateSupplierFromPayload,\n\tupdateWebhookEndpoint,\n\tuploadBillAttachmentFromPath,\n\tuploadBillAttachmentsFromPaths,\n\tuploadBillDocumentsFromPaths,\n\tuploadBudgetAttachmentFromPath,\n\tuploadQuotationAttachmentFromPath,\n\tvalidateBillSelectionFromPayload,\n\tvoidCustomerInvoice,\n\twhoAmI,\n} from \"@go-labs-sg/bb/commands/index\";\nimport { getFlag, parseArgs } from \"@go-labs-sg/bb/parse-args\";\nimport {\n\tbillStatusesForUpdateHelp,\n\tbudgetStatusesForHelp,\n\tisBudgetStatusUpdate,\n\tparseApprovalTypeFlag,\n\tparseBillStatusForUpdate,\n\tparseCommaSeparatedBillStatuses,\n\tparseCommaSeparatedBudgetStatuses,\n\tparseCommaSeparatedCustomerInvoiceStatuses,\n\tparseCommaSeparatedIds,\n\tparseCommaSeparatedIntegrationOperationStatuses,\n\tparseCommaSeparatedProjectStatuses,\n\tparseCommaSeparatedQuotationStatuses,\n\tparseCommaSeparatedSupplierStatuses,\n\tparseOptionalBillListSortBy,\n\tparseOptionalBillListSortDir,\n\tparseOptionalDashboardRole,\n\tparseOptionalDeals,\n\tparseOptionalErrorSeverity,\n\tparseOptionalErrorStatus,\n\tparseOptionalExtendedProjectStatus,\n\tparseOptionalFinancialRole,\n\tparseOptionalIsoDateFlag,\n\tparseOptionalProjectHubSortBy,\n\tparseOptionalSupplierAnalyticsTimeFrame,\n\tparseOptionalTimeFrame,\n\tparseProjectStatusForUpdate,\n\tparseUserRole,\n\tprojectStatusesForHelp,\n\tuserRolesForHelp,\n} from \"@go-labs-sg/bb/parse-cli-enums\";\nimport {\n\tparseJsonFlag,\n\tparseJsonObjectFlag,\n\tparseOptionalNumber as parseOptNum,\n} from \"@go-labs-sg/bb/parse-json-flag\";\nimport { parseCompanyBillingEmails } from \"@go-labs-sg/bb/parse-mutation-payload\";\nimport { ApprovalStatus, ProjectStatus } from \"@go-labs-sg/bb/prisma-enums\";\nimport {\n\ttype CompletionShell,\n\tcreateCompletionScript,\n\tcreateHumanHelp,\n\ttype ResolvedCommand,\n\tresolveCommand,\n} from \"@go-labs-sg/bb/registry/index\";\nimport {\n\ttype CliEffectPermissions,\n\ttype CliRuntime,\n\tCliRuntimeError,\n\tclearActiveCliSession,\n\tconfirmCurrentCommand,\n\tcreateProcessRuntime,\n\temitCommandError,\n\temitCommandResult,\n\tsetActiveCliSession,\n} from \"@go-labs-sg/bb/runtime/index\";\n\nconst SUPPLIER_ANALYTICS_SORT_IDS = [\n\t\"name\",\n\t\"gstRegistered\",\n\t\"status\",\n\t\"phone\",\n\t\"email\",\n\t\"updatedAt\",\n\t\"createdAt\",\n] as const;\n\nfunction parsePositiveIntFlag(\n\tvalue: string | number | undefined,\n\tflagName: string,\n): number | undefined {\n\tif (value === undefined) return undefined;\n\tconst parsed = Number.parseInt(String(value), 10);\n\tif (!Number.isFinite(parsed) || parsed <= 0) {\n\t\tthrow new Error(`${flagName} must be a positive integer.`);\n\t}\n\treturn parsed;\n}\n\nconst COMPANY_SORT_FIELDS = [\"name\", \"createdAt\"] as const;\nconst COMPANY_SORT_DIRECTIONS = [\"asc\", \"desc\"] as const;\nconst COMPANY_PAGE_FLAGS = [\n\t\"page\",\n\t\"perPage\",\n\t\"pageSize\",\n\t\"page-size\",\n\t\"per-page\",\n\t\"page_size\",\n\t\"per_page\",\n] as const;\n\nconst rejectBareFlag = (\n\tflags: Record<string, string | true>,\n\tkey: string,\n): void => {\n\tif (flags[key] === true) {\n\t\tthrow new Error(`--${key} requires a value.`);\n\t}\n};\n\nconst rejectCompanyPageFlags = (\n\tflags: Record<string, string | true>,\n\tcommand: \"list\" | \"count\",\n): void => {\n\tfor (const key of COMPANY_PAGE_FLAGS) {\n\t\tif (flags[key] !== undefined) {\n\t\t\tthrow new Error(\n\t\t\t\t`--${key} is not supported by company ${command}; use --limit and --cursor for list or company count for totals.`,\n\t\t\t);\n\t\t}\n\t}\n};\n\nconst parseCompanyLimit = (\n\tvalue: string | number | undefined,\n): CompanyListInput[\"limit\"] => {\n\tif (value === undefined) return 20;\n\tconst parsed = Number(String(value));\n\tif (!Number.isInteger(parsed) || parsed < 1 || parsed > 100) {\n\t\tthrow new Error(\"--limit must be an integer from 1 to 100.\");\n\t}\n\treturn parsed;\n};\n\nconst parseCompanySortBy = (\n\tvalue: string | undefined,\n): CompanyListInput[\"sortBy\"] => {\n\tif (value === undefined) return \"createdAt\";\n\tif (!(COMPANY_SORT_FIELDS as readonly string[]).includes(value)) {\n\t\tthrow new Error(\n\t\t\t`Invalid --sortBy \"${value}\". Use one of: ${COMPANY_SORT_FIELDS.join(\", \")}.`,\n\t\t);\n\t}\n\treturn value as CompanyListInput[\"sortBy\"];\n};\n\nconst parseCompanySortDir = (\n\tvalue: string | undefined,\n): CompanyListInput[\"sortDir\"] => {\n\tif (value === undefined) return \"desc\";\n\tif (!(COMPANY_SORT_DIRECTIONS as readonly string[]).includes(value)) {\n\t\tthrow new Error(\n\t\t\t`Invalid --sortDir \"${value}\". Use one of: ${COMPANY_SORT_DIRECTIONS.join(\", \")}.`,\n\t\t);\n\t}\n\treturn value as CompanyListInput[\"sortDir\"];\n};\n\nconst parseCompanyDirection = (\n\tvalue: string | undefined,\n): CompanyListInput[\"direction\"] => {\n\tif (value === undefined) return \"forward\";\n\tif (value !== \"forward\" && value !== \"backward\") {\n\t\tthrow new Error('--direction must be \"forward\" or \"backward\".');\n\t}\n\treturn value;\n};\n\nconst parseCompanyListFlags = (\n\tflags: Record<string, string | true>,\n): CompanyListInput => {\n\trejectCompanyPageFlags(flags, \"list\");\n\tfor (const key of [\n\t\t\"name\",\n\t\t\"createdBy\",\n\t\t\"createdByIds\",\n\t\t\"active\",\n\t\t\"limit\",\n\t\t\"cursor\",\n\t\t\"direction\",\n\t\t\"sortBy\",\n\t\t\"sortDir\",\n\t]) {\n\t\trejectBareFlag(flags, key);\n\t}\n\n\tconst cursor = getFlag(flags, \"cursor\");\n\tconst direction = parseCompanyDirection(getFlag(flags, \"direction\"));\n\tif (direction === \"backward\" && cursor === undefined) {\n\t\tthrow new Error(\"--direction backward requires --cursor <token>.\");\n\t}\n\tif (cursor === \"\") throw new Error(\"--cursor requires a non-empty token.\");\n\n\treturn {\n\t\tname: getFlag(flags, \"name\"),\n\t\tcreatedBy: getFlag(flags, \"createdBy\"),\n\t\tcreatedByIds: parseCommaSeparatedIds(getFlag(flags, \"createdByIds\")),\n\t\tactive: parseOptionalBoolFlag(flags, \"active\"),\n\t\tlimit: parseCompanyLimit(getFlag(flags, \"limit\")),\n\t\tcursor,\n\t\tdirection,\n\t\tsortBy: parseCompanySortBy(getFlag(flags, \"sortBy\")),\n\t\tsortDir: parseCompanySortDir(getFlag(flags, \"sortDir\")),\n\t};\n};\n\nconst parseCompanyCountFlags = (\n\tflags: Record<string, string | true>,\n): CompanyCountInput => {\n\trejectCompanyPageFlags(flags, \"count\");\n\tfor (const key of [\n\t\t\"name\",\n\t\t\"createdBy\",\n\t\t\"createdByIds\",\n\t\t\"active\",\n\t\t\"limit\",\n\t\t\"cursor\",\n\t\t\"direction\",\n\t\t\"sortBy\",\n\t\t\"sortDir\",\n\t]) {\n\t\trejectBareFlag(flags, key);\n\t}\n\tif (\n\t\tflags.limit !== undefined ||\n\t\tflags.cursor !== undefined ||\n\t\tflags.direction !== undefined\n\t) {\n\t\tthrow new Error(\"company count does not accept list pagination flags.\");\n\t}\n\tif (flags.sortBy !== undefined || flags.sortDir !== undefined) {\n\t\tthrow new Error(\"company count does not accept list sorting flags.\");\n\t}\n\treturn {\n\t\tname: getFlag(flags, \"name\"),\n\t\tcreatedBy: getFlag(flags, \"createdBy\"),\n\t\tcreatedByIds: parseCommaSeparatedIds(getFlag(flags, \"createdByIds\")),\n\t\tactive: parseOptionalBoolFlag(flags, \"active\"),\n\t};\n};\n\nconst PROJECT_SORT_FIELDS = [\n\t\"name\",\n\t\"createdAt\",\n\t\"status\",\n\t\"companyName\",\n\t\"wonAt\",\n] as const;\nconst PROJECT_SORT_DIRECTIONS = [\"asc\", \"desc\"] as const;\nconst PROJECT_PAGE_FLAGS = [\n\t\"page\",\n\t\"perPage\",\n\t\"pageSize\",\n\t\"page-size\",\n\t\"per-page\",\n\t\"page_size\",\n\t\"per_page\",\n] as const;\n\nconst rejectProjectPageFlags = (\n\tflags: Record<string, string | true>,\n\tcommand: \"list\" | \"count\",\n): void => {\n\tfor (const key of PROJECT_PAGE_FLAGS) {\n\t\tif (flags[key] !== undefined) {\n\t\t\tthrow new Error(\n\t\t\t\t`--${key} is not supported by project ${command}; use --limit and --cursor for list or project count for totals.`,\n\t\t\t);\n\t\t}\n\t}\n};\n\nconst parseProjectLimit = (\n\tvalue: string | number | undefined,\n): ProjectListInput[\"limit\"] => {\n\tif (value === undefined) return 20;\n\tconst parsed = Number(String(value));\n\tif (!Number.isInteger(parsed) || parsed < 1 || parsed > 100) {\n\t\tthrow new Error(\"--limit must be an integer from 1 to 100.\");\n\t}\n\treturn parsed;\n};\n\nconst parseProjectSortBy = (\n\tvalue: string | undefined,\n): ProjectListInput[\"sortBy\"] => {\n\tif (value === undefined) return \"createdAt\";\n\tif (!(PROJECT_SORT_FIELDS as readonly string[]).includes(value)) {\n\t\tthrow new Error(\n\t\t\t`Invalid --sortBy \"${value}\". Use one of: ${PROJECT_SORT_FIELDS.join(\", \")}.`,\n\t\t);\n\t}\n\treturn value as ProjectListInput[\"sortBy\"];\n};\n\nconst parseProjectSortDir = (\n\tvalue: string | undefined,\n): ProjectListInput[\"sortDir\"] => {\n\tif (value === undefined) return \"desc\";\n\tif (!(PROJECT_SORT_DIRECTIONS as readonly string[]).includes(value)) {\n\t\tthrow new Error(\n\t\t\t`Invalid --sortDir \"${value}\". Use one of: ${PROJECT_SORT_DIRECTIONS.join(\", \")}.`,\n\t\t);\n\t}\n\treturn value as ProjectListInput[\"sortDir\"];\n};\n\nconst parseProjectWonWithinDays = (\n\tvalue: string | undefined,\n): ProjectListInput[\"wonWithinDays\"] => {\n\tif (value === undefined) return undefined;\n\tconst parsed = Number(value);\n\tif (!Number.isInteger(parsed) || parsed < 1 || parsed > 3650) {\n\t\tthrow new Error(\"--wonWithinDays must be an integer from 1 to 3650.\");\n\t}\n\treturn parsed;\n};\n\nconst parseProjectDirection = (\n\tvalue: string | undefined,\n): ProjectListInput[\"direction\"] => {\n\tif (value === undefined) return \"forward\";\n\tif (value !== \"forward\" && value !== \"backward\") {\n\t\tthrow new Error('--direction must be \"forward\" or \"backward\".');\n\t}\n\treturn value;\n};\n\nconst parseProjectListFlags = (\n\tflags: Record<string, string | true>,\n): ProjectListInput => {\n\trejectProjectPageFlags(flags, \"list\");\n\tfor (const key of [\n\t\t\"companyId\",\n\t\t\"name\",\n\t\t\"status\",\n\t\t\"statuses\",\n\t\t\"active\",\n\t\t\"wonFrom\",\n\t\t\"wonTo\",\n\t\t\"wonWithinDays\",\n\t\t\"limit\",\n\t\t\"cursor\",\n\t\t\"direction\",\n\t\t\"sortBy\",\n\t\t\"sortDir\",\n\t]) {\n\t\trejectBareFlag(flags, key);\n\t}\n\tconst cursor = getFlag(flags, \"cursor\");\n\tconst direction = parseProjectDirection(getFlag(flags, \"direction\"));\n\tif (direction === \"backward\" && cursor === undefined) {\n\t\tthrow new Error(\"--direction backward requires --cursor <token>.\");\n\t}\n\tif (cursor === \"\") throw new Error(\"--cursor requires a non-empty token.\");\n\treturn {\n\t\tcompanyId: getFlag(flags, \"companyId\"),\n\t\tname: getFlag(flags, \"name\"),\n\t\tstatus: parseOptionalExtendedProjectStatus(getFlag(flags, \"status\")),\n\t\tstatuses: parseCommaSeparatedProjectStatuses(getFlag(flags, \"statuses\")),\n\t\tactive: parseOptionalBoolFlag(flags, \"active\"),\n\t\twonFrom: parseOptionalIsoDateFlag(getFlag(flags, \"wonFrom\"), \"--wonFrom\"),\n\t\twonTo: parseOptionalIsoDateFlag(getFlag(flags, \"wonTo\"), \"--wonTo\", {\n\t\t\tendOfDay: true,\n\t\t}),\n\t\twonWithinDays: parseProjectWonWithinDays(getFlag(flags, \"wonWithinDays\")),\n\t\tlimit: parseProjectLimit(getFlag(flags, \"limit\")),\n\t\tcursor,\n\t\tdirection,\n\t\tsortBy: parseProjectSortBy(getFlag(flags, \"sortBy\")),\n\t\tsortDir: parseProjectSortDir(getFlag(flags, \"sortDir\")),\n\t};\n};\n\nconst parseProjectCountFlags = (\n\tflags: Record<string, string | true>,\n): ProjectCountInput => {\n\trejectProjectPageFlags(flags, \"count\");\n\tfor (const key of [\n\t\t\"companyId\",\n\t\t\"name\",\n\t\t\"status\",\n\t\t\"statuses\",\n\t\t\"active\",\n\t\t\"wonFrom\",\n\t\t\"wonTo\",\n\t\t\"wonWithinDays\",\n\t\t\"limit\",\n\t\t\"cursor\",\n\t\t\"direction\",\n\t\t\"sortBy\",\n\t\t\"sortDir\",\n\t]) {\n\t\trejectBareFlag(flags, key);\n\t}\n\tif (\n\t\tflags.limit !== undefined ||\n\t\tflags.cursor !== undefined ||\n\t\tflags.direction !== undefined\n\t) {\n\t\tthrow new Error(\"project count does not accept list pagination flags.\");\n\t}\n\tif (flags.sortBy !== undefined || flags.sortDir !== undefined) {\n\t\tthrow new Error(\"project count does not accept list sorting flags.\");\n\t}\n\treturn {\n\t\tcompanyId: getFlag(flags, \"companyId\"),\n\t\tname: getFlag(flags, \"name\"),\n\t\tstatus: parseOptionalExtendedProjectStatus(getFlag(flags, \"status\")),\n\t\tstatuses: parseCommaSeparatedProjectStatuses(getFlag(flags, \"statuses\")),\n\t\tactive: parseOptionalBoolFlag(flags, \"active\"),\n\t\twonFrom: parseOptionalIsoDateFlag(getFlag(flags, \"wonFrom\"), \"--wonFrom\"),\n\t\twonTo: parseOptionalIsoDateFlag(getFlag(flags, \"wonTo\"), \"--wonTo\", {\n\t\t\tendOfDay: true,\n\t\t}),\n\t\twonWithinDays: parseProjectWonWithinDays(getFlag(flags, \"wonWithinDays\")),\n\t};\n};\n\nfunction parseOptionalBoolFlag(\n\tflags: Record<string, string | true>,\n\tkey: string,\n): boolean | undefined {\n\tconst v = flags[key];\n\tif (v === undefined || v === true) return undefined;\n\tconst s = String(v).toLowerCase();\n\tif (s === \"true\" || s === \"1\") return true;\n\tif (s === \"false\" || s === \"0\") return false;\n\tthrow new Error(`--${key} must be true or false.`);\n}\n\nfunction parseBudgetActiveFlag(\n\tflags: Record<string, string | true>,\n): GetAllBudgetsInput[\"active\"] {\n\tconst raw = flags.active;\n\tif (raw === undefined) return undefined;\n\tif (raw === true) {\n\t\tthrow new Error(\"--active requires true, false, or all.\");\n\t}\n\n\tconst value = String(raw).toLowerCase();\n\tif (value === \"all\") return \"all\";\n\tif (value === \"true\" || value === \"1\") return true;\n\tif (value === \"false\" || value === \"0\") return false;\n\tthrow new Error(\"--active must be true, false, or all.\");\n}\n\nconst CUSTOMER_INVOICE_SORT_FIELDS = [\n\t\"createdAt\",\n\t\"status\",\n\t\"totalInvoiceAmount\",\n\t\"totalNetAmount\",\n\t\"approvalExpiresAt\",\n] as const satisfies readonly CustomerInvoiceListInput[\"sortBy\"][];\n\nfunction parseCustomerInvoiceSortBy(\n\tvalue: string | undefined,\n): CustomerInvoiceListInput[\"sortBy\"] {\n\tif (value === undefined) return \"createdAt\";\n\tif (!(CUSTOMER_INVOICE_SORT_FIELDS as readonly string[]).includes(value)) {\n\t\tthrow new Error(\n\t\t\t`Invalid --sortBy \"${value}\". Use one of: ${CUSTOMER_INVOICE_SORT_FIELDS.join(\", \")}.`,\n\t\t);\n\t}\n\treturn value as CustomerInvoiceListInput[\"sortBy\"];\n}\n\nfunction parseCommercialRejectionProjectStatus(\n\tflags: Record<string, string | true>,\n): typeof ProjectStatus.PITCH | typeof ProjectStatus.LOST | undefined {\n\tconst raw = flags.projectStatusOnCommercialRejection;\n\tif (raw === undefined) return undefined;\n\tif (raw === true) {\n\t\tthrow new Error(\n\t\t\t\"--projectStatusOnCommercialRejection requires PITCH or LOST.\",\n\t\t);\n\t}\n\n\tconst status = String(raw).toUpperCase();\n\tif (status === ProjectStatus.PITCH || status === ProjectStatus.LOST) {\n\t\treturn status;\n\t}\n\n\tthrow new Error(\n\t\t\"--projectStatusOnCommercialRejection must be PITCH or LOST.\",\n\t);\n}\n\nconst rejectRetiredPageFlags = (flags: Record<string, string | true>) => {\n\tfor (const key of PROJECT_PAGE_FLAGS) {\n\t\tif (flags[key] !== undefined)\n\t\t\tthrow new Error(\n\t\t\t\t`--${key} is retired; use --limit/--cursor, or the matching count command for totals.`,\n\t\t\t);\n\t}\n};\n\n/** Shared `<id> [--limit] [--cursor]` parsing for forward-only detail feeds. */\nconst parseDetailFeedPage = (\n\tcommand: string,\n\tidLabel: string,\n\tpositional: readonly string[],\n\tflags: Record<string, string | true>,\n\tmaxLimit: number,\n) => {\n\tconst id = positional[0];\n\tif (!id) throw new Error(`${command} requires ${idLabel}`);\n\trejectRetiredPageFlags(flags);\n\tfor (const key of [\"limit\", \"cursor\"]) rejectBareFlag(flags, key);\n\tif (flags.direction !== undefined)\n\t\tthrow new Error(\n\t\t\t`${command} pages forward only; follow pageInfo.nextCursor with --cursor.`,\n\t\t);\n\tconst cursor = getFlag(flags, \"cursor\");\n\tif (cursor === \"\" || (cursor?.length ?? 0) > 8192)\n\t\tthrow new Error(\n\t\t\t\"--cursor must be a non-empty opaque token of at most 8192 characters.\",\n\t\t);\n\tconst limitFlag = getFlag(flags, \"limit\");\n\tconst limit = limitFlag === undefined ? undefined : Number(limitFlag);\n\tif (\n\t\tlimit !== undefined &&\n\t\t(!Number.isInteger(limit) || limit < 1 || limit > maxLimit)\n\t)\n\t\tthrow new Error(`--limit must be an integer from 1 to ${maxLimit}.`);\n\treturn { id, limit, cursor };\n};\n\nconst parseBillFilterFlags = (flags: Record<string, string | true>) => {\n\tconst statusRaw = getFlag(flags, \"status\");\n\tconst createdByIdsRaw = getFlag(flags, \"createdByIds\");\n\tconst searchRaw = getFlag(flags, \"search\");\n\treturn {\n\t\tprojectId: getFlag(flags, \"projectId\"),\n\t\tbudgetId: getFlag(flags, \"budgetId\"),\n\t\tstatuses: parseCommaSeparatedBillStatuses(\n\t\t\tstatusRaw !== undefined ? String(statusRaw) : undefined,\n\t\t),\n\t\tsearch: searchRaw !== undefined ? String(searchRaw) : undefined,\n\t\tisClaimable: parseOptionalBoolFlag(flags, \"isClaimable\"),\n\t\tcreatedByIds: parseCommaSeparatedIds(\n\t\t\tcreatedByIdsRaw !== undefined ? String(createdByIdsRaw) : undefined,\n\t\t),\n\t};\n};\n\nconst parseQuotationFilterFlags = (flags: Record<string, string | true>) => {\n\tconst createdByRaw =\n\t\tgetFlag(flags, \"createdBy\") ?? getFlag(flags, \"requesterIds\");\n\tconst searchRaw = getFlag(flags, \"search\");\n\treturn {\n\t\tprojectId: getFlag(flags, \"projectId\"),\n\t\tbudgetId: getFlag(flags, \"budgetId\"),\n\t\tsupplierId: getFlag(flags, \"supplierId\"),\n\t\tstatus: parseCommaSeparatedQuotationStatuses(getFlag(flags, \"status\")),\n\t\tcreatedBy: parseCommaSeparatedIds(createdByRaw),\n\t\tsearch:\n\t\t\tsearchRaw !== undefined\n\t\t\t\t? String(searchRaw).trim() || undefined\n\t\t\t\t: undefined,\n\t};\n};\n\nfunction parseListBillsFlags(flags: Record<string, string | true>) {\n\trejectRetiredPageFlags(flags);\n\tfor (const key of [\"limit\", \"cursor\", \"direction\", \"sortBy\", \"sortDir\"])\n\t\trejectBareFlag(flags, key);\n\tconst sortByRaw = getFlag(flags, \"sortBy\");\n\tconst sortDirRaw = getFlag(flags, \"sortDir\");\n\tconst cursor = getFlag(flags, \"cursor\");\n\tif (cursor === \"\" || (cursor?.length ?? 0) > 8192)\n\t\tthrow new Error(\n\t\t\t\"--cursor must be a non-empty opaque token of at most 8192 characters.\",\n\t\t);\n\tconst direction = parseProjectDirection(getFlag(flags, \"direction\"));\n\tif (direction === \"backward\" && !cursor)\n\t\tthrow new Error(\"--direction backward requires --cursor <token>.\");\n\treturn {\n\t\t...parseBillFilterFlags(flags),\n\t\tsortBy: parseOptionalBillListSortBy(\n\t\t\tsortByRaw !== undefined ? String(sortByRaw) : undefined,\n\t\t),\n\t\tsortDir: parseOptionalBillListSortDir(\n\t\t\tsortDirRaw !== undefined ? String(sortDirRaw) : undefined,\n\t\t),\n\t\tlimit: parseProjectLimit(getFlag(flags, \"limit\")),\n\t\tcursor,\n\t\tdirection,\n\t};\n}\n\nfunction parseCountBillsFlags(flags: Record<string, string | true>) {\n\trejectRetiredPageFlags(flags);\n\tfor (const key of [\"limit\", \"cursor\", \"direction\", \"sortBy\", \"sortDir\"]) {\n\t\tif (flags[key] !== undefined)\n\t\t\tthrow new Error(\n\t\t\t\t`bill count does not accept --${key}; totals use filters only.`,\n\t\t\t);\n\t}\n\treturn {\n\t\t...parseBillFilterFlags(flags),\n\t\tincludeMetrics: parseOptionalBoolFlag(flags, \"includeMetrics\") ?? false,\n\t};\n}\n\nconst SUPPLIER_SORT_FIELDS = [\n\t\"createdAt\",\n\t\"updatedAt\",\n\t\"name\",\n\t\"email\",\n\t\"phone\",\n\t\"gstRegistered\",\n\t\"status\",\n\t\"active\",\n] as const satisfies readonly SupplierSortId[];\n\nfunction parseOptionalSupplierSortBy(\n\traw: string | undefined,\n): (typeof SUPPLIER_SORT_FIELDS)[number] | undefined {\n\tif (raw === undefined || raw === \"\") return undefined;\n\tif (!(SUPPLIER_SORT_FIELDS as readonly string[]).includes(raw)) {\n\t\tthrow new Error(\n\t\t\t`Invalid --sortBy \"${raw}\". Use one of: ${SUPPLIER_SORT_FIELDS.join(\", \")}.`,\n\t\t);\n\t}\n\treturn raw as (typeof SUPPLIER_SORT_FIELDS)[number];\n}\n\nconst parseSupplierFilters = (\n\tflags: Record<string, string | true>,\n): RouterInputs[\"supplier\"][\"getSummary\"] => {\n\tfor (const key of [\n\t\t\"name\",\n\t\t\"createdBy\",\n\t\t\"gstRegistered\",\n\t\t\"status\",\n\t\t\"supplierTags\",\n\t\t\"active\",\n\t])\n\t\trejectBareFlag(flags, key);\n\treturn {\n\t\tname: getFlag(flags, \"name\"),\n\t\tcreatedBy: parseCommaSeparatedIds(getFlag(flags, \"createdBy\")),\n\t\tgstRegistered: parseOptionalBoolFlag(flags, \"gstRegistered\") ?? null,\n\t\tstatus: parseCommaSeparatedSupplierStatuses(getFlag(flags, \"status\")),\n\t\tsupplierTags: parseCommaSeparatedIds(getFlag(flags, \"supplierTags\")),\n\t\tactive: parseOptionalBoolFlag(flags, \"active\") ?? true,\n\t};\n};\n\nconst rejectSupplierPageFlags = (flags: Record<string, string | true>) => {\n\tfor (const key of PROJECT_PAGE_FLAGS) {\n\t\tif (flags[key] !== undefined)\n\t\t\tthrow new Error(\n\t\t\t\t`--${key} is retired for suppliers; use --limit/--cursor or supplier count for totals.`,\n\t\t\t);\n\t}\n};\n\nconst parseSupplierListSortEntries = (sortRaw: string): SupplierListSort => {\n\tconst parsed = parseJsonFlag<unknown>(sortRaw, \"--sort\");\n\tif (!Array.isArray(parsed) || parsed.length > 8)\n\t\tthrow new Error(\n\t\t\t\"--sort must be a JSON array of at most eight {id, desc} entries.\",\n\t\t);\n\treturn parsed.map((item: unknown) => {\n\t\tif (\n\t\t\ttypeof item !== \"object\" ||\n\t\t\titem === null ||\n\t\t\t!(\"id\" in item) ||\n\t\t\t!(\"desc\" in item) ||\n\t\t\ttypeof item.id !== \"string\" ||\n\t\t\ttypeof item.desc !== \"boolean\" ||\n\t\t\tObject.keys(item).some((key) => key !== \"id\" && key !== \"desc\")\n\t\t)\n\t\t\tthrow new Error(\"Invalid --sort entry; use {id, desc}.\");\n\t\tconst id = parseOptionalSupplierSortBy(item.id);\n\t\tif (!id) throw new Error(\"Invalid --sort field.\");\n\t\treturn { id, desc: item.desc };\n\t});\n};\n\nconst parseSupplierListSort = (\n\tflags: Record<string, string | true>,\n): SupplierListSort => {\n\tconst sortRaw = getFlag(flags, \"sort\");\n\tif (sortRaw !== undefined) {\n\t\tif (flags.sortBy !== undefined || flags.sortDir !== undefined)\n\t\t\tthrow new Error(\"Use --sort or --sortBy/--sortDir, not both.\");\n\t\treturn parseSupplierListSortEntries(sortRaw);\n\t}\n\tconst sortBy = parseOptionalSupplierSortBy(getFlag(flags, \"sortBy\"));\n\tconst sortDir = parseOptionalBillListSortDir(getFlag(flags, \"sortDir\"));\n\treturn [{ id: sortBy ?? \"createdAt\", desc: (sortDir ?? \"desc\") === \"desc\" }];\n};\n\nconst parseListSuppliersFlags = (\n\tflags: Record<string, string | true>,\n): SupplierListInput => {\n\trejectSupplierPageFlags(flags);\n\tfor (const key of [\n\t\t\"limit\",\n\t\t\"cursor\",\n\t\t\"direction\",\n\t\t\"sort\",\n\t\t\"sortBy\",\n\t\t\"sortDir\",\n\t])\n\t\trejectBareFlag(flags, key);\n\tconst limit =\n\t\tgetFlag(flags, \"limit\") === undefined\n\t\t\t? 10\n\t\t\t: parseProjectLimit(getFlag(flags, \"limit\"));\n\tconst cursor = getFlag(flags, \"cursor\");\n\tif (cursor === \"\" || (cursor?.length ?? 0) > 8192)\n\t\tthrow new Error(\n\t\t\t\"--cursor must be a non-empty opaque token of at most 8192 characters.\",\n\t\t);\n\tconst direction = parseProjectDirection(getFlag(flags, \"direction\"));\n\tif (direction === \"backward\" && !cursor)\n\t\tthrow new Error(\"--direction backward requires --cursor <token>.\");\n\tconst sort = parseSupplierListSort(flags);\n\treturn { ...parseSupplierFilters(flags), limit, cursor, direction, sort };\n};\n\nconst parseCountSuppliersFlags = (\n\tflags: Record<string, string | true>,\n): RouterInputs[\"supplier\"][\"getSummary\"] => {\n\trejectSupplierPageFlags(flags);\n\tfor (const key of [\n\t\t\"limit\",\n\t\t\"cursor\",\n\t\t\"direction\",\n\t\t\"sort\",\n\t\t\"sortBy\",\n\t\t\"sortDir\",\n\t]) {\n\t\tif (flags[key] !== undefined)\n\t\t\tthrow new Error(\n\t\t\t\t`supplier count does not accept --${key}; totals use filters only.`,\n\t\t\t);\n\t}\n\treturn parseSupplierFilters(flags);\n};\n\nfunction parseDashboardQueryFlags(flags: Record<string, string | true>) {\n\tconst roleRaw = getFlag(flags, \"role\");\n\tconst timeFrameRaw = getFlag(flags, \"timeFrame\");\n\treturn {\n\t\tuserId: getFlag(flags, \"userId\"),\n\t\trole: parseOptionalDashboardRole(\n\t\t\troleRaw !== undefined ? String(roleRaw) : undefined,\n\t\t),\n\t\tdeals: parseOptionalDeals(getFlag(flags, \"deals\")),\n\t\ttimeFrame: parseOptionalTimeFrame(\n\t\t\ttimeFrameRaw !== undefined ? String(timeFrameRaw) : undefined,\n\t\t) as\n\t\t\t| \"LAST_YEAR\"\n\t\t\t| \"LAST_6_MONTHS\"\n\t\t\t| \"LAST_3_MONTHS\"\n\t\t\t| \"CUSTOM\"\n\t\t\t| \"ALL\"\n\t\t\t| undefined,\n\t\tstartDate: getFlag(flags, \"startDate\"),\n\t\tendDate: getFlag(flags, \"endDate\"),\n\t};\n}\n\nfunction printLegacyHelp(runtime: CliRuntime): void {\n\tconst help = `\nbb — Budget Builder CLI for AI agents (parity with MCP tools)\n\nFirst step before each task: update to the latest published release with 'bun add --global @go-labs-sg/bb@latest', then run 'bb version' and 'bb --help' before using commands. Update once per task. If updating fails, stop and report it. Preserve an explicitly requested pinned or development/staging version.\n\nUsage: bb <command> [options] [args]\n\nIdentity: bb version — print the installed CLI package version and API target as JSON.\n\nGlobal: --quiet | -q | BB_CLI_QUIET=1 — hide action logs (default: log command + each tRPC call to stderr; stdout JSON unchanged).\n\nAuth: Run bb auth login for interactive use. BB_API_KEY remains supported for MCP, CI, and non-interactive automation.\n\nAuthorization: Run bb whoami before choosing commands. bb help lists the full\ncatalog for every role; it does not prove the active credential may call a command.\nThe API evaluates whoami.role (USER, INSIDE_SALES, LEAD, ACCOUNTING_TEAM, or\nADMIN) together with resource ownership/project assignment, current state, and\npending-approver assignment. On FORBIDDEN, stop and report the identity, role,\ncommand, and target; do not switch keys or try a lower-level procedure.\n\nSensitive workflow changes: approval decisions/requests, entity status updates,\nestimate emails, customer invoices, integration retries and QuickBooks outcome\nverification, mark-budget-won,\nsubmit-quotation, and supplier approval request side effects require an\ninteractive CONFIRM prompt and abort in non-interactive shells.\nAI agents must inspect the entity first, summarize the exact entity, target\nstate, and side effects, then wait for explicit user confirmation before running\nthe sensitive command.\n\nBudget mutations return a conflict while an estimate email is queued,\nprocessing, or awaiting provider reconciliation.\n\nBudgets\n list-budgets [--projectId] [--name] [--status CSV] [--createdBy] [--dateFrom] [--dateTo] [--sortBy lastActivityAt|createdAt|status|budget|date|createdBy] [--sortDir] [--limit 1-100] [--cursor <token>] [--direction forward|backward] [--summary]\n Returns { items, pageInfo }; follow nextCursor/previousCursor with the same filters and sort. --page/--perPage are rejected.\n count-budgets [same filter flags as list-budgets] totalCount plus status and active facets (each ignores its own filter)\n get-budget <id> Budget + line items\n get-budget-items <id> Line items only\n get-budget-details <id> Full detail (margins, suppliers, etc.)\n get-budget-categories [--q] [--limit 1-100] [--cursor <token>]\n Active categories, name A–Z. Returns { items, pageInfo }; follow nextCursor with the same --q.\n get-budget-versions <budgetId> [--limit <1-50>] [--cursor <token> | --all]\n rename-budget-version <versionId> --name <text>\n restore-budget-version <versionId> Replace current budget data and return it to DRAFT.\n update-budget-status <id> <status> [--projectManagerId <id>] [--markProjectWon true|false] [--projectStatusOnCommercialRejection PITCH|LOST]\n APPROVED requires a current Lead/Admin role, regardless of budget management permissions. Ordinary users must request approval.\n Material edits and generic status changes invalidate older pending budget requests; decide only a fresh request for the content reviewed.\n Budget-changing commands require interactive \"yes\" confirmation when the current budget is ESTIMATE_CREATED, ESTIMATE_SENT, ESTIMATE_ACCEPTED, ESTIMATE_REJECTED, or ESTIMATE_CLOSED.\n ESTIMATE_ACCEPTED requires win proof, auto-marks PITCH or LOST projects WON, requires --projectManagerId when the project has no PM, and auto-creates the Asana project/section when enabled.\n ESTIMATE_REJECTED requires --projectStatusOnCommercialRejection when rejecting the only accepted/closed budget on a commercial project.\n status: ${budgetStatusesForHelp.join(\", \")}\n\tmark-budget-won <budgetId> <filePath> [--projectManagerId <id>] [--invoiceSettings <json>] Upload signed quote/PO proof and set status to ESTIMATE_ACCEPTED; invoice settings optionally save project delivery preferences\n create-budget --payload '<json>' (budget.createBudget; when sourceBudgetId contains unavailable items, set unavailableItemReviewAcknowledged=true after explicit review)\n update-budget --payload '<json>' (budget.updateBudget; must include id)\n delete-budget <budgetId>\n create-budget-approval <budgetId> (also queues approval request emails)\n create-estimate <budgetId> (queues QuickBooks estimate creation; budget is read-only until it settles; supports preflight updates)\n send-estimate-to-contact-person --payload '<json>' Send using the web contact-person workflow; payload includes recipient fields plus HTML content/signature.\n add-budget-items --budgetId --items '[{\"itemId\":\"…\",\"quantity\":1,\"markup\":30},…]'\n update-budget-item --id <budgetItemId> [--description plain-text] [--note plain-text] [--quantity] [--markup] [--cost] [--unitPrice] [--isFreeOfCharge true|false] [--gstInclusive true|false] [--gstOutOfScope true|false]\n remove-budget-item <budgetItemId>\n replace-budget-item --budgetItemId <id> --replacementItemId <activeCatalogueItemId>\n approve-unavailable-item-exception --budgetItemId <id> --reason <text> Lead/Admin only; reason must be 5-1000 characters.\n reorder-budget-items <budgetId> --itemIds <csv>\n update-budget-item-supplier --budgetItemId --supplierId Material supplier/GST edit: supersedes pending approvals and applies the standard budget reset policy; unchanged supplier is a no-op.\n create-budget-category --name <text>\n update-budget-category --id --name\n delete-budget-category <id>\n update-budget-commission --payload '<json>' (budget.updateBudgetCommission)\n update-budget-discount --payload '<json>' (budget.updateBudgetDiscount; type percentage|amount)\n delete-budget-commission <budgetId> Remove commission and return the budget to DRAFT.\n delete-budget-discount <budgetId> Remove discount and return the budget to DRAFT.\n mark-budget-items-not-utilized --ids <csv> Remove unused lines from reconciliation and queue clearing their QBO placeholders.\n restore-budget-item <budgetItemId> Restore one Not Utilized line and queue its QBO placeholder when required.\n create-placeholder-bill <budgetItemId> Admin-only placeholder recovery; queues the QBO placeholder (operationId, status QUEUED).\n upload-budget-attachment <budgetId> <filePath> Presigned S3 upload + confirm\n\nBills\n list-bills [--projectId] [--budgetId] [--status CSV] [--search <text>] [--isClaimable true|false] [--createdByIds <csv>] [--sortBy createdAt|amount|status] [--sortDir asc|desc] [--limit 1-100] [--cursor <token>] [--direction forward|backward]\n Returns { items, pageInfo }; pass nextCursor with --direction forward or previousCursor with --direction backward, keeping the same filters and sort. --page/--pageSize/--perPage are rejected.\n list-claims same flags as list-bills; only reimbursable claims (ignores --isClaimable)\n count-bills [--projectId] [--budgetId] [--status CSV] [--search <text>] [--isClaimable true|false] [--createdByIds <csv>] [--includeMetrics true|false] totalCount, status facets (ignore --status) and optional amount metrics; no pagination/sort flags\n count-claims same flags as count-bills; only reimbursable claims\n Both lists return summaries; use get-bill-details <billId> for full detail.\n isClaimable differentiates the shared bill/claim records: false = bill, true = claim.\n Create supplier bills from approved quotations from the same supplier and project. Use quotationAllocations plus lineAmounts when quotations split one bill line. Eligible exemptions require explicit --quotation-exempt intent; claims do not consume or link quotations. Document-only quotations (documentOnly: true, $0) are never valid bill sources; create-bill, update-bill, validate-bill-selection and link-bill-quotations reject them, and a line covered only by one still counts as unquoted.\n Amounts for create/update (including drafts) exclude GST: amount = portion billed; extractedAmount = full invoice subtotal; lineAmounts[].amount and quotationAllocations[].amount also exclude GST. The CLI does not strip GST from input.\n Example: invoice subtotal 1800 + GST 162 = total 1962 -> amount: 1800, extractedAmount: 1800, allocations totaling 1800. BB calculates applicable GST separately. Re-read and verify both amount fields after writing.\n create-bill-approval <billId> (also queues approval request emails)\n create-bill --payload '<json>' [--draft-only] [--quotation-exempt] (bill.create; supplier bills use payload.quotationAllocations for split sources or quotationIds for disjoint coverage; explicit allocations require lineAmounts; claims reject quotation sources; an Admin's unpaid bill queues its QuickBooks bill: quickBooksSyncQueued, operationId)\n validate-bill-selection --payload '<json>' [--quotationIds <csv> | --quotationId <id>] Validate an approved supplier and approved quotation coverage for each supplier-bill line. --quotationId is legacy single-quotation syntax.\n link-bill-quotations <billId> (--payload '<json>' | --quotationIds <csv>) Admin-only source-link repair; payload.quotationAllocations supports same-line splits.\n stage-bill-attachment <projectId> <filePath...> [--file <path>] [--files <csv>] Upload files before create-bill; returns attachment JSON for attachments/paymentProofAttachments\n cleanup-staged-bill-attachments <projectId> --keys <csv> Queue cleanup of unattached staged uploads; returns operation IDs.\n update-bill --payload '<json>' (bill.update; must include id)\n update-bill-payment-evidence --payload '<json>' Replace paymentReference/paymentProofAttachments for an already-paid bill.\n delete-bill <billId>\n update-bill-status <id> <status> [--rejectionReason] [--paymentTrackingUrl] [--paymentReference] [--paymentProof <receipt.pdf>] [--overBudgetOverrideReason <text>]\n status (${billStatusesForUpdateHelp.join(\", \")}) — not PENDING_APPROVAL; use create-bill-approval\n PAID requires --paymentReference and a payment-proof PDF. Use --paymentProof to stage and submit the PDF atomically, or omit it only when BB already has a BILL_PAYMENT_PROOF attachment.\n Moving a bill or claim to PAID runs the server's paid-bill notification workflow.\n patch-bill-payment <billId> [--paymentTrackingUrl] [--paymentReference] [--quickbooksBillId] [--paymentDate <ISO>]\n Clear a field: --clearPaymentTrackingUrl true | --clearPaymentReference true | --clearQuickbooksBillId true | --clearPaymentDate true\n patch-bill-invoice-number <billId> <invoiceNumber>\n get-bill-attachments <billId> [--limit 1-50] [--cursor <token>]\n Newest first. Returns { items, pageInfo }; follow nextCursor.\n upload-bill-attachment <billId> <filePath...> [--file <path>] [--files <csv>] Attach invoice/supporting files as BILL attachments to any bill status, including PAID bills\n attach-bill-payment-receipt <billId> <filePath...> [--file <path>] [--files <csv>] Attach Wise/payment-proof PDFs as BILL_PAYMENT_PROOF attachments\n attach-bill-documents <billId> [--invoice <path>] [--invoices <csv>] [--paymentProof|--payment-proof|--proof <path>] [--paymentProofs|--payment-proofs|--proofs <csv>] Attach invoice and/or payment proof files with separate BB attachment types\n get-bill-details <billId> Bill summary as shown in the web app (status, amounts, people, payment, line totals)\n get-bill-line-items <billId> [--limit 1-100] [--cursor <token>] Line items with budget-item/quotation detail; { items, pageInfo }\n get-bill-approvals <billId> [--limit 1-50] [--cursor <token>] Approval requests with approver/requester/responder; { items, pageInfo }\n get-bill-payment <billId> Payment status, reference, date, tracking URL, QuickBooks link and external payment\n\nQuotations\n list-quotations [--projectId] [--budgetId] [--supplierId] [--status CSV] [--createdBy CSV] [--search] [--limit 1-100] [--cursor <token>] [--direction forward|backward]\n Newest first; returns { items, pageInfo }; rows carry documentOnly (document-only $0 quotations are listed and counted like any other). Follow nextCursor/previousCursor with the same filters. --page/--pageSize/--perPage are rejected; --requesterIds remains an alias for --createdBy.\n count-quotations [--projectId] [--budgetId] [--supplierId] [--status CSV] [--createdBy CSV] [--search] [--includeMetrics true|false] totalCount, status facets (ignore --status) and optional amount metrics\n get-quotation <quotationId> Quotation as shown in the web app (status, documentOnly, amounts, people, line totals, files, approvals; pdfProcessing is PROCESSING or FAILED until queued PDF conversion/signing links the PDF; gstMismatch warns when GST differs from the expected GST)\n get-quotation-line-items <quotationId> [--limit 1-100] [--cursor <token>] Line items with budget-item detail; { items, pageInfo }\n upload-quotation-attachment <projectId> <filePath> Upload one PDF, JPEG, or PNG up to 20MB; returns attachment JSON for a quotation payload.\n cleanup-staged-quotation-attachments <projectId> --keys <csv> Queue cleanup of unattached quotation uploads; returns operation IDs.\n create-quotation --payload '<json>' (quotation.createDraft; requires amountWithoutGst, gstAmount, and lineAmounts [{budgetItemId, amount}] for multiple budgetItemIds; amounts before GST must sum to amountWithoutGst; result gstMismatch warns when gstAmount is not 0 or the expected GST)\n Document-only ($0 supplier document, e.g. a contract or proposal with no price): set documentOnly: true with amountWithoutGst: 0, gstAmount: 0 and zero lineAmounts (lineAmounts may be omitted). It goes through submit/sign/approve like any quotation and shows documentOnly: true in list/get output, but it is never a valid bill quotation source (create-bill, update-bill, validate-bill-selection and link-bill-quotations are rejected by the API) and does not count as quotation coverage: a budget line covered only by it still counts as unquoted. Without documentOnly (default false), amountWithoutGst must be positive.\n Example: --payload '{\"projectId\":\"<id>\",\"budgetId\":\"<id>\",\"supplierId\":\"<id>\",\"budgetItemIds\":[\"<id>\"],\"amountWithoutGst\":0,\"gstAmount\":0,\"documentOnly\":true,\"attachments\":[<uploaded attachment>]}'\n update-quotation --payload '<json>' Update a DRAFT or REJECTED quotation; same allocation payload plus id; use lineAmounts [{budgetItemId, amount}] for every selected item. Result gstMismatch warns when gstAmount is not 0 or the expected GST. Update is a full replace: send documentOnly: true again when updating a document-only quotation, or it is treated as a priced quotation and needs a positive amountWithoutGst.\n delete-quotation <quotationId>\n submit-quotation <quotationId> [--overBudgetOverrideReason <text>] (signed PDF is made by a queued job: pdfProcessing; gstMismatch warns when GST is not 0 or the expected GST)\n approve-quotation <quotationId> [--overBudgetOverrideReason <text>] (assigned pending request/current Admin; concurrent revision or allocation changes conflict; final signed PDF is queued: pdfProcessing)\n reject-quotation <quotationId> --reason <text>\n download-quotation-pdf <quotationId> [original|staff|final] (refused with \"still processing\" until the queued PDF step links it)\n\nCustomer invoices\n check-customer-invoice-readiness <budgetId> Readiness plus the full remaining-balance amount preview and live QuickBooks validation.\n list-eligible-customer-invoice-budgets <projectId> Accepted budgets that are ready and still have invoice coverage remaining, including estimate total, invoiced/remaining percentages, and available amount.\n preview-customer-invoice-amount <budgetId> <percentage-of-estimate> Preview amount before GST, GST, and total for a percentage of the original estimate. The percentage cannot exceed the budget's remaining coverage.\n list-available-qbo-customer-invoices <budgetId> List unlinked QuickBooks invoices available for this accepted or closed estimate before previewing and importing one.\n list-customer-invoices [budgetId] [--projectId <id>] [--companyIds CSV] [--projectIds CSV] [--budgetIds CSV] [--createdByIds CSV] [--status CSV] [--search] [--sortBy createdAt|status|totalInvoiceAmount|approvalExpiresAt] [--sortDir asc|desc] [--limit 1-100] [--cursor <token>] [--direction forward|backward]\n Returns { items, pageInfo }; follow nextCursor/previousCursor with the same filters and sort. --page/--perPage are rejected.\n No scope flag lists invoices globally. --projectId uses the project scope. A positional budgetId is a backward-compatible shortcut for --budgetIds.\n count-customer-invoices [budgetId] [same filter flags as list-customer-invoices] totalCount, lifecycle status facets (ignore --status) and amount metrics; no paging or sort flags\n get-customer-invoice <batchId> Batch as shown in the web app: status, totals, people, approvals and invoice summaries\n get-customer-invoice-invoices <batchId> Invoices with QuickBooks identity, dates, sync state, bill email (from QuickBooks) and held QuickBooks changes (qboDetailsDrift)\n get-customer-invoice-lines <invoiceId> [--limit 1-100] [--cursor <token>] One invoice's lines; { items, pageInfo }\n get-customer-invoice-approvals <batchId> [--limit 1-50] [--cursor <token>] Approval requests with approver/requester/responder; { items, pageInfo }\n get-customer-invoice-history <batchId> [--limit 1-100] [--cursor <token>] Status history; { items, pageInfo }\n get-customer-invoice-payments <invoiceId> Payments QuickBooks applied to one invoice (date, reference, amount applied, attachment names). Live QuickBooks read.\n get-customer-invoice-email-context <batchId> Contact, required CC, budget, and project context for composing an invoice email.\n preview-qbo-customer-invoice <budgetId> <qboInvoiceId> Preview an invoice selected from list-available-qbo-customer-invoices; works on accepted/closed estimates.\n import-qbo-customer-invoice <budgetId> <qboInvoiceId> --token <previewToken> Confirm the reviewed BB-only link; requires --allow-state-change --allow-financial-write in automation.\n create-customer-invoice --payload '<json>' Create one invoice from an eligible budget. Include budgetId, a recommended UUID requestId, invoiceDate, details {billingAddress, customerMemo}, and exactly one split {label, percentage, dueDate}. Percentage is of the original estimate and cannot exceed the remaining coverage. Never sends.\n discard-customer-invoice <batchId> Discard a reserved CREATING batch with no created QBO invoices.\n delete-customer-invoice <batchId> Delete QBO invoices and the local batch.\n void-customer-invoice <batchId> Void the invoice batch in QuickBooks.\n resubmit-customer-invoice <batchId> Original requester only. Queues one replacement after confirmed expiry voiding; retries return the same replacement. Never sends to the customer.\n approve-customer-invoice <batchId> Admin approval; rejects voided invoices, notifies the creator, and closes the estimate at cumulative 100% coverage.\n reject-customer-invoice <batchId> --reason <text> Admin rejection; voids QBO invoices and notifies the creator.\n send-customer-invoice-to-contact-person --payload '<json>' Queues same composer workflow as web; requires invoiceId, to, cc, replyTo, subject, HTML content, and HTML signature.\n download-customer-invoice-pdf <invoiceId> [--output <path>]\n mark-customer-invoice-sent-externally <invoiceId> --sentAt <ISO datetime> --recipients a@x.com,b@y.com [--note <text>] Admin only. Record an APPROVED invoice as SENT because it was emailed outside Budget Builder; sends no email.\n sync-customer-invoice <invoiceId> Refresh local status and balance from QuickBooks; paid invoices become PAID, reversals restore delivery/approval, and QBO voids can reopen an estimate. QuickBooks edits to bill-to address, memo, bill email or total are not applied: they are flagged as qboDetailsDrift and admins are emailed.\n update-customer-invoice-details <invoiceId> --billingAddress <text> --customerMemo <text> [--requestId <uuid>]\n Save bill-to address and memo in BB and queue the QuickBooks update (external write). Bill email is managed in QuickBooks.\n update-customer-invoice-qbo-drift <invoiceId> --resolution ACCEPT_QBO|KEEP_BB [--requestId <uuid>]\n Admin: resolve flagged QuickBooks changes. ACCEPT_QBO copies them into BB only; KEEP_BB queues BB's address and memo to QuickBooks.\n\nApprovals\n list-approvals | get-pending-approvals [--type budget|supplier|bill|quotation|customer_invoice|all]\n approve-bill <billId> [--overBudgetOverrideReason <text>] (also sends requester reply email)\n reject-bill <billId> --reason <text> (also sends requester reply email)\n approve-budget <budgetId> (also sends requester reply email)\n reject-budget <budgetId> --reason <text> (also sends requester reply email)\n approve-supplier <supplierId> (approve a pending request, or Admin/Lead re-approve a rejected supplier; QuickBooks vendor sync is queued)\n reject-supplier <supplierId> --reason <text> (also sends requester reply email)\n\nCompanies & projects\n list-companies [--name] [--createdBy] [--createdByIds CSV] [--active true|false] [--sortBy name|createdAt] [--sortDir asc|desc] [--limit 1-100] [--cursor] [--direction forward|backward]\n Returns { items, pageInfo }; pass nextCursor with direction forward or previousCursor with direction backward. Omit --cursor to restart.\n count-companies [--name] [--createdBy] [--createdByIds CSV] [--active true|false]\n Returns independent { totalCount, counts: { active: { true, false } } }; no pagination or sorting flags.\n get-company <id>\n search-existing-companies --query <name> [--limit 1-50] [--cursor <token>] (BB + QuickBooks, read-only; follow pageInfo.nextCursor)\n use-existing-company --companyId <bbId> and/or --quickbooksId <qboId> [--name <qboName>] [--website <url>] [--confirmDistinct true]\n Supply both IDs to explicitly connect existing records with different names.\n Reuses both records, creating only the missing counterpart. A QBO-only import needs --name (from search-existing-companies);\n website is needed only for a QBO import without one. The QuickBooks link is queued (quickBooksSyncQueued, operationId).\n create-company --name --website <url> [--confirmDistinct true] [--billingEmails '<json-array>'] (QuickBooks customer queued)\n Exact existing companies are reused. Similar names require explicit separate-entity confirmation.\n update-company --payload '<json>' (optional billingEmails: omit to preserve, [] to clear; returns queued QBO operation ID, not completion)\n get-company-quickbooks-sync-status <companyId> (saved status only; no provider call or polling)\n delete-company <id>\n list-projects [--companyId] [--name] [--status|--statuses CSV] [--active true|false] [--wonFrom ISO] [--wonTo ISO] [--wonWithinDays N] [--limit 1-100] [--cursor] [--direction forward|backward] [--sortBy name|createdAt|status|companyName|wonAt] [--sortDir asc|desc]\n Returns { items, pageInfo }; pass nextCursor with direction forward or previousCursor with direction backward. Legacy --page/--perPage are rejected.\n --sortBy wonAt orders by when the project was marked WON (unwon projects last). Each project includes wonAt, wonBy { id, name } and wonAtEstimated (true for backfilled dates).\n count-projects [--companyId] [--name] [--status|--statuses CSV] [--active true|false] [--wonFrom ISO] [--wonTo ISO] [--wonWithinDays N]\n Returns independent { totalCount, counts: { status, active: { true, false } } }; no pagination or sorting flags.\n list-project-hubs [--q] [--status CSV] [--sortBy startDate|name|companyName|status] [--sortDir asc|desc] [--limit 1-100] [--cursor <token>] [--direction forward|backward]\n Returns { items, pageInfo }; follow nextCursor/previousCursor with the same filters and sort. --page/--perPage are rejected.\n count-project-hubs [--q] [--status CSV] totalCount plus status facet\n List active projects that have a Project Hub integration.\n get-project <id>\n Budget overview totalRevenue includes Estimate Accepted and Estimate Closed budgets only.\n create-project --name --companyId --contactPersonId --insideSalesId --businessDevelopmentId --venue --startDate <ISO> [--projectManagerId <userId>] [--asanaTaskId] [--asanaSearch <text>] [--slackChannelId --slackChannelUrl --slackChannelName] [--pax] [--endDate <ISO>] [--description]\n update-project --payload '<json>' (project.updateProject; warns before estimate-affecting changes reject linked estimates; a companyId change (with a contactPersonId from that company) does not itself reject estimates or touch invoices, but date/pax/venue changes in the same save still do; optional projectManagerId and requestQboAccountantNotification)\n delete-project <id>\n check-project-reconciliation <id> Run the same live reconciliation review as the web app without changing status.\n reconcile-project <id> Rerun all checks transactionally and mark an eligible WON project RECONCILED.\n complete-project <id> Rerun reconciliation validation, mark a RECONCILED project COMPLETED, and queue QBO placeholder cleanup.\n import-qbo-project <projectId> --url <quickBooksProjectUrl>\n update-project-status <id> <status> [--projectManagerId <userId>] [--projectManagerEmail <email>]\n PITCH → WON requires an accepted/closed estimate. To win a pitch, accept its estimate with mark-budget-won <budgetId> <signed-quote.pdf>, which moves the project to WON.\n Required when moving PITCH → WON: supply --projectManagerId or --projectManagerEmail.\n The project manager must be an active @getout.sg user; list eligible users with list-users --projectTeamOnly true.\n status: ${projectStatusesForHelp.join(\", \")}\n\nContacts\n list-contacts <companyId>\n create-contact-person --payload '<json>' (contactPerson.createContactPerson; title MR|MRS|MS|DR)\n update-contact-person --payload '<json>' (contactPerson.updateContactPerson; must include id)\n\nSuppliers & items\n list-suppliers [--name] [--limit 1-100] [--cursor <token>] [--direction forward|backward] [--sortBy createdAt|updatedAt|name|email|phone|gstRegistered|status|active] [--sortDir asc|desc | --sort JSON] [--createdBy <csv>] [--gstRegistered true|false] [--status CSV] [--supplierTags <csv>] [--active true|false]\n count-suppliers [--name] [--createdBy <csv>] [--gstRegistered true|false] [--status CSV] [--supplierTags <csv>] [--active true|false] (independent totals/facets; no pagination/sort flags)\n Defaults: --active true, --limit 10, --sortBy createdAt, --sortDir desc (same as the web list); pass --active false for archived suppliers.\n create-supplier --payload '<json>' (supplier.createSupplier; archived-name recreation is Admin-only; auto-requests approval + emails when status is PENDING_APPROVAL; Lead/Admin creates queue the QuickBooks vendor: quickBooksSyncQueued, operationId)\n update-supplier --payload '<json>' (authenticated; normal-user edits require server-enforced approval; Lead/Admin edits of a linked supplier queue the QuickBooks sync)\n delete-suppliers --ids <csv> (supplier.deleteSuppliers; admin; archives/deactivates supplier items)\n reactivate-suppliers --ids <csv> (supplier.reactivateSuppliers; admin; queues QuickBooks vendor reactivation, then the suppliers and their items become active: queuedSuppliers, operations)\n create-certification --name (supplier.createCertification)\n create-payment-method --name (supplier.createPaymentMethod)\n create-supplier-role --name (supplier.createSupplierRole)\n create-supplier-tag --name (supplier.createSupplierTag)\n create-item --payload '<json>' (item.createItem; saves the item and queues its QuickBooks create: quickBooksSyncQueued, operationId)\n update-item --payload '<json>' (item.updateItem; must include id)\n archive-items --ids <csv> (item.archiveItems; Budget Builder only; max 100; users can archive their own items, leads/admins any item; open estimates retain snapshot lines and require resolution before send/acceptance)\n delete-item <id> (item.deleteItem; admin; archives in Budget Builder and makes the item inactive in QuickBooks; blocked while used by an open estimate)\n get-supplier-details <supplierId>\n get-supplier-overview <supplierId> (supplier.getSupplierOverview; profile, approvals, attachments and tab counts; no usage or items)\n get-supplier-usage <supplierId> (supplier.getSupplierUsage; usage rows and spending)\n get-supplier-items <supplierId> (supplier.getSupplierItems; inventory items)\n get-supplier-analytics [--name] [--status CSV] [--gstRegistered true|false] [--createdBy <text>] [--timeFrame ALL|LAST_YEAR|LAST_6_MONTHS|LAST_3_MONTHS|CUSTOM] [--startDate <ISO> --endDate <ISO>] [--sortBy name|gstRegistered|status|phone|email|updatedAt|createdAt] [--sortDir asc|desc] [--limit 1-100] [--cursor <token>] [--direction forward|backward]\n Admin. Returns { items, pageInfo }; follow nextCursor/previousCursor with the same filters and sort. --page/--perPage are rejected.\n count-supplier-analytics [--name] [--status] [--gstRegistered] [--createdBy] [--timeFrame] [--startDate --endDate] Admin. totalCount for the same filters\n list-items [--name] [--includeQuickBooksDeactivationPending true] [--sortBy createdAt|updatedAt|name|cost|itemCategory|supplier] [--sortDir asc|desc] [--limit 1-100] [--cursor <token>] [--direction forward|backward]\n Returns { items, pageInfo }; follow nextCursor/previousCursor with the same filters and sort. --page/--perPage are rejected.\n count-items [same filter flags as list-items] total plus category and supplier facets\n get-item <id>\n get-item-quickbooks-sync-status <itemId> (saved status only; no provider call or polling)\n list-item-categories [--name] [--sortBy createdAt|name|itemCount|createdBy] [--sortDir asc|desc] [--limit 1-100] [--cursor <token>] [--direction forward|backward]\n Active categories only; returns { items, pageInfo }. Follow nextCursor/previousCursor with the same filters and sort. --page/--perPage are rejected.\n count-item-categories [--name] totalCount of active categories\n create-item-category --name (admin; saves the category and queues its QuickBooks create: quickBooksSyncQueued, operationId)\n update-item-category --id --name (authenticated; renames in BB now and queues the QuickBooks rename: quickBooksSyncQueued, operationId)\n delete-item-categories --ids <csv> (itemCategory.deleteItemCategories; admin; empty categories only)\n\nDashboard & users\n whoami Show the user identity and role for the active API key.\n list-users [--q] [--projectTeamOnly true|false] [--limit 1-100] [--cursor <token>]\n Name A–Z. Returns { items, pageInfo }; follow nextCursor with the same --q and --projectTeamOnly. --page/--perPage are rejected.\n --projectTeamOnly true lists only active @getout.sg users, the only accounts accepted as Inside Sales, Business Development or Project Manager.\n count-users [--q] [--projectTeamOnly true|false] totalCount for the same search\n create-user --email <email> [--name <name>] [--role ${userRolesForHelp.join(\"|\")}] (admin; API-only service identity with no Google sign-in)\n create-api-key --name <label> [--userId <userId>] (defaults to the caller; admin required for another user; raw key is shown once)\n list-api-keys [--userId <userId>] [--limit 1-100] [--cursor <token>] (newest first, { items, pageInfo }; defaults to the caller; admin required for another user)\n revoke-api-key <apiKeyId> [--userId <userId>] (defaults to the caller; admin required for another user)\n get-user-performance [--userId] (admin)\n get-dashboard [--userId] [--role BD|CREATOR|INSIDE_SALES|ALL] [--deals ALL|SUCCESSFUL|LOST] [--timeFrame] [--startDate] [--endDate] (admin)\n get-monthly-metrics [same optional flags as get-dashboard] (admin; dashboard.getMonthlyMetrics)\n get-system-overview [same optional flags as get-dashboard] (admin; dashboard.getSystemOverview)\n get-estimate-performance [same optional flags as get-dashboard] (admin; dashboard.getEstimatePerformance)\n get-financial-overview [same optional flags as dashboard; role uses BudgetRole enum] (admin)\n\nErrors\n get-recent-errors [--cursor] [--direction forward|backward] [--limit] [--severity] [--status] [--timeFrame] (admin)\n count-errors [--severity] [--status] [--timeFrame] (admin)\n get-error <errorId> Full diagnostics: stack, cause, request, metadata (admin)\n get-error-metrics (admin)\n\nAutomation (admin)\n list-integration-operations [--search] [--destination <provider,...>] [--status <PENDING|PROCESSING|FAILED|COMPLETED,...>] [--limit 1-100] [--cursor <token>] [--direction forward|backward]\n Newest first; returns { items, pageInfo }. Follow nextCursor/previousCursor with the same filters. --page/--perPage are rejected.\n count-integration-operations [same filter flags] provider filter options only (no total; filters do not change the result)\n get-integration-operation <operationId> (one job: who queued it, what it is for, saved progress, Retry state)\n retry-integration-operation <operationId> [--confirmExternalStateReconciled true|false] [--outboundEmailResolution ACCEPTED|NOT_ACCEPTED_RETRY] [--providerMessageId <id>] (QuickBooks jobs with a saved attempt check QuickBooks first: applied changes finish without resending, unapplied ones are sent again)\n reconcile-resource-operation <operationId> (admin: check a QuickBooks invoice/company/item job outcome without retrying; same check Retry runs first)\n\nWebhooks (admin)\n list-webhook-event-types (event catalogue: type, group, live|planned)\n list-webhook-endpoints\n get-webhook-endpoint <endpointId>\n create-webhook-endpoint --name <name> --url <https-url> --events <type|prefix.*|*,...> [--enabled true|false] (prints the signing secret once)\n update-webhook-endpoint <endpointId> [--name] [--url] [--events <...>] [--enabled true|false]\n delete-webhook-endpoint <endpointId>\n rotate-webhook-secret <endpointId> [--previousSecretTtlHours <0-168>] (prints the new secret once)\n send-webhook-test-event <endpointId>\n list-webhook-deliveries [--endpointId] [--status <PENDING|SUCCEEDED|FAILED,...>] [--eventType] [--limit 1-100] [--cursor <token>] [--direction forward|backward] (newest first; prints items + pageInfo)\n get-webhook-delivery <deliveryId> (attempts with response codes)\n replay-webhook-delivery <deliveryId> (same eventId, new attempt chain)\n\nHistorical / benchmarks\n get-approved-budgets [--projectId] [--limit] [--minRevenue] [--maxRevenue]\n get-budget-category-benchmarks <categoryId> [--limit]\n get-item-pricing-history [--itemName] [--categoryId] [--supplierId] [--limit]\n get-supplier-pricing-history <supplierId> [--itemCategoryId] [--limit]\n\nOutput: JSON to stdout. Errors to stderr; exit 1 on failure.\n\nMCP parity: every MCP tool maps to one command above. The CLI also exposes\n reorder-budget-items and update-budget-item-supplier (web UI–oriented tRPC).\n You may use MCP-style snake_case (e.g. bb list_bills) — normalized to kebab-case.\n\nNote: MCP also exposes a Prisma schema resource; the CLI has no equivalent.\n\nNot covered vs MCP get_budget: \"get-budget\" also fetches line items in one call.\n`.trim();\n\truntime.stdout.write(`${help}\\n`);\n}\n\ninterface CliPackageMetadata {\n\tname: string;\n\tversion: string;\n}\n\nconst getCliPackageMetadata = (): CliPackageMetadata => {\n\tconst packageJson = JSON.parse(\n\t\treadFileSync(new URL(\"../package.json\", import.meta.url), \"utf8\"),\n\t) as Partial<CliPackageMetadata>;\n\tif (!packageJson.name || !packageJson.version) {\n\t\tthrow new Error(\"Could not read Budget Builder CLI package metadata.\");\n\t}\n\treturn { name: packageJson.name, version: packageJson.version };\n};\n\nconst getVersionData = (): CliPackageMetadata & { apiBaseUrl: string } => {\n\tconst metadata = getCliPackageMetadata();\n\treturn {\n\t\t...metadata,\n\t\tapiBaseUrl: BUDGET_BUILDER_API_BASE_URL,\n\t};\n};\n\n/** MCP registers tools with snake_case; CLI commands are kebab-case. */\nfunction normalizeCliCommand(raw: string): string {\n\treturn raw.replace(/_/g, \"-\");\n}\n\nconst booleanFlagValues = new Set([\"true\", \"false\", \"1\", \"0\"]);\n\nconst isEnabledFlag = (argv: readonly string[], flag: string): boolean => {\n\tfor (let index = 0; index < argv.length; index++) {\n\t\tconst value = argv[index];\n\t\tif (value === `${flag}=true` || value === `${flag}=1`) return true;\n\t\tif (value?.startsWith(`${flag}=`)) return false;\n\t\tif (value !== flag) continue;\n\t\tconst next = argv[index + 1];\n\t\tif (next !== undefined && booleanFlagValues.has(next)) {\n\t\t\treturn next === \"true\" || next === \"1\";\n\t\t}\n\t\treturn true;\n\t}\n\treturn false;\n};\n\nconst runtimeOnlyFlags = [\n\t\"--allow-state-change\",\n\t\"--allow-email\",\n\t\"--allow-external-write\",\n\t\"--allow-delete\",\n\t\"--allow-financial-write\",\n\t\"--debug\",\n\t\"--quiet\",\n\t\"--api-url\",\n\t\"--no-browser\",\n] as const;\n\nconst isRuntimeOnlyArgument = (value: string): boolean =>\n\truntimeOnlyFlags.some(\n\t\t(flag) => value === flag || value.startsWith(`${flag}=`),\n\t) || value === \"-q\";\n\ninterface RootArguments {\n\tapiBaseUrl?: string;\n\tcommandArgv: string[];\n}\n\nconst readApiUrlArgumentValue = (\n\targv: readonly string[],\n\tindex: number,\n): string => {\n\tconst next = argv[index + 1];\n\tif (next === undefined || next.startsWith(\"-\")) {\n\t\tthrow new CliRuntimeError(\"USAGE\", \"--api-url requires a URL.\");\n\t}\n\treturn next;\n};\n\nconst parseRootArguments = (argv: readonly string[]): RootArguments => {\n\tconst commandArgv: string[] = [];\n\tlet apiBaseUrl: string | undefined;\n\tfor (let index = 0; index < argv.length; index++) {\n\t\tconst value = argv[index];\n\t\tif (value === undefined) continue;\n\t\tif (value.startsWith(\"--api-url=\")) {\n\t\t\tapiBaseUrl = value.slice(\"--api-url=\".length);\n\t\t\tcontinue;\n\t\t}\n\t\tif (value === \"--api-url\") {\n\t\t\tapiBaseUrl = readApiUrlArgumentValue(argv, index);\n\t\t\tindex++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (isRuntimeOnlyArgument(value)) {\n\t\t\tif (booleanFlagValues.has(argv[index + 1] ?? \"\")) index++;\n\t\t\tcontinue;\n\t\t}\n\t\tcommandArgv.push(value);\n\t}\n\treturn { apiBaseUrl, commandArgv };\n};\n\nconst effectPermissionsFromArgv = (\n\targv: readonly string[],\n): CliEffectPermissions => ({\n\tallowStateChange: isEnabledFlag(argv, \"--allow-state-change\"),\n\tallowEmail: isEnabledFlag(argv, \"--allow-email\"),\n\tallowExternalWrite: isEnabledFlag(argv, \"--allow-external-write\"),\n\tallowDelete: isEnabledFlag(argv, \"--allow-delete\"),\n\tallowFinancialWrite: isEnabledFlag(argv, \"--allow-financial-write\"),\n});\n\nconst isCompletionShell = (value: string): value is CompletionShell =>\n\tvalue === \"bash\" ||\n\tvalue === \"zsh\" ||\n\tvalue === \"fish\" ||\n\tvalue === \"powershell\";\n\nconst legacyArgvForCommand = (\n\targv: readonly string[],\n\tresolvedCommand: ResolvedCommand,\n): string[] => {\n\tconst legacyTarget = resolvedCommand.command.legacyTarget;\n\tif (legacyTarget === undefined) {\n\t\tthrow new CliRuntimeError(\n\t\t\t\"INTERNAL\",\n\t\t\t`Command ${resolvedCommand.command.path.join(\" \")} has no dispatcher target.`,\n\t\t);\n\t}\n\treturn [\n\t\targv[0] ?? \"node\",\n\t\targv[1] ?? \"bb\",\n\t\tlegacyTarget,\n\t\t...resolvedCommand.argv.filter((value) => !isRuntimeOnlyArgument(value)),\n\t];\n};\n\nconst normalizeDispatcherError = (error: unknown): unknown => {\n\tif (!(error instanceof Error)) return error;\n\tif (\n\t\t/\\brequires\\b|\\bmust be\\b|\\bmust include\\b|^Invalid\\b|^Missing\\b|^--/.test(\n\t\t\terror.message,\n\t\t)\n\t) {\n\t\treturn new CliRuntimeError(\"VALIDATION\", error.message);\n\t}\n\treturn error;\n};\n\nconst commandConfirmationTarget = (\n\tresolvedCommand: ResolvedCommand,\n): string => {\n\tconst positionalTarget = resolvedCommand.argv.find(\n\t\t(value) => value !== \"--\" && !value.startsWith(\"-\"),\n\t);\n\tif (\n\t\tpositionalTarget !== undefined &&\n\t\t!positionalTarget.startsWith(\"{\") &&\n\t\t!positionalTarget.startsWith(\"[\")\n\t) {\n\t\treturn positionalTarget;\n\t}\n\n\treturn resolvedCommand.command.path.join(\" \");\n};\n\nconst PAGING_FLAG_KEYS = [\n\t\"limit\",\n\t\"cursor\",\n\t\"direction\",\n\t\"sortBy\",\n\t\"sortDir\",\n] as const;\n\n/** Count commands accept filters only, never paging or sorting flags. */\nconst rejectCountPagingFlags = (\n\tflags: Record<string, string | true>,\n\tcommandName: string,\n) => {\n\tfor (const key of PAGING_FLAG_KEYS) {\n\t\tif (flags[key] !== undefined)\n\t\t\tthrow new Error(\n\t\t\t\t`${commandName} does not accept --${key}; totals use filters only.`,\n\t\t\t);\n\t}\n};\n\nconst rejectBarePagingFlags = (flags: Record<string, string | true>) => {\n\tfor (const key of PAGING_FLAG_KEYS) rejectBareFlag(flags, key);\n};\n\nconst parseCursorAndDirection = (flags: Record<string, string | true>) => {\n\tconst cursor = getFlag(flags, \"cursor\");\n\tif (cursor === \"\" || (cursor?.length ?? 0) > 8192)\n\t\tthrow new Error(\n\t\t\t\"--cursor must be a non-empty opaque token of at most 8192 characters.\",\n\t\t);\n\tconst direction = parseProjectDirection(getFlag(flags, \"direction\"));\n\tif (direction === \"backward\" && !cursor)\n\t\tthrow new Error(\"--direction backward requires --cursor <token>.\");\n\treturn { cursor, direction };\n};\n\nconst parseAscDescSortDir = (\n\tflags: Record<string, string | true>,\n): \"asc\" | \"desc\" | undefined => {\n\tconst sortDir = getFlag(flags, \"sortDir\");\n\tif (sortDir !== undefined && sortDir !== \"asc\" && sortDir !== \"desc\")\n\t\tthrow new Error('--sortDir must be \"asc\" or \"desc\".');\n\treturn sortDir;\n};\n\ntype CliCommandContext = {\n\tcmd: string;\n\tflags: Record<string, string | true>;\n\tpositional: string[];\n};\ntype CliCommandHandler = (context: CliCommandContext) => Promise<void>;\n\nconst commandWhoami: CliCommandHandler = async () => {\n\tawait whoAmI();\n};\n\nconst commandListBudgets: CliCommandHandler = async ({ cmd, flags }) => {\n\tconst statusStr = getFlag(flags, \"status\");\n\tconst statuses = parseCommaSeparatedBudgetStatuses(\n\t\tstatusStr !== undefined ? String(statusStr) : undefined,\n\t);\n\tconst filters = {\n\t\tprojectId: getFlag(flags, \"projectId\"),\n\t\tname: getFlag(flags, \"name\"),\n\t\tstatuses,\n\t\tcreatedBy: getFlag(flags, \"createdBy\"),\n\t\tdateFrom: getFlag(flags, \"dateFrom\"),\n\t\tdateTo: getFlag(flags, \"dateTo\"),\n\t\tactive: parseBudgetActiveFlag(flags),\n\t};\n\trejectRetiredPageFlags(flags);\n\tif (cmd === \"count-budgets\") {\n\t\tfor (const key of [\"limit\", \"cursor\", \"direction\", \"sortBy\", \"sortDir\"]) {\n\t\t\tif (flags[key] !== undefined)\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`count-budgets does not accept --${key}; totals use filters only.`,\n\t\t\t\t);\n\t\t}\n\t\tawait countBudgets(filters);\n\t\treturn;\n\t}\n\tfor (const key of [\"limit\", \"cursor\", \"direction\", \"sortBy\", \"sortDir\"])\n\t\trejectBareFlag(flags, key);\n\tconst cursor = getFlag(flags, \"cursor\");\n\tif (cursor === \"\" || (cursor?.length ?? 0) > 8192)\n\t\tthrow new Error(\n\t\t\t\"--cursor must be a non-empty opaque token of at most 8192 characters.\",\n\t\t);\n\tconst direction = parseProjectDirection(getFlag(flags, \"direction\"));\n\tif (direction === \"backward\" && !cursor)\n\t\tthrow new Error(\"--direction backward requires --cursor <token>.\");\n\tawait listBudgets({\n\t\t...filters,\n\t\tlimit: parseProjectLimit(getFlag(flags, \"limit\")),\n\t\tcursor,\n\t\tdirection,\n\t\tsortBy: getFlag(flags, \"sortBy\") as\n\t\t\t| GetAllBudgetsInput[\"sortBy\"]\n\t\t\t| undefined,\n\t\tsortDir: getFlag(flags, \"sortDir\") as\n\t\t\t| GetAllBudgetsInput[\"sortDir\"]\n\t\t\t| undefined,\n\t\tincludeDetails:\n\t\t\tflags.summary === true\n\t\t\t\t? false\n\t\t\t\t: (parseOptionalBoolFlag(flags, \"includeDetails\") ?? true),\n\t});\n};\n\nconst commandGetBudget: CliCommandHandler = async ({ flags, positional }) => {\n\tconst id = positional[0];\n\tif (!id) throw new Error(\"get-budget requires <id>\");\n\tawait getBudget(id, {\n\t\tincludeInactive:\n\t\t\tflags.includeInactive === true\n\t\t\t\t? true\n\t\t\t\t: (parseOptionalBoolFlag(flags, \"includeInactive\") ?? false),\n\t});\n};\n\nconst commandUploadBudgetAttachment: CliCommandHandler = async ({\n\tpositional,\n}) => {\n\tconst [budgetId, filePath] = positional;\n\tif (!budgetId || !filePath) {\n\t\tthrow new Error(\"upload-budget-attachment requires <budgetId> <filePath>\");\n\t}\n\tawait uploadBudgetAttachmentFromPath(budgetId, filePath);\n};\n\nconst commandMarkBudgetWon: CliCommandHandler = async ({\n\tflags,\n\tpositional,\n}) => {\n\tconst [budgetId, filePath] = positional;\n\tif (!budgetId || !filePath) {\n\t\tthrow new Error(\"mark-budget-won requires <budgetId> <filePath>\");\n\t}\n\tawait markBudgetWonWithProof(budgetId, filePath, {\n\t\tprojectManagerId:\n\t\t\tgetFlag(flags, \"projectManagerId\") !== undefined\n\t\t\t\t? String(getFlag(flags, \"projectManagerId\"))\n\t\t\t\t: undefined,\n\t\tmarkProjectWon: parseOptionalBoolFlag(flags, \"markProjectWon\"),\n\t\tprojectInvoiceSettings:\n\t\t\tgetFlag(flags, \"invoiceSettings\") !== undefined\n\t\t\t\t? parseJsonFlag<\n\t\t\t\t\t\tNonNullable<\n\t\t\t\t\t\t\tRouterInputs[\"budget\"][\"updateBudgetStatus\"][\"projectInvoiceSettings\"]\n\t\t\t\t\t\t>\n\t\t\t\t\t>(String(getFlag(flags, \"invoiceSettings\")), \"--invoiceSettings\")\n\t\t\t\t: undefined,\n\t});\n};\n\nconst commandGetBudgetItems: CliCommandHandler = async ({\n\tflags,\n\tpositional,\n}) => {\n\tconst id = positional[0];\n\tif (!id) throw new Error(\"get-budget-items requires <budgetId>\");\n\tawait getBudgetItemsOnly(id, {\n\t\tincludeInactive:\n\t\t\tflags.includeInactive === true\n\t\t\t\t? true\n\t\t\t\t: (parseOptionalBoolFlag(flags, \"includeInactive\") ?? false),\n\t});\n};\n\nconst commandGetBudgetDetails: CliCommandHandler = async ({\n\tflags,\n\tpositional,\n}) => {\n\tconst id = positional[0];\n\tif (!id) throw new Error(\"get-budget-details requires <budgetId>\");\n\tawait getBudgetDetails(id, {\n\t\tincludeInactive:\n\t\t\tflags.includeInactive === true\n\t\t\t\t? true\n\t\t\t\t: (parseOptionalBoolFlag(flags, \"includeInactive\") ?? false),\n\t});\n};\n\nconst commandGetBudgetCategories: CliCommandHandler = async ({ flags }) => {\n\trejectRetiredPageFlags(flags);\n\tfor (const key of [\"limit\", \"cursor\"]) rejectBareFlag(flags, key);\n\tif (flags.direction !== undefined)\n\t\tthrow new Error(\n\t\t\t\"get-budget-categories pages forward only; follow pageInfo.nextCursor with --cursor.\",\n\t\t);\n\tconst cursor = getFlag(flags, \"cursor\");\n\tif (cursor === \"\" || (cursor?.length ?? 0) > 8192)\n\t\tthrow new Error(\n\t\t\t\"--cursor must be a non-empty opaque token of at most 8192 characters.\",\n\t\t);\n\tawait getBudgetCategories({\n\t\tq: getFlag(flags, \"q\"),\n\t\tlimit: parseProjectLimit(getFlag(flags, \"limit\")),\n\t\tcursor,\n\t});\n};\n\nconst commandGetBudgetVersions: CliCommandHandler = async ({\n\tflags,\n\tpositional,\n}) => {\n\tconst id = positional[0];\n\tif (!id) throw new Error(\"get-budget-versions requires <budgetId>\");\n\tconst limit = flags.limit === undefined ? undefined : Number(flags.limit);\n\tif (\n\t\tflags.limit === true ||\n\t\t(limit !== undefined &&\n\t\t\t(!Number.isInteger(limit) || limit < 1 || limit > 50))\n\t) {\n\t\tthrow new CliRuntimeError(\n\t\t\t\"USAGE\",\n\t\t\t\"--limit must be an integer from 1 to 50.\",\n\t\t);\n\t}\n\tif (flags.cursor === true || flags.cursor === \"\") {\n\t\tthrow new CliRuntimeError(\n\t\t\t\"USAGE\",\n\t\t\t\"--cursor requires the nextCursor token from the previous page.\",\n\t\t);\n\t}\n\tawait getBudgetVersions(id, {\n\t\tlimit,\n\t\tcursor: flags.cursor,\n\t\tall: flags.all === true || (parseOptionalBoolFlag(flags, \"all\") ?? false),\n\t});\n};\n\nconst commandRenameBudgetVersion: CliCommandHandler = async ({\n\tflags,\n\tpositional,\n}) => {\n\tconst versionId = positional[0];\n\tconst newName = getFlag(flags, \"name\");\n\tif (!versionId || newName === undefined) {\n\t\tthrow new Error(\"rename-budget-version requires <versionId> --name <text>\");\n\t}\n\tawait renameBudgetVersion(versionId, String(newName));\n};\n\nconst commandRestoreBudgetVersion: CliCommandHandler = async ({\n\tpositional,\n}) => {\n\tconst versionId = positional[0];\n\tif (!versionId) {\n\t\tthrow new Error(\"restore-budget-version requires <versionId>\");\n\t}\n\tawait restoreBudgetVersion(versionId);\n};\n\nconst commandUpdateBudgetStatus: CliCommandHandler = async ({\n\tflags,\n\tpositional,\n}) => {\n\tconst [id, status] = positional;\n\tif (!id || !status) {\n\t\tthrow new Error(\"update-budget-status requires <id> <status>\");\n\t}\n\tif (!isBudgetStatusUpdate(status)) {\n\t\tthrow new Error(\n\t\t\t`Invalid status. Use one of: ${budgetStatusesForHelp.join(\", \")}`,\n\t\t);\n\t}\n\tawait updateBudgetStatus(id, status, {\n\t\tprojectManagerId:\n\t\t\tgetFlag(flags, \"projectManagerId\") !== undefined\n\t\t\t\t? String(getFlag(flags, \"projectManagerId\"))\n\t\t\t\t: undefined,\n\t\tmarkProjectWon: parseOptionalBoolFlag(flags, \"markProjectWon\"),\n\t\tprojectStatusOnCommercialRejection:\n\t\t\tparseCommercialRejectionProjectStatus(flags),\n\t\tprojectInvoiceSettings:\n\t\t\tgetFlag(flags, \"invoiceSettings\") !== undefined\n\t\t\t\t? parseJsonFlag<\n\t\t\t\t\t\tNonNullable<\n\t\t\t\t\t\t\tRouterInputs[\"budget\"][\"updateBudgetStatus\"][\"projectInvoiceSettings\"]\n\t\t\t\t\t\t>\n\t\t\t\t\t>(String(getFlag(flags, \"invoiceSettings\")), \"--invoiceSettings\")\n\t\t\t\t: undefined,\n\t});\n};\n\nconst commandCreateBudgetApproval: CliCommandHandler = async ({\n\tflags,\n\tpositional,\n}) => {\n\tconst id = positional[0];\n\tif (!id) throw new Error(\"create-budget-approval requires <budgetId>\");\n\tconst companyPayloadRaw = getFlag(flags, \"companyPayload\");\n\tconst contactPayloadRaw = getFlag(flags, \"contactPayload\");\n\tconst eventPayloadRaw = getFlag(flags, \"eventPayload\");\n\tawait createBudgetApproval(id, {\n\t\tcompany:\n\t\t\tcompanyPayloadRaw !== undefined\n\t\t\t\t? parseJsonObjectFlag<RouterInputs[\"company\"][\"updateCompany\"]>(\n\t\t\t\t\t\tString(companyPayloadRaw),\n\t\t\t\t\t\t\"--companyPayload\",\n\t\t\t\t\t)\n\t\t\t\t: undefined,\n\t\tcontactPerson:\n\t\t\tcontactPayloadRaw !== undefined\n\t\t\t\t? parseJsonObjectFlag<\n\t\t\t\t\t\tRouterInputs[\"contactPerson\"][\"updateContactPerson\"]\n\t\t\t\t\t>(String(contactPayloadRaw), \"--contactPayload\")\n\t\t\t\t: undefined,\n\t\teventDetails:\n\t\t\teventPayloadRaw !== undefined\n\t\t\t\t? parseJsonObjectFlag<{\n\t\t\t\t\t\tdate: string;\n\t\t\t\t\t\tstartTime: string;\n\t\t\t\t\t\tendTime: string;\n\t\t\t\t\t}>(String(eventPayloadRaw), \"--eventPayload\")\n\t\t\t\t: undefined,\n\t});\n};\n\nconst commandCreateEstimate: CliCommandHandler = async ({\n\tflags,\n\tpositional,\n}) => {\n\tconst id = positional[0];\n\tif (!id) throw new Error(\"create-estimate requires <budgetId>\");\n\tconst companyPayloadRaw = getFlag(flags, \"companyPayload\");\n\tconst contactPayloadRaw = getFlag(flags, \"contactPayload\");\n\tconst eventPayloadRaw = getFlag(flags, \"eventPayload\");\n\tawait createEstimate(id, {\n\t\tcompany:\n\t\t\tcompanyPayloadRaw !== undefined\n\t\t\t\t? parseJsonObjectFlag<RouterInputs[\"company\"][\"updateCompany\"]>(\n\t\t\t\t\t\tString(companyPayloadRaw),\n\t\t\t\t\t\t\"--companyPayload\",\n\t\t\t\t\t)\n\t\t\t\t: undefined,\n\t\tcontactPerson:\n\t\t\tcontactPayloadRaw !== undefined\n\t\t\t\t? parseJsonObjectFlag<\n\t\t\t\t\t\tRouterInputs[\"contactPerson\"][\"updateContactPerson\"]\n\t\t\t\t\t>(String(contactPayloadRaw), \"--contactPayload\")\n\t\t\t\t: undefined,\n\t\teventDetails:\n\t\t\teventPayloadRaw !== undefined\n\t\t\t\t? parseJsonObjectFlag<{\n\t\t\t\t\t\tdate: string;\n\t\t\t\t\t\tstartTime: string;\n\t\t\t\t\t\tendTime: string;\n\t\t\t\t\t}>(String(eventPayloadRaw), \"--eventPayload\")\n\t\t\t\t: undefined,\n\t});\n};\n\nconst commandSendEstimateEmail: CliCommandHandler = async ({ flags }) => {\n\tconst payloadRaw = getFlag(flags, \"payload\");\n\tif (!payloadRaw) {\n\t\tthrow new Error(\n\t\t\t\"send-estimate-to-contact-person requires --payload '<json>'\",\n\t\t);\n\t}\n\tconst raw = parseJsonFlag<unknown>(String(payloadRaw), \"--payload\");\n\tawait sendEstimateToContactPersonFromPayload(raw);\n};\n\nconst commandCreateBudget: CliCommandHandler = async ({ flags }) => {\n\tconst payloadRaw = getFlag(flags, \"payload\");\n\tif (!payloadRaw) {\n\t\tthrow new Error(\"create-budget requires --payload '<json>'\");\n\t}\n\tconst raw = parseJsonFlag<unknown>(String(payloadRaw), \"--payload\");\n\tawait createBudgetFromPayload(raw);\n};\n\nconst commandUpdateBudget: CliCommandHandler = async ({ flags }) => {\n\tconst payloadRaw = getFlag(flags, \"payload\");\n\tif (!payloadRaw) {\n\t\tthrow new Error(\"update-budget requires --payload '<json>'\");\n\t}\n\tconst raw = parseJsonFlag<unknown>(String(payloadRaw), \"--payload\");\n\tawait updateBudgetFromPayload(raw);\n};\n\nconst commandDeleteBudget: CliCommandHandler = async ({ positional }) => {\n\tconst id = positional[0];\n\tif (!id) throw new Error(\"delete-budget requires <budgetId>\");\n\tawait deleteBudgetById(id);\n};\n\nconst commandAddBudgetItems: CliCommandHandler = async ({ flags }) => {\n\tconst budgetId = getFlag(flags, \"budgetId\");\n\tif (!budgetId) throw new Error(\"add-budget-items requires --budgetId\");\n\tconst items = parseJsonFlag<\n\t\t{ itemId: string; quantity: number; markup?: number }[]\n\t>(String(getFlag(flags, \"items\")), \"--items\");\n\tawait addBudgetItems({ budgetId: String(budgetId), items });\n};\n\nconst commandUpdateBudgetItem: CliCommandHandler = async ({ flags }) => {\n\tconst id = getFlag(flags, \"id\");\n\tif (!id) throw new Error(\"update-budget-item requires --id\");\n\tawait updateBudgetItem({\n\t\tid: String(id),\n\t\tdescription: getFlag(flags, \"description\"),\n\t\tnote: getFlag(flags, \"note\"),\n\t\tquantity: parseOptNum(getFlag(flags, \"quantity\"), \"--quantity\"),\n\t\tmarkup: parseOptNum(getFlag(flags, \"markup\"), \"--markup\"),\n\t\tcost: parseOptNum(getFlag(flags, \"cost\"), \"--cost\"),\n\t\tunitPrice: parseOptNum(getFlag(flags, \"unitPrice\"), \"--unitPrice\"),\n\t\tisFreeOfCharge: parseOptionalBoolFlag(flags, \"isFreeOfCharge\"),\n\t\tgstInclusive: parseOptionalBoolFlag(flags, \"gstInclusive\"),\n\t\tgstOutOfScope: parseOptionalBoolFlag(flags, \"gstOutOfScope\"),\n\t});\n};\n\nconst commandRemoveBudgetItem: CliCommandHandler = async ({ positional }) => {\n\tconst id = positional[0];\n\tif (!id) throw new Error(\"remove-budget-item requires <budgetItemId>\");\n\tawait removeBudgetItem(id);\n};\n\nconst commandReplaceBudgetItem: CliCommandHandler = async ({ flags }) => {\n\tconst budgetItemId = getFlag(flags, \"budgetItemId\");\n\tconst replacementItemId = getFlag(flags, \"replacementItemId\");\n\tif (!budgetItemId || !replacementItemId) {\n\t\tthrow new Error(\n\t\t\t\"replace-budget-item requires --budgetItemId and --replacementItemId\",\n\t\t);\n\t}\n\tawait replaceBudgetItem({\n\t\tbudgetItemId: String(budgetItemId),\n\t\treplacementItemId: String(replacementItemId),\n\t});\n};\n\nconst commandApproveUnavailableItemException: CliCommandHandler = async ({\n\tflags,\n}) => {\n\tconst budgetItemId = getFlag(flags, \"budgetItemId\");\n\tconst reason = getFlag(flags, \"reason\");\n\tif (!budgetItemId || !reason) {\n\t\tthrow new Error(\n\t\t\t\"approve-unavailable-item-exception requires --budgetItemId and --reason\",\n\t\t);\n\t}\n\tawait approveUnavailableItemException({\n\t\tbudgetItemId: String(budgetItemId),\n\t\treason: String(reason),\n\t});\n};\n\nconst commandReorderBudgetItems: CliCommandHandler = async ({\n\tflags,\n\tpositional,\n}) => {\n\tconst budgetId = positional[0];\n\tconst itemIdsRaw = getFlag(flags, \"itemIds\");\n\tif (!budgetId || itemIdsRaw === undefined) {\n\t\tthrow new Error(\"reorder-budget-items requires <budgetId> --itemIds <csv>\");\n\t}\n\tconst itemIds = parseCommaSeparatedIds(String(itemIdsRaw));\n\tif (!itemIds?.length) {\n\t\tthrow new Error(\"reorder-budget-items requires non-empty --itemIds <csv>\");\n\t}\n\tawait reorderBudgetItemsCli({ budgetId, itemIds });\n};\n\nconst commandUpdateBudgetItemSupplier: CliCommandHandler = async ({\n\tflags,\n}) => {\n\tconst budgetItemId = getFlag(flags, \"budgetItemId\");\n\tconst supplierId = getFlag(flags, \"supplierId\");\n\tif (!budgetItemId || !supplierId) {\n\t\tthrow new Error(\n\t\t\t\"update-budget-item-supplier requires --budgetItemId and --supplierId\",\n\t\t);\n\t}\n\tawait updateBudgetItemSupplierCli({\n\t\tbudgetItemId: String(budgetItemId),\n\t\tsupplierId: String(supplierId),\n\t});\n};\n\nconst commandCreateBudgetCategory: CliCommandHandler = async ({ flags }) => {\n\tconst name = getFlag(flags, \"name\");\n\tif (!name) {\n\t\tthrow new Error(\"create-budget-category requires --name\");\n\t}\n\tawait createBudgetCategory(String(name));\n};\n\nconst commandUpdateBudgetCategory: CliCommandHandler = async ({ flags }) => {\n\tconst id = getFlag(flags, \"id\");\n\tconst name = getFlag(flags, \"name\");\n\tif (!id || !name) {\n\t\tthrow new Error(\"update-budget-category requires --id and --name\");\n\t}\n\tawait updateBudgetCategory({ id: String(id), name: String(name) });\n};\n\nconst commandDeleteBudgetCategory: CliCommandHandler = async ({\n\tpositional,\n}) => {\n\tconst id = positional[0];\n\tif (!id) {\n\t\tthrow new Error(\"delete-budget-category requires <id>\");\n\t}\n\tawait deleteBudgetCategory(id);\n};\n\nconst commandUpdateBudgetCommission: CliCommandHandler = async ({ flags }) => {\n\tconst payloadRaw = getFlag(flags, \"payload\");\n\tif (!payloadRaw) {\n\t\tthrow new Error(\"update-budget-commission requires --payload '<json>'\");\n\t}\n\tconst raw = parseJsonFlag<unknown>(String(payloadRaw), \"--payload\");\n\tawait updateBudgetCommissionFromPayload(raw);\n};\n\nconst commandUpdateBudgetDiscount: CliCommandHandler = async ({ flags }) => {\n\tconst payloadRaw = getFlag(flags, \"payload\");\n\tif (!payloadRaw) {\n\t\tthrow new Error(\"update-budget-discount requires --payload '<json>'\");\n\t}\n\tconst raw = parseJsonFlag<unknown>(String(payloadRaw), \"--payload\");\n\tawait updateBudgetDiscountFromPayload(raw);\n};\n\nconst commandDeleteBudgetCommission: CliCommandHandler = async ({\n\tpositional,\n}) => {\n\tconst budgetId = positional[0];\n\tif (!budgetId) {\n\t\tthrow new Error(\"delete-budget-commission requires <budgetId>\");\n\t}\n\tawait deleteBudgetCommission(budgetId);\n};\n\nconst commandDeleteBudgetDiscount: CliCommandHandler = async ({\n\tpositional,\n}) => {\n\tconst budgetId = positional[0];\n\tif (!budgetId) {\n\t\tthrow new Error(\"delete-budget-discount requires <budgetId>\");\n\t}\n\tawait deleteBudgetDiscount(budgetId);\n};\n\nconst commandMarkBudgetItemsNotUtilized: CliCommandHandler = async ({\n\tflags,\n}) => {\n\tconst budgetItemIds = parseCommaSeparatedIds(getFlag(flags, \"ids\"));\n\tif (!budgetItemIds?.length) {\n\t\tthrow new Error(\"mark-budget-items-not-utilized requires --ids <csv>\");\n\t}\n\tawait setBudgetItemsNotUtilized(budgetItemIds, true);\n};\n\nconst commandRestoreBudgetItem: CliCommandHandler = async ({ positional }) => {\n\tconst budgetItemId = positional[0];\n\tif (!budgetItemId) {\n\t\tthrow new Error(\"restore-budget-item requires <budgetItemId>\");\n\t}\n\tawait setBudgetItemsNotUtilized([budgetItemId], false);\n};\n\nconst commandCreatePlaceholderBill: CliCommandHandler = async ({\n\tpositional,\n}) => {\n\tconst budgetItemId = positional[0];\n\tif (!budgetItemId) {\n\t\tthrow new Error(\"create-placeholder-bill requires <budgetItemId>\");\n\t}\n\tawait createPlaceholderBillForBudgetItem(budgetItemId);\n};\n\nconst commandListBills: CliCommandHandler = async ({ flags }) => {\n\tawait listBills(parseListBillsFlags(flags));\n};\n\nconst commandListClaims: CliCommandHandler = async ({ flags }) => {\n\tawait listBills({\n\t\t...parseListBillsFlags(flags),\n\t\tisClaimable: true,\n\t});\n};\n\nconst commandCountBills: CliCommandHandler = async ({ flags }) => {\n\tawait countBills(parseCountBillsFlags(flags));\n};\n\nconst commandCountClaims: CliCommandHandler = async ({ flags }) => {\n\tawait countBills({ ...parseCountBillsFlags(flags), isClaimable: true });\n};\n\nconst commandCreateBillApproval: CliCommandHandler = async ({ positional }) => {\n\tconst id = positional[0];\n\tif (!id) throw new Error(\"create-bill-approval requires <billId>\");\n\tawait createBillApproval(id);\n};\n\nconst commandCreateBill: CliCommandHandler = async ({ flags }) => {\n\tconst payloadRaw = getFlag(flags, \"payload\");\n\tif (!payloadRaw) {\n\t\tthrow new Error(\"create-bill requires --payload '<json>'\");\n\t}\n\tconst raw = parseJsonFlag<unknown>(String(payloadRaw), \"--payload\");\n\tconst draftOnly =\n\t\tflags[\"draft-only\"] === true\n\t\t\t? true\n\t\t\t: parseOptionalBoolFlag(flags, \"draft-only\");\n\tconst quotationExempt = flags[\"quotation-exempt\"] === true;\n\tif (\n\t\tflags[\"quotation-exempt\"] !== undefined &&\n\t\tflags[\"quotation-exempt\"] !== true\n\t) {\n\t\tthrow new Error(\"--quotation-exempt does not take a value.\");\n\t}\n\tawait createBillFromPayload(raw, draftOnly, quotationExempt);\n};\n\nconst commandValidateBillSelection: CliCommandHandler = async ({ flags }) => {\n\tconst payloadRaw = getFlag(flags, \"payload\");\n\tif (!payloadRaw) {\n\t\tthrow new Error(\"validate-bill-selection requires --payload '<json>'\");\n\t}\n\tconst raw = parseJsonFlag<unknown>(String(payloadRaw), \"--payload\");\n\tif (flags.quotationIds === true || flags.quotationId === true) {\n\t\tthrow new Error(\n\t\t\t\"--quotationIds requires a CSV value and --quotationId requires an ID value.\",\n\t\t);\n\t}\n\tconst quotationIds = parseCommaSeparatedIds(getFlag(flags, \"quotationIds\"));\n\tconst quotationId = getFlag(flags, \"quotationId\")?.trim() || undefined;\n\tif (\n\t\tquotationId &&\n\t\tquotationIds &&\n\t\t(quotationIds.length !== 1 || quotationIds[0] !== quotationId)\n\t) {\n\t\tthrow new Error(\"--quotationId conflicts with --quotationIds.\");\n\t}\n\tif (quotationIds && new Set(quotationIds).size !== quotationIds.length) {\n\t\tthrow new Error(\"--quotationIds must not contain duplicates.\");\n\t}\n\tawait validateBillSelectionFromPayload(raw, {\n\t\t...(quotationId ? { quotationId } : {}),\n\t\t...(quotationIds ? { quotationIds } : {}),\n\t});\n};\n\nconst commandLinkBillQuotations: CliCommandHandler = async ({\n\tflags,\n\tpositional,\n}) => {\n\tconst billId = positional[0];\n\tconst payloadRaw = getFlag(flags, \"payload\");\n\tconst quotationIds = parseCommaSeparatedIds(getFlag(flags, \"quotationIds\"));\n\tif (\n\t\t!billId ||\n\t\t(!payloadRaw && (!quotationIds || quotationIds.length === 0))\n\t) {\n\t\tthrow new Error(\n\t\t\t\"link-bill-quotations requires <billId> and either --payload '<json>' or --quotationIds <csv>\",\n\t\t);\n\t}\n\tif (payloadRaw && quotationIds) {\n\t\tthrow new Error(\"--payload cannot be combined with --quotationIds.\");\n\t}\n\tif (quotationIds && new Set(quotationIds).size !== quotationIds.length) {\n\t\tthrow new Error(\"--quotationIds must not contain duplicates.\");\n\t}\n\tawait linkBillQuotations(\n\t\tbillId,\n\t\tpayloadRaw\n\t\t\t? parseJsonFlag<unknown>(String(payloadRaw), \"--payload\")\n\t\t\t: { quotationIds },\n\t);\n};\n\nconst commandUpdateBill: CliCommandHandler = async ({ flags }) => {\n\tconst payloadRaw = getFlag(flags, \"payload\");\n\tif (!payloadRaw) {\n\t\tthrow new Error(\"update-bill requires --payload '<json>'\");\n\t}\n\tconst raw = parseJsonFlag<unknown>(String(payloadRaw), \"--payload\");\n\tawait updateBillFromPayload(raw);\n};\n\nconst commandUpdateBillPaymentEvidence: CliCommandHandler = async ({\n\tflags,\n}) => {\n\tconst payloadRaw = getFlag(flags, \"payload\");\n\tif (!payloadRaw) {\n\t\tthrow new Error(\"update-bill-payment-evidence requires --payload '<json>'\");\n\t}\n\tconst raw = parseJsonFlag<unknown>(String(payloadRaw), \"--payload\");\n\tawait updateBillPaymentEvidenceFromPayload(raw);\n};\n\nconst commandDeleteBill: CliCommandHandler = async ({ positional }) => {\n\tconst id = positional[0];\n\tif (!id) throw new Error(\"delete-bill requires <billId>\");\n\tawait deleteBillById(id);\n};\n\nconst commandUpdateBillStatus: CliCommandHandler = async ({\n\tflags,\n\tpositional,\n}) => {\n\tconst [id, statusRaw] = positional;\n\tif (!id || !statusRaw) {\n\t\tthrow new Error(\n\t\t\t\"update-bill-status requires <billId> <status> [--rejectionReason] [--paymentTrackingUrl] [--paymentReference] [--paymentProof <receipt.pdf>]\",\n\t\t);\n\t}\n\tconst paymentProofFlag =\n\t\tflags.paymentProof ?? flags[\"payment-proof\"] ?? flags.receipt;\n\tif (paymentProofFlag === true) {\n\t\tthrow new Error(\"--paymentProof requires a PDF file path.\");\n\t}\n\tconst status = parseBillStatusForUpdate(statusRaw);\n\tawait updateBillStatus({\n\t\tid,\n\t\tstatus,\n\t\trejectionReason: getFlag(flags, \"rejectionReason\"),\n\t\tpaymentTrackingUrl: getFlag(flags, \"paymentTrackingUrl\"),\n\t\tpaymentReference: getFlag(flags, \"paymentReference\"),\n\t\tpaymentProofPath: paymentProofFlag,\n\t\toverBudgetOverrideReason: getFlag(flags, \"overBudgetOverrideReason\"),\n\t});\n};\n\nconst commandListExternalPaymentAccounts: CliCommandHandler = async () => {\n\tawait listExternalBillPaymentAccounts();\n};\n\nconst commandRefreshExternalPaymentAccounts: CliCommandHandler = async () => {\n\tawait refreshExternalBillPaymentAccounts();\n};\n\nconst commandRecordExternalBillPayment: CliCommandHandler = async ({\n\tflags,\n\tpositional,\n}) => {\n\tconst id = positional[0];\n\tconst paymentReference = getFlag(flags, \"paymentReference\");\n\tconst paymentDate = getFlag(flags, \"paymentDate\");\n\tconst paymentAccount = getFlag(flags, \"paymentAccount\");\n\tconst paymentProofPath = getFlag(flags, \"paymentProof\");\n\tif (!id || !paymentReference || !paymentDate || !paymentAccount)\n\t\tthrow new Error(\n\t\t\t\"record-external-bill-payment requires <billId> --paymentReference --paymentDate YYYY-MM-DD --paymentAccount <QBO account ID> [--paymentProof receipt.pdf]\",\n\t\t);\n\tawait recordExternalBillPayment({\n\t\tid,\n\t\tpaymentReference,\n\t\tpaymentDate,\n\t\tpaymentAccount,\n\t\tpaymentProofPath,\n\t});\n};\n\nconst commandPatchBillPayment: CliCommandHandler = async ({\n\tflags,\n\tpositional,\n}) => {\n\tconst id = positional[0];\n\tif (!id) throw new Error(\"patch-bill-payment requires <billId>\");\n\n\tconst paymentTrackingUrl = (() => {\n\t\tconst clear = parseOptionalBoolFlag(flags, \"clearPaymentTrackingUrl\");\n\t\tconst raw = getFlag(flags, \"paymentTrackingUrl\");\n\t\tif (clear === true && raw !== undefined) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Use either --paymentTrackingUrl or --clearPaymentTrackingUrl true, not both\",\n\t\t\t);\n\t\t}\n\t\tif (clear === true) return null;\n\t\tif (raw !== undefined) return String(raw);\n\t\treturn undefined;\n\t})();\n\n\tconst paymentReference = (() => {\n\t\tconst clear = parseOptionalBoolFlag(flags, \"clearPaymentReference\");\n\t\tconst raw = getFlag(flags, \"paymentReference\");\n\t\tif (clear === true && raw !== undefined) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Use either --paymentReference or --clearPaymentReference true, not both\",\n\t\t\t);\n\t\t}\n\t\tif (clear === true) return null;\n\t\tif (raw !== undefined) return String(raw);\n\t\treturn undefined;\n\t})();\n\n\tconst quickbooksBillId = (() => {\n\t\tconst clear = parseOptionalBoolFlag(flags, \"clearQuickbooksBillId\");\n\t\tconst raw = getFlag(flags, \"quickbooksBillId\");\n\t\tif (clear === true && raw !== undefined) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Use either --quickbooksBillId or --clearQuickbooksBillId true, not both\",\n\t\t\t);\n\t\t}\n\t\tif (clear === true) return null;\n\t\tif (raw !== undefined) return String(raw);\n\t\treturn undefined;\n\t})();\n\n\tconst paymentDate = (() => {\n\t\tconst clear = parseOptionalBoolFlag(flags, \"clearPaymentDate\");\n\t\tconst raw = getFlag(flags, \"paymentDate\");\n\t\tif (clear === true && raw !== undefined) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Use either --paymentDate or --clearPaymentDate true, not both\",\n\t\t\t);\n\t\t}\n\t\tif (clear === true) return null;\n\t\tif (raw !== undefined) return String(raw);\n\t\treturn undefined;\n\t})();\n\n\tawait patchBillPayment({\n\t\tid,\n\t\tpaymentTrackingUrl,\n\t\tpaymentReference,\n\t\tquickbooksBillId,\n\t\tpaymentDate,\n\t});\n};\n\nconst commandPatchBillInvoiceNumber: CliCommandHandler = async ({\n\tpositional,\n}) => {\n\tconst [id, inv] = positional;\n\tif (!id || !inv) {\n\t\tthrow new Error(\n\t\t\t\"patch-bill-invoice-number requires <billId> <invoiceNumber>\",\n\t\t);\n\t}\n\tawait patchBillInvoiceNumber(id, inv);\n};\n\nconst commandGetBillAttachments: CliCommandHandler = async ({\n\tflags,\n\tpositional,\n}) => {\n\tconst page = parseDetailFeedPage(\n\t\t\"get-bill-attachments\",\n\t\t\"<billId>\",\n\t\tpositional,\n\t\tflags,\n\t\t50,\n\t);\n\tawait getBillAttachments(page);\n};\n\nconst commandGetBillApprovals: CliCommandHandler = async ({\n\tflags,\n\tpositional,\n}) => {\n\tconst page = parseDetailFeedPage(\n\t\t\"get-bill-approvals\",\n\t\t\"<billId>\",\n\t\tpositional,\n\t\tflags,\n\t\t50,\n\t);\n\tawait getBillApprovals(page);\n};\n\nconst commandGetBillLineItems: CliCommandHandler = async ({\n\tflags,\n\tpositional,\n}) => {\n\tconst page = parseDetailFeedPage(\n\t\t\"get-bill-line-items\",\n\t\t\"<billId>\",\n\t\tpositional,\n\t\tflags,\n\t\t100,\n\t);\n\tawait getBillLineItems(page);\n};\n\nconst commandGetBillPayment: CliCommandHandler = async ({ positional }) => {\n\tconst id = positional[0];\n\tif (!id) throw new Error(\"get-bill-payment requires <billId>\");\n\tawait getBillPayment(id);\n};\n\nconst commandStageBillAttachment: CliCommandHandler = async ({\n\tflags,\n\tpositional,\n}) => {\n\tconst [projectId, ...positionalFilePaths] = positional;\n\tconst fileFlag = getFlag(flags, \"file\");\n\tconst filesFlag = getFlag(flags, \"files\");\n\tconst filePaths = [\n\t\t...positionalFilePaths,\n\t\t...(fileFlag !== undefined ? [String(fileFlag)] : []),\n\t\t...(filesFlag !== undefined\n\t\t\t? String(filesFlag)\n\t\t\t\t\t.split(\",\")\n\t\t\t\t\t.map((value) => value.trim())\n\t\t\t\t\t.filter(Boolean)\n\t\t\t: []),\n\t];\n\tif (!projectId || filePaths.length === 0) {\n\t\tthrow new Error(\n\t\t\t\"stage-bill-attachment requires <projectId> <filePath...> or --file/--files\",\n\t\t);\n\t}\n\tawait stageBillAttachmentsFromPaths(projectId, filePaths);\n};\n\nconst commandCleanupStagedBillAttachments: CliCommandHandler = async ({\n\tflags,\n\tpositional,\n}) => {\n\tconst projectId = positional[0];\n\tconst keys = parseCommaSeparatedIds(getFlag(flags, \"keys\"));\n\tif (!projectId || !keys) {\n\t\tthrow new Error(\n\t\t\t\"cleanup-staged-bill-attachments requires <projectId> --keys <csv>\",\n\t\t);\n\t}\n\tawait cleanupStagedBillAttachments(projectId, keys);\n};\n\nconst commandUploadBillAttachment: CliCommandHandler = async ({\n\tcmd,\n\tflags,\n\tpositional,\n}) => {\n\tconst [billId, ...positionalFilePaths] = positional;\n\tconst fileFlag = getFlag(flags, \"file\");\n\tconst filesFlag = getFlag(flags, \"files\");\n\tconst filePaths = [\n\t\t...positionalFilePaths,\n\t\t...(fileFlag !== undefined ? [String(fileFlag)] : []),\n\t\t...(filesFlag !== undefined\n\t\t\t? String(filesFlag)\n\t\t\t\t\t.split(\",\")\n\t\t\t\t\t.map((value) => value.trim())\n\t\t\t\t\t.filter(Boolean)\n\t\t\t: []),\n\t];\n\tif (!billId || filePaths.length === 0) {\n\t\tthrow new Error(`${cmd} requires <billId> <filePath...> or --file/--files`);\n\t}\n\tconst attachmentType =\n\t\tcmd === \"attach-bill-payment-receipt\"\n\t\t\t? AttachmentType.BILL_PAYMENT_PROOF\n\t\t\t: AttachmentType.BILL;\n\tconst [firstFilePath] = filePaths;\n\tif (filePaths.length === 1 && firstFilePath !== undefined) {\n\t\tawait uploadBillAttachmentFromPath(billId, firstFilePath, attachmentType);\n\t} else {\n\t\tawait uploadBillAttachmentsFromPaths(billId, filePaths, attachmentType);\n\t}\n};\n\nconst commandAttachBillDocuments: CliCommandHandler = async ({\n\tflags,\n\tpositional,\n}) => {\n\tconst billId = positional[0];\n\tif (!billId) throw new Error(\"attach-bill-documents requires <billId>\");\n\n\tconst getFlagAlias = (...flagNames: string[]) => {\n\t\tfor (const flagName of flagNames) {\n\t\t\tconst value = getFlag(flags, flagName);\n\t\t\tif (value !== undefined) return value;\n\t\t}\n\t\treturn undefined;\n\t};\n\tconst parseFilesFlag = (...flagNames: string[]) => {\n\t\tconst raw = getFlagAlias(...flagNames);\n\t\tif (raw === undefined) return [];\n\t\treturn String(raw)\n\t\t\t.split(\",\")\n\t\t\t.map((value) => value.trim())\n\t\t\t.filter(Boolean);\n\t};\n\tconst invoicePath = getFlagAlias(\"invoice\", \"invoice-file\");\n\tconst paymentProofPath = getFlagAlias(\n\t\t\"paymentProof\",\n\t\t\"payment-proof\",\n\t\t\"proof\",\n\t\t\"receipt\",\n\t);\n\tconst invoicePaths = [\n\t\t...(invoicePath !== undefined ? [String(invoicePath)] : []),\n\t\t...parseFilesFlag(\"invoices\", \"invoice-files\"),\n\t];\n\tconst paymentProofPaths = [\n\t\t...(paymentProofPath !== undefined ? [String(paymentProofPath)] : []),\n\t\t...parseFilesFlag(\"paymentProofs\", \"payment-proofs\", \"proofs\", \"receipts\"),\n\t];\n\n\tawait uploadBillDocumentsFromPaths({\n\t\tbillId,\n\t\tinvoicePaths,\n\t\tpaymentProofPaths,\n\t});\n};\n\nconst commandGetBillDetails: CliCommandHandler = async ({ positional }) => {\n\tconst id = positional[0];\n\tif (!id) throw new Error(\"get-bill-details requires <billId>\");\n\tawait getBillDetails(id);\n};\n\nconst commandListQuotations: CliCommandHandler = async ({ flags }) => {\n\trejectRetiredPageFlags(flags);\n\tfor (const key of [\"limit\", \"cursor\", \"direction\"])\n\t\trejectBareFlag(flags, key);\n\tconst cursor = getFlag(flags, \"cursor\");\n\tif (cursor === \"\" || (cursor?.length ?? 0) > 8192)\n\t\tthrow new Error(\n\t\t\t\"--cursor must be a non-empty opaque token of at most 8192 characters.\",\n\t\t);\n\tconst direction = parseProjectDirection(getFlag(flags, \"direction\"));\n\tif (direction === \"backward\" && !cursor)\n\t\tthrow new Error(\"--direction backward requires --cursor <token>.\");\n\tawait listQuotations({\n\t\t...parseQuotationFilterFlags(flags),\n\t\tlimit: parseProjectLimit(getFlag(flags, \"limit\")),\n\t\tcursor,\n\t\tdirection,\n\t});\n};\n\nconst commandCountQuotations: CliCommandHandler = async ({ flags }) => {\n\trejectRetiredPageFlags(flags);\n\tfor (const key of [\"limit\", \"cursor\", \"direction\"]) {\n\t\tif (flags[key] !== undefined)\n\t\t\tthrow new Error(\n\t\t\t\t`count-quotations does not accept --${key}; totals use filters only.`,\n\t\t\t);\n\t}\n\tawait countQuotations({\n\t\t...parseQuotationFilterFlags(flags),\n\t\tincludeMetrics: parseOptionalBoolFlag(flags, \"includeMetrics\") ?? false,\n\t});\n};\n\nconst commandGetQuotation: CliCommandHandler = async ({ positional }) => {\n\tconst id = positional[0];\n\tif (!id) throw new Error(\"get-quotation requires <quotationId>\");\n\tawait getQuotationDetails(id);\n};\n\nconst commandGetQuotationLineItems: CliCommandHandler = async ({\n\tflags,\n\tpositional,\n}) => {\n\tconst page = parseDetailFeedPage(\n\t\t\"get-quotation-line-items\",\n\t\t\"<quotationId>\",\n\t\tpositional,\n\t\tflags,\n\t\t100,\n\t);\n\tawait getQuotationLineItems(page);\n};\n\nconst commandUploadQuotationAttachment: CliCommandHandler = async ({\n\tpositional,\n}) => {\n\tconst [projectId, filePath] = positional;\n\tif (!projectId || !filePath) {\n\t\tthrow new Error(\n\t\t\t\"upload-quotation-attachment requires <projectId> <filePath>\",\n\t\t);\n\t}\n\tawait uploadQuotationAttachmentFromPath(projectId, filePath);\n};\n\nconst commandCleanupStagedQuotationAttachments: CliCommandHandler = async ({\n\tflags,\n\tpositional,\n}) => {\n\tconst projectId = positional[0];\n\tconst keys = parseCommaSeparatedIds(getFlag(flags, \"keys\"));\n\tif (!projectId || !keys) {\n\t\tthrow new Error(\n\t\t\t\"cleanup-staged-quotation-attachments requires <projectId> --keys <csv>\",\n\t\t);\n\t}\n\tawait cleanupStagedQuotationAttachments(projectId, keys);\n};\n\nconst commandCreateQuotation: CliCommandHandler = async ({ flags }) => {\n\tconst payloadRaw = getFlag(flags, \"payload\");\n\tif (!payloadRaw) {\n\t\tthrow new Error(\"create-quotation requires --payload '<json>'\");\n\t}\n\tconst raw = parseJsonFlag<unknown>(String(payloadRaw), \"--payload\");\n\tawait createQuotationFromPayload(raw);\n};\n\nconst commandUpdateQuotation: CliCommandHandler = async ({ flags }) => {\n\tconst payloadRaw = getFlag(flags, \"payload\");\n\tif (!payloadRaw) {\n\t\tthrow new Error(\"update-quotation requires --payload '<json>'\");\n\t}\n\tconst raw = parseJsonFlag<unknown>(String(payloadRaw), \"--payload\");\n\tawait updateQuotationFromPayload(raw);\n};\n\nconst commandDeleteQuotation: CliCommandHandler = async ({ positional }) => {\n\tconst id = positional[0];\n\tif (!id) throw new Error(\"delete-quotation requires <quotationId>\");\n\tawait deleteQuotationById(id);\n};\n\nconst commandSubmitQuotation: CliCommandHandler = async ({\n\tflags,\n\tpositional,\n}) => {\n\tconst id = positional[0];\n\tif (!id) throw new Error(\"submit-quotation requires <quotationId>\");\n\tawait submitQuotation(id, getFlag(flags, \"overBudgetOverrideReason\"));\n};\n\nconst commandApproveQuotation: CliCommandHandler = async ({\n\tflags,\n\tpositional,\n}) => {\n\tconst id = positional[0];\n\tif (!id) throw new Error(\"approve-quotation requires <quotationId>\");\n\tawait approveQuotation(id, getFlag(flags, \"overBudgetOverrideReason\"));\n};\n\nconst commandRejectQuotation: CliCommandHandler = async ({\n\tflags,\n\tpositional,\n}) => {\n\tconst id = positional[0];\n\tconst reason = getFlag(flags, \"reason\");\n\tif (!id || reason === undefined) {\n\t\tthrow new Error(\"reject-quotation requires <quotationId> --reason <text>\");\n\t}\n\tawait rejectQuotation(id, reason);\n};\n\nconst commandDownloadQuotationPdf: CliCommandHandler = async ({\n\tpositional,\n}) => {\n\tconst id = positional[0];\n\tif (!id) {\n\t\tthrow new Error(\n\t\t\t\"download-quotation-pdf requires <quotationId> [original|staff|final]\",\n\t\t);\n\t}\n\tconst roleRaw = (positional[1] ?? \"final\").toLowerCase();\n\tconst fileRole =\n\t\troleRaw === \"original\"\n\t\t\t? SupplierQuotationFileRole.ORIGINAL\n\t\t\t: roleRaw === \"staff\"\n\t\t\t\t? SupplierQuotationFileRole.STAFF_SIGNED\n\t\t\t\t: roleRaw === \"final\"\n\t\t\t\t\t? SupplierQuotationFileRole.FINAL_SIGNED\n\t\t\t\t\t: null;\n\tif (!fileRole) {\n\t\tthrow new Error(\n\t\t\t\"download-quotation-pdf role must be original, staff, or final\",\n\t\t);\n\t}\n\tawait downloadQuotationPdf(id, fileRole);\n};\n\nconst commandCheckCustomerInvoiceReadiness: CliCommandHandler = async ({\n\tpositional,\n}) => {\n\tconst budgetId = positional[0];\n\tif (!budgetId) {\n\t\tthrow new Error(\"check-customer-invoice-readiness requires <budgetId>\");\n\t}\n\tawait checkCustomerInvoiceReadiness(budgetId);\n};\n\nconst commandListEligibleCustomerInvoiceBudgets: CliCommandHandler = async ({\n\tpositional,\n}) => {\n\tconst projectId = positional[0];\n\tif (!projectId) {\n\t\tthrow new Error(\n\t\t\t\"list-eligible-customer-invoice-budgets requires <projectId>\",\n\t\t);\n\t}\n\tawait listEligibleCustomerInvoiceBudgets(projectId);\n};\n\nconst commandPreviewCustomerInvoiceAmount: CliCommandHandler = async ({\n\tpositional,\n}) => {\n\tconst [budgetId, rawPercentage] = positional;\n\tconst percentage = Number(rawPercentage);\n\tif (\n\t\t!budgetId ||\n\t\t!rawPercentage ||\n\t\tpositional.length !== 2 ||\n\t\t!Number.isFinite(percentage) ||\n\t\tpercentage <= 0 ||\n\t\tpercentage > 100 ||\n\t\tMath.round(percentage * 100) !== percentage * 100\n\t) {\n\t\tthrow new Error(\n\t\t\t\"preview-customer-invoice-amount requires <budgetId> <percentage-of-estimate> between 0.01 and 100\",\n\t\t);\n\t}\n\tawait previewCustomerInvoiceAmount(budgetId, percentage);\n};\n\nconst commandListAvailableQboCustomerInvoices: CliCommandHandler = async ({\n\tpositional,\n}) => {\n\tconst budgetId = positional[0];\n\tif (!budgetId || positional.length !== 1) {\n\t\tthrow new Error(\"list-available-qbo-customer-invoices requires <budgetId>\");\n\t}\n\tawait listAvailableQboCustomerInvoices(budgetId);\n};\n\nconst customerInvoiceFiltersFromFlags = (\n\tflags: Record<string, string | true>,\n\tpositionalBudgetId: string | undefined,\n) => {\n\tconst projectId = getFlag(flags, \"projectId\");\n\tconst projectIds = parseCommaSeparatedIds(getFlag(flags, \"projectIds\"));\n\tif (projectId && projectIds) {\n\t\tthrow new Error(\n\t\t\t\"Use either --projectId for project scope or --projectIds for a global filter, not both.\",\n\t\t);\n\t}\n\tconst budgetIds = [\n\t\t...(positionalBudgetId ? [positionalBudgetId] : []),\n\t\t...(parseCommaSeparatedIds(getFlag(flags, \"budgetIds\")) ?? []),\n\t];\n\tconst statusRaw = getFlag(flags, \"status\");\n\treturn {\n\t\tscope: projectId\n\t\t\t? { type: \"project\" as const, projectId }\n\t\t\t: { type: \"global\" as const },\n\t\tq: getFlag(flags, \"search\") ?? \"\",\n\t\tstatuses: parseCommaSeparatedCustomerInvoiceStatuses(\n\t\t\tstatusRaw !== undefined ? String(statusRaw) : undefined,\n\t\t),\n\t\tcompanyIds: parseCommaSeparatedIds(getFlag(flags, \"companyIds\")),\n\t\tprojectIds,\n\t\tbudgetIds: budgetIds.length > 0 ? [...new Set(budgetIds)] : undefined,\n\t\tcreatedByIds: parseCommaSeparatedIds(getFlag(flags, \"createdByIds\")),\n\t};\n};\n\nconst commandListCustomerInvoices: CliCommandHandler = async ({\n\tcmd,\n\tflags,\n\tpositional,\n}) => {\n\tconst filters = customerInvoiceFiltersFromFlags(flags, positional[0]);\n\trejectRetiredPageFlags(flags);\n\tif (cmd === \"count-customer-invoices\") {\n\t\trejectCountPagingFlags(flags, \"count-customer-invoices\");\n\t\tawait countCustomerInvoices(filters);\n\t\treturn;\n\t}\n\trejectBarePagingFlags(flags);\n\tconst { cursor, direction } = parseCursorAndDirection(flags);\n\tconst sortDir = parseOptionalBillListSortDir(getFlag(flags, \"sortDir\"));\n\tawait listCustomerInvoices({\n\t\t...filters,\n\t\tlimit: parseProjectLimit(getFlag(flags, \"limit\")),\n\t\tcursor,\n\t\tdirection,\n\t\tsortBy: parseCustomerInvoiceSortBy(getFlag(flags, \"sortBy\")),\n\t\tsortDir: sortDir ?? \"desc\",\n\t});\n};\n\nconst commandGetCustomerInvoice: CliCommandHandler = async ({ positional }) => {\n\tconst batchId = positional[0];\n\tif (!batchId) {\n\t\tthrow new Error(\"get-customer-invoice requires <batchId>\");\n\t}\n\tawait getCustomerInvoice(batchId);\n};\n\nconst commandGetCustomerInvoiceInvoices: CliCommandHandler = async ({\n\tpositional,\n}) => {\n\tconst batchId = positional[0];\n\tif (!batchId)\n\t\tthrow new Error(\"get-customer-invoice-invoices requires <batchId>\");\n\tawait getCustomerInvoiceInvoices(batchId);\n};\n\nconst commandGetCustomerInvoiceLines: CliCommandHandler = async ({\n\tflags,\n\tpositional,\n}) => {\n\tconst page = parseDetailFeedPage(\n\t\t\"get-customer-invoice-lines\",\n\t\t\"<invoiceId>\",\n\t\tpositional,\n\t\tflags,\n\t\t100,\n\t);\n\tawait getCustomerInvoiceLines(page);\n};\n\nconst commandGetCustomerInvoiceApprovals: CliCommandHandler = async ({\n\tflags,\n\tpositional,\n}) => {\n\tconst page = parseDetailFeedPage(\n\t\t\"get-customer-invoice-approvals\",\n\t\t\"<batchId>\",\n\t\tpositional,\n\t\tflags,\n\t\t50,\n\t);\n\tawait getCustomerInvoiceApprovals(page);\n};\n\nconst commandGetCustomerInvoiceHistory: CliCommandHandler = async ({\n\tflags,\n\tpositional,\n}) => {\n\tconst page = parseDetailFeedPage(\n\t\t\"get-customer-invoice-history\",\n\t\t\"<batchId>\",\n\t\tpositional,\n\t\tflags,\n\t\t100,\n\t);\n\tawait getCustomerInvoiceHistory(page);\n};\n\nconst commandGetCustomerInvoicePayments: CliCommandHandler = async ({\n\tpositional,\n}) => {\n\tconst invoiceId = positional[0];\n\tif (!invoiceId) {\n\t\tthrow new Error(\"get-customer-invoice-payments requires <invoiceId>\");\n\t}\n\tawait getCustomerInvoicePayments(invoiceId);\n};\n\nconst commandGetCustomerInvoiceEmailContext: CliCommandHandler = async ({\n\tpositional,\n}) => {\n\tconst batchId = positional[0];\n\tif (!batchId) {\n\t\tthrow new Error(\"get-customer-invoice-email-context requires <batchId>\");\n\t}\n\tawait getCustomerInvoiceEmailContext(batchId);\n};\n\nconst commandPreviewQboCustomerInvoice: CliCommandHandler = async ({\n\tcmd,\n\tflags,\n\tpositional,\n}) => {\n\tconst [budgetId, qboInvoiceId] = positional;\n\tif (!budgetId?.trim() || !qboInvoiceId || positional.length !== 2) {\n\t\tthrow new Error(`${cmd} requires <budgetId> <qboInvoiceId>`);\n\t}\n\tif (!/^\\d+$/.test(qboInvoiceId)) {\n\t\tthrow new Error(\n\t\t\t\"qboInvoiceId must be the numeric QuickBooks transaction ID, not the invoice number\",\n\t\t);\n\t}\n\tif (cmd === \"preview-qbo-customer-invoice\") {\n\t\tawait previewQboCustomerInvoice({ budgetId, qboInvoiceId });\n\t} else {\n\t\tconst token = getFlag(flags, \"token\");\n\t\tif (!token || !/^[a-f0-9]{64}$/.test(token)) {\n\t\t\tthrow new Error(\n\t\t\t\t\"import-qbo-customer-invoice requires --token <64-character preview token> from a reviewed preview-qbo result\",\n\t\t\t);\n\t\t}\n\t\tawait importQboCustomerInvoice({ budgetId, qboInvoiceId, token });\n\t}\n};\n\nconst commandCreateCustomerInvoice: CliCommandHandler = async ({ flags }) => {\n\tconst payloadRaw = getFlag(flags, \"payload\");\n\tif (!payloadRaw) {\n\t\tthrow new Error(\"create-customer-invoice requires --payload '<json>'\");\n\t}\n\tawait createCustomerInvoice(\n\t\tparseJsonFlag<unknown>(String(payloadRaw), \"--payload\"),\n\t);\n};\n\nconst commandResubmitCustomerInvoice: CliCommandHandler = async ({\n\tpositional,\n}) => {\n\tconst batchId = positional[0];\n\tif (!batchId) throw new Error(\"resubmit-customer-invoice requires <batchId>\");\n\tawait resubmitCustomerInvoice(batchId);\n};\n\nconst commandDiscardCustomerInvoice: CliCommandHandler = async ({\n\tpositional,\n}) => {\n\tconst batchId = positional[0];\n\tif (!batchId) {\n\t\tthrow new Error(\"discard-customer-invoice requires <batchId>\");\n\t}\n\tawait discardCreatingCustomerInvoice(batchId);\n};\n\nconst commandDeleteCustomerInvoice: CliCommandHandler = async ({\n\tpositional,\n}) => {\n\tconst batchId = positional[0];\n\tif (!batchId) {\n\t\tthrow new Error(\"delete-customer-invoice requires <batchId>\");\n\t}\n\tawait deleteCustomerInvoice(batchId);\n};\n\nconst commandVoidCustomerInvoice: CliCommandHandler = async ({\n\tpositional,\n}) => {\n\tconst batchId = positional[0];\n\tif (!batchId) {\n\t\tthrow new Error(\"void-customer-invoice requires <batchId>\");\n\t}\n\tawait voidCustomerInvoice(batchId);\n};\n\nconst commandApproveCustomerInvoice: CliCommandHandler = async ({\n\tpositional,\n}) => {\n\tconst batchId = positional[0];\n\tif (!batchId) {\n\t\tthrow new Error(\"approve-customer-invoice requires <batchId>\");\n\t}\n\tawait approveCustomerInvoice(batchId);\n};\n\nconst commandRejectCustomerInvoice: CliCommandHandler = async ({\n\tflags,\n\tpositional,\n}) => {\n\tconst batchId = positional[0];\n\tconst reason = getFlag(flags, \"reason\");\n\tif (!batchId || reason === undefined) {\n\t\tthrow new Error(\n\t\t\t\"reject-customer-invoice requires <batchId> --reason <text>\",\n\t\t);\n\t}\n\tawait rejectCustomerInvoice(batchId, String(reason));\n};\n\nconst commandSendCustomerInvoiceToContactPerson: CliCommandHandler = async ({\n\tflags,\n}) => {\n\tconst payloadRaw = getFlag(flags, \"payload\");\n\tif (!payloadRaw) {\n\t\tthrow new Error(\n\t\t\t\"send-customer-invoice-to-contact-person requires --payload '<json>'\",\n\t\t);\n\t}\n\tawait sendCustomerInvoiceToContactPersonFromPayload(\n\t\tparseJsonFlag<unknown>(String(payloadRaw), \"--payload\"),\n\t);\n};\n\nconst commandDownloadCustomerInvoicePdf: CliCommandHandler = async ({\n\tflags,\n\tpositional,\n}) => {\n\tconst invoiceId = positional[0];\n\tif (!invoiceId) {\n\t\tthrow new Error(\n\t\t\t\"download-customer-invoice-pdf requires <invoiceId> [--output <path>]\",\n\t\t);\n\t}\n\tawait downloadCustomerInvoicePdf(invoiceId, getFlag(flags, \"output\"));\n};\n\nconst commandUpdateCustomerInvoiceDetails: CliCommandHandler = async ({\n\tflags,\n\tpositional,\n}) => {\n\tconst invoiceId = positional[0];\n\tconst billingAddress = getFlag(flags, \"billingAddress\");\n\tconst customerMemo = getFlag(flags, \"customerMemo\");\n\tif (\n\t\t!invoiceId ||\n\t\ttypeof billingAddress !== \"string\" ||\n\t\ttypeof customerMemo !== \"string\"\n\t) {\n\t\tthrow new Error(\n\t\t\t\"update-customer-invoice-details requires <invoiceId> --billingAddress <text> --customerMemo <text> (send both; use \\\\n for address lines). The bill email is managed in QuickBooks.\",\n\t\t);\n\t}\n\tconst requestId = getFlag(flags, \"requestId\");\n\tawait updateCustomerInvoiceDetails({\n\t\tbillingAddress: billingAddress.replaceAll(\"\\\\n\", \"\\n\"),\n\t\tcustomerMemo,\n\t\tinvoiceId,\n\t\t...(typeof requestId === \"string\" ? { requestId } : {}),\n\t});\n};\n\nconst commandUpdateCustomerInvoiceQboDrift: CliCommandHandler = async ({\n\tflags,\n\tpositional,\n}) => {\n\tconst invoiceId = positional[0];\n\tconst resolution = getFlag(flags, \"resolution\");\n\tif (!invoiceId || (resolution !== \"ACCEPT_QBO\" && resolution !== \"KEEP_BB\")) {\n\t\tthrow new Error(\n\t\t\t\"update-customer-invoice-qbo-drift requires <invoiceId> --resolution ACCEPT_QBO|KEEP_BB\",\n\t\t);\n\t}\n\tconst requestId = getFlag(flags, \"requestId\");\n\tawait updateCustomerInvoiceQboDrift({\n\t\tinvoiceId,\n\t\tresolution,\n\t\t...(typeof requestId === \"string\" ? { requestId } : {}),\n\t});\n};\n\nconst commandMarkCustomerInvoiceSentExternally: CliCommandHandler = async ({\n\tflags,\n\tpositional,\n}) => {\n\tconst invoiceId = positional[0];\n\tconst sentAt = getFlag(flags, \"sentAt\");\n\tconst recipients = getFlag(flags, \"recipients\");\n\tif (!invoiceId || !sentAt || !recipients) {\n\t\tthrow new Error(\n\t\t\t\"mark-customer-invoice-sent-externally requires <invoiceId> --sentAt <ISO datetime> --recipients a@x.com,b@y.com [--note <text>]\",\n\t\t);\n\t}\n\tawait markCustomerInvoiceSentExternally({\n\t\tinvoiceId,\n\t\tsentAt,\n\t\trecipients: recipients\n\t\t\t.split(\",\")\n\t\t\t.map((recipient) => recipient.trim())\n\t\t\t.filter(Boolean),\n\t\tnote: getFlag(flags, \"note\"),\n\t});\n};\n\nconst commandSyncCustomerInvoice: CliCommandHandler = async ({\n\tpositional,\n}) => {\n\tconst invoiceId = positional[0];\n\tif (!invoiceId) {\n\t\tthrow new Error(\"sync-customer-invoice requires <invoiceId>\");\n\t}\n\tawait syncCustomerInvoice(invoiceId);\n};\n\nconst commandListApprovals: CliCommandHandler = async ({ flags }) => {\n\tconst typeRaw = getFlag(flags, \"type\");\n\tawait listApprovals({\n\t\ttype: parseApprovalTypeFlag(\n\t\t\ttypeRaw !== undefined ? String(typeRaw) : undefined,\n\t\t),\n\t});\n};\n\nconst commandApproveBill: CliCommandHandler = async ({ flags, positional }) => {\n\tconst id = positional[0];\n\tif (!id) throw new Error(\"approve-bill requires <billId>\");\n\tawait approveBill(id, getFlag(flags, \"overBudgetOverrideReason\"));\n};\n\nconst commandRejectBill: CliCommandHandler = async ({ flags, positional }) => {\n\tconst id = positional[0];\n\tconst reason = getFlag(flags, \"reason\");\n\tif (!id || reason === undefined) {\n\t\tthrow new Error(\"reject-bill requires <billId> --reason <text>\");\n\t}\n\tawait rejectBill(id, reason);\n};\n\nconst commandApproveBudget: CliCommandHandler = async ({ positional }) => {\n\tconst id = positional[0];\n\tif (!id) throw new Error(\"approve-budget requires <budgetId>\");\n\tawait approveBudget(id);\n};\n\nconst commandRejectBudget: CliCommandHandler = async ({\n\tflags,\n\tpositional,\n}) => {\n\tconst id = positional[0];\n\tconst reason = getFlag(flags, \"reason\");\n\tif (!id || reason === undefined) {\n\t\tthrow new Error(\"reject-budget requires <budgetId> --reason <text>\");\n\t}\n\tawait rejectBudget(id, reason);\n};\n\nconst commandApproveSupplier: CliCommandHandler = async ({ positional }) => {\n\tconst id = positional[0];\n\tif (!id) throw new Error(\"approve-supplier requires <supplierId>\");\n\tawait approveSupplier(id);\n};\n\nconst commandRejectSupplier: CliCommandHandler = async ({\n\tflags,\n\tpositional,\n}) => {\n\tconst id = positional[0];\n\tconst reason = getFlag(flags, \"reason\");\n\tif (!id || reason === undefined) {\n\t\tthrow new Error(\"reject-supplier requires <supplierId> --reason <text>\");\n\t}\n\tawait rejectSupplier(id, reason);\n};\n\nconst commandGetSupplierDetails: CliCommandHandler = async ({ positional }) => {\n\tconst id = positional[0];\n\tif (!id) throw new Error(\"get-supplier-details requires <supplierId>\");\n\tawait getSupplierDetails(id);\n};\n\nconst commandGetSupplierOverview: CliCommandHandler = async ({\n\tpositional,\n}) => {\n\tconst id = positional[0];\n\tif (!id) throw new Error(\"get-supplier-overview requires <supplierId>\");\n\tawait getSupplierOverview(id);\n};\n\nconst commandGetSupplierUsage: CliCommandHandler = async ({ positional }) => {\n\tconst id = positional[0];\n\tif (!id) throw new Error(\"get-supplier-usage requires <supplierId>\");\n\tawait getSupplierUsage(id);\n};\n\nconst commandGetSupplierItems: CliCommandHandler = async ({ positional }) => {\n\tconst id = positional[0];\n\tif (!id) throw new Error(\"get-supplier-items requires <supplierId>\");\n\tawait getSupplierItems(id);\n};\n\nconst commandListCompanies: CliCommandHandler = async ({ flags }) => {\n\tawait listCompanies(parseCompanyListFlags(flags));\n};\n\nconst commandCountCompanies: CliCommandHandler = async ({ flags }) => {\n\tawait countCompanies(parseCompanyCountFlags(flags));\n};\n\nconst commandGetCompany: CliCommandHandler = async ({ positional }) => {\n\tconst id = positional[0];\n\tif (!id) throw new Error(\"get-company requires <id>\");\n\tawait getCompany(id);\n};\n\nconst commandCreateCompany: CliCommandHandler = async ({ flags }) => {\n\trejectBareFlag(flags, \"billingEmails\");\n\tconst billingEmailsRaw = getFlag(flags, \"billingEmails\");\n\tconst billingEmails =\n\t\tbillingEmailsRaw === undefined\n\t\t\t? undefined\n\t\t\t: parseCompanyBillingEmails(\n\t\t\t\t\tparseJsonFlag<unknown>(billingEmailsRaw, \"--billingEmails\"),\n\t\t\t\t);\n\tconst name = getFlag(flags, \"name\");\n\tconst website = getFlag(flags, \"website\");\n\tif (!name || !website) {\n\t\tthrow new Error(\"create-company requires --name and --website <url>\");\n\t}\n\tawait createCompany({\n\t\tname,\n\t\twebsite,\n\t\t...(billingEmails === undefined ? {} : { billingEmails }),\n\t\tconfirmDistinct: parseOptionalBoolFlag(flags, \"confirmDistinct\"),\n\t});\n};\n\nconst commandSearchExistingCompanies: CliCommandHandler = async ({ flags }) => {\n\tconst query = getFlag(flags, \"query\");\n\tif (!query)\n\t\tthrow new Error(\"search-existing-companies requires --query <name>\");\n\trejectRetiredPageFlags(flags);\n\tfor (const key of [\"limit\", \"cursor\"]) rejectBareFlag(flags, key);\n\tconst cursor = getFlag(flags, \"cursor\");\n\tif (cursor === \"\" || (cursor?.length ?? 0) > 8192)\n\t\tthrow new Error(\n\t\t\t\"--cursor must be a non-empty opaque token of at most 8192 characters.\",\n\t\t);\n\tconst limitFlag = getFlag(flags, \"limit\");\n\tconst limit = limitFlag === undefined ? undefined : Number(limitFlag);\n\tif (\n\t\tlimit !== undefined &&\n\t\t(!Number.isInteger(limit) || limit < 1 || limit > 50)\n\t)\n\t\tthrow new Error(\"--limit must be an integer from 1 to 50.\");\n\tawait searchExistingCompanies({ query, limit, cursor });\n};\n\nconst commandUseExistingCompany: CliCommandHandler = async ({ flags }) => {\n\tconst companyId = getFlag(flags, \"companyId\");\n\tconst quickbooksId = getFlag(flags, \"quickbooksId\");\n\tif (!companyId && !quickbooksId)\n\t\tthrow new Error(\"Supply --companyId and/or --quickbooksId\");\n\tif (companyId)\n\t\tawait reuseExistingCompany({\n\t\t\tsource: \"bb\",\n\t\t\tcompanyId,\n\t\t\tquickbooksId,\n\t\t\tconfirmDistinct: parseOptionalBoolFlag(flags, \"confirmDistinct\"),\n\t\t});\n\telse if (quickbooksId)\n\t\tawait reuseExistingCompany({\n\t\t\tsource: \"qbo\",\n\t\t\tquickbooksId,\n\t\t\tname: getFlag(flags, \"name\"),\n\t\t\twebsite: getFlag(flags, \"website\"),\n\t\t\tconfirmDistinct: parseOptionalBoolFlag(flags, \"confirmDistinct\"),\n\t\t});\n};\n\nconst commandUpdateCompany: CliCommandHandler = async ({ flags }) => {\n\tconst payloadRaw = getFlag(flags, \"payload\");\n\tif (!payloadRaw) {\n\t\tthrow new Error(\"update-company requires --payload '<json>'\");\n\t}\n\tconst raw = parseJsonFlag<unknown>(String(payloadRaw), \"--payload\");\n\tawait updateCompanyFromPayload(raw);\n};\n\nconst commandGetCompanyQuickbooksSyncStatus: CliCommandHandler = async ({\n\tpositional,\n}) => {\n\tconst id = positional[0];\n\tif (!id)\n\t\tthrow new Error(\"get-company-quickbooks-sync-status requires <companyId>\");\n\tawait getCompanyQuickBooksSyncStatus(id);\n};\n\nconst commandDeleteCompany: CliCommandHandler = async ({ positional }) => {\n\tconst id = positional[0];\n\tif (!id) throw new Error(\"delete-company requires <id>\");\n\tawait deleteCompanyById(id);\n};\n\nconst commandListProjects: CliCommandHandler = async ({ flags }) => {\n\tawait listProjects(parseProjectListFlags(flags));\n};\n\nconst commandCountProjects: CliCommandHandler = async ({ flags }) => {\n\tawait countProjects(parseProjectCountFlags(flags));\n};\n\nconst commandListProjectHubs: CliCommandHandler = async ({ cmd, flags }) => {\n\trejectRetiredPageFlags(flags);\n\tconst filters = {\n\t\tq: getFlag(flags, \"q\"),\n\t\tstatuses: parseCommaSeparatedProjectStatuses(getFlag(flags, \"status\")),\n\t};\n\tif (cmd === \"count-project-hubs\") {\n\t\tfor (const key of [\"limit\", \"cursor\", \"direction\", \"sortBy\", \"sortDir\"])\n\t\t\tif (flags[key] !== undefined)\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`count-project-hubs does not accept --${key}; totals use filters only.`,\n\t\t\t\t);\n\t\tawait countProjectHubs(filters);\n\t\treturn;\n\t}\n\tfor (const key of [\"limit\", \"cursor\", \"direction\", \"sortBy\", \"sortDir\"])\n\t\trejectBareFlag(flags, key);\n\tconst cursor = getFlag(flags, \"cursor\");\n\tif (cursor === \"\" || (cursor?.length ?? 0) > 8192)\n\t\tthrow new Error(\n\t\t\t\"--cursor must be a non-empty opaque token of at most 8192 characters.\",\n\t\t);\n\tconst direction = parseProjectDirection(getFlag(flags, \"direction\"));\n\tif (direction === \"backward\" && !cursor)\n\t\tthrow new Error(\"--direction backward requires --cursor <token>.\");\n\tawait listProjectHubs({\n\t\t...filters,\n\t\tlimit: parseProjectLimit(getFlag(flags, \"limit\")),\n\t\tcursor,\n\t\tdirection,\n\t\tsortBy: parseOptionalProjectHubSortBy(getFlag(flags, \"sortBy\")),\n\t\tsortDir: parseOptionalBillListSortDir(getFlag(flags, \"sortDir\")),\n\t});\n};\n\nconst commandGetProject: CliCommandHandler = async ({ positional }) => {\n\tconst id = positional[0];\n\tif (!id) throw new Error(\"get-project requires <id>\");\n\tawait getProject(id);\n};\n\nconst commandGetProjectHubStatus: CliCommandHandler = async ({\n\tpositional,\n}) => {\n\tconst projectId = positional[0];\n\tif (!projectId) {\n\t\tthrow new Error(\"get-project-hub-status requires <projectId>\");\n\t}\n\tawait getProjectHubStatus(projectId);\n};\n\nconst commandSetupProjectHub: CliCommandHandler = async ({ positional }) => {\n\tconst projectId = positional[0];\n\tif (!projectId) {\n\t\tthrow new Error(\"setup-project-hub requires <projectId>\");\n\t}\n\tawait setupProjectHub(projectId);\n};\n\nconst commandSyncProjectHubCommercialDocuments: CliCommandHandler = async ({\n\tpositional,\n}) => {\n\tconst projectId = positional[0];\n\tif (!projectId) {\n\t\tthrow new Error(\n\t\t\t\"sync-project-hub-commercial-documents requires <projectId>\",\n\t\t);\n\t}\n\tawait syncProjectHubCommercialDocuments(projectId);\n};\n\nconst commandCreateProject: CliCommandHandler = async ({ flags }) => {\n\tconst name = getFlag(flags, \"name\");\n\tconst companyId = getFlag(flags, \"companyId\");\n\tconst contactPersonId = getFlag(flags, \"contactPersonId\");\n\tconst insideSalesId = getFlag(flags, \"insideSalesId\");\n\tconst businessDevelopmentId = getFlag(flags, \"businessDevelopmentId\");\n\tconst projectManagerId = getFlag(flags, \"projectManagerId\");\n\tconst venue = getFlag(flags, \"venue\");\n\tconst pax = getFlag(flags, \"pax\");\n\tconst asanaTaskId = getFlag(flags, \"asanaTaskId\");\n\tconst asanaSearch = getFlag(flags, \"asanaSearch\");\n\tconst slackChannelId = getFlag(flags, \"slackChannelId\");\n\tconst slackChannelUrl = getFlag(flags, \"slackChannelUrl\");\n\tconst slackChannelName = getFlag(flags, \"slackChannelName\");\n\tconst startDate = getFlag(flags, \"startDate\");\n\tif (getFlag(flags, \"requestQboAccountantNotification\") !== undefined) {\n\t\tthrow new Error(\n\t\t\t\"create-project does not allow --requestQboAccountantNotification; CLI project creation always requests the QuickBooks project import like the web app.\",\n\t\t);\n\t}\n\tif (\n\t\t!name ||\n\t\t!companyId ||\n\t\t!contactPersonId ||\n\t\t!insideSalesId ||\n\t\t!businessDevelopmentId ||\n\t\t!venue ||\n\t\t!startDate\n\t) {\n\t\tthrow new Error(\n\t\t\t\"create-project requires --name --companyId --contactPersonId --insideSalesId --businessDevelopmentId --venue --startDate (ISO/datetime flags as appropriate); optional --projectManagerId, --asanaTaskId, --asanaSearch, --pax and --endDate\",\n\t\t);\n\t}\n\tawait createProject({\n\t\tname,\n\t\tcompanyId,\n\t\tcontactPersonId,\n\t\tinsideSalesId,\n\t\tbusinessDevelopmentId,\n\t\tprojectManagerId,\n\t\tvenue,\n\t\tpax,\n\t\tasanaTaskId,\n\t\tasanaSearch,\n\t\tslackChannelId,\n\t\tslackChannelUrl,\n\t\tslackChannelName,\n\t\tstartDate,\n\t\tendDate: getFlag(flags, \"endDate\"),\n\t\tdescription: getFlag(flags, \"description\"),\n\t});\n};\n\nconst commandUpdateProject: CliCommandHandler = async ({ flags }) => {\n\tconst payloadRaw = getFlag(flags, \"payload\");\n\tif (!payloadRaw) {\n\t\tthrow new Error(\"update-project requires --payload '<json>'\");\n\t}\n\tconst raw = parseJsonFlag<unknown>(String(payloadRaw), \"--payload\");\n\tawait updateProjectFromPayload(raw);\n};\n\nconst commandDeleteProject: CliCommandHandler = async ({ positional }) => {\n\tconst id = positional[0];\n\tif (!id) throw new Error(\"delete-project requires <id>\");\n\tawait deleteProjectById(id);\n};\n\nconst commandCheckProjectReconciliation: CliCommandHandler = async ({\n\tpositional,\n}) => {\n\tconst id = positional[0];\n\tif (!id) {\n\t\tthrow new Error(\"check-project-reconciliation requires <id>\");\n\t}\n\tawait checkProjectReconciliation(id);\n};\n\nconst commandReconcileProject: CliCommandHandler = async ({ positional }) => {\n\tconst id = positional[0];\n\tif (!id) throw new Error(\"reconcile-project requires <id>\");\n\tawait reconcileProject(id);\n};\n\nconst commandCompleteProject: CliCommandHandler = async ({ positional }) => {\n\tconst id = positional[0];\n\tif (!id) throw new Error(\"complete-project requires <id>\");\n\tawait completeProject(id);\n};\n\nconst commandImportQboProject: CliCommandHandler = async ({\n\tflags,\n\tpositional,\n}) => {\n\tconst projectId = positional[0];\n\tconst projectUrl = getFlag(flags, \"url\");\n\tif (!projectId || projectUrl === undefined) {\n\t\tthrow new Error(\n\t\t\t\"import-qbo-project requires <projectId> --url <quickBooksProjectUrl>\",\n\t\t);\n\t}\n\tawait importQuickBooksProjectId(projectId, String(projectUrl));\n};\n\nconst commandUpdateProjectStatus: CliCommandHandler = async ({\n\tflags,\n\tpositional,\n}) => {\n\tconst [id, statusRaw] = positional;\n\tif (!id || !statusRaw) {\n\t\tthrow new Error(\"update-project-status requires <id> <status>\");\n\t}\n\tconst pmIdFlag = getFlag(flags, \"projectManagerId\");\n\tconst pmEmailFlag = getFlag(flags, \"projectManagerEmail\");\n\tawait updateProjectStatus(id, parseProjectStatusForUpdate(statusRaw), {\n\t\t...(pmIdFlag && { projectManagerId: String(pmIdFlag) }),\n\t\t...(pmEmailFlag && {\n\t\t\tprojectManagerEmail: String(pmEmailFlag),\n\t\t}),\n\t});\n};\n\nconst commandListContacts: CliCommandHandler = async ({ positional }) => {\n\tconst id = positional[0];\n\tif (!id) throw new Error(\"list-contacts requires <companyId>\");\n\tawait listContacts(id);\n};\n\nconst commandCreateContactPerson: CliCommandHandler = async ({ flags }) => {\n\tconst payloadRaw = getFlag(flags, \"payload\");\n\tif (!payloadRaw) {\n\t\tthrow new Error(\"create-contact-person requires --payload '<json>'\");\n\t}\n\tconst raw = parseJsonFlag<unknown>(String(payloadRaw), \"--payload\");\n\tawait createContactPersonFromPayload(raw);\n};\n\nconst commandUpdateContactPerson: CliCommandHandler = async ({ flags }) => {\n\tconst payloadRaw = getFlag(flags, \"payload\");\n\tif (!payloadRaw) {\n\t\tthrow new Error(\"update-contact-person requires --payload '<json>'\");\n\t}\n\tconst raw = parseJsonFlag<unknown>(String(payloadRaw), \"--payload\");\n\tawait updateContactPersonFromPayload(raw);\n};\n\nconst commandCountSuppliers: CliCommandHandler = async ({ flags }) => {\n\tawait countSuppliers(parseCountSuppliersFlags(flags));\n};\n\nconst commandListSuppliers: CliCommandHandler = async ({ flags }) => {\n\tawait listSuppliers(parseListSuppliersFlags(flags));\n};\n\nconst commandCreateSupplier: CliCommandHandler = async ({ flags }) => {\n\tconst payloadRaw = getFlag(flags, \"payload\");\n\tif (!payloadRaw) {\n\t\tthrow new Error(\"create-supplier requires --payload '<json>'\");\n\t}\n\tconst raw = parseJsonFlag<unknown>(String(payloadRaw), \"--payload\");\n\tawait createSupplierFromPayload(raw);\n};\n\nconst commandUpdateSupplier: CliCommandHandler = async ({ flags }) => {\n\tconst payloadRaw = getFlag(flags, \"payload\");\n\tif (!payloadRaw) {\n\t\tthrow new Error(\"update-supplier requires --payload '<json>'\");\n\t}\n\tconst raw = parseJsonFlag<unknown>(String(payloadRaw), \"--payload\");\n\tawait updateSupplierFromPayload(raw);\n};\n\nconst commandDeleteSuppliers: CliCommandHandler = async ({ flags }) => {\n\tconst idsRaw = getFlag(flags, \"ids\");\n\tif (idsRaw === undefined) {\n\t\tthrow new Error(\"delete-suppliers requires --ids <csv>\");\n\t}\n\tconst ids = parseCommaSeparatedIds(String(idsRaw));\n\tif (!ids?.length) {\n\t\tthrow new Error(\"delete-suppliers requires non-empty --ids\");\n\t}\n\tawait deleteSuppliersByIds(ids);\n};\n\nconst commandReactivateSuppliers: CliCommandHandler = async ({ flags }) => {\n\tconst idsRaw = getFlag(flags, \"ids\");\n\tif (idsRaw === undefined) {\n\t\tthrow new Error(\"reactivate-suppliers requires --ids <csv>\");\n\t}\n\tconst ids = parseCommaSeparatedIds(String(idsRaw));\n\tif (!ids?.length) {\n\t\tthrow new Error(\"reactivate-suppliers requires non-empty --ids\");\n\t}\n\tawait reactivateSuppliersByIds(ids);\n};\n\nconst commandCreateCertification: CliCommandHandler = async ({ flags }) => {\n\tconst name = getFlag(flags, \"name\");\n\tif (!name) throw new Error(\"create-certification requires --name\");\n\tawait createSupplierCertification(String(name));\n};\n\nconst commandCreatePaymentMethod: CliCommandHandler = async ({ flags }) => {\n\tconst name = getFlag(flags, \"name\");\n\tif (!name) throw new Error(\"create-payment-method requires --name\");\n\tawait createSupplierPaymentMethod(String(name));\n};\n\nconst commandCreateSupplierRole: CliCommandHandler = async ({ flags }) => {\n\tconst name = getFlag(flags, \"name\");\n\tif (!name) throw new Error(\"create-supplier-role requires --name\");\n\tawait createSupplierRoleOption(String(name));\n};\n\nconst commandCreateSupplierTag: CliCommandHandler = async ({ flags }) => {\n\tconst name = getFlag(flags, \"name\");\n\tif (!name) throw new Error(\"create-supplier-tag requires --name\");\n\tawait createSupplierTagOption(String(name));\n};\n\nconst supplierAnalyticsFiltersFromFlags = (\n\tflags: Record<string, string | true>,\n) => {\n\trejectRetiredPageFlags(flags);\n\tconst tfRaw = getFlag(flags, \"timeFrame\");\n\tfor (const key of [\n\t\t\"name\",\n\t\t\"status\",\n\t\t\"gstRegistered\",\n\t\t\"createdBy\",\n\t\t\"startDate\",\n\t\t\"endDate\",\n\t\t\"timeFrame\",\n\t])\n\t\trejectBareFlag(flags, key);\n\tconst timeFrame = parseOptionalSupplierAnalyticsTimeFrame(\n\t\ttfRaw !== undefined ? String(tfRaw) : undefined,\n\t);\n\tconst startDate = getFlag(flags, \"startDate\");\n\tconst endDate = getFlag(flags, \"endDate\");\n\tif ((startDate || endDate) && timeFrame !== \"CUSTOM\")\n\t\tthrow new Error(\n\t\t\t\"--startDate/--endDate need --timeFrame CUSTOM; other time frames ignore them.\",\n\t\t);\n\tconst statusRaw = getFlag(flags, \"status\");\n\tconst status = statusRaw\n\t\t?.split(\",\")\n\t\t.map((value) => value.trim())\n\t\t.filter(Boolean);\n\tconst badStatus = status?.find(\n\t\t(value) => !Object.values(ApprovalStatus).some((s) => s === value),\n\t);\n\tif (badStatus)\n\t\tthrow new Error(\n\t\t\t`Invalid --status ${badStatus}. Use a comma list of: ${Object.values(ApprovalStatus).join(\", \")}.`,\n\t\t);\n\tconst gstRaw = getFlag(flags, \"gstRegistered\");\n\tif (gstRaw !== undefined && gstRaw !== \"true\" && gstRaw !== \"false\")\n\t\tthrow new Error(\"--gstRegistered must be true or false.\");\n\treturn {\n\t\tname: getFlag(flags, \"name\"),\n\t\ttimeFrame,\n\t\tstatus: status?.length\n\t\t\t? (status as (typeof ApprovalStatus)[keyof typeof ApprovalStatus][])\n\t\t\t: undefined,\n\t\tgstRegistered: gstRaw === undefined ? undefined : gstRaw === \"true\",\n\t\tcreatedBy: getFlag(flags, \"createdBy\"),\n\t\tstartDate,\n\t\tendDate,\n\t};\n};\n\nconst commandGetSupplierAnalytics: CliCommandHandler = async ({\n\tcmd,\n\tflags,\n}) => {\n\tconst filters = supplierAnalyticsFiltersFromFlags(flags);\n\tif (cmd === \"count-supplier-analytics\") {\n\t\trejectCountPagingFlags(flags, \"count-supplier-analytics\");\n\t\tawait countSupplierAnalytics(filters);\n\t\treturn;\n\t}\n\trejectBarePagingFlags(flags);\n\tconst { cursor, direction } = parseCursorAndDirection(flags);\n\tconst sortBy = getFlag(flags, \"sortBy\");\n\tif (\n\t\tsortBy !== undefined &&\n\t\t!SUPPLIER_ANALYTICS_SORT_IDS.some((id) => id === sortBy)\n\t)\n\t\tthrow new Error(\n\t\t\t`--sortBy must be one of: ${SUPPLIER_ANALYTICS_SORT_IDS.join(\", \")}.`,\n\t\t);\n\tawait getSupplierAnalytics({\n\t\t...filters,\n\t\tlimit: parseProjectLimit(getFlag(flags, \"limit\")),\n\t\tcursor,\n\t\tdirection,\n\t\tsortBy: SUPPLIER_ANALYTICS_SORT_IDS.find((id) => id === sortBy),\n\t\tsortDir: parseOptionalBillListSortDir(getFlag(flags, \"sortDir\")),\n\t});\n};\n\nconst commandListItems: CliCommandHandler = async ({ cmd, flags }) => {\n\trejectRetiredPageFlags(flags);\n\tconst filters = {\n\t\tincludeQuickBooksDeactivationPending:\n\t\t\tflags.includeQuickBooksDeactivationPending === true\n\t\t\t\t? true\n\t\t\t\t: parseOptionalBoolFlag(flags, \"includeQuickBooksDeactivationPending\"),\n\t\tname: getFlag(flags, \"name\"),\n\t};\n\tif (cmd === \"count-items\") {\n\t\trejectCountPagingFlags(flags, \"count-items\");\n\t\tawait countItems(filters);\n\t\treturn;\n\t}\n\trejectBarePagingFlags(flags);\n\tconst { cursor, direction } = parseCursorAndDirection(flags);\n\tconst sortBy = getFlag(flags, \"sortBy\");\n\tconst sortId = INVENTORY_SORT_IDS.find((id) => id === sortBy);\n\tif (sortBy !== undefined && !sortId)\n\t\tthrow new Error(\n\t\t\t`Invalid --sortBy \"${sortBy}\". Use one of: ${INVENTORY_SORT_IDS.join(\", \")}.`,\n\t\t);\n\tconst sortDir = parseAscDescSortDir(flags);\n\tawait listItems({\n\t\t...filters,\n\t\tlimit: parseProjectLimit(getFlag(flags, \"limit\")),\n\t\tcursor,\n\t\tdirection,\n\t\tsort: sortId ? [{ id: sortId, desc: sortDir !== \"asc\" }] : undefined,\n\t});\n};\n\nconst commandGetItem: CliCommandHandler = async ({ positional }) => {\n\tconst id = positional[0];\n\tif (!id) throw new Error(\"get-item requires <id>\");\n\tawait getItem(id);\n};\n\nconst commandGetItemQuickbooksSyncStatus: CliCommandHandler = async ({\n\tpositional,\n}) => {\n\tconst id = positional[0];\n\tif (!id) {\n\t\tthrow new Error(\"get-item-quickbooks-sync-status requires <itemId>\");\n\t}\n\tawait getItemQuickBooksSyncStatus(id);\n};\n\nconst commandCreateItem: CliCommandHandler = async ({ flags }) => {\n\tconst payloadRaw = getFlag(flags, \"payload\");\n\tif (!payloadRaw) {\n\t\tthrow new Error(\"create-item requires --payload '<json>'\");\n\t}\n\tconst raw = parseJsonFlag<unknown>(String(payloadRaw), \"--payload\");\n\tawait createItemFromPayload(raw);\n};\n\nconst commandUpdateItem: CliCommandHandler = async ({ flags }) => {\n\tconst payloadRaw = getFlag(flags, \"payload\");\n\tif (!payloadRaw) {\n\t\tthrow new Error(\"update-item requires --payload '<json>'\");\n\t}\n\tconst raw = parseJsonFlag<unknown>(String(payloadRaw), \"--payload\");\n\tawait updateItemFromPayload(raw);\n};\n\nconst commandDeleteItem: CliCommandHandler = async ({ positional }) => {\n\tconst id = positional[0];\n\tif (!id) throw new Error(\"delete-item requires <id>\");\n\tawait deleteItemById(id);\n};\n\nconst commandArchiveItems: CliCommandHandler = async ({ flags }) => {\n\tconst idsRaw = getFlag(flags, \"ids\");\n\tif (!idsRaw) {\n\t\tthrow new Error(\"archive-items requires --ids <csv>\");\n\t}\n\tconst ids = parseCommaSeparatedIds(String(idsRaw));\n\tif (!ids?.length) {\n\t\tthrow new Error(\"archive-items requires non-empty --ids\");\n\t}\n\tawait archiveItemsByIds(ids);\n};\n\nconst commandListItemCategories: CliCommandHandler = async ({ cmd, flags }) => {\n\trejectRetiredPageFlags(flags);\n\tconst filters = { name: getFlag(flags, \"name\") };\n\tif (cmd === \"count-item-categories\") {\n\t\trejectCountPagingFlags(flags, \"count-item-categories\");\n\t\tawait countItemCategories(filters);\n\t\treturn;\n\t}\n\trejectBarePagingFlags(flags);\n\tconst { cursor, direction } = parseCursorAndDirection(flags);\n\tconst sortByRaw = getFlag(flags, \"sortBy\");\n\tconst sortBy = ITEM_CATEGORY_SORT_IDS.find((id) => id === sortByRaw);\n\tif (sortByRaw !== undefined && !sortBy)\n\t\tthrow new Error(\n\t\t\t`Invalid --sortBy \"${sortByRaw}\". Use one of: ${ITEM_CATEGORY_SORT_IDS.join(\", \")}.`,\n\t\t);\n\tconst sortDir = parseAscDescSortDir(flags);\n\tawait listItemCategories({\n\t\t...filters,\n\t\tlimit: parseProjectLimit(getFlag(flags, \"limit\")),\n\t\tcursor,\n\t\tdirection,\n\t\tsortBy,\n\t\tsortDir,\n\t});\n};\n\nconst commandCreateItemCategory: CliCommandHandler = async ({ flags }) => {\n\tconst name = getFlag(flags, \"name\");\n\tif (!name) throw new Error(\"create-item-category requires --name\");\n\tawait createItemCategory(String(name));\n};\n\nconst commandUpdateItemCategory: CliCommandHandler = async ({ flags }) => {\n\tconst id = getFlag(flags, \"id\");\n\tconst name = getFlag(flags, \"name\");\n\tif (!id || !name) {\n\t\tthrow new Error(\"update-item-category requires --id and --name\");\n\t}\n\tawait updateItemCategory({ id: String(id), name: String(name) });\n};\n\nconst commandDeleteItemCategories: CliCommandHandler = async ({ flags }) => {\n\tconst idsRaw = getFlag(flags, \"ids\");\n\tif (idsRaw === undefined) {\n\t\tthrow new Error(\"delete-item-categories requires --ids <csv>\");\n\t}\n\tconst ids = parseCommaSeparatedIds(String(idsRaw));\n\tif (!ids?.length) {\n\t\tthrow new Error(\"delete-item-categories requires non-empty --ids\");\n\t}\n\tawait deleteItemCategoriesByIds(ids);\n};\n\nconst commandListUsers: CliCommandHandler = async ({ cmd, flags }) => {\n\trejectRetiredPageFlags(flags);\n\tconst q = getFlag(flags, \"q\");\n\trejectBareFlag(flags, \"projectTeamOnly\");\n\tconst projectTeamOnly = parseOptionalBoolFlag(flags, \"projectTeamOnly\");\n\tif (cmd === \"count-users\") {\n\t\tfor (const key of [\"limit\", \"cursor\"])\n\t\t\tif (flags[key] !== undefined)\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`count-users does not accept --${key}; totals use --q and --projectTeamOnly only.`,\n\t\t\t\t);\n\t\tawait countUsers({ q, projectTeamOnly });\n\t\treturn;\n\t}\n\tfor (const key of [\"limit\", \"cursor\"]) rejectBareFlag(flags, key);\n\tif (flags.direction !== undefined)\n\t\tthrow new Error(\n\t\t\t\"list-users pages forward only; follow pageInfo.nextCursor with --cursor.\",\n\t\t);\n\tconst cursor = getFlag(flags, \"cursor\");\n\tif (cursor === \"\" || (cursor?.length ?? 0) > 8192)\n\t\tthrow new Error(\n\t\t\t\"--cursor must be a non-empty opaque token of at most 8192 characters.\",\n\t\t);\n\tawait listUsers({\n\t\tq,\n\t\tprojectTeamOnly,\n\t\tlimit: parseProjectLimit(getFlag(flags, \"limit\")),\n\t\tcursor,\n\t});\n};\n\nconst commandCreateUser: CliCommandHandler = async ({ flags }) => {\n\tconst email = getFlag(flags, \"email\");\n\tif (!email) {\n\t\tthrow new Error(\n\t\t\t`create-user requires --email <email> [--name <name>] [--role ${userRolesForHelp.join(\"|\")}]`,\n\t\t);\n\t}\n\tawait createUser({\n\t\temail,\n\t\tname: getFlag(flags, \"name\"),\n\t\trole: parseUserRole(getFlag(flags, \"role\")),\n\t});\n};\n\nconst commandCreateApiKey: CliCommandHandler = async ({ flags }) => {\n\tconst userId = getFlag(flags, \"userId\");\n\tconst name = getFlag(flags, \"name\");\n\tif (!name) {\n\t\tthrow new Error(\n\t\t\t\"create-api-key requires --name <label> [--userId <userId>]\",\n\t\t);\n\t}\n\tawait createApiKeyForUser({ userId, name });\n};\n\nconst commandListApiKeys: CliCommandHandler = async ({ flags }) => {\n\trejectRetiredPageFlags(flags);\n\tfor (const key of [\"limit\", \"cursor\"]) rejectBareFlag(flags, key);\n\tif (flags.direction !== undefined)\n\t\tthrow new Error(\n\t\t\t\"list-api-keys pages forward only; follow pageInfo.nextCursor with --cursor.\",\n\t\t);\n\tconst cursor = getFlag(flags, \"cursor\");\n\tif (cursor === \"\" || (cursor?.length ?? 0) > 8192)\n\t\tthrow new Error(\n\t\t\t\"--cursor must be a non-empty opaque token of at most 8192 characters.\",\n\t\t);\n\tconst limitFlag = getFlag(flags, \"limit\");\n\tconst limit = limitFlag === undefined ? undefined : Number(limitFlag);\n\tif (\n\t\tlimit !== undefined &&\n\t\t(!Number.isInteger(limit) || limit < 1 || limit > 100)\n\t)\n\t\tthrow new Error(\"--limit must be an integer from 1 to 100.\");\n\tawait listApiKeysForUser({\n\t\tuserId: getFlag(flags, \"userId\"),\n\t\tlimit,\n\t\tcursor,\n\t});\n};\n\nconst commandRevokeApiKey: CliCommandHandler = async ({\n\tflags,\n\tpositional,\n}) => {\n\tconst id = positional[0];\n\tif (!id) {\n\t\tthrow new Error(\"revoke-api-key requires <apiKeyId> [--userId <userId>]\");\n\t}\n\tawait revokeApiKeyForUser({\n\t\tid,\n\t\tuserId: getFlag(flags, \"userId\"),\n\t});\n};\n\nconst commandGetUserPerformance: CliCommandHandler = async ({ flags }) => {\n\tawait getUserPerformance(getFlag(flags, \"userId\"));\n};\n\nconst commandGetDashboard: CliCommandHandler = async ({ flags }) => {\n\tawait getDashboard(parseDashboardQueryFlags(flags));\n};\n\nconst commandGetMonthlyMetrics: CliCommandHandler = async ({ flags }) => {\n\tawait getMonthlyMetrics(parseDashboardQueryFlags(flags));\n};\n\nconst commandGetSystemOverview: CliCommandHandler = async ({ flags }) => {\n\tawait getSystemOverview(parseDashboardQueryFlags(flags));\n};\n\nconst commandGetEstimatePerformance: CliCommandHandler = async ({ flags }) => {\n\tawait getEstimatePerformance(parseDashboardQueryFlags(flags));\n};\n\nconst commandGetFinancialOverview: CliCommandHandler = async ({ flags }) => {\n\tawait getFinancialOverview({\n\t\tuserId: getFlag(flags, \"userId\"),\n\t\trole: parseOptionalFinancialRole(getFlag(flags, \"role\")),\n\t\tdeals: parseOptionalDeals(getFlag(flags, \"deals\")),\n\t\ttimeFrame: parseOptionalTimeFrame(getFlag(flags, \"timeFrame\")),\n\t\tstartDate: getFlag(flags, \"startDate\"),\n\t\tendDate: getFlag(flags, \"endDate\"),\n\t});\n};\n\nconst commandGetRecentErrors: CliCommandHandler = async ({ cmd, flags }) => {\n\tif (\n\t\tgetFlag(flags, \"page\") !== undefined ||\n\t\tgetFlag(flags, \"perPage\") !== undefined\n\t) {\n\t\tthrow new Error(\n\t\t\t\"Error logs now use --cursor and --limit; --page/--perPage are no longer supported.\",\n\t\t);\n\t}\n\tconst rawTimeFrame = getFlag(flags, \"timeFrame\");\n\tconst timeFrame = Object.values(ChartTimeFrame).find(\n\t\t(value) => value === rawTimeFrame,\n\t);\n\tif (rawTimeFrame !== undefined && timeFrame === undefined) {\n\t\tthrow new Error(\n\t\t\t`Invalid --timeFrame. Use ${Object.values(ChartTimeFrame).join(\", \")}.`,\n\t\t);\n\t}\n\tconst filters = {\n\t\tseverity: parseOptionalErrorSeverity(getFlag(flags, \"severity\")),\n\t\tstatus: parseOptionalErrorStatus(getFlag(flags, \"status\")),\n\t\ttimeFrame,\n\t};\n\tif (cmd === \"count-errors\") {\n\t\tawait countErrors(filters);\n\t} else {\n\t\tconst direction = getFlag(flags, \"direction\");\n\t\tif (\n\t\t\tdirection !== undefined &&\n\t\t\tdirection !== \"forward\" &&\n\t\t\tdirection !== \"backward\"\n\t\t) {\n\t\t\tthrow new Error(\"--direction must be forward or backward.\");\n\t\t}\n\t\tawait getRecentErrors({\n\t\t\t...filters,\n\t\t\tcursor: getFlag(flags, \"cursor\"),\n\t\t\tlimit: parsePositiveIntFlag(getFlag(flags, \"limit\"), \"--limit\"),\n\t\t\tdirection,\n\t\t});\n\t}\n};\n\nconst commandGetError: CliCommandHandler = async ({ positional }) => {\n\tconst id = positional[0];\n\tif (!id) throw new Error(\"get-error requires <errorId>\");\n\tawait getError(id);\n};\n\nconst commandGetErrorMetrics: CliCommandHandler = async () => {\n\tawait getErrorMetrics();\n};\n\nconst commandListIntegrationOperations: CliCommandHandler = async ({\n\tcmd,\n\tflags,\n}) => {\n\trejectRetiredPageFlags(flags);\n\tconst filters = {\n\t\tdestination: parseCommaSeparatedIds(getFlag(flags, \"destination\")),\n\t\tsearch: getFlag(flags, \"search\"),\n\t\tstatus: parseCommaSeparatedIntegrationOperationStatuses(\n\t\t\tgetFlag(flags, \"status\"),\n\t\t),\n\t};\n\tif (cmd === \"count-integration-operations\") {\n\t\tfor (const key of [\"limit\", \"cursor\", \"direction\"])\n\t\t\tif (flags[key] !== undefined)\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`count-integration-operations does not accept --${key}; it takes filter flags only.`,\n\t\t\t\t);\n\t\tawait countIntegrationOperations(filters);\n\t\treturn;\n\t}\n\tfor (const key of [\"limit\", \"cursor\", \"direction\"])\n\t\trejectBareFlag(flags, key);\n\tconst cursor = getFlag(flags, \"cursor\");\n\tif (cursor === \"\" || (cursor?.length ?? 0) > 8192)\n\t\tthrow new Error(\n\t\t\t\"--cursor must be a non-empty opaque token of at most 8192 characters.\",\n\t\t);\n\tconst direction = parseProjectDirection(getFlag(flags, \"direction\"));\n\tif (direction === \"backward\" && !cursor)\n\t\tthrow new Error(\"--direction backward requires --cursor <token>.\");\n\tconst limitRaw = getFlag(flags, \"limit\");\n\tawait listIntegrationOperations({\n\t\t...filters,\n\t\tlimit: limitRaw === undefined ? 25 : parseProjectLimit(limitRaw),\n\t\tcursor,\n\t\tdirection,\n\t});\n};\n\nconst commandGetIntegrationOperation: CliCommandHandler = async ({\n\tpositional,\n}) => {\n\tconst operationId = positional[0];\n\tif (!operationId) {\n\t\tthrow new Error(\"get-integration-operation requires <operationId>\");\n\t}\n\tawait getIntegrationOperation(operationId);\n};\n\nconst commandRetryIntegrationOperation: CliCommandHandler = async ({\n\tflags,\n\tpositional,\n}) => {\n\tconst operationId = positional[0];\n\tif (!operationId) {\n\t\tthrow new Error(\"retry-integration-operation requires <operationId>\");\n\t}\n\tconst outboundEmailResolution = getFlag(flags, \"outboundEmailResolution\");\n\tif (\n\t\toutboundEmailResolution &&\n\t\toutboundEmailResolution !== \"ACCEPTED\" &&\n\t\toutboundEmailResolution !== \"NOT_ACCEPTED_RETRY\"\n\t) {\n\t\tthrow new Error(\n\t\t\t\"--outboundEmailResolution must be ACCEPTED or NOT_ACCEPTED_RETRY\",\n\t\t);\n\t}\n\tawait retryIntegrationOperation(\n\t\toperationId,\n\t\tparseOptionalBoolFlag(flags, \"confirmExternalStateReconciled\") ?? false,\n\t\toutboundEmailResolution as \"ACCEPTED\" | \"NOT_ACCEPTED_RETRY\" | undefined,\n\t\tgetFlag(flags, \"providerMessageId\"),\n\t);\n};\n\nconst commandListWebhookEventTypes: CliCommandHandler = async () => {\n\tawait listWebhookEventTypes();\n};\n\nconst commandListWebhookEndpoints: CliCommandHandler = async () => {\n\tawait listWebhookEndpoints();\n};\n\nconst commandGetWebhookEndpoint: CliCommandHandler = async ({ positional }) => {\n\tconst id = positional[0];\n\tif (!id) throw new Error(\"get-webhook-endpoint requires <id>\");\n\tawait getWebhookEndpoint(id);\n};\n\nconst commandCreateWebhookEndpoint: CliCommandHandler = async ({ flags }) => {\n\tconst name = getFlag(flags, \"name\");\n\tconst url = getFlag(flags, \"url\");\n\tconst events = parseCommaSeparatedIds(getFlag(flags, \"events\"));\n\tif (!name || !url || !events?.length)\n\t\tthrow new Error(\n\t\t\t\"create-webhook-endpoint requires --name, --url and --events\",\n\t\t);\n\tawait createWebhookEndpoint({\n\t\tname,\n\t\turl,\n\t\teventPatterns: events,\n\t\tenabled: parseOptionalBoolFlag(flags, \"enabled\") ?? true,\n\t});\n};\n\nconst commandUpdateWebhookEndpoint: CliCommandHandler = async ({\n\tflags,\n\tpositional,\n}) => {\n\tconst id = positional[0];\n\tif (!id) throw new Error(\"update-webhook-endpoint requires <id>\");\n\tconst events = parseCommaSeparatedIds(getFlag(flags, \"events\"));\n\tawait updateWebhookEndpoint({\n\t\tid,\n\t\tname: getFlag(flags, \"name\"),\n\t\turl: getFlag(flags, \"url\"),\n\t\teventPatterns: events?.length ? events : undefined,\n\t\tenabled: parseOptionalBoolFlag(flags, \"enabled\"),\n\t});\n};\n\nconst commandDeleteWebhookEndpoint: CliCommandHandler = async ({\n\tpositional,\n}) => {\n\tconst id = positional[0];\n\tif (!id) throw new Error(\"delete-webhook-endpoint requires <id>\");\n\tawait deleteWebhookEndpoint(id);\n};\n\nconst commandRotateWebhookSecret: CliCommandHandler = async ({\n\tflags,\n\tpositional,\n}) => {\n\tconst id = positional[0];\n\tif (!id) throw new Error(\"rotate-webhook-secret requires <id>\");\n\tconst ttl = getFlag(flags, \"previousSecretTtlHours\");\n\tawait rotateWebhookSecret({\n\t\tid,\n\t\tpreviousSecretTtlHours:\n\t\t\tttl === undefined ? undefined : Number.parseInt(ttl, 10),\n\t});\n};\n\nconst commandSendWebhookTestEvent: CliCommandHandler = async ({\n\tpositional,\n}) => {\n\tconst id = positional[0];\n\tif (!id) throw new Error(\"send-webhook-test-event requires <id>\");\n\tawait sendWebhookTestEvent(id);\n};\n\nconst commandListWebhookDeliveries: CliCommandHandler = async ({ flags }) => {\n\tconst statuses = (getFlag(flags, \"status\") ?? \"\")\n\t\t.split(\",\")\n\t\t.map((value) => value.trim())\n\t\t.filter(Boolean);\n\tfor (const status of statuses)\n\t\tif (status !== \"PENDING\" && status !== \"SUCCEEDED\" && status !== \"FAILED\")\n\t\t\tthrow new Error(\n\t\t\t\t\"--status must be PENDING, SUCCEEDED or FAILED (comma-separated)\",\n\t\t\t);\n\tconst cursor = getFlag(flags, \"cursor\");\n\tconst direction = parseProjectDirection(getFlag(flags, \"direction\"));\n\tif (direction === \"backward\" && !cursor)\n\t\tthrow new Error(\"--direction backward requires --cursor <token>.\");\n\tawait listWebhookDeliveries({\n\t\tendpointId: getFlag(flags, \"endpointId\"),\n\t\t...(statuses.length\n\t\t\t? {\n\t\t\t\t\tstatus: statuses as Array<\"PENDING\" | \"SUCCEEDED\" | \"FAILED\">,\n\t\t\t\t}\n\t\t\t: {}),\n\t\teventType: getFlag(flags, \"eventType\"),\n\t\tcursor,\n\t\tdirection,\n\t\tlimit: parsePositiveIntFlag(getFlag(flags, \"limit\"), \"--limit\"),\n\t});\n};\n\nconst commandGetWebhookDelivery: CliCommandHandler = async ({ positional }) => {\n\tconst id = positional[0];\n\tif (!id) throw new Error(\"get-webhook-delivery requires <id>\");\n\tawait getWebhookDelivery(id);\n};\n\nconst commandReplayWebhookDelivery: CliCommandHandler = async ({\n\tpositional,\n}) => {\n\tconst id = positional[0];\n\tif (!id) throw new Error(\"replay-webhook-delivery requires <id>\");\n\tawait replayWebhookDelivery(id);\n};\n\nconst commandReconcileResourceOperation: CliCommandHandler = async ({\n\tpositional,\n}) => {\n\tconst operationId = positional[0];\n\tif (!operationId) {\n\t\tthrow new Error(\"reconcile-resource-operation requires <operationId>\");\n\t}\n\tawait reconcileResourceOperation(operationId);\n};\n\nconst inboundSourceFiltersFromFlags = (\n\tflags: Record<string, string | true>,\n) => {\n\tif (flags.page !== undefined || flags.perPage !== undefined)\n\t\tthrow new Error(\n\t\t\t\"Inbound sources now use --limit/--cursor/--direction; --page/--perPage are no longer supported.\",\n\t\t);\n\tfor (const key of [\"search\", \"processingMode\", \"cursor\", \"direction\"]) {\n\t\tif (flags[key] === true) throw new Error(`--${key} requires a value.`);\n\t}\n\tconst enabled = flags.processingEnabled;\n\tif (enabled !== undefined && enabled !== \"true\" && enabled !== \"false\")\n\t\tthrow new Error(\"--processingEnabled must be true or false.\");\n\tconst mode = getFlag(flags, \"processingMode\");\n\tconst processingMode = Object.values(InboundProcessingMode).find(\n\t\t(value) => value === mode,\n\t);\n\tif (mode !== undefined && processingMode === undefined)\n\t\tthrow new Error(\n\t\t\t\"Invalid --processingMode. Use ACTIVE, COLLECT_ONLY or SHADOW.\",\n\t\t);\n\treturn {\n\t\tsearch: getFlag(flags, \"search\"),\n\t\tprocessingEnabled: enabled === undefined ? undefined : enabled === \"true\",\n\t\tprocessingMode,\n\t};\n};\n\nconst parseInboundSourcePaging = (\n\tflags: Record<string, string | true>,\n): {\n\tcursor: string | undefined;\n\tdirection: \"forward\" | \"backward\";\n\tlimit: number;\n} => {\n\tconst rawDirection = getFlag(flags, \"direction\") ?? \"forward\";\n\tif (rawDirection !== \"forward\" && rawDirection !== \"backward\")\n\t\tthrow new Error(\"--direction must be forward or backward.\");\n\tconst direction = rawDirection;\n\tconst cursor = getFlag(flags, \"cursor\");\n\tif (direction === \"backward\" && !cursor)\n\t\tthrow new Error(\"Backward source pagination requires --cursor.\");\n\tconst rawLimit = flags.limit;\n\tconst limit = rawLimit === undefined ? 25 : Number(rawLimit);\n\tif (rawLimit === true || !Number.isInteger(limit) || limit < 1 || limit > 100)\n\t\tthrow new Error(\"--limit must be an integer between 1 and 100.\");\n\treturn { cursor, direction, limit };\n};\n\nconst commandListInboundSources: CliCommandHandler = async ({ cmd, flags }) => {\n\tconst filters = inboundSourceFiltersFromFlags(flags);\n\tif (cmd === \"count-inbound-sources\") {\n\t\tif (\n\t\t\t[\"limit\", \"cursor\", \"direction\"].some((key) => flags[key] !== undefined)\n\t\t)\n\t\t\tthrow new Error(\n\t\t\t\t\"Source counts accept filters only, not pagination flags.\",\n\t\t\t);\n\t\tawait countInboundSources(filters);\n\t} else {\n\t\tconst { cursor, direction, limit } = parseInboundSourcePaging(flags);\n\t\tawait listInboundSources({\n\t\t\t...filters,\n\t\t\tcursor,\n\t\t\tdirection,\n\t\t\tlimit,\n\t\t});\n\t}\n};\n\nconst commandCreateInboundSource: CliCommandHandler = async ({ flags }) => {\n\tconst name = getFlag(flags, \"name\");\n\tconst externalSourceId = getFlag(flags, \"formId\");\n\tif (!name || !externalSourceId) {\n\t\tthrow new Error(\n\t\t\t\"create-inbound-source requires --name <name> --formId <Typeform form ID>\",\n\t\t);\n\t}\n\tawait createInboundSource({ externalSourceId, name });\n};\n\nconst commandGetInboundSource: CliCommandHandler = async ({ positional }) => {\n\tconst sourceId = positional[0];\n\tif (!sourceId) throw new Error(\"get-inbound-source requires <sourceId>\");\n\tawait getInboundSource(sourceId);\n};\n\nconst commandUpdateInboundSource: CliCommandHandler = async ({\n\tflags,\n\tpositional,\n}) => {\n\tconst sourceId = positional[0];\n\tconst name = getFlag(flags, \"name\");\n\tif (!sourceId || !name) {\n\t\tthrow new Error(\"update-inbound-source requires <sourceId> --name <name>\");\n\t}\n\tawait updateInboundSource(sourceId, name);\n};\n\nconst commandListInboundSubmissions: CliCommandHandler = async ({ flags }) => {\n\tif (\n\t\tgetFlag(flags, \"page\") !== undefined ||\n\t\tgetFlag(flags, \"perPage\") !== undefined\n\t) {\n\t\tthrow new Error(\n\t\t\t\"Inbound submissions now use --limit and --cursor; --page/--perPage are no longer supported.\",\n\t\t);\n\t}\n\tawait listInboundSubmissions({\n\t\tcursor: getFlag(flags, \"cursor\"),\n\t\tlimit: parsePositiveIntFlag(getFlag(flags, \"limit\"), \"--limit\") ?? 25,\n\t\tsourceId: getFlag(flags, \"sourceId\"),\n\t});\n};\n\nconst commandCountInboundSubmissions: CliCommandHandler = async ({ flags }) => {\n\tawait countInboundSubmissions({ sourceId: getFlag(flags, \"sourceId\") });\n};\n\nconst commandGetInboundSubmission: CliCommandHandler = async ({\n\tpositional,\n}) => {\n\tconst submissionId = positional[0];\n\tif (!submissionId) {\n\t\tthrow new Error(\"get-inbound-submission requires <submissionId>\");\n\t}\n\tawait getInboundSubmission(submissionId);\n};\n\nconst commandSaveInboundMapping: CliCommandHandler = async ({\n\tflags,\n\tpositional,\n}) => {\n\tconst sourceId = positional[0];\n\tconst payloadRaw = getFlag(flags, \"payload\");\n\tif (!sourceId || payloadRaw === undefined) {\n\t\tthrow new Error(\n\t\t\t\"save-inbound-mapping requires <sourceId> --payload <JSON array>\",\n\t\t);\n\t}\n\tconst mappings = parseJsonFlag<\n\t\tRouterInputs[\"inbound\"][\"saveMappingVersion\"][\"mappings\"]\n\t>(String(payloadRaw), \"--payload\");\n\tawait saveInboundMappingVersion(sourceId, mappings);\n};\n\nconst commandSaveInboundAutomationConfig: CliCommandHandler = async ({\n\tflags,\n\tpositional,\n}) => {\n\tconst sourceId = positional[0];\n\tconst payloadRaw = getFlag(flags, \"payload\");\n\tif (!sourceId || payloadRaw === undefined) {\n\t\tthrow new Error(\n\t\t\t\"save-inbound-automation-config requires <sourceId> --payload <JSON object>\",\n\t\t);\n\t}\n\tconst config = parseJsonFlag<\n\t\tOmit<RouterInputs[\"inbound\"][\"saveAutomationConfig\"], \"sourceId\">\n\t>(String(payloadRaw), \"--payload\");\n\tawait saveInboundAutomationConfig({ ...config, sourceId });\n};\n\nconst commandUpdateInboundProcessing: CliCommandHandler = async ({\n\tflags,\n\tpositional,\n}) => {\n\tconst sourceId = positional[0];\n\tconst mode = getFlag(flags, \"mode\");\n\tconst enabled = parseOptionalBoolFlag(flags, \"enabled\");\n\tif (\n\t\t!sourceId ||\n\t\t!mode ||\n\t\tenabled === undefined ||\n\t\t!Object.values(InboundProcessingMode).includes(\n\t\t\tString(mode) as InboundProcessingMode,\n\t\t)\n\t) {\n\t\tthrow new Error(\n\t\t\t\"update-inbound-processing requires <sourceId> --mode COLLECT_ONLY|SHADOW|ACTIVE --enabled true|false\",\n\t\t);\n\t}\n\tawait updateInboundProcessing({\n\t\tprocessingEnabled: enabled,\n\t\tprocessingMode: String(mode) as InboundProcessingMode,\n\t\tsourceId,\n\t});\n};\n\nconst commandGetApprovedBudgets: CliCommandHandler = async ({ flags }) => {\n\tawait getApprovedBudgets({\n\t\tprojectId: getFlag(flags, \"projectId\"),\n\t\tlimit: parsePositiveIntFlag(getFlag(flags, \"limit\"), \"--limit\"),\n\t\tminRevenue: parseOptNum(getFlag(flags, \"minRevenue\"), \"--minRevenue\"),\n\t\tmaxRevenue: parseOptNum(getFlag(flags, \"maxRevenue\"), \"--maxRevenue\"),\n\t});\n};\n\nconst commandGetBudgetCategoryBenchmarks: CliCommandHandler = async ({\n\tflags,\n\tpositional,\n}) => {\n\tconst id = positional[0];\n\tif (!id) {\n\t\tthrow new Error(\n\t\t\t\"get-budget-category-benchmarks requires <categoryId> [--limit]\",\n\t\t);\n\t}\n\tawait getBudgetCategoryBenchmarks({\n\t\tcategoryId: id,\n\t\tlimit: parsePositiveIntFlag(getFlag(flags, \"limit\"), \"--limit\"),\n\t});\n};\n\nconst commandGetItemPricingHistory: CliCommandHandler = async ({ flags }) => {\n\tawait getItemPricingHistory({\n\t\titemName: getFlag(flags, \"itemName\"),\n\t\tcategoryId: getFlag(flags, \"categoryId\"),\n\t\tsupplierId: getFlag(flags, \"supplierId\"),\n\t\tlimit: parsePositiveIntFlag(getFlag(flags, \"limit\"), \"--limit\"),\n\t});\n};\n\nconst commandGetSupplierPricingHistory: CliCommandHandler = async ({\n\tflags,\n\tpositional,\n}) => {\n\tconst id = positional[0];\n\tif (!id) {\n\t\tthrow new Error(\n\t\t\t\"get-supplier-pricing-history requires <supplierId> [--itemCategoryId] [--limit]\",\n\t\t);\n\t}\n\tawait getSupplierPricingHistory({\n\t\tsupplierId: id,\n\t\titemCategoryId: getFlag(flags, \"itemCategoryId\"),\n\t\tlimit: parsePositiveIntFlag(getFlag(flags, \"limit\"), \"--limit\"),\n\t});\n};\n\nconst CLI_COMMAND_HANDLERS: ReadonlyMap<string, CliCommandHandler> = new Map([\n\t[\"whoami\", commandWhoami],\n\t[\"list-budgets\", commandListBudgets],\n\t[\"count-budgets\", commandListBudgets],\n\t[\"get-budget\", commandGetBudget],\n\t[\"upload-budget-attachment\", commandUploadBudgetAttachment],\n\t[\"mark-budget-won\", commandMarkBudgetWon],\n\t[\"get-budget-items\", commandGetBudgetItems],\n\t[\"get-budget-details\", commandGetBudgetDetails],\n\t[\"get-budget-categories\", commandGetBudgetCategories],\n\t[\"get-budget-versions\", commandGetBudgetVersions],\n\t[\"rename-budget-version\", commandRenameBudgetVersion],\n\t[\"restore-budget-version\", commandRestoreBudgetVersion],\n\t[\"update-budget-status\", commandUpdateBudgetStatus],\n\t[\"create-budget-approval\", commandCreateBudgetApproval],\n\t[\"create-estimate\", commandCreateEstimate],\n\t[\"send-estimate-email\", commandSendEstimateEmail],\n\t[\"send-estimate-to-contact-person\", commandSendEstimateEmail],\n\t[\"create-budget\", commandCreateBudget],\n\t[\"update-budget\", commandUpdateBudget],\n\t[\"delete-budget\", commandDeleteBudget],\n\t[\"add-budget-items\", commandAddBudgetItems],\n\t[\"update-budget-item\", commandUpdateBudgetItem],\n\t[\"remove-budget-item\", commandRemoveBudgetItem],\n\t[\"replace-budget-item\", commandReplaceBudgetItem],\n\t[\n\t\t\"approve-unavailable-item-exception\",\n\t\tcommandApproveUnavailableItemException,\n\t],\n\t[\"reorder-budget-items\", commandReorderBudgetItems],\n\t[\"update-budget-item-supplier\", commandUpdateBudgetItemSupplier],\n\t[\"create-budget-category\", commandCreateBudgetCategory],\n\t[\"update-budget-category\", commandUpdateBudgetCategory],\n\t[\"delete-budget-category\", commandDeleteBudgetCategory],\n\t[\"update-budget-commission\", commandUpdateBudgetCommission],\n\t[\"update-budget-discount\", commandUpdateBudgetDiscount],\n\t[\"delete-budget-commission\", commandDeleteBudgetCommission],\n\t[\"delete-budget-discount\", commandDeleteBudgetDiscount],\n\t[\"mark-budget-items-not-utilized\", commandMarkBudgetItemsNotUtilized],\n\t[\"restore-budget-item\", commandRestoreBudgetItem],\n\t[\"create-placeholder-bill\", commandCreatePlaceholderBill],\n\t[\"list-bills\", commandListBills],\n\t[\"list-claims\", commandListClaims],\n\t[\"count-bills\", commandCountBills],\n\t[\"count-claims\", commandCountClaims],\n\t[\"create-bill-approval\", commandCreateBillApproval],\n\t[\"create-bill\", commandCreateBill],\n\t[\"validate-bill-selection\", commandValidateBillSelection],\n\t[\"link-bill-quotations\", commandLinkBillQuotations],\n\t[\"update-bill\", commandUpdateBill],\n\t[\"update-bill-payment-evidence\", commandUpdateBillPaymentEvidence],\n\t[\"delete-bill\", commandDeleteBill],\n\t[\"update-bill-status\", commandUpdateBillStatus],\n\t[\"list-external-payment-accounts\", commandListExternalPaymentAccounts],\n\t[\"refresh-external-payment-accounts\", commandRefreshExternalPaymentAccounts],\n\t[\"record-external-bill-payment\", commandRecordExternalBillPayment],\n\t[\"patch-bill-payment\", commandPatchBillPayment],\n\t[\"patch-bill-invoice-number\", commandPatchBillInvoiceNumber],\n\t[\"get-bill-attachments\", commandGetBillAttachments],\n\t[\"get-bill-approvals\", commandGetBillApprovals],\n\t[\"get-bill-line-items\", commandGetBillLineItems],\n\t[\"get-bill-payment\", commandGetBillPayment],\n\t[\"stage-bill-attachment\", commandStageBillAttachment],\n\t[\"cleanup-staged-bill-attachments\", commandCleanupStagedBillAttachments],\n\t[\"upload-bill-attachment\", commandUploadBillAttachment],\n\t[\"attach-bill-attachment\", commandUploadBillAttachment],\n\t[\"attach-bill-payment-receipt\", commandUploadBillAttachment],\n\t[\"attach-bill-documents\", commandAttachBillDocuments],\n\t[\"get-bill-details\", commandGetBillDetails],\n\t[\"list-quotations\", commandListQuotations],\n\t[\"count-quotations\", commandCountQuotations],\n\t[\"get-quotation\", commandGetQuotation],\n\t[\"get-quotation-line-items\", commandGetQuotationLineItems],\n\t[\"upload-quotation-attachment\", commandUploadQuotationAttachment],\n\t[\n\t\t\"cleanup-staged-quotation-attachments\",\n\t\tcommandCleanupStagedQuotationAttachments,\n\t],\n\t[\"create-quotation\", commandCreateQuotation],\n\t[\"update-quotation\", commandUpdateQuotation],\n\t[\"delete-quotation\", commandDeleteQuotation],\n\t[\"submit-quotation\", commandSubmitQuotation],\n\t[\"approve-quotation\", commandApproveQuotation],\n\t[\"reject-quotation\", commandRejectQuotation],\n\t[\"download-quotation-pdf\", commandDownloadQuotationPdf],\n\t[\"check-customer-invoice-readiness\", commandCheckCustomerInvoiceReadiness],\n\t[\n\t\t\"list-eligible-customer-invoice-budgets\",\n\t\tcommandListEligibleCustomerInvoiceBudgets,\n\t],\n\t[\"preview-customer-invoice-amount\", commandPreviewCustomerInvoiceAmount],\n\t[\n\t\t\"list-available-qbo-customer-invoices\",\n\t\tcommandListAvailableQboCustomerInvoices,\n\t],\n\t[\"list-customer-invoices\", commandListCustomerInvoices],\n\t[\"count-customer-invoices\", commandListCustomerInvoices],\n\t[\"get-customer-invoice\", commandGetCustomerInvoice],\n\t[\"get-customer-invoice-invoices\", commandGetCustomerInvoiceInvoices],\n\t[\"get-customer-invoice-lines\", commandGetCustomerInvoiceLines],\n\t[\"get-customer-invoice-approvals\", commandGetCustomerInvoiceApprovals],\n\t[\"get-customer-invoice-history\", commandGetCustomerInvoiceHistory],\n\t[\"get-customer-invoice-payments\", commandGetCustomerInvoicePayments],\n\t[\"get-customer-invoice-email-context\", commandGetCustomerInvoiceEmailContext],\n\t[\"preview-qbo-customer-invoice\", commandPreviewQboCustomerInvoice],\n\t[\"import-qbo-customer-invoice\", commandPreviewQboCustomerInvoice],\n\t[\"create-customer-invoice\", commandCreateCustomerInvoice],\n\t[\"resubmit-customer-invoice\", commandResubmitCustomerInvoice],\n\t[\"discard-customer-invoice\", commandDiscardCustomerInvoice],\n\t[\"delete-customer-invoice\", commandDeleteCustomerInvoice],\n\t[\"void-customer-invoice\", commandVoidCustomerInvoice],\n\t[\"approve-customer-invoice\", commandApproveCustomerInvoice],\n\t[\"reject-customer-invoice\", commandRejectCustomerInvoice],\n\t[\n\t\t\"send-customer-invoice-to-contact-person\",\n\t\tcommandSendCustomerInvoiceToContactPerson,\n\t],\n\t[\"download-customer-invoice-pdf\", commandDownloadCustomerInvoicePdf],\n\t[\"update-customer-invoice-details\", commandUpdateCustomerInvoiceDetails],\n\t[\"update-customer-invoice-qbo-drift\", commandUpdateCustomerInvoiceQboDrift],\n\t[\n\t\t\"mark-customer-invoice-sent-externally\",\n\t\tcommandMarkCustomerInvoiceSentExternally,\n\t],\n\t[\"sync-customer-invoice\", commandSyncCustomerInvoice],\n\t[\"list-approvals\", commandListApprovals],\n\t[\"get-pending-approvals\", commandListApprovals],\n\t[\"approve-bill\", commandApproveBill],\n\t[\"reject-bill\", commandRejectBill],\n\t[\"approve-budget\", commandApproveBudget],\n\t[\"reject-budget\", commandRejectBudget],\n\t[\"approve-supplier\", commandApproveSupplier],\n\t[\"reject-supplier\", commandRejectSupplier],\n\t[\"get-supplier-details\", commandGetSupplierDetails],\n\t[\"get-supplier-overview\", commandGetSupplierOverview],\n\t[\"get-supplier-usage\", commandGetSupplierUsage],\n\t[\"get-supplier-items\", commandGetSupplierItems],\n\t[\"list-companies\", commandListCompanies],\n\t[\"count-companies\", commandCountCompanies],\n\t[\"get-company\", commandGetCompany],\n\t[\"create-company\", commandCreateCompany],\n\t[\"search-existing-companies\", commandSearchExistingCompanies],\n\t[\"use-existing-company\", commandUseExistingCompany],\n\t[\"update-company\", commandUpdateCompany],\n\t[\"get-company-quickbooks-sync-status\", commandGetCompanyQuickbooksSyncStatus],\n\t[\"delete-company\", commandDeleteCompany],\n\t[\"list-projects\", commandListProjects],\n\t[\"count-projects\", commandCountProjects],\n\t[\"list-project-hubs\", commandListProjectHubs],\n\t[\"count-project-hubs\", commandListProjectHubs],\n\t[\"get-project\", commandGetProject],\n\t[\"get-project-hub-status\", commandGetProjectHubStatus],\n\t[\"setup-project-hub\", commandSetupProjectHub],\n\t[\n\t\t\"sync-project-hub-commercial-documents\",\n\t\tcommandSyncProjectHubCommercialDocuments,\n\t],\n\t[\"create-project\", commandCreateProject],\n\t[\"update-project\", commandUpdateProject],\n\t[\"delete-project\", commandDeleteProject],\n\t[\"check-project-reconciliation\", commandCheckProjectReconciliation],\n\t[\"reconcile-project\", commandReconcileProject],\n\t[\"complete-project\", commandCompleteProject],\n\t[\"import-qbo-project\", commandImportQboProject],\n\t[\"update-project-status\", commandUpdateProjectStatus],\n\t[\"list-contacts\", commandListContacts],\n\t[\"create-contact-person\", commandCreateContactPerson],\n\t[\"update-contact-person\", commandUpdateContactPerson],\n\t[\"count-suppliers\", commandCountSuppliers],\n\t[\"list-suppliers\", commandListSuppliers],\n\t[\"create-supplier\", commandCreateSupplier],\n\t[\"update-supplier\", commandUpdateSupplier],\n\t[\"delete-suppliers\", commandDeleteSuppliers],\n\t[\"reactivate-suppliers\", commandReactivateSuppliers],\n\t[\"create-certification\", commandCreateCertification],\n\t[\"create-payment-method\", commandCreatePaymentMethod],\n\t[\"create-supplier-role\", commandCreateSupplierRole],\n\t[\"create-supplier-tag\", commandCreateSupplierTag],\n\t[\"get-supplier-analytics\", commandGetSupplierAnalytics],\n\t[\"count-supplier-analytics\", commandGetSupplierAnalytics],\n\t[\"list-items\", commandListItems],\n\t[\"count-items\", commandListItems],\n\t[\"get-item\", commandGetItem],\n\t[\"get-item-quickbooks-sync-status\", commandGetItemQuickbooksSyncStatus],\n\t[\"create-item\", commandCreateItem],\n\t[\"update-item\", commandUpdateItem],\n\t[\"delete-item\", commandDeleteItem],\n\t[\"archive-items\", commandArchiveItems],\n\t[\"list-item-categories\", commandListItemCategories],\n\t[\"count-item-categories\", commandListItemCategories],\n\t[\"create-item-category\", commandCreateItemCategory],\n\t[\"update-item-category\", commandUpdateItemCategory],\n\t[\"delete-item-categories\", commandDeleteItemCategories],\n\t[\"list-users\", commandListUsers],\n\t[\"count-users\", commandListUsers],\n\t[\"create-user\", commandCreateUser],\n\t[\"create-api-key\", commandCreateApiKey],\n\t[\"list-api-keys\", commandListApiKeys],\n\t[\"revoke-api-key\", commandRevokeApiKey],\n\t[\"get-user-performance\", commandGetUserPerformance],\n\t[\"get-dashboard\", commandGetDashboard],\n\t[\"get-monthly-metrics\", commandGetMonthlyMetrics],\n\t[\"get-system-overview\", commandGetSystemOverview],\n\t[\"get-estimate-performance\", commandGetEstimatePerformance],\n\t[\"get-financial-overview\", commandGetFinancialOverview],\n\t[\"get-recent-errors\", commandGetRecentErrors],\n\t[\"count-errors\", commandGetRecentErrors],\n\t[\"get-error\", commandGetError],\n\t[\"get-error-metrics\", commandGetErrorMetrics],\n\t[\"list-integration-operations\", commandListIntegrationOperations],\n\t[\"count-integration-operations\", commandListIntegrationOperations],\n\t[\"get-integration-operation\", commandGetIntegrationOperation],\n\t[\"retry-integration-operation\", commandRetryIntegrationOperation],\n\t[\"list-webhook-event-types\", commandListWebhookEventTypes],\n\t[\"list-webhook-endpoints\", commandListWebhookEndpoints],\n\t[\"get-webhook-endpoint\", commandGetWebhookEndpoint],\n\t[\"create-webhook-endpoint\", commandCreateWebhookEndpoint],\n\t[\"update-webhook-endpoint\", commandUpdateWebhookEndpoint],\n\t[\"delete-webhook-endpoint\", commandDeleteWebhookEndpoint],\n\t[\"rotate-webhook-secret\", commandRotateWebhookSecret],\n\t[\"send-webhook-test-event\", commandSendWebhookTestEvent],\n\t[\"list-webhook-deliveries\", commandListWebhookDeliveries],\n\t[\"get-webhook-delivery\", commandGetWebhookDelivery],\n\t[\"replay-webhook-delivery\", commandReplayWebhookDelivery],\n\t[\"reconcile-resource-operation\", commandReconcileResourceOperation],\n\t[\"list-inbound-sources\", commandListInboundSources],\n\t[\"count-inbound-sources\", commandListInboundSources],\n\t[\"create-inbound-source\", commandCreateInboundSource],\n\t[\"get-inbound-source\", commandGetInboundSource],\n\t[\"update-inbound-source\", commandUpdateInboundSource],\n\t[\"list-inbound-submissions\", commandListInboundSubmissions],\n\t[\"count-inbound-submissions\", commandCountInboundSubmissions],\n\t[\"get-inbound-submission\", commandGetInboundSubmission],\n\t[\"save-inbound-mapping\", commandSaveInboundMapping],\n\t[\"save-inbound-automation-config\", commandSaveInboundAutomationConfig],\n\t[\"update-inbound-processing\", commandUpdateInboundProcessing],\n\t[\"get-approved-budgets\", commandGetApprovedBudgets],\n\t[\"get-budget-category-benchmarks\", commandGetBudgetCategoryBenchmarks],\n\t[\"get-item-pricing-history\", commandGetItemPricingHistory],\n\t[\"get-supplier-pricing-history\", commandGetSupplierPricingHistory],\n]);\n\nconst dispatchCliCommand = async (\n\tcontext: CliCommandContext,\n): Promise<void> => {\n\tconst handler = CLI_COMMAND_HANDLERS.get(context.cmd);\n\tif (!handler) {\n\t\tthrow new Error(`Unknown command: ${context.cmd}. Run 'bb help'.`);\n\t}\n\tawait handler(context);\n};\n\ntype CliRunContext = {\n\truntime: CliRuntime;\n\tversion: string;\n\tquiet: boolean;\n\tdebug: boolean;\n};\n\nconst startCliSession = (context: CliRunContext, command: string) => {\n\tsetActiveCliSession({\n\t\truntime: context.runtime,\n\t\tinvocation: {\n\t\t\tcommand,\n\t\t\tcliVersion: context.version,\n\t\t\tapiBaseUrl: BUDGET_BUILDER_API_BASE_URL,\n\t\t\tquiet: context.quiet,\n\t\t\tdebug: context.debug,\n\t\t},\n\t\teffects: [],\n\t\tpermissions: {},\n\t});\n};\n\nconst failCliSession = (\n\tcontext: CliRunContext,\n\tcommand: string,\n\terror: unknown,\n): number => {\n\tstartCliSession(context, command);\n\tconst exitCode = emitCommandError(error);\n\tclearActiveCliSession();\n\treturn exitCode;\n};\n\nconst resolveRootArguments = (\n\trawArgv: readonly string[],\n\truntime: CliRuntime,\n): RootArguments => {\n\tconst rootArguments = parseRootArguments(rawArgv);\n\tconst apiBaseUrl = rootArguments.apiBaseUrl ?? runtime.env.BB_API_URL?.trim();\n\tconfigureBudgetBuilderApiBaseUrl(\n\t\tapiBaseUrl || DEFAULT_BUDGET_BUILDER_API_BASE_URL,\n\t);\n\treturn rootArguments;\n};\n\nconst isHelpRequest = (commandArgv: readonly string[]): boolean =>\n\tcommandArgv.length === 0 ||\n\tcommandArgv[0] === \"help\" ||\n\tisEnabledFlag(commandArgv, \"--help\") ||\n\tcommandArgv.includes(\"-h\");\n\nconst printCliHelp = (\n\tcommandArgv: readonly string[],\n\truntime: CliRuntime,\n): void => {\n\tif (commandArgv.includes(\"--legacy\")) {\n\t\tprintLegacyHelp(runtime);\n\t\treturn;\n\t}\n\tconst helpArgv = commandArgv.filter(\n\t\t(argument, index) =>\n\t\t\targument !== \"-h\" &&\n\t\t\targument !== \"--help\" &&\n\t\t\t!argument.startsWith(\"--help=\") &&\n\t\t\t!(commandArgv[index - 1] === \"--help\" && booleanFlagValues.has(argument)),\n\t);\n\tconst helpCommand = resolveCommand(\n\t\thelpArgv[0] === \"help\" ? helpArgv.slice(1) : helpArgv,\n\t)?.command;\n\truntime.stdout.write(`${createHumanHelp(helpCommand)}\\n`);\n};\n\nconst runCompletionCommand = (\n\tcontext: CliRunContext,\n\tcommandArgv: readonly string[],\n): number => {\n\tconst shell = commandArgv[1];\n\tif (shell === undefined || !isCompletionShell(shell)) {\n\t\treturn failCliSession(\n\t\t\tcontext,\n\t\t\t\"completion\",\n\t\t\tnew CliRuntimeError(\n\t\t\t\t\"USAGE\",\n\t\t\t\t\"completion requires bash, zsh, fish, or powershell.\",\n\t\t\t),\n\t\t);\n\t}\n\tcontext.runtime.stdout.write(createCompletionScript(shell));\n\treturn 0;\n};\n\nconst isVersionRequest = (commandArgv: readonly string[]): boolean =>\n\tcommandArgv[0] === \"version\" ||\n\tisEnabledFlag(commandArgv, \"--version\") ||\n\tcommandArgv.includes(\"-v\");\n\nconst runVersionCommand = (context: CliRunContext): number => {\n\tstartCliSession(context, \"version\");\n\temitCommandResult(getVersionData());\n\tclearActiveCliSession();\n\treturn 0;\n};\n\nconst createDefaultCredentialStore = (runtime: CliRuntime) =>\n\tcreateBunCredentialStore({\n\t\taccount: resolveCliCredentialAccount(runtime.env),\n\t\tproduct: \"budget-builder\",\n\t});\n\nconst authStatusResult = async (\n\truntime: CliRuntime,\n\tstore: CliCredentialStore,\n) => {\n\tconst apiKeyActive = Boolean(runtime.env.BB_API_KEY?.trim());\n\tconst credentials = apiKeyActive ? null : await store.get();\n\tif (apiKeyActive) {\n\t\treturn {\n\t\t\tauthenticated: true,\n\t\t\tmethod: \"api-key\",\n\t\t\tstorage: \"environment\",\n\t\t};\n\t}\n\tif (\n\t\tcredentials &&\n\t\tisCliCredentialForIssuer(credentials, BUDGET_BUILDER_API_BASE_URL)\n\t) {\n\t\treturn {\n\t\t\tauthenticated: true,\n\t\t\tmethod: \"browser-session\",\n\t\t\taccessTokenExpiresAt: credentials.accessTokenExpiresAt,\n\t\t\trefreshTokenExpiresAt: credentials.refreshTokenExpiresAt,\n\t\t\tsession: credentials.session,\n\t\t\tstorage: \"Bun.secrets\",\n\t\t};\n\t}\n\treturn {\n\t\tauthenticated: false,\n\t\tmethod: null,\n\t\tstorage: \"Bun.secrets\",\n\t};\n};\n\nconst runAuthAction = async (\n\tcontext: CliRunContext,\n\tauthAction: \"login\" | \"status\" | \"logout\",\n\trawArgv: readonly string[],\n\tstore: CliCredentialStore,\n): Promise<void> => {\n\tconst { runtime } = context;\n\tif (authAction === \"login\") {\n\t\tconst credentials = await loginWithBrowser({\n\t\t\tapiBaseUrl: BUDGET_BUILDER_API_BASE_URL,\n\t\t\tclientVersion: context.version,\n\t\t\tonVerification: ({ browserOpened, userCode, verificationUriComplete }) =>\n\t\t\t\truntime.stderr.write(\n\t\t\t\t\t`${browserOpened ? \"Opened\" : \"Open\"} ${verificationUriComplete}\\nCode: ${userCode}\\nWaiting for approval…\\n`,\n\t\t\t\t),\n\t\t\t...(isEnabledFlag(rawArgv, \"--no-browser\")\n\t\t\t\t? { openBrowser: async () => false }\n\t\t\t\t: {}),\n\t\t\tstore,\n\t\t});\n\t\temitCommandResult({\n\t\t\tauthenticated: true,\n\t\t\tmethod: \"browser-session\",\n\t\t\tsession: credentials.session,\n\t\t\tstorage: \"Bun.secrets\",\n\t\t});\n\t} else if (authAction === \"status\") {\n\t\temitCommandResult(await authStatusResult(runtime, store));\n\t} else {\n\t\temitCommandResult({\n\t\t\tloggedOut: true,\n\t\t\t...(await logoutCliSession({\n\t\t\t\tapiBaseUrl: BUDGET_BUILDER_API_BASE_URL,\n\t\t\t\tstore,\n\t\t\t})),\n\t\t\tapiKeyActive: Boolean(runtime.env.BB_API_KEY?.trim()),\n\t\t});\n\t}\n};\n\nconst runAuthCommand = async (\n\tcontext: CliRunContext,\n\tauthAction: \"login\" | \"status\" | \"logout\",\n\tcommandArgv: readonly string[],\n\trawArgv: readonly string[],\n\tcredentialStore: CliCredentialStore | undefined,\n): Promise<number> => {\n\tstartCliSession(context, `auth ${authAction}`);\n\ttry {\n\t\tif (commandArgv.length !== 2) {\n\t\t\tthrow new CliRuntimeError(\n\t\t\t\t\"USAGE\",\n\t\t\t\t`auth ${authAction} accepts no positional arguments.`,\n\t\t\t);\n\t\t}\n\t\tconst store =\n\t\t\tcredentialStore ?? createDefaultCredentialStore(context.runtime);\n\t\tawait runAuthAction(context, authAction, rawArgv, store);\n\t\treturn 0;\n\t} catch (error) {\n\t\treturn emitCommandError(error);\n\t} finally {\n\t\tclearActiveCliSession();\n\t}\n};\n\nconst authActionFromArgv = (\n\tcommandArgv: readonly string[],\n): \"login\" | \"status\" | \"logout\" | undefined => {\n\tconst authAction = commandArgv[0] === \"auth\" ? commandArgv[1] : undefined;\n\tif (\n\t\tauthAction === \"login\" ||\n\t\tauthAction === \"status\" ||\n\t\tauthAction === \"logout\"\n\t) {\n\t\treturn authAction;\n\t}\n\treturn undefined;\n};\n\nconst configureCliAuthentication = async (\n\truntime: CliRuntime,\n\tcredentialStore: CliCredentialStore | undefined,\n\tconfigureAccessToken: typeof configureBudgetBuilderAccessToken,\n): Promise<void> => {\n\tif (runtime.env.BB_API_KEY?.trim()) {\n\t\tconfigureAccessToken(undefined);\n\t\treturn;\n\t}\n\tlet accessToken: string;\n\ttry {\n\t\taccessToken = await getAuthenticatedAccessToken({\n\t\t\tapiBaseUrl: BUDGET_BUILDER_API_BASE_URL,\n\t\t\tstore: credentialStore ?? createDefaultCredentialStore(runtime),\n\t\t});\n\t} catch (error) {\n\t\tif (getCliStorageError(error)) throw error;\n\t\tthrow new CliRuntimeError(\n\t\t\t\"AUTHENTICATION\",\n\t\t\terror instanceof Error\n\t\t\t\t? error.message\n\t\t\t\t: \"Not authenticated. Run bb auth login first.\",\n\t\t);\n\t}\n\tconfigureAccessToken(accessToken);\n};\n\nconst CONFIRMATION_EXEMPT_COMMANDS: ReadonlySet<string> = new Set([\n\t\"create-bill\",\n\t\"import-qbo-customer-invoice\",\n\t\"approve-supplier\",\n]);\n\nconst confirmCanonicalMutation = async (\n\tresolvedCommand: ResolvedCommand,\n\tcmd: string,\n): Promise<void> => {\n\tif (\n\t\tresolvedCommand.isLegacyAlias ||\n\t\tCONFIRMATION_EXEMPT_COMMANDS.has(cmd) ||\n\t\tresolvedCommand.command.effects.length === 0\n\t) {\n\t\treturn;\n\t}\n\tawait confirmCurrentCommand({\n\t\taction: resolvedCommand.command.path.join(\" \"),\n\t\ttarget: commandConfirmationTarget(resolvedCommand),\n\t\tdetails:\n\t\t\t\"Canonical v2 mutation. Supply every effect-specific --allow-* flag for non-interactive execution.\",\n\t});\n};\n\nconst runResolvedCommand = async (\n\tcontext: CliRunContext,\n\targv: string[],\n\trawArgv: readonly string[],\n\tresolvedCommand: ResolvedCommand,\n\tcredentialStore: CliCredentialStore | undefined,\n\tconfigureAccessToken: typeof configureBudgetBuilderAccessToken,\n): Promise<number> => {\n\tconst { runtime, quiet, debug } = context;\n\tconst effectiveArgv = legacyArgvForCommand(argv, resolvedCommand);\n\tconst { command, positional, flags } = parseArgs(effectiveArgv);\n\tconsumeCliQuietFlags(flags);\n\tsetCliQuiet(resolvedCommand.isLegacyAlias ? quiet : quiet || !debug);\n\n\tsetActiveCliSession({\n\t\truntime,\n\t\tinvocation: {\n\t\t\tcommand: resolvedCommand.command.path.join(\" \"),\n\t\t\tcliVersion: context.version,\n\t\t\tapiBaseUrl: BUDGET_BUILDER_API_BASE_URL,\n\t\t\tlegacy: resolvedCommand.isLegacyAlias,\n\t\t\tquiet,\n\t\t\tdebug,\n\t\t},\n\t\teffects: resolvedCommand.command.effects,\n\t\tpermissions: effectPermissionsFromArgv(rawArgv),\n\t});\n\n\tif (resolvedCommand.isLegacyAlias && !quiet) {\n\t\truntime.stderr.write(\n\t\t\t`[bb] Deprecated command \"${resolvedCommand.invokedAs.join(\" \")}\"; use \"bb ${resolvedCommand.command.path.join(\" \")}\".\\n`,\n\t\t);\n\t}\n\n\tconst cmd = normalizeCliCommand(command ?? \"\");\n\n\tconst t0 = Date.now();\n\tif (shouldLogCliActions()) {\n\t\tlogCliAction({\n\t\t\tevent: \"cli.command\",\n\t\t\tphase: \"start\",\n\t\t\tcommand: cmd,\n\t\t\tpositional,\n\t\t\tflags: sanitizeFlagsForTrace(flags),\n\t\t});\n\t}\n\n\ttry {\n\t\t// `--q` is always a search value; a bare one would list everything.\n\t\tif (flags.q === true)\n\t\t\tthrow new CliRuntimeError(\n\t\t\t\t\"USAGE\",\n\t\t\t\t\"--q needs a search value (--q <text> or --q=<text>). Use -q or --quiet to hide logs.\",\n\t\t\t);\n\t\tawait configureCliAuthentication(\n\t\t\truntime,\n\t\t\tcredentialStore,\n\t\t\tconfigureAccessToken,\n\t\t);\n\t\tawait confirmCanonicalMutation(resolvedCommand, cmd);\n\t\tawait dispatchCliCommand({ cmd, flags, positional });\n\t\tif (shouldLogCliActions()) {\n\t\t\tlogCliAction({\n\t\t\t\tevent: \"cli.command\",\n\t\t\t\tphase: \"ok\",\n\t\t\t\tcommand: cmd,\n\t\t\t\tdurationMs: Date.now() - t0,\n\t\t\t});\n\t\t}\n\t\tclearActiveCliSession();\n\t\treturn 0;\n\t} catch (err) {\n\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\tif (shouldLogCliActions()) {\n\t\t\tlogCliAction({\n\t\t\t\tevent: \"cli.command\",\n\t\t\t\tphase: \"error\",\n\t\t\t\tcommand: cmd,\n\t\t\t\tdurationMs: Date.now() - t0,\n\t\t\t\terror: message,\n\t\t\t});\n\t\t}\n\t\tconst exitCode = emitCommandError(normalizeDispatcherError(err));\n\t\tclearActiveCliSession();\n\t\treturn exitCode;\n\t}\n};\n\nexport async function runCli(\n\targv: string[] = process.argv,\n\truntime: CliRuntime = createProcessRuntime(),\n\tcredentialStore?: CliCredentialStore,\n\tconfigureAccessToken: typeof configureBudgetBuilderAccessToken = configureBudgetBuilderAccessToken,\n): Promise<number> {\n\tconst rawArgv = argv.slice(2);\n\tconst metadata = getCliPackageMetadata();\n\tconst quiet =\n\t\tisEnabledFlag(rawArgv, \"--quiet\") ||\n\t\trawArgv.includes(\"-q\") ||\n\t\truntime.env.BB_CLI_QUIET === \"1\";\n\tconst debug = isEnabledFlag(rawArgv, \"--debug\");\n\tconst context: CliRunContext = {\n\t\truntime,\n\t\tversion: metadata.version,\n\t\tquiet,\n\t\tdebug,\n\t};\n\tlet rootArguments: RootArguments;\n\ttry {\n\t\trootArguments = resolveRootArguments(rawArgv, runtime);\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\treturn failCliSession(\n\t\t\tcontext,\n\t\t\t\"startup\",\n\t\t\terror instanceof CliRuntimeError\n\t\t\t\t? error\n\t\t\t\t: new CliRuntimeError(\"USAGE\", `Invalid API URL: ${message}`),\n\t\t);\n\t}\n\tconst { commandArgv } = rootArguments;\n\n\tif (isHelpRequest(commandArgv)) {\n\t\tprintCliHelp(commandArgv, runtime);\n\t\treturn 0;\n\t}\n\n\tif (commandArgv[0] === \"completion\") {\n\t\treturn runCompletionCommand(context, commandArgv);\n\t}\n\n\tif (isVersionRequest(commandArgv)) return runVersionCommand(context);\n\n\tconst authAction = authActionFromArgv(commandArgv);\n\tif (authAction !== undefined) {\n\t\treturn await runAuthCommand(\n\t\t\tcontext,\n\t\t\tauthAction,\n\t\t\tcommandArgv,\n\t\t\trawArgv,\n\t\t\tcredentialStore,\n\t\t);\n\t}\n\n\tconst resolvedCommand = resolveCommand(commandArgv);\n\tif (resolvedCommand === undefined) {\n\t\treturn failCliSession(\n\t\t\tcontext,\n\t\t\tcommandArgv[0] ?? \"unknown\",\n\t\t\tnew CliRuntimeError(\n\t\t\t\t\"USAGE\",\n\t\t\t\t`Unknown command: ${commandArgv.join(\" \")}. Run 'bb help'.`,\n\t\t\t),\n\t\t);\n\t}\n\n\treturn await runResolvedCommand(\n\t\tcontext,\n\t\targv,\n\t\trawArgv,\n\t\tresolvedCommand,\n\t\tcredentialStore,\n\t\tconfigureAccessToken,\n\t);\n}\n", "/** Sort keys implemented by the supplier-list API. */\nexport const SUPPLIER_SORT_IDS = [\n\t\"name\",\n\t\"email\",\n\t\"phone\",\n\t\"gstRegistered\",\n\t\"status\",\n\t\"active\",\n\t\"createdAt\",\n\t\"updatedAt\",\n] as const;\n\n/** Sort keys implemented by the inventory item-list API. */\nexport const INVENTORY_SORT_IDS = [\n\t\"itemCategory\",\n\t\"category\",\n\t\"supplier\",\n\t\"cost\",\n\t\"name\",\n\t\"createdAt\",\n\t\"updatedAt\",\n] as const;\n\n/** Sort keys implemented by the item-category list API. */\nexport const ITEM_CATEGORY_SORT_IDS = [\n\t\"name\",\n\t\"itemCount\",\n\t\"createdAt\",\n\t\"createdBy\",\n] as const;\n", "\n/* !!! This is code generated by Prisma. Do not edit directly. !!! */\n/* eslint-disable */\n// biome-ignore-all lint: generated file\n// @ts-nocheck \n/*\n* This file exports all enum related types from the schema.\n*\n* 🟢 You can import this file directly.\n*/\n\nexport const crdb_internal_region = {\n aws_ap_southeast_1: 'aws_ap_southeast_1'\n} as const\n\nexport type crdb_internal_region = (typeof crdb_internal_region)[keyof typeof crdb_internal_region]\n\n\nexport const InboundProvider = {\n TYPEFORM: 'TYPEFORM'\n} as const\n\nexport type InboundProvider = (typeof InboundProvider)[keyof typeof InboundProvider]\n\n\nexport const InboundProcessingMode = {\n COLLECT_ONLY: 'COLLECT_ONLY',\n SHADOW: 'SHADOW',\n ACTIVE: 'ACTIVE'\n} as const\n\nexport type InboundProcessingMode = (typeof InboundProcessingMode)[keyof typeof InboundProcessingMode]\n\n\nexport const InboundDeliveryStatus = {\n ACCEPTED: 'ACCEPTED',\n CONFLICT: 'CONFLICT',\n DUPLICATE: 'DUPLICATE'\n} as const\n\nexport type InboundDeliveryStatus = (typeof InboundDeliveryStatus)[keyof typeof InboundDeliveryStatus]\n\n\nexport const InboundProvisioningStatus = {\n PLANNED: 'PLANNED',\n QUEUED: 'QUEUED',\n IN_PROGRESS: 'IN_PROGRESS',\n NEEDS_REVIEW: 'NEEDS_REVIEW',\n COMPLETED: 'COMPLETED',\n CANCELLED: 'CANCELLED'\n} as const\n\nexport type InboundProvisioningStatus = (typeof InboundProvisioningStatus)[keyof typeof InboundProvisioningStatus]\n\n\nexport const InboundLeadCloseOutcome = {\n LOST: 'LOST',\n DISQUALIFIED: 'DISQUALIFIED'\n} as const\n\nexport type InboundLeadCloseOutcome = (typeof InboundLeadCloseOutcome)[keyof typeof InboundLeadCloseOutcome]\n\n\nexport const InboundGoshBriefStatus = {\n CREATED: 'CREATED',\n OPENED: 'OPENED',\n SUBMITTED: 'SUBMITTED',\n REVOKED: 'REVOKED'\n} as const\n\nexport type InboundGoshBriefStatus = (typeof InboundGoshBriefStatus)[keyof typeof InboundGoshBriefStatus]\n\n\nexport const InboundProvisioningStep = {\n PLAN: 'PLAN',\n INBOUND_SLACK_MESSAGE: 'INBOUND_SLACK_MESSAGE',\n INBOUND_EMAIL: 'INBOUND_EMAIL',\n ASANA_TASK: 'ASANA_TASK',\n CALENDAR_EVENT: 'CALENDAR_EVENT',\n PITCH_SLACK_CHANNEL: 'PITCH_SLACK_CHANNEL',\n ASANA_SLACK_LINK: 'ASANA_SLACK_LINK',\n SLACK_MESSAGES: 'SLACK_MESSAGES',\n COMPLETE: 'COMPLETE'\n} as const\n\nexport type InboundProvisioningStep = (typeof InboundProvisioningStep)[keyof typeof InboundProvisioningStep]\n\n\nexport const PayNowIdentifierType = {\n MOBILE_NUMBER: 'MOBILE_NUMBER',\n UEN: 'UEN'\n} as const\n\nexport type PayNowIdentifierType = (typeof PayNowIdentifierType)[keyof typeof PayNowIdentifierType]\n\n\nexport const DealLifecycleSource = {\n BB: 'BB',\n ASANA: 'ASANA'\n} as const\n\nexport type DealLifecycleSource = (typeof DealLifecycleSource)[keyof typeof DealLifecycleSource]\n\n\nexport const DealLifecycleOperationStatus = {\n PENDING: 'PENDING',\n IN_PROGRESS: 'IN_PROGRESS',\n NEEDS_REVIEW: 'NEEDS_REVIEW',\n COMPLETED: 'COMPLETED',\n FAILED: 'FAILED',\n UNDO_PENDING: 'UNDO_PENDING',\n UNDO_IN_PROGRESS: 'UNDO_IN_PROGRESS',\n UNDONE: 'UNDONE',\n UNDO_FAILED: 'UNDO_FAILED'\n} as const\n\nexport type DealLifecycleOperationStatus = (typeof DealLifecycleOperationStatus)[keyof typeof DealLifecycleOperationStatus]\n\n\nexport const DealLifecycleProvider = {\n BUDGET_BUILDER: 'BUDGET_BUILDER',\n QUICKBOOKS: 'QUICKBOOKS',\n ASANA: 'ASANA',\n SLACK: 'SLACK',\n GOOGLE_CALENDAR: 'GOOGLE_CALENDAR'\n} as const\n\nexport type DealLifecycleProvider = (typeof DealLifecycleProvider)[keyof typeof DealLifecycleProvider]\n\n\nexport const DealLifecycleStepStatus = {\n PENDING: 'PENDING',\n IN_PROGRESS: 'IN_PROGRESS',\n COMPLETED: 'COMPLETED',\n SKIPPED: 'SKIPPED',\n FAILED: 'FAILED'\n} as const\n\nexport type DealLifecycleStepStatus = (typeof DealLifecycleStepStatus)[keyof typeof DealLifecycleStepStatus]\n\n\nexport const ProjectHubSetupStatus = {\n QUEUED: 'QUEUED',\n IN_PROGRESS: 'IN_PROGRESS',\n READY: 'READY',\n FAILED: 'FAILED'\n} as const\n\nexport type ProjectHubSetupStatus = (typeof ProjectHubSetupStatus)[keyof typeof ProjectHubSetupStatus]\n\n\nexport const ProjectHubExternalStatus = {\n PENDING: 'PENDING',\n ACTIVE: 'ACTIVE'\n} as const\n\nexport type ProjectHubExternalStatus = (typeof ProjectHubExternalStatus)[keyof typeof ProjectHubExternalStatus]\n\n\nexport const AsanaTaskType = {\n default_task: 'default_task',\n milestone: 'milestone'\n} as const\n\nexport type AsanaTaskType = (typeof AsanaTaskType)[keyof typeof AsanaTaskType]\n\n\nexport const EstimationMode = {\n MICRO: 'MICRO',\n MANPOWER_SPECIFIED: 'MANPOWER_SPECIFIED'\n} as const\n\nexport type EstimationMode = (typeof EstimationMode)[keyof typeof EstimationMode]\n\n\nexport const IntegrationCredentialStatus = {\n DRAFT: 'DRAFT',\n CONNECTED: 'CONNECTED',\n REAUTHORIZATION_REQUIRED: 'REAUTHORIZATION_REQUIRED',\n INVALID: 'INVALID',\n DISABLED: 'DISABLED',\n ARCHIVED: 'ARCHIVED'\n} as const\n\nexport type IntegrationCredentialStatus = (typeof IntegrationCredentialStatus)[keyof typeof IntegrationCredentialStatus]\n\n\nexport const IntegrationCredentialTestOutcome = {\n ACCEPTED: 'ACCEPTED',\n REJECTED: 'REJECTED',\n UNVERIFIED: 'UNVERIFIED'\n} as const\n\nexport type IntegrationCredentialTestOutcome = (typeof IntegrationCredentialTestOutcome)[keyof typeof IntegrationCredentialTestOutcome]\n\n\nexport const IntegrationCredentialType = {\n GOOGLE_CALENDAR_OAUTH2: 'GOOGLE_CALENDAR_OAUTH2',\n GOOGLE_SERVICE_ACCOUNT: 'GOOGLE_SERVICE_ACCOUNT',\n ASANA_ACCESS_TOKEN: 'ASANA_ACCESS_TOKEN',\n ASANA_OAUTH2: 'ASANA_OAUTH2',\n SLACK_APP: 'SLACK_APP',\n TYPEFORM_WEBHOOK: 'TYPEFORM_WEBHOOK',\n RESEND_API_KEY: 'RESEND_API_KEY',\n OPENAI_API_KEY: 'OPENAI_API_KEY',\n S3_ACCESS_KEY: 'S3_ACCESS_KEY',\n QUICKBOOKS_OAUTH2: 'QUICKBOOKS_OAUTH2'\n} as const\n\nexport type IntegrationCredentialType = (typeof IntegrationCredentialType)[keyof typeof IntegrationCredentialType]\n\n\nexport const IntegrationCapability = {\n GOOGLE_CALENDAR_EVENTS: 'GOOGLE_CALENDAR_EVENTS',\n GOOGLE_DRIVE: 'GOOGLE_DRIVE',\n ASANA: 'ASANA',\n SLACK_WEB_API: 'SLACK_WEB_API',\n SLACK_EVENT_VERIFICATION: 'SLACK_EVENT_VERIFICATION',\n TYPEFORM_WEBHOOK_VERIFICATION: 'TYPEFORM_WEBHOOK_VERIFICATION',\n RESEND_EMAIL: 'RESEND_EMAIL',\n OPENAI: 'OPENAI',\n S3_OBJECT_STORAGE: 'S3_OBJECT_STORAGE',\n QUICKBOOKS_API: 'QUICKBOOKS_API'\n} as const\n\nexport type IntegrationCapability = (typeof IntegrationCapability)[keyof typeof IntegrationCapability]\n\n\nexport const IntegrationCredentialScope = {\n GLOBAL: 'GLOBAL',\n INBOUND_SOURCE: 'INBOUND_SOURCE'\n} as const\n\nexport type IntegrationCredentialScope = (typeof IntegrationCredentialScope)[keyof typeof IntegrationCredentialScope]\n\n\nexport const OutgoingEmailStatus = {\n QUEUED: 'QUEUED',\n SENDING: 'SENDING',\n SENT: 'SENT',\n RECONCILIATION_REQUIRED: 'RECONCILIATION_REQUIRED',\n DELIVERY_DELAYED: 'DELIVERY_DELAYED',\n DELIVERED: 'DELIVERED',\n OPENED: 'OPENED',\n CLICKED: 'CLICKED',\n BOUNCED: 'BOUNCED',\n FAILED: 'FAILED',\n COMPLAINED: 'COMPLAINED',\n SUPPRESSED: 'SUPPRESSED'\n} as const\n\nexport type OutgoingEmailStatus = (typeof OutgoingEmailStatus)[keyof typeof OutgoingEmailStatus]\n\n\nexport const OutgoingEmailSourceType = {\n DOCUMENT_DELIVERY: 'DOCUMENT_DELIVERY',\n BUDGET: 'BUDGET',\n APPROVAL: 'APPROVAL',\n INVOICE: 'INVOICE',\n BILL: 'BILL',\n PROJECT: 'PROJECT',\n INBOUND_SUBMISSION: 'INBOUND_SUBMISSION',\n QBO_OTP_CHALLENGE: 'QBO_OTP_CHALLENGE'\n} as const\n\nexport type OutgoingEmailSourceType = (typeof OutgoingEmailSourceType)[keyof typeof OutgoingEmailSourceType]\n\n\nexport const OutgoingEmailAttemptStatus = {\n SENDING: 'SENDING',\n SENT: 'SENT',\n FAILED: 'FAILED'\n} as const\n\nexport type OutgoingEmailAttemptStatus = (typeof OutgoingEmailAttemptStatus)[keyof typeof OutgoingEmailAttemptStatus]\n\n\nexport const OutboundEmailKind = {\n ESTIMATE: 'ESTIMATE'\n} as const\n\nexport type OutboundEmailKind = (typeof OutboundEmailKind)[keyof typeof OutboundEmailKind]\n\n\nexport const OutboundEmailProvider = {\n RESEND: 'RESEND'\n} as const\n\nexport type OutboundEmailProvider = (typeof OutboundEmailProvider)[keyof typeof OutboundEmailProvider]\n\n\nexport const OutboundEmailStatus = {\n QUEUED: 'QUEUED',\n PROCESSING: 'PROCESSING',\n RECONCILIATION_REQUIRED: 'RECONCILIATION_REQUIRED',\n SENT: 'SENT',\n FAILED: 'FAILED'\n} as const\n\nexport type OutboundEmailStatus = (typeof OutboundEmailStatus)[keyof typeof OutboundEmailStatus]\n\n\nexport const OutboundEmailAttemptStatus = {\n PROCESSING: 'PROCESSING',\n SENT: 'SENT',\n FAILED: 'FAILED'\n} as const\n\nexport type OutboundEmailAttemptStatus = (typeof OutboundEmailAttemptStatus)[keyof typeof OutboundEmailAttemptStatus]\n\n\nexport const CustomerDocumentEmailKind = {\n ESTIMATE: 'ESTIMATE',\n INVOICE: 'INVOICE'\n} as const\n\nexport type CustomerDocumentEmailKind = (typeof CustomerDocumentEmailKind)[keyof typeof CustomerDocumentEmailKind]\n\n\nexport const CustomerDocumentEmailProviderStatus = {\n QUEUED: 'QUEUED',\n SENT: 'SENT',\n DELIVERY_DELAYED: 'DELIVERY_DELAYED',\n DELIVERED: 'DELIVERED',\n OPENED: 'OPENED',\n CLICKED: 'CLICKED',\n BOUNCED: 'BOUNCED',\n FAILED: 'FAILED',\n COMPLAINED: 'COMPLAINED',\n SUPPRESSED: 'SUPPRESSED'\n} as const\n\nexport type CustomerDocumentEmailProviderStatus = (typeof CustomerDocumentEmailProviderStatus)[keyof typeof CustomerDocumentEmailProviderStatus]\n\n\nexport const AttachmentType = {\n GLOBAL_ATTACHMENT: 'GLOBAL_ATTACHMENT',\n BUDGET: 'BUDGET',\n BUDGET_WIN_PROOF: 'BUDGET_WIN_PROOF',\n ITEM: 'ITEM',\n SUPPLIER: 'SUPPLIER',\n BILL: 'BILL',\n BILL_PAYMENT_PROOF: 'BILL_PAYMENT_PROOF',\n QUOTATION: 'QUOTATION'\n} as const\n\nexport type AttachmentType = (typeof AttachmentType)[keyof typeof AttachmentType]\n\n\nexport const SupplierQuotationStatus = {\n DRAFT: 'DRAFT',\n PENDING_APPROVAL: 'PENDING_APPROVAL',\n APPROVED: 'APPROVED',\n REJECTED: 'REJECTED',\n SUPERSEDED: 'SUPERSEDED'\n} as const\n\nexport type SupplierQuotationStatus = (typeof SupplierQuotationStatus)[keyof typeof SupplierQuotationStatus]\n\n\nexport const SupplierQuotationFileRole = {\n ORIGINAL: 'ORIGINAL',\n STAFF_SIGNED: 'STAFF_SIGNED',\n FINAL_SIGNED: 'FINAL_SIGNED'\n} as const\n\nexport type SupplierQuotationFileRole = (typeof SupplierQuotationFileRole)[keyof typeof SupplierQuotationFileRole]\n\n\nexport const ProjectStatus = {\n PITCH: 'PITCH',\n WON: 'WON',\n COMPLETED: 'COMPLETED',\n RECONCILED: 'RECONCILED',\n LOST: 'LOST'\n} as const\n\nexport type ProjectStatus = (typeof ProjectStatus)[keyof typeof ProjectStatus]\n\n\nexport const ProjectWinProofRequirement = {\n PO_REQUIRED: 'PO_REQUIRED',\n SIGNED_QUOTE_REQUIRED: 'SIGNED_QUOTE_REQUIRED'\n} as const\n\nexport type ProjectWinProofRequirement = (typeof ProjectWinProofRequirement)[keyof typeof ProjectWinProofRequirement]\n\n\nexport const BudgetStatus = {\n DRAFT: 'DRAFT',\n PENDING_APPROVAL: 'PENDING_APPROVAL',\n APPROVED: 'APPROVED',\n REJECTED: 'REJECTED',\n ESTIMATE_CREATED: 'ESTIMATE_CREATED',\n ESTIMATE_SENT: 'ESTIMATE_SENT',\n ESTIMATE_ACCEPTED: 'ESTIMATE_ACCEPTED',\n ESTIMATE_REJECTED: 'ESTIMATE_REJECTED',\n ESTIMATE_CLOSED: 'ESTIMATE_CLOSED'\n} as const\n\nexport type BudgetStatus = (typeof BudgetStatus)[keyof typeof BudgetStatus]\n\n\nexport const AsanaExportStatus = {\n NOT_STARTED: 'NOT_STARTED',\n IN_PROGRESS: 'IN_PROGRESS',\n COMPLETED: 'COMPLETED',\n FAILED: 'FAILED'\n} as const\n\nexport type AsanaExportStatus = (typeof AsanaExportStatus)[keyof typeof AsanaExportStatus]\n\n\nexport const ApprovalStatus = {\n PENDING_APPROVAL: 'PENDING_APPROVAL',\n APPROVED: 'APPROVED',\n REJECTED: 'REJECTED',\n SUPERSEDED: 'SUPERSEDED'\n} as const\n\nexport type ApprovalStatus = (typeof ApprovalStatus)[keyof typeof ApprovalStatus]\n\n\nexport const ApprovalType = {\n BUDGET: 'BUDGET',\n SUPPLIER: 'SUPPLIER',\n BILL: 'BILL',\n CUSTOMER_INVOICE: 'CUSTOMER_INVOICE',\n QUOTATION: 'QUOTATION'\n} as const\n\nexport type ApprovalType = (typeof ApprovalType)[keyof typeof ApprovalType]\n\n\nexport const QboOtpChallengeStatus = {\n PENDING: 'PENDING',\n SUBMITTING: 'SUBMITTING',\n SUBMITTED: 'SUBMITTED',\n VERIFIED: 'VERIFIED',\n FAILED: 'FAILED',\n EXPIRED: 'EXPIRED',\n CANCELLED: 'CANCELLED'\n} as const\n\nexport type QboOtpChallengeStatus = (typeof QboOtpChallengeStatus)[keyof typeof QboOtpChallengeStatus]\n\n\nexport const QboOtpMethod = {\n EMAIL: 'EMAIL',\n SMS: 'SMS',\n VOICE: 'VOICE',\n AUTHENTICATOR: 'AUTHENTICATOR',\n UNKNOWN: 'UNKNOWN'\n} as const\n\nexport type QboOtpMethod = (typeof QboOtpMethod)[keyof typeof QboOtpMethod]\n\n\nexport const UserRole = {\n USER: 'USER',\n LEAD: 'LEAD',\n ADMIN: 'ADMIN',\n INSIDE_SALES: 'INSIDE_SALES',\n ACCOUNTING_TEAM: 'ACCOUNTING_TEAM'\n} as const\n\nexport type UserRole = (typeof UserRole)[keyof typeof UserRole]\n\n\nexport const Title = {\n MR: 'MR',\n MRS: 'MRS',\n MS: 'MS',\n DR: 'DR'\n} as const\n\nexport type Title = (typeof Title)[keyof typeof Title]\n\n\nexport const ChangeType = {\n BUDGET_CREATED: 'BUDGET_CREATED',\n BUDGET_DELETED: 'BUDGET_DELETED',\n DETAILS_UPDATED: 'DETAILS_UPDATED',\n MARKUP_UPDATED: 'MARKUP_UPDATED',\n FOC_UPDATED: 'FOC_UPDATED',\n QUANTITY_UPDATED: 'QUANTITY_UPDATED',\n ITEM_REMOVED: 'ITEM_REMOVED',\n ITEM_ADDED: 'ITEM_ADDED',\n VERSION_RESTORED: 'VERSION_RESTORED',\n DISCOUNT_ADDED: 'DISCOUNT_ADDED',\n DISCOUNT_UPDATED: 'DISCOUNT_UPDATED',\n DISCOUNT_REMOVED: 'DISCOUNT_REMOVED',\n ATTACHMENT_ADDED: 'ATTACHMENT_ADDED',\n ATTACHMENTS_UPDATED: 'ATTACHMENTS_UPDATED',\n ATTACHMENT_REMOVED: 'ATTACHMENT_REMOVED',\n CONTACT_PERSON_UPDATED: 'CONTACT_PERSON_UPDATED',\n COMMISSION_ADDED: 'COMMISSION_ADDED',\n COMMISSION_UPDATED: 'COMMISSION_UPDATED',\n COMMISSION_REMOVED: 'COMMISSION_REMOVED',\n DESCRIPTION_UPDATED: 'DESCRIPTION_UPDATED',\n COST_UPDATED: 'COST_UPDATED',\n UNIT_PRICE_UPDATED: 'UNIT_PRICE_UPDATED',\n GST_INCLUSIVE_UPDATED: 'GST_INCLUSIVE_UPDATED',\n NOTE_UPDATED: 'NOTE_UPDATED',\n SUPPLIER_UPDATED: 'SUPPLIER_UPDATED',\n ESTIMATE_CREATED: 'ESTIMATE_CREATED',\n ESTIMATE_SENT: 'ESTIMATE_SENT',\n ESTIMATE_ACCEPTED: 'ESTIMATE_ACCEPTED',\n ESTIMATE_REJECTED: 'ESTIMATE_REJECTED',\n ESTIMATE_CLOSED: 'ESTIMATE_CLOSED',\n ASANA_PROJECT_CREATED: 'ASANA_PROJECT_CREATED',\n APPROVAL_REQUESTED: 'APPROVAL_REQUESTED',\n APPROVAL_UPDATED: 'APPROVAL_UPDATED'\n} as const\n\nexport type ChangeType = (typeof ChangeType)[keyof typeof ChangeType]\n\n\nexport const ActivityActorType = {\n USER: 'USER',\n SYSTEM: 'SYSTEM'\n} as const\n\nexport type ActivityActorType = (typeof ActivityActorType)[keyof typeof ActivityActorType]\n\n\nexport const ActivityEventCategory = {\n COMPANY: 'COMPANY',\n PROJECT: 'PROJECT',\n BUDGET: 'BUDGET',\n BUDGET_ITEM: 'BUDGET_ITEM',\n SUPPLIER: 'SUPPLIER',\n ITEM: 'ITEM',\n BILL: 'BILL',\n CLAIM: 'CLAIM',\n QUOTATION: 'QUOTATION',\n APPROVAL: 'APPROVAL',\n INTEGRATION: 'INTEGRATION',\n SYSTEM: 'SYSTEM'\n} as const\n\nexport type ActivityEventCategory = (typeof ActivityEventCategory)[keyof typeof ActivityEventCategory]\n\n\nexport const ActivitySource = {\n WEB: 'WEB',\n API: 'API',\n MCP: 'MCP',\n CLI: 'CLI',\n SYSTEM: 'SYSTEM',\n QUICKBOOKS: 'QUICKBOOKS',\n ASANA: 'ASANA',\n SCHEDULED_JOB: 'SCHEDULED_JOB'\n} as const\n\nexport type ActivitySource = (typeof ActivitySource)[keyof typeof ActivitySource]\n\n\nexport const ErrorSeverity = {\n LOW: 'LOW',\n MEDIUM: 'MEDIUM',\n HIGH: 'HIGH',\n CRITICAL: 'CRITICAL'\n} as const\n\nexport type ErrorSeverity = (typeof ErrorSeverity)[keyof typeof ErrorSeverity]\n\n\nexport const ErrorStatus = {\n UNRESOLVED: 'UNRESOLVED',\n INVESTIGATING: 'INVESTIGATING',\n RESOLVED: 'RESOLVED',\n IGNORED: 'IGNORED'\n} as const\n\nexport type ErrorStatus = (typeof ErrorStatus)[keyof typeof ErrorStatus]\n\n\nexport const PaymentScheduleStatus = {\n DRAFT: 'DRAFT',\n PENDING_APPROVAL: 'PENDING_APPROVAL',\n APPROVED: 'APPROVED',\n REJECTED: 'REJECTED'\n} as const\n\nexport type PaymentScheduleStatus = (typeof PaymentScheduleStatus)[keyof typeof PaymentScheduleStatus]\n\n\nexport const PaymentScheduleScope = {\n BASE: 'BASE',\n REPLACEMENT: 'REPLACEMENT',\n VARIATION: 'VARIATION'\n} as const\n\nexport type PaymentScheduleScope = (typeof PaymentScheduleScope)[keyof typeof PaymentScheduleScope]\n\n\nexport const PaymentInstalmentStatus = {\n REVIEW: 'REVIEW',\n SCHEDULED: 'SCHEDULED',\n WAITING_CONDITION: 'WAITING_CONDITION',\n BLOCKED: 'BLOCKED',\n READY: 'READY',\n CREATING: 'CREATING',\n FAILED: 'FAILED',\n CREATED: 'CREATED',\n CANCELLED: 'CANCELLED'\n} as const\n\nexport type PaymentInstalmentStatus = (typeof PaymentInstalmentStatus)[keyof typeof PaymentInstalmentStatus]\n\n\nexport const QuickBooksPaymentAccountType = {\n Check: 'Check',\n CreditCard: 'CreditCard'\n} as const\n\nexport type QuickBooksPaymentAccountType = (typeof QuickBooksPaymentAccountType)[keyof typeof QuickBooksPaymentAccountType]\n\n\nexport const CustomerInvoiceSplitMode = {\n FULL: 'FULL',\n PERCENTAGE: 'PERCENTAGE'\n} as const\n\nexport type CustomerInvoiceSplitMode = (typeof CustomerInvoiceSplitMode)[keyof typeof CustomerInvoiceSplitMode]\n\n\nexport const CustomerInvoiceDiscountAllocation = {\n SPLIT_PERCENTAGE: 'SPLIT_PERCENTAGE'\n} as const\n\nexport type CustomerInvoiceDiscountAllocation = (typeof CustomerInvoiceDiscountAllocation)[keyof typeof CustomerInvoiceDiscountAllocation]\n\n\nexport const CustomerInvoiceBatchStatus = {\n CREATING: 'CREATING',\n PENDING_APPROVAL: 'PENDING_APPROVAL',\n APPROVED: 'APPROVED',\n REJECTED_VOIDED: 'REJECTED_VOIDED',\n EXPIRED_VOIDED: 'EXPIRED_VOIDED',\n PARTIAL_QBO_FAILURE: 'PARTIAL_QBO_FAILURE'\n} as const\n\nexport type CustomerInvoiceBatchStatus = (typeof CustomerInvoiceBatchStatus)[keyof typeof CustomerInvoiceBatchStatus]\n\n\nexport const CustomerInvoiceStatus = {\n CREATED_IN_QBO: 'CREATED_IN_QBO',\n APPROVED: 'APPROVED',\n SENT: 'SENT',\n PAID: 'PAID',\n VOIDED: 'VOIDED',\n QBO_SYNC_ERROR: 'QBO_SYNC_ERROR'\n} as const\n\nexport type CustomerInvoiceStatus = (typeof CustomerInvoiceStatus)[keyof typeof CustomerInvoiceStatus]\n\n\nexport const CustomerInvoiceSendSource = {\n BB_EMAIL: 'BB_EMAIL',\n QBO_EMAIL: 'QBO_EMAIL',\n PORTAL_UPLOAD: 'PORTAL_UPLOAD',\n EXTERNAL: 'EXTERNAL'\n} as const\n\nexport type CustomerInvoiceSendSource = (typeof CustomerInvoiceSendSource)[keyof typeof CustomerInvoiceSendSource]\n\n\nexport const CustomerInvoiceDeliveryMethod = {\n EMAIL: 'EMAIL',\n PORTAL_UPLOAD: 'PORTAL_UPLOAD'\n} as const\n\nexport type CustomerInvoiceDeliveryMethod = (typeof CustomerInvoiceDeliveryMethod)[keyof typeof CustomerInvoiceDeliveryMethod]\n\n\nexport const CustomerInvoiceHistorySource = {\n USER: 'USER',\n SYSTEM: 'SYSTEM',\n QBO: 'QBO'\n} as const\n\nexport type CustomerInvoiceHistorySource = (typeof CustomerInvoiceHistorySource)[keyof typeof CustomerInvoiceHistorySource]\n\n\nexport const BillStatus = {\n DRAFT: 'DRAFT',\n PENDING_APPROVAL: 'PENDING_APPROVAL',\n CHECKED: 'CHECKED',\n APPROVED: 'APPROVED',\n PAID: 'PAID',\n REJECTED: 'REJECTED'\n} as const\n\nexport type BillStatus = (typeof BillStatus)[keyof typeof BillStatus]\n\n\nexport const BillIntegrationOperationType = {\n EXTERNAL_PAYMENT: 'EXTERNAL_PAYMENT',\n APPROVAL_FINALIZATION: 'APPROVAL_FINALIZATION',\n DELETE: 'DELETE',\n QUICKBOOKS_SYNC: 'QUICKBOOKS_SYNC'\n} as const\n\nexport type BillIntegrationOperationType = (typeof BillIntegrationOperationType)[keyof typeof BillIntegrationOperationType]\n\n\nexport const BillVerificationStatus = {\n PENDING: 'PENDING',\n PASS: 'PASS',\n FAIL: 'FAIL',\n MANUAL_REVIEW: 'MANUAL_REVIEW'\n} as const\n\nexport type BillVerificationStatus = (typeof BillVerificationStatus)[keyof typeof BillVerificationStatus]\n\n\nexport const CliDeviceAuthorizationStatus = {\n PENDING: 'PENDING',\n APPROVED: 'APPROVED',\n DENIED: 'DENIED',\n CONSUMED: 'CONSUMED',\n EXPIRED: 'EXPIRED'\n} as const\n\nexport type CliDeviceAuthorizationStatus = (typeof CliDeviceAuthorizationStatus)[keyof typeof CliDeviceAuthorizationStatus]\n\n\nexport const CustomerInvoiceSource = {\n NATIVE: 'NATIVE',\n QBO_IMPORT: 'QBO_IMPORT'\n} as const\n\nexport type CustomerInvoiceSource = (typeof CustomerInvoiceSource)[keyof typeof CustomerInvoiceSource]\n\n\nexport const CustomerInvoiceMilestone = {\n FULL: 'FULL',\n DEPOSIT: 'DEPOSIT',\n BALANCE: 'BALANCE',\n CUSTOM: 'CUSTOM'\n} as const\n\nexport type CustomerInvoiceMilestone = (typeof CustomerInvoiceMilestone)[keyof typeof CustomerInvoiceMilestone]\n\n\nexport const WebhookDeliveryStatus = {\n PENDING: 'PENDING',\n SUCCEEDED: 'SUCCEEDED',\n FAILED: 'FAILED'\n} as const\n\nexport type WebhookDeliveryStatus = (typeof WebhookDeliveryStatus)[keyof typeof WebhookDeliveryStatus]\n", "import {\n\tApprovalStatus,\n\tApprovalType,\n\tBillStatus,\n\tBudgetStatus,\n\tErrorSeverity,\n\tErrorStatus,\n\tEstimationMode,\n\tProjectStatus,\n} from \"@go-labs/budget-builder-db/enums\";\n\nexport const ExtendedApprovalStatus = {\n\t...ApprovalStatus,\n\tALL: \"ALL\",\n} as const;\n\nexport type ExtendedApprovalStatus =\n\t(typeof ExtendedApprovalStatus)[keyof typeof ExtendedApprovalStatus];\n\nexport const ExtendedApprovalType = {\n\t...ApprovalType,\n\tALL: \"ALL\",\n} as const;\n\nexport type ExtendedApprovalType =\n\t(typeof ExtendedApprovalType)[keyof typeof ExtendedApprovalType];\n\nexport const ExtendedProjectStatus = {\n\t...ProjectStatus,\n\tALL: \"ALL\",\n} as const;\n\nexport type ExtendedProjectStatus =\n\t(typeof ExtendedProjectStatus)[keyof typeof ExtendedProjectStatus];\n\nexport const ExtendedBudgetStatus = {\n\t...BudgetStatus,\n\tALL: \"ALL\",\n} as const;\n\nexport type ExtendedBudgetStatus =\n\t(typeof ExtendedBudgetStatus)[keyof typeof ExtendedBudgetStatus];\n\nexport const ExtendedBillStatus = {\n\t...BillStatus,\n\tALL: \"ALL\",\n} as const;\n\nexport type ExtendedBillStatus =\n\t(typeof ExtendedBillStatus)[keyof typeof ExtendedBillStatus];\n\nexport const ExtendedEstimationMode = {\n\t...EstimationMode,\n\tALL: \"ALL\",\n} as const;\n\nexport type ExtendedEstimationMode =\n\t(typeof ExtendedEstimationMode)[keyof typeof ExtendedEstimationMode];\n\nexport const BudgetRole = {\n\tALL: \"ALL\",\n\tBD: \"BD\",\n\tCREATOR: \"CREATOR\",\n\tINSIDE_SALES: \"INSIDE_SALES\",\n} as const;\n\nexport type BudgetRole = (typeof BudgetRole)[keyof typeof BudgetRole];\n\nexport const Deals = {\n\tALL: \"ALL\",\n\tSUCCESSFUL: \"SUCCESSFUL\",\n\tLOST: \"LOST\",\n} as const;\n\nexport type Deals = (typeof Deals)[keyof typeof Deals];\n\nexport const TimeFrame = {\n\tALL: \"ALL\",\n\tLAST_YEAR: \"LAST_YEAR\",\n\tLAST_6_MONTHS: \"LAST_6_MONTHS\",\n\tLAST_3_MONTHS: \"LAST_3_MONTHS\",\n\tCUSTOM: \"CUSTOM\",\n} as const;\n\nexport type TimeFrame = (typeof TimeFrame)[keyof typeof TimeFrame];\n\nexport const ChartTimeFrame = {\n\tLAST_30_DAYS: \"last_30_days\",\n\tLAST_3_MONTHS: \"last_3_months\",\n\tLAST_6_MONTHS: \"last_6_months\",\n\tLAST_1_YEAR: \"last_1_year\",\n\tALL_TIME: \"all_time\",\n} as const;\n\nexport type ChartTimeFrame =\n\t(typeof ChartTimeFrame)[keyof typeof ChartTimeFrame];\n\nexport const ExtendedErrorSeverity = {\n\tALL: \"ALL\",\n\t...ErrorSeverity,\n} as const;\n\nexport type ExtendedErrorSeverity =\n\t(typeof ExtendedErrorSeverity)[keyof typeof ExtendedErrorSeverity];\n\nexport const ExtendedErrorStatus = {\n\tALL: \"ALL\",\n\t...ErrorStatus,\n} as const;\n\nexport type ExtendedErrorStatus =\n\t(typeof ExtendedErrorStatus)[keyof typeof ExtendedErrorStatus];\n", "/**\n * Action logging for the CLI (default on).\n * - Lifecycle: `logCliAction` in index (command + timing).\n * - Per API call: tRPC `loggerLink` in api-client when `shouldLogCliActions()`.\n * Logs go to stderr so stdout stays JSON for piping. Use `--quiet` / `-q` / BB_CLI_QUIET=1 to silence.\n */\nlet cliQuietSession = false;\n\n/** Call from main after `consumeCliQuietFlags`. */\nexport const setCliQuiet = (quiet: boolean): void => {\n\tcliQuietSession = quiet;\n};\n\nexport const isCliQuiet = (): boolean =>\n\tcliQuietSession || process.env.BB_CLI_QUIET === \"1\";\n\nexport const shouldLogCliActions = (): boolean => !isCliQuiet();\n\nconst SENSITIVE_FLAG = new Set([\n\t\"payload\",\n\t\"apikey\",\n\t\"bb_api_key\",\n\t\"token\",\n\t\"password\",\n\t\"payment-proof\",\n\t\"paymentproof\",\n\t\"paymentreference\",\n\t\"receipt\",\n\t\"secret\",\n\t\"authorization\",\n]);\n\nconst SENSITIVE_TRACE_FIELD = new Set([\n\t\"secret\",\n\t\"paymentproof\",\n\t\"paymentproofattachments\",\n\t\"paymentproofpath\",\n\t\"paymentreference\",\n\t\"proof\",\n\t\"receipt\",\n]);\n\nconst isPresignedUrl = (value: unknown): value is string =>\n\ttypeof value === \"string\" &&\n\t(/[?&]X-Amz-(?:Algorithm|Credential|Signature)=/i.test(value) ||\n\t\t/[?&]X-Goog-(?:Algorithm|Credential|Signature)=/i.test(value));\n\nexport const sanitizeValueForTrace = (\n\tvalue: unknown,\n\tseen = new WeakSet<object>(),\n): unknown => {\n\tif (typeof value !== \"object\" || value === null) return value;\n\tif (seen.has(value)) return \"[circular]\";\n\tseen.add(value);\n\tif (Array.isArray(value)) {\n\t\treturn value.map((item) => sanitizeValueForTrace(item, seen));\n\t}\n\tif (value instanceof Error) {\n\t\t// tRPC errors carry response data/shape/meta on a non-plain prototype.\n\t\t// Flatten diagnostics only: never return the original inspectable error.\n\t\treturn sanitizeValueForTrace(\n\t\t\t{\n\t\t\t\t...value,\n\t\t\t\tname: value.name,\n\t\t\t\tmessage: value.message,\n\t\t\t\tstack: value.stack,\n\t\t\t},\n\t\t\tseen,\n\t\t);\n\t}\n\tconst prototype = Object.getPrototypeOf(value);\n\tif (prototype !== Object.prototype && prototype !== null) return value;\n\n\treturn Object.fromEntries(\n\t\tObject.entries(value).map(([key, nestedValue]) => [\n\t\t\tkey,\n\t\t\tSENSITIVE_TRACE_FIELD.has(key.toLowerCase()) ||\n\t\t\tisPresignedUrl(nestedValue)\n\t\t\t\t? \"[redacted]\"\n\t\t\t\t: sanitizeValueForTrace(nestedValue, seen),\n\t\t]),\n\t);\n};\n\nexport const sanitizeFlagsForTrace = (\n\tflags: Record<string, string | true>,\n): Record<string, string | true> => {\n\tconst out: Record<string, string | true> = {};\n\tfor (const [k, v] of Object.entries(flags)) {\n\t\tconst lower = k.toLowerCase();\n\t\tif (\n\t\t\tSENSITIVE_FLAG.has(lower) ||\n\t\t\tlower.includes(\"secret\") ||\n\t\t\tlower.includes(\"password\")\n\t\t) {\n\t\t\tout[k] =\n\t\t\t\ttypeof v === \"string\" ? `[redacted ${v.length} chars]` : \"[redacted]\";\n\t\t} else {\n\t\t\tout[k] = v;\n\t\t}\n\t}\n\treturn out;\n};\n\nexport const consumeCliQuietFlags = (\n\tflags: Record<string, string | true>,\n): boolean => {\n\tconst fromEnv = process.env.BB_CLI_QUIET === \"1\";\n\t// `-q` / `--quiet` mean quiet. `--q` is always the search value; a bare\n\t// `--q` is left in place so the command rejects it rather than listing\n\t// everything unfiltered.\n\tconst fromFlags = flags.quiet === true;\n\tdelete flags.quiet;\n\treturn fromEnv || fromFlags;\n};\n\n/** stderr so stdout remains JSON-only for pipes (same intent as “log what the CLI is doing”). */\nexport const logCliAction = (record: Record<string, unknown>): void => {\n\tif (!shouldLogCliActions()) return;\n\tconsole.error(\n\t\t\"[bb]\",\n\t\tJSON.stringify({ ...record, ts: new Date().toISOString() }),\n\t);\n};\n", "export const DEFAULT_BUDGET_BUILDER_API_BASE_URL =\n\t\"https://budget-builder.getout.events\";\n\nexport const normalizeApiBaseUrl = (value: string): string => {\n\tconst url = new URL(value);\n\tconst isLocalHttp =\n\t\turl.protocol === \"http:\" &&\n\t\t(url.hostname === \"localhost\" || url.hostname === \"127.0.0.1\");\n\tif (url.protocol !== \"https:\" && !isLocalHttp) {\n\t\tthrow new Error(\n\t\t\t\"Budget Builder API URL must use HTTPS, except for localhost development.\",\n\t\t);\n\t}\n\turl.pathname = url.pathname.replace(/\\/$/, \"\");\n\treturn url.toString().replace(/\\/$/, \"\");\n};\n", "// src/observable/observable.ts\n/**\n* Whether a value is an observable: an object with `subscribe`.\n* @public\n*/\nfunction isObservable(x) {\n\treturn typeof x === \"object\" && x !== null && \"subscribe\" in x;\n}\n/**\n* Creates an observable. `subscribe` runs for each subscriber, and can\n* return a function that cleans up when it unsubscribes.\n* @example\n* ```ts\n* const ticks = observable<number>((observer) => {\n* const timer = setInterval(() => observer.next(Date.now()), 1000);\n* return () => clearInterval(timer);\n* });\n* ```\n* @see https://trpc.io/docs/client/links#creating-a-custom-link\n* @public\n*/\nfunction observable(subscribe) {\n\tconst self = {\n\t\tsubscribe(observer) {\n\t\t\tlet teardownRef = null;\n\t\t\tlet isDone = false;\n\t\t\tlet unsubscribed = false;\n\t\t\tlet teardownImmediately = false;\n\t\t\tlet subscribing = true;\n\t\t\tlet thrownWhileSubscribing = null;\n\t\t\tfunction end(notify) {\n\t\t\t\ttry {\n\t\t\t\t\tnotify();\n\t\t\t\t} catch (cause) {\n\t\t\t\t\tvar _thrownWhileSubscribi;\n\t\t\t\t\tif (!subscribing) throw cause;\n\t\t\t\t\t(_thrownWhileSubscribi = thrownWhileSubscribing) !== null && _thrownWhileSubscribi !== void 0 || (thrownWhileSubscribing = { cause });\n\t\t\t\t} finally {\n\t\t\t\t\tunsubscribe();\n\t\t\t\t}\n\t\t\t}\n\t\t\tfunction unsubscribe() {\n\t\t\t\tif (teardownRef === null) {\n\t\t\t\t\tteardownImmediately = true;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (unsubscribed) return;\n\t\t\t\tunsubscribed = true;\n\t\t\t\tif (typeof teardownRef === \"function\") teardownRef();\n\t\t\t\telse if (teardownRef) teardownRef.unsubscribe();\n\t\t\t}\n\t\t\tteardownRef = subscribe({\n\t\t\t\tnext(value) {\n\t\t\t\t\tvar _observer$next;\n\t\t\t\t\tif (isDone) return;\n\t\t\t\t\t(_observer$next = observer.next) === null || _observer$next === void 0 || _observer$next.call(observer, value);\n\t\t\t\t},\n\t\t\t\terror(err) {\n\t\t\t\t\tif (isDone) return;\n\t\t\t\t\tisDone = true;\n\t\t\t\t\tend(() => {\n\t\t\t\t\t\tvar _observer$error;\n\t\t\t\t\t\treturn (_observer$error = observer.error) === null || _observer$error === void 0 ? void 0 : _observer$error.call(observer, err);\n\t\t\t\t\t});\n\t\t\t\t},\n\t\t\t\tcomplete() {\n\t\t\t\t\tif (isDone) return;\n\t\t\t\t\tisDone = true;\n\t\t\t\t\tend(() => {\n\t\t\t\t\t\tvar _observer$complete;\n\t\t\t\t\t\treturn (_observer$complete = observer.complete) === null || _observer$complete === void 0 ? void 0 : _observer$complete.call(observer);\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t});\n\t\t\tsubscribing = false;\n\t\t\tif (teardownImmediately) unsubscribe();\n\t\t\tif (thrownWhileSubscribing) throw thrownWhileSubscribing.cause;\n\t\t\treturn { unsubscribe };\n\t\t},\n\t\tpipe(...operations) {\n\t\t\treturn operations.reduce(pipeReducer, self);\n\t\t}\n\t};\n\treturn self;\n}\nfunction pipeReducer(prev, fn) {\n\treturn fn(prev);\n}\n/**\n* Resolves with an observable's first value. Rejects if it errors or\n* completes first. It doesn't unsubscribe after the first value.\n* @internal\n*/\nfunction observableToPromise(observable) {\n\tconst ac = new AbortController();\n\treturn new Promise((resolve, reject) => {\n\t\tlet isDone = false;\n\t\tfunction onDone() {\n\t\t\tif (isDone) return;\n\t\t\tisDone = true;\n\t\t\tobs$.unsubscribe();\n\t\t}\n\t\tac.signal.addEventListener(\"abort\", () => {\n\t\t\treject(ac.signal.reason);\n\t\t});\n\t\tconst obs$ = observable.subscribe({\n\t\t\tnext(data) {\n\t\t\t\tisDone = true;\n\t\t\t\tresolve(data);\n\t\t\t\tonDone();\n\t\t\t},\n\t\t\terror(data) {\n\t\t\t\treject(data);\n\t\t\t},\n\t\t\tcomplete() {\n\t\t\t\tac.abort();\n\t\t\t\tonDone();\n\t\t\t}\n\t\t});\n\t});\n}\n/**\n* Turns an observable into an async iterable, like Node's `events.on()`.\n* Values wait in a queue until `next()` reads them. An error rejects the\n* `next()` after the queued values, once. Completion, `return()` and aborting\n* `signal` unsubscribe and end every pending `next()` with `{ done: true }`;\n* anything the observable sends after that is ignored.\n*\n* If unsubscribing throws, `return()` rejects with the error, and completion\n* or an error from the observable rethrows it. On abort, it rejects the\n* `next()` after the queued values instead, as an error would.\n* @internal\n*/\nfunction observableToAsyncIterable(observable, signal) {\n\tconst values = [];\n\tconst pending = [];\n\tlet error = null;\n\tlet finished = false;\n\tlet subscription = null;\n\t/** Unsubscribes once, and returns what the teardown threw. */\n\tfunction unsubscribe() {\n\t\tif (finished) return null;\n\t\tfinished = true;\n\t\tsignal.removeEventListener(\"abort\", abort);\n\t\ttry {\n\t\t\tsubscription === null || subscription === void 0 || subscription.unsubscribe();\n\t\t\treturn null;\n\t\t} catch (cause) {\n\t\t\treturn { cause };\n\t\t}\n\t}\n\t/** Settles every pending `next()`: the first with `error` if there is one. */\n\tfunction settle() {\n\t\tconst first = error ? pending.shift() : void 0;\n\t\tif (error && first) {\n\t\t\tconst { cause } = error;\n\t\t\terror = null;\n\t\t\tfirst.reject(cause);\n\t\t}\n\t\tfor (const promise of pending.splice(0)) promise.resolve({\n\t\t\tvalue: void 0,\n\t\t\tdone: true\n\t\t});\n\t}\n\tfunction finish() {\n\t\tconst failure = unsubscribe();\n\t\tsettle();\n\t\tif (failure) throw failure.cause;\n\t}\n\tfunction abort() {\n\t\tconst failure = unsubscribe();\n\t\tif (failure) error = failure;\n\t\tsettle();\n\t}\n\tsubscription = observable.subscribe({\n\t\tnext(value) {\n\t\t\tif (finished) return;\n\t\t\tconst promise = pending.shift();\n\t\t\tif (promise) promise.resolve({\n\t\t\t\tvalue,\n\t\t\t\tdone: false\n\t\t\t});\n\t\t\telse values.push(value);\n\t\t},\n\t\terror(cause) {\n\t\t\tif (finished) return;\n\t\t\terror = { cause };\n\t\t\tfinish();\n\t\t},\n\t\tcomplete: finish\n\t});\n\tif (finished) subscription.unsubscribe();\n\telse if (signal.aborted) abort();\n\telse signal.addEventListener(\"abort\", abort, { once: true });\n\tconst iterator = {\n\t\t[Symbol.asyncIterator]() {\n\t\t\treturn iterator;\n\t\t},\n\t\tasync next() {\n\t\t\tif (values.length > 0) return {\n\t\t\t\tvalue: values.shift(),\n\t\t\t\tdone: false\n\t\t\t};\n\t\t\tif (error) {\n\t\t\t\tconst { cause } = error;\n\t\t\t\terror = null;\n\t\t\t\tthrow cause;\n\t\t\t}\n\t\t\tif (finished) return {\n\t\t\t\tvalue: void 0,\n\t\t\t\tdone: true\n\t\t\t};\n\t\t\treturn new Promise((resolve, reject) => {\n\t\t\t\tpending.push({\n\t\t\t\t\tresolve,\n\t\t\t\t\treject\n\t\t\t\t});\n\t\t\t});\n\t\t},\n\t\tasync return() {\n\t\t\tvalues.length = 0;\n\t\t\terror = null;\n\t\t\tfinish();\n\t\t\treturn {\n\t\t\t\tvalue: void 0,\n\t\t\t\tdone: true\n\t\t\t};\n\t\t}\n\t};\n\treturn iterator;\n}\nexport { observableToPromise as i, observable as n, observableToAsyncIterable as r, isObservable as t };\n\n\n//# sourceMappingURL=observable-CodTG6Sf.mjs.map", "import { n as observable } from \"./observable-CodTG6Sf.mjs\";\n// src/observable/operators.ts\n/** Maps each value with `project`. */\nfunction map(project) {\n\treturn (source) => {\n\t\treturn observable((destination) => {\n\t\t\tlet index = 0;\n\t\t\treturn source.subscribe({\n\t\t\t\tnext(value) {\n\t\t\t\t\tdestination.next(project(value, index++));\n\t\t\t\t},\n\t\t\t\terror(error) {\n\t\t\t\t\tdestination.error(error);\n\t\t\t\t},\n\t\t\t\tcomplete() {\n\t\t\t\t\tdestination.complete();\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t};\n}\n/**\n* Shares one subscription to the source between all subscribers. It\n* starts with the first subscriber and ends when the last unsubscribes.\n*/\nfunction share(_opts) {\n\treturn (source) => {\n\t\tlet refCount = 0;\n\t\tlet subscription = null;\n\t\tlet isConnecting = false;\n\t\tlet observers = /* @__PURE__ */ new Set();\n\t\tfunction startIfNeeded() {\n\t\t\tif (subscription || isConnecting) return;\n\t\t\tisConnecting = true;\n\t\t\tlet isDone = false;\n\t\t\tlet sourceSubscription;\n\t\t\ttry {\n\t\t\t\tsourceSubscription = source.subscribe({\n\t\t\t\t\tnext(value) {\n\t\t\t\t\t\tnotify(observers, (observer) => {\n\t\t\t\t\t\t\tvar _observer$next;\n\t\t\t\t\t\t\treturn (_observer$next = observer.next) === null || _observer$next === void 0 ? void 0 : _observer$next.call(observer, value);\n\t\t\t\t\t\t});\n\t\t\t\t\t},\n\t\t\t\t\terror(error) {\n\t\t\t\t\t\tisDone = true;\n\t\t\t\t\t\tterminate((observer) => {\n\t\t\t\t\t\t\tvar _observer$error;\n\t\t\t\t\t\t\treturn (_observer$error = observer.error) === null || _observer$error === void 0 ? void 0 : _observer$error.call(observer, error);\n\t\t\t\t\t\t});\n\t\t\t\t\t},\n\t\t\t\t\tcomplete() {\n\t\t\t\t\t\tisDone = true;\n\t\t\t\t\t\tterminate((observer) => {\n\t\t\t\t\t\t\tvar _observer$complete;\n\t\t\t\t\t\t\treturn (_observer$complete = observer.complete) === null || _observer$complete === void 0 ? void 0 : _observer$complete.call(observer);\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t} finally {\n\t\t\t\tisConnecting = false;\n\t\t\t}\n\t\t\tif (isDone) sourceSubscription.unsubscribe();\n\t\t\telse subscription = sourceSubscription;\n\t\t}\n\t\tfunction notify(targets, callback) {\n\t\t\tfor (const observer of [...targets]) if (targets.has(observer)) callback(observer);\n\t\t}\n\t\tfunction terminate(callback) {\n\t\t\tconst _sub = subscription;\n\t\t\tconst terminatedObservers = observers;\n\t\t\tsubscription = null;\n\t\t\tobservers = /* @__PURE__ */ new Set();\n\t\t\tisConnecting = false;\n\t\t\ttry {\n\t\t\t\tnotify(terminatedObservers, callback);\n\t\t\t} finally {\n\t\t\t\t_sub === null || _sub === void 0 || _sub.unsubscribe();\n\t\t\t}\n\t\t}\n\t\tfunction resetSource() {\n\t\t\tconst _sub = subscription;\n\t\t\tsubscription = null;\n\t\t\t_sub === null || _sub === void 0 || _sub.unsubscribe();\n\t\t}\n\t\tfunction resetIfNeeded() {\n\t\t\tif (refCount === 0 && subscription) resetSource();\n\t\t}\n\t\treturn observable((subscriber) => {\n\t\t\trefCount++;\n\t\t\tconst subscriberObservers = observers;\n\t\t\tsubscriberObservers.add(subscriber);\n\t\t\tstartIfNeeded();\n\t\t\treturn { unsubscribe() {\n\t\t\t\trefCount--;\n\t\t\t\tresetIfNeeded();\n\t\t\t\tsubscriberObservers.delete(subscriber);\n\t\t\t} };\n\t\t});\n\t};\n}\n/** Calls `observer` with each value, error and completion, and passes them on unchanged. */\nfunction tap(observer) {\n\treturn (source) => {\n\t\treturn observable((destination) => {\n\t\t\treturn source.subscribe({\n\t\t\t\tnext(value) {\n\t\t\t\t\tvar _observer$next2;\n\t\t\t\t\t(_observer$next2 = observer.next) === null || _observer$next2 === void 0 || _observer$next2.call(observer, value);\n\t\t\t\t\tdestination.next(value);\n\t\t\t\t},\n\t\t\t\terror(error) {\n\t\t\t\t\tvar _observer$error2;\n\t\t\t\t\t(_observer$error2 = observer.error) === null || _observer$error2 === void 0 || _observer$error2.call(observer, error);\n\t\t\t\t\tdestination.error(error);\n\t\t\t\t},\n\t\t\t\tcomplete() {\n\t\t\t\t\tvar _observer$complete2;\n\t\t\t\t\t(_observer$complete2 = observer.complete) === null || _observer$complete2 === void 0 || _observer$complete2.call(observer);\n\t\t\t\t\tdestination.complete();\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t};\n}\nconst distinctUnsetMarker = Symbol();\n/** Skips values equal to the one before, by `compare` (`===` by default). */\nfunction distinctUntilChanged(compare = (a, b) => a === b) {\n\treturn (source) => {\n\t\treturn observable((destination) => {\n\t\t\tlet lastValue = distinctUnsetMarker;\n\t\t\treturn source.subscribe({\n\t\t\t\tnext(value) {\n\t\t\t\t\tif (lastValue !== distinctUnsetMarker && compare(lastValue, value)) return;\n\t\t\t\t\tlastValue = value;\n\t\t\t\t\tdestination.next(value);\n\t\t\t\t},\n\t\t\t\terror(error) {\n\t\t\t\t\tdestination.error(error);\n\t\t\t\t},\n\t\t\t\tcomplete() {\n\t\t\t\t\tdestination.complete();\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t};\n}\nconst isDeepEqual = (a, b) => {\n\tif (a === b) return true;\n\treturn !!(a && b && typeof a === \"object\" && typeof b === \"object\") && Object.keys(a).length === Object.keys(b).length && Object.entries(a).every(([k, v]) => isDeepEqual(v, b[k]));\n};\n/**\n* Skips values equal to the one before, comparing objects and arrays by\n* their own enumerable keys. Objects without such keys, like two `Date`s,\n* always count as equal.\n*/\nfunction distinctUntilDeepChanged() {\n\treturn distinctUntilChanged(isDeepEqual);\n}\n// src/observable/behaviorSubject.ts\n/**\n* Calls one of several observers. A throw would stop the caller from\n* notifying the rest, so it is rethrown asynchronously instead: it still\n* shows up as an uncaught exception.\n*/\nfunction callObserver(callback) {\n\ttry {\n\t\tcallback();\n\t} catch (error) {\n\t\tsetTimeout(() => {\n\t\t\tthrow error;\n\t\t});\n\t}\n}\n/**\n* Creates an observable that holds a current value. New subscribers get\n* it right away, unless it's `undefined`.\n* @internal\n*/\nfunction behaviorSubject(initialValue) {\n\tlet value = initialValue;\n\tconst observerList = /* @__PURE__ */ new Set();\n\tconst addObserver = (observer) => {\n\t\tif (value !== void 0) observer.next(value);\n\t\tobserverList.add(observer);\n\t};\n\tconst removeObserver = (observer) => {\n\t\tobserverList.delete(observer);\n\t};\n\tconst obs = observable((observer) => {\n\t\taddObserver(observer);\n\t\treturn () => {\n\t\t\tremoveObserver(observer);\n\t\t};\n\t});\n\tobs.next = (nextValue) => {\n\t\tif (value === nextValue) return;\n\t\tvalue = nextValue;\n\t\tfor (const observer of [...observerList]) if (observerList.has(observer)) callObserver(() => observer.next(nextValue));\n\t};\n\tobs.get = () => value;\n\treturn obs;\n}\nexport { share as a, map as i, distinctUntilChanged as n, tap as o, distinctUntilDeepChanged as r, behaviorSubject as t };\n\n\n//# sourceMappingURL=observable-BjUZYMQq.mjs.map", "import { observable } from \"@trpc/server/observable\";\n// src/links/internals/createChain.ts\n/** @internal */\nfunction createChain(opts) {\n\treturn observable((observer) => {\n\t\tfunction execute(index = 0, op = opts.op) {\n\t\t\tconst next = opts.links[index];\n\t\t\tif (!next) throw new Error(\"No more links to execute - did you forget to add an ending link?\");\n\t\t\treturn next({\n\t\t\t\top,\n\t\t\t\tnext(nextOp) {\n\t\t\t\t\treturn execute(index + 1, nextOp);\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t\treturn execute().subscribe(observer);\n\t});\n}\n// src/links/splitLink.ts\nfunction asArray(value) {\n\treturn Array.isArray(value) ? value : [value];\n}\n/**\n* Sends each operation down one of two link chains, based on `condition`.\n*\n* @see https://trpc.io/docs/client/links/splitLink\n*/\nfunction splitLink(opts) {\n\treturn (runtime) => {\n\t\tconst yes = asArray(opts.true).map((link) => link(runtime));\n\t\tconst no = asArray(opts.false).map((link) => link(runtime));\n\t\treturn (props) => {\n\t\t\treturn observable((observer) => {\n\t\t\t\tconst links = opts.condition(props.op) ? yes : no;\n\t\t\t\treturn createChain({\n\t\t\t\t\top: props.op,\n\t\t\t\t\tlinks\n\t\t\t\t}).subscribe(observer);\n\t\t\t});\n\t\t};\n\t};\n}\nexport { createChain as n, splitLink as t };\n\n//# sourceMappingURL=splitLink-PFsRy7Mf.mjs.map", "// \\0@oxc-project+runtime@0.157.0/helpers/esm/typeof.js\nfunction _typeof(o) {\n\t\"@babel/helpers - typeof\";\n\treturn _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function(o) {\n\t\treturn typeof o;\n\t} : function(o) {\n\t\treturn o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o;\n\t}, _typeof(o);\n}\n// \\0@oxc-project+runtime@0.157.0/helpers/esm/toPrimitive.js\nfunction toPrimitive(t, e) {\n\tif (\"object\" != _typeof(t) || !t) return t;\n\tvar r;\n\tif (\"undefined\" != typeof Symbol && void 0 !== (r = t[Symbol.toPrimitive])) {\n\t\tvar i = r.call(t, e || \"default\");\n\t\tif (\"object\" != _typeof(i)) return i;\n\t\tthrow new TypeError(\"@@toPrimitive must return a primitive value.\");\n\t}\n\treturn (\"string\" === e ? String : Number)(t);\n}\n// \\0@oxc-project+runtime@0.157.0/helpers/esm/toPropertyKey.js\nfunction toPropertyKey(t) {\n\tvar i = toPrimitive(t, \"string\");\n\treturn \"symbol\" == _typeof(i) ? i : i + \"\";\n}\n// \\0@oxc-project+runtime@0.157.0/helpers/esm/defineProperty.js\nfunction _defineProperty(e, r, t) {\n\treturn (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {\n\t\tvalue: t,\n\t\tenumerable: !0,\n\t\tconfigurable: !0,\n\t\twritable: !0\n\t}) : e[r] = t, e;\n}\n// \\0@oxc-project+runtime@0.157.0/helpers/esm/objectSpread2.js\nfunction ownKeys(e, r) {\n\tvar t = Object.keys(e);\n\tif (Object.getOwnPropertySymbols) {\n\t\tvar o = Object.getOwnPropertySymbols(e);\n\t\tr && (o = o.filter(function(r) {\n\t\t\treturn Object.getOwnPropertyDescriptor(e, r).enumerable;\n\t\t})), t.push.apply(t, o);\n\t}\n\treturn t;\n}\nfunction _objectSpread2(e) {\n\tfor (var r = 1; r < arguments.length; r++) {\n\t\tvar t = null != arguments[r] ? arguments[r] : {};\n\t\tr % 2 ? ownKeys(Object(t), !0).forEach(function(r) {\n\t\t\t_defineProperty(e, r, t[r]);\n\t\t}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function(r) {\n\t\t\tObject.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));\n\t\t});\n\t}\n\treturn e;\n}\nexport { _defineProperty as n, _objectSpread2 as t };\n", "// src/unstable-core-do-not-import/utils.ts\n/**\n* Ensures there are no duplicate keys when building a procedure.\n* @internal\n*/\nfunction mergeWithoutOverrides(obj1, ...objs) {\n\tconst newObj = Object.assign(emptyObject(), obj1);\n\tfor (const overrides of objs) for (const key in overrides) {\n\t\tif (key in newObj && newObj[key] !== overrides[key]) throw new Error(`Duplicate key ${key}`);\n\t\tnewObj[key] = overrides[key];\n\t}\n\treturn newObj;\n}\n/**\n* Check that value is object\n* @internal\n*/\nfunction isObject(value) {\n\treturn !!value && !Array.isArray(value) && typeof value === \"object\";\n}\nfunction isFunction(fn) {\n\treturn typeof fn === \"function\";\n}\n/**\n* Create an object without inheriting anything from `Object.prototype`\n* @internal\n*/\nfunction emptyObject() {\n\treturn Object.create(null);\n}\nconst asyncIteratorsSupported = typeof Symbol === \"function\" && !!Symbol.asyncIterator;\nfunction isAsyncIterable(value) {\n\treturn asyncIteratorsSupported && isObject(value) && Symbol.asyncIterator in value;\n}\n/**\n* Run an IIFE\n*/\nconst run = (fn) => fn();\nfunction noop() {}\nfunction identity(it) {\n\treturn it;\n}\n/**\n* Generic runtime assertion function. Throws, if the condition is not `true`.\n*\n* Can be used as a slightly less dangerous variant of type assertions. Code\n* mistakes would be revealed at runtime then (hopefully during testing).\n*/\nfunction assert(condition, msg = \"no additional info\") {\n\tif (!condition) throw new Error(`AssertionError: ${msg}`);\n}\nfunction assertNever(value) {\n\tthrow new Error(`AssertionError: unexpected value ${String(value)}`);\n}\nfunction sleep(ms = 0) {\n\treturn new Promise((res) => setTimeout(res, ms));\n}\n/**\n* Ponyfill for\n* [`AbortSignal.any`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/any_static).\n*/\nfunction abortSignalsAnyPonyfill(signals) {\n\tif (typeof AbortSignal.any === \"function\") return AbortSignal.any(signals);\n\tconst ac = new AbortController();\n\tfor (const signal of signals) {\n\t\tif (signal.aborted) {\n\t\t\ttrigger();\n\t\t\tbreak;\n\t\t}\n\t\tsignal.addEventListener(\"abort\", trigger, { once: true });\n\t}\n\treturn ac.signal;\n\tfunction trigger() {\n\t\tac.abort();\n\t\tfor (const signal of signals) signal.removeEventListener(\"abort\", trigger);\n\t}\n}\n// src/unstable-core-do-not-import/rpc/codes.ts\n/**\n* The JSON-RPC 2.0 error code of each tRPC error code. tRPC's own codes\n* use the range JSON-RPC leaves for servers, `-32000` to `-32099`, ending\n* in the digits of the matching HTTP status.\n* @see https://trpc.io/docs/rpc#error-codes---json-rpc-20-error-codes\n*/\nconst TRPC_ERROR_CODES_BY_KEY = {\n\t/**\n\t* Invalid JSON was received by the server.\n\t* An error occurred on the server while parsing the JSON text.\n\t*/\n\tPARSE_ERROR: -32700,\n\t/**\n\t* The JSON sent is not a valid Request object.\n\t*/\n\tBAD_REQUEST: -32600,\n\tINTERNAL_SERVER_ERROR: -32603,\n\tNOT_IMPLEMENTED: -32603,\n\tBAD_GATEWAY: -32603,\n\tSERVICE_UNAVAILABLE: -32603,\n\tGATEWAY_TIMEOUT: -32603,\n\tUNAUTHORIZED: -32001,\n\tPAYMENT_REQUIRED: -32002,\n\tFORBIDDEN: -32003,\n\tNOT_FOUND: -32004,\n\tMETHOD_NOT_SUPPORTED: -32005,\n\tTIMEOUT: -32008,\n\tCONFLICT: -32009,\n\tPRECONDITION_FAILED: -32012,\n\tPAYLOAD_TOO_LARGE: -32013,\n\tUNSUPPORTED_MEDIA_TYPE: -32015,\n\tUNPROCESSABLE_CONTENT: -32022,\n\tPRECONDITION_REQUIRED: -32028,\n\tTOO_MANY_REQUESTS: -32029,\n\tCLIENT_CLOSED_REQUEST: -32099\n};\n/**\n* The tRPC error code of each JSON-RPC 2.0 error code.\n* @see https://trpc.io/docs/rpc#error-codes---json-rpc-20-error-codes\n*/\nconst TRPC_ERROR_CODES_BY_NUMBER = {\n\t[-32700]: \"PARSE_ERROR\",\n\t[-32600]: \"BAD_REQUEST\",\n\t[-32603]: \"INTERNAL_SERVER_ERROR\",\n\t[-32001]: \"UNAUTHORIZED\",\n\t[-32002]: \"PAYMENT_REQUIRED\",\n\t[-32003]: \"FORBIDDEN\",\n\t[-32004]: \"NOT_FOUND\",\n\t[-32005]: \"METHOD_NOT_SUPPORTED\",\n\t[-32008]: \"TIMEOUT\",\n\t[-32009]: \"CONFLICT\",\n\t[-32012]: \"PRECONDITION_FAILED\",\n\t[-32013]: \"PAYLOAD_TOO_LARGE\",\n\t[-32015]: \"UNSUPPORTED_MEDIA_TYPE\",\n\t[-32022]: \"UNPROCESSABLE_CONTENT\",\n\t[-32028]: \"PRECONDITION_REQUIRED\",\n\t[-32029]: \"TOO_MANY_REQUESTS\",\n\t[-32099]: \"CLIENT_CLOSED_REQUEST\"\n};\n/**\n* tRPC error codes that are considered retryable\n* With out of the box SSE, the client will reconnect when these errors are encountered\n*/\nconst retryableRpcCodes = [\n\tTRPC_ERROR_CODES_BY_KEY.BAD_GATEWAY,\n\tTRPC_ERROR_CODES_BY_KEY.SERVICE_UNAVAILABLE,\n\tTRPC_ERROR_CODES_BY_KEY.GATEWAY_TIMEOUT,\n\tTRPC_ERROR_CODES_BY_KEY.INTERNAL_SERVER_ERROR\n];\nexport { assert as a, identity as c, isObject as d, mergeWithoutOverrides as f, sleep as h, abortSignalsAnyPonyfill as i, isAsyncIterable as l, run as m, TRPC_ERROR_CODES_BY_NUMBER as n, assertNever as o, noop as p, retryableRpcCodes as r, emptyObject as s, TRPC_ERROR_CODES_BY_KEY as t, isFunction as u };\n\n\n//# sourceMappingURL=codes-BCsCCyMj.mjs.map", "import { d as isObject, n as TRPC_ERROR_CODES_BY_NUMBER, s as emptyObject, t as TRPC_ERROR_CODES_BY_KEY } from \"./codes-BCsCCyMj.mjs\";\n// src/unstable-core-do-not-import/createProxy.ts\nconst noop = () => {};\nconst freezeIfAvailable = (obj) => {\n\tif (Object.freeze) Object.freeze(obj);\n};\nfunction createInnerProxy(callback, path, memo) {\n\tvar _memo$cacheKey;\n\tconst cacheKey = path.join(\".\");\n\t(_memo$cacheKey = memo[cacheKey]) !== null && _memo$cacheKey !== void 0 || (memo[cacheKey] = new Proxy(noop, {\n\t\tget(_obj, key) {\n\t\t\tif (typeof key !== \"string\" || key === \"then\") return;\n\t\t\treturn createInnerProxy(callback, [...path, key], memo);\n\t\t},\n\t\tapply(_1, _2, args) {\n\t\t\tconst lastOfPath = path[path.length - 1];\n\t\t\tif (lastOfPath === \"valueOf\" || lastOfPath === \"toString\" || lastOfPath === \"toJSON\") return `tRPC.proxy(${path.slice(0, -1).join(\".\")})`;\n\t\t\tlet opts = {\n\t\t\t\targs,\n\t\t\t\tpath\n\t\t\t};\n\t\t\tif (lastOfPath === \"call\") opts = {\n\t\t\t\targs: args.length >= 2 ? [args[1]] : [],\n\t\t\t\tpath: path.slice(0, -1)\n\t\t\t};\n\t\t\telse if (lastOfPath === \"apply\") opts = {\n\t\t\t\targs: args.length >= 2 ? args[1] : [],\n\t\t\t\tpath: path.slice(0, -1)\n\t\t\t};\n\t\t\tfreezeIfAvailable(opts.args);\n\t\t\tfreezeIfAvailable(opts.path);\n\t\t\treturn callback(opts);\n\t\t}\n\t}));\n\treturn memo[cacheKey];\n}\n/**\n* Creates a proxy that records the property path it's accessed with, and\n* calls `callback` with the path and arguments when it's called.\n* @internal\n*/\nconst createRecursiveProxy = (callback) => createInnerProxy(callback, [], emptyObject());\n/**\n* Creates a proxy that maps each property to `callback(name)`, one level\n* deep. It's not thenable.\n* @internal\n*/\nconst createFlatProxy = (callback) => {\n\treturn new Proxy(noop, { get(_obj, name) {\n\t\tif (name === \"then\") return;\n\t\treturn callback(name);\n\t} });\n};\n// src/unstable-core-do-not-import/http/getHTTPStatusCode.ts\nconst JSONRPC2_TO_HTTP_CODE = {\n\tPARSE_ERROR: 400,\n\tBAD_REQUEST: 400,\n\tUNAUTHORIZED: 401,\n\tPAYMENT_REQUIRED: 402,\n\tFORBIDDEN: 403,\n\tNOT_FOUND: 404,\n\tMETHOD_NOT_SUPPORTED: 405,\n\tTIMEOUT: 408,\n\tCONFLICT: 409,\n\tPRECONDITION_FAILED: 412,\n\tPAYLOAD_TOO_LARGE: 413,\n\tUNSUPPORTED_MEDIA_TYPE: 415,\n\tUNPROCESSABLE_CONTENT: 422,\n\tPRECONDITION_REQUIRED: 428,\n\tTOO_MANY_REQUESTS: 429,\n\tCLIENT_CLOSED_REQUEST: 499,\n\tINTERNAL_SERVER_ERROR: 500,\n\tNOT_IMPLEMENTED: 501,\n\tBAD_GATEWAY: 502,\n\tSERVICE_UNAVAILABLE: 503,\n\tGATEWAY_TIMEOUT: 504\n};\nconst HTTP_CODE_TO_JSONRPC2 = {\n\t400: \"BAD_REQUEST\",\n\t401: \"UNAUTHORIZED\",\n\t402: \"PAYMENT_REQUIRED\",\n\t403: \"FORBIDDEN\",\n\t404: \"NOT_FOUND\",\n\t405: \"METHOD_NOT_SUPPORTED\",\n\t408: \"TIMEOUT\",\n\t409: \"CONFLICT\",\n\t412: \"PRECONDITION_FAILED\",\n\t413: \"PAYLOAD_TOO_LARGE\",\n\t415: \"UNSUPPORTED_MEDIA_TYPE\",\n\t422: \"UNPROCESSABLE_CONTENT\",\n\t428: \"PRECONDITION_REQUIRED\",\n\t429: \"TOO_MANY_REQUESTS\",\n\t499: \"CLIENT_CLOSED_REQUEST\",\n\t500: \"INTERNAL_SERVER_ERROR\",\n\t501: \"NOT_IMPLEMENTED\",\n\t502: \"BAD_GATEWAY\",\n\t503: \"SERVICE_UNAVAILABLE\",\n\t504: \"GATEWAY_TIMEOUT\"\n};\nfunction getStatusCodeFromKey(code) {\n\tvar _JSONRPC2_TO_HTTP_COD;\n\treturn (_JSONRPC2_TO_HTTP_COD = JSONRPC2_TO_HTTP_CODE[code]) !== null && _JSONRPC2_TO_HTTP_COD !== void 0 ? _JSONRPC2_TO_HTTP_COD : 500;\n}\nfunction getStatusKeyFromCode(code) {\n\tvar _HTTP_CODE_TO_JSONRPC;\n\treturn (_HTTP_CODE_TO_JSONRPC = HTTP_CODE_TO_JSONRPC2[code]) !== null && _HTTP_CODE_TO_JSONRPC !== void 0 ? _HTTP_CODE_TO_JSONRPC : \"INTERNAL_SERVER_ERROR\";\n}\n/**\n* The HTTP status for a response, or for a batch of them: `207` when the\n* responses' statuses differ.\n* @see https://trpc.io/docs/rpc#error-codes---http-status\n*/\nfunction getHTTPStatusCode(json, errors) {\n\tconst httpStatuses = new Set((Array.isArray(json) ? json : [json]).map((res, index) => {\n\t\tif (\"error\" in res) {\n\t\t\tif (isObject(res.error.data) && typeof res.error.data[\"httpStatus\"] === \"number\") return res.error.data[\"httpStatus\"];\n\t\t\tconst original = errors === null || errors === void 0 ? void 0 : errors[index];\n\t\t\tif (original) return getStatusCodeFromKey(original.code);\n\t\t\tconst code = TRPC_ERROR_CODES_BY_NUMBER[res.error.code];\n\t\t\treturn getStatusCodeFromKey(code);\n\t\t}\n\t\treturn 200;\n\t}));\n\tif (httpStatuses.size !== 1) return 207;\n\treturn httpStatuses.values().next().value;\n}\n/**\n* The HTTP status of a `TRPCError`'s code.\n* @see https://trpc.io/docs/rpc#error-codes---http-status\n*/\nfunction getHTTPStatusCodeFromError(error) {\n\treturn getStatusCodeFromKey(error.code);\n}\n// src/unstable-core-do-not-import/error/formatter.ts\nconst defaultFormatter = ({ shape }) => {\n\treturn shape;\n};\n/**\n* @internal\n*/\nfunction getDefaultErrorShape(opts) {\n\tconst shape = {\n\t\tmessage: opts.error.message,\n\t\tcode: TRPC_ERROR_CODES_BY_KEY[opts.error.code],\n\t\tdata: {\n\t\t\tcode: opts.error.code,\n\t\t\thttpStatus: getHTTPStatusCodeFromError(opts.error)\n\t\t}\n\t};\n\tif (opts.isDev && typeof opts.error.stack === \"string\") shape.data.stack = opts.error.stack;\n\tif (typeof opts.path === \"string\") shape.data.path = opts.path;\n\treturn shape;\n}\nconst formattedShapeSymbol = Symbol(\"trpc_formattedErrorShape\");\n/**\n* @internal\n*/\nfunction setFormattedErrorShape(error, shape) {\n\tObject.defineProperty(error, formattedShapeSymbol, {\n\t\tvalue: shape,\n\t\tenumerable: false,\n\t\tconfigurable: true,\n\t\twritable: true\n\t});\n}\n/**\n* @internal\n*/\nfunction getFormattedErrorShape(error) {\n\tif (isFormattedErrorShape(error)) return error[formattedShapeSymbol];\n}\nfunction isFormattedErrorShape(error) {\n\treturn formattedShapeSymbol in error;\n}\n// \\0@oxc-project+runtime@0.157.0/helpers/esm/typeof.js\nfunction _typeof(o) {\n\t\"@babel/helpers - typeof\";\n\treturn _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function(o) {\n\t\treturn typeof o;\n\t} : function(o) {\n\t\treturn o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o;\n\t}, _typeof(o);\n}\n// \\0@oxc-project+runtime@0.157.0/helpers/esm/toPrimitive.js\nfunction toPrimitive(t, e) {\n\tif (\"object\" != _typeof(t) || !t) return t;\n\tvar r;\n\tif (\"undefined\" != typeof Symbol && void 0 !== (r = t[Symbol.toPrimitive])) {\n\t\tvar i = r.call(t, e || \"default\");\n\t\tif (\"object\" != _typeof(i)) return i;\n\t\tthrow new TypeError(\"@@toPrimitive must return a primitive value.\");\n\t}\n\treturn (\"string\" === e ? String : Number)(t);\n}\n// \\0@oxc-project+runtime@0.157.0/helpers/esm/toPropertyKey.js\nfunction toPropertyKey(t) {\n\tvar i = toPrimitive(t, \"string\");\n\treturn \"symbol\" == _typeof(i) ? i : i + \"\";\n}\n// \\0@oxc-project+runtime@0.157.0/helpers/esm/defineProperty.js\nfunction _defineProperty(e, r, t) {\n\treturn (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {\n\t\tvalue: t,\n\t\tenumerable: !0,\n\t\tconfigurable: !0,\n\t\twritable: !0\n\t}) : e[r] = t, e;\n}\n// \\0@oxc-project+runtime@0.157.0/helpers/esm/objectSpread2.js\nfunction ownKeys(e, r) {\n\tvar t = Object.keys(e);\n\tif (Object.getOwnPropertySymbols) {\n\t\tvar o = Object.getOwnPropertySymbols(e);\n\t\tr && (o = o.filter(function(r) {\n\t\t\treturn Object.getOwnPropertyDescriptor(e, r).enumerable;\n\t\t})), t.push.apply(t, o);\n\t}\n\treturn t;\n}\nfunction _objectSpread2(e) {\n\tfor (var r = 1; r < arguments.length; r++) {\n\t\tvar t = null != arguments[r] ? arguments[r] : {};\n\t\tr % 2 ? ownKeys(Object(t), !0).forEach(function(r) {\n\t\t\t_defineProperty(e, r, t[r]);\n\t\t}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function(r) {\n\t\t\tObject.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));\n\t\t});\n\t}\n\treturn e;\n}\n// src/unstable-core-do-not-import/error/getErrorShape.ts\n/**\n* The shape of an error as the client gets it: from a procedure's\n* `.errors()` formatter if one ran, or else from the root error formatter.\n* @internal\n*/\nfunction getErrorShape(opts) {\n\tconst { path, error, config } = opts;\n\tconst formatted = getFormattedErrorShape(error);\n\tif (formatted !== void 0) return formatted;\n\tconst shape = getDefaultErrorShape({\n\t\terror,\n\t\tpath,\n\t\tisDev: config.isDev\n\t});\n\treturn config.errorFormatter(_objectSpread2(_objectSpread2({}, opts), {}, { shape }));\n}\nexport { getDefaultErrorShape as a, setFormattedErrorShape as c, getHTTPStatusCode as d, getHTTPStatusCodeFromError as f, createRecursiveProxy as g, createFlatProxy as h, defaultFormatter as i, HTTP_CODE_TO_JSONRPC2 as l, getStatusKeyFromCode as m, _objectSpread2 as n, getFormattedErrorShape as o, getStatusCodeFromKey as p, _defineProperty as r, isFormattedErrorShape as s, getErrorShape as t, JSONRPC2_TO_HTTP_CODE as u };\n\n\n//# sourceMappingURL=getErrorShape-CVrl8_-w.mjs.map", "import { d as isObject, f as mergeWithoutOverrides, s as emptyObject, u as isFunction } from \"./codes-BCsCCyMj.mjs\";\nimport { g as createRecursiveProxy, i as defaultFormatter, n as _objectSpread2, r as _defineProperty } from \"./getErrorShape-CVrl8_-w.mjs\";\n// src/unstable-core-do-not-import/error/TRPCError.ts\nvar UnknownCauseError = class extends Error {\n\tconstructor(cause) {\n\t\tsuper(getMessage(cause));\n\t\tObject.assign(this, cause);\n\t\tif (isErrorLike(cause)) {\n\t\t\tif (typeof cause.name === \"string\") this.name = cause.name;\n\t\t\tif (typeof cause.stack === \"string\") this.stack = cause.stack;\n\t\t}\n\t}\n};\nfunction getMessage(cause) {\n\tif (\"message\" in cause) return String(cause.message);\n}\n/**\n* Errors from another realm (e.g. `node:vm`, iframes) fail `instanceof Error`\n* but still carry the `[object Error]` brand.\n*/\nfunction isErrorLike(value) {\n\treturn value instanceof Error || Object.prototype.toString.call(value) === \"[object Error]\";\n}\nfunction getCauseFromUnknown(cause) {\n\tif (cause instanceof Error) return cause;\n\tconst type = typeof cause;\n\tif (type === \"undefined\" || type === \"function\" || cause === null) return;\n\tif (type !== \"object\") return new Error(String(cause));\n\tif (isObject(cause)) return new UnknownCauseError(cause);\n}\n/**\n* Turns anything thrown into a `TRPCError`. A `TRPCError` is returned as\n* is; anything else becomes an `INTERNAL_SERVER_ERROR` with it as the\n* cause.\n*/\nfunction getTRPCErrorFromUnknown(cause) {\n\tif (cause instanceof TRPCError) return cause;\n\tif (cause instanceof Error && cause.name === \"TRPCError\") return cause;\n\tconst trpcError = new TRPCError({\n\t\tcode: \"INTERNAL_SERVER_ERROR\",\n\t\tcause\n\t});\n\tif (isErrorLike(cause) && cause.stack) trpcError.stack = cause.stack;\n\treturn trpcError;\n}\n/**\n* An error with a tRPC error code, which sets the HTTP status and the code\n* the client sees. Throw it from resolvers and middlewares.\n* @example\n* ```ts\n* throw new TRPCError({ code: 'NOT_FOUND', message: 'No such post' });\n* ```\n* @see https://trpc.io/docs/server/error-handling#throwing-errors\n*/\nvar TRPCError = class extends Error {\n\tconstructor(opts) {\n\t\tvar _ref, _opts$message, _this$cause;\n\t\tconst cause = getCauseFromUnknown(opts.cause);\n\t\tconst message = (_ref = (_opts$message = opts.message) !== null && _opts$message !== void 0 ? _opts$message : cause === null || cause === void 0 ? void 0 : cause.message) !== null && _ref !== void 0 ? _ref : opts.code;\n\t\tsuper(message, { cause });\n\t\t_defineProperty(this, \"cause\", void 0);\n\t\t_defineProperty(this, \"code\", void 0);\n\t\tthis.code = opts.code;\n\t\tthis.name = \"TRPCError\";\n\t\t(_this$cause = this.cause) !== null && _this$cause !== void 0 || (this.cause = cause);\n\t}\n};\n// src/unstable-core-do-not-import/transformer.ts\n/**\n* @internal\n*/\nfunction getDataTransformer(transformer) {\n\tif (\"input\" in transformer) return transformer;\n\treturn {\n\t\tinput: transformer,\n\t\toutput: transformer\n\t};\n}\n/**\n* @internal\n*/\nconst defaultTransformer = {\n\tinput: {\n\t\tserialize: (obj) => obj,\n\t\tdeserialize: (obj) => obj\n\t},\n\toutput: {\n\t\tserialize: (obj) => obj,\n\t\tdeserialize: (obj) => obj\n\t}\n};\nfunction transformTRPCResponseItem(config, item) {\n\tif (\"error\" in item) return _objectSpread2(_objectSpread2({}, item), {}, { error: config.transformer.output.serialize(item.error) });\n\tif (\"data\" in item.result) return _objectSpread2(_objectSpread2({}, item), {}, { result: _objectSpread2(_objectSpread2({}, item.result), {}, { data: config.transformer.output.serialize(item.result.data) }) });\n\treturn item;\n}\n/**\n* Serializes a response, or a list of them, with the router's output\n* transformer. Meant for custom adapters.\n**/\nfunction transformTRPCResponse(config, itemOrItems) {\n\treturn Array.isArray(itemOrItems) ? itemOrItems.map((item) => transformTRPCResponseItem(config, item)) : transformTRPCResponseItem(config, itemOrItems);\n}\n/** @internal */\nfunction transformResultInner(response, transformer) {\n\tif (\"error\" in response) {\n\t\tconst error = transformer.deserialize(response.error);\n\t\treturn {\n\t\t\tok: false,\n\t\t\terror: _objectSpread2(_objectSpread2({}, response), {}, { error })\n\t\t};\n\t}\n\treturn {\n\t\tok: true,\n\t\tresult: _objectSpread2(_objectSpread2({}, response.result), (!response.result.type || response.result.type === \"data\") && {\n\t\t\ttype: \"data\",\n\t\t\tdata: transformer.deserialize(response.result.data)\n\t\t})\n\t};\n}\nvar TransformResultError = class extends Error {\n\tconstructor() {\n\t\tsuper(\"Unable to transform response from server\");\n\t}\n};\n/**\n* Transforms and validates that the result is a valid TRPCResponse\n* @internal\n*/\nfunction transformResult(response, transformer) {\n\tlet result;\n\ttry {\n\t\tresult = transformResultInner(response, transformer);\n\t} catch (_unused) {\n\t\tthrow new TransformResultError();\n\t}\n\tif (!result.ok && (!isObject(result.error.error) || typeof result.error.error[\"code\"] !== \"number\")) throw new TransformResultError();\n\tif (result.ok && !isObject(result.result)) throw new TransformResultError();\n\treturn result;\n}\n// src/unstable-core-do-not-import/router.ts\n/**\n* @internal\n*/\nconst lazyMarker = \"lazyMarker\";\nfunction once(fn) {\n\tconst uncalled = Symbol();\n\tlet result = uncalled;\n\treturn () => {\n\t\tif (result === uncalled) result = fn();\n\t\treturn result;\n\t};\n}\n/**\n* Loads a router on its first call instead of at startup, which can make\n* cold starts faster. Pass a function that imports the router, or a module\n* whose only export is the router.\n* @example\n* ```ts\n* const appRouter = router({\n* slow: lazy(() => import('./slow.js').then((m) => m.slowRouter)),\n* });\n* ```\n* @see https://trpc.io/docs/server/merging-routers#lazy-load\n*/\nfunction lazy(importRouter) {\n\tasync function resolve() {\n\t\tconst mod = await importRouter();\n\t\tif (isRouter(mod)) return mod;\n\t\tconst routers = Object.values(mod);\n\t\tif (routers.length !== 1 || !isRouter(routers[0])) throw new Error(\"Invalid router module - either define exactly 1 export or return the router directly.\\nExample: `lazy(() => import('./slow.js').then((m) => m.slowRouter))`\");\n\t\treturn routers[0];\n\t}\n\tresolve[lazyMarker] = true;\n\treturn resolve;\n}\nfunction isLazy(input) {\n\treturn typeof input === \"function\" && lazyMarker in input;\n}\nfunction isRouter(value) {\n\treturn isObject(value) && isObject(value[\"_def\"]) && \"router\" in value[\"_def\"];\n}\nconst emptyRouter = {\n\t_ctx: null,\n\t_errorShape: null,\n\t_meta: null,\n\tqueries: {},\n\tmutations: {},\n\tsubscriptions: {},\n\terrorFormatter: defaultFormatter,\n\ttransformer: defaultTransformer\n};\n/**\n* Reserved words that can't be used as router or procedure names\n*/\nconst reservedWords = [\n\t\"then\",\n\t\"call\",\n\t\"apply\"\n];\nfunction getRouterInput(router) {\n\tconst input = Object.assign(emptyObject(), router._def.record);\n\tfor (const loader of Object.values(router._def.lazy)) {\n\t\tlet record = input;\n\t\tfor (const key of loader.path) record = record[key] = Object.assign(emptyObject(), record[key]);\n\t\trecord[loader.key] = loader.ref;\n\t}\n\treturn input;\n}\n/**\n* @internal\n*/\nfunction createRouterFactory(config) {\n\tfunction createRouterInner(input) {\n\t\tconst reservedWordsUsed = new Set(Object.keys(input).filter((v) => reservedWords.includes(v)));\n\t\tif (reservedWordsUsed.size > 0) throw new Error(\"Reserved words used in `router({})` call: \" + Array.from(reservedWordsUsed).join(\", \"));\n\t\tconst procedures = emptyObject();\n\t\tconst lazy = emptyObject();\n\t\tfunction createLazyLoader(opts) {\n\t\t\treturn {\n\t\t\t\tref: opts.ref,\n\t\t\t\tpath: opts.path,\n\t\t\t\tkey: opts.key,\n\t\t\t\tload: once(async () => {\n\t\t\t\t\tconst router = await opts.ref();\n\t\t\t\t\tconst lazyPath = [...opts.path, opts.key];\n\t\t\t\t\tconst lazyKey = lazyPath.join(\".\");\n\t\t\t\t\topts.aggregate[opts.key] = step(getRouterInput(router), lazyPath);\n\t\t\t\t\tdelete lazy[lazyKey];\n\t\t\t\t})\n\t\t\t};\n\t\t}\n\t\tconst separator = config.pathSeparator;\n\t\tfunction step(from, path = []) {\n\t\t\tconst aggregate = emptyObject();\n\t\t\tfor (const [key, item] of Object.entries(from !== null && from !== void 0 ? from : {})) {\n\t\t\t\tif (separator !== \".\" && key.includes(separator)) throw new Error(`Key \"${[...path, key].join(\".\")}\" contains the pathSeparator ${JSON.stringify(separator)}, so its URL would be ambiguous. Rename it or pick another pathSeparator.`);\n\t\t\t\tif (isLazy(item)) {\n\t\t\t\t\tlazy[[...path, key].join(\".\")] = createLazyLoader({\n\t\t\t\t\t\tpath,\n\t\t\t\t\t\tref: item,\n\t\t\t\t\t\tkey,\n\t\t\t\t\t\taggregate\n\t\t\t\t\t});\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (isRouter(item)) {\n\t\t\t\t\taggregate[key] = step(getRouterInput(item), [...path, key]);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (!isProcedure(item)) {\n\t\t\t\t\taggregate[key] = step(item, [...path, key]);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst newPath = [...path, key].join(\".\");\n\t\t\t\tif (procedures[newPath]) throw new Error(`Duplicate key: ${newPath}`);\n\t\t\t\tprocedures[newPath] = item;\n\t\t\t\taggregate[key] = item;\n\t\t\t}\n\t\t\treturn aggregate;\n\t\t}\n\t\tconst record = step(input);\n\t\tconst _def = _objectSpread2(_objectSpread2({\n\t\t\t_config: config,\n\t\t\trouter: true,\n\t\t\tprocedures,\n\t\t\tlazy\n\t\t}, emptyRouter), {}, { record });\n\t\treturn _objectSpread2(_objectSpread2({}, record), {}, {\n\t\t\t_def,\n\t\t\tcreateCaller: createCallerFactory()({ _def })\n\t\t});\n\t}\n\treturn createRouterInner;\n}\nfunction isProcedure(procedureOrRouter) {\n\treturn typeof procedureOrRouter === \"function\";\n}\n/**\n* @internal\n*/\nasync function getProcedureAtPath(router, path) {\n\tconst { _def } = router;\n\tlet procedure = _def.procedures[path];\n\twhile (!procedure) {\n\t\tconst key = Object.keys(_def.lazy).find((key) => path === key || path.startsWith(key + \".\"));\n\t\tif (!key) return null;\n\t\tawait _def.lazy[key].load();\n\t\tprocedure = _def.procedures[path];\n\t}\n\treturn procedure;\n}\n/**\n* Calls the procedure at `path`, throwing `NOT_FOUND` if there's none of\n* that type.\n* @internal\n*/\nasync function callProcedure(opts) {\n\tconst { type, path } = opts;\n\tconst proc = await getProcedureAtPath(opts.router, path);\n\tif (!proc || !isProcedure(proc) || proc._def.type !== type && !opts.allowMethodOverride) throw new TRPCError({\n\t\tcode: \"NOT_FOUND\",\n\t\tmessage: `No \"${type}\"-procedure on path \"${path}\"`\n\t});\n\t/* istanbul ignore if -- @preserve */\n\tif (proc._def.type !== type && opts.allowMethodOverride && proc._def.type === \"subscription\") throw new TRPCError({\n\t\tcode: \"METHOD_NOT_SUPPORTED\",\n\t\tmessage: `Method override is not supported for subscriptions`\n\t});\n\treturn proc(opts);\n}\nfunction createCallerFactory() {\n\treturn function createCallerInner(router) {\n\t\tconst { _def } = router;\n\t\treturn function createCaller(ctxOrCallback, opts) {\n\t\t\treturn createRecursiveProxy(async (innerOpts) => {\n\t\t\t\tconst { path, args } = innerOpts;\n\t\t\t\tconst fullPath = path.join(\".\");\n\t\t\t\tif (path.length === 1 && path[0] === \"_def\") return _def;\n\t\t\t\tconst procedure = await getProcedureAtPath(router, fullPath);\n\t\t\t\tlet ctx = void 0;\n\t\t\t\ttry {\n\t\t\t\t\tif (!procedure) throw new TRPCError({\n\t\t\t\t\t\tcode: \"NOT_FOUND\",\n\t\t\t\t\t\tmessage: `No procedure found on path \"${path}\"`\n\t\t\t\t\t});\n\t\t\t\t\tctx = isFunction(ctxOrCallback) ? await Promise.resolve(ctxOrCallback()) : ctxOrCallback;\n\t\t\t\t\treturn await procedure({\n\t\t\t\t\t\tpath: fullPath,\n\t\t\t\t\t\tgetRawInput: async () => args[0],\n\t\t\t\t\t\tctx,\n\t\t\t\t\t\ttype: procedure._def.type,\n\t\t\t\t\t\tsignal: opts === null || opts === void 0 ? void 0 : opts.signal,\n\t\t\t\t\t\tbatchIndex: 0\n\t\t\t\t\t});\n\t\t\t\t} catch (cause) {\n\t\t\t\t\tvar _opts$onError, _procedure$_def$type;\n\t\t\t\t\topts === null || opts === void 0 || (_opts$onError = opts.onError) === null || _opts$onError === void 0 || _opts$onError.call(opts, {\n\t\t\t\t\t\tctx,\n\t\t\t\t\t\terror: getTRPCErrorFromUnknown(cause),\n\t\t\t\t\t\tinput: args[0],\n\t\t\t\t\t\tpath: fullPath,\n\t\t\t\t\t\ttype: (_procedure$_def$type = procedure === null || procedure === void 0 ? void 0 : procedure._def.type) !== null && _procedure$_def$type !== void 0 ? _procedure$_def$type : \"unknown\"\n\t\t\t\t\t});\n\t\t\t\t\tthrow cause;\n\t\t\t\t}\n\t\t\t});\n\t\t};\n\t};\n}\nfunction mergeRouters(...routerList) {\n\tvar _routerList$, _routerList$2;\n\tconst record = mergeWithoutOverrides({}, ...[...new Set(routerList)].map((r) => getRouterInput(r)));\n\treturn createRouterFactory({\n\t\terrorFormatter: routerList.reduce((currentErrorFormatter, nextRouter) => {\n\t\t\tif (nextRouter._def._config.errorFormatter && nextRouter._def._config.errorFormatter !== defaultFormatter) {\n\t\t\t\tif (currentErrorFormatter !== defaultFormatter && currentErrorFormatter !== nextRouter._def._config.errorFormatter) throw new Error(\"You seem to have several error formatters\");\n\t\t\t\treturn nextRouter._def._config.errorFormatter;\n\t\t\t}\n\t\t\treturn currentErrorFormatter;\n\t\t}, defaultFormatter),\n\t\ttransformer: routerList.reduce((prev, current) => {\n\t\t\tif (current._def._config.transformer && current._def._config.transformer !== defaultTransformer) {\n\t\t\t\tif (prev !== defaultTransformer && prev !== current._def._config.transformer) throw new Error(\"You seem to have several transformers\");\n\t\t\t\treturn current._def._config.transformer;\n\t\t\t}\n\t\t\treturn prev;\n\t\t}, defaultTransformer),\n\t\tpathSeparator: routerList.reduce((prev, current) => {\n\t\t\tconst next = current._def._config.pathSeparator;\n\t\t\tif (next === \".\") return prev;\n\t\t\tif (prev !== \".\" && prev !== next) throw new Error(\"You seem to have several pathSeparators\");\n\t\t\treturn next;\n\t\t}, \".\"),\n\t\tisDev: routerList.every((r) => r._def._config.isDev),\n\t\tallowOutsideOfServer: routerList.every((r) => r._def._config.allowOutsideOfServer),\n\t\tisServer: routerList.every((r) => r._def._config.isServer),\n\t\t$types: (_routerList$ = routerList[0]) === null || _routerList$ === void 0 ? void 0 : _routerList$._def._config.$types,\n\t\tsse: (_routerList$2 = routerList[0]) === null || _routerList$2 === void 0 ? void 0 : _routerList$2._def._config.sse\n\t})(record);\n}\n// src/unstable-core-do-not-import/http/pathSeparator.ts\n/**\n* Applies the `'.'` default to a user-given `pathSeparator` option. Call it\n* once, where the option is read.\n* @internal\n*/\nfunction resolvePathSeparator(value) {\n\treturn value !== null && value !== void 0 ? value : \".\";\n}\n/**\n* `post.byId` → `post~byId`, for building URLs.\n* @internal\n*/\nfunction procedurePathToURLPath(path, separator) {\n\tif (separator === \".\") return path;\n\treturn path.split(\".\").join(separator);\n}\n/**\n* `post~byId` → `post.byId`, for reading URLs. Dotted paths still resolve,\n* so clients can move to the separator after the server does.\n* @internal\n*/\nfunction urlPathToProcedurePath(path, separator) {\n\tif (separator === \".\") return path;\n\treturn path.split(separator).join(\".\");\n}\n// \\0@oxc-project+runtime@0.157.0/helpers/esm/OverloadYield.js\nfunction _OverloadYield(e, d) {\n\tthis.v = e, this.k = d;\n}\n// \\0@oxc-project+runtime@0.157.0/helpers/esm/wrapAsyncGenerator.js\nfunction _wrapAsyncGenerator(e) {\n\treturn function() {\n\t\treturn new AsyncGenerator(e.apply(this, arguments));\n\t};\n}\nfunction AsyncGenerator(e) {\n\tvar t, n;\n\tfunction resume(t, n) {\n\t\ttry {\n\t\t\tvar r = e[t](n), o = r.value, u = o instanceof _OverloadYield;\n\t\t\tPromise.resolve(u ? o.v : o).then(function(n) {\n\t\t\t\tif (u) {\n\t\t\t\t\tvar i = \"return\" === t && o.k ? t : \"next\";\n\t\t\t\t\tif (!o.k || n.done) return resume(i, n);\n\t\t\t\t\tn = e[i](n).value;\n\t\t\t\t}\n\t\t\t\tsettle(!!r.done, n);\n\t\t\t}, function(e) {\n\t\t\t\tresume(\"throw\", e);\n\t\t\t});\n\t\t} catch (e) {\n\t\t\tsettle(2, e);\n\t\t}\n\t}\n\tfunction settle(e, r) {\n\t\t2 === e ? t.reject(r) : t.resolve({\n\t\t\tvalue: r,\n\t\t\tdone: e\n\t\t}), (t = t.next) ? resume(t.key, t.arg) : n = null;\n\t}\n\tthis._invoke = function(e, r) {\n\t\treturn new Promise(function(o, u) {\n\t\t\tvar i = {\n\t\t\t\tkey: e,\n\t\t\t\targ: r,\n\t\t\t\tresolve: o,\n\t\t\t\treject: u,\n\t\t\t\tnext: null\n\t\t\t};\n\t\t\tn ? n = n.next = i : (t = n = i, resume(e, r));\n\t\t});\n\t}, \"function\" != typeof e[\"return\"] && (this[\"return\"] = void 0);\n}\nAsyncGenerator.prototype[\"function\" == typeof Symbol && Symbol.asyncIterator || \"@@asyncIterator\"] = function() {\n\treturn this;\n}, AsyncGenerator.prototype.next = function(e) {\n\treturn this._invoke(\"next\", e);\n}, AsyncGenerator.prototype[\"throw\"] = function(e) {\n\treturn this._invoke(\"throw\", e);\n}, AsyncGenerator.prototype[\"return\"] = function(e) {\n\treturn this._invoke(\"return\", e);\n};\n// \\0@oxc-project+runtime@0.157.0/helpers/esm/asyncIterator.js\nfunction _asyncIterator(r) {\n\tvar n, t, o, e = 2;\n\tfor (\"undefined\" != typeof Symbol && (t = Symbol.asyncIterator, o = Symbol.iterator); e--;) {\n\t\tif (t && null != (n = r[t])) return n.call(r);\n\t\tif (o && null != (n = r[o])) return new AsyncFromSyncIterator(n.call(r));\n\t\tt = \"@@asyncIterator\", o = \"@@iterator\";\n\t}\n\tthrow new TypeError(\"Object is not async iterable\");\n}\nfunction AsyncFromSyncIterator(r) {\n\tfunction AsyncFromSyncIteratorContinuation(r) {\n\t\tif (Object(r) !== r) return Promise.reject(/* @__PURE__ */ new TypeError(r + \" is not an object.\"));\n\t\tvar n = r.done;\n\t\treturn Promise.resolve(r.value).then(function(r) {\n\t\t\treturn {\n\t\t\t\tvalue: r,\n\t\t\t\tdone: n\n\t\t\t};\n\t\t});\n\t}\n\treturn AsyncFromSyncIterator = function AsyncFromSyncIterator(r) {\n\t\tthis.s = r, this.n = r.next;\n\t}, AsyncFromSyncIterator.prototype = {\n\t\ts: null,\n\t\tn: null,\n\t\tnext: function next() {\n\t\t\treturn AsyncFromSyncIteratorContinuation(this.n.apply(this.s, arguments));\n\t\t},\n\t\t\"return\": function _return(r) {\n\t\t\tvar n = this.s[\"return\"];\n\t\t\treturn void 0 === n ? Promise.resolve({\n\t\t\t\tvalue: r,\n\t\t\t\tdone: !0\n\t\t\t}) : AsyncFromSyncIteratorContinuation(n.apply(this.s, arguments));\n\t\t},\n\t\t\"throw\": function _throw(r) {\n\t\t\tvar n = this.s[\"throw\"];\n\t\t\treturn void 0 === n ? Promise.reject(r) : AsyncFromSyncIteratorContinuation(n.apply(this.s, arguments));\n\t\t}\n\t}, new AsyncFromSyncIterator(r);\n}\n// src/unstable-core-do-not-import/stream/tracked.ts\nconst trackedSymbol = Symbol();\n/**\n* Wraps an event with an id, so a client can resume from it.\n* @deprecated Use `tracked(id, data)` instead.\n*/\nfunction sse(event) {\n\treturn tracked(event.id, event.data);\n}\n/** Whether a value was made by `tracked()`. */\nfunction isTrackedEnvelope(value) {\n\treturn Array.isArray(value) && value[2] === trackedSymbol;\n}\n/**\n* Gives a subscription event an id. When the connection drops, the client\n* reconnects with the last id it got, as `input.lastEventId`, so the\n* subscription can resume from there. The id can't be empty.\n* @example\n* ```ts\n* yield tracked(post.id, post);\n* ```\n* @see https://trpc.io/docs/server/subscriptions#tracked\n*/\nfunction tracked(id, data) {\n\tif (id === \"\") throw new Error(\"`id` must not be an empty string as empty string is the same as not setting the id at all\");\n\tif (/[\\0\\n\\r]/.test(id)) throw new Error(\"`id` must not contain line breaks or null characters as they are not allowed in a Server-Sent Events id\");\n\treturn [\n\t\tid,\n\t\tdata,\n\t\ttrackedSymbol\n\t];\n}\n// \\0@oxc-project+runtime@0.157.0/helpers/esm/asyncGeneratorDelegate.js\nfunction _asyncGeneratorDelegate(t) {\n\tvar e = {}, n = !1;\n\tfunction pump(e, r) {\n\t\treturn n = !0, r = new Promise(function(n) {\n\t\t\tn(t[e](r));\n\t\t}), {\n\t\t\tdone: !1,\n\t\t\tvalue: new _OverloadYield(r, 1)\n\t\t};\n\t}\n\treturn e[\"undefined\" != typeof Symbol && Symbol.iterator || \"@@iterator\"] = function() {\n\t\treturn this;\n\t}, e.next = function(t) {\n\t\treturn n ? (n = !1, t) : pump(\"next\", t);\n\t}, \"function\" == typeof t[\"throw\"] && (e[\"throw\"] = function(t) {\n\t\tif (n) throw n = !1, t;\n\t\treturn pump(\"throw\", t);\n\t}), \"function\" == typeof t[\"return\"] && (e[\"return\"] = function(t) {\n\t\treturn n ? (n = !1, t) : pump(\"return\", t);\n\t}), e;\n}\nexport { getTRPCErrorFromUnknown as C, getCauseFromUnknown as S, defaultTransformer as _, _asyncIterator as a, transformTRPCResponse as b, procedurePathToURLPath as c, callProcedure as d, createCallerFactory as f, mergeRouters as g, lazy as h, tracked as i, resolvePathSeparator as l, getProcedureAtPath as m, isTrackedEnvelope as n, _wrapAsyncGenerator as o, createRouterFactory as p, sse as r, _OverloadYield as s, _asyncGeneratorDelegate as t, urlPathToProcedurePath as u, getDataTransformer as v, TRPCError as x, transformResult as y };\n\n\n//# sourceMappingURL=asyncGeneratorDelegate-BRQGtkYG.mjs.map", "import { n as _defineProperty, t as _objectSpread2 } from \"./objectSpread2-pyA4QVO4.mjs\";\nimport { isObject } from \"@trpc/server/unstable-core-do-not-import\";\n// src/TRPCClientError.ts\n/**\n* Whether a value is a `TRPCClientError`, typed for a router or procedure.\n* @see https://trpc.io/docs/client/vanilla/error-handling#catching-a-thrown-error\n*/\nfunction isTRPCClientError(cause) {\n\treturn cause instanceof TRPCClientError;\n}\nfunction isTRPCErrorResponse(obj) {\n\treturn isObject(obj) && isObject(obj[\"error\"]) && typeof obj[\"error\"][\"code\"] === \"number\" && typeof obj[\"error\"][\"message\"] === \"string\";\n}\nfunction getMessageFromUnknownError(err, fallback) {\n\tif (typeof err === \"string\") return err;\n\tif (isObject(err) && typeof err[\"message\"] === \"string\") return err[\"message\"];\n\treturn fallback;\n}\n/**\n* The error a client call throws, whether the server sent an error or the\n* request failed.\n* @see https://trpc.io/docs/client/vanilla/error-handling\n*/\nvar TRPCClientError = class TRPCClientError extends Error {\n\tconstructor(message, opts) {\n\t\tvar _opts$result, _opts$result2;\n\t\tconst cause = opts === null || opts === void 0 ? void 0 : opts.cause;\n\t\tsuper(message, { cause });\n\t\t_defineProperty(this, \"cause\", void 0);\n\t\t_defineProperty(this, \"shape\", void 0);\n\t\t_defineProperty(this, \"data\", void 0);\n\t\t_defineProperty(this, \"meta\", void 0);\n\t\tthis.meta = opts === null || opts === void 0 ? void 0 : opts.meta;\n\t\tthis.cause = cause;\n\t\tthis.shape = opts === null || opts === void 0 || (_opts$result = opts.result) === null || _opts$result === void 0 ? void 0 : _opts$result.error;\n\t\tthis.data = opts === null || opts === void 0 || (_opts$result2 = opts.result) === null || _opts$result2 === void 0 ? void 0 : _opts$result2.error.data;\n\t\tthis.name = \"TRPCClientError\";\n\t\tObject.setPrototypeOf(this, TRPCClientError.prototype);\n\t}\n\t/**\n\t* Turns an error response, an `Error` or another object into a\n\t* `TRPCClientError`. A `TRPCClientError` is returned as it is.\n\t*/\n\tstatic from(_cause, opts = {}) {\n\t\tconst cause = _cause;\n\t\tif (isTRPCClientError(cause)) {\n\t\t\tif (opts.meta) cause.meta = _objectSpread2(_objectSpread2({}, cause.meta), opts.meta);\n\t\t\treturn cause;\n\t\t}\n\t\tif (isTRPCErrorResponse(cause)) return new TRPCClientError(cause.error.message, _objectSpread2(_objectSpread2({}, opts), {}, {\n\t\t\tresult: cause,\n\t\t\tcause: opts.cause\n\t\t}));\n\t\treturn new TRPCClientError(getMessageFromUnknownError(cause, \"Unknown error\"), _objectSpread2(_objectSpread2({}, opts), {}, { cause }));\n\t}\n};\nexport { isTRPCClientError as n, TRPCClientError as t };\n\n//# sourceMappingURL=TRPCClientError-DE6-fd1n.mjs.map", "// src/internals/transformer.ts\n/**\n* @internal\n*/\n/**\n* @internal\n*/\nfunction getTransformer(transformer) {\n\tconst _transformer = transformer;\n\tif (!_transformer) return {\n\t\tinput: {\n\t\t\tserialize: (data) => data,\n\t\t\tdeserialize: (data) => data\n\t\t},\n\t\toutput: {\n\t\t\tserialize: (data) => data,\n\t\t\tdeserialize: (data) => data\n\t\t}\n\t};\n\tif (\"input\" in _transformer) return _transformer;\n\treturn {\n\t\tinput: _transformer,\n\t\toutput: _transformer\n\t};\n}\nexport { getTransformer };\n\n//# sourceMappingURL=unstable-internals.mjs.map", "import { getTransformer } from \"./unstable-internals.mjs\";\nimport { t as _objectSpread2 } from \"./objectSpread2-pyA4QVO4.mjs\";\nimport { procedurePathToURLPath, resolvePathSeparator } from \"@trpc/server/unstable-core-do-not-import\";\n// src/getFetch.ts\nconst isFunction = (fn) => typeof fn === \"function\";\n/**\n* The `fetch` to use: `customFetchImpl` if given, or else the global one.\n* Throws if there's none.\n*/\nfunction getFetch(customFetchImpl) {\n\tif (customFetchImpl) return customFetchImpl;\n\tif (typeof window !== \"undefined\" && isFunction(window.fetch)) return window.fetch.bind(window);\n\tif (typeof globalThis !== \"undefined\" && isFunction(globalThis.fetch)) return globalThis.fetch;\n\tthrow new Error(\"No fetch implementation found\");\n}\n// src/internals/signals.ts\n/**\n* Like `Promise.all()` but for abort signals\n* - When all signals have been aborted, the merged signal will be aborted\n* - If one signal is `null`, no signal will be aborted\n*/\nfunction allAbortSignals(...signals) {\n\tconst ac = new AbortController();\n\tconst count = signals.length;\n\tlet abortedCount = 0;\n\tconst onAbort = () => {\n\t\tif (++abortedCount === count) ac.abort();\n\t};\n\tfor (const signal of signals) if (signal === null || signal === void 0 ? void 0 : signal.aborted) onAbort();\n\telse signal === null || signal === void 0 || signal.addEventListener(\"abort\", onAbort, { once: true });\n\treturn ac.signal;\n}\n/**\n* Like `Promise.race` but for abort signals\n*\n* Basically, a ponyfill for\n* [`AbortSignal.any`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/any_static).\n*/\nfunction raceAbortSignals(...signals) {\n\treturn raceAbortSignalsWithCleanup(...signals).signal;\n}\nfunction raceAbortSignalsWithCleanup(...signals) {\n\tconst ac = new AbortController();\n\tconst cleanup = () => {\n\t\tfor (const signal of signals) signal === null || signal === void 0 || signal.removeEventListener(\"abort\", onAbort);\n\t};\n\tconst onAbort = () => {\n\t\tcleanup();\n\t\tac.abort();\n\t};\n\tfor (const signal of signals) {\n\t\tif (signal === null || signal === void 0 ? void 0 : signal.aborted) {\n\t\t\tonAbort();\n\t\t\tbreak;\n\t\t}\n\t\tsignal === null || signal === void 0 || signal.addEventListener(\"abort\", onAbort, { once: true });\n\t}\n\treturn {\n\t\tsignal: ac.signal,\n\t\tcleanup\n\t};\n}\nfunction abortSignalToPromise(signal) {\n\treturn new Promise((_, reject) => {\n\t\tif (signal.aborted) {\n\t\t\treject(signal.reason);\n\t\t\treturn;\n\t\t}\n\t\tsignal.addEventListener(\"abort\", () => {\n\t\t\treject(signal.reason);\n\t\t}, { once: true });\n\t});\n}\n/**\n* Polyfill for DOMException with AbortError name\n*/\nvar AbortError = class extends Error {\n\tconstructor() {\n\t\tconst name = \"AbortError\";\n\t\tsuper(name);\n\t\tthis.name = name;\n\t\tthis.message = name;\n\t}\n};\n/**\n* Polyfill for `signal.throwIfAborted()`\n*\n* @see https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/throwIfAborted\n*/\nconst throwIfAborted = (signal) => {\n\tvar _signal$throwIfAborte;\n\tif (!(signal === null || signal === void 0 ? void 0 : signal.aborted)) return;\n\t(_signal$throwIfAborte = signal.throwIfAborted) === null || _signal$throwIfAborte === void 0 || _signal$throwIfAborte.call(signal);\n\tif (typeof DOMException !== \"undefined\") throw new DOMException(\"AbortError\", \"AbortError\");\n\tthrow new AbortError();\n};\n// src/links/internals/httpUtils.ts\nfunction resolveHTTPLinkOptions(opts) {\n\treturn {\n\t\turl: opts.url.toString(),\n\t\tfetch: opts.fetch,\n\t\ttransformer: getTransformer(opts.transformer),\n\t\tmethodOverride: opts.methodOverride,\n\t\tpathSeparator: resolvePathSeparator(opts.pathSeparator)\n\t};\n}\nfunction arrayToDict(array) {\n\tconst dict = {};\n\tfor (let index = 0; index < array.length; index++) {\n\t\tconst element = array[index];\n\t\tdict[index] = element;\n\t}\n\treturn dict;\n}\nconst METHOD = {\n\tquery: \"GET\",\n\tmutation: \"POST\",\n\tsubscription: \"PATCH\"\n};\nfunction getInput(opts) {\n\treturn \"input\" in opts ? opts.transformer.input.serialize(opts.input) : arrayToDict(opts.inputs.map((_input) => opts.transformer.input.serialize(_input)));\n}\nconst getUrl = (opts) => {\n\tconst parts = opts.url.split(\"?\");\n\tlet url = parts[0].replace(/\\/$/, \"\") + \"/\" + procedurePathToURLPath(opts.path, opts.pathSeparator);\n\tconst queryParts = [];\n\tif (parts[1]) queryParts.push(parts[1]);\n\tif (\"inputs\" in opts) queryParts.push(\"batch=1\");\n\tif (opts.type === \"query\" || opts.type === \"subscription\") {\n\t\tconst input = getInput(opts);\n\t\tif (input !== void 0 && opts.methodOverride !== \"POST\") queryParts.push(`input=${encodeURIComponent(JSON.stringify(input))}`);\n\t}\n\tif (queryParts.length) url += \"?\" + queryParts.join(\"&\");\n\treturn url;\n};\nconst getBody = (opts) => {\n\tif (opts.type === \"query\" && opts.methodOverride !== \"POST\") return;\n\tconst input = getInput(opts);\n\treturn input !== void 0 ? JSON.stringify(input) : void 0;\n};\nconst jsonHttpRequester = (opts) => {\n\treturn httpRequest(_objectSpread2(_objectSpread2({}, opts), {}, {\n\t\tcontentTypeHeader: \"application/json\",\n\t\tgetUrl,\n\t\tgetBody\n\t}));\n};\nasync function fetchHTTPResponse(opts) {\n\tvar _opts$methodOverride, _opts$trpcAcceptHeade;\n\tthrowIfAborted(opts.signal);\n\tconst url = opts.getUrl(opts);\n\tconst body = opts.getBody(opts);\n\tconst method = (_opts$methodOverride = opts.methodOverride) !== null && _opts$methodOverride !== void 0 ? _opts$methodOverride : METHOD[opts.type];\n\tconst resolvedHeaders = await (async () => {\n\t\tconst heads = await opts.headers();\n\t\tif (Symbol.iterator in heads) return Object.fromEntries(heads);\n\t\treturn heads;\n\t})();\n\tconst hasContentType = Object.keys(resolvedHeaders).some((key) => key.toLowerCase() === \"content-type\");\n\tconst headers = _objectSpread2(_objectSpread2(_objectSpread2({}, opts.contentTypeHeader && method !== \"GET\" && !hasContentType ? { \"content-type\": opts.contentTypeHeader } : {}), opts.trpcAcceptHeader ? { [(_opts$trpcAcceptHeade = opts.trpcAcceptHeaderKey) !== null && _opts$trpcAcceptHeade !== void 0 ? _opts$trpcAcceptHeade : \"trpc-accept\"]: opts.trpcAcceptHeader } : void 0), resolvedHeaders);\n\treturn getFetch(opts.fetch)(url, {\n\t\tmethod,\n\t\tsignal: opts.signal,\n\t\tbody,\n\t\theaders\n\t});\n}\nasync function httpRequest(opts) {\n\tconst meta = {};\n\tconst res = await fetchHTTPResponse(opts);\n\tmeta.response = res;\n\tconst json = await res.json();\n\tmeta.responseJSON = json;\n\treturn {\n\t\tjson,\n\t\tmeta\n\t};\n}\nexport { jsonHttpRequester as a, allAbortSignals as c, throwIfAborted as d, getFetch as f, httpRequest as i, raceAbortSignals as l, getBody as n, resolveHTTPLinkOptions as o, getUrl as r, abortSignalToPromise as s, fetchHTTPResponse as t, raceAbortSignalsWithCleanup as u };\n\n//# sourceMappingURL=httpUtils-CtMuyl9j.mjs.map", "import { a as jsonHttpRequester, c as allAbortSignals, o as resolveHTTPLinkOptions, r as getUrl, u as raceAbortSignalsWithCleanup } from \"./httpUtils-CtMuyl9j.mjs\";\nimport { t as TRPCClientError } from \"./TRPCClientError-DE6-fd1n.mjs\";\nimport { t as _objectSpread2 } from \"./objectSpread2-pyA4QVO4.mjs\";\nimport { observable } from \"@trpc/server/observable\";\nimport { transformResult } from \"@trpc/server/unstable-core-do-not-import\";\n// src/internals/dataLoader.ts\n/**\n* A function that should never be called unless we messed something up.\n*/\nconst throwFatalError = () => {\n\tthrow new Error(\"Something went wrong. Please submit an issue at https://github.com/trpc/trpc/issues/new\");\n};\n/**\n* Dataloader that's very inspired by https://github.com/graphql/dataloader\n* Less configuration, no caching, and allows you to cancel requests\n* When cancelling a single fetch the whole batch will be cancelled only when _all_ items are cancelled\n*/\nfunction dataLoader(batchLoader) {\n\tlet pendingItems = null;\n\tlet dispatchTimer = null;\n\tconst destroyTimerAndPendingItems = () => {\n\t\tclearTimeout(dispatchTimer);\n\t\tdispatchTimer = null;\n\t\tpendingItems = null;\n\t};\n\t/**\n\t* Iterate through the items and split them into groups based on the `batchLoader`'s validate function\n\t*/\n\tfunction groupItems(items) {\n\t\tconst groupedItems = [[]];\n\t\tlet index = 0;\n\t\twhile (true) {\n\t\t\tconst item = items[index];\n\t\t\tif (!item) break;\n\t\t\tconst lastGroup = groupedItems[groupedItems.length - 1];\n\t\t\tif (item.aborted) {\n\t\t\t\tvar _item$reject;\n\t\t\t\t(_item$reject = item.reject) === null || _item$reject === void 0 || _item$reject.call(item, /* @__PURE__ */ new Error(\"Aborted\"));\n\t\t\t\tindex++;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tlet isValid;\n\t\t\ttry {\n\t\t\t\tisValid = batchLoader.validate(lastGroup.concat(item).map((it) => it.key));\n\t\t\t} catch (cause) {\n\t\t\t\tvar _item$reject2;\n\t\t\t\t(_item$reject2 = item.reject) === null || _item$reject2 === void 0 || _item$reject2.call(item, cause);\n\t\t\t\tindex++;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (isValid) {\n\t\t\t\tlastGroup.push(item);\n\t\t\t\tindex++;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (lastGroup.length === 0) {\n\t\t\t\tvar _item$reject3;\n\t\t\t\t(_item$reject3 = item.reject) === null || _item$reject3 === void 0 || _item$reject3.call(item, /* @__PURE__ */ new Error(\"Input is too big for a single dispatch\"));\n\t\t\t\tindex++;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tgroupedItems.push([]);\n\t\t}\n\t\treturn groupedItems;\n\t}\n\tfunction dispatch() {\n\t\tconst groupedItems = groupItems(pendingItems);\n\t\tdestroyTimerAndPendingItems();\n\t\tfor (const items of groupedItems) {\n\t\t\tif (!items.length) continue;\n\t\t\tconst batch = { items };\n\t\t\tfor (const item of items) item.batch = batch;\n\t\t\tbatchLoader.fetch(batch.items.map((_item) => _item.key)).then(async (result) => {\n\t\t\t\tawait Promise.all(result.map(async (valueOrPromise, index) => {\n\t\t\t\t\tconst item = batch.items[index];\n\t\t\t\t\ttry {\n\t\t\t\t\t\tvar _item$resolve;\n\t\t\t\t\t\tconst value = await Promise.resolve(valueOrPromise);\n\t\t\t\t\t\t(_item$resolve = item.resolve) === null || _item$resolve === void 0 || _item$resolve.call(item, value);\n\t\t\t\t\t} catch (cause) {\n\t\t\t\t\t\tvar _item$reject4;\n\t\t\t\t\t\t(_item$reject4 = item.reject) === null || _item$reject4 === void 0 || _item$reject4.call(item, cause);\n\t\t\t\t\t}\n\t\t\t\t\titem.batch = null;\n\t\t\t\t\titem.reject = null;\n\t\t\t\t\titem.resolve = null;\n\t\t\t\t}));\n\t\t\t\tfor (const item of batch.items) {\n\t\t\t\t\tvar _item$reject5;\n\t\t\t\t\t(_item$reject5 = item.reject) === null || _item$reject5 === void 0 || _item$reject5.call(item, /* @__PURE__ */ new Error(\"Missing result\"));\n\t\t\t\t\titem.batch = null;\n\t\t\t\t}\n\t\t\t}).catch((cause) => {\n\t\t\t\tfor (const item of batch.items) {\n\t\t\t\t\tvar _item$reject6;\n\t\t\t\t\t(_item$reject6 = item.reject) === null || _item$reject6 === void 0 || _item$reject6.call(item, cause);\n\t\t\t\t\titem.batch = null;\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t}\n\tfunction load(key) {\n\t\tvar _dispatchTimer;\n\t\tconst item = {\n\t\t\taborted: false,\n\t\t\tkey,\n\t\t\tbatch: null,\n\t\t\tresolve: throwFatalError,\n\t\t\treject: throwFatalError\n\t\t};\n\t\tconst promise = new Promise((resolve, reject) => {\n\t\t\tvar _pendingItems;\n\t\t\titem.reject = reject;\n\t\t\titem.resolve = resolve;\n\t\t\t(_pendingItems = pendingItems) !== null && _pendingItems !== void 0 || (pendingItems = []);\n\t\t\tpendingItems.push(item);\n\t\t});\n\t\t(_dispatchTimer = dispatchTimer) !== null && _dispatchTimer !== void 0 || (dispatchTimer = setTimeout(dispatch));\n\t\treturn promise;\n\t}\n\treturn { load };\n}\n// src/links/httpBatchLink.ts\n/**\n* A terminating link that batches calls made in the same tick into one HTTP\n* request.\n*\n* @see https://trpc.io/docs/client/links/httpBatchLink\n*/\nfunction httpBatchLink(opts) {\n\tvar _opts$maxURLLength, _opts$maxItems;\n\tconst resolvedOpts = resolveHTTPLinkOptions(opts);\n\tconst maxURLLength = (_opts$maxURLLength = opts.maxURLLength) !== null && _opts$maxURLLength !== void 0 ? _opts$maxURLLength : Infinity;\n\tconst maxItems = (_opts$maxItems = opts.maxItems) !== null && _opts$maxItems !== void 0 ? _opts$maxItems : Infinity;\n\treturn () => {\n\t\tconst batchLoader = (type) => {\n\t\t\treturn {\n\t\t\t\tvalidate(batchOps) {\n\t\t\t\t\tif (maxURLLength === Infinity && maxItems === Infinity) return true;\n\t\t\t\t\tif (batchOps.length > maxItems) return false;\n\t\t\t\t\tconst path = batchOps.map((op) => op.path).join(\",\");\n\t\t\t\t\tconst inputs = batchOps.map((op) => op.input);\n\t\t\t\t\treturn getUrl(_objectSpread2(_objectSpread2({}, resolvedOpts), {}, {\n\t\t\t\t\t\ttype,\n\t\t\t\t\t\tpath,\n\t\t\t\t\t\tinputs,\n\t\t\t\t\t\tsignal: null\n\t\t\t\t\t})).length <= maxURLLength;\n\t\t\t\t},\n\t\t\t\tasync fetch(batchOps) {\n\t\t\t\t\tconst path = batchOps.map((op) => op.path).join(\",\");\n\t\t\t\t\tconst inputs = batchOps.map((op) => op.input);\n\t\t\t\t\tconst signal = allAbortSignals(...batchOps.map((op) => op.signal));\n\t\t\t\t\tconst res = await jsonHttpRequester(_objectSpread2(_objectSpread2({}, resolvedOpts), {}, {\n\t\t\t\t\t\tpath,\n\t\t\t\t\t\tinputs,\n\t\t\t\t\t\ttype,\n\t\t\t\t\t\theaders() {\n\t\t\t\t\t\t\tif (!opts.headers) return {};\n\t\t\t\t\t\t\tif (typeof opts.headers === \"function\") return opts.headers({ opList: batchOps });\n\t\t\t\t\t\t\treturn opts.headers;\n\t\t\t\t\t\t},\n\t\t\t\t\t\tsignal\n\t\t\t\t\t}));\n\t\t\t\t\treturn (Array.isArray(res.json) ? res.json : batchOps.map(() => res.json)).map((item) => ({\n\t\t\t\t\t\tmeta: res.meta,\n\t\t\t\t\t\tjson: item\n\t\t\t\t\t}));\n\t\t\t\t}\n\t\t\t};\n\t\t};\n\t\tconst loaders = {\n\t\t\tquery: dataLoader(batchLoader(\"query\")),\n\t\t\tmutation: dataLoader(batchLoader(\"mutation\"))\n\t\t};\n\t\treturn ({ op }) => {\n\t\t\treturn observable((observer) => {\n\t\t\t\t/* istanbul ignore if -- @preserve */\n\t\t\t\tif (op.type === \"subscription\") throw new Error(\"Subscriptions are unsupported by `httpLink` - use `httpSubscriptionLink` or `wsLink`\");\n\t\t\t\tconst ac = new AbortController();\n\t\t\t\tconst { signal, cleanup } = raceAbortSignalsWithCleanup(op.signal, ac.signal);\n\t\t\t\tconst promise = loaders[op.type].load(_objectSpread2(_objectSpread2({}, op), {}, { signal }));\n\t\t\t\tlet isDone = false;\n\t\t\t\tlet _res = void 0;\n\t\t\t\tpromise.then((res) => {\n\t\t\t\t\tisDone = true;\n\t\t\t\t\t_res = res;\n\t\t\t\t\tconst transformed = transformResult(res.json, resolvedOpts.transformer.output);\n\t\t\t\t\tif (!transformed.ok) {\n\t\t\t\t\t\tobserver.error(TRPCClientError.from(transformed.error, { meta: res.meta }));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tobserver.next({\n\t\t\t\t\t\tcontext: res.meta,\n\t\t\t\t\t\tresult: transformed.result\n\t\t\t\t\t});\n\t\t\t\t\tobserver.complete();\n\t\t\t\t}).catch((err) => {\n\t\t\t\t\tisDone = true;\n\t\t\t\t\tobserver.error(TRPCClientError.from(err, { meta: _res === null || _res === void 0 ? void 0 : _res.meta }));\n\t\t\t\t});\n\t\t\t\treturn () => {\n\t\t\t\t\tif (!isDone) ac.abort();\n\t\t\t\t\tcleanup();\n\t\t\t\t};\n\t\t\t});\n\t\t};\n\t};\n}\nexport { dataLoader as n, httpBatchLink as t };\n\n//# sourceMappingURL=httpBatchLink-BkVNtNND.mjs.map", "import { t as _objectSpread2 } from \"../objectSpread2-pyA4QVO4.mjs\";\nimport { observable, tap } from \"@trpc/server/observable\";\n// src/links/loggerLink.ts\nfunction isFormData(value) {\n\tif (typeof FormData === \"undefined\") return false;\n\treturn value instanceof FormData;\n}\nconst palettes = {\n\tcss: {\n\t\tquery: [\"72e3ff\", \"3fb0d8\"],\n\t\tmutation: [\"c5a3fc\", \"904dfc\"],\n\t\tsubscription: [\"ff49e1\", \"d83fbe\"]\n\t},\n\tansi: {\n\t\tregular: {\n\t\t\tquery: [\"\\x1B[30;46m\", \"\\x1B[97;46m\"],\n\t\t\tmutation: [\"\\x1B[30;45m\", \"\\x1B[97;45m\"],\n\t\t\tsubscription: [\"\\x1B[30;42m\", \"\\x1B[97;42m\"]\n\t\t},\n\t\tbold: {\n\t\t\tquery: [\"\\x1B[1;30;46m\", \"\\x1B[1;97;46m\"],\n\t\t\tmutation: [\"\\x1B[1;30;45m\", \"\\x1B[1;97;45m\"],\n\t\t\tsubscription: [\"\\x1B[1;30;42m\", \"\\x1B[1;97;42m\"]\n\t\t}\n\t}\n};\nfunction constructPartsAndArgs(opts) {\n\tconst { direction, type, withContext, path, id, input } = opts;\n\tconst parts = [];\n\tconst args = [];\n\tif (opts.colorMode === \"none\") parts.push(direction === \"up\" ? \">>\" : \"<<\", type, `#${id}`, path);\n\telse if (opts.colorMode === \"ansi\") {\n\t\tconst [lightRegular, darkRegular] = palettes.ansi.regular[type];\n\t\tconst [lightBold, darkBold] = palettes.ansi.bold[type];\n\t\tparts.push(direction === \"up\" ? lightRegular : darkRegular, direction === \"up\" ? \">>\" : \"<<\", type, direction === \"up\" ? lightBold : darkBold, `#${id}`, path, \"\\x1B[0m\");\n\t} else {\n\t\tconst [light, dark] = palettes.css[type];\n\t\tconst css = `\n background-color: #${direction === \"up\" ? light : dark};\n color: ${direction === \"up\" ? \"black\" : \"white\"};\n padding: 2px;\n `;\n\t\tparts.push(\"%c\", direction === \"up\" ? \">>\" : \"<<\", type, `#${id}`, `%c${path}%c`, \"%O\");\n\t\targs.push(css, `${css}; font-weight: bold;`, `${css}; font-weight: normal;`);\n\t}\n\tif (direction === \"up\") args.push(withContext ? {\n\t\tinput,\n\t\tcontext: opts.context\n\t} : { input });\n\telse args.push(_objectSpread2({\n\t\tinput,\n\t\tresult: opts.result,\n\t\telapsedMs: opts.elapsedMs\n\t}, withContext && { context: opts.context }));\n\treturn {\n\t\tparts,\n\t\targs\n\t};\n}\nconst defaultLogger = ({ c = console, colorMode = \"css\", withContext }) => (props) => {\n\tconst rawInput = props.input;\n\tconst input = isFormData(rawInput) ? Object.fromEntries(rawInput) : rawInput;\n\tconst { parts, args } = constructPartsAndArgs(_objectSpread2(_objectSpread2({}, props), {}, {\n\t\tcolorMode,\n\t\tinput,\n\t\twithContext\n\t}));\n\tc[props.direction === \"down\" && props.result && (props.result instanceof Error || \"error\" in props.result.result && props.result.result.error) ? \"error\" : \"log\"].apply(null, [parts.join(\" \")].concat(args));\n};\n/**\n* Logs each call when it starts, and each result or error it gets with the\n* time since the start.\n*\n* @see https://trpc.io/docs/client/links/loggerLink\n*/\nfunction loggerLink(opts = {}) {\n\tvar _opts$colorMode, _opts$withContext;\n\tconst { enabled = () => true } = opts;\n\tconst colorMode = (_opts$colorMode = opts.colorMode) !== null && _opts$colorMode !== void 0 ? _opts$colorMode : typeof window === \"undefined\" ? \"ansi\" : \"css\";\n\tconst withContext = (_opts$withContext = opts.withContext) !== null && _opts$withContext !== void 0 ? _opts$withContext : colorMode === \"css\";\n\tconst { logger = defaultLogger({\n\t\tc: opts.console,\n\t\tcolorMode,\n\t\twithContext\n\t}) } = opts;\n\treturn () => {\n\t\treturn ({ op, next }) => {\n\t\t\treturn observable((observer) => {\n\t\t\t\tif (enabled(_objectSpread2(_objectSpread2({}, op), {}, { direction: \"up\" }))) logger(_objectSpread2(_objectSpread2({}, op), {}, { direction: \"up\" }));\n\t\t\t\tconst requestStartTime = Date.now();\n\t\t\t\tfunction logResult(result) {\n\t\t\t\t\tconst elapsedMs = Date.now() - requestStartTime;\n\t\t\t\t\tif (enabled(_objectSpread2(_objectSpread2({}, op), {}, {\n\t\t\t\t\t\tdirection: \"down\",\n\t\t\t\t\t\tresult\n\t\t\t\t\t}))) logger(_objectSpread2(_objectSpread2({}, op), {}, {\n\t\t\t\t\t\tdirection: \"down\",\n\t\t\t\t\t\telapsedMs,\n\t\t\t\t\t\tresult\n\t\t\t\t\t}));\n\t\t\t\t}\n\t\t\t\treturn next(op).pipe(tap({\n\t\t\t\t\tnext(result) {\n\t\t\t\t\t\tlogResult(result);\n\t\t\t\t\t},\n\t\t\t\t\terror(result) {\n\t\t\t\t\t\tlogResult(result);\n\t\t\t\t\t}\n\t\t\t\t})).subscribe(observer);\n\t\t\t});\n\t\t};\n\t};\n}\nexport { loggerLink };\n\n//# sourceMappingURL=loggerLink.mjs.map", "import { getTransformer } from \"./unstable-internals.mjs\";\nimport { t as TRPCClientError } from \"./TRPCClientError-DE6-fd1n.mjs\";\nimport { n as _defineProperty, t as _objectSpread2 } from \"./objectSpread2-pyA4QVO4.mjs\";\nimport { behaviorSubject, observable } from \"@trpc/server/observable\";\nimport { run, sleep, transformResult } from \"@trpc/server/unstable-core-do-not-import\";\n// src/links/wsLink/wsClient/encoder.ts\n/**\n* The default WebSocket encoder. Sends messages as JSON text frames.\n*/\nconst jsonEncoder = {\n\tencode: (data) => JSON.stringify(data),\n\tdecode: (data) => {\n\t\tif (typeof data !== \"string\") throw new Error(\"jsonEncoder received binary data. JSON uses text frames. Use a binary encoder for binary data.\");\n\t\treturn JSON.parse(data);\n\t}\n};\n// src/links/wsLink/wsClient/options.ts\nconst lazyDefaults = {\n\tenabled: false,\n\tcloseMs: 0\n};\nconst keepAliveDefaults = {\n\tenabled: false,\n\tpongTimeoutMs: 1e3,\n\tintervalMs: 5e3\n};\n/**\n* Calculates a delay for exponential backoff based on the retry attempt index.\n* The delay starts at 0 for the first attempt and doubles for each subsequent attempt,\n* capped at 30 seconds.\n*/\nconst exponentialBackoff = (attemptIndex) => {\n\treturn attemptIndex === 0 ? 0 : Math.min(1e3 * 2 ** attemptIndex, 3e4);\n};\n// src/links/internals/urlWithConnectionParams.ts\n/**\n* Get the result of a value or function that returns a value\n* It also optionally accepts typesafe arguments for the function\n*/\nconst resultOf = (value, ...args) => {\n\treturn typeof value === \"function\" ? value(...args) : value;\n};\n// src/links/wsLink/wsClient/utils.ts\nvar TRPCWebSocketClosedError = class TRPCWebSocketClosedError extends Error {\n\tconstructor(opts) {\n\t\tsuper(opts.message, { cause: opts.cause });\n\t\tthis.name = \"TRPCWebSocketClosedError\";\n\t\tObject.setPrototypeOf(this, TRPCWebSocketClosedError.prototype);\n\t}\n};\n/**\n* Calls a user callback, including `connectionState` subscribers. A throw\n* would skip the rest of the client's bookkeeping (e.g. end the reconnect\n* loop, or, with event-emitter based WebSockets such as `ws`, skip the other\n* listeners for that event), so it is rethrown asynchronously instead.\n*/\nfunction callUserCallback(callback) {\n\ttry {\n\t\tcallback();\n\t} catch (error) {\n\t\tsetTimeout(() => {\n\t\t\tthrow error;\n\t\t});\n\t}\n}\n/**\n* Utility class for managing a timeout that can be started, stopped, and reset.\n* Useful for scenarios where the timeout duration is reset dynamically based on events.\n*/\nvar ResettableTimeout = class {\n\tconstructor(onTimeout, timeoutMs) {\n\t\tthis.onTimeout = onTimeout;\n\t\tthis.timeoutMs = timeoutMs;\n\t\t_defineProperty(this, \"timeout\", void 0);\n\t}\n\t/**\n\t* Resets the current timeout, restarting it with the same duration.\n\t* Does nothing if no timeout is active.\n\t*/\n\treset() {\n\t\tif (!this.timeout) return;\n\t\tclearTimeout(this.timeout);\n\t\tthis.timeout = setTimeout(this.onTimeout, this.timeoutMs);\n\t}\n\tstart() {\n\t\tclearTimeout(this.timeout);\n\t\tthis.timeout = setTimeout(this.onTimeout, this.timeoutMs);\n\t}\n\tstop() {\n\t\tclearTimeout(this.timeout);\n\t\tthis.timeout = void 0;\n\t}\n};\nfunction withResolvers() {\n\tlet resolve;\n\tlet reject;\n\treturn {\n\t\tpromise: new Promise((res, rej) => {\n\t\t\tresolve = res;\n\t\t\treject = rej;\n\t\t}),\n\t\tresolve,\n\t\treject\n\t};\n}\n/**\n* Resolves a WebSocket URL and optionally appends connection parameters.\n*\n* If connectionParams are provided, appends 'connectionParams=1' query parameter.\n*/\nasync function prepareUrl(urlOptions) {\n\tconst url = await resultOf(urlOptions.url);\n\tif (!urlOptions.connectionParams) return url;\n\treturn url + `${url.includes(\"?\") ? \"&\" : \"?\"}connectionParams=1`;\n}\nasync function buildConnectionMessage(connectionParams, encoder) {\n\tconst message = {\n\t\tmethod: \"connectionParams\",\n\t\tdata: await resultOf(connectionParams)\n\t};\n\treturn encoder.encode(message);\n}\n// src/links/wsLink/wsClient/requestManager.ts\n/**\n* Manages WebSocket requests, tracking their lifecycle and providing utility methods\n* for handling outgoing and pending requests.\n*\n* - **Outgoing requests**: Requests that are queued and waiting to be sent.\n* - **Pending requests**: Requests that have been sent and are in flight awaiting a response.\n* For subscriptions, multiple responses may be received until the subscription is closed.\n*/\nvar RequestManager = class {\n\tconstructor() {\n\t\t_defineProperty(this, \"outgoingRequests\", new Array());\n\t\t_defineProperty(this, \"pendingRequests\", {});\n\t\t_defineProperty(this, \"drainingRequests\", {});\n\t}\n\t/**\n\t* Registers a new request by adding it to the outgoing queue and setting up\n\t* callbacks for lifecycle events such as completion or error.\n\t*\n\t* @param message - The outgoing message to be sent.\n\t* @param callbacks - Callback functions to observe the request's state.\n\t* @returns A cleanup function to manually remove the request.\n\t*/\n\tregister(message, callbacks) {\n\t\tconst { promise: end, resolve } = withResolvers();\n\t\tthis.outgoingRequests.push({\n\t\t\tid: String(message.id),\n\t\t\tmessage,\n\t\t\tend,\n\t\t\tws: null,\n\t\t\tsuccessor: null,\n\t\t\toverlapEventIds: null,\n\t\t\tmovedFrom: /* @__PURE__ */ new Set(),\n\t\t\tcallbacks: {\n\t\t\t\tnext: callbacks.next,\n\t\t\t\tcomplete: () => {\n\t\t\t\t\tcallbacks.complete();\n\t\t\t\t\tresolve();\n\t\t\t\t},\n\t\t\t\terror: (e) => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tcallbacks.error(e);\n\t\t\t\t\t} finally {\n\t\t\t\t\t\tresolve();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\treturn () => {\n\t\t\tthis.delete(message);\n\t\t\tcallbacks.complete();\n\t\t\tresolve();\n\t\t};\n\t}\n\t/**\n\t* Deletes a request from both the outgoing and pending collections, if it exists.\n\t*\n\t* Matches the message itself rather than its id: a retry reuses the id, and\n\t* registers its request before the failed request with that id is deleted.\n\t*/\n\tdelete(message) {\n\t\tvar _this$pendingRequests;\n\t\tthis.outgoingRequests = this.outgoingRequests.filter((request) => request.message !== message);\n\t\tconst id = String(message.id);\n\t\tif (((_this$pendingRequests = this.pendingRequests[id]) === null || _this$pendingRequests === void 0 ? void 0 : _this$pendingRequests.message) === message) delete this.pendingRequests[id];\n\t\tfor (const [drainingId, request] of Object.entries(this.drainingRequests)) if (request.message === message) delete this.drainingRequests[drainingId];\n\t}\n\t/**\n\t* Moves all outgoing requests to the pending state and clears the outgoing queue.\n\t*\n\t* The caller is expected to handle the actual sending of the requests\n\t* (e.g., sending them over the network) after this method is called.\n\t*\n\t* @param ws - The socket the requests are sent on.\n\t* @returns The list of requests that were transitioned to the pending state.\n\t*/\n\tflush(ws = null) {\n\t\tconst requests = this.outgoingRequests;\n\t\tthis.outgoingRequests = [];\n\t\tfor (const request of requests) {\n\t\t\trequest.ws = ws;\n\t\t\trequest.successor = null;\n\t\t\trequest.movedFrom = /* @__PURE__ */ new Set();\n\t\t\tthis.pendingRequests[request.id] = request;\n\t\t}\n\t\treturn requests;\n\t}\n\t/**\n\t* Moves a pending request back to the outgoing queue, to be sent again\n\t* with `id`. Its earlier id then matches only the sockets it's still\n\t* draining; see `getDrainingRequest()`.\n\t*/\n\trequeue(message, id) {\n\t\tconst earlierId = String(message.id);\n\t\tconst request = this.pendingRequests[earlierId];\n\t\tif ((request === null || request === void 0 ? void 0 : request.message) !== message) return;\n\t\tdelete this.pendingRequests[earlierId];\n\t\tif (request.movedFrom.size) this.drainingRequests[earlierId] = request;\n\t\tmessage.id = id;\n\t\tthis.outgoingRequests.push(_objectSpread2(_objectSpread2({}, request), {}, {\n\t\t\tid: String(id),\n\t\t\tws: null,\n\t\t\tsuccessor: null,\n\t\t\toverlapEventIds: null,\n\t\t\tmovedFrom: /* @__PURE__ */ new Set()\n\t\t}));\n\t}\n\t/**\n\t* Retrieves all currently pending requests, which are in flight awaiting responses\n\t* or handling ongoing subscriptions.\n\t*/\n\tgetPendingRequests() {\n\t\treturn Object.values(this.pendingRequests);\n\t}\n\t/**\n\t* Retrieves a specific pending request by its message ID.\n\t*/\n\tgetPendingRequest(messageId) {\n\t\tif (messageId === null) return null;\n\t\treturn this.pendingRequests[String(messageId)];\n\t}\n\t/**\n\t* Retrieves a subscription sent again under a new id by its earlier id,\n\t* while a socket it moved from may still send events under that one.\n\t*/\n\tgetDrainingRequest(messageId) {\n\t\tif (messageId === null) return null;\n\t\treturn this.drainingRequests[String(messageId)];\n\t}\n\t/**\n\t* Retrieves the subscriptions sent again under a new id whose earlier id\n\t* is still in use on a socket they moved from.\n\t*/\n\tgetDrainingRequests() {\n\t\treturn Object.values(this.drainingRequests);\n\t}\n\t/**\n\t* Forgets the earlier ids of subscriptions no longer draining any socket.\n\t*/\n\tdeleteDrained() {\n\t\tfor (const [id, request] of Object.entries(this.drainingRequests)) if (!request.movedFrom.size) delete this.drainingRequests[id];\n\t}\n\t/**\n\t* Retrieves all outgoing requests, which are waiting to be sent.\n\t*/\n\tgetOutgoingRequests() {\n\t\treturn this.outgoingRequests;\n\t}\n\t/**\n\t* Retrieves all requests, both outgoing and pending, with their respective states.\n\t*\n\t* @returns An array of all requests with their state (\"outgoing\" or \"pending\").\n\t*/\n\tgetRequests() {\n\t\treturn [...this.getOutgoingRequests().map((request) => ({\n\t\t\tstate: \"outgoing\",\n\t\t\tmessage: request.message,\n\t\t\tend: request.end,\n\t\t\tcallbacks: request.callbacks\n\t\t})), ...this.getPendingRequests().map((request) => ({\n\t\t\tstate: \"pending\",\n\t\t\tmessage: request.message,\n\t\t\tend: request.end,\n\t\t\tcallbacks: request.callbacks\n\t\t}))];\n\t}\n\t/**\n\t* Checks if there are any pending requests, including ongoing subscriptions.\n\t*/\n\thasPendingRequests() {\n\t\treturn this.getPendingRequests().length > 0;\n\t}\n\t/**\n\t* Checks if there are any pending subscriptions\n\t*/\n\thasPendingSubscriptions() {\n\t\treturn this.getPendingRequests().some((request) => request.message.method === \"subscription\");\n\t}\n\t/**\n\t* Checks if a message is still waiting to be sent.\n\t*/\n\tisOutgoing(message) {\n\t\treturn this.outgoingRequests.some((request) => request.message === message);\n\t}\n\t/**\n\t* Checks if there are any outgoing requests waiting to be sent.\n\t*/\n\thasOutgoingRequests() {\n\t\treturn this.outgoingRequests.length > 0;\n\t}\n};\n// src/links/wsLink/wsClient/wsConnection.ts\n/**\n* Opens a WebSocket connection asynchronously and returns a promise\n* that resolves when the connection is successfully established.\n* The promise rejects if an error occurs during the connection attempt.\n*/\nfunction asyncWsOpen(ws) {\n\tconst { promise, resolve, reject } = withResolvers();\n\tws.addEventListener(\"open\", () => {\n\t\tws.removeEventListener(\"error\", reject);\n\t\tresolve();\n\t});\n\tws.addEventListener(\"error\", reject);\n\treturn promise;\n}\nconst pongCallbacks = /* @__PURE__ */ new WeakMap();\n/**\n* Sends \"PING\" on `ws` and calls `onPong`, if given, once its \"PONG\"\n* arrives. The server answers in order, so by then everything it sent before\n* it read this \"PING\" has arrived too.\n*/\nfunction sendPing(ws, onPong) {\n\tlet callbacks = pongCallbacks.get(ws);\n\tif (!callbacks) {\n\t\tconst queue = [];\n\t\tcallbacks = queue;\n\t\tpongCallbacks.set(ws, queue);\n\t\tws.addEventListener(\"message\", ({ data }) => {\n\t\t\tvar _queue$shift;\n\t\t\tif (data === \"PONG\") (_queue$shift = queue.shift()) === null || _queue$shift === void 0 || _queue$shift();\n\t\t});\n\t}\n\tcallbacks.push(onPong);\n\tws.send(\"PING\");\n}\n/**\n* Sets up a periodic ping-pong mechanism to keep the WebSocket connection alive.\n*\n* - Sends \"PING\" messages at regular intervals defined by `intervalMs`.\n* - If a \"PONG\" response is not received within the `pongTimeoutMs`, the WebSocket is closed.\n* - The ping timer resets upon receiving any message to maintain activity.\n* - Automatically starts the ping process when the WebSocket connection is opened.\n* - Cleans up timers when the WebSocket is closed.\n*\n* @param ws - The WebSocket instance to manage.\n* @param options - Configuration options for ping-pong intervals and timeouts.\n*/\nfunction setupPingInterval(ws, { intervalMs, pongTimeoutMs }) {\n\tlet pingTimeout;\n\tlet pongTimeout;\n\tfunction start() {\n\t\tpingTimeout = setTimeout(() => {\n\t\t\tsendPing(ws, null);\n\t\t\tpongTimeout = setTimeout(() => {\n\t\t\t\tws.close();\n\t\t\t}, pongTimeoutMs);\n\t\t}, intervalMs);\n\t}\n\tfunction reset() {\n\t\tclearTimeout(pingTimeout);\n\t\tstart();\n\t}\n\tfunction pong() {\n\t\tclearTimeout(pongTimeout);\n\t\treset();\n\t}\n\tws.addEventListener(\"open\", start);\n\tws.addEventListener(\"message\", ({ data }) => {\n\t\tclearTimeout(pingTimeout);\n\t\tstart();\n\t\tif (data === \"PONG\") pong();\n\t});\n\tws.addEventListener(\"close\", () => {\n\t\tclearTimeout(pingTimeout);\n\t\tclearTimeout(pongTimeout);\n\t});\n}\n/**\n* Manages a WebSocket connection with support for reconnection, keep-alive mechanisms,\n* and observable state tracking.\n*/\nvar WsConnection = class WsConnection {\n\tconstructor(opts) {\n\t\tvar _opts$WebSocketPonyfi;\n\t\t_defineProperty(this, \"id\", ++WsConnection.connectCount);\n\t\t_defineProperty(this, \"WebSocketPonyfill\", void 0);\n\t\t_defineProperty(this, \"urlOptions\", void 0);\n\t\t_defineProperty(this, \"keepAliveOpts\", void 0);\n\t\t_defineProperty(this, \"encoder\", void 0);\n\t\t_defineProperty(this, \"wsObservable\", behaviorSubject(null));\n\t\t_defineProperty(this, \"openPromise\", null);\n\t\tthis.WebSocketPonyfill = (_opts$WebSocketPonyfi = opts.WebSocketPonyfill) !== null && _opts$WebSocketPonyfi !== void 0 ? _opts$WebSocketPonyfi : WebSocket;\n\t\tif (!this.WebSocketPonyfill) throw new Error(\"No WebSocket implementation found - you probably don't want to use this on the server, but if you do you need to pass a `WebSocket`-ponyfill\");\n\t\tthis.urlOptions = opts.urlOptions;\n\t\tthis.keepAliveOpts = opts.keepAlive;\n\t\tthis.encoder = opts.encoder;\n\t}\n\tget ws() {\n\t\treturn this.wsObservable.get();\n\t}\n\tset ws(ws) {\n\t\tthis.wsObservable.next(ws);\n\t}\n\t/**\n\t* Checks if the WebSocket connection is open and ready to communicate.\n\t*/\n\tisOpen() {\n\t\treturn !!this.ws && this.ws.readyState === this.WebSocketPonyfill.OPEN && !this.openPromise;\n\t}\n\t/**\n\t* Checks if the WebSocket connection is closed or in the process of closing.\n\t*/\n\tisClosed() {\n\t\treturn !!this.ws && (this.ws.readyState === this.WebSocketPonyfill.CLOSING || this.ws.readyState === this.WebSocketPonyfill.CLOSED);\n\t}\n\tasync open() {\n\t\tif (this.openPromise) return this.openPromise;\n\t\tthis.id = ++WsConnection.connectCount;\n\t\tconst wsPromise = prepareUrl(this.urlOptions).then((url) => new this.WebSocketPonyfill(url));\n\t\tthis.openPromise = wsPromise.then(async (ws) => {\n\t\t\tthis.ws = ws;\n\t\t\tws.binaryType = \"arraybuffer\";\n\t\t\tws.addEventListener(\"message\", function({ data }) {\n\t\t\t\tif (data === \"PING\") this.send(\"PONG\");\n\t\t\t});\n\t\t\tif (this.keepAliveOpts.enabled) setupPingInterval(ws, this.keepAliveOpts);\n\t\t\tws.addEventListener(\"close\", () => {\n\t\t\t\tif (this.ws === ws) this.ws = null;\n\t\t\t});\n\t\t\tawait asyncWsOpen(ws);\n\t\t\tif (this.urlOptions.connectionParams) ws.send(await buildConnectionMessage(this.urlOptions.connectionParams, this.encoder));\n\t\t});\n\t\ttry {\n\t\t\tawait this.openPromise;\n\t\t} finally {\n\t\t\tthis.openPromise = null;\n\t\t}\n\t}\n\t/**\n\t* Closes the WebSocket connection gracefully.\n\t* Waits for any ongoing open operation to complete before closing.\n\t*/\n\tasync close() {\n\t\ttry {\n\t\t\tawait this.openPromise;\n\t\t} finally {\n\t\t\tvar _this$ws;\n\t\t\t(_this$ws = this.ws) === null || _this$ws === void 0 || _this$ws.close();\n\t\t}\n\t}\n};\n_defineProperty(WsConnection, \"connectCount\", 0);\n/**\n* Provides a backward-compatible representation of the connection state.\n*/\nfunction backwardCompatibility(connection) {\n\tif (connection.isOpen()) return {\n\t\tid: connection.id,\n\t\tstate: \"open\",\n\t\tws: connection.ws\n\t};\n\tif (connection.isClosed()) return {\n\t\tid: connection.id,\n\t\tstate: \"closed\",\n\t\tws: connection.ws\n\t};\n\tif (!connection.ws) return null;\n\treturn {\n\t\tid: connection.id,\n\t\tstate: \"connecting\",\n\t\tws: connection.ws\n\t};\n}\n// src/links/wsLink/wsClient/wsClient.ts\n/**\n* A WebSocket client for managing TRPC operations, supporting lazy initialization,\n* reconnection, keep-alive, and request management.\n*/\nvar WsClient = class {\n\tconstructor(opts) {\n\t\tvar _opts$experimental_en, _opts$retryDelayMs;\n\t\t_defineProperty(this, \"connectionState\", void 0);\n\t\t_defineProperty(this, \"allowReconnect\", false);\n\t\t_defineProperty(this, \"requestManager\", new RequestManager());\n\t\t_defineProperty(this, \"lastRequestId\", 0);\n\t\t_defineProperty(this, \"connectionOptions\", void 0);\n\t\t_defineProperty(this, \"activeConnection\", void 0);\n\t\t_defineProperty(this, \"reconnectRetryDelay\", void 0);\n\t\t_defineProperty(this, \"inactivityTimeout\", void 0);\n\t\t_defineProperty(this, \"callbacks\", void 0);\n\t\t_defineProperty(this, \"lazyMode\", void 0);\n\t\t_defineProperty(this, \"encoder\", void 0);\n\t\t_defineProperty(this, \"reconnecting\", null);\n\t\t_defineProperty(this, \"nextConnection\", null);\n\t\t_defineProperty(this, \"retiredConnection\", null);\n\t\t_defineProperty(this, \"replacementError\", null);\n\t\t_defineProperty(this, \"connectionAttemptIndex\", 0);\n\t\t_defineProperty(this, \"connectionRejected\", false);\n\t\t_defineProperty(this, \"started\", /* @__PURE__ */ new WeakSet());\n\t\tthis.encoder = (_opts$experimental_en = opts.experimental_encoder) !== null && _opts$experimental_en !== void 0 ? _opts$experimental_en : jsonEncoder;\n\t\tthis.callbacks = {\n\t\t\tonOpen: opts.onOpen,\n\t\t\tonClose: opts.onClose,\n\t\t\tonError: opts.onError\n\t\t};\n\t\tconst lazyOptions = _objectSpread2(_objectSpread2({}, lazyDefaults), opts.lazy);\n\t\tthis.inactivityTimeout = new ResettableTimeout(() => {\n\t\t\tif (this.requestManager.hasOutgoingRequests() || this.requestManager.hasPendingRequests()) {\n\t\t\t\tthis.inactivityTimeout.reset();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.close().catch(() => null);\n\t\t}, lazyOptions.closeMs);\n\t\tthis.connectionOptions = {\n\t\t\tWebSocketPonyfill: opts.WebSocket,\n\t\t\turlOptions: opts,\n\t\t\tkeepAlive: _objectSpread2(_objectSpread2({}, keepAliveDefaults), opts.keepAlive),\n\t\t\tencoder: this.encoder\n\t\t};\n\t\tthis.activeConnection = this.createConnection();\n\t\tthis.reconnectRetryDelay = (_opts$retryDelayMs = opts.retryDelayMs) !== null && _opts$retryDelayMs !== void 0 ? _opts$retryDelayMs : exponentialBackoff;\n\t\tthis.lazyMode = lazyOptions.enabled;\n\t\tthis.connectionState = behaviorSubject({\n\t\t\ttype: \"state\",\n\t\t\tstate: lazyOptions.enabled ? \"idle\" : \"connecting\",\n\t\t\terror: null\n\t\t});\n\t\tif (!this.lazyMode) this.open().catch(() => null);\n\t}\n\tcreateConnection() {\n\t\tconst connection = new WsConnection(this.connectionOptions);\n\t\tconnection.wsObservable.subscribe({ next: (ws) => {\n\t\t\tif (!ws) return;\n\t\t\tthis.setupWebSocketListeners(ws);\n\t\t} });\n\t\treturn connection;\n\t}\n\t/**\n\t* Opens the WebSocket connection. Handles reconnection attempts and updates\n\t* the connection state accordingly.\n\t*/\n\tasync open() {\n\t\tthis.allowReconnect = true;\n\t\tif (this.reconnecting) return this.reconnecting;\n\t\tthis.connectionAttemptIndex = 0;\n\t\tif (this.connectionState.get().state === \"idle\") callUserCallback(() => this.connectionState.next({\n\t\t\ttype: \"state\",\n\t\t\tstate: \"connecting\",\n\t\t\terror: null\n\t\t}));\n\t\ttry {\n\t\t\tawait this.activeConnection.open();\n\t\t} catch (error) {\n\t\t\tthis.reconnect(new TRPCWebSocketClosedError({\n\t\t\t\tmessage: \"Initialization error\",\n\t\t\t\tcause: error\n\t\t\t}));\n\t\t\tawait this.activeConnection.close().catch(() => null);\n\t\t\treturn this.reconnecting;\n\t\t}\n\t}\n\t/**\n\t* Closes the WebSocket connection and stops managing requests.\n\t* Ensures all outgoing and pending requests are properly finalized.\n\t*/\n\tasync close() {\n\t\tvar _this$nextConnection;\n\t\tthis.allowReconnect = false;\n\t\tthis.replacementError = null;\n\t\tthis.retiredConnection = null;\n\t\tthis.inactivityTimeout.stop();\n\t\tconst requestsToAwait = [];\n\t\tfor (const request of this.requestManager.getRequests()) if (request.message.method === \"subscription\") callUserCallback(() => request.callbacks.complete());\n\t\telse if (request.state === \"outgoing\") callUserCallback(() => request.callbacks.error(TRPCClientError.from(new TRPCWebSocketClosedError({ message: \"Closed before connection was established\" }))));\n\t\telse requestsToAwait.push(request.end);\n\t\tawait Promise.all(requestsToAwait).catch(() => null);\n\t\t(_this$nextConnection = this.nextConnection) === null || _this$nextConnection === void 0 || (_this$nextConnection = _this$nextConnection.ws) === null || _this$nextConnection === void 0 || _this$nextConnection.close();\n\t\tawait this.activeConnection.close().catch(() => null);\n\t\tcallUserCallback(() => this.connectionState.next({\n\t\t\ttype: \"state\",\n\t\t\tstate: \"idle\",\n\t\t\terror: null\n\t\t}));\n\t}\n\t/**\n\t* Method to request the server.\n\t* Handles data transformation, batching of requests, and subscription lifecycle.\n\t*\n\t* @param op - The operation details including type, path, input and signal. Each subscription to the returned observable is sent with a new id, not `op.id`.\n\t* @param transformer - Data transformer for serializing requests and deserializing responses\n\t* @param lastEventId - Optional ID of the last received event for subscriptions\n\t*\n\t* @returns An observable that emits operation results and handles cleanup\n\t*/\n\trequest({ op: { type, path, input, signal }, transformer, lastEventId }) {\n\t\treturn observable((observer) => {\n\t\t\tconst message = {\n\t\t\t\tid: ++this.lastRequestId,\n\t\t\t\tmethod: type,\n\t\t\t\tparams: {\n\t\t\t\t\tinput: transformer.input.serialize(input),\n\t\t\t\t\tpath,\n\t\t\t\t\tlastEventId\n\t\t\t\t}\n\t\t\t};\n\t\t\tconst abort = this.batchSend(message, _objectSpread2(_objectSpread2({}, observer), {}, { next(event) {\n\t\t\t\tconst transformed = transformResult(event, transformer.output);\n\t\t\t\tif (!transformed.ok) {\n\t\t\t\t\tobserver.error(TRPCClientError.from(transformed.error));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tobserver.next({ result: transformed.result });\n\t\t\t} }));\n\t\t\tconst onAbort = () => observer.complete();\n\t\t\tif (signal === null || signal === void 0 ? void 0 : signal.aborted) onAbort();\n\t\t\telse signal === null || signal === void 0 || signal.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\treturn () => {\n\t\t\t\tconst { id } = message;\n\t\t\t\tconst pending = this.requestManager.getPendingRequest(id);\n\t\t\t\tconst draining = this.requestManager.getDrainingRequests().filter((request) => request.message === message);\n\t\t\t\tabort();\n\t\t\t\tif (type === \"subscription\" && pending) {\n\t\t\t\t\tthis.stopSubscription(id, pending.ws);\n\t\t\t\t\tthis.stopSubscription(id, pending.successor);\n\t\t\t\t}\n\t\t\t\tthis.closeIfDrained(pending === null || pending === void 0 ? void 0 : pending.ws);\n\t\t\t\tfor (const request of [pending, ...draining]) {\n\t\t\t\t\tvar _request$movedFrom;\n\t\t\t\t\tfor (const earlier of (_request$movedFrom = request === null || request === void 0 ? void 0 : request.movedFrom) !== null && _request$movedFrom !== void 0 ? _request$movedFrom : []) this.closeIfDrained(earlier);\n\t\t\t\t}\n\t\t\t\tsignal === null || signal === void 0 || signal.removeEventListener(\"abort\", onAbort);\n\t\t\t};\n\t\t});\n\t}\n\t/**\n\t* The current WebSocket and its state, or `null` when there is no socket.\n\t*/\n\tget connection() {\n\t\tvar _this$nextConnection2;\n\t\treturn backwardCompatibility(this.activeConnection.ws ? this.activeConnection : (_this$nextConnection2 = this.nextConnection) !== null && _this$nextConnection2 !== void 0 ? _this$nextConnection2 : this.activeConnection);\n\t}\n\t/**\n\t* Opens a new connection, retrying until one opens. While the current\n\t* socket is open, it keeps serving every request, new ones included, until\n\t* the new one is fully open, `connectionParams` included.\n\t*\n\t* @param closedError - Why the current socket was lost, or `null` when it's\n\t* still open and serving requests, e.g. on a server-requested reconnect.\n\t*/\n\treconnect(closedError) {\n\t\tif (!this.allowReconnect) return;\n\t\tif (closedError) {\n\t\t\tvar _this$replacementErro;\n\t\t\tconst error = (_this$replacementErro = this.replacementError) !== null && _this$replacementErro !== void 0 ? _this$replacementErro : closedError;\n\t\t\tthis.replacementError = null;\n\t\t\tcallUserCallback(() => this.connectionState.next({\n\t\t\t\ttype: \"state\",\n\t\t\t\tstate: \"connecting\",\n\t\t\t\terror: TRPCClientError.from(error)\n\t\t\t}));\n\t\t}\n\t\tif (this.reconnecting) return;\n\t\tconst tryReconnect = async (attemptIndex) => {\n\t\t\ttry {\n\t\t\t\tawait sleep(this.reconnectRetryDelay(attemptIndex));\n\t\t\t\tif (this.allowReconnect) {\n\t\t\t\t\tconst next = this.createConnection();\n\t\t\t\t\tthis.nextConnection = next;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait next.open();\n\t\t\t\t\t\tif (!next.isOpen()) throw new Error(\"WebSocket closed before it was ready\");\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tawait next.close().catch(() => null);\n\t\t\t\t\t\tthrow error;\n\t\t\t\t\t} finally {\n\t\t\t\t\t\tthis.nextConnection = null;\n\t\t\t\t\t}\n\t\t\t\t\tif (this.allowReconnect) {\n\t\t\t\t\t\tconst previous = this.activeConnection;\n\t\t\t\t\t\tthis.activeConnection = next;\n\t\t\t\t\t\tthis.retiredConnection = previous.isOpen() ? previous : null;\n\t\t\t\t\t\tthis.connectionAttemptIndex = attemptIndex;\n\t\t\t\t\t\tthis.replacementError = null;\n\t\t\t\t\t\tthis.handOff(previous.ws);\n\t\t\t\t\t} else await next.close();\n\t\t\t\t}\n\t\t\t\tthis.reconnecting = null;\n\t\t\t} catch (error) {\n\t\t\t\tconst closedError = new TRPCWebSocketClosedError({\n\t\t\t\t\tmessage: \"Initialization error\",\n\t\t\t\t\tcause: error\n\t\t\t\t});\n\t\t\t\tif (this.allowReconnect && this.activeConnection.isOpen()) this.replacementError = closedError;\n\t\t\t\telse if (this.allowReconnect) callUserCallback(() => this.connectionState.next({\n\t\t\t\t\ttype: \"state\",\n\t\t\t\t\tstate: \"connecting\",\n\t\t\t\t\terror: TRPCClientError.from(closedError)\n\t\t\t\t}));\n\t\t\t\tawait tryReconnect(attemptIndex + 1);\n\t\t\t}\n\t\t};\n\t\tthis.reconnecting = tryReconnect(this.connectionRejected ? this.connectionAttemptIndex + 1 : 0);\n\t}\n\t/**\n\t* Moves the pending subscriptions to the active socket, which has just\n\t* opened: each is resubscribed with the id of the last event it delivered.\n\t* A subscription whose old socket is still open keeps delivering from it\n\t* until the new socket confirms it with `started`; see `confirmMove()`.\n\t* Closes the previous socket once nothing is left on it.\n\t*/\n\thandOff(previous) {\n\t\tif (this.connectionState.get().state !== \"pending\" && this.activeConnection.isOpen()) callUserCallback(() => this.connectionState.next({\n\t\t\ttype: \"state\",\n\t\t\tstate: \"pending\",\n\t\t\terror: null\n\t\t}));\n\t\tconst ws = this.activeConnection.ws;\n\t\tconst subscriptions = this.requestManager.getPendingRequests().filter((request) => request.message.method === \"subscription\" && request.ws !== ws);\n\t\tif (subscriptions.length) {\n\t\t\tthis.send(subscriptions.map(({ message }) => message));\n\t\t\tfor (const request of subscriptions) {\n\t\t\t\tthis.stopSubscription(request.message.id, request.successor);\n\t\t\t\tif (request.ws && request.ws.readyState === request.ws.OPEN) {\n\t\t\t\t\trequest.successor = ws;\n\t\t\t\t\trequest.overlapEventIds = /* @__PURE__ */ new Set();\n\t\t\t\t} else {\n\t\t\t\t\tthis.started.delete(request.message);\n\t\t\t\t\trequest.ws = ws;\n\t\t\t\t\trequest.successor = null;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tthis.closeIfDrained(previous);\n\t}\n\t/**\n\t* Completes a subscription's move once its new socket has confirmed it:\n\t* stops it on the old socket, whose later messages for it are dropped\n\t* apart from events without ids, and closes that socket once everything it\n\t* sent before the stop has arrived and nothing else is left on it.\n\t*/\n\tconfirmMove(request) {\n\t\tconst previous = request.ws;\n\t\trequest.ws = request.successor;\n\t\trequest.successor = null;\n\t\tif (previous && this.stopSubscription(request.message.id, previous)) {\n\t\t\trequest.movedFrom.add(previous);\n\t\t\tsendPing(previous, () => this.releaseMovedFrom(request, previous));\n\t\t}\n\t\tthis.closeIfDrained(previous);\n\t}\n\treleaseMovedFrom(request, ws) {\n\t\tif (!request.movedFrom.delete(ws)) return;\n\t\tthis.requestManager.deleteDrained();\n\t\tthis.closeIfDrained(ws);\n\t}\n\thasRequestsOn(ws) {\n\t\treturn [...this.requestManager.getPendingRequests(), ...this.requestManager.getDrainingRequests()].some((request) => request.ws === ws || ws !== null && request.movedFrom.has(ws));\n\t}\n\t/**\n\t* Closes `ws` once it's been replaced and nothing is left on it.\n\t*/\n\tcloseIfDrained(ws) {\n\t\tif (!ws || ws === this.activeConnection.ws) return;\n\t\tif (this.hasRequestsOn(ws)) return;\n\t\tws.close();\n\t}\n\t/**\n\t* Stops a subscription on the socket it was sent on, if that's still open.\n\t*\n\t* @returns Whether the stop was sent.\n\t*/\n\tstopSubscription(id, ws) {\n\t\tif (!ws || ws.readyState !== ws.OPEN) return false;\n\t\tws.send(this.encoder.encode({\n\t\t\tid,\n\t\t\tmethod: \"subscription.stop\"\n\t\t}));\n\t\treturn true;\n\t}\n\t/**\n\t* Fails the pending queries and mutations sent on `ws`, and returns its\n\t* pending subscriptions, which are kept to be sent again.\n\t*/\n\tfailPendingRequests(ws, cause) {\n\t\tconst subscriptions = [];\n\t\tfor (const request of this.requestManager.getPendingRequests()) {\n\t\t\tconst { message, callbacks } = request;\n\t\t\tif (request.ws !== ws) continue;\n\t\t\tif (message.method === \"subscription\") {\n\t\t\t\tsubscriptions.push(request);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tcallUserCallback(() => callbacks.error(TRPCClientError.from(cause !== null && cause !== void 0 ? cause : new TRPCWebSocketClosedError({\n\t\t\t\tmessage: \"WebSocket closed\",\n\t\t\t\tcause\n\t\t\t}))));\n\t\t\tthis.requestManager.delete(message);\n\t\t}\n\t\treturn subscriptions;\n\t}\n\tsetupWebSocketListeners(ws) {\n\t\tthis.connectionRejected = false;\n\t\t/**\n\t\t* Fails the queries and mutations sent on `ws`. Its subscriptions are\n\t\t* sent again on the active socket if that's open, or else by\n\t\t* `reconnect()` once the next one opens.\n\t\t*/\n\t\tconst handleCloseOrError = (cause) => {\n\t\t\tvar _this$retiredConnecti;\n\t\t\tif (ws === ((_this$retiredConnecti = this.retiredConnection) === null || _this$retiredConnecti === void 0 ? void 0 : _this$retiredConnecti.ws)) this.retiredConnection = null;\n\t\t\tconst retired = this.retiredConnection;\n\t\t\tlet restored = false;\n\t\t\tif (ws === this.activeConnection.ws && (retired === null || retired === void 0 ? void 0 : retired.isOpen())) {\n\t\t\t\trestored = true;\n\t\t\t\tthis.activeConnection = retired;\n\t\t\t\tthis.retiredConnection = null;\n\t\t\t\tthis.replacementError = new TRPCWebSocketClosedError({\n\t\t\t\t\tmessage: \"WebSocket closed\",\n\t\t\t\t\tcause\n\t\t\t\t});\n\t\t\t}\n\t\t\tfor (const request of this.requestManager.getPendingRequests()) {\n\t\t\t\tif (request.successor === ws) {\n\t\t\t\t\trequest.successor = null;\n\t\t\t\t\trequest.overlapEventIds = null;\n\t\t\t\t}\n\t\t\t\trequest.movedFrom.delete(ws);\n\t\t\t}\n\t\t\tfor (const request of this.requestManager.getDrainingRequests()) request.movedFrom.delete(ws);\n\t\t\tthis.requestManager.deleteDrained();\n\t\t\tconst lost = this.failPendingRequests(ws, cause).filter((request) => {\n\t\t\t\tif (!request.successor) return true;\n\t\t\t\trequest.ws = request.successor;\n\t\t\t\trequest.successor = null;\n\t\t\t\treturn false;\n\t\t\t});\n\t\t\tif (ws === this.activeConnection.ws || this.reconnecting && !this.activeConnection.isOpen()) return;\n\t\t\tfor (const { message, callbacks } of lost) {\n\t\t\t\tthis.started.delete(message);\n\t\t\t\tthis.requestManager.requeue(message, ++this.lastRequestId);\n\t\t\t\tthis.flushOutgoing(message, callbacks);\n\t\t\t}\n\t\t\tif (restored) this.reconnect(null);\n\t\t};\n\t\tws.addEventListener(\"open\", () => {\n\t\t\trun(async () => {\n\t\t\t\tvar _this$callbacks$onOpe, _this$callbacks;\n\t\t\t\tif (this.lazyMode) this.inactivityTimeout.start();\n\t\t\t\t(_this$callbacks$onOpe = (_this$callbacks = this.callbacks).onOpen) === null || _this$callbacks$onOpe === void 0 || _this$callbacks$onOpe.call(_this$callbacks);\n\t\t\t\tif (this.connectionState.get().state === \"pending\" || ws !== this.activeConnection.ws && this.activeConnection.isOpen()) return;\n\t\t\t\tcallUserCallback(() => this.connectionState.next({\n\t\t\t\t\ttype: \"state\",\n\t\t\t\t\tstate: \"pending\",\n\t\t\t\t\terror: null\n\t\t\t\t}));\n\t\t\t}).catch((error) => {\n\t\t\t\tws.close(3e3);\n\t\t\t\thandleCloseOrError(error);\n\t\t\t});\n\t\t});\n\t\tconst onMessage = ({ data }) => {\n\t\t\tvar _this$nextConnection3;\n\t\t\tthis.inactivityTimeout.reset();\n\t\t\tif ([\"PING\", \"PONG\"].includes(data)) return;\n\t\t\tconst incomingMessage = this.encoder.decode(data);\n\t\t\tif (\"method\" in incomingMessage) {\n\t\t\t\tif (ws === this.activeConnection.ws) this.handleIncomingRequest(incomingMessage);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst isRetired = ws !== this.activeConnection.ws && ws !== ((_this$nextConnection3 = this.nextConnection) === null || _this$nextConnection3 === void 0 ? void 0 : _this$nextConnection3.ws);\n\t\t\tif (!isRetired && incomingMessage.id === null && \"error\" in incomingMessage) this.connectionRejected = true;\n\t\t\telse if (!isRetired && \"result\" in incomingMessage) this.connectionRejected = false;\n\t\t\tthis.handleResponseMessage(incomingMessage, ws);\n\t\t};\n\t\tws.addEventListener(\"message\", (event) => {\n\t\t\tcallUserCallback(() => onMessage(event));\n\t\t});\n\t\tws.addEventListener(\"close\", (event) => {\n\t\t\thandleCloseOrError(event);\n\t\t\tcallUserCallback(() => {\n\t\t\t\tvar _this$callbacks$onClo, _this$callbacks2;\n\t\t\t\treturn (_this$callbacks$onClo = (_this$callbacks2 = this.callbacks).onClose) === null || _this$callbacks$onClo === void 0 ? void 0 : _this$callbacks$onClo.call(_this$callbacks2, event);\n\t\t\t});\n\t\t\tif (ws === this.activeConnection.ws && (!this.lazyMode || this.requestManager.hasPendingSubscriptions())) this.reconnect(new TRPCWebSocketClosedError({\n\t\t\t\tmessage: \"WebSocket closed\",\n\t\t\t\tcause: event\n\t\t\t}));\n\t\t});\n\t\tws.addEventListener(\"error\", (event) => {\n\t\t\thandleCloseOrError(event);\n\t\t\tcallUserCallback(() => {\n\t\t\t\tvar _this$callbacks$onErr, _this$callbacks3;\n\t\t\t\treturn (_this$callbacks$onErr = (_this$callbacks3 = this.callbacks).onError) === null || _this$callbacks$onErr === void 0 ? void 0 : _this$callbacks$onErr.call(_this$callbacks3, event);\n\t\t\t});\n\t\t\tif (ws !== this.activeConnection.ws) return;\n\t\t\tthis.reconnect(new TRPCWebSocketClosedError({\n\t\t\t\tmessage: \"WebSocket closed\",\n\t\t\t\tcause: event\n\t\t\t}));\n\t\t});\n\t}\n\thandleResponseMessage(message, ws) {\n\t\tvar _this$requestManager$;\n\t\tconst request = (_this$requestManager$ = this.requestManager.getPendingRequest(message.id)) !== null && _this$requestManager$ !== void 0 ? _this$requestManager$ : this.requestManager.getDrainingRequest(message.id);\n\t\tif (!request) return;\n\t\tconst result = \"result\" in message ? message.result : null;\n\t\tif (request.successor === ws) this.confirmMove(request);\n\t\telse if (request.ws !== ws) {\n\t\t\tif (request.movedFrom.has(ws)) {\n\t\t\t\tif ((result === null || result === void 0 ? void 0 : result.type) === \"stopped\") this.releaseMovedFrom(request, ws);\n\t\t\t\telse if ((result === null || result === void 0 ? void 0 : result.type) === \"data\" && result.id === void 0) callUserCallback(() => request.callbacks.next(message));\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tif ((result === null || result === void 0 ? void 0 : result.type) === \"started\" && this.started.has(request.message)) return;\n\t\tif ((result === null || result === void 0 ? void 0 : result.type) === \"data\" && result.id !== void 0) {\n\t\t\tvar _request$overlapEvent2;\n\t\t\tconst eventId = String(result.id);\n\t\t\tif (request.successor) {\n\t\t\t\tvar _request$overlapEvent;\n\t\t\t\t(_request$overlapEvent = request.overlapEventIds) === null || _request$overlapEvent === void 0 || _request$overlapEvent.add(eventId);\n\t\t\t} else if ((_request$overlapEvent2 = request.overlapEventIds) === null || _request$overlapEvent2 === void 0 ? void 0 : _request$overlapEvent2.delete(eventId)) return;\n\t\t}\n\t\tcallUserCallback(() => request.callbacks.next(message));\n\t\tlet completed = true;\n\t\tif (\"result\" in message && request.message.method === \"subscription\") {\n\t\t\tif (message.result.type === \"data\") request.message.params.lastEventId = message.result.id;\n\t\t\telse if (message.result.type === \"started\") this.started.add(request.message);\n\t\t\tif (message.result.type !== \"stopped\") completed = false;\n\t\t}\n\t\tif (completed) {\n\t\t\tcallUserCallback(() => request.callbacks.complete());\n\t\t\tthis.requestManager.delete(request.message);\n\t\t}\n\t}\n\thandleIncomingRequest(message) {\n\t\tif (message.method === \"reconnect\") this.reconnect(null);\n\t}\n\t/**\n\t* Sends a message or batch of messages directly to the server.\n\t*/\n\tsend(messageOrMessages) {\n\t\tif (!this.activeConnection.isOpen()) throw new Error(\"Active connection is not open\");\n\t\tconst messages = messageOrMessages instanceof Array ? messageOrMessages : [messageOrMessages];\n\t\tthis.activeConnection.ws.send(this.encoder.encode(messages.length === 1 ? messages[0] : messages));\n\t}\n\t/**\n\t* Groups requests for batch sending.\n\t*\n\t* @returns A function to abort the batched request.\n\t*/\n\tbatchSend(message, callbacks) {\n\t\tthis.inactivityTimeout.reset();\n\t\tthis.flushOutgoing(message, callbacks);\n\t\treturn this.requestManager.register(message, callbacks);\n\t}\n\t/**\n\t* Sends `message` with the other outgoing requests once the connection is\n\t* open, batching those queued in the same tick.\n\t*/\n\tflushOutgoing(message, callbacks) {\n\t\trun(async () => {\n\t\t\tdo {\n\t\t\t\tif (!this.activeConnection.isOpen()) await this.open();\n\t\t\t\tawait sleep(0);\n\t\t\t} while (!this.activeConnection.isOpen() && this.reconnecting);\n\t\t\tif (!this.requestManager.hasOutgoingRequests()) return;\n\t\t\tif (!this.activeConnection.isOpen() && !this.requestManager.isOutgoing(message)) return;\n\t\t\tconst requests = this.requestManager.flush(this.activeConnection.ws);\n\t\t\ttry {\n\t\t\t\tthis.send(requests.map((request) => request.message));\n\t\t\t} catch (err) {\n\t\t\t\tfor (const request of requests) {\n\t\t\t\t\tthis.requestManager.delete(request.message);\n\t\t\t\t\tcallUserCallback(() => request.callbacks.error(TRPCClientError.from(err)));\n\t\t\t\t}\n\t\t\t}\n\t\t}).catch((err) => {\n\t\t\tthis.requestManager.delete(message);\n\t\t\tcallUserCallback(() => callbacks.error(TRPCClientError.from(err)));\n\t\t});\n\t}\n};\n// src/links/wsLink/createWsClient.ts\n/**\n* Opens and manages a WebSocket connection to a tRPC server. Pass it to\n* `wsLink`.\n*\n* @see https://trpc.io/docs/client/links/wsLink#wslink--createwsclient-options\n*/\nfunction createWSClient(opts) {\n\treturn new WsClient(opts);\n}\n// src/links/wsLink/wsLink.ts\n/**\n* A terminating link that sends calls over a WebSocket.\n*\n* @see https://trpc.io/docs/client/links/wsLink\n*/\nfunction wsLink(opts) {\n\tconst { client } = opts;\n\tconst transformer = getTransformer(opts.transformer);\n\treturn () => {\n\t\treturn ({ op }) => {\n\t\t\treturn observable((observer) => {\n\t\t\t\tlet connStateSubscription = null;\n\t\t\t\tif (op.type === \"subscription\") {\n\t\t\t\t\tlet isSubscribing = true;\n\t\t\t\t\tconnStateSubscription = client.connectionState.subscribe({ next(result) {\n\t\t\t\t\t\tconst emit = () => observer.next({\n\t\t\t\t\t\t\tresult,\n\t\t\t\t\t\t\tcontext: op.context\n\t\t\t\t\t\t});\n\t\t\t\t\t\tif (isSubscribing) callUserCallback(emit);\n\t\t\t\t\t\telse emit();\n\t\t\t\t\t} });\n\t\t\t\t\tisSubscribing = false;\n\t\t\t\t}\n\t\t\t\tconst requestSubscription = client.request({\n\t\t\t\t\top,\n\t\t\t\t\ttransformer\n\t\t\t\t}).subscribe(observer);\n\t\t\t\treturn () => {\n\t\t\t\t\trequestSubscription.unsubscribe();\n\t\t\t\t\tconnStateSubscription === null || connStateSubscription === void 0 || connStateSubscription.unsubscribe();\n\t\t\t\t};\n\t\t\t});\n\t\t};\n\t};\n}\nexport { jsonEncoder as i, createWSClient as n, resultOf as r, wsLink as t };\n\n//# sourceMappingURL=wsLink-BiIe_j6D.mjs.map", "import { n as createChain, t as splitLink } from \"./splitLink-PFsRy7Mf.mjs\";\nimport { n as isTRPCClientError, t as TRPCClientError } from \"./TRPCClientError-DE6-fd1n.mjs\";\nimport { n as _defineProperty, t as _objectSpread2 } from \"./objectSpread2-pyA4QVO4.mjs\";\nimport { c as allAbortSignals, d as throwIfAborted, f as getFetch, l as raceAbortSignals, n as getBody, o as resolveHTTPLinkOptions, r as getUrl, s as abortSignalToPromise, t as fetchHTTPResponse } from \"./httpUtils-CtMuyl9j.mjs\";\nimport { n as dataLoader, t as httpBatchLink } from \"./httpBatchLink-BkVNtNND.mjs\";\nimport { i as isOctetType, n as isFormData, r as isNonJsonSerializable, t as httpLink } from \"./httpLink-B4UwXApa.mjs\";\nimport { loggerLink } from \"./links/loggerLink.mjs\";\nimport { i as jsonEncoder, n as createWSClient, r as resultOf, t as wsLink } from \"./wsLink-BiIe_j6D.mjs\";\nimport { getTransformer } from \"./unstable-internals.mjs\";\nimport { behaviorSubject, observable, observableToAsyncIterable, observableToPromise, share } from \"@trpc/server/observable\";\nimport { callProcedure, createFlatProxy, createRecursiveProxy, isAbortError, isAsyncIterable, isObject, iteratorResource, jsonlStreamConsumer, makeResource, resolvePathSeparator, retryableRpcCodes, run, sseStreamConsumer } from \"@trpc/server/unstable-core-do-not-import\";\nimport { getTRPCErrorFromUnknown, getTRPCErrorShape, isTrackedEnvelope } from \"@trpc/server\";\nimport { TRPC_ERROR_CODES_BY_KEY } from \"@trpc/server/rpc\";\n// src/internals/TRPCUntypedClient.ts\nconst observerKeys = [\n\t\"onStarted\",\n\t\"onData\",\n\t\"onError\",\n\t\"onStopped\",\n\t\"onComplete\",\n\t\"onConnectionStateChange\"\n];\n/**\n* A client that calls procedures by path string, without types.\n* `createTRPCClient` wraps one.\n*/\nvar TRPCUntypedClient = class {\n\tconstructor(opts) {\n\t\t_defineProperty(this, \"links\", void 0);\n\t\t_defineProperty(this, \"runtime\", void 0);\n\t\t_defineProperty(this, \"requestId\", void 0);\n\t\tthis.requestId = 0;\n\t\tthis.runtime = {};\n\t\tthis.links = opts.links.map((link) => link(this.runtime));\n\t}\n\t$request(opts) {\n\t\tvar _opts$context;\n\t\treturn createChain({\n\t\t\tlinks: this.links,\n\t\t\top: _objectSpread2(_objectSpread2({}, opts), {}, {\n\t\t\t\tcontext: (_opts$context = opts.context) !== null && _opts$context !== void 0 ? _opts$context : {},\n\t\t\t\tid: ++this.requestId\n\t\t\t})\n\t\t}).pipe(share());\n\t}\n\tasync requestAsPromise(opts) {\n\t\ttry {\n\t\t\tconst req$ = this.$request(opts);\n\t\t\treturn (await observableToPromise(req$)).result.data;\n\t\t} catch (err) {\n\t\t\tthrow TRPCClientError.from(err);\n\t\t}\n\t}\n\t/** Calls a query. */\n\tquery(path, input, opts) {\n\t\treturn this.requestAsPromise({\n\t\t\ttype: \"query\",\n\t\t\tpath,\n\t\t\tinput,\n\t\t\tcontext: opts === null || opts === void 0 ? void 0 : opts.context,\n\t\t\tsignal: opts === null || opts === void 0 ? void 0 : opts.signal\n\t\t});\n\t}\n\t/** Calls a mutation. */\n\tmutation(path, input, opts) {\n\t\treturn this.requestAsPromise({\n\t\t\ttype: \"mutation\",\n\t\t\tpath,\n\t\t\tinput,\n\t\t\tcontext: opts === null || opts === void 0 ? void 0 : opts.context,\n\t\t\tsignal: opts === null || opts === void 0 ? void 0 : opts.signal\n\t\t});\n\t}\n\tsubscription(path, input, opts = {}) {\n\t\tconst hasCallbacks = observerKeys.some((key) => typeof opts[key] === \"function\");\n\t\tconst observable$ = this.$request({\n\t\t\ttype: \"subscription\",\n\t\t\tpath,\n\t\t\tinput,\n\t\t\tcontext: opts.context,\n\t\t\tsignal: opts.signal\n\t\t});\n\t\tif (!hasCallbacks) {\n\t\t\tvar _opts$signal;\n\t\t\tconst data$ = observable((observer) => observable$.subscribe({\n\t\t\t\tnext(envelope) {\n\t\t\t\t\tif (envelope.result.type === \"data\" || envelope.result.type === void 0) observer.next(envelope.result.data);\n\t\t\t\t},\n\t\t\t\terror: (err) => observer.error(err),\n\t\t\t\tcomplete: () => observer.complete()\n\t\t\t}));\n\t\t\tconst iterator = observableToAsyncIterable(data$, (_opts$signal = opts.signal) !== null && _opts$signal !== void 0 ? _opts$signal : new AbortController().signal);\n\t\t\tlet iterated = false;\n\t\t\titerator[Symbol.asyncIterator] = () => {\n\t\t\t\tif (iterated) throw new Error(\"A subscription can only be iterated once. Call subscribe() again for another loop.\");\n\t\t\t\titerated = true;\n\t\t\t\treturn iterator;\n\t\t\t};\n\t\t\treturn iterator;\n\t\t}\n\t\treturn observable$.subscribe({\n\t\t\tnext(envelope) {\n\t\t\t\tswitch (envelope.result.type) {\n\t\t\t\t\tcase \"state\":\n\t\t\t\t\t\tvar _opts$onConnectionSta;\n\t\t\t\t\t\t(_opts$onConnectionSta = opts.onConnectionStateChange) === null || _opts$onConnectionSta === void 0 || _opts$onConnectionSta.call(opts, envelope.result);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"started\":\n\t\t\t\t\t\tvar _opts$onStarted;\n\t\t\t\t\t\t(_opts$onStarted = opts.onStarted) === null || _opts$onStarted === void 0 || _opts$onStarted.call(opts, { context: envelope.context });\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"stopped\":\n\t\t\t\t\t\tvar _opts$onStopped;\n\t\t\t\t\t\t(_opts$onStopped = opts.onStopped) === null || _opts$onStopped === void 0 || _opts$onStopped.call(opts);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"data\":\n\t\t\t\t\tcase void 0:\n\t\t\t\t\t\tvar _opts$onData;\n\t\t\t\t\t\t(_opts$onData = opts.onData) === null || _opts$onData === void 0 || _opts$onData.call(opts, envelope.result.data);\n\t\t\t\t}\n\t\t\t},\n\t\t\terror(err) {\n\t\t\t\tvar _opts$onError;\n\t\t\t\t(_opts$onError = opts.onError) === null || _opts$onError === void 0 || _opts$onError.call(opts, err);\n\t\t\t},\n\t\t\tcomplete() {\n\t\t\t\tvar _opts$onComplete;\n\t\t\t\t(_opts$onComplete = opts.onComplete) === null || _opts$onComplete === void 0 || _opts$onComplete.call(opts);\n\t\t\t}\n\t\t});\n\t}\n};\n// src/createTRPCUntypedClient.ts\n/**\n* Creates a client that calls procedures by path string, without types.\n* Meant for libraries built on tRPC; apps should use `createTRPCClient`.\n*/\nfunction createTRPCUntypedClient(opts) {\n\treturn new TRPCUntypedClient(opts);\n}\n// src/createTRPCClient.ts\nconst untypedClientSymbol = Symbol.for(\"trpc_untypedClient\");\nconst clientCallTypeMap = {\n\tquery: \"query\",\n\tmutate: \"mutation\",\n\tsubscribe: \"subscription\"\n};\n/**\n* The procedure type of a client method: `query`, `mutate` or `subscribe`.\n* @internal\n*/\nconst clientCallTypeToProcedureType = (clientCallType) => {\n\treturn clientCallTypeMap[clientCallType];\n};\n/**\n* Wraps an untyped client in the typed proxy `createTRPCClient` returns.\n* @internal\n*/\nfunction createTRPCClientProxy(client) {\n\tconst proxy = createRecursiveProxy(({ path, args }) => {\n\t\tconst pathCopy = [...path];\n\t\tconst procedureType = clientCallTypeToProcedureType(pathCopy.pop());\n\t\tconst fullPath = pathCopy.join(\".\");\n\t\treturn client[procedureType](fullPath, ...args);\n\t});\n\treturn createFlatProxy((key) => {\n\t\tif (key === untypedClientSymbol) return client;\n\t\treturn proxy[key];\n\t});\n}\n/**\n* Creates a typed client for a router. Pass the router's type, and the\n* links that send its calls.\n* @example\n* ```ts\n* const client = createTRPCClient<AppRouter>({\n* links: [httpBatchLink({ url: 'http://localhost:3000/trpc' })],\n* });\n* const post = await client.post.byId.query({ id: '1' });\n* ```\n* @see https://trpc.io/docs/client/vanilla/setup#3-initialize-the-trpc-client\n*/\nfunction createTRPCClient(opts) {\n\treturn createTRPCClientProxy(new TRPCUntypedClient(opts));\n}\n/**\n* The untyped client behind a typed client, which calls procedures by\n* path string.\n* @internal\n*/\nfunction getUntypedClient(client) {\n\treturn client[untypedClientSymbol];\n}\n// src/links/httpBatchStreamLink.ts\n/**\n* A terminating link that batches calls like `httpBatchLink`, but streams each\n* response back as soon as it is ready.\n*\n* @see https://trpc.io/docs/client/links/httpBatchStreamLink\n*/\nfunction httpBatchStreamLink(opts) {\n\tvar _opts$maxURLLength, _opts$maxItems;\n\tconst resolvedOpts = resolveHTTPLinkOptions(opts);\n\tconst maxURLLength = (_opts$maxURLLength = opts.maxURLLength) !== null && _opts$maxURLLength !== void 0 ? _opts$maxURLLength : Infinity;\n\tconst maxItems = (_opts$maxItems = opts.maxItems) !== null && _opts$maxItems !== void 0 ? _opts$maxItems : Infinity;\n\treturn () => {\n\t\tconst batchLoader = (type) => {\n\t\t\treturn {\n\t\t\t\tvalidate(batchOps) {\n\t\t\t\t\tif (maxURLLength === Infinity && maxItems === Infinity) return true;\n\t\t\t\t\tif (batchOps.length > maxItems) return false;\n\t\t\t\t\tconst path = batchOps.map((op) => op.path).join(\",\");\n\t\t\t\t\tconst inputs = batchOps.map((op) => op.input);\n\t\t\t\t\treturn getUrl(_objectSpread2(_objectSpread2({}, resolvedOpts), {}, {\n\t\t\t\t\t\ttype,\n\t\t\t\t\t\tpath,\n\t\t\t\t\t\tinputs,\n\t\t\t\t\t\tsignal: null\n\t\t\t\t\t})).length <= maxURLLength;\n\t\t\t\t},\n\t\t\t\tasync fetch(batchOps) {\n\t\t\t\t\tvar _opts$streamHeader;\n\t\t\t\t\tconst path = batchOps.map((op) => op.path).join(\",\");\n\t\t\t\t\tconst inputs = batchOps.map((op) => op.input);\n\t\t\t\t\tconst batchSignals = allAbortSignals(...batchOps.map((op) => op.signal));\n\t\t\t\t\tconst abortController = new AbortController();\n\t\t\t\t\tconst res = await fetchHTTPResponse(_objectSpread2(_objectSpread2({}, resolvedOpts), {}, {\n\t\t\t\t\t\tsignal: raceAbortSignals(batchSignals, abortController.signal),\n\t\t\t\t\t\ttype,\n\t\t\t\t\t\tcontentTypeHeader: \"application/json\",\n\t\t\t\t\t\ttrpcAcceptHeader: \"application/jsonl\",\n\t\t\t\t\t\ttrpcAcceptHeaderKey: (_opts$streamHeader = opts.streamHeader) !== null && _opts$streamHeader !== void 0 ? _opts$streamHeader : \"trpc-accept\",\n\t\t\t\t\t\tgetUrl,\n\t\t\t\t\t\tgetBody,\n\t\t\t\t\t\tinputs,\n\t\t\t\t\t\tpath,\n\t\t\t\t\t\theaders() {\n\t\t\t\t\t\t\tif (!opts.headers) return {};\n\t\t\t\t\t\t\tif (typeof opts.headers === \"function\") return opts.headers({ opList: batchOps });\n\t\t\t\t\t\t\treturn opts.headers;\n\t\t\t\t\t\t}\n\t\t\t\t\t}));\n\t\t\t\t\tif (!res.ok) {\n\t\t\t\t\t\tconst json = await res.json();\n\t\t\t\t\t\tif (\"error\" in json) json.error = resolvedOpts.transformer.output.deserialize(json.error);\n\t\t\t\t\t\treturn batchOps.map(() => Promise.resolve({\n\t\t\t\t\t\t\tjson,\n\t\t\t\t\t\t\tmeta: { response: res }\n\t\t\t\t\t\t}));\n\t\t\t\t\t}\n\t\t\t\t\tconst [head] = await jsonlStreamConsumer({\n\t\t\t\t\t\tfrom: res.body,\n\t\t\t\t\t\tdeserialize: (data) => resolvedOpts.transformer.output.deserialize(data),\n\t\t\t\t\t\tformatError(opts) {\n\t\t\t\t\t\t\tconst error = opts.error;\n\t\t\t\t\t\t\treturn TRPCClientError.from({ error });\n\t\t\t\t\t\t},\n\t\t\t\t\t\tabortController\n\t\t\t\t\t});\n\t\t\t\t\treturn Object.keys(batchOps).map(async (key) => {\n\t\t\t\t\t\tlet json = await Promise.resolve(head[key]);\n\t\t\t\t\t\tif (\"result\" in json) {\n\t\t\t\t\t\t\t/**\n\t\t\t\t\t\t\t* Not very pretty, but we need to unwrap nested data as promises\n\t\t\t\t\t\t\t* Our stream producer will only resolve top-level async values or async values that are directly nested in another async value\n\t\t\t\t\t\t\t*/\n\t\t\t\t\t\t\tconst result = await Promise.resolve(json.result);\n\t\t\t\t\t\t\tjson = { result: { data: await Promise.resolve(result.data) } };\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tjson,\n\t\t\t\t\t\t\tmeta: { response: res }\n\t\t\t\t\t\t};\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t};\n\t\t};\n\t\tconst loaders = {\n\t\t\tquery: dataLoader(batchLoader(\"query\")),\n\t\t\tmutation: dataLoader(batchLoader(\"mutation\"))\n\t\t};\n\t\treturn ({ op }) => {\n\t\t\treturn observable((observer) => {\n\t\t\t\t/* istanbul ignore if -- @preserve */\n\t\t\t\tif (op.type === \"subscription\") throw new Error(\"Subscriptions are unsupported by `httpBatchStreamLink` - use `httpSubscriptionLink` or `wsLink`\");\n\t\t\t\tconst ac = new AbortController();\n\t\t\t\tconst promise = loaders[op.type].load(_objectSpread2(_objectSpread2({}, op), {}, { signal: raceAbortSignals(op.signal, ac.signal) }));\n\t\t\t\tlet isDone = false;\n\t\t\t\tlet _res = void 0;\n\t\t\t\tpromise.then((res) => {\n\t\t\t\t\tisDone = true;\n\t\t\t\t\t_res = res;\n\t\t\t\t\tif (\"error\" in res.json) {\n\t\t\t\t\t\tobserver.error(TRPCClientError.from(res.json, { meta: res.meta }));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t} else if (\"result\" in res.json) {\n\t\t\t\t\t\tobserver.next({\n\t\t\t\t\t\t\tcontext: res.meta,\n\t\t\t\t\t\t\tresult: res.json.result\n\t\t\t\t\t\t});\n\t\t\t\t\t\tobserver.complete();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tobserver.complete();\n\t\t\t\t}).catch((err) => {\n\t\t\t\t\tisDone = true;\n\t\t\t\t\tobserver.error(TRPCClientError.from(err, { meta: _res === null || _res === void 0 ? void 0 : _res.meta }));\n\t\t\t\t});\n\t\t\t\treturn () => {\n\t\t\t\t\tif (!isDone) ac.abort();\n\t\t\t\t};\n\t\t\t});\n\t\t};\n\t};\n}\n/**\n* @deprecated Use {@link httpBatchStreamLink} instead.\n*/\nconst unstable_httpBatchStreamLink = httpBatchStreamLink;\n// src/internals/inputWithTrackedEventId.ts\nfunction inputWithTrackedEventId(input, lastEventId) {\n\tif (!lastEventId) return input;\n\tif (input != null && !isObject(input)) return input;\n\treturn _objectSpread2(_objectSpread2({}, input !== null && input !== void 0 ? input : {}), {}, { lastEventId });\n}\n// \\0@oxc-project+runtime@0.157.0/helpers/esm/asyncIterator.js\nfunction _asyncIterator(r) {\n\tvar n, t, o, e = 2;\n\tfor (\"undefined\" != typeof Symbol && (t = Symbol.asyncIterator, o = Symbol.iterator); e--;) {\n\t\tif (t && null != (n = r[t])) return n.call(r);\n\t\tif (o && null != (n = r[o])) return new AsyncFromSyncIterator(n.call(r));\n\t\tt = \"@@asyncIterator\", o = \"@@iterator\";\n\t}\n\tthrow new TypeError(\"Object is not async iterable\");\n}\nfunction AsyncFromSyncIterator(r) {\n\tfunction AsyncFromSyncIteratorContinuation(r) {\n\t\tif (Object(r) !== r) return Promise.reject(/* @__PURE__ */ new TypeError(r + \" is not an object.\"));\n\t\tvar n = r.done;\n\t\treturn Promise.resolve(r.value).then(function(r) {\n\t\t\treturn {\n\t\t\t\tvalue: r,\n\t\t\t\tdone: n\n\t\t\t};\n\t\t});\n\t}\n\treturn AsyncFromSyncIterator = function AsyncFromSyncIterator(r) {\n\t\tthis.s = r, this.n = r.next;\n\t}, AsyncFromSyncIterator.prototype = {\n\t\ts: null,\n\t\tn: null,\n\t\tnext: function next() {\n\t\t\treturn AsyncFromSyncIteratorContinuation(this.n.apply(this.s, arguments));\n\t\t},\n\t\t\"return\": function _return(r) {\n\t\t\tvar n = this.s[\"return\"];\n\t\t\treturn void 0 === n ? Promise.resolve({\n\t\t\t\tvalue: r,\n\t\t\t\tdone: !0\n\t\t\t}) : AsyncFromSyncIteratorContinuation(n.apply(this.s, arguments));\n\t\t},\n\t\t\"throw\": function _throw(r) {\n\t\t\tvar n = this.s[\"throw\"];\n\t\t\treturn void 0 === n ? Promise.reject(r) : AsyncFromSyncIteratorContinuation(n.apply(this.s, arguments));\n\t\t}\n\t}, new AsyncFromSyncIterator(r);\n}\n// src/links/httpSubscriptionLink.ts\nasync function urlWithConnectionParams(opts) {\n\tlet url = await resultOf(opts.url);\n\tif (opts.connectionParams) {\n\t\tconst params = await resultOf(opts.connectionParams);\n\t\tconst prefix = url.includes(\"?\") ? \"&\" : \"?\";\n\t\turl += prefix + \"connectionParams=\" + encodeURIComponent(JSON.stringify(params));\n\t}\n\treturn url;\n}\n/**\n* A terminating link that runs subscriptions over Server-Sent Events.\n*\n* @see https://trpc.io/docs/client/links/httpSubscriptionLink\n*/\nfunction httpSubscriptionLink(opts) {\n\tconst transformer = getTransformer(opts.transformer);\n\tconst pathSeparator = resolvePathSeparator(opts.pathSeparator);\n\treturn () => {\n\t\treturn ({ op }) => {\n\t\t\treturn observable((observer) => {\n\t\t\t\tvar _opts$EventSource;\n\t\t\t\tconst { type, path, input } = op;\n\t\t\t\t/* istanbul ignore if -- @preserve */\n\t\t\t\tif (type !== \"subscription\") throw new Error(\"httpSubscriptionLink only supports subscriptions\");\n\t\t\t\tlet lastEventId = void 0;\n\t\t\t\tconst ac = new AbortController();\n\t\t\t\tconst signal = raceAbortSignals(op.signal, ac.signal);\n\t\t\t\tconst eventSourceStream = sseStreamConsumer({\n\t\t\t\t\turl: async () => getUrl({\n\t\t\t\t\t\ttransformer,\n\t\t\t\t\t\turl: await urlWithConnectionParams(opts),\n\t\t\t\t\t\tinput: inputWithTrackedEventId(input, lastEventId),\n\t\t\t\t\t\tpath,\n\t\t\t\t\t\tpathSeparator,\n\t\t\t\t\t\ttype,\n\t\t\t\t\t\tsignal: null\n\t\t\t\t\t}),\n\t\t\t\t\tinit: () => resultOf(opts.eventSourceOptions, { op }),\n\t\t\t\t\tsignal,\n\t\t\t\t\tdeserialize: (data) => transformer.output.deserialize(data),\n\t\t\t\t\tEventSource: (_opts$EventSource = opts.EventSource) !== null && _opts$EventSource !== void 0 ? _opts$EventSource : globalThis.EventSource\n\t\t\t\t});\n\t\t\t\tconst connectionState = behaviorSubject({\n\t\t\t\t\ttype: \"state\",\n\t\t\t\t\tstate: \"connecting\",\n\t\t\t\t\terror: null\n\t\t\t\t});\n\t\t\t\tconst connectionSub = connectionState.subscribe({ next(state) {\n\t\t\t\t\tobserver.next({ result: state });\n\t\t\t\t} });\n\t\t\t\trun(async () => {\n\t\t\t\t\tvar _iteratorAbruptCompletion = false;\n\t\t\t\t\tvar _didIteratorError = false;\n\t\t\t\t\tvar _iteratorError;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tfor (var _iterator = _asyncIterator(eventSourceStream), _step; _iteratorAbruptCompletion = !(_step = await _iterator.next()).done; _iteratorAbruptCompletion = false) {\n\t\t\t\t\t\t\tconst chunk = _step.value;\n\t\t\t\t\t\t\tswitch (chunk.type) {\n\t\t\t\t\t\t\t\tcase \"ping\": break;\n\t\t\t\t\t\t\t\tcase \"data\":\n\t\t\t\t\t\t\t\t\tconst chunkData = chunk.data;\n\t\t\t\t\t\t\t\t\tlet result;\n\t\t\t\t\t\t\t\t\tif (chunkData.id) {\n\t\t\t\t\t\t\t\t\t\tlastEventId = chunkData.id;\n\t\t\t\t\t\t\t\t\t\tresult = {\n\t\t\t\t\t\t\t\t\t\t\tid: chunkData.id,\n\t\t\t\t\t\t\t\t\t\t\tdata: chunkData\n\t\t\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\t\t} else result = { data: chunkData.data };\n\t\t\t\t\t\t\t\t\tobserver.next({\n\t\t\t\t\t\t\t\t\t\tresult,\n\t\t\t\t\t\t\t\t\t\tcontext: { eventSource: chunk.eventSource }\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\tcase \"connected\":\n\t\t\t\t\t\t\t\t\tobserver.next({\n\t\t\t\t\t\t\t\t\t\tresult: { type: \"started\" },\n\t\t\t\t\t\t\t\t\t\tcontext: { eventSource: chunk.eventSource }\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\tconnectionState.next({\n\t\t\t\t\t\t\t\t\t\ttype: \"state\",\n\t\t\t\t\t\t\t\t\t\tstate: \"pending\",\n\t\t\t\t\t\t\t\t\t\terror: null\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\tcase \"serialized-error\": {\n\t\t\t\t\t\t\t\t\tconst error = TRPCClientError.from({ error: chunk.error });\n\t\t\t\t\t\t\t\t\tif (retryableRpcCodes.includes(chunk.error.code)) {\n\t\t\t\t\t\t\t\t\t\tconnectionState.next({\n\t\t\t\t\t\t\t\t\t\t\ttype: \"state\",\n\t\t\t\t\t\t\t\t\t\t\tstate: \"connecting\",\n\t\t\t\t\t\t\t\t\t\t\terror\n\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tthrow error;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcase \"connecting\": {\n\t\t\t\t\t\t\t\t\tconst lastState = connectionState.get();\n\t\t\t\t\t\t\t\t\tconst error = chunk.event && TRPCClientError.from(chunk.event);\n\t\t\t\t\t\t\t\t\tif (!error && lastState.state === \"connecting\") break;\n\t\t\t\t\t\t\t\t\tconnectionState.next({\n\t\t\t\t\t\t\t\t\t\ttype: \"state\",\n\t\t\t\t\t\t\t\t\t\tstate: \"connecting\",\n\t\t\t\t\t\t\t\t\t\terror\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcase \"timeout\": connectionState.next({\n\t\t\t\t\t\t\t\t\ttype: \"state\",\n\t\t\t\t\t\t\t\t\tstate: \"connecting\",\n\t\t\t\t\t\t\t\t\terror: new TRPCClientError(`Timeout of ${chunk.ms}ms reached while waiting for a response`)\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\t_didIteratorError = true;\n\t\t\t\t\t\t_iteratorError = err;\n\t\t\t\t\t} finally {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tif (_iteratorAbruptCompletion && _iterator.return != null) await _iterator.return();\n\t\t\t\t\t\t} finally {\n\t\t\t\t\t\t\tif (_didIteratorError) throw _iteratorError;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tobserver.next({ result: { type: \"stopped\" } });\n\t\t\t\t\tconnectionState.next({\n\t\t\t\t\t\ttype: \"state\",\n\t\t\t\t\t\tstate: \"idle\",\n\t\t\t\t\t\terror: null\n\t\t\t\t\t});\n\t\t\t\t\tobserver.complete();\n\t\t\t\t}).catch((error) => {\n\t\t\t\t\tobserver.error(TRPCClientError.from(error));\n\t\t\t\t});\n\t\t\t\treturn () => {\n\t\t\t\t\tobserver.complete();\n\t\t\t\t\tac.abort();\n\t\t\t\t\tconnectionSub.unsubscribe();\n\t\t\t\t};\n\t\t\t});\n\t\t};\n\t};\n}\n/**\n* @deprecated Use {@link httpSubscriptionLink} instead.\n*/\nconst unstable_httpSubscriptionLink = httpSubscriptionLink;\n// src/links/retryLink.ts\n/* istanbul ignore file -- @preserve */\n/**\n* Retries failed operations. Subscriptions resume from the last tracked event\n* id.\n*\n* @see https://trpc.io/docs/client/links/retryLink\n*/\nfunction retryLink(opts) {\n\treturn () => {\n\t\treturn (callOpts) => {\n\t\t\treturn observable((observer) => {\n\t\t\t\tlet next$;\n\t\t\t\tlet currentAttempt = 0;\n\t\t\t\tlet disposed = false;\n\t\t\t\tlet callNextTimeout = void 0;\n\t\t\t\tlet lastEventId = void 0;\n\t\t\t\tattempt(1);\n\t\t\t\tfunction opWithLastEventId() {\n\t\t\t\t\tconst op = callOpts.op;\n\t\t\t\t\tif (!lastEventId) return op;\n\t\t\t\t\treturn _objectSpread2(_objectSpread2({}, op), {}, { input: inputWithTrackedEventId(op.input, lastEventId) });\n\t\t\t\t}\n\t\t\t\tfunction attempt(attempts) {\n\t\t\t\t\tif (disposed) return;\n\t\t\t\t\tcurrentAttempt = attempts;\n\t\t\t\t\tconst op = opWithLastEventId();\n\t\t\t\t\tconst subscription = callOpts.next(op).subscribe({\n\t\t\t\t\t\terror(error) {\n\t\t\t\t\t\t\tvar _opts$retryDelayMs, _opts$retryDelayMs2;\n\t\t\t\t\t\t\tconst shouldRetry = opts.retry({\n\t\t\t\t\t\t\t\top,\n\t\t\t\t\t\t\t\tattempts,\n\t\t\t\t\t\t\t\terror\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tif (disposed) return;\n\t\t\t\t\t\t\tif (!shouldRetry) {\n\t\t\t\t\t\t\t\tobserver.error(error);\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconst delayMs = (_opts$retryDelayMs = (_opts$retryDelayMs2 = opts.retryDelayMs) === null || _opts$retryDelayMs2 === void 0 ? void 0 : _opts$retryDelayMs2.call(opts, attempts)) !== null && _opts$retryDelayMs !== void 0 ? _opts$retryDelayMs : 0;\n\t\t\t\t\t\t\tif (disposed) return;\n\t\t\t\t\t\t\tif (delayMs <= 0) {\n\t\t\t\t\t\t\t\tattempt(attempts + 1);\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcallNextTimeout = setTimeout(() => attempt(attempts + 1), delayMs);\n\t\t\t\t\t\t},\n\t\t\t\t\t\tnext(envelope) {\n\t\t\t\t\t\t\tif ((!envelope.result.type || envelope.result.type === \"data\") && envelope.result.id) lastEventId = envelope.result.id;\n\t\t\t\t\t\t\tobserver.next(envelope);\n\t\t\t\t\t\t},\n\t\t\t\t\t\tcomplete() {\n\t\t\t\t\t\t\tobserver.complete();\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t\tif (disposed) subscription.unsubscribe();\n\t\t\t\t\telse if (currentAttempt === attempts) next$ = subscription;\n\t\t\t\t}\n\t\t\t\treturn () => {\n\t\t\t\t\tdisposed = true;\n\t\t\t\t\tnext$.unsubscribe();\n\t\t\t\t\tclearTimeout(callNextTimeout);\n\t\t\t\t};\n\t\t\t});\n\t\t};\n\t};\n}\n// \\0@oxc-project+runtime@0.157.0/helpers/esm/usingCtx.js\nfunction _usingCtx() {\n\tvar r = \"function\" == typeof SuppressedError ? SuppressedError : function(r, e) {\n\t\tvar n = Error();\n\t\treturn n.name = \"SuppressedError\", n.error = r, n.suppressed = e, n;\n\t}, e = {}, n = [];\n\tfunction using(r, e) {\n\t\tif (null != e) {\n\t\t\tif (Object(e) !== e) throw new TypeError(\"using declarations can only be used with objects, functions, null, or undefined.\");\n\t\t\tif (r) var o = e[Symbol.asyncDispose || Symbol[\"for\"](\"Symbol.asyncDispose\")];\n\t\t\tif (void 0 === o && (o = e[Symbol.dispose || Symbol[\"for\"](\"Symbol.dispose\")], r)) var t = o;\n\t\t\tif (\"function\" != typeof o) throw new TypeError(\"Object is not disposable.\");\n\t\t\tt && (o = function o() {\n\t\t\t\ttry {\n\t\t\t\t\tt.call(e);\n\t\t\t\t} catch (r) {\n\t\t\t\t\treturn Promise.reject(r);\n\t\t\t\t}\n\t\t\t}), n.push({\n\t\t\t\tv: e,\n\t\t\t\td: o,\n\t\t\t\ta: r\n\t\t\t});\n\t\t} else r && n.push({\n\t\t\td: e,\n\t\t\ta: r\n\t\t});\n\t\treturn e;\n\t}\n\treturn {\n\t\te,\n\t\tu: using.bind(null, !1),\n\t\ta: using.bind(null, !0),\n\t\td: function d() {\n\t\t\tvar o, t = this.e, s = 0;\n\t\t\tfunction next() {\n\t\t\t\tfor (; o = n.pop();) try {\n\t\t\t\t\tif (!o.a && 1 === s) return s = 0, n.push(o), Promise.resolve().then(next);\n\t\t\t\t\tif (o.d) {\n\t\t\t\t\t\tvar r = o.d.call(o.v);\n\t\t\t\t\t\tif (o.a) return s |= 2, Promise.resolve(r).then(next, err);\n\t\t\t\t\t} else s |= 1;\n\t\t\t\t} catch (r) {\n\t\t\t\t\treturn err(r);\n\t\t\t\t}\n\t\t\t\tif (1 === s) return t !== e ? Promise.reject(t) : Promise.resolve();\n\t\t\t\tif (t !== e) throw t;\n\t\t\t}\n\t\t\tfunction err(n) {\n\t\t\t\treturn t = t !== e ? new r(n, t) : n, next();\n\t\t\t}\n\t\t\treturn next();\n\t\t}\n\t};\n}\n// \\0@oxc-project+runtime@0.157.0/helpers/esm/OverloadYield.js\nfunction _OverloadYield(e, d) {\n\tthis.v = e, this.k = d;\n}\n// \\0@oxc-project+runtime@0.157.0/helpers/esm/awaitAsyncGenerator.js\nfunction _awaitAsyncGenerator(e) {\n\treturn new _OverloadYield(e, 0);\n}\n// \\0@oxc-project+runtime@0.157.0/helpers/esm/wrapAsyncGenerator.js\nfunction _wrapAsyncGenerator(e) {\n\treturn function() {\n\t\treturn new AsyncGenerator(e.apply(this, arguments));\n\t};\n}\nfunction AsyncGenerator(e) {\n\tvar t, n;\n\tfunction resume(t, n) {\n\t\ttry {\n\t\t\tvar r = e[t](n), o = r.value, u = o instanceof _OverloadYield;\n\t\t\tPromise.resolve(u ? o.v : o).then(function(n) {\n\t\t\t\tif (u) {\n\t\t\t\t\tvar i = \"return\" === t && o.k ? t : \"next\";\n\t\t\t\t\tif (!o.k || n.done) return resume(i, n);\n\t\t\t\t\tn = e[i](n).value;\n\t\t\t\t}\n\t\t\t\tsettle(!!r.done, n);\n\t\t\t}, function(e) {\n\t\t\t\tresume(\"throw\", e);\n\t\t\t});\n\t\t} catch (e) {\n\t\t\tsettle(2, e);\n\t\t}\n\t}\n\tfunction settle(e, r) {\n\t\t2 === e ? t.reject(r) : t.resolve({\n\t\t\tvalue: r,\n\t\t\tdone: e\n\t\t}), (t = t.next) ? resume(t.key, t.arg) : n = null;\n\t}\n\tthis._invoke = function(e, r) {\n\t\treturn new Promise(function(o, u) {\n\t\t\tvar i = {\n\t\t\t\tkey: e,\n\t\t\t\targ: r,\n\t\t\t\tresolve: o,\n\t\t\t\treject: u,\n\t\t\t\tnext: null\n\t\t\t};\n\t\t\tn ? n = n.next = i : (t = n = i, resume(e, r));\n\t\t});\n\t}, \"function\" != typeof e[\"return\"] && (this[\"return\"] = void 0);\n}\nAsyncGenerator.prototype[\"function\" == typeof Symbol && Symbol.asyncIterator || \"@@asyncIterator\"] = function() {\n\treturn this;\n}, AsyncGenerator.prototype.next = function(e) {\n\treturn this._invoke(\"next\", e);\n}, AsyncGenerator.prototype[\"throw\"] = function(e) {\n\treturn this._invoke(\"throw\", e);\n}, AsyncGenerator.prototype[\"return\"] = function(e) {\n\treturn this._invoke(\"return\", e);\n};\n// src/links/localLink.ts\n/**\n* A terminating link that calls procedures on a router in the same process,\n* without HTTP.\n*\n* @see https://trpc.io/docs/client/links/localLink\n*/\nfunction localLink(opts) {\n\tconst transformer = getTransformer(opts.transformer);\n\tconst transformChunk = (chunk) => {\n\t\tif (opts.transformer) return chunk;\n\t\tif (chunk === void 0) return chunk;\n\t\tconst serialized = JSON.stringify(transformer.input.serialize(chunk));\n\t\treturn JSON.parse(transformer.output.deserialize(serialized));\n\t};\n\treturn () => ({ op }) => observable((observer) => {\n\t\tlet ctx = void 0;\n\t\tconst ac = new AbortController();\n\t\tconst signal = raceAbortSignals(op.signal, ac.signal);\n\t\tconst signalPromise = abortSignalToPromise(signal);\n\t\tsignalPromise.catch(() => {});\n\t\tlet input = op.input;\n\t\tasync function runProcedure(newInput) {\n\t\t\tinput = newInput;\n\t\t\tthrowIfAborted(signal);\n\t\t\tctx = await opts.createContext({ info: { signal } });\n\t\t\tthrowIfAborted(signal);\n\t\t\treturn callProcedure({\n\t\t\t\trouter: opts.router,\n\t\t\t\tpath: op.path,\n\t\t\t\tgetRawInput: async () => newInput,\n\t\t\t\tctx,\n\t\t\t\ttype: op.type,\n\t\t\t\tsignal,\n\t\t\t\tbatchIndex: 0\n\t\t\t});\n\t\t}\n\t\tfunction onErrorCallback(cause) {\n\t\t\tvar _opts$onError;\n\t\t\tif (isAbortError(cause)) return;\n\t\t\t(_opts$onError = opts.onError) === null || _opts$onError === void 0 || _opts$onError.call(opts, {\n\t\t\t\terror: getTRPCErrorFromUnknown(cause),\n\t\t\t\ttype: op.type,\n\t\t\t\tpath: op.path,\n\t\t\t\tinput,\n\t\t\t\tctx\n\t\t\t});\n\t\t}\n\t\tfunction coerceToTRPCClientError(cause) {\n\t\t\tif (isTRPCClientError(cause)) return cause;\n\t\t\tconst error = getTRPCErrorFromUnknown(cause);\n\t\t\tconst shape = getTRPCErrorShape({\n\t\t\t\tconfig: opts.router._def._config,\n\t\t\t\tctx,\n\t\t\t\terror,\n\t\t\t\tinput,\n\t\t\t\tpath: op.path,\n\t\t\t\ttype: op.type\n\t\t\t});\n\t\t\treturn TRPCClientError.from({ error: transformChunk(shape) }, { cause: cause instanceof Error ? cause : void 0 });\n\t\t}\n\t\trun(async () => {\n\t\t\tswitch (op.type) {\n\t\t\t\tcase \"query\":\n\t\t\t\tcase \"mutation\": {\n\t\t\t\t\tconst result = await Promise.race([runProcedure(op.input), signalPromise]);\n\t\t\t\t\tif (!isAsyncIterable(result)) {\n\t\t\t\t\t\tobserver.next({ result: { data: transformChunk(result) } });\n\t\t\t\t\t\tobserver.complete();\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tobserver.next({ result: { data: _wrapAsyncGenerator(function* () {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tvar _usingCtx$1 = _usingCtx();\n\t\t\t\t\t\t\tconst iterator = _usingCtx$1.a(iteratorResource(result));\n\t\t\t\t\t\t\t_usingCtx$1.u(makeResource({}, () => {\n\t\t\t\t\t\t\t\tobserver.complete();\n\t\t\t\t\t\t\t}));\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\twhile (true) {\n\t\t\t\t\t\t\t\t\tconst res = yield _awaitAsyncGenerator(Promise.race([iterator.next(), signalPromise]));\n\t\t\t\t\t\t\t\t\tif (res.done) return transformChunk(res.value);\n\t\t\t\t\t\t\t\t\tyield transformChunk(res.value);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} catch (cause) {\n\t\t\t\t\t\t\t\tonErrorCallback(cause);\n\t\t\t\t\t\t\t\tthrow coerceToTRPCClientError(cause);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} catch (_) {\n\t\t\t\t\t\t\t_usingCtx$1.e = _;\n\t\t\t\t\t\t} finally {\n\t\t\t\t\t\t\tyield _awaitAsyncGenerator(_usingCtx$1.d());\n\t\t\t\t\t\t}\n\t\t\t\t\t})() } });\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"subscription\": try {\n\t\t\t\t\tvar _usingCtx3 = _usingCtx();\n\t\t\t\t\tconst connectionState = behaviorSubject({\n\t\t\t\t\t\ttype: \"state\",\n\t\t\t\t\t\tstate: \"connecting\",\n\t\t\t\t\t\terror: null\n\t\t\t\t\t});\n\t\t\t\t\tconst connectionSub = connectionState.subscribe({ next(state) {\n\t\t\t\t\t\tobserver.next({ result: state });\n\t\t\t\t\t} });\n\t\t\t\t\tlet lastEventId = void 0;\n\t\t\t\t\t_usingCtx3.u(makeResource({}, async () => {\n\t\t\t\t\t\tconnectionState.next({\n\t\t\t\t\t\t\ttype: \"state\",\n\t\t\t\t\t\t\tstate: \"idle\",\n\t\t\t\t\t\t\terror: null\n\t\t\t\t\t\t});\n\t\t\t\t\t\tconnectionSub.unsubscribe();\n\t\t\t\t\t}));\n\t\t\t\t\tawait run(async () => {\n\t\t\t\t\t\twhile (true) try {\n\t\t\t\t\t\t\tvar _usingCtx4 = _usingCtx();\n\t\t\t\t\t\t\tconst result = await runProcedure(inputWithTrackedEventId(op.input, lastEventId));\n\t\t\t\t\t\t\tif (!isAsyncIterable(result)) throw new Error(\"Expected an async iterable\");\n\t\t\t\t\t\t\tconst iterator = _usingCtx4.a(iteratorResource(result));\n\t\t\t\t\t\t\tobserver.next({ result: { type: \"started\" } });\n\t\t\t\t\t\t\tconnectionState.next({\n\t\t\t\t\t\t\t\ttype: \"state\",\n\t\t\t\t\t\t\t\tstate: \"pending\",\n\t\t\t\t\t\t\t\terror: null\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\twhile (true) {\n\t\t\t\t\t\t\t\tlet res;\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\tres = await Promise.race([iterator.next(), signalPromise]);\n\t\t\t\t\t\t\t\t} catch (cause) {\n\t\t\t\t\t\t\t\t\tif (isAbortError(cause)) return;\n\t\t\t\t\t\t\t\t\tconst error = getTRPCErrorFromUnknown(cause);\n\t\t\t\t\t\t\t\t\tif (!retryableRpcCodes.includes(TRPC_ERROR_CODES_BY_KEY[error.code])) throw coerceToTRPCClientError(error);\n\t\t\t\t\t\t\t\t\tonErrorCallback(error);\n\t\t\t\t\t\t\t\t\tconnectionState.next({\n\t\t\t\t\t\t\t\t\t\ttype: \"state\",\n\t\t\t\t\t\t\t\t\t\tstate: \"connecting\",\n\t\t\t\t\t\t\t\t\t\terror: coerceToTRPCClientError(error)\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (res.done) return;\n\t\t\t\t\t\t\t\tlet chunk;\n\t\t\t\t\t\t\t\tif (isTrackedEnvelope(res.value)) {\n\t\t\t\t\t\t\t\t\tlastEventId = res.value[0];\n\t\t\t\t\t\t\t\t\tchunk = {\n\t\t\t\t\t\t\t\t\t\tid: res.value[0],\n\t\t\t\t\t\t\t\t\t\tdata: {\n\t\t\t\t\t\t\t\t\t\t\tid: res.value[0],\n\t\t\t\t\t\t\t\t\t\t\tdata: res.value[1]\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\t} else chunk = { data: res.value };\n\t\t\t\t\t\t\t\tobserver.next({ result: _objectSpread2(_objectSpread2({}, chunk), {}, { data: transformChunk(chunk.data) }) });\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} catch (_) {\n\t\t\t\t\t\t\t_usingCtx4.e = _;\n\t\t\t\t\t\t} finally {\n\t\t\t\t\t\t\tawait _usingCtx4.d();\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t\tobserver.complete();\n\t\t\t\t\tbreak;\n\t\t\t\t} catch (_) {\n\t\t\t\t\t_usingCtx3.e = _;\n\t\t\t\t} finally {\n\t\t\t\t\t_usingCtx3.d();\n\t\t\t\t}\n\t\t\t}\n\t\t}).catch((cause) => {\n\t\t\tonErrorCallback(cause);\n\t\t\tobserver.error(coerceToTRPCClientError(cause));\n\t\t});\n\t\treturn () => {\n\t\t\tac.abort();\n\t\t};\n\t});\n}\n/**\n* @deprecated Use {@link localLink} instead.\n* @function\n*/\nconst unstable_localLink = localLink;\n/**\n* @deprecated Use {@link localLink} instead. This alias will be removed in a\n* future major release.\n*/\nconst experimental_localLink = localLink;\n// src/safe.ts\n/**\n* Awaits a client `.query()` or `.mutate()` call without throwing, and\n* returns a `[data, error]` pair typed with the procedure's error shape.\n*\n* @example\n* ```ts\n* const [post, error] = await safe(client.post.byId.query({ id }));\n* if (error) {\n* console.error(error);\n* }\n*\n* const id = post.id;\n* ```\n* @see https://trpc.io/docs/client/vanilla/error-handling#errors-as-values-with-safe\n*/\nasync function safe(promise) {\n\ttry {\n\t\treturn [await promise, void 0];\n\t} catch (cause) {\n\t\treturn [void 0, cause];\n\t}\n}\nexport { TRPCClientError, TRPCUntypedClient, clientCallTypeToProcedureType, createTRPCClient, createTRPCClient as createTRPCProxyClient, createTRPCClientProxy, createTRPCUntypedClient, createWSClient, experimental_localLink, getFetch, getUntypedClient, httpBatchLink, httpBatchStreamLink, httpLink, httpSubscriptionLink, isFormData, isNonJsonSerializable, isOctetType, isTRPCClientError, jsonEncoder, localLink, loggerLink, retryLink, safe, splitLink, unstable_httpBatchStreamLink, unstable_httpSubscriptionLink, unstable_localLink, wsLink };\n\n//# sourceMappingURL=index.mjs.map", "import type { AppRouter } from \"@go-labs/budget-builder-api\";\nimport {\n\tsanitizeValueForTrace,\n\tshouldLogCliActions,\n} from \"@go-labs-sg/bb/cli-trace\";\nimport {\n\tDEFAULT_BUDGET_BUILDER_API_BASE_URL,\n\tnormalizeApiBaseUrl,\n} from \"@go-labs-sg/bb/config\";\nimport {\n\tcreateTRPCProxyClient,\n\thttpBatchLink,\n\tloggerLink,\n\ttype TRPCClient,\n} from \"@trpc/client\";\nimport SuperJSON from \"superjson\";\n\nexport {\n\tDEFAULT_BUDGET_BUILDER_API_BASE_URL,\n\tnormalizeApiBaseUrl,\n} from \"@go-labs-sg/bb/config\";\n\nexport let BUDGET_BUILDER_API_BASE_URL = DEFAULT_BUDGET_BUILDER_API_BASE_URL;\n\nlet interactiveAccessToken: string | undefined;\n\nfunction getAuthHeader(): string | undefined {\n\tconst key = process.env.BB_API_KEY;\n\tif (key?.trim()) return `Bearer ${key.trim()}`;\n\treturn interactiveAccessToken\n\t\t? `Bearer ${interactiveAccessToken}`\n\t\t: undefined;\n}\n\nconst containsRawApiKey = (\n\tvalue: unknown,\n\tseen = new WeakSet<object>(),\n): boolean => {\n\tif (typeof value !== \"object\" || value === null) return false;\n\tif (seen.has(value)) return false;\n\tseen.add(value);\n\n\treturn Object.entries(value).some(\n\t\t([key, nestedValue]) =>\n\t\t\t(key.toLowerCase() === \"apikey\" && typeof nestedValue === \"string\") ||\n\t\t\tcontainsRawApiKey(nestedValue, seen),\n\t);\n};\n\nexport type BudgetBuilderClient = TRPCClient<AppRouter>;\n\nexport const createBudgetBuilderClient = (\n\tapiBaseUrl = BUDGET_BUILDER_API_BASE_URL,\n): BudgetBuilderClient =>\n\tcreateTRPCProxyClient<AppRouter>({\n\t\tlinks: [\n\t\t\tloggerLink({\n\t\t\t\tenabled: (opts) =>\n\t\t\t\t\tshouldLogCliActions() &&\n\t\t\t\t\t!(opts.direction === \"down\" && containsRawApiKey(opts.result)),\n\t\t\t\tcolorMode: \"ansi\",\n\t\t\t\twithContext: false,\n\t\t\t\t// tRPC defaults use console.log for requests; stderr keeps stdout JSON-safe for pipes.\n\t\t\t\tconsole: {\n\t\t\t\t\tlog: (...args: unknown[]) =>\n\t\t\t\t\t\tconsole.error(...args.map((arg) => sanitizeValueForTrace(arg))),\n\t\t\t\t\terror: (...args: unknown[]) =>\n\t\t\t\t\t\tconsole.error(...args.map((arg) => sanitizeValueForTrace(arg))),\n\t\t\t\t},\n\t\t\t}),\n\t\t\thttpBatchLink({\n\t\t\t\turl: `${apiBaseUrl}/api/trpc`,\n\t\t\t\ttransformer: SuperJSON,\n\t\t\t\theaders: () => {\n\t\t\t\t\tconst headers: Record<string, string> = {\n\t\t\t\t\t\t\"x-trpc-source\": \"bb-cli\",\n\t\t\t\t\t};\n\t\t\t\t\tconst auth = getAuthHeader();\n\t\t\t\t\tif (auth) headers.Authorization = auth;\n\t\t\t\t\treturn headers;\n\t\t\t\t},\n\t\t\t}),\n\t\t],\n\t});\n\nlet activeClient = createBudgetBuilderClient();\n\nexport const configureBudgetBuilderApiBaseUrl = (value: string): string => {\n\tconst normalized = normalizeApiBaseUrl(value);\n\tBUDGET_BUILDER_API_BASE_URL = normalized;\n\tactiveClient = createBudgetBuilderClient(normalized);\n\treturn normalized;\n};\n\nexport const configureBudgetBuilderAccessToken = (\n\taccessToken: string | undefined,\n): void => {\n\tinteractiveAccessToken = accessToken;\n\tactiveClient = createBudgetBuilderClient(BUDGET_BUILDER_API_BASE_URL);\n};\n\n/**\n * Stable facade used by command handlers. Tests can replace the transport without\n * teaching commands about tRPC or process-wide authentication.\n */\nexport const api = new Proxy({} as BudgetBuilderClient, {\n\tget: (_target, property, receiver) =>\n\t\tReflect.get(activeClient, property, receiver),\n});\n\nexport const setBudgetBuilderClientForTesting = (\n\tclient: BudgetBuilderClient,\n): (() => void) => {\n\tconst previous = activeClient;\n\tactiveClient = client;\n\treturn () => {\n\t\tactiveClient = previous;\n\t};\n};\n", "/**\n * Runtime Prisma enum values the CLI needs. Mirrors\n * `packages/budget-builder/db/src/generated/prisma/enums.ts` — keep in sync when the schema changes.\n */\nexport const EstimationMode = {\n\tMICRO: \"MICRO\",\n\tMANPOWER_SPECIFIED: \"MANPOWER_SPECIFIED\",\n} as const;\n\nexport type EstimationMode =\n\t(typeof EstimationMode)[keyof typeof EstimationMode];\n\nexport const ProjectStatus = {\n\tPITCH: \"PITCH\",\n\tWON: \"WON\",\n\tCOMPLETED: \"COMPLETED\",\n\tRECONCILED: \"RECONCILED\",\n\tLOST: \"LOST\",\n} as const;\n\nexport type ProjectStatus = (typeof ProjectStatus)[keyof typeof ProjectStatus];\n\nexport const SupplierQuotationStatus = {\n\tDRAFT: \"DRAFT\",\n\tPENDING_APPROVAL: \"PENDING_APPROVAL\",\n\tAPPROVED: \"APPROVED\",\n\tREJECTED: \"REJECTED\",\n\tSUPERSEDED: \"SUPERSEDED\",\n} as const;\n\nexport type SupplierQuotationStatus =\n\t(typeof SupplierQuotationStatus)[keyof typeof SupplierQuotationStatus];\n\nexport const CustomerInvoiceBatchStatus = {\n\tCREATING: \"CREATING\",\n\tPENDING_APPROVAL: \"PENDING_APPROVAL\",\n\tAPPROVED: \"APPROVED\",\n\tREJECTED_VOIDED: \"REJECTED_VOIDED\",\n\tEXPIRED_VOIDED: \"EXPIRED_VOIDED\",\n\tPARTIAL_QBO_FAILURE: \"PARTIAL_QBO_FAILURE\",\n} as const;\n\nexport type CustomerInvoiceBatchStatus =\n\t(typeof CustomerInvoiceBatchStatus)[keyof typeof CustomerInvoiceBatchStatus];\n\nexport const BudgetStatus = {\n\tDRAFT: \"DRAFT\",\n\tPENDING_APPROVAL: \"PENDING_APPROVAL\",\n\tAPPROVED: \"APPROVED\",\n\tREJECTED: \"REJECTED\",\n\tESTIMATE_CREATED: \"ESTIMATE_CREATED\",\n\tESTIMATE_SENT: \"ESTIMATE_SENT\",\n\tESTIMATE_ACCEPTED: \"ESTIMATE_ACCEPTED\",\n\tESTIMATE_REJECTED: \"ESTIMATE_REJECTED\",\n\tESTIMATE_CLOSED: \"ESTIMATE_CLOSED\",\n} as const;\n\nexport type BudgetStatus = (typeof BudgetStatus)[keyof typeof BudgetStatus];\n\nexport const ApprovalStatus = {\n\tPENDING_APPROVAL: \"PENDING_APPROVAL\",\n\tAPPROVED: \"APPROVED\",\n\tREJECTED: \"REJECTED\",\n\tSUPERSEDED: \"SUPERSEDED\",\n} as const;\n\nexport type ApprovalStatus =\n\t(typeof ApprovalStatus)[keyof typeof ApprovalStatus];\n\nexport const ApprovalType = {\n\tBUDGET: \"BUDGET\",\n\tSUPPLIER: \"SUPPLIER\",\n\tBILL: \"BILL\",\n\tCUSTOMER_INVOICE: \"CUSTOMER_INVOICE\",\n\tQUOTATION: \"QUOTATION\",\n} as const;\n\nexport type ApprovalType = (typeof ApprovalType)[keyof typeof ApprovalType];\n\nexport const UserRole = {\n\tUSER: \"USER\",\n\tLEAD: \"LEAD\",\n\tADMIN: \"ADMIN\",\n\tINSIDE_SALES: \"INSIDE_SALES\",\n\tACCOUNTING_TEAM: \"ACCOUNTING_TEAM\",\n} as const;\n\nexport type UserRole = (typeof UserRole)[keyof typeof UserRole];\n\nexport const ErrorSeverity = {\n\tLOW: \"LOW\",\n\tMEDIUM: \"MEDIUM\",\n\tHIGH: \"HIGH\",\n\tCRITICAL: \"CRITICAL\",\n} as const;\n\nexport type ErrorSeverity = (typeof ErrorSeverity)[keyof typeof ErrorSeverity];\n\nexport const ErrorStatus = {\n\tUNRESOLVED: \"UNRESOLVED\",\n\tINVESTIGATING: \"INVESTIGATING\",\n\tRESOLVED: \"RESOLVED\",\n\tIGNORED: \"IGNORED\",\n} as const;\n\nexport type ErrorStatus = (typeof ErrorStatus)[keyof typeof ErrorStatus];\n\nexport const BillStatus = {\n\tDRAFT: \"DRAFT\",\n\tPENDING_APPROVAL: \"PENDING_APPROVAL\",\n\tCHECKED: \"CHECKED\",\n\tAPPROVED: \"APPROVED\",\n\tPAID: \"PAID\",\n\tREJECTED: \"REJECTED\",\n} as const;\n\nexport type BillStatus = (typeof BillStatus)[keyof typeof BillStatus];\n\nexport const BillVerificationStatus = {\n\tPENDING: \"PENDING\",\n\tPASS: \"PASS\",\n\tFAIL: \"FAIL\",\n\tMANUAL_REVIEW: \"MANUAL_REVIEW\",\n} as const;\nexport type BillVerificationStatus =\n\t(typeof BillVerificationStatus)[keyof typeof BillVerificationStatus];\n\nexport const SupplierQuotationFileRole = {\n\tORIGINAL: \"ORIGINAL\",\n\tSTAFF_SIGNED: \"STAFF_SIGNED\",\n\tFINAL_SIGNED: \"FINAL_SIGNED\",\n} as const;\nexport type SupplierQuotationFileRole =\n\t(typeof SupplierQuotationFileRole)[keyof typeof SupplierQuotationFileRole];\n\nexport const InboundProcessingMode = {\n\tCOLLECT_ONLY: \"COLLECT_ONLY\",\n\tSHADOW: \"SHADOW\",\n\tACTIVE: \"ACTIVE\",\n} as const;\nexport type InboundProcessingMode =\n\t(typeof InboundProcessingMode)[keyof typeof InboundProcessingMode];\n\nexport const AttachmentType = {\n\tGLOBAL_ATTACHMENT: \"GLOBAL_ATTACHMENT\",\n\tBUDGET: \"BUDGET\",\n\tBUDGET_WIN_PROOF: \"BUDGET_WIN_PROOF\",\n\tITEM: \"ITEM\",\n\tSUPPLIER: \"SUPPLIER\",\n\tBILL: \"BILL\",\n\tBILL_PAYMENT_PROOF: \"BILL_PAYMENT_PROOF\",\n\tQUOTATION: \"QUOTATION\",\n} as const;\nexport type AttachmentType =\n\t(typeof AttachmentType)[keyof typeof AttachmentType];\n", "import { randomUUID } from \"node:crypto\";\nimport { readFile, writeFile } from \"node:fs/promises\";\nimport { basename } from \"node:path\";\nimport { createInterface } from \"node:readline/promises\";\nimport type { RouterInputs, RouterOutputs } from \"@go-labs/budget-builder-api\";\nimport {\n\tBudgetRole,\n\tDeals,\n\tExtendedApprovalStatus,\n\tExtendedApprovalType,\n\tExtendedBudgetStatus,\n\tTimeFrame,\n} from \"@go-labs/budget-builder-utils/filter-enums\";\nimport { api } from \"@go-labs-sg/bb/api-client\";\nimport { budgetCreateUncertainError } from \"@go-labs-sg/bb/budget-create-outcome\";\nimport { invoiceSplitSetupNextAction } from \"@go-labs-sg/bb/commands/invoice-splits\";\nimport {\n\ttype ApprovalCliFilter,\n\ttype BudgetStatusUpdate,\n\tbillStatusesForApi,\n} from \"@go-labs-sg/bb/parse-cli-enums\";\nimport {\n\tparseBudgetDiscountPayload,\n\tparseCompanyUpdatePayload,\n\tparseContactCreatePayload,\n\tparseContactUpdatePayload,\n\tparseCreateBillPayload,\n\tparseCreateBudgetPayload,\n\tparseCreateCustomerInvoicePayload,\n\tparseCreateQuotationPayload,\n\tparseItemCreatePayload,\n\tparseItemUpdatePayload,\n\tparseLinkBillQuotationsPayload,\n\tparseQuickBooksName,\n\tparseSendCustomerInvoiceToContactPersonPayload,\n\tparseSendEstimateToContactPersonPayload,\n\tparseSupplierCreatePayload,\n\tparseSupplierUpdatePayload,\n\tparseUpdateBillPayload,\n\tparseUpdateBillPaymentEvidencePayload,\n\tparseUpdateBudgetCommissionPayload,\n\tparseUpdateBudgetPayload,\n\tparseUpdateProjectPayload,\n\tparseUpdateQuotationPayload,\n\tparseValidateBillSelectionPayload,\n} from \"@go-labs-sg/bb/parse-mutation-payload\";\nimport {\n\tApprovalStatus,\n\tApprovalType,\n\tAttachmentType,\n\tBillStatus,\n\tBudgetStatus,\n\tProjectStatus,\n} from \"@go-labs-sg/bb/prisma-enums\";\nimport { createRichTextFromPlainText } from \"@go-labs-sg/bb/rich-text\";\nimport {\n\tCliRuntimeError,\n\tconfirmCurrentCommand,\n\temitCommandResult,\n\tgetActiveCliSession,\n\tnormalizeCliError,\n} from \"@go-labs-sg/bb/runtime/index\";\nimport { contentType } from \"mime-types\";\n\ntype NotificationPage = RouterOutputs[\"budget\"][\"getNotificationPage\"];\ntype ProjectInvoiceSettingsInput = NonNullable<\n\tRouterInputs[\"budget\"][\"updateBudgetStatus\"][\"projectInvoiceSettings\"]\n>;\ntype NotificationRow = NotificationPage[\"notifications\"][number];\ntype PendingRequestRow = NotificationRow & { notificationType: \"request\" };\ntype AsanaSearchTask = RouterOutputs[\"asana\"][\"searchTasks\"][\"data\"][number];\ntype AsanaTaskDetails = RouterOutputs[\"asana\"][\"getTaskById\"][\"data\"];\ntype AsanaDealSlackChannel = RouterOutputs[\"asana\"][\"getDealSlackChannel\"];\ntype ResolvedAsanaDealSlackChannel = Extract<\n\tAsanaDealSlackChannel,\n\t{ status: \"resolved\" }\n>;\n\nconst BUDGET = ApprovalType.BUDGET satisfies PendingRequestRow[\"type\"];\nconst BILL = ApprovalType.BILL satisfies PendingRequestRow[\"type\"];\nconst SUPPLIER = ApprovalType.SUPPLIER satisfies PendingRequestRow[\"type\"];\nconst QUOTATION = ApprovalType.QUOTATION satisfies PendingRequestRow[\"type\"];\nconst CUSTOMER_INVOICE =\n\tApprovalType.CUSTOMER_INVOICE satisfies PendingRequestRow[\"type\"];\nconst ASANA_WON_LOST_SECTION_GIDS = new Set([\n\t\"1211678338364908\",\n\t\"1211678338364907\",\n]);\nconst MAX_ASANA_LEAD_CANDIDATES = 5;\nconst ASANA_SEARCH_DETAIL_LIMIT = 15;\nconst NOTIFICATION_PAGE_LIMIT = 50;\n\nconst getAllNotifications = async (): Promise<NotificationRow[]> => {\n\tconst user = await api.user.getCurrentUser.query();\n\tconst notifications: NotificationRow[] = [];\n\tlet cursor: RouterInputs[\"budget\"][\"getNotificationPage\"][\"cursor\"];\n\n\tdo {\n\t\tconst page = await api.budget.getNotificationPage.query({\n\t\t\tcacheUserId: user.id,\n\t\t\tcursor,\n\t\t\tlimit: NOTIFICATION_PAGE_LIMIT,\n\t\t});\n\t\tnotifications.push(...page.notifications);\n\t\tcursor = page.nextCursor;\n\t} while (cursor);\n\n\treturn notifications;\n};\n\ninterface AsanaSectionSummary {\n\tgid?: string;\n\tname?: string;\n}\n\ninterface AsanaLeadCandidate {\n\tgid: string;\n\tname: string;\n\tmodifiedAt?: string;\n\tcreatedAt?: string;\n\tsections: AsanaSectionSummary[];\n}\n\ninterface ApprovalEmailDelivery {\n\tqueuedCount: number;\n\tsentCount: number;\n\tskippedCount: number;\n\tmessage: string;\n\toperationIds: string[];\n}\n\ninterface ApprovalEmailDeliveryReport {\n\tqueued: boolean;\n\tsent: boolean;\n\tcount: number;\n\tqueuedCount: number;\n\tsentCount: number;\n\tskippedCount: number;\n\toperationIds?: string[];\n\tmessage?: string;\n\terror?: string;\n}\n\nconst createApprovalEmailDeliveryReport = (\n\tdelivery: ApprovalEmailDelivery | null | undefined,\n): ApprovalEmailDeliveryReport => {\n\tif (!delivery) {\n\t\treturn {\n\t\t\tqueued: false,\n\t\t\tsent: false,\n\t\t\tcount: 0,\n\t\t\tqueuedCount: 0,\n\t\t\tsentCount: 0,\n\t\t\tskippedCount: 0,\n\t\t\terror: \"No approval email delivery was queued\",\n\t\t};\n\t}\n\n\tconst { queuedCount, sentCount, skippedCount, message, operationIds } =\n\t\tdelivery;\n\treturn {\n\t\tqueued: queuedCount > 0,\n\t\tsent: false,\n\t\tcount: queuedCount,\n\t\tqueuedCount,\n\t\tsentCount,\n\t\tskippedCount,\n\t\toperationIds,\n\t\tmessage,\n\t};\n};\n\nconst createApprovalEmailDeliveryFailure = (\n\terror: string,\n): ApprovalEmailDeliveryReport => ({\n\tqueued: false,\n\tsent: false,\n\tcount: 0,\n\tqueuedCount: 0,\n\tsentCount: 0,\n\tskippedCount: 0,\n\terror,\n});\n\nfunction isPendingRequest(n: NotificationRow): n is PendingRequestRow {\n\treturn (\n\t\tn.notificationType === \"request\" &&\n\t\tn.status === ApprovalStatus.PENDING_APPROVAL\n\t);\n}\n\nconst out = (data: unknown) => {\n\temitCommandResult(data);\n};\n\ntype BillAttachmentUploadType =\n\t| typeof AttachmentType.BILL\n\t| typeof AttachmentType.BILL_PAYMENT_PROOF;\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n\ttypeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst stringField = (\n\trecord: Record<string, unknown>,\n\tkey: string,\n): string | undefined => {\n\tconst value = record[key];\n\treturn typeof value === \"string\" && value.trim() ? value.trim() : undefined;\n};\n\nconst asanaSectionsForTask = (task: unknown): AsanaSectionSummary[] => {\n\tif (!isRecord(task) || !Array.isArray(task.memberships)) return [];\n\n\treturn task.memberships.flatMap((membership) => {\n\t\tif (!isRecord(membership) || !isRecord(membership.section)) return [];\n\n\t\treturn [\n\t\t\t{\n\t\t\t\tgid: stringField(membership.section, \"gid\"),\n\t\t\t\tname: stringField(membership.section, \"name\"),\n\t\t\t},\n\t\t];\n\t});\n};\n\nconst isWonOrLostAsanaTask = (task: unknown): boolean =>\n\tasanaSectionsForTask(task).some((section) => {\n\t\tif (section.gid && ASANA_WON_LOST_SECTION_GIDS.has(section.gid)) {\n\t\t\treturn true;\n\t\t}\n\n\t\tconst name = section.name?.trim().toLowerCase();\n\t\treturn Boolean(name && /\\b(won|lost)\\b/.test(name));\n\t});\n\nconst asanaCandidateFromTask = (\n\ttask: AsanaSearchTask,\n\tdetails?: AsanaTaskDetails,\n): AsanaLeadCandidate | null => {\n\tconst source = details ?? task;\n\tconst sourceRecord = isRecord(source) ? source : undefined;\n\tconst gid =\n\t\t(sourceRecord ? stringField(sourceRecord, \"gid\") : undefined) ?? task.gid;\n\tconst name =\n\t\t(sourceRecord ? stringField(sourceRecord, \"name\") : undefined) ??\n\t\ttask.name ??\n\t\tgid;\n\n\tif (!gid || isWonOrLostAsanaTask(source)) return null;\n\n\treturn {\n\t\tgid,\n\t\tname,\n\t\tmodifiedAt:\n\t\t\t(sourceRecord ? stringField(sourceRecord, \"modified_at\") : undefined) ??\n\t\t\ttask.modified_at,\n\t\tcreatedAt:\n\t\t\t(sourceRecord ? stringField(sourceRecord, \"created_at\") : undefined) ??\n\t\t\ttask.created_at,\n\t\tsections: asanaSectionsForTask(source),\n\t};\n};\n\nconst uniqueSearchQueries = (\n\t...queries: Array<string | undefined>\n): string[] => {\n\tconst seen = new Set<string>();\n\tconst unique: string[] = [];\n\n\tfor (const query of queries) {\n\t\tconst normalized = query?.trim() ?? \"\";\n\t\tif (!normalized) continue;\n\n\t\tconst key = normalized.toLowerCase();\n\t\tif (seen.has(key)) continue;\n\t\tseen.add(key);\n\t\tunique.push(normalized);\n\t}\n\n\treturn unique;\n};\n\nconst searchOpenAsanaLeadCandidates = async ({\n\tprojectName,\n\tsearchQuery,\n}: {\n\tprojectName: string;\n\tsearchQuery?: string;\n}): Promise<AsanaLeadCandidate[]> => {\n\tconst queries = uniqueSearchQueries(projectName, searchQuery);\n\tconst candidates: AsanaLeadCandidate[] = [];\n\tconst seenTaskIds = new Set<string>();\n\n\tfor (const query of queries) {\n\t\tconst results = await api.asana.searchTasks.query({ query });\n\t\tconst tasks = results.data.slice(0, ASANA_SEARCH_DETAIL_LIMIT);\n\n\t\tconst detailsByTaskId = new Map<string, AsanaTaskDetails>();\n\t\tawait Promise.all(\n\t\t\ttasks.map(async (task) => {\n\t\t\t\tif (!task.gid) return;\n\t\t\t\ttry {\n\t\t\t\t\tconst details = await api.asana.getTaskById.query({ id: task.gid });\n\t\t\t\t\tdetailsByTaskId.set(task.gid, details.data);\n\t\t\t\t} catch {\n\t\t\t\t\t// Keep the compact search result if detail lookup fails for one task.\n\t\t\t\t}\n\t\t\t}),\n\t\t);\n\n\t\tfor (const task of tasks) {\n\t\t\tif (!task.gid || seenTaskIds.has(task.gid)) continue;\n\t\t\tconst candidate = asanaCandidateFromTask(\n\t\t\t\ttask,\n\t\t\t\tdetailsByTaskId.get(task.gid),\n\t\t\t);\n\t\t\tif (!candidate) continue;\n\n\t\t\tseenTaskIds.add(candidate.gid);\n\t\t\tcandidates.push(candidate);\n\t\t\tif (candidates.length >= MAX_ASANA_LEAD_CANDIDATES) return candidates;\n\t\t}\n\t}\n\n\treturn candidates;\n};\n\nconst formatAsanaCandidateMetadata = (\n\tcandidate: AsanaLeadCandidate,\n): string => {\n\tconst sectionText =\n\t\tcandidate.sections\n\t\t\t.map((section) => section.name ?? section.gid)\n\t\t\t.filter(Boolean)\n\t\t\t.join(\", \") || \"stage unavailable\";\n\tconst dateText = candidate.modifiedAt\n\t\t? `modified ${new Date(candidate.modifiedAt).toISOString()}`\n\t\t: candidate.createdAt\n\t\t\t? `created ${new Date(candidate.createdAt).toISOString()}`\n\t\t\t: \"date unavailable\";\n\n\treturn `${sectionText}; ${dateText}; ${candidate.gid}`;\n};\n\nconst promptForAsanaLeadCandidate = async (\n\tcandidates: AsanaLeadCandidate[],\n): Promise<AsanaLeadCandidate> => {\n\tif (candidates.length === 0) {\n\t\tthrow new Error(\n\t\t\t\"create-project requires an existing Asana deal task in the Deals project; none matched. For a new direct client, create the deal task using the website form first, then pass --asanaTaskId or --asanaSearch. The Slack channel comes from that task.\",\n\t\t);\n\t}\n\n\tif (!process.stdin.isTTY || !process.stderr.isTTY) {\n\t\tthrow new Error(\n\t\t\t\"create-project requires an existing Asana deal task: pass --asanaTaskId in non-interactive runs. Create the deal task using the website form first for a new direct client. The Slack channel comes from that task; interactive runs can choose from matching tasks.\",\n\t\t);\n\t}\n\n\tconsole.error(\"Select the Asana lead task to link to this project:\");\n\tcandidates.forEach((candidate, index) => {\n\t\tconsole.error(\n\t\t\t`${index + 1}. ${candidate.name} (${formatAsanaCandidateMetadata(candidate)})`,\n\t\t);\n\t});\n\n\tconst rl = createInterface({\n\t\tinput: process.stdin,\n\t\toutput: process.stderr,\n\t});\n\n\ttry {\n\t\twhile (true) {\n\t\t\tconst answer = await rl.question(\n\t\t\t\t`Choose 1-${candidates.length}, or q to abort: `,\n\t\t\t);\n\t\t\tconst trimmed = answer.trim().toLowerCase();\n\t\t\tif (trimmed === \"q\" || trimmed === \"quit\") {\n\t\t\t\tthrow new Error(\"Aborted.\");\n\t\t\t}\n\n\t\t\tconst selected = Number.parseInt(trimmed, 10);\n\t\t\tif (\n\t\t\t\tNumber.isInteger(selected) &&\n\t\t\t\tselected >= 1 &&\n\t\t\t\tselected <= candidates.length\n\t\t\t) {\n\t\t\t\tconst candidate = candidates[selected - 1];\n\t\t\t\tif (candidate) return candidate;\n\t\t\t}\n\n\t\t\tconsole.error(`Enter a number from 1 to ${candidates.length}.`);\n\t\t}\n\t} finally {\n\t\trl.close();\n\t}\n};\n\nconst resolveAsanaDealSlackChannel = async (\n\tasanaTaskId: string,\n): Promise<ResolvedAsanaDealSlackChannel[\"channel\"]> => {\n\tconst result = await api.asana.getDealSlackChannel.query({ id: asanaTaskId });\n\tif (result.status !== \"resolved\") {\n\t\tthrow new Error(result.message);\n\t}\n\n\tconsole.error(\n\t\t`Resolved Slack channel from Asana deal: #${result.channel.slackChannelName} (${result.channel.slackChannelId})`,\n\t);\n\treturn result.channel;\n};\n\nconst resolveCreateProjectLinks = async (opts: {\n\tname: string;\n\tasanaTaskId?: string;\n\tasanaSearch?: string;\n\tslackChannelId?: string;\n\tslackChannelUrl?: string;\n\tslackChannelName?: string;\n}): Promise<{\n\tasanaTaskId: string;\n\tslackChannelId: string;\n\tslackChannelUrl: string;\n\tslackChannelName: string;\n}> => {\n\tconst asanaTaskId =\n\t\topts.asanaTaskId?.trim() ||\n\t\t(\n\t\t\tawait promptForAsanaLeadCandidate(\n\t\t\t\tawait searchOpenAsanaLeadCandidates({\n\t\t\t\t\tprojectName: opts.name,\n\t\t\t\t\tsearchQuery: opts.asanaSearch,\n\t\t\t\t}),\n\t\t\t)\n\t\t).gid;\n\n\tconst hasCompleteManualSlackChannel = Boolean(\n\t\topts.slackChannelId && opts.slackChannelUrl && opts.slackChannelName,\n\t);\n\tif (hasCompleteManualSlackChannel) {\n\t\treturn {\n\t\t\tasanaTaskId,\n\t\t\tslackChannelId: opts.slackChannelId as string,\n\t\t\tslackChannelUrl: opts.slackChannelUrl as string,\n\t\t\tslackChannelName: opts.slackChannelName as string,\n\t\t};\n\t}\n\n\tconst slackChannel = await resolveAsanaDealSlackChannel(asanaTaskId);\n\treturn {\n\t\tasanaTaskId,\n\t\t...slackChannel,\n\t};\n};\n\nconst combineDateAndTime = (day: Date, time: Date): Date => {\n\tconst d = new Date(day);\n\td.setHours(time.getHours(), time.getMinutes(), time.getSeconds(), 0);\n\treturn d;\n};\n\nconst formatOptionalProjectPaxInput = (\n\tpax: number | null | undefined,\n): string => {\n\tif (typeof pax !== \"number\" || !Number.isFinite(pax) || pax <= 0) {\n\t\treturn \"\";\n\t}\n\n\treturn String(pax);\n};\n\n/** Extension-based MIME, like browser `File.type` when the OS provides it */\nconst contentTypeHeaderForFileName = (fileName: string): string => {\n\tconst ct = contentType(fileName);\n\treturn typeof ct === \"string\" ? ct : \"application/octet-stream\";\n};\n\nconst supportedAttachmentContentTypes = [\n\t\"application/pdf\",\n\t\"image/gif\",\n\t\"image/jpeg\",\n\t\"image/png\",\n\t\"image/webp\",\n] as const;\n\ntype SupportedAttachmentContentType =\n\t(typeof supportedAttachmentContentTypes)[number];\n\nconst attachmentContentTypeForFileName = (\n\tfileName: string,\n): SupportedAttachmentContentType => {\n\tconst resolvedContentType = contentTypeHeaderForFileName(fileName);\n\tconst supportedContentType = supportedAttachmentContentTypes.find(\n\t\t(contentTypeValue) => contentTypeValue === resolvedContentType,\n\t);\n\tif (supportedContentType) return supportedContentType;\n\n\tthrow new Error(`Unsupported attachment type: ${fileName}`);\n};\n\nconst billAttachmentContentTypeForFileName = (\n\tfileName: string,\n): Exclude<SupportedAttachmentContentType, \"image/webp\"> => {\n\tconst resolvedContentType = attachmentContentTypeForFileName(fileName);\n\tif (resolvedContentType === \"image/webp\") {\n\t\tthrow new Error(\n\t\t\t`Unsupported QuickBooks bill attachment type: ${fileName}. Use PDF, GIF, JPEG, or PNG.`,\n\t\t);\n\t}\n\treturn resolvedContentType;\n};\n\nconst PAYMENT_PROOF_MAX_SIZE = 20 * 1024 * 1024;\nconst QUOTATION_ATTACHMENT_MAX_SIZE = 20 * 1024 * 1024;\n\nconst quotationAttachmentContentTypeForFileName = (\n\tfileName: string,\n): \"application/pdf\" | \"image/jpeg\" | \"image/png\" => {\n\tconst resolvedContentType = contentTypeHeaderForFileName(fileName);\n\tif (\n\t\tresolvedContentType === \"application/pdf\" ||\n\t\tresolvedContentType === \"image/jpeg\" ||\n\t\tresolvedContentType === \"image/png\"\n\t) {\n\t\treturn resolvedContentType;\n\t}\n\n\tthrow new Error(\n\t\t`Unsupported quotation attachment type: ${fileName}. Use PDF, JPEG, or PNG.`,\n\t);\n};\n\ntype ProjectListInput = RouterInputs[\"project\"][\"getAllProjects\"];\ntype ProjectCountInput = RouterInputs[\"project\"][\"getProjectCounts\"];\ntype BudgetEventDetailsInput = {\n\tdate: string;\n\tstartTime: string;\n\tendTime: string;\n};\n\ntype LockedBudgetStatus = Extract<\n\tBudgetStatus,\n\t| \"ESTIMATE_CREATED\"\n\t| \"ESTIMATE_SENT\"\n\t| \"ESTIMATE_ACCEPTED\"\n\t| \"ESTIMATE_REJECTED\"\n\t| \"ESTIMATE_CLOSED\"\n>;\n\nconst LOCKED_BUDGET_STATUSES_REQUIRING_CONFIRMATION = new Set<BudgetStatus>([\n\tBudgetStatus.ESTIMATE_CREATED,\n\tBudgetStatus.ESTIMATE_SENT,\n\tBudgetStatus.ESTIMATE_ACCEPTED,\n\tBudgetStatus.ESTIMATE_REJECTED,\n\tBudgetStatus.ESTIMATE_CLOSED,\n]);\n\nconst lockedBudgetStatusLabels: Record<LockedBudgetStatus, string> = {\n\tESTIMATE_CREATED: \"Estimate Created\",\n\tESTIMATE_SENT: \"Estimate Sent\",\n\tESTIMATE_ACCEPTED: \"Estimate Accepted\",\n\tESTIMATE_REJECTED: \"Estimate Rejected\",\n\tESTIMATE_CLOSED: \"Estimate Closed\",\n};\n\nconst lockedBudgetStatusLabel = (status: BudgetStatus): string =>\n\tstatus in lockedBudgetStatusLabels\n\t\t? lockedBudgetStatusLabels[status as LockedBudgetStatus]\n\t\t: status;\n\ninterface SensitiveWorkflowPreviewInput {\n\taction: string;\n\tentity: string;\n\tdetails?: string;\n\teffects?: Parameters<typeof confirmCurrentCommand>[0][\"effects\"];\n}\n\nexport const buildSensitiveWorkflowPreview = ({\n\taction,\n\tentity,\n\tdetails,\n}: SensitiveWorkflowPreviewInput): string => {\n\tconst effects = details ?? \"may change workflow state or send notifications\";\n\treturn [\n\t\t\"Budget Builder workflow preview\",\n\t\t`Action: ${action}`,\n\t\t`Target: ${entity}`,\n\t\t`Effects: ${effects}`,\n\t].join(\"\\n\");\n};\n\nconst assertSensitiveWorkflowConfirmed = async (\n\tinput: SensitiveWorkflowPreviewInput,\n) => {\n\tif (getActiveCliSession()?.invocation.legacy !== true) {\n\t\tawait confirmCurrentCommand({\n\t\t\taction: input.action,\n\t\t\ttarget: input.entity,\n\t\t\tdetails: input.details,\n\t\t\teffects: input.effects,\n\t\t});\n\t\treturn;\n\t}\n\n\tconst expected = \"CONFIRM\";\n\tconst preview = buildSensitiveWorkflowPreview(input);\n\n\tif (!process.stdin.isTTY || !process.stderr.isTTY) {\n\t\tthrow new Error(\n\t\t\t`${preview}\\nThis is a sensitive workflow change. Run it in an interactive terminal only after the user explicitly confirms this exact action, then type \"${expected}\" to continue.`,\n\t\t);\n\t}\n\n\tconst rl = createInterface({\n\t\tinput: process.stdin,\n\t\toutput: process.stderr,\n\t});\n\n\ttry {\n\t\tconst answer = await rl.question(\n\t\t\t`${preview}\\nConfirm the user explicitly approved this exact action, then type \"${expected}\" to continue: `,\n\t\t);\n\t\tif (answer.trim() !== expected) {\n\t\t\tthrow new Error(\"Aborted.\");\n\t\t}\n\t} finally {\n\t\trl.close();\n\t}\n};\n\nconst assertLockedBudgetChangeConfirmed = async ({\n\tbudget,\n\taction,\n}: {\n\tbudget: { id: string; name: string; status: BudgetStatus };\n\taction: string;\n}) => {\n\tif (!LOCKED_BUDGET_STATUSES_REQUIRING_CONFIRMATION.has(budget.status)) {\n\t\treturn;\n\t}\n\n\tconst statusLabel = lockedBudgetStatusLabel(budget.status);\n\tif (getActiveCliSession()?.invocation.legacy !== true) {\n\t\tawait confirmCurrentCommand({\n\t\t\taction,\n\t\t\ttarget: `budget ${budget.id}`,\n\t\t\tdetails: `Changes locked budget \"${budget.name}\" in status ${statusLabel}.`,\n\t\t\teffects: [\"state-change\"],\n\t\t});\n\t\treturn;\n\t}\n\n\tif (!process.stdin.isTTY || !process.stderr.isTTY) {\n\t\tthrow new Error(\n\t\t\t`${action} would change locked budget \"${budget.name}\" (${budget.id}) with status ${statusLabel}. Run this command in an interactive terminal and type \"yes\" to confirm.`,\n\t\t);\n\t}\n\n\tconst rl = createInterface({\n\t\tinput: process.stdin,\n\t\toutput: process.stderr,\n\t});\n\n\ttry {\n\t\tconst answer = await rl.question(\n\t\t\t`${action} will change locked budget \"${budget.name}\" (${budget.id}) with status ${statusLabel}. Type \"yes\" to continue: `,\n\t\t);\n\t\tif (answer.trim().toLowerCase() !== \"yes\") {\n\t\t\tthrow new Error(\"Aborted.\");\n\t\t}\n\t} finally {\n\t\trl.close();\n\t}\n};\n\nconst confirmLockedBudgetChangeByBudgetId = async (\n\tbudgetId: string,\n\taction: string,\n) => {\n\tconst budget = await api.budget.getBudget.query({ id: budgetId });\n\tawait assertLockedBudgetChangeConfirmed({\n\t\tbudget: {\n\t\t\tid: budget.id,\n\t\t\tname: budget.name,\n\t\t\tstatus: budget.status,\n\t\t},\n\t\taction,\n\t});\n};\n\nconst confirmLockedBudgetChangeByBudgetItemId = async (\n\tbudgetItemId: string,\n\taction: string,\n) => {\n\tconst { budget } = await api.budgetItem.getBudgetItemContext.query({\n\t\tbudgetItemId,\n\t});\n\tawait assertLockedBudgetChangeConfirmed({ budget, action });\n};\n\nconst updateProjectWithEstimateInvalidationConfirmation = async (\n\tinput: RouterInputs[\"project\"][\"updateProject\"],\n) => {\n\ttry {\n\t\treturn await api.project.updateProject.mutate(input);\n\t} catch (error) {\n\t\tif (\n\t\t\tinput.confirmEstimateInvalidation === true ||\n\t\t\t!(error instanceof Error) ||\n\t\t\t!error.message.startsWith(\"This project change affects\")\n\t\t) {\n\t\t\tthrow error;\n\t\t}\n\n\t\tawait assertSensitiveWorkflowConfirmed({\n\t\t\taction: \"Update project and reject existing estimates\",\n\t\t\tentity: `project ${input.id}`,\n\t\t\tdetails: error.message,\n\t\t});\n\t\treturn api.project.updateProject.mutate({\n\t\t\t...input,\n\t\t\tconfirmEstimateInvalidation: true,\n\t\t});\n\t}\n};\n\ntype BudgetPreflightInput = {\n\tcompany?: RouterInputs[\"company\"][\"updateCompany\"];\n\tcontactPerson?: RouterInputs[\"contactPerson\"][\"updateContactPerson\"];\n\teventDetails?: BudgetEventDetailsInput;\n};\n\nexport const listBudgets = async (\n\tinput: RouterInputs[\"budget\"][\"getAllBudgets\"],\n): Promise<void> => {\n\tout(await api.budget.getAllBudgets.query(input));\n};\n\nexport const countBudgets = async (\n\tinput: RouterInputs[\"budget\"][\"getCounts\"],\n): Promise<void> => {\n\tout(await api.budget.getCounts.query(input));\n};\n\nexport async function getBudget(\n\tid: string,\n\topts?: { includeInactive?: boolean },\n): Promise<void> {\n\tconst includeInactive = opts?.includeInactive ?? false;\n\tconst [budget, items, totals] = await Promise.all([\n\t\tapi.budget.getBudget.query({ id, includeInactive }),\n\t\tapi.budget.getBudgetItems.query({ budgetId: id, includeInactive }),\n\t\tapi.budget.getBudgetItemTotals.query({ budgetId: id, includeInactive }),\n\t]);\n\tout({ budget, items: { ...items, totals } });\n}\n\nexport async function updateBudgetStatus(\n\tbudgetId: string,\n\tstatus: BudgetStatusUpdate,\n\topts?: {\n\t\tprojectManagerId?: string;\n\t\tmarkProjectWon?: boolean;\n\t\tprojectStatusOnCommercialRejection?: Extract<\n\t\t\tProjectStatus,\n\t\t\ttypeof ProjectStatus.PITCH | typeof ProjectStatus.LOST\n\t\t>;\n\t\tprojectInvoiceSettings?: ProjectInvoiceSettingsInput;\n\t},\n): Promise<void> {\n\tawait assertSensitiveWorkflowConfirmed({\n\t\taction: \"Update budget status\",\n\t\tentity: `budget ${budgetId}`,\n\t\tdetails: `to ${status}`,\n\t});\n\tawait confirmLockedBudgetChangeByBudgetId(budgetId, \"Update budget status\");\n\tconst result = await api.budget.updateBudgetStatus.mutate({\n\t\tid: budgetId,\n\t\tstatus,\n\t\t...(opts?.projectManagerId !== undefined && {\n\t\t\tprojectManagerId: opts.projectManagerId,\n\t\t}),\n\t\t...(opts?.markProjectWon !== undefined && {\n\t\t\tmarkProjectWon: opts.markProjectWon,\n\t\t}),\n\t\t...(opts?.projectStatusOnCommercialRejection !== undefined && {\n\t\t\tprojectStatusOnCommercialRejection:\n\t\t\t\topts.projectStatusOnCommercialRejection,\n\t\t}),\n\t\t...(opts?.projectInvoiceSettings !== undefined && {\n\t\t\tprojectInvoiceSettings: opts.projectInvoiceSettings,\n\t\t}),\n\t});\n\tout({\n\t\t...result,\n\t\tinvoiceSetup:\n\t\t\tresult.newStatus === BudgetStatus.ESTIMATE_ACCEPTED &&\n\t\t\tresult.hasQuickbooksEstimate\n\t\t\t\t? invoiceSplitSetupNextAction(budgetId)\n\t\t\t\t: null,\n\t});\n}\n\nconst assertBudgetActionReadiness = async ({\n\tbudgetId,\n\trequireQuickbooksProject,\n\tactionLabel,\n}: {\n\tbudgetId: string;\n\trequireQuickbooksProject: boolean;\n\tactionLabel: \"request approval\" | \"create estimate\";\n}) => {\n\tconst budget = await api.budget.getBudget.query({ id: budgetId });\n\n\tconst hasNoItems = budget.budgetItems.length === 0;\n\tif (hasNoItems) {\n\t\tthrow new Error(\n\t\t\t`Cannot ${actionLabel}: there are no line items in this budget.`,\n\t\t);\n\t}\n\n\tconst hasZeroCostItems = budget.budgetItems.some(\n\t\t(item) => Number(item.cost ?? 0) === 0,\n\t);\n\tif (hasZeroCostItems) {\n\t\tthrow new Error(\n\t\t\t`Cannot ${actionLabel}: all line items must have a cost greater than zero.`,\n\t\t);\n\t}\n\n\tconst inactiveSuppliers = budget.budgetItems\n\t\t.filter((item) => !item.supplier.active)\n\t\t.map((item) => item.supplier.name);\n\tconst uniqueInactiveSuppliers = [...new Set(inactiveSuppliers)];\n\tif (uniqueInactiveSuppliers.length > 0) {\n\t\tthrow new Error(\n\t\t\t`Cannot ${actionLabel}: inactive suppliers found (${uniqueInactiveSuppliers.join(\", \")}).`,\n\t\t);\n\t}\n\n\tif (requireQuickbooksProject && !budget.project.quickbooksProjectId) {\n\t\tthrow new Error(\n\t\t\t\"Cannot create estimate: project is not linked to QuickBooks yet.\",\n\t\t);\n\t}\n};\n\nconst runBudgetPreflight = async (\n\tbudgetId: string,\n\tpreflight?: BudgetPreflightInput,\n) => {\n\tif (!preflight) return;\n\n\tif (preflight.company) {\n\t\tawait api.company.updateCompany.mutate(preflight.company);\n\t}\n\n\tif (preflight.contactPerson) {\n\t\tawait api.contactPerson.updateContactPerson.mutate(preflight.contactPerson);\n\t}\n\n\tif (preflight.eventDetails) {\n\t\tconst budget = await api.budget.getBudget.query({ id: budgetId });\n\t\tconst project = await api.project.getProjectById.query({\n\t\t\tid: budget.projectId,\n\t\t});\n\t\tconst day = new Date(preflight.eventDetails.date);\n\t\tconst start = new Date(preflight.eventDetails.startTime);\n\t\tconst end = new Date(preflight.eventDetails.endTime);\n\t\tconst payload: RouterInputs[\"project\"][\"updateProject\"] = {\n\t\t\tid: project.id,\n\t\t\tname: project.name,\n\t\t\tdescription: project.description ?? undefined,\n\t\t\tdateRange: {\n\t\t\t\tfrom: combineDateAndTime(day, start),\n\t\t\t\tto: combineDateAndTime(day, end),\n\t\t\t},\n\t\t\tcompanyId: project.companyId,\n\t\t\tcontactPersonId: project.contactPersonId,\n\t\t\tasanaTaskId: project.asanaTaskId ?? \"\",\n\t\t\tinsideSalesId: project.insideSalesId ?? \"\",\n\t\t\tbusinessDevelopmentId: project.businessDevelopmentId ?? \"\",\n\t\t\tvenue: project.venue ?? \"\",\n\t\t\tpax: formatOptionalProjectPaxInput(project.pax),\n\t\t\t...(project.slackChannelId &&\n\t\t\tproject.slackChannelUrl &&\n\t\t\tproject.slackChannelName\n\t\t\t\t? {\n\t\t\t\t\t\tslackChannelId: project.slackChannelId,\n\t\t\t\t\t\tslackChannelUrl: project.slackChannelUrl,\n\t\t\t\t\t\tslackChannelName: project.slackChannelName,\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t};\n\t\tawait updateProjectWithEstimateInvalidationConfirmation(payload);\n\t}\n};\n\nexport const listBills = async (\n\tinput: RouterInputs[\"bill\"][\"getAll\"],\n): Promise<void> => {\n\tout(\n\t\tawait api.bill.getAll.query({\n\t\t\t...input,\n\t\t\tstatuses: billStatusesForApi(input.statuses),\n\t\t\tsearch: input.search?.trim() || undefined,\n\t\t\tcreatedByIds: input.createdByIds?.length ? input.createdByIds : undefined,\n\t\t}),\n\t);\n};\n\nexport const countBills = async (\n\tinput: RouterInputs[\"bill\"][\"getCounts\"],\n): Promise<void> => {\n\tout(\n\t\tawait api.bill.getCounts.query({\n\t\t\t...input,\n\t\t\tstatuses: billStatusesForApi(input.statuses),\n\t\t\tsearch: input.search?.trim() || undefined,\n\t\t\tcreatedByIds: input.createdByIds?.length ? input.createdByIds : undefined,\n\t\t}),\n\t);\n};\n\nexport async function approveBill(\n\tbillId: string,\n\toverBudgetOverrideReason?: string,\n): Promise<void> {\n\tawait assertSensitiveWorkflowConfirmed({\n\t\taction: \"Approve bill\",\n\t\tentity: `bill ${billId}`,\n\t\tdetails: \"and send requester reply email\",\n\t});\n\tconst notifications = await getAllNotifications();\n\tconst pending = notifications.filter(\n\t\t(n) =>\n\t\t\tisPendingRequest(n) &&\n\t\t\tn.type === BILL &&\n\t\t\t(n.billId === billId || n.bill?.id === billId),\n\t);\n\tconst approval = pending[0];\n\tif (!approval) {\n\t\tthrow new Error(\"No pending bill approval found for this bill.\");\n\t}\n\tconst result = await api.bill.updateApproval.mutate({\n\t\tbillApprovalId: approval.id,\n\t\tstatus: ApprovalStatus.APPROVED,\n\t\toverBudgetOverrideReason,\n\t});\n\tif (result.processing) {\n\t\tout(result);\n\t\treturn;\n\t}\n\tlet email: ApprovalEmailDeliveryReport;\n\ttry {\n\t\tconst delivery = result.emailDelivery;\n\t\temail = createApprovalEmailDeliveryReport(delivery);\n\t} catch (error) {\n\t\temail = createApprovalEmailDeliveryFailure(\n\t\t\terror instanceof Error ? error.message : String(error),\n\t\t);\n\t}\n\tout({\n\t\t...result,\n\t\temail,\n\t});\n}\n\nconst approvalIdentity = (\n\tn: PendingRequestRow,\n): { id: string; name: string } => {\n\tif (n.type === BUDGET && n.budget) {\n\t\treturn { id: n.budgetId ?? n.id, name: n.budget.name };\n\t}\n\tif (n.type === BILL && n.bill) {\n\t\treturn {\n\t\t\tid: n.bill.id,\n\t\t\tname: `Bill ${n.bill.invoiceNumber ?? n.bill.id.slice(0, 8)}`,\n\t\t};\n\t}\n\tif (n.type === SUPPLIER && n.supplier) {\n\t\treturn { id: n.supplier.id, name: n.supplier.name };\n\t}\n\tif (n.type === QUOTATION && n.supplierQuotation) {\n\t\treturn {\n\t\t\tid: n.supplierQuotation.id,\n\t\t\tname: `Quotation ${n.supplierQuotation.supplier.name}`,\n\t\t};\n\t}\n\tif (n.type === CUSTOMER_INVOICE && n.customerInvoiceBatch) {\n\t\treturn {\n\t\t\tid: n.customerInvoiceBatch.id,\n\t\t\tname: `Customer invoice ${n.customerInvoiceBatch.project.name}`,\n\t\t};\n\t}\n\treturn { id: n.id, name: \"Unknown\" };\n};\n\nconst approvalRequestedAt = (\n\tcreatedAt: PendingRequestRow[\"createdAt\"],\n): string => {\n\tif (typeof createdAt === \"string\") return createdAt;\n\tif (createdAt instanceof Date) return createdAt.toISOString();\n\treturn String(createdAt);\n};\n\nexport async function listApprovals(opts: {\n\ttype?: ApprovalCliFilter;\n}): Promise<void> {\n\tconst notifications = await getAllNotifications();\n\tconst pending = notifications.filter(isPendingRequest);\n\n\tconst typeFilter =\n\t\topts.type === undefined || opts.type === \"ALL\"\n\t\t\t? (_n: PendingRequestRow) => true\n\t\t\t: (n: PendingRequestRow) => n.type === opts.type;\n\n\tconst filtered = pending\n\t\t.filter(typeFilter)\n\t\t.filter((n) => n.type !== BUDGET || !n.budget?.quickbooksEstimateId);\n\n\tconst items = filtered.map((n) => {\n\t\tconst { id, name } = approvalIdentity(n);\n\t\treturn {\n\t\t\tapprovalId: n.id,\n\t\t\ttype: n.type,\n\t\t\tid,\n\t\t\tname,\n\t\t\trequestedBy: n.requester?.name ?? n.requester?.email ?? \"Unknown\",\n\t\t\trequestedAt: approvalRequestedAt(n.createdAt),\n\t\t};\n\t});\n\tout({ items });\n}\n\nexport const listSuppliers = async (\n\topts: RouterInputs[\"supplier\"][\"getSuppliers\"],\n): Promise<void> => {\n\tout(await api.supplier.getSuppliers.query(opts));\n};\n\nexport const countSuppliers = async (\n\topts: RouterInputs[\"supplier\"][\"getSummary\"],\n): Promise<void> => {\n\tout(await api.supplier.getSummary.query(opts));\n};\n\n// --- Bills (MCP parity) ---\n\nexport async function createBillApproval(billId: string): Promise<void> {\n\tawait assertSensitiveWorkflowConfirmed({\n\t\taction: \"Create bill approval request\",\n\t\tentity: `bill ${billId}`,\n\t\tdetails: \"and send approval request emails\",\n\t});\n\tconst result = await api.bill.createApproval.mutate({ billId });\n\tconst approvalIds = (result.results ?? []).map((item) => ({ id: item.id }));\n\n\tlet email: ApprovalEmailDeliveryReport;\n\tif (approvalIds.length === 0) {\n\t\temail = createApprovalEmailDeliveryFailure(\"No approval ids returned\");\n\t} else {\n\t\ttry {\n\t\t\tconst delivery = result.emailDelivery;\n\t\t\temail = createApprovalEmailDeliveryReport(delivery);\n\t\t} catch (error) {\n\t\t\temail = createApprovalEmailDeliveryFailure(\n\t\t\t\terror instanceof Error ? error.message : String(error),\n\t\t\t);\n\t\t}\n\t}\n\n\tout({\n\t\t...result,\n\t\temail,\n\t});\n}\n\ninterface UpdateBillStatusOptions {\n\tid: string;\n\tstatus: BillStatus;\n\toverBudgetOverrideReason?: string;\n\trejectionReason?: string;\n\tpaymentTrackingUrl?: string;\n\tpaymentReference?: string;\n\tpaymentProofPath?: string;\n}\n\nexport const validateBillStatusUpdateOptions = (\n\topts: UpdateBillStatusOptions,\n): void => {\n\tif (opts.status === BillStatus.PAID && !opts.paymentReference?.trim()) {\n\t\tthrow new Error(\n\t\t\t\"update-bill-status requires --paymentReference when status is PAID.\",\n\t\t);\n\t}\n\tif (opts.status !== BillStatus.PAID && opts.paymentProofPath !== undefined) {\n\t\tthrow new Error(\"--paymentProof can only be used when status is PAID.\");\n\t}\n\tif (opts.paymentProofPath !== undefined && !opts.paymentProofPath.trim()) {\n\t\tthrow new Error(\"--paymentProof requires a PDF file path.\");\n\t}\n};\n\ntype BillStatusPaymentProof = NonNullable<\n\tRouterInputs[\"bill\"][\"updateStatus\"][\"paymentProofAttachments\"]\n>[number];\n\nconst deleteStagedPaymentProof = async (\n\tprojectId: string,\n\tkey: string,\n): Promise<void> => {\n\t// This confirms durable queue admission, not physical S3 deletion. Worker\n\t// failures remain independently retryable in the Integration Queue.\n\tawait api.attachment.deleteStagedBillAttachments.mutate({\n\t\tprojectId,\n\t\tkeys: [key],\n\t});\n};\n\nexport const rethrowAfterStagedPaymentProofCleanup = async (\n\terror: unknown,\n\tcleanup?: () => Promise<void>,\n): Promise<never> => {\n\tif (cleanup) {\n\t\ttry {\n\t\t\tawait cleanup();\n\t\t} catch (cleanupError) {\n\t\t\tthrow new AggregateError(\n\t\t\t\t[error, cleanupError],\n\t\t\t\t\"Bill status update failed and its staged payment proof could not be cleaned up.\",\n\t\t\t);\n\t\t}\n\t}\n\tthrow error;\n};\n\nconst stageBillPaymentProof = async (\n\tprojectId: string,\n\tfilePath: string,\n): Promise<BillStatusPaymentProof> => {\n\tconst buffer = await readFile(filePath);\n\tconst fileName = basename(filePath);\n\tconst size = buffer.byteLength;\n\tconst contentType = billAttachmentContentTypeForFileName(fileName);\n\n\tif (\n\t\t!fileName.toLowerCase().endsWith(\".pdf\") ||\n\t\tcontentType !== \"application/pdf\"\n\t) {\n\t\tthrow new Error(\"Payment proof must be a PDF.\");\n\t}\n\tif (size === 0) {\n\t\tthrow new Error(\"Payment proof must not be empty.\");\n\t}\n\tif (size > PAYMENT_PROOF_MAX_SIZE) {\n\t\tthrow new Error(\"Payment proof must be 20MB or smaller.\");\n\t}\n\n\tconst { uploadUrl, key } =\n\t\tawait api.attachment.requestStagedBillAttachmentUpload.mutate({\n\t\t\tprojectId,\n\t\t\tfileName,\n\t\t\tsize,\n\t\t\tcontentType,\n\t\t});\n\ttry {\n\t\tconst response = await fetch(uploadUrl, {\n\t\t\tmethod: \"PUT\",\n\t\t\tbody: buffer,\n\t\t\theaders: { \"Content-Type\": contentType },\n\t\t});\n\t\tif (!response.ok) {\n\t\t\tthrow new Error(\n\t\t\t\t`S3 upload failed: HTTP ${response.status} ${(await response.text()).slice(0, 500)}`,\n\t\t\t);\n\t\t}\n\t} catch (uploadError) {\n\t\ttry {\n\t\t\tawait deleteStagedPaymentProof(projectId, key);\n\t\t} catch (cleanupError) {\n\t\t\tthrow new AggregateError(\n\t\t\t\t[uploadError, cleanupError],\n\t\t\t\t\"Payment-proof upload failed and its staged object could not be cleaned up.\",\n\t\t\t);\n\t\t}\n\t\tthrow uploadError;\n\t}\n\n\treturn { id: randomUUID(), key, name: fileName, size };\n};\n\nexport async function updateBillStatus(\n\topts: UpdateBillStatusOptions,\n): Promise<void> {\n\tvalidateBillStatusUpdateOptions(opts);\n\tawait assertSensitiveWorkflowConfirmed({\n\t\taction: \"Update bill status\",\n\t\tentity: `bill ${opts.id}`,\n\t\tdetails: `to ${opts.status}`,\n\t});\n\n\tconst bill = opts.paymentProofPath\n\t\t? await api.bill.getPayment.query({ id: opts.id })\n\t\t: null;\n\tconst paymentProof =\n\t\tbill && opts.paymentProofPath\n\t\t\t? await stageBillPaymentProof(bill.projectId, opts.paymentProofPath)\n\t\t\t: undefined;\n\n\ttry {\n\t\tconst result = await api.bill.updateStatus.mutate({\n\t\t\tid: opts.id,\n\t\t\tstatus: opts.status,\n\t\t\trejectionReason: opts.rejectionReason,\n\t\t\tpaymentTrackingUrl: opts.paymentTrackingUrl,\n\t\t\tpaymentReference: opts.paymentReference,\n\t\t\tpaymentProofAttachments: paymentProof ? [paymentProof] : undefined,\n\t\t\toverBudgetOverrideReason: opts.overBudgetOverrideReason,\n\t\t});\n\t\tout(result);\n\t} catch (error) {\n\t\tawait rethrowAfterStagedPaymentProofCleanup(\n\t\t\terror,\n\t\t\tbill && paymentProof\n\t\t\t\t? async () => {\n\t\t\t\t\t\t// The cleanup endpoint checks the staged-upload record and refuses to\n\t\t\t\t\t\t// delete a key that an ambiguously successful update already consumed.\n\t\t\t\t\t\tawait deleteStagedPaymentProof(bill.projectId, paymentProof.key);\n\t\t\t\t\t}\n\t\t\t\t: undefined,\n\t\t);\n\t}\n}\n\ninterface RecordExternalBillPaymentOptions {\n\tid: string;\n\tpaymentReference: string;\n\tpaymentDate: string;\n\tpaymentAccount: string;\n\tpaymentProofPath?: string;\n}\n\nexport const listExternalBillPaymentAccounts = async (): Promise<void> => {\n\tout(await api.bill.getExternalPaymentAccounts.query());\n};\n\nexport const refreshExternalBillPaymentAccounts = async (): Promise<void> => {\n\tawait confirmCurrentCommand({\n\t\taction: \"refresh QuickBooks payment accounts\",\n\t\ttarget: \"the cached external payment-account list\",\n\t\teffects: [\"state-change\"],\n\t\tdetails:\n\t\t\t\"Queue a read of QuickBooks bank and credit-card accounts; nothing is written to QuickBooks.\",\n\t});\n\tout(await api.bill.refreshExternalPaymentAccounts.mutate());\n};\n\nexport const recordExternalBillPayment = async (\n\topts: RecordExternalBillPaymentOptions,\n): Promise<void> => {\n\tif (\n\t\t!opts.paymentReference.trim() ||\n\t\t!opts.paymentAccount.trim() ||\n\t\t!/^\\d{4}-\\d{2}-\\d{2}$/.test(opts.paymentDate) ||\n\t\tnew Date(`${opts.paymentDate}T00:00:00Z`).toISOString().slice(0, 10) !==\n\t\t\topts.paymentDate\n\t)\n\t\tthrow new Error(\n\t\t\t\"Supply --paymentReference, --paymentDate YYYY-MM-DD, and --paymentAccount <QBO account ID>.\",\n\t\t);\n\tawait assertSensitiveWorkflowConfirmed({\n\t\taction: \"Record external payment (no email)\",\n\t\tentity: `bill ${opts.id}`,\n\t\tdetails: `already paid on ${opts.paymentDate}; reference ${opts.paymentReference}; QBO account ${opts.paymentAccount}. No money is transferred.`,\n\t});\n\tconst bill = await api.bill.getPayment.query({ id: opts.id });\n\tconst proof =\n\t\t!bill.externalPayment && opts.paymentProofPath\n\t\t\t? await stageBillPaymentProof(bill.projectId, opts.paymentProofPath)\n\t\t\t: undefined;\n\ttry {\n\t\tout(\n\t\t\tawait api.bill.recordExternalPayment.mutate({\n\t\t\t\tid: opts.id,\n\t\t\t\tpaymentReference: opts.paymentReference,\n\t\t\t\tpaymentDate: opts.paymentDate,\n\t\t\t\tpaymentAccount: opts.paymentAccount,\n\t\t\t\tpaymentProofAttachments: proof ? [proof] : undefined,\n\t\t\t}),\n\t\t);\n\t} catch (error) {\n\t\t// Network failures can hide a committed settlement. Never delete proof\n\t\t// based only on an error; retain it for canonical recovery and exact retry.\n\t\ttry {\n\t\t\tconst latest = await api.bill.getPayment.query({ id: opts.id });\n\t\t\tif (\n\t\t\t\tlatest.externalPayment?.paymentAccount === opts.paymentAccount &&\n\t\t\t\tlatest.paymentReference === opts.paymentReference.trim() &&\n\t\t\t\tlatest.paymentDate?.toISOString().slice(0, 10) === opts.paymentDate\n\t\t\t) {\n\t\t\t\tout({\n\t\t\t\t\t...latest,\n\t\t\t\t\tsupplierNotified: false,\n\t\t\t\t\tquickbooksReconciliationPending:\n\t\t\t\t\t\t!latest.externalPayment.quickbooksBillPaymentIds.length,\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\t\t} catch {\n\t\t\t/* Preserve the original error when readback is unavailable. */\n\t\t}\n\t\tthrow new Error(\n\t\t\t\"External payment result could not be confirmed. Inspect the bill, then retry the same reference/date/account; do not pay again. Any uploaded proof is retained.\",\n\t\t\t{ cause: error },\n\t\t);\n\t}\n};\n\nexport async function patchBillPayment(opts: {\n\tid: string;\n\tpaymentTrackingUrl?: string | null;\n\tpaymentReference?: string | null;\n\tquickbooksBillId?: string | null;\n\tpaymentDate?: string | Date | null;\n}): Promise<void> {\n\tconst input: RouterInputs[\"bill\"][\"patchPayment\"] = { id: opts.id };\n\tif (opts.paymentTrackingUrl !== undefined)\n\t\tinput.paymentTrackingUrl = opts.paymentTrackingUrl;\n\tif (opts.paymentReference !== undefined)\n\t\tinput.paymentReference = opts.paymentReference;\n\tif (opts.quickbooksBillId !== undefined)\n\t\tinput.quickbooksBillId = opts.quickbooksBillId;\n\tif (opts.paymentDate !== undefined) {\n\t\tinput.paymentDate =\n\t\t\topts.paymentDate === null\n\t\t\t\t? null\n\t\t\t\t: typeof opts.paymentDate === \"string\"\n\t\t\t\t\t? new Date(opts.paymentDate)\n\t\t\t\t\t: opts.paymentDate;\n\t}\n\tconst result = await api.bill.patchPayment.mutate(input);\n\tout(result);\n}\n\nexport async function patchBillInvoiceNumber(\n\tid: string,\n\tinvoiceNumber: string,\n): Promise<void> {\n\tconst result = await api.bill.patchInvoiceNumber.mutate({\n\t\tid,\n\t\tinvoiceNumber,\n\t});\n\tout(result);\n}\n\n/** One newest-first page of a bill's attachments: `{ items, pageInfo }`. */\nexport const getBillAttachments = async (\n\tinput: RouterInputs[\"bill\"][\"getAttachments\"],\n): Promise<void> => {\n\tout(await api.bill.getAttachments.query(input));\n};\n\n/** One newest-first page of a bill's approval requests: `{ items, pageInfo }`. */\nexport const getBillApprovals = async (\n\tinput: RouterInputs[\"bill\"][\"getApprovals\"],\n): Promise<void> => {\n\tout(await api.bill.getApprovals.query(input));\n};\n\n/** One newest-first page of a bill's line items: `{ items, pageInfo }`. */\nexport const getBillLineItems = async (\n\tinput: RouterInputs[\"bill\"][\"getLineItems\"],\n): Promise<void> => {\n\tout(await api.bill.getLineItems.query(input));\n};\n\n/** A bill's payment status, reference, date and external payment. */\nexport const getBillPayment = async (id: string): Promise<void> => {\n\tout(await api.bill.getPayment.query({ id }));\n};\n\nexport async function stageBillAttachmentsFromPaths(\n\tprojectId: string,\n\tfilePaths: string[],\n): Promise<void> {\n\tconst attachments = [];\n\tfor (const filePath of filePaths) {\n\t\tconst buffer = await readFile(filePath);\n\t\tconst fileName = basename(filePath);\n\t\tconst size = buffer.byteLength;\n\t\tconst contentType = billAttachmentContentTypeForFileName(fileName);\n\t\tconst { uploadUrl, key } =\n\t\t\tawait api.attachment.requestStagedBillAttachmentUpload.mutate({\n\t\t\t\tprojectId,\n\t\t\t\tfileName,\n\t\t\t\tsize,\n\t\t\t\tcontentType,\n\t\t\t});\n\t\tconst response = await fetch(uploadUrl, {\n\t\t\tmethod: \"PUT\",\n\t\t\tbody: buffer,\n\t\t\theaders: { \"Content-Type\": contentType },\n\t\t});\n\t\tif (!response.ok) {\n\t\t\tthrow new Error(\n\t\t\t\t`S3 upload failed: HTTP ${response.status} ${(await response.text()).slice(0, 500)}`,\n\t\t\t);\n\t\t}\n\t\tattachments.push({ id: randomUUID(), key, name: fileName, size });\n\t}\n\n\tout({\n\t\tsuccess: true as const,\n\t\tprojectId,\n\t\tcount: attachments.length,\n\t\tattachments,\n\t});\n}\n\nexport const cleanupStagedBillAttachments = async (\n\tprojectId: string,\n\tkeys: string[],\n): Promise<void> => {\n\tconst result = await api.attachment.deleteStagedBillAttachments.mutate({\n\t\tprojectId,\n\t\tkeys,\n\t});\n\tout(result);\n};\n\nexport async function uploadBillAttachmentFromPath(\n\tbillId: string,\n\tfilePath: string,\n\ttype: BillAttachmentUploadType = AttachmentType.BILL,\n): Promise<void> {\n\tconst confirmed = await uploadSingleBillAttachmentFromPath(\n\t\tbillId,\n\t\tfilePath,\n\t\ttype,\n\t);\n\tout(confirmed);\n}\n\nconst uploadSingleBillAttachmentFromPath = async (\n\tbillId: string,\n\tfilePath: string,\n\ttype: BillAttachmentUploadType = AttachmentType.BILL,\n) => {\n\tconst buf = await readFile(filePath);\n\tconst fileName = basename(filePath);\n\tconst size = buf.byteLength;\n\tconst attachmentContentType = billAttachmentContentTypeForFileName(fileName);\n\tconst { uploadUrl, key } =\n\t\tawait api.attachment.requestBillAttachmentUpload.mutate({\n\t\t\tbillId,\n\t\t\tcontentType: attachmentContentType,\n\t\t\tfileName,\n\t\t\tsize,\n\t\t});\n\tconst res = await fetch(uploadUrl, {\n\t\tmethod: \"PUT\",\n\t\tbody: buf,\n\t\theaders: { \"Content-Type\": attachmentContentType },\n\t});\n\tif (!res.ok) {\n\t\tthrow new Error(\n\t\t\t`S3 upload failed: HTTP ${res.status} ${(await res.text()).slice(0, 500)}`,\n\t\t);\n\t}\n\treturn await api.attachment.confirmBillAttachment.mutate({\n\t\tbillId,\n\t\tkey,\n\t\tname: fileName,\n\t\tsize,\n\t\ttype,\n\t});\n};\n\nexport async function uploadBillAttachmentsFromPaths(\n\tbillId: string,\n\tfilePaths: string[],\n\ttype: BillAttachmentUploadType = AttachmentType.BILL,\n): Promise<void> {\n\tif (filePaths.length === 0) {\n\t\tthrow new Error(\"At least one bill attachment file path is required\");\n\t}\n\n\tconst results = [];\n\tfor (const filePath of filePaths) {\n\t\tresults.push(\n\t\t\tawait uploadSingleBillAttachmentFromPath(billId, filePath, type),\n\t\t);\n\t}\n\n\tout({\n\t\tsuccess: true as const,\n\t\tbillId,\n\t\ttype,\n\t\tcount: results.length,\n\t\tattachments: results.map((result) => result.attachment),\n\t\tresults,\n\t});\n}\n\nexport async function uploadBillDocumentsFromPaths({\n\tbillId,\n\tinvoicePaths = [],\n\tpaymentProofPaths = [],\n}: {\n\tbillId: string;\n\tinvoicePaths?: string[];\n\tpaymentProofPaths?: string[];\n}): Promise<void> {\n\tif (invoicePaths.length === 0 && paymentProofPaths.length === 0) {\n\t\tthrow new Error(\n\t\t\t\"At least one invoice or payment proof file path is required\",\n\t\t);\n\t}\n\n\tconst invoiceResults = [];\n\tfor (const filePath of invoicePaths) {\n\t\tinvoiceResults.push(\n\t\t\tawait uploadSingleBillAttachmentFromPath(\n\t\t\t\tbillId,\n\t\t\t\tfilePath,\n\t\t\t\tAttachmentType.BILL,\n\t\t\t),\n\t\t);\n\t}\n\n\tconst paymentProofResults = [];\n\tfor (const filePath of paymentProofPaths) {\n\t\tpaymentProofResults.push(\n\t\t\tawait uploadSingleBillAttachmentFromPath(\n\t\t\t\tbillId,\n\t\t\t\tfilePath,\n\t\t\t\tAttachmentType.BILL_PAYMENT_PROOF,\n\t\t\t),\n\t\t);\n\t}\n\n\tout({\n\t\tsuccess: true as const,\n\t\tbillId,\n\t\tcount: invoiceResults.length + paymentProofResults.length,\n\t\tinvoiceAttachments: invoiceResults.map((result) => result.attachment),\n\t\tpaymentProofAttachments: paymentProofResults.map(\n\t\t\t(result) => result.attachment,\n\t\t),\n\t\tresults: [...invoiceResults, ...paymentProofResults],\n\t});\n}\n\nexport async function uploadQuotationAttachmentFromPath(\n\tprojectId: string,\n\tfilePath: string,\n): Promise<void> {\n\tconst buf = await readFile(filePath);\n\tconst fileName = basename(filePath);\n\tif (buf.byteLength > QUOTATION_ATTACHMENT_MAX_SIZE) {\n\t\tthrow new Error(\"Quotation attachment must be 20MB or smaller.\");\n\t}\n\tconst attachmentContentType =\n\t\tquotationAttachmentContentTypeForFileName(fileName);\n\tconst ext = fileName\n\t\t.split(\".\")\n\t\t.pop()\n\t\t?.toLowerCase()\n\t\t.replace(/[^a-z0-9]/g, \"\");\n\tconst key = `quotations/${projectId}/${randomUUID()}.${ext || \"pdf\"}`;\n\tconst uploadUrl = await api.attachment.getPresignedUrlToUpload.mutate({\n\t\tkey,\n\t\tsize: buf.byteLength,\n\t\tcontentType: attachmentContentType,\n\t});\n\tconst res = await fetch(uploadUrl, {\n\t\tmethod: \"PUT\",\n\t\tbody: buf,\n\t\theaders: { \"Content-Type\": attachmentContentType },\n\t});\n\tif (!res.ok) {\n\t\tthrow new Error(\n\t\t\t`S3 upload failed: HTTP ${res.status} ${(await res.text()).slice(0, 500)}`,\n\t\t);\n\t}\n\tout({\n\t\tid: randomUUID(),\n\t\tname: fileName,\n\t\tkey,\n\t\tsize: buf.byteLength,\n\t});\n}\n\nexport const cleanupStagedQuotationAttachments = async (\n\tprojectId: string,\n\tkeys: string[],\n): Promise<void> => {\n\tconst result = await api.quotation.deleteStagedAttachments.mutate({\n\t\tprojectId,\n\t\tkeys,\n\t});\n\tout(result);\n};\n\nexport async function uploadBudgetAttachmentFromPath(\n\tbudgetId: string,\n\tfilePath: string,\n): Promise<void> {\n\tawait confirmLockedBudgetChangeByBudgetId(\n\t\tbudgetId,\n\t\t\"Upload budget attachment\",\n\t);\n\tconst buf = await readFile(filePath);\n\tconst fileName = basename(filePath);\n\tconst size = buf.byteLength;\n\tconst attachmentContentType = attachmentContentTypeForFileName(fileName);\n\tconst { uploadUrl, key } =\n\t\tawait api.attachment.requestBudgetAttachmentUpload.mutate({\n\t\t\tbudgetId,\n\t\t\tcontentType: attachmentContentType,\n\t\t\tfileName,\n\t\t\tsize,\n\t\t});\n\tconst res = await fetch(uploadUrl, {\n\t\tmethod: \"PUT\",\n\t\tbody: buf,\n\t\theaders: { \"Content-Type\": attachmentContentType },\n\t});\n\tif (!res.ok) {\n\t\tthrow new Error(\n\t\t\t`S3 upload failed: HTTP ${res.status} ${(await res.text()).slice(0, 500)}`,\n\t\t);\n\t}\n\tconst confirmed = await api.attachment.confirmBudgetAttachment.mutate({\n\t\tbudgetId,\n\t\tkey,\n\t\tname: fileName,\n\t\tsize,\n\t});\n\tout(confirmed);\n}\n\nexport async function uploadBudgetWinProofFromPath(\n\tbudgetId: string,\n\tfilePath: string,\n\topts?: {\n\t\tprojectManagerId?: string;\n\t\tmarkProjectWon?: boolean;\n\t\tprojectInvoiceSettings?: ProjectInvoiceSettingsInput;\n\t},\n): Promise<void> {\n\tawait assertSensitiveWorkflowConfirmed({\n\t\taction: \"Mark budget won\",\n\t\tentity: `budget ${budgetId}`,\n\t\tdetails: \"by uploading proof and setting status to ESTIMATE_ACCEPTED\",\n\t});\n\tawait confirmLockedBudgetChangeByBudgetId(budgetId, \"Mark budget won\");\n\tconst buf = await readFile(filePath);\n\tconst fileName = basename(filePath);\n\tconst size = buf.byteLength;\n\tconst attachmentContentType = attachmentContentTypeForFileName(fileName);\n\tconst { uploadUrl, key } =\n\t\tawait api.attachment.requestBudgetWinProofUpload.mutate({\n\t\t\tbudgetId,\n\t\t\tcontentType: attachmentContentType,\n\t\t\tfileName,\n\t\t\tsize,\n\t\t});\n\tconst res = await fetch(uploadUrl, {\n\t\tmethod: \"PUT\",\n\t\tbody: buf,\n\t\theaders: { \"Content-Type\": attachmentContentType },\n\t});\n\tif (!res.ok) {\n\t\tthrow new Error(\n\t\t\t`S3 upload failed: HTTP ${res.status} ${(await res.text()).slice(0, 500)}`,\n\t\t);\n\t}\n\tawait api.attachment.confirmBudgetWinProofAttachment.mutate({\n\t\tbudgetId,\n\t\tkey,\n\t\tname: fileName,\n\t\tsize,\n\t});\n\tconst result = await api.budget.updateBudgetStatus.mutate({\n\t\tid: budgetId,\n\t\tstatus: BudgetStatus.ESTIMATE_ACCEPTED,\n\t\t...(opts?.projectManagerId !== undefined && {\n\t\t\tprojectManagerId: opts.projectManagerId,\n\t\t}),\n\t\t...(opts?.markProjectWon !== undefined && {\n\t\t\tmarkProjectWon: opts.markProjectWon,\n\t\t}),\n\t\t...(opts?.projectInvoiceSettings !== undefined && {\n\t\t\tprojectInvoiceSettings: opts.projectInvoiceSettings,\n\t\t}),\n\t});\n\tout({\n\t\t...result,\n\t\tinvoiceSetup: result.hasQuickbooksEstimate\n\t\t\t? invoiceSplitSetupNextAction(budgetId)\n\t\t\t: null,\n\t});\n}\n\nexport async function markBudgetWonWithProof(\n\tbudgetId: string,\n\tfilePath: string,\n\topts?: {\n\t\tprojectManagerId?: string;\n\t\tmarkProjectWon?: boolean;\n\t\tprojectInvoiceSettings?: ProjectInvoiceSettingsInput;\n\t},\n): Promise<void> {\n\tawait uploadBudgetWinProofFromPath(budgetId, filePath, opts);\n}\n\nexport async function getBillDetails(id: string): Promise<void> {\n\tconst result = await api.bill.getById.query({ id });\n\tout(result);\n}\n\n// --- Budgets (MCP parity) ---\n\nexport async function getBudgetItemsOnly(\n\tbudgetId: string,\n\topts?: { includeInactive?: boolean },\n): Promise<void> {\n\tconst includeInactive = opts?.includeInactive ?? false;\n\t// One budget's items load in full; totals come from their own query.\n\tconst [items, totals] = await Promise.all([\n\t\tapi.budget.getBudgetItems.query({ budgetId, includeInactive }),\n\t\tapi.budget.getBudgetItemTotals.query({ budgetId, includeInactive }),\n\t]);\n\tout({ ...items, totals });\n}\n\nexport async function addBudgetItems(opts: {\n\tbudgetId: string;\n\titems: { itemId: string; quantity: number; markup?: number }[];\n}): Promise<void> {\n\tawait confirmLockedBudgetChangeByBudgetId(opts.budgetId, \"Add budget items\");\n\tconst result = await api.budgetItem.addBudgetItems.mutate(opts);\n\tout(result);\n}\n\nexport async function updateBudgetItem(\n\tinput: RouterInputs[\"budgetItem\"][\"updateBudgetItem\"],\n): Promise<void> {\n\tawait confirmLockedBudgetChangeByBudgetItemId(input.id, \"Update budget item\");\n\tconst result = await api.budgetItem.updateBudgetItem.mutate({\n\t\t...input,\n\t\t...(input.description !== undefined &&\n\t\t\tinput.descriptionRichText === undefined && {\n\t\t\t\tdescriptionRichText: createRichTextFromPlainText(input.description),\n\t\t\t}),\n\t\t...(input.note !== undefined &&\n\t\t\tinput.noteRichText === undefined && {\n\t\t\t\tnoteRichText: createRichTextFromPlainText(input.note),\n\t\t\t}),\n\t});\n\tout(result);\n}\n\nexport async function removeBudgetItem(budgetItemId: string): Promise<void> {\n\tawait confirmLockedBudgetChangeByBudgetItemId(\n\t\tbudgetItemId,\n\t\t\"Remove budget item\",\n\t);\n\tconst result = await api.budgetItem.removeBudgetItem.mutate({\n\t\tbudgetItemId,\n\t});\n\tout(result);\n}\n\nexport const replaceBudgetItem = async (\n\tinput: RouterInputs[\"budgetItem\"][\"replaceBudgetItem\"],\n): Promise<void> => {\n\tawait confirmLockedBudgetChangeByBudgetItemId(\n\t\tinput.budgetItemId,\n\t\t\"Replace unavailable budget item\",\n\t);\n\tconst result = await api.budgetItem.replaceBudgetItem.mutate(input);\n\tout(result);\n};\n\nexport const approveUnavailableItemException = async (\n\tinput: RouterInputs[\"budgetItem\"][\"approveUnavailableItemException\"],\n): Promise<void> => {\n\tawait confirmLockedBudgetChangeByBudgetItemId(\n\t\tinput.budgetItemId,\n\t\t\"Approve unavailable item exception\",\n\t);\n\tconst result =\n\t\tawait api.budgetItem.approveUnavailableItemException.mutate(input);\n\tout(result);\n};\n\n/** One forward page of active budget categories (name A–Z): `{ items, pageInfo }`. */\nexport const getBudgetCategories = async (\n\tinput: RouterInputs[\"budget\"][\"searchBudgetCategories\"],\n): Promise<void> => {\n\tout(await api.budget.searchBudgetCategories.query(input));\n};\n\ninterface BudgetVersionListOptions {\n\tlimit?: number;\n\tcursor?: string;\n\tall?: boolean;\n}\n\nexport const getBudgetVersions = async (\n\tbudgetId: string,\n\toptions: BudgetVersionListOptions = {},\n): Promise<void> => {\n\tif (options.all && options.cursor !== undefined) {\n\t\tthrow new CliRuntimeError(\n\t\t\t\"USAGE\",\n\t\t\t\"--all cannot be combined with --cursor.\",\n\t\t);\n\t}\n\n\tconst versions: RouterOutputs[\"budgetVersion\"][\"getBudgetVersions\"][\"items\"] =\n\t\t[];\n\tconst seenCursors = new Set<string>();\n\tlet cursor: string | null | undefined = options.cursor;\n\tdo {\n\t\tconst page = await api.budgetVersion.getBudgetVersions.query({\n\t\t\tbudgetId,\n\t\t\tlimit: options.limit,\n\t\t\tcursor,\n\t\t});\n\t\tversions.push(...page.items);\n\t\tcursor = page.pageInfo.nextCursor;\n\t\tif (!options.all || cursor === null) break;\n\t\tif (seenCursors.has(cursor)) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Budget history pagination did not advance; export aborted.\",\n\t\t\t);\n\t\t}\n\t\tseenCursors.add(cursor);\n\t} while (cursor !== null);\n\n\t// The CLI keeps its documented `{ versions, nextCursor }` output shape.\n\tout({ versions, nextCursor: cursor ?? null });\n};\n\nexport async function createBudgetApproval(\n\tbudgetId: string,\n\tpreflight?: BudgetPreflightInput,\n): Promise<void> {\n\tawait assertSensitiveWorkflowConfirmed({\n\t\taction: \"Create budget approval request\",\n\t\tentity: `budget ${budgetId}`,\n\t\tdetails: \"and send approval request emails\",\n\t});\n\tawait confirmLockedBudgetChangeByBudgetId(budgetId, \"Create budget approval\");\n\tawait runBudgetPreflight(budgetId, preflight);\n\tawait assertBudgetActionReadiness({\n\t\tbudgetId,\n\t\trequireQuickbooksProject: false,\n\t\tactionLabel: \"request approval\",\n\t});\n\n\tconst result = await api.budget.createBudgetApproval.mutate({ budgetId });\n\tconst approvalIds = (result.results ?? []).map((item) => ({ id: item.id }));\n\n\tlet email: ApprovalEmailDeliveryReport;\n\tif (approvalIds.length === 0) {\n\t\temail = createApprovalEmailDeliveryFailure(\"No approval ids returned\");\n\t} else {\n\t\ttry {\n\t\t\tconst delivery = result.emailDelivery;\n\t\t\temail = createApprovalEmailDeliveryReport(delivery);\n\t\t} catch (error) {\n\t\t\temail = createApprovalEmailDeliveryFailure(\n\t\t\t\terror instanceof Error ? error.message : String(error),\n\t\t\t);\n\t\t}\n\t}\n\n\tout({\n\t\t...result,\n\t\temail,\n\t});\n}\n\nexport async function createEstimate(\n\tbudgetId: string,\n\tpreflight?: BudgetPreflightInput,\n): Promise<void> {\n\tawait confirmLockedBudgetChangeByBudgetId(budgetId, \"Create estimate\");\n\tawait runBudgetPreflight(budgetId, preflight);\n\tawait assertBudgetActionReadiness({\n\t\tbudgetId,\n\t\trequireQuickbooksProject: true,\n\t\tactionLabel: \"create estimate\",\n\t});\n\tconst result = await api.quickbooks.createEstimate.mutate({ budgetId });\n\tout(result);\n}\n\ntype EstimateEmailInput = RouterInputs[\"email\"][\"sendEstimateToContactPerson\"];\n\nexport const describeEstimateEmailConfirmation = (\n\tinput: EstimateEmailInput,\n): string =>\n\t`to ${input.to}; CC ${input.cc.length > 0 ? input.cc.join(\", \") : \"none\"}; reply-to ${input.replyTo}; subject \"${input.subject}\"; queue durable worker delivery with the QBO estimate PDF, terms and conditions, and Budget Builder attachments; mark the estimate sent after provider acceptance`;\n\nexport const sendEstimateToContactPersonFromPayload = async (\n\traw: unknown,\n): Promise<void> => {\n\tconst input = parseSendEstimateToContactPersonPayload(raw);\n\tawait assertSensitiveWorkflowConfirmed({\n\t\taction: \"Send estimate email\",\n\t\tentity: `budget ${input.budgetId}`,\n\t\tdetails: describeEstimateEmailConfirmation(input),\n\t});\n\tconst result = await api.email.sendEstimateToContactPerson.mutate(input);\n\tout(result);\n};\n\nexport async function getBudgetDetails(\n\tbudgetId: string,\n\topts?: { includeInactive?: boolean },\n): Promise<void> {\n\tconst detail = await api.budget.getBudgetDetail.query({\n\t\tid: budgetId,\n\t\tincludeInactive: opts?.includeInactive ?? false,\n\t});\n\tout(detail);\n}\n\nexport async function createBudgetFromPayload(raw: unknown): Promise<void> {\n\tconst input = parseCreateBudgetPayload(raw);\n\tlet result: Awaited<ReturnType<typeof api.budget.createBudget.mutate>>;\n\ttry {\n\t\tresult = await api.budget.createBudget.mutate(input);\n\t} catch (error) {\n\t\tconst uncertain = budgetCreateUncertainError(error, input);\n\t\tif (uncertain) throw uncertain;\n\t\tthrow error;\n\t}\n\tout(result);\n}\n\nexport async function updateBudgetFromPayload(raw: unknown): Promise<void> {\n\tconst input = parseUpdateBudgetPayload(raw);\n\tawait confirmLockedBudgetChangeByBudgetId(input.id, \"Update budget\");\n\tconst result = await api.budget.updateBudget.mutate(input);\n\tout(result);\n}\n\nexport async function deleteBudgetById(budgetId: string): Promise<void> {\n\tawait confirmLockedBudgetChangeByBudgetId(budgetId, \"Delete budget\");\n\tconst result = await api.budget.deleteBudget.mutate({ id: budgetId });\n\tout(result);\n}\n\nexport async function deleteProjectById(projectId: string): Promise<void> {\n\tconst result = await api.project.deleteProject.mutate({ id: projectId });\n\tout(result);\n}\n\nexport async function deleteCompanyById(companyId: string): Promise<void> {\n\tconst result = await api.company.deleteCompany.mutate({ id: companyId });\n\tout(result);\n}\n\nexport async function reorderBudgetItemsCli(opts: {\n\tbudgetId: string;\n\titemIds: string[];\n}): Promise<void> {\n\tawait confirmLockedBudgetChangeByBudgetId(\n\t\topts.budgetId,\n\t\t\"Reorder budget items\",\n\t);\n\tconst result = await api.budgetItem.reorderBudgetItems.mutate(opts);\n\tout(result);\n}\n\nexport async function updateBudgetItemSupplierCli(opts: {\n\tbudgetItemId: string;\n\tsupplierId: string;\n}): Promise<void> {\n\tawait confirmLockedBudgetChangeByBudgetItemId(\n\t\topts.budgetItemId,\n\t\t\"Update budget item supplier\",\n\t);\n\tconst result = await api.budgetItem.updateBudgetItemSupplier.mutate(opts);\n\tout(result);\n}\n\nexport async function createBudgetCategory(name: string): Promise<void> {\n\tconst result = await api.budget.createBudgetCategory.mutate({ name });\n\tout(result);\n}\n\nexport async function updateBudgetCategory(opts: {\n\tid: string;\n\tname: string;\n}): Promise<void> {\n\tconst result = await api.budget.updateBudgetCategory.mutate(opts);\n\tout(result);\n}\n\nexport async function deleteBudgetCategory(id: string): Promise<void> {\n\tconst result = await api.budget.deleteBudgetCategory.mutate({ id });\n\tout(result);\n}\n\nexport async function updateBudgetCommissionFromPayload(\n\traw: unknown,\n): Promise<void> {\n\tconst input = parseUpdateBudgetCommissionPayload(raw);\n\tawait confirmLockedBudgetChangeByBudgetId(\n\t\tinput.budgetId,\n\t\t\"Update budget commission\",\n\t);\n\tconst result = await api.budget.updateBudgetCommission.mutate(input);\n\tout(result);\n}\n\nexport async function updateBudgetDiscountFromPayload(\n\traw: unknown,\n): Promise<void> {\n\tconst input = parseBudgetDiscountPayload(raw);\n\tawait confirmLockedBudgetChangeByBudgetId(\n\t\tinput.budgetId,\n\t\t\"Update budget discount\",\n\t);\n\tconst result = await api.budget.updateBudgetDiscount.mutate(input);\n\tout(result);\n}\n\nexport const deleteBudgetDiscount = async (budgetId: string): Promise<void> => {\n\tawait assertSensitiveWorkflowConfirmed({\n\t\taction: \"Remove budget discount\",\n\t\tentity: `budget ${budgetId}`,\n\t\tdetails: \"and return the budget to DRAFT\",\n\t});\n\tconst result = await api.budget.deleteBudgetDiscount.mutate({ budgetId });\n\tout(result);\n};\n\nexport const deleteBudgetCommission = async (\n\tbudgetId: string,\n): Promise<void> => {\n\tawait assertSensitiveWorkflowConfirmed({\n\t\taction: \"Remove budget commission\",\n\t\tentity: `budget ${budgetId}`,\n\t\tdetails: \"and return the budget to DRAFT\",\n\t});\n\tconst result = await api.budget.deleteBudgetCommission.mutate({ budgetId });\n\tout(result);\n};\n\nexport const setBudgetItemsNotUtilized = async (\n\tbudgetItemIds: string[],\n\tnotUtilized: boolean,\n): Promise<void> => {\n\tawait assertSensitiveWorkflowConfirmed({\n\t\taction: notUtilized\n\t\t\t? \"Mark budget lines Not Utilized\"\n\t\t\t: \"Restore budget line\",\n\t\tentity: `budget item${budgetItemIds.length === 1 ? \"\" : \"s\"} ${budgetItemIds.join(\", \")}`,\n\t\tdetails: notUtilized\n\t\t\t? \"and queue removal of linked QuickBooks placeholder expenses\"\n\t\t\t: \"and queue restoring its QuickBooks placeholder expense when required\",\n\t});\n\tconst result = await api.budget.setBudgetItemsNotUtilized.mutate({\n\t\tbudgetItemIds,\n\t\tnotUtilized,\n\t});\n\tout(result);\n};\n\nexport const createPlaceholderBillForBudgetItem = async (\n\tbudgetItemId: string,\n): Promise<void> => {\n\tawait assertSensitiveWorkflowConfirmed({\n\t\taction: \"Queue QuickBooks placeholder bill\",\n\t\tentity: `budget item ${budgetItemId}`,\n\t});\n\tconst result = await api.budget.createPlaceholderBillForBudgetItem.mutate({\n\t\tbudgetItemId,\n\t});\n\tout(result);\n};\n\nexport const renameBudgetVersion = async (\n\tversionId: string,\n\tnewName: string,\n): Promise<void> => {\n\tconst result = await api.budgetVersion.renameBudgetVersion.mutate({\n\t\tversionId,\n\t\tnewName,\n\t});\n\tout(result);\n};\n\nexport const restoreBudgetVersion = async (\n\tversionId: string,\n): Promise<void> => {\n\tawait assertSensitiveWorkflowConfirmed({\n\t\taction: \"Restore budget version\",\n\t\tentity: `budget version ${versionId}`,\n\t\tdetails:\n\t\t\t\"replace the current budget, project fields, items, and attachments, clear its QuickBooks estimate link, and return it to DRAFT\",\n\t});\n\tconst result = await api.budgetVersion.restoreBudgetVersion.mutate({\n\t\tversionId,\n\t});\n\tout(result);\n};\n\nexport async function deleteItemById(itemId: string): Promise<void> {\n\tconst result = await api.item.deleteItem.mutate({ id: itemId });\n\tout(result);\n}\n\nexport async function archiveItemsByIds(ids: string[]): Promise<void> {\n\tconst result = await api.item.archiveItems.mutate({ ids });\n\tout(result);\n}\n\nexport async function deleteSuppliersByIds(ids: string[]): Promise<void> {\n\tconst result = await api.supplier.deleteSuppliers.mutate({ ids });\n\tout(result);\n}\n\nexport async function reactivateSuppliersByIds(ids: string[]): Promise<void> {\n\tconst result = await api.supplier.reactivateSuppliers.mutate({ ids });\n\tout(result);\n}\n\nexport async function createSupplierCertification(name: string): Promise<void> {\n\tconst result = await api.supplier.createCertification.mutate({ name });\n\tout(result);\n}\n\nexport async function createSupplierPaymentMethod(name: string): Promise<void> {\n\tconst result = await api.supplier.createPaymentMethod.mutate({ name });\n\tout(result);\n}\n\nexport async function createSupplierRoleOption(name: string): Promise<void> {\n\tconst result = await api.supplier.createSupplierRole.mutate({ name });\n\tout(result);\n}\n\nexport async function createSupplierTagOption(name: string): Promise<void> {\n\tconst result = await api.supplier.createSupplierTag.mutate({ name });\n\tout(result);\n}\n\nexport async function createItemCategory(name: string): Promise<void> {\n\tconst result = await api.itemCategory.createItemCategory.mutate({\n\t\tname: parseQuickBooksName(name),\n\t});\n\tout(result);\n}\n\nexport async function updateItemCategory(opts: {\n\tid: string;\n\tname: string;\n}): Promise<void> {\n\tconst result = await api.itemCategory.updateItemCategory.mutate({\n\t\t...opts,\n\t\tname: parseQuickBooksName(opts.name),\n\t});\n\tout(result);\n}\n\nexport async function deleteItemCategoriesByIds(ids: string[]): Promise<void> {\n\tconst result = await api.itemCategory.deleteItemCategories.mutate({ ids });\n\tout(result);\n}\n\nexport async function createBillFromPayload(\n\traw: unknown,\n\tdraftOnlyFlag?: boolean,\n\tquotationExempt = false,\n): Promise<void> {\n\tconst input = parseCreateBillPayload(raw, draftOnlyFlag, quotationExempt);\n\tawait confirmCurrentCommand({\n\t\taction: input.draftOnly ? \"bill create (draft only)\" : \"bill create\",\n\t\ttarget: `project ${input.projectId}, supplier ${input.supplierId}`,\n\t\teffects: [\n\t\t\t\"state-change\",\n\t\t\t\"financial-write\",\n\t\t\t...(input.draftOnly ? [] : ([\"external-write\"] as const)),\n\t\t\t...(input.alreadyPaid ? ([\"email\"] as const) : []),\n\t\t],\n\t\tdetails: input.draftOnly\n\t\t\t? \"Create a DRAFT bill without approval, email, or QuickBooks writes.\"\n\t\t\t: \"Uses the caller's normal bill creation workflow; Accounting auto-checks and Admin auto-approves unpaid bills and queues their QuickBooks bill.\",\n\t});\n\t// A dedicated route makes older servers fail closed instead of ignoring draftOnly.\n\tconst result = input.draftOnly\n\t\t? await api.bill.createDraft.mutate({\n\t\t\t\t...input,\n\t\t\t\tdraftOnly: true,\n\t\t\t\talreadyPaid: false,\n\t\t\t})\n\t\t: await api.bill.create.mutate(input);\n\tout(result);\n}\n\nexport const listQuotations = async (\n\tinput: RouterInputs[\"quotation\"][\"listPage\"],\n): Promise<void> => {\n\tout(await api.quotation.listPage.query(input));\n};\n\nexport const countQuotations = async (\n\tinput: RouterInputs[\"quotation\"][\"getCounts\"],\n): Promise<void> => {\n\tout(await api.quotation.getCounts.query(input));\n};\n\nexport async function getQuotationDetails(id: string): Promise<void> {\n\tconst result = await api.quotation.getById.query({ id });\n\tout(result);\n}\n\n/** One newest-first page of a quotation's line items: `{ items, pageInfo }`. */\nexport const getQuotationLineItems = async (\n\tinput: RouterInputs[\"quotation\"][\"getLineItems\"],\n): Promise<void> => {\n\tout(await api.quotation.getLineItems.query(input));\n};\n\nexport async function createQuotationFromPayload(raw: unknown): Promise<void> {\n\tconst input = parseCreateQuotationPayload(raw);\n\tconst result = await api.quotation.createDraft.mutate(input);\n\tout(result);\n}\n\nexport const updateQuotationFromPayload = async (\n\traw: unknown,\n): Promise<void> => {\n\tconst input = parseUpdateQuotationPayload(raw);\n\tconst result = await api.quotation.updateDraftOrRejected.mutate(input);\n\tout(result);\n};\n\nexport const deleteQuotationById = async (id: string): Promise<void> => {\n\tconst result = await api.quotation.delete.mutate({ id });\n\tout(result);\n};\n\nexport async function submitQuotation(\n\tid: string,\n\toverBudgetOverrideReason?: string,\n): Promise<void> {\n\tawait assertSensitiveWorkflowConfirmed({\n\t\taction: \"Submit quotation for approval\",\n\t\tentity: `quotation ${id}`,\n\t});\n\tconst result = await api.quotation.submitForApproval.mutate({\n\t\tid,\n\t\toverBudgetOverrideReason,\n\t});\n\tout(result);\n}\n\nexport async function downloadQuotationPdf(\n\tid: string,\n\tfileRole: RouterInputs[\"quotation\"][\"getSignedDownloadUrl\"][\"fileRole\"],\n): Promise<void> {\n\tconst result = await api.quotation.getSignedDownloadUrl.query({\n\t\tid,\n\t\tfileRole,\n\t});\n\tout(result);\n}\n\nexport const checkCustomerInvoiceReadiness = async (\n\tbudgetId: string,\n): Promise<void> => {\n\tconst result = await api.customerInvoice.getInvoiceReadiness.query({\n\t\tbudgetId,\n\t\tincludePreview: true,\n\t});\n\tout(result);\n};\n\nexport const listCustomerInvoices = async (\n\tinput: RouterInputs[\"customerInvoice\"][\"list\"],\n): Promise<void> => {\n\tout(await api.customerInvoice.list.query(input));\n};\n\nexport const countCustomerInvoices = async (\n\tinput: RouterInputs[\"customerInvoice\"][\"getCounts\"],\n): Promise<void> => {\n\tout(await api.customerInvoice.getCounts.query(input));\n};\n\nexport const listEligibleCustomerInvoiceBudgets = async (\n\tprojectId: string,\n): Promise<void> => {\n\tconst result = await api.customerInvoice.getEligibleBudgets.query({\n\t\tprojectId,\n\t});\n\tout(result);\n};\n\nexport const previewCustomerInvoiceAmount = async (\n\tbudgetId: string,\n\tpercentage: number,\n): Promise<void> => {\n\tconst result = await api.customerInvoice.getInvoiceAmountPreview.query({\n\t\tbudgetId,\n\t\tpercentage,\n\t});\n\tout(result);\n};\n\nexport const listAvailableQboCustomerInvoices = async (\n\tbudgetId: string,\n): Promise<void> => {\n\tconst result = await api.customerInvoice.getExistingInvoiceCandidates.query({\n\t\tbudgetId,\n\t});\n\tout(result);\n};\n\nexport const getCustomerInvoice = async (batchId: string): Promise<void> => {\n\tconst result = await api.customerInvoice.getInvoiceDetail.query({ batchId });\n\tout(result);\n};\n\n/** A batch's invoices with QuickBooks identity, dates and sync state. */\nexport const getCustomerInvoiceInvoices = async (\n\tbatchId: string,\n): Promise<void> => {\n\tout(await api.customerInvoice.getInvoices.query({ batchId }));\n};\n\n/** One newest-first page of one invoice's lines: `{ items, pageInfo }`. */\nexport const getCustomerInvoiceLines = async (\n\tinput: RouterInputs[\"customerInvoice\"][\"getInvoiceLines\"],\n): Promise<void> => {\n\tout(await api.customerInvoice.getInvoiceLines.query(input));\n};\n\n/** One newest-first page of a batch's approval requests: `{ items, pageInfo }`. */\nexport const getCustomerInvoiceApprovals = async (\n\tinput: RouterInputs[\"customerInvoice\"][\"getApprovals\"],\n): Promise<void> => {\n\tout(await api.customerInvoice.getApprovals.query(input));\n};\n\n/** One newest-first page of a batch's status history: `{ items, pageInfo }`. */\nexport const getCustomerInvoiceHistory = async (\n\tinput: RouterInputs[\"customerInvoice\"][\"getHistory\"],\n): Promise<void> => {\n\tout(await api.customerInvoice.getHistory.query(input));\n};\n\n/** Payments QuickBooks applied to one invoice, with attachment names; read live from QuickBooks. */\nexport const getCustomerInvoicePayments = async (\n\tinvoiceId: string,\n): Promise<void> => {\n\tout(await api.customerInvoice.getPayments.query({ invoiceId }));\n};\n\nexport const getCustomerInvoiceEmailContext = async (\n\tbatchId: string,\n): Promise<void> => {\n\tconst result = await api.customerInvoice.getInvoiceEmailContext.query({\n\t\tbatchId,\n\t});\n\tout(result);\n};\n\nexport const previewQboCustomerInvoice = async (\n\tinput: RouterInputs[\"customerInvoice\"][\"previewExistingInvoice\"],\n): Promise<void> => {\n\tconst result = await api.customerInvoice.previewExistingInvoice.mutate(input);\n\tout(result);\n};\n\nexport const importQboCustomerInvoice = async (\n\tinput: RouterInputs[\"customerInvoice\"][\"linkExistingInvoice\"],\n): Promise<void> => {\n\tawait confirmCurrentCommand({\n\t\taction: \"Link existing QuickBooks invoice\",\n\t\ttarget: `QuickBooks invoice ${input.qboInvoiceId} to budget ${input.budgetId}`,\n\t\tdetails:\n\t\t\t\"records the reviewed invoice in Budget Builder only; QuickBooks access is read-only; preserves original evidence and revalidates the preview token\",\n\t});\n\tconst result = await api.customerInvoice.linkExistingInvoice.mutate(input);\n\tout(result);\n};\n\nexport const createCustomerInvoice = async (raw: unknown): Promise<void> => {\n\tconst input = parseCreateCustomerInvoicePayload(raw);\n\tconst readiness = await api.customerInvoice.getInvoiceReadiness.query({\n\t\tbudgetId: input.budgetId,\n\t\tincludePreview: true,\n\t});\n\tif (!readiness.ready) {\n\t\tthrow new CliRuntimeError(\n\t\t\t\"VALIDATION\",\n\t\t\treadiness.issues.join(\"; \") || \"Invoice is not ready for creation.\",\n\t\t);\n\t}\n\tawait assertSensitiveWorkflowConfirmed({\n\t\taction: \"Create customer invoice\",\n\t\tentity: `budget ${input.budgetId}`,\n\t\tdetails: `queues ${input.splits.length} invoice(s) for creation in QuickBooks from the budget's remaining uninvoiced balance: ${input.splits.map((split) => `${split.label} (${split.percentage}% of the estimate), due ${new Date(split.dueDate).toISOString().slice(0, 10)}`).join(\"; \")}. Admin creation is auto-approved; other creators request approval. No customer email is sent.`,\n\t});\n\tconst result = await api.customerInvoice.createInvoiceBatch.mutate(input);\n\tout(result);\n};\n\nexport const resubmitCustomerInvoice = async (\n\tbatchId: string,\n): Promise<void> => {\n\tawait assertSensitiveWorkflowConfirmed({\n\t\taction: \"Resubmit expired customer invoice\",\n\t\tentity: `invoice batch ${batchId}`,\n\t\tdetails:\n\t\t\t\"queues one replacement QuickBooks invoice after confirmed expiry voiding, using the current estimate and the original percentage, due date and details; only the original requester may resubmit; no customer email is sent\",\n\t});\n\tout(await api.customerInvoice.resubmitInvoiceBatch.mutate({ batchId }));\n};\n\nexport const discardCreatingCustomerInvoice = async (\n\tbatchId: string,\n): Promise<void> => {\n\tawait assertSensitiveWorkflowConfirmed({\n\t\taction: \"Discard unfinished customer invoice\",\n\t\tentity: `invoice batch ${batchId}`,\n\t\tdetails:\n\t\t\t\"removes only a reserved CREATING batch that has no invoice created in QuickBooks\",\n\t});\n\tconst result = await api.customerInvoice.discardCreatingInvoiceBatch.mutate({\n\t\tbatchId,\n\t});\n\tout(result);\n};\n\nexport const deleteCustomerInvoice = async (batchId: string): Promise<void> => {\n\tawait assertSensitiveWorkflowConfirmed({\n\t\taction: \"Delete customer invoice\",\n\t\tentity: `invoice batch ${batchId}`,\n\t\tdetails:\n\t\t\t\"queues deletion of its invoices in QuickBooks; the local batch is removed once QuickBooks confirms; paid invoices are blocked until their QBO payments are reversed; removing approved coverage may reopen the estimate\",\n\t});\n\tconst result = await api.customerInvoice.deleteInvoiceBatch.mutate({\n\t\tbatchId,\n\t});\n\tout(result);\n};\n\nexport const voidCustomerInvoice = async (batchId: string): Promise<void> => {\n\tawait assertSensitiveWorkflowConfirmed({\n\t\taction: \"Void customer invoice\",\n\t\tentity: `invoice batch ${batchId}`,\n\t\tdetails:\n\t\t\t\"queues a void of its invoices in QuickBooks; Budget Builder updates once QuickBooks confirms; paid invoices are blocked until their QBO payments are reversed; removing approved coverage may reopen the estimate\",\n\t});\n\tconst result = await api.customerInvoice.voidInvoiceBatch.mutate({ batchId });\n\tout(result);\n};\n\nexport const approveCustomerInvoice = async (\n\tbatchId: string,\n): Promise<void> => {\n\tawait assertSensitiveWorkflowConfirmed({\n\t\taction: \"Approve customer invoice\",\n\t\tentity: `invoice batch ${batchId}`,\n\t\tdetails:\n\t\t\t\"approves the batch and notifies its creator; voided invoices cannot be approved; cumulative approved coverage of 100% closes the QuickBooks estimate\",\n\t});\n\tconst result = await api.customerInvoice.approveInvoiceBatch.mutate({\n\t\tbatchId,\n\t});\n\tout(result);\n};\n\nexport const rejectCustomerInvoice = async (\n\tbatchId: string,\n\trejectionReason: string,\n): Promise<void> => {\n\tawait assertSensitiveWorkflowConfirmed({\n\t\taction: \"Reject customer invoice\",\n\t\tentity: `invoice batch ${batchId}`,\n\t\tdetails: `queues a void of its invoices in QuickBooks; once QuickBooks confirms, records the rejection reason, notifies its creator, and reopens a prematurely closed estimate when applicable`,\n\t});\n\tconst result = await api.customerInvoice.rejectInvoiceBatch.mutate({\n\t\tbatchId,\n\t\trejectionReason,\n\t});\n\tout(result);\n};\n\nexport const downloadCustomerInvoicePdf = async (\n\tinvoiceId: string,\n\toutputPath?: string,\n): Promise<void> => {\n\tconst result = await api.customerInvoice.downloadPdf.mutate({ invoiceId });\n\tconst resolvedOutputPath = outputPath?.trim() || result.fileName;\n\tconst contents = Buffer.from(result.base64, \"base64\");\n\tawait writeFile(resolvedOutputPath, contents);\n\tout({\n\t\tcontentType: result.contentType,\n\t\tfileName: result.fileName,\n\t\toutputPath: resolvedOutputPath,\n\t\tsize: contents.byteLength,\n\t});\n};\n\nexport const syncCustomerInvoice = async (invoiceId: string): Promise<void> => {\n\tawait assertSensitiveWorkflowConfirmed({\n\t\taction: \"Sync customer invoice from QuickBooks\",\n\t\tentity: `invoice ${invoiceId}`,\n\t\tdetails:\n\t\t\t\"refreshes local status, QuickBooks metadata, balance, and history; QBO Paid or a zero balance becomes PAID, a reversed payment restores the delivery or approval status, and a QBO void becomes VOIDED\",\n\t});\n\tconst result = await api.customerInvoice.syncInvoiceStatus.mutate({\n\t\tinvoiceId,\n\t});\n\tout(result);\n};\n\n/**\n * Edit a BB-created invoice's bill-to address and memo. Saved in BB, then a\n * queued job updates QuickBooks. The bill email is not editable here:\n * QuickBooks is its source.\n */\nexport const updateCustomerInvoiceDetails = async ({\n\tbillingAddress,\n\tcustomerMemo,\n\tinvoiceId,\n\trequestId = randomUUID(),\n}: {\n\tbillingAddress: string;\n\tcustomerMemo: string;\n\tinvoiceId: string;\n\trequestId?: string;\n}): Promise<void> => {\n\tawait assertSensitiveWorkflowConfirmed({\n\t\taction: \"Update customer invoice billing details\",\n\t\tentity: `invoice ${invoiceId}`,\n\t\tdetails: `saves the bill-to address and memo in BB, then queues a QuickBooks invoice update (external write); the bill email is managed in QuickBooks and is not changed; retry a lost response with --requestId ${requestId}`,\n\t});\n\tconst result = await api.customerInvoice.updateInvoiceDetails.mutate({\n\t\tbillingAddress,\n\t\tcustomerMemo,\n\t\tinvoiceId,\n\t\trequestId,\n\t});\n\tout({\n\t\tinvoices: result.batch.invoices.filter(\n\t\t\t(invoice) => invoice.id === invoiceId,\n\t\t),\n\t\toperation: result.operation,\n\t});\n};\n\n/**\n * Admin decision for QuickBooks changes that status sync held back.\n * ACCEPT_QBO writes BB only; KEEP_BB queues BB's address and memo to QuickBooks.\n */\nexport const updateCustomerInvoiceQboDrift = async ({\n\tinvoiceId,\n\trequestId,\n\tresolution,\n}: {\n\tinvoiceId: string;\n\trequestId?: string;\n\tresolution: \"ACCEPT_QBO\" | \"KEEP_BB\";\n}): Promise<void> => {\n\tconst keepRequestId =\n\t\tresolution === \"KEEP_BB\" ? (requestId ?? randomUUID()) : undefined;\n\tawait assertSensitiveWorkflowConfirmed({\n\t\taction:\n\t\t\tresolution === \"ACCEPT_QBO\"\n\t\t\t\t? \"Accept QuickBooks invoice changes into BB\"\n\t\t\t\t: \"Keep BB invoice values over QuickBooks changes\",\n\t\tentity: `invoice ${invoiceId}`,\n\t\tdetails:\n\t\t\tresolution === \"ACCEPT_QBO\"\n\t\t\t\t? \"copies the held QuickBooks bill-to address, memo, bill email and total into BB; QuickBooks is not changed\"\n\t\t\t\t: `keeps BB's values; queues BB's bill-to address and memo to QuickBooks (external write); bill email and total are not changed in QuickBooks; retry a lost response with --requestId ${keepRequestId}`,\n\t});\n\tconst result = await api.customerInvoice.resolveQboDrift.mutate({\n\t\tinvoiceId,\n\t\tresolution,\n\t\t...(keepRequestId ? { requestId: keepRequestId } : {}),\n\t});\n\tout(result);\n};\n\nexport const markCustomerInvoiceSentExternally = async (\n\tinput: RouterInputs[\"customerInvoice\"][\"markSentExternally\"],\n): Promise<void> => {\n\tawait assertSensitiveWorkflowConfirmed({\n\t\taction: \"Record customer invoice as sent externally\",\n\t\tentity: `invoice ${input.invoiceId}`,\n\t\tdetails: `records the invoice as SENT (source EXTERNAL) at ${input.sentAt} for ${input.recipients.join(\", \")}; sends no email and does not write to QuickBooks`,\n\t});\n\tconst result = await api.customerInvoice.markSentExternally.mutate(input);\n\tout(result);\n};\n\ntype CustomerInvoiceEmailInput =\n\tRouterInputs[\"customerInvoice\"][\"sendInvoiceToContactPerson\"];\n\nexport const describeCustomerInvoiceEmailConfirmation = (\n\tinput: CustomerInvoiceEmailInput,\n): string =>\n\t`emails the QBO invoice PDF to ${input.to} and saves that address as the project's billing email; requested CC ${\n\t\tinput.cc === undefined\n\t\t\t? \"company billing defaults\"\n\t\t\t: input.cc.length > 0\n\t\t\t\t? input.cc.join(\", \")\n\t\t\t\t: \"none (company billing defaults removed)\"\n\t}; reply-to ${input.replyTo}; subject \"${input.subject}\"; server-required admin, creator, business-development, and inside-sales CC recipients are added; success marks the invoice SENT; do not retry blindly after an ambiguous delivery failure`;\n\nexport const sendCustomerInvoiceToContactPersonFromPayload = async (\n\traw: unknown,\n): Promise<void> => {\n\tconst input = parseSendCustomerInvoiceToContactPersonPayload(raw);\n\tawait assertSensitiveWorkflowConfirmed({\n\t\taction: \"Send customer invoice email\",\n\t\tentity: `invoice ${input.invoiceId}`,\n\t\tdetails: describeCustomerInvoiceEmailConfirmation(input),\n\t});\n\tconst result =\n\t\tawait api.customerInvoice.sendInvoiceToContactPerson.mutate(input);\n\tout(result);\n};\n\nexport async function updateBillFromPayload(raw: unknown): Promise<void> {\n\tconst input = parseUpdateBillPayload(raw);\n\tconst result = await api.bill.update.mutate(input);\n\tout(result);\n}\n\nexport const validateBillSelectionFromPayload = async (\n\traw: unknown,\n\tquotationFlags?: { quotationId?: string; quotationIds?: string[] },\n): Promise<void> => {\n\tconst input = parseValidateBillSelectionPayload(raw, quotationFlags);\n\tconst result = await api.bill.validateSelection.mutate(input);\n\tout(result);\n};\n\nexport const linkBillQuotations = async (\n\tbillId: string,\n\traw: unknown,\n): Promise<void> => {\n\tconst input = parseLinkBillQuotationsPayload(billId, raw);\n\tconst result = await api.bill.linkQuotations.mutate(input);\n\tout(result);\n};\n\nexport const updateBillPaymentEvidenceFromPayload = async (\n\traw: unknown,\n): Promise<void> => {\n\tconst input = parseUpdateBillPaymentEvidencePayload(raw);\n\tconst result = await api.bill.updatePaymentEvidence.mutate(input);\n\tout(result);\n};\n\nexport async function deleteBillById(id: string): Promise<void> {\n\tconst result = await api.bill.delete.mutate({ id });\n\tout(result);\n}\n\nexport async function createSupplierFromPayload(raw: unknown): Promise<void> {\n\tconst input = parseSupplierCreatePayload(raw);\n\tawait assertSensitiveWorkflowConfirmed({\n\t\taction: \"Create supplier and request approval if required\",\n\t\tentity: `supplier ${input.name}`,\n\t\tdetails:\n\t\t\t\"creates the supplier first; pending-approval suppliers also request approval and send emails\",\n\t});\n\tlet created: Awaited<ReturnType<typeof api.supplier.createSupplier.mutate>>;\n\ttry {\n\t\tcreated = await api.supplier.createSupplier.mutate(input);\n\t} catch (error) {\n\t\tconst normalized = normalizeCliError(error);\n\t\tif (normalized.code !== \"NETWORK\" && normalized.code !== \"API\") {\n\t\t\tthrow error;\n\t\t}\n\t\tthrow new CliRuntimeError(\n\t\t\tnormalized.code,\n\t\t\t`Supplier creation outcome is uncertain for ${JSON.stringify(input.name)}. Run list-suppliers and inspect matching supplier details before retrying; names may not be unique, so do not retry create-supplier until you can verify that no supplier was created. Original error: ${normalized.message}`,\n\t\t);\n\t}\n\n\tconst supplier = created.result as {\n\t\tid: string;\n\t\tstatus?: string;\n\t};\n\n\t// An auto-approved supplier waits as PENDING_APPROVAL only for its queued\n\t// QuickBooks vendor job (quickBooksSyncQueued); it needs no approval request.\n\tif (\n\t\tsupplier.status !== ApprovalStatus.PENDING_APPROVAL ||\n\t\t(\"quickBooksSyncQueued\" in created && created.quickBooksSyncQueued)\n\t) {\n\t\tout(created);\n\t\treturn;\n\t}\n\n\tlet approval: Awaited<\n\t\tReturnType<typeof api.supplier.createSupplierApproval.mutate>\n\t>;\n\ttry {\n\t\tapproval = await api.supplier.createSupplierApproval.mutate({\n\t\t\tsupplierId: supplier.id,\n\t\t});\n\t} catch (error) {\n\t\tthrow new CliRuntimeError(\n\t\t\t\"API\",\n\t\t\t`Supplier ${supplier.id} was created, but the approval request did not complete or its outcome is uncertain. Run get-supplier-details ${supplier.id} and inspect its approvals before retrying; do not run create-supplier again. Original error: ${normalizeCliError(error).message}`,\n\t\t);\n\t}\n\n\tlet emailResult: ApprovalEmailDeliveryReport;\n\tconst approvalIds = (approval.results ?? []).map((item) => ({ id: item.id }));\n\n\tif (approvalIds.length === 0) {\n\t\tthrow new CliRuntimeError(\n\t\t\t\"API\",\n\t\t\t`Supplier ${supplier.id} was created, but the approval request returned no approval IDs. Run get-supplier-details ${supplier.id} and inspect its approvals before retrying the approval request; do not run create-supplier again.`,\n\t\t);\n\t}\n\ttry {\n\t\tconst delivery = approval.emailDelivery;\n\t\temailResult = createApprovalEmailDeliveryReport(delivery);\n\t} catch (error) {\n\t\temailResult = createApprovalEmailDeliveryFailure(\n\t\t\terror instanceof Error ? error.message : String(error),\n\t\t);\n\t}\n\n\tout({\n\t\t...created,\n\t\tsupplierApproval: {\n\t\t\trequested: true,\n\t\t\tapprovalCount: approvalIds.length,\n\t\t\temail: emailResult,\n\t\t},\n\t});\n}\n\nexport async function updateSupplierFromPayload(raw: unknown): Promise<void> {\n\tconst input = parseSupplierUpdatePayload(raw);\n\tawait assertSensitiveWorkflowConfirmed({\n\t\taction: \"Update supplier\",\n\t\tentity: `supplier ${input.id}`,\n\t\tdetails:\n\t\t\t\"Normal-user edits also request approval and queue approval emails.\",\n\t});\n\tconst updated = await api.supplier.updateSupplier.mutate(input);\n\t// The server commits revisions, approval requests and email intents atomically.\n\tout(updated);\n}\n\nexport async function createItemFromPayload(raw: unknown): Promise<void> {\n\tconst input = parseItemCreatePayload(raw);\n\tconst result = await api.item.createItem.mutate(input);\n\tout(result);\n}\n\nexport async function updateItemFromPayload(raw: unknown): Promise<void> {\n\tconst input = parseItemUpdatePayload(raw);\n\tconst result = await api.item.updateItem.mutate(input);\n\tout(result);\n}\n\nexport async function createContactPersonFromPayload(\n\traw: unknown,\n): Promise<void> {\n\tconst input = parseContactCreatePayload(raw);\n\tconst result = await api.contactPerson.createContactPerson.mutate(input);\n\tout(result);\n}\n\nexport async function updateContactPersonFromPayload(\n\traw: unknown,\n): Promise<void> {\n\tconst input = parseContactUpdatePayload(raw);\n\tconst result = await api.contactPerson.updateContactPerson.mutate(input);\n\tout(result);\n}\n\nexport async function updateProjectFromPayload(raw: unknown): Promise<void> {\n\tconst input = parseUpdateProjectPayload(raw);\n\tconst result = await updateProjectWithEstimateInvalidationConfirmation(input);\n\tout(result);\n}\n\nexport const getCompanyQuickBooksSyncStatus = async (\n\tcompanyId: string,\n): Promise<void> => {\n\tconst result = await api.company.getQuickBooksSyncStatus.query({ companyId });\n\tout(result);\n};\n\nexport async function updateCompanyFromPayload(raw: unknown): Promise<void> {\n\tconst input = parseCompanyUpdatePayload(raw);\n\tconst result = await api.company.updateCompany.mutate(input);\n\tout(result);\n}\n\n// --- Approvals: budgets / suppliers / bills (MCP parity) ---\n\nexport async function approveBudget(budgetId: string): Promise<void> {\n\tawait assertSensitiveWorkflowConfirmed({\n\t\taction: \"Approve budget\",\n\t\tentity: `budget ${budgetId}`,\n\t\tdetails: \"and send requester reply email\",\n\t});\n\tconst notifications = await getAllNotifications();\n\tconst pending = notifications.filter(\n\t\t(n) =>\n\t\t\tn.notificationType === \"request\" &&\n\t\t\tn.status === ExtendedApprovalStatus.PENDING_APPROVAL &&\n\t\t\tn.type === ExtendedApprovalType.BUDGET &&\n\t\t\t(n.budgetId === budgetId ||\n\t\t\t\t(n.budget as { id?: string } | undefined)?.id === budgetId),\n\t);\n\tconst approval = pending[0];\n\tif (!approval) {\n\t\tthrow new Error(\n\t\t\t\"No pending budget approval found for this budget and approver.\",\n\t\t);\n\t}\n\tconst result = await api.budget.updateBudgetApproval.mutate({\n\t\tbudgetApprovalId: approval.id,\n\t\tstatus: ExtendedApprovalStatus.APPROVED,\n\t});\n\tlet email: ApprovalEmailDeliveryReport;\n\ttry {\n\t\tconst delivery = result.emailDelivery;\n\t\temail = createApprovalEmailDeliveryReport(delivery);\n\t} catch (error) {\n\t\temail = createApprovalEmailDeliveryFailure(\n\t\t\terror instanceof Error ? error.message : String(error),\n\t\t);\n\t}\n\tout({\n\t\t...result,\n\t\temail,\n\t});\n}\n\nexport async function rejectBudget(\n\tbudgetId: string,\n\treason: string,\n): Promise<void> {\n\tawait assertSensitiveWorkflowConfirmed({\n\t\taction: \"Reject budget\",\n\t\tentity: `budget ${budgetId}`,\n\t\tdetails: `with reason \"${reason}\" and send requester reply email`,\n\t});\n\tconst notifications = await getAllNotifications();\n\tconst pending = notifications.filter(\n\t\t(n) =>\n\t\t\tn.notificationType === \"request\" &&\n\t\t\tn.status === ExtendedApprovalStatus.PENDING_APPROVAL &&\n\t\t\tn.type === ExtendedApprovalType.BUDGET &&\n\t\t\t(n.budgetId === budgetId ||\n\t\t\t\t(n.budget as { id?: string } | undefined)?.id === budgetId),\n\t);\n\tconst approval = pending[0];\n\tif (!approval) {\n\t\tthrow new Error(\n\t\t\t\"No pending budget approval found for this budget and approver.\",\n\t\t);\n\t}\n\tconst result = await api.budget.updateBudgetApproval.mutate({\n\t\tbudgetApprovalId: approval.id,\n\t\tstatus: ExtendedApprovalStatus.REJECTED,\n\t\trejectionReason: reason,\n\t});\n\tlet email: ApprovalEmailDeliveryReport;\n\ttry {\n\t\tconst delivery = result.emailDelivery;\n\t\temail = createApprovalEmailDeliveryReport(delivery);\n\t} catch (error) {\n\t\temail = createApprovalEmailDeliveryFailure(\n\t\t\terror instanceof Error ? error.message : String(error),\n\t\t);\n\t}\n\tout({\n\t\t...result,\n\t\temail,\n\t});\n}\n\n/** Supplier profile, approvals and tab counts, without usage rows or items. */\nexport async function getSupplierOverview(supplierId: string): Promise<void> {\n\tout(await api.supplier.getSupplierOverview.query({ id: supplierId }));\n}\n\n/** Usage rows plus calculated spending for one supplier. */\nexport async function getSupplierUsage(supplierId: string): Promise<void> {\n\tout(await api.supplier.getSupplierUsage.query({ id: supplierId }));\n}\n\n/** Inventory items catalogued under one supplier. */\nexport async function getSupplierItems(supplierId: string): Promise<void> {\n\tout(await api.supplier.getSupplierItems.query({ id: supplierId }));\n}\n\nexport async function getSupplierDetails(supplierId: string): Promise<void> {\n\tconst supplier = await api.supplier.getSupplierById.query({\n\t\tid: supplierId,\n\t});\n\tconst respondedStatuses = new Set<string>([\n\t\tExtendedApprovalStatus.APPROVED,\n\t\tExtendedApprovalStatus.REJECTED,\n\t]);\n\tconst latestRespondedApproval = [\n\t\t...supplier.approvals.filter((approval) =>\n\t\t\trespondedStatuses.has(approval.status),\n\t\t),\n\t].sort(\n\t\t(a, b) =>\n\t\t\tnew Date(b.respondedAt ?? b.updatedAt).getTime() -\n\t\t\t\tnew Date(a.respondedAt ?? a.updatedAt).getTime() ||\n\t\t\tnew Date(b.createdAt).getTime() - new Date(a.createdAt).getTime(),\n\t)[0];\n\tconst pendingApprovals = supplier.approvals.filter(\n\t\t(approval) => approval.status === ExtendedApprovalStatus.PENDING_APPROVAL,\n\t);\n\tconst supersededApprovals = supplier.approvals.filter(\n\t\t(approval) => approval.status === ExtendedApprovalStatus.SUPERSEDED,\n\t);\n\tconst respondedByApproval = latestRespondedApproval ?? null;\n\tconst responseUser = respondedByApproval\n\t\t? (respondedByApproval.responder ?? respondedByApproval.approver)\n\t\t: null;\n\tout({\n\t\t...supplier,\n\t\tsupplierApprovalSummary: {\n\t\t\tpendingApprovalCount: pendingApprovals.length,\n\t\t\tpendingApprovers: pendingApprovals.map((approval) => ({\n\t\t\t\tapprovalId: approval.id,\n\t\t\t\tapproverId: approval.approverId,\n\t\t\t\tname: approval.approver.name,\n\t\t\t\temail: approval.approver.email,\n\t\t\t\tcreatedAt: approval.createdAt,\n\t\t\t\tupdatedAt: approval.updatedAt,\n\t\t\t})),\n\t\t\tsupersededApprovalCount: supersededApprovals.length,\n\t\t\tsupersededApprovers: supersededApprovals.map((approval) => ({\n\t\t\t\tapprovalId: approval.id,\n\t\t\t\tapproverId: approval.approverId,\n\t\t\t\tname: approval.approver.name,\n\t\t\t\temail: approval.approver.email,\n\t\t\t\trespondedAt: approval.respondedAt,\n\t\t\t\tresponder: approval.responder\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tid: approval.responder.id,\n\t\t\t\t\t\t\tname: approval.responder.name,\n\t\t\t\t\t\t\temail: approval.responder.email,\n\t\t\t\t\t\t}\n\t\t\t\t\t: null,\n\t\t\t})),\n\t\t\trespondedBy:\n\t\t\t\trespondedByApproval && responseUser\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tapprovalId: respondedByApproval.id,\n\t\t\t\t\t\t\tstatus: respondedByApproval.status,\n\t\t\t\t\t\t\tapproverId: respondedByApproval.approverId,\n\t\t\t\t\t\t\tresponderId: respondedByApproval.responderId,\n\t\t\t\t\t\t\tname: responseUser.name,\n\t\t\t\t\t\t\temail: responseUser.email,\n\t\t\t\t\t\t\trespondedAt: respondedByApproval.respondedAt,\n\t\t\t\t\t\t\tupdatedAt: respondedByApproval.updatedAt,\n\t\t\t\t\t\t}\n\t\t\t\t\t: null,\n\t\t},\n\t});\n}\n\nexport async function approveSupplier(supplierId: string): Promise<void> {\n\tconst supplier = await api.supplier.getSupplierOverview.query({\n\t\tid: supplierId,\n\t});\n\tif (supplier.status === ExtendedApprovalStatus.REJECTED) {\n\t\tawait assertSensitiveWorkflowConfirmed({\n\t\t\taction: \"Re-approve supplier\",\n\t\t\tentity: `supplier ${supplierId}`,\n\t\t\teffects: [\"state-change\", \"external-write\"],\n\t\t\tdetails: supplier.active\n\t\t\t\t? \"and queue its QuickBooks vendor sync (it is usable once QuickBooks confirms); append a new approval and retain earlier history; no requester reply email is sent\"\n\t\t\t\t: \"and queue its QuickBooks vendor sync; append a new approval and retain earlier history; it remains archived and no requester reply email is sent\",\n\t\t});\n\t\tout(await api.supplier.reapproveSupplier.mutate({ supplierId }));\n\t\treturn;\n\t}\n\tawait assertSensitiveWorkflowConfirmed({\n\t\taction: \"Approve supplier\",\n\t\tentity: `supplier ${supplierId}`,\n\t\tdetails: \"and send requester reply email\",\n\t});\n\tconst notifications = await getAllNotifications();\n\tconst pending = notifications.filter(\n\t\t(n) =>\n\t\t\tn.notificationType === \"request\" &&\n\t\t\tn.status === ExtendedApprovalStatus.PENDING_APPROVAL &&\n\t\t\tn.type === ExtendedApprovalType.SUPPLIER &&\n\t\t\t(n.supplierId === supplierId || n.supplier?.id === supplierId),\n\t);\n\tconst approval = pending[0];\n\tif (!approval) {\n\t\tthrow new Error(\"No pending supplier approval found.\");\n\t}\n\tconst result = await api.supplier.updateSupplierApproval.mutate({\n\t\tsupplierApprovalId: approval.id,\n\t\tstatus: ExtendedApprovalStatus.APPROVED,\n\t});\n\tlet email: ApprovalEmailDeliveryReport;\n\ttry {\n\t\tconst delivery = result.emailDelivery;\n\t\temail = createApprovalEmailDeliveryReport(delivery);\n\t} catch (error) {\n\t\temail = createApprovalEmailDeliveryFailure(\n\t\t\terror instanceof Error ? error.message : String(error),\n\t\t);\n\t}\n\tout({\n\t\t...result,\n\t\temail,\n\t});\n}\n\nexport async function rejectSupplier(\n\tsupplierId: string,\n\treason: string,\n): Promise<void> {\n\tawait assertSensitiveWorkflowConfirmed({\n\t\taction: \"Reject supplier\",\n\t\tentity: `supplier ${supplierId}`,\n\t\tdetails: `with reason \"${reason}\" and send requester reply email`,\n\t});\n\tconst notifications = await getAllNotifications();\n\tconst pending = notifications.filter(\n\t\t(n) =>\n\t\t\tn.notificationType === \"request\" &&\n\t\t\tn.status === ExtendedApprovalStatus.PENDING_APPROVAL &&\n\t\t\tn.type === ExtendedApprovalType.SUPPLIER &&\n\t\t\t(n.supplierId === supplierId || n.supplier?.id === supplierId),\n\t);\n\tconst approval = pending[0];\n\tif (!approval) {\n\t\tthrow new Error(\"No pending supplier approval found.\");\n\t}\n\tconst result = await api.supplier.updateSupplierApproval.mutate({\n\t\tsupplierApprovalId: approval.id,\n\t\tstatus: ExtendedApprovalStatus.REJECTED,\n\t\trejectionReason: reason,\n\t});\n\tlet email: ApprovalEmailDeliveryReport;\n\ttry {\n\t\tconst delivery = result.emailDelivery;\n\t\temail = createApprovalEmailDeliveryReport(delivery);\n\t} catch (error) {\n\t\temail = createApprovalEmailDeliveryFailure(\n\t\t\terror instanceof Error ? error.message : String(error),\n\t\t);\n\t}\n\tout({\n\t\t...result,\n\t\temail,\n\t});\n}\n\nexport async function rejectBill(\n\tbillId: string,\n\treason: string,\n): Promise<void> {\n\tawait assertSensitiveWorkflowConfirmed({\n\t\taction: \"Reject bill\",\n\t\tentity: `bill ${billId}`,\n\t\tdetails: `with reason \"${reason}\" and send requester reply email`,\n\t});\n\tconst notifications = await getAllNotifications();\n\tconst pending = notifications.filter(\n\t\t(n) =>\n\t\t\tn.notificationType === \"request\" &&\n\t\t\tn.status === ExtendedApprovalStatus.PENDING_APPROVAL &&\n\t\t\tn.type === ExtendedApprovalType.BILL &&\n\t\t\t(n.billId === billId || n.bill?.id === billId),\n\t);\n\tconst approval = pending[0];\n\tif (!approval) {\n\t\tthrow new Error(\"No pending bill approval found.\");\n\t}\n\tconst result = await api.bill.updateApproval.mutate({\n\t\tbillApprovalId: approval.id,\n\t\tstatus: ExtendedApprovalStatus.REJECTED,\n\t\trejectionReason: reason,\n\t});\n\tif (result.processing) {\n\t\tout(result);\n\t\treturn;\n\t}\n\tlet email: ApprovalEmailDeliveryReport;\n\ttry {\n\t\tconst delivery = result.emailDelivery;\n\t\temail = createApprovalEmailDeliveryReport(delivery);\n\t} catch (error) {\n\t\temail = createApprovalEmailDeliveryFailure(\n\t\t\terror instanceof Error ? error.message : String(error),\n\t\t);\n\t}\n\tout({\n\t\t...result,\n\t\temail,\n\t});\n}\n\nexport async function approveQuotation(\n\tquotationId: string,\n\toverBudgetOverrideReason?: string,\n): Promise<void> {\n\tawait assertSensitiveWorkflowConfirmed({\n\t\taction: \"Approve quotation\",\n\t\tentity: `quotation ${quotationId}`,\n\t});\n\tconst notifications = await getAllNotifications();\n\tconst pending = notifications.filter(\n\t\t(n) =>\n\t\t\tisPendingRequest(n) &&\n\t\t\tn.type === QUOTATION &&\n\t\t\t(n.supplierQuotationId === quotationId ||\n\t\t\t\tn.supplierQuotation?.id === quotationId),\n\t);\n\tconst approval = pending[0];\n\tif (!approval) {\n\t\tthrow new Error(\"No pending quotation approval found.\");\n\t}\n\tconst result = await api.quotation.approve.mutate({\n\t\tquotationApprovalId: approval.id,\n\t\toverBudgetOverrideReason,\n\t});\n\tout(result);\n}\n\nexport async function rejectQuotation(\n\tquotationId: string,\n\treason: string,\n): Promise<void> {\n\tawait assertSensitiveWorkflowConfirmed({\n\t\taction: \"Reject quotation\",\n\t\tentity: `quotation ${quotationId}`,\n\t\tdetails: `with reason \"${reason}\"`,\n\t});\n\tconst notifications = await getAllNotifications();\n\tconst pending = notifications.filter(\n\t\t(n) =>\n\t\t\tisPendingRequest(n) &&\n\t\t\tn.type === QUOTATION &&\n\t\t\t(n.supplierQuotationId === quotationId ||\n\t\t\t\tn.supplierQuotation?.id === quotationId),\n\t);\n\tconst approval = pending[0];\n\tif (!approval) {\n\t\tthrow new Error(\"No pending quotation approval found.\");\n\t}\n\tconst result = await api.quotation.reject.mutate({\n\t\tquotationApprovalId: approval.id,\n\t\trejectionReason: reason,\n\t});\n\tout(result);\n}\n\n// --- Companies & projects ---\n\nexport const listCompanies = async (\n\tinput: RouterInputs[\"company\"][\"getCompanies\"],\n): Promise<void> => {\n\tconst result = await api.company.getCompanies.query(input);\n\tout(result);\n};\n\nexport const countCompanies = async (\n\tinput: RouterInputs[\"company\"][\"getCompanyCounts\"],\n): Promise<void> => {\n\tconst result = await api.company.getCompanyCounts.query(input);\n\tout(result);\n};\n\nexport async function getCompany(id: string): Promise<void> {\n\tconst company = await api.company.getCompanyById.query({ id });\n\tout(company);\n}\n\nexport async function createCompany(\n\topts: RouterInputs[\"company\"][\"createCompany\"],\n): Promise<void> {\n\tconst result = await api.company.createCompany.mutate({\n\t\t...opts,\n\t\tname: parseQuickBooksName(opts.name),\n\t});\n\tout(result);\n}\n\n/** One ranked page of BB + QuickBooks matches: `{ items, totalCount, pageInfo }`. */\nexport const searchExistingCompanies = async (\n\tinput: RouterInputs[\"company\"][\"searchExistingCompanies\"],\n) => {\n\tout(await api.company.searchExistingCompanies.query(input));\n};\n\nexport const reuseExistingCompany = async (\n\tinput: RouterInputs[\"company\"][\"useExistingCompany\"],\n) => {\n\tout(await api.company.useExistingCompany.mutate(input));\n};\n\nexport const listProjects = async (input: ProjectListInput): Promise<void> => {\n\tconst result = await api.project.getAllProjects.query(input);\n\tout(result);\n};\n\nexport const countProjects = async (\n\tinput: ProjectCountInput,\n): Promise<void> => {\n\tconst result = await api.project.getProjectCounts.query(input);\n\tout(result);\n};\n\n/** One cursor page of Project Hubs: `{ items, pageInfo }`. */\nexport const listProjectHubs = async (\n\tinput: RouterInputs[\"project\"][\"getAllProjectHubs\"],\n): Promise<void> => {\n\tout(await api.project.getAllProjectHubs.query(input));\n};\n\n/** Total plus the status facet for the same filters. */\nexport const countProjectHubs = async (\n\tinput: RouterInputs[\"project\"][\"getProjectHubCounts\"],\n): Promise<void> => {\n\tout(await api.project.getProjectHubCounts.query(input));\n};\n\nexport async function getProject(id: string): Promise<void> {\n\tconst [project, budgetsOverview, billsOverview] = await Promise.all([\n\t\tapi.project.getProjectDetailsById.query({ id }),\n\t\tapi.project.getProjectBudgetsOverview.query({ projectId: id }),\n\t\tapi.project.getProjectBillsOverview.query({ projectId: id }),\n\t]);\n\tout({ project, budgetsOverview, billsOverview });\n}\n\nexport const getProjectHubStatus = async (projectId: string): Promise<void> => {\n\tconst result = await api.project.getProjectHubShareLink.query({ projectId });\n\tout(result);\n};\n\nexport const setupProjectHub = async (projectId: string): Promise<void> => {\n\tawait assertSensitiveWorkflowConfirmed({\n\t\taction: \"Set up Project Hub\",\n\t\tentity: `project ${projectId}`,\n\t\tdetails: \"queue Asana, Drive, and client Hub provisioning\",\n\t});\n\tconst result = await api.project.setupProjectHub.mutate({ projectId });\n\tout(result);\n};\n\nexport const syncProjectHubCommercialDocuments = async (\n\tprojectId: string,\n): Promise<void> => {\n\tawait assertSensitiveWorkflowConfirmed({\n\t\taction: \"Sync Project Hub commercial documents\",\n\t\tentity: `project ${projectId}`,\n\t\tdetails:\n\t\t\t\"queue a full Budget Builder to Google Drive and Asana reconciliation\",\n\t});\n\tconst result = await api.project.syncProjectHubCommercialDocuments.mutate({\n\t\tprojectId,\n\t});\n\tout(result);\n};\n\nexport async function createProject(opts: {\n\tname: string;\n\tdescription?: string;\n\tcompanyId: string;\n\tcontactPersonId: string;\n\tinsideSalesId: string;\n\tbusinessDevelopmentId: string;\n\tprojectManagerId?: string;\n\tvenue: string;\n\tpax?: string;\n\t/** Asana sales deal task gid; omitted values trigger interactive lead selection. */\n\tasanaTaskId?: string;\n\t/** Optional override for the automatic lead-task search query. */\n\tasanaSearch?: string;\n\tslackChannelId?: string;\n\tslackChannelUrl?: string;\n\tslackChannelName?: string;\n\tstartDate: string;\n\tendDate?: string;\n}): Promise<void> {\n\tconst name = parseQuickBooksName(opts.name);\n\tconst links = await resolveCreateProjectLinks({\n\t\tname,\n\t\tasanaTaskId: opts.asanaTaskId,\n\t\tasanaSearch: opts.asanaSearch,\n\t\tslackChannelId: opts.slackChannelId,\n\t\tslackChannelUrl: opts.slackChannelUrl,\n\t\tslackChannelName: opts.slackChannelName,\n\t});\n\n\tconst result = await api.project.createProject.mutate({\n\t\tname,\n\t\tdescription: opts.description,\n\t\tcompanyId: opts.companyId,\n\t\tcontactPersonId: opts.contactPersonId,\n\t\tinsideSalesId: opts.insideSalesId,\n\t\tbusinessDevelopmentId: opts.businessDevelopmentId,\n\t\tprojectManagerId: opts.projectManagerId,\n\t\tvenue: opts.venue,\n\t\tpax: opts.pax,\n\t\tasanaTaskId: links.asanaTaskId,\n\t\tslackChannelId: links.slackChannelId,\n\t\tslackChannelUrl: links.slackChannelUrl,\n\t\tslackChannelName: links.slackChannelName,\n\t\tdateRange: {\n\t\t\tfrom: new Date(opts.startDate),\n\t\t\tto: opts.endDate ? new Date(opts.endDate) : undefined,\n\t\t},\n\t});\n\tout(result);\n}\n\nexport async function updateProjectStatus(\n\tid: string,\n\tstatus: ProjectStatus,\n\topts?: {\n\t\tprojectManagerId?: string;\n\t\tprojectManagerEmail?: string;\n\t},\n): Promise<void> {\n\tawait assertSensitiveWorkflowConfirmed({\n\t\taction: \"Update project status\",\n\t\tentity: `project ${id}`,\n\t\tdetails: `to ${status}`,\n\t});\n\tconst result = await api.project.updateProjectStatus.mutate({\n\t\tid,\n\t\tstatus,\n\t\t...(opts?.projectManagerId && { projectManagerId: opts.projectManagerId }),\n\t\t...(opts?.projectManagerEmail && {\n\t\t\tprojectManagerEmail: opts.projectManagerEmail,\n\t\t}),\n\t});\n\tout(result);\n}\n\nexport const checkProjectReconciliation = async (\n\tprojectId: string,\n): Promise<void> => {\n\tconst result = await api.project.getReconciliationReview.query({ projectId });\n\tout(result);\n};\n\nexport const reconcileProject = async (projectId: string): Promise<void> => {\n\tawait assertSensitiveWorkflowConfirmed({\n\t\taction: \"Reconcile project\",\n\t\tentity: `project ${projectId}`,\n\t\tdetails: \"rerun all reconciliation checks and mark it RECONCILED\",\n\t});\n\tconst result = await api.project.reconcile.mutate({ projectId });\n\tout(result);\n};\n\nexport const completeProject = async (projectId: string): Promise<void> => {\n\tawait updateProjectStatus(projectId, ProjectStatus.COMPLETED);\n};\n\nexport const importQuickBooksProjectId = async (\n\tprojectId: string,\n\tprojectUrl: string,\n): Promise<void> => {\n\tconst result = await api.project.importQboProjectId.mutate({\n\t\tprojectId,\n\t\tprojectUrl,\n\t});\n\tout(result);\n};\n\nexport const listWebhookEventTypes = async (): Promise<void> => {\n\tout(await api.webhook.listEventTypes.query());\n};\n\nexport const listWebhookEndpoints = async (): Promise<void> => {\n\tout(await api.webhook.listEndpoints.query());\n};\n\nexport const getWebhookEndpoint = async (id: string): Promise<void> => {\n\tout(await api.webhook.getEndpoint.query({ id }));\n};\n\nexport const createWebhookEndpoint = async (\n\tinput: RouterInputs[\"webhook\"][\"createEndpoint\"],\n): Promise<void> => {\n\tconst result = await api.webhook.createEndpoint.mutate(input);\n\tout({\n\t\t...result,\n\t\tnote: \"Store the signing secret now; Budget Builder never shows it again.\",\n\t});\n};\n\nexport const updateWebhookEndpoint = async (\n\tinput: RouterInputs[\"webhook\"][\"updateEndpoint\"],\n): Promise<void> => {\n\tout(await api.webhook.updateEndpoint.mutate(input));\n};\n\nexport const deleteWebhookEndpoint = async (id: string): Promise<void> => {\n\tawait assertSensitiveWorkflowConfirmed({\n\t\taction: \"Delete webhook endpoint and its delivery history\",\n\t\tentity: `webhook endpoint ${id}`,\n\t});\n\tout(await api.webhook.deleteEndpoint.mutate({ id }));\n};\n\nexport const rotateWebhookSecret = async (\n\tinput: RouterInputs[\"webhook\"][\"rotateSecret\"],\n): Promise<void> => {\n\tawait assertSensitiveWorkflowConfirmed({\n\t\taction: \"Rotate webhook signing secret\",\n\t\tentity: `webhook endpoint ${input.id}`,\n\t\tdetails: `previous secrets keep signing for ${input.previousSecretTtlHours ?? 24}h`,\n\t});\n\tconst result = await api.webhook.rotateSecret.mutate(input);\n\tout({\n\t\t...result,\n\t\tnote: \"Store the new signing secret now; Budget Builder never shows it again.\",\n\t});\n};\n\nexport const sendWebhookTestEvent = async (id: string): Promise<void> => {\n\tout(await api.webhook.sendTestEvent.mutate({ id }));\n};\n\nexport const listWebhookDeliveries = async (\n\tinput: RouterInputs[\"webhook\"][\"listDeliveries\"],\n): Promise<void> => {\n\tout(await api.webhook.listDeliveries.query(input));\n};\n\nexport const getWebhookDelivery = async (deliveryId: string): Promise<void> => {\n\tout(await api.webhook.getDelivery.query({ deliveryId }));\n};\n\nexport const replayWebhookDelivery = async (\n\tdeliveryId: string,\n): Promise<void> => {\n\tout(await api.webhook.replayDelivery.mutate({ deliveryId }));\n};\n\n/** One cursor page of integration operations, newest first: `{ items, pageInfo }`. */\nexport const listIntegrationOperations = async (\n\tinput: RouterInputs[\"integration\"][\"listOperations\"],\n): Promise<void> => {\n\tconst result = await api.integration.listOperations.query(input);\n\tout(result);\n};\n\nexport const getIntegrationOperation = async (\n\toperationId: string,\n): Promise<void> => {\n\tconst result = await api.integration.getOperation.query({ operationId });\n\tout(result);\n};\n\n/** Provider filter options; no total. */\nexport const countIntegrationOperations = async (\n\tinput: RouterInputs[\"integration\"][\"getCounts\"],\n): Promise<void> => {\n\tout(await api.integration.getCounts.query(input));\n};\n\nexport const retryIntegrationOperation = async (\n\toperationId: string,\n\tconfirmExternalStateReconciled: boolean,\n\toutboundEmailResolution?: \"ACCEPTED\" | \"NOT_ACCEPTED_RETRY\",\n\tproviderMessageId?: string,\n): Promise<void> => {\n\tawait assertSensitiveWorkflowConfirmed({\n\t\taction:\n\t\t\toutboundEmailResolution === \"ACCEPTED\"\n\t\t\t\t? \"Reconcile integration operation as completed\"\n\t\t\t\t: \"Retry integration operation (QuickBooks jobs with a saved attempt check QuickBooks first and never resend an applied change)\",\n\t\tentity: `operation ${operationId}`,\n\t\tdetails:\n\t\t\toutboundEmailResolution === \"ACCEPTED\"\n\t\t\t\t? `mark provider-accepted email sent with message ID ${providerMessageId ?? \"<missing>\"}`\n\t\t\t\t: outboundEmailResolution === \"NOT_ACCEPTED_RETRY\"\n\t\t\t\t\t? \"rotate the Resend idempotency key and retry provider delivery\"\n\t\t\t\t\t: confirmExternalStateReconciled\n\t\t\t\t\t\t? \"after confirming the external state has been reconciled\"\n\t\t\t\t\t\t: undefined,\n\t});\n\tconst result = await api.integration.retryOperation.mutate({\n\t\toperationId,\n\t\tconfirmExternalStateReconciled,\n\t\toutboundEmailResolution,\n\t\tproviderMessageId,\n\t});\n\tout(result);\n};\n\nexport const reconcileResourceOperation = async (\n\toperationId: string,\n): Promise<void> => {\n\tawait assertSensitiveWorkflowConfirmed({\n\t\taction: \"Verify QuickBooks resource outcome\",\n\t\tentity: `operation ${operationId}`,\n\t\tdetails:\n\t\t\t\"verify the saved receipt or read QuickBooks when the attempt is uncertain, then queue local update/archive/reactivation finalization without repeating the provider mutation\",\n\t});\n\tconst result = await api.integration.reconcileResourceOperation.mutate({\n\t\toperationId,\n\t});\n\tout(result);\n};\n\n// --- Typeform inbound administration ---\n\nexport const listInboundSources = async (\n\tinput: RouterInputs[\"inbound\"][\"listSources\"],\n): Promise<void> => {\n\tconst result = await api.inbound.listSources.query(input);\n\tout(result);\n};\n\nexport const countInboundSources = async (\n\tinput: RouterInputs[\"inbound\"][\"countSources\"],\n): Promise<void> => {\n\tconst result = await api.inbound.countSources.query(input);\n\tout(result);\n};\n\nexport const createInboundSource = async (\n\tinput: RouterInputs[\"inbound\"][\"createSource\"],\n): Promise<void> => {\n\tconst result = await api.inbound.createSource.mutate(input);\n\tout(result);\n};\n\nexport const getInboundSource = async (sourceId: string): Promise<void> => {\n\tconst result = await api.inbound.getSource.query({ sourceId });\n\tout(result);\n};\n\nexport const updateInboundSource = async (\n\tsourceId: string,\n\tname: string,\n): Promise<void> => {\n\tconst result = await api.inbound.updateSource.mutate({ name, sourceId });\n\tout(result);\n};\n\nexport const listInboundSubmissions = async (\n\tinput: RouterInputs[\"inbound\"][\"listSubmissions\"],\n): Promise<void> => {\n\tconst result = await api.inbound.listSubmissions.query(input);\n\tout(result);\n};\n\nexport const countInboundSubmissions = async (\n\tinput: RouterInputs[\"inbound\"][\"countSubmissions\"],\n): Promise<void> => {\n\tout(await api.inbound.countSubmissions.query(input));\n};\n\nexport const getInboundSubmission = async (\n\tsubmissionId: string,\n): Promise<void> => {\n\tconst result = await api.inbound.getSubmission.query({ submissionId });\n\tout(result);\n};\n\nexport const saveInboundMappingVersion = async (\n\tsourceId: string,\n\tmappings: RouterInputs[\"inbound\"][\"saveMappingVersion\"][\"mappings\"],\n): Promise<void> => {\n\tconst source = await api.inbound.getSource.query({ sourceId });\n\tconst result = await api.inbound.saveMappingVersion.mutate({\n\t\texpectedActiveMappingVersion: source.activeMappingVersion,\n\t\tmappings,\n\t\tsourceId,\n\t});\n\tout(result);\n};\n\nexport const saveInboundAutomationConfig = async (\n\tinput: RouterInputs[\"inbound\"][\"saveAutomationConfig\"],\n): Promise<void> => {\n\tconst result = await api.inbound.saveAutomationConfig.mutate(input);\n\tout(result);\n};\n\nexport const updateInboundProcessing = async (\n\tinput: RouterInputs[\"inbound\"][\"updateProcessing\"],\n): Promise<void> => {\n\tconst result = await api.inbound.updateProcessing.mutate(input);\n\tout(result);\n};\n\n// --- Contacts ---\n\nexport async function listContacts(companyId: string): Promise<void> {\n\tconst contacts = await api.contactPerson.getContactPersonByCompanyId.query({\n\t\tcompanyId,\n\t});\n\tout(contacts);\n}\n\n// --- Items ---\n\n/** One cursor page of catalogue items: `{ items, pageInfo }`. */\nexport const listItems = async (\n\tinput: RouterInputs[\"item\"][\"getItems\"],\n): Promise<void> => {\n\tout(await api.item.getItems.query(input));\n};\n\n/** Total plus category and supplier facets for the same filters. */\nexport const countItems = async (\n\tinput: RouterInputs[\"item\"][\"getItemCounts\"],\n): Promise<void> => {\n\tout(await api.item.getItemCounts.query(input));\n};\n\nexport async function getItem(id: string): Promise<void> {\n\tconst item = await api.item.getItem.query({ id });\n\tout(item);\n}\n\nexport const getItemQuickBooksSyncStatus = async (\n\titemId: string,\n): Promise<void> => {\n\tconst result = await api.item.getQuickBooksSyncStatus.query({ id: itemId });\n\tout(result);\n};\n\n/** One cursor page of active item categories: `{ items, pageInfo }`. */\nexport const listItemCategories = async (\n\tinput: RouterInputs[\"itemCategory\"][\"getItemCategories\"],\n): Promise<void> => {\n\tout(await api.itemCategory.getItemCategories.query(input));\n};\n\n/** Total active item categories matching the filters. */\nexport const countItemCategories = async (\n\tinput: RouterInputs[\"itemCategory\"][\"getCounts\"],\n): Promise<void> => {\n\tout(await api.itemCategory.getCounts.query(input));\n};\n\n// --- Supplier analytics ---\n\n/** One cursor page of the admin supplier analytics table: `{ items, pageInfo }`. */\nexport const getSupplierAnalytics = async (\n\tinput: RouterInputs[\"dashboard\"][\"getSupplierTableData\"],\n): Promise<void> => {\n\tout(await api.dashboard.getSupplierTableData.query(input));\n};\n\n/** Total for the same supplier analytics filters. */\nexport const countSupplierAnalytics = async (\n\tinput: RouterInputs[\"dashboard\"][\"getSupplierTableCounts\"],\n): Promise<void> => {\n\tout(await api.dashboard.getSupplierTableCounts.query(input));\n};\n\n// --- Dashboard / analytics ---\n\nexport async function createUser(\n\tinput: RouterInputs[\"user\"][\"create\"],\n): Promise<void> {\n\tconst user = await api.user.create.mutate(input);\n\tout(user);\n}\n\nexport async function createApiKeyForUser(\n\tinput: RouterInputs[\"mcpApiKey\"][\"create\"],\n): Promise<void> {\n\tconst apiKey = await api.mcpApiKey.create.mutate(input);\n\tout(apiKey);\n}\n\nexport async function listApiKeysForUser(\n\tinput: RouterInputs[\"mcpApiKey\"][\"list\"],\n): Promise<void> {\n\tconst apiKeys = await api.mcpApiKey.list.query(input);\n\tout(apiKeys);\n}\n\nexport async function revokeApiKeyForUser(\n\tinput: RouterInputs[\"mcpApiKey\"][\"revoke\"],\n): Promise<void> {\n\tconst result = await api.mcpApiKey.revoke.mutate(input);\n\tout(result);\n}\n\n/** One forward page of users (name A–Z): `{ items, pageInfo }`. */\nexport const listUsers = async (\n\tinput: RouterInputs[\"user\"][\"searchUsers\"],\n): Promise<void> => {\n\tout(await api.user.searchUsers.query(input));\n};\n\n/** Total users matching `--q`. */\nexport const countUsers = async (\n\tinput: RouterInputs[\"user\"][\"getCounts\"],\n): Promise<void> => {\n\tout(await api.user.getCounts.query(input));\n};\n\nexport async function whoAmI(): Promise<void> {\n\tconst user = await api.user.getCurrentUser.query();\n\tout(user);\n}\n\nexport async function getUserPerformance(userId?: string): Promise<void> {\n\tconst result = await api.dashboard.getUserPerformance.query({ userId });\n\tout(result);\n}\n\nexport async function getDashboard(input: {\n\tuserId?: string;\n\trole?: \"BD\" | \"CREATOR\" | \"INSIDE_SALES\" | \"ALL\";\n\tdeals?: \"ALL\" | \"SUCCESSFUL\" | \"LOST\";\n\ttimeFrame?:\n\t\t| \"LAST_YEAR\"\n\t\t| \"LAST_6_MONTHS\"\n\t\t| \"LAST_3_MONTHS\"\n\t\t| \"CUSTOM\"\n\t\t| \"ALL\";\n\tstartDate?: string;\n\tendDate?: string;\n}): Promise<void> {\n\tconst result = await api.dashboard.getDashboard.query({\n\t\tuserId: input.userId,\n\t\trole: input.role ?? \"ALL\",\n\t\tdeals: input.deals ?? \"ALL\",\n\t\ttimeFrame: input.timeFrame ?? \"ALL\",\n\t\tstartDate: input.startDate,\n\t\tendDate: input.endDate,\n\t});\n\tout(result);\n}\n\nexport async function getMonthlyMetrics(input: {\n\tuserId?: string;\n\trole?: \"BD\" | \"CREATOR\" | \"INSIDE_SALES\" | \"ALL\";\n\tdeals?: \"ALL\" | \"SUCCESSFUL\" | \"LOST\";\n\ttimeFrame?:\n\t\t| \"LAST_YEAR\"\n\t\t| \"LAST_6_MONTHS\"\n\t\t| \"LAST_3_MONTHS\"\n\t\t| \"CUSTOM\"\n\t\t| \"ALL\";\n\tstartDate?: string;\n\tendDate?: string;\n}): Promise<void> {\n\tconst result = await api.dashboard.getMonthlyMetrics.query({\n\t\tuserId: input.userId,\n\t\trole: input.role ?? \"ALL\",\n\t\tdeals: input.deals ?? \"ALL\",\n\t\ttimeFrame: input.timeFrame ?? \"ALL\",\n\t\tstartDate: input.startDate,\n\t\tendDate: input.endDate,\n\t});\n\tout(result);\n}\n\nexport async function getSystemOverview(input: {\n\tuserId?: string;\n\trole?: \"BD\" | \"CREATOR\" | \"INSIDE_SALES\" | \"ALL\";\n\tdeals?: \"ALL\" | \"SUCCESSFUL\" | \"LOST\";\n\ttimeFrame?:\n\t\t| \"LAST_YEAR\"\n\t\t| \"LAST_6_MONTHS\"\n\t\t| \"LAST_3_MONTHS\"\n\t\t| \"CUSTOM\"\n\t\t| \"ALL\";\n\tstartDate?: string;\n\tendDate?: string;\n}): Promise<void> {\n\tconst result = await api.dashboard.getSystemOverview.query({\n\t\tuserId: input.userId,\n\t\trole: input.role ?? \"ALL\",\n\t\tdeals: input.deals ?? \"ALL\",\n\t\ttimeFrame: input.timeFrame ?? \"ALL\",\n\t\tstartDate: input.startDate,\n\t\tendDate: input.endDate,\n\t});\n\tout(result);\n}\n\nexport async function getEstimatePerformance(input: {\n\tuserId?: string;\n\trole?: \"BD\" | \"CREATOR\" | \"INSIDE_SALES\" | \"ALL\";\n\tdeals?: \"ALL\" | \"SUCCESSFUL\" | \"LOST\";\n\ttimeFrame?:\n\t\t| \"LAST_YEAR\"\n\t\t| \"LAST_6_MONTHS\"\n\t\t| \"LAST_3_MONTHS\"\n\t\t| \"CUSTOM\"\n\t\t| \"ALL\";\n\tstartDate?: string;\n\tendDate?: string;\n}): Promise<void> {\n\tconst result = await api.dashboard.getEstimatePerformance.query({\n\t\tuserId: input.userId,\n\t\trole: input.role ?? \"ALL\",\n\t\tdeals: input.deals ?? \"ALL\",\n\t\ttimeFrame: input.timeFrame ?? \"ALL\",\n\t\tstartDate: input.startDate,\n\t\tendDate: input.endDate,\n\t});\n\tout(result);\n}\n\nexport async function getFinancialOverview(input: {\n\tuserId?: string;\n\trole?: BudgetRole;\n\tdeals?: Deals;\n\ttimeFrame?: TimeFrame;\n\tstartDate?: string;\n\tendDate?: string;\n}): Promise<void> {\n\tconst result = await api.dashboard.getFinancialOverview.query({\n\t\tuserId: input.userId,\n\t\trole: input.role ?? BudgetRole.ALL,\n\t\tdeals: input.deals ?? Deals.ALL,\n\t\ttimeFrame: input.timeFrame ?? TimeFrame.ALL,\n\t\tstartDate: input.startDate,\n\t\tendDate: input.endDate,\n\t});\n\tout(result);\n}\n\n// --- Error logs ---\n\nexport const getRecentErrors = async (\n\tinput: RouterInputs[\"errorLog\"][\"getRecentErrors\"],\n): Promise<void> => {\n\tout(await api.errorLog.getRecentErrors.query(input));\n};\n\n/** One error log with full diagnostics (stack, cause, request and metadata). */\nexport const getError = async (errorId: string): Promise<void> => {\n\tout(await api.errorLog.getErrorById.query({ errorId }));\n};\n\nexport const countErrors = async (\n\tinput: RouterInputs[\"errorLog\"][\"countErrors\"],\n): Promise<void> => {\n\tout(await api.errorLog.countErrors.query(input));\n};\n\nexport async function getErrorMetrics(): Promise<void> {\n\tconst result = await api.errorLog.getErrorMetrics.query({});\n\tout(result);\n}\n\n// --- Historical / benchmarks ---\n\nexport async function getApprovedBudgets(opts: {\n\tprojectId?: string;\n\tlimit?: number;\n\tminRevenue?: number;\n\tmaxRevenue?: number;\n}): Promise<void> {\n\tconst filters = {\n\t\tprojectId: opts.projectId,\n\t\tstatuses: [\n\t\t\tExtendedBudgetStatus.APPROVED,\n\t\t\tExtendedBudgetStatus.ESTIMATE_ACCEPTED,\n\t\t\tExtendedBudgetStatus.ESTIMATE_CLOSED,\n\t\t],\n\t};\n\tconst [{ items: budgets }, { totalCount }] = await Promise.all([\n\t\tapi.budget.getAllBudgets.query({\n\t\t\t...filters,\n\t\t\tlimit: Math.min(opts.limit ?? 50, 100),\n\t\t\tincludeDetails: false,\n\t\t}),\n\t\tapi.budget.getCounts.query(filters),\n\t]);\n\n\tconst items = budgets.map((b) => {\n\t\tconst calc = b as {\n\t\t\ttotalSellingAfterDiscount?: number;\n\t\t\ttotalCostWithoutGst?: number;\n\t\t\tgpPercentage?: number;\n\t\t};\n\t\tconst revenue = calc.totalSellingAfterDiscount ?? 0;\n\t\tconst cost = calc.totalCostWithoutGst ?? 0;\n\t\tconst gp = calc.gpPercentage ?? 0;\n\t\tconst startDate = b.project.startDate;\n\t\tconst date =\n\t\t\tstartDate instanceof Date\n\t\t\t\t? startDate.toISOString()\n\t\t\t\t: String(startDate ?? \"\");\n\t\tconst createdAt =\n\t\t\tb.createdAt instanceof Date\n\t\t\t\t? b.createdAt.toISOString()\n\t\t\t\t: String(b.createdAt);\n\t\treturn {\n\t\t\tid: b.id,\n\t\t\tname: b.name,\n\t\t\tcategoryId: b.categoryId,\n\t\t\tcompany: (b.project as { company?: { name?: string } })?.company?.name,\n\t\t\tdate,\n\t\t\tpax: b.project.pax,\n\t\t\trevenue: Number(revenue.toFixed(2)),\n\t\t\tcost: Number(cost.toFixed(2)),\n\t\t\tgpPercentage: Number(gp.toFixed(2)),\n\t\t\tcreatedAt,\n\t\t};\n\t});\n\n\tlet filtered = items;\n\tif (opts.minRevenue != null) {\n\t\tconst minR = opts.minRevenue;\n\t\tfiltered = filtered.filter((i) => i.revenue >= minR);\n\t}\n\tif (opts.maxRevenue != null) {\n\t\tconst maxR = opts.maxRevenue;\n\t\tfiltered = filtered.filter((i) => i.revenue <= maxR);\n\t}\n\n\tout({ budgets: filtered, count: filtered.length, totalCount });\n}\n\nexport async function getBudgetCategoryBenchmarks(opts: {\n\tcategoryId: string;\n\tlimit?: number;\n}): Promise<void> {\n\tconst result = await api.budget.getBudgetCategoryBenchmarks.query({\n\t\tcategoryId: opts.categoryId,\n\t\tlimit: opts.limit ?? 100,\n\t});\n\tout(result);\n}\n\nexport async function getItemPricingHistory(opts: {\n\titemName?: string;\n\tcategoryId?: string;\n\tsupplierId?: string;\n\tlimit?: number;\n}): Promise<void> {\n\tconst result = await api.budget.getItemPricingHistory.query({\n\t\titemName: opts.itemName,\n\t\tcategoryId: opts.categoryId,\n\t\tsupplierId: opts.supplierId,\n\t\tlimit: opts.limit ?? 100,\n\t});\n\tout(result);\n}\n\nexport async function getSupplierPricingHistory(opts: {\n\tsupplierId: string;\n\titemCategoryId?: string;\n\tlimit?: number;\n}): Promise<void> {\n\tconst result = await api.budget.getSupplierPricingHistory.query({\n\t\tsupplierId: opts.supplierId,\n\t\titemCategoryId: opts.itemCategoryId,\n\t\tlimit: opts.limit ?? 100,\n\t});\n\tout(result);\n}\n", "import { getCliStorageError } from \"@go-labs/cli-auth/client\";\nimport type {\n\tCliErrorCode,\n\tCliErrorDetails,\n\tCliErrorPayload,\n\tCliExitCode,\n} from \"@go-labs-sg/bb/runtime/types\";\n\nconst invocationErrorCodes = new Set<CliErrorCode>([\n\t\"USAGE\",\n\t\"VALIDATION\",\n\t\"CONFIRMATION_REQUIRED\",\n]);\n\nconst trpcCodeMap: Readonly<Record<string, CliErrorCode>> = {\n\tBAD_REQUEST: \"VALIDATION\",\n\tCONFLICT: \"CONFLICT\",\n\tFORBIDDEN: \"AUTHORIZATION\",\n\tINTERNAL_SERVER_ERROR: \"API\",\n\tMETHOD_NOT_SUPPORTED: \"API\",\n\tNOT_FOUND: \"NOT_FOUND\",\n\tPARSE_ERROR: \"VALIDATION\",\n\tPAYLOAD_TOO_LARGE: \"VALIDATION\",\n\tPRECONDITION_FAILED: \"CONFLICT\",\n\tTIMEOUT: \"NETWORK\",\n\tTOO_MANY_REQUESTS: \"API\",\n\tUNAUTHORIZED: \"AUTHENTICATION\",\n\tUNPROCESSABLE_CONTENT: \"VALIDATION\",\n};\n\nconst cliErrorCodes = new Set<CliErrorCode>([\n\t\"USAGE\",\n\t\"VALIDATION\",\n\t\"CONFIRMATION_REQUIRED\",\n\t\"AUTHENTICATION\",\n\t\"AUTHORIZATION\",\n\t\"NOT_FOUND\",\n\t\"CONFLICT\",\n\t\"API\",\n\t\"NETWORK\",\n\t\"ABORTED\",\n\t\"INTERRUPTED\",\n\t\"INTERNAL\",\n]);\n\nexport class CliRuntimeError extends Error {\n\treadonly code: CliErrorCode;\n\treadonly details?: CliErrorDetails;\n\treadonly requestId?: string;\n\n\tconstructor(\n\t\tcode: CliErrorCode,\n\t\tmessage: string,\n\t\toptions: { details?: CliErrorDetails; requestId?: string } = {},\n\t) {\n\t\tsuper(message);\n\t\tthis.name = \"CliRuntimeError\";\n\t\tthis.code = code;\n\t\tthis.details = options.details;\n\t\tthis.requestId = options.requestId;\n\t}\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n\ttypeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst asNonEmptyString = (value: unknown): string | undefined =>\n\ttypeof value === \"string\" && value.trim() !== \"\" ? value : undefined;\n\nconst formatValidationMessage = (\n\tmessage: string,\n\tdata?: Record<string, unknown>,\n): string => {\n\tconst zodError = isRecord(data?.zodError) ? data.zodError : undefined;\n\tconst fieldErrors = isRecord(zodError?.fieldErrors)\n\t\t? zodError.fieldErrors\n\t\t: undefined;\n\tconst fields = fieldErrors\n\t\t? Object.entries(fieldErrors).flatMap(([field, errors]) =>\n\t\t\t\tArray.isArray(errors)\n\t\t\t\t\t? errors\n\t\t\t\t\t\t\t.filter((entry): entry is string => typeof entry === \"string\")\n\t\t\t\t\t\t\t.map((entry) => `${field}: ${entry}`)\n\t\t\t\t\t: [],\n\t\t\t)\n\t\t: [];\n\tconst formErrors = Array.isArray(zodError?.formErrors)\n\t\t? zodError.formErrors.filter(\n\t\t\t\t(entry): entry is string => typeof entry === \"string\",\n\t\t\t)\n\t\t: [];\n\tconst validationIssues = [...fields, ...formErrors];\n\tif (validationIssues.length > 0) return validationIssues.join(\"; \");\n\tlet parsed: unknown = message;\n\tfor (let depth = 0; depth < 3 && typeof parsed === \"string\"; depth++) {\n\t\ttry {\n\t\t\tparsed = JSON.parse(parsed);\n\t\t} catch {\n\t\t\treturn message;\n\t\t}\n\t}\n\tif (!Array.isArray(parsed) || parsed.length === 0 || !parsed.every(isRecord))\n\t\treturn message;\n\tconst issues = parsed.map((issue) => {\n\t\tif (\n\t\t\t!Array.isArray(issue.path) ||\n\t\t\ttypeof issue.message !== \"string\" ||\n\t\t\ttypeof issue.code !== \"string\"\n\t\t)\n\t\t\treturn undefined;\n\t\tconst path =\n\t\t\tissue.path\n\t\t\t\t.filter(\n\t\t\t\t\t(part): part is string | number =>\n\t\t\t\t\t\ttypeof part === \"string\" || typeof part === \"number\",\n\t\t\t\t)\n\t\t\t\t.join(\".\") || \"payload\";\n\t\tif (\n\t\t\tissue.code === \"invalid_type\" &&\n\t\t\ttypeof issue.expected === \"string\" &&\n\t\t\tissue.message.toLowerCase().includes(\"required\")\n\t\t) {\n\t\t\treturn `${path} must be a ${issue.expected}${path === \"cost\" ? ', e.g. \"19\"' : \"\"}`;\n\t\t}\n\t\treturn `${path}: ${issue.message}`;\n\t});\n\treturn issues.every((issue) => issue !== undefined)\n\t\t? issues.join(\"; \")\n\t\t: message;\n};\n\nconst asDetails = (value: unknown): CliErrorDetails | undefined => {\n\tif (!isRecord(value)) return undefined;\n\tconst details: Record<string, CliErrorDetails[string]> = {};\n\tfor (const [key, nestedValue] of Object.entries(value)) {\n\t\tif (isJsonValue(nestedValue)) details[key] = nestedValue;\n\t}\n\treturn Object.keys(details).length > 0 ? details : undefined;\n};\n\nconst isJsonValue = (value: unknown): value is CliErrorDetails[string] => {\n\tif (\n\t\tvalue === null ||\n\t\ttypeof value === \"string\" ||\n\t\ttypeof value === \"boolean\" ||\n\t\ttypeof value === \"number\"\n\t) {\n\t\treturn true;\n\t}\n\tif (Array.isArray(value)) return value.every(isJsonValue);\n\treturn isRecord(value) && Object.values(value).every(isJsonValue);\n};\n\nconst mapErrorCode = (value: unknown): CliErrorCode | undefined => {\n\tif (typeof value !== \"string\") return undefined;\n\tif (cliErrorCodes.has(value as CliErrorCode)) return value as CliErrorCode;\n\tif (value in trpcCodeMap) return trpcCodeMap[value];\n\treturn undefined;\n};\n\nconst networkMessagePattern =\n\t/\\b(fetch failed|network error|unable to connect|econnrefused|econnreset|enotfound|etimedout|socket hang up)\\b/i;\n\nconst isNetworkError = (error: unknown, depth = 0): boolean => {\n\tif (depth > 3 || !isRecord(error)) return false;\n\tconst message = asNonEmptyString(error.message);\n\tif (message !== undefined && networkMessagePattern.test(message)) return true;\n\tconst code = asNonEmptyString(error.code);\n\tif (code !== undefined && networkMessagePattern.test(code)) return true;\n\treturn isNetworkError(error.cause, depth + 1);\n};\n\nconst normalizeRuntimeError = (error: CliRuntimeError): CliErrorPayload => ({\n\tcode: error.code,\n\tmessage: error.message,\n\t...(error.details === undefined ? {} : { details: error.details }),\n\t...(error.requestId === undefined ? {} : { requestId: error.requestId }),\n});\n\nconst normalizeNetworkError = (error: unknown): CliErrorPayload => ({\n\tcode: \"NETWORK\",\n\tmessage:\n\t\terror instanceof Error\n\t\t\t? error.message\n\t\t\t: \"The Budget Builder API could not be reached.\",\n});\n\nconst normalizeRecordError = (\n\terror: Record<string, unknown>,\n): CliErrorPayload => {\n\tconst data = isRecord(error.data) ? error.data : undefined;\n\tconst transportCode = mapErrorCode(data?.code ?? error.code);\n\tif (\n\t\terror instanceof Error &&\n\t\tdata === undefined &&\n\t\ttransportCode === undefined\n\t) {\n\t\treturn { code: \"INTERNAL\", message: error.message };\n\t}\n\tconst code = transportCode ?? \"API\";\n\tconst rawMessage =\n\t\tasNonEmptyString(error.message) ?? \"The Budget Builder API request failed.\";\n\tconst message =\n\t\tcode === \"VALIDATION\"\n\t\t\t? formatValidationMessage(rawMessage, data)\n\t\t\t: rawMessage;\n\tconst requestId =\n\t\tasNonEmptyString(data?.requestId) ??\n\t\tasNonEmptyString(data?.requestID) ??\n\t\tasNonEmptyString(error.requestId);\n\tconst details = asDetails(data?.details ?? error.details);\n\n\treturn {\n\t\tcode,\n\t\tmessage,\n\t\t...(details === undefined ? {} : { details }),\n\t\t...(requestId === undefined ? {} : { requestId }),\n\t};\n};\n\n/**\n * Maps local errors and the common tRPC client error shape into the stable\n * CLI contract without importing a transport-specific error class.\n */\nexport const normalizeCliError = (error: unknown): CliErrorPayload => {\n\tconst storageError = getCliStorageError(error);\n\tif (storageError) return storageError;\n\tif (error instanceof CliRuntimeError) return normalizeRuntimeError(error);\n\tif (isNetworkError(error)) return normalizeNetworkError(error);\n\tif (isRecord(error)) return normalizeRecordError(error);\n\n\tif (error instanceof Error) {\n\t\treturn { code: \"INTERNAL\", message: error.message };\n\t}\n\n\treturn { code: \"INTERNAL\", message: \"An unexpected CLI error occurred.\" };\n};\n\nexport const exitCodeForCliError = (error: CliErrorPayload): CliExitCode => {\n\tif (error.code === \"INTERRUPTED\") return 130;\n\treturn invocationErrorCodes.has(error.code) ? 2 : 1;\n};\n", "import {\n\tCliRuntimeError,\n\tnormalizeCliError,\n} from \"@go-labs-sg/bb/runtime/error\";\n\nconst isP2028Error = (value: unknown, depth = 0): boolean => {\n\tif (depth > 3 || typeof value !== \"object\" || value === null) return false;\n\tconst error = value as {\n\t\tcode?: unknown;\n\t\tmessage?: unknown;\n\t\tcause?: unknown;\n\t\tdata?: unknown;\n\t\terror?: unknown;\n\t};\n\treturn (\n\t\terror.code === \"P2028\" ||\n\t\t(typeof error.message === \"string\" && /\\bP2028\\b/.test(error.message)) ||\n\t\tisP2028Error(error.cause, depth + 1) ||\n\t\tisP2028Error(error.data, depth + 1) ||\n\t\tisP2028Error(error.error, depth + 1)\n\t);\n};\n\nexport const budgetCreateUncertainError = (\n\terror: unknown,\n\tinput: { projectId: string; name: string },\n): CliRuntimeError | undefined => {\n\tconst message = error instanceof Error ? error.message : String(error);\n\tconst normalized = normalizeCliError(error);\n\tif (!isP2028Error(error) && normalized.code !== \"NETWORK\") return undefined;\n\treturn new CliRuntimeError(\n\t\tnormalized.code === \"NETWORK\" ? \"NETWORK\" : \"API\",\n\t\t`Budget creation outcome is uncertain (the write may have committed). Run list-budgets --projectId ${input.projectId} and check for ${JSON.stringify(input.name)} before retrying; matching names alone may be ambiguous. Original error: ${message}`,\n\t);\n};\n", "export const invoiceSplitSetupNextAction = (budgetId: string) => ({\n\tprompt:\n\t\t\"Review the uninvoiced balance, choose all or part of the remaining percentage, then supply invoice and due dates, billing address, and customer message. Non-admin creation requests admin approval; admin creation auto-approves. Sending remains separate.\",\n\treviewCommand: `bb customer-invoice readiness check ${budgetId}`,\n\tamountPreviewCommand: `bb customer-invoice amount preview ${budgetId} <percentage-of-estimate>`,\n\tcreateCommand:\n\t\t\"bb customer-invoice create --payload '<budgetId-requestId-invoiceDate-details-and-splits-json>'\",\n});\n", "export const CUSTOMER_INVOICE_APPROVAL_WINDOW_MS = 72 * 60 * 60 * 1000;\nexport const CUSTOMER_INVOICE_APPROVAL_REMINDER_LEAD_MS = 4 * 60 * 60 * 1000;\n\nexport const getCustomerInvoiceApprovalExpiresAt = (requestedAt: Date) =>\n\tnew Date(requestedAt.getTime() + CUSTOMER_INVOICE_APPROVAL_WINDOW_MS);\n\nexport const getCustomerInvoiceApprovalReminderAt = (expiresAt: Date) =>\n\tnew Date(expiresAt.getTime() - CUSTOMER_INVOICE_APPROVAL_REMINDER_LEAD_MS);\n\nexport const isCustomerInvoiceApprovalExpired = (\n\texpiresAt: Date,\n\tnow = new Date(),\n) => expiresAt.getTime() <= now.getTime();\n", "import {\n\tCustomerInvoiceBatchStatus,\n\tCustomerInvoiceStatus,\n} from \"@go-labs/budget-builder-db/enums\";\n\nimport { isCustomerInvoiceApprovalExpired } from \"./customer-invoice-approval-policy\";\n\nexport const customerInvoiceLifecycleStatuses = [\n\t\"EXPIRED\",\n\t...Object.values(CustomerInvoiceBatchStatus),\n\t\"PARTIALLY_SENT\",\n\tCustomerInvoiceStatus.SENT,\n\t\"PARTIALLY_PAID\",\n\tCustomerInvoiceStatus.PAID,\n\tCustomerInvoiceStatus.VOIDED,\n] as const;\nexport type CustomerInvoiceLifecycleStatus =\n\t(typeof customerInvoiceLifecycleStatuses)[number];\n\ninterface InvoiceLifecycleInput {\n\tstatus: CustomerInvoiceStatus;\n\tsentAt: Date | null;\n\tnetAmount: number | { toString(): string };\n\ttaxAmount: number | { toString(): string };\n\tqboBalance: number | { toString(): string } | null;\n}\n\nexport const getCustomerInvoiceLifecycleStatus = (\n\tinvoice: InvoiceLifecycleInput,\n): CustomerInvoiceStatus | \"PARTIALLY_PAID\" => {\n\tif (\n\t\tinvoice.status === CustomerInvoiceStatus.VOIDED ||\n\t\tinvoice.status === CustomerInvoiceStatus.PAID\n\t)\n\t\treturn invoice.status;\n\tconst balance =\n\t\tinvoice.qboBalance === null ? null : Number(invoice.qboBalance);\n\tconst total = Number(invoice.netAmount) + Number(invoice.taxAmount);\n\tif (balance !== null && balance > 0.005 && total - balance > 0.005)\n\t\treturn \"PARTIALLY_PAID\";\n\t// sentAt is persisted only after provider acceptance or a confirmed portal upload.\n\tif (invoice.status === CustomerInvoiceStatus.APPROVED && invoice.sentAt)\n\t\treturn CustomerInvoiceStatus.SENT;\n\treturn invoice.status;\n};\n\nexport const getCustomerInvoiceBatchLifecycleStatus = (\n\tbatch: {\n\t\tstatus: CustomerInvoiceBatchStatus;\n\t\tapprovalExpiresAt: Date;\n\t\tinvoices: readonly InvoiceLifecycleInput[];\n\t},\n\tnow = new Date(),\n): CustomerInvoiceLifecycleStatus => {\n\tif (\n\t\tbatch.status === CustomerInvoiceBatchStatus.PENDING_APPROVAL &&\n\t\tisCustomerInvoiceApprovalExpired(batch.approvalExpiresAt, now)\n\t)\n\t\treturn \"EXPIRED\";\n\tif (\n\t\tbatch.status !== CustomerInvoiceBatchStatus.APPROVED ||\n\t\tbatch.invoices.length === 0\n\t)\n\t\treturn batch.status;\n\tconst active = batch.invoices.filter(\n\t\t(invoice) => invoice.status !== CustomerInvoiceStatus.VOIDED,\n\t);\n\tif (active.length === 0) return CustomerInvoiceStatus.VOIDED;\n\tconst statuses = active.map(getCustomerInvoiceLifecycleStatus);\n\tif (statuses.every((status) => status === CustomerInvoiceStatus.PAID))\n\t\treturn CustomerInvoiceStatus.PAID;\n\tif (\n\t\tstatuses.some(\n\t\t\t(status) =>\n\t\t\t\tstatus === CustomerInvoiceStatus.PAID || status === \"PARTIALLY_PAID\",\n\t\t)\n\t)\n\t\treturn \"PARTIALLY_PAID\";\n\tif (statuses.every((status) => status === CustomerInvoiceStatus.SENT))\n\t\treturn CustomerInvoiceStatus.SENT;\n\tif (statuses.some((status) => status === CustomerInvoiceStatus.SENT))\n\t\treturn \"PARTIALLY_SENT\";\n\treturn batch.status;\n};\n", "import type { RouterInputs, RouterOutputs } from \"@go-labs/budget-builder-api\";\nimport { customerInvoiceLifecycleStatuses } from \"@go-labs/budget-builder-utils/customer-invoice-lifecycle\";\nimport {\n\tBudgetRole,\n\tDeals,\n\tExtendedApprovalStatus,\n\tExtendedBillStatus,\n\tExtendedErrorSeverity,\n\tExtendedErrorStatus,\n\tExtendedProjectStatus,\n\tTimeFrame,\n} from \"@go-labs/budget-builder-utils/filter-enums\";\nimport {\n\tBillStatus,\n\tBudgetStatus,\n\tProjectStatus,\n\tSupplierQuotationStatus,\n\tUserRole,\n} from \"@go-labs-sg/bb/prisma-enums\";\n\ntype NotificationRow =\n\tRouterOutputs[\"budget\"][\"getNotifications\"][\"notifications\"][number];\ntype PendingRequestRow = NotificationRow & { notificationType: \"request\" };\n\ntype GetAllBudgetsInput = RouterInputs[\"budget\"][\"getAllBudgets\"];\ntype GetBillListInput = RouterInputs[\"bill\"][\"getAll\"];\ntype IntegrationOperationListInput =\n\tRouterInputs[\"integration\"][\"listOperations\"];\ntype ListQuotationsInput = RouterInputs[\"quotation\"][\"listPage\"];\ntype UpdateBudgetStatusInput = RouterInputs[\"budget\"][\"updateBudgetStatus\"];\n\nexport type BudgetStatusListToken = NonNullable<\n\tGetAllBudgetsInput[\"statuses\"]\n>[number];\n\nexport type BillStatusListToken = NonNullable<\n\tGetBillListInput[\"statuses\"]\n>[number];\nexport type SupplierStatusListToken = NonNullable<\n\tRouterInputs[\"supplier\"][\"getSuppliers\"][\"status\"]\n>[number];\n\nexport type BudgetStatusUpdate = NonNullable<UpdateBudgetStatusInput[\"status\"]>;\n\nconst BUDGET_STATUS_VALUES = new Set<string>(Object.values(BudgetStatus));\nconst BILL_STATUS_VALUES = new Set<string>(Object.values(BillStatus));\nconst PROJECT_STATUS_VALUES = new Set<string>(Object.values(ProjectStatus));\nconst SUPPLIER_QUOTATION_STATUS_VALUES = new Set<string>(\n\tObject.values(SupplierQuotationStatus),\n);\nconst CUSTOMER_INVOICE_LIFECYCLE_STATUS_VALUES = new Set<string>(\n\tcustomerInvoiceLifecycleStatuses,\n);\nconst USER_ROLE_VALUES = new Set<string>(Object.values(UserRole));\nconst EXTENDED_PROJECT_STATUS_VALUES = new Set<string>(\n\tObject.values(ExtendedProjectStatus),\n);\nconst DASHBOARD_ROLE_VALUES = new Set<string>([\n\t\"BD\",\n\t\"CREATOR\",\n\t\"INSIDE_SALES\",\n\t\"ALL\",\n]);\nconst DEALS_VALUES = new Set<string>(Object.values(Deals));\nconst TIME_FRAME_VALUES = new Set<string>(Object.values(TimeFrame));\nconst BUDGET_ROLE_VALUES = new Set<string>(Object.values(BudgetRole));\nconst SUPPLIER_ANALYTICS_TF = new Set<string>([\n\t\"ALL\",\n\t\"LAST_YEAR\",\n\t\"LAST_6_MONTHS\",\n\t\"LAST_3_MONTHS\",\n\t\"CUSTOM\",\n]);\nconst SUPPLIER_APPROVAL_STATUS_VALUES = new Set<string>(\n\tObject.values(ExtendedApprovalStatus),\n);\nconst EXT_ERROR_SEVERITY_VALUES = new Set<string>(\n\tObject.values(ExtendedErrorSeverity),\n);\nconst EXT_ERROR_STATUS_VALUES = new Set<string>(\n\tObject.values(ExtendedErrorStatus),\n);\nconst INTEGRATION_OPERATION_STATUS_VALUES = new Set<string>([\n\t\"PENDING\",\n\t\"PROCESSING\",\n\t\"FAILED\",\n\t\"COMPLETED\",\n]);\n\ntype IntegrationOperationStatus = Extract<\n\tNonNullable<IntegrationOperationListInput[\"status\"]>,\n\tstring\n>;\n\nexport function isBudgetStatusListToken(s: string): s is BudgetStatusListToken {\n\tif (s === \"ALL\") return true;\n\treturn BUDGET_STATUS_VALUES.has(s);\n}\n\nexport function isBillStatusListToken(s: string): s is BillStatusListToken {\n\tif (s === \"ALL\") return true;\n\treturn BILL_STATUS_VALUES.has(s);\n}\n\nexport function isBudgetStatusUpdate(s: string): s is BudgetStatusUpdate {\n\treturn BUDGET_STATUS_VALUES.has(s);\n}\n\n/** For bill.updateStatus — PENDING_APPROVAL must use createBillApproval. */\nexport function parseBillStatusForUpdate(raw: string): BillStatus {\n\tif (!BILL_STATUS_VALUES.has(raw)) {\n\t\tthrow new Error(\n\t\t\t`Invalid bill status \"${raw}\". Use one of: ${[...BILL_STATUS_VALUES].join(\", \")}.`,\n\t\t);\n\t}\n\tif (raw === BillStatus.PENDING_APPROVAL) {\n\t\tthrow new Error(\n\t\t\t\"Cannot set PENDING_APPROVAL via update-bill-status. Use create-bill-approval <billId> instead.\",\n\t\t);\n\t}\n\treturn raw as BillStatus;\n}\n\nexport function parseProjectStatusForUpdate(raw: string): ProjectStatus {\n\tif (!PROJECT_STATUS_VALUES.has(raw)) {\n\t\tthrow new Error(\n\t\t\t`Invalid project status \"${raw}\". Use one of: ${[...PROJECT_STATUS_VALUES].join(\", \")}.`,\n\t\t);\n\t}\n\treturn raw as ProjectStatus;\n}\n\nexport function parseUserRole(raw: string | undefined): UserRole {\n\tif (raw === undefined || raw === \"\") return UserRole.USER;\n\tconst normalizedRole = raw.trim().toUpperCase();\n\tif (!USER_ROLE_VALUES.has(normalizedRole)) {\n\t\tthrow new Error(\n\t\t\t`Invalid user role \"${raw}\". Use one of: ${[...USER_ROLE_VALUES].join(\", \")}.`,\n\t\t);\n\t}\n\treturn normalizedRole as UserRole;\n}\n\nexport function parseOptionalExtendedProjectStatus(\n\traw: string | undefined,\n): ExtendedProjectStatus | undefined {\n\tif (raw === undefined || raw === \"\") return undefined;\n\tif (!EXTENDED_PROJECT_STATUS_VALUES.has(raw)) {\n\t\tthrow new Error(\n\t\t\t`Invalid project list status \"${raw}\". Use one of: ${[...EXTENDED_PROJECT_STATUS_VALUES].join(\", \")}.`,\n\t\t);\n\t}\n\treturn raw as ExtendedProjectStatus;\n}\n\nexport function parseCommaSeparatedProjectStatuses(\n\traw: string | undefined,\n): ProjectStatus[] | undefined {\n\tif (raw === undefined) return undefined;\n\tconst statuses = raw\n\t\t.split(\",\")\n\t\t.map((value) => value.trim().toUpperCase())\n\t\t.filter(Boolean);\n\tif (statuses.length === 0) return undefined;\n\n\tfor (const status of statuses) {\n\t\tif (!PROJECT_STATUS_VALUES.has(status)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Invalid project status \"${status}\". Use one of: ${[...PROJECT_STATUS_VALUES].join(\", \")}.`,\n\t\t\t);\n\t\t}\n\t}\n\n\treturn statuses as ProjectStatus[];\n}\n\nconst PROJECT_HUB_SORT_FIELDS = new Set<string>([\n\t\"startDate\",\n\t\"name\",\n\t\"companyName\",\n\t\"status\",\n]);\n\n/**\n * Parses an ISO date or datetime flag as UTC. Date-only values use UTC midnight\n * (or end of day); datetimes without an offset are read as UTC, not host time.\n */\nexport function parseOptionalIsoDateFlag(\n\traw: string | undefined,\n\tflagName: string,\n\t{ endOfDay = false }: { endOfDay?: boolean } = {},\n): Date | undefined {\n\tif (raw === undefined || raw === \"\") return undefined;\n\tconst value = /^\\d{4}-\\d{2}-\\d{2}$/.test(raw)\n\t\t? `${raw}T${endOfDay ? \"23:59:59.999\" : \"00:00:00.000\"}Z`\n\t\t: /T\\d{2}:\\d{2}(:\\d{2}(\\.\\d+)?)?$/.test(raw)\n\t\t\t? `${raw}Z`\n\t\t\t: raw;\n\tconst parsed = new Date(value);\n\tif (Number.isNaN(parsed.getTime())) {\n\t\tthrow new Error(\n\t\t\t`${flagName} must be an ISO date (YYYY-MM-DD) or ISO datetime.`,\n\t\t);\n\t}\n\treturn parsed;\n}\n\nexport function parseOptionalProjectHubSortBy(\n\traw: string | undefined,\n): \"startDate\" | \"name\" | \"companyName\" | \"status\" | undefined {\n\tif (raw === undefined || raw === \"\") return undefined;\n\tif (!PROJECT_HUB_SORT_FIELDS.has(raw)) {\n\t\tthrow new Error(\n\t\t\t`Invalid --sortBy \"${raw}\". Use one of: ${[...PROJECT_HUB_SORT_FIELDS].join(\", \")}.`,\n\t\t);\n\t}\n\treturn raw as \"startDate\" | \"name\" | \"companyName\" | \"status\";\n}\n\nexport function parseOptionalDashboardRole(\n\traw: string | undefined,\n): \"BD\" | \"CREATOR\" | \"INSIDE_SALES\" | \"ALL\" | undefined {\n\tif (raw === undefined || raw === \"\") return undefined;\n\tif (!DASHBOARD_ROLE_VALUES.has(raw)) {\n\t\tthrow ERROR_BAD_DASHBOARD_ROLE;\n\t}\n\treturn raw as \"BD\" | \"CREATOR\" | \"INSIDE_SALES\" | \"ALL\";\n}\n\nconst ERROR_BAD_DASHBOARD_ROLE = new Error(\n\t`Invalid dashboard role. Use one of: ${[...DASHBOARD_ROLE_VALUES].join(\", \")}.`,\n);\n\nexport function parseOptionalFinancialRole(\n\traw: string | undefined,\n): (typeof BudgetRole)[keyof typeof BudgetRole] | undefined {\n\tif (raw === undefined || raw === \"\") return undefined;\n\tif (!BUDGET_ROLE_VALUES.has(raw)) {\n\t\tthrow new Error(\n\t\t\t`Invalid financial role. Use one of: ${[...BUDGET_ROLE_VALUES].join(\", \")}.`,\n\t\t);\n\t}\n\treturn raw as (typeof BudgetRole)[keyof typeof BudgetRole];\n}\n\nexport function parseOptionalDeals(\n\traw: string | undefined,\n): (typeof Deals)[keyof typeof Deals] | undefined {\n\tif (raw === undefined || raw === \"\") return undefined;\n\tif (!DEALS_VALUES.has(raw)) {\n\t\tthrow new Error(\n\t\t\t`Invalid deals filter. Use one of: ${[...DEALS_VALUES].join(\", \")}.`,\n\t\t);\n\t}\n\treturn raw as (typeof Deals)[keyof typeof Deals];\n}\n\nexport function parseOptionalTimeFrame(\n\traw: string | undefined,\n): (typeof TimeFrame)[keyof typeof TimeFrame] | undefined {\n\tif (raw === undefined || raw === \"\") return undefined;\n\tif (!TIME_FRAME_VALUES.has(raw)) {\n\t\tthrow new Error(\n\t\t\t`Invalid timeFrame. Use one of: ${[...TIME_FRAME_VALUES].join(\", \")}.`,\n\t\t);\n\t}\n\treturn raw as (typeof TimeFrame)[keyof typeof TimeFrame];\n}\n\nexport function parseOptionalSupplierAnalyticsTimeFrame(\n\traw: string | undefined,\n): \"ALL\" | \"LAST_YEAR\" | \"LAST_6_MONTHS\" | \"LAST_3_MONTHS\" | \"CUSTOM\" {\n\tif (raw === undefined || raw === \"\") return \"ALL\";\n\tif (!SUPPLIER_ANALYTICS_TF.has(raw)) {\n\t\tthrow new Error(\n\t\t\t`Invalid supplier analytics timeFrame. Use one of: ${[...SUPPLIER_ANALYTICS_TF].join(\", \")}.`,\n\t\t);\n\t}\n\treturn raw as\n\t\t| \"ALL\"\n\t\t| \"LAST_YEAR\"\n\t\t| \"LAST_6_MONTHS\"\n\t\t| \"LAST_3_MONTHS\"\n\t\t| \"CUSTOM\";\n}\n\nexport function parseOptionalErrorSeverity(\n\traw: string | undefined,\n):\n\t| (typeof ExtendedErrorSeverity)[keyof typeof ExtendedErrorSeverity]\n\t| undefined {\n\tif (raw === undefined || raw === \"\") return undefined;\n\tif (!EXT_ERROR_SEVERITY_VALUES.has(raw)) {\n\t\tthrow new Error(\n\t\t\t`Invalid error severity. Use one of: ${[...EXT_ERROR_SEVERITY_VALUES].join(\", \")}.`,\n\t\t);\n\t}\n\treturn raw as (typeof ExtendedErrorSeverity)[keyof typeof ExtendedErrorSeverity];\n}\n\nexport function parseOptionalErrorStatus(\n\traw: string | undefined,\n): (typeof ExtendedErrorStatus)[keyof typeof ExtendedErrorStatus] | undefined {\n\tif (raw === undefined || raw === \"\") return undefined;\n\tif (!EXT_ERROR_STATUS_VALUES.has(raw)) {\n\t\tthrow new Error(\n\t\t\t`Invalid error status. Use one of: ${[...EXT_ERROR_STATUS_VALUES].join(\", \")}.`,\n\t\t);\n\t}\n\treturn raw as (typeof ExtendedErrorStatus)[keyof typeof ExtendedErrorStatus];\n}\n\n/** Comma-separated user IDs (e.g. `--createdByIds u1,u2` on list-bills). */\nexport function parseCommaSeparatedIds(\n\traw: string | undefined,\n): string[] | undefined {\n\tif (raw === undefined || raw.trim() === \"\") return undefined;\n\tconst ids = raw\n\t\t.split(\",\")\n\t\t.map((s) => s.trim())\n\t\t.filter(Boolean);\n\treturn ids.length > 0 ? ids : undefined;\n}\n\nexport function parseCommaSeparatedIntegrationOperationStatuses(\n\traw: string | undefined,\n): IntegrationOperationStatus[] | undefined {\n\tif (raw === undefined) return undefined;\n\tconst statuses = raw\n\t\t.split(\",\")\n\t\t.map((value) => value.trim().toUpperCase())\n\t\t.filter(Boolean);\n\tif (statuses.length === 0) return undefined;\n\n\tfor (const status of statuses) {\n\t\tif (!INTEGRATION_OPERATION_STATUS_VALUES.has(status)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Invalid integration operation status \"${status}\". Use one or more of: ${[...INTEGRATION_OPERATION_STATUS_VALUES].join(\", \")}.`,\n\t\t\t);\n\t\t}\n\t}\n\n\treturn statuses as IntegrationOperationStatus[];\n}\n\nexport function parseCommaSeparatedBudgetStatuses(\n\traw: string | undefined,\n): GetAllBudgetsInput[\"statuses\"] | undefined {\n\tif (raw === undefined) return undefined;\n\tconst parts = raw\n\t\t.split(\",\")\n\t\t.map((x) => x.trim())\n\t\t.filter(Boolean);\n\tif (parts.length === 0) return undefined;\n\tconst out: BudgetStatusListToken[] = [];\n\tfor (const p of parts) {\n\t\tif (!isBudgetStatusListToken(p)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Invalid budget status \"${p}\". Use ALL or one of: ${[...BUDGET_STATUS_VALUES].join(\", \")}.`,\n\t\t\t);\n\t\t}\n\t\tout.push(p);\n\t}\n\treturn out;\n}\n\nexport function parseCommaSeparatedSupplierStatuses(\n\traw: string | undefined,\n): RouterInputs[\"supplier\"][\"getSuppliers\"][\"status\"] | undefined {\n\tif (raw === undefined) return undefined;\n\tconst parts = raw\n\t\t.split(\",\")\n\t\t.map((x) => x.trim())\n\t\t.filter(Boolean);\n\tif (parts.length === 0) return undefined;\n\tconst out: SupplierStatusListToken[] = [];\n\tfor (const p of parts) {\n\t\tif (!SUPPLIER_APPROVAL_STATUS_VALUES.has(p)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Invalid supplier approval status \"${p}\". Use one of: ${[...SUPPLIER_APPROVAL_STATUS_VALUES].join(\", \")}.`,\n\t\t\t);\n\t\t}\n\t\tout.push(p as SupplierStatusListToken);\n\t}\n\treturn out;\n}\n\nexport function parseCommaSeparatedQuotationStatuses(\n\traw: string | undefined,\n): ListQuotationsInput[\"status\"] | undefined {\n\tif (raw === undefined) return undefined;\n\tconst parts = raw\n\t\t.split(\",\")\n\t\t.map((value) => value.trim().toUpperCase())\n\t\t.filter(Boolean);\n\tif (parts.length === 0) return undefined;\n\n\tfor (const status of parts) {\n\t\tif (!SUPPLIER_QUOTATION_STATUS_VALUES.has(status)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Invalid quotation status \"${status}\". Use one of: ${[...SUPPLIER_QUOTATION_STATUS_VALUES].join(\", \")}.`,\n\t\t\t);\n\t\t}\n\t}\n\n\treturn parts as ListQuotationsInput[\"status\"];\n}\n\nexport function parseCommaSeparatedCustomerInvoiceStatuses(\n\traw: string | undefined,\n): RouterInputs[\"customerInvoice\"][\"list\"][\"statuses\"] | undefined {\n\tif (raw === undefined) return undefined;\n\tconst parts = raw\n\t\t.split(\",\")\n\t\t.map((value) => value.trim().toUpperCase())\n\t\t.filter(Boolean);\n\tif (parts.length === 0) return undefined;\n\n\tfor (const status of parts) {\n\t\tif (!CUSTOMER_INVOICE_LIFECYCLE_STATUS_VALUES.has(status)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Invalid customer invoice status \"${status}\". Use one of: ${[...CUSTOMER_INVOICE_LIFECYCLE_STATUS_VALUES].join(\", \")}.`,\n\t\t\t);\n\t\t}\n\t}\n\n\treturn parts as RouterInputs[\"customerInvoice\"][\"list\"][\"statuses\"];\n}\n\nexport function parseBillStatusFlag(\n\traw: string | undefined,\n): BillStatusListToken | undefined {\n\tif (raw === undefined) return undefined;\n\tif (!isBillStatusListToken(raw)) {\n\t\tthrow new Error(\n\t\t\t`Invalid bill status \"${raw}\". Use ALL or one of: ${[...BILL_STATUS_VALUES].join(\", \")}.`,\n\t\t);\n\t}\n\treturn raw;\n}\n\n/** Comma-separated bill statuses (`ALL` or `BillStatus` values), same as list-budgets `--status`. */\nexport function parseCommaSeparatedBillStatuses(\n\traw: string | undefined,\n): GetBillListInput[\"statuses\"] | undefined {\n\tif (raw === undefined) return undefined;\n\tconst parts = raw\n\t\t.split(\",\")\n\t\t.map((x) => x.trim())\n\t\t.filter(Boolean);\n\tif (parts.length === 0) return undefined;\n\tconst out: BillStatusListToken[] = [];\n\tfor (const p of parts) {\n\t\tif (!isBillStatusListToken(p)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Invalid bill status \"${p}\". Use ALL or one of: ${[...BILL_STATUS_VALUES].join(\", \")}.`,\n\t\t\t);\n\t\t}\n\t\tout.push(p);\n\t}\n\treturn out;\n}\n\n/** Strip `ALL` tokens; empty after strip => no status filter (all statuses). */\nexport function billStatusesForApi(\n\tstatuses: GetBillListInput[\"statuses\"] | undefined,\n): GetBillListInput[\"statuses\"] | undefined {\n\tif (!statuses?.length) return undefined;\n\tconst withoutAll = statuses.filter((s) => s !== ExtendedBillStatus.ALL);\n\treturn withoutAll.length > 0 ? withoutAll : undefined;\n}\n\nconst BILL_SORT_BY = new Set<string>([\"createdAt\", \"amount\", \"status\"]);\n\nexport function parseOptionalBillListSortBy(\n\traw: string | undefined,\n): \"createdAt\" | \"amount\" | \"status\" | undefined {\n\tif (raw === undefined || raw === \"\") return undefined;\n\tif (!BILL_SORT_BY.has(raw)) {\n\t\tthrow new Error(\n\t\t\t`Invalid --sortBy \"${raw}\". Use one of: ${[...BILL_SORT_BY].join(\", \")}.`,\n\t\t);\n\t}\n\treturn raw as \"createdAt\" | \"amount\" | \"status\";\n}\n\nexport function parseOptionalBillListSortDir(\n\traw: string | undefined,\n): \"asc\" | \"desc\" | undefined {\n\tif (raw === undefined || raw === \"\") return undefined;\n\tif (raw !== \"asc\" && raw !== \"desc\") {\n\t\tthrow new Error(`Invalid --sortDir \"${raw}\". Use asc or desc.`);\n\t}\n\treturn raw;\n}\n\nexport type ApprovalCliFilter = PendingRequestRow[\"type\"] | \"ALL\";\n\nfunction isPendingRequestType(s: string): s is PendingRequestRow[\"type\"] {\n\treturn (\n\t\ts === \"BUDGET\" ||\n\t\ts === \"BILL\" ||\n\t\ts === \"SUPPLIER\" ||\n\t\ts === \"QUOTATION\" ||\n\t\ts === \"CUSTOMER_INVOICE\"\n\t);\n}\n\nexport function parseApprovalTypeFlag(\n\traw: string | undefined,\n): ApprovalCliFilter | undefined {\n\tif (raw === undefined) return undefined;\n\tconst u = raw.trim().toUpperCase();\n\tif (u === \"ALL\") return \"ALL\";\n\tif (!isPendingRequestType(u)) {\n\t\tthrow new Error(\n\t\t\t`Invalid --type \"${raw}\". Use budget, supplier, bill, quotation, customer_invoice, or all.`,\n\t\t);\n\t}\n\treturn u;\n}\n\n/** For help text / error messages (values from `./prisma-enums.js`, synced with Prisma). */\nexport const budgetStatusesForHelp = Object.values(BudgetStatus);\nexport const billStatusesForHelp = Object.values(BillStatus);\nexport const billStatusesForUpdateHelp = Object.values(BillStatus).filter(\n\t(s) => s !== BillStatus.PENDING_APPROVAL,\n);\nexport const projectStatusesForHelp = Object.values(ProjectStatus);\nexport const userRolesForHelp = Object.values(UserRole);\n", "import { z } from \"zod\";\n\nexport const QUICKBOOKS_NAME_VALIDATION_MESSAGE =\n\t\"Name cannot contain colons, tabs or line breaks (QuickBooks rule)\";\n\n/**\n * Mirrors the QuickBooks Online API business rules for the names Budget Builder\n * syncs: Customer/Vendor `DisplayName` and Item `Name` must not contain colon,\n * tab or newline (colons are QBO's parent:child separator). Item `Name` is\n * capped at 100 characters (DisplayName allows 500), so the shared cap is 100.\n * @see https://developer.intuit.com/app/developer/qbo/docs/api/accounting/all-entities/customer\n * @see https://developer.intuit.com/app/developer/qbo/docs/api/accounting/all-entities/vendor\n * @see https://developer.intuit.com/app/developer/qbo/docs/api/accounting/all-entities/item\n */\nexport const quickBooksNameSchema = z\n\t.string()\n\t.trim()\n\t.min(1, { error: \"Name is required\" })\n\t.max(100, { error: \"Name cannot be longer than 100 characters\" })\n\t.regex(/^[^:\\t\\n]+$/, {\n\t\terror: QUICKBOOKS_NAME_VALIDATION_MESSAGE,\n\t});\n", "export interface RichTextJsonShape {\n\tjson: {\n\t\ttype: \"doc\";\n\t\tcontent: Array<{\n\t\t\ttype: \"paragraph\";\n\t\t\tcontent?: Array<{ type: \"text\"; text: string }>;\n\t\t}>;\n\t};\n\thtml: string;\n}\n\nconst escapeHtml = (text: string): string =>\n\ttext\n\t\t.replace(/&/g, \"&amp;\")\n\t\t.replace(/</g, \"&lt;\")\n\t\t.replace(/>/g, \"&gt;\")\n\t\t.replace(/\"/g, \"&quot;\")\n\t\t.replace(/'/g, \"&#39;\");\n\nexport const createRichTextFromPlainText = (\n\ttext: string | null | undefined,\n): RichTextJsonShape => {\n\tconst lines = text?.split(/\\r?\\n/) ?? [];\n\tconst paragraphs = lines.length ? lines : [\"\"];\n\n\treturn {\n\t\tjson: {\n\t\t\ttype: \"doc\",\n\t\t\tcontent: paragraphs.map((line) => ({\n\t\t\t\ttype: \"paragraph\",\n\t\t\t\t...(line ? { content: [{ type: \"text\" as const, text: line }] } : {}),\n\t\t\t})),\n\t\t},\n\t\thtml: paragraphs.map((line) => `<p>${escapeHtml(line)}</p>`).join(\"\"),\n\t};\n};\n\nexport const isRichTextJson = (value: unknown): value is RichTextJsonShape =>\n\tBoolean(\n\t\tvalue &&\n\t\t\ttypeof value === \"object\" &&\n\t\t\t\"json\" in value &&\n\t\t\t\"html\" in value &&\n\t\t\ttypeof (value as { html?: unknown }).html === \"string\",\n\t);\n", "import {\n\tcreateRichTextFromPlainText,\n\tisRichTextJson,\n} from \"@go-labs/budget-builder-utils/rich-text\";\n\nexport { createRichTextFromPlainText, isRichTextJson };\n\nexport const normalizePlainTextRichTextField = <\n\tTInput extends Record<string, unknown>,\n>({\n\tinput,\n\ttextField,\n\trichTextField,\n}: {\n\tinput: TInput;\n\ttextField: keyof TInput & string;\n\trichTextField: keyof TInput & string;\n}): TInput => {\n\tif (isRichTextJson(input[richTextField]) || input[textField] === undefined) {\n\t\treturn input;\n\t}\n\n\treturn {\n\t\t...input,\n\t\t[richTextField]: createRichTextFromPlainText(\n\t\t\tString(input[textField] ?? \"\"),\n\t\t),\n\t};\n};\n", "import type { RouterInputs } from \"@go-labs/budget-builder-api\";\nimport { quickBooksNameSchema } from \"@go-labs/budget-builder-validators/quickbooks/qbo-name\";\nimport { BillVerificationStatus } from \"@go-labs-sg/bb/prisma-enums\";\nimport { normalizePlainTextRichTextField } from \"@go-labs-sg/bb/rich-text\";\nimport { CliRuntimeError } from \"@go-labs-sg/bb/runtime/error\";\n\nconst validationError = (message: string): CliRuntimeError =>\n\tnew CliRuntimeError(\"VALIDATION\", message);\n\nfunction requireObject(raw: unknown, label: string): Record<string, unknown> {\n\tif (raw === null || typeof raw !== \"object\" || Array.isArray(raw)) {\n\t\tthrow validationError(`${label} must be a JSON object.`);\n\t}\n\treturn raw as Record<string, unknown>;\n}\n\nfunction toDate(value: unknown, field: string): Date {\n\tif (value instanceof Date && !Number.isNaN(value.getTime())) {\n\t\treturn value;\n\t}\n\tif (typeof value === \"string\") {\n\t\tconst d = new Date(value);\n\t\tif (!Number.isNaN(d.getTime())) return d;\n\t}\n\tthrow validationError(`${field} must be an ISO date/datetime string.`);\n}\n\nfunction optionalString(v: unknown): string | undefined {\n\tif (v === undefined || v === null) return undefined;\n\tconst s = String(v);\n\treturn s === \"\" ? undefined : s;\n}\n\ninterface ParsedQuotationReferences {\n\tquotationId?: string;\n\tquotationIds?: string[];\n\tquotationAllocations?: Array<{\n\t\tbudgetItemId: string;\n\t\tquotationId: string;\n\t\tamount: number;\n\t}>;\n}\n\nconst requireDollarAmount = (\n\tsource: Record<string, unknown>,\n\tlabel: string,\n): number => {\n\tconst amount = Number(source.amount);\n\tif (\n\t\t!Number.isFinite(amount) ||\n\t\tamount < 0 ||\n\t\t!Number.isInteger(amount * 100)\n\t) {\n\t\tthrow validationError(\n\t\t\t`${label}.amount must be a non-negative dollar amount (ex-GST) with at most 2 decimal places.`,\n\t\t);\n\t}\n\treturn amount;\n};\n\nconst parseQuotationAllocations = (\n\tinput: Record<string, unknown>,\n\tcommandName: string,\n): ParsedQuotationReferences[\"quotationAllocations\"] => {\n\tconst rawAllocations = input.quotationAllocations;\n\tif (rawAllocations === undefined || rawAllocations === null) return undefined;\n\tif (!Array.isArray(rawAllocations) || rawAllocations.length === 0) {\n\t\tthrow validationError(\n\t\t\t`${commandName} payload.quotationAllocations must be a non-empty array.`,\n\t\t);\n\t}\n\tconst quotationAllocations = rawAllocations.map((raw, index) => {\n\t\tconst label = `${commandName} payload.quotationAllocations[${index}]`;\n\t\tconst allocation = requireObject(raw, label);\n\t\tconst amount = requireDollarAmount(allocation, label);\n\t\treturn {\n\t\t\tbudgetItemId: requiredString(\n\t\t\t\tallocation.budgetItemId,\n\t\t\t\t`${label}.budgetItemId`,\n\t\t\t),\n\t\t\tquotationId: requiredString(\n\t\t\t\tallocation.quotationId,\n\t\t\t\t`${label}.quotationId`,\n\t\t\t),\n\t\t\tamount,\n\t\t};\n\t});\n\tconst keys = quotationAllocations.map(\n\t\t(allocation) => `${allocation.budgetItemId}\\0${allocation.quotationId}`,\n\t);\n\tif (new Set(keys).size !== keys.length) {\n\t\tthrow validationError(\n\t\t\t`${commandName} payload.quotationAllocations must not repeat a budget-item/quotation pair.`,\n\t\t);\n\t}\n\treturn quotationAllocations;\n};\n\nconst parseQuotationIdList = (\n\tinput: Record<string, unknown>,\n\tcommandName: string,\n): string[] | undefined => {\n\tconst rawQuotationIds = input.quotationIds;\n\tif (rawQuotationIds === undefined || rawQuotationIds === null) {\n\t\treturn undefined;\n\t}\n\tif (!Array.isArray(rawQuotationIds)) {\n\t\tthrow validationError(\n\t\t\t`${commandName} payload.quotationIds must be a string array.`,\n\t\t);\n\t}\n\tconst quotationIds = rawQuotationIds.map((id, index) =>\n\t\trequiredString(id, `${commandName} payload.quotationIds[${index}]`),\n\t);\n\tif (new Set(quotationIds).size !== quotationIds.length) {\n\t\tthrow validationError(\n\t\t\t`${commandName} payload.quotationIds must not contain duplicates.`,\n\t\t);\n\t}\n\treturn quotationIds;\n};\n\nconst parseQuotationReferences = (\n\tinput: Record<string, unknown>,\n\tcommandName: string,\n): ParsedQuotationReferences => {\n\tconst quotationId = optionalString(input.quotationId)?.trim();\n\tconst quotationAllocations = parseQuotationAllocations(input, commandName);\n\tconst quotationIds = parseQuotationIdList(input, commandName);\n\tif (\n\t\tquotationId &&\n\t\tquotationIds &&\n\t\t(quotationIds.length !== 1 || quotationIds[0] !== quotationId)\n\t) {\n\t\tthrow validationError(\n\t\t\t`${commandName} payload.quotationId conflicts with payload.quotationIds.`,\n\t\t);\n\t}\n\tif (quotationAllocations && quotationIds) {\n\t\tconst allocationIds = [\n\t\t\t...new Set(\n\t\t\t\tquotationAllocations.map((allocation) => allocation.quotationId),\n\t\t\t),\n\t\t].sort();\n\t\tconst selectedIds = [...quotationIds].sort();\n\t\tif (allocationIds.join(\"\\0\") !== selectedIds.join(\"\\0\")) {\n\t\t\tthrow validationError(\n\t\t\t\t`${commandName} payload.quotationIds conflicts with payload.quotationAllocations.`,\n\t\t\t);\n\t\t}\n\t}\n\treturn {\n\t\t...(quotationId ? { quotationId } : {}),\n\t\t...(quotationIds ? { quotationIds } : {}),\n\t\t...(quotationAllocations ? { quotationAllocations } : {}),\n\t};\n};\n\nconst parseBillLineAmounts = (\n\tinput: Record<string, unknown>,\n\tcommandName: string,\n) => {\n\tif (input.lineAmounts === undefined || input.lineAmounts === null)\n\t\treturn undefined;\n\tif (!Array.isArray(input.lineAmounts) || input.lineAmounts.length === 0) {\n\t\tthrow validationError(\n\t\t\t`${commandName} payload.lineAmounts must be a non-empty array.`,\n\t\t);\n\t}\n\tconst lineAmounts = input.lineAmounts.map((raw, index) => {\n\t\tconst label = `${commandName} payload.lineAmounts[${index}]`;\n\t\tconst line = requireObject(raw, label);\n\t\tconst amount = requireDollarAmount(line, label);\n\t\treturn {\n\t\t\tbudgetItemId: requiredString(line.budgetItemId, `${label}.budgetItemId`),\n\t\t\tamount,\n\t\t};\n\t});\n\tif (\n\t\tnew Set(lineAmounts.map((line) => line.budgetItemId)).size !==\n\t\tlineAmounts.length\n\t) {\n\t\tthrow validationError(\n\t\t\t`${commandName} payload.lineAmounts must contain each budget item once.`,\n\t\t);\n\t}\n\treturn lineAmounts;\n};\n\nconst cents = (amount: number) => Math.round(amount * 100);\n\ntype BillLineAmounts = NonNullable<ReturnType<typeof parseBillLineAmounts>>;\ntype BillQuotationAllocations = NonNullable<\n\tParsedQuotationReferences[\"quotationAllocations\"]\n>;\n\nconst assertLineAmountsMatchSelection = ({\n\tamount,\n\tbudgetItemIds,\n\tcommandName,\n\tlineAmounts,\n}: {\n\tamount: number;\n\tbudgetItemIds: string[];\n\tcommandName: string;\n\tlineAmounts: BillLineAmounts;\n}) => {\n\tconst selected = new Set(budgetItemIds);\n\tif (\n\t\tlineAmounts.length !== selected.size ||\n\t\tlineAmounts.some((line) => !selected.has(line.budgetItemId))\n\t) {\n\t\tthrow validationError(\n\t\t\t`${commandName} payload.lineAmounts must contain each selected budget item exactly once.`,\n\t\t);\n\t}\n\tif (\n\t\tlineAmounts.reduce((sum, line) => sum + cents(line.amount), 0) !==\n\t\tcents(amount)\n\t) {\n\t\tthrow validationError(\n\t\t\t`${commandName} payload.lineAmounts must sum to payload.amount.`,\n\t\t);\n\t}\n};\n\nconst assertQuotationAllocationsFitLines = ({\n\tbudgetItemIds,\n\tcommandName,\n\tlineAmounts,\n\tquotationAllocations,\n}: {\n\tbudgetItemIds: string[];\n\tcommandName: string;\n\tlineAmounts: BillLineAmounts;\n\tquotationAllocations: BillQuotationAllocations;\n}) => {\n\tconst selected = new Set(budgetItemIds);\n\tconst lineAmountById = new Map(\n\t\tlineAmounts.map((line) => [line.budgetItemId, cents(line.amount)]),\n\t);\n\tconst allocatedById = new Map<string, number>();\n\tfor (const allocation of quotationAllocations) {\n\t\tif (!selected.has(allocation.budgetItemId)) {\n\t\t\tthrow validationError(\n\t\t\t\t`${commandName} payload.quotationAllocations references an unselected budget item.`,\n\t\t\t);\n\t\t}\n\t\tallocatedById.set(\n\t\t\tallocation.budgetItemId,\n\t\t\t(allocatedById.get(allocation.budgetItemId) ?? 0) +\n\t\t\t\tcents(allocation.amount),\n\t\t);\n\t\tif (\n\t\t\tcents(allocation.amount) === 0 &&\n\t\t\tlineAmountById.get(allocation.budgetItemId) !== 0\n\t\t) {\n\t\t\tthrow validationError(\n\t\t\t\t`${commandName} zero quotation allocations are only valid for zero-value bill lines.`,\n\t\t\t);\n\t\t}\n\t}\n\tfor (const [budgetItemId, allocated] of allocatedById) {\n\t\tif (allocated > (lineAmountById.get(budgetItemId) ?? 0)) {\n\t\t\tthrow validationError(\n\t\t\t\t`${commandName} quotation allocations exceed the line amount for ${budgetItemId}.`,\n\t\t\t);\n\t\t}\n\t}\n};\n\nconst validateExplicitBillAllocations = ({\n\tamount,\n\tbudgetItemIds,\n\tcommandName,\n\tlineAmounts,\n\tquotationAllocations,\n}: {\n\tamount: number;\n\tbudgetItemIds: string[];\n\tcommandName: string;\n\tlineAmounts: ReturnType<typeof parseBillLineAmounts>;\n\tquotationAllocations: ParsedQuotationReferences[\"quotationAllocations\"];\n}) => {\n\tif (!lineAmounts && !quotationAllocations) return;\n\tif (!lineAmounts) {\n\t\tthrow validationError(\n\t\t\t`${commandName} payload.lineAmounts is required with quotationAllocations.`,\n\t\t);\n\t}\n\tassertLineAmountsMatchSelection({\n\t\tamount,\n\t\tbudgetItemIds,\n\t\tcommandName,\n\t\tlineAmounts,\n\t});\n\tif (!quotationAllocations) return;\n\tassertQuotationAllocationsFitLines({\n\t\tbudgetItemIds,\n\t\tcommandName,\n\t\tlineAmounts,\n\t\tquotationAllocations,\n\t});\n};\n\n/** Required string fields: rejects null/undefined, whitespace-only, and avoids String(undefined) → \"undefined\" passing Zod .min(1). */\nfunction requiredString(value: unknown, fieldLabel: string): string {\n\tif (value === undefined || value === null) {\n\t\tthrow validationError(`${fieldLabel} is required.`);\n\t}\n\tconst s = typeof value === \"string\" ? value : String(value);\n\tconst t = s.trim();\n\tif (t === \"\") {\n\t\tthrow validationError(`${fieldLabel} is required.`);\n\t}\n\treturn t;\n}\n\nconst EMAIL_ADDRESS_PATTERN = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\n\nconst requiredEmail = (value: unknown, fieldLabel: string): string => {\n\tconst email = requiredString(value, fieldLabel);\n\tif (!EMAIL_ADDRESS_PATTERN.test(email)) {\n\t\tthrow validationError(`${fieldLabel} must be a valid email address.`);\n\t}\n\treturn email;\n};\n\ninterface ContactPersonEmailPayload {\n\tto: string;\n\tcc: string[];\n\treplyTo: string;\n\tsubject: string;\n\tcontent: string;\n\tsignature: string;\n}\n\nconst parseContactPersonEmailPayload = (\n\tinput: Record<string, unknown>,\n\tcommandName: string,\n): ContactPersonEmailPayload => {\n\tif (!Array.isArray(input.cc)) {\n\t\tthrow validationError(`${commandName} payload.cc must be an email array.`);\n\t}\n\n\treturn {\n\t\tto: requiredEmail(input.to, `${commandName} payload.to`),\n\t\tcc: input.cc.map((email, index) =>\n\t\t\trequiredEmail(email, `${commandName} payload.cc[${index}]`),\n\t\t),\n\t\treplyTo: requiredEmail(input.replyTo, `${commandName} payload.replyTo`),\n\t\tsubject: requiredString(input.subject, `${commandName} payload.subject`),\n\t\tcontent: requiredString(input.content, `${commandName} payload.content`),\n\t\tsignature: requiredString(\n\t\t\tinput.signature,\n\t\t\t`${commandName} payload.signature`,\n\t\t),\n\t};\n};\n\n/** Matches the web estimate composer (`email.sendEstimateToContactPerson`). */\nexport const parseSendEstimateToContactPersonPayload = (\n\traw: unknown,\n): RouterInputs[\"email\"][\"sendEstimateToContactPerson\"] => {\n\tconst input = requireObject(raw, \"send-estimate-to-contact-person payload\");\n\n\treturn {\n\t\t...parseContactPersonEmailPayload(input, \"send-estimate-to-contact-person\"),\n\t\testimateId: requiredString(\n\t\t\tinput.estimateId,\n\t\t\t\"send-estimate-to-contact-person payload.estimateId\",\n\t\t),\n\t\testimateDocNumber: optionalString(input.estimateDocNumber),\n\t\tbudgetId: requiredString(\n\t\t\tinput.budgetId,\n\t\t\t\"send-estimate-to-contact-person payload.budgetId\",\n\t\t),\n\t};\n};\n\n/** Matches the web customer-invoice email composer. */\nexport const parseSendCustomerInvoiceToContactPersonPayload = (\n\traw: unknown,\n): RouterInputs[\"customerInvoice\"][\"sendInvoiceToContactPerson\"] => {\n\tconst input = requireObject(\n\t\traw,\n\t\t\"send-customer-invoice-to-contact-person payload\",\n\t);\n\n\tconst { cc, ...email } = parseContactPersonEmailPayload(\n\t\t{ ...input, cc: input.cc === undefined ? [] : input.cc },\n\t\t\"send-customer-invoice-to-contact-person\",\n\t);\n\treturn {\n\t\t...email,\n\t\t// Do not materialize an empty Cc when omitted: the API uses company defaults.\n\t\t...(input.cc === undefined ? {} : { cc }),\n\t\tinvoiceId: requiredString(\n\t\t\tinput.invoiceId,\n\t\t\t\"send-customer-invoice-to-contact-person payload.invoiceId\",\n\t\t),\n\t};\n};\n\n/** Matches budget.createBudget; the Asana deal is project.asanaTaskId. */\nexport function parseCreateBudgetPayload(\n\traw: unknown,\n): RouterInputs[\"budget\"][\"createBudget\"] {\n\tconst o = requireObject(raw, \"create-budget payload\");\n\tif (\n\t\to.unavailableItemReviewAcknowledged !== undefined &&\n\t\ttypeof o.unavailableItemReviewAcknowledged !== \"boolean\"\n\t) {\n\t\tthrow validationError(\n\t\t\t\"create-budget payload.unavailableItemReviewAcknowledged must be a boolean when set.\",\n\t\t);\n\t}\n\treturn {\n\t\tname: requiredString(o.name, \"create-budget payload.name\"),\n\t\tbudget: requiredString(o.budget, \"create-budget payload.budget\"),\n\t\tpaymentTerm: requiredString(\n\t\t\to.paymentTerm,\n\t\t\t\"create-budget payload.paymentTerm\",\n\t\t),\n\t\tcategoryId: requiredString(\n\t\t\to.categoryId,\n\t\t\t\"create-budget payload.categoryId\",\n\t\t),\n\t\tprojectId: requiredString(o.projectId, \"create-budget payload.projectId\"),\n\t\tsourceBudgetId: optionalString(o.sourceBudgetId),\n\t\t...(o.unavailableItemReviewAcknowledged !== undefined && {\n\t\t\tunavailableItemReviewAcknowledged:\n\t\t\t\to.unavailableItemReviewAcknowledged as boolean,\n\t\t}),\n\t};\n}\n\n/** Matches budget.updateBudget — same as create plus id. */\nexport function parseUpdateBudgetPayload(\n\traw: unknown,\n): RouterInputs[\"budget\"][\"updateBudget\"] {\n\tconst o = requireObject(raw, \"update-budget payload\");\n\tconst id = requiredString(o.id, \"update-budget payload.id\");\n\tconst base = parseCreateBudgetPayload(raw);\n\treturn { ...base, id };\n}\n\nexport function parseUpdateBudgetCommissionPayload(\n\traw: unknown,\n): RouterInputs[\"budget\"][\"updateBudgetCommission\"] {\n\tconst o = requireObject(raw, \"update-budget-commission payload\");\n\treturn {\n\t\tbudgetId: requiredString(\n\t\t\to.budgetId,\n\t\t\t\"update-budget-commission payload.budgetId\",\n\t\t),\n\t\tname: requiredString(o.name, \"update-budget-commission payload.name\"),\n\t\tpercentage: requiredString(\n\t\t\to.percentage,\n\t\t\t\"update-budget-commission payload.percentage\",\n\t\t),\n\t\ttotalSellingAfterDiscount: Number(o.totalSellingAfterDiscount),\n\t};\n}\n\nexport function parseBudgetDiscountPayload(\n\traw: unknown,\n): RouterInputs[\"budget\"][\"updateBudgetDiscount\"] {\n\tconst o = requireObject(raw, \"update-budget-discount payload\");\n\tconst type = o.type;\n\tif (type !== \"percentage\" && type !== \"amount\") {\n\t\tthrow validationError(\n\t\t\t'update-budget-discount payload.type must be \"percentage\" or \"amount\".',\n\t\t);\n\t}\n\treturn {\n\t\tbudgetId: requiredString(\n\t\t\to.budgetId,\n\t\t\t\"update-budget-discount payload.budgetId\",\n\t\t),\n\t\tname: requiredString(o.name, \"update-budget-discount payload.name\"),\n\t\ttype,\n\t\tvalue: requiredString(o.value, \"update-budget-discount payload.value\"),\n\t\ttotalSellingBeforeDiscount: Number(o.totalSellingBeforeDiscount),\n\t};\n}\n\nconst billAttachment = (x: unknown, i: number, field = \"attachments\") => {\n\tconst label = `create-bill payload.${field}[${i}]`;\n\tconst a = requireObject(x, label);\n\treturn {\n\t\tid: requiredString(a.id, `${label}.id`),\n\t\tname: requiredString(a.name, `${label}.name`),\n\t\tkey: requiredString(a.key, `${label}.key`),\n\t\tsize: Number(a.size),\n\t};\n};\n\nconst billAttachmentList = (raw: unknown, field = \"attachments\") =>\n\tArray.isArray(raw) ? raw.map((x, i) => billAttachment(x, i, field)) : [];\n\nconst optionalNumber = (value: unknown): number | undefined =>\n\tvalue === undefined || value === null ? undefined : Number(value);\n\nconst nullableNumber = (value: unknown): number | null =>\n\tvalue === null || value === undefined ? null : Number(value);\n\nconst parseCreateBillDraftOnly = (\n\to: Record<string, unknown>,\n\tdraftOnlyFlag: boolean | undefined,\n): boolean | undefined => {\n\tconst draftOnlyRaw = o.draftOnly;\n\tif (draftOnlyRaw !== undefined && typeof draftOnlyRaw !== \"boolean\") {\n\t\tthrow validationError(\"create-bill payload.draftOnly must be boolean.\");\n\t}\n\tif (\n\t\tdraftOnlyFlag !== undefined &&\n\t\tdraftOnlyRaw !== undefined &&\n\t\tdraftOnlyFlag !== draftOnlyRaw\n\t) {\n\t\tthrow validationError(\"--draft-only conflicts with payload.draftOnly.\");\n\t}\n\treturn draftOnlyFlag ?? draftOnlyRaw;\n};\n\nconst parseCreateBillAlreadyPaid = (\n\to: Record<string, unknown>,\n\tdraftOnly: boolean | undefined,\n): boolean | null | undefined => {\n\tconst alreadyPaidRaw = o.alreadyPaid;\n\tif (draftOnly && alreadyPaidRaw === true) {\n\t\tthrow validationError(\n\t\t\t\"Draft-only creation cannot be combined with alreadyPaid: true.\",\n\t\t);\n\t}\n\tif (\n\t\talreadyPaidRaw !== undefined &&\n\t\talreadyPaidRaw !== null &&\n\t\ttypeof alreadyPaidRaw !== \"boolean\"\n\t) {\n\t\tthrow validationError(\"create-bill payload.alreadyPaid must be boolean.\");\n\t}\n\treturn alreadyPaidRaw;\n};\n\nconst parseCreateBillVerificationResults = (\n\tvr: unknown,\n): RouterInputs[\"bill\"][\"create\"][\"verificationResults\"] | undefined => {\n\tif (vr === undefined || vr === null) return undefined;\n\tconst v = requireObject(vr, \"verificationResults\");\n\tconst verificationResultStatus = v.status;\n\tif (\n\t\tverificationResultStatus !== BillVerificationStatus.PENDING &&\n\t\tverificationResultStatus !== BillVerificationStatus.PASS &&\n\t\tverificationResultStatus !== BillVerificationStatus.FAIL &&\n\t\tverificationResultStatus !== BillVerificationStatus.MANUAL_REVIEW\n\t) {\n\t\tthrow validationError(\n\t\t\t\"create-bill payload.verificationResults.status must be PENDING | PASS | FAIL | MANUAL_REVIEW.\",\n\t\t);\n\t}\n\treturn {\n\t\tstatus: verificationResultStatus,\n\t\textractedAmount: nullableNumber(v.extractedAmount),\n\t\tdifference: nullableNumber(v.difference),\n\t\tconfidence: nullableNumber(v.confidence),\n\t\tfailureReason:\n\t\t\tv.failureReason === null || v.failureReason === undefined\n\t\t\t\t? null\n\t\t\t\t: String(v.failureReason),\n\t};\n};\n\nconst parseCreateBillVerificationStatus = (\n\tverificationStatus: unknown,\n): RouterInputs[\"bill\"][\"create\"][\"verificationStatus\"] | undefined => {\n\tif (\n\t\tverificationStatus === BillVerificationStatus.PENDING ||\n\t\tverificationStatus === BillVerificationStatus.PASS ||\n\t\tverificationStatus === BillVerificationStatus.FAIL ||\n\t\tverificationStatus === BillVerificationStatus.MANUAL_REVIEW\n\t) {\n\t\treturn verificationStatus;\n\t}\n\tif (verificationStatus !== undefined && verificationStatus !== null) {\n\t\tthrow validationError(\n\t\t\t\"create-bill payload.verificationStatus must be PENDING | PASS | FAIL | MANUAL_REVIEW.\",\n\t\t);\n\t}\n\treturn undefined;\n};\n\nconst hasQuotationReference = (references: ParsedQuotationReferences) =>\n\tBoolean(references.quotationId) ||\n\t(references.quotationIds?.length ?? 0) > 0 ||\n\t(references.quotationAllocations?.length ?? 0) > 0;\n\nconst assertCreateBillQuotationSourceRules = ({\n\tisClaimable,\n\tquotationExempt,\n\tquotationReferences,\n\trequireSupplierQuotation,\n}: {\n\tisClaimable: boolean;\n\tquotationExempt: boolean;\n\tquotationReferences: ParsedQuotationReferences;\n\trequireSupplierQuotation: boolean;\n}) => {\n\tif (quotationExempt && isClaimable) {\n\t\tthrow validationError(\n\t\t\t\"--quotation-exempt is only valid for supplier bills.\",\n\t\t);\n\t}\n\tconst hasReference = hasQuotationReference(quotationReferences);\n\tif (quotationExempt && hasReference) {\n\t\tthrow validationError(\n\t\t\t\"--quotation-exempt cannot be combined with payload quotation IDs.\",\n\t\t);\n\t}\n\tif (isClaimable && hasReference) {\n\t\tthrow validationError(\n\t\t\t\"Employee claims cannot include quotation source inputs.\",\n\t\t);\n\t}\n\tif (\n\t\trequireSupplierQuotation &&\n\t\t!quotationExempt &&\n\t\t!isClaimable &&\n\t\t!hasReference\n\t) {\n\t\tthrow validationError(\n\t\t\t\"create-bill supplier bills require payload.quotationAllocations, payload.quotationIds, or legacy payload.quotationId.\",\n\t\t);\n\t}\n};\n\nconst parseInvoiceNumber = (value: unknown): string => {\n\tif (value === undefined || value === null) return \"\";\n\treturn typeof value === \"string\" ? value : String(value);\n};\n\n/** Matches bill.create — invoiceDate may be ISO string; attachments default to []. */\nexport function parseCreateBillPayload(\n\traw: unknown,\n\tdraftOnlyFlag?: boolean,\n\tquotationExempt = false,\n\trequireSupplierQuotation = true,\n): RouterInputs[\"bill\"][\"create\"] {\n\tconst o = requireObject(raw, \"create-bill payload\");\n\tconst isClaimable = o.isClaimable;\n\tif (typeof isClaimable !== \"boolean\") {\n\t\tthrow validationError(\"create-bill payload.isClaimable must be boolean.\");\n\t}\n\tconst budgetItemIds = o.budgetItemIds;\n\tif (!Array.isArray(budgetItemIds) || budgetItemIds.length === 0) {\n\t\tthrow validationError(\n\t\t\t\"create-bill payload.budgetItemIds must be a non-empty string array.\",\n\t\t);\n\t}\n\tconst attachments = billAttachmentList(o.attachments);\n\tconst draftOnly = parseCreateBillDraftOnly(o, draftOnlyFlag);\n\tconst alreadyPaidRaw = parseCreateBillAlreadyPaid(o, draftOnly);\n\tconst paymentProofAttachments = billAttachmentList(\n\t\to.paymentProofAttachments,\n\t\t\"paymentProofAttachments\",\n\t);\n\tconst verificationResults = parseCreateBillVerificationResults(\n\t\to.verificationResults,\n\t);\n\tconst vs = parseCreateBillVerificationStatus(o.verificationStatus);\n\n\tconst amount = Number(o.amount);\n\tif (!Number.isFinite(amount) || amount < 0) {\n\t\tthrow validationError(\"create-bill payload.amount must be a number >= 0.\");\n\t}\n\tconst quotationReferences = parseQuotationReferences(o, \"create-bill\");\n\tconst parsedBudgetItemIds = budgetItemIds.map((id, i) =>\n\t\trequiredString(id, `create-bill payload.budgetItemIds[${i}]`),\n\t);\n\tconst lineAmounts = parseBillLineAmounts(o, \"create-bill\");\n\tvalidateExplicitBillAllocations({\n\t\tamount,\n\t\tbudgetItemIds: parsedBudgetItemIds,\n\t\tcommandName: \"create-bill\",\n\t\tlineAmounts,\n\t\tquotationAllocations: quotationReferences.quotationAllocations,\n\t});\n\tassertCreateBillQuotationSourceRules({\n\t\tisClaimable,\n\t\tquotationExempt,\n\t\tquotationReferences,\n\t\trequireSupplierQuotation,\n\t});\n\treturn {\n\t\tbudgetId: requiredString(o.budgetId, \"create-bill payload.budgetId\"),\n\t\tprojectId: requiredString(o.projectId, \"create-bill payload.projectId\"),\n\t\tsupplierId: requiredString(o.supplierId, \"create-bill payload.supplierId\"),\n\t\t...quotationReferences,\n\t\tamount,\n\t\tbudgetItemIds: parsedBudgetItemIds,\n\t\t...(lineAmounts ? { lineAmounts } : {}),\n\t\tcomment: optionalString(o.comment),\n\t\tisClaimable,\n\t\tattachments,\n\t\talreadyPaid: alreadyPaidRaw ?? undefined,\n\t\tdraftOnly,\n\t\tpaymentReference: optionalString(o.paymentReference),\n\t\tpaymentProofAttachments,\n\t\textractedSupplierName: optionalString(o.extractedSupplierName),\n\t\textractedAmount: optionalNumber(o.extractedAmount),\n\t\tinvoiceNumber: parseInvoiceNumber(o.invoiceNumber),\n\t\tinvoiceDate:\n\t\t\to.invoiceDate === undefined || o.invoiceDate === null\n\t\t\t\t? undefined\n\t\t\t\t: toDate(o.invoiceDate, \"invoiceDate\"),\n\t\tverificationStatus: vs,\n\t\tverificationResults,\n\t};\n}\n\ntype UpdateBillInput = RouterInputs[\"bill\"][\"update\"];\n\nconst UPDATE_BILL_KNOWN_FIELDS = new Set([\n\t\"id\",\n\t\"budgetId\",\n\t\"projectId\",\n\t\"supplierId\",\n\t\"quotationId\",\n\t\"quotationIds\",\n\t\"quotationAllocations\",\n\t\"overBudgetOverrideReason\",\n\t\"amount\",\n\t\"budgetItemIds\",\n\t\"lineAmounts\",\n\t\"comment\",\n\t\"isClaimable\",\n\t\"attachments\",\n\t\"alreadyPaid\",\n\t\"paymentReference\",\n\t\"paymentProofAttachments\",\n\t\"extractedSupplierName\",\n\t\"extractedAmount\",\n\t\"invoiceNumber\",\n\t\"invoiceDate\",\n\t\"verificationStatus\",\n\t\"verificationResults\",\n]);\n\nconst assignUpdateBillStrings = (\n\to: Record<string, unknown>,\n\tinput: UpdateBillInput,\n) => {\n\tfor (const key of [\n\t\t\"budgetId\",\n\t\t\"projectId\",\n\t\t\"supplierId\",\n\t\t\"comment\",\n\t\t\"paymentReference\",\n\t\t\"extractedSupplierName\",\n\t\t\"invoiceNumber\",\n\t\t\"overBudgetOverrideReason\",\n\t] as const) {\n\t\tif (o[key] === undefined) continue;\n\t\tif (typeof o[key] !== \"string\")\n\t\t\tthrow validationError(`update-bill payload.${key} must be a string.`);\n\t\tinput[key] = o[key];\n\t}\n};\n\nconst assignUpdateBillAmountsAndFlags = (\n\to: Record<string, unknown>,\n\tinput: UpdateBillInput,\n) => {\n\tfor (const key of [\"amount\", \"extractedAmount\"] as const) {\n\t\tif (o[key] === undefined) continue;\n\t\tconst amount = Number(o[key]);\n\t\tif (!Number.isFinite(amount) || amount < 0)\n\t\t\tthrow validationError(\n\t\t\t\t`update-bill payload.${key} must be a number >= 0.`,\n\t\t\t);\n\t\tinput[key] = amount;\n\t}\n\tfor (const key of [\"isClaimable\", \"alreadyPaid\"] as const) {\n\t\tif (o[key] === undefined) continue;\n\t\tif (typeof o[key] !== \"boolean\")\n\t\t\tthrow validationError(`update-bill payload.${key} must be boolean.`);\n\t\tinput[key] = o[key];\n\t}\n};\n\nconst assignUpdateBillAttachmentsAndItems = (\n\to: Record<string, unknown>,\n\tinput: UpdateBillInput,\n) => {\n\tfor (const key of [\"attachments\", \"paymentProofAttachments\"] as const) {\n\t\tconst attachments = o[key];\n\t\tif (attachments === undefined) continue;\n\t\tif (!Array.isArray(attachments))\n\t\t\tthrow validationError(`update-bill payload.${key} must be an array.`);\n\t\tinput[key] = attachments.map((value, index) =>\n\t\t\tbillAttachment(value, index, key),\n\t\t);\n\t}\n\tif (o.budgetItemIds !== undefined) {\n\t\tif (!Array.isArray(o.budgetItemIds) || !o.budgetItemIds.length)\n\t\t\tthrow validationError(\n\t\t\t\t\"update-bill payload.budgetItemIds must be a non-empty array.\",\n\t\t\t);\n\t\tinput.budgetItemIds = o.budgetItemIds.map((id, index) =>\n\t\t\trequiredString(id, `update-bill payload.budgetItemIds[${index}]`),\n\t\t);\n\t}\n};\n\nconst assignUpdateBillVerification = (\n\to: Record<string, unknown>,\n\tinput: UpdateBillInput,\n) => {\n\tif (o.verificationStatus !== undefined) {\n\t\tif (\n\t\t\t!Object.values(BillVerificationStatus).includes(\n\t\t\t\to.verificationStatus as BillVerificationStatus,\n\t\t\t)\n\t\t)\n\t\t\tthrow validationError(\"Invalid bill verification status.\");\n\t\tinput.verificationStatus = o.verificationStatus as BillVerificationStatus;\n\t}\n\tif (o.verificationResults !== undefined) {\n\t\tconst value = requireObject(o.verificationResults, \"verificationResults\");\n\t\tconst status = value.status;\n\t\tif (\n\t\t\tstatus !== BillVerificationStatus.PENDING &&\n\t\t\tstatus !== BillVerificationStatus.PASS &&\n\t\t\tstatus !== BillVerificationStatus.FAIL &&\n\t\t\tstatus !== BillVerificationStatus.MANUAL_REVIEW\n\t\t)\n\t\t\tthrow validationError(\"Invalid verificationResults.status.\");\n\t\tinput.verificationResults = {\n\t\t\tstatus,\n\t\t\textractedAmount:\n\t\t\t\tvalue.extractedAmount == null ? null : Number(value.extractedAmount),\n\t\t\tdifference: value.difference == null ? null : Number(value.difference),\n\t\t\tconfidence: value.confidence == null ? null : Number(value.confidence),\n\t\t\tfailureReason:\n\t\t\t\tvalue.failureReason == null ? null : String(value.failureReason),\n\t\t};\n\t}\n};\n\n/** Matches bill.update */\nexport function parseUpdateBillPayload(\n\traw: unknown,\n): RouterInputs[\"bill\"][\"update\"] {\n\tconst o = requireObject(raw, \"update-bill payload\");\n\tif (o.draftOnly !== undefined) {\n\t\tthrow validationError(\"draftOnly is only supported when creating a bill.\");\n\t}\n\tconst input: RouterInputs[\"bill\"][\"update\"] = {\n\t\tid: requiredString(o.id, \"update-bill payload.id\"),\n\t};\n\tfor (const key of Object.keys(o))\n\t\tif (!UPDATE_BILL_KNOWN_FIELDS.has(key))\n\t\t\tthrow validationError(`Unknown update-bill payload field: ${key}`);\n\tassignUpdateBillStrings(o, input);\n\tassignUpdateBillAmountsAndFlags(o, input);\n\tassignUpdateBillAttachmentsAndItems(o, input);\n\tObject.assign(input, parseQuotationReferences(o, \"update-bill\"));\n\tif (o.lineAmounts !== undefined)\n\t\tinput.lineAmounts = parseBillLineAmounts(o, \"update-bill\");\n\tif (o.invoiceDate !== undefined)\n\t\tinput.invoiceDate = toDate(o.invoiceDate, \"invoiceDate\");\n\tassignUpdateBillVerification(o, input);\n\tif (Object.keys(input).length === 1)\n\t\tthrow validationError(\"Supply at least one field to update.\");\n\treturn input;\n}\n\nconst quotationIdsFromReferences = (references: ParsedQuotationReferences) =>\n\treferences.quotationIds ??\n\t(references.quotationId ? [references.quotationId] : undefined);\n\nconst assertSelectionQuotationFlagsMatchPayload = (\n\tpayloadReferences: ParsedQuotationReferences,\n\tflagReferences: ParsedQuotationReferences,\n) => {\n\tconst payloadIds = quotationIdsFromReferences(payloadReferences);\n\tconst flagIds = quotationIdsFromReferences(flagReferences);\n\tif (payloadIds && flagIds && payloadIds.join(\"\\0\") !== flagIds.join(\"\\0\")) {\n\t\tthrow validationError(\n\t\t\t\"validate-bill-selection quotation flags conflict with the payload quotation IDs.\",\n\t\t);\n\t}\n};\n\nconst parseSelectionIsClaimable = (\n\tinput: Record<string, unknown>,\n\tpayloadReferences: ParsedQuotationReferences,\n\tflagReferences: ParsedQuotationReferences,\n): boolean | undefined => {\n\tconst isClaimable = input.isClaimable;\n\tif (isClaimable !== undefined && typeof isClaimable !== \"boolean\") {\n\t\tthrow validationError(\n\t\t\t\"validate-bill-selection payload.isClaimable must be boolean.\",\n\t\t);\n\t}\n\tif (\n\t\tisClaimable === true &&\n\t\t(payloadReferences.quotationId ||\n\t\t\t(payloadReferences.quotationIds?.length ?? 0) > 0 ||\n\t\t\t(payloadReferences.quotationAllocations?.length ?? 0) > 0 ||\n\t\t\t!!flagReferences.quotationId ||\n\t\t\t(flagReferences.quotationIds?.length ?? 0) > 0)\n\t) {\n\t\tthrow validationError(\n\t\t\t\"Employee claims cannot include quotation source inputs.\",\n\t\t);\n\t}\n\treturn isClaimable;\n};\n\nconst assertSelectionExplicitAllocations = ({\n\tamount,\n\tbudgetItemIds,\n\tlineAmounts,\n\tquotationAllocations,\n}: {\n\tamount: number | undefined;\n\tbudgetItemIds: string[];\n\tlineAmounts: ReturnType<typeof parseBillLineAmounts>;\n\tquotationAllocations: ParsedQuotationReferences[\"quotationAllocations\"];\n}) => {\n\tif (!lineAmounts && !quotationAllocations) return;\n\tif (\n\t\tamount === undefined ||\n\t\t!Number.isFinite(amount) ||\n\t\tbudgetItemIds.length === 0\n\t) {\n\t\tthrow validationError(\n\t\t\t\"validate-bill-selection explicit allocations require payload.amount and payload.budgetItemIds.\",\n\t\t);\n\t}\n\tvalidateExplicitBillAllocations({\n\t\tamount,\n\t\tbudgetItemIds,\n\t\tcommandName: \"validate-bill-selection\",\n\t\tlineAmounts,\n\t\tquotationAllocations,\n\t});\n};\n\n/** Server performs the authoritative bill-selection and quotation-coverage checks. */\nexport function parseValidateBillSelectionPayload(\n\traw: unknown,\n\tquotationFlags: ParsedQuotationReferences = {},\n): RouterInputs[\"bill\"][\"validateSelection\"] {\n\tconst input = requireObject(raw, \"validate-bill-selection payload\");\n\tconst payloadReferences = parseQuotationReferences(\n\t\tinput,\n\t\t\"validate-bill-selection\",\n\t);\n\tconst flagReferences = parseQuotationReferences(\n\t\t{ ...quotationFlags },\n\t\t\"validate-bill-selection flags\",\n\t);\n\tassertSelectionQuotationFlagsMatchPayload(payloadReferences, flagReferences);\n\tconst isClaimable = parseSelectionIsClaimable(\n\t\tinput,\n\t\tpayloadReferences,\n\t\tflagReferences,\n\t);\n\tconst lineAmounts = parseBillLineAmounts(input, \"validate-bill-selection\");\n\tconst budgetItemIds = Array.isArray(input.budgetItemIds)\n\t\t? input.budgetItemIds.map((id, index) =>\n\t\t\t\trequiredString(\n\t\t\t\t\tid,\n\t\t\t\t\t`validate-bill-selection payload.budgetItemIds[${index}]`,\n\t\t\t\t),\n\t\t\t)\n\t\t: [];\n\tconst amount = optionalNumber(input.amount);\n\tassertSelectionExplicitAllocations({\n\t\tamount,\n\t\tbudgetItemIds,\n\t\tlineAmounts,\n\t\tquotationAllocations: payloadReferences.quotationAllocations,\n\t});\n\treturn {\n\t\t...input,\n\t\t...(amount !== undefined ? { amount } : {}),\n\t\t...(isClaimable !== undefined ? { isClaimable } : {}),\n\t\t...(lineAmounts ? { lineAmounts } : {}),\n\t\t...payloadReferences,\n\t\t...flagReferences,\n\t} as RouterInputs[\"bill\"][\"validateSelection\"];\n}\n\nexport function parseLinkBillQuotationsPayload(\n\tbillId: string,\n\traw: unknown,\n): RouterInputs[\"bill\"][\"linkQuotations\"] {\n\tconst input = requireObject(raw, \"link-bill-quotations payload\");\n\tconst references = parseQuotationReferences(input, \"link-bill-quotations\");\n\tif (references.quotationId) {\n\t\tthrow validationError(\n\t\t\t\"link-bill-quotations payload uses quotationIds or quotationAllocations; legacy quotationId is not supported.\",\n\t\t);\n\t}\n\tif (\n\t\t(references.quotationIds?.length ?? 0) === 0 &&\n\t\t(references.quotationAllocations?.length ?? 0) === 0\n\t) {\n\t\tthrow validationError(\n\t\t\t\"link-bill-quotations payload requires quotationIds or quotationAllocations.\",\n\t\t);\n\t}\n\treturn {\n\t\tbillId: requiredString(billId, \"billId\"),\n\t\t...(references.quotationIds\n\t\t\t? { quotationIds: references.quotationIds }\n\t\t\t: {}),\n\t\t...(references.quotationAllocations\n\t\t\t? { quotationAllocations: references.quotationAllocations }\n\t\t\t: {}),\n\t};\n}\n\n/** Matches bill.updatePaymentEvidence for already-paid supplier bills. */\nexport function parseUpdateBillPaymentEvidencePayload(\n\traw: unknown,\n): RouterInputs[\"bill\"][\"updatePaymentEvidence\"] {\n\trequireObject(raw, \"update-bill-payment-evidence payload\");\n\treturn raw as RouterInputs[\"bill\"][\"updatePaymentEvidence\"];\n}\n\nconst isQuotationCurrency = (value: unknown): value is number =>\n\ttypeof value === \"number\" &&\n\tNumber.isFinite(value) &&\n\tvalue >= 0 &&\n\tvalue <= 99_999_999.99 &&\n\tMath.abs(value * 100 - Math.round(value * 100)) < 1e-8;\n\nconst validateDocumentOnlyQuotation = (\n\tinput: Record<string, unknown>,\n\tids: readonly unknown[],\n\tcommand: string,\n): void => {\n\tif (input.amountWithoutGst !== 0 || input.gstAmount !== 0) {\n\t\tthrow new CliRuntimeError(\n\t\t\t\"VALIDATION\",\n\t\t\t`${command} with payload.documentOnly: true requires payload.amountWithoutGst: 0 and payload.gstAmount: 0 (a document-only quotation carries no amounts).`,\n\t\t);\n\t}\n\tif (input.lineAmounts === undefined) return;\n\tif (\n\t\t!Array.isArray(input.lineAmounts) ||\n\t\tinput.lineAmounts.length !== ids.length\n\t) {\n\t\tthrow new CliRuntimeError(\n\t\t\t\"VALIDATION\",\n\t\t\t`${command} with payload.documentOnly: true accepts payload.lineAmounts only as one entry per payload.budgetItemIds ID, each with amount: 0; omit payload.lineAmounts to let the API fill zeros.`,\n\t\t);\n\t}\n\tconst seenIds = new Set<string>();\n\tfor (const rawLine of input.lineAmounts) {\n\t\tconst line = requireObject(rawLine, `${command} payload.lineAmounts entry`);\n\t\tif (\n\t\t\ttypeof line.budgetItemId !== \"string\" ||\n\t\t\t!ids.includes(line.budgetItemId) ||\n\t\t\tseenIds.has(line.budgetItemId) ||\n\t\t\tline.amount !== 0\n\t\t) {\n\t\t\tthrow new CliRuntimeError(\n\t\t\t\t\"VALIDATION\",\n\t\t\t\t`${command} with payload.documentOnly: true requires every payload.lineAmounts amount to be 0 for a distinct payload.budgetItemIds ID.`,\n\t\t\t);\n\t\t}\n\t\tseenIds.add(line.budgetItemId);\n\t}\n};\n\nconst validatePricedQuotation = (\n\tinput: Record<string, unknown>,\n\tids: readonly unknown[],\n\tcommand: string,\n): void => {\n\tif (\n\t\t!isQuotationCurrency(input.amountWithoutGst) ||\n\t\tinput.amountWithoutGst === 0 ||\n\t\t!isQuotationCurrency(input.gstAmount)\n\t) {\n\t\tthrow new CliRuntimeError(\n\t\t\t\"VALIDATION\",\n\t\t\t`${command} requires a positive payload.amountWithoutGst and a non-negative payload.gstAmount, in currency units with at most two decimal places. Use gstAmount: 0 for no GST. For a $0 supplier document with no amounts, set payload.documentOnly: true with amountWithoutGst: 0 and gstAmount: 0. update-quotation is a full replace: send payload.documentOnly: true again when updating a document-only quotation, or it is treated as a priced quotation.`,\n\t\t);\n\t}\n\tconst guidance = `${command} requires payload.lineAmounts as [{\"budgetItemId\":\"<first-id>\",\"amount\":750},{\"budgetItemId\":\"<second-id>\",\"amount\":450}] for multiple budget items. Include each payload.budgetItemIds entry exactly once, with non-negative amounts before GST summing to payload.amountWithoutGst. For a 1200 quotation with no GST, use line amounts 750 and 450, amountWithoutGst: 1200, gstAmount: 0.`;\n\tif (input.lineAmounts === undefined && ids.length === 1) return;\n\tif (\n\t\t!Array.isArray(input.lineAmounts) ||\n\t\tinput.lineAmounts.length !== ids.length\n\t) {\n\t\tthrow new CliRuntimeError(\"VALIDATION\", guidance);\n\t}\n\tconst seen = new Set<string>();\n\tlet totalCents = 0;\n\tfor (const rawLine of input.lineAmounts) {\n\t\tconst line = requireObject(rawLine, `${command} payload.lineAmounts entry`);\n\t\tif (\n\t\t\ttypeof line.budgetItemId !== \"string\" ||\n\t\t\t!ids.includes(line.budgetItemId) ||\n\t\t\tseen.has(line.budgetItemId) ||\n\t\t\t!isQuotationCurrency(line.amount)\n\t\t) {\n\t\t\tthrow new CliRuntimeError(\"VALIDATION\", guidance);\n\t\t}\n\t\tseen.add(line.budgetItemId);\n\t\ttotalCents += Math.round(line.amount * 100);\n\t}\n\tif (totalCents !== Math.round(input.amountWithoutGst * 100)) {\n\t\tthrow new CliRuntimeError(\"VALIDATION\", guidance);\n\t}\n};\n\nconst validateQuotationAllocations = (raw: unknown, command: string): void => {\n\tconst input = requireObject(raw, `${command} payload`);\n\tconst ids = input.budgetItemIds;\n\tif (\n\t\t!Array.isArray(ids) ||\n\t\tids.length === 0 ||\n\t\tids.some((id) => typeof id !== \"string\" || id.length === 0) ||\n\t\tnew Set(ids).size !== ids.length\n\t) {\n\t\tthrow new CliRuntimeError(\n\t\t\t\"VALIDATION\",\n\t\t\t`${command} payload.budgetItemIds must contain each selected budget-item ID exactly once.`,\n\t\t);\n\t}\n\tif (\n\t\tinput.documentOnly !== undefined &&\n\t\ttypeof input.documentOnly !== \"boolean\"\n\t) {\n\t\tthrow new CliRuntimeError(\n\t\t\t\"VALIDATION\",\n\t\t\t`${command} payload.documentOnly must be a boolean (true or false).`,\n\t\t);\n\t}\n\tif (input.documentOnly === true) {\n\t\tvalidateDocumentOnlyQuotation(input, ids, command);\n\t\treturn;\n\t}\n\tvalidatePricedQuotation(input, ids, command);\n};\n\n/** Validate stated allocations locally; the server validates records and attachment. */\nexport function parseCreateQuotationPayload(\n\traw: unknown,\n): RouterInputs[\"quotation\"][\"createDraft\"] {\n\tvalidateQuotationAllocations(raw, \"create-quotation\");\n\treturn raw as RouterInputs[\"quotation\"][\"createDraft\"];\n}\n\nexport function parseUpdateQuotationPayload(\n\traw: unknown,\n): RouterInputs[\"quotation\"][\"updateDraftOrRejected\"] {\n\tvalidateQuotationAllocations(raw, \"update-quotation\");\n\treturn raw as RouterInputs[\"quotation\"][\"updateDraftOrRejected\"];\n}\n\nexport const parseCreateCustomerInvoicePayload = (raw: unknown) => {\n\tconst input = requireObject(raw, \"create-customer-invoice payload\");\n\tif (!Array.isArray(input.splits) || input.splits.length !== 1) {\n\t\tthrow validationError(\n\t\t\t\"create-customer-invoice payload.splits must contain exactly one invoice.\",\n\t\t);\n\t}\n\tif (\n\t\tinput.isCustomPercentage !== undefined &&\n\t\ttypeof input.isCustomPercentage !== \"boolean\"\n\t) {\n\t\tthrow validationError(\n\t\t\t\"create-customer-invoice payload.isCustomPercentage must be a boolean.\",\n\t\t);\n\t}\n\n\tconst details =\n\t\tinput.details === undefined\n\t\t\t? undefined\n\t\t\t: requireObject(input.details, \"invoice details\");\n\tif (details && typeof details.billingAddress !== \"string\")\n\t\tthrow validationError(\"invoice details.billingAddress must be a string.\");\n\treturn {\n\t\t...(input.requestId === undefined\n\t\t\t? {}\n\t\t\t: { requestId: requiredString(input.requestId, \"requestId\") }),\n\t\t...(input.invoiceDate === undefined\n\t\t\t? {}\n\t\t\t: { invoiceDate: toDate(input.invoiceDate, \"invoiceDate\") }),\n\t\tisCustomPercentage: input.isCustomPercentage ?? true,\n\t\t...(details\n\t\t\t? {\n\t\t\t\t\tdetails: {\n\t\t\t\t\t\tbillingAddress: String(details.billingAddress),\n\t\t\t\t\t\tcustomerMemo: requiredString(details.customerMemo, \"customerMemo\"),\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t: {}),\n\t\tbudgetId: requiredString(\n\t\t\tinput.budgetId,\n\t\t\t\"create-customer-invoice payload.budgetId\",\n\t\t),\n\t\tsplits: input.splits.map((rawSplit, index) => {\n\t\t\tconst split = requireObject(\n\t\t\t\trawSplit,\n\t\t\t\t`create-customer-invoice payload.splits[${index}]`,\n\t\t\t);\n\t\t\tconst percentage = Number(split.percentage);\n\t\t\tif (\n\t\t\t\t!Number.isFinite(percentage) ||\n\t\t\t\tpercentage <= 0 ||\n\t\t\t\tpercentage > 100 ||\n\t\t\t\tMath.round(percentage * 100) !== percentage * 100\n\t\t\t) {\n\t\t\t\tthrow validationError(\n\t\t\t\t\t`create-customer-invoice payload.splits[${index}].percentage must be between 0.01 and 100 with at most two decimal places.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tdueDate: toDate(\n\t\t\t\t\tsplit.dueDate,\n\t\t\t\t\t`create-customer-invoice payload.splits[${index}].dueDate`,\n\t\t\t\t),\n\t\t\t\tlabel: requiredString(\n\t\t\t\t\tsplit.label,\n\t\t\t\t\t`create-customer-invoice payload.splits[${index}].label`,\n\t\t\t\t),\n\t\t\t\tpercentage,\n\t\t\t};\n\t\t}),\n\t};\n};\n\n/** Matches project.updateProject — dateRange.from/to may be ISO strings. */\nexport function parseUpdateProjectPayload(\n\traw: unknown,\n): RouterInputs[\"project\"][\"updateProject\"] {\n\tconst o = requireObject(raw, \"update-project payload\");\n\tconst dr = o.dateRange;\n\tif (dr === null || typeof dr !== \"object\" || Array.isArray(dr)) {\n\t\tthrow validationError(\n\t\t\t\"update-project payload.dateRange must be an object.\",\n\t\t);\n\t}\n\tconst range = dr as Record<string, unknown>;\n\tconst notification = o.requestQboAccountantNotification;\n\tlet requestQboAccountantNotification: boolean | undefined;\n\tif (typeof notification === \"boolean\") {\n\t\trequestQboAccountantNotification = notification;\n\t} else if (notification !== undefined && notification !== null) {\n\t\tthrow validationError(\n\t\t\t\"update-project payload.requestQboAccountantNotification must be a boolean when set.\",\n\t\t);\n\t}\n\tconst estimateInvalidation = o.confirmEstimateInvalidation;\n\tlet confirmEstimateInvalidation: boolean | undefined;\n\tif (typeof estimateInvalidation === \"boolean\") {\n\t\tconfirmEstimateInvalidation = estimateInvalidation;\n\t} else if (\n\t\testimateInvalidation !== undefined &&\n\t\testimateInvalidation !== null\n\t) {\n\t\tthrow validationError(\n\t\t\t\"update-project payload.confirmEstimateInvalidation must be a boolean when set.\",\n\t\t);\n\t}\n\n\tconst slackChannelId = optionalString(o.slackChannelId);\n\tconst slackChannelUrl = optionalString(o.slackChannelUrl);\n\tconst slackChannelName = optionalString(o.slackChannelName);\n\tconst slackPatch =\n\t\tslackChannelId !== undefined &&\n\t\tslackChannelUrl !== undefined &&\n\t\tslackChannelName !== undefined\n\t\t\t? {\n\t\t\t\t\tslackChannelId,\n\t\t\t\t\tslackChannelUrl,\n\t\t\t\t\tslackChannelName,\n\t\t\t\t}\n\t\t\t: {};\n\n\treturn {\n\t\tid: requiredString(o.id, \"update-project payload.id\"),\n\t\tname: parseQuickBooksName(o.name),\n\t\tdescription: optionalString(o.description),\n\t\tcompanyId: requiredString(o.companyId, \"update-project payload.companyId\"),\n\t\tcontactPersonId: requiredString(\n\t\t\to.contactPersonId,\n\t\t\t\"update-project payload.contactPersonId\",\n\t\t),\n\t\tasanaTaskId: requiredString(\n\t\t\to.asanaTaskId,\n\t\t\t\"update-project payload.asanaTaskId\",\n\t\t),\n\t\tinsideSalesId: requiredString(\n\t\t\to.insideSalesId,\n\t\t\t\"update-project payload.insideSalesId\",\n\t\t),\n\t\tbusinessDevelopmentId: requiredString(\n\t\t\to.businessDevelopmentId,\n\t\t\t\"update-project payload.businessDevelopmentId\",\n\t\t),\n\t\tprojectManagerId: optionalString(o.projectManagerId),\n\t\tvenue: requiredString(o.venue, \"update-project payload.venue\"),\n\t\tpax: optionalString(o.pax),\n\t\tdateRange: {\n\t\t\tfrom: toDate(range.from, \"dateRange.from\"),\n\t\t\tto:\n\t\t\t\trange.to === undefined || range.to === null\n\t\t\t\t\t? undefined\n\t\t\t\t\t: toDate(range.to, \"dateRange.to\"),\n\t\t},\n\t\t...slackPatch,\n\t\t...(requestQboAccountantNotification !== undefined && {\n\t\t\trequestQboAccountantNotification,\n\t\t}),\n\t\t...(confirmEstimateInvalidation !== undefined && {\n\t\t\tconfirmEstimateInvalidation,\n\t\t}),\n\t};\n}\n\nexport const parseQuickBooksName = (value: unknown): string => {\n\tconst result = quickBooksNameSchema.safeParse(value);\n\tif (!result.success) {\n\t\tthrow validationError(\n\t\t\tresult.error.issues[0]?.message ?? \"Invalid QuickBooks name\",\n\t\t);\n\t}\n\treturn result.data;\n};\n\n/** Other supplier fields remain authoritative on the server. */\nexport function parseSupplierCreatePayload(\n\traw: unknown,\n): RouterInputs[\"supplier\"][\"createSupplier\"] {\n\tconst input = requireObject(raw, \"create-supplier payload\");\n\treturn {\n\t\t...input,\n\t\tname: parseQuickBooksName(input.name),\n\t} as RouterInputs[\"supplier\"][\"createSupplier\"];\n}\n\nexport function parseSupplierUpdatePayload(\n\traw: unknown,\n): RouterInputs[\"supplier\"][\"updateSupplier\"] {\n\tconst input = requireObject(raw, \"update-supplier payload\");\n\treturn {\n\t\t...input,\n\t\tname: parseQuickBooksName(input.name),\n\t} as RouterInputs[\"supplier\"][\"updateSupplier\"];\n}\n\nconst normalizeItemPayload = (input: Record<string, unknown>) => {\n\tconst normalized: Record<string, unknown> = {\n\t\t...input,\n\t\tname: parseQuickBooksName(input.name),\n\t\t...(typeof input.cost === \"number\" && Number.isFinite(input.cost)\n\t\t\t? { cost: String(input.cost) }\n\t\t\t: {}),\n\t};\n\treturn normalizePlainTextRichTextField({\n\t\tinput: normalized,\n\t\ttextField: \"description\",\n\t\trichTextField: \"descriptionRichText\",\n\t});\n};\n\nexport function parseItemCreatePayload(\n\traw: unknown,\n): RouterInputs[\"item\"][\"createItem\"] {\n\treturn normalizeItemPayload(\n\t\trequireObject(raw, \"create-item payload\"),\n\t) as RouterInputs[\"item\"][\"createItem\"];\n}\n\nexport function parseItemUpdatePayload(\n\traw: unknown,\n): RouterInputs[\"item\"][\"updateItem\"] {\n\treturn normalizeItemPayload(\n\t\trequireObject(raw, \"update-item payload\"),\n\t) as RouterInputs[\"item\"][\"updateItem\"];\n}\n\nexport function parseContactCreatePayload(\n\traw: unknown,\n): RouterInputs[\"contactPerson\"][\"createContactPerson\"] {\n\trequireObject(raw, \"create-contact-person payload\");\n\treturn raw as RouterInputs[\"contactPerson\"][\"createContactPerson\"];\n}\n\nexport function parseContactUpdatePayload(\n\traw: unknown,\n): RouterInputs[\"contactPerson\"][\"updateContactPerson\"] {\n\trequireObject(raw, \"update-contact-person payload\");\n\treturn raw as RouterInputs[\"contactPerson\"][\"updateContactPerson\"];\n}\n\nexport function parseCompanyUpdatePayload(\n\traw: unknown,\n): RouterInputs[\"company\"][\"updateCompany\"] {\n\tconst input = requireObject(raw, \"update-company payload\");\n\tconst billingEmails = parseCompanyBillingEmails(input.billingEmails);\n\tif (\n\t\tinput.confirmDistinct !== undefined &&\n\t\ttypeof input.confirmDistinct !== \"boolean\"\n\t) {\n\t\tthrow validationError(\"confirmDistinct must be a boolean.\");\n\t}\n\treturn {\n\t\tid: requiredString(input.id, \"id\"),\n\t\tname: parseQuickBooksName(input.name),\n\t\twebsite: requiredString(input.website, \"website\"),\n\t\t...(input.confirmDistinct === undefined\n\t\t\t? {}\n\t\t\t: { confirmDistinct: input.confirmDistinct }),\n\t\t...(billingEmails === undefined ? {} : { billingEmails }),\n\t};\n}\n\n/** Shape checks only; the shared API validates and normalizes addresses. */\nexport const parseCompanyBillingEmails = (\n\traw: unknown,\n): string[] | undefined => {\n\tif (raw === undefined) return undefined;\n\tif (!Array.isArray(raw) || raw.length > 50) {\n\t\tthrow validationError(\n\t\t\t\"billingEmails must be a JSON array of up to 50 email strings.\",\n\t\t);\n\t}\n\treturn raw.map((email: unknown) => {\n\t\tif (typeof email !== \"string\") {\n\t\t\tthrow validationError(\"billingEmails must contain only email strings.\");\n\t\t}\n\t\treturn email;\n\t});\n};\n", "import { CliRuntimeError } from \"@go-labs-sg/bb/runtime/error\";\nimport type {\n\tCliCommandEffect,\n\tCliConfirmationRequest,\n\tCliConfirmationResult,\n\tCliEffectPermissions,\n\tCliRuntime,\n} from \"@go-labs-sg/bb/runtime/types\";\n\nconst effectLabels: Readonly<Record<CliCommandEffect, string>> = {\n\t\"state-change\": \"changes Budget Builder state\",\n\temail: \"sends email\",\n\t\"external-write\": \"writes to an external system\",\n\tdelete: \"deletes data\",\n\t\"financial-write\": \"creates or changes financial records\",\n};\n\nconst isEffectAllowed = (\n\teffect: CliCommandEffect,\n\tpermissions: CliEffectPermissions,\n): boolean => {\n\tswitch (effect) {\n\t\tcase \"state-change\":\n\t\t\treturn permissions.allowStateChange === true;\n\t\tcase \"email\":\n\t\t\treturn permissions.allowEmail === true;\n\t\tcase \"external-write\":\n\t\t\treturn permissions.allowExternalWrite === true;\n\t\tcase \"delete\":\n\t\t\treturn permissions.allowDelete === true;\n\t\tcase \"financial-write\":\n\t\t\treturn permissions.allowFinancialWrite === true;\n\t}\n};\n\nconst uniqueEffects = (\n\teffects: readonly CliCommandEffect[],\n): CliCommandEffect[] => [...new Set(effects)];\n\nexport const getRequiredEffectPermissions = (\n\teffects: readonly CliCommandEffect[],\n\tpermissions: CliEffectPermissions,\n): CliCommandEffect[] =>\n\tuniqueEffects(effects).filter(\n\t\t(effect) => !isEffectAllowed(effect, permissions),\n\t);\n\nexport const formatConfirmationPreview = (\n\trequest: Pick<\n\t\tCliConfirmationRequest,\n\t\t\"action\" | \"target\" | \"effects\" | \"details\"\n\t>,\n): string =>\n\t[\n\t\t\"Budget Builder workflow preview\",\n\t\t`Action: ${request.action}`,\n\t\t`Target: ${request.target?.trim() || \"not specified\"}`,\n\t\t`Effects: ${\n\t\t\tuniqueEffects(request.effects)\n\t\t\t\t.map((effect) => effectLabels[effect])\n\t\t\t\t.join(\"; \") || \"none\"\n\t\t}`,\n\t\t...(request.details === undefined ? [] : [`Details: ${request.details}`]),\n\t].join(\"\\n\");\n\nexport const confirmSensitiveCommand = async (\n\truntime: CliRuntime,\n\trequest: CliConfirmationRequest,\n): Promise<CliConfirmationResult> => {\n\tconst requiredPermissions = getRequiredEffectPermissions(\n\t\trequest.effects,\n\t\trequest.permissions,\n\t);\n\tif (request.effects.length === 0) {\n\t\treturn { confirmed: true, requiredPermissions };\n\t}\n\n\tconst target = request.target?.trim();\n\tif (!runtime.isTTY) {\n\t\tif (target === undefined) {\n\t\t\tthrow new CliRuntimeError(\n\t\t\t\t\"CONFIRMATION_REQUIRED\",\n\t\t\t\t\"Non-interactive sensitive commands require an explicit target.\",\n\t\t\t\t{\n\t\t\t\t\tdetails: {\n\t\t\t\t\t\taction: request.action,\n\t\t\t\t\t\teffects: requiredPermissions,\n\t\t\t\t\t\tmissingFlags: requiredPermissions.map(\n\t\t\t\t\t\t\t(effect) => `--allow-${effect}`,\n\t\t\t\t\t\t),\n\t\t\t\t\t\ttarget: \"required\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t);\n\t\t}\n\t\tif (requiredPermissions.length === 0) {\n\t\t\treturn { confirmed: true, requiredPermissions };\n\t\t}\n\t\tconst missing = requiredPermissions.map((effect) => `--allow-${effect}`);\n\t\tthrow new CliRuntimeError(\n\t\t\t\"CONFIRMATION_REQUIRED\",\n\t\t\t\"Non-interactive sensitive commands require an explicit target and all applicable allow flags.\",\n\t\t\t{\n\t\t\t\tdetails: {\n\t\t\t\t\taction: request.action,\n\t\t\t\t\teffects: requiredPermissions,\n\t\t\t\t\tmissingFlags: missing,\n\t\t\t\t},\n\t\t\t},\n\t\t);\n\t}\n\tif (requiredPermissions.length === 0) {\n\t\treturn { confirmed: true, requiredPermissions };\n\t}\n\n\tconst preview = formatConfirmationPreview(request);\n\truntime.stderr.write(`${preview}\\n`);\n\tif (runtime.prompt === undefined) {\n\t\tthrow new CliRuntimeError(\n\t\t\t\"CONFIRMATION_REQUIRED\",\n\t\t\t\"This command needs an interactive confirmation prompt.\",\n\t\t);\n\t}\n\n\tconst answer = await runtime.prompt(\"Type CONFIRM to continue: \");\n\tif (answer !== \"CONFIRM\") {\n\t\tthrow new CliRuntimeError(\"ABORTED\", \"Command aborted by user.\");\n\t}\n\n\treturn { confirmed: true, preview, requiredPermissions };\n};\n", "import type { CliDiagnostic, CliJsonValue } from \"@go-labs-sg/bb/runtime/types\";\n\nconst sensitiveKeys = new Set([\n\t\"apikey\",\n\t\"authorization\",\n\t\"bb_api_key\",\n\t\"password\",\n\t\"paymentproof\",\n\t\"paymentproofattachments\",\n\t\"paymentproofpath\",\n\t\"paymentreference\",\n\t\"payload\",\n\t\"proof\",\n\t\"receipt\",\n\t\"secret\",\n\t\"token\",\n]);\n\nconst isPresignedUrl = (value: unknown): value is string =>\n\ttypeof value === \"string\" &&\n\t(/[?&]X-Amz-(?:Algorithm|Credential|Signature)=/i.test(value) ||\n\t\t/[?&]X-Goog-(?:Algorithm|Credential|Signature)=/i.test(value));\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n\ttypeof value === \"object\" && value !== null && !Array.isArray(value);\n\nexport const sanitizeCliValue = (\n\tvalue: unknown,\n\tseen = new WeakSet<object>(),\n): CliJsonValue => {\n\tif (\n\t\tvalue === null ||\n\t\ttypeof value === \"string\" ||\n\t\ttypeof value === \"boolean\" ||\n\t\ttypeof value === \"number\"\n\t) {\n\t\treturn isPresignedUrl(value) ? \"[redacted]\" : value;\n\t}\n\tif (typeof value === \"bigint\") return value.toString();\n\tif (value instanceof Date) return value.toISOString();\n\tif (typeof value !== \"object\" || value === null) return String(value);\n\tif (seen.has(value)) return \"[circular]\";\n\tseen.add(value);\n\n\tif (Array.isArray(value)) {\n\t\treturn value.map((item) => sanitizeCliValue(item, seen));\n\t}\n\tif (!isRecord(value)) return String(value);\n\n\treturn Object.fromEntries(\n\t\tObject.entries(value).map(([key, nestedValue]) => [\n\t\t\tkey,\n\t\t\tsensitiveKeys.has(key.toLowerCase()) ||\n\t\t\tkey.toLowerCase().includes(\"secret\") ||\n\t\t\tkey.toLowerCase().includes(\"password\")\n\t\t\t\t? \"[redacted]\"\n\t\t\t\t: sanitizeCliValue(nestedValue, seen),\n\t\t]),\n\t);\n};\n\nexport const sanitizeCliDiagnostic = (\n\tdiagnostic: CliDiagnostic,\n): CliDiagnostic => sanitizeCliValue(diagnostic) as CliDiagnostic;\n", "import {\n\texitCodeForCliError,\n\tnormalizeCliError,\n} from \"@go-labs-sg/bb/runtime/error\";\nimport { sanitizeCliDiagnostic } from \"@go-labs-sg/bb/runtime/sanitize\";\nimport type {\n\tCliDiagnostic,\n\tCliErrorEnvelope,\n\tCliExitCode,\n\tCliInvocation,\n\tCliJsonValue,\n\tCliRuntime,\n\tCliSuccessEnvelope,\n} from \"@go-labs-sg/bb/runtime/types\";\n\nconst serialize = (value: unknown): string =>\n\t`${JSON.stringify(value, null, 2)}\\n`;\n\nexport const createSuccessEnvelope = <TData extends CliJsonValue>(\n\tdata: TData,\n\tinvocation: CliInvocation,\n): CliSuccessEnvelope<TData> => ({\n\tok: true,\n\tdata,\n\tmeta: {\n\t\tcommand: invocation.command,\n\t\tcliVersion: invocation.cliVersion,\n\t\tapiBaseUrl: invocation.apiBaseUrl,\n\t},\n});\n\nexport const emitCliSuccess = <TData extends CliJsonValue>(\n\truntime: CliRuntime,\n\tinvocation: CliInvocation,\n\tdata: TData,\n): CliExitCode => {\n\truntime.stdout.write(\n\t\tserialize(\n\t\t\tinvocation.legacy ? data : createSuccessEnvelope(data, invocation),\n\t\t),\n\t);\n\treturn 0;\n};\n\nexport const emitCliError = (\n\truntime: CliRuntime,\n\tinvocation: Pick<CliInvocation, \"command\" | \"legacy\">,\n\terror: unknown,\n): CliExitCode => {\n\tconst normalized = normalizeCliError(error);\n\tif (invocation.legacy) {\n\t\truntime.stderr.write(serialize({ error: normalized.message }));\n\t} else {\n\t\tconst envelope: CliErrorEnvelope = {\n\t\t\tok: false,\n\t\t\terror: normalized,\n\t\t\tmeta: { command: invocation.command },\n\t\t};\n\t\truntime.stderr.write(serialize(envelope));\n\t}\n\treturn exitCodeForCliError(normalized);\n};\n\nexport const emitCliDiagnostic = (\n\truntime: CliRuntime,\n\tinvocation: Pick<CliInvocation, \"debug\" | \"quiet\">,\n\tdiagnostic: CliDiagnostic,\n): void => {\n\tif (invocation.quiet || !invocation.debug) return;\n\truntime.stderr.write(serialize(sanitizeCliDiagnostic(diagnostic)));\n};\n", "import { createInterface } from \"node:readline/promises\";\nimport type { CliRuntime } from \"@go-labs-sg/bb/runtime/types\";\n\nexport const createProcessRuntime = (): CliRuntime => ({\n\tstdout: {\n\t\twrite: (value) => {\n\t\t\tprocess.stdout.write(value);\n\t\t},\n\t},\n\tstderr: {\n\t\twrite: (value) => {\n\t\t\tprocess.stderr.write(value);\n\t\t},\n\t},\n\tisTTY: Boolean(process.stdin.isTTY && process.stderr.isTTY),\n\tenv: process.env,\n\tprompt: async (message) => {\n\t\tconst prompt = createInterface({\n\t\t\tinput: process.stdin,\n\t\t\toutput: process.stderr,\n\t\t});\n\t\ttry {\n\t\t\treturn await prompt.question(message);\n\t\t} finally {\n\t\t\tprompt.close();\n\t\t}\n\t},\n\tnow: () => new Date(),\n});\n", "import { confirmSensitiveCommand } from \"@go-labs-sg/bb/runtime/confirmation\";\nimport { emitCliError, emitCliSuccess } from \"@go-labs-sg/bb/runtime/output\";\nimport type {\n\tCliCommandEffect,\n\tCliEffectPermissions,\n\tCliExitCode,\n\tCliInvocation,\n\tCliJsonValue,\n\tCliRuntime,\n} from \"@go-labs-sg/bb/runtime/types\";\n\ninterface CliSessionInput {\n\truntime: CliRuntime;\n\tinvocation: CliInvocation;\n\teffects: readonly CliCommandEffect[];\n\tpermissions: CliEffectPermissions;\n}\n\ninterface CliSession extends CliSessionInput {\n\tconfirmedEffects: Set<CliCommandEffect>;\n}\n\nlet activeSession: CliSession | undefined;\n\nexport const setActiveCliSession = (session: CliSessionInput): void => {\n\tactiveSession = {\n\t\t...session,\n\t\tconfirmedEffects: new Set(),\n\t};\n};\n\nexport const clearActiveCliSession = (): void => {\n\tactiveSession = undefined;\n};\n\nexport const getActiveCliSession = (): CliSession | undefined => activeSession;\n\nconst requireSession = (): CliSession => {\n\tif (activeSession === undefined) {\n\t\tthrow new Error(\"Budget Builder CLI runtime session is not configured.\");\n\t}\n\treturn activeSession;\n};\n\nconst toJsonValue = (value: unknown): CliJsonValue => {\n\tconst serialized = JSON.stringify(value, (_key, nestedValue: unknown) =>\n\t\ttypeof nestedValue === \"bigint\" ? nestedValue.toString() : nestedValue,\n\t);\n\tif (serialized === undefined) return null;\n\treturn JSON.parse(serialized) as CliJsonValue;\n};\n\nexport const emitCommandResult = (data: unknown): CliExitCode => {\n\tconst session = requireSession();\n\treturn emitCliSuccess(session.runtime, session.invocation, toJsonValue(data));\n};\n\nexport const emitCommandError = (error: unknown): CliExitCode => {\n\tconst session = requireSession();\n\treturn emitCliError(session.runtime, session.invocation, error);\n};\n\nexport const confirmCurrentCommand = async (input: {\n\taction: string;\n\ttarget?: string;\n\tdetails?: string;\n\teffects?: readonly CliCommandEffect[];\n}): Promise<void> => {\n\tconst session = requireSession();\n\tconst effects = input.effects ?? session.effects;\n\tconst unconfirmedEffects = effects.filter(\n\t\t(effect) => !session.confirmedEffects.has(effect),\n\t);\n\tif (unconfirmedEffects.length === 0) return;\n\n\tawait confirmSensitiveCommand(session.runtime, {\n\t\taction: input.action,\n\t\ttarget: input.target,\n\t\tdetails: input.details,\n\t\teffects: unconfirmedEffects,\n\t\tpermissions: session.permissions,\n\t});\n\tfor (const effect of unconfirmedEffects) {\n\t\tsession.confirmedEffects.add(effect);\n\t}\n};\n", "/**\n * Stores one `--key=value`, `--key value` or `--key` flag. Resolves true when\n * the next argument was consumed as the flag's value.\n */\nfunction parseLongFlag(\n\targ: string,\n\tnext: string | undefined,\n\tflags: Record<string, string | true>,\n): boolean {\n\tconst eq = arg.indexOf(\"=\");\n\tif (eq > 0) {\n\t\tflags[arg.slice(2, eq)] = arg.slice(eq + 1);\n\t\treturn false;\n\t}\n\t// --flag or --flag value\n\tconst key = arg.slice(2);\n\tif (next !== undefined && !next.startsWith(\"--\")) {\n\t\tflags[key] = next;\n\t\treturn true;\n\t}\n\tflags[key] = true;\n\treturn false;\n}\n\n/**\n * Handles the argument at `index` and returns the index of the last argument\n * it consumed; `args.length` stops the scan.\n */\nfunction parseArgAt(\n\targs: string[],\n\tindex: number,\n\tpositional: string[],\n\tflags: Record<string, string | true>,\n): number {\n\tconst arg = args[index];\n\tif (arg === undefined || arg === \"\") return index;\n\tif (arg === \"--\") {\n\t\tfor (const rest of args.slice(index + 1)) {\n\t\t\tif (rest !== \"\") positional.push(rest);\n\t\t}\n\t\treturn args.length;\n\t}\n\tif (arg.startsWith(\"--\")) {\n\t\treturn parseLongFlag(arg, args[index + 1], flags) ? index + 1 : index;\n\t}\n\tif (arg === \"-q\") {\n\t\t// `-q` is the quiet shorthand; `--q <text>` stays a search value.\n\t\tflags.quiet = true;\n\t} else {\n\t\tpositional.push(arg);\n\t}\n\treturn index;\n}\n\n/**\n * Minimal argv parser for bb CLI.\n * Supports: command [positional...] [--key=value] [--key value]\n */\nexport function parseArgs(argv: string[]): {\n\tcommand: string;\n\tpositional: string[];\n\tflags: Record<string, string | true>;\n} {\n\tconst args = argv.slice(2); // drop node and script\n\tconst positional: string[] = [];\n\tconst flags: Record<string, string | true> = {};\n\n\tfor (let i = 0; i < args.length; i++) {\n\t\ti = parseArgAt(args, i, positional, flags);\n\t}\n\n\tconst command = positional[0] ?? \"\";\n\treturn { command, positional: positional.slice(1), flags };\n}\n\nexport function getFlag(\n\tflags: Record<string, string | true>,\n\tkey: string,\n): string | undefined;\nexport function getFlag<T extends string | number>(\n\tflags: Record<string, string | true>,\n\tkey: string,\n\tparse: (s: string) => T,\n): T | undefined;\nexport function getFlag<T extends string | number>(\n\tflags: Record<string, string | true>,\n\tkey: string,\n\tparse?: (s: string) => T,\n): string | number | undefined {\n\tconst v = flags[key];\n\tif (v === undefined || v === true) return undefined;\n\tif (parse) return parse(v);\n\treturn v;\n}\n", "import { CliRuntimeError } from \"@go-labs-sg/bb/runtime/error\";\n\nexport function parseJsonFlag<T>(raw: string | undefined, label: string): T {\n\tif (raw === undefined || raw === \"\") {\n\t\tthrow new CliRuntimeError(\n\t\t\t\"VALIDATION\",\n\t\t\t`${label} is required (JSON string).`,\n\t\t);\n\t}\n\ttry {\n\t\treturn JSON.parse(raw) as T;\n\t} catch {\n\t\tthrow new CliRuntimeError(\"VALIDATION\", `${label} must be valid JSON.`);\n\t}\n}\n\nexport function parseJsonObjectFlag<T extends object>(\n\traw: string | undefined,\n\tlabel: string,\n): T {\n\tconst value = parseJsonFlag<unknown>(raw, label);\n\tif (value === null || typeof value !== \"object\" || Array.isArray(value)) {\n\t\tthrow new CliRuntimeError(\"VALIDATION\", `${label} must be a JSON object.`);\n\t}\n\treturn value as T;\n}\n\nexport function parseOptionalNumber(\n\traw: string | number | undefined,\n\tlabel: string,\n): number | undefined {\n\tif (raw === undefined || raw === \"\") return undefined;\n\tconst n =\n\t\ttypeof raw === \"number\" ? raw : Number.parseFloat(String(raw).trim());\n\tif (!Number.isFinite(n)) {\n\t\tthrow new CliRuntimeError(\"VALIDATION\", `${label} must be a number.`);\n\t}\n\treturn n;\n}\n", "interface PayloadHelp {\n\trequired: string;\n\toptional: string;\n\texample: string;\n}\n\n// The CLI payload parsers and API validators remain authoritative; these examples\n// use placeholder IDs and illustrate the required JSON shape, not live records.\nexport const payloadHelp: Readonly<Record<string, PayloadHelp>> = {\n\t\"create-budget\": {\n\t\trequired:\n\t\t\t\"name: string; budget: decimal string; paymentTerm: string; categoryId: string; projectId: string\",\n\t\toptional:\n\t\t\t\"sourceBudgetId: string; unavailableItemReviewAcknowledged: boolean (only after review)\",\n\t\texample:\n\t\t\t'{\"name\":\"Event budget\",\"budget\":\"1500\",\"paymentTerm\":\"Net 30\",\"categoryId\":\"<category-id>\",\"projectId\":\"<project-id>\"}',\n\t},\n\t\"update-budget\": {\n\t\trequired:\n\t\t\t\"id: string; name: string; budget: decimal string; paymentTerm: string; categoryId: string; projectId: string\",\n\t\toptional: \"sourceBudgetId: string\",\n\t\texample:\n\t\t\t'{\"id\":\"<budget-id>\",\"name\":\"Event budget\",\"budget\":\"1500\",\"paymentTerm\":\"Net 30\",\"categoryId\":\"<category-id>\",\"projectId\":\"<project-id>\"}',\n\t},\n\t\"create-item\": {\n\t\trequired:\n\t\t\t\"name: string (QuickBooks-safe characters); categoryId: string; supplierId: string; cost: decimal string or number\",\n\t\toptional:\n\t\t\t\"description: string; gstInclusive: boolean; gstOutOfScope: boolean; goLabsProduct: boolean; attachments: array\",\n\t\texample:\n\t\t\t'{\"name\":\"Event Crew per hour\",\"categoryId\":\"<category-id>\",\"supplierId\":\"<supplier-id>\",\"cost\":19}',\n\t},\n\t\"update-item\": {\n\t\trequired:\n\t\t\t\"id: string; name: string; categoryId: string; supplierId: string; cost: decimal string or number\",\n\t\toptional:\n\t\t\t\"description: string; gstInclusive: boolean; gstOutOfScope: boolean; goLabsProduct: boolean; attachments: array\",\n\t\texample:\n\t\t\t'{\"id\":\"<item-id>\",\"name\":\"Event Crew per hour\",\"categoryId\":\"<category-id>\",\"supplierId\":\"<supplier-id>\",\"cost\":\"19\"}',\n\t},\n\t\"create-contact-person\": {\n\t\trequired:\n\t\t\t\"companyId: string; title: MR|MRS|MS|DR; firstName: string; lastName: string|null; email: string; mobile: string\",\n\t\toptional:\n\t\t\t\"address: {streetAddress1?, city?, state?, postalCode?, countryCode? (ISO 3166-1 alpha-2, e.g. SG)}\",\n\t\texample:\n\t\t\t'{\"companyId\":\"<company-id>\",\"title\":\"MS\",\"firstName\":\"Jane\",\"lastName\":\"Tan\",\"email\":\"jane@example.com\",\"mobile\":\"+65 9123 4567\"}',\n\t},\n\t\"update-contact-person\": {\n\t\trequired:\n\t\t\t\"id: string; companyId: string; title: MR|MRS|MS|DR; firstName: string; lastName: string|null; email: string; mobile: string\",\n\t\toptional: \"address: object\",\n\t\texample:\n\t\t\t'{\"id\":\"<contact-id>\",\"companyId\":\"<company-id>\",\"title\":\"MS\",\"firstName\":\"Jane\",\"lastName\":\"Tan\",\"email\":\"jane@example.com\",\"mobile\":\"+65 9123 4567\"}',\n\t},\n\t\"update-company\": {\n\t\trequired: \"id: string; name: string; website: URL string\",\n\t\toptional:\n\t\t\t\"confirmDistinct: boolean; billingEmails: email string[] (max 50; omit to preserve, [] to clear; trimmed, lowercased and deduplicated by the API)\",\n\t\texample:\n\t\t\t'{\"id\":\"<company-id>\",\"name\":\"Example Co\",\"website\":\"https://example.com\",\"billingEmails\":[\"ap@example.com\",\"finance@example.com\"]}',\n\t},\n\t\"update-project\": {\n\t\trequired:\n\t\t\t\"id: string; name: string; companyId: string; contactPersonId: string; asanaTaskId: string; insideSalesId: string; businessDevelopmentId: string; venue: string; dateRange: {from: ISO date}\",\n\t\toptional:\n\t\t\t\"dateRange.to: ISO date; projectManagerId: string; pax: string; description: string; slackChannelId/slackChannelUrl/slackChannelName: strings (supply all three); requestQboAccountantNotification: boolean; confirmEstimateInvalidation: boolean. Changing companyId requires a contactPersonId from the new company; the company change itself does not reject existing estimates or touch existing invoices, but date, pax or venue changes in the same save still require confirmEstimateInvalidation.\",\n\t\texample:\n\t\t\t'{\"id\":\"<project-id>\",\"name\":\"Launch\",\"companyId\":\"<company-id>\",\"contactPersonId\":\"<contact-id>\",\"asanaTaskId\":\"<asana-task-id>\",\"insideSalesId\":\"<user-id>\",\"businessDevelopmentId\":\"<user-id>\",\"venue\":\"Hall\",\"dateRange\":{\"from\":\"2026-10-01T09:00:00Z\"}}',\n\t},\n\t\"create-supplier\": {\n\t\trequired:\n\t\t\t\"name: string; primaryContactPerson: string; email: string; phone: string; paymentMethodId: string; paymentTerm: string; roleId: string\",\n\t\toptional:\n\t\t\t\"gstRegistered: boolean; tags: string[]; website: URL string; address: object; attachments: array; bank and PayNow fields\",\n\t\texample:\n\t\t\t'{\"name\":\"Example Supplier\",\"primaryContactPerson\":\"Jane Tan\",\"email\":\"jane@example.com\",\"phone\":\"91234567\",\"paymentMethodId\":\"<method-id>\",\"paymentTerm\":\"Net 30\",\"roleId\":\"<role-id>\"}',\n\t},\n\t\"update-supplier\": {\n\t\trequired:\n\t\t\t\"id: string; name: string; primaryContactPerson: string; email: string; phone: string; paymentMethodId: string; paymentTerm: string; roleId: string\",\n\t\toptional:\n\t\t\t\"gstRegistered: boolean; tags: string[]; website: URL string; address: object; attachments: array; bank and PayNow fields\",\n\t\texample:\n\t\t\t'{\"id\":\"<supplier-id>\",\"name\":\"Example Supplier\",\"primaryContactPerson\":\"Jane Tan\",\"email\":\"jane@example.com\",\"phone\":\"91234567\",\"paymentMethodId\":\"<method-id>\",\"paymentTerm\":\"Net 30\",\"roleId\":\"<role-id>\"}',\n\t},\n\t\"update-budget-commission\": {\n\t\trequired:\n\t\t\t\"budgetId: string; name: string; percentage: decimal string; totalSellingAfterDiscount: number\",\n\t\toptional: \"none\",\n\t\texample:\n\t\t\t'{\"budgetId\":\"<budget-id>\",\"name\":\"Sales commission\",\"percentage\":\"10\",\"totalSellingAfterDiscount\":1500}',\n\t},\n\t\"update-budget-discount\": {\n\t\trequired:\n\t\t\t\"budgetId: string; name: string; type: percentage|amount; value: decimal string; totalSellingBeforeDiscount: number\",\n\t\toptional: \"none\",\n\t\texample:\n\t\t\t'{\"budgetId\":\"<budget-id>\",\"name\":\"Discount\",\"type\":\"amount\",\"value\":\"100\",\"totalSellingBeforeDiscount\":1500}',\n\t},\n\t\"send-estimate-to-contact-person\": {\n\t\trequired:\n\t\t\t\"estimateId: string; budgetId: string; to: email; cc: email[]; replyTo: email; subject: string; content: HTML string; signature: HTML string\",\n\t\toptional: \"estimateDocNumber: string\",\n\t\texample:\n\t\t\t'{\"estimateId\":\"<estimate-id>\",\"budgetId\":\"<budget-id>\",\"to\":\"client@example.com\",\"cc\":[],\"replyTo\":\"team@example.com\",\"subject\":\"Estimate\",\"content\":\"<p>Attached estimate</p>\",\"signature\":\"<p>Team</p>\"}',\n\t},\n\t\"create-bill\": {\n\t\trequired:\n\t\t\t\"budgetId: string; projectId: string; supplierId: string; amount: number (ex-GST); budgetItemIds: string[]; isClaimable: boolean; supplier bills: quotationIds: string[] or quotationAllocations: {budgetItemId, quotationId, amount}[] (unless --quotation-exempt)\",\n\t\toptional:\n\t\t\t\"lineAmounts: {budgetItemId, amount}[] (required with quotationAllocations); attachments: {id,name,key,size}[]; invoiceNumber: string; invoiceDate: ISO date; draftOnly: boolean; alreadyPaid: boolean; extractedAmount: number\",\n\t\texample:\n\t\t\t'{\"budgetId\":\"<budget-id>\",\"projectId\":\"<project-id>\",\"supplierId\":\"<supplier-id>\",\"amount\":1800,\"budgetItemIds\":[\"<budget-item-id>\"],\"isClaimable\":false,\"quotationIds\":[\"<quotation-id>\"],\"attachments\":[]}',\n\t},\n\t\"update-bill\": {\n\t\trequired:\n\t\t\t\"id: string; budgetId: string; projectId: string; supplierId: string; amount: number (ex-GST); budgetItemIds: string[]; isClaimable: boolean\",\n\t\toptional:\n\t\t\t\"quotationIds: string[]; quotationAllocations: {budgetItemId, quotationId, amount}[]; lineAmounts: {budgetItemId, amount}[]; attachments: {id,name,key,size}[]; invoiceNumber: string; invoiceDate: ISO date\",\n\t\texample:\n\t\t\t'{\"id\":\"<bill-id>\",\"budgetId\":\"<budget-id>\",\"projectId\":\"<project-id>\",\"supplierId\":\"<supplier-id>\",\"amount\":1800,\"budgetItemIds\":[\"<budget-item-id>\"],\"isClaimable\":false,\"quotationIds\":[\"<quotation-id>\"],\"attachments\":[]}',\n\t},\n\t\"validate-bill-selection\": {\n\t\trequired: \"projectId: string; supplierId: string; budgetItemIds: string[]\",\n\t\toptional:\n\t\t\t\"quotationIds: string[] for supplier bills; isClaimable: boolean; amount: number; lineAmounts: {budgetItemId, amount}[]; quotationAllocations: {budgetItemId, quotationId, amount}[] (requires amount and lineAmounts)\",\n\t\texample:\n\t\t\t'{\"projectId\":\"<project-id>\",\"supplierId\":\"<supplier-id>\",\"budgetItemIds\":[\"<budget-item-id>\"],\"quotationIds\":[\"<quotation-id>\"]}',\n\t},\n\t\"link-bill-quotations\": {\n\t\trequired:\n\t\t\t\"positional <billId>; quotationIds: string[] or quotationAllocations: {budgetItemId, quotationId, amount}[]\",\n\t\toptional: \"none (legacy quotationId is not supported)\",\n\t\texample: '{\"quotationIds\":[\"<quotation-id>\"]}',\n\t},\n\t\"update-bill-payment-evidence\": {\n\t\trequired:\n\t\t\t\"id: string; paymentReference: string; paymentProofAttachments: {id,name (PDF),key,size}[] (at least one)\",\n\t\toptional: \"none\",\n\t\texample:\n\t\t\t'{\"id\":\"<bill-id>\",\"paymentReference\":\"TRANSFER-123\",\"paymentProofAttachments\":[{\"id\":\"<attachment-id>\",\"name\":\"receipt.pdf\",\"key\":\"<staged-key>\",\"size\":1000}]}',\n\t},\n\t\"create-quotation\": {\n\t\trequired:\n\t\t\t\"projectId: string; budgetId: string; supplierId: string; budgetItemIds: string[]; amountWithoutGst: number; gstAmount: number; attachments: array (uploaded attachment)\",\n\t\toptional:\n\t\t\t'lineAmounts: {budgetItemId, amount}[] (required for multiple budget items unless documentOnly); documentOnly: boolean (default false; true for a $0 supplier document: amountWithoutGst 0, gstAmount 0, zero lineAmounts, lineAmounts may be omitted; never a valid bill quotation source). Document-only example: {\"projectId\":\"<project-id>\",\"budgetId\":\"<budget-id>\",\"supplierId\":\"<supplier-id>\",\"budgetItemIds\":[\"<budget-item-id>\"],\"amountWithoutGst\":0,\"gstAmount\":0,\"documentOnly\":true,\"attachments\":[{...}]}',\n\t\texample:\n\t\t\t'{\"projectId\":\"<project-id>\",\"budgetId\":\"<budget-id>\",\"supplierId\":\"<supplier-id>\",\"budgetItemIds\":[\"<budget-item-id>\"],\"amountWithoutGst\":1200,\"gstAmount\":0,\"attachments\":[{\"id\":\"<attachment-id>\",\"name\":\"quote.pdf\",\"key\":\"<staged-key>\",\"size\":1000}]}',\n\t},\n\t\"update-quotation\": {\n\t\trequired:\n\t\t\t\"id: string; projectId: string; budgetId: string; supplierId: string; budgetItemIds: string[]; amountWithoutGst: number; gstAmount: number; attachments: array\",\n\t\toptional:\n\t\t\t\"lineAmounts: {budgetItemId, amount}[] (required for multiple budget items unless documentOnly); documentOnly: boolean (default false; update is a full replace, so send documentOnly: true again, with amountWithoutGst 0 and gstAmount 0, for a document-only quotation)\",\n\t\texample:\n\t\t\t'{\"id\":\"<quotation-id>\",\"projectId\":\"<project-id>\",\"budgetId\":\"<budget-id>\",\"supplierId\":\"<supplier-id>\",\"budgetItemIds\":[\"<budget-item-id>\"],\"amountWithoutGst\":1200,\"gstAmount\":0,\"attachments\":[{\"id\":\"<attachment-id>\",\"name\":\"quote.pdf\",\"key\":\"<staged-key>\",\"size\":1000}]}',\n\t},\n\t\"create-customer-invoice\": {\n\t\trequired:\n\t\t\t\"budgetId: string; splits: [{label: string, percentage: number, dueDate: ISO date}] (exactly one)\",\n\t\toptional:\n\t\t\t\"requestId: UUID string (recommended); invoiceDate: ISO date; details: {billingAddress: string, customerMemo: string}; isCustomPercentage: boolean\",\n\t\texample:\n\t\t\t'{\"budgetId\":\"<budget-id>\",\"splits\":[{\"label\":\"Deposit\",\"percentage\":50,\"dueDate\":\"2026-10-15\"}],\"details\":{\"billingAddress\":\"1 Example St\",\"customerMemo\":\"Thanks\"}}',\n\t},\n\t\"send-customer-invoice-to-contact-person\": {\n\t\trequired:\n\t\t\t\"invoiceId: string; to: email; replyTo: email; subject: string; content: HTML string; signature: HTML string\",\n\t\toptional:\n\t\t\t\"cc: email[] (max 50; omit to use company billing defaults, explicit list replaces defaults, [] removes defaults; required internal Cc still applies)\",\n\t\texample:\n\t\t\t'{\"invoiceId\":\"<invoice-id>\",\"to\":\"client@example.com\",\"cc\":[],\"replyTo\":\"team@example.com\",\"subject\":\"Invoice\",\"content\":\"<p>Attached invoice</p>\",\"signature\":\"<p>Team</p>\"}',\n\t},\n\t\"save-inbound-mapping\": {\n\t\trequired:\n\t\t\t\"positional <sourceId>; payload: [{canonicalField: enum, typeformFieldId: string, required?: boolean, typeformFieldRef?: string|null}] (1-50 entries)\",\n\t\toptional: \"required defaults false; typeformFieldRef may be omitted\",\n\t\texample:\n\t\t\t'[{\"canonicalField\":\"CONTACT_FIRST_NAME\",\"typeformFieldId\":\"<typeform-field-id>\"}]',\n\t},\n\t\"save-inbound-automation-config\": {\n\t\trequired:\n\t\t\t\"positional <sourceId>; asanaCustomFields: object; asanaDefaultAssigneeId: string|null; asanaDefaultAssigneeName: string|null; asanaFollowerIds: string[]; asanaProjectId: string; asanaSectionId: string; asanaWonSectionId: string; asanaLostSectionId: string; googleCalendarId: string; googleCalendarTimeZone: string; goshBriefBaseUrl: URL; slackDefaultAssigneeId: string|null; slackInboundChannelId: string; slackInviteUserIds: string[]; slackPitchChannelPrefix: string\",\n\t\toptional:\n\t\t\t\"asanaDiscussionSectionId, asanaFirstContactSectionId, asanaFirstProposalSentSectionId, asanaProposalWipSectionId: string|null; googlePitchCalendarId: string|null (PITCH project events; must differ from googleCalendarId; null keeps them in googleCalendarId); asanaCustomFields.*: mapped IDs\",\n\t\texample:\n\t\t\t'{\"asanaCustomFields\":{},\"asanaDefaultAssigneeId\":null,\"asanaDefaultAssigneeName\":null,\"asanaFollowerIds\":[],\"asanaProjectId\":\"<asana-project-id>\",\"asanaSectionId\":\"<asana-section-id>\",\"asanaWonSectionId\":\"<asana-won-id>\",\"asanaLostSectionId\":\"<asana-lost-id>\",\"googleCalendarId\":\"team@example.com\",\"googleCalendarTimeZone\":\"Asia/Singapore\",\"goshBriefBaseUrl\":\"https://example.com/brief\",\"slackDefaultAssigneeId\":null,\"slackInboundChannelId\":\"<slack-channel-id>\",\"slackInviteUserIds\":[],\"slackPitchChannelPrefix\":\"pitch\"}',\n\t},\n};\n\nexport const formatPayloadHelp = (command: string): string[] => {\n\tconst help = payloadHelp[command];\n\tif (!help) return [];\n\treturn [\n\t\t\"Payload fields (--payload JSON)\",\n\t\t` Required: ${help.required}`,\n\t\t` Optional: ${help.optional}`,\n\t\t` Example: bb ${command}${command === \"link-bill-quotations\" ? \" <billId>\" : command.startsWith(\"save-inbound-\") ? \" <sourceId>\" : \"\"} --payload '${help.example}'`,\n\t\t\"\",\n\t];\n};\n", "import { formatPayloadHelp } from \"@go-labs-sg/bb/registry/payload-help\";\n\n/**\n * Declarative command catalogue for the Budget Builder CLI.\n *\n * The first v2 integration step uses `legacyTarget` to dispatch through the\n * established command implementation. New command handlers can replace that\n * target incrementally by supplying `load` instead.\n */\n\nexport type CommandEffect =\n\t| \"state-change\"\n\t| \"email\"\n\t| \"external-write\"\n\t| \"delete\"\n\t| \"financial-write\";\n\nexport type CompletionShell = \"bash\" | \"zsh\" | \"fish\" | \"powershell\";\n\nexport type CommandPath = readonly [string, ...string[]];\n\nexport interface CommandOption {\n\tname: string;\n\tdescription: string;\n\trequired?: boolean;\n}\n\nexport interface LegacyCommandRequest {\n\targv: readonly string[];\n\tlegacyTarget: string;\n}\n\nexport type CommandHandler<TInput = unknown, TOutput = unknown> = (\n\tinput: TInput,\n) => Promise<TOutput>;\n\ninterface CommandMetadata {\n\tpath: CommandPath;\n\tlegacyAliases: readonly string[];\n\tsummary: string;\n\toptions: readonly CommandOption[];\n\teffects: readonly CommandEffect[];\n}\n\nexport type CommandDefinition<TInput = unknown, TOutput = unknown> =\n\t| (CommandMetadata & {\n\t\t\tlegacyTarget: string;\n\t\t\tload?: never;\n\t })\n\t| (CommandMetadata & {\n\t\t\tlegacyTarget?: never;\n\t\t\tload: () => Promise<CommandHandler<TInput, TOutput>>;\n\t });\n\nexport interface ResolvedCommand {\n\targv: readonly string[];\n\tcommand: CommandDefinition;\n\tinvokedAs: readonly string[];\n\tisLegacyAlias: boolean;\n}\n\nexport interface CommandManifestEntry {\n\tpath: readonly string[];\n\tlegacyAliases: readonly string[];\n\tsummary: string;\n\tglobalOptions: readonly CommandOption[];\n\targumentMode: \"legacy-passthrough\" | \"typed\";\n\teffects: readonly CommandEffect[];\n\tlegacyTarget?: string;\n}\n\nexport const globalCommandOptions = [\n\t{ name: \"--help\", description: \"Show help for this command.\" },\n\t{ name: \"--quiet\", description: \"Suppress non-error diagnostics.\" },\n\t{ name: \"--debug\", description: \"Emit sanitized diagnostic traces.\" },\n\t{\n\t\tname: \"--api-url\",\n\t\tdescription: \"Override the Budget Builder API base URL.\",\n\t},\n\t{\n\t\tname: \"--no-browser\",\n\t\tdescription: \"Print the authorization URL without opening a browser.\",\n\t},\n\t{\n\t\tname: \"--allow-state-change\",\n\t\tdescription: \"Allow a Budget Builder state change in non-interactive use.\",\n\t},\n\t{\n\t\tname: \"--allow-email\",\n\t\tdescription: \"Allow sending email in non-interactive use.\",\n\t},\n\t{\n\t\tname: \"--allow-external-write\",\n\t\tdescription: \"Allow writes to external systems in non-interactive use.\",\n\t},\n\t{\n\t\tname: \"--allow-delete\",\n\t\tdescription: \"Allow deleting data in non-interactive use.\",\n\t},\n\t{\n\t\tname: \"--allow-financial-write\",\n\t\tdescription: \"Allow financial-record changes in non-interactive use.\",\n\t},\n] as const satisfies readonly CommandOption[];\n\nconst mutationPrefixes = [\n\t\"add-\",\n\t\"approve-\",\n\t\"archive-\",\n\t\"attach-\",\n\t\"cleanup-\",\n\t\"complete-\",\n\t\"create-\",\n\t\"delete-\",\n\t\"discard-\",\n\t\"import-\",\n\t\"link-\",\n\t\"mark-\",\n\t\"patch-\",\n\t\"reactivate-\",\n\t\"reconcile-\",\n\t\"record-\",\n\t\"refresh-\",\n\t\"reject-\",\n\t\"remove-\",\n\t\"replace-\",\n\t\"rename-\",\n\t\"reorder-\",\n\t\"restore-\",\n\t\"retry-\",\n\t\"revoke-\",\n\t\"save-\",\n\t\"send-\",\n\t\"stage-\",\n\t\"setup-\",\n\t\"submit-\",\n\t\"sync-\",\n\t\"update-\",\n\t\"use-existing-\",\n\t\"upload-\",\n\t\"void-\",\n];\n\nconst emailTargets = new Set([\n\t\"approve-bill\",\n\t\"approve-budget\",\n\t\"approve-customer-invoice\",\n\t\"approve-supplier\",\n\t\"create-bill\",\n\t\"create-bill-approval\",\n\t\"create-budget-approval\",\n\t\"create-customer-invoice\",\n\t\"create-supplier\",\n\t\"reject-bill\",\n\t\"reject-budget\",\n\t\"reject-customer-invoice\",\n\t\"reject-supplier\",\n\t\"send-estimate-email\",\n\t\"send-estimate-to-contact-person\",\n\t\"send-customer-invoice-to-contact-person\",\n\t\"update-bill-status\",\n\t\"update-supplier\",\n]);\n\nconst externalWriteTargets = new Set([\n\t\"update-customer-invoice-details\",\n\t\"update-customer-invoice-qbo-drift\",\n\t\"record-external-bill-payment\",\n\t\"approve-bill\",\n\t\"approve-customer-invoice\",\n\t\"approve-supplier\",\n\t\"complete-project\",\n\t\"create-bill\",\n\t\"create-company\",\n\t\"use-existing-company\",\n\t\"create-estimate\",\n\t\"create-placeholder-bill\",\n\t\"create-customer-invoice\",\n\t\"create-item\",\n\t\"create-item-category\",\n\t\"create-project\",\n\t\"create-supplier\",\n\t\"delete-bill\",\n\t\"delete-budget\",\n\t\"delete-company\",\n\t\"delete-customer-invoice\",\n\t\"delete-item\",\n\t\"delete-project\",\n\t\"delete-suppliers\",\n\t\"discard-customer-invoice\",\n\t\"import-qbo-project\",\n\t\"mark-budget-items-not-utilized\",\n\t\"mark-budget-won\",\n\t\"reconcile-project\",\n\t\"reject-customer-invoice\",\n\t\"reactivate-suppliers\",\n\t\"restore-budget-item\",\n\t\"restore-budget-version\",\n\t\"retry-integration-operation\",\n\t\"setup-project-hub\",\n\t\"sync-project-hub-commercial-documents\",\n\t\"sync-customer-invoice\",\n\t\"update-bill\",\n\t\"update-budget-status\",\n\t\"update-company\",\n\t\"update-item\",\n\t\"update-item-category\",\n\t\"update-project\",\n\t\"update-project-status\",\n\t\"update-supplier\",\n\t\"void-customer-invoice\",\n]);\n\nconst financialWriteTargets = new Set([\n\t\"update-customer-invoice-qbo-drift\",\n\t\"record-external-bill-payment\",\n\t\"import-qbo-customer-invoice\",\n\t\"link-bill-quotations\",\n\t\"approve-bill\",\n\t\"approve-customer-invoice\",\n\t\"complete-project\",\n\t\"create-bill\",\n\t\"create-customer-invoice\",\n\t\"create-estimate\",\n\t\"create-placeholder-bill\",\n\t\"delete-budget-commission\",\n\t\"delete-budget-discount\",\n\t\"delete-bill\",\n\t\"delete-budget\",\n\t\"delete-customer-invoice\",\n\t\"mark-budget-items-not-utilized\",\n\t\"mark-budget-won\",\n\t\"mark-customer-invoice-sent-externally\",\n\t\"patch-bill-payment\",\n\t\"reject-customer-invoice\",\n\t\"restore-budget-item\",\n\t\"restore-budget-version\",\n\t\"replace-budget-item\",\n\t\"sync-customer-invoice\",\n\t\"update-bill\",\n\t\"update-bill-payment-evidence\",\n\t\"update-bill-status\",\n\t\"update-budget-commission\",\n\t\"update-budget-discount\",\n\t\"update-budget-status\",\n\t\"update-project-status\",\n\t\"void-customer-invoice\",\n]);\n\nconst deleteTargets = new Set([\n\t\"cleanup-staged-bill-attachments\",\n\t\"delete-webhook-endpoint\",\n\t\"cleanup-staged-quotation-attachments\",\n\t\"discard-customer-invoice\",\n\t\"complete-project\",\n\t\"mark-budget-items-not-utilized\",\n\t\"remove-budget-item\",\n\t\"restore-budget-version\",\n\t\"update-project-status\",\n]);\n\n// These operations do not use a mutation prefix. Keep their effects explicit:\n// replay queues an outbound delivery; rotation changes the signing credentials.\nconst explicitEffects: Readonly<Record<string, readonly CommandEffect[]>> = {\n\t\"resubmit-customer-invoice\": [\n\t\t\"state-change\",\n\t\t\"external-write\",\n\t\t\"financial-write\",\n\t\t\"email\",\n\t],\n\t\"rotate-webhook-secret\": [\"state-change\"],\n\t\"replay-webhook-delivery\": [\"state-change\", \"external-write\"],\n};\n\nconst effectsFor = (legacyTarget: string): readonly CommandEffect[] => {\n\tconst explicit = explicitEffects[legacyTarget];\n\tif (explicit) return explicit;\n\tconst effects = new Set<CommandEffect>();\n\tif (mutationPrefixes.some((prefix) => legacyTarget.startsWith(prefix))) {\n\t\teffects.add(\"state-change\");\n\t}\n\tif (legacyTarget.startsWith(\"delete-\") || deleteTargets.has(legacyTarget)) {\n\t\teffects.add(\"delete\");\n\t}\n\tif (emailTargets.has(legacyTarget)) effects.add(\"email\");\n\tif (externalWriteTargets.has(legacyTarget)) effects.add(\"external-write\");\n\tif (financialWriteTargets.has(legacyTarget)) effects.add(\"financial-write\");\n\treturn [...effects];\n};\n\nconst titleCase = (value: string): string =>\n\tvalue\n\t\t.split(\"-\")\n\t\t.map((word) => `${word.slice(0, 1).toUpperCase()}${word.slice(1)}`)\n\t\t.join(\" \");\n\nconst SUMMARIES: ReadonlyMap<string, string> = new Map([\n\t[\n\t\t\"update-budget-status\",\n\t\t\"Update budget status. APPROVED requires a current Lead/Admin role; budget management permission alone is insufficient. Ordinary users must request approval. Status changes invalidate old pending requests.\",\n\t],\n\t[\n\t\t\"approve-budget\",\n\t\t\"Decide your assigned pending budget approval as a current Lead/Admin. Material edits supersede old requests; inspect the latest content and use a fresh request after edits.\",\n\t],\n\t[\n\t\t\"reject-budget\",\n\t\t\"Decide your assigned pending budget approval as a current Lead/Admin. Material edits supersede old requests; inspect the latest content and use a fresh request after edits.\",\n\t],\n\t[\n\t\t\"create-budget-approval\",\n\t\t\"Request budget approval for the current content, superseding older pending requests. Existing Lead/Admin autoapproval remains available.\",\n\t],\n\t[\n\t\t\"update-budget-item-supplier\",\n\t\t\"Change a budget item's eligible supplier/GST snapshot as a material financial edit. Supersede pending approvals and apply the standard budget-to-DRAFT reset policy; inspect and request approval again. An unchanged supplier is a no-op.\",\n\t],\n\t[\n\t\t\"submit-quotation\",\n\t\t\"Submit a quotation for signing and approval. Claim the captured revision and exact allocation selection; concurrent edits, budget-item deletion or restore cascades conflict instead of attaching old signed PDFs. Refresh and resubmit the current content. The signed PDF is stamped by a queued job (pdfProcessing: PROCESSING until linked); a file whose PDF conversion failed must be uploaded again first. The result includes gstMismatch (null, or the basis, expected GST, saved GST and their difference; see create-quotation); it is a warning only and the approval email shows it to approvers.\",\n\t],\n\t[\n\t\t\"approve-quotation\",\n\t\t\"Approve your assigned pending quotation as a current Admin. Claim the captured revision and exact allocation selection after signing; concurrent changes conflict and roll back the decision, signed-PDF job and email/outbox. Refresh and review the current content before retrying. The final signed PDF is stamped by a queued job (pdfProcessing); a stopped earlier PDF step blocks approval until it is retried.\",\n\t],\n\t[\n\t\t\"approve-supplier\",\n\t\t\"Approve a pending supplier request and send a requester reply email, or directly re-approve a rejected supplier as Admin/Lead without a pending request or email. The QuickBooks vendor is created, linked or updated by a queued job (quickBooksSyncQueued, operationId); the supplier stays PENDING_APPROVAL until QuickBooks confirms, and archived suppliers remain archived. Argument: <supplierId>.\",\n\t],\n\t[\n\t\t\"get-bill-details\",\n\t\t\"Get a bill's summary as shown in the web app: status, amounts, people, payment and line totals. Use get-bill-line-items, get-bill-approvals, get-bill-attachments or get-bill-payment for more detail. Argument: <billId>.\",\n\t],\n\t[\n\t\t\"get-bill-line-items\",\n\t\t\"List a bill's line items with budget-item and quotation-allocation detail. <billId> [--limit 1-100] [--cursor <token>] Newest first. Returns { items, pageInfo }; follow nextCursor.\",\n\t],\n\t[\n\t\t\"get-bill-approvals\",\n\t\t\"List a bill's approval requests with approver, requester and responder. <billId> [--limit 1-50] [--cursor <token>] Newest first. Returns { items, pageInfo }; follow nextCursor.\",\n\t],\n\t[\n\t\t\"get-bill-payment\",\n\t\t\"Get a bill's payment status, reference, date, tracking URL, QuickBooks link and external payment. Argument: <billId>.\",\n\t],\n\t[\n\t\t\"get-quotation\",\n\t\t\"Get a quotation as shown in the web app: status, documentOnly (true for a $0 supplier document that is never a bill quotation source and does not count as coverage), amounts, people, line totals, files and approvals. pdfProcessing is { status: PROCESSING | FAILED, step: NORMALIZE | STAMP, operationId, error } while a queued PDF conversion or signing step has not linked its PDF, else null. gstMismatch is null, or { basis, expectedGstAmount, enteredGstAmount, difference, message } when the saved GST is non-zero and more than $0.05 away from the expected GST (TAXABLE_LINES: the bill calculation for the quoted lines; FULL_SUBTOTAL: 9% of the subtotal); check it before approving. Use get-quotation-line-items for budget-item detail. Argument: <quotationId>.\",\n\t],\n\t[\n\t\t\"get-customer-invoice\",\n\t\t\"Get an invoice batch as shown in the web app: status, totals, people, approvals and invoice summaries. Use get-customer-invoice-invoices, get-customer-invoice-lines, get-customer-invoice-approvals or get-customer-invoice-history for more detail. Argument: <batchId>.\",\n\t],\n\t[\n\t\t\"get-customer-invoice-invoices\",\n\t\t\"List a batch's invoices with QuickBooks id/doc number, issue/due dates, amounts, sync state and sender. Argument: <batchId>.\",\n\t],\n\t[\n\t\t\"get-customer-invoice-lines\",\n\t\t\"List one invoice's lines (name, description, QuickBooks item/tax code, quantity, amounts). <invoiceId> [--limit 1-100] [--cursor <token>] Newest first. Returns { items, pageInfo }; follow nextCursor.\",\n\t],\n\t[\n\t\t\"get-customer-invoice-approvals\",\n\t\t\"List an invoice batch's approval requests with approver, requester and responder. <batchId> [--limit 1-50] [--cursor <token>] Newest first. Returns { items, pageInfo }; follow nextCursor.\",\n\t],\n\t[\n\t\t\"get-customer-invoice-history\",\n\t\t\"List an invoice batch's status history (batch/invoice status changes, source, note, actor). <batchId> [--limit 1-100] [--cursor <token>] Newest first. Returns { items, pageInfo }; follow nextCursor.\",\n\t],\n\t[\n\t\t\"get-customer-invoice-payments\",\n\t\t\"List the payments QuickBooks applied to one invoice: payment id, date, reference, amount applied, total and attachment names. Argument: <invoiceId> (from get-customer-invoice-invoices). Live QuickBooks read.\",\n\t],\n\t[\n\t\t\"get-quotation-line-items\",\n\t\t\"List a quotation's line items with budget-item, supplier and budget detail. <quotationId> [--limit 1-100] [--cursor <token>] Newest first. Returns { items, pageInfo }; follow nextCursor.\",\n\t],\n\t[\n\t\t\"get-bill-attachments\",\n\t\t\"List bill attachments with cursor pagination. <billId> [--limit 1-50] [--cursor <token>] Newest first. Returns { items, pageInfo }; follow nextCursor.\",\n\t],\n\t[\n\t\t\"get-budget-categories\",\n\t\t\"List budget categories with cursor pagination. [--q] [--limit 1-100] [--cursor <token>] Active categories, name A–Z. Returns { items, pageInfo }; follow nextCursor with the same --q.\",\n\t],\n\t[\n\t\t\"get-supplier-overview\",\n\t\t\"Get a supplier's profile, approvals, pending update, attachments and tab counts (usageCount, _count.items). Skips usage rows, spending and items; use get-supplier-usage or get-supplier-items for those.\",\n\t],\n\t[\n\t\t\"get-supplier-usage\",\n\t\t\"Get a supplier's usage rows (accepted/closed budget lines and lines with its actual spending) plus spending, actualSpending and estimatedSpending.\",\n\t],\n\t[\n\t\t\"get-supplier-items\",\n\t\t\"Get the inventory items catalogued under a supplier.\",\n\t],\n\t[\n\t\t\"get-supplier-analytics\",\n\t\t\"List supplier analytics rows with cursor pagination. [--name] [--status CSV] [--gstRegistered true|false] [--createdBy <text>] [--timeFrame ALL|LAST_YEAR|LAST_6_MONTHS|LAST_3_MONTHS|CUSTOM] [--startDate <ISO> --endDate <ISO>] [--sortBy name|gstRegistered|status|phone|email|updatedAt|createdAt] [--sortDir asc|desc] [--limit 1-100] [--cursor <token>] [--direction forward|backward] Admin. Returns { items, pageInfo }; follow nextCursor/previousCursor with the same filters and sort. --page/--perPage are rejected.\",\n\t],\n\t[\n\t\t\"list-api-keys\",\n\t\t\"List API keys with cursor pagination. [--userId <userId>] [--limit 1-100] [--cursor <token>] (newest first, { items, pageInfo }; defaults to the caller; admin required for another user)\",\n\t],\n\t[\n\t\t\"list-claims\",\n\t\t\"List reimbursable claims with cursor pagination. Same flags as list-bills (--limit 1-100, --cursor, --direction forward|backward); ignores --isClaimable. Returns { items, pageInfo }.\",\n\t],\n\t[\n\t\t\"list-bills\",\n\t\t\"List bills with cursor pagination. [--projectId] [--budgetId] [--status CSV] [--search <text>] [--isClaimable true|false] [--createdByIds <csv>] [--sortBy createdAt|amount|status] [--sortDir asc|desc] [--limit 1-100] [--cursor <token>] [--direction forward|backward] Returns { items, pageInfo }; pass nextCursor with --direction forward or previousCursor with --direction backward, keeping the same filters and sort. --page/--pageSize/--perPage are rejected.\",\n\t],\n\t[\n\t\t\"list-customer-invoices\",\n\t\t\"List customer invoice batches with cursor pagination. [budgetId] [--projectId <id>] [--companyIds CSV] [--projectIds CSV] [--budgetIds CSV] [--createdByIds CSV] [--status CSV] [--search] [--sortBy createdAt|status|totalInvoiceAmount|approvalExpiresAt] [--sortDir asc|desc] [--limit 1-100] [--cursor <token>] [--direction forward|backward] Returns { items, pageInfo }; follow nextCursor/previousCursor with the same filters and sort. --page/--perPage are rejected. No scope flag lists invoices globally. --projectId uses the project scope. A positional budgetId is a backward-compatible shortcut for --budgetIds.\",\n\t],\n\t[\n\t\t\"list-quotations\",\n\t\t\"List quotations with cursor pagination. [--projectId] [--budgetId] [--supplierId] [--status CSV] [--createdBy CSV] [--search] [--limit 1-100] [--cursor <token>] [--direction forward|backward] Newest first; returns { items, pageInfo }; each row carries documentOnly (document-only $0 quotations are listed and counted like any other). Follow nextCursor/previousCursor with the same filters. --page/--pageSize/--perPage are rejected; --requesterIds remains an alias for --createdBy.\",\n\t],\n\t[\n\t\t\"list-users\",\n\t\t\"List users with cursor pagination. [--q] [--projectTeamOnly true|false] [--limit 1-100] [--cursor <token>] Name A–Z. Returns { items, pageInfo }; follow nextCursor with the same --q and --projectTeamOnly. --projectTeamOnly true lists only active @getout.sg users, the only accounts accepted as Inside Sales, Business Development or Project Manager. --page/--perPage are rejected.\",\n\t],\n\t[\n\t\t\"list-companies\",\n\t\t\"List companies with cursor pagination. Returns { items, pageInfo }; default sort is createdAt descending with limit 20. Pass nextCursor forward or previousCursor backward unchanged. Legacy page/perPage flags are rejected.\",\n\t],\n\t[\n\t\t\"count-companies\",\n\t\t\"Count companies independently from list pagination. Returns { totalCount, counts: { active: { true, false } } }; accepts filters only and rejects pagination/sorting flags.\",\n\t],\n\t[\n\t\t\"list-projects\",\n\t\t\"List projects with cursor pagination. Returns { items, pageInfo }; default sort is createdAt descending with limit 20. Supports legacy --status plus optional --statuses, WON-date filters (--wonFrom, --wonTo, --wonWithinDays) and --sortBy wonAt; pass nextCursor forward or previousCursor backward unchanged. Legacy page/perPage flags are rejected.\",\n\t],\n\t[\n\t\t\"count-projects\",\n\t\t\"Count projects independently from list pagination. Returns { totalCount, counts: { status, active: { true, false } } }; accepts project filters only and rejects pagination/sorting flags.\",\n\t],\n\t[\n\t\t\"search-existing-companies\",\n\t\t\"Search BB and QuickBooks companies without writes. --query <name> [--limit 1-50] [--cursor <token>]. Returns { items, totalCount, pageInfo }; follow pageInfo.nextCursor with the same --query. Legacy --page is rejected.\",\n\t],\n\t[\n\t\t\"use-existing-company\",\n\t\t\"Reuse a company in BB and QuickBooks, creating only its missing counterpart. Supply --companyId <bbId> and/or --quickbooksId <qboId>; both explicitly connect records with different names. Importing a QuickBooks-only company also needs --name <QuickBooks name from search-existing-companies>. --website <url> fills a missing QBO import website only. --confirmDistinct true confirms no similar record represents this entity. BB saves the company now; its QuickBooks customer is checked, found or created and linked by a queued job (quickBooksSyncQueued, operationId). Estimates, invoices and QuickBooks projects wait for that link.\",\n\t],\n\t[\n\t\t\"create-company\",\n\t\t\"Create or reuse a company in BB and QuickBooks. --name <name> --website <url> [--billingEmails '<json-array>'] (up to 50 invoice Cc defaults, stored in BB only for new companies; reused company defaults are preserved). Similar names require --confirmDistinct true; inactive companies are never reactivated. BB saves the company now; its QuickBooks customer is found or created by a queued job (quickBooksSyncQueued, operationId), which stops if similar QuickBooks customers exist without --confirmDistinct.\",\n\t],\n\t[\n\t\t\"create-project\",\n\t\t\"Create a project linked to an existing Asana Deals lead task. Supply --asanaTaskId in non-interactive use; interactive use searches for and selects a lead task (optionally --asanaSearch). The Slack channel is resolved from the selected Asana task unless all three Slack channel flags are supplied. For a new direct client, create the lead task using the website form first.\",\n\t],\n\t[\n\t\t\"create-supplier\",\n\t\t\"Create a supplier using --payload JSON; pending-approval suppliers also request approval and send emails. Reusing an archived name requires Admin; normal users and Leads must ask an Admin to reactivate it before editing. Recreation preserves the existing approval status and creator. Lead/Admin-created suppliers (and archived-name revivals) queue their QuickBooks vendor create or link (quickBooksSyncQueued, operationId) and become usable once QuickBooks confirms; the request makes no QuickBooks call.\",\n\t],\n\t[\n\t\t\"preview-qbo-customer-invoice\",\n\t\t\"Preview an available QuickBooks invoice selected for a BB budget using read-only QBO access. Arguments: <budgetId> <qboInvoiceId>.\",\n\t],\n\t[\n\t\t\"preview-customer-invoice-amount\",\n\t\t\"Preview amount before GST, GST, and total for a percentage of an accepted estimate. Arguments: <budgetId> <percentage-of-estimate>.\",\n\t],\n\t[\n\t\t\"list-available-qbo-customer-invoices\",\n\t\t\"List unlinked QuickBooks invoices available for an accepted or closed estimate. Argument: <budgetId>.\",\n\t],\n\t[\n\t\t\"resubmit-customer-invoice\",\n\t\t\"Resubmit a confirmed expired-and-voided BB invoice as its original requester. Argument: <batchId>. Queues one replacement using the current estimate, original percentage, due date and details; retries return the same replacement. No customer email.\",\n\t],\n\t[\n\t\t\"create-customer-invoice\",\n\t\t\"Create one invoice from an eligible budget using --payload JSON with invoice date, due date, billing address, customer memo, and a percentage of the original estimate that does not exceed its remaining coverage.\",\n\t],\n\t[\n\t\t\"import-qbo-customer-invoice\",\n\t\t\"Link an existing QuickBooks invoice in BB only after reviewing preview-qbo. Arguments: <budgetId> <qboInvoiceId> --token <previewToken>. Supports closed estimates; no QBO writes or emails.\",\n\t],\n\t[\"whoami\", \"Show the active API-key identity.\"],\n\t[\n\t\t\"list-budgets\",\n\t\t\"List one cursor page of budgets ({ items, pageInfo }; --limit/--cursor/--direction). Omit --active for active budgets only; use --active false or --active all for Admin-only historical reads.\",\n\t],\n\t[\n\t\t\"list-items\",\n\t\t\"List one cursor page of catalogue items ({ items, pageInfo }; --limit/--cursor/--direction, optional --sortBy/--sortDir). --page/--perPage are rejected.\",\n\t],\n\t[\n\t\t\"list-item-categories\",\n\t\t\"List one cursor page of active item categories ({ items, pageInfo }; --limit/--cursor/--direction, optional --name/--sortBy/--sortDir). --page/--perPage are rejected.\",\n\t],\n\t[\n\t\t\"create-item-category\",\n\t\t\"Admin only. Create (or reactivate) an item category. Budget Builder saves it now and a queued job creates or links the QuickBooks category (quickBooksSyncQueued, operationId); the request makes no QuickBooks call.\",\n\t],\n\t[\n\t\t\"update-item-category\",\n\t\t\"Rename an item category. Budget Builder saves the name immediately; a category linked to QuickBooks is renamed there by a queued job (quickBooksSyncQueued: true, operationId), never during the request.\",\n\t],\n\t[\n\t\t\"count-item-categories\",\n\t\t\"Count active item categories matching --name: { totalCount }.\",\n\t],\n\t[\n\t\t\"list-webhook-deliveries\",\n\t\t\"Admin-only: list webhook deliveries newest first. Returns { items, pageInfo }; follow pageInfo.nextCursor (or previousCursor with --direction backward). Cursors are opaque and filter-bound; raw delivery ids are rejected.\",\n\t],\n\t[\n\t\t\"list-integration-operations\",\n\t\t\"List one cursor page of integration operations, newest first ({ items, pageInfo }; --limit/--cursor/--direction). --page/--perPage are rejected. Admin only.\",\n\t],\n\t[\n\t\t\"count-integration-operations\",\n\t\t\"Provider filter options for integration operations: { filterOptions }. No total; filter flags are accepted but do not change the result. Admin only.\",\n\t],\n\t[\n\t\t\"count-items\",\n\t\t\"Count catalogue items matching filters: total plus category and supplier facets (each ignores its own filter).\",\n\t],\n\t[\n\t\t\"count-budgets\",\n\t\t\"Count budgets matching filters: totalCount plus status and active facets. Omit --active for active budgets only.\",\n\t],\n\t[\n\t\t\"get-budget\",\n\t\t\"Get a budget by ID. Omit --includeInactive for active budgets only; --includeInactive is an Admin-only historical read.\",\n\t],\n\t[\n\t\t\"get-budget-items\",\n\t\t\"Get line items for a budget. Omit --includeInactive for active budgets only; --includeInactive is an Admin-only historical read.\",\n\t],\n\t[\n\t\t\"get-budget-details\",\n\t\t\"Get budget details. Omit --includeInactive for active budgets only; --includeInactive is an Admin-only historical read.\",\n\t],\n\t[\n\t\t\"create-bill\",\n\t\t\"Create a bill or claim with an approved supplier. All amount fields exclude GST: amount is the portion billed; extractedAmount is the full invoice subtotal; lineAmounts and quotationAllocations also exclude GST. Example: 1800 + 162 GST = 1962 total requires amount=1800 and extractedAmount=1800 for a full bill. The CLI does not strip GST from input. If the selected quotations cannot split the bill amount across every selected line (a line without a quoted amount that cannot be derived from the quotation total), pass lineAmounts; updates that keep the same amount and lines reuse the existing line amounts. --draft-only guarantees DRAFT without email or external writes; otherwise unpaid creation skips email permission but keeps external-write permission. The result includes quotationOverBillingWarnings; a non-empty list means linked non-rejected bills exceed a quotation's quoted amount. It is a warning only and the write still succeeds. An Admin's unpaid bill is approved on creation and its QuickBooks bill is created by a queued job: the result has quickBooksSyncQueued: true and operationId; follow it with list-integration-operations. The request itself never writes to QuickBooks. Quotations with documentOnly: true (a $0 supplier document) are never valid bill quotation sources and are rejected; a budget line covered only by one still counts as unquoted.\",\n\t],\n\t[\n\t\t\"record-external-bill-payment\",\n\t\t\"Record an already-made payment on an APPROVED bill or claim, with no email and no money transfer. Requires <billId> --paymentReference --paymentDate YYYY-MM-DD --paymentAccount <QBO account ID> [--paymentProof receipt.pdf]. The account must be in the cached list (list-external-payment-accounts); the request makes no QuickBooks call. An inactive account (inactiveAccounts) only links the bill's existing QuickBooks payment when the bill is already settled; if there is none, the job is refused before anything is created and the bill goes back to APPROVED. Reuses settled QBO payment links or queues one dated payment from the selected account; the queued job re-checks the account in QuickBooks and stops in the Integration Queue if it is not active. Exact retries are safe; do not pay again while reconciliation is pending.\",\n\t],\n\t[\n\t\t\"mark-customer-invoice-sent-externally\",\n\t\t\"Admin only. Record an APPROVED customer invoice as SENT (source EXTERNAL) because it was emailed to the customer outside Budget Builder. Sends no email and writes nothing to QuickBooks. Requires <invoiceId> --sentAt <ISO datetime, not in the future, not before approval> --recipients a@x.com,b@y.com [--note <message reference>].\",\n\t],\n\t[\n\t\t\"list-external-payment-accounts\",\n\t\t\"List active QuickBooks bank and credit-card account IDs for recording external payments (admin only), from Budget Builder's cached list: { accounts, cacheState, inactiveAccounts, refreshedAt, refresh }. inactiveAccounts can only link an already-settled bill's existing payment. No QuickBooks call. The worker refreshes the list automatically every day and after a QuickBooks company change; cacheState is READY, NOT_LOADED (first load pending), REALM_CHANGED (refreshing after a company change; no accounts served and external payments refused until it lands) or DISCONNECTED.\",\n\t],\n\t[\n\t\t\"refresh-external-payment-accounts\",\n\t\t\"Admin only. Queue a refresh of the cached QuickBooks payment-account list ({ operationId, status: QUEUED }); a refresh already waiting is reused. Optional: the worker already refreshes the list every day and after a QuickBooks company change. Check refreshedAt with list-external-payment-accounts.\",\n\t],\n\t[\n\t\t\"update-bill\",\n\t\t\"Update a bill or claim with a partial payload including id; omitted fields are preserved. Comment-only updates are allowed on approved/paid bills without altering financial data or QuickBooks. All amount fields exclude GST: amount is the portion billed; extractedAmount is the full invoice subtotal; lineAmounts and quotationAllocations also exclude GST. Example: 1800 + 162 GST = 1962 total requires amount=1800 and extractedAmount=1800 for a full bill. The CLI does not strip GST from input. If the selected quotations cannot split the bill amount across every selected line (a line without a quoted amount that cannot be derived from the quotation total), pass lineAmounts; updates that keep the same amount and lines reuse the existing line amounts. Re-read and verify both amount fields and allocations after correcting a gross/net mistake. The result includes quotationOverBillingWarnings; a non-empty list means linked non-rejected bills exceed a quotation's quoted amount. It is a warning only and the write still succeeds. Quotations with documentOnly: true (a $0 supplier document) are never valid bill quotation sources and are rejected; a budget line covered only by one still counts as unquoted.\",\n\t],\n\t[\n\t\t\"validate-bill-selection\",\n\t\t\"Validate the approved supplier and selected bill line items. Supplier bills need approved quotation sources (quotationIds, legacy quotationId, or quotationAllocations with lineAmounts) for every line that is not quotation-exempt (Go Internal lines, or projects/budgets created before the quotation cutoff). With billId, lines already on the bill keep their stored sources unless new sources are supplied. Exemption is decided by the server, so there is no --quotation-exempt flag here. Amounts (amount, lineAmounts, quotationAllocations) are ex-GST dollars with at most 2 decimal places. Returns { success, quotationOverBillingWarnings }: a non-empty warning list means the selection would bill a quotation above its quoted amount (counting other non-rejected bills); this is a warning only and does not fail validation. Quotations with documentOnly: true (a $0 supplier document) are never valid bill quotation sources and are rejected; a budget line covered only by one still counts as unquoted.\",\n\t],\n\t[\n\t\t\"create-quotation\",\n\t\t'Create a quotation with an approved supplier using --payload JSON. Include projectId, budgetId, supplierId, budgetItemIds, amountWithoutGst, gstAmount, and one uploaded attachment in attachments. Multiple budget items require lineAmounts: [{\"budgetItemId\":\"<first-id>\",\"amount\":750},{\"budgetItemId\":\"<second-id>\",\"amount\":450}], covering every selected budget-item ID exactly once and summing to amountWithoutGst. Amounts exclude GST; use gstAmount: 0 for no GST. Example: amountWithoutGst: 1200 with line amounts 750 and 450. The upload is checked and converted to PDF by a queued job (pdfProcessing in the result and in get-quotation). The result includes gstMismatch: null, or { basis, expectedGstAmount, enteredGstAmount, difference, message } when gstAmount is non-zero and more than $0.05 away from the expected GST. basis TAXABLE_LINES uses the bill calculation for the quoted lines (9% of each in-scope line, rounded per line; none for a non-GST-registered supplier); FULL_SUBTOTAL is 9% of amountWithoutGst, used when line amounts are unknown. It is a warning only (GST 0 is always accepted) and the write still succeeds. Document-only quotation (a $0 supplier document, for example a supplier contract or proposal with no price): set documentOnly: true with amountWithoutGst: 0, gstAmount: 0 and every lineAmounts amount 0 (lineAmounts may be omitted; the API fills zeros). It uses the normal draft, submit, sign and Admin approve flow with the attachment, appears in list/get output with documentOnly: true, counts in quotation lists and approval queues, but does not count as quotation coverage: a budget line covered only by it still counts as unquoted, and it is never a valid bill quotation source (create-bill, update-bill, validate-bill-selection and link-bill-quotations are rejected by the API). Without documentOnly (default false), amountWithoutGst must be positive.',\n\t],\n\t[\n\t\t\"cleanup-staged-quotation-attachments\",\n\t\t\"Queue independent cleanup operations for unattached staged quotation uploads; returns operation IDs and queued/skipped counts, not deletion confirmation. Arguments: <projectId> --keys <csv>.\",\n\t],\n\t[\n\t\t\"update-quotation\",\n\t\t'Update a DRAFT or REJECTED quotation using --payload JSON with id and the complete creation payload. Multiple budget items require lineAmounts: [{\"budgetItemId\":\"<first-id>\",\"amount\":750},{\"budgetItemId\":\"<second-id>\",\"amount\":450}], covering every budgetItemIds entry exactly once and summing to amountWithoutGst. Amounts exclude GST; use gstAmount: 0 for no GST. The result includes gstMismatch: null, or { basis, expectedGstAmount, enteredGstAmount, difference, message } when gstAmount is non-zero and more than $0.05 away from the expected GST. basis TAXABLE_LINES uses the bill calculation for the quoted lines (9% of each in-scope line, rounded per line; none for a non-GST-registered supplier); FULL_SUBTOTAL is 9% of amountWithoutGst, used when line amounts are unknown. It is a warning only (GST 0 is always accepted) and the write still succeeds. Update is a full replace: send documentOnly: true again when updating a document-only quotation (documentOnly: true with amountWithoutGst: 0, gstAmount: 0 and zero lineAmounts; default false requires a positive amountWithoutGst), or it is treated as a priced quotation. Document-only quotations are never valid bill quotation sources and do not count as quotation coverage.',\n\t],\n\t[\n\t\t\"download-customer-invoice-pdf\",\n\t\t\"Download a customer invoice PDF when permitted.\",\n\t],\n\t[\n\t\t\"send-customer-invoice-to-contact-person\",\n\t\t\"Send a customer invoice and update the project billing email. Omit payload cc to use company billing defaults; an explicit list replaces them and [] removes them. Required internal Cc still applies.\",\n\t],\n\t[\n\t\t\"update-company\",\n\t\t\"Save company fields in BB and queue independent QuickBooks name/website synchronization; returns operation ID, not provider completion. Optional payload billingEmails: email string array (max 50), omit to preserve defaults or [] to clear. Billing emails stay in BB; estimates are unchanged.\",\n\t],\n\t[\n\t\t\"get-company-quickbooks-sync-status\",\n\t\t\"Read saved company synchronization status without provider calls or polling; use companyId.\",\n\t],\n\t[\n\t\t\"get-item-quickbooks-sync-status\",\n\t\t\"Read saved item QuickBooks synchronization status without provider calls or polling; use itemId.\",\n\t],\n\t[\n\t\t\"create-webhook-endpoint\",\n\t\t\"Admin-only: subscribe an HTTPS endpoint to BB events. --name --url --events <type|prefix.*|*,...>. Prints the whsec_ signing secret once; deliveries use Standard Webhooks headers.\",\n\t],\n\t[\n\t\t\"rotate-webhook-secret\",\n\t\t\"Admin-only: issue a new signing secret; older secrets keep signing for --previousSecretTtlHours (default 24). Prints the new secret once. Argument: <endpointId>.\",\n\t],\n\t[\n\t\t\"send-webhook-test-event\",\n\t\t\"Admin-only: send a signed webhook.test event to one endpoint. Argument: <endpointId>.\",\n\t],\n\t[\n\t\t\"replay-webhook-delivery\",\n\t\t\"Admin-only: resend a finished webhook delivery with the same eventId on a fresh attempt chain. Argument: <deliveryId>.\",\n\t],\n\t[\n\t\t\"get-error\",\n\t\t\"Admin-only: one error log with full diagnostics (stack, cause, request details, metadata, AI summary, resolution). Argument: <errorId>. error recent list returns table columns only.\",\n\t],\n\t[\n\t\t\"get-webhook-delivery\",\n\t\t\"Admin-only: one webhook delivery with payload and attempts (status codes, errors, durations). Argument: <deliveryId>.\",\n\t],\n\t[\n\t\t\"list-webhook-event-types\",\n\t\t\"List the outbound webhook event catalogue with group and live/planned status.\",\n\t],\n\t[\n\t\t\"reconcile-resource-operation\",\n\t\t\"Admin-only check of a saved QuickBooks invoice/company/item job outcome; reads the provider only when uncertain. Applied changes are finished locally without repeating the provider mutation; provably unapplied ones are queued again. Argument: <operationId>.\",\n\t],\n\t[\n\t\t\"get-integration-operation\",\n\t\t\"Admin-only read of one integration job: who queued it, the records it is for with app links, saved QuickBooks progress, admin actions and Retry state. No provider calls. Argument: <operationId>.\",\n\t],\n\t[\n\t\t\"retry-integration-operation\",\n\t\t\"Admin-only retry of a failed integration job. QuickBooks jobs with a saved attempt check QuickBooks first: applied changes finish without resending, provably unapplied ones are sent again, unprovable ones stay stopped with the reason. Argument: <operationId>.\",\n\t],\n]);\n\nconst summaryFor = (legacyTarget: string): string => {\n\tconst summary = SUMMARIES.get(legacyTarget);\n\tif (summary !== undefined) return summary;\n\tif (legacyTarget.startsWith(\"list-\")) {\n\t\treturn `List ${legacyTarget.slice(\"list-\".length).replaceAll(\"-\", \" \")}.`;\n\t}\n\tif (legacyTarget.startsWith(\"get-\")) {\n\t\treturn `Get ${legacyTarget.slice(\"get-\".length).replaceAll(\"-\", \" \")}.`;\n\t}\n\treturn `${titleCase(legacyTarget)}.`;\n};\n\nconst aliasesFor = (\n\tlegacyTarget: string,\n\taliases: readonly string[],\n): string[] => [\n\t...new Set(\n\t\t[legacyTarget, ...aliases].flatMap((alias) => [\n\t\t\talias,\n\t\t\talias.replaceAll(\"-\", \"_\"),\n\t\t]),\n\t),\n];\n\nconst legacyCommand = (\n\tlegacyTarget: string,\n\tpath: CommandPath,\n\taliases: readonly string[] = [],\n\tcommandOptions: readonly CommandOption[] = [],\n): CommandDefinition => ({\n\tpath,\n\tlegacyAliases: aliasesFor(legacyTarget, aliases),\n\tsummary: summaryFor(legacyTarget),\n\toptions: [...globalCommandOptions, ...commandOptions],\n\teffects: effectsFor(legacyTarget),\n\tlegacyTarget,\n});\n\nconst budgetPreflightOptions = [\n\t{\n\t\tname: \"--companyPayload <json>\",\n\t\tdescription:\n\t\t\t\"Company update JSON object with id, name, and website fields.\",\n\t},\n\t{\n\t\tname: \"--contactPayload <json>\",\n\t\tdescription:\n\t\t\t\"Contact update JSON object with companyId, title, firstName, lastName, email, and mobile fields.\",\n\t},\n\t{\n\t\tname: \"--eventPayload <json>\",\n\t\tdescription:\n\t\t\t\"Event timing JSON object with date, startTime, and endTime fields.\",\n\t},\n] as const satisfies readonly CommandOption[];\n\nconst authCommand = (\n\taction: \"login\" | \"status\" | \"logout\",\n\tsummary: string,\n): CommandDefinition => ({\n\tpath: [\"auth\", action],\n\tlegacyAliases: [],\n\tsummary,\n\toptions: globalCommandOptions,\n\teffects: [],\n\tload: async () => async () => ({}),\n});\n\nconst registry = [\n\tauthCommand(\n\t\t\"login\",\n\t\t\"Authorize this device through Budget Builder in your browser.\",\n\t),\n\tauthCommand(\n\t\t\"status\",\n\t\t\"Show the active CLI authentication method and session status.\",\n\t),\n\tauthCommand(\n\t\t\"logout\",\n\t\t\"Revoke the interactive CLI session and remove its local credential.\",\n\t),\n\tlegacyCommand(\"whoami\", [\"auth\", \"whoami\"]),\n\tlegacyCommand(\n\t\t\"list-budgets\",\n\t\t[\"budget\", \"list\"],\n\t\t[],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"--active <true|false|all>\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Omit for active budgets only; false or all requires Admin access.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--limit <1-100>\",\n\t\t\t\tdescription: \"Rows per page. Output is { items, pageInfo }.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--cursor <token>\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"pageInfo.nextCursor (or previousCursor with --direction backward) from the last page, unchanged; keep the same filters and sort.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--direction <forward|backward>\",\n\t\t\t\tdescription: \"forward (default) or backward; backward needs --cursor.\",\n\t\t\t},\n\t\t],\n\t),\n\tlegacyCommand(\n\t\t\"count-budgets\",\n\t\t[\"budget\", \"count\"],\n\t\t[],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"--active <true|false|all>\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Omit for active budgets only; false or all requires Admin access.\",\n\t\t\t},\n\t\t],\n\t),\n\tlegacyCommand(\n\t\t\"get-budget\",\n\t\t[\"budget\", \"get\"],\n\t\t[],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"--includeInactive\",\n\t\t\t\tdescription: \"Include inactive historical budgets; Admin only.\",\n\t\t\t},\n\t\t],\n\t),\n\tlegacyCommand(\"upload-budget-attachment\", [\"budget\", \"attachment\", \"upload\"]),\n\tlegacyCommand(\"mark-budget-won\", [\"budget\", \"won\", \"mark\"]),\n\tlegacyCommand(\n\t\t\"get-budget-items\",\n\t\t[\"budget\", \"item\", \"list\"],\n\t\t[],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"--includeInactive\",\n\t\t\t\tdescription: \"Include inactive historical budgets; Admin only.\",\n\t\t\t},\n\t\t],\n\t),\n\tlegacyCommand(\n\t\t\"get-budget-details\",\n\t\t[\"budget\", \"detail\", \"get\"],\n\t\t[],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"--includeInactive\",\n\t\t\t\tdescription: \"Include inactive historical budgets; Admin only.\",\n\t\t\t},\n\t\t],\n\t),\n\tlegacyCommand(\n\t\t\"get-budget-categories\",\n\t\t[\"budget\", \"category\", \"list\"],\n\t\t[],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"--q <text>\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Search active category names (name A–Z). A bare --q is rejected; use -q/--quiet to hide logs.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--limit <1-100>\",\n\t\t\t\tdescription: \"Rows per page. Output is { items, pageInfo }.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--cursor <token>\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"pageInfo.nextCursor from the last page, unchanged; pages forward only.\",\n\t\t\t},\n\t\t],\n\t),\n\tlegacyCommand(\n\t\t\"get-budget-versions\",\n\t\t[\"budget\", \"version\", \"list\"],\n\t\t[],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"--limit <1-50>\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Versions per page (default 20). Returns versions and nextCursor, not a full-history array.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--cursor <versionId>\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Load the next page using the previous nextCursor; null means complete.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--all\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Explicitly fetch all visible history in bounded pages; cannot combine with --cursor. May be expensive.\",\n\t\t\t},\n\t\t],\n\t),\n\tlegacyCommand(\"rename-budget-version\", [\"budget\", \"version\", \"rename\"]),\n\tlegacyCommand(\"restore-budget-version\", [\"budget\", \"version\", \"restore\"]),\n\tlegacyCommand(\"update-budget-status\", [\"budget\", \"status\", \"update\"]),\n\tlegacyCommand(\n\t\t\"create-budget-approval\",\n\t\t[\"budget\", \"approval\", \"create\"],\n\t\t[],\n\t\tbudgetPreflightOptions,\n\t),\n\tlegacyCommand(\n\t\t\"create-estimate\",\n\t\t[\"budget\", \"estimate\", \"create\"],\n\t\t[],\n\t\tbudgetPreflightOptions,\n\t),\n\tlegacyCommand(\n\t\t\"send-estimate-to-contact-person\",\n\t\t[\"budget\", \"estimate\", \"send\"],\n\t\t[\"send-estimate-email\"],\n\t),\n\tlegacyCommand(\"create-budget\", [\"budget\", \"create\"]),\n\tlegacyCommand(\"update-budget\", [\"budget\", \"update\"]),\n\tlegacyCommand(\"delete-budget\", [\"budget\", \"delete\"]),\n\tlegacyCommand(\"add-budget-items\", [\"budget\", \"item\", \"add\"]),\n\tlegacyCommand(\"update-budget-item\", [\"budget\", \"item\", \"update\"]),\n\tlegacyCommand(\"remove-budget-item\", [\"budget\", \"item\", \"remove\"]),\n\tlegacyCommand(\"replace-budget-item\", [\"budget\", \"item\", \"replace\"]),\n\tlegacyCommand(\"approve-unavailable-item-exception\", [\n\t\t\"budget\",\n\t\t\"item\",\n\t\t\"exception\",\n\t\t\"approve\",\n\t]),\n\tlegacyCommand(\"reorder-budget-items\", [\"budget\", \"item\", \"reorder\"]),\n\tlegacyCommand(\"update-budget-item-supplier\", [\n\t\t\"budget\",\n\t\t\"item\",\n\t\t\"supplier\",\n\t\t\"update\",\n\t]),\n\tlegacyCommand(\"create-budget-category\", [\"budget\", \"category\", \"create\"]),\n\tlegacyCommand(\"update-budget-category\", [\"budget\", \"category\", \"update\"]),\n\tlegacyCommand(\"delete-budget-category\", [\"budget\", \"category\", \"delete\"]),\n\tlegacyCommand(\"update-budget-commission\", [\"budget\", \"commission\", \"update\"]),\n\tlegacyCommand(\"update-budget-discount\", [\"budget\", \"discount\", \"update\"]),\n\tlegacyCommand(\"delete-budget-commission\", [\"budget\", \"commission\", \"delete\"]),\n\tlegacyCommand(\"delete-budget-discount\", [\"budget\", \"discount\", \"delete\"]),\n\tlegacyCommand(\"mark-budget-items-not-utilized\", [\n\t\t\"budget\",\n\t\t\"item\",\n\t\t\"mark-not-utilized\",\n\t]),\n\tlegacyCommand(\"restore-budget-item\", [\"budget\", \"item\", \"restore\"]),\n\tlegacyCommand(\"create-placeholder-bill\", [\n\t\t\"budget\",\n\t\t\"item\",\n\t\t\"placeholder-bill\",\n\t\t\"create\",\n\t]),\n\tlegacyCommand(\n\t\t\"list-bills\",\n\t\t[\"bill\", \"list\"],\n\t\t[],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"--limit <1-100>\",\n\t\t\t\tdescription: \"Rows per page. Output is { items, pageInfo }.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--cursor <token>\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"pageInfo.nextCursor (or previousCursor with --direction backward) from the last page, unchanged; keep the same filters and sort.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--direction <forward|backward>\",\n\t\t\t\tdescription: \"forward (default) or backward; backward needs --cursor.\",\n\t\t\t},\n\t\t],\n\t),\n\tlegacyCommand(\n\t\t\"list-claims\",\n\t\t[\"claim\", \"list\"],\n\t\t[],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"--limit <1-100>\",\n\t\t\t\tdescription: \"Rows per page. Output is { items, pageInfo }.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--cursor <token>\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"pageInfo.nextCursor (or previousCursor with --direction backward) from the last page, unchanged; keep the same filters and sort.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--direction <forward|backward>\",\n\t\t\t\tdescription: \"forward (default) or backward; backward needs --cursor.\",\n\t\t\t},\n\t\t],\n\t),\n\tlegacyCommand(\"count-bills\", [\"bill\", \"count\"]),\n\tlegacyCommand(\"count-claims\", [\"claim\", \"count\"]),\n\tlegacyCommand(\"create-bill-approval\", [\"bill\", \"approval\", \"create\"]),\n\tlegacyCommand(\n\t\t\"create-bill\",\n\t\t[\"bill\", \"create\"],\n\t\t[],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"--draft-only\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Create a draft for every role; no approval, email, or QuickBooks writes. Conflicts with alreadyPaid: true.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--quotation-exempt\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Explicitly request an eligible server-validated supplier-bill quotation exemption. Cannot be combined with quotation IDs.\",\n\t\t\t},\n\t\t],\n\t),\n\tlegacyCommand(\n\t\t\"validate-bill-selection\",\n\t\t[\"bill\", \"selection\", \"validate\"],\n\t\t[],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"--quotationIds <csv>\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Approved quotation IDs for a supplier bill. Each selected budget item must be covered once.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--quotationId <id>\",\n\t\t\t\tdescription: \"Legacy syntax for selecting one approved quotation.\",\n\t\t\t},\n\t\t],\n\t),\n\tlegacyCommand(\n\t\t\"link-bill-quotations\",\n\t\t[\"bill\", \"quotation\", \"link\"],\n\t\t[\"billId\"],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"--payload <json>\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Explicit quotationAllocations for split source coverage on the bill's stored line amounts; documentOnly quotations are rejected.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--quotationIds <csv>\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Approved quotation IDs to link across the bill's disjoint line coverage; documentOnly quotations are rejected.\",\n\t\t\t},\n\t\t],\n\t),\n\tlegacyCommand(\"update-bill\", [\"bill\", \"update\"]),\n\tlegacyCommand(\"update-bill-payment-evidence\", [\n\t\t\"bill\",\n\t\t\"payment-evidence\",\n\t\t\"update\",\n\t]),\n\tlegacyCommand(\"delete-bill\", [\"bill\", \"delete\"]),\n\tlegacyCommand(\"update-bill-status\", [\"bill\", \"status\", \"update\"]),\n\tlegacyCommand(\"record-external-bill-payment\", [\n\t\t\"bill\",\n\t\t\"payment\",\n\t\t\"record-external\",\n\t]),\n\tlegacyCommand(\"list-external-payment-accounts\", [\n\t\t\"bill\",\n\t\t\"payment\",\n\t\t\"accounts\",\n\t]),\n\tlegacyCommand(\"refresh-external-payment-accounts\", [\n\t\t\"bill\",\n\t\t\"payment\",\n\t\t\"accounts-refresh\",\n\t]),\n\tlegacyCommand(\"patch-bill-payment\", [\"bill\", \"payment\", \"patch\"]),\n\tlegacyCommand(\"patch-bill-invoice-number\", [\n\t\t\"bill\",\n\t\t\"invoice-number\",\n\t\t\"patch\",\n\t]),\n\tlegacyCommand(\n\t\t\"get-bill-attachments\",\n\t\t[\"bill\", \"attachment\", \"list\"],\n\t\t[],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"--limit <1-50>\",\n\t\t\t\tdescription: \"Rows per page. Output is { items, pageInfo }.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--cursor <token>\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"pageInfo.nextCursor from the last page, unchanged; pages forward only.\",\n\t\t\t},\n\t\t],\n\t),\n\tlegacyCommand(\"stage-bill-attachment\", [\"bill\", \"attachment\", \"stage\"]),\n\tlegacyCommand(\"cleanup-staged-bill-attachments\", [\n\t\t\"bill\",\n\t\t\"attachment\",\n\t\t\"staged\",\n\t\t\"cleanup\",\n\t]),\n\tlegacyCommand(\n\t\t\"upload-bill-attachment\",\n\t\t[\"bill\", \"attachment\", \"upload\"],\n\t\t[\"attach-bill-attachment\"],\n\t),\n\tlegacyCommand(\"attach-bill-payment-receipt\", [\n\t\t\"bill\",\n\t\t\"payment-receipt\",\n\t\t\"attach\",\n\t]),\n\tlegacyCommand(\"attach-bill-documents\", [\"bill\", \"document\", \"attach\"]),\n\tlegacyCommand(\"get-bill-details\", [\"bill\", \"get\"]),\n\tlegacyCommand(\n\t\t\"get-bill-line-items\",\n\t\t[\"bill\", \"line-item\", \"list\"],\n\t\t[],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"--limit <1-100>\",\n\t\t\t\tdescription: \"Rows per page. Output is { items, pageInfo }.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--cursor <token>\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"pageInfo.nextCursor from the last page, unchanged; pages forward only.\",\n\t\t\t},\n\t\t],\n\t),\n\tlegacyCommand(\n\t\t\"get-bill-approvals\",\n\t\t[\"bill\", \"approval\", \"list\"],\n\t\t[],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"--limit <1-50>\",\n\t\t\t\tdescription: \"Rows per page. Output is { items, pageInfo }.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--cursor <token>\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"pageInfo.nextCursor from the last page, unchanged; pages forward only.\",\n\t\t\t},\n\t\t],\n\t),\n\tlegacyCommand(\"get-bill-payment\", [\"bill\", \"payment\", \"get\"]),\n\tlegacyCommand(\n\t\t\"list-quotations\",\n\t\t[\"quotation\", \"list\"],\n\t\t[],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"--limit <1-100>\",\n\t\t\t\tdescription: \"Rows per page. Output is { items, pageInfo }.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--cursor <token>\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"pageInfo.nextCursor (or previousCursor with --direction backward) from the last page, unchanged; keep the same filters and sort.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--direction <forward|backward>\",\n\t\t\t\tdescription: \"forward (default) or backward; backward needs --cursor.\",\n\t\t\t},\n\t\t],\n\t),\n\tlegacyCommand(\"count-quotations\", [\"quotation\", \"count\"]),\n\tlegacyCommand(\"get-quotation\", [\"quotation\", \"get\"]),\n\tlegacyCommand(\n\t\t\"get-quotation-line-items\",\n\t\t[\"quotation\", \"line-item\", \"list\"],\n\t\t[],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"--limit <1-100>\",\n\t\t\t\tdescription: \"Rows per page. Output is { items, pageInfo }.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--cursor <token>\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"pageInfo.nextCursor from the last page, unchanged; pages forward only.\",\n\t\t\t},\n\t\t],\n\t),\n\tlegacyCommand(\"upload-quotation-attachment\", [\n\t\t\"quotation\",\n\t\t\"attachment\",\n\t\t\"upload\",\n\t]),\n\tlegacyCommand(\"cleanup-staged-quotation-attachments\", [\n\t\t\"quotation\",\n\t\t\"attachment\",\n\t\t\"staged\",\n\t\t\"cleanup\",\n\t]),\n\tlegacyCommand(\n\t\t\"create-quotation\",\n\t\t[\"quotation\", \"create\"],\n\t\t[],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"--payload\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Quotation JSON including lineAmounts for multiple selected budget items; see the payload format above. Set documentOnly: true with zero amounts for a $0 supplier document.\",\n\t\t\t\trequired: true,\n\t\t\t},\n\t\t],\n\t),\n\tlegacyCommand(\n\t\t\"update-quotation\",\n\t\t[\"quotation\", \"update\"],\n\t\t[],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"--payload\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Complete quotation JSON plus id, including lineAmounts for multiple selected budget items. Send documentOnly: true again when updating a document-only quotation.\",\n\t\t\t\trequired: true,\n\t\t\t},\n\t\t],\n\t),\n\tlegacyCommand(\"delete-quotation\", [\"quotation\", \"delete\"]),\n\tlegacyCommand(\"submit-quotation\", [\"quotation\", \"submit\"]),\n\tlegacyCommand(\"approve-quotation\", [\"quotation\", \"approve\"]),\n\tlegacyCommand(\"reject-quotation\", [\"quotation\", \"reject\"]),\n\tlegacyCommand(\"download-quotation-pdf\", [\"quotation\", \"pdf\", \"download\"]),\n\tlegacyCommand(\"check-customer-invoice-readiness\", [\n\t\t\"customer-invoice\",\n\t\t\"readiness\",\n\t\t\"check\",\n\t]),\n\tlegacyCommand(\"list-eligible-customer-invoice-budgets\", [\n\t\t\"customer-invoice\",\n\t\t\"eligible-budget\",\n\t\t\"list\",\n\t]),\n\tlegacyCommand(\"preview-customer-invoice-amount\", [\n\t\t\"customer-invoice\",\n\t\t\"amount\",\n\t\t\"preview\",\n\t]),\n\tlegacyCommand(\"list-available-qbo-customer-invoices\", [\n\t\t\"customer-invoice\",\n\t\t\"existing\",\n\t\t\"list\",\n\t]),\n\tlegacyCommand(\n\t\t\"list-customer-invoices\",\n\t\t[\"customer-invoice\", \"list\"],\n\t\t[],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"--limit <1-100>\",\n\t\t\t\tdescription: \"Rows per page. Output is { items, pageInfo }.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--cursor <token>\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"pageInfo.nextCursor (or previousCursor with --direction backward) from the last page, unchanged; keep the same filters and sort.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--direction <forward|backward>\",\n\t\t\t\tdescription: \"forward (default) or backward; backward needs --cursor.\",\n\t\t\t},\n\t\t],\n\t),\n\tlegacyCommand(\"count-customer-invoices\", [\"customer-invoice\", \"count\"]),\n\tlegacyCommand(\"get-customer-invoice\", [\"customer-invoice\", \"get\"]),\n\tlegacyCommand(\"get-customer-invoice-invoices\", [\n\t\t\"customer-invoice\",\n\t\t\"invoice\",\n\t\t\"list\",\n\t]),\n\tlegacyCommand(\n\t\t\"get-customer-invoice-lines\",\n\t\t[\"customer-invoice\", \"line\", \"list\"],\n\t\t[],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"--limit <1-100>\",\n\t\t\t\tdescription: \"Rows per page. Output is { items, pageInfo }.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--cursor <token>\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"pageInfo.nextCursor from the last page, unchanged; pages forward only.\",\n\t\t\t},\n\t\t],\n\t),\n\tlegacyCommand(\n\t\t\"get-customer-invoice-approvals\",\n\t\t[\"customer-invoice\", \"approval\", \"list\"],\n\t\t[],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"--limit <1-50>\",\n\t\t\t\tdescription: \"Rows per page. Output is { items, pageInfo }.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--cursor <token>\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"pageInfo.nextCursor from the last page, unchanged; pages forward only.\",\n\t\t\t},\n\t\t],\n\t),\n\tlegacyCommand(\n\t\t\"get-customer-invoice-history\",\n\t\t[\"customer-invoice\", \"history\", \"list\"],\n\t\t[],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"--limit <1-100>\",\n\t\t\t\tdescription: \"Rows per page. Output is { items, pageInfo }.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--cursor <token>\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"pageInfo.nextCursor from the last page, unchanged; pages forward only.\",\n\t\t\t},\n\t\t],\n\t),\n\tlegacyCommand(\"get-customer-invoice-payments\", [\n\t\t\"customer-invoice\",\n\t\t\"payments\",\n\t\t\"list\",\n\t]),\n\tlegacyCommand(\"get-customer-invoice-email-context\", [\n\t\t\"customer-invoice\",\n\t\t\"email-context\",\n\t\t\"get\",\n\t]),\n\tlegacyCommand(\"preview-qbo-customer-invoice\", [\n\t\t\"customer-invoice\",\n\t\t\"preview-qbo\",\n\t]),\n\tlegacyCommand(\"import-qbo-customer-invoice\", [\n\t\t\"customer-invoice\",\n\t\t\"import-qbo\",\n\t]),\n\tlegacyCommand(\"create-customer-invoice\", [\"customer-invoice\", \"create\"]),\n\tlegacyCommand(\"resubmit-customer-invoice\", [\"customer-invoice\", \"resubmit\"]),\n\tlegacyCommand(\"discard-customer-invoice\", [\"customer-invoice\", \"discard\"]),\n\tlegacyCommand(\"delete-customer-invoice\", [\"customer-invoice\", \"delete\"]),\n\tlegacyCommand(\"void-customer-invoice\", [\"customer-invoice\", \"void\"]),\n\tlegacyCommand(\"approve-customer-invoice\", [\"customer-invoice\", \"approve\"]),\n\tlegacyCommand(\"reject-customer-invoice\", [\"customer-invoice\", \"reject\"]),\n\tlegacyCommand(\"send-customer-invoice-to-contact-person\", [\n\t\t\"customer-invoice\",\n\t\t\"send\",\n\t]),\n\tlegacyCommand(\"download-customer-invoice-pdf\", [\n\t\t\"customer-invoice\",\n\t\t\"pdf\",\n\t\t\"download\",\n\t]),\n\tlegacyCommand(\"sync-customer-invoice\", [\"customer-invoice\", \"sync\"]),\n\tlegacyCommand(\"update-customer-invoice-details\", [\n\t\t\"customer-invoice\",\n\t\t\"details\",\n\t\t\"update\",\n\t]),\n\tlegacyCommand(\"update-customer-invoice-qbo-drift\", [\n\t\t\"customer-invoice\",\n\t\t\"qbo-drift\",\n\t\t\"resolve\",\n\t]),\n\tlegacyCommand(\"mark-customer-invoice-sent-externally\", [\n\t\t\"customer-invoice\",\n\t\t\"mark-sent-externally\",\n\t]),\n\tlegacyCommand(\n\t\t\"list-approvals\",\n\t\t[\"approval\", \"list\"],\n\t\t[\"get-pending-approvals\"],\n\t),\n\tlegacyCommand(\"approve-bill\", [\"bill\", \"approve\"]),\n\tlegacyCommand(\"reject-bill\", [\"bill\", \"reject\"]),\n\tlegacyCommand(\"approve-budget\", [\"budget\", \"approve\"]),\n\tlegacyCommand(\"reject-budget\", [\"budget\", \"reject\"]),\n\tlegacyCommand(\"approve-supplier\", [\"supplier\", \"approve\"]),\n\tlegacyCommand(\"reject-supplier\", [\"supplier\", \"reject\"]),\n\tlegacyCommand(\"get-supplier-details\", [\"supplier\", \"detail\", \"get\"]),\n\tlegacyCommand(\"get-supplier-overview\", [\"supplier\", \"overview\", \"get\"]),\n\tlegacyCommand(\"get-supplier-usage\", [\"supplier\", \"usage\", \"get\"]),\n\tlegacyCommand(\"get-supplier-items\", [\"supplier\", \"items\", \"get\"]),\n\tlegacyCommand(\n\t\t\"list-companies\",\n\t\t[\"company\", \"list\"],\n\t\t[],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"--name <text>\",\n\t\t\t\tdescription: \"Filter by company name substring.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--createdBy <userId>\",\n\t\t\t\tdescription: \"Filter by one creator user ID.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--createdByIds <csv>\",\n\t\t\t\tdescription: \"Filter by a comma-separated creator user ID list.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--active <true|false>\",\n\t\t\t\tdescription: \"Filter by active status; omit to include both states.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--sortBy <name|createdAt>\",\n\t\t\t\tdescription: \"Sort field (default createdAt).\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--sortDir <asc|desc>\",\n\t\t\t\tdescription: \"Sort direction (default desc).\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--limit <1-100>\",\n\t\t\t\tdescription: \"Bounded page size (default 20).\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--cursor <token>\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Opaque pageInfo cursor; pass nextCursor forward or previousCursor backward unchanged.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--direction <forward|backward>\",\n\t\t\t\tdescription: \"Use forward by default; backward requires --cursor.\",\n\t\t\t},\n\t\t],\n\t),\n\tlegacyCommand(\n\t\t\"count-companies\",\n\t\t[\"company\", \"count\"],\n\t\t[],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"--name <text>\",\n\t\t\t\tdescription: \"Filter by company name substring.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--createdBy <userId>\",\n\t\t\t\tdescription: \"Filter by one creator user ID.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--createdByIds <csv>\",\n\t\t\t\tdescription: \"Filter by a comma-separated creator user ID list.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--active <true|false>\",\n\t\t\t\tdescription: \"Filter by active status; facets omit this self-filter.\",\n\t\t\t},\n\t\t],\n\t),\n\tlegacyCommand(\"get-company\", [\"company\", \"get\"]),\n\tlegacyCommand(\n\t\t\"search-existing-companies\",\n\t\t[\"company\", \"search\"],\n\t\t[],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"--query\",\n\t\t\t\tdescription: \"Company name to search in BB and QuickBooks.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--limit\",\n\t\t\t\tdescription: \"Matches per page, 1–50 (default 8).\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--cursor\",\n\t\t\t\tdescription: \"pageInfo.nextCursor from the previous page, unchanged.\",\n\t\t\t},\n\t\t],\n\t),\n\tlegacyCommand(\n\t\t\"use-existing-company\",\n\t\t[\"company\", \"use\"],\n\t\t[],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"--companyId\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Existing BB company ID; combine with quickbooksId to explicitly connect both records.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--quickbooksId\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Existing QBO customer ID; alone imports or reuses its BB company.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--name\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"QuickBooks company name (from search-existing-companies); required for a QBO-only import.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--website\",\n\t\t\t\tdescription: \"Website only when missing from a QBO-only import.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--confirmDistinct\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Set true only when similar records do not represent this legal entity.\",\n\t\t\t},\n\t\t],\n\t),\n\tlegacyCommand(\n\t\t\"create-company\",\n\t\t[\"company\", \"create\"],\n\t\t[],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"--billingEmails\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"JSON email array (max 50) for new company invoice Cc defaults; reused companies keep their saved defaults.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--confirmDistinct\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Set true to confirm a separate legal entity despite similar names.\",\n\t\t\t},\n\t\t],\n\t),\n\tlegacyCommand(\"update-company\", [\"company\", \"update\"]),\n\tlegacyCommand(\"get-company-quickbooks-sync-status\", [\n\t\t\"company\",\n\t\t\"sync\",\n\t\t\"status\",\n\t]),\n\tlegacyCommand(\"delete-company\", [\"company\", \"delete\"]),\n\tlegacyCommand(\n\t\t\"list-projects\",\n\t\t[\"project\", \"list\"],\n\t\t[],\n\t\t[\n\t\t\t{ name: \"--companyId <id>\", description: \"Filter by company ID.\" },\n\t\t\t{\n\t\t\t\tname: \"--name <text>\",\n\t\t\t\tdescription: \"Filter by project name substring.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--status <status|ALL>\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Legacy single-status filter; use --statuses for multiple statuses.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--statuses <csv>\",\n\t\t\t\tdescription: \"Filter by a comma-separated project status list.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--active <true|false>\",\n\t\t\t\tdescription: \"Filter by active status; omit to include both states.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--wonFrom <iso>\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Only projects marked WON on or after this ISO date or datetime (UTC).\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--wonTo <iso>\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Only projects marked WON on or before this ISO date (inclusive) or datetime (UTC).\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--wonWithinDays <1-3650>\",\n\t\t\t\tdescription: \"Only projects marked WON in the last N days.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--limit <1-100>\",\n\t\t\t\tdescription: \"Bounded page size (default 20).\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--cursor <token>\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Opaque pageInfo cursor; pass nextCursor forward or previousCursor backward unchanged.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--direction <forward|backward>\",\n\t\t\t\tdescription: \"Use forward by default; backward requires --cursor.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--sortBy <name|createdAt|status|companyName|wonAt>\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Sort field (default createdAt); wonAt puts unwon projects last.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--sortDir <asc|desc>\",\n\t\t\t\tdescription: \"Sort direction (default desc).\",\n\t\t\t},\n\t\t],\n\t),\n\tlegacyCommand(\n\t\t\"count-projects\",\n\t\t[\"project\", \"count\"],\n\t\t[],\n\t\t[\n\t\t\t{ name: \"--companyId <id>\", description: \"Filter by company ID.\" },\n\t\t\t{\n\t\t\t\tname: \"--name <text>\",\n\t\t\t\tdescription: \"Filter by project name substring.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--status <status|ALL>\",\n\t\t\t\tdescription: \"Legacy single-status filter.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--statuses <csv>\",\n\t\t\t\tdescription: \"Filter by a comma-separated project status list.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--active <true|false>\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Filter by active status; facets exclude this self-filter.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--wonFrom <iso>\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Only projects marked WON on or after this ISO date or datetime (UTC).\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--wonTo <iso>\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Only projects marked WON on or before this ISO date (inclusive) or datetime (UTC).\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--wonWithinDays <1-3650>\",\n\t\t\t\tdescription: \"Only projects marked WON in the last N days.\",\n\t\t\t},\n\t\t],\n\t),\n\tlegacyCommand(\n\t\t\"list-project-hubs\",\n\t\t[\"project\", \"hub\", \"list\"],\n\t\t[],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"--q\",\n\t\t\t\tdescription: \"Search project and company names.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--status\",\n\t\t\t\tdescription: \"Filter by comma-separated project statuses.\",\n\t\t\t},\n\t\t\t{ name: \"--limit\", description: \"Page size, 1-100 (default 20).\" },\n\t\t\t{\n\t\t\t\tname: \"--cursor\",\n\t\t\t\tdescription: \"Opaque nextCursor/previousCursor from the last page.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--direction\",\n\t\t\t\tdescription: \"forward (default) or backward; backward needs --cursor.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--sortBy\",\n\t\t\t\tdescription: \"Sort by startDate, name, companyName, or status.\",\n\t\t\t},\n\t\t\t{ name: \"--sortDir\", description: \"Sort in asc or desc order.\" },\n\t\t],\n\t),\n\tlegacyCommand(\n\t\t\"count-project-hubs\",\n\t\t[\"project\", \"hub\", \"count\"],\n\t\t[],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"--q\",\n\t\t\t\tdescription: \"Search project and company names.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--status\",\n\t\t\t\tdescription: \"Filter by comma-separated project statuses.\",\n\t\t\t},\n\t\t],\n\t),\n\tlegacyCommand(\"get-project\", [\"project\", \"get\"]),\n\tlegacyCommand(\"get-project-hub-status\", [\"project\", \"hub\", \"status\"]),\n\tlegacyCommand(\"setup-project-hub\", [\"project\", \"hub\", \"setup\"]),\n\tlegacyCommand(\"sync-project-hub-commercial-documents\", [\n\t\t\"project\",\n\t\t\"hub\",\n\t\t\"sync\",\n\t]),\n\tlegacyCommand(\"create-project\", [\"project\", \"create\"]),\n\tlegacyCommand(\"update-project\", [\"project\", \"update\"]),\n\tlegacyCommand(\"delete-project\", [\"project\", \"delete\"]),\n\tlegacyCommand(\"check-project-reconciliation\", [\n\t\t\"project\",\n\t\t\"reconciliation\",\n\t\t\"check\",\n\t]),\n\tlegacyCommand(\"reconcile-project\", [\"project\", \"reconcile\"]),\n\tlegacyCommand(\"complete-project\", [\"project\", \"complete\"]),\n\tlegacyCommand(\"import-qbo-project\", [\"project\", \"quickbooks\", \"import\"]),\n\tlegacyCommand(\"update-project-status\", [\"project\", \"status\", \"update\"]),\n\tlegacyCommand(\"list-contacts\", [\"contact\", \"list\"]),\n\tlegacyCommand(\"create-contact-person\", [\"contact\", \"create\"]),\n\tlegacyCommand(\"update-contact-person\", [\"contact\", \"update\"]),\n\tlegacyCommand(\n\t\t\"list-suppliers\",\n\t\t[\"supplier\", \"list\"],\n\t\t[],\n\t\t[\n\t\t\t{ name: \"--name <text>\", description: \"Filter supplier name or email.\" },\n\t\t\t{ name: \"--createdBy <csv>\", description: \"Filter by creator IDs.\" },\n\t\t\t{\n\t\t\t\tname: \"--gstRegistered <true|false>\",\n\t\t\t\tdescription: \"Filter GST registration.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--status <csv>\",\n\t\t\t\tdescription: \"Filter approval statuses; ALL means no status filter.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--supplierTags <csv>\",\n\t\t\t\tdescription: \"Filter by supplier tag IDs.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--active <true|false>\",\n\t\t\t\tdescription: \"Active by default; false selects archived.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--limit <1-100>\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Bounded page size (default 10). Retired page/perPage flags are rejected.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--cursor <token>\",\n\t\t\t\tdescription: \"Opaque nextCursor or previousCursor from items/pageInfo.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--direction <forward|backward>\",\n\t\t\t\tdescription: \"Forward by default; backward requires a cursor.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--sortBy <field>\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"name, email, phone, gstRegistered, status, active, createdAt or updatedAt.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--sortDir <asc|desc>\",\n\t\t\t\tdescription: \"Descending createdAt by default.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--sort <json>\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Ordered {id,desc} array for multi-column sorting; cannot combine with sortBy/sortDir.\",\n\t\t\t},\n\t\t],\n\t),\n\tlegacyCommand(\n\t\t\"count-suppliers\",\n\t\t[\"supplier\", \"count\"],\n\t\t[],\n\t\t[\n\t\t\t{ name: \"--name <text>\", description: \"Filter supplier name or email.\" },\n\t\t\t{ name: \"--createdBy <csv>\", description: \"Filter by creator IDs.\" },\n\t\t\t{\n\t\t\t\tname: \"--gstRegistered <true|false>\",\n\t\t\t\tdescription: \"Filter GST registration.\",\n\t\t\t},\n\t\t\t{ name: \"--status <csv>\", description: \"Filter approval statuses.\" },\n\t\t\t{\n\t\t\t\tname: \"--supplierTags <csv>\",\n\t\t\t\tdescription: \"Filter by supplier tag IDs.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--active <true|false>\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Active by default; false selects archived. No pagination/sort flags.\",\n\t\t\t},\n\t\t],\n\t),\n\tlegacyCommand(\"create-supplier\", [\"supplier\", \"create\"]),\n\tlegacyCommand(\"update-supplier\", [\"supplier\", \"update\"]),\n\tlegacyCommand(\"delete-suppliers\", [\"supplier\", \"delete\"]),\n\tlegacyCommand(\"reactivate-suppliers\", [\"supplier\", \"reactivate\"]),\n\tlegacyCommand(\"create-certification\", [\n\t\t\"supplier\",\n\t\t\"certification\",\n\t\t\"create\",\n\t]),\n\tlegacyCommand(\"create-payment-method\", [\n\t\t\"supplier\",\n\t\t\"payment-method\",\n\t\t\"create\",\n\t]),\n\tlegacyCommand(\"create-supplier-role\", [\"supplier\", \"role\", \"create\"]),\n\tlegacyCommand(\"create-supplier-tag\", [\"supplier\", \"tag\", \"create\"]),\n\tlegacyCommand(\n\t\t\"get-supplier-analytics\",\n\t\t[\"supplier\", \"analytics\", \"get\"],\n\t\t[],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"--limit <1-100>\",\n\t\t\t\tdescription: \"Rows per page. Output is { items, pageInfo }.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--cursor <token>\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"pageInfo.nextCursor (or previousCursor with --direction backward) from the last page, unchanged; keep the same filters and sort.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--direction <forward|backward>\",\n\t\t\t\tdescription: \"forward (default) or backward; backward needs --cursor.\",\n\t\t\t},\n\t\t],\n\t),\n\tlegacyCommand(\"count-supplier-analytics\", [\"supplier\", \"analytics\", \"count\"]),\n\tlegacyCommand(\n\t\t\"list-items\",\n\t\t[\"item\", \"list\"],\n\t\t[],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"--limit <1-100>\",\n\t\t\t\tdescription: \"Rows per page. Output is { items, pageInfo }.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--cursor <token>\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"pageInfo.nextCursor (or previousCursor with --direction backward) from the last page, unchanged; keep the same filters and sort.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--direction <forward|backward>\",\n\t\t\t\tdescription: \"forward (default) or backward; backward needs --cursor.\",\n\t\t\t},\n\t\t],\n\t),\n\tlegacyCommand(\"count-items\", [\"item\", \"count\"]),\n\tlegacyCommand(\"get-item\", [\"item\", \"get\"]),\n\tlegacyCommand(\"get-item-quickbooks-sync-status\", [\"item\", \"sync\", \"status\"]),\n\tlegacyCommand(\"create-item\", [\"item\", \"create\"]),\n\tlegacyCommand(\"update-item\", [\"item\", \"update\"]),\n\tlegacyCommand(\"archive-items\", [\"item\", \"archive\"]),\n\tlegacyCommand(\"delete-item\", [\"item\", \"delete\"]),\n\tlegacyCommand(\n\t\t\"list-item-categories\",\n\t\t[\"item\", \"category\", \"list\"],\n\t\t[],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"--limit <1-100>\",\n\t\t\t\tdescription: \"Rows per page. Output is { items, pageInfo }.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--cursor <token>\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"pageInfo.nextCursor (or previousCursor with --direction backward) from the last page, unchanged; keep the same filters and sort.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--direction <forward|backward>\",\n\t\t\t\tdescription: \"forward (default) or backward; backward needs --cursor.\",\n\t\t\t},\n\t\t],\n\t),\n\tlegacyCommand(\"count-item-categories\", [\"item\", \"category\", \"count\"]),\n\tlegacyCommand(\"create-item-category\", [\"item\", \"category\", \"create\"]),\n\tlegacyCommand(\"update-item-category\", [\"item\", \"category\", \"update\"]),\n\tlegacyCommand(\"delete-item-categories\", [\"item\", \"category\", \"delete\"]),\n\tlegacyCommand(\n\t\t\"list-users\",\n\t\t[\"user\", \"list\"],\n\t\t[],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"--q <text>\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Search user names and emails (name A–Z). A bare --q is rejected; use -q/--quiet to hide logs.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--projectTeamOnly <true|false>\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"true lists only active @getout.sg users, the only accounts accepted as Inside Sales, Business Development or Project Manager.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--limit <1-100>\",\n\t\t\t\tdescription: \"Rows per page. Output is { items, pageInfo }.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--cursor <token>\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"pageInfo.nextCursor from the last page, unchanged; pages forward only.\",\n\t\t\t},\n\t\t],\n\t),\n\tlegacyCommand(\"count-users\", [\"user\", \"count\"]),\n\tlegacyCommand(\"create-user\", [\"user\", \"create\"]),\n\tlegacyCommand(\"create-api-key\", [\"user\", \"api-key\", \"create\"]),\n\tlegacyCommand(\n\t\t\"list-api-keys\",\n\t\t[\"user\", \"api-key\", \"list\"],\n\t\t[],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"--limit <1-100>\",\n\t\t\t\tdescription: \"Rows per page. Output is { items, pageInfo }.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--cursor <token>\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"pageInfo.nextCursor from the last page, unchanged; pages forward only.\",\n\t\t\t},\n\t\t],\n\t),\n\tlegacyCommand(\"revoke-api-key\", [\"user\", \"api-key\", \"revoke\"]),\n\tlegacyCommand(\"get-user-performance\", [\"user\", \"performance\", \"get\"]),\n\tlegacyCommand(\"get-dashboard\", [\"dashboard\", \"get\"]),\n\tlegacyCommand(\"get-monthly-metrics\", [\"dashboard\", \"monthly-metrics\", \"get\"]),\n\tlegacyCommand(\"get-system-overview\", [\"dashboard\", \"system-overview\", \"get\"]),\n\tlegacyCommand(\"get-estimate-performance\", [\n\t\t\"dashboard\",\n\t\t\"estimate-performance\",\n\t\t\"get\",\n\t]),\n\tlegacyCommand(\"get-financial-overview\", [\n\t\t\"dashboard\",\n\t\t\"financial-overview\",\n\t\t\"get\",\n\t]),\n\tlegacyCommand(\n\t\t\"get-recent-errors\",\n\t\t[\"error\", \"recent\", \"list\"],\n\t\t[],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"--cursor <token>\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Pass a returned pageInfo boundary unchanged, with the same filters.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--direction <direction>\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"forward (default) uses nextCursor; backward uses previousCursor.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--limit <number>\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"1–100 rows (default 10). Returns items and pageInfo, without a total.\",\n\t\t\t},\n\t\t\t{ name: \"--severity <severity>\", description: \"Error severity or ALL.\" },\n\t\t\t{ name: \"--status <status>\", description: \"Error status or ALL.\" },\n\t\t\t{\n\t\t\t\tname: \"--timeFrame <period>\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"all_time (default), last_30_days, last_3_months, last_6_months or last_1_year.\",\n\t\t\t},\n\t\t],\n\t),\n\tlegacyCommand(\n\t\t\"count-errors\",\n\t\t[\"error\", \"recent\", \"count\"],\n\t\t[],\n\t\t[\n\t\t\t{ name: \"--severity <severity>\", description: \"Error severity or ALL.\" },\n\t\t\t{ name: \"--status <status>\", description: \"Error status or ALL.\" },\n\t\t\t{\n\t\t\t\tname: \"--timeFrame <period>\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Same filters as error recent list; returns independent totalCount.\",\n\t\t\t},\n\t\t],\n\t),\n\tlegacyCommand(\"get-error\", [\"error\", \"get\"]),\n\tlegacyCommand(\"get-error-metrics\", [\"error\", \"metrics\", \"get\"]),\n\tlegacyCommand(\n\t\t\"list-integration-operations\",\n\t\t[\"integration\", \"operation\", \"list\"],\n\t\t[],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"--limit <1-100>\",\n\t\t\t\tdescription: \"Rows per page. Output is { items, pageInfo }.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--cursor <token>\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"pageInfo.nextCursor (or previousCursor with --direction backward) from the last page, unchanged; keep the same filters and sort.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--direction <forward|backward>\",\n\t\t\t\tdescription: \"forward (default) or backward; backward needs --cursor.\",\n\t\t\t},\n\t\t],\n\t),\n\tlegacyCommand(\"count-integration-operations\", [\n\t\t\"integration\",\n\t\t\"operation\",\n\t\t\"count\",\n\t]),\n\tlegacyCommand(\"get-integration-operation\", [\n\t\t\"integration\",\n\t\t\"operation\",\n\t\t\"get\",\n\t]),\n\tlegacyCommand(\"retry-integration-operation\", [\n\t\t\"integration\",\n\t\t\"operation\",\n\t\t\"retry\",\n\t]),\n\tlegacyCommand(\"reconcile-resource-operation\", [\n\t\t\"integration\",\n\t\t\"operation\",\n\t\t\"reconcile-resource\",\n\t]),\n\tlegacyCommand(\"list-webhook-event-types\", [\"webhook\", \"event-type\", \"list\"]),\n\tlegacyCommand(\"list-webhook-endpoints\", [\"webhook\", \"endpoint\", \"list\"]),\n\tlegacyCommand(\"get-webhook-endpoint\", [\"webhook\", \"endpoint\", \"get\"]),\n\tlegacyCommand(\"create-webhook-endpoint\", [\"webhook\", \"endpoint\", \"create\"]),\n\tlegacyCommand(\"update-webhook-endpoint\", [\"webhook\", \"endpoint\", \"update\"]),\n\tlegacyCommand(\"delete-webhook-endpoint\", [\"webhook\", \"endpoint\", \"delete\"]),\n\tlegacyCommand(\"rotate-webhook-secret\", [\"webhook\", \"secret\", \"rotate\"]),\n\tlegacyCommand(\"send-webhook-test-event\", [\"webhook\", \"endpoint\", \"test\"]),\n\tlegacyCommand(\n\t\t\"list-webhook-deliveries\",\n\t\t[\"webhook\", \"delivery\", \"list\"],\n\t\t[],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"--endpointId <id>\",\n\t\t\t\tdescription: \"Only deliveries to this endpoint.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--status <PENDING|SUCCEEDED|FAILED,...>\",\n\t\t\t\tdescription: \"Comma-separated delivery statuses.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--eventType <type>\",\n\t\t\t\tdescription: \"Exact event type, e.g. bill.approved.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--limit <n>\",\n\t\t\t\tdescription: \"Rows per cursor page (1..100; default 20).\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--cursor <token>\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Opaque token from pageInfo.nextCursor or pageInfo.previousCursor; bound to the same filters.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--direction <value>\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"forward or backward (default forward; backward requires cursor).\",\n\t\t\t},\n\t\t],\n\t),\n\tlegacyCommand(\"get-webhook-delivery\", [\"webhook\", \"delivery\", \"get\"]),\n\tlegacyCommand(\"replay-webhook-delivery\", [\"webhook\", \"delivery\", \"replay\"]),\n\tlegacyCommand(\n\t\t\"list-inbound-sources\",\n\t\t[\"inbound\", \"source\", \"list\"],\n\t\t[],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"--limit <n>\",\n\t\t\t\tdescription: \"Rows per cursor page (1..100; default 25).\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--cursor <token>\",\n\t\t\t\tdescription: \"Opaque source continuation token returned by pageInfo.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--direction <value>\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"forward or backward (default forward; backward requires cursor).\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--search <text>\",\n\t\t\t\tdescription: \"Search source name or Typeform form ID.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--processingEnabled <boolean>\",\n\t\t\t\tdescription: \"Filter processing enabled state.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--processingMode <mode>\",\n\t\t\t\tdescription: \"ACTIVE, COLLECT_ONLY or SHADOW.\",\n\t\t\t},\n\t\t],\n\t),\n\tlegacyCommand(\n\t\t\"count-inbound-sources\",\n\t\t[\"inbound\", \"source\", \"count\"],\n\t\t[],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"--search <text>\",\n\t\t\t\tdescription: \"Search source name or Typeform form ID.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--processingEnabled <boolean>\",\n\t\t\t\tdescription: \"Filter processing enabled state.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--processingMode <mode>\",\n\t\t\t\tdescription: \"ACTIVE, COLLECT_ONLY or SHADOW.\",\n\t\t\t},\n\t\t],\n\t),\n\tlegacyCommand(\"create-inbound-source\", [\"inbound\", \"source\", \"create\"]),\n\tlegacyCommand(\"get-inbound-source\", [\"inbound\", \"source\", \"get\"]),\n\tlegacyCommand(\"update-inbound-source\", [\"inbound\", \"source\", \"update\"]),\n\tlegacyCommand(\n\t\t\"list-inbound-submissions\",\n\t\t[\"inbound\", \"submission\", \"list\"],\n\t\t[],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"--limit <number>\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Page size from 1 to 100 (default 25). Returns submissions, hasMore and nextCursor; no total.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--cursor <token>\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Pass the previous response's nextCursor unchanged. Omit for newest submissions. Replaces --page/--perPage.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"--sourceId <id>\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Filter submissions to this source; keep the same filter while following cursors.\",\n\t\t\t},\n\t\t],\n\t),\n\tlegacyCommand(\n\t\t\"count-inbound-submissions\",\n\t\t[\"inbound\", \"submission\", \"count\"],\n\t\t[],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"--sourceId <id>\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Optional source filter. Returns an independently calculated exact totalCount, not a list snapshot.\",\n\t\t\t},\n\t\t],\n\t),\n\tlegacyCommand(\"get-inbound-submission\", [\"inbound\", \"submission\", \"get\"]),\n\tlegacyCommand(\"save-inbound-mapping\", [\"inbound\", \"mapping\", \"save\"]),\n\tlegacyCommand(\"save-inbound-automation-config\", [\n\t\t\"inbound\",\n\t\t\"automation\",\n\t\t\"save\",\n\t]),\n\tlegacyCommand(\"update-inbound-processing\", [\n\t\t\"inbound\",\n\t\t\"processing\",\n\t\t\"update\",\n\t]),\n\tlegacyCommand(\"get-approved-budgets\", [\"budget\", \"approved\", \"list\"]),\n\tlegacyCommand(\"get-budget-category-benchmarks\", [\n\t\t\"budget\",\n\t\t\"category\",\n\t\t\"benchmark\",\n\t\t\"get\",\n\t]),\n\tlegacyCommand(\"get-item-pricing-history\", [\n\t\t\"item\",\n\t\t\"pricing-history\",\n\t\t\"list\",\n\t]),\n\tlegacyCommand(\"get-supplier-pricing-history\", [\n\t\t\"supplier\",\n\t\t\"pricing-history\",\n\t\t\"list\",\n\t]),\n] as const satisfies readonly CommandDefinition[];\n\nconst normalizeToken = (value: string): string => value.replaceAll(\"_\", \"-\");\n\nconst normalizedPath = (path: readonly string[]): readonly string[] =>\n\tpath.map(normalizeToken);\n\nconst assertRegistry = (commands: readonly CommandDefinition[]): void => {\n\tconst paths = new Set<string>();\n\tconst aliases = new Set<string>();\n\tfor (const command of commands) {\n\t\tconst path = command.path.join(\" \");\n\t\tif (paths.has(path))\n\t\t\tthrow new Error(`Duplicate canonical command path: ${path}`);\n\t\tpaths.add(path);\n\t\tconst commandAliases = new Set<string>();\n\t\tfor (const alias of command.legacyAliases) {\n\t\t\tconst normalizedAlias = normalizeToken(alias);\n\t\t\tif (commandAliases.has(normalizedAlias)) continue;\n\t\t\tcommandAliases.add(normalizedAlias);\n\t\t\tif (aliases.has(normalizedAlias)) {\n\t\t\t\tthrow new Error(`Duplicate legacy command alias: ${alias}`);\n\t\t\t}\n\t\t\taliases.add(normalizedAlias);\n\t\t}\n\t}\n};\n\nassertRegistry(registry);\n\nexport const commandRegistry: readonly CommandDefinition[] = registry;\n\nexport const resolveCommand = (\n\targv: readonly string[],\n): ResolvedCommand | undefined => {\n\tconst normalizedArgv = argv.map(normalizeToken);\n\tconst canonical = [...commandRegistry]\n\t\t.sort((left, right) => right.path.length - left.path.length)\n\t\t.find((command) => {\n\t\t\tconst path = normalizedPath(command.path);\n\t\t\treturn path.every((segment, index) => normalizedArgv[index] === segment);\n\t\t});\n\n\tif (canonical) {\n\t\treturn {\n\t\t\tcommand: canonical,\n\t\t\targv: argv.slice(canonical.path.length),\n\t\t\tinvokedAs: argv.slice(0, canonical.path.length),\n\t\t\tisLegacyAlias: false,\n\t\t};\n\t}\n\n\tconst rawAlias = argv[0];\n\tif (!rawAlias) return undefined;\n\tconst normalizedAlias = normalizeToken(rawAlias);\n\tconst legacy = commandRegistry.find((command) =>\n\t\tcommand.legacyAliases.some(\n\t\t\t(alias) => normalizeToken(alias) === normalizedAlias,\n\t\t),\n\t);\n\tif (!legacy) return undefined;\n\treturn {\n\t\tcommand: legacy,\n\t\targv: argv.slice(1),\n\t\tinvokedAs: [rawAlias],\n\t\tisLegacyAlias: true,\n\t};\n};\n\nexport const createCommandManifest = (): readonly CommandManifestEntry[] =>\n\tcommandRegistry.map((command) => ({\n\t\tpath: command.path,\n\t\tlegacyAliases: command.legacyAliases,\n\t\tsummary: command.summary,\n\t\tglobalOptions: command.options,\n\t\targumentMode: \"legacyTarget\" in command ? \"legacy-passthrough\" : \"typed\",\n\t\teffects: command.effects,\n\t\t...(\"legacyTarget\" in command\n\t\t\t? { legacyTarget: command.legacyTarget }\n\t\t\t: {}),\n\t}));\n\nconst updateBeforeUse =\n\t\"First step before each task: update to the latest published release with 'bun add --global @go-labs-sg/bb@latest', then run 'bb version' and 'bb --help' before using commands. Update once per task. If updating fails, stop and report it. Preserve an explicitly requested pinned or development/staging version.\";\n\nexport const createHumanHelp = (command?: CommandDefinition): string => {\n\tif (command) {\n\t\treturn [\n\t\t\tupdateBeforeUse,\n\t\t\t\"\",\n\t\t\t`Usage: bb ${command.path.join(\" \")} [options] [args]`,\n\t\t\t\"\",\n\t\t\tcommand.summary,\n\t\t\t\"\",\n\t\t\t`Legacy aliases: ${command.legacyAliases.join(\", \")}`,\n\t\t\t\"\",\n\t\t\t\"Options\",\n\t\t\t...command.options.map(\n\t\t\t\t(option) => ` ${option.name}\\n ${option.description}`,\n\t\t\t),\n\t\t\t\"\",\n\t\t\t...formatPayloadHelp(command.legacyTarget ?? \"\"),\n\t\t\t\"Use `bb help --legacy` for additional command arguments.\",\n\t\t].join(\"\\n\");\n\t}\n\tconst lines = commandRegistry.map((command) => {\n\t\tconst canonical = `bb ${command.path.join(\" \")}`;\n\t\tconst aliases = command.legacyAliases\n\t\t\t.filter((alias) => alias.includes(\"-\"))\n\t\t\t.map((alias) => `bb ${alias}`)\n\t\t\t.join(\", \");\n\t\treturn ` ${canonical}\\n ${command.summary}${aliases ? ` Legacy: ${aliases}.` : \"\"}`;\n\t});\n\treturn [\n\t\t\"bb — Budget Builder CLI\",\n\t\t\"\",\n\t\tupdateBeforeUse,\n\t\t\"\",\n\t\t\"Usage: bb <resource> <operation> [options] [args]\",\n\t\t\"\",\n\t\t\"Global options\",\n\t\t...globalCommandOptions.map(\n\t\t\t(option) => ` ${option.name}\\n ${option.description}`,\n\t\t),\n\t\t\"\",\n\t\t\"Canonical commands\",\n\t\t...lines,\n\t\t\"\",\n\t\t\"Use `bb completion <shell>` to generate shell completion scripts.\",\n\t].join(\"\\n\");\n};\n\nconst completionWords = (): string[] => {\n\tconst words = new Set<string>();\n\tfor (const command of commandRegistry) {\n\t\tfor (const segment of command.path) words.add(segment);\n\t\tfor (const alias of command.legacyAliases) words.add(alias);\n\t}\n\twords.add(\"help\");\n\twords.add(\"version\");\n\twords.add(\"completion\");\n\treturn [...words].sort();\n};\n\nexport const createCompletionScript = (shell: CompletionShell): string => {\n\tconst words = completionWords().join(\" \");\n\tswitch (shell) {\n\t\tcase \"bash\":\n\t\t\treturn `# bash completion for bb\\n_bb() {\\n COMPREPLY=( $(compgen -W '${words}' -- \"${\"$\"}{COMP_WORDS[COMP_CWORD]}\") )\\n}\\ncomplete -F _bb bb\\n`;\n\t\tcase \"zsh\":\n\t\t\treturn `#compdef bb\\n_bb() {\\n local -a commands\\n commands=(${words})\\n _describe 'bb command' commands\\n}\\ncompdef _bb bb\\n`;\n\t\tcase \"fish\":\n\t\t\treturn completionWords()\n\t\t\t\t.map((word) => `complete -c bb -f -a '${word}'`)\n\t\t\t\t.join(\"\\n\")\n\t\t\t\t.concat(\"\\n\");\n\t\tcase \"powershell\":\n\t\t\treturn `Register-ArgumentCompleter -Native -CommandName bb -ScriptBlock {\\n param($wordToComplete)\\n '${words}'.Split(' ') | Where-Object { $_ -like \"$wordToComplete*\" }\\n}\\n`;\n\t}\n};\n", "#!/usr/bin/env bun\nimport \"@go-labs-sg/bb/load-env\";\nimport { assertBunRuntime } from \"@go-labs/cli-auth/client\";\nimport { runCli } from \"@go-labs-sg/bb/cli\";\n\nexport { runCli } from \"@go-labs-sg/bb/cli\";\n\nif (import.meta.main) {\n\tassertBunRuntime();\n\tprocess.exitCode = await runCli();\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;AAAA,MAAI,IAAEA,QAAA,CAAC,GAAE,MAAI,MAAI;AAAC,QAAG;AAAC,aAAO,KAAG,GAAG,IAAE,EAAC,SAAQ,CAAC,EAAC,GAAG,SAAQ,CAAC,GAAE,EAAE;IAAA,SAAc,GAAE;AAAC,YAAM,IAAE,GAAE;IAAA;EAAA,GAArF,GAAA,GAA6F,IAAE,EAAE,CAAC,GAAE,MAAI;AAAC,aAAS,EAAE,GAAE;AAAC,aAAO,OAAO,KAAG,WAAS,CAAC,CAAC,SAAQ,KAAI,MAAK,OAAM,EAAE,EAAE,SAAS,EAAE,YAAY,CAAC,IAAE,CAAC,CAAC;IAAA;AAAxF,oBAAAA,QAAA,GAAA,GAAA;AAA0F,aAAS,EAAE,IAAE,QAAQ,KAAI;AAAC,UAAI,IAAE,CAAC;AAAE,eAAQ,KAAI,CAAC,YAAW,QAAO,SAAQ,SAAQ,YAAW,MAAM,GAAE;AAAC,YAAI,IAAE,EAAE,UAAU,OAAA,CAAA,CAAA,KAAM,OAAK,EAAE,UAAU,OAAA,CAAA,CAAA,IAAK,EAAE,iBAAiB,OAAA,CAAA,CAAA;AAAK,aAAG,SAAO,EAAE,EAAE,YAAY,CAAA,IAAG,MAAI,cAAY,MAAI,SAAO,IAAE,EAAE,CAAC;MAAE;AAAC,aAAO;IAAA;AAA1O,oBAAAA,QAAA,GAAA,GAAA,GAA4O,EAAE,UAAQ,EAAC,cAAa,GAAE,gBAAe,EAAC;EAAA,CAAE,GAAM,IA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EACxB,UACC,+HACD,UAAU,mBACV,SACC,wJACF,GACA,kBAAkB,EACjB,UAAU,iDACV,UACC,oJACD,SACC,qIACF,GACA,kBAAkB,EACjB,UACC,+LACD,UACC,6eACD,SACC,+PACF,GACA,mBAAmB,EAClB,UACC,0IACD,UACC,4HACD,SACC,0LACF,GACA,mBAAmB,EAClB,UACC,sJACD,UACC,4HACD,SACC,+MACF,GACA,4BAA4B,EAC3B,UACC,iGACD,UAAU,QACV,SACC,0GACF,GACA,0BAA0B,EACzB,UACC,sHACD,UAAU,QACV,SACC,+GACF,GACA,mCAAmC,EAClC,UACC,+IACD,UAAU,6BACV,SACC,6MACF,GACA,eAAe,EACd,UACC,sQACD,UACC,kOACD,SACC,+MACF,GACA,eAAe,EACd,UACC,+IACD,UACC,+MACD,SACC,gOACF,GACA,2BAA2B,EAC1B,UAAU,kEACV,UACC,yNACD,SACC,mIACF,GACA,wBAAwB,EACvB,UACC,8GACD,UAAU,8CACV,SAAS,sCACV,GACA,gCAAgC,EAC/B,UACC,4GACD,UAAU,QACV,SACC,kKACF,GACA,oBAAoB,EACnB,UACC,2KACD,UACC,2fACD,SACC,6PACF,GACA,oBAAoB,EACnB,UACC,iKACD,UACC,6QACD,SACC,mRACF,GACA,2BAA2B,EAC1B,UACC,oGACD,UACC,qJACD,SACC,uKACF,GACA,2CAA2C,EAC1C,UACC,+GACD,UACC,wJACD,SACC,gLACF,GACA,wBAAwB,EACvB,UACC,wJACD,UAAU,4DACV,SACC,oFACF,GACA,kCAAkC,EACjC,UACC,udACD,UACC,qSACD,SACC,2gBACF,EACD,GAEa,oBAAoBA,QAAC,aAA8B;AAC/D,QAAM,OAAO,YAAY,OAAA;AACzB,SAAK,OACE,CACN,mCACA,eAAe,OAAA,KAAK,QAAA,GACpB,eAAe,OAAA,KAAK,QAAA,GACpB,iBAAiB,OAAA,OAAA,EAAU,OAAA,YAAY,yBAAyB,cAAc,QAAQ,WAAW,eAAe,IAAI,gBAAgB,IAAA,cAAA,EAAiB,OAAA,KAAK,SAAA,GAAA,GAC1J,EACD,IAPkB,CAAC;AAOnB,GATgC,mBAAA,GCzHpB,uBAAuB,CACnC,EAAE,MAAM,UAAU,aAAa,8BAA8B,GAC7D,EAAE,MAAM,WAAW,aAAa,kCAAkC,GAClE,EAAE,MAAM,WAAW,aAAa,oCAAoC,GACpE,EACC,MAAM,aACN,aAAa,4CACd,GACA,EACC,MAAM,gBACN,aAAa,yDACd,GACA,EACC,MAAM,wBACN,aAAa,8DACd,GACA,EACC,MAAM,iBACN,aAAa,8CACd,GACA,EACC,MAAM,0BACN,aAAa,2DACd,GACA,EACC,MAAM,kBACN,aAAa,8CACd,GACA,EACC,MAAM,2BACN,aAAa,yDACd,CACD,GAEM,mBAAmB,CACxB,QACA,YACA,YACA,WACA,YACA,aACA,WACA,WACA,YACA,WACA,SACA,SACA,UACA,eACA,cACA,WACA,YACA,WACA,WACA,YACA,WACA,YACA,YACA,UACA,WACA,SACA,SACA,UACA,UACA,WACA,SACA,WACA,iBACA,WACA,OACD,GAEM,eAAe,oBAAI,IAAI,CAC5B,gBACA,kBACA,4BACA,oBACA,eACA,wBACA,0BACA,2BACA,mBACA,eACA,iBACA,2BACA,mBACA,uBACA,mCACA,2CACA,sBACA,iBACD,CAAC,GAEK,uBAAuB,oBAAI,IAAI,CACpC,mCACA,qCACA,gCACA,gBACA,4BACA,oBACA,oBACA,eACA,kBACA,wBACA,mBACA,2BACA,2BACA,eACA,wBACA,kBACA,mBACA,eACA,iBACA,kBACA,2BACA,eACA,kBACA,oBACA,4BACA,sBACA,kCACA,mBACA,qBACA,2BACA,wBACA,uBACA,0BACA,+BACA,qBACA,yCACA,yBACA,eACA,wBACA,kBACA,eACA,wBACA,kBACA,yBACA,mBACA,uBACD,CAAC,GAEK,wBAAwB,oBAAI,IAAI,CACrC,qCACA,gCACA,+BACA,wBACA,gBACA,4BACA,oBACA,eACA,2BACA,mBACA,2BACA,4BACA,0BACA,eACA,iBACA,2BACA,kCACA,mBACA,y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A,kLACD;EACA,CACC,oBACA,uHACD;EACA,CACC,iBACA,2vBACD;EACA,CACC,wBACA,4QACD;EACA,CACC,iCACA,8HACD;EACA,CACC,8BACA,yMACD;EACA,CACC,kCACA,6LACD;EACA,CACC,gCACA,wMACD;EACA,CACC,iCACA,iNACD;EACA,CACC,4BACA,4LACD;EACA,CACC,wBACA,wJACD;EACA,CACC,yBACA,6LACD;EACA,CACC,yBACA,2MACD;EACA,CACC,sBACA,oJACD;EACA,CACC,sBACA,sDACD;EACA,CACC,0BACA,mgBACD;EACA,CACC,iBACA,2LACD;EACA,CACC,eACA,wLACD;EACA,CACC,cACA,4cACD;EACA,CACC,0BACA,qmBACD;EACA,CACC,mBACA,keACD;EACA,CACC,cACA,kYACD;EACA,CACC,kBACA,+NACD;EACA,CACC,mBACA,6KACD;EACA,CACC,iBACA,4VACD;EACA,CACC,kBACA,4LACD;EACA,CACC,6BACA,4NACD;EACA,CACC,wBACA,unBACD;EACA,CACC,kBACA,4fACD;EACA,CACC,kBACA,uXACD;EACA,CACC,mBACA,0fACD;EACA,CACC,gCACA,oIACD;EACA,CACC,mCACA,qIACD;EACA,CACC,wCACA,uGACD;EACA,CACC,6BACA,0PACD;EACA,CACC,2BACA,qNACD;EACA,CACC,+BACA,8LACD;EACA,CAAC,UAAU,mCAAmC;EAC9C,CACC,gBACA,iMACD;EACA,CACC,cACA,0JACD;EACA,CACC,wBACA,wKACD;EACA,CACC,wBACA,uNACD;EACA,CACC,wBACA,2MACD;EACA,CACC,yBACA,+DACD;EACA,CACC,2BACA,8NACD;EACA,CACC,+BACA,8JACD;EACA,CACC,gCACA,sJACD;EACA,CACC,eACA,gHACD;EACA,CACC,iBACA,kHACD;EACA,CACC,cACA,yHACD;EACA,CACC,oBACA,kIACD;EACA,CACC,sBACA,yHACD;EACA,CACC,eACA,81CACD;EACA,CACC,gCACA,4zBACD;EACA,CACC,yCACA,2UACD;EACA,CACC,kCACA,kkBACD;EACA,CACC,qCACA,2SACD;EACA,CACC,eACA,0rCACD;EACA,CACC,2BACA,u+BACD;EACA,CACC,oBACA,i2DACD;EACA,CACC,wCACA,gMACD;EACA,CACC,oBACA,itCACD;EACA,CACC,iCACA,iDACD;EACA,CACC,2CACA,wMACD;EACA,CACC,kBACA,oSACD;EACA,CACC,sCACA,6FACD;EACA,CACC,mCACA,kGACD;EACA,CACC,2BACA,qLACD;EACA,CACC,yBACA,mKACD;EACA,CACC,2BACA,uFACD;EACA,CACC,2BACA,wHACD;EACA,CACC,aACA,uLACD;EACA,CACC,wBACA,uHACD;EACA,CACC,4BACA,+EACD;EACA,CACC,gCACA,mQACD;EACA,CACC,6BACA,oMACD;EACA,CACC,+BACA,qQACD;AACD,CAAC,GAEK,aAAaA,QAAC,kBAAiC;AACpD,QAAM,UAAU,UAAU,IAAI,YAAY;AAC1C,SAAI,YAAY,SAAkB,UAC9B,aAAa,WAAW,OAAO,IAC3B,QAAQ,OAAA,aAAa,MAAM,CAAc,EAAE,WAAW,KAAK,GAAG,GAAA,GAAA,IAElE,aAAa,WAAW,MAAM,IAC1B,OAAO,OAAA,aAAa,MAAM,CAAa,EAAE,WAAW,KAAK,GAAG,GAAA,GAAA,IAE7D,GAAG,OAAA,UAAU,YAAY,GAAA,GAAA;AAAA,GATd,YAAA,GAYb,aAAaA,QAAA,CAClB,cACA,YACc,CACd,GAAG,IAAI,IACN,CAAC,cAAc,GAAG,OAAO,EAAE,QAAS,WAAU,CAC7C,OACA,MAAM,WAAW,KAAK,GAAG,CAC1B,CAAC,CACF,CACD,GAVmB,YAAA,GAYb,gBAAgBA,QAAA,CACrB,cACAE,OACA,UAA6B,CAAC,GAC9B,iBAA2C,CAAC,OACpB,EACxB,MAAAA,OACA,eAAe,WAAW,cAAc,OAAO,GAC/C,SAAS,WAAW,YAAY,GAChC,SAAS,CAAC,GAAG,sBAAsB,GAAG,cAAc,GACpD,SAAS,WAAW,YAAY,GAChC,aACD,IAZsB,eAAA,GAchB,yBAAyB,CAC9B,EACC,MAAM,2BACN,aACC,gEACF,GACA,EACC,MAAM,2BACN,aACC,mGACF,GACA,EACC,MAAM,yBACN,aACC,qEACF,CACD,GAEM,cAAcF,QAAA,CACnB,QACA,aACwB,EACxB,MAAM,CAAC,QAAQ,MAAM,GACrB,eAAe,CAAC,GAChB,SACA,SAAS,sBACT,SAAS,CAAC,GACV,MAAMA,QAAA,YAAY,aAAa,CAAC,IAA1B,MAAA,EACP,IAVoB,aAAA,GAYd,YAAW,CAChB,YACC,SACA,+DACD,GACA,YACC,UACA,+DACD,GACA,YACC,UACA,qEACD,GACA,cAAc,UAAU,CAAC,QAAQ,QAAQ,CAAC,GAC1C,cACC,gBACA,CAAC,UAAU,MAAM,GACjB,CAAC,GACD,CACC,EACC,MAAM,6BACN,aACC,oEACF,GACA,EACC,MAAM,mBACN,aAAa,gDACd,GACA,EACC,MAAM,oBACN,aACC,mIACF,GACA,EACC,MAAM,kCACN,aAAa,0DACd,CACD,CACD,GACA,cACC,iBACA,CAAC,UAAU,OAAO,GAClB,CAAC,GACD,CACC,EACC,MAAM,6BACN,aACC,oEACF,CACD,CACD,GACA,cACC,cACA,CAAC,UAAU,KAAK,GAChB,CAAC,GACD,CACC,EACC,MAAM,qBACN,aAAa,mDACd,CACD,CACD,GACA,cAAc,4BAA4B,CAAC,UAAU,cAAc,QAAQ,CAAC,GAC5E,cAAc,mBAAmB,CAAC,UAAU,OAAO,MAAM,CAAC,GAC1D,cACC,oBACA,CAAC,UAAU,QAAQ,MAAM,GACzB,CAAC,GACD,CACC,EACC,MAAM,qBACN,aAAa,mDACd,CACD,CACD,GACA,cACC,sBACA,CAAC,UAAU,UAAU,KAAK,GAC1B,CAAC,GACD,CACC,EACC,MAAM,qBACN,aAAa,mDACd,CACD,CACD,GACA,cACC,yBACA,CAAC,UAAU,YAAY,MAAM,GAC7B,CAAC,GACD,CACC,EACC,MAAM,cACN,aACC,qGACF,GACA,EACC,MAAM,mBACN,aAAa,gDACd,GACA,EACC,MAAM,oBACN,aACC,yEACF,CAC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EACA,EACC,MAAM,oBACN,aACC,mIACF;EACA,EACC,MAAM,kCACN,aAAa,0DACd;AACD,CACD,GACA,cAAc,oBAAoB,CAAC,aAAa,OAAO,CAAC,GACxD,cAAc,iBAAiB,CAAC,aAAa,KAAK,CAAC,GACnD,cACC,4BACA,CAAC,aAAa,aAAa,MAAM,GACjC,CAAC,GACD,CACC,EACC,MAAM,mBACN,aAAa,gDACd,GACA,EACC,MAAM,oBACN,aACC,yEACF,CACD,CACD,GACA,cAAc,+BAA+B,CAC5C,aACA,cACA,QACD,CAAC,GACD,cAAc,wCAAwC,CACrD,aACA,cACA,UACA,SACD,CAAC,GACD,cACC,oBACA,CAAC,aAAa,QAAQ,GACtB,CAAC,GACD,CACC,EACC,MAAM,aACN,aACC,+KACD,UAAU,GACX,CACD,CACD,GACA,cACC,oBACA,CAAC,aAAa,QAAQ,GACtB,CAAC,GACD,CACC,EACC,MAAM,aACN,aACC,qKACD,UAAU,GACX,CACD,CACD,GACA,cAAc,oBAAoB,CAAC,aAAa,QAAQ,CAAC,GACzD,cAAc,oBAAoB,CAAC,aAAa,QAAQ,CAAC,GACzD,cAAc,qBAAqB,CAAC,aAAa,SAAS,CAAC,GAC3D,cAAc,oBAAoB,CAAC,aAAa,QAAQ,CAAC,GACzD,cAAc,0BAA0B,CAAC,aAAa,OAAO,UAAU,CAAC,GACxE,cAAc,oCAAoC,CACjD,oBACA,aACA,OACD,CAAC,GACD,cAAc,0CAA0C,CACvD,oBACA,mBACA,MACD,CAAC,GACD,cAAc,mCAAmC,CAChD,oBACA,UACA,SACD,CAAC,GACD,cAAc,wCAAwC,CACrD,oBACA,YACA,MACD,CAAC,GACD,cACC,0BACA,CAAC,oBAAoB,MAAM,GAC3B,CAAC,GACD,CACC,EACC,MAAM,mBACN,aAAa,gDACd,GACA,EACC,MAAM,oBACN,aACC,mIACF,GACA,EACC,MAAM,kCACN,aAAa,0DACd,CACD,CACD,GACA,cAAc,2BAA2B,CAAC,oBAAoB,OAAO,CAAC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pB,CAAC,GACD,CACC,EACC,MAAM,WACN,aAAa,+CACd,GACA,EACC,MAAM,WACN,aAAa,2CACd,GACA,EACC,MAAM,YACN,aAAa,yDACd,CACD,CACD,GACA,cACC,wBACA,CAAC,WAAW,KAAK,GACjB,CAAC,GACD,CACC,EACC,MAAM,eACN,aACC,wFACF,GACA,EACC,MAAM,kBACN,aACC,oEACF,GACA,EACC,MAAM,UACN,aACC,4FACF,GACA,EACC,MAAM,aACN,aAAa,oDACd,GACA,EACC,MAAM,qBACN,aACC,yEACF,CACD,CACD,GACA,cACC,kBACA,CAAC,WAAW,QAAQ,GACpB,CAAC,GACD,CACC,EACC,MAAM,mBACN,aACC,6GACF,GACA,EACC,MAAM,qBACN,aACC,qEACF,CACD,CACD,GACA,cAAc,kBAAkB,CAAC,WAAW,QAAQ,CAAC,GACrD,cAAc,sCAAsC,CACnD,WACA,QACA,QACD,CAAC,GACD,cAAc,kBAAkB,CAAC,WAAW,QAAQ,CAAC,GACrD,cACC,iBACA,CAAC,WAAW,MAAM,GAClB,CAAC,GACD;EACC,EAAE,MAAM,oBAAoB,aAAa,wBAAwB;EACjE,EACC,MAAM,iBACN,aAAa,oCACd;EACA,EACC,MAAM,yBACN,aACC,qEACF;EACA,EACC,MAAM,oBACN,aAAa,mDACd;EACA,EACC,MAAM,yBACN,aAAa,wDACd;EACA,EACC,MAAM,mBACN,aACC,wEACF;EACA,EACC,MAAM,iBACN,aACC,qFACF;EACA,EACC,MAAM,4BACN,aAAa,+CACd;EACA,EACC,MAAM,mBACN,aAAa,kCACd;EACA,EACC,MAAM,oBACN,aACC,wFACF;EACA,EACC,MAAM,kCACN,aAAa,sDACd;EACA,EACC,MAAM,sDACN,aACC,kEACF;EACA,EACC,MAAM,wBACN,aAAa,iCACd;AACD,CACD,GACA,cACC,kBACA,CAAC,WAAW,OAAO,GACnB,CAAC,GACD,CACC,EAAE,MAAM,oBAAoB,aAAa,wBAAwB,GACjE,EACC,MAAM,iBACN,aAAa,oCACd,GAC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;EACN,aAAa;AACd,GACA,EACC,MAAM,oBACN,aAAa,yDACd,GACA,EACC,MAAM,uBACN,aACC,mEACF,GACA,EACC,MAAM,mBACN,aAAa,0CACd,GACA,EACC,MAAM,iCACN,aAAa,mCACd,GACA,EACC,MAAM,2BACN,aAAa,kCACd,CACD,CACD,GACA,cACC,yBACA,CAAC,WAAW,UAAU,OAAO,GAC7B,CAAC,GACD,CACC,EACC,MAAM,mBACN,aAAa,0CACd,GACA,EACC,MAAM,iCACN,aAAa,mCACd,GACA,EACC,MAAM,2BACN,aAAa,kCACd,CACD,CACD,GACA,cAAc,yBAAyB,CAAC,WAAW,UAAU,QAAQ,CAAC,GACtE,cAAc,sBAAsB,CAAC,WAAW,UAAU,KAAK,CAAC,GAChE,cAAc,yBAAyB,CAAC,WAAW,UAAU,QAAQ,CAAC,GACtE,cACC,4BACA,CAAC,WAAW,cAAc,MAAM,GAChC,CAAC,GACD,CACC,EACC,MAAM,oBACN,aACC,+FACF,GACA,EACC,MAAM,oBACN,aACC,6GACF,GACA,EACC,MAAM,mBACN,aACC,mFACF,CACD,CACD,GACA,cACC,6BACA,CAAC,WAAW,cAAc,OAAO,GACjC,CAAC,GACD,CACC,EACC,MAAM,mBACN,aACC,qGACF,CACD,CACD,GACA,cAAc,0BAA0B,CAAC,WAAW,cAAc,KAAK,CAAC,GACxE,cAAc,wBAAwB,CAAC,WAAW,WAAW,MAAM,CAAC,GACpE,cAAc,kCAAkC,CAC/C,WACA,cACA,MACD,CAAC,GACD,cAAc,6BAA6B,CAC1C,WACA,cACA,QACD,CAAC,GACD,cAAc,wBAAwB,CAAC,UAAU,YAAY,MAAM,CAAC,GACpE,cAAc,kCAAkC,CAC/C,UACA,YACA,aACA,KACD,CAAC,GACD,cAAc,4BAA4B,CACzC,QACA,mBACA,MACD,CAAC,GACD,cAAc,gCAAgC,CAC7C,YACA,mBACA,MACD,CAAC,CACF,GAEM,iBAAiBA,QAAC,WAA0B,MAAM,WAAW,KAAK,GAAG,GAAp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"names": ["__name", "array", "path", "_a", "initializer", "own", "proto", "error", "issue", "node", "parseAsync", "version", "checks", "checkResult", "canary", "result", "hostname", "base64", "memo", "r", "isObject2", "results", "left", "right", "output", "cached", "merge", "id", "schema", "members", "required", "object", "union", "issues", "_parse", "_parseAsync", "_encode", "_decode", "_encodeAsync", "_decodeAsync", "out", "failure", "directoryStat", "payload", "observable", "settle", "o", "t", "n", "e", "TRPCClientError", "WsConnection", "email", "guidance", "time", "contentType", "date", "command"]
7
+ }