factoriomod-debug 2.0.1 → 2.0.2

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.
@@ -207,7 +207,7 @@ ${e.message}`,void 0,i.handled===!0?!1:"force")}hookConfigurationChanged(e){this
207
207
  `)).on("segment",v=>{v.toString().match(/^Debugger listening/)&&console.log(v.toString()),n.write(v.toString()+`\r
208
208
  `)}),g.on("error",v=>{n.write(`${v.message}\r
209
209
  `)}),g.on("exit",(v,T)=>{j.workspace.fs.delete(Va),c(v??-1)}),o&&g.stdin.write(o),g.stdin.end()})}var Dn=class{constructor(e){this.runner=e}writeEmitter=new j.EventEmitter;onDidWrite=this.writeEmitter.event;closeEmitter=new j.EventEmitter;onDidClose=this.closeEmitter.event;tokensource=new j.CancellationTokenSource;async open(e){let t=this.writeEmitter,r=this.closeEmitter;await this.runner({write:i=>t.fire(i.replace(/\r?\n/g,`\r
210
- `)),close:()=>r.fire()},this.tokensource.token),r.fire()}close(){this.tokensource.cancel()}};var le=mt(require("vscode")),Xa=mt(require("os")),Th=mt(require("path"));var _h;(()=>{"use strict";var n={470:i=>{function o(c){if(typeof c!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(c))}function s(c,u){for(var d,g="",m=0,y=-1,v=0,T=0;T<=c.length;++T){if(T<c.length)d=c.charCodeAt(T);else{if(d===47)break;d=47}if(d===47){if(!(y===T-1||v===1))if(y!==T-1&&v===2){if(g.length<2||m!==2||g.charCodeAt(g.length-1)!==46||g.charCodeAt(g.length-2)!==46){if(g.length>2){var P=g.lastIndexOf("/");if(P!==g.length-1){P===-1?(g="",m=0):m=(g=g.slice(0,P)).length-1-g.lastIndexOf("/"),y=T,v=0;continue}}else if(g.length===2||g.length===1){g="",m=0,y=T,v=0;continue}}u&&(g.length>0?g+="/..":g="..",m=2)}else g.length>0?g+="/"+c.slice(y+1,T):g=c.slice(y+1,T),m=T-y-1;y=T,v=0}else d===46&&v!==-1?++v:v=-1}return g}var a={resolve:function(){for(var c,u="",d=!1,g=arguments.length-1;g>=-1&&!d;g--){var m;g>=0?m=arguments[g]:(c===void 0&&(c=process.cwd()),m=c),o(m),m.length!==0&&(u=m+"/"+u,d=m.charCodeAt(0)===47)}return u=s(u,!d),d?u.length>0?"/"+u:"/":u.length>0?u:"."},normalize:function(c){if(o(c),c.length===0)return".";var u=c.charCodeAt(0)===47,d=c.charCodeAt(c.length-1)===47;return(c=s(c,!u)).length!==0||u||(c="."),c.length>0&&d&&(c+="/"),u?"/"+c:c},isAbsolute:function(c){return o(c),c.length>0&&c.charCodeAt(0)===47},join:function(){if(arguments.length===0)return".";for(var c,u=0;u<arguments.length;++u){var d=arguments[u];o(d),d.length>0&&(c===void 0?c=d:c+="/"+d)}return c===void 0?".":a.normalize(c)},relative:function(c,u){if(o(c),o(u),c===u||(c=a.resolve(c))===(u=a.resolve(u)))return"";for(var d=1;d<c.length&&c.charCodeAt(d)===47;++d);for(var g=c.length,m=g-d,y=1;y<u.length&&u.charCodeAt(y)===47;++y);for(var v=u.length-y,T=m<v?m:v,P=-1,q=0;q<=T;++q){if(q===T){if(v>T){if(u.charCodeAt(y+q)===47)return u.slice(y+q+1);if(q===0)return u.slice(y+q)}else m>T&&(c.charCodeAt(d+q)===47?P=q:q===0&&(P=0));break}var L=c.charCodeAt(d+q);if(L!==u.charCodeAt(y+q))break;L===47&&(P=q)}var N="";for(q=d+P+1;q<=g;++q)q!==g&&c.charCodeAt(q)!==47||(N.length===0?N+="..":N+="/..");return N.length>0?N+u.slice(y+P):(y+=P,u.charCodeAt(y)===47&&++y,u.slice(y))},_makeLong:function(c){return c},dirname:function(c){if(o(c),c.length===0)return".";for(var u=c.charCodeAt(0),d=u===47,g=-1,m=!0,y=c.length-1;y>=1;--y)if((u=c.charCodeAt(y))===47){if(!m){g=y;break}}else m=!1;return g===-1?d?"/":".":d&&g===1?"//":c.slice(0,g)},basename:function(c,u){if(u!==void 0&&typeof u!="string")throw new TypeError('"ext" argument must be a string');o(c);var d,g=0,m=-1,y=!0;if(u!==void 0&&u.length>0&&u.length<=c.length){if(u.length===c.length&&u===c)return"";var v=u.length-1,T=-1;for(d=c.length-1;d>=0;--d){var P=c.charCodeAt(d);if(P===47){if(!y){g=d+1;break}}else T===-1&&(y=!1,T=d+1),v>=0&&(P===u.charCodeAt(v)?--v==-1&&(m=d):(v=-1,m=T))}return g===m?m=T:m===-1&&(m=c.length),c.slice(g,m)}for(d=c.length-1;d>=0;--d)if(c.charCodeAt(d)===47){if(!y){g=d+1;break}}else m===-1&&(y=!1,m=d+1);return m===-1?"":c.slice(g,m)},extname:function(c){o(c);for(var u=-1,d=0,g=-1,m=!0,y=0,v=c.length-1;v>=0;--v){var T=c.charCodeAt(v);if(T!==47)g===-1&&(m=!1,g=v+1),T===46?u===-1?u=v:y!==1&&(y=1):u!==-1&&(y=-1);else if(!m){d=v+1;break}}return u===-1||g===-1||y===0||y===1&&u===g-1&&u===d+1?"":c.slice(u,g)},format:function(c){if(c===null||typeof c!="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof c);return function(u,d){var g=d.dir||d.root,m=d.base||(d.name||"")+(d.ext||"");return g?g===d.root?g+m:g+"/"+m:m}(0,c)},parse:function(c){o(c);var u={root:"",dir:"",base:"",ext:"",name:""};if(c.length===0)return u;var d,g=c.charCodeAt(0),m=g===47;m?(u.root="/",d=1):d=0;for(var y=-1,v=0,T=-1,P=!0,q=c.length-1,L=0;q>=d;--q)if((g=c.charCodeAt(q))!==47)T===-1&&(P=!1,T=q+1),g===46?y===-1?y=q:L!==1&&(L=1):y!==-1&&(L=-1);else if(!P){v=q+1;break}return y===-1||T===-1||L===0||L===1&&y===T-1&&y===v+1?T!==-1&&(u.base=u.name=v===0&&m?c.slice(1,T):c.slice(v,T)):(v===0&&m?(u.name=c.slice(1,y),u.base=c.slice(1,T)):(u.name=c.slice(v,y),u.base=c.slice(v,T)),u.ext=c.slice(y,T)),v>0?u.dir=c.slice(0,v-1):m&&(u.dir="/"),u},sep:"/",delimiter:":",win32:null,posix:null};a.posix=a,i.exports=a}},e={};function t(i){var o=e[i];if(o!==void 0)return o.exports;var s=e[i]={exports:{}};return n[i](s,s.exports,t),s.exports}t.d=(i,o)=>{for(var s in o)t.o(o,s)&&!t.o(i,s)&&Object.defineProperty(i,s,{enumerable:!0,get:o[s]})},t.o=(i,o)=>Object.prototype.hasOwnProperty.call(i,o),t.r=i=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(i,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(i,"__esModule",{value:!0})};var r={};(()=>{let i;t.r(r),t.d(r,{URI:()=>m,Utils:()=>Ne}),typeof process=="object"?i=process.platform==="win32":typeof navigator=="object"&&(i=navigator.userAgent.indexOf("Windows")>=0);let o=/^\w[\w\d+.-]*$/,s=/^\//,a=/^\/\//;function c(U,I){if(!U.scheme&&I)throw new Error(`[UriError]: Scheme is missing: {scheme: "", authority: "${U.authority}", path: "${U.path}", query: "${U.query}", fragment: "${U.fragment}"}`);if(U.scheme&&!o.test(U.scheme))throw new Error("[UriError]: Scheme contains illegal characters.");if(U.path){if(U.authority){if(!s.test(U.path))throw new Error('[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character')}else if(a.test(U.path))throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")')}}let u="",d="/",g=/^(([^:/?#]+?):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;class m{static isUri(I){return I instanceof m||!!I&&typeof I.authority=="string"&&typeof I.fragment=="string"&&typeof I.path=="string"&&typeof I.query=="string"&&typeof I.scheme=="string"&&typeof I.fsPath=="string"&&typeof I.with=="function"&&typeof I.toString=="function"}scheme;authority;path;query;fragment;constructor(I,J,B,pe,ie,oe=!1){typeof I=="object"?(this.scheme=I.scheme||u,this.authority=I.authority||u,this.path=I.path||u,this.query=I.query||u,this.fragment=I.fragment||u):(this.scheme=function(st,be){return st||be?st:"file"}(I,oe),this.authority=J||u,this.path=function(st,be){switch(st){case"https":case"http":case"file":be?be[0]!==d&&(be=d+be):be=d}return be}(this.scheme,B||u),this.query=pe||u,this.fragment=ie||u,c(this,oe))}get fsPath(){return L(this,!1)}with(I){if(!I)return this;let{scheme:J,authority:B,path:pe,query:ie,fragment:oe}=I;return J===void 0?J=this.scheme:J===null&&(J=u),B===void 0?B=this.authority:B===null&&(B=u),pe===void 0?pe=this.path:pe===null&&(pe=u),ie===void 0?ie=this.query:ie===null&&(ie=u),oe===void 0?oe=this.fragment:oe===null&&(oe=u),J===this.scheme&&B===this.authority&&pe===this.path&&ie===this.query&&oe===this.fragment?this:new v(J,B,pe,ie,oe)}static parse(I,J=!1){let B=g.exec(I);return B?new v(B[2]||u,Z(B[4]||u),Z(B[5]||u),Z(B[7]||u),Z(B[9]||u),J):new v(u,u,u,u,u)}static file(I){let J=u;if(i&&(I=I.replace(/\\/g,d)),I[0]===d&&I[1]===d){let B=I.indexOf(d,2);B===-1?(J=I.substring(2),I=d):(J=I.substring(2,B),I=I.substring(B)||d)}return new v("file",J,I,u,u)}static from(I){let J=new v(I.scheme,I.authority,I.path,I.query,I.fragment);return c(J,!0),J}toString(I=!1){return N(this,I)}toJSON(){return this}static revive(I){if(I){if(I instanceof m)return I;{let J=new v(I);return J._formatted=I.external,J._fsPath=I._sep===y?I.fsPath:null,J}}return I}}let y=i?1:void 0;class v extends m{_formatted=null;_fsPath=null;get fsPath(){return this._fsPath||(this._fsPath=L(this,!1)),this._fsPath}toString(I=!1){return I?N(this,!0):(this._formatted||(this._formatted=N(this,!1)),this._formatted)}toJSON(){let I={$mid:1};return this._fsPath&&(I.fsPath=this._fsPath,I._sep=y),this._formatted&&(I.external=this._formatted),this.path&&(I.path=this.path),this.scheme&&(I.scheme=this.scheme),this.authority&&(I.authority=this.authority),this.query&&(I.query=this.query),this.fragment&&(I.fragment=this.fragment),I}}let T={58:"%3A",47:"%2F",63:"%3F",35:"%23",91:"%5B",93:"%5D",64:"%40",33:"%21",36:"%24",38:"%26",39:"%27",40:"%28",41:"%29",42:"%2A",43:"%2B",44:"%2C",59:"%3B",61:"%3D",32:"%20"};function P(U,I,J){let B,pe=-1;for(let ie=0;ie<U.length;ie++){let oe=U.charCodeAt(ie);if(oe>=97&&oe<=122||oe>=65&&oe<=90||oe>=48&&oe<=57||oe===45||oe===46||oe===95||oe===126||I&&oe===47||J&&oe===91||J&&oe===93||J&&oe===58)pe!==-1&&(B+=encodeURIComponent(U.substring(pe,ie)),pe=-1),B!==void 0&&(B+=U.charAt(ie));else{B===void 0&&(B=U.substr(0,ie));let st=T[oe];st!==void 0?(pe!==-1&&(B+=encodeURIComponent(U.substring(pe,ie)),pe=-1),B+=st):pe===-1&&(pe=ie)}}return pe!==-1&&(B+=encodeURIComponent(U.substring(pe))),B!==void 0?B:U}function q(U){let I;for(let J=0;J<U.length;J++){let B=U.charCodeAt(J);B===35||B===63?(I===void 0&&(I=U.substr(0,J)),I+=T[B]):I!==void 0&&(I+=U[J])}return I!==void 0?I:U}function L(U,I){let J;return J=U.authority&&U.path.length>1&&U.scheme==="file"?`//${U.authority}${U.path}`:U.path.charCodeAt(0)===47&&(U.path.charCodeAt(1)>=65&&U.path.charCodeAt(1)<=90||U.path.charCodeAt(1)>=97&&U.path.charCodeAt(1)<=122)&&U.path.charCodeAt(2)===58?I?U.path.substr(1):U.path[1].toLowerCase()+U.path.substr(2):U.path,i&&(J=J.replace(/\//g,"\\")),J}function N(U,I){let J=I?q:P,B="",{scheme:pe,authority:ie,path:oe,query:st,fragment:be}=U;if(pe&&(B+=pe,B+=":"),(ie||pe==="file")&&(B+=d,B+=d),ie){let Re=ie.indexOf("@");if(Re!==-1){let ct=ie.substr(0,Re);ie=ie.substr(Re+1),Re=ct.lastIndexOf(":"),Re===-1?B+=J(ct,!1,!1):(B+=J(ct.substr(0,Re),!1,!1),B+=":",B+=J(ct.substr(Re+1),!1,!0)),B+="@"}ie=ie.toLowerCase(),Re=ie.lastIndexOf(":"),Re===-1?B+=J(ie,!1,!0):(B+=J(ie.substr(0,Re),!1,!0),B+=ie.substr(Re))}if(oe){if(oe.length>=3&&oe.charCodeAt(0)===47&&oe.charCodeAt(2)===58){let Re=oe.charCodeAt(1);Re>=65&&Re<=90&&(oe=`/${String.fromCharCode(Re+32)}:${oe.substr(3)}`)}else if(oe.length>=2&&oe.charCodeAt(1)===58){let Re=oe.charCodeAt(0);Re>=65&&Re<=90&&(oe=`${String.fromCharCode(Re+32)}:${oe.substr(2)}`)}B+=J(oe,!0,!1)}return st&&(B+="?",B+=J(st,!1,!1)),be&&(B+="#",B+=I?be:P(be,!1,!1)),B}function K(U){try{return decodeURIComponent(U)}catch{return U.length>3?U.substr(0,3)+K(U.substr(3)):U}}let te=/(%[0-9A-Za-z][0-9A-Za-z])+/g;function Z(U){return U.match(te)?U.replace(te,I=>K(I)):U}var V=t(470);let ne=V.posix||V,ce="/";var Ne;(function(U){U.joinPath=function(I,...J){return I.with({path:ne.join(I.path,...J)})},U.resolvePath=function(I,...J){let B=I.path,pe=!1;B[0]!==ce&&(B=ce+B,pe=!0);let ie=ne.resolve(B,...J);return pe&&ie[0]===ce&&!I.authority&&(ie=ie.substring(1)),I.with({path:ie})},U.dirname=function(I){if(I.path.length===0||I.path===ce)return I;let J=ne.dirname(I.path);return J.length===1&&J.charCodeAt(0)===46&&(J=""),I.with({path:J})},U.basename=function(I){return ne.basename(I.path)},U.extname=function(I){return ne.extname(I.path)}})(Ne||(Ne={}))})(),_h=r})();var{URI:cr,Utils:$t}=_h;var Io="2.0.1";var cn=require("./fmtk.js"),jn=le.workspace.fs,hS=[{name:"Steam",factorioPath:"C:\\Program Files (x86)\\Steam\\steamapps\\common\\Factorio\\bin\\x64\\factorio.exe"},{name:"System",factorioPath:"C:\\Program Files\\Factorio\\bin\\x64\\factorio.exe"},{name:"Steam",factorioPath:"~/Library/Application Support/Steam/steamapps/common/Factorio/factorio.app/Contents/MacOS/factorio"},{name:"System",factorioPath:"/Applications/factorio.app/Contents/MacOS/factorio"},{name:"Home",factorioPath:"~/.factorio/bin/x64/factorio"}],Fo=class{constructor(e,t){this.context=e;this.output=t;this.bar=le.window.createStatusBarItem("factorio-version",le.StatusBarAlignment.Left,10),this.bar.name="Factorio Version Selector",this.bar.text="Factorio (unselected)",this.bar.command="factorio.selectVersion",this.bar.show(),e.subscriptions.push(this.bar),e.subscriptions.push(le.commands.registerCommand("factorio.selectVersion",this.selectVersionCommand,this)),e.subscriptions.push(le.commands.registerCommand("factorio.checkConfig",this.checkConfigCommand,this)),e.subscriptions.push(le.commands.registerCommand("factorio.disablePrototypeCache",this.disablePrototypeCacheCommand,this)),e.subscriptions.push(le.commands.registerCommand("factorio.disableMouseAutoCapture",this.disableMouseAutoCaptureCommand,this)),this.loadActiveVersion(),e.subscriptions.push(le.workspace.onDidChangeConfiguration(r=>{r.affectsConfiguration("factorio.versions")&&this.loadActiveVersion()}))}bar;async loadActiveVersion(){let e=le.workspace.getConfiguration("factorio"),t=e.get("versions",[]),r=t.find(o=>o.active);if(!r||this._active_version&&this._active_version.is(r))return;let i=await this.tryJsonDocs(r);if(!i){delete r.active,e.update("versions",t);return}this.bar.text=`Factorio ${i.application_version} (${r.name})`,this._active_version=new cn.ActiveFactorioVersion(le.workspace.fs,r,i,le.workspace.workspaceFolders),this.output.info(`Active Factorio version: ${r.name} (${i.application_version})`),this.checkDocs()}async checkConfigCommand(){this.output.info("Check Config:"),this.output.show();let e=await this.getActiveVersion();if(!e){this.output.error("No Active Factorio Version");return}this.output.info("Active Factorio Version:"),this.output.info(`Binary: ${await e.getBinaryVersion().catch(d=>d.toString())}`),this.output.info(`Runtime JSON: ${e.docs.application_version}`),await e.isPrototypeCacheEnabled()&&this.output.warn("Prototype Cache is enabled!"),await e.isMouseAutoCaptureDisabled()&&this.output.info("Mouse Auto Capture is disabled");let t=this.context.storageUri;if(!t){this.output.error("No Workspace");return}try{let d=(await jn.readFile($t.joinPath(t,"sumneko-3rd/factorio/config.json"))).toString(),g=JSON.parse(d);this.output.info(`Library bundle found in ${t.fsPath}, generated from Factorio ${g.factorioVersion} with FMTK ${g.bundleVersion}`);for(let m of await cn.LuaLSAddon.getLuaFiles())try{(await jn.readFile($t.joinPath(t,"sumneko-3rd",m.name))).toString()!==m.content&&this.output.info(`file ${m.name} content mismatch!`)}catch(y){this.output.error(`file ${m.name} ${y}`)}}catch(d){this.output.error(`Missing or damaged library bundle info ${d}`)}let r=le.extensions.getExtension("sumneko.lua");if(!r){this.output.warn("LuaLS (sumneko.lua) not present!");return}this.output.info(`LuaLS ${r.packageJSON.version} ${r.isActive?"Activated":"Not Yet Activated"}`);let i=le.workspace.getConfiguration("Lua"),o=i.get("workspace.userThirdParty");if(!o)this.output.warn("Lua.workspace.userThirdParty not present!");else{let d=$t.joinPath(t,"sumneko-3rd").fsPath;o.includes(d)?this.output.info(`Lua.workspace.userThirdParty: workspace link OK (${d})`):this.output.warn(`Lua.workspace.userThirdParty: workspace link missing! (${d})`);let g=o.filter(m=>m!==d);for(let m of g)m.match(/justarandomgeek\.factoriomod\-debug[\\\/]sumneko\-3rd$/)?this.output.warn(`Lua.workspace.userThirdParty: stale workspace link? (${m})`):this.output.info(`Lua.workspace.userThirdParty: other library (${m})`)}let s=i.get("workspace.checkThirdParty"),a=s==="ApplyInMemory";s===!1||s==="Disable"?this.output.warn(`Lua.workspace.checkThirdParty = ${s}`):this.output.info(`Lua.workspace.checkThirdParty = ${s}`);let c=i.get("workspace.library");if(!c)this.output.warn("Lua.workspace.library not present!");else{let d=cr.file(await e.dataPath()).fsPath;c.includes(d)?this.output.info(`Lua.workspace.library: /data link OK (${d})`):this.output.warn(`Lua.workspace.library: /data link missing! (${d})`);let g=$t.joinPath(t,"sumneko-3rd/factorio/library").fsPath,m=c.find(v=>cr.file(v).fsPath===g);m?a?this.output.warn(`Lua.workspace.library: redundant workspace library link (${m})`):this.output.info(`Lua.workspace.library: workspace library link OK (${m})`):a||this.output.warn(`Lua.workspace.library: workspace library link missing! (${g})`);let y=c.filter(v=>![d,m].includes(v));for(let v of y)v.match(/justarandomgeek\.factoriomod\-debug[\\\/]sumneko\-3rd[\\\/]factorio[\\\/]library$/)?this.output.warn(`Lua.workspace.library: stale workspace link? (${v})`):v.endsWith("data")?this.output.warn(`Lua.workspace.library: stale data link? (${v})`):this.output.info(`Lua.workspace.library: other library (${v})`)}let u=i.get("runtime.plugin");if(!u)a||this.output.warn("Lua.runtime.plugin not present!");else{let d=$t.joinPath(t,"sumneko-3rd/factorio/plugin.lua").fsPath.replace(/[\\]/g,"/");u===d?a?this.output.warn(`Lua.runtime.plugin: redundant workspace link (${u})`):this.output.info(`Lua.runtime.plugin: OK (${u})`):this.output.warn(`Lua.runtime.plugin: wrong plugin? (${u})`)}}async disablePrototypeCacheCommand(){return(await this.getActiveVersion())?.disablePrototypeCache()}async disableMouseAutoCaptureCommand(){return(await this.getActiveVersion())?.disableMouseAutoCapture()}async selectVersionCommand(){if(le.debug.activeDebugSession?.type==="factoriomod"){le.window.showInformationMessage("Cannot select Factorio version while debugging.");return}let e=le.workspace.getConfiguration("factorio"),t=e.get("versions",[]),r=t.map(u=>u.factorioPath),i=(await Promise.all(hS.filter(u=>!r.includes(u.factorioPath)).map(async u=>{try{return(await jn.stat(cr.file((0,cn.substitutePathVariables)(u.factorioPath,le.workspace.workspaceFolders)))).type&le.FileType.File?u:void 0}catch{return}}))).filter(u=>!!u),o=await le.window.showQuickPick(Promise.all([...t.map(async u=>({fv:u,label:u.name,description:(await this.tryJsonDocs(u))?.application_version,detail:u.factorioPath,picked:u.active})),...i.map(async u=>({fv:u,label:`${u.name} (autodetected)`,description:(await this.tryJsonDocs(u))?.application_version,detail:u.factorioPath})),{fv:void 0,label:"Select other version..."}]),{title:"Select Factorio Version"});if(!o)return;let s=o.fv;if(s){let u=!1;try{(await jn.stat(cr.file((0,cn.substitutePathVariables)(s.factorioPath,le.workspace.workspaceFolders)))).type&le.FileType.File&&(u=!0)}catch{}if(!u)switch(await le.window.showErrorMessage("The selected factorio version is no longer present at the specified location","Remove from settings","Cancel")){case"Remove from settings":e.update("versions",t.filter(g=>g!==s));return;default:return}}if(!s){let u=await le.window.showOpenDialog({canSelectFiles:!0,canSelectFolders:!1,openLabel:"Select Factorio binary",filters:Xa.platform()==="win32"?{"":["exe"]}:void 0});if(!u)return;let d=await le.window.showInputBox({prompt:"Display Name for this version",placeHolder:"Enter a display name to be used in the Version Selector for this version"});if(!d)return;s={name:d,factorioPath:u[0].fsPath}}let a;try{a=await this.tryJsonDocs(s,!0)}catch(u){if(await le.window.showErrorMessage(`Unable to read JSON docs: ${u}`,"Select alternate location","Cancel")!=="Select alternate location")return;let d=await le.window.showOpenDialog({canSelectFiles:!0,canSelectFolders:!1,openLabel:"Select Runtime JSON Docs",title:"Select Runtime JSON Docs",filters:{"JSON Docs":["json"]}});if(!d)return;s.docsPath=Th.relative((0,cn.substitutePathVariables)(s.factorioPath,le.workspace.workspaceFolders),d[0].fsPath);try{a=await this.tryJsonDocs(s,!0)}catch(g){le.window.showErrorMessage(`Unable to read JSON docs: ${g}`);return}}t.includes(s)||t.push(s),t.forEach(u=>delete u.active),s.active=!0,e.update("versions",t),this.bar.text=`Factorio ${a.application_version} (${s.name})`;let c=this._active_version;this._active_version=new cn.ActiveFactorioVersion(le.workspace.fs,s,a,le.workspace.workspaceFolders),this.output.info(`Active Factorio version: ${s.name} (${a.application_version})`),await this.generateDocs(c)}_active_version;async getActiveVersion(){return this._active_version||await this.selectVersionCommand(),this._active_version}async tryJsonDocs(e,t){let r=$t.joinPath(cr.file((0,cn.substitutePathVariables)(e.factorioPath,le.workspace.workspaceFolders)),e.docsPath?e.docsPath:Xa.platform()==="darwin"?"../../doc-html/runtime-api.json":"../../../doc-html/runtime-api.json"),i=await le.workspace.getConfiguration("factorio").get("docs",{});try{return new cn.ApiDocGenerator((await jn.readFile(r)).toString(),i)}catch(o){if(!t)return;throw o}}async checkDocs(){let e=await this.getActiveVersion();if(!e)return;let t=this.context.storageUri;if(t)try{let r=(await jn.readFile($t.joinPath(t,"sumneko-3rd/factorio/config.json"))).toString(),i=JSON.parse(r);if(i.factorioVersion!==e.docs.application_version||i.bundleVersion!==Io){this.generateDocs();return}}catch{this.generateDocs();return}}async generateDocs(e){if(!le.workspace.getConfiguration("factorio").get("docs.generateDocs",!0))return;let t=await this.getActiveVersion();if(!t)return;let r=this.context.storageUri;if(!r){le.window.showErrorMessage("Unable to generate docs: no open workspace");return}let i=$t.joinPath(r,"sumneko-3rd");await jn.createDirectory(i);try{await Promise.allSettled([jn.delete($t.joinPath(i,"factorio","library"),{recursive:!0}),jn.delete($t.joinPath(i,"factorio","factorio-plugin"),{recursive:!0})])}catch{}let o=["sumneko-3rd","-d",t.docsPath,"-p",t.protosPath];await Ln({close(){},write(T){}},this.context.asAbsolutePath("./dist/fmtk-cli.js"),o,i.fsPath);let s=le.workspace.getConfiguration("Lua"),a=s.get("workspace.library",[]),c=(T,...P)=>{if(T){let q=$t.joinPath(T,...P),L=a.indexOf(q.fsPath);L!==-1&&a.splice(L,1)}},u=async(T,...P)=>{try{let q=$t.joinPath(T,...P);!a.includes(q.fsPath)&&(await jn.stat(q)).type&le.FileType.Directory&&a.push(q.fsPath)}catch{}},d=le.workspace.getConfiguration("factorio");if(e){let T=cr.file(await e.dataPath());c(T)}if(a.length===0?await s.update("workspace.library",void 0):await s.update("workspace.library",a),d.get("workspace.manageLibraryDataLinks",!0)){let T=cr.file(await t.dataPath());await u(T)}a.length===0?await s.update("workspace.library",void 0):await s.update("workspace.library",a);let g=s.get("workspace.userThirdParty",[]),m=$t.joinPath(r,"sumneko-3rd").fsPath;g=g.filter(T=>!T.includes("justarandomgeek.factoriomod-debug")),await s.update("workspace.userThirdParty",g),g.push(m),await s.update("workspace.userThirdParty",g);let y=s.get("workspace.checkThirdParty");y&&["Ask","Apply","ApplyInMemory"].includes(y)||await s.update("workspace.checkThirdParty","ApplyInMemory");let v=le.extensions.getExtension("sumneko.lua");v&&(v.isActive||await v.activate())}};var Ph=mt(require("vscode"));var de=mt(require("vscode")),Qa=require("console");function Vr(n,e){return isNaN(n)?e:isNaN(e)?n:Math.max(n,e)}var zr=class n{constructor(e=0,t=0){this.timer=e;this.count=t}add(e){return e?new n(this.timer+e.timer,this.count+e.count):this}avg(){return this.timer/this.count}},Oo=class{functions=new Map;lines=new Map;add(e){e.functions.forEach((t,r)=>{this.functions.set(r,t.add(this.functions.get(r)))}),e.lines.forEach((t,r)=>{this.lines.set(r,t.add(this.lines.get(r)))})}max(){let e={func:{timer:0,count:0,average:0},line:{timer:0,count:0,average:0}};return this.functions.forEach(t=>{e.func.timer=Vr(e.func.timer,t.timer),e.func.count=Vr(e.func.count,t.count),e.func.average=Vr(e.func.average,t.avg())}),this.lines.forEach(t=>{e.line.timer=Vr(e.line.timer,t.timer),e.line.count=Vr(e.line.count,t.count),e.line.average=Vr(e.line.average,t.avg())}),e}},Ya=class{totalTime=0;file=new Map},Mo=class n{constructor(e,t,r,i){this.name=e;this.value=t;this.filename=r;this.line=i}children=[];ToStringInner(e){return`${e}${this.name} : ${this.value}
210
+ `)),close:()=>r.fire()},this.tokensource.token),r.fire()}close(){this.tokensource.cancel()}};var le=mt(require("vscode")),Xa=mt(require("os")),Th=mt(require("path"));var _h;(()=>{"use strict";var n={470:i=>{function o(c){if(typeof c!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(c))}function s(c,u){for(var d,g="",m=0,y=-1,v=0,T=0;T<=c.length;++T){if(T<c.length)d=c.charCodeAt(T);else{if(d===47)break;d=47}if(d===47){if(!(y===T-1||v===1))if(y!==T-1&&v===2){if(g.length<2||m!==2||g.charCodeAt(g.length-1)!==46||g.charCodeAt(g.length-2)!==46){if(g.length>2){var P=g.lastIndexOf("/");if(P!==g.length-1){P===-1?(g="",m=0):m=(g=g.slice(0,P)).length-1-g.lastIndexOf("/"),y=T,v=0;continue}}else if(g.length===2||g.length===1){g="",m=0,y=T,v=0;continue}}u&&(g.length>0?g+="/..":g="..",m=2)}else g.length>0?g+="/"+c.slice(y+1,T):g=c.slice(y+1,T),m=T-y-1;y=T,v=0}else d===46&&v!==-1?++v:v=-1}return g}var a={resolve:function(){for(var c,u="",d=!1,g=arguments.length-1;g>=-1&&!d;g--){var m;g>=0?m=arguments[g]:(c===void 0&&(c=process.cwd()),m=c),o(m),m.length!==0&&(u=m+"/"+u,d=m.charCodeAt(0)===47)}return u=s(u,!d),d?u.length>0?"/"+u:"/":u.length>0?u:"."},normalize:function(c){if(o(c),c.length===0)return".";var u=c.charCodeAt(0)===47,d=c.charCodeAt(c.length-1)===47;return(c=s(c,!u)).length!==0||u||(c="."),c.length>0&&d&&(c+="/"),u?"/"+c:c},isAbsolute:function(c){return o(c),c.length>0&&c.charCodeAt(0)===47},join:function(){if(arguments.length===0)return".";for(var c,u=0;u<arguments.length;++u){var d=arguments[u];o(d),d.length>0&&(c===void 0?c=d:c+="/"+d)}return c===void 0?".":a.normalize(c)},relative:function(c,u){if(o(c),o(u),c===u||(c=a.resolve(c))===(u=a.resolve(u)))return"";for(var d=1;d<c.length&&c.charCodeAt(d)===47;++d);for(var g=c.length,m=g-d,y=1;y<u.length&&u.charCodeAt(y)===47;++y);for(var v=u.length-y,T=m<v?m:v,P=-1,q=0;q<=T;++q){if(q===T){if(v>T){if(u.charCodeAt(y+q)===47)return u.slice(y+q+1);if(q===0)return u.slice(y+q)}else m>T&&(c.charCodeAt(d+q)===47?P=q:q===0&&(P=0));break}var L=c.charCodeAt(d+q);if(L!==u.charCodeAt(y+q))break;L===47&&(P=q)}var N="";for(q=d+P+1;q<=g;++q)q!==g&&c.charCodeAt(q)!==47||(N.length===0?N+="..":N+="/..");return N.length>0?N+u.slice(y+P):(y+=P,u.charCodeAt(y)===47&&++y,u.slice(y))},_makeLong:function(c){return c},dirname:function(c){if(o(c),c.length===0)return".";for(var u=c.charCodeAt(0),d=u===47,g=-1,m=!0,y=c.length-1;y>=1;--y)if((u=c.charCodeAt(y))===47){if(!m){g=y;break}}else m=!1;return g===-1?d?"/":".":d&&g===1?"//":c.slice(0,g)},basename:function(c,u){if(u!==void 0&&typeof u!="string")throw new TypeError('"ext" argument must be a string');o(c);var d,g=0,m=-1,y=!0;if(u!==void 0&&u.length>0&&u.length<=c.length){if(u.length===c.length&&u===c)return"";var v=u.length-1,T=-1;for(d=c.length-1;d>=0;--d){var P=c.charCodeAt(d);if(P===47){if(!y){g=d+1;break}}else T===-1&&(y=!1,T=d+1),v>=0&&(P===u.charCodeAt(v)?--v==-1&&(m=d):(v=-1,m=T))}return g===m?m=T:m===-1&&(m=c.length),c.slice(g,m)}for(d=c.length-1;d>=0;--d)if(c.charCodeAt(d)===47){if(!y){g=d+1;break}}else m===-1&&(y=!1,m=d+1);return m===-1?"":c.slice(g,m)},extname:function(c){o(c);for(var u=-1,d=0,g=-1,m=!0,y=0,v=c.length-1;v>=0;--v){var T=c.charCodeAt(v);if(T!==47)g===-1&&(m=!1,g=v+1),T===46?u===-1?u=v:y!==1&&(y=1):u!==-1&&(y=-1);else if(!m){d=v+1;break}}return u===-1||g===-1||y===0||y===1&&u===g-1&&u===d+1?"":c.slice(u,g)},format:function(c){if(c===null||typeof c!="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof c);return function(u,d){var g=d.dir||d.root,m=d.base||(d.name||"")+(d.ext||"");return g?g===d.root?g+m:g+"/"+m:m}(0,c)},parse:function(c){o(c);var u={root:"",dir:"",base:"",ext:"",name:""};if(c.length===0)return u;var d,g=c.charCodeAt(0),m=g===47;m?(u.root="/",d=1):d=0;for(var y=-1,v=0,T=-1,P=!0,q=c.length-1,L=0;q>=d;--q)if((g=c.charCodeAt(q))!==47)T===-1&&(P=!1,T=q+1),g===46?y===-1?y=q:L!==1&&(L=1):y!==-1&&(L=-1);else if(!P){v=q+1;break}return y===-1||T===-1||L===0||L===1&&y===T-1&&y===v+1?T!==-1&&(u.base=u.name=v===0&&m?c.slice(1,T):c.slice(v,T)):(v===0&&m?(u.name=c.slice(1,y),u.base=c.slice(1,T)):(u.name=c.slice(v,y),u.base=c.slice(v,T)),u.ext=c.slice(y,T)),v>0?u.dir=c.slice(0,v-1):m&&(u.dir="/"),u},sep:"/",delimiter:":",win32:null,posix:null};a.posix=a,i.exports=a}},e={};function t(i){var o=e[i];if(o!==void 0)return o.exports;var s=e[i]={exports:{}};return n[i](s,s.exports,t),s.exports}t.d=(i,o)=>{for(var s in o)t.o(o,s)&&!t.o(i,s)&&Object.defineProperty(i,s,{enumerable:!0,get:o[s]})},t.o=(i,o)=>Object.prototype.hasOwnProperty.call(i,o),t.r=i=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(i,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(i,"__esModule",{value:!0})};var r={};(()=>{let i;t.r(r),t.d(r,{URI:()=>m,Utils:()=>Ne}),typeof process=="object"?i=process.platform==="win32":typeof navigator=="object"&&(i=navigator.userAgent.indexOf("Windows")>=0);let o=/^\w[\w\d+.-]*$/,s=/^\//,a=/^\/\//;function c(U,I){if(!U.scheme&&I)throw new Error(`[UriError]: Scheme is missing: {scheme: "", authority: "${U.authority}", path: "${U.path}", query: "${U.query}", fragment: "${U.fragment}"}`);if(U.scheme&&!o.test(U.scheme))throw new Error("[UriError]: Scheme contains illegal characters.");if(U.path){if(U.authority){if(!s.test(U.path))throw new Error('[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character')}else if(a.test(U.path))throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")')}}let u="",d="/",g=/^(([^:/?#]+?):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;class m{static isUri(I){return I instanceof m||!!I&&typeof I.authority=="string"&&typeof I.fragment=="string"&&typeof I.path=="string"&&typeof I.query=="string"&&typeof I.scheme=="string"&&typeof I.fsPath=="string"&&typeof I.with=="function"&&typeof I.toString=="function"}scheme;authority;path;query;fragment;constructor(I,J,B,pe,ie,oe=!1){typeof I=="object"?(this.scheme=I.scheme||u,this.authority=I.authority||u,this.path=I.path||u,this.query=I.query||u,this.fragment=I.fragment||u):(this.scheme=function(st,be){return st||be?st:"file"}(I,oe),this.authority=J||u,this.path=function(st,be){switch(st){case"https":case"http":case"file":be?be[0]!==d&&(be=d+be):be=d}return be}(this.scheme,B||u),this.query=pe||u,this.fragment=ie||u,c(this,oe))}get fsPath(){return L(this,!1)}with(I){if(!I)return this;let{scheme:J,authority:B,path:pe,query:ie,fragment:oe}=I;return J===void 0?J=this.scheme:J===null&&(J=u),B===void 0?B=this.authority:B===null&&(B=u),pe===void 0?pe=this.path:pe===null&&(pe=u),ie===void 0?ie=this.query:ie===null&&(ie=u),oe===void 0?oe=this.fragment:oe===null&&(oe=u),J===this.scheme&&B===this.authority&&pe===this.path&&ie===this.query&&oe===this.fragment?this:new v(J,B,pe,ie,oe)}static parse(I,J=!1){let B=g.exec(I);return B?new v(B[2]||u,Z(B[4]||u),Z(B[5]||u),Z(B[7]||u),Z(B[9]||u),J):new v(u,u,u,u,u)}static file(I){let J=u;if(i&&(I=I.replace(/\\/g,d)),I[0]===d&&I[1]===d){let B=I.indexOf(d,2);B===-1?(J=I.substring(2),I=d):(J=I.substring(2,B),I=I.substring(B)||d)}return new v("file",J,I,u,u)}static from(I){let J=new v(I.scheme,I.authority,I.path,I.query,I.fragment);return c(J,!0),J}toString(I=!1){return N(this,I)}toJSON(){return this}static revive(I){if(I){if(I instanceof m)return I;{let J=new v(I);return J._formatted=I.external,J._fsPath=I._sep===y?I.fsPath:null,J}}return I}}let y=i?1:void 0;class v extends m{_formatted=null;_fsPath=null;get fsPath(){return this._fsPath||(this._fsPath=L(this,!1)),this._fsPath}toString(I=!1){return I?N(this,!0):(this._formatted||(this._formatted=N(this,!1)),this._formatted)}toJSON(){let I={$mid:1};return this._fsPath&&(I.fsPath=this._fsPath,I._sep=y),this._formatted&&(I.external=this._formatted),this.path&&(I.path=this.path),this.scheme&&(I.scheme=this.scheme),this.authority&&(I.authority=this.authority),this.query&&(I.query=this.query),this.fragment&&(I.fragment=this.fragment),I}}let T={58:"%3A",47:"%2F",63:"%3F",35:"%23",91:"%5B",93:"%5D",64:"%40",33:"%21",36:"%24",38:"%26",39:"%27",40:"%28",41:"%29",42:"%2A",43:"%2B",44:"%2C",59:"%3B",61:"%3D",32:"%20"};function P(U,I,J){let B,pe=-1;for(let ie=0;ie<U.length;ie++){let oe=U.charCodeAt(ie);if(oe>=97&&oe<=122||oe>=65&&oe<=90||oe>=48&&oe<=57||oe===45||oe===46||oe===95||oe===126||I&&oe===47||J&&oe===91||J&&oe===93||J&&oe===58)pe!==-1&&(B+=encodeURIComponent(U.substring(pe,ie)),pe=-1),B!==void 0&&(B+=U.charAt(ie));else{B===void 0&&(B=U.substr(0,ie));let st=T[oe];st!==void 0?(pe!==-1&&(B+=encodeURIComponent(U.substring(pe,ie)),pe=-1),B+=st):pe===-1&&(pe=ie)}}return pe!==-1&&(B+=encodeURIComponent(U.substring(pe))),B!==void 0?B:U}function q(U){let I;for(let J=0;J<U.length;J++){let B=U.charCodeAt(J);B===35||B===63?(I===void 0&&(I=U.substr(0,J)),I+=T[B]):I!==void 0&&(I+=U[J])}return I!==void 0?I:U}function L(U,I){let J;return J=U.authority&&U.path.length>1&&U.scheme==="file"?`//${U.authority}${U.path}`:U.path.charCodeAt(0)===47&&(U.path.charCodeAt(1)>=65&&U.path.charCodeAt(1)<=90||U.path.charCodeAt(1)>=97&&U.path.charCodeAt(1)<=122)&&U.path.charCodeAt(2)===58?I?U.path.substr(1):U.path[1].toLowerCase()+U.path.substr(2):U.path,i&&(J=J.replace(/\//g,"\\")),J}function N(U,I){let J=I?q:P,B="",{scheme:pe,authority:ie,path:oe,query:st,fragment:be}=U;if(pe&&(B+=pe,B+=":"),(ie||pe==="file")&&(B+=d,B+=d),ie){let Re=ie.indexOf("@");if(Re!==-1){let ct=ie.substr(0,Re);ie=ie.substr(Re+1),Re=ct.lastIndexOf(":"),Re===-1?B+=J(ct,!1,!1):(B+=J(ct.substr(0,Re),!1,!1),B+=":",B+=J(ct.substr(Re+1),!1,!0)),B+="@"}ie=ie.toLowerCase(),Re=ie.lastIndexOf(":"),Re===-1?B+=J(ie,!1,!0):(B+=J(ie.substr(0,Re),!1,!0),B+=ie.substr(Re))}if(oe){if(oe.length>=3&&oe.charCodeAt(0)===47&&oe.charCodeAt(2)===58){let Re=oe.charCodeAt(1);Re>=65&&Re<=90&&(oe=`/${String.fromCharCode(Re+32)}:${oe.substr(3)}`)}else if(oe.length>=2&&oe.charCodeAt(1)===58){let Re=oe.charCodeAt(0);Re>=65&&Re<=90&&(oe=`${String.fromCharCode(Re+32)}:${oe.substr(2)}`)}B+=J(oe,!0,!1)}return st&&(B+="?",B+=J(st,!1,!1)),be&&(B+="#",B+=I?be:P(be,!1,!1)),B}function K(U){try{return decodeURIComponent(U)}catch{return U.length>3?U.substr(0,3)+K(U.substr(3)):U}}let te=/(%[0-9A-Za-z][0-9A-Za-z])+/g;function Z(U){return U.match(te)?U.replace(te,I=>K(I)):U}var V=t(470);let ne=V.posix||V,ce="/";var Ne;(function(U){U.joinPath=function(I,...J){return I.with({path:ne.join(I.path,...J)})},U.resolvePath=function(I,...J){let B=I.path,pe=!1;B[0]!==ce&&(B=ce+B,pe=!0);let ie=ne.resolve(B,...J);return pe&&ie[0]===ce&&!I.authority&&(ie=ie.substring(1)),I.with({path:ie})},U.dirname=function(I){if(I.path.length===0||I.path===ce)return I;let J=ne.dirname(I.path);return J.length===1&&J.charCodeAt(0)===46&&(J=""),I.with({path:J})},U.basename=function(I){return ne.basename(I.path)},U.extname=function(I){return ne.extname(I.path)}})(Ne||(Ne={}))})(),_h=r})();var{URI:cr,Utils:$t}=_h;var Io="2.0.2";var cn=require("./fmtk.js"),jn=le.workspace.fs,hS=[{name:"Steam",factorioPath:"C:\\Program Files (x86)\\Steam\\steamapps\\common\\Factorio\\bin\\x64\\factorio.exe"},{name:"System",factorioPath:"C:\\Program Files\\Factorio\\bin\\x64\\factorio.exe"},{name:"Steam",factorioPath:"~/Library/Application Support/Steam/steamapps/common/Factorio/factorio.app/Contents/MacOS/factorio"},{name:"System",factorioPath:"/Applications/factorio.app/Contents/MacOS/factorio"},{name:"Home",factorioPath:"~/.factorio/bin/x64/factorio"}],Fo=class{constructor(e,t){this.context=e;this.output=t;this.bar=le.window.createStatusBarItem("factorio-version",le.StatusBarAlignment.Left,10),this.bar.name="Factorio Version Selector",this.bar.text="Factorio (unselected)",this.bar.command="factorio.selectVersion",this.bar.show(),e.subscriptions.push(this.bar),e.subscriptions.push(le.commands.registerCommand("factorio.selectVersion",this.selectVersionCommand,this)),e.subscriptions.push(le.commands.registerCommand("factorio.checkConfig",this.checkConfigCommand,this)),e.subscriptions.push(le.commands.registerCommand("factorio.disablePrototypeCache",this.disablePrototypeCacheCommand,this)),e.subscriptions.push(le.commands.registerCommand("factorio.disableMouseAutoCapture",this.disableMouseAutoCaptureCommand,this)),this.loadActiveVersion(),e.subscriptions.push(le.workspace.onDidChangeConfiguration(r=>{r.affectsConfiguration("factorio.versions")&&this.loadActiveVersion()}))}bar;async loadActiveVersion(){let e=le.workspace.getConfiguration("factorio"),t=e.get("versions",[]),r=t.find(o=>o.active);if(!r||this._active_version&&this._active_version.is(r))return;let i=await this.tryJsonDocs(r);if(!i){delete r.active,e.update("versions",t);return}this.bar.text=`Factorio ${i.application_version} (${r.name})`,this._active_version=new cn.ActiveFactorioVersion(le.workspace.fs,r,i,le.workspace.workspaceFolders),this.output.info(`Active Factorio version: ${r.name} (${i.application_version})`),this.checkDocs()}async checkConfigCommand(){this.output.info("Check Config:"),this.output.show();let e=await this.getActiveVersion();if(!e){this.output.error("No Active Factorio Version");return}this.output.info("Active Factorio Version:"),this.output.info(`Binary: ${await e.getBinaryVersion().catch(d=>d.toString())}`),this.output.info(`Runtime JSON: ${e.docs.application_version}`),await e.isPrototypeCacheEnabled()&&this.output.warn("Prototype Cache is enabled!"),await e.isMouseAutoCaptureDisabled()&&this.output.info("Mouse Auto Capture is disabled");let t=this.context.storageUri;if(!t){this.output.error("No Workspace");return}try{let d=(await jn.readFile($t.joinPath(t,"sumneko-3rd/factorio/config.json"))).toString(),g=JSON.parse(d);this.output.info(`Library bundle found in ${t.fsPath}, generated from Factorio ${g.factorioVersion} with FMTK ${g.bundleVersion}`);for(let m of await cn.LuaLSAddon.getLuaFiles())try{(await jn.readFile($t.joinPath(t,"sumneko-3rd",m.name))).toString()!==m.content&&this.output.info(`file ${m.name} content mismatch!`)}catch(y){this.output.error(`file ${m.name} ${y}`)}}catch(d){this.output.error(`Missing or damaged library bundle info ${d}`)}let r=le.extensions.getExtension("sumneko.lua");if(!r){this.output.warn("LuaLS (sumneko.lua) not present!");return}this.output.info(`LuaLS ${r.packageJSON.version} ${r.isActive?"Activated":"Not Yet Activated"}`);let i=le.workspace.getConfiguration("Lua"),o=i.get("workspace.userThirdParty");if(!o)this.output.warn("Lua.workspace.userThirdParty not present!");else{let d=$t.joinPath(t,"sumneko-3rd").fsPath;o.includes(d)?this.output.info(`Lua.workspace.userThirdParty: workspace link OK (${d})`):this.output.warn(`Lua.workspace.userThirdParty: workspace link missing! (${d})`);let g=o.filter(m=>m!==d);for(let m of g)m.match(/justarandomgeek\.factoriomod\-debug[\\\/]sumneko\-3rd$/)?this.output.warn(`Lua.workspace.userThirdParty: stale workspace link? (${m})`):this.output.info(`Lua.workspace.userThirdParty: other library (${m})`)}let s=i.get("workspace.checkThirdParty"),a=s==="ApplyInMemory";s===!1||s==="Disable"?this.output.warn(`Lua.workspace.checkThirdParty = ${s}`):this.output.info(`Lua.workspace.checkThirdParty = ${s}`);let c=i.get("workspace.library");if(!c)this.output.warn("Lua.workspace.library not present!");else{let d=cr.file(await e.dataPath()).fsPath;c.includes(d)?this.output.info(`Lua.workspace.library: /data link OK (${d})`):this.output.warn(`Lua.workspace.library: /data link missing! (${d})`);let g=$t.joinPath(t,"sumneko-3rd/factorio/library").fsPath,m=c.find(v=>cr.file(v).fsPath===g);m?a?this.output.warn(`Lua.workspace.library: redundant workspace library link (${m})`):this.output.info(`Lua.workspace.library: workspace library link OK (${m})`):a||this.output.warn(`Lua.workspace.library: workspace library link missing! (${g})`);let y=c.filter(v=>![d,m].includes(v));for(let v of y)v.match(/justarandomgeek\.factoriomod\-debug[\\\/]sumneko\-3rd[\\\/]factorio[\\\/]library$/)?this.output.warn(`Lua.workspace.library: stale workspace link? (${v})`):v.endsWith("data")?this.output.warn(`Lua.workspace.library: stale data link? (${v})`):this.output.info(`Lua.workspace.library: other library (${v})`)}let u=i.get("runtime.plugin");if(!u)a||this.output.warn("Lua.runtime.plugin not present!");else{let d=$t.joinPath(t,"sumneko-3rd/factorio/plugin.lua").fsPath.replace(/[\\]/g,"/");u===d?a?this.output.warn(`Lua.runtime.plugin: redundant workspace link (${u})`):this.output.info(`Lua.runtime.plugin: OK (${u})`):this.output.warn(`Lua.runtime.plugin: wrong plugin? (${u})`)}}async disablePrototypeCacheCommand(){return(await this.getActiveVersion())?.disablePrototypeCache()}async disableMouseAutoCaptureCommand(){return(await this.getActiveVersion())?.disableMouseAutoCapture()}async selectVersionCommand(){if(le.debug.activeDebugSession?.type==="factoriomod"){le.window.showInformationMessage("Cannot select Factorio version while debugging.");return}let e=le.workspace.getConfiguration("factorio"),t=e.get("versions",[]),r=t.map(u=>u.factorioPath),i=(await Promise.all(hS.filter(u=>!r.includes(u.factorioPath)).map(async u=>{try{return(await jn.stat(cr.file((0,cn.substitutePathVariables)(u.factorioPath,le.workspace.workspaceFolders)))).type&le.FileType.File?u:void 0}catch{return}}))).filter(u=>!!u),o=await le.window.showQuickPick(Promise.all([...t.map(async u=>({fv:u,label:u.name,description:(await this.tryJsonDocs(u))?.application_version,detail:u.factorioPath,picked:u.active})),...i.map(async u=>({fv:u,label:`${u.name} (autodetected)`,description:(await this.tryJsonDocs(u))?.application_version,detail:u.factorioPath})),{fv:void 0,label:"Select other version..."}]),{title:"Select Factorio Version"});if(!o)return;let s=o.fv;if(s){let u=!1;try{(await jn.stat(cr.file((0,cn.substitutePathVariables)(s.factorioPath,le.workspace.workspaceFolders)))).type&le.FileType.File&&(u=!0)}catch{}if(!u)switch(await le.window.showErrorMessage("The selected factorio version is no longer present at the specified location","Remove from settings","Cancel")){case"Remove from settings":e.update("versions",t.filter(g=>g!==s));return;default:return}}if(!s){let u=await le.window.showOpenDialog({canSelectFiles:!0,canSelectFolders:!1,openLabel:"Select Factorio binary",filters:Xa.platform()==="win32"?{"":["exe"]}:void 0});if(!u)return;let d=await le.window.showInputBox({prompt:"Display Name for this version",placeHolder:"Enter a display name to be used in the Version Selector for this version"});if(!d)return;s={name:d,factorioPath:u[0].fsPath}}let a;try{a=await this.tryJsonDocs(s,!0)}catch(u){if(await le.window.showErrorMessage(`Unable to read JSON docs: ${u}`,"Select alternate location","Cancel")!=="Select alternate location")return;let d=await le.window.showOpenDialog({canSelectFiles:!0,canSelectFolders:!1,openLabel:"Select Runtime JSON Docs",title:"Select Runtime JSON Docs",filters:{"JSON Docs":["json"]}});if(!d)return;s.docsPath=Th.relative((0,cn.substitutePathVariables)(s.factorioPath,le.workspace.workspaceFolders),d[0].fsPath);try{a=await this.tryJsonDocs(s,!0)}catch(g){le.window.showErrorMessage(`Unable to read JSON docs: ${g}`);return}}t.includes(s)||t.push(s),t.forEach(u=>delete u.active),s.active=!0,e.update("versions",t),this.bar.text=`Factorio ${a.application_version} (${s.name})`;let c=this._active_version;this._active_version=new cn.ActiveFactorioVersion(le.workspace.fs,s,a,le.workspace.workspaceFolders),this.output.info(`Active Factorio version: ${s.name} (${a.application_version})`),await this.generateDocs(c)}_active_version;async getActiveVersion(){return this._active_version||await this.selectVersionCommand(),this._active_version}async tryJsonDocs(e,t){let r=$t.joinPath(cr.file((0,cn.substitutePathVariables)(e.factorioPath,le.workspace.workspaceFolders)),e.docsPath?e.docsPath:Xa.platform()==="darwin"?"../../doc-html/runtime-api.json":"../../../doc-html/runtime-api.json"),i=await le.workspace.getConfiguration("factorio").get("docs",{});try{return new cn.ApiDocGenerator((await jn.readFile(r)).toString(),i)}catch(o){if(!t)return;throw o}}async checkDocs(){let e=await this.getActiveVersion();if(!e)return;let t=this.context.storageUri;if(t)try{let r=(await jn.readFile($t.joinPath(t,"sumneko-3rd/factorio/config.json"))).toString(),i=JSON.parse(r);if(i.factorioVersion!==e.docs.application_version||i.bundleVersion!==Io){this.generateDocs();return}}catch{this.generateDocs();return}}async generateDocs(e){if(!le.workspace.getConfiguration("factorio").get("docs.generateDocs",!0))return;let t=await this.getActiveVersion();if(!t)return;let r=this.context.storageUri;if(!r){le.window.showErrorMessage("Unable to generate docs: no open workspace");return}let i=$t.joinPath(r,"sumneko-3rd");await jn.createDirectory(i);try{await Promise.allSettled([jn.delete($t.joinPath(i,"factorio","library"),{recursive:!0}),jn.delete($t.joinPath(i,"factorio","factorio-plugin"),{recursive:!0})])}catch{}let o=["sumneko-3rd","-d",t.docsPath,"-p",t.protosPath];await Ln({close(){},write(T){}},this.context.asAbsolutePath("./dist/fmtk-cli.js"),o,i.fsPath);let s=le.workspace.getConfiguration("Lua"),a=s.get("workspace.library",[]),c=(T,...P)=>{if(T){let q=$t.joinPath(T,...P),L=a.indexOf(q.fsPath);L!==-1&&a.splice(L,1)}},u=async(T,...P)=>{try{let q=$t.joinPath(T,...P);!a.includes(q.fsPath)&&(await jn.stat(q)).type&le.FileType.Directory&&a.push(q.fsPath)}catch{}},d=le.workspace.getConfiguration("factorio");if(e){let T=cr.file(await e.dataPath());c(T)}if(a.length===0?await s.update("workspace.library",void 0):await s.update("workspace.library",a),d.get("workspace.manageLibraryDataLinks",!0)){let T=cr.file(await t.dataPath());await u(T)}a.length===0?await s.update("workspace.library",void 0):await s.update("workspace.library",a);let g=s.get("workspace.userThirdParty",[]),m=$t.joinPath(r,"sumneko-3rd").fsPath;g=g.filter(T=>!T.includes("justarandomgeek.factoriomod-debug")),await s.update("workspace.userThirdParty",g),g.push(m),await s.update("workspace.userThirdParty",g);let y=s.get("workspace.checkThirdParty");y&&["Ask","Apply","ApplyInMemory"].includes(y)||await s.update("workspace.checkThirdParty","ApplyInMemory");let v=le.extensions.getExtension("sumneko.lua");v&&(v.isActive||await v.activate())}};var Ph=mt(require("vscode"));var de=mt(require("vscode")),Qa=require("console");function Vr(n,e){return isNaN(n)?e:isNaN(e)?n:Math.max(n,e)}var zr=class n{constructor(e=0,t=0){this.timer=e;this.count=t}add(e){return e?new n(this.timer+e.timer,this.count+e.count):this}avg(){return this.timer/this.count}},Oo=class{functions=new Map;lines=new Map;add(e){e.functions.forEach((t,r)=>{this.functions.set(r,t.add(this.functions.get(r)))}),e.lines.forEach((t,r)=>{this.lines.set(r,t.add(this.lines.get(r)))})}max(){let e={func:{timer:0,count:0,average:0},line:{timer:0,count:0,average:0}};return this.functions.forEach(t=>{e.func.timer=Vr(e.func.timer,t.timer),e.func.count=Vr(e.func.count,t.count),e.func.average=Vr(e.func.average,t.avg())}),this.lines.forEach(t=>{e.line.timer=Vr(e.line.timer,t.timer),e.line.count=Vr(e.line.count,t.count),e.line.average=Vr(e.line.average,t.avg())}),e}},Ya=class{totalTime=0;file=new Map},Mo=class n{constructor(e,t,r,i){this.name=e;this.value=t;this.filename=r;this.line=i}children=[];ToStringInner(e){return`${e}${this.name} : ${this.value}
211
211
  ${this.children.map(t=>t.ToStringInner(e+" ")).join(`
212
212
  `)}`}ToString(){return this.ToStringInner("")}AddToChild(e,t,r,i){let o=this.children.find(s=>s.name===e);return o?o.value+=t:(o=new n(e,t,r,i),this.children.push(o)),o}Merge(e){this.value+=e.value,e.children.forEach(t=>{let r=this.children.find(i=>i.name===t.name);r?r.Merge(t):this.children.push(t)})}},Za=class{totalTime=0;mod=new Map;getMod(e){let t=this.mod.get(e);return t||(t=new Ya,this.mod.set(e,t)),t}getFile(e,t){let r=this.getMod(e),i=r.file.get(t);return i||(i=new Oo,r.file.set(t,i)),i}AddModTime(e,t){this.totalTime+=t,this.getMod(e).totalTime+=t}AddLineTime(e,t,r,i,o){let s=this.getFile(e,t),a=new zr(i,o),c=s.lines.get(r);s.lines.set(r,a.add(c))}AddFuncTime(e,t,r,i,o){let s=this.getFile(e,t),a=new zr(i,o),c=s.functions.get(r);s.functions.set(r,a.add(c))}Report(e){let t=new Oo;return this.mod.forEach(r=>{let i=r.file.get(e);i&&t.add(i)}),{totalTime:this.totalTime,fileData:t}}},Ao=class{constructor(e,t,r){this.context=t;this.debug=r;this._disposables.push(de.debug.onDidReceiveDebugSessionCustomEvent(this.onCustomEvent,this)),this._disposables.push(de.debug.onDidTerminateDebugSession(this.onTerminate,this)),this.timeDecorationType=de.window.createTextEditorDecorationType({before:{contentText:"",color:new de.ThemeColor("factorio.ProfileTimerForeground")}}),this.funcDecorationType=de.window.createTextEditorDecorationType({after:{contentText:"",color:new de.ThemeColor("factorio.ProfileFunctionTimerForeground"),borderColor:new de.ThemeColor("factorio.ProfileFunctionTimerForeground"),border:"1px solid",margin:"0 0 0 3ch"}});let i=de.workspace.getConfiguration().get("factorio.profile.rulers",[]);this.rulerDecorationTypes=i.filter(o=>o.color||o.themeColor).map(o=>{let s=de.OverviewRulerLane.Right;switch(o.lane){case"Right":s=de.OverviewRulerLane.Right;break;case"Center":s=de.OverviewRulerLane.Center;break;case"Left":s=de.OverviewRulerLane.Left;break;case"Full":s=de.OverviewRulerLane.Full;break;default:break}return{type:de.window.createTextEditorDecorationType({overviewRulerColor:o.color??new de.ThemeColor(o.themeColor),overviewRulerLane:s}),threshold:o.threshold}}),this.statusBar=de.window.createStatusBarItem(),this._disposables.push(de.window.onDidChangeActiveTextEditor(o=>{o&&o.document.uri.scheme==="file"&&this.render(o)})),e&&this.createFlamePanel()}profileData=new Za;profileTreeRoot=new Mo("root",0);profileOverhead=new zr(0,0);timeDecorationType;funcDecorationType;rulerDecorationTypes;statusBar;flamePanel;_disposables=[];onTerminate(e){e===this.debug&&this.dispose()}dispose(){this._disposables.forEach(e=>e.dispose()),this.timeDecorationType.dispose(),this.funcDecorationType.dispose(),this.rulerDecorationTypes.forEach(e=>{e.type.dispose()}),this.statusBar.dispose(),this.flamePanel&&this.flamePanel.dispose()}async onCustomEvent(e){if(e.session===this.debug&&e.event==="x-Factorio-Profile"){await this.parse(e.body);let t=de.window.activeTextEditor;t&&t.document.uri.scheme==="file"&&this.render(t)}}async createFlamePanel(){if(this.flamePanel)return;this.flamePanel=de.window.createWebviewPanel("factorioProfile","Factorio Profile",de.ViewColumn.Two,{enableScripts:!0,localResourceRoots:[this.context.extensionUri]});let e=this.flamePanel.webview,t=(await Promise.resolve().then(()=>mt(Rh()))).default;e.html=t.replace("$Flamegraph.css$",e.asWebviewUri(de.Uri.joinPath(this.context.extensionUri,"/dist/Flamegraph.css")).toString()).replace("$Flamegraph.js$",e.asWebviewUri(de.Uri.joinPath(this.context.extensionUri,"/dist/Flamegraph.js")).toString()),e.onDidReceiveMessage(r=>{switch(r.command){case"init":e.postMessage({command:"update",data:this.profileTreeRoot});break;case"click":r.line&&r.line>0&&r.filename&&r.line&&de.window.showTextDocument(de.Uri.parse(r.filename),{selection:new de.Range(r.line,0,r.line,0),viewColumn:de.ViewColumn.One});break;default:break}}),this.flamePanel.onDidDispose(()=>this.flamePanel=void 0)}async parse(e){let t=e.split(`
213
213
  `),r,i,o=[new Mo("root",0)],s;for(let a of t){let c=a.split(":");switch(c[0]){case"PROFILE":break;case"PMN":{r=c[1].replace(/[\r\n]*/g,"");let u=parseFloat(c[3]);this.profileData.AddModTime(r,u)}break;case"PFN":r&&(i=await this.debug.customRequest("x-Factorio-ConvertPath",{path:c[1].replace(/[\r\n]*/g,"")}));break;case"PLN":if(r&&i){let u=parseInt(c[1]),d=parseFloat(c[3]),g=parseInt(c[4]);this.profileData.AddLineTime(r,i,u,d,g)}break;case"PFT":if(r&&i){let u=parseInt(c[1]),d=parseFloat(c[3]),g=parseInt(c[4]);this.profileData.AddFuncTime(r,i,u,d,g)}break;case"POV":{let u=parseFloat(c[2]);this.profileOverhead=this.profileOverhead.add(new zr(u,1))}break;case"PROOT":r&&((0,Qa.assert)(o.length===1),s=o[0].AddToChild(r,0));break;case"PTREE":if(s){let u=c[1],d=await this.debug.customRequest("x-Factorio-ConvertPath",{path:c[2]}),g=c[3],m=u+":"+d+":"+g,y=parseFloat(c[5]);o.push(s),s=s.AddToChild(m,y,d,parseInt(g))}break;case"PTEND":s&&(o.length===1?s=void 0:s=o.pop());break}}(0,Qa.assert)(o.length===1),this.flamePanel&&this.flamePanel.visible&&this.flamePanel.webview.postMessage({command:"merge",data:o[0]}),this.profileTreeRoot.Merge(o[0])}render(e){let t=this.profileData.Report(e.document.uri.fsPath),r=t.fileData.max(),i=r.line.timer,o=r.line.average,s=r.line.count,a=new Array,c=new Array,u=this.rulerDecorationTypes.map((Z,V)=>({type:Z.type,threshold:Z.threshold,decs:new Array})),d=de.workspace.getConfiguration().get("factorio.profile.displayAverageTime"),g=de.workspace.getConfiguration().get("factorio.profile.colorBy","totaltime"),m=de.workspace.getConfiguration().get("factorio.profile.timerHighlightColor"),y={count:s,totaltime:i,averagetime:o}[g],v=Math.max(Number.MIN_VALUE,de.workspace.getConfiguration().get("factorio.profile.colorScaleFactor",1)),T={boost:Z=>Math.log1p(Z*v)/Math.log1p(y*v),linear:Z=>Z/y,mute:Z=>(Math.pow(1+y,Z*v/y)-1)/(y*v)}[de.workspace.getConfiguration().get("factorio.profile.colorScaleMode","boost")],P=s.toFixed(0).length+1,q=d?6:3,L=i.toFixed(q).length+1,N=P+L+3,K=t.fileData.lines.size>0,te=t.fileData.functions.size>0;for(let Z=1;Z<=e.document.lineCount;Z++){if(K){let V=t.fileData.lines.get(Z);if(V){let ne=V.timer,ce=V.count,Ne=d?V.avg():ne,U=T({count:ce,totaltime:ne,averagetime:V.avg()}[g]),I=e.document.validateRange(new de.Range(Z-1,0,Z-1,1/0));a.push({range:I,hoverMessage:d?`total: ${ne}`:`avg: ${V.avg()}`,renderOptions:{before:{backgroundColor:`${m}${Math.floor(255*U).toString(16)}`,contentText:`${ce.toFixed(0).padStart(P,"\xA0")}${Ne.toFixed(q).padStart(L,"\xA0")}\xA0ms`,width:`${N+1}ch`}}});let J=u.find(B=>U>=B.threshold);J&&J.decs.push({range:I})}else a.push({range:e.document.validateRange(new de.Range(Z-1,0,Z-1,1/0)),renderOptions:{before:{width:`${N+1}ch`}}})}if(te){let V=t.fileData.functions.get(Z);if(V){let ne=V.timer,ce=V.count,Ne=d?V.avg():ne,U=e.document.validateRange(new de.Range(Z-1,0,Z-1,1/0));c.push({range:U,renderOptions:{after:{contentText:`\xA0${ce.toFixed(0)}\xA0|\xA0${Ne.toFixed(q)}\xA0ms\xA0`,color:new de.ThemeColor("factorio.ProfileFunctionTimerForeground"),borderColor:new de.ThemeColor("factorio.ProfileFunctionTimerForeground"),margin:"0 0 0 3ch"}}})}}}e.setDecorations(this.timeDecorationType,a),e.setDecorations(this.funcDecorationType,c),u.forEach(Z=>{e.setDecorations(Z.type,Z.decs)}),this.statusBar.text=`Profile Dump Avg ${this.profileOverhead.avg().toFixed(3)} ms`,this.statusBar.show()}clear(){de.window.visibleTextEditors.forEach(e=>{e.setDecorations(this.timeDecorationType,[]),e.setDecorations(this.funcDecorationType,[]),this.rulerDecorationTypes.forEach(t=>{e.setDecorations(t.type,[])})}),this.statusBar.hide()}};var Lo=class{constructor(e){this.context=e;e.subscriptions.push(Ph.debug.onDidStartDebugSession(this.onDidStartDebugSession,this))}async onDidStartDebugSession(e){e.type==="factoriomod"&&e.configuration.hookMode==="profile"&&new Ao(e.configuration.profileTree??!0,this.context,e)}};var Zb=mt(require("path")),ew=require("vscode"),po=mt(Yb());function tw(n){let e=n.asAbsolutePath(Zb.join("dist","fmtk-cli.js")),t={execArgv:["--nolazy","--inspect-brk=34199"]},r={run:{module:e,transport:po.TransportKind.ipc,args:["lsp"]},debug:{module:e,transport:po.TransportKind.ipc,args:["lsp"],options:t}},i={documentSelector:[{language:"factorio-locale"},{language:"factorio-changelog"},{language:"lua"}],synchronize:{fileEvents:[ew.workspace.createFileSystemWatcher("**/locale/*/*.cfg")]}},o=new po.LanguageClient("factorioLanguageServer","Factorio Language Server",r,i);o.start(),n.subscriptions.push({dispose(){return o.stop()}})}var wt=mt(require("vscode")),Ti=require("./fmtk.js");function nw(n){return n.type==="int"?{type:"int",value:cP("",n.value)}:n}function yf(n,e){return typeof e=="bigint"?`jsonbigint ${e}n`:e}function cP(n,e){if(typeof e=="string"){let t=e.match(/^jsonbigint\x01\x02 (\d+)n$/);if(t)return BigInt(t[1])}return e}function wa(){let n="",e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";for(let t=0;t<32;t++)n+=e.charAt(Math.floor(Math.random()*e.length));return n}var Ca=class{constructor(e){this.context=e;this.context.subscriptions.push(wt.window.registerCustomEditorProvider("fmtk.modsettings",this,{supportsMultipleEditorsPerDocument:!1,webviewOptions:{retainContextWhenHidden:!0}}))}webviews=new Map;_onDidChangeCustomDocument=new wt.EventEmitter;onDidChangeCustomDocument=this._onDidChangeCustomDocument.event;async saveCustomDocument(e,t){return e.save(t)}async saveCustomDocumentAs(e,t,r){return e.saveAs(t,r)}async revertCustomDocument(e,t){return e.revert(t)}async backupCustomDocument(e,t,r){return e.backup(t.destination,r)}async openCustomDocument(e,t,r){let i=await bf.create(e,t.backupId),o=[];return o.push(i.onDidChange(s=>{this._onDidChangeCustomDocument.fire({document:i,...s})})),o.push(i.onDidChangeContent(s=>{let a=this.webviews.get(i.uri.toString());a&&this.postMessage(a,"init",{version:i.version,saves_ints:i.saves_ints,settings:JSON.stringify(i.settings,yf),editable:wt.workspace.fs.isWritableFileSystem(i.uri.scheme)!==!1})})),i.onDidDispose(()=>o.forEach(s=>s.dispose())),i}async resolveCustomEditor(e,t,r){let i=t.webview;this.webviews.set(e.uri.toString(),t),i.options={enableScripts:!0};let o=(await Promise.resolve().then(()=>mt(rw()))).default;i.html=o.replace(/\$cspSource\$/g,i.cspSource).replace(/\$nonce\$/g,wa()).replace(/\$ModSettingsWebview\.css\$/g,i.asWebviewUri(wt.Uri.joinPath(this.context.extensionUri,"/dist/ModSettingsWebview.css")).toString()).replace(/\$ModSettingsWebview\.js\$/g,i.asWebviewUri(wt.Uri.joinPath(this.context.extensionUri,"/dist/ModSettingsWebview.js")).toString()),t.webview.onDidReceiveMessage(s=>this.onMessage(e,s)),t.webview.onDidReceiveMessage(s=>{s.type==="ready"&&this.postMessage(t,"init",{version:e.version,saves_ints:e.saves_ints,settings:JSON.stringify(e.settings,yf),editable:wt.workspace.fs.isWritableFileSystem(e.uri.scheme)!==!1})})}postMessage(e,t,r){e.webview.postMessage({type:t,body:r})}onMessage(e,t){switch(t.type){case"edit":{e.edit(t.body);return}}}},bf=class n{constructor(e,t){this.uri=e;this._settings=new Ti.ModSettings(new Ti.BufferStream(t))}static async create(e,t){let r=typeof t=="string"?wt.Uri.parse(t):e,i=await wt.workspace.fs.readFile(r);return new n(e,i)}_settings;get version(){return this._settings.version.format()}get saves_ints(){return this._settings.version.isBeyond(1,2)}get settings(){return this._settings.settings}async save(e){return this.saveAs(this.uri,e)}async saveAs(e,t){return wt.workspace.fs.writeFile(e,this._settings.save())}async revert(e){this._settings=new Ti.ModSettings(new Ti.BufferStream(await wt.workspace.fs.readFile(this.uri))),this._onDidChangeDocument.fire({})}async backup(e,t){return await this.saveAs(e,t),{id:e.toString(),delete:async()=>{try{await wt.workspace.fs.delete(e)}catch{}}}}edit(e){e.value.type==="none"?this._settings.set(e.scope,e.name,void 0):this._settings.set(e.scope,e.name,nw(e.value)),this._onDidChange.fire({})}_onDidDispose=new wt.EventEmitter;onDidDispose=this._onDidDispose.event;_onDidChangeDocument=new wt.EventEmitter;onDidChangeContent=this._onDidChangeDocument.event;_onDidChange=new wt.EventEmitter;onDidChange=this._onDidChange.event;disposables=[this._onDidDispose,this._onDidChangeDocument,this._onDidChange];dispose(){this._onDidDispose.fire(),this.disposables.forEach(e=>e.dispose())}};var nn=mt(require("vscode"));var _a=require("./fmtk.js");function Da(n){switch(n.type){case"Table":case"TableWithMeta":return Object.assign({},n,{values:void 0});default:return n}}var Sa=class{constructor(e){this.context=e;this.context.subscriptions.push(nn.window.registerCustomEditorProvider("fmtk.scriptdat",this,{supportsMultipleEditorsPerDocument:!1,webviewOptions:{retainContextWhenHidden:!0}}))}webviews=new Map;_onDidChangeCustomDocument=new nn.EventEmitter;onDidChangeCustomDocument=this._onDidChangeCustomDocument.event;async openCustomDocument(e,t,r){let i=await wf.create(e,t.backupId),o=[];return o.push(i.onDidChange(s=>{this._onDidChangeCustomDocument.fire({document:i,...s})})),o.push(i.onDidChangeContent(s=>{let a=this.webviews.get(i.uri.toString());a&&this.postMessage(a,"init",{version:i.version,data:i.rootdata})})),i.onDidDispose(()=>o.forEach(s=>s.dispose())),i}async resolveCustomEditor(e,t,r){let i=t.webview;this.webviews.set(e.uri.toString(),t),i.options={enableScripts:!0};let o=(await Promise.resolve().then(()=>mt(iw()))).default;i.html=o.replace(/\$cspSource\$/g,i.cspSource).replace(/\$nonce\$/g,wa()).replace(/\$ScriptDatWebview\.css\$/g,i.asWebviewUri(nn.Uri.joinPath(this.context.extensionUri,"/dist/ScriptDatWebview.css")).toString()).replace(/\$ScriptDatWebview\.js\$/g,i.asWebviewUri(nn.Uri.joinPath(this.context.extensionUri,"/dist/ScriptDatWebview.js")).toString()),t.webview.onDidReceiveMessage(s=>this.onMessage(e,s)),t.webview.onDidReceiveMessage(s=>{s.type==="ready"&&this.postMessage(t,"init",{version:e.version,data:e.rootdata})})}postMessage(e,t,r){e.webview.postMessage({type:t,body:r})}onMessage(e,t){switch(t.type){case"fetch":let r=t.body,i=e.find(r.modname,r.gcid);this.postMessage(this.webviews.get(e.uri.toString()),"values",{...r,values:i.values.map(o=>({key:Da(o.key),value:Da(o.value)}))});break}}},wf=class n{constructor(e,t){this.uri=e;this._data=new _a.ScriptDat(new _a.BufferStream(t))}static async create(e,t){let r=typeof t=="string"?nn.Uri.parse(t):e,i=await nn.workspace.fs.readFile(r);return new n(e,i)}_data;get version(){return this._data.version.format()}get rootdata(){let e={};for(let t in this._data.data)e[t]=Da(this._data.data[t]);return e}find(e,t){return this._data.find(e,t)}_onDidDispose=new nn.EventEmitter;onDidDispose=this._onDidDispose.event;_onDidChangeDocument=new nn.EventEmitter;onDidChangeContent=this._onDidChangeDocument.event;_onDidChange=new nn.EventEmitter;onDidChange=this._onDidChange.event;disposables=[this._onDidDispose,this._onDidChangeDocument,this._onDidChange];dispose(){this._onDidDispose.fire(),this.disposables.forEach(e=>e.dispose())}};function dP(n){let e=pt.window.createOutputChannel("FMTK",{log:!0});e.info(`FMTK ${Io}`);try{e.info("Registering Version Selector...");let t=new Fo(n,e);e.info("Registering Debug Provider...");let r=new Cf(t);n.subscriptions.push(pt.debug.registerDebugConfigurationProvider("factoriomod",r));let i=new Df(t);n.subscriptions.push(pt.debug.registerDebugAdapterDescriptorFactory("factoriomod",i)),n.subscriptions.push(i),e.info("Registering Language Client..."),tw(n),e.info("Registering Mod Package Provider..."),Sh(n),e.info("Registering Profile Renderer..."),new Lo(n),e.info("Registering Custom Editors..."),new Ca(n),new Sa(n),e.info("Activate Complete")}catch(t){e.error(`Error while activating: ${t}`)}}var Cf=class{constructor(e){this.versionSelector=e}async resolveDebugConfigurationWithSubstitutedVariables(e,t,r){let i=await this.versionSelector.getActiveVersion();if(!i)return;if(await i.isPrototypeCacheEnabled()){let s=await pt.window.showWarningMessage("Prototype Caching is enabled, which usually conflicts with the final portion of debugger initialization (which occurs in settings stage).","Disable in config.ini","Continue anyway");if(s==="Disable in config.ini")await i.disablePrototypeCache();else if(s===void 0)return}let o=pt.workspace.getConfiguration("factorio.debug").get("env",{});return Object.keys(o).length>0&&(t.env=Object.assign({},o,t.env)),t}},Df=class{constructor(e){this.versionSelector=e}async createDebugAdapterDescriptor(e,t){let r=await this.versionSelector.getActiveVersion();if(!r)return;if(r.nativeDAP)return new pt.DebugAdapterExecutable(r.factorioPath,["--dap"]);let i=pt.workspace.getConfiguration("factorio");switch(i.get("debug.runMode","inline")){case"inline":default:return new pt.DebugAdapterInlineImplementation(new ow.FactorioModDebugSession(r,pt.workspace.fs,{findWorkspaceFiles:pt.workspace.findFiles,getExtension:pt.extensions.getExtension,executeCommand:pt.commands.executeCommand}));case"external":return i.get("inspect",!1)&&t.args.unshift("--nolazy","--inspect-brk=34198"),t.args.push(...await r.debugLaunchArgs()),t}}dispose(){}};0&&(module.exports={activate});