alran 0.9.0 → 1.0.1

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 (127) hide show
  1. package/ALRAN_TOOLS_NOTICES.md +11 -0
  2. package/README.md +11 -16
  3. package/assets/agents/alran/skills/alran-code-product/SKILL.md +3 -3
  4. package/assets/agents/alran/skills/alran-code-product/references/account-models.md +19 -16
  5. package/chunks/{account-commands-JZ6NXTTK.js → account-commands-GW7N3MYC.js} +1 -1
  6. package/chunks/{anthropic-MN33DP4E.js → anthropic-63VE6MAE.js} +1 -1
  7. package/chunks/{application-ITGAJ4HC.js → application-WPPTE6LU.js} +1 -1
  8. package/chunks/{auth-command-V3RVPLZO.js → auth-command-36RMNQZW.js} +1 -1
  9. package/chunks/azure-openai-responses-OIP3KVKJ.js +2 -0
  10. package/chunks/chunk-2K5H5GA7.js +2 -0
  11. package/chunks/chunk-3GGKARES.js +2 -0
  12. package/chunks/chunk-5RIMHTEU.js +207 -0
  13. package/chunks/{chunk-EYK25HWR.js → chunk-5Y76VFHY.js} +1 -1
  14. package/chunks/{chunk-QIN5ZBE2.js → chunk-6DOVXX7W.js} +1 -1
  15. package/chunks/{chunk-E3GLGDGC.js → chunk-6PFI65C6.js} +1 -1
  16. package/chunks/{chunk-4PDIO3M6.js → chunk-6UXSIWCB.js} +1 -1
  17. package/chunks/{chunk-OQNU3VPS.js → chunk-C6LAAFG2.js} +2 -2
  18. package/chunks/{chunk-33CNY6GP.js → chunk-CUG7F2FN.js} +1 -1
  19. package/chunks/chunk-DFMYLGVU.js +249 -0
  20. package/chunks/{chunk-IIE366LR.js → chunk-G5MOGPZ3.js} +490 -485
  21. package/chunks/{chunk-FC4M2B7E.js → chunk-IC6A323Q.js} +1 -1
  22. package/chunks/{chunk-4X22UJQH.js → chunk-IN2Z5SSJ.js} +1 -1
  23. package/chunks/chunk-JSTSFMGK.js +70 -0
  24. package/chunks/{chunk-WWNUAU4P.js → chunk-LCC45PCZ.js} +1 -1
  25. package/chunks/{chunk-7QLAXRD2.js → chunk-MPQ6G7LH.js} +254 -254
  26. package/chunks/{chunk-FUERW2DW.js → chunk-MUXNNOSQ.js} +1 -1
  27. package/chunks/{chunk-44VPC5LA.js → chunk-NBONSNQZ.js} +1 -1
  28. package/chunks/chunk-NMKRNU5O.js +2 -0
  29. package/chunks/chunk-NVPGGFT3.js +2 -0
  30. package/chunks/chunk-NZXJAHTO.js +9 -0
  31. package/chunks/{chunk-6255CZPL.js → chunk-PCL2CVVE.js} +1 -1
  32. package/chunks/chunk-PXH4SBCS.js +3 -0
  33. package/chunks/chunk-RLJVY75P.js +28 -0
  34. package/chunks/{chunk-WYANV3IX.js → chunk-RLND4AYL.js} +1 -1
  35. package/chunks/chunk-TJC4LPRQ.js +2 -0
  36. package/chunks/chunk-U4PFHJ7Z.js +27 -0
  37. package/chunks/chunk-V2SB4U4D.js +2 -0
  38. package/chunks/chunk-VGKKKM2W.js +6 -0
  39. package/chunks/{chunk-XFCC2CI2.js → chunk-VUISZDXX.js} +1 -1
  40. package/chunks/chunk-XVGPB7TW.js +21 -0
  41. package/chunks/{chunk-CJM7ZJ6W.js → chunk-ZDI22NOK.js} +1 -1
  42. package/chunks/{data-dir-LDVKDCJ2.js → data-dir-OEPRRIOO.js} +1 -1
  43. package/chunks/{dist-2BRD4JFU.js → dist-VKYZJYR6.js} +1 -1
  44. package/chunks/{dist-EXKHRFQO.js → dist-WGTMUM3E.js} +1 -1
  45. package/chunks/{ffi-OUPK6AY6.js → ffi-EFLUAAVX.js} +1 -1
  46. package/chunks/{ffi-M5UP5J6C.js → ffi-QKKA5HYI.js} +1 -1
  47. package/chunks/{google-UJAPMFAB.js → google-RCR46TTQ.js} +1 -1
  48. package/chunks/{google-vertex-VLSF55PW.js → google-vertex-Y26T7YYR.js} +1 -1
  49. package/chunks/{install-source-JTIUC4G4.js → install-source-63OVVBMK.js} +1 -1
  50. package/chunks/launcher-2UG3JPYF.js +63 -0
  51. package/chunks/lifecycle-5IPJRP2V.js +2 -0
  52. package/chunks/{main-TQGGRHTS.js → main-7SGOQBHZ.js} +2 -2
  53. package/chunks/{mistral-ZJZUEF2X.js → mistral-NEBDKUEI.js} +1 -1
  54. package/chunks/{module-6F3E5H7Y-BN7QWGYB.js → module-6F3E5H7Y-FIMLNSCK.js} +1 -1
  55. package/chunks/{module-asyncify-R6PWJ6ZV-P4FWSBAY.js → module-asyncify-R6PWJ6ZV-Q2HJ3NOC.js} +1 -1
  56. package/chunks/{multipart-parser-L6M455MS.js → multipart-parser-JVSLI2CL.js} +1 -1
  57. package/chunks/{network-proxy-U72JCK2I.js → network-proxy-AJO7ZW3O.js} +1 -1
  58. package/chunks/openai-codex-responses-L2CIGCKO.js +2 -0
  59. package/chunks/openai-completions-C4PHW6MD.js +2 -0
  60. package/chunks/openai-responses-5NVFOW4Y.js +2 -0
  61. package/chunks/{openrouter-G2EHY5BD.js → openrouter-BKUGQT7Z.js} +1 -1
  62. package/chunks/{otel-OHXIZ666.js → otel-DRJM2PIX.js} +1 -1
  63. package/chunks/plugin-command-CIDTOPNB.js +2 -0
  64. package/chunks/provider-command-UZ7KQFAC.js +2 -0
  65. package/chunks/run-acp-command-AKDLHKMR.js +59 -0
  66. package/chunks/{run-exec-command-5ADSQR2Z.js → run-exec-command-UXTPS7LC.js} +1 -1
  67. package/chunks/{skills-command-XXXEZAG6.js → skills-command-57TF53NO.js} +1 -1
  68. package/chunks/src-5PSNGHHD.js +2 -0
  69. package/chunks/{src-IBHIRTD7.js → src-YZ26EVSY.js} +1 -1
  70. package/chunks/telemetry-3NXMCOVD.js +2 -0
  71. package/chunks/{telemetry-command-COQG2AKK.js → telemetry-command-CMDERYNN.js} +1 -1
  72. package/chunks/{tools-WDBB2JKV.js → tools-CRJR35HS.js} +1 -1
  73. package/chunks/{undici-TUGHZJSA.js → undici-O4OQVZ6I.js} +1 -1
  74. package/chunks/{update-NB6OD572.js → update-ACFAGV6F.js} +1 -1
  75. package/cli.js +2 -3
  76. package/embedded/alran-tools/cli.mjs +1 -5
  77. package/embedded/alran-tools/manifest.json +1 -1
  78. package/image-preview-worker.js +1 -1
  79. package/matrix-mcp-stdio.js +1 -1
  80. package/package.json +1 -1
  81. package/quickjs-worker.js +1 -1
  82. package/chunks/azure-openai-responses-OWHMUNKC.js +0 -2
  83. package/chunks/chunk-C3CMJAAV.js +0 -3
  84. package/chunks/chunk-ENHOPPS7.js +0 -16
  85. package/chunks/chunk-FSNYOJPJ.js +0 -2
  86. package/chunks/chunk-FXOH6TEQ.js +0 -21
  87. package/chunks/chunk-GRXX6I72.js +0 -2
  88. package/chunks/chunk-GSYHBK5Q.js +0 -6
  89. package/chunks/chunk-IWK7PZP7.js +0 -207
  90. package/chunks/chunk-KCLRJQ53.js +0 -59
  91. package/chunks/chunk-M7GW4VMR.js +0 -27
  92. package/chunks/chunk-QFUV5PX6.js +0 -2
  93. package/chunks/chunk-TW23QKAD.js +0 -3
  94. package/chunks/chunk-U7U3DJHF.js +0 -2
  95. package/chunks/chunk-WTAJMYF2.js +0 -249
  96. package/chunks/chunk-YLQXZBEL.js +0 -2
  97. package/chunks/chunk-Z6BHCXKT.js +0 -25
  98. package/chunks/chunk-Z6HBNJCA.js +0 -8
  99. package/chunks/launcher-FCZ3EDBF.js +0 -61
  100. package/chunks/lifecycle-GY435YMF.js +0 -2
  101. package/chunks/openai-codex-responses-FPCDNRL5.js +0 -2
  102. package/chunks/openai-completions-D32YW6KL.js +0 -2
  103. package/chunks/openai-responses-ZCGSENM4.js +0 -2
  104. package/chunks/plugin-command-OSAFHS7C.js +0 -2
  105. package/chunks/provider-command-SKTCHD4E.js +0 -2
  106. package/chunks/run-acp-command-SG2BDMFJ.js +0 -2
  107. package/chunks/src-DNIDEMVV.js +0 -2
  108. package/chunks/telemetry-J7ZLGF5X.js +0 -2
  109. /package/chunks/{chunk-EOR6EDNR.js → chunk-2AYWJZ72.js} +0 -0
  110. /package/chunks/{chunk-YPV2X2RG.js → chunk-4XP5XUIZ.js} +0 -0
  111. /package/chunks/{chunk-NWB7LFOK.js → chunk-5DQTVSQV.js} +0 -0
  112. /package/chunks/{chunk-OIQ336YE.js → chunk-EJN3SE5B.js} +0 -0
  113. /package/chunks/{chunk-A7GMJNA2.js → chunk-K5DTFR6D.js} +0 -0
  114. /package/chunks/{chunk-ZQOALVGL.js → chunk-R44C5DM6.js} +0 -0
  115. /package/chunks/{chunk-PNXZWSWT.js → chunk-UJCAE7SG.js} +0 -0
  116. /package/chunks/{chunk-J3KCPYZT.js → chunk-W5ZOLW7T.js} +0 -0
  117. /package/chunks/{chunk-XAGZ6ZEU.js → chunk-XLVABFJC.js} +0 -0
  118. /package/chunks/{chunk-N5SVBCUB.js → chunk-XSEU4WQD.js} +0 -0
  119. /package/chunks/{chunk-CSOUJVKM.js → chunk-Z5HOCNTZ.js} +0 -0
  120. /package/chunks/{emscripten-module-ZS3PMSDF.js → emscripten-module-3WGSFZYF.js} +0 -0
  121. /package/chunks/{emscripten-module-XPTEOIWW.js → emscripten-module-74WUXTHL.js} +0 -0
  122. /package/chunks/{emscripten-module-WYNDFH3N.js → emscripten-module-MCN4Y3N4.js} +0 -0
  123. /package/chunks/{emscripten-module-RD6P2XH5.js → emscripten-module-NEAT5LGD.js} +0 -0
  124. /package/chunks/{ffi-ORLOPBB3.js → ffi-JIGPPPF7.js} +0 -0
  125. /package/chunks/{ffi-IO7WZQNG.js → ffi-RLX77WFG.js} +0 -0
  126. /package/chunks/{pdfjs-SHZAF7PF.js → pdfjs-2UOWBGC2.js} +0 -0
  127. /package/chunks/{photon_rs-C52RL4CI.js → photon_rs-MVWYTYTO.js} +0 -0
@@ -1,4 +1,4 @@
1
1
  import { createRequire as __alran_cR } from "module"; import { basename as __alran_basename, dirname as __alran_dirname, join as __alran_join } from "path"; import { fileURLToPath as __alran_fileURLToPath, pathToFileURL as __alran_pathToFileURL } from "url"; const __alran_tuiCurrentModuleDir = __alran_dirname(__alran_fileURLToPath(import.meta.url)); const __alran_tuiPackageRoot = __alran_basename(__alran_tuiCurrentModuleDir) === "chunks" ? __alran_dirname(__alran_tuiCurrentModuleDir) : __alran_tuiCurrentModuleDir; const __alran_tuiPackageEntryUrl = __alran_pathToFileURL(__alran_join(__alran_tuiPackageRoot, "cli.js")).href; const require = __alran_cR(__alran_tuiPackageEntryUrl); const __dirname = __alran_tuiPackageRoot;
2
- import{o as q}from"./chunk-XFCC2CI2.js";var Q="alran.store/v1";var ee="alran.store.installed/v1";var be="alran.store.sources/v1";var F="ottili";var Ne="https://ai.ottili.one/v1/store/index.json";var ge="off";var he="ALRAN_STORE_URL";var O={indexBytes:8*1024*1024,entries:5e3,fetchTimeoutMs:2e4,freshForMs:10*60*1e3};var ye=["Office","Studio","Design & Sites","Code","Business","Sales","Productivity","Science & Healthcare","Education","Other"];var u=class extends Error{constructor(r,n,o){super(n,o);this.code=r;this.name="StoreError"}code};var te=/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u;var ne=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u;var Se=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;var re=/^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(?:-((?:0|[1-9][0-9]*|[0-9]*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9][0-9]*|[0-9]*[A-Za-z-][0-9A-Za-z-]*))*))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/u;var Oe=/^[0-9a-f]{64}$/u;var Pe=/^sha256-tree-v1:[0-9a-f]{64}$/u;import ln from"node:path";import{randomBytes as ct}from"node:crypto";import{mkdirSync as dt,renameSync as Ce,rmSync as ut}from"node:fs";import{mkdir as we,readFile as ft,rename as pt,rm as Ee,stat as ve,writeFile as mt}from"node:fs/promises";import oe from"node:path";function x(t){return oe.join(t,"store")}function H(){return ct(6).toString("hex")}function De(t){return typeof t==="object"&&t!==null&&"code"in t&&t.code==="ENOENT"}async function P(t){try{return await ft(t,"utf8")}catch(e){if(De(e))return void 0;throw e}}async function V(t,e){await we(oe.dirname(t),{recursive:true});const r=`${t}.${H()}.tmp`;try{await mt(r,e,{encoding:"utf8",mode:384});q(()=>Ce(r,t))}catch(n){await Ee(r,{force:true});throw n}}function ie(t,e){dt(oe.dirname(e),{recursive:true});q(()=>Ce(t,e))}function se(t){q(()=>ut(t,{recursive:true,force:true}))}async function j(t){try{await ve(t);return true}catch(e){if(De(e))return false;throw e}}var gt=6e4;var ht=15e3;async function U(t,e){const r=oe.join(x(t),"lock");await we(x(t),{recursive:true});const n=Date.now()+ht;for(;;){try{await we(r);break}catch(o){if(typeof o!=="object"||o===null||!("code"in o))throw o;if(o.code!=="EEXIST")throw o;const i=await ve(r).then(a=>Date.now()-a.mtimeMs,()=>0);if(i>gt){await Ee(r,{recursive:true,force:true});continue}if(Date.now()>n)throw new Error("The Store is busy in another Alran process.");await new Promise(a=>{setTimeout(a,100)})}}try{return await e()}finally{const o=`${r}.${H()}.released`;await pt(r,o).then(()=>Ee(o,{recursive:true,force:true}),()=>void 0)}}import{existsSync as wt}from"node:fs";import{readdir as Et,readFile as It}from"node:fs/promises";import{fileURLToPath as At}from"node:url";import $t from"node:path";var yt=/[\u0000-\u001f\u007f-\u009f؜‎‏‪-‮⁦-⁩]/gu;function C(t){return t.replace(yt,e=>`\\u{${e.codePointAt(0)?.toString(16)}}`)}function T(t){return C(t.replace(/\s+/gu," ").trim())}function Ue(t,e){const r=new Map(t.map(I=>[I.path,I.content]));const n=r.get(".alran-plugin/plugin.json");if(!n)y("has no .alran-plugin/plugin.json");const o=ae(n,".alran-plugin/plugin.json");if(o.schemaVersion!==1)y("manifest schemaVersion must be 1");const i=_(o.name,"manifest name");if(!te.test(i)||i!==e.name){y(`manifest name "${i}" is not the listed name "${e.name}"`)}const a=_(o.version,"manifest version");if(!re.test(a)||a!==e.version){y(`manifest version "${a}" is not the listed version "${e.version}"`)}const s=_(o.icon,"manifest icon");if(!r.has(s))y(`icon ${s} is missing`);const l=z(o.skills,"skills").map(I=>{const m=_(I,"skills entry");const A=/^skills\/([A-Za-z0-9._-]+)\/SKILL\.md$/u.exec(m);if(!A?.[1])y(`skill reference ${m} is not skills/<name>/SKILL.md`);const $=r.get(m);if(!$)y(`${m} is missing`);const w=G($.toString("utf8"),m);if(w.name!==A[1])y(`${m} names the skill "${w.name}"`);return{name:w.name,description:T(w.description),hasScripts:[...r.keys()].some(b=>b.startsWith(`skills/${A[1]}/scripts/`))}});const c=[];const d=[];for(const I of z(o.mcpServers,"mcpServers")){const m=_(I,"mcpServers entry");const A=ae(Ie(r,m),m);const $=W(A.mcpServers,`${m} mcpServers`);for(const[w,b]of Object.entries($)){const k=W(b,`${m} server ${w}`);d.push(C(w));if(k.type==="stdio"){const N=Array.isArray(k.args)?k.args.map(String):[];c.push({kind:"mcp-stdio",line:C(`MCP server "${w}" runs: ${[String(k.command),...N].join(" ")}`)})}else{c.push({kind:"mcp-remote",line:C(`MCP server "${w}" connects to: ${String(k.url)}`)})}}}const p=[];for(const I of z(o.apps,"apps")){const m=_(I,"apps entry");const A=_(ae(Ie(r,m),m).provider,`${m} provider`);p.push(C(A));c.push({kind:"app",line:C(`Connector "${A}" asks to link an account`)})}let h=0;for(const I of z(o.hooks,"hooks")){const m=_(I,"hooks entry");const A=ae(Ie(r,m),m);for(const[$,w]of Object.entries(W(A.hooks,`${m} hooks`))){for(const b of z(w,`${m} ${$}`)){for(const k of z(W(b,`${m} ${$} group`).hooks,"hooks")){const N=W(k,`${m} ${$} handler`);if(N.type!=="command")continue;h+=1;c.push({kind:"hook",line:C(`Hook on ${$} runs: ${String(N.command)}`)})}}}}const D=typeof o.displayName==="string"&&o.displayName.trim()?o.displayName.trim():i;return{kind:"plugin",name:i,version:a,displayName:T(D),description:T(_(o.description,"manifest description")),author:T(_(o.author,"manifest author")),category:_(o.category,"manifest category"),skills:l,mcpServers:d,apps:p,hooks:h,files:t.length,executes:c,requiresConsent:c.length>0}}function Me(t,e){if(!ne.test(e.name))y(`"${e.name}" is not a Skill name`);const r=t.find(o=>o.path==="SKILL.md");if(!r)y("has no SKILL.md at its root");const n=G(r.content.toString("utf8"),"SKILL.md");if(n.name!==e.name){y(`SKILL.md names the skill "${n.name}", the store lists "${e.name}"`)}return{kind:"skill",name:n.name,description:T(n.description),files:t.length,hasScripts:t.some(o=>o.path.startsWith("scripts/")),executes:[],requiresConsent:false}}function G(t,e){if(t.charCodeAt(0)===65279)y(`${e} starts with a byte order mark`);const r=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/u.exec(t);if(!r?.[1])y(`${e} has no YAML frontmatter`);const n=St(r[1]);const o=n.get("name");const i=n.get("description");if(!o)y(`${e} frontmatter has no name`);if(!i)y(`${e} frontmatter has no description`);return{name:o,description:i}}function St(t){const e=new Map;const r=t.split(/\r?\n/u);for(let n=0;n<r.length;n+=1){const o=r[n]??"";const i=/^([A-Za-z0-9_-]+)\s*:\s*(.*)$/u.exec(o);if(!i?.[1])continue;const a=i[1];let s=(i[2]??"").trim();if(/^[|>][+-]?$/u.test(s)){const l=s.startsWith(">");const c=[];while(n+1<r.length&&/^(\s+|$)/u.test(r[n+1]??"")){n+=1;c.push((r[n]??"").trim())}s=c.filter((d,p)=>d||p<c.length-1).join(l?" ":"\n").trim()}else if(s.startsWith('"')&&s.endsWith('"')&&s.length>=2){try{s=JSON.parse(s)}catch{s=s.slice(1,-1)}}else if(s.startsWith("'")&&s.endsWith("'")&&s.length>=2){s=s.slice(1,-1).replace(/''/gu,"'")}else if(s===""){const l=[];while(n+1<r.length&&/^\s+\S/u.test(r[n+1]??"")){n+=1;l.push((r[n]??"").trim())}s=l.join(" ")}if(!e.has(a))e.set(a,s)}return e}function ae(t,e){let r;try{r=JSON.parse(t.toString("utf8"))}catch{y(`${e} is not valid JSON`)}return W(r,e)}function Ie(t,e){const r=t.get(e);if(!r)y(`${e} is listed in the manifest but missing`);return r}function W(t,e){if(typeof t!=="object"||t===null||Array.isArray(t)){y(`${e} must be an object`)}return t}function z(t,e){if(t===void 0)return[];if(!Array.isArray(t))y(`${e} must be an array`);return t}function _(t,e){if(typeof t!=="string"||!t.trim())y(`${e} must be a non-empty string`);return t.trim()}function y(t){throw new u("PACKAGE_INVALID",`The package ${t}.`)}function Be(t){const e=["../assets/skills/","./assets/skills/","../../../local-runtime/assets/skills/"];for(const r of e){const n=At(new URL(r,t));if(wt(n))return n}return void 0}async function Fe(t){let e;try{e=await Et(t)}catch{return[]}const r=[];for(const n of e.sort()){try{const o=await It($t.join(t,n,"SKILL.md"),"utf8");const i=G(o,`${n}/SKILL.md`);r.push({name:i.name,description:T(i.description)})}catch{}}return r}import{mkdir as Ze,writeFile as Zt}from"node:fs/promises";import B from"node:path";import{createHash as He}from"node:crypto";var L={archiveBytes:64*1024*1024,entries:2048,files:1024,fileBytes:16*1024*1024,totalBytes:64*1024*1024,pathBytes:512,segmentBytes:128,pathSegments:16};var J=class extends Error{constructor(r,n){super(`${r}: ${n}`);this.code=r;this.detail=n;this.name="StoreArchiveError"}code;detail};var kt=67324752;var xt=33639248;var _t=101010256;var Rt=61440;var Lt=32768;var Tt=16384;var bt=40960;var Nt=/^[A-Za-z0-9._-]+$/u;var Ot=new Set(["con","prn","aux","nul",...Array.from({length:9},(t,e)=>`com${e+1}`),...Array.from({length:9},(t,e)=>`lpt${e+1}`)]);var Pt=Buffer.from("ALRAN-PLUGIN-CONTENT-DIGEST\0","ascii");function Ct(t){if(!t)f("INVALID_PATH","path is empty");if(!/^[\x00-\x7f]*$/u.test(t)){f("NON_PORTABLE_PATH",`${JSON.stringify(t)} is not ASCII`)}if(t.startsWith("/")||/^[A-Za-z]:/u.test(t)){f("ABSOLUTE_PATH",`${JSON.stringify(t)} is absolute`)}if(t.includes("\\")){f("BACKSLASH_PATH",`${JSON.stringify(t)} contains a backslash`)}if(t.endsWith("/")){f("INVALID_PATH",`${JSON.stringify(t)} has a trailing slash`)}if(/[\x00-\x1f\x7f]/u.test(t)){f("CONTROL_CHARACTER",`${JSON.stringify(t)} contains a control character`)}if(t.length>L.pathBytes){f("PATH_TOO_LONG",`${JSON.stringify(t)} exceeds the path limit`)}const e=t.split("/");if(e.length>L.pathSegments){f("PATH_TOO_DEEP",`${JSON.stringify(t)} has too many segments`)}for(const r of e){if(!r||r==="."||r===".."){f("PATH_TRAVERSAL",`${JSON.stringify(t)} has an empty or dot segment`)}if(r.length>L.segmentBytes){f("SEGMENT_TOO_LONG",`${JSON.stringify(r)} exceeds the segment limit`)}if(!Nt.test(r)||r.endsWith(".")){f("NON_PORTABLE_PATH",`${JSON.stringify(r)} is not portable`)}const[n=""]=r.split(".",1);if(Ot.has(n.toLowerCase())){f("WINDOWS_RESERVED_PATH",`${JSON.stringify(r)} is reserved on Windows`)}}}function vt(t){const e=[...t].sort((n,o)=>Buffer.compare(Buffer.from(n.path,"ascii"),Buffer.from(o.path,"ascii")));const r=He("sha256");r.update(Pt);r.update(Ae(1));r.update(Ae(e.length));for(const n of e){const o=Buffer.from(n.path,"ascii");r.update(Buffer.from([70]));r.update(Ae(o.length));r.update(o);r.update(jt(n.content.length));r.update(n.content)}return`sha256-tree-v1:${r.digest("hex")}`}function Ve(t){return He("sha256").update(t).digest("hex")}function je(t){if(t.length>L.archiveBytes){f("ARCHIVE_TOO_LARGE",`${t.length} bytes exceed the archive limit`)}if(t.length<22)f("INVALID_ZIP","end-of-central-directory record is missing");const e=Dt(t);const r=Ut(t,e);const n=[];const o=[];const i=new Set;const a=new Map;const s=new Set;let l=0;for(const d of r){const p=Mt(t,d,e.centralOffset);o.push({start:d.localOffset,end:p.end});const h=t.subarray(p.data,p.end);if(Wt(h)!==d.crc)f("CRC_MISMATCH",`${d.path} has an invalid CRC`);if(d.kind==="symlink")f("SYMLINK_NOT_ALLOWED",`${d.path} is a symlink`);if(d.kind==="special")f("SPECIAL_ENTRY_NOT_ALLOWED",`${d.path} is special`);Ct(d.path);if(i.has(d.path))f("DUPLICATE_PATH",`${d.path} appears twice`);i.add(d.path);Ht(d.path,a);if(d.kind==="directory")continue;s.add(d.path);if(h.length>L.fileBytes){f("FILE_TOO_LARGE",`${d.path} exceeds the per-file limit`)}l+=h.length;if(l>L.totalBytes){f("TOTAL_SIZE_LIMIT","unpacked size exceeds the total limit")}n.push({path:d.path,content:h})}if(n.length>L.files)f("TOO_MANY_FILES",`${n.length} files`);Ft(o);Vt(i,s);const c=[...n].sort((d,p)=>Buffer.compare(Buffer.from(d.path,"ascii"),Buffer.from(p.path,"ascii")));return{files:c,contentDigest:vt(c),totalBytes:l}}function Dt(t){const e=t.length-22;$e(t,e,_t,"end-of-central-directory");const r=E(t,e+4);const n=E(t,e+6);const o=E(t,e+8);const i=E(t,e+10);const a=R(t,e+12);const s=R(t,e+16);if(E(t,e+20)!==0)f("ARCHIVE_COMMENT_NOT_ALLOWED","comment not empty");if(r!==0||n!==0||o!==i){f("MULTI_DISK_NOT_ALLOWED","multi-disk ZIP is not supported")}if(i===65535||a===4294967295||s===4294967295){f("ZIP64_NOT_ALLOWED","ZIP64 sentinel values are not supported")}if(i>L.entries)f("TOO_MANY_ENTRIES",`${i} entries`);if(s+a!==e){f("INVALID_ZIP","central directory bounds do not match the archive")}return{endOffset:e,entryCount:i,centralOffset:s}}function Ut(t,e){const r=[];let n=e.centralOffset;for(let o=0;o<e.entryCount;o+=1){M(t,n,46,"central directory header");$e(t,n,xt,"central directory");const i=E(t,n+4);const a=E(t,n+8);const s=E(t,n+10);const l=R(t,n+16);const c=R(t,n+20);const d=R(t,n+24);const p=E(t,n+28);const h=E(t,n+30);const D=E(t,n+32);const I=E(t,n+34);const m=R(t,n+38);const A=R(t,n+42);ze(a);if(s!==0)f("UNSUPPORTED_COMPRESSION",`ZIP method ${s} is not STORE`);if(c===4294967295||d===4294967295){f("ZIP64_NOT_ALLOWED","ZIP64 entry values are not supported")}if(A===4294967295)f("ZIP64_NOT_ALLOWED","ZIP64 offset");if(h!==0)f("EXTRA_FIELD_NOT_ALLOWED","ZIP extra fields are not supported");if(D!==0)f("ENTRY_COMMENT_NOT_ALLOWED","entry comments are not supported");if(I!==0)f("MULTI_DISK_NOT_ALLOWED","entry on a non-zero disk");if(c!==d)f("SIZE_MISMATCH","STORE sizes differ");const $=n+46+p;M(t,n+46,p,"central entry name");if($>e.endOffset)f("INVALID_ZIP","central entry exceeds the directory");const w=t.subarray(n+46,$);if(w.length===0)f("INVALID_PATH","ZIP entry name is empty");if(w.some(lt=>lt>127))f("NON_PORTABLE_PATH","entry name is not ASCII");const b=w.toString("ascii");const k=b.endsWith("/");const N=k?b.slice(0,-1):b;const X=Bt(i,m,k);if(X==="directory"&&!k)f("INVALID_DIRECTORY_ENTRY",N);if(X!=="directory"&&k)f("INVALID_DIRECTORY_ENTRY",N);if(X==="directory"&&d!==0)f("INVALID_DIRECTORY_ENTRY",N);r.push({path:N,rawName:w,kind:X,flags:a,method:s,crc:l,compressedSize:c,uncompressedSize:d,localOffset:A});n=$}if(n!==e.endOffset)f("INVALID_ZIP","central directory entry count is inconsistent");return r}function Mt(t,e,r){const n=e.localOffset;M(t,n,30,"local file header");$e(t,n,kt,"local file");const o=E(t,n+6);const i=E(t,n+8);const a=R(t,n+14);const s=R(t,n+18);const l=R(t,n+22);const c=E(t,n+26);const d=E(t,n+28);ze(o);if(d!==0)f("EXTRA_FIELD_NOT_ALLOWED","local ZIP extra field is not empty");if(o!==e.flags||i!==e.method||a!==e.crc||s!==e.compressedSize||l!==e.uncompressedSize){f("LOCAL_HEADER_MISMATCH",`${e.path} local and central headers differ`)}M(t,n+30,c,"local entry name");if(!t.subarray(n+30,n+30+c).equals(e.rawName)){f("LOCAL_HEADER_MISMATCH",`${e.path} local and central names differ`)}const p=n+30+c;const h=p+s;if(h>r)f("INVALID_ZIP",`${e.path} data overlaps the directory`);return{data:p,end:h}}function Bt(t,e,r){if(t>>>8===3){const n=e>>>16&Rt;if(n===bt)return"symlink";if(n===Tt)return"directory";if(n===Lt||n===0)return r?"directory":"file";return"special"}return(e&16)!==0||r?"directory":"file"}function ze(t){if((t&1)!==0)f("ENCRYPTION_NOT_ALLOWED","encrypted ZIP entry");if((t&8)!==0)f("DATA_DESCRIPTOR_NOT_ALLOWED","data descriptor ZIP entry");if(t!==0)f("UNSUPPORTED_ZIP_FLAGS",`unsupported ZIP flags 0x${t.toString(16)}`)}function Ft(t){t.sort((e,r)=>e.start-r.start);for(let e=1;e<t.length;e+=1){const r=t[e];const n=t[e-1];if(r&&n&&r.start<n.end){f("OVERLAPPING_ENTRIES","local ZIP entries overlap")}}}function Ht(t,e){const r=t.split("/");for(let n=1;n<=r.length;n+=1){const o=r.slice(0,n).join("/");const i=o.toLowerCase();const a=e.get(i);if(a!==void 0&&a!==o){f("CASE_COLLISION",`${o} and ${a} differ only by case`)}e.set(i,o)}}function Vt(t,e){for(const r of t){const n=r.split("/");for(let o=1;o<n.length;o+=1){const i=n.slice(0,o).join("/");if(e.has(i)){f("PATH_TYPE_CONFLICT",`${i} is a file but ${r} lies beneath it`)}}}}function $e(t,e,r,n){M(t,e,4,`${n} signature`);if(R(t,e)!==r)f("INVALID_ZIP",`${n} signature is invalid`)}function M(t,e,r,n){if(e<0||r<0||e+r>t.length){f("INVALID_ZIP",`${n} exceeds archive bounds`)}}function E(t,e){M(t,e,2,"uint16");return t.readUInt16LE(e)}function R(t,e){M(t,e,4,"uint32");return t.readUInt32LE(e)}function Ae(t){const e=Buffer.alloc(4);e.writeUInt32BE(t);return e}function jt(t){const e=Buffer.alloc(8);e.writeBigUInt64BE(BigInt(t));return e}var zt=Array.from({length:256},(t,e)=>{let r=e;for(let n=0;n<8;n+=1){r=(r&1)===1?3988292384^r>>>1:r>>>1}return r>>>0});function Wt(t){let e=4294967295;for(const r of t)e=(zt[(e^r)&255]??0)^e>>>8;return(e^4294967295)>>>0}function f(t,e){throw new J(t,e)}import{rename as Gt}from"node:fs/promises";import Kt from"node:path";var We={schema:ee,plugins:{},skills:{}};var le=class{constructor(e){this.dataDir=e}dataDir;async read(){const e=this.file();const r=await P(e);if(r===void 0)return We;try{const n=JSON.parse(r);if(n.schema!==ee)throw new Error("unknown schema");return{schema:ee,plugins:Ke(n.plugins),skills:Ke(n.skills)}}catch{await Gt(e,`${e}.corrupt-${H()}`).catch(()=>void 0);return We}}async record(e,r,n){const o=await this.read();const i=Ge(o,e,r,n);await this.write(i);return i}async forget(e,r){const n=await this.read();const o=Ge(n,e,r,void 0);await this.write(o);return o}async write(e){await V(this.file(),`${JSON.stringify(e,null,2)}
2
+ import{o as q}from"./chunk-VUISZDXX.js";var Q="alran.store/v1";var ee="alran.store.installed/v1";var be="alran.store.sources/v1";var F="ottili";var Ne="https://ai.ottili.one/v1/store/index.json";var ge="off";var he="ALRAN_STORE_URL";var O={indexBytes:8*1024*1024,entries:5e3,fetchTimeoutMs:2e4,freshForMs:10*60*1e3};var ye=["Office","Studio","Design & Sites","Code","Business","Sales","Productivity","Science & Healthcare","Education","Other"];var u=class extends Error{constructor(r,n,o){super(n,o);this.code=r;this.name="StoreError"}code};var te=/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u;var ne=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u;var Se=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;var re=/^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(?:-((?:0|[1-9][0-9]*|[0-9]*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9][0-9]*|[0-9]*[A-Za-z-][0-9A-Za-z-]*))*))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/u;var Oe=/^[0-9a-f]{64}$/u;var Pe=/^sha256-tree-v1:[0-9a-f]{64}$/u;import ln from"node:path";import{randomBytes as ct}from"node:crypto";import{mkdirSync as dt,renameSync as Ce,rmSync as ut}from"node:fs";import{mkdir as we,readFile as ft,rename as pt,rm as Ee,stat as ve,writeFile as mt}from"node:fs/promises";import oe from"node:path";function x(t){return oe.join(t,"store")}function H(){return ct(6).toString("hex")}function De(t){return typeof t==="object"&&t!==null&&"code"in t&&t.code==="ENOENT"}async function P(t){try{return await ft(t,"utf8")}catch(e){if(De(e))return void 0;throw e}}async function V(t,e){await we(oe.dirname(t),{recursive:true});const r=`${t}.${H()}.tmp`;try{await mt(r,e,{encoding:"utf8",mode:384});q(()=>Ce(r,t))}catch(n){await Ee(r,{force:true});throw n}}function ie(t,e){dt(oe.dirname(e),{recursive:true});q(()=>Ce(t,e))}function se(t){q(()=>ut(t,{recursive:true,force:true}))}async function j(t){try{await ve(t);return true}catch(e){if(De(e))return false;throw e}}var gt=6e4;var ht=15e3;async function U(t,e){const r=oe.join(x(t),"lock");await we(x(t),{recursive:true});const n=Date.now()+ht;for(;;){try{await we(r);break}catch(o){if(typeof o!=="object"||o===null||!("code"in o))throw o;if(o.code!=="EEXIST")throw o;const i=await ve(r).then(a=>Date.now()-a.mtimeMs,()=>0);if(i>gt){await Ee(r,{recursive:true,force:true});continue}if(Date.now()>n)throw new Error("The Store is busy in another Alran process.");await new Promise(a=>{setTimeout(a,100)})}}try{return await e()}finally{const o=`${r}.${H()}.released`;await pt(r,o).then(()=>Ee(o,{recursive:true,force:true}),()=>void 0)}}import{existsSync as wt}from"node:fs";import{readdir as Et,readFile as It}from"node:fs/promises";import{fileURLToPath as At}from"node:url";import $t from"node:path";var yt=/[\u0000-\u001f\u007f-\u009f؜‎‏‪-‮⁦-⁩]/gu;function C(t){return t.replace(yt,e=>`\\u{${e.codePointAt(0)?.toString(16)}}`)}function T(t){return C(t.replace(/\s+/gu," ").trim())}function Ue(t,e){const r=new Map(t.map(I=>[I.path,I.content]));const n=r.get(".alran-plugin/plugin.json");if(!n)y("has no .alran-plugin/plugin.json");const o=ae(n,".alran-plugin/plugin.json");if(o.schemaVersion!==1)y("manifest schemaVersion must be 1");const i=_(o.name,"manifest name");if(!te.test(i)||i!==e.name){y(`manifest name "${i}" is not the listed name "${e.name}"`)}const a=_(o.version,"manifest version");if(!re.test(a)||a!==e.version){y(`manifest version "${a}" is not the listed version "${e.version}"`)}const s=_(o.icon,"manifest icon");if(!r.has(s))y(`icon ${s} is missing`);const l=z(o.skills,"skills").map(I=>{const m=_(I,"skills entry");const A=/^skills\/([A-Za-z0-9._-]+)\/SKILL\.md$/u.exec(m);if(!A?.[1])y(`skill reference ${m} is not skills/<name>/SKILL.md`);const $=r.get(m);if(!$)y(`${m} is missing`);const w=G($.toString("utf8"),m);if(w.name!==A[1])y(`${m} names the skill "${w.name}"`);return{name:w.name,description:T(w.description),hasScripts:[...r.keys()].some(b=>b.startsWith(`skills/${A[1]}/scripts/`))}});const c=[];const d=[];for(const I of z(o.mcpServers,"mcpServers")){const m=_(I,"mcpServers entry");const A=ae(Ie(r,m),m);const $=W(A.mcpServers,`${m} mcpServers`);for(const[w,b]of Object.entries($)){const k=W(b,`${m} server ${w}`);d.push(C(w));if(k.type==="stdio"){const N=Array.isArray(k.args)?k.args.map(String):[];c.push({kind:"mcp-stdio",line:C(`MCP server "${w}" runs: ${[String(k.command),...N].join(" ")}`)})}else{c.push({kind:"mcp-remote",line:C(`MCP server "${w}" connects to: ${String(k.url)}`)})}}}const p=[];for(const I of z(o.apps,"apps")){const m=_(I,"apps entry");const A=_(ae(Ie(r,m),m).provider,`${m} provider`);p.push(C(A));c.push({kind:"app",line:C(`Connector "${A}" asks to link an account`)})}let h=0;for(const I of z(o.hooks,"hooks")){const m=_(I,"hooks entry");const A=ae(Ie(r,m),m);for(const[$,w]of Object.entries(W(A.hooks,`${m} hooks`))){for(const b of z(w,`${m} ${$}`)){for(const k of z(W(b,`${m} ${$} group`).hooks,"hooks")){const N=W(k,`${m} ${$} handler`);if(N.type!=="command")continue;h+=1;c.push({kind:"hook",line:C(`Hook on ${$} runs: ${String(N.command)}`)})}}}}const D=typeof o.displayName==="string"&&o.displayName.trim()?o.displayName.trim():i;return{kind:"plugin",name:i,version:a,displayName:T(D),description:T(_(o.description,"manifest description")),author:T(_(o.author,"manifest author")),category:_(o.category,"manifest category"),skills:l,mcpServers:d,apps:p,hooks:h,files:t.length,executes:c,requiresConsent:c.length>0}}function Me(t,e){if(!ne.test(e.name))y(`"${e.name}" is not a Skill name`);const r=t.find(o=>o.path==="SKILL.md");if(!r)y("has no SKILL.md at its root");const n=G(r.content.toString("utf8"),"SKILL.md");if(n.name!==e.name){y(`SKILL.md names the skill "${n.name}", the store lists "${e.name}"`)}return{kind:"skill",name:n.name,description:T(n.description),files:t.length,hasScripts:t.some(o=>o.path.startsWith("scripts/")),executes:[],requiresConsent:false}}function G(t,e){if(t.charCodeAt(0)===65279)y(`${e} starts with a byte order mark`);const r=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/u.exec(t);if(!r?.[1])y(`${e} has no YAML frontmatter`);const n=St(r[1]);const o=n.get("name");const i=n.get("description");if(!o)y(`${e} frontmatter has no name`);if(!i)y(`${e} frontmatter has no description`);return{name:o,description:i}}function St(t){const e=new Map;const r=t.split(/\r?\n/u);for(let n=0;n<r.length;n+=1){const o=r[n]??"";const i=/^([A-Za-z0-9_-]+)\s*:\s*(.*)$/u.exec(o);if(!i?.[1])continue;const a=i[1];let s=(i[2]??"").trim();if(/^[|>][+-]?$/u.test(s)){const l=s.startsWith(">");const c=[];while(n+1<r.length&&/^(\s+|$)/u.test(r[n+1]??"")){n+=1;c.push((r[n]??"").trim())}s=c.filter((d,p)=>d||p<c.length-1).join(l?" ":"\n").trim()}else if(s.startsWith('"')&&s.endsWith('"')&&s.length>=2){try{s=JSON.parse(s)}catch{s=s.slice(1,-1)}}else if(s.startsWith("'")&&s.endsWith("'")&&s.length>=2){s=s.slice(1,-1).replace(/''/gu,"'")}else if(s===""){const l=[];while(n+1<r.length&&/^\s+\S/u.test(r[n+1]??"")){n+=1;l.push((r[n]??"").trim())}s=l.join(" ")}if(!e.has(a))e.set(a,s)}return e}function ae(t,e){let r;try{r=JSON.parse(t.toString("utf8"))}catch{y(`${e} is not valid JSON`)}return W(r,e)}function Ie(t,e){const r=t.get(e);if(!r)y(`${e} is listed in the manifest but missing`);return r}function W(t,e){if(typeof t!=="object"||t===null||Array.isArray(t)){y(`${e} must be an object`)}return t}function z(t,e){if(t===void 0)return[];if(!Array.isArray(t))y(`${e} must be an array`);return t}function _(t,e){if(typeof t!=="string"||!t.trim())y(`${e} must be a non-empty string`);return t.trim()}function y(t){throw new u("PACKAGE_INVALID",`The package ${t}.`)}function Be(t){const e=["../assets/skills/","./assets/skills/","../../../local-runtime/assets/skills/"];for(const r of e){const n=At(new URL(r,t));if(wt(n))return n}return void 0}async function Fe(t){let e;try{e=await Et(t)}catch{return[]}const r=[];for(const n of e.sort()){try{const o=await It($t.join(t,n,"SKILL.md"),"utf8");const i=G(o,`${n}/SKILL.md`);r.push({name:i.name,description:T(i.description)})}catch{}}return r}import{mkdir as Ze,writeFile as Zt}from"node:fs/promises";import B from"node:path";import{createHash as He}from"node:crypto";var L={archiveBytes:64*1024*1024,entries:2048,files:1024,fileBytes:16*1024*1024,totalBytes:64*1024*1024,pathBytes:512,segmentBytes:128,pathSegments:16};var J=class extends Error{constructor(r,n){super(`${r}: ${n}`);this.code=r;this.detail=n;this.name="StoreArchiveError"}code;detail};var kt=67324752;var xt=33639248;var _t=101010256;var Rt=61440;var Lt=32768;var Tt=16384;var bt=40960;var Nt=/^[A-Za-z0-9._-]+$/u;var Ot=new Set(["con","prn","aux","nul",...Array.from({length:9},(t,e)=>`com${e+1}`),...Array.from({length:9},(t,e)=>`lpt${e+1}`)]);var Pt=Buffer.from("ALRAN-PLUGIN-CONTENT-DIGEST\0","ascii");function Ct(t){if(!t)f("INVALID_PATH","path is empty");if(!/^[\x00-\x7f]*$/u.test(t)){f("NON_PORTABLE_PATH",`${JSON.stringify(t)} is not ASCII`)}if(t.startsWith("/")||/^[A-Za-z]:/u.test(t)){f("ABSOLUTE_PATH",`${JSON.stringify(t)} is absolute`)}if(t.includes("\\")){f("BACKSLASH_PATH",`${JSON.stringify(t)} contains a backslash`)}if(t.endsWith("/")){f("INVALID_PATH",`${JSON.stringify(t)} has a trailing slash`)}if(/[\x00-\x1f\x7f]/u.test(t)){f("CONTROL_CHARACTER",`${JSON.stringify(t)} contains a control character`)}if(t.length>L.pathBytes){f("PATH_TOO_LONG",`${JSON.stringify(t)} exceeds the path limit`)}const e=t.split("/");if(e.length>L.pathSegments){f("PATH_TOO_DEEP",`${JSON.stringify(t)} has too many segments`)}for(const r of e){if(!r||r==="."||r===".."){f("PATH_TRAVERSAL",`${JSON.stringify(t)} has an empty or dot segment`)}if(r.length>L.segmentBytes){f("SEGMENT_TOO_LONG",`${JSON.stringify(r)} exceeds the segment limit`)}if(!Nt.test(r)||r.endsWith(".")){f("NON_PORTABLE_PATH",`${JSON.stringify(r)} is not portable`)}const[n=""]=r.split(".",1);if(Ot.has(n.toLowerCase())){f("WINDOWS_RESERVED_PATH",`${JSON.stringify(r)} is reserved on Windows`)}}}function vt(t){const e=[...t].sort((n,o)=>Buffer.compare(Buffer.from(n.path,"ascii"),Buffer.from(o.path,"ascii")));const r=He("sha256");r.update(Pt);r.update(Ae(1));r.update(Ae(e.length));for(const n of e){const o=Buffer.from(n.path,"ascii");r.update(Buffer.from([70]));r.update(Ae(o.length));r.update(o);r.update(jt(n.content.length));r.update(n.content)}return`sha256-tree-v1:${r.digest("hex")}`}function Ve(t){return He("sha256").update(t).digest("hex")}function je(t){if(t.length>L.archiveBytes){f("ARCHIVE_TOO_LARGE",`${t.length} bytes exceed the archive limit`)}if(t.length<22)f("INVALID_ZIP","end-of-central-directory record is missing");const e=Dt(t);const r=Ut(t,e);const n=[];const o=[];const i=new Set;const a=new Map;const s=new Set;let l=0;for(const d of r){const p=Mt(t,d,e.centralOffset);o.push({start:d.localOffset,end:p.end});const h=t.subarray(p.data,p.end);if(Wt(h)!==d.crc)f("CRC_MISMATCH",`${d.path} has an invalid CRC`);if(d.kind==="symlink")f("SYMLINK_NOT_ALLOWED",`${d.path} is a symlink`);if(d.kind==="special")f("SPECIAL_ENTRY_NOT_ALLOWED",`${d.path} is special`);Ct(d.path);if(i.has(d.path))f("DUPLICATE_PATH",`${d.path} appears twice`);i.add(d.path);Ht(d.path,a);if(d.kind==="directory")continue;s.add(d.path);if(h.length>L.fileBytes){f("FILE_TOO_LARGE",`${d.path} exceeds the per-file limit`)}l+=h.length;if(l>L.totalBytes){f("TOTAL_SIZE_LIMIT","unpacked size exceeds the total limit")}n.push({path:d.path,content:h})}if(n.length>L.files)f("TOO_MANY_FILES",`${n.length} files`);Ft(o);Vt(i,s);const c=[...n].sort((d,p)=>Buffer.compare(Buffer.from(d.path,"ascii"),Buffer.from(p.path,"ascii")));return{files:c,contentDigest:vt(c),totalBytes:l}}function Dt(t){const e=t.length-22;$e(t,e,_t,"end-of-central-directory");const r=E(t,e+4);const n=E(t,e+6);const o=E(t,e+8);const i=E(t,e+10);const a=R(t,e+12);const s=R(t,e+16);if(E(t,e+20)!==0)f("ARCHIVE_COMMENT_NOT_ALLOWED","comment not empty");if(r!==0||n!==0||o!==i){f("MULTI_DISK_NOT_ALLOWED","multi-disk ZIP is not supported")}if(i===65535||a===4294967295||s===4294967295){f("ZIP64_NOT_ALLOWED","ZIP64 sentinel values are not supported")}if(i>L.entries)f("TOO_MANY_ENTRIES",`${i} entries`);if(s+a!==e){f("INVALID_ZIP","central directory bounds do not match the archive")}return{endOffset:e,entryCount:i,centralOffset:s}}function Ut(t,e){const r=[];let n=e.centralOffset;for(let o=0;o<e.entryCount;o+=1){M(t,n,46,"central directory header");$e(t,n,xt,"central directory");const i=E(t,n+4);const a=E(t,n+8);const s=E(t,n+10);const l=R(t,n+16);const c=R(t,n+20);const d=R(t,n+24);const p=E(t,n+28);const h=E(t,n+30);const D=E(t,n+32);const I=E(t,n+34);const m=R(t,n+38);const A=R(t,n+42);ze(a);if(s!==0)f("UNSUPPORTED_COMPRESSION",`ZIP method ${s} is not STORE`);if(c===4294967295||d===4294967295){f("ZIP64_NOT_ALLOWED","ZIP64 entry values are not supported")}if(A===4294967295)f("ZIP64_NOT_ALLOWED","ZIP64 offset");if(h!==0)f("EXTRA_FIELD_NOT_ALLOWED","ZIP extra fields are not supported");if(D!==0)f("ENTRY_COMMENT_NOT_ALLOWED","entry comments are not supported");if(I!==0)f("MULTI_DISK_NOT_ALLOWED","entry on a non-zero disk");if(c!==d)f("SIZE_MISMATCH","STORE sizes differ");const $=n+46+p;M(t,n+46,p,"central entry name");if($>e.endOffset)f("INVALID_ZIP","central entry exceeds the directory");const w=t.subarray(n+46,$);if(w.length===0)f("INVALID_PATH","ZIP entry name is empty");if(w.some(lt=>lt>127))f("NON_PORTABLE_PATH","entry name is not ASCII");const b=w.toString("ascii");const k=b.endsWith("/");const N=k?b.slice(0,-1):b;const X=Bt(i,m,k);if(X==="directory"&&!k)f("INVALID_DIRECTORY_ENTRY",N);if(X!=="directory"&&k)f("INVALID_DIRECTORY_ENTRY",N);if(X==="directory"&&d!==0)f("INVALID_DIRECTORY_ENTRY",N);r.push({path:N,rawName:w,kind:X,flags:a,method:s,crc:l,compressedSize:c,uncompressedSize:d,localOffset:A});n=$}if(n!==e.endOffset)f("INVALID_ZIP","central directory entry count is inconsistent");return r}function Mt(t,e,r){const n=e.localOffset;M(t,n,30,"local file header");$e(t,n,kt,"local file");const o=E(t,n+6);const i=E(t,n+8);const a=R(t,n+14);const s=R(t,n+18);const l=R(t,n+22);const c=E(t,n+26);const d=E(t,n+28);ze(o);if(d!==0)f("EXTRA_FIELD_NOT_ALLOWED","local ZIP extra field is not empty");if(o!==e.flags||i!==e.method||a!==e.crc||s!==e.compressedSize||l!==e.uncompressedSize){f("LOCAL_HEADER_MISMATCH",`${e.path} local and central headers differ`)}M(t,n+30,c,"local entry name");if(!t.subarray(n+30,n+30+c).equals(e.rawName)){f("LOCAL_HEADER_MISMATCH",`${e.path} local and central names differ`)}const p=n+30+c;const h=p+s;if(h>r)f("INVALID_ZIP",`${e.path} data overlaps the directory`);return{data:p,end:h}}function Bt(t,e,r){if(t>>>8===3){const n=e>>>16&Rt;if(n===bt)return"symlink";if(n===Tt)return"directory";if(n===Lt||n===0)return r?"directory":"file";return"special"}return(e&16)!==0||r?"directory":"file"}function ze(t){if((t&1)!==0)f("ENCRYPTION_NOT_ALLOWED","encrypted ZIP entry");if((t&8)!==0)f("DATA_DESCRIPTOR_NOT_ALLOWED","data descriptor ZIP entry");if(t!==0)f("UNSUPPORTED_ZIP_FLAGS",`unsupported ZIP flags 0x${t.toString(16)}`)}function Ft(t){t.sort((e,r)=>e.start-r.start);for(let e=1;e<t.length;e+=1){const r=t[e];const n=t[e-1];if(r&&n&&r.start<n.end){f("OVERLAPPING_ENTRIES","local ZIP entries overlap")}}}function Ht(t,e){const r=t.split("/");for(let n=1;n<=r.length;n+=1){const o=r.slice(0,n).join("/");const i=o.toLowerCase();const a=e.get(i);if(a!==void 0&&a!==o){f("CASE_COLLISION",`${o} and ${a} differ only by case`)}e.set(i,o)}}function Vt(t,e){for(const r of t){const n=r.split("/");for(let o=1;o<n.length;o+=1){const i=n.slice(0,o).join("/");if(e.has(i)){f("PATH_TYPE_CONFLICT",`${i} is a file but ${r} lies beneath it`)}}}}function $e(t,e,r,n){M(t,e,4,`${n} signature`);if(R(t,e)!==r)f("INVALID_ZIP",`${n} signature is invalid`)}function M(t,e,r,n){if(e<0||r<0||e+r>t.length){f("INVALID_ZIP",`${n} exceeds archive bounds`)}}function E(t,e){M(t,e,2,"uint16");return t.readUInt16LE(e)}function R(t,e){M(t,e,4,"uint32");return t.readUInt32LE(e)}function Ae(t){const e=Buffer.alloc(4);e.writeUInt32BE(t);return e}function jt(t){const e=Buffer.alloc(8);e.writeBigUInt64BE(BigInt(t));return e}var zt=Array.from({length:256},(t,e)=>{let r=e;for(let n=0;n<8;n+=1){r=(r&1)===1?3988292384^r>>>1:r>>>1}return r>>>0});function Wt(t){let e=4294967295;for(const r of t)e=(zt[(e^r)&255]??0)^e>>>8;return(e^4294967295)>>>0}function f(t,e){throw new J(t,e)}import{rename as Gt}from"node:fs/promises";import Kt from"node:path";var We={schema:ee,plugins:{},skills:{}};var le=class{constructor(e){this.dataDir=e}dataDir;async read(){const e=this.file();const r=await P(e);if(r===void 0)return We;try{const n=JSON.parse(r);if(n.schema!==ee)throw new Error("unknown schema");return{schema:ee,plugins:Ke(n.plugins),skills:Ke(n.skills)}}catch{await Gt(e,`${e}.corrupt-${H()}`).catch(()=>void 0);return We}}async record(e,r,n){const o=await this.read();const i=Ge(o,e,r,n);await this.write(i);return i}async forget(e,r){const n=await this.read();const o=Ge(n,e,r,void 0);await this.write(o);return o}async write(e){await V(this.file(),`${JSON.stringify(e,null,2)}
3
3
  `)}file(){return Kt.join(x(this.dataDir),"installed.json")}};function Ge(t,e,r,n){const o=e==="plugin"?"plugins":"skills";const i={...t[o]};if(n)i[r]=n;else delete i[r];return{...t,[o]:i}}function Ke(t){const e={};if(typeof t!=="object"||t===null)return e;for(const[r,n]of Object.entries(t)){if(typeof n!=="object"||n===null)continue;const{source:o,version:i,contentDigest:a,installedAt:s}=n;if(typeof o==="string"&&typeof i==="string"&&typeof a==="string"&&typeof s==="string"){e[r]={source:o,version:i,contentDigest:a,installedAt:s}}}return e}var ce=class{constructor(e){this.options=e;this.ledgerFile=new le(e.dataDir);this.now=e.now??(()=>new Date)}options;ledgerFile;now;ledger(){return this.ledgerFile.read()}installDirectory(e,r){return B.join(this.options.dataDir,e==="plugin"?"plugins":"skills",r)}async stage(e,r,n={}){const o=await this.ledgerFile.read();const i=e.kind==="plugin"?o.plugins:o.skills;const a=i[e.name];const s=this.installDirectory(e.kind,e.name);if(a&&a.source!==r){throw new u("CONFLICT",`"${e.name}" is installed from the "${a.source}" store; remove it before installing it from "${r}".`)}if(!a&&await j(s)){throw new u("CONFLICT",`${s} already exists and was not installed by the Store. Move or remove it first; the Store never overwrites a ${e.kind} you put there.`)}const l=await this.options.transport.readBytes(e.archive.url,{maxBytes:e.archive.size,...n.signal?{signal:n.signal}:{}});if(l.length!==e.archive.size){throw new u("DIGEST_MISMATCH",`${e.name}: the archive is ${l.length} bytes, the index says ${e.archive.size}.`)}if(Ve(l)!==e.archive.archiveSha256){throw new u("DIGEST_MISMATCH",`${e.name}: the downloaded archive does not match the SHA-256 in the index. Nothing was installed.`)}let c;let d;try{({files:c,contentDigest:d}=je(l))}catch(h){if(h instanceof J){throw new u("ARCHIVE_INVALID",`${e.name}: ${h.message}`,{cause:h})}throw h}if(d!==e.archive.contentDigest){throw new u("DIGEST_MISMATCH",`${e.name}: the unpacked files do not match the content digest in the index. Nothing was installed.`)}const p=e.kind==="plugin"?Ue(c,{name:e.name,version:e.version}):Me(c,{name:e.name});return{entry:e,sourceId:r,inspection:p,...a?{replacesVersion:a.version}:{},target:s,files:c,contentDigest:d}}async commit(e,r){if(e.inspection.requiresConsent&&!r.consent){throw new u("CONSENT_REQUIRED",`${e.entry.name} runs commands or connects to services (${e.inspection.executes.length}); it was not installed because it was not approved.`)}return U(this.options.dataDir,async()=>{const n=await this.ledgerFile.read();const o=e.entry.kind==="plugin"?n.plugins:n.skills;const i=o[e.entry.name];const a=await j(e.target);if(a&&(!i||i.source!==e.sourceId)){throw new u("CONFLICT",`${e.target} appeared while installing; left alone.`)}const s=H();const l=B.join(x(this.options.dataDir),"staging",s);const c=B.join(x(this.options.dataDir),"trash",s);try{await Jt(l,e.files);if(a)ie(e.target,c);try{ie(l,e.target)}catch(p){if(a)ie(c,e.target);throw p}}catch(p){se(l);if(p instanceof u)throw p;throw new u("INSTALL_FAILED",`Could not install ${e.entry.name}: ${p instanceof Error?p.message:String(p)}`,{cause:p})}se(c);const d={source:e.sourceId,version:e.entry.version,contentDigest:e.contentDigest,installedAt:this.now().toISOString()};await this.ledgerFile.record(e.entry.kind,e.entry.name,d);return d})}async remove(e,r){return U(this.options.dataDir,async()=>{const n=await this.ledgerFile.read();const o=(e==="plugin"?n.plugins:n.skills)[r];if(!o){throw new u("NOT_FOUND",`"${r}" was not installed by the Store, so the Store will not delete it.`)}const i=this.installDirectory(e,r);const a=await j(i);if(a)se(i);await this.ledgerFile.forget(e,r);return a})}async forget(e,r){await U(this.options.dataDir,async()=>{await this.ledgerFile.forget(e,r)})}};async function Jt(t,e){await Ze(t,{recursive:true});const r=B.resolve(t);for(const n of e){const o=B.resolve(r,...n.path.split("/"));if(!o.startsWith(`${r}${B.sep}`)){throw new u("ARCHIVE_INVALID",`${n.path} would be written outside the package.`)}await Ze(B.dirname(o),{recursive:true});await Zt(o,n.content,{flag:"wx",mode:420})}}import en from"node:path";function de(t,e){let r;try{r=JSON.parse(t)}catch(l){throw g("",`is not JSON (${l instanceof Error?l.message:String(l)})`)}const n=Z(r,"");if(n.schema!==Q){throw g("schema",`must be "${Q}"`)}const o=K(n.plugins??[],"plugins").map((l,c)=>Yt(l,`plugins[${c}]`,e));const i=K(n.skills??[],"skills").map((l,c)=>qt(l,`skills[${c}]`,e));if(o.length+i.length>O.entries){throw g("",`holds more than ${O.entries} entries`)}Je(o.map(l=>l.name),"plugins");Je(i.map(l=>l.name),"skills");const a=v(n.description,"description",2e3);const s=v(n.updatedAt,"updatedAt",64);return{schema:Q,name:S(n.name,"name",80),...a?{description:a}:{},...s?{updatedAt:s}:{},plugins:o,skills:i}}function Yt(t,e,r){const n=Z(t,e);const o=S(n.name,`${e}.name`,80);if(!te.test(o))throw g(`${e}.name`,"is not a Plugin name");const i=S(n.category,`${e}.category`,64);if(!ye.includes(i)){throw g(`${e}.category`,`must be one of ${ye.join(", ")}`)}const a=v(n.license,`${e}.license`,128);const s=Qt(n.homepage,`${e}.homepage`);return{kind:"plugin",name:o,displayName:v(n.displayName,`${e}.displayName`,200)??o,version:Xe(n.version,`${e}.version`),description:S(n.description,`${e}.description`,2e3),author:S(n.author,`${e}.author`,200),category:i,...a?{license:a}:{},...s?{homepage:s}:{},exampleQueries:K(n.exampleQueries??[],`${e}.exampleQueries`).slice(0,3).map((l,c)=>S(l,`${e}.exampleQueries[${c}]`,500)),contents:Xt(n.contents,`${e}.contents`),archive:Ye(n.archive,`${e}.archive`,r)}}function Xt(t,e){const r=Z(t,e);return{skills:K(r.skills??[],`${e}.skills`).map((n,o)=>{const i=Z(n,`${e}.skills[${o}]`);const a=v(i.description,`${e}.skills[${o}].description`,4e3);return{name:S(i.name,`${e}.skills[${o}].name`,80),...a?{description:a}:{}}}),mcpServers:K(r.mcpServers??[],`${e}.mcpServers`).map((n,o)=>S(n,`${e}.mcpServers[${o}]`,80)),apps:K(r.apps??[],`${e}.apps`).map((n,o)=>S(n,`${e}.apps[${o}]`,80)),hooks:ke(r.hooks??0,`${e}.hooks`,0,64)}}function qt(t,e,r){const n=Z(t,e);const o=S(n.name,`${e}.name`,64);if(!ne.test(o))throw g(`${e}.name`,"is not a Skill name");const i=v(n.author,`${e}.author`,200);const a=v(n.license,`${e}.license`,128);return{kind:"skill",name:o,title:v(n.title,`${e}.title`,200)??o,version:Xe(n.version,`${e}.version`),description:S(n.description,`${e}.description`,4e3),group:S(n.group,`${e}.group`,80),...i?{author:i}:{},...a?{license:a}:{},files:ke(n.files,`${e}.files`,1,L.files),archive:Ye(n.archive,`${e}.archive`,r)}}function Ye(t,e,r){const n=Z(t,e);const o=S(n.url,`${e}.url`,2048);let i;try{i=new URL(o,r)}catch{throw g(`${e}.url`,"is not a URL")}const a=/^https?:$/u.test(new URL(r).protocol);if(i.protocol!=="https:"&&i.protocol!=="http:"&&i.protocol!=="file:"){throw g(`${e}.url`,"must be an https or file URL")}if(a&&i.protocol==="file:"){throw g(`${e}.url`,"must not be a file URL in an index that was fetched")}const s=i.toString();const l=S(n.archiveSha256,`${e}.archiveSha256`,64);if(!Oe.test(l)){throw g(`${e}.archiveSha256`,"must be 64 lowercase hex digits")}const c=S(n.contentDigest,`${e}.contentDigest`,80);if(!Pe.test(c)){throw g(`${e}.contentDigest`,"must be sha256-tree-v1:<64 lowercase hex digits>")}return{url:s,size:ke(n.size,`${e}.size`,22,L.archiveBytes),archiveSha256:l,contentDigest:c}}function Xe(t,e){const r=S(t,e,128);if(!re.test(r))throw g(e,"must be a SemVer version");return r}function Z(t,e){if(typeof t!=="object"||t===null||Array.isArray(t)){throw g(e,"must be an object")}return t}function K(t,e){if(!Array.isArray(t))throw g(e,"must be an array");return t}function S(t,e,r){if(typeof t!=="string")throw g(e,"must be a string");const n=T(t);if(!n)throw g(e,"must not be empty");if(n.length>r)throw g(e,`must be at most ${r} characters`);return n}function v(t,e,r){return t===void 0?void 0:S(t,e,r)}function Qt(t,e){if(t===void 0)return void 0;const r=S(t,e,2048);let n;try{n=new URL(r)}catch{throw g(e,"is not a URL")}if(n.protocol!=="https:")throw g(e,"must be an https URL");return n.toString()}function ke(t,e,r,n){if(typeof t!=="number"||!Number.isInteger(t)||t<r||t>n){throw g(e,`must be an integer from ${r} to ${n}`)}return t}function Je(t,e){const r=new Set;for(const n of t){if(r.has(n))throw g(e,`lists "${n}" twice`);r.add(n)}}function g(t,e){return new u("INDEX_INVALID",`Store index ${t?`field ${t} `:""}${e}.`)}var ue=class{constructor(e){this.options=e;this.now=e.now??Date.now;this.freshForMs=e.freshForMs??O.freshForMs}options;now;freshForMs;async load(e,r={}){const n=e.url.startsWith("file:");const o=n?void 0:await this.readCache(e);if(o&&!r.refresh&&this.now()-o.fetchedAtMs<this.freshForMs){const i=qe(o.text,e.url);if(i)return{source:e,index:i,stale:false,fetchedAtMs:o.fetchedAtMs}}try{const i=await this.options.transport.readText(e.url,{maxBytes:O.indexBytes,...o?.etag?{etag:o.etag}:{},...r.signal?{signal:r.signal}:{}});const a=this.now();if(i.status==="not-modified"&&o){const l=de(o.text,e.url);await this.writeCache(e,{...o,fetchedAtMs:a});return{source:e,index:l,stale:false,fetchedAtMs:a}}if(i.status!=="ok"){throw new u("SOURCE_UNREACHABLE",`${e.url} answered 304 with nothing cached.`)}const s=de(i.text,e.url);if(!n){await this.writeCache(e,{url:e.url,fetchedAtMs:a,...i.etag?{etag:i.etag}:{},text:i.text})}return{source:e,index:s,stale:false,fetchedAtMs:a}}catch(i){if(r.signal?.aborted)throw i;const a=i instanceof Error?i.message:String(i);const s=o?qe(o.text,e.url):void 0;if(o&&s){return{source:e,index:s,stale:true,fetchedAtMs:o.fetchedAtMs,error:a}}return{source:e,stale:false,error:a}}}cacheFile(e){return en.join(x(this.options.dataDir),"cache",`${e.id}.json`)}async readCache(e){const r=await P(this.cacheFile(e));if(r===void 0)return void 0;try{const n=JSON.parse(r);if(n.url===e.url&&typeof n.text==="string"&&typeof n.fetchedAtMs==="number"){return{url:n.url,fetchedAtMs:n.fetchedAtMs,text:n.text,...typeof n.etag==="string"?{etag:n.etag}:{}}}}catch{}return void 0}async writeCache(e,r){try{await V(this.cacheFile(e),JSON.stringify(r))}catch{}}};function qe(t,e){try{return de(t,e)}catch{return void 0}}import Le from"node:path";import{pathToFileURL as sn}from"node:url";import{open as tn,stat as nn}from"node:fs/promises";import{fileURLToPath as rn}from"node:url";function rt(t={}){const e=t.fetch??fetch;const r=t.timeoutMs??O.fetchTimeoutMs;return{async readText(n,o){if(Qe(n)){return{status:"ok",text:(await et(n,o.maxBytes)).toString("utf8")}}const i=await tt(e,n,r,o.signal,{...o.etag?{"if-none-match":o.etag}:{},accept:"application/json"});if(i.status===304)return{status:"not-modified"};const a=await nt(i,o.maxBytes,n);const s=i.headers.get("etag")??void 0;return{status:"ok",text:a.toString("utf8"),...s?{etag:s}:{}}},async readBytes(n,o){if(Qe(n))return et(n,o.maxBytes);const i=await tt(e,n,r,o.signal,{accept:"application/octet-stream"});return nt(i,o.maxBytes,n)}}}function fe(t){let e;try{e=new URL(t)}catch{throw new u("SOURCE_INVALID",`"${t}" is not a URL.`)}if(e.protocol==="https:"||e.protocol==="file:")return e;if(e.protocol==="http:"&&on(e.hostname))return e;throw new u("SOURCE_INVALID",`"${t}" must use https (plain http is only allowed for localhost).`)}function on(t){const e=t.replace(/^\[|\]$/gu,"").toLowerCase();return e==="localhost"||e==="::1"||/^127(?:\.\d{1,3}){3}$/u.test(e)}function Qe(t){return t.startsWith("file:")}async function et(t,e){let r;try{r=rn(t)}catch(n){throw new u("SOURCE_UNREACHABLE",`"${t}" is not a usable file URL.`,{cause:n})}try{const n=await nn(r);if(!n.isFile())throw new u("SOURCE_UNREACHABLE",`${r} is not a file.`);if(n.size>e)throw xe(t,e);const o=await tn(r,"r");try{return await o.readFile()}finally{await o.close()}}catch(n){if(n instanceof u)throw n;throw new u("SOURCE_UNREACHABLE",`Could not read ${r}: ${_e(n)}`,{cause:n})}}async function tt(t,e,r,n,o){fe(e);const i=AbortSignal.timeout(r);let a;try{a=await t(e,{headers:o,redirect:"follow",signal:n?AbortSignal.any([n,i]):i})}catch(s){if(n?.aborted)throw s;throw new u("SOURCE_UNREACHABLE",`${e} could not be reached (${i.aborted?"timed out":_e(s)}).`,{cause:s})}if(a.url&&a.url!==e){try{fe(a.url)}catch{throw new u("SOURCE_UNREACHABLE",`${e} redirected to a URL that is not allowed.`)}}if(a.status!==304&&!a.ok){throw new u("SOURCE_UNREACHABLE",`${e} answered ${a.status}${a.statusText?` ${a.statusText}`:""}.`)}return a}async function nt(t,e,r){const n=Number(t.headers.get("content-length"));if(Number.isFinite(n)&&n>e)throw xe(r,e);if(!t.body)return Buffer.alloc(0);const o=[];let i=0;const a=t.body.getReader();try{for(;;){const{done:s,value:l}=await a.read();if(s)break;i+=l.length;if(i>e){await a.cancel();throw xe(r,e)}o.push(Buffer.from(l))}}catch(s){if(s instanceof u)throw s;throw new u("SOURCE_UNREACHABLE",`${r} broke off (${_e(s)}).`,{cause:s})}return Buffer.concat(o,i)}function xe(t,e){return new u("SOURCE_UNREACHABLE",`${t} is larger than ${e} bytes.`)}function _e(t){if(t instanceof Error){const e=t.cause instanceof Error?` (${t.cause.message})`:"";return`${t.message}${e}`}return String(t)}var pe=class{constructor(e,r=process.env){this.dataDir=e;this.environment=r}dataDir;environment;async list(){const e=this.environment[he]?.trim();const r=e?.toLowerCase()===ge?void 0:e||Ne;const n=r?[{id:F,url:Re(r),label:"Alran store",builtin:true}]:[];return[...n,...await this.readAdded()]}async add(e){const r=Re(e.url);return U(this.dataDir,async()=>{const n=await this.readAdded();const o=[{id:F},...n];const i=n.find(c=>c.url===r);if(i){throw new u("SOURCE_EXISTS",`That store is already added as "${i.id}".`)}const a=e.id?.trim()||an(r,new Set(o.map(c=>c.id)));if(!Se.test(a)||a.length>40){throw new u("SOURCE_INVALID",`"${a}" is not a store name: use lowercase letters, digits and dashes, starting with a letter.`)}if(o.some(c=>c.id===a)){throw new u("SOURCE_EXISTS",`A store named "${a}" already exists.`)}const s=e.label?.trim();const l={id:a,url:r,...s?{label:s}:{}};await this.writeAdded([...n,l]);return l})}async remove(e){if(e===F){throw new u("SOURCE_INVALID",`"${F}" is the default store; set ${he}=${ge} to drop it.`)}return U(this.dataDir,async()=>{const r=await this.readAdded();const n=r.find(o=>o.id===e);if(!n)throw new u("SOURCE_NOT_FOUND",`No store named "${e}".`);await this.writeAdded(r.filter(o=>o.id!==e));return n})}file(){return Le.join(x(this.dataDir),"sources.json")}async readAdded(){const e=await P(this.file());if(e===void 0)return[];let r;try{r=JSON.parse(e)}catch(i){throw new u("SOURCE_INVALID",`${this.file()} is not valid JSON.`,{cause:i})}const n=typeof r==="object"&&r!==null&&"sources"in r?r.sources:void 0;if(!Array.isArray(n)){throw new u("SOURCE_INVALID",`${this.file()} has no "sources" list.`)}const o=[];for(const i of n){if(typeof i!=="object"||i===null)continue;const{id:a,url:s,label:l}=i;if(typeof a!=="string"||typeof s!=="string")continue;if(!Se.test(a)||a===F)continue;o.push({id:a,url:Re(s),...typeof l==="string"&&l.trim()?{label:l.trim()}:{}})}return o}async writeAdded(e){await V(this.file(),`${JSON.stringify({schema:be,sources:e},null,2)}
4
4
  `)}};function Re(t){const e=t.trim();if(!e)throw new u("SOURCE_INVALID","A store location is empty.");const r=/^[A-Za-z]:[\\/]/u.test(e);const n=e.startsWith("/")||r?sn(e):fe(e);if(!n.pathname.endsWith(".json")){n.pathname=`${n.pathname.replace(/\/+$/u,"")}/index.json`}n.hash="";return n.toString()}function an(t,e){const r=new URL(t);const n=r.protocol==="file:"?Le.basename(Le.dirname(decodeURIComponent(r.pathname))):`${r.hostname}${r.pathname.replace(/\/index\.json$/u,"")}`;let o=n.toLowerCase().replace(/[^a-z0-9]+/gu,"-").replace(/^-+|-+$/gu,"").slice(0,32);if(!/^[a-z]/u.test(o))o=`store-${o}`.replace(/-+$/u,"");if(!e.has(o))return o;for(let i=2;;i+=1){const a=`${o}-${i}`;if(!e.has(a))return a}}var Te="built-in";function me(t){return t.origin===Te}var ot=class{constructor(e){this.options=e;const r=e.transport??rt();this.environment=e.environment??process.env;this.sources=new pe(e.dataDir,this.environment);this.loader=new ue({dataDir:e.dataDir,transport:r,...e.now?{now:e.now}:{},...e.freshForMs!==void 0?{freshForMs:e.freshForMs}:{}});this.installer=new ce({dataDir:e.dataDir,transport:r});this.plugins=e.plugins;this.bundledSkills=e.bundledSkills??(async()=>{const n=Be(__alran_tuiPackageEntryUrl);return n?Fe(n):[]})}options;sources;loader;installer;plugins;environment;bundledSkills;bundledSkillsCache;async catalog(e={}){const r=e.offline?[]:await this.sources.list();const[n,o,i,a]=await Promise.all([Promise.all(r.map(d=>this.loader.load(d,e))),this.installer.ledger(),this.readInstalledPlugins(),this.readOfficialPlugins()]);const s=[];const l=new Map(i.filter(d=>d.marketplace==="local").map(d=>[d.name,d]));const c=new Set((await this.readBundledSkills()).map(d=>d.name));for(const d of n){if(!d.index)continue;for(const p of[...d.index.plugins,...d.index.skills]){s.push(await this.itemFor(p,d.source,o,l,c))}}s.push(...this.itemsWithoutEntry(s,o,i,a));s.push(...await this.orphanedSkills(s,o));s.push(...await this.builtInItems());return{items:s,sources:n}}resolve(e,r,n){const o=n.lastIndexOf("@");const i=o>0?n.slice(0,o):n;const a=o>0?n.slice(o+1):void 0;const s=e.items.filter(c=>c.kind===r&&c.name===i&&(!a||c.origin===a));if(s.length===0){throw new u("NOT_FOUND",`No ${r} named "${n}". Try: alran ${r==="plugin"?"plugin":"skills"} search`)}const l=s.filter(c=>c.installed);if(s.length>1&&l.length===1)return l[0];if(s.length>1){throw new u("AMBIGUOUS",`"${i}" exists in several places (${s.map(c=>`${i}@${c.origin}`).join(", ")}); name one of them.`)}return s[0]}stage(e,r={}){if(!e.entry){throw new u("NOT_FOUND",`${e.name} has no store entry to install from.`)}if(e.conflict==="built-in"){throw new u("CONFLICT",`A Skill named "${e.name}" is built in to Alran Code; installing this one would replace it, so the Store does not.`)}if(e.conflict){throw new u("CONFLICT",`A ${e.kind} named "${e.name}" is already installed outside the Store; the Store leaves it alone.`)}return this.installer.stage(e.entry,e.origin,r)}async commit(e,r){const n=await this.installer.commit(e,r);const o=[];if(e.entry.kind==="plugin")await this.reloadPlugins(o);return{record:n,warnings:o}}async remove(e){if(me(e)){throw new u("INSTALL_FAILED",`${e.name} is built in to Alran Code and cannot be removed.`)}const r=[];if(e.kind==="skill"){await this.installer.remove("skill",e.name);return r}if(e.origin==="official"||e.origin==="local"){await this.requirePlugins().mutatePlugin({action:"remove",plugin:{name:e.name,marketplace:e.origin}});return r}await this.plugins?.mutatePlugin({action:"remove",plugin:{name:e.name,marketplace:"local"}}).catch(()=>void 0);await this.installer.remove("plugin",e.name);await this.reloadPlugins(r);return r}async setEnabled(e,r){if(e.kind!=="plugin"){throw new u("INSTALL_FAILED","Only Plugins can be switched on and off.")}const n=e.origin==="official"?"official":"local";await this.requirePlugins().mutatePlugin({action:r?"enable":"disable",plugin:{name:e.name,marketplace:n}})}async installOfficial(e){await this.requirePlugins().mutatePlugin({action:"install",plugin:{name:e.name,marketplace:"official"}})}async refreshRuntime(){await this.plugins?.refreshPlugins()}requirePlugins(){if(!this.plugins)throw new u("INSTALL_FAILED","Plugin management is unavailable.");return this.plugins}async reloadPlugins(e){try{await this.plugins?.refreshPlugins()}catch(r){e.push(`The Plugin is in place but Alran could not reload Plugins (${r instanceof Error?r.message:String(r)}). Restart Alran or run /reload.`)}}async readInstalledPlugins(){if(!this.plugins)return[];return this.plugins.listInstalledPlugins().catch(()=>[])}async readOfficialPlugins(){if(!this.plugins||!this.environment.ALRAN_PLUGIN_REGISTRY_URL?.trim())return[];return this.plugins.listMarketplacePlugins({marketplace:"official"}).catch(()=>[])}async itemFor(e,r,n,o,i){const a=e.kind==="plugin"?n.plugins:n.skills;const s=a[e.name];const l=s?.source===r.id?s:void 0;const c=e.kind==="plugin"?o.get(e.name):void 0;const d=this.installer.installDirectory(e.kind,e.name);const p=c!==void 0||await j(d);const h=e.kind==="skill"&&i.has(e.name)?"built-in":p&&!s?"local":void 0;const D=l!==void 0&&p;const I={id:`${e.kind}:${e.name}@${r.id}`,kind:e.kind,name:e.name,origin:r.id,version:e.version,installed:D,enabled:D&&(e.kind==="skill"||(c?c.enabled:this.plugins===void 0)),updateAvailable:D&&l!==void 0&&(l.version!==e.version||l.contentDigest!==e.archive.contentDigest),...l?{installedVersion:l.version}:{},...h?{conflict:h}:{},entry:e,...c?{plugin:c}:{}};if(e.kind==="plugin"){return{...I,displayName:e.displayName,description:e.description,author:e.author,group:e.category,...e.license?{license:e.license}:{},summary:cn(e)}}return{...I,displayName:e.title,description:e.description,...e.author?{author:e.author}:{},group:e.group,...e.license?{license:e.license}:{},summary:`${e.files} ${e.files===1?"file":"files"}`}}itemsWithoutEntry(e,r,n,o){const i=new Set(e.filter(s=>s.kind==="plugin").map(s=>s.name));const a=[];for(const s of[...n,...o]){if(s.marketplace==="local"&&i.has(s.name))continue;const l=s.marketplace==="local"?r.plugins[s.name]:void 0;const c=l?l.source:s.marketplace;const d=`plugin:${s.name}@${c}`;if(a.some(p=>p.id===d))continue;a.push({id:d,kind:"plugin",name:s.name,displayName:s.displayName,description:s.description??"",...s.author?{author:s.author}:{},...s.version?{version:s.version,installedVersion:s.version}:{},origin:c,installed:s.installed,enabled:s.enabled,updateAvailable:false,summary:dn(s),plugin:s})}return a}readBundledSkills(){this.bundledSkillsCache??=this.bundledSkills().catch(()=>[]);return this.bundledSkillsCache}async builtInItems(){return(await this.readBundledSkills()).map(e=>({id:`skill:${e.name}@${Te}`,kind:"skill",name:e.name,displayName:e.name,description:e.description,group:"Built in",origin:Te,installed:true,enabled:true,updateAvailable:false,summary:""}))}async orphanedSkills(e,r){const n=new Set(e.filter(i=>i.kind==="skill").map(i=>i.name));const o=[];for(const[i,a]of Object.entries(r.skills)){if(n.has(i))continue;const s=this.installer.installDirectory("skill",i);const l=await P(ln.join(s,"SKILL.md"));if(l===void 0)continue;let c="";try{c=G(l,"SKILL.md").description}catch{}o.push({id:`skill:${i}@${a.source}`,kind:"skill",name:i,displayName:i,description:c,version:a.version,installedVersion:a.version,origin:a.source,installed:true,enabled:true,updateAvailable:false,summary:"installed"})}return o}};function cn(t){const e=[];const{skills:r,mcpServers:n,apps:o,hooks:i}=t.contents;if(r.length)e.push(`${r.length} ${r.length===1?"skill":"skills"}`);if(n.length)e.push(`${n.length} MCP`);if(o.length)e.push(`${o.length} ${o.length===1?"app":"apps"}`);if(i)e.push(`${i} ${i===1?"hook":"hooks"}`);return e.join(" \xB7 ")||"empty"}function dn(t){const{appCount:e,mcpServerCount:r,skillCount:n,agentCount:o}=t.capabilities;const i=[];if(n)i.push(`${n} ${n===1?"skill":"skills"}`);if(r)i.push(`${r} MCP`);if(e)i.push(`${e} ${e===1?"app":"apps"}`);if(o)i.push(`${o} subagents`);return i.join(" \xB7 ")||"empty"}function un(t){if(t.conflict)return"[!]";if(!t.installed)return"[ ]";return t.enabled?"[*]":"[-]"}function st(t){if(me(t))return"built in";if(t.conflict==="built-in")return"same name as a built-in skill";if(t.conflict)return"installed outside the Store";if(!t.installed)return"available";if(t.updateAvailable)return`update available (${t.installedVersion??"?"} \u2192 ${t.version??"?"})`;if(t.kind==="plugin"&&!t.enabled)return"installed, disabled";return"installed"}function at(t){return t.origin==="ottili"||me(t)?t.name:`${t.name}@${t.origin}`}function fn(t,e,r=""){const n=Math.max(20,e-r.length);const o=[];let i="";for(const a of t.split(/\s+/u).filter(Boolean)){if(i&&i.length+1+a.length>n){o.push(`${r}${i}`);i=a}else{i=i?`${i} ${a}`:a}}if(i)o.push(`${r}${i}`);return o}function it(t,e){if(e<=1)return t.slice(0,Math.max(0,e));return t.length<=e?t:`${t.slice(0,e-1)}\u2026`}function $r(t,e=100){if(t.length===0)return"";const r=t.map(at);const n=Math.min(34,Math.max(...r.map(i=>i.length)));const o=Math.max(...t.map(i=>(i.version??"").length),5);return t.map((i,a)=>{const s=`${un(i)} ${it(r[a]??"",n).padEnd(n)} ${(i.version??"").padEnd(o)} `;const l=i.installed||i.conflict?` ${st(i)}`:"";const c=Math.max(10,e-s.length-l.length);return`${s}${it(i.description,c)}${l}`}).join("\n")}function kr(t,e,r=100){const n=[`${t.displayName} (${at(t)})`,` ${st(t)}${t.version?` \xB7 version ${t.version}`:""}`,"",...fn(t.description,r," "),""];const o=[["Kind",t.kind==="plugin"?"Plugin":"Skill"],["From",t.origin],["Author",t.author],[t.kind==="plugin"?"Category":"Group",t.group],["License",t.license],["Contains",t.summary]];for(const[a,s]of o)if(s)n.push(` ${`${a}:`.padEnd(10)}${s}`);const i=t.entry;if(i?.kind==="plugin"){if(i.homepage)n.push(` ${"Homepage:".padEnd(10)}${i.homepage}`);if(i.contents.skills.length>0){n.push(""," Skills:");for(const a of i.contents.skills)n.push(` ${a.name}`)}if(i.exampleQueries.length>0){n.push(""," Try:");for(const a of i.exampleQueries)n.push(` \u201C${a}\u201D`)}}if(e&&e.executes.length>0){n.push("",...pn(e.executes.map(a=>a.line)).split("\n"))}return n.join("\n")}function pn(t){return[" This package will run commands or connect to services:",...t.map(e=>` \u2022 ${e}`)].join("\n")}var Y=(t,e,r)=>{const n=t.toLowerCase();if(n===e)return r*4;if(n.startsWith(e))return r*3;if(n.includes(e))return r*2;return 0};function xr(t,e){const r=e.toLowerCase().split(/\s+/u).filter(Boolean);if(r.length===0)return[...t];const n=[];t.forEach((o,i)=>{let a=0;for(const s of r){const l=Y(o.name,s,50)+Y(o.displayName,s,30)+Y(o.group??"",s,10)+Y(o.author??"",s,5)+Y(o.description,s,1);if(l===0)return;a+=l}n.push({item:o,points:a,index:i})});return n.sort((o,i)=>i.points-o.points||o.index-i.index).map(({item:o})=>o)}export{u as a,C as b,me as c,ot as d,un as e,at as f,$r as g,kr as h,pn as i,xr as j};
@@ -0,0 +1,2 @@
1
+ import { createRequire as __alran_cR } from "module"; import { basename as __alran_basename, dirname as __alran_dirname, join as __alran_join } from "path"; import { fileURLToPath as __alran_fileURLToPath, pathToFileURL as __alran_pathToFileURL } from "url"; const __alran_tuiCurrentModuleDir = __alran_dirname(__alran_fileURLToPath(import.meta.url)); const __alran_tuiPackageRoot = __alran_basename(__alran_tuiCurrentModuleDir) === "chunks" ? __alran_dirname(__alran_tuiCurrentModuleDir) : __alran_tuiCurrentModuleDir; const __alran_tuiPackageEntryUrl = __alran_pathToFileURL(__alran_join(__alran_tuiPackageRoot, "cli.js")).href; const require = __alran_cR(__alran_tuiPackageEntryUrl); const __dirname = __alran_tuiPackageRoot;
2
+ import{Eb as l}from"./chunk-XVGPB7TW.js";function c(e){return{schemaVersion:1,type:"exec.result",sessionId:e.sessionId,turnId:e.turnId,status:e.status==="awaiting-user-continuation"?"blocked":e.status,answer:e.answer??null,...e.model?{model:{...e.model}}:{},...e.error?{error:{...e.error}}:{},durationMs:e.durationMs}}function x(e){if(!e||typeof e!=="object"||Array.isArray(e))return false;const t=e;const n=t.model===void 0||typeof t.model==="object"&&t.model!==null&&typeof t.model.providerId==="string"&&typeof t.model.modelId==="string"&&(t.model.variant===void 0||typeof t.model.variant==="string");return t.schemaVersion===1&&t.type==="exec.result"&&typeof t.sessionId==="string"&&typeof t.turnId==="string"&&typeof t.durationMs==="number"&&n&&(t.status==="succeeded"||t.status==="failed"||t.status==="blocked"||t.status==="timeout"||t.status==="cancelled"||t.status==="limit_exceeded")}function v(e){return e.coordinator.execute(e.request,t=>{if(e.isActive())e.onSessionEvent(t)},e.onRunAccepted,e.onResult?t=>e.onResult?.(c(t)):void 0)}var m=class{turnId;samples=new Map;value;beginTurn(t){this.reset();this.turnId=t}apply(t,n){if(t!==this.turnId||n.type!=="message"||n.message.role!=="assistant"||!n.message.id||n.message.kind)return this.value;const s=n.message.usage?.outputTokens;const i=n.message.usage?.decodeDurationMs;if(!r(s)||!r(i))return this.value;if(g(s,i,n.message.usage?.requestDurationMs))return this.value;this.samples.set(n.message.id,{outputTokens:s,decodeDurationMs:i});let a=0;let o=0;for(const d of this.samples.values()){a+=d.outputTokens;o+=d.decodeDurationMs}const u=o>0?a/(o/1e3):void 0;this.value=r(u)&&u>0?u:void 0;return this.value}finalize(){return this.value}current(){return this.value}currentEstimated(){return this.value===void 0?void 0:false}reset(){this.turnId=void 0;this.samples.clear();this.value=void 0}};var p=1e3;var f=.1;var y=4e3;function g(e,t,n){if(t>0&&e/(t/1e3)>y)return true;if(!r(n)||t>=n*f)return false;return e>t/1e3*p}function r(e){return typeof e==="number"&&Number.isFinite(e)&&e>=0}var R="alran";function I(e,t){if(e===R){try{return l(t)}catch{}}return`${e}/${t}`}var M={help:{name:"help",description:"Show available commands"},new:{name:"new",description:"Start a fresh session in the current workspace"},model:{name:"model",description:"Choose a model"},status:{name:"status",description:"Show account and model status"},doctor:{name:"doctor",description:"Check the local config file"},context:{name:"context",description:"Show the Runtime-owned context snapshot"},skills:{name:"skills",description:"List built-in and user Skills"},mcp:{name:"mcp",description:"Inspect MCP capabilities and project configuration"},usage:{name:"usage",description:"Show session usage"},compact:{name:"compact",description:"Shorten the active conversation"},export:{name:"export",description:"Export the current Session as Markdown"}};export{M as a,x as b,v as c,m as d,I as e};
@@ -0,0 +1,27 @@
1
+ import { createRequire as __alran_cR } from "module"; import { basename as __alran_basename, dirname as __alran_dirname, join as __alran_join } from "path"; import { fileURLToPath as __alran_fileURLToPath, pathToFileURL as __alran_pathToFileURL } from "url"; const __alran_tuiCurrentModuleDir = __alran_dirname(__alran_fileURLToPath(import.meta.url)); const __alran_tuiPackageRoot = __alran_basename(__alran_tuiCurrentModuleDir) === "chunks" ? __alran_dirname(__alran_tuiCurrentModuleDir) : __alran_tuiCurrentModuleDir; const __alran_tuiPackageEntryUrl = __alran_pathToFileURL(__alran_join(__alran_tuiPackageRoot, "cli.js")).href; const require = __alran_cR(__alran_tuiPackageEntryUrl); const __dirname = __alran_tuiPackageRoot;
2
+ import{b as M}from"./chunk-6UXSIWCB.js";import{Ab as D,Bb as L,Ga as O,Tb as q,b,fb as $,lb as S,pb as R,qb as x,rb as g,sb as T,ub as _,vb as j,yb as E}from"./chunk-XVGPB7TW.js";import{randomUUID as V}from"node:crypto";var l=Object.freeze({ok:0,error:1,authRequired:2,rateLimited:3,unreachable:4,credits:5});var d=class extends Error{constructor(t,o,a){super(t);this.exitCode=o;this.code=a;this.name="AlranAccountError"}exitCode;code};function X(){return{dataDir:M(),platformEnv:S(),environment:process.env,fetchImpl:fetch,out:e=>process.stdout.write(e),err:e=>process.stderr.write(e),now:()=>new Date,login:async({openBrowser:e,apiKey:n,device:t})=>{const{runTuiLogin:o}=await import("./auth-command-36RMNQZW.js");return o({openBrowser:e,provider:n?"api-key":"platform",...t===void 0?{}:{device:t}})},clearLocalCredentials:async()=>{const{runTuiLogout:e}=await import("./auth-command-36RMNQZW.js");const n=[];await e({writeError:t=>n.push(t.trimEnd())});return n},setDefaultModel:async e=>{await q({modelKey:e})},readDefaultModel:()=>{try{return O().defaultModel}catch{return void 0}}}}function v(e){const n=g(e.dataDir,e.platformEnv);if(!n){throw new d("Not signed in. Run `alran auth login` first.",l.authRequired,"not_signed_in")}return n}function B(e,n){const t=n.environment.OTTILI_PLATFORM_URL?.trim();return(e.baseUrl||t||"https://platform.ottili.one").replace(/\/+$/u,"")}function C(e,n){return $(n.platformEnv,e.environment).replace(/\/+$/u,"")}async function Y(e){try{const n=await e.json();return n&&typeof n==="object"?n:{}}catch{return{}}}var Q=new Set(["byok_key_required","byok_key_invalid","byok_key_rejected","byok_key_forbidden","byok_unavailable"]);function W(e,n,t,o){const a=n.error&&typeof n.error==="object"?n.error:n;const i=String(a.code??a.detail??"");const r=typeof a.message==="string"?a.message:typeof a.title==="string"?a.title:"";if(e===401){return new d("Your session has ended. Run `alran auth login` to sign in again.",l.authRequired,i||"unauthenticated")}if(e===429){const s=o?` Try again in ${o} s.`:"";return new d(`${t} is rate limiting this account.${s}`,l.rateLimited,i||"rate_limited")}if(Q.has(i)){return new d(r||"Claude runs on your own Anthropic API key. Add or replace it in the Ottili AI Platform under Settings \u2192 Provider keys.",l.credits,i)}if(i==="byok_provider_billing"){return new d(r||"Your Anthropic account cannot pay for this request. Anthropic bills it, not Ottili \u2014 check your balance in the Anthropic Console.",l.credits,i)}if(e===402||i==="insufficient_quota"){return new d(r||"Your credit does not cover this request. Add credits in the Ottili AI Platform.",l.credits,i)}if(e>=500){return new d(`${t} is not reachable right now (HTTP ${e}). Try again in a moment.`,l.unreachable,i||"unavailable")}return new d(`${t} refused the request (HTTP ${e}${i?`, ${i}`:""})${r?`: ${r}`:"."}`,l.error,i)}async function J(e,n,t,o){try{return await e.fetchImpl(n,{...t,signal:AbortSignal.timeout(15e3)})}catch{throw new d(`${o} is not reachable (${n.host}). Check your network connection and try again.`,l.unreachable,"network_error")}}async function y(e,n,t,o={}){const a=new URL(t,`${B(n,e)}/`);for(const[c,u]of Object.entries(o.query??{}))a.searchParams.set(c,u);const i={accept:"application/json","x-ottili-session":n.sessionId,...n.companyId?{"x-ottili-company":n.companyId}:{},...o.body!==void 0?{"content-type":"application/json"}:{},...o.idempotent?{"idempotency-key":`alran-cli-${V()}`}:{}};const r=await J(e,a,{method:o.method??"GET",headers:i,...o.body!==void 0?{body:JSON.stringify(o.body)}:{}},"The Ottili Platform");const s=await Y(r);if(!r.ok)throw W(r.status,s,"The Ottili Platform",r.headers.get("retry-after"));return s.data??s}async function K(e,n,t){const o=new URL(`${C(e,n)}${t}`);const a=n.companyId?_(e.dataDir).projects[n.companyId]:void 0;const i=await J(e,o,{method:"GET",headers:{accept:"application/json",authorization:`Bearer ${n.sessionId}`,...n.companyId?{"x-ottili-company":n.companyId}:{},...a?{"x-ottili-project":a}:{}}},"The Ottili AI Gateway");const r=await Y(i);if(!i.ok)throw W(i.status,r,"The Ottili AI Gateway",i.headers.get("retry-after"));return r}function m(e){const n=Number(e)/1e6;if(!Number.isFinite(n))return"\u2014";const t=Math.abs(n);const o=t>0&&t<.01?4:2;return`${n<0?"-":""}$${t.toFixed(o)}`}function Z(e){const n=e&&typeof e==="object"?e:{};const t=Number(n.amount_minor);if(!Number.isFinite(t))return"\u2014";return`${(t/100).toFixed(2)} ${String(n.currency??"USD").toUpperCase()}`}function k(e,n){const t=e.map((a,i)=>Math.max(a.length,...n.map(r=>(r[i]??"").length)));const o=a=>a.map((i,r)=>(i??"").padEnd(t[r])).join(" ").trimEnd();return[o(e),o(t.map(a=>"\u2500".repeat(a))),...n.map(o)].join("\n")}var f=e=>`${JSON.stringify(e,null,2)}
3
+ `;async function G(e,n){const[t,o]=await Promise.all([y(e,n,"/v2/profile"),y(e,n,`/v2/auth/sessions/${encodeURIComponent(n.sessionId)}`).catch(a=>{if(a instanceof d&&a.exitCode===l.authRequired)throw a;return{}})]);return{name:t.profile?.display_name||t.profile?.subject_id||n.subjectId||"unknown",subjectId:t.profile?.subject_id||n.subjectId,expiresAt:typeof o.expires_at==="string"?o.expires_at:null}}async function ee(e,n={}){const t=g(e.dataDir,e.platformEnv);if(!t){if(n.json)e.out(f({signed_in:false}));else e.out("Not signed in. Run `alran auth login` to connect Alran Code to your Ottili account.\n");throw new d("",l.authRequired,"not_signed_in")}const o=await G(e,t);const a=_(e.dataDir).projects[t.companyId]??null;const i={signed_in:true,name:o.name,subject_id:o.subjectId,company_id:t.companyId,project_id:a,environment:t.platformEnv==="prod"?"production":"development",platform:B(t,e),gateway:C(e,t),session_expires_at:o.expiresAt,default_model:e.readDefaultModel()??"alran/Alran-Werk"};if(n.json){e.out(f(i));return}e.out([`Signed in as ${i.name}`,` Company ${i.company_id}`,` Project ${i.project_id??"default project of the company"}`,` Model ${i.default_model}`,` Platform ${i.platform} (${i.environment})`,` Gateway ${i.gateway}`,...i.session_expires_at?[` Session valid until ${i.session_expires_at}`]:[],""].join("\n"))}async function ne(e,n={}){const t=g(e.dataDir,e.platformEnv);if(t&&!n.force&&!n.apiKey){try{const o=await G(e,t);e.out(`Already logged in as ${o.name} (company ${t.companyId}). Use \`alran auth login --force\` to sign in again.
4
+ `);return}catch(o){if(!(o instanceof d)||o.exitCode!==l.authRequired)throw o}}e.out(`${await e.login({openBrowser:n.browser!==false,apiKey:n.apiKey===true,...n.device===void 0?{}:{device:n.device}})}
5
+ `)}async function te(e){const n=[];for(const t of x(e.platformEnv)){const o=g(e.dataDir,t);if(!o||o.platformEnv!==t)continue;try{await y(e,o,`/v2/auth/sessions/${encodeURIComponent(o.sessionId)}`,{method:"DELETE",idempotent:true})}catch(a){if(!(a instanceof d)||a.exitCode!==l.authRequired){n.push(`Could not revoke the ${t} session at the Platform (${a instanceof Error?a.message:String(a)}); it was removed from this machine and expires on its own.`)}}R(e.dataDir,t)}n.push(...await e.clearLocalCredentials()??[]);for(const t of n)e.err(`${t}
6
+ `);e.out("Logged out.\n")}async function N(e,n,t={}){const o=v(e);const a=await y(e,o,"/v2/companies");const i=a.companies??[];if(!n){if(t.json){e.out(f({current:o.companyId,companies:i}));return}if(i.length===0){e.out("Your account is not a member of a company yet. Create or join one in the Ottili Console.\n");return}e.out(`${k(["","Company","Slug","Roles"],i.map(c=>[c.company_id===o.companyId?"*":"",c.company_id,c.slug??"",(c.roles??[]).join(", ")]))}
7
+
8
+ Switch with \`alran auth switch-company <company id or slug>\`.
9
+ `);return}const r=i.find(c=>c.company_id===n||c.slug===n);if(!r){throw new d(`You are not a member of a company "${n}". Run \`alran auth switch-company\` to list yours.`,l.error,"company_not_found")}if(r.company_id===o.companyId){e.out(`Already working in ${r.slug??r.company_id}.
10
+ `);return}const s=await y(e,o,"/v2/auth/company",{method:"POST",body:{company_id:r.company_id},idempotent:true});T(e.dataDir,o.platformEnv,{sessionId:s.session?.session_id||o.sessionId,companyId:s.session?.company_id||r.company_id,subjectId:o.subjectId,baseUrl:o.baseUrl},{via:"oidc"});e.out(`Switched to ${r.slug??r.company_id}. Model calls, usage and billing now use this company.
11
+ `)}async function oe(e,n,t={}){const o=v(e);const a=_(e.dataDir).projects[o.companyId]??null;if(t.clear){j(e.dataDir,o.companyId,null);e.out("Project cleared: requests use the default project of the company.\n");return}let i;try{i=await y(e,o,"/v2/projects",{query:{status:"active",member:"me",limit:"200"}})}catch(c){if(c instanceof d&&/HTTP 404/u.test(c.message)){throw new d("This Ottili Platform does not offer projects yet; requests use the default project of the company.",l.error,"projects_unavailable")}throw c}const r=i.items??[];if(!n){if(t.json){e.out(f({current:a,projects:r}));return}if(r.length===0){e.out("No projects you can use in this company. Requests use the default project.\n");return}e.out(`${k(["","Project","Name","Your role"],r.map(c=>[c.project_id===a?"*":"",c.project_id,c.name??"",c.access?.role??""]))}
12
+
13
+ ${a?"":"No project chosen: requests use the default project.\n"}Choose one with \`alran config project <project id or name>\`.
14
+ `);return}const s=r.find(c=>c.project_id===n||c.name===n);if(!s){throw new d(`No active project "${n}" that you are a member of. Run \`alran config project\` to list them.`,l.error,"project_not_found")}j(e.dataDir,o.companyId,s.project_id);e.out(`Project set to ${s.name??s.project_id}. Model calls are attributed to it from now on.
15
+ `)}function F(e){const n=D(e.replace(/^(alran|external)\//u,""));if(!Object.hasOwn(b,n))return void 0;return`alran/${n}`}async function H(e,n){if(!n)return null;try{return await K(e,n,"/credits")}catch{return null}}async function z(e,n){if(!n){e.out(`${e.readDefaultModel()??"alran/Alran-Werk"}
16
+ `);return}const t=F(n);if(!t){throw new d(`Unknown model "${n}". Run \`alran models\` to list the models.`,l.error,"model_not_found")}await e.setDefaultModel(t);e.out(`Default model set to ${b[t.slice(t.indexOf("/")+1)]?.name??t} (${t}).
17
+ `);if(L(t.slice(t.indexOf("/")+1))){const o=await H(e,g(e.dataDir,e.platformEnv));const a=o?.models?.find(i=>i.id===E[t.slice(t.indexOf("/")+1)]);if(a&&a.usable===false){e.err(`Note: ${U[a.reason??""]??U.requires_byok_key}
18
+ `)}}}var U=Object.freeze({requires_byok_key:"Claude runs on your own Anthropic API key, which you have not added yet. Add it in the Ottili AI Platform under Settings \u2192 Provider keys; Anthropic bills it directly and Ottili charges nothing for Claude.",byok_key_invalid:"Anthropic does not accept your stored API key. Replace it in the Ottili AI Platform under Settings \u2192 Provider keys.",byok_unavailable:"This Ottili deployment cannot store provider keys, so Claude is not available here.",requires_paid_credit:"this model uses purchased credits only. Your current credit is welcome credit, which covers Werk. Add credits in the Ottili AI Platform to use it."});var P=Object.freeze([{key:"alran/Alran-Werk",id:"ottili/werk-1.1",short:"werk",name:"Ottili Werk 1.1",input:5e5,output:15e5,billing:"platform",credit:"welcome or purchased credit",description:"Ottili\u2019s own model for coding and agentic work. Default."},{key:"alran/anthropic/claude-sonnet-5.5",id:"anthropic/claude-sonnet-5.5",short:"sonnet",name:"Claude Sonnet 5.5",input:2e6,output:1e7,billing:"byok",credit:"your Anthropic key",description:"Anthropic\u2019s everyday model for coding and agents."},{key:"alran/anthropic/claude-opus-5.5",id:"anthropic/claude-opus-5.5",short:"opus",name:"Claude Opus 5.5",input:4e6,output:2e7,billing:"byok",credit:"your Anthropic key",description:"Anthropic\u2019s most capable Opus model for hard, long tasks."}]);function I(e,n){if(!n)return"sign in to check";const t=n.models?.find(o=>o.id===e.id);if(!t)return"not offered right now";if(t.usable)return"available";switch(t.reason){case"requires_byok_key":return"needs your Anthropic key";case"byok_key_invalid":return"Anthropic rejected your key";case"byok_unavailable":return"keys not available here";case"requires_paid_credit":return"requires purchased credit";default:return"no credit left"}}function re(e,n,t=Boolean(process.stdout.isTTY)){const o=e.environment.FORCE_COLOR!==void 0&&e.environment.FORCE_COLOR!=="0";if(e.environment.NO_COLOR!==void 0||!t&&!o)return n;const a=n==="available"?32:n==="needs your Anthropic key"||n==="requires purchased credit"?33:n==="no credit left"||n==="Anthropic rejected your key"?31:null;return a===null?n:`\x1B[${a}m${n}\x1B[39m`}async function ie(e,n={}){if(n.setDefault){await z(e,n.setDefault);return}if(n.thirdParty){e.out(["Third-party providers (bring your own key)","","Alran Code can call another provider directly with your own API key. Ottili does not see,","meter or bill those requests; the provider bills you. Configure one with:",""," alran provider add --name <name> --base-url <url> --api-format openai-completions \\"," --model <model id> --api-key-env <ENV_VAR_WITH_YOUR_KEY> --use","","Supported formats: openai-completions, openai-responses, anthropic-messages. `alran provider`","opens the provider picker with the bundled catalog of known providers; `alran provider list`","shows what you configured. See docs/MODELS.md.",""].join("\n"));return}const t=g(e.dataDir,e.platformEnv);const o=await H(e,t);const a=e.readDefaultModel()??"alran/Alran-Werk";if(n.info){const i=F(n.info);const r=P.find(u=>u.key===i);if(!r)throw new d(`Unknown model "${n.info}". Run \`alran models\` to list the models.`,l.error,"model_not_found");const s=b[r.key.slice(r.key.indexOf("/")+1)];const c={id:r.id,name:r.name,short_name:r.short,description:r.description,context_tokens:s?.limit?.context??null,max_output_tokens:s?.limit?.output??null,price_per_million_tokens:{input:m(r.input),output:m(r.output)},billed_by:r.billing==="byok"?"Anthropic, to your own account (Ottili charges nothing for this model)":"Ottili, from your credit",paid_with:r.credit,status:I(r,o)};if(n.json)e.out(f(c));else e.out(`${Object.entries(c).filter(([,u])=>u!==null).map(([u,p])=>`${u.padEnd(18)} ${typeof p==="object"?JSON.stringify(p):String(p)}`).join("\n")}
19
+ `);return}if(n.json){e.out(f(P.map(i=>({...i,status:I(i,o),default:i.key===a}))));return}e.out(`${k(["","Model","Name","Input / output per 1M tokens","Paid with","Status"],P.map(i=>[i.key===a?"*":"",i.short,i.name,`${m(i.input)} / ${m(i.output)}`,i.credit,re(e,I(i,o))]))}
20
+
21
+ Claude models run on your own Anthropic API key: add it in the Ottili AI Platform under Settings \u2192
22
+ Provider keys. Anthropic bills you directly at the prices above; Ottili charges nothing for Claude and
23
+ adds no fee. Change the default with \`alran models --set-default <model>\`; details with
24
+ \`alran models --info <model>\`; your own providers with \`alran models --third-party\`.
25
+ `)}async function ae(e,n={}){const t=v(e);const o=await K(e,t,"/credits");if(n.json){e.out(f(o));return}const a=o.current_month;const i=(a?.by_model??[]).map(s=>[s.model,String(s.requests),String((s.input_tokens??0)+(s.output_tokens??0)),s.billing==="byok"?"billed by Anthropic":m(s.cost_microcents)]);const r=o.byok?.anthropic;e.out([`Credits (${String(o.currency??"USD").toUpperCase()})`,` Available ${m(o.available_microcents??0)}`,` Reserved ${m(o.reserved_microcents??0)}`,` Welcome credit ${m(o.free_credit?.remaining_microcents??0)} left of ${m(o.free_credit?.granted_microcents??0)} (Werk only)`,` Purchased credit ${m(o.paid_credit?.available_microcents??0)} (Werk)`,` Anthropic key ${r?.configured?`${r.hint??"stored"} (${r.status??"active"}) \u2014 Claude is billed by Anthropic, not by Ottili`:"not added \u2014 Claude needs your own key (Ottili AI Platform \u2192 Settings \u2192 Provider keys)"}`,"",`This month (since ${a?.from?.slice(0,10)??"\u2014"})`,i.length>0?k(["Model","Requests","Tokens","Charged by Ottili"],i):" No requests yet.","",`Charged by Ottili this month: ${m(a?.total_cost_microcents??0)}`,""].join("\n"))}async function se(e,n={}){const t=v(e);const o=async h=>{try{return await h}catch(A){if(A instanceof d&&A.exitCode===l.authRequired)throw A;return null}};const[a,i,r,s]=await Promise.all([o(y(e,t,"/v2/billing/subscription")),o(y(e,t,"/v2/billing/payment-methods")),o(y(e,t,"/v2/billing/invoices",{query:{limit:"1"}})),o(y(e,t,"/v2/billing/welcome-credit"))]);const c={subscription:a?.subscription??null,paymentMethods:i?.payment_methods??[],invoices:r?.invoices??[],welcome:s?.welcome_credit??null};const u=`${C(e,t).replace(/\/v1$/u,"")}/billing`;if(n.json){e.out(f({plan:c.subscription?String(c.subscription.plan_id??"pay-per-use"):"pay-per-use",payment_methods:c.paymentMethods.map(h=>({label:h.display_label??null,default:h.is_default===true,state:h.state??null})),last_invoice:c.invoices[0]??null,welcome_credit:c.welcome?{state:c.welcome.state??null}:null,manage_at:u}));return}const p=c.paymentMethods.find(h=>h.is_default===true)??c.paymentMethods[0];const w=c.invoices[0];e.out([`Plan ${c.subscription?String(c.subscription.plan_id??"Pay-per-use"):"Pay-per-use (prepaid credits)"}`,`Payment method ${p?String(p.display_label??"on file"):"none on file"}`,`Last invoice ${w?`${Z(w.amount)} \xB7 ${String(w.state??"")} \xB7 ${String(w.issued_at??"").slice(0,10)}`:"none yet"}`,`Next billing ${c.subscription&&c.subscription.state==="active"?"with your subscription period":"none: credits are prepaid, nothing is billed automatically"}`,`Welcome credit ${c.welcome?String(c.welcome.state??"unknown").replaceAll("_"," "):"not available"}`,"",`Add credits, change the payment method or download invoices: ${u}`,""].join("\n"))}async function ce(e,n){try{await n()}catch(t){if(t instanceof d){if(t.message)e.err(`${t.message}
26
+ `);process.exitCode=t.exitCode;return}throw t}}function me(e,n=X,t){const o=r=>async()=>{const s=n();const c=t?import("./update-hint-ED7O67WU.js").then(({resolveUpdateHint:p})=>p({currentVersion:t,dataDir:s.dataDir,environment:s.environment,fetchImpl:s.fetchImpl})).catch(()=>null):Promise.resolve(null);await ce(s,()=>r(s));const u=await Promise.race([c,new Promise(p=>setTimeout(()=>p(null),1500).unref())]);if(u)s.err(`${u}
27
+ `)};const a=e.command("auth").description("Sign in to your Ottili account, check it, switch company, sign out");a.command("login").description("Sign in with your Ottili account (in the browser, or with a code confirmed on any device)").option("--force","sign in again even when a session exists").option("--device","sign in with a code you confirm in a browser anywhere (the default over SSH or without a display)").option("--no-device","sign in through a browser on this machine even when none seems to be there").option("--no-browser","print the sign-in page URL without opening a browser").option("--api-key","paste an Ottili API key instead (for machines without a browser)").action(r=>o(s=>ne(s,r))());a.command("logout").description("Revoke the session at the Ottili Platform and remove local credentials").action(()=>o(te)());a.command("status").description("Who you are signed in as, and which company, project and model you use").option("--json","print a JSON document").action(r=>o(s=>ee(s,r))());a.command("switch-company").description("List your companies, or switch to one").argument("[company]","company id or slug").option("--json","print a JSON document").action((r,s)=>o(c=>N(c,r,s))());const i=e.command("config").description("Show or set the company, project and model Alran Code works with");i.command("company").description("Show your companies, or switch to one").argument("[company]","company id or slug").option("--json","print a JSON document").action((r,s)=>o(c=>N(c,r,s))());i.command("project").description("Show your projects, or choose the one model calls are attributed to").argument("[project]","project id or name").option("--clear","go back to the default project of the company").option("--json","print a JSON document").action((r,s)=>o(c=>oe(c,r,s))());i.command("model").description("Show or set the default model (werk, sonnet, opus or a full id)").argument("[model]","model").action(r=>o(s=>z(s,r))());e.command("models").description("List the Ottili models, their prices and whether your credit covers them").option("--third-party","how to use another provider with your own API key").option("--info <model>","details of one model").option("--set-default <model>","make a model the default").option("--list","list the models (the default)").option("--json","print a JSON document").action(r=>o(s=>ie(s,r))());e.command("usage").description("Credits left and this month's spend per model").option("--json","print a JSON document").action(r=>o(s=>ae(s,r))());e.command("billing").description("Plan, payment method, last invoice, and where to manage billing").option("--json","print a JSON document").action(r=>o(s=>se(s,r))())}export{l as a,d as b,X as c,y as d,K as e,m as f,k as g,ee as h,ne as i,te as j,N as k,oe as l,F as m,z as n,P as o,re as p,ie as q,ae as r,se as s,ce as t,me as u};
@@ -0,0 +1,2 @@
1
+ import { createRequire as __alran_cR } from "module"; import { basename as __alran_basename, dirname as __alran_dirname, join as __alran_join } from "path"; import { fileURLToPath as __alran_fileURLToPath, pathToFileURL as __alran_pathToFileURL } from "url"; const __alran_tuiCurrentModuleDir = __alran_dirname(__alran_fileURLToPath(import.meta.url)); const __alran_tuiPackageRoot = __alran_basename(__alran_tuiCurrentModuleDir) === "chunks" ? __alran_dirname(__alran_tuiCurrentModuleDir) : __alran_tuiCurrentModuleDir; const __alran_tuiPackageEntryUrl = __alran_pathToFileURL(__alran_join(__alran_tuiPackageRoot, "cli.js")).href; const require = __alran_cR(__alran_tuiPackageEntryUrl); const __dirname = __alran_tuiPackageRoot;
2
+ import{readFileSync as G}from"node:fs";var ie="22.19+, 24, 25, or 26";var y="alran";var D=["@ottili/alran-code","@ottili/code"];function Y(t=__alran_tuiPackageEntryUrl){for(const e of["./package.json","../package.json"]){try{const r=JSON.parse(G(new URL(e,t),"utf8"));if((r.name===y||D.includes(r.name??""))&&typeof r.version==="string"&&r.version.length>0){return r.version}}catch(r){if(r.code!=="ENOENT")throw r}}throw new Error(`Cannot resolve ${y} package version`)}function V(t){const e=t.split(".");if(e.length===0||e.some(r=>!/^\d+$/.test(r)))return void 0;return e.map(r=>Number.parseInt(r,10))}function le(t=process.versions.node){const e=V(t);if(!e)return false;const[r=-1,o=0]=e;return r===22&&o>=19||r>=24&&r<=26}var ae=Y();var m="__ALRAN_TUI_LOGIN_RESTART";function ce(t){return{...t,[m]:"1"}}function fe(t){if(t[m]!=="1")return false;delete t[m];return true}var $=/^[a-z0-9][a-z0-9._/-]*$/u;var T=class{entries=new Map;frozen=false;register(e){if(this.frozen)throw new Error("Contribution registry is already frozen.");U(e.id);if(this.entries.has(e.id)){throw new Error(`Duplicate contribution id: ${e.id}`)}this.entries.set(e.id,e)}registerAll(e){for(const r of e)this.register(r)}get(e){return this.entries.get(e)}list(){return[...this.entries.values()].sort((e,r)=>(e.order??0)-(r.order??0)||e.id.localeCompare(r.id))}freeze(){this.frozen=true;return this.list()}};function U(t){if(!t)throw new Error("Contribution id must be non-empty.");if(!$.test(t)){throw new Error("Contribution id must use lowercase letters, numbers, dot, slash, underscore, or hyphen.")}}var O=10;var v=(t=0)=>e=>`\x1B[${e+t}m`;var x=(t=0)=>e=>`\x1B[${38+t};5;${e}m`;var I=(t=0)=>(e,r,o)=>`\x1B[${38+t};2;${e};${r};${o}m`;var s={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};var ge=Object.keys(s.modifier);var z=Object.keys(s.color);var J=Object.keys(s.bgColor);var me=[...z,...J];function K(){const t=new Map;for(const[e,r]of Object.entries(s)){for(const[o,n]of Object.entries(r)){s[o]={open:`\x1B[${n[0]}m`,close:`\x1B[${n[1]}m`};r[o]=s[o];t.set(n[0],n[1])}Object.defineProperty(s,e,{value:r,enumerable:false})}Object.defineProperty(s,"codes",{value:t,enumerable:false});s.color.close="\x1B[39m";s.bgColor.close="\x1B[49m";s.color.ansi=v();s.color.ansi256=x();s.color.ansi16m=I();s.bgColor.ansi=v(O);s.bgColor.ansi256=x(O);s.bgColor.ansi16m=I(O);Object.defineProperties(s,{rgbToAnsi256:{value(e,r,o){if(e===r&&r===o){if(e<8){return 16}if(e>248){return 231}return Math.round((e-8)/247*24)+232}return 16+36*Math.round(e/255*5)+6*Math.round(r/255*5)+Math.round(o/255*5)},enumerable:false},hexToRgb:{value(e){const r=/[a-f\d]{6}|[a-f\d]{3}/i.exec(e.toString(16));if(!r){return[0,0,0]}let[o]=r;if(o.length===3){o=[...o].map(l=>l+l).join("")}const n=Number.parseInt(o,16);return[n>>16&255,n>>8&255,n&255]},enumerable:false},hexToAnsi256:{value:e=>s.rgbToAnsi256(...s.hexToRgb(e)),enumerable:false},ansi256ToAnsi:{value(e){if(e<8){return 30+e}if(e<16){return 90+(e-8)}let r;let o;let n;if(e>=232){r=((e-232)*10+8)/255;o=r;n=r}else{e-=16;const A=e%36;r=Math.floor(e/36)/5;o=Math.floor(A/6)/5;n=A%6/5}const l=Math.max(r,o,n)*2;if(l===0){return 30}let a=30+(Math.round(n)<<2|Math.round(o)<<1|Math.round(r));if(l===2){a+=60}return a},enumerable:false},rgbToAnsi:{value:(e,r,o)=>s.ansi256ToAnsi(s.rgbToAnsi256(e,r,o)),enumerable:false},hexToAnsi:{value:e=>s.ansi256ToAnsi(s.hexToAnsi256(e)),enumerable:false}});return s}var W=K();var c=W;import E from"node:process";import H from"node:os";import _ from"node:tty";function u(t,e=globalThis.Deno?globalThis.Deno.args:E.argv){const r=t.startsWith("-")?"":t.length===1?"-":"--";const o=e.indexOf(r+t);const n=e.indexOf("--");return o!==-1&&(n===-1||o<n)}var{env:i}=E;var b;if(u("no-color")||u("no-colors")||u("color=false")||u("color=never")){b=0}else if(u("color")||u("colors")||u("color=true")||u("color=always")){b=1}function q(){if("FORCE_COLOR"in i){if(i.FORCE_COLOR==="true"){return 1}if(i.FORCE_COLOR==="false"){return 0}return i.FORCE_COLOR.length===0?1:Math.min(Number.parseInt(i.FORCE_COLOR,10),3)}}function Q(t){if(t===0){return false}return{level:t,hasBasic:true,has256:t>=2,has16m:t>=3}}function X(t,{streamIsTTY:e,sniffFlags:r=true}={}){const o=q();if(o!==void 0){b=o}const n=r?b:o;if(n===0){return 0}if(r){if(u("color=16m")||u("color=full")||u("color=truecolor")){return 3}if(u("color=256")){return 2}}if("TF_BUILD"in i&&"AGENT_NAME"in i){return 1}if(t&&!e&&n===void 0){return 0}const l=n||0;if(i.TERM==="dumb"){return l}if(E.platform==="win32"){const a=H.release().split(".");if(Number(a[0])>=10&&Number(a[2])>=10586){return Number(a[2])>=14931?3:2}return 1}if("CI"in i){if(["GITHUB_ACTIONS","GITEA_ACTIONS","CIRCLECI"].some(a=>a in i)){return 3}if(["TRAVIS","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some(a=>a in i)||i.CI_NAME==="codeship"){return 1}return l}if("TEAMCITY_VERSION"in i){return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(i.TEAMCITY_VERSION)?1:0}if(i.COLORTERM==="truecolor"){return 3}if(i.TERM==="xterm-kitty"){return 3}if(i.TERM==="xterm-ghostty"){return 3}if(i.TERM==="wezterm"){return 3}if("TERM_PROGRAM"in i){const a=Number.parseInt((i.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(i.TERM_PROGRAM){case"iTerm.app":{return a>=3?3:2}case"Apple_Terminal":{return 2}}}if(/-256(color)?$/i.test(i.TERM)){return 2}if(/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(i.TERM)){return 1}if("COLORTERM"in i){return 1}return l}function M(t,e={}){const r=X(t,{streamIsTTY:t&&t.isTTY,...e});return Q(r)}var Z={stdout:M({isTTY:_.isatty(1)}),stderr:M({isTTY:_.isatty(2)})};var S=Z;function B(t,e,r){let o=t.indexOf(e);if(o===-1){return t}const n=e.length;let l=0;let a="";do{a+=t.slice(l,o)+e+r;l=o+n;o=t.indexOf(e,l)}while(o!==-1);a+=t.slice(l);return a}function w(t,e,r,o){let n=0;let l="";do{const a=t[o-1]==="\r";l+=t.slice(n,a?o-1:o)+e+(a?"\r\n":"\n")+r;n=o+1;o=t.indexOf("\n",n)}while(o!==-1);l+=t.slice(n);return l}var{stdout:P,stderr:L}=S;var R=Symbol("GENERATOR");var f=Symbol("STYLER");var p=Symbol("IS_EMPTY");var F=["ansi","ansi","ansi256","ansi16m"];var d=Object.create(null);var ee=(t,e={})=>{if(e.level&&!(Number.isInteger(e.level)&&e.level>=0&&e.level<=3)){throw new Error("The `level` option should be an integer from 0 to 3")}const r=P?P.level:0;t.level=e.level===void 0?r:e.level};var k=class{constructor(e){return j(e)}};var j=t=>{const e=(...r)=>r.join(" ");ee(e,t);Object.setPrototypeOf(e,h.prototype);return e};function h(t){return j(t)}Object.setPrototypeOf(h.prototype,Function.prototype);for(const[t,e]of Object.entries(c)){d[t]={get(){const r=g(this,N(e.open,e.close,this[f]),this[p]);Object.defineProperty(this,t,{value:r});return r}}}d.visible={get(){const t=g(this,this[f],true);Object.defineProperty(this,"visible",{value:t});return t}};var C=(t,e,r,...o)=>{if(t==="rgb"){if(e==="ansi16m"){return c[r].ansi16m(...o)}if(e==="ansi256"){return c[r].ansi256(c.rgbToAnsi256(...o))}return c[r].ansi(c.rgbToAnsi(...o))}if(t==="hex"){return C("rgb",e,r,...c.hexToRgb(...o))}return c[r][t](...o)};var re=["rgb","hex","ansi256"];for(const t of re){d[t]={get(){const{level:r}=this;return function(...o){const n=N(C(t,F[r],"color",...o),c.color.close,this[f]);return g(this,n,this[p])}}};const e="bg"+t[0].toUpperCase()+t.slice(1);d[e]={get(){const{level:r}=this;return function(...o){const n=N(C(t,F[r],"bgColor",...o),c.bgColor.close,this[f]);return g(this,n,this[p])}}}}var te=Object.defineProperties(()=>{},{...d,level:{enumerable:true,get(){return this[R].level},set(t){this[R].level=t}}});var N=(t,e,r)=>{let o;let n;if(r===void 0){o=t;n=e}else{o=r.openAll+t;n=e+r.closeAll}return{open:t,close:e,openAll:o,closeAll:n,parent:r}};var g=(t,e,r)=>{const o=(...n)=>oe(o,n.length===1?""+n[0]:n.join(" "));Object.setPrototypeOf(o,te);o[R]=t;o[f]=e;o[p]=r;return o};var oe=(t,e)=>{if(t.level<=0||!e){return t[p]?"":e}let r=t[f];if(r===void 0){return e}const{openAll:o,closeAll:n}=r;if(e.includes("\x1B")){while(r!==void 0){e=B(e,r.close,r.open);r=r.parent}}const l=e.indexOf("\n");if(l!==-1){e=w(e,n,o,l)}return o+e+n};Object.defineProperties(h.prototype,d);var ne=h();var xe=h({level:L?L.level:0});var Ie=ne;export{ie as a,le as b,ae as c,T as d,k as e,Ie as f,ce as g,fe as h};
@@ -0,0 +1,6 @@
1
+ import { createRequire as __alran_cR } from "module"; import { basename as __alran_basename, dirname as __alran_dirname, join as __alran_join } from "path"; import { fileURLToPath as __alran_fileURLToPath, pathToFileURL as __alran_pathToFileURL } from "url"; const __alran_tuiCurrentModuleDir = __alran_dirname(__alran_fileURLToPath(import.meta.url)); const __alran_tuiPackageRoot = __alran_basename(__alran_tuiCurrentModuleDir) === "chunks" ? __alran_dirname(__alran_tuiCurrentModuleDir) : __alran_tuiCurrentModuleDir; const __alran_tuiPackageEntryUrl = __alran_pathToFileURL(__alran_join(__alran_tuiPackageRoot, "cli.js")).href; const require = __alran_cR(__alran_tuiPackageEntryUrl); const __dirname = __alran_tuiPackageRoot;
2
+ var Me=Symbol("Let zodToJsonSchema decide on which parser to use");var $e={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:true,rejectedAdditionalProperties:false,definitionPath:"definitions",target:"jsonSchema7",strictUnions:false,definitions:{},errorMessages:false,markdownDescription:false,patternStrategy:"escape",applyRegexFlags:false,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"};var ze=r=>typeof r==="string"?{...$e,name:r}:{...$e,...r};var x;(function(r){r.assertEqual=a=>{};function e(a){}r.assertIs=e;function t(a){throw new Error}r.assertNever=t;r.arrayToEnum=a=>{const s={};for(const i of a){s[i]=i}return s};r.getValidEnumValues=a=>{const s=r.objectKeys(a).filter(o=>typeof a[a[o]]!=="number");const i={};for(const o of s){i[o]=a[o]}return r.objectValues(i)};r.objectValues=a=>{return r.objectKeys(a).map(function(s){return a[s]})};r.objectKeys=typeof Object.keys==="function"?a=>Object.keys(a):a=>{const s=[];for(const i in a){if(Object.prototype.hasOwnProperty.call(a,i)){s.push(i)}}return s};r.find=(a,s)=>{for(const i of a){if(s(i))return i}return void 0};r.isInteger=typeof Number.isInteger==="function"?a=>Number.isInteger(a):a=>typeof a==="number"&&Number.isFinite(a)&&Math.floor(a)===a;function n(a,s=" | "){return a.map(i=>typeof i==="string"?`'${i}'`:i).join(s)}r.joinValues=n;r.jsonStringifyReplacer=(a,s)=>{if(typeof s==="bigint"){return s.toString()}return s}})(x||(x={}));var Le;(function(r){r.mergeShapes=(e,t)=>{return{...e,...t}}})(Le||(Le={}));var f=x.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]);var E=r=>{const e=typeof r;switch(e){case"undefined":return f.undefined;case"string":return f.string;case"number":return Number.isNaN(r)?f.nan:f.number;case"boolean":return f.boolean;case"function":return f.function;case"bigint":return f.bigint;case"symbol":return f.symbol;case"object":if(Array.isArray(r)){return f.array}if(r===null){return f.null}if(r.then&&typeof r.then==="function"&&r.catch&&typeof r.catch==="function"){return f.promise}if(typeof Map!=="undefined"&&r instanceof Map){return f.map}if(typeof Set!=="undefined"&&r instanceof Set){return f.set}if(typeof Date!=="undefined"&&r instanceof Date){return f.date}return f.object;default:return f.unknown}};var u=x.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"]);var O=class r extends Error{get errors(){return this.issues}constructor(e){super();this.issues=[];this.addIssue=n=>{this.issues=[...this.issues,n]};this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};const t=new.target.prototype;if(Object.setPrototypeOf){Object.setPrototypeOf(this,t)}else{this.__proto__=t}this.name="ZodError";this.issues=e}format(e){const t=e||function(s){return s.message};const n={_errors:[]};const a=s=>{for(const i of s.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){n._errors.push(t(i))}else{let o=n;let c=0;while(c<i.path.length){const p=i.path[c];const g=c===i.path.length-1;if(p==="_errors"){if(g)o._errors.push(t(i));c++;continue}if(!Object.prototype.hasOwnProperty.call(o,p)){if(p==="__proto__"){Object.defineProperty(o,p,{value:{_errors:[]},writable:true,enumerable:true,configurable:true})}else{o[p]={_errors:[]}}}o=o[p];if(g){o._errors.push(t(i))}c++}}}};a(this);return n}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,x.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){const t=Object.create(null);const n=[];for(const a of this.issues){if(a.path.length>0){const s=a.path[0];t[s]=t[s]||[];t[s].push(e(a))}else{n.push(e(a))}}return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};O.create=r=>{const e=new O(r);return e};var xt=(r,e)=>{let t;switch(r.code){case u.invalid_type:if(r.received===f.undefined){t="Required"}else{t=`Expected ${r.expected}, received ${r.received}`}break;case u.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,x.jsonStringifyReplacer)}`;break;case u.unrecognized_keys:t=`Unrecognized key(s) in object: ${x.joinValues(r.keys,", ")}`;break;case u.invalid_union:t=`Invalid input`;break;case u.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${x.joinValues(r.options)}`;break;case u.invalid_enum_value:t=`Invalid enum value. Expected ${x.joinValues(r.options)}, received '${r.received}'`;break;case u.invalid_arguments:t=`Invalid function arguments`;break;case u.invalid_return_type:t=`Invalid function return type`;break;case u.invalid_date:t=`Invalid date`;break;case u.invalid_string:if(typeof r.validation==="object"){if("includes"in r.validation){t=`Invalid input: must include "${r.validation.includes}"`;if(typeof r.validation.position==="number"){t=`${t} at one or more positions greater than or equal to ${r.validation.position}`}}else if("startsWith"in r.validation){t=`Invalid input: must start with "${r.validation.startsWith}"`}else if("endsWith"in r.validation){t=`Invalid input: must end with "${r.validation.endsWith}"`}else{x.assertNever(r.validation)}}else if(r.validation!=="regex"){t=`Invalid ${r.validation}`}else{t="Invalid"}break;case u.too_small:if(r.type==="array")t=`Array must contain ${r.exact?"exactly":r.inclusive?`at least`:`more than`} ${r.minimum} element(s)`;else if(r.type==="string")t=`String must contain ${r.exact?"exactly":r.inclusive?`at least`:`over`} ${r.minimum} character(s)`;else if(r.type==="number")t=`Number must be ${r.exact?`exactly equal to `:r.inclusive?`greater than or equal to `:`greater than `}${r.minimum}`;else if(r.type==="bigint")t=`Number must be ${r.exact?`exactly equal to `:r.inclusive?`greater than or equal to `:`greater than `}${r.minimum}`;else if(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))}`;else t="Invalid input";break;case u.too_big:if(r.type==="array")t=`Array must contain ${r.exact?`exactly`:r.inclusive?`at most`:`less than`} ${r.maximum} element(s)`;else if(r.type==="string")t=`String must contain ${r.exact?`exactly`:r.inclusive?`at most`:`under`} ${r.maximum} character(s)`;else if(r.type==="number")t=`Number must be ${r.exact?`exactly`:r.inclusive?`less than or equal to`:`less than`} ${r.maximum}`;else if(r.type==="bigint")t=`BigInt must be ${r.exact?`exactly`:r.inclusive?`less than or equal to`:`less than`} ${r.maximum}`;else if(r.type==="date")t=`Date must be ${r.exact?`exactly`:r.inclusive?`smaller than or equal to`:`smaller than`} ${new Date(Number(r.maximum))}`;else t="Invalid input";break;case u.custom:t=`Invalid input`;break;case u.invalid_intersection_types:t=`Intersection results could not be merged`;break;case u.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case u.not_finite:t="Number must be finite";break;default:t=e.defaultError;x.assertNever(r)}return{message:t}};var z=xt;var bt=z;function ae(){return bt}var ge=r=>{const{data:e,path:t,errorMaps:n,issueData:a}=r;const s=[...t,...a.path||[]];const i={...a,path:s};if(a.message!==void 0){return{...a,path:s,message:a.message}}let o="";const c=n.filter(p=>!!p).slice().reverse();for(const p of c){o=p(i,{data:e,defaultError:o}).message}return{...a,path:s,message:o}};function l(r,e){const t=ae();const n=ge({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===z?void 0:z].filter(a=>!!a)});r.common.issues.push(n)}var w=class r{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray(e,t){const n=[];for(const a of t){if(a.status==="aborted")return h;if(a.status==="dirty")e.dirty();n.push(a.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){const n=[];for(const a of t){const s=await a.key;const i=await a.value;n.push({key:s,value:i})}return r.mergeObjectSync(e,n)}static mergeObjectSync(e,t){const n={};for(const a of t){const{key:s,value:i}=a;if(s.status==="aborted")return h;if(i.status==="aborted")return h;if(s.status==="dirty")e.dirty();if(i.status==="dirty")e.dirty();if(s.value!=="__proto__"&&(typeof i.value!=="undefined"||a.alwaysSet)){n[s.value]=i.value}}return{status:e.value,value:n}}};var h=Object.freeze({status:"aborted"});var B=r=>({status:"dirty",value:r});var A=r=>({status:"valid",value:r});var Oe=r=>r.status==="aborted";var Se=r=>r.status==="dirty";var F=r=>r.status==="valid";var se=r=>typeof Promise!=="undefined"&&r instanceof Promise;var m;(function(r){r.errToObj=e=>typeof e==="string"?{message:e}:e||{};r.toString=e=>typeof e==="string"?e:e?.message})(m||(m={}));var j=class{constructor(e,t,n,a){this._cachedPath=[];this.parent=e;this.data=t;this._path=n;this._key=a}get path(){if(!this._cachedPath.length){if(Array.isArray(this._key)){this._cachedPath.push(...this._path,...this._key)}else{this._cachedPath.push(...this._path,this._key)}}return this._cachedPath}};var Ve=(r,e)=>{if(F(e)){return{success:true,data:e.value}}else{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;const t=new O(r.common.issues);this._error=t;return this._error}}}};function _(r){if(!r)return{};const{errorMap:e,invalid_type_error:t,required_error:n,description:a}=r;if(e&&(t||n)){throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`)}if(e)return{errorMap:e,description:a};const s=(i,o)=>{const{message:c}=r;if(i.code==="invalid_enum_value"){return{message:c??o.defaultError}}if(typeof o.data==="undefined"){return{message:c??n??o.defaultError}}if(i.code!=="invalid_type")return{message:o.defaultError};return{message:c??t??o.defaultError}};return{errorMap:s,description:a}}var v=class{get description(){return this._def.description}_getType(e){return E(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:E(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new w,ctx:{common:e.parent.common,data:e.data,parsedType:E(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(se(t)){throw new Error("Synchronous parse encountered promise.")}return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){const n={common:{issues:[],async:t?.async??false,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:E(e)};const a=this._parseSync({data:e,path:n.path,parent:n});return Ve(n,a)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:E(e)};if(!this["~standard"].async){try{const n=this._parseSync({data:e,path:[],parent:t});return F(n)?{value:n.value}:{issues:t.common.issues}}catch(n){if(n?.message?.toLowerCase()?.includes("encountered")){this["~standard"].async=true}t.common={issues:[],async:true}}}return this._parseAsync({data:e,path:[],parent:t}).then(n=>F(n)?{value:n.value}:{issues:t.common.issues})}async parseAsync(e,t){const n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){const n={common:{issues:[],contextualErrorMap:t?.errorMap,async:true},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:E(e)};const a=this._parse({data:e,path:n.path,parent:n});const s=await(se(a)?a:Promise.resolve(a));return Ve(n,s)}refine(e,t){const n=a=>{if(typeof t==="string"||typeof t==="undefined"){return{message:t}}else if(typeof t==="function"){return t(a)}else{return t}};return this._refinement((a,s)=>{const i=e(a);const o=()=>s.addIssue({code:u.custom,...n(a)});if(typeof Promise!=="undefined"&&i instanceof Promise){return i.then(c=>{if(!c){o();return false}else{return true}})}if(!i){o();return false}else{return true}})}refinement(e,t){return this._refinement((n,a)=>{if(!e(n)){a.addIssue(typeof t==="function"?t(n,a):t);return false}else{return true}})}_refinement(e){return new C({schema:this,typeName:d.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 N.create(this,this._def)}nullable(){return M.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return V.create(this)}promise(){return U.create(this,this._def)}or(e){return Y.create([this,e],this._def)}and(e){return G.create(this,e,this._def)}transform(e){return new C({..._(this._def),schema:this,typeName:d.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e==="function"?e:()=>e;return new te({..._(this._def),innerType:this,defaultValue:t,typeName:d.ZodDefault})}brand(){return new _e({typeName:d.ZodBranded,type:this,..._(this._def)})}catch(e){const t=typeof e==="function"?e:()=>e;return new re({..._(this._def),innerType:this,catchValue:t,typeName:d.ZodCatch})}describe(e){const t=this.constructor;return new t({...this._def,description:e})}pipe(e){return ve.create(this,e)}readonly(){return ne.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};var kt=/^c[^\s-]{8,}$/i;var wt=/^[0-9a-z]+$/;var At=/^[0-9A-HJKMNP-TV-Z]{26}$/i;var Tt=/^[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;var Ot=/^[a-z0-9_-]{21}$/i;var St=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;var Pt=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;var jt=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;var Nt=`^[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$`;var Pe;var Ct=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;var Zt=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/;var Dt=/^(([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]))$/;var Rt=/^(([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])$/;var Et=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;var It=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;var Fe=`((\\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])))`;var $t=new RegExp(`^${Fe}$`);function Ue(r){let e=`[0-5]\\d`;if(r.precision){e=`${e}\\.\\d{${r.precision}}`}else if(r.precision==null){e=`${e}(\\.\\d+)?`}const t=r.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function Mt(r){return new RegExp(`^${Ue(r)}$`)}function zt(r){let e=`${Fe}T${Ue(r)}`;const t=[];t.push(r.local?`Z?`:`Z`);if(r.offset)t.push(`([+-]\\d{2}:?\\d{2})`);e=`${e}(${t.join("|")})`;return new RegExp(`^${e}$`)}function Lt(r,e){if((e==="v4"||!e)&&Ct.test(r)){return true}if((e==="v6"||!e)&&Dt.test(r)){return true}return false}function Vt(r,e){if(!St.test(r))return false;try{const[t]=r.split(".");if(!t)return false;const n=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"=");const a=JSON.parse(atob(n));if(typeof a!=="object"||a===null)return false;if("typ"in a&&a?.typ!=="JWT")return false;if(!a.alg)return false;if(e&&a.alg!==e)return false;return true}catch{return false}}function Ft(r,e){if((e==="v4"||!e)&&Zt.test(r)){return true}if((e==="v6"||!e)&&Rt.test(r)){return true}return false}var q=class r extends v{_parse(e){if(this._def.coerce){e.data=String(e.data)}const t=this._getType(e);if(t!==f.string){const s=this._getOrReturnCtx(e);l(s,{code:u.invalid_type,expected:f.string,received:s.parsedType});return h}const n=new w;let a=void 0;for(const s of this._def.checks){if(s.kind==="min"){if(e.data.length<s.value){a=this._getOrReturnCtx(e,a);l(a,{code:u.too_small,minimum:s.value,type:"string",inclusive:true,exact:false,message:s.message});n.dirty()}}else if(s.kind==="max"){if(e.data.length>s.value){a=this._getOrReturnCtx(e,a);l(a,{code:u.too_big,maximum:s.value,type:"string",inclusive:true,exact:false,message:s.message});n.dirty()}}else if(s.kind==="length"){const i=e.data.length>s.value;const o=e.data.length<s.value;if(i||o){a=this._getOrReturnCtx(e,a);if(i){l(a,{code:u.too_big,maximum:s.value,type:"string",inclusive:true,exact:true,message:s.message})}else if(o){l(a,{code:u.too_small,minimum:s.value,type:"string",inclusive:true,exact:true,message:s.message})}n.dirty()}}else if(s.kind==="email"){if(!jt.test(e.data)){a=this._getOrReturnCtx(e,a);l(a,{validation:"email",code:u.invalid_string,message:s.message});n.dirty()}}else if(s.kind==="emoji"){if(!Pe){Pe=new RegExp(Nt,"u")}if(!Pe.test(e.data)){a=this._getOrReturnCtx(e,a);l(a,{validation:"emoji",code:u.invalid_string,message:s.message});n.dirty()}}else if(s.kind==="uuid"){if(!Tt.test(e.data)){a=this._getOrReturnCtx(e,a);l(a,{validation:"uuid",code:u.invalid_string,message:s.message});n.dirty()}}else if(s.kind==="nanoid"){if(!Ot.test(e.data)){a=this._getOrReturnCtx(e,a);l(a,{validation:"nanoid",code:u.invalid_string,message:s.message});n.dirty()}}else if(s.kind==="cuid"){if(!kt.test(e.data)){a=this._getOrReturnCtx(e,a);l(a,{validation:"cuid",code:u.invalid_string,message:s.message});n.dirty()}}else if(s.kind==="cuid2"){if(!wt.test(e.data)){a=this._getOrReturnCtx(e,a);l(a,{validation:"cuid2",code:u.invalid_string,message:s.message});n.dirty()}}else if(s.kind==="ulid"){if(!At.test(e.data)){a=this._getOrReturnCtx(e,a);l(a,{validation:"ulid",code:u.invalid_string,message:s.message});n.dirty()}}else if(s.kind==="url"){try{new URL(e.data)}catch{a=this._getOrReturnCtx(e,a);l(a,{validation:"url",code:u.invalid_string,message:s.message});n.dirty()}}else if(s.kind==="regex"){s.regex.lastIndex=0;const i=s.regex.test(e.data);if(!i){a=this._getOrReturnCtx(e,a);l(a,{validation:"regex",code:u.invalid_string,message:s.message});n.dirty()}}else if(s.kind==="trim"){e.data=e.data.trim()}else if(s.kind==="includes"){if(!e.data.includes(s.value,s.position)){a=this._getOrReturnCtx(e,a);l(a,{code:u.invalid_string,validation:{includes:s.value,position:s.position},message:s.message});n.dirty()}}else if(s.kind==="toLowerCase"){e.data=e.data.toLowerCase()}else if(s.kind==="toUpperCase"){e.data=e.data.toUpperCase()}else if(s.kind==="startsWith"){if(!e.data.startsWith(s.value)){a=this._getOrReturnCtx(e,a);l(a,{code:u.invalid_string,validation:{startsWith:s.value},message:s.message});n.dirty()}}else if(s.kind==="endsWith"){if(!e.data.endsWith(s.value)){a=this._getOrReturnCtx(e,a);l(a,{code:u.invalid_string,validation:{endsWith:s.value},message:s.message});n.dirty()}}else if(s.kind==="datetime"){const i=zt(s);if(!i.test(e.data)){a=this._getOrReturnCtx(e,a);l(a,{code:u.invalid_string,validation:"datetime",message:s.message});n.dirty()}}else if(s.kind==="date"){const i=$t;if(!i.test(e.data)){a=this._getOrReturnCtx(e,a);l(a,{code:u.invalid_string,validation:"date",message:s.message});n.dirty()}}else if(s.kind==="time"){const i=Mt(s);if(!i.test(e.data)){a=this._getOrReturnCtx(e,a);l(a,{code:u.invalid_string,validation:"time",message:s.message});n.dirty()}}else if(s.kind==="duration"){if(!Pt.test(e.data)){a=this._getOrReturnCtx(e,a);l(a,{validation:"duration",code:u.invalid_string,message:s.message});n.dirty()}}else if(s.kind==="ip"){if(!Lt(e.data,s.version)){a=this._getOrReturnCtx(e,a);l(a,{validation:"ip",code:u.invalid_string,message:s.message});n.dirty()}}else if(s.kind==="jwt"){if(!Vt(e.data,s.alg)){a=this._getOrReturnCtx(e,a);l(a,{validation:"jwt",code:u.invalid_string,message:s.message});n.dirty()}}else if(s.kind==="cidr"){if(!Ft(e.data,s.version)){a=this._getOrReturnCtx(e,a);l(a,{validation:"cidr",code:u.invalid_string,message:s.message});n.dirty()}}else if(s.kind==="base64"){if(!Et.test(e.data)){a=this._getOrReturnCtx(e,a);l(a,{validation:"base64",code:u.invalid_string,message:s.message});n.dirty()}}else if(s.kind==="base64url"){if(!It.test(e.data)){a=this._getOrReturnCtx(e,a);l(a,{validation:"base64url",code:u.invalid_string,message:s.message});n.dirty()}}else{x.assertNever(s)}}return{status:n.value,value:e.data}}_regex(e,t,n){return this.refinement(a=>e.test(a),{validation:t,code:u.invalid_string,...m.errToObj(n)})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...m.errToObj(e)})}url(e){return this._addCheck({kind:"url",...m.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...m.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...m.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...m.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...m.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...m.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...m.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...m.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...m.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...m.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...m.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...m.errToObj(e)})}datetime(e){if(typeof e==="string"){return this._addCheck({kind:"datetime",precision:null,offset:false,local:false,message:e})}return this._addCheck({kind:"datetime",precision:typeof e?.precision==="undefined"?null:e?.precision,offset:e?.offset??false,local:e?.local??false,...m.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){if(typeof e==="string"){return this._addCheck({kind:"time",precision:null,message:e})}return this._addCheck({kind:"time",precision:typeof e?.precision==="undefined"?null:e?.precision,...m.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...m.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...m.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...m.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...m.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...m.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...m.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...m.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...m.errToObj(t)})}nonempty(e){return this.min(1,m.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(const t of this._def.checks){if(t.kind==="min"){if(e===null||t.value>e)e=t.value}}return e}get maxLength(){let e=null;for(const t of this._def.checks){if(t.kind==="max"){if(e===null||t.value<e)e=t.value}}return e}};q.create=r=>{return new q({checks:[],typeName:d.ZodString,coerce:r?.coerce??false,..._(r)})};function Ut(r,e){const t=(r.toString().split(".")[1]||"").length;const n=(e.toString().split(".")[1]||"").length;const a=t>n?t:n;const s=Number.parseInt(r.toFixed(a).replace(".",""));const i=Number.parseInt(e.toFixed(a).replace(".",""));return s%i/10**a}var ie=class r extends v{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)}const t=this._getType(e);if(t!==f.number){const s=this._getOrReturnCtx(e);l(s,{code:u.invalid_type,expected:f.number,received:s.parsedType});return h}let n=void 0;const a=new w;for(const s of this._def.checks){if(s.kind==="int"){if(!x.isInteger(e.data)){n=this._getOrReturnCtx(e,n);l(n,{code:u.invalid_type,expected:"integer",received:"float",message:s.message});a.dirty()}}else if(s.kind==="min"){const i=s.inclusive?e.data<s.value:e.data<=s.value;if(i){n=this._getOrReturnCtx(e,n);l(n,{code:u.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:false,message:s.message});a.dirty()}}else if(s.kind==="max"){const i=s.inclusive?e.data>s.value:e.data>=s.value;if(i){n=this._getOrReturnCtx(e,n);l(n,{code:u.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:false,message:s.message});a.dirty()}}else if(s.kind==="multipleOf"){if(Ut(e.data,s.value)!==0){n=this._getOrReturnCtx(e,n);l(n,{code:u.not_multiple_of,multipleOf:s.value,message:s.message});a.dirty()}}else if(s.kind==="finite"){if(!Number.isFinite(e.data)){n=this._getOrReturnCtx(e,n);l(n,{code:u.not_finite,message:s.message});a.dirty()}}else{x.assertNever(s)}}return{status:a.value,value:e.data}}gte(e,t){return this.setLimit("min",e,true,m.toString(t))}gt(e,t){return this.setLimit("min",e,false,m.toString(t))}lte(e,t){return this.setLimit("max",e,true,m.toString(t))}lt(e,t){return this.setLimit("max",e,false,m.toString(t))}setLimit(e,t,n,a){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:m.toString(a)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:m.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:false,message:m.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:false,message:m.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:true,message:m.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:true,message:m.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:m.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:m.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:true,value:Number.MIN_SAFE_INTEGER,message:m.toString(e)})._addCheck({kind:"max",inclusive:true,value:Number.MAX_SAFE_INTEGER,message:m.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks){if(t.kind==="min"){if(e===null||t.value>e)e=t.value}}return e}get maxValue(){let e=null;for(const t of this._def.checks){if(t.kind==="max"){if(e===null||t.value<e)e=t.value}}return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&x.isInteger(e.value))}get isFinite(){let e=null;let t=null;for(const n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf"){return true}else if(n.kind==="min"){if(t===null||n.value>t)t=n.value}else if(n.kind==="max"){if(e===null||n.value<e)e=n.value}}return Number.isFinite(t)&&Number.isFinite(e)}};ie.create=r=>{return new ie({checks:[],typeName:d.ZodNumber,coerce:r?.coerce||false,..._(r)})};var oe=class r extends v{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)}}const t=this._getType(e);if(t!==f.bigint){return this._getInvalidInput(e)}let n=void 0;const a=new w;for(const s of this._def.checks){if(s.kind==="min"){const i=s.inclusive?e.data<s.value:e.data<=s.value;if(i){n=this._getOrReturnCtx(e,n);l(n,{code:u.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message});a.dirty()}}else if(s.kind==="max"){const i=s.inclusive?e.data>s.value:e.data>=s.value;if(i){n=this._getOrReturnCtx(e,n);l(n,{code:u.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message});a.dirty()}}else if(s.kind==="multipleOf"){if(e.data%s.value!==BigInt(0)){n=this._getOrReturnCtx(e,n);l(n,{code:u.not_multiple_of,multipleOf:s.value,message:s.message});a.dirty()}}else{x.assertNever(s)}}return{status:a.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);l(t,{code:u.invalid_type,expected:f.bigint,received:t.parsedType});return h}gte(e,t){return this.setLimit("min",e,true,m.toString(t))}gt(e,t){return this.setLimit("min",e,false,m.toString(t))}lte(e,t){return this.setLimit("max",e,true,m.toString(t))}lt(e,t){return this.setLimit("max",e,false,m.toString(t))}setLimit(e,t,n,a){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:m.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:m.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:false,message:m.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:true,message:m.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:true,message:m.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:m.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks){if(t.kind==="min"){if(e===null||t.value>e)e=t.value}}return e}get maxValue(){let e=null;for(const t of this._def.checks){if(t.kind==="max"){if(e===null||t.value<e)e=t.value}}return e}};oe.create=r=>{return new oe({checks:[],typeName:d.ZodBigInt,coerce:r?.coerce??false,..._(r)})};var ce=class extends v{_parse(e){if(this._def.coerce){e.data=Boolean(e.data)}const t=this._getType(e);if(t!==f.boolean){const n=this._getOrReturnCtx(e);l(n,{code:u.invalid_type,expected:f.boolean,received:n.parsedType});return h}return A(e.data)}};ce.create=r=>{return new ce({typeName:d.ZodBoolean,coerce:r?.coerce||false,..._(r)})};var ue=class r extends v{_parse(e){if(this._def.coerce){e.data=new Date(e.data)}const t=this._getType(e);if(t!==f.date){const s=this._getOrReturnCtx(e);l(s,{code:u.invalid_type,expected:f.date,received:s.parsedType});return h}if(Number.isNaN(e.data.getTime())){const s=this._getOrReturnCtx(e);l(s,{code:u.invalid_date});return h}const n=new w;let a=void 0;for(const s of this._def.checks){if(s.kind==="min"){if(e.data.getTime()<s.value){a=this._getOrReturnCtx(e,a);l(a,{code:u.too_small,message:s.message,inclusive:true,exact:false,minimum:s.value,type:"date"});n.dirty()}}else if(s.kind==="max"){if(e.data.getTime()>s.value){a=this._getOrReturnCtx(e,a);l(a,{code:u.too_big,message:s.message,inclusive:true,exact:false,maximum:s.value,type:"date"});n.dirty()}}else{x.assertNever(s)}}return{status:n.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:m.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:m.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks){if(t.kind==="min"){if(e===null||t.value>e)e=t.value}}return e!=null?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks){if(t.kind==="max"){if(e===null||t.value<e)e=t.value}}return e!=null?new Date(e):null}};ue.create=r=>{return new ue({checks:[],coerce:r?.coerce||false,typeName:d.ZodDate,..._(r)})};var de=class extends v{_parse(e){const t=this._getType(e);if(t!==f.symbol){const n=this._getOrReturnCtx(e);l(n,{code:u.invalid_type,expected:f.symbol,received:n.parsedType});return h}return A(e.data)}};de.create=r=>{return new de({typeName:d.ZodSymbol,..._(r)})};var J=class extends v{_parse(e){const t=this._getType(e);if(t!==f.undefined){const n=this._getOrReturnCtx(e);l(n,{code:u.invalid_type,expected:f.undefined,received:n.parsedType});return h}return A(e.data)}};J.create=r=>{return new J({typeName:d.ZodUndefined,..._(r)})};var H=class extends v{_parse(e){const t=this._getType(e);if(t!==f.null){const n=this._getOrReturnCtx(e);l(n,{code:u.invalid_type,expected:f.null,received:n.parsedType});return h}return A(e.data)}};H.create=r=>{return new H({typeName:d.ZodNull,..._(r)})};var le=class extends v{constructor(){super(...arguments);this._any=true}_parse(e){return A(e.data)}};le.create=r=>{return new le({typeName:d.ZodAny,..._(r)})};var L=class extends v{constructor(){super(...arguments);this._unknown=true}_parse(e){return A(e.data)}};L.create=r=>{return new L({typeName:d.ZodUnknown,..._(r)})};var R=class extends v{_parse(e){const t=this._getOrReturnCtx(e);l(t,{code:u.invalid_type,expected:f.never,received:t.parsedType});return h}};R.create=r=>{return new R({typeName:d.ZodNever,..._(r)})};var pe=class extends v{_parse(e){const t=this._getType(e);if(t!==f.undefined){const n=this._getOrReturnCtx(e);l(n,{code:u.invalid_type,expected:f.void,received:n.parsedType});return h}return A(e.data)}};pe.create=r=>{return new pe({typeName:d.ZodVoid,..._(r)})};var V=class r extends v{_parse(e){const{ctx:t,status:n}=this._processInputParams(e);const a=this._def;if(t.parsedType!==f.array){l(t,{code:u.invalid_type,expected:f.array,received:t.parsedType});return h}if(a.exactLength!==null){const i=t.data.length>a.exactLength.value;const o=t.data.length<a.exactLength.value;if(i||o){l(t,{code:i?u.too_big:u.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});n.dirty()}}if(a.minLength!==null){if(t.data.length<a.minLength.value){l(t,{code:u.too_small,minimum:a.minLength.value,type:"array",inclusive:true,exact:false,message:a.minLength.message});n.dirty()}}if(a.maxLength!==null){if(t.data.length>a.maxLength.value){l(t,{code:u.too_big,maximum:a.maxLength.value,type:"array",inclusive:true,exact:false,message:a.maxLength.message});n.dirty()}}if(t.common.async){return Promise.all([...t.data].map((i,o)=>{return a.type._parseAsync(new j(t,i,t.path,o))})).then(i=>{return w.mergeArray(n,i)})}const s=[...t.data].map((i,o)=>{return a.type._parseSync(new j(t,i,t.path,o))});return w.mergeArray(n,s)}get element(){return this._def.type}min(e,t){return new r({...this._def,minLength:{value:e,message:m.toString(t)}})}max(e,t){return new r({...this._def,maxLength:{value:e,message:m.toString(t)}})}length(e,t){return new r({...this._def,exactLength:{value:e,message:m.toString(t)}})}nonempty(e){return this.min(1,e)}};V.create=(r,e)=>{return new V({type:r,minLength:null,maxLength:null,exactLength:null,typeName:d.ZodArray,..._(e)})};function W(r){if(r instanceof S){const e={};for(const t in r.shape){const n=r.shape[t];e[t]=N.create(W(n))}return new S({...r._def,shape:()=>e})}else if(r instanceof V){return new V({...r._def,type:W(r.element)})}else if(r instanceof N){return N.create(W(r.unwrap()))}else if(r instanceof M){return M.create(W(r.unwrap()))}else if(r instanceof $){return $.create(r.items.map(e=>W(e)))}else{return r}}var S=class r extends v{constructor(){super(...arguments);this._cached=null;this.nonstrict=this.passthrough;this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape();const t=x.objectKeys(e);this._cached={shape:e,keys:t};return this._cached}_parse(e){const t=this._getType(e);if(t!==f.object){const p=this._getOrReturnCtx(e);l(p,{code:u.invalid_type,expected:f.object,received:p.parsedType});return h}const{status:n,ctx:a}=this._processInputParams(e);const{shape:s,keys:i}=this._getCached();const o=[];if(!(this._def.catchall instanceof R&&this._def.unknownKeys==="strip")){for(const p in a.data){if(!i.includes(p)){o.push(p)}}}const c=[];for(const p of i){const g=s[p];const P=a.data[p];c.push({key:{status:"valid",value:p},value:g._parse(new j(a,P,a.path,p)),alwaysSet:p in a.data})}if(this._def.catchall instanceof R){const p=this._def.unknownKeys;if(p==="passthrough"){for(const g of o){c.push({key:{status:"valid",value:g},value:{status:"valid",value:a.data[g]}})}}else if(p==="strict"){if(o.length>0){l(a,{code:u.unrecognized_keys,keys:o});n.dirty()}}else if(p==="strip"){}else{throw new Error(`Internal ZodObject error: invalid unknownKeys value.`)}}else{const p=this._def.catchall;for(const g of o){const P=a.data[g];c.push({key:{status:"valid",value:g},value:p._parse(new j(a,P,a.path,g)),alwaysSet:g in a.data})}}if(a.common.async){return Promise.resolve().then(async()=>{const p=[];for(const g of c){const P=await g.key;const Ae=await g.value;p.push({key:P,value:Ae,alwaysSet:g.alwaysSet})}return p}).then(p=>{return w.mergeObjectSync(n,p)})}else{return w.mergeObjectSync(n,c)}}get shape(){return this._def.shape()}strict(e){m.errToObj;return new r({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,n)=>{const a=this._def.errorMap?.(t,n).message??n.defaultError;if(t.code==="unrecognized_keys")return{message:m.errToObj(e).message??a};return{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){const t=new r({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:d.ZodObject});return t}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new r({...this._def,catchall:e})}pick(e){const t={};for(const n of x.objectKeys(e)){if(e[n]&&this.shape[n]){t[n]=this.shape[n]}}return new r({...this._def,shape:()=>t})}omit(e){const t={};for(const n of x.objectKeys(this.shape)){if(!e[n]){t[n]=this.shape[n]}}return new r({...this._def,shape:()=>t})}deepPartial(){return W(this)}partial(e){const t={};for(const n of x.objectKeys(this.shape)){const a=this.shape[n];if(e&&!e[n]){t[n]=a}else{t[n]=a.optional()}}return new r({...this._def,shape:()=>t})}required(e){const t={};for(const n of x.objectKeys(this.shape)){if(e&&!e[n]){t[n]=this.shape[n]}else{const a=this.shape[n];let s=a;while(s instanceof N){s=s._def.innerType}t[n]=s}}return new r({...this._def,shape:()=>t})}keyof(){return Be(x.objectKeys(this.shape))}};S.create=(r,e)=>{return new S({shape:()=>r,unknownKeys:"strip",catchall:R.create(),typeName:d.ZodObject,..._(e)})};S.strictCreate=(r,e)=>{return new S({shape:()=>r,unknownKeys:"strict",catchall:R.create(),typeName:d.ZodObject,..._(e)})};S.lazycreate=(r,e)=>{return new S({shape:r,unknownKeys:"strip",catchall:R.create(),typeName:d.ZodObject,..._(e)})};var Y=class extends v{_parse(e){const{ctx:t}=this._processInputParams(e);const n=this._def.options;function a(s){for(const o of s){if(o.result.status==="valid"){return o.result}}for(const o of s){if(o.result.status==="dirty"){t.common.issues.push(...o.ctx.common.issues);return o.result}}const i=s.map(o=>new O(o.ctx.common.issues));l(t,{code:u.invalid_union,unionErrors:i});return h}if(t.common.async){return Promise.all(n.map(async s=>{const i={...t,common:{...t.common,issues:[]},parent:null};return{result:await s._parseAsync({data:t.data,path:t.path,parent:i}),ctx:i}})).then(a)}else{let s=void 0;const i=[];for(const c of n){const p={...t,common:{...t.common,issues:[]},parent:null};const g=c._parseSync({data:t.data,path:t.path,parent:p});if(g.status==="valid"){return g}else if(g.status==="dirty"&&!s){s={result:g,ctx:p}}if(p.common.issues.length){i.push(p.common.issues)}}if(s){t.common.issues.push(...s.ctx.common.issues);return s.result}const o=i.map(c=>new O(c));l(t,{code:u.invalid_union,unionErrors:o});return h}}get options(){return this._def.options}};Y.create=(r,e)=>{return new Y({options:r,typeName:d.ZodUnion,..._(e)})};var I=r=>{if(r instanceof K){return I(r.schema)}else if(r instanceof C){return I(r.innerType())}else if(r instanceof Q){return[r.value]}else if(r instanceof X){return r.options}else if(r instanceof ee){return x.objectValues(r.enum)}else if(r instanceof te){return I(r._def.innerType)}else if(r instanceof J){return[void 0]}else if(r instanceof H){return[null]}else if(r instanceof N){return[void 0,...I(r.unwrap())]}else if(r instanceof M){return[null,...I(r.unwrap())]}else if(r instanceof _e){return I(r.unwrap())}else if(r instanceof ne){return I(r.unwrap())}else if(r instanceof re){return I(r._def.innerType)}else{return[]}};var je=class r extends v{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==f.object){l(t,{code:u.invalid_type,expected:f.object,received:t.parsedType});return h}const n=this.discriminator;const a=t.data[n];const s=this.optionsMap.get(a);if(!s){l(t,{code:u.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]});return h}if(t.common.async){return s._parseAsync({data:t.data,path:t.path,parent:t})}else{return s._parseSync({data:t.data,path:t.path,parent:t})}}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,n){const a=new Map;for(const s of t){const i=I(s.shape[e]);if(!i.length){throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`)}for(const o of i){if(a.has(o)){throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(o)}`)}a.set(o,s)}}return new r({typeName:d.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:a,..._(n)})}};function Ne(r,e){const t=E(r);const n=E(e);if(r===e){return{valid:true,data:r}}else if(t===f.object&&n===f.object){const a=x.objectKeys(e);const s=x.objectKeys(r).filter(o=>a.indexOf(o)!==-1);const i={...r,...e};if(Object.prototype.hasOwnProperty.call(i,"__proto__"))delete i.__proto__;for(const o of s){if(o==="__proto__")continue;const c=Ne(r[o],e[o]);if(!c.valid){return{valid:false}}i[o]=c.data}return{valid:true,data:i}}else if(t===f.array&&n===f.array){if(r.length!==e.length){return{valid:false}}const a=[];for(let s=0;s<r.length;s++){const i=r[s];const o=e[s];const c=Ne(i,o);if(!c.valid){return{valid:false}}a.push(c.data)}return{valid:true,data:a}}else if(t===f.date&&n===f.date&&+r===+e){return{valid:true,data:r}}else{return{valid:false}}}var G=class extends v{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);const a=(s,i)=>{if(Oe(s)||Oe(i)){return h}const o=Ne(s.value,i.value);if(!o.valid){l(n,{code:u.invalid_intersection_types});return h}if(Se(s)||Se(i)){t.dirty()}return{status:t.value,value:o.data}};if(n.common.async){return Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([s,i])=>a(s,i))}else{return a(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}}};G.create=(r,e,t)=>{return new G({left:r,right:e,typeName:d.ZodIntersection,..._(t)})};var $=class r extends v{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==f.array){l(n,{code:u.invalid_type,expected:f.array,received:n.parsedType});return h}if(n.data.length<this._def.items.length){l(n,{code:u.too_small,minimum:this._def.items.length,inclusive:true,exact:false,type:"array"});return h}const a=this._def.rest;if(!a&&n.data.length>this._def.items.length){l(n,{code:u.too_big,maximum:this._def.items.length,inclusive:true,exact:false,type:"array"});t.dirty()}const s=[...n.data].map((i,o)=>{const c=this._def.items[o]||this._def.rest;if(!c)return null;return c._parse(new j(n,i,n.path,o))}).filter(i=>!!i);if(n.common.async){return Promise.all(s).then(i=>{return w.mergeArray(t,i)})}else{return w.mergeArray(t,s)}}get items(){return this._def.items}rest(e){return new r({...this._def,rest:e})}};$.create=(r,e)=>{if(!Array.isArray(r)){throw new Error("You must pass an array of schemas to z.tuple([ ... ])")}return new $({items:r,typeName:d.ZodTuple,rest:null,..._(e)})};var Ce=class r extends v{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==f.object){l(n,{code:u.invalid_type,expected:f.object,received:n.parsedType});return h}const a=[];const s=this._def.keyType;const i=this._def.valueType;for(const o in n.data){a.push({key:s._parse(new j(n,o,n.path,o)),value:i._parse(new j(n,n.data[o],n.path,o)),alwaysSet:o in n.data})}if(n.common.async){return w.mergeObjectAsync(t,a)}else{return w.mergeObjectSync(t,a)}}get element(){return this._def.valueType}static create(e,t,n){if(t instanceof v){return new r({keyType:e,valueType:t,typeName:d.ZodRecord,..._(n)})}return new r({keyType:q.create(),valueType:e,typeName:d.ZodRecord,..._(t)})}};var fe=class extends v{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==f.map){l(n,{code:u.invalid_type,expected:f.map,received:n.parsedType});return h}const a=this._def.keyType;const s=this._def.valueType;const i=[...n.data.entries()].map(([o,c],p)=>{return{key:a._parse(new j(n,o,n.path,[p,"key"])),value:s._parse(new j(n,c,n.path,[p,"value"]))}});if(n.common.async){const o=new Map;return Promise.resolve().then(async()=>{for(const c of i){const p=await c.key;const g=await c.value;if(p.status==="aborted"||g.status==="aborted"){return h}if(p.status==="dirty"||g.status==="dirty"){t.dirty()}o.set(p.value,g.value)}return{status:t.value,value:o}})}else{const o=new Map;for(const c of i){const p=c.key;const g=c.value;if(p.status==="aborted"||g.status==="aborted"){return h}if(p.status==="dirty"||g.status==="dirty"){t.dirty()}o.set(p.value,g.value)}return{status:t.value,value:o}}}};fe.create=(r,e,t)=>{return new fe({valueType:e,keyType:r,typeName:d.ZodMap,..._(t)})};var me=class r extends v{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==f.set){l(n,{code:u.invalid_type,expected:f.set,received:n.parsedType});return h}const a=this._def;if(a.minSize!==null){if(n.data.size<a.minSize.value){l(n,{code:u.too_small,minimum:a.minSize.value,type:"set",inclusive:true,exact:false,message:a.minSize.message});t.dirty()}}if(a.maxSize!==null){if(n.data.size>a.maxSize.value){l(n,{code:u.too_big,maximum:a.maxSize.value,type:"set",inclusive:true,exact:false,message:a.maxSize.message});t.dirty()}}const s=this._def.valueType;function i(c){const p=new Set;for(const g of c){if(g.status==="aborted")return h;if(g.status==="dirty")t.dirty();p.add(g.value)}return{status:t.value,value:p}}const o=[...n.data.values()].map((c,p)=>s._parse(new j(n,c,n.path,p)));if(n.common.async){return Promise.all(o).then(c=>i(c))}else{return i(o)}}min(e,t){return new r({...this._def,minSize:{value:e,message:m.toString(t)}})}max(e,t){return new r({...this._def,maxSize:{value:e,message:m.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};me.create=(r,e)=>{return new me({valueType:r,minSize:null,maxSize:null,typeName:d.ZodSet,..._(e)})};var Ze=class r extends v{constructor(){super(...arguments);this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==f.function){l(t,{code:u.invalid_type,expected:f.function,received:t.parsedType});return h}function n(o,c){return ge({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,ae(),z].filter(p=>!!p),issueData:{code:u.invalid_arguments,argumentsError:c}})}function a(o,c){return ge({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,ae(),z].filter(p=>!!p),issueData:{code:u.invalid_return_type,returnTypeError:c}})}const s={errorMap:t.common.contextualErrorMap};const i=t.data;if(this._def.returns instanceof U){const o=this;return A(async function(...c){const p=new O([]);const g=await o._def.args.parseAsync(c,s).catch(Te=>{p.addIssue(n(c,Te));throw p});const P=await Reflect.apply(i,this,g);const Ae=await o._def.returns._def.type.parseAsync(P,s).catch(Te=>{p.addIssue(a(P,Te));throw p});return Ae})}else{const o=this;return A(function(...c){const p=o._def.args.safeParse(c,s);if(!p.success){throw new O([n(c,p.error)])}const g=Reflect.apply(i,this,p.data);const P=o._def.returns.safeParse(g,s);if(!P.success){throw new O([a(g,P.error)])}return P.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new r({...this._def,args:$.create(e).rest(L.create())})}returns(e){return new r({...this._def,returns:e})}implement(e){const t=this.parse(e);return t}strictImplement(e){const t=this.parse(e);return t}static create(e,t,n){return new r({args:e?e:$.create([]).rest(L.create()),returns:t||L.create(),typeName:d.ZodFunction,..._(n)})}};var K=class extends v{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);const n=this._def.getter();return n._parse({data:t.data,path:t.path,parent:t})}};K.create=(r,e)=>{return new K({getter:r,typeName:d.ZodLazy,..._(e)})};var Q=class extends v{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);l(t,{received:t.data,code:u.invalid_literal,expected:this._def.value});return h}return{status:"valid",value:e.data}}get value(){return this._def.value}};Q.create=(r,e)=>{return new Q({value:r,typeName:d.ZodLiteral,..._(e)})};function Be(r,e){return new X({values:r,typeName:d.ZodEnum,..._(e)})}var X=class r extends v{_parse(e){if(typeof e.data!=="string"){const t=this._getOrReturnCtx(e);const n=this._def.values;l(t,{expected:x.joinValues(n),received:t.parsedType,code:u.invalid_type});return h}if(!this._cache){this._cache=new Set(this._def.values)}if(!this._cache.has(e.data)){const t=this._getOrReturnCtx(e);const n=this._def.values;l(t,{received:t.data,code:u.invalid_enum_value,options:n});return h}return A(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values){e[t]=t}return e}get Values(){const e={};for(const t of this._def.values){e[t]=t}return e}get Enum(){const e={};for(const 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(n=>!e.includes(n)),{...this._def,...t})}};X.create=Be;var ee=class extends v{_parse(e){const t=x.getValidEnumValues(this._def.values);const n=this._getOrReturnCtx(e);if(n.parsedType!==f.string&&n.parsedType!==f.number){const a=x.objectValues(t);l(n,{expected:x.joinValues(a),received:n.parsedType,code:u.invalid_type});return h}if(!this._cache){this._cache=new Set(x.getValidEnumValues(this._def.values))}if(!this._cache.has(e.data)){const a=x.objectValues(t);l(n,{received:n.data,code:u.invalid_enum_value,options:a});return h}return A(e.data)}get enum(){return this._def.values}};ee.create=(r,e)=>{return new ee({values:r,typeName:d.ZodNativeEnum,..._(e)})};var U=class extends v{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==f.promise&&t.common.async===false){l(t,{code:u.invalid_type,expected:f.promise,received:t.parsedType});return h}const n=t.parsedType===f.promise?t.data:Promise.resolve(t.data);return A(n.then(a=>{return this._def.type.parseAsync(a,{path:t.path,errorMap:t.common.contextualErrorMap})}))}};U.create=(r,e)=>{return new U({type:r,typeName:d.ZodPromise,..._(e)})};var C=class extends v{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===d.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:n}=this._processInputParams(e);const a=this._def.effect||null;const s={addIssue:i=>{l(n,i);if(i.fatal){t.abort()}else{t.dirty()}},get path(){return n.path}};s.addIssue=s.addIssue.bind(s);if(a.type==="preprocess"){const i=a.transform(n.data,s);if(n.common.async){return Promise.resolve(i).then(async o=>{if(t.value==="aborted")return h;const c=await this._def.schema._parseAsync({data:o,path:n.path,parent:n});if(c.status==="aborted")return h;if(c.status==="dirty")return B(c.value);if(t.value==="dirty")return B(c.value);return c})}else{if(t.value==="aborted")return h;const o=this._def.schema._parseSync({data:i,path:n.path,parent:n});if(o.status==="aborted")return h;if(o.status==="dirty")return B(o.value);if(t.value==="dirty")return B(o.value);return o}}if(a.type==="refinement"){const i=o=>{const c=a.refinement(o,s);if(n.common.async){return Promise.resolve(c)}if(c instanceof Promise){throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.")}return o};if(n.common.async===false){const o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(o.status==="aborted")return h;if(o.status==="dirty")t.dirty();i(o.value);return{status:t.value,value:o.value}}else{return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>{if(o.status==="aborted")return h;if(o.status==="dirty")t.dirty();return i(o.value).then(()=>{return{status:t.value,value:o.value}})})}}if(a.type==="transform"){if(n.common.async===false){const i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!F(i))return h;const o=a.transform(i.value,s);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:n.data,path:n.path,parent:n}).then(i=>{if(!F(i))return h;return Promise.resolve(a.transform(i.value,s)).then(o=>({status:t.value,value:o}))})}}x.assertNever(a)}};C.create=(r,e,t)=>{return new C({schema:r,typeName:d.ZodEffects,effect:e,..._(t)})};C.createWithPreprocess=(r,e,t)=>{return new C({schema:e,effect:{type:"preprocess",transform:r},typeName:d.ZodEffects,..._(t)})};var N=class extends v{_parse(e){const t=this._getType(e);if(t===f.undefined){return A(void 0)}return this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};N.create=(r,e)=>{return new N({innerType:r,typeName:d.ZodOptional,..._(e)})};var M=class extends v{_parse(e){const t=this._getType(e);if(t===f.null){return A(null)}return this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};M.create=(r,e)=>{return new M({innerType:r,typeName:d.ZodNullable,..._(e)})};var te=class extends v{_parse(e){const{ctx:t}=this._processInputParams(e);let n=t.data;if(t.parsedType===f.undefined){n=this._def.defaultValue()}return this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};te.create=(r,e)=>{return new te({innerType:r,typeName:d.ZodDefault,defaultValue:typeof e.default==="function"?e.default:()=>e.default,..._(e)})};var re=class extends v{_parse(e){const{ctx:t}=this._processInputParams(e);const n={...t,common:{...t.common,issues:[]}};const a=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});if(se(a)){return a.then(s=>{return{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new O(n.common.issues)},input:n.data})}})}else{return{status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new O(n.common.issues)},input:n.data})}}}removeCatch(){return this._def.innerType}};re.create=(r,e)=>{return new re({innerType:r,typeName:d.ZodCatch,catchValue:typeof e.catch==="function"?e.catch:()=>e.catch,..._(e)})};var he=class extends v{_parse(e){const t=this._getType(e);if(t!==f.nan){const n=this._getOrReturnCtx(e);l(n,{code:u.invalid_type,expected:f.nan,received:n.parsedType});return h}return{status:"valid",value:e.data}}};he.create=r=>{return new he({typeName:d.ZodNaN,..._(r)})};var _e=class extends v{_parse(e){const{ctx:t}=this._processInputParams(e);const n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}};var ve=class r extends v{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.common.async){const a=async()=>{const s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});if(s.status==="aborted")return h;if(s.status==="dirty"){t.dirty();return B(s.value)}else{return this._def.out._parseAsync({data:s.value,path:n.path,parent:n})}};return a()}else{const a=this._def.in._parseSync({data:n.data,path:n.path,parent:n});if(a.status==="aborted")return h;if(a.status==="dirty"){t.dirty();return{status:"dirty",value:a.value}}else{return this._def.out._parseSync({data:a.value,path:n.path,parent:n})}}}static create(e,t){return new r({in:e,out:t,typeName:d.ZodPipeline})}};var ne=class extends v{_parse(e){const t=this._def.innerType._parse(e);const n=a=>{if(F(a)){a.value=Object.freeze(a.value)}return a};return se(t)?t.then(a=>n(a)):n(t)}unwrap(){return this._def.innerType}};ne.create=(r,e)=>{return new ne({innerType:r,typeName:d.ZodReadonly,..._(e)})};var gr={object:S.lazycreate};var d;(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"})(d||(d={}));var _r=q.create;var vr=ie.create;var xr=he.create;var br=oe.create;var kr=ce.create;var wr=ue.create;var Ar=de.create;var Tr=J.create;var Or=H.create;var Sr=le.create;var Pr=L.create;var jr=R.create;var Nr=pe.create;var Cr=V.create;var Zr=S.create;var Dr=S.strictCreate;var Rr=Y.create;var Er=je.create;var Ir=G.create;var $r=$.create;var Mr=Ce.create;var zr=fe.create;var Lr=me.create;var Vr=Ze.create;var Fr=K.create;var Ur=Q.create;var Br=X.create;var Wr=ee.create;var qr=U.create;var Jr=C.create;var Hr=N.create;var Yr=M.create;var Gr=C.createWithPreprocess;var Kr=ve.create;var xe=(r,e)=>{let t=0;for(;t<r.length&&t<e.length;t++){if(r[t]!==e[t])break}return[(r.length-t).toString(),...e.slice(t)].join("/")};function k(r){if(r.target!=="openAi"){return{}}const e=[...r.basePath,r.definitionPath,r.openAiAnyTypeName];r.flags.hasReferencedOpenAiAnyType=true;return{$ref:r.$refStrategy==="relative"?xe(e,r.currentPath):e.join("/")}}function De(r,e,t,n){if(!n?.errorMessages)return;if(t){r.errorMessage={...r.errorMessage,[e]:t}}}function b(r,e,t,n,a){r[e]=t;De(r,e,n,a)}function We(r,e){const t={type:"array"};if(r.type?._def&&r.type?._def?.typeName!==d.ZodAny){t.items=y(r.type._def,{...e,currentPath:[...e.currentPath,"items"]})}if(r.minLength){b(t,"minItems",r.minLength.value,r.minLength.message,e)}if(r.maxLength){b(t,"maxItems",r.maxLength.value,r.maxLength.message,e)}if(r.exactLength){b(t,"minItems",r.exactLength.value,r.exactLength.message,e);b(t,"maxItems",r.exactLength.value,r.exactLength.message,e)}return t}function qe(r,e){const t={type:"integer",format:"int64"};if(!r.checks)return t;for(const n of r.checks){switch(n.kind){case"min":if(e.target==="jsonSchema7"){if(n.inclusive){b(t,"minimum",n.value,n.message,e)}else{b(t,"exclusiveMinimum",n.value,n.message,e)}}else{if(!n.inclusive){t.exclusiveMinimum=true}b(t,"minimum",n.value,n.message,e)}break;case"max":if(e.target==="jsonSchema7"){if(n.inclusive){b(t,"maximum",n.value,n.message,e)}else{b(t,"exclusiveMaximum",n.value,n.message,e)}}else{if(!n.inclusive){t.exclusiveMaximum=true}b(t,"maximum",n.value,n.message,e)}break;case"multipleOf":b(t,"multipleOf",n.value,n.message,e);break}}return t}function Je(){return{type:"boolean"}}function be(r,e){return y(r.type._def,e)}var He=(r,e)=>{return y(r.innerType._def,e)};function Re(r,e,t){const n=t??e.dateStrategy;if(Array.isArray(n)){return{anyOf:n.map((a,s)=>Re(r,e,a))}}switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return Bt(r,e)}}var Bt=(r,e)=>{const t={type:"integer",format:"unix-time"};if(e.target==="openApi3"){return t}for(const n of r.checks){switch(n.kind){case"min":b(t,"minimum",n.value,n.message,e);break;case"max":b(t,"maximum",n.value,n.message,e);break}}return t};function Ye(r,e){return{...y(r.innerType._def,e),default:r.defaultValue()}}function Ge(r,e){return e.effectStrategy==="input"?y(r.schema._def,e):k(e)}function Ke(r){return{type:"string",enum:Array.from(r.values)}}var Wt=r=>{if("type"in r&&r.type==="string")return false;return"allOf"in r};function Qe(r,e){const t=[y(r.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),y(r.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s);let n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:false}:void 0;const a=[];t.forEach(s=>{if(Wt(s)){a.push(...s.allOf);if(s.unevaluatedProperties===void 0){n=void 0}}else{let i=s;if("additionalProperties"in s&&s.additionalProperties===false){const{additionalProperties:o,...c}=s;i=c}else{n=void 0}a.push(i)}});return a.length?{allOf:a,...n}:void 0}function Xe(r,e){const t=typeof r.value;if(t!=="bigint"&&t!=="number"&&t!=="boolean"&&t!=="string"){return{type:Array.isArray(r.value)?"array":"object"}}if(e.target==="openApi3"){return{type:t==="bigint"?"integer":t,enum:[r.value]}}return{type:t==="bigint"?"integer":t,const:r.value}}var Ee=void 0;var Z={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>{if(Ee===void 0){Ee=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")}return Ee},uuid:/^[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}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([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])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function ke(r,e){const t={type:"string"};if(r.checks){for(const n of r.checks){switch(n.kind){case"min":b(t,"minLength",typeof t.minLength==="number"?Math.max(t.minLength,n.value):n.value,n.message,e);break;case"max":b(t,"maxLength",typeof t.maxLength==="number"?Math.min(t.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":D(t,"email",n.message,e);break;case"format:idn-email":D(t,"idn-email",n.message,e);break;case"pattern:zod":T(t,Z.email,n.message,e);break}break;case"url":D(t,"uri",n.message,e);break;case"uuid":D(t,"uuid",n.message,e);break;case"regex":T(t,n.regex,n.message,e);break;case"cuid":T(t,Z.cuid,n.message,e);break;case"cuid2":T(t,Z.cuid2,n.message,e);break;case"startsWith":T(t,RegExp(`^${Ie(n.value,e)}`),n.message,e);break;case"endsWith":T(t,RegExp(`${Ie(n.value,e)}$`),n.message,e);break;case"datetime":D(t,"date-time",n.message,e);break;case"date":D(t,"date",n.message,e);break;case"time":D(t,"time",n.message,e);break;case"duration":D(t,"duration",n.message,e);break;case"length":b(t,"minLength",typeof t.minLength==="number"?Math.max(t.minLength,n.value):n.value,n.message,e);b(t,"maxLength",typeof t.maxLength==="number"?Math.min(t.maxLength,n.value):n.value,n.message,e);break;case"includes":{T(t,RegExp(Ie(n.value,e)),n.message,e);break}case"ip":{if(n.version!=="v6"){D(t,"ipv4",n.message,e)}if(n.version!=="v4"){D(t,"ipv6",n.message,e)}break}case"base64url":T(t,Z.base64url,n.message,e);break;case"jwt":T(t,Z.jwt,n.message,e);break;case"cidr":{if(n.version!=="v6"){T(t,Z.ipv4Cidr,n.message,e)}if(n.version!=="v4"){T(t,Z.ipv6Cidr,n.message,e)}break}case"emoji":T(t,Z.emoji(),n.message,e);break;case"ulid":{T(t,Z.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{D(t,"binary",n.message,e);break}case"contentEncoding:base64":{b(t,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{T(t,Z.base64,n.message,e);break}}break}case"nanoid":{T(t,Z.nanoid,n.message,e)}case"toLowerCase":case"toUpperCase":case"trim":break;default:(a=>{})(n)}}}return t}function Ie(r,e){return e.patternStrategy==="escape"?Jt(r):r}var qt=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Jt(r){let e="";for(let t=0;t<r.length;t++){if(!qt.has(r[t])){e+="\\"}e+=r[t]}return e}function D(r,e,t,n){if(r.format||r.anyOf?.some(a=>a.format)){if(!r.anyOf){r.anyOf=[]}if(r.format){r.anyOf.push({format:r.format,...r.errorMessage&&n.errorMessages&&{errorMessage:{format:r.errorMessage.format}}});delete r.format;if(r.errorMessage){delete r.errorMessage.format;if(Object.keys(r.errorMessage).length===0){delete r.errorMessage}}}r.anyOf.push({format:e,...t&&n.errorMessages&&{errorMessage:{format:t}}})}else{b(r,"format",e,t,n)}}function T(r,e,t,n){if(r.pattern||r.allOf?.some(a=>a.pattern)){if(!r.allOf){r.allOf=[]}if(r.pattern){r.allOf.push({pattern:r.pattern,...r.errorMessage&&n.errorMessages&&{errorMessage:{pattern:r.errorMessage.pattern}}});delete r.pattern;if(r.errorMessage){delete r.errorMessage.pattern;if(Object.keys(r.errorMessage).length===0){delete r.errorMessage}}}r.allOf.push({pattern:et(e,n),...t&&n.errorMessages&&{errorMessage:{pattern:t}}})}else{b(r,"pattern",et(e,n),t,n)}}function et(r,e){if(!e.applyRegexFlags||!r.flags){return r.source}const t={i:r.flags.includes("i"),m:r.flags.includes("m"),s:r.flags.includes("s")};const n=t.i?r.source.toLowerCase():r.source;let a="";let s=false;let i=false;let o=false;for(let c=0;c<n.length;c++){if(s){a+=n[c];s=false;continue}if(t.i){if(i){if(n[c].match(/[a-z]/)){if(o){a+=n[c];a+=`${n[c-2]}-${n[c]}`.toUpperCase();o=false}else if(n[c+1]==="-"&&n[c+2]?.match(/[a-z]/)){a+=n[c];o=true}else{a+=`${n[c]}${n[c].toUpperCase()}`}continue}}else if(n[c].match(/[a-z]/)){a+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(t.m){if(n[c]==="^"){a+=`(^|(?<=[\r
3
+ ]))`;continue}else if(n[c]==="$"){a+=`($|(?=[\r
4
+ ]))`;continue}}if(t.s&&n[c]==="."){a+=i?`${n[c]}\r
5
+ `:`[${n[c]}\r
6
+ ]`;continue}a+=n[c];if(n[c]==="\\"){s=true}else if(i&&n[c]==="]"){i=false}else if(!i&&n[c]==="["){i=true}}try{new RegExp(a)}catch{console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`);return r.source}return a}function we(r,e){if(e.target==="openAi"){console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.")}if(e.target==="openApi3"&&r.keyType?._def.typeName===d.ZodEnum){return{type:"object",required:r.keyType._def.values,properties:r.keyType._def.values.reduce((n,a)=>({...n,[a]:y(r.valueType._def,{...e,currentPath:[...e.currentPath,"properties",a]})??k(e)}),{}),additionalProperties:e.rejectedAdditionalProperties}}const t={type:"object",additionalProperties:y(r.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3"){return t}if(r.keyType?._def.typeName===d.ZodString&&r.keyType._def.checks?.length){const{type:n,...a}=ke(r.keyType._def,e);return{...t,propertyNames:a}}else if(r.keyType?._def.typeName===d.ZodEnum){return{...t,propertyNames:{enum:r.keyType._def.values}}}else if(r.keyType?._def.typeName===d.ZodBranded&&r.keyType._def.type._def.typeName===d.ZodString&&r.keyType._def.type._def.checks?.length){const{type:n,...a}=be(r.keyType._def,e);return{...t,propertyNames:a}}return t}function tt(r,e){if(e.mapStrategy==="record"){return we(r,e)}const t=y(r.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||k(e);const n=y(r.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||k(e);return{type:"array",maxItems:125,items:{type:"array",items:[t,n],minItems:2,maxItems:2}}}function rt(r){const e=r.values;const t=Object.keys(r.values).filter(s=>{return typeof e[e[s]]!=="number"});const n=t.map(s=>e[s]);const a=Array.from(new Set(n.map(s=>typeof s)));return{type:a.length===1?a[0]==="string"?"string":"number":["string","number"],enum:n}}function nt(r){return r.target==="openAi"?void 0:{not:k({...r,currentPath:[...r.currentPath,"not"]})}}function at(r){return r.target==="openApi3"?{enum:["null"],nullable:true}:{type:"null"}}var ye={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function it(r,e){if(e.target==="openApi3")return st(r,e);const t=r.options instanceof Map?Array.from(r.options.values()):r.options;if(t.every(n=>n._def.typeName in ye&&(!n._def.checks||!n._def.checks.length))){const n=t.reduce((a,s)=>{const i=ye[s._def.typeName];return i&&!a.includes(i)?[...a,i]:a},[]);return{type:n.length>1?n:n[0]}}else if(t.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){const n=t.reduce((a,s)=>{const i=typeof s._def.value;switch(i){case"string":case"number":case"boolean":return[...a,i];case"bigint":return[...a,"integer"];case"object":if(s._def.value===null)return[...a,"null"];case"symbol":case"undefined":case"function":default:return a}},[]);if(n.length===t.length){const a=n.filter((s,i,o)=>o.indexOf(s)===i);return{type:a.length>1?a:a[0],enum:t.reduce((s,i)=>{return s.includes(i._def.value)?s:[...s,i._def.value]},[])}}}else if(t.every(n=>n._def.typeName==="ZodEnum")){return{type:"string",enum:t.reduce((n,a)=>[...n,...a._def.values.filter(s=>!n.includes(s))],[])}}return st(r,e)}var st=(r,e)=>{const t=(r.options instanceof Map?Array.from(r.options.values()):r.options).map((n,a)=>y(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${a}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n==="object"&&Object.keys(n).length>0));return t.length?{anyOf:t}:void 0};function ot(r,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(r.innerType._def.typeName)&&(!r.innerType._def.checks||!r.innerType._def.checks.length)){if(e.target==="openApi3"){return{type:ye[r.innerType._def.typeName],nullable:true}}return{type:[ye[r.innerType._def.typeName],"null"]}}if(e.target==="openApi3"){const n=y(r.innerType._def,{...e,currentPath:[...e.currentPath]});if(n&&"$ref"in n)return{allOf:[n],nullable:true};return n&&{...n,nullable:true}}const t=y(r.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return t&&{anyOf:[t,{type:"null"}]}}function ct(r,e){const t={type:"number"};if(!r.checks)return t;for(const n of r.checks){switch(n.kind){case"int":t.type="integer";De(t,"type",n.message,e);break;case"min":if(e.target==="jsonSchema7"){if(n.inclusive){b(t,"minimum",n.value,n.message,e)}else{b(t,"exclusiveMinimum",n.value,n.message,e)}}else{if(!n.inclusive){t.exclusiveMinimum=true}b(t,"minimum",n.value,n.message,e)}break;case"max":if(e.target==="jsonSchema7"){if(n.inclusive){b(t,"maximum",n.value,n.message,e)}else{b(t,"exclusiveMaximum",n.value,n.message,e)}}else{if(!n.inclusive){t.exclusiveMaximum=true}b(t,"maximum",n.value,n.message,e)}break;case"multipleOf":b(t,"multipleOf",n.value,n.message,e);break}}return t}function ut(r,e){const t=e.target==="openAi";const n={type:"object",properties:{}};const a=[];const s=r.shape();for(const o in s){let c=s[o];if(c===void 0||c._def===void 0){continue}let p=Yt(c);if(p&&t){if(c._def.typeName==="ZodOptional"){c=c._def.innerType}if(!c.isNullable()){c=c.nullable()}p=false}const g=y(c._def,{...e,currentPath:[...e.currentPath,"properties",o],propertyPath:[...e.currentPath,"properties",o]});if(g===void 0){continue}n.properties[o]=g;if(!p){a.push(o)}}if(a.length){n.required=a}const i=Ht(r,e);if(i!==void 0){n.additionalProperties=i}return n}function Ht(r,e){if(r.catchall._def.typeName!=="ZodNever"){return y(r.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})}switch(r.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function Yt(r){try{return r.isOptional()}catch{return true}}var dt=(r,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString()){return y(r.innerType._def,e)}const t=y(r.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return t?{anyOf:[{not:k(e)},t]}:k(e)};var lt=(r,e)=>{if(e.pipeStrategy==="input"){return y(r.in._def,e)}else if(e.pipeStrategy==="output"){return y(r.out._def,e)}const t=y(r.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]});const n=y(r.out._def,{...e,currentPath:[...e.currentPath,"allOf",t?"1":"0"]});return{allOf:[t,n].filter(a=>a!==void 0)}};function pt(r,e){return y(r.type._def,e)}function ft(r,e){const t=y(r.valueType._def,{...e,currentPath:[...e.currentPath,"items"]});const n={type:"array",uniqueItems:true,items:t};if(r.minSize){b(n,"minItems",r.minSize.value,r.minSize.message,e)}if(r.maxSize){b(n,"maxItems",r.maxSize.value,r.maxSize.message,e)}return n}function mt(r,e){if(r.rest){return{type:"array",minItems:r.items.length,items:r.items.map((t,n)=>y(t._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((t,n)=>n===void 0?t:[...t,n],[]),additionalItems:y(r.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}}else{return{type:"array",minItems:r.items.length,maxItems:r.items.length,items:r.items.map((t,n)=>y(t._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((t,n)=>n===void 0?t:[...t,n],[])}}}function ht(r){return{not:k(r)}}function yt(r){return k(r)}var gt=(r,e)=>{return y(r.innerType._def,e)};var _t=(r,e,t)=>{switch(e){case d.ZodString:return ke(r,t);case d.ZodNumber:return ct(r,t);case d.ZodObject:return ut(r,t);case d.ZodBigInt:return qe(r,t);case d.ZodBoolean:return Je();case d.ZodDate:return Re(r,t);case d.ZodUndefined:return ht(t);case d.ZodNull:return at(t);case d.ZodArray:return We(r,t);case d.ZodUnion:case d.ZodDiscriminatedUnion:return it(r,t);case d.ZodIntersection:return Qe(r,t);case d.ZodTuple:return mt(r,t);case d.ZodRecord:return we(r,t);case d.ZodLiteral:return Xe(r,t);case d.ZodEnum:return Ke(r);case d.ZodNativeEnum:return rt(r);case d.ZodNullable:return ot(r,t);case d.ZodOptional:return dt(r,t);case d.ZodMap:return tt(r,t);case d.ZodSet:return ft(r,t);case d.ZodLazy:return()=>r.getter()._def;case d.ZodPromise:return pt(r,t);case d.ZodNaN:case d.ZodNever:return nt(t);case d.ZodEffects:return Ge(r,t);case d.ZodAny:return k(t);case d.ZodUnknown:return yt(t);case d.ZodDefault:return Ye(r,t);case d.ZodBranded:return be(r,t);case d.ZodReadonly:return gt(r,t);case d.ZodCatch:return He(r,t);case d.ZodPipeline:return lt(r,t);case d.ZodFunction:case d.ZodVoid:case d.ZodSymbol:return void 0;default:return(n=>void 0)(e)}};function y(r,e,t=false){const n=e.seen.get(r);if(e.override){const o=e.override?.(r,e,n,t);if(o!==Me){return o}}if(n&&!t){const o=Gt(n,e);if(o!==void 0){return o}}const a={def:r,path:e.currentPath,jsonSchema:void 0};e.seen.set(r,a);const s=_t(r,r.typeName,e);const i=typeof s==="function"?y(s(),e):s;if(i){Kt(r,e,i)}if(e.postProcess){const o=e.postProcess(i,r,e);a.jsonSchema=i;return o}a.jsonSchema=i;return i}var Gt=(r,e)=>{switch(e.$refStrategy){case"root":return{$ref:r.path.join("/")};case"relative":return{$ref:xe(e.currentPath,r.path)};case"none":case"seen":{if(r.path.length<e.currentPath.length&&r.path.every((t,n)=>e.currentPath[n]===t)){console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`);return k(e)}return e.$refStrategy==="seen"?k(e):void 0}}};var Kt=(r,e,t)=>{if(r.description){t.description=r.description;if(e.markdownDescription){t.markdownDescription=r.description}}return t};var vt=r=>{const e=ze(r);const t=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:false},currentPath:t,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,a])=>[a._def,{def:a._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}};var Qt=(r,e)=>{const t=vt(e);let n=typeof e==="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[p,g])=>({...c,[p]:y(g._def,{...t,currentPath:[...t.basePath,t.definitionPath,p]},true)??k(t)}),{}):void 0;const a=typeof e==="string"?e:e?.nameStrategy==="title"?void 0:e?.name;const s=y(r._def,a===void 0?t:{...t,currentPath:[...t.basePath,t.definitionPath,a]},false)??k(t);const i=typeof e==="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;if(i!==void 0){s.title=i}if(t.flags.hasReferencedOpenAiAnyType){if(!n){n={}}if(!n[t.openAiAnyTypeName]){n[t.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:t.$refStrategy==="relative"?"1":[...t.basePath,t.definitionPath,t.openAiAnyTypeName].join("/")}}}}const o=a===void 0?n?{...s,[t.definitionPath]:n}:s:{$ref:[...t.$refStrategy==="relative"?[]:t.basePath,t.definitionPath,a].join("/"),[t.definitionPath]:{...n,[a]:s}};if(t.target==="jsonSchema7"){o.$schema="http://json-schema.org/draft-07/schema#"}else if(t.target==="jsonSchema2019-09"||t.target==="openAi"){o.$schema="https://json-schema.org/draft/2019-09/schema#"}if(t.target==="openAi"&&("anyOf"in o||"oneOf"in o||"allOf"in o||"type"in o&&Array.isArray(o.type))){console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.")}return o};export{Qt as a};