@microi.net/cli 5.9.7 → 5.9.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.codebuddy-plugin/marketplace.json +2 -2
- package/.codebuddy-plugin/plugin.json +1 -1
- package/.codex-plugin/plugin.json +43 -43
- package/.workbuddy-plugin/marketplace.json +2 -2
- package/.workbuddy-plugin/plugin.json +1 -1
- package/assets/build-meta.json +4 -4
- package/cordis.patch.yml +1 -1
- package/package.json +82 -82
- package/scripts/microi-cli.js +54 -54
- package/scripts/microi-skills.meta.json +210 -210
- package/skills/.microi-skills-version.json +2 -2
- package/skills/.progressive-disclosure-manifest.json +25 -25
- package/skills/microi-client-frontend/SKILL.md +8 -2
- package/skills/microi-deployment/SKILL.md +6 -0
- package/skills/microi-docs-coverage/references/capability-map.md +1 -1
- package/skills/microi-system-delivery/references/progressive-02-/350/207/252/345/212/250/345/214/226/346/265/213/350/257/225/345/277/205/351/241/273/350/246/206/347/233/226/347/232/204/345/235/221.md +20 -2
- package/skills/microi-uniapp-frontend/SKILL.md +5 -1
- package/skills/module-engine/SKILL.md +10 -0
- package/skills/playwright-e2e/SKILL.md +2 -0
- package/skills/workspace-conventions/SKILL.md +4 -2
package/scripts/microi-cli.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var pi=Object.create;var _r=Object.defineProperty;var mi=Object.getOwnPropertyDescriptor;var fi=Object.getOwnPropertyNames;var hi=Object.getPrototypeOf,yi=Object.prototype.hasOwnProperty;var
|
|
3
|
-
`,r:"\r",t:" ",'"':'"',"\\":"\\","/":"/"},qe=class s extends Ti{static make(e){return new s(e)}constructor(e){super(Object.assign({},e,{readableObjectMode:!0})),this._packKeys=this._packStrings=this._packNumbers=this._streamKeys=this._streamStrings=this._streamNumbers=!0,e&&("packValues"in e&&(this._packKeys=this._packStrings=this._packNumbers=e.packValues),"packKeys"in e&&(this._packKeys=e.packKeys),"packStrings"in e&&(this._packStrings=e.packStrings),"packNumbers"in e&&(this._packNumbers=e.packNumbers),"streamValues"in e&&(this._streamKeys=this._streamStrings=this._streamNumbers=e.streamValues),"streamKeys"in e&&(this._streamKeys=e.streamKeys),"streamStrings"in e&&(this._streamStrings=e.streamStrings),"streamNumbers"in e&&(this._streamNumbers=e.streamNumbers),this._jsonStreaming=e.jsonStreaming),!this._packKeys&&(this._streamKeys=!0),!this._packStrings&&(this._streamStrings=!0),!this._packNumbers&&(this._streamNumbers=!0),this._done=!1,this._expect=this._jsonStreaming?"done":"value",this._stack=[],this._parent="",this._open_number=!1,this._accumulator=""}_flush(e){this._done=!0,super._flush(t=>{if(t)return e(t);this._open_number&&(this._streamNumbers&&this.push({name:"endNumber"}),this._open_number=!1,this._packNumbers&&(this.push({name:"numberValue",value:this._accumulator}),this._accumulator="")),e(null)})}_processBuffer(e){let t,n,r=0;e:for(;;)switch(this._expect){case"value1":case"value":if(G.value1.lastIndex=r,t=G.value1.exec(this._buffer),!t){if(this._done||r+_i<this._buffer.length)return r<this._buffer.length?e(new Error("Parser cannot parse input: expected a value")):e(new Error("Parser has expected a value"));break e}switch(n=t[0],n){case'"':this._streamStrings&&this.push({name:"startString"}),this._expect="string";break;case"{":this.push({name:"startObject"}),this._stack.push(this._parent),this._parent="object",this._expect="key1";break;case"[":this.push({name:"startArray"}),this._stack.push(this._parent),this._parent="array",this._expect="value1";break;case"]":if(this._expect!=="value1")return e(new Error("Parser cannot parse input: unexpected token ']'"));this._open_number&&(this._streamNumbers&&this.push({name:"endNumber"}),this._open_number=!1,this._packNumbers&&(this.push({name:"numberValue",value:this._accumulator}),this._accumulator="")),this.push({name:"endArray"}),this._parent=this._stack.pop(),this._expect=Ne[this._parent];break;case"-":this._open_number=!0,this._streamNumbers&&(this.push({name:"startNumber"}),this.push({name:"numberChunk",value:"-"})),this._packNumbers&&(this._accumulator="-"),this._expect="numberStart";break;case"0":this._open_number=!0,this._streamNumbers&&(this.push({name:"startNumber"}),this.push({name:"numberChunk",value:"0"})),this._packNumbers&&(this._accumulator="0"),this._expect="numberFraction";break;case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":this._open_number=!0,this._streamNumbers&&(this.push({name:"startNumber"}),this.push({name:"numberChunk",value:n})),this._packNumbers&&(this._accumulator=n),this._expect="numberDigit";break;case"true":case"false":case"null":if(this._buffer.length-r===n.length&&!this._done)break e;this.push({name:n+"Value",value:Pi[n]}),this._expect=Ne[this._parent];break}fe?this._buffer=this._buffer.slice(n.length):r+=n.length;break;case"keyVal":case"string":if(G.string.lastIndex=r,t=G.string.exec(this._buffer),!t){if(r<this._buffer.length&&(this._done||this._buffer.length-r>=6))return e(new Error("Parser cannot parse input: escaped characters"));if(this._done)return e(new Error("Parser has expected a string value"));break e}if(n=t[0],n==='"')this._expect==="keyVal"?(this._streamKeys&&this.push({name:"endKey"}),this._packKeys&&(this.push({name:"keyValue",value:this._accumulator}),this._accumulator=""),this._expect="colon"):(this._streamStrings&&this.push({name:"endString"}),this._packStrings&&(this.push({name:"stringValue",value:this._accumulator}),this._accumulator=""),this._expect=Ne[this._parent]);else if(n.length>1&&n.charAt(0)==="\\"){let i=n.length==2?Ri[n.charAt(1)]:Di(n);(this._expect==="keyVal"?this._streamKeys:this._streamStrings)&&this.push({name:"stringChunk",value:i}),(this._expect==="keyVal"?this._packKeys:this._packStrings)&&(this._accumulator+=i)}else(this._expect==="keyVal"?this._streamKeys:this._streamStrings)&&this.push({name:"stringChunk",value:n}),(this._expect==="keyVal"?this._packKeys:this._packStrings)&&(this._accumulator+=n);fe?this._buffer=this._buffer.slice(n.length):r+=n.length;break;case"key1":case"key":if(G.key1.lastIndex=r,t=G.key1.exec(this._buffer),!t){if(r<this._buffer.length||this._done)return e(new Error("Parser cannot parse input: expected an object key"));break e}if(n=t[0],n==='"')this._streamKeys&&this.push({name:"startKey"}),this._expect="keyVal";else if(n==="}"){if(this._expect!=="key1")return e(new Error("Parser cannot parse input: unexpected token '}'"));this.push({name:"endObject"}),this._parent=this._stack.pop(),this._expect=Ne[this._parent]}fe?this._buffer=this._buffer.slice(n.length):r+=n.length;break;case"colon":if(G.colon.lastIndex=r,t=G.colon.exec(this._buffer),!t){if(r<this._buffer.length||this._done)return e(new Error("Parser cannot parse input: expected ':'"));break e}n=t[0],n===":"&&(this._expect="value"),fe?this._buffer=this._buffer.slice(n.length):r+=n.length;break;case"arrayStop":case"objectStop":if(G.comma.lastIndex=r,t=G.comma.exec(this._buffer),!t){if(r<this._buffer.length||this._done)return e(new Error("Parser cannot parse input: expected ','"));break e}if(this._open_number&&(this._streamNumbers&&this.push({name:"endNumber"}),this._open_number=!1,this._packNumbers&&(this.push({name:"numberValue",value:this._accumulator}),this._accumulator="")),n=t[0],n===",")this._expect=this._expect==="arrayStop"?"value":"key";else if(n==="}"||n==="]"){if(n==="}"?this._expect==="arrayStop":this._expect!=="arrayStop")return e(new Error("Parser cannot parse input: expected '"+(this._expect==="arrayStop"?"]":"}")+"'"));this.push({name:n==="}"?"endObject":"endArray"}),this._parent=this._stack.pop(),this._expect=Ne[this._parent]}fe?this._buffer=this._buffer.slice(n.length):r+=n.length;break;case"numberStart":if(G.numberStart.lastIndex=r,t=G.numberStart.exec(this._buffer),!t){if(r<this._buffer.length||this._done)return e(new Error("Parser cannot parse input: expected a starting digit"));break e}n=t[0],this._streamNumbers&&this.push({name:"numberChunk",value:n}),this._packNumbers&&(this._accumulator+=n),this._expect=n==="0"?"numberFraction":"numberDigit",fe?this._buffer=this._buffer.slice(n.length):r+=n.length;break;case"numberDigit":if(G.numberDigit.lastIndex=r,t=G.numberDigit.exec(this._buffer),!t){if(r<this._buffer.length||this._done)return e(new Error("Parser cannot parse input: expected a digit"));break e}if(n=t[0],n)this._streamNumbers&&this.push({name:"numberChunk",value:n}),this._packNumbers&&(this._accumulator+=n),fe?this._buffer=this._buffer.slice(n.length):r+=n.length;else{if(r<this._buffer.length){this._expect="numberFraction";break}if(this._done){this._expect=Ne[this._parent];break}break e}break;case"numberFraction":if(G.numberFraction.lastIndex=r,t=G.numberFraction.exec(this._buffer),!t){if(r<this._buffer.length||this._done){this._expect=Ne[this._parent];break}break e}n=t[0],this._streamNumbers&&this.push({name:"numberChunk",value:n}),this._packNumbers&&(this._accumulator+=n),this._expect=n==="."?"numberFracStart":"numberExpSign",fe?this._buffer=this._buffer.slice(n.length):r+=n.length;break;case"numberFracStart":if(G.numberFracStart.lastIndex=r,t=G.numberFracStart.exec(this._buffer),!t){if(r<this._buffer.length||this._done)return e(new Error("Parser cannot parse input: expected a fractional part of a number"));break e}n=t[0],this._streamNumbers&&this.push({name:"numberChunk",value:n}),this._packNumbers&&(this._accumulator+=n),this._expect="numberFracDigit",fe?this._buffer=this._buffer.slice(n.length):r+=n.length;break;case"numberFracDigit":if(G.numberFracDigit.lastIndex=r,t=G.numberFracDigit.exec(this._buffer),n=t[0],n)this._streamNumbers&&this.push({name:"numberChunk",value:n}),this._packNumbers&&(this._accumulator+=n),fe?this._buffer=this._buffer.slice(n.length):r+=n.length;else{if(r<this._buffer.length){this._expect="numberExponent";break}if(this._done){this._expect=Ne[this._parent];break}break e}break;case"numberExponent":if(G.numberExponent.lastIndex=r,t=G.numberExponent.exec(this._buffer),!t){if(r<this._buffer.length){this._expect=Ne[this._parent];break}if(this._done){this._expect="done";break}break e}n=t[0],this._streamNumbers&&this.push({name:"numberChunk",value:n}),this._packNumbers&&(this._accumulator+=n),this._expect="numberExpSign",fe?this._buffer=this._buffer.slice(n.length):r+=n.length;break;case"numberExpSign":if(G.numberExpSign.lastIndex=r,t=G.numberExpSign.exec(this._buffer),!t){if(r<this._buffer.length){this._expect="numberExpStart";break}if(this._done)return e(new Error("Parser has expected an exponent value of a number"));break e}n=t[0],this._streamNumbers&&this.push({name:"numberChunk",value:n}),this._packNumbers&&(this._accumulator+=n),this._expect="numberExpStart",fe?this._buffer=this._buffer.slice(n.length):r+=n.length;break;case"numberExpStart":if(G.numberExpStart.lastIndex=r,t=G.numberExpStart.exec(this._buffer),!t){if(r<this._buffer.length||this._done)return e(new Error("Parser cannot parse input: expected an exponent part of a number"));break e}n=t[0],this._streamNumbers&&this.push({name:"numberChunk",value:n}),this._packNumbers&&(this._accumulator+=n),this._expect="numberExpDigit",fe?this._buffer=this._buffer.slice(n.length):r+=n.length;break;case"numberExpDigit":if(G.numberExpDigit.lastIndex=r,t=G.numberExpDigit.exec(this._buffer),n=t[0],n)this._streamNumbers&&this.push({name:"numberChunk",value:n}),this._packNumbers&&(this._accumulator+=n),fe?this._buffer=this._buffer.slice(n.length):r+=n.length;else{if(r<this._buffer.length||this._done){this._expect=Ne[this._parent];break}break e}break;case"done":if(G.ws.lastIndex=r,t=G.ws.exec(this._buffer),!t){if(r<this._buffer.length){if(this._jsonStreaming){this._expect="value";break}return e(new Error("Parser cannot parse input: unexpected characters"))}break e}n=t[0],this._open_number&&(this._streamNumbers&&this.push({name:"endNumber"}),this._open_number=!1,this._packNumbers&&(this.push({name:"numberValue",value:this._accumulator}),this._accumulator="")),fe?this._buffer=this._buffer.slice(n.length):r+=n.length;break}!fe&&(this._buffer=this._buffer.slice(r)),e(null)}};qe.parser=qe.make;qe.make.Constructor=qe;Yr.exports=qe});var es=Yt((ma,Zr)=>{"use strict";var Ii=s=>s.on("data",e=>s.emit(e.name,e.value));Zr.exports=Ii});var ns=Yt((fa,ts)=>{"use strict";var Zn=Xr(),Ni=es(),er=s=>Ni(new Zn(s));er.Parser=Zn;er.parser=Zn.parser;ts.exports=er});var oe=B(require("fs")),le=B(require("path")),di=B(require("readline"));var Pr=B(require("os")),Dr=process.cwd();function Rr(s){Dr=s}var Ci={append:s=>process.stderr.write(s),appendLine:(s="")=>console.error(s),clear:()=>{},show:()=>{},hide:()=>{},replace:s=>process.stderr.write(s),dispose:()=>{},name:"Microi CLI"},kt={get workspaceFolders(){return[{uri:{fsPath:Dr}}]},workspaceFile:void 0,findFiles:async()=>[]},On={machineId:Pr.hostname()||"microi-cli",sessionId:`microi-cli-${process.pid}`},et={executeCommand:async()=>{}},tt={Notification:15},Ir={file:s=>({fsPath:s})},Se={createOutputChannel:()=>Ci,showInformationMessage:async()=>{},showWarningMessage:async()=>{},showErrorMessage:async()=>{},showTextDocument:async()=>{},onDidChangeWindowState:()=>({dispose:()=>{}}),withProgress:async(s,e)=>e({report:({message:t})=>t&&console.error(t)},{isCancellationRequested:!1,onCancellationRequested:()=>({dispose:()=>{}})})};var v=B(require("fs")),E=B(require("path"));var It=B(require("https")),Nt=B(require("http")),on=B(require("crypto")),dt=B(require("fs"));var _e=B(require("path")),X=B(require("fs")),Jr=B(require("crypto"));var rt=".microi-meta.json",Xt=".microi-config.json",vt=".microi-mcp-tokens.json";var Nr=".mcp.json";var Ie="Microi-V8-Engine";var st="\u63A5\u53E3\u5F15\u64CE",Mr="V8\u4E8B\u4EF6",Le="\u8868\u5355\u5F15\u64CE",Ge="\u6A21\u5757\u5F15\u64CE",it="\u6D41\u7A0B\u5F15\u64CE",Ar="AI\u5E94\u7528",Zt="\u8868\u5355V8\u4E8B\u4EF6",Et="\u5B57\u6BB5V8\u4E8B\u4EF6",en="\u8282\u70B9",xr={InFormV8:"\u524D\u7AEF\u8868\u5355\u8FDB\u5165V8\u4E8B\u4EF6",SubmitFormV8:"\u524D\u7AEF\u8868\u5355\u63D0\u4EA4\u524DV8\u4E8B\u4EF6",SubmitBeforeServerV8:"\u540E\u7AEF\u8868\u5355\u63D0\u4EA4\u524DV8\u4E8B\u4EF6",SubmitAfterServerV8:"\u540E\u7AEF\u8868\u5355\u63D0\u4EA4\u540EV8\u4E8B\u4EF6",ServerDataV8:"\u540E\u7AEF\u6570\u636E\u5904\u7406V8\u4E8B\u4EF6",OutFormV8:"\u524D\u7AEF\u8868\u5355\u63D0\u4EA4\u540EV8\u4E8B\u4EF6",DataFilterV8:"\u540E\u7AEF\u6570\u636E\u8FC7\u6EE4V8\u4E8B\u4EF6"},$n={V8Code:"\u503C\u53D8\u66F4V8\u4E8B\u4EF6",KeyupV8Code:"\u952E\u76D8V8\u4E8B\u4EF6",V8TmpEngineTable:"\u6A21\u677FV8\u5F15\u64CE\uFF08\u8868\u683C\uFF09",V8TmpEngineForm:"\u6A21\u677FV8\u5F15\u64CE\uFF08\u8868\u5355\uFF09"},ot={PageTabs:"\u9875\u9762\u591ATab",PageBtns:"[\u9875\u9762]\u66F4\u591A\u6309\u94AE",MoreBtns:"[\u884C]\u66F4\u591A\u6309\u94AE",FormBtns:"[\u8868\u5355]\u66F4\u591A\u6309\u94AE",BatchSelectMoreBtns:"[\u6279\u91CF\u9009\u62E9]\u66F4\u591A\u6309\u94AE",ExportMoreBtns:"[\u5BFC\u51FA]\u66F4\u591A\u6309\u94AE"},Tt={SqlJoin:"Join\u5173\u8054",SqlWhere:"Where\u6761\u4EF6"},Fr={StartV8:"\u8282\u70B9\u5F00\u59CB\u524D\u7AEFV8\u4E8B\u4EF6",EndV8:"\u8282\u70B9\u7ED3\u675F\u524D\u7AEFV8\u4E8B\u4EF6",StartV8Server:"\u8282\u70B9\u5F00\u59CB\u540E\u7AEFV8\u4E8B\u4EF6",EndV8Server:"\u8282\u70B9\u7ED3\u675F\u540E\u7AEFV8\u4E8B\u4EF6",LineValueV8:"\u6761\u4EF6\u5224\u65ADV8\u4E8B\u4EF6",AllowAddUserV8Code:"\u5141\u8BB8\u6DFB\u52A0\u5BA1\u6279\u4EBAV8\u4E8B\u4EF6"},_t=".microi-typings",tn="v8-engine.d.ts",Bn=".github",Ln="copilot-instructions.md",Un="CLAUDE.md",jn="AGENTS.md",Kn=".cursorrules",Hn=".cursor/rules",Wn="microi-skills.mdc",H={LOGIN:"/api/SysUser/Login",TOKEN_LOGIN:"/api/SysUser/tokenlogin",GET_SYS_CONFIG:"/api/DiyTable/GetSysConfig",GET_CAPTCHA:"/api/Captcha/GetCaptcha",GET_STATUS:"/api/V8Debug/GetStatus",GET_ENGINE_LIST:"/api/V8Debug/GetApiEngineList",UPDATE_ENGINE_CODE:"/api/V8Debug/UpdateApiEngineCode",EXECUTE_ENGINE:"/api/V8Debug/ExecuteApiEngine",UPLOAD_FILE_BASE64:"/api/V8Debug/UploadFileBase64",LIST_APPLICATIONS:"/api/V8Debug/ListApplications",GET_APPLICATION_CONTEXT:"/api/V8Debug/GetApplicationContext",GET_APPLICATION_FILE:"/api/V8Debug/GetApplicationFile",SYNC_MICRO_SERVICE_SOURCE:"/api/V8Debug/SyncMicroServiceSource",STAGE_MICRO_SERVICE_SOURCE_FILE:"/api/V8Debug/StageMicroServiceSourceFile",FINALIZE_MICRO_SERVICE_SOURCE_MANIFEST:"/api/V8Debug/FinalizeMicroServiceSourceManifest",UPLOAD_APPLICATION_ASSET_STREAM:"/api/V8Debug/UploadApplicationAssetStream",FINALIZE_APPLICATION_STREAM_PUBLISH:"/api/V8Debug/FinalizeApplicationStreamPublish",GET_EVENT_LIST:"/api/V8Debug/GetV8EventList",GET_EVENT_CODE:"/api/V8Debug/GetV8EventCode",UPDATE_EVENT_CODE:"/api/V8Debug/UpdateV8EventCode",EXECUTE_EVENT:"/api/V8Debug/ExecuteV8Event",GET_WORKFLOW_V8_EVENT_LIST:"/api/V8Debug/GetWorkflowV8EventList",GET_WORKFLOW_V8_EVENT_CODE:"/api/V8Debug/GetWorkflowV8EventCode",UPDATE_WORKFLOW_V8_EVENT_CODE:"/api/V8Debug/UpdateWorkflowV8EventCode",GET_ENGINE_CODE:"/api/V8Debug/GetApiEngineCode",CREATE_ENGINE:"/api/V8Debug/CreateApiEngine",REFRESH_TOKEN:"/api/SysUser/RefreshToken",GET_DB_SCHEMA:"/api/V8Debug/GetDbSchema",LIST_MODULES:"/api/V8Debug/ListModules",GET_MODULE:"/api/V8Debug/GetModule",UPDATE_MODULE:"/api/V8Debug/UpdateModule",GET_FIELD_LIST:"/api/V8Debug/GetFieldList",UPDATE_FIELD:"/api/V8Debug/UpdateField",GET_PLAYWRIGHT_CONTEXT:"/api/V8Debug/GetPlaywrightContext",FORM_GET_DATA:"/api/FormEngine/GetFormData",FORM_GET_LIST:"/api/FormEngine/GetTableData",FORM_ADD:"/api/FormEngine/AddFormData",FORM_UPDATE:"/api/FormEngine/UptFormData",FORM_UPDATE_BY_WHERE:"/api/FormEngine/UptFormDataByWhere",FORM_DELETE_BY_WHERE:"/api/FormEngine/DelFormDataByWhere",DEBUG_WS:"/api/V8Debug/ws"},at=".microi-db-schema.json",ze=".microi-db-schema.md";var Gn=`\u26A0\uFE0F \u4FEE\u6539\u540E\u8BF7\u624B\u52A8\u63A8\u9001\u5230\u6570\u636E\u5E93
|
|
2
|
+
"use strict";var pi=Object.create;var _r=Object.defineProperty;var mi=Object.getOwnPropertyDescriptor;var fi=Object.getOwnPropertyNames;var hi=Object.getPrototypeOf,yi=Object.prototype.hasOwnProperty;var Qt=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports);var Si=(s,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of fi(e))!yi.call(s,r)&&r!==t&&_r(s,r,{get:()=>e[r],enumerable:!(n=mi(e,r))||n.enumerable});return s};var B=(s,e,t)=>(t=s!=null?pi(hi(s)):{},Si(e||!s||!s.__esModule?_r(t,"default",{value:s,enumerable:!0}):t,s));var Yr=Qt((ga,qr)=>{"use strict";var{Transform:vi}=require("stream"),{StringDecoder:Ei}=require("string_decoder"),Xn=class extends vi{constructor(e){super(Object.assign({},e,{writableObjectMode:!1})),this._buffer=""}_transform(e,t,n){typeof e=="string"?this._transform=this._transformString:(this._stringDecoder=new Ei,this._transform=this._transformBuffer),this._transform(e,t,n)}_transformBuffer(e,t,n){this._buffer+=this._stringDecoder.write(e),this._processBuffer(n)}_transformString(e,t,n){this._buffer+=e.toString(),this._processBuffer(n)}_processBuffer(e){this._buffer&&(this.push(this._buffer,"utf8"),this._buffer=""),e(null)}_flushInput(){this._stringDecoder&&(this._buffer+=this._stringDecoder.end())}_flush(e){this._flushInput(),this._processBuffer(e)}};qr.exports=Xn});var Xr=Qt((pa,Qr)=>{"use strict";var Ti=Yr(),G={value1:/^(?:[\"\{\[\]\-\d]|true\b|false\b|null\b|\s{1,256})/,string:/^(?:[^\x00-\x1f\"\\]{1,256}|\\[bfnrt\"\\\/]|\\u[\da-fA-F]{4}|\")/,key1:/^(?:[\"\}]|\s{1,256})/,colon:/^(?:\:|\s{1,256})/,comma:/^(?:[\,\]\}]|\s{1,256})/,ws:/^\s{1,256}/,numberStart:/^\d/,numberDigit:/^\d{0,256}/,numberFraction:/^[\.eE]/,numberExponent:/^[eE]/,numberExpSign:/^[-+]/},_i=16,fe=!0;try{new RegExp(".","y"),fe=!1}catch{}!fe&&Object.keys(G).forEach(s=>{let e=G[s].source.slice(1);e.slice(0,3)==="(?:"&&e.slice(-1)===")"&&(e=e.slice(3,-1)),G[s]=new RegExp(e,"y")});G.numberFracStart=G.numberExpStart=G.numberStart;G.numberFracDigit=G.numberExpDigit=G.numberDigit;var Pi={true:!0,false:!1,null:null},Ne={object:"objectStop",array:"arrayStop","":"done"},Di=s=>String.fromCharCode(parseInt(s.slice(2),16)),Ii={b:"\b",f:"\f",n:`
|
|
3
|
+
`,r:"\r",t:" ",'"':'"',"\\":"\\","/":"/"},qe=class s extends Ti{static make(e){return new s(e)}constructor(e){super(Object.assign({},e,{readableObjectMode:!0})),this._packKeys=this._packStrings=this._packNumbers=this._streamKeys=this._streamStrings=this._streamNumbers=!0,e&&("packValues"in e&&(this._packKeys=this._packStrings=this._packNumbers=e.packValues),"packKeys"in e&&(this._packKeys=e.packKeys),"packStrings"in e&&(this._packStrings=e.packStrings),"packNumbers"in e&&(this._packNumbers=e.packNumbers),"streamValues"in e&&(this._streamKeys=this._streamStrings=this._streamNumbers=e.streamValues),"streamKeys"in e&&(this._streamKeys=e.streamKeys),"streamStrings"in e&&(this._streamStrings=e.streamStrings),"streamNumbers"in e&&(this._streamNumbers=e.streamNumbers),this._jsonStreaming=e.jsonStreaming),!this._packKeys&&(this._streamKeys=!0),!this._packStrings&&(this._streamStrings=!0),!this._packNumbers&&(this._streamNumbers=!0),this._done=!1,this._expect=this._jsonStreaming?"done":"value",this._stack=[],this._parent="",this._open_number=!1,this._accumulator=""}_flush(e){this._done=!0,super._flush(t=>{if(t)return e(t);this._open_number&&(this._streamNumbers&&this.push({name:"endNumber"}),this._open_number=!1,this._packNumbers&&(this.push({name:"numberValue",value:this._accumulator}),this._accumulator="")),e(null)})}_processBuffer(e){let t,n,r=0;e:for(;;)switch(this._expect){case"value1":case"value":if(G.value1.lastIndex=r,t=G.value1.exec(this._buffer),!t){if(this._done||r+_i<this._buffer.length)return r<this._buffer.length?e(new Error("Parser cannot parse input: expected a value")):e(new Error("Parser has expected a value"));break e}switch(n=t[0],n){case'"':this._streamStrings&&this.push({name:"startString"}),this._expect="string";break;case"{":this.push({name:"startObject"}),this._stack.push(this._parent),this._parent="object",this._expect="key1";break;case"[":this.push({name:"startArray"}),this._stack.push(this._parent),this._parent="array",this._expect="value1";break;case"]":if(this._expect!=="value1")return e(new Error("Parser cannot parse input: unexpected token ']'"));this._open_number&&(this._streamNumbers&&this.push({name:"endNumber"}),this._open_number=!1,this._packNumbers&&(this.push({name:"numberValue",value:this._accumulator}),this._accumulator="")),this.push({name:"endArray"}),this._parent=this._stack.pop(),this._expect=Ne[this._parent];break;case"-":this._open_number=!0,this._streamNumbers&&(this.push({name:"startNumber"}),this.push({name:"numberChunk",value:"-"})),this._packNumbers&&(this._accumulator="-"),this._expect="numberStart";break;case"0":this._open_number=!0,this._streamNumbers&&(this.push({name:"startNumber"}),this.push({name:"numberChunk",value:"0"})),this._packNumbers&&(this._accumulator="0"),this._expect="numberFraction";break;case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":this._open_number=!0,this._streamNumbers&&(this.push({name:"startNumber"}),this.push({name:"numberChunk",value:n})),this._packNumbers&&(this._accumulator=n),this._expect="numberDigit";break;case"true":case"false":case"null":if(this._buffer.length-r===n.length&&!this._done)break e;this.push({name:n+"Value",value:Pi[n]}),this._expect=Ne[this._parent];break}fe?this._buffer=this._buffer.slice(n.length):r+=n.length;break;case"keyVal":case"string":if(G.string.lastIndex=r,t=G.string.exec(this._buffer),!t){if(r<this._buffer.length&&(this._done||this._buffer.length-r>=6))return e(new Error("Parser cannot parse input: escaped characters"));if(this._done)return e(new Error("Parser has expected a string value"));break e}if(n=t[0],n==='"')this._expect==="keyVal"?(this._streamKeys&&this.push({name:"endKey"}),this._packKeys&&(this.push({name:"keyValue",value:this._accumulator}),this._accumulator=""),this._expect="colon"):(this._streamStrings&&this.push({name:"endString"}),this._packStrings&&(this.push({name:"stringValue",value:this._accumulator}),this._accumulator=""),this._expect=Ne[this._parent]);else if(n.length>1&&n.charAt(0)==="\\"){let i=n.length==2?Ii[n.charAt(1)]:Di(n);(this._expect==="keyVal"?this._streamKeys:this._streamStrings)&&this.push({name:"stringChunk",value:i}),(this._expect==="keyVal"?this._packKeys:this._packStrings)&&(this._accumulator+=i)}else(this._expect==="keyVal"?this._streamKeys:this._streamStrings)&&this.push({name:"stringChunk",value:n}),(this._expect==="keyVal"?this._packKeys:this._packStrings)&&(this._accumulator+=n);fe?this._buffer=this._buffer.slice(n.length):r+=n.length;break;case"key1":case"key":if(G.key1.lastIndex=r,t=G.key1.exec(this._buffer),!t){if(r<this._buffer.length||this._done)return e(new Error("Parser cannot parse input: expected an object key"));break e}if(n=t[0],n==='"')this._streamKeys&&this.push({name:"startKey"}),this._expect="keyVal";else if(n==="}"){if(this._expect!=="key1")return e(new Error("Parser cannot parse input: unexpected token '}'"));this.push({name:"endObject"}),this._parent=this._stack.pop(),this._expect=Ne[this._parent]}fe?this._buffer=this._buffer.slice(n.length):r+=n.length;break;case"colon":if(G.colon.lastIndex=r,t=G.colon.exec(this._buffer),!t){if(r<this._buffer.length||this._done)return e(new Error("Parser cannot parse input: expected ':'"));break e}n=t[0],n===":"&&(this._expect="value"),fe?this._buffer=this._buffer.slice(n.length):r+=n.length;break;case"arrayStop":case"objectStop":if(G.comma.lastIndex=r,t=G.comma.exec(this._buffer),!t){if(r<this._buffer.length||this._done)return e(new Error("Parser cannot parse input: expected ','"));break e}if(this._open_number&&(this._streamNumbers&&this.push({name:"endNumber"}),this._open_number=!1,this._packNumbers&&(this.push({name:"numberValue",value:this._accumulator}),this._accumulator="")),n=t[0],n===",")this._expect=this._expect==="arrayStop"?"value":"key";else if(n==="}"||n==="]"){if(n==="}"?this._expect==="arrayStop":this._expect!=="arrayStop")return e(new Error("Parser cannot parse input: expected '"+(this._expect==="arrayStop"?"]":"}")+"'"));this.push({name:n==="}"?"endObject":"endArray"}),this._parent=this._stack.pop(),this._expect=Ne[this._parent]}fe?this._buffer=this._buffer.slice(n.length):r+=n.length;break;case"numberStart":if(G.numberStart.lastIndex=r,t=G.numberStart.exec(this._buffer),!t){if(r<this._buffer.length||this._done)return e(new Error("Parser cannot parse input: expected a starting digit"));break e}n=t[0],this._streamNumbers&&this.push({name:"numberChunk",value:n}),this._packNumbers&&(this._accumulator+=n),this._expect=n==="0"?"numberFraction":"numberDigit",fe?this._buffer=this._buffer.slice(n.length):r+=n.length;break;case"numberDigit":if(G.numberDigit.lastIndex=r,t=G.numberDigit.exec(this._buffer),!t){if(r<this._buffer.length||this._done)return e(new Error("Parser cannot parse input: expected a digit"));break e}if(n=t[0],n)this._streamNumbers&&this.push({name:"numberChunk",value:n}),this._packNumbers&&(this._accumulator+=n),fe?this._buffer=this._buffer.slice(n.length):r+=n.length;else{if(r<this._buffer.length){this._expect="numberFraction";break}if(this._done){this._expect=Ne[this._parent];break}break e}break;case"numberFraction":if(G.numberFraction.lastIndex=r,t=G.numberFraction.exec(this._buffer),!t){if(r<this._buffer.length||this._done){this._expect=Ne[this._parent];break}break e}n=t[0],this._streamNumbers&&this.push({name:"numberChunk",value:n}),this._packNumbers&&(this._accumulator+=n),this._expect=n==="."?"numberFracStart":"numberExpSign",fe?this._buffer=this._buffer.slice(n.length):r+=n.length;break;case"numberFracStart":if(G.numberFracStart.lastIndex=r,t=G.numberFracStart.exec(this._buffer),!t){if(r<this._buffer.length||this._done)return e(new Error("Parser cannot parse input: expected a fractional part of a number"));break e}n=t[0],this._streamNumbers&&this.push({name:"numberChunk",value:n}),this._packNumbers&&(this._accumulator+=n),this._expect="numberFracDigit",fe?this._buffer=this._buffer.slice(n.length):r+=n.length;break;case"numberFracDigit":if(G.numberFracDigit.lastIndex=r,t=G.numberFracDigit.exec(this._buffer),n=t[0],n)this._streamNumbers&&this.push({name:"numberChunk",value:n}),this._packNumbers&&(this._accumulator+=n),fe?this._buffer=this._buffer.slice(n.length):r+=n.length;else{if(r<this._buffer.length){this._expect="numberExponent";break}if(this._done){this._expect=Ne[this._parent];break}break e}break;case"numberExponent":if(G.numberExponent.lastIndex=r,t=G.numberExponent.exec(this._buffer),!t){if(r<this._buffer.length){this._expect=Ne[this._parent];break}if(this._done){this._expect="done";break}break e}n=t[0],this._streamNumbers&&this.push({name:"numberChunk",value:n}),this._packNumbers&&(this._accumulator+=n),this._expect="numberExpSign",fe?this._buffer=this._buffer.slice(n.length):r+=n.length;break;case"numberExpSign":if(G.numberExpSign.lastIndex=r,t=G.numberExpSign.exec(this._buffer),!t){if(r<this._buffer.length){this._expect="numberExpStart";break}if(this._done)return e(new Error("Parser has expected an exponent value of a number"));break e}n=t[0],this._streamNumbers&&this.push({name:"numberChunk",value:n}),this._packNumbers&&(this._accumulator+=n),this._expect="numberExpStart",fe?this._buffer=this._buffer.slice(n.length):r+=n.length;break;case"numberExpStart":if(G.numberExpStart.lastIndex=r,t=G.numberExpStart.exec(this._buffer),!t){if(r<this._buffer.length||this._done)return e(new Error("Parser cannot parse input: expected an exponent part of a number"));break e}n=t[0],this._streamNumbers&&this.push({name:"numberChunk",value:n}),this._packNumbers&&(this._accumulator+=n),this._expect="numberExpDigit",fe?this._buffer=this._buffer.slice(n.length):r+=n.length;break;case"numberExpDigit":if(G.numberExpDigit.lastIndex=r,t=G.numberExpDigit.exec(this._buffer),n=t[0],n)this._streamNumbers&&this.push({name:"numberChunk",value:n}),this._packNumbers&&(this._accumulator+=n),fe?this._buffer=this._buffer.slice(n.length):r+=n.length;else{if(r<this._buffer.length||this._done){this._expect=Ne[this._parent];break}break e}break;case"done":if(G.ws.lastIndex=r,t=G.ws.exec(this._buffer),!t){if(r<this._buffer.length){if(this._jsonStreaming){this._expect="value";break}return e(new Error("Parser cannot parse input: unexpected characters"))}break e}n=t[0],this._open_number&&(this._streamNumbers&&this.push({name:"endNumber"}),this._open_number=!1,this._packNumbers&&(this.push({name:"numberValue",value:this._accumulator}),this._accumulator="")),fe?this._buffer=this._buffer.slice(n.length):r+=n.length;break}!fe&&(this._buffer=this._buffer.slice(r)),e(null)}};qe.parser=qe.make;qe.make.Constructor=qe;Qr.exports=qe});var es=Qt((ma,Zr)=>{"use strict";var Ri=s=>s.on("data",e=>s.emit(e.name,e.value));Zr.exports=Ri});var ns=Qt((fa,ts)=>{"use strict";var Zn=Xr(),Ni=es(),er=s=>Ni(new Zn(s));er.Parser=Zn;er.parser=Zn.parser;ts.exports=er});var oe=B(require("fs")),le=B(require("path")),di=B(require("readline"));var Pr=B(require("os")),Dr=process.cwd();function Ir(s){Dr=s}var Ci={append:s=>process.stderr.write(s),appendLine:(s="")=>console.error(s),clear:()=>{},show:()=>{},hide:()=>{},replace:s=>process.stderr.write(s),dispose:()=>{},name:"Microi CLI"},kt={get workspaceFolders(){return[{uri:{fsPath:Dr}}]},workspaceFile:void 0,findFiles:async()=>[]},On={machineId:Pr.hostname()||"microi-cli",sessionId:`microi-cli-${process.pid}`},et={executeCommand:async()=>{}},tt={Notification:15},Rr={file:s=>({fsPath:s})},Se={createOutputChannel:()=>Ci,showInformationMessage:async()=>{},showWarningMessage:async()=>{},showErrorMessage:async()=>{},showTextDocument:async()=>{},onDidChangeWindowState:()=>({dispose:()=>{}}),withProgress:async(s,e)=>e({report:({message:t})=>t&&console.error(t)},{isCancellationRequested:!1,onCancellationRequested:()=>({dispose:()=>{}})})};var v=B(require("fs")),_=B(require("path"));var Rt=B(require("https")),Nt=B(require("http")),on=B(require("crypto")),dt=B(require("fs"));var _e=B(require("path")),Z=B(require("fs")),Jr=B(require("crypto"));var rt=".microi-meta.json",Xt=".microi-config.json",vt=".microi-mcp-tokens.json";var Nr=".mcp.json";var Re="Microi-V8-Engine";var st="\u63A5\u53E3\u5F15\u64CE",Ar="V8\u4E8B\u4EF6",Le="\u8868\u5355\u5F15\u64CE",Ge="\u6A21\u5757\u5F15\u64CE",it="\u6D41\u7A0B\u5F15\u64CE",Mr="AI\u5E94\u7528",Zt="\u8868\u5355V8\u4E8B\u4EF6",Et="\u5B57\u6BB5V8\u4E8B\u4EF6",en="\u8282\u70B9",xr={InFormV8:"\u524D\u7AEF\u8868\u5355\u8FDB\u5165V8\u4E8B\u4EF6",SubmitFormV8:"\u524D\u7AEF\u8868\u5355\u63D0\u4EA4\u524DV8\u4E8B\u4EF6",SubmitBeforeServerV8:"\u540E\u7AEF\u8868\u5355\u63D0\u4EA4\u524DV8\u4E8B\u4EF6",SubmitAfterServerV8:"\u540E\u7AEF\u8868\u5355\u63D0\u4EA4\u540EV8\u4E8B\u4EF6",ServerDataV8:"\u540E\u7AEF\u6570\u636E\u5904\u7406V8\u4E8B\u4EF6",OutFormV8:"\u524D\u7AEF\u8868\u5355\u63D0\u4EA4\u540EV8\u4E8B\u4EF6",DataFilterV8:"\u540E\u7AEF\u6570\u636E\u8FC7\u6EE4V8\u4E8B\u4EF6"},$n={V8Code:"\u503C\u53D8\u66F4V8\u4E8B\u4EF6",KeyupV8Code:"\u952E\u76D8V8\u4E8B\u4EF6",V8TmpEngineTable:"\u6A21\u677FV8\u5F15\u64CE\uFF08\u8868\u683C\uFF09",V8TmpEngineForm:"\u6A21\u677FV8\u5F15\u64CE\uFF08\u8868\u5355\uFF09"},ot={PageTabs:"\u9875\u9762\u591ATab",PageBtns:"[\u9875\u9762]\u66F4\u591A\u6309\u94AE",MoreBtns:"[\u884C]\u66F4\u591A\u6309\u94AE",FormBtns:"[\u8868\u5355]\u66F4\u591A\u6309\u94AE",BatchSelectMoreBtns:"[\u6279\u91CF\u9009\u62E9]\u66F4\u591A\u6309\u94AE",ExportMoreBtns:"[\u5BFC\u51FA]\u66F4\u591A\u6309\u94AE"},Tt={SqlJoin:"Join\u5173\u8054",SqlWhere:"Where\u6761\u4EF6"},Fr={StartV8:"\u8282\u70B9\u5F00\u59CB\u524D\u7AEFV8\u4E8B\u4EF6",EndV8:"\u8282\u70B9\u7ED3\u675F\u524D\u7AEFV8\u4E8B\u4EF6",StartV8Server:"\u8282\u70B9\u5F00\u59CB\u540E\u7AEFV8\u4E8B\u4EF6",EndV8Server:"\u8282\u70B9\u7ED3\u675F\u540E\u7AEFV8\u4E8B\u4EF6",LineValueV8:"\u6761\u4EF6\u5224\u65ADV8\u4E8B\u4EF6",AllowAddUserV8Code:"\u5141\u8BB8\u6DFB\u52A0\u5BA1\u6279\u4EBAV8\u4E8B\u4EF6"},_t=".microi-typings",tn="v8-engine.d.ts",Bn=".github",Ln="copilot-instructions.md",Un="CLAUDE.md",jn="AGENTS.md",Kn=".cursorrules",Hn=".cursor/rules",Wn="microi-skills.mdc",H={LOGIN:"/api/SysUser/Login",TOKEN_LOGIN:"/api/SysUser/tokenlogin",GET_SYS_CONFIG:"/api/DiyTable/GetSysConfig",GET_CAPTCHA:"/api/Captcha/GetCaptcha",GET_STATUS:"/api/V8Debug/GetStatus",GET_ENGINE_LIST:"/api/V8Debug/GetApiEngineList",UPDATE_ENGINE_CODE:"/api/V8Debug/UpdateApiEngineCode",EXECUTE_ENGINE:"/api/V8Debug/ExecuteApiEngine",UPLOAD_FILE_BASE64:"/api/V8Debug/UploadFileBase64",LIST_APPLICATIONS:"/api/V8Debug/ListApplications",GET_APPLICATION_CONTEXT:"/api/V8Debug/GetApplicationContext",GET_APPLICATION_FILE:"/api/V8Debug/GetApplicationFile",SYNC_MICRO_SERVICE_SOURCE:"/api/V8Debug/SyncMicroServiceSource",STAGE_MICRO_SERVICE_SOURCE_FILE:"/api/V8Debug/StageMicroServiceSourceFile",FINALIZE_MICRO_SERVICE_SOURCE_MANIFEST:"/api/V8Debug/FinalizeMicroServiceSourceManifest",UPLOAD_APPLICATION_ASSET_STREAM:"/api/V8Debug/UploadApplicationAssetStream",FINALIZE_APPLICATION_STREAM_PUBLISH:"/api/V8Debug/FinalizeApplicationStreamPublish",GET_EVENT_LIST:"/api/V8Debug/GetV8EventList",GET_EVENT_CODE:"/api/V8Debug/GetV8EventCode",UPDATE_EVENT_CODE:"/api/V8Debug/UpdateV8EventCode",EXECUTE_EVENT:"/api/V8Debug/ExecuteV8Event",GET_WORKFLOW_V8_EVENT_LIST:"/api/V8Debug/GetWorkflowV8EventList",GET_WORKFLOW_V8_EVENT_CODE:"/api/V8Debug/GetWorkflowV8EventCode",UPDATE_WORKFLOW_V8_EVENT_CODE:"/api/V8Debug/UpdateWorkflowV8EventCode",GET_ENGINE_CODE:"/api/V8Debug/GetApiEngineCode",CREATE_ENGINE:"/api/V8Debug/CreateApiEngine",REFRESH_TOKEN:"/api/SysUser/RefreshToken",GET_DB_SCHEMA:"/api/V8Debug/GetDbSchema",LIST_MODULES:"/api/V8Debug/ListModules",GET_MODULE:"/api/V8Debug/GetModule",UPDATE_MODULE:"/api/V8Debug/UpdateModule",GET_FIELD_LIST:"/api/V8Debug/GetFieldList",UPDATE_FIELD:"/api/V8Debug/UpdateField",GET_PLAYWRIGHT_CONTEXT:"/api/V8Debug/GetPlaywrightContext",FORM_GET_DATA:"/api/FormEngine/GetFormData",FORM_GET_LIST:"/api/FormEngine/GetTableData",FORM_ADD:"/api/FormEngine/AddFormData",FORM_UPDATE:"/api/FormEngine/UptFormData",FORM_UPDATE_BY_WHERE:"/api/FormEngine/UptFormDataByWhere",FORM_DELETE_BY_WHERE:"/api/FormEngine/DelFormDataByWhere",DEBUG_WS:"/api/V8Debug/ws"},at=".microi-db-schema.json",ze=".microi-db-schema.md";var Gn=`\u26A0\uFE0F \u4FEE\u6539\u540E\u8BF7\u624B\u52A8\u63A8\u9001\u5230\u6570\u636E\u5E93
|
|
4
4
|
*/
|
|
5
5
|
|
|
6
6
|
`;var ct="microi.isLoggedIn";var zn="microi.authToken",ve="microi.username",Ee="microi.password",Vr=`-----BEGIN PUBLIC KEY-----
|
|
@@ -10,46 +10,46 @@ XaFX8UgCFE4d4pvK6IvQsWunm+WfYqgrSzBMS1LH1fstmZB0wnVUX1uGROaZTKGZ
|
|
|
10
10
|
1DsI9VJ7gTHGL3R7sQIDAQAB
|
|
11
11
|
-----END PUBLIC KEY-----`;var we=B(require("fs")),ne=B(require("path")),Jn=require("child_process");var Or="# Microi VS Code extension local runtime files";function nn(s){let e="",t=0;for(;t<s.length;)if(s[t]==='"'){let n=t;for(t++;t<s.length&&s[t]!=='"';)s[t]==="\\"&&t++,t++;t++,e+=s.slice(n,t)}else if(s[t]==="/"&&s[t+1]==="/")for(;t<s.length&&s[t]!==`
|
|
12
12
|
`;)t++;else if(s[t]==="/"&&s[t+1]==="*"){for(t+=2;t<s.length&&!(s[t]==="*"&&s[t+1]==="/");)t++;t+=2}else e+=s[t],t++;return JSON.parse(e)}function me(s){we.existsSync(s)||we.mkdirSync(s,{recursive:!0})}function $r(s){return s.replace(/\\/g,"/").replace(/^\.\//,"")}function Br(s){let e=s;for(;;){let t=ne.join(e,".git");if(we.existsSync(t))try{let r=we.statSync(t);if(r.isDirectory())return{gitDir:t,workTreeRoot:e};if(r.isFile()){let o=we.readFileSync(t,"utf-8").match(/^gitdir:\s*(.+)$/m);if(o?.[1])return{gitDir:ne.isAbsolute(o[1])?o[1]:ne.resolve(e,o[1]),workTreeRoot:e}}}catch{return null}let n=ne.dirname(e);if(n===e)return null;e=n}}function Ue(s,e){try{let t=Br(s);if(!t)return;let n=ne.join(t.gitDir,"info");me(n);let r=ne.join(n,"exclude"),i=$r(ne.relative(t.workTreeRoot,s)),o=e.map(g=>g.trim()).filter(Boolean).map(g=>$r(g.replace(/^\/+/,""))).map(g=>i?`${i}/${g}`:g),a=we.existsSync(r)?we.readFileSync(r,"utf-8"):"",c=new Set(a.split(/\r?\n/).map(g=>g.trim())),l=o.filter(g=>!c.has(g));if(!l.length)return;let p=a.length>0&&!a.endsWith(`
|
|
13
|
-
`),
|
|
14
|
-
`,
|
|
15
|
-
`:""}${
|
|
13
|
+
`),d=a.includes(Or)?"":`${Or}
|
|
14
|
+
`,u=`${p?`
|
|
15
|
+
`:""}${d}${l.join(`
|
|
16
16
|
`)}
|
|
17
|
-
`;we.appendFileSync(r,
|
|
18
|
-
`)}function
|
|
17
|
+
`;we.appendFileSync(r,u,"utf-8")}catch{}}function lt(s){if(process.platform==="win32")try{let e=Br(s);if(!e)return;try{if((0,Jn.execFileSync)("git",["config","--get","core.longpaths"],{cwd:e.workTreeRoot,encoding:"utf-8",stdio:["ignore","pipe","ignore"],windowsHide:!0}).trim().toLowerCase()==="true")return}catch{}(0,Jn.execFileSync)("git",["config","core.longpaths","true"],{cwd:e.workTreeRoot,stdio:"ignore",windowsHide:!0})}catch{}}function X(s){let e=String(s||"").replace(/[<>:"/\\|?*\x00-\x1F]/g,"_").replace(/[. ]+$/g,""),t=!e||e==="."||e===".."?"_":e;return/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/i.test(t)?`_${t}`:t}function qn(s){return encodeURIComponent(String(s||"")).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)}function bi(s){try{return decodeURIComponent(String(s||""))}catch{return String(s||"")}}function Fe(s){let e=s.indexOf(Gn);return e!==-1?s.substring(e+Gn.length):s}function wi(s){let e=s||"";if(!e.trim())return!1;let t=e.trimStart();return t.startsWith("var ")||t.startsWith("let ")||t.startsWith("const ")||t.startsWith("function")||t.startsWith("return")||t.startsWith("//")||t.startsWith("/*")||e.includes("V8.")||e.includes("return ")||e.includes("=>")||e.includes("console.")||e.includes(";")||e.includes("{")||e.includes(`
|
|
18
|
+
`)}function Yn(s){let e=s||"",t=e.trim();if(!t||t.length%4!==0||!/^[A-Za-z0-9+/]+={0,2}$/.test(t))return e;try{let n=Buffer.from(t,"base64").toString("utf8");if(!n||n.includes("\uFFFD"))return e;let r=t.replace(/=+$/,""),i=Buffer.from(n,"utf8").toString("base64").replace(/=+$/,"");return r!==i?e:wi(n)?n:e}catch{return e}}function Lr(s,e){let n=ne.relative(e,s).split(ne.sep);if(n.length>=5&&(n[2]===st||n[2]==="api-engine")){let r=n[1],i=r.split(".")[0];if(n.length===5&&n[4]?.endsWith(".js")){let o=n[4].replace(".js",""),a=o.match(/\(([^)]+)\)$/);return a?{serverDir:n[0],osClientDir:r,osClient:i,category:n[3],apiEngineKey:bi(a[1])}:{serverDir:n[0],osClientDir:r,osClient:i,category:n[3],apiEngineKey:o}}if(n.length>=6&&n[5]?.endsWith(".js"))return{serverDir:n[0],osClientDir:r,osClient:i,category:n[3],apiEngineKey:n[5].replace(".js","")}}return null}function Ur(s,e){let n=ne.relative(e,s).split(ne.sep),r=i=>{let o=i.match(/[((]([^))]+)[))]\s*$/);return o?o[1]:i};if(n.length>=6&&n[2]===Le&&n[4]===Zt){let i=n[1],o=i.split(".")[0],a=r(n[3]),c=n[5].replace(/\.js$/i,""),l=r(c);return{serverDir:n[0],osClientDir:i,osClient:o,formEngineKey:a,eventType:l}}if(n.length>=5&&(n[2]===Ar||n[2]==="v8-event"||n[2]==="v8-events")){let i=n[1],o=i.split(".")[0],a=r(n[3]);return{serverDir:n[0],osClientDir:i,osClient:o,formEngineKey:a,eventType:n[4].replace(/\.js$/i,"")}}return null}function Te(s){return(s||new Date).toISOString().replace("T"," ").substring(0,19)}function jr(s,e){let n=ne.relative(e,s).split(ne.sep);if(n.length<7||n[2]!==Le||n[4]!==Et)return null;let r=d=>{let u=d.match(/[((]([^))]+)[))]\s*$/);return u?u[1]:d},i=n[1],o=i.split(".")[0],a=r(n[3]),c=r(n[5]),l=n[6].replace(/\.js$/i,""),p=r(l);return{serverDir:n[0],osClientDir:i,osClient:o,tableName:a,fieldName:c,v8Key:p}}function Kr(s,e){let n=ne.relative(e,s).split(ne.sep);if(n[2]!==Ge)return null;let r=d=>{let u=d.match(/[((]([^))]+)[))]\s*$/);return u?u[1]:d},i=d=>d.replace(/[((][^))]+[))]\s*$/,"").trim()||d,o=n[1],a=o.split(".")[0],c=n.findIndex((d,u)=>u>2&&Object.prototype.hasOwnProperty.call(ot,r(d)));if(c<=3)return null;let l=r(n[c-1]),p=r(n[c]);if(n.length>c+1&&n[c+1].endsWith(".js")){let d=n[c+1].replace(/\.js$/i,""),u=r(d),g=i(d).replace(/_显隐判断$/,"")||i(d),m=d.includes("\u663E\u9690\u5224\u65AD")?"V8CodeShow":"V8Code";return{serverDir:n[0],osClientDir:o,osClient:a,moduleId:l,btnField:p,btnId:u,btnName:g,v8SubField:m}}if(n.length>c+2&&n[c+2].endsWith(".js")){let d=r(n[c+1]),u=i(n[c+1]),g=n[c+2].replace(/\.js$/i,""),m=r(g);return m!=="V8Code"&&m!=="V8CodeShow"?null:{serverDir:n[0],osClientDir:o,osClient:a,moduleId:l,btnField:p,btnId:d,btnName:u,v8SubField:m}}return null}function Hr(s,e){let n=ne.relative(e,s).split(ne.sep),r=n[n.length-1];if(n.length<5||n[2]!==Ge||!r?.endsWith(".js"))return null;let i=l=>{let p=l.match(/[((]([^))]+)[))]\s*$/);return p?p[1]:l},o=i(r.replace(/\.js$/i,""));if(!Object.prototype.hasOwnProperty.call(Tt,o))return null;let a=i(n[n.length-2]);if(!a)return null;let c=n[1];return{serverDir:n[0],osClientDir:c,osClient:c.split(".")[0],moduleId:a,scriptField:o}}function Wr(s){let e=[],t=[{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}];return s.replace(/\r\n/g,`
|
|
19
19
|
`).split(`
|
|
20
|
-
`).forEach((n,r)=>{for(let i of t)if(i.regex.test(n)){e.push({line:r+1,marker:i.label});break}}),e}function Gr(s,e){let n=ne.relative(e,s).split(ne.sep);if(n.length<7||n[2]!==it||n[4]!==en||!n[6]?.endsWith(".js"))return null;let r=p=>{let
|
|
21
|
-
`,"utf-8"),X.renameSync(n,e)}finally{try{X.existsSync(n)&&X.unlinkSync(n)}catch{}}}async mutateWorkspaceConfig(e){let t=this.getWorkspaceConfigPath();if(!t)throw new Error("\u8BF7\u5148\u6253\u5F00\u4E00\u4E2A\u5DE5\u4F5C\u533A");X.mkdirSync(_e.dirname(t),{recursive:!0});let n=`${t}.lock`,r=Date.now()+3e3,i;for(;i===void 0;)try{i=X.openSync(n,"wx",384),X.writeFileSync(i,JSON.stringify({pid:process.pid,createdAt:Date.now()}),"utf-8")}catch(o){if(o.code!=="EEXIST")throw o;try{Date.now()-X.statSync(n).mtimeMs>3e4&&X.unlinkSync(n)}catch{}if(Date.now()>=r)throw new Error("Microi \u914D\u7F6E\u6B63\u5728\u88AB CLI \u6216 VS Code \u63D2\u4EF6\u4FEE\u6539\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");await new Promise(c=>setTimeout(c,40))}try{let o=this.readWorkspaceConfigForUpdate(t),a=this.normalizeSettings(e(o));return this.writeWorkspaceConfig(t,a),this.normalizeSettings(a)}finally{try{X.closeSync(i)}catch{}try{X.unlinkSync(n)}catch{}}}normalizeSettings(e){return{...this.defaultSettings,...e,profiles:Array.isArray(e.profiles)?e.profiles:[],showConsoleOnExecute:e.showConsoleOnExecute??this.defaultSettings.showConsoleOnExecute}}getSettings(){return this.normalizeSettings(this.readWorkspaceConfig())}async updateSettings(e){await this.mutateWorkspaceConfig(t=>({...t,...e}))}getProfiles(){return this.getSettings().profiles}findProfileByIdentity(e,t){let n=this.profileIdentity({apiBaseUrl:e,osClient:t});return this.getProfiles().find(r=>this.profileIdentity(r)===n)}async addProfile(e){await this.upsertProfiles([e])}async upsertProfiles(e){await this.mutateWorkspaceConfig(t=>{let n=Array.isArray(t.profiles)?[...t.profiles]:[];for(let r of e){let i=this.profileIdentity(r),o=n.findIndex(a=>this.profileIdentity(a)===i);if(o>=0){let a=n[o];n[o]={...a,...r,apiBaseUrl:a.apiBaseUrl,osClient:a.osClient}}else n.push(r)}return{...t,profiles:n}})}async removeProfile(e){let t=await this.mutateWorkspaceConfig(n=>{let r=Array.isArray(n.profiles)?[...n.profiles]:[];return r.splice(e,1),{...n,profiles:r}});this._activeProfileIndex>=t.profiles.length&&(this._activeProfileIndex=t.profiles.length-1)}profileIdentity(e){let t=String(e.apiBaseUrl||"").trim().replace(/\/+$/,""),n=t;try{let r=new URL(t);n=`${r.protocol.toLowerCase()}//${r.host.toLowerCase()}${r.pathname.replace(/\/+$/,"")}`}catch{n=t.toLowerCase()}return`${n}|${String(e.osClient||"").trim().toLowerCase()}`}setActiveProfile(e){this._activeProfileIndex=e}get activeProfileIndex(){return this._activeProfileIndex}getActiveProfile(){let e=this.getProfiles();if(this._activeProfileIndex>=0&&this._activeProfileIndex<e.length)return e[this._activeProfileIndex];let t=this.getSettings();return t.apiBaseUrl?{label:"",apiBaseUrl:t.apiBaseUrl,osClient:t.osClient}:e[0]}getWorkspaceRoot(){return kt.workspaceFolders?.[0]?.uri.fsPath}getDefaultSyncRootDir(e){return this.ensureDefaultSyncDirCasing(e),_e.join(e,Ie)}ensureDefaultSyncDirCasing(e){try{if(!X.existsSync(e))return;let t=X.readdirSync(e,{withFileTypes:!0}).filter(a=>a.isDirectory());if(t.some(a=>a.name===Ie))return;let n=t.find(a=>a.name.toLowerCase()===Ie.toLowerCase());if(!n)return;let r=_e.join(e,n.name),i=_e.join(e,Ie),o=_e.join(e,`${Ie}.case-rename-${Date.now()}`);X.renameSync(r,o);try{X.renameSync(o,i)}catch(a){try{X.renameSync(o,r)}catch{}throw a}}catch{this._syncDirCasingWarningShown||(this._syncDirCasingWarningShown=!0,O.warn(`Microi: \u65E0\u6CD5\u5C06\u65E7\u540C\u6B65\u76EE\u5F55\u91CD\u547D\u540D\u4E3A ${Ie}\uFF0C\u8BF7\u5173\u95ED\u6B63\u5728\u5360\u7528 microi-v8-engine \u7684\u6587\u4EF6\u3001\u7EC8\u7AEF\u6216\u6269\u5C55\u7A97\u53E3\u540E\u91CD\u542F VS Code\uFF0C\u6216\u624B\u52A8\u6539\u540D\u3002`))}}getWorkspaceSecretKey(e){let t=this.getWorkspaceRoot()||"no-workspace",n=_e.resolve(t).toLowerCase(),r=Jr.createHash("sha256").update(n).digest("hex").slice(0,16);return`${e}.workspace.${r}`}getSyncRootDir(){let e=this.getSettings();if(e.localDir)return e.localDir;let t=this.getWorkspaceRoot();if(!t)throw new Error("\u8BF7\u5148\u6253\u5F00\u4E00\u4E2A\u5DE5\u4F5C\u533A");return this.getDefaultSyncRootDir(t)}getEngineDir(){return this.getSyncRootDir()}getEventDir(){return this.getSyncRootDir()}buildServerDirName(e,t){let n=t;try{n=new URL(t).host}catch{}return Y(`${e||"\u672A\u547D\u540D"} (${n})`)}buildOsClientDirName(e,t,n){return Y([e||"default",t||"default",n||"default"].join("."))}getApiBaseUrl(){let e=this.getActiveProfile();return e?.apiBaseUrl?e.apiBaseUrl:this.getSettings().apiBaseUrl||""}getOsClient(){let e=this.getActiveProfile();return e?.osClient?e.osClient:this.getSettings().osClient||""}};var tr=B(require("fs")),rs=B(require("crypto")),ss=require("stream"),is=require("stream/promises"),{parser:Mi}=ns();async function os(s,e,t){if(!Number.isSafeInteger(t.size)||t.size<0)throw new Error("\u6E90\u7801\u6587\u4EF6\u5927\u5C0F\u4E0D\u5408\u6CD5");let n=await tr.promises.open(e,"wx",384),r=rs.createHash("sha256"),i=0,o=0,a=0,c="",l="",p=[],u=0,d,g="",m="",f=[],y=()=>{let w=f[f.length-1];return w?`${w.path}${w.path?".":""}${Array.isArray(w.value)?w.value.length:w.key}`:""},S=w=>{let F=f[f.length-1];if(!F){d=w;return}Array.isArray(F.value)?F.value.push(w):(F.value[F.key]=w,F.key=void 0)},h=async()=>{let w=Buffer.concat(p,u);p=[],u=0;for(let F=0;F<w.length;){let M=await n.write(w,F,w.length-F);if(!M.bytesWritten)throw new Error("\u6E90\u7801\u4E34\u65F6\u6587\u4EF6\u5199\u5165\u5931\u8D25");F+=M.bytesWritten}},C=async w=>{if(i+=w.length,i>t.size)throw new Error(`\u6E90\u7801\u5927\u5C0F\u8D85\u8FC7\u6E05\u5355\uFF1A${t.relativePath}`);r.update(w),p.push(w),u+=w.length,u>=64*1024&&await h()},b="",T=0,k=new ss.Transform({transform(w,F,M){T+=w.length,M(T>t.size*8+4*1024*1024?new Error("\u6E90\u7801\u54CD\u5E94\u8D85\u8FC7\u6E05\u5355\u4F20\u8F93\u9884\u7B97"):null,w)}}),I=Mi({packStrings:!1,streamStrings:!0,packKeys:!1,streamKeys:!0,packNumbers:!0,streamNumbers:!1});try{await(0,is.pipeline)(s,k,I,async D=>{for await(let x of D)switch(x.name){case"startObject":case"startArray":{if(f.length>32)throw new Error("\u6E90\u7801\u54CD\u5E94\u5D4C\u5957\u8FC7\u6DF1");let P=x.name==="startArray"?[]:Object.create(null),_=y();S(P),f.push({value:P,path:_,keys:new Set});break}case"endObject":case"endArray":f.pop();break;case"startKey":b="",g="#key";break;case"stringChunk":{if(g==="#key"){if(b+=x.value,b.length>4096)throw new Error("\u6E90\u7801\u54CD\u5E94\u5B57\u6BB5\u540D\u8FC7\u957F");break}if(!m){if(g.startsWith("Data.Application."))break;if(o+=Buffer.byteLength(x.value),o>1024*1024)throw new Error("\u6E90\u7801\u54CD\u5E94\u5143\u6570\u636E\u8FC7\u5927");c+=x.value;break}let P=l+x.value;if(m==="base64"){if(!/^[A-Za-z0-9+/=]*$/u.test(P))throw new Error("\u6E90\u7801 Base64 \u7F16\u7801\u4E0D\u5408\u6CD5");let _=Math.max(0,Math.floor(P.length/4)*4-4),V=P.slice(0,_);if(V.includes("="))throw new Error("\u6E90\u7801 Base64 padding \u4E0D\u5408\u6CD5");await C(Buffer.from(V,"base64")),l=P.slice(_)}else{let _=P.charCodeAt(P.length-1),V=_>=55296&&_<=56319?P.length-1:P.length;await C(Buffer.from(P.slice(0,V),"utf8")),l=P.slice(V)}break}case"endKey":{let P=f[f.length-1];if(o+=Buffer.byteLength(b),o>1024*1024)throw new Error("\u6E90\u7801\u54CD\u5E94\u5143\u6570\u636E\u8FC7\u5927");if(!P||P.keys.has(b))throw new Error("\u6E90\u7801\u54CD\u5E94\u5305\u542B\u91CD\u590D\u5B57\u6BB5");P.keys.add(b),P.key=b,g="";break}case"startString":if(c="",l="",g=y(),m=g==="Data.File.Content"?"utf8":g==="Data.File.FileByteBase64"?"base64":"",m&&++a>1)throw new Error("\u6E90\u7801\u54CD\u5E94\u5305\u542B\u591A\u4E2A\u5185\u5BB9\u5B57\u6BB5");break;case"endString":if(m==="base64"){let P=Buffer.from(l,"base64");if(P.toString("base64")!==l)throw new Error("\u6E90\u7801 Base64 \u5C3E\u90E8\u4E0D\u5B8C\u6574");await C(P)}else m&&await C(Buffer.from(l,"utf8"));S(m?"":c),m="";break;case"numberValue":S(Number(x.value));break;case"trueValue":S(!0);break;case"falseValue":S(!1);break;case"nullValue":S(null);break}}),await h();let w=d?.Data?.File;if(d?.Code!==1)throw new Error(d?.Msg||"\u8BFB\u53D6\u5E94\u7528\u6E90\u7801\u5931\u8D25");if(!w||w.ContentReadError||w.ContentSkipped||a!==1)throw new Error(w?.ContentReadError||"\u6E90\u7801\u54CD\u5E94\u6CA1\u6709\u5B8C\u6574\u6587\u4EF6\u5185\u5BB9");if(String(w.FilePath||w.Path||w.FileName||"").replace(/\\/g,"/")!==t.relativePath)throw new Error("\u6E90\u7801\u54CD\u5E94\u6587\u4EF6\u8DEF\u5F84\u4E0E\u8BF7\u6C42\u4E0D\u4E00\u81F4");if(i!==t.size)throw new Error(`\u6E90\u7801\u5927\u5C0F\u4E0E\u6E05\u5355\u4E0D\u4E00\u81F4\uFF1A${t.relativePath}`);let F=r.digest("hex"),M=String(w.ContentHash||w.Sha256||w.Hash||"").toLowerCase();if(t.sha256&&F!==t.sha256||M&&F!==M)throw new Error(`\u6E90\u7801 SHA-256 \u6821\u9A8C\u5931\u8D25\uFF1A${t.relativePath}`);return{size:i,sha256:F}}catch(w){throw await n.close(),await tr.promises.unlink(e).catch(()=>{}),w}finally{await n.close().catch(()=>{})}}function cs(s){if(s?.Code===1001||s?.Code===1002)return!0;let e=String(s?.DataAppend?.ReasonCode||"").trim();if(/^(MissingToken|MalformedToken|MissingClaims|TenantMismatch|AuthVersionChanged|JwtExpired|SessionExpired|SessionMissing|TokenReplaced|SignatureMismatch)$/i.test(e))return!0;let t=[s?.Msg,s?.DataAppend?.UserMessage,s?.DataAppend?.AppendMsg].filter(Boolean).join(" ");return/Token签名|Token.*(无效|失效|过期)|登录.*(无效|失效|过期)|invalid\s*token|token\s*invalid|signature\s*mismatch/i.test(t)}function Rt(s){if(!cs(s))return!1;let e=String(s?.DataAppend?.ReasonCode||"").trim();if(/^(InvalidTenant|InvalidOsClient|TenantNotFound|TenantDisabled)$/i.test(e))return!0;let t=[s?.Msg,s?.DataAppend?.UserMessage,s?.DataAppend?.Hint].filter(Boolean).join(" ");return/无效的租户标识|租户不存在|租户.*未启用|invalid\s+(tenant|osclient)|tenant\s+not\s+found|unknown\s+tenant/i.test(t)}function sn(s){return cs(s)&&!Rt(s)}function ls(s){return/^[a-f0-9]{64}$/i.test(String(s||"").trim())}function as(s){try{let t=String(s||"").replace(/^Bearer\s+/i,"").trim().split(".");if(t.length<2)return;let n=t[1].replace(/-/g,"+").replace(/_/g,"/"),r=JSON.parse(Buffer.from(n,"base64").toString("utf-8")),i=Number(r.MicroiTokenIssuedAt??r.iat);return Number.isFinite(i)&&i>0?i:void 0}catch{return}}function ut(s,e,t=!1){let n=String(s||"").trim(),r=String(e||"").trim();if(!n)return r;if(!r||r===n)return n;let i=as(n),o=as(r);return i!==void 0&&o!==void 0&&i!==o?o>i?r:n:i===void 0&&o!==void 0?r:o===void 0&&i!==void 0?n:t?r:n}var rn=class{constructor(){this.inFlight=new Map}async run(e,t){let n=this.inFlight.get(e);if(n)return n;let r=Promise.resolve().then(t);this.inFlight.set(e,r);try{return await r}finally{this.inFlight.get(e)===r&&this.inFlight.delete(e)}}};var us="microi.authTokenMap",Ai=64*1024;function xi(s){return new Promise((e,t)=>{let n=!1,r=()=>{s.removeListener("drain",o),s.removeListener("error",a),s.removeListener("close",c)},i=l=>{n||(n=!0,r(),l())},o=()=>i(e),a=l=>i(()=>t(l)),c=()=>i(()=>t(new Error("\u8BF7\u6C42\u8FDE\u63A5\u5728\u5199\u5165\u5B8C\u6210\u524D\u5173\u95ED")));s.once("drain",o),s.once("error",a),s.once("close",c)})}async function Fi(s,e,t){let n=Buffer.isBuffer(e)?e:Buffer.from(e,"utf8"),r=0;for(;r<n.length;){let i=Math.min(r+Ai,n.length),o=s.write(n.subarray(r,i));r=i,t?.(r),o||await xi(s)}return s.end(),r}var K=class s{constructor(){this._strictTlsHosts=new Set;this._token="";this._tokenMap={};this._authRecoveryGate=new rn}setStrictTlsHosts(e){this._strictTlsHosts=new Set(e.map(t=>t.toLowerCase()))}static getInstance(){return s._instance||(s._instance=new s),s._instance}setSecretStorage(e){this._secretStorage=e}setAuthRecoveryHandler(e){this._authRecoveryHandler=e}setTokenStateChangedHandler(e){this._tokenStateChangedHandler=e}async notifyTokenStateChanged(){if(this._tokenStateChangedHandler)try{await this._tokenStateChangedHandler()}catch{}}getDeviceId(){let e=kt.workspaceFile?.fsPath||kt.workspaceFolders?.map(n=>n.uri.fsPath).sort().join("|")||On.sessionId||"empty-window",t=on.createHash("sha256").update(e.toLowerCase()).digest("hex").slice(0,16);return`VSCode:${On.machineId||"Unknown"}:${t}`}tokenKey(e,t,n,r){return t?[e,t,n||"",r||""].join("|"):e}legacyCompactTokenKey(e,t,n,r){return[e,t,n,r].filter(Boolean).join("|")}legacyTokenScope(e,t){try{let n=e.trim().replace(/\/+$/,"").toLowerCase(),r=String(t||"").trim().toLowerCase(),i=N.getInstance().getProfiles().filter(a=>String(a.apiBaseUrl||"").trim().replace(/\/+$/,"").toLowerCase()===n);return{tenantKeyUnambiguous:i.filter(a=>String(a.osClient||"").trim().toLowerCase()===r).length<=1,apiKeyUnambiguous:i.length<=1}}catch{return{tenantKeyUnambiguous:!0,apiKeyUnambiguous:!0}}}tokenLookupKeys(e,t,n,r){let i=[],o=this.legacyTokenScope(e,t);if(t){let a=this.tokenKey(e,t,n,r),c=this.tokenKey(e,t,"",""),l=this.legacyCompactTokenKey(e,t,n,r);i.push(a),o.tenantKeyUnambiguous&&i.push(c),(l===a||o.tenantKeyUnambiguous)&&i.push(l),n&&o.tenantKeyUnambiguous&&i.push(this.legacyCompactTokenKey(e,t,n)),o.tenantKeyUnambiguous&&i.push(this.legacyCompactTokenKey(e,t))}return(!t||o.apiKeyUnambiguous)&&i.push(e),Array.from(new Set(i))}async persistTokens(){if(!this._secretStorage)return;let e=N.getInstance(),t=e.getWorkspaceSecretKey(zn),n=e.getWorkspaceSecretKey(us);this._token?await this._secretStorage.store(t,this._token):await this._secretStorage.delete(t),Object.keys(this._tokenMap).length>0?await this._secretStorage.store(n,JSON.stringify(this._tokenMap)):await this._secretStorage.delete(n)}async setToken(e,t,n,r,i){this._token=e,t&&(this._tokenMap[this.tokenKey(t,n,r,i)]=e),await this.persistTokens(),await this.notifyTokenStateChanged()}async loadToken(){if(this._token)return this._token;if(this._secretStorage){let e=N.getInstance();this._token=await this._secretStorage.get(e.getWorkspaceSecretKey(zn))||"";try{let t=await this._secretStorage.get(e.getWorkspaceSecretKey(us));t&&(this._tokenMap=JSON.parse(t))}catch{}}return this._token}getTokenForServer(e,t,n,r){let i=this.tokenLookupKeys(e,t,n,r),o="";for(let a of i)t&&a===e||(o=ut(o,this._tokenMap[a]));return o||i.includes(e)&&this._tokenMap[e]||""}getExactTokenForServer(e,t,n,r){return this._tokenMap[this.tokenKey(e,t,n,r)]||""}async adoptTokenFromSharedFile(e,t,n,r,i){await this.adoptTokensFromSharedFile([{token:e,apiBaseUrl:t,osClient:n,osClientType:r,osClientNetwork:i}])}async adoptTokensFromSharedFile(e){let t=0,n=!1;for(let r of e){let i=String(r.token||"").trim();if(!i)continue;let o=this.tokenKey(r.apiBaseUrl,r.osClient,r.osClientType,r.osClientNetwork);this._tokenMap[o]!==i&&(this._tokenMap[o]=i,t+=1,n=!0);let a=ut(this._token,i);a!==this._token&&(this._token=a,n=!0)}return n&&await this.persistTokens(),t}async clearTokenForServer(e,t,n,r,i){let o=!1;for(let a of this.tokenLookupKeys(e,t,n,r))this._tokenMap[a]&&(!i||this._tokenMap[a]===i)&&(delete this._tokenMap[a],o=!0);this._token&&(!i||this._token===i)&&(this._token="",o=!0),o&&(await this.persistTokens(),await this.notifyTokenStateChanged())}async clearToken(){this._token="",this._tokenMap={},await this.persistTokens(),await this.notifyTokenStateChanged()}get hasToken(){return!!this._token||Object.keys(this._tokenMap).length>0}isInvalidRefreshToken(e,t){if(t===401||t===403)return!0;let n=String(e?.DataAppend?.ReasonCode||"");if(/^(MissingToken|MalformedToken|MissingClaims|TenantMismatch|AuthVersionChanged|JwtExpired|SessionExpired|SessionMissing|TokenReplaced)$/i.test(n))return!0;let r=e?.Msg||"";return e?.Code!==1&&/无效.*Token|Token.*无效|Token.*过期|登录.*过期|租户.*不一致|invalid\s*token|token\s*invalid/i.test(r)}serializeRequestBody(e,t){if(t==="form"){let n=new URLSearchParams;if(e&&typeof e=="object"&&!Array.isArray(e))for(let[r,i]of Object.entries(e))i!=null&&n.append(r,typeof i=="object"?JSON.stringify(i):String(i));return n.toString()}return JSON.stringify(e)}maskSensitiveBody(e){if(!e||typeof e!="object")return e;if(Array.isArray(e))return e.map(n=>this.maskSensitiveBody(n));let t={};for(let[n,r]of Object.entries(e))/^(pwd|password|authorization|token)$/i.test(n)?t[n]="***":r&&typeof r=="object"?t[n]=this.maskSensitiveBody(r):t[n]=r;return t}async refreshTokenForRequest(e,t,n){if(!t)return!1;let r=N.getInstance(),i=e.osClient||r.getOsClient()||"",o=new URL(n),c=o.pathname.replace(/\/+$/,"")+H.REFRESH_TOKEN,l=o.protocol==="https:",p=l?It:Nt,u=JSON.stringify({authorization:t,OsClient:i||void 0,_ClientType:"VSCode"}),d={hostname:o.hostname,port:o.port||(l?443:80),path:c,method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",Authorization:`Bearer ${t}`,did:this.getDeviceId(),"Content-Length":Buffer.byteLength(u),...i?{OsClient:i}:{}},timeout:e.timeout||3e4,rejectUnauthorized:this._strictTlsHosts.has(o.hostname.toLowerCase())};return ce.log("API",`\u{1F504} RefreshToken ${n}${c}`),new Promise(g=>{let m=p.request(d,f=>{let y=[];f.on("data",S=>y.push(S)),f.on("end",async()=>{let S=Buffer.concat(y).toString("utf-8"),h;try{h=JSON.parse(S)}catch{}let C=f.headers,b=f.statusCode||0,T=C.authorization||"";if(h?.Code===1&&T){await this.setToken(T,e.apiBaseUrl||n,e.osClient,e.osClientType,e.osClientNetwork),ce.log("API","\u2705 Token \u5DF2\u4EE5\u65E7\u6362\u65B0"),g(!0);return}this.isInvalidRefreshToken(h,b)&&await this.clearTokenForServer(e.apiBaseUrl||n,e.osClient,e.osClientType,e.osClientNetwork,t),ce.log("API",`\u26A0\uFE0F RefreshToken \u5931\u8D25: ${h?.Msg||S.slice(0,120)}`),g(!1)})});m.on("error",f=>{ce.log("API",`\u274C RefreshToken Error: ${f.message}`),g(!1)}),m.on("timeout",()=>{m.destroy(),g(!1)}),m.write(u),m.end()})}async recoverAuthForRequest(e,t){if(!this._authRecoveryHandler)return!1;let n=N.getInstance(),r={apiBaseUrl:e.apiBaseUrl||t,osClient:e.osClient||n.getOsClient()||void 0,osClientType:e.osClientType,osClientNetwork:e.osClientNetwork},i=this.tokenKey(r.apiBaseUrl,r.osClient,r.osClientType,r.osClientNetwork);return this._authRecoveryGate.run(i,()=>this._authRecoveryHandler(r))}async request(e){let t=N.getInstance(),n=e.apiBaseUrl||t.getApiBaseUrl();if(!n)throw new Error('\u672A\u914D\u7F6E API \u5730\u5740\uFF0C\u8BF7\u5148\u6267\u884C "Microi: \u914D\u7F6E\u8FDE\u63A5"');let r=new URL(n),o=r.pathname.replace(/\/+$/,"")+e.path;if(e.params){let y=new URLSearchParams;for(let[h,C]of Object.entries(e.params))C!==void 0&&C!==""&&y.append(h,C);let S=y.toString();S&&(o+=`?${S}`)}let a=r.protocol==="https:",c=a?It:Nt,l=e.bodyFormat||"json",p=e.body!==void 0?this.serializeRequestBody(e.body,l):void 0,u={hostname:r.hostname,port:r.port||(a?443:80),path:o,method:e.method,headers:{"Content-Type":l==="form"?"application/x-www-form-urlencoded":"application/json",Accept:"application/json",did:this.getDeviceId()},timeout:e.timeout||3e4,rejectUnauthorized:this._strictTlsHosts.has(r.hostname.toLowerCase())};p!==void 0&&(u.headers["Content-Length"]=Buffer.byteLength(p));let d=e.allowAuthRetry!==!1,g=e.osClient||t.getOsClient()||"";g&&(u.headers.OsClient=g);let m=e.apiBaseUrl?this.getTokenForServer(e.apiBaseUrl,e.osClient,e.osClientType,e.osClientNetwork):await this.loadToken();m&&(u.headers.Authorization=`Bearer ${m}`);let f=`${n}${o}`;if(e.silent||ce.log("API",`\u27A1\uFE0F ${e.method} ${f}`),e.body&&!e.silent){let y=JSON.stringify(this.maskSensitiveBody(e.body));ce.appendLine(` Body: ${y.length>500?y.substring(0,500)+"...(truncated)":y}`)}return new Promise((y,S)=>{let h=p===void 0?0:Buffer.byteLength(p),C=0,b=c.request(u,k=>{let I=[];k.on("data",w=>I.push(w)),k.on("end",async()=>{let w=Buffer.concat(I).toString("utf-8"),F=k.statusCode||0;if(!e.silent){ce.log("API",`\u2B05\uFE0F ${F} ${e.method} ${e.path}`);let D=w.length>500?w.substring(0,500)+"...(truncated)":w;ce.appendLine(` Response: ${D}`)}let M;try{M=JSON.parse(w)}catch{}if(M){let D={};for(let[P,_]of Object.entries(k.headers))typeof _=="string"&&(D[P.toLowerCase()]=_);M._headers=D;let x=D.authorization||"";if(x&&x!==m&&await this.setToken(x,e.apiBaseUrl||n,e.osClient,e.osClientType,e.osClientNetwork),d&&Rt(M))ce.log("API",`\u26A0\uFE0F \u79DF\u6237\u8FDE\u63A5\u914D\u7F6E\u65E0\u6548\uFF0C\u5DF2\u505C\u6B62 token \u5237\u65B0\u4E0E\u9759\u9ED8\u91CD\u767B: ${M.Msg||""}`);else if(d&&sn(M)&&(ce.log("API",`\u{1F510} \u8EAB\u4EFD\u5DF2\u8FC7\u671F\uFF0C\u5C1D\u8BD5\u4F7F\u7528\u65E7 token \u5237\u65B0\u540E\u91CD\u8BD5: ${M.Msg||""}`),await this.refreshTokenForRequest(e,m,n)||await this.recoverAuthForRequest(e,n))){try{y(await this.request({...e,allowAuthRetry:!1}))}catch(V){S(V)}return}y(M)}else if(F===401||F===403){if(d&&(await this.refreshTokenForRequest(e,m,n)||await this.recoverAuthForRequest(e,n))){try{y(await this.request({...e,allowAuthRetry:!1}))}catch(P){S(P)}return}S(new Error(`\u8EAB\u4EFD\u9A8C\u8BC1\u5931\u8D25 (HTTP ${F})\uFF0C\u8BF7\u91CD\u65B0\u767B\u5F55`))}else if(F>=400){let D=w.replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim().substring(0,120);S(new Error(`\u670D\u52A1\u5668\u9519\u8BEF (HTTP ${F}): ${D||"\u672A\u77E5\u9519\u8BEF"}`))}else S(new Error(`\u54CD\u5E94\u89E3\u6790\u5931\u8D25 (HTTP ${F}): ${w.substring(0,200)}`))})}),T=!1;b.on("error",k=>{if(T)return;let I=Dt(k),w=h>0?`\uFF1B\u8BF7\u6C42\u4F53\u5DF2\u5206\u7247\u6392\u961F ${C}/${h} bytes\uFF0C\u670D\u52A1\u7AEF\u662F\u5426\u5DF2\u63D0\u4EA4\u672A\u77E5\uFF0C\u63D2\u4EF6\u4E0D\u4F1A\u76F2\u76EE\u91CD\u653E\u975E\u5E42\u7B49\u8BF7\u6C42`:"";e.silent||ce.log("API",`\u274C ${e.method} ${e.path} Error: ${I}${w}`),S(new Error(`\u8BF7\u6C42\u5931\u8D25: ${I}${w}`))}),b.on("timeout",()=>{T=!0,b.destroy(),e.silent||ce.log("API",`\u23F0 ${e.method} ${e.path} Timeout`),S(new Error("\u8BF7\u6C42\u8D85\u65F6"))}),p!==void 0?Fi(b,p,k=>{C=k}).catch(k=>{!T&&!b.destroyed&&b.destroy(k instanceof Error?k:new Error(String(k)))}):b.end()})}async get(e,t,n,r){return this.request({method:"GET",path:e,params:t,apiBaseUrl:n,osClient:r?.osClient,osClientType:r?.osClientType,osClientNetwork:r?.osClientNetwork})}async post(e,t,n,r,i,o,a){return this.request({method:"POST",path:e,body:t,params:n,apiBaseUrl:r,osClient:i?.osClient,osClientType:i?.osClientType,osClientNetwork:i?.osClientNetwork,timeout:o,silent:a})}async downloadApplicationSourceFile(e,t,n,r,i){let o=new URL(r);if(!["http:","https:"].includes(o.protocol)||o.username||o.password)throw new Error("\u6E90\u7801 API \u5730\u5740\u4E0D\u5408\u6CD5");let a=this.getTokenForServer(r,i.osClient,i.osClientType,i.osClientNetwork),c=JSON.stringify({OsClient:i.osClient,AppIdOrKey:e,FilePath:t.relativePath,IncludeContents:!0,MaxFileBytes:Math.max(1,t.size)});return new Promise((l,p)=>{let u=(o.protocol==="https:"?It:Nt).request({hostname:o.hostname,port:o.port||(o.protocol==="https:"?443:80),path:o.pathname.replace(/\/+$/,"")+H.GET_APPLICATION_FILE,method:"POST",rejectUnauthorized:this._strictTlsHosts.has(o.hostname.toLowerCase()),headers:{"Content-Type":"application/json",Accept:"application/json","Content-Length":Buffer.byteLength(c),did:this.getDeviceId(),...a?{Authorization:`Bearer ${a}`}:{},...i.osClient?{OsClient:i.osClient}:{}}},g=>{if(g.statusCode!==200){g.destroy(),p(new Error(`\u6E90\u7801\u4E0B\u8F7D\u5931\u8D25\uFF1AHTTP ${g.statusCode}`));return}os(g,n,t).then(l,p)}),d=setTimeout(()=>u.destroy(new Error("\u6E90\u7801\u4E0B\u8F7D\u8D85\u65F6")),5*60*1e3);u.once("close",()=>clearTimeout(d)),u.once("error",p),u.end(c)})}async getRaw(e,t,n){let r=N.getInstance(),i=n||r.getApiBaseUrl();if(!i)throw new Error("\u672A\u914D\u7F6E API \u5730\u5740");let o=new URL(i),c=o.pathname.replace(/\/+$/,"")+e;if(t){let d=new URLSearchParams;for(let[m,f]of Object.entries(t))f!==void 0&&f!==""&&d.append(m,f);let g=d.toString();g&&(c+=`?${g}`)}let l=o.protocol==="https:",p=l?It:Nt,u={hostname:o.hostname,port:o.port||(l?443:80),path:c,method:"GET",timeout:15e3,rejectUnauthorized:this._strictTlsHosts.has(o.hostname.toLowerCase())};return new Promise((d,g)=>{let m=p.request(u,f=>{let y=[];f.on("data",S=>y.push(S)),f.on("end",()=>{let S=Buffer.concat(y),h=f.headers.captchaid||"";d({data:S,captchaId:h,statusCode:f.statusCode||0,contentType:String(f.headers["content-type"]||"")})})});m.on("error",f=>g(new Error(`\u8BF7\u6C42\u5931\u8D25: ${f.message}`))),m.on("timeout",()=>{m.destroy(),g(new Error("\u8BF7\u6C42\u8D85\u65F6"))}),m.end()})}async postMultipartFile(e,t,n,r,i,o,a=30*60*1e3){let c=dt.realpathSync(n),l=dt.lstatSync(c);if(!l.isFile()||l.isSymbolicLink())throw new Error(`\u4E0A\u4F20\u8D44\u4EA7\u5FC5\u987B\u662F\u666E\u901A\u6587\u4EF6\u4E14\u4E0D\u80FD\u662F\u7B26\u53F7\u94FE\u63A5\uFF1A${n}`);if(!r||/[\r\n"]/u.test(r))throw new Error("\u4E0A\u4F20\u6587\u4EF6\u540D\u4E0D\u5408\u6CD5");let p=String(i||"").replace(/\/+$/,""),u=new URL(p),d=`----microi-vscode-${on.randomBytes(24).toString("hex")}`,g=Object.entries(t).map(([k,I])=>Buffer.from(`--${d}\r
|
|
22
|
-
Content-Disposition: form-data; name="${
|
|
20
|
+
`).forEach((n,r)=>{for(let i of t)if(i.regex.test(n)){e.push({line:r+1,marker:i.label});break}}),e}function Gr(s,e){let n=ne.relative(e,s).split(ne.sep);if(n.length<7||n[2]!==it||n[4]!==en||!n[6]?.endsWith(".js"))return null;let r=p=>{let d=p.match(/[((]([^))]+)[))]\s*$/);return d?d[1]:p},i=n[1],o=i.split(".")[0],a=r(n[3]),c=r(n[5]),l=r(n[6].replace(/\.js$/i,""));return{serverDir:n[0],osClientDir:i,osClient:o,flowDesignId:a,nodeId:c,eventType:l}}function Pt(s){return String(s).padStart(2,"0")}function zr(s=new Date){return`${s.getFullYear()}-${Pt(s.getMonth()+1)}-${Pt(s.getDate())} ${Pt(s.getHours())}:${Pt(s.getMinutes())}:${Pt(s.getSeconds())}`}function Je(s,e,t){let n=String(t??"").trim();!n||e.has(n)||(e.add(n),s.push(n))}function Dt(s){if(typeof s=="string")return s.trim()||"\u672A\u77E5\u9519\u8BEF";if(!s||typeof s!="object")return String(s??"\u672A\u77E5\u9519\u8BEF");let e=s,t=[],n=new Set;return Je(t,n,e.message),Je(t,n,e.code),Je(t,n,e.syscall),e.address&&Je(t,n,`address=${e.address}`),e.port!==void 0&&e.port!==null&&e.port!==""&&Je(t,n,`port=${e.port}`),(Array.isArray(e.errors)?e.errors:[]).forEach(i=>Je(t,n,Dt(i))),t.length||Je(t,n,e.name),t.join(" | ")||"\u672A\u77E5\u9519\u8BEF"}var ce=class s{static init(){s._channel||(s._channel=Se.createOutputChannel("Microi \u543E\u7801"))}static get channel(){return s._channel}static log(e,t){s.init();let n=zr();s._channel.appendLine(`[${n}] [${e}] ${t}`)}static appendLine(e){s.init(),s._channel.appendLine(e)}static show(e){s._channel.show(e)}static dispose(){s._channel?.dispose()}};function ki(s){return typeof s=="string"?s:s&&typeof s=="object"&&"title"in s?String(s.title||""):""}function Qn(s,e){return s.then(t=>{let n=ki(t);return n&&ce.log("\u901A\u77E5/\u64CD\u4F5C",`${e}\u901A\u77E5\u9009\u62E9\uFF1A${n}`),t})}var F=class{static info(e,...t){return ce.log("\u901A\u77E5/\u4FE1\u606F",e),Qn(Se.showInformationMessage(e,...t),"\u4FE1\u606F")}static warn(e,...t){return ce.log("\u901A\u77E5/\u8B66\u544A",e),Qn(Se.showWarningMessage(e,...t),"\u8B66\u544A")}static error(e,...t){return ce.log("\u901A\u77E5/\u9519\u8BEF",e),Qn(Se.showErrorMessage(e,...t),"\u9519\u8BEF")}};var N=class s{constructor(){this._activeProfileIndex=-1;this._syncDirCasingWarningShown=!1;this.defaultSettings={apiBaseUrl:"",osClient:"",localDir:"",showConsoleOnExecute:!0,profiles:[]}}static getInstance(){return s._instance||(s._instance=new s),s._instance}getWorkspaceConfigPath(){let e=this.getWorkspaceRoot();if(e)return _e.join(this.getDefaultSyncRootDir(e),Xt)}getWorkspaceStateFilePath(e){let t=this.getWorkspaceRoot();if(!t)throw new Error("\u8BF7\u5148\u6253\u5F00\u4E00\u4E2A\u5DE5\u4F5C\u533A");return _e.join(this.getDefaultSyncRootDir(t),e)}readWorkspaceConfig(){let e=this.getWorkspaceConfigPath();if(!e||!Z.existsSync(e))return{};try{let t=JSON.parse(Z.readFileSync(e,"utf-8"));return t&&typeof t=="object"?t:{}}catch{return{}}}readWorkspaceConfigForUpdate(e){if(!Z.existsSync(e))return{};let t;try{t=JSON.parse(Z.readFileSync(e,"utf-8"))}catch(n){throw new Error(`Microi \u914D\u7F6E\u6587\u4EF6\u65E0\u6CD5\u89E3\u6790\uFF0C\u5DF2\u4FDD\u7559\u539F\u6587\u4EF6\u5E76\u505C\u6B62\u5199\u5165\uFF1A${e}\uFF08${n instanceof Error?n.message:String(n)}\uFF09`)}if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`Microi \u914D\u7F6E\u6587\u4EF6\u5FC5\u987B\u662F JSON \u5BF9\u8C61\uFF0C\u5DF2\u4FDD\u7559\u539F\u6587\u4EF6\u5E76\u505C\u6B62\u5199\u5165\uFF1A${e}`);return t}writeWorkspaceConfig(e,t){Z.mkdirSync(_e.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${Date.now()}.tmp`;try{Z.writeFileSync(n,`${JSON.stringify(t,null,2)}
|
|
21
|
+
`,"utf-8"),Z.renameSync(n,e)}finally{try{Z.existsSync(n)&&Z.unlinkSync(n)}catch{}}}async mutateWorkspaceConfig(e){let t=this.getWorkspaceConfigPath();if(!t)throw new Error("\u8BF7\u5148\u6253\u5F00\u4E00\u4E2A\u5DE5\u4F5C\u533A");Z.mkdirSync(_e.dirname(t),{recursive:!0});let n=`${t}.lock`,r=Date.now()+3e3,i;for(;i===void 0;)try{i=Z.openSync(n,"wx",384),Z.writeFileSync(i,JSON.stringify({pid:process.pid,createdAt:Date.now()}),"utf-8")}catch(o){if(o.code!=="EEXIST")throw o;try{Date.now()-Z.statSync(n).mtimeMs>3e4&&Z.unlinkSync(n)}catch{}if(Date.now()>=r)throw new Error("Microi \u914D\u7F6E\u6B63\u5728\u88AB CLI \u6216 VS Code \u63D2\u4EF6\u4FEE\u6539\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");await new Promise(c=>setTimeout(c,40))}try{let o=this.readWorkspaceConfigForUpdate(t),a=this.normalizeSettings(e(o));return this.writeWorkspaceConfig(t,a),this.normalizeSettings(a)}finally{try{Z.closeSync(i)}catch{}try{Z.unlinkSync(n)}catch{}}}normalizeSettings(e){return{...this.defaultSettings,...e,profiles:Array.isArray(e.profiles)?e.profiles:[],showConsoleOnExecute:e.showConsoleOnExecute??this.defaultSettings.showConsoleOnExecute}}getSettings(){return this.normalizeSettings(this.readWorkspaceConfig())}async updateSettings(e){await this.mutateWorkspaceConfig(t=>({...t,...e}))}getProfiles(){return this.getSettings().profiles}findProfileByIdentity(e,t){let n=this.profileIdentity({apiBaseUrl:e,osClient:t});return this.getProfiles().find(r=>this.profileIdentity(r)===n)}async addProfile(e){await this.upsertProfiles([e])}async upsertProfiles(e){await this.mutateWorkspaceConfig(t=>{let n=Array.isArray(t.profiles)?[...t.profiles]:[];for(let r of e){let i=this.profileIdentity(r),o=n.findIndex(a=>this.profileIdentity(a)===i);if(o>=0){let a=n[o];n[o]={...a,...r,apiBaseUrl:a.apiBaseUrl,osClient:a.osClient}}else n.push(r)}return{...t,profiles:n}})}async removeProfile(e){let t=await this.mutateWorkspaceConfig(n=>{let r=Array.isArray(n.profiles)?[...n.profiles]:[];return r.splice(e,1),{...n,profiles:r}});this._activeProfileIndex>=t.profiles.length&&(this._activeProfileIndex=t.profiles.length-1)}profileIdentity(e){let t=String(e.apiBaseUrl||"").trim().replace(/\/+$/,""),n=t;try{let r=new URL(t);n=`${r.protocol.toLowerCase()}//${r.host.toLowerCase()}${r.pathname.replace(/\/+$/,"")}`}catch{n=t.toLowerCase()}return`${n}|${String(e.osClient||"").trim().toLowerCase()}`}setActiveProfile(e){this._activeProfileIndex=e}get activeProfileIndex(){return this._activeProfileIndex}getActiveProfile(){let e=this.getProfiles();if(this._activeProfileIndex>=0&&this._activeProfileIndex<e.length)return e[this._activeProfileIndex];let t=this.getSettings();return t.apiBaseUrl?{label:"",apiBaseUrl:t.apiBaseUrl,osClient:t.osClient}:e[0]}getWorkspaceRoot(){return kt.workspaceFolders?.[0]?.uri.fsPath}getDefaultSyncRootDir(e){return this.ensureDefaultSyncDirCasing(e),_e.join(e,Re)}ensureDefaultSyncDirCasing(e){try{if(!Z.existsSync(e))return;let t=Z.readdirSync(e,{withFileTypes:!0}).filter(a=>a.isDirectory());if(t.some(a=>a.name===Re))return;let n=t.find(a=>a.name.toLowerCase()===Re.toLowerCase());if(!n)return;let r=_e.join(e,n.name),i=_e.join(e,Re),o=_e.join(e,`${Re}.case-rename-${Date.now()}`);Z.renameSync(r,o);try{Z.renameSync(o,i)}catch(a){try{Z.renameSync(o,r)}catch{}throw a}}catch{this._syncDirCasingWarningShown||(this._syncDirCasingWarningShown=!0,F.warn(`Microi: \u65E0\u6CD5\u5C06\u65E7\u540C\u6B65\u76EE\u5F55\u91CD\u547D\u540D\u4E3A ${Re}\uFF0C\u8BF7\u5173\u95ED\u6B63\u5728\u5360\u7528 microi-v8-engine \u7684\u6587\u4EF6\u3001\u7EC8\u7AEF\u6216\u6269\u5C55\u7A97\u53E3\u540E\u91CD\u542F VS Code\uFF0C\u6216\u624B\u52A8\u6539\u540D\u3002`))}}getWorkspaceSecretKey(e){let t=this.getWorkspaceRoot()||"no-workspace",n=_e.resolve(t).toLowerCase(),r=Jr.createHash("sha256").update(n).digest("hex").slice(0,16);return`${e}.workspace.${r}`}getSyncRootDir(){let e=this.getSettings();if(e.localDir)return e.localDir;let t=this.getWorkspaceRoot();if(!t)throw new Error("\u8BF7\u5148\u6253\u5F00\u4E00\u4E2A\u5DE5\u4F5C\u533A");return this.getDefaultSyncRootDir(t)}getEngineDir(){return this.getSyncRootDir()}getEventDir(){return this.getSyncRootDir()}buildServerDirName(e,t){let n=t;try{n=new URL(t).host}catch{}return X(`${e||"\u672A\u547D\u540D"} (${n})`)}buildOsClientDirName(e,t,n){return X([e||"default",t||"default",n||"default"].join("."))}getApiBaseUrl(){let e=this.getActiveProfile();return e?.apiBaseUrl?e.apiBaseUrl:this.getSettings().apiBaseUrl||""}getOsClient(){let e=this.getActiveProfile();return e?.osClient?e.osClient:this.getSettings().osClient||""}};var tr=B(require("fs")),rs=B(require("crypto")),ss=require("stream"),is=require("stream/promises"),{parser:Ai}=ns();async function os(s,e,t){if(!Number.isSafeInteger(t.size)||t.size<0)throw new Error("\u6E90\u7801\u6587\u4EF6\u5927\u5C0F\u4E0D\u5408\u6CD5");let n=await tr.promises.open(e,"wx",384),r=rs.createHash("sha256"),i=0,o=0,a=0,c="",l="",p=[],d=0,u,g="",m="",f=[],y=()=>{let w=f[f.length-1];return w?`${w.path}${w.path?".":""}${Array.isArray(w.value)?w.value.length:w.key}`:""},C=w=>{let O=f[f.length-1];if(!O){u=w;return}Array.isArray(O.value)?O.value.push(w):(O.value[O.key]=w,O.key=void 0)},h=async()=>{let w=Buffer.concat(p,d);p=[],d=0;for(let O=0;O<w.length;){let A=await n.write(w,O,w.length-O);if(!A.bytesWritten)throw new Error("\u6E90\u7801\u4E34\u65F6\u6587\u4EF6\u5199\u5165\u5931\u8D25");O+=A.bytesWritten}},S=async w=>{if(i+=w.length,i>t.size)throw new Error(`\u6E90\u7801\u5927\u5C0F\u8D85\u8FC7\u6E05\u5355\uFF1A${t.relativePath}`);r.update(w),p.push(w),d+=w.length,d>=64*1024&&await h()},b="",E=0,k=new ss.Transform({transform(w,O,A){E+=w.length,A(E>t.size*8+4*1024*1024?new Error("\u6E90\u7801\u54CD\u5E94\u8D85\u8FC7\u6E05\u5355\u4F20\u8F93\u9884\u7B97"):null,w)}}),I=Ai({packStrings:!1,streamStrings:!0,packKeys:!1,streamKeys:!0,packNumbers:!0,streamNumbers:!1});try{await(0,is.pipeline)(s,k,I,async D=>{for await(let $ of D)switch($.name){case"startObject":case"startArray":{if(f.length>32)throw new Error("\u6E90\u7801\u54CD\u5E94\u5D4C\u5957\u8FC7\u6DF1");let T=$.name==="startArray"?[]:Object.create(null),P=y();C(T),f.push({value:T,path:P,keys:new Set});break}case"endObject":case"endArray":f.pop();break;case"startKey":b="",g="#key";break;case"stringChunk":{if(g==="#key"){if(b+=$.value,b.length>4096)throw new Error("\u6E90\u7801\u54CD\u5E94\u5B57\u6BB5\u540D\u8FC7\u957F");break}if(!m){if(g.startsWith("Data.Application."))break;if(o+=Buffer.byteLength($.value),o>1024*1024)throw new Error("\u6E90\u7801\u54CD\u5E94\u5143\u6570\u636E\u8FC7\u5927");c+=$.value;break}let T=l+$.value;if(m==="base64"){if(!/^[A-Za-z0-9+/=]*$/u.test(T))throw new Error("\u6E90\u7801 Base64 \u7F16\u7801\u4E0D\u5408\u6CD5");let P=Math.max(0,Math.floor(T.length/4)*4-4),M=T.slice(0,P);if(M.includes("="))throw new Error("\u6E90\u7801 Base64 padding \u4E0D\u5408\u6CD5");await S(Buffer.from(M,"base64")),l=T.slice(P)}else{let P=T.charCodeAt(T.length-1),M=P>=55296&&P<=56319?T.length-1:T.length;await S(Buffer.from(T.slice(0,M),"utf8")),l=T.slice(M)}break}case"endKey":{let T=f[f.length-1];if(o+=Buffer.byteLength(b),o>1024*1024)throw new Error("\u6E90\u7801\u54CD\u5E94\u5143\u6570\u636E\u8FC7\u5927");if(!T||T.keys.has(b))throw new Error("\u6E90\u7801\u54CD\u5E94\u5305\u542B\u91CD\u590D\u5B57\u6BB5");T.keys.add(b),T.key=b,g="";break}case"startString":if(c="",l="",g=y(),m=g==="Data.File.Content"?"utf8":g==="Data.File.FileByteBase64"?"base64":"",m&&++a>1)throw new Error("\u6E90\u7801\u54CD\u5E94\u5305\u542B\u591A\u4E2A\u5185\u5BB9\u5B57\u6BB5");break;case"endString":if(m==="base64"){let T=Buffer.from(l,"base64");if(T.toString("base64")!==l)throw new Error("\u6E90\u7801 Base64 \u5C3E\u90E8\u4E0D\u5B8C\u6574");await S(T)}else m&&await S(Buffer.from(l,"utf8"));C(m?"":c),m="";break;case"numberValue":C(Number($.value));break;case"trueValue":C(!0);break;case"falseValue":C(!1);break;case"nullValue":C(null);break}}),await h();let w=u?.Data?.File;if(u?.Code!==1)throw new Error(u?.Msg||"\u8BFB\u53D6\u5E94\u7528\u6E90\u7801\u5931\u8D25");if(!w||w.ContentReadError||w.ContentSkipped||a!==1)throw new Error(w?.ContentReadError||"\u6E90\u7801\u54CD\u5E94\u6CA1\u6709\u5B8C\u6574\u6587\u4EF6\u5185\u5BB9");if(String(w.FilePath||w.Path||w.FileName||"").replace(/\\/g,"/")!==t.relativePath)throw new Error("\u6E90\u7801\u54CD\u5E94\u6587\u4EF6\u8DEF\u5F84\u4E0E\u8BF7\u6C42\u4E0D\u4E00\u81F4");if(i!==t.size)throw new Error(`\u6E90\u7801\u5927\u5C0F\u4E0E\u6E05\u5355\u4E0D\u4E00\u81F4\uFF1A${t.relativePath}`);let O=r.digest("hex"),A=String(w.ContentHash||w.Sha256||w.Hash||"").toLowerCase();if(t.sha256&&O!==t.sha256||A&&O!==A)throw new Error(`\u6E90\u7801 SHA-256 \u6821\u9A8C\u5931\u8D25\uFF1A${t.relativePath}`);return{size:i,sha256:O}}catch(w){throw await n.close(),await tr.promises.unlink(e).catch(()=>{}),w}finally{await n.close().catch(()=>{})}}function cs(s){if(s?.Code===1001||s?.Code===1002)return!0;let e=String(s?.DataAppend?.ReasonCode||"").trim();if(/^(MissingToken|MalformedToken|MissingClaims|TenantMismatch|AuthVersionChanged|JwtExpired|SessionExpired|SessionMissing|TokenReplaced|SignatureMismatch)$/i.test(e))return!0;let t=[s?.Msg,s?.DataAppend?.UserMessage,s?.DataAppend?.AppendMsg].filter(Boolean).join(" ");return/Token签名|Token.*(无效|失效|过期)|登录.*(无效|失效|过期)|invalid\s*token|token\s*invalid|signature\s*mismatch/i.test(t)}function It(s){if(!cs(s))return!1;let e=String(s?.DataAppend?.ReasonCode||"").trim();if(/^(InvalidTenant|InvalidOsClient|TenantNotFound|TenantDisabled)$/i.test(e))return!0;let t=[s?.Msg,s?.DataAppend?.UserMessage,s?.DataAppend?.Hint].filter(Boolean).join(" ");return/无效的租户标识|租户不存在|租户.*未启用|invalid\s+(tenant|osclient)|tenant\s+not\s+found|unknown\s+tenant/i.test(t)}function sn(s){return cs(s)&&!It(s)}function ls(s){return/^[a-f0-9]{64}$/i.test(String(s||"").trim())}function as(s){try{let t=String(s||"").replace(/^Bearer\s+/i,"").trim().split(".");if(t.length<2)return;let n=t[1].replace(/-/g,"+").replace(/_/g,"/"),r=JSON.parse(Buffer.from(n,"base64").toString("utf-8")),i=Number(r.MicroiTokenIssuedAt??r.iat);return Number.isFinite(i)&&i>0?i:void 0}catch{return}}function ut(s,e,t=!1){let n=String(s||"").trim(),r=String(e||"").trim();if(!n)return r;if(!r||r===n)return n;let i=as(n),o=as(r);return i!==void 0&&o!==void 0&&i!==o?o>i?r:n:i===void 0&&o!==void 0?r:o===void 0&&i!==void 0?n:t?r:n}var rn=class{constructor(){this.inFlight=new Map}async run(e,t){let n=this.inFlight.get(e);if(n)return n;let r=Promise.resolve().then(t);this.inFlight.set(e,r);try{return await r}finally{this.inFlight.get(e)===r&&this.inFlight.delete(e)}}};var us="microi.authTokenMap",Mi=64*1024;function xi(s){return new Promise((e,t)=>{let n=!1,r=()=>{s.removeListener("drain",o),s.removeListener("error",a),s.removeListener("close",c)},i=l=>{n||(n=!0,r(),l())},o=()=>i(e),a=l=>i(()=>t(l)),c=()=>i(()=>t(new Error("\u8BF7\u6C42\u8FDE\u63A5\u5728\u5199\u5165\u5B8C\u6210\u524D\u5173\u95ED")));s.once("drain",o),s.once("error",a),s.once("close",c)})}async function Fi(s,e,t){let n=Buffer.isBuffer(e)?e:Buffer.from(e,"utf8"),r=0;for(;r<n.length;){let i=Math.min(r+Mi,n.length),o=s.write(n.subarray(r,i));r=i,t?.(r),o||await xi(s)}return s.end(),r}var L=class s{constructor(){this._strictTlsHosts=new Set;this._token="";this._tokenMap={};this._tokenPersistence=Promise.resolve();this._authRecoveryGate=new rn}setStrictTlsHosts(e){this._strictTlsHosts=new Set(e.map(t=>t.toLowerCase()))}static getInstance(){return s._instance||(s._instance=new s),s._instance}setSecretStorage(e){this._secretStorage=e}setAuthRecoveryHandler(e){this._authRecoveryHandler=e}setResponseTokenAdmission(e){this._responseTokenAdmission=e}captureResponseTokenCommit(e){return this._responseTokenAdmission?.(e)||{current:()=>!0,commit:async t=>(await this.setToken(t,e.apiBaseUrl,e.osClient,e.osClientType,e.osClientNetwork),!0)}}setTokenStateChangedHandler(e){this._tokenStateChangedHandler=e}async notifyTokenStateChanged(){if(this._tokenStateChangedHandler)try{await this._tokenStateChangedHandler()}catch{}}getDeviceId(){let e=kt.workspaceFile?.fsPath||kt.workspaceFolders?.map(n=>n.uri.fsPath).sort().join("|")||On.sessionId||"empty-window",t=on.createHash("sha256").update(e.toLowerCase()).digest("hex").slice(0,16);return`VSCode:${On.machineId||"Unknown"}:${t}`}tokenKey(e,t,n,r){return t?[e,t,n||"",r||""].join("|"):e}legacyCompactTokenKey(e,t,n,r){return[e,t,n,r].filter(Boolean).join("|")}legacyTokenScope(e,t){try{let n=e.trim().replace(/\/+$/,"").toLowerCase(),r=String(t||"").trim().toLowerCase(),i=N.getInstance().getProfiles().filter(a=>String(a.apiBaseUrl||"").trim().replace(/\/+$/,"").toLowerCase()===n);return{tenantKeyUnambiguous:i.filter(a=>String(a.osClient||"").trim().toLowerCase()===r).length<=1,apiKeyUnambiguous:i.length<=1}}catch{return{tenantKeyUnambiguous:!0,apiKeyUnambiguous:!0}}}tokenLookupKeys(e,t,n,r){let i=[],o=this.legacyTokenScope(e,t);if(t){let a=this.tokenKey(e,t,n,r),c=this.tokenKey(e,t,"",""),l=this.legacyCompactTokenKey(e,t,n,r);i.push(a),o.tenantKeyUnambiguous&&i.push(c),(l===a||o.tenantKeyUnambiguous)&&i.push(l),n&&o.tenantKeyUnambiguous&&i.push(this.legacyCompactTokenKey(e,t,n)),o.tenantKeyUnambiguous&&i.push(this.legacyCompactTokenKey(e,t))}return(!t||o.apiKeyUnambiguous)&&i.push(e),Array.from(new Set(i))}async persistTokens(){let e=this._tokenPersistence.then(()=>this.persistCurrentTokens(),()=>this.persistCurrentTokens());return this._tokenPersistence=e.catch(()=>{}),e}async persistCurrentTokens(){if(!this._secretStorage)return;let e=N.getInstance(),t=e.getWorkspaceSecretKey(zn),n=e.getWorkspaceSecretKey(us);this._token?await this._secretStorage.store(t,this._token):await this._secretStorage.delete(t),Object.keys(this._tokenMap).length>0?await this._secretStorage.store(n,JSON.stringify(this._tokenMap)):await this._secretStorage.delete(n)}async setToken(e,t,n,r,i){this._token=e,t&&(this._tokenMap[this.tokenKey(t,n,r,i)]=e),await this.persistTokens(),await this.notifyTokenStateChanged()}async loadToken(){if(this._token)return this._token;if(this._secretStorage){let e=N.getInstance();this._token=await this._secretStorage.get(e.getWorkspaceSecretKey(zn))||"";try{let t=await this._secretStorage.get(e.getWorkspaceSecretKey(us));t&&(this._tokenMap=JSON.parse(t))}catch{}}return this._token}getTokenForServer(e,t,n,r){let i=this.tokenLookupKeys(e,t,n,r),o="";for(let a of i)t&&a===e||(o=ut(o,this._tokenMap[a]));return o||i.includes(e)&&this._tokenMap[e]||""}getExactTokenForServer(e,t,n,r){return this._tokenMap[this.tokenKey(e,t,n,r)]||""}async adoptTokenFromSharedFile(e,t,n,r,i){await this.adoptTokensFromSharedFile([{token:e,apiBaseUrl:t,osClient:n,osClientType:r,osClientNetwork:i}])}async adoptTokensFromSharedFile(e){let t=0,n=!1;for(let r of e){let i=String(r.token||"").trim();if(!i)continue;let o=this.tokenKey(r.apiBaseUrl,r.osClient,r.osClientType,r.osClientNetwork);this._tokenMap[o]!==i&&(this._tokenMap[o]=i,t+=1,n=!0);let a=ut(this._token,i);a!==this._token&&(this._token=a,n=!0)}return n&&await this.persistTokens(),t}async clearTokenForServer(e,t,n,r,i){let o=!1;for(let a of this.tokenLookupKeys(e,t,n,r))this._tokenMap[a]&&(!i||this._tokenMap[a]===i)&&(delete this._tokenMap[a],o=!0);this._token&&(!i||this._token===i)&&(this._token="",o=!0),o&&(await this.persistTokens(),await this.notifyTokenStateChanged())}async clearToken(){this._token="",this._tokenMap={},await this.persistTokens(),await this.notifyTokenStateChanged()}get hasToken(){return!!this._token||Object.keys(this._tokenMap).length>0}isInvalidRefreshToken(e,t){if(t===401||t===403)return!0;let n=String(e?.DataAppend?.ReasonCode||"");if(/^(MissingToken|MalformedToken|MissingClaims|TenantMismatch|AuthVersionChanged|JwtExpired|SessionExpired|SessionMissing|TokenReplaced)$/i.test(n))return!0;let r=e?.Msg||"";return e?.Code!==1&&/无效.*Token|Token.*无效|Token.*过期|登录.*过期|租户.*不一致|invalid\s*token|token\s*invalid/i.test(r)}serializeRequestBody(e,t){if(t==="form"){let n=new URLSearchParams;if(e&&typeof e=="object"&&!Array.isArray(e))for(let[r,i]of Object.entries(e))i!=null&&n.append(r,typeof i=="object"?JSON.stringify(i):String(i));return n.toString()}return JSON.stringify(e)}maskSensitiveBody(e){if(!e||typeof e!="object")return e;if(Array.isArray(e))return e.map(n=>this.maskSensitiveBody(n));let t={};for(let[n,r]of Object.entries(e))/^(pwd|password|authorization|token)$/i.test(n)?t[n]="***":r&&typeof r=="object"?t[n]=this.maskSensitiveBody(r):t[n]=r;return t}async refreshTokenForRequest(e,t,n,r){if(!t)return!1;let i=N.getInstance(),o=e.osClient||i.getOsClient()||"",a=r||this.captureResponseTokenCommit({apiBaseUrl:e.apiBaseUrl||n,osClient:e.osClient,osClientType:e.osClientType,osClientNetwork:e.osClientNetwork}),c=new URL(n),p=c.pathname.replace(/\/+$/,"")+H.REFRESH_TOKEN,d=c.protocol==="https:",u=d?Rt:Nt,g=JSON.stringify({authorization:t,OsClient:o||void 0,_ClientType:"VSCode"}),m={hostname:c.hostname,port:c.port||(d?443:80),path:p,method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",Authorization:`Bearer ${t}`,did:this.getDeviceId(),"Content-Length":Buffer.byteLength(g),...o?{OsClient:o}:{}},timeout:e.timeout||3e4,rejectUnauthorized:this._strictTlsHosts.has(c.hostname.toLowerCase())};return ce.log("API",`\u{1F504} RefreshToken ${n}${p}`),new Promise(f=>{let y=u.request(m,C=>{let h=[];C.on("data",S=>h.push(S)),C.on("end",async()=>{let S=Buffer.concat(h).toString("utf-8"),b;try{b=JSON.parse(S)}catch{}let E=C.headers,k=C.statusCode||0,I=E.authorization||"";if(!a.current()){f(!1);return}if(b?.Code===1&&I){if(!await a.commit(I)){f(!1);return}ce.log("API","\u2705 Token \u5DF2\u4EE5\u65E7\u6362\u65B0"),f(!0);return}this.isInvalidRefreshToken(b,k)&&await this.clearTokenForServer(e.apiBaseUrl||n,e.osClient,e.osClientType,e.osClientNetwork,t),ce.log("API",`\u26A0\uFE0F RefreshToken \u5931\u8D25: ${b?.Msg||S.slice(0,120)}`),f(!1)})});y.on("error",C=>{ce.log("API",`\u274C RefreshToken Error: ${C.message}`),f(!1)}),y.on("timeout",()=>{y.destroy(),f(!1)}),y.write(g),y.end()})}async recoverAuthForRequest(e,t){if(!this._authRecoveryHandler)return!1;let n=N.getInstance(),r={apiBaseUrl:e.apiBaseUrl||t,osClient:e.osClient||n.getOsClient()||void 0,osClientType:e.osClientType,osClientNetwork:e.osClientNetwork},i=this.tokenKey(r.apiBaseUrl,r.osClient,r.osClientType,r.osClientNetwork);return this._authRecoveryGate.run(i,()=>this._authRecoveryHandler(r))}async request(e){let t=N.getInstance(),n=e.apiBaseUrl||t.getApiBaseUrl();if(!n)throw new Error('\u672A\u914D\u7F6E API \u5730\u5740\uFF0C\u8BF7\u5148\u6267\u884C "Microi: \u914D\u7F6E\u8FDE\u63A5"');let r=this.captureResponseTokenCommit({apiBaseUrl:n,osClient:e.osClient,osClientType:e.osClientType,osClientNetwork:e.osClientNetwork}),i=r.current,o=new URL(n),c=o.pathname.replace(/\/+$/,"")+e.path;if(e.params){let h=new URLSearchParams;for(let[b,E]of Object.entries(e.params))E!==void 0&&E!==""&&h.append(b,E);let S=h.toString();S&&(c+=`?${S}`)}let l=o.protocol==="https:",p=l?Rt:Nt,d=e.bodyFormat||"json",u=e.body!==void 0?this.serializeRequestBody(e.body,d):void 0,g={hostname:o.hostname,port:o.port||(l?443:80),path:c,method:e.method,headers:{"Content-Type":d==="form"?"application/x-www-form-urlencoded":"application/json",Accept:"application/json",did:this.getDeviceId()},timeout:e.timeout||3e4,rejectUnauthorized:this._strictTlsHosts.has(o.hostname.toLowerCase())};u!==void 0&&(g.headers["Content-Length"]=Buffer.byteLength(u));let m=e.allowAuthRetry!==!1,f=e.osClient||t.getOsClient()||"";f&&(g.headers.OsClient=f);let y=e.apiBaseUrl?this.getTokenForServer(e.apiBaseUrl,e.osClient,e.osClientType,e.osClientNetwork):await this.loadToken();y&&(g.headers.Authorization=`Bearer ${y}`);let C=`${n}${c}`;if(e.silent||ce.log("API",`\u27A1\uFE0F ${e.method} ${C}`),e.body&&!e.silent){let h=JSON.stringify(this.maskSensitiveBody(e.body));ce.appendLine(` Body: ${h.length>500?h.substring(0,500)+"...(truncated)":h}`)}return new Promise((h,S)=>{let b=u===void 0?0:Buffer.byteLength(u),E=0,k=p.request(g,w=>{let O=[];w.on("data",A=>O.push(A)),w.on("end",async()=>{let A=Buffer.concat(O).toString("utf-8"),D=w.statusCode||0;if(!e.silent){ce.log("API",`\u2B05\uFE0F ${D} ${e.method} ${e.path}`);let T=A.length>500?A.substring(0,500)+"...(truncated)":A;ce.appendLine(` Response: ${T}`)}let $;try{$=JSON.parse(A)}catch{}if($){let T={};for(let[M,J]of Object.entries(w.headers))typeof J=="string"&&(T[M.toLowerCase()]=J);$._headers=T;let P=T.authorization||"";if(e.persistResponseToken!==!1&&P&&P!==y&&i()&&await r.commit(P),m&&It($))ce.log("API",`\u26A0\uFE0F \u79DF\u6237\u8FDE\u63A5\u914D\u7F6E\u65E0\u6548\uFF0C\u5DF2\u505C\u6B62 token \u5237\u65B0\u4E0E\u9759\u9ED8\u91CD\u767B: ${$.Msg||""}`);else if(m&&i()&&sn($)&&(ce.log("API",`\u{1F510} \u8EAB\u4EFD\u5DF2\u8FC7\u671F\uFF0C\u5C1D\u8BD5\u4F7F\u7528\u65E7 token \u5237\u65B0\u540E\u91CD\u8BD5: ${$.Msg||""}`),await this.refreshTokenForRequest(e,y,n,r)||i()&&await this.recoverAuthForRequest(e,n))){try{h(await this.request({...e,allowAuthRetry:!1}))}catch(Y){S(Y)}return}h($)}else if(D===401||D===403){if(m&&i()&&(await this.refreshTokenForRequest(e,y,n,r)||i()&&await this.recoverAuthForRequest(e,n))){try{h(await this.request({...e,allowAuthRetry:!1}))}catch(M){S(M)}return}S(new Error(`\u8EAB\u4EFD\u9A8C\u8BC1\u5931\u8D25 (HTTP ${D})\uFF0C\u8BF7\u91CD\u65B0\u767B\u5F55`))}else if(D>=400){let T=A.replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim().substring(0,120);S(new Error(`\u670D\u52A1\u5668\u9519\u8BEF (HTTP ${D}): ${T||"\u672A\u77E5\u9519\u8BEF"}`))}else S(new Error(`\u54CD\u5E94\u89E3\u6790\u5931\u8D25 (HTTP ${D}): ${A.substring(0,200)}`))})}),I=!1;k.on("error",w=>{if(I)return;let O=Dt(w),A=b>0?`\uFF1B\u8BF7\u6C42\u4F53\u5DF2\u5206\u7247\u6392\u961F ${E}/${b} bytes\uFF0C\u670D\u52A1\u7AEF\u662F\u5426\u5DF2\u63D0\u4EA4\u672A\u77E5\uFF0C\u63D2\u4EF6\u4E0D\u4F1A\u76F2\u76EE\u91CD\u653E\u975E\u5E42\u7B49\u8BF7\u6C42`:"";e.silent||ce.log("API",`\u274C ${e.method} ${e.path} Error: ${O}${A}`),S(new Error(`\u8BF7\u6C42\u5931\u8D25: ${O}${A}`))}),k.on("timeout",()=>{I=!0,k.destroy(),e.silent||ce.log("API",`\u23F0 ${e.method} ${e.path} Timeout`),S(new Error("\u8BF7\u6C42\u8D85\u65F6"))}),u!==void 0?Fi(k,u,w=>{E=w}).catch(w=>{!I&&!k.destroyed&&k.destroy(w instanceof Error?w:new Error(String(w)))}):k.end()})}async get(e,t,n,r){return this.request({method:"GET",path:e,params:t,apiBaseUrl:n,osClient:r?.osClient,osClientType:r?.osClientType,osClientNetwork:r?.osClientNetwork})}async post(e,t,n,r,i,o,a){return this.request({method:"POST",path:e,body:t,params:n,apiBaseUrl:r,osClient:i?.osClient,osClientType:i?.osClientType,osClientNetwork:i?.osClientNetwork,timeout:o,silent:a})}async downloadApplicationSourceFile(e,t,n,r,i){let o=new URL(r);if(!["http:","https:"].includes(o.protocol)||o.username||o.password)throw new Error("\u6E90\u7801 API \u5730\u5740\u4E0D\u5408\u6CD5");let a=this.getTokenForServer(r,i.osClient,i.osClientType,i.osClientNetwork),c=JSON.stringify({OsClient:i.osClient,AppIdOrKey:e,FilePath:t.relativePath,IncludeContents:!0,MaxFileBytes:Math.max(1,t.size)});return new Promise((l,p)=>{let d=(o.protocol==="https:"?Rt:Nt).request({hostname:o.hostname,port:o.port||(o.protocol==="https:"?443:80),path:o.pathname.replace(/\/+$/,"")+H.GET_APPLICATION_FILE,method:"POST",rejectUnauthorized:this._strictTlsHosts.has(o.hostname.toLowerCase()),headers:{"Content-Type":"application/json",Accept:"application/json","Content-Length":Buffer.byteLength(c),did:this.getDeviceId(),...a?{Authorization:`Bearer ${a}`}:{},...i.osClient?{OsClient:i.osClient}:{}}},g=>{if(g.statusCode!==200){g.destroy(),p(new Error(`\u6E90\u7801\u4E0B\u8F7D\u5931\u8D25\uFF1AHTTP ${g.statusCode}`));return}os(g,n,t).then(l,p)}),u=setTimeout(()=>d.destroy(new Error("\u6E90\u7801\u4E0B\u8F7D\u8D85\u65F6")),5*60*1e3);d.once("close",()=>clearTimeout(u)),d.once("error",p),d.end(c)})}async getRaw(e,t,n){let r=N.getInstance(),i=n||r.getApiBaseUrl();if(!i)throw new Error("\u672A\u914D\u7F6E API \u5730\u5740");let o=new URL(i),c=o.pathname.replace(/\/+$/,"")+e;if(t){let u=new URLSearchParams;for(let[m,f]of Object.entries(t))f!==void 0&&f!==""&&u.append(m,f);let g=u.toString();g&&(c+=`?${g}`)}let l=o.protocol==="https:",p=l?Rt:Nt,d={hostname:o.hostname,port:o.port||(l?443:80),path:c,method:"GET",timeout:15e3,rejectUnauthorized:this._strictTlsHosts.has(o.hostname.toLowerCase())};return new Promise((u,g)=>{let m=p.request(d,f=>{let y=[];f.on("data",C=>y.push(C)),f.on("end",()=>{let C=Buffer.concat(y),h=f.headers.captchaid||"";u({data:C,captchaId:h,statusCode:f.statusCode||0,contentType:String(f.headers["content-type"]||"")})})});m.on("error",f=>g(new Error(`\u8BF7\u6C42\u5931\u8D25: ${f.message}`))),m.on("timeout",()=>{m.destroy(),g(new Error("\u8BF7\u6C42\u8D85\u65F6"))}),m.end()})}async postMultipartFile(e,t,n,r,i,o,a=30*60*1e3){let c=dt.realpathSync(n),l=dt.lstatSync(c);if(!l.isFile()||l.isSymbolicLink())throw new Error(`\u4E0A\u4F20\u8D44\u4EA7\u5FC5\u987B\u662F\u666E\u901A\u6587\u4EF6\u4E14\u4E0D\u80FD\u662F\u7B26\u53F7\u94FE\u63A5\uFF1A${n}`);if(!r||/[\r\n"]/u.test(r))throw new Error("\u4E0A\u4F20\u6587\u4EF6\u540D\u4E0D\u5408\u6CD5");let p=String(i||"").replace(/\/+$/,""),d=this.captureResponseTokenCommit({apiBaseUrl:p,osClient:o?.osClient,osClientType:o?.osClientType,osClientNetwork:o?.osClientNetwork}),u=new URL(p),g=`----microi-vscode-${on.randomBytes(24).toString("hex")}`,m=Object.entries(t).map(([I,w])=>Buffer.from(`--${g}\r
|
|
22
|
+
Content-Disposition: form-data; name="${I}"\r
|
|
23
23
|
\r
|
|
24
|
-
${
|
|
25
|
-
`,"utf8")),
|
|
24
|
+
${w}\r
|
|
25
|
+
`,"utf8")),f=Buffer.from(`--${g}\r
|
|
26
26
|
Content-Disposition: form-data; name="file"; filename="${r}"\r
|
|
27
27
|
Content-Type: application/octet-stream\r
|
|
28
28
|
\r
|
|
29
|
-
`,"utf8"),
|
|
30
|
-
--${
|
|
31
|
-
`,"utf8"),
|
|
32
|
-
`,i=Ft.spawnSync("/usr/bin/security",["-q","-i"],{input:r,encoding:"utf8",timeout:15e3,maxBuffer:4*1024*1024});if(i.error||i.status!==0||sr(s,e)!==t)throw new Error("macOS Keychain \u5199\u5165\u6216\u56DE\u8BFB\u5931\u8D25\uFF1B\u51ED\u636E\u672A\u5199\u5165\u660E\u6587\u6587\u4EF6")}function Oi(s,e){if(process.platform!=="darwin")throw new Error("macOS Keychain is unavailable on this platform");let t=Ft.spawnSync("/usr/bin/security",["delete-generic-password","-s",s,"-a",e],{encoding:"utf8",timeout:15e3,maxBuffer:4*1024*1024});if(t.error||t.status!==0&&t.status!==44)throw new Error("macOS Keychain \u5220\u9664\u5931\u8D25")}var cn=class{constructor(e){this.workspaceTokenFile=e;this.onDidChange=()=>({dispose:()=>{}})}account(e){return fs(`${this.workspaceTokenFile}\0${e}`)}async get(e){return sr(nr,this.account(e))}async store(e,t){hs(nr,this.account(e),t)}async delete(e){Oi(nr,this.account(e))}},
|
|
29
|
+
`,"utf8"),y=Buffer.concat([...m,f]),C=Buffer.from(`\r
|
|
30
|
+
--${g}--\r
|
|
31
|
+
`,"utf8"),h=o?this.getTokenForServer(p,o.osClient,o.osClientType,o.osClientNetwork):await this.loadToken(),S=u.protocol==="https:",b=S?Rt:Nt,E=u.pathname.replace(/\/+$/,""),k={hostname:u.hostname,port:u.port||(S?443:80),path:E+e,method:"POST",timeout:a,rejectUnauthorized:this._strictTlsHosts.has(u.hostname.toLowerCase()),headers:{Accept:"application/json",...h?{Authorization:`Bearer ${h}`}:{},did:this.getDeviceId(),...o?.osClient?{OsClient:o.osClient}:{},"Content-Type":`multipart/form-data; boundary=${g}`,"Content-Length":y.length+l.size+C.length}};return new Promise((I,w)=>{let O=!1,A=T=>{O||(O=!0,w(T))},D=b.request(k,T=>{let P=[];T.on("data",M=>P.push(M)),T.on("end",async()=>{if(O)return;let M=Buffer.concat(P).toString("utf8"),J;try{J=JSON.parse(M)}catch{A(new Error(`\u6D41\u5F0F\u4E0A\u4F20\u54CD\u5E94\u4E0D\u662F JSON\uFF08HTTP ${T.statusCode||0}\uFF09`));return}let Y=String(T.headers.authorization||"");Y&&d.current()&&await d.commit(Y),O=!0,I(J)})});D.on("error",T=>A(new Error(`\u6D41\u5F0F\u4E0A\u4F20\u5931\u8D25\uFF1A${Dt(T)}`))),D.on("timeout",()=>{D.destroy(),A(new Error(`\u6D41\u5F0F\u4E0A\u4F20\u8D85\u65F6\uFF08${a}ms\uFF09`))}),D.write(y);let $=dt.createReadStream(c);$.on("error",T=>{D.destroy(),A(new Error(`\u8BFB\u53D6\u672C\u5730\u53D1\u5E03\u8D44\u4EA7\u5931\u8D25\uFF1A${Dt(T)}`))}),$.on("end",()=>D.end(C)),$.pipe(D,{end:!1})})}};var gt=B(require("crypto")),z=B(require("fs")),$t=B(require("path"));var Ft=B(require("child_process")),ds=require("crypto"),se=B(require("fs")),un=B(require("path")),Vt=".microi-workspace-secrets.dpapi.json",gs=["$ErrorActionPreference = 'Stop';","Add-Type -AssemblyName System.Security;","$inputBase64 = [Console]::In.ReadToEnd().Trim();","$plain = [Convert]::FromBase64String($inputBase64);","$cipher = [Security.Cryptography.ProtectedData]::Protect($plain, $null, [Security.Cryptography.DataProtectionScope]::CurrentUser);","[Console]::Out.Write([Convert]::ToBase64String($cipher));"].join(" "),ps=["$ErrorActionPreference = 'Stop';","Add-Type -AssemblyName System.Security;","$inputBase64 = [Console]::In.ReadToEnd().Trim();","$cipher = [Convert]::FromBase64String($inputBase64);","$plain = [Security.Cryptography.ProtectedData]::Unprotect($cipher, $null, [Security.Cryptography.DataProtectionScope]::CurrentUser);","[Console]::Out.Write([Convert]::ToBase64String($plain));"].join(" ");function an(s,e){if(process.platform!=="win32")throw new Error("\u5F53\u524D\u64CD\u4F5C\u7CFB\u7EDF\u4E0D\u652F\u6301 Windows DPAPI \u5DE5\u4F5C\u533A\u51ED\u636E\u4FDD\u9669\u5E93");let t=process.env.SystemRoot||"C:\\Windows",n=un.join(t,"System32","WindowsPowerShell","v1.0","powershell.exe"),r=Ft.spawnSync(n,["-NoLogo","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command",s],{input:e.toString("base64"),encoding:"utf8",windowsHide:!0,maxBuffer:4*1024*1024,timeout:15e3}),i=String(r.stdout||"").trim();if(r.error||r.status!==0||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(i))throw new Error("Windows DPAPI \u64CD\u4F5C\u5931\u8D25\uFF1B\u51ED\u636E\u672A\u5199\u5165\u660E\u6587\u6587\u4EF6");return Buffer.from(i,"base64")}function Vi(s){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,s)}var rr="dpapi-session-v1:",xt="keychain-session-v1:",nr="net.microi.cli.workspace.v1",ms="net.microi.cli.session.v1",fs=s=>(0,ds.createHash)("sha256").update(s).digest("hex");function sr(s,e){if(process.platform!=="darwin")throw new Error("macOS Keychain is unavailable on this platform");let t=Ft.spawnSync("/usr/bin/security",["find-generic-password","-s",s,"-a",e,"-w"],{encoding:"utf8",timeout:15e3,maxBuffer:4*1024*1024});if(t.status===44)return;if(t.error||t.status!==0)throw new Error("macOS Keychain \u8BFB\u53D6\u5931\u8D25\uFF1B\u51ED\u636E\u672A\u5199\u5165\u660E\u6587\u6587\u4EF6");let n=String(t.stdout||"").trim();if(!/^[A-Za-z0-9+/]+={0,2}$/.test(n))throw new Error("macOS Keychain \u51ED\u636E\u683C\u5F0F\u65E0\u6548");return Buffer.from(n,"base64").toString("utf8")}function hs(s,e,t){if(process.platform!=="darwin")throw new Error("macOS Keychain is unavailable on this platform");let n=Buffer.from(t,"utf8").toString("base64"),r=`add-generic-password -U -s ${s} -a ${e} -w ${n}
|
|
32
|
+
`,i=Ft.spawnSync("/usr/bin/security",["-q","-i"],{input:r,encoding:"utf8",timeout:15e3,maxBuffer:4*1024*1024});if(i.error||i.status!==0||sr(s,e)!==t)throw new Error("macOS Keychain \u5199\u5165\u6216\u56DE\u8BFB\u5931\u8D25\uFF1B\u51ED\u636E\u672A\u5199\u5165\u660E\u6587\u6587\u4EF6")}function Oi(s,e){if(process.platform!=="darwin")throw new Error("macOS Keychain is unavailable on this platform");let t=Ft.spawnSync("/usr/bin/security",["delete-generic-password","-s",s,"-a",e],{encoding:"utf8",timeout:15e3,maxBuffer:4*1024*1024});if(t.error||t.status!==0&&t.status!==44)throw new Error("macOS Keychain \u5220\u9664\u5931\u8D25")}var cn=class{constructor(e){this.workspaceTokenFile=e;this.onDidChange=()=>({dispose:()=>{}})}account(e){return fs(`${this.workspaceTokenFile}\0${e}`)}async get(e){return sr(nr,this.account(e))}async store(e,t){hs(nr,this.account(e),t)}async delete(e){Oi(nr,this.account(e))}},At=new Map,Mt=new Map;function Ot(s){return typeof s=="string"&&(s.startsWith(rr)||s.startsWith(xt))}function ys(s){if(!s||Ot(s))return s;if(process.platform==="darwin"){let e=xt+fs(s);return hs(ms,e.slice(xt.length),s),e}return Mt.has(s)||(Mt.size>256&&Mt.clear(),Mt.set(s,rr+an(gs,Buffer.from(s,"utf8")).toString("base64"))),Mt.get(s)}function ir(s){if(typeof s!="string")return"";if(!Ot(s))return s;if(s.startsWith(xt)){let e=s.slice(xt.length);if(!/^[a-f0-9]{64}$/.test(e))throw new Error("macOS Keychain Token \u5F15\u7528\u683C\u5F0F\u65E0\u6548");let t=sr(ms,e);if(!t)throw new Error("macOS Keychain Token \u5F15\u7528\u4E0D\u5B58\u5728");return t}return At.has(s)||(At.size>256&&At.clear(),At.set(s,an(ps,Buffer.from(s.slice(rr.length),"base64")).toString("utf8"))),At.get(s)}function $i(s){if(!Number.isInteger(s)||s<=1)return!1;try{return process.kill(s,0),!0}catch(e){return e.code==="EPERM"}}function Bi(s){try{let e=JSON.parse(se.readFileSync(s,"utf8"));return $i(Number(e?.pid))}catch{return!1}}var ln=class{constructor(e,t){this.filePath=e;this.onDidChange=()=>({dispose:()=>{}});this.protect=t?.protect||(n=>an(gs,n)),this.unprotect=t?.unprotect||(n=>an(ps,n))}async get(e){return this.readDocument().values[e]}async store(e,t){this.mutate(n=>{n.values[e]=t})}async delete(e){this.mutate(t=>{delete t.values[e]})}mutate(e){se.mkdirSync(un.dirname(this.filePath),{recursive:!0});let t=`${this.filePath}.lock`,n=Date.now()+3e3,r;for(;r===void 0;)try{r=se.openSync(t,"wx",384),se.writeFileSync(r,`${JSON.stringify({pid:process.pid,createdAt:new Date().toISOString()})}
|
|
33
33
|
`,"utf8")}catch(o){if(o.code!=="EEXIST")throw o;try{let a=Date.now()-se.statSync(t).mtimeMs>3e4;(!Bi(t)||a)&&se.unlinkSync(t)}catch{}if(Date.now()>=n)throw new Error("Microi \u5DE5\u4F5C\u533A\u51ED\u636E\u4FDD\u9669\u5E93\u6B63\u88AB\u53E6\u4E00\u8FDB\u7A0B\u66F4\u65B0\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");Vi(40)}let i=`${this.filePath}.${process.pid}.${Date.now()}.tmp`;try{let o=this.readDocument();e(o);let a=Buffer.from(JSON.stringify(o),"utf8"),c={version:1,protection:"windows-dpapi-current-user",ciphertext:this.protect(a).toString("base64")};if(!this.unprotect(Buffer.from(c.ciphertext,"base64")).equals(a))throw new Error("Microi \u5DE5\u4F5C\u533A\u51ED\u636E\u52A0\u5BC6\u56DE\u8BFB\u4E0D\u4E00\u81F4\uFF0C\u5DF2\u4FDD\u7559\u539F\u4FDD\u9669\u5E93");se.writeFileSync(i,`${JSON.stringify(c,null,2)}
|
|
34
|
-
`,{encoding:"utf8",mode:384}),se.renameSync(i,this.filePath)}finally{try{se.existsSync(i)&&se.unlinkSync(i)}catch{}try{se.closeSync(r)}catch{}try{se.unlinkSync(t)}catch{}}}readDocument(){if(!se.existsSync(this.filePath))return{version:1,values:{}};if(se.statSync(this.filePath).size>2*1024*1024)throw new Error("Microi \u5DE5\u4F5C\u533A\u51ED\u636E\u4FDD\u9669\u5E93\u8D85\u8FC7\u5B89\u5168\u5927\u5C0F\u9650\u5236\uFF0C\u5DF2\u62D2\u7EDD\u8BFB\u53D6");let e;try{e=JSON.parse(se.readFileSync(this.filePath,"utf8"))}catch{throw new Error("Microi \u5DE5\u4F5C\u533A\u51ED\u636E\u4FDD\u9669\u5E93\u65E0\u6CD5\u89E3\u6790\uFF0C\u5DF2\u4FDD\u7559\u539F\u6587\u4EF6\u4E14\u505C\u6B62\u8986\u76D6")}if(e.version!==1||e.protection!=="windows-dpapi-current-user"||typeof e.ciphertext!="string"||!e.ciphertext)throw new Error("Microi \u5DE5\u4F5C\u533A\u51ED\u636E\u4FDD\u9669\u5E93\u683C\u5F0F\u65E0\u6548\uFF0C\u5DF2\u4FDD\u7559\u539F\u6587\u4EF6\u4E14\u505C\u6B62\u8986\u76D6");try{let t=this.unprotect(Buffer.from(e.ciphertext,"base64"));if(t.length===0)return{version:1,values:{}};let n=JSON.parse(t.toString("utf8"));if(n.version!==1||!n.values||typeof n.values!="object")throw new Error("invalid document");return n.values=Object.fromEntries(Object.entries(n.values).filter(r=>typeof r[0]=="string"&&typeof r[1]=="string")),n}catch{throw new Error("Microi \u5DE5\u4F5C\u533A\u51ED\u636E\u4FDD\u9669\u5E93\u65E0\u6CD5\u7531\u5F53\u524D Windows \u7528\u6237\u89E3\u5BC6\uFF0C\u5DF2\u505C\u6B62\u8986\u76D6")}}};var Li=60*60*1e3,Ui=5*60,Ss=24*60*60,ji=2*60*1e3,Ki=60*1e3;function Hi(s,e){let t=(e||"").trim();return t?gt.publicEncrypt({key:t,padding:gt.constants.RSA_PKCS1_PADDING},Buffer.from(s,"utf-8")).toString("base64"):s}var ke=class s{constructor(){this._isLoggedIn=!1;this._refreshInProgress=!1;this._mcpTokenFilePath="";this._mcpAuthRecoveryDirPath="";this._mcpAuthRecoveryInProgress=new Set;this._mcpAuthRecoveryFailureUntil=new Map;this._mcpAuthRecoveryPassInProgress=!1;this._lastAuthWarning="";this._lastAuthWarningTime=0;this.protectedMcpTokenKeys=new Set}static getInstance(){return s._instance||(s._instance=new s),s._instance}setSecretStorage(e){this._secretStorage=e,K.getInstance().setTokenStateChangedHandler(async()=>{await this.writeMcpTokenFile()}),K.getInstance().setAuthRecoveryHandler(async t=>{let n=N.getInstance(),r=this.normalizeApiBaseUrl(t.apiBaseUrl),i=this.normalizeOsClient(t.osClient),o=this.normalizeIdentityPart(t.osClientType),a=this.normalizeIdentityPart(t.osClientNetwork),c=n.getProfiles().filter(u=>this.normalizeApiBaseUrl(u.apiBaseUrl)===r&&this.normalizeOsClient(u.osClient)===i),l=c.find(u=>this.normalizeIdentityPart(u.osClientType)===o&&this.normalizeIdentityPart(u.osClientNetwork)===a);if(!l&&!o&&!a&&c.length===1&&(l=c[0]),!l&&c.length===0&&(l={label:t.osClient||t.apiBaseUrl,apiBaseUrl:t.apiBaseUrl,osClient:t.osClient||"",osClientType:t.osClientType,osClientNetwork:t.osClientNetwork}),!l)return this.showAuthExpiredWarning("\u68C0\u6D4B\u5230\u540C\u4E00\u670D\u52A1\u5668\u4E0E\u79DF\u6237\u5B58\u5728\u591A\u4E2A\u8FDE\u63A5\u73AF\u5883\uFF0C\u65E0\u6CD5\u5B89\u5168\u5224\u65AD\u5E94\u6062\u590D\u54EA\u4E00\u4E2A\u767B\u5F55\u8EAB\u4EFD\u3002"),!1;let p=await this.reLoginForProfile(l);return p&&(this._isLoggedIn=!0,await et.executeCommand("setContext",ct,!0)),await this.writeMcpTokenFile(),p})}setMcpTokenFilePath(e){this._mcpTokenFilePath=e,this._mcpAuthRecoveryDirPath=e?`${e}.recovery`:""}enableProtectedMcpTokens(e){let t=this.normalizeApiBaseUrl(e.apiBaseUrl),n=this.normalizeOsClient(e.osClient);this.protectedMcpTokenKeys.add(this.mcpRecoveryIdentity(t,n,e.osClientType,e.osClientNetwork)),this.protectedMcpTokenKeys.add(n?`${t}|${n}`:t)}get mcpTokenFilePath(){return this._mcpTokenFilePath}get mcpAuthRecoveryDirPath(){return this._mcpAuthRecoveryDirPath}async loadMcpTokenFile(){if(!this._mcpTokenFilePath||!z.existsSync(this._mcpTokenFilePath))return 0;let e;try{let i=JSON.parse(z.readFileSync(this._mcpTokenFilePath,"utf-8"));if(!i||typeof i!="object"||Array.isArray(i))return 0;for(let[o,a]of Object.entries(i))Ot(a)&&this.protectedMcpTokenKeys.add(o);e=Object.fromEntries(Object.entries(i).map(([o,a])=>[o,ir(a)]))}catch{return 0}let t=K.getInstance(),n=N.getInstance().getProfiles(),r=[];for(let i of n){let o=this.normalizeApiBaseUrl(i.apiBaseUrl),a=this.normalizeOsClient(i.osClient),c=this.mcpRecoveryIdentity(o,a,i.osClientType,i.osClientNetwork),p=n.filter(y=>this.normalizeApiBaseUrl(y.apiBaseUrl)===o&&this.normalizeOsClient(y.osClient)===a).length===1?[[o,a,i.osClientType,i.osClientNetwork].filter(Boolean).join("|"),[o,a,i.osClientType].filter(Boolean).join("|"),a?`${o}|${a}`:o]:[],u=typeof e[c]=="string"&&String(e[c]).trim()?String(e[c]).trim():"",d=p.map(y=>e[y]).find(y=>typeof y=="string"&&y.trim()),g=t.getTokenForServer(i.apiBaseUrl,i.osClient,i.osClientType,i.osClientNetwork),m=t.getExactTokenForServer(i.apiBaseUrl,i.osClient,i.osClientType,i.osClientNetwork),f=ut(g,u||d,!!u&&!m);!f||m===f||r.push({token:f,apiBaseUrl:i.apiBaseUrl,osClient:i.osClient,osClientType:i.osClientType,osClientNetwork:i.osClientNetwork})}return t.adoptTokensFromSharedFile(r)}get isLoggedIn(){return this._isLoggedIn}secretKey(e){return N.getInstance().getWorkspaceSecretKey(e)}normalizeApiBaseUrl(e){return(e||"").trim().replace(/\/+$/,"")}normalizeOsClient(e){return(e||"").trim()}normalizeIdentityPart(e){return(e||"").trim()}mcpRecoveryIdentity(e,t,n,r){return[this.normalizeApiBaseUrl(e),this.normalizeOsClient(t),this.normalizeIdentityPart(n),this.normalizeIdentityPart(r)].join("|")}serverSecretKey(e,t,n){return this.secretKey(`${e}.${this.normalizeApiBaseUrl(t)}|${this.normalizeOsClient(n)}`)}getCredentialSecretKeys(e){return{usernameKey:this.serverSecretKey(ve,e.apiBaseUrl,e.osClient),passwordKey:this.serverSecretKey(Ee,e.apiBaseUrl,e.osClient)}}legacyServerSecretKey(e,t){return this.secretKey(`${e}.${this.normalizeApiBaseUrl(t)}`)}canUseLegacyCredential(e,t){let n=this.normalizeApiBaseUrl(e),r=this.normalizeOsClient(t);if(!n)return!1;let i=N.getInstance().getProfiles().filter(a=>this.normalizeApiBaseUrl(a.apiBaseUrl)===n);if(i.length===0)return!r;if(i.length===1)return!0;let o=i.filter(a=>this.normalizeOsClient(a.osClient)===r);return!!r&&o.length===i.length}async writeMcpTokenFile(){if(!this._mcpTokenFilePath)return;let e=K.getInstance(),t=N.getInstance(),n=t.getProfiles(),r=this._mcpTokenFilePath;if(!(n.some(f=>!!this.normalizeApiBaseUrl(f.apiBaseUrl)&&!!this.normalizeOsClient(f.osClient))||!!this.normalizeApiBaseUrl(t.getApiBaseUrl())&&!!this.normalizeOsClient(t.getOsClient()))&&!z.existsSync(r))return;let o={},a=new Set,c=[];for(let f of n){let y=this.normalizeApiBaseUrl(f.apiBaseUrl),S=this.normalizeOsClient(f.osClient),h=this.mcpRecoveryIdentity(y,S,f.osClientType,f.osClientNetwork);a.add(h);let C=n.filter(k=>this.normalizeApiBaseUrl(k.apiBaseUrl)===y&&this.normalizeOsClient(k.osClient)===S),b=S?`${y}|${S}`:y;C.length===1&&a.add(b);let T=e.getTokenForServer(f.apiBaseUrl,f.osClient,f.osClientType,f.osClientNetwork);c.push({profile:f,exactKey:h,legacyKey:C.length===1?b:void 0,currentToken:T,currentExactToken:e.getExactTokenForServer(f.apiBaseUrl,f.osClient,f.osClientType,f.osClientNetwork)}),T&&(o[h]=T,C.length===1&&(o[b]=T))}let l=$t.dirname(r);z.existsSync(l)||z.mkdirSync(l,{recursive:!0});let p=`${r}.lock`,u=Date.now()+3e3,d;for(;d===void 0;)try{d=z.openSync(p,"wx",384),z.writeFileSync(d,JSON.stringify({pid:process.pid,createdAt:Date.now()}),"utf-8")}catch(f){if(f.code!=="EEXIST")throw f;try{Date.now()-z.statSync(p).mtimeMs>3e4&&z.unlinkSync(p)}catch{}if(Date.now()>=u)throw new Error("Microi MCP Token \u6587\u4EF6\u6B63\u5728\u88AB CLI \u6216 VS Code \u63D2\u4EF6\u4FEE\u6539\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");await new Promise(y=>setTimeout(y,40))}let g=`${r}.${process.pid}.${Date.now()}.tmp`,m=[];try{let f={};if(z.existsSync(r)){let h=JSON.parse(z.readFileSync(r,"utf-8"));if(!h||typeof h!="object"||Array.isArray(h))throw new Error(`Microi MCP Token \u6587\u4EF6\u5FC5\u987B\u662F JSON \u5BF9\u8C61\uFF0C\u5DF2\u4FDD\u7559\u539F\u6587\u4EF6\uFF1A${r}`);for(let[C,b]of Object.entries(h))Ot(b)&&this.protectedMcpTokenKeys.add(C);f=Object.fromEntries(Object.entries(h).filter(C=>typeof C[1]=="string"&&!!C[1]).map(([C,b])=>[C,ir(b)]))}for(let h of c){let C=f[h.exactKey]||"",b=h.legacyKey&&f[h.legacyKey]||"",T=ut(h.currentToken,C||b,!!C&&!h.currentExactToken);T&&(o[h.exactKey]=T,h.legacyKey&&(o[h.legacyKey]=T),T!==h.currentExactToken&&m.push({profile:h.profile,token:T}))}for(let h of a)delete f[h];let y={...f,...o},S=Object.fromEntries(Object.entries(y).map(([h,C])=>[h,this.protectedMcpTokenKeys.has(h)?ys(C):C]));z.writeFileSync(g,`${JSON.stringify(S,null,2)}
|
|
35
|
-
`,{encoding:"utf-8",mode:384}),z.renameSync(g,r)}finally{try{z.existsSync(g)&&z.unlinkSync(g)}catch{}try{z.closeSync(d)}catch{}try{z.unlinkSync(p)}catch{}}await e.adoptTokensFromSharedFile(m.map(f=>({token:f.token,apiBaseUrl:f.profile.apiBaseUrl,osClient:f.profile.osClient,osClientType:f.profile.osClientType,osClientNetwork:f.profile.osClientNetwork})))}tokenFingerprint(e){return gt.createHash("sha256").update(String(e||"")).digest("hex")}deleteMcpAuthRecoveryRequests(e,t){let n=this._mcpAuthRecoveryDirPath;if(!n||!z.existsSync(n))return;let r=[];try{r=z.readdirSync(n).filter(i=>i.endsWith(".json")).slice(0,200)}catch{return}for(let i of r){let o=$t.join(n,i);try{let a=JSON.parse(z.readFileSync(o,"utf-8")),c=this.normalizeApiBaseUrl(String(a.apiBaseUrl||"")),l=this.normalizeOsClient(String(a.osClient||"")),p=this.normalizeIdentityPart(String(a.osClientType||"")),u=this.normalizeIdentityPart(String(a.osClientNetwork||"")),d=this.mcpRecoveryIdentity(c,l,p,u);if(!p&&!u){let g=t.filter(m=>this.normalizeApiBaseUrl(m.apiBaseUrl)===c&&this.normalizeOsClient(m.osClient)===l);g.length===1&&(d=this.mcpRecoveryIdentity(g[0].apiBaseUrl,g[0].osClient,g[0].osClientType,g[0].osClientNetwork))}d===e&&z.unlinkSync(o)}catch{}}}async processMcpAuthRecoveryRequests(){let e=this._mcpAuthRecoveryDirPath;if(!(!e||!z.existsSync(e)||this._mcpAuthRecoveryPassInProgress)){this._mcpAuthRecoveryPassInProgress=!0;try{let t=[];try{t=z.readdirSync(e).filter(o=>o.endsWith(".json")).slice(0,100)}catch{return}let r=N.getInstance().getProfiles(),i=K.getInstance();for(let o of t){let a=$t.join(e,o),c={};try{c=JSON.parse(z.readFileSync(a,"utf-8"))}catch{try{z.unlinkSync(a)}catch{}continue}let l=Number(c.requestedAt||0),p=this.normalizeApiBaseUrl(String(c.apiBaseUrl||"")),u=this.normalizeOsClient(String(c.osClient||"")),d=this.normalizeIdentityPart(String(c.osClientType||"")),g=this.normalizeIdentityPart(String(c.osClientNetwork||"")),m=String(c.failedTokenHash||"").trim().toLowerCase();if(Number(c.version)!==1||!p||!l||Math.abs(Date.now()-l)>ji||!ls(m)){try{z.unlinkSync(a)}catch{}continue}let f=r.filter(h=>this.normalizeApiBaseUrl(h.apiBaseUrl)===p&&this.normalizeOsClient(h.osClient)===u),y=d||g?f.find(h=>this.normalizeIdentityPart(h.osClientType)===d&&this.normalizeIdentityPart(h.osClientNetwork)===g):f.length===1?f[0]:void 0;if(!y){try{z.unlinkSync(a)}catch{}continue}let S=this.mcpRecoveryIdentity(y.apiBaseUrl,y.osClient,y.osClientType,y.osClientNetwork);if(!this._mcpAuthRecoveryInProgress.has(S)){if((this._mcpAuthRecoveryFailureUntil.get(S)||0)>Date.now()){this.deleteMcpAuthRecoveryRequests(S,r);continue}this._mcpAuthRecoveryInProgress.add(S);try{let h=i.getTokenForServer(y.apiBaseUrl,y.osClient,y.osClientType,y.osClientNetwork);h&&this.tokenFingerprint(h)!==m?(this._mcpAuthRecoveryFailureUntil.delete(S),await this.writeMcpTokenFile()):(h&&await i.clearTokenForServer(y.apiBaseUrl,y.osClient,y.osClientType,y.osClientNetwork,h),await this.reLoginForProfile(y)?this._mcpAuthRecoveryFailureUntil.delete(S):(this._mcpAuthRecoveryFailureUntil.set(S,Date.now()+Ki),this.showAuthExpiredWarning("MCP \u8EAB\u4EFD\u5DF2\u5931\u6548\uFF0C\u4FDD\u5B58\u7684\u51ED\u636E\u65E0\u6CD5\u9759\u9ED8\u6062\u590D\uFF1B\u82E5\u670D\u52A1\u5668\u542F\u7528\u4E86\u9A8C\u8BC1\u7801\uFF0C\u8BF7\u5728\u63D2\u4EF6\u914D\u7F6E\u4E2D\u4EA4\u4E92\u5F0F\u91CD\u65B0\u767B\u5F55\u3002")))}finally{this._mcpAuthRecoveryInProgress.delete(S),this.deleteMcpAuthRecoveryRequests(S,r)}}}}finally{this._mcpAuthRecoveryPassInProgress=!1}}}startMcpAuthRecoveryWatcher(){this._mcpAuthRecoveryTimer||!this._mcpAuthRecoveryDirPath||(this._mcpAuthRecoveryTimer=setInterval(()=>{this.processMcpAuthRecoveryRequests()},1e3),this.processMcpAuthRecoveryRequests())}stopMcpAuthRecoveryWatcher(){this._mcpAuthRecoveryTimer&&(clearInterval(this._mcpAuthRecoveryTimer),this._mcpAuthRecoveryTimer=void 0)}async tryAutoLogin(){let e=K.getInstance(),n=N.getInstance().getProfiles(),r=!1,i=await e.loadToken(),o=await this.loadMcpTokenFile();r=!!i||o>0||e.hasToken;let a=n.filter(u=>!e.getTokenForServer(u.apiBaseUrl,u.osClient,u.osClientType,u.osClientNetwork)),c=0,l=async()=>{for(;c<a.length;){let u=a[c++];await this.reLoginForProfile(u)&&(r=!0)}},p=Math.min(4,a.length);return await Promise.all(Array.from({length:p},()=>l())),r&&(this._isLoggedIn=!0,await et.executeCommand("setContext",ct,!0),await this.writeMcpTokenFile()),r}async getSysConfig(e,t,n,r=!1){let i=K.getInstance(),o=N.getInstance();try{let a=await i.request({method:"POST",path:H.GET_SYS_CONFIG,body:{_SearchEqual:{IsEnable:1},OsClient:t||o.getOsClient()||void 0},apiBaseUrl:e,osClient:t,allowAuthRetry:!1,silent:r});if(a.Code===1&&a.Data)return a.Data;n&&(n.message=a.Code!==1?`\u670D\u52A1\u5668\u8FD4\u56DE\u9519\u8BEF (Code: ${a.Code})${a.Msg?"\uFF1A"+a.Msg:""}\uFF0C\u8BF7\u68C0\u67E5 OsClient \u662F\u5426\u6B63\u786E`:"\u670D\u52A1\u5668\u672A\u8FD4\u56DE\u914D\u7F6E\u6570\u636E")}catch(a){n&&(n.message=a instanceof Error?a.message:String(a))}return null}async getCaptcha(e,t){let n=K.getInstance(),r=N.getInstance();try{let i=await n.getRaw(H.GET_CAPTCHA,{OsClient:t||r.getOsClient()||""},e);if(i.data&&i.captchaId){let o=i.data.toString("base64");return{captchaId:i.captchaId,imageBase64:`data:image/png;base64,${o}`}}}catch{}return null}async login(e,t,n={}){let r=K.getInstance(),i=N.getInstance(),o=n.osClient||i.getOsClient(),a=n.silent??!1;try{let c=await this.getSysConfig(n.apiBaseUrl,o,void 0,a),l=c?.EnableCaptcha;if((l===!0||l===1||String(l||"").trim().toLowerCase()==="true")&&(!n.captchaId||!n.captchaValue)){let S="\u670D\u52A1\u5668\u5DF2\u5F00\u542F\u56FE\u5F62\u9A8C\u8BC1\u7801\uFF0C\u8BF7\u5728\u63D2\u4EF6\u914D\u7F6E\u4E2D\u4EA4\u4E92\u5F0F\u767B\u5F55\u3002";return a||O.error(`Microi: \u767B\u5F55\u5931\u8D25 - ${S}`),{ok:!1,msg:S}}let u=typeof c?.LoginRsaPublicKey=="string"&&c.LoginRsaPublicKey.trim()?c.LoginRsaPublicKey:Vr,d=Hi(t,u),g={Account:e,Pwd:d,OsClient:o||void 0,_ClientType:"VSCode"};n.captchaId&&n.captchaValue&&(g._CaptchaId=n.captchaId,g._CaptchaValue=n.captchaValue);let m=await r.request({method:"POST",path:H.LOGIN,body:g,bodyFormat:"form",apiBaseUrl:n.apiBaseUrl,osClient:n.osClient,osClientType:n.osClientType,osClientNetwork:n.osClientNetwork,allowAuthRetry:!1,silent:a}),y=m._headers?.authorization||"";if(m.Code===1)return y&&await r.setToken(y,n.apiBaseUrl,n.osClient,n.osClientType,n.osClientNetwork),this._secretStorage&&(n.apiBaseUrl?(await this._secretStorage.store(this.serverSecretKey(ve,n.apiBaseUrl,o),e),await this._secretStorage.store(this.serverSecretKey(Ee,n.apiBaseUrl,o),t)):(await this._secretStorage.store(this.secretKey(ve),e),await this._secretStorage.store(this.secretKey(Ee),t))),m.Data?.OsClient&&!o&&await i.updateSettings({osClient:m.Data.OsClient}),this._isLoggedIn=!0,await et.executeCommand("setContext",ct,!0),await this.writeMcpTokenFile(),a||O.info(`Microi: \u767B\u5F55\u6210\u529F\uFF0C\u6B22\u8FCE ${m.Data?.Name||m.Data?.Account||e}`),{ok:!0,msg:""};{let S=m.Msg||"\u8BF7\u68C0\u67E5\u8D26\u53F7\u5BC6\u7801";return a||O.error(`Microi: \u767B\u5F55\u5931\u8D25 - ${S}`),{ok:!1,msg:S}}}catch(c){let l=c instanceof Error?c.message:String(c);return a||O.error(`Microi: \u767B\u5F55\u5931\u8D25 - ${l}`),{ok:!1,msg:l}}}async refreshAllTokens(){if(this._refreshInProgress)return;this._refreshInProgress=!0;let e=K.getInstance(),n=N.getInstance().getProfiles();try{for(let r of n){let i=e.getTokenForServer(r.apiBaseUrl,r.osClient,r.osClientType,r.osClientNetwork);if(!i){await this.reLoginForProfile(r);continue}try{let d=await e.request({method:"GET",path:H.GET_STATUS,apiBaseUrl:r.apiBaseUrl,osClient:r.osClient,osClientType:r.osClientType,osClientNetwork:r.osClientNetwork,allowAuthRetry:!1,silent:!0});if(Rt(d))continue;if(sn(d)){await e.clearTokenForServer(r.apiBaseUrl,r.osClient,r.osClientType,r.osClientNetwork,i),await this.reLoginForProfile(r)||this.showAuthExpiredWarning(d.Msg||"\u5F53\u524D\u767B\u5F55\u8EAB\u4EFD\u5DF2\u5931\u6548\uFF0C\u8BF7\u91CD\u65B0\u767B\u5F55\u3002");continue}}catch{}let o=this.readJwtClientClaims(i),a=String(o?.ClientType||"").trim(),c=a.toLowerCase()!=="vscode",l=!a||a.toLowerCase()==="empty";if(c&&(await this.reLoginForProfile(r)||!l))continue;let p=String(o?.Did||"").trim(),u=a.toLowerCase()==="vscode"&&p!==e.getDeviceId();if(!(!c&&!u&&!this.shouldRefreshToken(i,o)))try{let d=await e.request({method:"POST",path:H.REFRESH_TOKEN,body:{authorization:i,OsClient:r.osClient,_ClientType:"VSCode"},apiBaseUrl:r.apiBaseUrl,osClient:r.osClient,osClientType:r.osClientType,osClientNetwork:r.osClientNetwork,allowAuthRetry:!1,silent:!0}),m=d._headers?.authorization||"";d.Code===1&&m?await e.setToken(m,r.apiBaseUrl,r.osClient,r.osClientType,r.osClientNetwork):(await e.clearTokenForServer(r.apiBaseUrl,r.osClient,r.osClientType,r.osClientNetwork,i),await this.reLoginForProfile(r)||this.showAuthExpiredWarning(d.Msg||"\u5F53\u524D\u767B\u5F55\u8EAB\u4EFD\u5DF2\u5931\u6548\uFF0C\u8BF7\u91CD\u65B0\u767B\u5F55\u3002"))}catch{await this.reLoginForProfile(r)}}}finally{this._isLoggedIn=e.hasToken,await et.executeCommand("setContext",ct,this._isLoggedIn),await this.writeMcpTokenFile(),this._refreshInProgress=!1}}showAuthExpiredWarning(e){let t=String(e||"\u5F53\u524D\u767B\u5F55\u8EAB\u4EFD\u5DF2\u5931\u6548\uFF0C\u8BF7\u91CD\u65B0\u767B\u5F55\u3002"),n=Date.now();t===this._lastAuthWarning&&n-this._lastAuthWarningTime<60*1e3||(this._lastAuthWarning=t,this._lastAuthWarningTime=n,O.warn(`Microi: ${t}`))}readJwtClientClaims(e){try{let n=e.replace(/^Bearer\s+/i,"").trim().split(".");if(n.length<2)return null;let r=n[1].replace(/-/g,"+").replace(/_/g,"/");return JSON.parse(Buffer.from(r,"base64").toString("utf-8"))}catch{return null}}shouldRefreshToken(e,t){let n=t??this.readJwtClientClaims(e),r=Number(n?.exp);if(!Number.isFinite(r)||r<=0)return!0;let i=Number(n?.MicroiTokenIssuedAt??n?.iat),o=Number.isFinite(i)&&i>0&&r>i?r-i:Ss,a=Math.min(Ss,Math.max(Ui,Math.floor(o/10)));return r-Math.floor(Date.now()/1e3)<=a}async getCredentialsForProfile(e,t){if(!this._secretStorage)return null;let n=this.normalizeApiBaseUrl(e),r=this.normalizeOsClient(t),i=n?await this._secretStorage.get(this.serverSecretKey(ve,n,r)):void 0,o=n?await this._secretStorage.get(this.serverSecretKey(Ee,n,r)):void 0;return(!i||!o)&&n&&this.canUseLegacyCredential(n,r)&&(i=i||await this._secretStorage.get(this.legacyServerSecretKey(ve,n)),o=o||await this._secretStorage.get(this.legacyServerSecretKey(Ee,n))),(!i||!o)&&!n&&!r&&(i=i||await this._secretStorage.get(this.secretKey(ve)),o=o||await this._secretStorage.get(this.secretKey(Ee))),!i||!o?null:{username:i,password:o}}async reLoginForProfile(e){if(!this._secretStorage)return!1;let t=await this.getCredentialsForProfile(e.apiBaseUrl,e.osClient);return t?(await this.login(t.username,t.password,{silent:!0,apiBaseUrl:e.apiBaseUrl,osClient:e.osClient,osClientType:e.osClientType,osClientNetwork:e.osClientNetwork})).ok:!1}async recoverProfileLogin(e){let t=await this.reLoginForProfile(e);return t&&(this._isLoggedIn=!0,await this.writeMcpTokenFile()),t}startTokenRefresh(){this.stopTokenRefresh(),this.startMcpAuthRecoveryWatcher(),this.refreshAllTokens(),this._refreshTimer=setInterval(()=>{this.refreshAllTokens()},Li),this._windowStateSubscription=Se.onDidChangeWindowState(e=>{e.focused&&this.refreshAllTokens()})}stopTokenRefresh(){this._refreshTimer&&(clearInterval(this._refreshTimer),this._refreshTimer=void 0),this._windowStateSubscription&&(this._windowStateSubscription.dispose(),this._windowStateSubscription=void 0),this.stopMcpAuthRecoveryWatcher()}async logoutProfile(e){await K.getInstance().clearTokenForServer(e.apiBaseUrl,e.osClient,e.osClientType,e.osClientNetwork),this._secretStorage&&(await this._secretStorage.delete(this.serverSecretKey(ve,e.apiBaseUrl,e.osClient)),await this._secretStorage.delete(this.serverSecretKey(Ee,e.apiBaseUrl,e.osClient)),this.canUseLegacyCredential(e.apiBaseUrl,e.osClient)&&(await this._secretStorage.delete(this.legacyServerSecretKey(ve,e.apiBaseUrl)),await this._secretStorage.delete(this.legacyServerSecretKey(Ee,e.apiBaseUrl)))),await this.writeMcpTokenFile()}async logout(){if(this.stopTokenRefresh(),await K.getInstance().clearToken(),this._secretStorage){await this._secretStorage.delete(this.secretKey(ve)),await this._secretStorage.delete(this.secretKey(Ee));let t=N.getInstance().getProfiles();for(let n of t)await this._secretStorage.delete(this.serverSecretKey(ve,n.apiBaseUrl,n.osClient)),await this._secretStorage.delete(this.serverSecretKey(Ee,n.apiBaseUrl,n.osClient)),await this._secretStorage.delete(this.legacyServerSecretKey(ve,n.apiBaseUrl)),await this._secretStorage.delete(this.legacyServerSecretKey(Ee,n.apiBaseUrl))}this._isLoggedIn=!1,await et.executeCommand("setContext",ct,!1),O.info("Microi: \u5DF2\u9000\u51FA\u767B\u5F55")}};var Wi=/^\s*\*?\s*Version\s*:\s*(v\d+\.\d+\.\d+)\s*$/im,ws=/^v(\d+)\.(\d+)\.(\d+)$/;function dn(s){let e=(s||"").trim();if(!e)return null;let t=e.match(ws);if(t)return`v${Number(t[1])}.${Number(t[2])}.${Number(t[3])}`;let n=e.match(Wi);return n?dn(n[1]):null}function ks(s){if(!s)return null;let e=s.match(ws);return e?{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3])}:null}function Gi(s,e){return s.major!==e.major?s.major-e.major:s.minor!==e.minor?s.minor-e.minor:s.patch-e.patch}function zi(s){let e=null;for(let t of s){let n=ks(t);n&&(!e||Gi(n,e)>0)&&(e=n)}return e?`v${e.major}.${e.minor}.${e.patch}`:null}function Ji(s){let e=ks(s);if(!e)return"v1.0.0";let{major:t,minor:n,patch:r}=e;return r<9?`v${t}.${n}.${r+1}`:(r=0,n<9?`v${t}.${n+1}.${r}`:(n=0,t+=1,`v${t}.${n}.${r}`))}function qi(s){let e=(s||"").trim();return e?e.replace(/\r\n/g,`
|
|
34
|
+
`,{encoding:"utf8",mode:384}),se.renameSync(i,this.filePath)}finally{try{se.existsSync(i)&&se.unlinkSync(i)}catch{}try{se.closeSync(r)}catch{}try{se.unlinkSync(t)}catch{}}}readDocument(){if(!se.existsSync(this.filePath))return{version:1,values:{}};if(se.statSync(this.filePath).size>2*1024*1024)throw new Error("Microi \u5DE5\u4F5C\u533A\u51ED\u636E\u4FDD\u9669\u5E93\u8D85\u8FC7\u5B89\u5168\u5927\u5C0F\u9650\u5236\uFF0C\u5DF2\u62D2\u7EDD\u8BFB\u53D6");let e;try{e=JSON.parse(se.readFileSync(this.filePath,"utf8"))}catch{throw new Error("Microi \u5DE5\u4F5C\u533A\u51ED\u636E\u4FDD\u9669\u5E93\u65E0\u6CD5\u89E3\u6790\uFF0C\u5DF2\u4FDD\u7559\u539F\u6587\u4EF6\u4E14\u505C\u6B62\u8986\u76D6")}if(e.version!==1||e.protection!=="windows-dpapi-current-user"||typeof e.ciphertext!="string"||!e.ciphertext)throw new Error("Microi \u5DE5\u4F5C\u533A\u51ED\u636E\u4FDD\u9669\u5E93\u683C\u5F0F\u65E0\u6548\uFF0C\u5DF2\u4FDD\u7559\u539F\u6587\u4EF6\u4E14\u505C\u6B62\u8986\u76D6");try{let t=this.unprotect(Buffer.from(e.ciphertext,"base64"));if(t.length===0)return{version:1,values:{}};let n=JSON.parse(t.toString("utf8"));if(n.version!==1||!n.values||typeof n.values!="object")throw new Error("invalid document");return n.values=Object.fromEntries(Object.entries(n.values).filter(r=>typeof r[0]=="string"&&typeof r[1]=="string")),n}catch{throw new Error("Microi \u5DE5\u4F5C\u533A\u51ED\u636E\u4FDD\u9669\u5E93\u65E0\u6CD5\u7531\u5F53\u524D Windows \u7528\u6237\u89E3\u5BC6\uFF0C\u5DF2\u505C\u6B62\u8986\u76D6")}}};var Li=60*60*1e3,Ui=5*60,Ss=24*60*60,ji=2*60*1e3,Ki=60*1e3;function Hi(s,e){let t=(e||"").trim();return t?gt.publicEncrypt({key:t,padding:gt.constants.RSA_PKCS1_PADDING},Buffer.from(s,"utf-8")).toString("base64"):s}var ke=class s{constructor(){this._isLoggedIn=!1;this._refreshInProgress=!1;this._mcpTokenFilePath="";this._mcpAuthRecoveryDirPath="";this._mcpAuthRecoveryInProgress=new Set;this._mcpAuthRecoveryFailureUntil=new Map;this._mcpAuthRecoveryPassInProgress=!1;this._lastAuthWarning="";this._lastAuthWarningTime=0;this._loggedOutProfiles=new Set;this._profileAuthEpochs=new Map;this._profileLoginIntents=new Map;this._explicitLogins=new Map;this._profileAuthMutations=new Map;this.protectedMcpTokenKeys=new Set}profileIdentity(e){return this.mcpRecoveryIdentity(e.apiBaseUrl,e.osClient,e.osClientType,e.osClientNetwork)}logoutMarkerKey(e){return this.secretKey("microi.explicitLogout."+this.profileIdentity(e))}profileEpoch(e){return this._profileAuthEpochs.get(this.profileIdentity(e))||0}nextProfileEpoch(e){let t=this.profileEpoch(e)+1;return this._profileAuthEpochs.set(this.profileIdentity(e),t),t}async isProfileLoggedOut(e){let t=this.profileIdentity(e),n=this.profileEpoch(e);return this._loggedOutProfiles.has(t)?!0:(await this._secretStorage?.get(this.logoutMarkerKey(e))==="1"&&this.profileEpoch(e)===n&&this._loggedOutProfiles.add(t),this._loggedOutProfiles.has(t))}profileAuthCurrent(e,t){return this.profileEpoch(e)===t&&!this._loggedOutProfiles.has(this.profileIdentity(e))}mutateProfile(e,t){return this.mutateProfiles([e],t)}mutateProfiles(e,t){let n=Array.from(new Set(e.map(a=>this.profileIdentity(a)))),i=Promise.all(n.map(a=>this._profileAuthMutations.get(a)||Promise.resolve())).then(t,t),o=i.then(()=>{},()=>{});for(let a of n)this._profileAuthMutations.set(a,o);return o.then(()=>{for(let a of n)this._profileAuthMutations.get(a)===o&&this._profileAuthMutations.delete(a)}),i}static getInstance(){return s._instance||(s._instance=new s),s._instance}setSecretStorage(e){this._secretStorage=e,L.getInstance().setResponseTokenAdmission(t=>{let n=N.getInstance(),r=t.osClient||n.getOsClient()||"",i=n.getProfiles().filter(d=>this.normalizeApiBaseUrl(d.apiBaseUrl)===this.normalizeApiBaseUrl(t.apiBaseUrl)&&this.normalizeOsClient(d.osClient)===this.normalizeOsClient(r)&&(!t.osClientType||this.normalizeIdentityPart(d.osClientType)===this.normalizeIdentityPart(t.osClientType))&&(!t.osClientNetwork||this.normalizeIdentityPart(d.osClientNetwork)===this.normalizeIdentityPart(t.osClientNetwork))),o=i.length===1?i[0]:{label:"",...t,osClient:r},a=this.profileEpoch(o),c=this.profileIdentity(o),l=this._profileLoginIntents.get(c)||0,p=()=>i.length<=1&&this.profileAuthCurrent(o,a)&&(this._profileLoginIntents.get(c)||0)===l;return{current:p,commit:d=>this.mutateProfile(o,async()=>p()?(await L.getInstance().setToken(d,t.apiBaseUrl,t.osClient,t.osClientType,t.osClientNetwork),p()):!1)}}),L.getInstance().setTokenStateChangedHandler(async()=>{await this.writeMcpTokenFile()}),L.getInstance().setAuthRecoveryHandler(async t=>{let n=N.getInstance(),r=this.normalizeApiBaseUrl(t.apiBaseUrl),i=this.normalizeOsClient(t.osClient),o=this.normalizeIdentityPart(t.osClientType),a=this.normalizeIdentityPart(t.osClientNetwork),c=n.getProfiles().filter(d=>this.normalizeApiBaseUrl(d.apiBaseUrl)===r&&this.normalizeOsClient(d.osClient)===i),l=c.find(d=>this.normalizeIdentityPart(d.osClientType)===o&&this.normalizeIdentityPart(d.osClientNetwork)===a);if(!l&&!o&&!a&&c.length===1&&(l=c[0]),!l&&c.length===0&&(l={label:t.osClient||t.apiBaseUrl,apiBaseUrl:t.apiBaseUrl,osClient:t.osClient||"",osClientType:t.osClientType,osClientNetwork:t.osClientNetwork}),!l)return this.showAuthExpiredWarning("\u68C0\u6D4B\u5230\u540C\u4E00\u670D\u52A1\u5668\u4E0E\u79DF\u6237\u5B58\u5728\u591A\u4E2A\u8FDE\u63A5\u73AF\u5883\uFF0C\u65E0\u6CD5\u5B89\u5168\u5224\u65AD\u5E94\u6062\u590D\u54EA\u4E00\u4E2A\u767B\u5F55\u8EAB\u4EFD\u3002"),!1;let p=await this.reLoginForProfile(l);return p&&(this._isLoggedIn=!0,await et.executeCommand("setContext",ct,!0)),await this.writeMcpTokenFile(),p})}setMcpTokenFilePath(e){this._mcpTokenFilePath=e,this._mcpAuthRecoveryDirPath=e?`${e}.recovery`:""}enableProtectedMcpTokens(e){let t=this.normalizeApiBaseUrl(e.apiBaseUrl),n=this.normalizeOsClient(e.osClient);this.protectedMcpTokenKeys.add(this.mcpRecoveryIdentity(t,n,e.osClientType,e.osClientNetwork)),this.protectedMcpTokenKeys.add(n?`${t}|${n}`:t)}get mcpTokenFilePath(){return this._mcpTokenFilePath}get mcpAuthRecoveryDirPath(){return this._mcpAuthRecoveryDirPath}async loadMcpTokenFile(){if(!this._mcpTokenFilePath||!z.existsSync(this._mcpTokenFilePath))return 0;let e;try{let i=JSON.parse(z.readFileSync(this._mcpTokenFilePath,"utf-8"));if(!i||typeof i!="object"||Array.isArray(i))return 0;for(let[o,a]of Object.entries(i))Ot(a)&&this.protectedMcpTokenKeys.add(o);e=Object.fromEntries(Object.entries(i).map(([o,a])=>[o,ir(a)]))}catch{return 0}let t=L.getInstance(),n=N.getInstance().getProfiles(),r=[];for(let i of n){if(await this.isProfileLoggedOut(i))continue;let o=this.normalizeApiBaseUrl(i.apiBaseUrl),a=this.normalizeOsClient(i.osClient),c=this.mcpRecoveryIdentity(o,a,i.osClientType,i.osClientNetwork),p=n.filter(y=>this.normalizeApiBaseUrl(y.apiBaseUrl)===o&&this.normalizeOsClient(y.osClient)===a).length===1?[[o,a,i.osClientType,i.osClientNetwork].filter(Boolean).join("|"),[o,a,i.osClientType].filter(Boolean).join("|"),a?`${o}|${a}`:o]:[],d=typeof e[c]=="string"&&String(e[c]).trim()?String(e[c]).trim():"",u=p.map(y=>e[y]).find(y=>typeof y=="string"&&y.trim()),g=t.getTokenForServer(i.apiBaseUrl,i.osClient,i.osClientType,i.osClientNetwork),m=t.getExactTokenForServer(i.apiBaseUrl,i.osClient,i.osClientType,i.osClientNetwork),f=ut(g,d||u,!!d&&!m);!f||m===f||r.push({token:f,apiBaseUrl:i.apiBaseUrl,osClient:i.osClient,osClientType:i.osClientType,osClientNetwork:i.osClientNetwork,authEpoch:this.profileEpoch(i),profile:i})}return t.adoptTokensFromSharedFile(r.filter(i=>this.profileAuthCurrent(i.profile,i.authEpoch)))}get isLoggedIn(){return this._isLoggedIn}secretKey(e){return N.getInstance().getWorkspaceSecretKey(e)}normalizeApiBaseUrl(e){return(e||"").trim().replace(/\/+$/,"")}normalizeOsClient(e){return(e||"").trim()}normalizeIdentityPart(e){return(e||"").trim()}mcpRecoveryIdentity(e,t,n,r){return[this.normalizeApiBaseUrl(e),this.normalizeOsClient(t),this.normalizeIdentityPart(n),this.normalizeIdentityPart(r)].join("|")}serverSecretKey(e,t,n){return this.secretKey(`${e}.${this.normalizeApiBaseUrl(t)}|${this.normalizeOsClient(n)}`)}getCredentialSecretKeys(e){return{usernameKey:this.serverSecretKey(ve,e.apiBaseUrl,e.osClient),passwordKey:this.serverSecretKey(Ee,e.apiBaseUrl,e.osClient)}}legacyServerSecretKey(e,t){return this.secretKey(`${e}.${this.normalizeApiBaseUrl(t)}`)}canUseLegacyCredential(e,t){let n=this.normalizeApiBaseUrl(e),r=this.normalizeOsClient(t);if(!n)return!1;let i=N.getInstance().getProfiles().filter(a=>this.normalizeApiBaseUrl(a.apiBaseUrl)===n);if(i.length===0)return!r;if(i.length===1)return!0;let o=i.filter(a=>this.normalizeOsClient(a.osClient)===r);return!!r&&o.length===i.length}async writeMcpTokenFile(){if(!this._mcpTokenFilePath)return;let e=L.getInstance(),t=N.getInstance(),n=t.getProfiles(),r=this._mcpTokenFilePath;if(!(n.some(f=>!!this.normalizeApiBaseUrl(f.apiBaseUrl)&&!!this.normalizeOsClient(f.osClient))||!!this.normalizeApiBaseUrl(t.getApiBaseUrl())&&!!this.normalizeOsClient(t.getOsClient()))&&!z.existsSync(r))return;let o={},a=new Set,c=[];for(let f of n){let y=this.normalizeApiBaseUrl(f.apiBaseUrl),C=this.normalizeOsClient(f.osClient),h=this.mcpRecoveryIdentity(y,C,f.osClientType,f.osClientNetwork);a.add(h);let S=n.filter(I=>this.normalizeApiBaseUrl(I.apiBaseUrl)===y&&this.normalizeOsClient(I.osClient)===C),b=C?`${y}|${C}`:y;S.length===1&&a.add(b);let k=await this.isProfileLoggedOut(f)?"":e.getTokenForServer(f.apiBaseUrl,f.osClient,f.osClientType,f.osClientNetwork);c.push({profile:f,exactKey:h,legacyKey:S.length===1?b:void 0,currentToken:k,currentExactToken:e.getExactTokenForServer(f.apiBaseUrl,f.osClient,f.osClientType,f.osClientNetwork)}),k&&(o[h]=k,S.length===1&&(o[b]=k))}let l=$t.dirname(r);z.existsSync(l)||z.mkdirSync(l,{recursive:!0});let p=`${r}.lock`,d=Date.now()+3e3,u;for(;u===void 0;)try{u=z.openSync(p,"wx",384),z.writeFileSync(u,JSON.stringify({pid:process.pid,createdAt:Date.now()}),"utf-8")}catch(f){if(f.code!=="EEXIST")throw f;try{Date.now()-z.statSync(p).mtimeMs>3e4&&z.unlinkSync(p)}catch{}if(Date.now()>=d)throw new Error("Microi MCP Token \u6587\u4EF6\u6B63\u5728\u88AB CLI \u6216 VS Code \u63D2\u4EF6\u4FEE\u6539\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");await new Promise(y=>setTimeout(y,40))}let g=`${r}.${process.pid}.${Date.now()}.tmp`,m=[];try{let f={};if(z.existsSync(r)){let h=JSON.parse(z.readFileSync(r,"utf-8"));if(!h||typeof h!="object"||Array.isArray(h))throw new Error(`Microi MCP Token \u6587\u4EF6\u5FC5\u987B\u662F JSON \u5BF9\u8C61\uFF0C\u5DF2\u4FDD\u7559\u539F\u6587\u4EF6\uFF1A${r}`);for(let[S,b]of Object.entries(h))Ot(b)&&this.protectedMcpTokenKeys.add(S);f=Object.fromEntries(Object.entries(h).filter(S=>typeof S[1]=="string"&&!!S[1]).map(([S,b])=>[S,ir(b)]))}for(let h of c){if(delete o[h.exactKey],h.legacyKey&&delete o[h.legacyKey],this._loggedOutProfiles.has(this.profileIdentity(h.profile)))continue;h.currentToken=e.getTokenForServer(h.profile.apiBaseUrl,h.profile.osClient,h.profile.osClientType,h.profile.osClientNetwork),h.currentExactToken=e.getExactTokenForServer(h.profile.apiBaseUrl,h.profile.osClient,h.profile.osClientType,h.profile.osClientNetwork);let S=f[h.exactKey]||"",b=h.legacyKey&&f[h.legacyKey]||"",E=ut(h.currentToken,S||b,!!S&&!h.currentExactToken);E&&(o[h.exactKey]=E,h.legacyKey&&(o[h.legacyKey]=E),E!==h.currentExactToken&&m.push({profile:h.profile,token:E,authEpoch:this.profileEpoch(h.profile)}))}for(let h of a)delete f[h];let y={...f,...o},C=Object.fromEntries(Object.entries(y).map(([h,S])=>[h,this.protectedMcpTokenKeys.has(h)?ys(S):S]));z.writeFileSync(g,`${JSON.stringify(C,null,2)}
|
|
35
|
+
`,{encoding:"utf-8",mode:384});for(let h=0;;h++)try{z.renameSync(g,r);break}catch(S){let b=S.code;if(!["EPERM","EACCES","EBUSY"].includes(b||"")||h>=3)throw S;await new Promise(E=>setTimeout(E,20*2**h))}}finally{try{z.existsSync(g)&&z.unlinkSync(g)}catch{}try{z.closeSync(u)}catch{}try{z.unlinkSync(p)}catch{}}await e.adoptTokensFromSharedFile(m.filter(f=>this.profileAuthCurrent(f.profile,f.authEpoch)).map(f=>({token:f.token,apiBaseUrl:f.profile.apiBaseUrl,osClient:f.profile.osClient,osClientType:f.profile.osClientType,osClientNetwork:f.profile.osClientNetwork})))}tokenFingerprint(e){return gt.createHash("sha256").update(String(e||"")).digest("hex")}deleteMcpAuthRecoveryRequests(e,t){let n=this._mcpAuthRecoveryDirPath;if(!n||!z.existsSync(n))return;let r=[];try{r=z.readdirSync(n).filter(i=>i.endsWith(".json")).slice(0,200)}catch{return}for(let i of r){let o=$t.join(n,i);try{let a=JSON.parse(z.readFileSync(o,"utf-8")),c=this.normalizeApiBaseUrl(String(a.apiBaseUrl||"")),l=this.normalizeOsClient(String(a.osClient||"")),p=this.normalizeIdentityPart(String(a.osClientType||"")),d=this.normalizeIdentityPart(String(a.osClientNetwork||"")),u=this.mcpRecoveryIdentity(c,l,p,d);if(!p&&!d){let g=t.filter(m=>this.normalizeApiBaseUrl(m.apiBaseUrl)===c&&this.normalizeOsClient(m.osClient)===l);g.length===1&&(u=this.mcpRecoveryIdentity(g[0].apiBaseUrl,g[0].osClient,g[0].osClientType,g[0].osClientNetwork))}u===e&&z.unlinkSync(o)}catch{}}}async processMcpAuthRecoveryRequests(){let e=this._mcpAuthRecoveryDirPath;if(!(!e||!z.existsSync(e)||this._mcpAuthRecoveryPassInProgress)){this._mcpAuthRecoveryPassInProgress=!0;try{let t=[];try{t=z.readdirSync(e).filter(o=>o.endsWith(".json")).slice(0,100)}catch{return}let r=N.getInstance().getProfiles(),i=L.getInstance();for(let o of t){let a=$t.join(e,o),c={};try{c=JSON.parse(z.readFileSync(a,"utf-8"))}catch{try{z.unlinkSync(a)}catch{}continue}let l=Number(c.requestedAt||0),p=this.normalizeApiBaseUrl(String(c.apiBaseUrl||"")),d=this.normalizeOsClient(String(c.osClient||"")),u=this.normalizeIdentityPart(String(c.osClientType||"")),g=this.normalizeIdentityPart(String(c.osClientNetwork||"")),m=String(c.failedTokenHash||"").trim().toLowerCase();if(Number(c.version)!==1||!p||!l||Math.abs(Date.now()-l)>ji||!ls(m)){try{z.unlinkSync(a)}catch{}continue}let f=r.filter(h=>this.normalizeApiBaseUrl(h.apiBaseUrl)===p&&this.normalizeOsClient(h.osClient)===d),y=u||g?f.find(h=>this.normalizeIdentityPart(h.osClientType)===u&&this.normalizeIdentityPart(h.osClientNetwork)===g):f.length===1?f[0]:void 0;if(!y){try{z.unlinkSync(a)}catch{}continue}let C=this.mcpRecoveryIdentity(y.apiBaseUrl,y.osClient,y.osClientType,y.osClientNetwork);if(await this.isProfileLoggedOut(y)){this.deleteMcpAuthRecoveryRequests(C,r);continue}if(!this._mcpAuthRecoveryInProgress.has(C)){if((this._mcpAuthRecoveryFailureUntil.get(C)||0)>Date.now()){this.deleteMcpAuthRecoveryRequests(C,r);continue}this._mcpAuthRecoveryInProgress.add(C);try{let h=i.getTokenForServer(y.apiBaseUrl,y.osClient,y.osClientType,y.osClientNetwork);h&&this.tokenFingerprint(h)!==m?(this._mcpAuthRecoveryFailureUntil.delete(C),await this.writeMcpTokenFile()):(h&&await i.clearTokenForServer(y.apiBaseUrl,y.osClient,y.osClientType,y.osClientNetwork,h),await this.reLoginForProfile(y)?this._mcpAuthRecoveryFailureUntil.delete(C):(this._mcpAuthRecoveryFailureUntil.set(C,Date.now()+Ki),this.showAuthExpiredWarning("MCP \u8EAB\u4EFD\u5DF2\u5931\u6548\uFF0C\u4FDD\u5B58\u7684\u51ED\u636E\u65E0\u6CD5\u9759\u9ED8\u6062\u590D\uFF1B\u82E5\u670D\u52A1\u5668\u542F\u7528\u4E86\u9A8C\u8BC1\u7801\uFF0C\u8BF7\u5728\u63D2\u4EF6\u914D\u7F6E\u4E2D\u4EA4\u4E92\u5F0F\u91CD\u65B0\u767B\u5F55\u3002")))}finally{this._mcpAuthRecoveryInProgress.delete(C),this.deleteMcpAuthRecoveryRequests(C,r)}}}}finally{this._mcpAuthRecoveryPassInProgress=!1}}}startMcpAuthRecoveryWatcher(){this._mcpAuthRecoveryTimer||!this._mcpAuthRecoveryDirPath||(this._mcpAuthRecoveryTimer=setInterval(()=>{this.processMcpAuthRecoveryRequests()},1e3),this.processMcpAuthRecoveryRequests())}stopMcpAuthRecoveryWatcher(){this._mcpAuthRecoveryTimer&&(clearInterval(this._mcpAuthRecoveryTimer),this._mcpAuthRecoveryTimer=void 0)}async tryAutoLogin(){let e=L.getInstance(),n=N.getInstance().getProfiles(),r=!1,i=await e.loadToken(),o=await this.loadMcpTokenFile();r=!!i||o>0||e.hasToken;let a=n.filter(d=>!e.getTokenForServer(d.apiBaseUrl,d.osClient,d.osClientType,d.osClientNetwork)),c=0,l=async()=>{for(;c<a.length;){let d=a[c++];await this.reLoginForProfile(d)&&(r=!0)}},p=Math.min(4,a.length);return await Promise.all(Array.from({length:p},()=>l())),r&&(this._isLoggedIn=!0,await et.executeCommand("setContext",ct,!0),await this.writeMcpTokenFile()),r}async getSysConfig(e,t,n,r=!1){let i=L.getInstance(),o=N.getInstance();try{let a=await i.request({method:"POST",path:H.GET_SYS_CONFIG,body:{_SearchEqual:{IsEnable:1},OsClient:t||o.getOsClient()||void 0},apiBaseUrl:e,osClient:t,allowAuthRetry:!1,silent:r});if(a.Code===1&&a.Data)return a.Data;n&&(n.message=a.Code!==1?`\u670D\u52A1\u5668\u8FD4\u56DE\u9519\u8BEF (Code: ${a.Code})${a.Msg?"\uFF1A"+a.Msg:""}\uFF0C\u8BF7\u68C0\u67E5 OsClient \u662F\u5426\u6B63\u786E`:"\u670D\u52A1\u5668\u672A\u8FD4\u56DE\u914D\u7F6E\u6570\u636E")}catch(a){n&&(n.message=a instanceof Error?a.message:String(a))}return null}async getCaptcha(e,t){let n=L.getInstance(),r=N.getInstance();try{let i=await n.getRaw(H.GET_CAPTCHA,{OsClient:t||r.getOsClient()||""},e);if(i.data&&i.captchaId){let o=i.data.toString("base64");return{captchaId:i.captchaId,imageBase64:`data:image/png;base64,${o}`}}}catch{}return null}async login(e,t,n={}){let r=L.getInstance(),i=N.getInstance(),o=n.osClient||i.getOsClient(),a=n.silent??!1,c={label:o||"",apiBaseUrl:n.apiBaseUrl||i.getApiBaseUrl(),osClient:o,osClientType:n.osClientType,osClientNetwork:n.osClientNetwork},l=this.profileEpoch(c),p=this.profileIdentity(c);if(n.automatic&&this._explicitLogins.has(p))return{ok:!1,msg:"\u7528\u6237\u6B63\u5728\u767B\u5F55\uFF0C\u540E\u53F0\u6062\u590D\u5DF2\u8DF3\u8FC7\u3002"};let d=(this._profileLoginIntents.get(p)||0)+1;this._profileLoginIntents.set(p,d),n.automatic||this._explicitLogins.set(p,d);let u=()=>{if(this.profileEpoch(c)!==l||this._profileLoginIntents.get(p)!==d)throw new Error("\u8BE5\u8FDE\u63A5\u5DF2\u9000\u51FA\u6216\u88AB\u65B0\u7684\u767B\u5F55\u66FF\u6362\uFF0C\u8BF7\u91CD\u65B0\u767B\u5F55\u3002")};try{let g=await this.getSysConfig(n.apiBaseUrl,o,void 0,a);u();let m=g?.EnableCaptcha;if((m===!0||m===1||String(m||"").trim().toLowerCase()==="true")&&(!n.captchaId||!n.captchaValue)){let k="\u670D\u52A1\u5668\u5DF2\u5F00\u542F\u56FE\u5F62\u9A8C\u8BC1\u7801\uFF0C\u8BF7\u5728\u63D2\u4EF6\u914D\u7F6E\u4E2D\u4EA4\u4E92\u5F0F\u767B\u5F55\u3002";return a||F.error(`Microi: \u767B\u5F55\u5931\u8D25 - ${k}`),{ok:!1,msg:k}}let y=typeof g?.LoginRsaPublicKey=="string"&&g.LoginRsaPublicKey.trim()?g.LoginRsaPublicKey:Vr,C=Hi(t,y),h={Account:e,Pwd:C,OsClient:o||void 0,_ClientType:"VSCode"};n.captchaId&&n.captchaValue&&(h._CaptchaId=n.captchaId,h._CaptchaValue=n.captchaValue);let S=await r.request({method:"POST",path:H.LOGIN,persistResponseToken:!1,body:h,bodyFormat:"form",apiBaseUrl:n.apiBaseUrl,osClient:n.osClient,osClientType:n.osClientType,osClientNetwork:n.osClientNetwork,allowAuthRetry:!1,silent:a});u();let E=S._headers?.authorization||"";if(S.Code===1)return await this.mutateProfile(c,async()=>{if(u(),await this.isProfileLoggedOut(c)&&!E)throw new Error("\u767B\u5F55\u54CD\u5E94\u7F3A\u5C11\u65B0\u4F1A\u8BDD\uFF0C\u4FDD\u6301\u5DF2\u9000\u51FA\u72B6\u6001\u3002");return u(),l=this.nextProfileEpoch(c),await this._secretStorage?.delete(this.logoutMarkerKey(c)),u(),this._loggedOutProfiles.delete(this.profileIdentity(c)),E&&(await r.setToken(E,n.apiBaseUrl,n.osClient,n.osClientType,n.osClientNetwork),u()),this._secretStorage&&(n.apiBaseUrl?(await this._secretStorage.store(this.serverSecretKey(ve,n.apiBaseUrl,o),e),u(),await this._secretStorage.store(this.serverSecretKey(Ee,n.apiBaseUrl,o),t),u()):(await this._secretStorage.store(this.secretKey(ve),e),u(),await this._secretStorage.store(this.secretKey(Ee),t),u())),S.Data?.OsClient&&!o&&await i.updateSettings({osClient:S.Data.OsClient}),u(),this._isLoggedIn=!0,await et.executeCommand("setContext",ct,!0),u(),await this.writeMcpTokenFile(),u(),a||F.info(`Microi: \u767B\u5F55\u6210\u529F\uFF0C\u6B22\u8FCE ${S.Data?.Name||S.Data?.Account||e}`),{ok:!0,msg:""}});{let k=S.Msg||"\u8BF7\u68C0\u67E5\u8D26\u53F7\u5BC6\u7801";return a||F.error(`Microi: \u767B\u5F55\u5931\u8D25 - ${k}`),{ok:!1,msg:k}}}catch(g){let m=g instanceof Error?g.message:String(g);return a||F.error(`Microi: \u767B\u5F55\u5931\u8D25 - ${m}`),{ok:!1,msg:m}}finally{!n.automatic&&this._explicitLogins.get(p)===d&&this._explicitLogins.delete(p)}}async refreshAllTokens(){if(this._refreshInProgress)return;this._refreshInProgress=!0;let e=L.getInstance(),n=N.getInstance().getProfiles();try{for(let r of n){let i=this.profileEpoch(r);if(await this.isProfileLoggedOut(r)||!this.profileAuthCurrent(r,i))continue;let o=e.getTokenForServer(r.apiBaseUrl,r.osClient,r.osClientType,r.osClientNetwork);if(!o){await this.reLoginForProfile(r);continue}try{let g=await e.request({method:"GET",path:H.GET_STATUS,apiBaseUrl:r.apiBaseUrl,osClient:r.osClient,osClientType:r.osClientType,osClientNetwork:r.osClientNetwork,allowAuthRetry:!1,silent:!0});if(!this.profileAuthCurrent(r,i)||It(g))continue;if(sn(g)){await e.clearTokenForServer(r.apiBaseUrl,r.osClient,r.osClientType,r.osClientNetwork,o),await this.reLoginForProfile(r)||this.showAuthExpiredWarning(g.Msg||"\u5F53\u524D\u767B\u5F55\u8EAB\u4EFD\u5DF2\u5931\u6548\uFF0C\u8BF7\u91CD\u65B0\u767B\u5F55\u3002");continue}}catch{}if(!this.profileAuthCurrent(r,i))continue;let a=this.readJwtClientClaims(o),c=String(a?.ClientType||"").trim(),l=c.toLowerCase()!=="vscode",p=!c||c.toLowerCase()==="empty";if(l&&(await this.reLoginForProfile(r)||!p)||!this.profileAuthCurrent(r,i))continue;let d=String(a?.Did||"").trim(),u=c.toLowerCase()==="vscode"&&d!==e.getDeviceId();if(!(!l&&!u&&!this.shouldRefreshToken(o,a)))try{let g=await e.request({method:"POST",path:H.REFRESH_TOKEN,persistResponseToken:!1,body:{authorization:o,OsClient:r.osClient,_ClientType:"VSCode"},apiBaseUrl:r.apiBaseUrl,osClient:r.osClient,osClientType:r.osClientType,osClientNetwork:r.osClientNetwork,allowAuthRetry:!1,silent:!0});if(!this.profileAuthCurrent(r,i))continue;let f=g._headers?.authorization||"";g.Code===1&&f?await this.mutateProfile(r,async()=>{this.profileAuthCurrent(r,i)&&await e.setToken(f,r.apiBaseUrl,r.osClient,r.osClientType,r.osClientNetwork)}):(await e.clearTokenForServer(r.apiBaseUrl,r.osClient,r.osClientType,r.osClientNetwork,o),await this.reLoginForProfile(r)||this.showAuthExpiredWarning(g.Msg||"\u5F53\u524D\u767B\u5F55\u8EAB\u4EFD\u5DF2\u5931\u6548\uFF0C\u8BF7\u91CD\u65B0\u767B\u5F55\u3002"))}catch{await this.reLoginForProfile(r)}}}finally{this._isLoggedIn=e.hasToken,await et.executeCommand("setContext",ct,this._isLoggedIn),await this.writeMcpTokenFile(),this._refreshInProgress=!1}}showAuthExpiredWarning(e){let t=String(e||"\u5F53\u524D\u767B\u5F55\u8EAB\u4EFD\u5DF2\u5931\u6548\uFF0C\u8BF7\u91CD\u65B0\u767B\u5F55\u3002"),n=Date.now();t===this._lastAuthWarning&&n-this._lastAuthWarningTime<60*1e3||(this._lastAuthWarning=t,this._lastAuthWarningTime=n,F.warn(`Microi: ${t}`))}readJwtClientClaims(e){try{let n=e.replace(/^Bearer\s+/i,"").trim().split(".");if(n.length<2)return null;let r=n[1].replace(/-/g,"+").replace(/_/g,"/");return JSON.parse(Buffer.from(r,"base64").toString("utf-8"))}catch{return null}}shouldRefreshToken(e,t){let n=t??this.readJwtClientClaims(e),r=Number(n?.exp);if(!Number.isFinite(r)||r<=0)return!0;let i=Number(n?.MicroiTokenIssuedAt??n?.iat),o=Number.isFinite(i)&&i>0&&r>i?r-i:Ss,a=Math.min(Ss,Math.max(Ui,Math.floor(o/10)));return r-Math.floor(Date.now()/1e3)<=a}async getCredentialsForProfile(e,t){if(!this._secretStorage)return null;let n=this.normalizeApiBaseUrl(e),r=this.normalizeOsClient(t),i=n?await this._secretStorage.get(this.serverSecretKey(ve,n,r)):void 0,o=n?await this._secretStorage.get(this.serverSecretKey(Ee,n,r)):void 0;return(!i||!o)&&n&&this.canUseLegacyCredential(n,r)&&(i=i||await this._secretStorage.get(this.legacyServerSecretKey(ve,n)),o=o||await this._secretStorage.get(this.legacyServerSecretKey(Ee,n))),(!i||!o)&&!n&&!r&&(i=i||await this._secretStorage.get(this.secretKey(ve)),o=o||await this._secretStorage.get(this.secretKey(Ee))),!i||!o?null:{username:i,password:o}}async reLoginForProfile(e){if(!this._secretStorage)return!1;let t=this.profileEpoch(e);if(await this.isProfileLoggedOut(e)||!this.profileAuthCurrent(e,t))return!1;let n=await this.getCredentialsForProfile(e.apiBaseUrl,e.osClient);return!n||await this.isProfileLoggedOut(e)||!this.profileAuthCurrent(e,t)?!1:(await this.login(n.username,n.password,{silent:!0,automatic:!0,apiBaseUrl:e.apiBaseUrl,osClient:e.osClient,osClientType:e.osClientType,osClientNetwork:e.osClientNetwork})).ok}async recoverProfileLogin(e){let t=await this.reLoginForProfile(e);return t&&(this._isLoggedIn=!0,await this.writeMcpTokenFile()),t}startTokenRefresh(){this.stopTokenRefresh(),this.startMcpAuthRecoveryWatcher(),this.refreshAllTokens(),this._refreshTimer=setInterval(()=>{this.refreshAllTokens()},Li),this._windowStateSubscription=Se.onDidChangeWindowState(e=>{e.focused&&this.refreshAllTokens()})}stopTokenRefresh(){this._refreshTimer&&(clearInterval(this._refreshTimer),this._refreshTimer=void 0),this._windowStateSubscription&&(this._windowStateSubscription.dispose(),this._windowStateSubscription=void 0),this.stopMcpAuthRecoveryWatcher()}async logoutProfile(e){this._loggedOutProfiles.add(this.profileIdentity(e)),this.nextProfileEpoch(e),await this.mutateProfile(e,async()=>{await this._secretStorage?.store(this.logoutMarkerKey(e),"1"),await L.getInstance().clearTokenForServer(e.apiBaseUrl,e.osClient,e.osClientType,e.osClientNetwork);let t=N.getInstance().getProfiles().some(n=>this.profileIdentity(n)!==this.profileIdentity(e)&&this.normalizeApiBaseUrl(n.apiBaseUrl)===this.normalizeApiBaseUrl(e.apiBaseUrl)&&this.normalizeOsClient(n.osClient)===this.normalizeOsClient(e.osClient));this._secretStorage&&!t&&(await this._secretStorage.delete(this.serverSecretKey(ve,e.apiBaseUrl,e.osClient)),await this._secretStorage.delete(this.serverSecretKey(Ee,e.apiBaseUrl,e.osClient)),this.canUseLegacyCredential(e.apiBaseUrl,e.osClient)&&(await this._secretStorage.delete(this.legacyServerSecretKey(ve,e.apiBaseUrl)),await this._secretStorage.delete(this.legacyServerSecretKey(Ee,e.apiBaseUrl)))),await this.writeMcpTokenFile(),this._isLoggedIn=L.getInstance().hasToken})}async logout(){this.stopTokenRefresh();let e=L.getInstance(),t=N.getInstance().getProfiles();for(let n of t)this._loggedOutProfiles.add(this.profileIdentity(n)),this.nextProfileEpoch(n);await this.mutateProfiles(t,async()=>{for(let n of t)await this._secretStorage?.store(this.logoutMarkerKey(n),"1");if(await e.clearToken(),this._secretStorage){await this._secretStorage.delete(this.secretKey(ve)),await this._secretStorage.delete(this.secretKey(Ee));let n=N.getInstance().getProfiles();for(let r of n)await this._secretStorage.delete(this.serverSecretKey(ve,r.apiBaseUrl,r.osClient)),await this._secretStorage.delete(this.serverSecretKey(Ee,r.apiBaseUrl,r.osClient)),await this._secretStorage.delete(this.legacyServerSecretKey(ve,r.apiBaseUrl)),await this._secretStorage.delete(this.legacyServerSecretKey(Ee,r.apiBaseUrl))}this._isLoggedIn=!1,await et.executeCommand("setContext",ct,!1),F.info("Microi: \u5DF2\u9000\u51FA\u767B\u5F55")})}};var Wi=/^\s*\*?\s*Version\s*:\s*(v\d+\.\d+\.\d+)\s*$/im,ws=/^v(\d+)\.(\d+)\.(\d+)$/;function dn(s){let e=(s||"").trim();if(!e)return null;let t=e.match(ws);if(t)return`v${Number(t[1])}.${Number(t[2])}.${Number(t[3])}`;let n=e.match(Wi);return n?dn(n[1]):null}function ks(s){if(!s)return null;let e=s.match(ws);return e?{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3])}:null}function Gi(s,e){return s.major!==e.major?s.major-e.major:s.minor!==e.minor?s.minor-e.minor:s.patch-e.patch}function zi(s){let e=null;for(let t of s){let n=ks(t);n&&(!e||Gi(n,e)>0)&&(e=n)}return e?`v${e.major}.${e.minor}.${e.patch}`:null}function Ji(s){let e=ks(s);if(!e)return"v1.0.0";let{major:t,minor:n,patch:r}=e;return r<9?`v${t}.${n}.${r+1}`:(r=0,n<9?`v${t}.${n+1}.${r}`:(n=0,t+=1,`v${t}.${n}.${r}`))}function qi(s){let e=(s||"").trim();return e?e.replace(/\r\n/g,`
|
|
36
36
|
`).split(`
|
|
37
|
-
`).map(t=>t.trim()).filter(Boolean):["\u8BF7\u8865\u5145\u8BE5 V8 \u4EE3\u7801\u7684\u5B8C\u6574\u529F\u80FD\u8BF4\u660E\u3002"]}function
|
|
37
|
+
`).map(t=>t.trim()).filter(Boolean):["\u8BF7\u8865\u5145\u8BE5 V8 \u4EE3\u7801\u7684\u5B8C\u6574\u529F\u80FD\u8BF4\u660E\u3002"]}function Yi(s){let e=s.replace(/\r\n/g,`
|
|
38
38
|
`).split(`
|
|
39
39
|
`),t=[],n=!1;for(let r of e){let i=r.replace(/^\s*\/\*+\s?/,"").replace(/^\s*\*\/?\s?/,"").trim();if(/^(Function|功能说明)\s*[::]/i.test(i)){n=!0;let o=i.replace(/^(Function|功能说明)\s*[::]\s*/i,"").trim();o&&t.push(o.replace(/^[-*]\s*/,""));continue}if(/^(ChangeLog|修改记录|LastModified|Version|ApiEngineKey|TableKey|WorkflowKey|EventType)\s*[::]/i.test(i)){if(n)break;continue}n&&i&&i!=="*/"&&t.push(i.replace(/^[-*]\s*/,""))}return t.length?t.join(`
|
|
40
|
-
`):void 0}function or(s){let e=s.match(/^\s*(\/\*[\s\S]*?\*\/)\s*/);return e?{comment:e[1],rest:s.slice(e[0].length)}:null}function Cs(s){return/^\/\*\s*OFFICIAL_(?:MANAGED|CREATE_IF_MISSING)_API_ENGINE_NOTICE_V1\b/i.test(s)}function bs(s){return/Microi\s+V8|V8\s+(?:ApiEngine|Event|Workflow)|Version\s*:|ChangeLog\s*:|TableKey\s*:|WorkflowKey\s*:/i.test(s)}function
|
|
40
|
+
`):void 0}function or(s){let e=s.match(/^\s*(\/\*[\s\S]*?\*\/)\s*/);return e?{comment:e[1],rest:s.slice(e[0].length)}:null}function Cs(s){return/^\/\*\s*OFFICIAL_(?:MANAGED|CREATE_IF_MISSING)_API_ENGINE_NOTICE_V1\b/i.test(s)}function bs(s){return/Microi\s+V8|V8\s+(?:ApiEngine|Event|Workflow)|Version\s*:|ChangeLog\s*:|TableKey\s*:|WorkflowKey\s*:/i.test(s)}function Qi(s){let e=s.replace(/^\uFEFF/,""),t=or(e);if(!t)return{body:e};if(Cs(t.comment)){let r=or(t.rest);return r&&bs(r.comment)?{notice:t.comment,header:r.comment,body:r.rest}:{notice:t.comment,body:t.rest}}if(!bs(t.comment))return{body:e};let n=or(t.rest);return n&&Cs(n.comment)?{notice:n.comment,header:t.comment,body:n.rest}:{header:t.comment,body:t.rest}}function Xi(s,e,t){let n=s.functionDescription||Yi(t||""),r=qi(n),i=s.kind==="ApiEngine"?"V8 ApiEngine":s.kind==="V8Event"?"V8 Event":"V8 Workflow",o=s.kind==="ApiEngine"?"ApiEngineKey":s.kind==="V8Event"?"TableKey":"WorkflowKey",a=["/*",` * ${i}`,` * ${o}: ${s.key}`];s.eventType&&a.push(` * EventType: ${s.eventType}`),a.push(` * Version: ${e}`),a.push(" * Function:");for(let c of r)a.push(` * - ${c}`);return a.push(" */"),`${a.join(`
|
|
41
41
|
`)}
|
|
42
42
|
|
|
43
|
-
`}function Bt(s){let e=dn(s.currentCode),t=dn(s.remoteCode),n=dn(s.remoteVersion),r=zi([e,t,n]),i=s.initial?r||"v1.0.0":Ji(r),{notice:o,header:a,body:c}=
|
|
43
|
+
`}function Bt(s){let e=dn(s.currentCode),t=dn(s.remoteCode),n=dn(s.remoteVersion),r=zi([e,t,n]),i=s.initial?r||"v1.0.0":Ji(r),{notice:o,header:a,body:c}=Qi(s.currentCode||""),p=`${o?`${o.trim()}
|
|
44
44
|
|
|
45
|
-
`:""}${Xi(s,i,a)}${c.replace(/^\s+/,"")}`,
|
|
46
|
-
`,"utf-8"),v.renameSync(a,o)}finally{try{v.existsSync(a)&&v.unlinkSync(a)}catch{}}}catch{}}getWorkspaceFilePath(e){let t=N.getInstance().getWorkspaceRoot();return t?
|
|
47
|
-
`).trimEnd()}isLocalModified(e,t){try{if(!v.existsSync(e))return!1;let n=v.statSync(e),r=new Date(t);return isNaN(r.getTime())?!1:n.mtime.getTime()>r.getTime()+1e3}catch{return!1}}getLocalModifiedTime(e,t){try{if(!v.existsSync(e))return null;let n=v.statSync(e),r=new Date(t);return isNaN(r.getTime())?null:n.mtime.getTime()>r.getTime()+1e3?Te(n.mtime):null}catch{return null}}touchSyncedFile(e,t){let n=new Date(t),r=isNaN(n.getTime())?new Date:n;try{v.utimesSync(e,r,r)}catch{}}ensureSyncGitExcludes(e){try{let t=e||N.getInstance().getSyncRootDir();lt(t),Ue(t,[".backups/","**/.backups/",".microi-mcp-tokens.json","**/.microi-mcp-tokens.json"])}catch{}}shortBackupKey(e){return require("crypto").createHash("sha1").update(e||"").digest("hex").slice(0,10)}getMenuButtonMetaKey(e,t,n,r){return`${e}__${t}__${n}__${r}`}getMenuScriptMetaKey(e,t){return`${e}__${t}`}sourceHash(e){return require("crypto").createHash("sha256").update(this.normalizeCode(e||"")).digest("hex")}extractTrailingKey(e){let t=e.match(/[((]([^))]+)[))]\s*$/);return t?t[1]:e}getServerDirs(){try{let e=N.getInstance().getSyncRootDir();return v.existsSync(e)?v.readdirSync(e,{withFileTypes:!0}).filter(t=>t.isDirectory()).filter(t=>!t.name.startsWith(".")).map(t=>t.name):[]}catch{return[]}}getLocalChangeSummary(){let e={engines:0,events:0,fields:0,menuButtons:0,menuScripts:0,workflowNodeEvents:0,total:0};for(let t of this.getLocalChangeItems())t.kind==="engine"?e.engines+=1:t.kind==="event"?e.events+=1:t.kind==="field"?e.fields+=1:t.kind==="menuButton"?e.menuButtons+=1:t.kind==="menuScript"?e.menuScripts+=1:t.kind==="workflow"&&(e.workflowNodeEvents+=1);return e.total=e.engines+e.events+e.fields+e.menuButtons+e.menuScripts+e.workflowNodeEvents,e}getLocalChangeItems(){let e=[],t=(n,r,i,o,a)=>{let c=this.getWorkspaceFilePath(a.filePath);if(!c)return;let l=this.getLocalModifiedTime(c,a.updateTime);l&&e.push({kind:r,key:i,name:o,serverDir:n,filePath:c,updateTime:a.updateTime,modifiedTime:l})};for(let n of this.getServerDirs()){let r=this.loadMeta(n);for(let[i,o]of Object.entries(r.engines))t(n,"engine",i,o.apiName||i,o);for(let[i,o]of Object.entries(r.events))t(n,"event",i,`${o.description||o.formEngineKey}/${o.eventType}`,o);for(let[i,o]of Object.entries(r.fields||{}))t(n,"field",i,`${o.tableName}.${o.fieldName}/${o.v8Key}`,o);for(let[i,o]of Object.entries(r.menuButtons||{}))t(n,"menuButton",i,`${o.moduleName}/${o.btnName}/${o.v8SubField}`,o);for(let[i,o]of Object.entries(r.menuScripts||{}))t(n,"menuScript",i,`${o.moduleName}/${o.scriptField}`,o);for(let[i,o]of Object.entries(r.workflowNodeEvents||{}))t(n,"workflow",i,`${o.flowName}/${o.nodeName}/${o.eventType}`,o)}return e}async checkRemoteDifferences(e,t="all",n){let r=e?[e]:N.getInstance().getProfiles(),i=[];for(let o of r){let a=N.getInstance().buildServerDirName(o.label,o.apiBaseUrl),c=this.loadMeta(a),l=n?this.getTargetSyncKind(c,n):null;if(n&&!l)throw new Error(`\u540C\u6B65\u76EE\u6807\u4E0D\u5728\u672C\u5730\u57FA\u7EBF\u4E2D: ${n}`);(t==="all"||t==="api")&&(!n||l==="engine")&&await this.collectEngineDifferences(o,a,c,i,n),(t==="all"||t==="form")&&(!n||l==="event")&&await this.collectEventDifferences(o,a,c,i,n),(t==="all"||t==="form")&&(!n||l==="field")&&await this.collectFieldDifferences(o,a,c,i,n),(t==="all"||t==="module")&&(!n||l==="menuButton")&&await this.collectMenuButtonDifferences(o,a,c,i,n),(t==="all"||t==="module")&&(!n||l==="menuScript")&&await this.collectMenuScriptDifferences(o,a,c,i,n),(t==="all"||t==="workflow")&&(!n||l==="workflow")&&await this.collectWorkflowDifferences(o,a,c,i,n)}return i}matchesTargetFile(e,t){if(!t)return!0;let n=this.getWorkspaceFilePath(e);return!!n&&E.resolve(n).toLowerCase()===E.resolve(t).toLowerCase()}getTargetSyncKind(e,t){let n=[["engine",e.engines],["event",e.events],["field",e.fields||{}],["menuButton",e.menuButtons||{}],["menuScript",e.menuScripts||{}],["workflow",e.workflowNodeEvents||{}]];for(let[r,i]of n)if(Object.values(i).some(o=>this.matchesTargetFile(o.filePath,t)))return r;return null}classifyDifference(e,t,n,r){return n===r?null:e&&t?"conflict":e?"localModified":"remoteModified"}classifyRemoteDeletion(e,t){return this.isLocalModified(e,t)?"conflict":"remoteDeleted"}createRemoteDeletedItem(e,t,n,r,i,o){return!i||!v.existsSync(i)?null:{kind:e,status:this.classifyRemoteDeletion(i,o),name:t,key:n,serverDir:r,filePath:i,localCode:this.normalizeCode(v.readFileSync(i,"utf-8")),remoteCode:"",localUpdateTime:o,remoteUpdateTime:""}}isRemoteNewer(e,t){let n=new Date(e||"").getTime(),r=new Date(t||"").getTime();return isNaN(n)||isNaN(r)?!1:n>r+1e3}getRemoteOnlyPlaceholderPath(e,t,n,r){let i=N.getInstance(),o=n==="api"?st:n==="form"?Le:n==="module"?Ge:it;return E.join(i.getSyncRootDir(),t,i.buildOsClientDirName(e.osClient,e.osClientType,e.osClientNetwork),o,"\u670D\u52A1\u5668\u65B0\u589E\u5F85\u62C9\u53D6",`${Y(r)}.js`)}async collectEngineDifferences(e,t,n,r,i){let a=await K.getInstance().get(H.GET_ENGINE_LIST,{osClient:e.osClient},e.apiBaseUrl,e);if(a.Code!==1||!Array.isArray(a.Data?.List))throw new Error(`\u83B7\u53D6\u63A5\u53E3\u5F15\u64CE\u540C\u6B65\u72B6\u6001\u5931\u8D25: ${a.Msg||"\u670D\u52A1\u5668\u8FD4\u56DE\u6570\u636E\u683C\u5F0F\u4E0D\u6B63\u786E"}`);let c=new Map(a.Data.List.map(u=>[u.ApiEngineKey,u])),l=!1;for(let[u,d]of Object.entries(n.engines)){if(!this.matchesTargetFile(d.filePath,i))continue;let g=c.get(u),m=this.getWorkspaceFilePath(d.filePath);if(!m||!v.existsSync(m))continue;if(!g){let b=this.createRemoteDeletedItem("engine",d.apiName||u,u,t,m,d.updateTime);b&&r.push(b);continue}let f=this.normalizeCode(v.readFileSync(m,"utf-8")),y=this.normalizeCode(g.ApiV8Code||""),S=this.isLocalModified(m,d.updateTime),h=this.isRemoteNewer(g.UpdateTime,d.updateTime);if(f===y){(S||h)&&g.UpdateTime&&(d.updateTime=g.UpdateTime,this.touchSyncedFile(m,g.UpdateTime),l=!0);continue}let C=this.classifyDifference(S,h,f,y);C&&r.push({kind:"engine",status:C,name:g.ApiName||d.apiName||u,key:u,serverDir:t,filePath:m,localCode:f,remoteCode:y,localUpdateTime:d.updateTime,remoteUpdateTime:g.UpdateTime})}if(l&&this.saveMeta(n,t),i)return;let p=new Set(Object.keys(n.engines).map(u=>u.toLowerCase()));for(let u of a.Data.List)!String(u.ApiV8Code||"").trim()||p.has(u.ApiEngineKey.toLowerCase())||r.push({kind:"engine",status:"remoteModified",name:u.ApiName||u.ApiEngineKey,key:u.ApiEngineKey,serverDir:t,filePath:this.getRemoteOnlyPlaceholderPath(e,t,"api",u.ApiEngineKey),localCode:"",remoteCode:this.normalizeCode(u.ApiV8Code||""),localUpdateTime:"",remoteUpdateTime:u.UpdateTime})}async collectEventDifferences(e,t,n,r,i){let a=await K.getInstance().get(H.GET_EVENT_LIST,{osClient:e.osClient},e.apiBaseUrl,e);if(a.Code!==1||!Array.isArray(a.Data?.List))throw new Error(`\u83B7\u53D6\u8868\u5355\u4E8B\u4EF6\u540C\u6B65\u72B6\u6001\u5931\u8D25: ${a.Msg||"\u670D\u52A1\u5668\u8FD4\u56DE\u6570\u636E\u683C\u5F0F\u4E0D\u6B63\u786E"}`);let c=new Map;for(let u of a.Data.List){let d=`${u.FormEngineKey}__${u.EventType}`;c.set(d,u),c.set(d.toLowerCase(),u)}let l=!1;for(let[u,d]of Object.entries(n.events)){if(!this.matchesTargetFile(d.filePath,i))continue;let g=c.get(u)||c.get(u.toLowerCase()),m=this.getWorkspaceFilePath(d.filePath);if(!m||!v.existsSync(m))continue;if(!g){let b=this.createRemoteDeletedItem("event",`${d.description||d.formEngineKey}/${d.eventType}`,u,t,m,d.updateTime);b&&r.push(b);continue}let f=this.normalizeCode(v.readFileSync(m,"utf-8")),y=this.normalizeCode(g.V8Code||""),S=this.isLocalModified(m,d.updateTime),h=this.isRemoteNewer(g.UpdateTime,d.updateTime);if(f===y){(S||h)&&g.UpdateTime&&(d.updateTime=g.UpdateTime,this.touchSyncedFile(m,g.UpdateTime),l=!0);continue}let C=this.classifyDifference(S,h,f,y);C&&r.push({kind:"event",status:C,name:`${g.Description||d.formEngineKey}/${d.eventType}`,key:u,serverDir:t,filePath:m,localCode:f,remoteCode:y,localUpdateTime:d.updateTime,remoteUpdateTime:g.UpdateTime})}if(l&&this.saveMeta(n,t),i)return;let p=new Set(Object.keys(n.events).map(u=>u.toLowerCase()));for(let u of a.Data.List){let d=`${u.FormEngineKey}__${u.EventType}`;!String(u.V8Code||"").trim()||p.has(d.toLowerCase())||r.push({kind:"event",status:"remoteModified",name:`${u.Description||u.FormEngineKey}/${u.EventType}`,key:d,serverDir:t,filePath:this.getRemoteOnlyPlaceholderPath(e,t,"form",d),localCode:"",remoteCode:this.normalizeCode(u.V8Code||""),localUpdateTime:"",remoteUpdateTime:u.UpdateTime})}}async collectFieldDifferences(e,t,n,r,i){let o=K.getInstance(),a=new Map;for(let l of Object.entries(n.fields||{})){if(!this.matchesTargetFile(l[1].filePath,i))continue;let p=a.get(l[1].tableId||l[1].tableName)||[];p.push(l),a.set(l[1].tableId||l[1].tableName,p)}let c=!1;await this.runInBatches([...a.values()],i?1:2,async l=>{let p=l[0][1],u=await o.get(H.GET_FIELD_LIST,{osClient:e.osClient,tableId:p.tableId,tableName:p.tableName},e.apiBaseUrl,e);if(u.Code!==1||!Array.isArray(u.Data?.List))throw new Error(`\u83B7\u53D6\u5B57\u6BB5\u540C\u6B65\u72B6\u6001\u5931\u8D25[${p.tableName}]: ${u.Msg||"\u670D\u52A1\u5668\u8FD4\u56DE\u6570\u636E\u683C\u5F0F\u4E0D\u6B63\u786E"}`);let d=new Map(u.Data.List.map(g=>[String(g.Name||"").toLowerCase(),g]));for(let[g,m]of l){let f=d.get(m.fieldName.toLowerCase()),y=this.getWorkspaceFilePath(m.filePath);if(!y||!v.existsSync(y))continue;if(!f||!String(f[m.v8Key]||"").trim()){let I=this.createRemoteDeletedItem("field",`${m.tableName}.${m.fieldName}/${m.v8Key}`,g,t,y,m.updateTime);I&&r.push(I);continue}let S=this.normalizeCode(v.readFileSync(y,"utf-8")),h=this.normalizeCode(String(f[m.v8Key]||"")),C=String(f.UpdateTime||""),b=this.isLocalModified(y,m.updateTime),T=this.isRemoteNewer(C,m.updateTime);if(S===h){(b||T)&&C&&(m.updateTime=C,this.touchSyncedFile(y,C),c=!0);continue}let k=this.classifyDifference(b,T,S,h);k&&r.push({kind:"field",status:k,name:`${m.tableName}.${m.fieldName}/${m.v8Key}`,key:g,serverDir:t,filePath:y,localCode:S,remoteCode:h,localUpdateTime:m.updateTime,remoteUpdateTime:C})}}),c&&this.saveMeta(n,t)}async collectMenuButtonDifferences(e,t,n,r,i){let o=K.getInstance(),a=new Map;if(!i)for(let d of Object.keys(n.menus||{}))a.set(d,[]);for(let d of Object.entries(n.menuButtons||{})){if(!this.matchesTargetFile(d[1].filePath,i))continue;let g=a.get(d[1].moduleId)||[];g.push(d),a.set(d[1].moduleId,g)}let c=[];if(!i){let d=await o.get(H.LIST_MODULES,{osClient:e.osClient},e.apiBaseUrl,e);if(d.Code!==1||!Array.isArray(d.Data?.List))throw new Error(`\u83B7\u53D6\u6A21\u5757\u540C\u6B65\u72B6\u6001\u5931\u8D25: ${d.Msg||"\u670D\u52A1\u5668\u8FD4\u56DE\u6570\u636E\u683C\u5F0F\u4E0D\u6B63\u786E"}`);c=d.Data.List}let l=new Set(c.map(d=>String(d.ParentId||"")).filter(Boolean)),p=new Map(c.map(d=>[d.Id,d]));for(let d of c){if(l.has(d.Id)||n.menus?.[d.Id])continue;let g=d.Label||d.Name||d.Id;r.push({kind:"menuButton",status:"remoteModified",name:`${g}/\u670D\u52A1\u5668\u65B0\u589E\u6A21\u5757`,key:d.Id,serverDir:t,filePath:this.getRemoteOnlyPlaceholderPath(e,t,"module",d.Id),localCode:"",remoteCode:JSON.stringify(d,null,2),localUpdateTime:"",remoteUpdateTime:String(d.UpdateTime||"")})}let u=!1;await this.runInBatches([...a.entries()],i?1:2,async([d,g])=>{let m=()=>{for(let[T,k]of g){let I=this.getWorkspaceFilePath(k.filePath);if(!I)continue;let w=this.createRemoteDeletedItem("menuButton",`${k.moduleName}/${k.btnName}/${k.v8SubField}`,T,t,I,k.updateTime);w&&r.push(w)}};if(!i&&!p.has(d)){m();return}let f=await o.get(H.GET_MODULE,{osClient:e.osClient,moduleId:d},e.apiBaseUrl,e);if(f.Code!==1||!f.Data){if(/不存在|not\s*found/i.test(String(f.Msg||""))){m();return}throw new Error(`\u83B7\u53D6\u6A21\u5757\u6309\u94AE\u540C\u6B65\u72B6\u6001\u5931\u8D25[${d}]: ${f.Msg||"\u670D\u52A1\u5668\u8FD4\u56DE\u6570\u636E\u683C\u5F0F\u4E0D\u6B63\u786E"}`)}let y=f.Data,S=String(y.UpdateTime||""),h=new Map;for(let T of Object.keys(ot)){let k=[];try{let I=y[T];k=typeof I=="string"?JSON.parse(I):Array.isArray(I)?I:[],Array.isArray(k)||(k=[])}catch{k=[]}h.set(T,new Map(k.map(I=>[String(I.Id||""),I])))}for(let[T,k]of g){let I=h.get(k.btnField)?.get(k.btnId),w=this.getWorkspaceFilePath(k.filePath);if(!w||!v.existsSync(w))continue;if(!I||!String(I[k.v8SubField]||"").trim()){let _=this.createRemoteDeletedItem("menuButton",`${k.moduleName}/${k.btnName}/${k.v8SubField}`,T,t,w,k.updateTime);_&&r.push(_);continue}let F=this.normalizeCode(v.readFileSync(w,"utf-8")),M=this.normalizeCode(String(I[k.v8SubField]||"")),D=this.isLocalModified(w,k.updateTime),x=this.isRemoteNewer(S,k.updateTime);if(F===M){(D||x)&&S&&(k.updateTime=S,this.touchSyncedFile(w,S),u=!0);continue}let P=this.classifyDifference(D,x,F,M);P&&r.push({kind:"menuButton",status:P,name:`${k.moduleName}/${k.btnName}/${k.v8SubField}`,key:T,serverDir:t,filePath:w,localCode:F,remoteCode:M,localUpdateTime:k.updateTime,remoteUpdateTime:S})}if(i)return;let C=new Set(g.map(([T])=>T)),b=n.menus?.[d]?.moduleName||p.get(d)?.Label||p.get(d)?.Name||d;for(let[T,k]of h)for(let[I,w]of k){if(!I)continue;let F=String(w.Name||I);for(let M of["V8Code","V8CodeShow"]){let D=String(w[M]||""),x=this.getMenuButtonMetaKey(d,T,I,M);!D.trim()||C.has(x)||r.push({kind:"menuButton",status:"remoteModified",name:`${b}/${F}/${M}`,key:x,serverDir:t,filePath:this.getRemoteOnlyPlaceholderPath(e,t,"module",x),localCode:"",remoteCode:this.normalizeCode(D),localUpdateTime:"",remoteUpdateTime:S})}}}),u&&this.saveMeta(n,t)}async collectMenuScriptDifferences(e,t,n,r,i){let o=K.getInstance(),a=Object.entries(n.menuScripts||{}).filter(([,l])=>this.matchesTargetFile(l.filePath,i)),c=!1;await this.runInBatches(a,i?1:2,async([l,p])=>{let u=this.getWorkspaceFilePath(p.filePath);if(!u||!v.existsSync(u))return;let d=await o.get(H.GET_MODULE,{osClient:e.osClient,moduleId:p.moduleId},e.apiBaseUrl,e);if(d.Code!==1||!d.Data){if(/不存在|not\s*found/i.test(String(d.Msg||""))){let b=this.createRemoteDeletedItem("menuScript",`${p.moduleName}/${p.scriptField}`,l,t,u,p.updateTime);b&&r.push(b);return}throw new Error(`\u83B7\u53D6\u6A21\u5757 Join/Where \u540C\u6B65\u72B6\u6001\u5931\u8D25[${p.moduleId}]: ${d.Msg||"\u670D\u52A1\u5668\u8FD4\u56DE\u6570\u636E\u683C\u5F0F\u4E0D\u6B63\u786E"}`)}let g=d.Data,m=this.normalizeCode(String(g[p.scriptField]||"")),f=this.normalizeCode(v.readFileSync(u,"utf-8")),y=String(g.UpdateTime||""),S=this.isLocalModified(u,p.updateTime),h=this.sourceHash(m)!==p.codeHash;if(f===m){(S||h||y&&y!==p.updateTime)&&(p.codeHash=this.sourceHash(m),p.updateTime=y||p.updateTime,this.touchSyncedFile(u,p.updateTime),c=!0);return}let C=this.classifyDifference(S,h,f,m);C&&r.push({kind:"menuScript",status:C,name:`${p.moduleName}/${p.scriptField}`,key:l,serverDir:t,filePath:u,localCode:f,remoteCode:m,localUpdateTime:p.updateTime,remoteUpdateTime:y})}),c&&this.saveMeta(n,t)}async runInBatches(e,t,n){for(let r=0;r<e.length;r+=t)await Promise.all(e.slice(r,r+t).map(i=>n(i))),r+t<e.length&&await new Promise(i=>setTimeout(i,120))}async collectWorkflowDifferences(e,t,n,r,i){let a=await K.getInstance().get(H.GET_WORKFLOW_V8_EVENT_LIST,{osClient:e.osClient},e.apiBaseUrl,e);if(a.Code!==1||!Array.isArray(a.Data?.List))throw new Error(`\u83B7\u53D6\u6D41\u7A0B\u4E8B\u4EF6\u540C\u6B65\u72B6\u6001\u5931\u8D25: ${a.Msg||"\u670D\u52A1\u5668\u8FD4\u56DE\u6570\u636E\u683C\u5F0F\u4E0D\u6B63\u786E"}`);let c=new Map(a.Data.List.map(u=>[`${u.FlowDesignId}__${u.NodeId}__${u.EventType}`,u])),l=!1;for(let[u,d]of Object.entries(n.workflowNodeEvents||{})){if(!this.matchesTargetFile(d.filePath,i))continue;let g=c.get(u),m=this.getWorkspaceFilePath(d.filePath);if(!m||!v.existsSync(m))continue;if(!g||!String(g.V8Code||g.Code||"").trim()){let b=this.createRemoteDeletedItem("workflow",`${d.flowName}/${d.nodeName}/${d.eventType}`,u,t,m,d.updateTime);b&&r.push(b);continue}let f=this.normalizeCode(v.readFileSync(m,"utf-8")),y=this.normalizeCode(g.V8Code||g.Code||""),S=this.isLocalModified(m,d.updateTime),h=this.isRemoteNewer(g.UpdateTime,d.updateTime);if(f===y){(S||h)&&g.UpdateTime&&(d.updateTime=g.UpdateTime,this.touchSyncedFile(m,g.UpdateTime),l=!0);continue}let C=this.classifyDifference(S,h,f,y);if(C){let b=`${g.FlowName||d.flowName}/${g.NodeName||d.nodeName}/${g.EventType||d.eventType}`;r.push({kind:"workflow",status:C,name:b,key:u,serverDir:t,filePath:m,localCode:f,remoteCode:y,localUpdateTime:d.updateTime,remoteUpdateTime:g.UpdateTime})}}if(l&&this.saveMeta(n,t),i)return;let p=new Set(Object.keys(n.workflowNodeEvents||{}));for(let u of a.Data.List){let d=`${u.FlowDesignId}__${u.NodeId}__${u.EventType}`,g=u.V8Code||u.Code||"";if(!g.trim()||p.has(d))continue;let m=`${u.FlowName||u.FlowDesignId}/${u.NodeName||u.NodeId}/${u.EventType}`;r.push({kind:"workflow",status:"remoteModified",name:m,key:d,serverDir:t,filePath:this.getRemoteOnlyPlaceholderPath(e,t,"workflow",d),localCode:"",remoteCode:this.normalizeCode(g),localUpdateTime:"",remoteUpdateTime:u.UpdateTime})}}migrateFromFlatMeta(e){let t=N.getInstance();try{let n=t.getSyncRootDir(),r=E.join(n,rt);if(!v.existsSync(r))return{engines:{},events:{},fields:{},menus:{},menuButtons:{},menuScripts:{},workflows:{},workflowNodeEvents:{}};let i=t.getWorkspaceRoot();if(!i)return{engines:{},events:{},fields:{},menus:{},menuButtons:{},menuScripts:{},workflows:{},workflowNodeEvents:{}};let o=JSON.parse(v.readFileSync(r,"utf-8")),a=o.engines||{},c=o.events||{},l={engines:{},events:{},fields:{},menus:{},menuButtons:{},menuScripts:{},workflows:{},workflowNodeEvents:{}};for(let[p,u]of Object.entries(a)){let d=u;if(d.filePath){let g=E.join(i,d.filePath);E.relative(n,g).split(E.sep)[0]===e&&(l.engines[p]=d)}}for(let[p,u]of Object.entries(c)){let d=u;if(d.filePath){let g=E.join(i,d.filePath);E.relative(n,g).split(E.sep)[0]===e&&(l.events[p]=d)}}return(Object.keys(l.engines).length>0||Object.keys(l.events).length>0)&&this.saveMeta(l,e),l}catch{return{engines:{},events:{},fields:{},menus:{},menuButtons:{},menuScripts:{},workflows:{},workflowNodeEvents:{}}}}async pullEngines(e){if(!e){let t=N.getInstance().getProfiles();if(t.length===0){O.warn("Microi: \u6CA1\u6709\u5DF2\u8FDE\u63A5\u7684\u670D\u52A1\u5668\uFF0C\u8BF7\u5148\u5728\u8BBE\u7F6E\u4E2D\u6DFB\u52A0\u8FDE\u63A5\u5E76\u767B\u5F55");return}for(let n of t)try{await this.pullEnginesForProfile(n)}catch(r){let i=r instanceof Error?r.message:String(r);this.log(`\u62C9\u53D6\u5931\u8D25 [${n.label||n.apiBaseUrl}]: ${i}`),O.error(`Microi: \u62C9\u53D6 [${n.label||n.apiBaseUrl}] \u5931\u8D25 - ${i}`)}return}await this.pullEnginesForProfile(e)}async pullEnginesForProfile(e){let t=N.getInstance(),n=K.getInstance(),r=e.apiBaseUrl,i=e.osClient;this.log(`\u5F00\u59CB\u5168\u91CF\u62C9\u53D6\u63A5\u53E3\u5F15\u64CE\u4EE3\u7801 [${e.label||r}]...`),await Se.withProgress({location:tt.Notification,title:`Microi: \u62C9\u53D6\u63A5\u53E3\u5F15\u64CE [${e.label||r}]`,cancellable:!1},async o=>{o.report({message:"\u68C0\u67E5\u540E\u7AEF\u72B6\u6001..."});let a=await n.get(H.GET_STATUS,void 0,r,e);if(a.Code!==1){let P=a.Code===1001||a.Code===1002?"\uFF0C\u8BF7\u91CD\u65B0\u767B\u5F55":"";throw new Error(`\u540E\u7AEF\u72B6\u6001\u5F02\u5E38: ${a.Msg||"Code="+a.Code}${P}`)}o.report({message:"\u83B7\u53D6\u7CFB\u7EDF\u914D\u7F6E..."});let l=await ke.getInstance().getSysConfig(r,i),p=l?.SysShortTitle||"",u=l?.SysTitle||"",d=p||u||l?.CompanyName||e.label||"";d&&(d!==e.label||p!==e.sysShortTitle||u!==e.sysTitle)&&await t.addProfile({...e,label:d,sysShortTitle:p,sysTitle:u}),o.report({message:"\u83B7\u53D6\u63A5\u53E3\u5F15\u64CE\u5217\u8868..."});let g=await n.get(H.GET_ENGINE_LIST,{osClient:i},r,e);if(g.Code!==1){let P=g.Code===1001||g.Code===1002?"\uFF0C\u8BF7\u91CD\u65B0\u767B\u5F55":"";throw new Error(`\u83B7\u53D6\u5217\u8868\u5931\u8D25: ${g.Msg||"Code="+g.Code}${P}`)}let{OsClient:m,OsClientType:f,OsClientNetwork:y,List:S,Total:h}=g.Data;if(this.log(`\u83B7\u53D6\u5230 ${h} \u4E2A\u63A5\u53E3\u5F15\u64CE (OsClient: ${m})`),!f||!y)throw new Error(`\u540E\u7AEF\u672A\u8FD4\u56DE\u5B8C\u6574\u7684 OsClientType/OsClientNetwork (OsClient: ${m}, Type: ${f||"\u7A7A"}, Network: ${y||"\u7A7A"})\uFF0C\u65E0\u6CD5\u62C9\u53D6\u4EE3\u7801`);if(f||y){let P={...e,osClientType:f,osClientNetwork:y};await t.addProfile(P)}let C=t.getSyncRootDir(),b=t.buildServerDirName(d,r),T=this.loadMeta(b),k=0,I=0,w=[],F=new Set,M=new Set,D=t.buildOsClientDirName(m,f,y);for(let P of S)try{let _=Y(P.Category||"\u672A\u5206\u7C7B"),V=Y(P.ApiName||P.ApiEngineKey),Q=E.join(C,b,D,st,_),Z=Y(`${V}(${qn(P.ApiEngineKey)}).js`),pe=E.join(Q,Z),he=Qn(P.ApiV8Code||"");if(!he.trim()){I++,v.existsSync(pe)&&this.backupAndDeleteSyncFile(pe,b,"remote-deleted-api"),delete T.engines[P.ApiEngineKey];continue}F.add(P.ApiEngineKey),me(Q),v.writeFileSync(pe,he,"utf-8");let re=new Date(P.UpdateTime);isNaN(re.getTime())||v.utimesSync(pe,re,re),T.engines[P.ApiEngineKey]={id:P.Id,apiName:P.ApiName,category:_,apiAddress:P.ApiAddress,apiRoutes:P.ApiRoutes||"",updateTime:P.UpdateTime,filePath:E.relative(t.getWorkspaceRoot(),pe)},k++,o.report({message:`${k}/${h} ${P.ApiEngineKey}`,increment:1/h*100})}catch(_){let V=_ instanceof Error?_.message:String(_);M.add(P.ApiEngineKey),w.push(`${P.ApiEngineKey}: ${V}`),this.log(`\u63A5\u53E3\u5F15\u64CE\u6587\u4EF6\u5199\u5165\u5931\u8D25\uFF0C\u7EE7\u7EED\u4E0B\u4E00\u9879 [${P.ApiEngineKey}]: ${V}`)}for(let[P,_]of Object.entries(T.engines)){if(F.has(P)||M.has(P))continue;let V=this.getWorkspaceFilePath(_.filePath);V&&this.backupAndDeleteSyncFile(V,b,"remote-deleted-api"),delete T.engines[P]}this.saveMeta(T,b);let x=d||e.label||r;this.log(`[${x}] \u62C9\u53D6\u5B8C\u6210: ${k} \u4E2A\u63A5\u53E3\u5F15\u64CE\uFF0C\u8DF3\u8FC7\u7A7A\u4EE3\u7801 ${I} \u9879\uFF0C\u5931\u8D25 ${w.length} \u9879`),w.length>0?O.warn(`Microi: [${x}] \u5DF2\u62C9\u53D6 ${k} \u4E2A\u63A5\u53E3\u5F15\u64CE\uFF0C${w.length} \u4E2A\u6587\u4EF6\u5931\u8D25\uFF1B\u5931\u8D25\u660E\u7EC6\u5DF2\u5199\u5165 Microi \u8F93\u51FA\u3002`):O.info(`Microi: [${x}] \u6210\u529F\u62C9\u53D6 ${k} \u4E2A\u63A5\u53E3\u5F15\u64CE${I>0?`\uFF08\u8DF3\u8FC7 ${I} \u4E2A\u7A7A\u4EE3\u7801\uFF09`:""}`)})}async pullEvents(e){if(!e){let t=N.getInstance().getProfiles();if(t.length===0)return;for(let n of t)try{await this.pullEventsForProfile(n)}catch(r){let i=r instanceof Error?r.message:String(r);this.log(`\u62C9\u53D6V8\u4E8B\u4EF6\u5931\u8D25 [${n.label||n.apiBaseUrl}]: ${i}`)}return}await this.pullEventsForProfile(e)}async pullEventsForProfile(e){let t=N.getInstance(),n=K.getInstance(),r=e.apiBaseUrl,i=e.osClient;this.log(`\u5F00\u59CB\u5168\u91CF\u62C9\u53D6V8\u4E8B\u4EF6\u4EE3\u7801 [${e.label||r}]...`),await Se.withProgress({location:tt.Notification,title:`Microi: \u62C9\u53D6V8\u4E8B\u4EF6 [${e.label||r}]`,cancellable:!1},async o=>{o.report({message:"\u83B7\u53D6V8\u4E8B\u4EF6\u5217\u8868..."});let a=await n.get(H.GET_EVENT_LIST,{osClient:i},r,e);if(a.Code!==1){let D=a.Code===1001||a.Code===1002?"\uFF0C\u8BF7\u91CD\u65B0\u767B\u5F55":"";throw new Error(`\u83B7\u53D6V8\u4E8B\u4EF6\u5217\u8868\u5931\u8D25: ${a.Msg||"Code="+a.Code}${D}`)}let{List:c,Total:l}=a.Data;this.log(`\u83B7\u53D6\u5230 ${l} \u4E2AV8\u4E8B\u4EF6`);let u=await ke.getInstance().getSysConfig(r,i),d=u?.SysShortTitle||"",g=u?.SysTitle||"",m=d||g||u?.CompanyName||e.label||"";m&&(m!==e.label||d!==e.sysShortTitle||g!==e.sysTitle)&&await t.addProfile({...e,label:m,sysShortTitle:d,sysTitle:g});let f=t.getSyncRootDir(),y=t.buildServerDirName(m,r),S=this.loadMeta(y),h=0,C=0,b=0,T=new Set(c.map(D=>`${D.FormEngineKey}__${D.EventType}`)),I=t.getProfiles().find(D=>D.apiBaseUrl===e.apiBaseUrl&&D.osClient===e.osClient)||e;if(!I.osClientType||!I.osClientNetwork)throw new Error("\u7F3A\u5C11 OsClientType/OsClientNetwork\uFF0C\u8BF7\u5148\u62C9\u53D6\u63A5\u53E3\u5F15\u64CE\u4EE5\u83B7\u53D6\u5B8C\u6574\u914D\u7F6E");let w=t.buildOsClientDirName(i,I.osClientType,I.osClientNetwork),F={SubmitBeforeServerV8:"\u540E\u7AEF\u63D0\u4EA4\u524DV8\u4E8B\u4EF6",SubmitAfterServerV8:"\u540E\u7AEF\u63D0\u4EA4\u540EV8\u4E8B\u4EF6",SubmitFormV8:"\u524D\u7AEF\u8868\u5355\u63D0\u4EA4V8\u4E8B\u4EF6",OutFormV8:"\u524D\u7AEF\u8868\u5355\u9000\u51FAV8\u4E8B\u4EF6",ServerDataV8:"\u540E\u7AEF\u6570\u636EV8\u4E8B\u4EF6"};for(let D of c){let x=D.V8Code||"",P=Y(D.Description?`${D.Description}\uFF08${D.FormEngineKey}\uFF09`:D.FormEngineKey),_=xr[D.EventType]||D.EventType,V=Y(`${_}\uFF08${D.EventType}\uFF09`)+".js",Q=E.join(f,y,w,Le,P,Zt);me(Q);let Z=E.join(Q,V),pe=F[D.EventType];if(pe){let Ce=Y(`${pe}\uFF08${D.EventType}\uFF09`)+".js",de=E.join(Q,Ce);de!==Z&&v.existsSync(de)&&!this.isLocalModified(de,D.UpdateTime)&&(v.existsSync(Z)?v.unlinkSync(de):v.renameSync(de,Z))}let he=`${D.FormEngineKey}__${D.EventType}`;if(S.events[he]={id:D.Id,formEngineKey:D.FormEngineKey,description:D.Description||"",eventType:D.EventType,updateTime:D.UpdateTime,filePath:E.relative(t.getWorkspaceRoot(),Z)},!x.trim()){v.existsSync(Z)&&this.backupAndDeleteSyncFile(Z,y,"remote-deleted-form-event"),b++,h++,o.report({message:`${h}/${l}`,increment:l>0?1/l*100:void 0});continue}v.writeFileSync(Z,x,"utf-8");let re=new Date(D.UpdateTime);isNaN(re.getTime())||v.utimesSync(Z,re,re),C++,h++,o.report({message:`${h}/${l}`,increment:l>0?1/l*100:void 0})}for(let[D,x]of Object.entries(S.events)){if(T.has(D))continue;let P=this.getWorkspaceFilePath(x.filePath);P&&this.backupAndDeleteSyncFile(P,y,"remote-deleted-form-event"),delete S.events[D]}this.saveMeta(S,y);let M=m||e.label||r;this.log(`[${M}] \u62C9\u53D6\u5B8C\u6210: ${C} \u4E2AV8\u4E8B\u4EF6\u6587\u4EF6\uFF0C\u8DF3\u8FC7\u7A7A\u4EE3\u7801 ${b} \u9879`),O.info(`Microi: [${M}] \u6210\u529F\u62C9\u53D6 ${C} \u4E2AV8\u4E8B\u4EF6\u6587\u4EF6${b>0?`\uFF08\u8DF3\u8FC7 ${b} \u4E2A\u7A7A\u4EE3\u7801\u4E8B\u4EF6\uFF09`:""}`)})}async pullWorkflows(e){if(!e){let t=N.getInstance().getProfiles();if(t.length===0)return;for(let n of t)try{await this.pullWorkflowsForProfile(n)}catch(r){let i=r instanceof Error?r.message:String(r);this.log(`\u62C9\u53D6\u6D41\u7A0B\u5F15\u64CE\u5931\u8D25 [${n.label||n.apiBaseUrl}]: ${i}`)}return}await this.pullWorkflowsForProfile(e)}async pullWorkflowsForProfile(e){let t=N.getInstance(),n=K.getInstance(),r=e.apiBaseUrl,i=e.osClient;this.log(`\u5F00\u59CB\u5168\u91CF\u62C9\u53D6\u6D41\u7A0B\u5F15\u64CE\u8282\u70B9 V8 [${e.label||r}]...`),await Se.withProgress({location:tt.Notification,title:`Microi: \u62C9\u53D6\u6D41\u7A0B\u5F15\u64CE [${e.label||r}]`,cancellable:!1},async o=>{o.report({message:"\u83B7\u53D6\u6D41\u7A0B\u8282\u70B9V8\u5217\u8868..."});let a=await n.get(H.GET_WORKFLOW_V8_EVENT_LIST,{osClient:i},r,e);if(a.Code!==1){let _=a.Code===1001||a.Code===1002?"\uFF0C\u8BF7\u91CD\u65B0\u767B\u5F55":"";throw new Error(`\u83B7\u53D6\u6D41\u7A0B\u8282\u70B9V8\u5217\u8868\u5931\u8D25: ${a.Msg||"Code="+a.Code}${_}`)}let l=await ke.getInstance().getSysConfig(r,i),p=l?.SysShortTitle||"",u=l?.SysTitle||"",d=p||u||l?.CompanyName||e.label||"";d&&(d!==e.label||p!==e.sysShortTitle||u!==e.sysTitle)&&await t.addProfile({...e,label:d,sysShortTitle:p,sysTitle:u});let m=t.getProfiles().find(_=>_.apiBaseUrl===e.apiBaseUrl&&_.osClient===e.osClient)||e;if(!m.osClientType||!m.osClientNetwork)throw new Error("\u7F3A\u5C11 OsClientType/OsClientNetwork\uFF0C\u8BF7\u5148\u62C9\u53D6\u63A5\u53E3\u5F15\u64CE");let f=a.Data.OsClient||i,y=t.buildServerDirName(d,r),S=t.buildOsClientDirName(f,m.osClientType,m.osClientNetwork),h=t.getSyncRootDir(),C=this.loadMeta(y);C.workflows||(C.workflows={}),C.workflowNodeEvents||(C.workflowNodeEvents={});let b=a.Data.Flows||[],T=a.Data.Nodes||[],k=a.Data.Lines||[],I=a.Data.List||[],w=new Map(b.map(_=>[String(_.Id||""),_])),F=new Set(b.map(_=>String(_.Id||"")).filter(Boolean)),M=new Set(I.filter(_=>String(_.V8Code||_.Code||"").trim()).map(_=>`${_.FlowDesignId}__${_.NodeId}__${_.EventType}`)),D=0,x=0;for(let _ of b){let V=String(_.Id||"");if(!V)continue;let Q=String(_.FlowName||V),Z=String(_.UpdateTime||Te()),pe=E.join(h,y,S,it,Y(`${Q}\uFF08${V}\uFF09`));me(pe);let he=T.filter(de=>String(de.FlowDesignId||"")===V),re=k.filter(de=>String(de.FlowDesignId||"")===V),Ce=E.join(pe,"\u6D41\u7A0B\u8BBE\u8BA1\u56FE\uFF08WF_FlowDesign\uFF09.json");v.writeFileSync(Ce,JSON.stringify({FlowDesign:_,Nodes:he,Lines:re},null,2),"utf-8"),this.touchSyncedFile(Ce,Z),C.workflows[V]={flowDesignId:V,flowName:Q,updateTime:Z,filePath:E.relative(t.getWorkspaceRoot(),Ce)}}for(let _ of I){let V=String(_.FlowDesignId||""),Q=String(_.NodeId||""),Z=String(_.EventType||"");if(!V||!Q||!Z)continue;let pe=w.get(V),he=String(_.FlowName||pe?.FlowName||V),re=String(_.NodeName||Q),Ce=Fr[Z]||_.EventName||Z,de=E.join(h,y,S,it,Y(`${he}\uFF08${V}\uFF09`),en,Y(`${re}\uFF08${Q}\uFF09`));me(de);let $=E.join(de,Y(`${Ce}\uFF08${Z}\uFF09`)+".js"),ye=_.V8Code||_.Code||"",ae=String(_.UpdateTime||pe?.UpdateTime||Te());if(C.workflowNodeEvents[`${V}__${Q}__${Z}`]={flowDesignId:V,flowName:he,nodeId:Q,nodeName:re,eventType:Z,updateTime:ae,filePath:E.relative(t.getWorkspaceRoot(),$)},!ye.trim()){v.existsSync($)&&this.backupAndDeleteSyncFile($,y,"remote-deleted-workflow-event"),x++,o.report({message:`${D}/${I.length} ${he}/${re}`});continue}v.writeFileSync($,ye,"utf-8"),this.touchSyncedFile($,ae),D++,o.report({message:`${D}/${I.length} ${he}/${re}`})}for(let[_,V]of Object.entries(C.workflowNodeEvents)){if(M.has(_))continue;let Q=this.getWorkspaceFilePath(V.filePath);Q&&this.backupAndDeleteSyncFile(Q,y,"remote-deleted-workflow-event"),delete C.workflowNodeEvents[_]}for(let[_,V]of Object.entries(C.workflows)){if(F.has(_))continue;let Q=this.getWorkspaceFilePath(V.filePath);Q&&this.backupAndDeleteSyncFile(Q,y,"remote-deleted-workflow"),delete C.workflows[_]}this.saveMeta(C,y);let P=d||e.label||r;this.log(`[${P}] \u6D41\u7A0B\u5F15\u64CE\u62C9\u53D6\u5B8C\u6210: ${b.length} \u4E2A\u6D41\u7A0B\uFF0C${D} \u4E2A\u8282\u70B9V8\u6587\u4EF6\uFF0C\u8DF3\u8FC7\u7A7A\u4EE3\u7801 ${x} \u9879`),O.info(`Microi: [${P}] \u6210\u529F\u62C9\u53D6 ${b.length} \u4E2A\u6D41\u7A0B\u3001${D} \u4E2A\u6D41\u7A0B\u8282\u70B9V8\u6587\u4EF6${x>0?`\uFF08\u8DF3\u8FC7 ${x} \u4E2A\u7A7A\u4EE3\u7801\u4E8B\u4EF6\uFF09`:""}`)})}findProfileByServerDir(e){let t=N.getInstance(),n=t.getProfiles();for(let r of n)if(t.buildServerDirName(r.label,r.apiBaseUrl)===e)return r}hasSyncBaseline(e,t){let n=E.resolve(e).toLowerCase(),r=this.loadMeta(t);return[r.engines,r.events,r.fields||{},r.menuButtons||{},r.menuScripts||{},r.workflowNodeEvents||{}].some(o=>Object.values(o).some(a=>{let c=this.getWorkspaceFilePath(a.filePath);return!!c&&E.resolve(c).toLowerCase()===n}))}async runPushPreflight(e,t,n,r){if(!n){let i=`\u65E0\u6CD5\u8BC6\u522B\u6587\u4EF6\u6240\u5C5E\u670D\u52A1\u5668\u914D\u7F6E\uFF0C\u5DF2\u505C\u6B62\u63A8\u9001\uFF1A${e}`;return this.log(i),O.error(`Microi: ${i}`),!1}if(!this.hasSyncBaseline(e,t)){let i=`\u6587\u4EF6\u6CA1\u6709\u540C\u6B65\u57FA\u7EBF\uFF0C\u65E0\u6CD5\u786E\u8BA4\u670D\u52A1\u5668\u7AEF\u662F\u5426\u66F4\u65B0\uFF0C\u5DF2\u505C\u6B62\u63A8\u9001\u3002\u8BF7\u5148\u62C9\u53D6\u5BF9\u5E94\u5F15\u64CE\uFF1A${e}`;return this.log(i),O.error(`Microi: ${i}`),!1}try{let i=await this.checkRemoteDifferences(n,r,e),o=E.resolve(e).toLowerCase(),a=i.find(p=>E.resolve(p.filePath).toLowerCase()===o);if(!a||a.status==="localModified")return!0;let l=`${a.status==="conflict"?"\u672C\u5730\u4E0E\u670D\u52A1\u5668\u5747\u5DF2\u4FEE\u6539":a.status==="remoteDeleted"?"\u670D\u52A1\u5668\u7AEF\u8D44\u6E90\u5DF2\u5220\u9664":"\u670D\u52A1\u5668\u4EE3\u7801\u8F83\u65B0"}\uFF0C\u5DF2\u505C\u6B62\u63A8\u9001\u4EE5\u907F\u514D\u8986\u76D6\u3002\u8BF7\u5728\u201C\u540C\u6B65\u7ED3\u679C\u201D\u4E2D\u67E5\u770B\u5DEE\u5F02\u5E76\u62C9\u53D6\u6216\u5408\u5E76\uFF1A${a.name}`;return this.log(l),O.error(`Microi: ${l}`),!1}catch(i){let o=i instanceof Error?i.message:String(i);return this.log(`\u63A8\u9001\u524D\u540C\u6B65\u72B6\u6001\u68C0\u6D4B\u5931\u8D25\uFF0C\u5DF2\u505C\u6B62\u63A8\u9001\uFF1A${o}`),O.error(`Microi: \u63A8\u9001\u524D\u540C\u6B65\u72B6\u6001\u68C0\u6D4B\u5931\u8D25\uFF0C\u5DF2\u505C\u6B62\u63A8\u9001 - ${o}`),!1}}async pushFile(e,t={}){let r=N.getInstance().getSyncRootDir();if(E.extname(e).toLowerCase()===".js"&&v.existsSync(e)){let u=Wr(Fe(v.readFileSync(e,"utf-8")));if(u.length>0){let d=u[0],g=`\u68C0\u6D4B\u5230 AI/\u7EC8\u7AEF\u5DE5\u5177\u8F93\u51FA\u6C61\u67D3\uFF08\u7B2C ${d.line} \u884C: ${d.marker}\uFF09\uFF0C\u5DF2\u505C\u6B62\u63A8\u9001\u3002\u8BF7\u6062\u590D\u5B8C\u6574\u6E90\u7801\u540E\u518D\u8BD5\uFF1A${e}`;return this.log(g),O.error(`Microi: ${g}`),!1}}let i=Lr(e,r);if(i){let u=this.findProfileByServerDir(i.serverDir);return!t.skipPreflight&&!await this.runPushPreflight(e,i.serverDir,u,"api")?!1:this.pushEngineFile(e,i,u)}let o=Ur(e,r);if(o){let u=this.findProfileByServerDir(o.serverDir);return!t.skipPreflight&&!await this.runPushPreflight(e,o.serverDir,u,"form")?!1:this.pushEventFile(e,o,u)}let a=jr(e,r);if(a){let u=this.findProfileByServerDir(a.serverDir);return!t.skipPreflight&&!await this.runPushPreflight(e,a.serverDir,u,"form")?!1:this.pushFieldFile(e,a,u)}let c=Kr(e,r);if(c){let u=this.findProfileByServerDir(c.serverDir);return!t.skipPreflight&&!await this.runPushPreflight(e,c.serverDir,u,"module")?!1:this.pushMenuButtonFile(e,c,u)}let l=Hr(e,r);if(l){let u=this.findProfileByServerDir(l.serverDir);return!t.skipPreflight&&!await this.runPushPreflight(e,l.serverDir,u,"module")?!1:this.pushMenuScriptFile(e,l,u)}let p=Gr(e,r);if(p){let u=this.findProfileByServerDir(p.serverDir);return!t.skipPreflight&&!await this.runPushPreflight(e,p.serverDir,u,"workflow")?!1:this.pushWorkflowNodeFile(e,p,u)}return this.log(`\u65E0\u6CD5\u89E3\u6790\u6587\u4EF6\u8DEF\u5F84: ${e}`),!1}async pushEngineFile(e,t,n){let r=K.getInstance(),i=v.readFileSync(e,"utf-8"),o=Fe(i);this.log(`\u63A8\u9001\u63A5\u53E3\u5F15\u64CE: ${t.apiEngineKey}...`);try{let a="",c="";try{let g=await r.post(H.GET_ENGINE_CODE,{OsClient:t.osClient,ApiEngineKey:t.apiEngineKey},void 0,n?.apiBaseUrl,n);g.Code===1&&g.Data&&(a=g.Data.ApiV8Code||g.Data.Code||"",c=g.Data.Version||"")}catch{a="",c=""}let l=!o.trim(),p=l?{code:"",version:c,changeHistory:""}:Bt({kind:"ApiEngine",key:t.apiEngineKey,currentCode:o,remoteCode:a,remoteVersion:c,changeSummary:`\u901A\u8FC7 VS Code \u63A8\u9001\u63A5\u53E3\u5F15\u64CE ${t.apiEngineKey}`}),u={OsClient:t.osClient,ApiEngineKey:t.apiEngineKey,ApiV8CodeBase64:Buffer.from(p.code,"utf8").toString("base64")};l||(u.Version=p.version,u.ChangeSummary=p.changeHistory);let d=await r.post(H.UPDATE_ENGINE_CODE,u,void 0,n?.apiBaseUrl,n);if(d.Code===1){this.log(`\u63A8\u9001\u6210\u529F: ${t.apiEngineKey}`);let g=d.Data?.UpdateTime||Te(),m=this.loadMeta(t.serverDir);if(l?delete m.engines[t.apiEngineKey]:m.engines[t.apiEngineKey]&&(m.engines[t.apiEngineKey].updateTime=g),this.saveMeta(m,t.serverDir),l)v.existsSync(e)&&v.unlinkSync(e);else{v.writeFileSync(e,p.code,"utf-8");let f=new Date(g);isNaN(f.getTime())||v.utimesSync(e,f,f)}return!0}else return this.log(`\u63A8\u9001\u5931\u8D25: ${t.apiEngineKey} - ${d.Msg}`),O.error(`Microi: \u63A8\u9001\u5931\u8D25 - ${d.Msg}`),!1}catch(a){let c=a instanceof Error?a.message:String(a);return this.log(`\u63A8\u9001\u5F02\u5E38: ${t.apiEngineKey} - ${c}`),O.error(`Microi: \u63A8\u9001\u5F02\u5E38 - ${c}`),!1}}async pushEventFile(e,t,n){let r=K.getInstance(),i=v.readFileSync(e,"utf-8"),o=Fe(i);this.log(`\u63A8\u9001V8\u4E8B\u4EF6: ${t.formEngineKey}/${t.eventType}...`);try{let a="",c="";try{let g=await r.post(H.GET_EVENT_CODE,{OsClient:t.osClient,FormEngineKey:t.formEngineKey,EventType:t.eventType},void 0,n?.apiBaseUrl,n);g.Code===1&&g.Data&&(a=g.Data.V8Code||g.Data.Code||"",c=g.Data.Version||"")}catch{a="",c=""}let l=!o.trim(),p=l?{code:"",version:c,changeHistory:""}:Bt({kind:"V8Event",key:t.formEngineKey,eventType:t.eventType,currentCode:o,remoteCode:a,remoteVersion:c,changeSummary:`\u901A\u8FC7 VS Code \u63A8\u9001 V8 \u4E8B\u4EF6 ${t.formEngineKey}/${t.eventType}`}),u={OsClient:t.osClient,FormEngineKey:t.formEngineKey,EventType:t.eventType,V8Code:p.code};l||(u.Version=p.version,u.ChangeHistory=p.changeHistory);let d=await r.post(H.UPDATE_EVENT_CODE,u,void 0,n?.apiBaseUrl,n);if(d.Code===1){this.log(`\u63A8\u9001\u6210\u529F: ${t.formEngineKey}/${t.eventType}`);let g=d.Data?.UpdateTime||Te(),m=this.loadMeta(t.serverDir),f=`${t.formEngineKey}__${t.eventType}`;if(l)delete m.events[f];else{let y=m.events[f];m.events[f]={id:y?.id||"",formEngineKey:t.formEngineKey,description:y?.description||"",eventType:t.eventType,updateTime:g,filePath:E.relative(N.getInstance().getWorkspaceRoot(),e)}}if(this.saveMeta(m,t.serverDir),l)v.existsSync(e)&&v.unlinkSync(e);else{v.writeFileSync(e,p.code,"utf-8");let y=new Date(g);isNaN(y.getTime())||v.utimesSync(e,y,y)}return!0}else return this.log(`\u63A8\u9001\u5931\u8D25: ${t.formEngineKey}/${t.eventType} - ${d.Msg}`),O.error(`Microi: \u63A8\u9001\u5931\u8D25 - ${d.Msg}`),!1}catch(a){let c=a instanceof Error?a.message:String(a);return this.log(`\u63A8\u9001\u5F02\u5E38: ${t.formEngineKey}/${t.eventType} - ${c}`),O.error(`Microi: \u63A8\u9001\u5F02\u5E38 - ${c}`),!1}}async createEngine(e){let t=K.getInstance(),n=N.getInstance();this.log(`\u521B\u5EFA\u63A5\u53E3\u5F15\u64CE: ${e.apiEngineKey}...`);try{let r=Bt({kind:"ApiEngine",key:e.apiEngineKey,currentCode:"",functionDescription:`\u63A5\u53E3\u5F15\u64CE ${e.apiName} \u7684\u5B8C\u6574\u4E1A\u52A1\u903B\u8F91\u3002`,changeSummary:`\u901A\u8FC7 VS Code \u521B\u5EFA\u63A5\u53E3\u5F15\u64CE ${e.apiEngineKey}`,initial:!0}),i=await t.post(H.CREATE_ENGINE,{OsClient:e.profile.osClient,ApiName:e.apiName,ApiEngineKey:e.apiEngineKey,ApiAddress:e.apiAddress||"",ApiRoutes:e.apiRoutes||"",ApiRemark:e.apiRemark||"",Lock:e.lock?1:0,LockKey:e.lockKey||"",AllowAnonymous:e.allowAnonymous?1:0,V8Limit:e.v8Limit?1:0,IsEnable:e.isEnable!==!1?1:0,ApiRole:e.apiRole||"",Category:e.category||"\u672A\u5206\u7C7B",ApiV8CodeBase64:Buffer.from(r.code,"utf8").toString("base64"),Version:r.version,ChangeSummary:r.changeHistory},void 0,e.profile.apiBaseUrl,e.profile);if(i.Code===1){let o=n.getSyncRootDir(),a=n.buildServerDirName(e.profile.label,e.profile.apiBaseUrl),c=n.buildOsClientDirName(e.profile.osClient,e.profile.osClientType,e.profile.osClientNetwork),l=Y(e.category||"\u672A\u5206\u7C7B"),p=Y(e.apiName||e.apiEngineKey),u=E.join(o,a,c,st,l);me(u);let d=E.join(u,Y(`${p}(${qn(e.apiEngineKey)}).js`));v.writeFileSync(d,r.code,"utf-8");let g=this.loadMeta(a);return g.engines[e.apiEngineKey]={id:"",apiName:e.apiName,category:l,apiAddress:e.apiAddress||"",apiRoutes:e.apiRoutes||"",updateTime:Te(),filePath:E.relative(n.getWorkspaceRoot(),d)},this.saveMeta(g,a),this.log(`\u521B\u5EFA\u6210\u529F: ${e.apiEngineKey}`),O.info(`Microi: \u63A5\u53E3\u5F15\u64CE [${e.apiEngineKey}] \u521B\u5EFA\u6210\u529F`),await Se.showTextDocument(Ir.file(d)),!0}else return this.log(`\u521B\u5EFA\u5931\u8D25: ${e.apiEngineKey} - ${i.Msg}`),O.error(`Microi: \u521B\u5EFA\u5931\u8D25 - ${i.Msg}`),!1}catch(r){let i=r instanceof Error?r.message:String(r);return this.log(`\u521B\u5EFA\u5F02\u5E38: ${e.apiEngineKey} - ${i}`),O.error(`Microi: \u521B\u5EFA\u5F02\u5E38 - ${i}`),!1}}async pullFields(e){if(!e){let t=N.getInstance().getProfiles();for(let n of t)try{await this.pullFieldsForProfile(n)}catch(r){this.log(`\u62C9\u53D6\u5B57\u6BB5V8\u4E8B\u4EF6\u5931\u8D25 [${n.label||n.apiBaseUrl}]: ${r instanceof Error?r.message:String(r)}`)}return}await this.pullFieldsForProfile(e)}async pullFieldsForTableFolder(e){let n=N.getInstance().getSyncRootDir(),r=E.relative(n,e).split(E.sep);if(r.length<4||r[2]!==Le){O.warn("Microi: \u8BF7\u5728\u201C\u8868\u5355\u5F15\u64CE\u201D\u4E0B\u7684\u8868\u76EE\u5F55\u6267\u884C\u5B57\u6BB5 V8 \u4E8B\u4EF6\u62C9\u53D6");return}let i=a=>{let c=a.match(/[((]([^))]+)[))]\s*$/);return c?c[1]:a},o=this.findProfileByServerDir(r[0]);if(!o){O.error(`Microi: \u672A\u627E\u5230\u4E0E\u76EE\u5F55 "${r[0]}" \u5339\u914D\u7684\u670D\u52A1\u5668\u8FDE\u63A5`);return}await this.pullFieldsForTable(o,i(r[3]),e,r[0])}async pullFieldsForTable(e,t,n,r){let i=N.getInstance(),o=K.getInstance(),a=this.loadMeta(r);a.fields||(a.fields={}),this.log(`\u62C9\u53D6\u8868\u5B57\u6BB5V8\u4E8B\u4EF6: ${t}...`);let c=await o.get(H.GET_FIELD_LIST,{osClient:e.osClient,tableName:t},e.apiBaseUrl,e);if(c.Code!==1){O.error(`Microi: \u62C9\u53D6\u5B57\u6BB5V8\u4E8B\u4EF6\u5931\u8D25 - ${c.Msg}`);return}let l=c.Data.List||[],p=["V8Code","KeyupV8Code","V8TmpEngineTable","V8TmpEngineForm"],u=0,d=0;for(let g of l){let m=Y(g.Label?`${g.Label}\uFF08${g.Name}\uFF09`:g.Name),f=E.join(n,Et,m);for(let y of p){let S=(g[y]||"").toString(),h=$n[y]||y,C=Y(`${h}\uFF08${y}\uFF09`)+".js",b=E.join(f,C),T=`${t}__${g.Name}__${y}`;if(!S.trim()){d++,v.existsSync(b)&&v.unlinkSync(b),delete a.fields[T];continue}me(f),v.writeFileSync(b,S,"utf-8");let k=new Date(g.UpdateTime);isNaN(k.getTime())||v.utimesSync(b,k,k),a.fields[T]={fieldId:g.Id,tableId:g.TableId,tableName:t,fieldName:g.Name,fieldLabel:g.Label||"",v8Key:y,updateTime:g.UpdateTime,filePath:E.relative(i.getWorkspaceRoot(),b)},u++}}this.saveMeta(a,r),O.info(`Microi: \u5DF2\u62C9\u53D6 ${t} \u7684 ${u} \u4E2A\u5B57\u6BB5V8\u4E8B\u4EF6\u6587\u4EF6${d>0?`\uFF08\u8DF3\u8FC7 ${d} \u4E2A\u7A7A\u4EE3\u7801\uFF09`:""}`)}async pullFieldsForProfile(e){let t=N.getInstance(),n=K.getInstance(),r=e.apiBaseUrl,i=e.osClient;this.log(`\u5F00\u59CB\u5168\u91CF\u62C9\u53D6\u5B57\u6BB5V8\u4E8B\u4EF6 [${e.label||r}]...`),await Se.withProgress({location:tt.Notification,title:`Microi: \u62C9\u53D6\u5B57\u6BB5V8\u4E8B\u4EF6 [${e.label||r}]`,cancellable:!1},async o=>{o.report({message:"\u83B7\u53D6\u8868\u5217\u8868..."});let a=await n.get(H.GET_DB_SCHEMA,{osClient:i},r,e);if(a.Code!==1)throw new Error(`\u83B7\u53D6\u8868\u5217\u8868\u5931\u8D25: ${a.Msg||"Code="+a.Code}`);let c=a.Data.Tables||[],p=await ke.getInstance().getSysConfig(r,i),u=p?.SysShortTitle||"",d=p?.SysTitle||"",g=u||d||e.label||"",m=t.buildServerDirName(g,r),f=this.loadMeta(m);f.fields||(f.fields={});let S=t.getProfiles().find(M=>M.apiBaseUrl===e.apiBaseUrl&&M.osClient===e.osClient)||e;if(!S.osClientType||!S.osClientNetwork)throw new Error("\u7F3A\u5C11 OsClientType/OsClientNetwork\uFF0C\u8BF7\u5148\u62C9\u53D6\u63A5\u53E3\u5F15\u64CE");let h=t.buildOsClientDirName(i,S.osClientType,S.osClientNetwork),C=t.getSyncRootDir(),b=["V8Code","KeyupV8Code","V8TmpEngineTable","V8TmpEngineForm"],T=0,k=0,I=0,w=new Set,F=new Set;for(let M of c){I++,o.report({message:`[${I}/${c.length}] ${M.Name}`});let D=await n.get(H.GET_FIELD_LIST,{osClient:i,tableId:M.Id},r,e);if(D.Code!==1){F.add(M.Name.toLowerCase()),this.log(` \u8DF3\u8FC7\u8868 ${M.Name}: ${D.Msg}`);continue}let x=D.Data.List||[],P=Y(M.Description?`${M.Description}\uFF08${M.Name}\uFF09`:M.Name);for(let _ of x)for(let V of b){let Q=(_[V]||"").toString();if(!Q.trim()){k++;continue}let Z=Y(_.Label?`${_.Label}\uFF08${_.Name}\uFF09`:_.Name),pe=$n[V]||V,he=Y(`${pe}\uFF08${V}\uFF09`)+".js",re=E.join(C,m,h,Le,P,Et,Z);me(re);let Ce=E.join(re,he);v.writeFileSync(Ce,Q,"utf-8");let de=new Date(_.UpdateTime);isNaN(de.getTime())||v.utimesSync(Ce,de,de);let $=`${M.Name}__${_.Name}__${V}`;w.add($),f.fields[$]={fieldId:_.Id,tableId:_.TableId,tableName:M.Name,fieldName:_.Name,fieldLabel:_.Label||"",v8Key:V,updateTime:_.UpdateTime,filePath:E.relative(t.getWorkspaceRoot(),Ce)},T++}}for(let[M,D]of Object.entries(f.fields)){if(w.has(M)||F.has(D.tableName.toLowerCase()))continue;let x=this.getWorkspaceFilePath(D.filePath);x&&this.backupAndDeleteSyncFile(x,m,"remote-deleted-field-event"),delete f.fields[M]}this.saveMeta(f,m),this.log(`\u5B57\u6BB5V8\u4E8B\u4EF6\u62C9\u53D6\u5B8C\u6210: ${T} \u4E2A\u6587\u4EF6\uFF0C\u8DF3\u8FC7\u7A7A\u4EE3\u7801 ${k} \u9879`),O.info(`Microi: \u6210\u529F\u62C9\u53D6 ${T} \u4E2A\u5B57\u6BB5V8\u4E8B\u4EF6${k>0?`\uFF08\u8DF3\u8FC7 ${k} \u4E2A\u7A7A\u4EE3\u7801\uFF09`:""}`)})}async pushFieldFile(e,t,n){let r=K.getInstance(),i=Fe(v.readFileSync(e,"utf-8"));this.log(`\u63A8\u9001\u5B57\u6BB5V8\u4E8B\u4EF6: ${t.tableName}/${t.fieldName}/${t.v8Key}...`);try{let o=await r.post(H.UPDATE_FIELD,{OsClient:t.osClient,TableName:t.tableName,Name:t.fieldName,[t.v8Key]:i},void 0,n?.apiBaseUrl,n);if(o.Code===1){this.log(`\u63A8\u9001\u6210\u529F: ${t.tableName}/${t.fieldName}/${t.v8Key}`);let a=this.loadMeta(t.serverDir),c=`${t.tableName}__${t.fieldName}__${t.v8Key}`;a.fields||(a.fields={});let l=o.Data?.UpdateTime||Te();return i.trim()?a.fields[c]={fieldId:a.fields[c]?.fieldId||"",tableId:a.fields[c]?.tableId||"",tableName:t.tableName,fieldName:t.fieldName,fieldLabel:a.fields[c]?.fieldLabel||"",v8Key:t.v8Key,updateTime:l,filePath:E.relative(N.getInstance().getWorkspaceRoot(),e)}:delete a.fields[c],this.saveMeta(a,t.serverDir),i.trim()?this.touchSyncedFile(e,l):v.existsSync(e)&&v.unlinkSync(e),!0}return this.log(`\u63A8\u9001\u5931\u8D25: ${o.Msg}`),O.error(`Microi: \u63A8\u9001\u5B57\u6BB5V8\u4E8B\u4EF6\u5931\u8D25 - ${o.Msg}`),!1}catch(o){let a=o instanceof Error?o.message:String(o);return this.log(`\u63A8\u9001\u5F02\u5E38: ${a}`),O.error(`Microi: \u63A8\u9001\u5F02\u5E38 - ${a}`),!1}}async pullMenuButtons(e){if(!e){let t=N.getInstance().getProfiles();for(let n of t)try{await this.pullMenuButtonsForProfile(n)}catch(r){this.log(`\u62C9\u53D6\u83DC\u5355\u6309\u94AE\u5931\u8D25 [${n.label||n.apiBaseUrl}]: ${r instanceof Error?r.message:String(r)}`)}return}await this.pullMenuButtonsForProfile(e)}async pullMenuButtonsForModuleFolder(e){let n=N.getInstance().getSyncRootDir(),r=E.relative(n,e).split(E.sep);if(r.length<4||r[2]!==Ge){O.warn("Microi: \u8BF7\u5728\u201C\u6A21\u5757\u5F15\u64CE\u201D\u4E0B\u7684\u6A21\u5757\u76EE\u5F55\u6267\u884C\u62C9\u53D6");return}let i=this.findProfileByServerDir(r[0]);if(!i){O.error(`Microi: \u672A\u627E\u5230\u4E0E\u76EE\u5F55 "${r[0]}" \u5339\u914D\u7684\u670D\u52A1\u5668\u8FDE\u63A5`);return}let o=this.extractTrailingKey(E.basename(e));await this.pullMenuButtonsForProfile(i,o,r[0],r[1],e)}async pullMenuButtonsForProfile(e,t,n,r,i){let o=N.getInstance(),a=K.getInstance(),c=e.apiBaseUrl,l=e.osClient;this.log(`\u5F00\u59CB\u62C9\u53D6\u6A21\u5757 Join/Where \u4E0E\u6309\u94AE V8 \u4EE3\u7801 [${e.label||c}]...`),await Se.withProgress({location:tt.Notification,title:`Microi: \u62C9\u53D6\u6A21\u5757\u4EE3\u7801 [${e.label||c}]`,cancellable:!1},async p=>{let u=await a.get(H.LIST_MODULES,{osClient:l},c,e);if(u.Code!==1)throw new Error(`\u83B7\u53D6\u6A21\u5757\u5217\u8868\u5931\u8D25: ${u.Msg}`);let d=u.Data.List||[],m=await ke.getInstance().getSysConfig(c,l),f=m?.SysShortTitle||"",y=m?.SysTitle||"",S=f||y||e.label||"",h=n||o.buildServerDirName(S,c),C=this.loadMeta(h);C.menus||(C.menus={}),C.menuButtons||(C.menuButtons={}),C.menuScripts||(C.menuScripts={});let T=o.getProfiles().find($=>$.apiBaseUrl===e.apiBaseUrl&&$.osClient===e.osClient)||e;if(!T.osClientType||!T.osClientNetwork)throw new Error("\u7F3A\u5C11 OsClientType/OsClientNetwork\uFF0C\u8BF7\u5148\u62C9\u53D6\u63A5\u53E3\u5F15\u64CE");let k=r||o.buildOsClientDirName(l,T.osClientType,T.osClientNetwork),I=o.getSyncRootDir(),w=E.join(I,h,k,Ge),F=Object.keys(ot),M=Object.keys(Tt),D=0,x=0,P=0,_=0,V=0,Q=new Map(d.map($=>[$.Id,$])),Z=new Map,pe=$=>$||"";for(let $ of d){let ye=pe($.ParentId);Z.has(ye)||Z.set(ye,[]),Z.get(ye).push($)}let he=$=>$.sort((ye,ae)=>{let be=typeof ye.Sort=="number"?ye.Sort:0,wt=typeof ae.Sort=="number"?ae.Sort:0;return be!==wt?be-wt:String(ye.Name||ye.Label||"").localeCompare(String(ae.Name||ae.Label||""))}),re=t?Q.get(t)?[Q.get(t)]:[]:he(d.filter($=>!$.ParentId||!Q.has($.ParentId)));if(t&&re.length===0)throw new Error(`\u627E\u4E0D\u5230\u6A21\u5757 Id=${t}`);let Ce=t?i||E.join(w,Y(`${re[0].Label||re[0].Name||re[0].Id}\uFF08${re[0].Id}\uFF09`)):w;if(this.backupExistingTree(Ce,h,t?"module-subtree":"module-engine"),!t)C.menus={},C.menuButtons={},C.menuScripts={};else{let $=new Set,ye=ae=>{if(!$.has(ae)){$.add(ae);for(let be of Z.get(ae)||[])ye(be.Id)}};ye(t);for(let ae of $)delete C.menus[ae];for(let[ae,be]of Object.entries(C.menuButtons))$.has(be.moduleId)&&delete C.menuButtons[ae];for(let[ae,be]of Object.entries(C.menuScripts))$.has(be.moduleId)&&delete C.menuScripts[ae]}let de=async($,ye)=>{_++,p.report({message:`[${_}/${d.length}] ${$.Name||$.Label}`});let ae=$.Label||$.Name||$.Id,be=E.join(ye,Y(`${ae}\uFF08${$.Id}\uFF09`));me(be);let wt=he(Z.get($.Id)||[]);if(wt.length>0){for(let ge of wt)await de(ge,be);return}let Mn=await a.get(H.GET_MODULE,{osClient:l,moduleId:$.Id},c,e);if(Mn.Code!==1){this.log(` \u8DF3\u8FC7\u6A21\u5757 ${$.Name}: ${Mn.Msg}`);return}let An=Mn.Data,He=String(An.UpdateTime||Te()),vr={};for(let ge of M){let Jt=String(An[ge]||""),xn=Tt[ge]||ge,We=E.join(be,Y(`${xn}\uFF08${ge}\uFF09`)+".js");v.writeFileSync(We,Jt,"utf-8"),this.touchSyncedFile(We,He),C.menuScripts[this.getMenuScriptMetaKey($.Id,ge)]={moduleId:$.Id,moduleName:ae,scriptField:ge,codeHash:this.sourceHash(Jt),updateTime:He,filePath:E.relative(o.getWorkspaceRoot(),We)},P++}for(let ge of F){let Jt=ot[ge]||ge,xn=Y(`${Jt}\uFF08${ge}\uFF09`),We=E.join(be,xn);me(We),x++;let qt=An[ge],Xe=[];if(qt)try{Xe=typeof qt=="string"?JSON.parse(qt):qt,Array.isArray(Xe)||(Xe=[])}catch{this.log(` \u6309\u94AE JSON \u89E3\u6790\u5931\u8D25 ${$.Name}.${ge}`),Xe=[]}let gi=[...Xe].sort((Ze,Re)=>String(Ze.Id||"").localeCompare(String(Re.Id||"")));vr[ge]=require("crypto").createHash("sha1").update(JSON.stringify(gi)).digest("hex");for(let Ze of Xe){let Re=String(Ze.Id||""),Qt=String(Ze.Name||Re||"Unknown");if(!Re)continue;let Er=String(Ze.V8Code||""),Fn=E.join(We,Y(`${Qt}\uFF08${Re}\uFF09`)+".js");C.menuButtons[this.getMenuButtonMetaKey($.Id,ge,Re,"V8Code")]={moduleId:$.Id,moduleName:ae,btnField:ge,btnId:Re,btnName:Qt,v8SubField:"V8Code",updateTime:He,filePath:E.relative(o.getWorkspaceRoot(),Fn)},Er.trim()?(v.writeFileSync(Fn,Er,"utf-8"),this.touchSyncedFile(Fn,He),D++):V++;let Tr=String(Ze.V8CodeShow||"");if(Tr.trim()){let Vn=E.join(We,Y(`${Qt}_\u663E\u9690\u5224\u65AD\uFF08${Re}\uFF09`)+".js");v.writeFileSync(Vn,Tr,"utf-8"),this.touchSyncedFile(Vn,He),C.menuButtons[this.getMenuButtonMetaKey($.Id,ge,Re,"V8CodeShow")]={moduleId:$.Id,moduleName:ae,btnField:ge,btnId:Re,btnName:Qt,v8SubField:"V8CodeShow",updateTime:He,filePath:E.relative(o.getWorkspaceRoot(),Vn)},D++}else V++}}C.menus[$.Id]={moduleId:$.Id,moduleName:ae,updateTime:He,buttonHashes:vr}};me(w);for(let $ of re)await de($,w);this.saveMeta(C,h),this.log(`\u6A21\u5757\u4EE3\u7801\u62C9\u53D6\u5B8C\u6210: ${D} \u4E2A\u6309\u94AEV8\u6587\u4EF6\uFF0C${P} \u4E2A Join/Where \u6587\u4EF6\uFF0C${x} \u4E2A\u6309\u94AE\u76EE\u5F55\uFF0C\u8DF3\u8FC7\u7A7A\u6309\u94AE\u4EE3\u7801 ${V} \u9879`),O.info(`Microi: \u6210\u529F\u62C9\u53D6 ${D} \u4E2A\u6309\u94AEV8\u6587\u4EF6\u548C ${P} \u4E2A Join/Where \u6587\u4EF6${V>0?`\uFF08\u8DF3\u8FC7 ${V} \u4E2A\u7A7A\u6309\u94AE\u4EE3\u7801\uFF09`:""}\uFF0C\u5DF2\u751F\u6210 ${x} \u4E2A\u6309\u94AE\u76EE\u5F55`)})}backupExistingTree(e,t,n){if(!v.existsSync(e))return;let i=N.getInstance().getSyncRootDir();this.ensureSyncGitExcludes(i);let o=E.join(i,".backups",n,this.shortBackupKey(t));me(o);let a=E.join(o,`${Date.now()}-${this.shortBackupKey(E.basename(e))}`);v.renameSync(e,a)}backupAndDeleteSyncFile(e,t,n){if(!v.existsSync(e))return;let r=N.getInstance(),i=r.getSyncRootDir();this.ensureSyncGitExcludes(i);let o=r.getWorkspaceRoot()||i,c=E.relative(o,e).split(E.sep).filter(u=>u&&u!=="..").map(Y),l=E.join(i,".backups",n,this.shortBackupKey(t),String(Date.now())),p=E.join(l,...c.length?c:[Y(E.basename(e))]);me(E.dirname(p)),v.copyFileSync(e,p),v.unlinkSync(e)}async pushMenuScriptFile(e,t,n){let r=K.getInstance(),i=Fe(v.readFileSync(e,"utf-8"));this.log(`\u63A8\u9001\u6A21\u5757\u811A\u672C: ${t.moduleId}.${t.scriptField}...`);try{let o=await r.get(H.GET_MODULE,{osClient:t.osClient,moduleId:t.moduleId},n?.apiBaseUrl,n);if(o.Code!==1||!o.Data)return O.error(`Microi: \u63A8\u9001\u5931\u8D25 - \u62C9\u53D6\u6A21\u5757\u5931\u8D25 ${o.Msg}`),!1;let a=o.Data,c=String(a[t.scriptField]||""),l=N.getInstance(),p=l.getSyncRootDir();this.ensureSyncGitExcludes(p);let u=E.join(p,".backups","menu-script",this.shortBackupKey(t.serverDir),t.moduleId);me(u),v.writeFileSync(E.join(u,`${t.scriptField}-${Date.now()}.js`),c,"utf-8");let d={OsClient:t.osClient,ModuleId:t.moduleId,[t.scriptField]:i},g=await r.post(H.UPDATE_MODULE,d,void 0,n?.apiBaseUrl,n);if(g.Code!==1)return O.error(`Microi: \u63A8\u9001\u6A21\u5757 ${t.scriptField} \u5931\u8D25 - ${g.Msg}`),!1;let m=await r.get(H.GET_MODULE,{osClient:t.osClient,moduleId:t.moduleId},n?.apiBaseUrl,n),f=m.Data;if(m.Code!==1||!f||this.normalizeCode(String(f[t.scriptField]||""))!==this.normalizeCode(i))return O.error(`Microi: ${t.scriptField} \u63A5\u53E3\u8FD4\u56DE\u6210\u529F\uFF0C\u4F46\u8FDC\u7AEF\u56DE\u8BFB\u4E0D\u4E00\u81F4\uFF1B\u5DF2\u4FDD\u7559\u672C\u5730\u4FEE\u6539\u548C\u8FDC\u7AEF\u5907\u4EFD`),!1;let y=String(f.UpdateTime||g.Data?.UpdateTime||Te()),S=this.loadMeta(t.serverDir);return S.menuScripts||(S.menuScripts={}),S.menuScripts[this.getMenuScriptMetaKey(t.moduleId,t.scriptField)]={moduleId:t.moduleId,moduleName:String(f.Label||f.Name||a.Label||a.Name||t.moduleId),scriptField:t.scriptField,codeHash:this.sourceHash(i),updateTime:y,filePath:E.relative(l.getWorkspaceRoot(),e)},S.menus||(S.menus={}),S.menus[t.moduleId]={moduleId:t.moduleId,moduleName:String(f.Label||f.Name||a.Label||a.Name||t.moduleId),updateTime:y,buttonHashes:S.menus[t.moduleId]?.buttonHashes||{}},this.saveMeta(S,t.serverDir),this.touchSyncedFile(e,y),this.log(`\u63A8\u9001\u5E76\u56DE\u8BFB\u6210\u529F: ${t.moduleId}.${t.scriptField}`),!0}catch(o){let a=o instanceof Error?o.message:String(o);return this.log(`\u63A8\u9001\u6A21\u5757\u811A\u672C\u5F02\u5E38: ${a}`),O.error(`Microi: \u63A8\u9001\u6A21\u5757\u811A\u672C\u5F02\u5E38 - ${a}`),!1}}async pushMenuButtonFile(e,t,n){let r=K.getInstance(),i=Fe(v.readFileSync(e,"utf-8"));this.log(`\u63A8\u9001\u6309\u94AEV8\u4EE3\u7801: ${t.moduleId}.${t.btnField}.${t.btnId}.${t.v8SubField}...`);try{let o=await r.get(H.GET_MODULE,{osClient:t.osClient,moduleId:t.moduleId},n?.apiBaseUrl,n);if(o.Code!==1)return O.error(`Microi: \u63A8\u9001\u5931\u8D25 - \u62C9\u53D6\u6A21\u5757\u5931\u8D25 ${o.Msg}`),!1;let a=o.Data,c=[],l=a[t.btnField];if(l)try{c=typeof l=="string"?JSON.parse(l):l,Array.isArray(c)||(c=[])}catch{return O.error("Microi: \u63A8\u9001\u5931\u8D25 - \u6309\u94AE JSON \u89E3\u6790\u5931\u8D25"),!1}let u=N.getInstance().getSyncRootDir();this.ensureSyncGitExcludes(u);let d=E.join(u,".backups","menu-button-json",this.shortBackupKey(t.serverDir),t.moduleId);me(d);let g=E.join(d,`${t.btnField}-${Date.now()}.json`);v.writeFileSync(g,JSON.stringify(c,null,2),"utf-8");let m=c.find(S=>String(S.Id||"")===t.btnId);if(!m){let S=c.map(h=>Number(h.Sort||0)).filter(h=>!isNaN(h));m={Id:t.btnId,Name:t.btnName||t.btnId,Sort:S.length>0?Math.max(...S)+1:c.length+1,IsVisible:!0,ShowRow:t.btnField==="MoreBtns"},c.push(m)}m[t.v8SubField]=i;let f={OsClient:t.osClient,ModuleId:t.moduleId};f[t.btnField]=JSON.stringify(c);let y=await r.post(H.UPDATE_MODULE,f,void 0,n?.apiBaseUrl,n);if(y.Code===1){this.log(`\u63A8\u9001\u6210\u529F: ${t.moduleId}.${t.btnField}.${t.btnId}.${t.v8SubField}`);let S=y.Data?.UpdateTime||Te(),h=this.loadMeta(t.serverDir);h.menuButtons||(h.menuButtons={});let C=this.getMenuButtonMetaKey(t.moduleId,t.btnField,t.btnId,t.v8SubField);return i.trim()?h.menuButtons[C]={moduleId:t.moduleId,moduleName:String(a.Name||a.Label||t.moduleId),btnField:t.btnField,btnId:t.btnId,btnName:String(m.Name||t.btnName||t.btnId),v8SubField:t.v8SubField,updateTime:S,filePath:E.relative(N.getInstance().getWorkspaceRoot(),e)}:delete h.menuButtons[C],h.menus||(h.menus={}),h.menus[t.moduleId]={moduleId:t.moduleId,moduleName:String(a.Name||a.Label||t.moduleId),updateTime:S,buttonHashes:h.menus[t.moduleId]?.buttonHashes||{}},this.saveMeta(h,t.serverDir),i.trim()?this.touchSyncedFile(e,S):v.existsSync(e)&&v.unlinkSync(e),!0}return O.error(`Microi: \u63A8\u9001\u6309\u94AE\u5931\u8D25 - ${y.Msg}`),!1}catch(o){let a=o instanceof Error?o.message:String(o);return this.log(`\u63A8\u9001\u5F02\u5E38: ${a}`),O.error(`Microi: \u63A8\u9001\u5F02\u5E38 - ${a}`),!1}}async pushWorkflowNodeFile(e,t,n){let r=K.getInstance(),i=v.readFileSync(e,"utf-8"),o=Fe(i);this.log(`\u63A8\u9001\u6D41\u7A0B\u8282\u70B9V8: ${t.flowDesignId}/${t.nodeId}/${t.eventType}...`);try{let a="",c="";try{let g=await r.post(H.GET_WORKFLOW_V8_EVENT_CODE,{OsClient:t.osClient,FlowDesignId:t.flowDesignId,NodeId:t.nodeId,EventType:t.eventType},void 0,n?.apiBaseUrl,n);g.Code===1&&g.Data&&(a=g.Data.V8Code||g.Data.Code||"",c=g.Data.Version||"")}catch{a="",c=""}let l=!o.trim(),p=l?{code:"",version:c,changeHistory:""}:Bt({kind:"Workflow",key:`${t.flowDesignId}/${t.nodeId}`,eventType:t.eventType,currentCode:o,remoteCode:a,remoteVersion:c,changeSummary:`\u901A\u8FC7 VS Code \u63A8\u9001\u6D41\u7A0B\u8282\u70B9 V8 ${t.flowDesignId}/${t.nodeId}/${t.eventType}`}),u={OsClient:t.osClient,FlowDesignId:t.flowDesignId,NodeId:t.nodeId,EventType:t.eventType};l?u.V8Code="":(u.V8CodeBase64=Buffer.from(p.code,"utf8").toString("base64"),u.Version=p.version,u.ChangeHistory=p.changeHistory);let d=await r.post(H.UPDATE_WORKFLOW_V8_EVENT_CODE,u,void 0,n?.apiBaseUrl,n);if(d.Code===1){let g=d.Data?.UpdateTime||Te(),m=this.loadMeta(t.serverDir);m.workflowNodeEvents||(m.workflowNodeEvents={});let f=`${t.flowDesignId}__${t.nodeId}__${t.eventType}`;return l?delete m.workflowNodeEvents[f]:m.workflowNodeEvents[f]={flowDesignId:t.flowDesignId,flowName:m.workflowNodeEvents[f]?.flowName||t.flowDesignId,nodeId:t.nodeId,nodeName:m.workflowNodeEvents[f]?.nodeName||t.nodeId,eventType:t.eventType,updateTime:g,filePath:E.relative(N.getInstance().getWorkspaceRoot(),e)},this.saveMeta(m,t.serverDir),l?v.existsSync(e)&&v.unlinkSync(e):(v.writeFileSync(e,p.code,"utf-8"),this.touchSyncedFile(e,g)),this.log(`\u63A8\u9001\u6210\u529F: ${t.flowDesignId}/${t.nodeId}/${t.eventType}`),!0}return this.log(`\u63A8\u9001\u6D41\u7A0B\u8282\u70B9V8\u5931\u8D25: ${d.Msg}`),O.error(`Microi: \u63A8\u9001\u6D41\u7A0B\u8282\u70B9V8\u5931\u8D25 - ${d.Msg}`),!1}catch(a){let c=a instanceof Error?a.message:String(a);return this.log(`\u63A8\u9001\u6D41\u7A0B\u8282\u70B9V8\u5F02\u5E38: ${c}`),O.error(`Microi: \u63A8\u9001\u5F02\u5E38 - ${c}`),!1}}async pullDbSchema(e){let t=N.getInstance(),n=K.getInstance();if(!e){let r=t.getProfiles();if(r.length===0){O.warn("Microi: \u6CA1\u6709\u5DF2\u8FDE\u63A5\u7684\u670D\u52A1\u5668");return}for(let i of r)try{await this.pullDbSchemaForProfile(i)}catch(o){let a=o instanceof Error?o.message:String(o);this.log(`\u62C9\u53D6\u6570\u636E\u5E93\u7ED3\u6784\u5931\u8D25 [${i.label||i.apiBaseUrl}]: ${a}`)}return}await this.pullDbSchemaForProfile(e)}async pullDbSchemaForProfile(e){let t=N.getInstance(),n=K.getInstance(),r=e.apiBaseUrl,i=e.osClient;this.log(`\u5F00\u59CB\u62C9\u53D6\u6570\u636E\u5E93\u7ED3\u6784 [${e.label||r}]...`);let o=await n.get(H.GET_DB_SCHEMA,{osClient:i},r,e);if(o.Code!==1){let I=o.Code===1001||o.Code===1002?"\uFF0C\u8BF7\u91CD\u65B0\u767B\u5F55":"";throw new Error(`\u83B7\u53D6\u6570\u636E\u5E93\u7ED3\u6784\u5931\u8D25: ${o.Msg||"Code="+o.Code}${I}`)}let a=t.getSyncRootDir(),l=await ke.getInstance().getSysConfig(r,i),p=l?.SysShortTitle||"",u=l?.SysTitle||"",d=p||u||l?.CompanyName||e.label||"";d&&(d!==e.label||p!==e.sysShortTitle||u!==e.sysTitle)&&await t.addProfile({...e,label:d,sysShortTitle:p,sysTitle:u});let g=t.buildServerDirName(d,r),f=t.getProfiles().find(I=>I.apiBaseUrl===e.apiBaseUrl&&I.osClient===e.osClient)||e,y=t.buildOsClientDirName(i,f.osClientType,f.osClientNetwork),S=E.join(a,g,y);me(S);let h=E.join(S,at);v.writeFileSync(h,JSON.stringify(o.Data,null,2),"utf-8");let C=E.join(S,ze),b=this.formatDbSchemaMarkdown(o.Data,g,y);b&&v.writeFileSync(C,b,"utf-8");let T=o.Data.Tables?.length||0,k=d||e.label||r;this.log(`[${k}] \u62C9\u53D6\u6570\u636E\u5E93\u7ED3\u6784\u5B8C\u6210: ${T} \u5F20\u8868`),O.info(`Microi: [${k}] \u6210\u529F\u62C9\u53D6\u6570\u636E\u5E93\u7ED3\u6784\uFF08${T} \u5F20\u8868\uFF09`)}formatDbSchemaMarkdown(e,t,n){let r=(e.Tables||[]).filter(c=>c.Name);if(!r.length)return"";let i=r.reduce((c,l)=>{let p=l._Fields||l.Fields||[];return c+p.length},0),o=e.Menus?.length||0,a=[];a.push(`# \u6570\u636E\u5E93\u7ED3\u6784 \u2014 ${t}/${n}
|
|
45
|
+
`:""}${Xi(s,i,a)}${c.replace(/^\s+/,"")}`,d=(s.changeSummary||"\u540C\u6B65 V8 \u4EE3\u7801").trim();return{code:p,version:i,changeHistory:`${i} ${d}`}}var pt=class s{static getInstance(){return s._instance||(s._instance=new s),s._instance}constructor(){}get outputChannel(){return ce.channel}log(e){ce.log("\u540C\u6B65",e)}loadMeta(e){let t=N.getInstance(),n="";try{n=t.getSyncRootDir()}catch{}if(!n)return{engines:{},events:{},fields:{},menus:{},menuButtons:{},menuScripts:{},workflows:{},workflowNodeEvents:{}};let r=_.join(n,e,rt);if(!v.existsSync(r))return this.migrateFromFlatMeta(e);try{let i=JSON.parse(v.readFileSync(r,"utf-8"));if(!i||typeof i!="object"||Array.isArray(i))throw new Error("\u9876\u5C42\u5FC5\u987B\u662F JSON \u5BF9\u8C61");let o=i;return{...o,engines:o.engines||{},events:o.events||{},fields:o.fields||{},menus:o.menus||{},menuButtons:o.menuButtons||{},menuScripts:o.menuScripts||{},workflows:o.workflows||{},workflowNodeEvents:o.workflowNodeEvents||{}}}catch(i){throw new Error(`Microi \u540C\u6B65\u5143\u6570\u636E\u65E0\u6CD5\u89E3\u6790\uFF0C\u5DF2\u4FDD\u7559\u539F\u6587\u4EF6\u5E76\u505C\u6B62\u5199\u5165\uFF1A${r}\uFF08${i instanceof Error?i.message:String(i)}\uFF09`)}}saveMeta(e,t){let n=N.getInstance();try{let r=n.getSyncRootDir();this.ensureSyncGitExcludes(r);let i=_.join(r,t);me(i);let o=_.join(i,rt),a=`${o}.${process.pid}.${Date.now()}.tmp`;try{v.writeFileSync(a,`${JSON.stringify(e,null,2)}
|
|
46
|
+
`,"utf-8"),v.renameSync(a,o)}finally{try{v.existsSync(a)&&v.unlinkSync(a)}catch{}}}catch{}}getWorkspaceFilePath(e){let t=N.getInstance().getWorkspaceRoot();return t?_.isAbsolute(e)?e:_.join(t,e):null}normalizeCode(e){return Fe(Yn(e||"")).replace(/\r\n/g,`
|
|
47
|
+
`).trimEnd()}isLocalModified(e,t){try{if(!v.existsSync(e))return!1;let n=v.statSync(e),r=new Date(t);return isNaN(r.getTime())?!1:n.mtime.getTime()>r.getTime()+1e3}catch{return!1}}getLocalModifiedTime(e,t){try{if(!v.existsSync(e))return null;let n=v.statSync(e),r=new Date(t);return isNaN(r.getTime())?null:n.mtime.getTime()>r.getTime()+1e3?Te(n.mtime):null}catch{return null}}touchSyncedFile(e,t){let n=new Date(t),r=isNaN(n.getTime())?new Date:n;try{v.utimesSync(e,r,r)}catch{}}ensureSyncGitExcludes(e){try{let t=e||N.getInstance().getSyncRootDir();lt(t),Ue(t,[".backups/","**/.backups/",".microi-mcp-tokens.json","**/.microi-mcp-tokens.json"])}catch{}}shortBackupKey(e){return require("crypto").createHash("sha1").update(e||"").digest("hex").slice(0,10)}getMenuButtonMetaKey(e,t,n,r){return`${e}__${t}__${n}__${r}`}getMenuScriptMetaKey(e,t){return`${e}__${t}`}sourceHash(e){return require("crypto").createHash("sha256").update(this.normalizeCode(e||"")).digest("hex")}extractTrailingKey(e){let t=e.match(/[((]([^))]+)[))]\s*$/);return t?t[1]:e}getServerDirs(){try{let e=N.getInstance().getSyncRootDir();return v.existsSync(e)?v.readdirSync(e,{withFileTypes:!0}).filter(t=>t.isDirectory()).filter(t=>!t.name.startsWith(".")).map(t=>t.name):[]}catch{return[]}}getLocalChangeSummary(){let e={engines:0,events:0,fields:0,menuButtons:0,menuScripts:0,workflowNodeEvents:0,total:0};for(let t of this.getLocalChangeItems())t.kind==="engine"?e.engines+=1:t.kind==="event"?e.events+=1:t.kind==="field"?e.fields+=1:t.kind==="menuButton"?e.menuButtons+=1:t.kind==="menuScript"?e.menuScripts+=1:t.kind==="workflow"&&(e.workflowNodeEvents+=1);return e.total=e.engines+e.events+e.fields+e.menuButtons+e.menuScripts+e.workflowNodeEvents,e}getLocalChangeItems(){let e=[],t=(n,r,i,o,a)=>{let c=this.getWorkspaceFilePath(a.filePath);if(!c)return;let l=this.getLocalModifiedTime(c,a.updateTime);l&&e.push({kind:r,key:i,name:o,serverDir:n,filePath:c,updateTime:a.updateTime,modifiedTime:l})};for(let n of this.getServerDirs()){let r=this.loadMeta(n);for(let[i,o]of Object.entries(r.engines))t(n,"engine",i,o.apiName||i,o);for(let[i,o]of Object.entries(r.events))t(n,"event",i,`${o.description||o.formEngineKey}/${o.eventType}`,o);for(let[i,o]of Object.entries(r.fields||{}))t(n,"field",i,`${o.tableName}.${o.fieldName}/${o.v8Key}`,o);for(let[i,o]of Object.entries(r.menuButtons||{}))t(n,"menuButton",i,`${o.moduleName}/${o.btnName}/${o.v8SubField}`,o);for(let[i,o]of Object.entries(r.menuScripts||{}))t(n,"menuScript",i,`${o.moduleName}/${o.scriptField}`,o);for(let[i,o]of Object.entries(r.workflowNodeEvents||{}))t(n,"workflow",i,`${o.flowName}/${o.nodeName}/${o.eventType}`,o)}return e}async checkRemoteDifferences(e,t="all",n){let r=e?[e]:N.getInstance().getProfiles(),i=[];for(let o of r){let a=N.getInstance().buildServerDirName(o.label,o.apiBaseUrl),c=this.loadMeta(a),l=n?this.getTargetSyncKind(c,n):null;if(n&&!l)throw new Error(`\u540C\u6B65\u76EE\u6807\u4E0D\u5728\u672C\u5730\u57FA\u7EBF\u4E2D: ${n}`);(t==="all"||t==="api")&&(!n||l==="engine")&&await this.collectEngineDifferences(o,a,c,i,n),(t==="all"||t==="form")&&(!n||l==="event")&&await this.collectEventDifferences(o,a,c,i,n),(t==="all"||t==="form")&&(!n||l==="field")&&await this.collectFieldDifferences(o,a,c,i,n),(t==="all"||t==="module")&&(!n||l==="menuButton")&&await this.collectMenuButtonDifferences(o,a,c,i,n),(t==="all"||t==="module")&&(!n||l==="menuScript")&&await this.collectMenuScriptDifferences(o,a,c,i,n),(t==="all"||t==="workflow")&&(!n||l==="workflow")&&await this.collectWorkflowDifferences(o,a,c,i,n)}return i}matchesTargetFile(e,t){if(!t)return!0;let n=this.getWorkspaceFilePath(e);return!!n&&_.resolve(n).toLowerCase()===_.resolve(t).toLowerCase()}getTargetSyncKind(e,t){let n=[["engine",e.engines],["event",e.events],["field",e.fields||{}],["menuButton",e.menuButtons||{}],["menuScript",e.menuScripts||{}],["workflow",e.workflowNodeEvents||{}]];for(let[r,i]of n)if(Object.values(i).some(o=>this.matchesTargetFile(o.filePath,t)))return r;return null}classifyDifference(e,t,n,r){return n===r?null:e&&t?"conflict":e?"localModified":"remoteModified"}classifyRemoteDeletion(e,t){return this.isLocalModified(e,t)?"conflict":"remoteDeleted"}createRemoteDeletedItem(e,t,n,r,i,o){return!i||!v.existsSync(i)?null:{kind:e,status:this.classifyRemoteDeletion(i,o),name:t,key:n,serverDir:r,filePath:i,localCode:this.normalizeCode(v.readFileSync(i,"utf-8")),remoteCode:"",localUpdateTime:o,remoteUpdateTime:""}}isRemoteNewer(e,t){let n=new Date(e||"").getTime(),r=new Date(t||"").getTime();return isNaN(n)||isNaN(r)?!1:n>r+1e3}getRemoteOnlyPlaceholderPath(e,t,n,r){let i=N.getInstance(),o=n==="api"?st:n==="form"?Le:n==="module"?Ge:it;return _.join(i.getSyncRootDir(),t,i.buildOsClientDirName(e.osClient,e.osClientType,e.osClientNetwork),o,"\u670D\u52A1\u5668\u65B0\u589E\u5F85\u62C9\u53D6",`${X(r)}.js`)}async collectEngineDifferences(e,t,n,r,i){let a=await L.getInstance().get(H.GET_ENGINE_LIST,{osClient:e.osClient},e.apiBaseUrl,e);if(a.Code!==1||!Array.isArray(a.Data?.List))throw new Error(`\u83B7\u53D6\u63A5\u53E3\u5F15\u64CE\u540C\u6B65\u72B6\u6001\u5931\u8D25: ${a.Msg||"\u670D\u52A1\u5668\u8FD4\u56DE\u6570\u636E\u683C\u5F0F\u4E0D\u6B63\u786E"}`);let c=new Map(a.Data.List.map(d=>[d.ApiEngineKey,d])),l=!1;for(let[d,u]of Object.entries(n.engines)){if(!this.matchesTargetFile(u.filePath,i))continue;let g=c.get(d),m=this.getWorkspaceFilePath(u.filePath);if(!m||!v.existsSync(m))continue;if(!g){let b=this.createRemoteDeletedItem("engine",u.apiName||d,d,t,m,u.updateTime);b&&r.push(b);continue}let f=this.normalizeCode(v.readFileSync(m,"utf-8")),y=this.normalizeCode(g.ApiV8Code||""),C=this.isLocalModified(m,u.updateTime),h=this.isRemoteNewer(g.UpdateTime,u.updateTime);if(f===y){(C||h)&&g.UpdateTime&&(u.updateTime=g.UpdateTime,this.touchSyncedFile(m,g.UpdateTime),l=!0);continue}let S=this.classifyDifference(C,h,f,y);S&&r.push({kind:"engine",status:S,name:g.ApiName||u.apiName||d,key:d,serverDir:t,filePath:m,localCode:f,remoteCode:y,localUpdateTime:u.updateTime,remoteUpdateTime:g.UpdateTime})}if(l&&this.saveMeta(n,t),i)return;let p=new Set(Object.keys(n.engines).map(d=>d.toLowerCase()));for(let d of a.Data.List)!String(d.ApiV8Code||"").trim()||p.has(d.ApiEngineKey.toLowerCase())||r.push({kind:"engine",status:"remoteModified",name:d.ApiName||d.ApiEngineKey,key:d.ApiEngineKey,serverDir:t,filePath:this.getRemoteOnlyPlaceholderPath(e,t,"api",d.ApiEngineKey),localCode:"",remoteCode:this.normalizeCode(d.ApiV8Code||""),localUpdateTime:"",remoteUpdateTime:d.UpdateTime})}async collectEventDifferences(e,t,n,r,i){let a=await L.getInstance().get(H.GET_EVENT_LIST,{osClient:e.osClient},e.apiBaseUrl,e);if(a.Code!==1||!Array.isArray(a.Data?.List))throw new Error(`\u83B7\u53D6\u8868\u5355\u4E8B\u4EF6\u540C\u6B65\u72B6\u6001\u5931\u8D25: ${a.Msg||"\u670D\u52A1\u5668\u8FD4\u56DE\u6570\u636E\u683C\u5F0F\u4E0D\u6B63\u786E"}`);let c=new Map;for(let d of a.Data.List){let u=`${d.FormEngineKey}__${d.EventType}`;c.set(u,d),c.set(u.toLowerCase(),d)}let l=!1;for(let[d,u]of Object.entries(n.events)){if(!this.matchesTargetFile(u.filePath,i))continue;let g=c.get(d)||c.get(d.toLowerCase()),m=this.getWorkspaceFilePath(u.filePath);if(!m||!v.existsSync(m))continue;if(!g){let b=this.createRemoteDeletedItem("event",`${u.description||u.formEngineKey}/${u.eventType}`,d,t,m,u.updateTime);b&&r.push(b);continue}let f=this.normalizeCode(v.readFileSync(m,"utf-8")),y=this.normalizeCode(g.V8Code||""),C=this.isLocalModified(m,u.updateTime),h=this.isRemoteNewer(g.UpdateTime,u.updateTime);if(f===y){(C||h)&&g.UpdateTime&&(u.updateTime=g.UpdateTime,this.touchSyncedFile(m,g.UpdateTime),l=!0);continue}let S=this.classifyDifference(C,h,f,y);S&&r.push({kind:"event",status:S,name:`${g.Description||u.formEngineKey}/${u.eventType}`,key:d,serverDir:t,filePath:m,localCode:f,remoteCode:y,localUpdateTime:u.updateTime,remoteUpdateTime:g.UpdateTime})}if(l&&this.saveMeta(n,t),i)return;let p=new Set(Object.keys(n.events).map(d=>d.toLowerCase()));for(let d of a.Data.List){let u=`${d.FormEngineKey}__${d.EventType}`;!String(d.V8Code||"").trim()||p.has(u.toLowerCase())||r.push({kind:"event",status:"remoteModified",name:`${d.Description||d.FormEngineKey}/${d.EventType}`,key:u,serverDir:t,filePath:this.getRemoteOnlyPlaceholderPath(e,t,"form",u),localCode:"",remoteCode:this.normalizeCode(d.V8Code||""),localUpdateTime:"",remoteUpdateTime:d.UpdateTime})}}async collectFieldDifferences(e,t,n,r,i){let o=L.getInstance(),a=new Map;for(let l of Object.entries(n.fields||{})){if(!this.matchesTargetFile(l[1].filePath,i))continue;let p=a.get(l[1].tableId||l[1].tableName)||[];p.push(l),a.set(l[1].tableId||l[1].tableName,p)}let c=!1;await this.runInBatches([...a.values()],i?1:2,async l=>{let p=l[0][1],d=await o.get(H.GET_FIELD_LIST,{osClient:e.osClient,tableId:p.tableId,tableName:p.tableName},e.apiBaseUrl,e);if(d.Code!==1||!Array.isArray(d.Data?.List))throw new Error(`\u83B7\u53D6\u5B57\u6BB5\u540C\u6B65\u72B6\u6001\u5931\u8D25[${p.tableName}]: ${d.Msg||"\u670D\u52A1\u5668\u8FD4\u56DE\u6570\u636E\u683C\u5F0F\u4E0D\u6B63\u786E"}`);let u=new Map(d.Data.List.map(g=>[String(g.Name||"").toLowerCase(),g]));for(let[g,m]of l){let f=u.get(m.fieldName.toLowerCase()),y=this.getWorkspaceFilePath(m.filePath);if(!y||!v.existsSync(y))continue;if(!f||!String(f[m.v8Key]||"").trim()){let I=this.createRemoteDeletedItem("field",`${m.tableName}.${m.fieldName}/${m.v8Key}`,g,t,y,m.updateTime);I&&r.push(I);continue}let C=this.normalizeCode(v.readFileSync(y,"utf-8")),h=this.normalizeCode(String(f[m.v8Key]||"")),S=String(f.UpdateTime||""),b=this.isLocalModified(y,m.updateTime),E=this.isRemoteNewer(S,m.updateTime);if(C===h){(b||E)&&S&&(m.updateTime=S,this.touchSyncedFile(y,S),c=!0);continue}let k=this.classifyDifference(b,E,C,h);k&&r.push({kind:"field",status:k,name:`${m.tableName}.${m.fieldName}/${m.v8Key}`,key:g,serverDir:t,filePath:y,localCode:C,remoteCode:h,localUpdateTime:m.updateTime,remoteUpdateTime:S})}}),c&&this.saveMeta(n,t)}async collectMenuButtonDifferences(e,t,n,r,i){let o=L.getInstance(),a=new Map;if(!i)for(let u of Object.keys(n.menus||{}))a.set(u,[]);for(let u of Object.entries(n.menuButtons||{})){if(!this.matchesTargetFile(u[1].filePath,i))continue;let g=a.get(u[1].moduleId)||[];g.push(u),a.set(u[1].moduleId,g)}let c=[];if(!i){let u=await o.get(H.LIST_MODULES,{osClient:e.osClient},e.apiBaseUrl,e);if(u.Code!==1||!Array.isArray(u.Data?.List))throw new Error(`\u83B7\u53D6\u6A21\u5757\u540C\u6B65\u72B6\u6001\u5931\u8D25: ${u.Msg||"\u670D\u52A1\u5668\u8FD4\u56DE\u6570\u636E\u683C\u5F0F\u4E0D\u6B63\u786E"}`);c=u.Data.List}let l=new Set(c.map(u=>String(u.ParentId||"")).filter(Boolean)),p=new Map(c.map(u=>[u.Id,u]));for(let u of c){if(l.has(u.Id)||n.menus?.[u.Id])continue;let g=u.Label||u.Name||u.Id;r.push({kind:"menuButton",status:"remoteModified",name:`${g}/\u670D\u52A1\u5668\u65B0\u589E\u6A21\u5757`,key:u.Id,serverDir:t,filePath:this.getRemoteOnlyPlaceholderPath(e,t,"module",u.Id),localCode:"",remoteCode:JSON.stringify(u,null,2),localUpdateTime:"",remoteUpdateTime:String(u.UpdateTime||"")})}let d=!1;await this.runInBatches([...a.entries()],i?1:2,async([u,g])=>{let m=()=>{for(let[E,k]of g){let I=this.getWorkspaceFilePath(k.filePath);if(!I)continue;let w=this.createRemoteDeletedItem("menuButton",`${k.moduleName}/${k.btnName}/${k.v8SubField}`,E,t,I,k.updateTime);w&&r.push(w)}};if(!i&&!p.has(u)){m();return}let f=await o.get(H.GET_MODULE,{osClient:e.osClient,moduleId:u},e.apiBaseUrl,e);if(f.Code!==1||!f.Data){if(/不存在|not\s*found/i.test(String(f.Msg||""))){m();return}throw new Error(`\u83B7\u53D6\u6A21\u5757\u6309\u94AE\u540C\u6B65\u72B6\u6001\u5931\u8D25[${u}]: ${f.Msg||"\u670D\u52A1\u5668\u8FD4\u56DE\u6570\u636E\u683C\u5F0F\u4E0D\u6B63\u786E"}`)}let y=f.Data,C=String(y.UpdateTime||""),h=new Map;for(let E of Object.keys(ot)){let k=[];try{let I=y[E];k=typeof I=="string"?JSON.parse(I):Array.isArray(I)?I:[],Array.isArray(k)||(k=[])}catch{k=[]}h.set(E,new Map(k.map(I=>[String(I.Id||""),I])))}for(let[E,k]of g){let I=h.get(k.btnField)?.get(k.btnId),w=this.getWorkspaceFilePath(k.filePath);if(!w||!v.existsSync(w))continue;if(!I||!String(I[k.v8SubField]||"").trim()){let P=this.createRemoteDeletedItem("menuButton",`${k.moduleName}/${k.btnName}/${k.v8SubField}`,E,t,w,k.updateTime);P&&r.push(P);continue}let O=this.normalizeCode(v.readFileSync(w,"utf-8")),A=this.normalizeCode(String(I[k.v8SubField]||"")),D=this.isLocalModified(w,k.updateTime),$=this.isRemoteNewer(C,k.updateTime);if(O===A){(D||$)&&C&&(k.updateTime=C,this.touchSyncedFile(w,C),d=!0);continue}let T=this.classifyDifference(D,$,O,A);T&&r.push({kind:"menuButton",status:T,name:`${k.moduleName}/${k.btnName}/${k.v8SubField}`,key:E,serverDir:t,filePath:w,localCode:O,remoteCode:A,localUpdateTime:k.updateTime,remoteUpdateTime:C})}if(i)return;let S=new Set(g.map(([E])=>E)),b=n.menus?.[u]?.moduleName||p.get(u)?.Label||p.get(u)?.Name||u;for(let[E,k]of h)for(let[I,w]of k){if(!I)continue;let O=String(w.Name||I);for(let A of["V8Code","V8CodeShow"]){let D=String(w[A]||""),$=this.getMenuButtonMetaKey(u,E,I,A);!D.trim()||S.has($)||r.push({kind:"menuButton",status:"remoteModified",name:`${b}/${O}/${A}`,key:$,serverDir:t,filePath:this.getRemoteOnlyPlaceholderPath(e,t,"module",$),localCode:"",remoteCode:this.normalizeCode(D),localUpdateTime:"",remoteUpdateTime:C})}}}),d&&this.saveMeta(n,t)}async collectMenuScriptDifferences(e,t,n,r,i){let o=L.getInstance(),a=Object.entries(n.menuScripts||{}).filter(([,l])=>this.matchesTargetFile(l.filePath,i)),c=!1;await this.runInBatches(a,i?1:2,async([l,p])=>{let d=this.getWorkspaceFilePath(p.filePath);if(!d||!v.existsSync(d))return;let u=await o.get(H.GET_MODULE,{osClient:e.osClient,moduleId:p.moduleId},e.apiBaseUrl,e);if(u.Code!==1||!u.Data){if(/不存在|not\s*found/i.test(String(u.Msg||""))){let b=this.createRemoteDeletedItem("menuScript",`${p.moduleName}/${p.scriptField}`,l,t,d,p.updateTime);b&&r.push(b);return}throw new Error(`\u83B7\u53D6\u6A21\u5757 Join/Where \u540C\u6B65\u72B6\u6001\u5931\u8D25[${p.moduleId}]: ${u.Msg||"\u670D\u52A1\u5668\u8FD4\u56DE\u6570\u636E\u683C\u5F0F\u4E0D\u6B63\u786E"}`)}let g=u.Data,m=this.normalizeCode(String(g[p.scriptField]||"")),f=this.normalizeCode(v.readFileSync(d,"utf-8")),y=String(g.UpdateTime||""),C=this.isLocalModified(d,p.updateTime),h=this.sourceHash(m)!==p.codeHash;if(f===m){(C||h||y&&y!==p.updateTime)&&(p.codeHash=this.sourceHash(m),p.updateTime=y||p.updateTime,this.touchSyncedFile(d,p.updateTime),c=!0);return}let S=this.classifyDifference(C,h,f,m);S&&r.push({kind:"menuScript",status:S,name:`${p.moduleName}/${p.scriptField}`,key:l,serverDir:t,filePath:d,localCode:f,remoteCode:m,localUpdateTime:p.updateTime,remoteUpdateTime:y})}),c&&this.saveMeta(n,t)}async runInBatches(e,t,n){for(let r=0;r<e.length;r+=t)await Promise.all(e.slice(r,r+t).map(i=>n(i))),r+t<e.length&&await new Promise(i=>setTimeout(i,120))}async collectWorkflowDifferences(e,t,n,r,i){let a=await L.getInstance().get(H.GET_WORKFLOW_V8_EVENT_LIST,{osClient:e.osClient},e.apiBaseUrl,e);if(a.Code!==1||!Array.isArray(a.Data?.List))throw new Error(`\u83B7\u53D6\u6D41\u7A0B\u4E8B\u4EF6\u540C\u6B65\u72B6\u6001\u5931\u8D25: ${a.Msg||"\u670D\u52A1\u5668\u8FD4\u56DE\u6570\u636E\u683C\u5F0F\u4E0D\u6B63\u786E"}`);let c=new Map(a.Data.List.map(d=>[`${d.FlowDesignId}__${d.NodeId}__${d.EventType}`,d])),l=!1;for(let[d,u]of Object.entries(n.workflowNodeEvents||{})){if(!this.matchesTargetFile(u.filePath,i))continue;let g=c.get(d),m=this.getWorkspaceFilePath(u.filePath);if(!m||!v.existsSync(m))continue;if(!g||!String(g.V8Code||g.Code||"").trim()){let b=this.createRemoteDeletedItem("workflow",`${u.flowName}/${u.nodeName}/${u.eventType}`,d,t,m,u.updateTime);b&&r.push(b);continue}let f=this.normalizeCode(v.readFileSync(m,"utf-8")),y=this.normalizeCode(g.V8Code||g.Code||""),C=this.isLocalModified(m,u.updateTime),h=this.isRemoteNewer(g.UpdateTime,u.updateTime);if(f===y){(C||h)&&g.UpdateTime&&(u.updateTime=g.UpdateTime,this.touchSyncedFile(m,g.UpdateTime),l=!0);continue}let S=this.classifyDifference(C,h,f,y);if(S){let b=`${g.FlowName||u.flowName}/${g.NodeName||u.nodeName}/${g.EventType||u.eventType}`;r.push({kind:"workflow",status:S,name:b,key:d,serverDir:t,filePath:m,localCode:f,remoteCode:y,localUpdateTime:u.updateTime,remoteUpdateTime:g.UpdateTime})}}if(l&&this.saveMeta(n,t),i)return;let p=new Set(Object.keys(n.workflowNodeEvents||{}));for(let d of a.Data.List){let u=`${d.FlowDesignId}__${d.NodeId}__${d.EventType}`,g=d.V8Code||d.Code||"";if(!g.trim()||p.has(u))continue;let m=`${d.FlowName||d.FlowDesignId}/${d.NodeName||d.NodeId}/${d.EventType}`;r.push({kind:"workflow",status:"remoteModified",name:m,key:u,serverDir:t,filePath:this.getRemoteOnlyPlaceholderPath(e,t,"workflow",u),localCode:"",remoteCode:this.normalizeCode(g),localUpdateTime:"",remoteUpdateTime:d.UpdateTime})}}migrateFromFlatMeta(e){let t=N.getInstance();try{let n=t.getSyncRootDir(),r=_.join(n,rt);if(!v.existsSync(r))return{engines:{},events:{},fields:{},menus:{},menuButtons:{},menuScripts:{},workflows:{},workflowNodeEvents:{}};let i=t.getWorkspaceRoot();if(!i)return{engines:{},events:{},fields:{},menus:{},menuButtons:{},menuScripts:{},workflows:{},workflowNodeEvents:{}};let o=JSON.parse(v.readFileSync(r,"utf-8")),a=o.engines||{},c=o.events||{},l={engines:{},events:{},fields:{},menus:{},menuButtons:{},menuScripts:{},workflows:{},workflowNodeEvents:{}};for(let[p,d]of Object.entries(a)){let u=d;if(u.filePath){let g=_.join(i,u.filePath);_.relative(n,g).split(_.sep)[0]===e&&(l.engines[p]=u)}}for(let[p,d]of Object.entries(c)){let u=d;if(u.filePath){let g=_.join(i,u.filePath);_.relative(n,g).split(_.sep)[0]===e&&(l.events[p]=u)}}return(Object.keys(l.engines).length>0||Object.keys(l.events).length>0)&&this.saveMeta(l,e),l}catch{return{engines:{},events:{},fields:{},menus:{},menuButtons:{},menuScripts:{},workflows:{},workflowNodeEvents:{}}}}async pullEngines(e){if(!e){let t=N.getInstance().getProfiles();if(t.length===0){F.warn("Microi: \u6CA1\u6709\u5DF2\u8FDE\u63A5\u7684\u670D\u52A1\u5668\uFF0C\u8BF7\u5148\u5728\u8BBE\u7F6E\u4E2D\u6DFB\u52A0\u8FDE\u63A5\u5E76\u767B\u5F55");return}for(let n of t)try{await this.pullEnginesForProfile(n)}catch(r){let i=r instanceof Error?r.message:String(r);this.log(`\u62C9\u53D6\u5931\u8D25 [${n.label||n.apiBaseUrl}]: ${i}`),F.error(`Microi: \u62C9\u53D6 [${n.label||n.apiBaseUrl}] \u5931\u8D25 - ${i}`)}return}await this.pullEnginesForProfile(e)}async pullEnginesForProfile(e){let t=N.getInstance(),n=L.getInstance(),r=e.apiBaseUrl,i=e.osClient;this.log(`\u5F00\u59CB\u5168\u91CF\u62C9\u53D6\u63A5\u53E3\u5F15\u64CE\u4EE3\u7801 [${e.label||r}]...`),await Se.withProgress({location:tt.Notification,title:`Microi: \u62C9\u53D6\u63A5\u53E3\u5F15\u64CE [${e.label||r}]`,cancellable:!1},async o=>{o.report({message:"\u68C0\u67E5\u540E\u7AEF\u72B6\u6001..."});let a=await n.get(H.GET_STATUS,void 0,r,e);if(a.Code!==1){let T=a.Code===1001||a.Code===1002?"\uFF0C\u8BF7\u91CD\u65B0\u767B\u5F55":"";throw new Error(`\u540E\u7AEF\u72B6\u6001\u5F02\u5E38: ${a.Msg||"Code="+a.Code}${T}`)}o.report({message:"\u83B7\u53D6\u7CFB\u7EDF\u914D\u7F6E..."});let l=await ke.getInstance().getSysConfig(r,i),p=l?.SysShortTitle||"",d=l?.SysTitle||"",u=p||d||l?.CompanyName||e.label||"";u&&(u!==e.label||p!==e.sysShortTitle||d!==e.sysTitle)&&await t.addProfile({...e,label:u,sysShortTitle:p,sysTitle:d}),o.report({message:"\u83B7\u53D6\u63A5\u53E3\u5F15\u64CE\u5217\u8868..."});let g=await n.get(H.GET_ENGINE_LIST,{osClient:i},r,e);if(g.Code!==1){let T=g.Code===1001||g.Code===1002?"\uFF0C\u8BF7\u91CD\u65B0\u767B\u5F55":"";throw new Error(`\u83B7\u53D6\u5217\u8868\u5931\u8D25: ${g.Msg||"Code="+g.Code}${T}`)}let{OsClient:m,OsClientType:f,OsClientNetwork:y,List:C,Total:h}=g.Data;if(this.log(`\u83B7\u53D6\u5230 ${h} \u4E2A\u63A5\u53E3\u5F15\u64CE (OsClient: ${m})`),!f||!y)throw new Error(`\u540E\u7AEF\u672A\u8FD4\u56DE\u5B8C\u6574\u7684 OsClientType/OsClientNetwork (OsClient: ${m}, Type: ${f||"\u7A7A"}, Network: ${y||"\u7A7A"})\uFF0C\u65E0\u6CD5\u62C9\u53D6\u4EE3\u7801`);if(f||y){let T={...e,osClientType:f,osClientNetwork:y};await t.addProfile(T)}let S=t.getSyncRootDir(),b=t.buildServerDirName(u,r),E=this.loadMeta(b),k=0,I=0,w=[],O=new Set,A=new Set,D=t.buildOsClientDirName(m,f,y);for(let T of C)try{let P=X(T.Category||"\u672A\u5206\u7C7B"),M=X(T.ApiName||T.ApiEngineKey),J=_.join(S,b,D,st,P),Y=X(`${M}(${qn(T.ApiEngineKey)}).js`),pe=_.join(J,Y),he=Yn(T.ApiV8Code||"");if(!he.trim()){I++,v.existsSync(pe)&&this.backupAndDeleteSyncFile(pe,b,"remote-deleted-api"),delete E.engines[T.ApiEngineKey];continue}O.add(T.ApiEngineKey),me(J),v.writeFileSync(pe,he,"utf-8");let re=new Date(T.UpdateTime);isNaN(re.getTime())||v.utimesSync(pe,re,re),E.engines[T.ApiEngineKey]={id:T.Id,apiName:T.ApiName,category:P,apiAddress:T.ApiAddress,apiRoutes:T.ApiRoutes||"",updateTime:T.UpdateTime,filePath:_.relative(t.getWorkspaceRoot(),pe)},k++,o.report({message:`${k}/${h} ${T.ApiEngineKey}`,increment:1/h*100})}catch(P){let M=P instanceof Error?P.message:String(P);A.add(T.ApiEngineKey),w.push(`${T.ApiEngineKey}: ${M}`),this.log(`\u63A5\u53E3\u5F15\u64CE\u6587\u4EF6\u5199\u5165\u5931\u8D25\uFF0C\u7EE7\u7EED\u4E0B\u4E00\u9879 [${T.ApiEngineKey}]: ${M}`)}for(let[T,P]of Object.entries(E.engines)){if(O.has(T)||A.has(T))continue;let M=this.getWorkspaceFilePath(P.filePath);M&&this.backupAndDeleteSyncFile(M,b,"remote-deleted-api"),delete E.engines[T]}this.saveMeta(E,b);let $=u||e.label||r;this.log(`[${$}] \u62C9\u53D6\u5B8C\u6210: ${k} \u4E2A\u63A5\u53E3\u5F15\u64CE\uFF0C\u8DF3\u8FC7\u7A7A\u4EE3\u7801 ${I} \u9879\uFF0C\u5931\u8D25 ${w.length} \u9879`),w.length>0?F.warn(`Microi: [${$}] \u5DF2\u62C9\u53D6 ${k} \u4E2A\u63A5\u53E3\u5F15\u64CE\uFF0C${w.length} \u4E2A\u6587\u4EF6\u5931\u8D25\uFF1B\u5931\u8D25\u660E\u7EC6\u5DF2\u5199\u5165 Microi \u8F93\u51FA\u3002`):F.info(`Microi: [${$}] \u6210\u529F\u62C9\u53D6 ${k} \u4E2A\u63A5\u53E3\u5F15\u64CE${I>0?`\uFF08\u8DF3\u8FC7 ${I} \u4E2A\u7A7A\u4EE3\u7801\uFF09`:""}`)})}async pullEvents(e){if(!e){let t=N.getInstance().getProfiles();if(t.length===0)return;for(let n of t)try{await this.pullEventsForProfile(n)}catch(r){let i=r instanceof Error?r.message:String(r);this.log(`\u62C9\u53D6V8\u4E8B\u4EF6\u5931\u8D25 [${n.label||n.apiBaseUrl}]: ${i}`)}return}await this.pullEventsForProfile(e)}async pullEventsForProfile(e){let t=N.getInstance(),n=L.getInstance(),r=e.apiBaseUrl,i=e.osClient;this.log(`\u5F00\u59CB\u5168\u91CF\u62C9\u53D6V8\u4E8B\u4EF6\u4EE3\u7801 [${e.label||r}]...`),await Se.withProgress({location:tt.Notification,title:`Microi: \u62C9\u53D6V8\u4E8B\u4EF6 [${e.label||r}]`,cancellable:!1},async o=>{o.report({message:"\u83B7\u53D6V8\u4E8B\u4EF6\u5217\u8868..."});let a=await n.get(H.GET_EVENT_LIST,{osClient:i},r,e);if(a.Code!==1){let D=a.Code===1001||a.Code===1002?"\uFF0C\u8BF7\u91CD\u65B0\u767B\u5F55":"";throw new Error(`\u83B7\u53D6V8\u4E8B\u4EF6\u5217\u8868\u5931\u8D25: ${a.Msg||"Code="+a.Code}${D}`)}let{List:c,Total:l}=a.Data;this.log(`\u83B7\u53D6\u5230 ${l} \u4E2AV8\u4E8B\u4EF6`);let d=await ke.getInstance().getSysConfig(r,i),u=d?.SysShortTitle||"",g=d?.SysTitle||"",m=u||g||d?.CompanyName||e.label||"";m&&(m!==e.label||u!==e.sysShortTitle||g!==e.sysTitle)&&await t.addProfile({...e,label:m,sysShortTitle:u,sysTitle:g});let f=t.getSyncRootDir(),y=t.buildServerDirName(m,r),C=this.loadMeta(y),h=0,S=0,b=0,E=new Set(c.map(D=>`${D.FormEngineKey}__${D.EventType}`)),I=t.getProfiles().find(D=>D.apiBaseUrl===e.apiBaseUrl&&D.osClient===e.osClient)||e;if(!I.osClientType||!I.osClientNetwork)throw new Error("\u7F3A\u5C11 OsClientType/OsClientNetwork\uFF0C\u8BF7\u5148\u62C9\u53D6\u63A5\u53E3\u5F15\u64CE\u4EE5\u83B7\u53D6\u5B8C\u6574\u914D\u7F6E");let w=t.buildOsClientDirName(i,I.osClientType,I.osClientNetwork),O={SubmitBeforeServerV8:"\u540E\u7AEF\u63D0\u4EA4\u524DV8\u4E8B\u4EF6",SubmitAfterServerV8:"\u540E\u7AEF\u63D0\u4EA4\u540EV8\u4E8B\u4EF6",SubmitFormV8:"\u524D\u7AEF\u8868\u5355\u63D0\u4EA4V8\u4E8B\u4EF6",OutFormV8:"\u524D\u7AEF\u8868\u5355\u9000\u51FAV8\u4E8B\u4EF6",ServerDataV8:"\u540E\u7AEF\u6570\u636EV8\u4E8B\u4EF6"};for(let D of c){let $=D.V8Code||"",T=X(D.Description?`${D.Description}\uFF08${D.FormEngineKey}\uFF09`:D.FormEngineKey),P=xr[D.EventType]||D.EventType,M=X(`${P}\uFF08${D.EventType}\uFF09`)+".js",J=_.join(f,y,w,Le,T,Zt);me(J);let Y=_.join(J,M),pe=O[D.EventType];if(pe){let Ce=X(`${pe}\uFF08${D.EventType}\uFF09`)+".js",de=_.join(J,Ce);de!==Y&&v.existsSync(de)&&!this.isLocalModified(de,D.UpdateTime)&&(v.existsSync(Y)?v.unlinkSync(de):v.renameSync(de,Y))}let he=`${D.FormEngineKey}__${D.EventType}`;if(C.events[he]={id:D.Id,formEngineKey:D.FormEngineKey,description:D.Description||"",eventType:D.EventType,updateTime:D.UpdateTime,filePath:_.relative(t.getWorkspaceRoot(),Y)},!$.trim()){v.existsSync(Y)&&this.backupAndDeleteSyncFile(Y,y,"remote-deleted-form-event"),b++,h++,o.report({message:`${h}/${l}`,increment:l>0?1/l*100:void 0});continue}v.writeFileSync(Y,$,"utf-8");let re=new Date(D.UpdateTime);isNaN(re.getTime())||v.utimesSync(Y,re,re),S++,h++,o.report({message:`${h}/${l}`,increment:l>0?1/l*100:void 0})}for(let[D,$]of Object.entries(C.events)){if(E.has(D))continue;let T=this.getWorkspaceFilePath($.filePath);T&&this.backupAndDeleteSyncFile(T,y,"remote-deleted-form-event"),delete C.events[D]}this.saveMeta(C,y);let A=m||e.label||r;this.log(`[${A}] \u62C9\u53D6\u5B8C\u6210: ${S} \u4E2AV8\u4E8B\u4EF6\u6587\u4EF6\uFF0C\u8DF3\u8FC7\u7A7A\u4EE3\u7801 ${b} \u9879`),F.info(`Microi: [${A}] \u6210\u529F\u62C9\u53D6 ${S} \u4E2AV8\u4E8B\u4EF6\u6587\u4EF6${b>0?`\uFF08\u8DF3\u8FC7 ${b} \u4E2A\u7A7A\u4EE3\u7801\u4E8B\u4EF6\uFF09`:""}`)})}async pullWorkflows(e){if(!e){let t=N.getInstance().getProfiles();if(t.length===0)return;for(let n of t)try{await this.pullWorkflowsForProfile(n)}catch(r){let i=r instanceof Error?r.message:String(r);this.log(`\u62C9\u53D6\u6D41\u7A0B\u5F15\u64CE\u5931\u8D25 [${n.label||n.apiBaseUrl}]: ${i}`)}return}await this.pullWorkflowsForProfile(e)}async pullWorkflowsForProfile(e){let t=N.getInstance(),n=L.getInstance(),r=e.apiBaseUrl,i=e.osClient;this.log(`\u5F00\u59CB\u5168\u91CF\u62C9\u53D6\u6D41\u7A0B\u5F15\u64CE\u8282\u70B9 V8 [${e.label||r}]...`),await Se.withProgress({location:tt.Notification,title:`Microi: \u62C9\u53D6\u6D41\u7A0B\u5F15\u64CE [${e.label||r}]`,cancellable:!1},async o=>{o.report({message:"\u83B7\u53D6\u6D41\u7A0B\u8282\u70B9V8\u5217\u8868..."});let a=await n.get(H.GET_WORKFLOW_V8_EVENT_LIST,{osClient:i},r,e);if(a.Code!==1){let P=a.Code===1001||a.Code===1002?"\uFF0C\u8BF7\u91CD\u65B0\u767B\u5F55":"";throw new Error(`\u83B7\u53D6\u6D41\u7A0B\u8282\u70B9V8\u5217\u8868\u5931\u8D25: ${a.Msg||"Code="+a.Code}${P}`)}let l=await ke.getInstance().getSysConfig(r,i),p=l?.SysShortTitle||"",d=l?.SysTitle||"",u=p||d||l?.CompanyName||e.label||"";u&&(u!==e.label||p!==e.sysShortTitle||d!==e.sysTitle)&&await t.addProfile({...e,label:u,sysShortTitle:p,sysTitle:d});let m=t.getProfiles().find(P=>P.apiBaseUrl===e.apiBaseUrl&&P.osClient===e.osClient)||e;if(!m.osClientType||!m.osClientNetwork)throw new Error("\u7F3A\u5C11 OsClientType/OsClientNetwork\uFF0C\u8BF7\u5148\u62C9\u53D6\u63A5\u53E3\u5F15\u64CE");let f=a.Data.OsClient||i,y=t.buildServerDirName(u,r),C=t.buildOsClientDirName(f,m.osClientType,m.osClientNetwork),h=t.getSyncRootDir(),S=this.loadMeta(y);S.workflows||(S.workflows={}),S.workflowNodeEvents||(S.workflowNodeEvents={});let b=a.Data.Flows||[],E=a.Data.Nodes||[],k=a.Data.Lines||[],I=a.Data.List||[],w=new Map(b.map(P=>[String(P.Id||""),P])),O=new Set(b.map(P=>String(P.Id||"")).filter(Boolean)),A=new Set(I.filter(P=>String(P.V8Code||P.Code||"").trim()).map(P=>`${P.FlowDesignId}__${P.NodeId}__${P.EventType}`)),D=0,$=0;for(let P of b){let M=String(P.Id||"");if(!M)continue;let J=String(P.FlowName||M),Y=String(P.UpdateTime||Te()),pe=_.join(h,y,C,it,X(`${J}\uFF08${M}\uFF09`));me(pe);let he=E.filter(de=>String(de.FlowDesignId||"")===M),re=k.filter(de=>String(de.FlowDesignId||"")===M),Ce=_.join(pe,"\u6D41\u7A0B\u8BBE\u8BA1\u56FE\uFF08WF_FlowDesign\uFF09.json");v.writeFileSync(Ce,JSON.stringify({FlowDesign:P,Nodes:he,Lines:re},null,2),"utf-8"),this.touchSyncedFile(Ce,Y),S.workflows[M]={flowDesignId:M,flowName:J,updateTime:Y,filePath:_.relative(t.getWorkspaceRoot(),Ce)}}for(let P of I){let M=String(P.FlowDesignId||""),J=String(P.NodeId||""),Y=String(P.EventType||"");if(!M||!J||!Y)continue;let pe=w.get(M),he=String(P.FlowName||pe?.FlowName||M),re=String(P.NodeName||J),Ce=Fr[Y]||P.EventName||Y,de=_.join(h,y,C,it,X(`${he}\uFF08${M}\uFF09`),en,X(`${re}\uFF08${J}\uFF09`));me(de);let V=_.join(de,X(`${Ce}\uFF08${Y}\uFF09`)+".js"),ye=P.V8Code||P.Code||"",ae=String(P.UpdateTime||pe?.UpdateTime||Te());if(S.workflowNodeEvents[`${M}__${J}__${Y}`]={flowDesignId:M,flowName:he,nodeId:J,nodeName:re,eventType:Y,updateTime:ae,filePath:_.relative(t.getWorkspaceRoot(),V)},!ye.trim()){v.existsSync(V)&&this.backupAndDeleteSyncFile(V,y,"remote-deleted-workflow-event"),$++,o.report({message:`${D}/${I.length} ${he}/${re}`});continue}v.writeFileSync(V,ye,"utf-8"),this.touchSyncedFile(V,ae),D++,o.report({message:`${D}/${I.length} ${he}/${re}`})}for(let[P,M]of Object.entries(S.workflowNodeEvents)){if(A.has(P))continue;let J=this.getWorkspaceFilePath(M.filePath);J&&this.backupAndDeleteSyncFile(J,y,"remote-deleted-workflow-event"),delete S.workflowNodeEvents[P]}for(let[P,M]of Object.entries(S.workflows)){if(O.has(P))continue;let J=this.getWorkspaceFilePath(M.filePath);J&&this.backupAndDeleteSyncFile(J,y,"remote-deleted-workflow"),delete S.workflows[P]}this.saveMeta(S,y);let T=u||e.label||r;this.log(`[${T}] \u6D41\u7A0B\u5F15\u64CE\u62C9\u53D6\u5B8C\u6210: ${b.length} \u4E2A\u6D41\u7A0B\uFF0C${D} \u4E2A\u8282\u70B9V8\u6587\u4EF6\uFF0C\u8DF3\u8FC7\u7A7A\u4EE3\u7801 ${$} \u9879`),F.info(`Microi: [${T}] \u6210\u529F\u62C9\u53D6 ${b.length} \u4E2A\u6D41\u7A0B\u3001${D} \u4E2A\u6D41\u7A0B\u8282\u70B9V8\u6587\u4EF6${$>0?`\uFF08\u8DF3\u8FC7 ${$} \u4E2A\u7A7A\u4EE3\u7801\u4E8B\u4EF6\uFF09`:""}`)})}findProfileByServerDir(e){let t=N.getInstance(),n=t.getProfiles();for(let r of n)if(t.buildServerDirName(r.label,r.apiBaseUrl)===e)return r}hasSyncBaseline(e,t){let n=_.resolve(e).toLowerCase(),r=this.loadMeta(t);return[r.engines,r.events,r.fields||{},r.menuButtons||{},r.menuScripts||{},r.workflowNodeEvents||{}].some(o=>Object.values(o).some(a=>{let c=this.getWorkspaceFilePath(a.filePath);return!!c&&_.resolve(c).toLowerCase()===n}))}async runPushPreflight(e,t,n,r){if(!n){let i=`\u65E0\u6CD5\u8BC6\u522B\u6587\u4EF6\u6240\u5C5E\u670D\u52A1\u5668\u914D\u7F6E\uFF0C\u5DF2\u505C\u6B62\u63A8\u9001\uFF1A${e}`;return this.log(i),F.error(`Microi: ${i}`),!1}if(!this.hasSyncBaseline(e,t)){let i=`\u6587\u4EF6\u6CA1\u6709\u540C\u6B65\u57FA\u7EBF\uFF0C\u65E0\u6CD5\u786E\u8BA4\u670D\u52A1\u5668\u7AEF\u662F\u5426\u66F4\u65B0\uFF0C\u5DF2\u505C\u6B62\u63A8\u9001\u3002\u8BF7\u5148\u62C9\u53D6\u5BF9\u5E94\u5F15\u64CE\uFF1A${e}`;return this.log(i),F.error(`Microi: ${i}`),!1}try{let i=await this.checkRemoteDifferences(n,r,e),o=_.resolve(e).toLowerCase(),a=i.find(p=>_.resolve(p.filePath).toLowerCase()===o);if(!a||a.status==="localModified")return!0;let l=`${a.status==="conflict"?"\u672C\u5730\u4E0E\u670D\u52A1\u5668\u5747\u5DF2\u4FEE\u6539":a.status==="remoteDeleted"?"\u670D\u52A1\u5668\u7AEF\u8D44\u6E90\u5DF2\u5220\u9664":"\u670D\u52A1\u5668\u4EE3\u7801\u8F83\u65B0"}\uFF0C\u5DF2\u505C\u6B62\u63A8\u9001\u4EE5\u907F\u514D\u8986\u76D6\u3002\u8BF7\u5728\u201C\u540C\u6B65\u7ED3\u679C\u201D\u4E2D\u67E5\u770B\u5DEE\u5F02\u5E76\u62C9\u53D6\u6216\u5408\u5E76\uFF1A${a.name}`;return this.log(l),F.error(`Microi: ${l}`),!1}catch(i){let o=i instanceof Error?i.message:String(i);return this.log(`\u63A8\u9001\u524D\u540C\u6B65\u72B6\u6001\u68C0\u6D4B\u5931\u8D25\uFF0C\u5DF2\u505C\u6B62\u63A8\u9001\uFF1A${o}`),F.error(`Microi: \u63A8\u9001\u524D\u540C\u6B65\u72B6\u6001\u68C0\u6D4B\u5931\u8D25\uFF0C\u5DF2\u505C\u6B62\u63A8\u9001 - ${o}`),!1}}async pushFile(e,t={}){let r=N.getInstance().getSyncRootDir();if(_.extname(e).toLowerCase()===".js"&&v.existsSync(e)){let d=Wr(Fe(v.readFileSync(e,"utf-8")));if(d.length>0){let u=d[0],g=`\u68C0\u6D4B\u5230 AI/\u7EC8\u7AEF\u5DE5\u5177\u8F93\u51FA\u6C61\u67D3\uFF08\u7B2C ${u.line} \u884C: ${u.marker}\uFF09\uFF0C\u5DF2\u505C\u6B62\u63A8\u9001\u3002\u8BF7\u6062\u590D\u5B8C\u6574\u6E90\u7801\u540E\u518D\u8BD5\uFF1A${e}`;return this.log(g),F.error(`Microi: ${g}`),!1}}let i=Lr(e,r);if(i){let d=this.findProfileByServerDir(i.serverDir);return!t.skipPreflight&&!await this.runPushPreflight(e,i.serverDir,d,"api")?!1:this.pushEngineFile(e,i,d)}let o=Ur(e,r);if(o){let d=this.findProfileByServerDir(o.serverDir);return!t.skipPreflight&&!await this.runPushPreflight(e,o.serverDir,d,"form")?!1:this.pushEventFile(e,o,d)}let a=jr(e,r);if(a){let d=this.findProfileByServerDir(a.serverDir);return!t.skipPreflight&&!await this.runPushPreflight(e,a.serverDir,d,"form")?!1:this.pushFieldFile(e,a,d)}let c=Kr(e,r);if(c){let d=this.findProfileByServerDir(c.serverDir);return!t.skipPreflight&&!await this.runPushPreflight(e,c.serverDir,d,"module")?!1:this.pushMenuButtonFile(e,c,d)}let l=Hr(e,r);if(l){let d=this.findProfileByServerDir(l.serverDir);return!t.skipPreflight&&!await this.runPushPreflight(e,l.serverDir,d,"module")?!1:this.pushMenuScriptFile(e,l,d)}let p=Gr(e,r);if(p){let d=this.findProfileByServerDir(p.serverDir);return!t.skipPreflight&&!await this.runPushPreflight(e,p.serverDir,d,"workflow")?!1:this.pushWorkflowNodeFile(e,p,d)}return this.log(`\u65E0\u6CD5\u89E3\u6790\u6587\u4EF6\u8DEF\u5F84: ${e}`),!1}async pushEngineFile(e,t,n){let r=L.getInstance(),i=v.readFileSync(e,"utf-8"),o=Fe(i);this.log(`\u63A8\u9001\u63A5\u53E3\u5F15\u64CE: ${t.apiEngineKey}...`);try{let a="",c="";try{let g=await r.post(H.GET_ENGINE_CODE,{OsClient:t.osClient,ApiEngineKey:t.apiEngineKey},void 0,n?.apiBaseUrl,n);g.Code===1&&g.Data&&(a=g.Data.ApiV8Code||g.Data.Code||"",c=g.Data.Version||"")}catch{a="",c=""}let l=!o.trim(),p=l?{code:"",version:c,changeHistory:""}:Bt({kind:"ApiEngine",key:t.apiEngineKey,currentCode:o,remoteCode:a,remoteVersion:c,changeSummary:`\u901A\u8FC7 VS Code \u63A8\u9001\u63A5\u53E3\u5F15\u64CE ${t.apiEngineKey}`}),d={OsClient:t.osClient,ApiEngineKey:t.apiEngineKey,ApiV8CodeBase64:Buffer.from(p.code,"utf8").toString("base64")};l||(d.Version=p.version,d.ChangeSummary=p.changeHistory);let u=await r.post(H.UPDATE_ENGINE_CODE,d,void 0,n?.apiBaseUrl,n);if(u.Code===1){this.log(`\u63A8\u9001\u6210\u529F: ${t.apiEngineKey}`);let g=u.Data?.UpdateTime||Te(),m=this.loadMeta(t.serverDir);if(l?delete m.engines[t.apiEngineKey]:m.engines[t.apiEngineKey]&&(m.engines[t.apiEngineKey].updateTime=g),this.saveMeta(m,t.serverDir),l)v.existsSync(e)&&v.unlinkSync(e);else{v.writeFileSync(e,p.code,"utf-8");let f=new Date(g);isNaN(f.getTime())||v.utimesSync(e,f,f)}return!0}else return this.log(`\u63A8\u9001\u5931\u8D25: ${t.apiEngineKey} - ${u.Msg}`),F.error(`Microi: \u63A8\u9001\u5931\u8D25 - ${u.Msg}`),!1}catch(a){let c=a instanceof Error?a.message:String(a);return this.log(`\u63A8\u9001\u5F02\u5E38: ${t.apiEngineKey} - ${c}`),F.error(`Microi: \u63A8\u9001\u5F02\u5E38 - ${c}`),!1}}async pushEventFile(e,t,n){let r=L.getInstance(),i=v.readFileSync(e,"utf-8"),o=Fe(i);this.log(`\u63A8\u9001V8\u4E8B\u4EF6: ${t.formEngineKey}/${t.eventType}...`);try{let a="",c="";try{let g=await r.post(H.GET_EVENT_CODE,{OsClient:t.osClient,FormEngineKey:t.formEngineKey,EventType:t.eventType},void 0,n?.apiBaseUrl,n);g.Code===1&&g.Data&&(a=g.Data.V8Code||g.Data.Code||"",c=g.Data.Version||"")}catch{a="",c=""}let l=!o.trim(),p=l?{code:"",version:c,changeHistory:""}:Bt({kind:"V8Event",key:t.formEngineKey,eventType:t.eventType,currentCode:o,remoteCode:a,remoteVersion:c,changeSummary:`\u901A\u8FC7 VS Code \u63A8\u9001 V8 \u4E8B\u4EF6 ${t.formEngineKey}/${t.eventType}`}),d={OsClient:t.osClient,FormEngineKey:t.formEngineKey,EventType:t.eventType,V8Code:p.code};l||(d.Version=p.version,d.ChangeHistory=p.changeHistory);let u=await r.post(H.UPDATE_EVENT_CODE,d,void 0,n?.apiBaseUrl,n);if(u.Code===1){this.log(`\u63A8\u9001\u6210\u529F: ${t.formEngineKey}/${t.eventType}`);let g=u.Data?.UpdateTime||Te(),m=this.loadMeta(t.serverDir),f=`${t.formEngineKey}__${t.eventType}`;if(l)delete m.events[f];else{let y=m.events[f];m.events[f]={id:y?.id||"",formEngineKey:t.formEngineKey,description:y?.description||"",eventType:t.eventType,updateTime:g,filePath:_.relative(N.getInstance().getWorkspaceRoot(),e)}}if(this.saveMeta(m,t.serverDir),l)v.existsSync(e)&&v.unlinkSync(e);else{v.writeFileSync(e,p.code,"utf-8");let y=new Date(g);isNaN(y.getTime())||v.utimesSync(e,y,y)}return!0}else return this.log(`\u63A8\u9001\u5931\u8D25: ${t.formEngineKey}/${t.eventType} - ${u.Msg}`),F.error(`Microi: \u63A8\u9001\u5931\u8D25 - ${u.Msg}`),!1}catch(a){let c=a instanceof Error?a.message:String(a);return this.log(`\u63A8\u9001\u5F02\u5E38: ${t.formEngineKey}/${t.eventType} - ${c}`),F.error(`Microi: \u63A8\u9001\u5F02\u5E38 - ${c}`),!1}}async createEngine(e){let t=L.getInstance(),n=N.getInstance();this.log(`\u521B\u5EFA\u63A5\u53E3\u5F15\u64CE: ${e.apiEngineKey}...`);try{let r=Bt({kind:"ApiEngine",key:e.apiEngineKey,currentCode:"",functionDescription:`\u63A5\u53E3\u5F15\u64CE ${e.apiName} \u7684\u5B8C\u6574\u4E1A\u52A1\u903B\u8F91\u3002`,changeSummary:`\u901A\u8FC7 VS Code \u521B\u5EFA\u63A5\u53E3\u5F15\u64CE ${e.apiEngineKey}`,initial:!0}),i=await t.post(H.CREATE_ENGINE,{OsClient:e.profile.osClient,ApiName:e.apiName,ApiEngineKey:e.apiEngineKey,ApiAddress:e.apiAddress||"",ApiRoutes:e.apiRoutes||"",ApiRemark:e.apiRemark||"",Lock:e.lock?1:0,LockKey:e.lockKey||"",AllowAnonymous:e.allowAnonymous?1:0,V8Limit:e.v8Limit?1:0,IsEnable:e.isEnable!==!1?1:0,ApiRole:e.apiRole||"",Category:e.category||"\u672A\u5206\u7C7B",ApiV8CodeBase64:Buffer.from(r.code,"utf8").toString("base64"),Version:r.version,ChangeSummary:r.changeHistory},void 0,e.profile.apiBaseUrl,e.profile);if(i.Code===1){let o=n.getSyncRootDir(),a=n.buildServerDirName(e.profile.label,e.profile.apiBaseUrl),c=n.buildOsClientDirName(e.profile.osClient,e.profile.osClientType,e.profile.osClientNetwork),l=X(e.category||"\u672A\u5206\u7C7B"),p=X(e.apiName||e.apiEngineKey),d=_.join(o,a,c,st,l);me(d);let u=_.join(d,X(`${p}(${qn(e.apiEngineKey)}).js`));v.writeFileSync(u,r.code,"utf-8");let g=this.loadMeta(a);return g.engines[e.apiEngineKey]={id:"",apiName:e.apiName,category:l,apiAddress:e.apiAddress||"",apiRoutes:e.apiRoutes||"",updateTime:Te(),filePath:_.relative(n.getWorkspaceRoot(),u)},this.saveMeta(g,a),this.log(`\u521B\u5EFA\u6210\u529F: ${e.apiEngineKey}`),F.info(`Microi: \u63A5\u53E3\u5F15\u64CE [${e.apiEngineKey}] \u521B\u5EFA\u6210\u529F`),await Se.showTextDocument(Rr.file(u)),!0}else return this.log(`\u521B\u5EFA\u5931\u8D25: ${e.apiEngineKey} - ${i.Msg}`),F.error(`Microi: \u521B\u5EFA\u5931\u8D25 - ${i.Msg}`),!1}catch(r){let i=r instanceof Error?r.message:String(r);return this.log(`\u521B\u5EFA\u5F02\u5E38: ${e.apiEngineKey} - ${i}`),F.error(`Microi: \u521B\u5EFA\u5F02\u5E38 - ${i}`),!1}}async pullFields(e){if(!e){let t=N.getInstance().getProfiles();for(let n of t)try{await this.pullFieldsForProfile(n)}catch(r){this.log(`\u62C9\u53D6\u5B57\u6BB5V8\u4E8B\u4EF6\u5931\u8D25 [${n.label||n.apiBaseUrl}]: ${r instanceof Error?r.message:String(r)}`)}return}await this.pullFieldsForProfile(e)}async pullFieldsForTableFolder(e){let n=N.getInstance().getSyncRootDir(),r=_.relative(n,e).split(_.sep);if(r.length<4||r[2]!==Le){F.warn("Microi: \u8BF7\u5728\u201C\u8868\u5355\u5F15\u64CE\u201D\u4E0B\u7684\u8868\u76EE\u5F55\u6267\u884C\u5B57\u6BB5 V8 \u4E8B\u4EF6\u62C9\u53D6");return}let i=a=>{let c=a.match(/[((]([^))]+)[))]\s*$/);return c?c[1]:a},o=this.findProfileByServerDir(r[0]);if(!o){F.error(`Microi: \u672A\u627E\u5230\u4E0E\u76EE\u5F55 "${r[0]}" \u5339\u914D\u7684\u670D\u52A1\u5668\u8FDE\u63A5`);return}await this.pullFieldsForTable(o,i(r[3]),e,r[0])}async pullFieldsForTable(e,t,n,r){let i=N.getInstance(),o=L.getInstance(),a=this.loadMeta(r);a.fields||(a.fields={}),this.log(`\u62C9\u53D6\u8868\u5B57\u6BB5V8\u4E8B\u4EF6: ${t}...`);let c=await o.get(H.GET_FIELD_LIST,{osClient:e.osClient,tableName:t},e.apiBaseUrl,e);if(c.Code!==1){F.error(`Microi: \u62C9\u53D6\u5B57\u6BB5V8\u4E8B\u4EF6\u5931\u8D25 - ${c.Msg}`);return}let l=c.Data.List||[],p=["V8Code","KeyupV8Code","V8TmpEngineTable","V8TmpEngineForm"],d=0,u=0;for(let g of l){let m=X(g.Label?`${g.Label}\uFF08${g.Name}\uFF09`:g.Name),f=_.join(n,Et,m);for(let y of p){let C=(g[y]||"").toString(),h=$n[y]||y,S=X(`${h}\uFF08${y}\uFF09`)+".js",b=_.join(f,S),E=`${t}__${g.Name}__${y}`;if(!C.trim()){u++,v.existsSync(b)&&v.unlinkSync(b),delete a.fields[E];continue}me(f),v.writeFileSync(b,C,"utf-8");let k=new Date(g.UpdateTime);isNaN(k.getTime())||v.utimesSync(b,k,k),a.fields[E]={fieldId:g.Id,tableId:g.TableId,tableName:t,fieldName:g.Name,fieldLabel:g.Label||"",v8Key:y,updateTime:g.UpdateTime,filePath:_.relative(i.getWorkspaceRoot(),b)},d++}}this.saveMeta(a,r),F.info(`Microi: \u5DF2\u62C9\u53D6 ${t} \u7684 ${d} \u4E2A\u5B57\u6BB5V8\u4E8B\u4EF6\u6587\u4EF6${u>0?`\uFF08\u8DF3\u8FC7 ${u} \u4E2A\u7A7A\u4EE3\u7801\uFF09`:""}`)}async pullFieldsForProfile(e){let t=N.getInstance(),n=L.getInstance(),r=e.apiBaseUrl,i=e.osClient;this.log(`\u5F00\u59CB\u5168\u91CF\u62C9\u53D6\u5B57\u6BB5V8\u4E8B\u4EF6 [${e.label||r}]...`),await Se.withProgress({location:tt.Notification,title:`Microi: \u62C9\u53D6\u5B57\u6BB5V8\u4E8B\u4EF6 [${e.label||r}]`,cancellable:!1},async o=>{o.report({message:"\u83B7\u53D6\u8868\u5217\u8868..."});let a=await n.get(H.GET_DB_SCHEMA,{osClient:i},r,e);if(a.Code!==1)throw new Error(`\u83B7\u53D6\u8868\u5217\u8868\u5931\u8D25: ${a.Msg||"Code="+a.Code}`);let c=a.Data.Tables||[],p=await ke.getInstance().getSysConfig(r,i),d=p?.SysShortTitle||"",u=p?.SysTitle||"",g=d||u||e.label||"",m=t.buildServerDirName(g,r),f=this.loadMeta(m);f.fields||(f.fields={});let C=t.getProfiles().find(A=>A.apiBaseUrl===e.apiBaseUrl&&A.osClient===e.osClient)||e;if(!C.osClientType||!C.osClientNetwork)throw new Error("\u7F3A\u5C11 OsClientType/OsClientNetwork\uFF0C\u8BF7\u5148\u62C9\u53D6\u63A5\u53E3\u5F15\u64CE");let h=t.buildOsClientDirName(i,C.osClientType,C.osClientNetwork),S=t.getSyncRootDir(),b=["V8Code","KeyupV8Code","V8TmpEngineTable","V8TmpEngineForm"],E=0,k=0,I=0,w=new Set,O=new Set;for(let A of c){I++,o.report({message:`[${I}/${c.length}] ${A.Name}`});let D=await n.get(H.GET_FIELD_LIST,{osClient:i,tableId:A.Id},r,e);if(D.Code!==1){O.add(A.Name.toLowerCase()),this.log(` \u8DF3\u8FC7\u8868 ${A.Name}: ${D.Msg}`);continue}let $=D.Data.List||[],T=X(A.Description?`${A.Description}\uFF08${A.Name}\uFF09`:A.Name);for(let P of $)for(let M of b){let J=(P[M]||"").toString();if(!J.trim()){k++;continue}let Y=X(P.Label?`${P.Label}\uFF08${P.Name}\uFF09`:P.Name),pe=$n[M]||M,he=X(`${pe}\uFF08${M}\uFF09`)+".js",re=_.join(S,m,h,Le,T,Et,Y);me(re);let Ce=_.join(re,he);v.writeFileSync(Ce,J,"utf-8");let de=new Date(P.UpdateTime);isNaN(de.getTime())||v.utimesSync(Ce,de,de);let V=`${A.Name}__${P.Name}__${M}`;w.add(V),f.fields[V]={fieldId:P.Id,tableId:P.TableId,tableName:A.Name,fieldName:P.Name,fieldLabel:P.Label||"",v8Key:M,updateTime:P.UpdateTime,filePath:_.relative(t.getWorkspaceRoot(),Ce)},E++}}for(let[A,D]of Object.entries(f.fields)){if(w.has(A)||O.has(D.tableName.toLowerCase()))continue;let $=this.getWorkspaceFilePath(D.filePath);$&&this.backupAndDeleteSyncFile($,m,"remote-deleted-field-event"),delete f.fields[A]}this.saveMeta(f,m),this.log(`\u5B57\u6BB5V8\u4E8B\u4EF6\u62C9\u53D6\u5B8C\u6210: ${E} \u4E2A\u6587\u4EF6\uFF0C\u8DF3\u8FC7\u7A7A\u4EE3\u7801 ${k} \u9879`),F.info(`Microi: \u6210\u529F\u62C9\u53D6 ${E} \u4E2A\u5B57\u6BB5V8\u4E8B\u4EF6${k>0?`\uFF08\u8DF3\u8FC7 ${k} \u4E2A\u7A7A\u4EE3\u7801\uFF09`:""}`)})}async pushFieldFile(e,t,n){let r=L.getInstance(),i=Fe(v.readFileSync(e,"utf-8"));this.log(`\u63A8\u9001\u5B57\u6BB5V8\u4E8B\u4EF6: ${t.tableName}/${t.fieldName}/${t.v8Key}...`);try{let o=await r.post(H.UPDATE_FIELD,{OsClient:t.osClient,TableName:t.tableName,Name:t.fieldName,[t.v8Key]:i},void 0,n?.apiBaseUrl,n);if(o.Code===1){this.log(`\u63A8\u9001\u6210\u529F: ${t.tableName}/${t.fieldName}/${t.v8Key}`);let a=this.loadMeta(t.serverDir),c=`${t.tableName}__${t.fieldName}__${t.v8Key}`;a.fields||(a.fields={});let l=o.Data?.UpdateTime||Te();return i.trim()?a.fields[c]={fieldId:a.fields[c]?.fieldId||"",tableId:a.fields[c]?.tableId||"",tableName:t.tableName,fieldName:t.fieldName,fieldLabel:a.fields[c]?.fieldLabel||"",v8Key:t.v8Key,updateTime:l,filePath:_.relative(N.getInstance().getWorkspaceRoot(),e)}:delete a.fields[c],this.saveMeta(a,t.serverDir),i.trim()?this.touchSyncedFile(e,l):v.existsSync(e)&&v.unlinkSync(e),!0}return this.log(`\u63A8\u9001\u5931\u8D25: ${o.Msg}`),F.error(`Microi: \u63A8\u9001\u5B57\u6BB5V8\u4E8B\u4EF6\u5931\u8D25 - ${o.Msg}`),!1}catch(o){let a=o instanceof Error?o.message:String(o);return this.log(`\u63A8\u9001\u5F02\u5E38: ${a}`),F.error(`Microi: \u63A8\u9001\u5F02\u5E38 - ${a}`),!1}}async pullMenuButtons(e){if(!e){let t=N.getInstance().getProfiles();for(let n of t)try{await this.pullMenuButtonsForProfile(n)}catch(r){this.log(`\u62C9\u53D6\u83DC\u5355\u6309\u94AE\u5931\u8D25 [${n.label||n.apiBaseUrl}]: ${r instanceof Error?r.message:String(r)}`)}return}await this.pullMenuButtonsForProfile(e)}async pullMenuButtonsForModuleFolder(e){let n=N.getInstance().getSyncRootDir(),r=_.relative(n,e).split(_.sep);if(r.length<4||r[2]!==Ge){F.warn("Microi: \u8BF7\u5728\u201C\u6A21\u5757\u5F15\u64CE\u201D\u4E0B\u7684\u6A21\u5757\u76EE\u5F55\u6267\u884C\u62C9\u53D6");return}let i=this.findProfileByServerDir(r[0]);if(!i){F.error(`Microi: \u672A\u627E\u5230\u4E0E\u76EE\u5F55 "${r[0]}" \u5339\u914D\u7684\u670D\u52A1\u5668\u8FDE\u63A5`);return}let o=this.extractTrailingKey(_.basename(e));await this.pullMenuButtonsForProfile(i,o,r[0],r[1],e)}async pullMenuButtonsForProfile(e,t,n,r,i){let o=N.getInstance(),a=L.getInstance(),c=e.apiBaseUrl,l=e.osClient;this.log(`\u5F00\u59CB\u62C9\u53D6\u6A21\u5757 Join/Where \u4E0E\u6309\u94AE V8 \u4EE3\u7801 [${e.label||c}]...`),await Se.withProgress({location:tt.Notification,title:`Microi: \u62C9\u53D6\u6A21\u5757\u4EE3\u7801 [${e.label||c}]`,cancellable:!1},async p=>{let d=await a.get(H.LIST_MODULES,{osClient:l},c,e);if(d.Code!==1)throw new Error(`\u83B7\u53D6\u6A21\u5757\u5217\u8868\u5931\u8D25: ${d.Msg}`);let u=d.Data.List||[],m=await ke.getInstance().getSysConfig(c,l),f=m?.SysShortTitle||"",y=m?.SysTitle||"",C=f||y||e.label||"",h=n||o.buildServerDirName(C,c),S=this.loadMeta(h);S.menus||(S.menus={}),S.menuButtons||(S.menuButtons={}),S.menuScripts||(S.menuScripts={});let E=o.getProfiles().find(V=>V.apiBaseUrl===e.apiBaseUrl&&V.osClient===e.osClient)||e;if(!E.osClientType||!E.osClientNetwork)throw new Error("\u7F3A\u5C11 OsClientType/OsClientNetwork\uFF0C\u8BF7\u5148\u62C9\u53D6\u63A5\u53E3\u5F15\u64CE");let k=r||o.buildOsClientDirName(l,E.osClientType,E.osClientNetwork),I=o.getSyncRootDir(),w=_.join(I,h,k,Ge),O=Object.keys(ot),A=Object.keys(Tt),D=0,$=0,T=0,P=0,M=0,J=new Map(u.map(V=>[V.Id,V])),Y=new Map,pe=V=>V||"";for(let V of u){let ye=pe(V.ParentId);Y.has(ye)||Y.set(ye,[]),Y.get(ye).push(V)}let he=V=>V.sort((ye,ae)=>{let be=typeof ye.Sort=="number"?ye.Sort:0,wt=typeof ae.Sort=="number"?ae.Sort:0;return be!==wt?be-wt:String(ye.Name||ye.Label||"").localeCompare(String(ae.Name||ae.Label||""))}),re=t?J.get(t)?[J.get(t)]:[]:he(u.filter(V=>!V.ParentId||!J.has(V.ParentId)));if(t&&re.length===0)throw new Error(`\u627E\u4E0D\u5230\u6A21\u5757 Id=${t}`);let Ce=t?i||_.join(w,X(`${re[0].Label||re[0].Name||re[0].Id}\uFF08${re[0].Id}\uFF09`)):w;if(this.backupExistingTree(Ce,h,t?"module-subtree":"module-engine"),!t)S.menus={},S.menuButtons={},S.menuScripts={};else{let V=new Set,ye=ae=>{if(!V.has(ae)){V.add(ae);for(let be of Y.get(ae)||[])ye(be.Id)}};ye(t);for(let ae of V)delete S.menus[ae];for(let[ae,be]of Object.entries(S.menuButtons))V.has(be.moduleId)&&delete S.menuButtons[ae];for(let[ae,be]of Object.entries(S.menuScripts))V.has(be.moduleId)&&delete S.menuScripts[ae]}let de=async(V,ye)=>{P++,p.report({message:`[${P}/${u.length}] ${V.Name||V.Label}`});let ae=V.Label||V.Name||V.Id,be=_.join(ye,X(`${ae}\uFF08${V.Id}\uFF09`));me(be);let wt=he(Y.get(V.Id)||[]);if(wt.length>0){for(let ge of wt)await de(ge,be);return}let An=await a.get(H.GET_MODULE,{osClient:l,moduleId:V.Id},c,e);if(An.Code!==1){this.log(` \u8DF3\u8FC7\u6A21\u5757 ${V.Name}: ${An.Msg}`);return}let Mn=An.Data,He=String(Mn.UpdateTime||Te()),vr={};for(let ge of A){let Jt=String(Mn[ge]||""),xn=Tt[ge]||ge,We=_.join(be,X(`${xn}\uFF08${ge}\uFF09`)+".js");v.writeFileSync(We,Jt,"utf-8"),this.touchSyncedFile(We,He),S.menuScripts[this.getMenuScriptMetaKey(V.Id,ge)]={moduleId:V.Id,moduleName:ae,scriptField:ge,codeHash:this.sourceHash(Jt),updateTime:He,filePath:_.relative(o.getWorkspaceRoot(),We)},T++}for(let ge of O){let Jt=ot[ge]||ge,xn=X(`${Jt}\uFF08${ge}\uFF09`),We=_.join(be,xn);me(We),$++;let qt=Mn[ge],Xe=[];if(qt)try{Xe=typeof qt=="string"?JSON.parse(qt):qt,Array.isArray(Xe)||(Xe=[])}catch{this.log(` \u6309\u94AE JSON \u89E3\u6790\u5931\u8D25 ${V.Name}.${ge}`),Xe=[]}let gi=[...Xe].sort((Ze,Ie)=>String(Ze.Id||"").localeCompare(String(Ie.Id||"")));vr[ge]=require("crypto").createHash("sha1").update(JSON.stringify(gi)).digest("hex");for(let Ze of Xe){let Ie=String(Ze.Id||""),Yt=String(Ze.Name||Ie||"Unknown");if(!Ie)continue;let Er=String(Ze.V8Code||""),Fn=_.join(We,X(`${Yt}\uFF08${Ie}\uFF09`)+".js");S.menuButtons[this.getMenuButtonMetaKey(V.Id,ge,Ie,"V8Code")]={moduleId:V.Id,moduleName:ae,btnField:ge,btnId:Ie,btnName:Yt,v8SubField:"V8Code",updateTime:He,filePath:_.relative(o.getWorkspaceRoot(),Fn)},Er.trim()?(v.writeFileSync(Fn,Er,"utf-8"),this.touchSyncedFile(Fn,He),D++):M++;let Tr=String(Ze.V8CodeShow||"");if(Tr.trim()){let Vn=_.join(We,X(`${Yt}_\u663E\u9690\u5224\u65AD\uFF08${Ie}\uFF09`)+".js");v.writeFileSync(Vn,Tr,"utf-8"),this.touchSyncedFile(Vn,He),S.menuButtons[this.getMenuButtonMetaKey(V.Id,ge,Ie,"V8CodeShow")]={moduleId:V.Id,moduleName:ae,btnField:ge,btnId:Ie,btnName:Yt,v8SubField:"V8CodeShow",updateTime:He,filePath:_.relative(o.getWorkspaceRoot(),Vn)},D++}else M++}}S.menus[V.Id]={moduleId:V.Id,moduleName:ae,updateTime:He,buttonHashes:vr}};me(w);for(let V of re)await de(V,w);this.saveMeta(S,h),this.log(`\u6A21\u5757\u4EE3\u7801\u62C9\u53D6\u5B8C\u6210: ${D} \u4E2A\u6309\u94AEV8\u6587\u4EF6\uFF0C${T} \u4E2A Join/Where \u6587\u4EF6\uFF0C${$} \u4E2A\u6309\u94AE\u76EE\u5F55\uFF0C\u8DF3\u8FC7\u7A7A\u6309\u94AE\u4EE3\u7801 ${M} \u9879`),F.info(`Microi: \u6210\u529F\u62C9\u53D6 ${D} \u4E2A\u6309\u94AEV8\u6587\u4EF6\u548C ${T} \u4E2A Join/Where \u6587\u4EF6${M>0?`\uFF08\u8DF3\u8FC7 ${M} \u4E2A\u7A7A\u6309\u94AE\u4EE3\u7801\uFF09`:""}\uFF0C\u5DF2\u751F\u6210 ${$} \u4E2A\u6309\u94AE\u76EE\u5F55`)})}backupExistingTree(e,t,n){if(!v.existsSync(e))return;let i=N.getInstance().getSyncRootDir();this.ensureSyncGitExcludes(i);let o=_.join(i,".backups",n,this.shortBackupKey(t));me(o);let a=_.join(o,`${Date.now()}-${this.shortBackupKey(_.basename(e))}`);v.renameSync(e,a)}backupAndDeleteSyncFile(e,t,n){if(!v.existsSync(e))return;let r=N.getInstance(),i=r.getSyncRootDir();this.ensureSyncGitExcludes(i);let o=r.getWorkspaceRoot()||i,c=_.relative(o,e).split(_.sep).filter(d=>d&&d!=="..").map(X),l=_.join(i,".backups",n,this.shortBackupKey(t),String(Date.now())),p=_.join(l,...c.length?c:[X(_.basename(e))]);me(_.dirname(p)),v.copyFileSync(e,p),v.unlinkSync(e)}async pushMenuScriptFile(e,t,n){let r=L.getInstance(),i=Fe(v.readFileSync(e,"utf-8"));this.log(`\u63A8\u9001\u6A21\u5757\u811A\u672C: ${t.moduleId}.${t.scriptField}...`);try{let o=await r.get(H.GET_MODULE,{osClient:t.osClient,moduleId:t.moduleId},n?.apiBaseUrl,n);if(o.Code!==1||!o.Data)return F.error(`Microi: \u63A8\u9001\u5931\u8D25 - \u62C9\u53D6\u6A21\u5757\u5931\u8D25 ${o.Msg}`),!1;let a=o.Data,c=String(a[t.scriptField]||""),l=N.getInstance(),p=l.getSyncRootDir();this.ensureSyncGitExcludes(p);let d=_.join(p,".backups","menu-script",this.shortBackupKey(t.serverDir),t.moduleId);me(d),v.writeFileSync(_.join(d,`${t.scriptField}-${Date.now()}.js`),c,"utf-8");let u={OsClient:t.osClient,ModuleId:t.moduleId,[t.scriptField]:i},g=await r.post(H.UPDATE_MODULE,u,void 0,n?.apiBaseUrl,n);if(g.Code!==1)return F.error(`Microi: \u63A8\u9001\u6A21\u5757 ${t.scriptField} \u5931\u8D25 - ${g.Msg}`),!1;let m=await r.get(H.GET_MODULE,{osClient:t.osClient,moduleId:t.moduleId},n?.apiBaseUrl,n),f=m.Data;if(m.Code!==1||!f||this.normalizeCode(String(f[t.scriptField]||""))!==this.normalizeCode(i))return F.error(`Microi: ${t.scriptField} \u63A5\u53E3\u8FD4\u56DE\u6210\u529F\uFF0C\u4F46\u8FDC\u7AEF\u56DE\u8BFB\u4E0D\u4E00\u81F4\uFF1B\u5DF2\u4FDD\u7559\u672C\u5730\u4FEE\u6539\u548C\u8FDC\u7AEF\u5907\u4EFD`),!1;let y=String(f.UpdateTime||g.Data?.UpdateTime||Te()),C=this.loadMeta(t.serverDir);return C.menuScripts||(C.menuScripts={}),C.menuScripts[this.getMenuScriptMetaKey(t.moduleId,t.scriptField)]={moduleId:t.moduleId,moduleName:String(f.Label||f.Name||a.Label||a.Name||t.moduleId),scriptField:t.scriptField,codeHash:this.sourceHash(i),updateTime:y,filePath:_.relative(l.getWorkspaceRoot(),e)},C.menus||(C.menus={}),C.menus[t.moduleId]={moduleId:t.moduleId,moduleName:String(f.Label||f.Name||a.Label||a.Name||t.moduleId),updateTime:y,buttonHashes:C.menus[t.moduleId]?.buttonHashes||{}},this.saveMeta(C,t.serverDir),this.touchSyncedFile(e,y),this.log(`\u63A8\u9001\u5E76\u56DE\u8BFB\u6210\u529F: ${t.moduleId}.${t.scriptField}`),!0}catch(o){let a=o instanceof Error?o.message:String(o);return this.log(`\u63A8\u9001\u6A21\u5757\u811A\u672C\u5F02\u5E38: ${a}`),F.error(`Microi: \u63A8\u9001\u6A21\u5757\u811A\u672C\u5F02\u5E38 - ${a}`),!1}}async pushMenuButtonFile(e,t,n){let r=L.getInstance(),i=Fe(v.readFileSync(e,"utf-8"));this.log(`\u63A8\u9001\u6309\u94AEV8\u4EE3\u7801: ${t.moduleId}.${t.btnField}.${t.btnId}.${t.v8SubField}...`);try{let o=await r.get(H.GET_MODULE,{osClient:t.osClient,moduleId:t.moduleId},n?.apiBaseUrl,n);if(o.Code!==1)return F.error(`Microi: \u63A8\u9001\u5931\u8D25 - \u62C9\u53D6\u6A21\u5757\u5931\u8D25 ${o.Msg}`),!1;let a=o.Data,c=[],l=a[t.btnField];if(l)try{c=typeof l=="string"?JSON.parse(l):l,Array.isArray(c)||(c=[])}catch{return F.error("Microi: \u63A8\u9001\u5931\u8D25 - \u6309\u94AE JSON \u89E3\u6790\u5931\u8D25"),!1}let d=N.getInstance().getSyncRootDir();this.ensureSyncGitExcludes(d);let u=_.join(d,".backups","menu-button-json",this.shortBackupKey(t.serverDir),t.moduleId);me(u);let g=_.join(u,`${t.btnField}-${Date.now()}.json`);v.writeFileSync(g,JSON.stringify(c,null,2),"utf-8");let m=c.find(C=>String(C.Id||"")===t.btnId);if(!m){let C=c.map(h=>Number(h.Sort||0)).filter(h=>!isNaN(h));m={Id:t.btnId,Name:t.btnName||t.btnId,Sort:C.length>0?Math.max(...C)+1:c.length+1,IsVisible:!0,ShowRow:t.btnField==="MoreBtns"},c.push(m)}m[t.v8SubField]=i;let f={OsClient:t.osClient,ModuleId:t.moduleId};f[t.btnField]=JSON.stringify(c);let y=await r.post(H.UPDATE_MODULE,f,void 0,n?.apiBaseUrl,n);if(y.Code===1){this.log(`\u63A8\u9001\u6210\u529F: ${t.moduleId}.${t.btnField}.${t.btnId}.${t.v8SubField}`);let C=y.Data?.UpdateTime||Te(),h=this.loadMeta(t.serverDir);h.menuButtons||(h.menuButtons={});let S=this.getMenuButtonMetaKey(t.moduleId,t.btnField,t.btnId,t.v8SubField);return i.trim()?h.menuButtons[S]={moduleId:t.moduleId,moduleName:String(a.Name||a.Label||t.moduleId),btnField:t.btnField,btnId:t.btnId,btnName:String(m.Name||t.btnName||t.btnId),v8SubField:t.v8SubField,updateTime:C,filePath:_.relative(N.getInstance().getWorkspaceRoot(),e)}:delete h.menuButtons[S],h.menus||(h.menus={}),h.menus[t.moduleId]={moduleId:t.moduleId,moduleName:String(a.Name||a.Label||t.moduleId),updateTime:C,buttonHashes:h.menus[t.moduleId]?.buttonHashes||{}},this.saveMeta(h,t.serverDir),i.trim()?this.touchSyncedFile(e,C):v.existsSync(e)&&v.unlinkSync(e),!0}return F.error(`Microi: \u63A8\u9001\u6309\u94AE\u5931\u8D25 - ${y.Msg}`),!1}catch(o){let a=o instanceof Error?o.message:String(o);return this.log(`\u63A8\u9001\u5F02\u5E38: ${a}`),F.error(`Microi: \u63A8\u9001\u5F02\u5E38 - ${a}`),!1}}async pushWorkflowNodeFile(e,t,n){let r=L.getInstance(),i=v.readFileSync(e,"utf-8"),o=Fe(i);this.log(`\u63A8\u9001\u6D41\u7A0B\u8282\u70B9V8: ${t.flowDesignId}/${t.nodeId}/${t.eventType}...`);try{let a="",c="";try{let g=await r.post(H.GET_WORKFLOW_V8_EVENT_CODE,{OsClient:t.osClient,FlowDesignId:t.flowDesignId,NodeId:t.nodeId,EventType:t.eventType},void 0,n?.apiBaseUrl,n);g.Code===1&&g.Data&&(a=g.Data.V8Code||g.Data.Code||"",c=g.Data.Version||"")}catch{a="",c=""}let l=!o.trim(),p=l?{code:"",version:c,changeHistory:""}:Bt({kind:"Workflow",key:`${t.flowDesignId}/${t.nodeId}`,eventType:t.eventType,currentCode:o,remoteCode:a,remoteVersion:c,changeSummary:`\u901A\u8FC7 VS Code \u63A8\u9001\u6D41\u7A0B\u8282\u70B9 V8 ${t.flowDesignId}/${t.nodeId}/${t.eventType}`}),d={OsClient:t.osClient,FlowDesignId:t.flowDesignId,NodeId:t.nodeId,EventType:t.eventType};l?d.V8Code="":(d.V8CodeBase64=Buffer.from(p.code,"utf8").toString("base64"),d.Version=p.version,d.ChangeHistory=p.changeHistory);let u=await r.post(H.UPDATE_WORKFLOW_V8_EVENT_CODE,d,void 0,n?.apiBaseUrl,n);if(u.Code===1){let g=u.Data?.UpdateTime||Te(),m=this.loadMeta(t.serverDir);m.workflowNodeEvents||(m.workflowNodeEvents={});let f=`${t.flowDesignId}__${t.nodeId}__${t.eventType}`;return l?delete m.workflowNodeEvents[f]:m.workflowNodeEvents[f]={flowDesignId:t.flowDesignId,flowName:m.workflowNodeEvents[f]?.flowName||t.flowDesignId,nodeId:t.nodeId,nodeName:m.workflowNodeEvents[f]?.nodeName||t.nodeId,eventType:t.eventType,updateTime:g,filePath:_.relative(N.getInstance().getWorkspaceRoot(),e)},this.saveMeta(m,t.serverDir),l?v.existsSync(e)&&v.unlinkSync(e):(v.writeFileSync(e,p.code,"utf-8"),this.touchSyncedFile(e,g)),this.log(`\u63A8\u9001\u6210\u529F: ${t.flowDesignId}/${t.nodeId}/${t.eventType}`),!0}return this.log(`\u63A8\u9001\u6D41\u7A0B\u8282\u70B9V8\u5931\u8D25: ${u.Msg}`),F.error(`Microi: \u63A8\u9001\u6D41\u7A0B\u8282\u70B9V8\u5931\u8D25 - ${u.Msg}`),!1}catch(a){let c=a instanceof Error?a.message:String(a);return this.log(`\u63A8\u9001\u6D41\u7A0B\u8282\u70B9V8\u5F02\u5E38: ${c}`),F.error(`Microi: \u63A8\u9001\u5F02\u5E38 - ${c}`),!1}}async pullDbSchema(e){let t=N.getInstance(),n=L.getInstance();if(!e){let r=t.getProfiles();if(r.length===0){F.warn("Microi: \u6CA1\u6709\u5DF2\u8FDE\u63A5\u7684\u670D\u52A1\u5668");return}for(let i of r)try{await this.pullDbSchemaForProfile(i)}catch(o){let a=o instanceof Error?o.message:String(o);this.log(`\u62C9\u53D6\u6570\u636E\u5E93\u7ED3\u6784\u5931\u8D25 [${i.label||i.apiBaseUrl}]: ${a}`)}return}await this.pullDbSchemaForProfile(e)}async pullDbSchemaForProfile(e){let t=N.getInstance(),n=L.getInstance(),r=e.apiBaseUrl,i=e.osClient;this.log(`\u5F00\u59CB\u62C9\u53D6\u6570\u636E\u5E93\u7ED3\u6784 [${e.label||r}]...`);let o=await n.get(H.GET_DB_SCHEMA,{osClient:i},r,e);if(o.Code!==1){let I=o.Code===1001||o.Code===1002?"\uFF0C\u8BF7\u91CD\u65B0\u767B\u5F55":"";throw new Error(`\u83B7\u53D6\u6570\u636E\u5E93\u7ED3\u6784\u5931\u8D25: ${o.Msg||"Code="+o.Code}${I}`)}let a=t.getSyncRootDir(),l=await ke.getInstance().getSysConfig(r,i),p=l?.SysShortTitle||"",d=l?.SysTitle||"",u=p||d||l?.CompanyName||e.label||"";u&&(u!==e.label||p!==e.sysShortTitle||d!==e.sysTitle)&&await t.addProfile({...e,label:u,sysShortTitle:p,sysTitle:d});let g=t.buildServerDirName(u,r),f=t.getProfiles().find(I=>I.apiBaseUrl===e.apiBaseUrl&&I.osClient===e.osClient)||e,y=t.buildOsClientDirName(i,f.osClientType,f.osClientNetwork),C=_.join(a,g,y);me(C);let h=_.join(C,at);v.writeFileSync(h,JSON.stringify(o.Data,null,2),"utf-8");let S=_.join(C,ze),b=this.formatDbSchemaMarkdown(o.Data,g,y);b&&v.writeFileSync(S,b,"utf-8");let E=o.Data.Tables?.length||0,k=u||e.label||r;this.log(`[${k}] \u62C9\u53D6\u6570\u636E\u5E93\u7ED3\u6784\u5B8C\u6210: ${E} \u5F20\u8868`),F.info(`Microi: [${k}] \u6210\u529F\u62C9\u53D6\u6570\u636E\u5E93\u7ED3\u6784\uFF08${E} \u5F20\u8868\uFF09`)}formatDbSchemaMarkdown(e,t,n){let r=(e.Tables||[]).filter(c=>c.Name);if(!r.length)return"";let i=r.reduce((c,l)=>{let p=l._Fields||l.Fields||[];return c+p.length},0),o=e.Menus?.length||0,a=[];a.push(`# \u6570\u636E\u5E93\u7ED3\u6784 \u2014 ${t}/${n}
|
|
48
48
|
`),a.push("> \u6B64\u6587\u4EF6\u7531 Microi\u543E\u7801 VS Code \u63D2\u4EF6\u81EA\u52A8\u751F\u6210\uFF0C\u4F9B AI \u7F16\u5199 V8.FormEngine / V8.Db \u4EE3\u7801\u65F6\u53C2\u8003\u3002"),a.push(`> \u5171 ${r.length} \u5F20\u8868\uFF0C${i} \u4E2A\u5B57\u6BB5\uFF0C${o} \u4E2A\u83DC\u5355\u3002
|
|
49
49
|
`);for(let c of r){let l=c.Description?` \u2014 ${c.Description}`:"";a.push(`## ${c.Name}${l}
|
|
50
50
|
`);let p=c._Fields||c.Fields||[];if(!p.length){a.push(`_\u6682\u65E0\u5B57\u6BB5\u4FE1\u606F._
|
|
51
|
-
`);continue}a.push("| \u5B57\u6BB5 | \u6807\u7B7E/\u8BF4\u660E | \u7C7B\u578B | \u7EC4\u4EF6 | \u5FC5\u586B | \u5173\u8054 |"),a.push("|------|-----------|------|------|------|------|");for(let
|
|
52
|
-
`)}dispose(){}};var R=B(require("fs")),
|
|
51
|
+
`);continue}a.push("| \u5B57\u6BB5 | \u6807\u7B7E/\u8BF4\u660E | \u7C7B\u578B | \u7EC4\u4EF6 | \u5FC5\u586B | \u5173\u8054 |"),a.push("|------|-----------|------|------|------|------|");for(let d of p){let u=d.Label||d.Description||"",g=d.Type||d.FieldType||"",m=d.Required===!0||d.NotEmpty===1?"\u662F":"",f=d.ChildTableId||d.ChildSysMenuId||"";a.push(`| ${d.Name} | ${u} | ${g} | ${d.Component||""} | ${m} | ${f} |`)}a.push("")}return a.join(`
|
|
52
|
+
`)}dispose(){}};var R=B(require("fs")),x=B(require("path")),_s=B(require("crypto")),cr=require("child_process");var gn="<!-- microi-ai-routing:begin -->",Lt="<!-- microi-ai-routing:end -->";function pn(){return'## Microi \u5DE5\u4F5C\u533A\u5F3A\u5236\u89C4\u5219\u552F\u4E00\u6765\u6E90\n\n\u7528\u6237\u5728\u5DF2\u521D\u59CB\u5316\u543E\u7801\u5DE5\u4F5C\u533A\u4E2D\u76F4\u63A5\u63CF\u8FF0\u9700\u6C42\u5373\u53EF\uFF0C\u65E0\u9700\u7528\u6237\u6307\u5B9A Skill \u540D\u79F0\u3002\u8D28\u91CF\u548C\u6B63\u786E\u6027\u4F18\u5148\uFF1B\u8282\u7701 token \u53EA\u51CF\u5C11\u65E0\u5173\u8D44\u6599\u3001\u91CD\u590D\u8BFB\u53D6\u548C\u91CD\u590D\u56DE\u6267\uFF0C\u4E0D\u80FD\u7701\u7565\u5FC5\u8981\u5206\u6790\u3001\u5B9E\u73B0\u6216\u9A8C\u6536\u3002\n\n1. \u6BCF\u6B21\u65B0\u5BF9\u8BDD\u6216\u63A5\u7EED Microi \u4EFB\u52A1\uFF0C\u5148\u5B8C\u6574\u8BFB\u53D6 `microi.skills/workspace-conventions/SKILL.md`\uFF1B\u6267\u884C\u5176\u4E2D\u7684\u521B\u59CB\u4EBA\u8EAB\u4EFD\u8BC6\u522B\u3001\u5E73\u53F0\u529F\u80FD\u56DB\u9879\u540C\u6B65\u68C0\u67E5\uFF08\u5E94\u7528\u5546\u57CE\u3001\u5B98\u65B9\u6587\u6863\u3001Skills\u3001MCP\uFF09\u3001\u7248\u672C\u68C0\u67E5\u3001\u975E\u963B\u585E\u81EA\u52A8\u5347\u7EA7\u53CA\u8FDB\u5EA6\u64AD\u62A5\u3002\n2. \u968F\u540E\u8BFB\u53D6 `microi.skills/microi-system-delivery/SKILL.md` \u5224\u5B9A\u4EFB\u52A1\u8303\u56F4\u3002\u5B8C\u6574\u7CFB\u7EDF\u5FC5\u987B\u5B8C\u6574\u8BFB\u53D6 `microi.skills/microi-system-delivery/references/progressive-01-\u6807\u51C6\u5DE5\u4F5C\u6D41.md` \u4E2D\u7684\u539F 1\u20138 \u53CA\u540E\u7EED\u589E\u8865\uFF0C\u5E76\u6309\u603B\u63A7\u8DEF\u7531\u5B8C\u6574\u8BFB\u53D6\u76F8\u5173\u4E13\u9879 Skills\uFF1B\u5B8C\u6574\u7CFB\u7EDF\u9010\u9879\u6267\u884C\u5168\u90E8\u6E05\u5355\u548C\u589E\u8865\uFF0C\u4E0D\u80FD\u964D\u4E3A\u6837\u4F8B\u3001\u65B9\u6848\u6216\u5F85\u529E\u3002\u5C40\u90E8\u4FEE\u6539\u8BFB\u53D6\u8D28\u91CF\u89C4\u8303\u3001\u76F8\u5173\u6761\u76EE\u548C\u76EE\u6807\u4F9D\u8D56\u6D89\u53CA\u7684\u4E13\u9879\uFF1B\u8303\u56F4\u4E0D\u660E\u65F6\u6269\u5927\u8BFB\u53D6\uFF0C\u65E0\u6CD5\u6392\u9664\u65B0\u7CFB\u7EDF\u610F\u56FE\u65F6\u6309\u5B8C\u6574\u7CFB\u7EDF\u5904\u7406\u3002\u53EA\u8BFB\u5206\u6790\u4E0D\u521B\u5EFA\u3001\u5199\u5165\u6216\u53D1\u5E03\u8D44\u6E90\u3002\n3. \u5B9E\u73B0\u524D\u5148\u62A5\u544A\u5DF2\u8BFB\u53D6\u7684\u6587\u4EF6\u8DEF\u5F84\u53CA\u672C\u6B21\u9002\u7528\u7684\u4EA4\u4ED8\u6E05\u5355\uFF1B\u4E0A\u4E0B\u6587\u53D6\u820D\u8BFB\u53D6 `microi.skills/microi-system-delivery/references/context-quality.md`\u3002\u7F3A\u5C11\u5165\u53E3\u6216\u4E13\u9879 Skill \u65F6\u6309 `microi.skills/microi-codex-installer/SKILL.md` \u6062\u590D\uFF1B\u672A\u8BFB\u53D6\u5B8C\u6574\u6B63\u6587\u65F6\u4E0D\u80FD\u58F0\u79F0\u5DF2\u81EA\u52A8\u52A0\u8F7D\u3002\u9700\u8981\u67E5\u627E\u80FD\u529B\u65F6\u5148\u68C0\u7D22 `microi.skills/README.md`\uFF0C\u4E0D\u4E00\u6B21\u52A0\u8F7D\u6240\u6709 Skills\u3002\n4. \u9996\u6B21\u4EE5\u201CMicroi\u543E\u7801\u5F00\u53D1\u5DE5\u5177\u7248\u672C\u201D\u62A5\u544A\u5B9E\u9645\u4E0E\u5B98\u65B9\u7248\u672C\u3001\u81EA\u52A8\u66F4\u65B0\u548C\u540C\u6B65\u72B6\u6001\uFF1B\u5DF2\u6709 CLI \u65F6\u5FC5\u987B\u6295\u9012 `microi update --background --workspace "<\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84>" --json`\uFF0C\u4E0D\u7B49\u5F85\u66F4\u65B0\u5B8C\u6210\uFF0C\u4FDD\u6301\u5F53\u524D\u3001\u6B63\u5728\u8FDB\u884C\u548C\u65B0\u5EFA\u5DE5\u4F5C\u7EE7\u7EED\u6267\u884C\u3002\u7248\u672C\u67E5\u8BE2\u3001\u5931\u8D25\u5EF6\u540E\u53CA\u5B8C\u6574\u540C\u6B65\u8981\u6C42\u4EE5\u57FA\u7840\u89C4\u8303\u4E3A\u51C6\u3002\n\n## \u6309\u76EE\u6807\u4E0E\u4F9D\u8D56\u8BFB\u53D6\n\n- \u5C40\u90E8\u4FEE\u6539\u5148\u786E\u8BA4\u76EE\u6807\u5E94\u7528\u3001\u6587\u4EF6\u3001\u8868\u6216\u63A5\u53E3\u53CA\u76F4\u63A5\u4F9D\u8D56\uFF1B\u5148\u53D6\u76EE\u5F55\u3001\u5143\u6570\u636E\u548C\u7248\u672C\uFF0C\u518D\u8BFB\u53D6\u76EE\u6807\u6B63\u6587\u4E0E\u53D7\u5F71\u54CD\u4F9D\u8D56\u3002\u8303\u56F4\u4E0D\u6E05\u3001\u8BC1\u636E\u4E0D\u8DB3\u3001\u6743\u9650\u6216\u5173\u8054\u5173\u7CFB\u590D\u6742\u65F6\u6269\u5927\u68C0\u7D22\u4E0E\u8BFB\u53D6\uFF0C\u4E0D\u80FD\u51ED\u731C\u6D4B\u4FEE\u6539\uFF0C\u4E5F\u4E0D\u80FD\u56E0\u9884\u7B97\u786C\u622A\u65AD\u5FC5\u8981\u4E0A\u4E0B\u6587\u3002\n- \u5B9A\u5236\u524D\u7AEF\u3001\u6E38\u620F\u3001\u7B97\u6CD5\u6216\u786C\u4EF6\u4EFB\u52A1\uFF0C\u6309\u9700\u8BFB\u53D6\u6700\u5C0F\u76F8\u5173 SDK\u3001\u811A\u624B\u67B6\u3001\u6A21\u677F\u548C\u534F\u8BAE\uFF1A\u524D\u7AEF\u4F18\u5148 `microi-frontend-sdk` / \u5BF9\u5E94\u5E94\u7528 Skill\uFF0CUnity \u4F7F\u7528 `unity-integration`\uFF0CTCP/\u6D88\u606F\u8BBE\u5907\u4F7F\u7528\u5BF9\u5E94\u96C6\u6210 Skill\uFF1B\u7531\u4F9D\u8D56\u5206\u6790\u51B3\u5B9A\u662F\u5426\u7EE7\u7EED\u8BFB\u53D6\u8868\u5355\u3001\u6A21\u5757\u3001V8\u3001\u6570\u636E\u5E93\u7B49\u5E73\u53F0\u77E5\u8BC6\u3002\n- V8 \u65B9\u6CD5\u548C\u7B7E\u540D\u6309\u9700\u8BFB\u53D6\u8D23\u4EFB Skill \u53CA\u540C\u6B65\u76EE\u5F55\u7684\u7C7B\u578B\u5B9A\u4E49\uFF1B\u6570\u636E\u5E93\u4EE5\u5F53\u524D\u79DF\u6237 MCP \u5B9E\u65F6\u7ED3\u6784\u4E3A\u51C6\uFF0C\u67E5\u8BE2\u65F6\u6536\u7A84\u5230\u76EE\u6807\u53CA\u4F9D\u8D56\uFF0C\u7ED3\u6784\u53D8\u5316\u540E\u91CD\u65B0\u56DE\u8BFB\u3002\u6E90\u7801\u6E05\u5355\u3001\u6458\u8981\u3001\u7F13\u5B58\u6216\u622A\u65AD\u8F93\u51FA\u4E0D\u80FD\u5192\u5145\u5DF2\u8BFB\u5B8C\u6574\u6B63\u6587\uFF1B\u4FEE\u6539\u524D\u5FC5\u987B\u8BFB\u5168\u88AB\u4FEE\u6539\u7684\u6E90\u7801\u5E76\u6838\u5BF9\u7248\u672C\u3002\n- \u9274\u6743\u3001\u79DF\u6237\u9694\u79BB\u3001\u6743\u9650\u3001\u4E8B\u52A1\u3001\u5E42\u7B49\u3001\u51B2\u7A81\u4FDD\u62A4\u3001\u771F\u5B9E\u4E1A\u52A1\u6D4B\u8BD5\u548C\u5199\u540E\u56DE\u8BFB\u59CB\u7EC8\u4FDD\u7559\uFF1B\u4E0D\u628A\u9ED8\u8BA4\u8BFB\u53D6\u6269\u5F20\u4E3A\u751F\u4EA7\u5199\u5165\u6216\u5BA2\u6237\u81EA\u52A8\u90E8\u7F72\u3002\u5DE5\u5177\u7ED3\u679C\u4E0D\u786E\u5B9A\u65F6\u5148\u56DE\u8BFB\uFF0C\u4E0D\u80FD\u76F2\u76EE\u91CD\u8BD5\u5199\u5165\u3002\n- \u8BE6\u7EC6\u89C4\u5219\u53EA\u7EF4\u62A4\u5728\u4E0A\u8FF0 Skills\uFF1B\u9ED8\u8BA4\u4F7F\u7528\u7B80\u4F53\u4E2D\u6587\uFF0C\u6700\u7EC8\u62A5\u544A\u5B9E\u9645\u6539\u52A8\u3001\u9A8C\u8BC1\u7ED3\u679C\u4E0E\u672A\u8986\u76D6\u8FB9\u754C\uFF0C\u907F\u514D\u91CD\u590D\u8F93\u51FA\u672A\u6539\u53D8\u7684\u5168\u6587\u3002\n'}function mn(s){return`${gn}
|
|
53
53
|
${s.trim()}
|
|
54
54
|
${Lt}
|
|
55
55
|
`}function fn(s){let e=s.indexOf(gn),t=s.indexOf(Lt);if(e<0||t<e||s.indexOf(gn,e+gn.length)>=0||s.indexOf(Lt,t+Lt.length)>=0)return;let n=t+Lt.length;return{start:e,end:n,text:s.slice(e,n)}}var Zi=`/**
|
|
@@ -1336,10 +1336,10 @@ declare function DateAdd(date: any, unit: string, amount: number, format?: strin
|
|
|
1336
1336
|
declare function JSON_Encode(obj: any): string;
|
|
1337
1337
|
/** JSON \u53CD\u5E8F\u5217\u5316 */
|
|
1338
1338
|
declare function JSON_Decode(json: string): any;
|
|
1339
|
-
`,vs="microi.skills",ar=".microi-skills-manifest.json",eo="microi-skills.meta.json",hn=".microi-ai-docs-manifest.json",to="microi-ai-doc-guard:",Es=[".codebuddy/skills/microi/SKILL.md",".qoder/skills/microi/SKILL.md",".agents/skills/microi/SKILL.md",".comate/skills/microi/SKILL.md"],Ts=".codebuddy/rules/microi.md";var
|
|
1340
|
-
`;var yn=class s{static getInstance(){return s._instance||(s._instance=new s),s._instance}inject(){let e=N.getInstance();if(!e.getWorkspaceRoot())return;let n;try{n=e.getSyncRootDir()}catch{return}let r=
|
|
1341
|
-
`,"utf-8"),Ue(e,[`${vs}/${ar}`]))}readSkillManifest(e){if(!R.existsSync(e))return{version:1,generatedBy:"Microi\u543E\u7801 VSCode Extension",files:{}};try{let t=JSON.parse(R.readFileSync(e,"utf-8"));return{version:typeof t.version=="number"?t.version:1,generatedBy:t.generatedBy||"Microi\u543E\u7801 VSCode Extension",bundleVersion:typeof t.bundleVersion=="string"?t.bundleVersion:void 0,bundleBuiltAt:typeof t.bundleBuiltAt=="string"?t.bundleBuiltAt:void 0,fileVersions:t.fileVersions&&typeof t.fileVersions=="object"?t.fileVersions:{},files:t.files&&typeof t.files=="object"?t.files:{}}}catch{return{version:1,generatedBy:"Microi\u543E\u7801 VSCode Extension",files:{}}}}readBundledSkillsMeta(){let e=
|
|
1342
|
-
`,"utf-8")}Ue(e,[`.vscode/${hn}`])}readAiDocsManifest(e){if(!R.existsSync(e))return{version:2,generatedBy:"Microi\u543E\u7801 AI\u5F00\u53D1\u5DE5\u5177",files:{},fileHashes:{},fileVersions:{},routingBlockHashes:{}};try{let t=JSON.parse(R.readFileSync(e,"utf-8"));return{version:typeof t.version=="number"?t.version:1,generatedBy:t.generatedBy||"Microi\u543E\u7801 AI\u5F00\u53D1\u5DE5\u5177",bundleVersion:typeof t.bundleVersion=="string"?t.bundleVersion:void 0,fileVersions:t.fileVersions&&typeof t.fileVersions=="object"?t.fileVersions:{},fileHashes:t.fileHashes&&typeof t.fileHashes=="object"?t.fileHashes:{},routingBlockHashes:t.routingBlockHashes&&typeof t.routingBlockHashes=="object"?t.routingBlockHashes:{},files:t.files&&typeof t.files=="object"?t.files:{}}}catch{return{version:2,generatedBy:"Microi\u543E\u7801 AI\u5F00\u53D1\u5DE5\u5177",files:{},fileHashes:{},fileVersions:{},routingBlockHashes:{}}}}normalizeRelativePath(e){let t=e.replace(/\\/g,"/").replace(/^\.\//,"");return process.platform==="win32"?t.toLowerCase():t}getGitTrackedWorkspaceFiles(e,t){let n=(0,cr.spawnSync)("git",["-C",e,"rev-parse","--show-toplevel"],{encoding:"utf-8",windowsHide:!0,timeout:3e3});if(n.error)return this.hasGitMetadata(e)?void 0:new Set;if(n.status!==0)return new Set;let r=String(n.stdout||"").trim();if(!r)return;let i=new Map,o=[];for(let l of t){let p=
|
|
1339
|
+
`,vs="microi.skills",ar=".microi-skills-manifest.json",eo="microi-skills.meta.json",hn=".microi-ai-docs-manifest.json",to="microi-ai-doc-guard:",Es=[".codebuddy/skills/microi/SKILL.md",".qoder/skills/microi/SKILL.md",".agents/skills/microi/SKILL.md",".comate/skills/microi/SKILL.md"],Ts=".codebuddy/rules/microi.md";var Ye=`<!-- Generated by Microi\u543E\u7801 VSCode Extension - DO NOT REMOVE THIS LINE -->
|
|
1340
|
+
`;var yn=class s{static getInstance(){return s._instance||(s._instance=new s),s._instance}inject(){let e=N.getInstance();if(!e.getWorkspaceRoot())return;let n;try{n=e.getSyncRootDir()}catch{return}let r=x.join(n,_t);R.existsSync(r)||R.mkdirSync(r,{recursive:!0});let i=x.join(r,tn);R.writeFileSync(i,Zi,"utf-8"),this.injectAiDocs(n),this.ensureJsConfig(n,r)}injectAiDocs(e){try{this.generatePerOsClientSchemaDocs(e);let t=N.getInstance().getWorkspaceRoot();if(!t)return;this.ensureLocalRuntimeFilesIgnored(t,e),this.syncBundledSkills(t);let n=this.collectSkillEntries(t),r=mn(pn()),i=[{relativePath:`${Bn}/${Ln}`,content:Ye+r},{relativePath:Un,content:Ye+r},{relativePath:jn,content:Ye+r},{relativePath:Kn,content:Ye+r}];if(n.length>0){i.push({relativePath:`${Hn}/${Wn}`,content:this.buildCursorSkillRule(n)});let o=this.buildPortableAiSkill(n);for(let a of Es)i.push({relativePath:a,content:o});i.push({relativePath:Ts,content:this.buildCodeBuddyRule()})}this.syncGeneratedAiDocs(t,i)}catch{}}ensureLocalRuntimeFilesIgnored(e,t){let n=[".vscode/mcp.json",`.vscode/${hn}`,".cursor/mcp.json",".trae/mcp.json",".workbuddy/mcp.json",".comate/mcp.json",Nr,".claude/settings.local.json"],r=x.relative(e,t);if(r&&!r.startsWith("..")&&!x.isAbsolute(r)){let i=r.replace(/\\/g,"/");n.push(`${i}/**/${at}`,`${i}/**/${ze}`,`${i}/**/${rt}`,`${i}/${vt}`,`${i}/**/${vt}`,`${i}/.backups/`,`${i}/**/.backups/`,`${i}/${_t}/`)}lt(e),Ue(e,n)}getBundledSkillsDir(){let e=x.join(__dirname,"microi.skills");if(R.existsSync(e))return e;let t=x.resolve(__dirname,"..","skills");return R.existsSync(t)?t:e}syncBundledSkills(e){let t=this.getBundledSkillsDir();if(!R.existsSync(t))return;let n=x.join(e,vs),r=x.join(n,ar),i=this.readSkillManifest(r),o=this.readBundledSkillsMeta(),a=o.skills?.version,c=this.compareMicroiVersions(a,i.bundleVersion)<0,l={version:1,generatedBy:"Microi\u543E\u7801 VSCode Extension",bundleVersion:c?i.bundleVersion:a||i.bundleVersion,bundleBuiltAt:c?i.bundleBuiltAt:o.builtAt||i.bundleBuiltAt,fileVersions:{...i.fileVersions||{}},files:{...i.files}},p=[];this.walkSkillSource(t,(u,g)=>{let m=x.join(n,g),f=R.readFileSync(u,"utf-8"),y=this.hashText(f),C=i.files[g],h=o.fileVersions?.[g]||a,S=i.fileVersions?.[g]||i.bundleVersion,b=this.compareMicroiVersions(h,S)<0,E=!1;if(!R.existsSync(m))E=!b;else if(C)try{E=this.hashText(R.readFileSync(m,"utf-8"))===C&&!b}catch{E=!1}if(E){let k=x.dirname(m);R.existsSync(k)||R.mkdirSync(k,{recursive:!0}),R.writeFileSync(m,f,"utf-8"),p.push(g)}if(E)l.files[g]=y,h&&(l.fileVersions[g]=h);else try{if(this.hashText(R.readFileSync(m,"utf-8"))===y){l.files[g]=y;let I=this.pickNewerMicroiVersion(h,i.fileVersions?.[g]);I&&(l.fileVersions[g]=I)}else C?(l.files[g]=C,i.fileVersions?.[g]&&(l.fileVersions[g]=i.fileVersions[g])):(delete l.files[g],delete l.fileVersions[g])}catch{C&&(l.files[g]=C,i.fileVersions?.[g]&&(l.fileVersions[g]=i.fileVersions[g]))}});let d=JSON.stringify(l)!==JSON.stringify(i);(p.length>0||d||!R.existsSync(r))&&(R.existsSync(n)||R.mkdirSync(n,{recursive:!0}),R.writeFileSync(r,JSON.stringify(l,null,2)+`
|
|
1341
|
+
`,"utf-8"),Ue(e,[`${vs}/${ar}`]))}readSkillManifest(e){if(!R.existsSync(e))return{version:1,generatedBy:"Microi\u543E\u7801 VSCode Extension",files:{}};try{let t=JSON.parse(R.readFileSync(e,"utf-8"));return{version:typeof t.version=="number"?t.version:1,generatedBy:t.generatedBy||"Microi\u543E\u7801 VSCode Extension",bundleVersion:typeof t.bundleVersion=="string"?t.bundleVersion:void 0,bundleBuiltAt:typeof t.bundleBuiltAt=="string"?t.bundleBuiltAt:void 0,fileVersions:t.fileVersions&&typeof t.fileVersions=="object"?t.fileVersions:{},files:t.files&&typeof t.files=="object"?t.files:{}}}catch{return{version:1,generatedBy:"Microi\u543E\u7801 VSCode Extension",files:{}}}}readBundledSkillsMeta(){let e=x.join(__dirname,eo);if(!R.existsSync(e))return{};try{let t=JSON.parse(R.readFileSync(e,"utf-8"));return t&&typeof t=="object"?t:{}}catch{return{}}}walkSkillSource(e,t){let n=r=>{for(let i of R.readdirSync(r,{withFileTypes:!0})){if(i.name===".git"||i.name==="node_modules"||i.name===ar)continue;let o=x.join(r,i.name);if(i.isDirectory())n(o);else if(i.isFile()){let a=x.relative(e,o).replace(/\\/g,"/");t(o,a)}}};n(e)}hashText(e){return _s.createHash("sha256").update(e,"utf-8").digest("hex")}compareMicroiVersions(e,t){let n=o=>{if(!(!o||!/^\d+(?:\.\d+){2}$/.test(o)))return o.split(".").map(a=>Number(a))},r=n(e),i=n(t);if(!r||!i)return 0;for(let o=0;o<3;o++)if(r[o]!==i[o])return r[o]>i[o]?1:-1;return 0}pickNewerMicroiVersion(e,t){return e?t?this.compareMicroiVersions(e,t)>=0?e:t:e:t}syncGeneratedAiDocs(e,t){let n=t.map(u=>u.relativePath.replace(/\\/g,"/")),r=n.map(u=>this.normalizeRelativePath(u)),i=this.getGitTrackedWorkspaceFiles(e,n);if(i===void 0)return;let o=x.join(e,".vscode",hn),a=this.readAiDocsManifest(o),c=this.readBundledSkillsMeta().skills?.version,l=this.pickNewerMicroiVersion(c,a.bundleVersion),p={version:2,generatedBy:"Microi\u543E\u7801 AI\u5F00\u53D1\u5DE5\u5177",bundleVersion:l,fileVersions:{...a.fileVersions||{}},fileHashes:{...a.fileHashes||{}},routingBlockHashes:{...a.routingBlockHashes||{}},files:{...a.files}},d=new Set(r);for(let u of Object.keys(p.files))d.has(this.normalizeRelativePath(u))||(delete p.files[u],delete p.fileHashes[u],delete p.fileVersions[u],delete p.routingBlockHashes[u]);for(let u of Object.keys(p.fileHashes))d.has(this.normalizeRelativePath(u))||(delete p.fileHashes[u],delete p.fileVersions[u],delete p.files[u],delete p.routingBlockHashes[u]);for(let u of t){let g=this.normalizeRelativePath(u.relativePath);if(i.has(g)){delete p.files[g],delete p.fileHashes[g],delete p.fileVersions[g],delete p.routingBlockHashes[g];continue}let m=x.join(e,g),f=this.hashText(u.content),y=a.files[g],C=a.fileHashes?.[g]||(/^[a-f0-9]{64}$/i.test(y||"")?y:void 0),h=a.fileVersions?.[g]||a.bundleVersion,S=this.compareMicroiVersions(c,h)<0,b=!R.existsSync(m)&&!S,E="",k=u.content;if(R.existsSync(m))try{let w=R.readFileSync(m,"utf-8");E=this.hashText(w),b=!!C&&E===C&&!S;let O=fn(w),A=fn(u.content),D=a.routingBlockHashes?.[g];!b&&!S&&O&&A&&D&&this.hashText(O.text)===D&&(k=w.slice(0,O.start)+A.text+w.slice(O.end),b=!0)}catch{b=!1}if(b){let w=x.dirname(m);R.existsSync(w)||R.mkdirSync(w,{recursive:!0}),R.writeFileSync(m,k,"utf-8"),E=this.hashText(k),p.fileHashes[g]=f,c&&(p.fileVersions[g]=c)}else if(E===f){p.fileHashes[g]=f;let w=this.pickNewerMicroiVersion(c,h);w&&(p.fileVersions[g]=w)}else C?(p.fileHashes[g]=C,h&&(p.fileVersions[g]=h)):p.fileHashes[g]||delete p.fileVersions[g];if(b||E===f){let w=fn(u.content);w?p.routingBlockHashes[g]=this.hashText(w.text):delete p.routingBlockHashes[g]}let I=p.fileHashes[g];if(I){let w=p.fileVersions[g]||l||"unknown";p.files[g]=`${to}${w}:${I}`}else delete p.files[g]}if(JSON.stringify(p)!==JSON.stringify(a)||!R.existsSync(o)){let u=x.dirname(o);R.existsSync(u)||R.mkdirSync(u,{recursive:!0}),R.writeFileSync(o,JSON.stringify(p,null,2)+`
|
|
1342
|
+
`,"utf-8")}Ue(e,[`.vscode/${hn}`])}readAiDocsManifest(e){if(!R.existsSync(e))return{version:2,generatedBy:"Microi\u543E\u7801 AI\u5F00\u53D1\u5DE5\u5177",files:{},fileHashes:{},fileVersions:{},routingBlockHashes:{}};try{let t=JSON.parse(R.readFileSync(e,"utf-8"));return{version:typeof t.version=="number"?t.version:1,generatedBy:t.generatedBy||"Microi\u543E\u7801 AI\u5F00\u53D1\u5DE5\u5177",bundleVersion:typeof t.bundleVersion=="string"?t.bundleVersion:void 0,fileVersions:t.fileVersions&&typeof t.fileVersions=="object"?t.fileVersions:{},fileHashes:t.fileHashes&&typeof t.fileHashes=="object"?t.fileHashes:{},routingBlockHashes:t.routingBlockHashes&&typeof t.routingBlockHashes=="object"?t.routingBlockHashes:{},files:t.files&&typeof t.files=="object"?t.files:{}}}catch{return{version:2,generatedBy:"Microi\u543E\u7801 AI\u5F00\u53D1\u5DE5\u5177",files:{},fileHashes:{},fileVersions:{},routingBlockHashes:{}}}}normalizeRelativePath(e){let t=e.replace(/\\/g,"/").replace(/^\.\//,"");return process.platform==="win32"?t.toLowerCase():t}getGitTrackedWorkspaceFiles(e,t){let n=(0,cr.spawnSync)("git",["-C",e,"rev-parse","--show-toplevel"],{encoding:"utf-8",windowsHide:!0,timeout:3e3});if(n.error)return this.hasGitMetadata(e)?void 0:new Set;if(n.status!==0)return new Set;let r=String(n.stdout||"").trim();if(!r)return;let i=new Map,o=[];for(let l of t){let p=x.relative(r,x.join(e,l));p.startsWith("..")||x.isAbsolute(p)||(o.push(p.replace(/\\/g,"/")),i.set(this.normalizeRelativePath(p),this.normalizeRelativePath(l)))}if(o.length===0)return new Set;let a=(0,cr.spawnSync)("git",["-C",r,"ls-files","-z","--",...o],{encoding:"utf-8",windowsHide:!0,timeout:3e3,maxBuffer:1024*1024});if(a.error||a.status!==0)return;let c=new Set;for(let l of String(a.stdout||"").split("\0").filter(Boolean)){let p=i.get(this.normalizeRelativePath(l));p&&c.add(p)}return c}hasGitMetadata(e){let t=x.resolve(e);for(;;){if(R.existsSync(x.join(t,".git")))return!0;let n=x.dirname(t);if(n===t)return!1;t=n}}canRemoveGeneratedAiDoc(e,t){if(!R.existsSync(t))return!1;let n=x.relative(e,t).replace(/\\/g,"/"),r=this.normalizeRelativePath(n),i=this.getGitTrackedWorkspaceFiles(e,[n]);if(i===void 0||i.has(r))return!1;let o=this.readAiDocsManifest(x.join(e,".vscode",hn)),a=o.files[r],c=o.fileHashes?.[r]||(/^[a-f0-9]{64}$/i.test(a||"")?a:void 0);if(!c)return!1;try{return this.hashText(R.readFileSync(t,"utf-8"))===c}catch{return!1}}collectSkillEntries(e){let t=x.join(e,"microi.skills");if(!R.existsSync(t))return[];let n=new Map,r=x.join(t,"README.md");if(R.existsSync(r))try{let a=R.readFileSync(r,"utf-8").matchAll(/`([^`]+\/SKILL\.md)`/g),c=0;for(let l of a){let p=l[1].split(/[\\/]/)[0];p&&!n.has(p)&&n.set(p,c++)}}catch{}let i=[];try{for(let o of R.readdirSync(t,{withFileTypes:!0})){if(!o.isDirectory())continue;let a=x.join(t,o.name,"SKILL.md");R.existsSync(a)&&i.push({name:o.name,relativePath:`microi.skills/${o.name}/SKILL.md`,description:this.readSkillDescription(a,o.name)})}}catch{}return i.sort((o,a)=>{let c=n.get(o.name),l=n.get(a.name);return c!==void 0&&l!==void 0?c-l:c!==void 0?-1:l!==void 0?1:o.name.localeCompare(a.name)})}readSkillDescription(e,t){try{let r=R.readFileSync(e,"utf-8").split(/\r?\n/).find(i=>i.startsWith("# "));if(r)return r.replace(/^#\s+/,"").trim()}catch{}return t}buildSkillsReference(e){if(!e.length)return"";let t=e.map(n=>`- \`${n.relativePath}\` \u2014 ${n.description}`).join(`
|
|
1343
1343
|
`);return`
|
|
1344
1344
|
|
|
1345
1345
|
---
|
|
@@ -1353,35 +1353,35 @@ description: Microi\u543E\u7801\u6309\u4EFB\u52A1\u8303\u56F4\u8BFB\u53D6\u89C4\
|
|
|
1353
1353
|
globs: ["**/*.{vue,js,ts,jsx,tsx,css,scss,json,md,mdc,cs,csproj,xml,yml,yaml}", "Microi-V8-Engine/**/*.js", "microi-v8-engine/**/*.js", "microi.skills/**/*.md"]
|
|
1354
1354
|
alwaysApply: true
|
|
1355
1355
|
---
|
|
1356
|
-
${
|
|
1356
|
+
${Ye}${mn(pn())}`}buildPortableAiSkill(e){return`---
|
|
1357
1357
|
name: microi
|
|
1358
1358
|
description: \u5B89\u88C5\u6216\u521D\u59CB\u5316 @microi.net/cli\u3001\u914D\u7F6E Microi\u543E\u7801\u670D\u52A1\u5668\u8FDE\u63A5\u4E0E MCP\u3001\u6309\u8FDE\u63A5\u62C9\u53D6\u5168\u90E8 V8 \u4EE3\u7801\uFF0C\u5E76\u5904\u7406\u543E\u7801\u4F4E\u4EE3\u7801\u5E73\u53F0\u4EFB\u52A1\u3002\u7528\u6237\u63D0\u5230\u201C\u5B89\u88C5\u543E\u7801\u63D2\u4EF6\u201D\u201C\u521D\u59CB\u5316 Microi\u201D\u201C\u6DFB\u52A0\u670D\u52A1\u5668/MCP\u201D\u201C\u62C9\u53D6\u67D0\u8FDE\u63A5\u7684\u6240\u6709 V8\u201D\u6216\u5DF2\u521D\u59CB\u5316\u543E\u7801\u5DE5\u4F5C\u533A\u4E2D\u76F4\u63A5\u63CF\u8FF0\u4E1A\u52A1\u5F00\u53D1\u9700\u6C42\u65F6\u4F7F\u7528\uFF0C\u65E0\u9700\u6307\u5B9A\u6280\u80FD\u540D\u79F0\u3002
|
|
1359
1359
|
---
|
|
1360
1360
|
|
|
1361
1361
|
# Microi\u543E\u7801 AI \u5F00\u53D1\u8DEF\u7531
|
|
1362
1362
|
|
|
1363
|
-
${
|
|
1363
|
+
${Ye}${mn("## \u5B89\u88C5\u4E0E\u8FDE\u63A5\n\n\u5C1A\u672A\u521D\u59CB\u5316\u3001\u9700\u8981\u5B89\u88C5 CLI\u3001\u8FDE\u63A5\u670D\u52A1\u5668\u3001\u767B\u5F55\u6216\u62C9\u53D6 V8 \u65F6\uFF0C\u5148\u8BFB\u53D6\u53EF\u7528\u7684 `microi-codex-installer/SKILL.md`\uFF08\u5DE5\u4F5C\u533A `microi.skills/` \u6216\u5F53\u524D\u63D2\u4EF6 `skills/`\uFF09\uFF0C\u6309\u5F53\u524D\u7B7E\u540D\u64CD\u4F5C\u3002\u7528\u6237\u660E\u786E\u8981\u6C42\u5B89\u88C5\u65F6\u4F7F\u7528 npm \u5B98\u65B9 latest\uFF1B\u5DF2\u6709\u8FDE\u63A5\u5148\u5217\u51FA\u5E76\u552F\u4E00\u5339\u914D\uFF0C\u5BC6\u7801\u3001Token \u4E0D\u8FDB\u5165\u63D0\u793A\u8BCD\u3001\u547D\u4EE4\u5386\u53F2\u6216\u65E5\u5FD7\u3002\u521D\u59CB\u5316\u540E\u8FD0\u884C doctor \u5E76\u7EE7\u7EED\u5F53\u524D\u4EFB\u52A1\uFF0C\u4E0D\u4EE5\u5BBF\u4E3B\u5C1A\u672A\u70ED\u52A0\u8F7D\u4E3A\u7531\u505C\u6B62\u5DE5\u4F5C\u3002\n\n"+pn())}
|
|
1364
1364
|
`}buildCodeBuddyRule(){return`---
|
|
1365
1365
|
description: Microi\u543E\u7801\u521D\u59CB\u5316\u3001\u670D\u52A1\u5668/MCP \u8FDE\u63A5\u3001\u5168\u90E8 V8 \u62C9\u53D6\u53CA\u4F4E\u4EE3\u7801\u5F00\u53D1\u5165\u53E3
|
|
1366
1366
|
alwaysApply: true
|
|
1367
1367
|
---
|
|
1368
1368
|
|
|
1369
|
-
${
|
|
1369
|
+
${Ye}
|
|
1370
1370
|
# Microi\u543E\u7801\u5165\u53E3
|
|
1371
1371
|
|
|
1372
1372
|
\u5728\u5DF2\u521D\u59CB\u5316\u543E\u7801\u5DE5\u4F5C\u533A\u4E2D\u76F4\u63A5\u63CF\u8FF0\u4E1A\u52A1\u9700\u6C42\uFF0C\u6216\u9047\u5230 Microi\u3001\u543E\u7801\u3001\`@microi.net/cli\`\u3001\u670D\u52A1\u5668\u8FDE\u63A5\u3001MCP \u6216 V8 \u62C9\u53D6\u4EFB\u52A1\u65F6\uFF0C\u7ACB\u5373\u8BFB\u53D6 \`.codebuddy/skills/microi/SKILL.md\` \u5E76\u6309\u5176\u4E2D\u6D41\u7A0B\u6267\u884C\u3002\u5B8C\u6574\u89C4\u8303\u4F4D\u4E8E\u5DE5\u4F5C\u533A \`microi.skills/\`\uFF0C\u4E0D\u8981\u51ED\u7A7A\u731C\u6D4B\u547D\u4EE4\u3001\u670D\u52A1\u5668\u6216\u6570\u636E\u7ED3\u6784\u3002
|
|
1373
|
-
`}generatePerOsClientSchemaDocs(e){let t=[];if(!R.existsSync(e))return t;let n=r=>{try{for(let i of R.readdirSync(r)){if(i.startsWith(".")&&i!==at)continue;let o=
|
|
1373
|
+
`}generatePerOsClientSchemaDocs(e){let t=[];if(!R.existsSync(e))return t;let n=r=>{try{for(let i of R.readdirSync(r)){if(i.startsWith(".")&&i!==at)continue;let o=x.join(r,i);if(i===at)try{let a=JSON.parse(R.readFileSync(o,"utf-8")),c=this.formatDbSchemaFull(a,x.relative(e,r));if(c){let l=x.join(r,ze);R.writeFileSync(l,c,"utf-8"),t.push(l)}}catch{}else try{R.statSync(o).isDirectory()&&n(o)}catch{}}}catch{}};return n(e),t}formatDbSchemaFull(e,t){if(!e.Tables||e.Tables.length===0)return"";let n=e.Tables.filter(i=>i.Name);if(n.length===0)return"";let r=[];r.push(`# \u6570\u636E\u5E93\u7ED3\u6784 \u2014 ${t}
|
|
1374
1374
|
`),r.push("> \u6B64\u6587\u4EF6\u7531 Microi\u543E\u7801 VS Code \u63D2\u4EF6\u81EA\u52A8\u751F\u6210\uFF0C\u5305\u542B\u8BE5\u5E94\u7528\u7684\u6240\u6709\u6570\u636E\u5E93\u8868\u548C\u5B57\u6BB5\u4FE1\u606F\u3002"),r.push(`> \u5171 ${n.length} \u5F20\u8868\u3002
|
|
1375
1375
|
`);for(let i of n){let o=i.Description?` \u2014 ${i.Description}`:"";r.push(`## ${i.Name}${o}
|
|
1376
1376
|
`);let a=i._Fields||i.Fields;if(a&&a.length>0){r.push("| \u5B57\u6BB5 | \u8BF4\u660E | \u7C7B\u578B |"),r.push("|------|------|------|");for(let c of a){let l=c.Description||c.Label||"",p=c.Type||c.FieldType||"";r.push(`| ${c.Name} | ${l} | ${p} |`)}r.push("")}}return r.join(`
|
|
1377
|
-
`)}ensureJsConfig(e,t){let n=
|
|
1378
|
-
`).trim()}function
|
|
1379
|
-
`)}}function no(s){let e=
|
|
1380
|
-
${lr(n)}`.trim());return n}function so(s){let e=[];for(let t of s.split(/\r?\n/)){let n=t.trim().split(/\s{2,}/);n.length<2||n[0]==="MARKETPLACE"||e.push({name:n[0],root:n.slice(1).join(" ")})}return e}function io(s){let e=[];for(let t of s.split(/\r?\n/)){let n=t.trim().split(/\s{2,}/);if(n.length<2||n[0]==="PLUGIN"||!n[0].includes("@"))continue;let r=/^not installed$/i.test(n[1]||"");e.push({selector:n[0],status:n[1]||"",version:r?"":n[2]||"",pluginPath:r?n.slice(2).join(" "):n.slice(3).join(" ")})}return e}function oo(){let e=[
|
|
1381
|
-
`,expectedVersion:n.version,pluginRoot:n.root}}function lo(s,e){let t=`${s}.${process.pid}.${Date.now()}.tmp`;try{W.writeFileSync(t,e,"utf8"),W.renameSync(t,s)}finally{try{W.existsSync(t)&&W.unlinkSync(t)}catch{}}}function
|
|
1382
|
-
${lr(c)}`:""}`.trim())}if(l.plugin.version!==t)throw new Error(`\u5F53\u524D\u5DF2\u5B89\u88C5 ${l.plugin.version||"\u672A\u77E5\u7248\u672C"}\uFF0C\u76EE\u6807\u63D2\u4EF6\u5FEB\u7167\u4E3A ${t}\u3002\u8BF7\u4F7F\u7528 --force \u663E\u5F0F\u91CD\u88C5\u3002`);let p=i.legacy.pluginInstalled?Cn:"";return i.legacy.pluginInstalled&&
|
|
1383
|
-
`)}}function yo(){let s=String(process.env.MICROI_DSH_PATH||"").trim();if(s){let n=te.resolve(s);if(!De.existsSync(n))throw new Error(`MICROI_DSH_PATH \u6307\u5411\u7684\u6587\u4EF6\u4E0D\u5B58\u5728\uFF1A${n}`);return[n]}let e=process.platform==="win32"?[["where.exe",["dsh.exe"]],["where.exe",["dsh.cmd"]],["where.exe",["dsh"]]]:[["which",["dsh"]]],t=[];for(let[n,r]of e){let i=mr.spawnSync(n,r,{encoding:"utf8",windowsHide:!0,timeout:3e3});i.status===0&&t.push(...String(i.stdout||"").split(/\r?\n/).map(o=>o.trim()).filter(Boolean))}return process.platform!=="win32"&&t.push("dsh"),[...new Map(t.map(n=>[process.platform==="win32"?n.toLowerCase():n,n])).values()]}function $s(){for(let s of yo()){if(te.isAbsolute(s)&&!De.existsSync(s))continue;let e=ho(s),t=Os(e,["--version"],5e3);if(t.status!==0)continue;let n=t.stdout.trim()||t.stderr.trim();if(n)return{...e,version:n}}}function So(s){return s==="~"?kn.homedir():s.startsWith("~/")||s.startsWith("~\\")?te.join(kn.homedir(),s.slice(2)):s}function gr(){let s=String(process.env.DSH_HOME||"").trim();return te.resolve(So(s||te.join(kn.homedir(),".dsh")))}function Co(s){let e=s.trim();if(!e||e==="."||e===".."||e==="node_modules"||/[/\\]/.test(e))throw new Error(`DeepSeek Harness profile \u540D\u79F0\u65E0\u6548\uFF1A${JSON.stringify(s)}`);return e}function Bs(s){return s?[Co(s)]:[...mo]}function bo(s,e){if(!e)return;let t=te.resolve(s,e),n=te.relative(s,t);if(!(!n||n.startsWith("..")||te.isAbsolute(n)))return t}function pr(s,e,t){let n=te.join(s,"profiles",e),r=vn(te.join(n,"package.json")),i=Oe(r?.dependencies),o=Oe(r?.dsh),a=Oe(o?.profile),c=Array.isArray(a?.bundles)?a?.bundles.map(String):[],l=te.join(n,"node_modules","@microi.net","cli"),p=vn(te.join(l,"package.json")),
|
|
1384
|
-
`).trim().slice(0,5e3)}function Us(s={}){let e=$s();if(!e)throw new Error("\u672A\u68C0\u6D4B\u5230 DeepSeek Harness dsh CLI\uFF1B\u8BF7\u5148\u6267\u884C npm install -g @deepseek-ai/dsh\uFF0C\u518D\u91CD\u8BD5 microi dsh install");let t=Vs(),n=Bs(s.profile),r=s.source?ko(s.source):"",i=r||`${$e}@${t.version}`,o=[];for(let c of n){let l=pr(gr(),c,t.version);if(l.ok&&!s.force){o.push({...l,changed:!1});continue}let p=["plugin","--profile",c,"add",i,"--save-exact",...r?[]:[`--registry=${fo}`]],
|
|
1377
|
+
`)}ensureJsConfig(e,t){let n=x.join(e,"jsconfig.json"),r=e,i=e,o;if(R.existsSync(n))try{o=JSON.parse(R.readFileSync(n,"utf-8"))}catch{o={}}else o={};let a=o.compilerOptions||{};a.target=a.target||"ES2020",a.module=a.module||"CommonJS",a.checkJs=!0;let c=x.relative(e,t),l=a.typeRoots||[];l.includes(`./${c}`)||l.push(`./${c}`),a.typeRoots=l,o.compilerOptions=a;let p=o.include||[],d=x.relative(e,r),u=x.relative(e,i),g=`${c}/**/*`;for(let f of[`${d}/**/*`,`${u}/**/*`,g])p.includes(f)||p.push(f);o.include=p;let m=o.exclude||[];m.includes("node_modules")||m.push("node_modules"),o.exclude=m,R.writeFileSync(n,JSON.stringify(o,null,2),"utf-8")}cleanup(){let e=N.getInstance(),t=e.getWorkspaceRoot();if(!t)return;let n=e.getSyncRootDir(),r=x.join(n,_t),i=x.join(r,tn);R.existsSync(i)&&R.unlinkSync(i);let o=x.join(t,_t),a=x.join(o,tn);if(R.existsSync(a)&&R.unlinkSync(a),x.resolve(n)!==x.resolve(t)){let c=x.join(t,Bn,Ln),l=x.join(t,Un),p=x.join(t,jn),d=x.join(t,Kn),u=x.join(t,Hn,Wn),g=Es.map(f=>x.join(t,f)),m=x.join(t,Ts);if(this.canRemoveGeneratedAiDoc(t,c))try{R.unlinkSync(c)}catch{}if(this.canRemoveGeneratedAiDoc(t,l))try{R.unlinkSync(l)}catch{}if(this.canRemoveGeneratedAiDoc(t,p))try{R.unlinkSync(p)}catch{}if(this.canRemoveGeneratedAiDoc(t,d))try{R.unlinkSync(d)}catch{}if(this.canRemoveGeneratedAiDoc(t,u))try{R.unlinkSync(u)}catch{}for(let f of g)if(this.canRemoveGeneratedAiDoc(t,f))try{R.unlinkSync(f)}catch{}if(this.canRemoveGeneratedAiDoc(t,m))try{R.unlinkSync(m)}catch{}}this.cleanupSchemaDocs(n)}cleanupSchemaDocs(e){try{for(let t of R.readdirSync(e)){if(t.startsWith(".")&&t!==ze)continue;let n=x.join(e,t);if(t===ze)try{R.unlinkSync(n)}catch{}else try{R.statSync(n).isDirectory()&&this.cleanupSchemaDocs(n)}catch{}}}catch{}}};function jt(s,e){let t=i=>{if(!(!i||!/^\d+(?:\.\d+){2}$/.test(i)))return i.split(".").map(o=>Number(o))},n=t(s),r=t(e);if(!n||!r)return 0;for(let i=0;i<3;i+=1)if(n[i]!==r[i])return n[i]>r[i]?1:-1;return 0}function Ut(s){let e=s.env,t=String(e?.MICROI_TOOL_VERSION||"").trim();return/^\d+(?:\.\d+){2}$/.test(t)?t:""}function Sn(s){let e=s.env||{},t=s.headers||{},r=(o=>o.trim().replace(/\/+$/,"").toLowerCase())(String(e.MICROI_API_URL||s.url||"")),i=String(e.MICROI_OS_CLIENT||t["X-Microi-OsClient"]||"").trim().toLowerCase();return`${r}|${i}`}function Ps(s,e,t){let n={...s},r={},i=new Set,o=[];for(let[c,l]of Object.entries(e)){let p=Sn(l),d=Ut(l),u=Object.entries(n).filter(([m,f])=>{if(!t.isManaged(m,f))return!1;let y=Sn(f);return m===c||p!=="|"&&y===p}),g=u.find(([,m])=>jt(Ut(m),d)>0);if(g){let m=Ut(g[1]);for(let[f]of u)i.add(f);o.push({name:g[0],version:m});continue}r[c]=l}let a=new Set(Object.values(r).map(Sn).filter(c=>c!=="|"));for(let[c,l]of Object.entries(n)){if(!t.isManaged(c,l)||i.has(c))continue;if(Object.prototype.hasOwnProperty.call(r,c)){delete n[c];continue}let p=Sn(l);if(a.has(p)){delete n[c];continue}(t.removeManagedNotInNext||t.isStableName&&!t.isStableName(c))&&delete n[c]}return Object.assign(n,r),{servers:n,skippedNewerProviders:o}}var dr=B(require("child_process")),W=B(require("fs")),Ds=B(require("os")),q=B(require("path")),je="microi-net",Me="microi",Ve=`${Me}@${je}`,wn="@microi.net/cli",Is="@microi.net/codex-plugin",Kt="microi-official",Cn=`${Me}@${Kt}`;function lr(s){return[s.stderr,s.stdout].filter(Boolean).join(`
|
|
1378
|
+
`).trim()}function Rs(s,e,t=3e4){let n=dr.spawnSync(s.command,[...s.prefixArgs,...e],{encoding:"utf8",windowsHide:!0,timeout:t,maxBuffer:16777216});return{status:typeof n.status=="number"?n.status:1,stdout:String(n.stdout||""),stderr:[n.error?.message,n.stderr].filter(Boolean).join(`
|
|
1379
|
+
`)}}function no(s){let e=q.extname(s).toLowerCase();return e===".js"||e===".cjs"||e===".mjs"?{command:process.execPath,prefixArgs:[s],displayPath:s}:process.platform==="win32"&&(e===".cmd"||e===".bat")?{command:process.env.ComSpec||"cmd.exe",prefixArgs:["/d","/s","/c",s],displayPath:s}:{command:s,prefixArgs:[],displayPath:s}}function ro(){let s=String(process.env.MICROI_CODEX_PATH||"").trim();if(s){let r=q.resolve(s);if(!W.existsSync(r))throw new Error(`MICROI_CODEX_PATH \u6307\u5411\u7684\u6587\u4EF6\u4E0D\u5B58\u5728\uFF1A${r}`);return[r]}let e=process.platform==="win32"?[["where.exe",["codex.exe"]],["where.exe",["codex"]]]:[["which",["codex"]]],t=[];for(let[r,i]of e){let o=dr.spawnSync(r,i,{encoding:"utf8",windowsHide:!0,timeout:3e3});o.status===0&&t.push(...String(o.stdout||"").split(/\r?\n/).map(a=>a.trim()).filter(Boolean))}return process.platform!=="win32"&&t.push("codex"),[...new Map(t.map(r=>[process.platform==="win32"?r.toLowerCase():r,r])).values()].sort((r,i)=>{let o=q.extname(r).toLowerCase()===".exe"?0:1,a=q.extname(i).toLowerCase()===".exe"?0:1;return o-a})}function Ns(){for(let s of ro()){if(q.isAbsolute(s)&&!W.existsSync(s))continue;let e=no(s),t=Rs(e,["--version"],5e3);if(t.status!==0)continue;let n=t.stdout.trim()||t.stderr.trim();if(/codex/i.test(n))return{...e,version:n}}}function Ae(s,e,t=!1){let n=Rs(s,["-c",'model_reasoning_effort="high"',...e]);if(!t&&n.status!==0)throw new Error(`Codex CLI \u6267\u884C\u5931\u8D25\uFF1Acodex ${e.join(" ")}
|
|
1380
|
+
${lr(n)}`.trim());return n}function so(s){let e=[];for(let t of s.split(/\r?\n/)){let n=t.trim().split(/\s{2,}/);n.length<2||n[0]==="MARKETPLACE"||e.push({name:n[0],root:n.slice(1).join(" ")})}return e}function io(s){let e=[];for(let t of s.split(/\r?\n/)){let n=t.trim().split(/\s{2,}/);if(n.length<2||n[0]==="PLUGIN"||!n[0].includes("@"))continue;let r=/^not installed$/i.test(n[1]||"");e.push({selector:n[0],status:n[1]||"",version:r?"":n[2]||"",pluginPath:r?n.slice(2).join(" "):n.slice(3).join(" ")})}return e}function oo(){let e=[q.join(__dirname,"codex-marketplace.json"),q.resolve(__dirname,"..","..","codex","marketplace.npm.json")].find(t=>W.existsSync(t));if(!e)throw new Error("CLI \u7F3A\u5C11 codex-marketplace.json\uFF0C\u8BF7\u91CD\u65B0\u5B89\u88C5\u6700\u65B0\u7248 @microi.net/cli");return e}function ur(s,e){let t=q.join(s,".codex-plugin","plugin.json"),n=q.join(s,"package.json"),r,i;try{r=JSON.parse(W.readFileSync(t,"utf8")),i=JSON.parse(W.readFileSync(n,"utf8"))}catch(o){throw new Error(`${e}\u8EAB\u4EFD\u6587\u4EF6\u65E0\u6CD5\u89E3\u6790\uFF1A${o instanceof Error?o.message:String(o)}`)}return{name:String(r.name||""),version:String(r.version||""),packageName:String(i.name||"")}}function ao(){let s=[q.resolve(__dirname,".."),q.resolve(__dirname,"..","..","plugins",Me)];for(let e of s){if(!W.existsSync(q.join(e,".codex-plugin","plugin.json"))||!W.existsSync(q.join(e,"package.json")))continue;let t=ur(e,"\u5185\u7F6E Microi Agentx \u63D2\u4EF6");if(t.name===Me&&t.packageName===wn&&t.version)return{root:e,version:t.version}}throw new Error("CLI \u7F3A\u5C11\u5B8C\u6574\u7684 Microi Agentx \u63D2\u4EF6\u6587\u4EF6\uFF0C\u8BF7\u91CD\u65B0\u5B89\u88C5\u6700\u65B0\u7248 @microi.net/cli")}function co(s){if(!s||s.name!==Me)return!1;if(s.source?.source==="local")return String(s.source.path||"").replace(/\\/g,"/").replace(/^\.\//,"")==="plugins/microi";let e=[wn,Is];return s.source?.source==="npm"&&e.includes(s.source.package||"")}function As(){let s=W.readFileSync(oo(),"utf8"),e;try{e=JSON.parse(s)}catch(r){throw new Error(`Codex marketplace \u6A21\u677F\u65E0\u6CD5\u89E3\u6790\uFF1A${r instanceof Error?r.message:String(r)}`)}let t=e.plugins?.find(r=>r.name===Me);if(e.name!==je||t?.source?.source!=="local"||String(t.source.path||"").replace(/\\/g,"/").replace(/^\.\//,"")!=="plugins/microi")throw new Error("Codex marketplace \u6A21\u677F\u8EAB\u4EFD\u4E0D\u5408\u6CD5\uFF0C\u62D2\u7EDD\u5199\u5165\u5168\u5C40\u914D\u7F6E");let n=ao();return{manifest:e,content:`${JSON.stringify(e,null,2)}
|
|
1381
|
+
`,expectedVersion:n.version,pluginRoot:n.root}}function lo(s,e){let t=`${s}.${process.pid}.${Date.now()}.tmp`;try{W.writeFileSync(t,e,"utf8"),W.renameSync(t,s)}finally{try{W.existsSync(t)&&W.unlinkSync(t)}catch{}}}function Ms(){return q.resolve(process.env.CODEX_HOME||q.join(Ds.homedir(),".codex"))}function uo(s,e,t){let n=q.resolve(s),r=q.resolve(e),i=q.relative(n,r);if(!i||!i.startsWith("..")&&!q.isAbsolute(i))throw new Error(`Codex \u63D2\u4EF6\u76EE\u6807\u76EE\u5F55\u4E0D\u80FD\u4F4D\u4E8E npm \u5305\u5185\u90E8\uFF1A${r}`);if(W.existsSync(r)){let d=ur(r,"\u73B0\u6709 Microi Agentx \u63D2\u4EF6"),u=[wn,Is];if(d.name!==Me||!u.includes(d.packageName))throw new Error(`\u76EE\u6807\u76EE\u5F55\u5305\u542B\u975E Microi \u7BA1\u7406\u7684\u63D2\u4EF6\uFF0C\u62D2\u7EDD\u8986\u76D6\uFF1A${r}`)}let o=q.dirname(r);W.mkdirSync(o,{recursive:!0});let a=`${process.pid}-${Date.now()}`,c=q.join(o,`.microi-staging-${a}`),l=q.join(o,`.microi-backup-${a}`),p=!1;try{W.cpSync(n,c,{recursive:!0,errorOnExist:!0});let d=ur(c,"\u5F85\u5B89\u88C5 Microi Agentx \u63D2\u4EF6");if(d.name!==Me||d.packageName!==wn||d.version!==t)throw new Error("\u5F85\u5B89\u88C5\u7684 Microi Agentx \u63D2\u4EF6\u8EAB\u4EFD\u6216\u7248\u672C\u4E0D\u4E00\u81F4");W.existsSync(r)&&(W.renameSync(r,l),p=!0),W.renameSync(c,r)}catch(d){if(!W.existsSync(r)&&p&&W.existsSync(l))try{W.renameSync(l,r)}catch{}throw d}finally{try{W.existsSync(c)&&W.rmSync(c,{recursive:!0,force:!0})}catch{}}try{W.existsSync(l)&&W.rmSync(l,{recursive:!0,force:!0})}catch{}}function go(s,e,t){let n=Ms(),r=q.join(n,"microi-net-marketplace"),i=q.join(r,".agents","plugins","marketplace.json"),o=q.join(r,"plugins",Me);if(W.mkdirSync(q.dirname(i),{recursive:!0}),W.existsSync(i)){let a;try{a=JSON.parse(W.readFileSync(i,"utf8"))}catch(l){throw new Error(`\u5DF2\u5B58\u5728\u7684 Microi marketplace \u65E0\u6CD5\u89E3\u6790\uFF0C\u5DF2\u4FDD\u7559\u539F\u6587\u4EF6\uFF1A${i}\uFF08${l instanceof Error?l.message:String(l)}\uFF09`)}let c=a.plugins?.find(l=>l.name===Me);if(a.name!==je||!co(c))throw new Error(`\u76EE\u6807\u76EE\u5F55\u5305\u542B\u975E Microi \u7BA1\u7406\u7684 marketplace\uFF0C\u62D2\u7EDD\u8986\u76D6\uFF1A${i}`)}return uo(e,o,t),(!W.existsSync(i)||W.readFileSync(i,"utf8")!==s)&&lo(i,s),r}function po(s){let e=s.trim();if(!e||/[\r\n]/.test(e))throw new Error("Codex marketplace source \u65E0\u6548");let t=q.resolve(e);if(W.existsSync(t))return t;if(q.isAbsolute(e)||e.startsWith("."))throw new Error(`Codex marketplace \u672C\u5730\u8DEF\u5F84\u4E0D\u5B58\u5728\uFF1A${t}`);return e}function bn(s,e){let t=so(Ae(s,["plugin","marketplace","list"]).stdout),n=io(Ae(s,["plugin","list"]).stdout),r=t.find(u=>u.name===je),i=n.find(u=>u.selector===Ve),o=t.some(u=>u.name===Kt),a=n.some(u=>u.selector===Cn&&/^installed\b/i.test(u.status)),c=!!(i&&/^installed\b/i.test(i.status)),l=!!(i&&/enabled/i.test(i.status)),p=!e||i?.version===e,d=c?l?p?"none":"update":"enable":"install";return{ok:c&&l&&p,codex:{found:!0,command:s.displayPath,version:s.version},marketplace:{name:je,configured:!!r,root:r?.root||""},plugin:{selector:Ve,installed:c,enabled:l,version:i?.version||"",expectedVersion:e},legacy:{marketplaceConfigured:o,pluginInstalled:a},action:d}}function xs(){let{expectedVersion:s}=As(),e=Ns();return e?bn(e,s):{ok:!1,codex:{found:!1,command:"",version:""},marketplace:{name:je,configured:!1,root:""},plugin:{selector:Ve,installed:!1,enabled:!1,version:"",expectedVersion:s},legacy:{marketplaceConfigured:!1,pluginInstalled:!1},action:"install-codex"}}function Fs(s={}){let{content:e,expectedVersion:t,pluginRoot:n}=As(),r=Ns();if(!r)throw new Error("\u672A\u627E\u5230\u53EF\u6267\u884C\u7684 Codex CLI\u3002\u8BF7\u5148\u5B89\u88C5\u6216\u66F4\u65B0 Codex\uFF0C\u518D\u6267\u884C microi codex install --yes");W.mkdirSync(Ms(),{recursive:!0});let i=bn(r,t);if(i.ok&&!s.force){i.legacy.pluginInstalled&&Ae(r,["plugin","remove",Cn]),i.legacy.marketplaceConfigured&&Ae(r,["plugin","marketplace","remove",Kt]);let d=i.legacy.pluginInstalled||i.legacy.marketplaceConfigured;return{installed:!0,changed:d,selector:Ve,version:i.plugin.version,migratedFrom:d?Kt:void 0,restartRequired:d}}let o=s.marketplaceSource?po(s.marketplaceSource):go(e,n,t);i.marketplace.configured||Ae(r,["plugin","marketplace","add",o]);let a=bn(r,t);if(!a.marketplace.configured)throw new Error(`Codex \u672A\u80FD\u6CE8\u518C marketplace ${je}`);let c;s.force&&a.plugin.installed?(Ae(r,["plugin","remove",Ve]),c=Ae(r,["plugin","add",Ve],!0)):c=Ae(r,["plugin","add",Ve],!0);let l=bn(r,t);if(!l.plugin.installed||!l.plugin.enabled){let d=s.force?"--force \u5DF2\u6267\u884C\u663E\u5F0F\u91CD\u88C5\uFF0C\u8BF7\u68C0\u67E5\u4E0A\u65B9\u9519\u8BEF\u540E\u91CD\u8BD5\u3002":"\u539F\u6709\u63D2\u4EF6\u672A\u88AB\u5220\u9664\u3002";throw new Error(`\u5B89\u88C5 ${Ve} \u5931\u8D25\uFF0C${d}${lr(c)?`
|
|
1382
|
+
${lr(c)}`:""}`.trim())}if(l.plugin.version!==t)throw new Error(`\u5F53\u524D\u5DF2\u5B89\u88C5 ${l.plugin.version||"\u672A\u77E5\u7248\u672C"}\uFF0C\u76EE\u6807\u63D2\u4EF6\u5FEB\u7167\u4E3A ${t}\u3002\u8BF7\u4F7F\u7528 --force \u663E\u5F0F\u91CD\u88C5\u3002`);let p=i.legacy.pluginInstalled?Cn:"";return i.legacy.pluginInstalled&&Ae(r,["plugin","remove",Cn]),i.legacy.marketplaceConfigured&&Ae(r,["plugin","marketplace","remove",Kt]),{installed:!0,changed:!0,selector:Ve,version:l.plugin.version,marketplace:je,marketplaceSource:o,migratedFrom:p||void 0,restartRequired:!0,next:"\u65B0\u5EFA Codex \u4EFB\u52A1\u6216\u91CD\u8F7D Codex\uFF0C\u4F7F\u63D2\u4EF6 Skills \u4E0E MCP \u751F\u6548\u3002"}}var mr=B(require("child_process")),De=B(require("fs")),kn=B(require("os")),te=B(require("path")),$e="@microi.net/cli",mo=["web","headless"],fo="https://registry.npmjs.org/";function vn(s){try{let e=JSON.parse(De.readFileSync(s,"utf8"));return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}catch{return}}function Oe(s){return s&&typeof s=="object"&&!Array.isArray(s)?s:void 0}function Vs(){let s=[te.resolve(__dirname,".."),te.resolve(__dirname,"..","..","plugins","microi")];for(let e of s){let t=vn(te.join(e,"package.json")),n=Oe(t?.dsh),r=Oe(n?.bundle),i=String(r?.patch||""),o=String(t?.version||"");if(!(t?.name!==$e||!o||i!=="./cordis.patch.yml")&&De.existsSync(te.join(e,"cordis.patch.yml")))return{root:e,version:o,patch:i}}throw new Error("CLI \u7F3A\u5C11\u5B8C\u6574\u7684 Microi DeepSeek Harness bundle\uFF0C\u8BF7\u91CD\u65B0\u5B89\u88C5\u6700\u65B0\u7248 @microi.net/cli")}function ho(s){let e=te.extname(s).toLowerCase();return e===".js"||e===".cjs"||e===".mjs"?{command:process.execPath,prefixArgs:[s],displayPath:s}:process.platform==="win32"&&(e===".cmd"||e===".bat")?{command:process.env.ComSpec||"cmd.exe",prefixArgs:["/d","/s","/c",s],displayPath:s}:{command:s,prefixArgs:[],displayPath:s}}function Os(s,e,t=3e4){let n=mr.spawnSync(s.command,[...s.prefixArgs,...e],{cwd:process.cwd(),encoding:"utf8",windowsHide:!0,timeout:t,maxBuffer:33554432,env:{...process.env}});return{status:typeof n.status=="number"?n.status:1,stdout:String(n.stdout||""),stderr:[n.error?.message,n.stderr].filter(Boolean).join(`
|
|
1383
|
+
`)}}function yo(){let s=String(process.env.MICROI_DSH_PATH||"").trim();if(s){let n=te.resolve(s);if(!De.existsSync(n))throw new Error(`MICROI_DSH_PATH \u6307\u5411\u7684\u6587\u4EF6\u4E0D\u5B58\u5728\uFF1A${n}`);return[n]}let e=process.platform==="win32"?[["where.exe",["dsh.exe"]],["where.exe",["dsh.cmd"]],["where.exe",["dsh"]]]:[["which",["dsh"]]],t=[];for(let[n,r]of e){let i=mr.spawnSync(n,r,{encoding:"utf8",windowsHide:!0,timeout:3e3});i.status===0&&t.push(...String(i.stdout||"").split(/\r?\n/).map(o=>o.trim()).filter(Boolean))}return process.platform!=="win32"&&t.push("dsh"),[...new Map(t.map(n=>[process.platform==="win32"?n.toLowerCase():n,n])).values()]}function $s(){for(let s of yo()){if(te.isAbsolute(s)&&!De.existsSync(s))continue;let e=ho(s),t=Os(e,["--version"],5e3);if(t.status!==0)continue;let n=t.stdout.trim()||t.stderr.trim();if(n)return{...e,version:n}}}function So(s){return s==="~"?kn.homedir():s.startsWith("~/")||s.startsWith("~\\")?te.join(kn.homedir(),s.slice(2)):s}function gr(){let s=String(process.env.DSH_HOME||"").trim();return te.resolve(So(s||te.join(kn.homedir(),".dsh")))}function Co(s){let e=s.trim();if(!e||e==="."||e===".."||e==="node_modules"||/[/\\]/.test(e))throw new Error(`DeepSeek Harness profile \u540D\u79F0\u65E0\u6548\uFF1A${JSON.stringify(s)}`);return e}function Bs(s){return s?[Co(s)]:[...mo]}function bo(s,e){if(!e)return;let t=te.resolve(s,e),n=te.relative(s,t);if(!(!n||n.startsWith("..")||te.isAbsolute(n)))return t}function pr(s,e,t){let n=te.join(s,"profiles",e),r=vn(te.join(n,"package.json")),i=Oe(r?.dependencies),o=Oe(r?.dsh),a=Oe(o?.profile),c=Array.isArray(a?.bundles)?a?.bundles.map(String):[],l=te.join(n,"node_modules","@microi.net","cli"),p=vn(te.join(l,"package.json")),d=Oe(p?.dsh),u=Oe(d?.bundle),g=String(u?.patch||""),m=bo(l,g),f=!!r,y=typeof i?.[$e]=="string",C=p?.name===$e,h=C?String(p?.version||""):"",S=c.includes($e),b=g==="./cordis.patch.yml"&&!!(m&&De.existsSync(m)),E=h===t;return{profile:e,profileDir:n,initialized:f,dependencyDeclared:y,installed:C,active:S,installedVersion:h,expectedVersion:t,bundlePatch:g,bundlePatchExists:b,ok:f&&y&&C&&S&&b&&E,action:!C||!y?"install":!E||!b?"update":S?"none":"activate"}}function wo(s,e){let t=Vs(),n=gr(),r=e.map(o=>pr(n,o,t.version)),i=s?r.some(o=>o.action==="install")?"install":r.some(o=>o.action==="update")?"update":r.some(o=>o.action==="activate")?"activate":"none":"install-dsh";return{ok:!!s&&r.every(o=>o.ok),dsh:{found:!!s,command:s?.displayPath||"",version:s?.version||"",home:n},package:{name:$e,expectedVersion:t.version,bundlePatch:t.patch},profiles:r,action:i,requiresNewSession:i!=="none"&&i!=="install-dsh"}}function Ls(s){return wo($s(),Bs(s))}function ko(s){let e=te.resolve(s);if(!De.existsSync(e))throw new Error(`DeepSeek Harness bundle \u672C\u5730\u6765\u6E90\u4E0D\u5B58\u5728\uFF1A${e}`);if(!De.statSync(e).isDirectory()){if(!/\.(?:tgz|tar\.gz)$/i.test(e))throw new Error("DeepSeek Harness bundle --source \u53EA\u63A5\u53D7\u672C\u5730\u76EE\u5F55\u6216 .tgz/.tar.gz");return e}let t=[e,te.join(e,"plugins","microi")];for(let n of t){let r=vn(te.join(n,"package.json")),i=Oe(r?.dsh),o=Oe(i?.bundle);if(r?.name===$e&&o?.patch==="./cordis.patch.yml"&&De.existsSync(te.join(n,"cordis.patch.yml")))return n}throw new Error(`\u672C\u5730\u6765\u6E90\u4E0D\u662F\u5B8C\u6574\u7684 ${$e} DeepSeek Harness bundle\uFF1A${e}`)}function vo(s){return[s.stderr,s.stdout].filter(Boolean).join(`
|
|
1384
|
+
`).trim().slice(0,5e3)}function Us(s={}){let e=$s();if(!e)throw new Error("\u672A\u68C0\u6D4B\u5230 DeepSeek Harness dsh CLI\uFF1B\u8BF7\u5148\u6267\u884C npm install -g @deepseek-ai/dsh\uFF0C\u518D\u91CD\u8BD5 microi dsh install");let t=Vs(),n=Bs(s.profile),r=s.source?ko(s.source):"",i=r||`${$e}@${t.version}`,o=[];for(let c of n){let l=pr(gr(),c,t.version);if(l.ok&&!s.force){o.push({...l,changed:!1});continue}let p=["plugin","--profile",c,"add",i,"--save-exact",...r?[]:[`--registry=${fo}`]],d=Os(e,p,5*6e4);if(d.status!==0)throw new Error(`DeepSeek Harness profile ${c} \u5B89\u88C5 Microi bundle \u5931\u8D25\uFF1A${vo(d)||`exit ${d.status}`}`);let u=pr(gr(),c,t.version);if(!u.ok)throw new Error(`DeepSeek Harness profile ${c} \u5B89\u88C5\u540E\u6821\u9A8C\u5931\u8D25\uFF08action=${u.action}\uFF0Cversion=${u.installedVersion||"missing"}\uFF09`);o.push({...u,changed:!0})}let a=o.some(c=>c.changed);return{ok:!0,package:`${$e}@${t.version}`,source:i,profiles:o,requiresNewSession:a,message:a?"Microi\u543E\u7801\u5DF2\u5B89\u88C5\u4E3A DeepSeek Harness profile bundle\uFF1B\u8BF7\u65B0\u5EFA DSH \u4F1A\u8BDD\u52A0\u8F7D\u65B0\u589E MCP \u5DE5\u5177\uFF0C\u5F53\u524D\u4F1A\u8BDD\u4E0D\u4F1A\u88AB\u7EC8\u6B62\u3002":"DeepSeek Harness \u4E2D\u7684 Microi\u543E\u7801 bundle \u5DF2\u662F\u5F53\u524D\u7248\u672C\uFF0C\u65E0\u9700\u6539\u52A8\u3002"}}var En=B(require("crypto")),U=B(require("fs")),Gt=B(require("os")),K=B(require("path"));function fr(s){return s.normalize("NFKD").replace(/[^\x00-\x7F]/g,"").replace(/[^A-Za-z0-9_]+/g,"_").replace(/_+/g,"_").replace(/^_+|_+$/g,"").toLowerCase().slice(0,48)}function Ks(s){try{return fr(new URL(s.apiBaseUrl.trim().replace(/\/+$/,"")).host)}catch{return fr(s.apiBaseUrl)}}function js(s){return fr(s.osClient||s.sysShortTitle||s.sysTitle||s.label||"")||Ks(s)||"default"}function mt(s){let e=new Map;for(let r of s){let i=js(r);e.set(i,(e.get(i)||0)+1)}let t=new Set(Array.from(e).filter(([,r])=>r>1).map(([r])=>r)),n=new Set;return s.map(r=>{let i=Ks(r),o=js(r),a=`microi_${o}`,c=t.has(o)&&i&&i!==o?`${a}_${i}`:a;n.has(c)&&i&&(c=`${a}_${i}`);let l=2;for(;n.has(c);)c=`${a}_${l++}`;return n.add(c),{profile:r,mcpName:c}})}var Ht="";function Ke(){if(Ht)return Ht;try{let s=JSON.parse(U.readFileSync(K.join(__dirname,"..","package.json"),"utf8"));Ht=/^\d+(?:\.\d+){2}$/.test(String(s.version||""))?String(s.version):"0.0.0"}catch{Ht="0.0.0"}return Ht}function Eo(s){return s.trim().replace(/\/+$/,"")}function To(){let s=`MCP:${Gt.hostname()||"Unknown"}`;return/^[\x20-\x7E]{1,128}$/.test(s)?s:`MCP-${En.createHash("sha256").update(s).digest("hex").slice(0,16)}`}function Ws(s){let e=K.basename(s).toLowerCase();return!!process.versions.electron||["code.exe","code - insiders.exe","cursor.exe","windsurf.exe","trae.exe","electron.exe"].includes(e)}function _o(){return{command:process.execPath,isElectron:Ws(process.execPath)}}function Po(s,e){let t=e.env;return/^microi(?:_|-|$)/i.test(s)||typeof t?.MICROI_API_URL=="string"}function Gs(s,e){let t=`${s}.${process.pid}.${Date.now()}.tmp`;try{U.writeFileSync(t,e,"utf8"),U.renameSync(t,s)}finally{try{U.existsSync(t)&&U.unlinkSync(t)}catch{}}}function xe(s,e){if(U.existsSync(s)&&U.readFileSync(s).equals(e))return;U.mkdirSync(K.dirname(s),{recursive:!0});let t=`${process.pid}.${Date.now()}.${En.randomBytes(4).toString("hex")}`,n=`${s}.${t}.stage`,r=`${s}.${t}.backup`,i=!1;try{U.writeFileSync(n,e),U.existsSync(s)&&(U.renameSync(s,r),i=!0),U.renameSync(n,s),i&&U.rmSync(r,{force:!0})}catch(o){if(!U.existsSync(s)&&i&&U.existsSync(r))try{U.renameSync(r,s)}catch{}throw o}finally{try{U.existsSync(n)&&U.rmSync(n,{force:!0})}catch{}}}function Do(){let s=Ke();if(!/^\d+(?:\.\d+){2}$/.test(s))throw new Error(`CLI \u7248\u672C\u4E0D\u5408\u6CD5\uFF0C\u65E0\u6CD5\u521B\u5EFA MCP \u8FD0\u884C\u65F6\uFF1A${s}`);let e={launcher:K.join(__dirname,"microi-cli-mcp.js"),server:K.join(__dirname,"mcp-server.js"),adapter:K.join(__dirname,"mcp-codex-stdio-adapter.js"),router:K.join(__dirname,"microi-codex-router.js"),broker:K.join(__dirname,"microi-codex-broker.js"),cli:K.join(__dirname,"microi-cli.js"),trae:K.join(__dirname,"mcp-trae-windows-launcher.cmd")},t=Object.values(e).filter(u=>!U.existsSync(u));if(t.length>0)throw new Error(`CLI \u5B89\u88C5\u5305\u7F3A\u5C11\u5185\u7F6E MCP \u8FD0\u884C\u6587\u4EF6\uFF1A${t.join(", ")}`);let n=K.resolve(process.env.MICROI_RUNTIME_HOME||K.join(Gt.homedir(),".microi","runtime")),r=K.join(n,"versions"),i=K.join(r,s);U.mkdirSync(i,{recursive:!0}),xe(K.join(i,"microi-cli-mcp.js"),U.readFileSync(e.launcher)),xe(K.join(i,"mcp-server.js"),U.readFileSync(e.server)),xe(K.join(i,"microi-codex-router.js"),U.readFileSync(e.router)),xe(K.join(i,"microi-codex-broker.js"),U.readFileSync(e.broker)),xe(K.join(i,"microi-cli.js"),U.readFileSync(e.cli));let o=`#!/usr/bin/env node
|
|
1385
1385
|
'use strict';
|
|
1386
1386
|
const fs = require('node:fs');
|
|
1387
1387
|
const path = require('node:path');
|
|
@@ -1393,22 +1393,22 @@ const target = path.resolve(versionsRoot, pointer.version, 'microi-cli-mcp.js');
|
|
|
1393
1393
|
const relative = path.relative(versionsRoot, target);
|
|
1394
1394
|
if (!relative || relative.startsWith('..') || path.isAbsolute(relative)) throw new Error('Unsafe Microi MCP runtime target');
|
|
1395
1395
|
require(target);
|
|
1396
|
-
`,a=
|
|
1397
|
-
`,"utf8")),{root:n,launcherPath:a,adapterPath:c,routerPath:l,traeLauncherPath:p}}function ft(s,e,t,n=!1){
|
|
1398
|
-
`;(!
|
|
1399
|
-
`);if(!(/^microi(?:_|-|$)/.test(l)||/\bMICROI_(?:API_URL|TOKEN_FILE|OS_CLIENT)\b/.test(p)))return!0;let
|
|
1396
|
+
`,a=K.join(n,"microi-cli-mcp.js"),c=K.join(n,"mcp-codex-stdio-adapter.js"),l=K.join(n,"microi-codex-router.js"),p=K.join(n,"mcp-trae-windows-launcher.cmd");xe(a,Buffer.from(o,"utf8"));let d=o.replace(/microi-cli-mcp\.js/g,"microi-codex-router.js");return xe(l,Buffer.from(d,"utf8")),xe(c,U.readFileSync(e.adapter)),xe(p,U.readFileSync(e.trae)),xe(K.join(n,"current.json"),Buffer.from(`${JSON.stringify({version:s,activatedAt:new Date().toISOString()},null,2)}
|
|
1397
|
+
`,"utf8")),{root:n,launcherPath:a,adapterPath:c,routerPath:l,traeLauncherPath:p}}function ft(s,e,t,n=!1){U.mkdirSync(K.dirname(s),{recursive:!0});let r={};if(U.existsSync(s))try{r=nn(U.readFileSync(s,"utf8"))}catch(l){throw new Error(`MCP \u914D\u7F6E\u65E0\u6CD5\u89E3\u6790\uFF0C\u5DF2\u4FDD\u7559\u539F\u6587\u4EF6\u4E14\u505C\u6B62\u5199\u5165\uFF1A${s}\uFF08${l instanceof Error?l.message:String(l)}\uFF09`)}let i=r[e]&&typeof r[e]=="object"?r[e]:{},o=Object.fromEntries(Object.entries(t).map(([l,p])=>[l,n?Object.fromEntries(Object.entries(p).filter(([d])=>["command","args","env","url","headers"].includes(d))):p])),a=Ps(i,o,{isManaged:Po,isStableName:l=>/^microi_[a-z0-9_]+$/.test(l),removeManagedNotInNext:!0});r[e]=a.servers;let c=`${JSON.stringify(r,null,2)}
|
|
1398
|
+
`;(!U.existsSync(s)||U.readFileSync(s,"utf8")!==c)&&Gs(s,c)}function Wt(s){return JSON.stringify(String(s))}function Io(s){return`[${s.map(Wt).join(", ")}]`}function Ro(s){return`{ ${Object.entries(s).filter(([,e])=>e!==""&&e!=null).map(([e,t])=>`${Wt(e)} = ${Wt(t)}`).join(", ")} }`}function No(s,e){let t=[],n=[];for(let o of s.split(/\r?\n/))/^\s*\[[^\]]+\]\s*$/.test(o)&&n.length&&(t.push(n),n=[]),n.push(o);n.length&&t.push(n);let r=new Set;return{cleaned:t.filter(o=>{let c=o.find(g=>g.trim())?.match(/^\s*\[mcp_servers\.(?:"([^"]+)"|([A-Za-z0-9_-]+))(?:\.|\])/)||null;if(!c)return!0;let l=(c[1]||c[2]||"").toLowerCase(),p=o.join(`
|
|
1399
|
+
`);if(!(/^microi(?:_|-|$)/.test(l)||/\bMICROI_(?:API_URL|TOKEN_FILE|OS_CLIENT)\b/.test(p)))return!0;let u=p.match(/["']?MICROI_TOOL_VERSION["']?\s*=\s*["']([^"']+)["']/)?.[1]||"";return jt(u,e)>0?(r.add(l),!0):!1}).map(o=>o.join(`
|
|
1400
1400
|
`)).join(`
|
|
1401
1401
|
`).replace(/\n{3,}/g,`
|
|
1402
1402
|
|
|
1403
|
-
`).trimEnd(),preservedNames:r}}function Hs(s,e,t,n,r){
|
|
1403
|
+
`).trimEnd(),preservedNames:r}}function Hs(s,e,t,n,r){U.mkdirSync(K.dirname(s),{recursive:!0});let i=U.existsSync(s)?U.readFileSync(s,"utf8"):"",o=Ke(),{cleaned:a,preservedNames:c}=No(i,o),l=Object.values(e).find(f=>typeof f.command=="string"),p=String(l?.command||""),d={...l?.env||{}},u=Object.fromEntries(Object.entries(d).filter(([f])=>!f.startsWith("MICROI_")));p&&Ws(p)&&(u.ELECTRON_RUN_AS_NODE="1");let g=l&&c.size===0?["[mcp_servers.microi_codex]",`command = ${Wt(p)}`,`args = ${Io([t,n])}`,`cwd = ${Wt(r)}`,`env = ${Ro({...u,MICROI_CODEX_MODE:"1",MICROI_TOOL_SOURCE:"cli-codex-router",MICROI_TOOL_VERSION:o,MICROI_WORKSPACE_ROOT:r})}`,'enabled_tools = ["microi_codex"]','default_tools_approval_mode = "auto"'].join(`
|
|
1404
1404
|
`):"",m=[a,g].filter(Boolean).join(`
|
|
1405
1405
|
|
|
1406
1406
|
`)+`
|
|
1407
|
-
`;(!
|
|
1408
|
-
`)}function Lo(){try{return JSON.parse(
|
|
1409
|
-
`,"utf8")}function St(s,e){try{Bo(s)}catch{}if(e)try{ni(e)}catch{}}function
|
|
1410
|
-
`).trim()}}function br(s,e=12e4){let t=qs();return Cr=t.env,ri(t.command,[...t.prefixArgs,...s],e,t.shell,t.env)}function
|
|
1411
|
-
`),
|
|
1407
|
+
`;(!U.existsSync(s)||i!==m)&&Gs(s,m)}function Ao(s,e){let t=e.label||e.sysShortTitle||e.sysTitle||e.apiBaseUrl||"\u672A\u547D\u540D\u670D\u52A1\u5668";return K.join(s.getSyncRootDir(),s.buildServerDirName(t,e.apiBaseUrl),s.buildOsClientDirName(e.osClient,e.osClientType,e.osClientNetwork),Mr)}function Mo(s,e,t){let n={...s.env||{}},r=String(s.command||""),i=Array.isArray(s.args)?s.args.map(String):[];return process.platform==="win32"&&r&&i.length>0?{command:"cmd.exe",args:["/d","/s","/c","call",t,r,e,i[0]],env:n}:{command:r,args:i,env:n}}function xo(s){return typeof s.url=="string"&&s.url.trim()?{url:s.url,...s.headers&&typeof s.headers=="object"?{headers:{...s.headers}}:{}}:{command:String(s.command||""),args:Array.isArray(s.args)?s.args.map(String):[],...s.env&&typeof s.env=="object"?{env:{...s.env}}:{}}}function Fo(s){return typeof s.url=="string"&&s.url.trim()?{transportType:"streamableHttp",url:s.url,...s.headers&&typeof s.headers=="object"?{headers:{...s.headers}}:{}}:{transportType:"stdio",command:String(s.command||""),args:Array.isArray(s.args)?s.args.map(String):[],...s.env&&typeof s.env=="object"?{env:{...s.env}}:{},...typeof s.cwd=="string"&&s.cwd?{cwd:s.cwd}:{}}}async function Tn(s,e={}){let t=N.getInstance(),n=ke.getInstance(),r=L.getInstance(),i=t.getProfiles(),o=Ke(),a=Do(),c=a.launcherPath,l=a.adapterPath,p=a.routerPath,d=a.traeLauncherPath,u=_o(),g={};for(let{profile:h,mcpName:S}of mt(i)){let b=n.mcpTokenFilePath,E=b?K.join(K.dirname(b),Vt):"",k=n.getCredentialSecretKeys(h),I=r.getTokenForServer(h.apiBaseUrl,h.osClient,h.osClientType,h.osClientNetwork);!b||!I&&!U.existsSync(E)||(g[S]={type:"stdio",command:u.command,args:[c],cwd:a.root,env:{...u.isElectron?{ELECTRON_RUN_AS_NODE:"1"}:{},MICROI_API_URL:Eo(h.apiBaseUrl),MICROI_TOKEN_FILE:b,MICROI_AUTH_RECOVERY_DIR:n.mcpAuthRecoveryDirPath,MICROI_WORKSPACE_CREDENTIAL_FILE:E,MICROI_WORKSPACE_USERNAME_KEY:k.usernameKey,MICROI_WORKSPACE_PASSWORD_KEY:k.passwordKey,MICROI_OS_CLIENT:h.osClient||"",MICROI_OS_CLIENT_TYPE:h.osClientType||"",MICROI_OS_CLIENT_NETWORK:h.osClientNetwork||"",MICROI_WORKSPACE_ROOT:s,MICROI_SYNC_ROOT:t.getSyncRootDir(),MICROI_AI_APPLICATIONS_DIR:Ao(t,h),MICROI_LABEL_BASE64:Buffer.from(h.label||"","utf8").toString("base64"),MICROI_MCP_DID:To(),MICROI_TOOL_SOURCE:"cli",MICROI_TOOL_VERSION:o}})}await n.writeMcpTokenFile(),lt(s),Ue(s,[".vscode/mcp.json",".cursor/mcp.json",".trae/mcp.json",".workbuddy/mcp.json",".comate/mcp.json",".mcp.json",".codex/config.toml","Microi-V8-Engine/.microi-mcp-tokens.json",`Microi-V8-Engine/${Vt}`]),ft(K.join(s,".vscode","mcp.json"),"servers",g),ft(K.join(s,".cursor","mcp.json"),"mcpServers",g);let m=Object.fromEntries(Object.entries(g).map(([h,S])=>[h,Mo(S,l,d)]));ft(K.join(s,".trae","mcp.json"),"mcpServers",m,!0);let f=Object.fromEntries(Object.entries(g).map(([h,S])=>[h,xo(S)]));ft(K.join(s,".workbuddy","mcp.json"),"mcpServers",f,!0);let y=Object.fromEntries(Object.entries(g).map(([h,S])=>[h,Fo(S)]));ft(K.join(s,".comate","mcp.json"),"mcpServers",y),ft(K.join(s,".mcp.json"),"mcpServers",g,!0);let C=process.env.CODEX_HOME||K.join(Gt.homedir(),".codex");return e.globalCodex!==!1&&Hs(K.join(C,"config.toml"),g,l,p,s),Hs(K.join(s,".codex","config.toml"),g,l,p,s),{count:Object.keys(g).length,names:Object.keys(g)}}var _n=B(require("fs")),ht=B(require("path"));async function zs(s,e){let t=ht.resolve(s);if(!_n.existsSync(t)||!_n.statSync(t).isDirectory())throw new Error(`\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728\u6216\u4E0D\u662F\u76EE\u5F55\uFF1A${t}`);Ir(t);let n=N.getInstance(),r=L.getInstance(),i=ke.getInstance();if(!e&&process.platform!=="win32"&&process.platform!=="darwin")throw new Error("\u5F53\u524D CLI \u7248\u672C\u4EC5\u652F\u6301 Windows DPAPI \u4E0E macOS Keychain \u5DE5\u4F5C\u533A\u51ED\u636E");let o=n.getWorkspaceStateFilePath(vt),a=e||(process.platform==="darwin"?new cn(o):new ln(ht.join(ht.dirname(o),Vt)));return r.setSecretStorage(a),i.setSecretStorage(a),i.setMcpTokenFilePath(o),await i.loadMcpTokenFile(),{root:t,config:n,api:r,auth:i}}function zt(s,e){let t=s.getProfiles();if(!t.length)throw new Error("\u5C1A\u672A\u6DFB\u52A0\u670D\u52A1\u5668\u8FDE\u63A5\uFF0C\u8BF7\u5148\u6267\u884C microi profile add");if(!e)return t[0];let n=Number(e);if(Number.isInteger(n)&&n>=1&&n<=t.length)return t[n-1];let r=e.toLowerCase(),i=t.filter(o=>o.osClient.toLowerCase()===r||o.label.toLowerCase()===r||`${o.apiBaseUrl}|${o.osClient}`.toLowerCase()===r);if(i.length===0){let o=mt(t).filter(a=>a.mcpName.toLowerCase()===r).map(a=>a.profile);if(o.length===1)return o[0]}if(i.length!==1)throw new Error(`\u65E0\u6CD5\u552F\u4E00\u5B9A\u4F4D\u670D\u52A1\u5668\u8FDE\u63A5\uFF1A${e}`);return i[0]}function Qe(s,e){return!!s.api.getTokenForServer(e.apiBaseUrl,e.osClient,e.osClientType,e.osClientNetwork)}var Rn=B(require("child_process")),Nn=B(require("crypto")),j=B(require("fs")),Xs=B(require("os")),ee=B(require("path"));var yt=B(require("fs")),Js=B(require("os")),Q=B(require("path"));function qs(s={}){let e={...s.env??process.env},t=s.execPath??process.execPath,n=s.home??Js.homedir(),i=(s.platform??process.platform)==="win32",o=i?";":":",a=i?Object.keys(e).find(m=>/^path$/i.test(m))??"Path":"PATH",c=i?"node.exe":"node",l=m=>{try{return yt.statSync(m).isFile()}catch{return!1}},p=m=>{let f=yt.realpathSync(m);if(/\.(?:c?m?js)$/i.test(f)){let y=Q.dirname(Q.dirname(f)),h=(i?[Q.dirname(y),Q.dirname(Q.dirname(y))]:[Q.resolve(y,"../../../bin")]).map(b=>Q.join(b,c)).find(l),S=h??t;return h||/^node(?:\.exe)?$/i.test(Q.basename(S))?delete e.ELECTRON_RUN_AS_NODE:e.ELECTRON_RUN_AS_NODE="1",e[a]=[Q.dirname(S),e[a]??""].filter(Boolean).join(o),{command:S,prefixArgs:[f],env:e,shell:!1}}return e[a]=[Q.dirname(f),e[a]??""].filter(Boolean).join(o),{command:f,prefixArgs:[],env:e,shell:i&&/\.(?:cmd|bat)$/i.test(f)}},d=String(e.MICROI_NPM_PATH??"").trim();if(d){let m=Q.resolve(d);if(!l(m))throw new Error("\u914D\u7F6E\u7684 npm \u5165\u53E3\u4E0D\u5B58\u5728\uFF0C\u8BF7\u68C0\u67E5 MICROI_NPM_PATH\u3002");return p(m)}let u=new Set;for(let m of String(e[a]??"").split(o))Q.isAbsolute(m)&&u.add(m);if(u.add(Q.dirname(t)),u.add(Q.join(n,".microi","nodejs",...i?[]:["bin"])),i){for(let m of[e.ProgramFiles,e["ProgramFiles(x86)"],e.LOCALAPPDATA])m&&Q.isAbsolute(m)&&u.add(Q.join(m,"nodejs"));e.APPDATA&&Q.isAbsolute(e.APPDATA)&&u.add(Q.join(e.APPDATA,"npm")),e.NVM_SYMLINK&&Q.isAbsolute(e.NVM_SYMLINK)&&u.add(e.NVM_SYMLINK)}else{for(let f of["/opt/homebrew/bin","/usr/local/bin","/usr/bin",Q.join(n,".volta","bin")])u.add(f);let m=Q.join(e.NVM_DIR&&Q.isAbsolute(e.NVM_DIR)?e.NVM_DIR:Q.join(n,".nvm"),"versions","node");try{for(let f of yt.readdirSync(m).filter(y=>/^v\d+\.\d+\.\d+$/.test(y)).sort((y,C)=>C.localeCompare(y,void 0,{numeric:!0})).slice(0,8))u.add(Q.join(m,f,"bin"))}catch{}}let g=[];e.npm_execpath&&Q.isAbsolute(e.npm_execpath)&&g.push(e.npm_execpath);for(let m of u)g.push(Q.join(m,"../lib/node_modules/npm/bin/npm-cli.js")),g.push(Q.join(m,"node_modules/npm/bin/npm-cli.js")),g.push(Q.join(m,i?"npm.cmd":"npm"));for(let m of g)if(l(m))return p(m);throw new Error("\u672A\u627E\u5230\u672C\u673A Node.js/npm\uFF1B\u8BF7\u5B89\u88C5 Node.js \u6216\u5728 Microi\u543E\u7801\u8BBE\u7F6E\u4E2D\u5B89\u88C5\u672C\u5730 Node.js\u3002")}var Zs="https://registry.npmjs.org/",Sr="@microi.net/cli",Vo=24*60*60*1e3,Dn=15*60*1e3,ei=30*60*1e3;function Pn(s){return typeof s=="string"&&s.trim().length>0}function Oo(s){if(!s||typeof s!="object"||Array.isArray(s))return!1;let e=s;return Array.isArray(e.profiles)&&e.profiles.some(t=>{if(!t||typeof t!="object"||Array.isArray(t))return!1;let n=t;return Pn(n.apiBaseUrl)&&Pn(n.osClient)})?!0:Pn(e.apiBaseUrl)&&Pn(e.osClient)}function $o(s){try{let e=ee.resolve(s);if(!j.existsSync(e)||!j.statSync(e).isDirectory())return!1;let t=new Set([ee.join(e,Re)]);for(let n of j.readdirSync(e,{withFileTypes:!0}))n.isDirectory()&&n.name.toLowerCase()===Re.toLowerCase()&&t.add(ee.join(e,n.name));for(let n of t){let r=ee.join(n,Xt);if(!j.existsSync(r))continue;let i=j.statSync(r);if(!(!i.isFile()||i.size>2*1024*1024)&&Oo(JSON.parse(j.readFileSync(r,"utf8"))))return!0}}catch{}return!1}function Ct(){let s=ee.resolve(process.env.MICROI_UPDATE_HOME||ee.join(Xs.homedir(),".microi","updater"));return{root:s,status:ee.join(s,"status.json"),log:ee.join(s,"update.log"),lock:ee.join(s,"update.lock")}}function ti(s,e){j.mkdirSync(ee.dirname(s),{recursive:!0});let t=`${s}.${process.pid}.${Date.now()}.${Nn.randomBytes(3).toString("hex")}.tmp`;try{j.writeFileSync(t,e),j.existsSync(s)&&j.rmSync(s,{force:!0}),j.renameSync(t,s)}finally{try{j.existsSync(t)&&j.rmSync(t,{force:!0})}catch{}}}function Bo(s){ti(Ct().status,`${JSON.stringify(s,null,2)}
|
|
1408
|
+
`)}function Lo(){try{return JSON.parse(j.readFileSync(Ct().status,"utf8"))}catch{return}}function ni(s){let e=Ct();j.mkdirSync(e.root,{recursive:!0}),j.appendFileSync(e.log,`[${new Date().toISOString()}] ${s}
|
|
1409
|
+
`,"utf8")}function St(s,e){try{Bo(s)}catch{}if(e)try{ni(e)}catch{}}function In(s){let e=String(s||"").trim().match(/^(\d+)\.(\d+)\.(\d+)$/);return e?e.slice(1).map(Number):void 0}function Uo(s,e){let t=In(s),n=In(e);if(!t||!n)return s.localeCompare(e);for(let r=0;r<3;r+=1)if(t[r]!==n[r])return t[r]-n[r];return 0}var Cr;function ri(s,e,t=12e4,n=!1,r=Cr??process.env){let i=Rn.spawnSync(s,e,{encoding:"utf8",windowsHide:!0,timeout:t,maxBuffer:33554432,shell:n,env:r});return{ok:i.status===0,status:typeof i.status=="number"?i.status:1,stdout:String(i.stdout||""),stderr:[i.error?.message,i.stderr].filter(Boolean).join(`
|
|
1410
|
+
`).trim()}}function br(s,e=12e4){let t=qs();return Cr=t.env,ri(t.command,[...t.prefixArgs,...s],e,t.shell,t.env)}function Ys(){let s=br(["root","--global"],3e4);return s.ok?s.stdout.trim():""}function Qs(s){if(!s)return;let e=ee.join(s,"@microi.net","cli"),t=ee.join(e,"scripts","microi-cli.js"),n=ee.join(e,"package.json");try{let r=JSON.parse(j.readFileSync(n,"utf8")),i=String(r.version||"");return!j.existsSync(t)||!In(i)?void 0:{cliPath:t,version:i}}catch{return}}function Be(s,e,t=12e4){return ri(process.execPath,[s,...e],t,!1,{...Cr??process.env,...process.env.ELECTRON_RUN_AS_NODE?{ELECTRON_RUN_AS_NODE:process.env.ELECTRON_RUN_AS_NODE}:{}})}function jo(){let s=br(["view",Sr,"version","--json","--prefer-online",`--registry=${Zs}`],45e3);if(!s.ok)throw new Error(s.stderr||s.stdout||"npm registry query failed");let e=s.stdout.trim();try{e=String(JSON.parse(e))}catch{e=e.replace(/^"|"$/g,"")}if(!In(e))throw new Error(`npm registry returned invalid version: ${e}`);return e}function Ko(s){return br(["install","--global",`${Sr}@${s}`,`--registry=${Zs}`,"--prefer-online","--no-audit","--no-fund"],5*6e4)}function Pe(s){return(s.stderr||s.stdout||`exit ${s.status}`).trim().slice(0,2e3)}function hr(s){return/(?:未检测到|未找到|not found|cannot find).*Codex|Codex CLI.*(?:未检测到|未找到|not found|cannot find)/i.test(Pe(s))}function yr(s){return/(?:未检测到|未找到|not found|cannot find).*DeepSeek Harness|DeepSeek Harness.*(?:未检测到|未找到|not found|cannot find)/i.test(Pe(s))}function Ho(s){let e=ee.resolve(ee.dirname(s),"..");try{let t=JSON.parse(j.readFileSync(ee.join(e,"package.json"),"utf8"));return t.name!==Sr||t.dsh?.bundle?.patch!=="./cordis.patch.yml"||!j.existsSync(ee.join(e,"cordis.patch.yml"))?void 0:e}catch{return}}function Wo(s,e){if(!s||s.currentVersion!==e)return!0;let t=Date.parse(s.attemptedAt||"");if(!Number.isFinite(t))return!0;let n=Date.now()-t;return s.state==="completed"||s.state==="completed-with-warnings"?n>=Vo:s.state==="scheduled"||s.state==="running"?n>=ei:n>=Dn}function wr(s){let e=Ct(),t=ee.resolve(s.sourceCliPath||process.argv[1]||"");if(!j.existsSync(t))throw new Error(`\u65E0\u6CD5\u627E\u5230 Microi CLI \u66F4\u65B0\u5165\u53E3\uFF1A${t}`);let n=Lo();if(!s.force&&!Wo(n,s.currentVersion))return{scheduled:!1,reason:`recent-${n?.state||"unknown"}`,statusPath:e.status};j.mkdirSync(e.root,{recursive:!0});let r=s.currentVersion.replace(/[^0-9.]/g,"")||"unknown",i=ee.join(e.root,`microi-update-worker-${r}-${process.pid}-${Nn.randomBytes(4).toString("hex")}.js`);ti(i,j.readFileSync(t));let o=new Date().toISOString();St({state:"scheduled",currentVersion:s.currentVersion,workspace:s.workspace,message:"\u540E\u53F0\u66F4\u65B0\u5DF2\u6392\u961F\uFF1B\u5F53\u524D\u5DE5\u4F5C\u7EE7\u7EED\u4F7F\u7528\u73B0\u6709\u7248\u672C\u3002",attemptedAt:o});let a=[i,"update","--worker","--current-version",s.currentVersion,"--source-cli",t,"--json",...s.workspace?["--workspace",ee.resolve(s.workspace)]:[]],c=Rn.spawn(process.execPath,a,{cwd:e.root,detached:!0,windowsHide:!0,stdio:"ignore",env:{...process.env}});return c.once("error",l=>{let p=new Date(Date.now()+Dn).toISOString();St({state:"deferred",currentVersion:s.currentVersion,workspace:s.workspace,message:`\u540E\u53F0\u66F4\u65B0\u8FDB\u7A0B\u6682\u65F6\u65E0\u6CD5\u542F\u52A8\uFF1A${l.message}\uFF1B\u4E0D\u5F71\u54CD\u5F53\u524D\u5DE5\u4F5C\u3002`,attemptedAt:o,nextRetryAt:p})}),c.unref(),{scheduled:!0,reason:"scheduled",statusPath:e.status,workerPid:c.pid}}function Go(){let s=Ct();j.mkdirSync(s.root,{recursive:!0});let e=`${process.pid}-${Date.now()}-${Nn.randomBytes(6).toString("hex")}`;for(let t=0;t<2;t+=1)try{let n=j.openSync(s.lock,"wx");return j.writeFileSync(n,`${JSON.stringify({token:e,pid:process.pid,startedAt:new Date().toISOString()})}
|
|
1411
|
+
`),j.closeSync(n),{token:e,release:()=>{try{JSON.parse(j.readFileSync(s.lock,"utf8")).token===e&&j.rmSync(s.lock,{force:!0})}catch{}}}}catch(n){if((n&&typeof n=="object"?n.code:"")!=="EEXIST")throw n;try{if(Date.now()-j.statSync(s.lock).mtimeMs<ei)return;j.rmSync(s.lock,{force:!0})}catch{}}}function si(s){let e=new Date().toISOString(),t;try{t=Go()}catch(a){let c={state:"deferred",currentVersion:s.currentVersion,workspace:s.workspace,message:`\u65E0\u6CD5\u521B\u5EFA\u540E\u53F0\u66F4\u65B0\u72B6\u6001\u76EE\u5F55\uFF1A${a instanceof Error?a.message:String(a)}\uFF1B\u4E0D\u5F71\u54CD\u5F53\u524D\u6216\u65B0\u5EFA\u5DE5\u4F5C\u3002`,attemptedAt:e,nextRetryAt:new Date(Date.now()+Dn).toISOString()};return St(c,c.message),c}if(!t)return{state:"scheduled",currentVersion:s.currentVersion,workspace:s.workspace,message:"\u5DF2\u6709\u540E\u53F0\u66F4\u65B0\u6B63\u5728\u8FD0\u884C\uFF1B\u5F53\u524D\u5DE5\u4F5C\u7EE7\u7EED\u4F7F\u7528\u73B0\u6709\u7248\u672C\u3002",attemptedAt:e};let n=[],r=s.workspace?ee.resolve(s.workspace):void 0,i=!!r&&$o(r),o=(a,c,l)=>{let p={state:"deferred",currentVersion:s.currentVersion,latestVersion:c,globalVersion:l,workspace:s.workspace,message:`${a}\uFF1B\u5DF2\u5EF6\u540E\u91CD\u8BD5\uFF0C\u4E0D\u5F71\u54CD\u5F53\u524D\u6216\u65B0\u5EFA\u5DE5\u4F5C\u3002`,warnings:n,attemptedAt:e,finishedAt:new Date().toISOString(),nextRetryAt:new Date(Date.now()+Dn).toISOString()};return St(p,p.message),p};try{let a={state:"running",currentVersion:s.currentVersion,workspace:s.workspace,message:"\u6B63\u5728\u540E\u53F0\u68C0\u67E5\u5B98\u65B9\u66F4\u65B0\uFF1B\u5F53\u524D\u5DE5\u4F5C\u4E0D\u7B49\u5F85\u3002",attemptedAt:e,workerPid:process.pid};St(a,`update started from ${s.currentVersion}`);let c;try{c=jo()}catch(h){let S=h instanceof Error?h.message:String(h);return o(/npm 入口不存在|未找到本机 Node.js\/npm/.test(S)?S:`\u65E0\u6CD5\u8BBF\u95EE npm \u5B98\u65B9 registry\uFF1A${S}`)}let l=Ys(),p=Qs(l);if(!p||Uo(p.version,c)<0){let h=Ko(c);if(!h.ok){let S=Pe(h),b=/\b(?:EBUSY|EPERM|EACCES)\b/i.test(S);if(b&&s.sourceCliPath&&j.existsSync(s.sourceCliPath)){let E=Be(s.sourceCliPath,["codex","install","--yes","--json"],18e4);!E.ok&&!hr(E)&&n.push(`\u5F53\u524D Codex \u63D2\u4EF6\u5FEB\u7167\u6682\u672A\u9884\u7F6E\uFF1A${Pe(E)}`);let k=Ho(s.sourceCliPath),I=Be(s.sourceCliPath,["dsh","install",...k?["--source",k]:[],"--json"],5*6e4);if(!I.ok&&!yr(I)&&n.push(`\u5F53\u524D DeepSeek Harness bundle \u5FEB\u7167\u6682\u672A\u9884\u7F6E\uFF1A${Pe(I)}`),i&&r){let w=Be(s.sourceCliPath,["ai","init","--workspace",r,"--json"],18e4);w.ok||n.push(`\u7248\u672C\u9694\u79BB MCP \u5165\u53E3\u6682\u672A\u9884\u7F6E\uFF1A${Pe(w)}`)}}return o(b?"\u5168\u5C40 CLI \u6B63\u88AB\u8FD0\u884C\u4E2D\u7684\u65E7\u4EFB\u52A1\u5360\u7528\uFF0C\u5C06\u5728\u7A7A\u95F2\u540E\u91CD\u8BD5\uFF0C\u7EDD\u4E0D\u7EC8\u6B62\u65E7\u4EFB\u52A1":`\u5168\u5C40 CLI \u81EA\u52A8\u5B89\u88C5\u6682\u672A\u5B8C\u6210\uFF1A${S}`,c,p?.version)}l=Ys(),p=Qs(l)}if(!p)return o("\u5168\u5C40 CLI \u5B89\u88C5\u540E\u672A\u627E\u5230\u53EF\u6267\u884C\u6587\u4EF6",c);let d=p.cliPath,u=Be(d,["codex","install","--yes","--json"],3*6e4),g=u.ok||!hr(u);!u.ok&&g&&n.push(`Codex \u63D2\u4EF6\u7A0D\u540E\u91CD\u8BD5\uFF1A${Pe(u)}`);let m=Be(d,["dsh","install","--json"],5*6e4),f=m.ok||!yr(m);if(!m.ok&&f&&n.push(`DeepSeek Harness bundle \u7A0D\u540E\u91CD\u8BD5\uFF1A${Pe(m)}`),i&&r){let h=Be(d,["ai","init","--workspace",r,"--json"],18e4);h.ok||n.push(`\u5DE5\u4F5C\u533A AI/MCP \u521D\u59CB\u5316\u7A0D\u540E\u91CD\u8BD5\uFF1A${Pe(h)}`);let S=Be(d,["doctor","--workspace",r,"--json"],2*6e4);if(!S.ok)try{ni(`workspace doctor note: ${Pe(S)}`)}catch{}}if(g){let h=Be(d,["codex","status","--json"],6e4);!h.ok&&!hr(h)&&n.push(`Codex \u72B6\u6001\u5F85\u540E\u7EED\u786E\u8BA4\uFF1A${Pe(h)}`)}if(f){let h=Be(d,["dsh","status","--json"],6e4);!h.ok&&!yr(h)&&n.push(`DeepSeek Harness \u72B6\u6001\u5F85\u540E\u7EED\u786E\u8BA4\uFF1A${Pe(h)}`)}let C={state:n.length>0?"completed-with-warnings":"completed",currentVersion:s.currentVersion,latestVersion:c,globalVersion:p.version,workspace:s.workspace,message:n.length>0?"\u6838\u5FC3\u81EA\u52A8\u66F4\u65B0\u5DF2\u5B8C\u6210\uFF0C\u4E2A\u522B\u5BBF\u4E3B\u5C06\u5728\u4E0B\u6B21\u7A7A\u95F2\u6216\u542F\u52A8\u65F6\u7EE7\u7EED\uFF1B\u5F53\u524D\u5DE5\u4F5C\u672A\u88AB\u4E2D\u65AD\u3002":i?"CLI\u3001Codex/DeepSeek Harness \u63D2\u4EF6\u4E0E\u5DE5\u4F5C\u533A AI/MCP \u5DF2\u5728\u540E\u53F0\u66F4\u65B0\uFF1B\u5F53\u524D\u8FDB\u7A0B\u65E0\u9700\u5F3A\u5236\u91CD\u8F7D\u3002":"CLI\u3001Codex/DeepSeek Harness \u63D2\u4EF6\u5DF2\u5728\u540E\u53F0\u66F4\u65B0\uFF1B\u5F53\u524D\u5DE5\u4F5C\u533A\u672A\u914D\u7F6E\u543E\u7801\u670D\u52A1\u5668\uFF0C\u672A\u751F\u6210 AI/MCP \u6587\u4EF6\u3002",warnings:n,attemptedAt:e,finishedAt:new Date().toISOString()};return St(C,`${C.message} latest=${c} global=${p.version}`),C}catch(a){return o(`\u81EA\u52A8\u66F4\u65B0\u51FA\u73B0\u53EF\u6062\u590D\u9519\u8BEF\uFF1A${a instanceof Error?a.message:String(a)}`)}finally{t?.release();let a=ee.resolve(process.argv[1]||""),c=Ct();if(ee.dirname(a)===c.root&&/^microi-update-worker-[\w.-]+\.js$/i.test(ee.basename(a)))try{j.rmSync(a,{force:!0})}catch{}}}function ii(s){if(s.length>32768)throw new Error("\u8FDE\u63A5\u4FE1\u606F\u8FC7\u957F");let e,t;try{if(e=JSON.parse(s.replace(/^\uFEFF/,"").trim()),!e||typeof e!="object"||Array.isArray(e))throw new Error;t=new URL(String(e.ApiBase||""))}catch{throw new Error("\u8FDE\u63A5\u4FE1\u606F\u683C\u5F0F\u65E0\u6548\uFF0C\u8BF7\u91CD\u65B0\u590D\u5236\u5B8C\u6574\u8FDE\u63A5\u4FE1\u606F")}if(!["https:","http:"].includes(t.protocol)||t.username||t.password||t.search||t.hash)throw new Error("ApiBase \u5FC5\u987B\u662F\u65E0\u51ED\u636E\u3001\u65E0\u67E5\u8BE2\u53C2\u6570\u7684 HTTP(S) \u5730\u5740");let n=String(e.OsClient||"").trim(),r=String(e.Token||"").trim().replace(/^Bearer\s+/i,"");if(!/^[A-Za-z0-9_.-]{1,100}$/.test(n)||!/^[\w-]+\.[\w-]+\.[\w-]+$/.test(r))throw new Error("\u8FDE\u63A5\u4FE1\u606F\u7F3A\u5C11\u6709\u6548 OsClient \u6216 Token");let i;try{i=JSON.parse(Buffer.from(r.split(".")[1],"base64url").toString("utf8"))}catch{throw new Error("Token \u683C\u5F0F\u65E0\u6548\uFF0C\u8BF7\u91CD\u65B0\u751F\u6210\u8FDE\u63A5\u4FE1\u606F")}if(!i||typeof i!="object")throw new Error("Token \u683C\u5F0F\u65E0\u6548");if(String(i.OsClient||"").toLowerCase()!==n.toLowerCase()||!Number.isFinite(i.exp)||i.exp*1e3<=Date.now())throw new Error("Token \u5DF2\u8FC7\u671F\u6216\u4E0E\u76EE\u6807\u79DF\u6237\u4E0D\u4E00\u81F4\uFF0C\u8BF7\u91CD\u65B0\u751F\u6210\u8FDE\u63A5\u4FE1\u606F");return{ApiBase:t.href.replace(/\/+$/,""),OsClient:n,Token:r,Did:String(e.Did||"")}}async function oi(s){let e="";for await(let t of s)if(e+=t.toString(),e.length>32768)throw new Error("\u8FDE\u63A5\u4FE1\u606F\u8FC7\u957F");return e}function zo(s){let e=[],t={};for(let n=0;n<s.length;n+=1){let r=s[n];if(!r.startsWith("--")){e.push(r);continue}let[i,o]=r.slice(2).split(/=(.*)/s,2);if(i.startsWith("no-")&&o===void 0){t[i.slice(3)]=!1;continue}if(o!==void 0){t[i]=o;continue}let a=s[n+1];a&&!a.startsWith("--")?(t[i]=a,n+=1):t[i]=!0}return{words:e,options:t}}function ue(s,e){let t=s[e];return typeof t=="string"?t:void 0}function ie(s,e=!1){console.log(e||typeof s!="string"?JSON.stringify(s,null,2):s)}function bt(s,e=""){let t=di.createInterface({input:process.stdin,output:process.stdout});return new Promise(n=>t.question(`${s}${e?` (${e})`:""}: `,r=>{t.close(),n(r.trim()||e)}))}function Jo(s){return!process.stdin.isTTY||!process.stdin.setRawMode?bt(s):new Promise((e,t)=>{let n="";process.stdout.write(`${s}: `),process.stdin.setRawMode(!0),process.stdin.resume();let r=()=>{process.stdin.off("data",i),process.stdin.setRawMode(!1),process.stdin.pause()},i=o=>{let a=o.toString("utf8");if(a===""){r(),t(new Error("\u5DF2\u53D6\u6D88"));return}if(a==="\r"||a===`
|
|
1412
1412
|
`){process.stdout.write(`
|
|
1413
1413
|
`),r(),e(n);return}if(a==="\x7F"||a==="\b"){n&&(n=n.slice(0,-1),process.stdout.write("\b \b"));return}/^[\x20-\x7E\u0080-\uFFFF]+$/.test(a)&&(n+=a,process.stdout.write("*".repeat([...a].length)))};process.stdin.on("data",i)})}function ai(){return`Microi\u543E\u7801 CLI
|
|
1414
1414
|
|
|
@@ -1432,6 +1432,6 @@ require(target);
|
|
|
1432
1432
|
sync status [--scope ...] \u6BD4\u8F83\u672C\u5730\u4E0E\u8FDC\u7AEF\u5DEE\u5F02
|
|
1433
1433
|
doctor \u68C0\u67E5\u8FDE\u63A5\u3001Token\u3001AI \u4E0E MCP \u914D\u7F6E
|
|
1434
1434
|
|
|
1435
|
-
\u901A\u7528\u9009\u9879\uFF1A--workspace <\u76EE\u5F55>\uFF08\u9ED8\u8BA4\u5F53\u524D\u76EE\u5F55\uFF09\u3001--profile <\u5E8F\u53F7/OsClient/\u540D\u79F0/mcpName>\u3001--json`}async function ci(s,e){let t=(ue(e,"api")||await bt("API \u5730\u5740")).replace(/\/+$/,""),n=ue(e,"os-client")||await bt("OsClient");if(!/^https?:\/\//i.test(t))throw new Error("API \u5730\u5740\u5FC5\u987B\u4EE5 http:// \u6216 https:// \u5F00\u5934");if(!n)throw new Error("OsClient \u4E0D\u80FD\u4E3A\u7A7A");let i={label:ue(e,"label")||await bt("\u8FDE\u63A5\u540D\u79F0",n),apiBaseUrl:t,osClient:n,osClientType:ue(e,"type")||"",osClientNetwork:ue(e,"network")||""};return await s.config.addProfile(i),i}function qo(s){return s===!0||s===1||String(s||"").trim().toLowerCase()==="true"}async function li(s,e,t){let n=ue(t,"account")||await bt("\u5E10\u53F7"),r=await Jo("\u5BC6\u7801"),i=await s.auth.getSysConfig(e.apiBaseUrl,e.osClient),o,a,c="";if(qo(i?.EnableCaptcha)){let l=await s.auth.getCaptcha(e.apiBaseUrl,e.osClient);if(!l)throw new Error("\u670D\u52A1\u5668\u8981\u6C42\u9A8C\u8BC1\u7801\uFF0C\u4F46\u9A8C\u8BC1\u7801\u56FE\u7247\u83B7\u53D6\u5931\u8D25");c=le.join(s.config.getSyncRootDir(),".microi-login-captcha.png"),oe.mkdirSync(le.dirname(c),{recursive:!0}),oe.writeFileSync(c,Buffer.from(l.imageBase64.split(",")[1],"base64")),console.log(`\u9A8C\u8BC1\u7801\u56FE\u7247\uFF1A${c}`),o=l.captchaId,a=ue(t,"captcha")||await bt("\u9A8C\u8BC1\u7801")}try{let l=await s.auth.login(n,r,{apiBaseUrl:e.apiBaseUrl,osClient:e.osClient,osClientType:e.osClientType,osClientNetwork:e.osClientNetwork,captchaId:o,captchaValue:a});if(!l.ok)throw new Error(l.msg||"\u767B\u5F55\u5931\u8D25");let p=await s.auth.getSysConfig(e.apiBaseUrl,e.osClient,void 0,!0);p&&await s.config.addProfile({...e,label:String(p.SysShortTitle||p.SysTitle||e.label),sysShortTitle:String(p.SysShortTitle||""),sysTitle:String(p.SysTitle||"")})}finally{c&&oe.existsSync(c)&&oe.rmSync(c,{force:!0})}}async function kr(s,e){yn.getInstance().inject();let t=e?await Tn(s.root):{count:0,names:[]};return{workspace:s.root,syncRoot:s.config.getSyncRootDir(),mcp:t}}async function ui(s,e,t){if(!Ye(s,e))throw new Error("\u8BE5\u8FDE\u63A5\u6CA1\u6709\u53EF\u7528 Token\uFF0C\u8BF7\u5148\u6267\u884C microi auth login");let n=pt.getInstance();(t==="all"||t==="api")&&await n.pullEngines(e),(t==="all"||t==="form")&&(await n.pullEvents(e),await n.pullFields(e)),(t==="all"||t==="module")&&await n.pullMenuButtons(e),(t==="all"||t==="workflow")&&await n.pullWorkflows(e),(t==="all"||t==="schema")&&await n.pullDbSchema(e)}async function Qo(){let{words:s,options:e}=zo(process.argv.slice(2)),t=e.json===!0;if(s[0]==="version"||e.version===!0){let a={package:"@microi.net/cli",version:Ke()};t?ie(a,!0):console.log(a.version);return}if(!s.length||s[0]==="help"||e.help){console.log(ai());return}let[n,r,i]=s;if(n==="update"){let a=ue(e,"current-version")||Ke();if(e.worker===!0){ie(si({currentVersion:a,workspace:ue(e,"workspace"),sourceCliPath:ue(e,"source-cli")}),t);return}try{ie(wr({currentVersion:a,workspace:ue(e,"workspace")||process.cwd(),sourceCliPath:process.argv[1],force:e.force===!0}),t)}catch(c){ie({scheduled:!1,deferred:!0,message:`\u81EA\u52A8\u66F4\u65B0\u6682\u672A\u6295\u9012\uFF0C\u5C06\u5728\u540E\u7EED\u4F7F\u7528\u65F6\u91CD\u8BD5\uFF1B\u4E0D\u5F71\u54CD\u5F53\u524D\u6216\u65B0\u5EFA\u5DE5\u4F5C\uFF1A${c instanceof Error?c.message:String(c)}`},t)}return}if(process.env.MICROI_DISABLE_AUTO_UPDATE!=="1")try{wr({currentVersion:Ke(),workspace:ue(e,"workspace")||process.cwd(),sourceCliPath:process.argv[1]})}catch{}if(n==="plugin"&&r==="path"){let a=le.resolve(__dirname,"..");ie({package:"@microi.net/cli",packageRoot:a,codeBuddyManifest:le.join(a,".codebuddy-plugin","plugin.json"),codeBuddyMarketplace:le.join(a,".codebuddy-plugin","marketplace.json"),workBuddyManifest:le.join(a,".workbuddy-plugin","plugin.json"),workBuddyMarketplace:le.join(a,".workbuddy-plugin","marketplace.json"),dshBundle:le.join(a,"cordis.patch.yml")},t);return}if(n==="codex"){if(r==="status"){let a=xs();ie(a,t),a.ok||(process.exitCode=2);return}if(r==="install"){ie(Fs({force:e.force===!0,marketplaceSource:ue(e,"source")}),t);return}}if(n==="dsh"){let a=ue(e,"profile");if(r==="status"){let c=Ls(a);ie(c,t),c.ok||(process.exitCode=2);return}if(r==="install"){ie(Us({profile:a,source:ue(e,"source"),force:e.force===!0}),t);return}}let o=await zs(ue(e,"workspace")||process.cwd());if(n==="auth"&&r==="import"){if(e["session-stdin"]!==!0)throw new Error("\u8BF7\u4F7F\u7528 --session-stdin\uFF0C\u51ED\u636E\u4E0D\u5F97\u653E\u5165\u547D\u4EE4\u884C\u53C2\u6570");let a=ii(await oi(process.stdin)),c=o.config.getProfiles().find(u=>u.apiBaseUrl.replace(/\/+$/,"")===a.ApiBase&&u.osClient.toLowerCase()===a.OsClient.toLowerCase()),l=c||{label:a.OsClient,apiBaseUrl:a.ApiBase,osClient:a.OsClient,osClientType:"",osClientNetwork:""};o.auth.enableProtectedMcpTokens(l);let p=o.api.getTokenForServer(l.apiBaseUrl,l.osClient,l.osClientType,l.osClientNetwork);try{await o.api.setToken(a.Token,l.apiBaseUrl,l.osClient,l.osClientType,l.osClientNetwork);let u=await o.api.request({method:"POST",path:"/apiengine/platform-current-user",body:{},apiBaseUrl:l.apiBaseUrl,osClient:l.osClient,osClientType:l.osClientType,osClientNetwork:l.osClientNetwork,allowAuthRetry:!1,silent:!0});if(u.Code!==1||!u.Data)throw new Error("\u670D\u52A1\u5668\u672A\u63A5\u53D7\u6B64\u8FDE\u63A5\uFF0C\u8BF7\u91CD\u65B0\u751F\u6210\u5F00\u53D1\u5DE5\u5177 Token");c||await o.config.addProfile(l),await o.auth.writeMcpTokenFile(),ie({imported:!0,ApiBase:l.apiBaseUrl,OsClient:l.osClient,Next:"microi ai init"},t)}catch(u){throw p?await o.api.setToken(p,l.apiBaseUrl,l.osClient,l.osClientType,l.osClientNetwork):await o.api.clearTokenForServer(l.apiBaseUrl,l.osClient,l.osClientType,l.osClientNetwork),u}return}if(n==="profile"){if(r==="list"){let a=mt(o.config.getProfiles()).map(({profile:c,mcpName:l},p)=>({index:p+1,mcpName:l,...c,loggedIn:Ye(o,c)}));ie(a,t);return}if(r==="add"){ie(await ci(o,e),t);return}if(r==="remove"){let a=zt(o.config,i||ue(e,"profile")),c=o.config.getProfiles().findIndex(l=>l.apiBaseUrl===a.apiBaseUrl&&l.osClient===a.osClient);await o.config.removeProfile(c),await o.auth.writeMcpTokenFile(),await Tn(o.root),ie({removed:!0,profile:a},t);return}}if(n==="auth"){let a=zt(o.config,ue(e,"profile"));if(r==="login"){await li(o,a,e),ie({loggedIn:!0,profile:a.osClient},t);return}if(r==="repair"){if(!await o.auth.recoverProfileLogin(a))throw new Error("\u5F53\u524D\u5DE5\u4F5C\u533A\u6CA1\u6709\u8BE5\u8FDE\u63A5\u53EF\u7528\u7684 OS \u52A0\u5BC6\u5E10\u53F7\u5BC6\u7801\uFF0C\u9700\u5148\u6267\u884C\u4E00\u6B21 microi auth login");ie({loggedIn:!0,repaired:!0,profile:a.osClient},t);return}if(r==="status"){ie({loggedIn:Ye(o,a),profile:a},t);return}if(r==="logout"){await o.api.clearTokenForServer(a.apiBaseUrl,a.osClient,a.osClientType,a.osClientNetwork),await o.auth.writeMcpTokenFile(),await Tn(o.root),ie({loggedIn:!1,profile:a.osClient},t);return}}if(n==="ai"&&r==="init"){ie(await kr(o,e.mcp!==!1),t);return}if(n==="mcp"&&r==="init"){let a=await kr(o,!0);ie(a.mcp,t);return}if(n==="init"){let a=o.config.getProfiles()[0];a||(a=await ci(o,e)),Ye(o,a)||await li(o,a,e);let c=await kr(o,!0);e.pull===!0&&await ui(o,a,"all"),ie({initialized:!0,pulled:e.pull===!0,details:c},t);return}if(n==="pull"){let a=zt(o.config,ue(e,"profile")),c=ue(e,"scope")||"all";if(!["all","api","form","module","workflow","schema"].includes(c))throw new Error(`\u4E0D\u652F\u6301\u7684\u62C9\u53D6\u8303\u56F4\uFF1A${c}`);await ui(o,a,c),ie({pulled:!0,scope:c,profile:a.osClient},t);return}if(n==="push"){let a=le.resolve(r||"");if(!oe.existsSync(a))throw new Error(`\u6587\u4EF6\u4E0D\u5B58\u5728\uFF1A${a}`);if(!await pt.getInstance().pushFile(a))throw new Error("\u63A8\u9001\u5931\u8D25\uFF0C\u8BF7\u67E5\u770B\u4E0A\u65B9 Microi \u65E5\u5FD7");ie({pushed:!0,file:a},t);return}if(n==="sync"&&r==="status"){let a=zt(o.config,ue(e,"profile")),c=ue(e,"scope")||"all";if(!["all","api","form","module","workflow"].includes(c))throw new Error(`\u4E0D\u652F\u6301\u7684\u5DEE\u5F02\u8303\u56F4\uFF1A${c}`);let l=await pt.getInstance().checkRemoteDifferences(a,c);ie({profile:a.osClient,scope:c,count:l.length,differences:l},t);return}if(n==="doctor"){let a=o.config.getProfiles(),c=Ke(),l=le.join(o.root,".vscode","mcp.json"),p=[];if(oe.existsSync(l))try{let m=nn(oe.readFileSync(l,"utf-8")),f=m.servers&&typeof m.servers=="object"?m.servers:{};for(let[y,S]of Object.entries(f)){let h=S.env&&typeof S.env=="object"?S.env:{};if(!/^microi(?:_|-|$)/i.test(y)&&typeof h.MICROI_API_URL!="string")continue;let C=Ut(S),b=jt(C,c);p.push({name:y,source:String(h.MICROI_TOOL_SOURCE||"legacy"),version:C||"legacy",compatibility:b>0?"newer-provider-preserved":b<0?"upgrade-available":"compatible"})}}catch(m){p.push({name:"(config)",source:"unknown",version:"unknown",compatibility:`invalid-json: ${m instanceof Error?m.message:String(m)}`})}let u=le.join(o.root,".vscode",".microi-ai-docs-manifest.json"),d="";if(oe.existsSync(u))try{let m=JSON.parse(oe.readFileSync(u,"utf-8"));d=String(m.bundleVersion||"")}catch{d="invalid-json"}let g={ok:a.length>0&&a.some(m=>Ye(o,m)),tool:{source:"cli",version:c},node:process.version,workspace:o.root,syncRoot:o.config.getSyncRootDir(),profiles:a.map(m=>({label:m.label,osClient:m.osClient,apiBaseUrl:m.apiBaseUrl,loggedIn:Ye(o,m)})),files:{agents:oe.existsSync(le.join(o.root,"AGENTS.md")),codeBuddySkill:oe.existsSync(le.join(o.root,".codebuddy","skills","microi","SKILL.md")),qoderSkill:oe.existsSync(le.join(o.root,".qoder","skills","microi","SKILL.md")),comateSkill:oe.existsSync(le.join(o.root,".comate","skills","microi","SKILL.md")),vscodeMcp:oe.existsSync(l),workBuddyMcp:oe.existsSync(le.join(o.root,".workbuddy","mcp.json")),portableMcp:oe.existsSync(le.join(o.root,".mcp.json")),comateMcp:oe.existsSync(le.join(o.root,".comate","mcp.json")),codexMcp:oe.existsSync(le.join(o.root,".codex","config.toml")),tokenFile:oe.existsSync(o.auth.mcpTokenFilePath)},coexistence:{aiBundleVersion:d||"not-initialized",mcpProviders:p}};ie(g,t),g.ok||(process.exitCode=2);return}throw new Error(`\u672A\u77E5\u547D\u4EE4\uFF1A${s.join(" ")}
|
|
1435
|
+
\u901A\u7528\u9009\u9879\uFF1A--workspace <\u76EE\u5F55>\uFF08\u9ED8\u8BA4\u5F53\u524D\u76EE\u5F55\uFF09\u3001--profile <\u5E8F\u53F7/OsClient/\u540D\u79F0/mcpName>\u3001--json`}async function ci(s,e){let t=(ue(e,"api")||await bt("API \u5730\u5740")).replace(/\/+$/,""),n=ue(e,"os-client")||await bt("OsClient");if(!/^https?:\/\//i.test(t))throw new Error("API \u5730\u5740\u5FC5\u987B\u4EE5 http:// \u6216 https:// \u5F00\u5934");if(!n)throw new Error("OsClient \u4E0D\u80FD\u4E3A\u7A7A");let i={label:ue(e,"label")||await bt("\u8FDE\u63A5\u540D\u79F0",n),apiBaseUrl:t,osClient:n,osClientType:ue(e,"type")||"",osClientNetwork:ue(e,"network")||""};return await s.config.addProfile(i),i}function qo(s){return s===!0||s===1||String(s||"").trim().toLowerCase()==="true"}async function li(s,e,t){let n=ue(t,"account")||await bt("\u5E10\u53F7"),r=await Jo("\u5BC6\u7801"),i=await s.auth.getSysConfig(e.apiBaseUrl,e.osClient),o,a,c="";if(qo(i?.EnableCaptcha)){let l=await s.auth.getCaptcha(e.apiBaseUrl,e.osClient);if(!l)throw new Error("\u670D\u52A1\u5668\u8981\u6C42\u9A8C\u8BC1\u7801\uFF0C\u4F46\u9A8C\u8BC1\u7801\u56FE\u7247\u83B7\u53D6\u5931\u8D25");c=le.join(s.config.getSyncRootDir(),".microi-login-captcha.png"),oe.mkdirSync(le.dirname(c),{recursive:!0}),oe.writeFileSync(c,Buffer.from(l.imageBase64.split(",")[1],"base64")),console.log(`\u9A8C\u8BC1\u7801\u56FE\u7247\uFF1A${c}`),o=l.captchaId,a=ue(t,"captcha")||await bt("\u9A8C\u8BC1\u7801")}try{let l=await s.auth.login(n,r,{apiBaseUrl:e.apiBaseUrl,osClient:e.osClient,osClientType:e.osClientType,osClientNetwork:e.osClientNetwork,captchaId:o,captchaValue:a});if(!l.ok)throw new Error(l.msg||"\u767B\u5F55\u5931\u8D25");let p=await s.auth.getSysConfig(e.apiBaseUrl,e.osClient,void 0,!0);p&&await s.config.addProfile({...e,label:String(p.SysShortTitle||p.SysTitle||e.label),sysShortTitle:String(p.SysShortTitle||""),sysTitle:String(p.SysTitle||"")})}finally{c&&oe.existsSync(c)&&oe.rmSync(c,{force:!0})}}async function kr(s,e){yn.getInstance().inject();let t=e?await Tn(s.root):{count:0,names:[]};return{workspace:s.root,syncRoot:s.config.getSyncRootDir(),mcp:t}}async function ui(s,e,t){if(!Qe(s,e))throw new Error("\u8BE5\u8FDE\u63A5\u6CA1\u6709\u53EF\u7528 Token\uFF0C\u8BF7\u5148\u6267\u884C microi auth login");let n=pt.getInstance();(t==="all"||t==="api")&&await n.pullEngines(e),(t==="all"||t==="form")&&(await n.pullEvents(e),await n.pullFields(e)),(t==="all"||t==="module")&&await n.pullMenuButtons(e),(t==="all"||t==="workflow")&&await n.pullWorkflows(e),(t==="all"||t==="schema")&&await n.pullDbSchema(e)}async function Yo(){let{words:s,options:e}=zo(process.argv.slice(2)),t=e.json===!0;if(s[0]==="version"||e.version===!0){let a={package:"@microi.net/cli",version:Ke()};t?ie(a,!0):console.log(a.version);return}if(!s.length||s[0]==="help"||e.help){console.log(ai());return}let[n,r,i]=s;if(n==="update"){let a=ue(e,"current-version")||Ke();if(e.worker===!0){ie(si({currentVersion:a,workspace:ue(e,"workspace"),sourceCliPath:ue(e,"source-cli")}),t);return}try{ie(wr({currentVersion:a,workspace:ue(e,"workspace")||process.cwd(),sourceCliPath:process.argv[1],force:e.force===!0}),t)}catch(c){ie({scheduled:!1,deferred:!0,message:`\u81EA\u52A8\u66F4\u65B0\u6682\u672A\u6295\u9012\uFF0C\u5C06\u5728\u540E\u7EED\u4F7F\u7528\u65F6\u91CD\u8BD5\uFF1B\u4E0D\u5F71\u54CD\u5F53\u524D\u6216\u65B0\u5EFA\u5DE5\u4F5C\uFF1A${c instanceof Error?c.message:String(c)}`},t)}return}if(process.env.MICROI_DISABLE_AUTO_UPDATE!=="1")try{wr({currentVersion:Ke(),workspace:ue(e,"workspace")||process.cwd(),sourceCliPath:process.argv[1]})}catch{}if(n==="plugin"&&r==="path"){let a=le.resolve(__dirname,"..");ie({package:"@microi.net/cli",packageRoot:a,codeBuddyManifest:le.join(a,".codebuddy-plugin","plugin.json"),codeBuddyMarketplace:le.join(a,".codebuddy-plugin","marketplace.json"),workBuddyManifest:le.join(a,".workbuddy-plugin","plugin.json"),workBuddyMarketplace:le.join(a,".workbuddy-plugin","marketplace.json"),dshBundle:le.join(a,"cordis.patch.yml")},t);return}if(n==="codex"){if(r==="status"){let a=xs();ie(a,t),a.ok||(process.exitCode=2);return}if(r==="install"){ie(Fs({force:e.force===!0,marketplaceSource:ue(e,"source")}),t);return}}if(n==="dsh"){let a=ue(e,"profile");if(r==="status"){let c=Ls(a);ie(c,t),c.ok||(process.exitCode=2);return}if(r==="install"){ie(Us({profile:a,source:ue(e,"source"),force:e.force===!0}),t);return}}let o=await zs(ue(e,"workspace")||process.cwd());if(n==="auth"&&r==="import"){if(e["session-stdin"]!==!0)throw new Error("\u8BF7\u4F7F\u7528 --session-stdin\uFF0C\u51ED\u636E\u4E0D\u5F97\u653E\u5165\u547D\u4EE4\u884C\u53C2\u6570");let a=ii(await oi(process.stdin)),c=o.config.getProfiles().find(d=>d.apiBaseUrl.replace(/\/+$/,"")===a.ApiBase&&d.osClient.toLowerCase()===a.OsClient.toLowerCase()),l=c||{label:a.OsClient,apiBaseUrl:a.ApiBase,osClient:a.OsClient,osClientType:"",osClientNetwork:""};o.auth.enableProtectedMcpTokens(l);let p=o.api.getTokenForServer(l.apiBaseUrl,l.osClient,l.osClientType,l.osClientNetwork);try{await o.api.setToken(a.Token,l.apiBaseUrl,l.osClient,l.osClientType,l.osClientNetwork);let d=await o.api.request({method:"POST",path:"/apiengine/platform-current-user",body:{},apiBaseUrl:l.apiBaseUrl,osClient:l.osClient,osClientType:l.osClientType,osClientNetwork:l.osClientNetwork,allowAuthRetry:!1,silent:!0});if(d.Code!==1||!d.Data)throw new Error("\u670D\u52A1\u5668\u672A\u63A5\u53D7\u6B64\u8FDE\u63A5\uFF0C\u8BF7\u91CD\u65B0\u751F\u6210\u5F00\u53D1\u5DE5\u5177 Token");c||await o.config.addProfile(l),await o.auth.writeMcpTokenFile(),ie({imported:!0,ApiBase:l.apiBaseUrl,OsClient:l.osClient,Next:"microi ai init"},t)}catch(d){throw p?await o.api.setToken(p,l.apiBaseUrl,l.osClient,l.osClientType,l.osClientNetwork):await o.api.clearTokenForServer(l.apiBaseUrl,l.osClient,l.osClientType,l.osClientNetwork),d}return}if(n==="profile"){if(r==="list"){let a=mt(o.config.getProfiles()).map(({profile:c,mcpName:l},p)=>({index:p+1,mcpName:l,...c,loggedIn:Qe(o,c)}));ie(a,t);return}if(r==="add"){ie(await ci(o,e),t);return}if(r==="remove"){let a=zt(o.config,i||ue(e,"profile")),c=o.config.getProfiles().findIndex(l=>l.apiBaseUrl===a.apiBaseUrl&&l.osClient===a.osClient);await o.config.removeProfile(c),await o.auth.writeMcpTokenFile(),await Tn(o.root),ie({removed:!0,profile:a},t);return}}if(n==="auth"){let a=zt(o.config,ue(e,"profile"));if(r==="login"){await li(o,a,e),ie({loggedIn:!0,profile:a.osClient},t);return}if(r==="repair"){if(!await o.auth.recoverProfileLogin(a))throw new Error("\u5F53\u524D\u5DE5\u4F5C\u533A\u6CA1\u6709\u8BE5\u8FDE\u63A5\u53EF\u7528\u7684 OS \u52A0\u5BC6\u5E10\u53F7\u5BC6\u7801\uFF0C\u9700\u5148\u6267\u884C\u4E00\u6B21 microi auth login");ie({loggedIn:!0,repaired:!0,profile:a.osClient},t);return}if(r==="status"){ie({loggedIn:Qe(o,a),profile:a},t);return}if(r==="logout"){await o.api.clearTokenForServer(a.apiBaseUrl,a.osClient,a.osClientType,a.osClientNetwork),await o.auth.writeMcpTokenFile(),await Tn(o.root),ie({loggedIn:!1,profile:a.osClient},t);return}}if(n==="ai"&&r==="init"){ie(await kr(o,e.mcp!==!1),t);return}if(n==="mcp"&&r==="init"){let a=await kr(o,!0);ie(a.mcp,t);return}if(n==="init"){let a=o.config.getProfiles()[0];a||(a=await ci(o,e)),Qe(o,a)||await li(o,a,e);let c=await kr(o,!0);e.pull===!0&&await ui(o,a,"all"),ie({initialized:!0,pulled:e.pull===!0,details:c},t);return}if(n==="pull"){let a=zt(o.config,ue(e,"profile")),c=ue(e,"scope")||"all";if(!["all","api","form","module","workflow","schema"].includes(c))throw new Error(`\u4E0D\u652F\u6301\u7684\u62C9\u53D6\u8303\u56F4\uFF1A${c}`);await ui(o,a,c),ie({pulled:!0,scope:c,profile:a.osClient},t);return}if(n==="push"){let a=le.resolve(r||"");if(!oe.existsSync(a))throw new Error(`\u6587\u4EF6\u4E0D\u5B58\u5728\uFF1A${a}`);if(!await pt.getInstance().pushFile(a))throw new Error("\u63A8\u9001\u5931\u8D25\uFF0C\u8BF7\u67E5\u770B\u4E0A\u65B9 Microi \u65E5\u5FD7");ie({pushed:!0,file:a},t);return}if(n==="sync"&&r==="status"){let a=zt(o.config,ue(e,"profile")),c=ue(e,"scope")||"all";if(!["all","api","form","module","workflow"].includes(c))throw new Error(`\u4E0D\u652F\u6301\u7684\u5DEE\u5F02\u8303\u56F4\uFF1A${c}`);let l=await pt.getInstance().checkRemoteDifferences(a,c);ie({profile:a.osClient,scope:c,count:l.length,differences:l},t);return}if(n==="doctor"){let a=o.config.getProfiles(),c=Ke(),l=le.join(o.root,".vscode","mcp.json"),p=[];if(oe.existsSync(l))try{let m=nn(oe.readFileSync(l,"utf-8")),f=m.servers&&typeof m.servers=="object"?m.servers:{};for(let[y,C]of Object.entries(f)){let h=C.env&&typeof C.env=="object"?C.env:{};if(!/^microi(?:_|-|$)/i.test(y)&&typeof h.MICROI_API_URL!="string")continue;let S=Ut(C),b=jt(S,c);p.push({name:y,source:String(h.MICROI_TOOL_SOURCE||"legacy"),version:S||"legacy",compatibility:b>0?"newer-provider-preserved":b<0?"upgrade-available":"compatible"})}}catch(m){p.push({name:"(config)",source:"unknown",version:"unknown",compatibility:`invalid-json: ${m instanceof Error?m.message:String(m)}`})}let d=le.join(o.root,".vscode",".microi-ai-docs-manifest.json"),u="";if(oe.existsSync(d))try{let m=JSON.parse(oe.readFileSync(d,"utf-8"));u=String(m.bundleVersion||"")}catch{u="invalid-json"}let g={ok:a.length>0&&a.some(m=>Qe(o,m)),tool:{source:"cli",version:c},node:process.version,workspace:o.root,syncRoot:o.config.getSyncRootDir(),profiles:a.map(m=>({label:m.label,osClient:m.osClient,apiBaseUrl:m.apiBaseUrl,loggedIn:Qe(o,m)})),files:{agents:oe.existsSync(le.join(o.root,"AGENTS.md")),codeBuddySkill:oe.existsSync(le.join(o.root,".codebuddy","skills","microi","SKILL.md")),qoderSkill:oe.existsSync(le.join(o.root,".qoder","skills","microi","SKILL.md")),comateSkill:oe.existsSync(le.join(o.root,".comate","skills","microi","SKILL.md")),vscodeMcp:oe.existsSync(l),workBuddyMcp:oe.existsSync(le.join(o.root,".workbuddy","mcp.json")),portableMcp:oe.existsSync(le.join(o.root,".mcp.json")),comateMcp:oe.existsSync(le.join(o.root,".comate","mcp.json")),codexMcp:oe.existsSync(le.join(o.root,".codex","config.toml")),tokenFile:oe.existsSync(o.auth.mcpTokenFilePath)},coexistence:{aiBundleVersion:u||"not-initialized",mcpProviders:p}};ie(g,t),g.ok||(process.exitCode=2);return}throw new Error(`\u672A\u77E5\u547D\u4EE4\uFF1A${s.join(" ")}
|
|
1436
1436
|
|
|
1437
|
-
${ai()}`)}
|
|
1437
|
+
${ai()}`)}Yo().catch(s=>{console.error(`Microi CLI: ${s instanceof Error?s.message:String(s)}`),process.exitCode=1});
|