@nekzus/liop 2.1.0-alpha.3 → 2.1.0-alpha.5

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.
Files changed (83) hide show
  1. package/README.md +10 -0
  2. package/dist/bin/agent.js +301 -4
  3. package/dist/bin/agent.js.map +1 -1
  4. package/dist/bridge.js +3 -1
  5. package/dist/chunk-32ADSAJS.js +104 -0
  6. package/dist/chunk-32ADSAJS.js.map +1 -0
  7. package/dist/chunk-4KIGYPIQ.js +3298 -0
  8. package/dist/chunk-4KIGYPIQ.js.map +1 -0
  9. package/dist/chunk-72MNYFR6.js +64 -0
  10. package/dist/chunk-72MNYFR6.js.map +1 -0
  11. package/dist/chunk-AL7H7DTW.js +463 -0
  12. package/dist/chunk-AL7H7DTW.js.map +1 -0
  13. package/dist/chunk-CT6NHSYP.js +30 -0
  14. package/dist/chunk-CT6NHSYP.js.map +1 -0
  15. package/dist/chunk-IJHTRIZC.js +56 -0
  16. package/dist/chunk-IJHTRIZC.js.map +1 -0
  17. package/dist/chunk-J3WPBMJ5.js +332 -0
  18. package/dist/chunk-J3WPBMJ5.js.map +1 -0
  19. package/dist/chunk-MMYZR7G7.js +815 -0
  20. package/dist/chunk-MMYZR7G7.js.map +1 -0
  21. package/dist/chunk-ODJT7ZUF.js +300 -0
  22. package/dist/chunk-ODJT7ZUF.js.map +1 -0
  23. package/dist/chunk-OUUTDSOW.js +24 -0
  24. package/dist/chunk-OUUTDSOW.js.map +1 -0
  25. package/dist/chunk-QLCOEP5J.js +68 -0
  26. package/dist/chunk-QLCOEP5J.js.map +1 -0
  27. package/dist/chunk-RDWCGZ2A.js +87 -0
  28. package/dist/chunk-RDWCGZ2A.js.map +1 -0
  29. package/dist/chunk-RWRRBYG4.js +1 -0
  30. package/dist/chunk-SSURAA3I.js +469 -0
  31. package/dist/chunk-SSURAA3I.js.map +1 -0
  32. package/dist/chunk-Y73XGYY7.js +1597 -0
  33. package/dist/chunk-Y73XGYY7.js.map +1 -0
  34. package/dist/client.js +8 -1
  35. package/dist/gateway.js +9 -1
  36. package/dist/index.js +58 -4
  37. package/dist/index.js.map +1 -1
  38. package/dist/kyber-3ULIJSE3.js +3 -0
  39. package/dist/{kyber-NONMBQNH.js.map → kyber-3ULIJSE3.js.map} +1 -1
  40. package/dist/mesh.js +4 -1
  41. package/dist/server.js +6 -1
  42. package/dist/types.js +2 -1
  43. package/dist/verifier-3FAKCFNN.js +5 -0
  44. package/dist/{verifier-XU2DB56Z.js.map → verifier-3FAKCFNN.js.map} +1 -1
  45. package/dist/workers/logic-execution.js +255 -1
  46. package/dist/workers/logic-execution.js.map +1 -1
  47. package/dist/workers/zk-verifier.js +173 -1
  48. package/dist/workers/zk-verifier.js.map +1 -1
  49. package/package.json +7 -7
  50. package/dist/chunk-4C666HHU.js +0 -2
  51. package/dist/chunk-4C666HHU.js.map +0 -1
  52. package/dist/chunk-ANFXJGMP.js +0 -2
  53. package/dist/chunk-ANFXJGMP.js.map +0 -1
  54. package/dist/chunk-DBXGYHKY.js +0 -2
  55. package/dist/chunk-DBXGYHKY.js.map +0 -1
  56. package/dist/chunk-DQ6UW6L7.js +0 -2
  57. package/dist/chunk-DQ6UW6L7.js.map +0 -1
  58. package/dist/chunk-G45SRWLR.js +0 -3
  59. package/dist/chunk-G45SRWLR.js.map +0 -1
  60. package/dist/chunk-GI2LSJYZ.js +0 -13
  61. package/dist/chunk-GI2LSJYZ.js.map +0 -1
  62. package/dist/chunk-I46YEWND.js +0 -33
  63. package/dist/chunk-I46YEWND.js.map +0 -1
  64. package/dist/chunk-PWCXZWSE.js +0 -2
  65. package/dist/chunk-PWCXZWSE.js.map +0 -1
  66. package/dist/chunk-QNFD36B7.js +0 -54
  67. package/dist/chunk-QNFD36B7.js.map +0 -1
  68. package/dist/chunk-RYYRR4N5.js +0 -31
  69. package/dist/chunk-RYYRR4N5.js.map +0 -1
  70. package/dist/chunk-S6RJHZV2.js +0 -2
  71. package/dist/chunk-S6RJHZV2.js.map +0 -1
  72. package/dist/chunk-SB5XJXKV.js +0 -2
  73. package/dist/chunk-SB5XJXKV.js.map +0 -1
  74. package/dist/chunk-T3L6OCM3.js +0 -3
  75. package/dist/chunk-T3L6OCM3.js.map +0 -1
  76. package/dist/chunk-V5MKJT6S.js +0 -2
  77. package/dist/chunk-V5MKJT6S.js.map +0 -1
  78. package/dist/chunk-VQUSWD4U.js +0 -2
  79. package/dist/chunk-VQUSWD4U.js.map +0 -1
  80. package/dist/chunk-XOITNPU3.js +0 -2
  81. package/dist/chunk-XOITNPU3.js.map +0 -1
  82. package/dist/kyber-NONMBQNH.js +0 -2
  83. package/dist/verifier-XU2DB56Z.js +0 -2
@@ -1,31 +0,0 @@
1
- import j from'crypto';import*as i from'fs/promises';import*as S from'os';import*as u from'path';import E from'vm';import {WASI}from'wasi';var l=class extends Error{constructor(r){super(`AST Sec-Policy Violation: ${r}`),this.name="GuardianError";}},w={analyze(c){let r=WebAssembly.Module.imports(c),o=0,d=new Set(["fd_write","fd_read","fd_close","fd_seek","environ_get","environ_sizes_get","args_get","args_sizes_get","clock_time_get","random_get","proc_exit","fd_prestat_get","fd_prestat_dir_name","fd_fdstat_get"]);for(let n of r){if(n.module==="wasi_snapshot_preview1"){if(!d.has(n.name))throw new l(`Banned WASI Import Detected: ${n.module}/${n.name}`)}else throw new l(`Banned Host Import Module Detected: ${n.module}`);if(o++,o>128)throw new l("Import limit exceeded. Possible resource exhaustion attack.")}}};var x=process.emit;process.emit=(c,r,...o)=>c==="warning"&&typeof r=="object"&&r.name==="ExperimentalWarning"&&String(r.message).includes("WASI")||String(r.message).includes("importing WASI")?false:x.call(process,c,r,...o);function R(){let r=process.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"],o={NODE_ENV:"production",LIOP_NODE:"true"};for(let d of r){let n=process.env[d];n!==void 0&&!n.startsWith("()")&&(o[d]=n);}return o}var h=class{wasi;sandboxId;workingDir;config;stdoutHandle=null;stderrHandle=null;constructor(r={}){this.sandboxId=j.randomUUID(),this.workingDir=u.join(S.tmpdir(),"liop-mesh","sandboxes",this.sandboxId),this.config=r;}async init(){try{await i.mkdir(this.workingDir,{recursive:!0}),this.stdoutHandle=await i.open(u.join(this.workingDir,"stdout.log"),"w+"),this.stderrHandle=await i.open(u.join(this.workingDir,"stderr.log"),"w+"),this.wasi=new WASI({version:"preview1",args:["liop_runtime"],env:this.config.allowEnv?{...R(),RUNTIME_ID:this.sandboxId}:{NODE_ENV:"production",LIOP_NODE:"true",RUNTIME_ID:this.sandboxId},preopens:{"/sandbox":this.workingDir,...this.config.allowedDirectories},stdout:this.stdoutHandle.fd,stderr:this.stderrHandle.fd});}catch(r){throw new Error(`Sandbox Initialization Failed: ${r instanceof Error?r.message:"FS Error"}`)}}async execute(r,o=[],d={}){let n=performance.now();if(r instanceof Buffer)try{let e=await WebAssembly.compile(new Uint8Array(r));w.analyze(e);let y=await WebAssembly.instantiate(e,this.wasi.getImportObject());this.wasi.start(y);let f=u.join(this.workingDir,"stdout.log"),p=u.join(this.workingDir,"stderr.log"),s=await i.readFile(f,"utf-8"),m=await i.readFile(p,"utf-8"),t=performance.now()-n;return {output:s||(m?`Error: ${m}`:"WASM_EXECUTION_SUCCESS"),fuelConsumed:Math.floor(t*1e3)}}catch(e){throw new Error(`WASM Runtime Error: ${e instanceof Error?e.message:String(e)}`)}else {let e=Object.create(null),y={records:o,...d};e.require=void 0,e.process=void 0,e.global=void 0,e.globalThis=void 0,e.Buffer=void 0,e.setTimeout=void 0,e.setInterval=void 0,e.setImmediate=void 0,e.queueMicrotask=void 0,e.eval=void 0,e.Function=void 0,e.SharedArrayBuffer=void 0,e.Date=void 0,e.ArrayBuffer=void 0,e.Uint8Array=void 0,e.Int8Array=void 0,e.Uint16Array=void 0,e.Int16Array=void 0,e.Uint32Array=void 0,e.Int32Array=void 0,e.Float32Array=void 0,e.Float64Array=void 0,e.BigInt64Array=void 0,e.BigUint64Array=void 0,e.DataView=void 0;let f=t=>{if(!t||typeof t!="object")return t;if(Array.isArray(t))return t.map(f);let a=Object.create(null);for(let[g,O]of Object.entries(t))a[g]=f(O);return a};e.records=f(JSON.parse(JSON.stringify(o))),e.env=f(JSON.parse(JSON.stringify(y)));for(let[t,a]of Object.entries(d))e[t]=f(JSON.parse(JSON.stringify(a)));let p=t=>{if(t&&typeof t=="object"&&!Object.isFrozen(t)){Object.freeze(t);for(let a of Object.keys(t))p(t[a]);}return t};p(e.records),p(e.env);for(let t of Object.keys(e))Object.defineProperty(e,t,{writable:false,configurable:false});let s=String(r);(/^\s*return\s/m.test(s)||!s.includes("function liop_main"))&&(s.includes("function liop_main")||(s=`function liop_main(env) {
2
- ${s}
3
- }`));let m=`
4
- (function() {
5
- "use strict";
6
- try {
7
- // Pre-execution prototype freezing (PCI-DSS Compliance)
8
- Object.freeze(Object.prototype);
9
- Object.freeze(Array.prototype);
10
- Object.freeze(String.prototype);
11
- Object.freeze(Number.prototype);
12
- Object.freeze(Boolean.prototype);
13
- Object.freeze(RegExp.prototype);
14
- Object.freeze(Map.prototype);
15
- Object.freeze(Set.prototype);
16
- Object.freeze(Promise.prototype);
17
- Object.freeze(Error.prototype);
18
- Object.freeze(Object.getPrototypeOf(function(){}));
19
-
20
- ${s}
21
- if (typeof liop_main === 'function') {
22
- return liop_main(env);
23
- }
24
- return "ERR_NO_ENTRY_POINT";
25
- } catch(e) {
26
- return "LogicError: " + e.message;
27
- }
28
- })();
29
- `;try{let t=new E.Script(m,{filename:`liop-sandbox-${this.sandboxId.slice(0,8)}.js`});!process.env.VITEST&&typeof Object.prototype=="object"&&!Object.isFrozen(Object.prototype)&&(Object.freeze(Object.prototype),Object.freeze(Array.prototype),Object.freeze(String.prototype),Object.freeze(Number.prototype),Object.freeze(Boolean.prototype),Object.freeze(RegExp.prototype),Object.freeze(Map.prototype),Object.freeze(Set.prototype),Object.freeze(Promise.prototype),Object.freeze(Error.prototype));let a=E.createContext(e,{name:"LIOP Isolate",origin:"liop://sandbox",microtaskMode:"afterEvaluate"}),g=t.runInContext(a,{timeout:5e3,breakOnSigint:!0,displayErrors:!0}),O=performance.now()-n,A=Math.floor(O*1500+100),b=Math.ceil(A/100)*100;if(b>1e6)throw new Error("LIOP_RESOURCE_EXHAUSTED: Execution fuel limit exceeded.");return {output:g,fuelConsumed:b}}catch(t){throw new Error(`V8 Isolate Fault: ${t instanceof Error?t.message:"Execution Timeout"}`)}}}async teardown(){try{this.stdoutHandle&&await this.stdoutHandle.close(),this.stderrHandle&&await this.stderrHandle.close(),await i.rm(this.workingDir,{recursive:!0,force:!0});}catch{}}};
30
- export{w as a,R as b,h as c};//# sourceMappingURL=chunk-RYYRR4N5.js.map
31
- //# sourceMappingURL=chunk-RYYRR4N5.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/sandbox/guardian.ts","../src/sandbox/wasi.ts"],"names":["GuardianError","message","ASTGuardian","module","imports","_importCount","ALLOWED_WASI_FUNCTIONS","imp","originalEmit","name","data","args","getDefaultEnvironment","safeKeys","env","key","val","WasiSandbox","config","crypto","WASI","error","compiledLogic","records","inputs","startTime","instance","stdoutPath","stderrPath","stdout","stderr","duration","sandboxEnv","toNullPrototype","obj","clone","value","deepFreeze","processedLogic","scriptCode","script","vm","context","output","rawFuel","fuelUsed"],"mappings":"0IAAO,IAAMA,EAAN,cAA4B,KAAM,CACxC,WAAA,CAAYC,CAAAA,CAAiB,CAC5B,KAAA,CAAM,CAAA,0BAAA,EAA6BA,CAAO,CAAA,CAAE,EAC5C,IAAA,CAAK,IAAA,CAAO,gBACb,CACD,CAAA,CAQaC,EAAc,CAO1B,OAAA,CAAQC,CAAAA,CAAkC,CACzC,IAAMC,CAAAA,CAAU,WAAA,CAAY,OAAO,OAAA,CAAQD,CAAM,EAC7CE,CAAAA,CAAe,CA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AE,SAAA,CAAW,GAAM,KAAA,CAAO,CAAA,CAAK,CAAC,EAC9D,CAAA,KAAa,CAEb,CACD,CACD","file":"chunk-RYYRR4N5.js","sourcesContent":["export class GuardianError extends Error {\n\tconstructor(message: string) {\n\t\tsuper(`AST Sec-Policy Violation: ${message}`);\n\t\tthis.name = \"GuardianError\";\n\t}\n}\n\n/**\n * The Guardian-TS Module\n * Scans the Abstract Syntax Tree (AST) imports of incoming WASM\n * before it reaches the V8 Wasmtime engine to prevent sandbox-escape\n * zero-days, resource exhaustion bombs, and evasive execution.\n */\nexport const ASTGuardian = {\n\t/**\n\t * Analyzes the WebAssembly Module interface proactively.\n\t *\n\t * @param module - The compiled WebAssembly.Module to inspect\n\t * @throws {GuardianError} If illegal imports or capabilities are detected\n\t */\n\tanalyze(module: WebAssembly.Module): void {\n\t\tconst imports = WebAssembly.Module.imports(module);\n\t\tlet _importCount = 0;\n\n\t\tconst ALLOWED_WASI_FUNCTIONS = new Set([\n\t\t\t\"fd_write\",\n\t\t\t\"fd_read\",\n\t\t\t\"fd_close\",\n\t\t\t\"fd_seek\",\n\t\t\t\"environ_get\",\n\t\t\t\"environ_sizes_get\",\n\t\t\t\"args_get\",\n\t\t\t\"args_sizes_get\",\n\t\t\t\"clock_time_get\",\n\t\t\t\"random_get\",\n\t\t\t\"proc_exit\",\n\t\t\t\"fd_prestat_get\",\n\t\t\t\"fd_prestat_dir_name\",\n\t\t\t\"fd_fdstat_get\",\n\t\t]);\n\n\t\tfor (const imp of imports) {\n\t\t\t// Strict Sandbox Validation: Only allow WASI preview 1 specific whitelisted functions.\n\t\t\tif (imp.module === \"wasi_snapshot_preview1\") {\n\t\t\t\tif (!ALLOWED_WASI_FUNCTIONS.has(imp.name)) {\n\t\t\t\t\tthrow new GuardianError(\n\t\t\t\t\t\t`Banned WASI Import Detected: ${imp.module}/${imp.name}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tthrow new GuardianError(\n\t\t\t\t\t`Banned Host Import Module Detected: ${imp.module}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\t_importCount++;\n\n\t\t\tif (_importCount > 128) {\n\t\t\t\tthrow new GuardianError(\n\t\t\t\t\t\"Import limit exceeded. Possible resource exhaustion attack.\",\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\t// In Node.js / V8, the maximum module size and function limits\n\t\t// are natively enforced by the engine during compilation.\n\t\t// A successfully compiled WebAssembly.Module already passed structural checks.\n\t},\n};\n","import crypto from \"node:crypto\";\nimport * as fs from \"node:fs/promises\";\nimport * as os from \"node:os\";\nimport * as path from \"node:path\";\nimport vm from \"node:vm\";\nimport { WASI } from \"node:wasi\";\nimport { ASTGuardian } from \"./guardian.js\";\n\n// Silence Node.js ExperimentalWarning for WASI (Industrial console parity)\nconst originalEmit = process.emit;\n// @ts-expect-error\nprocess.emit = (name, data, ...args) => {\n\tif (\n\t\t(name === \"warning\" &&\n\t\t\ttypeof data === \"object\" &&\n\t\t\t(data as Record<string, unknown>).name === \"ExperimentalWarning\" &&\n\t\t\tString((data as Record<string, unknown>).message).includes(\"WASI\")) ||\n\t\tString((data as Record<string, unknown>).message).includes(\"importing WASI\")\n\t) {\n\t\treturn false;\n\t}\n\treturn originalEmit.call(process, name, data, ...args);\n};\n\n/**\n * Returns a filtered environment object containing only safe system variables,\n * preventing exposure of sensitive credentials and shell function injection.\n */\nexport function getDefaultEnvironment(): Record<string, string> {\n\tconst isWindows = process.platform === \"win32\";\n\tconst safeKeys = isWindows\n\t\t? [\n\t\t\t\t\"APPDATA\",\n\t\t\t\t\"HOMEDRIVE\",\n\t\t\t\t\"HOMEPATH\",\n\t\t\t\t\"LOCALAPPDATA\",\n\t\t\t\t\"PATH\",\n\t\t\t\t\"PROCESSOR_ARCHITECTURE\",\n\t\t\t\t\"SYSTEMDRIVE\",\n\t\t\t\t\"SYSTEMROOT\",\n\t\t\t\t\"TEMP\",\n\t\t\t\t\"USERNAME\",\n\t\t\t\t\"USERPROFILE\",\n\t\t\t\t\"PROGRAMFILES\",\n\t\t\t]\n\t\t: [\"HOME\", \"LOGNAME\", \"PATH\", \"SHELL\", \"TERM\", \"USER\"];\n\n\tconst env: Record<string, string> = {\n\t\tNODE_ENV: \"production\",\n\t\tLIOP_NODE: \"true\",\n\t};\n\n\tfor (const key of safeKeys) {\n\t\tconst val = process.env[key];\n\t\tif (val !== undefined && !val.startsWith(\"()\")) {\n\t\t\tenv[key] = val;\n\t\t}\n\t}\n\n\treturn env;\n}\n\nexport interface SandboxConfig {\n\tallowEnv?: boolean;\n\tallowedDirectories?: Record<string, string>; // guestPath -> hostPath\n\tmemoryLimitMb?: number;\n}\n\n/**\n * LIOP WasiSandbox (Industrial Grade)\n *\n * Provides a production-grade isolated environment for executing untrusted logic.\n * Primarily uses WebAssembly (WASI) for byte-code isolation, with a hardened\n * V8 Isolate fallback for dynamic JS-to-WASM logic injection.\n */\nexport class WasiSandbox {\n\tprivate wasi!: WASI;\n\tprivate sandboxId: string;\n\tprivate workingDir: string;\n\tprivate config: SandboxConfig;\n\tprivate stdoutHandle: fs.FileHandle | null = null;\n\tprivate stderrHandle: fs.FileHandle | null = null;\n\n\tconstructor(config: SandboxConfig = {}) {\n\t\tthis.sandboxId = crypto.randomUUID();\n\t\t// Use a dedicated LIOP directory in the OS temp folder\n\t\tthis.workingDir = path.join(\n\t\t\tos.tmpdir(),\n\t\t\t\"liop-mesh\",\n\t\t\t\"sandboxes\",\n\t\t\tthis.sandboxId,\n\t\t);\n\t\tthis.config = config;\n\t}\n\n\t/**\n\t * Initializes the physical sandbox environment with strict directory lockdown.\n\t */\n\tpublic async init(): Promise<void> {\n\t\ttry {\n\t\t\tawait fs.mkdir(this.workingDir, { recursive: true });\n\n\t\t\t// Initialize WASI with explicit limits\n\t\t\tthis.stdoutHandle = await fs.open(\n\t\t\t\tpath.join(this.workingDir, \"stdout.log\"),\n\t\t\t\t\"w+\",\n\t\t\t);\n\t\t\tthis.stderrHandle = await fs.open(\n\t\t\t\tpath.join(this.workingDir, \"stderr.log\"),\n\t\t\t\t\"w+\",\n\t\t\t);\n\n\t\t\tthis.wasi = new WASI({\n\t\t\t\tversion: \"preview1\",\n\t\t\t\targs: [\"liop_runtime\"],\n\t\t\t\tenv: this.config.allowEnv\n\t\t\t\t\t? { ...getDefaultEnvironment(), RUNTIME_ID: this.sandboxId }\n\t\t\t\t\t: {\n\t\t\t\t\t\t\tNODE_ENV: \"production\",\n\t\t\t\t\t\t\tLIOP_NODE: \"true\",\n\t\t\t\t\t\t\tRUNTIME_ID: this.sandboxId,\n\t\t\t\t\t\t},\n\t\t\t\tpreopens: {\n\t\t\t\t\t\"/sandbox\": this.workingDir,\n\t\t\t\t\t...this.config.allowedDirectories,\n\t\t\t\t},\n\t\t\t\tstdout: this.stdoutHandle.fd,\n\t\t\t\tstderr: this.stderrHandle.fd,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tthrow new Error(\n\t\t\t\t`Sandbox Initialization Failed: ${error instanceof Error ? error.message : \"FS Error\"}`,\n\t\t\t);\n\t\t}\n\t}\n\n\t/**\n\t * Executes logic (WASM or JS-Wrapped) with hard resource limits.\n\t */\n\tpublic async execute(\n\t\tcompiledLogic: Buffer | string,\n\t\trecords: Record<string, unknown>[] = [],\n\t\tinputs: Record<string, unknown> = {},\n\t): Promise<{ output: unknown; fuelConsumed: number }> {\n\t\tconst startTime = performance.now();\n\n\t\tif (compiledLogic instanceof Buffer) {\n\t\t\t// Path A: Native WebAssembly Isolation\n\t\t\ttry {\n\t\t\t\tconst module = await WebAssembly.compile(new Uint8Array(compiledLogic));\n\n\t\t\t\t// Tier-0 Guardian: Static analysis to prevent sandbox escapes\n\t\t\t\tASTGuardian.analyze(module);\n\n\t\t\t\tconst instance = await WebAssembly.instantiate(\n\t\t\t\t\tmodule,\n\t\t\t\t\tthis.wasi.getImportObject() as WebAssembly.Imports,\n\t\t\t\t);\n\n\t\t\t\t// Standard entry point\n\t\t\t\tthis.wasi.start(instance);\n\n\t\t\t\t// Capture output from the sandbox\n\t\t\t\tconst stdoutPath = path.join(this.workingDir, \"stdout.log\");\n\t\t\t\tconst stderrPath = path.join(this.workingDir, \"stderr.log\");\n\t\t\t\tconst stdout = await fs.readFile(stdoutPath, \"utf-8\");\n\t\t\t\tconst stderr = await fs.readFile(stderrPath, \"utf-8\");\n\n\t\t\t\tconst duration = performance.now() - startTime;\n\t\t\t\treturn {\n\t\t\t\t\toutput:\n\t\t\t\t\t\tstdout || (stderr ? `Error: ${stderr}` : \"WASM_EXECUTION_SUCCESS\"),\n\t\t\t\t\tfuelConsumed: Math.floor(duration * 1000),\n\t\t\t\t};\n\t\t\t} catch (error: unknown) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`WASM Runtime Error: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t\t);\n\t\t\t}\n\t\t} else {\n\t\t\t// Path B: Hardened V8 Isolate Fallback\n\t\t\t// Uses node:vm with zero-prototype objects to prevent prototype pollution escapes.\n\n\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Required for Sandbox global poisoning\n\t\t\tconst sandboxEnv: any = Object.create(null); // Isolated global object\n\t\t\tconst env = { records, ...inputs };\n\n\t\t\t// Explicitly poison Node.js escape vectors in the context\n\t\t\tsandboxEnv.require = undefined;\n\t\t\tsandboxEnv.process = undefined;\n\t\t\tsandboxEnv.global = undefined;\n\t\t\tsandboxEnv.globalThis = undefined;\n\t\t\tsandboxEnv.Buffer = undefined;\n\t\t\tsandboxEnv.setTimeout = undefined;\n\t\t\tsandboxEnv.setInterval = undefined;\n\t\t\tsandboxEnv.setImmediate = undefined;\n\t\t\tsandboxEnv.queueMicrotask = undefined;\n\t\t\tsandboxEnv.eval = undefined;\n\t\t\tsandboxEnv.Function = undefined;\n\t\t\tsandboxEnv.SharedArrayBuffer = undefined;\n\t\t\tsandboxEnv.Date = undefined;\n\n\t\t\t// [DoS Defense] Block off-heap memory allocation vectors.\n\t\t\t// Logic-on-Origin operates on JSON data (env.records) — binary buffers\n\t\t\t// serve no legitimate purpose and enable memory exhaustion DoS.\n\t\t\t// (Uint8Array(2GB) bypassed Piscina's maxOldGenerationSizeMb limit)\n\t\t\tsandboxEnv.ArrayBuffer = undefined;\n\t\t\tsandboxEnv.Uint8Array = undefined;\n\t\t\tsandboxEnv.Int8Array = undefined;\n\t\t\tsandboxEnv.Uint16Array = undefined;\n\t\t\tsandboxEnv.Int16Array = undefined;\n\t\t\tsandboxEnv.Uint32Array = undefined;\n\t\t\tsandboxEnv.Int32Array = undefined;\n\t\t\tsandboxEnv.Float32Array = undefined;\n\t\t\tsandboxEnv.Float64Array = undefined;\n\t\t\tsandboxEnv.BigInt64Array = undefined;\n\t\t\tsandboxEnv.BigUint64Array = undefined;\n\t\t\tsandboxEnv.DataView = undefined;\n\n\t\t\t// Recurse and strip prototype chain from host-passed objects to prevent escaping via constructor\n\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Required for recursive null prototype mapping\n\t\t\tconst toNullPrototype = (obj: any): any => {\n\t\t\t\tif (!obj || typeof obj !== \"object\") {\n\t\t\t\t\treturn obj;\n\t\t\t\t}\n\t\t\t\tif (Array.isArray(obj)) {\n\t\t\t\t\treturn obj.map(toNullPrototype);\n\t\t\t\t}\n\t\t\t\tconst clone = Object.create(null);\n\t\t\t\tfor (const [key, val] of Object.entries(obj)) {\n\t\t\t\t\tclone[key] = toNullPrototype(val);\n\t\t\t\t}\n\t\t\t\treturn clone;\n\t\t\t};\n\n\t\t\t// Inject strictly monitored globals\n\t\t\tsandboxEnv.records = toNullPrototype(JSON.parse(JSON.stringify(records))); // Deep copy safety + null prototype\n\t\t\tsandboxEnv.env = toNullPrototype(JSON.parse(JSON.stringify(env)));\n\n\t\t\tfor (const [key, value] of Object.entries(inputs)) {\n\t\t\t\tsandboxEnv[key] = toNullPrototype(JSON.parse(JSON.stringify(value)));\n\t\t\t}\n\n\t\t\t// Freeze the sandbox context to prevent mutation (SEC-GAP-1)\n\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Required for recursive deep freeze of unknown data\n\t\t\tconst deepFreeze = (obj: any) => {\n\t\t\t\tif (obj && typeof obj === \"object\" && !Object.isFrozen(obj)) {\n\t\t\t\t\tObject.freeze(obj);\n\t\t\t\t\tfor (const key of Object.keys(obj)) {\n\t\t\t\t\t\tdeepFreeze(obj[key]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn obj;\n\t\t\t};\n\n\t\t\tdeepFreeze(sandboxEnv.records);\n\t\t\tdeepFreeze(sandboxEnv.env);\n\n\t\t\t// Prevent property addition/modification on global scope\n\t\t\tfor (const key of Object.keys(sandboxEnv)) {\n\t\t\t\tObject.defineProperty(sandboxEnv, key, {\n\t\t\t\t\twritable: false,\n\t\t\t\t\tconfigurable: false,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\t// LIOP Execution Wrapper\n\t\t\t// Host-side logic transformation to avoid 'new Function' in sandbox\n\t\t\tlet processedLogic = String(compiledLogic);\n\t\t\tif (\n\t\t\t\t/^\\s*return\\s/m.test(processedLogic) ||\n\t\t\t\t!processedLogic.includes(\"function liop_main\")\n\t\t\t) {\n\t\t\t\tif (!processedLogic.includes(\"function liop_main\")) {\n\t\t\t\t\tprocessedLogic = `function liop_main(env) {\\n${processedLogic}\\n}`;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst scriptCode = `\n\t\t\t\t(function() {\n\t\t\t\t\t\"use strict\";\n\t\t\t\t\ttry {\n\t\t\t\t\t\t// Pre-execution prototype freezing (PCI-DSS Compliance)\n\t\t\t\t\t\tObject.freeze(Object.prototype);\n\t\t\t\t\t\tObject.freeze(Array.prototype);\n\t\t\t\t\t\tObject.freeze(String.prototype);\n\t\t\t\t\t\tObject.freeze(Number.prototype);\n\t\t\t\t\t\tObject.freeze(Boolean.prototype);\n\t\t\t\t\t\tObject.freeze(RegExp.prototype);\n\t\t\t\t\t\tObject.freeze(Map.prototype);\n\t\t\t\t\t\tObject.freeze(Set.prototype);\n\t\t\t\t\t\tObject.freeze(Promise.prototype);\n\t\t\t\t\t\tObject.freeze(Error.prototype);\n\t\t\t\t\t\tObject.freeze(Object.getPrototypeOf(function(){}));\n\n\t\t\t\t\t\t${processedLogic}\n\t\t\t\t\t\tif (typeof liop_main === 'function') {\n\t\t\t\t\t\t\treturn liop_main(env);\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn \"ERR_NO_ENTRY_POINT\";\n\t\t\t\t\t} catch(e) {\n\t\t\t\t\t\treturn \"LogicError: \" + e.message;\n\t\t\t\t\t}\n\t\t\t\t})();\n\t\t\t`;\n\n\t\t\ttry {\n\t\t\t\tconst script = new vm.Script(scriptCode, {\n\t\t\t\t\tfilename: `liop-sandbox-${this.sandboxId.slice(0, 8)}.js`,\n\t\t\t\t});\n\n\t\t\t\t// Freeze Host prototypes in production (non-test environments) to completely block Prototype Pollution\n\t\t\t\tif (\n\t\t\t\t\t!process.env.VITEST &&\n\t\t\t\t\ttypeof Object.prototype === \"object\" &&\n\t\t\t\t\t!Object.isFrozen(Object.prototype)\n\t\t\t\t) {\n\t\t\t\t\tObject.freeze(Object.prototype);\n\t\t\t\t\tObject.freeze(Array.prototype);\n\t\t\t\t\tObject.freeze(String.prototype);\n\t\t\t\t\tObject.freeze(Number.prototype);\n\t\t\t\t\tObject.freeze(Boolean.prototype);\n\t\t\t\t\tObject.freeze(RegExp.prototype);\n\t\t\t\t\tObject.freeze(Map.prototype);\n\t\t\t\t\tObject.freeze(Set.prototype);\n\t\t\t\t\tObject.freeze(Promise.prototype);\n\t\t\t\t\tObject.freeze(Error.prototype);\n\t\t\t\t}\n\n\t\t\t\t// microtaskMode: Ensures Promises created inside the sandbox are\n\t\t\t\t// resolved within the timeout/breakOnSigint scope (Node.js ≥14.6).\n\t\t\t\t// Without this, async microtasks could escape the 5s CPU limit.\n\t\t\t\tconst context = vm.createContext(sandboxEnv, {\n\t\t\t\t\tname: \"LIOP Isolate\",\n\t\t\t\t\torigin: \"liop://sandbox\",\n\t\t\t\t\tmicrotaskMode: \"afterEvaluate\",\n\t\t\t\t});\n\n\t\t\t\t// Execution with hard CPU and Memory limits (Fuel)\n\t\t\t\tconst output = script.runInContext(context, {\n\t\t\t\t\ttimeout: 5000,\n\t\t\t\t\tbreakOnSigint: true,\n\t\t\t\t\tdisplayErrors: true,\n\t\t\t\t});\n\n\t\t\t\tconst duration = performance.now() - startTime;\n\t\t\t\t// SEC: Normalize fuel to buckets of 100 to prevent timing side-channel inference\n\t\t\t\tconst rawFuel = Math.floor(duration * 1500 + 100);\n\t\t\t\tconst fuelUsed = Math.ceil(rawFuel / 100) * 100;\n\n\t\t\t\tif (fuelUsed > 1000000) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\"LIOP_RESOURCE_EXHAUSTED: Execution fuel limit exceeded.\",\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\treturn { output, fuelConsumed: fuelUsed };\n\t\t\t} catch (error) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`V8 Isolate Fault: ${error instanceof Error ? error.message : \"Execution Timeout\"}`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Physically cleans up the sandbox and releases resources.\n\t */\n\tpublic async teardown(): Promise<void> {\n\t\ttry {\n\t\t\tif (this.stdoutHandle) await this.stdoutHandle.close();\n\t\t\tif (this.stderrHandle) await this.stderrHandle.close();\n\t\t\tawait fs.rm(this.workingDir, { recursive: true, force: true });\n\t\t} catch (_e) {\n\t\t\t// Silent fail on teardown to prevent process crashes\n\t\t}\n\t}\n}\n"]}
@@ -1,2 +0,0 @@
1
- var s=class r{static instance;level="info";constructor(){this.setLevelFromEnv();}static getInstance(){return r.instance||(r.instance=new r),r.instance}setLevelFromEnv(){let e=process.env.LIOP_LOG_LEVEL?.toLowerCase();e==="silent"||e==="error"||e==="warn"||e==="info"||e==="debug"?this.level=e:this.level="info";}setLevel(e){this.level=e;}shouldLog(e){let o={silent:0,error:1,warn:2,info:3,debug:4};return o[this.level]>=o[e]}formatMessage(e,o){return `[${new Date().toISOString()}] [${e}] ${o}`}error(e,...o){this.shouldLog("error")&&console.error(this.formatMessage("ERROR",e),...o);}warn(e,...o){this.shouldLog("warn")&&console.error(this.formatMessage("WARN",e),...o);}info(e,...o){this.shouldLog("info")&&console.error(this.formatMessage("INFO",e),...o);}debug(e,...o){this.shouldLog("debug")&&console.error(this.formatMessage("DEBUG",e),...o);}},l=s.getInstance();export{l as a};//# sourceMappingURL=chunk-S6RJHZV2.js.map
2
- //# sourceMappingURL=chunk-S6RJHZV2.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/utils/logger.ts"],"names":["LiopLogger","_LiopLogger","envLevel","level","targetLevel","levels","message","args","log"],"mappings":"AAOO,IAAMA,EAAN,MAAMC,CAAW,CACvB,OAAe,QAAA,CACP,MAAkB,MAAA,CAElB,WAAA,EAAc,CACrB,IAAA,CAAK,eAAA,GACN,CAEA,OAAc,aAA0B,CACvC,OAAKA,EAAW,QAAA,GACfA,CAAAA,CAAW,QAAA,CAAW,IAAIA,GAEpBA,CAAAA,CAAW,QACnB,CAEQ,eAAA,EAAkB,CACzB,IAAMC,CAAAA,CAAW,OAAA,CAAQ,IAAI,cAAA,EAAgB,WAAA,GAE5CA,CAAAA,GAAa,QAAA,EACbA,IAAa,OAAA,EACbA,CAAAA,GAAa,QACbA,CAAAA,GAAa,MAAA,EACbA,CAAAA,GAAa,OAAA,CAEb,KAAK,KAAA,CAAQA,CAAAA,CAGb,KAAK,KAAA,CAAQ,OAEf,CAEO,QAAA,CAASC,CAAAA,CAAiB,CAChC,IAAA,CAAK,KAAA,CAAQA,EACd,CAEQ,SAAA,CAAUC,EAAgC,CACjD,IAAMC,EAAmC,CACxC,MAAA,CAAQ,EACR,KAAA,CAAO,CAAA,CACP,KAAM,CAAA,CACN,IAAA,CAAM,EACN,KAAA,CAAO,CACR,EACA,OAAOA,CAAAA,CAAO,KAAK,KAAK,CAAA,EAAKA,EAAOD,CAAW,CAChD,CAEQ,aAAA,CAAcD,CAAAA,CAAeG,EAAyB,CAE7D,OAAO,CAAA,CAAA,EADI,IAAI,MAAK,CAAE,WAAA,EACT,CAAA,GAAA,EAAMH,CAAK,KAAKG,CAAO,CAAA,CACrC,CAEO,KAAA,CAAMA,CAAAA,CAAAA,GAAoBC,EAAiB,CAC7C,IAAA,CAAK,UAAU,OAAO,CAAA,EACzB,QAAQ,KAAA,CAAM,IAAA,CAAK,aAAA,CAAc,OAAA,CAASD,CAAO,CAAA,CAAG,GAAGC,CAAI,EAE7D,CAEO,KAAKD,CAAAA,CAAAA,GAAoBC,CAAAA,CAAiB,CAC5C,IAAA,CAAK,SAAA,CAAU,MAAM,CAAA,EACxB,OAAA,CAAQ,MAAM,IAAA,CAAK,aAAA,CAAc,OAAQD,CAAO,CAAA,CAAG,GAAGC,CAAI,EAE5D,CAEO,IAAA,CAAKD,KAAoBC,CAAAA,CAAiB,CAC5C,KAAK,SAAA,CAAU,MAAM,GACxB,OAAA,CAAQ,KAAA,CAAM,KAAK,aAAA,CAAc,MAAA,CAAQD,CAAO,CAAA,CAAG,GAAGC,CAAI,EAE5D,CAEO,MAAMD,CAAAA,CAAAA,GAAoBC,CAAAA,CAAiB,CAC7C,IAAA,CAAK,SAAA,CAAU,OAAO,CAAA,EACzB,OAAA,CAAQ,MAAM,IAAA,CAAK,aAAA,CAAc,QAASD,CAAO,CAAA,CAAG,GAAGC,CAAI,EAE7D,CACD,CAAA,CAEaC,CAAAA,CAAMR,EAAW,WAAA","file":"chunk-S6RJHZV2.js","sourcesContent":["export type LogLevel = \"silent\" | \"error\" | \"warn\" | \"info\" | \"debug\";\n\n/**\n * LiopLogger - Structured Logging Abstraction\n * Configurable via `process.env.LIOP_LOG_LEVEL`.\n * Emits strictly to stderr to comply with MCP stdio protocols.\n */\nexport class LiopLogger {\n\tprivate static instance: LiopLogger;\n\tprivate level: LogLevel = \"info\";\n\n\tprivate constructor() {\n\t\tthis.setLevelFromEnv();\n\t}\n\n\tpublic static getInstance(): LiopLogger {\n\t\tif (!LiopLogger.instance) {\n\t\t\tLiopLogger.instance = new LiopLogger();\n\t\t}\n\t\treturn LiopLogger.instance;\n\t}\n\n\tprivate setLevelFromEnv() {\n\t\tconst envLevel = process.env.LIOP_LOG_LEVEL?.toLowerCase();\n\t\tif (\n\t\t\tenvLevel === \"silent\" ||\n\t\t\tenvLevel === \"error\" ||\n\t\t\tenvLevel === \"warn\" ||\n\t\t\tenvLevel === \"info\" ||\n\t\t\tenvLevel === \"debug\"\n\t\t) {\n\t\t\tthis.level = envLevel as LogLevel;\n\t\t} else {\n\t\t\t// Default level: info\n\t\t\tthis.level = \"info\";\n\t\t}\n\t}\n\n\tpublic setLevel(level: LogLevel) {\n\t\tthis.level = level;\n\t}\n\n\tprivate shouldLog(targetLevel: LogLevel): boolean {\n\t\tconst levels: Record<LogLevel, number> = {\n\t\t\tsilent: 0,\n\t\t\terror: 1,\n\t\t\twarn: 2,\n\t\t\tinfo: 3,\n\t\t\tdebug: 4,\n\t\t};\n\t\treturn levels[this.level] >= levels[targetLevel];\n\t}\n\n\tprivate formatMessage(level: string, message: string): string {\n\t\tconst ts = new Date().toISOString();\n\t\treturn `[${ts}] [${level}] ${message}`;\n\t}\n\n\tpublic error(message: string, ...args: unknown[]) {\n\t\tif (this.shouldLog(\"error\")) {\n\t\t\tconsole.error(this.formatMessage(\"ERROR\", message), ...args);\n\t\t}\n\t}\n\n\tpublic warn(message: string, ...args: unknown[]) {\n\t\tif (this.shouldLog(\"warn\")) {\n\t\t\tconsole.error(this.formatMessage(\"WARN\", message), ...args);\n\t\t}\n\t}\n\n\tpublic info(message: string, ...args: unknown[]) {\n\t\tif (this.shouldLog(\"info\")) {\n\t\t\tconsole.error(this.formatMessage(\"INFO\", message), ...args);\n\t\t}\n\t}\n\n\tpublic debug(message: string, ...args: unknown[]) {\n\t\tif (this.shouldLog(\"debug\")) {\n\t\t\tconsole.error(this.formatMessage(\"DEBUG\", message), ...args);\n\t\t}\n\t}\n}\n\nexport const log = LiopLogger.getInstance();\n"]}
@@ -1,2 +0,0 @@
1
- var a={initialize:[],"notifications/initialized":[],"notifications/cancelled":[],ping:[],"tools/list":["liop:tools:list"],"tools/call":["liop:tools:call"],"resources/list":["liop:resources:read"],"resources/read":["liop:resources:read"],"prompts/list":["liop:schema:read"],"prompts/get":["liop:schema:read"]};function d(e,t,l){let o=a[e];if(o!==void 0&&o.length===0)return {allowed:true};if(!t)return {allowed:false,reason:`Authentication required for method: ${e}`};let s=[...o??[],...l??[]];if(s.length===0)return {allowed:false,reason:`Unknown method: ${e}. Access denied (fail-closed).`};let n=new Set(t.scopes),i=s.filter(r=>!n.has(r));return i.length>0?{allowed:false,reason:`Insufficient scopes for ${e}. Missing: ${i.join(", ")}`}:{allowed:true}}var u=["liop:tools:list","liop:tools:call","liop:resources:read","liop:schema:read","liop:mesh:query"];export{d as a,u as b};//# sourceMappingURL=chunk-SB5XJXKV.js.map
2
- //# sourceMappingURL=chunk-SB5XJXKV.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/security/rbac.ts"],"names":["SCOPE_MAP","authorizeRequest","method","auth","additionalScopes","methodScopes","needed","clientScopes","missing","s","LIOP_SCOPES"],"mappings":"AAiBA,IAAMA,CAAAA,CAAyD,CAE9D,UAAA,CAAY,GACZ,2BAAA,CAA6B,EAAC,CAC9B,yBAAA,CAA2B,EAAC,CAC5B,IAAA,CAAM,GAGN,YAAA,CAAc,CAAC,iBAAiB,CAAA,CAChC,YAAA,CAAc,CAAC,iBAAiB,CAAA,CAGhC,iBAAkB,CAAC,qBAAqB,CAAA,CACxC,gBAAA,CAAkB,CAAC,qBAAqB,CAAA,CAGxC,cAAA,CAAgB,CAAC,kBAAkB,CAAA,CACnC,aAAA,CAAe,CAAC,kBAAkB,CACnC,CAAA,CAuBO,SAASC,CAAAA,CACfC,EACAC,CAAAA,CACAC,CAAAA,CACsB,CACtB,IAAMC,CAAAA,CAAeL,CAAAA,CAAUE,CAAM,CAAA,CAGrC,GAAIG,CAAAA,GAAiB,MAAA,EAAaA,CAAAA,CAAa,MAAA,GAAW,CAAA,CACzD,OAAO,CAAE,OAAA,CAAS,IAAK,CAAA,CAIxB,GAAI,CAACF,CAAAA,CACJ,OAAO,CACN,OAAA,CAAS,KAAA,CACT,MAAA,CAAQ,uCAAuCD,CAAM,CAAA,CACtD,CAAA,CAID,IAAMI,CAAAA,CAAS,CAAC,GAAID,CAAAA,EAAgB,EAAC,CAAI,GAAID,CAAAA,EAAoB,EAAG,CAAA,CAGpE,GAAIE,CAAAA,CAAO,SAAW,CAAA,CACrB,OAAO,CACN,OAAA,CAAS,KAAA,CACT,MAAA,CAAQ,CAAA,gBAAA,EAAmBJ,CAAM,gCAClC,CAAA,CAID,IAAMK,CAAAA,CAAe,IAAI,IAAIJ,CAAAA,CAAK,MAAM,CAAA,CAClCK,CAAAA,CAAUF,EAAO,MAAA,CAAQG,CAAAA,EAAM,CAACF,CAAAA,CAAa,GAAA,CAAIE,CAAC,CAAC,CAAA,CAEzD,OAAID,CAAAA,CAAQ,MAAA,CAAS,CAAA,CACb,CACN,OAAA,CAAS,KAAA,CACT,MAAA,CAAQ,CAAA,wBAAA,EAA2BN,CAAM,CAAA,WAAA,EAAcM,CAAAA,CAAQ,IAAA,CAAK,IAAI,CAAC,CAAA,CAC1E,CAAA,CAGM,CAAE,QAAS,IAAK,CACxB,CAMO,IAAME,EAAc,CAC1B,iBAAA,CACA,iBAAA,CACA,qBAAA,CACA,mBACA,iBACD","file":"chunk-SB5XJXKV.js","sourcesContent":["/**\n * LIOP RBAC Engine — Scope-Based Authorization\n *\n * Maps MCP JSON-RPC methods to required LIOP OAuth scopes.\n * Enforces least-privilege access at the router level before\n * any tool execution or resource read occurs.\n *\n * Standards: NIST SP 800-207 §4.3 (least privilege), OWASP LLM06 (Excessive Agency),\n * OWASP API-A01 (Broken Access Control)\n */\n\nimport type { AuthInfo } from \"./jwt-validator.js\";\n\n/**\n * Maps MCP JSON-RPC methods to the LIOP scopes required to invoke them.\n * Empty array = no authentication required (public endpoints).\n */\nconst SCOPE_MAP: Readonly<Record<string, readonly string[]>> = {\n\t// Protocol lifecycle — unauthenticated (MCP spec compliance)\n\tinitialize: [],\n\t\"notifications/initialized\": [],\n\t\"notifications/cancelled\": [],\n\tping: [],\n\n\t// Tool operations — require explicit authorization\n\t\"tools/list\": [\"liop:tools:list\"],\n\t\"tools/call\": [\"liop:tools:call\"],\n\n\t// Resource operations — read-level access\n\t\"resources/list\": [\"liop:resources:read\"],\n\t\"resources/read\": [\"liop:resources:read\"],\n\n\t// Prompt/schema operations — schema-level access\n\t\"prompts/list\": [\"liop:schema:read\"],\n\t\"prompts/get\": [\"liop:schema:read\"],\n};\n\n/**\n * Authorization result with optional denial reason for audit logging.\n */\nexport interface AuthorizationResult {\n\tallowed: boolean;\n\treason?: string;\n}\n\n/**\n * Evaluates whether a request is authorized based on JWT scopes.\n *\n * Decision logic:\n * 1. Methods with no required scopes (initialize, ping) → always allowed.\n * 2. Methods with required scopes but no auth → denied.\n * 3. Methods with required scopes → all scopes must be present in the JWT.\n * 4. Unknown methods with no auth → denied (fail-closed per NIST SP 800-207).\n *\n * @param method - MCP JSON-RPC method name (e.g., \"tools/call\")\n * @param auth - Validated JWT context, or null if unauthenticated\n * @param additionalScopes - Extra scopes required by specific node configuration\n */\nexport function authorizeRequest(\n\tmethod: string,\n\tauth: AuthInfo | null,\n\tadditionalScopes?: readonly string[],\n): AuthorizationResult {\n\tconst methodScopes = SCOPE_MAP[method];\n\n\t// Methods explicitly marked as public (empty scope array) pass freely\n\tif (methodScopes !== undefined && methodScopes.length === 0) {\n\t\treturn { allowed: true };\n\t}\n\n\t// If no auth context and method requires scopes → deny\n\tif (!auth) {\n\t\treturn {\n\t\t\tallowed: false,\n\t\t\treason: `Authentication required for method: ${method}`,\n\t\t};\n\t}\n\n\t// Merge method-level scopes with node-level additional scopes\n\tconst needed = [...(methodScopes ?? []), ...(additionalScopes ?? [])];\n\n\t// If no scopes needed (unknown method, no additional) → fail-closed\n\tif (needed.length === 0) {\n\t\treturn {\n\t\t\tallowed: false,\n\t\t\treason: `Unknown method: ${method}. Access denied (fail-closed).`,\n\t\t};\n\t}\n\n\t// Verify all required scopes are present in the JWT\n\tconst clientScopes = new Set(auth.scopes);\n\tconst missing = needed.filter((s) => !clientScopes.has(s));\n\n\tif (missing.length > 0) {\n\t\treturn {\n\t\t\tallowed: false,\n\t\t\treason: `Insufficient scopes for ${method}. Missing: ${missing.join(\", \")}`,\n\t\t};\n\t}\n\n\treturn { allowed: true };\n}\n\n/**\n * All LIOP OAuth scopes supported by the protocol.\n * Used for PRM metadata and client registration.\n */\nexport const LIOP_SCOPES = [\n\t\"liop:tools:list\",\n\t\"liop:tools:call\",\n\t\"liop:resources:read\",\n\t\"liop:schema:read\",\n\t\"liop:mesh:query\",\n] as const;\n\nexport type LiopScope = (typeof LIOP_SCOPES)[number];\n"]}
@@ -1,3 +0,0 @@
1
- import {a as a$1}from'./chunk-PWCXZWSE.js';import {a as a$4}from'./chunk-DBXGYHKY.js';import {c,a}from'./chunk-V5MKJT6S.js';import {a as a$3}from'./chunk-DQ6UW6L7.js';import {a as a$2}from'./chunk-S6RJHZV2.js';import*as L from'@grpc/grpc-js';import {createDecipheriv,randomBytes,createCipheriv}from'crypto';var v=class{client;token;constructor(e,o,t){let i=c(o);this.client=new a.LogicMesh(e,i),this.token=t;}async negotiateIntent(e){return new Promise((o,t)=>{let i=new L.Metadata;this.token&&i.add("authorization",`Bearer ${this.token}`),this.client.NegotiateIntent(e,i,(n,s)=>{n?t(n):o(s);});})}executeLogic(e){let o=new L.Metadata;return this.token&&o.add("authorization",`Bearer ${this.token}`),this.client.ExecuteLogic(e,o)}close(){this.client.close();}};var M={encryptPayload(u,e){if(e.length!==32)throw new Error("Symmetric Key must be exactly 32 bytes (256 bits).");let o=randomBytes(12),t=createCipheriv("aes-256-gcm",e,o),i=Buffer.concat([t.update(u),t.final()]),n=t.getAuthTag();return {ciphertext:Buffer.concat([i,n]),nonce:o}},decryptPayload(u,e,o){if(u.length<16)throw new Error("Invalid GCM Ciphertext; missing authentication tag length");let t=u.subarray(0,-16),i=u.subarray(-16),n=createDecipheriv("aes-256-gcm",o,e);return n.setAuthTag(i),Buffer.concat([n.update(t),n.final()])}};var x=class{meshNode=null;rpcClients=new Map;manifests=new Map;tlsOptions;serverInfo;verifier=new a$1;oauthToken;constructor(e){this.tlsOptions=e;}async acquireM2MToken(e){let t=`${e.nexusUrl.endsWith("/oidc")?e.nexusUrl:`${e.nexusUrl}/oidc`}/token`;a$2.info(`[LiopClient] Requesting M2M Token from Nexus AS: ${t}`);let i=new URLSearchParams({grant_type:"client_credentials",scope:e.scope||"liop:tools:call liop:tools:list liop:resources:read liop:schema:read liop:mesh:query",resource:e.audience,client_id:e.clientId,client_secret:e.clientSecret}),n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i.toString()});if(!n.ok){let c=await n.text();throw new Error(`OAuth token request failed with status ${n.status}: ${c}`)}let s=await n.json();if(!s.access_token)throw new Error("OAuth token response did not contain an access_token.");return a$2.info("[LiopClient] M2M Token acquired successfully."),s.access_token}async connect(e,o){let t=o?.auth?.clientId||process.env.LIOP_OAUTH_CLIENT_ID||process.env.LIOP_CLIENT_ID,i=o?.auth?.clientSecret||process.env.LIOP_OAUTH_CLIENT_SECRET||process.env.LIOP_CLIENT_SECRET,n=o?.auth?.nexusUrl||process.env.LIOP_NEXUS_URL||"http://localhost:3000",s=o?.auth?.audience||process.env.LIOP_OAUTH_AUDIENCE||"urn:liop:mesh:api",c=o?.auth?.scope||process.env.LIOP_OAUTH_SCOPE||"liop:tools:call liop:tools:list liop:resources:read liop:schema:read liop:mesh:query";if(this.oauthToken=o?.auth?.token||process.env.LIOP_OAUTH_TOKEN||process.env.LIOP_TOKEN,t&&i)try{this.oauthToken=await this.acquireM2MToken({clientId:t,clientSecret:i,nexusUrl:n,audience:s,scope:c});}catch(a){a$2.error(`[LiopClient] Failed to acquire OAuth M2M Token: ${a instanceof Error?a.message:String(a)}`);}this.meshNode=new a$3(o?.meshConfig),await this.meshNode.start(),a$2.info(`[LiopClient] Mesh Node synchronized. PeerID: ${this.meshNode.getPeerId()}`),e?(this.rpcClients.set("static",new v(e,this.tlsOptions,this.oauthToken)),this.serverInfo={name:`LiopServer (${e})`,version:"1.0.0"},a$2.info(`[LiopClient] Static gRPC configured for: ${e}`)):this.serverInfo={name:"LiopServer (Mesh Alpha)",version:"1.0.0"};}async resolveCapability(e){if(!this.meshNode)throw new Error("Client must be connected to Mesh to resolve capabilities.");a$2.info(`[LiopClient] Querying Mesh DHT for Provider: ${e}...`);let o=await this.meshNode.findProviders(e);if(o.length===0)throw new Error(`Kademlia DHT found zero providers for capability: ${e}`);let t=o[0];a$2.info(`[LiopClient] Identified Alpha Provider PeerID: ${t}`);let i=50051,n=await this.meshNode.queryManifest(t);n&&(i=n.grpcPort,a$2.info(`[LiopClient] Manifest resolved: gRPC port ${i}`));let s=await this.meshNode.resolvePeer(t);for(let c of s){let a=c.split("/");if(a[1]==="ip4"){let p=`${a[2]}:${i}`;return a$2.info(`[LiopClient] Translated Multiaddr to gRPC Target: ${p}`),p}}return `127.0.0.1:${i}`}async discoverTools(){if(!this.meshNode)throw new Error("Client must be connected before discovering tools.");a$2.info("[LiopClient] Discovery started...");let e=await this.meshNode.discoverManifestProviders(),o=[],t=new Set;for(let i of e)try{a$2.info(`[LiopClient] Querying manifest from: ${i}`);let n=await this.meshNode.queryManifest(i);if(n){this.manifests.set(i,n);for(let s of n.tools)t.has(s.name)||(o.push({name:s.name,description:s.description}),t.add(s.name));}}catch(n){a$2.info(`[LiopClient] Error querying manifest from ${i}:`,n instanceof Error?n.message:String(n));}return a$2.info(`[LiopClient] Discovery finished. Found ${o.length} unique tools.`),o}async callTool(e,o){if(!this.meshNode)throw new Error("Client must be connected before calling tools.");let t=e.name;a$2.info(`[LiopClient] Resolving Tool: ${t}`);let i=this.rpcClients.get("static");if(i)a$2.info(`[LiopClient] Using existing static gRPC connection for ${t}.`);else {let y=await this.resolveCapability(t);i=this.getOrCreateRpcClient(t,y);}a$2.info(`[LiopClient] Negotiating intent for ${t}...`);let n=this.meshNode?`did:liop:${this.meshNode.getPeerId()}`:"did:liop:ephemeral",s=Buffer.from(`${t}:${Date.now()}`),c=this.meshNode?await this.meshNode.sign(s):s,a=await i.negotiateIntent({agent_did:n,capability_hash:t,proof_of_intent:c});if(!a.accepted)throw new Error(`Intent denied by host: ${a.error_message}`);let p=a.kyber_public_key||a.kyberPublicKey,f=a.session_token||a.sessionToken;if(!p)throw a$2.info("[LiopClient] Critical Error: Kyber Public Key not found in IntentResponse.",a),new Error("Handshake failed: Remote host did not provide a valid Kyber Public Key.");a$2.info(`[LiopClient] Encapsulating Post-Quantum Shared Secret for ${e.name}...`);let{ciphertext:C,sharedSecret:g}=await a$4.encapsulateAsymmetric(p);a$2.info("[LiopClient] Sealing WASM Payload and Inputs...");let T=o||Buffer.from(""),{ciphertext:A,nonce:S}=M.encryptPayload(T,g),_={},I=await import('crypto');for(let[y,h]of Object.entries(e.arguments||{})){let m=I.randomBytes(12),d=I.createCipheriv("aes-256-gcm",g,m),w=Buffer.concat([d.update(JSON.stringify(h)),d.final()]),l=d.getAuthTag();_[y]=Buffer.concat([m,w,l]);}let U={session_token:f,wasm_binary:A,inputs:_,pqc_ciphertext:C,aes_nonce:S};return new Promise((y,h)=>{let m=i.executeLogic(U);if(!m){h(new Error("RPC Client unavailable or failed to create stream."));return}let d=false,w=false;m.on("data",async l=>{if(!d){w=true,a$2.info("[LiopClient] Logic Executed. Verification in progress...");try{if(!l.is_error&&!await this.verifier.verifyZkReceipt(T,Buffer.from(l.cryptographic_proof).toString("hex"),Buffer.from(l.zk_receipt),Buffer.from(g),l.semantic_evidence)){h(new Error("PROTOCOL INTEGRITY VIOLATION: ZK-Receipt verification failed."));return}d=!0,y({content:[{type:"text",text:l.semantic_evidence}],isError:l.is_error});}catch(P){h(P);}}}),m.on("error",l=>{d||(a$2.error("[LiopClient] Stream Error:",l),h(l));}),m.on("end",()=>{!w&&!d&&h(new Error("Logic-on-Origin stream closed without results."));});})}getOrCreateRpcClient(e,o){let t=this.rpcClients.get(e);if(!t){let i=this.oauthToken,n=this.manifests.get(e),s=e;if(!n){for(let[f,C]of this.manifests.entries())if(C.tools.some(g=>g.name===e)){n=C,s=f;break}}let c=n?.serverInfo?.name?.toLowerCase()||"",a,p=n?.tokenSlug;if(p&&(a=process.env[`LIOP_TOKEN_${p}`]||process.env[`LIOP_OAUTH_TOKEN_${p}`]),!a&&s){let f=s.slice(-8).toUpperCase();a=process.env[`LIOP_TOKEN_${f}`]||process.env[`LIOP_OAUTH_TOKEN_${f}`];}if(!a&&c){let f=c.toUpperCase().replace(/[^A-Z0-9_]/g,"_");a=process.env[`LIOP_TOKEN_${f}`]||process.env[`LIOP_OAUTH_TOKEN_${f}`];}a&&(a$2.info(`[LiopClient] Resolved node-specific token for peer ${s.slice(-8)} (${c||"unknown"})`),i=a),t=new v(o,this.tlsOptions,i),this.rpcClients.set(e,t);}return t}async readResource(e){if(!this.meshNode)throw new Error("Client must be connected before reading resources.");a$2.info(`[LiopClient] Querying Mesh for Resource: ${e}...`);let o=await this.meshNode.findProviders(e);if(o.length===0)throw new Error(`No mesh providers found for resource: ${e}`);let t=await this.meshNode.queryManifest(o[0]);if(!t)throw new Error("Target peer did not return a valid LIOP Manifest.");let i=t.resources?.find(n=>n.uri===e);if(!i)throw new Error(`Resource ${e} not listed in remote manifest.`);return {contents:[{uri:e,mimeType:i.mimeType||"application/json",text:JSON.stringify(i,null,2)}]}}getServerInfo(){return this.serverInfo}async close(){this.meshNode&&await this.meshNode.stop();}};
2
- export{v as a,x as b};//# sourceMappingURL=chunk-T3L6OCM3.js.map
3
- //# sourceMappingURL=chunk-T3L6OCM3.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/rpc/client.ts","../src/rpc/crypto/aes.ts","../src/client/index.ts"],"names":["LiopRpcClient","address","tls","token","credentials","createChannelCredentials","liopV1","request","resolve","reject","metadata","error","response","AesGcmWrapper","payload","sharedSecret","nonce","randomBytes","cipher","createCipheriv","encrypted","authTag","ciphertextBuffer","encryptedData","decipher","createDecipheriv","LiopClient","LiopVerifier","authOpts","tokenUrl","log","params","text","data","options","clientId","clientSecret","nexusUrl","audience","scope","err","MeshNode","toolName","providers","providerId","grpcPort","manifest","addrs","maddr","parts","grpcHost","providerIds","tools","seenNames","peerId","tool","_wasmPayload","rpcClient","dynamicAddress","agentDid","intentPayload","proofOfIntent","intentResponse","publicKey","sessionToken","kyberCiphertext","Kyber768Wrapper","_safePayload","encryptedWasm","aesNonce","encryptedInputs","crypto","key","value","inputNonce","logicRequest","stream","resultFulfilled","hasReceivedData","client","nodeToken","realPeerId","pId","m","t","providerName","envToken","slug","shortId","cleanName","uri","resourceDef","r"],"mappings":"mTAcO,IAAMA,EAAN,KAAoB,CAElB,OACA,KAAA,CAER,WAAA,CAAYC,CAAAA,CAAiBC,CAAAA,CAAsBC,EAAgB,CAClE,IAAMC,EAAcC,CAAAA,CAAyBH,CAAG,EAChD,IAAA,CAAK,MAAA,CAAS,IAAII,CAAAA,CAAO,UAAUL,CAAAA,CAASG,CAAW,EACvD,IAAA,CAAK,KAAA,CAAQD,EACd,CAMA,MAAa,gBACZI,CAAAA,CAC0B,CAC1B,OAAO,IAAI,OAAA,CAAQ,CAACC,CAAAA,CAASC,CAAAA,GAAW,CACvC,IAAMC,CAAAA,CAAW,IAAS,CAAA,CAAA,QAAA,CACtB,KAAK,KAAA,EACRA,CAAAA,CAAS,IAAI,eAAA,CAAiB,CAAA,OAAA,EAAU,KAAK,KAAK,CAAA,CAAE,CAAA,CAErD,IAAA,CAAK,OAAO,eAAA,CACXH,CAAAA,CACAG,EACA,CAACC,CAAAA,CAAiCC,IAA6B,CAC1DD,CAAAA,CACHF,CAAAA,CAAOE,CAAK,EAEZH,CAAAA,CAAQI,CAAQ,EAElB,CACD,EACD,CAAC,CACF,CAMO,aACNL,CAA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,EACxB,MAAM,IAAI,MAAM,CAAA,sCAAA,EAAyC+C,CAAG,CAAA,CAAE,CAAA,CAI/D,IAAM5C,CAAAA,CAAW,MAAM,KAAK,QAAA,CAAS,aAAA,CAAcH,EAAU,CAAC,CAAC,CAAA,CAC/D,GAAI,CAACG,CAAAA,CACJ,MAAM,IAAI,KAAA,CAAM,mDAAmD,EAIpE,IAAM6C,CAAAA,CAAc7C,EAAS,SAAA,EAAW,IAAA,CAAM8C,GAAMA,CAAAA,CAAE,GAAA,GAAQF,CAAG,CAAA,CACjE,GAAI,CAACC,CAAAA,CACJ,MAAM,IAAI,KAAA,CAAM,YAAYD,CAAG,CAAA,+BAAA,CAAiC,EAIjE,OAAO,CACN,SAAU,CACT,CACC,IAAAA,CAAAA,CACA,QAAA,CAAUC,EAAY,QAAA,EAAY,kBAAA,CAClC,KAAM,IAAA,CAAK,SAAA,CAAUA,EAAa,IAAA,CAAM,CAAC,CAC1C,CACD,CACD,CACD,CAEO,eAA+D,CACrE,OAAO,KAAK,UACb,CAKA,MAAa,KAAA,EAAuB,CAC/B,KAAK,QAAA,EACR,MAAM,KAAK,QAAA,CAAS,IAAA,GAEtB,CACD","file":"chunk-T3L6OCM3.js","sourcesContent":["import * as grpc from \"@grpc/grpc-js\";\nimport { liopV1 } from \"./proto.js\";\nimport { createChannelCredentials, type LiopTlsOptions } from \"./tls.js\";\nimport type {\n\tIntentRequest,\n\tIntentResponse,\n\tLogicRequest,\n\tLogicResponse,\n} from \"./types.js\";\n\n/**\n * LIOP gRPC Client Implementation\n * Provides a high-level interface for secure intent negotiation and logic execution.\n */\nexport class LiopRpcClient {\n\t// biome-ignore lint/suspicious/noExplicitAny: internal gRPC client type\n\tprivate client: any;\n\tprivate token?: string;\n\n\tconstructor(address: string, tls?: LiopTlsOptions, token?: string) {\n\t\tconst credentials = createChannelCredentials(tls);\n\t\tthis.client = new liopV1.LogicMesh(address, credentials);\n\t\tthis.token = token;\n\t}\n\n\t/**\n\t * Negotiates intent with the remote host.\n\t * Returns the ephemeral Kyber public key for payload encryption.\n\t */\n\tpublic async negotiateIntent(\n\t\trequest: IntentRequest,\n\t): Promise<IntentResponse> {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst metadata = new grpc.Metadata();\n\t\t\tif (this.token) {\n\t\t\t\tmetadata.add(\"authorization\", `Bearer ${this.token}`);\n\t\t\t}\n\t\t\tthis.client.NegotiateIntent(\n\t\t\t\trequest,\n\t\t\t\tmetadata,\n\t\t\t\t(error: grpc.ServiceError | null, response: IntentResponse) => {\n\t\t\t\t\tif (error) {\n\t\t\t\t\t\treject(error);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tresolve(response);\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t);\n\t\t});\n\t}\n\n\t/**\n\t * Pushes the encrypted Logic-on-Origin payload to the origin.\n\t * Returns a stream of semantic responses and ZK proofs.\n\t */\n\tpublic executeLogic(\n\t\trequest: LogicRequest,\n\t): grpc.ClientReadableStream<LogicResponse> {\n\t\tconst metadata = new grpc.Metadata();\n\t\tif (this.token) {\n\t\t\tmetadata.add(\"authorization\", `Bearer ${this.token}`);\n\t\t}\n\t\treturn this.client.ExecuteLogic(request, metadata);\n\t}\n\n\tpublic close(): void {\n\t\tthis.client.close();\n\t}\n}\n","import { createCipheriv, createDecipheriv, randomBytes } from \"node:crypto\";\n\n/**\n * LIOP Symmetric Payload Encryption Wrapper\n * Uses AES-256-GCM to secure WASM Code transport over Zero-Trust networks.\n * Fully compatible with the `aes-gcm` Rust crate used by Wasmtime.\n */\nexport const AesGcmWrapper = {\n\t/**\n\t * Encrypts a raw WASM payload using the shared secret negotiated via Kyber768.\n\t *\n\t * @param payload Raw incoming WASM byte array or string.\n\t * @param sharedSecret A perfectly derived 32-byte (256-bit) shared secret array\n\t * @returns The encrypted buffer to push to the GRPc stream, along with the 12-byte initialization vector natively generated.\n\t */\n\tencryptPayload(\n\t\tpayload: Uint8Array | Buffer,\n\t\tsharedSecret: Uint8Array,\n\t): {\n\t\tciphertext: Buffer;\n\t\tnonce: Buffer;\n\t} {\n\t\tif (sharedSecret.length !== 32) {\n\t\t\tthrow new Error(\"Symmetric Key must be exactly 32 bytes (256 bits).\");\n\t\t}\n\n\t\t// LIOP standard demands 96-bit (12 byte) IVs/Nonces for AES-GCM\n\t\tconst nonce = randomBytes(12);\n\n\t\tconst cipher = createCipheriv(\"aes-256-gcm\", sharedSecret, nonce);\n\n\t\t// Encrypt the payload and seal the tag\n\t\tconst encrypted = Buffer.concat([cipher.update(payload), cipher.final()]);\n\t\tconst authTag = cipher.getAuthTag(); // 16 bytes for GCM integrity\n\n\t\t// In LIOP, the auth tag is strictly appended to the end of the ciphertext bytes\n\t\t// mirroring the default serialization logic within `aes_gcm::Aes256Gcm` in Rust\n\t\tconst finalCiphertext = Buffer.concat([encrypted, authTag]);\n\n\t\treturn {\n\t\t\tciphertext: finalCiphertext,\n\t\t\tnonce: nonce,\n\t\t};\n\t},\n\n\t/**\n\t * Decrypts a remote Zero-Knowledge receipt using AES-256-GCM.\n\t */\n\tdecryptPayload(\n\t\tciphertextBuffer: Buffer,\n\t\tnonce: Buffer,\n\t\tsharedSecret: Uint8Array,\n\t): Buffer {\n\t\tif (ciphertextBuffer.length < 16) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Invalid GCM Ciphertext; missing authentication tag length\",\n\t\t\t);\n\t\t}\n\n\t\t// The last 16 bytes represent the AuthTag appended by rust-aes-gcm\n\t\tconst encryptedData = ciphertextBuffer.subarray(0, -16);\n\t\tconst authTag = ciphertextBuffer.subarray(-16);\n\n\t\tconst decipher = createDecipheriv(\"aes-256-gcm\", sharedSecret, nonce);\n\t\tdecipher.setAuthTag(authTag);\n\n\t\treturn Buffer.concat([decipher.update(encryptedData), decipher.final()]);\n\t},\n};\n","import { LiopVerifier } from \"../crypto/verifier.js\";\nimport {\n\ttype LiopManifest,\n\tMeshNode,\n\ttype MeshNodeConfig,\n} from \"../mesh/node.js\";\nimport { LiopRpcClient } from \"../rpc/client.js\";\nimport { AesGcmWrapper } from \"../rpc/crypto/aes.js\";\nimport { Kyber768Wrapper } from \"../rpc/crypto/kyber.js\";\nimport type { LiopTlsOptions } from \"../rpc/tls.js\";\nimport type { LogicRequest, LogicResponse } from \"../rpc/types.js\";\nimport type { CallToolRequest, CallToolResult } from \"../types.js\";\nimport { log } from \"../utils/logger.js\";\n\n/**\n * LIOP Client\n * High-level orchestration for discovery and execution in the Logic-Injection-on-Origin mesh.\n */\nexport class LiopClient {\n\tprivate meshNode: MeshNode | null = null;\n\tprivate rpcClients: Map<string, LiopRpcClient> = new Map();\n\tprivate manifests: Map<string, LiopManifest> = new Map();\n\tprivate tlsOptions?: LiopTlsOptions;\n\tprivate serverInfo?: { name: string; version: string };\n\tpublic verifier: LiopVerifier = new LiopVerifier();\n\tprivate oauthToken?: string;\n\n\tconstructor(tls?: LiopTlsOptions) {\n\t\tthis.tlsOptions = tls;\n\t}\n\n\t/**\n\t * Requests an M2M access token from the Nexus Authorization Server using Client Credentials.\n\t */\n\tprivate async acquireM2MToken(authOpts: {\n\t\tclientId: string;\n\t\tclientSecret: string;\n\t\tnexusUrl: string;\n\t\taudience: string;\n\t\tscope?: string;\n\t}): Promise<string> {\n\t\tconst baseUrl = authOpts.nexusUrl.endsWith(\"/oidc\")\n\t\t\t? authOpts.nexusUrl\n\t\t\t: `${authOpts.nexusUrl}/oidc`;\n\t\tconst tokenUrl = `${baseUrl}/token`;\n\t\tlog.info(`[LiopClient] Requesting M2M Token from Nexus AS: ${tokenUrl}`);\n\n\t\tconst params = new URLSearchParams({\n\t\t\tgrant_type: \"client_credentials\",\n\t\t\tscope:\n\t\t\t\tauthOpts.scope ||\n\t\t\t\t\"liop:tools:call liop:tools:list liop:resources:read liop:schema:read liop:mesh:query\",\n\t\t\tresource: authOpts.audience,\n\t\t\tclient_id: authOpts.clientId,\n\t\t\tclient_secret: authOpts.clientSecret,\n\t\t});\n\n\t\tconst response = await fetch(tokenUrl, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: {\n\t\t\t\t\"Content-Type\": \"application/x-www-form-urlencoded\",\n\t\t\t},\n\t\t\tbody: params.toString(),\n\t\t});\n\n\t\tif (!response.ok) {\n\t\t\tconst text = await response.text();\n\t\t\tthrow new Error(\n\t\t\t\t`OAuth token request failed with status ${response.status}: ${text}`,\n\t\t\t);\n\t\t}\n\n\t\tconst data = (await response.json()) as {\n\t\t\taccess_token: string;\n\t\t\texpires_in?: number;\n\t\t};\n\t\tif (!data.access_token) {\n\t\t\tthrow new Error(\"OAuth token response did not contain an access_token.\");\n\t\t}\n\n\t\tlog.info(\"[LiopClient] M2M Token acquired successfully.\");\n\t\treturn data.access_token;\n\t}\n\n\t/**\n\t * Discovers and connects to the target server or mesh capability.\n\t * If address is omitted, it sets up the MeshNode to act purely dynamically.\n\t */\n\tpublic async connect(\n\t\taddress?: string,\n\t\toptions?: {\n\t\t\tmeshConfig?: MeshNodeConfig;\n\t\t\tauth?: {\n\t\t\t\tclientId?: string;\n\t\t\t\tclientSecret?: string;\n\t\t\t\tnexusUrl?: string;\n\t\t\t\taudience?: string;\n\t\t\t\tscope?: string;\n\t\t\t\ttoken?: string;\n\t\t\t};\n\t\t},\n\t): Promise<void> {\n\t\t// Attempt to acquire OAuth M2M access token if credentials are provided\n\t\tconst clientId =\n\t\t\toptions?.auth?.clientId ||\n\t\t\tprocess.env.LIOP_OAUTH_CLIENT_ID ||\n\t\t\tprocess.env.LIOP_CLIENT_ID;\n\t\tconst clientSecret =\n\t\t\toptions?.auth?.clientSecret ||\n\t\t\tprocess.env.LIOP_OAUTH_CLIENT_SECRET ||\n\t\t\tprocess.env.LIOP_CLIENT_SECRET;\n\t\tconst nexusUrl =\n\t\t\toptions?.auth?.nexusUrl ||\n\t\t\tprocess.env.LIOP_NEXUS_URL ||\n\t\t\t\"http://localhost:3000\";\n\t\tconst audience =\n\t\t\toptions?.auth?.audience ||\n\t\t\tprocess.env.LIOP_OAUTH_AUDIENCE ||\n\t\t\t\"urn:liop:mesh:api\";\n\t\tconst scope =\n\t\t\toptions?.auth?.scope ||\n\t\t\tprocess.env.LIOP_OAUTH_SCOPE ||\n\t\t\t\"liop:tools:call liop:tools:list liop:resources:read liop:schema:read liop:mesh:query\";\n\n\t\tthis.oauthToken =\n\t\t\toptions?.auth?.token ||\n\t\t\tprocess.env.LIOP_OAUTH_TOKEN ||\n\t\t\tprocess.env.LIOP_TOKEN;\n\n\t\tif (clientId && clientSecret) {\n\t\t\ttry {\n\t\t\t\tthis.oauthToken = await this.acquireM2MToken({\n\t\t\t\t\tclientId,\n\t\t\t\t\tclientSecret,\n\t\t\t\t\tnexusUrl,\n\t\t\t\t\taudience,\n\t\t\t\t\tscope,\n\t\t\t\t});\n\t\t\t} catch (err: unknown) {\n\t\t\t\tlog.error(\n\t\t\t\t\t`[LiopClient] Failed to acquire OAuth M2M Token: ${\n\t\t\t\t\t\terr instanceof Error ? err.message : String(err)\n\t\t\t\t\t}`,\n\t\t\t\t);\n\t\t\t\t// In development or when using static local token, allow connection to proceed\n\t\t\t}\n\t\t}\n\n\t\tthis.meshNode = new MeshNode(options?.meshConfig);\n\t\tawait this.meshNode.start();\n\t\tlog.info(\n\t\t\t`[LiopClient] Mesh Node synchronized. PeerID: ${this.meshNode.getPeerId()}`,\n\t\t);\n\n\t\tif (address) {\n\t\t\tthis.rpcClients.set(\n\t\t\t\t\"static\",\n\t\t\t\tnew LiopRpcClient(address, this.tlsOptions, this.oauthToken),\n\t\t\t);\n\t\t\tthis.serverInfo = { name: `LiopServer (${address})`, version: \"1.0.0\" };\n\t\t\tlog.info(`[LiopClient] Static gRPC configured for: ${address}`);\n\t\t} else {\n\t\t\tthis.serverInfo = { name: \"LiopServer (Mesh Alpha)\", version: \"1.0.0\" };\n\t\t}\n\t}\n\n\t/**\n\t * Dynamically queries Kademlia DHT to find the optimal PeerID providing the Capability\n\t * and returns the physical gRPC target (host:port) resolved from the provider's manifest.\n\t */\n\tpublic async resolveCapability(toolName: string): Promise<string> {\n\t\tif (!this.meshNode)\n\t\t\tthrow new Error(\n\t\t\t\t\"Client must be connected to Mesh to resolve capabilities.\",\n\t\t\t);\n\n\t\tlog.info(`[LiopClient] Querying Mesh DHT for Provider: ${toolName}...`);\n\t\tconst providers = await this.meshNode.findProviders(toolName);\n\n\t\tif (providers.length === 0) {\n\t\t\tthrow new Error(\n\t\t\t\t`Kademlia DHT found zero providers for capability: ${toolName}`,\n\t\t\t);\n\t\t}\n\n\t\tconst providerId = providers[0];\n\t\tlog.info(`[LiopClient] Identified Alpha Provider PeerID: ${providerId}`);\n\n\t\tlet grpcPort = 50051;\n\t\tconst manifest = await this.meshNode.queryManifest(providerId);\n\t\tif (manifest) {\n\t\t\tgrpcPort = manifest.grpcPort;\n\t\t\tlog.info(`[LiopClient] Manifest resolved: gRPC port ${grpcPort}`);\n\t\t}\n\n\t\tconst addrs = await this.meshNode.resolvePeer(providerId);\n\t\tfor (const maddr of addrs) {\n\t\t\tconst parts = maddr.split(\"/\");\n\t\t\tif (parts[1] === \"ip4\") {\n\t\t\t\tconst grpcHost = `${parts[2]}:${grpcPort}`;\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LiopClient] Translated Multiaddr to gRPC Target: ${grpcHost}`,\n\t\t\t\t);\n\t\t\t\treturn grpcHost;\n\t\t\t}\n\t\t}\n\n\t\treturn `127.0.0.1:${grpcPort}`;\n\t}\n\n\t/**\n\t * Discovers remote capabilities via the LIOP Manifest Protocol.\n\t */\n\tpublic async discoverTools(): Promise<\n\t\t{ name: string; description?: string }[]\n\t> {\n\t\tif (!this.meshNode) {\n\t\t\tthrow new Error(\"Client must be connected before discovering tools.\");\n\t\t}\n\n\t\tlog.info(`[LiopClient] Discovery started...`);\n\t\tconst providerIds = await this.meshNode.discoverManifestProviders();\n\t\tconst tools: { name: string; description?: string }[] = [];\n\t\tconst seenNames = new Set<string>();\n\n\t\tfor (const peerId of providerIds) {\n\t\t\ttry {\n\t\t\t\tlog.info(`[LiopClient] Querying manifest from: ${peerId}`);\n\t\t\t\tconst manifest = await this.meshNode.queryManifest(peerId);\n\t\t\t\tif (manifest) {\n\t\t\t\t\tthis.manifests.set(peerId, manifest);\n\t\t\t\t\tfor (const tool of manifest.tools) {\n\t\t\t\t\t\tif (!seenNames.has(tool.name)) {\n\t\t\t\t\t\t\ttools.push({ name: tool.name, description: tool.description });\n\t\t\t\t\t\t\tseenNames.add(tool.name);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} catch (err: unknown) {\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LiopClient] Error querying manifest from ${peerId}:`,\n\t\t\t\t\terr instanceof Error ? err.message : String(err),\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tlog.info(\n\t\t\t`[LiopClient] Discovery finished. Found ${tools.length} unique tools.`,\n\t\t);\n\t\treturn tools;\n\t}\n\n\t/**\n\t * Invokes a tool.\n\t */\n\tpublic async callTool(\n\t\trequest: CallToolRequest,\n\t\t_wasmPayload?: Buffer,\n\t): Promise<CallToolResult> {\n\t\tif (!this.meshNode) {\n\t\t\tthrow new Error(\"Client must be connected before calling tools.\");\n\t\t}\n\n\t\tconst toolName = request.name;\n\t\tlog.info(`[LiopClient] Resolving Tool: ${toolName}`);\n\n\t\t// [ALPHA-FIX] Bypass DHT discovery if we are already statically connected to a provider (Enterprise/Test mode)\n\t\tlet rpcClient = this.rpcClients.get(\"static\");\n\n\t\tif (!rpcClient) {\n\t\t\tconst dynamicAddress = await this.resolveCapability(toolName);\n\t\t\trpcClient = this.getOrCreateRpcClient(toolName, dynamicAddress);\n\t\t} else {\n\t\t\tlog.info(\n\t\t\t\t`[LiopClient] Using existing static gRPC connection for ${toolName}.`,\n\t\t\t);\n\t\t}\n\n\t\tlog.info(`[LiopClient] Negotiating intent for ${toolName}...`);\n\t\tconst agentDid = this.meshNode\n\t\t\t? `did:liop:${this.meshNode.getPeerId()}`\n\t\t\t: \"did:liop:ephemeral\";\n\t\tconst intentPayload = Buffer.from(`${toolName}:${Date.now()}`);\n\t\tconst proofOfIntent = this.meshNode\n\t\t\t? await this.meshNode.sign(intentPayload)\n\t\t\t: intentPayload;\n\n\t\tconst intentResponse = (await rpcClient.negotiateIntent({\n\t\t\tagent_did: agentDid,\n\t\t\tcapability_hash: toolName,\n\t\t\tproof_of_intent: proofOfIntent,\n\t\t})) as unknown as {\n\t\t\taccepted: boolean;\n\t\t\terror_message: string;\n\t\t\tkyber_public_key: Uint8Array;\n\t\t\tkyberPublicKey: Uint8Array;\n\t\t\tsession_token: string;\n\t\t\tsessionToken: string;\n\t\t};\n\n\t\tif (!intentResponse.accepted) {\n\t\t\tthrow new Error(`Intent denied by host: ${intentResponse.error_message}`);\n\t\t}\n\n\t\t// LIOP Robust Field Extraction (Supports both snake_case and camelCase via gRPC-JS)\n\t\tconst publicKey =\n\t\t\tintentResponse.kyber_public_key || intentResponse.kyberPublicKey;\n\t\tconst sessionToken =\n\t\t\tintentResponse.session_token || intentResponse.sessionToken;\n\n\t\tif (!publicKey) {\n\t\t\tlog.info(\n\t\t\t\t\"[LiopClient] Critical Error: Kyber Public Key not found in IntentResponse.\",\n\t\t\t\tintentResponse,\n\t\t\t);\n\t\t\tthrow new Error(\n\t\t\t\t\"Handshake failed: Remote host did not provide a valid Kyber Public Key.\",\n\t\t\t);\n\t\t}\n\n\t\t// 2. Post-Quantum Encapsulation (ML-KEM-768)\n\t\tlog.info(\n\t\t\t`[LiopClient] Encapsulating Post-Quantum Shared Secret for ${request.name}...`,\n\t\t);\n\t\tconst { ciphertext: kyberCiphertext, sharedSecret } =\n\t\t\tawait Kyber768Wrapper.encapsulateAsymmetric(publicKey);\n\n\t\t// 3. Symmetric Sealing (AES-256-GCM)\n\t\tlog.info(`[LiopClient] Sealing WASM Payload and Inputs...`);\n\n\t\tconst _safePayload = _wasmPayload || Buffer.from(\"\");\n\n\t\t// Encrypt WASM binary\n\t\tconst { ciphertext: encryptedWasm, nonce: aesNonce } =\n\t\t\tAesGcmWrapper.encryptPayload(_safePayload, sharedSecret);\n\n\t\t// Encrypt inputs using a fresh random nonce per input to prevent AES-GCM nonce reuse\n\t\tconst encryptedInputs: Record<string, Uint8Array> = {};\n\t\tconst crypto = await import(\"node:crypto\");\n\t\tfor (const [key, value] of Object.entries(request.arguments || {})) {\n\t\t\tconst inputNonce = crypto.randomBytes(12);\n\t\t\tconst cipher = crypto.createCipheriv(\n\t\t\t\t\"aes-256-gcm\",\n\t\t\t\tsharedSecret,\n\t\t\t\tinputNonce,\n\t\t\t);\n\t\t\tconst encrypted = Buffer.concat([\n\t\t\t\tcipher.update(JSON.stringify(value)),\n\t\t\t\tcipher.final(),\n\t\t\t]);\n\t\t\tconst authTag = cipher.getAuthTag();\n\t\t\t// Prepend the 12-byte nonce to the ciphertext\n\t\t\tencryptedInputs[key] = Buffer.concat([inputNonce, encrypted, authTag]);\n\t\t}\n\n\t\t// 4. Assemble and Execute gRPC LogicRequest\n\t\tconst logicRequest: LogicRequest = {\n\t\t\tsession_token: sessionToken,\n\t\t\twasm_binary: encryptedWasm,\n\t\t\tinputs: encryptedInputs,\n\t\t\tpqc_ciphertext: kyberCiphertext,\n\t\t\taes_nonce: aesNonce,\n\t\t};\n\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst stream = rpcClient.executeLogic(logicRequest);\n\t\t\tif (!stream) {\n\t\t\t\treject(new Error(\"RPC Client unavailable or failed to create stream.\"));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tlet resultFulfilled = false;\n\t\t\tlet hasReceivedData = false;\n\n\t\t\tstream.on(\"data\", async (response: LogicResponse) => {\n\t\t\t\tif (resultFulfilled) return;\n\t\t\t\thasReceivedData = true;\n\n\t\t\t\tlog.info(\"[LiopClient] Logic Executed. Verification in progress...\");\n\n\t\t\t\ttry {\n\t\t\t\t\t// Only verify ZK-Receipt if the remote execution succeeded.\n\t\t\t\t\t// If the remote execution failed due to a policy error (e.g. Egress Shield),\n\t\t\t\t\t// the ZK proof is empty and we should bypass validation to propagate the original error.\n\t\t\t\t\tif (!response.is_error) {\n\t\t\t\t\t\tconst isValid = await this.verifier.verifyZkReceipt(\n\t\t\t\t\t\t\t_safePayload,\n\t\t\t\t\t\t\tBuffer.from(response.cryptographic_proof).toString(\"hex\"),\n\t\t\t\t\t\t\tBuffer.from(response.zk_receipt),\n\t\t\t\t\t\t\tBuffer.from(sharedSecret),\n\t\t\t\t\t\t\tresponse.semantic_evidence,\n\t\t\t\t\t\t);\n\n\t\t\t\t\t\tif (!isValid) {\n\t\t\t\t\t\t\treject(\n\t\t\t\t\t\t\t\tnew Error(\n\t\t\t\t\t\t\t\t\t\"PROTOCOL INTEGRITY VIOLATION: ZK-Receipt verification failed.\",\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tresultFulfilled = true;\n\t\t\t\t\tresolve({\n\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\ttext: response.semantic_evidence,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t\tisError: response.is_error,\n\t\t\t\t\t});\n\t\t\t\t} catch (err) {\n\t\t\t\t\treject(err);\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tstream.on(\"error\", (err) => {\n\t\t\t\tif (resultFulfilled) return;\n\t\t\t\tlog.error(\"[LiopClient] Stream Error:\", err);\n\t\t\t\treject(err);\n\t\t\t});\n\n\t\t\tstream.on(\"end\", () => {\n\t\t\t\t// We don't throw here if we already received a response block that is currently\n\t\t\t\t// undergoing ZK Verification in the Piscina worker pool.\n\t\t\t\tif (!hasReceivedData && !resultFulfilled) {\n\t\t\t\t\treject(new Error(\"Logic-on-Origin stream closed without results.\"));\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t}\n\n\tprivate getOrCreateRpcClient(peerId: string, address: string): LiopRpcClient {\n\t\tlet client = this.rpcClients.get(peerId);\n\t\tif (!client) {\n\t\t\tlet nodeToken = this.oauthToken;\n\n\t\t\tlet manifest = this.manifests.get(peerId);\n\t\t\tlet realPeerId = peerId;\n\n\t\t\t// If peerId is actually a toolName (which happens when called from callTool),\n\t\t\t// resolve the real PeerID and its manifest from the manifest cache.\n\t\t\tif (!manifest) {\n\t\t\t\tfor (const [pId, m] of this.manifests.entries()) {\n\t\t\t\t\tif (m.tools.some((t) => t.name === peerId)) {\n\t\t\t\t\t\tmanifest = m;\n\t\t\t\t\t\trealPeerId = pId;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst providerName = manifest?.serverInfo?.name?.toLowerCase() || \"\";\n\t\t\tlet envToken: string | undefined;\n\n\t\t\t// 0. Deterministic tokenSlug resolution (highest priority, zero heuristic)\n\t\t\tconst slug = manifest?.tokenSlug;\n\t\t\tif (slug) {\n\t\t\t\tenvToken =\n\t\t\t\t\tprocess.env[`LIOP_TOKEN_${slug}`] ||\n\t\t\t\t\tprocess.env[`LIOP_OAUTH_TOKEN_${slug}`];\n\t\t\t}\n\n\t\t\t// 1. PeerID-specific resolution: LIOP_TOKEN_<last 8 chars of PeerID in uppercase>\n\t\t\tif (!envToken && realPeerId) {\n\t\t\t\tconst shortId = realPeerId.slice(-8).toUpperCase();\n\t\t\t\tenvToken =\n\t\t\t\t\tprocess.env[`LIOP_TOKEN_${shortId}`] ||\n\t\t\t\t\tprocess.env[`LIOP_OAUTH_TOKEN_${shortId}`];\n\t\t\t}\n\n\t\t\t// 2. Provider-name resolution: LIOP_TOKEN_<CLEAN_PROVIDER_NAME_UPPERCASE>\n\t\t\tif (!envToken && providerName) {\n\t\t\t\tconst cleanName = providerName\n\t\t\t\t\t.toUpperCase()\n\t\t\t\t\t.replace(/[^A-Z0-9_]/g, \"_\");\n\t\t\t\tenvToken =\n\t\t\t\t\tprocess.env[`LIOP_TOKEN_${cleanName}`] ||\n\t\t\t\t\tprocess.env[`LIOP_OAUTH_TOKEN_${cleanName}`];\n\t\t\t}\n\n\t\t\tif (envToken) {\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LiopClient] Resolved node-specific token for peer ${realPeerId.slice(-8)} (${providerName || \"unknown\"})`,\n\t\t\t\t);\n\t\t\t\tnodeToken = envToken;\n\t\t\t}\n\n\t\t\tclient = new LiopRpcClient(address, this.tlsOptions, nodeToken);\n\t\t\tthis.rpcClients.set(peerId, client);\n\t\t}\n\t\treturn client;\n\t}\n\n\t/**\n\t * Reads a specific resource by URI.\n\t * In LIOP, resources can be static definitions or dynamic streams.\n\t */\n\tpublic async readResource(uri: string): Promise<{\n\t\tcontents: Array<{ uri: string; mimeType?: string; text: string }>;\n\t}> {\n\t\tif (!this.meshNode) {\n\t\t\tthrow new Error(\"Client must be connected before reading resources.\");\n\t\t}\n\t\tlog.info(`[LiopClient] Querying Mesh for Resource: ${uri}...`);\n\n\t\t// We search for the peer hosting the resource in the P2P Mesh\n\t\tconst providers = await this.meshNode.findProviders(uri);\n\t\tif (providers.length === 0) {\n\t\t\tthrow new Error(`No mesh providers found for resource: ${uri}`);\n\t\t}\n\n\t\t// Query the remote peer's manifest\n\t\tconst manifest = await this.meshNode.queryManifest(providers[0]);\n\t\tif (!manifest) {\n\t\t\tthrow new Error(\"Target peer did not return a valid LIOP Manifest.\");\n\t\t}\n\n\t\t// Locate the exact resource metadata\n\t\tconst resourceDef = manifest.resources?.find((r) => r.uri === uri);\n\t\tif (!resourceDef) {\n\t\t\tthrow new Error(`Resource ${uri} not listed in remote manifest.`);\n\t\t}\n\n\t\t// Return the declarative metadata (Logic-Injection is required for actual data extraction)\n\t\treturn {\n\t\t\tcontents: [\n\t\t\t\t{\n\t\t\t\t\turi,\n\t\t\t\t\tmimeType: resourceDef.mimeType || \"application/json\",\n\t\t\t\t\ttext: JSON.stringify(resourceDef, null, 2),\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\n\tpublic getServerInfo(): { name: string; version: string } | undefined {\n\t\treturn this.serverInfo;\n\t}\n\n\t/**\n\t * Destroys the active Mesh Node resources.\n\t */\n\tpublic async close(): Promise<void> {\n\t\tif (this.meshNode) {\n\t\t\tawait this.meshNode.stop();\n\t\t}\n\t}\n}\n"]}
@@ -1,2 +0,0 @@
1
- import {a}from'./chunk-S6RJHZV2.js';import i from'path';import {fileURLToPath}from'url';import*as o from'@grpc/grpc-js';import*as d from'@grpc/proto-loader';import*as n from'fs';var S=fileURLToPath(import.meta.url),s=i.dirname(S),m=[i.resolve(s,"./protocol/liop_core.proto"),i.resolve(s,"../protocol/liop_core.proto")],C=i.resolve(s,"../../../../protocol/proto/liop_core.proto"),p=m.find(e=>n.existsSync(e))||C;n.existsSync(p)||a.error(`[LIOP-Proto] CRITICAL: Proto file not found at ${p}`);var v=d.loadSync(p,{keepCase:true,longs:String,enums:String,defaults:true,oneofs:true}),L=o.loadPackageDefinition(v),P=L.liop.v1;var u=()=>process.env.NODE_ENV==="production";function A(e){if(!e?.certChain||!e?.privateKey)return a.warn("[LIOP-TLS] No TLS certificates configured \u2014 using insecure server credentials"),o.ServerCredentials.createInsecure();try{let r=e.rootCert?n.readFileSync(e.rootCert):null,c=n.readFileSync(e.certChain),a=n.readFileSync(e.privateKey);return o.ServerCredentials.createSsl(r,[{cert_chain:c,private_key:a}])}catch(r){if(u())throw new Error(`[LIOP-TLS] FATAL: Server certificate loading failed in production mode. Refusing insecure fallback to prevent MITM/eavesdropping: ${r}`);return a.warn(`[LIOP-TLS] Server certificate loading failed, falling back to insecure (dev mode): ${r}`),o.ServerCredentials.createInsecure()}}function F(e){if(!e?.rootCert)return a.warn("[LIOP-TLS] No TLS root certificate configured \u2014 using insecure channel credentials"),o.credentials.createInsecure();try{let r=n.readFileSync(e.rootCert),c=e.certChain?n.readFileSync(e.certChain):void 0,a=e.privateKey?n.readFileSync(e.privateKey):void 0;return o.credentials.createSsl(r,a,c)}catch(r){if(u())throw new Error(`[LIOP-TLS] FATAL: Channel certificate loading failed in production mode. Refusing insecure fallback to prevent MITM/eavesdropping: ${r}`);return a.warn(`[LIOP-TLS] Channel certificate loading failed, falling back to insecure (dev mode): ${r}`),o.credentials.createInsecure()}}export{P as a,A as b,F as c};//# sourceMappingURL=chunk-V5MKJT6S.js.map
2
- //# sourceMappingURL=chunk-V5MKJT6S.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/rpc/proto.ts","../src/rpc/tls.ts"],"names":["__filename","fileURLToPath","__dirname","path","PROD_PATHS","DEV_PROTO_PATH","PROTO_PATH","p","l","log","packageDefinition","liopProto","f","liopV1","isProduction","createServerCredentials","tls","rootCert","certChain","privateKey","error","createChannelCredentials"],"mappings":"kLAKA,IAAMA,CAAAA,CAAaC,aAAAA,CAAc,MAAA,CAAA,IAAA,CAAY,GAAG,CAAA,CAC1CC,CAAAA,CAAYC,CAAAA,CAAK,OAAA,CAAQH,CAAU,CAAA,CAMnCI,CAAAA,CAAa,CAClBD,CAAAA,CAAK,OAAA,CAAQD,CAAAA,CAAW,4BAA4B,CAAA,CACpDC,CAAAA,CAAK,OAAA,CAAQD,CAAAA,CAAW,6BAA6B,CACtD,CAAA,CAEMG,CAAAA,CAAiBF,CAAAA,CAAK,OAAA,CAC3BD,CAAAA,CACA,4CACD,CAAA,CAGMI,CAAAA,CAAaF,CAAAA,CAAW,IAAA,CAAMG,CAAAA,EAASC,CAAA,CAAA,UAAA,CAAWD,CAAC,CAAC,CAAA,EAAKF,CAAAA,CAEvDG,CAAA,CAAA,UAAA,CAAWF,CAAU,CAAA,EAC5BG,CAAAA,CAAI,KAAA,CAAM,CAAA,+CAAA,EAAkDH,CAAU,EAAE,CAAA,CAOzE,IAAMI,CAAAA,CAAgC,CAAA,CAAA,QAAA,CAASJ,CAAAA,CAAY,CAC1D,QAAA,CAAU,IAAA,CACV,KAAA,CAAO,MAAA,CACP,KAAA,CAAO,MAAA,CACP,QAAA,CAAU,IAAA,CACV,MAAA,CAAQ,I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AAe,CAGxC,GAAI,CACH,IAAMQ,CAAAA,CAAc,CAAA,CAAA,YAAA,CAAaD,CAAAA,CAAI,QAAQ,CAAA,CACvCE,CAAAA,CAAYF,CAAAA,CAAI,SAAA,CAChB,CAAA,CAAA,YAAA,CAAaA,CAAAA,CAAI,SAAS,CAAA,CAC7B,KAAA,CAAA,CACGG,CAAAA,CAAaH,CAAAA,CAAI,UAAA,CACjB,CAAA,CAAA,YAAA,CAAaA,CAAAA,CAAI,UAAU,CAAA,CAC9B,KAAA,CAAA,CAEH,OAAY,CAAA,CAAA,WAAA,CAAY,SAAA,CAAUC,CAAAA,CAAUE,CAAAA,CAAYD,CAAS,CAClE,CAAA,MAASE,CAAAA,CAAO,CACf,GAAIN,CAAAA,EAAa,CAChB,MAAM,IAAI,KAAA,CACT,CAAA,mIAAA,EAC8DM,CAAK,CAAA,CACpE,CAAA,CAED,OAAAX,CAAAA,CAAI,IAAA,CACH,CAAA,oFAAA,EAAuFW,CAAK,CAAA,CAC7F,CAAA,CACY,CAAA,CAAA,WAAA,CAAY,cAAA,EACzB,CACD","file":"chunk-V5MKJT6S.js","sourcesContent":["import path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport * as grpc from \"@grpc/grpc-js\";\nimport * as protoLoader from \"@grpc/proto-loader\";\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = path.dirname(__filename);\n\nimport * as fs from \"node:fs\";\nimport { log } from \"../utils/logger.js\";\n\n// Selection logic: support both flat dist/ and original src/ structure\nconst PROD_PATHS = [\n\tpath.resolve(__dirname, \"./protocol/liop_core.proto\"), // Flat dist/ (tsup)\n\tpath.resolve(__dirname, \"../protocol/liop_core.proto\"), // dist/rpc/ (tsc)\n];\n\nconst DEV_PROTO_PATH = path.resolve(\n\t__dirname,\n\t\"../../../../protocol/proto/liop_core.proto\",\n);\n\n// Selection logic\nconst PROTO_PATH = PROD_PATHS.find((p) => fs.existsSync(p)) || DEV_PROTO_PATH;\n\nif (!fs.existsSync(PROTO_PATH)) {\n\tlog.error(`[LIOP-Proto] CRITICAL: Proto file not found at ${PROTO_PATH}`);\n}\n\n/**\n * LIOP Proto Loader\n * Loads the core gRPC definitions for the Logic-Injection-on-Origin Protocol.\n */\nconst packageDefinition = protoLoader.loadSync(PROTO_PATH, {\n\tkeepCase: true,\n\tlongs: String,\n\tenums: String,\n\tdefaults: true,\n\toneofs: true,\n});\n\n// biome-ignore lint/suspicious/noExplicitAny: gRPC dynamic loading requires any for the service definition map\nexport const liopProto = grpc.loadPackageDefinition(packageDefinition) as any;\nexport const liopV1 = liopProto.liop.v1;\n","/**\n * LIOP TLS Configuration\n *\n * Provides conditional TLS credential factories for gRPC connections.\n * When TLS options are provided, connections are secured with mutual TLS.\n * Otherwise, falls back to insecure credentials (alpha/development mode).\n *\n * Production Hardening (Phase 128):\n * - When NODE_ENV=production and TLS is configured but certificate loading\n * fails, the system throws a fatal error instead of silently degrading\n * to insecure credentials. This prevents MITM/eavesdropping attacks\n * caused by misconfigured certificate paths going unnoticed.\n * - Reference: gRPC-node official docs — \"Using insecure credentials in\n * production poses significant security risks including eavesdropping,\n * MITM attacks, and lack of authentication.\"\n */\n\nimport * as fs from \"node:fs\";\nimport * as grpc from \"@grpc/grpc-js\";\nimport { log } from \"../utils/logger.js\";\n\nexport interface LiopTlsOptions {\n\t/** Path to the root CA certificate (PEM format) */\n\trootCert?: string;\n\t/** Path to the server/client certificate (PEM format) */\n\tcertChain?: string;\n\t/** Path to the private key (PEM format) */\n\tprivateKey?: string;\n}\n\nconst isProduction = () => process.env.NODE_ENV === \"production\";\n\n/**\n * Creates gRPC server credentials from TLS options.\n * In production, refuses to fall back to insecure if TLS loading fails.\n */\nexport function createServerCredentials(\n\ttls?: LiopTlsOptions,\n): grpc.ServerCredentials {\n\tif (!tls?.certChain || !tls?.privateKey) {\n\t\tlog.warn(\n\t\t\t\"[LIOP-TLS] No TLS certificates configured — using insecure server credentials\",\n\t\t);\n\t\treturn grpc.ServerCredentials.createInsecure();\n\t}\n\n\ttry {\n\t\tconst rootCert = tls.rootCert ? fs.readFileSync(tls.rootCert) : null;\n\t\tconst certChain = fs.readFileSync(tls.certChain);\n\t\tconst privateKey = fs.readFileSync(tls.privateKey);\n\n\t\treturn grpc.ServerCredentials.createSsl(rootCert, [\n\t\t\t{ cert_chain: certChain, private_key: privateKey },\n\t\t]);\n\t} catch (error) {\n\t\tif (isProduction()) {\n\t\t\tthrow new Error(\n\t\t\t\t`[LIOP-TLS] FATAL: Server certificate loading failed in production mode. ` +\n\t\t\t\t\t`Refusing insecure fallback to prevent MITM/eavesdropping: ${error}`,\n\t\t\t);\n\t\t}\n\t\tlog.warn(\n\t\t\t`[LIOP-TLS] Server certificate loading failed, falling back to insecure (dev mode): ${error}`,\n\t\t);\n\t\treturn grpc.ServerCredentials.createInsecure();\n\t}\n}\n\n/**\n * Creates gRPC channel credentials from TLS options.\n * In production, refuses to fall back to insecure if TLS loading fails.\n */\nexport function createChannelCredentials(\n\ttls?: LiopTlsOptions,\n): grpc.ChannelCredentials {\n\tif (!tls?.rootCert) {\n\t\tlog.warn(\n\t\t\t\"[LIOP-TLS] No TLS root certificate configured — using insecure channel credentials\",\n\t\t);\n\t\treturn grpc.credentials.createInsecure();\n\t}\n\n\ttry {\n\t\tconst rootCert = fs.readFileSync(tls.rootCert);\n\t\tconst certChain = tls.certChain\n\t\t\t? fs.readFileSync(tls.certChain)\n\t\t\t: undefined;\n\t\tconst privateKey = tls.privateKey\n\t\t\t? fs.readFileSync(tls.privateKey)\n\t\t\t: undefined;\n\n\t\treturn grpc.credentials.createSsl(rootCert, privateKey, certChain);\n\t} catch (error) {\n\t\tif (isProduction()) {\n\t\t\tthrow new Error(\n\t\t\t\t`[LIOP-TLS] FATAL: Channel certificate loading failed in production mode. ` +\n\t\t\t\t\t`Refusing insecure fallback to prevent MITM/eavesdropping: ${error}`,\n\t\t\t);\n\t\t}\n\t\tlog.warn(\n\t\t\t`[LIOP-TLS] Channel certificate loading failed, falling back to insecure (dev mode): ${error}`,\n\t\t);\n\t\treturn grpc.credentials.createInsecure();\n\t}\n}\n"]}
@@ -1,2 +0,0 @@
1
- import {a}from'./chunk-4C666HHU.js';var Me={};a(Me,{BRAND:()=>dt,DIRTY:()=>U,EMPTY_PATH:()=>Le,INVALID:()=>p,NEVER:()=>Jt,OK:()=>k,ParseStatus:()=>x,Schema:()=>_,ZodAny:()=>D,ZodArray:()=>$,ZodBigInt:()=>B,ZodBoolean:()=>W,ZodBranded:()=>he,ZodCatch:()=>re,ZodDate:()=>q,ZodDefault:()=>te,ZodDiscriminatedUnion:()=>_e,ZodEffects:()=>S,ZodEnum:()=>K,ZodError:()=>b,ZodFirstPartyTypeKind:()=>m,ZodFunction:()=>ve,ZodIntersection:()=>G,ZodIssueCode:()=>c,ZodLazy:()=>Q,ZodLiteral:()=>X,ZodMap:()=>de,ZodNaN:()=>le,ZodNativeEnum:()=>ee,ZodNever:()=>A,ZodNull:()=>Y,ZodNullable:()=>j,ZodNumber:()=>F,ZodObject:()=>w,ZodOptional:()=>C,ZodParsedType:()=>u,ZodPipeline:()=>pe,ZodPromise:()=>L,ZodReadonly:()=>se,ZodRecord:()=>ge,ZodSchema:()=>_,ZodSet:()=>ue,ZodString:()=>z,ZodSymbol:()=>oe,ZodTransformer:()=>S,ZodTuple:()=>N,ZodType:()=>_,ZodUndefined:()=>J,ZodUnion:()=>H,ZodUnknown:()=>Z,ZodVoid:()=>ce,addIssueToContext:()=>d,any:()=>gt,array:()=>bt,bigint:()=>ht,boolean:()=>$e,coerce:()=>qt,custom:()=>Ie,date:()=>pt,datetimeRegex:()=>Ne,defaultErrorMap:()=>I,discriminatedUnion:()=>Ot,effect:()=>Pt,enum:()=>$t,function:()=>It,getErrorMap:()=>ae,getParsedType:()=>R,instanceof:()=>lt,intersection:()=>St,isAborted:()=>me,isAsync:()=>ne,isDirty:()=>ye,isValid:()=>P,late:()=>ut,lazy:()=>Et,literal:()=>Zt,makeIssue:()=>fe,map:()=>Nt,nan:()=>ft,nativeEnum:()=>Mt,never:()=>xt,null:()=>_t,nullable:()=>Dt,number:()=>Ze,object:()=>wt,objectUtil:()=>ke,oboolean:()=>Wt,onumber:()=>Bt,optional:()=>zt,ostring:()=>Ft,pipeline:()=>Ut,preprocess:()=>Lt,promise:()=>Vt,quotelessJson:()=>Pe,record:()=>Rt,set:()=>jt,setErrorMap:()=>De,strictObject:()=>Tt,string:()=>Ee,symbol:()=>mt,transformer:()=>Pt,tuple:()=>At,undefined:()=>yt,union:()=>Ct,unknown:()=>vt,util:()=>g,void:()=>kt});var g;(function(r){r.assertEqual=a=>{};function e(a){}r.assertIs=e;function t(a){throw new Error}r.assertNever=t,r.arrayToEnum=a=>{let n={};for(let i of a)n[i]=i;return n},r.getValidEnumValues=a=>{let n=r.objectKeys(a).filter(o=>typeof a[a[o]]!="number"),i={};for(let o of n)i[o]=a[o];return r.objectValues(i)},r.objectValues=a=>r.objectKeys(a).map(function(n){return a[n]}),r.objectKeys=typeof Object.keys=="function"?a=>Object.keys(a):a=>{let n=[];for(let i in a)Object.prototype.hasOwnProperty.call(a,i)&&n.push(i);return n},r.find=(a,n)=>{for(let i of a)if(n(i))return i},r.isInteger=typeof Number.isInteger=="function"?a=>Number.isInteger(a):a=>typeof a=="number"&&Number.isFinite(a)&&Math.floor(a)===a;function s(a,n=" | "){return a.map(i=>typeof i=="string"?`'${i}'`:i).join(n)}r.joinValues=s,r.jsonStringifyReplacer=(a,n)=>typeof n=="bigint"?n.toString():n;})(g||(g={}));var ke;(function(r){r.mergeShapes=(e,t)=>({...e,...t});})(ke||(ke={}));var u=g.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),R=r=>{switch(typeof r){case "undefined":return u.undefined;case "string":return u.string;case "number":return Number.isNaN(r)?u.nan:u.number;case "boolean":return u.boolean;case "function":return u.function;case "bigint":return u.bigint;case "symbol":return u.symbol;case "object":return Array.isArray(r)?u.array:r===null?u.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?u.promise:typeof Map<"u"&&r instanceof Map?u.map:typeof Set<"u"&&r instanceof Set?u.set:typeof Date<"u"&&r instanceof Date?u.date:u.object;default:return u.unknown}};var c=g.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Pe=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:"),b=class r extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=s=>{this.issues=[...this.issues,s];},this.addIssues=(s=[])=>{this.issues=[...this.issues,...s];};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e;}format(e){let t=e||function(n){return n.message},s={_errors:[]},a=n=>{for(let i of n.issues)if(i.code==="invalid_union")i.unionErrors.map(a);else if(i.code==="invalid_return_type")a(i.returnTypeError);else if(i.code==="invalid_arguments")a(i.argumentsError);else if(i.path.length===0)s._errors.push(t(i));else {let o=s,f=0;for(;f<i.path.length;){let l=i.path[f];f===i.path.length-1?(o[l]=o[l]||{_errors:[]},o[l]._errors.push(t(i))):o[l]=o[l]||{_errors:[]},o=o[l],f++;}}};return a(this),s}static assert(e){if(!(e instanceof r))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,g.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){let t={},s=[];for(let a of this.issues)if(a.path.length>0){let n=a.path[0];t[n]=t[n]||[],t[n].push(e(a));}else s.push(e(a));return {formErrors:s,fieldErrors:t}}get formErrors(){return this.flatten()}};b.create=r=>new b(r);var ze=(r,e)=>{let t;switch(r.code){case c.invalid_type:r.received===u.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case c.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,g.jsonStringifyReplacer)}`;break;case c.unrecognized_keys:t=`Unrecognized key(s) in object: ${g.joinValues(r.keys,", ")}`;break;case c.invalid_union:t="Invalid input";break;case c.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${g.joinValues(r.options)}`;break;case c.invalid_enum_value:t=`Invalid enum value. Expected ${g.joinValues(r.options)}, received '${r.received}'`;break;case c.invalid_arguments:t="Invalid function arguments";break;case c.invalid_return_type:t="Invalid function return type";break;case c.invalid_date:t="Invalid date";break;case c.invalid_string:typeof r.validation=="object"?"includes"in r.validation?(t=`Invalid input: must include "${r.validation.includes}"`,typeof r.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${r.validation.position}`)):"startsWith"in r.validation?t=`Invalid input: must start with "${r.validation.startsWith}"`:"endsWith"in r.validation?t=`Invalid input: must end with "${r.validation.endsWith}"`:g.assertNever(r.validation):r.validation!=="regex"?t=`Invalid ${r.validation}`:t="Invalid";break;case c.too_small:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at least":"more than"} ${r.minimum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at least":"over"} ${r.minimum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="bigint"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(r.minimum))}`:t="Invalid input";break;case c.too_big:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at most":"less than"} ${r.maximum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at most":"under"} ${r.maximum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="bigint"?t=`BigInt must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly":r.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(r.maximum))}`:t="Invalid input";break;case c.custom:t="Invalid input";break;case c.invalid_intersection_types:t="Intersection results could not be merged";break;case c.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case c.not_finite:t="Number must be finite";break;default:t=e.defaultError,g.assertNever(r);}return {message:t}},I=ze;var Ce=I;function De(r){Ce=r;}function ae(){return Ce}var fe=r=>{let{data:e,path:t,errorMaps:s,issueData:a}=r,n=[...t,...a.path||[]],i={...a,path:n};if(a.message!==void 0)return {...a,path:n,message:a.message};let o="",f=s.filter(l=>!!l).slice().reverse();for(let l of f)o=l(i,{data:e,defaultError:o}).message;return {...a,path:n,message:o}},Le=[];function d(r,e){let t=ae(),s=fe({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===I?void 0:I].filter(a=>!!a)});r.common.issues.push(s);}var x=class r{constructor(){this.value="valid";}dirty(){this.value==="valid"&&(this.value="dirty");}abort(){this.value!=="aborted"&&(this.value="aborted");}static mergeArray(e,t){let s=[];for(let a of t){if(a.status==="aborted")return p;a.status==="dirty"&&e.dirty(),s.push(a.value);}return {status:e.value,value:s}}static async mergeObjectAsync(e,t){let s=[];for(let a of t){let n=await a.key,i=await a.value;s.push({key:n,value:i});}return r.mergeObjectSync(e,s)}static mergeObjectSync(e,t){let s={};for(let a of t){let{key:n,value:i}=a;if(n.status==="aborted"||i.status==="aborted")return p;n.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),n.value!=="__proto__"&&(typeof i.value<"u"||a.alwaysSet)&&(s[n.value]=i.value);}return {status:e.value,value:s}}},p=Object.freeze({status:"aborted"}),U=r=>({status:"dirty",value:r}),k=r=>({status:"valid",value:r}),me=r=>r.status==="aborted",ye=r=>r.status==="dirty",P=r=>r.status==="valid",ne=r=>typeof Promise<"u"&&r instanceof Promise;var h;(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e?.message;})(h||(h={}));var O=class{constructor(e,t,s,a){this._cachedPath=[],this.parent=e,this.data=t,this._path=s,this._key=a;}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},Oe=(r,e)=>{if(P(e))return {success:true,data:e.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return {success:false,get error(){if(this._error)return this._error;let t=new b(r.common.issues);return this._error=t,this._error}}};function y(r){if(!r)return {};let{errorMap:e,invalid_type_error:t,required_error:s,description:a}=r;if(e&&(t||s))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:a}:{errorMap:(i,o)=>{let{message:f}=r;return i.code==="invalid_enum_value"?{message:f??o.defaultError}:typeof o.data>"u"?{message:f??s??o.defaultError}:i.code!=="invalid_type"?{message:o.defaultError}:{message:f??t??o.defaultError}},description:a}}var _=class{get description(){return this._def.description}_getType(e){return R(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:R(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return {status:new x,ctx:{common:e.parent.common,data:e.data,parsedType:R(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(ne(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let s=this.safeParse(e,t);if(s.success)return s.data;throw s.error}safeParse(e,t){let s={common:{issues:[],async:t?.async??false,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:R(e)},a=this._parseSync({data:e,path:s.path,parent:s});return Oe(s,a)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:R(e)};if(!this["~standard"].async)try{let s=this._parseSync({data:e,path:[],parent:t});return P(s)?{value:s.value}:{issues:t.common.issues}}catch(s){s?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=true),t.common={issues:[],async:true};}return this._parseAsync({data:e,path:[],parent:t}).then(s=>P(s)?{value:s.value}:{issues:t.common.issues})}async parseAsync(e,t){let s=await this.safeParseAsync(e,t);if(s.success)return s.data;throw s.error}async safeParseAsync(e,t){let s={common:{issues:[],contextualErrorMap:t?.errorMap,async:true},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:R(e)},a=this._parse({data:e,path:s.path,parent:s}),n=await(ne(a)?a:Promise.resolve(a));return Oe(s,n)}refine(e,t){let s=a=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(a):t;return this._refinement((a,n)=>{let i=e(a),o=()=>n.addIssue({code:c.custom,...s(a)});return typeof Promise<"u"&&i instanceof Promise?i.then(f=>f?true:(o(),false)):i?true:(o(),false)})}refinement(e,t){return this._refinement((s,a)=>e(s)?true:(a.addIssue(typeof t=="function"?t(s,a):t),false))}_refinement(e){return new S({schema:this,typeName:m.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)};}optional(){return C.create(this,this._def)}nullable(){return j.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return $.create(this)}promise(){return L.create(this,this._def)}or(e){return H.create([this,e],this._def)}and(e){return G.create(this,e,this._def)}transform(e){return new S({...y(this._def),schema:this,typeName:m.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new te({...y(this._def),innerType:this,defaultValue:t,typeName:m.ZodDefault})}brand(){return new he({typeName:m.ZodBranded,type:this,...y(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new re({...y(this._def),innerType:this,catchValue:t,typeName:m.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return pe.create(this,e)}readonly(){return se.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Ue=/^c[^\s-]{8,}$/i,Fe=/^[0-9a-z]+$/,Be=/^[0-9A-HJKMNP-TV-Z]{26}$/i,We=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,qe=/^[a-z0-9_-]{21}$/i,Je=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Ye=/^[-+]?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+[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-9]))$/,et=/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,tt=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,rt=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Ae="((\\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])))",st=new RegExp(`^${Ae}$`);function Re(r){let e="[0-5]\\d";r.precision?e=`${e}\\.\\d{${r.precision}}`:r.precision==null&&(e=`${e}(\\.\\d+)?`);let t=r.precision?"+":"?";return `([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function at(r){return new RegExp(`^${Re(r)}$`)}function Ne(r){let e=`${Ae}T${Re(r)}`,t=[];return t.push(r.local?"Z?":"Z"),r.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function nt(r,e){return !!((e==="v4"||!e)&&Qe.test(r)||(e==="v6"||!e)&&Ke.test(r))}function it(r,e){if(!Je.test(r))return false;try{let[t]=r.split(".");if(!t)return !1;let s=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),a=JSON.parse(atob(s));return !(typeof a!="object"||a===null||"typ"in a&&a?.typ!=="JWT"||!a.alg||e&&a.alg!==e)}catch{return false}}function ot(r,e){return !!((e==="v4"||!e)&&Xe.test(r)||(e==="v6"||!e)&&et.test(r))}var z=class r extends _{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==u.string){let n=this._getOrReturnCtx(e);return d(n,{code:c.invalid_type,expected:u.string,received:n.parsedType}),p}let s=new x,a;for(let n of this._def.checks)if(n.kind==="min")e.data.length<n.value&&(a=this._getOrReturnCtx(e,a),d(a,{code:c.too_small,minimum:n.value,type:"string",inclusive:true,exact:false,message:n.message}),s.dirty());else if(n.kind==="max")e.data.length>n.value&&(a=this._getOrReturnCtx(e,a),d(a,{code:c.too_big,maximum:n.value,type:"string",inclusive:true,exact:false,message:n.message}),s.dirty());else if(n.kind==="length"){let i=e.data.length>n.value,o=e.data.length<n.value;(i||o)&&(a=this._getOrReturnCtx(e,a),i?d(a,{code:c.too_big,maximum:n.value,type:"string",inclusive:true,exact:true,message:n.message}):o&&d(a,{code:c.too_small,minimum:n.value,type:"string",inclusive:true,exact:true,message:n.message}),s.dirty());}else if(n.kind==="email")He.test(e.data)||(a=this._getOrReturnCtx(e,a),d(a,{validation:"email",code:c.invalid_string,message:n.message}),s.dirty());else if(n.kind==="emoji")be||(be=new RegExp(Ge,"u")),be.test(e.data)||(a=this._getOrReturnCtx(e,a),d(a,{validation:"emoji",code:c.invalid_string,message:n.message}),s.dirty());else if(n.kind==="uuid")We.test(e.data)||(a=this._getOrReturnCtx(e,a),d(a,{validation:"uuid",code:c.invalid_string,message:n.message}),s.dirty());else if(n.kind==="nanoid")qe.test(e.data)||(a=this._getOrReturnCtx(e,a),d(a,{validation:"nanoid",code:c.invalid_string,message:n.message}),s.dirty());else if(n.kind==="cuid")Ue.test(e.data)||(a=this._getOrReturnCtx(e,a),d(a,{validation:"cuid",code:c.invalid_string,message:n.message}),s.dirty());else if(n.kind==="cuid2")Fe.test(e.data)||(a=this._getOrReturnCtx(e,a),d(a,{validation:"cuid2",code:c.invalid_string,message:n.message}),s.dirty());else if(n.kind==="ulid")Be.test(e.data)||(a=this._getOrReturnCtx(e,a),d(a,{validation:"ulid",code:c.invalid_string,message:n.message}),s.dirty());else if(n.kind==="url")try{new URL(e.data);}catch{a=this._getOrReturnCtx(e,a),d(a,{validation:"url",code:c.invalid_string,message:n.message}),s.dirty();}else n.kind==="regex"?(n.regex.lastIndex=0,n.regex.test(e.data)||(a=this._getOrReturnCtx(e,a),d(a,{validation:"regex",code:c.invalid_string,message:n.message}),s.dirty())):n.kind==="trim"?e.data=e.data.trim():n.kind==="includes"?e.data.includes(n.value,n.position)||(a=this._getOrReturnCtx(e,a),d(a,{code:c.invalid_string,validation:{includes:n.value,position:n.position},message:n.message}),s.dirty()):n.kind==="toLowerCase"?e.data=e.data.toLowerCase():n.kind==="toUpperCase"?e.data=e.data.toUpperCase():n.kind==="startsWith"?e.data.startsWith(n.value)||(a=this._getOrReturnCtx(e,a),d(a,{code:c.invalid_string,validation:{startsWith:n.value},message:n.message}),s.dirty()):n.kind==="endsWith"?e.data.endsWith(n.value)||(a=this._getOrReturnCtx(e,a),d(a,{code:c.invalid_string,validation:{endsWith:n.value},message:n.message}),s.dirty()):n.kind==="datetime"?Ne(n).test(e.data)||(a=this._getOrReturnCtx(e,a),d(a,{code:c.invalid_string,validation:"datetime",message:n.message}),s.dirty()):n.kind==="date"?st.test(e.data)||(a=this._getOrReturnCtx(e,a),d(a,{code:c.invalid_string,validation:"date",message:n.message}),s.dirty()):n.kind==="time"?at(n).test(e.data)||(a=this._getOrReturnCtx(e,a),d(a,{code:c.invalid_string,validation:"time",message:n.message}),s.dirty()):n.kind==="duration"?Ye.test(e.data)||(a=this._getOrReturnCtx(e,a),d(a,{validation:"duration",code:c.invalid_string,message:n.message}),s.dirty()):n.kind==="ip"?nt(e.data,n.version)||(a=this._getOrReturnCtx(e,a),d(a,{validation:"ip",code:c.invalid_string,message:n.message}),s.dirty()):n.kind==="jwt"?it(e.data,n.alg)||(a=this._getOrReturnCtx(e,a),d(a,{validation:"jwt",code:c.invalid_string,message:n.message}),s.dirty()):n.kind==="cidr"?ot(e.data,n.version)||(a=this._getOrReturnCtx(e,a),d(a,{validation:"cidr",code:c.invalid_string,message:n.message}),s.dirty()):n.kind==="base64"?tt.test(e.data)||(a=this._getOrReturnCtx(e,a),d(a,{validation:"base64",code:c.invalid_string,message:n.message}),s.dirty()):n.kind==="base64url"?rt.test(e.data)||(a=this._getOrReturnCtx(e,a),d(a,{validation:"base64url",code:c.invalid_string,message:n.message}),s.dirty()):g.assertNever(n);return {status:s.value,value:e.data}}_regex(e,t,s){return this.refinement(a=>e.test(a),{validation:t,code:c.invalid_string,...h.errToObj(s)})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...h.errToObj(e)})}url(e){return this._addCheck({kind:"url",...h.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...h.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...h.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...h.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...h.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...h.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...h.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...h.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...h.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...h.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...h.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...h.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:false,local:false,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??false,local:e?.local??false,...h.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...h.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...h.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...h.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...h.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...h.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...h.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...h.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...h.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...h.errToObj(t)})}nonempty(e){return this.min(1,h.errToObj(e))}trim(){return new r({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return !!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return !!this._def.checks.find(e=>e.kind==="date")}get isTime(){return !!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return !!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return !!this._def.checks.find(e=>e.kind==="email")}get isURL(){return !!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return !!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return !!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return !!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return !!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return !!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return !!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return !!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return !!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return !!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return !!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};z.create=r=>new z({checks:[],typeName:m.ZodString,coerce:r?.coerce??false,...y(r)});function ct(r,e){let t=(r.toString().split(".")[1]||"").length,s=(e.toString().split(".")[1]||"").length,a=t>s?t:s,n=Number.parseInt(r.toFixed(a).replace(".","")),i=Number.parseInt(e.toFixed(a).replace(".",""));return n%i/10**a}var F=class r extends _{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf;}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==u.number){let n=this._getOrReturnCtx(e);return d(n,{code:c.invalid_type,expected:u.number,received:n.parsedType}),p}let s,a=new x;for(let n of this._def.checks)n.kind==="int"?g.isInteger(e.data)||(s=this._getOrReturnCtx(e,s),d(s,{code:c.invalid_type,expected:"integer",received:"float",message:n.message}),a.dirty()):n.kind==="min"?(n.inclusive?e.data<n.value:e.data<=n.value)&&(s=this._getOrReturnCtx(e,s),d(s,{code:c.too_small,minimum:n.value,type:"number",inclusive:n.inclusive,exact:false,message:n.message}),a.dirty()):n.kind==="max"?(n.inclusive?e.data>n.value:e.data>=n.value)&&(s=this._getOrReturnCtx(e,s),d(s,{code:c.too_big,maximum:n.value,type:"number",inclusive:n.inclusive,exact:false,message:n.message}),a.dirty()):n.kind==="multipleOf"?ct(e.data,n.value)!==0&&(s=this._getOrReturnCtx(e,s),d(s,{code:c.not_multiple_of,multipleOf:n.value,message:n.message}),a.dirty()):n.kind==="finite"?Number.isFinite(e.data)||(s=this._getOrReturnCtx(e,s),d(s,{code:c.not_finite,message:n.message}),a.dirty()):g.assertNever(n);return {status:a.value,value:e.data}}gte(e,t){return this.setLimit("min",e,true,h.toString(t))}gt(e,t){return this.setLimit("min",e,false,h.toString(t))}lte(e,t){return this.setLimit("max",e,true,h.toString(t))}lt(e,t){return this.setLimit("max",e,false,h.toString(t))}setLimit(e,t,s,a){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:s,message:h.toString(a)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:h.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:false,message:h.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:false,message:h.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:true,message:h.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:true,message:h.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:h.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:h.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:true,value:Number.MIN_SAFE_INTEGER,message:h.toString(e)})._addCheck({kind:"max",inclusive:true,value:Number.MAX_SAFE_INTEGER,message:h.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return !!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&g.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let s of this._def.checks){if(s.kind==="finite"||s.kind==="int"||s.kind==="multipleOf")return true;s.kind==="min"?(t===null||s.value>t)&&(t=s.value):s.kind==="max"&&(e===null||s.value<e)&&(e=s.value);}return Number.isFinite(t)&&Number.isFinite(e)}};F.create=r=>new F({checks:[],typeName:m.ZodNumber,coerce:r?.coerce||false,...y(r)});var B=class r extends _{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte;}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data);}catch{return this._getInvalidInput(e)}if(this._getType(e)!==u.bigint)return this._getInvalidInput(e);let s,a=new x;for(let n of this._def.checks)n.kind==="min"?(n.inclusive?e.data<n.value:e.data<=n.value)&&(s=this._getOrReturnCtx(e,s),d(s,{code:c.too_small,type:"bigint",minimum:n.value,inclusive:n.inclusive,message:n.message}),a.dirty()):n.kind==="max"?(n.inclusive?e.data>n.value:e.data>=n.value)&&(s=this._getOrReturnCtx(e,s),d(s,{code:c.too_big,type:"bigint",maximum:n.value,inclusive:n.inclusive,message:n.message}),a.dirty()):n.kind==="multipleOf"?e.data%n.value!==BigInt(0)&&(s=this._getOrReturnCtx(e,s),d(s,{code:c.not_multiple_of,multipleOf:n.value,message:n.message}),a.dirty()):g.assertNever(n);return {status:a.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return d(t,{code:c.invalid_type,expected:u.bigint,received:t.parsedType}),p}gte(e,t){return this.setLimit("min",e,true,h.toString(t))}gt(e,t){return this.setLimit("min",e,false,h.toString(t))}lte(e,t){return this.setLimit("max",e,true,h.toString(t))}lt(e,t){return this.setLimit("max",e,false,h.toString(t))}setLimit(e,t,s,a){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:s,message:h.toString(a)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:false,message:h.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:false,message:h.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:true,message:h.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:true,message:h.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:h.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};B.create=r=>new B({checks:[],typeName:m.ZodBigInt,coerce:r?.coerce??false,...y(r)});var W=class extends _{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==u.boolean){let s=this._getOrReturnCtx(e);return d(s,{code:c.invalid_type,expected:u.boolean,received:s.parsedType}),p}return k(e.data)}};W.create=r=>new W({typeName:m.ZodBoolean,coerce:r?.coerce||false,...y(r)});var q=class r extends _{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==u.date){let n=this._getOrReturnCtx(e);return d(n,{code:c.invalid_type,expected:u.date,received:n.parsedType}),p}if(Number.isNaN(e.data.getTime())){let n=this._getOrReturnCtx(e);return d(n,{code:c.invalid_date}),p}let s=new x,a;for(let n of this._def.checks)n.kind==="min"?e.data.getTime()<n.value&&(a=this._getOrReturnCtx(e,a),d(a,{code:c.too_small,message:n.message,inclusive:true,exact:false,minimum:n.value,type:"date"}),s.dirty()):n.kind==="max"?e.data.getTime()>n.value&&(a=this._getOrReturnCtx(e,a),d(a,{code:c.too_big,message:n.message,inclusive:true,exact:false,maximum:n.value,type:"date"}),s.dirty()):g.assertNever(n);return {status:s.value,value:new Date(e.data.getTime())}}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:h.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:h.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}};q.create=r=>new q({checks:[],coerce:r?.coerce||false,typeName:m.ZodDate,...y(r)});var oe=class extends _{_parse(e){if(this._getType(e)!==u.symbol){let s=this._getOrReturnCtx(e);return d(s,{code:c.invalid_type,expected:u.symbol,received:s.parsedType}),p}return k(e.data)}};oe.create=r=>new oe({typeName:m.ZodSymbol,...y(r)});var J=class extends _{_parse(e){if(this._getType(e)!==u.undefined){let s=this._getOrReturnCtx(e);return d(s,{code:c.invalid_type,expected:u.undefined,received:s.parsedType}),p}return k(e.data)}};J.create=r=>new J({typeName:m.ZodUndefined,...y(r)});var Y=class extends _{_parse(e){if(this._getType(e)!==u.null){let s=this._getOrReturnCtx(e);return d(s,{code:c.invalid_type,expected:u.null,received:s.parsedType}),p}return k(e.data)}};Y.create=r=>new Y({typeName:m.ZodNull,...y(r)});var D=class extends _{constructor(){super(...arguments),this._any=true;}_parse(e){return k(e.data)}};D.create=r=>new D({typeName:m.ZodAny,...y(r)});var Z=class extends _{constructor(){super(...arguments),this._unknown=true;}_parse(e){return k(e.data)}};Z.create=r=>new Z({typeName:m.ZodUnknown,...y(r)});var A=class extends _{_parse(e){let t=this._getOrReturnCtx(e);return d(t,{code:c.invalid_type,expected:u.never,received:t.parsedType}),p}};A.create=r=>new A({typeName:m.ZodNever,...y(r)});var ce=class extends _{_parse(e){if(this._getType(e)!==u.undefined){let s=this._getOrReturnCtx(e);return d(s,{code:c.invalid_type,expected:u.void,received:s.parsedType}),p}return k(e.data)}};ce.create=r=>new ce({typeName:m.ZodVoid,...y(r)});var $=class r extends _{_parse(e){let{ctx:t,status:s}=this._processInputParams(e),a=this._def;if(t.parsedType!==u.array)return d(t,{code:c.invalid_type,expected:u.array,received:t.parsedType}),p;if(a.exactLength!==null){let i=t.data.length>a.exactLength.value,o=t.data.length<a.exactLength.value;(i||o)&&(d(t,{code:i?c.too_big:c.too_small,minimum:o?a.exactLength.value:void 0,maximum:i?a.exactLength.value:void 0,type:"array",inclusive:true,exact:true,message:a.exactLength.message}),s.dirty());}if(a.minLength!==null&&t.data.length<a.minLength.value&&(d(t,{code:c.too_small,minimum:a.minLength.value,type:"array",inclusive:true,exact:false,message:a.minLength.message}),s.dirty()),a.maxLength!==null&&t.data.length>a.maxLength.value&&(d(t,{code:c.too_big,maximum:a.maxLength.value,type:"array",inclusive:true,exact:false,message:a.maxLength.message}),s.dirty()),t.common.async)return Promise.all([...t.data].map((i,o)=>a.type._parseAsync(new O(t,i,t.path,o)))).then(i=>x.mergeArray(s,i));let n=[...t.data].map((i,o)=>a.type._parseSync(new O(t,i,t.path,o)));return x.mergeArray(s,n)}get element(){return this._def.type}min(e,t){return new r({...this._def,minLength:{value:e,message:h.toString(t)}})}max(e,t){return new r({...this._def,maxLength:{value:e,message:h.toString(t)}})}length(e,t){return new r({...this._def,exactLength:{value:e,message:h.toString(t)}})}nonempty(e){return this.min(1,e)}};$.create=(r,e)=>new $({type:r,minLength:null,maxLength:null,exactLength:null,typeName:m.ZodArray,...y(e)});function ie(r){if(r instanceof w){let e={};for(let t in r.shape){let s=r.shape[t];e[t]=C.create(ie(s));}return new w({...r._def,shape:()=>e})}else return r instanceof $?new $({...r._def,type:ie(r.element)}):r instanceof C?C.create(ie(r.unwrap())):r instanceof j?j.create(ie(r.unwrap())):r instanceof N?N.create(r.items.map(e=>ie(e))):r}var w=class r extends _{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend;}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=g.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==u.object){let l=this._getOrReturnCtx(e);return d(l,{code:c.invalid_type,expected:u.object,received:l.parsedType}),p}let{status:s,ctx:a}=this._processInputParams(e),{shape:n,keys:i}=this._getCached(),o=[];if(!(this._def.catchall instanceof A&&this._def.unknownKeys==="strip"))for(let l in a.data)i.includes(l)||o.push(l);let f=[];for(let l of i){let v=n[l],T=a.data[l];f.push({key:{status:"valid",value:l},value:v._parse(new O(a,T,a.path,l)),alwaysSet:l in a.data});}if(this._def.catchall instanceof A){let l=this._def.unknownKeys;if(l==="passthrough")for(let v of o)f.push({key:{status:"valid",value:v},value:{status:"valid",value:a.data[v]}});else if(l==="strict")o.length>0&&(d(a,{code:c.unrecognized_keys,keys:o}),s.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else {let l=this._def.catchall;for(let v of o){let T=a.data[v];f.push({key:{status:"valid",value:v},value:l._parse(new O(a,T,a.path,v)),alwaysSet:v in a.data});}}return a.common.async?Promise.resolve().then(async()=>{let l=[];for(let v of f){let T=await v.key,Te=await v.value;l.push({key:T,value:Te,alwaysSet:v.alwaysSet});}return l}).then(l=>x.mergeObjectSync(s,l)):x.mergeObjectSync(s,f)}get shape(){return this._def.shape()}strict(e){return h.errToObj,new r({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,s)=>{let a=this._def.errorMap?.(t,s).message??s.defaultError;return t.code==="unrecognized_keys"?{message:h.errToObj(e).message??a}:{message:a}}}:{}})}strip(){return new r({...this._def,unknownKeys:"strip"})}passthrough(){return new r({...this._def,unknownKeys:"passthrough"})}extend(e){return new r({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new r({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:m.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new r({...this._def,catchall:e})}pick(e){let t={};for(let s of g.objectKeys(e))e[s]&&this.shape[s]&&(t[s]=this.shape[s]);return new r({...this._def,shape:()=>t})}omit(e){let t={};for(let s of g.objectKeys(this.shape))e[s]||(t[s]=this.shape[s]);return new r({...this._def,shape:()=>t})}deepPartial(){return ie(this)}partial(e){let t={};for(let s of g.objectKeys(this.shape)){let a=this.shape[s];e&&!e[s]?t[s]=a:t[s]=a.optional();}return new r({...this._def,shape:()=>t})}required(e){let t={};for(let s of g.objectKeys(this.shape))if(e&&!e[s])t[s]=this.shape[s];else {let n=this.shape[s];for(;n instanceof C;)n=n._def.innerType;t[s]=n;}return new r({...this._def,shape:()=>t})}keyof(){return je(g.objectKeys(this.shape))}};w.create=(r,e)=>new w({shape:()=>r,unknownKeys:"strip",catchall:A.create(),typeName:m.ZodObject,...y(e)});w.strictCreate=(r,e)=>new w({shape:()=>r,unknownKeys:"strict",catchall:A.create(),typeName:m.ZodObject,...y(e)});w.lazycreate=(r,e)=>new w({shape:r,unknownKeys:"strip",catchall:A.create(),typeName:m.ZodObject,...y(e)});var H=class extends _{_parse(e){let{ctx:t}=this._processInputParams(e),s=this._def.options;function a(n){for(let o of n)if(o.result.status==="valid")return o.result;for(let o of n)if(o.result.status==="dirty")return t.common.issues.push(...o.ctx.common.issues),o.result;let i=n.map(o=>new b(o.ctx.common.issues));return d(t,{code:c.invalid_union,unionErrors:i}),p}if(t.common.async)return Promise.all(s.map(async n=>{let i={...t,common:{...t.common,issues:[]},parent:null};return {result:await n._parseAsync({data:t.data,path:t.path,parent:i}),ctx:i}})).then(a);{let n,i=[];for(let f of s){let l={...t,common:{...t.common,issues:[]},parent:null},v=f._parseSync({data:t.data,path:t.path,parent:l});if(v.status==="valid")return v;v.status==="dirty"&&!n&&(n={result:v,ctx:l}),l.common.issues.length&&i.push(l.common.issues);}if(n)return t.common.issues.push(...n.ctx.common.issues),n.result;let o=i.map(f=>new b(f));return d(t,{code:c.invalid_union,unionErrors:o}),p}}get options(){return this._def.options}};H.create=(r,e)=>new H({options:r,typeName:m.ZodUnion,...y(e)});var E=r=>r instanceof Q?E(r.schema):r instanceof S?E(r.innerType()):r instanceof X?[r.value]:r instanceof K?r.options:r instanceof ee?g.objectValues(r.enum):r instanceof te?E(r._def.innerType):r instanceof J?[void 0]:r instanceof Y?[null]:r instanceof C?[void 0,...E(r.unwrap())]:r instanceof j?[null,...E(r.unwrap())]:r instanceof he||r instanceof se?E(r.unwrap()):r instanceof re?E(r._def.innerType):[],_e=class r extends _{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==u.object)return d(t,{code:c.invalid_type,expected:u.object,received:t.parsedType}),p;let s=this.discriminator,a=t.data[s],n=this.optionsMap.get(a);return n?t.common.async?n._parseAsync({data:t.data,path:t.path,parent:t}):n._parseSync({data:t.data,path:t.path,parent:t}):(d(t,{code:c.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[s]}),p)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,s){let a=new Map;for(let n of t){let i=E(n.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let o of i){if(a.has(o))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(o)}`);a.set(o,n);}}return new r({typeName:m.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:a,...y(s)})}};function we(r,e){let t=R(r),s=R(e);if(r===e)return {valid:true,data:r};if(t===u.object&&s===u.object){let a=g.objectKeys(e),n=g.objectKeys(r).filter(o=>a.indexOf(o)!==-1),i={...r,...e};for(let o of n){let f=we(r[o],e[o]);if(!f.valid)return {valid:false};i[o]=f.data;}return {valid:true,data:i}}else if(t===u.array&&s===u.array){if(r.length!==e.length)return {valid:false};let a=[];for(let n=0;n<r.length;n++){let i=r[n],o=e[n],f=we(i,o);if(!f.valid)return {valid:false};a.push(f.data);}return {valid:true,data:a}}else return t===u.date&&s===u.date&&+r==+e?{valid:true,data:r}:{valid:false}}var G=class extends _{_parse(e){let{status:t,ctx:s}=this._processInputParams(e),a=(n,i)=>{if(me(n)||me(i))return p;let o=we(n.value,i.value);return o.valid?((ye(n)||ye(i))&&t.dirty(),{status:t.value,value:o.data}):(d(s,{code:c.invalid_intersection_types}),p)};return s.common.async?Promise.all([this._def.left._parseAsync({data:s.data,path:s.path,parent:s}),this._def.right._parseAsync({data:s.data,path:s.path,parent:s})]).then(([n,i])=>a(n,i)):a(this._def.left._parseSync({data:s.data,path:s.path,parent:s}),this._def.right._parseSync({data:s.data,path:s.path,parent:s}))}};G.create=(r,e,t)=>new G({left:r,right:e,typeName:m.ZodIntersection,...y(t)});var N=class r extends _{_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==u.array)return d(s,{code:c.invalid_type,expected:u.array,received:s.parsedType}),p;if(s.data.length<this._def.items.length)return d(s,{code:c.too_small,minimum:this._def.items.length,inclusive:true,exact:false,type:"array"}),p;!this._def.rest&&s.data.length>this._def.items.length&&(d(s,{code:c.too_big,maximum:this._def.items.length,inclusive:true,exact:false,type:"array"}),t.dirty());let n=[...s.data].map((i,o)=>{let f=this._def.items[o]||this._def.rest;return f?f._parse(new O(s,i,s.path,o)):null}).filter(i=>!!i);return s.common.async?Promise.all(n).then(i=>x.mergeArray(t,i)):x.mergeArray(t,n)}get items(){return this._def.items}rest(e){return new r({...this._def,rest:e})}};N.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new N({items:r,typeName:m.ZodTuple,rest:null,...y(e)})};var ge=class r extends _{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==u.object)return d(s,{code:c.invalid_type,expected:u.object,received:s.parsedType}),p;let a=[],n=this._def.keyType,i=this._def.valueType;for(let o in s.data)a.push({key:n._parse(new O(s,o,s.path,o)),value:i._parse(new O(s,s.data[o],s.path,o)),alwaysSet:o in s.data});return s.common.async?x.mergeObjectAsync(t,a):x.mergeObjectSync(t,a)}get element(){return this._def.valueType}static create(e,t,s){return t instanceof _?new r({keyType:e,valueType:t,typeName:m.ZodRecord,...y(s)}):new r({keyType:z.create(),valueType:e,typeName:m.ZodRecord,...y(t)})}},de=class extends _{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==u.map)return d(s,{code:c.invalid_type,expected:u.map,received:s.parsedType}),p;let a=this._def.keyType,n=this._def.valueType,i=[...s.data.entries()].map(([o,f],l)=>({key:a._parse(new O(s,o,s.path,[l,"key"])),value:n._parse(new O(s,f,s.path,[l,"value"]))}));if(s.common.async){let o=new Map;return Promise.resolve().then(async()=>{for(let f of i){let l=await f.key,v=await f.value;if(l.status==="aborted"||v.status==="aborted")return p;(l.status==="dirty"||v.status==="dirty")&&t.dirty(),o.set(l.value,v.value);}return {status:t.value,value:o}})}else {let o=new Map;for(let f of i){let l=f.key,v=f.value;if(l.status==="aborted"||v.status==="aborted")return p;(l.status==="dirty"||v.status==="dirty")&&t.dirty(),o.set(l.value,v.value);}return {status:t.value,value:o}}}};de.create=(r,e,t)=>new de({valueType:e,keyType:r,typeName:m.ZodMap,...y(t)});var ue=class r extends _{_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==u.set)return d(s,{code:c.invalid_type,expected:u.set,received:s.parsedType}),p;let a=this._def;a.minSize!==null&&s.data.size<a.minSize.value&&(d(s,{code:c.too_small,minimum:a.minSize.value,type:"set",inclusive:true,exact:false,message:a.minSize.message}),t.dirty()),a.maxSize!==null&&s.data.size>a.maxSize.value&&(d(s,{code:c.too_big,maximum:a.maxSize.value,type:"set",inclusive:true,exact:false,message:a.maxSize.message}),t.dirty());let n=this._def.valueType;function i(f){let l=new Set;for(let v of f){if(v.status==="aborted")return p;v.status==="dirty"&&t.dirty(),l.add(v.value);}return {status:t.value,value:l}}let o=[...s.data.values()].map((f,l)=>n._parse(new O(s,f,s.path,l)));return s.common.async?Promise.all(o).then(f=>i(f)):i(o)}min(e,t){return new r({...this._def,minSize:{value:e,message:h.toString(t)}})}max(e,t){return new r({...this._def,maxSize:{value:e,message:h.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};ue.create=(r,e)=>new ue({valueType:r,minSize:null,maxSize:null,typeName:m.ZodSet,...y(e)});var ve=class r extends _{constructor(){super(...arguments),this.validate=this.implement;}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==u.function)return d(t,{code:c.invalid_type,expected:u.function,received:t.parsedType}),p;function s(o,f){return fe({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,ae(),I].filter(l=>!!l),issueData:{code:c.invalid_arguments,argumentsError:f}})}function a(o,f){return fe({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,ae(),I].filter(l=>!!l),issueData:{code:c.invalid_return_type,returnTypeError:f}})}let n={errorMap:t.common.contextualErrorMap},i=t.data;if(this._def.returns instanceof L){let o=this;return k(async function(...f){let l=new b([]),v=await o._def.args.parseAsync(f,n).catch(xe=>{throw l.addIssue(s(f,xe)),l}),T=await Reflect.apply(i,this,v);return await o._def.returns._def.type.parseAsync(T,n).catch(xe=>{throw l.addIssue(a(T,xe)),l})})}else {let o=this;return k(function(...f){let l=o._def.args.safeParse(f,n);if(!l.success)throw new b([s(f,l.error)]);let v=Reflect.apply(i,this,l.data),T=o._def.returns.safeParse(v,n);if(!T.success)throw new b([a(v,T.error)]);return T.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new r({...this._def,args:N.create(e).rest(Z.create())})}returns(e){return new r({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,s){return new r({args:e||N.create([]).rest(Z.create()),returns:t||Z.create(),typeName:m.ZodFunction,...y(s)})}},Q=class extends _{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};Q.create=(r,e)=>new Q({getter:r,typeName:m.ZodLazy,...y(e)});var X=class extends _{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return d(t,{received:t.data,code:c.invalid_literal,expected:this._def.value}),p}return {status:"valid",value:e.data}}get value(){return this._def.value}};X.create=(r,e)=>new X({value:r,typeName:m.ZodLiteral,...y(e)});function je(r,e){return new K({values:r,typeName:m.ZodEnum,...y(e)})}var K=class r extends _{_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),s=this._def.values;return d(t,{expected:g.joinValues(s),received:t.parsedType,code:c.invalid_type}),p}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),s=this._def.values;return d(t,{received:t.data,code:c.invalid_enum_value,options:s}),p}return k(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return r.create(e,{...this._def,...t})}exclude(e,t=this._def){return r.create(this.options.filter(s=>!e.includes(s)),{...this._def,...t})}};K.create=je;var ee=class extends _{_parse(e){let t=g.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(e);if(s.parsedType!==u.string&&s.parsedType!==u.number){let a=g.objectValues(t);return d(s,{expected:g.joinValues(a),received:s.parsedType,code:c.invalid_type}),p}if(this._cache||(this._cache=new Set(g.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let a=g.objectValues(t);return d(s,{received:s.data,code:c.invalid_enum_value,options:a}),p}return k(e.data)}get enum(){return this._def.values}};ee.create=(r,e)=>new ee({values:r,typeName:m.ZodNativeEnum,...y(e)});var L=class extends _{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==u.promise&&t.common.async===false)return d(t,{code:c.invalid_type,expected:u.promise,received:t.parsedType}),p;let s=t.parsedType===u.promise?t.data:Promise.resolve(t.data);return k(s.then(a=>this._def.type.parseAsync(a,{path:t.path,errorMap:t.common.contextualErrorMap})))}};L.create=(r,e)=>new L({type:r,typeName:m.ZodPromise,...y(e)});var S=class extends _{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===m.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:s}=this._processInputParams(e),a=this._def.effect||null,n={addIssue:i=>{d(s,i),i.fatal?t.abort():t.dirty();},get path(){return s.path}};if(n.addIssue=n.addIssue.bind(n),a.type==="preprocess"){let i=a.transform(s.data,n);if(s.common.async)return Promise.resolve(i).then(async o=>{if(t.value==="aborted")return p;let f=await this._def.schema._parseAsync({data:o,path:s.path,parent:s});return f.status==="aborted"?p:f.status==="dirty"?U(f.value):t.value==="dirty"?U(f.value):f});{if(t.value==="aborted")return p;let o=this._def.schema._parseSync({data:i,path:s.path,parent:s});return o.status==="aborted"?p:o.status==="dirty"?U(o.value):t.value==="dirty"?U(o.value):o}}if(a.type==="refinement"){let i=o=>{let f=a.refinement(o,n);if(s.common.async)return Promise.resolve(f);if(f instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(s.common.async===false){let o=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});return o.status==="aborted"?p:(o.status==="dirty"&&t.dirty(),i(o.value),{status:t.value,value:o.value})}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(o=>o.status==="aborted"?p:(o.status==="dirty"&&t.dirty(),i(o.value).then(()=>({status:t.value,value:o.value}))))}if(a.type==="transform")if(s.common.async===false){let i=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!P(i))return p;let o=a.transform(i.value,n);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return {status:t.value,value:o}}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(i=>P(i)?Promise.resolve(a.transform(i.value,n)).then(o=>({status:t.value,value:o})):p);g.assertNever(a);}};S.create=(r,e,t)=>new S({schema:r,typeName:m.ZodEffects,effect:e,...y(t)});S.createWithPreprocess=(r,e,t)=>new S({schema:e,effect:{type:"preprocess",transform:r},typeName:m.ZodEffects,...y(t)});var C=class extends _{_parse(e){return this._getType(e)===u.undefined?k(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};C.create=(r,e)=>new C({innerType:r,typeName:m.ZodOptional,...y(e)});var j=class extends _{_parse(e){return this._getType(e)===u.null?k(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};j.create=(r,e)=>new j({innerType:r,typeName:m.ZodNullable,...y(e)});var te=class extends _{_parse(e){let{ctx:t}=this._processInputParams(e),s=t.data;return t.parsedType===u.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};te.create=(r,e)=>new te({innerType:r,typeName:m.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...y(e)});var re=class extends _{_parse(e){let{ctx:t}=this._processInputParams(e),s={...t,common:{...t.common,issues:[]}},a=this._def.innerType._parse({data:s.data,path:s.path,parent:{...s}});return ne(a)?a.then(n=>({status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new b(s.common.issues)},input:s.data})})):{status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new b(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}};re.create=(r,e)=>new re({innerType:r,typeName:m.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...y(e)});var le=class extends _{_parse(e){if(this._getType(e)!==u.nan){let s=this._getOrReturnCtx(e);return d(s,{code:c.invalid_type,expected:u.nan,received:s.parsedType}),p}return {status:"valid",value:e.data}}};le.create=r=>new le({typeName:m.ZodNaN,...y(r)});var dt=Symbol("zod_brand"),he=class extends _{_parse(e){let{ctx:t}=this._processInputParams(e),s=t.data;return this._def.type._parse({data:s,path:t.path,parent:t})}unwrap(){return this._def.type}},pe=class r extends _{_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.common.async)return (async()=>{let n=await this._def.in._parseAsync({data:s.data,path:s.path,parent:s});return n.status==="aborted"?p:n.status==="dirty"?(t.dirty(),U(n.value)):this._def.out._parseAsync({data:n.value,path:s.path,parent:s})})();{let a=this._def.in._parseSync({data:s.data,path:s.path,parent:s});return a.status==="aborted"?p:a.status==="dirty"?(t.dirty(),{status:"dirty",value:a.value}):this._def.out._parseSync({data:a.value,path:s.path,parent:s})}}static create(e,t){return new r({in:e,out:t,typeName:m.ZodPipeline})}},se=class extends _{_parse(e){let t=this._def.innerType._parse(e),s=a=>(P(a)&&(a.value=Object.freeze(a.value)),a);return ne(t)?t.then(a=>s(a)):s(t)}unwrap(){return this._def.innerType}};se.create=(r,e)=>new se({innerType:r,typeName:m.ZodReadonly,...y(e)});function Se(r,e){let t=typeof r=="function"?r(e):typeof r=="string"?{message:r}:r;return typeof t=="string"?{message:t}:t}function Ie(r,e={},t){return r?D.create().superRefine((s,a)=>{let n=r(s);if(n instanceof Promise)return n.then(i=>{if(!i){let o=Se(e,s),f=o.fatal??t??true;a.addIssue({code:"custom",...o,fatal:f});}});if(!n){let i=Se(e,s),o=i.fatal??t??true;a.addIssue({code:"custom",...i,fatal:o});}}):D.create()}var ut={object:w.lazycreate},m;(function(r){r.ZodString="ZodString",r.ZodNumber="ZodNumber",r.ZodNaN="ZodNaN",r.ZodBigInt="ZodBigInt",r.ZodBoolean="ZodBoolean",r.ZodDate="ZodDate",r.ZodSymbol="ZodSymbol",r.ZodUndefined="ZodUndefined",r.ZodNull="ZodNull",r.ZodAny="ZodAny",r.ZodUnknown="ZodUnknown",r.ZodNever="ZodNever",r.ZodVoid="ZodVoid",r.ZodArray="ZodArray",r.ZodObject="ZodObject",r.ZodUnion="ZodUnion",r.ZodDiscriminatedUnion="ZodDiscriminatedUnion",r.ZodIntersection="ZodIntersection",r.ZodTuple="ZodTuple",r.ZodRecord="ZodRecord",r.ZodMap="ZodMap",r.ZodSet="ZodSet",r.ZodFunction="ZodFunction",r.ZodLazy="ZodLazy",r.ZodLiteral="ZodLiteral",r.ZodEnum="ZodEnum",r.ZodEffects="ZodEffects",r.ZodNativeEnum="ZodNativeEnum",r.ZodOptional="ZodOptional",r.ZodNullable="ZodNullable",r.ZodDefault="ZodDefault",r.ZodCatch="ZodCatch",r.ZodPromise="ZodPromise",r.ZodBranded="ZodBranded",r.ZodPipeline="ZodPipeline",r.ZodReadonly="ZodReadonly";})(m||(m={}));var lt=(r,e={message:`Input not instance of ${r.name}`})=>Ie(t=>t instanceof r,e),Ee=z.create,Ze=F.create,ft=le.create,ht=B.create,$e=W.create,pt=q.create,mt=oe.create,yt=J.create,_t=Y.create,gt=D.create,vt=Z.create,xt=A.create,kt=ce.create,bt=$.create,wt=w.create,Tt=w.strictCreate,Ct=H.create,Ot=_e.create,St=G.create,At=N.create,Rt=ge.create,Nt=de.create,jt=ue.create,It=ve.create,Et=Q.create,Zt=X.create,$t=K.create,Mt=ee.create,Vt=L.create,Pt=S.create,zt=C.create,Dt=j.create,Lt=S.createWithPreprocess,Ut=pe.create,Ft=()=>Ee().optional(),Bt=()=>Ze().optional(),Wt=()=>$e().optional(),qt={string:(r=>z.create({...r,coerce:true})),number:(r=>F.create({...r,coerce:true})),boolean:(r=>W.create({...r,coerce:true})),bigint:(r=>B.create({...r,coerce:true})),date:(r=>q.create({...r,coerce:true}))};var Jt=p;export{C as a,m as b,Me as c};//# sourceMappingURL=chunk-VQUSWD4U.js.map
2
- //# sourceMappingURL=chunk-VQUSWD4U.js.map