@microi.net/cli 5.3.5 → 5.3.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.codebuddy-plugin/marketplace.json +2 -2
- package/.codebuddy-plugin/plugin.json +1 -1
- package/.codex-plugin/plugin.json +1 -1
- package/.workbuddy-plugin/marketplace.json +2 -2
- package/.workbuddy-plugin/plugin.json +1 -1
- package/assets/build-meta.json +4 -4
- package/cordis.patch.yml +1 -1
- package/package.json +1 -1
- package/scripts/mcp-server.js +3 -3
- package/scripts/microi-skills.meta.json +188 -188
- package/skills/.microi-skills-version.json +2 -2
- package/skills/microi.v8.js +2 -2
- package/skills/ocr-engine/SKILL.md +3 -3
- package/skills/translate-engine/SKILL.md +1 -3
- package/skills/v8-security/references/progressive-02-7-/346/227/245/345/277/227/350/256/260/345/275/225.md +1 -1
- package/skills/workspace-conventions/SKILL.md +20 -2
package/scripts/mcp-server.js
CHANGED
|
@@ -95,7 +95,7 @@ data: ${n}
|
|
|
95
95
|
`),this._sseResponse=this.res,this.res.on("close",()=>{this._sseResponse=void 0,this.onclose?.()})}async handlePostMessage(e,r,n){if(!this._sseResponse){let p="SSE connection not established";throw r.writeHead(500).end(p),new Error(p)}let i=this.validateRequestHeaders(e);if(i){r.writeHead(403).end(i),this.onerror?.(new Error(i));return}let a=e.auth,o=e.headers.host,s=e.socket instanceof l_.TLSSocket?"https":"http",c=o&&e.url?new Xh.URL(e.url,`${s}://${o}`):void 0,l={headers:e.headers,url:c},u;try{let p=p_.default.parse(e.headers["content-type"]??"");if(p.type!=="application/json")throw new Error(`Unsupported content-type: ${p.type}`);u=n??await(0,u_.default)(e,{limit:dM,encoding:p.parameters.charset??"utf-8"})}catch(p){r.writeHead(400).end(String(p)),this.onerror?.(p);return}try{await this.handleMessage(typeof u=="string"?JSON.parse(u):u,{requestInfo:l,authInfo:a})}catch{r.writeHead(400).end(`Invalid message: ${u}`);return}r.writeHead(202).end("Accepted")}async handleMessage(e,r){let n;try{n=bl.parse(e)}catch(i){throw this.onerror?.(i),i}this.onmessage?.(n,r)}async close(){this._sseResponse?.end(),this._sseResponse=void 0,this.onclose?.()}async send(e){if(!this._sseResponse)throw new Error("Not connected");this._sseResponse.write(`event: message
|
|
96
96
|
data: ${JSON.stringify(e)}
|
|
97
97
|
|
|
98
|
-
`)}get sessionId(){return this._sessionId}};var Ad=Ne(j8(),1);var hn=Ne(require("node:crypto"),1),Ot=Ne(require("node:fs"),1),sp=Ne(require("node:http"),1),cp=Ne(require("node:https"),1),nP=Ne(require("node:os"),1),tc=Ne(require("node:path"),1),iP=require("node:stream"),aP=require("node:zlib");var O={LOGIN:"/api/SysUser/Login",REFRESH_TOKEN:"/api/SysUser/RefreshToken",LIST_USER_ACCESS_KEYS:"/api/SysUserAccessKey/List",CREATE_USER_ACCESS_KEY:"/api/SysUserAccessKey/Create",REVOKE_USER_ACCESS_KEY:"/api/SysUserAccessKey/Revoke",GET_STATUS:"/api/V8Engine/GetStatus",AI_CHAT:"/api/Ai/Chat",OCR_RECOGNIZE:"/
|
|
98
|
+
`)}get sessionId(){return this._sessionId}};var Ad=Ne(j8(),1);var hn=Ne(require("node:crypto"),1),Ot=Ne(require("node:fs"),1),sp=Ne(require("node:http"),1),cp=Ne(require("node:https"),1),nP=Ne(require("node:os"),1),tc=Ne(require("node:path"),1),iP=require("node:stream"),aP=require("node:zlib");var O={LOGIN:"/api/SysUser/Login",REFRESH_TOKEN:"/api/SysUser/RefreshToken",LIST_USER_ACCESS_KEYS:"/api/SysUserAccessKey/List",CREATE_USER_ACCESS_KEY:"/api/SysUserAccessKey/Create",REVOKE_USER_ACCESS_KEY:"/api/SysUserAccessKey/Revoke",GET_STATUS:"/api/V8Engine/GetStatus",AI_CHAT:"/api/Ai/Chat",OCR_RECOGNIZE:"/apiengine/platform-ocr-recognize",TRANSLATE_TEXT:"/apiengine/platform-translate-runtime",TRANSLATE_DETECT:"/apiengine/platform-translate-runtime",TRANSLATE_LANGUAGES:"/apiengine/platform-translate-runtime",TRANSLATE_FILE:"/apiengine/platform-translate-runtime",TRANSLATE_SUGGEST:"/apiengine/platform-translate-runtime",TRANSLATE_HEALTH:"/apiengine/platform-translate-runtime",TRANSITION_APPLICATION_STREAM_GATE:"/api/V8Engine/TransitionApplicationStreamGate",REDIS_STATISTICS:"/apiengine/platform-cache-manager",REDIS_KEYS:"/apiengine/platform-cache-manager",REDIS_KEY:"/apiengine/platform-cache-manager",REDIS_DELETE_KEYS:"/apiengine/platform-cache-manager",REDIS_REPLACE_VALUE:"/apiengine/platform-cache-manager",REDIS_RENAME_KEY:"/apiengine/platform-cache-manager",REDIS_SET_TTL:"/apiengine/platform-cache-manager",GET_DB_SCHEMA:"/api/V8Engine/GetDbSchema",GET_TABLE_INDEXES:"/api/V8Engine/GetTableIndexes",CREATE_TABLE_INDEX:"/api/V8Engine/CreateTableIndex",DROP_TABLE_INDEX:"/api/V8Engine/DropTableIndex",GET_SUPPORTED_DATABASE_TYPES:"/api/V8Engine/GetSupportedDatabaseTypes",INSPECT_EXTERNAL_DATABASE:"/api/V8Engine/InspectExternalDatabase",QUERY_EXTERNAL_DATABASE:"/api/V8Engine/QueryExternalDatabase",EXECUTE_EXTERNAL_DATABASE_SQL:"/api/V8Engine/ExecuteExternalDatabaseSql",SAVE_DATABASE_CONNECTION:"/api/V8Engine/SaveDatabaseConnection",IMPORT_EXTERNAL_ATTACHMENT:"/api/V8Engine/ImportExternalAttachment",GET_PLAYWRIGHT_CONTEXT:"/api/V8Engine/GetPlaywrightContext",GET_ENGINE_LIST:"/api/V8Engine/GetApiEngineList",GET_ENGINE_CODE:"/api/V8Engine/GetApiEngineCode",UPDATE_ENGINE_CODE:"/api/V8Engine/UpdateApiEngineCode",CREATE_ENGINE:"/api/V8Engine/CreateApiEngine",EXECUTE_ENGINE:"/api/V8Engine/ExecuteApiEngine",RUN_BACKGROUND_API_ENGINE:"/apiengine/platform-background-task",LIST_BACKGROUND_TASKS:"/apiengine/platform-background-task",CANCEL_BACKGROUND_TASK:"/apiengine/platform-background-task",UPLOAD_FILE_BASE64:"/api/V8Engine/UploadFileBase64",UPLOAD_APPLICATION_ASSET_STREAM:"/api/V8Engine/UploadApplicationAssetStream",INITIATE_APPLICATION_ASSET_MULTIPART:"/api/V8Engine/InitiateApplicationAssetMultipart",GET_APPLICATION_ASSET_MULTIPART_STATUS:"/api/V8Engine/GetApplicationAssetMultipartStatus",UPLOAD_APPLICATION_ASSET_MULTIPART_PART:"/api/V8Engine/UploadApplicationAssetMultipartPart",COMPLETE_APPLICATION_ASSET_MULTIPART:"/api/V8Engine/CompleteApplicationAssetMultipart",ABORT_APPLICATION_ASSET_MULTIPART:"/api/V8Engine/AbortApplicationAssetMultipart",FINALIZE_APPLICATION_STREAM_PUBLISH:"/api/V8Engine/FinalizeApplicationStreamPublish",LIST_APPLICATIONS:"/api/V8Engine/ListApplications",GET_APPLICATION_CONTEXT:"/api/V8Engine/GetApplicationContext",GET_APPLICATION_FILE:"/api/V8Engine/GetApplicationFile",GET_MICRO_SERVICE:"/api/V8Engine/GetMicroService",CREATE_MICRO_SERVICE:"/api/V8Engine/CreateMicroService",SYNC_MICRO_SERVICE_SOURCE:"/api/V8Engine/SyncMicroServiceSource",PUBLISH_MICRO_SERVICE:"/api/V8Engine/PublishMicroService",GET_EVENT_LIST:"/api/V8Engine/GetV8EventList",GET_EVENT_CODE:"/api/V8Engine/GetV8EventCode",UPDATE_EVENT_CODE:"/api/V8Engine/UpdateV8EventCode",GET_WORKFLOW_V8_EVENT_LIST:"/api/V8Engine/GetWorkflowV8EventList",GET_WORKFLOW_V8_EVENT_CODE:"/api/V8Engine/GetWorkflowV8EventCode",UPDATE_WORKFLOW_V8_EVENT_CODE:"/api/V8Engine/UpdateWorkflowV8EventCode",CREATE_TABLE:"/api/V8Engine/CreateTable",REPAIR_FIXED_AUDIT_FIELDS:"/api/DiyField/RepairFixedDiyFieldMetadata",ADD_FIELD:"/api/V8Engine/AddField",DELETE_FIELD:"/api/DiyField/DelDiyField",GET_FIELD_LIST:"/api/V8Engine/GetFieldList",UPDATE_FIELD:"/api/V8Engine/UpdateField",UPDATE_FIELD_LIST:"/api/V8Engine/UpdateFieldList",UPDATE_TABLE:"/api/V8Engine/UpdateTable",REFRESH_SCHEMA_CACHE:"/api/V8Engine/RefreshSchemaCache",SET_ENGINE_ANONYMOUS:"/api/V8Engine/SetEngineAnonymous",CREATE_MODULE:"/api/V8Engine/CreateModule",SET_ROLE_PERMISSION:"/api/V8Engine/SetRolePermission",LIST_ROLES:"/api/V8Engine/ListRoles",SAVE_ROLE:"/api/V8Engine/SaveRole",LIST_MODULES:"/api/V8Engine/ListModules",GET_MODULE:"/api/V8Engine/GetModule",UPDATE_MODULE:"/api/V8Engine/UpdateModule",LIST_DATA_SOURCES:"/api/V8Engine/ListDataSources",SAVE_DATA_SOURCE:"/api/V8Engine/SaveDataSource",LIST_PRINT_TEMPLATES:"/api/V8Engine/ListPrintTemplates",SAVE_PRINT_TEMPLATE:"/api/V8Engine/SavePrintTemplate",SAVE_WORKFLOW_PACKAGE:"/api/V8Engine/SaveWorkflowPackage",SAVE_JOB:"/api/V8Engine/SaveJob",LIST_DATABASE_BACKUP_TENANTS:"/api/V8Engine/ListDatabaseBackupTenants",RUN_DATABASE_BACKUP:"/api/V8Engine/RunDatabaseBackup",VALIDATE_LOW_CODE_SYSTEM:"/api/V8Engine/ValidateLowCodeSystem",WRITE_MCP_AUDIT_LOG:"/api/V8Engine/WriteMcpAuditLog",QUERY_MONGODB_LOGS:"/api/V8Engine/QueryMongodbLogs",WRITE_MONGODB_LOG:"/api/V8Engine/WriteMongodbLog",RUN_DATA_SOURCE:"/apiengine/platform-data-source-run",FORM_GET_TABLE_DATA:"/api/FormEngine/GetTableData",FORM_ADD_FORM_DATA:"/api/FormEngine/AddFormData",FORM_UPT_FORM_DATA:"/api/FormEngine/UptFormData",GET_PAGE_ENGINE_LIST:"/api/V8Engine/GetPageEngineList",GET_PAGE_ENGINE_DETAIL:"/api/V8Engine/GetPageEngineDetail",SAVE_PAGE_ENGINE:"/api/V8Engine/SavePageEngine",LIST_PAGE_ENGINE_HISTORY:"/api/V8Engine/ListPageEngineHistory",GET_PAGE_ENGINE_HISTORY:"/api/V8Engine/GetPageEngineHistory",COMPARE_PAGE_ENGINE_VERSIONS:"/api/V8Engine/ComparePageEngineVersions",EXPORT_PAGE_ENGINE:"/api/V8Engine/ExportPageEngine",ROLLBACK_PAGE_ENGINE:"/api/V8Engine/RollbackPageEngine",LIST_BLUEPRINTS:"/api/V8Engine/ListBlueprints",GET_BLUEPRINT:"/api/V8Engine/GetBlueprint",LIST_BLUEPRINT_HISTORY:"/api/V8Engine/ListBlueprintHistory",GET_BLUEPRINT_HISTORY:"/api/V8Engine/GetBlueprintHistory",COMPARE_BLUEPRINT_VERSIONS:"/api/V8Engine/CompareBlueprintVersions",EXPORT_BLUEPRINT:"/api/V8Engine/ExportBlueprint",SAVE_BLUEPRINT:"/api/V8Engine/SaveBlueprint",ROLLBACK_BLUEPRINT:"/api/V8Engine/RollbackBlueprint",DELETE_BLUEPRINT:"/api/V8Engine/DeleteBlueprint",VALIDATE_BLUEPRINT:"/api/V8Engine/ValidateBlueprint"};var q8=Ne(require("node:crypto"),1),V8=128,xV=/^[\x20-\x7E]+$/;function B8(t,e="Unknown"){let r=`MCP:${e||"Unknown"}`,n=String(t||r).trim()||"MCP:Unknown";if(n.length<=V8&&xV.test(n))return n;let i=q8.default.createHash("sha256").update(n,"utf8").digest("hex").slice(0,16),a=n.normalize("NFKD").replace(/[^\x20-\x7E]/g,"").replace(/[^A-Za-z0-9._:-]+/g,"-").replace(/-+/g,"-").replace(/^[-.:]+|[-.:]+$/g,"")||"MCP",o=V8-i.length-1;return`${a.slice(0,o)}-${i}`}var wV=/^Bearer\s+/i;function ar(t){return String(t||"").replace(wV,"").trim()}function _V(t){try{let r=ar(t).split(".");if(r.length<2)return;let n=r[1].replace(/-/g,"+").replace(/_/g,"/"),i=JSON.parse(Buffer.from(n,"base64").toString("utf8")),a=Number(i.exp);return Number.isFinite(a)&&a>0?a:void 0}catch{return}}function U8(t){try{let r=ar(t).split(".");if(r.length<2)return;let n=r[1].replace(/-/g,"+").replace(/_/g,"/"),i=JSON.parse(Buffer.from(n,"base64").toString("utf8")),a=Number(i.MicroiTokenIssuedAt??i.iat);return Number.isFinite(a)&&a>0?a:void 0}catch{return}}function SV(t,e){let r=ar(t),n=ar(e);if(!r)return n;if(!n||n===r)return r;let i=U8(r),a=U8(n);return i!==void 0&&a!==void 0?a>i?n:r:i===void 0&&a!==void 0?n:r}function np(t){return t.reduce((e,r)=>SV(e,r),"")}function J8(t,e=Math.floor(Date.now()/1e3),r=24*60*60){let n=_V(t);return n===void 0||n-e<=r}var EV=[{label:"tokens truncated",regex:/(?:\.\.\.|…)\s*[\d,.]+\s+tokens?\s+truncated\s*(?:\.\.\.|…)/i},{label:"Exit code",regex:/^\s*Exit code:\s*-?\d+\s*$/i},{label:"Process exited with code",regex:/^\s*Process exited with code\s+-?\d+\s*$/i},{label:"Chunk ID",regex:/^\s*Chunk ID:\s*\S+\s*$/i},{label:"Wall time",regex:/^\s*Wall time:\s*[\d.]+\s*(?:s|sec(?:ond)?s?)\s*$/i}];function Z8(t){let e=[];return String(t||"").replace(/\r\n/g,`
|
|
99
99
|
`).split(`
|
|
100
100
|
`).forEach((r,n)=>{for(let i of EV)if(i.regex.test(r)){e.push({line:n+1,marker:i.label});break}}),e}function Qs(t,e){let r=Z8(t);if(r.length===0)return;let n=r[0];throw new Error(`${e} \u5DF2\u62E6\u622A\uFF1A\u6E90\u7801\u7B2C ${n.line} \u884C\u5305\u542B AI/\u7EC8\u7AEF\u5DE5\u5177\u8F93\u51FA\u6807\u8BB0 "${n.marker}"\u3002 \u8FD9\u901A\u5E38\u8868\u793A\u5DE5\u5177\u7ED3\u679C\u88AB\u622A\u65AD\u6216\u547D\u4EE4\u5305\u88C5\u6587\u672C\u88AB\u8BEF\u5F53\u6210\u6E90\u7801\uFF1B\u8BF7\u4ECE\u672C\u5730\u5B8C\u6574\u6587\u4EF6\u6216\u5206\u6BB5\u8BFB\u53D6\u7ED3\u679C\u6062\u590D\u6E90\u7801\u540E\u518D\u4FDD\u5B58\u3002`)}function Ys(t,e,r="payload"){if(typeof t=="string"){let n=Z8(t);if(n.length>0){let a=n[0];throw new Error(`${e} \u5DF2\u62E6\u622A\uFF1A${r} \u7B2C ${a.line} \u884C\u5305\u542B AI/\u7EC8\u7AEF\u5DE5\u5177\u8F93\u51FA\u6807\u8BB0 "${a.marker}"\u3002 \u8BF7\u6062\u590D\u5B8C\u6574\u6E90\u7801\u540E\u518D\u63D0\u4EA4\u3002`)}let i=t.trim();if(i.startsWith("{")||i.startsWith("[")){let a;try{a=JSON.parse(i)}catch{}a&&typeof a=="object"&&Ys(a,e,`${r}(json)`)}return}if(Array.isArray(t)){t.forEach((n,i)=>Ys(n,e,`${r}[${i}]`));return}if(t&&typeof t=="object")for(let[n,i]of Object.entries(t))Ys(i,e,`${r}.${n}`)}var kV=/^\s*\*?\s*Version\s*:\s*(v\d+\.\d+\.\d+)\s*$/im,W8=/^v(\d+)\.(\d+)\.(\d+)$/;function ip(t){let e=(t||"").trim();if(!e)return null;let r=e.match(W8);if(r)return`v${Number(r[1])}.${Number(r[2])}.${Number(r[3])}`;let n=e.match(kV);return n?ip(n[1]):null}function G8(t){if(!t)return null;let e=t.match(W8);return e?{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3])}:null}function TV(t,e){return t.major!==e.major?t.major-e.major:t.minor!==e.minor?t.minor-e.minor:t.patch-e.patch}function CV(t){let e=null;for(let r of t){let n=G8(r);n&&(!e||TV(n,e)>0)&&(e=n)}return e?`v${e.major}.${e.minor}.${e.patch}`:null}function PV(t){let e=G8(t);if(!e)return"v1.0.0";let{major:r,minor:n,patch:i}=e;return i<9?`v${r}.${n}.${i+1}`:(i=0,n<9?`v${r}.${n+1}.${i}`:(n=0,r+=1,`v${r}.${n}.${i}`))}function AV(t){let e=(t||"").trim();return e?e.replace(/\r\n/g,`
|
|
101
101
|
`).split(`
|
|
@@ -123,7 +123,7 @@ Content-Type: application/octet-stream\r
|
|
|
123
123
|
`,"utf8"));let o=Buffer.concat(a),s=Buffer.from(`\r
|
|
124
124
|
--${n}--\r
|
|
125
125
|
`,"utf8"),c=Ot.default.statSync(e).size;async function*l(){yield o;let u=Ot.default.createReadStream(e),p=i==="gzip"?u.pipe((0,aP.createGzip)()):u;for await(let f of p)yield Buffer.isBuffer(f)?f:Buffer.from(f);yield s}return{body:iP.Readable.from(l()),contentLength:o.length+c+s.length}}async function KV(t,e,r){let n=hn.default.createHash("sha256");if(r>0){let i=Ot.default.createReadStream(t,{start:e,end:e+r-1});for await(let a of i)n.update(a)}return n.digest("hex")}function WV(t){return t.ProtocolVersion!==3?{}:{ProtocolVersion:3,PublishMode:"stage",ExpectedGateEpoch:String(t.ExpectedGateEpoch??""),RequestFingerprint:String(t.RequestFingerprint??""),DeliveryBatchId:String(t.DeliveryBatchId??""),SourceManifestHash:String(t.SourceManifestHash??""),RuntimeManifestHash:String(t.RuntimeManifestHash??""),RouteSnapshotJson:String(t.RouteSnapshotJson??""),RouteSnapshotHash:String(t.RouteSnapshotHash??""),ExpectedCurrentVersion:Number(t.ExpectedCurrentVersion),ExpectedAppVersion:t.ExpectedAppVersion??null,ExpectedPublishFence:String(t.ExpectedPublishFence??""),ExpectedPublishRowVersion:String(t.ExpectedPublishRowVersion??""),ExpectedVersionRowVersion:t.ExpectedVersionRowVersion??null,ExpectedActivePublishVersionId:t.ExpectedActivePublishVersionId??null,ExpectedCommittedPublishVersionId:t.ExpectedCommittedPublishVersionId??null}}function Jn(t){return String(t??"").replace(/\r\n/g,`
|
|
126
|
-
`).trim()}function Ky(t){return t?.V8Limit!==void 0&&t.V8Limit!==null?Number(t.V8Limit)===1?1:0:t?.V8Unlimited!==void 0&&t.V8Unlimited!==null?Number(t.V8Unlimited)===1?0:1:0}function Gy(t){if(Array.isArray(t))return t.map(Gy);if(!t||typeof t!="object")return t;let e=Object.entries(t).filter(([r])=>!r.startsWith("_")).sort(([r],[n])=>r.localeCompare(n));return Object.fromEntries(e.map(([r,n])=>[r,Gy(n)]))}function rP(t){try{let e=typeof t=="string"?JSON.parse(t):t;return JSON.stringify(Gy(e))}catch{return}}function GV(t,e){let r=new Set(["OsClient","ModuleId","Id"]),n=[];for(let[i,a]of Object.entries(t)){if(r.has(i)||a===void 0)continue;let o=e[i];if(HV.has(i)||i==="ViewSchema"){let s=rP(a),c=rP(o);(!s||!c||s!==c)&&n.push(i);continue}String(a??"")!==String(o??"")&&n.push(i)}return{matched:n.length===0,mismatches:n}}var rc=class{config;token="";refreshTimer;rsaPublicKey;did;requestTimeoutMs;writeRequestTimeoutMs;readbackRequestTimeoutMs;inflightRefresh;inflightAuthRecovery;inflightCredentialRecovery;constructor(e){this.config=e,this.reloadWorkspaceCredentials(),this.rsaPublicKey=e.rsaPublicKey||DV,this.did=B8(process.env.MICROI_MCP_DID,nP.default.hostname()),this.requestTimeoutMs=op(e.requestTimeoutMs??process.env.MICROI_MCP_HTTP_TIMEOUT_MS,LV),this.writeRequestTimeoutMs=op(e.writeRequestTimeoutMs??process.env.MICROI_MCP_WRITE_TIMEOUT_MS,jV),this.readbackRequestTimeoutMs=op(e.readbackRequestTimeoutMs??process.env.MICROI_MCP_READBACK_TIMEOUT_MS,VV),e.token&&(this.token=ar(e.token))}rsaEncrypt(e){let r=(this.rsaPublicKey||"").trim();return r?hn.default.publicEncrypt({key:r,padding:hn.default.constants.RSA_PKCS1_PADDING},Buffer.from(e,"utf-8")).toString("base64"):e}updateToken(e){this.token=ar(e)}async login(e){if(this.token){this.startAutoRefresh(),console.error("[microi-mcp] Using provided token (auto-refresh enabled)");return}if(this.reloadWorkspaceCredentials(),!this.config.username||!this.config.password)throw new Error("Login credentials are unavailable from environment or workspace protected storage");let r=this.rsaEncrypt(this.config.password),n=new URLSearchParams;n.append("Account",this.config.username),n.append("Pwd",r),this.config.osClient&&n.append("OsClient",this.config.osClient),n.append("_ClientType","MCP");let i=await fetch(`${this.config.apiBaseUrl}${O.LOGIN}`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",did:this.did,...this.config.osClient?{OsClient:this.config.osClient}:{}},body:n.toString()}),a=i.headers.get("authorization")||"",o=await i.text();if(!i.ok||!o)throw new Error(`Login failed: HTTP ${i.status} \u2014 ${o?.slice(0,200)||"empty response"}`);let s;try{s=JSON.parse(o)}catch{throw new Error(`Login failed: invalid JSON \u2014 ${o.slice(0,200)}`)}if(s.Code!==1)throw new Error(`Login failed: ${s.Msg||"Unknown error"}`);if(!a)throw new Error("Login succeeded but no token in response header");this.token=ar(a),this.startAutoRefresh(),console.error("[microi-mcp] Login successful")}startAutoRefresh(){this.refreshTimer&&clearInterval(this.refreshTimer),this.refreshTimer=setInterval(()=>{J8(this.token)&&this.refreshTokenNow().catch(e=>console.error("[microi-mcp] Token refresh failed:",e))},60*60*1e3)}async refreshTokenNow(){return this.inflightRefresh?this.inflightRefresh:this.token?(this.inflightRefresh=(async()=>{try{let e=await fetch(`${this.config.apiBaseUrl}${O.REFRESH_TOKEN}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`,did:this.did,...this.config.osClient?{OsClient:this.config.osClient}:{}},body:JSON.stringify({authorization:this.token,OsClient:this.config.osClient||void 0,_ClientType:"MCP"})}),r=e.headers.get("authorization"),n=await e.text(),i=null;try{i=JSON.parse(n)}catch{}return r&&i?.Code===1?(this.token=ar(r),this.writeTokenToFile(),console.error("[microi-mcp] Token refreshed"),!0):(console.error(`[microi-mcp] Refresh rejected: Code=${i?.Code} Msg=${i?.Msg||""}`),!1)}catch(e){return console.error("[microi-mcp] Refresh request error:",e),!1}finally{this.inflightRefresh=void 0}})(),this.inflightRefresh):!1}reloadTokenFromFile(){let e=this.config.tokenFilePath;if(!e)return!1;try{let r=JSON.parse(Ot.default.readFileSync(e,"utf-8")),n=lp(this.config.apiBaseUrl,this.config.osClient,this.config.osClientType,this.config.osClientNetwork),i=String(this.config.apiBaseUrl||"").replace(/\/+$/,""),a=this.config.osClient?n.filter(c=>c!==i):n,o=np(a.map(c=>r[c]))||r[i],s=ar(o);if(s&&s!==this.token)return this.token=s,!0}catch{}return!1}writeTokenToFile(){let e=this.config.tokenFilePath;if(!(!e||!this.token))try{let r={};try{r=JSON.parse(Ot.default.readFileSync(e,"utf-8"))}catch{}let[n]=lp(this.config.apiBaseUrl,this.config.osClient,this.config.osClientType,this.config.osClientNetwork);if(!n)return;r[n]=this.token;let i=tc.default.dirname(e);Ot.default.existsSync(i)||Ot.default.mkdirSync(i,{recursive:!0}),Ot.default.writeFileSync(e,JSON.stringify(r,null,2),{encoding:"utf-8",mode:384})}catch(r){console.error("[microi-mcp] Write token file failed:",r)}}async requestVsCodeCredentialRecovery(e){let r=this.config.authRecoveryRequestDir,n=this.config.tokenFilePath;if(!r||!n)return!1;try{Ot.default.existsSync(r)||Ot.default.mkdirSync(r,{recursive:!0});let i=this.config.apiBaseUrl.replace(/\/+$/,""),a=this.config.osClient||"",o=this.config.osClientType||"",s=this.config.osClientNetwork||"",c=`${i}|${a}|${o}|${s}`,u=`${hn.default.createHash("sha256").update(c).digest("hex").slice(0,24)}-${process.pid}-${Date.now()}-${hn.default.randomBytes(4).toString("hex")}.json`,p=tc.default.join(r,u),f=`${p}.${process.pid}.tmp`,h={version:1,apiBaseUrl:i,osClient:a,osClientType:o,osClientNetwork:s,requestedAt:Date.now(),failedTokenHash:hn.default.createHash("sha256").update(e||"").digest("hex")};Ot.default.writeFileSync(f,JSON.stringify(h),{encoding:"utf-8",mode:384}),Ot.default.renameSync(f,p);for(let m=0;m<40;m++)if(await new Promise(g=>setTimeout(g,250)),this.reloadTokenFromFile())return console.error("[microi-mcp] Token recovered by VS Code SecretStorage broker"),!0}catch(i){console.error("[microi-mcp] VS Code credential recovery request failed:",i)}return!1}async tryRecoverFromAuthFailure(e,r=!1){if(this.token&&e&&this.token!==e)return!0;if(r){if(this.inflightCredentialRecovery)return this.inflightCredentialRecovery;let n=this.inflightAuthRecovery;this.inflightCredentialRecovery=(async()=>(n&&await n,this.token&&e&&this.token!==e?!0:this.tryRecoverFromAuthFailureCore(e,!0)))();try{return await this.inflightCredentialRecovery}finally{this.inflightCredentialRecovery=void 0}}if(this.inflightCredentialRecovery)return this.inflightCredentialRecovery;if(this.inflightAuthRecovery)return this.inflightAuthRecovery;this.inflightAuthRecovery=this.tryRecoverFromAuthFailureCore(e,!1);try{return await this.inflightAuthRecovery}finally{this.inflightAuthRecovery=void 0}}async tryRecoverFromAuthFailureCore(e,r){if(this.token&&e&&this.token!==e)return!0;if(this.reloadTokenFromFile())return console.error("[microi-mcp] Token reloaded from file after auth failure"),!0;if(!r&&await this.refreshTokenNow())return!0;if(this.reloadWorkspaceCredentials(),this.config.username&&this.config.password)try{if(this.token="",await this.login(),this.token&&this.token!==e)return this.writeTokenToFile(),console.error("[microi-mcp] Re-logged in after auth failure"),!0}catch(n){this.token=e,console.error("[microi-mcp] Re-login failed:",n)}return this.requestVsCodeCredentialRecovery(e)}reloadWorkspaceCredentials(){let e=Q8({filePath:this.config.workspaceCredentialFilePath,usernameKey:this.config.workspaceCredentialUsernameKey,passwordKey:this.config.workspaceCredentialPasswordKey});return e?(this.config.username=e.username,this.config.password=e.password,!0):!1}async post(e,r,n={}){return this.requestJson("POST",e,r,void 0,"initial",n)}async get(e,r,n={}){return this.requestJson("GET",e,void 0,r,"initial",n)}async requestJson(e,r,n,i,a="initial",o={}){let s=`${this.config.apiBaseUrl}${r}`;if(e==="GET"&&i){let b=new URLSearchParams(i).toString();b&&(s+=`?${b}`)}let c=this.token,l={Authorization:`Bearer ${c}`,did:this.did};this.config.osClient&&(l.OsClient=this.config.osClient),e==="POST"&&(l["Content-Type"]="application/json");let u=op(o.timeoutMs,this.requestTimeoutMs,o.maxTimeoutMs),p=o.operationName||`${e} ${r}`,f=new AbortController,h=setTimeout(()=>f.abort(),u),m,g,y=e==="POST"?JSON.stringify(n??{}):void 0;try{let b=await fetch(s,{method:e,headers:l,signal:f.signal,...y!==void 0?{body:y}:{}});m=b,g=await b.text()}catch(b){if(f.signal.aborted)throw new gn(`${p} \u8BF7\u6C42\u8D85\u65F6\uFF08${u}ms\uFF09`,{kind:"timeout",requestPath:r,uncertainOutcome:e==="POST",cause:b});try{await new Promise(S=>setTimeout(S,250));let E=await this.requestJsonNative(e,s,l,y,u);m=E.res,g=E.text}catch(E){let S=b instanceof Error?b.message:String(b),T=E instanceof Error?E.message:String(E);throw new gn(`${p} \u7F51\u7EDC\u8BF7\u6C42\u5931\u8D25\uFF1Afetch=${S}\uFF1Bnative=${T}`,{kind:"network",requestPath:r,uncertainOutcome:e==="POST",cause:E})}}finally{clearTimeout(h)}let v=m.headers.get("authorization");if(v&&(this.token=ar(v),this.writeTokenToFile()),m.status===401&&a!=="credential-token"){let b=a!=="initial";if(b&&console.error("[microi-mcp] Replacement token was rejected; escalating to credential recovery"),await this.tryRecoverFromAuthFailure(c,b))return this.requestJson(e,r,n,i,Ya(a),o);throw new Error(`HTTP 401 Unauthorized \u2014 token recovery failed: ${g.slice(0,200)}`)}if(!m.ok)throw new Error(`HTTP ${m.status} ${m.statusText} \u2014 ${g.slice(0,200)}`);if(!g)throw new Error(`HTTP ${m.status} \u2014 empty response body`);let x;try{x=JSON.parse(g)}catch{throw new Error(`HTTP ${m.status} \u2014 invalid JSON: ${g.slice(0,200)}`)}if(Hy(x)&&a!=="credential-token"){console.error(`[microi-mcp] Auth expired (Code=${x.Code}: ${x.Msg||""}), attempting recovery...`);let b=a!=="initial";if(b&&console.error("[microi-mcp] Replacement token was rejected; escalating to credential recovery"),await this.tryRecoverFromAuthFailure(c,b))return this.requestJson(e,r,n,i,Ya(a),o)}return x}async requestMultipartFile(e,r,n,i,a="initial",o,s){let c=this.token,l=s==="gzip"?{...r,ContentEncoding:"gzip"}:r,u=`----microi-mcp-${hn.default.randomBytes(24).toString("hex")}`,p=tP(l,n,i,u,s),f=new AbortController,h=eP(o),m=setTimeout(()=>f.abort(),h),g,y;try{let b=await fetch(`${this.config.apiBaseUrl}${e}`,{method:"POST",headers:{Authorization:`Bearer ${c}`,did:this.did,...this.config.osClient?{OsClient:this.config.osClient}:{},"Content-Type":`multipart/form-data; boundary=${u}`},body:p.body,duplex:"half",signal:f.signal});g=b,y=await b.text()}catch(b){if(f.signal.aborted)throw new gn(`\u5E94\u7528\u8D44\u4EA7\u6D41\u5F0F\u4E0A\u4F20\u8D85\u65F6\uFF08${h}ms\uFF09`,{kind:"timeout",requestPath:e,uncertainOutcome:!0,cause:b});try{await new Promise(S=>setTimeout(S,250));let E=await this.requestMultipartFileNative(e,l,n,i,h,s);g=E.res,y=E.text}catch(E){let S=b instanceof Error?b.message:String(b),T=E instanceof Error?E.message:String(E);if(s!=="gzip")try{return await this.requestMultipartFile(e,r,n,i,a,o,"gzip")}catch(C){let $=C instanceof Error?C.message:String(C);throw new gn(`\u5E94\u7528\u8D44\u4EA7\u6D41\u5F0F\u4E0A\u4F20\u7F51\u7EDC\u5931\u8D25\uFF1Afetch=${S}\uFF1Bnative=${T}\uFF1Bgzip=${$}`,{kind:"network",requestPath:e,uncertainOutcome:!0,cause:C})}throw new gn(`\u5E94\u7528\u8D44\u4EA7 gzip \u6D41\u5F0F\u4E0A\u4F20\u7F51\u7EDC\u5931\u8D25\uFF1Afetch=${S}\uFF1Bnative=${T}`,{kind:"network",requestPath:e,uncertainOutcome:!0,cause:E})}}finally{clearTimeout(m),p.body.destroy()}let v=g.headers.get("authorization");if(v&&(this.token=ar(v),this.writeTokenToFile()),g.status===401&&a!=="credential-token"){let b=a!=="initial";if(b&&console.error("[microi-mcp] Replacement token was rejected; escalating to credential recovery"),await this.tryRecoverFromAuthFailure(c,b))return this.requestMultipartFile(e,r,n,i,Ya(a),o,s);throw new Error(`HTTP 401 Unauthorized \u2014 token recovery failed: ${y.slice(0,200)}`)}if(!g.ok)throw new Error(`HTTP ${g.status} ${g.statusText} \u2014 ${y.slice(0,200)}`);if(!y)throw new Error(`HTTP ${g.status} \u2014 empty response body`);let x;try{x=JSON.parse(y)}catch{throw new Error(`HTTP ${g.status} \u2014 invalid JSON: ${y.slice(0,200)}`)}if(Hy(x)&&a!=="credential-token"){let b=a!=="initial";if(b&&console.error("[microi-mcp] Replacement token was rejected; escalating to credential recovery"),await this.tryRecoverFromAuthFailure(c,b))return this.requestMultipartFile(e,r,n,i,Ya(a),o,s)}return x}async requestJsonNative(e,r,n,i,a){let o=new URL(r),s=o.protocol==="https:"?cp.default:sp.default,c=i===void 0?void 0:Buffer.from(i,"utf8");return new Promise((l,u)=>{let p=!1,f=m=>{p||(p=!0,u(m))},h=s.request({protocol:o.protocol,hostname:o.hostname,port:o.port||void 0,path:`${o.pathname}${o.search}`,method:e,timeout:a,headers:{...n,...c?{"Content-Length":String(c.length)}:{}}},m=>{let g=[];m.on("data",y=>g.push(Buffer.isBuffer(y)?y:Buffer.from(y))),m.on("end",()=>{if(p)return;p=!0;let y=m.statusCode||0,v={get(x){let b=m.headers[x.toLowerCase()];return Array.isArray(b)?b.join(", "):b===void 0?null:String(b)}};l({res:{status:y,statusText:m.statusMessage||"",ok:y>=200&&y<300,headers:v},text:Buffer.concat(g).toString("utf8")})})});h.on("error",m=>f(new Error(m.message,{cause:m}))),h.on("timeout",()=>{h.destroy(),f(new Error(`native request timeout (${a}ms)`))}),c&&h.write(c),h.end()})}async requestMultipartFileNative(e,r,n,i,a,o){let s=`----microi-mcp-native-${hn.default.randomBytes(24).toString("hex")}`,c=tP(r,n,i,s,o),l=new URL(`${this.config.apiBaseUrl}${e}`),u=l.protocol==="https:"?cp.default:sp.default;try{return await new Promise((p,f)=>{let h=!1,m=y=>{h||(h=!0,f(y))},g=u.request({protocol:l.protocol,hostname:l.hostname,port:l.port||void 0,path:`${l.pathname}${l.search}`,method:"POST",timeout:a,headers:{Authorization:`Bearer ${this.token}`,did:this.did,...this.config.osClient?{OsClient:this.config.osClient}:{},"Content-Type":`multipart/form-data; boundary=${s}`}},y=>{let v=[];y.on("data",x=>v.push(Buffer.isBuffer(x)?x:Buffer.from(x))),y.on("end",()=>{if(h)return;h=!0;let x=y.statusCode||0,b={get(_){let E=y.headers[_.toLowerCase()];return Array.isArray(E)?E.join(", "):E===void 0?null:String(E)}};p({res:{status:x,statusText:y.statusMessage||"",ok:x>=200&&x<300,headers:b},text:Buffer.concat(v).toString("utf8")})})});g.on("error",y=>m(new Error(y.message,{cause:y}))),g.on("timeout",()=>{g.destroy(),m(new Error(`native request timeout (${a}ms)`))}),c.body.on("error",y=>{g.destroy(),m(new Error(`local asset stream failed: ${y.message}`,{cause:y}))}),c.body.pipe(g)})}finally{c.body.destroy()}}async requestBinaryFileRange(e,r,n,i,a,o="initial",s){if(!Number.isSafeInteger(i)||i<0||!Number.isSafeInteger(a)||a<0)throw new Error("\u65AD\u70B9\u5206\u7247 start/length \u5FC5\u987B\u662F\u975E\u8D1F JavaScript \u5B89\u5168\u6574\u6570");let c=new URL(`${this.config.apiBaseUrl}${e}`);for(let[g,y]of Object.entries(r))c.searchParams.set(g,y);let l=this.token,u=eP(s),p=c.protocol==="https:"?cp.default:sp.default,f=await new Promise((g,y)=>{let v=!1,x=E=>{v||(v=!0,y(E))},b=p.request({protocol:c.protocol,hostname:c.hostname,port:c.port||void 0,path:`${c.pathname}${c.search}`,method:"POST",timeout:u,headers:{Authorization:`Bearer ${l}`,did:this.did,...this.config.osClient?{OsClient:this.config.osClient}:{},"Content-Type":"application/octet-stream","Content-Length":String(a)}},E=>{let S=[];E.on("data",T=>S.push(Buffer.isBuffer(T)?T:Buffer.from(T))),E.on("end",()=>{if(v)return;v=!0;let T=E.statusCode||0,C={get($){let P=E.headers[$.toLowerCase()];return Array.isArray(P)?P.join(", "):P===void 0?null:String(P)}};g({status:T,statusText:E.statusMessage||"",headers:C,text:Buffer.concat(S).toString("utf8")})})});if(b.on("error",E=>x(new Error(E.message,{cause:E}))),b.on("timeout",()=>{b.destroy(),x(new Error(`\u65AD\u70B9\u5206\u7247\u7F51\u7EDC\u8D85\u65F6\uFF08${u}ms\uFF09`))}),a===0){b.end();return}let _=Ot.default.createReadStream(n,{start:i,end:i+a-1});_.on("error",E=>{b.destroy(),x(new Error(`\u8BFB\u53D6\u672C\u5730\u5206\u7247\u5931\u8D25\uFF1A${E.message}`,{cause:E}))}),_.pipe(b)}).catch(g=>{throw new gn(`\u65AD\u70B9\u5206\u7247\u4E0A\u4F20\u7F51\u7EDC\u5931\u8D25\uFF1A${g instanceof Error?g.message:String(g)}`,{kind:/超时/u.test(String(g))?"timeout":"network",requestPath:e,uncertainOutcome:!0,cause:g})}),h=f.headers.get("authorization");if(h&&(this.token=ar(h),this.writeTokenToFile()),f.status===401&&o!=="credential-token"){let g=o!=="initial";if(await this.tryRecoverFromAuthFailure(l,g))return this.requestBinaryFileRange(e,r,n,i,a,Ya(o),s);throw new Error(`HTTP 401 Unauthorized \u2014 token recovery failed: ${f.text.slice(0,200)}`)}if(f.status<200||f.status>=300)throw new Error(`HTTP ${f.status} ${f.statusText} \u2014 ${f.text.slice(0,200)}`);if(!f.text)throw new Error(`HTTP ${f.status} \u2014 empty response body`);let m;try{m=JSON.parse(f.text)}catch{throw new Error(`HTTP ${f.status} \u2014 invalid JSON: ${f.text.slice(0,200)}`)}if(Hy(m)&&o!=="credential-token"){let g=o!=="initial";if(await this.tryRecoverFromAuthFailure(l,g))return this.requestBinaryFileRange(e,r,n,i,a,Ya(o),s)}return m}isUncertainWriteError(e){return e instanceof gn&&e.uncertainOutcome}readbackOptions(e){return{timeoutMs:this.readbackRequestTimeoutMs,operationName:e}}async pollReadback(e,r){let n,i="";for(let a of qV){a>0&&await new Promise(o=>setTimeout(o,a));try{let o=await e();if(n=o,o.Code===1&&r(o.Data))return{matched:!0,response:o};i=o.Msg||`\u56DE\u8BFB Code=${o.Code}`}catch(o){i=o instanceof Error?o.message:String(o)}}return{matched:!1,response:n,lastError:i}}recoveredWriteResult(e,r,n={}){return{Code:1,Data:{...n,RecoveredAfterTransportError:!0,Verification:"readback",TransportError:r.message},Msg:`${e} \u7684\u5BA2\u6237\u7AEF\u54CD\u5E94\u5F02\u5E38\uFF0C\u4F46\u5DF2\u901A\u8FC7\u8FDC\u7AEF\u56DE\u8BFB\u786E\u8BA4\u5199\u5165\u6210\u529F\u3002`}}uncertainWriteFailure(e,r,n){return new Error(`${e} \u7684\u5BA2\u6237\u7AEF\u54CD\u5E94\u5F02\u5E38\uFF0C\u4E14\u56DE\u8BFB\u672A\u80FD\u786E\u8BA4\u5199\u5165\u7ED3\u679C\u3002\u539F\u59CB\u9519\u8BEF\uFF1A${r.message}${n?`\uFF1B\u56DE\u8BFB\u7ED3\u679C\uFF1A${n}`:""}\u3002\u8BF7\u7EE7\u7EED\u4F7F\u7528\u5BF9\u5E94\u7684\u6807\u51C6 MCP \u83B7\u53D6\u5DE5\u5177\u56DE\u8BFB\u540E\u518D\u51B3\u5B9A\u662F\u5426\u91CD\u8BD5\uFF1B\u4E0D\u8981\u6539\u8D70\u539F\u751F FormEngine\u3001\u76F4\u63A5 SQL \u6216\u4E34\u65F6\u7EF4\u62A4\u63A5\u53E3\u5F15\u64CE\u3002`,{cause:r})}async getStatus(){return this.get(O.GET_STATUS)}async transitionApplicationStreamGate(e){return this.post(O.TRANSITION_APPLICATION_STREAM_GATE,e,{timeoutMs:this.writeRequestTimeoutMs,operationName:`transition application stream gate ${e.TransitionId}`})}async listMyUserAccessKeys(){return this.post(O.LIST_USER_ACCESS_KEYS,{})}async createMyUserAccessKey(e){return this.post(O.CREATE_USER_ACCESS_KEY,{Name:e.name,Scopes:e.scopes,AllowedRoutes:e.allowedRoutes,RedirectPath:e.redirectPath,AllowedTableNames:e.allowedTableNames,AllowedApiEngineKeys:e.allowedApiEngineKeys,AllowedDataSourceKeys:e.allowedDataSourceKeys,ExpiresAt:e.expiresAt,Remark:e.remark,Permanent:!1},{timeoutMs:this.writeRequestTimeoutMs,operationName:`\u521B\u5EFA\u5F53\u524D\u7528\u6237\u8BBF\u95EE\u5BC6\u94A5 ${e.name}`})}async revokeMyUserAccessKey(e){return this.post(O.REVOKE_USER_ACCESS_KEY,{Id:e},{timeoutMs:this.writeRequestTimeoutMs,operationName:`\u540A\u9500\u5F53\u524D\u7528\u6237\u8BBF\u95EE\u5BC6\u94A5 ${e}`})}async getDbSchema(){return this.post(O.GET_DB_SCHEMA,{OsClient:this.config.osClient})}async getTableIndexes(e,r=!1){return this.post(O.GET_TABLE_INDEXES,{OsClient:this.config.osClient,TableName:e},r?this.readbackOptions(`\u56DE\u8BFB\u8868 ${e} \u7D22\u5F15`):{})}async createTableIndex(e){let r={OsClient:this.config.osClient,...e};try{return await this.post(O.CREATE_TABLE_INDEX,r,{timeoutMs:this.writeRequestTimeoutMs,operationName:`\u521B\u5EFA\u7D22\u5F15 ${e.IndexName||`${e.TableName}:${e.Columns.join(",")}`}`})}catch(n){if(!this.isUncertainWriteError(n))throw n;let i=await this.pollReadback(()=>this.getTableIndexes(e.TableName,!0),a=>a.some(o=>{let s=e.IndexName?String(o.Key_name||o.Name||"").toLowerCase()===e.IndexName.toLowerCase():!0,c=o.Columns?.length?o.Columns:String(o.Column_name||"").split(",").map(u=>u.trim()).filter(Boolean),l=o.IsUnique??Number(o.Non_unique)===0;return s&&l===!!e.Unique&&c.length===e.Columns.length&&c.every((u,p)=>u.toLowerCase()===e.Columns[p].toLowerCase())}));if(i.matched)return this.recoveredWriteResult("\u521B\u5EFA\u6570\u636E\u5E93\u7D22\u5F15",n,{TableName:e.TableName,IndexName:e.IndexName,Columns:e.Columns});throw this.uncertainWriteFailure("\u521B\u5EFA\u6570\u636E\u5E93\u7D22\u5F15",n,i.lastError)}}async dropTableIndex(e,r){try{return await this.post(O.DROP_TABLE_INDEX,{OsClient:this.config.osClient,TableName:e,IndexName:r},{timeoutMs:this.writeRequestTimeoutMs,operationName:`\u5220\u9664\u7D22\u5F15 ${r}`})}catch(n){if(!this.isUncertainWriteError(n))throw n;let i=await this.pollReadback(()=>this.getTableIndexes(e,!0),a=>!a.some(o=>String(o.Key_name||o.Name||"").toLowerCase()===r.toLowerCase()));if(i.matched)return this.recoveredWriteResult("\u5220\u9664\u6570\u636E\u5E93\u7D22\u5F15",n,{TableName:e,IndexName:r});throw this.uncertainWriteFailure("\u5220\u9664\u6570\u636E\u5E93\u7D22\u5F15",n,i.lastError)}}async getSupportedDatabaseTypes(){return this.post(O.GET_SUPPORTED_DATABASE_TYPES,{})}async inspectExternalDatabase(e){return this.post(O.INSPECT_EXTERNAL_DATABASE,{OsClient:this.config.osClient,...e})}async queryExternalDatabase(e){return this.post(O.QUERY_EXTERNAL_DATABASE,{OsClient:this.config.osClient,...e})}async executeExternalDatabaseSql(e){let r=Number(e.CommandTimeoutSeconds||0),n=Number.isFinite(r)&&r>0?(r+30)*1e3:63e4;return this.post(O.EXECUTE_EXTERNAL_DATABASE_SQL,{OsClient:this.config.osClient,...e},{timeoutMs:Math.max(this.config.requestTimeoutMs??12e4,this.config.writeRequestTimeoutMs??6e4,n),operationName:"execute external database sql"})}async saveDatabaseConnection(e){return this.post(O.SAVE_DATABASE_CONNECTION,{OsClient:this.config.osClient,...e},{timeoutMs:this.config.writeRequestTimeoutMs,operationName:"save database connection"})}async importExternalAttachment(e){let r=Number(e.TimeoutSeconds||0),n=Number.isFinite(r)&&r>0?(r+30)*1e3:363e4;return this.post(O.IMPORT_EXTERNAL_ATTACHMENT,{OsClient:this.config.osClient,...e},{timeoutMs:Math.max(this.config.requestTimeoutMs??12e4,this.config.writeRequestTimeoutMs??6e4,n),operationName:"import external attachment"})}async getPlaywrightContext(e,r){return this.post(O.GET_PLAYWRIGHT_CONTEXT,{OsClient:this.config.osClient,...e?{Keyword:e}:{},...r?{PageSize:r}:{}})}async getEngineList(e){return this.post(O.GET_ENGINE_LIST,{OsClient:this.config.osClient,...e?{_SearchKey:e}:{}})}async getEngineCode(e,r={}){return this.post(O.GET_ENGINE_CODE,{OsClient:this.config.osClient,ApiEngineKey:e},r)}async executeEngine(e,r){return this.post(O.EXECUTE_ENGINE,{OsClient:this.config.osClient,ApiEngineKey:e,Param:r||{}})}async chat(e){return this.post(O.AI_CHAT,{UserChatMsg:e.question,AiModel:e.aiModel,...e.systemPrompt?{SystemChatMsg:e.systemPrompt}:{},...e.aiModelId?{AiModelId:e.aiModelId}:{},...e.relayModel?{RelayModel:e.relayModel}:{},...e.conversationId?{ConversationId:e.conversationId}:{},...e.reasoningEffort?{ReasoningEffort:e.reasoningEffort}:{},...e.mode?{Mode:e.mode}:{},OsClient:this.config.osClient},{timeoutMs:Math.max(this.config.requestTimeoutMs??12e4,33e4),operationName:"Microi AI chat"})}async recognizeOcr(e){return this.post(O.OCR_RECOGNIZE,e,{timeoutMs:ZV,operationName:`OCR recognize ${e.FileName||"unnamed file"}`})}async translateText(e){return this.post(O.TRANSLATE_TEXT,e,{timeoutMs:Qa,operationName:"translate text"})}async detectLanguage(e){return this.post(O.TRANSLATE_DETECT,{SourceText:e},{timeoutMs:Qa,operationName:"detect language"})}async listTranslateLanguages(){return this.post(O.TRANSLATE_LANGUAGES,{},{timeoutMs:Qa,operationName:"list translation languages"})}async translateFile(e){return this.post(O.TRANSLATE_FILE,e,{timeoutMs:Qa,operationName:`translate file ${e.FileName}`})}async suggestTranslation(e){return this.post(O.TRANSLATE_SUGGEST,e,{timeoutMs:Qa,operationName:"suggest translation"})}async getTranslateHealth(){return this.post(O.TRANSLATE_HEALTH,{},{timeoutMs:Qa,operationName:"translation health"})}async saveEngineCode(e,r,n){Qs(r,`\u4FDD\u5B58\u63A5\u53E3\u5F15\u64CE ${e}`);let i;try{let p=await this.getEngineCode(e);i=p.Code===1?p.Data:void 0}catch{i=void 0}let a=Jn(i?.ApiV8Code||i?.Code),o=Jn(r);if(a.length>=8e3&&o.length<a.length*.85&&!n?.confirmLargeReduction)throw new Error(`\u4FDD\u5B58\u63A5\u53E3\u5F15\u64CE ${e} \u5DF2\u62E6\u622A\uFF1A\u65B0\u6E90\u7801 ${o.length} \u5B57\u7B26\uFF0C\u8FDC\u7AEF\u6E90\u7801 ${a.length} \u5B57\u7B26\uFF0C\u51CF\u5C11\u8D85\u8FC7 15%\u3002\u8FD9\u53EF\u80FD\u662F\u957F\u5DE5\u5177\u7ED3\u679C\u88AB\u622A\u65AD\uFF1B\u786E\u8BA4\u786E\u9700\u5927\u5E45\u5220\u51CF\u65F6\u8BF7\u4F20 confirmLargeReduction="${e}"\u3002`);let s=ec({kind:"ApiEngine",key:e,currentCode:r,remoteCode:i?.ApiV8Code||i?.Code,remoteVersion:i?.Version,functionDescription:n?.functionDescription,changeSummary:n?.changeSummary||`\u4FDD\u5B58\u63A5\u53E3\u5F15\u64CE ${e}`}),c=n?.v8Limit??(n?.v8Unlimited===void 0?void 0:!n.v8Unlimited),l={OsClient:this.config.osClient,ApiEngineKey:e,ApiV8CodeBase64:Buffer.from(s.code,"utf8").toString("base64"),Version:s.version,ChangeSummary:s.changeHistory,...c===void 0?{}:{V8Limit:c?1:0},...n?.responseType===void 0?{}:{ResponseType:n.responseType}},u=p=>Jn(p?.ApiV8Code||p?.Code)===Jn(s.code)&&(c===void 0||Ky(p)===(c?1:0))&&(n?.responseType===void 0||String(p?.ResponseType||"JSON").toLowerCase()===n.responseType.toLowerCase());try{let p=await this.post(O.UPDATE_ENGINE_CODE,l,{timeoutMs:this.writeRequestTimeoutMs,operationName:`\u4FDD\u5B58\u63A5\u53E3\u5F15\u64CE ${e}`});if(p.Code!==1||c===void 0&&n?.responseType===void 0)return p;let f=await this.pollReadback(()=>this.getEngineCode(e,this.readbackOptions(`\u56DE\u8BFB\u63A5\u53E3\u5F15\u64CE ${e} V8Limit`)),u);return f.matched?{...p,Data:{...p.Data&&typeof p.Data=="object"?p.Data:{},ApiEngineKey:e,...c===void 0?{}:{V8Limit:c?1:0},...n?.responseType===void 0?{}:{ResponseType:n.responseType},Verified:!0,Verification:"readback"}}:{Code:0,Data:{ApiEngineKey:e,UpdateResponse:p.Data},Msg:`\u4FDD\u5B58\u63A5\u53E3\u5F15\u64CE ${e} \u8FD4\u56DE\u6210\u529F\uFF0C\u4F46\u8FD0\u884C\u914D\u7F6E\u5199\u540E\u56DE\u8BFB\u4E0D\u4E00\u81F4\uFF1A${f.lastError||"\u4EE3\u7801\u6216\u914D\u7F6E\u4E0D\u4E00\u81F4"}`}}catch(p){if(!this.isUncertainWriteError(p))throw p;let f=await this.pollReadback(()=>this.getEngineCode(e,this.readbackOptions(`\u56DE\u8BFB\u63A5\u53E3\u5F15\u64CE ${e}`)),u);if(f.matched)return this.recoveredWriteResult(`\u4FDD\u5B58\u63A5\u53E3\u5F15\u64CE ${e}`,p,{ApiEngineKey:e,Version:s.version});throw this.uncertainWriteFailure(`\u4FDD\u5B58\u63A5\u53E3\u5F15\u64CE ${e}`,p,f.lastError)}}async updateEngineRuntimeLimit(e,r){let n={OsClient:this.config.osClient,ApiEngineKey:e,V8Limit:r?1:0},i=()=>this.pollReadback(()=>this.getEngineCode(e,this.readbackOptions(`\u56DE\u8BFB\u63A5\u53E3\u5F15\u64CE ${e} V8Limit`)),o=>Ky(o)===(r?1:0)),a=`\u66F4\u65B0\u63A5\u53E3\u5F15\u64CE ${e} V8Limit`;try{let o=await this.post(O.UPDATE_ENGINE_CODE,n,{timeoutMs:this.writeRequestTimeoutMs,operationName:a});if(o.Code!==1)return o;let s=await i();return s.matched?{...o,Data:{...o.Data&&typeof o.Data=="object"?o.Data:{},ApiEngineKey:e,V8Limit:r?1:0,Verified:!0,Verification:"readback"}}:{Code:0,Data:{ApiEngineKey:e,UpdateResponse:o.Data},Msg:`${a} \u63A5\u53E3\u8FD4\u56DE\u6210\u529F\uFF0C\u4F46\u8FDC\u7AEF\u5199\u540E\u56DE\u8BFB\u4E0D\u4E00\u81F4\uFF1A${s.lastError||"\u914D\u7F6E\u4E0D\u4E00\u81F4"}`}}catch(o){if(!this.isUncertainWriteError(o))throw o;let s=await i();if(s.matched)return this.recoveredWriteResult(a,o,{ApiEngineKey:e,V8Limit:r?1:0,Verified:!0});throw this.uncertainWriteFailure(a,o,s.lastError)}}async updateEngineRuntimeConfig(e,r){return this.updateEngineRuntimeLimit(e,!r)}async createEngine(e){let r={OsClient:this.config.osClient,...e};r.V8Limit===void 0&&r.V8Unlimited!==void 0&&(r.V8Limit=Number(r.V8Unlimited)===1?0:1),delete r.V8Unlimited;let n=typeof r.Code=="string"?r.Code:typeof r.ApiV8Code=="string"?r.ApiV8Code:"";Qs(n,`\u521B\u5EFA\u63A5\u53E3\u5F15\u64CE ${e.ApiEngineKey}`);let i=ec({kind:"ApiEngine",key:e.ApiEngineKey,currentCode:n,functionDescription:r.functionDescription,changeSummary:r.changeSummary||`\u521B\u5EFA\u63A5\u53E3\u5F15\u64CE ${e.ApiEngineKey}`,initial:!0});r.ApiV8CodeBase64=Buffer.from(i.code,"utf8").toString("base64"),r.Version=i.version,r.ChangeSummary=i.changeHistory,delete r.Code,delete r.ApiV8Code,delete r.functionDescription,delete r.changeSummary,(!r.ApiAddress||r.ApiAddress.trim().length===0)&&(r.ApiAddress=`/apiengine/${e.ApiEngineKey}`),r.IsEnable=r.IsEnable??1,r.StopHttp=r.StopHttp??0,r.AllowAnonymous=r.AllowAnonymous??0;let a=`\u521B\u5EFA\u63A5\u53E3\u5F15\u64CE ${e.ApiEngineKey}`,o=()=>this.pollReadback(()=>this.getEngineCode(e.ApiEngineKey,this.readbackOptions(`\u56DE\u8BFB\u65B0\u5EFA\u63A5\u53E3\u5F15\u64CE ${e.ApiEngineKey}`)),s=>String(s?.ApiEngineKey||"")===e.ApiEngineKey&&Jn(s?.ApiV8Code||s?.Code)===Jn(i.code)&&(r.V8Limit===void 0||Ky(s)===(Number(r.V8Limit)===1?1:0))&&(r.ResponseType===void 0||String(s?.ResponseType||"JSON").toLowerCase()===String(r.ResponseType).toLowerCase()));try{let s=await this.post(O.CREATE_ENGINE,r,{timeoutMs:this.writeRequestTimeoutMs,operationName:a});if(s.Code!==1)return s;let c=await o();return c.matched?{...s,Data:{...s.Data&&typeof s.Data=="object"?s.Data:{},ApiEngineKey:e.ApiEngineKey,Verified:!0,Verification:"readback"}}:{Code:0,Data:{ApiEngineKey:e.ApiEngineKey,CreateResponse:s.Data},Msg:`${a} \u63A5\u53E3\u8FD4\u56DE\u6210\u529F\uFF0C\u4F46\u8FDC\u7AEF\u56DE\u8BFB\u672A\u786E\u8BA4\u65B0\u8BB0\u5F55\uFF1A${c.lastError||"\u8BB0\u5F55\u6216\u4EE3\u7801\u4E0D\u4E00\u81F4"}`}}catch(s){if(!this.isUncertainWriteError(s))throw s;let c=await o();if(c.matched)return this.recoveredWriteResult(a,s,{ApiEngineKey:e.ApiEngineKey,Version:i.version,Verified:!0});throw this.uncertainWriteFailure(a,s,c.lastError)}}async uploadFileBase64(e){return this.post(O.UPLOAD_FILE_BASE64,{OsClient:this.config.osClient,...e})}async uploadApplicationAssetStream(e){let r=tc.default.resolve(e.FilePath),n=Ot.default.lstatSync(r);if(!n.isFile()||n.isSymbolicLink())throw new Error(`\u5E94\u7528\u8D44\u4EA7\u5FC5\u987B\u662F\u666E\u901A\u6587\u4EF6\u4E14\u4E0D\u80FD\u662F\u7B26\u53F7\u94FE\u63A5\uFF1A${r}`);let i=tc.default.posix.basename(String(e.RelativePath||"").replace(/\\/g,"/"));if(!i||/[\r\n"]/u.test(i))throw new Error("RelativePath \u7684\u6587\u4EF6\u540D\u4E0D\u5408\u6CD5");if(e.ProtocolVersion===3)return this.uploadApplicationAssetResumable(e,r,n.size);if(n.size>UV)throw new Error(`\u5F53\u524D\u6587\u4EF6 ${n.size} bytes \u8D85\u8FC7\u65E7\u7248 128MiB \u5355\u8BF7\u6C42\u8FB9\u754C\uFF1B\u8BF7\u542F\u7528 ProtocolVersion=3\uFF0CMCP \u5C06\u81EA\u52A8\u4F7F\u7528 HDFS \u5206\u7247\u65AD\u70B9\u7EED\u4F20\u3002`);let a=`microi-asset-${e.ExpectedSha256.slice(0,16)}.bin`,o={};if(e.ProtocolVersion===3){let s=c=>c===null?"null":String(c??"");Object.assign(o,{ProtocolVersion:"3",PublishMode:"stage",ExpectedGateEpoch:String(e.ExpectedGateEpoch??""),RequestFingerprint:String(e.RequestFingerprint??""),DeliveryBatchId:String(e.DeliveryBatchId??""),SourceManifestHash:String(e.SourceManifestHash??""),RuntimeManifestHash:String(e.RuntimeManifestHash??""),RouteSnapshotJson:String(e.RouteSnapshotJson??""),RouteSnapshotHash:String(e.RouteSnapshotHash??""),ExpectedCurrentVersion:String(e.ExpectedCurrentVersion??""),ExpectedAppVersion:s(e.ExpectedAppVersion),ExpectedPublishFence:String(e.ExpectedPublishFence??""),ExpectedPublishRowVersion:String(e.ExpectedPublishRowVersion??""),ExpectedVersionRowVersion:s(e.ExpectedVersionRowVersion),ExpectedActivePublishVersionId:s(e.ExpectedActivePublishVersionId),ExpectedCommittedPublishVersionId:s(e.ExpectedCommittedPublishVersionId)})}return this.requestMultipartFile(O.UPLOAD_APPLICATION_ASSET_STREAM,{OsClient:this.config.osClient||"",AppIdOrKey:e.AppIdOrKey,VersionNo:e.VersionNo,RelativePath:e.RelativePath,ExpectedSha256:e.ExpectedSha256,RequestId:e.RequestId,...o},r,a,"initial",e.TimeoutMs)}async getApplicationAssetMultipartStatus(e,r){return this.post(O.GET_APPLICATION_ASSET_MULTIPART_STATUS,{OsClient:this.config.osClient,AppIdOrKey:e,SessionId:r},{timeoutMs:2*6e4,operationName:"read resumable application asset status"})}async uploadApplicationAssetResumable(e,r,n){if(!Number.isSafeInteger(n)||n<0)throw new Error("\u5E94\u7528\u8D44\u4EA7\u5927\u5C0F\u8D85\u51FA JavaScript \u5B89\u5168\u6574\u6570\u8303\u56F4");let i=WV(e),a=await this.post(O.INITIATE_APPLICATION_ASSET_MULTIPART,{OsClient:this.config.osClient,AppIdOrKey:e.AppIdOrKey,VersionNo:e.VersionNo,RelativePath:e.RelativePath,ExpectedSha256:e.ExpectedSha256,TotalSize:n,RequestedChunkSize:JV,RequestId:e.RequestId,...i},{timeoutMs:2*6e4,operationName:"initiate resumable application asset upload"});if(a.Code!==1)return a;let o=a.Data,s=String(o?.SessionId||"").trim(),c=Number(o?.ChunkSize),l=Number(o?.TotalParts);if(!/^mciau-[a-f0-9]{30}$/u.test(s)||!Number.isSafeInteger(c)||c<16*1024*1024||!Number.isSafeInteger(l)||l<0||l>1e4||l!==(n===0?0:Math.ceil(n/c)))throw new Error("\u670D\u52A1\u7AEF\u8FD4\u56DE\u7684\u65AD\u70B9\u4E0A\u4F20 SessionId/ChunkSize/TotalParts \u4E0D\u5408\u6CD5");let u=await this.getApplicationAssetMultipartStatus(e.AppIdOrKey,s);if(u.Code!==1||String(u.Data?.Status||"")==="Succeeded")return u;let f=new Map;for(let g of u.Data?.Parts||[]){let y=Number(g.Number);Number.isSafeInteger(y)&&y>0&&y<=l&&f.set(y,g)}let h=0,m=0;for(let g=1;g<=l;g+=1){let y=(g-1)*c,v=Math.min(c,n-y),x=await KV(r,y,v),b=f.get(g);if(b){if(Number(b.Size)!==v||String(b.Sha256||"")!==x)throw new Error(`\u65AD\u70B9\u4F1A\u8BDD\u7B2C ${g} \u5757\u4E0E\u672C\u5730\u4E0D\u53EF\u53D8\u6587\u4EF6\u4E0D\u4E00\u81F4\uFF1B\u5DF2\u62D2\u7EDD\u8986\u76D6\uFF0C\u8BF7\u6838\u5BF9\u672C\u5730\u6587\u4EF6\u662F\u5426\u5728\u4E0A\u4F20\u671F\u95F4\u53D1\u751F\u53D8\u5316\u3002`);m+=1;continue}let _;for(let E=0;E<5;E+=1)try{if(_=await this.requestBinaryFileRange(O.UPLOAD_APPLICATION_ASSET_MULTIPART_PART,{osClient:this.config.osClient||"",sessionId:s,partNumber:String(g),expectedPartSha256:x},r,y,v,"initial",e.TimeoutMs),_.Code===1)break;if(E===4)return _}catch(S){u=await this.getApplicationAssetMultipartStatus(e.AppIdOrKey,s);let T=(u.Data?.Parts||[]).find(C=>Number(C.Number)===g);if(u.Code===1&&T&&Number(T.Size)===v&&String(T.Sha256||"")===x){_=u;break}if(E===4)throw S;await new Promise(C=>setTimeout(C,500*(E+1)))}if(!_||_.Code!==1)return _||{Code:0,Data:null,Msg:`\u7B2C ${g} \u5757\u4E0A\u4F20\u6CA1\u6709\u8FD4\u56DE\u7EC8\u6001`};h+=1,(g===1||g%20===0||g===l)&&console.error(`[microi-mcp] Resumable HDFS asset ${e.RelativePath}: ${g}/${l}`)}try{let g=await this.post(O.COMPLETE_APPLICATION_ASSET_MULTIPART,{OsClient:this.config.osClient,AppIdOrKey:e.AppIdOrKey,SessionId:s},{timeoutMs:Wy,maxTimeoutMs:Wy,operationName:"complete resumable application asset upload"});return g.Code===1&&g.Data&&typeof g.Data=="object"?{...g,Data:{...g.Data,UploadedInThisRun:h,ResumedParts:m}}:g}catch(g){let y=await this.getApplicationAssetMultipartStatus(e.AppIdOrKey,s);if(y.Code===1&&String(y.Data?.Status||"")==="Succeeded")return{...y,Data:{...y.Data,RecoveredAfterTransportError:!0,UploadedInThisRun:h,ResumedParts:m},Msg:"\u5B8C\u6210\u8BF7\u6C42\u54CD\u5E94\u4E2D\u65AD\uFF0C\u4F46\u5DF2\u901A\u8FC7\u4F1A\u8BDD\u56DE\u8BFB\u786E\u8BA4\u6700\u7EC8\u5BF9\u8C61 Prepared\u3002"};throw g}}async finalizeApplicationStreamPublish(e){return this.post(O.FINALIZE_APPLICATION_STREAM_PUBLISH,{OsClient:this.config.osClient,...e},{timeoutMs:10*6e4,operationName:"finalize application stream publish"})}async getMicroService(e){return this.post(O.GET_MICRO_SERVICE,{OsClient:this.config.osClient,MsKey:e})}async listApplications(e={}){return this.post(O.LIST_APPLICATIONS,{OsClient:this.config.osClient,...e})}async getApplicationContext(e){return this.post(O.GET_APPLICATION_CONTEXT,{OsClient:this.config.osClient,...e})}async getApplicationFile(e){return this.post(O.GET_APPLICATION_FILE,{OsClient:this.config.osClient,...e})}async createMicroService(e){return this.post(O.CREATE_MICRO_SERVICE,{OsClient:this.config.osClient,...e})}async syncMicroServiceSource(e){return this.post(O.SYNC_MICRO_SERVICE_SOURCE,{OsClient:this.config.osClient,...e})}async publishMicroService(e){return this.post(O.PUBLISH_MICRO_SERVICE,{OsClient:this.config.osClient,...e})}async probeMicroAppEntry(e){let r=FV(this.config.apiBaseUrl,this.config.osClient||"",e),n=new AbortController,i=setTimeout(()=>n.abort(),1e4);try{let a=await fetch(r,{method:"GET",headers:{Accept:"text/html,application/xhtml+xml"},redirect:"follow",signal:n.signal}),o=a.headers.get("content-type")||"",s=Number(a.headers.get("content-length")||0);if(Number.isFinite(s)&&s>2*1024*1024)return await a.body?.cancel(),{ok:!1,url:r,status:a.status,contentType:o,bodyBytes:s,error:"MicroApp entry exceeds the 2MB probe limit"};let c=Buffer.from(await a.arrayBuffer()),l=c.byteLength,u=c.toString("utf8"),p=/<head(?:\s|>)/iu.test(u),f=/<body(?:\s|>)/iu.test(u),h=a.ok&&o.toLowerCase().includes("text/html")&&l>0&&p&&f;return{ok:h,url:r,status:a.status,contentType:o,bodyBytes:l,hasHead:p,hasBody:f,...a.ok?h?{}:{error:"MicroApp entry is not a complete HTML document with <head> and <body>"}:{error:`HTTP ${a.status} ${a.statusText}`}}}catch(a){return{ok:!1,url:r,error:n.signal.aborted?"MicroApp entry probe timed out after 10000ms":a instanceof Error?a.message:String(a)}}finally{clearTimeout(i)}}async getTableData(e,r={}){return this.post(O.FORM_GET_TABLE_DATA,{OsClient:this.config.osClient,FormEngineKey:e,...r})}async addFormData(e,r){return this.post(O.FORM_ADD_FORM_DATA,{OsClient:this.config.osClient,FormEngineKey:e,...r})}async updateFormData(e,r){return this.post(O.FORM_UPT_FORM_DATA,{OsClient:this.config.osClient,FormEngineKey:e,...r})}async getEventCode(e,r,n={}){return this.post(O.GET_EVENT_CODE,{OsClient:this.config.osClient,FormEngineKey:e,EventType:r},n)}async saveEventCode(e,r,n,i){Qs(n,`\u4FDD\u5B58 V8 \u4E8B\u4EF6 ${e}/${r}`);let a;try{let c=await this.getEventCode(e,r);a=c.Code===1?c.Data:void 0}catch{a=void 0}let o=ec({kind:"V8Event",key:e,eventType:r,currentCode:n,remoteCode:a?.V8Code||a?.Code,remoteVersion:a?.Version,functionDescription:i?.functionDescription,changeSummary:i?.changeSummary||`\u4FDD\u5B58 V8 \u4E8B\u4EF6 ${e}/${r}`}),s={OsClient:this.config.osClient,FormEngineKey:e,EventType:r,V8Code:o.code,Version:o.version,ChangeHistory:o.changeHistory};try{return await this.post(O.UPDATE_EVENT_CODE,s,{timeoutMs:this.writeRequestTimeoutMs,operationName:`\u4FDD\u5B58 V8 \u4E8B\u4EF6 ${e}/${r}`})}catch(c){if(!this.isUncertainWriteError(c))throw c;let l=await this.pollReadback(()=>this.getEventCode(e,r,this.readbackOptions(`\u56DE\u8BFB V8 \u4E8B\u4EF6 ${e}/${r}`)),u=>Jn(u?.V8Code||u?.Code)===Jn(o.code));if(l.matched)return this.recoveredWriteResult(`\u4FDD\u5B58 V8 \u4E8B\u4EF6 ${e}/${r}`,c,{FormEngineKey:e,EventType:r,Version:o.version});throw this.uncertainWriteFailure(`\u4FDD\u5B58 V8 \u4E8B\u4EF6 ${e}/${r}`,c,l.lastError)}}async getEventList(e){return this.post(O.GET_EVENT_LIST,{OsClient:this.config.osClient,...e?{_SearchKey:e}:{}})}async getWorkflowV8EventList(e){return this.post(O.GET_WORKFLOW_V8_EVENT_LIST,{OsClient:this.config.osClient,...e?{FlowDesignId:e}:{}})}async getWorkflowV8EventCode(e,r,n){return this.post(O.GET_WORKFLOW_V8_EVENT_CODE,{OsClient:this.config.osClient,...n?{FlowDesignId:n}:{},NodeId:e,EventType:r})}async saveWorkflowV8EventCode(e,r,n,i){Qs(n,`\u4FDD\u5B58\u6D41\u7A0B\u8282\u70B9 V8 ${e}/${r}`);let a;try{let c=await this.getWorkflowV8EventCode(e,r,i?.flowDesignId);a=c.Code===1?c.Data:void 0}catch{a=void 0}let o=!n.trim(),s={OsClient:this.config.osClient,...i?.flowDesignId?{FlowDesignId:i.flowDesignId}:{},NodeId:e,EventType:r};if(o)s.V8Code="";else{let c=`${i?.flowDesignId||a?.FlowDesignId||"workflow"}/${e}`,l=ec({kind:"Workflow",key:c,eventType:r,currentCode:n,remoteCode:a?.V8Code||a?.Code,remoteVersion:a?.Version,functionDescription:i?.functionDescription,changeSummary:i?.changeSummary||`\u4FDD\u5B58\u6D41\u7A0B\u8282\u70B9 V8 ${e}/${r}`});s.V8CodeBase64=Buffer.from(l.code,"utf8").toString("base64"),s.Version=l.version,s.ChangeHistory=l.changeHistory}return this.post(O.UPDATE_WORKFLOW_V8_EVENT_CODE,s)}async createTable(e,r,n){let i={...n||{}};return i.V8Limit===void 0&&i.V8Unlimited!==void 0&&(i.V8Limit=Number(i.V8Unlimited)===1?0:1),delete i.V8Unlimited,this.post(O.CREATE_TABLE,{OsClient:this.config.osClient,Name:e,Description:r||"",...i})}async repairFixedAuditFields(e){return this.post(O.REPAIR_FIXED_AUDIT_FIELDS,{OsClient:this.config.osClient,TableId:e.tableId,TableName:e.tableName})}async addField(e){return this.post(O.ADD_FIELD,{OsClient:this.config.osClient,...e,Visible:e.Visible??1,AppVisible:e.AppVisible??1})}async deleteField(e){return this.post(O.DELETE_FIELD,{OsClient:this.config.osClient,...e})}async updateField(e){return this.post(O.UPDATE_FIELD,{OsClient:this.config.osClient,...e})}async updateFieldList(e){return this.post(O.UPDATE_FIELD_LIST,{OsClient:this.config.osClient,...e})}async getFieldList(e,r){return this.post(O.GET_FIELD_LIST,{OsClient:this.config.osClient,TableName:e,TableId:r})}async updateTable(e){return this.post(O.UPDATE_TABLE,{OsClient:this.config.osClient,...e})}async refreshSchemaCache(e){return this.post(O.REFRESH_SCHEMA_CACHE,{OsClient:this.config.osClient,Tables:e})}async setEngineAnonymous(e,r=1){return this.post(O.SET_ENGINE_ANONYMOUS,{OsClient:this.config.osClient,ApiEngineKeys:e,AllowAnonymous:r})}async createModule(e){let r=await this.post(O.CREATE_MODULE,{OsClient:this.config.osClient,...e,Display:e.Display??1,AppDisplay:e.AppDisplay??1});if(r.Code!==1||!!!(e.IsMicroiService===1||e.MicroServiceId||e.MicroServicePageId||e.MicroServiceRoutePath))return r;let i=r.Data&&typeof r.Data=="object"?r.Data:{},a=String(i.ModuleId||i.Id||"");if(!a)return{Code:0,Data:{CreateResponse:r.Data},Msg:"\u83DC\u5355\u5DF2\u521B\u5EFA\uFF0C\u4F46\u8FD4\u56DE\u7ED3\u679C\u7F3A\u5C11 ModuleId\uFF0C\u65E0\u6CD5\u5199\u5165\u5E76\u56DE\u8BFB\u5FAE\u670D\u52A1\u5173\u8054\u5B57\u6BB5\u3002"};let o={ModuleId:a,IsMicroiService:1,OpenType:e.OpenType||"MicroService",ComponentName:e.ComponentName||"MicroService",ComponentPath:e.ComponentPath||"/micro-app/host",Url:e.Url,MicroServiceId:e.MicroServiceId,MicroServicePageId:e.MicroServicePageId,MicroServiceRoutePath:e.MicroServiceRoutePath},s=await this.updateModule(o);return s.Code!==1?{Code:0,Data:{ModuleId:a,CreateResponse:r.Data,BindingResponse:s.Data},Msg:`\u83DC\u5355\u57FA\u7840\u8BB0\u5F55\u5DF2\u521B\u5EFA\uFF0C\u4F46\u5FAE\u670D\u52A1\u5173\u8054\u5B57\u6BB5\u5199\u5165\u6216\u56DE\u8BFB\u5931\u8D25\uFF1A${s.Msg||"\u672A\u77E5\u9519\u8BEF"}`}:{...r,Data:{...i,MicroServiceBindingVerified:!0,BindingVerification:s.Data}}}async setRolePermission(e,r){return this.post(O.SET_ROLE_PERMISSION,{OsClient:this.config.osClient,RoleId:e,MenuIds:r})}async listRoles(e){return this.post(O.LIST_ROLES,{OsClient:this.config.osClient,...e?{Keyword:e}:{}})}async saveRole(e){return this.post(O.SAVE_ROLE,{OsClient:this.config.osClient,...e})}async listModules(e){return this.post(O.LIST_MODULES,{OsClient:this.config.osClient,...e?{Keyword:e}:{}})}async getModule(e,r={}){return this.post(O.GET_MODULE,{OsClient:this.config.osClient,ModuleId:e},r)}async updateModule(e){let r={OsClient:this.config.osClient,...e},n=String(r.ModuleId||r.Id||""),i=`\u66F4\u65B0\u83DC\u5355\u6A21\u5757 ${n||r.Name||""}`.trim();Ys(r,i);let a=async()=>{if(!n)return{matched:!1,mismatches:["ModuleId"]};try{let o=await this.getModule(n,this.readbackOptions(`\u56DE\u8BFB\u83DC\u5355\u6A21\u5757 ${n}`));return o.Code!==1||!o.Data||typeof o.Data!="object"?{matched:!1,mismatches:["\u56DE\u8BFB\u5931\u8D25"],response:o}:{...GV(r,o.Data),response:o}}catch{return{matched:!1,mismatches:["\u56DE\u8BFB\u8BF7\u6C42\u5F02\u5E38"]}}};try{let o=await this.post(O.UPDATE_MODULE,r,{timeoutMs:this.writeRequestTimeoutMs,operationName:i});if(o.Code!==1)return o;let s=await a();return s.matched?{...o,Data:{...o.Data&&typeof o.Data=="object"?o.Data:{},Verified:!0,Verification:"readback"}}:{Code:0,Data:{ModuleId:n,Mismatches:s.mismatches,UpdateResponse:o.Data},Msg:`${i} \u63A5\u53E3\u8FD4\u56DE\u6210\u529F\uFF0C\u4F46\u8FDC\u7AEF\u56DE\u8BFB\u4E0D\u4E00\u81F4\uFF1A${s.mismatches.join(", ")}`}}catch(o){if(!this.isUncertainWriteError(o))throw o;let s=[],c=await this.pollReadback(async()=>{let l=await a();return s=l.mismatches,{Code:l.response?.Code??(l.matched?1:0),Data:l,Msg:l.response?.Msg||""}},l=>l.matched);if(c.matched)return this.recoveredWriteResult(i,o,{ModuleId:n,Verified:!0});throw this.uncertainWriteFailure(i,o,s.length?`\u5B57\u6BB5\u4E0D\u4E00\u81F4\uFF1A${s.join(", ")}`:c.lastError)}}async listDataSources(e){return this.post(O.LIST_DATA_SOURCES,{OsClient:this.config.osClient,...e?{Keyword:e}:{}})}async saveDataSource(e){return this.post(O.SAVE_DATA_SOURCE,{OsClient:this.config.osClient,...e})}async runDataSource(e,r){return this.post(O.RUN_DATA_SOURCE,{OsClient:this.config.osClient,DataSourceKey:e,...r||{}})}async listPrintTemplates(e){return this.post(O.LIST_PRINT_TEMPLATES,{OsClient:this.config.osClient,...e?{Keyword:e}:{}})}async savePrintTemplate(e){return this.post(O.SAVE_PRINT_TEMPLATE,{OsClient:this.config.osClient,...e})}async saveWorkflowPackage(e){return this.post(O.SAVE_WORKFLOW_PACKAGE,{OsClient:this.config.osClient,...e})}async saveJob(e){return this.post(O.SAVE_JOB,{OsClient:this.config.osClient,...e})}async listDatabaseBackupTenants(){return this.post(O.LIST_DATABASE_BACKUP_TENANTS,{OsClient:this.config.osClient})}async runDatabaseBackup(e){if(!/^[A-Za-z0-9:._-]{8,128}$/.test(e?.idempotencyKey||""))throw new Error("database backup idempotencyKey is required (8-128 safe characters) and must be reused for uncertain retries");return this.post(O.RUN_DATABASE_BACKUP,{OsClient:this.config.osClient,ConfirmExecution:"DATABASE_BACKUP",RetainCount:e.retainCount??7,...e.tenantOsClients===void 0?{}:{TenantOsClients:e.tenantOsClients},IdempotencyKey:e.idempotencyKey})}async runBackgroundApiEngine(e){return this.post(O.RUN_BACKGROUND_API_ENGINE,{OsClient:this.config.osClient,Action:"RunApiEngine",TargetApiEngineKey:e.apiEngineKey,Title:e.title,Param:e.param,Options:e.options||{}},{timeoutMs:this.writeRequestTimeoutMs,operationName:`queue background API engine ${e.apiEngineKey}`})}async validateLowCodeSystem(e){return this.post(O.VALIDATE_LOW_CODE_SYSTEM,{OsClient:this.config.osClient,Manifest:e})}async writeAuditLog(e,r,n){return this.post(O.WRITE_MCP_AUDIT_LOG,{OsClient:this.config.osClient,Action:e,Target:r,Content:n})}async queryMongodbLogs(e={}){return this.post(O.QUERY_MONGODB_LOGS,{OsClient:this.config.osClient,Keyword:e.keyword,Type:e.type,Level:e.level,SearchMonth:e.searchMonth,PageIndex:e.pageIndex||1,PageSize:e.pageSize||20})}async writeMongodbLog(e){return this.post(O.WRITE_MONGODB_LOG,{OsClient:this.config.osClient,Type:e.type||"MCP",Title:e.title,Content:e.content,Level:e.level||1,Api:e.api||"microi.mcp",Param:e.param||"",Remark:e.remark||"",OtherInfo:e.otherInfo||"",Timer:e.timer,Result:e.result||"",AppId:e.appId||"microi.mcp"})}async querySystemObservability(e){return this.executeEngine("mci-system-observability-query",e)}async manageSystemObservability(e){return this.executeEngine("mci-system-observability-action",e)}async getRedisStatistics(e=0,r){return this.post(O.REDIS_STATISTICS,{Action:"RedisStatistics",Mode:r?"saved":"tenant",ConnectionId:r||"",Database:e})}async getRedisKeys(e="*",r=0,n=100,i,a){return this.post(O.REDIS_KEYS,{Action:"Keys",Mode:a?"saved":"tenant",ConnectionId:a||"",Database:r,Pattern:e,PageSize:n,Cursor:i||""})}async getRedisKey(e,r=0,n=1,i=500,a){return this.post(O.REDIS_KEY,{Action:"Key",Mode:a?"saved":"tenant",ConnectionId:a||"",Database:r,Key:e,PageIndex:n,PageSize:i})}async deleteRedisKeys(e,r=0,n){return this.post(O.REDIS_DELETE_KEYS,{Action:"DeleteKeys",Mode:n?"saved":"tenant",ConnectionId:n||"",Database:r,Keys:e})}async replaceRedisValue(e,r,n,i=0,a,o){return this.post(O.REDIS_REPLACE_VALUE,{Action:"ReplaceValue",Mode:o?"saved":"tenant",ConnectionId:o||"",Database:i,Key:e,DataType:r,Value:n,...a===void 0?{}:{TtlSeconds:a}})}async renameRedisKey(e,r,n=0,i){return this.post(O.REDIS_RENAME_KEY,{Action:"RenameKey",Mode:i?"saved":"tenant",ConnectionId:i||"",Database:n,Key:e,NewKey:r})}async setRedisTtl(e,r,n=0,i){return this.post(O.REDIS_SET_TTL,{Action:"SetTtl",Mode:i?"saved":"tenant",ConnectionId:i||"",Database:n,Key:e,TtlSeconds:r})}async getPageEngineList(e){return this.post(O.GET_PAGE_ENGINE_LIST,{OsClient:this.config.osClient,...e?{Keyword:e}:{}})}async getPageEngineDetail(e){return this.post(O.GET_PAGE_ENGINE_DETAIL,{OsClient:this.config.osClient,PageId:e})}async savePageEngine(e){return this.post(O.SAVE_PAGE_ENGINE,{OsClient:this.config.osClient,...e})}async listBackgroundTasks(){return this.post(O.LIST_BACKGROUND_TASKS,{OsClient:this.config.osClient,Action:"List"},{timeoutMs:this.requestTimeoutMs,operationName:"list background tasks"})}async cancelBackgroundTask(e){return this.post(O.CANCEL_BACKGROUND_TASK,{OsClient:this.config.osClient,Action:"Cancel",Id:e},{timeoutMs:this.writeRequestTimeoutMs,operationName:"cancel background task"})}async listPageEngineHistory(e,r=1,n=50){return this.post(O.LIST_PAGE_ENGINE_HISTORY,{OsClient:this.config.osClient,PageId:e,PageIndex:r,PageSize:n})}async getPageEngineHistory(e,r){return this.post(O.GET_PAGE_ENGINE_HISTORY,{OsClient:this.config.osClient,PageId:e,HistoryId:r})}async comparePageEngineVersions(e,r,n){return this.post(O.COMPARE_PAGE_ENGINE_VERSIONS,{OsClient:this.config.osClient,PageId:e,...r?{LeftHistoryId:r}:{},...n?{RightHistoryId:n}:{}})}async exportPageEngine(e){return this.post(O.EXPORT_PAGE_ENGINE,{OsClient:this.config.osClient,PageId:e})}async rollbackPageEngine(e){return this.post(O.ROLLBACK_PAGE_ENGINE,{OsClient:this.config.osClient,...e})}async listBlueprints(e){return this.post(O.LIST_BLUEPRINTS,{OsClient:this.config.osClient,...e?{Keyword:e}:{}})}async getBlueprint(e){return this.post(O.GET_BLUEPRINT,{OsClient:this.config.osClient,BlueprintId:e})}async listBlueprintHistory(e,r=1,n=50){return this.post(O.LIST_BLUEPRINT_HISTORY,{OsClient:this.config.osClient,BlueprintId:e,PageIndex:r,PageSize:n})}async getBlueprintHistory(e,r){return this.post(O.GET_BLUEPRINT_HISTORY,{OsClient:this.config.osClient,BlueprintId:e,HistoryId:r})}async compareBlueprintVersions(e,r,n){return this.post(O.COMPARE_BLUEPRINT_VERSIONS,{OsClient:this.config.osClient,BlueprintId:e,...r?{LeftHistoryId:r}:{},...n?{RightHistoryId:n}:{}})}async exportBlueprint(e){return this.post(O.EXPORT_BLUEPRINT,{OsClient:this.config.osClient,BlueprintId:e})}async saveBlueprint(e){return this.post(O.SAVE_BLUEPRINT,{OsClient:this.config.osClient,...e})}async rollbackBlueprint(e){return this.post(O.ROLLBACK_BLUEPRINT,{OsClient:this.config.osClient,...e})}async deleteBlueprint(e){return this.post(O.DELETE_BLUEPRINT,{OsClient:this.config.osClient,BlueprintId:e})}async validateBlueprint(e){return this.post(O.VALIDATE_BLUEPRINT,{OsClient:this.config.osClient,BlueprintId:e})}destroy(){this.refreshTimer&&(clearInterval(this.refreshTimer),this.refreshTimer=void 0)}};var d={};Fd(d,{BRAND:()=>_q,DIRTY:()=>Mi,EMPTY_PATH:()=>eq,INVALID:()=>W,NEVER:()=>aB,OK:()=>_t,ParseStatus:()=>gt,Schema:()=>ae,ZodAny:()=>Kn,ZodArray:()=>xn,ZodBigInt:()=>Fi,ZodBoolean:()=>zi,ZodBranded:()=>ic,ZodCatch:()=>Wi,ZodDate:()=>Li,ZodDefault:()=>Ki,ZodDiscriminatedUnion:()=>dp,ZodEffects:()=>hr,ZodEnum:()=>Zi,ZodError:()=>Zt,ZodFirstPartyTypeKind:()=>M,ZodFunction:()=>mp,ZodIntersection:()=>Bi,ZodIssueCode:()=>N,ZodLazy:()=>Ui,ZodLiteral:()=>Ji,ZodMap:()=>ao,ZodNaN:()=>so,ZodNativeEnum:()=>Hi,ZodNever:()=>Rr,ZodNull:()=>Vi,ZodNullable:()=>Yr,ZodNumber:()=>Di,ZodObject:()=>Kt,ZodOptional:()=>Ht,ZodParsedType:()=>L,ZodPipeline:()=>ac,ZodPromise:()=>Wn,ZodReadonly:()=>Gi,ZodRecord:()=>fp,ZodSchema:()=>ae,ZodSet:()=>oo,ZodString:()=>Hn,ZodSymbol:()=>no,ZodTransformer:()=>hr,ZodTuple:()=>Xr,ZodType:()=>ae,ZodUndefined:()=>ji,ZodUnion:()=>qi,ZodUnknown:()=>vn,ZodVoid:()=>io,addIssueToContext:()=>z,any:()=>Rq,array:()=>Mq,bigint:()=>Tq,boolean:()=>gP,coerce:()=>iB,custom:()=>fP,date:()=>Cq,datetimeRegex:()=>pP,defaultErrorMap:()=>yn,discriminatedUnion:()=>zq,effect:()=>Gq,enum:()=>Hq,function:()=>Uq,getErrorMap:()=>eo,getParsedType:()=>Gr,instanceof:()=>Eq,intersection:()=>Lq,isAborted:()=>up,isAsync:()=>to,isDirty:()=>pp,isValid:()=>Zn,late:()=>Sq,lazy:()=>Jq,literal:()=>Zq,makeIssue:()=>nc,map:()=>qq,nan:()=>kq,nativeEnum:()=>Kq,never:()=>Oq,null:()=>Iq,nullable:()=>Yq,number:()=>hP,object:()=>eb,objectUtil:()=>Xy,oboolean:()=>nB,onumber:()=>rB,optional:()=>Xq,ostring:()=>tB,pipeline:()=>eB,preprocess:()=>Qq,promise:()=>Wq,quotelessJson:()=>XV,record:()=>Vq,set:()=>Bq,setErrorMap:()=>QV,strictObject:()=>Dq,string:()=>mP,symbol:()=>Pq,transformer:()=>Gq,tuple:()=>jq,undefined:()=>Aq,union:()=>Fq,unknown:()=>$q,util:()=>de,void:()=>Nq});var de;(function(t){t.assertEqual=i=>{};function e(i){}t.assertIs=e;function r(i){throw new Error}t.assertNever=r,t.arrayToEnum=i=>{let a={};for(let o of i)a[o]=o;return a},t.getValidEnumValues=i=>{let a=t.objectKeys(i).filter(s=>typeof i[i[s]]!="number"),o={};for(let s of a)o[s]=i[s];return t.objectValues(o)},t.objectValues=i=>t.objectKeys(i).map(function(a){return i[a]}),t.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let a=[];for(let o in i)Object.prototype.hasOwnProperty.call(i,o)&&a.push(o);return a},t.find=(i,a)=>{for(let o of i)if(a(o))return o},t.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function n(i,a=" | "){return i.map(o=>typeof o=="string"?`'${o}'`:o).join(a)}t.joinValues=n,t.jsonStringifyReplacer=(i,a)=>typeof a=="bigint"?a.toString():a})(de||(de={}));var Xy;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Xy||(Xy={}));var L=de.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Gr=t=>{switch(typeof t){case"undefined":return L.undefined;case"string":return L.string;case"number":return Number.isNaN(t)?L.nan:L.number;case"boolean":return L.boolean;case"function":return L.function;case"bigint":return L.bigint;case"symbol":return L.symbol;case"object":return Array.isArray(t)?L.array:t===null?L.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?L.promise:typeof Map<"u"&&t instanceof Map?L.map:typeof Set<"u"&&t instanceof Set?L.set:typeof Date<"u"&&t instanceof Date?L.date:L.object;default:return L.unknown}};var N=de.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"]),XV=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),Zt=class t 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]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(a){return a.message},n={_errors:[]},i=a=>{for(let o of a.issues)if(o.code==="invalid_union")o.unionErrors.map(i);else if(o.code==="invalid_return_type")i(o.returnTypeError);else if(o.code==="invalid_arguments")i(o.argumentsError);else if(o.path.length===0)n._errors.push(r(o));else{let s=n,c=0;for(;c<o.path.length;){let l=o.path[c];c===o.path.length-1?(s[l]=s[l]||{_errors:[]},s[l]._errors.push(r(o))):s[l]=s[l]||{_errors:[]},s=s[l],c++}}};return i(this),n}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,de.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let i of this.issues)if(i.path.length>0){let a=i.path[0];r[a]=r[a]||[],r[a].push(e(i))}else n.push(e(i));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};Zt.create=t=>new Zt(t);var YV=(t,e)=>{let r;switch(t.code){case N.invalid_type:t.received===L.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case N.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,de.jsonStringifyReplacer)}`;break;case N.unrecognized_keys:r=`Unrecognized key(s) in object: ${de.joinValues(t.keys,", ")}`;break;case N.invalid_union:r="Invalid input";break;case N.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${de.joinValues(t.options)}`;break;case N.invalid_enum_value:r=`Invalid enum value. Expected ${de.joinValues(t.options)}, received '${t.received}'`;break;case N.invalid_arguments:r="Invalid function arguments";break;case N.invalid_return_type:r="Invalid function return type";break;case N.invalid_date:r="Invalid date";break;case N.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:de.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case N.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case N.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case N.custom:r="Invalid input";break;case N.invalid_intersection_types:r="Intersection results could not be merged";break;case N.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case N.not_finite:r="Number must be finite";break;default:r=e.defaultError,de.assertNever(t)}return{message:r}},yn=YV;var oP=yn;function QV(t){oP=t}function eo(){return oP}var nc=t=>{let{data:e,path:r,errorMaps:n,issueData:i}=t,a=[...r,...i.path||[]],o={...i,path:a};if(i.message!==void 0)return{...i,path:a,message:i.message};let s="",c=n.filter(l=>!!l).slice().reverse();for(let l of c)s=l(o,{data:e,defaultError:s}).message;return{...i,path:a,message:s}},eq=[];function z(t,e){let r=eo(),n=nc({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===yn?void 0:yn].filter(i=>!!i)});t.common.issues.push(n)}var gt=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let i of r){if(i.status==="aborted")return W;i.status==="dirty"&&e.dirty(),n.push(i.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let i of r){let a=await i.key,o=await i.value;n.push({key:a,value:o})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let i of r){let{key:a,value:o}=i;if(a.status==="aborted"||o.status==="aborted")return W;a.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),a.value!=="__proto__"&&(typeof o.value<"u"||i.alwaysSet)&&(n[a.value]=o.value)}return{status:e.value,value:n}}},W=Object.freeze({status:"aborted"}),Mi=t=>({status:"dirty",value:t}),_t=t=>({status:"valid",value:t}),up=t=>t.status==="aborted",pp=t=>t.status==="dirty",Zn=t=>t.status==="valid",to=t=>typeof Promise<"u"&&t instanceof Promise;var q;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(q||(q={}));var mr=class{constructor(e,r,n,i){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=i}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},sP=(t,e)=>{if(Zn(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new Zt(t.common.issues);return this._error=r,this._error}}};function re(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:i}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:i}:{errorMap:(o,s)=>{let{message:c}=t;return o.code==="invalid_enum_value"?{message:c??s.defaultError}:typeof s.data>"u"?{message:c??n??s.defaultError}:o.code!=="invalid_type"?{message:s.defaultError}:{message:c??r??s.defaultError}},description:i}}var ae=class{get description(){return this._def.description}_getType(e){return Gr(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:Gr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new gt,ctx:{common:e.parent.common,data:e.data,parsedType:Gr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(to(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Gr(e)},i=this._parseSync({data:e,path:n.path,parent:n});return sP(n,i)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Gr(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return Zn(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>Zn(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Gr(e)},i=this._parse({data:e,path:n.path,parent:n}),a=await(to(i)?i:Promise.resolve(i));return sP(n,a)}refine(e,r){let n=i=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(i):r;return this._refinement((i,a)=>{let o=e(i),s=()=>a.addIssue({code:N.custom,...n(i)});return typeof Promise<"u"&&o instanceof Promise?o.then(c=>c?!0:(s(),!1)):o?!0:(s(),!1)})}refinement(e,r){return this._refinement((n,i)=>e(n)?!0:(i.addIssue(typeof r=="function"?r(n,i):r),!1))}_refinement(e){return new hr({schema:this,typeName:M.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return Ht.create(this,this._def)}nullable(){return Yr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return xn.create(this)}promise(){return Wn.create(this,this._def)}or(e){return qi.create([this,e],this._def)}and(e){return Bi.create(this,e,this._def)}transform(e){return new hr({...re(this._def),schema:this,typeName:M.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new Ki({...re(this._def),innerType:this,defaultValue:r,typeName:M.ZodDefault})}brand(){return new ic({typeName:M.ZodBranded,type:this,...re(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Wi({...re(this._def),innerType:this,catchValue:r,typeName:M.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return ac.create(this,e)}readonly(){return Gi.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},tq=/^c[^\s-]{8,}$/i,rq=/^[0-9a-z]+$/,nq=/^[0-9A-HJKMNP-TV-Z]{26}$/i,iq=/^[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,aq=/^[a-z0-9_-]{21}$/i,oq=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,sq=/^[-+]?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)?)??$/,cq=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,lq="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Yy,uq=/^(?:(?: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])$/,pq=/^(?:(?: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])$/,dq=/^(([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]))$/,fq=/^(([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])$/,mq=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,hq=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,lP="((\\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])))",gq=new RegExp(`^${lP}$`);function uP(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function yq(t){return new RegExp(`^${uP(t)}$`)}function pP(t){let e=`${lP}T${uP(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function bq(t,e){return!!((e==="v4"||!e)&&uq.test(t)||(e==="v6"||!e)&&dq.test(t))}function vq(t,e){if(!oq.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),i=JSON.parse(atob(n));return!(typeof i!="object"||i===null||"typ"in i&&i?.typ!=="JWT"||!i.alg||e&&i.alg!==e)}catch{return!1}}function xq(t,e){return!!((e==="v4"||!e)&&pq.test(t)||(e==="v6"||!e)&&fq.test(t))}var Hn=class t extends ae{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==L.string){let a=this._getOrReturnCtx(e);return z(a,{code:N.invalid_type,expected:L.string,received:a.parsedType}),W}let n=new gt,i;for(let a of this._def.checks)if(a.kind==="min")e.data.length<a.value&&(i=this._getOrReturnCtx(e,i),z(i,{code:N.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),n.dirty());else if(a.kind==="max")e.data.length>a.value&&(i=this._getOrReturnCtx(e,i),z(i,{code:N.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),n.dirty());else if(a.kind==="length"){let o=e.data.length>a.value,s=e.data.length<a.value;(o||s)&&(i=this._getOrReturnCtx(e,i),o?z(i,{code:N.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}):s&&z(i,{code:N.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}),n.dirty())}else if(a.kind==="email")cq.test(e.data)||(i=this._getOrReturnCtx(e,i),z(i,{validation:"email",code:N.invalid_string,message:a.message}),n.dirty());else if(a.kind==="emoji")Yy||(Yy=new RegExp(lq,"u")),Yy.test(e.data)||(i=this._getOrReturnCtx(e,i),z(i,{validation:"emoji",code:N.invalid_string,message:a.message}),n.dirty());else if(a.kind==="uuid")iq.test(e.data)||(i=this._getOrReturnCtx(e,i),z(i,{validation:"uuid",code:N.invalid_string,message:a.message}),n.dirty());else if(a.kind==="nanoid")aq.test(e.data)||(i=this._getOrReturnCtx(e,i),z(i,{validation:"nanoid",code:N.invalid_string,message:a.message}),n.dirty());else if(a.kind==="cuid")tq.test(e.data)||(i=this._getOrReturnCtx(e,i),z(i,{validation:"cuid",code:N.invalid_string,message:a.message}),n.dirty());else if(a.kind==="cuid2")rq.test(e.data)||(i=this._getOrReturnCtx(e,i),z(i,{validation:"cuid2",code:N.invalid_string,message:a.message}),n.dirty());else if(a.kind==="ulid")nq.test(e.data)||(i=this._getOrReturnCtx(e,i),z(i,{validation:"ulid",code:N.invalid_string,message:a.message}),n.dirty());else if(a.kind==="url")try{new URL(e.data)}catch{i=this._getOrReturnCtx(e,i),z(i,{validation:"url",code:N.invalid_string,message:a.message}),n.dirty()}else a.kind==="regex"?(a.regex.lastIndex=0,a.regex.test(e.data)||(i=this._getOrReturnCtx(e,i),z(i,{validation:"regex",code:N.invalid_string,message:a.message}),n.dirty())):a.kind==="trim"?e.data=e.data.trim():a.kind==="includes"?e.data.includes(a.value,a.position)||(i=this._getOrReturnCtx(e,i),z(i,{code:N.invalid_string,validation:{includes:a.value,position:a.position},message:a.message}),n.dirty()):a.kind==="toLowerCase"?e.data=e.data.toLowerCase():a.kind==="toUpperCase"?e.data=e.data.toUpperCase():a.kind==="startsWith"?e.data.startsWith(a.value)||(i=this._getOrReturnCtx(e,i),z(i,{code:N.invalid_string,validation:{startsWith:a.value},message:a.message}),n.dirty()):a.kind==="endsWith"?e.data.endsWith(a.value)||(i=this._getOrReturnCtx(e,i),z(i,{code:N.invalid_string,validation:{endsWith:a.value},message:a.message}),n.dirty()):a.kind==="datetime"?pP(a).test(e.data)||(i=this._getOrReturnCtx(e,i),z(i,{code:N.invalid_string,validation:"datetime",message:a.message}),n.dirty()):a.kind==="date"?gq.test(e.data)||(i=this._getOrReturnCtx(e,i),z(i,{code:N.invalid_string,validation:"date",message:a.message}),n.dirty()):a.kind==="time"?yq(a).test(e.data)||(i=this._getOrReturnCtx(e,i),z(i,{code:N.invalid_string,validation:"time",message:a.message}),n.dirty()):a.kind==="duration"?sq.test(e.data)||(i=this._getOrReturnCtx(e,i),z(i,{validation:"duration",code:N.invalid_string,message:a.message}),n.dirty()):a.kind==="ip"?bq(e.data,a.version)||(i=this._getOrReturnCtx(e,i),z(i,{validation:"ip",code:N.invalid_string,message:a.message}),n.dirty()):a.kind==="jwt"?vq(e.data,a.alg)||(i=this._getOrReturnCtx(e,i),z(i,{validation:"jwt",code:N.invalid_string,message:a.message}),n.dirty()):a.kind==="cidr"?xq(e.data,a.version)||(i=this._getOrReturnCtx(e,i),z(i,{validation:"cidr",code:N.invalid_string,message:a.message}),n.dirty()):a.kind==="base64"?mq.test(e.data)||(i=this._getOrReturnCtx(e,i),z(i,{validation:"base64",code:N.invalid_string,message:a.message}),n.dirty()):a.kind==="base64url"?hq.test(e.data)||(i=this._getOrReturnCtx(e,i),z(i,{validation:"base64url",code:N.invalid_string,message:a.message}),n.dirty()):de.assertNever(a);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(i=>e.test(i),{validation:r,code:N.invalid_string,...q.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...q.errToObj(e)})}url(e){return this._addCheck({kind:"url",...q.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...q.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...q.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...q.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...q.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...q.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...q.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...q.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...q.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...q.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...q.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...q.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...q.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...q.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...q.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...q.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...q.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...q.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...q.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...q.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...q.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...q.errToObj(r)})}nonempty(e){return this.min(1,q.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Hn.create=t=>new Hn({checks:[],typeName:M.ZodString,coerce:t?.coerce??!1,...re(t)});function wq(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,i=r>n?r:n,a=Number.parseInt(t.toFixed(i).replace(".","")),o=Number.parseInt(e.toFixed(i).replace(".",""));return a%o/10**i}var Di=class t extends ae{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==L.number){let a=this._getOrReturnCtx(e);return z(a,{code:N.invalid_type,expected:L.number,received:a.parsedType}),W}let n,i=new gt;for(let a of this._def.checks)a.kind==="int"?de.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),z(n,{code:N.invalid_type,expected:"integer",received:"float",message:a.message}),i.dirty()):a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(n=this._getOrReturnCtx(e,n),z(n,{code:N.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),i.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(n=this._getOrReturnCtx(e,n),z(n,{code:N.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),i.dirty()):a.kind==="multipleOf"?wq(e.data,a.value)!==0&&(n=this._getOrReturnCtx(e,n),z(n,{code:N.not_multiple_of,multipleOf:a.value,message:a.message}),i.dirty()):a.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),z(n,{code:N.not_finite,message:a.message}),i.dirty()):de.assertNever(a);return{status:i.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,q.toString(r))}gt(e,r){return this.setLimit("min",e,!1,q.toString(r))}lte(e,r){return this.setLimit("max",e,!0,q.toString(r))}lt(e,r){return this.setLimit("max",e,!1,q.toString(r))}setLimit(e,r,n,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:q.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:q.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:q.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:q.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:q.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:q.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:q.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:q.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:q.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:q.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&de.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};Di.create=t=>new Di({checks:[],typeName:M.ZodNumber,coerce:t?.coerce||!1,...re(t)});var Fi=class t extends ae{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==L.bigint)return this._getInvalidInput(e);let n,i=new gt;for(let a of this._def.checks)a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(n=this._getOrReturnCtx(e,n),z(n,{code:N.too_small,type:"bigint",minimum:a.value,inclusive:a.inclusive,message:a.message}),i.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(n=this._getOrReturnCtx(e,n),z(n,{code:N.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),i.dirty()):a.kind==="multipleOf"?e.data%a.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),z(n,{code:N.not_multiple_of,multipleOf:a.value,message:a.message}),i.dirty()):de.assertNever(a);return{status:i.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return z(r,{code:N.invalid_type,expected:L.bigint,received:r.parsedType}),W}gte(e,r){return this.setLimit("min",e,!0,q.toString(r))}gt(e,r){return this.setLimit("min",e,!1,q.toString(r))}lte(e,r){return this.setLimit("max",e,!0,q.toString(r))}lt(e,r){return this.setLimit("max",e,!1,q.toString(r))}setLimit(e,r,n,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:q.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:q.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:q.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:q.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:q.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:q.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Fi.create=t=>new Fi({checks:[],typeName:M.ZodBigInt,coerce:t?.coerce??!1,...re(t)});var zi=class extends ae{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==L.boolean){let n=this._getOrReturnCtx(e);return z(n,{code:N.invalid_type,expected:L.boolean,received:n.parsedType}),W}return _t(e.data)}};zi.create=t=>new zi({typeName:M.ZodBoolean,coerce:t?.coerce||!1,...re(t)});var Li=class t extends ae{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==L.date){let a=this._getOrReturnCtx(e);return z(a,{code:N.invalid_type,expected:L.date,received:a.parsedType}),W}if(Number.isNaN(e.data.getTime())){let a=this._getOrReturnCtx(e);return z(a,{code:N.invalid_date}),W}let n=new gt,i;for(let a of this._def.checks)a.kind==="min"?e.data.getTime()<a.value&&(i=this._getOrReturnCtx(e,i),z(i,{code:N.too_small,message:a.message,inclusive:!0,exact:!1,minimum:a.value,type:"date"}),n.dirty()):a.kind==="max"?e.data.getTime()>a.value&&(i=this._getOrReturnCtx(e,i),z(i,{code:N.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),n.dirty()):de.assertNever(a);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:q.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:q.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};Li.create=t=>new Li({checks:[],coerce:t?.coerce||!1,typeName:M.ZodDate,...re(t)});var no=class extends ae{_parse(e){if(this._getType(e)!==L.symbol){let n=this._getOrReturnCtx(e);return z(n,{code:N.invalid_type,expected:L.symbol,received:n.parsedType}),W}return _t(e.data)}};no.create=t=>new no({typeName:M.ZodSymbol,...re(t)});var ji=class extends ae{_parse(e){if(this._getType(e)!==L.undefined){let n=this._getOrReturnCtx(e);return z(n,{code:N.invalid_type,expected:L.undefined,received:n.parsedType}),W}return _t(e.data)}};ji.create=t=>new ji({typeName:M.ZodUndefined,...re(t)});var Vi=class extends ae{_parse(e){if(this._getType(e)!==L.null){let n=this._getOrReturnCtx(e);return z(n,{code:N.invalid_type,expected:L.null,received:n.parsedType}),W}return _t(e.data)}};Vi.create=t=>new Vi({typeName:M.ZodNull,...re(t)});var Kn=class extends ae{constructor(){super(...arguments),this._any=!0}_parse(e){return _t(e.data)}};Kn.create=t=>new Kn({typeName:M.ZodAny,...re(t)});var vn=class extends ae{constructor(){super(...arguments),this._unknown=!0}_parse(e){return _t(e.data)}};vn.create=t=>new vn({typeName:M.ZodUnknown,...re(t)});var Rr=class extends ae{_parse(e){let r=this._getOrReturnCtx(e);return z(r,{code:N.invalid_type,expected:L.never,received:r.parsedType}),W}};Rr.create=t=>new Rr({typeName:M.ZodNever,...re(t)});var io=class extends ae{_parse(e){if(this._getType(e)!==L.undefined){let n=this._getOrReturnCtx(e);return z(n,{code:N.invalid_type,expected:L.void,received:n.parsedType}),W}return _t(e.data)}};io.create=t=>new io({typeName:M.ZodVoid,...re(t)});var xn=class t extends ae{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),i=this._def;if(r.parsedType!==L.array)return z(r,{code:N.invalid_type,expected:L.array,received:r.parsedType}),W;if(i.exactLength!==null){let o=r.data.length>i.exactLength.value,s=r.data.length<i.exactLength.value;(o||s)&&(z(r,{code:o?N.too_big:N.too_small,minimum:s?i.exactLength.value:void 0,maximum:o?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),n.dirty())}if(i.minLength!==null&&r.data.length<i.minLength.value&&(z(r,{code:N.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),n.dirty()),i.maxLength!==null&&r.data.length>i.maxLength.value&&(z(r,{code:N.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((o,s)=>i.type._parseAsync(new mr(r,o,r.path,s)))).then(o=>gt.mergeArray(n,o));let a=[...r.data].map((o,s)=>i.type._parseSync(new mr(r,o,r.path,s)));return gt.mergeArray(n,a)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:q.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:q.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:q.toString(r)}})}nonempty(e){return this.min(1,e)}};xn.create=(t,e)=>new xn({type:t,minLength:null,maxLength:null,exactLength:null,typeName:M.ZodArray,...re(e)});function ro(t){if(t instanceof Kt){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=Ht.create(ro(n))}return new Kt({...t._def,shape:()=>e})}else return t instanceof xn?new xn({...t._def,type:ro(t.element)}):t instanceof Ht?Ht.create(ro(t.unwrap())):t instanceof Yr?Yr.create(ro(t.unwrap())):t instanceof Xr?Xr.create(t.items.map(e=>ro(e))):t}var Kt=class t extends ae{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=de.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==L.object){let l=this._getOrReturnCtx(e);return z(l,{code:N.invalid_type,expected:L.object,received:l.parsedType}),W}let{status:n,ctx:i}=this._processInputParams(e),{shape:a,keys:o}=this._getCached(),s=[];if(!(this._def.catchall instanceof Rr&&this._def.unknownKeys==="strip"))for(let l in i.data)o.includes(l)||s.push(l);let c=[];for(let l of o){let u=a[l],p=i.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new mr(i,p,i.path,l)),alwaysSet:l in i.data})}if(this._def.catchall instanceof Rr){let l=this._def.unknownKeys;if(l==="passthrough")for(let u of s)c.push({key:{status:"valid",value:u},value:{status:"valid",value:i.data[u]}});else if(l==="strict")s.length>0&&(z(i,{code:N.unrecognized_keys,keys:s}),n.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let u of s){let p=i.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new mr(i,p,i.path,u)),alwaysSet:u in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let l=[];for(let u of c){let p=await u.key,f=await u.value;l.push({key:p,value:f,alwaysSet:u.alwaysSet})}return l}).then(l=>gt.mergeObjectSync(n,l)):gt.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return q.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let i=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:q.errToObj(e).message??i}:{message:i}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:M.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of de.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let n of de.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return ro(this)}partial(e){let r={};for(let n of de.objectKeys(this.shape)){let i=this.shape[n];e&&!e[n]?r[n]=i:r[n]=i.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of de.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let a=this.shape[n];for(;a instanceof Ht;)a=a._def.innerType;r[n]=a}return new t({...this._def,shape:()=>r})}keyof(){return dP(de.objectKeys(this.shape))}};Kt.create=(t,e)=>new Kt({shape:()=>t,unknownKeys:"strip",catchall:Rr.create(),typeName:M.ZodObject,...re(e)});Kt.strictCreate=(t,e)=>new Kt({shape:()=>t,unknownKeys:"strict",catchall:Rr.create(),typeName:M.ZodObject,...re(e)});Kt.lazycreate=(t,e)=>new Kt({shape:t,unknownKeys:"strip",catchall:Rr.create(),typeName:M.ZodObject,...re(e)});var qi=class extends ae{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function i(a){for(let s of a)if(s.result.status==="valid")return s.result;for(let s of a)if(s.result.status==="dirty")return r.common.issues.push(...s.ctx.common.issues),s.result;let o=a.map(s=>new Zt(s.ctx.common.issues));return z(r,{code:N.invalid_union,unionErrors:o}),W}if(r.common.async)return Promise.all(n.map(async a=>{let o={...r,common:{...r.common,issues:[]},parent:null};return{result:await a._parseAsync({data:r.data,path:r.path,parent:o}),ctx:o}})).then(i);{let a,o=[];for(let c of n){let l={...r,common:{...r.common,issues:[]},parent:null},u=c._parseSync({data:r.data,path:r.path,parent:l});if(u.status==="valid")return u;u.status==="dirty"&&!a&&(a={result:u,ctx:l}),l.common.issues.length&&o.push(l.common.issues)}if(a)return r.common.issues.push(...a.ctx.common.issues),a.result;let s=o.map(c=>new Zt(c));return z(r,{code:N.invalid_union,unionErrors:s}),W}}get options(){return this._def.options}};qi.create=(t,e)=>new qi({options:t,typeName:M.ZodUnion,...re(e)});var bn=t=>t instanceof Ui?bn(t.schema):t instanceof hr?bn(t.innerType()):t instanceof Ji?[t.value]:t instanceof Zi?t.options:t instanceof Hi?de.objectValues(t.enum):t instanceof Ki?bn(t._def.innerType):t instanceof ji?[void 0]:t instanceof Vi?[null]:t instanceof Ht?[void 0,...bn(t.unwrap())]:t instanceof Yr?[null,...bn(t.unwrap())]:t instanceof ic||t instanceof Gi?bn(t.unwrap()):t instanceof Wi?bn(t._def.innerType):[],dp=class t extends ae{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==L.object)return z(r,{code:N.invalid_type,expected:L.object,received:r.parsedType}),W;let n=this.discriminator,i=r.data[n],a=this.optionsMap.get(i);return a?r.common.async?a._parseAsync({data:r.data,path:r.path,parent:r}):a._parseSync({data:r.data,path:r.path,parent:r}):(z(r,{code:N.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),W)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let i=new Map;for(let a of r){let o=bn(a.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let s of o){if(i.has(s))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(s)}`);i.set(s,a)}}return new t({typeName:M.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:i,...re(n)})}};function Qy(t,e){let r=Gr(t),n=Gr(e);if(t===e)return{valid:!0,data:t};if(r===L.object&&n===L.object){let i=de.objectKeys(e),a=de.objectKeys(t).filter(s=>i.indexOf(s)!==-1),o={...t,...e};for(let s of a){let c=Qy(t[s],e[s]);if(!c.valid)return{valid:!1};o[s]=c.data}return{valid:!0,data:o}}else if(r===L.array&&n===L.array){if(t.length!==e.length)return{valid:!1};let i=[];for(let a=0;a<t.length;a++){let o=t[a],s=e[a],c=Qy(o,s);if(!c.valid)return{valid:!1};i.push(c.data)}return{valid:!0,data:i}}else return r===L.date&&n===L.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var Bi=class extends ae{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),i=(a,o)=>{if(up(a)||up(o))return W;let s=Qy(a.value,o.value);return s.valid?((pp(a)||pp(o))&&r.dirty(),{status:r.value,value:s.data}):(z(n,{code:N.invalid_intersection_types}),W)};return n.common.async?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(([a,o])=>i(a,o)):i(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};Bi.create=(t,e,r)=>new Bi({left:t,right:e,typeName:M.ZodIntersection,...re(r)});var Xr=class t extends ae{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==L.array)return z(n,{code:N.invalid_type,expected:L.array,received:n.parsedType}),W;if(n.data.length<this._def.items.length)return z(n,{code:N.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),W;!this._def.rest&&n.data.length>this._def.items.length&&(z(n,{code:N.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let a=[...n.data].map((o,s)=>{let c=this._def.items[s]||this._def.rest;return c?c._parse(new mr(n,o,n.path,s)):null}).filter(o=>!!o);return n.common.async?Promise.all(a).then(o=>gt.mergeArray(r,o)):gt.mergeArray(r,a)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Xr.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Xr({items:t,typeName:M.ZodTuple,rest:null,...re(e)})};var fp=class t extends ae{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==L.object)return z(n,{code:N.invalid_type,expected:L.object,received:n.parsedType}),W;let i=[],a=this._def.keyType,o=this._def.valueType;for(let s in n.data)i.push({key:a._parse(new mr(n,s,n.path,s)),value:o._parse(new mr(n,n.data[s],n.path,s)),alwaysSet:s in n.data});return n.common.async?gt.mergeObjectAsync(r,i):gt.mergeObjectSync(r,i)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof ae?new t({keyType:e,valueType:r,typeName:M.ZodRecord,...re(n)}):new t({keyType:Hn.create(),valueType:e,typeName:M.ZodRecord,...re(r)})}},ao=class extends ae{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==L.map)return z(n,{code:N.invalid_type,expected:L.map,received:n.parsedType}),W;let i=this._def.keyType,a=this._def.valueType,o=[...n.data.entries()].map(([s,c],l)=>({key:i._parse(new mr(n,s,n.path,[l,"key"])),value:a._parse(new mr(n,c,n.path,[l,"value"]))}));if(n.common.async){let s=new Map;return Promise.resolve().then(async()=>{for(let c of o){let l=await c.key,u=await c.value;if(l.status==="aborted"||u.status==="aborted")return W;(l.status==="dirty"||u.status==="dirty")&&r.dirty(),s.set(l.value,u.value)}return{status:r.value,value:s}})}else{let s=new Map;for(let c of o){let l=c.key,u=c.value;if(l.status==="aborted"||u.status==="aborted")return W;(l.status==="dirty"||u.status==="dirty")&&r.dirty(),s.set(l.value,u.value)}return{status:r.value,value:s}}}};ao.create=(t,e,r)=>new ao({valueType:e,keyType:t,typeName:M.ZodMap,...re(r)});var oo=class t extends ae{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==L.set)return z(n,{code:N.invalid_type,expected:L.set,received:n.parsedType}),W;let i=this._def;i.minSize!==null&&n.data.size<i.minSize.value&&(z(n,{code:N.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),r.dirty()),i.maxSize!==null&&n.data.size>i.maxSize.value&&(z(n,{code:N.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),r.dirty());let a=this._def.valueType;function o(c){let l=new Set;for(let u of c){if(u.status==="aborted")return W;u.status==="dirty"&&r.dirty(),l.add(u.value)}return{status:r.value,value:l}}let s=[...n.data.values()].map((c,l)=>a._parse(new mr(n,c,n.path,l)));return n.common.async?Promise.all(s).then(c=>o(c)):o(s)}min(e,r){return new t({...this._def,minSize:{value:e,message:q.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:q.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};oo.create=(t,e)=>new oo({valueType:t,minSize:null,maxSize:null,typeName:M.ZodSet,...re(e)});var mp=class t extends ae{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==L.function)return z(r,{code:N.invalid_type,expected:L.function,received:r.parsedType}),W;function n(s,c){return nc({data:s,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,eo(),yn].filter(l=>!!l),issueData:{code:N.invalid_arguments,argumentsError:c}})}function i(s,c){return nc({data:s,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,eo(),yn].filter(l=>!!l),issueData:{code:N.invalid_return_type,returnTypeError:c}})}let a={errorMap:r.common.contextualErrorMap},o=r.data;if(this._def.returns instanceof Wn){let s=this;return _t(async function(...c){let l=new Zt([]),u=await s._def.args.parseAsync(c,a).catch(h=>{throw l.addIssue(n(c,h)),l}),p=await Reflect.apply(o,this,u);return await s._def.returns._def.type.parseAsync(p,a).catch(h=>{throw l.addIssue(i(p,h)),l})})}else{let s=this;return _t(function(...c){let l=s._def.args.safeParse(c,a);if(!l.success)throw new Zt([n(c,l.error)]);let u=Reflect.apply(o,this,l.data),p=s._def.returns.safeParse(u,a);if(!p.success)throw new Zt([i(u,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:Xr.create(e).rest(vn.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||Xr.create([]).rest(vn.create()),returns:r||vn.create(),typeName:M.ZodFunction,...re(n)})}},Ui=class extends ae{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};Ui.create=(t,e)=>new Ui({getter:t,typeName:M.ZodLazy,...re(e)});var Ji=class extends ae{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return z(r,{received:r.data,code:N.invalid_literal,expected:this._def.value}),W}return{status:"valid",value:e.data}}get value(){return this._def.value}};Ji.create=(t,e)=>new Ji({value:t,typeName:M.ZodLiteral,...re(e)});function dP(t,e){return new Zi({values:t,typeName:M.ZodEnum,...re(e)})}var Zi=class t extends ae{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return z(r,{expected:de.joinValues(n),received:r.parsedType,code:N.invalid_type}),W}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return z(r,{received:r.data,code:N.invalid_enum_value,options:n}),W}return _t(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};Zi.create=dP;var Hi=class extends ae{_parse(e){let r=de.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==L.string&&n.parsedType!==L.number){let i=de.objectValues(r);return z(n,{expected:de.joinValues(i),received:n.parsedType,code:N.invalid_type}),W}if(this._cache||(this._cache=new Set(de.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let i=de.objectValues(r);return z(n,{received:n.data,code:N.invalid_enum_value,options:i}),W}return _t(e.data)}get enum(){return this._def.values}};Hi.create=(t,e)=>new Hi({values:t,typeName:M.ZodNativeEnum,...re(e)});var Wn=class extends ae{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==L.promise&&r.common.async===!1)return z(r,{code:N.invalid_type,expected:L.promise,received:r.parsedType}),W;let n=r.parsedType===L.promise?r.data:Promise.resolve(r.data);return _t(n.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Wn.create=(t,e)=>new Wn({type:t,typeName:M.ZodPromise,...re(e)});var hr=class extends ae{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===M.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),i=this._def.effect||null,a={addIssue:o=>{z(n,o),o.fatal?r.abort():r.dirty()},get path(){return n.path}};if(a.addIssue=a.addIssue.bind(a),i.type==="preprocess"){let o=i.transform(n.data,a);if(n.common.async)return Promise.resolve(o).then(async s=>{if(r.value==="aborted")return W;let c=await this._def.schema._parseAsync({data:s,path:n.path,parent:n});return c.status==="aborted"?W:c.status==="dirty"?Mi(c.value):r.value==="dirty"?Mi(c.value):c});{if(r.value==="aborted")return W;let s=this._def.schema._parseSync({data:o,path:n.path,parent:n});return s.status==="aborted"?W:s.status==="dirty"?Mi(s.value):r.value==="dirty"?Mi(s.value):s}}if(i.type==="refinement"){let o=s=>{let c=i.refinement(s,a);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 s};if(n.common.async===!1){let s=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?W:(s.status==="dirty"&&r.dirty(),o(s.value),{status:r.value,value:s.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(s=>s.status==="aborted"?W:(s.status==="dirty"&&r.dirty(),o(s.value).then(()=>({status:r.value,value:s.value}))))}if(i.type==="transform")if(n.common.async===!1){let o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Zn(o))return W;let s=i.transform(o.value,a);if(s instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:s}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>Zn(o)?Promise.resolve(i.transform(o.value,a)).then(s=>({status:r.value,value:s})):W);de.assertNever(i)}};hr.create=(t,e,r)=>new hr({schema:t,typeName:M.ZodEffects,effect:e,...re(r)});hr.createWithPreprocess=(t,e,r)=>new hr({schema:e,effect:{type:"preprocess",transform:t},typeName:M.ZodEffects,...re(r)});var Ht=class extends ae{_parse(e){return this._getType(e)===L.undefined?_t(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Ht.create=(t,e)=>new Ht({innerType:t,typeName:M.ZodOptional,...re(e)});var Yr=class extends ae{_parse(e){return this._getType(e)===L.null?_t(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Yr.create=(t,e)=>new Yr({innerType:t,typeName:M.ZodNullable,...re(e)});var Ki=class extends ae{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===L.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};Ki.create=(t,e)=>new Ki({innerType:t,typeName:M.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...re(e)});var Wi=class extends ae{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},i=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return to(i)?i.then(a=>({status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new Zt(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Zt(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Wi.create=(t,e)=>new Wi({innerType:t,typeName:M.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...re(e)});var so=class extends ae{_parse(e){if(this._getType(e)!==L.nan){let n=this._getOrReturnCtx(e);return z(n,{code:N.invalid_type,expected:L.nan,received:n.parsedType}),W}return{status:"valid",value:e.data}}};so.create=t=>new so({typeName:M.ZodNaN,...re(t)});var _q=Symbol("zod_brand"),ic=class extends ae{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},ac=class t extends ae{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let a=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?W:a.status==="dirty"?(r.dirty(),Mi(a.value)):this._def.out._parseAsync({data:a.value,path:n.path,parent:n})})();{let i=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?W:i.status==="dirty"?(r.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:M.ZodPipeline})}},Gi=class extends ae{_parse(e){let r=this._def.innerType._parse(e),n=i=>(Zn(i)&&(i.value=Object.freeze(i.value)),i);return to(r)?r.then(i=>n(i)):n(r)}unwrap(){return this._def.innerType}};Gi.create=(t,e)=>new Gi({innerType:t,typeName:M.ZodReadonly,...re(e)});function cP(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function fP(t,e={},r){return t?Kn.create().superRefine((n,i)=>{let a=t(n);if(a instanceof Promise)return a.then(o=>{if(!o){let s=cP(e,n),c=s.fatal??r??!0;i.addIssue({code:"custom",...s,fatal:c})}});if(!a){let o=cP(e,n),s=o.fatal??r??!0;i.addIssue({code:"custom",...o,fatal:s})}}):Kn.create()}var Sq={object:Kt.lazycreate},M;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(M||(M={}));var Eq=(t,e={message:`Input not instance of ${t.name}`})=>fP(r=>r instanceof t,e),mP=Hn.create,hP=Di.create,kq=so.create,Tq=Fi.create,gP=zi.create,Cq=Li.create,Pq=no.create,Aq=ji.create,Iq=Vi.create,Rq=Kn.create,$q=vn.create,Oq=Rr.create,Nq=io.create,Mq=xn.create,eb=Kt.create,Dq=Kt.strictCreate,Fq=qi.create,zq=dp.create,Lq=Bi.create,jq=Xr.create,Vq=fp.create,qq=ao.create,Bq=oo.create,Uq=mp.create,Jq=Ui.create,Zq=Ji.create,Hq=Zi.create,Kq=Hi.create,Wq=Wn.create,Gq=hr.create,Xq=Ht.create,Yq=Yr.create,Qq=hr.createWithPreprocess,eB=ac.create,tB=()=>mP().optional(),rB=()=>hP().optional(),nB=()=>gP().optional(),iB={string:t=>Hn.create({...t,coerce:!0}),number:t=>Di.create({...t,coerce:!0}),boolean:t=>zi.create({...t,coerce:!0}),bigint:t=>Fi.create({...t,coerce:!0}),date:t=>Li.create({...t,coerce:!0})};var aB=W;var sB=R("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");Pe.init(t,e),t.def=e,t.parse=(r,n)=>Xd(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>mi(t,r,n),t.parseAsync=async(r,n)=>Qd(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>hi(t,r,n),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>rr(t,r,n),t.brand=()=>t,t.register=(r,n)=>(r.add(t,n),t)});var cB=R("ZodMiniObject",(t,e)=>{il.init(t,e),sB.init(t,e),fe.defineLazy(t,"shape",()=>e.shape)});function tb(t,e){let r={type:"object",get shape(){return fe.assignProp(this,"shape",{...t}),this.shape},...fe.normalizeParams(e)};return new cB(r)}function gr(t){return!!t._zod}function Xi(t){let e=Object.values(t);if(e.length===0)return tb({});let r=e.every(gr),n=e.every(i=>!gr(i));if(r)return tb(t);if(n)return eb(t);throw new Error("Mixed Zod versions detected in object shape.")}function Gn(t,e){return gr(t)?mi(t,e):t.safeParse(e)}async function hp(t,e){return gr(t)?await hi(t,e):await t.safeParseAsync(e)}function Xn(t){if(!t)return;let e;if(gr(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function co(t){if(t){if(typeof t=="object"){let e=t,r=t;if(!e._def&&!r._zod){let n=Object.values(t);if(n.length>0&&n.every(i=>typeof i=="object"&&i!==null&&(i._def!==void 0||i._zod!==void 0||typeof i.parse=="function")))return Xi(t)}}if(gr(t)){let r=t._zod?.def;if(r&&(r.type==="object"||r.shape!==void 0))return t}else if(t.shape!==void 0)return t}}function gp(t){if(t&&typeof t=="object"){if("message"in t&&typeof t.message=="string")return t.message;if("issues"in t&&Array.isArray(t.issues)&&t.issues.length>0){let e=t.issues[0];if(e&&typeof e=="object"&&"message"in e)return String(e.message)}try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function yP(t){return t.description}function bP(t){if(gr(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function yp(t){if(gr(t)){let a=t._zod?.def;if(a){if(a.value!==void 0)return a.value;if(Array.isArray(a.values)&&a.values.length>0)return a.values[0]}}let r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=t.value;if(n!==void 0)return n}function Yn(t){return t==="completed"||t==="failed"||t==="cancelled"}var xP=Symbol("Let zodToJsonSchema decide on which parser to use");var vP={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},wP=t=>typeof t=="string"?{...vP,name:t}:{...vP,...t};var _P=t=>{let e=wP(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,i])=>[i._def,{def:i._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}};function rb(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function ye(t,e,r,n,i){t[e]=r,rb(t,e,n,i)}var bp=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")};function Je(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?bp(e,t.currentPath):e.join("/")}}function SP(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==M.ZodAny&&(r.items=G(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&ye(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&ye(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(ye(r,"minItems",t.exactLength.value,t.exactLength.message,e),ye(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function EP(t,e){let r={type:"integer",format:"int64"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?ye(r,"minimum",n.value,n.message,e):ye(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ye(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ye(r,"maximum",n.value,n.message,e):ye(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ye(r,"maximum",n.value,n.message,e));break;case"multipleOf":ye(r,"multipleOf",n.value,n.message,e);break}return r}function kP(){return{type:"boolean"}}function vp(t,e){return G(t.type._def,e)}var TP=(t,e)=>G(t.innerType._def,e);function nb(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((i,a)=>nb(t,e,i))};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 uB(t,e)}}var uB=(t,e)=>{let r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(let n of t.checks)switch(n.kind){case"min":ye(r,"minimum",n.value,n.message,e);break;case"max":ye(r,"maximum",n.value,n.message,e);break}return r};function CP(t,e){return{...G(t.innerType._def,e),default:t.defaultValue()}}function PP(t,e){return e.effectStrategy==="input"?G(t.schema._def,e):Je(e)}function AP(t){return{type:"string",enum:Array.from(t.values)}}var pB=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function IP(t,e){let r=[G(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),G(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(a=>!!a),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,i=[];return r.forEach(a=>{if(pB(a))i.push(...a.allOf),a.unevaluatedProperties===void 0&&(n=void 0);else{let o=a;if("additionalProperties"in a&&a.additionalProperties===!1){let{additionalProperties:s,...c}=a;o=c}else n=void 0;i.push(o)}}),i.length?{allOf:i,...n}:void 0}function RP(t,e){let r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[t.value]}:{type:r==="bigint"?"integer":r,const:t.value}}var ib,$r={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:()=>(ib===void 0&&(ib=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),ib),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 xp(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":ye(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":ye(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":Or(r,"email",n.message,e);break;case"format:idn-email":Or(r,"idn-email",n.message,e);break;case"pattern:zod":Nt(r,$r.email,n.message,e);break}break;case"url":Or(r,"uri",n.message,e);break;case"uuid":Or(r,"uuid",n.message,e);break;case"regex":Nt(r,n.regex,n.message,e);break;case"cuid":Nt(r,$r.cuid,n.message,e);break;case"cuid2":Nt(r,$r.cuid2,n.message,e);break;case"startsWith":Nt(r,RegExp(`^${ab(n.value,e)}`),n.message,e);break;case"endsWith":Nt(r,RegExp(`${ab(n.value,e)}$`),n.message,e);break;case"datetime":Or(r,"date-time",n.message,e);break;case"date":Or(r,"date",n.message,e);break;case"time":Or(r,"time",n.message,e);break;case"duration":Or(r,"duration",n.message,e);break;case"length":ye(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),ye(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{Nt(r,RegExp(ab(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&Or(r,"ipv4",n.message,e),n.version!=="v4"&&Or(r,"ipv6",n.message,e);break}case"base64url":Nt(r,$r.base64url,n.message,e);break;case"jwt":Nt(r,$r.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&Nt(r,$r.ipv4Cidr,n.message,e),n.version!=="v4"&&Nt(r,$r.ipv6Cidr,n.message,e);break}case"emoji":Nt(r,$r.emoji(),n.message,e);break;case"ulid":{Nt(r,$r.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Or(r,"binary",n.message,e);break}case"contentEncoding:base64":{ye(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{Nt(r,$r.base64,n.message,e);break}}break}case"nanoid":Nt(r,$r.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function ab(t,e){return e.patternStrategy==="escape"?fB(t):t}var dB=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function fB(t){let e="";for(let r=0;r<t.length;r++)dB.has(t[r])||(e+="\\"),e+=t[r];return e}function Or(t,e,r,n){t.format||t.anyOf?.some(i=>i.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):ye(t,"format",e,r,n)}function Nt(t,e,r,n){t.pattern||t.allOf?.some(i=>i.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:$P(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):ye(t,"pattern",$P(e,n),r,n)}function $P(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;let r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=r.i?t.source.toLowerCase():t.source,i="",a=!1,o=!1,s=!1;for(let c=0;c<n.length;c++){if(a){i+=n[c],a=!1;continue}if(r.i){if(o){if(n[c].match(/[a-z]/)){s?(i+=n[c],i+=`${n[c-2]}-${n[c]}`.toUpperCase(),s=!1):n[c+1]==="-"&&n[c+2]?.match(/[a-z]/)?(i+=n[c],s=!0):i+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){i+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(r.m){if(n[c]==="^"){i+=`(^|(?<=[\r
|
|
126
|
+
`).trim()}function Ky(t){return t?.V8Limit!==void 0&&t.V8Limit!==null?Number(t.V8Limit)===1?1:0:t?.V8Unlimited!==void 0&&t.V8Unlimited!==null?Number(t.V8Unlimited)===1?0:1:0}function Gy(t){if(Array.isArray(t))return t.map(Gy);if(!t||typeof t!="object")return t;let e=Object.entries(t).filter(([r])=>!r.startsWith("_")).sort(([r],[n])=>r.localeCompare(n));return Object.fromEntries(e.map(([r,n])=>[r,Gy(n)]))}function rP(t){try{let e=typeof t=="string"?JSON.parse(t):t;return JSON.stringify(Gy(e))}catch{return}}function GV(t,e){let r=new Set(["OsClient","ModuleId","Id"]),n=[];for(let[i,a]of Object.entries(t)){if(r.has(i)||a===void 0)continue;let o=e[i];if(HV.has(i)||i==="ViewSchema"){let s=rP(a),c=rP(o);(!s||!c||s!==c)&&n.push(i);continue}String(a??"")!==String(o??"")&&n.push(i)}return{matched:n.length===0,mismatches:n}}var rc=class{config;token="";refreshTimer;rsaPublicKey;did;requestTimeoutMs;writeRequestTimeoutMs;readbackRequestTimeoutMs;inflightRefresh;inflightAuthRecovery;inflightCredentialRecovery;constructor(e){this.config=e,this.reloadWorkspaceCredentials(),this.rsaPublicKey=e.rsaPublicKey||DV,this.did=B8(process.env.MICROI_MCP_DID,nP.default.hostname()),this.requestTimeoutMs=op(e.requestTimeoutMs??process.env.MICROI_MCP_HTTP_TIMEOUT_MS,LV),this.writeRequestTimeoutMs=op(e.writeRequestTimeoutMs??process.env.MICROI_MCP_WRITE_TIMEOUT_MS,jV),this.readbackRequestTimeoutMs=op(e.readbackRequestTimeoutMs??process.env.MICROI_MCP_READBACK_TIMEOUT_MS,VV),e.token&&(this.token=ar(e.token))}rsaEncrypt(e){let r=(this.rsaPublicKey||"").trim();return r?hn.default.publicEncrypt({key:r,padding:hn.default.constants.RSA_PKCS1_PADDING},Buffer.from(e,"utf-8")).toString("base64"):e}updateToken(e){this.token=ar(e)}async login(e){if(this.token){this.startAutoRefresh(),console.error("[microi-mcp] Using provided token (auto-refresh enabled)");return}if(this.reloadWorkspaceCredentials(),!this.config.username||!this.config.password)throw new Error("Login credentials are unavailable from environment or workspace protected storage");let r=this.rsaEncrypt(this.config.password),n=new URLSearchParams;n.append("Account",this.config.username),n.append("Pwd",r),this.config.osClient&&n.append("OsClient",this.config.osClient),n.append("_ClientType","MCP");let i=await fetch(`${this.config.apiBaseUrl}${O.LOGIN}`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",did:this.did,...this.config.osClient?{OsClient:this.config.osClient}:{}},body:n.toString()}),a=i.headers.get("authorization")||"",o=await i.text();if(!i.ok||!o)throw new Error(`Login failed: HTTP ${i.status} \u2014 ${o?.slice(0,200)||"empty response"}`);let s;try{s=JSON.parse(o)}catch{throw new Error(`Login failed: invalid JSON \u2014 ${o.slice(0,200)}`)}if(s.Code!==1)throw new Error(`Login failed: ${s.Msg||"Unknown error"}`);if(!a)throw new Error("Login succeeded but no token in response header");this.token=ar(a),this.startAutoRefresh(),console.error("[microi-mcp] Login successful")}startAutoRefresh(){this.refreshTimer&&clearInterval(this.refreshTimer),this.refreshTimer=setInterval(()=>{J8(this.token)&&this.refreshTokenNow().catch(e=>console.error("[microi-mcp] Token refresh failed:",e))},60*60*1e3)}async refreshTokenNow(){return this.inflightRefresh?this.inflightRefresh:this.token?(this.inflightRefresh=(async()=>{try{let e=await fetch(`${this.config.apiBaseUrl}${O.REFRESH_TOKEN}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`,did:this.did,...this.config.osClient?{OsClient:this.config.osClient}:{}},body:JSON.stringify({authorization:this.token,OsClient:this.config.osClient||void 0,_ClientType:"MCP"})}),r=e.headers.get("authorization"),n=await e.text(),i=null;try{i=JSON.parse(n)}catch{}return r&&i?.Code===1?(this.token=ar(r),this.writeTokenToFile(),console.error("[microi-mcp] Token refreshed"),!0):(console.error(`[microi-mcp] Refresh rejected: Code=${i?.Code} Msg=${i?.Msg||""}`),!1)}catch(e){return console.error("[microi-mcp] Refresh request error:",e),!1}finally{this.inflightRefresh=void 0}})(),this.inflightRefresh):!1}reloadTokenFromFile(){let e=this.config.tokenFilePath;if(!e)return!1;try{let r=JSON.parse(Ot.default.readFileSync(e,"utf-8")),n=lp(this.config.apiBaseUrl,this.config.osClient,this.config.osClientType,this.config.osClientNetwork),i=String(this.config.apiBaseUrl||"").replace(/\/+$/,""),a=this.config.osClient?n.filter(c=>c!==i):n,o=np(a.map(c=>r[c]))||r[i],s=ar(o);if(s&&s!==this.token)return this.token=s,!0}catch{}return!1}writeTokenToFile(){let e=this.config.tokenFilePath;if(!(!e||!this.token))try{let r={};try{r=JSON.parse(Ot.default.readFileSync(e,"utf-8"))}catch{}let[n]=lp(this.config.apiBaseUrl,this.config.osClient,this.config.osClientType,this.config.osClientNetwork);if(!n)return;r[n]=this.token;let i=tc.default.dirname(e);Ot.default.existsSync(i)||Ot.default.mkdirSync(i,{recursive:!0}),Ot.default.writeFileSync(e,JSON.stringify(r,null,2),{encoding:"utf-8",mode:384})}catch(r){console.error("[microi-mcp] Write token file failed:",r)}}async requestVsCodeCredentialRecovery(e){let r=this.config.authRecoveryRequestDir,n=this.config.tokenFilePath;if(!r||!n)return!1;try{Ot.default.existsSync(r)||Ot.default.mkdirSync(r,{recursive:!0});let i=this.config.apiBaseUrl.replace(/\/+$/,""),a=this.config.osClient||"",o=this.config.osClientType||"",s=this.config.osClientNetwork||"",c=`${i}|${a}|${o}|${s}`,u=`${hn.default.createHash("sha256").update(c).digest("hex").slice(0,24)}-${process.pid}-${Date.now()}-${hn.default.randomBytes(4).toString("hex")}.json`,p=tc.default.join(r,u),f=`${p}.${process.pid}.tmp`,h={version:1,apiBaseUrl:i,osClient:a,osClientType:o,osClientNetwork:s,requestedAt:Date.now(),failedTokenHash:hn.default.createHash("sha256").update(e||"").digest("hex")};Ot.default.writeFileSync(f,JSON.stringify(h),{encoding:"utf-8",mode:384}),Ot.default.renameSync(f,p);for(let m=0;m<40;m++)if(await new Promise(g=>setTimeout(g,250)),this.reloadTokenFromFile())return console.error("[microi-mcp] Token recovered by VS Code SecretStorage broker"),!0}catch(i){console.error("[microi-mcp] VS Code credential recovery request failed:",i)}return!1}async tryRecoverFromAuthFailure(e,r=!1){if(this.token&&e&&this.token!==e)return!0;if(r){if(this.inflightCredentialRecovery)return this.inflightCredentialRecovery;let n=this.inflightAuthRecovery;this.inflightCredentialRecovery=(async()=>(n&&await n,this.token&&e&&this.token!==e?!0:this.tryRecoverFromAuthFailureCore(e,!0)))();try{return await this.inflightCredentialRecovery}finally{this.inflightCredentialRecovery=void 0}}if(this.inflightCredentialRecovery)return this.inflightCredentialRecovery;if(this.inflightAuthRecovery)return this.inflightAuthRecovery;this.inflightAuthRecovery=this.tryRecoverFromAuthFailureCore(e,!1);try{return await this.inflightAuthRecovery}finally{this.inflightAuthRecovery=void 0}}async tryRecoverFromAuthFailureCore(e,r){if(this.token&&e&&this.token!==e)return!0;if(this.reloadTokenFromFile())return console.error("[microi-mcp] Token reloaded from file after auth failure"),!0;if(!r&&await this.refreshTokenNow())return!0;if(this.reloadWorkspaceCredentials(),this.config.username&&this.config.password)try{if(this.token="",await this.login(),this.token&&this.token!==e)return this.writeTokenToFile(),console.error("[microi-mcp] Re-logged in after auth failure"),!0}catch(n){this.token=e,console.error("[microi-mcp] Re-login failed:",n)}return this.requestVsCodeCredentialRecovery(e)}reloadWorkspaceCredentials(){let e=Q8({filePath:this.config.workspaceCredentialFilePath,usernameKey:this.config.workspaceCredentialUsernameKey,passwordKey:this.config.workspaceCredentialPasswordKey});return e?(this.config.username=e.username,this.config.password=e.password,!0):!1}async post(e,r,n={}){return this.requestJson("POST",e,r,void 0,"initial",n)}async get(e,r,n={}){return this.requestJson("GET",e,void 0,r,"initial",n)}async requestJson(e,r,n,i,a="initial",o={}){let s=`${this.config.apiBaseUrl}${r}`;if(e==="GET"&&i){let b=new URLSearchParams(i).toString();b&&(s+=`?${b}`)}let c=this.token,l={Authorization:`Bearer ${c}`,did:this.did};this.config.osClient&&(l.OsClient=this.config.osClient),e==="POST"&&(l["Content-Type"]="application/json");let u=op(o.timeoutMs,this.requestTimeoutMs,o.maxTimeoutMs),p=o.operationName||`${e} ${r}`,f=new AbortController,h=setTimeout(()=>f.abort(),u),m,g,y=e==="POST"?JSON.stringify(n??{}):void 0;try{let b=await fetch(s,{method:e,headers:l,signal:f.signal,...y!==void 0?{body:y}:{}});m=b,g=await b.text()}catch(b){if(f.signal.aborted)throw new gn(`${p} \u8BF7\u6C42\u8D85\u65F6\uFF08${u}ms\uFF09`,{kind:"timeout",requestPath:r,uncertainOutcome:e==="POST",cause:b});try{await new Promise(S=>setTimeout(S,250));let E=await this.requestJsonNative(e,s,l,y,u);m=E.res,g=E.text}catch(E){let S=b instanceof Error?b.message:String(b),T=E instanceof Error?E.message:String(E);throw new gn(`${p} \u7F51\u7EDC\u8BF7\u6C42\u5931\u8D25\uFF1Afetch=${S}\uFF1Bnative=${T}`,{kind:"network",requestPath:r,uncertainOutcome:e==="POST",cause:E})}}finally{clearTimeout(h)}let v=m.headers.get("authorization");if(v&&(this.token=ar(v),this.writeTokenToFile()),m.status===401&&a!=="credential-token"){let b=a!=="initial";if(b&&console.error("[microi-mcp] Replacement token was rejected; escalating to credential recovery"),await this.tryRecoverFromAuthFailure(c,b))return this.requestJson(e,r,n,i,Ya(a),o);throw new Error(`HTTP 401 Unauthorized \u2014 token recovery failed: ${g.slice(0,200)}`)}if(!m.ok)throw new Error(`HTTP ${m.status} ${m.statusText} \u2014 ${g.slice(0,200)}`);if(!g)throw new Error(`HTTP ${m.status} \u2014 empty response body`);let x;try{x=JSON.parse(g)}catch{throw new Error(`HTTP ${m.status} \u2014 invalid JSON: ${g.slice(0,200)}`)}if(Hy(x)&&a!=="credential-token"){console.error(`[microi-mcp] Auth expired (Code=${x.Code}: ${x.Msg||""}), attempting recovery...`);let b=a!=="initial";if(b&&console.error("[microi-mcp] Replacement token was rejected; escalating to credential recovery"),await this.tryRecoverFromAuthFailure(c,b))return this.requestJson(e,r,n,i,Ya(a),o)}return x}async requestMultipartFile(e,r,n,i,a="initial",o,s){let c=this.token,l=s==="gzip"?{...r,ContentEncoding:"gzip"}:r,u=`----microi-mcp-${hn.default.randomBytes(24).toString("hex")}`,p=tP(l,n,i,u,s),f=new AbortController,h=eP(o),m=setTimeout(()=>f.abort(),h),g,y;try{let b=await fetch(`${this.config.apiBaseUrl}${e}`,{method:"POST",headers:{Authorization:`Bearer ${c}`,did:this.did,...this.config.osClient?{OsClient:this.config.osClient}:{},"Content-Type":`multipart/form-data; boundary=${u}`},body:p.body,duplex:"half",signal:f.signal});g=b,y=await b.text()}catch(b){if(f.signal.aborted)throw new gn(`\u5E94\u7528\u8D44\u4EA7\u6D41\u5F0F\u4E0A\u4F20\u8D85\u65F6\uFF08${h}ms\uFF09`,{kind:"timeout",requestPath:e,uncertainOutcome:!0,cause:b});try{await new Promise(S=>setTimeout(S,250));let E=await this.requestMultipartFileNative(e,l,n,i,h,s);g=E.res,y=E.text}catch(E){let S=b instanceof Error?b.message:String(b),T=E instanceof Error?E.message:String(E);if(s!=="gzip")try{return await this.requestMultipartFile(e,r,n,i,a,o,"gzip")}catch(C){let $=C instanceof Error?C.message:String(C);throw new gn(`\u5E94\u7528\u8D44\u4EA7\u6D41\u5F0F\u4E0A\u4F20\u7F51\u7EDC\u5931\u8D25\uFF1Afetch=${S}\uFF1Bnative=${T}\uFF1Bgzip=${$}`,{kind:"network",requestPath:e,uncertainOutcome:!0,cause:C})}throw new gn(`\u5E94\u7528\u8D44\u4EA7 gzip \u6D41\u5F0F\u4E0A\u4F20\u7F51\u7EDC\u5931\u8D25\uFF1Afetch=${S}\uFF1Bnative=${T}`,{kind:"network",requestPath:e,uncertainOutcome:!0,cause:E})}}finally{clearTimeout(m),p.body.destroy()}let v=g.headers.get("authorization");if(v&&(this.token=ar(v),this.writeTokenToFile()),g.status===401&&a!=="credential-token"){let b=a!=="initial";if(b&&console.error("[microi-mcp] Replacement token was rejected; escalating to credential recovery"),await this.tryRecoverFromAuthFailure(c,b))return this.requestMultipartFile(e,r,n,i,Ya(a),o,s);throw new Error(`HTTP 401 Unauthorized \u2014 token recovery failed: ${y.slice(0,200)}`)}if(!g.ok)throw new Error(`HTTP ${g.status} ${g.statusText} \u2014 ${y.slice(0,200)}`);if(!y)throw new Error(`HTTP ${g.status} \u2014 empty response body`);let x;try{x=JSON.parse(y)}catch{throw new Error(`HTTP ${g.status} \u2014 invalid JSON: ${y.slice(0,200)}`)}if(Hy(x)&&a!=="credential-token"){let b=a!=="initial";if(b&&console.error("[microi-mcp] Replacement token was rejected; escalating to credential recovery"),await this.tryRecoverFromAuthFailure(c,b))return this.requestMultipartFile(e,r,n,i,Ya(a),o,s)}return x}async requestJsonNative(e,r,n,i,a){let o=new URL(r),s=o.protocol==="https:"?cp.default:sp.default,c=i===void 0?void 0:Buffer.from(i,"utf8");return new Promise((l,u)=>{let p=!1,f=m=>{p||(p=!0,u(m))},h=s.request({protocol:o.protocol,hostname:o.hostname,port:o.port||void 0,path:`${o.pathname}${o.search}`,method:e,timeout:a,headers:{...n,...c?{"Content-Length":String(c.length)}:{}}},m=>{let g=[];m.on("data",y=>g.push(Buffer.isBuffer(y)?y:Buffer.from(y))),m.on("end",()=>{if(p)return;p=!0;let y=m.statusCode||0,v={get(x){let b=m.headers[x.toLowerCase()];return Array.isArray(b)?b.join(", "):b===void 0?null:String(b)}};l({res:{status:y,statusText:m.statusMessage||"",ok:y>=200&&y<300,headers:v},text:Buffer.concat(g).toString("utf8")})})});h.on("error",m=>f(new Error(m.message,{cause:m}))),h.on("timeout",()=>{h.destroy(),f(new Error(`native request timeout (${a}ms)`))}),c&&h.write(c),h.end()})}async requestMultipartFileNative(e,r,n,i,a,o){let s=`----microi-mcp-native-${hn.default.randomBytes(24).toString("hex")}`,c=tP(r,n,i,s,o),l=new URL(`${this.config.apiBaseUrl}${e}`),u=l.protocol==="https:"?cp.default:sp.default;try{return await new Promise((p,f)=>{let h=!1,m=y=>{h||(h=!0,f(y))},g=u.request({protocol:l.protocol,hostname:l.hostname,port:l.port||void 0,path:`${l.pathname}${l.search}`,method:"POST",timeout:a,headers:{Authorization:`Bearer ${this.token}`,did:this.did,...this.config.osClient?{OsClient:this.config.osClient}:{},"Content-Type":`multipart/form-data; boundary=${s}`}},y=>{let v=[];y.on("data",x=>v.push(Buffer.isBuffer(x)?x:Buffer.from(x))),y.on("end",()=>{if(h)return;h=!0;let x=y.statusCode||0,b={get(_){let E=y.headers[_.toLowerCase()];return Array.isArray(E)?E.join(", "):E===void 0?null:String(E)}};p({res:{status:x,statusText:y.statusMessage||"",ok:x>=200&&x<300,headers:b},text:Buffer.concat(v).toString("utf8")})})});g.on("error",y=>m(new Error(y.message,{cause:y}))),g.on("timeout",()=>{g.destroy(),m(new Error(`native request timeout (${a}ms)`))}),c.body.on("error",y=>{g.destroy(),m(new Error(`local asset stream failed: ${y.message}`,{cause:y}))}),c.body.pipe(g)})}finally{c.body.destroy()}}async requestBinaryFileRange(e,r,n,i,a,o="initial",s){if(!Number.isSafeInteger(i)||i<0||!Number.isSafeInteger(a)||a<0)throw new Error("\u65AD\u70B9\u5206\u7247 start/length \u5FC5\u987B\u662F\u975E\u8D1F JavaScript \u5B89\u5168\u6574\u6570");let c=new URL(`${this.config.apiBaseUrl}${e}`);for(let[g,y]of Object.entries(r))c.searchParams.set(g,y);let l=this.token,u=eP(s),p=c.protocol==="https:"?cp.default:sp.default,f=await new Promise((g,y)=>{let v=!1,x=E=>{v||(v=!0,y(E))},b=p.request({protocol:c.protocol,hostname:c.hostname,port:c.port||void 0,path:`${c.pathname}${c.search}`,method:"POST",timeout:u,headers:{Authorization:`Bearer ${l}`,did:this.did,...this.config.osClient?{OsClient:this.config.osClient}:{},"Content-Type":"application/octet-stream","Content-Length":String(a)}},E=>{let S=[];E.on("data",T=>S.push(Buffer.isBuffer(T)?T:Buffer.from(T))),E.on("end",()=>{if(v)return;v=!0;let T=E.statusCode||0,C={get($){let P=E.headers[$.toLowerCase()];return Array.isArray(P)?P.join(", "):P===void 0?null:String(P)}};g({status:T,statusText:E.statusMessage||"",headers:C,text:Buffer.concat(S).toString("utf8")})})});if(b.on("error",E=>x(new Error(E.message,{cause:E}))),b.on("timeout",()=>{b.destroy(),x(new Error(`\u65AD\u70B9\u5206\u7247\u7F51\u7EDC\u8D85\u65F6\uFF08${u}ms\uFF09`))}),a===0){b.end();return}let _=Ot.default.createReadStream(n,{start:i,end:i+a-1});_.on("error",E=>{b.destroy(),x(new Error(`\u8BFB\u53D6\u672C\u5730\u5206\u7247\u5931\u8D25\uFF1A${E.message}`,{cause:E}))}),_.pipe(b)}).catch(g=>{throw new gn(`\u65AD\u70B9\u5206\u7247\u4E0A\u4F20\u7F51\u7EDC\u5931\u8D25\uFF1A${g instanceof Error?g.message:String(g)}`,{kind:/超时/u.test(String(g))?"timeout":"network",requestPath:e,uncertainOutcome:!0,cause:g})}),h=f.headers.get("authorization");if(h&&(this.token=ar(h),this.writeTokenToFile()),f.status===401&&o!=="credential-token"){let g=o!=="initial";if(await this.tryRecoverFromAuthFailure(l,g))return this.requestBinaryFileRange(e,r,n,i,a,Ya(o),s);throw new Error(`HTTP 401 Unauthorized \u2014 token recovery failed: ${f.text.slice(0,200)}`)}if(f.status<200||f.status>=300)throw new Error(`HTTP ${f.status} ${f.statusText} \u2014 ${f.text.slice(0,200)}`);if(!f.text)throw new Error(`HTTP ${f.status} \u2014 empty response body`);let m;try{m=JSON.parse(f.text)}catch{throw new Error(`HTTP ${f.status} \u2014 invalid JSON: ${f.text.slice(0,200)}`)}if(Hy(m)&&o!=="credential-token"){let g=o!=="initial";if(await this.tryRecoverFromAuthFailure(l,g))return this.requestBinaryFileRange(e,r,n,i,a,Ya(o),s)}return m}isUncertainWriteError(e){return e instanceof gn&&e.uncertainOutcome}readbackOptions(e){return{timeoutMs:this.readbackRequestTimeoutMs,operationName:e}}async pollReadback(e,r){let n,i="";for(let a of qV){a>0&&await new Promise(o=>setTimeout(o,a));try{let o=await e();if(n=o,o.Code===1&&r(o.Data))return{matched:!0,response:o};i=o.Msg||`\u56DE\u8BFB Code=${o.Code}`}catch(o){i=o instanceof Error?o.message:String(o)}}return{matched:!1,response:n,lastError:i}}recoveredWriteResult(e,r,n={}){return{Code:1,Data:{...n,RecoveredAfterTransportError:!0,Verification:"readback",TransportError:r.message},Msg:`${e} \u7684\u5BA2\u6237\u7AEF\u54CD\u5E94\u5F02\u5E38\uFF0C\u4F46\u5DF2\u901A\u8FC7\u8FDC\u7AEF\u56DE\u8BFB\u786E\u8BA4\u5199\u5165\u6210\u529F\u3002`}}uncertainWriteFailure(e,r,n){return new Error(`${e} \u7684\u5BA2\u6237\u7AEF\u54CD\u5E94\u5F02\u5E38\uFF0C\u4E14\u56DE\u8BFB\u672A\u80FD\u786E\u8BA4\u5199\u5165\u7ED3\u679C\u3002\u539F\u59CB\u9519\u8BEF\uFF1A${r.message}${n?`\uFF1B\u56DE\u8BFB\u7ED3\u679C\uFF1A${n}`:""}\u3002\u8BF7\u7EE7\u7EED\u4F7F\u7528\u5BF9\u5E94\u7684\u6807\u51C6 MCP \u83B7\u53D6\u5DE5\u5177\u56DE\u8BFB\u540E\u518D\u51B3\u5B9A\u662F\u5426\u91CD\u8BD5\uFF1B\u4E0D\u8981\u6539\u8D70\u539F\u751F FormEngine\u3001\u76F4\u63A5 SQL \u6216\u4E34\u65F6\u7EF4\u62A4\u63A5\u53E3\u5F15\u64CE\u3002`,{cause:r})}async getStatus(){return this.get(O.GET_STATUS)}async transitionApplicationStreamGate(e){return this.post(O.TRANSITION_APPLICATION_STREAM_GATE,e,{timeoutMs:this.writeRequestTimeoutMs,operationName:`transition application stream gate ${e.TransitionId}`})}async listMyUserAccessKeys(){return this.post(O.LIST_USER_ACCESS_KEYS,{})}async createMyUserAccessKey(e){return this.post(O.CREATE_USER_ACCESS_KEY,{Name:e.name,Scopes:e.scopes,AllowedRoutes:e.allowedRoutes,RedirectPath:e.redirectPath,AllowedTableNames:e.allowedTableNames,AllowedApiEngineKeys:e.allowedApiEngineKeys,AllowedDataSourceKeys:e.allowedDataSourceKeys,ExpiresAt:e.expiresAt,Remark:e.remark,Permanent:!1},{timeoutMs:this.writeRequestTimeoutMs,operationName:`\u521B\u5EFA\u5F53\u524D\u7528\u6237\u8BBF\u95EE\u5BC6\u94A5 ${e.name}`})}async revokeMyUserAccessKey(e){return this.post(O.REVOKE_USER_ACCESS_KEY,{Id:e},{timeoutMs:this.writeRequestTimeoutMs,operationName:`\u540A\u9500\u5F53\u524D\u7528\u6237\u8BBF\u95EE\u5BC6\u94A5 ${e}`})}async getDbSchema(){return this.post(O.GET_DB_SCHEMA,{OsClient:this.config.osClient})}async getTableIndexes(e,r=!1){return this.post(O.GET_TABLE_INDEXES,{OsClient:this.config.osClient,TableName:e},r?this.readbackOptions(`\u56DE\u8BFB\u8868 ${e} \u7D22\u5F15`):{})}async createTableIndex(e){let r={OsClient:this.config.osClient,...e};try{return await this.post(O.CREATE_TABLE_INDEX,r,{timeoutMs:this.writeRequestTimeoutMs,operationName:`\u521B\u5EFA\u7D22\u5F15 ${e.IndexName||`${e.TableName}:${e.Columns.join(",")}`}`})}catch(n){if(!this.isUncertainWriteError(n))throw n;let i=await this.pollReadback(()=>this.getTableIndexes(e.TableName,!0),a=>a.some(o=>{let s=e.IndexName?String(o.Key_name||o.Name||"").toLowerCase()===e.IndexName.toLowerCase():!0,c=o.Columns?.length?o.Columns:String(o.Column_name||"").split(",").map(u=>u.trim()).filter(Boolean),l=o.IsUnique??Number(o.Non_unique)===0;return s&&l===!!e.Unique&&c.length===e.Columns.length&&c.every((u,p)=>u.toLowerCase()===e.Columns[p].toLowerCase())}));if(i.matched)return this.recoveredWriteResult("\u521B\u5EFA\u6570\u636E\u5E93\u7D22\u5F15",n,{TableName:e.TableName,IndexName:e.IndexName,Columns:e.Columns});throw this.uncertainWriteFailure("\u521B\u5EFA\u6570\u636E\u5E93\u7D22\u5F15",n,i.lastError)}}async dropTableIndex(e,r){try{return await this.post(O.DROP_TABLE_INDEX,{OsClient:this.config.osClient,TableName:e,IndexName:r},{timeoutMs:this.writeRequestTimeoutMs,operationName:`\u5220\u9664\u7D22\u5F15 ${r}`})}catch(n){if(!this.isUncertainWriteError(n))throw n;let i=await this.pollReadback(()=>this.getTableIndexes(e,!0),a=>!a.some(o=>String(o.Key_name||o.Name||"").toLowerCase()===r.toLowerCase()));if(i.matched)return this.recoveredWriteResult("\u5220\u9664\u6570\u636E\u5E93\u7D22\u5F15",n,{TableName:e,IndexName:r});throw this.uncertainWriteFailure("\u5220\u9664\u6570\u636E\u5E93\u7D22\u5F15",n,i.lastError)}}async getSupportedDatabaseTypes(){return this.post(O.GET_SUPPORTED_DATABASE_TYPES,{})}async inspectExternalDatabase(e){return this.post(O.INSPECT_EXTERNAL_DATABASE,{OsClient:this.config.osClient,...e})}async queryExternalDatabase(e){return this.post(O.QUERY_EXTERNAL_DATABASE,{OsClient:this.config.osClient,...e})}async executeExternalDatabaseSql(e){let r=Number(e.CommandTimeoutSeconds||0),n=Number.isFinite(r)&&r>0?(r+30)*1e3:63e4;return this.post(O.EXECUTE_EXTERNAL_DATABASE_SQL,{OsClient:this.config.osClient,...e},{timeoutMs:Math.max(this.config.requestTimeoutMs??12e4,this.config.writeRequestTimeoutMs??6e4,n),operationName:"execute external database sql"})}async saveDatabaseConnection(e){return this.post(O.SAVE_DATABASE_CONNECTION,{OsClient:this.config.osClient,...e},{timeoutMs:this.config.writeRequestTimeoutMs,operationName:"save database connection"})}async importExternalAttachment(e){let r=Number(e.TimeoutSeconds||0),n=Number.isFinite(r)&&r>0?(r+30)*1e3:363e4;return this.post(O.IMPORT_EXTERNAL_ATTACHMENT,{OsClient:this.config.osClient,...e},{timeoutMs:Math.max(this.config.requestTimeoutMs??12e4,this.config.writeRequestTimeoutMs??6e4,n),operationName:"import external attachment"})}async getPlaywrightContext(e,r){return this.post(O.GET_PLAYWRIGHT_CONTEXT,{OsClient:this.config.osClient,...e?{Keyword:e}:{},...r?{PageSize:r}:{}})}async getEngineList(e){return this.post(O.GET_ENGINE_LIST,{OsClient:this.config.osClient,...e?{_SearchKey:e}:{}})}async getEngineCode(e,r={}){return this.post(O.GET_ENGINE_CODE,{OsClient:this.config.osClient,ApiEngineKey:e},r)}async executeEngine(e,r){return this.post(O.EXECUTE_ENGINE,{OsClient:this.config.osClient,ApiEngineKey:e,Param:r||{}})}async chat(e){return this.post(O.AI_CHAT,{UserChatMsg:e.question,AiModel:e.aiModel,...e.systemPrompt?{SystemChatMsg:e.systemPrompt}:{},...e.aiModelId?{AiModelId:e.aiModelId}:{},...e.relayModel?{RelayModel:e.relayModel}:{},...e.conversationId?{ConversationId:e.conversationId}:{},...e.reasoningEffort?{ReasoningEffort:e.reasoningEffort}:{},...e.mode?{Mode:e.mode}:{},OsClient:this.config.osClient},{timeoutMs:Math.max(this.config.requestTimeoutMs??12e4,33e4),operationName:"Microi AI chat"})}async recognizeOcr(e){return this.post(O.OCR_RECOGNIZE,e,{timeoutMs:ZV,operationName:`OCR recognize ${e.FileName||"unnamed file"}`})}async translateText(e){return this.post(O.TRANSLATE_TEXT,{Action:"TranslateText",...e},{timeoutMs:Qa,operationName:"translate text"})}async detectLanguage(e){return this.post(O.TRANSLATE_DETECT,{Action:"Detect",SourceText:e},{timeoutMs:Qa,operationName:"detect language"})}async listTranslateLanguages(){return this.post(O.TRANSLATE_LANGUAGES,{Action:"Languages"},{timeoutMs:Qa,operationName:"list translation languages"})}async translateFile(e){return this.post(O.TRANSLATE_FILE,{Action:"TranslateFile",...e},{timeoutMs:Qa,operationName:`translate file ${e.FileName}`})}async suggestTranslation(e){return this.post(O.TRANSLATE_SUGGEST,{Action:"Suggest",...e},{timeoutMs:Qa,operationName:"suggest translation"})}async getTranslateHealth(){return this.post(O.TRANSLATE_HEALTH,{Action:"Health"},{timeoutMs:Qa,operationName:"translation health"})}async saveEngineCode(e,r,n){Qs(r,`\u4FDD\u5B58\u63A5\u53E3\u5F15\u64CE ${e}`);let i;try{let p=await this.getEngineCode(e);i=p.Code===1?p.Data:void 0}catch{i=void 0}let a=Jn(i?.ApiV8Code||i?.Code),o=Jn(r);if(a.length>=8e3&&o.length<a.length*.85&&!n?.confirmLargeReduction)throw new Error(`\u4FDD\u5B58\u63A5\u53E3\u5F15\u64CE ${e} \u5DF2\u62E6\u622A\uFF1A\u65B0\u6E90\u7801 ${o.length} \u5B57\u7B26\uFF0C\u8FDC\u7AEF\u6E90\u7801 ${a.length} \u5B57\u7B26\uFF0C\u51CF\u5C11\u8D85\u8FC7 15%\u3002\u8FD9\u53EF\u80FD\u662F\u957F\u5DE5\u5177\u7ED3\u679C\u88AB\u622A\u65AD\uFF1B\u786E\u8BA4\u786E\u9700\u5927\u5E45\u5220\u51CF\u65F6\u8BF7\u4F20 confirmLargeReduction="${e}"\u3002`);let s=ec({kind:"ApiEngine",key:e,currentCode:r,remoteCode:i?.ApiV8Code||i?.Code,remoteVersion:i?.Version,functionDescription:n?.functionDescription,changeSummary:n?.changeSummary||`\u4FDD\u5B58\u63A5\u53E3\u5F15\u64CE ${e}`}),c=n?.v8Limit??(n?.v8Unlimited===void 0?void 0:!n.v8Unlimited),l={OsClient:this.config.osClient,ApiEngineKey:e,ApiV8CodeBase64:Buffer.from(s.code,"utf8").toString("base64"),Version:s.version,ChangeSummary:s.changeHistory,...c===void 0?{}:{V8Limit:c?1:0},...n?.responseType===void 0?{}:{ResponseType:n.responseType}},u=p=>Jn(p?.ApiV8Code||p?.Code)===Jn(s.code)&&(c===void 0||Ky(p)===(c?1:0))&&(n?.responseType===void 0||String(p?.ResponseType||"JSON").toLowerCase()===n.responseType.toLowerCase());try{let p=await this.post(O.UPDATE_ENGINE_CODE,l,{timeoutMs:this.writeRequestTimeoutMs,operationName:`\u4FDD\u5B58\u63A5\u53E3\u5F15\u64CE ${e}`});if(p.Code!==1||c===void 0&&n?.responseType===void 0)return p;let f=await this.pollReadback(()=>this.getEngineCode(e,this.readbackOptions(`\u56DE\u8BFB\u63A5\u53E3\u5F15\u64CE ${e} V8Limit`)),u);return f.matched?{...p,Data:{...p.Data&&typeof p.Data=="object"?p.Data:{},ApiEngineKey:e,...c===void 0?{}:{V8Limit:c?1:0},...n?.responseType===void 0?{}:{ResponseType:n.responseType},Verified:!0,Verification:"readback"}}:{Code:0,Data:{ApiEngineKey:e,UpdateResponse:p.Data},Msg:`\u4FDD\u5B58\u63A5\u53E3\u5F15\u64CE ${e} \u8FD4\u56DE\u6210\u529F\uFF0C\u4F46\u8FD0\u884C\u914D\u7F6E\u5199\u540E\u56DE\u8BFB\u4E0D\u4E00\u81F4\uFF1A${f.lastError||"\u4EE3\u7801\u6216\u914D\u7F6E\u4E0D\u4E00\u81F4"}`}}catch(p){if(!this.isUncertainWriteError(p))throw p;let f=await this.pollReadback(()=>this.getEngineCode(e,this.readbackOptions(`\u56DE\u8BFB\u63A5\u53E3\u5F15\u64CE ${e}`)),u);if(f.matched)return this.recoveredWriteResult(`\u4FDD\u5B58\u63A5\u53E3\u5F15\u64CE ${e}`,p,{ApiEngineKey:e,Version:s.version});throw this.uncertainWriteFailure(`\u4FDD\u5B58\u63A5\u53E3\u5F15\u64CE ${e}`,p,f.lastError)}}async updateEngineRuntimeLimit(e,r){let n={OsClient:this.config.osClient,ApiEngineKey:e,V8Limit:r?1:0},i=()=>this.pollReadback(()=>this.getEngineCode(e,this.readbackOptions(`\u56DE\u8BFB\u63A5\u53E3\u5F15\u64CE ${e} V8Limit`)),o=>Ky(o)===(r?1:0)),a=`\u66F4\u65B0\u63A5\u53E3\u5F15\u64CE ${e} V8Limit`;try{let o=await this.post(O.UPDATE_ENGINE_CODE,n,{timeoutMs:this.writeRequestTimeoutMs,operationName:a});if(o.Code!==1)return o;let s=await i();return s.matched?{...o,Data:{...o.Data&&typeof o.Data=="object"?o.Data:{},ApiEngineKey:e,V8Limit:r?1:0,Verified:!0,Verification:"readback"}}:{Code:0,Data:{ApiEngineKey:e,UpdateResponse:o.Data},Msg:`${a} \u63A5\u53E3\u8FD4\u56DE\u6210\u529F\uFF0C\u4F46\u8FDC\u7AEF\u5199\u540E\u56DE\u8BFB\u4E0D\u4E00\u81F4\uFF1A${s.lastError||"\u914D\u7F6E\u4E0D\u4E00\u81F4"}`}}catch(o){if(!this.isUncertainWriteError(o))throw o;let s=await i();if(s.matched)return this.recoveredWriteResult(a,o,{ApiEngineKey:e,V8Limit:r?1:0,Verified:!0});throw this.uncertainWriteFailure(a,o,s.lastError)}}async updateEngineRuntimeConfig(e,r){return this.updateEngineRuntimeLimit(e,!r)}async createEngine(e){let r={OsClient:this.config.osClient,...e};r.V8Limit===void 0&&r.V8Unlimited!==void 0&&(r.V8Limit=Number(r.V8Unlimited)===1?0:1),delete r.V8Unlimited;let n=typeof r.Code=="string"?r.Code:typeof r.ApiV8Code=="string"?r.ApiV8Code:"";Qs(n,`\u521B\u5EFA\u63A5\u53E3\u5F15\u64CE ${e.ApiEngineKey}`);let i=ec({kind:"ApiEngine",key:e.ApiEngineKey,currentCode:n,functionDescription:r.functionDescription,changeSummary:r.changeSummary||`\u521B\u5EFA\u63A5\u53E3\u5F15\u64CE ${e.ApiEngineKey}`,initial:!0});r.ApiV8CodeBase64=Buffer.from(i.code,"utf8").toString("base64"),r.Version=i.version,r.ChangeSummary=i.changeHistory,delete r.Code,delete r.ApiV8Code,delete r.functionDescription,delete r.changeSummary,(!r.ApiAddress||r.ApiAddress.trim().length===0)&&(r.ApiAddress=`/apiengine/${e.ApiEngineKey}`),r.IsEnable=r.IsEnable??1,r.StopHttp=r.StopHttp??0,r.AllowAnonymous=r.AllowAnonymous??0;let a=`\u521B\u5EFA\u63A5\u53E3\u5F15\u64CE ${e.ApiEngineKey}`,o=()=>this.pollReadback(()=>this.getEngineCode(e.ApiEngineKey,this.readbackOptions(`\u56DE\u8BFB\u65B0\u5EFA\u63A5\u53E3\u5F15\u64CE ${e.ApiEngineKey}`)),s=>String(s?.ApiEngineKey||"")===e.ApiEngineKey&&Jn(s?.ApiV8Code||s?.Code)===Jn(i.code)&&(r.V8Limit===void 0||Ky(s)===(Number(r.V8Limit)===1?1:0))&&(r.ResponseType===void 0||String(s?.ResponseType||"JSON").toLowerCase()===String(r.ResponseType).toLowerCase()));try{let s=await this.post(O.CREATE_ENGINE,r,{timeoutMs:this.writeRequestTimeoutMs,operationName:a});if(s.Code!==1)return s;let c=await o();return c.matched?{...s,Data:{...s.Data&&typeof s.Data=="object"?s.Data:{},ApiEngineKey:e.ApiEngineKey,Verified:!0,Verification:"readback"}}:{Code:0,Data:{ApiEngineKey:e.ApiEngineKey,CreateResponse:s.Data},Msg:`${a} \u63A5\u53E3\u8FD4\u56DE\u6210\u529F\uFF0C\u4F46\u8FDC\u7AEF\u56DE\u8BFB\u672A\u786E\u8BA4\u65B0\u8BB0\u5F55\uFF1A${c.lastError||"\u8BB0\u5F55\u6216\u4EE3\u7801\u4E0D\u4E00\u81F4"}`}}catch(s){if(!this.isUncertainWriteError(s))throw s;let c=await o();if(c.matched)return this.recoveredWriteResult(a,s,{ApiEngineKey:e.ApiEngineKey,Version:i.version,Verified:!0});throw this.uncertainWriteFailure(a,s,c.lastError)}}async uploadFileBase64(e){return this.post(O.UPLOAD_FILE_BASE64,{OsClient:this.config.osClient,...e})}async uploadApplicationAssetStream(e){let r=tc.default.resolve(e.FilePath),n=Ot.default.lstatSync(r);if(!n.isFile()||n.isSymbolicLink())throw new Error(`\u5E94\u7528\u8D44\u4EA7\u5FC5\u987B\u662F\u666E\u901A\u6587\u4EF6\u4E14\u4E0D\u80FD\u662F\u7B26\u53F7\u94FE\u63A5\uFF1A${r}`);let i=tc.default.posix.basename(String(e.RelativePath||"").replace(/\\/g,"/"));if(!i||/[\r\n"]/u.test(i))throw new Error("RelativePath \u7684\u6587\u4EF6\u540D\u4E0D\u5408\u6CD5");if(e.ProtocolVersion===3)return this.uploadApplicationAssetResumable(e,r,n.size);if(n.size>UV)throw new Error(`\u5F53\u524D\u6587\u4EF6 ${n.size} bytes \u8D85\u8FC7\u65E7\u7248 128MiB \u5355\u8BF7\u6C42\u8FB9\u754C\uFF1B\u8BF7\u542F\u7528 ProtocolVersion=3\uFF0CMCP \u5C06\u81EA\u52A8\u4F7F\u7528 HDFS \u5206\u7247\u65AD\u70B9\u7EED\u4F20\u3002`);let a=`microi-asset-${e.ExpectedSha256.slice(0,16)}.bin`,o={};if(e.ProtocolVersion===3){let s=c=>c===null?"null":String(c??"");Object.assign(o,{ProtocolVersion:"3",PublishMode:"stage",ExpectedGateEpoch:String(e.ExpectedGateEpoch??""),RequestFingerprint:String(e.RequestFingerprint??""),DeliveryBatchId:String(e.DeliveryBatchId??""),SourceManifestHash:String(e.SourceManifestHash??""),RuntimeManifestHash:String(e.RuntimeManifestHash??""),RouteSnapshotJson:String(e.RouteSnapshotJson??""),RouteSnapshotHash:String(e.RouteSnapshotHash??""),ExpectedCurrentVersion:String(e.ExpectedCurrentVersion??""),ExpectedAppVersion:s(e.ExpectedAppVersion),ExpectedPublishFence:String(e.ExpectedPublishFence??""),ExpectedPublishRowVersion:String(e.ExpectedPublishRowVersion??""),ExpectedVersionRowVersion:s(e.ExpectedVersionRowVersion),ExpectedActivePublishVersionId:s(e.ExpectedActivePublishVersionId),ExpectedCommittedPublishVersionId:s(e.ExpectedCommittedPublishVersionId)})}return this.requestMultipartFile(O.UPLOAD_APPLICATION_ASSET_STREAM,{OsClient:this.config.osClient||"",AppIdOrKey:e.AppIdOrKey,VersionNo:e.VersionNo,RelativePath:e.RelativePath,ExpectedSha256:e.ExpectedSha256,RequestId:e.RequestId,...o},r,a,"initial",e.TimeoutMs)}async getApplicationAssetMultipartStatus(e,r){return this.post(O.GET_APPLICATION_ASSET_MULTIPART_STATUS,{OsClient:this.config.osClient,AppIdOrKey:e,SessionId:r},{timeoutMs:2*6e4,operationName:"read resumable application asset status"})}async uploadApplicationAssetResumable(e,r,n){if(!Number.isSafeInteger(n)||n<0)throw new Error("\u5E94\u7528\u8D44\u4EA7\u5927\u5C0F\u8D85\u51FA JavaScript \u5B89\u5168\u6574\u6570\u8303\u56F4");let i=WV(e),a=await this.post(O.INITIATE_APPLICATION_ASSET_MULTIPART,{OsClient:this.config.osClient,AppIdOrKey:e.AppIdOrKey,VersionNo:e.VersionNo,RelativePath:e.RelativePath,ExpectedSha256:e.ExpectedSha256,TotalSize:n,RequestedChunkSize:JV,RequestId:e.RequestId,...i},{timeoutMs:2*6e4,operationName:"initiate resumable application asset upload"});if(a.Code!==1)return a;let o=a.Data,s=String(o?.SessionId||"").trim(),c=Number(o?.ChunkSize),l=Number(o?.TotalParts);if(!/^mciau-[a-f0-9]{30}$/u.test(s)||!Number.isSafeInteger(c)||c<16*1024*1024||!Number.isSafeInteger(l)||l<0||l>1e4||l!==(n===0?0:Math.ceil(n/c)))throw new Error("\u670D\u52A1\u7AEF\u8FD4\u56DE\u7684\u65AD\u70B9\u4E0A\u4F20 SessionId/ChunkSize/TotalParts \u4E0D\u5408\u6CD5");let u=await this.getApplicationAssetMultipartStatus(e.AppIdOrKey,s);if(u.Code!==1||String(u.Data?.Status||"")==="Succeeded")return u;let f=new Map;for(let g of u.Data?.Parts||[]){let y=Number(g.Number);Number.isSafeInteger(y)&&y>0&&y<=l&&f.set(y,g)}let h=0,m=0;for(let g=1;g<=l;g+=1){let y=(g-1)*c,v=Math.min(c,n-y),x=await KV(r,y,v),b=f.get(g);if(b){if(Number(b.Size)!==v||String(b.Sha256||"")!==x)throw new Error(`\u65AD\u70B9\u4F1A\u8BDD\u7B2C ${g} \u5757\u4E0E\u672C\u5730\u4E0D\u53EF\u53D8\u6587\u4EF6\u4E0D\u4E00\u81F4\uFF1B\u5DF2\u62D2\u7EDD\u8986\u76D6\uFF0C\u8BF7\u6838\u5BF9\u672C\u5730\u6587\u4EF6\u662F\u5426\u5728\u4E0A\u4F20\u671F\u95F4\u53D1\u751F\u53D8\u5316\u3002`);m+=1;continue}let _;for(let E=0;E<5;E+=1)try{if(_=await this.requestBinaryFileRange(O.UPLOAD_APPLICATION_ASSET_MULTIPART_PART,{osClient:this.config.osClient||"",sessionId:s,partNumber:String(g),expectedPartSha256:x},r,y,v,"initial",e.TimeoutMs),_.Code===1)break;if(E===4)return _}catch(S){u=await this.getApplicationAssetMultipartStatus(e.AppIdOrKey,s);let T=(u.Data?.Parts||[]).find(C=>Number(C.Number)===g);if(u.Code===1&&T&&Number(T.Size)===v&&String(T.Sha256||"")===x){_=u;break}if(E===4)throw S;await new Promise(C=>setTimeout(C,500*(E+1)))}if(!_||_.Code!==1)return _||{Code:0,Data:null,Msg:`\u7B2C ${g} \u5757\u4E0A\u4F20\u6CA1\u6709\u8FD4\u56DE\u7EC8\u6001`};h+=1,(g===1||g%20===0||g===l)&&console.error(`[microi-mcp] Resumable HDFS asset ${e.RelativePath}: ${g}/${l}`)}try{let g=await this.post(O.COMPLETE_APPLICATION_ASSET_MULTIPART,{OsClient:this.config.osClient,AppIdOrKey:e.AppIdOrKey,SessionId:s},{timeoutMs:Wy,maxTimeoutMs:Wy,operationName:"complete resumable application asset upload"});return g.Code===1&&g.Data&&typeof g.Data=="object"?{...g,Data:{...g.Data,UploadedInThisRun:h,ResumedParts:m}}:g}catch(g){let y=await this.getApplicationAssetMultipartStatus(e.AppIdOrKey,s);if(y.Code===1&&String(y.Data?.Status||"")==="Succeeded")return{...y,Data:{...y.Data,RecoveredAfterTransportError:!0,UploadedInThisRun:h,ResumedParts:m},Msg:"\u5B8C\u6210\u8BF7\u6C42\u54CD\u5E94\u4E2D\u65AD\uFF0C\u4F46\u5DF2\u901A\u8FC7\u4F1A\u8BDD\u56DE\u8BFB\u786E\u8BA4\u6700\u7EC8\u5BF9\u8C61 Prepared\u3002"};throw g}}async finalizeApplicationStreamPublish(e){return this.post(O.FINALIZE_APPLICATION_STREAM_PUBLISH,{OsClient:this.config.osClient,...e},{timeoutMs:10*6e4,operationName:"finalize application stream publish"})}async getMicroService(e){return this.post(O.GET_MICRO_SERVICE,{OsClient:this.config.osClient,MsKey:e})}async listApplications(e={}){return this.post(O.LIST_APPLICATIONS,{OsClient:this.config.osClient,...e})}async getApplicationContext(e){return this.post(O.GET_APPLICATION_CONTEXT,{OsClient:this.config.osClient,...e})}async getApplicationFile(e){return this.post(O.GET_APPLICATION_FILE,{OsClient:this.config.osClient,...e})}async createMicroService(e){return this.post(O.CREATE_MICRO_SERVICE,{OsClient:this.config.osClient,...e})}async syncMicroServiceSource(e){return this.post(O.SYNC_MICRO_SERVICE_SOURCE,{OsClient:this.config.osClient,...e})}async publishMicroService(e){return this.post(O.PUBLISH_MICRO_SERVICE,{OsClient:this.config.osClient,...e})}async probeMicroAppEntry(e){let r=FV(this.config.apiBaseUrl,this.config.osClient||"",e),n=new AbortController,i=setTimeout(()=>n.abort(),1e4);try{let a=await fetch(r,{method:"GET",headers:{Accept:"text/html,application/xhtml+xml"},redirect:"follow",signal:n.signal}),o=a.headers.get("content-type")||"",s=Number(a.headers.get("content-length")||0);if(Number.isFinite(s)&&s>2*1024*1024)return await a.body?.cancel(),{ok:!1,url:r,status:a.status,contentType:o,bodyBytes:s,error:"MicroApp entry exceeds the 2MB probe limit"};let c=Buffer.from(await a.arrayBuffer()),l=c.byteLength,u=c.toString("utf8"),p=/<head(?:\s|>)/iu.test(u),f=/<body(?:\s|>)/iu.test(u),h=a.ok&&o.toLowerCase().includes("text/html")&&l>0&&p&&f;return{ok:h,url:r,status:a.status,contentType:o,bodyBytes:l,hasHead:p,hasBody:f,...a.ok?h?{}:{error:"MicroApp entry is not a complete HTML document with <head> and <body>"}:{error:`HTTP ${a.status} ${a.statusText}`}}}catch(a){return{ok:!1,url:r,error:n.signal.aborted?"MicroApp entry probe timed out after 10000ms":a instanceof Error?a.message:String(a)}}finally{clearTimeout(i)}}async getTableData(e,r={}){return this.post(O.FORM_GET_TABLE_DATA,{OsClient:this.config.osClient,FormEngineKey:e,...r})}async addFormData(e,r){return this.post(O.FORM_ADD_FORM_DATA,{OsClient:this.config.osClient,FormEngineKey:e,...r})}async updateFormData(e,r){return this.post(O.FORM_UPT_FORM_DATA,{OsClient:this.config.osClient,FormEngineKey:e,...r})}async getEventCode(e,r,n={}){return this.post(O.GET_EVENT_CODE,{OsClient:this.config.osClient,FormEngineKey:e,EventType:r},n)}async saveEventCode(e,r,n,i){Qs(n,`\u4FDD\u5B58 V8 \u4E8B\u4EF6 ${e}/${r}`);let a;try{let c=await this.getEventCode(e,r);a=c.Code===1?c.Data:void 0}catch{a=void 0}let o=ec({kind:"V8Event",key:e,eventType:r,currentCode:n,remoteCode:a?.V8Code||a?.Code,remoteVersion:a?.Version,functionDescription:i?.functionDescription,changeSummary:i?.changeSummary||`\u4FDD\u5B58 V8 \u4E8B\u4EF6 ${e}/${r}`}),s={OsClient:this.config.osClient,FormEngineKey:e,EventType:r,V8Code:o.code,Version:o.version,ChangeHistory:o.changeHistory};try{return await this.post(O.UPDATE_EVENT_CODE,s,{timeoutMs:this.writeRequestTimeoutMs,operationName:`\u4FDD\u5B58 V8 \u4E8B\u4EF6 ${e}/${r}`})}catch(c){if(!this.isUncertainWriteError(c))throw c;let l=await this.pollReadback(()=>this.getEventCode(e,r,this.readbackOptions(`\u56DE\u8BFB V8 \u4E8B\u4EF6 ${e}/${r}`)),u=>Jn(u?.V8Code||u?.Code)===Jn(o.code));if(l.matched)return this.recoveredWriteResult(`\u4FDD\u5B58 V8 \u4E8B\u4EF6 ${e}/${r}`,c,{FormEngineKey:e,EventType:r,Version:o.version});throw this.uncertainWriteFailure(`\u4FDD\u5B58 V8 \u4E8B\u4EF6 ${e}/${r}`,c,l.lastError)}}async getEventList(e){return this.post(O.GET_EVENT_LIST,{OsClient:this.config.osClient,...e?{_SearchKey:e}:{}})}async getWorkflowV8EventList(e){return this.post(O.GET_WORKFLOW_V8_EVENT_LIST,{OsClient:this.config.osClient,...e?{FlowDesignId:e}:{}})}async getWorkflowV8EventCode(e,r,n){return this.post(O.GET_WORKFLOW_V8_EVENT_CODE,{OsClient:this.config.osClient,...n?{FlowDesignId:n}:{},NodeId:e,EventType:r})}async saveWorkflowV8EventCode(e,r,n,i){Qs(n,`\u4FDD\u5B58\u6D41\u7A0B\u8282\u70B9 V8 ${e}/${r}`);let a;try{let c=await this.getWorkflowV8EventCode(e,r,i?.flowDesignId);a=c.Code===1?c.Data:void 0}catch{a=void 0}let o=!n.trim(),s={OsClient:this.config.osClient,...i?.flowDesignId?{FlowDesignId:i.flowDesignId}:{},NodeId:e,EventType:r};if(o)s.V8Code="";else{let c=`${i?.flowDesignId||a?.FlowDesignId||"workflow"}/${e}`,l=ec({kind:"Workflow",key:c,eventType:r,currentCode:n,remoteCode:a?.V8Code||a?.Code,remoteVersion:a?.Version,functionDescription:i?.functionDescription,changeSummary:i?.changeSummary||`\u4FDD\u5B58\u6D41\u7A0B\u8282\u70B9 V8 ${e}/${r}`});s.V8CodeBase64=Buffer.from(l.code,"utf8").toString("base64"),s.Version=l.version,s.ChangeHistory=l.changeHistory}return this.post(O.UPDATE_WORKFLOW_V8_EVENT_CODE,s)}async createTable(e,r,n){let i={...n||{}};return i.V8Limit===void 0&&i.V8Unlimited!==void 0&&(i.V8Limit=Number(i.V8Unlimited)===1?0:1),delete i.V8Unlimited,this.post(O.CREATE_TABLE,{OsClient:this.config.osClient,Name:e,Description:r||"",...i})}async repairFixedAuditFields(e){return this.post(O.REPAIR_FIXED_AUDIT_FIELDS,{OsClient:this.config.osClient,TableId:e.tableId,TableName:e.tableName})}async addField(e){return this.post(O.ADD_FIELD,{OsClient:this.config.osClient,...e,Visible:e.Visible??1,AppVisible:e.AppVisible??1})}async deleteField(e){return this.post(O.DELETE_FIELD,{OsClient:this.config.osClient,...e})}async updateField(e){return this.post(O.UPDATE_FIELD,{OsClient:this.config.osClient,...e})}async updateFieldList(e){return this.post(O.UPDATE_FIELD_LIST,{OsClient:this.config.osClient,...e})}async getFieldList(e,r){return this.post(O.GET_FIELD_LIST,{OsClient:this.config.osClient,TableName:e,TableId:r})}async updateTable(e){return this.post(O.UPDATE_TABLE,{OsClient:this.config.osClient,...e})}async refreshSchemaCache(e){return this.post(O.REFRESH_SCHEMA_CACHE,{OsClient:this.config.osClient,Tables:e})}async setEngineAnonymous(e,r=1){return this.post(O.SET_ENGINE_ANONYMOUS,{OsClient:this.config.osClient,ApiEngineKeys:e,AllowAnonymous:r})}async createModule(e){let r=await this.post(O.CREATE_MODULE,{OsClient:this.config.osClient,...e,Display:e.Display??1,AppDisplay:e.AppDisplay??1});if(r.Code!==1||!!!(e.IsMicroiService===1||e.MicroServiceId||e.MicroServicePageId||e.MicroServiceRoutePath))return r;let i=r.Data&&typeof r.Data=="object"?r.Data:{},a=String(i.ModuleId||i.Id||"");if(!a)return{Code:0,Data:{CreateResponse:r.Data},Msg:"\u83DC\u5355\u5DF2\u521B\u5EFA\uFF0C\u4F46\u8FD4\u56DE\u7ED3\u679C\u7F3A\u5C11 ModuleId\uFF0C\u65E0\u6CD5\u5199\u5165\u5E76\u56DE\u8BFB\u5FAE\u670D\u52A1\u5173\u8054\u5B57\u6BB5\u3002"};let o={ModuleId:a,IsMicroiService:1,OpenType:e.OpenType||"MicroService",ComponentName:e.ComponentName||"MicroService",ComponentPath:e.ComponentPath||"/micro-app/host",Url:e.Url,MicroServiceId:e.MicroServiceId,MicroServicePageId:e.MicroServicePageId,MicroServiceRoutePath:e.MicroServiceRoutePath},s=await this.updateModule(o);return s.Code!==1?{Code:0,Data:{ModuleId:a,CreateResponse:r.Data,BindingResponse:s.Data},Msg:`\u83DC\u5355\u57FA\u7840\u8BB0\u5F55\u5DF2\u521B\u5EFA\uFF0C\u4F46\u5FAE\u670D\u52A1\u5173\u8054\u5B57\u6BB5\u5199\u5165\u6216\u56DE\u8BFB\u5931\u8D25\uFF1A${s.Msg||"\u672A\u77E5\u9519\u8BEF"}`}:{...r,Data:{...i,MicroServiceBindingVerified:!0,BindingVerification:s.Data}}}async setRolePermission(e,r){return this.post(O.SET_ROLE_PERMISSION,{OsClient:this.config.osClient,RoleId:e,MenuIds:r})}async listRoles(e){return this.post(O.LIST_ROLES,{OsClient:this.config.osClient,...e?{Keyword:e}:{}})}async saveRole(e){return this.post(O.SAVE_ROLE,{OsClient:this.config.osClient,...e})}async listModules(e){return this.post(O.LIST_MODULES,{OsClient:this.config.osClient,...e?{Keyword:e}:{}})}async getModule(e,r={}){return this.post(O.GET_MODULE,{OsClient:this.config.osClient,ModuleId:e},r)}async updateModule(e){let r={OsClient:this.config.osClient,...e},n=String(r.ModuleId||r.Id||""),i=`\u66F4\u65B0\u83DC\u5355\u6A21\u5757 ${n||r.Name||""}`.trim();Ys(r,i);let a=async()=>{if(!n)return{matched:!1,mismatches:["ModuleId"]};try{let o=await this.getModule(n,this.readbackOptions(`\u56DE\u8BFB\u83DC\u5355\u6A21\u5757 ${n}`));return o.Code!==1||!o.Data||typeof o.Data!="object"?{matched:!1,mismatches:["\u56DE\u8BFB\u5931\u8D25"],response:o}:{...GV(r,o.Data),response:o}}catch{return{matched:!1,mismatches:["\u56DE\u8BFB\u8BF7\u6C42\u5F02\u5E38"]}}};try{let o=await this.post(O.UPDATE_MODULE,r,{timeoutMs:this.writeRequestTimeoutMs,operationName:i});if(o.Code!==1)return o;let s=await a();return s.matched?{...o,Data:{...o.Data&&typeof o.Data=="object"?o.Data:{},Verified:!0,Verification:"readback"}}:{Code:0,Data:{ModuleId:n,Mismatches:s.mismatches,UpdateResponse:o.Data},Msg:`${i} \u63A5\u53E3\u8FD4\u56DE\u6210\u529F\uFF0C\u4F46\u8FDC\u7AEF\u56DE\u8BFB\u4E0D\u4E00\u81F4\uFF1A${s.mismatches.join(", ")}`}}catch(o){if(!this.isUncertainWriteError(o))throw o;let s=[],c=await this.pollReadback(async()=>{let l=await a();return s=l.mismatches,{Code:l.response?.Code??(l.matched?1:0),Data:l,Msg:l.response?.Msg||""}},l=>l.matched);if(c.matched)return this.recoveredWriteResult(i,o,{ModuleId:n,Verified:!0});throw this.uncertainWriteFailure(i,o,s.length?`\u5B57\u6BB5\u4E0D\u4E00\u81F4\uFF1A${s.join(", ")}`:c.lastError)}}async listDataSources(e){return this.post(O.LIST_DATA_SOURCES,{OsClient:this.config.osClient,...e?{Keyword:e}:{}})}async saveDataSource(e){return this.post(O.SAVE_DATA_SOURCE,{OsClient:this.config.osClient,...e})}async runDataSource(e,r){return this.post(O.RUN_DATA_SOURCE,{OsClient:this.config.osClient,DataSourceKey:e,...r||{}})}async listPrintTemplates(e){return this.post(O.LIST_PRINT_TEMPLATES,{OsClient:this.config.osClient,...e?{Keyword:e}:{}})}async savePrintTemplate(e){return this.post(O.SAVE_PRINT_TEMPLATE,{OsClient:this.config.osClient,...e})}async saveWorkflowPackage(e){return this.post(O.SAVE_WORKFLOW_PACKAGE,{OsClient:this.config.osClient,...e})}async saveJob(e){return this.post(O.SAVE_JOB,{OsClient:this.config.osClient,...e})}async listDatabaseBackupTenants(){return this.post(O.LIST_DATABASE_BACKUP_TENANTS,{OsClient:this.config.osClient})}async runDatabaseBackup(e){if(!/^[A-Za-z0-9:._-]{8,128}$/.test(e?.idempotencyKey||""))throw new Error("database backup idempotencyKey is required (8-128 safe characters) and must be reused for uncertain retries");return this.post(O.RUN_DATABASE_BACKUP,{OsClient:this.config.osClient,ConfirmExecution:"DATABASE_BACKUP",RetainCount:e.retainCount??7,...e.tenantOsClients===void 0?{}:{TenantOsClients:e.tenantOsClients},IdempotencyKey:e.idempotencyKey})}async runBackgroundApiEngine(e){return this.post(O.RUN_BACKGROUND_API_ENGINE,{OsClient:this.config.osClient,Action:"RunApiEngine",TargetApiEngineKey:e.apiEngineKey,Title:e.title,Param:e.param,Options:e.options||{}},{timeoutMs:this.writeRequestTimeoutMs,operationName:`queue background API engine ${e.apiEngineKey}`})}async validateLowCodeSystem(e){return this.post(O.VALIDATE_LOW_CODE_SYSTEM,{OsClient:this.config.osClient,Manifest:e})}async writeAuditLog(e,r,n){return this.post(O.WRITE_MCP_AUDIT_LOG,{OsClient:this.config.osClient,Action:e,Target:r,Content:n})}async queryMongodbLogs(e={}){return this.post(O.QUERY_MONGODB_LOGS,{OsClient:this.config.osClient,Keyword:e.keyword,Type:e.type,Level:e.level,SearchMonth:e.searchMonth,PageIndex:e.pageIndex||1,PageSize:e.pageSize||20})}async writeMongodbLog(e){return this.post(O.WRITE_MONGODB_LOG,{OsClient:this.config.osClient,Type:e.type||"MCP",Title:e.title,Content:e.content,Level:e.level||1,Api:e.api||"microi.mcp",Param:e.param||"",Remark:e.remark||"",OtherInfo:e.otherInfo||"",Timer:e.timer,Result:e.result||"",AppId:e.appId||"microi.mcp"})}async querySystemObservability(e){return this.executeEngine("mci-system-observability-query",e)}async manageSystemObservability(e){return this.executeEngine("mci-system-observability-action",e)}async getRedisStatistics(e=0,r){return this.post(O.REDIS_STATISTICS,{Action:"RedisStatistics",Mode:r?"saved":"tenant",ConnectionId:r||"",Database:e})}async getRedisKeys(e="*",r=0,n=100,i,a){return this.post(O.REDIS_KEYS,{Action:"Keys",Mode:a?"saved":"tenant",ConnectionId:a||"",Database:r,Pattern:e,PageSize:n,Cursor:i||""})}async getRedisKey(e,r=0,n=1,i=500,a){return this.post(O.REDIS_KEY,{Action:"Key",Mode:a?"saved":"tenant",ConnectionId:a||"",Database:r,Key:e,PageIndex:n,PageSize:i})}async deleteRedisKeys(e,r=0,n){return this.post(O.REDIS_DELETE_KEYS,{Action:"DeleteKeys",Mode:n?"saved":"tenant",ConnectionId:n||"",Database:r,Keys:e})}async replaceRedisValue(e,r,n,i=0,a,o){return this.post(O.REDIS_REPLACE_VALUE,{Action:"ReplaceValue",Mode:o?"saved":"tenant",ConnectionId:o||"",Database:i,Key:e,DataType:r,Value:n,...a===void 0?{}:{TtlSeconds:a}})}async renameRedisKey(e,r,n=0,i){return this.post(O.REDIS_RENAME_KEY,{Action:"RenameKey",Mode:i?"saved":"tenant",ConnectionId:i||"",Database:n,Key:e,NewKey:r})}async setRedisTtl(e,r,n=0,i){return this.post(O.REDIS_SET_TTL,{Action:"SetTtl",Mode:i?"saved":"tenant",ConnectionId:i||"",Database:n,Key:e,TtlSeconds:r})}async getPageEngineList(e){return this.post(O.GET_PAGE_ENGINE_LIST,{OsClient:this.config.osClient,...e?{Keyword:e}:{}})}async getPageEngineDetail(e){return this.post(O.GET_PAGE_ENGINE_DETAIL,{OsClient:this.config.osClient,PageId:e})}async savePageEngine(e){return this.post(O.SAVE_PAGE_ENGINE,{OsClient:this.config.osClient,...e})}async listBackgroundTasks(){return this.post(O.LIST_BACKGROUND_TASKS,{OsClient:this.config.osClient,Action:"List"},{timeoutMs:this.requestTimeoutMs,operationName:"list background tasks"})}async cancelBackgroundTask(e){return this.post(O.CANCEL_BACKGROUND_TASK,{OsClient:this.config.osClient,Action:"Cancel",Id:e},{timeoutMs:this.writeRequestTimeoutMs,operationName:"cancel background task"})}async listPageEngineHistory(e,r=1,n=50){return this.post(O.LIST_PAGE_ENGINE_HISTORY,{OsClient:this.config.osClient,PageId:e,PageIndex:r,PageSize:n})}async getPageEngineHistory(e,r){return this.post(O.GET_PAGE_ENGINE_HISTORY,{OsClient:this.config.osClient,PageId:e,HistoryId:r})}async comparePageEngineVersions(e,r,n){return this.post(O.COMPARE_PAGE_ENGINE_VERSIONS,{OsClient:this.config.osClient,PageId:e,...r?{LeftHistoryId:r}:{},...n?{RightHistoryId:n}:{}})}async exportPageEngine(e){return this.post(O.EXPORT_PAGE_ENGINE,{OsClient:this.config.osClient,PageId:e})}async rollbackPageEngine(e){return this.post(O.ROLLBACK_PAGE_ENGINE,{OsClient:this.config.osClient,...e})}async listBlueprints(e){return this.post(O.LIST_BLUEPRINTS,{OsClient:this.config.osClient,...e?{Keyword:e}:{}})}async getBlueprint(e){return this.post(O.GET_BLUEPRINT,{OsClient:this.config.osClient,BlueprintId:e})}async listBlueprintHistory(e,r=1,n=50){return this.post(O.LIST_BLUEPRINT_HISTORY,{OsClient:this.config.osClient,BlueprintId:e,PageIndex:r,PageSize:n})}async getBlueprintHistory(e,r){return this.post(O.GET_BLUEPRINT_HISTORY,{OsClient:this.config.osClient,BlueprintId:e,HistoryId:r})}async compareBlueprintVersions(e,r,n){return this.post(O.COMPARE_BLUEPRINT_VERSIONS,{OsClient:this.config.osClient,BlueprintId:e,...r?{LeftHistoryId:r}:{},...n?{RightHistoryId:n}:{}})}async exportBlueprint(e){return this.post(O.EXPORT_BLUEPRINT,{OsClient:this.config.osClient,BlueprintId:e})}async saveBlueprint(e){return this.post(O.SAVE_BLUEPRINT,{OsClient:this.config.osClient,...e})}async rollbackBlueprint(e){return this.post(O.ROLLBACK_BLUEPRINT,{OsClient:this.config.osClient,...e})}async deleteBlueprint(e){return this.post(O.DELETE_BLUEPRINT,{OsClient:this.config.osClient,BlueprintId:e})}async validateBlueprint(e){return this.post(O.VALIDATE_BLUEPRINT,{OsClient:this.config.osClient,BlueprintId:e})}destroy(){this.refreshTimer&&(clearInterval(this.refreshTimer),this.refreshTimer=void 0)}};var d={};Fd(d,{BRAND:()=>_q,DIRTY:()=>Mi,EMPTY_PATH:()=>eq,INVALID:()=>W,NEVER:()=>aB,OK:()=>_t,ParseStatus:()=>gt,Schema:()=>ae,ZodAny:()=>Kn,ZodArray:()=>xn,ZodBigInt:()=>Fi,ZodBoolean:()=>zi,ZodBranded:()=>ic,ZodCatch:()=>Wi,ZodDate:()=>Li,ZodDefault:()=>Ki,ZodDiscriminatedUnion:()=>dp,ZodEffects:()=>hr,ZodEnum:()=>Zi,ZodError:()=>Zt,ZodFirstPartyTypeKind:()=>M,ZodFunction:()=>mp,ZodIntersection:()=>Bi,ZodIssueCode:()=>N,ZodLazy:()=>Ui,ZodLiteral:()=>Ji,ZodMap:()=>ao,ZodNaN:()=>so,ZodNativeEnum:()=>Hi,ZodNever:()=>Rr,ZodNull:()=>Vi,ZodNullable:()=>Yr,ZodNumber:()=>Di,ZodObject:()=>Kt,ZodOptional:()=>Ht,ZodParsedType:()=>L,ZodPipeline:()=>ac,ZodPromise:()=>Wn,ZodReadonly:()=>Gi,ZodRecord:()=>fp,ZodSchema:()=>ae,ZodSet:()=>oo,ZodString:()=>Hn,ZodSymbol:()=>no,ZodTransformer:()=>hr,ZodTuple:()=>Xr,ZodType:()=>ae,ZodUndefined:()=>ji,ZodUnion:()=>qi,ZodUnknown:()=>vn,ZodVoid:()=>io,addIssueToContext:()=>z,any:()=>Rq,array:()=>Mq,bigint:()=>Tq,boolean:()=>gP,coerce:()=>iB,custom:()=>fP,date:()=>Cq,datetimeRegex:()=>pP,defaultErrorMap:()=>yn,discriminatedUnion:()=>zq,effect:()=>Gq,enum:()=>Hq,function:()=>Uq,getErrorMap:()=>eo,getParsedType:()=>Gr,instanceof:()=>Eq,intersection:()=>Lq,isAborted:()=>up,isAsync:()=>to,isDirty:()=>pp,isValid:()=>Zn,late:()=>Sq,lazy:()=>Jq,literal:()=>Zq,makeIssue:()=>nc,map:()=>qq,nan:()=>kq,nativeEnum:()=>Kq,never:()=>Oq,null:()=>Iq,nullable:()=>Yq,number:()=>hP,object:()=>eb,objectUtil:()=>Xy,oboolean:()=>nB,onumber:()=>rB,optional:()=>Xq,ostring:()=>tB,pipeline:()=>eB,preprocess:()=>Qq,promise:()=>Wq,quotelessJson:()=>XV,record:()=>Vq,set:()=>Bq,setErrorMap:()=>QV,strictObject:()=>Dq,string:()=>mP,symbol:()=>Pq,transformer:()=>Gq,tuple:()=>jq,undefined:()=>Aq,union:()=>Fq,unknown:()=>$q,util:()=>de,void:()=>Nq});var de;(function(t){t.assertEqual=i=>{};function e(i){}t.assertIs=e;function r(i){throw new Error}t.assertNever=r,t.arrayToEnum=i=>{let a={};for(let o of i)a[o]=o;return a},t.getValidEnumValues=i=>{let a=t.objectKeys(i).filter(s=>typeof i[i[s]]!="number"),o={};for(let s of a)o[s]=i[s];return t.objectValues(o)},t.objectValues=i=>t.objectKeys(i).map(function(a){return i[a]}),t.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let a=[];for(let o in i)Object.prototype.hasOwnProperty.call(i,o)&&a.push(o);return a},t.find=(i,a)=>{for(let o of i)if(a(o))return o},t.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function n(i,a=" | "){return i.map(o=>typeof o=="string"?`'${o}'`:o).join(a)}t.joinValues=n,t.jsonStringifyReplacer=(i,a)=>typeof a=="bigint"?a.toString():a})(de||(de={}));var Xy;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Xy||(Xy={}));var L=de.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Gr=t=>{switch(typeof t){case"undefined":return L.undefined;case"string":return L.string;case"number":return Number.isNaN(t)?L.nan:L.number;case"boolean":return L.boolean;case"function":return L.function;case"bigint":return L.bigint;case"symbol":return L.symbol;case"object":return Array.isArray(t)?L.array:t===null?L.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?L.promise:typeof Map<"u"&&t instanceof Map?L.map:typeof Set<"u"&&t instanceof Set?L.set:typeof Date<"u"&&t instanceof Date?L.date:L.object;default:return L.unknown}};var N=de.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"]),XV=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),Zt=class t 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]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(a){return a.message},n={_errors:[]},i=a=>{for(let o of a.issues)if(o.code==="invalid_union")o.unionErrors.map(i);else if(o.code==="invalid_return_type")i(o.returnTypeError);else if(o.code==="invalid_arguments")i(o.argumentsError);else if(o.path.length===0)n._errors.push(r(o));else{let s=n,c=0;for(;c<o.path.length;){let l=o.path[c];c===o.path.length-1?(s[l]=s[l]||{_errors:[]},s[l]._errors.push(r(o))):s[l]=s[l]||{_errors:[]},s=s[l],c++}}};return i(this),n}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,de.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let i of this.issues)if(i.path.length>0){let a=i.path[0];r[a]=r[a]||[],r[a].push(e(i))}else n.push(e(i));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};Zt.create=t=>new Zt(t);var YV=(t,e)=>{let r;switch(t.code){case N.invalid_type:t.received===L.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case N.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,de.jsonStringifyReplacer)}`;break;case N.unrecognized_keys:r=`Unrecognized key(s) in object: ${de.joinValues(t.keys,", ")}`;break;case N.invalid_union:r="Invalid input";break;case N.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${de.joinValues(t.options)}`;break;case N.invalid_enum_value:r=`Invalid enum value. Expected ${de.joinValues(t.options)}, received '${t.received}'`;break;case N.invalid_arguments:r="Invalid function arguments";break;case N.invalid_return_type:r="Invalid function return type";break;case N.invalid_date:r="Invalid date";break;case N.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:de.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case N.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case N.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case N.custom:r="Invalid input";break;case N.invalid_intersection_types:r="Intersection results could not be merged";break;case N.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case N.not_finite:r="Number must be finite";break;default:r=e.defaultError,de.assertNever(t)}return{message:r}},yn=YV;var oP=yn;function QV(t){oP=t}function eo(){return oP}var nc=t=>{let{data:e,path:r,errorMaps:n,issueData:i}=t,a=[...r,...i.path||[]],o={...i,path:a};if(i.message!==void 0)return{...i,path:a,message:i.message};let s="",c=n.filter(l=>!!l).slice().reverse();for(let l of c)s=l(o,{data:e,defaultError:s}).message;return{...i,path:a,message:s}},eq=[];function z(t,e){let r=eo(),n=nc({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===yn?void 0:yn].filter(i=>!!i)});t.common.issues.push(n)}var gt=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let i of r){if(i.status==="aborted")return W;i.status==="dirty"&&e.dirty(),n.push(i.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let i of r){let a=await i.key,o=await i.value;n.push({key:a,value:o})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let i of r){let{key:a,value:o}=i;if(a.status==="aborted"||o.status==="aborted")return W;a.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),a.value!=="__proto__"&&(typeof o.value<"u"||i.alwaysSet)&&(n[a.value]=o.value)}return{status:e.value,value:n}}},W=Object.freeze({status:"aborted"}),Mi=t=>({status:"dirty",value:t}),_t=t=>({status:"valid",value:t}),up=t=>t.status==="aborted",pp=t=>t.status==="dirty",Zn=t=>t.status==="valid",to=t=>typeof Promise<"u"&&t instanceof Promise;var q;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(q||(q={}));var mr=class{constructor(e,r,n,i){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=i}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},sP=(t,e)=>{if(Zn(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new Zt(t.common.issues);return this._error=r,this._error}}};function re(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:i}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:i}:{errorMap:(o,s)=>{let{message:c}=t;return o.code==="invalid_enum_value"?{message:c??s.defaultError}:typeof s.data>"u"?{message:c??n??s.defaultError}:o.code!=="invalid_type"?{message:s.defaultError}:{message:c??r??s.defaultError}},description:i}}var ae=class{get description(){return this._def.description}_getType(e){return Gr(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:Gr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new gt,ctx:{common:e.parent.common,data:e.data,parsedType:Gr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(to(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Gr(e)},i=this._parseSync({data:e,path:n.path,parent:n});return sP(n,i)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Gr(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return Zn(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>Zn(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Gr(e)},i=this._parse({data:e,path:n.path,parent:n}),a=await(to(i)?i:Promise.resolve(i));return sP(n,a)}refine(e,r){let n=i=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(i):r;return this._refinement((i,a)=>{let o=e(i),s=()=>a.addIssue({code:N.custom,...n(i)});return typeof Promise<"u"&&o instanceof Promise?o.then(c=>c?!0:(s(),!1)):o?!0:(s(),!1)})}refinement(e,r){return this._refinement((n,i)=>e(n)?!0:(i.addIssue(typeof r=="function"?r(n,i):r),!1))}_refinement(e){return new hr({schema:this,typeName:M.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return Ht.create(this,this._def)}nullable(){return Yr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return xn.create(this)}promise(){return Wn.create(this,this._def)}or(e){return qi.create([this,e],this._def)}and(e){return Bi.create(this,e,this._def)}transform(e){return new hr({...re(this._def),schema:this,typeName:M.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new Ki({...re(this._def),innerType:this,defaultValue:r,typeName:M.ZodDefault})}brand(){return new ic({typeName:M.ZodBranded,type:this,...re(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Wi({...re(this._def),innerType:this,catchValue:r,typeName:M.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return ac.create(this,e)}readonly(){return Gi.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},tq=/^c[^\s-]{8,}$/i,rq=/^[0-9a-z]+$/,nq=/^[0-9A-HJKMNP-TV-Z]{26}$/i,iq=/^[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,aq=/^[a-z0-9_-]{21}$/i,oq=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,sq=/^[-+]?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)?)??$/,cq=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,lq="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Yy,uq=/^(?:(?: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])$/,pq=/^(?:(?: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])$/,dq=/^(([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]))$/,fq=/^(([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])$/,mq=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,hq=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,lP="((\\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])))",gq=new RegExp(`^${lP}$`);function uP(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function yq(t){return new RegExp(`^${uP(t)}$`)}function pP(t){let e=`${lP}T${uP(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function bq(t,e){return!!((e==="v4"||!e)&&uq.test(t)||(e==="v6"||!e)&&dq.test(t))}function vq(t,e){if(!oq.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),i=JSON.parse(atob(n));return!(typeof i!="object"||i===null||"typ"in i&&i?.typ!=="JWT"||!i.alg||e&&i.alg!==e)}catch{return!1}}function xq(t,e){return!!((e==="v4"||!e)&&pq.test(t)||(e==="v6"||!e)&&fq.test(t))}var Hn=class t extends ae{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==L.string){let a=this._getOrReturnCtx(e);return z(a,{code:N.invalid_type,expected:L.string,received:a.parsedType}),W}let n=new gt,i;for(let a of this._def.checks)if(a.kind==="min")e.data.length<a.value&&(i=this._getOrReturnCtx(e,i),z(i,{code:N.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),n.dirty());else if(a.kind==="max")e.data.length>a.value&&(i=this._getOrReturnCtx(e,i),z(i,{code:N.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),n.dirty());else if(a.kind==="length"){let o=e.data.length>a.value,s=e.data.length<a.value;(o||s)&&(i=this._getOrReturnCtx(e,i),o?z(i,{code:N.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}):s&&z(i,{code:N.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}),n.dirty())}else if(a.kind==="email")cq.test(e.data)||(i=this._getOrReturnCtx(e,i),z(i,{validation:"email",code:N.invalid_string,message:a.message}),n.dirty());else if(a.kind==="emoji")Yy||(Yy=new RegExp(lq,"u")),Yy.test(e.data)||(i=this._getOrReturnCtx(e,i),z(i,{validation:"emoji",code:N.invalid_string,message:a.message}),n.dirty());else if(a.kind==="uuid")iq.test(e.data)||(i=this._getOrReturnCtx(e,i),z(i,{validation:"uuid",code:N.invalid_string,message:a.message}),n.dirty());else if(a.kind==="nanoid")aq.test(e.data)||(i=this._getOrReturnCtx(e,i),z(i,{validation:"nanoid",code:N.invalid_string,message:a.message}),n.dirty());else if(a.kind==="cuid")tq.test(e.data)||(i=this._getOrReturnCtx(e,i),z(i,{validation:"cuid",code:N.invalid_string,message:a.message}),n.dirty());else if(a.kind==="cuid2")rq.test(e.data)||(i=this._getOrReturnCtx(e,i),z(i,{validation:"cuid2",code:N.invalid_string,message:a.message}),n.dirty());else if(a.kind==="ulid")nq.test(e.data)||(i=this._getOrReturnCtx(e,i),z(i,{validation:"ulid",code:N.invalid_string,message:a.message}),n.dirty());else if(a.kind==="url")try{new URL(e.data)}catch{i=this._getOrReturnCtx(e,i),z(i,{validation:"url",code:N.invalid_string,message:a.message}),n.dirty()}else a.kind==="regex"?(a.regex.lastIndex=0,a.regex.test(e.data)||(i=this._getOrReturnCtx(e,i),z(i,{validation:"regex",code:N.invalid_string,message:a.message}),n.dirty())):a.kind==="trim"?e.data=e.data.trim():a.kind==="includes"?e.data.includes(a.value,a.position)||(i=this._getOrReturnCtx(e,i),z(i,{code:N.invalid_string,validation:{includes:a.value,position:a.position},message:a.message}),n.dirty()):a.kind==="toLowerCase"?e.data=e.data.toLowerCase():a.kind==="toUpperCase"?e.data=e.data.toUpperCase():a.kind==="startsWith"?e.data.startsWith(a.value)||(i=this._getOrReturnCtx(e,i),z(i,{code:N.invalid_string,validation:{startsWith:a.value},message:a.message}),n.dirty()):a.kind==="endsWith"?e.data.endsWith(a.value)||(i=this._getOrReturnCtx(e,i),z(i,{code:N.invalid_string,validation:{endsWith:a.value},message:a.message}),n.dirty()):a.kind==="datetime"?pP(a).test(e.data)||(i=this._getOrReturnCtx(e,i),z(i,{code:N.invalid_string,validation:"datetime",message:a.message}),n.dirty()):a.kind==="date"?gq.test(e.data)||(i=this._getOrReturnCtx(e,i),z(i,{code:N.invalid_string,validation:"date",message:a.message}),n.dirty()):a.kind==="time"?yq(a).test(e.data)||(i=this._getOrReturnCtx(e,i),z(i,{code:N.invalid_string,validation:"time",message:a.message}),n.dirty()):a.kind==="duration"?sq.test(e.data)||(i=this._getOrReturnCtx(e,i),z(i,{validation:"duration",code:N.invalid_string,message:a.message}),n.dirty()):a.kind==="ip"?bq(e.data,a.version)||(i=this._getOrReturnCtx(e,i),z(i,{validation:"ip",code:N.invalid_string,message:a.message}),n.dirty()):a.kind==="jwt"?vq(e.data,a.alg)||(i=this._getOrReturnCtx(e,i),z(i,{validation:"jwt",code:N.invalid_string,message:a.message}),n.dirty()):a.kind==="cidr"?xq(e.data,a.version)||(i=this._getOrReturnCtx(e,i),z(i,{validation:"cidr",code:N.invalid_string,message:a.message}),n.dirty()):a.kind==="base64"?mq.test(e.data)||(i=this._getOrReturnCtx(e,i),z(i,{validation:"base64",code:N.invalid_string,message:a.message}),n.dirty()):a.kind==="base64url"?hq.test(e.data)||(i=this._getOrReturnCtx(e,i),z(i,{validation:"base64url",code:N.invalid_string,message:a.message}),n.dirty()):de.assertNever(a);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(i=>e.test(i),{validation:r,code:N.invalid_string,...q.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...q.errToObj(e)})}url(e){return this._addCheck({kind:"url",...q.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...q.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...q.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...q.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...q.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...q.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...q.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...q.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...q.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...q.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...q.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...q.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...q.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...q.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...q.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...q.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...q.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...q.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...q.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...q.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...q.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...q.errToObj(r)})}nonempty(e){return this.min(1,q.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Hn.create=t=>new Hn({checks:[],typeName:M.ZodString,coerce:t?.coerce??!1,...re(t)});function wq(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,i=r>n?r:n,a=Number.parseInt(t.toFixed(i).replace(".","")),o=Number.parseInt(e.toFixed(i).replace(".",""));return a%o/10**i}var Di=class t extends ae{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==L.number){let a=this._getOrReturnCtx(e);return z(a,{code:N.invalid_type,expected:L.number,received:a.parsedType}),W}let n,i=new gt;for(let a of this._def.checks)a.kind==="int"?de.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),z(n,{code:N.invalid_type,expected:"integer",received:"float",message:a.message}),i.dirty()):a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(n=this._getOrReturnCtx(e,n),z(n,{code:N.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),i.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(n=this._getOrReturnCtx(e,n),z(n,{code:N.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),i.dirty()):a.kind==="multipleOf"?wq(e.data,a.value)!==0&&(n=this._getOrReturnCtx(e,n),z(n,{code:N.not_multiple_of,multipleOf:a.value,message:a.message}),i.dirty()):a.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),z(n,{code:N.not_finite,message:a.message}),i.dirty()):de.assertNever(a);return{status:i.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,q.toString(r))}gt(e,r){return this.setLimit("min",e,!1,q.toString(r))}lte(e,r){return this.setLimit("max",e,!0,q.toString(r))}lt(e,r){return this.setLimit("max",e,!1,q.toString(r))}setLimit(e,r,n,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:q.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:q.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:q.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:q.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:q.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:q.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:q.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:q.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:q.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:q.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&de.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};Di.create=t=>new Di({checks:[],typeName:M.ZodNumber,coerce:t?.coerce||!1,...re(t)});var Fi=class t extends ae{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==L.bigint)return this._getInvalidInput(e);let n,i=new gt;for(let a of this._def.checks)a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(n=this._getOrReturnCtx(e,n),z(n,{code:N.too_small,type:"bigint",minimum:a.value,inclusive:a.inclusive,message:a.message}),i.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(n=this._getOrReturnCtx(e,n),z(n,{code:N.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),i.dirty()):a.kind==="multipleOf"?e.data%a.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),z(n,{code:N.not_multiple_of,multipleOf:a.value,message:a.message}),i.dirty()):de.assertNever(a);return{status:i.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return z(r,{code:N.invalid_type,expected:L.bigint,received:r.parsedType}),W}gte(e,r){return this.setLimit("min",e,!0,q.toString(r))}gt(e,r){return this.setLimit("min",e,!1,q.toString(r))}lte(e,r){return this.setLimit("max",e,!0,q.toString(r))}lt(e,r){return this.setLimit("max",e,!1,q.toString(r))}setLimit(e,r,n,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:q.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:q.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:q.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:q.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:q.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:q.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Fi.create=t=>new Fi({checks:[],typeName:M.ZodBigInt,coerce:t?.coerce??!1,...re(t)});var zi=class extends ae{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==L.boolean){let n=this._getOrReturnCtx(e);return z(n,{code:N.invalid_type,expected:L.boolean,received:n.parsedType}),W}return _t(e.data)}};zi.create=t=>new zi({typeName:M.ZodBoolean,coerce:t?.coerce||!1,...re(t)});var Li=class t extends ae{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==L.date){let a=this._getOrReturnCtx(e);return z(a,{code:N.invalid_type,expected:L.date,received:a.parsedType}),W}if(Number.isNaN(e.data.getTime())){let a=this._getOrReturnCtx(e);return z(a,{code:N.invalid_date}),W}let n=new gt,i;for(let a of this._def.checks)a.kind==="min"?e.data.getTime()<a.value&&(i=this._getOrReturnCtx(e,i),z(i,{code:N.too_small,message:a.message,inclusive:!0,exact:!1,minimum:a.value,type:"date"}),n.dirty()):a.kind==="max"?e.data.getTime()>a.value&&(i=this._getOrReturnCtx(e,i),z(i,{code:N.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),n.dirty()):de.assertNever(a);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:q.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:q.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};Li.create=t=>new Li({checks:[],coerce:t?.coerce||!1,typeName:M.ZodDate,...re(t)});var no=class extends ae{_parse(e){if(this._getType(e)!==L.symbol){let n=this._getOrReturnCtx(e);return z(n,{code:N.invalid_type,expected:L.symbol,received:n.parsedType}),W}return _t(e.data)}};no.create=t=>new no({typeName:M.ZodSymbol,...re(t)});var ji=class extends ae{_parse(e){if(this._getType(e)!==L.undefined){let n=this._getOrReturnCtx(e);return z(n,{code:N.invalid_type,expected:L.undefined,received:n.parsedType}),W}return _t(e.data)}};ji.create=t=>new ji({typeName:M.ZodUndefined,...re(t)});var Vi=class extends ae{_parse(e){if(this._getType(e)!==L.null){let n=this._getOrReturnCtx(e);return z(n,{code:N.invalid_type,expected:L.null,received:n.parsedType}),W}return _t(e.data)}};Vi.create=t=>new Vi({typeName:M.ZodNull,...re(t)});var Kn=class extends ae{constructor(){super(...arguments),this._any=!0}_parse(e){return _t(e.data)}};Kn.create=t=>new Kn({typeName:M.ZodAny,...re(t)});var vn=class extends ae{constructor(){super(...arguments),this._unknown=!0}_parse(e){return _t(e.data)}};vn.create=t=>new vn({typeName:M.ZodUnknown,...re(t)});var Rr=class extends ae{_parse(e){let r=this._getOrReturnCtx(e);return z(r,{code:N.invalid_type,expected:L.never,received:r.parsedType}),W}};Rr.create=t=>new Rr({typeName:M.ZodNever,...re(t)});var io=class extends ae{_parse(e){if(this._getType(e)!==L.undefined){let n=this._getOrReturnCtx(e);return z(n,{code:N.invalid_type,expected:L.void,received:n.parsedType}),W}return _t(e.data)}};io.create=t=>new io({typeName:M.ZodVoid,...re(t)});var xn=class t extends ae{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),i=this._def;if(r.parsedType!==L.array)return z(r,{code:N.invalid_type,expected:L.array,received:r.parsedType}),W;if(i.exactLength!==null){let o=r.data.length>i.exactLength.value,s=r.data.length<i.exactLength.value;(o||s)&&(z(r,{code:o?N.too_big:N.too_small,minimum:s?i.exactLength.value:void 0,maximum:o?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),n.dirty())}if(i.minLength!==null&&r.data.length<i.minLength.value&&(z(r,{code:N.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),n.dirty()),i.maxLength!==null&&r.data.length>i.maxLength.value&&(z(r,{code:N.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((o,s)=>i.type._parseAsync(new mr(r,o,r.path,s)))).then(o=>gt.mergeArray(n,o));let a=[...r.data].map((o,s)=>i.type._parseSync(new mr(r,o,r.path,s)));return gt.mergeArray(n,a)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:q.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:q.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:q.toString(r)}})}nonempty(e){return this.min(1,e)}};xn.create=(t,e)=>new xn({type:t,minLength:null,maxLength:null,exactLength:null,typeName:M.ZodArray,...re(e)});function ro(t){if(t instanceof Kt){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=Ht.create(ro(n))}return new Kt({...t._def,shape:()=>e})}else return t instanceof xn?new xn({...t._def,type:ro(t.element)}):t instanceof Ht?Ht.create(ro(t.unwrap())):t instanceof Yr?Yr.create(ro(t.unwrap())):t instanceof Xr?Xr.create(t.items.map(e=>ro(e))):t}var Kt=class t extends ae{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=de.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==L.object){let l=this._getOrReturnCtx(e);return z(l,{code:N.invalid_type,expected:L.object,received:l.parsedType}),W}let{status:n,ctx:i}=this._processInputParams(e),{shape:a,keys:o}=this._getCached(),s=[];if(!(this._def.catchall instanceof Rr&&this._def.unknownKeys==="strip"))for(let l in i.data)o.includes(l)||s.push(l);let c=[];for(let l of o){let u=a[l],p=i.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new mr(i,p,i.path,l)),alwaysSet:l in i.data})}if(this._def.catchall instanceof Rr){let l=this._def.unknownKeys;if(l==="passthrough")for(let u of s)c.push({key:{status:"valid",value:u},value:{status:"valid",value:i.data[u]}});else if(l==="strict")s.length>0&&(z(i,{code:N.unrecognized_keys,keys:s}),n.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let u of s){let p=i.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new mr(i,p,i.path,u)),alwaysSet:u in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let l=[];for(let u of c){let p=await u.key,f=await u.value;l.push({key:p,value:f,alwaysSet:u.alwaysSet})}return l}).then(l=>gt.mergeObjectSync(n,l)):gt.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return q.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let i=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:q.errToObj(e).message??i}:{message:i}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:M.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of de.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let n of de.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return ro(this)}partial(e){let r={};for(let n of de.objectKeys(this.shape)){let i=this.shape[n];e&&!e[n]?r[n]=i:r[n]=i.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of de.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let a=this.shape[n];for(;a instanceof Ht;)a=a._def.innerType;r[n]=a}return new t({...this._def,shape:()=>r})}keyof(){return dP(de.objectKeys(this.shape))}};Kt.create=(t,e)=>new Kt({shape:()=>t,unknownKeys:"strip",catchall:Rr.create(),typeName:M.ZodObject,...re(e)});Kt.strictCreate=(t,e)=>new Kt({shape:()=>t,unknownKeys:"strict",catchall:Rr.create(),typeName:M.ZodObject,...re(e)});Kt.lazycreate=(t,e)=>new Kt({shape:t,unknownKeys:"strip",catchall:Rr.create(),typeName:M.ZodObject,...re(e)});var qi=class extends ae{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function i(a){for(let s of a)if(s.result.status==="valid")return s.result;for(let s of a)if(s.result.status==="dirty")return r.common.issues.push(...s.ctx.common.issues),s.result;let o=a.map(s=>new Zt(s.ctx.common.issues));return z(r,{code:N.invalid_union,unionErrors:o}),W}if(r.common.async)return Promise.all(n.map(async a=>{let o={...r,common:{...r.common,issues:[]},parent:null};return{result:await a._parseAsync({data:r.data,path:r.path,parent:o}),ctx:o}})).then(i);{let a,o=[];for(let c of n){let l={...r,common:{...r.common,issues:[]},parent:null},u=c._parseSync({data:r.data,path:r.path,parent:l});if(u.status==="valid")return u;u.status==="dirty"&&!a&&(a={result:u,ctx:l}),l.common.issues.length&&o.push(l.common.issues)}if(a)return r.common.issues.push(...a.ctx.common.issues),a.result;let s=o.map(c=>new Zt(c));return z(r,{code:N.invalid_union,unionErrors:s}),W}}get options(){return this._def.options}};qi.create=(t,e)=>new qi({options:t,typeName:M.ZodUnion,...re(e)});var bn=t=>t instanceof Ui?bn(t.schema):t instanceof hr?bn(t.innerType()):t instanceof Ji?[t.value]:t instanceof Zi?t.options:t instanceof Hi?de.objectValues(t.enum):t instanceof Ki?bn(t._def.innerType):t instanceof ji?[void 0]:t instanceof Vi?[null]:t instanceof Ht?[void 0,...bn(t.unwrap())]:t instanceof Yr?[null,...bn(t.unwrap())]:t instanceof ic||t instanceof Gi?bn(t.unwrap()):t instanceof Wi?bn(t._def.innerType):[],dp=class t extends ae{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==L.object)return z(r,{code:N.invalid_type,expected:L.object,received:r.parsedType}),W;let n=this.discriminator,i=r.data[n],a=this.optionsMap.get(i);return a?r.common.async?a._parseAsync({data:r.data,path:r.path,parent:r}):a._parseSync({data:r.data,path:r.path,parent:r}):(z(r,{code:N.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),W)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let i=new Map;for(let a of r){let o=bn(a.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let s of o){if(i.has(s))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(s)}`);i.set(s,a)}}return new t({typeName:M.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:i,...re(n)})}};function Qy(t,e){let r=Gr(t),n=Gr(e);if(t===e)return{valid:!0,data:t};if(r===L.object&&n===L.object){let i=de.objectKeys(e),a=de.objectKeys(t).filter(s=>i.indexOf(s)!==-1),o={...t,...e};for(let s of a){let c=Qy(t[s],e[s]);if(!c.valid)return{valid:!1};o[s]=c.data}return{valid:!0,data:o}}else if(r===L.array&&n===L.array){if(t.length!==e.length)return{valid:!1};let i=[];for(let a=0;a<t.length;a++){let o=t[a],s=e[a],c=Qy(o,s);if(!c.valid)return{valid:!1};i.push(c.data)}return{valid:!0,data:i}}else return r===L.date&&n===L.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var Bi=class extends ae{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),i=(a,o)=>{if(up(a)||up(o))return W;let s=Qy(a.value,o.value);return s.valid?((pp(a)||pp(o))&&r.dirty(),{status:r.value,value:s.data}):(z(n,{code:N.invalid_intersection_types}),W)};return n.common.async?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(([a,o])=>i(a,o)):i(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};Bi.create=(t,e,r)=>new Bi({left:t,right:e,typeName:M.ZodIntersection,...re(r)});var Xr=class t extends ae{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==L.array)return z(n,{code:N.invalid_type,expected:L.array,received:n.parsedType}),W;if(n.data.length<this._def.items.length)return z(n,{code:N.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),W;!this._def.rest&&n.data.length>this._def.items.length&&(z(n,{code:N.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let a=[...n.data].map((o,s)=>{let c=this._def.items[s]||this._def.rest;return c?c._parse(new mr(n,o,n.path,s)):null}).filter(o=>!!o);return n.common.async?Promise.all(a).then(o=>gt.mergeArray(r,o)):gt.mergeArray(r,a)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Xr.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Xr({items:t,typeName:M.ZodTuple,rest:null,...re(e)})};var fp=class t extends ae{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==L.object)return z(n,{code:N.invalid_type,expected:L.object,received:n.parsedType}),W;let i=[],a=this._def.keyType,o=this._def.valueType;for(let s in n.data)i.push({key:a._parse(new mr(n,s,n.path,s)),value:o._parse(new mr(n,n.data[s],n.path,s)),alwaysSet:s in n.data});return n.common.async?gt.mergeObjectAsync(r,i):gt.mergeObjectSync(r,i)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof ae?new t({keyType:e,valueType:r,typeName:M.ZodRecord,...re(n)}):new t({keyType:Hn.create(),valueType:e,typeName:M.ZodRecord,...re(r)})}},ao=class extends ae{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==L.map)return z(n,{code:N.invalid_type,expected:L.map,received:n.parsedType}),W;let i=this._def.keyType,a=this._def.valueType,o=[...n.data.entries()].map(([s,c],l)=>({key:i._parse(new mr(n,s,n.path,[l,"key"])),value:a._parse(new mr(n,c,n.path,[l,"value"]))}));if(n.common.async){let s=new Map;return Promise.resolve().then(async()=>{for(let c of o){let l=await c.key,u=await c.value;if(l.status==="aborted"||u.status==="aborted")return W;(l.status==="dirty"||u.status==="dirty")&&r.dirty(),s.set(l.value,u.value)}return{status:r.value,value:s}})}else{let s=new Map;for(let c of o){let l=c.key,u=c.value;if(l.status==="aborted"||u.status==="aborted")return W;(l.status==="dirty"||u.status==="dirty")&&r.dirty(),s.set(l.value,u.value)}return{status:r.value,value:s}}}};ao.create=(t,e,r)=>new ao({valueType:e,keyType:t,typeName:M.ZodMap,...re(r)});var oo=class t extends ae{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==L.set)return z(n,{code:N.invalid_type,expected:L.set,received:n.parsedType}),W;let i=this._def;i.minSize!==null&&n.data.size<i.minSize.value&&(z(n,{code:N.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),r.dirty()),i.maxSize!==null&&n.data.size>i.maxSize.value&&(z(n,{code:N.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),r.dirty());let a=this._def.valueType;function o(c){let l=new Set;for(let u of c){if(u.status==="aborted")return W;u.status==="dirty"&&r.dirty(),l.add(u.value)}return{status:r.value,value:l}}let s=[...n.data.values()].map((c,l)=>a._parse(new mr(n,c,n.path,l)));return n.common.async?Promise.all(s).then(c=>o(c)):o(s)}min(e,r){return new t({...this._def,minSize:{value:e,message:q.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:q.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};oo.create=(t,e)=>new oo({valueType:t,minSize:null,maxSize:null,typeName:M.ZodSet,...re(e)});var mp=class t extends ae{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==L.function)return z(r,{code:N.invalid_type,expected:L.function,received:r.parsedType}),W;function n(s,c){return nc({data:s,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,eo(),yn].filter(l=>!!l),issueData:{code:N.invalid_arguments,argumentsError:c}})}function i(s,c){return nc({data:s,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,eo(),yn].filter(l=>!!l),issueData:{code:N.invalid_return_type,returnTypeError:c}})}let a={errorMap:r.common.contextualErrorMap},o=r.data;if(this._def.returns instanceof Wn){let s=this;return _t(async function(...c){let l=new Zt([]),u=await s._def.args.parseAsync(c,a).catch(h=>{throw l.addIssue(n(c,h)),l}),p=await Reflect.apply(o,this,u);return await s._def.returns._def.type.parseAsync(p,a).catch(h=>{throw l.addIssue(i(p,h)),l})})}else{let s=this;return _t(function(...c){let l=s._def.args.safeParse(c,a);if(!l.success)throw new Zt([n(c,l.error)]);let u=Reflect.apply(o,this,l.data),p=s._def.returns.safeParse(u,a);if(!p.success)throw new Zt([i(u,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:Xr.create(e).rest(vn.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||Xr.create([]).rest(vn.create()),returns:r||vn.create(),typeName:M.ZodFunction,...re(n)})}},Ui=class extends ae{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};Ui.create=(t,e)=>new Ui({getter:t,typeName:M.ZodLazy,...re(e)});var Ji=class extends ae{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return z(r,{received:r.data,code:N.invalid_literal,expected:this._def.value}),W}return{status:"valid",value:e.data}}get value(){return this._def.value}};Ji.create=(t,e)=>new Ji({value:t,typeName:M.ZodLiteral,...re(e)});function dP(t,e){return new Zi({values:t,typeName:M.ZodEnum,...re(e)})}var Zi=class t extends ae{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return z(r,{expected:de.joinValues(n),received:r.parsedType,code:N.invalid_type}),W}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return z(r,{received:r.data,code:N.invalid_enum_value,options:n}),W}return _t(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};Zi.create=dP;var Hi=class extends ae{_parse(e){let r=de.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==L.string&&n.parsedType!==L.number){let i=de.objectValues(r);return z(n,{expected:de.joinValues(i),received:n.parsedType,code:N.invalid_type}),W}if(this._cache||(this._cache=new Set(de.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let i=de.objectValues(r);return z(n,{received:n.data,code:N.invalid_enum_value,options:i}),W}return _t(e.data)}get enum(){return this._def.values}};Hi.create=(t,e)=>new Hi({values:t,typeName:M.ZodNativeEnum,...re(e)});var Wn=class extends ae{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==L.promise&&r.common.async===!1)return z(r,{code:N.invalid_type,expected:L.promise,received:r.parsedType}),W;let n=r.parsedType===L.promise?r.data:Promise.resolve(r.data);return _t(n.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Wn.create=(t,e)=>new Wn({type:t,typeName:M.ZodPromise,...re(e)});var hr=class extends ae{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===M.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),i=this._def.effect||null,a={addIssue:o=>{z(n,o),o.fatal?r.abort():r.dirty()},get path(){return n.path}};if(a.addIssue=a.addIssue.bind(a),i.type==="preprocess"){let o=i.transform(n.data,a);if(n.common.async)return Promise.resolve(o).then(async s=>{if(r.value==="aborted")return W;let c=await this._def.schema._parseAsync({data:s,path:n.path,parent:n});return c.status==="aborted"?W:c.status==="dirty"?Mi(c.value):r.value==="dirty"?Mi(c.value):c});{if(r.value==="aborted")return W;let s=this._def.schema._parseSync({data:o,path:n.path,parent:n});return s.status==="aborted"?W:s.status==="dirty"?Mi(s.value):r.value==="dirty"?Mi(s.value):s}}if(i.type==="refinement"){let o=s=>{let c=i.refinement(s,a);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 s};if(n.common.async===!1){let s=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?W:(s.status==="dirty"&&r.dirty(),o(s.value),{status:r.value,value:s.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(s=>s.status==="aborted"?W:(s.status==="dirty"&&r.dirty(),o(s.value).then(()=>({status:r.value,value:s.value}))))}if(i.type==="transform")if(n.common.async===!1){let o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Zn(o))return W;let s=i.transform(o.value,a);if(s instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:s}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>Zn(o)?Promise.resolve(i.transform(o.value,a)).then(s=>({status:r.value,value:s})):W);de.assertNever(i)}};hr.create=(t,e,r)=>new hr({schema:t,typeName:M.ZodEffects,effect:e,...re(r)});hr.createWithPreprocess=(t,e,r)=>new hr({schema:e,effect:{type:"preprocess",transform:t},typeName:M.ZodEffects,...re(r)});var Ht=class extends ae{_parse(e){return this._getType(e)===L.undefined?_t(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Ht.create=(t,e)=>new Ht({innerType:t,typeName:M.ZodOptional,...re(e)});var Yr=class extends ae{_parse(e){return this._getType(e)===L.null?_t(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Yr.create=(t,e)=>new Yr({innerType:t,typeName:M.ZodNullable,...re(e)});var Ki=class extends ae{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===L.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};Ki.create=(t,e)=>new Ki({innerType:t,typeName:M.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...re(e)});var Wi=class extends ae{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},i=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return to(i)?i.then(a=>({status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new Zt(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Zt(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Wi.create=(t,e)=>new Wi({innerType:t,typeName:M.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...re(e)});var so=class extends ae{_parse(e){if(this._getType(e)!==L.nan){let n=this._getOrReturnCtx(e);return z(n,{code:N.invalid_type,expected:L.nan,received:n.parsedType}),W}return{status:"valid",value:e.data}}};so.create=t=>new so({typeName:M.ZodNaN,...re(t)});var _q=Symbol("zod_brand"),ic=class extends ae{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},ac=class t extends ae{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let a=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?W:a.status==="dirty"?(r.dirty(),Mi(a.value)):this._def.out._parseAsync({data:a.value,path:n.path,parent:n})})();{let i=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?W:i.status==="dirty"?(r.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:M.ZodPipeline})}},Gi=class extends ae{_parse(e){let r=this._def.innerType._parse(e),n=i=>(Zn(i)&&(i.value=Object.freeze(i.value)),i);return to(r)?r.then(i=>n(i)):n(r)}unwrap(){return this._def.innerType}};Gi.create=(t,e)=>new Gi({innerType:t,typeName:M.ZodReadonly,...re(e)});function cP(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function fP(t,e={},r){return t?Kn.create().superRefine((n,i)=>{let a=t(n);if(a instanceof Promise)return a.then(o=>{if(!o){let s=cP(e,n),c=s.fatal??r??!0;i.addIssue({code:"custom",...s,fatal:c})}});if(!a){let o=cP(e,n),s=o.fatal??r??!0;i.addIssue({code:"custom",...o,fatal:s})}}):Kn.create()}var Sq={object:Kt.lazycreate},M;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(M||(M={}));var Eq=(t,e={message:`Input not instance of ${t.name}`})=>fP(r=>r instanceof t,e),mP=Hn.create,hP=Di.create,kq=so.create,Tq=Fi.create,gP=zi.create,Cq=Li.create,Pq=no.create,Aq=ji.create,Iq=Vi.create,Rq=Kn.create,$q=vn.create,Oq=Rr.create,Nq=io.create,Mq=xn.create,eb=Kt.create,Dq=Kt.strictCreate,Fq=qi.create,zq=dp.create,Lq=Bi.create,jq=Xr.create,Vq=fp.create,qq=ao.create,Bq=oo.create,Uq=mp.create,Jq=Ui.create,Zq=Ji.create,Hq=Zi.create,Kq=Hi.create,Wq=Wn.create,Gq=hr.create,Xq=Ht.create,Yq=Yr.create,Qq=hr.createWithPreprocess,eB=ac.create,tB=()=>mP().optional(),rB=()=>hP().optional(),nB=()=>gP().optional(),iB={string:t=>Hn.create({...t,coerce:!0}),number:t=>Di.create({...t,coerce:!0}),boolean:t=>zi.create({...t,coerce:!0}),bigint:t=>Fi.create({...t,coerce:!0}),date:t=>Li.create({...t,coerce:!0})};var aB=W;var sB=R("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");Pe.init(t,e),t.def=e,t.parse=(r,n)=>Xd(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>mi(t,r,n),t.parseAsync=async(r,n)=>Qd(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>hi(t,r,n),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>rr(t,r,n),t.brand=()=>t,t.register=(r,n)=>(r.add(t,n),t)});var cB=R("ZodMiniObject",(t,e)=>{il.init(t,e),sB.init(t,e),fe.defineLazy(t,"shape",()=>e.shape)});function tb(t,e){let r={type:"object",get shape(){return fe.assignProp(this,"shape",{...t}),this.shape},...fe.normalizeParams(e)};return new cB(r)}function gr(t){return!!t._zod}function Xi(t){let e=Object.values(t);if(e.length===0)return tb({});let r=e.every(gr),n=e.every(i=>!gr(i));if(r)return tb(t);if(n)return eb(t);throw new Error("Mixed Zod versions detected in object shape.")}function Gn(t,e){return gr(t)?mi(t,e):t.safeParse(e)}async function hp(t,e){return gr(t)?await hi(t,e):await t.safeParseAsync(e)}function Xn(t){if(!t)return;let e;if(gr(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function co(t){if(t){if(typeof t=="object"){let e=t,r=t;if(!e._def&&!r._zod){let n=Object.values(t);if(n.length>0&&n.every(i=>typeof i=="object"&&i!==null&&(i._def!==void 0||i._zod!==void 0||typeof i.parse=="function")))return Xi(t)}}if(gr(t)){let r=t._zod?.def;if(r&&(r.type==="object"||r.shape!==void 0))return t}else if(t.shape!==void 0)return t}}function gp(t){if(t&&typeof t=="object"){if("message"in t&&typeof t.message=="string")return t.message;if("issues"in t&&Array.isArray(t.issues)&&t.issues.length>0){let e=t.issues[0];if(e&&typeof e=="object"&&"message"in e)return String(e.message)}try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function yP(t){return t.description}function bP(t){if(gr(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function yp(t){if(gr(t)){let a=t._zod?.def;if(a){if(a.value!==void 0)return a.value;if(Array.isArray(a.values)&&a.values.length>0)return a.values[0]}}let r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=t.value;if(n!==void 0)return n}function Yn(t){return t==="completed"||t==="failed"||t==="cancelled"}var xP=Symbol("Let zodToJsonSchema decide on which parser to use");var vP={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},wP=t=>typeof t=="string"?{...vP,name:t}:{...vP,...t};var _P=t=>{let e=wP(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,i])=>[i._def,{def:i._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}};function rb(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function ye(t,e,r,n,i){t[e]=r,rb(t,e,n,i)}var bp=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")};function Je(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?bp(e,t.currentPath):e.join("/")}}function SP(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==M.ZodAny&&(r.items=G(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&ye(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&ye(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(ye(r,"minItems",t.exactLength.value,t.exactLength.message,e),ye(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function EP(t,e){let r={type:"integer",format:"int64"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?ye(r,"minimum",n.value,n.message,e):ye(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ye(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ye(r,"maximum",n.value,n.message,e):ye(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ye(r,"maximum",n.value,n.message,e));break;case"multipleOf":ye(r,"multipleOf",n.value,n.message,e);break}return r}function kP(){return{type:"boolean"}}function vp(t,e){return G(t.type._def,e)}var TP=(t,e)=>G(t.innerType._def,e);function nb(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((i,a)=>nb(t,e,i))};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 uB(t,e)}}var uB=(t,e)=>{let r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(let n of t.checks)switch(n.kind){case"min":ye(r,"minimum",n.value,n.message,e);break;case"max":ye(r,"maximum",n.value,n.message,e);break}return r};function CP(t,e){return{...G(t.innerType._def,e),default:t.defaultValue()}}function PP(t,e){return e.effectStrategy==="input"?G(t.schema._def,e):Je(e)}function AP(t){return{type:"string",enum:Array.from(t.values)}}var pB=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function IP(t,e){let r=[G(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),G(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(a=>!!a),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,i=[];return r.forEach(a=>{if(pB(a))i.push(...a.allOf),a.unevaluatedProperties===void 0&&(n=void 0);else{let o=a;if("additionalProperties"in a&&a.additionalProperties===!1){let{additionalProperties:s,...c}=a;o=c}else n=void 0;i.push(o)}}),i.length?{allOf:i,...n}:void 0}function RP(t,e){let r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[t.value]}:{type:r==="bigint"?"integer":r,const:t.value}}var ib,$r={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:()=>(ib===void 0&&(ib=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),ib),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 xp(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":ye(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":ye(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":Or(r,"email",n.message,e);break;case"format:idn-email":Or(r,"idn-email",n.message,e);break;case"pattern:zod":Nt(r,$r.email,n.message,e);break}break;case"url":Or(r,"uri",n.message,e);break;case"uuid":Or(r,"uuid",n.message,e);break;case"regex":Nt(r,n.regex,n.message,e);break;case"cuid":Nt(r,$r.cuid,n.message,e);break;case"cuid2":Nt(r,$r.cuid2,n.message,e);break;case"startsWith":Nt(r,RegExp(`^${ab(n.value,e)}`),n.message,e);break;case"endsWith":Nt(r,RegExp(`${ab(n.value,e)}$`),n.message,e);break;case"datetime":Or(r,"date-time",n.message,e);break;case"date":Or(r,"date",n.message,e);break;case"time":Or(r,"time",n.message,e);break;case"duration":Or(r,"duration",n.message,e);break;case"length":ye(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),ye(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{Nt(r,RegExp(ab(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&Or(r,"ipv4",n.message,e),n.version!=="v4"&&Or(r,"ipv6",n.message,e);break}case"base64url":Nt(r,$r.base64url,n.message,e);break;case"jwt":Nt(r,$r.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&Nt(r,$r.ipv4Cidr,n.message,e),n.version!=="v4"&&Nt(r,$r.ipv6Cidr,n.message,e);break}case"emoji":Nt(r,$r.emoji(),n.message,e);break;case"ulid":{Nt(r,$r.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Or(r,"binary",n.message,e);break}case"contentEncoding:base64":{ye(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{Nt(r,$r.base64,n.message,e);break}}break}case"nanoid":Nt(r,$r.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function ab(t,e){return e.patternStrategy==="escape"?fB(t):t}var dB=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function fB(t){let e="";for(let r=0;r<t.length;r++)dB.has(t[r])||(e+="\\"),e+=t[r];return e}function Or(t,e,r,n){t.format||t.anyOf?.some(i=>i.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):ye(t,"format",e,r,n)}function Nt(t,e,r,n){t.pattern||t.allOf?.some(i=>i.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:$P(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):ye(t,"pattern",$P(e,n),r,n)}function $P(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;let r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=r.i?t.source.toLowerCase():t.source,i="",a=!1,o=!1,s=!1;for(let c=0;c<n.length;c++){if(a){i+=n[c],a=!1;continue}if(r.i){if(o){if(n[c].match(/[a-z]/)){s?(i+=n[c],i+=`${n[c-2]}-${n[c]}`.toUpperCase(),s=!1):n[c+1]==="-"&&n[c+2]?.match(/[a-z]/)?(i+=n[c],s=!0):i+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){i+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(r.m){if(n[c]==="^"){i+=`(^|(?<=[\r
|
|
127
127
|
]))`;continue}else if(n[c]==="$"){i+=`($|(?=[\r
|
|
128
128
|
]))`;continue}}if(r.s&&n[c]==="."){i+=o?`${n[c]}\r
|
|
129
129
|
`:`[${n[c]}\r
|
|
@@ -291,7 +291,7 @@ BOUNDARY RULES:
|
|
|
291
291
|
- **\u56FA\u5B9A\u770B\u677F\u542F\u52A8 URL \u89C4\u8303** \u2014 \u4F7F\u7528 Microi.Client \u524D\u7AEF WebBase\uFF08\u4E0D\u662F API Server\uFF09\u62FC\u63A5 \`/?OsClient=${t.osClient}#/access-login?access_key=<\u5BC6\u94A5>&redirect=<encodeURIComponent\u540E\u7684\u7AD9\u5185Hash\u8DEF\u7531>\`\u3002\u4F8B\u5982 redirect \u539F\u503C\u4E3A \`/mic/data-dashboard/preview/01KK988A0YPHKAM8SF216917HX\` \u65F6\u7F16\u7801\u4E3A \`%2Fmic%2Fdata-dashboard%2Fpreview%2F01KK988A0YPHKAM8SF216917HX\`\u3002\u5B8C\u6574\u81EA\u52A8\u767B\u5F55\u94FE\u63A5\u5E94\u4FDD\u5B58\u4E3A\u7535\u89C6/\u770B\u677F\u7684\u542F\u52A8\u9875\uFF1B\u5151\u6362\u6210\u529F\u540E\u5730\u5740\u680F\u53D8\u4E3A\u4E0D\u542B \`access_key\` \u7684\u76EE\u6807\u9875\u662F\u5B89\u5168\u8BBE\u8BA1\uFF0C\u7981\u6B62\u7ED9\u76EE\u6807\u9875\u518D\u6B21\u8FFD\u52A0\u5BC6\u94A5\uFF0C\u4E5F\u7981\u6B62\u65B0\u589E \`permanent=1\` \u4E00\u7C7B\u7531\u5BA2\u6237\u7AEF\u51B3\u5B9A\u6709\u6548\u671F\u7684\u53C2\u6570
|
|
292
292
|
|
|
293
293
|
## OCR \u80FD\u529B
|
|
294
|
-
- \u56FE\u7247/PDF \u6587\u5B57\u8BC6\u522B\u7EDF\u4E00\u8C03\u7528\u540E\u7AEF \`V8.OCR.Recognize({...})\` \u6216\u53D7\u8BA4\u8BC1\u7684 \`POST /
|
|
294
|
+
- \u56FE\u7247/PDF \u6587\u5B57\u8BC6\u522B\u7EDF\u4E00\u8C03\u7528\u540E\u7AEF \`V8.OCR.Recognize({...})\` \u6216\u53D7\u8BA4\u8BC1\u7684 \`POST /apiengine/platform-ocr-recognize\`\uFF1B\u4E0D\u8981\u5728\u63A5\u53E3\u5F15\u64CE\u91CC\u81EA\u884C\u8BFB\u53D6\u5BC6\u94A5\u5E76\u8C03\u7528 OCR endpoint\u3002
|
|
295
295
|
- \u670D\u52A1\u5730\u5740\u3001API Key\u3001\u56FA\u5B9A Header\u3001\u8D85\u65F6\u548C\u914D\u989D\u53EA\u4ECE\u5F53\u524D\u79DF\u6237 \`sys_osclients\` \u7684\u201COCR\u8BC6\u522B\u201DTab \u8BFB\u53D6\uFF0C\u8C03\u7528\u53C2\u6570\u4E0D\u5F97\u8986\u76D6 endpoint\u3001\u5BC6\u94A5\u3001Header \u6216 OsClient\u3002
|
|
296
296
|
- \u76F8\u5173\u5B9E\u73B0\u4E0E\u4EA4\u4ED8\u89C4\u8303\u8BFB\u53D6 \`microi.skills/ocr-engine/SKILL.md\`\uFF1B\u6279\u91CF\u6216\u957F\u8017\u65F6 OCR \u5FC5\u987B\u4F7F\u7528\u6570\u636E\u5E93/MQ/outbox \u7684\u53EF\u6062\u590D\u5E42\u7B49\u4EFB\u52A1\uFF0C\u4E0D\u80FD\u4F7F\u7528\u5355\u8282\u70B9\u5185\u5B58\u961F\u5217\u3002
|
|
297
297
|
|