@microi.net/cli 4.6.2 → 4.6.4
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/dist/mcp-server.js +9 -7
- package/dist/microi-cli.js +44 -44
- package/dist/microi-skills.meta.json +120 -120
- package/dist/microi.skills/.microi-skills-version.json +2 -2
- package/dist/microi.skills/app-store/SKILL.md +5 -0
- package/dist/microi.skills/message-notification/agents/openai.yaml +0 -1
- package/dist/microi.skills/microi-client-frontend/SKILL.md +9 -2
- package/dist/microi.skills/microi-db-schema/SKILL.md +1 -0
- package/dist/microi.skills/microi-form-engine/SKILL.md +6 -0
- package/dist/microi.skills/microi-system-delivery/SKILL.md +4 -2
- package/dist/microi.skills/microi-ui/SKILL.md +9 -0
- package/dist/microi.skills/ui-design/SKILL.md +21 -0
- package/dist/microi.skills/ui-design/assets/templates/MCI-DESIGN.md +163 -62
- package/dist/microi.skills/ui-design/references/design-pattern-library.md +13 -0
- package/dist/microi.skills/ui-design/references/mci-design-contract.md +150 -71
- package/dist/microi.skills/workspace-conventions/SKILL.md +7 -0
- package/package.json +1 -1
package/dist/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 xw.TLSSocket?"https":"http",c=o&&e.url?new Ch.URL(e.url,`${s}://${o}`):void 0,l={headers:e.headers,url:c},u;try{let p=_w.default.parse(e.headers["content-type"]??"");if(p.type!=="application/json")throw new Error(`Unsupported content-type: ${p.type}`);u=n??await(0,ww.default)(e,{limit:eN,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=tl.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 nd=tt(XT(),1);var vi=tt(require("node:crypto"),1),Kt=tt(require("node:fs"),1),sC=tt(require("node:os"),1),zs=tt(require("node:path"),1),cC=require("node:stream");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",TRANSITION_APPLICATION_STREAM_GATE:"/api/V8Engine/TransitionApplicationStreamGate",REDIS_STATISTICS:"/api/Cache/redis/statistics",REDIS_KEYS:"/api/Cache/redis/keys",REDIS_KEY:"/api/Cache/redis/key",REDIS_DELETE_KEYS:"/api/Cache/redis/keys/delete",REDIS_REPLACE_VALUE:"/api/Cache/redis/key/replace",REDIS_RENAME_KEY:"/api/Cache/redis/key/rename",REDIS_SET_TTL:"/api/Cache/redis/key/ttl",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:"/api/BackgroundTask/RunApiEngine",UPLOAD_FILE_BASE64:"/api/V8Engine/UploadFileBase64",UPLOAD_APPLICATION_ASSET_STREAM:"/api/V8Engine/UploadApplicationAssetStream",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",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:"/api/DataSourceEngine/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_BLUEPRINTS:"/api/V8Engine/ListBlueprints",GET_BLUEPRINT:"/api/V8Engine/GetBlueprint",SAVE_BLUEPRINT:"/api/V8Engine/SaveBlueprint",DELETE_BLUEPRINT:"/api/V8Engine/DeleteBlueprint",VALIDATE_BLUEPRINT:"/api/V8Engine/ValidateBlueprint"};var YT=tt(require("node:crypto"),1),QT=128,cL=/^[\x20-\x7E]+$/;function eC(t,e="Unknown"){let r=`MCP:${e||"Unknown"}`,n=String(t||r).trim()||"MCP:Unknown";if(n.length<=QT&&cL.test(n))return n;let i=YT.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=QT-i.length-1;return`${a.slice(0,o)}-${i}`}var lL=/^Bearer\s+/i;function Yr(t){return String(t||"").replace(lL,"").trim()}function uL(t){try{let r=Yr(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 tC(t,e=Math.floor(Date.now()/1e3),r=24*60*60){let n=uL(t);return n===void 0||n-e<=r}var pL=[{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 rC(t){let e=[];return String(t||"").replace(/\r\n/g,`
|
|
98
|
+
`)}get sessionId(){return this._sessionId}};var nd=tt(XT(),1);var vi=tt(require("node:crypto"),1),Kt=tt(require("node:fs"),1),sC=tt(require("node:os"),1),zs=tt(require("node:path"),1),cC=require("node:stream");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",TRANSITION_APPLICATION_STREAM_GATE:"/api/V8Engine/TransitionApplicationStreamGate",REDIS_STATISTICS:"/api/Cache/redis/statistics",REDIS_KEYS:"/api/Cache/redis/keys",REDIS_KEY:"/api/Cache/redis/key",REDIS_DELETE_KEYS:"/api/Cache/redis/keys/delete",REDIS_REPLACE_VALUE:"/api/Cache/redis/key/replace",REDIS_RENAME_KEY:"/api/Cache/redis/key/rename",REDIS_SET_TTL:"/api/Cache/redis/key/ttl",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:"/api/BackgroundTask/RunApiEngine",UPLOAD_FILE_BASE64:"/api/V8Engine/UploadFileBase64",UPLOAD_APPLICATION_ASSET_STREAM:"/api/V8Engine/UploadApplicationAssetStream",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:"/api/DataSourceEngine/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_BLUEPRINTS:"/api/V8Engine/ListBlueprints",GET_BLUEPRINT:"/api/V8Engine/GetBlueprint",SAVE_BLUEPRINT:"/api/V8Engine/SaveBlueprint",DELETE_BLUEPRINT:"/api/V8Engine/DeleteBlueprint",VALIDATE_BLUEPRINT:"/api/V8Engine/ValidateBlueprint"};var YT=tt(require("node:crypto"),1),QT=128,cL=/^[\x20-\x7E]+$/;function eC(t,e="Unknown"){let r=`MCP:${e||"Unknown"}`,n=String(t||r).trim()||"MCP:Unknown";if(n.length<=QT&&cL.test(n))return n;let i=YT.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=QT-i.length-1;return`${a.slice(0,o)}-${i}`}var lL=/^Bearer\s+/i;function Yr(t){return String(t||"").replace(lL,"").trim()}function uL(t){try{let r=Yr(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 tC(t,e=Math.floor(Date.now()/1e3),r=24*60*60){let n=uL(t);return n===void 0||n-e<=r}var pL=[{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 rC(t){let e=[];return String(t||"").replace(/\r\n/g,`
|
|
99
99
|
`).split(`
|
|
100
100
|
`).forEach((r,n)=>{for(let i of pL)if(i.regex.test(r)){e.push({line:n+1,marker:i.label});break}}),e}function Ms(t,e){let r=rC(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 Ns(t,e,r="payload"){if(typeof t=="string"){let n=rC(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"&&Ns(a,e,`${r}(json)`)}return}if(Array.isArray(t)){t.forEach((n,i)=>Ns(n,e,`${r}[${i}]`));return}if(t&&typeof t=="object")for(let[n,i]of Object.entries(t))Ns(i,e,`${r}.${n}`)}var dL=/^\s*\*?\s*Version\s*:\s*(v\d+\.\d+\.\d+)\s*$/im,nC=/^v(\d+)\.(\d+)\.(\d+)$/;function Lu(t){let e=(t||"").trim();if(!e)return null;let r=e.match(nC);if(r)return`v${Number(r[1])}.${Number(r[2])}.${Number(r[3])}`;let n=e.match(dL);return n?Lu(n[1]):null}function iC(t){if(!t)return null;let e=t.match(nC);return e?{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3])}:null}function fL(t,e){return t.major!==e.major?t.major-e.major:t.minor!==e.minor?t.minor-e.minor:t.patch-e.patch}function mL(t){let e=null;for(let r of t){let n=iC(r);n&&(!e||fL(n,e)>0)&&(e=n)}return e?`v${e.major}.${e.minor}.${e.patch}`:null}function hL(t){let e=iC(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 gL(t){let e=(t||"").trim();return e?e.replace(/\r\n/g,`
|
|
101
101
|
`).split(`
|
|
@@ -110,7 +110,7 @@ MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC7q21EG3HiSFNO9XFUJoMeyz2R
|
|
|
110
110
|
XaFX8UgCFE4d4pvK6IvQsWunm+WfYqgrSzBMS1LH1fstmZB0wnVUX1uGROaZTKGZ
|
|
111
111
|
1rS/MVn4i6CsPgP9Q7nFV6dZvbxro1byH/E3CV/Q1CgCDeue9FzQUlWQ+UZld8Jg
|
|
112
112
|
1DsI9VJ7gTHGL3R7sQIDAQAB
|
|
113
|
-
-----END PUBLIC KEY-----`;function Bu(t,e="",r="",n=""){let i=String(t||"").replace(/\/+$/,""),a=String(e||"").trim(),o=String(r||"").trim(),s=String(n||"").trim(),c=[];
|
|
113
|
+
-----END PUBLIC KEY-----`;function Bu(t,e="",r="",n=""){let i=String(t||"").replace(/\/+$/,""),a=String(e||"").trim(),o=String(r||"").trim(),s=String(n||"").trim(),c=[];if(a){c.push(`${i}|${a}|${o}|${s}`);let l=[i,a,o,s].filter(Boolean).join("|");c.push(l),o&&c.push(`${i}|${a}|${o}`),c.push(`${i}|${a}`)}return c.push(i),Array.from(new Set(c.filter(Boolean)))}function _L(t,e,r){return`${String(t||"").replace(/\/+$/,"")}/micro-app/${encodeURIComponent(String(e||"").trim())}/${encodeURIComponent(String(r||"").trim())}/index.html`}function SL(t){let e=String(t?.DataAppend?.ReasonCode||"").trim();if(/^(InvalidTenant|InvalidOsClient|TenantNotFound|TenantDisabled)$/i.test(e))return!0;let r=[t?.Msg,t?.DataAppend?.UserMessage,t?.DataAppend?.Hint].filter(Boolean).join(" ");return/无效的租户标识|租户不存在|租户.*未启用|invalid\s+(tenant|osclient)|tenant\s+not\s+found|unknown\s+tenant/i.test(r)}function aC(t){if(!t||SL(t))return!1;if(xL.has(Number(t.Code)))return!0;let e=String(t.DataAppend?.ReasonCode||"").trim();if(/^(MissingToken|MalformedToken|MissingClaims|TenantMismatch|AuthVersionChanged|JwtExpired|SessionExpired|SessionMissing|TokenReplaced|SignatureMismatch)$/i.test(e))return!0;let r=[t.Msg,t.DataAppend?.UserMessage,t.DataAppend?.AppendMsg].filter(Boolean).join(" ");return/Token签名|Token.*(无效|失效|过期)|登录.*(无效|失效|过期)|invalid\s*token|token\s*invalid|signature\s*mismatch/i.test(r)}function qu(t){return t==="initial"?"replacement-token":t==="replacement-token"?"broker-token":"credential-token"}var js=class extends Error{kind;requestPath;uncertainOutcome;constructor(e,r){super(e,{cause:r.cause}),this.name="MicroiTransportError",this.kind=r.kind,this.requestPath=r.requestPath,this.uncertainOutcome=r.uncertainOutcome}},EL=12e4,kL=6e4,TL=5e3,CL=[0,300,800,1500,3e3],$L=30*6e4,AL=2*60*6e4,PL=new Set(["MoreBtns","FormBtns","BatchSelectMoreBtns","PageTabs","ExportMoreBtns","PageBtns","SearchFieldIds","TableDiyFieldIds","SelectFields","SortFieldIds","NotShowFields","StatisticsFields","MobileListFields","CardTitleTagFields","CardBottomTagFields"]);function Vu(t,e){let r=Number(t);return!Number.isFinite(r)||r<1e3?e:Math.min(10*6e4,Math.round(r))}function IL(t){let e=Number(t);return!Number.isFinite(e)||e<1e3?$L:Math.min(AL,Math.round(e))}function RL(t,e,r,n){let i=[];for(let[l,u]of Object.entries(t))i.push(Buffer.from(`--${n}\r
|
|
114
114
|
Content-Disposition: form-data; name="${l}"\r
|
|
115
115
|
\r
|
|
116
116
|
${u}\r
|
|
@@ -121,12 +121,12 @@ Content-Type: application/octet-stream\r
|
|
|
121
121
|
`,"utf8"));let a=Buffer.concat(i),o=Buffer.from(`\r
|
|
122
122
|
--${n}--\r
|
|
123
123
|
`,"utf8"),s=Kt.default.statSync(e).size;async function*c(){yield a;for await(let l of Kt.default.createReadStream(e))yield Buffer.isBuffer(l)?l:Buffer.from(l);yield o}return{body:cC.Readable.from(c()),contentLength:a.length+s+o.length}}function Tn(t){return String(t??"").replace(/\r\n/g,`
|
|
124
|
-
`).trim()}function _y(t){if(Array.isArray(t))return t.map(_y);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,_y(n)]))}function oC(t){try{let e=typeof t=="string"?JSON.parse(t):t;return JSON.stringify(_y(e))}catch{return}}function OL(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(PL.has(i)||i==="ViewSchema"){let s=oC(a),c=oC(o);(!s||!c||s!==c)&&n.push(i);continue}String(a??"")!==String(o??"")&&n.push(i)}return{matched:n.length===0,mismatches:n}}var Fs=class{config;token="";refreshTimer;rsaPublicKey;did;requestTimeoutMs;writeRequestTimeoutMs;readbackRequestTimeoutMs;inflightRefresh;inflightAuthRecovery;inflightCredentialRecovery;constructor(e){this.config=e,this.rsaPublicKey=e.rsaPublicKey||wL,this.did=eC(process.env.MICROI_MCP_DID,sC.default.hostname()),this.requestTimeoutMs=Vu(e.requestTimeoutMs??process.env.MICROI_MCP_HTTP_TIMEOUT_MS,EL),this.writeRequestTimeoutMs=Vu(e.writeRequestTimeoutMs??process.env.MICROI_MCP_WRITE_TIMEOUT_MS,kL),this.readbackRequestTimeoutMs=Vu(e.readbackRequestTimeoutMs??process.env.MICROI_MCP_READBACK_TIMEOUT_MS,TL),e.token&&(this.token=Yr(e.token))}rsaEncrypt(e){let r=(this.rsaPublicKey||"").trim();return r?vi.default.publicEncrypt({key:r,padding:vi.default.constants.RSA_PKCS1_PADDING},Buffer.from(e,"utf-8")).toString("base64"):e}updateToken(e){this.token=Yr(e)}async login(e){if(this.token){this.startAutoRefresh(),console.error("[microi-mcp] Using provided token (auto-refresh enabled)");return}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=Yr(a),this.startAutoRefresh(),console.error("[microi-mcp] Login successful")}startAutoRefresh(){this.refreshTimer&&clearInterval(this.refreshTimer),this.refreshTimer=setInterval(()=>{tC(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=Yr(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(Kt.default.readFileSync(e,"utf-8")),i=Bu(this.config.apiBaseUrl,this.config.osClient,this.config.osClientType,this.config.osClientNetwork).map(o=>r[o]).find(Boolean),a=Yr(i);if(a&&a!==this.token)return this.token=a,!0}catch{}return!1}writeTokenToFile(){let e=this.config.tokenFilePath;if(!(!e||!this.token))try{let r={};try{r=JSON.parse(Kt.default.readFileSync(e,"utf-8"))}catch{}let[n]=Bu(this.config.apiBaseUrl,this.config.osClient,this.config.osClientType,this.config.osClientNetwork);if(!n)return;r[n]=this.token;let i=zs.default.dirname(e);Kt.default.existsSync(i)||Kt.default.mkdirSync(i,{recursive:!0}),Kt.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{Kt.default.existsSync(r)||Kt.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=`${vi.default.createHash("sha256").update(c).digest("hex").slice(0,24)}-${process.pid}-${Date.now()}-${vi.default.randomBytes(4).toString("hex")}.json`,p=zs.default.join(r,u),d=`${p}.${process.pid}.tmp`,h={version:1,apiBaseUrl:i,osClient:a,osClientType:o,osClientNetwork:s,requestedAt:Date.now(),failedTokenHash:vi.default.createHash("sha256").update(e||"").digest("hex")};Kt.default.writeFileSync(d,JSON.stringify(h),{encoding:"utf-8",mode:384}),Kt.default.renameSync(d,p);for(let m=0;m<40;m++)if(await new Promise(y=>setTimeout(y,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.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)}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=Vu(o.timeoutMs,this.requestTimeoutMs),p=o.operationName||`${e} ${r}`,d=new AbortController,h=setTimeout(()=>d.abort(),u),m,y;try{m=await fetch(s,{method:e,headers:l,signal:d.signal,...e==="POST"?{body:JSON.stringify(n??{})}:{}}),y=await m.text()}catch(b){let v=d.signal.aborted;throw new js(v?`${p} \u8BF7\u6C42\u8D85\u65F6\uFF08${u}ms\uFF09`:`${p} \u7F51\u7EDC\u8BF7\u6C42\u5931\u8D25\uFF1A${b instanceof Error?b.message:String(b)}`,{kind:v?"timeout":"network",requestPath:r,uncertainOutcome:e==="POST",cause:b})}finally{clearTimeout(h)}let g=m.headers.get("authorization");if(g&&(this.token=Yr(g),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,qu(a),o);throw new Error(`HTTP 401 Unauthorized \u2014 token recovery failed: ${y.slice(0,200)}`)}if(!m.ok)throw new Error(`HTTP ${m.status} ${m.statusText} \u2014 ${y.slice(0,200)}`);if(!y)throw new Error(`HTTP ${m.status} \u2014 empty response body`);let x;try{x=JSON.parse(y)}catch{throw new Error(`HTTP ${m.status} \u2014 invalid JSON: ${y.slice(0,200)}`)}if(aC(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,qu(a),o)}return x}async requestMultipartFile(e,r,n,i,a="initial",o){let s=this.token,c=`----microi-mcp-${vi.default.randomBytes(24).toString("hex")}`,l=RL(r,n,i,c),u=new AbortController,p=IL(o),d=setTimeout(()=>u.abort(),p),h,m;try{h=await fetch(`${this.config.apiBaseUrl}${e}`,{method:"POST",headers:{Authorization:`Bearer ${s}`,did:this.did,...this.config.osClient?{OsClient:this.config.osClient}:{},"Content-Type":`multipart/form-data; boundary=${c}`,"Content-Length":String(l.contentLength)},body:l.body,duplex:"half",signal:u.signal}),m=await h.text()}catch(x){let b=u.signal.aborted;throw new js(b?`\u5E94\u7528\u8D44\u4EA7\u6D41\u5F0F\u4E0A\u4F20\u8D85\u65F6\uFF08${p}ms\uFF09`:`\u5E94\u7528\u8D44\u4EA7\u6D41\u5F0F\u4E0A\u4F20\u7F51\u7EDC\u5931\u8D25\uFF1A${x instanceof Error?x.message:String(x)}`,{kind:b?"timeout":"network",requestPath:e,uncertainOutcome:!0,cause:x})}finally{clearTimeout(d),l.body.destroy()}let y=h.headers.get("authorization");if(y&&(this.token=Yr(y),this.writeTokenToFile()),h.status===401&&a!=="credential-token"){let x=a!=="initial";if(x&&console.error("[microi-mcp] Replacement token was rejected; escalating to credential recovery"),await this.tryRecoverFromAuthFailure(s,x))return this.requestMultipartFile(e,r,n,i,qu(a),o);throw new Error(`HTTP 401 Unauthorized \u2014 token recovery failed: ${m.slice(0,200)}`)}if(!h.ok)throw new Error(`HTTP ${h.status} ${h.statusText} \u2014 ${m.slice(0,200)}`);if(!m)throw new Error(`HTTP ${h.status} \u2014 empty response body`);let g;try{g=JSON.parse(m)}catch{throw new Error(`HTTP ${h.status} \u2014 invalid JSON: ${m.slice(0,200)}`)}if(aC(g)&&a!=="credential-token"){let x=a!=="initial";if(x&&console.error("[microi-mcp] Replacement token was rejected; escalating to credential recovery"),await this.tryRecoverFromAuthFailure(s,x))return this.requestMultipartFile(e,r,n,i,qu(a),o)}return g}isUncertainWriteError(e){return e instanceof js&&e.uncertainOutcome}readbackOptions(e){return{timeoutMs:this.readbackRequestTimeoutMs,operationName:e}}async pollReadback(e,r){let n,i="";for(let a of CL){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 saveEngineCode(e,r,n){Ms(r,`\u4FDD\u5B58\u63A5\u53E3\u5F15\u64CE ${e}`);let i;try{let u=await this.getEngineCode(e);i=u.Code===1?u.Data:void 0}catch{i=void 0}let a=Tn(i?.ApiV8Code||i?.Code),o=Tn(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=Ds({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={OsClient:this.config.osClient,ApiEngineKey:e,ApiV8CodeBase64:Buffer.from(s.code,"utf8").toString("base64"),Version:s.version,ChangeHistory:s.changeHistory,...n?.v8Unlimited===void 0?{}:{V8Unlimited:n.v8Unlimited?1:0}},l=u=>Tn(u?.ApiV8Code||u?.Code)===Tn(s.code)&&(n?.v8Unlimited===void 0||Number(u?.V8Unlimited||0)===(n.v8Unlimited?1:0));try{let u=await this.post(O.UPDATE_ENGINE_CODE,c,{timeoutMs:this.writeRequestTimeoutMs,operationName:`\u4FDD\u5B58\u63A5\u53E3\u5F15\u64CE ${e}`});if(u.Code!==1||n?.v8Unlimited===void 0)return u;let p=await this.pollReadback(()=>this.getEngineCode(e,this.readbackOptions(`\u56DE\u8BFB\u63A5\u53E3\u5F15\u64CE ${e} V8Unlimited`)),l);return p.matched?{...u,Data:{...u.Data&&typeof u.Data=="object"?u.Data:{},ApiEngineKey:e,V8Unlimited:n.v8Unlimited?1:0,Verified:!0,Verification:"readback"}}:{Code:0,Data:{ApiEngineKey:e,UpdateResponse:u.Data},Msg:`\u4FDD\u5B58\u63A5\u53E3\u5F15\u64CE ${e} \u8FD4\u56DE\u6210\u529F\uFF0C\u4F46 V8Unlimited \u5199\u540E\u56DE\u8BFB\u4E0D\u4E00\u81F4\uFF1A${p.lastError||"\u4EE3\u7801\u6216\u914D\u7F6E\u4E0D\u4E00\u81F4"}`}}catch(u){if(!this.isUncertainWriteError(u))throw u;let p=await this.pollReadback(()=>this.getEngineCode(e,this.readbackOptions(`\u56DE\u8BFB\u63A5\u53E3\u5F15\u64CE ${e}`)),l);if(p.matched)return this.recoveredWriteResult(`\u4FDD\u5B58\u63A5\u53E3\u5F15\u64CE ${e}`,u,{ApiEngineKey:e,Version:s.version});throw this.uncertainWriteFailure(`\u4FDD\u5B58\u63A5\u53E3\u5F15\u64CE ${e}`,u,p.lastError)}}async updateEngineRuntimeConfig(e,r){let n={OsClient:this.config.osClient,ApiEngineKey:e,V8Unlimited:r?1:0},i=()=>this.pollReadback(()=>this.getEngineCode(e,this.readbackOptions(`\u56DE\u8BFB\u63A5\u53E3\u5F15\u64CE ${e} V8Unlimited`)),o=>Number(o?.V8Unlimited||0)===(r?1:0)),a=`\u66F4\u65B0\u63A5\u53E3\u5F15\u64CE ${e} V8Unlimited`;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,V8Unlimited: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,V8Unlimited:r?1:0,Verified:!0});throw this.uncertainWriteFailure(a,o,s.lastError)}}async createEngine(e){let r={OsClient:this.config.osClient,...e},n=typeof r.Code=="string"?r.Code:typeof r.ApiV8Code=="string"?r.ApiV8Code:"";Ms(n,`\u521B\u5EFA\u63A5\u53E3\u5F15\u64CE ${e.ApiEngineKey}`);let i=Ds({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.ChangeHistory=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&&Tn(s?.ApiV8Code||s?.Code)===Tn(i.code)&&(e.V8Unlimited===void 0||Number(s?.V8Unlimited||0)===(e.V8Unlimited===1?1:0)));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=zs.default.resolve(e.FilePath),n=Kt.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=zs.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");let a={};if(e.ProtocolVersion===3){let o=s=>s===null?"null":String(s??"");Object.assign(a,{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:o(e.ExpectedAppVersion),ExpectedPublishFence:String(e.ExpectedPublishFence??""),ExpectedPublishRowVersion:String(e.ExpectedPublishRowVersion??""),ExpectedVersionRowVersion:o(e.ExpectedVersionRowVersion),ExpectedActivePublishVersionId:o(e.ExpectedActivePublishVersionId),ExpectedCommittedPublishVersionId:o(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,...a},r,i,"initial",e.TimeoutMs)}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=_L(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),d=/<body(?:\s|>)/iu.test(u),h=a.ok&&o.toLowerCase().includes("text/html")&&l>0&&p&&d;return{ok:h,url:r,status:a.status,contentType:o,bodyBytes:l,hasHead:p,hasBody:d,...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){Ms(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=Ds({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=>Tn(u?.V8Code||u?.Code)===Tn(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){Ms(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=Ds({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){return this.post(O.CREATE_TABLE,{OsClient:this.config.osClient,Name:e,Description:r||"",...n})}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();Ns(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}:{...OL(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,ApiEngineKey: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 getRedisStatistics(e=0,r){return this.post(O.REDIS_STATISTICS,{Mode:r?"saved":"tenant",ConnectionId:r||"",Database:e})}async getRedisKeys(e="*",r=0,n=100,i,a){return this.post(O.REDIS_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,{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,{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,{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,{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,{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 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 saveBlueprint(e){return this.post(O.SAVE_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 f={};fd(f,{BRAND:()=>aq,DIRTY:()=>xi,EMPTY_PATH:()=>zL,INVALID:()=>J,NEVER:()=>Vq,OK:()=>mt,ParseStatus:()=>ut,Schema:()=>Y,ZodAny:()=>An,ZodArray:()=>nn,ZodBigInt:()=>_i,ZodBoolean:()=>Si,ZodBranded:()=>qs,ZodCatch:()=>Ni,ZodDate:()=>Ei,ZodDefault:()=>Oi,ZodDiscriminatedUnion:()=>Ju,ZodEffects:()=>nr,ZodEnum:()=>Ii,ZodError:()=>Nt,ZodFirstPartyTypeKind:()=>R,ZodFunction:()=>Ku,ZodIntersection:()=>$i,ZodIssueCode:()=>I,ZodLazy:()=>Ai,ZodLiteral:()=>Pi,ZodMap:()=>Ua,ZodNaN:()=>Ja,ZodNativeEnum:()=>Ri,ZodNever:()=>yr,ZodNull:()=>Ti,ZodNullable:()=>zr,ZodNumber:()=>wi,ZodObject:()=>Dt,ZodOptional:()=>Mt,ZodParsedType:()=>z,ZodPipeline:()=>Vs,ZodPromise:()=>Pn,ZodReadonly:()=>Mi,ZodRecord:()=>Hu,ZodSchema:()=>Y,ZodSet:()=>Za,ZodString:()=>$n,ZodSymbol:()=>Va,ZodTransformer:()=>nr,ZodTuple:()=>Dr,ZodType:()=>Y,ZodUndefined:()=>ki,ZodUnion:()=>Ci,ZodUnknown:()=>rn,ZodVoid:()=>Ba,addIssueToContext:()=>D,any:()=>mq,array:()=>bq,bigint:()=>lq,boolean:()=>vC,coerce:()=>qq,custom:()=>gC,date:()=>uq,datetimeRegex:()=>mC,defaultErrorMap:()=>en,discriminatedUnion:()=>wq,effect:()=>Oq,enum:()=>Pq,function:()=>Cq,getErrorMap:()=>Fa,getParsedType:()=>Mr,instanceof:()=>sq,intersection:()=>_q,isAborted:()=>Uu,isAsync:()=>La,isDirty:()=>Zu,isValid:()=>Cn,late:()=>oq,lazy:()=>$q,literal:()=>Aq,makeIssue:()=>Ls,map:()=>kq,nan:()=>cq,nativeEnum:()=>Iq,never:()=>gq,null:()=>fq,nullable:()=>Mq,number:()=>bC,object:()=>Ty,objectUtil:()=>Sy,oboolean:()=>Lq,onumber:()=>Fq,optional:()=>Nq,ostring:()=>jq,pipeline:()=>zq,preprocess:()=>Dq,promise:()=>Rq,quotelessJson:()=>NL,record:()=>Eq,set:()=>Tq,setErrorMap:()=>DL,strictObject:()=>vq,string:()=>yC,symbol:()=>pq,transformer:()=>Oq,tuple:()=>Sq,undefined:()=>dq,union:()=>xq,unknown:()=>hq,util:()=>ae,void:()=>yq});var ae;(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})(ae||(ae={}));var Sy;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Sy||(Sy={}));var z=ae.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Mr=t=>{switch(typeof t){case"undefined":return z.undefined;case"string":return z.string;case"number":return Number.isNaN(t)?z.nan:z.number;case"boolean":return z.boolean;case"function":return z.function;case"bigint":return z.bigint;case"symbol":return z.symbol;case"object":return Array.isArray(t)?z.array:t===null?z.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?z.promise:typeof Map<"u"&&t instanceof Map?z.map:typeof Set<"u"&&t instanceof Set?z.set:typeof Date<"u"&&t instanceof Date?z.date:z.object;default:return z.unknown}};var I=ae.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"]),NL=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),Nt=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,ae.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()}};Nt.create=t=>new Nt(t);var ML=(t,e)=>{let r;switch(t.code){case I.invalid_type:t.received===z.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case I.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,ae.jsonStringifyReplacer)}`;break;case I.unrecognized_keys:r=`Unrecognized key(s) in object: ${ae.joinValues(t.keys,", ")}`;break;case I.invalid_union:r="Invalid input";break;case I.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${ae.joinValues(t.options)}`;break;case I.invalid_enum_value:r=`Invalid enum value. Expected ${ae.joinValues(t.options)}, received '${t.received}'`;break;case I.invalid_arguments:r="Invalid function arguments";break;case I.invalid_return_type:r="Invalid function return type";break;case I.invalid_date:r="Invalid date";break;case I.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}"`:ae.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case I.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 I.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 I.custom:r="Invalid input";break;case I.invalid_intersection_types:r="Intersection results could not be merged";break;case I.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case I.not_finite:r="Number must be finite";break;default:r=e.defaultError,ae.assertNever(t)}return{message:r}},en=ML;var lC=en;function DL(t){lC=t}function Fa(){return lC}var Ls=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}},zL=[];function D(t,e){let r=Fa(),n=Ls({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===en?void 0:en].filter(i=>!!i)});t.common.issues.push(n)}var ut=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 J;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 J;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}}},J=Object.freeze({status:"aborted"}),xi=t=>({status:"dirty",value:t}),mt=t=>({status:"valid",value:t}),Uu=t=>t.status==="aborted",Zu=t=>t.status==="dirty",Cn=t=>t.status==="valid",La=t=>typeof Promise<"u"&&t instanceof Promise;var L;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(L||(L={}));var rr=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}},uC=(t,e)=>{if(Cn(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 Nt(t.common.issues);return this._error=r,this._error}}};function G(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 Y=class{get description(){return this._def.description}_getType(e){return Mr(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:Mr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ut,ctx:{common:e.parent.common,data:e.data,parsedType:Mr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(La(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:Mr(e)},i=this._parseSync({data:e,path:n.path,parent:n});return uC(n,i)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Mr(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return Cn(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=>Cn(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:Mr(e)},i=this._parse({data:e,path:n.path,parent:n}),a=await(La(i)?i:Promise.resolve(i));return uC(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:I.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 nr({schema:this,typeName:R.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 Mt.create(this,this._def)}nullable(){return zr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return nn.create(this)}promise(){return Pn.create(this,this._def)}or(e){return Ci.create([this,e],this._def)}and(e){return $i.create(this,e,this._def)}transform(e){return new nr({...G(this._def),schema:this,typeName:R.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new Oi({...G(this._def),innerType:this,defaultValue:r,typeName:R.ZodDefault})}brand(){return new qs({typeName:R.ZodBranded,type:this,...G(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Ni({...G(this._def),innerType:this,catchValue:r,typeName:R.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return Vs.create(this,e)}readonly(){return Mi.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},jL=/^c[^\s-]{8,}$/i,FL=/^[0-9a-z]+$/,LL=/^[0-9A-HJKMNP-TV-Z]{26}$/i,qL=/^[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,VL=/^[a-z0-9_-]{21}$/i,BL=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,UL=/^[-+]?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)?)??$/,ZL=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,JL="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Ey,HL=/^(?:(?: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])$/,KL=/^(?:(?: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])$/,WL=/^(([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]))$/,GL=/^(([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])$/,XL=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,QL=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,dC="((\\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])))",YL=new RegExp(`^${dC}$`);function fC(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 eq(t){return new RegExp(`^${fC(t)}$`)}function mC(t){let e=`${dC}T${fC(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 tq(t,e){return!!((e==="v4"||!e)&&HL.test(t)||(e==="v6"||!e)&&WL.test(t))}function rq(t,e){if(!BL.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 nq(t,e){return!!((e==="v4"||!e)&&KL.test(t)||(e==="v6"||!e)&&GL.test(t))}var $n=class t extends Y{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==z.string){let a=this._getOrReturnCtx(e);return D(a,{code:I.invalid_type,expected:z.string,received:a.parsedType}),J}let n=new ut,i;for(let a of this._def.checks)if(a.kind==="min")e.data.length<a.value&&(i=this._getOrReturnCtx(e,i),D(i,{code:I.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),D(i,{code:I.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?D(i,{code:I.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}):s&&D(i,{code:I.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}),n.dirty())}else if(a.kind==="email")ZL.test(e.data)||(i=this._getOrReturnCtx(e,i),D(i,{validation:"email",code:I.invalid_string,message:a.message}),n.dirty());else if(a.kind==="emoji")Ey||(Ey=new RegExp(JL,"u")),Ey.test(e.data)||(i=this._getOrReturnCtx(e,i),D(i,{validation:"emoji",code:I.invalid_string,message:a.message}),n.dirty());else if(a.kind==="uuid")qL.test(e.data)||(i=this._getOrReturnCtx(e,i),D(i,{validation:"uuid",code:I.invalid_string,message:a.message}),n.dirty());else if(a.kind==="nanoid")VL.test(e.data)||(i=this._getOrReturnCtx(e,i),D(i,{validation:"nanoid",code:I.invalid_string,message:a.message}),n.dirty());else if(a.kind==="cuid")jL.test(e.data)||(i=this._getOrReturnCtx(e,i),D(i,{validation:"cuid",code:I.invalid_string,message:a.message}),n.dirty());else if(a.kind==="cuid2")FL.test(e.data)||(i=this._getOrReturnCtx(e,i),D(i,{validation:"cuid2",code:I.invalid_string,message:a.message}),n.dirty());else if(a.kind==="ulid")LL.test(e.data)||(i=this._getOrReturnCtx(e,i),D(i,{validation:"ulid",code:I.invalid_string,message:a.message}),n.dirty());else if(a.kind==="url")try{new URL(e.data)}catch{i=this._getOrReturnCtx(e,i),D(i,{validation:"url",code:I.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),D(i,{validation:"regex",code:I.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),D(i,{code:I.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),D(i,{code:I.invalid_string,validation:{startsWith:a.value},message:a.message}),n.dirty()):a.kind==="endsWith"?e.data.endsWith(a.value)||(i=this._getOrReturnCtx(e,i),D(i,{code:I.invalid_string,validation:{endsWith:a.value},message:a.message}),n.dirty()):a.kind==="datetime"?mC(a).test(e.data)||(i=this._getOrReturnCtx(e,i),D(i,{code:I.invalid_string,validation:"datetime",message:a.message}),n.dirty()):a.kind==="date"?YL.test(e.data)||(i=this._getOrReturnCtx(e,i),D(i,{code:I.invalid_string,validation:"date",message:a.message}),n.dirty()):a.kind==="time"?eq(a).test(e.data)||(i=this._getOrReturnCtx(e,i),D(i,{code:I.invalid_string,validation:"time",message:a.message}),n.dirty()):a.kind==="duration"?UL.test(e.data)||(i=this._getOrReturnCtx(e,i),D(i,{validation:"duration",code:I.invalid_string,message:a.message}),n.dirty()):a.kind==="ip"?tq(e.data,a.version)||(i=this._getOrReturnCtx(e,i),D(i,{validation:"ip",code:I.invalid_string,message:a.message}),n.dirty()):a.kind==="jwt"?rq(e.data,a.alg)||(i=this._getOrReturnCtx(e,i),D(i,{validation:"jwt",code:I.invalid_string,message:a.message}),n.dirty()):a.kind==="cidr"?nq(e.data,a.version)||(i=this._getOrReturnCtx(e,i),D(i,{validation:"cidr",code:I.invalid_string,message:a.message}),n.dirty()):a.kind==="base64"?XL.test(e.data)||(i=this._getOrReturnCtx(e,i),D(i,{validation:"base64",code:I.invalid_string,message:a.message}),n.dirty()):a.kind==="base64url"?QL.test(e.data)||(i=this._getOrReturnCtx(e,i),D(i,{validation:"base64url",code:I.invalid_string,message:a.message}),n.dirty()):ae.assertNever(a);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(i=>e.test(i),{validation:r,code:I.invalid_string,...L.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...L.errToObj(e)})}url(e){return this._addCheck({kind:"url",...L.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...L.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...L.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...L.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...L.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...L.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...L.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...L.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...L.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...L.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...L.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...L.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,...L.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,...L.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...L.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...L.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...L.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...L.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...L.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...L.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...L.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...L.errToObj(r)})}nonempty(e){return this.min(1,L.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}};$n.create=t=>new $n({checks:[],typeName:R.ZodString,coerce:t?.coerce??!1,...G(t)});function iq(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 wi=class t extends Y{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)!==z.number){let a=this._getOrReturnCtx(e);return D(a,{code:I.invalid_type,expected:z.number,received:a.parsedType}),J}let n,i=new ut;for(let a of this._def.checks)a.kind==="int"?ae.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),D(n,{code:I.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),D(n,{code:I.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),D(n,{code:I.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),i.dirty()):a.kind==="multipleOf"?iq(e.data,a.value)!==0&&(n=this._getOrReturnCtx(e,n),D(n,{code:I.not_multiple_of,multipleOf:a.value,message:a.message}),i.dirty()):a.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),D(n,{code:I.not_finite,message:a.message}),i.dirty()):ae.assertNever(a);return{status:i.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,L.toString(r))}gt(e,r){return this.setLimit("min",e,!1,L.toString(r))}lte(e,r){return this.setLimit("max",e,!0,L.toString(r))}lt(e,r){return this.setLimit("max",e,!1,L.toString(r))}setLimit(e,r,n,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:L.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:L.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:L.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:L.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:L.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:L.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:L.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:L.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:L.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:L.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"&&ae.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)}};wi.create=t=>new wi({checks:[],typeName:R.ZodNumber,coerce:t?.coerce||!1,...G(t)});var _i=class t extends Y{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)!==z.bigint)return this._getInvalidInput(e);let n,i=new ut;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),D(n,{code:I.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),D(n,{code:I.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),D(n,{code:I.not_multiple_of,multipleOf:a.value,message:a.message}),i.dirty()):ae.assertNever(a);return{status:i.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return D(r,{code:I.invalid_type,expected:z.bigint,received:r.parsedType}),J}gte(e,r){return this.setLimit("min",e,!0,L.toString(r))}gt(e,r){return this.setLimit("min",e,!1,L.toString(r))}lte(e,r){return this.setLimit("max",e,!0,L.toString(r))}lt(e,r){return this.setLimit("max",e,!1,L.toString(r))}setLimit(e,r,n,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:L.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:L.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:L.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:L.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:L.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:L.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}};_i.create=t=>new _i({checks:[],typeName:R.ZodBigInt,coerce:t?.coerce??!1,...G(t)});var Si=class extends Y{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==z.boolean){let n=this._getOrReturnCtx(e);return D(n,{code:I.invalid_type,expected:z.boolean,received:n.parsedType}),J}return mt(e.data)}};Si.create=t=>new Si({typeName:R.ZodBoolean,coerce:t?.coerce||!1,...G(t)});var Ei=class t extends Y{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==z.date){let a=this._getOrReturnCtx(e);return D(a,{code:I.invalid_type,expected:z.date,received:a.parsedType}),J}if(Number.isNaN(e.data.getTime())){let a=this._getOrReturnCtx(e);return D(a,{code:I.invalid_date}),J}let n=new ut,i;for(let a of this._def.checks)a.kind==="min"?e.data.getTime()<a.value&&(i=this._getOrReturnCtx(e,i),D(i,{code:I.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),D(i,{code:I.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),n.dirty()):ae.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:L.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:L.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}};Ei.create=t=>new Ei({checks:[],coerce:t?.coerce||!1,typeName:R.ZodDate,...G(t)});var Va=class extends Y{_parse(e){if(this._getType(e)!==z.symbol){let n=this._getOrReturnCtx(e);return D(n,{code:I.invalid_type,expected:z.symbol,received:n.parsedType}),J}return mt(e.data)}};Va.create=t=>new Va({typeName:R.ZodSymbol,...G(t)});var ki=class extends Y{_parse(e){if(this._getType(e)!==z.undefined){let n=this._getOrReturnCtx(e);return D(n,{code:I.invalid_type,expected:z.undefined,received:n.parsedType}),J}return mt(e.data)}};ki.create=t=>new ki({typeName:R.ZodUndefined,...G(t)});var Ti=class extends Y{_parse(e){if(this._getType(e)!==z.null){let n=this._getOrReturnCtx(e);return D(n,{code:I.invalid_type,expected:z.null,received:n.parsedType}),J}return mt(e.data)}};Ti.create=t=>new Ti({typeName:R.ZodNull,...G(t)});var An=class extends Y{constructor(){super(...arguments),this._any=!0}_parse(e){return mt(e.data)}};An.create=t=>new An({typeName:R.ZodAny,...G(t)});var rn=class extends Y{constructor(){super(...arguments),this._unknown=!0}_parse(e){return mt(e.data)}};rn.create=t=>new rn({typeName:R.ZodUnknown,...G(t)});var yr=class extends Y{_parse(e){let r=this._getOrReturnCtx(e);return D(r,{code:I.invalid_type,expected:z.never,received:r.parsedType}),J}};yr.create=t=>new yr({typeName:R.ZodNever,...G(t)});var Ba=class extends Y{_parse(e){if(this._getType(e)!==z.undefined){let n=this._getOrReturnCtx(e);return D(n,{code:I.invalid_type,expected:z.void,received:n.parsedType}),J}return mt(e.data)}};Ba.create=t=>new Ba({typeName:R.ZodVoid,...G(t)});var nn=class t extends Y{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),i=this._def;if(r.parsedType!==z.array)return D(r,{code:I.invalid_type,expected:z.array,received:r.parsedType}),J;if(i.exactLength!==null){let o=r.data.length>i.exactLength.value,s=r.data.length<i.exactLength.value;(o||s)&&(D(r,{code:o?I.too_big:I.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&&(D(r,{code:I.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&&(D(r,{code:I.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 rr(r,o,r.path,s)))).then(o=>ut.mergeArray(n,o));let a=[...r.data].map((o,s)=>i.type._parseSync(new rr(r,o,r.path,s)));return ut.mergeArray(n,a)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:L.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:L.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:L.toString(r)}})}nonempty(e){return this.min(1,e)}};nn.create=(t,e)=>new nn({type:t,minLength:null,maxLength:null,exactLength:null,typeName:R.ZodArray,...G(e)});function qa(t){if(t instanceof Dt){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=Mt.create(qa(n))}return new Dt({...t._def,shape:()=>e})}else return t instanceof nn?new nn({...t._def,type:qa(t.element)}):t instanceof Mt?Mt.create(qa(t.unwrap())):t instanceof zr?zr.create(qa(t.unwrap())):t instanceof Dr?Dr.create(t.items.map(e=>qa(e))):t}var Dt=class t extends Y{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=ae.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==z.object){let l=this._getOrReturnCtx(e);return D(l,{code:I.invalid_type,expected:z.object,received:l.parsedType}),J}let{status:n,ctx:i}=this._processInputParams(e),{shape:a,keys:o}=this._getCached(),s=[];if(!(this._def.catchall instanceof yr&&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 rr(i,p,i.path,l)),alwaysSet:l in i.data})}if(this._def.catchall instanceof yr){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&&(D(i,{code:I.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 rr(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,d=await u.value;l.push({key:p,value:d,alwaysSet:u.alwaysSet})}return l}).then(l=>ut.mergeObjectSync(n,l)):ut.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return L.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:L.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:R.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 ae.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 ae.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return qa(this)}partial(e){let r={};for(let n of ae.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 ae.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let a=this.shape[n];for(;a instanceof Mt;)a=a._def.innerType;r[n]=a}return new t({...this._def,shape:()=>r})}keyof(){return hC(ae.objectKeys(this.shape))}};Dt.create=(t,e)=>new Dt({shape:()=>t,unknownKeys:"strip",catchall:yr.create(),typeName:R.ZodObject,...G(e)});Dt.strictCreate=(t,e)=>new Dt({shape:()=>t,unknownKeys:"strict",catchall:yr.create(),typeName:R.ZodObject,...G(e)});Dt.lazycreate=(t,e)=>new Dt({shape:t,unknownKeys:"strip",catchall:yr.create(),typeName:R.ZodObject,...G(e)});var Ci=class extends Y{_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 Nt(s.ctx.common.issues));return D(r,{code:I.invalid_union,unionErrors:o}),J}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 Nt(c));return D(r,{code:I.invalid_union,unionErrors:s}),J}}get options(){return this._def.options}};Ci.create=(t,e)=>new Ci({options:t,typeName:R.ZodUnion,...G(e)});var tn=t=>t instanceof Ai?tn(t.schema):t instanceof nr?tn(t.innerType()):t instanceof Pi?[t.value]:t instanceof Ii?t.options:t instanceof Ri?ae.objectValues(t.enum):t instanceof Oi?tn(t._def.innerType):t instanceof ki?[void 0]:t instanceof Ti?[null]:t instanceof Mt?[void 0,...tn(t.unwrap())]:t instanceof zr?[null,...tn(t.unwrap())]:t instanceof qs||t instanceof Mi?tn(t.unwrap()):t instanceof Ni?tn(t._def.innerType):[],Ju=class t extends Y{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==z.object)return D(r,{code:I.invalid_type,expected:z.object,received:r.parsedType}),J;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}):(D(r,{code:I.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),J)}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=tn(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:R.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:i,...G(n)})}};function ky(t,e){let r=Mr(t),n=Mr(e);if(t===e)return{valid:!0,data:t};if(r===z.object&&n===z.object){let i=ae.objectKeys(e),a=ae.objectKeys(t).filter(s=>i.indexOf(s)!==-1),o={...t,...e};for(let s of a){let c=ky(t[s],e[s]);if(!c.valid)return{valid:!1};o[s]=c.data}return{valid:!0,data:o}}else if(r===z.array&&n===z.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=ky(o,s);if(!c.valid)return{valid:!1};i.push(c.data)}return{valid:!0,data:i}}else return r===z.date&&n===z.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var $i=class extends Y{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),i=(a,o)=>{if(Uu(a)||Uu(o))return J;let s=ky(a.value,o.value);return s.valid?((Zu(a)||Zu(o))&&r.dirty(),{status:r.value,value:s.data}):(D(n,{code:I.invalid_intersection_types}),J)};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}))}};$i.create=(t,e,r)=>new $i({left:t,right:e,typeName:R.ZodIntersection,...G(r)});var Dr=class t extends Y{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==z.array)return D(n,{code:I.invalid_type,expected:z.array,received:n.parsedType}),J;if(n.data.length<this._def.items.length)return D(n,{code:I.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),J;!this._def.rest&&n.data.length>this._def.items.length&&(D(n,{code:I.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 rr(n,o,n.path,s)):null}).filter(o=>!!o);return n.common.async?Promise.all(a).then(o=>ut.mergeArray(r,o)):ut.mergeArray(r,a)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Dr.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Dr({items:t,typeName:R.ZodTuple,rest:null,...G(e)})};var Hu=class t extends Y{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!==z.object)return D(n,{code:I.invalid_type,expected:z.object,received:n.parsedType}),J;let i=[],a=this._def.keyType,o=this._def.valueType;for(let s in n.data)i.push({key:a._parse(new rr(n,s,n.path,s)),value:o._parse(new rr(n,n.data[s],n.path,s)),alwaysSet:s in n.data});return n.common.async?ut.mergeObjectAsync(r,i):ut.mergeObjectSync(r,i)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof Y?new t({keyType:e,valueType:r,typeName:R.ZodRecord,...G(n)}):new t({keyType:$n.create(),valueType:e,typeName:R.ZodRecord,...G(r)})}},Ua=class extends Y{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!==z.map)return D(n,{code:I.invalid_type,expected:z.map,received:n.parsedType}),J;let i=this._def.keyType,a=this._def.valueType,o=[...n.data.entries()].map(([s,c],l)=>({key:i._parse(new rr(n,s,n.path,[l,"key"])),value:a._parse(new rr(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 J;(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 J;(l.status==="dirty"||u.status==="dirty")&&r.dirty(),s.set(l.value,u.value)}return{status:r.value,value:s}}}};Ua.create=(t,e,r)=>new Ua({valueType:e,keyType:t,typeName:R.ZodMap,...G(r)});var Za=class t extends Y{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==z.set)return D(n,{code:I.invalid_type,expected:z.set,received:n.parsedType}),J;let i=this._def;i.minSize!==null&&n.data.size<i.minSize.value&&(D(n,{code:I.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&&(D(n,{code:I.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 J;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 rr(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:L.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:L.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};Za.create=(t,e)=>new Za({valueType:t,minSize:null,maxSize:null,typeName:R.ZodSet,...G(e)});var Ku=class t extends Y{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==z.function)return D(r,{code:I.invalid_type,expected:z.function,received:r.parsedType}),J;function n(s,c){return Ls({data:s,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Fa(),en].filter(l=>!!l),issueData:{code:I.invalid_arguments,argumentsError:c}})}function i(s,c){return Ls({data:s,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Fa(),en].filter(l=>!!l),issueData:{code:I.invalid_return_type,returnTypeError:c}})}let a={errorMap:r.common.contextualErrorMap},o=r.data;if(this._def.returns instanceof Pn){let s=this;return mt(async function(...c){let l=new Nt([]),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 mt(function(...c){let l=s._def.args.safeParse(c,a);if(!l.success)throw new Nt([n(c,l.error)]);let u=Reflect.apply(o,this,l.data),p=s._def.returns.safeParse(u,a);if(!p.success)throw new Nt([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:Dr.create(e).rest(rn.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||Dr.create([]).rest(rn.create()),returns:r||rn.create(),typeName:R.ZodFunction,...G(n)})}},Ai=class extends Y{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})}};Ai.create=(t,e)=>new Ai({getter:t,typeName:R.ZodLazy,...G(e)});var Pi=class extends Y{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return D(r,{received:r.data,code:I.invalid_literal,expected:this._def.value}),J}return{status:"valid",value:e.data}}get value(){return this._def.value}};Pi.create=(t,e)=>new Pi({value:t,typeName:R.ZodLiteral,...G(e)});function hC(t,e){return new Ii({values:t,typeName:R.ZodEnum,...G(e)})}var Ii=class t extends Y{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return D(r,{expected:ae.joinValues(n),received:r.parsedType,code:I.invalid_type}),J}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 D(r,{received:r.data,code:I.invalid_enum_value,options:n}),J}return mt(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})}};Ii.create=hC;var Ri=class extends Y{_parse(e){let r=ae.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==z.string&&n.parsedType!==z.number){let i=ae.objectValues(r);return D(n,{expected:ae.joinValues(i),received:n.parsedType,code:I.invalid_type}),J}if(this._cache||(this._cache=new Set(ae.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let i=ae.objectValues(r);return D(n,{received:n.data,code:I.invalid_enum_value,options:i}),J}return mt(e.data)}get enum(){return this._def.values}};Ri.create=(t,e)=>new Ri({values:t,typeName:R.ZodNativeEnum,...G(e)});var Pn=class extends Y{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==z.promise&&r.common.async===!1)return D(r,{code:I.invalid_type,expected:z.promise,received:r.parsedType}),J;let n=r.parsedType===z.promise?r.data:Promise.resolve(r.data);return mt(n.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Pn.create=(t,e)=>new Pn({type:t,typeName:R.ZodPromise,...G(e)});var nr=class extends Y{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===R.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=>{D(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 J;let c=await this._def.schema._parseAsync({data:s,path:n.path,parent:n});return c.status==="aborted"?J:c.status==="dirty"?xi(c.value):r.value==="dirty"?xi(c.value):c});{if(r.value==="aborted")return J;let s=this._def.schema._parseSync({data:o,path:n.path,parent:n});return s.status==="aborted"?J:s.status==="dirty"?xi(s.value):r.value==="dirty"?xi(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"?J:(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"?J:(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(!Cn(o))return J;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=>Cn(o)?Promise.resolve(i.transform(o.value,a)).then(s=>({status:r.value,value:s})):J);ae.assertNever(i)}};nr.create=(t,e,r)=>new nr({schema:t,typeName:R.ZodEffects,effect:e,...G(r)});nr.createWithPreprocess=(t,e,r)=>new nr({schema:e,effect:{type:"preprocess",transform:t},typeName:R.ZodEffects,...G(r)});var Mt=class extends Y{_parse(e){return this._getType(e)===z.undefined?mt(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Mt.create=(t,e)=>new Mt({innerType:t,typeName:R.ZodOptional,...G(e)});var zr=class extends Y{_parse(e){return this._getType(e)===z.null?mt(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};zr.create=(t,e)=>new zr({innerType:t,typeName:R.ZodNullable,...G(e)});var Oi=class extends Y{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===z.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};Oi.create=(t,e)=>new Oi({innerType:t,typeName:R.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...G(e)});var Ni=class extends Y{_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 La(i)?i.then(a=>({status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new Nt(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Nt(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Ni.create=(t,e)=>new Ni({innerType:t,typeName:R.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...G(e)});var Ja=class extends Y{_parse(e){if(this._getType(e)!==z.nan){let n=this._getOrReturnCtx(e);return D(n,{code:I.invalid_type,expected:z.nan,received:n.parsedType}),J}return{status:"valid",value:e.data}}};Ja.create=t=>new Ja({typeName:R.ZodNaN,...G(t)});var aq=Symbol("zod_brand"),qs=class extends Y{_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}},Vs=class t extends Y{_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"?J:a.status==="dirty"?(r.dirty(),xi(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"?J: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:R.ZodPipeline})}},Mi=class extends Y{_parse(e){let r=this._def.innerType._parse(e),n=i=>(Cn(i)&&(i.value=Object.freeze(i.value)),i);return La(r)?r.then(i=>n(i)):n(r)}unwrap(){return this._def.innerType}};Mi.create=(t,e)=>new Mi({innerType:t,typeName:R.ZodReadonly,...G(e)});function pC(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function gC(t,e={},r){return t?An.create().superRefine((n,i)=>{let a=t(n);if(a instanceof Promise)return a.then(o=>{if(!o){let s=pC(e,n),c=s.fatal??r??!0;i.addIssue({code:"custom",...s,fatal:c})}});if(!a){let o=pC(e,n),s=o.fatal??r??!0;i.addIssue({code:"custom",...o,fatal:s})}}):An.create()}var oq={object:Dt.lazycreate},R;(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"})(R||(R={}));var sq=(t,e={message:`Input not instance of ${t.name}`})=>gC(r=>r instanceof t,e),yC=$n.create,bC=wi.create,cq=Ja.create,lq=_i.create,vC=Si.create,uq=Ei.create,pq=Va.create,dq=ki.create,fq=Ti.create,mq=An.create,hq=rn.create,gq=yr.create,yq=Ba.create,bq=nn.create,Ty=Dt.create,vq=Dt.strictCreate,xq=Ci.create,wq=Ju.create,_q=$i.create,Sq=Dr.create,Eq=Hu.create,kq=Ua.create,Tq=Za.create,Cq=Ku.create,$q=Ai.create,Aq=Pi.create,Pq=Ii.create,Iq=Ri.create,Rq=Pn.create,Oq=nr.create,Nq=Mt.create,Mq=zr.create,Dq=nr.createWithPreprocess,zq=Vs.create,jq=()=>yC().optional(),Fq=()=>bC().optional(),Lq=()=>vC().optional(),qq={string:t=>$n.create({...t,coerce:!0}),number:t=>wi.create({...t,coerce:!0}),boolean:t=>Si.create({...t,coerce:!0}),bigint:t=>_i.create({...t,coerce:!0}),date:t=>Ei.create({...t,coerce:!0})};var Vq=J;var Uq=$("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");Se.init(t,e),t.def=e,t.parse=(r,n)=>Cd(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>Qn(t,r,n),t.parseAsync=async(r,n)=>Ad(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Yn(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)=>Zt(t,r,n),t.brand=()=>t,t.register=(r,n)=>(r.add(t,n),t)});var Zq=$("ZodMiniObject",(t,e)=>{qc.init(t,e),Uq.init(t,e),oe.defineLazy(t,"shape",()=>e.shape)});function Cy(t,e){let r={type:"object",get shape(){return oe.assignProp(this,"shape",{...t}),this.shape},...oe.normalizeParams(e)};return new Zq(r)}function ir(t){return!!t._zod}function Di(t){let e=Object.values(t);if(e.length===0)return Cy({});let r=e.every(ir),n=e.every(i=>!ir(i));if(r)return Cy(t);if(n)return Ty(t);throw new Error("Mixed Zod versions detected in object shape.")}function In(t,e){return ir(t)?Qn(t,e):t.safeParse(e)}async function Wu(t,e){return ir(t)?await Yn(t,e):await t.safeParseAsync(e)}function Rn(t){if(!t)return;let e;if(ir(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function Ha(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 Di(t)}}if(ir(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 Gu(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 xC(t){return t.description}function wC(t){if(ir(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function Xu(t){if(ir(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 On(t){return t==="completed"||t==="failed"||t==="cancelled"}var SC=Symbol("Let zodToJsonSchema decide on which parser to use");var _C={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"},EC=t=>typeof t=="string"?{..._C,name:t}:{..._C,...t};var kC=t=>{let e=EC(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 $y(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function ce(t,e,r,n,i){t[e]=r,$y(t,e,n,i)}var Qu=(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 Le(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?Qu(e,t.currentPath):e.join("/")}}function TC(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==R.ZodAny&&(r.items=H(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&ce(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&ce(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(ce(r,"minItems",t.exactLength.value,t.exactLength.message,e),ce(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function CC(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?ce(r,"minimum",n.value,n.message,e):ce(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ce(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ce(r,"maximum",n.value,n.message,e):ce(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ce(r,"maximum",n.value,n.message,e));break;case"multipleOf":ce(r,"multipleOf",n.value,n.message,e);break}return r}function $C(){return{type:"boolean"}}function Yu(t,e){return H(t.type._def,e)}var AC=(t,e)=>H(t.innerType._def,e);function Ay(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((i,a)=>Ay(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 Hq(t,e)}}var Hq=(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":ce(r,"minimum",n.value,n.message,e);break;case"max":ce(r,"maximum",n.value,n.message,e);break}return r};function PC(t,e){return{...H(t.innerType._def,e),default:t.defaultValue()}}function IC(t,e){return e.effectStrategy==="input"?H(t.schema._def,e):Le(e)}function RC(t){return{type:"string",enum:Array.from(t.values)}}var Kq=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function OC(t,e){let r=[H(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),H(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(Kq(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 NC(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 Py,br={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:()=>(Py===void 0&&(Py=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Py),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 ep(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":ce(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":ce(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":vr(r,"email",n.message,e);break;case"format:idn-email":vr(r,"idn-email",n.message,e);break;case"pattern:zod":St(r,br.email,n.message,e);break}break;case"url":vr(r,"uri",n.message,e);break;case"uuid":vr(r,"uuid",n.message,e);break;case"regex":St(r,n.regex,n.message,e);break;case"cuid":St(r,br.cuid,n.message,e);break;case"cuid2":St(r,br.cuid2,n.message,e);break;case"startsWith":St(r,RegExp(`^${Iy(n.value,e)}`),n.message,e);break;case"endsWith":St(r,RegExp(`${Iy(n.value,e)}$`),n.message,e);break;case"datetime":vr(r,"date-time",n.message,e);break;case"date":vr(r,"date",n.message,e);break;case"time":vr(r,"time",n.message,e);break;case"duration":vr(r,"duration",n.message,e);break;case"length":ce(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),ce(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{St(r,RegExp(Iy(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&vr(r,"ipv4",n.message,e),n.version!=="v4"&&vr(r,"ipv6",n.message,e);break}case"base64url":St(r,br.base64url,n.message,e);break;case"jwt":St(r,br.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&St(r,br.ipv4Cidr,n.message,e),n.version!=="v4"&&St(r,br.ipv6Cidr,n.message,e);break}case"emoji":St(r,br.emoji(),n.message,e);break;case"ulid":{St(r,br.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{vr(r,"binary",n.message,e);break}case"contentEncoding:base64":{ce(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{St(r,br.base64,n.message,e);break}}break}case"nanoid":St(r,br.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function Iy(t,e){return e.patternStrategy==="escape"?Gq(t):t}var Wq=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Gq(t){let e="";for(let r=0;r<t.length;r++)Wq.has(t[r])||(e+="\\"),e+=t[r];return e}function vr(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}}})):ce(t,"format",e,r,n)}function St(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:MC(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):ce(t,"pattern",MC(e,n),r,n)}function MC(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
|
|
124
|
+
`).trim()}function _y(t){if(Array.isArray(t))return t.map(_y);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,_y(n)]))}function oC(t){try{let e=typeof t=="string"?JSON.parse(t):t;return JSON.stringify(_y(e))}catch{return}}function OL(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(PL.has(i)||i==="ViewSchema"){let s=oC(a),c=oC(o);(!s||!c||s!==c)&&n.push(i);continue}String(a??"")!==String(o??"")&&n.push(i)}return{matched:n.length===0,mismatches:n}}var Fs=class{config;token="";refreshTimer;rsaPublicKey;did;requestTimeoutMs;writeRequestTimeoutMs;readbackRequestTimeoutMs;inflightRefresh;inflightAuthRecovery;inflightCredentialRecovery;constructor(e){this.config=e,this.rsaPublicKey=e.rsaPublicKey||wL,this.did=eC(process.env.MICROI_MCP_DID,sC.default.hostname()),this.requestTimeoutMs=Vu(e.requestTimeoutMs??process.env.MICROI_MCP_HTTP_TIMEOUT_MS,EL),this.writeRequestTimeoutMs=Vu(e.writeRequestTimeoutMs??process.env.MICROI_MCP_WRITE_TIMEOUT_MS,kL),this.readbackRequestTimeoutMs=Vu(e.readbackRequestTimeoutMs??process.env.MICROI_MCP_READBACK_TIMEOUT_MS,TL),e.token&&(this.token=Yr(e.token))}rsaEncrypt(e){let r=(this.rsaPublicKey||"").trim();return r?vi.default.publicEncrypt({key:r,padding:vi.default.constants.RSA_PKCS1_PADDING},Buffer.from(e,"utf-8")).toString("base64"):e}updateToken(e){this.token=Yr(e)}async login(e){if(this.token){this.startAutoRefresh(),console.error("[microi-mcp] Using provided token (auto-refresh enabled)");return}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=Yr(a),this.startAutoRefresh(),console.error("[microi-mcp] Login successful")}startAutoRefresh(){this.refreshTimer&&clearInterval(this.refreshTimer),this.refreshTimer=setInterval(()=>{tC(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=Yr(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(Kt.default.readFileSync(e,"utf-8")),i=Bu(this.config.apiBaseUrl,this.config.osClient,this.config.osClientType,this.config.osClientNetwork).map(o=>r[o]).find(Boolean),a=Yr(i);if(a&&a!==this.token)return this.token=a,!0}catch{}return!1}writeTokenToFile(){let e=this.config.tokenFilePath;if(!(!e||!this.token))try{let r={};try{r=JSON.parse(Kt.default.readFileSync(e,"utf-8"))}catch{}let[n]=Bu(this.config.apiBaseUrl,this.config.osClient,this.config.osClientType,this.config.osClientNetwork);if(!n)return;r[n]=this.token;let i=zs.default.dirname(e);Kt.default.existsSync(i)||Kt.default.mkdirSync(i,{recursive:!0}),Kt.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{Kt.default.existsSync(r)||Kt.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=`${vi.default.createHash("sha256").update(c).digest("hex").slice(0,24)}-${process.pid}-${Date.now()}-${vi.default.randomBytes(4).toString("hex")}.json`,p=zs.default.join(r,u),d=`${p}.${process.pid}.tmp`,h={version:1,apiBaseUrl:i,osClient:a,osClientType:o,osClientNetwork:s,requestedAt:Date.now(),failedTokenHash:vi.default.createHash("sha256").update(e||"").digest("hex")};Kt.default.writeFileSync(d,JSON.stringify(h),{encoding:"utf-8",mode:384}),Kt.default.renameSync(d,p);for(let m=0;m<40;m++)if(await new Promise(y=>setTimeout(y,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.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)}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=Vu(o.timeoutMs,this.requestTimeoutMs),p=o.operationName||`${e} ${r}`,d=new AbortController,h=setTimeout(()=>d.abort(),u),m,y;try{m=await fetch(s,{method:e,headers:l,signal:d.signal,...e==="POST"?{body:JSON.stringify(n??{})}:{}}),y=await m.text()}catch(b){let v=d.signal.aborted;throw new js(v?`${p} \u8BF7\u6C42\u8D85\u65F6\uFF08${u}ms\uFF09`:`${p} \u7F51\u7EDC\u8BF7\u6C42\u5931\u8D25\uFF1A${b instanceof Error?b.message:String(b)}`,{kind:v?"timeout":"network",requestPath:r,uncertainOutcome:e==="POST",cause:b})}finally{clearTimeout(h)}let g=m.headers.get("authorization");if(g&&(this.token=Yr(g),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,qu(a),o);throw new Error(`HTTP 401 Unauthorized \u2014 token recovery failed: ${y.slice(0,200)}`)}if(!m.ok)throw new Error(`HTTP ${m.status} ${m.statusText} \u2014 ${y.slice(0,200)}`);if(!y)throw new Error(`HTTP ${m.status} \u2014 empty response body`);let x;try{x=JSON.parse(y)}catch{throw new Error(`HTTP ${m.status} \u2014 invalid JSON: ${y.slice(0,200)}`)}if(aC(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,qu(a),o)}return x}async requestMultipartFile(e,r,n,i,a="initial",o){let s=this.token,c=`----microi-mcp-${vi.default.randomBytes(24).toString("hex")}`,l=RL(r,n,i,c),u=new AbortController,p=IL(o),d=setTimeout(()=>u.abort(),p),h,m;try{h=await fetch(`${this.config.apiBaseUrl}${e}`,{method:"POST",headers:{Authorization:`Bearer ${s}`,did:this.did,...this.config.osClient?{OsClient:this.config.osClient}:{},"Content-Type":`multipart/form-data; boundary=${c}`,"Content-Length":String(l.contentLength)},body:l.body,duplex:"half",signal:u.signal}),m=await h.text()}catch(x){let b=u.signal.aborted;throw new js(b?`\u5E94\u7528\u8D44\u4EA7\u6D41\u5F0F\u4E0A\u4F20\u8D85\u65F6\uFF08${p}ms\uFF09`:`\u5E94\u7528\u8D44\u4EA7\u6D41\u5F0F\u4E0A\u4F20\u7F51\u7EDC\u5931\u8D25\uFF1A${x instanceof Error?x.message:String(x)}`,{kind:b?"timeout":"network",requestPath:e,uncertainOutcome:!0,cause:x})}finally{clearTimeout(d),l.body.destroy()}let y=h.headers.get("authorization");if(y&&(this.token=Yr(y),this.writeTokenToFile()),h.status===401&&a!=="credential-token"){let x=a!=="initial";if(x&&console.error("[microi-mcp] Replacement token was rejected; escalating to credential recovery"),await this.tryRecoverFromAuthFailure(s,x))return this.requestMultipartFile(e,r,n,i,qu(a),o);throw new Error(`HTTP 401 Unauthorized \u2014 token recovery failed: ${m.slice(0,200)}`)}if(!h.ok)throw new Error(`HTTP ${h.status} ${h.statusText} \u2014 ${m.slice(0,200)}`);if(!m)throw new Error(`HTTP ${h.status} \u2014 empty response body`);let g;try{g=JSON.parse(m)}catch{throw new Error(`HTTP ${h.status} \u2014 invalid JSON: ${m.slice(0,200)}`)}if(aC(g)&&a!=="credential-token"){let x=a!=="initial";if(x&&console.error("[microi-mcp] Replacement token was rejected; escalating to credential recovery"),await this.tryRecoverFromAuthFailure(s,x))return this.requestMultipartFile(e,r,n,i,qu(a),o)}return g}isUncertainWriteError(e){return e instanceof js&&e.uncertainOutcome}readbackOptions(e){return{timeoutMs:this.readbackRequestTimeoutMs,operationName:e}}async pollReadback(e,r){let n,i="";for(let a of CL){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 saveEngineCode(e,r,n){Ms(r,`\u4FDD\u5B58\u63A5\u53E3\u5F15\u64CE ${e}`);let i;try{let u=await this.getEngineCode(e);i=u.Code===1?u.Data:void 0}catch{i=void 0}let a=Tn(i?.ApiV8Code||i?.Code),o=Tn(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=Ds({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={OsClient:this.config.osClient,ApiEngineKey:e,ApiV8CodeBase64:Buffer.from(s.code,"utf8").toString("base64"),Version:s.version,ChangeHistory:s.changeHistory,...n?.v8Unlimited===void 0?{}:{V8Unlimited:n.v8Unlimited?1:0}},l=u=>Tn(u?.ApiV8Code||u?.Code)===Tn(s.code)&&(n?.v8Unlimited===void 0||Number(u?.V8Unlimited||0)===(n.v8Unlimited?1:0));try{let u=await this.post(O.UPDATE_ENGINE_CODE,c,{timeoutMs:this.writeRequestTimeoutMs,operationName:`\u4FDD\u5B58\u63A5\u53E3\u5F15\u64CE ${e}`});if(u.Code!==1||n?.v8Unlimited===void 0)return u;let p=await this.pollReadback(()=>this.getEngineCode(e,this.readbackOptions(`\u56DE\u8BFB\u63A5\u53E3\u5F15\u64CE ${e} V8Unlimited`)),l);return p.matched?{...u,Data:{...u.Data&&typeof u.Data=="object"?u.Data:{},ApiEngineKey:e,V8Unlimited:n.v8Unlimited?1:0,Verified:!0,Verification:"readback"}}:{Code:0,Data:{ApiEngineKey:e,UpdateResponse:u.Data},Msg:`\u4FDD\u5B58\u63A5\u53E3\u5F15\u64CE ${e} \u8FD4\u56DE\u6210\u529F\uFF0C\u4F46 V8Unlimited \u5199\u540E\u56DE\u8BFB\u4E0D\u4E00\u81F4\uFF1A${p.lastError||"\u4EE3\u7801\u6216\u914D\u7F6E\u4E0D\u4E00\u81F4"}`}}catch(u){if(!this.isUncertainWriteError(u))throw u;let p=await this.pollReadback(()=>this.getEngineCode(e,this.readbackOptions(`\u56DE\u8BFB\u63A5\u53E3\u5F15\u64CE ${e}`)),l);if(p.matched)return this.recoveredWriteResult(`\u4FDD\u5B58\u63A5\u53E3\u5F15\u64CE ${e}`,u,{ApiEngineKey:e,Version:s.version});throw this.uncertainWriteFailure(`\u4FDD\u5B58\u63A5\u53E3\u5F15\u64CE ${e}`,u,p.lastError)}}async updateEngineRuntimeConfig(e,r){let n={OsClient:this.config.osClient,ApiEngineKey:e,V8Unlimited:r?1:0},i=()=>this.pollReadback(()=>this.getEngineCode(e,this.readbackOptions(`\u56DE\u8BFB\u63A5\u53E3\u5F15\u64CE ${e} V8Unlimited`)),o=>Number(o?.V8Unlimited||0)===(r?1:0)),a=`\u66F4\u65B0\u63A5\u53E3\u5F15\u64CE ${e} V8Unlimited`;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,V8Unlimited: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,V8Unlimited:r?1:0,Verified:!0});throw this.uncertainWriteFailure(a,o,s.lastError)}}async createEngine(e){let r={OsClient:this.config.osClient,...e},n=typeof r.Code=="string"?r.Code:typeof r.ApiV8Code=="string"?r.ApiV8Code:"";Ms(n,`\u521B\u5EFA\u63A5\u53E3\u5F15\u64CE ${e.ApiEngineKey}`);let i=Ds({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.ChangeHistory=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&&Tn(s?.ApiV8Code||s?.Code)===Tn(i.code)&&(e.V8Unlimited===void 0||Number(s?.V8Unlimited||0)===(e.V8Unlimited===1?1:0)));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=zs.default.resolve(e.FilePath),n=Kt.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=zs.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");let a={};if(e.ProtocolVersion===3){let o=s=>s===null?"null":String(s??"");Object.assign(a,{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:o(e.ExpectedAppVersion),ExpectedPublishFence:String(e.ExpectedPublishFence??""),ExpectedPublishRowVersion:String(e.ExpectedPublishRowVersion??""),ExpectedVersionRowVersion:o(e.ExpectedVersionRowVersion),ExpectedActivePublishVersionId:o(e.ExpectedActivePublishVersionId),ExpectedCommittedPublishVersionId:o(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,...a},r,i,"initial",e.TimeoutMs)}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=_L(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),d=/<body(?:\s|>)/iu.test(u),h=a.ok&&o.toLowerCase().includes("text/html")&&l>0&&p&&d;return{ok:h,url:r,status:a.status,contentType:o,bodyBytes:l,hasHead:p,hasBody:d,...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){Ms(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=Ds({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=>Tn(u?.V8Code||u?.Code)===Tn(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){Ms(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=Ds({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){return this.post(O.CREATE_TABLE,{OsClient:this.config.osClient,Name:e,Description:r||"",...n})}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();Ns(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}:{...OL(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,ApiEngineKey: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 getRedisStatistics(e=0,r){return this.post(O.REDIS_STATISTICS,{Mode:r?"saved":"tenant",ConnectionId:r||"",Database:e})}async getRedisKeys(e="*",r=0,n=100,i,a){return this.post(O.REDIS_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,{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,{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,{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,{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,{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 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 saveBlueprint(e){return this.post(O.SAVE_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 f={};fd(f,{BRAND:()=>aq,DIRTY:()=>xi,EMPTY_PATH:()=>zL,INVALID:()=>J,NEVER:()=>Vq,OK:()=>mt,ParseStatus:()=>ut,Schema:()=>Y,ZodAny:()=>An,ZodArray:()=>nn,ZodBigInt:()=>_i,ZodBoolean:()=>Si,ZodBranded:()=>qs,ZodCatch:()=>Ni,ZodDate:()=>Ei,ZodDefault:()=>Oi,ZodDiscriminatedUnion:()=>Ju,ZodEffects:()=>nr,ZodEnum:()=>Ii,ZodError:()=>Nt,ZodFirstPartyTypeKind:()=>R,ZodFunction:()=>Ku,ZodIntersection:()=>$i,ZodIssueCode:()=>I,ZodLazy:()=>Ai,ZodLiteral:()=>Pi,ZodMap:()=>Ua,ZodNaN:()=>Ja,ZodNativeEnum:()=>Ri,ZodNever:()=>yr,ZodNull:()=>Ti,ZodNullable:()=>zr,ZodNumber:()=>wi,ZodObject:()=>Dt,ZodOptional:()=>Mt,ZodParsedType:()=>z,ZodPipeline:()=>Vs,ZodPromise:()=>Pn,ZodReadonly:()=>Mi,ZodRecord:()=>Hu,ZodSchema:()=>Y,ZodSet:()=>Za,ZodString:()=>$n,ZodSymbol:()=>Va,ZodTransformer:()=>nr,ZodTuple:()=>Dr,ZodType:()=>Y,ZodUndefined:()=>ki,ZodUnion:()=>Ci,ZodUnknown:()=>rn,ZodVoid:()=>Ba,addIssueToContext:()=>D,any:()=>mq,array:()=>bq,bigint:()=>lq,boolean:()=>vC,coerce:()=>qq,custom:()=>gC,date:()=>uq,datetimeRegex:()=>mC,defaultErrorMap:()=>en,discriminatedUnion:()=>wq,effect:()=>Oq,enum:()=>Pq,function:()=>Cq,getErrorMap:()=>Fa,getParsedType:()=>Mr,instanceof:()=>sq,intersection:()=>_q,isAborted:()=>Uu,isAsync:()=>La,isDirty:()=>Zu,isValid:()=>Cn,late:()=>oq,lazy:()=>$q,literal:()=>Aq,makeIssue:()=>Ls,map:()=>kq,nan:()=>cq,nativeEnum:()=>Iq,never:()=>gq,null:()=>fq,nullable:()=>Mq,number:()=>bC,object:()=>Ty,objectUtil:()=>Sy,oboolean:()=>Lq,onumber:()=>Fq,optional:()=>Nq,ostring:()=>jq,pipeline:()=>zq,preprocess:()=>Dq,promise:()=>Rq,quotelessJson:()=>NL,record:()=>Eq,set:()=>Tq,setErrorMap:()=>DL,strictObject:()=>vq,string:()=>yC,symbol:()=>pq,transformer:()=>Oq,tuple:()=>Sq,undefined:()=>dq,union:()=>xq,unknown:()=>hq,util:()=>ae,void:()=>yq});var ae;(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})(ae||(ae={}));var Sy;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Sy||(Sy={}));var z=ae.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Mr=t=>{switch(typeof t){case"undefined":return z.undefined;case"string":return z.string;case"number":return Number.isNaN(t)?z.nan:z.number;case"boolean":return z.boolean;case"function":return z.function;case"bigint":return z.bigint;case"symbol":return z.symbol;case"object":return Array.isArray(t)?z.array:t===null?z.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?z.promise:typeof Map<"u"&&t instanceof Map?z.map:typeof Set<"u"&&t instanceof Set?z.set:typeof Date<"u"&&t instanceof Date?z.date:z.object;default:return z.unknown}};var I=ae.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"]),NL=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),Nt=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,ae.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()}};Nt.create=t=>new Nt(t);var ML=(t,e)=>{let r;switch(t.code){case I.invalid_type:t.received===z.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case I.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,ae.jsonStringifyReplacer)}`;break;case I.unrecognized_keys:r=`Unrecognized key(s) in object: ${ae.joinValues(t.keys,", ")}`;break;case I.invalid_union:r="Invalid input";break;case I.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${ae.joinValues(t.options)}`;break;case I.invalid_enum_value:r=`Invalid enum value. Expected ${ae.joinValues(t.options)}, received '${t.received}'`;break;case I.invalid_arguments:r="Invalid function arguments";break;case I.invalid_return_type:r="Invalid function return type";break;case I.invalid_date:r="Invalid date";break;case I.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}"`:ae.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case I.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 I.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 I.custom:r="Invalid input";break;case I.invalid_intersection_types:r="Intersection results could not be merged";break;case I.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case I.not_finite:r="Number must be finite";break;default:r=e.defaultError,ae.assertNever(t)}return{message:r}},en=ML;var lC=en;function DL(t){lC=t}function Fa(){return lC}var Ls=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}},zL=[];function D(t,e){let r=Fa(),n=Ls({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===en?void 0:en].filter(i=>!!i)});t.common.issues.push(n)}var ut=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 J;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 J;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}}},J=Object.freeze({status:"aborted"}),xi=t=>({status:"dirty",value:t}),mt=t=>({status:"valid",value:t}),Uu=t=>t.status==="aborted",Zu=t=>t.status==="dirty",Cn=t=>t.status==="valid",La=t=>typeof Promise<"u"&&t instanceof Promise;var L;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(L||(L={}));var rr=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}},uC=(t,e)=>{if(Cn(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 Nt(t.common.issues);return this._error=r,this._error}}};function G(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 Y=class{get description(){return this._def.description}_getType(e){return Mr(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:Mr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ut,ctx:{common:e.parent.common,data:e.data,parsedType:Mr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(La(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:Mr(e)},i=this._parseSync({data:e,path:n.path,parent:n});return uC(n,i)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Mr(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return Cn(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=>Cn(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:Mr(e)},i=this._parse({data:e,path:n.path,parent:n}),a=await(La(i)?i:Promise.resolve(i));return uC(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:I.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 nr({schema:this,typeName:R.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 Mt.create(this,this._def)}nullable(){return zr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return nn.create(this)}promise(){return Pn.create(this,this._def)}or(e){return Ci.create([this,e],this._def)}and(e){return $i.create(this,e,this._def)}transform(e){return new nr({...G(this._def),schema:this,typeName:R.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new Oi({...G(this._def),innerType:this,defaultValue:r,typeName:R.ZodDefault})}brand(){return new qs({typeName:R.ZodBranded,type:this,...G(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Ni({...G(this._def),innerType:this,catchValue:r,typeName:R.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return Vs.create(this,e)}readonly(){return Mi.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},jL=/^c[^\s-]{8,}$/i,FL=/^[0-9a-z]+$/,LL=/^[0-9A-HJKMNP-TV-Z]{26}$/i,qL=/^[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,VL=/^[a-z0-9_-]{21}$/i,BL=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,UL=/^[-+]?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)?)??$/,ZL=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,JL="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Ey,HL=/^(?:(?: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])$/,KL=/^(?:(?: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])$/,WL=/^(([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]))$/,GL=/^(([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])$/,XL=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,QL=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,dC="((\\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])))",YL=new RegExp(`^${dC}$`);function fC(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 eq(t){return new RegExp(`^${fC(t)}$`)}function mC(t){let e=`${dC}T${fC(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 tq(t,e){return!!((e==="v4"||!e)&&HL.test(t)||(e==="v6"||!e)&&WL.test(t))}function rq(t,e){if(!BL.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 nq(t,e){return!!((e==="v4"||!e)&&KL.test(t)||(e==="v6"||!e)&&GL.test(t))}var $n=class t extends Y{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==z.string){let a=this._getOrReturnCtx(e);return D(a,{code:I.invalid_type,expected:z.string,received:a.parsedType}),J}let n=new ut,i;for(let a of this._def.checks)if(a.kind==="min")e.data.length<a.value&&(i=this._getOrReturnCtx(e,i),D(i,{code:I.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),D(i,{code:I.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?D(i,{code:I.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}):s&&D(i,{code:I.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}),n.dirty())}else if(a.kind==="email")ZL.test(e.data)||(i=this._getOrReturnCtx(e,i),D(i,{validation:"email",code:I.invalid_string,message:a.message}),n.dirty());else if(a.kind==="emoji")Ey||(Ey=new RegExp(JL,"u")),Ey.test(e.data)||(i=this._getOrReturnCtx(e,i),D(i,{validation:"emoji",code:I.invalid_string,message:a.message}),n.dirty());else if(a.kind==="uuid")qL.test(e.data)||(i=this._getOrReturnCtx(e,i),D(i,{validation:"uuid",code:I.invalid_string,message:a.message}),n.dirty());else if(a.kind==="nanoid")VL.test(e.data)||(i=this._getOrReturnCtx(e,i),D(i,{validation:"nanoid",code:I.invalid_string,message:a.message}),n.dirty());else if(a.kind==="cuid")jL.test(e.data)||(i=this._getOrReturnCtx(e,i),D(i,{validation:"cuid",code:I.invalid_string,message:a.message}),n.dirty());else if(a.kind==="cuid2")FL.test(e.data)||(i=this._getOrReturnCtx(e,i),D(i,{validation:"cuid2",code:I.invalid_string,message:a.message}),n.dirty());else if(a.kind==="ulid")LL.test(e.data)||(i=this._getOrReturnCtx(e,i),D(i,{validation:"ulid",code:I.invalid_string,message:a.message}),n.dirty());else if(a.kind==="url")try{new URL(e.data)}catch{i=this._getOrReturnCtx(e,i),D(i,{validation:"url",code:I.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),D(i,{validation:"regex",code:I.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),D(i,{code:I.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),D(i,{code:I.invalid_string,validation:{startsWith:a.value},message:a.message}),n.dirty()):a.kind==="endsWith"?e.data.endsWith(a.value)||(i=this._getOrReturnCtx(e,i),D(i,{code:I.invalid_string,validation:{endsWith:a.value},message:a.message}),n.dirty()):a.kind==="datetime"?mC(a).test(e.data)||(i=this._getOrReturnCtx(e,i),D(i,{code:I.invalid_string,validation:"datetime",message:a.message}),n.dirty()):a.kind==="date"?YL.test(e.data)||(i=this._getOrReturnCtx(e,i),D(i,{code:I.invalid_string,validation:"date",message:a.message}),n.dirty()):a.kind==="time"?eq(a).test(e.data)||(i=this._getOrReturnCtx(e,i),D(i,{code:I.invalid_string,validation:"time",message:a.message}),n.dirty()):a.kind==="duration"?UL.test(e.data)||(i=this._getOrReturnCtx(e,i),D(i,{validation:"duration",code:I.invalid_string,message:a.message}),n.dirty()):a.kind==="ip"?tq(e.data,a.version)||(i=this._getOrReturnCtx(e,i),D(i,{validation:"ip",code:I.invalid_string,message:a.message}),n.dirty()):a.kind==="jwt"?rq(e.data,a.alg)||(i=this._getOrReturnCtx(e,i),D(i,{validation:"jwt",code:I.invalid_string,message:a.message}),n.dirty()):a.kind==="cidr"?nq(e.data,a.version)||(i=this._getOrReturnCtx(e,i),D(i,{validation:"cidr",code:I.invalid_string,message:a.message}),n.dirty()):a.kind==="base64"?XL.test(e.data)||(i=this._getOrReturnCtx(e,i),D(i,{validation:"base64",code:I.invalid_string,message:a.message}),n.dirty()):a.kind==="base64url"?QL.test(e.data)||(i=this._getOrReturnCtx(e,i),D(i,{validation:"base64url",code:I.invalid_string,message:a.message}),n.dirty()):ae.assertNever(a);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(i=>e.test(i),{validation:r,code:I.invalid_string,...L.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...L.errToObj(e)})}url(e){return this._addCheck({kind:"url",...L.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...L.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...L.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...L.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...L.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...L.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...L.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...L.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...L.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...L.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...L.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...L.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,...L.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,...L.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...L.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...L.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...L.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...L.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...L.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...L.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...L.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...L.errToObj(r)})}nonempty(e){return this.min(1,L.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}};$n.create=t=>new $n({checks:[],typeName:R.ZodString,coerce:t?.coerce??!1,...G(t)});function iq(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 wi=class t extends Y{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)!==z.number){let a=this._getOrReturnCtx(e);return D(a,{code:I.invalid_type,expected:z.number,received:a.parsedType}),J}let n,i=new ut;for(let a of this._def.checks)a.kind==="int"?ae.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),D(n,{code:I.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),D(n,{code:I.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),D(n,{code:I.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),i.dirty()):a.kind==="multipleOf"?iq(e.data,a.value)!==0&&(n=this._getOrReturnCtx(e,n),D(n,{code:I.not_multiple_of,multipleOf:a.value,message:a.message}),i.dirty()):a.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),D(n,{code:I.not_finite,message:a.message}),i.dirty()):ae.assertNever(a);return{status:i.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,L.toString(r))}gt(e,r){return this.setLimit("min",e,!1,L.toString(r))}lte(e,r){return this.setLimit("max",e,!0,L.toString(r))}lt(e,r){return this.setLimit("max",e,!1,L.toString(r))}setLimit(e,r,n,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:L.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:L.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:L.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:L.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:L.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:L.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:L.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:L.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:L.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:L.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"&&ae.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)}};wi.create=t=>new wi({checks:[],typeName:R.ZodNumber,coerce:t?.coerce||!1,...G(t)});var _i=class t extends Y{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)!==z.bigint)return this._getInvalidInput(e);let n,i=new ut;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),D(n,{code:I.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),D(n,{code:I.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),D(n,{code:I.not_multiple_of,multipleOf:a.value,message:a.message}),i.dirty()):ae.assertNever(a);return{status:i.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return D(r,{code:I.invalid_type,expected:z.bigint,received:r.parsedType}),J}gte(e,r){return this.setLimit("min",e,!0,L.toString(r))}gt(e,r){return this.setLimit("min",e,!1,L.toString(r))}lte(e,r){return this.setLimit("max",e,!0,L.toString(r))}lt(e,r){return this.setLimit("max",e,!1,L.toString(r))}setLimit(e,r,n,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:L.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:L.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:L.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:L.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:L.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:L.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}};_i.create=t=>new _i({checks:[],typeName:R.ZodBigInt,coerce:t?.coerce??!1,...G(t)});var Si=class extends Y{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==z.boolean){let n=this._getOrReturnCtx(e);return D(n,{code:I.invalid_type,expected:z.boolean,received:n.parsedType}),J}return mt(e.data)}};Si.create=t=>new Si({typeName:R.ZodBoolean,coerce:t?.coerce||!1,...G(t)});var Ei=class t extends Y{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==z.date){let a=this._getOrReturnCtx(e);return D(a,{code:I.invalid_type,expected:z.date,received:a.parsedType}),J}if(Number.isNaN(e.data.getTime())){let a=this._getOrReturnCtx(e);return D(a,{code:I.invalid_date}),J}let n=new ut,i;for(let a of this._def.checks)a.kind==="min"?e.data.getTime()<a.value&&(i=this._getOrReturnCtx(e,i),D(i,{code:I.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),D(i,{code:I.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),n.dirty()):ae.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:L.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:L.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}};Ei.create=t=>new Ei({checks:[],coerce:t?.coerce||!1,typeName:R.ZodDate,...G(t)});var Va=class extends Y{_parse(e){if(this._getType(e)!==z.symbol){let n=this._getOrReturnCtx(e);return D(n,{code:I.invalid_type,expected:z.symbol,received:n.parsedType}),J}return mt(e.data)}};Va.create=t=>new Va({typeName:R.ZodSymbol,...G(t)});var ki=class extends Y{_parse(e){if(this._getType(e)!==z.undefined){let n=this._getOrReturnCtx(e);return D(n,{code:I.invalid_type,expected:z.undefined,received:n.parsedType}),J}return mt(e.data)}};ki.create=t=>new ki({typeName:R.ZodUndefined,...G(t)});var Ti=class extends Y{_parse(e){if(this._getType(e)!==z.null){let n=this._getOrReturnCtx(e);return D(n,{code:I.invalid_type,expected:z.null,received:n.parsedType}),J}return mt(e.data)}};Ti.create=t=>new Ti({typeName:R.ZodNull,...G(t)});var An=class extends Y{constructor(){super(...arguments),this._any=!0}_parse(e){return mt(e.data)}};An.create=t=>new An({typeName:R.ZodAny,...G(t)});var rn=class extends Y{constructor(){super(...arguments),this._unknown=!0}_parse(e){return mt(e.data)}};rn.create=t=>new rn({typeName:R.ZodUnknown,...G(t)});var yr=class extends Y{_parse(e){let r=this._getOrReturnCtx(e);return D(r,{code:I.invalid_type,expected:z.never,received:r.parsedType}),J}};yr.create=t=>new yr({typeName:R.ZodNever,...G(t)});var Ba=class extends Y{_parse(e){if(this._getType(e)!==z.undefined){let n=this._getOrReturnCtx(e);return D(n,{code:I.invalid_type,expected:z.void,received:n.parsedType}),J}return mt(e.data)}};Ba.create=t=>new Ba({typeName:R.ZodVoid,...G(t)});var nn=class t extends Y{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),i=this._def;if(r.parsedType!==z.array)return D(r,{code:I.invalid_type,expected:z.array,received:r.parsedType}),J;if(i.exactLength!==null){let o=r.data.length>i.exactLength.value,s=r.data.length<i.exactLength.value;(o||s)&&(D(r,{code:o?I.too_big:I.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&&(D(r,{code:I.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&&(D(r,{code:I.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 rr(r,o,r.path,s)))).then(o=>ut.mergeArray(n,o));let a=[...r.data].map((o,s)=>i.type._parseSync(new rr(r,o,r.path,s)));return ut.mergeArray(n,a)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:L.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:L.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:L.toString(r)}})}nonempty(e){return this.min(1,e)}};nn.create=(t,e)=>new nn({type:t,minLength:null,maxLength:null,exactLength:null,typeName:R.ZodArray,...G(e)});function qa(t){if(t instanceof Dt){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=Mt.create(qa(n))}return new Dt({...t._def,shape:()=>e})}else return t instanceof nn?new nn({...t._def,type:qa(t.element)}):t instanceof Mt?Mt.create(qa(t.unwrap())):t instanceof zr?zr.create(qa(t.unwrap())):t instanceof Dr?Dr.create(t.items.map(e=>qa(e))):t}var Dt=class t extends Y{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=ae.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==z.object){let l=this._getOrReturnCtx(e);return D(l,{code:I.invalid_type,expected:z.object,received:l.parsedType}),J}let{status:n,ctx:i}=this._processInputParams(e),{shape:a,keys:o}=this._getCached(),s=[];if(!(this._def.catchall instanceof yr&&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 rr(i,p,i.path,l)),alwaysSet:l in i.data})}if(this._def.catchall instanceof yr){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&&(D(i,{code:I.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 rr(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,d=await u.value;l.push({key:p,value:d,alwaysSet:u.alwaysSet})}return l}).then(l=>ut.mergeObjectSync(n,l)):ut.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return L.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:L.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:R.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 ae.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 ae.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return qa(this)}partial(e){let r={};for(let n of ae.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 ae.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let a=this.shape[n];for(;a instanceof Mt;)a=a._def.innerType;r[n]=a}return new t({...this._def,shape:()=>r})}keyof(){return hC(ae.objectKeys(this.shape))}};Dt.create=(t,e)=>new Dt({shape:()=>t,unknownKeys:"strip",catchall:yr.create(),typeName:R.ZodObject,...G(e)});Dt.strictCreate=(t,e)=>new Dt({shape:()=>t,unknownKeys:"strict",catchall:yr.create(),typeName:R.ZodObject,...G(e)});Dt.lazycreate=(t,e)=>new Dt({shape:t,unknownKeys:"strip",catchall:yr.create(),typeName:R.ZodObject,...G(e)});var Ci=class extends Y{_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 Nt(s.ctx.common.issues));return D(r,{code:I.invalid_union,unionErrors:o}),J}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 Nt(c));return D(r,{code:I.invalid_union,unionErrors:s}),J}}get options(){return this._def.options}};Ci.create=(t,e)=>new Ci({options:t,typeName:R.ZodUnion,...G(e)});var tn=t=>t instanceof Ai?tn(t.schema):t instanceof nr?tn(t.innerType()):t instanceof Pi?[t.value]:t instanceof Ii?t.options:t instanceof Ri?ae.objectValues(t.enum):t instanceof Oi?tn(t._def.innerType):t instanceof ki?[void 0]:t instanceof Ti?[null]:t instanceof Mt?[void 0,...tn(t.unwrap())]:t instanceof zr?[null,...tn(t.unwrap())]:t instanceof qs||t instanceof Mi?tn(t.unwrap()):t instanceof Ni?tn(t._def.innerType):[],Ju=class t extends Y{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==z.object)return D(r,{code:I.invalid_type,expected:z.object,received:r.parsedType}),J;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}):(D(r,{code:I.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),J)}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=tn(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:R.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:i,...G(n)})}};function ky(t,e){let r=Mr(t),n=Mr(e);if(t===e)return{valid:!0,data:t};if(r===z.object&&n===z.object){let i=ae.objectKeys(e),a=ae.objectKeys(t).filter(s=>i.indexOf(s)!==-1),o={...t,...e};for(let s of a){let c=ky(t[s],e[s]);if(!c.valid)return{valid:!1};o[s]=c.data}return{valid:!0,data:o}}else if(r===z.array&&n===z.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=ky(o,s);if(!c.valid)return{valid:!1};i.push(c.data)}return{valid:!0,data:i}}else return r===z.date&&n===z.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var $i=class extends Y{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),i=(a,o)=>{if(Uu(a)||Uu(o))return J;let s=ky(a.value,o.value);return s.valid?((Zu(a)||Zu(o))&&r.dirty(),{status:r.value,value:s.data}):(D(n,{code:I.invalid_intersection_types}),J)};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}))}};$i.create=(t,e,r)=>new $i({left:t,right:e,typeName:R.ZodIntersection,...G(r)});var Dr=class t extends Y{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==z.array)return D(n,{code:I.invalid_type,expected:z.array,received:n.parsedType}),J;if(n.data.length<this._def.items.length)return D(n,{code:I.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),J;!this._def.rest&&n.data.length>this._def.items.length&&(D(n,{code:I.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 rr(n,o,n.path,s)):null}).filter(o=>!!o);return n.common.async?Promise.all(a).then(o=>ut.mergeArray(r,o)):ut.mergeArray(r,a)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Dr.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Dr({items:t,typeName:R.ZodTuple,rest:null,...G(e)})};var Hu=class t extends Y{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!==z.object)return D(n,{code:I.invalid_type,expected:z.object,received:n.parsedType}),J;let i=[],a=this._def.keyType,o=this._def.valueType;for(let s in n.data)i.push({key:a._parse(new rr(n,s,n.path,s)),value:o._parse(new rr(n,n.data[s],n.path,s)),alwaysSet:s in n.data});return n.common.async?ut.mergeObjectAsync(r,i):ut.mergeObjectSync(r,i)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof Y?new t({keyType:e,valueType:r,typeName:R.ZodRecord,...G(n)}):new t({keyType:$n.create(),valueType:e,typeName:R.ZodRecord,...G(r)})}},Ua=class extends Y{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!==z.map)return D(n,{code:I.invalid_type,expected:z.map,received:n.parsedType}),J;let i=this._def.keyType,a=this._def.valueType,o=[...n.data.entries()].map(([s,c],l)=>({key:i._parse(new rr(n,s,n.path,[l,"key"])),value:a._parse(new rr(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 J;(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 J;(l.status==="dirty"||u.status==="dirty")&&r.dirty(),s.set(l.value,u.value)}return{status:r.value,value:s}}}};Ua.create=(t,e,r)=>new Ua({valueType:e,keyType:t,typeName:R.ZodMap,...G(r)});var Za=class t extends Y{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==z.set)return D(n,{code:I.invalid_type,expected:z.set,received:n.parsedType}),J;let i=this._def;i.minSize!==null&&n.data.size<i.minSize.value&&(D(n,{code:I.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&&(D(n,{code:I.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 J;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 rr(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:L.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:L.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};Za.create=(t,e)=>new Za({valueType:t,minSize:null,maxSize:null,typeName:R.ZodSet,...G(e)});var Ku=class t extends Y{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==z.function)return D(r,{code:I.invalid_type,expected:z.function,received:r.parsedType}),J;function n(s,c){return Ls({data:s,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Fa(),en].filter(l=>!!l),issueData:{code:I.invalid_arguments,argumentsError:c}})}function i(s,c){return Ls({data:s,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Fa(),en].filter(l=>!!l),issueData:{code:I.invalid_return_type,returnTypeError:c}})}let a={errorMap:r.common.contextualErrorMap},o=r.data;if(this._def.returns instanceof Pn){let s=this;return mt(async function(...c){let l=new Nt([]),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 mt(function(...c){let l=s._def.args.safeParse(c,a);if(!l.success)throw new Nt([n(c,l.error)]);let u=Reflect.apply(o,this,l.data),p=s._def.returns.safeParse(u,a);if(!p.success)throw new Nt([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:Dr.create(e).rest(rn.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||Dr.create([]).rest(rn.create()),returns:r||rn.create(),typeName:R.ZodFunction,...G(n)})}},Ai=class extends Y{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})}};Ai.create=(t,e)=>new Ai({getter:t,typeName:R.ZodLazy,...G(e)});var Pi=class extends Y{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return D(r,{received:r.data,code:I.invalid_literal,expected:this._def.value}),J}return{status:"valid",value:e.data}}get value(){return this._def.value}};Pi.create=(t,e)=>new Pi({value:t,typeName:R.ZodLiteral,...G(e)});function hC(t,e){return new Ii({values:t,typeName:R.ZodEnum,...G(e)})}var Ii=class t extends Y{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return D(r,{expected:ae.joinValues(n),received:r.parsedType,code:I.invalid_type}),J}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 D(r,{received:r.data,code:I.invalid_enum_value,options:n}),J}return mt(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})}};Ii.create=hC;var Ri=class extends Y{_parse(e){let r=ae.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==z.string&&n.parsedType!==z.number){let i=ae.objectValues(r);return D(n,{expected:ae.joinValues(i),received:n.parsedType,code:I.invalid_type}),J}if(this._cache||(this._cache=new Set(ae.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let i=ae.objectValues(r);return D(n,{received:n.data,code:I.invalid_enum_value,options:i}),J}return mt(e.data)}get enum(){return this._def.values}};Ri.create=(t,e)=>new Ri({values:t,typeName:R.ZodNativeEnum,...G(e)});var Pn=class extends Y{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==z.promise&&r.common.async===!1)return D(r,{code:I.invalid_type,expected:z.promise,received:r.parsedType}),J;let n=r.parsedType===z.promise?r.data:Promise.resolve(r.data);return mt(n.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Pn.create=(t,e)=>new Pn({type:t,typeName:R.ZodPromise,...G(e)});var nr=class extends Y{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===R.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=>{D(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 J;let c=await this._def.schema._parseAsync({data:s,path:n.path,parent:n});return c.status==="aborted"?J:c.status==="dirty"?xi(c.value):r.value==="dirty"?xi(c.value):c});{if(r.value==="aborted")return J;let s=this._def.schema._parseSync({data:o,path:n.path,parent:n});return s.status==="aborted"?J:s.status==="dirty"?xi(s.value):r.value==="dirty"?xi(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"?J:(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"?J:(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(!Cn(o))return J;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=>Cn(o)?Promise.resolve(i.transform(o.value,a)).then(s=>({status:r.value,value:s})):J);ae.assertNever(i)}};nr.create=(t,e,r)=>new nr({schema:t,typeName:R.ZodEffects,effect:e,...G(r)});nr.createWithPreprocess=(t,e,r)=>new nr({schema:e,effect:{type:"preprocess",transform:t},typeName:R.ZodEffects,...G(r)});var Mt=class extends Y{_parse(e){return this._getType(e)===z.undefined?mt(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Mt.create=(t,e)=>new Mt({innerType:t,typeName:R.ZodOptional,...G(e)});var zr=class extends Y{_parse(e){return this._getType(e)===z.null?mt(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};zr.create=(t,e)=>new zr({innerType:t,typeName:R.ZodNullable,...G(e)});var Oi=class extends Y{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===z.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};Oi.create=(t,e)=>new Oi({innerType:t,typeName:R.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...G(e)});var Ni=class extends Y{_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 La(i)?i.then(a=>({status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new Nt(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Nt(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Ni.create=(t,e)=>new Ni({innerType:t,typeName:R.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...G(e)});var Ja=class extends Y{_parse(e){if(this._getType(e)!==z.nan){let n=this._getOrReturnCtx(e);return D(n,{code:I.invalid_type,expected:z.nan,received:n.parsedType}),J}return{status:"valid",value:e.data}}};Ja.create=t=>new Ja({typeName:R.ZodNaN,...G(t)});var aq=Symbol("zod_brand"),qs=class extends Y{_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}},Vs=class t extends Y{_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"?J:a.status==="dirty"?(r.dirty(),xi(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"?J: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:R.ZodPipeline})}},Mi=class extends Y{_parse(e){let r=this._def.innerType._parse(e),n=i=>(Cn(i)&&(i.value=Object.freeze(i.value)),i);return La(r)?r.then(i=>n(i)):n(r)}unwrap(){return this._def.innerType}};Mi.create=(t,e)=>new Mi({innerType:t,typeName:R.ZodReadonly,...G(e)});function pC(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function gC(t,e={},r){return t?An.create().superRefine((n,i)=>{let a=t(n);if(a instanceof Promise)return a.then(o=>{if(!o){let s=pC(e,n),c=s.fatal??r??!0;i.addIssue({code:"custom",...s,fatal:c})}});if(!a){let o=pC(e,n),s=o.fatal??r??!0;i.addIssue({code:"custom",...o,fatal:s})}}):An.create()}var oq={object:Dt.lazycreate},R;(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"})(R||(R={}));var sq=(t,e={message:`Input not instance of ${t.name}`})=>gC(r=>r instanceof t,e),yC=$n.create,bC=wi.create,cq=Ja.create,lq=_i.create,vC=Si.create,uq=Ei.create,pq=Va.create,dq=ki.create,fq=Ti.create,mq=An.create,hq=rn.create,gq=yr.create,yq=Ba.create,bq=nn.create,Ty=Dt.create,vq=Dt.strictCreate,xq=Ci.create,wq=Ju.create,_q=$i.create,Sq=Dr.create,Eq=Hu.create,kq=Ua.create,Tq=Za.create,Cq=Ku.create,$q=Ai.create,Aq=Pi.create,Pq=Ii.create,Iq=Ri.create,Rq=Pn.create,Oq=nr.create,Nq=Mt.create,Mq=zr.create,Dq=nr.createWithPreprocess,zq=Vs.create,jq=()=>yC().optional(),Fq=()=>bC().optional(),Lq=()=>vC().optional(),qq={string:t=>$n.create({...t,coerce:!0}),number:t=>wi.create({...t,coerce:!0}),boolean:t=>Si.create({...t,coerce:!0}),bigint:t=>_i.create({...t,coerce:!0}),date:t=>Ei.create({...t,coerce:!0})};var Vq=J;var Uq=$("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");Se.init(t,e),t.def=e,t.parse=(r,n)=>Cd(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>Qn(t,r,n),t.parseAsync=async(r,n)=>Ad(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Yn(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)=>Zt(t,r,n),t.brand=()=>t,t.register=(r,n)=>(r.add(t,n),t)});var Zq=$("ZodMiniObject",(t,e)=>{qc.init(t,e),Uq.init(t,e),oe.defineLazy(t,"shape",()=>e.shape)});function Cy(t,e){let r={type:"object",get shape(){return oe.assignProp(this,"shape",{...t}),this.shape},...oe.normalizeParams(e)};return new Zq(r)}function ir(t){return!!t._zod}function Di(t){let e=Object.values(t);if(e.length===0)return Cy({});let r=e.every(ir),n=e.every(i=>!ir(i));if(r)return Cy(t);if(n)return Ty(t);throw new Error("Mixed Zod versions detected in object shape.")}function In(t,e){return ir(t)?Qn(t,e):t.safeParse(e)}async function Wu(t,e){return ir(t)?await Yn(t,e):await t.safeParseAsync(e)}function Rn(t){if(!t)return;let e;if(ir(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function Ha(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 Di(t)}}if(ir(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 Gu(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 xC(t){return t.description}function wC(t){if(ir(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function Xu(t){if(ir(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 On(t){return t==="completed"||t==="failed"||t==="cancelled"}var SC=Symbol("Let zodToJsonSchema decide on which parser to use");var _C={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"},EC=t=>typeof t=="string"?{..._C,name:t}:{..._C,...t};var kC=t=>{let e=EC(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 $y(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function ce(t,e,r,n,i){t[e]=r,$y(t,e,n,i)}var Qu=(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 Le(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?Qu(e,t.currentPath):e.join("/")}}function TC(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==R.ZodAny&&(r.items=H(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&ce(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&ce(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(ce(r,"minItems",t.exactLength.value,t.exactLength.message,e),ce(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function CC(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?ce(r,"minimum",n.value,n.message,e):ce(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ce(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ce(r,"maximum",n.value,n.message,e):ce(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ce(r,"maximum",n.value,n.message,e));break;case"multipleOf":ce(r,"multipleOf",n.value,n.message,e);break}return r}function $C(){return{type:"boolean"}}function Yu(t,e){return H(t.type._def,e)}var AC=(t,e)=>H(t.innerType._def,e);function Ay(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((i,a)=>Ay(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 Hq(t,e)}}var Hq=(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":ce(r,"minimum",n.value,n.message,e);break;case"max":ce(r,"maximum",n.value,n.message,e);break}return r};function PC(t,e){return{...H(t.innerType._def,e),default:t.defaultValue()}}function IC(t,e){return e.effectStrategy==="input"?H(t.schema._def,e):Le(e)}function RC(t){return{type:"string",enum:Array.from(t.values)}}var Kq=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function OC(t,e){let r=[H(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),H(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(Kq(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 NC(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 Py,br={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:()=>(Py===void 0&&(Py=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Py),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 ep(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":ce(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":ce(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":vr(r,"email",n.message,e);break;case"format:idn-email":vr(r,"idn-email",n.message,e);break;case"pattern:zod":St(r,br.email,n.message,e);break}break;case"url":vr(r,"uri",n.message,e);break;case"uuid":vr(r,"uuid",n.message,e);break;case"regex":St(r,n.regex,n.message,e);break;case"cuid":St(r,br.cuid,n.message,e);break;case"cuid2":St(r,br.cuid2,n.message,e);break;case"startsWith":St(r,RegExp(`^${Iy(n.value,e)}`),n.message,e);break;case"endsWith":St(r,RegExp(`${Iy(n.value,e)}$`),n.message,e);break;case"datetime":vr(r,"date-time",n.message,e);break;case"date":vr(r,"date",n.message,e);break;case"time":vr(r,"time",n.message,e);break;case"duration":vr(r,"duration",n.message,e);break;case"length":ce(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),ce(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{St(r,RegExp(Iy(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&vr(r,"ipv4",n.message,e),n.version!=="v4"&&vr(r,"ipv6",n.message,e);break}case"base64url":St(r,br.base64url,n.message,e);break;case"jwt":St(r,br.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&St(r,br.ipv4Cidr,n.message,e),n.version!=="v4"&&St(r,br.ipv6Cidr,n.message,e);break}case"emoji":St(r,br.emoji(),n.message,e);break;case"ulid":{St(r,br.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{vr(r,"binary",n.message,e);break}case"contentEncoding:base64":{ce(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{St(r,br.base64,n.message,e);break}}break}case"nanoid":St(r,br.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function Iy(t,e){return e.patternStrategy==="escape"?Gq(t):t}var Wq=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Gq(t){let e="";for(let r=0;r<t.length;r++)Wq.has(t[r])||(e+="\\"),e+=t[r];return e}function vr(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}}})):ce(t,"format",e,r,n)}function St(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:MC(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):ce(t,"pattern",MC(e,n),r,n)}function MC(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
|
|
125
125
|
]))`;continue}else if(n[c]==="$"){i+=`($|(?=[\r
|
|
126
126
|
]))`;continue}}if(r.s&&n[c]==="."){i+=o?`${n[c]}\r
|
|
127
127
|
`:`[${n[c]}\r
|
|
128
128
|
]`;continue}i+=n[c],n[c]==="\\"?a=!0:o&&n[c]==="]"?o=!1:!o&&n[c]==="["&&(o=!0)}try{new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return i}function tp(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===R.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,i)=>({...n,[i]:H(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",i]})??Le(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:H(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===R.ZodString&&t.keyType._def.checks?.length){let{type:n,...i}=ep(t.keyType._def,e);return{...r,propertyNames:i}}else{if(t.keyType?._def.typeName===R.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===R.ZodBranded&&t.keyType._def.type._def.typeName===R.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...i}=Yu(t.keyType._def,e);return{...r,propertyNames:i}}}return r}function DC(t,e){if(e.mapStrategy==="record")return tp(t,e);let r=H(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Le(e),n=H(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Le(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function zC(t){let e=t.values,n=Object.keys(t.values).filter(a=>typeof e[e[a]]!="number").map(a=>e[a]),i=Array.from(new Set(n.map(a=>typeof a)));return{type:i.length===1?i[0]==="string"?"string":"number":["string","number"],enum:n}}function jC(t){return t.target==="openAi"?void 0:{not:Le({...t,currentPath:[...t.currentPath,"not"]})}}function FC(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Bs={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function qC(t,e){if(e.target==="openApi3")return LC(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in Bs&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((i,a)=>{let o=Bs[a._def.typeName];return o&&!i.includes(o)?[...i,o]:i},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((i,a)=>{let o=typeof a._def.value;switch(o){case"string":case"number":case"boolean":return[...i,o];case"bigint":return[...i,"integer"];case"object":if(a._def.value===null)return[...i,"null"];case"symbol":case"undefined":case"function":default:return i}},[]);if(n.length===r.length){let i=n.filter((a,o,s)=>s.indexOf(a)===o);return{type:i.length>1?i:i[0],enum:r.reduce((a,o)=>a.includes(o._def.value)?a:[...a,o._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,i)=>[...n,...i._def.values.filter(a=>!n.includes(a))],[])};return LC(t,e)}var LC=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,i)=>H(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${i}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function VC(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:Bs[t.innerType._def.typeName],nullable:!0}:{type:[Bs[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=H(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=H(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function BC(t,e){let r={type:"number"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"int":r.type="integer",$y(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?ce(r,"minimum",n.value,n.message,e):ce(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ce(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ce(r,"maximum",n.value,n.message,e):ce(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ce(r,"maximum",n.value,n.message,e));break;case"multipleOf":ce(r,"multipleOf",n.value,n.message,e);break}return r}function UC(t,e){let r=e.target==="openAi",n={type:"object",properties:{}},i=[],a=t.shape();for(let s in a){let c=a[s];if(c===void 0||c._def===void 0)continue;let l=Qq(c);l&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),l=!1);let u=H(c._def,{...e,currentPath:[...e.currentPath,"properties",s],propertyPath:[...e.currentPath,"properties",s]});u!==void 0&&(n.properties[s]=u,l||i.push(s))}i.length&&(n.required=i);let o=Xq(t,e);return o!==void 0&&(n.additionalProperties=o),n}function Xq(t,e){if(t.catchall._def.typeName!=="ZodNever")return H(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function Qq(t){try{return t.isOptional()}catch{return!0}}var ZC=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return H(t.innerType._def,e);let r=H(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Le(e)},r]}:Le(e)};var JC=(t,e)=>{if(e.pipeStrategy==="input")return H(t.in._def,e);if(e.pipeStrategy==="output")return H(t.out._def,e);let r=H(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=H(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(i=>i!==void 0)}};function HC(t,e){return H(t.type._def,e)}function KC(t,e){let n={type:"array",uniqueItems:!0,items:H(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&ce(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&ce(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function WC(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>H(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:H(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>H(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function GC(t){return{not:Le(t)}}function XC(t){return Le(t)}var QC=(t,e)=>H(t.innerType._def,e);var YC=(t,e,r)=>{switch(e){case R.ZodString:return ep(t,r);case R.ZodNumber:return BC(t,r);case R.ZodObject:return UC(t,r);case R.ZodBigInt:return CC(t,r);case R.ZodBoolean:return $C();case R.ZodDate:return Ay(t,r);case R.ZodUndefined:return GC(r);case R.ZodNull:return FC(r);case R.ZodArray:return TC(t,r);case R.ZodUnion:case R.ZodDiscriminatedUnion:return qC(t,r);case R.ZodIntersection:return OC(t,r);case R.ZodTuple:return WC(t,r);case R.ZodRecord:return tp(t,r);case R.ZodLiteral:return NC(t,r);case R.ZodEnum:return RC(t);case R.ZodNativeEnum:return zC(t);case R.ZodNullable:return VC(t,r);case R.ZodOptional:return ZC(t,r);case R.ZodMap:return DC(t,r);case R.ZodSet:return KC(t,r);case R.ZodLazy:return()=>t.getter()._def;case R.ZodPromise:return HC(t,r);case R.ZodNaN:case R.ZodNever:return jC(r);case R.ZodEffects:return IC(t,r);case R.ZodAny:return Le(r);case R.ZodUnknown:return XC(r);case R.ZodDefault:return PC(t,r);case R.ZodBranded:return Yu(t,r);case R.ZodReadonly:return QC(t,r);case R.ZodCatch:return AC(t,r);case R.ZodPipeline:return JC(t,r);case R.ZodFunction:case R.ZodVoid:case R.ZodSymbol:return;default:return(n=>{})(e)}};function H(t,e,r=!1){let n=e.seen.get(t);if(e.override){let s=e.override?.(t,e,n,r);if(s!==SC)return s}if(n&&!r){let s=Yq(n,e);if(s!==void 0)return s}let i={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,i);let a=YC(t,t.typeName,e),o=typeof a=="function"?H(a(),e):a;if(o&&eV(t,e,o),e.postProcess){let s=e.postProcess(o,t,e);return i.jsonSchema=o,s}return i.jsonSchema=o,o}var Yq=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Qu(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),Le(e)):e.$refStrategy==="seen"?Le(e):void 0}},eV=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var Ry=(t,e)=>{let r=kC(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[l,u])=>({...c,[l]:H(u._def,{...r,currentPath:[...r.basePath,r.definitionPath,l]},!0)??Le(r)}),{}):void 0,i=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,a=H(t._def,i===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,i]},!1)??Le(r),o=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;o!==void 0&&(a.title=o),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let s=i===void 0?n?{...a,[r.definitionPath]:n}:a:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,i].join("/"),[r.definitionPath]:{...n,[i]:a}};return r.target==="jsonSchema7"?s.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(s.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in s||"oneOf"in s||"allOf"in s||"type"in s&&Array.isArray(s.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),s};function tV(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function Oy(t,e){return ir(t)?um(t,{target:tV(e?.target),io:e?.pipeStrategy??"input"}):Ry(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function Ny(t){let r=Rn(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Xu(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function My(t,e){let r=In(t,e);if(!r.success)throw r.error;return r.data}var rV=6e4,rp=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(nl,r=>{this._oncancel(r)}),this.setNotificationHandler(al,r=>{this._onprogress(r)}),this.setRequestHandler(il,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(ol,async(r,n)=>{let i=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!i)throw new q(U.InvalidParams,"Failed to retrieve task: Task not found");return{...i}}),this.setRequestHandler(cl,async(r,n)=>{let i=async()=>{let a=r.params.taskId;if(this._taskMessageQueue){let s;for(;s=await this._taskMessageQueue.dequeue(a,n.sessionId);){if(s.type==="response"||s.type==="error"){let c=s.message,l=c.id,u=this._requestResolvers.get(l);if(u)if(this._requestResolvers.delete(l),s.type==="response")u(c);else{let p=c,d=new q(p.error.code,p.error.message,p.error.data);u(d)}else{let p=s.type==="response"?"Response":"Error";this._onerror(new Error(`${p} handler missing for request ${l}`))}continue}await this._transport?.send(s.message,{relatedRequestId:n.requestId})}}let o=await this._taskStore.getTask(a,n.sessionId);if(!o)throw new q(U.InvalidParams,`Task not found: ${a}`);if(!On(o.status))return await this._waitForTaskUpdate(a,n.signal),await i();if(On(o.status)){let s=await this._taskStore.getTaskResult(a,n.sessionId);return this._clearTaskQueue(a),{...s,_meta:{...s._meta,[hn]:{taskId:a}}}}return await i()};return await i()}),this.setRequestHandler(ll,async(r,n)=>{try{let{tasks:i,nextCursor:a}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:i,nextCursor:a,_meta:{}}}catch(i){throw new q(U.InvalidParams,`Failed to list tasks: ${i instanceof Error?i.message:String(i)}`)}}),this.setRequestHandler(pl,async(r,n)=>{try{let i=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!i)throw new q(U.InvalidParams,`Task not found: ${r.params.taskId}`);if(On(i.status))throw new q(U.InvalidParams,`Cannot cancel task in terminal status: ${i.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let a=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!a)throw new q(U.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...a}}catch(i){throw i instanceof q?i:new q(U.InvalidRequest,`Failed to cancel task: ${i instanceof Error?i.message:String(i)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,i,a=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(i,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:a,onTimeout:i})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),q.fromError(U.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=a=>{n?.(a),this._onerror(a)};let i=this._transport?.onmessage;this._transport.onmessage=(a,o)=>{i?.(a,o),Lo(a)||X0(a)?this._onresponse(a):_m(a)?this._onrequest(a,o):G0(a)?this._onnotification(a):this._onerror(new Error(`Unknown message type: ${JSON.stringify(a)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=q.fromError(U.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,i=this._transport,a=e.params?._meta?.[hn]?.taskId;if(n===void 0){let u={jsonrpc:"2.0",id:e.id,error:{code:U.MethodNotFound,message:"Method not found"}};a&&this._taskMessageQueue?this._enqueueTaskMessage(a,{type:"error",message:u,timestamp:Date.now()},i?.sessionId).catch(p=>this._onerror(new Error(`Failed to enqueue error response: ${p}`))):i?.send(u).catch(p=>this._onerror(new Error(`Failed to send an error response: ${p}`)));return}let o=new AbortController;this._requestHandlerAbortControllers.set(e.id,o);let s=H0(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,i?.sessionId):void 0,l={signal:o.signal,sessionId:i?.sessionId,_meta:e.params?._meta,sendNotification:async u=>{if(o.signal.aborted)return;let p={relatedRequestId:e.id};a&&(p.relatedTask={taskId:a}),await this.notification(u,p)},sendRequest:async(u,p,d)=>{if(o.signal.aborted)throw new q(U.ConnectionClosed,"Request was cancelled");let h={...d,relatedRequestId:e.id};a&&!h.relatedTask&&(h.relatedTask={taskId:a});let m=h.relatedTask?.taskId??a;return m&&c&&await c.updateTaskStatus(m,"input_required"),await this.request(u,p,h)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:a,taskStore:c,taskRequestedTtl:s?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{s&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,l)).then(async u=>{if(o.signal.aborted)return;let p={result:u,jsonrpc:"2.0",id:e.id};a&&this._taskMessageQueue?await this._enqueueTaskMessage(a,{type:"response",message:p,timestamp:Date.now()},i?.sessionId):await i?.send(p)},async u=>{if(o.signal.aborted)return;let p={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(u.code)?u.code:U.InternalError,message:u.message??"Internal error",...u.data!==void 0&&{data:u.data}}};a&&this._taskMessageQueue?await this._enqueueTaskMessage(a,{type:"error",message:p,timestamp:Date.now()},i?.sessionId):await i?.send(p)}).catch(u=>this._onerror(new Error(`Failed to send response: ${u}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===o&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,i=Number(r),a=this._progressHandlers.get(i);if(!a){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let o=this._responseHandlers.get(i),s=this._timeoutInfo.get(i);if(s&&o&&s.resetTimeoutOnProgress)try{this._resetTimeout(i)}catch(c){this._responseHandlers.delete(i),this._progressHandlers.delete(i),this._cleanupTimeout(i),o(c);return}a(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),Lo(e))n(e);else{let o=new q(e.error.code,e.error.message,e.error.data);n(o)}return}let i=this._responseHandlers.get(r);if(i===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let a=!1;if(Lo(e)&&e.result&&typeof e.result=="object"){let o=e.result;if(o.task&&typeof o.task=="object"){let s=o.task;typeof s.taskId=="string"&&(a=!0,this._taskProgressTokens.set(s.taskId,r))}}if(a||this._progressHandlers.delete(r),Lo(e))i(e);else{let o=q.fromError(e.error.code,e.error.message,e.error.data);i(o)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){let{task:i}=n??{};if(!i){try{yield{type:"result",result:await this.request(e,r,n)}}catch(o){yield{type:"error",error:o instanceof q?o:new q(U.InternalError,String(o))}}return}let a;try{let o=await this.request(e,sa,n);if(o.task)a=o.task.taskId,yield{type:"taskCreated",task:o.task};else throw new q(U.InternalError,"Task creation did not return a task");for(;;){let s=await this.getTask({taskId:a},n);if(yield{type:"taskStatus",task:s},On(s.status)){s.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:a},r,n)}:s.status==="failed"?yield{type:"error",error:new q(U.InternalError,`Task ${a} failed`)}:s.status==="cancelled"&&(yield{type:"error",error:new q(U.InternalError,`Task ${a} was cancelled`)});return}if(s.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:a},r,n)};return}let c=s.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(l=>setTimeout(l,c)),n?.signal?.throwIfAborted()}}catch(o){yield{type:"error",error:o instanceof q?o:new q(U.InternalError,String(o))}}}request(e,r,n){let{relatedRequestId:i,resumptionToken:a,onresumptiontoken:o,task:s,relatedTask:c}=n??{};return new Promise((l,u)=>{let p=b=>{u(b)};if(!this._transport){p(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),s&&this.assertTaskCapability(e.method)}catch(b){p(b);return}n?.signal?.throwIfAborted();let d=this._requestMessageId++,h={...e,jsonrpc:"2.0",id:d};n?.onprogress&&(this._progressHandlers.set(d,n.onprogress),h.params={...e.params,_meta:{...e.params?._meta||{},progressToken:d}}),s&&(h.params={...h.params,task:s}),c&&(h.params={...h.params,_meta:{...h.params?._meta||{},[hn]:c}});let m=b=>{this._responseHandlers.delete(d),this._progressHandlers.delete(d),this._cleanupTimeout(d),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:d,reason:String(b)}},{relatedRequestId:i,resumptionToken:a,onresumptiontoken:o}).catch(w=>this._onerror(new Error(`Failed to send cancellation: ${w}`)));let v=b instanceof q?b:new q(U.RequestTimeout,String(b));u(v)};this._responseHandlers.set(d,b=>{if(!n?.signal?.aborted){if(b instanceof Error)return u(b);try{let v=In(r,b.result);v.success?l(v.data):u(v.error)}catch(v){u(v)}}}),n?.signal?.addEventListener("abort",()=>{m(n?.signal?.reason)});let y=n?.timeout??rV,g=()=>m(q.fromError(U.RequestTimeout,"Request timed out",{timeout:y}));this._setupTimeout(d,y,n?.maxTotalTimeout,g,n?.resetTimeoutOnProgress??!1);let x=c?.taskId;if(x){let b=v=>{let w=this._responseHandlers.get(d);w?w(v):this._onerror(new Error(`Response handler missing for side-channeled request ${d}`))};this._requestResolvers.set(d,b),this._enqueueTaskMessage(x,{type:"request",message:h,timestamp:Date.now()}).catch(v=>{this._cleanupTimeout(d),u(v)})}else this._transport.send(h,{relatedRequestId:i,resumptionToken:a,onresumptiontoken:o}).catch(b=>{this._cleanupTimeout(d),u(b)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},sl,r)}async getTaskResult(e,r,n){return this.request({method:"tasks/result",params:e},r,n)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},ul,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},Y0,r)}async notification(e,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let n=r?.relatedTask?.taskId;if(n){let s={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[hn]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:s,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let s={...e,jsonrpc:"2.0"};r?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[hn]:r.relatedTask}}}),this._transport?.send(s,r).catch(c=>this._onerror(c))});return}let o={...e,jsonrpc:"2.0"};r?.relatedTask&&(o={...o,params:{...o.params,_meta:{...o.params?._meta||{},[hn]:r.relatedTask}}}),await this._transport.send(o,r)}setRequestHandler(e,r){let n=Ny(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(i,a)=>{let o=My(e,i);return Promise.resolve(r(o,a))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){let n=Ny(e);this._notificationHandlers.set(n,i=>{let a=My(e,i);return Promise.resolve(r(a))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let i=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,i)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let i of n)if(i.type==="request"&&_m(i.message)){let a=i.message.id,o=this._requestResolvers.get(a);o?(o(new q(U.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(a)):this._onerror(new Error(`Resolver missing for request ${a} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let i=await this._taskStore?.getTask(e);i?.pollInterval&&(n=i.pollInterval)}catch{}return new Promise((i,a)=>{if(r.aborted){a(new q(U.InvalidRequest,"Request cancelled"));return}let o=setTimeout(i,n);r.addEventListener("abort",()=>{clearTimeout(o),a(new q(U.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async i=>{if(!e)throw new Error("No request provided");return await n.createTask(i,e.id,{method:e.method,params:e.params},r)},getTask:async i=>{let a=await n.getTask(i,r);if(!a)throw new q(U.InvalidParams,"Failed to retrieve task: Task not found");return a},storeTaskResult:async(i,a,o)=>{await n.storeTaskResult(i,a,o,r);let s=await n.getTask(i,r);if(s){let c=Zo.parse({method:"notifications/tasks/status",params:s});await this.notification(c),On(s.status)&&this._cleanupTaskProgressHandler(i)}},getTaskResult:i=>n.getTaskResult(i,r),updateTaskStatus:async(i,a,o)=>{let s=await n.getTask(i,r);if(!s)throw new q(U.InvalidParams,`Task "${i}" not found - it may have been cleaned up`);if(On(s.status))throw new q(U.InvalidParams,`Cannot update task "${i}" from terminal status "${s.status}" to "${a}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(i,a,o,r);let c=await n.getTask(i,r);if(c){let l=Zo.parse({method:"notifications/tasks/status",params:c});await this.notification(l),On(c.status)&&this._cleanupTaskProgressHandler(i)}},listTasks:i=>n.listTasks(i,r)}}};function e4(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function t4(t,e){let r={...t};for(let n in e){let i=n,a=e[i];if(a===void 0)continue;let o=r[i];e4(o)&&e4(a)?r[i]={...o,...a}:r[i]=a}return r}var q$=tt(xv(),1),V$=tt(L$(),1);function HJ(){let t=new q$.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,V$.default)(t),t}var jp=class{constructor(e){this._ajv=e??HJ()}getValidator(e){let r="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}};var Fp=class{constructor(e){this._server=e}requestStream(e,r,n){return this._server.requestStream(e,r,n)}createMessageStream(e,r){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let i=e.messages[e.messages.length-1],a=Array.isArray(i.content)?i.content:[i.content],o=a.some(u=>u.type==="tool_result"),s=e.messages.length>1?e.messages[e.messages.length-2]:void 0,c=s?Array.isArray(s.content)?s.content:[s.content]:[],l=c.some(u=>u.type==="tool_use");if(o){if(a.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!l)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(l){let u=new Set(c.filter(d=>d.type==="tool_use").map(d=>d.id)),p=new Set(a.filter(d=>d.type==="tool_result").map(d=>d.toolUseId));if(u.size!==p.size||![...u].every(d=>p.has(d)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},Ko,r)}elicitInputStream(e,r){let n=this._server.getClientCapabilities(),i=e.mode??"form";switch(i){case"url":{if(!n?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!n?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let a=i==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:a},ua,r)}async getTask(e,r){return this._server.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._server.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._server.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._server.cancelTask({taskId:e},r)}};function B$(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${e})`);break;default:break}}function U$(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var Lp=class extends rp{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Ho.options.map((n,i)=>[n,i])),this.isMessageIgnored=(n,i)=>{let a=this._loggingLevels.get(i);return a?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(a):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new jp,this.setRequestHandler(km,n=>this._oninitialize(n)),this.setNotificationHandler(Tm,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Om,async(n,i)=>{let a=i.sessionId||i.requestInfo?.headers["mcp-session-id"]||void 0,{level:o}=n.params,s=Ho.safeParse(o);return s.success&&this._loggingLevels.set(a,s.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Fp(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=t4(this._capabilities,e)}setRequestHandler(e,r){let i=Rn(e)?.method;if(!i)throw new Error("Schema is missing a method literal");let a;if(ir(i)){let s=i;a=s._zod?.def?.value??s.value}else{let s=i;a=s._def?.value??s.value}if(typeof a!="string")throw new Error("Schema method literal must be a string");if(a==="tools/call"){let s=async(c,l)=>{let u=In(la,c);if(!u.success){let m=u.error instanceof Error?u.error.message:String(u.error);throw new q(U.InvalidParams,`Invalid tools/call request: ${m}`)}let{params:p}=u.data,d=await Promise.resolve(r(c,l));if(p.task){let m=In(sa,d);if(!m.success){let y=m.error instanceof Error?m.error.message:String(m.error);throw new q(U.InvalidParams,`Invalid task creation result: ${y}`)}return m.data}let h=In(bl,d);if(!h.success){let m=h.error instanceof Error?h.error.message:String(h.error);throw new q(U.InvalidParams,`Invalid tools/call result: ${m}`)}return h.data};return super.setRequestHandler(e,s)}return super.setRequestHandler(e,r)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){U$(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&B$(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let r=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:U0.includes(r)?r:xm,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},rl)}async createMessage(e,r){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let n=e.messages[e.messages.length-1],i=Array.isArray(n.content)?n.content:[n.content],a=i.some(l=>l.type==="tool_result"),o=e.messages.length>1?e.messages[e.messages.length-2]:void 0,s=o?Array.isArray(o.content)?o.content:[o.content]:[],c=s.some(l=>l.type==="tool_use");if(a){if(i.some(l=>l.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let l=new Set(s.filter(p=>p.type==="tool_use").map(p=>p.id)),u=new Set(i.filter(p=>p.type==="tool_result").map(p=>p.toolUseId));if(l.size!==u.size||![...l].every(p=>u.has(p)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},Nm,r):this.request({method:"sampling/createMessage",params:e},Ko,r)}async elicitInput(e,r){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let i=e;return this.request({method:"elicitation/create",params:i},ua,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let i=e.mode==="form"?e:{...e,mode:"form"},a=await this.request({method:"elicitation/create",params:i},ua,r);if(a.action==="accept"&&a.content&&i.requestedSchema)try{let s=this._jsonSchemaValidator.getValidator(i.requestedSchema)(a.content);if(!s.valid)throw new q(U.InvalidParams,`Elicitation response content does not match requested schema: ${s.errorMessage}`)}catch(o){throw o instanceof q?o:new q(U.InternalError,`Error validating elicitation response: ${o instanceof Error?o.message:String(o)}`)}return a}}}createElicitationCompletionNotifier(e,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},r)}async listRoots(e,r){return this.request({method:"roots/list",params:e},Mm,r)}async sendLoggingMessage(e,r){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,r))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};var J$=Symbol.for("mcp.completable");function $v(t){return!!t&&typeof t=="object"&&J$ in t}function H$(t){return t[J$]?.complete}var Z$;(function(t){t.Completable="McpCompletable"})(Z$||(Z$={}));var qp=class t{static isTemplate(e){return/\{[^}\s]+\}/.test(e)}static validateLength(e,r,n){if(e.length>r)throw new Error(`${n} exceeds maximum length of ${r} characters (got ${e.length})`)}get variableNames(){return this.parts.flatMap(e=>typeof e=="string"?[]:e.names)}constructor(e){t.validateLength(e,1e6,"Template"),this.template=e,this.parts=this.parse(e)}toString(){return this.template}parse(e){let r=[],n="",i=0,a=0;for(;i<e.length;)if(e[i]==="{"){n&&(r.push(n),n="");let o=e.indexOf("}",i);if(o===-1)throw new Error("Unclosed template expression");if(a++,a>1e4)throw new Error("Template contains too many expressions (max 10000)");let s=e.slice(i+1,o),c=this.getOperator(s),l=s.includes("*"),u=this.getNames(s),p=u[0];for(let d of u)t.validateLength(d,1e6,"Variable name");r.push({name:p,operator:c,names:u,exploded:l}),i=o+1}else n+=e[i],i++;return n&&r.push(n),r}getOperator(e){return["+","#",".","/","?","&"].find(n=>e.startsWith(n))||""}getNames(e){let r=this.getOperator(e);return e.slice(r.length).split(",").map(n=>n.replace("*","").trim()).filter(n=>n.length>0)}encodeValue(e,r){return t.validateLength(e,1e6,"Variable value"),r==="+"||r==="#"?encodeURI(e):encodeURIComponent(e)}expandPart(e,r){if(e.operator==="?"||e.operator==="&"){let o=e.names.map(c=>{let l=r[c];if(l===void 0)return"";let u=Array.isArray(l)?l.map(p=>this.encodeValue(p,e.operator)).join(","):this.encodeValue(l.toString(),e.operator);return`${c}=${u}`}).filter(c=>c.length>0);return o.length===0?"":(e.operator==="?"?"?":"&")+o.join("&")}if(e.names.length>1){let o=e.names.map(s=>r[s]).filter(s=>s!==void 0);return o.length===0?"":o.map(s=>Array.isArray(s)?s[0]:s).join(",")}let n=r[e.name];if(n===void 0)return"";let a=(Array.isArray(n)?n:[n]).map(o=>this.encodeValue(o,e.operator));switch(e.operator){case"":return a.join(",");case"+":return a.join(",");case"#":return"#"+a.join(",");case".":return"."+a.join(".");case"/":return"/"+a.join("/");default:return a.join(",")}}expand(e){let r="",n=!1;for(let i of this.parts){if(typeof i=="string"){r+=i;continue}let a=this.expandPart(i,e);a&&((i.operator==="?"||i.operator==="&")&&n?r+=a.replace("?","&"):r+=a,(i.operator==="?"||i.operator==="&")&&(n=!0))}return r}escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}partToRegExp(e){let r=[];for(let a of e.names)t.validateLength(a,1e6,"Variable name");if(e.operator==="?"||e.operator==="&"){for(let a=0;a<e.names.length;a++){let o=e.names[a],s=a===0?"\\"+e.operator:"&";r.push({pattern:s+this.escapeRegExp(o)+"=([^&]+)",name:o})}return r}let n,i=e.name;switch(e.operator){case"":n=e.exploded?"([^/,]+(?:,[^/,]+)*)":"([^/,]+)";break;case"+":case"#":n="(.+)";break;case".":n="\\.([^/,]+)";break;case"/":n="/"+(e.exploded?"([^/,]+(?:,[^/,]+)*)":"([^/,]+)");break;default:n="([^/]+)"}return r.push({pattern:n,name:i}),r}match(e){t.validateLength(e,1e6,"URI");let r="^",n=[];for(let s of this.parts)if(typeof s=="string")r+=this.escapeRegExp(s);else{let c=this.partToRegExp(s);for(let{pattern:l,name:u}of c)r+=l,n.push({name:u,exploded:s.exploded})}r+="$",t.validateLength(r,1e6,"Generated regex pattern");let i=new RegExp(r),a=e.match(i);if(!a)return null;let o={};for(let s=0;s<n.length;s++){let{name:c,exploded:l}=n[s],u=a[s+1],p=c.replace("*","");l&&u.includes(",")?o[p]=u.split(","):o[p]=u}return o}};var KJ=/^[A-Za-z0-9._-]{1,128}$/;function WJ(t){let e=[];if(t.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(t.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${t.length})`]};if(t.includes(" ")&&e.push("Tool name contains spaces, which may cause parsing issues"),t.includes(",")&&e.push("Tool name contains commas, which may cause parsing issues"),(t.startsWith("-")||t.endsWith("-"))&&e.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(t.startsWith(".")||t.endsWith("."))&&e.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!KJ.test(t)){let r=t.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,i,a)=>a.indexOf(n)===i);return e.push(`Tool name contains invalid characters: ${r.map(n=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function GJ(t,e){if(e.length>0){console.warn(`Tool name validation warning for "${t}":`);for(let r of e)console.warn(` - ${r}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function Av(t){let e=WJ(t);return GJ(t,e.warnings),e.isValid}var Vp=class{constructor(e){this._mcpServer=e}registerToolTask(e,r,n){let i={taskSupport:"required",...r.execution};if(i.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,r.title,r.description,r.inputSchema,r.outputSchema,r.annotations,i,r._meta,n)}};var Bp=class{constructor(e,r){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Lp(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new Vp(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(Vn(yl)),this.server.assertCanSetRequestHandler(Vn(la)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(yl,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,r])=>{let n={name:e,title:r.title,description:r.description,inputSchema:(()=>{let i=Ha(r.inputSchema);return i?Oy(i,{strictUnions:!0,pipeStrategy:"input"}):XJ})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let i=Ha(r.outputSchema);i&&(n.outputSchema=Oy(i,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(la,async(e,r)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new q(U.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new q(U.InvalidParams,`Tool ${e.params.name} disabled`);let i=!!e.params.task,a=n.execution?.taskSupport,o="createTask"in n.handler;if((a==="required"||a==="optional")&&!o)throw new q(U.InternalError,`Tool ${e.params.name} has taskSupport '${a}' but was not registered with registerToolTask`);if(a==="required"&&!i)throw new q(U.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(a==="optional"&&!i&&o)return await this.handleAutomaticTaskPolling(n,e,r);let s=await this.validateToolInput(n,e.params.arguments,e.params.name),c=await this.executeToolHandler(n,s,r);return i||await this.validateToolOutput(n,c,e.params.name),c}catch(n){if(n instanceof q&&n.code===U.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,r,n){if(!e.inputSchema)return;let a=Ha(e.inputSchema)??e.inputSchema,o=await Wu(a,r);if(!o.success){let s="error"in o?o.error:"Unknown error",c=Gu(s);throw new q(U.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${c}`)}return o.data}async validateToolOutput(e,r,n){if(!e.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new q(U.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let i=Ha(e.outputSchema),a=await Wu(i,r.structuredContent);if(!a.success){let o="error"in a?a.error:"Unknown error",s=Gu(o);throw new q(U.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${s}`)}}async executeToolHandler(e,r,n){let i=e.handler;if("createTask"in i){if(!n.taskStore)throw new Error("No task store provided.");let o={...n,taskStore:n.taskStore};if(e.inputSchema){let s=i;return await Promise.resolve(s.createTask(r,o))}else{let s=i;return await Promise.resolve(s.createTask(o))}}if(e.inputSchema){let o=i;return await Promise.resolve(o(r,n))}else{let o=i;return await Promise.resolve(o(n))}}async handleAutomaticTaskPolling(e,r,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");let i=await this.validateToolInput(e,r.params.arguments,r.params.name),a=e.handler,o={...n,taskStore:n.taskStore},s=i?await Promise.resolve(a.createTask(i,o)):await Promise.resolve(a.createTask(o)),c=s.task.taskId,l=s.task,u=l.pollInterval??5e3;for(;l.status!=="completed"&&l.status!=="failed"&&l.status!=="cancelled";){await new Promise(d=>setTimeout(d,u));let p=await n.taskStore.getTask(c);if(!p)throw new q(U.InternalError,`Task ${c} not found during polling`);l=p}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(Vn(vl)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(vl,async e=>{switch(e.params.ref.type){case"ref/prompt":return a1(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return o1(e),this.handleResourceCompletion(e,e.params.ref);default:throw new q(U.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){let n=this._registeredPrompts[r.name];if(!n)throw new q(U.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new q(U.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return vc;let a=Rn(n.argsSchema)?.[e.params.argument.name];if(!$v(a))return vc;let o=H$(a);if(!o)return vc;let s=await o(e.params.argument.value,e.params.context);return W$(s)}async handleResourceCompletion(e,r){let n=Object.values(this._registeredResourceTemplates).find(o=>o.resourceTemplate.uriTemplate.toString()===r.uri);if(!n){if(this._registeredResources[r.uri])return vc;throw new q(U.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let i=n.resourceTemplate.completeCallback(e.params.argument.name);if(!i)return vc;let a=await i(e.params.argument.value,e.params.context);return W$(a)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(Vn(dl)),this.server.assertCanSetRequestHandler(Vn(fl)),this.server.assertCanSetRequestHandler(Vn(ml)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(dl,async(e,r)=>{let n=Object.entries(this._registeredResources).filter(([a,o])=>o.enabled).map(([a,o])=>({uri:a,name:o.name,...o.metadata})),i=[];for(let a of Object.values(this._registeredResourceTemplates)){if(!a.resourceTemplate.listCallback)continue;let o=await a.resourceTemplate.listCallback(r);for(let s of o.resources)i.push({...a.metadata,...s})}return{resources:[...n,...i]}}),this.server.setRequestHandler(fl,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(ml,async(e,r)=>{let n=new URL(e.params.uri),i=this._registeredResources[n.toString()];if(i){if(!i.enabled)throw new q(U.InvalidParams,`Resource ${n} disabled`);return i.readCallback(n,r)}for(let a of Object.values(this._registeredResourceTemplates)){let o=a.resourceTemplate.uriTemplate.match(n.toString());if(o)return a.readCallback(n,o,r)}throw new q(U.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(Vn(hl)),this.server.assertCanSetRequestHandler(Vn(gl)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(hl,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?QJ(r.argsSchema):void 0}))})),this.server.setRequestHandler(gl,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new q(U.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new q(U.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let i=Ha(n.argsSchema),a=await Wu(i,e.params.arguments);if(!a.success){let c="error"in a?a.error:"Unknown error",l=Gu(c);throw new q(U.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${l}`)}let o=a.data,s=n.callback;return await Promise.resolve(s(o,r))}else{let i=n.callback;return await Promise.resolve(i(r))}}),this._promptHandlersInitialized=!0)}resource(e,r,...n){let i;typeof n[0]=="object"&&(i=n.shift());let a=n[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let o=this._createRegisteredResource(e,void 0,r,i,a);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let o=this._createRegisteredResourceTemplate(e,void 0,r,i,a);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}}registerResource(e,r,n,i){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let a=this._createRegisteredResource(e,n.title,r,n,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let a=this._createRegisteredResourceTemplate(e,n.title,r,n,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}}_createRegisteredResource(e,r,n,i,a){let o={name:e,title:r,metadata:i,readCallback:a,enabled:!0,disable:()=>o.update({enabled:!1}),enable:()=>o.update({enabled:!0}),remove:()=>o.update({uri:null}),update:s=>{typeof s.uri<"u"&&s.uri!==n&&(delete this._registeredResources[n],s.uri&&(this._registeredResources[s.uri]=o)),typeof s.name<"u"&&(o.name=s.name),typeof s.title<"u"&&(o.title=s.title),typeof s.metadata<"u"&&(o.metadata=s.metadata),typeof s.callback<"u"&&(o.readCallback=s.callback),typeof s.enabled<"u"&&(o.enabled=s.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=o,o}_createRegisteredResourceTemplate(e,r,n,i,a){let o={resourceTemplate:n,title:r,metadata:i,readCallback:a,enabled:!0,disable:()=>o.update({enabled:!1}),enable:()=>o.update({enabled:!0}),remove:()=>o.update({name:null}),update:l=>{typeof l.name<"u"&&l.name!==e&&(delete this._registeredResourceTemplates[e],l.name&&(this._registeredResourceTemplates[l.name]=o)),typeof l.title<"u"&&(o.title=l.title),typeof l.template<"u"&&(o.resourceTemplate=l.template),typeof l.metadata<"u"&&(o.metadata=l.metadata),typeof l.callback<"u"&&(o.readCallback=l.callback),typeof l.enabled<"u"&&(o.enabled=l.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=o;let s=n.uriTemplate.variableNames;return Array.isArray(s)&&s.some(l=>!!n.completeCallback(l))&&this.setCompletionRequestHandler(),o}_createRegisteredPrompt(e,r,n,i,a){let o={title:r,description:n,argsSchema:i===void 0?void 0:Di(i),callback:a,enabled:!0,disable:()=>o.update({enabled:!1}),enable:()=>o.update({enabled:!0}),remove:()=>o.update({name:null}),update:s=>{typeof s.name<"u"&&s.name!==e&&(delete this._registeredPrompts[e],s.name&&(this._registeredPrompts[s.name]=o)),typeof s.title<"u"&&(o.title=s.title),typeof s.description<"u"&&(o.description=s.description),typeof s.argsSchema<"u"&&(o.argsSchema=Di(s.argsSchema)),typeof s.callback<"u"&&(o.callback=s.callback),typeof s.enabled<"u"&&(o.enabled=s.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=o,i&&Object.values(i).some(c=>{let l=c instanceof Mt?c._def?.innerType:c;return $v(l)})&&this.setCompletionRequestHandler(),o}_createRegisteredTool(e,r,n,i,a,o,s,c,l){Av(e);let u={title:r,description:n,inputSchema:K$(i),outputSchema:K$(a),annotations:o,execution:s,_meta:c,handler:l,enabled:!0,disable:()=>u.update({enabled:!1}),enable:()=>u.update({enabled:!0}),remove:()=>u.update({name:null}),update:p=>{typeof p.name<"u"&&p.name!==e&&(typeof p.name=="string"&&Av(p.name),delete this._registeredTools[e],p.name&&(this._registeredTools[p.name]=u)),typeof p.title<"u"&&(u.title=p.title),typeof p.description<"u"&&(u.description=p.description),typeof p.paramsSchema<"u"&&(u.inputSchema=Di(p.paramsSchema)),typeof p.outputSchema<"u"&&(u.outputSchema=Di(p.outputSchema)),typeof p.callback<"u"&&(u.handler=p.callback),typeof p.annotations<"u"&&(u.annotations=p.annotations),typeof p._meta<"u"&&(u._meta=p._meta),typeof p.enabled<"u"&&(u.enabled=p.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=u,this.setToolRequestHandlers(),this.sendToolListChanged(),u}tool(e,...r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let n,i,a,o;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){let c=r[0];if(Pv(c))i=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!Pv(r[0])&&(o=r.shift());else if(typeof c=="object"&&c!==null){if(Object.values(c).some(l=>typeof l=="object"&&l!==null))throw new Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);o=r.shift()}}let s=r[0];return this._createRegisteredTool(e,void 0,n,i,a,o,{taskSupport:"forbidden"},void 0,s)}registerTool(e,r,n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:i,description:a,inputSchema:o,outputSchema:s,annotations:c,_meta:l}=r;return this._createRegisteredTool(e,i,a,o,s,c,{taskSupport:"forbidden"},l,n)}prompt(e,...r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let n;typeof r[0]=="string"&&(n=r.shift());let i;r.length>1&&(i=r.shift());let a=r[0],o=this._createRegisteredPrompt(e,void 0,n,i,a);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),o}registerPrompt(e,r,n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:i,description:a,argsSchema:o}=r,s=this._createRegisteredPrompt(e,i,a,o,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),s}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,r){return this.server.sendLoggingMessage(e,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}},Up=class{constructor(e,r){this._callbacks=r,this._uriTemplate=typeof e=="string"?new qp(e):e}get uriTemplate(){return this._uriTemplate}get listCallback(){return this._callbacks.list}completeCallback(e){return this._callbacks.complete?.[e]}},XJ={type:"object",properties:{}};function G$(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function X$(t){return"_def"in t||"_zod"in t||G$(t)}function Pv(t){return typeof t!="object"||t===null||X$(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(G$)}function K$(t){if(t){if(Pv(t))return Di(t);if(!X$(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function QJ(t){let e=Rn(t);return e?Object.entries(e).map(([r,n])=>{let i=xC(n),a=wC(n);return{name:r,description:i,required:!a}}):[]}function Vn(t){let r=Rn(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Xu(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function W$(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var vc={completion:{values:[],hasMore:!1}};var Vt=tt(require("node:crypto"),1),Hn=tt(require("node:fs"),1),Yi=tt(require("node:path"),1);var Jp={gutter:0,mask:!1,drag:!1,left:!1,hover:!1,shadow:!0,link:!0,watermark:!1,mobile:!1,dark:!1,autoRefresh:0,lastRefreshTime:"",watermarkStyle:{content:"Microi",font:{fontSize:16,color:"rgba(255, 0, 0, 0.15)"},rotate:-22},dynamicStyle:{padding:"10px",backgroundColor:"",opacity:1}};function ne(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}var YJ=new Set(["true","false","axis","item","none","vertical","horizontal"]);function eH(t){if(typeof t!="string")return"";let e=t.trim();return e?YJ.has(e.toLowerCase())?"":e:""}function mo(t){if(t==null||t==="")return{ok:!1,error:"JSON value is empty."};if(typeof t!="string")return{ok:!0,value:t};try{return{ok:!0,value:JSON.parse(t)}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}function Q$(t,e){return{...t,...ne(e)}}function Hp(){return Math.floor(Math.random()*8e4+1e4)}function tH(t){let e=Math.random().toString(36).slice(2,8);return`page_${t.replace(/[^\w\u4e00-\u9fa5]+/g,"_").replace(/^_+|_+$/g,"").slice(0,24)||"ai"}_${e}`}function N(t,e,r,n,i){let a={sort:t,label:e,type:r,value:n};return i&&(a.typeOptions=i),a}var rH=[{label:"\u672C\u65E5",value:"today"},{label:"\u672C\u5468",value:"week"},{label:"\u672C\u6708",value:"month"},{label:"\u672C\u5B63",value:"quarter"},{label:"\u672C\u5E74",value:"year"},{label:"\u53BB\u5E74",value:"lastYear"}];function nH(){return{prop:"period",label:"\u7EDF\u8BA1\u5468\u671F",type:"select",value:"month",defaultValue:"month",remote:!1,options:rH.map(t=>({...t}))}}function Ki(t){let e=Array.isArray(t)?t.map(n=>ne(n)).filter(n=>Object.keys(n).length):[];return e.some(n=>n.prop==="period"||n.prop==="_period")?e:[nH(),...e]}function tA(t){return{...t,searchData:Ki(t.searchData)}}function iH(t,e){let r={statistic:[18,19],progress:[26,27],bar:[1,16],line:[1,16],linebar:[1,18],pie:[1,19],funnel:[1,13],tabel:[1,13]};for(let n of r[t]??[]){let i=ne(e[n]);Object.keys(i).length&&(i.value=!0,e[n]=i)}}function Rv(t,e){if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t=="string"){let r=Number.parseFloat(t);if(Number.isFinite(r))return r}return e}function Y$(t,e,r){return Rv(ne(t[e]).value,r)}function Zp(t,e){return ne(t[e]).value===!0}function aH(t){let e=Array.isArray(t.widgetParams)?t.widgetParams:[],r=ne(e[0]),n=ne(r.typeOptions).dataJson;if(Array.isArray(n))return n.length;let i=ne(n);return Array.isArray(i.data)?i.data.length:Array.isArray(i.bodyData)?i.bodyData.length:0}function oH(t){let e=Bn(t,"type"),r=Array.isArray(t.widgetParams)?t.widgetParams:[],n=aH(t);if(e==="statistic"){let i=Math.min(24,Math.max(1,Y$(r,1,6))),a=Math.max(1,Math.floor(24/i)),o=Math.max(1,Math.ceil(Math.max(n,1)/a)),s=Zp(r,18)||Zp(r,19)?44:0;return Math.max(190,s+o*88+18)}if(e==="progress"){let i=Math.min(24,Math.max(1,Y$(r,1,12))),a=Math.max(1,Math.floor(24/i)),o=Math.max(1,Math.ceil(Math.max(n,1)/a)),s=Zp(r,26)||Zp(r,27)?44:0;return Math.max(180,s+o*108+24)}return 0}function sH(t,e,r){let n=oH(t);if(!n)return 0;let i=ne(t.widgetOption);return Rv(i.height,0)<n&&(i.height=n,t.widgetOption=i,r.push(`${e}.widgetOption.height was raised to ${n} so content widgets do not clip when rendered.`)),n}function cH(t,e,r){return{number:Hp(),wrapperNumber:t,span:e,offset:0,push:0,pull:0,height:r,marginTop:0,dynamicStyle:{padding:"8px",backgroundColor:""}}}function lH(t,e){return[N(0,"Data source","textarea","",{rows:3,dataJson:{data:t,searchData:Ki([])}}),N(1,"Grid width","slider",6,{min:1,max:24,step:1}),N(2,"Background","color",""),N(3,"Gap","input","5px"),N(4,"Block colors","input","#2563eb,#16a34a,#f59e0b,#dc2626,#7c3aed,#0891b2"),N(5,"Padding","input","18px"),N(6,"Radius","input","8px"),N(7,"Title size","input","13px"),N(8,"Title weight","input","500"),N(9,"Title color","color",e?"#dbeafe":"#ffffff"),N(10,"Title margin","input","0 0 10px 0"),N(11,"Value size","input","22px"),N(12,"Value weight","input","700"),N(13,"Value color","color","#ffffff"),N(14,"Icon position","radio","suffix"),N(15,"Icon color","color","#ffffff"),N(16,"Icon size","input","18px"),N(17,"Background image","input",""),N(18,"Show search","switch",!0),N(19,"Date filter","switch",!0),N(20,"Precision","number",0),N(21,"Value padding","input","0"),N(22,"Value margin","input","0"),N(23,"Icon margin","input","0")]}function Iv(t,e,r,n=""){let i=tA(e);return t==="pie"?[N(0,"Data source","textarea","",{rows:3,dataJson:i}),N(1,"Show search","switch",!0),N(2,"Inner radius","number",36),N(3,"Outer radius","number",92),N(4,"Unit","input",n),N(5,"Title","input",r),N(6,"Subtitle","input",""),N(7,"Show legend","switch",!0),N(8,"Legend orient","select","vertical"),N(9,"Legend position","select","left"),N(10,"Tooltip","switch",!0),N(11,"Trigger","select","item"),N(12,"Toolbox","switch",!1),N(13,"Show label","switch",!0),N(14,"Label position","select","outside"),N(15,"Border radius","number",8),N(16,"Border width","number",2),N(17,"Pad angle","number",2),N(18,"Nightingale","switch",!1),N(19,"Date filter","switch",!0),N(20,"Label format","input","{d}%")]:[N(0,"Data source","textarea","",{rows:3,dataJson:i}),N(1,"Show search","switch",!0),N(2,"Boundary gap","switch",t==="bar"),N(3,"Bar effect","select","shadow"),N(4,"Unit","input",n),N(5,"Title","input",r),N(6,"Subtitle","input",""),N(7,"Show legend","switch",!0),N(8,"Legend orient","select","horizontal"),N(9,"Legend position","select","center"),N(10,"Tooltip","switch",!0),N(11,"Trigger","select","axis"),N(12,"Toolbox","switch",!1),N(13,"Show label","switch",t==="bar"),N(14,"Label position","select","outside"),N(15,"Split line","switch",!0),N(16,"Date filter","switch",!0),N(17,"Rotate","switch",!1)]}function uH(t){return[N(0,"Data source","textarea","",{rows:3,dataJson:tA(t)}),N(1,"Show search","switch",!0),N(2,"Stripe","switch",!0),N(3,"Border","switch",!0),N(4,"Size","select","small"),N(5,"Progress width","number",16),N(6,"Merge column","input",""),N(7,"Page size","number",-1),N(8,"Summary","switch",!1),N(9,"Border color","color","var(--el-border-color-lighter)"),N(10,"Header background","color","var(--el-fill-color-light)"),N(11,"Header color","color","var(--el-table-header-text-color)"),N(12,"Text color","color","var(--el-table-text-color)"),N(13,"Date filter","switch",!0),N(14,"Pie width","number",30),N(15,"Pie background","color","#409eff50"),N(16,"Pie border","color","#409eff")]}function po(t,e,r,n,i,a){return{type:t,label:e,category:0,show:1,icon:"",img:"",widgetOption:cH(r,n,i),widgetParams:a}}function fo(t,e,r,n,i){let a=Hp();return{type:"pannel",label:"Card",hidden:!1,icon:"",img:"",wrapperOption:{number:a,gutter:0,span:e,offset:0,push:0,pull:0,height:r,marginTop:0,margin:"0px 10px 10px 0px",pannelColor:i?"#111827":"#ffffff",dynamicStyle:{padding:"12px",backgroundColor:i?"#111827":"#ffffff"},titleOption:{hidden:!0,title:t,dynamicStyle:{textAlign:"left",padding:"0px",height:"22px",lineHeight:"22px",fontSize:"14px",color:i?"#e5e7eb":"#111827"},moreOption:{hidden:!1,icon:"More",iconShow:!1,text:"More",linkurl:"/",linktype:"router",refresh:"0",datetime:"0",autotime:!1,autotimeval:1,dynamicStyle:{color:i?"#93c5fd":"#2563eb",fontSize:"12px"}}}},widgetList:n(a)}}function Ov(t,e){let r=`${t} ${e||""}`.toLowerCase();return/维保|维修|设备|工单|巡检|maintenance|service|ticket|asset/.test(r)?"maintenance":/商城|商品|库存|订单|门店|mall|shop|ecommerce|retail|sku/.test(r)?"mall":/财务|发票|收款|付款|finance|invoice|payment/.test(r)?"finance":/销售|客户|商机|营收|sales|customer|crm|revenue/.test(r)?"sales":"operations"}function rA(t){return t==="maintenance"?{title:"\u7EF4\u4FDD\u8FD0\u8425\u9A7E\u9A76\u8231",subtitle:"\u5DE5\u5355\u3001\u8BBE\u5907\u3001\u5DE1\u68C0\u4E0E\u5BA2\u6237\u670D\u52A1\u72B6\u6001\u603B\u89C8",stats:[{name:"\u4ECA\u65E5\u5DE5\u5355",value:86,icon:"Tickets",bgColor:"#2563eb",bgImage:"",linkUrl:"/"},{name:"\u5F85\u6D3E\u5355",value:14,icon:"Clock",bgColor:"#f59e0b",bgImage:"",linkUrl:"/"},{name:"\u6309\u65F6\u5B8C\u6210\u7387",value:96,icon:"Top",bgColor:"#16a34a",bgImage:"",linkUrl:"/"},{name:"\u9AD8\u98CE\u9669\u8BBE\u5907",value:7,icon:"Warning",bgColor:"#dc2626",bgImage:"",linkUrl:"/"}],xAxis:["\u5468\u4E00","\u5468\u4E8C","\u5468\u4E09","\u5468\u56DB","\u5468\u4E94","\u5468\u516D","\u5468\u65E5"],barSeries:[{name:"\u65B0\u589E\u5DE5\u5355",data:[18,22,16,28,31,20,14]},{name:"\u5B8C\u6210\u5DE5\u5355",data:[15,20,18,24,29,21,16]}],lineSeries:[{name:"\u54CD\u5E94\u65F6\u957F(\u5206\u949F)",data:[42,38,35,33,31,29,28]},{name:"\u6EE1\u610F\u5EA6",data:[92,93,94,94,95,96,96]}],pieData:[{name:"\u5F85\u63A5\u5355",value:14},{name:"\u5904\u7406\u4E2D",value:28},{name:"\u5F85\u9A8C\u6536",value:17},{name:"\u5DF2\u5B8C\u6210",value:63}],tableHeaders:[{prop:"WorkOrderNo",label:"\u5DE5\u5355\u53F7",align:"center"},{prop:"CustomerName",label:"\u5BA2\u6237",align:"center"},{prop:"DeviceName",label:"\u8BBE\u5907",align:"center"},{prop:"Status",label:"\u72B6\u6001",align:"center",status_ui:!0},{prop:"Owner",label:"\u8D1F\u8D23\u4EBA",align:"center"}],tableRows:[{WorkOrderNo:"WO-20260611-001",CustomerName:"\u5229\u8F69\u79D1\u6280\u56ED",DeviceName:"\u7A7A\u538B\u673A A01",Status:"\u5904\u7406\u4E2D",Owner:"\u5F20\u5DE5",status_ui:"warning"},{WorkOrderNo:"WO-20260611-002",CustomerName:"\u661F\u6CB3\u5DE5\u5382",DeviceName:"\u51B7\u5374\u5854 C03",Status:"\u5F85\u9A8C\u6536",Owner:"\u674E\u5DE5",status_ui:"primary"},{WorkOrderNo:"WO-20260611-003",CustomerName:"\u5317\u57CE\u4ED3\u50A8",DeviceName:"\u914D\u7535\u67DC P12",Status:"\u5DF2\u5B8C\u6210",Owner:"\u738B\u5DE5",status_ui:"success"}]}:t==="mall"?{title:"\u5546\u57CE\u7ECF\u8425\u770B\u677F",subtitle:"\u8BA2\u5355\u3001\u5546\u54C1\u3001\u5E93\u5B58\u4E0E\u4F1A\u5458\u589E\u957F\u6982\u89C8",stats:[{name:"\u4ECA\u65E5\u8BA2\u5355",value:328,icon:"ShoppingCart",bgColor:"#2563eb",bgImage:"",linkUrl:"/"},{name:"\u9500\u552E\u989D",value:128900,icon:"Money",bgColor:"#16a34a",bgImage:"",linkUrl:"/"},{name:"\u4F4E\u5E93\u5B58 SKU",value:23,icon:"Warning",bgColor:"#f59e0b",bgImage:"",linkUrl:"/"},{name:"\u65B0\u589E\u4F1A\u5458",value:78,icon:"User",bgColor:"#7c3aed",bgImage:"",linkUrl:"/"}],xAxis:["1\u6708","2\u6708","3\u6708","4\u6708","5\u6708","6\u6708"],barSeries:[{name:"\u8BA2\u5355\u6570",data:[1200,1420,1380,1680,1910,2250]},{name:"\u53D1\u8D27\u6570",data:[1160,1390,1350,1610,1880,2190]}],lineSeries:[{name:"\u9500\u552E\u989D",data:[82,96,91,116,132,158]},{name:"\u590D\u8D2D\u7387",data:[28,31,30,34,36,39]}],pieData:[{name:"\u98DF\u54C1\u996E\u6599",value:35},{name:"\u5BB6\u6E05\u65E5\u5316",value:24},{name:"\u6570\u7801\u5BB6\u7535",value:18},{name:"\u670D\u9970\u978B\u5305",value:23}],tableHeaders:[{prop:"SkuName",label:"\u5546\u54C1",align:"center"},{prop:"Stock",label:"\u5E93\u5B58",align:"center"},{prop:"Sales",label:"\u9500\u91CF",align:"center"},{prop:"Status",label:"\u72B6\u6001",align:"center",status_ui:!0}],tableRows:[{SkuName:"\u8F7B\u98DF\u71D5\u9EA6\u7EC4\u5408",Stock:128,Sales:486,Status:"\u70ED\u9500",status_ui:"success"},{SkuName:"\u65E0\u7EBF\u8033\u673A Pro",Stock:18,Sales:221,Status:"\u4F4E\u5E93\u5B58",status_ui:"warning"},{SkuName:"\u667A\u80FD\u6C34\u676F",Stock:76,Sales:164,Status:"\u6B63\u5E38",status_ui:"primary"}]}:{title:t==="sales"?"\u9500\u552E\u8FD0\u8425\u4EEA\u8868\u76D8":t==="finance"?"\u8D22\u52A1\u6536\u4ED8\u6B3E\u770B\u677F":"\u7EFC\u5408\u8FD0\u8425\u9A7E\u9A76\u8231",subtitle:"\u6838\u5FC3\u6307\u6807\u3001\u8D8B\u52BF\u5206\u6790\u3001\u7ED3\u6784\u5206\u5E03\u4E0E\u660E\u7EC6\u5217\u8868",stats:[{name:"\u672C\u6708\u76EE\u6807",value:128,icon:"Aim",bgColor:"#2563eb",bgImage:"",linkUrl:"/"},{name:"\u5DF2\u5B8C\u6210",value:96,icon:"Top",bgColor:"#16a34a",bgImage:"",linkUrl:"/"},{name:"\u5F85\u5904\u7406",value:18,icon:"Clock",bgColor:"#f59e0b",bgImage:"",linkUrl:"/"},{name:"\u98CE\u9669\u9879",value:6,icon:"Warning",bgColor:"#dc2626",bgImage:"",linkUrl:"/"}],xAxis:["1\u6708","2\u6708","3\u6708","4\u6708","5\u6708","6\u6708"],barSeries:[{name:"\u8BA1\u5212",data:[80,92,100,116,124,138]},{name:"\u5B9E\u9645",data:[76,88,96,110,129,146]}],lineSeries:[{name:"\u589E\u957F\u7387",data:[8,12,10,16,18,21]},{name:"\u8FBE\u6210\u7387",data:[88,91,93,94,96,98]}],pieData:[{name:"A \u7C7B",value:42},{name:"B \u7C7B",value:28},{name:"C \u7C7B",value:18},{name:"\u5176\u4ED6",value:12}],tableHeaders:[{prop:"Name",label:"\u540D\u79F0",align:"center"},{prop:"Owner",label:"\u8D1F\u8D23\u4EBA",align:"center"},{prop:"Progress",label:"\u8FDB\u5EA6",align:"center",progress_ui:!0},{prop:"Status",label:"\u72B6\u6001",align:"center",status_ui:!0}],tableRows:[{Name:"\u91CD\u70B9\u9879\u76EE A",Owner:"\u9648\u6668",Progress:92,Status:"\u8FDB\u884C\u4E2D",progress_ui:"success",status_ui:"success"},{Name:"\u5BA2\u6237\u8DDF\u8FDB B",Owner:"\u6797\u66E6",Progress:68,Status:"\u5F85\u63A8\u8FDB",progress_ui:"warning",status_ui:"warning"},{Name:"\u98CE\u9669\u6574\u6539 C",Owner:"\u8D75\u5B81",Progress:35,Status:"\u9884\u8B66",progress_ui:"exception",status_ui:"danger"}]}}function pH(t){let e=t.prompt||"",r=Ov(e,t.theme),n=/dark|深色|黑色|大屏|驾驶舱/.test(`${e} ${t.style||""}`.toLowerCase()),i=rA(r),a=t.title||i.title,o=t.desc||i.subtitle;return{formConfig:{...Jp,dark:n,title:a,dynamicStyle:{padding:"12px 0 0 0",backgroundColor:n?"#0f172a":"#f3f4f6",opacity:1}},wrapperList:[fo(a,24,120,c=>[po("workbench","Workbench",c,24,90,[N(0,"Data source","textarea","",{rows:3,dataJson:{icon:"",title:a,subTitle:o}})])],n),fo("\u6838\u5FC3\u6307\u6807",24,220,c=>[po("statistic","Statistic",c,24,190,lH(i.stats,n))],n),fo("\u8D8B\u52BF\u5206\u6790",12,340,c=>[po("bar","Bar Chart",c,24,300,Iv("bar",{xAxis:i.xAxis,series:i.barSeries,searchData:[]},"\u4E1A\u52A1\u8D8B\u52BF",""))],n),fo("\u7ED3\u6784\u5360\u6BD4",12,340,c=>[po("pie","Pie Chart",c,24,300,Iv("pie",{data:i.pieData,searchData:[]},"\u5206\u7C7B\u5360\u6BD4",""))],n),fo("\u6548\u7387\u8D70\u52BF",12,340,c=>[po("line","Line Chart",c,24,300,Iv("line",{xAxis:i.xAxis,series:i.lineSeries,searchData:[]},"\u6548\u7387\u8D70\u52BF",""))],n),fo("\u91CD\u70B9\u660E\u7EC6",12,340,c=>[po("tabel","Table",c,24,300,uH({headerData:i.tableHeaders,bodyData:i.tableRows,total:i.tableRows.length,searchData:[]}))],n)]}}function Ge(t,e,r,n,i,a={}){return{options:{left:t,top:e,width:r,height:n,title:i,fontSize:9,lineHeight:n,...a},printElementType:{title:"Text",type:"text"}}}function eA(t,e,r){return{options:{left:t,top:e,width:r,height:1,borderStyle:"solid"},printElementType:{title:"Line",type:"hline"}}}function dH(t,e,r,n){return{options:{left:t,top:e,width:r,height:n,borderWidth:1},printElementType:{title:"Rect",type:"rect"}}}function fH(t){return Ov(t)}function mH(t){let e=fH(t.prompt||""),r=t.title||(e==="maintenance"?"\u7EF4\u4FDD\u5DE5\u5355\u6253\u5370\u6A21\u677F":e==="mall"?"\u5546\u57CE\u8BA2\u5355\u6253\u5370\u6A21\u677F":"\u4E1A\u52A1\u5355\u636E\u6253\u5370\u6A21\u677F"),n=e==="maintenance"?"Items":"Details",i=e==="maintenance"?[[{title:"\u9879\u76EE",field:"ItemName",width:120,checked:!0},{title:"\u5904\u7406\u7ED3\u679C",field:"Result",width:180,checked:!0},{title:"\u5DE5\u65F6",field:"Hours",width:80,checked:!0},{title:"\u5907\u6CE8",field:"Remark",width:150,checked:!0}]]:[[{title:"\u540D\u79F0",field:"Name",width:150,checked:!0},{title:"\u89C4\u683C",field:"Spec",width:120,checked:!0},{title:"\u6570\u91CF",field:"Qty",width:80,checked:!0},{title:"\u91D1\u989D",field:"Amount",width:100,checked:!0},{title:"\u5907\u6CE8",field:"Remark",width:120,checked:!0}]],a=e==="maintenance"?{WorkOrderNo:"WO-20260611-001",CustomerName:"\u5229\u8F69\u79D1\u6280\u56ED",ContactName:"\u738B\u7ECF\u7406",DeviceName:"\u7A7A\u538B\u673A A01",ServiceDate:"2026-06-11",EngineerName:"\u5F20\u5DE5",FaultDesc:"\u8BBE\u5907\u8FD0\u884C\u5F02\u54CD\uFF0C\u538B\u529B\u6CE2\u52A8\u5F02\u5E38\u3002",Solution:"\u5B8C\u6210\u8F74\u627F\u68C0\u67E5\u3001\u7BA1\u8DEF\u7D27\u56FA\u4E0E\u8FD0\u884C\u6D4B\u8BD5\u3002",Items:[{ItemName:"\u73B0\u573A\u68C0\u67E5",Result:"\u5DF2\u5B8C\u6210",Hours:1.5,Remark:"\u8FD0\u884C\u8BB0\u5F55\u6B63\u5E38"},{ItemName:"\u90E8\u4EF6\u7EF4\u62A4",Result:"\u5DF2\u5B8C\u6210",Hours:2,Remark:"\u66F4\u6362\u6613\u635F\u4EF6"}]}:{BillNo:"BILL-20260611-001",CustomerName:"\u793A\u4F8B\u5BA2\u6237",ContactName:"\u674E\u7ECF\u7406",BillDate:"2026-06-11",OwnerName:"\u9648\u6668",Summary:"\u4E1A\u52A1\u5355\u636E\u6458\u8981\u8BF4\u660E\u3002",Details:[{Name:"\u670D\u52A1\u9879\u76EE A",Spec:"\u6807\u51C6",Qty:2,Amount:1200,Remark:"\u542B\u7A0E"},{Name:"\u670D\u52A1\u9879\u76EE B",Spec:"\u9AD8\u7EA7",Qty:1,Amount:2800,Remark:"\u542B\u5B89\u88C5"}]},o=[Ge(40,18,520,24,r,{fontSize:18,fontWeight:"700",textAlign:"center",lineHeight:24}),eA(36,50,535),Ge(42,66,76,16,e==="maintenance"?"\u5DE5\u5355\u53F7":"\u5355\u636E\u53F7",{fontWeight:"600"}),Ge(118,66,160,16,"",{field:e==="maintenance"?"WorkOrderNo":"BillNo",testData:e==="maintenance"?a.WorkOrderNo:a.BillNo}),Ge(320,66,76,16,"\u65E5\u671F",{fontWeight:"600"}),Ge(396,66,160,16,"",{field:e==="maintenance"?"ServiceDate":"BillDate",testData:e==="maintenance"?a.ServiceDate:a.BillDate}),Ge(42,92,76,16,"\u5BA2\u6237",{fontWeight:"600"}),Ge(118,92,160,16,"",{field:"CustomerName",testData:a.CustomerName}),Ge(320,92,76,16,"\u8054\u7CFB\u4EBA",{fontWeight:"600"}),Ge(396,92,160,16,"",{field:"ContactName",testData:a.ContactName}),Ge(42,118,76,16,e==="maintenance"?"\u8BBE\u5907":"\u8D1F\u8D23\u4EBA",{fontWeight:"600"}),Ge(118,118,160,16,"",{field:e==="maintenance"?"DeviceName":"OwnerName",testData:e==="maintenance"?a.DeviceName:a.OwnerName}),Ge(320,118,76,16,e==="maintenance"?"\u5DE5\u7A0B\u5E08":"\u5236\u5355\u4EBA",{fontWeight:"600"}),Ge(396,118,160,16,"",{field:e==="maintenance"?"EngineerName":"OwnerName",testData:e==="maintenance"?a.EngineerName:a.OwnerName}),dH(38,150,535,70),Ge(48,160,70,16,e==="maintenance"?"\u6545\u969C\u63CF\u8FF0":"\u6458\u8981",{fontWeight:"600"}),Ge(118,160,430,46,"",{field:e==="maintenance"?"FaultDesc":"Summary",testData:e==="maintenance"?a.FaultDesc:a.Summary,lineHeight:18}),Ge(42,242,160,16,"\u660E\u7EC6",{fontSize:12,fontWeight:"700"}),{options:{left:40,top:266,width:530,height:92,field:n,columns:i,fields:i[0].map(c=>({text:c.title,field:c.field}))},printElementType:{title:"Table",type:"table"}},Ge(42,392,76,16,e==="maintenance"?"\u5904\u7406\u65B9\u6848":"\u5907\u6CE8",{fontWeight:"600"}),Ge(118,392,430,38,"",{field:e==="maintenance"?"Solution":"Summary",testData:e==="maintenance"?a.Solution:a.Summary,lineHeight:18}),eA(36,468,535),Ge(60,492,120,16,"\u5BA2\u6237\u7B7E\u5B57\uFF1A"),Ge(330,492,120,16,"\u7ECF\u529E\u4EBA\u7B7E\u5B57\uFF1A")];return{pageObj:{panels:[{index:0,name:r,paperType:t.paperType||"A4",height:297,width:210,paperHeader:0,paperFooter:841.8897637795277,paperNumberContinue:!0,watermarkOptions:{},panelLayoutOptions:{},printElements:o}]},printObj:a}}function Hi(t){let e=mo(t);if(!e.ok)return t;let r=e.value;if(typeof r=="string"){let a=mo(r);a.ok&&(r=a.value)}let n=ne(r);if(n.JsonObj!==void 0)return Hi(n.JsonObj);if(n.jsonObj!==void 0)return Hi(n.jsonObj);if(n.JsonStr!==void 0)return Hi(n.JsonStr);if(n.jsonStr!==void 0)return Hi(n.jsonStr);let i=ne(n.formData??n.FormData);if(Object.keys(i).length){if(i.JsonObj!==void 0)return Hi(i.JsonObj);if(i.jsonObj!==void 0)return Hi(i.jsonObj);if(i.formConfig!==void 0||i.wrapperList!==void 0)return i}return r}function hH(t,e,r){let n=Bn(t,"type");if(!Array.isArray(t.widgetParams)||t.widgetParams.length===0)return;let i=t.widgetParams,a={bar:[5,6],line:[5,6],linebar:[5,6],pie:[5,6],funnel:[3,4]};for(let l of a[n]??[]){let u=ne(i[l]);if(!Object.keys(u).length||u.value===void 0||u.value==="")continue;let p=eH(u.value);u.value!==p&&(u.value=p,i[l]=u,r.push(`${e}.widgetParams[${l}].value was cleared because it looked like a chart option, not display text.`))}let o=ne(i[0]),s={rows:3,...ne(o.typeOptions)},c=s.dataJson;if(["statistic","pie","funnel","progress"].includes(n))if(Array.isArray(c))s.dataJson={data:c,searchData:Ki([])},r.push(`${e}.widgetParams[0].typeOptions.dataJson array was wrapped as {data, searchData}.`);else{let l=ne(c);s.dataJson={...l,data:Array.isArray(l.data)?l.data:[],searchData:Ki(l.searchData)}}if(["bar","line","linebar"].includes(n)){let l=ne(s.dataJson);s.dataJson={...l,xAxis:Array.isArray(l.xAxis)?l.xAxis:[],series:Array.isArray(l.series)?l.series:[],searchData:Ki(l.searchData)}}if(n==="tabel")if(Array.isArray(c))s.dataJson={headerData:[],bodyData:c,total:c.length,searchData:Ki([])},r.push(`${e}.widgetParams[0].typeOptions.dataJson array was wrapped as table bodyData.`);else{let l=ne(s.dataJson);s.dataJson={...l,headerData:Array.isArray(l.headerData)?l.headerData:[],bodyData:Array.isArray(l.bodyData)?l.bodyData:[],total:typeof l.total=="number"?l.total:Array.isArray(l.bodyData)?l.bodyData.length:0,searchData:Ki(l.searchData)}}iH(n,i),o.typeOptions=s,i[0]=o,t.widgetParams=i}function un(t){let e=Hi(t),r=mo(e);if(!r.ok)return{ok:!1,errors:[`JsonObj is not valid JSON: ${r.error}`],warnings:[]};let n=ne(r.value),i=[],a=[];Object.keys(n).length||i.push("JsonObj must be an object."),n.formConfig!==void 0&&Object.keys(ne(n.formConfig)).length===0&&a.push("formConfig is empty; defaults were applied."),n.wrapperList!==void 0&&!Array.isArray(n.wrapperList)&&i.push("JsonObj.wrapperList must be an array.");let o=Array.isArray(n.wrapperList)?n.wrapperList.map((c,l)=>{let u=ne(c);Bn(u,"type")||(u.type="pannel"),Bn(u,"label")||(u.label="Card"),u.hidden===void 0&&(u.hidden=!1),u.icon=u.icon??"",u.img=u.img??"",u.wrapperOption=Q$({number:Hp(),gutter:0,span:24,offset:0,push:0,pull:0,height:300,marginTop:0,margin:"0px 10px 10px 0px",pannelColor:"",dynamicStyle:{padding:"10px",backgroundColor:""},titleOption:{hidden:!0,title:`Section ${l+1}`,dynamicStyle:{textAlign:"left",padding:"0px",height:"20px",lineHeight:"20px",fontSize:"14px",color:""},moreOption:{hidden:!1,icon:"More",iconShow:!1,text:"More",linkurl:"/",linktype:"router",refresh:"0",datetime:"0",autotime:!1,autotimeval:1,dynamicStyle:{color:"",fontSize:"12px"}}}},u.wrapperOption);let p=0;if(Array.isArray(u.widgetList)?u.widgetList=u.widgetList.map((d,h)=>{let m=ne(d);Bn(m,"type")||i.push(`wrapperList[${l}].widgetList[${h}].type is required.`),m.label=m.label??m.type??"Widget",m.category=m.category??0,m.show=m.show??1,m.icon=m.icon??"",m.img=m.img??"",m.widgetOption=Q$({number:Hp(),wrapperNumber:ne(u.wrapperOption).number,span:24,offset:0,push:0,pull:0,height:260,marginTop:0,dynamicStyle:{padding:"8px",backgroundColor:""}},m.widgetOption),Array.isArray(m.widgetParams)||(m.widgetParams=[N(0,"Data source","textarea","",{rows:3,dataJson:{}})],a.push(`wrapperList[${l}].widgetList[${h}].widgetParams was missing and a safe data param was added.`));let y=`wrapperList[${l}].widgetList[${h}]`;return hH(m,y,a),p=Math.max(p,sH(m,y,a)),m}):(u.widgetList=[],a.push(`wrapperList[${l}].widgetList was missing and was set to an empty array.`)),p>0){let d=ne(u.wrapperOption),h=p+16;Rv(d.height,0)<h&&(d.height=h,u.wrapperOption=d,a.push(`wrapperList[${l}].wrapperOption.height was raised to ${h} to fit content widgets.`))}return u}):[];Array.isArray(n.wrapperList)||a.push("wrapperList was missing and was set to an empty array.");let s={formConfig:{...Jp,...ne(n.formConfig),dynamicStyle:{...ne(Jp.dynamicStyle),...ne(ne(n.formConfig).dynamicStyle)},watermarkStyle:{...ne(Jp.watermarkStyle),...ne(ne(n.formConfig).watermarkStyle)}},wrapperList:o};return{ok:i.length===0,value:s,json:JSON.stringify(s),errors:i,warnings:a}}function gH(t){let e=mo(t);if(!e.ok)return t;let r=e.value,n=ne(r);return n.PageObj!==void 0?r=n.PageObj:n.pageObj!==void 0&&(r=n.pageObj),r}function Wi(t){let e=gH(t),r=mo(e);if(!r.ok)return{ok:!1,errors:[`PageObj is not valid JSON: ${r.error}`],warnings:[]};let n=ne(r.value),i=[],a=[];Array.isArray(n.panels)||i.push("PageObj.panels must be an array.");let o=Array.isArray(n.panels)?n.panels.map((s,c)=>{let l=ne(s);return l.index=l.index??c,l.name=l.name??`Panel ${c+1}`,l.paperType=l.paperType??"A4",l.height=l.height??297,l.width=l.width??210,l.paperHeader=l.paperHeader??0,l.paperFooter=l.paperFooter??841.8897637795277,l.paperNumberContinue=l.paperNumberContinue??!0,l.watermarkOptions=l.watermarkOptions??{},l.panelLayoutOptions=l.panelLayoutOptions??{},Array.isArray(l.printElements)||(l.printElements=[],a.push(`panels[${c}].printElements was missing and was set to an empty array.`)),l.printElements=l.printElements.map((u,p)=>{let d=ne(u);return Bn(ne(d.printElementType),"type")||i.push(`panels[${c}].printElements[${p}].printElementType.type is required.`),d.options=ne(d.options),d}),l}):[];return o.length===0&&i.push("PageObj.panels must contain at least one panel."),{ok:i.length===0,value:{...n,panels:o},json:JSON.stringify({...n,panels:o}),errors:i,warnings:a}}function Gi(t){if(t==null||t==="")return{ok:!0,value:{},json:"{}",errors:[],warnings:[]};let e=mo(t);return e.ok?{ok:!0,value:e.value,json:JSON.stringify(e.value),errors:[],warnings:[]}:{ok:!1,errors:[`PrintObj is not valid JSON: ${e.error}`],warnings:[]}}function Bn(t,...e){for(let r of e){let n=t[r];if(typeof n=="string"&&n.trim())return n.trim();if(typeof n=="number"||typeof n=="boolean")return String(n)}return""}function nA(t){let e=rA(Ov(t.prompt||"",t.theme)),r=t.title||e.title,n=pH({...t,title:r});return{title:r,number:t.number||tH(r),desc:t.desc||e.subtitle||Bn(ne(n.formConfig),"title")||"",jsonObj:n,jsonStr:JSON.stringify(n)}}function iA(t){let e=mH(t),r=Array.isArray(e.pageObj.panels)?e.pageObj.panels:[],n=t.title||Bn(ne(r[0]),"name")||"AI print template",i=t.number||`print_${Math.random().toString(36).slice(2,8)}`;return{title:n,number:i,desc:t.desc||"",pageObj:e.pageObj,pageObjStr:JSON.stringify(e.pageObj),printObj:e.printObj,printObjStr:JSON.stringify(e.printObj),dataApi:t.dataApi||""}}var aA="/* MICROI_WF_LINE_CONDITION_JSON",yH="MICROI_WF_LINE_CONDITION_JSON */",Tt=f.record(f.unknown());function Q(t,e=!1){return{content:[{type:"text",text:t}],isError:e}}function we(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Wp(t){return Array.isArray(t)?t.map(we).filter(e=>Object.keys(e).length>0):[]}function he(t,...e){for(let r of e){let n=t[r];if(Array.isArray(n))return Wp(n)}return[]}function S(t,...e){for(let r of e){let n=t[r];if(typeof n=="string"&&n.trim())return n.trim();if(typeof n=="number"||typeof n=="boolean")return String(n)}return""}function ge(t,...e){for(let r of e){let n=t[r];if(typeof n=="number")return n;if(typeof n=="string"&&n.trim()&&!Number.isNaN(Number(n)))return Number(n)}}function xc(t,...e){for(let r of e){let n=t[r];if(Array.isArray(n))return n.map(i=>typeof i=="string"?i:S(we(i),"name","Name","id","Id")).filter(Boolean);if(typeof n=="string"&&n.trim())return n.split(/[,,;;]/).map(i=>i.trim()).filter(Boolean)}return[]}function Zr(t,...e){for(let r of e)if(Object.prototype.hasOwnProperty.call(t,r))return t[r]}function yo(t){return t.trim().toLowerCase()}function xA(t,e){return`${yo(t)}::${yo(e)}`}function Uv(t){return["Id","CreateTime","UpdateTime","CreateUserId","CreateUserName","UpdateUserId","UpdateUserName","OsClient","IsDeleted"].some(e=>e.toLowerCase()===t.toLowerCase())}function bH(t){let e=t.trim();if(!e)return[];if(e.startsWith("["))try{let r=JSON.parse(e);if(Array.isArray(r))return r}catch{}return e.split(/[,;\n\uFF0C\uFF1B\u3001]+/).map(r=>r.trim()).filter(Boolean)}function ur(t,...e){for(let r of e){let n=Zr(t,r);if(n==null||n==="")continue;return(Array.isArray(n)?n:typeof n=="string"?bH(n):[n]).map(a=>{if(typeof a=="string"||typeof a=="number"||typeof a=="boolean")return{ref:String(a).trim()};let o=we(a);return{ref:S(o,"field","Field","fieldName","FieldName","name","Name","id","Id","fieldId","FieldId"),asName:S(o,"asName","AsName","alias","Alias")||void 0,type:S(o,"type","Type")||void 0,displayType:S(o,"displayType","DisplayType")||void 0,displaySelect:typeof o.displaySelect=="boolean"?o.displaySelect:typeof o.DisplaySelect=="boolean"?o.DisplaySelect:void 0,equal:typeof o.equal=="boolean"?o.equal:typeof o.Equal=="boolean"?o.Equal:void 0}}).filter(a=>a.ref)}return[]}function vH(){return{byTableAndRef:new Map,fieldsByTable:new Map}}function wA(t,e){let r=[e.tableId,e.tableName].filter(Boolean),n=[e.id,e.name,e.label].filter(Boolean);for(let i of r){for(let s of n)t.byTableAndRef.set(xA(i,s),e);let a=yo(i),o=t.fieldsByTable.get(a)||[];o.some(s=>s.id===e.id||yo(s.name)===yo(e.name))||(o.push(e),t.fieldsByTable.set(a,o))}}function oA(t,e,r){if(!(!e||!r))return t.byTableAndRef.get(xA(e,r))}function Nv(t,e){return t.fieldsByTable.get(yo(e))||[]}function _A(t,e,r){return{id:r,name:r,label:r,tableId:t,tableName:e,tableDescription:e,component:"Text",type:"varchar(255)"}}function dn(t){return Object.fromEntries(Object.entries(t).filter(([,e])=>e!=null&&e!==""))}function zv(){let t=Date.now().toString(36).toUpperCase().padStart(10,"0"),e=Math.random().toString(36).slice(2,18).toUpperCase().padEnd(16,"0");return`${t}${e}`.slice(0,26)}function ft(t,e){let r=[`## ${t}`,`- Code: ${e.Code}`,e.Msg?`- Message: ${e.Msg}`:"","","```json",JSON.stringify(e.Data??{},null,2),"```"].filter(Boolean);return Q(r.join(`
|
|
129
|
-
`),e.Code!==1)}function wc(t){if(!(t==null||t===""))return typeof t=="string"?t:JSON.stringify(t)}function xH(t){let e=we(t),r=we(e.Workload??e.workload??e.BackgroundWorkload??e.backgroundWorkload),n=[],i=ge(r,"ExpectedSeconds","expectedSeconds")??0,a=ge(r,"ExpectedItems","expectedItems","EstimatedRows","estimatedRows")??0,o=ge(r,"FanOutOperations","fanOutOperations","FanOut","fanOut")??0,s=ge(r,"ExternalCalls","externalCalls")??0;i>=120&&n.push(`\u9884\u8BA1\u8017\u65F6 ${i}s >= 120s`),a>=500&&n.push(`\u9884\u8BA1\u5904\u7406 ${a} \u6761 >= 500 \u6761`),o>=1e3&&n.push(`\u9884\u8BA1\u6247\u51FA ${o} \u4E2A\u5B50\u64CD\u4F5C >= 1000`),s>=100&&n.push(`\u9884\u8BA1\u5916\u90E8\u8C03\u7528 ${s} \u6B21 >= 100 \u6B21`),Un(r,"UnknownTotal","unknownTotal")===!0&&n.push("\u603B\u5DE5\u4F5C\u91CF\u672A\u77E5\u4E14\u53EF\u80FD\u957F\u65F6\u95F4\u8FD0\u884C");let c=[S(e,"Name","name"),S(e,"ApiEngineKey","apiEngineKey"),S(e,"V8Code","v8Code")].join(" ");return/(批量.{0,4}(导入|生成|修复|处理)|安装|初始化|全量同步|数据迁移|数据库备份|批量任务)/i.test(c)&&n.push("\u52A8\u4F5C\u8BED\u4E49\u5C5E\u4E8E\u5178\u578B\u957F\u4EFB\u52A1"),{required:n.length>0,reasons:n}}function wH(t){let e=we(t),r=we(e.Workload??e.workload??e.BackgroundWorkload??e.backgroundWorkload),n=S(r,"ExecutionMode","executionMode").trim().toLowerCase(),i=Un(r,"ClientChunked","clientChunked")===!0||n==="clientchunked"||n==="clientsequential",a=ge(r,"MaxItemsPerChunk","maxItemsPerChunk")??0,o=Un(r,"Resumable","resumable")===!0;return{declared:i,valid:i&&a>0&&o,maxItemsPerChunk:a,resumable:o}}var Kp="https://api.itdos.com",Mv="iTdos";function _H(t){let e=String(t.storeId||"").trim(),r=String(t.requestId||"").trim();if(!/^[A-Za-z0-9:._-]{1,100}$/u.test(e))throw new Error("storeId \u53EA\u80FD\u5305\u542B\u5B57\u6BCD\u3001\u6570\u5B57\u3001\u5192\u53F7\u3001\u70B9\u3001\u4E0B\u5212\u7EBF\u548C\u8FDE\u5B57\u7B26\uFF0C\u957F\u5EA6 1-100\u3002");if(!/^[A-Za-z0-9:._-]{8,100}$/u.test(r))throw new Error("requestId \u5FC5\u987B\u662F\u8C03\u7528\u65B9\u4FDD\u5B58\u5E76\u5728\u91CD\u8BD5\u65F6\u590D\u7528\u7684\u7A33\u5B9A\u5E42\u7B49 Id\uFF0C\u957F\u5EA6 8-100\u3002");let n=String(t.storeApiBase||Kp).trim(),i;try{i=new URL(n)}catch{throw new Error("storeApiBase \u5FC5\u987B\u662F\u6709\u6548\u7684 HTTP/HTTPS \u670D\u52A1\u6839\u5730\u5740\u3002")}if(i.protocol!=="https:"||i.username||i.password||i.pathname&&i.pathname!=="/"||i.search||i.hash||i.origin!==Kp)throw new Error(`storeApiBase \u4EC5\u5141\u8BB8\u543E\u7801\u5B98\u65B9\u5546\u57CE ${Kp}\uFF0C\u4E14\u4E0D\u80FD\u5305\u542B\u51ED\u636E\u3001\u8DEF\u5F84\u3001\u67E5\u8BE2\u3001\u7247\u6BB5\u6216\u81EA\u5B9A\u4E49\u7AEF\u53E3\u3002`);let a=Kp,o=String(t.storeOsClient||Mv).trim();if(o.toLowerCase()!==Mv.toLowerCase())throw new Error(`storeOsClient \u4EC5\u5141\u8BB8\u543E\u7801\u5B98\u65B9\u5546\u57CE\u79DF\u6237 ${Mv}\u3002`);return{ApiEngineKey:"import-microi-store-package",Title:`${t.operation==="update"?"\u66F4\u65B0":"\u5B89\u88C5"}\u5E94\u7528\uFF1A${String(t.appName||t.appId||e).trim()}`,Param:dn({StoreId:e,AppId:t.appId,AppName:t.appName,AppVersion:t.appVersion,StoreApiBase:a,StoreOsClient:o,InstallParentSysMenuId:t.installParentSysMenuId,ResumeInstall:t.resumeInstall!==!1}),Options:{IdempotencyKey:`mcp:store:${t.operation}:${e}:${r}`,ConcurrencyKey:"import-microi-store-package",MaxAttempts:3,RetryOnFailure:!0}}}function SH(t,e){let r=[],n=[];if(e==null||e==="")return{ok:!0,value:void 0,errors:r,warnings:n};let i;try{i=typeof e=="string"?JSON.parse(e):e}catch(s){return{ok:!1,errors:[`${t} \u4E0D\u662F\u5408\u6CD5 JSON \u6570\u7EC4\uFF1A${s instanceof Error?s.message:String(s)}`],warnings:n}}if(!Array.isArray(i))return{ok:!1,errors:[`${t} \u5FC5\u987B\u662F JSON \u6570\u7EC4`],warnings:n};let a=new Set,o=i.map((s,c)=>{let l=we(s),u=S(l,"Name","name");u||r.push(`${t}[${c}].Name \u4E0D\u80FD\u4E3A\u7A7A`);let p=xH(l),d=wH(l),h=l.RunBackground??l.runBackground??l.BackgroundTask??l.backgroundTask??l.IsBackgroundTask??l.isBackgroundTask,m=S(l,"ApiEngineKey","apiEngineKey");p.required&&h!==!0&&(d.declared&&!d.valid?r.push(`${t}[${c}] \u58F0\u660E\u5BA2\u6237\u7AEF\u5206\u7247\u65F6\u5FC5\u987B\u8BBE\u7F6E Workload.MaxItemsPerChunk > 0 \u4E14 Workload.Resumable=true`):d.valid?n.push(`${t}[${c}] \u5DF2\u58F0\u660E\u5BA2\u6237\u7AEF\u53EF\u6062\u590D\u5206\u7247\uFF0C\u5355\u7247\u6700\u591A ${d.maxItemsPerChunk} \u6761\uFF1B\u4FDD\u7559\u524D\u7AEF\u5206\u7247\u6267\u884C\uFF1A${p.reasons.join("\uFF1B")}`):m?(h=!0,n.push(`${t}[${c}] \u5DF2\u8BC6\u522B\u4E3A\u957F\u4EFB\u52A1\u5E76\u81EA\u52A8\u542F\u7528 RunBackground\uFF1A${p.reasons.join("\uFF1B")}`)):r.push(`${t}[${c}] \u5DF2\u8BC6\u522B\u4E3A\u957F\u4EFB\u52A1\uFF0C\u4F46\u7F3A\u5C11 ApiEngineKey\uFF1A${p.reasons.join("\uFF1B")}`));let y=we(l.BackgroundTaskOptions??l.backgroundTaskOptions);h===!0&&(!S(y,"IdempotencyKey","idempotencyKey")&&!xc(y,"IdempotencyKeyFields","idempotencyKeyFields").length&&n.push(`${t}[${c}] \u540E\u53F0\u4EFB\u52A1\u672A\u914D\u7F6E IdempotencyKey \u6216 IdempotencyKeyFields\uFF1B\u6D89\u53CA\u5199\u64CD\u4F5C\u65F6\u5FC5\u987B\u8865\u7A33\u5B9A\u4E1A\u52A1\u5E42\u7B49\u952E`),S(y,"BusinessTable","businessTable")&&(!S(y,"BusinessStatusField","businessStatusField")||!S(y,"BusinessTaskIdField","businessTaskIdField"))&&n.push(`${t}[${c}] \u5DF2\u5173\u8054\u4E1A\u52A1\u8868\uFF0C\u4F46\u7F3A\u5C11 BusinessStatusField/BusinessTaskIdField`));let g=S(l,"TargetSysMenuId","targetSysMenuId"),x=t==="PageTabs"&&!!g;!S(l,"V8Code","v8Code")&&!S(l,"Url","url")&&!(h&&m)&&!x&&r.push(`${t}[${c}] \u5FC5\u987B\u914D\u7F6E V8Code\u3001Url\u3001\u5173\u8054\u6A21\u5757 TargetSysMenuId\uFF0C\u6216\u540E\u53F0\u4EFB\u52A1 ApiEngineKey`);let b=S(l,"Id","id")||zv();S(l,"Id","id")||n.push(`${t}[${c}] \u672A\u4F20 Id\uFF0C\u5DF2\u81EA\u52A8\u751F\u6210 ${b}`),a.has(b)&&r.push(`${t} \u4E2D\u5B58\u5728\u91CD\u590D Id\uFF1A${b}`),a.add(b);let v=S(l,"V8CodeShow","v8CodeShow");return v&&!v.includes("V8.Result")&&n.push(`${t}[${c}].V8CodeShow \u5EFA\u8BAE\u663E\u5F0F\u8D4B\u503C V8.Result=true/false`),dn({...l,Id:b,Sort:ge(l,"Sort","sort")??c*10,Name:u,Icon:S(l,"Icon","icon")||void 0,BtnStyle:S(l,"BtnStyle","btnStyle")||void 0,IsVisible:l.IsVisible??l.isVisible??!0,ShowRow:t==="MoreBtns"?l.ShowRow??l.showRow??!0:l.ShowRow??l.showRow,V8CodeShow:v||void 0,V8Code:S(l,"V8Code","v8Code")||void 0,Url:S(l,"Url","url")||void 0,RunBackground:h===void 0?void 0:!!h,BackgroundTask:l.BackgroundTask??l.backgroundTask??void 0,IsBackgroundTask:l.IsBackgroundTask??l.isBackgroundTask??void 0,ApiEngineKey:m||void 0,Workload:Object.keys(we(l.Workload??l.workload)).length?we(l.Workload??l.workload):void 0,BackgroundTaskOptions:Object.keys(y).length?y:void 0,TargetSysMenuId:g||void 0})});return{ok:r.length===0,value:JSON.stringify(o),errors:r,warnings:n}}function bo(t){let e={...t},r=[],n=[];(t.DiyConfig!==void 0||t.diyConfig!==void 0)&&(r.push("DiyConfig \u5DF2\u5E9F\u5F03\uFF1B\u8BF7\u65B0\u589E\u4E13\u7528\u7269\u7406\u5B57\u6BB5\uFF0C\u5E76\u901A\u8FC7 diy_field \u5143\u6570\u636E\u66B4\u9732\u914D\u7F6E\u63A7\u4EF6\u3002\u8DE8\u7AEF\u89C6\u56FE\u8BF7\u4F7F\u7528 sys_menu.ViewSchema\u3002"),delete e.DiyConfig,delete e.diyConfig);let i={MoreBtns:["MoreBtns","moreBtns"],FormBtns:["FormBtns","formBtns"],BatchSelectMoreBtns:["BatchSelectMoreBtns","batchSelectMoreBtns"],PageTabs:["PageTabs","pageTabs"],ExportMoreBtns:["ExportMoreBtns","exportMoreBtns"],PageBtns:["PageBtns","pageBtns"]};for(let[c,l]of Object.entries(i)){let u=l.find(d=>t[d]!==void 0);if(!u)continue;let p=SH(c,t[u]);r.push(...p.errors),n.push(...p.warnings),p.ok&&p.value!==void 0&&(e[c]=p.value)}let a=[["MenuBadgeEnabled","menuBadgeEnabled"],["EnableViewSchema","enableViewSchema"],["ViewConfigVersion","viewConfigVersion"]];for(let[c,l]of a){if(t[c]===void 0&&t[l]===void 0)continue;let u=ge(t,c,l);u!==void 0&&(e[c]=c.endsWith("Enabled")?u===1?1:0:u),delete e[l]}let o=[["MenuBadgeApiEngineKey","menuBadgeApiEngineKey"],["ViewSchemaVersion","viewSchemaVersion"]];for(let[c,l]of o)t[c]===void 0&&t[l]===void 0||(e[c]=S(t,c,l),delete e[l]);let s=["ViewSchema","viewSchema"].find(c=>t[c]!==void 0);if(s){let c=Zv(t[s]);r.push(...c.errors),n.push(...c.warnings),delete e.viewSchema,c.value!==void 0&&(e.ViewSchema=c.value)}return{data:e,errors:r,warnings:n}}function Un(t,...e){for(let r of e){let n=t[r];if(typeof n=="boolean")return n;if(typeof n=="number")return n!==0;if(typeof n=="string"&&n.trim()){let i=n.trim().toLowerCase();if(["true","1","yes"].includes(i))return!0;if(["false","0","no"].includes(i))return!1}}}function sA(t,e,r,n){let i=Zr(t,"v8Unlimited","V8Unlimited");if(i==null||i==="")return;let a=Un(t,"v8Unlimited","V8Unlimited");if(a===void 0){r.push(`${e}.v8Unlimited \u5FC5\u987B\u662F boolean \u6216 0/1`);return}return a&&n.push(`${e}.v8Unlimited=true \u4F1A\u53D6\u6D88\u8BE5\u63A5\u53E3\u6216\u8BE5\u8868\u540E\u7AEF V8 \u4E8B\u4EF6\u7684\u5355\u6B21 Jint \u8D85\u65F6\u3001\u8BED\u53E5\u3001\u9012\u5F52\u548C\u7D2F\u8BA1\u5206\u914D\u9884\u7B97\uFF1B\u4EC5\u5728\u4E1A\u52A1\u660E\u786E\u8981\u6C42\u5355\u4E8B\u52A1\u4E14\u5DF2\u8BC4\u4F30\u6570\u636E\u5E93\u9501\u3001\u56DE\u6EDA\u3001\u8FDE\u63A5\u8D85\u65F6\u4E0E\u8FDB\u7A0B\u5185\u5B58\u98CE\u9669\u65F6\u5F00\u542F\u3002\u8FDB\u7A0B\u5E38\u9A7B\u5185\u5B58\u4FDD\u62A4\u4ECD\u751F\u6548\uFF0C\u4E14\u4E0D\u4F1A\u5411\u5D4C\u5957\u63A5\u53E3\u7EE7\u627F\u3002`),a}var EH=["Detail","Edit","List","Card"],kH=["PC","Mobile","All"],TH=["ApiEngine","OpenDetail","OpenList","OpenForm","Navigate","Dial","Scan","Map","Refresh","Back","Copy"],CH=new Set(["v8code","v8codeshow","script","javascript","eval","onclick","function"]);function jv(t,e){let r=String(t??"").trim().toLowerCase();return e.find(n=>n.toLowerCase()===r)||""}function pn(t,...e){let r=new Set(e.map(i=>i.toLowerCase()));return Object.entries(t).find(([i])=>r.has(i.toLowerCase()))?.[1]}function Fv(t,e="ViewSchema"){if(Array.isArray(t)){for(let r=0;r<t.length;r+=1){let n=Fv(t[r],`${e}[${r}]`);if(n)return n}return""}if(!t||typeof t!="object")return"";for(let[r,n]of Object.entries(t)){if(CH.has(r.toLowerCase()))return`${e}.${r}`;let i=Fv(n,`${e}.${r}`);if(i)return i}return""}function Lv(t,e,r=0){if(t==null)return[];if(r>4)return[`${e} \u7684 SuccessActions \u5D4C\u5957\u4E0D\u80FD\u8D85\u8FC7 4 \u5C42`];if(!Array.isArray(t))return[`${e} \u5FC5\u987B\u662F JSON \u6570\u7EC4`];if(t.length>50)return[`${e} \u6700\u591A\u5141\u8BB8 50 \u4E2A\u52A8\u4F5C`];let n=[];return t.forEach((i,a)=>{let o=we(i);if(!Object.keys(o).length){n.push(`${e}[${a}] \u5FC5\u987B\u662F JSON \u5BF9\u8C61`);return}let s=jv(pn(o,"ActionType","Type"),TH);if(!s){n.push(`${e}[${a}].ActionType \u4E0D\u53D7\u652F\u6301`);return}s==="ApiEngine"&&!S(o,"ApiEngineKey","apiEngineKey")&&n.push(`${e}[${a}] \u4F7F\u7528 ApiEngine \u65F6\u5FC5\u987B\u914D\u7F6E ApiEngineKey`);let c=pn(o,"SuccessActions");n.push(...Lv(c,`${e}[${a}].SuccessActions`,r+1))}),n}function Zv(t){let e=[],r=[];if(t==null||t==="")return{ok:!0,value:void 0,errors:e,warnings:r};let n=t;try{typeof n=="string"&&(n=JSON.parse(n)),typeof n=="string"&&(n=JSON.parse(n))}catch(c){return{ok:!1,errors:[`ViewSchema \u4E0D\u662F\u5408\u6CD5 JSON\uFF1A${c instanceof Error?c.message:String(c)}`],warnings:r}}if(!n||typeof n!="object"||Array.isArray(n))return{ok:!1,errors:["ViewSchema \u5FC5\u987B\u662F JSON \u5BF9\u8C61"],warnings:r};let i=Fv(n);i&&e.push(`ViewSchema \u4E0D\u5141\u8BB8\u5305\u542B\u53EF\u6267\u884C\u524D\u7AEF\u811A\u672C\u5B57\u6BB5\uFF1A${i}`);let o=pn(n,"Views");o!==void 0&&!Array.isArray(o)?e.push("ViewSchema.Views \u5FC5\u987B\u662F JSON \u6570\u7EC4"):Array.isArray(o)?(o.length>100&&e.push("ViewSchema.Views \u6700\u591A\u5141\u8BB8 100 \u4E2A\u89C6\u56FE"),o.forEach((c,l)=>{let u=we(c);if(!Object.keys(u).length){e.push(`ViewSchema.Views[${l}] \u5FC5\u987B\u662F JSON \u5BF9\u8C61`);return}jv(pn(u,"Scene"),EH)||e.push(`ViewSchema.Views[${l}].Scene \u4E0D\u53D7\u652F\u6301`);let p=pn(u,"Device");p!==void 0&&!jv(p,kH)&&e.push(`ViewSchema.Views[${l}].Device \u4E0D\u53D7\u652F\u6301`);let d=pn(u,"Layout","LayoutJson");if(typeof d=="string")try{d=JSON.parse(d)}catch{e.push(`ViewSchema.Views[${l}].Layout \u4E0D\u662F\u5408\u6CD5 JSON`);return}if(d==null)return;let h=we(d);if(!Object.keys(h).length&&(typeof d!="object"||Array.isArray(d))){e.push(`ViewSchema.Views[${l}].Layout \u5FC5\u987B\u662F JSON \u5BF9\u8C61`);return}e.push(...Lv(pn(h,"Actions","ActionSchema"),`ViewSchema.Views[${l}].Layout.Actions`));let m=pn(h,"Blocks","Sections");m!==void 0&&!Array.isArray(m)?e.push(`ViewSchema.Views[${l}].Layout.Blocks \u5FC5\u987B\u662F JSON \u6570\u7EC4`):Array.isArray(m)&&(m.length>100&&e.push(`ViewSchema.Views[${l}].Layout.Blocks \u6700\u591A\u5141\u8BB8 100 \u4E2A\u533A\u5757`),m.forEach((y,g)=>{let x=we(y);e.push(...Lv(pn(x,"Actions"),`ViewSchema.Views[${l}].Layout.Blocks[${g}].Actions`))}))})):r.push("ViewSchema.Views \u4E3A\u7A7A\uFF0C\u5BA2\u6237\u7AEF\u5C06\u4F7F\u7528\u73B0\u6709\u6A21\u5757\u548C\u8868\u5355\u914D\u7F6E\u3002");let s=JSON.stringify(n);return Buffer.byteLength(s,"utf8")>512*1024&&e.push("ViewSchema \u4E0D\u80FD\u8D85\u8FC7 512KB"),{ok:e.length===0,value:s,errors:e,warnings:r}}function cA(t,e){let r=[],n=t.toLowerCase();if(n==="keyvalue"){let i=S(e,"data","options"),a=i?i.split(/[,,;;\n]/).map(o=>o.trim()).filter(Boolean).map(o=>{let[s,c]=o.split("|");return{Key:(s||"").trim(),Value:(c||s||"").trim()}}):Wp(e.items).map(o=>({Key:S(o,"Key","key"),Value:S(o,"Value","label","name")}));return{data:JSON.stringify(a),config:{DataSource:"KeyValue",SelectLabel:"Value",SelectSaveField:"Key",SelectSaveFormat:"Text",EnableSearch:!1,DataSourceSqlRemote:!1},warnings:r}}if(n==="data"){let i=S(e,"data","options"),a=i?i.split(/[,,;;\n]/).map(o=>o.trim()).filter(Boolean):Array.isArray(e.items)?e.items:[];return{data:JSON.stringify(a),config:{DataSource:"Data",SelectSaveFormat:"Text",EnableSearch:!1,DataSourceSqlRemote:!1},warnings:r}}if(n==="sql"){let i=S(e,"sql","Sql");return i||r.push("SQL \u6570\u636E\u6E90\u7F3A\u5C11 sql"),{config:{DataSource:"Sql",Sql:i,SelectLabel:S(e,"selectLabel","SelectLabel")||"Name",SelectSaveField:S(e,"selectSaveField","SelectSaveField")||"Id",DataSourceSqlRemote:e.dataSourceSqlRemote??e.DataSourceSqlRemote??!0,EnableSearch:e.enableSearch??e.EnableSearch??!0},warnings:r}}if(n==="apiengine"){let i=S(e,"apiEngineKey","DataSourceApiEngineKey");return i||r.push("\u63A5\u53E3\u5F15\u64CE\u6570\u636E\u6E90\u7F3A\u5C11 apiEngineKey"),{config:{DataSource:"ApiEngine",DataSourceApiEngineKey:i,SelectLabel:S(e,"selectLabel")||"name",SelectSaveField:S(e,"selectSaveField")||"id"},warnings:r}}if(n==="datasource"){let i=S(e,"dataSourceId","DataSourceId");return i||r.push("\u6570\u636E\u6E90\u5F15\u64CE\u914D\u7F6E\u7F3A\u5C11 dataSourceId"),{config:{DataSource:"DataSource",DataSourceId:i,SelectLabel:S(e,"selectLabel")||"Name",SelectSaveField:S(e,"selectSaveField")||"Id"},warnings:r}}return n==="autonumber"?{config:{AutoNumberFixed:S(e,"prefix","AutoNumberFixed"),AutoNumberLength:ge(e,"length","AutoNumberLength")??4},warnings:r}:n==="datetime"?{config:{DateTimeType:S(e,"dateTimeType","DateTimeType")||"datetime"},warnings:r}:n==="joinform"?{config:{JoinForm:{TableId:S(e,"tableId"),TableName:S(e,"tableName"),JoinFieldName:S(e,"joinFieldName")||"Name"}},warnings:r}:(r.push(`\u672A\u77E5 sourceType: ${t}\uFF0C\u5DF2\u8FD4\u56DE\u7A7A\u914D\u7F6E`),{config:{},warnings:r})}function Dv(t,e){let r=Jr(t);return dn({Id:t.id,AsName:e?.asName||"",Name:t.name,Label:t.label||t.name,TableId:t.tableId,TableName:t.tableName,TableDescription:t.tableDescription||t.tableName,DisplayType:e?.displayType||(qv.has(r)||Qi(t)||r==="numbertext"?"In":"Out"),DisplaySelect:e?.displaySelect??["opentable","joinform","department","selecttree"].includes(r),Equal:e?.equal??(qv.has(r)||r==="numbertext"?!0:void 0),IsVisible:!0})}function ho(t,e,r,n,i){return n.map(a=>{let o=oA(t,e,a.ref)||oA(t,r,a.ref)||(Uv(a.ref)?_A(e,r,a.ref):void 0);if(!o)throw new Error(`${i}: unknown field "${a.ref}" on table "${r||e}"`);return{meta:o,ref:a}})}function et(t,...e){for(let r of e){let n=Zr(t,r);if(!(n==null||n===""))return typeof n=="string"?n:JSON.stringify(n)}return""}var $H=new Set(["id","osclient","isdeleted","createuserid","updateuserid","deleteuserid","tenantid","storeid","userid","userids","roleid","roleids","parentid","parentids","class","code","enname","endescription"]),SA=new Set(["button","divider","collapsegroup","tabs","alert","statictext","html","devcomponent"]),AH=new Set(["textarea","richtext","codeeditor","jsontable","imgupload","fileupload","tablechild","map","maparea","jointable","opentable","treecheckbox","transfer"]),PH=new Set(["text","textarea","select","multipleselect","radio","checkbox","datetime","date","numbertext","autonumber","switch","department","address","cascader","selecttree","opentable","joinform","autocomplete","taginput"]),qv=new Set(["select","multipleselect","radio","checkbox","switch","department","selecttree","opentable","joinform","cascader"]);function Ur(t){return(t||"").trim().toLowerCase()}function pr(t){return`${t.name||""} ${t.label||""} ${t.component||""} ${t.type||""}`.toLowerCase()}function qe(t,e){return e.some(r=>t.includes(r.toLowerCase()))}function Jr(t){return Ur(t.component||"Text")}function IH(t){return SA.has(Jr(t))}function RH(t){return AH.has(Jr(t))}function OH(t){let e=t.name||"",r=Ur(e).replace(/[_\-\s]+/g,"");return!!($H.has(r)||/^(.*id|.*ids|.*idlist|.*guid)$/.test(r)&&!/idcard|identity|cardid/.test(r)||/Id$|ID$|Ids$|IDs$|Guid$/u.test(e)&&!/IdCard|IDCard|Identity|CardId/u.test(e))}function _c(t){return Uv(t.name)&&!["CreateTime","UpdateTime","UserName"].some(e=>e.toLowerCase()===t.name.toLowerCase())||OH(t)||IH(t)||RH(t)?!0:Jr(t).includes("hidden")}function vo(t){let e=new Set;return t.filter(r=>{let n=r.id||r.name;return!n||e.has(n)?!1:(e.add(n),!0)})}function Zn(t,e){return t.map((r,n)=>({field:r,index:n,score:e(r)})).sort((r,n)=>n.score-r.score||r.index-n.index).map(r=>r.field)}function Jv(t){let e=Ur(t.type);return Jr(t)==="numbertext"||e.startsWith("decimal")||e==="int"||e==="bigint"}function Qi(t){let e=pr(t);return Jr(t)==="datetime"||qe(e,["time","date","\u65E5\u671F","\u65F6\u95F4"])}function NH(t){let e=Jr(t),r=qv.has(e)||e==="numbertext"||e==="rate"||e==="progress";return{ref:t.name,displayType:r||Qi(t)?"In":"Out",displaySelect:["opentable","joinform","department","selecttree"].includes(e),equal:r?!0:void 0}}function lA(t){let e=pr(t),r=0;return qe(e,["name","title","no","code","account","phone","mobile","email","\u540D\u79F0","\u6807\u9898","\u7F16\u53F7","\u8D26\u53F7","\u7535\u8BDD","\u624B\u673A","\u90AE\u7BB1"])&&(r+=50),qe(e,["status","state","type","category","level","class","\u72B6\u6001","\u7C7B\u578B","\u5206\u7C7B","\u7B49\u7EA7"])&&(r+=45),qe(e,["customer","member","user","owner","\u8D1F\u8D23\u4EBA","\u5BA2\u6237","\u4F1A\u5458","\u7528\u6237","\u8054\u7CFB\u4EBA"])&&(r+=35),Qi(t)&&(r+=25),Jv(t)&&!qe(e,["phone","mobile","tel","\u7535\u8BDD","\u624B\u673A"])&&(r+=15),Jr(t)==="textarea"&&(r-=25),r}function MH(t){let e=pr(t),r=0;return qe(e,["name","title","no","code","\u540D\u79F0","\u6807\u9898","\u7F16\u53F7"])&&(r+=70),qe(e,["status","state","type","category","\u72B6\u6001","\u7C7B\u578B","\u5206\u7C7B"])&&(r+=45),qe(e,["customer","member","user","owner","phone","mobile","\u5BA2\u6237","\u4F1A\u5458","\u7528\u6237","\u8D1F\u8D23\u4EBA","\u7535\u8BDD","\u624B\u673A"])&&(r+=35),qe(e,["amount","money","price","total","count","qty","\u91D1\u989D","\u4EF7\u683C","\u603B\u989D","\u6570\u91CF","\u79EF\u5206","\u4F59\u989D"])&&(r+=30),Qi(t)&&(r+=15),Jr(t)==="autonumber"&&(r+=55),r}function DH(t){return vo(t.filter(_c))}function Gp(t){let e=t.filter(n=>!_c(n)),r=e.length?e:t;return vo(Zn(r,MH)).slice(0,Math.min(12,r.length))}function zH(t){let e=t.filter(n=>!_c(n)&&PH.has(Jr(n))),r=Zn(e,lA).filter(n=>lA(n)>0);return vo(r.length?r:e).slice(0,Math.min(8,e.length))}function jH(t){let e=t.filter(r=>!_c(r)&&(Qi(r)||Jv(r)||Ur(r.name)==="sort"));return vo(Zn(e,r=>{let n=pr(r);return qe(n,["update","\u4FEE\u6539"])?80:qe(n,["create","\u521B\u5EFA"])?75:Ur(r.name)==="sort"?70:qe(n,["amount","money","price","total","count","\u91D1\u989D","\u4EF7\u683C","\u6570\u91CF"])?60:20})).slice(0,Math.min(8,e.length))}function FH(t){let e=["phone","mobile","tel","status","state","sort","rate","level","\u7535\u8BDD","\u624B\u673A","\u72B6\u6001","\u6392\u5E8F","\u7B49\u7EA7"],r=t.filter(n=>{let i=pr(n);return!_c(n)&&Jv(n)&&!qe(i,e)&&qe(i,["amount","money","price","total","count","qty","score","point","balance","\u91D1\u989D","\u4EF7\u683C","\u603B\u989D","\u6570\u91CF","\u79EF\u5206","\u4F59\u989D","\u9762\u79EF","\u91CD\u91CF"])});return vo(Zn(r,n=>qe(pr(n),["amount","money","price","total","\u91D1\u989D","\u4EF7\u683C","\u603B\u989D"])?80:40)).slice(0,6)}function LH(t){let e=Gp(t),r=Zn(e,a=>qe(pr(a),["name","title","no","code","\u540D\u79F0","\u6807\u9898","\u7F16\u53F7"])?100:0)[0],n=Zn(e.filter(a=>a!==r),a=>qe(pr(a),["status","state","type","category","\u72B6\u6001","\u7C7B\u578B","\u5206\u7C7B"])?80:0),i=e.filter(a=>a!==r&&!n.slice(0,1).includes(a));return vo([r,...n.slice(0,1),...i].filter(Boolean)).slice(0,4)}function qH(t){return Zn(Gp(t),e=>qe(pr(e),["status","state","type","category","level","\u72B6\u6001","\u7C7B\u578B","\u5206\u7C7B","\u7B49\u7EA7"])?100:0).filter(e=>qe(pr(e),["status","state","type","category","level","\u72B6\u6001","\u7C7B\u578B","\u5206\u7C7B","\u7B49\u7EA7"])).slice(0,2)}function VH(t){return Zn(Gp(t),e=>{let r=pr(e);return qe(r,["amount","money","price","total","count","qty","\u79EF\u5206","\u4F59\u989D","\u91D1\u989D","\u4EF7\u683C","\u6570\u91CF"])?90:Qi(e)?60:0}).filter(e=>{let r=pr(e);return Qi(e)||qe(r,["amount","money","price","total","count","qty","\u79EF\u5206","\u4F59\u989D","\u91D1\u989D","\u4EF7\u683C","\u6570\u91CF"])}).slice(0,3)}function BH(t,e,r){let n=t.length?t:[_A(e,r,"CreateTime")],i=n.find(a=>Ur(a.name)==="createtime")||n.find(a=>Ur(a.name)==="updatetime")||n.find(a=>Ur(a.name)==="sort");if(i)return JSON.stringify([{Id:i.id,Name:i.name,Type:Ur(i.name)==="sort"?"ASC":"DESC",Sort:0}])}function UH(t,e,r,n){let i=Zr(t,"DefaultOrderBy");if(i!=null&&i!=="")return typeof i=="string"?i:JSON.stringify(i);let a=Zr(t,"defaultOrderBy");if(a!=null&&a!==""){let s=Array.isArray(a)||typeof a=="string"&&a.trim().startsWith("[")?ur({value:a},"value"):[{ref:String(a).trim(),type:"DESC"}];return JSON.stringify(ho(e,r,n,s,"module.defaultOrderBy").map(({meta:c,ref:l},u)=>({Id:c.id,Name:c.name,Type:l.type||"DESC",Sort:u})))}let o=ur(t,"orderBy","OrderBy","defaultSort","DefaultSort","sortBy","SortBy");if(o.length)return JSON.stringify(ho(e,r,n,o,"module.defaultOrderBy").map(({meta:s,ref:c},l)=>({Id:s.id,Name:s.name,Type:c.type||"DESC",Sort:l})))}function ZH(t,e,r,n){if(!r&&!n)return{};let i=Nv(e,r).length?Nv(e,r):Nv(e,n),a={},o=ur(t,"searchFields","SearchFields","searchFieldNames","SearchFieldNames"),s=o.length?ho(e,r,n,o,"module.searchFields"):zH(i).map(h=>({meta:h,ref:NH(h)}));!et(t,"searchFieldIds","SearchFieldIds")&&s.length&&(a.SearchFieldIds=JSON.stringify(s.map(({meta:h,ref:m})=>Dv(h,m))));let c=ur(t,"listFields","ListFields","tableFields","TableFields","columns","Columns"),l=c.length?ho(e,r,n,c,"module.listFields"):Gp(i).map(h=>({meta:h,ref:{ref:h.name}}));!et(t,"tableDiyFieldIds","TableDiyFieldIds")&&l.length&&(a.TableDiyFieldIds=JSON.stringify(l.map(({meta:h})=>h.id))),!et(t,"selectFields","SelectFields")&&l.length&&(a.SelectFields=JSON.stringify(l.map(({meta:h,ref:m})=>Dv(h,m))));let u=[{canonical:"SortFieldIds",explicitKeys:["sortFieldIds","SortFieldIds"],refKeys:["sortFields","SortFields"]},{canonical:"NotShowFields",explicitKeys:["notShowFields","NotShowFields"],refKeys:["hiddenFields","HiddenFields","notShowFieldsByName","NotShowFieldsByName"]},{canonical:"InTableEditFields",explicitKeys:["inTableEditFields","InTableEditFields"],refKeys:["editableFields","EditableFields","inTableEditFieldsByName","InTableEditFieldsByName"]},{canonical:"MobileListFields",explicitKeys:["mobileListFields","MobileListFields"],refKeys:["mobileFields","MobileFields"],objectArray:!0},{canonical:"CardTitleTagFields",explicitKeys:["cardTitleTagFields","CardTitleTagFields"],refKeys:["cardTitleFields","CardTitleFields"],objectArray:!0},{canonical:"CardBottomTagFields",explicitKeys:["cardBottomTagFields","CardBottomTagFields"],refKeys:["cardBottomFields","CardBottomFields"],objectArray:!0}];for(let h of u){if(et(t,...h.explicitKeys))continue;let m=ur(t,...h.refKeys),y={SortFieldIds:jH(i),NotShowFields:DH(i),MobileListFields:LH(i),CardTitleTagFields:qH(i),CardBottomTagFields:VH(i),InTableEditFields:[]};if(!m.length&&!y[h.canonical]?.length)continue;let g=m.length?ho(e,r,n,m,`module.${h.canonical}`):y[h.canonical].map(x=>({meta:x,ref:{ref:x.name}}));a[h.canonical]=JSON.stringify(h.objectArray?g.map(({meta:x,ref:b})=>Dv(x,b)):g.map(({meta:x})=>x.id))}let p=ur(t,"statisticsFieldNames","StatisticsFieldNames","statFields","StatFields");if(!et(t,"statisticsFields","StatisticsFields")){let h=p.length?ho(e,r,n,p,"module.statisticsFields"):FH(i).map(m=>({meta:m,ref:{ref:m.name,type:"Sum"}}));h.length&&(a.StatisticsFields=JSON.stringify(h.map(({meta:m,ref:y})=>({Id:m.id,Type:y.type||"Sum"}))))}let d=UH(t,e,r,n)||(et(t,"DefaultOrderBy","defaultOrderBy")?void 0:BH(i,r,n));return d&&(a.DefaultOrderBy=d),a}function JH(t,e,r){let n=Wp(we(e).Tables);for(let i of n){let a=S(i,"Id","id"),o=S(i,"Name","name");if(!a||!o)continue;r?.set(o.toLowerCase(),a);let s=Zr(i,"_Fields","Fields","fields"),c=Array.isArray(s)?Wp(s):[];for(let l of c){let u=S(l,"Id","id"),p=S(l,"Name","name");!u||!p||wA(t,{id:u,name:p,label:S(l,"Label","label")||p,tableId:a,tableName:o,tableDescription:S(i,"Description","description")||o,component:S(l,"Component","component")||"Text",type:S(l,"Type","type")||"varchar(255)"})}}}function EA(t){return Ur(S(t,"component","Component")||"Text")}function HH(t){return`${S(t,"name","Name")} ${S(t,"label","Label")} ${S(t,"component","Component")}`.toLowerCase()}function KH(t,e){let r=HH(t),n=EA(t);return["imgupload","fileupload","richtext","codeeditor","jsontable","tablechild","map","maparea","textarea"].includes(n)||qe(r,["remark","note","content","file","image","attach","map","\u5907\u6CE8","\u8BF4\u660E","\u5185\u5BB9","\u9644\u4EF6","\u56FE\u7247","\u5730\u56FE"])?"attachment":qe(r,["phone","mobile","email","address","city","contact","\u8054\u7CFB\u4EBA","\u7535\u8BDD","\u624B\u673A","\u90AE\u7BB1","\u5730\u5740","\u57CE\u5E02"])?"contact":qe(r,["status","state","type","category","amount","money","price","count","date","time","\u72B6\u6001","\u7C7B\u578B","\u5206\u7C7B","\u91D1\u989D","\u4EF7\u683C","\u6570\u91CF","\u65F6\u95F4","\u65E5\u671F"])?"business":e<8?"basic":"extra"}function kA(t){let e=he(t,"fields","Fields"),r=Zr(t,"tabs","Tabs"),n=new Map,i=ge(t,"column","Column")??(e.length>6?2:void 0);if(r!=null&&r!=="")return{fieldTabs:n,column:i};let a=e.filter(l=>!SA.has(EA(l)));if(a.length<=12)return{fieldTabs:n,column:i};let o={basic:{Name:"\u57FA\u7840\u4FE1\u606F",Icon:"fas fa-id-card",Sort:10},contact:{Name:"\u8054\u7CFB\u4FE1\u606F",Icon:"fas fa-address-book",Sort:20},business:{Name:"\u4E1A\u52A1\u4FE1\u606F",Icon:"fas fa-briefcase",Sort:30},attachment:{Name:"\u9644\u4EF6\u5907\u6CE8",Icon:"fas fa-paperclip",Sort:40},extra:{Name:"\u6269\u5C55\u4FE1\u606F",Icon:"fas fa-layer-group",Sort:50}},s=new Set;return a.forEach((l,u)=>{let p=S(l,"name","Name");if(!p||S(l,"tab","Tab"))return;let d=KH(l,u);n.set(p,d),s.add(d)}),{tabs:["basic","contact","business","attachment","extra"].filter(l=>s.has(l)).map(l=>({Id:l,Name:o[l].Name,Icon:o[l].Icon,Sort:o[l].Sort})),fieldTabs:n,column:i}}function uA(t){let e=[],r=[],n=[],i=he(t,"roles","Roles"),a=he(t,"tables","Tables"),o=he(t,"engines","Engines"),s=he(t,"modules","Modules"),c=he(t,"events","Events"),l=he(t,"dataSources","DataSources"),u=he(t,"pages","Pages"),p=he(t,"printTemplates","PrintTemplates"),d=he(t,"workflows","Workflows"),h=he(t,"jobs","Jobs"),m=he(t,"permissions","Permissions"),y=new Map;return!a.length&&!o.length&&!s.length&&!u.length&&r.push("Manifest \u672A\u58F0\u660E tables/engines/modules/pages\uFF0C\u53EF\u80FD\u4E0D\u662F\u5B8C\u6574\u7CFB\u7EDF\u8BA1\u5212"),i.forEach(g=>n.push(`save_role ${S(g,"name","Name")}`)),a.forEach((g,x)=>{let b=S(g,"name","Name");b||e.push(`tables[${x}].name \u4E0D\u80FD\u4E3A\u7A7A`),sA(g,`tables[${x}]`,e,r),n.push(`create_table ${b||`(index ${x})`}`),kA(g).tabs?.length&&r.push(`table ${b||`(index ${x})`} has many fields; generator will create diy_table.Tabs and assign empty field Tab values automatically`),b&&y.set(b.toLowerCase(),new Set),he(g,"fields","Fields").forEach((E,T)=>{let k=S(E,"name","Name"),A=S(E,"label","Label");k||e.push(`tables[${x}].fields[${T}].name \u4E0D\u80FD\u4E3A\u7A7A`),A||e.push(`tables[${x}].fields[${T}].label \u4E0D\u80FD\u4E3A\u7A7A`),b&&k&&y.get(b.toLowerCase())?.add(k.toLowerCase()),b&&A&&y.get(b.toLowerCase())?.add(A.toLowerCase()),n.push(`add_field ${b}.${k}`)});let w=new Set(he(g,"fields","Fields").map(E=>S(E,"name","Name").toLowerCase()).filter(Boolean));["id","createtime","updatetime","createuser","osclient"].forEach(E=>w.add(E)),he(g,"indexes","Indexes").forEach((E,T)=>{let k=xc(E,"columns","Columns");k.length||e.push(`tables[${x}].indexes[${T}].columns \u81F3\u5C11\u9700\u8981\u4E00\u4E2A\u5B57\u6BB5`);for(let A of k)w.has(A.toLowerCase())||e.push(`tables[${x}].indexes[${T}] references unknown physical field "${A}" on table "${b}"`);k.some((A,M)=>k.findIndex(P=>P.toLowerCase()===A.toLowerCase())!==M)&&e.push(`tables[${x}].indexes[${T}] \u5305\u542B\u91CD\u590D\u5B57\u6BB5`),n.push(`create_index ${b}.${S(E,"name","Name")||k.join("_")}`)})}),l.forEach(g=>n.push(`save_data_source ${S(g,"dataSourceKey","DataSourceKey")}`)),o.forEach((g,x)=>{let b=S(g,"apiEngineKey","ApiEngineKey");b||e.push(`engines[${x}].apiEngineKey \u4E0D\u80FD\u4E3A\u7A7A`),sA(g,`engines[${x}]`,e,r),n.push(`upsert_engine ${b}`)}),c.forEach(g=>n.push(`save_event ${S(g,"formEngineKey","FormEngineKey")}/${S(g,"eventType","EventType")}`)),s.forEach(g=>{let x=bo(g);e.push(...x.errors),r.push(...x.warnings);let b=S(g,"table","tableName","diyTableName","DiyTableName"),v=S(g,"name","Name");if(b&&y.has(b.toLowerCase())){let w=y.get(b.toLowerCase())||new Set,E=[["listFields",ur(g,"listFields","ListFields","tableFields","TableFields","columns","Columns")],["searchFields",ur(g,"searchFields","SearchFields","searchFieldNames","SearchFieldNames")],["sortFields",ur(g,"sortFields","SortFields")],["hiddenFields",ur(g,"hiddenFields","HiddenFields","notShowFieldsByName","NotShowFieldsByName")],["mobileFields",ur(g,"mobileFields","MobileFields")]];for(let[T,k]of E)for(let A of k)!w.has(A.ref.toLowerCase())&&!Uv(A.ref)&&e.push(`modules.${v||b}.${T} references unknown field "${A.ref}" on table "${b}"`)}b&&!ur(g,"listFields","ListFields","tableFields","TableFields","columns","Columns").length&&!et(g,"TableDiyFieldIds","SelectFields")&&r.push(`module ${v||b} has no listFields; generator will use the first business fields from ${b}`),n.push(`create_or_update_module ${S(g,"name","Name")}`)}),m.forEach(g=>n.push(`set_permission ${S(g,"roleId","RoleId")||"admin"}`)),u.forEach((g,x)=>{let b=un(g.json??g.JsonObj??g.JsonStr??g);e.push(...b.errors.map(v=>`pages[${x}]: ${v}`)),r.push(...b.warnings.map(v=>`pages[${x}]: ${v}`)),n.push(`save_page ${S(g,"title","Title")}`)}),p.forEach((g,x)=>{let b=Wi(g.PageObj??g.pageObj),v=Gi(g.PrintObj??g.printObj);e.push(...b.errors.map(w=>`printTemplates[${x}].PageObj: ${w}`)),r.push(...b.warnings.map(w=>`printTemplates[${x}].PageObj: ${w}`)),e.push(...v.errors.map(w=>`printTemplates[${x}].PrintObj: ${w}`)),r.push(...v.warnings.map(w=>`printTemplates[${x}].PrintObj: ${w}`)),n.push(`save_print_template ${S(g,"title","Title")}`)}),d.forEach((g,x)=>{let b=Bv(g);e.push(...b.errors.map(v=>`workflows[${x}]: ${v}`)),r.push(...b.warnings.map(v=>`workflows[${x}]: ${v}`)),n.push(`save_workflow ${S(we(g.FlowDesign??g.flowDesign??g),"FlowName","flowName","name")}`)}),h.forEach(g=>n.push(`save_job ${S(g,"jobName","JobName")}`)),{plan:n,errors:e,warnings:r}}function Hv(t){return{flow:we(t.FlowDesign??t.flowDesign??t),nodes:he(t,"Nodes","nodes"),lines:he(t,"Lines","lines")}}function go(t){return S(t,"Id","id","NodeId","nodeId")}function Xi(t){return S(t,"NodeName","nodeName","Name","name")}function TA(t){return S(t,"NodeType","nodeType","Type","type")}function Vv(t){let e=`${TA(t)} ${Xi(t)}`.toLowerCase();return e.includes("start")||e.includes("begin")||e.includes("\u5F00\u59CB")||e.includes("\u53D1\u8D77")}function pA(t){let e=`${TA(t)} ${Xi(t)}`.toLowerCase();return e.includes("end")||e.includes("finish")||e.includes("\u7ED3\u675F")||e.includes("\u5B8C\u6210")}function Bv(t){let e=[],r=[],{flow:n,nodes:i,lines:a}=Hv(t),o=S(n,"FlowName","flowName","Name","name"),s=S(n,"TableId","tableId"),c=S(n,"table","tableName","TableName","diyTableName","DiyTableName"),l=new Map,u=new Map,p=new Map;o||e.push("FlowDesign.FlowName \u4E0D\u80FD\u4E3A\u7A7A"),i.length||e.push("Nodes \u81F3\u5C11\u9700\u8981\u5305\u542B\u5F00\u59CB\u3001\u5BA1\u6279/\u4E1A\u52A1\u3001\u7ED3\u675F\u8282\u70B9"),a.length||e.push("Lines \u81F3\u5C11\u9700\u8981\u8FDE\u63A5\u5F00\u59CB\u5230\u4E0B\u4E00\u8282\u70B9"),!s&&!c&&r.push("FlowDesign.TableId \u4E3A\u7A7A\uFF1B\u666E\u901A\u5BA1\u6279\u6D41\u5EFA\u8BAE\u7ED1\u5B9A\u4E1A\u52A1 diy_table"),i.forEach((m,y)=>{let g=go(m),x=Xi(m);g||e.push(`Nodes[${y}].Id/NodeId \u4E0D\u80FD\u4E3A\u7A7A`),x||e.push(`Nodes[${y}].NodeName \u4E0D\u80FD\u4E3A\u7A7A`),g&&(l.has(g)&&e.push(`\u8282\u70B9 Id \u91CD\u590D\uFF1A${g}`),l.set(g,m))}),a.forEach((m,y)=>{let g=S(m,"Id","id","LineId","lineId")||`(index ${y})`,x=S(m,"FromNodeId","fromNodeId"),b=S(m,"ToNodeId","toNodeId");x||e.push(`Lines[${y}].FromNodeId \u4E0D\u80FD\u4E3A\u7A7A`),b||e.push(`Lines[${y}].ToNodeId \u4E0D\u80FD\u4E3A\u7A7A`),x&&!l.has(x)&&e.push(`\u8FDE\u7EBF ${g} \u7684 FromNodeId \u4E0D\u5B58\u5728\uFF1A${x}`),b&&!l.has(b)&&e.push(`\u8FDE\u7EBF ${g} \u7684 ToNodeId \u4E0D\u5B58\u5728\uFF1A${b}`),x===b&&x&&r.push(`\u8FDE\u7EBF ${g} \u6307\u5411\u81EA\u8EAB\uFF0C\u8BF7\u786E\u8BA4\u662F\u5426\u4E3A\u6709\u610F\u5FAA\u73AF`),x&&u.set(x,[...u.get(x)||[],m]),b&&p.set(b,[...p.get(b)||[],m])});let d=i.filter(Vv),h=i.filter(pA);return d.length!==1&&e.push(`\u9700\u8981\u4E14\u4EC5\u9700\u8981 1 \u4E2A\u5F00\u59CB\u8282\u70B9\uFF0C\u5F53\u524D ${d.length} \u4E2A`),h.length<1&&e.push("\u81F3\u5C11\u9700\u8981 1 \u4E2A\u7ED3\u675F\u8282\u70B9"),i.forEach(m=>{let y=go(m),g=Xi(m)||y;if(!y)return;let x=u.get(y)||[],b=p.get(y)||[];!Vv(m)&&b.length===0&&r.push(`\u8282\u70B9 ${g} \u6CA1\u6709\u5165\u7EBF`),!pA(m)&&x.length===0&&r.push(`\u8282\u70B9 ${g} \u6CA1\u6709\u51FA\u7EBF`),x.length>1&&(S(m,"LineValueV8","lineValueV8","V8Code","v8Code")||r.push(`\u8282\u70B9 ${g} \u6709 ${x.length} \u6761\u51FA\u7EBF\uFF0C\u5EFA\u8BAE\u914D\u7F6E LineValueV8\uFF0C\u5E76\u4F18\u5148\u7528 V8.NextNodeId \u6307\u5B9A\u4E0B\u4E00\u8282\u70B9`))}),{ok:e.length===0,errors:e,warnings:r,summary:{flowName:o,tableId:s,table:c,nodeCount:i.length,lineCount:a.length,startNodes:d.map(m=>({id:go(m),name:Xi(m)})),endNodes:h.map(m=>({id:go(m),name:Xi(m)}))}}}function WH(t){let e=t.indexOf(aA);if(e<0)return null;let r=e+aA.length,n=t.indexOf(yH,r);if(n<0)return null;try{return we(JSON.parse(t.slice(r,n).trim()))}catch{return null}}function dA(t){return t==null||String(t).trim()===""}function fA(t,e){let r=S(t,"field","Field"),n=S(t,"operator","Operator")||"eq",i=Zr(t,"value","Value"),a=r?e[r]:void 0,o=a==null?"":String(a),s=i==null?"":String(i);if(n==="empty")return dA(a);if(n==="notEmpty")return!dA(a);if(n==="contains")return o.includes(s);if(n==="notContains")return!o.includes(s);if(n==="startsWith")return o.startsWith(s);if(n==="endsWith")return s===""||o.endsWith(s);if(["gt","gte","lt","lte"].includes(n)){let c=Number(a),l=Number(i);return Number.isNaN(c)||Number.isNaN(l)?!1:n==="gt"?c>l:n==="gte"?c>=l:n==="lt"?c<l:c<=l}return n==="ne"?o!==s:o===s}function GH(t){let e=we(t.workflow),r=we(t.formData),n=S(t,"lineValueV8Code","LineValueV8","code");if(!n&&Object.keys(e).length>0){let{nodes:s}=Hv(e),c=S(t,"nodeId","NodeId"),l=(c?s.find(u=>go(u)===c):s.find(Vv)||s[0])||{};n=S(l,"LineValueV8","lineValueV8","V8Code","v8Code")}let i=WH(n),a=he(i||{},"routes","Routes");if(!i||a.length===0)return{ok:!1,selectedRoute:null,warnings:["\u672A\u627E\u5230\u56FE\u5F62\u6761\u4EF6\u6807\u8BB0\uFF0CMCP \u4E0D\u6267\u884C\u4EFB\u610F\u624B\u5199 V8\uFF1B\u8BF7\u7528\u56FE\u5F62\u6761\u4EF6\u751F\u6210 LineValueV8 \u540E\u518D\u6D4B\u8BD5\u3002"]};let o=a.find(s=>!!Zr(s,"isDefault","IsDefault"))||null;for(let s of a){if(s===o)continue;let c=he(s,"rules","Rules").filter(u=>S(u,"field","Field"));if(c.length===0)continue;if(S(s,"match","Match")==="any"?c.some(u=>fA(u,r)):c.every(u=>fA(u,r)))return{ok:!0,selectedRoute:s,assignment:mA(s),source:"matched"}}return{ok:!!o,selectedRoute:o,assignment:o?mA(o):null,source:o?"default":"none"}}function mA(t){let e=S(t,"lineValue","LineValue"),r=S(t,"toNodeId","ToNodeId");return e?{LineValue:e}:{NextNodeId:r}}function XH(t,e){let{flow:r,nodes:n,lines:i}=Hv(t),a={...r},o=S(r,"table","tableName","TableName","diyTableName","DiyTableName");if(!S(a,"TableId","tableId")&&o){let u=e.get(o.toLowerCase());u&&(a.TableId=u)}let s=new Map,c=n.map((u,p)=>{let d=go(u)||`wf_node_${p+1}_${zv().slice(0,8)}`,h={...u,Id:d},m=Xi(h);return m&&s.set(d,m),h}),l=i.map((u,p)=>{let d=S(u,"FromNodeId","fromNodeId"),h=S(u,"ToNodeId","toNodeId"),m=S(u,"LineName","lineName")||`${s.get(d)||d||"\u5F53\u524D\u8282\u70B9"} \u5230 ${s.get(h)||h||"\u4E0B\u4E00\u8282\u70B9"}`;return{...u,Id:S(u,"Id","id","LineId","lineId")||`wf_line_${p+1}_${zv().slice(0,8)}`,LineName:m}});return{FlowDesign:a,Nodes:c,Lines:l}}async function lr(t,e,r,n){try{await t.writeAuditLog(e,r,JSON.stringify(n).slice(0,6e3))}catch(i){console.error("[microi-mcp] audit log failed:",i instanceof Error?i.message:String(i))}}async function hA(t,e){let r=S(e,"apiEngineKey","ApiEngineKey"),n=S(e,"apiName","ApiName","name","Name")||r,i=S(e,"category","Category")||"AI\u751F\u6210",a=Zr(e,"code","Code","ApiV8Code"),o=typeof a=="string",s=o?String(a):"",c=Un(e,"v8Unlimited","V8Unlimited"),l=await t.getEngineCode(r);return l.Code===1?!o&&c!==void 0?t.updateEngineRuntimeConfig(r,c):o?t.saveEngineCode(r,s,{functionDescription:S(e,"functionDescription","FunctionDescription")||void 0,changeSummary:S(e,"changeSummary","ChangeSummary")||void 0,v8Unlimited:c}):{Code:1,Data:{ApiEngineKey:r,V8Unlimited:Number(l.Data?.V8Unlimited||0),Skipped:!0},Msg:"\u63A5\u53E3\u5F15\u64CE\u5DF2\u5B58\u5728\uFF0CManifest \u672A\u63D0\u4F9B code \u6216 V8Unlimited\uFF0C\u4FDD\u6301\u539F\u914D\u7F6E"}:t.createEngine({ApiEngineKey:r,ApiName:n,Category:i,Code:s,V8Unlimited:c===void 0?void 0:c?1:0,functionDescription:S(e,"functionDescription","FunctionDescription")||void 0,changeSummary:S(e,"changeSummary","ChangeSummary")||void 0})}function QH(t,e,r,n){let i=S(t,"table","tableName","diyTableName","DiyTableName"),a=bo(t);if(a.errors.length)throw new Error(a.errors.join(`
|
|
129
|
+
`),e.Code!==1)}function wc(t){if(!(t==null||t===""))return typeof t=="string"?t:JSON.stringify(t)}function xH(t){let e=we(t),r=we(e.Workload??e.workload??e.BackgroundWorkload??e.backgroundWorkload),n=[],i=ge(r,"ExpectedSeconds","expectedSeconds")??0,a=ge(r,"ExpectedItems","expectedItems","EstimatedRows","estimatedRows")??0,o=ge(r,"FanOutOperations","fanOutOperations","FanOut","fanOut")??0,s=ge(r,"ExternalCalls","externalCalls")??0;i>=120&&n.push(`\u9884\u8BA1\u8017\u65F6 ${i}s >= 120s`),a>=500&&n.push(`\u9884\u8BA1\u5904\u7406 ${a} \u6761 >= 500 \u6761`),o>=1e3&&n.push(`\u9884\u8BA1\u6247\u51FA ${o} \u4E2A\u5B50\u64CD\u4F5C >= 1000`),s>=100&&n.push(`\u9884\u8BA1\u5916\u90E8\u8C03\u7528 ${s} \u6B21 >= 100 \u6B21`),Un(r,"UnknownTotal","unknownTotal")===!0&&n.push("\u603B\u5DE5\u4F5C\u91CF\u672A\u77E5\u4E14\u53EF\u80FD\u957F\u65F6\u95F4\u8FD0\u884C");let c=[S(e,"Name","name"),S(e,"ApiEngineKey","apiEngineKey"),S(e,"V8Code","v8Code")].join(" ");return/(批量.{0,4}(导入|生成|修复|处理)|安装|初始化|全量同步|数据迁移|数据库备份|批量任务)/i.test(c)&&n.push("\u52A8\u4F5C\u8BED\u4E49\u5C5E\u4E8E\u5178\u578B\u957F\u4EFB\u52A1"),{required:n.length>0,reasons:n}}function wH(t){let e=we(t),r=we(e.Workload??e.workload??e.BackgroundWorkload??e.backgroundWorkload),n=S(r,"ExecutionMode","executionMode").trim().toLowerCase(),i=Un(r,"ClientChunked","clientChunked")===!0||n==="clientchunked"||n==="clientsequential",a=ge(r,"MaxItemsPerChunk","maxItemsPerChunk")??0,o=Un(r,"Resumable","resumable")===!0;return{declared:i,valid:i&&a>0&&o,maxItemsPerChunk:a,resumable:o}}var Kp="https://api.itdos.com",Mv="iTdos";function _H(t){let e=String(t.storeId||"").trim(),r=String(t.requestId||"").trim();if(!/^[A-Za-z0-9:._-]{1,100}$/u.test(e))throw new Error("storeId \u53EA\u80FD\u5305\u542B\u5B57\u6BCD\u3001\u6570\u5B57\u3001\u5192\u53F7\u3001\u70B9\u3001\u4E0B\u5212\u7EBF\u548C\u8FDE\u5B57\u7B26\uFF0C\u957F\u5EA6 1-100\u3002");if(!/^[A-Za-z0-9:._-]{8,100}$/u.test(r))throw new Error("requestId \u5FC5\u987B\u662F\u8C03\u7528\u65B9\u4FDD\u5B58\u5E76\u5728\u91CD\u8BD5\u65F6\u590D\u7528\u7684\u7A33\u5B9A\u5E42\u7B49 Id\uFF0C\u957F\u5EA6 8-100\u3002");let n=String(t.storeApiBase||Kp).trim(),i;try{i=new URL(n)}catch{throw new Error("storeApiBase \u5FC5\u987B\u662F\u6709\u6548\u7684 HTTP/HTTPS \u670D\u52A1\u6839\u5730\u5740\u3002")}if(i.protocol!=="https:"||i.username||i.password||i.pathname&&i.pathname!=="/"||i.search||i.hash||i.origin!==Kp)throw new Error(`storeApiBase \u4EC5\u5141\u8BB8\u543E\u7801\u5B98\u65B9\u5546\u57CE ${Kp}\uFF0C\u4E14\u4E0D\u80FD\u5305\u542B\u51ED\u636E\u3001\u8DEF\u5F84\u3001\u67E5\u8BE2\u3001\u7247\u6BB5\u6216\u81EA\u5B9A\u4E49\u7AEF\u53E3\u3002`);let a=Kp,o=String(t.storeOsClient||Mv).trim();if(o.toLowerCase()!==Mv.toLowerCase())throw new Error(`storeOsClient \u4EC5\u5141\u8BB8\u543E\u7801\u5B98\u65B9\u5546\u57CE\u79DF\u6237 ${Mv}\u3002`);return{ApiEngineKey:"import-microi-store-package",Title:`${t.operation==="update"?"\u66F4\u65B0":"\u5B89\u88C5"}\u5E94\u7528\uFF1A${String(t.appName||t.appId||e).trim()}`,Param:dn({StoreId:e,AppId:t.appId,AppName:t.appName,AppVersion:t.appVersion,StoreApiBase:a,StoreOsClient:o,InstallParentSysMenuId:t.installParentSysMenuId,ResumeInstall:t.resumeInstall!==!1,InstallAction:t.operation==="update"?"Update":"Install",InstallOperationId:r}),Options:{IdempotencyKey:`mcp:store:${t.operation}:${e}:${r}`,ConcurrencyKey:"import-microi-store-package",MaxAttempts:3,RetryOnFailure:!0}}}function SH(t,e){let r=[],n=[];if(e==null||e==="")return{ok:!0,value:void 0,errors:r,warnings:n};let i;try{i=typeof e=="string"?JSON.parse(e):e}catch(s){return{ok:!1,errors:[`${t} \u4E0D\u662F\u5408\u6CD5 JSON \u6570\u7EC4\uFF1A${s instanceof Error?s.message:String(s)}`],warnings:n}}if(!Array.isArray(i))return{ok:!1,errors:[`${t} \u5FC5\u987B\u662F JSON \u6570\u7EC4`],warnings:n};let a=new Set,o=i.map((s,c)=>{let l=we(s),u=S(l,"Name","name");u||r.push(`${t}[${c}].Name \u4E0D\u80FD\u4E3A\u7A7A`);let p=xH(l),d=wH(l),h=l.RunBackground??l.runBackground??l.BackgroundTask??l.backgroundTask??l.IsBackgroundTask??l.isBackgroundTask,m=S(l,"ApiEngineKey","apiEngineKey");p.required&&h!==!0&&(d.declared&&!d.valid?r.push(`${t}[${c}] \u58F0\u660E\u5BA2\u6237\u7AEF\u5206\u7247\u65F6\u5FC5\u987B\u8BBE\u7F6E Workload.MaxItemsPerChunk > 0 \u4E14 Workload.Resumable=true`):d.valid?n.push(`${t}[${c}] \u5DF2\u58F0\u660E\u5BA2\u6237\u7AEF\u53EF\u6062\u590D\u5206\u7247\uFF0C\u5355\u7247\u6700\u591A ${d.maxItemsPerChunk} \u6761\uFF1B\u4FDD\u7559\u524D\u7AEF\u5206\u7247\u6267\u884C\uFF1A${p.reasons.join("\uFF1B")}`):m?(h=!0,n.push(`${t}[${c}] \u5DF2\u8BC6\u522B\u4E3A\u957F\u4EFB\u52A1\u5E76\u81EA\u52A8\u542F\u7528 RunBackground\uFF1A${p.reasons.join("\uFF1B")}`)):r.push(`${t}[${c}] \u5DF2\u8BC6\u522B\u4E3A\u957F\u4EFB\u52A1\uFF0C\u4F46\u7F3A\u5C11 ApiEngineKey\uFF1A${p.reasons.join("\uFF1B")}`));let y=we(l.BackgroundTaskOptions??l.backgroundTaskOptions);h===!0&&(!S(y,"IdempotencyKey","idempotencyKey")&&!xc(y,"IdempotencyKeyFields","idempotencyKeyFields").length&&n.push(`${t}[${c}] \u540E\u53F0\u4EFB\u52A1\u672A\u914D\u7F6E IdempotencyKey \u6216 IdempotencyKeyFields\uFF1B\u6D89\u53CA\u5199\u64CD\u4F5C\u65F6\u5FC5\u987B\u8865\u7A33\u5B9A\u4E1A\u52A1\u5E42\u7B49\u952E`),S(y,"BusinessTable","businessTable")&&(!S(y,"BusinessStatusField","businessStatusField")||!S(y,"BusinessTaskIdField","businessTaskIdField"))&&n.push(`${t}[${c}] \u5DF2\u5173\u8054\u4E1A\u52A1\u8868\uFF0C\u4F46\u7F3A\u5C11 BusinessStatusField/BusinessTaskIdField`));let g=S(l,"TargetSysMenuId","targetSysMenuId"),x=t==="PageTabs"&&!!g;!S(l,"V8Code","v8Code")&&!S(l,"Url","url")&&!(h&&m)&&!x&&r.push(`${t}[${c}] \u5FC5\u987B\u914D\u7F6E V8Code\u3001Url\u3001\u5173\u8054\u6A21\u5757 TargetSysMenuId\uFF0C\u6216\u540E\u53F0\u4EFB\u52A1 ApiEngineKey`);let b=S(l,"Id","id")||zv();S(l,"Id","id")||n.push(`${t}[${c}] \u672A\u4F20 Id\uFF0C\u5DF2\u81EA\u52A8\u751F\u6210 ${b}`),a.has(b)&&r.push(`${t} \u4E2D\u5B58\u5728\u91CD\u590D Id\uFF1A${b}`),a.add(b);let v=S(l,"V8CodeShow","v8CodeShow");return v&&!v.includes("V8.Result")&&n.push(`${t}[${c}].V8CodeShow \u5EFA\u8BAE\u663E\u5F0F\u8D4B\u503C V8.Result=true/false`),dn({...l,Id:b,Sort:ge(l,"Sort","sort")??c*10,Name:u,Icon:S(l,"Icon","icon")||void 0,BtnStyle:S(l,"BtnStyle","btnStyle")||void 0,IsVisible:l.IsVisible??l.isVisible??!0,ShowRow:t==="MoreBtns"?l.ShowRow??l.showRow??!0:l.ShowRow??l.showRow,V8CodeShow:v||void 0,V8Code:S(l,"V8Code","v8Code")||void 0,Url:S(l,"Url","url")||void 0,RunBackground:h===void 0?void 0:!!h,BackgroundTask:l.BackgroundTask??l.backgroundTask??void 0,IsBackgroundTask:l.IsBackgroundTask??l.isBackgroundTask??void 0,ApiEngineKey:m||void 0,Workload:Object.keys(we(l.Workload??l.workload)).length?we(l.Workload??l.workload):void 0,BackgroundTaskOptions:Object.keys(y).length?y:void 0,TargetSysMenuId:g||void 0})});return{ok:r.length===0,value:JSON.stringify(o),errors:r,warnings:n}}function bo(t){let e={...t},r=[],n=[];(t.DiyConfig!==void 0||t.diyConfig!==void 0)&&(r.push("DiyConfig \u5DF2\u5E9F\u5F03\uFF1B\u8BF7\u65B0\u589E\u4E13\u7528\u7269\u7406\u5B57\u6BB5\uFF0C\u5E76\u901A\u8FC7 diy_field \u5143\u6570\u636E\u66B4\u9732\u914D\u7F6E\u63A7\u4EF6\u3002\u8DE8\u7AEF\u89C6\u56FE\u8BF7\u4F7F\u7528 sys_menu.ViewSchema\u3002"),delete e.DiyConfig,delete e.diyConfig);let i={MoreBtns:["MoreBtns","moreBtns"],FormBtns:["FormBtns","formBtns"],BatchSelectMoreBtns:["BatchSelectMoreBtns","batchSelectMoreBtns"],PageTabs:["PageTabs","pageTabs"],ExportMoreBtns:["ExportMoreBtns","exportMoreBtns"],PageBtns:["PageBtns","pageBtns"]};for(let[c,l]of Object.entries(i)){let u=l.find(d=>t[d]!==void 0);if(!u)continue;let p=SH(c,t[u]);r.push(...p.errors),n.push(...p.warnings),p.ok&&p.value!==void 0&&(e[c]=p.value)}let a=[["MenuBadgeEnabled","menuBadgeEnabled"],["EnableViewSchema","enableViewSchema"],["ViewConfigVersion","viewConfigVersion"]];for(let[c,l]of a){if(t[c]===void 0&&t[l]===void 0)continue;let u=ge(t,c,l);u!==void 0&&(e[c]=c.endsWith("Enabled")?u===1?1:0:u),delete e[l]}let o=[["MenuBadgeApiEngineKey","menuBadgeApiEngineKey"],["ViewSchemaVersion","viewSchemaVersion"]];for(let[c,l]of o)t[c]===void 0&&t[l]===void 0||(e[c]=S(t,c,l),delete e[l]);let s=["ViewSchema","viewSchema"].find(c=>t[c]!==void 0);if(s){let c=Zv(t[s]);r.push(...c.errors),n.push(...c.warnings),delete e.viewSchema,c.value!==void 0&&(e.ViewSchema=c.value)}return{data:e,errors:r,warnings:n}}function Un(t,...e){for(let r of e){let n=t[r];if(typeof n=="boolean")return n;if(typeof n=="number")return n!==0;if(typeof n=="string"&&n.trim()){let i=n.trim().toLowerCase();if(["true","1","yes"].includes(i))return!0;if(["false","0","no"].includes(i))return!1}}}function sA(t,e,r,n){let i=Zr(t,"v8Unlimited","V8Unlimited");if(i==null||i==="")return;let a=Un(t,"v8Unlimited","V8Unlimited");if(a===void 0){r.push(`${e}.v8Unlimited \u5FC5\u987B\u662F boolean \u6216 0/1`);return}return a&&n.push(`${e}.v8Unlimited=true \u4F1A\u53D6\u6D88\u8BE5\u63A5\u53E3\u6216\u8BE5\u8868\u540E\u7AEF V8 \u4E8B\u4EF6\u7684\u5355\u6B21 Jint \u8D85\u65F6\u3001\u8BED\u53E5\u3001\u9012\u5F52\u548C\u7D2F\u8BA1\u5206\u914D\u9884\u7B97\uFF1B\u4EC5\u5728\u4E1A\u52A1\u660E\u786E\u8981\u6C42\u5355\u4E8B\u52A1\u4E14\u5DF2\u8BC4\u4F30\u6570\u636E\u5E93\u9501\u3001\u56DE\u6EDA\u3001\u8FDE\u63A5\u8D85\u65F6\u4E0E\u8FDB\u7A0B\u5185\u5B58\u98CE\u9669\u65F6\u5F00\u542F\u3002\u8FDB\u7A0B\u5E38\u9A7B\u5185\u5B58\u4FDD\u62A4\u4ECD\u751F\u6548\uFF0C\u4E14\u4E0D\u4F1A\u5411\u5D4C\u5957\u63A5\u53E3\u7EE7\u627F\u3002`),a}var EH=["Detail","Edit","List","Card"],kH=["PC","Mobile","All"],TH=["ApiEngine","OpenDetail","OpenList","OpenForm","Navigate","Dial","Scan","Map","Refresh","Back","Copy"],CH=new Set(["v8code","v8codeshow","script","javascript","eval","onclick","function"]);function jv(t,e){let r=String(t??"").trim().toLowerCase();return e.find(n=>n.toLowerCase()===r)||""}function pn(t,...e){let r=new Set(e.map(i=>i.toLowerCase()));return Object.entries(t).find(([i])=>r.has(i.toLowerCase()))?.[1]}function Fv(t,e="ViewSchema"){if(Array.isArray(t)){for(let r=0;r<t.length;r+=1){let n=Fv(t[r],`${e}[${r}]`);if(n)return n}return""}if(!t||typeof t!="object")return"";for(let[r,n]of Object.entries(t)){if(CH.has(r.toLowerCase()))return`${e}.${r}`;let i=Fv(n,`${e}.${r}`);if(i)return i}return""}function Lv(t,e,r=0){if(t==null)return[];if(r>4)return[`${e} \u7684 SuccessActions \u5D4C\u5957\u4E0D\u80FD\u8D85\u8FC7 4 \u5C42`];if(!Array.isArray(t))return[`${e} \u5FC5\u987B\u662F JSON \u6570\u7EC4`];if(t.length>50)return[`${e} \u6700\u591A\u5141\u8BB8 50 \u4E2A\u52A8\u4F5C`];let n=[];return t.forEach((i,a)=>{let o=we(i);if(!Object.keys(o).length){n.push(`${e}[${a}] \u5FC5\u987B\u662F JSON \u5BF9\u8C61`);return}let s=jv(pn(o,"ActionType","Type"),TH);if(!s){n.push(`${e}[${a}].ActionType \u4E0D\u53D7\u652F\u6301`);return}s==="ApiEngine"&&!S(o,"ApiEngineKey","apiEngineKey")&&n.push(`${e}[${a}] \u4F7F\u7528 ApiEngine \u65F6\u5FC5\u987B\u914D\u7F6E ApiEngineKey`);let c=pn(o,"SuccessActions");n.push(...Lv(c,`${e}[${a}].SuccessActions`,r+1))}),n}function Zv(t){let e=[],r=[];if(t==null||t==="")return{ok:!0,value:void 0,errors:e,warnings:r};let n=t;try{typeof n=="string"&&(n=JSON.parse(n)),typeof n=="string"&&(n=JSON.parse(n))}catch(c){return{ok:!1,errors:[`ViewSchema \u4E0D\u662F\u5408\u6CD5 JSON\uFF1A${c instanceof Error?c.message:String(c)}`],warnings:r}}if(!n||typeof n!="object"||Array.isArray(n))return{ok:!1,errors:["ViewSchema \u5FC5\u987B\u662F JSON \u5BF9\u8C61"],warnings:r};let i=Fv(n);i&&e.push(`ViewSchema \u4E0D\u5141\u8BB8\u5305\u542B\u53EF\u6267\u884C\u524D\u7AEF\u811A\u672C\u5B57\u6BB5\uFF1A${i}`);let o=pn(n,"Views");o!==void 0&&!Array.isArray(o)?e.push("ViewSchema.Views \u5FC5\u987B\u662F JSON \u6570\u7EC4"):Array.isArray(o)?(o.length>100&&e.push("ViewSchema.Views \u6700\u591A\u5141\u8BB8 100 \u4E2A\u89C6\u56FE"),o.forEach((c,l)=>{let u=we(c);if(!Object.keys(u).length){e.push(`ViewSchema.Views[${l}] \u5FC5\u987B\u662F JSON \u5BF9\u8C61`);return}jv(pn(u,"Scene"),EH)||e.push(`ViewSchema.Views[${l}].Scene \u4E0D\u53D7\u652F\u6301`);let p=pn(u,"Device");p!==void 0&&!jv(p,kH)&&e.push(`ViewSchema.Views[${l}].Device \u4E0D\u53D7\u652F\u6301`);let d=pn(u,"Layout","LayoutJson");if(typeof d=="string")try{d=JSON.parse(d)}catch{e.push(`ViewSchema.Views[${l}].Layout \u4E0D\u662F\u5408\u6CD5 JSON`);return}if(d==null)return;let h=we(d);if(!Object.keys(h).length&&(typeof d!="object"||Array.isArray(d))){e.push(`ViewSchema.Views[${l}].Layout \u5FC5\u987B\u662F JSON \u5BF9\u8C61`);return}e.push(...Lv(pn(h,"Actions","ActionSchema"),`ViewSchema.Views[${l}].Layout.Actions`));let m=pn(h,"Blocks","Sections");m!==void 0&&!Array.isArray(m)?e.push(`ViewSchema.Views[${l}].Layout.Blocks \u5FC5\u987B\u662F JSON \u6570\u7EC4`):Array.isArray(m)&&(m.length>100&&e.push(`ViewSchema.Views[${l}].Layout.Blocks \u6700\u591A\u5141\u8BB8 100 \u4E2A\u533A\u5757`),m.forEach((y,g)=>{let x=we(y);e.push(...Lv(pn(x,"Actions"),`ViewSchema.Views[${l}].Layout.Blocks[${g}].Actions`))}))})):r.push("ViewSchema.Views \u4E3A\u7A7A\uFF0C\u5BA2\u6237\u7AEF\u5C06\u4F7F\u7528\u73B0\u6709\u6A21\u5757\u548C\u8868\u5355\u914D\u7F6E\u3002");let s=JSON.stringify(n);return Buffer.byteLength(s,"utf8")>512*1024&&e.push("ViewSchema \u4E0D\u80FD\u8D85\u8FC7 512KB"),{ok:e.length===0,value:s,errors:e,warnings:r}}function cA(t,e){let r=[],n=t.toLowerCase();if(n==="keyvalue"){let i=S(e,"data","options"),a=i?i.split(/[,,;;\n]/).map(o=>o.trim()).filter(Boolean).map(o=>{let[s,c]=o.split("|");return{Key:(s||"").trim(),Value:(c||s||"").trim()}}):Wp(e.items).map(o=>({Key:S(o,"Key","key"),Value:S(o,"Value","label","name")}));return{data:JSON.stringify(a),config:{DataSource:"KeyValue",SelectLabel:"Value",SelectSaveField:"Key",SelectSaveFormat:"Text",EnableSearch:!1,DataSourceSqlRemote:!1},warnings:r}}if(n==="data"){let i=S(e,"data","options"),a=i?i.split(/[,,;;\n]/).map(o=>o.trim()).filter(Boolean):Array.isArray(e.items)?e.items:[];return{data:JSON.stringify(a),config:{DataSource:"Data",SelectSaveFormat:"Text",EnableSearch:!1,DataSourceSqlRemote:!1},warnings:r}}if(n==="sql"){let i=S(e,"sql","Sql");return i||r.push("SQL \u6570\u636E\u6E90\u7F3A\u5C11 sql"),{config:{DataSource:"Sql",Sql:i,SelectLabel:S(e,"selectLabel","SelectLabel")||"Name",SelectSaveField:S(e,"selectSaveField","SelectSaveField")||"Id",DataSourceSqlRemote:e.dataSourceSqlRemote??e.DataSourceSqlRemote??!0,EnableSearch:e.enableSearch??e.EnableSearch??!0},warnings:r}}if(n==="apiengine"){let i=S(e,"apiEngineKey","DataSourceApiEngineKey");return i||r.push("\u63A5\u53E3\u5F15\u64CE\u6570\u636E\u6E90\u7F3A\u5C11 apiEngineKey"),{config:{DataSource:"ApiEngine",DataSourceApiEngineKey:i,SelectLabel:S(e,"selectLabel")||"name",SelectSaveField:S(e,"selectSaveField")||"id"},warnings:r}}if(n==="datasource"){let i=S(e,"dataSourceId","DataSourceId");return i||r.push("\u6570\u636E\u6E90\u5F15\u64CE\u914D\u7F6E\u7F3A\u5C11 dataSourceId"),{config:{DataSource:"DataSource",DataSourceId:i,SelectLabel:S(e,"selectLabel")||"Name",SelectSaveField:S(e,"selectSaveField")||"Id"},warnings:r}}return n==="autonumber"?{config:{AutoNumberFixed:S(e,"prefix","AutoNumberFixed"),AutoNumberLength:ge(e,"length","AutoNumberLength")??4},warnings:r}:n==="datetime"?{config:{DateTimeType:S(e,"dateTimeType","DateTimeType")||"datetime"},warnings:r}:n==="joinform"?{config:{JoinForm:{TableId:S(e,"tableId"),TableName:S(e,"tableName"),JoinFieldName:S(e,"joinFieldName")||"Name"}},warnings:r}:(r.push(`\u672A\u77E5 sourceType: ${t}\uFF0C\u5DF2\u8FD4\u56DE\u7A7A\u914D\u7F6E`),{config:{},warnings:r})}function Dv(t,e){let r=Jr(t);return dn({Id:t.id,AsName:e?.asName||"",Name:t.name,Label:t.label||t.name,TableId:t.tableId,TableName:t.tableName,TableDescription:t.tableDescription||t.tableName,DisplayType:e?.displayType||(qv.has(r)||Qi(t)||r==="numbertext"?"In":"Out"),DisplaySelect:e?.displaySelect??["opentable","joinform","department","selecttree"].includes(r),Equal:e?.equal??(qv.has(r)||r==="numbertext"?!0:void 0),IsVisible:!0})}function ho(t,e,r,n,i){return n.map(a=>{let o=oA(t,e,a.ref)||oA(t,r,a.ref)||(Uv(a.ref)?_A(e,r,a.ref):void 0);if(!o)throw new Error(`${i}: unknown field "${a.ref}" on table "${r||e}"`);return{meta:o,ref:a}})}function et(t,...e){for(let r of e){let n=Zr(t,r);if(!(n==null||n===""))return typeof n=="string"?n:JSON.stringify(n)}return""}var $H=new Set(["id","osclient","isdeleted","createuserid","updateuserid","deleteuserid","tenantid","storeid","userid","userids","roleid","roleids","parentid","parentids","class","code","enname","endescription"]),SA=new Set(["button","divider","collapsegroup","tabs","alert","statictext","html","devcomponent"]),AH=new Set(["textarea","richtext","codeeditor","jsontable","imgupload","fileupload","tablechild","map","maparea","jointable","opentable","treecheckbox","transfer"]),PH=new Set(["text","textarea","select","multipleselect","radio","checkbox","datetime","date","numbertext","autonumber","switch","department","address","cascader","selecttree","opentable","joinform","autocomplete","taginput"]),qv=new Set(["select","multipleselect","radio","checkbox","switch","department","selecttree","opentable","joinform","cascader"]);function Ur(t){return(t||"").trim().toLowerCase()}function pr(t){return`${t.name||""} ${t.label||""} ${t.component||""} ${t.type||""}`.toLowerCase()}function qe(t,e){return e.some(r=>t.includes(r.toLowerCase()))}function Jr(t){return Ur(t.component||"Text")}function IH(t){return SA.has(Jr(t))}function RH(t){return AH.has(Jr(t))}function OH(t){let e=t.name||"",r=Ur(e).replace(/[_\-\s]+/g,"");return!!($H.has(r)||/^(.*id|.*ids|.*idlist|.*guid)$/.test(r)&&!/idcard|identity|cardid/.test(r)||/Id$|ID$|Ids$|IDs$|Guid$/u.test(e)&&!/IdCard|IDCard|Identity|CardId/u.test(e))}function _c(t){return Uv(t.name)&&!["CreateTime","UpdateTime","UserName"].some(e=>e.toLowerCase()===t.name.toLowerCase())||OH(t)||IH(t)||RH(t)?!0:Jr(t).includes("hidden")}function vo(t){let e=new Set;return t.filter(r=>{let n=r.id||r.name;return!n||e.has(n)?!1:(e.add(n),!0)})}function Zn(t,e){return t.map((r,n)=>({field:r,index:n,score:e(r)})).sort((r,n)=>n.score-r.score||r.index-n.index).map(r=>r.field)}function Jv(t){let e=Ur(t.type);return Jr(t)==="numbertext"||e.startsWith("decimal")||e==="int"||e==="bigint"}function Qi(t){let e=pr(t);return Jr(t)==="datetime"||qe(e,["time","date","\u65E5\u671F","\u65F6\u95F4"])}function NH(t){let e=Jr(t),r=qv.has(e)||e==="numbertext"||e==="rate"||e==="progress";return{ref:t.name,displayType:r||Qi(t)?"In":"Out",displaySelect:["opentable","joinform","department","selecttree"].includes(e),equal:r?!0:void 0}}function lA(t){let e=pr(t),r=0;return qe(e,["name","title","no","code","account","phone","mobile","email","\u540D\u79F0","\u6807\u9898","\u7F16\u53F7","\u8D26\u53F7","\u7535\u8BDD","\u624B\u673A","\u90AE\u7BB1"])&&(r+=50),qe(e,["status","state","type","category","level","class","\u72B6\u6001","\u7C7B\u578B","\u5206\u7C7B","\u7B49\u7EA7"])&&(r+=45),qe(e,["customer","member","user","owner","\u8D1F\u8D23\u4EBA","\u5BA2\u6237","\u4F1A\u5458","\u7528\u6237","\u8054\u7CFB\u4EBA"])&&(r+=35),Qi(t)&&(r+=25),Jv(t)&&!qe(e,["phone","mobile","tel","\u7535\u8BDD","\u624B\u673A"])&&(r+=15),Jr(t)==="textarea"&&(r-=25),r}function MH(t){let e=pr(t),r=0;return qe(e,["name","title","no","code","\u540D\u79F0","\u6807\u9898","\u7F16\u53F7"])&&(r+=70),qe(e,["status","state","type","category","\u72B6\u6001","\u7C7B\u578B","\u5206\u7C7B"])&&(r+=45),qe(e,["customer","member","user","owner","phone","mobile","\u5BA2\u6237","\u4F1A\u5458","\u7528\u6237","\u8D1F\u8D23\u4EBA","\u7535\u8BDD","\u624B\u673A"])&&(r+=35),qe(e,["amount","money","price","total","count","qty","\u91D1\u989D","\u4EF7\u683C","\u603B\u989D","\u6570\u91CF","\u79EF\u5206","\u4F59\u989D"])&&(r+=30),Qi(t)&&(r+=15),Jr(t)==="autonumber"&&(r+=55),r}function DH(t){return vo(t.filter(_c))}function Gp(t){let e=t.filter(n=>!_c(n)),r=e.length?e:t;return vo(Zn(r,MH)).slice(0,Math.min(12,r.length))}function zH(t){let e=t.filter(n=>!_c(n)&&PH.has(Jr(n))),r=Zn(e,lA).filter(n=>lA(n)>0);return vo(r.length?r:e).slice(0,Math.min(8,e.length))}function jH(t){let e=t.filter(r=>!_c(r)&&(Qi(r)||Jv(r)||Ur(r.name)==="sort"));return vo(Zn(e,r=>{let n=pr(r);return qe(n,["update","\u4FEE\u6539"])?80:qe(n,["create","\u521B\u5EFA"])?75:Ur(r.name)==="sort"?70:qe(n,["amount","money","price","total","count","\u91D1\u989D","\u4EF7\u683C","\u6570\u91CF"])?60:20})).slice(0,Math.min(8,e.length))}function FH(t){let e=["phone","mobile","tel","status","state","sort","rate","level","\u7535\u8BDD","\u624B\u673A","\u72B6\u6001","\u6392\u5E8F","\u7B49\u7EA7"],r=t.filter(n=>{let i=pr(n);return!_c(n)&&Jv(n)&&!qe(i,e)&&qe(i,["amount","money","price","total","count","qty","score","point","balance","\u91D1\u989D","\u4EF7\u683C","\u603B\u989D","\u6570\u91CF","\u79EF\u5206","\u4F59\u989D","\u9762\u79EF","\u91CD\u91CF"])});return vo(Zn(r,n=>qe(pr(n),["amount","money","price","total","\u91D1\u989D","\u4EF7\u683C","\u603B\u989D"])?80:40)).slice(0,6)}function LH(t){let e=Gp(t),r=Zn(e,a=>qe(pr(a),["name","title","no","code","\u540D\u79F0","\u6807\u9898","\u7F16\u53F7"])?100:0)[0],n=Zn(e.filter(a=>a!==r),a=>qe(pr(a),["status","state","type","category","\u72B6\u6001","\u7C7B\u578B","\u5206\u7C7B"])?80:0),i=e.filter(a=>a!==r&&!n.slice(0,1).includes(a));return vo([r,...n.slice(0,1),...i].filter(Boolean)).slice(0,4)}function qH(t){return Zn(Gp(t),e=>qe(pr(e),["status","state","type","category","level","\u72B6\u6001","\u7C7B\u578B","\u5206\u7C7B","\u7B49\u7EA7"])?100:0).filter(e=>qe(pr(e),["status","state","type","category","level","\u72B6\u6001","\u7C7B\u578B","\u5206\u7C7B","\u7B49\u7EA7"])).slice(0,2)}function VH(t){return Zn(Gp(t),e=>{let r=pr(e);return qe(r,["amount","money","price","total","count","qty","\u79EF\u5206","\u4F59\u989D","\u91D1\u989D","\u4EF7\u683C","\u6570\u91CF"])?90:Qi(e)?60:0}).filter(e=>{let r=pr(e);return Qi(e)||qe(r,["amount","money","price","total","count","qty","\u79EF\u5206","\u4F59\u989D","\u91D1\u989D","\u4EF7\u683C","\u6570\u91CF"])}).slice(0,3)}function BH(t,e,r){let n=t.length?t:[_A(e,r,"CreateTime")],i=n.find(a=>Ur(a.name)==="createtime")||n.find(a=>Ur(a.name)==="updatetime")||n.find(a=>Ur(a.name)==="sort");if(i)return JSON.stringify([{Id:i.id,Name:i.name,Type:Ur(i.name)==="sort"?"ASC":"DESC",Sort:0}])}function UH(t,e,r,n){let i=Zr(t,"DefaultOrderBy");if(i!=null&&i!=="")return typeof i=="string"?i:JSON.stringify(i);let a=Zr(t,"defaultOrderBy");if(a!=null&&a!==""){let s=Array.isArray(a)||typeof a=="string"&&a.trim().startsWith("[")?ur({value:a},"value"):[{ref:String(a).trim(),type:"DESC"}];return JSON.stringify(ho(e,r,n,s,"module.defaultOrderBy").map(({meta:c,ref:l},u)=>({Id:c.id,Name:c.name,Type:l.type||"DESC",Sort:u})))}let o=ur(t,"orderBy","OrderBy","defaultSort","DefaultSort","sortBy","SortBy");if(o.length)return JSON.stringify(ho(e,r,n,o,"module.defaultOrderBy").map(({meta:s,ref:c},l)=>({Id:s.id,Name:s.name,Type:c.type||"DESC",Sort:l})))}function ZH(t,e,r,n){if(!r&&!n)return{};let i=Nv(e,r).length?Nv(e,r):Nv(e,n),a={},o=ur(t,"searchFields","SearchFields","searchFieldNames","SearchFieldNames"),s=o.length?ho(e,r,n,o,"module.searchFields"):zH(i).map(h=>({meta:h,ref:NH(h)}));!et(t,"searchFieldIds","SearchFieldIds")&&s.length&&(a.SearchFieldIds=JSON.stringify(s.map(({meta:h,ref:m})=>Dv(h,m))));let c=ur(t,"listFields","ListFields","tableFields","TableFields","columns","Columns"),l=c.length?ho(e,r,n,c,"module.listFields"):Gp(i).map(h=>({meta:h,ref:{ref:h.name}}));!et(t,"tableDiyFieldIds","TableDiyFieldIds")&&l.length&&(a.TableDiyFieldIds=JSON.stringify(l.map(({meta:h})=>h.id))),!et(t,"selectFields","SelectFields")&&l.length&&(a.SelectFields=JSON.stringify(l.map(({meta:h,ref:m})=>Dv(h,m))));let u=[{canonical:"SortFieldIds",explicitKeys:["sortFieldIds","SortFieldIds"],refKeys:["sortFields","SortFields"]},{canonical:"NotShowFields",explicitKeys:["notShowFields","NotShowFields"],refKeys:["hiddenFields","HiddenFields","notShowFieldsByName","NotShowFieldsByName"]},{canonical:"InTableEditFields",explicitKeys:["inTableEditFields","InTableEditFields"],refKeys:["editableFields","EditableFields","inTableEditFieldsByName","InTableEditFieldsByName"]},{canonical:"MobileListFields",explicitKeys:["mobileListFields","MobileListFields"],refKeys:["mobileFields","MobileFields"],objectArray:!0},{canonical:"CardTitleTagFields",explicitKeys:["cardTitleTagFields","CardTitleTagFields"],refKeys:["cardTitleFields","CardTitleFields"],objectArray:!0},{canonical:"CardBottomTagFields",explicitKeys:["cardBottomTagFields","CardBottomTagFields"],refKeys:["cardBottomFields","CardBottomFields"],objectArray:!0}];for(let h of u){if(et(t,...h.explicitKeys))continue;let m=ur(t,...h.refKeys),y={SortFieldIds:jH(i),NotShowFields:DH(i),MobileListFields:LH(i),CardTitleTagFields:qH(i),CardBottomTagFields:VH(i),InTableEditFields:[]};if(!m.length&&!y[h.canonical]?.length)continue;let g=m.length?ho(e,r,n,m,`module.${h.canonical}`):y[h.canonical].map(x=>({meta:x,ref:{ref:x.name}}));a[h.canonical]=JSON.stringify(h.objectArray?g.map(({meta:x,ref:b})=>Dv(x,b)):g.map(({meta:x})=>x.id))}let p=ur(t,"statisticsFieldNames","StatisticsFieldNames","statFields","StatFields");if(!et(t,"statisticsFields","StatisticsFields")){let h=p.length?ho(e,r,n,p,"module.statisticsFields"):FH(i).map(m=>({meta:m,ref:{ref:m.name,type:"Sum"}}));h.length&&(a.StatisticsFields=JSON.stringify(h.map(({meta:m,ref:y})=>({Id:m.id,Type:y.type||"Sum"}))))}let d=UH(t,e,r,n)||(et(t,"DefaultOrderBy","defaultOrderBy")?void 0:BH(i,r,n));return d&&(a.DefaultOrderBy=d),a}function JH(t,e,r){let n=Wp(we(e).Tables);for(let i of n){let a=S(i,"Id","id"),o=S(i,"Name","name");if(!a||!o)continue;r?.set(o.toLowerCase(),a);let s=Zr(i,"_Fields","Fields","fields"),c=Array.isArray(s)?Wp(s):[];for(let l of c){let u=S(l,"Id","id"),p=S(l,"Name","name");!u||!p||wA(t,{id:u,name:p,label:S(l,"Label","label")||p,tableId:a,tableName:o,tableDescription:S(i,"Description","description")||o,component:S(l,"Component","component")||"Text",type:S(l,"Type","type")||"varchar(255)"})}}}function EA(t){return Ur(S(t,"component","Component")||"Text")}function HH(t){return`${S(t,"name","Name")} ${S(t,"label","Label")} ${S(t,"component","Component")}`.toLowerCase()}function KH(t,e){let r=HH(t),n=EA(t);return["imgupload","fileupload","richtext","codeeditor","jsontable","tablechild","map","maparea","textarea"].includes(n)||qe(r,["remark","note","content","file","image","attach","map","\u5907\u6CE8","\u8BF4\u660E","\u5185\u5BB9","\u9644\u4EF6","\u56FE\u7247","\u5730\u56FE"])?"attachment":qe(r,["phone","mobile","email","address","city","contact","\u8054\u7CFB\u4EBA","\u7535\u8BDD","\u624B\u673A","\u90AE\u7BB1","\u5730\u5740","\u57CE\u5E02"])?"contact":qe(r,["status","state","type","category","amount","money","price","count","date","time","\u72B6\u6001","\u7C7B\u578B","\u5206\u7C7B","\u91D1\u989D","\u4EF7\u683C","\u6570\u91CF","\u65F6\u95F4","\u65E5\u671F"])?"business":e<8?"basic":"extra"}function kA(t){let e=he(t,"fields","Fields"),r=Zr(t,"tabs","Tabs"),n=new Map,i=ge(t,"column","Column")??(e.length>6?2:void 0);if(r!=null&&r!=="")return{fieldTabs:n,column:i};let a=e.filter(l=>!SA.has(EA(l)));if(a.length<=12)return{fieldTabs:n,column:i};let o={basic:{Name:"\u57FA\u7840\u4FE1\u606F",Icon:"fas fa-id-card",Sort:10},contact:{Name:"\u8054\u7CFB\u4FE1\u606F",Icon:"fas fa-address-book",Sort:20},business:{Name:"\u4E1A\u52A1\u4FE1\u606F",Icon:"fas fa-briefcase",Sort:30},attachment:{Name:"\u9644\u4EF6\u5907\u6CE8",Icon:"fas fa-paperclip",Sort:40},extra:{Name:"\u6269\u5C55\u4FE1\u606F",Icon:"fas fa-layer-group",Sort:50}},s=new Set;return a.forEach((l,u)=>{let p=S(l,"name","Name");if(!p||S(l,"tab","Tab"))return;let d=KH(l,u);n.set(p,d),s.add(d)}),{tabs:["basic","contact","business","attachment","extra"].filter(l=>s.has(l)).map(l=>({Id:l,Name:o[l].Name,Icon:o[l].Icon,Sort:o[l].Sort})),fieldTabs:n,column:i}}function uA(t){let e=[],r=[],n=[],i=he(t,"roles","Roles"),a=he(t,"tables","Tables"),o=he(t,"engines","Engines"),s=he(t,"modules","Modules"),c=he(t,"events","Events"),l=he(t,"dataSources","DataSources"),u=he(t,"pages","Pages"),p=he(t,"printTemplates","PrintTemplates"),d=he(t,"workflows","Workflows"),h=he(t,"jobs","Jobs"),m=he(t,"permissions","Permissions"),y=new Map;return!a.length&&!o.length&&!s.length&&!u.length&&r.push("Manifest \u672A\u58F0\u660E tables/engines/modules/pages\uFF0C\u53EF\u80FD\u4E0D\u662F\u5B8C\u6574\u7CFB\u7EDF\u8BA1\u5212"),i.forEach(g=>n.push(`save_role ${S(g,"name","Name")}`)),a.forEach((g,x)=>{let b=S(g,"name","Name");b||e.push(`tables[${x}].name \u4E0D\u80FD\u4E3A\u7A7A`),sA(g,`tables[${x}]`,e,r),n.push(`create_table ${b||`(index ${x})`}`),kA(g).tabs?.length&&r.push(`table ${b||`(index ${x})`} has many fields; generator will create diy_table.Tabs and assign empty field Tab values automatically`),b&&y.set(b.toLowerCase(),new Set),he(g,"fields","Fields").forEach((E,T)=>{let k=S(E,"name","Name"),A=S(E,"label","Label");k||e.push(`tables[${x}].fields[${T}].name \u4E0D\u80FD\u4E3A\u7A7A`),A||e.push(`tables[${x}].fields[${T}].label \u4E0D\u80FD\u4E3A\u7A7A`),b&&k&&y.get(b.toLowerCase())?.add(k.toLowerCase()),b&&A&&y.get(b.toLowerCase())?.add(A.toLowerCase()),n.push(`add_field ${b}.${k}`)});let w=new Set(he(g,"fields","Fields").map(E=>S(E,"name","Name").toLowerCase()).filter(Boolean));["id","createtime","updatetime","createuser","osclient"].forEach(E=>w.add(E)),he(g,"indexes","Indexes").forEach((E,T)=>{let k=xc(E,"columns","Columns");k.length||e.push(`tables[${x}].indexes[${T}].columns \u81F3\u5C11\u9700\u8981\u4E00\u4E2A\u5B57\u6BB5`);for(let A of k)w.has(A.toLowerCase())||e.push(`tables[${x}].indexes[${T}] references unknown physical field "${A}" on table "${b}"`);k.some((A,M)=>k.findIndex(P=>P.toLowerCase()===A.toLowerCase())!==M)&&e.push(`tables[${x}].indexes[${T}] \u5305\u542B\u91CD\u590D\u5B57\u6BB5`),n.push(`create_index ${b}.${S(E,"name","Name")||k.join("_")}`)})}),l.forEach(g=>n.push(`save_data_source ${S(g,"dataSourceKey","DataSourceKey")}`)),o.forEach((g,x)=>{let b=S(g,"apiEngineKey","ApiEngineKey");b||e.push(`engines[${x}].apiEngineKey \u4E0D\u80FD\u4E3A\u7A7A`),sA(g,`engines[${x}]`,e,r),n.push(`upsert_engine ${b}`)}),c.forEach(g=>n.push(`save_event ${S(g,"formEngineKey","FormEngineKey")}/${S(g,"eventType","EventType")}`)),s.forEach(g=>{let x=bo(g);e.push(...x.errors),r.push(...x.warnings);let b=S(g,"table","tableName","diyTableName","DiyTableName"),v=S(g,"name","Name");if(b&&y.has(b.toLowerCase())){let w=y.get(b.toLowerCase())||new Set,E=[["listFields",ur(g,"listFields","ListFields","tableFields","TableFields","columns","Columns")],["searchFields",ur(g,"searchFields","SearchFields","searchFieldNames","SearchFieldNames")],["sortFields",ur(g,"sortFields","SortFields")],["hiddenFields",ur(g,"hiddenFields","HiddenFields","notShowFieldsByName","NotShowFieldsByName")],["mobileFields",ur(g,"mobileFields","MobileFields")]];for(let[T,k]of E)for(let A of k)!w.has(A.ref.toLowerCase())&&!Uv(A.ref)&&e.push(`modules.${v||b}.${T} references unknown field "${A.ref}" on table "${b}"`)}b&&!ur(g,"listFields","ListFields","tableFields","TableFields","columns","Columns").length&&!et(g,"TableDiyFieldIds","SelectFields")&&r.push(`module ${v||b} has no listFields; generator will use the first business fields from ${b}`),n.push(`create_or_update_module ${S(g,"name","Name")}`)}),m.forEach(g=>n.push(`set_permission ${S(g,"roleId","RoleId")||"admin"}`)),u.forEach((g,x)=>{let b=un(g.json??g.JsonObj??g.JsonStr??g);e.push(...b.errors.map(v=>`pages[${x}]: ${v}`)),r.push(...b.warnings.map(v=>`pages[${x}]: ${v}`)),n.push(`save_page ${S(g,"title","Title")}`)}),p.forEach((g,x)=>{let b=Wi(g.PageObj??g.pageObj),v=Gi(g.PrintObj??g.printObj);e.push(...b.errors.map(w=>`printTemplates[${x}].PageObj: ${w}`)),r.push(...b.warnings.map(w=>`printTemplates[${x}].PageObj: ${w}`)),e.push(...v.errors.map(w=>`printTemplates[${x}].PrintObj: ${w}`)),r.push(...v.warnings.map(w=>`printTemplates[${x}].PrintObj: ${w}`)),n.push(`save_print_template ${S(g,"title","Title")}`)}),d.forEach((g,x)=>{let b=Bv(g);e.push(...b.errors.map(v=>`workflows[${x}]: ${v}`)),r.push(...b.warnings.map(v=>`workflows[${x}]: ${v}`)),n.push(`save_workflow ${S(we(g.FlowDesign??g.flowDesign??g),"FlowName","flowName","name")}`)}),h.forEach(g=>n.push(`save_job ${S(g,"jobName","JobName")}`)),{plan:n,errors:e,warnings:r}}function Hv(t){return{flow:we(t.FlowDesign??t.flowDesign??t),nodes:he(t,"Nodes","nodes"),lines:he(t,"Lines","lines")}}function go(t){return S(t,"Id","id","NodeId","nodeId")}function Xi(t){return S(t,"NodeName","nodeName","Name","name")}function TA(t){return S(t,"NodeType","nodeType","Type","type")}function Vv(t){let e=`${TA(t)} ${Xi(t)}`.toLowerCase();return e.includes("start")||e.includes("begin")||e.includes("\u5F00\u59CB")||e.includes("\u53D1\u8D77")}function pA(t){let e=`${TA(t)} ${Xi(t)}`.toLowerCase();return e.includes("end")||e.includes("finish")||e.includes("\u7ED3\u675F")||e.includes("\u5B8C\u6210")}function Bv(t){let e=[],r=[],{flow:n,nodes:i,lines:a}=Hv(t),o=S(n,"FlowName","flowName","Name","name"),s=S(n,"TableId","tableId"),c=S(n,"table","tableName","TableName","diyTableName","DiyTableName"),l=new Map,u=new Map,p=new Map;o||e.push("FlowDesign.FlowName \u4E0D\u80FD\u4E3A\u7A7A"),i.length||e.push("Nodes \u81F3\u5C11\u9700\u8981\u5305\u542B\u5F00\u59CB\u3001\u5BA1\u6279/\u4E1A\u52A1\u3001\u7ED3\u675F\u8282\u70B9"),a.length||e.push("Lines \u81F3\u5C11\u9700\u8981\u8FDE\u63A5\u5F00\u59CB\u5230\u4E0B\u4E00\u8282\u70B9"),!s&&!c&&r.push("FlowDesign.TableId \u4E3A\u7A7A\uFF1B\u666E\u901A\u5BA1\u6279\u6D41\u5EFA\u8BAE\u7ED1\u5B9A\u4E1A\u52A1 diy_table"),i.forEach((m,y)=>{let g=go(m),x=Xi(m);g||e.push(`Nodes[${y}].Id/NodeId \u4E0D\u80FD\u4E3A\u7A7A`),x||e.push(`Nodes[${y}].NodeName \u4E0D\u80FD\u4E3A\u7A7A`),g&&(l.has(g)&&e.push(`\u8282\u70B9 Id \u91CD\u590D\uFF1A${g}`),l.set(g,m))}),a.forEach((m,y)=>{let g=S(m,"Id","id","LineId","lineId")||`(index ${y})`,x=S(m,"FromNodeId","fromNodeId"),b=S(m,"ToNodeId","toNodeId");x||e.push(`Lines[${y}].FromNodeId \u4E0D\u80FD\u4E3A\u7A7A`),b||e.push(`Lines[${y}].ToNodeId \u4E0D\u80FD\u4E3A\u7A7A`),x&&!l.has(x)&&e.push(`\u8FDE\u7EBF ${g} \u7684 FromNodeId \u4E0D\u5B58\u5728\uFF1A${x}`),b&&!l.has(b)&&e.push(`\u8FDE\u7EBF ${g} \u7684 ToNodeId \u4E0D\u5B58\u5728\uFF1A${b}`),x===b&&x&&r.push(`\u8FDE\u7EBF ${g} \u6307\u5411\u81EA\u8EAB\uFF0C\u8BF7\u786E\u8BA4\u662F\u5426\u4E3A\u6709\u610F\u5FAA\u73AF`),x&&u.set(x,[...u.get(x)||[],m]),b&&p.set(b,[...p.get(b)||[],m])});let d=i.filter(Vv),h=i.filter(pA);return d.length!==1&&e.push(`\u9700\u8981\u4E14\u4EC5\u9700\u8981 1 \u4E2A\u5F00\u59CB\u8282\u70B9\uFF0C\u5F53\u524D ${d.length} \u4E2A`),h.length<1&&e.push("\u81F3\u5C11\u9700\u8981 1 \u4E2A\u7ED3\u675F\u8282\u70B9"),i.forEach(m=>{let y=go(m),g=Xi(m)||y;if(!y)return;let x=u.get(y)||[],b=p.get(y)||[];!Vv(m)&&b.length===0&&r.push(`\u8282\u70B9 ${g} \u6CA1\u6709\u5165\u7EBF`),!pA(m)&&x.length===0&&r.push(`\u8282\u70B9 ${g} \u6CA1\u6709\u51FA\u7EBF`),x.length>1&&(S(m,"LineValueV8","lineValueV8","V8Code","v8Code")||r.push(`\u8282\u70B9 ${g} \u6709 ${x.length} \u6761\u51FA\u7EBF\uFF0C\u5EFA\u8BAE\u914D\u7F6E LineValueV8\uFF0C\u5E76\u4F18\u5148\u7528 V8.NextNodeId \u6307\u5B9A\u4E0B\u4E00\u8282\u70B9`))}),{ok:e.length===0,errors:e,warnings:r,summary:{flowName:o,tableId:s,table:c,nodeCount:i.length,lineCount:a.length,startNodes:d.map(m=>({id:go(m),name:Xi(m)})),endNodes:h.map(m=>({id:go(m),name:Xi(m)}))}}}function WH(t){let e=t.indexOf(aA);if(e<0)return null;let r=e+aA.length,n=t.indexOf(yH,r);if(n<0)return null;try{return we(JSON.parse(t.slice(r,n).trim()))}catch{return null}}function dA(t){return t==null||String(t).trim()===""}function fA(t,e){let r=S(t,"field","Field"),n=S(t,"operator","Operator")||"eq",i=Zr(t,"value","Value"),a=r?e[r]:void 0,o=a==null?"":String(a),s=i==null?"":String(i);if(n==="empty")return dA(a);if(n==="notEmpty")return!dA(a);if(n==="contains")return o.includes(s);if(n==="notContains")return!o.includes(s);if(n==="startsWith")return o.startsWith(s);if(n==="endsWith")return s===""||o.endsWith(s);if(["gt","gte","lt","lte"].includes(n)){let c=Number(a),l=Number(i);return Number.isNaN(c)||Number.isNaN(l)?!1:n==="gt"?c>l:n==="gte"?c>=l:n==="lt"?c<l:c<=l}return n==="ne"?o!==s:o===s}function GH(t){let e=we(t.workflow),r=we(t.formData),n=S(t,"lineValueV8Code","LineValueV8","code");if(!n&&Object.keys(e).length>0){let{nodes:s}=Hv(e),c=S(t,"nodeId","NodeId"),l=(c?s.find(u=>go(u)===c):s.find(Vv)||s[0])||{};n=S(l,"LineValueV8","lineValueV8","V8Code","v8Code")}let i=WH(n),a=he(i||{},"routes","Routes");if(!i||a.length===0)return{ok:!1,selectedRoute:null,warnings:["\u672A\u627E\u5230\u56FE\u5F62\u6761\u4EF6\u6807\u8BB0\uFF0CMCP \u4E0D\u6267\u884C\u4EFB\u610F\u624B\u5199 V8\uFF1B\u8BF7\u7528\u56FE\u5F62\u6761\u4EF6\u751F\u6210 LineValueV8 \u540E\u518D\u6D4B\u8BD5\u3002"]};let o=a.find(s=>!!Zr(s,"isDefault","IsDefault"))||null;for(let s of a){if(s===o)continue;let c=he(s,"rules","Rules").filter(u=>S(u,"field","Field"));if(c.length===0)continue;if(S(s,"match","Match")==="any"?c.some(u=>fA(u,r)):c.every(u=>fA(u,r)))return{ok:!0,selectedRoute:s,assignment:mA(s),source:"matched"}}return{ok:!!o,selectedRoute:o,assignment:o?mA(o):null,source:o?"default":"none"}}function mA(t){let e=S(t,"lineValue","LineValue"),r=S(t,"toNodeId","ToNodeId");return e?{LineValue:e}:{NextNodeId:r}}function XH(t,e){let{flow:r,nodes:n,lines:i}=Hv(t),a={...r},o=S(r,"table","tableName","TableName","diyTableName","DiyTableName");if(!S(a,"TableId","tableId")&&o){let u=e.get(o.toLowerCase());u&&(a.TableId=u)}let s=new Map,c=n.map((u,p)=>{let d=go(u)||`wf_node_${p+1}_${zv().slice(0,8)}`,h={...u,Id:d},m=Xi(h);return m&&s.set(d,m),h}),l=i.map((u,p)=>{let d=S(u,"FromNodeId","fromNodeId"),h=S(u,"ToNodeId","toNodeId"),m=S(u,"LineName","lineName")||`${s.get(d)||d||"\u5F53\u524D\u8282\u70B9"} \u5230 ${s.get(h)||h||"\u4E0B\u4E00\u8282\u70B9"}`;return{...u,Id:S(u,"Id","id","LineId","lineId")||`wf_line_${p+1}_${zv().slice(0,8)}`,LineName:m}});return{FlowDesign:a,Nodes:c,Lines:l}}async function lr(t,e,r,n){try{await t.writeAuditLog(e,r,JSON.stringify(n).slice(0,6e3))}catch(i){console.error("[microi-mcp] audit log failed:",i instanceof Error?i.message:String(i))}}async function hA(t,e){let r=S(e,"apiEngineKey","ApiEngineKey"),n=S(e,"apiName","ApiName","name","Name")||r,i=S(e,"category","Category")||"AI\u751F\u6210",a=Zr(e,"code","Code","ApiV8Code"),o=typeof a=="string",s=o?String(a):"",c=Un(e,"v8Unlimited","V8Unlimited"),l=await t.getEngineCode(r);return l.Code===1?!o&&c!==void 0?t.updateEngineRuntimeConfig(r,c):o?t.saveEngineCode(r,s,{functionDescription:S(e,"functionDescription","FunctionDescription")||void 0,changeSummary:S(e,"changeSummary","ChangeSummary")||void 0,v8Unlimited:c}):{Code:1,Data:{ApiEngineKey:r,V8Unlimited:Number(l.Data?.V8Unlimited||0),Skipped:!0},Msg:"\u63A5\u53E3\u5F15\u64CE\u5DF2\u5B58\u5728\uFF0CManifest \u672A\u63D0\u4F9B code \u6216 V8Unlimited\uFF0C\u4FDD\u6301\u539F\u914D\u7F6E"}:t.createEngine({ApiEngineKey:r,ApiName:n,Category:i,Code:s,V8Unlimited:c===void 0?void 0:c?1:0,functionDescription:S(e,"functionDescription","FunctionDescription")||void 0,changeSummary:S(e,"changeSummary","ChangeSummary")||void 0})}function QH(t,e,r,n){let i=S(t,"table","tableName","diyTableName","DiyTableName"),a=bo(t);if(a.errors.length)throw new Error(a.errors.join(`
|
|
130
130
|
`));let o=S(t,"diyTableId","DiyTableId")||(i?e.get(i.toLowerCase()):""),s=i||S(t,"DiyTableName","diyTableName"),c=n?ZH(t,n,o||"",s):{};return dn({...a.data,...c,Name:S(t,"name","Name"),DiyTableId:o,ParentId:S(t,"parentId","ParentId")||(r?r.get(S(t,"parentName","ParentName").toLowerCase()):void 0),ComponentName:S(t,"componentName","ComponentName"),ComponentPath:S(t,"componentPath","ComponentPath"),Display:ge(t,"display","Display")??1,AppDisplay:ge(t,"appDisplay","AppDisplay")??1,OpenType:S(t,"openType","OpenType"),Url:S(t,"url","Url"),Sort:ge(t,"sort","Sort"),Icon:S(t,"icon","Icon"),SearchFieldIds:et(t,"searchFieldIds","SearchFieldIds")||c.SearchFieldIds,TableDiyFieldIds:et(t,"tableDiyFieldIds","TableDiyFieldIds")||c.TableDiyFieldIds,SelectFields:et(t,"selectFields","SelectFields")||c.SelectFields,DefaultOrderBy:et(t,"DefaultOrderBy")||c.DefaultOrderBy,SqlWhere:S(t,"sqlWhere","SqlWhere"),SqlJoin:S(t,"sqlJoin","SqlJoin"),JoinTables:et(t,"joinTables","JoinTables"),SortFieldIds:et(t,"sortFieldIds","SortFieldIds")||c.SortFieldIds,NotShowFields:et(t,"notShowFields","NotShowFields")||c.NotShowFields,StatisticsFields:et(t,"statisticsFields","StatisticsFields")||c.StatisticsFields,InTableEdit:ge(t,"inTableEdit","InTableEdit"),InTableEditFields:et(t,"inTableEditFields","InTableEditFields")||c.InTableEditFields,MobileListFields:et(t,"mobileListFields","MobileListFields")||c.MobileListFields,CardTitleTagFields:et(t,"cardTitleTagFields","CardTitleTagFields")||c.CardTitleTagFields,CardBottomTagFields:et(t,"cardBottomTagFields","CardBottomTagFields")||c.CardBottomTagFields,MenuBadgeEnabled:ge(t,"menuBadgeEnabled","MenuBadgeEnabled"),MenuBadgeApiEngineKey:S(t,"menuBadgeApiEngineKey","MenuBadgeApiEngineKey"),EnableViewSchema:ge(t,"enableViewSchema","EnableViewSchema"),ViewSchemaVersion:S(t,"viewSchemaVersion","ViewSchemaVersion"),ViewConfigVersion:ge(t,"viewConfigVersion","ViewConfigVersion"),ViewSchema:a.data.ViewSchema})}function gA(t){return dn({...t,Id:S(t,"Id","roleId","RoleId")||void 0,Name:S(t,"Name","name"),Level:ge(t,"Level","level"),Sort:ge(t,"Sort","sort"),Remark:S(t,"Remark","remark","description"),DeptIds:S(t,"DeptIds","deptIds"),BaseLimit:S(t,"BaseLimit","baseLimit")})}function yA(t){return dn({...t,Id:S(t,"Id","dataSourceId","DataSourceId")||void 0,DataSourceName:S(t,"DataSourceName","dataSourceName","name","Name"),DataSourceKey:S(t,"DataSourceKey","dataSourceKey"),DataSourceType:S(t,"DataSourceType","dataSourceType")||"V8",SqlDataSource:S(t,"SqlDataSource","sqlDataSource","sql"),V8DataSource:S(t,"V8DataSource","v8DataSource","code"),JsonDataSource:wc(t.JsonDataSource??t.jsonDataSource??t.json),TestParam:wc(t.TestParam??t.testParam),DataSourceRole:S(t,"DataSourceRole","dataSourceRole"),AllowAnonymous:ge(t,"AllowAnonymous","allowAnonymous"),IsEnable:ge(t,"IsEnable","isEnable")??1})}function bA(t){let e=Wi(t.PageObj??t.pageObj);if(!e.ok||!e.json)throw new Error(`printTemplates.${S(t,"Title","title")||"(untitled)"} PageObj invalid: ${e.errors.join("; ")}`);let r=Gi(t.PrintObj??t.printObj);if(!r.ok||!r.json)throw new Error(`printTemplates.${S(t,"Title","title")||"(untitled)"} PrintObj invalid: ${r.errors.join("; ")}`);return dn({...t,Id:S(t,"Id","printId","PrintId")||void 0,Title:S(t,"Title","title"),Number:S(t,"Number","number"),Desc:S(t,"Desc","desc","description"),DataApi:S(t,"DataApi","dataApi"),PageObj:e.json,PrintObj:r.json})}function vA(t){return dn({...t,Id:S(t,"Id","jobId","JobId")||void 0,JobName:S(t,"JobName","jobName","name","Name"),CronExpression:S(t,"CronExpression","cronExpression","cron"),JobType:S(t,"JobType","jobType")||"1",ApiEngineKey:S(t,"ApiEngineKey","apiEngineKey"),JobParam:wc(t.JobParam??t.jobParam??t.params),JobDesc:S(t,"JobDesc","jobDesc","description"),CronDesc:S(t,"CronDesc","cronDesc"),DllName:S(t,"DllName","dllName"),JobPath:S(t,"JobPath","jobPath")})}function YH(t){return{osClient:t,workflow:["Call microi_get_db_schema first to inspect existing tables.","Call microi_get_manifest_schema to draft a manifest from the user requirement.","Call microi_plan_system with the manifest and fix all errors.","Call microi_generate_system with dryRun=true.",`Call microi_generate_system with dryRun=false and confirmExecution="${t||"EXECUTE"}" only after the user confirms writes.`,"Call microi_validate_system after generation if you need an independent validation pass."],manifestShape:{name:"System name",roles:[{name:"Admin",level:999}],tables:[{name:"Biz_Order",description:"Order main table",v8Unlimited:!1,tabs:[{Id:"basic",Name:"Basic Info",Sort:10},{Id:"business",Name:"Business Info",Sort:20}],fields:[{name:"OrderNo",label:"Order No",type:"varchar(50)",component:"AutoNumber",tab:"basic",configSource:{sourceType:"AutoNumber",prefix:"ORD",length:6},notEmpty:1,unique:1,tableWidth:160,sort:10},{name:"CustomerName",label:"Customer",type:"varchar(100)",component:"Text",tab:"basic",notEmpty:1,tableWidth:160,sort:20},{name:"Status",label:"Status",type:"varchar(50)",component:"Select",tab:"business",configSource:{sourceType:"KeyValue",items:[{Key:"Draft",Value:"Draft"},{Key:"Submitted",Value:"Submitted"}]},sort:30}],indexes:[{name:"uk_biz_order_osclient_orderno",columns:["OsClient","OrderNo"],unique:!0,purpose:"Tenant-scoped order number invariant"},{name:"idx_biz_order_osclient_status_createtime",columns:["OsClient","Status","CreateTime"],unique:!1,purpose:"Status list ordered by creation time"}]}],engines:[{apiEngineKey:"biz_order_submit",apiName:"Submit order",category:"Biz_Order",v8Unlimited:!1,code:"return { Code: 1, Data: V8.Param };"},{apiEngineKey:"biz_order_metrics",apiName:"Order metrics",category:"Biz_Order",code:["var result = V8.FormEngine.GetTableData('Biz_Order', {"," _Where: [['Status', '=', 'Submitted']],"," _SelectFields: ['Id'],"," _PageIndex: 1,"," _PageSize: 1","});","if (result.Code !== 1) return result;","var count = result.DataCount || 0;","return { Code: 1, Data: { Value: count, Pending: count } };"].join(`
|
|
131
131
|
`)}],events:[{formEngineKey:"Biz_Order",eventType:"SubmitBeforeServerV8",code:"if (!V8.Form.OrderNo) return { Code: 0, Msg: 'OrderNo required' };"}],modules:[{name:"Orders",table:"Biz_Order",icon:"Document",listFields:["OrderNo","CustomerName","Status","CreateTime"],searchFields:["OrderNo","CustomerName","Status"],sortFields:["CreateTime"],defaultOrderBy:[{field:"CreateTime",type:"DESC"}],menuBadgeEnabled:1,menuBadgeApiEngineKey:"biz_order_metrics",enableViewSchema:1,viewSchemaVersion:"1.0",viewConfigVersion:1,viewSchema:{Views:[{Scene:"List",Device:"PC",Priority:100,Layout:{Hero:{Title:"Orders",Metrics:[{Key:"pending",Label:"Pending",ApiEngineKey:"biz_order_metrics",ValuePath:"Data.Pending",Tone:"warning"}]},List:{Density:"Comfortable",Columns:[{Field:"OrderNo",Lines:[{Name:"CustomerName",Label:"Customer",ShowLabel:!0,Tone:"info"}],TrailingFields:[{Name:"Status",DisplayStyle:"Tag"}],RequiredFields:["CustomerName","Status"]}]}}},{Scene:"Detail",Device:"All",Priority:100,Layout:{Hero:{Title:"Order Detail",TitleField:"OrderNo",StatusField:"Status"},Blocks:[{Type:"ResponsiveSection",Title:"Order Info",Fields:["OrderNo","CustomerName","Status"]}]}},{Scene:"Card",Device:"Mobile",Priority:100,Layout:{Card:{AvatarTextField:"CustomerName",TitleField:"OrderNo",SubtitleFields:["CustomerName"],StatusField:"Status",TopFields:[{Name:"Status",DisplayStyle:"Tag"}],RightFields:[{Name:"Amount",Format:"currency",Tone:"danger"}],Fields:[{Name:"CustomerName",Label:"Customer"},{Name:"CreateTime",Label:"Created At",Format:"datetime"}],MetaFields:[{Name:"CreateTime",Label:"Created At",Format:"datetime"}],BottomFields:[{Name:"Status",DisplayStyle:"Tag"}]}}}]},moreBtns:[{Name:"Submit",BtnStyle:"primary",V8CodeShow:"V8.Result=V8.Form.Status=='Draft';",V8Code:"var r=await V8.ApiEngine.Run({ApiEngineKey:'biz_order_submit',Id:V8.Form.Id});V8.Result=r;"}]}],permissions:[{roleId:"admin",moduleNames:["Orders"]}],dataSources:[],pages:[{title:"Operations Dashboard",number:"page_operations_dashboard",routePath:"/page/operations-dashboard",JsonObj:{formConfig:{gutter:0,mask:!1,drag:!1,hover:!1,shadow:!0,link:!0,dark:!1,dynamicStyle:{padding:"12px 0 0 0",backgroundColor:"#f3f4f6",opacity:1}},wrapperList:[{type:"pannel",label:"Card",wrapperOption:{span:24,height:180,titleOption:{hidden:!0,title:"Core Metrics"}},widgetList:[]}]}}],printTemplates:[{title:"Business Print Template",number:"print_business_template",PageObj:{panels:[{index:0,name:"A4 Template",paperType:"A4",height:297,width:210,paperHeader:0,paperFooter:841.8897637795277,printElements:[]}]},PrintObj:{}}],workflows:[{FlowDesign:{FlowName:"Order approval",TableId:"<Biz_Order table id or tableName-resolved id>",IsEnable:1},Nodes:[{Id:"start",NodeName:"\u53D1\u8D77\u4EBA",NodeType:"Start",AllowSelectUsers:0,PositionLeft:80,PositionTop:160,LineValueV8:""},{Id:"manager",NodeName:"\u90E8\u95E8\u7ECF\u7406\u5BA1\u6279",NodeType:"Approve",Roles:"Manager",AllowSelectUsers:1,PositionLeft:320,PositionTop:160},{Id:"end",NodeName:"\u7ED3\u675F",NodeType:"End",PositionLeft:560,PositionTop:160}],Lines:[{Id:"line_start_manager",FromNodeId:"start",ToNodeId:"manager",LineName:"\u53D1\u8D77\u4EBA \u5230 \u90E8\u95E8\u7ECF\u7406\u5BA1\u6279",LineValue:""},{Id:"line_manager_end",FromNodeId:"manager",ToNodeId:"end",LineName:"\u90E8\u95E8\u7ECF\u7406\u5BA1\u6279 \u5230 \u7ED3\u675F",LineValue:""}]}],jobs:[]},naturalFieldKeys:{tables:{tabs:"diy_table.Tabs form groups. When omitted and the table has more than 12 business fields, generator creates Basic/Contact/Business/Attachment/Extra tabs and assigns empty field tab values.",column:"Form column count. Omit to use 2 columns for generated systems unless the user asks for a single-column form.",indexes:"Physical database indexes. Declare ordered columns and unique. Required indexes must be created by microi_create_table_index or manifest generation, never by ad-hoc SQL. Tenant tables should usually lead with OsClient.",v8Unlimited:"Default false. Set true only when this table's backend V8 events must keep one database transaction and the user explicitly accepts unbounded Jint per-execution budgets. Process resident-memory protection remains active."},engines:{v8Unlimited:"Default false. Explicit high-risk opt-in for one API engine. It does not inherit to nested API engines; each child must opt in separately. Omit to preserve an existing engine setting during upsert."},fields:{component:"Use the real Microi component name. Available controls include Text, Textarea, NumberText, DateTime, Select, MultipleSelect, Radio, Checkbox, Switch, Rate, Progress, Slider, ColorPicker, AutoNumber, Divider, CollapseGroup, Tabs, Alert, StaticText, Html, RichText, CodeEditor, JsonTable, ImgUpload, FileUpload, Autocomplete, TagInput, Transfer, Cascader, Address, Department, SelectTree, TreeCheckbox, OpenTable, JoinTable, JoinForm, TableChild, Map, MapArea, Qrcode, FontAwesome, DevComponent.",tab:"Assign a field to a diy_table.Tabs Id/Name. For many fields, prefer table-level Tabs; use CollapseGroup or field component Tabs only when an in-page section needs collapsible or nested grouping."},modules:{table:"Bind by table name. The generator resolves the table Id after create/refresh schema.",listFields:"Field names/labels/ids for grid columns. Produces TableDiyFieldIds and SelectFields. When omitted, generator chooses title/no/status/person/amount/time fields.",searchFields:"Field names/labels/ids for search controls. Produces SearchFieldIds object array. When omitted, generator chooses title/no/status/type/category/person/time fields.",sortFields:"Field names/labels/ids for sortable fields. Produces SortFieldIds. When omitted, generator chooses date/time, Sort and numeric business fields.",hiddenFields:"Field names/labels/ids to hide. Produces NotShowFields. When omitted, generator hides Id-like fields, foreign keys, system fields and layout/large controls.",editableFields:"Field names/labels/ids for in-table editing. Produces InTableEditFields.",mobileFields:"Field names/labels/ids for mobile card list. Produces MobileListFields. When omitted, generator picks 3-4 compact title/status/summary fields.",cardTitleFields:"Field names/labels/ids for card title tags. Produces CardTitleTagFields. When omitted, generator picks status/type/category fields.",cardBottomFields:"Field names/labels/ids for card bottom tags. Produces CardBottomTagFields. When omitted, generator picks amount/count/date fields.",statisticsFields:"Field names/labels/ids for table footer statistics. When omitted, generator sums amount/price/count/point/balance numeric fields.",menuBadgeEnabled:"Set to 1 for important menus that need a sidebar statistic badge.",menuBadgeApiEngineKey:"API engine used by the sidebar statistic badge. Return {Code:1,Data:{Value:number}}; keep the query tenant-scoped and inexpensive.",enableViewSchema:"Set to 1 to enable the versioned cross-client view protocol stored in physical sys_menu columns.",viewSchema:"Versioned Detail/Edit/List/Card layouts for PC/Mobile/All. Layout.List supports multi-line columns and trailing fields; Layout.Card supports top/right/body/meta/bottom field groups. The full declarative object is preserved. Use ActionSchema only; never place arbitrary client V8Code in mobile actions."}},rules:["Use table and field names in manifests; do not ask the user for diy_field ids.","Put business logic in API engines and call them from menu button V8Code.",'For workflow manifests, include exactly one start node, at least one end node, valid FromNodeId/ToNodeId lines, and stable LineName values in the form "{from node} \u5230 {to node}".',"For multi-route workflow nodes, generate LineValueV8 with the visual condition marker and prefer assigning V8.NextNodeId; then call microi_check_workflow_package and microi_test_workflow_condition before microi_save_workflow_package.","Use parameterized V8.Db SQL or V8.FormEngine CRUD in engine/event code.","Never infer v8Unlimited=true from data volume alone. Enable it only for an explicit single-transaction requirement after warning about database locks, rollback cost, connection timeout and process memory; the resident-memory guard remains active.","Leave diy_field.FormWidth null/omitted for normal fields; use formWidth: 24 only for full-row controls such as CodeEditor, Textarea, RichText, upload, TableChild, map/layout/custom components.","Do not leave sys_menu list configuration empty. If the user does not specify it, rely on the generator defaults for NotShowFields, SearchFieldIds, SortFieldIds, StatisticsFields, MobileListFields, CardTitleTagFields and CardBottomTagFields.","Do not use diy_table.DiyConfig, diy_field.DiyConfig or sys_menu.DiyConfig for new configuration. Add dedicated physical columns and expose them through DIY metadata.","For forms with many fields, use diy_table.Tabs first. Use CollapseGroup for optional/secondary sections and field component Tabs for nested in-page grouping.","Use dryRun=true until the user explicitly asks to write.","For Page Engine pages, save only the JsonObj layer to mic_page.JsonObj: {formConfig, wrapperList}. Do not wrap it in formData.","For Print Engine templates, PageObj must be a hiprint object with panels[].printElements; PrintObj is sample/runtime data.","For natural-language UI or print design, prefer microi_build_page_design or microi_build_print_template_design, then save after confirmation."]}}function CA(t,e,r){let n=r.osClient,i=n||"EXECUTE";t.tool("microi_get_manifest_schema","Return the recommended full-system manifest schema for natural-language Microi generation, including field-name based module configuration.",{},async()=>Q(JSON.stringify(YH(n),null,2))),t.tool("microi_validate_menu_buttons","Validate and normalize sys_menu button/tab JSON arrays (MoreBtns/FormBtns/BatchSelectMoreBtns/PageTabs/ExportMoreBtns/PageBtns). Returns canonical JSON strings with generated Id/Sort/default visibility.",{moreBtns:f.unknown().optional(),formBtns:f.unknown().optional(),batchSelectMoreBtns:f.unknown().optional(),pageTabs:f.unknown().optional(),exportMoreBtns:f.unknown().optional(),pageBtns:f.unknown().optional()},async s=>{let c=bo(s);return Q(JSON.stringify({ok:c.errors.length===0,...c},null,2),c.errors.length>0)}),t.tool("microi_build_field_config",`Build and validate Microi diy_field Data/Config JSON for option controls, SQL/APIEngine/DataSource sources, JoinForm, AutoNumber and DateTime. OsClient: ${n}`,{sourceType:f.enum(["Data","KeyValue","Sql","ApiEngine","DataSource","AutoNumber","JoinForm","DateTime"]).describe("Config source type"),options:Tt.optional().describe("Source options, such as data/options, sql, apiEngineKey, dataSourceId, tableId, prefix, length")},async({sourceType:s,options:c})=>{let l=cA(s,c||{});return Q(JSON.stringify({ok:l.warnings.length===0,...l,configJson:JSON.stringify(l.config)},null,2))}),t.tool("microi_plan_system","Create a dry-run execution plan for a full low-code system manifest. This performs local structural validation only and does not write to Microi.",{manifest:Tt.describe("System manifest with tables, engines, modules, permissions, pages, dataSources, printTemplates, workflows, jobs")},async({manifest:s})=>{let c=uA(s);return Q(JSON.stringify({ok:c.errors.length===0,dryRun:!0,...c},null,2),c.errors.length>0)}),t.tool("microi_check_workflow_package","Validate a wf_flowdesign + wf_node + wf_line workflow package locally before saving. Checks topology, node ids, line endpoints, start/end nodes and multi-route condition setup.",{workflow:Tt.describe("Workflow package with FlowDesign, Nodes and Lines")},async({workflow:s})=>{let c=Bv(s);return Q(JSON.stringify(c,null,2),!c.ok)}),t.tool("microi_test_workflow_condition","Test a workflow LineValueV8 generated by the visual condition designer against sample formData. For safety this only evaluates Microi visual-condition marker JSON, not arbitrary hand-written V8.",{workflow:Tt.optional().describe("Optional workflow package; when provided the tool reads the selected node LineValueV8"),nodeId:f.string().optional().describe("Node Id whose LineValueV8 should be tested. If omitted, uses the start node or first node."),lineValueV8Code:f.string().optional().describe("Direct LineValueV8 JavaScript code containing MICROI_WF_LINE_CONDITION_JSON marker"),formData:Tt.optional().describe("Sample business form data used for rule evaluation")},async s=>Q(JSON.stringify(GH(s),null,2))),t.tool("microi_validate_system",`Validate that a generated low-code system exists on Microi server after generation. OsClient: ${n}`,{manifest:Tt.describe("The same manifest used by microi_generate_system")},async({manifest:s})=>{try{let c=await e.validateLowCodeSystem(s);return ft("Low-Code System Validation",c)}catch(c){return Q(`Error: ${c instanceof Error?c.message:String(c)}`,!0)}}),t.tool("microi_generate_system",`Generate a complete Microi low-code system from a manifest. Supports dryRun execution plans and post-generation validation. Writes require confirmExecution="${i}". OsClient: ${n}`,{manifest:Tt.describe("System manifest with tables, fields, dataSources, engines, events, modules, permissions, pages, printTemplates, workflows and jobs"),dryRun:f.boolean().optional().describe("Default true. When true, only returns an execution plan."),confirmExecution:f.string().optional().describe(`Required when dryRun=false. Must equal "${i}".`)},async({manifest:s,dryRun:c=!0,confirmExecution:l})=>{let u=uA(s);if(u.errors.length>0)return Q(JSON.stringify({ok:!1,...u},null,2),!0);if(c)return Q(JSON.stringify({ok:!0,dryRun:!0,...u},null,2));if(l!==i)return Q(`\u5199\u5165\u5DF2\u62E6\u622A\uFF1A\u8BF7\u91CD\u65B0\u8C03\u7528\u5E76\u4F20 confirmExecution="${i}"\u3002
|
|
132
132
|
|
|
@@ -235,7 +235,7 @@ dist/
|
|
|
235
235
|
</html>
|
|
236
236
|
`),i.set("vite.config.ts",EK()),i.set("tsconfig.json",kK()),i.set("src/env.d.ts",TK()),i.set("src/main.ts",CK()),i.set("src/App.vue",vK(t.name)),i.set("src/microi.ts",yK()),i.set("src/routes.ts",bK(e)),i.set("src/style.css",SK()),i.set("src/utils/microi.v8.js",t.sdkSource||gK()),e.forEach((s,c)=>{let l=c===0?xK(s.description||""):c===1?wK(s.description||""):_K(s.description||"",c);i.set(s.sourceFile,l)}),i}function Wv(t){let e=dK(t.aiApplicationsDirectory),r=String(t.appKey||"").trim(),n=String(t.name||"").trim();if(!nK.test(r))throw new Error("appKey \u53EA\u80FD\u4F7F\u7528\u5C0F\u5199\u5B57\u6BCD\u3001\u6570\u5B57\u3001\u8FDE\u5B57\u7B26\u548C\u4E0B\u5212\u7EBF\uFF0C\u957F\u5EA6\u4E0D\u8D85\u8FC7 64\u3002");if(!n||n.length>120)throw new Error("name \u4E0D\u80FD\u4E3A\u7A7A\u4E14\u4E0D\u80FD\u8D85\u8FC7 120 \u4E2A\u5B57\u7B26\u3002");let i=fK(t.buildVersion),a=hK(t.routes),o=$K({...t,appKey:r,name:n},a,i),s=[...o.entries()].map(([c,l])=>({relativePath:c,size:Buffer.byteLength(l,"utf8"),sha256:Kv.default.createHash("sha256").update(l,"utf8").digest("hex")})).sort((c,l)=>c.relativePath.localeCompare(l.relativePath));return{targetDirectory:at.default.join(e,r),appKey:r,name:n,buildVersion:i,routes:a,files:s,fileContents:o}}function AK(t){try{let e=Ct.default.lstatSync(t.targetDirectory);if(!e.isDirectory()||e.isSymbolicLink())return!1;let r=JSON.parse(Ct.default.readFileSync(at.default.join(t.targetDirectory,".microi-micro-app.json"),"utf8")),n=JSON.parse(Ct.default.readFileSync(at.default.join(t.targetDirectory,"microi.routes.json"),"utf8"));return r.appKey!==t.appKey||r.applicationType!=="MicroService"||n.length!==t.routes.length?!1:t.routes.every((i,a)=>{let o=n[a]||{};return o.path===i.path&&o.name===i.name&&o.title===i.title&&o.sourceFile===i.sourceFile&&!!o.isHome===i.isHome})}catch{return!1}}function RA(t){let e=Wv(t);if(Ct.default.existsSync(e.targetDirectory)){if(AK(e))return{created:!1,skipped:!0,targetDirectory:e.targetDirectory,appKey:e.appKey,fileCount:e.files.length,routes:e.routes};throw new Error(`\u76EE\u6807\u76EE\u5F55\u5DF2\u5B58\u5728\u4E14\u4E0D\u662F\u540C\u4E00\u4EFD\u811A\u624B\u67B6\uFF0C\u5DF2\u62D2\u7EDD\u8986\u76D6\uFF1A${e.targetDirectory}`)}let r=at.default.dirname(e.targetDirectory),n=at.default.join(r,`.${e.appKey}.microi-scaffold-${process.pid}-${Kv.default.randomUUID()}`);try{Ct.default.mkdirSync(n,{recursive:!1});for(let[i,a]of e.fileContents.entries()){let o=at.default.resolve(n,i);if(!o.startsWith(at.default.resolve(n)+at.default.sep))throw new Error(`\u811A\u624B\u67B6\u6587\u4EF6\u8D8A\u8FC7\u76EE\u6807\u76EE\u5F55\uFF1A${i}`);Ct.default.mkdirSync(at.default.dirname(o),{recursive:!0}),Ct.default.writeFileSync(o,a,"utf8")}PK(n,e.targetDirectory)}catch(i){throw Ct.default.existsSync(n)&&Ct.default.rmSync(n,{recursive:!0,force:!0}),i}return{created:!0,skipped:!1,targetDirectory:e.targetDirectory,appKey:e.appKey,fileCount:e.files.length,routes:e.routes}}function PK(t,e){let r=new Set(["EPERM","EACCES","EBUSY"]),n=[25,50,100,200];for(let i=0;;i+=1)try{Ct.default.renameSync(t,e);return}catch(a){let o=a?.code||"";if(!r.has(o)||i>=n.length)throw a;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,n[i])}}function Jn(t){if(Array.isArray(t))return t;if(!t||typeof t!="object")return[];let e=t;return Array.isArray(e.List)?e.List:Array.isArray(e.Data)?e.Data:[]}function kc(t,...e){if(!t||typeof t!="object")return"";let r=t;for(let n of e){let i=r[n];if(typeof i=="string"&&i.trim())return i}return""}var IK=new Set([".git",".svn",".hg","node_modules"]),RK=[/^\.env(?:\.|$)/iu,/^(?:id_rsa|id_dsa|id_ecdsa|id_ed25519)(?:\.|$)/iu,/\.(?:pem|key|pfx|p12|jks|keystore)$/iu],OA=128*1024*1024,$c=1024*1024*1024;function OK(t,e,r,n=$c){if(e>OA)throw new Error(`\u53D1\u5E03\u5355\u6587\u4EF6\u8D85\u8FC7\u786C\u4E0A\u9650 ${OA} bytes\uFF1A${t}\uFF1B\u5DF2\u5728\u4E0A\u4F20\u524D\u4E2D\u6B62\u3002`);if(r>Math.min(n,$c))throw new Error(`\u53D1\u5E03\u603B\u5927\u5C0F\u8D85\u8FC7\u4E0A\u9650 ${Math.min(n,$c)} bytes\uFF0C\u5DF2\u5728\u4E0A\u4F20\u524D\u4E2D\u6B62\u3002`)}function ed(t){let e=String(t||"").trim().replace(/\\/g,"/").replace(/^\.\//,""),r=e.split("/");if(!e||e.startsWith("/")||e.includes("//")||e.includes(":")||r.some(n=>!n||n==="."||n==="..")||/[\u0000-\u001f\u007f<>"|?*]/u.test(e))throw new Error(`\u5E94\u7528\u8D44\u4EA7\u76F8\u5BF9\u8DEF\u5F84\u4E0D\u5408\u6CD5\uFF1A${t}`);if(["versions","latest",".microi-integrity"].includes(r[0].toLowerCase()))throw new Error(`\u5E94\u7528\u8D44\u4EA7\u5360\u7528\u4E86\u53D1\u5E03\u5668\u4FDD\u7559\u76EE\u5F55\uFF1A${t}`);return e}async function VA(t){let e=Vt.default.createHash("sha256");for await(let r of Hn.default.createReadStream(t))e.update(r);return e.digest("hex")}function ta(t){return Vt.default.createHash("sha256").update(t.map(e=>String(e||"").trim()).join(`
|
|
237
237
|
`)).digest("hex")}function Bt(t){let e=String(t||"").trim().toLowerCase();return e.startsWith("v")?e:`v${e}`}function BA(t){return ta(["microi-application-asset-upload-v1",t.deliveryBatchId,t.appIdOrKey,Bt(t.versionNo),ed(t.relativePath),String(t.sha256||"").toLowerCase()])}function NK(t){return t.expectedCurrentVersion!==void 0||t.expectedAppVersion!==void 0?ta(["microi-application-finalize-v2",t.deliveryBatchId,t.appIdOrKey,Bt(t.versionNo),String(t.runtimeManifestHash||"").toLowerCase(),t.expectedCurrentVersion===void 0?"0:":`1:${t.expectedCurrentVersion}`,t.expectedAppVersion===void 0?"0:":`1:${JSON.stringify(t.expectedAppVersion)}`]):ta(["microi-application-finalize-v1",t.deliveryBatchId,t.appIdOrKey,Bt(t.versionNo),String(t.runtimeManifestHash||"").toLowerCase()])}function MK(t){return ta(["microi-application-stage-v1",t.deliveryBatchId,t.appIdOrKey,Bt(t.versionNo),String(t.runtimeManifestHash||"").toLowerCase()])}var wo=/^[a-f0-9]{64}$/u,ex=/^(0|[1-9]\d*)$/u,DK=/^[A-Za-z0-9._:-]{8,100}$/u,zK=/^[A-Za-z0-9._:-]{8,50}$/u,NA=/^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/u,td=1e3,jK=255;function Ac(t,e="Routes"){if(t===null)return"null";if(Array.isArray(t))return`[${t.map(r=>Ac(r,e)).join(",")}]`;if(typeof t=="object"){let r=t;return`{${Object.keys(r).sort().map(n=>`${JSON.stringify(n)}:${Ac(r[n],e)}`).join(",")}}`}if(typeof t=="string"||typeof t=="boolean"||typeof t=="number"&&Number.isSafeInteger(t))return JSON.stringify(t);throw new Error(`${e} \u53EA\u5141\u8BB8 JSON \u503C\uFF0Cnumber \u5FC5\u987B\u662F JavaScript safe integer`)}var UA=9223372036854775807n,FK=/^[A-Za-z0-9._:-]{8,100}$/u,LK=/^[A-Za-z0-9](?:[A-Za-z0-9._-]{0,98}[A-Za-z0-9])?$/u;function xo(t,e,{allowEmpty:r=!1,maxLength:n=1e3}={}){if(typeof t!="string"||t!==t.trim())throw new Error(`${e} \u5FC5\u987B\u662F\u65E0\u9996\u5C3E\u7A7A\u767D\u7684\u539F\u59CB\u5B57\u7B26\u4E32`);if(!r&&!t||t.length>n||/[\u0000-\u001f\u007f]/u.test(t))throw new Error(`${e} \u957F\u5EA6\u6216\u63A7\u5236\u5B57\u7B26\u4E0D\u5408\u6CD5`);return t}function qK(t){if(typeof t!="string"||!ex.test(t))throw new Error("ExpectedGateEpoch \u5FC5\u987B\u662F\u89C4\u8303\u975E\u8D1F\u5341\u8FDB\u5236\u5B57\u7B26\u4E32");if(BigInt(t)>UA)throw new Error("ExpectedGateEpoch \u8D85\u8FC7 Int64 \u4E0A\u9650");return t}function VK(t,e){let r=xo(t.osClient,"OsClient",{maxLength:100});if(!LK.test(r))throw new Error("OsClient \u53EA\u5141\u8BB8 1-100 \u4F4D ASCII \u5B57\u6BCD\u3001\u6570\u5B57\u3001\u70B9\u3001\u4E0B\u5212\u7EBF\u6216\u77ED\u6A2A\u7EBF");let n=xo(t.osClientType,"OsClientType",{allowEmpty:!0,maxLength:100}),i=xo(t.osClientNetwork,"OsClientNetwork",{allowEmpty:!0,maxLength:100}),a={osClient:e.osClient,osClientType:e.osClientType??"",osClientNetwork:e.osClientNetwork??""};if(r!==a.osClient||n!==a.osClientType||i!==a.osClientNetwork)throw new Error(`\u79DF\u6237\u5750\u6807\u4E0D\u5339\u914D\uFF1A\u8BF7\u6C42 ${r}|${n}|${i}\uFF0CMCP \u7ED1\u5B9A ${a.osClient}|${a.osClientType}|${a.osClientNetwork}`);let o=qK(t.expectedGateEpoch);if(BigInt(o)===UA)throw new Error("ExpectedGateEpoch \u5DF2\u8FBE Int64 \u4E0A\u9650\uFF0C\u65E0\u6CD5\u5B89\u5168\u9012\u589E\u95E8\u7981\u4EE3\u6B21");if(t.expectedMode==="V3Only"){if(t.expectedMinProtocol!==3||BigInt(o)<1n)throw new Error("ExpectedMode=V3Only \u8981\u6C42 ExpectedMinProtocol=3 \u4E14 ExpectedGateEpoch>0")}else if(t.expectedMinProtocol!==2)throw new Error(`ExpectedMode=${t.expectedMode} \u8981\u6C42 ExpectedMinProtocol=2`);let s=t.targetMode;if(!(t.expectedMode==="LegacyOpen"&&s==="Drain"||t.expectedMode==="Drain"&&(s==="V3Only"||s==="LegacyOpen")))throw t.expectedMode==="LegacyOpen"&&s==="V3Only"?new Error("\u7981\u6B62 LegacyOpen \u76F4\u63A5\u5207\u6362\u5230 V3Only\uFF1B\u5FC5\u987B\u5148\u8FDB\u5165 Drain"):t.expectedMode==="V3Only"?new Error("\u7981\u6B62\u4ECE V3Only \u964D\u7EA7\u6216\u518D\u6B21\u8F6C\u6362"):new Error(`\u4E0D\u5141\u8BB8\u95E8\u7981\u72B6\u6001\u8F6C\u6362 ${t.expectedMode} -> ${s}`);let l=xo(t.transitionId,"TransitionId",{maxLength:100});if(!FK.test(l))throw new Error("TransitionId \u5FC5\u987B\u662F 8-100 \u4F4D ASCII \u5B57\u6BCD\u3001\u6570\u5B57\u3001\u70B9\u3001\u4E0B\u5212\u7EBF\u3001\u5192\u53F7\u6216\u77ED\u6A2A\u7EBF");let u=xo(t.reason,"Reason",{maxLength:1e3}),p=xo(t.drainProofJson,"DrainProofJson",{maxLength:1024*1024});if(Buffer.byteLength(p,"utf8")>1024*1024)throw new Error("DrainProofJson \u7684 UTF-8 \u957F\u5EA6\u8D85\u8FC7 1 MiB \u5B89\u5168\u4E0A\u9650");let d;try{d=JSON.parse(p)}catch{throw new Error("DrainProofJson \u5FC5\u987B\u662F\u5408\u6CD5 JSON \u5BF9\u8C61")}if(!d||typeof d!="object"||Array.isArray(d))throw new Error("DrainProofJson \u5FC5\u987B\u662F JSON \u5BF9\u8C61");let h=Ac(d,"DrainProofJson");if(p!==h)throw new Error("DrainProofJson \u5FC5\u987B\u4F7F\u7528\u9012\u5F52\u952E\u6392\u5E8F\u3001\u65E0\u591A\u4F59\u7A7A\u767D\u7684 canonical JSON");if(!wo.test(t.drainProofHash))throw new Error("DrainProofHash \u5FC5\u987B\u662F 64 \u4F4D\u5C0F\u5199 SHA-256");let m=Vt.default.createHash("sha256").update(p,"utf8").digest("hex");if(t.drainProofHash!==m)throw new Error("DrainProofHash \u4E0E DrainProofJson \u7684 UTF-8 SHA-256 \u4E0D\u4E00\u81F4");let y={OsClient:r,OsClientType:n,OsClientNetwork:i,ExpectedMode:t.expectedMode,ExpectedMinProtocol:t.expectedMinProtocol,ExpectedGateEpoch:o,TargetMode:s,TargetMinProtocol:s==="V3Only"?3:2,TransitionId:l,Reason:u,DrainProofJson:p,DrainProofHash:t.drainProofHash},g=Ac(y,"ApplicationStreamGateTransition");return{payload:y,confirmationCanonicalJson:g,confirmationSha256:Vt.default.createHash("sha256").update(g,"utf8").digest("hex")}}function BK(t=[]){if(!Array.isArray(t))throw new Error("Routes \u5FC5\u987B\u662F\u6570\u7EC4\uFF0Cv3 \u7F3A\u7701\u503C\u4E3A\u663E\u5F0F []");let e=Ac(t);if(Buffer.byteLength(e,"utf8")>1024*1024)throw new Error("RouteSnapshotJson \u7684 UTF-8 \u957F\u5EA6\u8D85\u8FC7 1 MiB \u5B89\u5168\u4E0A\u9650");return{routeSnapshotJson:e,routeSnapshotHash:Vt.default.createHash("sha256").update(e,"utf8").digest("hex")}}function Qp(t,e,{positive:r=!1}={}){if(typeof t!="string"||!ex.test(t))throw new Error(`${e} \u5FC5\u987B\u662F\u89C4\u8303\u5341\u8FDB\u5236 bigint \u5B57\u7B26\u4E32`);if(r&&BigInt(t)<1n)throw new Error(`${e} \u5FC5\u987B\u5927\u4E8E 0`);return t}function MA(t,e){if(t===void 0)throw new Error(`${e} \u5FC5\u987B\u663E\u5F0F\u63D0\u4F9B\uFF1B\u7A7A\u57FA\u7EBF\u8BF7\u4F20 null`);if(t===null)return null;if(typeof t!="string"||!t.trim())throw new Error(`${e} \u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32\u6216 null`);let r=t.trim();if(r.length>64)throw new Error(`${e} \u957F\u5EA6\u4E0D\u80FD\u8D85\u8FC7 64`);return r}function UK(t,e){if(t.protocolVersion===void 0)return null;if(t.protocolVersion!==3)throw new Error("ProtocolVersion \u53EA\u652F\u6301\u663E\u5F0F v3\uFF1Bv2 \u8BF7\u7701\u7565\u8BE5\u5B57\u6BB5");if(t.publishMode!=="stage"&&t.publishMode!=="finalize")throw new Error("ProtocolVersion=3 \u53EA\u5141\u8BB8\u663E\u5F0F publishMode=stage|finalize");if(t.allowLegacyFallback===!0)throw new Error("ProtocolVersion=3 \u7981\u6B62 compatibility fallback");let r=String(t.requestId||"").trim();if(!DK.test(r))throw new Error("RequestId \u5FC5\u987B\u662F 8-100 \u4F4D\u7A33\u5B9A v3 \u8BF7\u6C42\u6807\u8BC6");let n=String(t.requestFingerprint||"").trim().toLowerCase();if(!wo.test(n))throw new Error("RequestFingerprint \u5FC5\u987B\u662F 64 \u4F4D\u5C0F\u5199 SHA-256");let i=String(t.deliveryBatchId||"").trim();if(!zK.test(i))throw new Error("DeliveryBatchId \u5FC5\u987B\u662F 8-50 \u4F4D\u7A33\u5B9A\u6807\u8BC6");let a=String(t.sourceManifestHash||"").trim().toLowerCase();if(!wo.test(a))throw new Error("SourceManifestHash \u662F v3 \u5FC5\u586B\u7684 64 \u4F4D\u5C0F\u5199 SHA-256");let o=String(t.runtimeManifestHash||"").trim().toLowerCase();if(!wo.test(o))throw new Error("RuntimeManifestHash \u662F v3 \u5FC5\u586B\u7684 64 \u4F4D\u5C0F\u5199 SHA-256");if(o!==e.toLowerCase())throw new Error("RuntimeManifestHash \u4E0E MCP \u672C\u5730\u6D41\u5F0F\u6E05\u5355\u4E0D\u4E00\u81F4");let s=BK(t.routes??[]);if(typeof t.routeSnapshotJson!="string"||t.routeSnapshotJson!==s.routeSnapshotJson)throw new Error("RouteSnapshotJson \u5FC5\u987B\u4E0E Routes \u7684\u9012\u5F52\u952E\u6392\u5E8F/UTF-8 canonical JSON \u7CBE\u786E\u4E00\u81F4");let c=String(t.routeSnapshotHash||"").trim().toLowerCase();if(!wo.test(c)||c!==s.routeSnapshotHash)throw new Error("RouteSnapshotHash \u5FC5\u987B\u662F RouteSnapshotJson \u7684\u5C0F\u5199 SHA-256");let l=t.expectedCurrentVersion;if(!Number.isSafeInteger(l)||Number(l)<0)throw new Error("ExpectedCurrentVersion \u662F v3 \u5FC5\u586B\u7684\u975E\u8D1F\u5B89\u5168\u6574\u6570");if(t.expectedAppVersion===void 0)throw new Error("ExpectedAppVersion \u5FC5\u987B\u663E\u5F0F\u63D0\u4F9B\uFF1B\u7A7A\u57FA\u7EBF\u8BF7\u4F20 null");if(t.expectedAppVersion!==null&&(typeof t.expectedAppVersion!="string"||!t.expectedAppVersion.trim()))throw new Error("ExpectedAppVersion \u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32\u6216 null\uFF1B\u7A7A\u57FA\u7EBF\u8BF7\u4F20 null");if(typeof t.expectedAppVersion=="string"&&t.expectedAppVersion.length>64)throw new Error("ExpectedAppVersion \u957F\u5EA6\u4E0D\u80FD\u8D85\u8FC7 64");let u=t.expectedVersionRowVersion===null?null:Qp(t.expectedVersionRowVersion,"ExpectedVersionRowVersion");return{protocolVersion:3,expectedGateEpoch:Qp(t.expectedGateEpoch,"ExpectedGateEpoch",{positive:!0}),requestId:r,requestFingerprint:n,deliveryBatchId:i,sourceManifestHash:a,runtimeManifestHash:o,routeSnapshotJson:s.routeSnapshotJson,routeSnapshotHash:s.routeSnapshotHash,expectedCurrentVersion:l,expectedAppVersion:t.expectedAppVersion,expectedPublishFence:Qp(t.expectedPublishFence,"ExpectedPublishFence"),expectedPublishRowVersion:Qp(t.expectedPublishRowVersion,"ExpectedPublishRowVersion"),expectedVersionRowVersion:u,expectedActivePublishVersionId:MA(t.expectedActivePublishVersionId,"ExpectedActivePublishVersionId"),expectedCommittedPublishVersionId:MA(t.expectedCommittedPublishVersionId,"ExpectedCommittedPublishVersionId")}}function ZK(t){return{ProtocolVersion:3,ExpectedGateEpoch:t.expectedGateEpoch,RequestId:t.requestId,RequestFingerprint:t.requestFingerprint,DeliveryBatchId:t.deliveryBatchId,SourceManifestHash:t.sourceManifestHash,RuntimeManifestHash:t.runtimeManifestHash,RouteSnapshotJson:t.routeSnapshotJson,RouteSnapshotHash:t.routeSnapshotHash,ExpectedCurrentVersion:t.expectedCurrentVersion,ExpectedAppVersion:t.expectedAppVersion,ExpectedPublishFence:t.expectedPublishFence,ExpectedPublishRowVersion:t.expectedPublishRowVersion,ExpectedVersionRowVersion:t.expectedVersionRowVersion,ExpectedActivePublishVersionId:t.expectedActivePublishVersionId,ExpectedCommittedPublishVersionId:t.expectedCommittedPublishVersionId}}function tx(t,e="v3 \u76F8\u5BF9\u8DEF\u5F84"){if(typeof t!="string"||!t||!t.trim())throw new Error(`${e} \u4E0D\u80FD\u4E3A\u7A7A`);if(t.length>td)throw new Error(`${e} \u539F\u59CB\u957F\u5EA6\u8D85\u8FC7 varchar(1000) \u8FB9\u754C`);if(t!==t.trim())throw new Error(`${e} \u4E0D\u80FD\u5305\u542B\u9996\u5C3E\u7A7A\u767D`);if(t.startsWith("/"))throw new Error(`${e} \u5FC5\u987B\u662F\u76F8\u5BF9\u8DEF\u5F84`);if(t.includes("\\"))throw new Error(`${e} \u7981\u6B62\u53CD\u659C\u6760`);if(/[%?#]/u.test(t))throw new Error(`${e} \u7981\u6B62\u9884\u7F16\u7801\u3001\u67E5\u8BE2\u4E32\u6216\u7247\u6BB5`);let r=[];for(let i of t.split("/")){if(!i)throw new Error(`${e} \u5305\u542B\u7A7A\u76EE\u5F55\u6BB5`);if(i==="."||i==="..")throw new Error(`${e} \u7981\u6B62\u76EE\u5F55\u904D\u5386`);if(/^(?:root|latest)$/iu.test(i))throw new Error(`${e} \u7981\u6B62 mutable root/latest \u6BB5`);if(i.length>jK)throw new Error(`${e} \u76EE\u5F55\u6BB5\u957F\u5EA6\u8D85\u8FC7 255`);if(/[\u0000-\u001f\u007f-\u009f]/u.test(i))throw new Error(`${e} \u7981\u6B62\u63A7\u5236\u5B57\u7B26`);let a=i.normalize("NFC");if(a!==i)throw new Error(`${e} \u5FC5\u987B\u4F7F\u7528 Unicode NFC \u89C4\u8303\u5F62\u5F0F`);try{r.push(encodeURIComponent(a))}catch{throw new Error(`${e} \u5305\u542B\u65E0\u6548 Unicode`)}}let n=r.join("/");if(n.length>td)throw new Error(`${e} \u7F16\u7801\u540E\u957F\u5EA6\u8D85\u8FC7 varchar(1000) \u8FB9\u754C`);return n}function JK(t){let e=t.appIdOrKey,r=Bt(t.versionNo);if(!NA.test(e)||e.length>128||/^(?:root|latest)$/iu.test(e))throw new Error("ProtocolVersion=3 \u7684 AppIdOrKey \u5FC5\u987B\u662F 1-128 \u4F4D Core v3 identity\uFF1B\u7981\u6B62 root/latest");if(!NA.test(r)||r.length>64||/^(?:root|latest)$/iu.test(r))throw new Error("ProtocolVersion=3 \u7684 VersionNo \u5FC5\u987B\u662F 1-64 \u4F4D Core v3 identity\uFF1B\u7981\u6B62 root/latest");if(!wo.test(t.requestFingerprint))throw new Error("ProtocolVersion=3 \u7684 RequestFingerprint \u5FC5\u987B\u662F 64 \u4F4D\u5C0F\u5199 SHA-256");let n=tx(t.relativePath),a=`${["microi","application-assets","v3","tenants","t".repeat(64),"kinds","k".repeat(32),"apps",e,"releases",r,"requests",t.requestFingerprint].join("/")}/assets/${n}`;if(a.length>td)throw new Error(`v3 \u8D44\u4EA7\u5B8C\u6574 immutable path \u8D85\u8FC7 varchar(1000) \u8FB9\u754C\uFF1A${t.relativePath}`);return{encodedRelativePath:n,immutablePath:a}}function HK(t,e,r){let n=new Map;for(let i of t.assets){let a=Yi.default.relative(t.rootDirectory,i.absolutePath).replace(/\\/gu,"/");if(a!==i.relativePath)throw new Error(`v3 \u6E05\u5355\u8DEF\u5F84\u88AB\u65E7\u7248\u89C4\u8303\u5316\u5668\u6539\u5199\uFF0C\u5DF2\u5728\u4E0A\u4F20\u524D\u62D2\u7EDD\uFF1A${a}`);let{encodedRelativePath:o}=JK({appIdOrKey:e.appIdOrKey,versionNo:e.versionNo,requestFingerprint:r.requestFingerprint,relativePath:i.relativePath});n.set(i.relativePath,o)}return tx(t.entryPath,"v3 EntryPath"),n}function Yp(t,e){if(typeof t!="string"||!t||t!==t.trim()||t.includes("\\")||t.length>td||/[\u0000-\u001f\u007f-\u009f]/u.test(t)||t.split("/").some(r=>/^(root|latest)$/iu.test(r)))throw new Error(`${e} \u7F3A\u5931\u6216\u5305\u542B v3 \u7981\u6B62\u7684 root/latest mutable \u6BB5`);return t}function KK(t,e){let r=rd(t.Data),n=`v3 \u5E94\u7528\u8D44\u4EA7 ${e.relativePath}`;if(ea(r,"ProtocolVersion",3,n),me(r,"PublishMode","stage",n),me(r,"GateEpoch",e.expectedGateEpoch,n),me(r,"RequestId",e.requestId,n),me(r,"RequestFingerprint",e.requestFingerprint,n),me(r,"RouteSnapshotJson",e.routeSnapshotJson,n),me(r,"RouteSnapshotHash",e.routeSnapshotHash,n),me(r,"VersionNo",Bt(e.versionNo),n),me(r,"Path",e.relativePath,n),me(r,"Sha256",e.sha256,n),ea(r,"Size",e.size,n),String(r.PublishState||"")!=="Prepared"||String(r.PointerState||"")!=="Uncommitted"||r.Pending!==!0)throw new Error(`${n} \u5FC5\u987B\u8FD4\u56DE Prepared/Uncommitted/Pending=true`);let i=Cc(r,"FencingToken",n,{positive:!0});if(BigInt(i)<=BigInt(e.expectedPublishFence))throw new Error(`${n}.FencingToken \u5FC5\u987B\u4E25\u683C\u5927\u4E8E ExpectedPublishFence`);let a=Yp(r.ReleaseFilePath,`${n}.ReleaseFilePath`);if(!a.includes(`/releases/${Bt(e.versionNo)}/requests/${e.requestFingerprint}/assets/`)||!a.endsWith(`/${e.encodedRelativePath}`))throw new Error(`${n}.ReleaseFilePath \u672A\u7ED1\u5B9A immutable release/request/path`);return r}function WK(t,e){let r=rd(t.Data),n=`v3 ${e.publishMode}`;ea(r,"ProtocolVersion",3,n),me(r,"PublishMode",e.publishMode,n),me(r,"GateEpoch",e.expectedGateEpoch,n),me(r,"AppKey",e.appIdOrKey,n),me(r,"VersionNo",Bt(e.versionNo),n),me(r,"RequestId",e.requestId,n),me(r,"RequestFingerprint",e.requestFingerprint,n),me(r,"DeliveryBatchId",e.deliveryBatchId,n),me(r,"RuntimeManifestHash",e.runtimeManifestHash,n),me(r,"SourceManifestHash",e.sourceManifestHash,n),me(r,"RouteSnapshotJson",e.routeSnapshotJson,n),me(r,"RouteSnapshotHash",e.routeSnapshotHash,n);let i=String(r.VersionId||"").trim();if(!i)throw new Error(`${n}.VersionId \u4E0D\u80FD\u4E3A\u7A7A`);let a=Cc(r,"PublishFence",n),o=Cc(r,"PublishRowVersion",n),s=Cc(r,"VersionRowVersion",n,{positive:!0});if(r.V3Only!==!0)throw new Error(`${n}.V3Only \u5FC5\u987B\u4E3A true`);let c=Array.isArray(r.AllowedModes)?r.AllowedModes.map(String):[];if(!c.includes("stage")||!c.includes("finalize"))throw new Error(`${n}.AllowedModes \u5FC5\u987B\u5305\u542B stage/finalize`);let l=String(r.PublishState||"");if(e.publishMode==="stage"){if(me(r,"PhaseState","ReleaseVerified",n),l!=="ReleaseVerified"||String(r.PointerState||"")!=="Uncommitted"||r.Pending!==!1)throw new Error("v3 stage \u5FC5\u987B\u8FD4\u56DE ReleaseVerified/Uncommitted/Pending=false");if(a!==e.expectedPublishFence||o!==e.expectedPublishRowVersion)throw new Error("v3 stage \u4E0D\u5F97\u524D\u6EDA sys_microistore pointer fence/rowversion");let h=Cc(r,"FencingToken",n,{positive:!0});if(BigInt(h)<=BigInt(e.expectedPublishFence))throw new Error("v3 stage.FencingToken \u5FC5\u987B\u4E25\u683C\u5927\u4E8E ExpectedPublishFence")}else{let h=String(r.AppPublishState||""),m=new Set(["PointerCommitted","ProjectionPending","RepairRequired","Completed"]),y=l==="Completed"&&h==="Completed",g=!y&&m.has(l)&&m.has(h);if(String(r.PointerState||"")!=="Committed"||g&&r.Pending!==!0||y&&r.Pending!==!1||!g&&!y||r.Completed!==y||r.ProjectionPending!==!y)throw new Error(`v3 finalize \u8FD4\u56DE\u975E\u6CD5\u72B6\u6001 version=${l||"(empty)"}, app=${h||"(empty)"}`);if(me(r,"CommittedPublishVersionId",i,n),me(r,"CommittedRuntimeManifestHash",e.runtimeManifestHash,n),BigInt(a)<=BigInt(e.expectedPublishFence))throw new Error("v3 finalize.PublishFence \u5FC5\u987B\u4E25\u683C\u5927\u4E8E ExpectedPublishFence");if(BigInt(o)!==BigInt(e.expectedPublishRowVersion)+1n)throw new Error("v3 finalize.PublishRowVersion \u5FC5\u987B\u7CBE\u786E\u524D\u6EDA 1");if(e.expectedVersionRowVersion!==null&&BigInt(s)<=BigInt(e.expectedVersionRowVersion))throw new Error("v3 finalize.VersionRowVersion \u5FC5\u987B\u4E25\u683C\u524D\u6EDA")}let u=Yp(r.ReleasePrefix,`${n}.ReleasePrefix`),p=Yp(r.ReleaseEntryPath,`${n}.ReleaseEntryPath`),d=Yp(r.StableResolverPath,`${n}.StableResolverPath`);if(!u.endsWith(`/releases/${Bt(e.versionNo)}/requests/${e.requestFingerprint}`)||!p.startsWith(`${u}/assets/`)||!p.endsWith(`/${e.encodedEntryPath}`))throw new Error(`${n} immutable release \u8DEF\u5F84\u4E0D\u4E00\u81F4`);if(!/(^|\/)micro-app\/v3\/tenants\//u.test(d)||d.includes("/releases/")||d.includes("/requests/"))throw new Error(`${n}.StableResolverPath \u4E0D\u662F versionless v3 resolver`);return r}async function GK(t,e="index.html",r={}){let n=Yi.default.resolve(t),i=Hn.default.lstatSync(n);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`\u53D1\u5E03\u6839\u76EE\u5F55\u5FC5\u987B\u662F\u771F\u5B9E\u76EE\u5F55\u4E14\u4E0D\u80FD\u662F\u7B26\u53F7\u94FE\u63A5\uFF1A${n}`);let a=Hn.default.realpathSync(n),o=ed(e),s=Math.min(2e4,Math.max(1,r.maxFiles??2e4)),c=Math.min($c,Math.max(1,r.maxTotalBytes??$c)),l=[a],u=[],p=[],d=[],h=0;for(;l.length>0;){let g=l.pop();for(let x of Hn.default.readdirSync(g,{withFileTypes:!0})){let b=Yi.default.join(g,x.name),v=Hn.default.lstatSync(b);if(v.isSymbolicLink())throw new Error(`\u53D1\u5E03\u76EE\u5F55\u4E0D\u5141\u8BB8\u7B26\u53F7\u94FE\u63A5\uFF1A${b}`);let w=ed(Yi.default.relative(a,b)),E=Hn.default.realpathSync(b);if(E!==a&&!E.startsWith(a+Yi.default.sep))throw new Error(`\u53D1\u5E03\u8D44\u4EA7\u8D8A\u8FC7\u4E86\u6839\u76EE\u5F55\uFF1A${b}`);if(v.isDirectory()){if(IK.has(x.name.toLowerCase()))throw new Error(`\u53D1\u5E03\u76EE\u5F55\u5305\u542B\u7981\u6B62\u4E0A\u4F20\u7684\u76EE\u5F55 ${x.name}\uFF1B\u8BF7\u4F20\u5165\u771F\u5B9E\u7F16\u8BD1\u8F93\u51FA\u76EE\u5F55\uFF0C\u800C\u4E0D\u662F\u9879\u76EE\u6839\u76EE\u5F55\u3002`);l.push(b);continue}if(!v.isFile())throw new Error(`\u53D1\u5E03\u76EE\u5F55\u5305\u542B\u975E\u666E\u901A\u6587\u4EF6\uFF1A${b}`);if(RK.some(T=>T.test(x.name)))throw new Error(`\u53D1\u5E03\u76EE\u5F55\u7591\u4F3C\u5305\u542B\u5BC6\u94A5\u6216\u73AF\u5883\u914D\u7F6E\uFF0C\u5DF2\u62D2\u7EDD\u4E0A\u4F20\uFF1A${w}`);if(w.toLowerCase()===".microi-build-evidence.json"){d.push(w);continue}if(!r.includeSourceMaps&&w.toLowerCase().endsWith(".map")){p.push(w);continue}if(OK(w,v.size,h+v.size,c),u.push({absolutePath:b,relativePath:w,size:v.size}),h+=v.size,u.length>s)throw new Error(`\u53D1\u5E03\u6587\u4EF6\u8D85\u8FC7\u4E0A\u9650 ${s}\uFF0C\u8BF7\u68C0\u67E5\u662F\u5426\u8BEF\u9009\u9879\u76EE\u6839\u76EE\u5F55\u6216\u4EA7\u751F\u5783\u573E\u6587\u4EF6\u3002`)}}if(u.sort((g,x)=>g.relativePath<x.relativePath?-1:g.relativePath>x.relativePath?1:0),!u.some(g=>g.relativePath.toLowerCase()===o.toLowerCase()))throw new Error(`\u53D1\u5E03\u76EE\u5F55\u7F3A\u5C11\u5165\u53E3\u6587\u4EF6\uFF1A${o}`);let m=[];for(let g of u)m.push({...g,sha256:await VA(g.absolutePath),isEntry:g.relativePath.toLowerCase()===o.toLowerCase()});let y=Vt.default.createHash("sha256").update(m.map(g=>`${g.relativePath} ${g.sha256} ${g.size}`).join(`
|
|
238
|
-
`)).digest("hex");return{rootDirectory:a,entryPath:o,assets:m,totalSize:h,manifestHash:y,skippedSourceMaps:p,skippedInternalEvidenceFiles:d}}var Nae=5*1024*1024;function XK(t){if(!t||Number(t.Code)===1)return!1;let e=String(t.Msg||"");return/Newtonsoft\.Json\.Linq\.JValue/iu.test(e)&&/does not contain a definition for ['‘’"]?Val|\.Val(?:<|\b)/iu.test(e)}function rd(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function me(t,e,r,n){if(String(t[e]??"")!==r)throw new Error(`${n} \u8FD4\u56DE\u8BC1\u636E ${e} \u4E0D\u4E00\u81F4`)}function ea(t,e,r,n){if(!Number.isFinite(Number(t[e]))||Number(t[e])!==r)throw new Error(`${n} \u8FD4\u56DE\u8BC1\u636E ${e} \u4E0D\u4E00\u81F4`)}function Cc(t,e,r,{positive:n=!1}={}){let i=t[e];if(typeof i!="string"||!ex.test(i)||n&&BigInt(i)<1n)throw new Error(`${r}.${e} \u5FC5\u987B\u662F${n?"\u6B63":"\u975E\u8D1F"}\u89C4\u8303\u5341\u8FDB\u5236 bigint \u5B57\u7B26\u4E32`);return i}function ZA(t,e){let r=rd(t.Data),n=`\u5E94\u7528\u8D44\u4EA7 ${e.relativePath}`;if(me(r,"RequestId",e.requestId,n),me(r,"VersionNo",Bt(e.versionNo),n),me(r,"Path",e.relativePath,n),me(r,"Sha256",e.sha256,n),ea(r,"Size",e.size,n),r.StablePromoted!==!1)throw new Error(`${n} \u8FD4\u56DE\u8BC1\u636E StablePromoted \u5FC5\u987B\u4E3A false`);return r}function QK(t,e){let r=rd(t.Data),n="\u5E94\u7528\u6E05\u5355\u786E\u8BA4";if(me(r,"RequestId",e.requestId,n),me(r,"VersionNo",Bt(e.versionNo),n),me(r,"EntryPath",e.entryPath,n),me(r,"DeliveryBatchId",e.deliveryBatchId,n),me(r,"RuntimeManifestHash",e.runtimeManifestHash,n),ea(r,"AssetCount",e.assetCount,n),ea(r,"TotalSize",e.totalSize,n),e.expectedCurrentVersion!==void 0&&ea(r,"ExpectedCurrentVersion",e.expectedCurrentVersion,n),e.expectedAppVersion!==void 0&&me(r,"ExpectedAppVersion",e.expectedAppVersion,n),r.StablePromoted!==!0)throw new Error(`${n} \u8FD4\u56DE\u8BC1\u636E StablePromoted \u5FC5\u987B\u4E3A true`);if(String(r.PublishStatus||"")!=="Published")throw new Error(`${n} \u8FD4\u56DE\u8BC1\u636E PublishStatus \u5FC5\u987B\u4E3A Published`);if(String(r.VerificationStatus||"")!=="Verified")throw new Error(`${n} \u8FD4\u56DE\u8BC1\u636E VerificationStatus \u5FC5\u987B\u4E3A Verified`);return r}async function YK(t,e){let r=e.publishMode||"stage-and-finalize";try{if(e.confirmExecution&&e.confirmExecution!==e.appIdOrKey)return{content:[{type:"text",text:`Error: confirmExecution \u5FC5\u987B\u7CBE\u786E\u7B49\u4E8E ${e.appIdOrKey}`}],isError:!0};if(e.confirmExecution===e.appIdOrKey&&r!=="stage"&&(e.expectedCurrentVersion===void 0||e.expectedAppVersion===void 0))return{content:[{type:"text",text:JSON.stringify({error:"finalize \u5FC5\u987B\u540C\u65F6\u4F20\u5165 expectedCurrentVersion \u4E0E expectedAppVersion\uFF1B\u8BF7\u5148\u56DE\u8BFB\u5E94\u7528\u4E0A\u4E0B\u6587\u5E76\u51BB\u7ED3\u53D1\u5E03\u57FA\u7EBF\u3002",publishMode:r,stablePromoted:!1,retrySafe:!0,expectedStateRequired:!0},null,2)}],isError:!0};let n=await GK(e.directory,e.entryPath||"index.html",{includeSourceMaps:e.includeSourceMaps,maxFiles:e.maxFiles,maxTotalBytes:e.maxTotalMegabytes?Math.floor(e.maxTotalMegabytes*1024*1024):void 0}),i=UK(e,n.manifestHash),a=i?HK(n,e,i):null,o=i?.deliveryBatchId||e.deliveryBatchId||`mcp-${ta(["microi-application-delivery-v1",e.appIdOrKey,Bt(e.versionNo),n.manifestHash]).slice(0,40)}`,s=i?.requestId||MK({deliveryBatchId:o,appIdOrKey:e.appIdOrKey,versionNo:e.versionNo,runtimeManifestHash:n.manifestHash}),c=i?.requestId||NK({deliveryBatchId:o,appIdOrKey:e.appIdOrKey,versionNo:e.versionNo,runtimeManifestHash:n.manifestHash,expectedCurrentVersion:e.expectedCurrentVersion,expectedAppVersion:e.expectedAppVersion}),l=n.assets.map(b=>({Path:b.relativePath,RequestId:i?.requestId||BA({deliveryBatchId:o,appIdOrKey:e.appIdOrKey,versionNo:e.versionNo,relativePath:b.relativePath,sha256:b.sha256})})),u=ta(l.flatMap(b=>[b.Path,b.RequestId]));if(e.confirmExecution!==e.appIdOrKey)return{content:[{type:"text",text:JSON.stringify({dryRun:!0,publishMode:r,confirmationRequired:e.appIdOrKey,rootDirectory:n.rootDirectory,entryPath:n.entryPath,assetCount:n.assets.length,totalSize:n.totalSize,runtimeManifestHash:n.manifestHash,deliveryBatchId:o,...e.expectedCurrentVersion!==void 0?{expectedCurrentVersion:e.expectedCurrentVersion}:{},...e.expectedAppVersion!==void 0?{expectedAppVersion:e.expectedAppVersion}:{},finalizePreconditionsRequired:r!=="stage",requestId:r==="stage"?s:c,...i?{protocolVersion:3,expectedGateEpoch:i.expectedGateEpoch,requestFingerprint:i.requestFingerprint,routeSnapshotJson:i.routeSnapshotJson,routeSnapshotHash:i.routeSnapshotHash,expectedPublishFence:i.expectedPublishFence,expectedPublishRowVersion:i.expectedPublishRowVersion,expectedVersionRowVersion:i.expectedVersionRowVersion,expectedActivePublishVersionId:i.expectedActivePublishVersionId,expectedCommittedPublishVersionId:i.expectedCommittedPublishVersionId}:{},assetRequestManifestHash:u,skippedSourceMaps:n.skippedSourceMaps,skippedInternalEvidenceFiles:n.skippedInternalEvidenceFiles,assetsPreview:n.assets.slice(0,200).map((b,v)=>({Path:b.relativePath,Size:b.size,Sha256:b.sha256,RequestId:l[v].RequestId})),previewTruncated:n.assets.length>200},null,2)}]};let p=0,d=0;if(r!=="finalize"){let b=new Map(l.map(w=>[w.Path,w.RequestId])),v=[...n.assets].sort((w,E)=>Number(w.isEntry)-Number(E.isEntry));for(let w of v){let E=b.get(w.relativePath),T;try{T=await t.uploadApplicationAssetStream({AppIdOrKey:e.appIdOrKey,VersionNo:e.versionNo,RelativePath:w.relativePath,ExpectedSha256:w.sha256,RequestId:E,FilePath:w.absolutePath,TimeoutMs:e.timeoutMsPerFile,...i?{ProtocolVersion:3,ExpectedGateEpoch:i.expectedGateEpoch,RequestFingerprint:i.requestFingerprint,DeliveryBatchId:i.deliveryBatchId,SourceManifestHash:i.sourceManifestHash,RuntimeManifestHash:i.runtimeManifestHash,RouteSnapshotJson:i.routeSnapshotJson,RouteSnapshotHash:i.routeSnapshotHash,ExpectedCurrentVersion:i.expectedCurrentVersion,ExpectedAppVersion:i.expectedAppVersion,ExpectedPublishFence:i.expectedPublishFence,ExpectedPublishRowVersion:i.expectedPublishRowVersion,ExpectedVersionRowVersion:i.expectedVersionRowVersion,ExpectedActivePublishVersionId:i.expectedActivePublishVersionId,ExpectedCommittedPublishVersionId:i.expectedCommittedPublishVersionId}:{}})}catch(A){return{content:[{type:"text",text:JSON.stringify({error:A instanceof Error?A.message:String(A),failedPath:w.relativePath,requestId:E,uploadedCount:p,totalCount:n.assets.length,publishMode:r,retrySafe:!0},null,2)}],isError:!0}}if(T.Code!==1){let A=XK(T);return{content:[{type:"text",text:JSON.stringify({error:T.Msg,failedPath:w.relativePath,requestId:E,uploadedCount:p,totalCount:n.assets.length,publishMode:r,retrySafe:!0,requiresRequestIdCapableApi:A,compatibilityFallbackAttempted:!1,compatibilityFallbackDisabled:e.allowLegacyFallback===!0},null,2)}],isError:!0}}let k;try{k=i?KK(T,{...i,versionNo:e.versionNo,relativePath:w.relativePath,encodedRelativePath:a.get(w.relativePath),sha256:w.sha256,size:w.size}):ZA(T,{requestId:E,versionNo:e.versionNo,relativePath:w.relativePath,sha256:w.sha256,size:w.size})}catch(A){return{content:[{type:"text",text:JSON.stringify({error:A instanceof Error?A.message:String(A),failedPath:w.relativePath,requestId:E,uploadedCount:p,totalCount:n.assets.length,publishMode:r,retrySafe:!0,evidenceMismatch:!0},null,2)}],isError:!0}}p+=1,k.Idempotent===!0&&(d+=1),(p===1||p%25===0||p===n.assets.length)&&console.error(`[microi-mcp] Stream stage ${e.appIdOrKey} ${e.versionNo}: ${p}/${n.assets.length}`)}}if(r==="stage"&&!i){let b={appIdOrKey:e.appIdOrKey,versionNo:Bt(e.versionNo),deliveryBatchId:o,runtimeManifestHash:n.manifestHash,assetRequestManifestHash:u,assetCount:n.assets.length,stagedCount:n.assets.length,uploadedCount:n.assets.length,idempotentCount:d,totalSize:n.totalSize,transport:"multipart-stream-to-hdfs-stage-only",jintFileBytes:0,publishMode:r,requestId:s,StablePromoted:!1};return{content:[{type:"text",text:JSON.stringify(b,null,2)}]}}let h;try{h=await t.finalizeApplicationStreamPublish({AppIdOrKey:e.appIdOrKey,VersionNo:e.versionNo,EntryPath:n.entryPath,Assets:n.assets.map(b=>({Path:b.relativePath,Sha256:b.sha256,Size:b.size})),Routes:e.routes||[],ChangeSummary:e.changeSummary||"MCP \u4E8C\u8FDB\u5236\u6D41\u5F0F\u53D1\u5E03",DeliveryBatchId:o,SourceManifestHash:e.sourceManifestHash||"",RuntimeManifestHash:n.manifestHash,RequestId:c,...i?{PublishMode:r,...ZK(i)}:{},...e.expectedCurrentVersion!==void 0?{ExpectedCurrentVersion:e.expectedCurrentVersion}:{},...e.expectedAppVersion!==void 0?{ExpectedAppVersion:e.expectedAppVersion}:{}})}catch(b){return{content:[{type:"text",text:JSON.stringify({error:b instanceof Error?b.message:String(b),requestId:c,uploadedCount:p,stablePromoted:!1,publishMode:r,retrySafe:!0},null,2)}],isError:!0}}if(h.Code!==1){let b=h.Data&&typeof h.Data=="object"?h.Data:null,v=b?.RetrySafe===!0||b?.retrySafe===!0;return{content:[{type:"text",text:JSON.stringify({error:h.Msg,requestId:c,uploadedCount:p,stablePromoted:!1,publishMode:r,retrySafe:v},null,2)}],isError:!0}}let m;try{m=i?WK(h,{...i,appIdOrKey:e.appIdOrKey,versionNo:e.versionNo,publishMode:r,entryPath:n.entryPath,encodedEntryPath:a.get(n.entryPath)||tx(n.entryPath,"v3 EntryPath")}):QK(h,{requestId:c,versionNo:e.versionNo,entryPath:n.entryPath,deliveryBatchId:o,runtimeManifestHash:n.manifestHash,assetCount:n.assets.length,totalSize:n.totalSize,expectedCurrentVersion:e.expectedCurrentVersion,expectedAppVersion:e.expectedAppVersion??void 0})}catch(b){return{content:[{type:"text",text:JSON.stringify({error:b instanceof Error?b.message:String(b),requestId:c,uploadedCount:p,publishMode:r,retrySafe:!1,evidenceMismatch:!0},null,2)}],isError:!0}}if(i){let b={...m,deliveryBatchId:i.deliveryBatchId,sourceManifestHash:i.sourceManifestHash,runtimeManifestHash:i.runtimeManifestHash,assetRequestManifestHash:u,assetCount:n.assets.length,stagedCount:r==="stage"?n.assets.length:0,uploadedCount:r==="stage"?n.assets.length:0,idempotentCount:d,totalSize:n.totalSize,transport:r==="stage"?"v3-multipart-immutable-release-stage":"v3-immutable-pointer-finalize",jintFileBytes:0,publishMode:r,requestId:i.requestId,requestFingerprint:i.requestFingerprint};return{content:[{type:"text",text:JSON.stringify(b,null,2)}]}}let y=String(m.AppKey||e.appIdOrKey),g=await t.probeMicroAppEntry(y);for(let b of[250,750,1500]){if(g.ok)break;await new Promise(v=>setTimeout(v,b)),g=await t.probeMicroAppEntry(y)}let x={...m,deliveryBatchId:o,sourceManifestHash:e.sourceManifestHash||"",runtimeManifestHash:n.manifestHash,assetRequestManifestHash:u,assetCount:n.assets.length,stagedCount:r==="stage-and-finalize"?n.assets.length:0,uploadedCount:r==="stage-and-finalize"?n.assets.length:0,idempotentCount:d,totalSize:n.totalSize,transport:r==="finalize"?"manifest-finalize-only":"multipart-stream-to-hdfs",jintFileBytes:0,publishMode:r,requestId:c,RuntimeProbe:g,PublishedButUnavailable:!g.ok,StablePromoted:!0};return{content:[{type:"text",text:JSON.stringify(x,null,2)}],...g.ok?{}:{isError:!0}}}catch(n){return{content:[{type:"text",text:`Error: ${n instanceof Error?n.message:String(n)}`}],isError:!0}}}function Tc(t,e=!1){let r=(t||[]).map(n=>String(n||"").trim()).filter(Boolean).map(n=>e?n.toLowerCase():n);return Array.from(new Set(r)).sort((n,i)=>n.localeCompare(i))}function eW(t,e){let r=encodeURIComponent(String(t||"").trim()),n=String(e||"").trim()||"/",i=`/?OsClient=${r}#/access-login?access_key=<AccessKey>&redirect=${encodeURIComponent(n)}`;return{relative:i,absolute:`https://<Microi\u524D\u7AEF\u57DF\u540D>${i}`}}function tW(t){let e={name:String(t.name||"").trim(),allowedRoutes:Tc(t.allowedRoutes),allowedTableNames:Tc(t.allowedTableNames),scopes:Tc(t.scopes||["page:open","form:read"],!0),redirectPath:String(t.redirectPath||"").trim(),allowedApiEngineKeys:Tc(t.allowedApiEngineKeys),allowedDataSourceKeys:Tc(t.allowedDataSourceKeys),expiresAt:String(t.expiresAt||"").trim(),remark:String(t.remark||"").trim()},r=Vt.default.createHash("sha256").update(JSON.stringify(e),"utf8").digest("hex");return{normalized:e,sha256:r}}function Hr(t,e){return e?String(t||"").toLowerCase().includes(e.toLowerCase()):!0}function Gv(t){return t.normalize("NFKD").replace(/[^\x00-\x7F]/g,"").replace(/[^a-zA-Z0-9_-]+/g,"_").replace(/_+/g,"_").replace(/^_+|_+$/g,"").toLowerCase().substring(0,48)}function rW(t){let e="";try{e=Gv(new URL(t.apiBaseUrl).host)}catch{e=Gv(t.apiBaseUrl||"")}return`Microi-${Gv(t.osClient||"")||e||"default"}`}var nW=["microi_codex","microi_get_status","microi_transition_application_stream_gate","microi_redis_statistics","microi_redis_list_keys","microi_redis_get_key","microi_redis_delete_keys","microi_redis_replace_value","microi_redis_rename_key","microi_redis_set_ttl","microi_get_db_schema","microi_get_table_indexes","microi_create_table_index","microi_drop_table_index","microi_list_database_types","microi_inspect_external_database","microi_query_external_database","microi_execute_external_database","microi_save_database_connection","microi_import_external_attachment","microi_get_field_list","microi_add_field","microi_add_layout_field","microi_bulk_apply_form_layout","microi_delete_field","microi_update_field","microi_refresh_schema_cache","microi_create_table","microi_create_module","microi_scaffold_vue_microservice","microi_get_event_code","microi_save_event_code","microi_list_events","microi_get_table_data","microi_add_form_data","microi_update_form_data","microi_get_manifest_schema","microi_plan_system","microi_generate_system","microi_validate_system","microi_build_field_config","microi_validate_menu_buttons","microi_list_engines","microi_get_engine_code","microi_save_engine_code","microi_create_engine","microi_get_module","microi_update_module","microi_bulk_apply_module_presentation","microi_list_modules","microi_update_table","microi_bulk_update_table_features","microi_set_role_permission","microi_set_engine_anonymous"],DA=new Map(nW.map((t,e)=>[t,e])),dr=f.record(f.unknown());function JA(t){return!!t&&typeof t=="object"&&typeof t.safeParse=="function"}function Xv(t){return t.args.find((e,r)=>r>0&&typeof e=="string")||""}function zA(t){for(let e=1;e<t.args.length-1;e+=1){let r=t.args[e];if(!r||typeof r!="object"||Array.isArray(r))continue;let n=Object.values(r);if(n.length===0||n.every(JA))return r}}function iW(t){let e=t,r=[];for(;e?._def?.innerType&&JA(e._def.innerType);)r.push(String(e._def.typeName||e.constructor.name)),e=e._def.innerType;let i=String(e?._def?.typeName||e?.constructor?.name||"unknown").replace(/^Zod/,"").toLowerCase();return r.some(a=>/Array/i.test(a))?`${i}[]`:i}function aW(t){let e=String(t||"").trim();if(!e)return{};let r=[e];try{r.push(decodeURIComponent(e))}catch{}for(let n of r)try{let i=JSON.parse(n);if(i&&typeof i=="object"&&!Array.isArray(i))return i}catch{}throw new Error("params must be a URI-encoded JSON object")}function jA(t){return JSON.stringify({isError:t.isError===!0,content:t.content,structuredContent:t.structuredContent},null,2)}function oW(t){let e=t,r=e.tool.bind(t),n=[];e.tool=(...a)=>{let o=typeof a[0]=="string"?a[0]:"";n.push({name:o,args:a,index:n.length})};let i=a=>{let o=a.startsWith("microi_")?a:`microi_${a}`;return n.find(s=>s.name===o)};return{flush:a=>{let o=a?new Set(a):void 0;e.tool=r,n.filter(s=>!o||o.has(s.name)).sort((s,c)=>{let l=DA.get(s.name)??Number.MAX_SAFE_INTEGER,u=DA.get(c.name)??Number.MAX_SAFE_INTEGER;return l-u||s.index-c.index}).forEach(s=>{r(...s.args)})},invoke:async(a,o={})=>{let s=i(a);if(!s||s.name==="microi_codex")return{content:[{type:"text",text:`Unknown Microi action: ${a}. Call action="list_tools" to discover available tools.`}],isError:!0};let c=s.args[s.args.length-1];if(typeof c!="function")return{content:[{type:"text",text:`Microi action has no callable handler: ${s.name}`}],isError:!0};let l=zA(s),u=o;if(l){let p=f.object(l).safeParse(o);if(!p.success)return{content:[{type:"text",text:JSON.stringify({action:s.name,error:"Invalid tool parameters",issues:p.error.issues},null,2)}],isError:!0};u=p.data}return c(u,{})},list:a=>n.filter(o=>o.name!=="microi_codex").filter(o=>!a||Hr(o.name,a)||Hr(Xv(o),a)).map(o=>({name:o.name,description:Xv(o)})),describe:a=>{let o=i(a);if(!o||o.name==="microi_codex")return;let s=zA(o)||{};return{name:o.name,description:Xv(o),params:Object.fromEntries(Object.entries(s).map(([c,l])=>[c,{type:iW(l),required:!l.isOptional(),description:l.description||""}]))}}}}function sW(t){if(!t.length)return"No tables found.";let e=[`# Database Schema (${t.length} tables)
|
|
238
|
+
`)).digest("hex");return{rootDirectory:a,entryPath:o,assets:m,totalSize:h,manifestHash:y,skippedSourceMaps:p,skippedInternalEvidenceFiles:d}}var Nae=5*1024*1024;function XK(t){if(!t||Number(t.Code)===1)return!1;let e=String(t.Msg||"");return/Newtonsoft\.Json\.Linq\.JValue/iu.test(e)&&/does not contain a definition for ['‘’"]?Val|\.Val(?:<|\b)/iu.test(e)}function rd(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function me(t,e,r,n){if(String(t[e]??"")!==r)throw new Error(`${n} \u8FD4\u56DE\u8BC1\u636E ${e} \u4E0D\u4E00\u81F4`)}function ea(t,e,r,n){if(!Number.isFinite(Number(t[e]))||Number(t[e])!==r)throw new Error(`${n} \u8FD4\u56DE\u8BC1\u636E ${e} \u4E0D\u4E00\u81F4`)}function Cc(t,e,r,{positive:n=!1}={}){let i=t[e];if(typeof i!="string"||!ex.test(i)||n&&BigInt(i)<1n)throw new Error(`${r}.${e} \u5FC5\u987B\u662F${n?"\u6B63":"\u975E\u8D1F"}\u89C4\u8303\u5341\u8FDB\u5236 bigint \u5B57\u7B26\u4E32`);return i}function ZA(t,e){let r=rd(t.Data),n=`\u5E94\u7528\u8D44\u4EA7 ${e.relativePath}`;if(me(r,"RequestId",e.requestId,n),me(r,"VersionNo",Bt(e.versionNo),n),me(r,"Path",e.relativePath,n),me(r,"Sha256",e.sha256,n),ea(r,"Size",e.size,n),r.StablePromoted!==!1)throw new Error(`${n} \u8FD4\u56DE\u8BC1\u636E StablePromoted \u5FC5\u987B\u4E3A false`);return r}function QK(t,e){let r=rd(t.Data),n="\u5E94\u7528\u6E05\u5355\u786E\u8BA4";if(me(r,"RequestId",e.requestId,n),me(r,"VersionNo",Bt(e.versionNo),n),me(r,"EntryPath",e.entryPath,n),me(r,"DeliveryBatchId",e.deliveryBatchId,n),me(r,"RuntimeManifestHash",e.runtimeManifestHash,n),ea(r,"AssetCount",e.assetCount,n),ea(r,"TotalSize",e.totalSize,n),e.expectedCurrentVersion!==void 0&&ea(r,"ExpectedCurrentVersion",e.expectedCurrentVersion,n),e.expectedAppVersion!==void 0&&me(r,"ExpectedAppVersion",e.expectedAppVersion,n),r.StablePromoted!==!0)throw new Error(`${n} \u8FD4\u56DE\u8BC1\u636E StablePromoted \u5FC5\u987B\u4E3A true`);if(String(r.PublishStatus||"")!=="Published")throw new Error(`${n} \u8FD4\u56DE\u8BC1\u636E PublishStatus \u5FC5\u987B\u4E3A Published`);if(String(r.VerificationStatus||"")!=="Verified")throw new Error(`${n} \u8FD4\u56DE\u8BC1\u636E VerificationStatus \u5FC5\u987B\u4E3A Verified`);return r}async function YK(t,e){let r=e.publishMode||"stage-and-finalize";try{if(e.confirmExecution&&e.confirmExecution!==e.appIdOrKey)return{content:[{type:"text",text:`Error: confirmExecution \u5FC5\u987B\u7CBE\u786E\u7B49\u4E8E ${e.appIdOrKey}`}],isError:!0};if(e.confirmExecution===e.appIdOrKey&&r!=="stage"&&(e.expectedCurrentVersion===void 0||e.expectedAppVersion===void 0))return{content:[{type:"text",text:JSON.stringify({error:"finalize \u5FC5\u987B\u540C\u65F6\u4F20\u5165 expectedCurrentVersion \u4E0E expectedAppVersion\uFF1B\u8BF7\u5148\u56DE\u8BFB\u5E94\u7528\u4E0A\u4E0B\u6587\u5E76\u51BB\u7ED3\u53D1\u5E03\u57FA\u7EBF\u3002",publishMode:r,stablePromoted:!1,retrySafe:!0,expectedStateRequired:!0},null,2)}],isError:!0};let n=await GK(e.directory,e.entryPath||"index.html",{includeSourceMaps:e.includeSourceMaps,maxFiles:e.maxFiles,maxTotalBytes:e.maxTotalMegabytes?Math.floor(e.maxTotalMegabytes*1024*1024):void 0}),i=UK(e,n.manifestHash),a=i?HK(n,e,i):null,o=i?.deliveryBatchId||e.deliveryBatchId||`mcp-${ta(["microi-application-delivery-v1",e.appIdOrKey,Bt(e.versionNo),n.manifestHash]).slice(0,40)}`,s=i?.requestId||MK({deliveryBatchId:o,appIdOrKey:e.appIdOrKey,versionNo:e.versionNo,runtimeManifestHash:n.manifestHash}),c=i?.requestId||NK({deliveryBatchId:o,appIdOrKey:e.appIdOrKey,versionNo:e.versionNo,runtimeManifestHash:n.manifestHash,expectedCurrentVersion:e.expectedCurrentVersion,expectedAppVersion:e.expectedAppVersion}),l=n.assets.map(b=>({Path:b.relativePath,RequestId:i?.requestId||BA({deliveryBatchId:o,appIdOrKey:e.appIdOrKey,versionNo:e.versionNo,relativePath:b.relativePath,sha256:b.sha256})})),u=ta(l.flatMap(b=>[b.Path,b.RequestId]));if(e.confirmExecution!==e.appIdOrKey)return{content:[{type:"text",text:JSON.stringify({dryRun:!0,publishMode:r,confirmationRequired:e.appIdOrKey,rootDirectory:n.rootDirectory,entryPath:n.entryPath,assetCount:n.assets.length,totalSize:n.totalSize,runtimeManifestHash:n.manifestHash,deliveryBatchId:o,...e.expectedCurrentVersion!==void 0?{expectedCurrentVersion:e.expectedCurrentVersion}:{},...e.expectedAppVersion!==void 0?{expectedAppVersion:e.expectedAppVersion}:{},finalizePreconditionsRequired:r!=="stage",requestId:r==="stage"?s:c,...i?{protocolVersion:3,expectedGateEpoch:i.expectedGateEpoch,requestFingerprint:i.requestFingerprint,routeSnapshotJson:i.routeSnapshotJson,routeSnapshotHash:i.routeSnapshotHash,expectedPublishFence:i.expectedPublishFence,expectedPublishRowVersion:i.expectedPublishRowVersion,expectedVersionRowVersion:i.expectedVersionRowVersion,expectedActivePublishVersionId:i.expectedActivePublishVersionId,expectedCommittedPublishVersionId:i.expectedCommittedPublishVersionId}:{},assetRequestManifestHash:u,skippedSourceMaps:n.skippedSourceMaps,skippedInternalEvidenceFiles:n.skippedInternalEvidenceFiles,assetsPreview:n.assets.slice(0,200).map((b,v)=>({Path:b.relativePath,Size:b.size,Sha256:b.sha256,RequestId:l[v].RequestId})),previewTruncated:n.assets.length>200},null,2)}]};let p=0,d=0;if(r!=="finalize"){let b=new Map(l.map(w=>[w.Path,w.RequestId])),v=[...n.assets].sort((w,E)=>Number(w.isEntry)-Number(E.isEntry));for(let w of v){let E=b.get(w.relativePath),T;try{T=await t.uploadApplicationAssetStream({AppIdOrKey:e.appIdOrKey,VersionNo:e.versionNo,RelativePath:w.relativePath,ExpectedSha256:w.sha256,RequestId:E,FilePath:w.absolutePath,TimeoutMs:e.timeoutMsPerFile,...i?{ProtocolVersion:3,ExpectedGateEpoch:i.expectedGateEpoch,RequestFingerprint:i.requestFingerprint,DeliveryBatchId:i.deliveryBatchId,SourceManifestHash:i.sourceManifestHash,RuntimeManifestHash:i.runtimeManifestHash,RouteSnapshotJson:i.routeSnapshotJson,RouteSnapshotHash:i.routeSnapshotHash,ExpectedCurrentVersion:i.expectedCurrentVersion,ExpectedAppVersion:i.expectedAppVersion,ExpectedPublishFence:i.expectedPublishFence,ExpectedPublishRowVersion:i.expectedPublishRowVersion,ExpectedVersionRowVersion:i.expectedVersionRowVersion,ExpectedActivePublishVersionId:i.expectedActivePublishVersionId,ExpectedCommittedPublishVersionId:i.expectedCommittedPublishVersionId}:{}})}catch(A){return{content:[{type:"text",text:JSON.stringify({error:A instanceof Error?A.message:String(A),failedPath:w.relativePath,requestId:E,uploadedCount:p,totalCount:n.assets.length,publishMode:r,retrySafe:!0},null,2)}],isError:!0}}if(T.Code!==1){let A=XK(T);return{content:[{type:"text",text:JSON.stringify({error:T.Msg,failedPath:w.relativePath,requestId:E,uploadedCount:p,totalCount:n.assets.length,publishMode:r,retrySafe:!0,requiresRequestIdCapableApi:A,compatibilityFallbackAttempted:!1,compatibilityFallbackDisabled:e.allowLegacyFallback===!0},null,2)}],isError:!0}}let k;try{k=i?KK(T,{...i,versionNo:e.versionNo,relativePath:w.relativePath,encodedRelativePath:a.get(w.relativePath),sha256:w.sha256,size:w.size}):ZA(T,{requestId:E,versionNo:e.versionNo,relativePath:w.relativePath,sha256:w.sha256,size:w.size})}catch(A){return{content:[{type:"text",text:JSON.stringify({error:A instanceof Error?A.message:String(A),failedPath:w.relativePath,requestId:E,uploadedCount:p,totalCount:n.assets.length,publishMode:r,retrySafe:!0,evidenceMismatch:!0},null,2)}],isError:!0}}p+=1,k.Idempotent===!0&&(d+=1),(p===1||p%25===0||p===n.assets.length)&&console.error(`[microi-mcp] Stream stage ${e.appIdOrKey} ${e.versionNo}: ${p}/${n.assets.length}`)}}if(r==="stage"&&!i){let b={appIdOrKey:e.appIdOrKey,versionNo:Bt(e.versionNo),deliveryBatchId:o,runtimeManifestHash:n.manifestHash,assetRequestManifestHash:u,assetCount:n.assets.length,stagedCount:n.assets.length,uploadedCount:n.assets.length,idempotentCount:d,totalSize:n.totalSize,transport:"multipart-stream-to-hdfs-stage-only",jintFileBytes:0,publishMode:r,requestId:s,StablePromoted:!1};return{content:[{type:"text",text:JSON.stringify(b,null,2)}]}}let h;try{h=await t.finalizeApplicationStreamPublish({AppIdOrKey:e.appIdOrKey,VersionNo:e.versionNo,EntryPath:n.entryPath,Assets:n.assets.map(b=>({Path:b.relativePath,Sha256:b.sha256,Size:b.size})),Routes:e.routes||[],ChangeSummary:e.changeSummary||"MCP \u4E8C\u8FDB\u5236\u6D41\u5F0F\u53D1\u5E03",DeliveryBatchId:o,SourceManifestHash:e.sourceManifestHash||"",RuntimeManifestHash:n.manifestHash,RequestId:c,...i?{PublishMode:r,...ZK(i)}:{},...e.expectedCurrentVersion!==void 0?{ExpectedCurrentVersion:e.expectedCurrentVersion}:{},...e.expectedAppVersion!==void 0?{ExpectedAppVersion:e.expectedAppVersion}:{}})}catch(b){return{content:[{type:"text",text:JSON.stringify({error:b instanceof Error?b.message:String(b),requestId:c,uploadedCount:p,stablePromoted:!1,publishMode:r,retrySafe:!0},null,2)}],isError:!0}}if(h.Code!==1){let b=h.Data&&typeof h.Data=="object"?h.Data:null,v=b?.RetrySafe===!0||b?.retrySafe===!0;return{content:[{type:"text",text:JSON.stringify({error:h.Msg,requestId:c,uploadedCount:p,stablePromoted:!1,publishMode:r,retrySafe:v},null,2)}],isError:!0}}let m;try{m=i?WK(h,{...i,appIdOrKey:e.appIdOrKey,versionNo:e.versionNo,publishMode:r,entryPath:n.entryPath,encodedEntryPath:a.get(n.entryPath)||tx(n.entryPath,"v3 EntryPath")}):QK(h,{requestId:c,versionNo:e.versionNo,entryPath:n.entryPath,deliveryBatchId:o,runtimeManifestHash:n.manifestHash,assetCount:n.assets.length,totalSize:n.totalSize,expectedCurrentVersion:e.expectedCurrentVersion,expectedAppVersion:e.expectedAppVersion??void 0})}catch(b){return{content:[{type:"text",text:JSON.stringify({error:b instanceof Error?b.message:String(b),requestId:c,uploadedCount:p,publishMode:r,retrySafe:!1,evidenceMismatch:!0},null,2)}],isError:!0}}if(i){let b={...m,deliveryBatchId:i.deliveryBatchId,sourceManifestHash:i.sourceManifestHash,runtimeManifestHash:i.runtimeManifestHash,assetRequestManifestHash:u,assetCount:n.assets.length,stagedCount:r==="stage"?n.assets.length:0,uploadedCount:r==="stage"?n.assets.length:0,idempotentCount:d,totalSize:n.totalSize,transport:r==="stage"?"v3-multipart-immutable-release-stage":"v3-immutable-pointer-finalize",jintFileBytes:0,publishMode:r,requestId:i.requestId,requestFingerprint:i.requestFingerprint};return{content:[{type:"text",text:JSON.stringify(b,null,2)}]}}let y=String(m.AppKey||e.appIdOrKey),g=await t.probeMicroAppEntry(y);for(let b of[250,750,1500]){if(g.ok)break;await new Promise(v=>setTimeout(v,b)),g=await t.probeMicroAppEntry(y)}let x={...m,deliveryBatchId:o,sourceManifestHash:e.sourceManifestHash||"",runtimeManifestHash:n.manifestHash,assetRequestManifestHash:u,assetCount:n.assets.length,stagedCount:r==="stage-and-finalize"?n.assets.length:0,uploadedCount:r==="stage-and-finalize"?n.assets.length:0,idempotentCount:d,totalSize:n.totalSize,transport:r==="finalize"?"manifest-finalize-only":"multipart-stream-to-hdfs",jintFileBytes:0,publishMode:r,requestId:c,RuntimeProbe:g,PublishedButUnavailable:!g.ok,StablePromoted:!0};return{content:[{type:"text",text:JSON.stringify(x,null,2)}],...g.ok?{}:{isError:!0}}}catch(n){return{content:[{type:"text",text:`Error: ${n instanceof Error?n.message:String(n)}`}],isError:!0}}}function Tc(t,e=!1){let r=(t||[]).map(n=>String(n||"").trim()).filter(Boolean).map(n=>e?n.toLowerCase():n);return Array.from(new Set(r)).sort((n,i)=>n.localeCompare(i))}function eW(t,e){let r=encodeURIComponent(String(t||"").trim()),n=String(e||"").trim()||"/",i=`/?OsClient=${r}#/access-login?access_key=<AccessKey>&redirect=${encodeURIComponent(n)}`;return{relative:i,absolute:`https://<Microi\u524D\u7AEF\u57DF\u540D>${i}`}}function tW(t){let e={name:String(t.name||"").trim(),allowedRoutes:Tc(t.allowedRoutes),allowedTableNames:Tc(t.allowedTableNames),scopes:Tc(t.scopes||["page:open","form:read"],!0),redirectPath:String(t.redirectPath||"").trim(),allowedApiEngineKeys:Tc(t.allowedApiEngineKeys),allowedDataSourceKeys:Tc(t.allowedDataSourceKeys),expiresAt:String(t.expiresAt||"").trim(),remark:String(t.remark||"").trim()},r=Vt.default.createHash("sha256").update(JSON.stringify(e),"utf8").digest("hex");return{normalized:e,sha256:r}}function Hr(t,e){return e?String(t||"").toLowerCase().includes(e.toLowerCase()):!0}function Gv(t){return t.normalize("NFKD").replace(/[^\x00-\x7F]/g,"").replace(/[^a-zA-Z0-9_-]+/g,"_").replace(/_+/g,"_").replace(/^_+|_+$/g,"").toLowerCase().substring(0,48)}function rW(t){let e="";try{e=Gv(new URL(t.apiBaseUrl).host)}catch{e=Gv(t.apiBaseUrl||"")}return`Microi-${Gv(t.osClient||"")||e||"default"}`}var nW=["microi_codex","microi_get_status","microi_transition_application_stream_gate","microi_redis_statistics","microi_redis_list_keys","microi_redis_get_key","microi_redis_delete_keys","microi_redis_replace_value","microi_redis_rename_key","microi_redis_set_ttl","microi_get_db_schema","microi_get_table_indexes","microi_create_table_index","microi_drop_table_index","microi_list_database_types","microi_inspect_external_database","microi_query_external_database","microi_execute_external_database","microi_save_database_connection","microi_import_external_attachment","microi_get_field_list","microi_add_field","microi_add_layout_field","microi_bulk_apply_form_layout","microi_delete_field","microi_update_field","microi_refresh_schema_cache","microi_create_table","microi_repair_audit_fields","microi_create_module","microi_scaffold_vue_microservice","microi_get_event_code","microi_save_event_code","microi_list_events","microi_get_table_data","microi_add_form_data","microi_update_form_data","microi_get_manifest_schema","microi_plan_system","microi_generate_system","microi_validate_system","microi_build_field_config","microi_validate_menu_buttons","microi_list_engines","microi_get_engine_code","microi_save_engine_code","microi_create_engine","microi_get_module","microi_update_module","microi_bulk_apply_module_presentation","microi_list_modules","microi_update_table","microi_bulk_update_table_features","microi_set_role_permission","microi_set_engine_anonymous"],DA=new Map(nW.map((t,e)=>[t,e])),dr=f.record(f.unknown());function JA(t){return!!t&&typeof t=="object"&&typeof t.safeParse=="function"}function Xv(t){return t.args.find((e,r)=>r>0&&typeof e=="string")||""}function zA(t){for(let e=1;e<t.args.length-1;e+=1){let r=t.args[e];if(!r||typeof r!="object"||Array.isArray(r))continue;let n=Object.values(r);if(n.length===0||n.every(JA))return r}}function iW(t){let e=t,r=[];for(;e?._def?.innerType&&JA(e._def.innerType);)r.push(String(e._def.typeName||e.constructor.name)),e=e._def.innerType;let i=String(e?._def?.typeName||e?.constructor?.name||"unknown").replace(/^Zod/,"").toLowerCase();return r.some(a=>/Array/i.test(a))?`${i}[]`:i}function aW(t){let e=String(t||"").trim();if(!e)return{};let r=[e];try{r.push(decodeURIComponent(e))}catch{}for(let n of r)try{let i=JSON.parse(n);if(i&&typeof i=="object"&&!Array.isArray(i))return i}catch{}throw new Error("params must be a URI-encoded JSON object")}function jA(t){return JSON.stringify({isError:t.isError===!0,content:t.content,structuredContent:t.structuredContent},null,2)}function oW(t){let e=t,r=e.tool.bind(t),n=[];e.tool=(...a)=>{let o=typeof a[0]=="string"?a[0]:"";n.push({name:o,args:a,index:n.length})};let i=a=>{let o=a.startsWith("microi_")?a:`microi_${a}`;return n.find(s=>s.name===o)};return{flush:a=>{let o=a?new Set(a):void 0;e.tool=r,n.filter(s=>!o||o.has(s.name)).sort((s,c)=>{let l=DA.get(s.name)??Number.MAX_SAFE_INTEGER,u=DA.get(c.name)??Number.MAX_SAFE_INTEGER;return l-u||s.index-c.index}).forEach(s=>{r(...s.args)})},invoke:async(a,o={})=>{let s=i(a);if(!s||s.name==="microi_codex")return{content:[{type:"text",text:`Unknown Microi action: ${a}. Call action="list_tools" to discover available tools.`}],isError:!0};let c=s.args[s.args.length-1];if(typeof c!="function")return{content:[{type:"text",text:`Microi action has no callable handler: ${s.name}`}],isError:!0};let l=zA(s),u=o;if(l){let p=f.object(l).safeParse(o);if(!p.success)return{content:[{type:"text",text:JSON.stringify({action:s.name,error:"Invalid tool parameters",issues:p.error.issues},null,2)}],isError:!0};u=p.data}return c(u,{})},list:a=>n.filter(o=>o.name!=="microi_codex").filter(o=>!a||Hr(o.name,a)||Hr(Xv(o),a)).map(o=>({name:o.name,description:Xv(o)})),describe:a=>{let o=i(a);if(!o||o.name==="microi_codex")return;let s=zA(o)||{};return{name:o.name,description:Xv(o),params:Object.fromEntries(Object.entries(s).map(([c,l])=>[c,{type:iW(l),required:!l.isOptional(),description:l.description||""}]))}}}}function sW(t){if(!t.length)return"No tables found.";let e=[`# Database Schema (${t.length} tables)
|
|
239
239
|
`];for(let r of t){let n=r._Fields||r.Fields||[];if(e.push(`## ${r.Name}${r.Description?` \u2014 ${r.Description}`:""}`),!n.length){e.push(`_No field information available._
|
|
240
240
|
`);continue}e.push("| Field | Label | Type | Nullable | Description |"),e.push("|-------|-------|------|----------|-------------|");for(let i of n){let a=i.AllowNull===!1?"NO":"YES";e.push(`| ${i.Name} | ${i.Label||""} | ${i.Type||""} | ${a} | ${i.Description||""} |`)}e.push("")}return e.join(`
|
|
241
241
|
`)}function Qv(t){let e=(t.Url||"").trim();return e?/^https?:\/\//i.test(e)||e.startsWith("/")?e:`/${e}`:""}function Yv(t){return Number(t.AllowAnonymous)===1&&Number(t.StopHttp)!==1&&Number(t.IsEnable)!==0}function cW(t){return Number(t.StopHttp)!==1&&Number(t.IsEnable)!==0}function lW(t,e){let r=Array.isArray(t.Engines)?t.Engines:[],n=Array.isArray(t.Modules)?t.Modules:[],i=r.filter(Yv),a=r.filter(l=>cW(l)&&!Yv(l)),o=n.filter(l=>Qv(l)),s=t.ApiBaseUrl||e,c=[`# Playwright Context for ${t.OsClient||"current tenant"}`,"","## Recommended Environment","```bash",`PW_API_BASE=${s}`,`PW_OS_CLIENT=${t.OsClient||""}`,"PW_BASE_URL=http://127.0.0.1:5180","PW_HOME_PATH=/","```","","## Summary",`- Engines: ${r.length}`,`- Public callable engines: ${i.length}`,`- Protected callable engines: ${a.length}`,`- Menu routes: ${o.length}`];return t.Warnings?.length&&c.push("","## Warnings",...t.Warnings.map(l=>`- ${l}`)),c.push("","## Public API Engines"),i.length?(c.push("| Engine Key | Name | Category | Address |","|---|---|---|---|"),i.slice(0,80).forEach(l=>{c.push(`| ${l.ApiEngineKey||""} | ${l.ApiName||""} | ${l.Category||""} | ${l.ApiAddress||`/apiengine/${l.ApiEngineKey}`} |`)})):c.push("_No public callable engines found._"),c.push("","## Protected API Engines"),a.length?(c.push("| Engine Key | Name | Category | Address |","|---|---|---|---|"),a.slice(0,80).forEach(l=>{c.push(`| ${l.ApiEngineKey||""} | ${l.ApiName||""} | ${l.Category||""} | ${l.ApiAddress||`/apiengine/${l.ApiEngineKey}`} |`)})):c.push("_No protected callable engines found._"),c.push("","## Menu Routes"),o.length?(c.push("| Route | Name | Table | Component | PC | Mobile |","|---|---|---|---|---|---|"),o.slice(0,120).forEach(l=>{c.push(`| ${Qv(l)} | ${l.Name||""} | ${l.DiyTableName||l.DiyTableId||""} | ${l.ComponentName||l.ComponentPath||""} | ${l.Display===1?"yes":"no"} | ${l.AppDisplay===1?"yes":"no"} |`)})):c.push("_No menu routes found._"),c.join(`
|
|
@@ -255,7 +255,7 @@ BOUNDARY RULES:
|
|
|
255
255
|
|
|
256
256
|
## \u4F4E\u4EE3\u7801\u7CFB\u7EDF\u8BBE\u8BA1\u5DE5\u4F5C\u6D41\uFF08\u6309\u987A\u5E8F\u6267\u884C\uFF09
|
|
257
257
|
1. **microi_get_db_schema** \u2014 \u5148\u67E5\u770B\u5DF2\u6709\u8868\u7ED3\u6784\uFF0C\u4E86\u89E3\u6570\u636E\u6A21\u578B
|
|
258
|
-
2. **microi_create_table** \u2014 \u521B\u5EFA\u81EA\u5B9A\u4E49\u8868\uFF08\u5199\u5165 diy_table\uFF0C\
|
|
258
|
+
2. **microi_create_table** \u2014 \u521B\u5EFA\u81EA\u5B9A\u4E49\u8868\uFF08\u5199\u5165 diy_table\uFF0C\u5E76\u540C\u6B65\u521B\u5EFA Id/CreateTime/UpdateTime/UserId/UserName/IsDeleted \u516D\u4E2A\u56FA\u5B9A\u5BA1\u8BA1\u5B57\u6BB5\u7684\u7269\u7406\u5217\u4E0E diy_field \u5143\u6570\u636E\uFF09
|
|
259
259
|
3. **microi_add_field** \u2014 \u9010\u4E2A\u6DFB\u52A0\u4E1A\u52A1\u5B57\u6BB5\uFF08\u5199\u5165 diy_field\uFF0C\u6267\u884C ALTER TABLE\uFF09\uFF0C\u9700\u6307\u5B9A component \u7EC4\u4EF6\u7C7B\u578B
|
|
260
260
|
4. **microi_get_table_indexes / microi_create_table_index** \u2014 \u6309\u771F\u5B9E\u67E5\u8BE2\u4E0E\u4E1A\u52A1\u552F\u4E00\u7EA6\u675F\u521B\u5EFA\u5E76\u56DE\u8BFB\u7269\u7406\u7D22\u5F15
|
|
261
261
|
5. **microi_create_module** \u2014 \u521B\u5EFA\u83DC\u5355\u6A21\u5757\uFF08\u5199\u5165 sys_menu\uFF09\uFF0C\u7ED1\u5B9A diyTableId \u540E\u5373\u53EF\u5728\u5BFC\u822A\u680F\u770B\u5230\u5E76\u4F7F\u7528 CRUD\u3002**\u590D\u6742\u4E1A\u52A1\u7CFB\u7EDF\u8BF7\u540C\u65F6\u4F20\u5165 moreBtns/formBtns/pageTabs/batchSelectMoreBtns** \u4E00\u6B21\u6027\u914D\u9F50\u6309\u94AE
|
|
@@ -270,7 +270,9 @@ BOUNDARY RULES:
|
|
|
270
270
|
- **microi_validate_menu_buttons** \u2014 \u6821\u9A8C\u5E76\u89C4\u8303\u5316 MoreBtns/FormBtns/PageTabs \u7B49\u6309\u94AE JSON\uFF0C\u81EA\u52A8\u8865 Id/Sort/\u9ED8\u8BA4\u663E\u9690
|
|
271
271
|
- **microi_build_field_config** \u2014 \u751F\u6210 Select/Radio/Checkbox/JoinForm/AutoNumber/DateTime \u7B49\u5B57\u6BB5\u7684 Data/Config JSON
|
|
272
272
|
- **microi_get_field_list / microi_update_field / microi_refresh_schema_cache** \u2014 \u4FEE\u6539\u5DF2\u6709 diy_field \u5B57\u6BB5\u5C5E\u6027\u3001KeyValue \u6570\u636E\u6E90\u3001Config \u540E\u5FC5\u987B\u56DE\u8BFB\u5E76\u5237\u65B0\u7F13\u5B58\uFF0C\u907F\u514D\u540E\u53F0\u5B57\u6BB5\u9009\u9879\u4E0E\u524D\u7AEF/\u63A5\u53E3\u679A\u4E3E\u4E0D\u4E00\u81F4
|
|
273
|
+
- **microi_repair_audit_fields** \u2014 \u4FEE\u590D\u6307\u5B9A\u8868\u5DF2\u5B58\u5728\u7684\u516D\u4E2A\u56FA\u5B9A\u5BA1\u8BA1\u7269\u7406\u5217\u5BF9\u5E94\u7684 diy_field \u5143\u6570\u636E\uFF1B\u4FEE\u590D\u540E\u5B83\u4EEC\u4E0D\u518D\u51FA\u73B0\u5728\u201C\u5F02\u5E38\u5B57\u6BB5\u4FEE\u590D\u201D\uFF0C\u8868\u5355\u9ED8\u8BA4\u663E\u9690\u7EE7\u7EED\u7531 diy_table.DisplayDefaultField \u63A7\u5236
|
|
273
274
|
- **microi_get_table_data / microi_add_form_data / microi_update_form_data** \u2014 \u7EF4\u62A4\u79DF\u6237\u4E1A\u52A1\u8868\u6570\u636E\uFF08\u5982\u5546\u54C1\u3001\u793A\u4F8B\u6570\u636E\u3001\u914D\u7F6E\u9879\uFF09\u65F6\u4F7F\u7528\uFF0C\u5199\u5165\u540E\u5FC5\u987B\u56DE\u8BFB\u9A8C\u8BC1\u5173\u952E\u5B57\u6BB5
|
|
275
|
+
- **sys_user.DefaultIndexUrl** \u2014 \u5F53\u524D\u7528\u6237\u767B\u5F55\u540E\u7684\u9996\u9009\u7AD9\u5185\u8DEF\u7531\uFF0C\u652F\u6301 /route\u3001#/route\u3001/#/route\uFF1B\u7559\u7A7A\u65F6\u56DE\u9000\u7CFB\u7EDF\u9ED8\u8BA4\u9996\u9875\u3002\u5BA2\u6237\u7AEF\u53EA\u91C7\u7528\u5B58\u5728\u4E14\u5F53\u524D\u7528\u6237\u6709\u6743\u9650\u7684\u5185\u90E8\u8DEF\u7531
|
|
274
276
|
- **microi_upsert_engine** \u2014 \u63A5\u53E3\u5F15\u64CE\u5B58\u5728\u5219\u66F4\u65B0\uFF0C\u4E0D\u5B58\u5728\u5219\u521B\u5EFA\uFF1B\u771F\u5B9E\u5199\u5165\u5FC5\u987B\u786E\u8BA4
|
|
275
277
|
- **microi_save_engine_code** \u2014 \u9012\u589E\u4EE3\u7801\u5934\u8BED\u4E49\u7248\u672C\u5E76\u4FDD\u5B58 ApiV8Code\uFF1B\u5982 sys_apiengine \u5B58\u5728 Version/ChangeHistory \u5B57\u6BB5\u5219\u540C\u6B65\u5199\u5165\uFF1B\u4E0D\u4FEE\u6539 AllowAnonymous/StopHttp/IsEnable/ApiAddress \u7B49\u63A5\u53E3\u914D\u7F6E
|
|
276
278
|
- **microi_check_workflow_package / microi_test_workflow_condition** \u2014 \u4FDD\u5B58\u5DE5\u4F5C\u6D41\u524D\u68C0\u67E5\u62D3\u6251\uFF0C\u5E76\u7528\u6837\u4F8B\u8868\u5355\u6570\u636E\u6D4B\u8BD5\u56FE\u5F62\u6761\u4EF6\u8DEF\u7EBF
|
|
@@ -532,7 +534,7 @@ ${JSON.stringify(y.Data,null,2)}`}]}}catch(y){return{content:[{type:"text",text:
|
|
|
532
534
|
${JSON.stringify(p.Data||{},null,2)}`}]}}catch(p){return{content:[{type:"text",text:`Error: ${p instanceof Error?p.message:String(p)}`}],isError:!0}}}),i.tool("microi_list_workflow_v8_events",`List workflow node V8 events from WF_Node for OsClient ${r}. WF_Line is returned only in the workflow package snapshot; executable route condition code is WF_Node.LineValueV8.`,{flowDesignId:f.string().optional().describe("Optional WF_FlowDesign.Id to limit results to one workflow")},async({flowDesignId:o})=>{try{let s=await t.getWorkflowV8EventList(o);return s.Code!==1?{content:[{type:"text",text:`Error: ${s.Msg}`}],isError:!0}:{content:[{type:"text",text:JSON.stringify(s.Data,null,2)}]}}catch(s){return{content:[{type:"text",text:`Error: ${s instanceof Error?s.message:String(s)}`}],isError:!0}}}),i.tool("microi_get_workflow_v8_code",`Get workflow node V8 JavaScript code from WF_Node by nodeId and event type (OsClient: ${r}).`,{nodeId:f.string().describe("WF_Node.Id"),eventType:f.string().describe("WF_Node V8 field: StartV8 | EndV8 | StartV8Server | EndV8Server | LineValueV8 | AllowAddUserV8Code"),flowDesignId:f.string().optional().describe("Optional WF_FlowDesign.Id used as a safety check")},async({nodeId:o,eventType:s,flowDesignId:c})=>{try{let l=await t.getWorkflowV8EventCode(o,s,c);if(l.Code!==1)return{content:[{type:"text",text:`Error: ${l.Msg}`}],isError:!0};let u=l.Data,p=kc(u,"V8Code","Code");return{content:[{type:"text",text:[`## Workflow V8: ${u?.FlowName||u?.FlowDesignId||c||""} / ${u?.NodeName||o} / ${s}`,u?.EventName?`- **Name**: ${u.EventName}`:"",u?.FlowDesignId?`- **FlowDesignId**: ${u.FlowDesignId}`:"",u?.NodeId?`- **NodeId**: ${u.NodeId}`:"","","```javascript",p||"// No code available","```"].filter(Boolean).join(`
|
|
533
535
|
`)}]}}catch(l){return{content:[{type:"text",text:`Error: ${l instanceof Error?l.message:String(l)}`}],isError:!0}}}),i.tool("microi_save_workflow_v8_code",`Save workflow node V8 code into WF_Node for OsClient ${r}. Empty code clears the field without adding a generated header.`,{nodeId:f.string().describe("WF_Node.Id"),eventType:f.string().describe("WF_Node V8 field: StartV8 | EndV8 | StartV8Server | EndV8Server | LineValueV8 | AllowAddUserV8Code"),code:f.string().describe("The complete JavaScript source code to save; pass empty string to clear"),flowDesignId:f.string().optional().describe("Optional WF_FlowDesign.Id used as a safety check"),functionDescription:f.string().optional().describe("Complete function description to keep in the code header. No change history here."),changeSummary:f.string().optional().describe("One-line change summary for audit/future compatible storage.")},async({nodeId:o,eventType:s,code:c,flowDesignId:l,functionDescription:u,changeSummary:p})=>{try{let d=await t.saveWorkflowV8EventCode(o,s,c,{flowDesignId:l,functionDescription:u,changeSummary:p});return d.Code!==1?{content:[{type:"text",text:`Error: ${d.Msg}`}],isError:!0}:{content:[{type:"text",text:`\u2705 Workflow node V8 "${o}/${s}" saved successfully.`}]}}catch(d){return{content:[{type:"text",text:`Error: ${d instanceof Error?d.message:String(d)}`}],isError:!0}}}),i.tool("microi_query_mongodb_logs",`Query Microi MongoDB system logs (sys_log_<osClient>/log_yyyyMM) for OsClient ${r}. Use this after automated tests to inspect V8 errors, slow logs, workflow logs and platform guard logs.`,{keyword:f.string().optional().describe("Keyword searched in log Title and Content"),type:f.string().optional().describe("Log Type, for example MCP, \u8868\u5355V8\u6162\u65E5\u5FD7, \u8868\u5355V8\u9012\u5F52\u4FDD\u62A4, \u5DE5\u4F5C\u6D41\u5408\u5E76\u63D0\u4EA4\u6162\u65E5\u5FD7"),level:f.number().optional().describe("Log level. Common values: 1 info, 2 warning, 3 error"),searchMonth:f.string().optional().describe("Month in yyyyMM. Defaults to current month on server"),pageIndex:f.number().optional().describe("Page index, default 1"),pageSize:f.number().optional().describe("Page size, default 20, backend max 200")},async({keyword:o,type:s,level:c,searchMonth:l,pageIndex:u,pageSize:p})=>{try{let d=await t.queryMongodbLogs({keyword:o,type:s,level:c,searchMonth:l,pageIndex:u,pageSize:p});return d.Code!==1?{content:[{type:"text",text:`Error: ${d.Msg}`}],isError:!0}:{content:[{type:"text",text:JSON.stringify(d.Data,null,2)}]}}catch(d){return{content:[{type:"text",text:`Error: ${d instanceof Error?d.message:String(d)}`}],isError:!0}}}),i.tool("microi_write_mongodb_log",`Write a Microi MongoDB system log for OsClient ${r}. Useful for AI automated test milestones, reproduction markers, and repair verification notes.`,{title:f.string().describe("Log title"),content:f.string().describe("Log content"),type:f.string().optional().describe("Log Type, default MCP"),level:f.number().optional().describe("Log level, default 1"),api:f.string().optional().describe("Related API/tool name"),param:f.string().optional().describe("Input or context summary. Avoid secrets."),remark:f.string().optional().describe("Short remark or target identifier"),otherInfo:f.string().optional().describe("Additional diagnostic info. Avoid secrets."),timer:f.number().optional().describe("Elapsed milliseconds, if applicable"),result:f.string().optional().describe("Result summary"),appId:f.string().optional().describe("AppId, default microi.mcp")},async({title:o,content:s,type:c,level:l,api:u,param:p,remark:d,otherInfo:h,timer:m,result:y,appId:g})=>{try{let x=await t.writeMongodbLog({title:o,content:s,type:c,level:l,api:u,param:p,remark:d,otherInfo:h,timer:m,result:y,appId:g});return x.Code!==1?{content:[{type:"text",text:`Error: ${x.Msg}`}],isError:!0}:{content:[{type:"text",text:JSON.stringify(x.Data||{ok:!0},null,2)}]}}catch(x){return{content:[{type:"text",text:`Error: ${x instanceof Error?x.message:String(x)}`}],isError:!0}}}),i.tool("microi_create_table",`Create or reconcile a custom table for OsClient "${r}". Inserts a record into diy_table. IDEMPOTENT \u2014 calling again with the same name reuses the existing TableId; an explicitly supplied v8Unlimited value is reconciled and read back by system validation. This is step 2 of system design.`,{name:f.string().describe('Table name in English (e.g. "Crm_Customer", "Order_Main"). Convention: Module_Entity format. Will be a real MySQL table.'),description:f.string().optional().describe('Chinese description of the table (e.g. "\u5BA2\u6237\u4FE1\u606F", "\u8BA2\u5355\u4E3B\u8868")'),tabs:f.string().optional().describe(`Form tab layout JSON (e.g. '[{"Id":"basic","Name":"\u57FA\u672C\u4FE1\u606F","Sort":10},{"Id":"business","Name":"\u4E1A\u52A1\u4FE1\u606F","Sort":20}]'). Groups fields into diy_table.Tabs. When using microi_generate_system, many-field tables can be auto-tabbed.`),isTree:f.number().optional().describe("Enable tree structure (1=tree table with ParentId self-referencing, 0=flat). Default: 0"),column:f.number().optional().describe("Number of form columns (1, 2, or 3). Controls form layout. Default: 2 (\u53CC\u5217\uFF0C\u66F4\u7D27\u51D1\u73B0\u4EE3)"),formOpenType:f.string().optional().describe('How to open form: "Dialog" (\u5F39\u7A97), "Drawer" (\u62BD\u5C49), "Page" (\u65B0\u9875\u9762). Default: Dialog'),formOpenWidth:f.string().optional().describe('Form dialog/drawer width (e.g. "800px", "60%"). Default: auto'),v8Unlimited:f.boolean().optional().describe("Default false for new tables; omit to preserve an existing table. true removes Jint per-execution budgets only for this table's backend V8 events while retaining the process resident-memory guard.")},async({name:o,description:s,tabs:c,isTree:l,column:u,formOpenType:p,formOpenWidth:d,v8Unlimited:h})=>{try{let m=await t.createTable(o,s,{Tabs:c,IsTree:l,Column:u??2,FormOpenType:p,FormOpenWidth:d,V8Unlimited:h===void 0?void 0:h?1:0});if(m.Code!==1)return{content:[{type:"text",text:`Error: ${m.Msg}`}],isError:!0};let y=m.Data;return{content:[{type:"text",text:`\u2705 Table "${o}" created.
|
|
534
536
|
- TableId: ${y?.TableId}
|
|
535
|
-
- Use this TableId when adding fields via microi_add_field`}]}}catch(m){return{content:[{type:"text",text:`Error: ${m instanceof Error?m.message:String(m)}`}],isError:!0}}}),i.tool("microi_add_field",`Add a field to a custom table for OsClient "${r}". Inserts a record into diy_field and executes ALTER TABLE to add the column. The "type" parameter MUST be a platform-allowed column type. \u26A0\uFE0F FORBIDDEN: datetime, date, timestamp, time \u2014 all date/time fields MUST use varchar(25) and store 'yyyy-MM-dd HH:mm:ss' strings. Allowed types: varchar(N), mediumtext, longtext, int, bigint, decimal(18,N). This tool is IDEMPOTENT \u2014 calling it again with the same TableId+name returns Skipped:true instead of failing.`,{tableId:f.string().describe("The TableId returned from microi_create_table"),name:f.string().describe('Field name in English (e.g. "CustomerName", "Phone", "Amount")'),label:f.string().describe('Chinese display label (e.g. "\u5BA2\u6237\u540D\u79F0", "\u624B\u673A\u53F7", "\u91D1\u989D")'),type:f.string().optional().describe("Platform column type. Default: varchar(500). Valid: varchar(25/50/200/500/2000), int, bigint, decimal(18,2), mediumtext, longtext. \u26A0\uFE0F FORBIDDEN: datetime, date, timestamp, float, double, boolean \u2014 for dates use varchar(25); for floats use decimal(18,N); for booleans use int."),component:f.string().optional().describe("UI component type. Default: Text. Options: Text, Textarea, NumberText, Select, MultipleSelect, Radio, Checkbox, Switch, DateTime, RichText, ImgUpload, FileUpload, AutoNumber, JoinForm, OpenTable, SelectTree, Cascader, Department, Address, Map, Rate, TableChild"),visible:f.number().optional().describe("Is visible in form (1=yes, 0=no). Default: 1"),appVisible:f.number().optional().describe("Is visible in mobile app (1=yes, 0=no). Default: 1"),tab:f.string().optional().describe("Form tab group name (for organizing fields into tabs)"),tableWidth:f.number().optional().describe("Column width in list view (pixels). Default: 120"),sort:f.number().optional().describe("Field display order (smaller = front). If omitted, MCP auto-increments per table starting at 100, step 10 \u2014 so adding fields in business-meaningful order produces correct list/form ordering automatically. Override only when you need a specific position."),readonly:f.number().optional().describe("Is readonly (1=yes, 0=no). Default: 0"),notEmpty:f.number().optional().describe("Required field validation (1=required, 0=optional). Default: 0"),unique:f.number().optional().describe("Unique constraint (1=unique, 0=allow duplicates). Default: 0"),defaultValue:f.string().optional().describe("Default value for the field"),placeholder:f.string().optional().describe("Placeholder text shown in form input"),formWidth:f.number().nullable().optional().describe("Field width in form grid columns (1-24). Default: null/omitted for normal fields. Use 24 only for full-row controls such as CodeEditor, Textarea, RichText, upload, TableChild, map/layout/custom components."),data:f.string().optional().describe('Options data source for Select/MultipleSelect/Radio/Checkbox components. REQUIRED for these four components. Format: "key1|label1,key2|label2" (KeyValue, recommended \u2014 e.g. "1|\u542F\u7528,0|\u7981\u7528", "male|\u7537,female|\u5973") \u2014 backend stores key, displays label. Or simple "v1,v2,v3" (same value for both). Backend auto-builds the Config JSON. For SQL/ApiEngine/DataSource sources, use the config parameter instead.'),config:f.string().optional().describe(`Component config JSON string. Auto-generated for Select/Radio/Checkbox when "data" is provided. Use this only for advanced cases:
|
|
537
|
+
- Use this TableId when adding fields via microi_add_field`}]}}catch(m){return{content:[{type:"text",text:`Error: ${m instanceof Error?m.message:String(m)}`}],isError:!0}}}),i.tool("microi_repair_audit_fields",`Repair the fixed audit-field metadata for one existing table in OsClient "${r}". The backend reconciles Id, CreateTime, UpdateTime, UserId, UserName and IsDeleted only when the physical columns exist, restores soft-deleted diy_field rows, adds missing diy_field rows without repeating DDL, clears shared metadata caches, and reads the final state back. The fields remain hidden by default when diy_table.DisplayDefaultField is off.`,{tableId:f.string().optional().describe("Exact diy_table.Id. Provide tableId or tableName."),tableName:f.string().optional().describe("Exact physical table/diy_table.Name. Provide tableName or tableId.")},async({tableId:o,tableName:s})=>{if(!o&&!s)return{content:[{type:"text",text:"Error: tableId \u548C tableName \u81F3\u5C11\u4F20\u4E00\u4E2A\u3002"}],isError:!0};try{let c=await t.repairFixedAuditFields({tableId:o,tableName:s});return c.Code!==1?{content:[{type:"text",text:`Error: ${c.Msg}`}],isError:!0}:{content:[{type:"text",text:JSON.stringify(c.Data||{},null,2)}]}}catch(c){return{content:[{type:"text",text:`Error: ${c instanceof Error?c.message:String(c)}`}],isError:!0}}}),i.tool("microi_add_field",`Add a field to a custom table for OsClient "${r}". Inserts a record into diy_field and executes ALTER TABLE to add the column. The "type" parameter MUST be a platform-allowed column type. \u26A0\uFE0F FORBIDDEN: datetime, date, timestamp, time \u2014 all date/time fields MUST use varchar(25) and store 'yyyy-MM-dd HH:mm:ss' strings. Allowed types: varchar(N), mediumtext, longtext, int, bigint, decimal(18,N). This tool is IDEMPOTENT \u2014 calling it again with the same TableId+name returns Skipped:true instead of failing.`,{tableId:f.string().describe("The TableId returned from microi_create_table"),name:f.string().describe('Field name in English (e.g. "CustomerName", "Phone", "Amount")'),label:f.string().describe('Chinese display label (e.g. "\u5BA2\u6237\u540D\u79F0", "\u624B\u673A\u53F7", "\u91D1\u989D")'),type:f.string().optional().describe("Platform column type. Default: varchar(500). Valid: varchar(25/50/200/500/2000), int, bigint, decimal(18,2), mediumtext, longtext. \u26A0\uFE0F FORBIDDEN: datetime, date, timestamp, float, double, boolean \u2014 for dates use varchar(25); for floats use decimal(18,N); for booleans use int."),component:f.string().optional().describe("UI component type. Default: Text. Options: Text, Textarea, NumberText, Select, MultipleSelect, Radio, Checkbox, Switch, DateTime, RichText, ImgUpload, FileUpload, AutoNumber, JoinForm, OpenTable, SelectTree, Cascader, Department, Address, Map, Rate, TableChild"),visible:f.number().optional().describe("Is visible in form (1=yes, 0=no). Default: 1"),appVisible:f.number().optional().describe("Is visible in mobile app (1=yes, 0=no). Default: 1"),tab:f.string().optional().describe("Form tab group name (for organizing fields into tabs)"),tableWidth:f.number().optional().describe("Column width in list view (pixels). Default: 120"),sort:f.number().optional().describe("Field display order (smaller = front). If omitted, MCP auto-increments per table starting at 100, step 10 \u2014 so adding fields in business-meaningful order produces correct list/form ordering automatically. Override only when you need a specific position."),readonly:f.number().optional().describe("Is readonly (1=yes, 0=no). Default: 0"),notEmpty:f.number().optional().describe("Required field validation (1=required, 0=optional). Default: 0"),unique:f.number().optional().describe("Unique constraint (1=unique, 0=allow duplicates). Default: 0"),defaultValue:f.string().optional().describe("Default value for the field"),placeholder:f.string().optional().describe("Placeholder text shown in form input"),formWidth:f.number().nullable().optional().describe("Field width in form grid columns (1-24). Default: null/omitted for normal fields. Use 24 only for full-row controls such as CodeEditor, Textarea, RichText, upload, TableChild, map/layout/custom components."),data:f.string().optional().describe('Options data source for Select/MultipleSelect/Radio/Checkbox components. REQUIRED for these four components. Format: "key1|label1,key2|label2" (KeyValue, recommended \u2014 e.g. "1|\u542F\u7528,0|\u7981\u7528", "male|\u7537,female|\u5973") \u2014 backend stores key, displays label. Or simple "v1,v2,v3" (same value for both). Backend auto-builds the Config JSON. For SQL/ApiEngine/DataSource sources, use the config parameter instead.'),config:f.string().optional().describe(`Component config JSON string. Auto-generated for Select/Radio/Checkbox when "data" is provided. Use this only for advanced cases:
|
|
536
538
|
- SQL source: '{"DataSource":"Sql","Sql":"select Id,Name from t where Name like \\'%$Keyword$%\\' limit 0,20","SelectLabel":"Name","SelectSaveField":"Id","DataSourceSqlRemote":true}'
|
|
537
539
|
- ApiEngine: '{"DataSource":"ApiEngine","DataSourceApiEngineKey":"key","SelectLabel":"name","SelectSaveField":"id"}'
|
|
538
540
|
- AutoNumber: '{"AutoNumberFixed":"ORD","AutoNumberLength":4}'
|