node-karin 1.8.0 → 1.8.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.
- package/CHANGELOG.md +835 -819
- package/README.md +32 -0
- package/default/config/adapter.json +27 -27
- package/default/config/config.json +44 -44
- package/default/config/groups.json +66 -66
- package/default/config/pm2.json +15 -15
- package/default/config/privates.json +25 -25
- package/default/config/redis.json +5 -5
- package/default/config/render.json +18 -18
- package/dist/cli/index.cjs +1 -1
- package/dist/cli/index.mjs +6609 -24
- package/dist/global.d.d.ts +48 -48
- package/dist/index.mjs +34 -12
- package/dist/web/assets/css/index-BrG42AwU.css.br +0 -0
- package/dist/web/assets/js/components-CxadY39V.js.br +0 -0
- package/dist/web/assets/js/entry-CHFt_H9g.js.br +0 -0
- package/dist/web/assets/js/hooks-DCwZcclx.js.br +0 -0
- package/dist/web/assets/js/page-404.tsx-DuSCXxgV.js +1 -0
- package/dist/web/assets/js/page-dashboard-DeOjlIBI.js.br +0 -0
- package/dist/web/assets/js/page-loading.tsx-DGpPkY1i.js.br +0 -0
- package/dist/web/assets/js/page-login.tsx-Uw_-NauC.js.br +0 -0
- package/dist/web/assets/js/{utils-Cj3xTboC.js → utils-qrmq67Xg.js} +1 -1
- package/dist/web/assets/js/vendor-heroui-CWZ6Mu45.js.br +0 -0
- package/dist/web/assets/js/vendor-others-BM6DakDu.js.br +0 -0
- package/dist/web/assets/js/vendor-react-BFjuLQyM.js.br +0 -0
- package/dist/web/assets/js/vendor-visual-CzYP84zg.js.br +0 -0
- package/dist/web/grid.svg +5 -5
- package/dist/web/icon.css +24 -24
- package/dist/web/index.html +32 -32
- package/dist/web/sha256.min.js.br +0 -0
- package/package.json +192 -192
- package/dist/web/assets/css/index-DxLRZkvi.css.br +0 -0
- package/dist/web/assets/js/components-Bp80gYJA.js.br +0 -0
- package/dist/web/assets/js/entry-DhKjPdoJ.js.br +0 -0
- package/dist/web/assets/js/hooks-CSKAeqvP.js.br +0 -0
- package/dist/web/assets/js/page-404.tsx-Dr2zAhTf.js +0 -1
- package/dist/web/assets/js/page-dashboard-B6B4ob8B.js.br +0 -0
- package/dist/web/assets/js/page-loading.tsx-g_ta_NRr.js.br +0 -0
- package/dist/web/assets/js/page-login.tsx-Cm98Ubip.js.br +0 -0
- package/dist/web/assets/js/vendor-heroui-CMeNhCFh.js.br +0 -0
- package/dist/web/assets/js/vendor-others-Bv0hrdEA.js.br +0 -0
- package/dist/web/assets/js/vendor-react-ChUmQ3I2.js.br +0 -0
- package/dist/web/assets/js/vendor-visual-CdiJEXnN.js.br +0 -0
package/dist/cli/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";const t=require("node:fs"),e=require("node:url"),i=require("node:path"),n=require("node:child_process"),s=require("node:stream/promises"),r=require("node:events"),o=require("node:process");var a="undefined"!=typeof document?document.currentScript:null;const c=(t,e={})=>{try{return{status:!0,error:null,stdout:n.execSync(t,e).toString(),stderr:""}}catch(i){return{status:!1,error:i,stdout:"",stderr:""}}},l=(t,e={})=>new Promise((i=>{n.exec(t,e,((t,e,n)=>{i({status:!t,error:t,stdout:e,stderr:n})}))})),p=i.join(process.cwd(),"@karinjs/config/pm2.json"),h=()=>t.existsSync(p)?JSON.parse(t.readFileSync(p,"utf-8")):(console.log(`[pm2] 配置文件不存在 请检查 ${p} 是否存在`),null),u=async(e,n,r,o)=>{if(!t.existsSync(e))return!1;const a=t.statSync(e),c=1024*o*1024;if(a.size<c)return!1;const l=i.basename(e),p=`${l}.${Date.now()}`,h=i.join(n,p),u=i.join(n,`${l}.temp`);try{const i=t.createReadStream(e),n=t.createWriteStream(h);await s.pipeline(i,n);const o=t.statSync(e).mode;return t.writeFileSync(u,""),t.chmodSync(u,o),t.renameSync(u,e),console.log(`[pm2] 日志已按大小切割: ${r} => ${p} (${(a.size/1024/1024).toFixed(2)}MB)`),!0}catch(m){return console.error(`[pm2] 切割日志失败: ${r}`,m),t.existsSync(u)&&t.unlinkSync(u),!1}},m=async()=>{const e=h();var n;if(e)try{const s=Number(e.maxLogFiles)??10,r=Number(e.maxErrorLogSize)??50,o=Number(e.maxOutLogSize)??50;if(0===s)return;const a=i.resolve(process.cwd(),e.apps[0].error_file),c=i.resolve(process.cwd(),e.apps[0].out_file),l=i.dirname(a);if(n=l,!t.existsSync(n)&&(t.mkdirSync(n,{recursive:!0}),console.log(`[pm2] 创建日志目录: ${n}`),1))return;const p=i.basename(a),h=i.basename(c);await u(c,l,"输出",o),await u(a,l,"错误",r),((e,n,s,r)=>{if(r<=0)return;const o=t.readdirSync(s),a=(e,n)=>{const a=new RegExp(`^${e.replace(/\./g,"\\.")}\\.(\\d+)$`),c=o.filter((t=>a.test(t))).map((t=>{const e=t.match(a);return{file:t,timestamp:e?parseInt(e[1],10):0}})).sort(((t,e)=>e.timestamp-t.timestamp));c.length>r&&c.slice(r).forEach((e=>{const r=i.join(s,e.file);t.unlinkSync(r),console.log(`[pm2] 删除过期${n}日志: ${e.file}`)}))};a(e,"错误"),a(n,"输出")})(p,h,l,s)}catch(s){console.error("[pm2] 日志切割过程中发生错误:",s)}},d=async()=>{m(),console.log("[pm2] 启动中...");const e=h();e||process.exit(1),(e=>{const i="index.mjs";e.apps[0].script!==i&&(e.apps[0].script=i,t.writeFileSync(p,JSON.stringify(e,null,2)))})(e),t.existsSync("index.mjs")||(console.log("正在升级到1.8.0版本..."),c("npx ki init",{cwd:process.cwd()}),console.log("升级成功 正在启动pm2服务..."));const{error:i}=c(`pm2 start ${p}`,{cwd:process.cwd()});i&&(console.log("[pm2] 启动失败"),console.log(i),process.exit(1)),console.log("[pm2] 启动成功"),console.log("[pm2] 重启服务: pnpm rs"),console.log("[pm2] 查看日志: pnpm log"),console.log("[pm2] 停止服务: pnpm stop"),console.log("[pm2] 查看监控: pm2 monit"),console.log("[pm2] 查看列表: pm2 list"),process.exit(0)},g=async()=>{m();const t=h();t||(console.log("[pm2] 如果是新项目,请先前台启动生成配置文件: pnpm app"),process.exit(1));try{const e="win32"===process.platform?"pm2.cmd":"pm2";n.spawn(e,["logs",t.apps[0].name,"--lines",t.lines||1e3],{stdio:"inherit",shell:!0})}catch(e){console.error("[pm2] 发生未知错误: 请检查pm2是否安装 【npm install -g pm2】"),console.error(e),process.exit(1)}},f=async()=>{m();const t=h();t||(console.log("[pm2] 如果是新项目,请先前台启动生成配置文件: pnpm app"),process.exit(1)),c(`pm2 stop ${t.apps[0].name}`,{cwd:process.cwd()}),console.log("[pm2] 停止成功"),process.exit(0)},_=async e=>{m(),console.log("[pm2] 重启中..."),t.existsSync(p)||e||(console.log(`[pm2] 配置文件不存在 请检查 ${p} 是否存在`),console.log("[pm2] 如果是新项目,请先前台启动生成配置文件: pnpm app"),process.exit(1));const i=e?"karin":h()?.apps[0].name;i||process.exit(1),c(`pm2 delete ${i}`,{cwd:process.cwd()}),c(`pm2 start ${p}`,{cwd:process.cwd()}),console.log("[pm2] 重启成功"),process.exit(0)},y=e=>{var n;n=i.join(e,"@karinjs"),t.existsSync(n)&&t.rmSync(n,{recursive:!0,force:!0});const s=i.join(e,".pnpmfile.cjs");t.existsSync(s)&&t.unlinkSync(s);const r=i.join(e,"index.mjs");t.existsSync(r)&&t.unlinkSync(r);const o=i.join(e,".env");t.existsSync(o)&&t.unlinkSync(o)},O=async n=>{const s=process.env.INIT_CWD||process.cwd(),r=(e=>"development"===process.env.NODE_ENV||["src","tsconfig.json","eslint.config.mjs","eslint.config.js",".prettierrc","vite.config.ts","tsup.config.ts"].some((n=>t.existsSync(i.join(e,n)))))(s);n&&y(s),((e,n)=>{if(["logs","config","data","resource","temp/console","temp/html"].forEach((e=>{const s=i.join(n,"@karinjs",e);t.existsSync(s)||t.mkdirSync(s,{recursive:!0})})),e)return;const s=i.join(n,"plugins","karin-plugin-example");t.existsSync(s)||t.mkdirSync(s,{recursive:!0})})(r,s),((e,n)=>{if(e)return;const s=i.join(n,"pnpm-workspace.yaml");if(t.existsSync(s))return;t.writeFileSync(s,"packages:\n - 'plugins/*'\n")})(r,s),(n=>{const s=e.fileURLToPath(new e.URL("../..","undefined"==typeof document?require("url").pathToFileURL(__filename).href:a&&"SCRIPT"===a.tagName.toUpperCase()&&a.src||new URL("index.cjs",document.baseURI).href)),r=i.join(s,"default","config");t.readdirSync(r).forEach((e=>{if(!e.endsWith(".json"))return;const s=i.join(r,e),o=i.join(n,"@karinjs","config"),a=i.join(o,e);if(!t.existsSync(a))return void t.copyFileSync(s,a);const c=t.readFileSync(s,"utf-8"),l=t.readFileSync(a,"utf-8"),p={...JSON.parse(c),...JSON.parse(l)};e.includes("pm2.json")&&(p.apps[0].script="index.mjs"),t.writeFileSync(a,JSON.stringify(p,null,2))}))})(s),((e,n)=>{const s=i.join(n,"package.json"),r=(()=>{try{return JSON.parse(t.readFileSync(s,"utf-8"))}catch{return{}}})();r.scripts||(r.scripts={}),r.name||(r.name="karin-project"),r.version||(r.version="1.0.0"),r.type="module",e||(r.scripts.ki||(r.scripts.ki="ki"),r.scripts.karin||(r.scripts.karin="ki"),r.scripts.app||(r.scripts.app="node index.mjs"),r.scripts.start||(r.scripts.start="node index.mjs"),r.scripts.pm2||(r.scripts.pm2="pm2 start @karinjs/config/pm2.json"),r.scripts.stop||(r.scripts.stop="ki stop"),r.scripts.rs||(r.scripts.rs="ki rs"),r.scripts.log||(r.scripts.log="ki log"),r.scripts.up||(r.scripts.up="ki up")),e||r?.dependencies?.["node-karin"]||(r.dependencies||(r.dependencies={}),r.dependencies["node-karin"]="latest"),r.pnpm&&delete r.pnpm,t.writeFileSync(s,JSON.stringify(r,null,2))})(r,s),(e=>{const n=["package-lock=false","public-hoist-pattern[]=*sqlite3*","public-hoist-pattern[]=*express*","sqlite3_binary_host_mirror=https://registry.npmmirror.com/-/binary/sqlite3","node_sqlite3_binary_host_mirror=https://registry.npmmirror.com/-/binary/sqlite3","better_sqlite3_binary_host_mirror=https://registry.npmmirror.com/-/binary/better-sqlite3","sass_binary_site=https://registry.npmmirror.com/-/binary/node-sass","sharp_binary_host=https://registry.npmmirror.com/-/binary/sharp","sharp_libvips_binary_host=https://registry.npmmirror.com/-/binary/sharp-libvips","canvas_binary_host_mirror=https://registry.npmmirror.com/-/binary/canvas","# 19以下版本","puppeteer_download_host=https://registry.npmmirror.com/mirrors","# 20以上版本","PUPPETEER_DOWNLOAD_BASE_URL = https://registry.npmmirror.com/binaries/chrome-for-testing"],s=i.join(e,".npmrc");if(!t.existsSync(s))return void t.writeFileSync(s,n.join("\n"));const r=t.readFileSync(s,"utf-8"),o=r.split("\n").map((t=>t.trim())),a=n.filter((t=>{if(t.startsWith("public-hoist-pattern[]="))return!o.includes(t);const e=t.split("=")[0];return!r.includes(e)}));a.length>0&&t.appendFileSync(s,"\n"+a.join("\n"))})(s),((e,n)=>{if(e)return;const s=i.join(n,".pnpmfile.cjs");if(t.existsSync(s))return;const r=["// 清空对等依赖中的node-karin","function readPackage (pkg, context) {"," if (pkg?.['peerDependencies']?.['node-karin'] && pkg['peerDependencies']['node-karin'] !== 'file:./lib') {"," delete pkg['peerDependencies']['node-karin']"," }"," return pkg","}","module.exports = {"," hooks: {"," readPackage"," },","}"].join("\n");t.writeFileSync(s,r)})(r,s),((e,n)=>{if(e&&t.existsSync(`${n}/src`))return void t.writeFileSync(i.join(n,"src","app.ts"),"import('node-karin/start')");const s=i.join(n,"index.mjs");t.existsSync(s)||t.writeFileSync(s,"(() => {\n import('node-karin/start')\n})()\n")})(r,s),(e=>{const n=t=>{if("http"===t&&process.env.HTTP_AUTH_KEY)return process.env.HTTP_AUTH_KEY;if("ws"===t&&process.env.WS_SERVER_AUTH_KEY)return process.env.WS_SERVER_AUTH_KEY;const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";return Array.from({length:6},(()=>e.charAt(Math.floor(62*Math.random())))).join("")},s=["# 是否启用HTTP","HTTP_ENABLE=true","# HTTP监听端口","HTTP_PORT=7777","# HTTP监听地址","HTTP_HOST=0.0.0.0","# HTTP鉴权秘钥 仅用于karin自身Api",`HTTP_AUTH_KEY=${n("http")}`,"# ws_server鉴权秘钥",`WS_SERVER_AUTH_KEY=${n("ws")}`,"\n","# 是否启用Redis 关闭后将使用内部虚拟Redis","REDIS_ENABLE=true","# 重启是否调用pm2 如果不调用则会直接关机 此配置适合有进程守护的程序","PM2_RESTART=true","\n","# 日志等级","LOG_LEVEL=info","# 日志保留天数","LOG_DAYS_TO_KEEP=7","# 日志文件最大大小 如果此项大于0则启用日志分割","LOG_MAX_LOG_SIZE=0","# logger.fnc颜色",'LOG_FNC_COLOR="#E1D919"',"# 日志实时Api最多支持同时连接数","LOG_API_MAX_CONNECTIONS=5","\n","# ffmpeg","FFMPEG_PATH=","# ffprobe","FFPROBE_PATH=","# ffplay","FFPLAY_PATH=","RUNTIME=node","NODE_ENV=production","TSX_WATCH=false"],r=i.join(e,".env");if(!t.existsSync(r))return void t.writeFileSync(r,s.join("\n"));const o=t.readFileSync(r,"utf-8"),a=s.filter((t=>{if(t.includes("#"))return!1;const e=t.split("=")[0];return!o.includes(e)}));a.length>0&&t.appendFileSync(r,"\n"+a.join("\n"))})(s),process.env.KARIN_CLI&&(console.log("[cli] 初始化完成 请使用 pnpm app 启动项目"),process.exit(0))},v=async()=>{const t=i.join(process.cwd(),"index.mjs");await import(e.pathToFileURL(t).toString())},w=(t,e)=>new Promise((i=>{const s=setTimeout((()=>{i({status:!1,error:new Error("命令执行超时"),stdout:"",stderr:"命令执行超时"})}),1e3*(e?.timeout||30)),r=n.exec(t,e,((t,e,n)=>{clearTimeout(s),n=n.toString().trim(),e=e.toString().trim();i({status:!t,error:t,stdout:e,stderr:n})}));r.stdin?.write("\n")})),C=(t,e)=>{if(t.error||"string"!=typeof t.stdout)throw t.error||new Error("stdout 类型错误");return t.stdout},A=async(t,e)=>{const i=await w("git rev-parse HEAD",{cwd:t});return C(i)},b=(t,e,i,n,s="")=>({status:t,data:"string"==typeof n?n:`${s}${n.message||n.stack||"未知错误"}`,hash:{before:e,after:i}}),S=async(t,e={})=>{try{const i=await A(t),n=await(async t=>{let e="origin/HEAD";e.startsWith("origin/")||(e=`origin/${e}`);const i=`git rev-parse ${e}`,n=await w(i,{cwd:t});return C(n)})(t);if(i===n)return b(!1,i,n,"当前已经是最新版本");if(e.force){const s=e.remote||"origin/HEAD",r=await w("git fetch origin",{cwd:t,...e});if(r.error)return b(!1,i,n,r.error,"同步远程分支失败: ");const o=await w(`git reset --hard ${s}`,{cwd:t,...e});if(o.error)return b(!1,i,n,o.error,"强制同步远程分支失败: ");const a=await A(t);return b(!0,i,a,"本地分支已强制与远程分支同步")}const s=e.customCmd||"git pull",{error:r}=await w(s,{...e,cwd:t});if(r)return b(!1,i,n,r,"更新失败: ");const o=await A(t);return b(!0,i,o,"更新成功")}catch(i){return b(!1,"","",i.message,"发生错误: ")}},x=async(e,i,n)=>{try{const s=JSON.parse(t.readFileSync(e,"utf-8")).dependencies||{},r=Object.entries(s).map((async([t,e])=>{if(!t.startsWith("@types/"))try{const{stdout:s}=await l(`pnpm view ${t} --json`);if(!JSON.parse(s.trim()).karin&&"node-karin"!==t)return;const r=e.replace(/[\^~]/g,""),{stdout:o}=await l(`pnpm view ${t} dist-tags --json`),a=JSON.parse(o.trim()),c=/[-+]/.test(r),p=a.latest;c||r!==p?(n.push(`${t}@latest`),i.push({name:t,type:"npm",currentVersion:`${r}${c?" (预发布)":""}`,latestVersion:p,status:`${r} -> ${p}`,needUpdate:!0,isPlugin:!0})):i.push({name:t,type:"npm",currentVersion:r,latestVersion:p,status:"已是最新",needUpdate:!1,isPlugin:!0})}catch(s){console.error(`检查 ${t} 版本失败:`,s)}}));await Promise.all(r)}catch(s){console.error("更新依赖失败:",s)}},E=async(e,i,n,s=!0)=>{if(!(await(async()=>{try{const{status:t}=await l("git --version");return t}catch{return!1}})()))return void console.error("请先安装git");if(!t.existsSync(e))return void console.error("plugins目录不存在");if(!(await t.promises.stat(e)).isDirectory())return void console.error("plugins路径不是一个目录");const r=await t.promises.readdir(e);if(s){const t=r.map((async t=>{await k(t,e,i,n)}));await Promise.all(t)}else for(const t of r)await k(t,e,i,n)},k=async(e,n,s,r)=>{const o=i.join(n,e),a=i.join(o,".git"),c=i.join(o,"package.json");if(e.startsWith("karin-plugin-")&&(await t.promises.stat(o)).isDirectory()&&!t.existsSync(a)){s.push({name:e,type:"git",currentVersion:"-",latestVersion:"-",status:"不是git仓库,已跳过",needUpdate:!1,isPlugin:!1});try{if(!JSON.parse(t.readFileSync(c,"utf-8")).karin)return void s.push({name:e,type:"git",currentVersion:"-",latestVersion:"-",status:"非Karin插件,已跳过",needUpdate:!1,isPlugin:!1});const{status:i,hash:n,data:a}=await S(o,{customCmd:"git pull",force:r});i?s.push({name:e,type:"git",currentVersion:n.before,latestVersion:n.after,status:"更新成功",needUpdate:!0,isPlugin:!0}):s.push({name:e,type:"git",currentVersion:"-",latestVersion:"-",status:`更新失败: ${a}`,needUpdate:!1,isPlugin:!0})}catch(l){s.push({name:e,type:"git",currentVersion:"-",latestVersion:"-",status:`处理失败: ${l}`,needUpdate:!1,isPlugin:!1})}}};function $(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var T,H,V={},j={},P={};function F(){if(T)return P;T=1;class t extends Error{constructor(t,e,i){super(i),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=e,this.exitCode=t,this.nestedError=void 0}}return P.CommanderError=t,P.InvalidArgumentError=class extends t{constructor(t){super(1,"commander.invalidArgument",t),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}},P}function N(){if(H)return j;H=1;const{InvalidArgumentError:t}=F();return j.Argument=class{constructor(t,e){switch(this.description=e||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,t[0]){case"<":this.required=!0,this._name=t.slice(1,-1);break;case"[":this.required=!1,this._name=t.slice(1,-1);break;default:this.required=!0,this._name=t}this._name.length>3&&"..."===this._name.slice(-3)&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(t,e){return e!==this.defaultValue&&Array.isArray(e)?e.concat(t):[t]}default(t,e){return this.defaultValue=t,this.defaultValueDescription=e,this}argParser(t){return this.parseArg=t,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(e,i)=>{if(!this.argChoices.includes(e))throw new t(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(e,i):e},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}},j.humanReadableArgName=function(t){const e=t.name()+(!0===t.variadic?"...":"");return t.required?"<"+e+">":"["+e+"]"},j}var D,W={},R={};function U(){if(D)return R;D=1;const{humanReadableArgName:t}=N();function e(t){return t.replace(/\x1b\[\d*(;\d*)*m/g,"")}return R.Help=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(t){this.helpWidth=this.helpWidth??t.helpWidth??80}visibleCommands(t){const e=t.commands.filter((t=>!t._hidden)),i=t._getHelpCommand();return i&&!i._hidden&&e.push(i),this.sortSubcommands&&e.sort(((t,e)=>t.name().localeCompare(e.name()))),e}compareOptions(t,e){const i=t=>t.short?t.short.replace(/^-/,""):t.long.replace(/^--/,"");return i(t).localeCompare(i(e))}visibleOptions(t){const e=t.options.filter((t=>!t.hidden)),i=t._getHelpOption();if(i&&!i.hidden){const n=i.short&&t._findOption(i.short),s=i.long&&t._findOption(i.long);n||s?i.long&&!s?e.push(t.createOption(i.long,i.description)):i.short&&!n&&e.push(t.createOption(i.short,i.description)):e.push(i)}return this.sortOptions&&e.sort(this.compareOptions),e}visibleGlobalOptions(t){if(!this.showGlobalOptions)return[];const e=[];for(let i=t.parent;i;i=i.parent){const t=i.options.filter((t=>!t.hidden));e.push(...t)}return this.sortOptions&&e.sort(this.compareOptions),e}visibleArguments(t){return t._argsDescription&&t.registeredArguments.forEach((e=>{e.description=e.description||t._argsDescription[e.name()]||""})),t.registeredArguments.find((t=>t.description))?t.registeredArguments:[]}subcommandTerm(e){const i=e.registeredArguments.map((e=>t(e))).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(i?" "+i:"")}optionTerm(t){return t.flags}argumentTerm(t){return t.name()}longestSubcommandTermLength(t,e){return e.visibleCommands(t).reduce(((t,i)=>Math.max(t,this.displayWidth(e.styleSubcommandTerm(e.subcommandTerm(i))))),0)}longestOptionTermLength(t,e){return e.visibleOptions(t).reduce(((t,i)=>Math.max(t,this.displayWidth(e.styleOptionTerm(e.optionTerm(i))))),0)}longestGlobalOptionTermLength(t,e){return e.visibleGlobalOptions(t).reduce(((t,i)=>Math.max(t,this.displayWidth(e.styleOptionTerm(e.optionTerm(i))))),0)}longestArgumentTermLength(t,e){return e.visibleArguments(t).reduce(((t,i)=>Math.max(t,this.displayWidth(e.styleArgumentTerm(e.argumentTerm(i))))),0)}commandUsage(t){let e=t._name;t._aliases[0]&&(e=e+"|"+t._aliases[0]);let i="";for(let n=t.parent;n;n=n.parent)i=n.name()+" "+i;return i+e+" "+t.usage()}commandDescription(t){return t.description()}subcommandDescription(t){return t.summary()||t.description()}optionDescription(t){const e=[];if(t.argChoices&&e.push(`choices: ${t.argChoices.map((t=>JSON.stringify(t))).join(", ")}`),void 0!==t.defaultValue){(t.required||t.optional||t.isBoolean()&&"boolean"==typeof t.defaultValue)&&e.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`)}return void 0!==t.presetArg&&t.optional&&e.push(`preset: ${JSON.stringify(t.presetArg)}`),void 0!==t.envVar&&e.push(`env: ${t.envVar}`),e.length>0?`${t.description} (${e.join(", ")})`:t.description}argumentDescription(t){const e=[];if(t.argChoices&&e.push(`choices: ${t.argChoices.map((t=>JSON.stringify(t))).join(", ")}`),void 0!==t.defaultValue&&e.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`),e.length>0){const i=`(${e.join(", ")})`;return t.description?`${t.description} ${i}`:i}return t.description}formatHelp(t,e){const i=e.padWidth(t,e),n=e.helpWidth??80;function s(t,n){return e.formatItem(t,i,n,e)}let r=[`${e.styleTitle("Usage:")} ${e.styleUsage(e.commandUsage(t))}`,""];const o=e.commandDescription(t);o.length>0&&(r=r.concat([e.boxWrap(e.styleCommandDescription(o),n),""]));const a=e.visibleArguments(t).map((t=>s(e.styleArgumentTerm(e.argumentTerm(t)),e.styleArgumentDescription(e.argumentDescription(t)))));a.length>0&&(r=r.concat([e.styleTitle("Arguments:"),...a,""]));const c=e.visibleOptions(t).map((t=>s(e.styleOptionTerm(e.optionTerm(t)),e.styleOptionDescription(e.optionDescription(t)))));if(c.length>0&&(r=r.concat([e.styleTitle("Options:"),...c,""])),e.showGlobalOptions){const i=e.visibleGlobalOptions(t).map((t=>s(e.styleOptionTerm(e.optionTerm(t)),e.styleOptionDescription(e.optionDescription(t)))));i.length>0&&(r=r.concat([e.styleTitle("Global Options:"),...i,""]))}const l=e.visibleCommands(t).map((t=>s(e.styleSubcommandTerm(e.subcommandTerm(t)),e.styleSubcommandDescription(e.subcommandDescription(t)))));return l.length>0&&(r=r.concat([e.styleTitle("Commands:"),...l,""])),r.join("\n")}displayWidth(t){return e(t).length}styleTitle(t){return t}styleUsage(t){return t.split(" ").map((t=>"[options]"===t?this.styleOptionText(t):"[command]"===t?this.styleSubcommandText(t):"["===t[0]||"<"===t[0]?this.styleArgumentText(t):this.styleCommandText(t))).join(" ")}styleCommandDescription(t){return this.styleDescriptionText(t)}styleOptionDescription(t){return this.styleDescriptionText(t)}styleSubcommandDescription(t){return this.styleDescriptionText(t)}styleArgumentDescription(t){return this.styleDescriptionText(t)}styleDescriptionText(t){return t}styleOptionTerm(t){return this.styleOptionText(t)}styleSubcommandTerm(t){return t.split(" ").map((t=>"[options]"===t?this.styleOptionText(t):"["===t[0]||"<"===t[0]?this.styleArgumentText(t):this.styleSubcommandText(t))).join(" ")}styleArgumentTerm(t){return this.styleArgumentText(t)}styleOptionText(t){return t}styleArgumentText(t){return t}styleSubcommandText(t){return t}styleCommandText(t){return t}padWidth(t,e){return Math.max(e.longestOptionTermLength(t,e),e.longestGlobalOptionTermLength(t,e),e.longestSubcommandTermLength(t,e),e.longestArgumentTermLength(t,e))}preformatted(t){return/\n[^\S\r\n]/.test(t)}formatItem(t,e,i,n){const s=" ".repeat(2);if(!i)return s+t;const r=t.padEnd(e+t.length-n.displayWidth(t)),o=(this.helpWidth??80)-e-2-2;let a;if(o<this.minWidthToWrap||n.preformatted(i))a=i;else{a=n.boxWrap(i,o).replace(/\n/g,"\n"+" ".repeat(e+2))}return s+r+" ".repeat(2)+a.replace(/\n/g,`\n${s}`)}boxWrap(t,e){if(e<this.minWidthToWrap)return t;const i=t.split(/\r\n|\n/),n=/[\s]*[^\s]+/g,s=[];return i.forEach((t=>{const i=t.match(n);if(null===i)return void s.push("");let r=[i.shift()],o=this.displayWidth(r[0]);i.forEach((t=>{const i=this.displayWidth(t);if(o+i<=e)return r.push(t),void(o+=i);s.push(r.join(""));const n=t.trimStart();r=[n],o=this.displayWidth(n)})),s.push(r.join(""))})),s.join("\n")}},R.stripColor=e,R}var I,L={};function q(){if(I)return L;I=1;const{InvalidArgumentError:t}=F();function e(t){return t.split("-").reduce(((t,e)=>t+e[0].toUpperCase()+e.slice(1)))}return L.Option=class{constructor(t,e){this.flags=t,this.description=e||"",this.required=t.includes("<"),this.optional=t.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(t),this.mandatory=!1;const i=function(t){let e,i;const n=/^-[^-]$/,s=/^--[^-]/,r=t.split(/[ |,]+/).concat("guard");n.test(r[0])&&(e=r.shift());s.test(r[0])&&(i=r.shift());!e&&n.test(r[0])&&(e=r.shift());!e&&s.test(r[0])&&(e=i,i=r.shift());if(r[0].startsWith("-")){const e=r[0],i=`option creation failed due to '${e}' in option flags '${t}'`;if(/^-[^-][^-]/.test(e))throw new Error(`${i}\n- a short flag is a single dash and a single character\n - either use a single dash and a single character (for a short flag)\n - or use a double dash for a long option (and can have two, like '--ws, --workspace')`);if(n.test(e))throw new Error(`${i}\n- too many short flags`);if(s.test(e))throw new Error(`${i}\n- too many long flags`);throw new Error(`${i}\n- unrecognised flag format`)}if(void 0===e&&void 0===i)throw new Error(`option creation failed due to no flags found in '${t}'.`);return{shortFlag:e,longFlag:i}}(t);this.short=i.shortFlag,this.long=i.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default(t,e){return this.defaultValue=t,this.defaultValueDescription=e,this}preset(t){return this.presetArg=t,this}conflicts(t){return this.conflictsWith=this.conflictsWith.concat(t),this}implies(t){let e=t;return"string"==typeof t&&(e={[t]:!0}),this.implied=Object.assign(this.implied||{},e),this}env(t){return this.envVar=t,this}argParser(t){return this.parseArg=t,this}makeOptionMandatory(t=!0){return this.mandatory=!!t,this}hideHelp(t=!0){return this.hidden=!!t,this}_concatValue(t,e){return e!==this.defaultValue&&Array.isArray(e)?e.concat(t):[t]}choices(e){return this.argChoices=e.slice(),this.parseArg=(e,i)=>{if(!this.argChoices.includes(e))throw new t(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(e,i):e},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return this.negate?e(this.name().replace(/^no-/,"")):e(this.name())}is(t){return this.short===t||this.long===t}isBoolean(){return!this.required&&!this.optional&&!this.negate}},L.DualOptions=class{constructor(t){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,t.forEach((t=>{t.negate?this.negativeOptions.set(t.attributeName(),t):this.positiveOptions.set(t.attributeName(),t)})),this.negativeOptions.forEach(((t,e)=>{this.positiveOptions.has(e)&&this.dualOptions.add(e)}))}valueFromOption(t,e){const i=e.attributeName();if(!this.dualOptions.has(i))return!0;const n=this.negativeOptions.get(i).presetArg,s=void 0!==n&&n;return e.negate===(s===t)}},L}var M,G,B,J={};function Y(){if(M)return J;M=1;return J.suggestSimilar=function(t,e){if(!e||0===e.length)return"";e=Array.from(new Set(e));const i=t.startsWith("--");i&&(t=t.slice(2),e=e.map((t=>t.slice(2))));let n=[],s=3;return e.forEach((e=>{if(e.length<=1)return;const i=function(t,e){if(Math.abs(t.length-e.length)>3)return Math.max(t.length,e.length);const i=[];for(let n=0;n<=t.length;n++)i[n]=[n];for(let n=0;n<=e.length;n++)i[0][n]=n;for(let n=1;n<=e.length;n++)for(let s=1;s<=t.length;s++){let r=1;r=t[s-1]===e[n-1]?0:1,i[s][n]=Math.min(i[s-1][n]+1,i[s][n-1]+1,i[s-1][n-1]+r),s>1&&n>1&&t[s-1]===e[n-2]&&t[s-2]===e[n-1]&&(i[s][n]=Math.min(i[s][n],i[s-2][n-2]+1))}return i[t.length][e.length]}(t,e),r=Math.max(t.length,e.length);(r-i)/r>.4&&(i<s?(s=i,n=[e]):i===s&&n.push(e))})),n.sort(((t,e)=>t.localeCompare(e))),i&&(n=n.map((t=>`--${t}`))),n.length>1?`\n(Did you mean one of ${n.join(", ")}?)`:1===n.length?`\n(Did you mean ${n[0]}?)`:""},J}const K=$(function(){if(B)return V;B=1;const{Argument:e}=N(),{Command:s}=function(){if(G)return W;G=1;const e=r.EventEmitter,s=n,a=i,c=t,l=o,{Argument:p,humanReadableArgName:h}=N(),{CommanderError:u}=F(),{Help:m,stripColor:d}=U(),{Option:g,DualOptions:f}=q(),{suggestSimilar:_}=Y();class y extends e{constructor(t){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=t||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:t=>l.stdout.write(t),writeErr:t=>l.stderr.write(t),outputError:(t,e)=>e(t),getOutHelpWidth:()=>l.stdout.isTTY?l.stdout.columns:void 0,getErrHelpWidth:()=>l.stderr.isTTY?l.stderr.columns:void 0,getOutHasColors:()=>v()??(l.stdout.isTTY&&l.stdout.hasColors?.()),getErrHasColors:()=>v()??(l.stderr.isTTY&&l.stderr.hasColors?.()),stripColor:t=>d(t)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings(t){return this._outputConfiguration=t._outputConfiguration,this._helpOption=t._helpOption,this._helpCommand=t._helpCommand,this._helpConfiguration=t._helpConfiguration,this._exitCallback=t._exitCallback,this._storeOptionsAsProperties=t._storeOptionsAsProperties,this._combineFlagAndOptionalValue=t._combineFlagAndOptionalValue,this._allowExcessArguments=t._allowExcessArguments,this._enablePositionalOptions=t._enablePositionalOptions,this._showHelpAfterError=t._showHelpAfterError,this._showSuggestionAfterError=t._showSuggestionAfterError,this}_getCommandAndAncestors(){const t=[];for(let e=this;e;e=e.parent)t.push(e);return t}command(t,e,i){let n=e,s=i;"object"==typeof n&&null!==n&&(s=n,n=null),s=s||{};const[,r,o]=t.match(/([^ ]+) *(.*)/),a=this.createCommand(r);return n&&(a.description(n),a._executableHandler=!0),s.isDefault&&(this._defaultCommandName=a._name),a._hidden=!(!s.noHelp&&!s.hidden),a._executableFile=s.executableFile||null,o&&a.arguments(o),this._registerCommand(a),a.parent=this,a.copyInheritedSettings(this),n?this:a}createCommand(t){return new y(t)}createHelp(){return Object.assign(new m,this.configureHelp())}configureHelp(t){return void 0===t?this._helpConfiguration:(this._helpConfiguration=t,this)}configureOutput(t){return void 0===t?this._outputConfiguration:(Object.assign(this._outputConfiguration,t),this)}showHelpAfterError(t=!0){return"string"!=typeof t&&(t=!!t),this._showHelpAfterError=t,this}showSuggestionAfterError(t=!0){return this._showSuggestionAfterError=!!t,this}addCommand(t,e){if(!t._name)throw new Error("Command passed to .addCommand() must have a name\n- specify the name in Command constructor or using .name()");return(e=e||{}).isDefault&&(this._defaultCommandName=t._name),(e.noHelp||e.hidden)&&(t._hidden=!0),this._registerCommand(t),t.parent=this,t._checkForBrokenPassThrough(),this}createArgument(t,e){return new p(t,e)}argument(t,e,i,n){const s=this.createArgument(t,e);return"function"==typeof i?s.default(n).argParser(i):s.default(i),this.addArgument(s),this}arguments(t){return t.trim().split(/ +/).forEach((t=>{this.argument(t)})),this}addArgument(t){const e=this.registeredArguments.slice(-1)[0];if(e&&e.variadic)throw new Error(`only the last argument can be variadic '${e.name()}'`);if(t.required&&void 0!==t.defaultValue&&void 0===t.parseArg)throw new Error(`a default value for a required argument is never used: '${t.name()}'`);return this.registeredArguments.push(t),this}helpCommand(t,e){if("boolean"==typeof t)return this._addImplicitHelpCommand=t,this;t=t??"help [command]";const[,i,n]=t.match(/([^ ]+) *(.*)/),s=e??"display help for command",r=this.createCommand(i);return r.helpOption(!1),n&&r.arguments(n),s&&r.description(s),this._addImplicitHelpCommand=!0,this._helpCommand=r,this}addHelpCommand(t,e){return"object"!=typeof t?(this.helpCommand(t,e),this):(this._addImplicitHelpCommand=!0,this._helpCommand=t,this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(void 0===this._helpCommand&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(t,e){const i=["preSubcommand","preAction","postAction"];if(!i.includes(t))throw new Error(`Unexpected value for event passed to hook : '${t}'.\nExpecting one of '${i.join("', '")}'`);return this._lifeCycleHooks[t]?this._lifeCycleHooks[t].push(e):this._lifeCycleHooks[t]=[e],this}exitOverride(t){return this._exitCallback=t||(t=>{if("commander.executeSubCommandAsync"!==t.code)throw t}),this}_exit(t,e,i){this._exitCallback&&this._exitCallback(new u(t,e,i)),l.exit(t)}action(t){return this._actionHandler=e=>{const i=this.registeredArguments.length,n=e.slice(0,i);return this._storeOptionsAsProperties?n[i]=this:n[i]=this.opts(),n.push(this),t.apply(this,n)},this}createOption(t,e){return new g(t,e)}_callParseArg(t,e,i,n){try{return t.parseArg(e,i)}catch(s){if("commander.invalidArgument"===s.code){const t=`${n} ${s.message}`;this.error(t,{exitCode:s.exitCode,code:s.code})}throw s}}_registerOption(t){const e=t.short&&this._findOption(t.short)||t.long&&this._findOption(t.long);if(e){const i=t.long&&this._findOption(t.long)?t.long:t.short;throw new Error(`Cannot add option '${t.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${i}'\n- already used by option '${e.flags}'`)}this.options.push(t)}_registerCommand(t){const e=t=>[t.name()].concat(t.aliases()),i=e(t).find((t=>this._findCommand(t)));if(i){const n=e(this._findCommand(i)).join("|"),s=e(t).join("|");throw new Error(`cannot add command '${s}' as already have command '${n}'`)}this.commands.push(t)}addOption(t){this._registerOption(t);const e=t.name(),i=t.attributeName();if(t.negate){const e=t.long.replace(/^--no-/,"--");this._findOption(e)||this.setOptionValueWithSource(i,void 0===t.defaultValue||t.defaultValue,"default")}else void 0!==t.defaultValue&&this.setOptionValueWithSource(i,t.defaultValue,"default");const n=(e,n,s)=>{null==e&&void 0!==t.presetArg&&(e=t.presetArg);const r=this.getOptionValue(i);null!==e&&t.parseArg?e=this._callParseArg(t,e,r,n):null!==e&&t.variadic&&(e=t._concatValue(e,r)),null==e&&(e=!t.negate&&(!(!t.isBoolean()&&!t.optional)||"")),this.setOptionValueWithSource(i,e,s)};return this.on("option:"+e,(e=>{const i=`error: option '${t.flags}' argument '${e}' is invalid.`;n(e,i,"cli")})),t.envVar&&this.on("optionEnv:"+e,(e=>{const i=`error: option '${t.flags}' value '${e}' from env '${t.envVar}' is invalid.`;n(e,i,"env")})),this}_optionEx(t,e,i,n,s){if("object"==typeof e&&e instanceof g)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");const r=this.createOption(e,i);if(r.makeOptionMandatory(!!t.mandatory),"function"==typeof n)r.default(s).argParser(n);else if(n instanceof RegExp){const t=n;n=(e,i)=>{const n=t.exec(e);return n?n[0]:i},r.default(s).argParser(n)}else r.default(n);return this.addOption(r)}option(t,e,i,n){return this._optionEx({},t,e,i,n)}requiredOption(t,e,i,n){return this._optionEx({mandatory:!0},t,e,i,n)}combineFlagAndOptionalValue(t=!0){return this._combineFlagAndOptionalValue=!!t,this}allowUnknownOption(t=!0){return this._allowUnknownOption=!!t,this}allowExcessArguments(t=!0){return this._allowExcessArguments=!!t,this}enablePositionalOptions(t=!0){return this._enablePositionalOptions=!!t,this}passThroughOptions(t=!0){return this._passThroughOptions=!!t,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(t=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!t,this}getOptionValue(t){return this._storeOptionsAsProperties?this[t]:this._optionValues[t]}setOptionValue(t,e){return this.setOptionValueWithSource(t,e,void 0)}setOptionValueWithSource(t,e,i){return this._storeOptionsAsProperties?this[t]=e:this._optionValues[t]=e,this._optionValueSources[t]=i,this}getOptionValueSource(t){return this._optionValueSources[t]}getOptionValueSourceWithGlobals(t){let e;return this._getCommandAndAncestors().forEach((i=>{void 0!==i.getOptionValueSource(t)&&(e=i.getOptionValueSource(t))})),e}_prepareUserArgs(t,e){if(void 0!==t&&!Array.isArray(t))throw new Error("first parameter to parse must be array or undefined");if(e=e||{},void 0===t&&void 0===e.from){l.versions?.electron&&(e.from="electron");const t=l.execArgv??[];(t.includes("-e")||t.includes("--eval")||t.includes("-p")||t.includes("--print"))&&(e.from="eval")}let i;switch(void 0===t&&(t=l.argv),this.rawArgs=t.slice(),e.from){case void 0:case"node":this._scriptPath=t[1],i=t.slice(2);break;case"electron":l.defaultApp?(this._scriptPath=t[1],i=t.slice(2)):i=t.slice(1);break;case"user":i=t.slice(0);break;case"eval":i=t.slice(1);break;default:throw new Error(`unexpected parse option { from: '${e.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",i}parse(t,e){this._prepareForParse();const i=this._prepareUserArgs(t,e);return this._parseCommand([],i),this}async parseAsync(t,e){this._prepareForParse();const i=this._prepareUserArgs(t,e);return await this._parseCommand([],i),this}_prepareForParse(){null===this._savedState?this.saveStateBeforeParse():this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw new Error("Can not call parse again when storeOptionsAsProperties is true.\n- either make a new Command for each call to parse, or stop storing options as properties");this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable(t,e,i){if(!c.existsSync(t))throw new Error(`'${t}' does not exist\n - if '${i}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead\n - if the default executable name is not suitable, use the executableFile option to supply a custom name or path\n - ${e?`searched for local subcommand relative to directory '${e}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory"}`)}_executeSubCommand(t,e){e=e.slice();let i=!1;const n=[".js",".ts",".tsx",".mjs",".cjs"];function r(t,e){const i=a.resolve(t,e);if(c.existsSync(i))return i;if(n.includes(a.extname(e)))return;const s=n.find((t=>c.existsSync(`${i}${t}`)));return s?`${i}${s}`:void 0}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o,p=t._executableFile||`${this._name}-${t._name}`,h=this._executableDir||"";if(this._scriptPath){let t;try{t=c.realpathSync(this._scriptPath)}catch{t=this._scriptPath}h=a.resolve(a.dirname(t),h)}if(h){let e=r(h,p);if(!e&&!t._executableFile&&this._scriptPath){const i=a.basename(this._scriptPath,a.extname(this._scriptPath));i!==this._name&&(e=r(h,`${i}-${t._name}`))}p=e||p}i=n.includes(a.extname(p)),"win32"!==l.platform?i?(e.unshift(p),e=O(l.execArgv).concat(e),o=s.spawn(l.argv[0],e,{stdio:"inherit"})):o=s.spawn(p,e,{stdio:"inherit"}):(this._checkForMissingExecutable(p,h,t._name),e.unshift(p),e=O(l.execArgv).concat(e),o=s.spawn(l.execPath,e,{stdio:"inherit"})),o.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach((t=>{l.on(t,(()=>{!1===o.killed&&null===o.exitCode&&o.kill(t)}))}));const m=this._exitCallback;o.on("close",(t=>{t=t??1,m?m(new u(t,"commander.executeSubCommandAsync","(close)")):l.exit(t)})),o.on("error",(e=>{if("ENOENT"===e.code)this._checkForMissingExecutable(p,h,t._name);else if("EACCES"===e.code)throw new Error(`'${p}' not executable`);if(m){const t=new u(1,"commander.executeSubCommandAsync","(error)");t.nestedError=e,m(t)}else l.exit(1)})),this.runningCommand=o}_dispatchSubcommand(t,e,i){const n=this._findCommand(t);let s;return n||this.help({error:!0}),n._prepareForParse(),s=this._chainOrCallSubCommandHook(s,n,"preSubcommand"),s=this._chainOrCall(s,(()=>{if(!n._executableHandler)return n._parseCommand(e,i);this._executeSubCommand(n,e.concat(i))})),s}_dispatchHelpCommand(t){t||this.help();const e=this._findCommand(t);return e&&!e._executableHandler&&e.help(),this._dispatchSubcommand(t,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach(((t,e)=>{t.required&&null==this.args[e]&&this.missingArgument(t.name())})),this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic||this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){const t=(t,e,i)=>{let n=e;if(null!==e&&t.parseArg){const s=`error: command-argument value '${e}' is invalid for argument '${t.name()}'.`;n=this._callParseArg(t,e,i,s)}return n};this._checkNumberOfArguments();const e=[];this.registeredArguments.forEach(((i,n)=>{let s=i.defaultValue;i.variadic?n<this.args.length?(s=this.args.slice(n),i.parseArg&&(s=s.reduce(((e,n)=>t(i,n,e)),i.defaultValue))):void 0===s&&(s=[]):n<this.args.length&&(s=this.args[n],i.parseArg&&(s=t(i,s,i.defaultValue))),e[n]=s})),this.processedArgs=e}_chainOrCall(t,e){return t&&t.then&&"function"==typeof t.then?t.then((()=>e())):e()}_chainOrCallHooks(t,e){let i=t;const n=[];return this._getCommandAndAncestors().reverse().filter((t=>void 0!==t._lifeCycleHooks[e])).forEach((t=>{t._lifeCycleHooks[e].forEach((e=>{n.push({hookedCommand:t,callback:e})}))})),"postAction"===e&&n.reverse(),n.forEach((t=>{i=this._chainOrCall(i,(()=>t.callback(t.hookedCommand,this)))})),i}_chainOrCallSubCommandHook(t,e,i){let n=t;return void 0!==this._lifeCycleHooks[i]&&this._lifeCycleHooks[i].forEach((t=>{n=this._chainOrCall(n,(()=>t(this,e)))})),n}_parseCommand(t,e){const i=this.parseOptions(e);if(this._parseOptionsEnv(),this._parseOptionsImplied(),t=t.concat(i.operands),e=i.unknown,this.args=t.concat(e),t&&this._findCommand(t[0]))return this._dispatchSubcommand(t[0],t.slice(1),e);if(this._getHelpCommand()&&t[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(t[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(e),this._dispatchSubcommand(this._defaultCommandName,t,e);!this.commands.length||0!==this.args.length||this._actionHandler||this._defaultCommandName||this.help({error:!0}),this._outputHelpIfRequested(i.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();const n=()=>{i.unknown.length>0&&this.unknownOption(i.unknown[0])},s=`command:${this.name()}`;if(this._actionHandler){let i;return n(),this._processArguments(),i=this._chainOrCallHooks(i,"preAction"),i=this._chainOrCall(i,(()=>this._actionHandler(this.processedArgs))),this.parent&&(i=this._chainOrCall(i,(()=>{this.parent.emit(s,t,e)}))),i=this._chainOrCallHooks(i,"postAction"),i}if(this.parent&&this.parent.listenerCount(s))n(),this._processArguments(),this.parent.emit(s,t,e);else if(t.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",t,e);this.listenerCount("command:*")?this.emit("command:*",t,e):this.commands.length?this.unknownCommand():(n(),this._processArguments())}else this.commands.length?(n(),this.help({error:!0})):(n(),this._processArguments())}_findCommand(t){if(t)return this.commands.find((e=>e._name===t||e._aliases.includes(t)))}_findOption(t){return this.options.find((e=>e.is(t)))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach((t=>{t.options.forEach((e=>{e.mandatory&&void 0===t.getOptionValue(e.attributeName())&&t.missingMandatoryOptionValue(e)}))}))}_checkForConflictingLocalOptions(){const t=this.options.filter((t=>{const e=t.attributeName();return void 0!==this.getOptionValue(e)&&"default"!==this.getOptionValueSource(e)}));t.filter((t=>t.conflictsWith.length>0)).forEach((e=>{const i=t.find((t=>e.conflictsWith.includes(t.attributeName())));i&&this._conflictingOption(e,i)}))}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach((t=>{t._checkForConflictingLocalOptions()}))}parseOptions(t){const e=[],i=[];let n=e;const s=t.slice();function r(t){return t.length>1&&"-"===t[0]}let o=null;for(;s.length;){const t=s.shift();if("--"===t){n===i&&n.push(t),n.push(...s);break}if(!o||r(t)){if(o=null,r(t)){const e=this._findOption(t);if(e){if(e.required){const t=s.shift();void 0===t&&this.optionMissingArgument(e),this.emit(`option:${e.name()}`,t)}else if(e.optional){let t=null;s.length>0&&!r(s[0])&&(t=s.shift()),this.emit(`option:${e.name()}`,t)}else this.emit(`option:${e.name()}`);o=e.variadic?e:null;continue}}if(t.length>2&&"-"===t[0]&&"-"!==t[1]){const e=this._findOption(`-${t[1]}`);if(e){e.required||e.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${e.name()}`,t.slice(2)):(this.emit(`option:${e.name()}`),s.unshift(`-${t.slice(2)}`));continue}}if(/^--[^=]+=/.test(t)){const e=t.indexOf("="),i=this._findOption(t.slice(0,e));if(i&&(i.required||i.optional)){this.emit(`option:${i.name()}`,t.slice(e+1));continue}}if(r(t)&&(n=i),(this._enablePositionalOptions||this._passThroughOptions)&&0===e.length&&0===i.length){if(this._findCommand(t)){e.push(t),s.length>0&&i.push(...s);break}if(this._getHelpCommand()&&t===this._getHelpCommand().name()){e.push(t),s.length>0&&e.push(...s);break}if(this._defaultCommandName){i.push(t),s.length>0&&i.push(...s);break}}if(this._passThroughOptions){n.push(t),s.length>0&&n.push(...s);break}n.push(t)}else this.emit(`option:${o.name()}`,t)}return{operands:e,unknown:i}}opts(){if(this._storeOptionsAsProperties){const t={},e=this.options.length;for(let i=0;i<e;i++){const e=this.options[i].attributeName();t[e]=e===this._versionOptionName?this._version:this[e]}return t}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce(((t,e)=>Object.assign(t,e.opts())),{})}error(t,e){this._outputConfiguration.outputError(`${t}\n`,this._outputConfiguration.writeErr),"string"==typeof this._showHelpAfterError?this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`):this._showHelpAfterError&&(this._outputConfiguration.writeErr("\n"),this.outputHelp({error:!0}));const i=e||{},n=i.exitCode||1,s=i.code||"commander.error";this._exit(n,s,t)}_parseOptionsEnv(){this.options.forEach((t=>{if(t.envVar&&t.envVar in l.env){const e=t.attributeName();(void 0===this.getOptionValue(e)||["default","config","env"].includes(this.getOptionValueSource(e)))&&(t.required||t.optional?this.emit(`optionEnv:${t.name()}`,l.env[t.envVar]):this.emit(`optionEnv:${t.name()}`))}}))}_parseOptionsImplied(){const t=new f(this.options),e=t=>void 0!==this.getOptionValue(t)&&!["default","implied"].includes(this.getOptionValueSource(t));this.options.filter((i=>void 0!==i.implied&&e(i.attributeName())&&t.valueFromOption(this.getOptionValue(i.attributeName()),i))).forEach((t=>{Object.keys(t.implied).filter((t=>!e(t))).forEach((e=>{this.setOptionValueWithSource(e,t.implied[e],"implied")}))}))}missingArgument(t){const e=`error: missing required argument '${t}'`;this.error(e,{code:"commander.missingArgument"})}optionMissingArgument(t){const e=`error: option '${t.flags}' argument missing`;this.error(e,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(t){const e=`error: required option '${t.flags}' not specified`;this.error(e,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(t,e){const i=t=>{const e=t.attributeName(),i=this.getOptionValue(e),n=this.options.find((t=>t.negate&&e===t.attributeName())),s=this.options.find((t=>!t.negate&&e===t.attributeName()));return n&&(void 0===n.presetArg&&!1===i||void 0!==n.presetArg&&i===n.presetArg)?n:s||t},n=t=>{const e=i(t),n=e.attributeName();return"env"===this.getOptionValueSource(n)?`environment variable '${e.envVar}'`:`option '${e.flags}'`},s=`error: ${n(t)} cannot be used with ${n(e)}`;this.error(s,{code:"commander.conflictingOption"})}unknownOption(t){if(this._allowUnknownOption)return;let e="";if(t.startsWith("--")&&this._showSuggestionAfterError){let i=[],n=this;do{const t=n.createHelp().visibleOptions(n).filter((t=>t.long)).map((t=>t.long));i=i.concat(t),n=n.parent}while(n&&!n._enablePositionalOptions);e=_(t,i)}const i=`error: unknown option '${t}'${e}`;this.error(i,{code:"commander.unknownOption"})}_excessArguments(t){if(this._allowExcessArguments)return;const e=this.registeredArguments.length,i=1===e?"":"s",n=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${e} argument${i} but got ${t.length}.`;this.error(n,{code:"commander.excessArguments"})}unknownCommand(){const t=this.args[0];let e="";if(this._showSuggestionAfterError){const i=[];this.createHelp().visibleCommands(this).forEach((t=>{i.push(t.name()),t.alias()&&i.push(t.alias())})),e=_(t,i)}const i=`error: unknown command '${t}'${e}`;this.error(i,{code:"commander.unknownCommand"})}version(t,e,i){if(void 0===t)return this._version;this._version=t,e=e||"-V, --version",i=i||"output the version number";const n=this.createOption(e,i);return this._versionOptionName=n.attributeName(),this._registerOption(n),this.on("option:"+n.name(),(()=>{this._outputConfiguration.writeOut(`${t}\n`),this._exit(0,"commander.version",t)})),this}description(t,e){return void 0===t&&void 0===e?this._description:(this._description=t,e&&(this._argsDescription=e),this)}summary(t){return void 0===t?this._summary:(this._summary=t,this)}alias(t){if(void 0===t)return this._aliases[0];let e=this;if(0!==this.commands.length&&this.commands[this.commands.length-1]._executableHandler&&(e=this.commands[this.commands.length-1]),t===e._name)throw new Error("Command alias can't be the same as its name");const i=this.parent?._findCommand(t);if(i){const e=[i.name()].concat(i.aliases()).join("|");throw new Error(`cannot add alias '${t}' to command '${this.name()}' as already have command '${e}'`)}return e._aliases.push(t),this}aliases(t){return void 0===t?this._aliases:(t.forEach((t=>this.alias(t))),this)}usage(t){if(void 0===t){if(this._usage)return this._usage;const t=this.registeredArguments.map((t=>h(t)));return[].concat(this.options.length||null!==this._helpOption?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?t:[]).join(" ")}return this._usage=t,this}name(t){return void 0===t?this._name:(this._name=t,this)}nameFromFilename(t){return this._name=a.basename(t,a.extname(t)),this}executableDir(t){return void 0===t?this._executableDir:(this._executableDir=t,this)}helpInformation(t){const e=this.createHelp(),i=this._getOutputContext(t);e.prepareContext({error:i.error,helpWidth:i.helpWidth,outputHasColors:i.hasColors});const n=e.formatHelp(this,e);return i.hasColors?n:this._outputConfiguration.stripColor(n)}_getOutputContext(t){const e=!!(t=t||{}).error;let i,n,s;return e?(i=t=>this._outputConfiguration.writeErr(t),n=this._outputConfiguration.getErrHasColors(),s=this._outputConfiguration.getErrHelpWidth()):(i=t=>this._outputConfiguration.writeOut(t),n=this._outputConfiguration.getOutHasColors(),s=this._outputConfiguration.getOutHelpWidth()),{error:e,write:t=>(n||(t=this._outputConfiguration.stripColor(t)),i(t)),hasColors:n,helpWidth:s}}outputHelp(t){let e;"function"==typeof t&&(e=t,t=void 0);const i=this._getOutputContext(t),n={error:i.error,write:i.write,command:this};this._getCommandAndAncestors().reverse().forEach((t=>t.emit("beforeAllHelp",n))),this.emit("beforeHelp",n);let s=this.helpInformation({error:i.error});if(e&&(s=e(s),"string"!=typeof s&&!Buffer.isBuffer(s)))throw new Error("outputHelp callback must return a string or a Buffer");i.write(s),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",n),this._getCommandAndAncestors().forEach((t=>t.emit("afterAllHelp",n)))}helpOption(t,e){return"boolean"==typeof t?(this._helpOption=t?this._helpOption??void 0:null,this):(t=t??"-h, --help",e=e??"display help for command",this._helpOption=this.createOption(t,e),this)}_getHelpOption(){return void 0===this._helpOption&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(t){return this._helpOption=t,this}help(t){this.outputHelp(t);let e=Number(l.exitCode??0);0===e&&t&&"function"!=typeof t&&t.error&&(e=1),this._exit(e,"commander.help","(outputHelp)")}addHelpText(t,e){const i=["beforeAll","before","after","afterAll"];if(!i.includes(t))throw new Error(`Unexpected value for position to addHelpText.\nExpecting one of '${i.join("', '")}'`);const n=`${t}Help`;return this.on(n,(t=>{let i;i="function"==typeof e?e({error:t.error,command:t.command}):e,i&&t.write(`${i}\n`)})),this}_outputHelpIfRequested(t){const e=this._getHelpOption();e&&t.find((t=>e.is(t)))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}}function O(t){return t.map((t=>{if(!t.startsWith("--inspect"))return t;let e,i,n="127.0.0.1",s="9229";return null!==(i=t.match(/^(--inspect(-brk)?)$/))?e=i[1]:null!==(i=t.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))?(e=i[1],/^\d+$/.test(i[3])?s=i[3]:n=i[3]):null!==(i=t.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))&&(e=i[1],n=i[3],s=i[4]),e&&"0"!==s?`${e}=${n}:${parseInt(s)+1}`:t}))}function v(){return!l.env.NO_COLOR&&"0"!==l.env.FORCE_COLOR&&"false"!==l.env.FORCE_COLOR&&(!(!l.env.FORCE_COLOR&&void 0===l.env.CLICOLOR_FORCE)||void 0)}return W.Command=y,W.useColor=v,W}(),{CommanderError:a,InvalidArgumentError:c}=F(),{Help:l}=U(),{Option:p}=q();return V.program=new s,V.createCommand=t=>new s(t),V.createOption=(t,e)=>new p(t,e),V.createArgument=(t,i)=>new e(t,i),V.Command=s,V.Option=p,V.Argument=e,V.Help=l,V.CommanderError=a,V.InvalidArgumentError=c,V.InvalidOptionArgumentError=c,V}()),{program:z,createCommand:X,createArgument:Z,createOption:Q,CommanderError:tt,InvalidArgumentError:et,InvalidOptionArgumentError:it,Command:nt,Argument:st,Option:rt,Help:ot}=K;process.argv?.[2]||process.argv.push("-h");z.version((()=>{try{const i=e.fileURLToPath(new URL("../../package.json","undefined"==typeof document?require("url").pathToFileURL(__filename).href:a&&"SCRIPT"===a.tagName.toUpperCase()&&a.src||new URL("index.cjs",document.baseURI).href));return JSON.parse(t.readFileSync(i,"utf-8")).version}catch{return"unknown"}})(),"-v, --version","显示版本号"),z.command(".").description("前台启动").action(v),z.command("app").description("前台启动").action(v),z.command("start").description("前台启动").action(v),z.command("pm2").description("后台运行").action(d),z.command("stop").description("停止后台服务").action(f),z.command("rs").description("重启后台服务").option("-f, --force","强制重启").action((t=>_(t.force))),z.command("log").description("查看日志").action(g),z.command("up").description("更新插件").option("-f, --force","强制更新").option("-s, --serial","并发更新").action((t=>(async(t,e=!1)=>{try{console.log("开始执行更新任务\n");const s=[],r=[];await x("./package.json",s,r),await E("./plugins",s,t,e);const o=(i=s,[...i].sort(((t,e)=>t.isPlugin!==e.isPlugin?t.isPlugin?1:-1:t.needUpdate!==e.needUpdate?t.needUpdate?1:-1:t.name.localeCompare(e.name))));if(o.length>0){console.log("检查结果:");const t=o.map((t=>({name:t.name,type:t.type,currentVersion:t.currentVersion,latestVersion:t.latestVersion,status:t.status})));console.table(t)}else console.log("没有找到需要检查的项目");if(r.length>0){console.log("\n开始更新包:");try{const{status:t,error:e}=await l(`pnpm update ${r.join(" ")} --save`);if(t){console.log("npm包更新完成");const t=o.filter((t=>t.needUpdate));if(t.length>0){console.log("\n已更新的项目:");const e=t.map((t=>({name:t.name,type:t.type,from:t.currentVersion,to:t.latestVersion})));console.table(e)}}else console.error("npm包更新失败:",e)}catch(n){console.error("npm包更新失败:",n)}}console.log("\n更新任务执行完成")}finally{process.exit(0)}var i})(t.force,!t.serial))),z.command("init").description("初始化项目").option("-f, --force","强制初始化").option("-d, --dev","开发模式").action((t=>{process.env.KARIN_CLI="true",t.dev&&(process.env.NODE_ENV="development"),O(t.force)})),z.parse(process.argv);
|
|
2
|
+
"use strict";const e=require("node:fs"),t=require("node:url"),n=require("node:path"),s=require("node:child_process"),i=require("node:stream/promises"),r=require("fs"),o=require("node:events"),a=require("node:process");var c="undefined"!=typeof document?document.currentScript:null;const l=(e,t={})=>{try{return{status:!0,error:null,stdout:s.execSync(e,t).toString(),stderr:""}}catch(n){return{status:!1,error:n,stdout:"",stderr:""}}},u=(e,t={})=>new Promise((n=>{s.exec(e,t,((e,t,s)=>{n({status:!e,error:e,stdout:t,stderr:s})}))})),h=n.join(process.cwd(),"@karinjs/config/pm2.json"),p=()=>e.existsSync(h)?JSON.parse(e.readFileSync(h,"utf-8")):(console.log(`[pm2] 配置文件不存在 请检查 ${h} 是否存在`),null),d=async(t,s,r,o)=>{if(!e.existsSync(t))return!1;const a=e.statSync(t),c=1024*o*1024;if(a.size<c)return!1;const l=n.basename(t),u=`${l}.${Date.now()}`,h=n.join(s,u),p=n.join(s,`${l}.temp`);try{const n=e.createReadStream(t),s=e.createWriteStream(h);await i.pipeline(n,s);const o=e.statSync(t).mode;return e.writeFileSync(p,""),e.chmodSync(p,o),e.renameSync(p,t),console.log(`[pm2] 日志已按大小切割: ${r} => ${u} (${(a.size/1024/1024).toFixed(2)}MB)`),!0}catch(d){return console.error(`[pm2] 切割日志失败: ${r}`,d),e.existsSync(p)&&e.unlinkSync(p),!1}},f=async()=>{const t=p();var s;if(t)try{const i=Number(t.maxLogFiles)??10,r=Number(t.maxErrorLogSize)??50,o=Number(t.maxOutLogSize)??50;if(0===i)return;const a=n.resolve(process.cwd(),t.apps[0].error_file),c=n.resolve(process.cwd(),t.apps[0].out_file),l=n.dirname(a);if(s=l,!e.existsSync(s)&&(e.mkdirSync(s,{recursive:!0}),console.log(`[pm2] 创建日志目录: ${s}`),1))return;const u=n.basename(a),h=n.basename(c);await d(c,l,"输出",o),await d(a,l,"错误",r),((t,s,i,r)=>{if(r<=0)return;const o=e.readdirSync(i),a=(t,s)=>{const a=new RegExp(`^${t.replace(/\./g,"\\.")}\\.(\\d+)$`),c=o.filter((e=>a.test(e))).map((e=>{const t=e.match(a);return{file:e,timestamp:t?parseInt(t[1],10):0}})).sort(((e,t)=>t.timestamp-e.timestamp));c.length>r&&c.slice(r).forEach((t=>{const r=n.join(i,t.file);e.unlinkSync(r),console.log(`[pm2] 删除过期${s}日志: ${t.file}`)}))};a(t,"错误"),a(s,"输出")})(u,h,l,i)}catch(i){console.error("[pm2] 日志切割过程中发生错误:",i)}},m=async()=>{f(),console.log("[pm2] 启动中...");const t=p();t||process.exit(1),(t=>{const n="index.mjs";t.apps[0].script!==n&&(t.apps[0].script=n,e.writeFileSync(h,JSON.stringify(t,null,2)))})(t),e.existsSync("index.mjs")||(console.log("正在升级到1.8.0版本..."),l("npx ki init",{cwd:process.cwd()}),console.log("升级成功 正在启动pm2服务..."));const{error:n}=l(`pm2 start ${h}`,{cwd:process.cwd()});n&&(console.log("[pm2] 启动失败"),console.log(n),process.exit(1)),console.log("[pm2] 启动成功"),console.log("[pm2] 重启服务: pnpm rs"),console.log("[pm2] 查看日志: pnpm log"),console.log("[pm2] 停止服务: pnpm stop"),console.log("[pm2] 查看监控: pm2 monit"),console.log("[pm2] 查看列表: pm2 list"),process.exit(0)},g=async()=>{f();const e=p();e||(console.log("[pm2] 如果是新项目,请先前台启动生成配置文件: pnpm app"),process.exit(1));try{const t="win32"===process.platform?"pm2.cmd":"pm2";s.spawn(t,["logs",e.apps[0].name,"--lines",e.lines||1e3],{stdio:"inherit",shell:!0})}catch(t){console.error("[pm2] 发生未知错误: 请检查pm2是否安装 【npm install -g pm2】"),console.error(t),process.exit(1)}},y=async()=>{f();const e=p();e||(console.log("[pm2] 如果是新项目,请先前台启动生成配置文件: pnpm app"),process.exit(1)),l(`pm2 stop ${e.apps[0].name}`,{cwd:process.cwd()}),console.log("[pm2] 停止成功"),process.exit(0)},b=async t=>{f(),console.log("[pm2] 重启中..."),e.existsSync(h)||t||(console.log(`[pm2] 配置文件不存在 请检查 ${h} 是否存在`),console.log("[pm2] 如果是新项目,请先前台启动生成配置文件: pnpm app"),process.exit(1));const n=t?"karin":p()?.apps[0].name;n||process.exit(1),l(`pm2 delete ${n}`,{cwd:process.cwd()}),l(`pm2 start ${h}`,{cwd:process.cwd()}),console.log("[pm2] 重启成功"),process.exit(0)},w=Symbol.for("yaml.alias"),v=Symbol.for("yaml.document"),k=Symbol.for("yaml.map"),_=Symbol.for("yaml.pair"),O=Symbol.for("yaml.scalar"),S=Symbol.for("yaml.seq"),E=Symbol.for("yaml.node.type"),A=e=>!!e&&"object"==typeof e&&e[E]===w,C=e=>!!e&&"object"==typeof e&&e[E]===v,x=e=>!!e&&"object"==typeof e&&e[E]===k,N=e=>!!e&&"object"==typeof e&&e[E]===_,T=e=>!!e&&"object"==typeof e&&e[E]===O,$=e=>!!e&&"object"==typeof e&&e[E]===S;function I(e){if(e&&"object"==typeof e)switch(e[E]){case k:case S:return!0}return!1}function L(e){if(e&&"object"==typeof e)switch(e[E]){case w:case k:case O:case S:return!0}return!1}const j=Symbol("break visit"),D=Symbol("skip children"),P=Symbol("remove node");function B(e,t){const n=q(t);if(C(e)){M(null,e.contents,n,Object.freeze([e]))===P&&(e.contents=null)}else M(null,e,n,Object.freeze([]))}function M(e,t,n,s){const i=H(e,t,n,s);if(L(i)||N(i))return K(e,s,i),M(e,i,n,s);if("symbol"!=typeof i)if(I(t)){s=Object.freeze(s.concat(t));for(let e=0;e<t.items.length;++e){const i=M(e,t.items[e],n,s);if("number"==typeof i)e=i-1;else{if(i===j)return j;i===P&&(t.items.splice(e,1),e-=1)}}}else if(N(t)){s=Object.freeze(s.concat(t));const e=M("key",t.key,n,s);if(e===j)return j;e===P&&(t.key=null);const i=M("value",t.value,n,s);if(i===j)return j;i===P&&(t.value=null)}return i}async function V(e,t){const n=q(t);if(C(e)){await F(null,e.contents,n,Object.freeze([e]))===P&&(e.contents=null)}else await F(null,e,n,Object.freeze([]))}async function F(e,t,n,s){const i=await H(e,t,n,s);if(L(i)||N(i))return K(e,s,i),F(e,i,n,s);if("symbol"!=typeof i)if(I(t)){s=Object.freeze(s.concat(t));for(let e=0;e<t.items.length;++e){const i=await F(e,t.items[e],n,s);if("number"==typeof i)e=i-1;else{if(i===j)return j;i===P&&(t.items.splice(e,1),e-=1)}}}else if(N(t)){s=Object.freeze(s.concat(t));const e=await F("key",t.key,n,s);if(e===j)return j;e===P&&(t.key=null);const i=await F("value",t.value,n,s);if(i===j)return j;i===P&&(t.value=null)}return i}function q(e){return"object"==typeof e&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function H(e,t,n,s){return"function"==typeof n?n(e,t,s):x(t)?n.Map?.(e,t,s):$(t)?n.Seq?.(e,t,s):N(t)?n.Pair?.(e,t,s):T(t)?n.Scalar?.(e,t,s):A(t)?n.Alias?.(e,t,s):void 0}function K(e,t,n){const s=t[t.length-1];if(I(s))s.items[e]=n;else if(N(s))"key"===e?s.key=n:s.value=n;else{if(!C(s)){const e=A(s)?"alias":"scalar";throw new Error(`Cannot replace node with ${e} parent`)}s.contents=n}}B.BREAK=j,B.SKIP=D,B.REMOVE=P,V.BREAK=j,V.SKIP=D,V.REMOVE=P;const U={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"};class R{constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},R.defaultYaml,e),this.tags=Object.assign({},R.defaultTags,t)}clone(){const e=new R(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){const e=new R(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:R.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},R.defaultTags)}return e}add(e,t){this.atNextDocument&&(this.yaml={explicit:R.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},R.defaultTags),this.atNextDocument=!1);const n=e.trim().split(/[ \t]+/),s=n.shift();switch(s){case"%TAG":{if(2!==n.length&&(t(0,"%TAG directive should contain exactly two parts"),n.length<2))return!1;const[e,s]=n;return this.tags[e]=s,!0}case"%YAML":{if(this.yaml.explicit=!0,1!==n.length)return t(0,"%YAML directive should contain exactly one part"),!1;const[e]=n;if("1.1"===e||"1.2"===e)return this.yaml.version=e,!0;return t(6,`Unsupported YAML version ${e}`,/^\d+\.\d+$/.test(e)),!1}default:return t(0,`Unknown directive ${s}`,!0),!1}}tagName(e,t){if("!"===e)return"!";if("!"!==e[0])return t(`Not a valid tag: ${e}`),null;if("<"===e[1]){const n=e.slice(2,-1);return"!"===n||"!!"===n?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(">"!==e[e.length-1]&&t("Verbatim tags must end with a >"),n)}const[,n,s]=e.match(/^(.*!)([^!]*)$/s);s||t(`The ${e} tag has no suffix`);const i=this.tags[n];if(i)try{return i+decodeURIComponent(s)}catch(r){return t(String(r)),null}return"!"===n?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(const[t,n]of Object.entries(this.tags))if(e.startsWith(n))return t+e.substring(n.length).replace(/[!,[\]{}]/g,(e=>U[e]));return"!"===e[0]?e:`!<${e}>`}toString(e){const t=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],n=Object.entries(this.tags);let s;if(e&&n.length>0&&L(e.contents)){const t={};B(e.contents,((e,n)=>{L(n)&&n.tag&&(t[n.tag]=!0)})),s=Object.keys(t)}else s=[];for(const[i,r]of n)"!!"===i&&"tag:yaml.org,2002:"===r||e&&!s.some((e=>e.startsWith(r)))||t.push(`%TAG ${i} ${r}`);return t.join("\n")}}function W(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){const t=JSON.stringify(e);throw new Error(`Anchor must not contain whitespace or control characters: ${t}`)}return!0}function J(e){const t=new Set;return B(e,{Value(e,n){n.anchor&&t.add(n.anchor)}}),t}function G(e,t){for(let n=1;;++n){const s=`${e}${n}`;if(!t.has(s))return s}}function Y(e,t,n,s){if(s&&"object"==typeof s)if(Array.isArray(s))for(let i=0,r=s.length;i<r;++i){const t=s[i],n=Y(e,s,String(i),t);void 0===n?delete s[i]:n!==t&&(s[i]=n)}else if(s instanceof Map)for(const i of Array.from(s.keys())){const t=s.get(i),n=Y(e,s,i,t);void 0===n?s.delete(i):n!==t&&s.set(i,n)}else if(s instanceof Set)for(const i of Array.from(s)){const t=Y(e,s,i,i);void 0===t?s.delete(i):t!==i&&(s.delete(i),s.add(t))}else for(const[i,r]of Object.entries(s)){const t=Y(e,s,i,r);void 0===t?delete s[i]:t!==r&&(s[i]=t)}return e.call(t,n,s)}function Q(e,t,n){if(Array.isArray(e))return e.map(((e,t)=>Q(e,String(t),n)));if(e&&"function"==typeof e.toJSON){if(!n||(!T(s=e)&&!I(s)||!s.anchor))return e.toJSON(t,n);const i={aliasCount:0,count:1,res:void 0};n.anchors.set(e,i),n.onCreate=e=>{i.res=e,delete n.onCreate};const r=e.toJSON(t,n);return n.onCreate&&n.onCreate(r),r}var s;return"bigint"!=typeof e||n?.keep?e:Number(e)}R.defaultYaml={explicit:!1,version:"1.2"},R.defaultTags={"!!":"tag:yaml.org,2002:"};class X{constructor(e){Object.defineProperty(this,E,{value:e})}clone(){const e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:t,maxAliasCount:n,onAnchor:s,reviver:i}={}){if(!C(e))throw new TypeError("A document argument is required");const r={anchors:new Map,doc:e,keep:!0,mapAsMap:!0===t,mapKeyWarned:!1,maxAliasCount:"number"==typeof n?n:100},o=Q(this,"",r);if("function"==typeof s)for(const{count:a,res:c}of r.anchors.values())s(c,a);return"function"==typeof i?Y(i,{"":o},"",o):o}}class z extends X{constructor(e){super(w),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e){let t;return B(e,{Node:(e,n)=>{if(n===this)return B.BREAK;n.anchor===this.source&&(t=n)}}),t}toJSON(e,t){if(!t)return{source:this.source};const{anchors:n,doc:s,maxAliasCount:i}=t,r=this.resolve(s);if(!r){const e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(e)}let o=n.get(r);if(o||(Q(r,null,t),o=n.get(r)),!o||void 0===o.res){throw new ReferenceError("This should not happen: Alias anchor was not resolved?")}if(i>=0&&(o.count+=1,0===o.aliasCount&&(o.aliasCount=Z(s,r,n)),o.count*o.aliasCount>i)){throw new ReferenceError("Excessive alias count indicates a resource exhaustion attack")}return o.res}toString(e,t,n){const s=`*${this.source}`;if(e){if(W(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){const e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(e)}if(e.implicitKey)return`${s} `}return s}}function Z(e,t,n){if(A(t)){const s=t.resolve(e),i=n&&s&&n.get(s);return i?i.count*i.aliasCount:0}if(I(t)){let s=0;for(const i of t.items){const t=Z(e,i,n);t>s&&(s=t)}return s}if(N(t)){const s=Z(e,t.key,n),i=Z(e,t.value,n);return Math.max(s,i)}return 1}const ee=e=>!e||"function"!=typeof e&&"object"!=typeof e;class te extends X{constructor(e){super(O),this.value=e}toJSON(e,t){return t?.keep?this.value:Q(this.value,e,t)}toString(){return String(this.value)}}te.BLOCK_FOLDED="BLOCK_FOLDED",te.BLOCK_LITERAL="BLOCK_LITERAL",te.PLAIN="PLAIN",te.QUOTE_DOUBLE="QUOTE_DOUBLE",te.QUOTE_SINGLE="QUOTE_SINGLE";function ne(e,t,n){if(C(e)&&(e=e.contents),L(e))return e;if(N(e)){const t=n.schema[k].createNode?.(n.schema,null,n);return t.items.push(e),t}(e instanceof String||e instanceof Number||e instanceof Boolean||"undefined"!=typeof BigInt&&e instanceof BigInt)&&(e=e.valueOf());const{aliasDuplicateObjects:s,onAnchor:i,onTagObj:r,schema:o,sourceObjects:a}=n;let c;if(s&&e&&"object"==typeof e){if(c=a.get(e),c)return c.anchor||(c.anchor=i(e)),new z(c.anchor);c={anchor:null,node:null},a.set(e,c)}t?.startsWith("!!")&&(t="tag:yaml.org,2002:"+t.slice(2));let l=function(e,t,n){if(t){const e=n.filter((e=>e.tag===t)),s=e.find((e=>!e.format))??e[0];if(!s)throw new Error(`Tag ${t} not found`);return s}return n.find((t=>t.identify?.(e)&&!t.format))}(e,t,o.tags);if(!l){if(e&&"function"==typeof e.toJSON&&(e=e.toJSON()),!e||"object"!=typeof e){const t=new te(e);return c&&(c.node=t),t}l=e instanceof Map?o[k]:Symbol.iterator in Object(e)?o[S]:o[k]}r&&(r(l),delete n.onTagObj);const u=l?.createNode?l.createNode(n.schema,e,n):"function"==typeof l?.nodeClass?.from?l.nodeClass.from(n.schema,e,n):new te(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}function se(e,t,n){let s=n;for(let i=t.length-1;i>=0;--i){const e=t[i];if("number"==typeof e&&Number.isInteger(e)&&e>=0){const t=[];t[e]=s,s=t}else s=new Map([[e,s]])}return ne(s,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}const ie=e=>null==e||"object"==typeof e&&!!e[Symbol.iterator]().next().done;class re extends X{constructor(e,t){super(e),Object.defineProperty(this,"schema",{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){const t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map((t=>L(t)||N(t)?t.clone(e):t)),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(ie(e))this.add(t);else{const[n,...s]=e,i=this.get(n,!0);if(I(i))i.addIn(s,t);else{if(void 0!==i||!this.schema)throw new Error(`Expected YAML collection at ${n}. Remaining path: ${s}`);this.set(n,se(this.schema,s,t))}}}deleteIn(e){const[t,...n]=e;if(0===n.length)return this.delete(t);const s=this.get(t,!0);if(I(s))return s.deleteIn(n);throw new Error(`Expected YAML collection at ${t}. Remaining path: ${n}`)}getIn(e,t){const[n,...s]=e,i=this.get(n,!0);return 0===s.length?!t&&T(i)?i.value:i:I(i)?i.getIn(s,t):void 0}hasAllNullValues(e){return this.items.every((t=>{if(!N(t))return!1;const n=t.value;return null==n||e&&T(n)&&null==n.value&&!n.commentBefore&&!n.comment&&!n.tag}))}hasIn(e){const[t,...n]=e;if(0===n.length)return this.has(t);const s=this.get(t,!0);return!!I(s)&&s.hasIn(n)}setIn(e,t){const[n,...s]=e;if(0===s.length)this.set(n,t);else{const e=this.get(n,!0);if(I(e))e.setIn(s,t);else{if(void 0!==e||!this.schema)throw new Error(`Expected YAML collection at ${n}. Remaining path: ${s}`);this.set(n,se(this.schema,s,t))}}}}const oe=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function ae(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}const ce=(e,t,n)=>e.endsWith("\n")?ae(n,t):n.includes("\n")?"\n"+ae(n,t):(e.endsWith(" ")?"":" ")+n,le="flow",ue="block",he="quoted";function pe(e,t,n="flow",{indentAtStart:s,lineWidth:i=80,minContentWidth:r=20,onFold:o,onOverflow:a}={}){if(!i||i<0)return e;i<r&&(r=0);const c=Math.max(1+r,1+i-t.length);if(e.length<=c)return e;const l=[],u={};let h,p,d=i-t.length;"number"==typeof s&&(s>i-Math.max(2,r)?l.push(0):d=i-s);let f=!1,m=-1,g=-1,y=-1;n===ue&&(m=de(e,m,t.length),-1!==m&&(d=m+c));for(let w;w=e[m+=1];){if(n===he&&"\\"===w){switch(g=m,e[m+1]){case"x":m+=3;break;case"u":m+=5;break;case"U":m+=9;break;default:m+=1}y=m}if("\n"===w)n===ue&&(m=de(e,m,t.length)),d=m+t.length+c,h=void 0;else{if(" "===w&&p&&" "!==p&&"\n"!==p&&"\t"!==p){const t=e[m+1];t&&" "!==t&&"\n"!==t&&"\t"!==t&&(h=m)}if(m>=d)if(h)l.push(h),d=h+c,h=void 0;else if(n===he){for(;" "===p||"\t"===p;)p=w,w=e[m+=1],f=!0;const t=m>y+1?m-2:g-1;if(u[t])return e;l.push(t),u[t]=!0,d=t+c,h=void 0}else f=!0}p=w}if(f&&a&&a(),0===l.length)return e;o&&o();let b=e.slice(0,l[0]);for(let w=0;w<l.length;++w){const s=l[w],i=l[w+1]||e.length;0===s?b=`\n${t}${e.slice(0,i)}`:(n===he&&u[s]&&(b+=`${e[s]}\\`),b+=`\n${t}${e.slice(s+1,i)}`)}return b}function de(e,t,n){let s=t,i=t+1,r=e[i];for(;" "===r||"\t"===r;)if(t<i+n)r=e[++t];else{do{r=e[++t]}while(r&&"\n"!==r);s=t,i=t+1,r=e[i]}return s}const fe=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),me=e=>/^(%|---|\.\.\.)/m.test(e);function ge(e,t){const n=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return n;const{implicitKey:s}=t,i=t.options.doubleQuotedMinMultiLineLength,r=t.indent||(me(e)?" ":"");let o="",a=0;for(let c=0,l=n[c];l;l=n[++c])if(" "===l&&"\\"===n[c+1]&&"n"===n[c+2]&&(o+=n.slice(a,c)+"\\ ",c+=1,a=c,l="\\"),"\\"===l)switch(n[c+1]){case"u":{o+=n.slice(a,c);const e=n.substr(c+2,4);switch(e){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:"00"===e.substr(0,2)?o+="\\x"+e.substr(2):o+=n.substr(c,6)}c+=5,a=c+1}break;case"n":if(s||'"'===n[c+2]||n.length<i)c+=1;else{for(o+=n.slice(a,c)+"\n\n";"\\"===n[c+2]&&"n"===n[c+3]&&'"'!==n[c+4];)o+="\n",c+=2;o+=r," "===n[c+2]&&(o+="\\"),c+=1,a=c+1}break;default:c+=1}return o=a?o+n.slice(a):n,s?o:pe(o,r,he,fe(t,!1))}function ye(e,t){if(!1===t.options.singleQuote||t.implicitKey&&e.includes("\n")||/[ \t]\n|\n[ \t]/.test(e))return ge(e,t);const n=t.indent||(me(e)?" ":""),s="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&\n${n}`)+"'";return t.implicitKey?s:pe(s,n,le,fe(t,!1))}function be(e,t){const{singleQuote:n}=t.options;let s;if(!1===n)s=ge;else{const t=e.includes('"'),i=e.includes("'");s=t&&!i?ye:i&&!t?ge:n?ye:ge}return s(e,t)}let we;try{we=new RegExp("(^|(?<!\n))\n+(?!\n|$)","g")}catch{we=/\n+(?!\n|$)/g}function ve({comment:e,type:t,value:n},s,i,r){const{blockQuote:o,commentString:a,lineWidth:c}=s.options;if(!o||/\n[\t ]+$/.test(n)||/^\s*$/.test(n))return be(n,s);const l=s.indent||(s.forceBlockIndent||me(n)?" ":""),u="literal"===o||"folded"!==o&&t!==te.BLOCK_FOLDED&&(t===te.BLOCK_LITERAL||!function(e,t,n){if(!t||t<0)return!1;const s=t-n,i=e.length;if(i<=s)return!1;for(let r=0,o=0;r<i;++r)if("\n"===e[r]){if(r-o>s)return!0;if(o=r+1,i-o<=s)return!1}return!0}(n,c,l.length));if(!n)return u?"|\n":">\n";let h,p;for(p=n.length;p>0;--p){const e=n[p-1];if("\n"!==e&&"\t"!==e&&" "!==e)break}let d=n.substring(p);const f=d.indexOf("\n");-1===f?h="-":n===d||f!==d.length-1?(h="+",r&&r()):h="",d&&(n=n.slice(0,-d.length),"\n"===d[d.length-1]&&(d=d.slice(0,-1)),d=d.replace(we,`$&${l}`));let m,g=!1,y=-1;for(m=0;m<n.length;++m){const e=n[m];if(" "===e)g=!0;else{if("\n"!==e)break;y=m}}let b=n.substring(0,y<m?y+1:m);b&&(n=n.substring(b.length),b=b.replace(/\n+/g,`$&${l}`));let w=(g?l?"2":"1":"")+h;if(e&&(w+=" "+a(e.replace(/ ?[\r\n]+/g," ")),i&&i()),!u){const e=n.replace(/\n+/g,"\n$&").replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`);let i=!1;const r=fe(s,!0);"folded"!==o&&t!==te.BLOCK_FOLDED&&(r.onOverflow=()=>{i=!0});const a=pe(`${b}${e}${d}`,l,ue,r);if(!i)return`>${w}\n${l}${a}`}return`|${w}\n${l}${b}${n=n.replace(/\n+/g,`$&${l}`)}${d}`}function ke(e,t,n,s){const{implicitKey:i,inFlow:r}=t,o="string"==typeof e.value?e:Object.assign({},e,{value:String(e.value)});let{type:a}=e;a!==te.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=te.QUOTE_DOUBLE);const c=e=>{switch(e){case te.BLOCK_FOLDED:case te.BLOCK_LITERAL:return i||r?be(o.value,t):ve(o,t,n,s);case te.QUOTE_DOUBLE:return ge(o.value,t);case te.QUOTE_SINGLE:return ye(o.value,t);case te.PLAIN:return function(e,t,n,s){const{type:i,value:r}=e,{actualString:o,implicitKey:a,indent:c,indentStep:l,inFlow:u}=t;if(a&&r.includes("\n")||u&&/[[\]{},]/.test(r))return be(r,t);if(!r||/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(r))return a||u||!r.includes("\n")?be(r,t):ve(e,t,n,s);if(!a&&!u&&i!==te.PLAIN&&r.includes("\n"))return ve(e,t,n,s);if(me(r)){if(""===c)return t.forceBlockIndent=!0,ve(e,t,n,s);if(a&&c===l)return be(r,t)}const h=r.replace(/\n+/g,`$&\n${c}`);if(o){const e=e=>e.default&&"tag:yaml.org,2002:str"!==e.tag&&e.test?.test(h),{compat:n,tags:s}=t.doc.schema;if(s.some(e)||n?.some(e))return be(r,t)}return a?h:pe(h,c,le,fe(t,!1))}(o,t,n,s);default:return null}};let l=c(a);if(null===l){const{defaultKeyType:e,defaultStringType:n}=t.options,s=i&&e||n;if(l=c(s),null===l)throw new Error(`Unsupported default string type ${s}`)}return l}function _e(e,t){const n=Object.assign({blockQuote:!0,commentString:oe,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trueStr:"true",verifyAliasOrder:!0},e.schema.toStringOptions,t);let s;switch(n.collectionStyle){case"block":s=!1;break;case"flow":s=!0;break;default:s=null}return{anchors:new Set,doc:e,flowCollectionPadding:n.flowCollectionPadding?" ":"",indent:"",indentStep:"number"==typeof n.indent?" ".repeat(n.indent):" ",inFlow:s,options:n}}function Oe(e,t,n,s){if(N(e))return e.toString(t,n,s);if(A(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw new TypeError("Cannot stringify circular structure without alias nodes");t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let i;const r=L(e)?e:t.doc.createNode(e,{onTagObj:e=>i=e});i||(i=function(e,t){if(t.tag){const n=e.filter((e=>e.tag===t.tag));if(n.length>0)return n.find((e=>e.format===t.format))??n[0]}let n,s;if(T(t)){s=t.value;let i=e.filter((e=>e.identify?.(s)));if(i.length>1){const e=i.filter((e=>e.test));e.length>0&&(i=e)}n=i.find((e=>e.format===t.format))??i.find((e=>!e.format))}else s=t,n=e.find((e=>e.nodeClass&&s instanceof e.nodeClass));if(!n)throw new Error(`Tag not resolved for ${s?.constructor?.name??typeof s} value`);return n}(t.doc.schema.tags,r));const o=function(e,t,{anchors:n,doc:s}){if(!s.directives)return"";const i=[],r=(T(e)||I(e))&&e.anchor;r&&W(r)&&(n.add(r),i.push(`&${r}`));const o=e.tag?e.tag:t.default?null:t.tag;return o&&i.push(s.directives.tagString(o)),i.join(" ")}(r,i,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);const a="function"==typeof i.stringify?i.stringify(r,t,n,s):T(r)?ke(r,t,n,s):r.toString(t,n,s);return o?T(r)||"{"===a[0]||"["===a[0]?`${o} ${a}`:`${o}\n${t.indent}${a}`:a}function Se(e,t){"debug"!==e&&"warn"!==e||console.warn(t)}const Ee="<<",Ae={identify:e=>e===Ee||"symbol"==typeof e&&e.description===Ee,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new te(Symbol(Ee)),{addToJSMap:Ce}),stringify:()=>Ee};function Ce(e,t,n){if(n=e&&A(n)?n.resolve(e.doc):n,$(n))for(const s of n.items)xe(e,t,s);else if(Array.isArray(n))for(const s of n)xe(e,t,s);else xe(e,t,n)}function xe(e,t,n){const s=e&&A(n)?n.resolve(e.doc):n;if(!x(s))throw new Error("Merge sources must be maps or map aliases");const i=s.toJSON(null,e,Map);for(const[r,o]of i)t instanceof Map?t.has(r)||t.set(r,o):t instanceof Set?t.add(r):Object.prototype.hasOwnProperty.call(t,r)||Object.defineProperty(t,r,{value:o,writable:!0,enumerable:!0,configurable:!0});return t}function Ne(e,t,{key:n,value:s}){if(L(n)&&n.addToJSMap)n.addToJSMap(e,t,s);else if(((e,t)=>(Ae.identify(t)||T(t)&&(!t.type||t.type===te.PLAIN)&&Ae.identify(t.value))&&e?.doc.schema.tags.some((e=>e.tag===Ae.tag&&e.default)))(e,n))Ce(e,t,s);else{const i=Q(n,"",e);if(t instanceof Map)t.set(i,Q(s,i,e));else if(t instanceof Set)t.add(i);else{const r=function(e,t,n){if(null===t)return"";if("object"!=typeof t)return String(t);if(L(e)&&n?.doc){const t=_e(n.doc,{});t.anchors=new Set;for(const e of n.anchors.keys())t.anchors.add(e.anchor);t.inFlow=!0,t.inStringifyKey=!0;const s=e.toString(t);if(!n.mapKeyWarned){let e=JSON.stringify(s);e.length>40&&(e=e.substring(0,36)+'..."'),Se(n.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${e}. Set mapAsMap: true to use object keys.`),n.mapKeyWarned=!0}return s}return JSON.stringify(t)}(n,i,e),o=Q(s,r,e);r in t?Object.defineProperty(t,r,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[r]=o}}return t}function Te(e,t,n){const s=ne(e,void 0,n),i=ne(t,void 0,n);return new $e(s,i)}class $e{constructor(e,t=null){Object.defineProperty(this,E,{value:_}),this.key=e,this.value=t}clone(e){let{key:t,value:n}=this;return L(t)&&(t=t.clone(e)),L(n)&&(n=n.clone(e)),new $e(t,n)}toJSON(e,t){return Ne(t,t?.mapAsMap?new Map:{},this)}toString(e,t,n){return e?.doc?function({key:e,value:t},n,s,i){const{allNullValues:r,doc:o,indent:a,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:h}}=n;let p=L(e)&&e.comment||null;if(h){if(p)throw new Error("With simple keys, key nodes cannot have comments");if(I(e)||!L(e)&&"object"==typeof e)throw new Error("With simple keys, collection cannot be used as a key value")}let d=!h&&(!e||p&&null==t&&!n.inFlow||I(e)||(T(e)?e.type===te.BLOCK_FOLDED||e.type===te.BLOCK_LITERAL:"object"==typeof e));n=Object.assign({},n,{allNullValues:!1,implicitKey:!d&&(h||!r),indent:a+c});let f,m,g,y=!1,b=!1,w=Oe(e,n,(()=>y=!0),(()=>b=!0));if(!d&&!n.inFlow&&w.length>1024){if(h)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");d=!0}if(n.inFlow){if(r||null==t)return y&&s&&s(),""===w?"?":d?`? ${w}`:w}else if(r&&!h||null==t&&d)return w=`? ${w}`,p&&!y?w+=ce(w,n.indent,l(p)):b&&i&&i(),w;y&&(p=null),d?(p&&(w+=ce(w,n.indent,l(p))),w=`? ${w}\n${a}:`):(w=`${w}:`,p&&(w+=ce(w,n.indent,l(p)))),L(t)?(f=!!t.spaceBefore,m=t.commentBefore,g=t.comment):(f=!1,m=null,g=null,t&&"object"==typeof t&&(t=o.createNode(t))),n.implicitKey=!1,d||p||!T(t)||(n.indentAtStart=w.length+1),b=!1,u||!(c.length>=2)||n.inFlow||d||!$(t)||t.flow||t.tag||t.anchor||(n.indent=n.indent.substring(2));let v=!1;const k=Oe(t,n,(()=>v=!0),(()=>b=!0));let _=" ";if(p||f||m)_=f?"\n":"",m&&(_+=`\n${ae(l(m),n.indent)}`),""!==k||n.inFlow?_+=`\n${n.indent}`:"\n"===_&&(_="\n\n");else if(!d&&I(t)){const e=k[0],s=k.indexOf("\n"),i=-1!==s,r=n.inFlow??t.flow??0===t.items.length;if(i||!r){let t=!1;if(i&&("&"===e||"!"===e)){let n=k.indexOf(" ");"&"===e&&-1!==n&&n<s&&"!"===k[n+1]&&(n=k.indexOf(" ",n+1)),(-1===n||s<n)&&(t=!0)}t||(_=`\n${n.indent}`)}}else""!==k&&"\n"!==k[0]||(_="");return w+=_+k,n.inFlow?v&&s&&s():g&&!v?w+=ce(w,n.indent,l(g)):b&&i&&i(),w}(this,e,t,n):JSON.stringify(this)}}function Ie(e,t,n){return(t.inFlow??e.flow?je:Le)(e,t,n)}function Le({comment:e,items:t},n,{blockItemPrefix:s,flowChars:i,itemIndent:r,onChompKeep:o,onComment:a}){const{indent:c,options:{commentString:l}}=n,u=Object.assign({},n,{indent:r,type:null});let h=!1;const p=[];for(let f=0;f<t.length;++f){const e=t[f];let i=null;if(L(e))!h&&e.spaceBefore&&p.push(""),De(n,p,e.commentBefore,h),e.comment&&(i=e.comment);else if(N(e)){const t=L(e.key)?e.key:null;t&&(!h&&t.spaceBefore&&p.push(""),De(n,p,t.commentBefore,h))}h=!1;let o=Oe(e,u,(()=>i=null),(()=>h=!0));i&&(o+=ce(o,r,l(i))),h&&i&&(h=!1),p.push(s+o)}let d;if(0===p.length)d=i.start+i.end;else{d=p[0];for(let e=1;e<p.length;++e){const t=p[e];d+=t?`\n${c}${t}`:"\n"}}return e?(d+="\n"+ae(l(e),c),a&&a()):h&&o&&o(),d}function je({items:e},t,{flowChars:n,itemIndent:s}){const{indent:i,indentStep:r,flowCollectionPadding:o,options:{commentString:a}}=t;s+=r;const c=Object.assign({},t,{indent:s,inFlow:!0,type:null});let l=!1,u=0;const h=[];for(let f=0;f<e.length;++f){const n=e[f];let i=null;if(L(n))n.spaceBefore&&h.push(""),De(t,h,n.commentBefore,!1),n.comment&&(i=n.comment);else if(N(n)){const e=L(n.key)?n.key:null;e&&(e.spaceBefore&&h.push(""),De(t,h,e.commentBefore,!1),e.comment&&(l=!0));const s=L(n.value)?n.value:null;s?(s.comment&&(i=s.comment),s.commentBefore&&(l=!0)):null==n.value&&e?.comment&&(i=e.comment)}i&&(l=!0);let r=Oe(n,c,(()=>i=null));f<e.length-1&&(r+=","),i&&(r+=ce(r,s,a(i))),!l&&(h.length>u||r.includes("\n"))&&(l=!0),h.push(r),u=h.length}const{start:p,end:d}=n;if(0===h.length)return p+d;if(!l){const e=h.reduce(((e,t)=>e+t.length+2),2);l=t.options.lineWidth>0&&e>t.options.lineWidth}if(l){let e=p;for(const t of h)e+=t?`\n${r}${i}${t}`:"\n";return`${e}\n${i}${d}`}return`${p}${o}${h.join(" ")}${o}${d}`}function De({indent:e,options:{commentString:t}},n,s,i){if(s&&i&&(s=s.replace(/^\n+/,"")),s){const i=ae(t(s),e);n.push(i.trimStart())}}function Pe(e,t){const n=T(t)?t.value:t;for(const s of e)if(N(s)){if(s.key===t||s.key===n)return s;if(T(s.key)&&s.key.value===n)return s}}class Be extends re{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(k,e),this.items=[]}static from(e,t,n){const{keepUndefined:s,replacer:i}=n,r=new this(e),o=(e,o)=>{if("function"==typeof i)o=i.call(t,e,o);else if(Array.isArray(i)&&!i.includes(e))return;(void 0!==o||s)&&r.items.push(Te(e,o,n))};if(t instanceof Map)for(const[a,c]of t)o(a,c);else if(t&&"object"==typeof t)for(const a of Object.keys(t))o(a,t[a]);return"function"==typeof e.sortMapEntries&&r.items.sort(e.sortMapEntries),r}add(e,t){let n;n=N(e)?e:e&&"object"==typeof e&&"key"in e?new $e(e.key,e.value):new $e(e,e?.value);const s=Pe(this.items,n.key),i=this.schema?.sortMapEntries;if(s){if(!t)throw new Error(`Key ${n.key} already set`);T(s.value)&&ee(n.value)?s.value.value=n.value:s.value=n.value}else if(i){const e=this.items.findIndex((e=>i(n,e)<0));-1===e?this.items.push(n):this.items.splice(e,0,n)}else this.items.push(n)}delete(e){const t=Pe(this.items,e);if(!t)return!1;return this.items.splice(this.items.indexOf(t),1).length>0}get(e,t){const n=Pe(this.items,e),s=n?.value;return(!t&&T(s)?s.value:s)??void 0}has(e){return!!Pe(this.items,e)}set(e,t){this.add(new $e(e,t),!0)}toJSON(e,t,n){const s=n?new n:t?.mapAsMap?new Map:{};t?.onCreate&&t.onCreate(s);for(const i of this.items)Ne(t,s,i);return s}toString(e,t,n){if(!e)return JSON.stringify(this);for(const s of this.items)if(!N(s))throw new Error(`Map items must all be pairs; found ${JSON.stringify(s)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),Ie(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:n,onComment:t})}}const Me={collection:"map",default:!0,nodeClass:Be,tag:"tag:yaml.org,2002:map",resolve:(e,t)=>(x(e)||t("Expected a mapping for this tag"),e),createNode:(e,t,n)=>Be.from(e,t,n)};class Ve extends re{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(S,e),this.items=[]}add(e){this.items.push(e)}delete(e){const t=Fe(e);if("number"!=typeof t)return!1;return this.items.splice(t,1).length>0}get(e,t){const n=Fe(e);if("number"!=typeof n)return;const s=this.items[n];return!t&&T(s)?s.value:s}has(e){const t=Fe(e);return"number"==typeof t&&t<this.items.length}set(e,t){const n=Fe(e);if("number"!=typeof n)throw new Error(`Expected a valid index, not ${e}.`);const s=this.items[n];T(s)&&ee(t)?s.value=t:this.items[n]=t}toJSON(e,t){const n=[];t?.onCreate&&t.onCreate(n);let s=0;for(const i of this.items)n.push(Q(i,String(s++),t));return n}toString(e,t,n){return e?Ie(this,e,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(e.indent||"")+" ",onChompKeep:n,onComment:t}):JSON.stringify(this)}static from(e,t,n){const{replacer:s}=n,i=new this(e);if(t&&Symbol.iterator in Object(t)){let e=0;for(let r of t){if("function"==typeof s){const n=t instanceof Set?r:String(e++);r=s.call(t,n,r)}i.items.push(ne(r,void 0,n))}}return i}}function Fe(e){let t=T(e)?e.value:e;return t&&"string"==typeof t&&(t=Number(t)),"number"==typeof t&&Number.isInteger(t)&&t>=0?t:null}const qe={collection:"seq",default:!0,nodeClass:Ve,tag:"tag:yaml.org,2002:seq",resolve:(e,t)=>($(e)||t("Expected a sequence for this tag"),e),createNode:(e,t,n)=>Ve.from(e,t,n)},He={identify:e=>"string"==typeof e,default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:(e,t,n,s)=>ke(e,t=Object.assign({actualString:!0},t),n,s)},Ke={identify:e=>null==e,createNode:()=>new te(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new te(null),stringify:({source:e},t)=>"string"==typeof e&&Ke.test.test(e)?e:t.options.nullStr},Ue={identify:e=>"boolean"==typeof e,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new te("t"===e[0]||"T"===e[0]),stringify({source:e,value:t},n){if(e&&Ue.test.test(e)){if(t===("t"===e[0]||"T"===e[0]))return e}return t?n.options.trueStr:n.options.falseStr}};function Re({format:e,minFractionDigits:t,tag:n,value:s}){if("bigint"==typeof s)return String(s);const i="number"==typeof s?s:Number(s);if(!isFinite(i))return isNaN(i)?".nan":i<0?"-.inf":".inf";let r=JSON.stringify(s);if(!e&&t&&(!n||"tag:yaml.org,2002:float"===n)&&/^\d/.test(r)){let e=r.indexOf(".");e<0&&(e=r.length,r+=".");let n=t-(r.length-e-1);for(;n-- >0;)r+="0"}return r}const We={identify:e=>"number"==typeof e,default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>"nan"===e.slice(-3).toLowerCase()?NaN:"-"===e[0]?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Re},Je={identify:e=>"number"==typeof e,default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e),stringify(e){const t=Number(e.value);return isFinite(t)?t.toExponential():Re(e)}},Ge={identify:e=>"number"==typeof e,default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(e){const t=new te(parseFloat(e)),n=e.indexOf(".");return-1!==n&&"0"===e[e.length-1]&&(t.minFractionDigits=e.length-n-1),t},stringify:Re},Ye=e=>"bigint"==typeof e||Number.isInteger(e),Qe=(e,t,n,{intAsBigInt:s})=>s?BigInt(e):parseInt(e.substring(t),n);function Xe(e,t,n){const{value:s}=e;return Ye(s)&&s>=0?n+s.toString(t):Re(e)}const ze={identify:e=>Ye(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,n)=>Qe(e,2,8,n),stringify:e=>Xe(e,8,"0o")},Ze={identify:Ye,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,n)=>Qe(e,0,10,n),stringify:Re},et={identify:e=>Ye(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,n)=>Qe(e,2,16,n),stringify:e=>Xe(e,16,"0x")},tt=[Me,qe,He,Ke,Ue,ze,Ze,et,We,Je,Ge];function nt(e){return"bigint"==typeof e||Number.isInteger(e)}const st=({value:e})=>JSON.stringify(e),it=[Me,qe].concat([{identify:e=>"string"==typeof e,default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:st},{identify:e=>null==e,createNode:()=>new te(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:st},{identify:e=>"boolean"==typeof e,default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>"true"===e,stringify:st},{identify:nt,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:n})=>n?BigInt(e):parseInt(e,10),stringify:({value:e})=>nt(e)?e.toString():JSON.stringify(e)},{identify:e=>"number"==typeof e,default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:e=>parseFloat(e),stringify:st}],{default:!0,tag:"",test:/^/,resolve:(e,t)=>(t(`Unresolved plain scalar ${JSON.stringify(e)}`),e)}),rt={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if("function"==typeof atob){const t=atob(e.replace(/[\n\r]/g,"")),n=new Uint8Array(t.length);for(let e=0;e<t.length;++e)n[e]=t.charCodeAt(e);return n}return t("This environment does not support reading binary tags; either Buffer or atob is required"),e},stringify({comment:e,type:t,value:n},s,i,r){const o=n;let a;if("function"!=typeof btoa)throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");{let e="";for(let t=0;t<o.length;++t)e+=String.fromCharCode(o[t]);a=btoa(e)}if(t||(t=te.BLOCK_LITERAL),t!==te.QUOTE_DOUBLE){const e=Math.max(s.options.lineWidth-s.indent.length,s.options.minContentWidth),n=Math.ceil(a.length/e),i=new Array(n);for(let t=0,s=0;t<n;++t,s+=e)i[t]=a.substr(s,e);a=i.join(t===te.BLOCK_LITERAL?"\n":" ")}return ke({comment:e,type:t,value:a},s,i,r)}};function ot(e,t){if($(e))for(let n=0;n<e.items.length;++n){let s=e.items[n];if(!N(s)){if(x(s)){s.items.length>1&&t("Each pair must have its own sequence indicator");const e=s.items[0]||new $e(new te(null));if(s.commentBefore&&(e.key.commentBefore=e.key.commentBefore?`${s.commentBefore}\n${e.key.commentBefore}`:s.commentBefore),s.comment){const t=e.value??e.key;t.comment=t.comment?`${s.comment}\n${t.comment}`:s.comment}s=e}e.items[n]=N(s)?s:new $e(s)}}else t("Expected a sequence for this tag");return e}function at(e,t,n){const{replacer:s}=n,i=new Ve(e);i.tag="tag:yaml.org,2002:pairs";let r=0;if(t&&Symbol.iterator in Object(t))for(let o of t){let e,a;if("function"==typeof s&&(o=s.call(t,String(r++),o)),Array.isArray(o)){if(2!==o.length)throw new TypeError(`Expected [key, value] tuple: ${o}`);e=o[0],a=o[1]}else if(o&&o instanceof Object){const t=Object.keys(o);if(1!==t.length)throw new TypeError(`Expected tuple with one key, not ${t.length} keys`);e=t[0],a=o[e]}else e=o;i.items.push(Te(e,a,n))}return i}const ct={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:ot,createNode:at};class lt extends Ve{constructor(){super(),this.add=Be.prototype.add.bind(this),this.delete=Be.prototype.delete.bind(this),this.get=Be.prototype.get.bind(this),this.has=Be.prototype.has.bind(this),this.set=Be.prototype.set.bind(this),this.tag=lt.tag}toJSON(e,t){if(!t)return super.toJSON(e);const n=new Map;t?.onCreate&&t.onCreate(n);for(const s of this.items){let e,i;if(N(s)?(e=Q(s.key,"",t),i=Q(s.value,e,t)):e=Q(s,"",t),n.has(e))throw new Error("Ordered maps must not include duplicate keys");n.set(e,i)}return n}static from(e,t,n){const s=at(e,t,n),i=new this;return i.items=s.items,i}}lt.tag="tag:yaml.org,2002:omap";const ut={collection:"seq",identify:e=>e instanceof Map,nodeClass:lt,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){const n=ot(e,t),s=[];for(const{key:i}of n.items)T(i)&&(s.includes(i.value)?t(`Ordered maps must not include duplicate keys: ${i.value}`):s.push(i.value));return Object.assign(new lt,n)},createNode:(e,t,n)=>lt.from(e,t,n)};function ht({value:e,source:t},n){return t&&(e?pt:dt).test.test(t)?t:e?n.options.trueStr:n.options.falseStr}const pt={identify:e=>!0===e,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new te(!0),stringify:ht},dt={identify:e=>!1===e,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new te(!1),stringify:ht},ft={identify:e=>"number"==typeof e,default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>"nan"===e.slice(-3).toLowerCase()?NaN:"-"===e[0]?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Re},mt={identify:e=>"number"==typeof e,default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e.replace(/_/g,"")),stringify(e){const t=Number(e.value);return isFinite(t)?t.toExponential():Re(e)}},gt={identify:e=>"number"==typeof e,default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(e){const t=new te(parseFloat(e.replace(/_/g,""))),n=e.indexOf(".");if(-1!==n){const s=e.substring(n+1).replace(/_/g,"");"0"===s[s.length-1]&&(t.minFractionDigits=s.length)}return t},stringify:Re},yt=e=>"bigint"==typeof e||Number.isInteger(e);function bt(e,t,n,{intAsBigInt:s}){const i=e[0];if("-"!==i&&"+"!==i||(t+=1),e=e.substring(t).replace(/_/g,""),s){switch(n){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`}const t=BigInt(e);return"-"===i?BigInt(-1)*t:t}const r=parseInt(e,n);return"-"===i?-1*r:r}function wt(e,t,n){const{value:s}=e;if(yt(s)){const e=s.toString(t);return s<0?"-"+n+e.substr(1):n+e}return Re(e)}const vt={identify:yt,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,n)=>bt(e,2,2,n),stringify:e=>wt(e,2,"0b")},kt={identify:yt,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,n)=>bt(e,1,8,n),stringify:e=>wt(e,8,"0")},_t={identify:yt,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,n)=>bt(e,0,10,n),stringify:Re},Ot={identify:yt,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,n)=>bt(e,2,16,n),stringify:e=>wt(e,16,"0x")};class St extends Be{constructor(e){super(e),this.tag=St.tag}add(e){let t;t=N(e)?e:e&&"object"==typeof e&&"key"in e&&"value"in e&&null===e.value?new $e(e.key,null):new $e(e,null);Pe(this.items,t.key)||this.items.push(t)}get(e,t){const n=Pe(this.items,e);return!t&&N(n)?T(n.key)?n.key.value:n.key:n}set(e,t){if("boolean"!=typeof t)throw new Error("Expected boolean value for set(key, value) in a YAML set, not "+typeof t);const n=Pe(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new $e(e))}toJSON(e,t){return super.toJSON(e,t,Set)}toString(e,t,n){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),t,n);throw new Error("Set items must all have null values")}static from(e,t,n){const{replacer:s}=n,i=new this(e);if(t&&Symbol.iterator in Object(t))for(let r of t)"function"==typeof s&&(r=s.call(t,r,r)),i.items.push(Te(r,null,n));return i}}St.tag="tag:yaml.org,2002:set";const Et={collection:"map",identify:e=>e instanceof Set,nodeClass:St,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,n)=>St.from(e,t,n),resolve(e,t){if(x(e)){if(e.hasAllNullValues(!0))return Object.assign(new St,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};function At(e,t){const n=e[0],s="-"===n||"+"===n?e.substring(1):e,i=e=>t?BigInt(e):Number(e),r=s.replace(/_/g,"").split(":").reduce(((e,t)=>e*i(60)+i(t)),i(0));return"-"===n?i(-1)*r:r}function Ct(e){let{value:t}=e,n=e=>e;if("bigint"==typeof t)n=e=>BigInt(e);else if(isNaN(t)||!isFinite(t))return Re(e);let s="";t<0&&(s="-",t*=n(-1));const i=n(60),r=[t%i];return t<60?r.unshift(0):(t=(t-r[0])/i,r.unshift(t%i),t>=60&&(t=(t-r[0])/i,r.unshift(t))),s+r.map((e=>String(e).padStart(2,"0"))).join(":").replace(/000000\d*$/,"")}const xt={identify:e=>"bigint"==typeof e||Number.isInteger(e),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:n})=>At(e,n),stringify:Ct},Nt={identify:e=>"number"==typeof e,default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:e=>At(e,!1),stringify:Ct},Tt={identify:e=>e instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(e){const t=e.match(Tt.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");const[,n,s,i,r,o,a]=t.map(Number),c=t[7]?Number((t[7]+"00").substr(1,3)):0;let l=Date.UTC(n,s-1,i,r||0,o||0,a||0,c);const u=t[8];if(u&&"Z"!==u){let e=At(u,!1);Math.abs(e)<30&&(e*=60),l-=6e4*e}return new Date(l)},stringify:({value:e})=>e.toISOString().replace(/(T00:00:00)?\.000Z$/,"")},$t=[Me,qe,He,Ke,pt,dt,vt,kt,_t,Ot,ft,mt,gt,rt,Ae,ut,ct,Et,xt,Nt,Tt],It=new Map([["core",tt],["failsafe",[Me,qe,He]],["json",it],["yaml11",$t],["yaml-1.1",$t]]),Lt={binary:rt,bool:Ue,float:Ge,floatExp:Je,floatNaN:We,floatTime:Nt,int:Ze,intHex:et,intOct:ze,intTime:xt,map:Me,merge:Ae,null:Ke,omap:ut,pairs:ct,seq:qe,set:Et,timestamp:Tt},jt={"tag:yaml.org,2002:binary":rt,"tag:yaml.org,2002:merge":Ae,"tag:yaml.org,2002:omap":ut,"tag:yaml.org,2002:pairs":ct,"tag:yaml.org,2002:set":Et,"tag:yaml.org,2002:timestamp":Tt};function Dt(e,t,n){const s=It.get(t);if(s&&!e)return n&&!s.includes(Ae)?s.concat(Ae):s.slice();let i=s;if(!i){if(!Array.isArray(e)){const e=Array.from(It.keys()).filter((e=>"yaml11"!==e)).map((e=>JSON.stringify(e))).join(", ");throw new Error(`Unknown schema "${t}"; use one of ${e} or define customTags array`)}i=[]}if(Array.isArray(e))for(const r of e)i=i.concat(r);else"function"==typeof e&&(i=e(i.slice()));return n&&(i=i.concat(Ae)),i.reduce(((e,t)=>{const n="string"==typeof t?Lt[t]:t;if(!n){const e=JSON.stringify(t),n=Object.keys(Lt).map((e=>JSON.stringify(e))).join(", ");throw new Error(`Unknown custom tag ${e}; use one of ${n}`)}return e.includes(n)||e.push(n),e}),[])}const Pt=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0;class Bt{constructor({compat:e,customTags:t,merge:n,resolveKnownTags:s,schema:i,sortMapEntries:r,toStringDefaults:o}){this.compat=Array.isArray(e)?Dt(e,"compat"):e?Dt(null,e):null,this.name="string"==typeof i&&i||"core",this.knownTags=s?jt:{},this.tags=Dt(t,this.name,n),this.toStringOptions=o??null,Object.defineProperty(this,k,{value:Me}),Object.defineProperty(this,O,{value:He}),Object.defineProperty(this,S,{value:qe}),this.sortMapEntries="function"==typeof r?r:!0===r?Pt:null}clone(){const e=Object.create(Bt.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}}class Mt{constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,E,{value:v});let s=null;"function"==typeof t||Array.isArray(t)?s=t:void 0===n&&t&&(n=t,t=void 0);const i=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},n);this.options=i;let{version:r}=i;n?._directives?(this.directives=n._directives.atDocument(),this.directives.yaml.explicit&&(r=this.directives.yaml.version)):this.directives=new R({version:r}),this.setSchema(r,n),this.contents=void 0===e?null:this.createNode(e,s,n)}clone(){const e=Object.create(Mt.prototype,{[E]:{value:v}});return e.commentBefore=this.commentBefore,e.comment=this.comment,e.errors=this.errors.slice(),e.warnings=this.warnings.slice(),e.options=Object.assign({},this.options),this.directives&&(e.directives=this.directives.clone()),e.schema=this.schema.clone(),e.contents=L(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){Vt(this.contents)&&this.contents.add(e)}addIn(e,t){Vt(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){const n=J(this);e.anchor=!t||n.has(t)?G(t||"a",n):t}return new z(e.anchor)}createNode(e,t,n){let s;if("function"==typeof t)e=t.call({"":e},"",e),s=t;else if(Array.isArray(t)){const e=e=>"number"==typeof e||e instanceof String||e instanceof Number,n=t.filter(e).map(String);n.length>0&&(t=t.concat(n)),s=t}else void 0===n&&t&&(n=t,t=void 0);const{aliasDuplicateObjects:i,anchorPrefix:r,flow:o,keepUndefined:a,onTagObj:c,tag:l}=n??{},{onAnchor:u,setAnchors:h,sourceObjects:p}=function(e,t){const n=[],s=new Map;let i=null;return{onAnchor:s=>{n.push(s),i||(i=J(e));const r=G(t,i);return i.add(r),r},setAnchors:()=>{for(const e of n){const t=s.get(e);if("object"!=typeof t||!t.anchor||!T(t.node)&&!I(t.node)){const t=new Error("Failed to resolve repeated object (this should not happen)");throw t.source=e,t}t.node.anchor=t.anchor}},sourceObjects:s}}(this,r||"a"),d=ne(e,l,{aliasDuplicateObjects:i??!0,keepUndefined:a??!1,onAnchor:u,onTagObj:c,replacer:s,schema:this.schema,sourceObjects:p});return o&&I(d)&&(d.flow=!0),h(),d}createPair(e,t,n={}){const s=this.createNode(e,null,n),i=this.createNode(t,null,n);return new $e(s,i)}delete(e){return!!Vt(this.contents)&&this.contents.delete(e)}deleteIn(e){return ie(e)?null!=this.contents&&(this.contents=null,!0):!!Vt(this.contents)&&this.contents.deleteIn(e)}get(e,t){return I(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return ie(e)?!t&&T(this.contents)?this.contents.value:this.contents:I(this.contents)?this.contents.getIn(e,t):void 0}has(e){return!!I(this.contents)&&this.contents.has(e)}hasIn(e){return ie(e)?void 0!==this.contents:!!I(this.contents)&&this.contents.hasIn(e)}set(e,t){null==this.contents?this.contents=se(this.schema,[e],t):Vt(this.contents)&&this.contents.set(e,t)}setIn(e,t){ie(e)?this.contents=t:null==this.contents?this.contents=se(this.schema,Array.from(e),t):Vt(this.contents)&&this.contents.setIn(e,t)}setSchema(e,t={}){let n;switch("number"==typeof e&&(e=String(e)),e){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new R({version:"1.1"}),n={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=e:this.directives=new R({version:e}),n={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,n=null;break;default:{const t=JSON.stringify(e);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${t}`)}}if(t.schema instanceof Object)this.schema=t.schema;else{if(!n)throw new Error("With a null YAML version, the { schema: Schema } option is required");this.schema=new Bt(Object.assign(n,t))}}toJS({json:e,jsonArg:t,mapAsMap:n,maxAliasCount:s,onAnchor:i,reviver:r}={}){const o={anchors:new Map,doc:this,keep:!e,mapAsMap:!0===n,mapKeyWarned:!1,maxAliasCount:"number"==typeof s?s:100},a=Q(this.contents,t??"",o);if("function"==typeof i)for(const{count:c,res:l}of o.anchors.values())i(l,c);return"function"==typeof r?Y(r,{"":a},"",a):a}toJSON(e,t){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:t})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){const t=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${t}`)}return function(e,t){const n=[];let s=!0===t.directives;if(!1!==t.directives&&e.directives){const t=e.directives.toString(e);t?(n.push(t),s=!0):e.directives.docStart&&(s=!0)}s&&n.push("---");const i=_e(e,t),{commentString:r}=i.options;if(e.commentBefore){1!==n.length&&n.unshift("");const t=r(e.commentBefore);n.unshift(ae(t,""))}let o=!1,a=null;if(e.contents){if(L(e.contents)){if(e.contents.spaceBefore&&s&&n.push(""),e.contents.commentBefore){const t=r(e.contents.commentBefore);n.push(ae(t,""))}i.forceBlockIndent=!!e.comment,a=e.contents.comment}const t=a?void 0:()=>o=!0;let c=Oe(e.contents,i,(()=>a=null),t);a&&(c+=ce(c,"",r(a))),"|"!==c[0]&&">"!==c[0]||"---"!==n[n.length-1]?n.push(c):n[n.length-1]=`--- ${c}`}else n.push(Oe(e.contents,i));if(e.directives?.docEnd)if(e.comment){const t=r(e.comment);t.includes("\n")?(n.push("..."),n.push(ae(t,""))):n.push(`... ${t}`)}else n.push("...");else{let t=e.comment;t&&o&&(t=t.replace(/^\n+/,"")),t&&(o&&!a||""===n[n.length-1]||n.push(""),n.push(ae(r(t),"")))}return n.join("\n")+"\n"}(this,e)}}function Vt(e){if(I(e))return!0;throw new Error("Expected a YAML collection as document contents")}class Ft extends Error{constructor(e,t,n,s){super(),this.name=e,this.code=n,this.message=s,this.pos=t}}class qt extends Ft{constructor(e,t,n){super("YAMLParseError",e,t,n)}}class Ht extends Ft{constructor(e,t,n){super("YAMLWarning",e,t,n)}}const Kt=(e,t)=>n=>{if(-1===n.pos[0])return;n.linePos=n.pos.map((e=>t.linePos(e)));const{line:s,col:i}=n.linePos[0];n.message+=` at line ${s}, column ${i}`;let r=i-1,o=e.substring(t.lineStarts[s-1],t.lineStarts[s]).replace(/[\n\r]+$/,"");if(r>=60&&o.length>80){const e=Math.min(r-39,o.length-79);o="…"+o.substring(e),r-=e-1}if(o.length>80&&(o=o.substring(0,79)+"…"),s>1&&/^ *$/.test(o.substring(0,r))){let n=e.substring(t.lineStarts[s-2],t.lineStarts[s-1]);n.length>80&&(n=n.substring(0,79)+"…\n"),o=n+o}if(/[^ ]/.test(o)){let e=1;const t=n.linePos[1];t&&t.line===s&&t.col>i&&(e=Math.max(1,Math.min(t.col-i,80-r)));const a=" ".repeat(r)+"^".repeat(e);n.message+=`:\n\n${o}\n${a}\n`}};function Ut(e,{flow:t,indicator:n,next:s,offset:i,onError:r,parentIndent:o,startOnNewline:a}){let c=!1,l=a,u=a,h="",p="",d=!1,f=!1,m=null,g=null,y=null,b=null,w=null,v=null,k=null;for(const S of e)switch(f&&("space"!==S.type&&"newline"!==S.type&&"comma"!==S.type&&r(S.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),f=!1),m&&(l&&"comment"!==S.type&&"newline"!==S.type&&r(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),m=null),S.type){case"space":t||"doc-start"===n&&"flow-collection"===s?.type||!S.source.includes("\t")||(m=S),u=!0;break;case"comment":{u||r(S,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");const e=S.source.substring(1)||" ";h?h+=p+e:h=e,p="",l=!1;break}case"newline":l?h?h+=S.source:v&&"seq-item-ind"===n||(c=!0):p+=S.source,l=!0,d=!0,(g||y)&&(b=S),u=!0;break;case"anchor":g&&r(S,"MULTIPLE_ANCHORS","A node can have at most one anchor"),S.source.endsWith(":")&&r(S.offset+S.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),g=S,null===k&&(k=S.offset),l=!1,u=!1,f=!0;break;case"tag":y&&r(S,"MULTIPLE_TAGS","A node can have at most one tag"),y=S,null===k&&(k=S.offset),l=!1,u=!1,f=!0;break;case n:(g||y)&&r(S,"BAD_PROP_ORDER",`Anchors and tags must be after the ${S.source} indicator`),v&&r(S,"UNEXPECTED_TOKEN",`Unexpected ${S.source} in ${t??"collection"}`),v=S,l="seq-item-ind"===n||"explicit-key-ind"===n,u=!1;break;case"comma":if(t){w&&r(S,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),w=S,l=!1,u=!1;break}default:r(S,"UNEXPECTED_TOKEN",`Unexpected ${S.type} token`),l=!1,u=!1}const _=e[e.length-1],O=_?_.offset+_.source.length:i;return f&&s&&"space"!==s.type&&"newline"!==s.type&&"comma"!==s.type&&("scalar"!==s.type||""!==s.source)&&r(s.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m&&(l&&m.indent<=o||"block-map"===s?.type||"block-seq"===s?.type)&&r(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:w,found:v,spaceBefore:c,comment:h,hasNewline:d,anchor:g,tag:y,newlineAfterProp:b,end:O,start:k??O}}function Rt(e){if(!e)return null;switch(e.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(e.source.includes("\n"))return!0;if(e.end)for(const t of e.end)if("newline"===t.type)return!0;return!1;case"flow-collection":for(const t of e.items){for(const e of t.start)if("newline"===e.type)return!0;if(t.sep)for(const e of t.sep)if("newline"===e.type)return!0;if(Rt(t.key)||Rt(t.value))return!0}return!1;default:return!0}}function Wt(e,t,n){if("flow-collection"===t?.type){const s=t.end[0];if(s.indent===e&&("]"===s.source||"}"===s.source)&&Rt(t)){n(s,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}}function Jt(e,t,n){const{uniqueKeys:s}=e.options;if(!1===s)return!1;const i="function"==typeof s?s:(e,t)=>e===t||T(e)&&T(t)&&e.value===t.value;return t.some((e=>i(e.key,n)))}const Gt="All mapping items must start at the same column";function Yt(e,t,n,s){let i="";if(e){let r=!1,o="";for(const a of e){const{source:e,type:c}=a;switch(c){case"space":r=!0;break;case"comment":{n&&!r&&s(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");const t=e.substring(1)||" ";i?i+=o+t:i=t,o="";break}case"newline":i&&(o+=e),r=!0;break;default:s(a,"UNEXPECTED_TOKEN",`Unexpected ${c} at node end`)}t+=e.length}}return{comment:i,offset:t}}const Qt="Block collections are not allowed within flow collections",Xt=e=>e&&("block-map"===e.type||"block-seq"===e.type);function zt(e,t,n,s,i,r){const o="block-map"===n.type?function({composeNode:e,composeEmptyNode:t},n,s,i,r){const o=new(r?.nodeClass??Be)(n.schema);n.atRoot&&(n.atRoot=!1);let a=s.offset,c=null;for(const l of s.items){const{start:r,key:u,sep:h,value:p}=l,d=Ut(r,{indicator:"explicit-key-ind",next:u??h?.[0],offset:a,onError:i,parentIndent:s.indent,startOnNewline:!0}),f=!d.found;if(f){if(u&&("block-seq"===u.type?i(a,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in u&&u.indent!==s.indent&&i(a,"BAD_INDENT",Gt)),!d.anchor&&!d.tag&&!h){c=d.end,d.comment&&(o.comment?o.comment+="\n"+d.comment:o.comment=d.comment);continue}(d.newlineAfterProp||Rt(u))&&i(u??r[r.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else d.found?.indent!==s.indent&&i(a,"BAD_INDENT",Gt);n.atKey=!0;const m=d.end,g=u?e(n,u,d,i):t(n,m,r,null,d,i);n.schema.compat&&Wt(s.indent,u,i),n.atKey=!1,Jt(n,o.items,g)&&i(m,"DUPLICATE_KEY","Map keys must be unique");const y=Ut(h??[],{indicator:"map-value-ind",next:p,offset:g.range[2],onError:i,parentIndent:s.indent,startOnNewline:!u||"block-scalar"===u.type});if(a=y.end,y.found){f&&("block-map"!==p?.type||y.hasNewline||i(a,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),n.options.strict&&d.start<y.found.offset-1024&&i(g.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));const r=p?e(n,p,y,i):t(n,a,h,null,y,i);n.schema.compat&&Wt(s.indent,p,i),a=r.range[2];const c=new $e(g,r);n.options.keepSourceTokens&&(c.srcToken=l),o.items.push(c)}else{f&&i(g.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),y.comment&&(g.comment?g.comment+="\n"+y.comment:g.comment=y.comment);const e=new $e(g);n.options.keepSourceTokens&&(e.srcToken=l),o.items.push(e)}}return c&&c<a&&i(c,"IMPOSSIBLE","Map comment with trailing content"),o.range=[s.offset,a,c??a],o}(e,t,n,s,r):"block-seq"===n.type?function({composeNode:e,composeEmptyNode:t},n,s,i,r){const o=new(r?.nodeClass??Ve)(n.schema);n.atRoot&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let a=s.offset,c=null;for(const{start:l,value:u}of s.items){const r=Ut(l,{indicator:"seq-item-ind",next:u,offset:a,onError:i,parentIndent:s.indent,startOnNewline:!0});if(!r.found){if(!(r.anchor||r.tag||u)){c=r.end,r.comment&&(o.comment=r.comment);continue}u&&"block-seq"===u.type?i(r.end,"BAD_INDENT","All sequence items must start at the same column"):i(a,"MISSING_CHAR","Sequence item without - indicator")}const h=u?e(n,u,r,i):t(n,r.end,l,null,r,i);n.schema.compat&&Wt(s.indent,u,i),a=h.range[2],o.items.push(h)}return o.range=[s.offset,a,c??a],o}(e,t,n,s,r):function({composeNode:e,composeEmptyNode:t},n,s,i,r){const o="{"===s.start.source,a=o?"flow map":"flow sequence",c=new(r?.nodeClass??(o?Be:Ve))(n.schema);c.flow=!0;const l=n.atRoot;l&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let u=s.offset+s.start.source.length;for(let m=0;m<s.items.length;++m){const r=s.items[m],{start:l,key:h,sep:p,value:d}=r,f=Ut(l,{flow:a,indicator:"explicit-key-ind",next:h??p?.[0],offset:u,onError:i,parentIndent:s.indent,startOnNewline:!1});if(!f.found){if(!(f.anchor||f.tag||p||d)){0===m&&f.comma?i(f.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):m<s.items.length-1&&i(f.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${a}`),f.comment&&(c.comment?c.comment+="\n"+f.comment:c.comment=f.comment),u=f.end;continue}!o&&n.options.strict&&Rt(h)&&i(h,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(0===m)f.comma&&i(f.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`);else if(f.comma||i(f.start,"MISSING_CHAR",`Missing , between ${a} items`),f.comment){let e="";e:for(const t of l)switch(t.type){case"comma":case"space":break;case"comment":e=t.source.substring(1);break e;default:break e}if(e){let t=c.items[c.items.length-1];N(t)&&(t=t.value??t.key),t.comment?t.comment+="\n"+e:t.comment=e,f.comment=f.comment.substring(e.length+1)}}if(o||p||f.found){n.atKey=!0;const m=f.end,g=h?e(n,h,f,i):t(n,m,l,null,f,i);Xt(h)&&i(g.range,"BLOCK_IN_FLOW",Qt),n.atKey=!1;const y=Ut(p??[],{flow:a,indicator:"map-value-ind",next:d,offset:g.range[2],onError:i,parentIndent:s.indent,startOnNewline:!1});if(y.found){if(!o&&!f.found&&n.options.strict){if(p)for(const e of p){if(e===y.found)break;if("newline"===e.type){i(e,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}f.start<y.found.offset-1024&&i(y.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else d&&("source"in d&&d.source&&":"===d.source[0]?i(d,"MISSING_CHAR",`Missing space after : in ${a}`):i(y.start,"MISSING_CHAR",`Missing , or : between ${a} items`));const b=d?e(n,d,y,i):y.found?t(n,y.end,p,null,y,i):null;b?Xt(d)&&i(b.range,"BLOCK_IN_FLOW",Qt):y.comment&&(g.comment?g.comment+="\n"+y.comment:g.comment=y.comment);const w=new $e(g,b);if(n.options.keepSourceTokens&&(w.srcToken=r),o){const e=c;Jt(n,e.items,g)&&i(m,"DUPLICATE_KEY","Map keys must be unique"),e.items.push(w)}else{const e=new Be(n.schema);e.flow=!0,e.items.push(w);const t=(b??g).range;e.range=[g.range[0],t[1],t[2]],c.items.push(e)}u=b?b.range[2]:y.end}else{const s=d?e(n,d,f,i):t(n,f.end,p,null,f,i);c.items.push(s),u=s.range[2],Xt(d)&&i(s.range,"BLOCK_IN_FLOW",Qt)}}const h=o?"}":"]",[p,...d]=s.end;let f=u;if(p&&p.source===h)f=p.offset+p.source.length;else{const e=a[0].toUpperCase()+a.substring(1);i(u,l?"MISSING_CHAR":"BAD_INDENT",l?`${e} must end with a ${h}`:`${e} in block collection must be sufficiently indented and end with a ${h}`),p&&1!==p.source.length&&d.unshift(p)}if(d.length>0){const e=Yt(d,f,n.options.strict,i);e.comment&&(c.comment?c.comment+="\n"+e.comment:c.comment=e.comment),c.range=[s.offset,f,e.offset]}else c.range=[s.offset,f,f];return c}(e,t,n,s,r),a=o.constructor;return"!"===i||i===a.tagName?(o.tag=a.tagName,o):(i&&(o.tag=i),o)}function Zt(e,t,n){const s=t.offset,i=function({offset:e,props:t},n,s){if("block-scalar-header"!==t[0].type)return s(t[0],"IMPOSSIBLE","Block scalar header not found"),null;const{source:i}=t[0],r=i[0];let o=0,a="",c=-1;for(let p=1;p<i.length;++p){const t=i[p];if(a||"-"!==t&&"+"!==t){const n=Number(t);!o&&n?o=n:-1===c&&(c=e+p)}else a=t}-1!==c&&s(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${i}`);let l=!1,u="",h=i.length;for(let p=1;p<t.length;++p){const e=t[p];switch(e.type){case"space":l=!0;case"newline":h+=e.source.length;break;case"comment":if(n&&!l){s(e,"MISSING_CHAR","Comments must be separated from other tokens by white space characters")}h+=e.source.length,u=e.source.substring(1);break;case"error":s(e,"UNEXPECTED_TOKEN",e.message),h+=e.source.length;break;default:{s(e,"UNEXPECTED_TOKEN",`Unexpected token in block scalar header: ${e.type}`);const t=e.source;t&&"string"==typeof t&&(h+=t.length)}}}return{mode:r,indent:o,chomp:a,comment:u,length:h}}(t,e.options.strict,n);if(!i)return{value:"",type:null,comment:"",range:[s,s,s]};const r=">"===i.mode?te.BLOCK_FOLDED:te.BLOCK_LITERAL,o=t.source?function(e){const t=e.split(/\n( *)/),n=t[0],s=n.match(/^( *)/),i=[s?.[1]?[s[1],n.slice(s[1].length)]:["",n]];for(let r=1;r<t.length;r+=2)i.push([t[r],t[r+1]]);return i}(t.source):[];let a=o.length;for(let m=o.length-1;m>=0;--m){const e=o[m][1];if(""!==e&&"\r"!==e)break;a=m}if(0===a){const e="+"===i.chomp&&o.length>0?"\n".repeat(Math.max(1,o.length-1)):"";let n=s+i.length;return t.source&&(n+=t.source.length),{value:e,type:r,comment:i.comment,range:[s,n,n]}}let c=t.indent+i.indent,l=t.offset+i.length,u=0;for(let m=0;m<a;++m){const[t,s]=o[m];if(""!==s&&"\r"!==s){if(t.length<c){const e="Block scalars with more-indented leading empty lines must use an explicit indentation indicator";n(l+t.length,"MISSING_CHAR",e)}if(0===i.indent&&(c=t.length),u=m,0===c&&!e.atRoot){n(l,"BAD_INDENT","Block scalar values in collections must be indented")}break}0===i.indent&&t.length>c&&(c=t.length),l+=t.length+s.length+1}for(let m=o.length-1;m>=a;--m)o[m][0].length>c&&(a=m+1);let h="",p="",d=!1;for(let m=0;m<u;++m)h+=o[m][0].slice(c)+"\n";for(let m=u;m<a;++m){let[e,t]=o[m];l+=e.length+t.length+1;const s="\r"===t[t.length-1];if(s&&(t=t.slice(0,-1)),t&&e.length<c){const r=`Block scalar lines must not be less indented than their ${i.indent?"explicit indentation indicator":"first line"}`;n(l-t.length-(s?2:1),"BAD_INDENT",r),e=""}r===te.BLOCK_LITERAL?(h+=p+e.slice(c)+t,p="\n"):e.length>c||"\t"===t[0]?(" "===p?p="\n":d||"\n"!==p||(p="\n\n"),h+=p+e.slice(c)+t,p="\n",d=!0):""===t?"\n"===p?h+="\n":p="\n":(h+=p+t,p=" ",d=!1)}switch(i.chomp){case"-":break;case"+":for(let e=a;e<o.length;++e)h+="\n"+o[e][0].slice(c);"\n"!==h[h.length-1]&&(h+="\n");break;default:h+="\n"}const f=s+i.length+t.source.length;return{value:h,type:r,comment:i.comment,range:[s,f,f]}}function en(e,t,n){const{offset:s,type:i,source:r,end:o}=e;let a,c;const l=(e,t,i)=>n(s+e,t,i);switch(i){case"scalar":a=te.PLAIN,c=function(e,t){let n="";switch(e[0]){case"\t":n="a tab character";break;case",":n="flow indicator character ,";break;case"%":n="directive indicator character %";break;case"|":case">":n=`block scalar indicator ${e[0]}`;break;case"@":case"`":n=`reserved character ${e[0]}`}n&&t(0,"BAD_SCALAR_START",`Plain value cannot start with ${n}`);return tn(e)}(r,l);break;case"single-quoted-scalar":a=te.QUOTE_SINGLE,c=function(e,t){"'"===e[e.length-1]&&1!==e.length||t(e.length,"MISSING_CHAR","Missing closing 'quote");return tn(e.slice(1,-1)).replace(/''/g,"'")}(r,l);break;case"double-quoted-scalar":a=te.QUOTE_DOUBLE,c=function(e,t){let n="";for(let s=1;s<e.length-1;++s){const i=e[s];if("\r"!==i||"\n"!==e[s+1])if("\n"===i){const{fold:t,offset:i}=nn(e,s);n+=t,s=i}else if("\\"===i){let i=e[++s];const r=sn[i];if(r)n+=r;else if("\n"===i)for(i=e[s+1];" "===i||"\t"===i;)i=e[1+ ++s];else if("\r"===i&&"\n"===e[s+1])for(i=e[1+ ++s];" "===i||"\t"===i;)i=e[1+ ++s];else if("x"===i||"u"===i||"U"===i){const r={x:2,u:4,U:8}[i];n+=rn(e,s+1,r,t),s+=r}else{const i=e.substr(s-1,2);t(s-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${i}`),n+=i}}else if(" "===i||"\t"===i){const t=s;let r=e[s+1];for(;" "===r||"\t"===r;)r=e[1+ ++s];"\n"===r||"\r"===r&&"\n"===e[s+2]||(n+=s>t?e.slice(t,s+1):i)}else n+=i}'"'===e[e.length-1]&&1!==e.length||t(e.length,"MISSING_CHAR",'Missing closing "quote');return n}(r,l);break;default:return n(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${i}`),{value:"",type:null,comment:"",range:[s,s+r.length,s+r.length]}}const u=s+r.length,h=Yt(o,u,t,n);return{value:c,type:a,comment:h.comment,range:[s,u,h.offset]}}function tn(e){let t,n;try{t=new RegExp("(.*?)(?<![ \t])[ \t]*\r?\n","sy"),n=new RegExp("[ \t]*(.*?)(?:(?<![ \t])[ \t]*)?\r?\n","sy")}catch{t=/(.*?)[ \t]*\r?\n/sy,n=/[ \t]*(.*?)[ \t]*\r?\n/sy}let s=t.exec(e);if(!s)return e;let i=s[1],r=" ",o=t.lastIndex;for(n.lastIndex=o;s=n.exec(e);)""===s[1]?"\n"===r?i+=r:r="\n":(i+=r+s[1],r=" "),o=n.lastIndex;const a=/[ \t]*(.*)/sy;return a.lastIndex=o,s=a.exec(e),i+r+(s?.[1]??"")}function nn(e,t){let n="",s=e[t+1];for(;!(" "!==s&&"\t"!==s&&"\n"!==s&&"\r"!==s||"\r"===s&&"\n"!==e[t+2]);)"\n"===s&&(n+="\n"),s=e[(t+=1)+1];return n||(n=" "),{fold:n,offset:t}}const sn={0:"\0",a:"",b:"\b",e:"",f:"\f",n:"\n",r:"\r",t:"\t",v:"\v",N:"
",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\","\t":"\t"};function rn(e,t,n,s){const i=e.substr(t,n),r=i.length===n&&/^[0-9a-fA-F]+$/.test(i)?parseInt(i,16):NaN;if(isNaN(r)){const i=e.substr(t-2,n+2);return s(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${i}`),i}return String.fromCodePoint(r)}function on(e,t,n,s){const{value:i,type:r,comment:o,range:a}="block-scalar"===t.type?Zt(e,t,s):en(t,e.options.strict,s),c=n?e.directives.tagName(n.source,(e=>s(n,"TAG_RESOLVE_FAILED",e))):null;let l,u;l=e.options.stringKeys&&e.atKey?e.schema[O]:c?function(e,t,n,s,i){if("!"===n)return e[O];const r=[];for(const a of e.tags)if(!a.collection&&a.tag===n){if(!a.default||!a.test)return a;r.push(a)}for(const a of r)if(a.test?.test(t))return a;const o=e.knownTags[n];if(o&&!o.collection)return e.tags.push(Object.assign({},o,{default:!1,test:void 0})),o;return i(s,"TAG_RESOLVE_FAILED",`Unresolved tag: ${n}`,"tag:yaml.org,2002:str"!==n),e[O]}(e.schema,i,c,n,s):"scalar"===t.type?function({atKey:e,directives:t,schema:n},s,i,r){const o=n.tags.find((t=>(!0===t.default||e&&"key"===t.default)&&t.test?.test(s)))||n[O];if(n.compat){const e=n.compat.find((e=>e.default&&e.test?.test(s)))??n[O];if(o.tag!==e.tag){r(i,"TAG_RESOLVE_FAILED",`Value may be parsed as either ${t.tagString(o.tag)} or ${t.tagString(e.tag)}`,!0)}}return o}(e,i,t,s):e.schema[O];try{const r=l.resolve(i,(e=>s(n??t,"TAG_RESOLVE_FAILED",e)),e.options);u=T(r)?r:new te(r)}catch(h){const e=h instanceof Error?h.message:String(h);s(n??t,"TAG_RESOLVE_FAILED",e),u=new te(i)}return u.range=a,u.source=i,r&&(u.type=r),c&&(u.tag=c),l.format&&(u.format=l.format),o&&(u.comment=o),u}function an(e,t,n){if(t){null===n&&(n=t.length);for(let s=n-1;s>=0;--s){let n=t[s];switch(n.type){case"space":case"comment":case"newline":e-=n.source.length;continue}for(n=t[++s];"space"===n?.type;)e+=n.source.length,n=t[++s];break}}return e}const cn={composeNode:ln,composeEmptyNode:un};function ln(e,t,n,s){const i=e.atKey,{spaceBefore:r,comment:o,anchor:a,tag:c}=n;let l,u=!0;switch(t.type){case"alias":l=function({options:e},{offset:t,source:n,end:s},i){const r=new z(n.substring(1));""===r.source&&i(t,"BAD_ALIAS","Alias cannot be an empty string");r.source.endsWith(":")&&i(t+n.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);const o=t+n.length,a=Yt(s,o,e.strict,i);r.range=[t,o,a.offset],a.comment&&(r.comment=a.comment);return r}(e,t,s),(a||c)&&s(t,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=on(e,t,c,s),a&&(l.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":l=function(e,t,n,s,i){const r=s.tag,o=r?t.directives.tagName(r.source,(e=>i(r,"TAG_RESOLVE_FAILED",e))):null;if("block-seq"===n.type){const{anchor:e,newlineAfterProp:t}=s,n=e&&r?e.offset>r.offset?e:r:e??r;n&&(!t||t.offset<n.offset)&&i(n,"MISSING_CHAR","Missing newline after block sequence props")}const a="block-map"===n.type?"map":"block-seq"===n.type?"seq":"{"===n.start.source?"map":"seq";if(!r||!o||"!"===o||o===Be.tagName&&"map"===a||o===Ve.tagName&&"seq"===a)return zt(e,t,n,i,o);let c=t.schema.tags.find((e=>e.tag===o&&e.collection===a));if(!c){const s=t.schema.knownTags[o];if(!s||s.collection!==a)return s?.collection?i(r,"BAD_COLLECTION_TYPE",`${s.tag} used for ${a} collection, but expects ${s.collection}`,!0):i(r,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),zt(e,t,n,i,o);t.schema.tags.push(Object.assign({},s,{default:!1})),c=s}const l=zt(e,t,n,i,o,c),u=c.resolve?.(l,(e=>i(r,"TAG_RESOLVE_FAILED",e)),t.options)??l,h=L(u)?u:new te(u);return h.range=l.range,h.tag=o,c?.format&&(h.format=c.format),h}(cn,e,t,n,s),a&&(l.anchor=a.source.substring(1));break;default:s(t,"UNEXPECTED_TOKEN","error"===t.type?t.message:`Unsupported token (type: ${t.type})`),l=un(e,t.offset,void 0,null,n,s),u=!1}if(a&&""===l.anchor&&s(a,"BAD_ALIAS","Anchor cannot be an empty string"),i&&e.options.stringKeys&&(!T(l)||"string"!=typeof l.value||l.tag&&"tag:yaml.org,2002:str"!==l.tag)){s(c??t,"NON_STRING_KEY","With stringKeys, all keys must be strings")}return r&&(l.spaceBefore=!0),o&&("scalar"===t.type&&""===t.source?l.comment=o:l.commentBefore=o),e.options.keepSourceTokens&&u&&(l.srcToken=t),l}function un(e,t,n,s,{spaceBefore:i,comment:r,anchor:o,tag:a,end:c},l){const u=on(e,{type:"scalar",offset:an(t,n,s),indent:-1,source:""},a,l);return o&&(u.anchor=o.source.substring(1),""===u.anchor&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),i&&(u.spaceBefore=!0),r&&(u.comment=r,u.range[2]=c),u}function hn(e){if("number"==typeof e)return[e,e+1];if(Array.isArray(e))return 2===e.length?e:[e[0],e[1]];const{offset:t,source:n}=e;return[t,t+("string"==typeof n?n.length:1)]}function pn(e){let t="",n=!1,s=!1;for(let i=0;i<e.length;++i){const r=e[i];switch(r[0]){case"#":t+=(""===t?"":s?"\n\n":"\n")+(r.substring(1)||" "),n=!0,s=!1;break;case"%":"#"!==e[i+1]?.[0]&&(i+=1),n=!1;break;default:n||(s=!0),n=!1}}return{comment:t,afterEmptyLine:s}}class dn{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(e,t,n,s)=>{const i=hn(e);s?this.warnings.push(new Ht(i,t,n)):this.errors.push(new qt(i,t,n))},this.directives=new R({version:e.version||"1.2"}),this.options=e}decorate(e,t){const{comment:n,afterEmptyLine:s}=pn(this.prelude);if(n){const i=e.contents;if(t)e.comment=e.comment?`${e.comment}\n${n}`:n;else if(s||e.directives.docStart||!i)e.commentBefore=n;else if(I(i)&&!i.flow&&i.items.length>0){let e=i.items[0];N(e)&&(e=e.key);const t=e.commentBefore;e.commentBefore=t?`${n}\n${t}`:n}else{const e=i.commentBefore;i.commentBefore=e?`${n}\n${e}`:n}}t?(Array.prototype.push.apply(e.errors,this.errors),Array.prototype.push.apply(e.warnings,this.warnings)):(e.errors=this.errors,e.warnings=this.warnings),this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:pn(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(e,t=!1,n=-1){for(const s of e)yield*this.next(s);yield*this.end(t,n)}*next(e){switch(e.type){case"directive":this.directives.add(e.source,((t,n,s)=>{const i=hn(e);i[0]+=t,this.onError(i,"BAD_DIRECTIVE",n,s)})),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{const t=function(e,t,{offset:n,start:s,value:i,end:r},o){const a=Object.assign({_directives:t},e),c=new Mt(void 0,a),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=Ut(s,{indicator:"doc-start",next:i??r?.[0],offset:n,onError:o,parentIndent:0,startOnNewline:!0});u.found&&(c.directives.docStart=!0,!i||"block-map"!==i.type&&"block-seq"!==i.type||u.hasNewline||o(u.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=i?ln(l,i,u,o):un(l,u.end,s,null,u,o);const h=c.contents.range[2],p=Yt(r,h,!1,o);return p.comment&&(c.comment=p.comment),c.range=[n,h,p.offset],c}(this.options,this.directives,e,this.onError);this.atDirectives&&!t.directives.docStart&&this.onError(e,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(t,!1),this.doc&&(yield this.doc),this.doc=t,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(e.source);break;case"error":{const t=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,n=new qt(hn(e),"UNEXPECTED_TOKEN",t);this.atDirectives||!this.doc?this.errors.push(n):this.doc.errors.push(n);break}case"doc-end":{if(!this.doc){const t="Unexpected doc-end without preceding document";this.errors.push(new qt(hn(e),"UNEXPECTED_TOKEN",t));break}this.doc.directives.docEnd=!0;const t=Yt(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),t.comment){const e=this.doc.comment;this.doc.comment=e?`${e}\n${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new qt(hn(e),"UNEXPECTED_TOKEN",`Unsupported token ${e.type}`))}}*end(e=!1,t=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){const e=Object.assign({_directives:this.directives},this.options),n=new Mt(void 0,e);this.atDirectives&&this.onError(t,"MISSING_CHAR","Missing directives-end indicator line"),n.range=[0,t,t],this.decorate(n,!1),yield n}}}function fn(e,t){if(t)for(const n of t)switch(n.type){case"space":case"comment":e.push(n);break;case"newline":return e.push(n),!0}return!1}function mn(e,t,n){switch(e.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":e.type=n,e.source=t;break;case"block-scalar":{const s=e.props.slice(1);let i=t.length;"block-scalar-header"===e.props[0].type&&(i-=e.props[0].source.length);for(const e of s)e.offset+=i;delete e.props,Object.assign(e,{type:n,source:t,end:s});break}case"block-map":case"block-seq":{const s={type:"newline",offset:e.offset+t.length,indent:e.indent,source:"\n"};delete e.items,Object.assign(e,{type:n,source:t,end:[s]});break}default:{const s="indent"in e?e.indent:-1,i="end"in e&&Array.isArray(e.end)?e.end.filter((e=>"space"===e.type||"comment"===e.type||"newline"===e.type)):[];for(const t of Object.keys(e))"type"!==t&&"offset"!==t&&delete e[t];Object.assign(e,{type:n,indent:s,source:t,end:i})}}}function gn(e){switch(e.type){case"block-scalar":{let t="";for(const n of e.props)t+=gn(n);return t+e.source}case"block-map":case"block-seq":{let t="";for(const n of e.items)t+=yn(n);return t}case"flow-collection":{let t=e.start.source;for(const n of e.items)t+=yn(n);for(const n of e.end)t+=n.source;return t}case"document":{let t=yn(e);if(e.end)for(const n of e.end)t+=n.source;return t}default:{let t=e.source;if("end"in e&&e.end)for(const n of e.end)t+=n.source;return t}}}function yn({start:e,key:t,sep:n,value:s}){let i="";for(const r of e)i+=r.source;if(t&&(i+=gn(t)),n)for(const r of n)i+=r.source;return s&&(i+=gn(s)),i}const bn=Symbol("break visit"),wn=Symbol("skip children"),vn=Symbol("remove item");function kn(e,t){"type"in e&&"document"===e.type&&(e={start:e.start,value:e.value}),_n(Object.freeze([]),e,t)}function _n(e,t,n){let s=n(t,e);if("symbol"==typeof s)return s;for(const i of["key","value"]){const r=t[i];if(r&&"items"in r){for(let t=0;t<r.items.length;++t){const s=_n(Object.freeze(e.concat([[i,t]])),r.items[t],n);if("number"==typeof s)t=s-1;else{if(s===bn)return bn;s===vn&&(r.items.splice(t,1),t-=1)}}"function"==typeof s&&"key"===i&&(s=s(t,e))}}return"function"==typeof s?s(t,e):s}kn.BREAK=bn,kn.SKIP=wn,kn.REMOVE=vn,kn.itemAtPath=(e,t)=>{let n=e;for(const[s,i]of t){const e=n?.[s];if(!e||!("items"in e))return;n=e.items[i]}return n},kn.parentCollection=(e,t)=>{const n=kn.itemAtPath(e,t.slice(0,-1)),s=t[t.length-1][0],i=n?.[s];if(i&&"items"in i)return i;throw new Error("Parent collection not found")};const On="\ufeff",Sn="",En="",An="";function Cn(e){switch(e){case On:return"byte-order-mark";case Sn:return"doc-mode";case En:return"flow-error-end";case An:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case"\n":case"\r\n":return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(e[0]){case" ":case"\t":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}const xn=Object.freeze(Object.defineProperty({__proto__:null,BOM:On,DOCUMENT:Sn,FLOW_END:En,SCALAR:An,createScalarToken:function(e,t){const{implicitKey:n=!1,indent:s,inFlow:i=!1,offset:r=-1,type:o="PLAIN"}=t,a=ke({type:o,value:e},{implicitKey:n,indent:s>0?" ".repeat(s):"",inFlow:i,options:{blockQuote:!0,lineWidth:-1}}),c=t.end??[{type:"newline",offset:-1,indent:s,source:"\n"}];switch(a[0]){case"|":case">":{const e=a.indexOf("\n"),t=a.substring(0,e),n=a.substring(e+1)+"\n",i=[{type:"block-scalar-header",offset:r,indent:s,source:t}];return fn(i,c)||i.push({type:"newline",offset:-1,indent:s,source:"\n"}),{type:"block-scalar",offset:r,indent:s,props:i,source:n}}case'"':return{type:"double-quoted-scalar",offset:r,indent:s,source:a,end:c};case"'":return{type:"single-quoted-scalar",offset:r,indent:s,source:a,end:c};default:return{type:"scalar",offset:r,indent:s,source:a,end:c}}},isCollection:e=>!!e&&"items"in e,isScalar:e=>!!e&&("scalar"===e.type||"single-quoted-scalar"===e.type||"double-quoted-scalar"===e.type||"block-scalar"===e.type),prettyToken:function(e){switch(e){case On:return"<BOM>";case Sn:return"<DOC>";case En:return"<FLOW_END>";case An:return"<SCALAR>";default:return JSON.stringify(e)}},resolveAsScalar:function(e,t=!0,n){if(e){const s=(e,t,s)=>{const i="number"==typeof e?e:Array.isArray(e)?e[0]:e.offset;if(!n)throw new qt([i,i+1],t,s);n(i,t,s)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return en(e,t,s);case"block-scalar":return Zt({options:{strict:t}},e,s)}}return null},setScalarValue:function(e,t,n={}){let{afterKey:s=!1,implicitKey:i=!1,inFlow:r=!1,type:o}=n,a="indent"in e?e.indent:null;if(s&&"number"==typeof a&&(a+=2),!o)switch(e.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{const t=e.props[0];if("block-scalar-header"!==t.type)throw new Error("Invalid block scalar header");o=">"===t.source[0]?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}const c=ke({type:o,value:t},{implicitKey:i||null===a,indent:null!==a&&a>0?" ".repeat(a):"",inFlow:r,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":!function(e,t){const n=t.indexOf("\n"),s=t.substring(0,n),i=t.substring(n+1)+"\n";if("block-scalar"===e.type){const t=e.props[0];if("block-scalar-header"!==t.type)throw new Error("Invalid block scalar header");t.source=s,e.source=i}else{const{offset:t}=e,n="indent"in e?e.indent:-1,r=[{type:"block-scalar-header",offset:t,indent:n,source:s}];fn(r,"end"in e?e.end:void 0)||r.push({type:"newline",offset:-1,indent:n,source:"\n"});for(const s of Object.keys(e))"type"!==s&&"offset"!==s&&delete e[s];Object.assign(e,{type:"block-scalar",indent:n,props:r,source:i})}}(e,c);break;case'"':mn(e,c,"double-quoted-scalar");break;case"'":mn(e,c,"single-quoted-scalar");break;default:mn(e,c,"scalar")}},stringify:e=>"type"in e?gn(e):yn(e),tokenType:Cn,visit:kn},Symbol.toStringTag,{value:"Module"}));function Nn(e){switch(e){case void 0:case" ":case"\n":case"\r":case"\t":return!0;default:return!1}}const Tn=new Set("0123456789ABCDEFabcdef"),$n=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),In=new Set(",[]{}"),Ln=new Set(" ,[]{}\n\r\t"),jn=e=>!e||Ln.has(e);class Dn{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,t=!1){if(e){if("string"!=typeof e)throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!t;let n=this.next??"stream";for(;n&&(t||this.hasChars(1));)n=yield*this.parseNext(n)}atLineEnd(){let e=this.pos,t=this.buffer[e];for(;" "===t||"\t"===t;)t=this.buffer[++e];return!t||"#"===t||"\n"===t||"\r"===t&&"\n"===this.buffer[e+1]}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let t=this.buffer[e];if(this.indentNext>0){let n=0;for(;" "===t;)t=this.buffer[++n+e];if("\r"===t){const t=this.buffer[n+e+1];if("\n"===t||!t&&!this.atEnd)return e+n+1}return"\n"===t||n>=this.indentNext||!t&&!this.atEnd?e+n:-1}if("-"===t||"."===t){const t=this.buffer.substr(e,3);if(("---"===t||"..."===t)&&Nn(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return("number"!=typeof e||-1!==e&&e<this.pos)&&(e=this.buffer.indexOf("\n",this.pos),this.lineEndPos=e),-1===e?this.atEnd?this.buffer.substring(this.pos):null:("\r"===this.buffer[e-1]&&(e-=1),this.buffer.substring(this.pos,e))}hasChars(e){return this.pos+e<=this.buffer.length}setNext(e){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=e,null}peek(e){return this.buffer.substr(this.pos,e)}*parseNext(e){switch(e){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let e=this.getLine();if(null===e)return this.setNext("stream");if(e[0]===On&&(yield*this.pushCount(1),e=e.substring(1)),"%"===e[0]){let t=e.length,n=e.indexOf("#");for(;-1!==n;){const s=e[n-1];if(" "===s||"\t"===s){t=n-1;break}n=e.indexOf("#",n+1)}for(;;){const n=e[t-1];if(" "!==n&&"\t"!==n)break;t-=1}const s=(yield*this.pushCount(t))+(yield*this.pushSpaces(!0));return yield*this.pushCount(e.length-s),this.pushNewline(),"stream"}if(this.atLineEnd()){const t=yield*this.pushSpaces(!0);return yield*this.pushCount(e.length-t),yield*this.pushNewline(),"stream"}return yield Sn,yield*this.parseLineStart()}*parseLineStart(){const e=this.charAt(0);if(!e&&!this.atEnd)return this.setNext("line-start");if("-"===e||"."===e){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");const e=this.peek(3);if(("---"===e||"..."===e)&&Nn(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,"---"===e?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!Nn(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){const[e,t]=this.peek(2);if(!t&&!this.atEnd)return this.setNext("block-start");if(("-"===e||"?"===e||":"===e)&&Nn(t)){const e=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=e,yield*this.parseBlockStart()}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);const e=this.getLine();if(null===e)return this.setNext("doc");let t=yield*this.pushIndicators();switch(e[t]){case"#":yield*this.pushCount(e.length-t);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(jn),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return t+=(yield*this.parseBlockScalarHeader()),t+=(yield*this.pushSpaces(!0)),yield*this.pushCount(e.length-t),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,t,n=-1;do{e=yield*this.pushNewline(),e>0?(t=yield*this.pushSpaces(!1),this.indentValue=n=t):t=0,t+=(yield*this.pushSpaces(!0))}while(e+t>0);const s=this.getLine();if(null===s)return this.setNext("flow");if(-1!==n&&n<this.indentNext&&"#"!==s[0]||0===n&&(s.startsWith("---")||s.startsWith("..."))&&Nn(s[3])){if(!(n===this.indentNext-1&&1===this.flowLevel&&("]"===s[0]||"}"===s[0])))return this.flowLevel=0,yield En,yield*this.parseLineStart()}let i=0;for(;","===s[i];)i+=(yield*this.pushCount(1)),i+=(yield*this.pushSpaces(!0)),this.flowKey=!1;switch(i+=(yield*this.pushIndicators()),s[i]){case void 0:return"flow";case"#":return yield*this.pushCount(s.length-i),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil(jn),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{const e=this.charAt(1);if(this.flowKey||Nn(e)||","===e)return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){const e=this.charAt(0);let t=this.buffer.indexOf(e,this.pos+1);if("'"===e)for(;-1!==t&&"'"===this.buffer[t+1];)t=this.buffer.indexOf("'",t+2);else for(;-1!==t;){let e=0;for(;"\\"===this.buffer[t-1-e];)e+=1;if(e%2==0)break;t=this.buffer.indexOf('"',t+1)}const n=this.buffer.substring(0,t);let s=n.indexOf("\n",this.pos);if(-1!==s){for(;-1!==s;){const e=this.continueScalar(s+1);if(-1===e)break;s=n.indexOf("\n",e)}-1!==s&&(t=s-("\r"===n[s-1]?2:1))}if(-1===t){if(!this.atEnd)return this.setNext("quoted-scalar");t=this.buffer.length}return yield*this.pushToIndex(t+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let e=this.pos;for(;;){const t=this.buffer[++e];if("+"===t)this.blockScalarKeep=!0;else if(t>"0"&&t<="9")this.blockScalarIndent=Number(t)-1;else if("-"!==t)break}return yield*this.pushUntil((e=>Nn(e)||"#"===e))}*parseBlockScalar(){let e,t=this.pos-1,n=0;e:for(let i=this.pos;e=this.buffer[i];++i)switch(e){case" ":n+=1;break;case"\n":t=i,n=0;break;case"\r":{const e=this.buffer[i+1];if(!e&&!this.atEnd)return this.setNext("block-scalar");if("\n"===e)break}default:break e}if(!e&&!this.atEnd)return this.setNext("block-scalar");if(n>=this.indentNext){-1===this.blockScalarIndent?this.indentNext=n:this.indentNext=this.blockScalarIndent+(0===this.indentNext?1:this.indentNext);do{const e=this.continueScalar(t+1);if(-1===e)break;t=this.buffer.indexOf("\n",e)}while(-1!==t);if(-1===t){if(!this.atEnd)return this.setNext("block-scalar");t=this.buffer.length}}let s=t+1;for(e=this.buffer[s];" "===e;)e=this.buffer[++s];if("\t"===e){for(;"\t"===e||" "===e||"\r"===e||"\n"===e;)e=this.buffer[++s];t=s-1}else if(!this.blockScalarKeep)for(;;){let e=t-1,s=this.buffer[e];"\r"===s&&(s=this.buffer[--e]);const i=e;for(;" "===s;)s=this.buffer[--e];if(!("\n"===s&&e>=this.pos&&e+1+n>i))break;t=e}return yield An,yield*this.pushToIndex(t+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){const e=this.flowLevel>0;let t,n=this.pos-1,s=this.pos-1;for(;t=this.buffer[++s];)if(":"===t){const t=this.buffer[s+1];if(Nn(t)||e&&In.has(t))break;n=s}else if(Nn(t)){let i=this.buffer[s+1];if("\r"===t&&("\n"===i?(s+=1,t="\n",i=this.buffer[s+1]):n=s),"#"===i||e&&In.has(i))break;if("\n"===t){const e=this.continueScalar(s+1);if(-1===e)break;s=Math.max(s,e-2)}}else{if(e&&In.has(t))break;n=s}return t||this.atEnd?(yield An,yield*this.pushToIndex(n+1,!0),e?"flow":"doc"):this.setNext("plain-scalar")}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,t){const n=this.buffer.slice(this.pos,e);return n?(yield n,this.pos+=n.length,n.length):(t&&(yield""),0)}*pushIndicators(){switch(this.charAt(0)){case"!":return(yield*this.pushTag())+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"&":return(yield*this.pushUntil(jn))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"-":case"?":case":":{const e=this.flowLevel>0,t=this.charAt(1);if(Nn(t)||e&&In.has(t))return e?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,(yield*this.pushCount(1))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators())}}return 0}*pushTag(){if("<"===this.charAt(1)){let e=this.pos+2,t=this.buffer[e];for(;!Nn(t)&&">"!==t;)t=this.buffer[++e];return yield*this.pushToIndex(">"===t?e+1:e,!1)}{let e=this.pos+1,t=this.buffer[e];for(;t;)if($n.has(t))t=this.buffer[++e];else{if("%"!==t||!Tn.has(this.buffer[e+1])||!Tn.has(this.buffer[e+2]))break;t=this.buffer[e+=3]}return yield*this.pushToIndex(e,!1)}}*pushNewline(){const e=this.buffer[this.pos];return"\n"===e?yield*this.pushCount(1):"\r"===e&&"\n"===this.charAt(1)?yield*this.pushCount(2):0}*pushSpaces(e){let t,n=this.pos-1;do{t=this.buffer[++n]}while(" "===t||e&&"\t"===t);const s=n-this.pos;return s>0&&(yield this.buffer.substr(this.pos,s),this.pos=n),s}*pushUntil(e){let t=this.pos,n=this.buffer[t];for(;!e(n);)n=this.buffer[++t];return yield*this.pushToIndex(t,!1)}}class Pn{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let t=0,n=this.lineStarts.length;for(;t<n;){const s=t+n>>1;this.lineStarts[s]<e?t=s+1:n=s}if(this.lineStarts[t]===e)return{line:t+1,col:1};if(0===t)return{line:0,col:e};return{line:t,col:e-this.lineStarts[t-1]+1}}}}function Bn(e,t){for(let n=0;n<e.length;++n)if(e[n].type===t)return!0;return!1}function Mn(e){for(let t=0;t<e.length;++t)switch(e[t].type){case"space":case"comment":case"newline":break;default:return t}return-1}function Vn(e){switch(e?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function Fn(e){switch(e.type){case"document":return e.start;case"block-map":{const t=e.items[e.items.length-1];return t.sep??t.start}case"block-seq":return e.items[e.items.length-1].start;default:return[]}}function qn(e){if(0===e.length)return[];let t=e.length;e:for(;--t>=0;)switch(e[t].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;"space"===e[++t]?.type;);return e.splice(t,e.length)}function Hn(e){if("flow-seq-start"===e.start.type)for(const t of e.items)!t.sep||t.value||Bn(t.start,"explicit-key-ind")||Bn(t.sep,"map-value-ind")||(t.key&&(t.value=t.key),delete t.key,Vn(t.value)?t.value.end?Array.prototype.push.apply(t.value.end,t.sep):t.value.end=t.sep:Array.prototype.push.apply(t.start,t.sep),delete t.sep)}class Kn{constructor(e){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new Dn,this.onNewLine=e}*parse(e,t=!1){this.onNewLine&&0===this.offset&&this.onNewLine(0);for(const n of this.lexer.lex(e,t))yield*this.next(n);t||(yield*this.end())}*next(e){if(this.source=e,this.atScalar)return this.atScalar=!1,yield*this.step(),void(this.offset+=e.length);const t=Cn(e);if(t)if("scalar"===t)this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=t,yield*this.step(),t){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+e.length);break;case"space":this.atNewLine&&" "===e[0]&&(this.indent+=e.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=e.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=e.length}else{const t=`Not a YAML token: ${e}`;yield*this.pop({type:"error",offset:this.offset,message:t,source:e}),this.offset+=e.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){const e=this.peek(1);if("doc-end"!==this.type||e&&"doc-end"===e.type){if(!e)return yield*this.stream();switch(e.type){case"document":return yield*this.document(e);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(e);case"block-scalar":return yield*this.blockScalar(e);case"block-map":return yield*this.blockMap(e);case"block-seq":return yield*this.blockSequence(e);case"flow-collection":return yield*this.flowCollection(e);case"doc-end":return yield*this.documentEnd(e)}yield*this.pop()}else{for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source})}}peek(e){return this.stack[this.stack.length-e]}*pop(e){const t=e??this.stack.pop();if(t)if(0===this.stack.length)yield t;else{const e=this.peek(1);switch("block-scalar"===t.type?t.indent="indent"in e?e.indent:0:"flow-collection"===t.type&&"document"===e.type&&(t.indent=0),"flow-collection"===t.type&&Hn(t),e.type){case"document":e.value=t;break;case"block-scalar":e.props.push(t);break;case"block-map":{const n=e.items[e.items.length-1];if(n.value)return e.items.push({start:[],key:t,sep:[]}),void(this.onKeyLine=!0);if(!n.sep)return Object.assign(n,{key:t,sep:[]}),void(this.onKeyLine=!n.explicitKey);n.value=t;break}case"block-seq":{const n=e.items[e.items.length-1];n.value?e.items.push({start:[],value:t}):n.value=t;break}case"flow-collection":{const n=e.items[e.items.length-1];return void(!n||n.value?e.items.push({start:[],key:t,sep:[]}):n.sep?n.value=t:Object.assign(n,{key:t,sep:[]}))}default:yield*this.pop(),yield*this.pop(t)}if(!("document"!==e.type&&"block-map"!==e.type&&"block-seq"!==e.type||"block-map"!==t.type&&"block-seq"!==t.type)){const n=t.items[t.items.length-1];n&&!n.sep&&!n.value&&n.start.length>0&&-1===Mn(n.start)&&(0===t.indent||n.start.every((e=>"comment"!==e.type||e.indent<t.indent)))&&("document"===e.type?e.end=n.start:e.items.push({start:n.start}),t.items.splice(-1,1))}}else{const e="Tried to pop an empty stack";yield{type:"error",offset:this.offset,source:"",message:e}}}*stream(){switch(this.type){case"directive-line":return void(yield{type:"directive",offset:this.offset,source:this.source});case"byte-order-mark":case"space":case"comment":case"newline":return void(yield this.sourceToken);case"doc-mode":case"doc-start":{const e={type:"document",offset:this.offset,start:[]};return"doc-start"===this.type&&e.start.push(this.sourceToken),void this.stack.push(e)}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(e){if(e.value)return yield*this.lineEnd(e);switch(this.type){case"doc-start":return void(-1!==Mn(e.start)?(yield*this.pop(),yield*this.step()):e.start.push(this.sourceToken));case"anchor":case"tag":case"space":case"comment":case"newline":return void e.start.push(this.sourceToken)}const t=this.startBlockValue(e);t?this.stack.push(t):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(e){if("map-value-ind"===this.type){const t=qn(Fn(this.peek(2)));let n;e.end?(n=e.end,n.push(this.sourceToken),delete e.end):n=[this.sourceToken];const s={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:t,key:e,sep:n}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(e)}*blockScalar(e){switch(this.type){case"space":case"comment":case"newline":return void e.props.push(this.sourceToken);case"scalar":if(e.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let e=this.source.indexOf("\n")+1;for(;0!==e;)this.onNewLine(this.offset+e),e=this.source.indexOf("\n",e)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){const t=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,t.value){const n="end"in t.value?t.value.end:void 0,s=Array.isArray(n)?n[n.length-1]:void 0;"comment"===s?.type?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){const n=e.items[e.items.length-2],s=n?.value?.end;if(Array.isArray(s))return Array.prototype.push.apply(s,t.start),s.push(this.sourceToken),void e.items.pop()}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){const n=!this.onKeyLine&&this.indent===e.indent,s=n&&(t.sep||t.explicitKey)&&"seq-item-ind"!==this.type;let i=[];if(s&&t.sep&&!t.value){const n=[];for(let s=0;s<t.sep.length;++s){const i=t.sep[s];switch(i.type){case"newline":n.push(s);break;case"space":break;case"comment":i.indent>e.indent&&(n.length=0);break;default:n.length=0}}n.length>=2&&(i=t.sep.splice(n[1]))}switch(this.type){case"anchor":case"tag":return void(s||t.value?(i.push(this.sourceToken),e.items.push({start:i}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken));case"explicit-key-ind":return t.sep||t.explicitKey?s||t.value?(i.push(this.sourceToken),e.items.push({start:i,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}):(t.start.push(this.sourceToken),t.explicitKey=!0),void(this.onKeyLine=!0);case"map-value-ind":if(t.explicitKey)if(t.sep)if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Bn(t.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]});else if(Vn(t.key)&&!Bn(t.sep,"newline")){const e=qn(t.start),n=t.key,s=t.sep;s.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:e,key:n,sep:s}]})}else i.length>0?t.sep=t.sep.concat(i,this.sourceToken):t.sep.push(this.sourceToken);else if(Bn(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{const e=qn(t.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:e,key:null,sep:[this.sourceToken]}]})}else t.sep?t.value||s?e.items.push({start:i,key:null,sep:[this.sourceToken]}):Bn(t.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});return void(this.onKeyLine=!0);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{const n=this.flowScalar(this.type);return void(s||t.value?(e.items.push({start:i,key:n,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(n):(Object.assign(t,{key:n,sep:[]}),this.onKeyLine=!0))}default:{const t=this.startBlockValue(e);if(t)return n&&"block-seq"!==t.type&&e.items.push({start:i}),void this.stack.push(t)}}}yield*this.pop(),yield*this.step()}*blockSequence(e){const t=e.items[e.items.length-1];switch(this.type){case"newline":if(t.value){const n="end"in t.value?t.value.end:void 0,s=Array.isArray(n)?n[n.length-1]:void 0;"comment"===s?.type?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){const n=e.items[e.items.length-2],s=n?.value?.end;if(Array.isArray(s))return Array.prototype.push.apply(s,t.start),s.push(this.sourceToken),void e.items.pop()}t.start.push(this.sourceToken)}return;case"anchor":case"tag":if(t.value||this.indent<=e.indent)break;return void t.start.push(this.sourceToken);case"seq-item-ind":if(this.indent!==e.indent)break;return void(t.value||Bn(t.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken))}if(this.indent>e.indent){const t=this.startBlockValue(e);if(t)return void this.stack.push(t)}yield*this.pop(),yield*this.step()}*flowCollection(e){const t=e.items[e.items.length-1];if("flow-error-end"===this.type){let e;do{yield*this.pop(),e=this.peek(1)}while(e&&"flow-collection"===e.type)}else if(0===e.end.length){switch(this.type){case"comma":case"explicit-key-ind":return void(!t||t.sep?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken));case"map-value-ind":return void(!t||t.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]}));case"space":case"comment":case"newline":case"anchor":case"tag":return void(!t||t.value?e.items.push({start:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken));case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{const n=this.flowScalar(this.type);return void(!t||t.value?e.items.push({start:[],key:n,sep:[]}):t.sep?this.stack.push(n):Object.assign(t,{key:n,sep:[]}))}case"flow-map-end":case"flow-seq-end":return void e.end.push(this.sourceToken)}const n=this.startBlockValue(e);n?this.stack.push(n):(yield*this.pop(),yield*this.step())}else{const t=this.peek(2);if("block-map"===t.type&&("map-value-ind"===this.type&&t.indent===e.indent||"newline"===this.type&&!t.items[t.items.length-1].sep))yield*this.pop(),yield*this.step();else if("map-value-ind"===this.type&&"flow-collection"!==t.type){const n=qn(Fn(t));Hn(e);const s=e.end.splice(1,e.end.length);s.push(this.sourceToken);const i={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:n,key:e,sep:s}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=i}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let e=this.source.indexOf("\n")+1;for(;0!==e;)this.onNewLine(this.offset+e),e=this.source.indexOf("\n",e)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;const t=qn(Fn(e));return t.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:t,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;const t=qn(Fn(e));return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:t,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return"comment"===this.type&&(!(this.indent<=t)&&e.every((e=>"newline"===e.type||"space"===e.type)))}*documentEnd(e){"doc-mode"!==this.type&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],"newline"===this.type&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],"newline"===this.type&&(yield*this.pop())}}}function Un(e){const t=!1!==e.prettyErrors;return{lineCounter:e.lineCounter||t&&new Pn||null,prettyErrors:t}}function Rn(e,t={}){const{lineCounter:n,prettyErrors:s}=Un(t),i=new Kn(n?.addNewLine),r=new dn(t);let o=null;for(const a of r.compose(i.parse(e),!0,e.length))if(o){if("silent"!==o.options.logLevel){o.errors.push(new qt(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}}else o=a;return s&&n&&(o.errors.forEach(Kt(e,n)),o.warnings.forEach(Kt(e,n))),o}const Wn=Object.freeze(Object.defineProperty({__proto__:null,Alias:z,CST:xn,Composer:dn,Document:Mt,Lexer:Dn,LineCounter:Pn,Pair:$e,Parser:Kn,Scalar:te,Schema:Bt,YAMLError:Ft,YAMLMap:Be,YAMLParseError:qt,YAMLSeq:Ve,YAMLWarning:Ht,isAlias:A,isCollection:I,isDocument:C,isMap:x,isNode:L,isPair:N,isScalar:T,isSeq:$,parse:function(e,t,n){let s;"function"==typeof t?s=t:void 0===n&&t&&"object"==typeof t&&(n=t);const i=Rn(e,n);if(!i)return null;if(i.warnings.forEach((e=>Se(i.options.logLevel,e))),i.errors.length>0){if("silent"!==i.options.logLevel)throw i.errors[0];i.errors=[]}return i.toJS(Object.assign({reviver:s},n))},parseAllDocuments:function(e,t={}){const{lineCounter:n,prettyErrors:s}=Un(t),i=new Kn(n?.addNewLine),r=new dn(t),o=Array.from(r.compose(i.parse(e)));if(s&&n)for(const a of o)a.errors.forEach(Kt(e,n)),a.warnings.forEach(Kt(e,n));return o.length>0?o:Object.assign([],{empty:!0},r.streamInfo())},parseDocument:Rn,stringify:function(e,t,n){let s=null;if("function"==typeof t||Array.isArray(t)?s=t:void 0===n&&t&&(n=t),"string"==typeof n&&(n=n.length),"number"==typeof n){const e=Math.round(n);n=e<1?void 0:e>8?{indent:8}:{indent:e}}if(void 0===e){const{keepUndefined:e}=n??t??{};if(!e)return}return C(e)&&!s?e.toString(n):new Mt(e,s,n).toString(n)},visit:B,visitAsync:V},Symbol.toStringTag,{value:"Module"})),Jn="index.mjs",Gn=t=>{var s;s=n.join(t,"@karinjs"),e.existsSync(s)&&e.rmSync(s,{recursive:!0,force:!0});const i=n.join(t,".pnpmfile.cjs");e.existsSync(i)&&e.unlinkSync(i);const r=n.join(t,"index.mjs");e.existsSync(r)&&e.unlinkSync(r);const o=n.join(t,".env");e.existsSync(o)&&e.unlinkSync(o)},Yn=async i=>{const r=process.env.INIT_CWD||process.cwd(),o=(t=>"development"===process.env.NODE_ENV||["src","tsconfig.json","eslint.config.mjs","eslint.config.js",".prettierrc","vite.config.ts","tsup.config.ts"].some((s=>e.existsSync(n.join(t,s)))))(r);i&&Gn(r),((t,s)=>{if(["logs","config","data","resource","temp/console","temp/html"].forEach((t=>{const i=n.join(s,"@karinjs",t);e.existsSync(i)||e.mkdirSync(i,{recursive:!0})})),t)return;const i=n.join(s,"plugins","karin-plugin-example");e.existsSync(i)||e.mkdirSync(i,{recursive:!0})})(o,r),((t,s)=>{const i=e=>Array.from(new Set(e)),r=n.join(s,"pnpm-workspace.yaml");let o={};e.existsSync(r)&&(o=Wn.parse(e.readFileSync(r,"utf-8"))),"boolean"!=typeof o.lockfile&&(o.lockfile=!1),t||(o.packages&&Array.isArray(o.packages)||(o.packages=[]),o.packages.forEach(((e,t)=>{"plugins/**"===e&&(o.packages[t]="plugins/*")})),o.packages?.includes("plugins/*")||o.packages.push("plugins/*"),o.packages=i(o.packages)),o.onlyBuiltDependencies&&Array.isArray(o.onlyBuiltDependencies)||(o.onlyBuiltDependencies=[]);const a=["@karinjs/node-pty","@karinjs/sqlite3-cjs","canvas","sqlite3","sharp","puppeteer","classic-level",...o.onlyBuiltDependencies];o.onlyBuiltDependencies=i(a),o.publicHoistPattern&&Array.isArray(o.publicHoistPattern)||(o.publicHoistPattern=[]);const c=["*sqlite3*","*express*",...o.publicHoistPattern];o.publicHoistPattern=i(c),e.writeFileSync(r,Wn.stringify(Object.assign({lockfile:!1,packages:[],publicHoistPattern:[],onlyBuiltDependencies:[]},o)),"utf-8")})(o,r),(s=>{const i=t.fileURLToPath(new t.URL("../..","undefined"==typeof document?require("url").pathToFileURL(__filename).href:c&&"SCRIPT"===c.tagName.toUpperCase()&&c.src||new URL("index.cjs",document.baseURI).href)),r=n.join(i,"default","config");e.readdirSync(r).forEach((t=>{if(!t.endsWith(".json"))return;const i=n.join(r,t),o=n.join(s,"@karinjs","config"),a=n.join(o,t);if(!e.existsSync(a))return void e.copyFileSync(i,a);const c=e.readFileSync(i,"utf-8"),l=e.readFileSync(a,"utf-8"),u={...JSON.parse(c),...JSON.parse(l)};t.includes("pm2.json")&&(u.apps[0].script="index.mjs"),e.writeFileSync(a,JSON.stringify(u,null,2))}))})(r),((t,s)=>{const i=n.join(s,"package.json"),r=(()=>{try{return JSON.parse(e.readFileSync(i,"utf-8"))}catch{return{}}})();r.scripts||(r.scripts={}),r.name||(r.name="karin-project"),r.version||(r.version="1.0.0"),r.type="module",t||(r.scripts.ki||(r.scripts.ki="ki"),r.scripts.karin||(r.scripts.karin="ki"),r.scripts.app||(r.scripts.app="node index.mjs"),r.scripts.start||(r.scripts.start="node index.mjs"),r.scripts.pm2||(r.scripts.pm2="pm2 start @karinjs/config/pm2.json"),r.scripts.stop||(r.scripts.stop="ki stop"),r.scripts.rs||(r.scripts.rs="ki rs"),r.scripts.log||(r.scripts.log="ki log"),r.scripts.up||(r.scripts.up="ki up"),r.main=Jn),t||r?.dependencies?.["node-karin"]||(r.dependencies||(r.dependencies={}),r.dependencies["node-karin"]="latest"),r.pnpm&&delete r.pnpm,e.writeFileSync(i,JSON.stringify(r,null,2))})(o,r),(t=>{const s=["package-lock=false","public-hoist-pattern[]=*sqlite3*","public-hoist-pattern[]=*express*","sqlite3_binary_host_mirror=https://registry.npmmirror.com/-/binary/sqlite3","node_sqlite3_binary_host_mirror=https://registry.npmmirror.com/-/binary/sqlite3","better_sqlite3_binary_host_mirror=https://registry.npmmirror.com/-/binary/better-sqlite3","sass_binary_site=https://registry.npmmirror.com/-/binary/node-sass","sharp_binary_host=https://registry.npmmirror.com/-/binary/sharp","sharp_libvips_binary_host=https://registry.npmmirror.com/-/binary/sharp-libvips","canvas_binary_host_mirror=https://registry.npmmirror.com/-/binary/canvas","# 19以下版本","puppeteer_download_host=https://registry.npmmirror.com/mirrors","# 20以上版本","PUPPETEER_DOWNLOAD_BASE_URL = https://registry.npmmirror.com/binaries/chrome-for-testing"],i=n.join(t,".npmrc");if(!e.existsSync(i))return void e.writeFileSync(i,s.join("\n"));const r=e.readFileSync(i,"utf-8"),o=r.split("\n").map((e=>e.trim())),a=s.filter((e=>{if(e.startsWith("public-hoist-pattern[]="))return!o.includes(e);const t=e.split("=")[0];return!r.includes(t)}));a.length>0&&e.appendFileSync(i,"\n"+a.join("\n"))})(r),((t,s)=>{if(t)return;const i=n.join(s,".pnpmfile.cjs");if(e.existsSync(i))return;const r=["// 清空对等依赖中的node-karin","function readPackage (pkg, context) {"," if (pkg?.['peerDependencies']?.['node-karin'] && pkg['peerDependencies']['node-karin'] !== 'file:./lib') {"," delete pkg['peerDependencies']['node-karin']"," }"," return pkg","}","module.exports = {"," hooks: {"," readPackage"," },","}"].join("\n");e.writeFileSync(i,r)})(o,r),((t,s)=>{if(t&&e.existsSync(`${s}/src`))return void e.writeFileSync(n.join(s,"src","app.ts"),"import('node-karin/start')");const i=n.join(s,"index.mjs");e.existsSync(i)||e.writeFileSync(i,"(() => {\n import('node-karin/start')\n})()\n")})(o,r),(t=>{const s=e=>{if("http"===e&&process.env.HTTP_AUTH_KEY)return process.env.HTTP_AUTH_KEY;if("ws"===e&&process.env.WS_SERVER_AUTH_KEY)return process.env.WS_SERVER_AUTH_KEY;const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";return Array.from({length:6},(()=>t.charAt(Math.floor(62*Math.random())))).join("")},i=["# 是否启用HTTP","HTTP_ENABLE=true","# HTTP监听端口","HTTP_PORT=7777","# HTTP监听地址","HTTP_HOST=0.0.0.0","# HTTP鉴权秘钥 仅用于karin自身Api",`HTTP_AUTH_KEY=${s("http")}`,"# ws_server鉴权秘钥",`WS_SERVER_AUTH_KEY=${s("ws")}`,"\n","# 是否启用Redis 关闭后将使用内部虚拟Redis","REDIS_ENABLE=true","# 重启是否调用pm2 如果不调用则会直接关机 此配置适合有进程守护的程序","PM2_RESTART=true","\n","# 日志等级","LOG_LEVEL=info","# 日志保留天数","LOG_DAYS_TO_KEEP=7","# 日志文件最大大小 如果此项大于0则启用日志分割","LOG_MAX_LOG_SIZE=0","# logger.fnc颜色",'LOG_FNC_COLOR="#E1D919"',"# 日志实时Api最多支持同时连接数","LOG_API_MAX_CONNECTIONS=5","\n","# ffmpeg","FFMPEG_PATH=","# ffprobe","FFPROBE_PATH=","# ffplay","FFPLAY_PATH=","RUNTIME=node","NODE_ENV=production","TSX_WATCH=false"],r=n.join(t,".env");if(!e.existsSync(r))return void e.writeFileSync(r,i.join("\n"));const o=e.readFileSync(r,"utf-8"),a=i.filter((e=>{if(e.includes("#"))return!1;const t=e.split("=")[0];return!o.includes(t)}));a.length>0&&e.appendFileSync(r,"\n"+a.join("\n"))})(r),e.existsSync(n.join(r,"pnpm-lock.yaml"))&&(e.rmSync(n.join(r,"pnpm-lock.yaml")),s.execSync("pnpm install -f",{stdio:"inherit",cwd:r})),process.env.KARIN_CLI&&(console.log("[cli] 初始化完成 请使用 pnpm app 启动项目"),process.exit(0))},Qn=async()=>{const e=n.join(process.cwd(),Jn);r.existsSync(e)&&r.existsSync(n.join(process.cwd(),".npmrc"))&&r.readFileSync(n.join(process.cwd(),".npmrc"))?.includes("public-hoist-pattern[]=*sqlite3*")||(console.log("检查到项目升级到 1.8.0+ 版本,正在初始化项目..."),s.execSync("npx karin init",{stdio:"inherit",cwd:process.cwd()})),await import(t.pathToFileURL(e).toString())},Xn=(e,t)=>new Promise((n=>{const i=setTimeout((()=>{n({status:!1,error:new Error("命令执行超时"),stdout:"",stderr:"命令执行超时"})}),1e3*(t?.timeout||30)),r=s.exec(e,t,((e,t,s)=>{clearTimeout(i),s=s.toString().trim(),t=t.toString().trim();n({status:!e,error:e,stdout:t,stderr:s})}));r.stdin?.write("\n")})),zn=(e,t)=>{if(e.error||"string"!=typeof e.stdout)throw e.error||new Error("stdout 类型错误");return e.stdout},Zn=async(e,t)=>{const n=await Xn("git rev-parse HEAD",{cwd:e});return zn(n)},es=(e,t,n,s,i="")=>({status:e,data:"string"==typeof s?s:`${i}${s.message||s.stack||"未知错误"}`,hash:{before:t,after:n}}),ts=async(e,t={})=>{try{const n=await Zn(e),s=await(async e=>{let t="origin/HEAD";t.startsWith("origin/")||(t=`origin/${t}`);const n=`git rev-parse ${t}`,s=await Xn(n,{cwd:e});return zn(s)})(e);if(n===s)return es(!1,n,s,"当前已经是最新版本");if(t.force){const i=t.remote||"origin/HEAD",r=await Xn("git fetch origin",{cwd:e,...t});if(r.error)return es(!1,n,s,r.error,"同步远程分支失败: ");const o=await Xn(`git reset --hard ${i}`,{cwd:e,...t});if(o.error)return es(!1,n,s,o.error,"强制同步远程分支失败: ");const a=await Zn(e);return es(!0,n,a,"本地分支已强制与远程分支同步")}const i=t.customCmd||"git pull",{error:r}=await Xn(i,{...t,cwd:e});if(r)return es(!1,n,s,r,"更新失败: ");const o=await Zn(e);return es(!0,n,o,"更新成功")}catch(n){return es(!1,"","",n.message,"发生错误: ")}},ns=async(t,n,s)=>{try{const i=JSON.parse(e.readFileSync(t,"utf-8")).dependencies||{},r=Object.entries(i).map((async([e,t])=>{if(!e.startsWith("@types/"))try{const{stdout:i}=await u(`pnpm view ${e} --json`);if(!JSON.parse(i.trim()).karin&&"node-karin"!==e)return;const r=t.replace(/[\^~]/g,""),{stdout:o}=await u(`pnpm view ${e} dist-tags --json`),a=JSON.parse(o.trim()),c=/[-+]/.test(r),l=a.latest;c||r!==l?(s.push(`${e}@latest`),n.push({name:e,type:"npm",currentVersion:`${r}${c?" (预发布)":""}`,latestVersion:l,status:`${r} -> ${l}`,needUpdate:!0,isPlugin:!0})):n.push({name:e,type:"npm",currentVersion:r,latestVersion:l,status:"已是最新",needUpdate:!1,isPlugin:!0})}catch(i){console.error(`检查 ${e} 版本失败:`,i)}}));await Promise.all(r)}catch(i){console.error("更新依赖失败:",i)}},ss=async(t,n,s,i=!0)=>{if(!(await(async()=>{try{const{status:e}=await u("git --version");return e}catch{return!1}})()))return void console.error("请先安装git");if(!e.existsSync(t))return void console.error("plugins目录不存在");if(!(await e.promises.stat(t)).isDirectory())return void console.error("plugins路径不是一个目录");const r=await e.promises.readdir(t);if(i){const e=r.map((async e=>{await is(e,t,n,s)}));await Promise.all(e)}else for(const e of r)await is(e,t,n,s)},is=async(t,s,i,r)=>{const o=n.join(s,t),a=n.join(o,".git"),c=n.join(o,"package.json");if(t.startsWith("karin-plugin-")&&(await e.promises.stat(o)).isDirectory()&&!e.existsSync(a)){i.push({name:t,type:"git",currentVersion:"-",latestVersion:"-",status:"不是git仓库,已跳过",needUpdate:!1,isPlugin:!1});try{if(!JSON.parse(e.readFileSync(c,"utf-8")).karin)return void i.push({name:t,type:"git",currentVersion:"-",latestVersion:"-",status:"非Karin插件,已跳过",needUpdate:!1,isPlugin:!1});const{status:n,hash:s,data:a}=await ts(o,{customCmd:"git pull",force:r});n?i.push({name:t,type:"git",currentVersion:s.before,latestVersion:s.after,status:"更新成功",needUpdate:!0,isPlugin:!0}):i.push({name:t,type:"git",currentVersion:"-",latestVersion:"-",status:`更新失败: ${a}`,needUpdate:!1,isPlugin:!0})}catch(l){i.push({name:t,type:"git",currentVersion:"-",latestVersion:"-",status:`处理失败: ${l}`,needUpdate:!1,isPlugin:!1})}}},rs=()=>{const e=process.cwd();return n.join(e,"pnpm-workspace.yaml")},os=()=>{const t=rs();if(!e.existsSync(t))throw new Error("pnpm-workspace.yaml 文件不存在");const n=e.readFileSync(t,"utf-8");return Wn.parse(n)},as=t=>{const n=rs(),s=Wn.stringify(t);e.writeFileSync(n,s,"utf-8")},cs=e=>{try{const t=os(),n=e.split(" ").filter((e=>""!==e.trim()));if(0===n.length)return void console.log("提示:请提供有效的依赖名称");t.onlyBuiltDependencies||(t.onlyBuiltDependencies=[]);let s=0,i=0;n.forEach((e=>{t.onlyBuiltDependencies.includes(e)?i++:(t.onlyBuiltDependencies.push(e),s++)})),s>0&&(as(t),console.log(`成功:已添加 ${s} 个依赖到 onlyBuiltDependencies 中`)),i>0&&console.log(`提示:${i} 个依赖已存在于 onlyBuiltDependencies 中,无需添加`)}catch(t){console.error(`错误:添加构建依赖失败 - ${t.message}`)}},ls=e=>{try{const t=os(),n=e.split(" ").filter((e=>""!==e.trim()));if(0===n.length)return void console.log("提示:请提供有效的依赖名称");if(!t.onlyBuiltDependencies)return void console.log("提示:onlyBuiltDependencies 列表为空或不存在,无需删除");let s=0,i=0;n.forEach((e=>{const n=t.onlyBuiltDependencies.length;t.onlyBuiltDependencies=t.onlyBuiltDependencies.filter((t=>t!==e)),t.onlyBuiltDependencies.length!==n?s++:i++})),s>0&&(as(t),console.log(`成功:已从 onlyBuiltDependencies 中删除 ${s} 个依赖`)),i>0&&console.log(`提示:${i} 个依赖不存在于 onlyBuiltDependencies 中,无需删除`)}catch(t){console.error(`错误:删除构建依赖失败 - ${t.message}`)}},us=()=>{try{const e=os();if(!e.onlyBuiltDependencies||0===e.onlyBuiltDependencies.length)return void console.log("提示:onlyBuiltDependencies 列表为空,没有构建依赖");console.log("==== onlyBuiltDependencies 列表 ===="),e.onlyBuiltDependencies.forEach((e=>{console.log(e)})),console.log("==== 共 "+e.onlyBuiltDependencies.length+" 个依赖 ====")}catch(e){console.error(`错误:列出构建依赖失败 - ${e.message}`)}};function hs(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var ps,ds,fs={},ms={},gs={};function ys(){if(ps)return gs;ps=1;class e extends Error{constructor(e,t,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}}return gs.CommanderError=e,gs.InvalidArgumentError=class extends e{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}},gs}function bs(){if(ds)return ms;ds=1;const{InvalidArgumentError:e}=ys();return ms.Argument=class{constructor(e,t){switch(this.description=t||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e}this._name.length>3&&"..."===this._name.slice(-3)&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(e,t){return t!==this.defaultValue&&Array.isArray(t)?t.concat(e):[e]}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(t){return this.argChoices=t.slice(),this.parseArg=(t,n)=>{if(!this.argChoices.includes(t))throw new e(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,n):t},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}},ms.humanReadableArgName=function(e){const t=e.name()+(!0===e.variadic?"...":"");return e.required?"<"+t+">":"["+t+"]"},ms}var ws,vs={},ks={};function _s(){if(ws)return ks;ws=1;const{humanReadableArgName:e}=bs();function t(e){return e.replace(/\x1b\[\d*(;\d*)*m/g,"")}return ks.Help=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(e){this.helpWidth=this.helpWidth??e.helpWidth??80}visibleCommands(e){const t=e.commands.filter((e=>!e._hidden)),n=e._getHelpCommand();return n&&!n._hidden&&t.push(n),this.sortSubcommands&&t.sort(((e,t)=>e.name().localeCompare(t.name()))),t}compareOptions(e,t){const n=e=>e.short?e.short.replace(/^-/,""):e.long.replace(/^--/,"");return n(e).localeCompare(n(t))}visibleOptions(e){const t=e.options.filter((e=>!e.hidden)),n=e._getHelpOption();if(n&&!n.hidden){const s=n.short&&e._findOption(n.short),i=n.long&&e._findOption(n.long);s||i?n.long&&!i?t.push(e.createOption(n.long,n.description)):n.short&&!s&&t.push(e.createOption(n.short,n.description)):t.push(n)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];const t=[];for(let n=e.parent;n;n=n.parent){const e=n.options.filter((e=>!e.hidden));t.push(...e)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach((t=>{t.description=t.description||e._argsDescription[t.name()]||""})),e.registeredArguments.find((e=>e.description))?e.registeredArguments:[]}subcommandTerm(t){const n=t.registeredArguments.map((t=>e(t))).join(" ");return t._name+(t._aliases[0]?"|"+t._aliases[0]:"")+(t.options.length?" [options]":"")+(n?" "+n:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce(((e,n)=>Math.max(e,this.displayWidth(t.styleSubcommandTerm(t.subcommandTerm(n))))),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce(((e,n)=>Math.max(e,this.displayWidth(t.styleOptionTerm(t.optionTerm(n))))),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce(((e,n)=>Math.max(e,this.displayWidth(t.styleOptionTerm(t.optionTerm(n))))),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce(((e,n)=>Math.max(e,this.displayWidth(t.styleArgumentTerm(t.argumentTerm(n))))),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+"|"+e._aliases[0]);let n="";for(let s=e.parent;s;s=s.parent)n=s.name()+" "+n;return n+t+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){const t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map((e=>JSON.stringify(e))).join(", ")}`),void 0!==e.defaultValue){(e.required||e.optional||e.isBoolean()&&"boolean"==typeof e.defaultValue)&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`)}return void 0!==e.presetArg&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),void 0!==e.envVar&&t.push(`env: ${e.envVar}`),t.length>0?`${e.description} (${t.join(", ")})`:e.description}argumentDescription(e){const t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map((e=>JSON.stringify(e))).join(", ")}`),void 0!==e.defaultValue&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){const n=`(${t.join(", ")})`;return e.description?`${e.description} ${n}`:n}return e.description}formatHelp(e,t){const n=t.padWidth(e,t),s=t.helpWidth??80;function i(e,s){return t.formatItem(e,n,s,t)}let r=[`${t.styleTitle("Usage:")} ${t.styleUsage(t.commandUsage(e))}`,""];const o=t.commandDescription(e);o.length>0&&(r=r.concat([t.boxWrap(t.styleCommandDescription(o),s),""]));const a=t.visibleArguments(e).map((e=>i(t.styleArgumentTerm(t.argumentTerm(e)),t.styleArgumentDescription(t.argumentDescription(e)))));a.length>0&&(r=r.concat([t.styleTitle("Arguments:"),...a,""]));const c=t.visibleOptions(e).map((e=>i(t.styleOptionTerm(t.optionTerm(e)),t.styleOptionDescription(t.optionDescription(e)))));if(c.length>0&&(r=r.concat([t.styleTitle("Options:"),...c,""])),t.showGlobalOptions){const n=t.visibleGlobalOptions(e).map((e=>i(t.styleOptionTerm(t.optionTerm(e)),t.styleOptionDescription(t.optionDescription(e)))));n.length>0&&(r=r.concat([t.styleTitle("Global Options:"),...n,""]))}const l=t.visibleCommands(e).map((e=>i(t.styleSubcommandTerm(t.subcommandTerm(e)),t.styleSubcommandDescription(t.subcommandDescription(e)))));return l.length>0&&(r=r.concat([t.styleTitle("Commands:"),...l,""])),r.join("\n")}displayWidth(e){return t(e).length}styleTitle(e){return e}styleUsage(e){return e.split(" ").map((e=>"[options]"===e?this.styleOptionText(e):"[command]"===e?this.styleSubcommandText(e):"["===e[0]||"<"===e[0]?this.styleArgumentText(e):this.styleCommandText(e))).join(" ")}styleCommandDescription(e){return this.styleDescriptionText(e)}styleOptionDescription(e){return this.styleDescriptionText(e)}styleSubcommandDescription(e){return this.styleDescriptionText(e)}styleArgumentDescription(e){return this.styleDescriptionText(e)}styleDescriptionText(e){return e}styleOptionTerm(e){return this.styleOptionText(e)}styleSubcommandTerm(e){return e.split(" ").map((e=>"[options]"===e?this.styleOptionText(e):"["===e[0]||"<"===e[0]?this.styleArgumentText(e):this.styleSubcommandText(e))).join(" ")}styleArgumentTerm(e){return this.styleArgumentText(e)}styleOptionText(e){return e}styleArgumentText(e){return e}styleSubcommandText(e){return e}styleCommandText(e){return e}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}preformatted(e){return/\n[^\S\r\n]/.test(e)}formatItem(e,t,n,s){const i=" ".repeat(2);if(!n)return i+e;const r=e.padEnd(t+e.length-s.displayWidth(e)),o=(this.helpWidth??80)-t-2-2;let a;if(o<this.minWidthToWrap||s.preformatted(n))a=n;else{a=s.boxWrap(n,o).replace(/\n/g,"\n"+" ".repeat(t+2))}return i+r+" ".repeat(2)+a.replace(/\n/g,`\n${i}`)}boxWrap(e,t){if(t<this.minWidthToWrap)return e;const n=e.split(/\r\n|\n/),s=/[\s]*[^\s]+/g,i=[];return n.forEach((e=>{const n=e.match(s);if(null===n)return void i.push("");let r=[n.shift()],o=this.displayWidth(r[0]);n.forEach((e=>{const n=this.displayWidth(e);if(o+n<=t)return r.push(e),void(o+=n);i.push(r.join(""));const s=e.trimStart();r=[s],o=this.displayWidth(s)})),i.push(r.join(""))})),i.join("\n")}},ks.stripColor=t,ks}var Os,Ss={};function Es(){if(Os)return Ss;Os=1;const{InvalidArgumentError:e}=ys();function t(e){return e.split("-").reduce(((e,t)=>e+t[0].toUpperCase()+t.slice(1)))}return Ss.Option=class{constructor(e,t){this.flags=e,this.description=t||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;const n=function(e){let t,n;const s=/^-[^-]$/,i=/^--[^-]/,r=e.split(/[ |,]+/).concat("guard");s.test(r[0])&&(t=r.shift());i.test(r[0])&&(n=r.shift());!t&&s.test(r[0])&&(t=r.shift());!t&&i.test(r[0])&&(t=n,n=r.shift());if(r[0].startsWith("-")){const t=r[0],n=`option creation failed due to '${t}' in option flags '${e}'`;if(/^-[^-][^-]/.test(t))throw new Error(`${n}\n- a short flag is a single dash and a single character\n - either use a single dash and a single character (for a short flag)\n - or use a double dash for a long option (and can have two, like '--ws, --workspace')`);if(s.test(t))throw new Error(`${n}\n- too many short flags`);if(i.test(t))throw new Error(`${n}\n- too many long flags`);throw new Error(`${n}\n- unrecognised flag format`)}if(void 0===t&&void 0===n)throw new Error(`option creation failed due to no flags found in '${e}'.`);return{shortFlag:t,longFlag:n}}(e);this.short=n.shortFlag,this.long=n.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;return"string"==typeof e&&(t={[e]:!0}),this.implied=Object.assign(this.implied||{},t),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_concatValue(e,t){return t!==this.defaultValue&&Array.isArray(t)?t.concat(e):[e]}choices(t){return this.argChoices=t.slice(),this.parseArg=(t,n)=>{if(!this.argChoices.includes(t))throw new e(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,n):t},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return this.negate?t(this.name().replace(/^no-/,"")):t(this.name())}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},Ss.DualOptions=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach((e=>{e.negate?this.negativeOptions.set(e.attributeName(),e):this.positiveOptions.set(e.attributeName(),e)})),this.negativeOptions.forEach(((e,t)=>{this.positiveOptions.has(t)&&this.dualOptions.add(t)}))}valueFromOption(e,t){const n=t.attributeName();if(!this.dualOptions.has(n))return!0;const s=this.negativeOptions.get(n).presetArg,i=void 0!==s&&s;return t.negate===(i===e)}},Ss}var As,Cs,xs,Ns={};function Ts(){if(As)return Ns;As=1;return Ns.suggestSimilar=function(e,t){if(!t||0===t.length)return"";t=Array.from(new Set(t));const n=e.startsWith("--");n&&(e=e.slice(2),t=t.map((e=>e.slice(2))));let s=[],i=3;return t.forEach((t=>{if(t.length<=1)return;const n=function(e,t){if(Math.abs(e.length-t.length)>3)return Math.max(e.length,t.length);const n=[];for(let s=0;s<=e.length;s++)n[s]=[s];for(let s=0;s<=t.length;s++)n[0][s]=s;for(let s=1;s<=t.length;s++)for(let i=1;i<=e.length;i++){let r=1;r=e[i-1]===t[s-1]?0:1,n[i][s]=Math.min(n[i-1][s]+1,n[i][s-1]+1,n[i-1][s-1]+r),i>1&&s>1&&e[i-1]===t[s-2]&&e[i-2]===t[s-1]&&(n[i][s]=Math.min(n[i][s],n[i-2][s-2]+1))}return n[e.length][t.length]}(e,t),r=Math.max(e.length,t.length);(r-n)/r>.4&&(n<i?(i=n,s=[t]):n===i&&s.push(t))})),s.sort(((e,t)=>e.localeCompare(t))),n&&(s=s.map((e=>`--${e}`))),s.length>1?`\n(Did you mean one of ${s.join(", ")}?)`:1===s.length?`\n(Did you mean ${s[0]}?)`:""},Ns}const $s=hs(function(){if(xs)return fs;xs=1;const{Argument:t}=bs(),{Command:i}=function(){if(Cs)return vs;Cs=1;const t=o.EventEmitter,i=s,r=n,c=e,l=a,{Argument:u,humanReadableArgName:h}=bs(),{CommanderError:p}=ys(),{Help:d,stripColor:f}=_s(),{Option:m,DualOptions:g}=Es(),{suggestSimilar:y}=Ts();class b extends t{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:e=>l.stdout.write(e),writeErr:e=>l.stderr.write(e),outputError:(e,t)=>t(e),getOutHelpWidth:()=>l.stdout.isTTY?l.stdout.columns:void 0,getErrHelpWidth:()=>l.stderr.isTTY?l.stderr.columns:void 0,getOutHasColors:()=>v()??(l.stdout.isTTY&&l.stdout.hasColors?.()),getErrHasColors:()=>v()??(l.stderr.isTTY&&l.stderr.hasColors?.()),stripColor:e=>f(e)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){const e=[];for(let t=this;t;t=t.parent)e.push(t);return e}command(e,t,n){let s=t,i=n;"object"==typeof s&&null!==s&&(i=s,s=null),i=i||{};const[,r,o]=e.match(/([^ ]+) *(.*)/),a=this.createCommand(r);return s&&(a.description(s),a._executableHandler=!0),i.isDefault&&(this._defaultCommandName=a._name),a._hidden=!(!i.noHelp&&!i.hidden),a._executableFile=i.executableFile||null,o&&a.arguments(o),this._registerCommand(a),a.parent=this,a.copyInheritedSettings(this),s?this:a}createCommand(e){return new b(e)}createHelp(){return Object.assign(new d,this.configureHelp())}configureHelp(e){return void 0===e?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return void 0===e?this._outputConfiguration:(Object.assign(this._outputConfiguration,e),this)}showHelpAfterError(e=!0){return"string"!=typeof e&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,t){if(!e._name)throw new Error("Command passed to .addCommand() must have a name\n- specify the name in Command constructor or using .name()");return(t=t||{}).isDefault&&(this._defaultCommandName=e._name),(t.noHelp||t.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new u(e,t)}argument(e,t,n,s){const i=this.createArgument(e,t);return"function"==typeof n?i.default(s).argParser(n):i.default(n),this.addArgument(i),this}arguments(e){return e.trim().split(/ +/).forEach((e=>{this.argument(e)})),this}addArgument(e){const t=this.registeredArguments.slice(-1)[0];if(t&&t.variadic)throw new Error(`only the last argument can be variadic '${t.name()}'`);if(e.required&&void 0!==e.defaultValue&&void 0===e.parseArg)throw new Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,t){if("boolean"==typeof e)return this._addImplicitHelpCommand=e,this;e=e??"help [command]";const[,n,s]=e.match(/([^ ]+) *(.*)/),i=t??"display help for command",r=this.createCommand(n);return r.helpOption(!1),s&&r.arguments(s),i&&r.description(i),this._addImplicitHelpCommand=!0,this._helpCommand=r,this}addHelpCommand(e,t){return"object"!=typeof e?(this.helpCommand(e,t),this):(this._addImplicitHelpCommand=!0,this._helpCommand=e,this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(void 0===this._helpCommand&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,t){const n=["preSubcommand","preAction","postAction"];if(!n.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.\nExpecting one of '${n.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return this._exitCallback=e||(e=>{if("commander.executeSubCommandAsync"!==e.code)throw e}),this}_exit(e,t,n){this._exitCallback&&this._exitCallback(new p(e,t,n)),l.exit(e)}action(e){return this._actionHandler=t=>{const n=this.registeredArguments.length,s=t.slice(0,n);return this._storeOptionsAsProperties?s[n]=this:s[n]=this.opts(),s.push(this),e.apply(this,s)},this}createOption(e,t){return new m(e,t)}_callParseArg(e,t,n,s){try{return e.parseArg(t,n)}catch(i){if("commander.invalidArgument"===i.code){const e=`${s} ${i.message}`;this.error(e,{exitCode:i.exitCode,code:i.code})}throw i}}_registerOption(e){const t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){const n=e.long&&this._findOption(e.long)?e.long:e.short;throw new Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${n}'\n- already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){const t=e=>[e.name()].concat(e.aliases()),n=t(e).find((e=>this._findCommand(e)));if(n){const s=t(this._findCommand(n)).join("|"),i=t(e).join("|");throw new Error(`cannot add command '${i}' as already have command '${s}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);const t=e.name(),n=e.attributeName();if(e.negate){const t=e.long.replace(/^--no-/,"--");this._findOption(t)||this.setOptionValueWithSource(n,void 0===e.defaultValue||e.defaultValue,"default")}else void 0!==e.defaultValue&&this.setOptionValueWithSource(n,e.defaultValue,"default");const s=(t,s,i)=>{null==t&&void 0!==e.presetArg&&(t=e.presetArg);const r=this.getOptionValue(n);null!==t&&e.parseArg?t=this._callParseArg(e,t,r,s):null!==t&&e.variadic&&(t=e._concatValue(t,r)),null==t&&(t=!e.negate&&(!(!e.isBoolean()&&!e.optional)||"")),this.setOptionValueWithSource(n,t,i)};return this.on("option:"+t,(t=>{const n=`error: option '${e.flags}' argument '${t}' is invalid.`;s(t,n,"cli")})),e.envVar&&this.on("optionEnv:"+t,(t=>{const n=`error: option '${e.flags}' value '${t}' from env '${e.envVar}' is invalid.`;s(t,n,"env")})),this}_optionEx(e,t,n,s,i){if("object"==typeof t&&t instanceof m)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");const r=this.createOption(t,n);if(r.makeOptionMandatory(!!e.mandatory),"function"==typeof s)r.default(i).argParser(s);else if(s instanceof RegExp){const e=s;s=(t,n)=>{const s=e.exec(t);return s?s[0]:n},r.default(i).argParser(s)}else r.default(s);return this.addOption(r)}option(e,t,n,s){return this._optionEx({},e,t,n,s)}requiredOption(e,t,n,s){return this._optionEx({mandatory:!0},e,t,n,s)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,n){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=n,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach((n=>{void 0!==n.getOptionValueSource(e)&&(t=n.getOptionValueSource(e))})),t}_prepareUserArgs(e,t){if(void 0!==e&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(t=t||{},void 0===e&&void 0===t.from){l.versions?.electron&&(t.from="electron");const e=l.execArgv??[];(e.includes("-e")||e.includes("--eval")||e.includes("-p")||e.includes("--print"))&&(t.from="eval")}let n;switch(void 0===e&&(e=l.argv),this.rawArgs=e.slice(),t.from){case void 0:case"node":this._scriptPath=e[1],n=e.slice(2);break;case"electron":l.defaultApp?(this._scriptPath=e[1],n=e.slice(2)):n=e.slice(1);break;case"user":n=e.slice(0);break;case"eval":n=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${t.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",n}parse(e,t){this._prepareForParse();const n=this._prepareUserArgs(e,t);return this._parseCommand([],n),this}async parseAsync(e,t){this._prepareForParse();const n=this._prepareUserArgs(e,t);return await this._parseCommand([],n),this}_prepareForParse(){null===this._savedState?this.saveStateBeforeParse():this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw new Error("Can not call parse again when storeOptionsAsProperties is true.\n- either make a new Command for each call to parse, or stop storing options as properties");this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable(e,t,n){if(!c.existsSync(e))throw new Error(`'${e}' does not exist\n - if '${n}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead\n - if the default executable name is not suitable, use the executableFile option to supply a custom name or path\n - ${t?`searched for local subcommand relative to directory '${t}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory"}`)}_executeSubCommand(e,t){t=t.slice();let n=!1;const s=[".js",".ts",".tsx",".mjs",".cjs"];function o(e,t){const n=r.resolve(e,t);if(c.existsSync(n))return n;if(s.includes(r.extname(t)))return;const i=s.find((e=>c.existsSync(`${n}${e}`)));return i?`${n}${i}`:void 0}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let a,u=e._executableFile||`${this._name}-${e._name}`,h=this._executableDir||"";if(this._scriptPath){let e;try{e=c.realpathSync(this._scriptPath)}catch{e=this._scriptPath}h=r.resolve(r.dirname(e),h)}if(h){let t=o(h,u);if(!t&&!e._executableFile&&this._scriptPath){const n=r.basename(this._scriptPath,r.extname(this._scriptPath));n!==this._name&&(t=o(h,`${n}-${e._name}`))}u=t||u}n=s.includes(r.extname(u)),"win32"!==l.platform?n?(t.unshift(u),t=w(l.execArgv).concat(t),a=i.spawn(l.argv[0],t,{stdio:"inherit"})):a=i.spawn(u,t,{stdio:"inherit"}):(this._checkForMissingExecutable(u,h,e._name),t.unshift(u),t=w(l.execArgv).concat(t),a=i.spawn(l.execPath,t,{stdio:"inherit"})),a.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach((e=>{l.on(e,(()=>{!1===a.killed&&null===a.exitCode&&a.kill(e)}))}));const d=this._exitCallback;a.on("close",(e=>{e=e??1,d?d(new p(e,"commander.executeSubCommandAsync","(close)")):l.exit(e)})),a.on("error",(t=>{if("ENOENT"===t.code)this._checkForMissingExecutable(u,h,e._name);else if("EACCES"===t.code)throw new Error(`'${u}' not executable`);if(d){const e=new p(1,"commander.executeSubCommandAsync","(error)");e.nestedError=t,d(e)}else l.exit(1)})),this.runningCommand=a}_dispatchSubcommand(e,t,n){const s=this._findCommand(e);let i;return s||this.help({error:!0}),s._prepareForParse(),i=this._chainOrCallSubCommandHook(i,s,"preSubcommand"),i=this._chainOrCall(i,(()=>{if(!s._executableHandler)return s._parseCommand(t,n);this._executeSubCommand(s,t.concat(n))})),i}_dispatchHelpCommand(e){e||this.help();const t=this._findCommand(e);return t&&!t._executableHandler&&t.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach(((e,t)=>{e.required&&null==this.args[t]&&this.missingArgument(e.name())})),this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic||this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){const e=(e,t,n)=>{let s=t;if(null!==t&&e.parseArg){const i=`error: command-argument value '${t}' is invalid for argument '${e.name()}'.`;s=this._callParseArg(e,t,n,i)}return s};this._checkNumberOfArguments();const t=[];this.registeredArguments.forEach(((n,s)=>{let i=n.defaultValue;n.variadic?s<this.args.length?(i=this.args.slice(s),n.parseArg&&(i=i.reduce(((t,s)=>e(n,s,t)),n.defaultValue))):void 0===i&&(i=[]):s<this.args.length&&(i=this.args[s],n.parseArg&&(i=e(n,i,n.defaultValue))),t[s]=i})),this.processedArgs=t}_chainOrCall(e,t){return e&&e.then&&"function"==typeof e.then?e.then((()=>t())):t()}_chainOrCallHooks(e,t){let n=e;const s=[];return this._getCommandAndAncestors().reverse().filter((e=>void 0!==e._lifeCycleHooks[t])).forEach((e=>{e._lifeCycleHooks[t].forEach((t=>{s.push({hookedCommand:e,callback:t})}))})),"postAction"===t&&s.reverse(),s.forEach((e=>{n=this._chainOrCall(n,(()=>e.callback(e.hookedCommand,this)))})),n}_chainOrCallSubCommandHook(e,t,n){let s=e;return void 0!==this._lifeCycleHooks[n]&&this._lifeCycleHooks[n].forEach((e=>{s=this._chainOrCall(s,(()=>e(this,t)))})),s}_parseCommand(e,t){const n=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(n.operands),t=n.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);!this.commands.length||0!==this.args.length||this._actionHandler||this._defaultCommandName||this.help({error:!0}),this._outputHelpIfRequested(n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();const s=()=>{n.unknown.length>0&&this.unknownOption(n.unknown[0])},i=`command:${this.name()}`;if(this._actionHandler){let n;return s(),this._processArguments(),n=this._chainOrCallHooks(n,"preAction"),n=this._chainOrCall(n,(()=>this._actionHandler(this.processedArgs))),this.parent&&(n=this._chainOrCall(n,(()=>{this.parent.emit(i,e,t)}))),n=this._chainOrCallHooks(n,"postAction"),n}if(this.parent&&this.parent.listenerCount(i))s(),this._processArguments(),this.parent.emit(i,e,t);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,t);this.listenerCount("command:*")?this.emit("command:*",e,t):this.commands.length?this.unknownCommand():(s(),this._processArguments())}else this.commands.length?(s(),this.help({error:!0})):(s(),this._processArguments())}_findCommand(e){if(e)return this.commands.find((t=>t._name===e||t._aliases.includes(e)))}_findOption(e){return this.options.find((t=>t.is(e)))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach((e=>{e.options.forEach((t=>{t.mandatory&&void 0===e.getOptionValue(t.attributeName())&&e.missingMandatoryOptionValue(t)}))}))}_checkForConflictingLocalOptions(){const e=this.options.filter((e=>{const t=e.attributeName();return void 0!==this.getOptionValue(t)&&"default"!==this.getOptionValueSource(t)}));e.filter((e=>e.conflictsWith.length>0)).forEach((t=>{const n=e.find((e=>t.conflictsWith.includes(e.attributeName())));n&&this._conflictingOption(t,n)}))}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach((e=>{e._checkForConflictingLocalOptions()}))}parseOptions(e){const t=[],n=[];let s=t;const i=e.slice();function r(e){return e.length>1&&"-"===e[0]}let o=null;for(;i.length;){const e=i.shift();if("--"===e){s===n&&s.push(e),s.push(...i);break}if(!o||r(e)){if(o=null,r(e)){const t=this._findOption(e);if(t){if(t.required){const e=i.shift();void 0===e&&this.optionMissingArgument(t),this.emit(`option:${t.name()}`,e)}else if(t.optional){let e=null;i.length>0&&!r(i[0])&&(e=i.shift()),this.emit(`option:${t.name()}`,e)}else this.emit(`option:${t.name()}`);o=t.variadic?t:null;continue}}if(e.length>2&&"-"===e[0]&&"-"!==e[1]){const t=this._findOption(`-${e[1]}`);if(t){t.required||t.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${t.name()}`,e.slice(2)):(this.emit(`option:${t.name()}`),i.unshift(`-${e.slice(2)}`));continue}}if(/^--[^=]+=/.test(e)){const t=e.indexOf("="),n=this._findOption(e.slice(0,t));if(n&&(n.required||n.optional)){this.emit(`option:${n.name()}`,e.slice(t+1));continue}}if(r(e)&&(s=n),(this._enablePositionalOptions||this._passThroughOptions)&&0===t.length&&0===n.length){if(this._findCommand(e)){t.push(e),i.length>0&&n.push(...i);break}if(this._getHelpCommand()&&e===this._getHelpCommand().name()){t.push(e),i.length>0&&t.push(...i);break}if(this._defaultCommandName){n.push(e),i.length>0&&n.push(...i);break}}if(this._passThroughOptions){s.push(e),i.length>0&&s.push(...i);break}s.push(e)}else this.emit(`option:${o.name()}`,e)}return{operands:t,unknown:n}}opts(){if(this._storeOptionsAsProperties){const e={},t=this.options.length;for(let n=0;n<t;n++){const t=this.options[n].attributeName();e[t]=t===this._versionOptionName?this._version:this[t]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce(((e,t)=>Object.assign(e,t.opts())),{})}error(e,t){this._outputConfiguration.outputError(`${e}\n`,this._outputConfiguration.writeErr),"string"==typeof this._showHelpAfterError?this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`):this._showHelpAfterError&&(this._outputConfiguration.writeErr("\n"),this.outputHelp({error:!0}));const n=t||{},s=n.exitCode||1,i=n.code||"commander.error";this._exit(s,i,e)}_parseOptionsEnv(){this.options.forEach((e=>{if(e.envVar&&e.envVar in l.env){const t=e.attributeName();(void 0===this.getOptionValue(t)||["default","config","env"].includes(this.getOptionValueSource(t)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,l.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}}))}_parseOptionsImplied(){const e=new g(this.options),t=e=>void 0!==this.getOptionValue(e)&&!["default","implied"].includes(this.getOptionValueSource(e));this.options.filter((n=>void 0!==n.implied&&t(n.attributeName())&&e.valueFromOption(this.getOptionValue(n.attributeName()),n))).forEach((e=>{Object.keys(e.implied).filter((e=>!t(e))).forEach((t=>{this.setOptionValueWithSource(t,e.implied[t],"implied")}))}))}missingArgument(e){const t=`error: missing required argument '${e}'`;this.error(t,{code:"commander.missingArgument"})}optionMissingArgument(e){const t=`error: option '${e.flags}' argument missing`;this.error(t,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){const t=`error: required option '${e.flags}' not specified`;this.error(t,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,t){const n=e=>{const t=e.attributeName(),n=this.getOptionValue(t),s=this.options.find((e=>e.negate&&t===e.attributeName())),i=this.options.find((e=>!e.negate&&t===e.attributeName()));return s&&(void 0===s.presetArg&&!1===n||void 0!==s.presetArg&&n===s.presetArg)?s:i||e},s=e=>{const t=n(e),s=t.attributeName();return"env"===this.getOptionValueSource(s)?`environment variable '${t.envVar}'`:`option '${t.flags}'`},i=`error: ${s(e)} cannot be used with ${s(t)}`;this.error(i,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let n=[],s=this;do{const e=s.createHelp().visibleOptions(s).filter((e=>e.long)).map((e=>e.long));n=n.concat(e),s=s.parent}while(s&&!s._enablePositionalOptions);t=y(e,n)}const n=`error: unknown option '${e}'${t}`;this.error(n,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;const t=this.registeredArguments.length,n=1===t?"":"s",s=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${t} argument${n} but got ${e.length}.`;this.error(s,{code:"commander.excessArguments"})}unknownCommand(){const e=this.args[0];let t="";if(this._showSuggestionAfterError){const n=[];this.createHelp().visibleCommands(this).forEach((e=>{n.push(e.name()),e.alias()&&n.push(e.alias())})),t=y(e,n)}const n=`error: unknown command '${e}'${t}`;this.error(n,{code:"commander.unknownCommand"})}version(e,t,n){if(void 0===e)return this._version;this._version=e,t=t||"-V, --version",n=n||"output the version number";const s=this.createOption(t,n);return this._versionOptionName=s.attributeName(),this._registerOption(s),this.on("option:"+s.name(),(()=>{this._outputConfiguration.writeOut(`${e}\n`),this._exit(0,"commander.version",e)})),this}description(e,t){return void 0===e&&void 0===t?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return void 0===e?this._summary:(this._summary=e,this)}alias(e){if(void 0===e)return this._aliases[0];let t=this;if(0!==this.commands.length&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw new Error("Command alias can't be the same as its name");const n=this.parent?._findCommand(e);if(n){const t=[n.name()].concat(n.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${t}'`)}return t._aliases.push(e),this}aliases(e){return void 0===e?this._aliases:(e.forEach((e=>this.alias(e))),this)}usage(e){if(void 0===e){if(this._usage)return this._usage;const e=this.registeredArguments.map((e=>h(e)));return[].concat(this.options.length||null!==this._helpOption?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?e:[]).join(" ")}return this._usage=e,this}name(e){return void 0===e?this._name:(this._name=e,this)}nameFromFilename(e){return this._name=r.basename(e,r.extname(e)),this}executableDir(e){return void 0===e?this._executableDir:(this._executableDir=e,this)}helpInformation(e){const t=this.createHelp(),n=this._getOutputContext(e);t.prepareContext({error:n.error,helpWidth:n.helpWidth,outputHasColors:n.hasColors});const s=t.formatHelp(this,t);return n.hasColors?s:this._outputConfiguration.stripColor(s)}_getOutputContext(e){const t=!!(e=e||{}).error;let n,s,i;return t?(n=e=>this._outputConfiguration.writeErr(e),s=this._outputConfiguration.getErrHasColors(),i=this._outputConfiguration.getErrHelpWidth()):(n=e=>this._outputConfiguration.writeOut(e),s=this._outputConfiguration.getOutHasColors(),i=this._outputConfiguration.getOutHelpWidth()),{error:t,write:e=>(s||(e=this._outputConfiguration.stripColor(e)),n(e)),hasColors:s,helpWidth:i}}outputHelp(e){let t;"function"==typeof e&&(t=e,e=void 0);const n=this._getOutputContext(e),s={error:n.error,write:n.write,command:this};this._getCommandAndAncestors().reverse().forEach((e=>e.emit("beforeAllHelp",s))),this.emit("beforeHelp",s);let i=this.helpInformation({error:n.error});if(t&&(i=t(i),"string"!=typeof i&&!Buffer.isBuffer(i)))throw new Error("outputHelp callback must return a string or a Buffer");n.write(i),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",s),this._getCommandAndAncestors().forEach((e=>e.emit("afterAllHelp",s)))}helpOption(e,t){return"boolean"==typeof e?(this._helpOption=e?this._helpOption??void 0:null,this):(e=e??"-h, --help",t=t??"display help for command",this._helpOption=this.createOption(e,t),this)}_getHelpOption(){return void 0===this._helpOption&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this}help(e){this.outputHelp(e);let t=Number(l.exitCode??0);0===t&&e&&"function"!=typeof e&&e.error&&(t=1),this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){const n=["beforeAll","before","after","afterAll"];if(!n.includes(e))throw new Error(`Unexpected value for position to addHelpText.\nExpecting one of '${n.join("', '")}'`);const s=`${e}Help`;return this.on(s,(e=>{let n;n="function"==typeof t?t({error:e.error,command:e.command}):t,n&&e.write(`${n}\n`)})),this}_outputHelpIfRequested(e){const t=this._getHelpOption();t&&e.find((e=>t.is(e)))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}}function w(e){return e.map((e=>{if(!e.startsWith("--inspect"))return e;let t,n,s="127.0.0.1",i="9229";return null!==(n=e.match(/^(--inspect(-brk)?)$/))?t=n[1]:null!==(n=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))?(t=n[1],/^\d+$/.test(n[3])?i=n[3]:s=n[3]):null!==(n=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))&&(t=n[1],s=n[3],i=n[4]),t&&"0"!==i?`${t}=${s}:${parseInt(i)+1}`:e}))}function v(){return!l.env.NO_COLOR&&"0"!==l.env.FORCE_COLOR&&"false"!==l.env.FORCE_COLOR&&(!(!l.env.FORCE_COLOR&&void 0===l.env.CLICOLOR_FORCE)||void 0)}return vs.Command=b,vs.useColor=v,vs}(),{CommanderError:r,InvalidArgumentError:c}=ys(),{Help:l}=_s(),{Option:u}=Es();return fs.program=new i,fs.createCommand=e=>new i(e),fs.createOption=(e,t)=>new u(e,t),fs.createArgument=(e,n)=>new t(e,n),fs.Command=i,fs.Option=u,fs.Argument=t,fs.Help=l,fs.CommanderError=r,fs.InvalidArgumentError=c,fs.InvalidOptionArgumentError=c,fs}()),{program:Is,createCommand:Ls,createArgument:js,createOption:Ds,CommanderError:Ps,InvalidArgumentError:Bs,InvalidOptionArgumentError:Ms,Command:Vs,Argument:Fs,Option:qs,Help:Hs}=$s;process.argv?.[2]||process.argv.push("-h");Is.version((()=>{try{const n=t.fileURLToPath(new URL("../../package.json","undefined"==typeof document?require("url").pathToFileURL(__filename).href:c&&"SCRIPT"===c.tagName.toUpperCase()&&c.src||new URL("index.cjs",document.baseURI).href));return JSON.parse(e.readFileSync(n,"utf-8")).version}catch{return"unknown"}})(),"-v, --version","显示版本号"),Is.command(".").description("前台启动").action(Qn),Is.command("app").description("前台启动").action(Qn),Is.command("start").description("前台启动").action(Qn),Is.command("pm2").description("后台运行").action(m),Is.command("stop").description("停止后台服务").action(y),Is.command("rs").alias("restart").description("重启后台服务").option("-f, --force","强制重启").action((e=>b(e.force))),Is.command("log").description("查看日志").action(g),Is.command("up").description("更新插件").option("-f, --force","强制更新").option("-s, --serial","并发更新").action((e=>(async(e,t=!1)=>{try{console.log("开始执行更新任务\n");const i=[],r=[];await ns("./package.json",i,r),await ss("./plugins",i,e,t);const o=(n=i,[...n].sort(((e,t)=>e.isPlugin!==t.isPlugin?e.isPlugin?1:-1:e.needUpdate!==t.needUpdate?e.needUpdate?1:-1:e.name.localeCompare(t.name))));if(o.length>0){console.log("检查结果:");const e=o.map((e=>({name:e.name,type:e.type,currentVersion:e.currentVersion,latestVersion:e.latestVersion,status:e.status})));console.table(e)}else console.log("没有找到需要检查的项目");if(r.length>0){console.log("\n开始更新包:");try{const{status:e,error:t}=await u(`pnpm update ${r.join(" ")} --save`);if(e){console.log("npm包更新完成");const e=o.filter((e=>e.needUpdate));if(e.length>0){console.log("\n已更新的项目:");const t=e.map((e=>({name:e.name,type:e.type,from:e.currentVersion,to:e.latestVersion})));console.table(t)}}else console.error("npm包更新失败:",t)}catch(s){console.error("npm包更新失败:",s)}}console.log("\n更新任务执行完成")}finally{process.exit(0)}var n})(e.force,!e.serial))),Is.command("init").description("初始化项目").option("-f, --force","强制初始化").option("-d, --dev","开发模式").action((e=>{process.env.KARIN_CLI="true",e.dev&&(process.env.NODE_ENV="development"),Yn(e.force)})),Is.command("b").alias("allow-build").description("构建依赖管理 (pnpm v10.x)").argument("<action>","操作类型: add, rm, ls").argument("[dependency]","依赖包名称 (add/rm操作需要 多个使用,分割)").action(((e,t)=>{"add"===e&&t?cs(t):"rm"===e&&t?ls(t):"ls"===e?us():console.log("无效的命令。有效命令: add <dependency>, rm <dependency>, ls")})),Is.parse(process.argv);
|