UNPKG

pioarduino-node-helpers

Version:

Collection of Node.JS helpers for PlatformIO fork pioarduino

2 lines 44.2 kB
!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e(require("global-agent"),require("got"),require("ws"),require("jsonrpc-lite"),require("tcp-port-used"),require("tar"),require("semver")):"function"==typeof define&&define.amd?define("pioarduino-node-helpers",["global-agent","got","ws","jsonrpc-lite","tcp-port-used","tar","semver"],e):"object"==typeof exports?exports["pioarduino-node-helpers"]=e(require("global-agent"),require("got"),require("ws"),require("jsonrpc-lite"),require("tcp-port-used"),require("tar"),require("semver")):t["pioarduino-node-helpers"]=e(t["global-agent"],t.got,t.ws,t["jsonrpc-lite"],t["tcp-port-used"],t.tar,t.semver)}(global,(t,e,n,o,r,i,s)=>(()=>{"use strict";var a={317(t){t.exports=require("child_process")},303(e){e.exports=t},810(t){t.exports=e},852(t){t.exports=o},924(t){t.exports=s},871(t){t.exports=i},65(t){t.exports=r},2(t){t.exports=n},330(t){t.exports={rE:"12.6.1"}}},c={};function u(t){var e=c[t];if(void 0!==e)return e.exports;var n=c[t]={exports:{}};return a[t](n,n.exports,u),n.exports}u.n=t=>{var e=t&&t.__esModule?()=>t.default:()=>t;return u.d(e,{a:e}),e},u.d=(t,e)=>{for(var n in e)u.o(e,n)&&!u.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:e[n]})},u.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),u.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})};var l={};u.r(l),u.d(l,{core:()=>h,home:()=>m,installer:()=>ae,misc:()=>d,proc:()=>p,project:()=>ce});var p={};u.r(p),u.d(p,{IS_WINDOWS:()=>P,extendOSEnvironPath:()=>b,getCommandOutput:()=>I,getSysType:()=>S,patchOSEnviron:()=>O,runCommand:()=>E,terminateCmdsInQueue:()=>C,whereIsProgram:()=>D});var h={};u.r(h),u.d(h,{getCacheDir:()=>R,getCoreDir:()=>L,getCorePythonCommandOutput:()=>U,getCorePythonExe:()=>N,getCoreState:()=>$,getEnvBinDir:()=>M,getEnvDir:()=>F,getPIOCommandOutput:()=>H,getTmpDir:()=>k,runPIOCommand:()=>B,setCoreState:()=>x});var d={};u.r(d),u.d(d,{PEPverToSemver:()=>z,arrayRemove:()=>Y,disposeSubscriptions:()=>K,getErrorReportUrl:()=>Z,loadJSON:()=>X,reportError:()=>Q,sleep:()=>J});var m={};u.r(m),u.d(m,{constructServerUrl:()=>vt,ensureServerStarted:()=>Pt,getFrontendUrl:()=>gt,getFrontendVersion:()=>yt,isServerStarted:()=>_t,showAtStartup:()=>Ct,shutdownAllServers:()=>bt,shutdownServer:()=>Ot});var f=u(303);const v=require("fs");var g=u.n(v);const y=require("path");var w=u.n(y);const{spawn:_}=u(317),P=process.platform.startsWith("win");function S(){const t=`${process.platform}_${process.arch}`;return{win32_x64:"windows_amd64",win32_x32:"windows_x86",win32_ia32:"windows_x86",darwin_x64:"darwin_x86_64",darwin_x32:"darwin_i686",darwin_arm64:"darwin_arm64",linux_x64:"linux_x86_64",linux_x32:"linux_i686",linux_arm:"linux_armv6l",linux_arm64:"linux_aarch64",freebsd_x64:"freebsd_amd64"}[t]||t}function O({caller:t,extraPath:e,extraVars:n}){process.env.PLATFORMIO_CALLER=t,"darwin"===process.platform&&(process.env.LC_ALL="en_US.UTF-8"),"atom"===t&&(process.env.PLATFORMIO_DISABLE_PROGRESSBAR="true"),n&&Object.keys(n).forEach(t=>process.env[t]=n[t]),process.env.PLATFORMIO_PATH=process.env.PATH,process.env.Path&&(process.env.PLATFORMIO_PATH?process.env.PLATFORMIO_PATH+=w().delimiter+process.env.Path:process.env.PLATFORMIO_PATH=process.env.Path),e&&b("PLATFORMIO_PATH",e.split(w().delimiter));const o=/\%([^\%]+)\%/g,r=[];for(;P;){const t=o.exec(process.env.PLATFORMIO_PATH);if(!t||r.includes(t[1]))break;r.push(t[1]),process.env.PLATFORMIO_PATH=process.env.PLATFORMIO_PATH.replace(t[0],process.env[t[1]]||"")}process.env.NO_PROXY="127.0.0.1"+(process.env.NO_PROXY?`,${process.env.NO_PROXY}`:""),(process.env.HTTP_PROXY||process.env.HTTPS_PROXY||process.env.ALL_PROXY)&&(process.env.GLOBAL_AGENT_ENVIRONMENT_VARIABLE_NAMESPACE="",(0,f.bootstrap)())}function b(t,e,n=!0){e.reverse().forEach(e=>{process.env[t].includes(e)||(process.env[t]=(n?[e,process.env[t]]:[process.env[t],e]).join(w().delimiter))})}const T=[];function C(){for(;T.length;){const t=T.pop()[2];t&&t(-1,void 0,new Error("Terminated by user"))}}function E(t,e,n=void 0,o={}){if((o=o||{})._id||(o._id=`${t}-${Math.random()}`),!(o.runInQueue&&(console.info("Put command in queue",t,e,o),T.push([t,e,n,o]),T.length>1)))return A(t,e,n,o)}function A(t,e,n,o){console.info("runCommand",t,e,o);const r=[],i=[];let s=!1;function a(t){if(s)return;if(o.runInQueue&&(function(t){const e=T.findIndex(e=>e[3]._id===t);e>-1&&T.splice(e,1)}(o._id),T.length>0&&A(...T.pop())),!n)return;s=!0;const e=r.join(""),a=i.join("");n(t,e,a)}o.spawnOptions=o.spawnOptions||{},o.projectDir&&(o.spawnOptions.cwd=o.projectDir);const c=Object.assign({},o.spawnOptions.env||process.env);process.env.PLATFORMIO_PATH&&(c.PATH=process.env.PLATFORMIO_PATH,c.Path=process.env.PLATFORMIO_PATH),o.spawnOptions.env=c;try{const n=_(t,e,o.spawnOptions);o.onProcCreated&&o.onProcCreated(n),n.stdout.on("data",t=>{r.push(t.toString()),o.onProcStdout&&o.onProcStdout(t)}),n.stderr.on("data",t=>{i.push(t.toString()),o.onProcStderr&&o.onProcStderr(t)}),n.on("close",a),n.on("error",t=>{i.push(t.toString()),a(-1)})}catch(t){i.push(t.toString()),a(-1)}}function I(t,e,n={}){return new Promise((o,r)=>{E(t,e,(t,e,n)=>{if(0===t)return o(e);{const t=new Error(e?`${n} -> ${e}`:n);return t.stderr=n,t.stdout=e,r(t)}},n)})}function D(t){const e=process.env.PLATFORMIO_PATH||process.env.PATH;for(const n of e.split(w().delimiter)){const e=w().normalize(w().join(n,t)).replace(/"/g,"");try{if(g().existsSync(e))return e}catch(t){}}return null}let j;function x(t){j=t}function $(){return j||{}}function L(){if($().core_dir)return $().core_dir;let t=process.env.HOME||"~";P&&(process.env.USERPROFILE?t=process.env.USERPROFILE:process.env.HOMEPATH&&(t=w().join(process.env.HOMEDRIVE||"",process.env.HOMEPATH)));const e=process.env.PLATFORMIO_CORE_DIR||process.env.PLATFORMIO_HOME_DIR||w().join(t,".platformio");if(!P)return e;const n=w().parse(e),o=w().format({root:n.root,dir:n.root,base:".platformio",name:".platformio"});try{return g().accessSync(o),o}catch(t){}for(const t of e)if(t.charCodeAt(0)>127)return o;return e}function R(){if($().cache_dir)return $().cache_dir;const t=w().join(L(),".cache");try{g().accessSync(t)}catch(e){g().mkdirSync(t,{recursive:!0})}return t}function k(){const t=w().join(R(),"tmp");try{g().accessSync(t)}catch(e){g().mkdirSync(t,{recursive:!0})}return t}function F(){return $().penv_dir?$().penv_dir:"PLATFORMIO_PENV_DIR"in process.env?process.env.PLATFORMIO_PENV_DIR:w().join(L(),"penv")}function M(){return $().penv_bin_dir?$().penv_bin_dir:w().join(F(),P?"Scripts":"bin")}async function N(){const t=$().python_exe;if(!t)throw new Error("pioarduino Core is not installed");return t}async function U(t,e){return await I(await N(),t,e)}async function H(t,e={}){const n=["-m","platformio"];return process.env.PLATFORMIO_CALLER&&n.push("-c",process.env.PLATFORMIO_CALLER),await U([...n,...t],e)}async function B(t,e,n={}){const o=["-m","platformio"];process.env.PLATFORMIO_CALLER&&o.push("-c",process.env.PLATFORMIO_CALLER),E(await N(),[...o,...t],e,n)}var q=u(810),W=u.n(q);const V=require("os");var G=u.n(V);function J(t){return new Promise(e=>setTimeout(e,t))}async function X(t){try{return await v.promises.access(t),JSON.parse(await v.promises.readFile(t,{encoding:"utf-8"}))}catch(t){return console.error(t),null}}function Y(t,e){return t.splice(t.indexOf(e),1)}function K(t){for(;t.length;)t.pop().dispose()}function z(t){return t.replace(/(\.\d+)\.?(dev|a|b|rc|post)/,"$1-$2.")}async function Q(t){const e=new URLSearchParams;e.set("v",1),e.set("tid","UA-1768265-13"),e.set("cid",function(){const t=()=>Math.floor(65536*(1+Math.random())).toString(16).substring(1);return`${t()}${t()}-${t()}-${t()}-${t()}-${t()}${t()}${t()}`}()),e.set("aid","node.helpers"),e.set("av","12.6.1"),e.set("an",`${G().type()}, ${G().release()}, ${G().arch()}`),e.set("t","exception"),e.set("exd",t.toString()),e.set("exf",1),process.env.PLATFORMIO_CALLER&&e.set("cd1",process.env.PLATFORMIO_CALLER),await W().post("https://www.google-analytics.com/collect",{body:e.toString(),timeout:2e3})}function Z(t,e){const n=[["Multiple requests to rebuild the project","https://bit.ly/3mMTOgB"],["WindowsError: [Error 5]","https://bit.ly/3GTAtlG"],["[WinError 5]","https://bit.ly/3GTAtlG"],["[WinError 225]","https://bit.ly/3GTAtlG"],["Could not start PIO Home server: Error: timeout","https://bit.ly/2Yfl65C"],["`venv` module","https://bit.ly/3bK6zlH"],["after connection broken by","https://bit.ly/3q6StTV"],["subprocess.CalledProcessError","https://bit.ly/3EFlxWq"],["Can not find Python 3.13 Interpreter","https://bit.ly/3wkz0Qv"],["platformio-ide.useBuiltinPIOCore","https://bit.ly/3AhJHHe"],["Could not start PIO Home server: Timeout error","https://bit.ly/3m2Tbl9"],["Could not create PIO Core Virtual Environment","https://bit.ly/43hNh04"],["Compatible pioarduino Core not found","https://bit.ly/43tNj4C"],["Could not find a version that satisfies the requirement","https://bit.ly/3TOcnBK"],["PIO IDE: v2.","https://bit.ly/3H70AHl"]];for(const t of n)if(e.includes(t[0]))return t[1];let o=`${process.env.PLATFORMIO_CALLER||"vscode"}-ide`;t.includes("Installation Manager")&&(o="core-installer");const r=new URLSearchParams;return r.set("title",t),r.set("body",e),r.set("labels","auto"),`https://github.com/pioarduino/pioarduino-${o}/issues/new?${r.toString()}`}var tt=u(2),et=u.n(tt);const nt=require("crypto");var ot=u.n(nt),rt=u(852),it=u.n(rt),st=u(65),at=u.n(st);const ct=30,ut=3600,lt=45e3,pt=45999,ht=ot().createHash("sha1").update(ot().randomBytes(512)).digest("hex");let dt="127.0.0.1",mt=0,ft=0;function vt({scheme:t="http",host:e,port:n,path:o,query:r,includeSID:i=!0}={}){let s=`${t}://${e||dt}:${n||mt}`;if(i&&(s+=`/session/${ht}`),s+=o||"/",r){const t=new URLSearchParams;Object.keys(r).forEach(e=>t.set(e,r[e])),s+=`?${t.toString()}`}return s}function gt(t){const e=(Tt()||{}).storage||{},n={start:t.start||"/",theme:e.theme||t.theme,workspace:e.workspace||t.workspace};return Object.keys(n).forEach(t=>{[void 0,null].includes(n[t])&&delete n[t]}),vt({query:n})}async function yt(){try{return(await W()(vt({path:"/package.json"}),{timeout:1e3}).json()).version}catch(t){}}async function wt(t,e){return new Promise(n=>{at().check(t,e).then(t=>n(t),()=>n(!1))})}async function _t(){return!!await wt(mt,dt)&&!!await yt()}async function Pt(t={}){let e,n=0;for(;n<3;){try{return await St(t)}catch(t){mt=0,e=t,console.warn(t)}n++}throw Q(e),e}async function St(t={}){return 0===mt&&(mt=t.port||await async function(){let t=0;for(;t<13;){const e=Math.floor(Math.random()*(pt-lt)+lt);if(!await wt(e,dt))return e;t++}return 0}()),t.host&&(dt=t.host),await _t()||await new Promise((t,e)=>{const n=setTimeout(()=>e(new Error("Could not start PIO Home server: Timeout error")),1e3*ct);let o="";B(["home","--port",mt,"--host",dt,"--session-id",ht,"--shutdown-timeout",ut,"--no-open"],(t,n,o)=>{if(0!==t)return mt=0,e(new Error(o))},{onProcStdout:e=>{o+=e.toString(),o.includes("PIO Home has been started")&&(clearTimeout(n),t(!0))}})}),t.onIDECommand&&async function(t){if(ft>0)return;const e=new(et())(vt({scheme:"ws",path:"/wsrpc"}),{perMessageDeflate:!1});e.on("open",()=>{ft=1,e.send(JSON.stringify(it().request(Math.random().toString(),"core.version")))}),e.on("close",()=>{ft=0}),e.on("message",async n=>{try{const o=it().parse(n.toString());if("success"===o.type&&o.payload.result.method){const n=await t(o.payload.result.method,o.payload.result.params);e.send(JSON.stringify(it().request(Math.random().toString(),"ide.on_command_result",[o.payload.result.id,n])))}else"error"===o.type&&console.error("Errored WS result: ",o.payload)}catch(t){console.error("Invalid RPC message: ",t)}e.send(JSON.stringify(it().request(Math.random().toString(),"ide.listen_commands")))})}(t.onIDECommand),{host:dt,port:mt,sessionId:ht}}async function Ot(){if(mt)try{await W().post(vt({path:"/__shutdown__"}),{timeout:1e3})}catch(t){}}async function bt(){let t=lt;for(;t<pt;){try{W()(vt({port:t,includeSID:!1,query:{__shutdown__:"1"}}),{timeout:1e3,throwHttpErrors:!1}).then(()=>{},()=>{})}catch(t){}t++}await J(2e3)}function Tt(){try{return JSON.parse(g().readFileSync(w().join(L(),"homestate.json"),{encoding:"utf-8"}))}catch(t){}}function Ct(t){const e=Tt();return!e||!e.storage||!e.storage.showOnStartup||!(t in e.storage.showOnStartup)||e.storage.showOnStartup[t]}function Et(t,e,n){if(n&&"function"==typeof n.rebuildArgs)return n.rebuildArgs(t);const o=["project","init","--ide",e];return t&&o.push("--environment",t),o}class At{static generalTasks=[{name:"Build",args:["run"],multienv:!0},{name:"Upload",args:["run","--target","upload"],optionalArgs:["--upload-port"],multienv:!0},{name:"Monitor",args:["device","monitor"],optionalArgs:["--port"],multienv:!0},{name:"Upload and Monitor",args:["run","--target","upload","--target","monitor"],optionalArgs:["--upload-port","--monitor-port"],multienv:!0},{name:"Devices",args:["device","list"]},{name:"Clean",args:["run","--target","clean"],multienv:!0},{name:"Full Clean",description:"Clean a build environment and installed library dependencies",args:["run","--target","fullclean"],multienv:!0},{name:"List",args:["pkg","list"],group:"Dependencies",multienv:!0},{name:"Outdated",args:["pkg","outdated"],group:"Dependencies",multienv:!0},{name:"Update",args:["pkg","update"],group:"Dependencies",multienv:!0},{name:"Test",args:["test"],optionalArgs:["--upload-port","--test-port"],group:"Advanced",multienv:!0},{name:"Check",args:["check"],group:"Advanced",multienv:!0},{name:"Pre-Debug",description:"Build in debug mode",args:["debug"],group:"Advanced",multienv:!0},{name:"Verbose Build",args:["run","--verbose"],group:"Advanced",multienv:!0},{name:"Verbose Upload",args:["run","--verbose","--target","upload"],optionalArgs:["--upload-port"],group:"Advanced",multienv:!0},{name:"Verbose Test",args:["test","--verbose"],group:"Advanced",multienv:!0},{name:"Verbose Check",args:["check","--verbose"],group:"Advanced",multienv:!0},{name:"Compilation Database",description:"Generate compilation database `compile_commands.json`",args:["run","--target","compiledb"],group:"Advanced",multienv:!0},{name:"Remote Upload",args:["remote","run","--target","upload"],group:"Remote",multienv:!0},{name:"Remote Monitor",args:["remote","device","monitor"],group:"Remote"},{name:"Remote Devices",args:["remote","device","list"],group:"Remote"},{name:"Remote Test",args:["remote","test"],group:"Remote",multienv:!0},{name:"Upgrade pioarduino Core",args:["upgrade"],group:"Miscellaneous"}];constructor(t,e,n){this.projectDir=t,this.ide=e,this.intelliSenseBackend=n}async getDefaultTasks(){return At.generalTasks.map(t=>{const e=new It(t.name,t.args.slice(0),t.group);return e.description=t.description,e.multienv=!!t.multienv,e.optionalArgs=t.optionalArgs,e})}async fetchEnvTasks(t){const e=[],n=[];for(const o of At.generalTasks){if(!o.multienv)continue;n.push(o.name);const r=new It(o.name,[...o.args.slice(0),"--environment",t],o.group);r.description=o.description,r.multienv=!0,r.optionalArgs=o.optionalArgs,e.push(r)}const o=Et(t,this.ide,this.intelliSenseBackend);!t||o.includes("--environment")||o.includes("-e")||o.push("--environment",t);const r=new It("Rebuild IntelliSense Index",o,"Miscellaneous");r.multienv=!0,e.push(r);try{for(const o of await this.fetchEnvTargets(t)){if(n.includes(o.title))continue;const r=new It(o.title||o.name,["run","--target",o.name,"--environment",t],o.group);r.description=o.description,r.multienv=!0,e.push(r)}}catch(e){console.error(`Could not fetch project targets for '${t}' environment => ${e}`)}return e}async fetchEnvTargets(t){const e=`\nimport json\nimport os\nfrom platformio.public import load_build_metadata\n\nprint(json.dumps(load_build_metadata(os.getcwd(), '${t}', cache=True)["targets"]))\n `,n=await U(["-c",e],{projectDir:this.projectDir,runInQueue:!0});return JSON.parse(n.trim())}}class It{constructor(t,e,n="General"){this.name=t,this.args=e,this.group=n,this.description=void 0,this.multienv=!1,this.optionalArgs=void 0}isBuild(){return this.name.startsWith("Build")}isClean(){return this.name.startsWith("Clean")}isTest(){return this.name.startsWith("Test")}get coreTarget(){if("run"!==this.args[0])return this.args[0];const t=this.args.indexOf("--target");return-1!==t?this.args[t+1]:"build"}get coreEnv(){const t=this.args.indexOf("--environment");return-1!==t?this.args[t+1]:void 0}get id(){const t=this.coreEnv;return t?`${this.name} (${t})`:this.name}get title(){const t=this.coreEnv,e=this.description||this.name;return t?`${e} (${t})`:e}getCoreArgs(t={}){const e=this.args.slice(0);return this.optionalArgs&&t.port&&this.optionalArgs.filter(t=>t.endsWith("-port")).forEach(n=>{e.push(n),e.push(t.port)}),e}}const Dt=require("stream/promises"),jt=require("util"),xt=u(871),$t=(0,jt.promisify)(u(317).execFile),Lt="3.13",Rt=P?"uv.exe":"uv",kt=P?"python.exe":"python3",Ft=P?"Scripts":"bin";function Mt(t,e){const n=(new Date).toISOString();console[t](`[${n}] [Python-Installer] ${e}`)}async function Nt(t){try{return await $t(t,["--version"],{timeout:1e4}),!0}catch{return Mt("warn",`uv at ${t} is not usable`),!1}}function Ut(t,e){const n=g().readdirSync(e,{withFileTypes:!0});for(const o of n){const n=w().join(e,o.name);if(o.isFile()&&o.name===t)return n;if(o.isDirectory()){const e=Ut(t,n);if(e)return e}}return null}async function Ht(t){const e=function(){const t=process.platform,e=process.arch;if("darwin"===t){const t={arm64:"aarch64",x64:"x86_64"}[e];if(t)return`uv-${t}-apple-darwin`}else if("linux"===t){const t=function(){try{const{execSync:t}=u(317);return t("ldd --version 2>&1 || true",{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","pipe"]}).toLowerCase().includes("musl")}catch{return!1}}(),n={x64:["x86_64",t?"musl":"gnu"],arm64:["aarch64",t?"musl":"gnu"],arm:["armv7",t?"musleabihf":"gnueabihf"]}[e];if(n){const[t,e]=n;return`uv-${t}-unknown-linux-${e}`}}else if("win32"===t){const t={x64:"x86_64",arm64:"aarch64"}[e];if(t)return`uv-${t}-pc-windows-msvc`}return null}();if(!e)return Mt("info",`Unsupported platform for direct uv download: ${process.platform}/${process.arch}`),null;const n=w().join(t,Rt),o=P?`${e}.zip`:`${e}.tar.gz`,r=`https://github.com/astral-sh/uv/releases/download/0.11.6/${o}`;Mt("info",`Downloading uv from ${r}`);const i=w().join(G().tmpdir(),`uv-download-${Date.now()}`);try{g().mkdirSync(i,{recursive:!0});const e=w().join(i,o);await async function(t,e){const n=g().createWriteStream(e);await(0,Dt.pipeline)(W().stream(t,{followRedirect:!0,timeout:{request:3e5}}),n)}(r,e);const a=`${r}.sha256`,c=await W()(a,{timeout:{request:3e4}}),u=c.body.split(/\s+/)[0].trim().toLowerCase();if(!/^[a-f0-9]{64}$/.test(u))return Mt("warn",`Invalid SHA256 response (possible CDN error page): ${c.body.slice(0,100)}`),null;if(await(s=e,new Promise((t,e)=>{const n=ot().createHash("sha256"),o=g().createReadStream(s);o.on("data",t=>n.update(t)),o.on("end",()=>t(n.digest("hex").toLowerCase())),o.on("error",e)}))!==u)return Mt("warn","uv archive SHA256 mismatch"),null;const l=w().join(i,"extract");if(g().mkdirSync(l,{recursive:!0}),P){const t=t=>`'${String(t).replace(/'/g,"''")}'`;await async function(t,e){try{return await $t("pwsh",t,e)}catch(n){if("ENOENT"===n.code)return Mt("info","pwsh not found, falling back to powershell.exe"),await $t("powershell.exe",t,e);throw n}}(["-NoProfile","-NonInteractive","-Command",`Expand-Archive -LiteralPath ${t(e)} -DestinationPath ${t(l)} -Force`],{timeout:6e4})}else await xt.extract({file:e,cwd:l});const p=Ut(Rt,l);return p?(g().mkdirSync(t,{recursive:!0}),g().copyFileSync(p,n),P||g().chmodSync(n,493),Mt("info",`uv downloaded and installed at ${n}`),n):(Mt("warn","uv binary not found in downloaded archive"),null)}catch(t){return Mt("warn",`Failed to download uv directly: ${t.message}`),null}finally{try{g().rmSync(i,{recursive:!0,force:!0})}catch{}}var s}async function Bt(){const t=function(t){const e=process.env.PLATFORMIO_PATH||process.env.PATH;if(!e)return null;for(const n of e.split(w().delimiter)){const e=w().join(n,t);try{return P?g().accessSync(e):g().accessSync(e,g().constants.X_OK),e}catch{}}return null}(Rt);if(t&&await Nt(t))return Mt("info",`Found uv in PATH: ${t}`),t;const e=w().join(F(),Ft,Rt);if(g().existsSync(e)){if(await Nt(e))return Mt("info",`Found uv in penv: ${e}`),e;Mt("info","penv uv not usable, falling through to cache")}const n=R(),o=w().join(n,Rt);if(g().existsSync(o)){if(await Nt(o))return Mt("info",`Found cached uv: ${o}`),o;Mt("info","Cached uv not usable, reinstalling")}let r=await Ht(n);if(r&&await Nt(r))return Mt("info",`uv downloaded at ${r}`),r;if(r=await async function(t){let e=null;try{g().mkdirSync(t,{recursive:!0});const n=w().join(t,Rt),o={...process.env,UV_UNMANAGED_INSTALL:t};e=g().mkdtempSync(w().join(G().tmpdir(),"uv-install-"));const r=g().mkdtempSync(w().join(G().tmpdir(),"uv-installer-"));try{if(P){const t=w().join(r,"install.ps1"),{body:e}=await W()("https://astral.sh/uv/install.ps1",{timeout:{request:3e4}});g().writeFileSync(t,e),await $t("powershell",["-ExecutionPolicy","ByPass","-File",t],{timeout:9e5,env:o})}else{const t=w().join(r,"install.sh"),{body:e}=await W()("https://astral.sh/uv/install.sh",{timeout:{request:3e4}});g().writeFileSync(t,e,{mode:493}),await $t("sh",[t],{timeout:9e5,env:o})}}finally{try{g().rmSync(r,{recursive:!0,force:!0})}catch{}}if(g().existsSync(n))return P||g().chmodSync(n,493),Mt("info",`uv installed at ${n}`),n}catch(t){Mt("warn",`Failed to install uv with official script: ${t.message}`)}finally{if(e)try{g().rmSync(e,{recursive:!0,force:!0})}catch{}}return null}(n),r&&await Nt(r))return Mt("info",`uv installed at ${r}`),r;throw new Error("Failed to install uv. Please check internet connection and try again.")}async function qt(){const t=R(),e=w().join(t,Rt);if(g().existsSync(e))try{g().unlinkSync(e),Mt("info",`Removed bootstrap uv from cache: ${e}`)}catch(t){Mt("warn",`Could not remove cached uv: ${t.message}`)}const n=w().join(t,P?"uvx.exe":"uvx");if(g().existsSync(n))try{g().unlinkSync(n),Mt("info",`Removed bootstrap uvx from cache: ${n}`)}catch(t){Mt("warn",`Could not remove cached uvx: ${t.message}`)}const o=w().join(t,"uv");try{g().statSync(o).isDirectory()&&(g().rmSync(o,{recursive:!0,force:!0}),Mt("info",`Removed uv installer cache directory: ${o}`))}catch{}}async function Wt(t,e,n=null){let o=null;const r=w().resolve(t),i=w().resolve(e);if(r.startsWith(i+w().sep)){o=g().mkdtempSync(w().join(G().tmpdir(),"uv-safe-"));const e=w().join(o,Rt);g().copyFileSync(r,e),P||g().chmodSync(e,493),Mt("info",`Copied penv-resident uv to safe location: ${e}`),t=e}g().existsSync(e)&&g().rmSync(e,{recursive:!0,force:!0});const s=w().dirname(t),a=process.env.PATH||"";a.split(w().delimiter).includes(s)||(process.env.PATH=s+w().delimiter+a);try{const o=["venv",e,"--python",n||Lt];n&&w().isAbsolute(n)||o.push("--python-preference","managed");const r=await $t(t,o,{timeout:9e5});Mt("info",`uv venv output: ${r.stdout||""} ${r.stderr||""}`);const i=w().join(e,Ft,kt);if(g().existsSync(i)){Mt("info",`Successfully created venv at ${e} with Python ${n||Lt}`);try{await $t(t,["pip","install","uv>=0.1.0",`--python=${i}`],{timeout:12e4}),Mt("info","uv installed into penv via uv pip install")}catch(t){throw new Error(`Could not install uv into penv: ${t.message}`)}try{const t=w().join(e,Ft,Rt);await $t(t,["pip","install","pip>=24.3",`--python=${i}`],{timeout:12e4}),Mt("info","pip installed into penv via venv uv for compatibility")}catch(t){Mt("warn",`Could not install pip into penv (non-fatal): ${t.message}`)}return e}return Mt("warn",`Expected python not found at ${i}`),null}catch(t){return Mt("error",`Failed to create venv with uv: ${t.message}`),null}finally{if(o)try{g().rmSync(o,{recursive:!0,force:!0})}catch{}}}async function Vt(t){const e=w().join(t,Ft,kt),n=w().join(t,Ft,Rt);try{return await $t(e,["-c","import pip"],{timeout:5e3}),void Mt("info","pip already available in penv")}catch{}if(g().existsSync(n))try{await $t(n,["pip","install","pip>=24.3",`--python=${e}`],{timeout:12e4}),Mt("info","pip installed into penv via venv uv (compat migration)")}catch(t){Mt("warn",`Could not install pip into penv (non-fatal): ${t.message}`)}else Mt("warn","Cannot install pip: venv uv not found in penv")}async function Gt(t){try{const{execSync:e}=u(317),n=e(`"${t}" --version`,{encoding:"utf8",timeout:3e3,stdio:["ignore","pipe","pipe"]}).match(/Python (\d+\.\d+\.\d+)/);return!!n&&function(t){const e=t.split("."),n=parseInt(e[0],10),o=parseInt(e[1],10);return 3===n&&13===o}(n[1])}catch{return!1}}function Jt(t){if("cygwin"===process.platform)return!1;if(process.env.CONDA_DEFAULT_ENV||process.env.CONDA_PREFIX)return!1;if(P){const e=t.toLowerCase();if(["msys","mingw","emacs"].some(t=>e.includes(t)))return!1}return!0}async function Xt(){const t=P?["python.exe"]:["python3","python"],e=process.env.PLATFORMIO_PATH||process.env.PATH||"";Mt("info","Searching for Python 3.13 installation");for(const n of e.split(w().delimiter))for(const e of t){const t=w().normalize(w().join(n,e)).replace(/"/g,"");try{if(g().existsSync(t)&&await Gt(t)&&Jt(t))return Mt("info",`Found compatible Python: ${t}`),t}catch(t){}}return Mt("info","No Python 3.13 found on system"),null}async function Yt(t){const e=F(),n=w().join(e,Ft,kt);try{await g().promises.access(n,g().constants.X_OK)}catch{if(!P)throw new Error(`Python not found in penv at: ${n}`);try{await g().promises.access(n)}catch{throw new Error(`Python not found in penv at: ${n}`)}}if(t){const{execFile:e}=u(317),o=(0,jt.promisify)(e);try{const{stdout:e}=await o(n,["--version"],{timeout:5e3}),r=e.trim().match(/Python (\d+\.\d+)/);if(!r)throw new Error(`Could not parse Python version from: ${e.trim()}`);if(!r[1].startsWith(t.replace(/\.\*$/,"")))throw new Error(`Python version mismatch: found ${r[1]}, expected ${t}`)}catch(t){throw new Error(`Python version check failed at ${n}: ${t.message}`)}}return n}class Kt{static STATUS_CHECKING=0;static STATUS_INSTALLING=1;static STATUS_SUCCESSED=2;static STATUS_FAILED=3;constructor(t,e,n={}){this.stateStorage=t,this.onStatusChange=e,this.params=n,this._status=Kt.STATUS_CHECKING}get name(){return"Stage"}get status(){return this._status}set status(t){this._status=t,this.onStatusChange()}get stateKey(){return this.name.toLocaleLowerCase().replace(/\s+/g,"-")}get state(){return this.stateStorage.getValue(this.stateKey)}set state(t){this.stateStorage.setValue(this.stateKey,t)}check(){throw new Error("Stage must implement a `check` method")}install(){throw new Error("Stage must implement an `install` method")}destroy(){}}class zt{constructor(t){this.projectDir=t,this._data=void 0}async read(){const t=await U(["-c",'\nimport json\nfrom platformio.public import ProjectConfig\n\nconfig = ProjectConfig()\nenvs = config.envs()\n\ndef _monitor_speed(env):\n value = config.get(f"env:{env}", "monitor_speed", default=None)\n if value is None:\n return None\n try:\n return int(value)\n except (TypeError, ValueError):\n return None\n\nprint(json.dumps(dict(\n envs=envs,\n default_envs=config.default_envs(),\n default_env=config.get_default_env(),\n env_platforms={env:config.get(f"env:{env}", "platform", default=None) for env in envs},\n env_monitor_speeds={env:_monitor_speed(env) for env in envs}\n)))\n'],{projectDir:this.projectDir});this._data=JSON.parse(t.trim())}envs(){return this._data.envs}defaultEnvs(){return this._data.default_envs}defaultEnv(){return this._data.default_env}getEnvPlatform(t){return this._data.env_platforms[t]}getEnvMonitorSpeed(t){return(this._data.env_monitor_speeds||{})[t]??void 0}}class Qt{static AUTO_REBUILD_DELAY=3;static FLOOD_TIME_WINDOW=600;static FLOOD_MAX_ATTEMPTS=30;constructor(t,e,n){this.projectDir=t,this.options=e,this.observer=n,this._rebuildTimeout=void 0,this._inProgress=!1,this._floodStartedAt=Date.now(),this._floodAttempts=0}dispose(){this._rebuildTimeout&&clearTimeout(this._rebuildTimeout)}requestRebuild(){if(Date.now()-this._floodStartedAt<1e3*Qt.FLOOD_TIME_WINDOW?this._floodAttempts++:(this._floodAttempts=0,this._floodStartedAt=Date.now()),this._rebuildTimeout&&(clearTimeout(this._rebuildTimeout),this._rebuildTimeout=void 0),this._floodAttempts>=Qt.FLOOD_MAX_ATTEMPTS){if(this._floodAttempts===Qt.FLOOD_MAX_ATTEMPTS&&this.options.api.onDidNotifyError){const t=`Multiple requests to rebuild the project "${w().basename(this.projectDir)}" index have been received!\nAutomatic index rebuilding process has been terminated for ${Qt.FLOOD_TIME_WINDOW/60} minutes.`;this.options.api.onDidNotifyError(t,new Error(t))}}else this._rebuildTimeout=setTimeout(this.rebuild.bind(this),1e3*Qt.AUTO_REBUILD_DELAY)}rebuild(){if(!this._inProgress)return this.options.api.withIndexRebuildingProgress(this._rebuildWithProgress.bind(this))}async _rebuildWithProgress(t=void 0,e=void 0){t||(t=()=>{}),this._inProgress=!0,this.options.api.logOutputChannel&&this.options.api.logOutputChannel.clear();const n=(e,n=!1)=>{t(e.toString().trim()),this.options.api.logOutputChannel&&(this.options.api.logOutputChannel.append(e.toString()),n&&this.options.api.logOutputChannel.show(),n&&this.options.api.logOutputChannel.appendLine(""))};try{const t=Et(this.observer.getSelectedEnv(),this.options.ide,this.options.intelliSenseBackend);await H(t,{projectDir:this.projectDir,runInQueue:!0,onProcCreated:t=>{e&&e.onCancellationRequested(()=>{n("Configuration process has been terminated!",!0),C(),t.kill()})},onProcStdout:t=>n(t),onProcStderr:t=>n(t,!0)}),this.options.api.onDidRebuildIndex&&Promise.resolve().then(()=>this.options.api.onDidRebuildIndex(this.projectDir)).catch(t=>{const e=`onDidRebuildIndex callback failed for project ${this.projectDir}:`;this.options.api.onDidNotifyError?this.options.api.onDidNotifyError(e,t):console.error(e,t)})}catch(t){console.warn(t),e&&e.isCancellationRequested||n(t,!0)}finally{this._inProgress=!1}}}class Zt{static WATCH_DIRS_UPDATE_DELAY=1e4;constructor(t,e){this.projectDir=t,this.options=e,this.subscriptions=[],this.dirWatchSubscriptions=[],this._cache=new Map,this._config=void 0,this._indexer=void 0,this._projectTasks=new At(this.projectDir,this.options.ide,this.options.intelliSenseBackend),this._updateDirWatchersTimeout=void 0,this._selectedEnv=void 0,this._apiConfigChangedTimeout=void 0,this.getSetting("autoRebuild")&&this.setupFSWatchers()}dispose(){K(this.dirWatchSubscriptions),K(this.subscriptions),this._updateDirWatchersTimeout&&clearTimeout(this._updateDirWatchersTimeout),this._indexer&&this._indexer.dispose(),this.resetCache()}activate(){console.info("Activating project",this.projectDir),this.rebuildIndex()}deactivate(){console.info("Deactivating project",this.projectDir)}getSetting(t){return(this.options.settings||{})[t]}resetCache(){this._cache.clear()}async getConfig(){return this._config||(this._config=new zt(this.projectDir),await this._config.read()),this._config}rebuildIndex({force:t=!1,delayed:e=!1}={}){if(t||this.getSetting("autoRebuild"))return this._indexer||(this._indexer=new Qt(this.projectDir,this.options,this)),e?this._indexer.requestRebuild():this._indexer.rebuild()}async switchProjectEnv(t){(await this.getConfig()).envs().includes(t)||(t=void 0),this._selectedEnv=t}getSelectedEnv(){return this._selectedEnv}async revealActiveEnvironment(){return this._selectedEnv?this._selectedEnv:(await this.getConfig()).defaultEnv()}async getDefaultTasks(){return this._projectTasks.getDefaultTasks()}async getLoadedEnvTasks(t,e={preload:!1}){const n=`envTasks${t}`;return this._cache.has(n)?this._cache.get(n):e.preload||this.getSetting("autoPreloadEnvTasks")||this._selectedEnv===t||1===(await this.getConfig()).envs().length?await this.loadEnvTasks(t):void 0}async loadEnvTasks(t){const e=`envTasks${t}`;return this._cache.has(e)||(this._cache.set(e,[]),this._cache.set(e,await this.options.api.withTasksLoadingProgress(async()=>await this._projectTasks.fetchEnvTasks(t)))),this._cache.get(e)}onDidChangeProjectConfig(){this._config=void 0,this.resetCache(),this.requestUpdateDirWatchers(),(this.options.api||{}).onDidChangeProjectConfig&&this.options.api.onDidChangeProjectConfig(w().join(this.projectDir,"platformio.ini"))}onDidChangeLibDirs(){this.rebuildIndex({delayed:!0})}setupFSWatchers(){const t=this.options.api.createFileSystemWatcher(w().join(this.projectDir,"platformio.ini"));this.subscriptions.push(t,t.onDidCreate(()=>this.onDidChangeProjectConfig()),t.onDidChange(()=>this.onDidChangeProjectConfig())),this.requestUpdateDirWatchers()}requestUpdateDirWatchers(){this._updateDirWatchersTimeout&&clearTimeout(this._updateDirWatchersTimeout),this._updateDirWatchersTimeout=setTimeout(this.updateDirWatchers.bind(this),Zt.WATCH_DIRS_UPDATE_DELAY)}async updateDirWatchers(){K(this.dirWatchSubscriptions);try{(await this.fetchLibDirs()).forEach(t=>{const e=this.options.api.createDirSystemWatcher(t);this.dirWatchSubscriptions.push(e,e.onDidCreate(()=>this.onDidChangeLibDirs()),e.onDidChange(()=>this.onDidChangeLibDirs()),e.onDidDelete(()=>this.onDidChangeLibDirs()))})}catch(t){console.warn(t)}}async fetchLibDirs(){const t=await U(["-c","\nimport json\nfrom platformio.public import get_project_watch_lib_dirs\nprint(json.dumps(get_project_watch_lib_dirs()))\n"],{projectDir:this.projectDir});return JSON.parse(t.trim())}}const te=require("dns");var ee=u(924),ne=u.n(ee);const oe=(0,jt.promisify)(te.lookup),re=(0,jt.promisify)(u(317).execFile),ie=u(330).rE;class se extends Kt{static getBuiltInPythonDir(){return w().join(L(),"penv")}static getBuiltInPythonBinDir(){const t=se.getBuiltInPythonDir();return P?w().join(t,"Scripts"):w().join(t,"bin")}static async findBuiltInPythonExe(){const t=se.getBuiltInPythonDir();if(P){const e="python.exe",n=[w().join(t,e),w().join(t,"Scripts",e)];for(const t of n)try{return await v.promises.access(t),t}catch(t){}return n[0]}return w().join(t,"bin","python3")}static getBuiltInPythonExe(){const t=se.getBuiltInPythonDir();return P?w().join(t,"python.exe"):w().join(t,"bin","python3")}constructor(){super(...arguments)}get name(){return"pioarduino Core"}async hasInternetConnection(){try{return await oe("1.1.1.1"),!0}catch(t){return console.info("No internet connection detected"),!1}}async checkPlatformIOOnline(){try{const t=await I("platformio",["--version"],{timeout:1e4});return console.info("PlatformIO online check successful:",t.trim()),!0}catch(t){return console.warn("PlatformIO online check failed:",t.message),!1}}async check(){if(this.params.useBuiltinPIOCore)try{const t=w().join(L(),"penv");await v.promises.access(t),console.info("PlatformIO installation detected at:",t);const e=se.getBuiltInPythonBinDir();b("PLATFORMIO_PATH",[e,w().join(L(),"penv")]);const n=await se.findBuiltInPythonExe();try{await v.promises.access(n),x({core_dir:L(),python_exe:n,penv_bin_dir:e})}catch(t){throw console.warn("Python executable not found at:",n),new Error("pioarduino Core installation is incomplete - Python not found!")}if(this.params.useBuiltinPython&&(await this.checkPythonOffline()||console.warn("Python check failed, but continuing with existing installation"),await Vt(t)),await this.hasInternetConnection()){if(!await this.checkPlatformIOOnline())throw console.warn("PlatformIO online check failed, triggering reinstall..."),this.status=Kt.STATUS_FAILED,new Error("PlatformIO installation is corrupted and needs to be reinstalled!")}else console.info("Skipping PlatformIO online check (no internet connection)")}catch(t){if("ENOENT"===t.code||t.message.includes("ENOENT")||t.message.includes("no such file")||t.message.includes("not been installed"))throw new Error("pioarduino Core has not been installed yet!");throw t}else try{const t=await Xt();if(!t)throw new Error("No Python found for global PlatformIO");if(x({core_dir:L(),python_exe:t}),console.info("Using system Python for global PlatformIO:",t),await this.hasInternetConnection()){if(!await this.checkPlatformIOOnline())throw new Error("Could not find compatible pioarduino Core. Please enable `pioarduino-ide.useBuiltinPIOCore` setting and restart IDE.")}else console.info("Offline mode: assuming global PlatformIO installation exists")}catch(t){throw console.warn("Global PIO setup failed:",t.message),new Error("Could not find compatible pioarduino Core. Please enable `pioarduino-ide.useBuiltinPIOCore` setting and restart IDE.")}return this.status=Kt.STATUS_SUCCESSED,!0}async loadCoreState(){const t=F(),e=M(),n=!this.params.useBuiltinPIOCore,o=n?await this.whereIsPython():await se.findBuiltInPythonExe(),r=n?D(P?"platformio.exe":"platformio"):w().join(e,P?"platformio.exe":"platformio");if(!r)throw n?new Error(`pioarduino executable \`${P?"platformio.exe":"platformio"}\` not found on system PATH (searched via proc.whereIsProgram)`):new Error(`pioarduino executable not found in \`${e}\``);try{await v.promises.access(r)}catch{throw n?new Error(`pioarduino executable \`${r}\` not found on system PATH`):new Error(`pioarduino executable not found at \`${r}\` in ${e}`)}try{await re(r,["--help"],{timeout:3e4})}catch(t){throw new Error(`Could not run \`${r} --help\`. Error: ${t.message}`)}let i,s;try{({coreVersion:i,pythonVersion:s}=await this.probePioCoreVersion(o))}catch(t){throw new Error(`Could not import pioarduino module. Error: ${t.message}`)}const a=this.useDevCore()||(i||"").includes("-"),c={core_version:i,python_version:s,core_dir:L(),cache_dir:R(),penv_dir:t,penv_bin_dir:e,platformio_exe:r,installer_version:ie,python_exe:o,system:S(),is_develop_core:a};if(this.params.pioCoreVersionSpec&&i){const t=ne().valid(i)||ne().coerce(i);if(t&&!ne().satisfies(t,this.params.pioCoreVersionSpec,{includePrerelease:!0}))throw new Error(`pioarduino Core version ${i} does not match version requirements ${this.params.pioCoreVersionSpec}.`)}if(!n&&!this.params.disableAutoUpdates){await this.autoUpgradeCore(r,a);try{const t=await this.probePioCoreVersion(o);c.core_version=t.coreVersion,c.python_version=t.pythonVersion}catch{}}return console.info("PIO Core State",c),x(c),!0}async probePioCoreVersion(t){const{stdout:e}=await re(t,["-c",'import json, platform, platformio; print(json.dumps({"core_version": platformio.__version__, "python_version": platform.python_version()}))'],{timeout:15e3}),n=JSON.parse(e.trim());return{coreVersion:n.core_version,pythonVersion:n.python_version}}async autoUpgradeCore(t,e){const n=w().join(L(),"state.json");let o={};try{const t=await v.promises.readFile(n,"utf-8");o=JSON.parse(t)}catch{}const r=Math.round(Date.now()/1e3),i=o.last_piocore_version_check;if(i&&r-i<2678400)return;if(!i)return o.last_piocore_version_check=r,void await v.promises.writeFile(n,JSON.stringify(o,null,2),"utf-8");const s=["upgrade"];e&&s.push("--dev");try{await re(t,s,{timeout:3e5}),console.info("PlatformIO Core upgraded successfully")}catch(t){console.warn(`Could not upgrade pioarduino Core: ${t.message}`)}o.last_piocore_version_check=r,await v.promises.writeFile(n,JSON.stringify(o,null,2),"utf-8")}useDevCore(){return this.params.useDevelopmentPIOCore||(this.params.pioCoreVersionSpec||"").includes("-")}async checkPythonOffline(){if(!this.params.useBuiltinPython)return!0;try{const t=se.getBuiltInPythonDir();await v.promises.access(t);const e=await se.findBuiltInPythonExe();await v.promises.access(e);const n=await this.checkPythonVersionOffline(e);return console.info(`Built-in Python ${n} is valid for offline use`),!0}catch(t){return console.warn("Built-in Python check failed:",t.message),!1}}async checkPythonVersionOffline(t){try{const e=(await I(t,["-c","import sys; print(sys.version)"],{timeout:5e3})).match(/^(\d+)\.(\d+)\.(\d+)/);if(e){const t=parseInt(e[1]),n=parseInt(e[2]);if(3===t&&13===n)return console.info(`Python ${e[0]} detected (offline check)`),e[0];throw new Error(`Python ${e[0]} found, but Python 3.13 is required`)}throw new Error("Could not determine Python version")}catch(t){throw new Error(`Python version check failed: ${t.message}`)}}async isBuiltinPythonOutdated(){if(!this.params.useBuiltinPython)return!1;const t=se.getBuiltInPythonDir();try{await v.promises.access(t);const e=$();if(e.python_version){if(!/^3\.13\./.test(e.python_version))throw new Error("Python is not 3.13 in penv (Python 3.13 required)");return!1}return console.info("No Python version info available, assuming existing installation is valid"),!1}catch(t){return!!t.message.includes("Python is not 3.13")&&(console.info("Upgrading built-in Python..."),!0)}}async whereIsPython({prompt:t=!1}={}){let e=this.params.pythonPrompt.STATUS_TRY_AGAIN;if(!t){if(this.params.useBuiltinPython)try{const t=await Yt("3.13");return console.info("Using UV-managed Python:",t),t}catch(t){console.info("UV-managed Python not found, searching system PATH")}return await Xt()}do{if(this.params.useBuiltinPython)try{const t=await Yt("3.13");return console.info("Using UV-managed Python:",t),t}catch(t){console.info("UV-managed Python not found, searching system PATH")}const t=await Xt();if(t)return t;const n=await this.params.pythonPrompt.prompt();e=n.status,e===this.params.pythonPrompt.STATUS_CUSTOMEXE&&n.pythonExecutable&&b("PLATFORMIO_PATH",[w().dirname(n.pythonExecutable)])}while(e!==this.params.pythonPrompt.STATUS_ABORT);throw this.status=Kt.STATUS_FAILED,new Error("Can not find Python Interpreter. Please install Python 3.13")}async install(t=void 0){if(this.status===Kt.STATUS_SUCCESSED)return!0;if(!this.params.useBuiltinPIOCore)throw this.status=Kt.STATUS_FAILED,new Error("Could not find compatible pioarduino Core. Please enable `pioarduino-ide.useBuiltinPIOCore` setting and restart IDE.");this.status=Kt.STATUS_INSTALLING,t||(t=()=>{}),t("Preparing for installation",10);try{t("Installing UV package manager",20);let e,n=await Bt();if(console.info("UV available at:",n),this.params.useBuiltinPython)t("Creating virtual environment with Python 3.13",40),e=await async function(){Mt("info","Installing uv and creating Python 3.13 virtual environment");const t=await Bt();Mt("info",`Using uv: ${t}`);const e=F();if(!await Wt(t,e))throw new Error("Could not create PIO Core Virtual Environment. Please report to https://github.com/pioarduino/pioarduino-core-installer/issues");await qt();const n=w().join(e,Ft,kt);return Mt("info",`Python available at: ${n}`),n}(),console.info("Python installed at:",e);else{const o=await this.whereIsPython({prompt:!0});t("Creating virtual environment with system Python",40);const r=F();await Wt(n,r,o),await qt();const i=se.getBuiltInPythonBinDir();e=w().join(i,P?"python.exe":"python3"),console.info("Venv created with system Python, Python at:",e)}n=await Bt(),t("Installing PlatformIO Core",60);const o=F();await async function(t,e,n=!1,o=null){const r=o||w().join(e,Ft,kt),i=n?"https://github.com/pioarduino/platformio-core/archive/pioarduino.zip":"pioarduino";Mt("info",`Installing PlatformIO Core using uv (develop=${n})`);try{Mt("info",`PlatformIO install output: ${(await $t(t,["pip","install","--python",r,i],{timeout:9e5})).stdout||""}`)}catch(t){const e=P?`If you have antivirus/firewall/defender software, try to disable it.\n${t.message}`:t.message;throw new Error(`Could not install pioarduino Core with uv: ${e}`)}}(n,o,this.useDevCore(),e),console.info("PlatformIO Core installed successfully"),t("Loading pioarduino Core state",80),await this.loadCoreState(),t("Installing pioarduino Home",90),await this.installPIOHome()}catch(t){throw Q(t),t}return t("Completed!",100),!0}async installPIOHome(){try{await H(["home","--host","__do_not_start__"])}catch(t){console.warn(t)}}}const ae={BaseStage:Kt,pioarduinoCoreStage:se,createVenvWithUv:Wt,ensurePipInPenv:Vt},ce={ProjectConfig:zt,ProjectPool:class{constructor(t){this.options=t||{},this._observers=[],this._activeProjectDir=void 0}getActiveProjectDir(){return this._activeProjectDir}getActiveObserver(){return this._activeProjectDir?this.getObserver(this._activeProjectDir):void 0}getObserver(t){if(!t)return;let e=this._observers.find(e=>e.projectDir===t);return e||(e=new Zt(t,this.options),this._observers.push(e)),e}async switch(t){this._activeProjectDir=t,console.info("Switching project to",t),this._observers.filter(e=>e.projectDir!==t).forEach(t=>t.deactivate());const e=this.getObserver(t);return await e.activate(),e}dispose(){K(this._observers)}},ProjectTasks:At,TaskItem:It};return l})()); //# sourceMappingURL=index.js.map