@cardstack/boxel-cli 0.1.0 → 0.1.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/LICENSE +21 -0
- package/dist/index.js +48 -48
- package/package.json +30 -31
- package/src/build-program.ts +91 -0
- package/src/commands/realm/push.ts +27 -11
- package/src/commands/realm/sync.ts +7 -0
- package/src/index.ts +3 -83
- package/src/lib/boxel-cli-client.ts +11 -0
- package/src/lib/realm-sync-base.ts +76 -7
- package/bin/boxel.js +0 -15
package/dist/index.js
CHANGED
|
@@ -1,114 +1,114 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var
|
|
3
|
-
`);let n;for(;(n=
|
|
4
|
-
`),s=s.replace(/\\r/g,"\r")),e[i]=s}return e}function mc(r){r=r||{};let e=Bn(r);r.path=e;let t=U.configDotenv(r);if(!t.parsed){let o=new Error(`MISSING_DATA: Cannot parse ${e} for an unknown reason`);throw o.code="MISSING_DATA",o}let n=Wn(r).split(","),i=n.length,s;for(let o=0;o<i;o++)try{let a=n[o].trim(),l=hc(t,a);s=U.decrypt(l.ciphertext,l.key);break}catch(a){if(o+1>=i)throw a}return U.parse(s)}function dc(r){console.log(`[dotenv@${er}][WARN] ${r}`)}function De(r){console.log(`[dotenv@${er}][DEBUG] ${r}`)}function Hn(r){console.log(`[dotenv@${er}] ${r}`)}function Wn(r){return r&&r.DOTENV_KEY&&r.DOTENV_KEY.length>0?r.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:""}function hc(r,e){let t;try{t=new URL(e)}catch(a){if(a.code==="ERR_INVALID_URL"){let l=new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");throw l.code="INVALID_DOTENV_KEY",l}throw a}let n=t.password;if(!n){let a=new Error("INVALID_DOTENV_KEY: Missing key part");throw a.code="INVALID_DOTENV_KEY",a}let i=t.searchParams.get("environment");if(!i){let a=new Error("INVALID_DOTENV_KEY: Missing environment part");throw a.code="INVALID_DOTENV_KEY",a}let s=`DOTENV_VAULT_${i.toUpperCase()}`,o=r.parsed[s];if(!o){let a=new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${s} in your .env.vault file.`);throw a.code="NOT_FOUND_DOTENV_ENVIRONMENT",a}return{ciphertext:o,key:n}}function Bn(r){let e=null;if(r&&r.path&&r.path.length>0)if(Array.isArray(r.path))for(let t of r.path)Zt.existsSync(t)&&(e=t.endsWith(".vault")?t:`${t}.vault`);else e=r.path.endsWith(".vault")?r.path:`${r.path}.vault`;else e=it.resolve(process.cwd(),".env.vault");return Zt.existsSync(e)?e:null}function Gn(r){return r[0]==="~"?it.join(ac.homedir(),r.slice(1)):r}function pc(r){let e=!!(r&&r.debug),t=r&&"quiet"in r?r.quiet:!0;(e||!t)&&Hn("Loading env from encrypted .env.vault");let n=U._parseVault(r),i=process.env;return r&&r.processEnv!=null&&(i=r.processEnv),U.populate(i,n,r),{parsed:n}}function gc(r){let e=it.resolve(process.cwd(),".env"),t="utf8",n=!!(r&&r.debug),i=r&&"quiet"in r?r.quiet:!0;r&&r.encoding?t=r.encoding:n&&De("No encoding is specified. UTF-8 is used by default");let s=[e];if(r&&r.path)if(!Array.isArray(r.path))s=[Gn(r.path)];else{s=[];for(let u of r.path)s.push(Gn(u))}let o,a={};for(let u of s)try{let c=U.parse(Zt.readFileSync(u,{encoding:t}));U.populate(a,c,r)}catch(c){n&&De(`Failed to load ${u} ${c.message}`),o=c}let l=process.env;if(r&&r.processEnv!=null&&(l=r.processEnv),U.populate(l,a,r),n||!i){let u=Object.keys(a).length,c=[];for(let f of s)try{let d=it.relative(process.cwd(),f);c.push(d)}catch(d){n&&De(`Failed to load ${f} ${d.message}`),o=d}Hn(`injecting env (${u}) from ${c.join(",")}`)}return o?{parsed:a,error:o}:{parsed:a}}function yc(r){if(Wn(r).length===0)return U.configDotenv(r);let e=Bn(r);return e?U._configVault(r):(dc(`You set DOTENV_KEY but you are missing a .env.vault file at ${e}. Did you forget to build it?`),U.configDotenv(r))}function Ec(r,e){let t=Buffer.from(e.slice(-64),"hex"),n=Buffer.from(r,"base64"),i=n.subarray(0,12),s=n.subarray(-16);n=n.subarray(12,-16);try{let o=lc.createDecipheriv("aes-256-gcm",t,i);return o.setAuthTag(s),`${o.update(n)}${o.final()}`}catch(o){let a=o instanceof RangeError,l=o.message==="Invalid key length",u=o.message==="Unsupported state or unable to authenticate data";if(a||l){let c=new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");throw c.code="INVALID_DOTENV_KEY",c}else if(u){let c=new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");throw c.code="DECRYPTION_FAILED",c}else throw o}}function wc(r,e,t={}){let n=!!(t&&t.debug),i=!!(t&&t.override);if(typeof e!="object"){let s=new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");throw s.code="OBJECT_REQUIRED",s}for(let s of Object.keys(e))Object.prototype.hasOwnProperty.call(r,s)?(i===!0&&(r[s]=e[s]),n&&De(i===!0?`"${s}" is already defined and WAS overwritten`:`"${s}" is already defined and was NOT overwritten`)):r[s]=e[s]}var U={configDotenv:gc,_configVault:pc,_parseVault:mc,config:yc,decrypt:Ec,parse:fc,populate:wc};le.exports.configDotenv=U.configDotenv;le.exports._configVault=U._configVault;le.exports._parseVault=U._parseVault;le.exports.config=U.config;le.exports.decrypt=U.decrypt;le.exports.parse=U.parse;le.exports.populate=U.populate;le.exports=U});var zn=p((by,Xn)=>{var be={};process.env.DOTENV_CONFIG_ENCODING!=null&&(be.encoding=process.env.DOTENV_CONFIG_ENCODING);process.env.DOTENV_CONFIG_PATH!=null&&(be.path=process.env.DOTENV_CONFIG_PATH);process.env.DOTENV_CONFIG_QUIET!=null&&(be.quiet=process.env.DOTENV_CONFIG_QUIET);process.env.DOTENV_CONFIG_DEBUG!=null&&(be.debug=process.env.DOTENV_CONFIG_DEBUG);process.env.DOTENV_CONFIG_OVERRIDE!=null&&(be.override=process.env.DOTENV_CONFIG_OVERRIDE);process.env.DOTENV_CONFIG_DOTENV_KEY!=null&&(be.DOTENV_KEY=process.env.DOTENV_CONFIG_DOTENV_KEY);Xn.exports=be});var Kn=p((Ry,Jn)=>{var bc=/^dotenv_config_(encoding|path|quiet|debug|override|DOTENV_KEY)=(.+)$/;Jn.exports=function(e){let t=e.reduce(function(n,i){let s=i.match(bc);return s&&(n[s[1]]=s[2]),n},{});return"quiet"in t||(t.quiet="true"),t}});var Fe=p(rr=>{var st=class 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}},tr=class extends st{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};rr.CommanderError=st;rr.InvalidArgumentError=tr});var ot=p(ir=>{var{InvalidArgumentError:Rc}=Fe(),nr=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;break}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)?[e]:t.concat(e)}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,n)=>{if(!this.argChoices.includes(t))throw new Rc(`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}};function $c(r){let e=r.name()+(r.variadic===!0?"...":"");return r.required?"<"+e+">":"["+e+"]"}ir.Argument=nr;ir.humanReadableArgName=$c});var ar=p(or=>{var{humanReadableArgName:vc}=ot(),sr=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){let t=e.commands.filter(i=>!i._hidden),n=e._getHelpCommand();return n&&!n._hidden&&t.push(n),this.sortSubcommands&&t.sort((i,s)=>i.name().localeCompare(s.name())),t}compareOptions(e,t){let n=i=>i.short?i.short.replace(/^-/,""):i.long.replace(/^--/,"");return n(e).localeCompare(n(t))}visibleOptions(e){let t=e.options.filter(i=>!i.hidden),n=e._getHelpOption();if(n&&!n.hidden){let i=n.short&&e._findOption(n.short),s=n.long&&e._findOption(n.long);!i&&!s?t.push(n):n.long&&!s?t.push(e.createOption(n.long,n.description)):n.short&&!i&&t.push(e.createOption(n.short,n.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let n=e.parent;n;n=n.parent){let i=n.options.filter(s=>!s.hidden);t.push(...i)}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(t=>t.description)?e.registeredArguments:[]}subcommandTerm(e){let t=e.registeredArguments.map(n=>vc(n)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(t?" "+t:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((n,i)=>Math.max(n,this.displayWidth(t.styleSubcommandTerm(t.subcommandTerm(i)))),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((n,i)=>Math.max(n,this.displayWidth(t.styleOptionTerm(t.optionTerm(i)))),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((n,i)=>Math.max(n,this.displayWidth(t.styleOptionTerm(t.optionTerm(i)))),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((n,i)=>Math.max(n,this.displayWidth(t.styleArgumentTerm(t.argumentTerm(i)))),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+"|"+e._aliases[0]);let n="";for(let i=e.parent;i;i=i.parent)n=i.name()+" "+n;return n+t+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];return e.argChoices&&t.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&t.push(`env: ${e.envVar}`),t.length>0?`${e.description} (${t.join(", ")})`:e.description}argumentDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let n=`(${t.join(", ")})`;return e.description?`${e.description} ${n}`:n}return e.description}formatHelp(e,t){let n=t.padWidth(e,t),i=t.helpWidth??80;function s(f,d){return t.formatItem(f,n,d,t)}let o=[`${t.styleTitle("Usage:")} ${t.styleUsage(t.commandUsage(e))}`,""],a=t.commandDescription(e);a.length>0&&(o=o.concat([t.boxWrap(t.styleCommandDescription(a),i),""]));let l=t.visibleArguments(e).map(f=>s(t.styleArgumentTerm(t.argumentTerm(f)),t.styleArgumentDescription(t.argumentDescription(f))));l.length>0&&(o=o.concat([t.styleTitle("Arguments:"),...l,""]));let u=t.visibleOptions(e).map(f=>s(t.styleOptionTerm(t.optionTerm(f)),t.styleOptionDescription(t.optionDescription(f))));if(u.length>0&&(o=o.concat([t.styleTitle("Options:"),...u,""])),t.showGlobalOptions){let f=t.visibleGlobalOptions(e).map(d=>s(t.styleOptionTerm(t.optionTerm(d)),t.styleOptionDescription(t.optionDescription(d))));f.length>0&&(o=o.concat([t.styleTitle("Global Options:"),...f,""]))}let c=t.visibleCommands(e).map(f=>s(t.styleSubcommandTerm(t.subcommandTerm(f)),t.styleSubcommandDescription(t.subcommandDescription(f))));return c.length>0&&(o=o.concat([t.styleTitle("Commands:"),...c,""])),o.join(`
|
|
2
|
+
"use strict";var tc=Object.create;var qn=Object.defineProperty;var rc=Object.getOwnPropertyDescriptor;var nc=Object.getOwnPropertyNames;var ic=Object.getPrototypeOf,sc=Object.prototype.hasOwnProperty;var h=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports);var oc=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of nc(e))!sc.call(r,i)&&i!==t&&qn(r,i,{get:()=>e[i],enumerable:!(n=rc(e,i))||n.enumerable});return r};var N=(r,e,t)=>(t=r!=null?tc(ic(r)):{},oc(e||!r||!r.__esModule?qn(t,"default",{value:r,enumerable:!0}):t,r));var Vn=h((Ry,ac)=>{ac.exports={name:"dotenv",version:"16.6.1",description:"Loads environment variables from .env file",main:"lib/main.js",types:"lib/main.d.ts",exports:{".":{types:"./lib/main.d.ts",require:"./lib/main.js",default:"./lib/main.js"},"./config":"./config.js","./config.js":"./config.js","./lib/env-options":"./lib/env-options.js","./lib/env-options.js":"./lib/env-options.js","./lib/cli-options":"./lib/cli-options.js","./lib/cli-options.js":"./lib/cli-options.js","./package.json":"./package.json"},scripts:{"dts-check":"tsc --project tests/types/tsconfig.json",lint:"standard",pretest:"npm run lint && npm run dts-check",test:"tap run --allow-empty-coverage --disable-coverage --timeout=60000","test:coverage":"tap run --show-full-coverage --timeout=60000 --coverage-report=text --coverage-report=lcov",prerelease:"npm test",release:"standard-version"},repository:{type:"git",url:"git://github.com/motdotla/dotenv.git"},homepage:"https://github.com/motdotla/dotenv#readme",funding:"https://dotenvx.com",keywords:["dotenv","env",".env","environment","variables","config","settings"],readmeFilename:"README.md",license:"BSD-2-Clause",devDependencies:{"@types/node":"^18.11.3",decache:"^4.6.2",sinon:"^14.0.1",standard:"^17.0.0","standard-version":"^9.5.0",tap:"^19.2.0",typescript:"^4.8.4"},engines:{node:">=12"},browser:{fs:!1}}});var Yn=h(($y,le)=>{var Zt=require("fs"),it=require("path"),lc=require("os"),cc=require("crypto"),uc=Vn(),er=uc.version,fc=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;function mc(r){let e={},t=r.toString();t=t.replace(/\r\n?/mg,`
|
|
3
|
+
`);let n;for(;(n=fc.exec(t))!=null;){let i=n[1],s=n[2]||"";s=s.trim();let o=s[0];s=s.replace(/^(['"`])([\s\S]*)\1$/mg,"$2"),o==='"'&&(s=s.replace(/\\n/g,`
|
|
4
|
+
`),s=s.replace(/\\r/g,"\r")),e[i]=s}return e}function dc(r){r=r||{};let e=Bn(r);r.path=e;let t=U.configDotenv(r);if(!t.parsed){let o=new Error(`MISSING_DATA: Cannot parse ${e} for an unknown reason`);throw o.code="MISSING_DATA",o}let n=Wn(r).split(","),i=n.length,s;for(let o=0;o<i;o++)try{let a=n[o].trim(),l=hc(t,a);s=U.decrypt(l.ciphertext,l.key);break}catch(a){if(o+1>=i)throw a}return U.parse(s)}function pc(r){console.log(`[dotenv@${er}][WARN] ${r}`)}function Me(r){console.log(`[dotenv@${er}][DEBUG] ${r}`)}function Hn(r){console.log(`[dotenv@${er}] ${r}`)}function Wn(r){return r&&r.DOTENV_KEY&&r.DOTENV_KEY.length>0?r.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:""}function hc(r,e){let t;try{t=new URL(e)}catch(a){if(a.code==="ERR_INVALID_URL"){let l=new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");throw l.code="INVALID_DOTENV_KEY",l}throw a}let n=t.password;if(!n){let a=new Error("INVALID_DOTENV_KEY: Missing key part");throw a.code="INVALID_DOTENV_KEY",a}let i=t.searchParams.get("environment");if(!i){let a=new Error("INVALID_DOTENV_KEY: Missing environment part");throw a.code="INVALID_DOTENV_KEY",a}let s=`DOTENV_VAULT_${i.toUpperCase()}`,o=r.parsed[s];if(!o){let a=new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${s} in your .env.vault file.`);throw a.code="NOT_FOUND_DOTENV_ENVIRONMENT",a}return{ciphertext:o,key:n}}function Bn(r){let e=null;if(r&&r.path&&r.path.length>0)if(Array.isArray(r.path))for(let t of r.path)Zt.existsSync(t)&&(e=t.endsWith(".vault")?t:`${t}.vault`);else e=r.path.endsWith(".vault")?r.path:`${r.path}.vault`;else e=it.resolve(process.cwd(),".env.vault");return Zt.existsSync(e)?e:null}function Gn(r){return r[0]==="~"?it.join(lc.homedir(),r.slice(1)):r}function gc(r){let e=!!(r&&r.debug),t=r&&"quiet"in r?r.quiet:!0;(e||!t)&&Hn("Loading env from encrypted .env.vault");let n=U._parseVault(r),i=process.env;return r&&r.processEnv!=null&&(i=r.processEnv),U.populate(i,n,r),{parsed:n}}function yc(r){let e=it.resolve(process.cwd(),".env"),t="utf8",n=!!(r&&r.debug),i=r&&"quiet"in r?r.quiet:!0;r&&r.encoding?t=r.encoding:n&&Me("No encoding is specified. UTF-8 is used by default");let s=[e];if(r&&r.path)if(!Array.isArray(r.path))s=[Gn(r.path)];else{s=[];for(let u of r.path)s.push(Gn(u))}let o,a={};for(let u of s)try{let c=U.parse(Zt.readFileSync(u,{encoding:t}));U.populate(a,c,r)}catch(c){n&&Me(`Failed to load ${u} ${c.message}`),o=c}let l=process.env;if(r&&r.processEnv!=null&&(l=r.processEnv),U.populate(l,a,r),n||!i){let u=Object.keys(a).length,c=[];for(let f of s)try{let d=it.relative(process.cwd(),f);c.push(d)}catch(d){n&&Me(`Failed to load ${f} ${d.message}`),o=d}Hn(`injecting env (${u}) from ${c.join(",")}`)}return o?{parsed:a,error:o}:{parsed:a}}function Ec(r){if(Wn(r).length===0)return U.configDotenv(r);let e=Bn(r);return e?U._configVault(r):(pc(`You set DOTENV_KEY but you are missing a .env.vault file at ${e}. Did you forget to build it?`),U.configDotenv(r))}function wc(r,e){let t=Buffer.from(e.slice(-64),"hex"),n=Buffer.from(r,"base64"),i=n.subarray(0,12),s=n.subarray(-16);n=n.subarray(12,-16);try{let o=cc.createDecipheriv("aes-256-gcm",t,i);return o.setAuthTag(s),`${o.update(n)}${o.final()}`}catch(o){let a=o instanceof RangeError,l=o.message==="Invalid key length",u=o.message==="Unsupported state or unable to authenticate data";if(a||l){let c=new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");throw c.code="INVALID_DOTENV_KEY",c}else if(u){let c=new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");throw c.code="DECRYPTION_FAILED",c}else throw o}}function bc(r,e,t={}){let n=!!(t&&t.debug),i=!!(t&&t.override);if(typeof e!="object"){let s=new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");throw s.code="OBJECT_REQUIRED",s}for(let s of Object.keys(e))Object.prototype.hasOwnProperty.call(r,s)?(i===!0&&(r[s]=e[s]),n&&Me(i===!0?`"${s}" is already defined and WAS overwritten`:`"${s}" is already defined and was NOT overwritten`)):r[s]=e[s]}var U={configDotenv:yc,_configVault:gc,_parseVault:dc,config:Ec,decrypt:wc,parse:mc,populate:bc};le.exports.configDotenv=U.configDotenv;le.exports._configVault=U._configVault;le.exports._parseVault=U._parseVault;le.exports.config=U.config;le.exports.decrypt=U.decrypt;le.exports.parse=U.parse;le.exports.populate=U.populate;le.exports=U});var zn=h((vy,Xn)=>{var we={};process.env.DOTENV_CONFIG_ENCODING!=null&&(we.encoding=process.env.DOTENV_CONFIG_ENCODING);process.env.DOTENV_CONFIG_PATH!=null&&(we.path=process.env.DOTENV_CONFIG_PATH);process.env.DOTENV_CONFIG_QUIET!=null&&(we.quiet=process.env.DOTENV_CONFIG_QUIET);process.env.DOTENV_CONFIG_DEBUG!=null&&(we.debug=process.env.DOTENV_CONFIG_DEBUG);process.env.DOTENV_CONFIG_OVERRIDE!=null&&(we.override=process.env.DOTENV_CONFIG_OVERRIDE);process.env.DOTENV_CONFIG_DOTENV_KEY!=null&&(we.DOTENV_KEY=process.env.DOTENV_CONFIG_DOTENV_KEY);Xn.exports=we});var Kn=h((Sy,Jn)=>{var Rc=/^dotenv_config_(encoding|path|quiet|debug|override|DOTENV_KEY)=(.+)$/;Jn.exports=function(e){let t=e.reduce(function(n,i){let s=i.match(Rc);return s&&(n[s[1]]=s[2]),n},{});return"quiet"in t||(t.quiet="true"),t}});var De=h(rr=>{var st=class 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}},tr=class extends st{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};rr.CommanderError=st;rr.InvalidArgumentError=tr});var ot=h(ir=>{var{InvalidArgumentError:$c}=De(),nr=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;break}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)?[e]:t.concat(e)}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,n)=>{if(!this.argChoices.includes(t))throw new $c(`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}};function vc(r){let e=r.name()+(r.variadic===!0?"...":"");return r.required?"<"+e+">":"["+e+"]"}ir.Argument=nr;ir.humanReadableArgName=vc});var ar=h(or=>{var{humanReadableArgName:Sc}=ot(),sr=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){let t=e.commands.filter(i=>!i._hidden),n=e._getHelpCommand();return n&&!n._hidden&&t.push(n),this.sortSubcommands&&t.sort((i,s)=>i.name().localeCompare(s.name())),t}compareOptions(e,t){let n=i=>i.short?i.short.replace(/^-/,""):i.long.replace(/^--/,"");return n(e).localeCompare(n(t))}visibleOptions(e){let t=e.options.filter(i=>!i.hidden),n=e._getHelpOption();if(n&&!n.hidden){let i=n.short&&e._findOption(n.short),s=n.long&&e._findOption(n.long);!i&&!s?t.push(n):n.long&&!s?t.push(e.createOption(n.long,n.description)):n.short&&!i&&t.push(e.createOption(n.short,n.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let n=e.parent;n;n=n.parent){let i=n.options.filter(s=>!s.hidden);t.push(...i)}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(t=>t.description)?e.registeredArguments:[]}subcommandTerm(e){let t=e.registeredArguments.map(n=>Sc(n)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(t?" "+t:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((n,i)=>Math.max(n,this.displayWidth(t.styleSubcommandTerm(t.subcommandTerm(i)))),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((n,i)=>Math.max(n,this.displayWidth(t.styleOptionTerm(t.optionTerm(i)))),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((n,i)=>Math.max(n,this.displayWidth(t.styleOptionTerm(t.optionTerm(i)))),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((n,i)=>Math.max(n,this.displayWidth(t.styleArgumentTerm(t.argumentTerm(i)))),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+"|"+e._aliases[0]);let n="";for(let i=e.parent;i;i=i.parent)n=i.name()+" "+n;return n+t+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];return e.argChoices&&t.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&t.push(`env: ${e.envVar}`),t.length>0?`${e.description} (${t.join(", ")})`:e.description}argumentDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let n=`(${t.join(", ")})`;return e.description?`${e.description} ${n}`:n}return e.description}formatHelp(e,t){let n=t.padWidth(e,t),i=t.helpWidth??80;function s(f,d){return t.formatItem(f,n,d,t)}let o=[`${t.styleTitle("Usage:")} ${t.styleUsage(t.commandUsage(e))}`,""],a=t.commandDescription(e);a.length>0&&(o=o.concat([t.boxWrap(t.styleCommandDescription(a),i),""]));let l=t.visibleArguments(e).map(f=>s(t.styleArgumentTerm(t.argumentTerm(f)),t.styleArgumentDescription(t.argumentDescription(f))));l.length>0&&(o=o.concat([t.styleTitle("Arguments:"),...l,""]));let u=t.visibleOptions(e).map(f=>s(t.styleOptionTerm(t.optionTerm(f)),t.styleOptionDescription(t.optionDescription(f))));if(u.length>0&&(o=o.concat([t.styleTitle("Options:"),...u,""])),t.showGlobalOptions){let f=t.visibleGlobalOptions(e).map(d=>s(t.styleOptionTerm(t.optionTerm(d)),t.styleOptionDescription(t.optionDescription(d))));f.length>0&&(o=o.concat([t.styleTitle("Global Options:"),...f,""]))}let c=t.visibleCommands(e).map(f=>s(t.styleSubcommandTerm(t.subcommandTerm(f)),t.styleSubcommandDescription(t.subcommandDescription(f))));return c.length>0&&(o=o.concat([t.styleTitle("Commands:"),...c,""])),o.join(`
|
|
5
5
|
`)}displayWidth(e){return Qn(e).length}styleTitle(e){return e}styleUsage(e){return e.split(" ").map(t=>t==="[options]"?this.styleOptionText(t):t==="[command]"?this.styleSubcommandText(t):t[0]==="["||t[0]==="<"?this.styleArgumentText(t):this.styleCommandText(t)).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(t=>t==="[options]"?this.styleOptionText(t):t[0]==="["||t[0]==="<"?this.styleArgumentText(t):this.styleSubcommandText(t)).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,i){let o=" ".repeat(2);if(!n)return o+e;let a=e.padEnd(t+e.length-i.displayWidth(e)),l=2,c=(this.helpWidth??80)-t-l-2,f;return c<this.minWidthToWrap||i.preformatted(n)?f=n:f=i.boxWrap(n,c).replace(/\n/g,`
|
|
6
6
|
`+" ".repeat(t+l)),o+a+" ".repeat(l)+f.replace(/\n/g,`
|
|
7
7
|
${o}`)}boxWrap(e,t){if(t<this.minWidthToWrap)return e;let n=e.split(/\r\n|\n/),i=/[\s]*[^\s]+/g,s=[];return n.forEach(o=>{let a=o.match(i);if(a===null){s.push("");return}let l=[a.shift()],u=this.displayWidth(l[0]);a.forEach(c=>{let f=this.displayWidth(c);if(u+f<=t){l.push(c),u+=f;return}s.push(l.join(""));let d=c.trimStart();l=[d],u=this.displayWidth(d)}),s.push(l.join(""))}),s.join(`
|
|
8
|
-
`)}};function Qn(r){let e=/\x1b\[\d*(;\d*)*m/g;return r.replace(e,"")}or.Help=sr;or.stripColor=Qn});var fr=
|
|
8
|
+
`)}};function Qn(r){let e=/\x1b\[\d*(;\d*)*m/g;return r.replace(e,"")}or.Help=sr;or.stripColor=Qn});var fr=h(ur=>{var{InvalidArgumentError:xc}=De(),lr=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;let n=_c(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 typeof e=="string"&&(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)?[e]:t.concat(e)}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,n)=>{if(!this.argChoices.includes(t))throw new xc(`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?Zn(this.name().replace(/^no-/,"")):Zn(this.name())}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},cr=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(t=>{t.negate?this.negativeOptions.set(t.attributeName(),t):this.positiveOptions.set(t.attributeName(),t)}),this.negativeOptions.forEach((t,n)=>{this.positiveOptions.has(n)&&this.dualOptions.add(n)})}valueFromOption(e,t){let n=t.attributeName();if(!this.dualOptions.has(n))return!0;let i=this.negativeOptions.get(n).presetArg,s=i!==void 0?i:!1;return t.negate===(s===e)}};function Zn(r){return r.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function _c(r){let e,t,n=/^-[^-]$/,i=/^--[^-]/,s=r.split(/[ |,]+/).concat("guard");if(n.test(s[0])&&(e=s.shift()),i.test(s[0])&&(t=s.shift()),!e&&n.test(s[0])&&(e=s.shift()),!e&&i.test(s[0])&&(e=t,t=s.shift()),s[0].startsWith("-")){let o=s[0],a=`option creation failed due to '${o}' in option flags '${r}'`;throw/^-[^-][^-]/.test(o)?new Error(`${a}
|
|
9
9
|
- a short flag is a single dash and a single character
|
|
10
10
|
- either use a single dash and a single character (for a short flag)
|
|
11
11
|
- or use a double dash for a long option (and can have two, like '--ws, --workspace')`):n.test(o)?new Error(`${a}
|
|
12
12
|
- too many short flags`):i.test(o)?new Error(`${a}
|
|
13
13
|
- too many long flags`):new Error(`${a}
|
|
14
|
-
- unrecognised flag format`)}if(e===void 0&&t===void 0)throw new Error(`option creation failed due to no flags found in '${r}'.`);return{shortFlag:e,longFlag:t}}ur.Option=lr;ur.DualOptions=cr});var ti=
|
|
14
|
+
- unrecognised flag format`)}if(e===void 0&&t===void 0)throw new Error(`option creation failed due to no flags found in '${r}'.`);return{shortFlag:e,longFlag:t}}ur.Option=lr;ur.DualOptions=cr});var ti=h(ei=>{function Oc(r,e){if(Math.abs(r.length-e.length)>3)return Math.max(r.length,e.length);let t=[];for(let n=0;n<=r.length;n++)t[n]=[n];for(let n=0;n<=e.length;n++)t[0][n]=n;for(let n=1;n<=e.length;n++)for(let i=1;i<=r.length;i++){let s=1;r[i-1]===e[n-1]?s=0:s=1,t[i][n]=Math.min(t[i-1][n]+1,t[i][n-1]+1,t[i-1][n-1]+s),i>1&&n>1&&r[i-1]===e[n-2]&&r[i-2]===e[n-1]&&(t[i][n]=Math.min(t[i][n],t[i-2][n-2]+1))}return t[r.length][e.length]}function Cc(r,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let t=r.startsWith("--");t&&(r=r.slice(2),e=e.map(o=>o.slice(2)));let n=[],i=3,s=.4;return e.forEach(o=>{if(o.length<=1)return;let a=Oc(r,o),l=Math.max(r.length,o.length);(l-a)/l>s&&(a<i?(i=a,n=[o]):a===i&&n.push(o))}),n.sort((o,a)=>o.localeCompare(a)),t&&(n=n.map(o=>`--${o}`)),n.length>1?`
|
|
15
15
|
(Did you mean one of ${n.join(", ")}?)`:n.length===1?`
|
|
16
|
-
(Did you mean ${n[0]}?)`:""}ei.suggestSimilar=
|
|
17
|
-
- specify the name in Command constructor or using .name()`);return t=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
|
|
16
|
+
(Did you mean ${n[0]}?)`:""}ei.suggestSimilar=Cc});var si=h(gr=>{var Ac=require("node:events").EventEmitter,mr=require("node:child_process"),ce=require("node:path"),at=require("node:fs"),A=require("node:process"),{Argument:Tc,humanReadableArgName:kc}=ot(),{CommanderError:dr}=De(),{Help:Pc,stripColor:Lc}=ar(),{Option:ri,DualOptions:Ic}=fr(),{suggestSimilar:ni}=ti(),pr=class r extends Ac{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:t=>A.stdout.write(t),writeErr:t=>A.stderr.write(t),outputError:(t,n)=>n(t),getOutHelpWidth:()=>A.stdout.isTTY?A.stdout.columns:void 0,getErrHelpWidth:()=>A.stderr.isTTY?A.stderr.columns:void 0,getOutHasColors:()=>hr()??(A.stdout.isTTY&&A.stdout.hasColors?.()),getErrHasColors:()=>hr()??(A.stderr.isTTY&&A.stderr.hasColors?.()),stripColor:t=>Lc(t)},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(){let e=[];for(let t=this;t;t=t.parent)e.push(t);return e}command(e,t,n){let i=t,s=n;typeof i=="object"&&i!==null&&(s=i,i=null),s=s||{};let[,o,a]=e.match(/([^ ]+) *(.*)/),l=this.createCommand(o);return i&&(l.description(i),l._executableHandler=!0),s.isDefault&&(this._defaultCommandName=l._name),l._hidden=!!(s.noHelp||s.hidden),l._executableFile=s.executableFile||null,a&&l.arguments(a),this._registerCommand(l),l.parent=this,l.copyInheritedSettings(this),i?this:l}createCommand(e){return new r(e)}createHelp(){return Object.assign(new Pc,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(Object.assign(this._outputConfiguration,e),this)}showHelpAfterError(e=!0){return typeof e!="string"&&(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
|
|
17
|
+
- specify the name in Command constructor or using .name()`);return t=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 Tc(e,t)}argument(e,t,n,i){let s=this.createArgument(e,t);return typeof n=="function"?s.default(i).argParser(n):s.default(n),this.addArgument(s),this}arguments(e){return e.trim().split(/ +/).forEach(t=>{this.argument(t)}),this}addArgument(e){let 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&&e.defaultValue!==void 0&&e.parseArg===void 0)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(typeof e=="boolean")return this._addImplicitHelpCommand=e,this;e=e??"help [command]";let[,n,i]=e.match(/([^ ]+) *(.*)/),s=t??"display help for command",o=this.createCommand(n);return o.helpOption(!1),i&&o.arguments(i),s&&o.description(s),this._addImplicitHelpCommand=!0,this._helpCommand=o,this}addHelpCommand(e,t){return typeof e!="object"?(this.helpCommand(e,t),this):(this._addImplicitHelpCommand=!0,this._helpCommand=e,this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,t){let n=["preSubcommand","preAction","postAction"];if(!n.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
|
|
18
18
|
Expecting one of '${n.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=t=>{if(t.code!=="commander.executeSubCommandAsync")throw t},this}_exit(e,t,n){this._exitCallback&&this._exitCallback(new dr(e,t,n)),A.exit(e)}action(e){let t=n=>{let i=this.registeredArguments.length,s=n.slice(0,i);return this._storeOptionsAsProperties?s[i]=this:s[i]=this.opts(),s.push(this),e.apply(this,s)};return this._actionHandler=t,this}createOption(e,t){return new ri(e,t)}_callParseArg(e,t,n,i){try{return e.parseArg(t,n)}catch(s){if(s.code==="commander.invalidArgument"){let o=`${i} ${s.message}`;this.error(o,{exitCode:s.exitCode,code:s.code})}throw s}}_registerOption(e){let t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){let 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}'
|
|
19
19
|
- already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){let t=i=>[i.name()].concat(i.aliases()),n=t(e).find(i=>this._findCommand(i));if(n){let i=t(this._findCommand(n)).join("|"),s=t(e).join("|");throw new Error(`cannot add command '${s}' as already have command '${i}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),n=e.attributeName();if(e.negate){let s=e.long.replace(/^--no-/,"--");this._findOption(s)||this.setOptionValueWithSource(n,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(n,e.defaultValue,"default");let i=(s,o,a)=>{s==null&&e.presetArg!==void 0&&(s=e.presetArg);let l=this.getOptionValue(n);s!==null&&e.parseArg?s=this._callParseArg(e,s,l,o):s!==null&&e.variadic&&(s=e._concatValue(s,l)),s==null&&(e.negate?s=!1:e.isBoolean()||e.optional?s=!0:s=""),this.setOptionValueWithSource(n,s,a)};return this.on("option:"+t,s=>{let o=`error: option '${e.flags}' argument '${s}' is invalid.`;i(s,o,"cli")}),e.envVar&&this.on("optionEnv:"+t,s=>{let o=`error: option '${e.flags}' value '${s}' from env '${e.envVar}' is invalid.`;i(s,o,"env")}),this}_optionEx(e,t,n,i,s){if(typeof t=="object"&&t instanceof ri)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let o=this.createOption(t,n);if(o.makeOptionMandatory(!!e.mandatory),typeof i=="function")o.default(s).argParser(i);else if(i instanceof RegExp){let a=i;i=(l,u)=>{let c=a.exec(l);return c?c[0]:u},o.default(s).argParser(i)}else o.default(i);return this.addOption(o)}option(e,t,n,i){return this._optionEx({},e,t,n,i)}requiredOption(e,t,n,i){return this._optionEx({mandatory:!0},e,t,n,i)}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=>{n.getOptionValueSource(e)!==void 0&&(t=n.getOptionValueSource(e))}),t}_prepareUserArgs(e,t){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(t=t||{},e===void 0&&t.from===void 0){A.versions?.electron&&(t.from="electron");let i=A.execArgv??[];(i.includes("-e")||i.includes("--eval")||i.includes("-p")||i.includes("--print"))&&(t.from="eval")}e===void 0&&(e=A.argv),this.rawArgs=e.slice();let n;switch(t.from){case void 0:case"node":this._scriptPath=e[1],n=e.slice(2);break;case"electron":A.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();let n=this._prepareUserArgs(e,t);return this._parseCommand([],n),this}async parseAsync(e,t){this._prepareForParse();let n=this._prepareUserArgs(e,t);return await this._parseCommand([],n),this}_prepareForParse(){this._savedState===null?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.
|
|
20
20
|
- 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(at.existsSync(e))return;let i=t?`searched for local subcommand relative to directory '${t}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",s=`'${e}' does not exist
|
|
21
21
|
- if '${n}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
22
22
|
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
23
|
-
- ${i}`;throw new Error(s)}_executeSubCommand(e,t){t=t.slice();let n=!1,i=[".js",".ts",".tsx",".mjs",".cjs"];function s(c,f){let d=ce.resolve(c,f);if(at.existsSync(d))return d;if(i.includes(ce.extname(f)))return;let
|
|
23
|
+
- ${i}`;throw new Error(s)}_executeSubCommand(e,t){t=t.slice();let n=!1,i=[".js",".ts",".tsx",".mjs",".cjs"];function s(c,f){let d=ce.resolve(c,f);if(at.existsSync(d))return d;if(i.includes(ce.extname(f)))return;let p=i.find(g=>at.existsSync(`${d}${g}`));if(p)return`${d}${p}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let c;try{c=at.realpathSync(this._scriptPath)}catch{c=this._scriptPath}a=ce.resolve(ce.dirname(c),a)}if(a){let c=s(a,o);if(!c&&!e._executableFile&&this._scriptPath){let f=ce.basename(this._scriptPath,ce.extname(this._scriptPath));f!==this._name&&(c=s(a,`${f}-${e._name}`))}o=c||o}n=i.includes(ce.extname(o));let l;A.platform!=="win32"?n?(t.unshift(o),t=ii(A.execArgv).concat(t),l=mr.spawn(A.argv[0],t,{stdio:"inherit"})):l=mr.spawn(o,t,{stdio:"inherit"}):(this._checkForMissingExecutable(o,a,e._name),t.unshift(o),t=ii(A.execArgv).concat(t),l=mr.spawn(A.execPath,t,{stdio:"inherit"})),l.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(f=>{A.on(f,()=>{l.killed===!1&&l.exitCode===null&&l.kill(f)})});let u=this._exitCallback;l.on("close",c=>{c=c??1,u?u(new dr(c,"commander.executeSubCommandAsync","(close)")):A.exit(c)}),l.on("error",c=>{if(c.code==="ENOENT")this._checkForMissingExecutable(o,a,e._name);else if(c.code==="EACCES")throw new Error(`'${o}' not executable`);if(!u)A.exit(1);else{let f=new dr(1,"commander.executeSubCommandAsync","(error)");f.nestedError=c,u(f)}}),this.runningCommand=l}_dispatchSubcommand(e,t,n){let i=this._findCommand(e);i||this.help({error:!0}),i._prepareForParse();let s;return s=this._chainOrCallSubCommandHook(s,i,"preSubcommand"),s=this._chainOrCall(s,()=>{if(i._executableHandler)this._executeSubCommand(i,t.concat(n));else return i._parseCommand(t,n)}),s}_dispatchHelpCommand(e){e||this.help();let 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&&this.args[t]==null&&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(){let e=(n,i,s)=>{let o=i;if(i!==null&&n.parseArg){let a=`error: command-argument value '${i}' is invalid for argument '${n.name()}'.`;o=this._callParseArg(n,i,s,a)}return o};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((n,i)=>{let s=n.defaultValue;n.variadic?i<this.args.length?(s=this.args.slice(i),n.parseArg&&(s=s.reduce((o,a)=>e(n,a,o),n.defaultValue))):s===void 0&&(s=[]):i<this.args.length&&(s=this.args[i],n.parseArg&&(s=e(n,s,n.defaultValue))),t[i]=s}),this.processedArgs=t}_chainOrCall(e,t){return e&&e.then&&typeof e.then=="function"?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let n=e,i=[];return this._getCommandAndAncestors().reverse().filter(s=>s._lifeCycleHooks[t]!==void 0).forEach(s=>{s._lifeCycleHooks[t].forEach(o=>{i.push({hookedCommand:s,callback:o})})}),t==="postAction"&&i.reverse(),i.forEach(s=>{n=this._chainOrCall(n,()=>s.callback(s.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,t,n){let i=e;return this._lifeCycleHooks[n]!==void 0&&this._lifeCycleHooks[n].forEach(s=>{i=this._chainOrCall(i,()=>s(this,t))}),i}_parseCommand(e,t){let 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&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let i=()=>{n.unknown.length>0&&this.unknownOption(n.unknown[0])},s=`command:${this.name()}`;if(this._actionHandler){i(),this._processArguments();let o;return o=this._chainOrCallHooks(o,"preAction"),o=this._chainOrCall(o,()=>this._actionHandler(this.processedArgs)),this.parent&&(o=this._chainOrCall(o,()=>{this.parent.emit(s,e,t)})),o=this._chainOrCallHooks(o,"postAction"),o}if(this.parent&&this.parent.listenerCount(s))i(),this._processArguments(),this.parent.emit(s,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():(i(),this._processArguments())}else this.commands.length?(i(),this.help({error:!0})):(i(),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&&e.getOptionValue(t.attributeName())===void 0&&e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(n=>{let i=n.attributeName();return this.getOptionValue(i)===void 0?!1:this.getOptionValueSource(i)!=="default"});e.filter(n=>n.conflictsWith.length>0).forEach(n=>{let i=e.find(s=>n.conflictsWith.includes(s.attributeName()));i&&this._conflictingOption(n,i)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],n=[],i=t,s=e.slice();function o(l){return l.length>1&&l[0]==="-"}let a=null;for(;s.length;){let l=s.shift();if(l==="--"){i===n&&i.push(l),i.push(...s);break}if(a&&!o(l)){this.emit(`option:${a.name()}`,l);continue}if(a=null,o(l)){let u=this._findOption(l);if(u){if(u.required){let c=s.shift();c===void 0&&this.optionMissingArgument(u),this.emit(`option:${u.name()}`,c)}else if(u.optional){let c=null;s.length>0&&!o(s[0])&&(c=s.shift()),this.emit(`option:${u.name()}`,c)}else this.emit(`option:${u.name()}`);a=u.variadic?u:null;continue}}if(l.length>2&&l[0]==="-"&&l[1]!=="-"){let u=this._findOption(`-${l[1]}`);if(u){u.required||u.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${u.name()}`,l.slice(2)):(this.emit(`option:${u.name()}`),s.unshift(`-${l.slice(2)}`));continue}}if(/^--[^=]+=/.test(l)){let u=l.indexOf("="),c=this._findOption(l.slice(0,u));if(c&&(c.required||c.optional)){this.emit(`option:${c.name()}`,l.slice(u+1));continue}}if(o(l)&&(i=n),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&n.length===0){if(this._findCommand(l)){t.push(l),s.length>0&&n.push(...s);break}else if(this._getHelpCommand()&&l===this._getHelpCommand().name()){t.push(l),s.length>0&&t.push(...s);break}else if(this._defaultCommandName){n.push(l),s.length>0&&n.push(...s);break}}if(this._passThroughOptions){i.push(l),s.length>0&&i.push(...s);break}i.push(l)}return{operands:t,unknown:n}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let n=0;n<t;n++){let i=this.options[n].attributeName();e[i]=i===this._versionOptionName?this._version:this[i]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}
|
|
24
24
|
`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
25
25
|
`):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
|
|
26
|
-
`),this.outputHelp({error:!0}));let n=t||{},i=n.exitCode||1,s=n.code||"commander.error";this._exit(i,s,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in A.env){let t=e.attributeName();(this.getOptionValue(t)===void 0||["default","config","env"].includes(this.getOptionValueSource(t)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,A.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new
|
|
27
|
-
`),this._exit(0,"commander.version",e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&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");let n=this.parent?._findCommand(e);if(n){let i=[n.name()].concat(n.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${i}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(t=>this.alias(t)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let t=this.registeredArguments.map(n=>
|
|
26
|
+
`),this.outputHelp({error:!0}));let n=t||{},i=n.exitCode||1,s=n.code||"commander.error";this._exit(i,s,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in A.env){let t=e.attributeName();(this.getOptionValue(t)===void 0||["default","config","env"].includes(this.getOptionValueSource(t)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,A.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new Ic(this.options),t=n=>this.getOptionValue(n)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(n));this.options.filter(n=>n.implied!==void 0&&t(n.attributeName())&&e.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach(n=>{Object.keys(n.implied).filter(i=>!t(i)).forEach(i=>{this.setOptionValueWithSource(i,n.implied[i],"implied")})})}missingArgument(e){let t=`error: missing required argument '${e}'`;this.error(t,{code:"commander.missingArgument"})}optionMissingArgument(e){let t=`error: option '${e.flags}' argument missing`;this.error(t,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let t=`error: required option '${e.flags}' not specified`;this.error(t,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,t){let n=o=>{let a=o.attributeName(),l=this.getOptionValue(a),u=this.options.find(f=>f.negate&&a===f.attributeName()),c=this.options.find(f=>!f.negate&&a===f.attributeName());return u&&(u.presetArg===void 0&&l===!1||u.presetArg!==void 0&&l===u.presetArg)?u:c||o},i=o=>{let a=n(o),l=a.attributeName();return this.getOptionValueSource(l)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},s=`error: ${i(e)} cannot be used with ${i(t)}`;this.error(s,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let i=[],s=this;do{let o=s.createHelp().visibleOptions(s).filter(a=>a.long).map(a=>a.long);i=i.concat(o),s=s.parent}while(s&&!s._enablePositionalOptions);t=ni(e,i)}let n=`error: unknown option '${e}'${t}`;this.error(n,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,n=t===1?"":"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(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let i=[];this.createHelp().visibleCommands(this).forEach(s=>{i.push(s.name()),s.alias()&&i.push(s.alias())}),t=ni(e,i)}let n=`error: unknown command '${e}'${t}`;this.error(n,{code:"commander.unknownCommand"})}version(e,t,n){if(e===void 0)return this._version;this._version=e,t=t||"-V, --version",n=n||"output the version number";let i=this.createOption(t,n);return this._versionOptionName=i.attributeName(),this._registerOption(i),this.on("option:"+i.name(),()=>{this._outputConfiguration.writeOut(`${e}
|
|
27
|
+
`),this._exit(0,"commander.version",e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&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");let n=this.parent?._findCommand(e);if(n){let i=[n.name()].concat(n.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${i}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(t=>this.alias(t)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let t=this.registeredArguments.map(n=>kc(n));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?t:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}nameFromFilename(e){return this._name=ce.basename(e,ce.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp(),n=this._getOutputContext(e);t.prepareContext({error:n.error,helpWidth:n.helpWidth,outputHasColors:n.hasColors});let i=t.formatHelp(this,t);return n.hasColors?i:this._outputConfiguration.stripColor(i)}_getOutputContext(e){e=e||{};let t=!!e.error,n,i,s;return t?(n=a=>this._outputConfiguration.writeErr(a),i=this._outputConfiguration.getErrHasColors(),s=this._outputConfiguration.getErrHelpWidth()):(n=a=>this._outputConfiguration.writeOut(a),i=this._outputConfiguration.getOutHasColors(),s=this._outputConfiguration.getOutHelpWidth()),{error:t,write:a=>(i||(a=this._outputConfiguration.stripColor(a)),n(a)),hasColors:i,helpWidth:s}}outputHelp(e){let t;typeof e=="function"&&(t=e,e=void 0);let n=this._getOutputContext(e),i={error:n.error,write:n.write,command:this};this._getCommandAndAncestors().reverse().forEach(o=>o.emit("beforeAllHelp",i)),this.emit("beforeHelp",i);let s=this.helpInformation({error:n.error});if(t&&(s=t(s),typeof s!="string"&&!Buffer.isBuffer(s)))throw new Error("outputHelp callback must return a string or a Buffer");n.write(s),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",i),this._getCommandAndAncestors().forEach(o=>o.emit("afterAllHelp",i))}helpOption(e,t){return typeof e=="boolean"?(e?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(e=e??"-h, --help",t=t??"display help for command",this._helpOption=this.createOption(e,t),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this}help(e){this.outputHelp(e);let t=Number(A.exitCode??0);t===0&&e&&typeof e!="function"&&e.error&&(t=1),this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){let n=["beforeAll","before","after","afterAll"];if(!n.includes(e))throw new Error(`Unexpected value for position to addHelpText.
|
|
28
28
|
Expecting one of '${n.join("', '")}'`);let i=`${e}Help`;return this.on(i,s=>{let o;typeof t=="function"?o=t({error:s.error,command:s.command}):o=t,o&&s.write(`${o}
|
|
29
|
-
`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(i=>t.is(i))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function ii(r){return r.map(e=>{if(!e.startsWith("--inspect"))return e;let t,n="127.0.0.1",i="9229",s;return(s=e.match(/^(--inspect(-brk)?)$/))!==null?t=s[1]:(s=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=s[1],/^\d+$/.test(s[3])?i=s[3]:n=s[3]):(s=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=s[1],n=s[3],i=s[4]),t&&i!=="0"?`${t}=${n}:${parseInt(i)+1}`:e})}function
|
|
29
|
+
`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(i=>t.is(i))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function ii(r){return r.map(e=>{if(!e.startsWith("--inspect"))return e;let t,n="127.0.0.1",i="9229",s;return(s=e.match(/^(--inspect(-brk)?)$/))!==null?t=s[1]:(s=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=s[1],/^\d+$/.test(s[3])?i=s[3]:n=s[3]):(s=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=s[1],n=s[3],i=s[4]),t&&i!=="0"?`${t}=${n}:${parseInt(i)+1}`:e})}function hr(){if(A.env.NO_COLOR||A.env.FORCE_COLOR==="0"||A.env.FORCE_COLOR==="false")return!1;if(A.env.FORCE_COLOR||A.env.CLICOLOR_FORCE!==void 0)return!0}gr.Command=pr;gr.useColor=hr});var lt=h(Q=>{var{Argument:oi}=ot(),{Command:yr}=si(),{CommanderError:Nc,InvalidArgumentError:ai}=De(),{Help:Mc}=ar(),{Option:li}=fr();Q.program=new yr;Q.createCommand=r=>new yr(r);Q.createOption=(r,e)=>new li(r,e);Q.createArgument=(r,e)=>new oi(r,e);Q.Command=yr;Q.Option=li;Q.Argument=oi;Q.Help=Mc;Q.CommanderError=Nc;Q.InvalidArgumentError=ai;Q.InvalidOptionArgumentError=ai});var Pi=h((dE,ki)=>{function Si(r){return Array.isArray(r)?r:[r]}var Tr="",xi=" ",Cr="\\",ou=/^\s+$/,au=/(?:[^\\]|^)\\$/,lu=/^\\!/,cu=/^\\#/,uu=/\r?\n/g,fu=/^\.*\/|^\.+$/,Ar="/",Ci="node-ignore";typeof Symbol<"u"&&(Ci=Symbol.for("node-ignore"));var _i=Ci,mu=(r,e,t)=>Object.defineProperty(r,e,{value:t}),du=/([0-z])-([0-z])/g,Ai=()=>!1,pu=r=>r.replace(du,(e,t,n)=>t.charCodeAt(0)<=n.charCodeAt(0)?e:Tr),hu=r=>{let{length:e}=r;return r.slice(0,e-e%2)},gu=[[/^\uFEFF/,()=>Tr],[/((?:\\\\)*?)(\\?\s+)$/,(r,e,t)=>e+(t.indexOf("\\")===0?xi:Tr)],[/(\\+?)\s/g,(r,e)=>{let{length:t}=e;return e.slice(0,t-t%2)+xi}],[/[\\$.|*+(){^]/g,r=>`\\${r}`],[/(?!\\)\?/g,()=>"[^/]"],[/^\//,()=>"^"],[/\//g,()=>"\\/"],[/^\^*\\\*\\\*\\\//,()=>"^(?:.*\\/)?"],[/^(?=[^^])/,function(){return/\/(?!$)/.test(this)?"^":"(?:^|\\/)"}],[/\\\/\\\*\\\*(?=\\\/|$)/g,(r,e,t)=>e+6<t.length?"(?:\\/[^\\/]+)*":"\\/.+"],[/(^|[^\\]+)(\\\*)+(?=.+)/g,(r,e,t)=>{let n=t.replace(/\\\*/g,"[^\\/]*");return e+n}],[/\\\\\\(?=[$.|*+(){^])/g,()=>Cr],[/\\\\/g,()=>Cr],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(r,e,t,n,i)=>e===Cr?`\\[${t}${hu(n)}${i}`:i==="]"&&n.length%2===0?`[${pu(t)}${n}]`:"[]"],[/(?:[^*])$/,r=>/\/$/.test(r)?`${r}$`:`${r}(?=$|\\/$)`],[/(\^|\\\/)?\\\*$/,(r,e)=>`${e?`${e}[^/]+`:"[^/]*"}(?=$|\\/$)`]],Oi=Object.create(null),yu=(r,e)=>{let t=Oi[r];return t||(t=gu.reduce((n,[i,s])=>n.replace(i,s.bind(r)),r),Oi[r]=t),e?new RegExp(t,"i"):new RegExp(t)},Lr=r=>typeof r=="string",Eu=r=>r&&Lr(r)&&!ou.test(r)&&!au.test(r)&&r.indexOf("#")!==0,wu=r=>r.split(uu),kr=class{constructor(e,t,n,i){this.origin=e,this.pattern=t,this.negative=n,this.regex=i}},bu=(r,e)=>{let t=r,n=!1;r.indexOf("!")===0&&(n=!0,r=r.substr(1)),r=r.replace(lu,"!").replace(cu,"#");let i=yu(r,e);return new kr(t,r,n,i)},Ru=(r,e)=>{throw new e(r)},ue=(r,e,t)=>Lr(r)?r?ue.isNotRelative(r)?t(`path should be a \`path.relative()\`d string, but got "${e}"`,RangeError):!0:t("path must not be empty",TypeError):t(`path must be a string, but got \`${e}\``,TypeError),Ti=r=>fu.test(r);ue.isNotRelative=Ti;ue.convert=r=>r;var Pr=class{constructor({ignorecase:e=!0,ignoreCase:t=e,allowRelativePaths:n=!1}={}){mu(this,_i,!0),this._rules=[],this._ignoreCase=t,this._allowRelativePaths=n,this._initCache()}_initCache(){this._ignoreCache=Object.create(null),this._testCache=Object.create(null)}_addPattern(e){if(e&&e[_i]){this._rules=this._rules.concat(e._rules),this._added=!0;return}if(Eu(e)){let t=bu(e,this._ignoreCase);this._added=!0,this._rules.push(t)}}add(e){return this._added=!1,Si(Lr(e)?wu(e):e).forEach(this._addPattern,this),this._added&&this._initCache(),this}addPattern(e){return this.add(e)}_testOne(e,t){let n=!1,i=!1;return this._rules.forEach(s=>{let{negative:o}=s;if(i===o&&n!==i||o&&!n&&!i&&!t)return;s.regex.test(e)&&(n=!o,i=o)}),{ignored:n,unignored:i}}_test(e,t,n,i){let s=e&&ue.convert(e);return ue(s,e,this._allowRelativePaths?Ai:Ru),this._t(s,t,n,i)}_t(e,t,n,i){if(e in t)return t[e];if(i||(i=e.split(Ar)),i.pop(),!i.length)return t[e]=this._testOne(e,n);let s=this._t(i.join(Ar)+Ar,t,n,i);return t[e]=s.ignored?s:this._testOne(e,n)}ignores(e){return this._test(e,this._ignoreCache,!1).ignored}createFilter(){return e=>!this.ignores(e)}filter(e){return Si(e).filter(this.createFilter())}test(e){return this._test(e,this._testCache,!0)}},gt=r=>new Pr(r),$u=r=>ue(r&&ue.convert(r),r,Ai);gt.isPathValid=$u;gt.default=gt;ki.exports=gt;if(typeof process<"u"&&(process.env&&process.env.IGNORE_TEST_WIN32||process.platform==="win32")){let r=t=>/^\\\\\?\\/.test(t)||/["<>|\u0000-\u001F]+/u.test(t)?t:t.replace(/\\/g,"/");ue.convert=r;let e=/^[a-z]:\//i;ue.isNotRelative=t=>e.test(t)||Ti(t)}});var Oe=h((Ur,Hi)=>{var Et=require("buffer"),oe=Et.Buffer;function Gi(r,e){for(var t in r)e[t]=r[t]}oe.from&&oe.alloc&&oe.allocUnsafe&&oe.allocUnsafeSlow?Hi.exports=Et:(Gi(Et,Ur),Ur.Buffer=Re);function Re(r,e,t){return oe(r,e,t)}Re.prototype=Object.create(oe.prototype);Gi(oe,Re);Re.from=function(r,e,t){if(typeof r=="number")throw new TypeError("Argument must not be a number");return oe(r,e,t)};Re.alloc=function(r,e,t){if(typeof r!="number")throw new TypeError("Argument must be a number");var n=oe(r);return e!==void 0?typeof t=="string"?n.fill(e,t):n.fill(e):n.fill(0),n};Re.allocUnsafe=function(r){if(typeof r!="number")throw new TypeError("Argument must be a number");return oe(r)};Re.allocUnsafeSlow=function(r){if(typeof r!="number")throw new TypeError("Argument must be a number");return Et.SlowBuffer(r)}});var jr=h((kE,Wi)=>{var wt=Oe().Buffer,Mu=require("stream"),Du=require("util");function bt(r){if(this.buffer=null,this.writable=!0,this.readable=!0,!r)return this.buffer=wt.alloc(0),this;if(typeof r.pipe=="function")return this.buffer=wt.alloc(0),r.pipe(this),this;if(r.length||typeof r=="object")return this.buffer=r,this.writable=!1,process.nextTick(function(){this.emit("end",r),this.readable=!1,this.emit("close")}.bind(this)),this;throw new TypeError("Unexpected data type ("+typeof r+")")}Du.inherits(bt,Mu);bt.prototype.write=function(e){this.buffer=wt.concat([this.buffer,wt.from(e)]),this.emit("data",e)};bt.prototype.end=function(e){e&&this.write(e),this.emit("end",e),this.emit("close"),this.writable=!1,this.readable=!1};Wi.exports=bt});var Yi=h((PE,Bi)=>{"use strict";function qr(r){var e=(r/8|0)+(r%8===0?0:1);return e}var Fu={ES256:qr(256),ES384:qr(384),ES512:qr(521)};function Uu(r){var e=Fu[r];if(e)return e;throw new Error('Unknown algorithm "'+r+'"')}Bi.exports=Uu});var es=h((LE,Zi)=>{"use strict";var Rt=Oe().Buffer,zi=Yi(),$t=128,Ji=0,ju=32,qu=16,Vu=2,Ki=qu|ju|Ji<<6,vt=Vu|Ji<<6;function Gu(r){return r.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function Qi(r){if(Rt.isBuffer(r))return r;if(typeof r=="string")return Rt.from(r,"base64");throw new TypeError("ECDSA signature must be a Base64 string or a Buffer")}function Hu(r,e){r=Qi(r);var t=zi(e),n=t+1,i=r.length,s=0;if(r[s++]!==Ki)throw new Error('Could not find expected "seq"');var o=r[s++];if(o===($t|1)&&(o=r[s++]),i-s<o)throw new Error('"seq" specified length of "'+o+'", only "'+(i-s)+'" remaining');if(r[s++]!==vt)throw new Error('Could not find expected "int" for "r"');var a=r[s++];if(i-s-2<a)throw new Error('"r" specified length of "'+a+'", only "'+(i-s-2)+'" available');if(n<a)throw new Error('"r" specified length of "'+a+'", max of "'+n+'" is acceptable');var l=s;if(s+=a,r[s++]!==vt)throw new Error('Could not find expected "int" for "s"');var u=r[s++];if(i-s!==u)throw new Error('"s" specified length of "'+u+'", expected "'+(i-s)+'"');if(n<u)throw new Error('"s" specified length of "'+u+'", max of "'+n+'" is acceptable');var c=s;if(s+=u,s!==i)throw new Error('Expected to consume entire buffer, but "'+(i-s)+'" bytes remain');var f=t-a,d=t-u,p=Rt.allocUnsafe(f+a+d+u);for(s=0;s<f;++s)p[s]=0;r.copy(p,s,l+Math.max(-f,0),l+a),s=t;for(var g=s;s<g+d;++s)p[s]=0;return r.copy(p,s,c+Math.max(-d,0),c+u),p=p.toString("base64"),p=Gu(p),p}function Xi(r,e,t){for(var n=0;e+n<t&&r[e+n]===0;)++n;var i=r[e+n]>=$t;return i&&--n,n}function Wu(r,e){r=Qi(r);var t=zi(e),n=r.length;if(n!==t*2)throw new TypeError('"'+e+'" signatures must be "'+t*2+'" bytes, saw "'+n+'"');var i=Xi(r,0,t),s=Xi(r,t,r.length),o=t-i,a=t-s,l=2+o+1+1+a,u=l<$t,c=Rt.allocUnsafe((u?2:3)+l),f=0;return c[f++]=Ki,u?c[f++]=l:(c[f++]=$t|1,c[f++]=l&255),c[f++]=vt,c[f++]=o,i<0?(c[f++]=0,f+=r.copy(c,f,0,t)):f+=r.copy(c,f,i,t),c[f++]=vt,c[f++]=a,s<0?(c[f++]=0,r.copy(c,f,t)):r.copy(c,f,t+s),c}Zi.exports={derToJose:Hu,joseToDer:Wu}});var rs=h((IE,ts)=>{"use strict";var qe=require("buffer").Buffer,Vr=require("buffer").SlowBuffer;ts.exports=St;function St(r,e){if(!qe.isBuffer(r)||!qe.isBuffer(e)||r.length!==e.length)return!1;for(var t=0,n=0;n<r.length;n++)t|=r[n]^e[n];return t===0}St.install=function(){qe.prototype.equal=Vr.prototype.equal=function(e){return St(this,e)}};var Bu=qe.prototype.equal,Yu=Vr.prototype.equal;St.restore=function(){qe.prototype.equal=Bu,Vr.prototype.equal=Yu}});var Br=h((NE,fs)=>{var Ae=Oe().Buffer,Z=require("crypto"),is=es(),ns=require("util"),Xu=`"%s" is not a valid algorithm.
|
|
30
30
|
Supported algorithms are:
|
|
31
|
-
"HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".`,Ve="secret must be a string or buffer",Ae="key must be a string or a buffer",Yu="key must be a string, a buffer or an object",Hr=typeof Z.createPublicKey=="function";Hr&&(Ae+=" or a KeyObject",Ve+="or a KeyObject");function ss(r){if(!Te.isBuffer(r)&&typeof r!="string"&&(!Hr||typeof r!="object"||typeof r.type!="string"||typeof r.asymmetricKeyType!="string"||typeof r.export!="function"))throw ne(Ae)}function os(r){if(!Te.isBuffer(r)&&typeof r!="string"&&typeof r!="object")throw ne(Yu)}function Xu(r){if(!Te.isBuffer(r)){if(typeof r=="string")return r;if(!Hr||typeof r!="object"||r.type!=="secret"||typeof r.export!="function")throw ne(Ve)}}function Wr(r){return r.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function as(r){r=r.toString();var e=4-r.length%4;if(e!==4)for(var t=0;t<e;++t)r+="=";return r.replace(/\-/g,"+").replace(/_/g,"/")}function ne(r){var e=[].slice.call(arguments,1),t=ns.format.bind(ns,r).apply(null,e);return new TypeError(t)}function zu(r){return Te.isBuffer(r)||typeof r=="string"}function Ge(r){return zu(r)||(r=JSON.stringify(r)),r}function ls(r){return function(t,n){Xu(n),t=Ge(t);var i=Z.createHmac("sha"+r,n),s=(i.update(t),i.digest("base64"));return Wr(s)}}var Gr,Ju="timingSafeEqual"in Z?function(e,t){return e.byteLength!==t.byteLength?!1:Z.timingSafeEqual(e,t)}:function(e,t){return Gr||(Gr=rs()),Gr(e,t)};function Ku(r){return function(t,n,i){var s=ls(r)(t,i);return Ju(Te.from(n),Te.from(s))}}function cs(r){return function(t,n){os(n),t=Ge(t);var i=Z.createSign("RSA-SHA"+r),s=(i.update(t),i.sign(n,"base64"));return Wr(s)}}function us(r){return function(t,n,i){ss(i),t=Ge(t),n=as(n);var s=Z.createVerify("RSA-SHA"+r);return s.update(t),s.verify(i,n,"base64")}}function Qu(r){return function(t,n){os(n),t=Ge(t);var i=Z.createSign("RSA-SHA"+r),s=(i.update(t),i.sign({key:n,padding:Z.constants.RSA_PKCS1_PSS_PADDING,saltLength:Z.constants.RSA_PSS_SALTLEN_DIGEST},"base64"));return Wr(s)}}function Zu(r){return function(t,n,i){ss(i),t=Ge(t),n=as(n);var s=Z.createVerify("RSA-SHA"+r);return s.update(t),s.verify({key:i,padding:Z.constants.RSA_PKCS1_PSS_PADDING,saltLength:Z.constants.RSA_PSS_SALTLEN_DIGEST},n,"base64")}}function ef(r){var e=cs(r);return function(){var n=e.apply(null,arguments);return n=is.derToJose(n,"ES"+r),n}}function tf(r){var e=us(r);return function(n,i,s){i=is.joseToDer(i,"ES"+r).toString("base64");var o=e(n,i,s);return o}}function rf(){return function(){return""}}function nf(){return function(e,t){return t===""}}fs.exports=function(e){var t={hs:ls,rs:cs,ps:Qu,es:ef,none:rf},n={hs:Ku,rs:us,ps:Zu,es:tf,none:nf},i=e.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);if(!i)throw ne(Bu,e);var s=(i[1]||i[3]).toLowerCase(),o=i[2];return{sign:t[s](o),verify:n[s](o)}}});var Yr=p((LE,ms)=>{var sf=require("buffer").Buffer;ms.exports=function(e){return typeof e=="string"?e:typeof e=="number"||sf.isBuffer(e)?e.toString():JSON.stringify(e)}});var Es=p((IE,ys)=>{var of=Ce().Buffer,ds=jr(),af=Br(),lf=require("stream"),hs=Yr(),Xr=require("util");function ps(r,e){return of.from(r,e).toString("base64").replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function cf(r,e,t){t=t||"utf8";var n=ps(hs(r),"binary"),i=ps(hs(e),t);return Xr.format("%s.%s",n,i)}function gs(r){var e=r.header,t=r.payload,n=r.secret||r.privateKey,i=r.encoding,s=af(e.alg),o=cf(e,t,i),a=s.sign(o,n);return Xr.format("%s.%s",o,a)}function xt(r){var e=r.secret;if(e=e??r.privateKey,e=e??r.key,/^hs/i.test(r.header.alg)===!0&&e==null)throw new TypeError("secret must be a string or buffer or a KeyObject");var t=new ds(e);this.readable=!0,this.header=r.header,this.encoding=r.encoding,this.secret=this.privateKey=this.key=t,this.payload=new ds(r.payload),this.secret.once("close",function(){!this.payload.writable&&this.readable&&this.sign()}.bind(this)),this.payload.once("close",function(){!this.secret.writable&&this.readable&&this.sign()}.bind(this))}Xr.inherits(xt,lf);xt.prototype.sign=function(){try{var e=gs({header:this.header,payload:this.payload.buffer,secret:this.secret.buffer,encoding:this.encoding});return this.emit("done",e),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(t){this.readable=!1,this.emit("error",t),this.emit("close")}};xt.sign=gs;ys.exports=xt});var Cs=p((NE,Os)=>{var bs=Ce().Buffer,ws=jr(),uf=Br(),ff=require("stream"),Rs=Yr(),mf=require("util"),df=/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;function hf(r){return Object.prototype.toString.call(r)==="[object Object]"}function pf(r){if(hf(r))return r;try{return JSON.parse(r)}catch{return}}function $s(r){var e=r.split(".",1)[0];return pf(bs.from(e,"base64").toString("binary"))}function gf(r){return r.split(".",2).join(".")}function vs(r){return r.split(".")[2]}function yf(r,e){e=e||"utf8";var t=r.split(".")[1];return bs.from(t,"base64").toString(e)}function Ss(r){return df.test(r)&&!!$s(r)}function xs(r,e,t){if(!e){var n=new Error("Missing algorithm parameter for jws.verify");throw n.code="MISSING_ALGORITHM",n}r=Rs(r);var i=vs(r),s=gf(r),o=uf(e);return o.verify(s,i,t)}function _s(r,e){if(e=e||{},r=Rs(r),!Ss(r))return null;var t=$s(r);if(!t)return null;var n=yf(r);return(t.typ==="JWT"||e.json)&&(n=JSON.parse(n,e.encoding)),{header:t,payload:n,signature:vs(r)}}function ke(r){r=r||{};var e=r.secret;if(e=e??r.publicKey,e=e??r.key,/^hs/i.test(r.algorithm)===!0&&e==null)throw new TypeError("secret must be a string or buffer or a KeyObject");var t=new ws(e);this.readable=!0,this.algorithm=r.algorithm,this.encoding=r.encoding,this.secret=this.publicKey=this.key=t,this.signature=new ws(r.signature),this.secret.once("close",function(){!this.signature.writable&&this.readable&&this.verify()}.bind(this)),this.signature.once("close",function(){!this.secret.writable&&this.readable&&this.verify()}.bind(this))}mf.inherits(ke,ff);ke.prototype.verify=function(){try{var e=xs(this.signature.buffer,this.algorithm,this.key.buffer),t=_s(this.signature.buffer,this.encoding);return this.emit("done",e,t),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(n){this.readable=!1,this.emit("error",n),this.emit("close")}};ke.decode=_s;ke.isValid=Ss;ke.verify=xs;Os.exports=ke});var Ot=p(pe=>{var As=Es(),_t=Cs(),Ef=["HS256","HS384","HS512","RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512"];pe.ALGORITHMS=Ef;pe.sign=As.sign;pe.verify=_t.verify;pe.decode=_t.decode;pe.isValid=_t.isValid;pe.createSign=function(e){return new As(e)};pe.createVerify=function(e){return new _t(e)}});var zr=p((DE,Ts)=>{var wf=Ot();Ts.exports=function(r,e){e=e||{};var t=wf.decode(r,e);if(!t)return null;var n=t.payload;if(typeof n=="string")try{var i=JSON.parse(n);i!==null&&typeof i=="object"&&(n=i)}catch{}return e.complete===!0?{header:t.header,payload:n,signature:t.signature}:n}});var He=p((FE,ks)=>{var Ct=function(r,e){Error.call(this,r),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor),this.name="JsonWebTokenError",this.message=r,e&&(this.inner=e)};Ct.prototype=Object.create(Error.prototype);Ct.prototype.constructor=Ct;ks.exports=Ct});var Jr=p((UE,Ls)=>{var Ps=He(),At=function(r,e){Ps.call(this,r),this.name="NotBeforeError",this.date=e};At.prototype=Object.create(Ps.prototype);At.prototype.constructor=At;Ls.exports=At});var Kr=p((jE,Ns)=>{var Is=He(),Tt=function(r,e){Is.call(this,r),this.name="TokenExpiredError",this.expiredAt=e};Tt.prototype=Object.create(Is.prototype);Tt.prototype.constructor=Tt;Ns.exports=Tt});var Ds=p((qE,Ms)=>{var Pe=1e3,Le=Pe*60,Ie=Le*60,ve=Ie*24,bf=ve*7,Rf=ve*365.25;Ms.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return $f(r);if(t==="number"&&isFinite(r))return e.long?Sf(r):vf(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function $f(r){if(r=String(r),!(r.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(e){var t=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return t*Rf;case"weeks":case"week":case"w":return t*bf;case"days":case"day":case"d":return t*ve;case"hours":case"hour":case"hrs":case"hr":case"h":return t*Ie;case"minutes":case"minute":case"mins":case"min":case"m":return t*Le;case"seconds":case"second":case"secs":case"sec":case"s":return t*Pe;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function vf(r){var e=Math.abs(r);return e>=ve?Math.round(r/ve)+"d":e>=Ie?Math.round(r/Ie)+"h":e>=Le?Math.round(r/Le)+"m":e>=Pe?Math.round(r/Pe)+"s":r+"ms"}function Sf(r){var e=Math.abs(r);return e>=ve?kt(r,e,ve,"day"):e>=Ie?kt(r,e,Ie,"hour"):e>=Le?kt(r,e,Le,"minute"):e>=Pe?kt(r,e,Pe,"second"):r+" ms"}function kt(r,e,t,n){var i=e>=t*1.5;return Math.round(r/t)+" "+n+(i?"s":"")}});var Qr=p((VE,Fs)=>{var xf=Ds();Fs.exports=function(r,e){var t=e||Math.floor(Date.now()/1e3);if(typeof r=="string"){var n=xf(r);return typeof n>"u"?void 0:Math.floor(t+n/1e3)}else return typeof r=="number"?t+r:void 0}});var We=p((GE,Us)=>{"use strict";var _f="2.0.0",Of=Number.MAX_SAFE_INTEGER||9007199254740991,Cf=16,Af=250,Tf=["major","premajor","minor","preminor","patch","prepatch","prerelease"];Us.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:Cf,MAX_SAFE_BUILD_LENGTH:Af,MAX_SAFE_INTEGER:Of,RELEASE_TYPES:Tf,SEMVER_SPEC_VERSION:_f,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var Be=p((HE,js)=>{"use strict";var kf=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...r)=>console.error("SEMVER",...r):()=>{};js.exports=kf});var Ne=p((ae,qs)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:Zr,MAX_SAFE_BUILD_LENGTH:Pf,MAX_LENGTH:Lf}=We(),If=Be();ae=qs.exports={};var Nf=ae.re=[],Mf=ae.safeRe=[],w=ae.src=[],Df=ae.safeSrc=[],b=ae.t={},Ff=0,en="[a-zA-Z0-9-]",Uf=[["\\s",1],["\\d",Lf],[en,Pf]],jf=r=>{for(let[e,t]of Uf)r=r.split(`${e}*`).join(`${e}{0,${t}}`).split(`${e}+`).join(`${e}{1,${t}}`);return r},v=(r,e,t)=>{let n=jf(e),i=Ff++;If(r,i,e),b[r]=i,w[i]=e,Df[i]=n,Nf[i]=new RegExp(e,t?"g":void 0),Mf[i]=new RegExp(n,t?"g":void 0)};v("NUMERICIDENTIFIER","0|[1-9]\\d*");v("NUMERICIDENTIFIERLOOSE","\\d+");v("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${en}*`);v("MAINVERSION",`(${w[b.NUMERICIDENTIFIER]})\\.(${w[b.NUMERICIDENTIFIER]})\\.(${w[b.NUMERICIDENTIFIER]})`);v("MAINVERSIONLOOSE",`(${w[b.NUMERICIDENTIFIERLOOSE]})\\.(${w[b.NUMERICIDENTIFIERLOOSE]})\\.(${w[b.NUMERICIDENTIFIERLOOSE]})`);v("PRERELEASEIDENTIFIER",`(?:${w[b.NONNUMERICIDENTIFIER]}|${w[b.NUMERICIDENTIFIER]})`);v("PRERELEASEIDENTIFIERLOOSE",`(?:${w[b.NONNUMERICIDENTIFIER]}|${w[b.NUMERICIDENTIFIERLOOSE]})`);v("PRERELEASE",`(?:-(${w[b.PRERELEASEIDENTIFIER]}(?:\\.${w[b.PRERELEASEIDENTIFIER]})*))`);v("PRERELEASELOOSE",`(?:-?(${w[b.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${w[b.PRERELEASEIDENTIFIERLOOSE]})*))`);v("BUILDIDENTIFIER",`${en}+`);v("BUILD",`(?:\\+(${w[b.BUILDIDENTIFIER]}(?:\\.${w[b.BUILDIDENTIFIER]})*))`);v("FULLPLAIN",`v?${w[b.MAINVERSION]}${w[b.PRERELEASE]}?${w[b.BUILD]}?`);v("FULL",`^${w[b.FULLPLAIN]}$`);v("LOOSEPLAIN",`[v=\\s]*${w[b.MAINVERSIONLOOSE]}${w[b.PRERELEASELOOSE]}?${w[b.BUILD]}?`);v("LOOSE",`^${w[b.LOOSEPLAIN]}$`);v("GTLT","((?:<|>)?=?)");v("XRANGEIDENTIFIERLOOSE",`${w[b.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);v("XRANGEIDENTIFIER",`${w[b.NUMERICIDENTIFIER]}|x|X|\\*`);v("XRANGEPLAIN",`[v=\\s]*(${w[b.XRANGEIDENTIFIER]})(?:\\.(${w[b.XRANGEIDENTIFIER]})(?:\\.(${w[b.XRANGEIDENTIFIER]})(?:${w[b.PRERELEASE]})?${w[b.BUILD]}?)?)?`);v("XRANGEPLAINLOOSE",`[v=\\s]*(${w[b.XRANGEIDENTIFIERLOOSE]})(?:\\.(${w[b.XRANGEIDENTIFIERLOOSE]})(?:\\.(${w[b.XRANGEIDENTIFIERLOOSE]})(?:${w[b.PRERELEASELOOSE]})?${w[b.BUILD]}?)?)?`);v("XRANGE",`^${w[b.GTLT]}\\s*${w[b.XRANGEPLAIN]}$`);v("XRANGELOOSE",`^${w[b.GTLT]}\\s*${w[b.XRANGEPLAINLOOSE]}$`);v("COERCEPLAIN",`(^|[^\\d])(\\d{1,${Zr}})(?:\\.(\\d{1,${Zr}}))?(?:\\.(\\d{1,${Zr}}))?`);v("COERCE",`${w[b.COERCEPLAIN]}(?:$|[^\\d])`);v("COERCEFULL",w[b.COERCEPLAIN]+`(?:${w[b.PRERELEASE]})?(?:${w[b.BUILD]})?(?:$|[^\\d])`);v("COERCERTL",w[b.COERCE],!0);v("COERCERTLFULL",w[b.COERCEFULL],!0);v("LONETILDE","(?:~>?)");v("TILDETRIM",`(\\s*)${w[b.LONETILDE]}\\s+`,!0);ae.tildeTrimReplace="$1~";v("TILDE",`^${w[b.LONETILDE]}${w[b.XRANGEPLAIN]}$`);v("TILDELOOSE",`^${w[b.LONETILDE]}${w[b.XRANGEPLAINLOOSE]}$`);v("LONECARET","(?:\\^)");v("CARETTRIM",`(\\s*)${w[b.LONECARET]}\\s+`,!0);ae.caretTrimReplace="$1^";v("CARET",`^${w[b.LONECARET]}${w[b.XRANGEPLAIN]}$`);v("CARETLOOSE",`^${w[b.LONECARET]}${w[b.XRANGEPLAINLOOSE]}$`);v("COMPARATORLOOSE",`^${w[b.GTLT]}\\s*(${w[b.LOOSEPLAIN]})$|^$`);v("COMPARATOR",`^${w[b.GTLT]}\\s*(${w[b.FULLPLAIN]})$|^$`);v("COMPARATORTRIM",`(\\s*)${w[b.GTLT]}\\s*(${w[b.LOOSEPLAIN]}|${w[b.XRANGEPLAIN]})`,!0);ae.comparatorTrimReplace="$1$2$3";v("HYPHENRANGE",`^\\s*(${w[b.XRANGEPLAIN]})\\s+-\\s+(${w[b.XRANGEPLAIN]})\\s*$`);v("HYPHENRANGELOOSE",`^\\s*(${w[b.XRANGEPLAINLOOSE]})\\s+-\\s+(${w[b.XRANGEPLAINLOOSE]})\\s*$`);v("STAR","(<|>)?=?\\s*\\*");v("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");v("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var Pt=p((WE,Vs)=>{"use strict";var qf=Object.freeze({loose:!0}),Vf=Object.freeze({}),Gf=r=>r?typeof r!="object"?qf:r:Vf;Vs.exports=Gf});var tn=p((BE,Ws)=>{"use strict";var Gs=/^[0-9]+$/,Hs=(r,e)=>{if(typeof r=="number"&&typeof e=="number")return r===e?0:r<e?-1:1;let t=Gs.test(r),n=Gs.test(e);return t&&n&&(r=+r,e=+e),r===e?0:t&&!n?-1:n&&!t?1:r<e?-1:1},Hf=(r,e)=>Hs(e,r);Ws.exports={compareIdentifiers:Hs,rcompareIdentifiers:Hf}});var H=p((YE,Ys)=>{"use strict";var Lt=Be(),{MAX_LENGTH:Bs,MAX_SAFE_INTEGER:It}=We(),{safeRe:Nt,t:Mt}=Ne(),Wf=Pt(),{compareIdentifiers:rn}=tn(),nn=class r{constructor(e,t){if(t=Wf(t),e instanceof r){if(e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease)return e;e=e.version}else if(typeof e!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof e}".`);if(e.length>Bs)throw new TypeError(`version is longer than ${Bs} characters`);Lt("SemVer",e,t),this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease;let n=e.trim().match(t.loose?Nt[Mt.LOOSE]:Nt[Mt.FULL]);if(!n)throw new TypeError(`Invalid Version: ${e}`);if(this.raw=e,this.major=+n[1],this.minor=+n[2],this.patch=+n[3],this.major>It||this.major<0)throw new TypeError("Invalid major version");if(this.minor>It||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>It||this.patch<0)throw new TypeError("Invalid patch version");n[4]?this.prerelease=n[4].split(".").map(i=>{if(/^[0-9]+$/.test(i)){let s=+i;if(s>=0&&s<It)return s}return i}):this.prerelease=[],this.build=n[5]?n[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(e){if(Lt("SemVer.compare",this.version,this.options,e),!(e instanceof r)){if(typeof e=="string"&&e===this.version)return 0;e=new r(e,this.options)}return e.version===this.version?0:this.compareMain(e)||this.comparePre(e)}compareMain(e){return e instanceof r||(e=new r(e,this.options)),this.major<e.major?-1:this.major>e.major?1:this.minor<e.minor?-1:this.minor>e.minor?1:this.patch<e.patch?-1:this.patch>e.patch?1:0}comparePre(e){if(e instanceof r||(e=new r(e,this.options)),this.prerelease.length&&!e.prerelease.length)return-1;if(!this.prerelease.length&&e.prerelease.length)return 1;if(!this.prerelease.length&&!e.prerelease.length)return 0;let t=0;do{let n=this.prerelease[t],i=e.prerelease[t];if(Lt("prerelease compare",t,n,i),n===void 0&&i===void 0)return 0;if(i===void 0)return 1;if(n===void 0)return-1;if(n===i)continue;return rn(n,i)}while(++t)}compareBuild(e){e instanceof r||(e=new r(e,this.options));let t=0;do{let n=this.build[t],i=e.build[t];if(Lt("build compare",t,n,i),n===void 0&&i===void 0)return 0;if(i===void 0)return 1;if(n===void 0)return-1;if(n===i)continue;return rn(n,i)}while(++t)}inc(e,t,n){if(e.startsWith("pre")){if(!t&&n===!1)throw new Error("invalid increment argument: identifier is empty");if(t){let i=`-${t}`.match(this.options.loose?Nt[Mt.PRERELEASELOOSE]:Nt[Mt.PRERELEASE]);if(!i||i[1]!==t)throw new Error(`invalid identifier: ${t}`)}}switch(e){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",t,n);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",t,n);break;case"prepatch":this.prerelease.length=0,this.inc("patch",t,n),this.inc("pre",t,n);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",t,n),this.inc("pre",t,n);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{let i=Number(n)?1:0;if(this.prerelease.length===0)this.prerelease=[i];else{let s=this.prerelease.length;for(;--s>=0;)typeof this.prerelease[s]=="number"&&(this.prerelease[s]++,s=-2);if(s===-1){if(t===this.prerelease.join(".")&&n===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(i)}}if(t){let s=[t,i];n===!1&&(s=[t]),rn(this.prerelease[0],t)===0?isNaN(this.prerelease[1])&&(this.prerelease=s):this.prerelease=s}break}default:throw new Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};Ys.exports=nn});var Se=p((XE,zs)=>{"use strict";var Xs=H(),Bf=(r,e,t=!1)=>{if(r instanceof Xs)return r;try{return new Xs(r,e)}catch(n){if(!t)return null;throw n}};zs.exports=Bf});var Ks=p((zE,Js)=>{"use strict";var Yf=Se(),Xf=(r,e)=>{let t=Yf(r,e);return t?t.version:null};Js.exports=Xf});var Zs=p((JE,Qs)=>{"use strict";var zf=Se(),Jf=(r,e)=>{let t=zf(r.trim().replace(/^[=v]+/,""),e);return t?t.version:null};Qs.exports=Jf});var ro=p((KE,to)=>{"use strict";var eo=H(),Kf=(r,e,t,n,i)=>{typeof t=="string"&&(i=n,n=t,t=void 0);try{return new eo(r instanceof eo?r.version:r,t).inc(e,n,i).version}catch{return null}};to.exports=Kf});var so=p((QE,io)=>{"use strict";var no=Se(),Qf=(r,e)=>{let t=no(r,null,!0),n=no(e,null,!0),i=t.compare(n);if(i===0)return null;let s=i>0,o=s?t:n,a=s?n:t,l=!!o.prerelease.length;if(!!a.prerelease.length&&!l){if(!a.patch&&!a.minor)return"major";if(a.compareMain(o)===0)return a.minor&&!a.patch?"minor":"patch"}let c=l?"pre":"";return t.major!==n.major?c+"major":t.minor!==n.minor?c+"minor":t.patch!==n.patch?c+"patch":"prerelease"};io.exports=Qf});var ao=p((ZE,oo)=>{"use strict";var Zf=H(),em=(r,e)=>new Zf(r,e).major;oo.exports=em});var co=p((ew,lo)=>{"use strict";var tm=H(),rm=(r,e)=>new tm(r,e).minor;lo.exports=rm});var fo=p((tw,uo)=>{"use strict";var nm=H(),im=(r,e)=>new nm(r,e).patch;uo.exports=im});var ho=p((rw,mo)=>{"use strict";var sm=Se(),om=(r,e)=>{let t=sm(r,e);return t&&t.prerelease.length?t.prerelease:null};mo.exports=om});var ee=p((nw,go)=>{"use strict";var po=H(),am=(r,e,t)=>new po(r,t).compare(new po(e,t));go.exports=am});var Eo=p((iw,yo)=>{"use strict";var lm=ee(),cm=(r,e,t)=>lm(e,r,t);yo.exports=cm});var bo=p((sw,wo)=>{"use strict";var um=ee(),fm=(r,e)=>um(r,e,!0);wo.exports=fm});var Dt=p((ow,$o)=>{"use strict";var Ro=H(),mm=(r,e,t)=>{let n=new Ro(r,t),i=new Ro(e,t);return n.compare(i)||n.compareBuild(i)};$o.exports=mm});var So=p((aw,vo)=>{"use strict";var dm=Dt(),hm=(r,e)=>r.sort((t,n)=>dm(t,n,e));vo.exports=hm});var _o=p((lw,xo)=>{"use strict";var pm=Dt(),gm=(r,e)=>r.sort((t,n)=>pm(n,t,e));xo.exports=gm});var Ye=p((cw,Oo)=>{"use strict";var ym=ee(),Em=(r,e,t)=>ym(r,e,t)>0;Oo.exports=Em});var Ft=p((uw,Co)=>{"use strict";var wm=ee(),bm=(r,e,t)=>wm(r,e,t)<0;Co.exports=bm});var sn=p((fw,Ao)=>{"use strict";var Rm=ee(),$m=(r,e,t)=>Rm(r,e,t)===0;Ao.exports=$m});var on=p((mw,To)=>{"use strict";var vm=ee(),Sm=(r,e,t)=>vm(r,e,t)!==0;To.exports=Sm});var Ut=p((dw,ko)=>{"use strict";var xm=ee(),_m=(r,e,t)=>xm(r,e,t)>=0;ko.exports=_m});var jt=p((hw,Po)=>{"use strict";var Om=ee(),Cm=(r,e,t)=>Om(r,e,t)<=0;Po.exports=Cm});var an=p((pw,Lo)=>{"use strict";var Am=sn(),Tm=on(),km=Ye(),Pm=Ut(),Lm=Ft(),Im=jt(),Nm=(r,e,t,n)=>{switch(e){case"===":return typeof r=="object"&&(r=r.version),typeof t=="object"&&(t=t.version),r===t;case"!==":return typeof r=="object"&&(r=r.version),typeof t=="object"&&(t=t.version),r!==t;case"":case"=":case"==":return Am(r,t,n);case"!=":return Tm(r,t,n);case">":return km(r,t,n);case">=":return Pm(r,t,n);case"<":return Lm(r,t,n);case"<=":return Im(r,t,n);default:throw new TypeError(`Invalid operator: ${e}`)}};Lo.exports=Nm});var No=p((gw,Io)=>{"use strict";var Mm=H(),Dm=Se(),{safeRe:qt,t:Vt}=Ne(),Fm=(r,e)=>{if(r instanceof Mm)return r;if(typeof r=="number"&&(r=String(r)),typeof r!="string")return null;e=e||{};let t=null;if(!e.rtl)t=r.match(e.includePrerelease?qt[Vt.COERCEFULL]:qt[Vt.COERCE]);else{let l=e.includePrerelease?qt[Vt.COERCERTLFULL]:qt[Vt.COERCERTL],u;for(;(u=l.exec(r))&&(!t||t.index+t[0].length!==r.length);)(!t||u.index+u[0].length!==t.index+t[0].length)&&(t=u),l.lastIndex=u.index+u[1].length+u[2].length;l.lastIndex=-1}if(t===null)return null;let n=t[2],i=t[3]||"0",s=t[4]||"0",o=e.includePrerelease&&t[5]?`-${t[5]}`:"",a=e.includePrerelease&&t[6]?`+${t[6]}`:"";return Dm(`${n}.${i}.${s}${o}${a}`,e)};Io.exports=Fm});var Do=p((yw,Mo)=>{"use strict";var ln=class{constructor(){this.max=1e3,this.map=new Map}get(e){let t=this.map.get(e);if(t!==void 0)return this.map.delete(e),this.map.set(e,t),t}delete(e){return this.map.delete(e)}set(e,t){if(!this.delete(e)&&t!==void 0){if(this.map.size>=this.max){let i=this.map.keys().next().value;this.delete(i)}this.map.set(e,t)}return this}};Mo.exports=ln});var te=p((Ew,qo)=>{"use strict";var Um=/\s+/g,cn=class r{constructor(e,t){if(t=qm(t),e instanceof r)return e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease?e:new r(e.raw,t);if(e instanceof un)return this.raw=e.value,this.set=[[e]],this.formatted=void 0,this;if(this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease,this.raw=e.trim().replace(Um," "),this.set=this.raw.split("||").map(n=>this.parseRange(n.trim())).filter(n=>n.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let n=this.set[0];if(this.set=this.set.filter(i=>!Uo(i[0])),this.set.length===0)this.set=[n];else if(this.set.length>1){for(let i of this.set)if(i.length===1&&Xm(i[0])){this.set=[i];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let e=0;e<this.set.length;e++){e>0&&(this.formatted+="||");let t=this.set[e];for(let n=0;n<t.length;n++)n>0&&(this.formatted+=" "),this.formatted+=t[n].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(e){let n=((this.options.includePrerelease&&Bm)|(this.options.loose&&Ym))+":"+e,i=Fo.get(n);if(i)return i;let s=this.options.loose,o=s?Y[W.HYPHENRANGELOOSE]:Y[W.HYPHENRANGE];e=e.replace(o,id(this.options.includePrerelease)),I("hyphen replace",e),e=e.replace(Y[W.COMPARATORTRIM],Gm),I("comparator trim",e),e=e.replace(Y[W.TILDETRIM],Hm),I("tilde trim",e),e=e.replace(Y[W.CARETTRIM],Wm),I("caret trim",e);let a=e.split(" ").map(f=>zm(f,this.options)).join(" ").split(/\s+/).map(f=>nd(f,this.options));s&&(a=a.filter(f=>(I("loose invalid filter",f,this.options),!!f.match(Y[W.COMPARATORLOOSE])))),I("range list",a);let l=new Map,u=a.map(f=>new un(f,this.options));for(let f of u){if(Uo(f))return[f];l.set(f.value,f)}l.size>1&&l.has("")&&l.delete("");let c=[...l.values()];return Fo.set(n,c),c}intersects(e,t){if(!(e instanceof r))throw new TypeError("a Range is required");return this.set.some(n=>jo(n,t)&&e.set.some(i=>jo(i,t)&&n.every(s=>i.every(o=>s.intersects(o,t)))))}test(e){if(!e)return!1;if(typeof e=="string")try{e=new Vm(e,this.options)}catch{return!1}for(let t=0;t<this.set.length;t++)if(sd(this.set[t],e,this.options))return!0;return!1}};qo.exports=cn;var jm=Do(),Fo=new jm,qm=Pt(),un=Xe(),I=Be(),Vm=H(),{safeRe:Y,t:W,comparatorTrimReplace:Gm,tildeTrimReplace:Hm,caretTrimReplace:Wm}=Ne(),{FLAG_INCLUDE_PRERELEASE:Bm,FLAG_LOOSE:Ym}=We(),Uo=r=>r.value==="<0.0.0-0",Xm=r=>r.value==="",jo=(r,e)=>{let t=!0,n=r.slice(),i=n.pop();for(;t&&n.length;)t=n.every(s=>i.intersects(s,e)),i=n.pop();return t},zm=(r,e)=>(r=r.replace(Y[W.BUILD],""),I("comp",r,e),r=Qm(r,e),I("caret",r),r=Jm(r,e),I("tildes",r),r=ed(r,e),I("xrange",r),r=rd(r,e),I("stars",r),r),X=r=>!r||r.toLowerCase()==="x"||r==="*",Jm=(r,e)=>r.trim().split(/\s+/).map(t=>Km(t,e)).join(" "),Km=(r,e)=>{let t=e.loose?Y[W.TILDELOOSE]:Y[W.TILDE];return r.replace(t,(n,i,s,o,a)=>{I("tilde",r,n,i,s,o,a);let l;return X(i)?l="":X(s)?l=`>=${i}.0.0 <${+i+1}.0.0-0`:X(o)?l=`>=${i}.${s}.0 <${i}.${+s+1}.0-0`:a?(I("replaceTilde pr",a),l=`>=${i}.${s}.${o}-${a} <${i}.${+s+1}.0-0`):l=`>=${i}.${s}.${o} <${i}.${+s+1}.0-0`,I("tilde return",l),l})},Qm=(r,e)=>r.trim().split(/\s+/).map(t=>Zm(t,e)).join(" "),Zm=(r,e)=>{I("caret",r,e);let t=e.loose?Y[W.CARETLOOSE]:Y[W.CARET],n=e.includePrerelease?"-0":"";return r.replace(t,(i,s,o,a,l)=>{I("caret",r,i,s,o,a,l);let u;return X(s)?u="":X(o)?u=`>=${s}.0.0${n} <${+s+1}.0.0-0`:X(a)?s==="0"?u=`>=${s}.${o}.0${n} <${s}.${+o+1}.0-0`:u=`>=${s}.${o}.0${n} <${+s+1}.0.0-0`:l?(I("replaceCaret pr",l),s==="0"?o==="0"?u=`>=${s}.${o}.${a}-${l} <${s}.${o}.${+a+1}-0`:u=`>=${s}.${o}.${a}-${l} <${s}.${+o+1}.0-0`:u=`>=${s}.${o}.${a}-${l} <${+s+1}.0.0-0`):(I("no pr"),s==="0"?o==="0"?u=`>=${s}.${o}.${a}${n} <${s}.${o}.${+a+1}-0`:u=`>=${s}.${o}.${a}${n} <${s}.${+o+1}.0-0`:u=`>=${s}.${o}.${a} <${+s+1}.0.0-0`),I("caret return",u),u})},ed=(r,e)=>(I("replaceXRanges",r,e),r.split(/\s+/).map(t=>td(t,e)).join(" ")),td=(r,e)=>{r=r.trim();let t=e.loose?Y[W.XRANGELOOSE]:Y[W.XRANGE];return r.replace(t,(n,i,s,o,a,l)=>{I("xRange",r,n,i,s,o,a,l);let u=X(s),c=u||X(o),f=c||X(a),d=f;return i==="="&&d&&(i=""),l=e.includePrerelease?"-0":"",u?i===">"||i==="<"?n="<0.0.0-0":n="*":i&&d?(c&&(o=0),a=0,i===">"?(i=">=",c?(s=+s+1,o=0,a=0):(o=+o+1,a=0)):i==="<="&&(i="<",c?s=+s+1:o=+o+1),i==="<"&&(l="-0"),n=`${i+s}.${o}.${a}${l}`):c?n=`>=${s}.0.0${l} <${+s+1}.0.0-0`:f&&(n=`>=${s}.${o}.0${l} <${s}.${+o+1}.0-0`),I("xRange return",n),n})},rd=(r,e)=>(I("replaceStars",r,e),r.trim().replace(Y[W.STAR],"")),nd=(r,e)=>(I("replaceGTE0",r,e),r.trim().replace(Y[e.includePrerelease?W.GTE0PRE:W.GTE0],"")),id=r=>(e,t,n,i,s,o,a,l,u,c,f,d)=>(X(n)?t="":X(i)?t=`>=${n}.0.0${r?"-0":""}`:X(s)?t=`>=${n}.${i}.0${r?"-0":""}`:o?t=`>=${t}`:t=`>=${t}${r?"-0":""}`,X(u)?l="":X(c)?l=`<${+u+1}.0.0-0`:X(f)?l=`<${u}.${+c+1}.0-0`:d?l=`<=${u}.${c}.${f}-${d}`:r?l=`<${u}.${c}.${+f+1}-0`:l=`<=${l}`,`${t} ${l}`.trim()),sd=(r,e,t)=>{for(let n=0;n<r.length;n++)if(!r[n].test(e))return!1;if(e.prerelease.length&&!t.includePrerelease){for(let n=0;n<r.length;n++)if(I(r[n].semver),r[n].semver!==un.ANY&&r[n].semver.prerelease.length>0){let i=r[n].semver;if(i.major===e.major&&i.minor===e.minor&&i.patch===e.patch)return!0}return!1}return!0}});var Xe=p((ww,Yo)=>{"use strict";var ze=Symbol("SemVer ANY"),dn=class r{static get ANY(){return ze}constructor(e,t){if(t=Vo(t),e instanceof r){if(e.loose===!!t.loose)return e;e=e.value}e=e.trim().split(/\s+/).join(" "),mn("comparator",e,t),this.options=t,this.loose=!!t.loose,this.parse(e),this.semver===ze?this.value="":this.value=this.operator+this.semver.version,mn("comp",this)}parse(e){let t=this.options.loose?Go[Ho.COMPARATORLOOSE]:Go[Ho.COMPARATOR],n=e.match(t);if(!n)throw new TypeError(`Invalid comparator: ${e}`);this.operator=n[1]!==void 0?n[1]:"",this.operator==="="&&(this.operator=""),n[2]?this.semver=new Wo(n[2],this.options.loose):this.semver=ze}toString(){return this.value}test(e){if(mn("Comparator.test",e,this.options.loose),this.semver===ze||e===ze)return!0;if(typeof e=="string")try{e=new Wo(e,this.options)}catch{return!1}return fn(e,this.operator,this.semver,this.options)}intersects(e,t){if(!(e instanceof r))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new Bo(e.value,t).test(this.value):e.operator===""?e.value===""?!0:new Bo(this.value,t).test(e.semver):(t=Vo(t),t.includePrerelease&&(this.value==="<0.0.0-0"||e.value==="<0.0.0-0")||!t.includePrerelease&&(this.value.startsWith("<0.0.0")||e.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&e.operator.startsWith(">")||this.operator.startsWith("<")&&e.operator.startsWith("<")||this.semver.version===e.semver.version&&this.operator.includes("=")&&e.operator.includes("=")||fn(this.semver,"<",e.semver,t)&&this.operator.startsWith(">")&&e.operator.startsWith("<")||fn(this.semver,">",e.semver,t)&&this.operator.startsWith("<")&&e.operator.startsWith(">")))}};Yo.exports=dn;var Vo=Pt(),{safeRe:Go,t:Ho}=Ne(),fn=an(),mn=Be(),Wo=H(),Bo=te()});var Je=p((bw,Xo)=>{"use strict";var od=te(),ad=(r,e,t)=>{try{e=new od(e,t)}catch{return!1}return e.test(r)};Xo.exports=ad});var Jo=p((Rw,zo)=>{"use strict";var ld=te(),cd=(r,e)=>new ld(r,e).set.map(t=>t.map(n=>n.value).join(" ").trim().split(" "));zo.exports=cd});var Qo=p(($w,Ko)=>{"use strict";var ud=H(),fd=te(),md=(r,e,t)=>{let n=null,i=null,s=null;try{s=new fd(e,t)}catch{return null}return r.forEach(o=>{s.test(o)&&(!n||i.compare(o)===-1)&&(n=o,i=new ud(n,t))}),n};Ko.exports=md});var ea=p((vw,Zo)=>{"use strict";var dd=H(),hd=te(),pd=(r,e,t)=>{let n=null,i=null,s=null;try{s=new hd(e,t)}catch{return null}return r.forEach(o=>{s.test(o)&&(!n||i.compare(o)===1)&&(n=o,i=new dd(n,t))}),n};Zo.exports=pd});var na=p((Sw,ra)=>{"use strict";var hn=H(),gd=te(),ta=Ye(),yd=(r,e)=>{r=new gd(r,e);let t=new hn("0.0.0");if(r.test(t)||(t=new hn("0.0.0-0"),r.test(t)))return t;t=null;for(let n=0;n<r.set.length;++n){let i=r.set[n],s=null;i.forEach(o=>{let a=new hn(o.semver.version);switch(o.operator){case">":a.prerelease.length===0?a.patch++:a.prerelease.push(0),a.raw=a.format();case"":case">=":(!s||ta(a,s))&&(s=a);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${o.operator}`)}}),s&&(!t||ta(t,s))&&(t=s)}return t&&r.test(t)?t:null};ra.exports=yd});var sa=p((xw,ia)=>{"use strict";var Ed=te(),wd=(r,e)=>{try{return new Ed(r,e).range||"*"}catch{return null}};ia.exports=wd});var Gt=p((_w,ca)=>{"use strict";var bd=H(),la=Xe(),{ANY:Rd}=la,$d=te(),vd=Je(),oa=Ye(),aa=Ft(),Sd=jt(),xd=Ut(),_d=(r,e,t,n)=>{r=new bd(r,n),e=new $d(e,n);let i,s,o,a,l;switch(t){case">":i=oa,s=Sd,o=aa,a=">",l=">=";break;case"<":i=aa,s=xd,o=oa,a="<",l="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(vd(r,e,n))return!1;for(let u=0;u<e.set.length;++u){let c=e.set[u],f=null,d=null;if(c.forEach(h=>{h.semver===Rd&&(h=new la(">=0.0.0")),f=f||h,d=d||h,i(h.semver,f.semver,n)?f=h:o(h.semver,d.semver,n)&&(d=h)}),f.operator===a||f.operator===l||(!d.operator||d.operator===a)&&s(r,d.semver))return!1;if(d.operator===l&&o(r,d.semver))return!1}return!0};ca.exports=_d});var fa=p((Ow,ua)=>{"use strict";var Od=Gt(),Cd=(r,e,t)=>Od(r,e,">",t);ua.exports=Cd});var da=p((Cw,ma)=>{"use strict";var Ad=Gt(),Td=(r,e,t)=>Ad(r,e,"<",t);ma.exports=Td});var ga=p((Aw,pa)=>{"use strict";var ha=te(),kd=(r,e,t)=>(r=new ha(r,t),e=new ha(e,t),r.intersects(e,t));pa.exports=kd});var Ea=p((Tw,ya)=>{"use strict";var Pd=Je(),Ld=ee();ya.exports=(r,e,t)=>{let n=[],i=null,s=null,o=r.sort((c,f)=>Ld(c,f,t));for(let c of o)Pd(c,e,t)?(s=c,i||(i=c)):(s&&n.push([i,s]),s=null,i=null);i&&n.push([i,null]);let a=[];for(let[c,f]of n)c===f?a.push(c):!f&&c===o[0]?a.push("*"):f?c===o[0]?a.push(`<=${f}`):a.push(`${c} - ${f}`):a.push(`>=${c}`);let l=a.join(" || "),u=typeof e.raw=="string"?e.raw:String(e);return l.length<u.length?l:e}});var Sa=p((kw,va)=>{"use strict";var wa=te(),gn=Xe(),{ANY:pn}=gn,Ke=Je(),yn=ee(),Id=(r,e,t={})=>{if(r===e)return!0;r=new wa(r,t),e=new wa(e,t);let n=!1;e:for(let i of r.set){for(let s of e.set){let o=Md(i,s,t);if(n=n||o!==null,o)continue e}if(n)return!1}return!0},Nd=[new gn(">=0.0.0-0")],ba=[new gn(">=0.0.0")],Md=(r,e,t)=>{if(r===e)return!0;if(r.length===1&&r[0].semver===pn){if(e.length===1&&e[0].semver===pn)return!0;t.includePrerelease?r=Nd:r=ba}if(e.length===1&&e[0].semver===pn){if(t.includePrerelease)return!0;e=ba}let n=new Set,i,s;for(let h of r)h.operator===">"||h.operator===">="?i=Ra(i,h,t):h.operator==="<"||h.operator==="<="?s=$a(s,h,t):n.add(h.semver);if(n.size>1)return null;let o;if(i&&s){if(o=yn(i.semver,s.semver,t),o>0)return null;if(o===0&&(i.operator!==">="||s.operator!=="<="))return null}for(let h of n){if(i&&!Ke(h,String(i),t)||s&&!Ke(h,String(s),t))return null;for(let y of e)if(!Ke(h,String(y),t))return!1;return!0}let a,l,u,c,f=s&&!t.includePrerelease&&s.semver.prerelease.length?s.semver:!1,d=i&&!t.includePrerelease&&i.semver.prerelease.length?i.semver:!1;f&&f.prerelease.length===1&&s.operator==="<"&&f.prerelease[0]===0&&(f=!1);for(let h of e){if(c=c||h.operator===">"||h.operator===">=",u=u||h.operator==="<"||h.operator==="<=",i){if(d&&h.semver.prerelease&&h.semver.prerelease.length&&h.semver.major===d.major&&h.semver.minor===d.minor&&h.semver.patch===d.patch&&(d=!1),h.operator===">"||h.operator===">="){if(a=Ra(i,h,t),a===h&&a!==i)return!1}else if(i.operator===">="&&!Ke(i.semver,String(h),t))return!1}if(s){if(f&&h.semver.prerelease&&h.semver.prerelease.length&&h.semver.major===f.major&&h.semver.minor===f.minor&&h.semver.patch===f.patch&&(f=!1),h.operator==="<"||h.operator==="<="){if(l=$a(s,h,t),l===h&&l!==s)return!1}else if(s.operator==="<="&&!Ke(s.semver,String(h),t))return!1}if(!h.operator&&(s||i)&&o!==0)return!1}return!(i&&u&&!s&&o!==0||s&&c&&!i&&o!==0||d||f)},Ra=(r,e,t)=>{if(!r)return e;let n=yn(r.semver,e.semver,t);return n>0?r:n<0||e.operator===">"&&r.operator===">="?e:r},$a=(r,e,t)=>{if(!r)return e;let n=yn(r.semver,e.semver,t);return n<0?r:n>0||e.operator==="<"&&r.operator==="<="?e:r};va.exports=Id});var Ht=p((Pw,Oa)=>{"use strict";var En=Ne(),xa=We(),Dd=H(),_a=tn(),Fd=Se(),Ud=Ks(),jd=Zs(),qd=ro(),Vd=so(),Gd=ao(),Hd=co(),Wd=fo(),Bd=ho(),Yd=ee(),Xd=Eo(),zd=bo(),Jd=Dt(),Kd=So(),Qd=_o(),Zd=Ye(),eh=Ft(),th=sn(),rh=on(),nh=Ut(),ih=jt(),sh=an(),oh=No(),ah=Xe(),lh=te(),ch=Je(),uh=Jo(),fh=Qo(),mh=ea(),dh=na(),hh=sa(),ph=Gt(),gh=fa(),yh=da(),Eh=ga(),wh=Ea(),bh=Sa();Oa.exports={parse:Fd,valid:Ud,clean:jd,inc:qd,diff:Vd,major:Gd,minor:Hd,patch:Wd,prerelease:Bd,compare:Yd,rcompare:Xd,compareLoose:zd,compareBuild:Jd,sort:Kd,rsort:Qd,gt:Zd,lt:eh,eq:th,neq:rh,gte:nh,lte:ih,cmp:sh,coerce:oh,Comparator:ah,Range:lh,satisfies:ch,toComparators:uh,maxSatisfying:fh,minSatisfying:mh,minVersion:dh,validRange:hh,outside:ph,gtr:gh,ltr:yh,intersects:Eh,simplifyRange:wh,subset:bh,SemVer:Dd,re:En.re,src:En.src,tokens:En.t,SEMVER_SPEC_VERSION:xa.SEMVER_SPEC_VERSION,RELEASE_TYPES:xa.RELEASE_TYPES,compareIdentifiers:_a.compareIdentifiers,rcompareIdentifiers:_a.rcompareIdentifiers}});var Aa=p((Lw,Ca)=>{var Rh=Ht();Ca.exports=Rh.satisfies(process.version,">=15.7.0")});var ka=p((Iw,Ta)=>{var $h=Ht();Ta.exports=$h.satisfies(process.version,">=16.9.0")});var wn=p((Nw,Pa)=>{var vh=Aa(),Sh=ka(),xh={ec:["ES256","ES384","ES512"],rsa:["RS256","PS256","RS384","PS384","RS512","PS512"],"rsa-pss":["PS256","PS384","PS512"]},_h={ES256:"prime256v1",ES384:"secp384r1",ES512:"secp521r1"};Pa.exports=function(r,e){if(!r||!e)return;let t=e.asymmetricKeyType;if(!t)return;let n=xh[t];if(!n)throw new Error(`Unknown key type "${t}".`);if(!n.includes(r))throw new Error(`"alg" parameter for "${t}" key type must be one of: ${n.join(", ")}.`);if(vh)switch(t){case"ec":let i=e.asymmetricKeyDetails.namedCurve,s=_h[r];if(i!==s)throw new Error(`"alg" parameter "${r}" requires curve "${s}".`);break;case"rsa-pss":if(Sh){let o=parseInt(r.slice(-3),10),{hashAlgorithm:a,mgf1HashAlgorithm:l,saltLength:u}=e.asymmetricKeyDetails;if(a!==`sha${o}`||l!==a)throw new Error(`Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" ${r}.`);if(u!==void 0&&u>o>>3)throw new Error(`Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of "alg" ${r}.`)}break}}});var bn=p((Mw,La)=>{var Oh=Ht();La.exports=Oh.satisfies(process.version,"^6.12.0 || >=8.0.0")});var Ma=p((Dw,Na)=>{var k=He(),Ch=Jr(),Ia=Kr(),Ah=zr(),Th=Qr(),kh=wn(),Ph=bn(),Lh=Ot(),{KeyObject:Ih,createSecretKey:Nh,createPublicKey:Mh}=require("crypto"),Rn=["RS256","RS384","RS512"],Dh=["ES256","ES384","ES512"],$n=["RS256","RS384","RS512"],Fh=["HS256","HS384","HS512"];Ph&&(Rn.splice(Rn.length,0,"PS256","PS384","PS512"),$n.splice($n.length,0,"PS256","PS384","PS512"));Na.exports=function(r,e,t,n){typeof t=="function"&&!n&&(n=t,t={}),t||(t={}),t=Object.assign({},t);let i;if(n?i=n:i=function(c,f){if(c)throw c;return f},t.clockTimestamp&&typeof t.clockTimestamp!="number")return i(new k("clockTimestamp must be a number"));if(t.nonce!==void 0&&(typeof t.nonce!="string"||t.nonce.trim()===""))return i(new k("nonce must be a non-empty string"));if(t.allowInvalidAsymmetricKeyTypes!==void 0&&typeof t.allowInvalidAsymmetricKeyTypes!="boolean")return i(new k("allowInvalidAsymmetricKeyTypes must be a boolean"));let s=t.clockTimestamp||Math.floor(Date.now()/1e3);if(!r)return i(new k("jwt must be provided"));if(typeof r!="string")return i(new k("jwt must be a string"));let o=r.split(".");if(o.length!==3)return i(new k("jwt malformed"));let a;try{a=Ah(r,{complete:!0})}catch(c){return i(c)}if(!a)return i(new k("invalid token"));let l=a.header,u;if(typeof e=="function"){if(!n)return i(new k("verify must be called asynchronous if secret or public key is provided as a callback"));u=e}else u=function(c,f){return f(null,e)};return u(l,function(c,f){if(c)return i(new k("error in secret or public key callback: "+c.message));let d=o[2].trim()!=="";if(!d&&f)return i(new k("jwt signature is required"));if(d&&!f)return i(new k("secret or public key must be provided"));if(!d&&!t.algorithms)return i(new k('please specify "none" in "algorithms" to verify unsigned tokens'));if(f!=null&&!(f instanceof Ih))try{f=Mh(f)}catch{try{f=Nh(typeof f=="string"?Buffer.from(f):f)}catch{return i(new k("secretOrPublicKey is not valid key material"))}}if(t.algorithms||(f.type==="secret"?t.algorithms=Fh:["rsa","rsa-pss"].includes(f.asymmetricKeyType)?t.algorithms=$n:f.asymmetricKeyType==="ec"?t.algorithms=Dh:t.algorithms=Rn),t.algorithms.indexOf(a.header.alg)===-1)return i(new k("invalid algorithm"));if(l.alg.startsWith("HS")&&f.type!=="secret")return i(new k(`secretOrPublicKey must be a symmetric key when using ${l.alg}`));if(/^(?:RS|PS|ES)/.test(l.alg)&&f.type!=="public")return i(new k(`secretOrPublicKey must be an asymmetric key when using ${l.alg}`));if(!t.allowInvalidAsymmetricKeyTypes)try{kh(l.alg,f)}catch(S){return i(S)}let h;try{h=Lh.verify(r,a.header.alg,f)}catch(S){return i(S)}if(!h)return i(new k("invalid signature"));let y=a.payload;if(typeof y.nbf<"u"&&!t.ignoreNotBefore){if(typeof y.nbf!="number")return i(new k("invalid nbf value"));if(y.nbf>s+(t.clockTolerance||0))return i(new Ch("jwt not active",new Date(y.nbf*1e3)))}if(typeof y.exp<"u"&&!t.ignoreExpiration){if(typeof y.exp!="number")return i(new k("invalid exp value"));if(s>=y.exp+(t.clockTolerance||0))return i(new Ia("jwt expired",new Date(y.exp*1e3)))}if(t.audience){let S=Array.isArray(t.audience)?t.audience:[t.audience];if(!(Array.isArray(y.aud)?y.aud:[y.aud]).some(function(R){return S.some(function($){return $ instanceof RegExp?$.test(R):$===R})}))return i(new k("jwt audience invalid. expected: "+S.join(" or ")))}if(t.issuer&&(typeof t.issuer=="string"&&y.iss!==t.issuer||Array.isArray(t.issuer)&&t.issuer.indexOf(y.iss)===-1))return i(new k("jwt issuer invalid. expected: "+t.issuer));if(t.subject&&y.sub!==t.subject)return i(new k("jwt subject invalid. expected: "+t.subject));if(t.jwtid&&y.jti!==t.jwtid)return i(new k("jwt jwtid invalid. expected: "+t.jwtid));if(t.nonce&&y.nonce!==t.nonce)return i(new k("jwt nonce invalid. expected: "+t.nonce));if(t.maxAge){if(typeof y.iat!="number")return i(new k("iat required when maxAge is specified"));let S=Th(t.maxAge,y.iat);if(typeof S>"u")return i(new k('"maxAge" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60'));if(s>=S+(t.clockTolerance||0))return i(new Ia("maxAge exceeded",new Date(S*1e3)))}if(t.complete===!0){let S=a.signature;return i(null,{header:l,payload:y,signature:S})}return i(null,y)})}});var Va=p((Fw,qa)=>{var Da=1/0,Ua=9007199254740991,Uh=17976931348623157e292,Fa=NaN,jh="[object Arguments]",qh="[object Function]",Vh="[object GeneratorFunction]",Gh="[object String]",Hh="[object Symbol]",Wh=/^\s+|\s+$/g,Bh=/^[-+]0x[0-9a-f]+$/i,Yh=/^0b[01]+$/i,Xh=/^0o[0-7]+$/i,zh=/^(?:0|[1-9]\d*)$/,Jh=parseInt;function Kh(r,e){for(var t=-1,n=r?r.length:0,i=Array(n);++t<n;)i[t]=e(r[t],t,r);return i}function Qh(r,e,t,n){for(var i=r.length,s=t+(n?1:-1);n?s--:++s<i;)if(e(r[s],s,r))return s;return-1}function Zh(r,e,t){if(e!==e)return Qh(r,ep,t);for(var n=t-1,i=r.length;++n<i;)if(r[n]===e)return n;return-1}function ep(r){return r!==r}function tp(r,e){for(var t=-1,n=Array(r);++t<r;)n[t]=e(t);return n}function rp(r,e){return Kh(e,function(t){return r[t]})}function np(r,e){return function(t){return r(e(t))}}var Wt=Object.prototype,Sn=Wt.hasOwnProperty,Bt=Wt.toString,ip=Wt.propertyIsEnumerable,sp=np(Object.keys,Object),op=Math.max;function ap(r,e){var t=ja(r)||mp(r)?tp(r.length,String):[],n=t.length,i=!!n;for(var s in r)(e||Sn.call(r,s))&&!(i&&(s=="length"||cp(s,n)))&&t.push(s);return t}function lp(r){if(!up(r))return sp(r);var e=[];for(var t in Object(r))Sn.call(r,t)&&t!="constructor"&&e.push(t);return e}function cp(r,e){return e=e??Ua,!!e&&(typeof r=="number"||zh.test(r))&&r>-1&&r%1==0&&r<e}function up(r){var e=r&&r.constructor,t=typeof e=="function"&&e.prototype||Wt;return r===t}function fp(r,e,t,n){r=xn(r)?r:$p(r),t=t&&!n?wp(t):0;var i=r.length;return t<0&&(t=op(i+t,0)),gp(r)?t<=i&&r.indexOf(e,t)>-1:!!i&&Zh(r,e,t)>-1}function mp(r){return dp(r)&&Sn.call(r,"callee")&&(!ip.call(r,"callee")||Bt.call(r)==jh)}var ja=Array.isArray;function xn(r){return r!=null&&pp(r.length)&&!hp(r)}function dp(r){return _n(r)&&xn(r)}function hp(r){var e=vn(r)?Bt.call(r):"";return e==qh||e==Vh}function pp(r){return typeof r=="number"&&r>-1&&r%1==0&&r<=Ua}function vn(r){var e=typeof r;return!!r&&(e=="object"||e=="function")}function _n(r){return!!r&&typeof r=="object"}function gp(r){return typeof r=="string"||!ja(r)&&_n(r)&&Bt.call(r)==Gh}function yp(r){return typeof r=="symbol"||_n(r)&&Bt.call(r)==Hh}function Ep(r){if(!r)return r===0?r:0;if(r=bp(r),r===Da||r===-Da){var e=r<0?-1:1;return e*Uh}return r===r?r:0}function wp(r){var e=Ep(r),t=e%1;return e===e?t?e-t:e:0}function bp(r){if(typeof r=="number")return r;if(yp(r))return Fa;if(vn(r)){var e=typeof r.valueOf=="function"?r.valueOf():r;r=vn(e)?e+"":e}if(typeof r!="string")return r===0?r:+r;r=r.replace(Wh,"");var t=Yh.test(r);return t||Xh.test(r)?Jh(r.slice(2),t?2:8):Bh.test(r)?Fa:+r}function Rp(r){return xn(r)?ap(r):lp(r)}function $p(r){return r?rp(r,Rp(r)):[]}qa.exports=fp});var Ha=p((Uw,Ga)=>{var vp="[object Boolean]",Sp=Object.prototype,xp=Sp.toString;function _p(r){return r===!0||r===!1||Op(r)&&xp.call(r)==vp}function Op(r){return!!r&&typeof r=="object"}Ga.exports=_p});var za=p((jw,Xa)=>{var Wa=1/0,Cp=17976931348623157e292,Ba=NaN,Ap="[object Symbol]",Tp=/^\s+|\s+$/g,kp=/^[-+]0x[0-9a-f]+$/i,Pp=/^0b[01]+$/i,Lp=/^0o[0-7]+$/i,Ip=parseInt,Np=Object.prototype,Mp=Np.toString;function Dp(r){return typeof r=="number"&&r==qp(r)}function Ya(r){var e=typeof r;return!!r&&(e=="object"||e=="function")}function Fp(r){return!!r&&typeof r=="object"}function Up(r){return typeof r=="symbol"||Fp(r)&&Mp.call(r)==Ap}function jp(r){if(!r)return r===0?r:0;if(r=Vp(r),r===Wa||r===-Wa){var e=r<0?-1:1;return e*Cp}return r===r?r:0}function qp(r){var e=jp(r),t=e%1;return e===e?t?e-t:e:0}function Vp(r){if(typeof r=="number")return r;if(Up(r))return Ba;if(Ya(r)){var e=typeof r.valueOf=="function"?r.valueOf():r;r=Ya(e)?e+"":e}if(typeof r!="string")return r===0?r:+r;r=r.replace(Tp,"");var t=Pp.test(r);return t||Lp.test(r)?Ip(r.slice(2),t?2:8):kp.test(r)?Ba:+r}Xa.exports=Dp});var Ka=p((qw,Ja)=>{var Gp="[object Number]",Hp=Object.prototype,Wp=Hp.toString;function Bp(r){return!!r&&typeof r=="object"}function Yp(r){return typeof r=="number"||Bp(r)&&Wp.call(r)==Gp}Ja.exports=Yp});var tl=p((Vw,el)=>{var Xp="[object Object]";function zp(r){var e=!1;if(r!=null&&typeof r.toString!="function")try{e=!!(r+"")}catch{}return e}function Jp(r,e){return function(t){return r(e(t))}}var Kp=Function.prototype,Qa=Object.prototype,Za=Kp.toString,Qp=Qa.hasOwnProperty,Zp=Za.call(Object),eg=Qa.toString,tg=Jp(Object.getPrototypeOf,Object);function rg(r){return!!r&&typeof r=="object"}function ng(r){if(!rg(r)||eg.call(r)!=Xp||zp(r))return!1;var e=tg(r);if(e===null)return!0;var t=Qp.call(e,"constructor")&&e.constructor;return typeof t=="function"&&t instanceof t&&Za.call(t)==Zp}el.exports=ng});var nl=p((Gw,rl)=>{var ig="[object String]",sg=Object.prototype,og=sg.toString,ag=Array.isArray;function lg(r){return!!r&&typeof r=="object"}function cg(r){return typeof r=="string"||!ag(r)&&lg(r)&&og.call(r)==ig}rl.exports=cg});var ll=p((Hw,al)=>{var ug="Expected a function",il=1/0,fg=17976931348623157e292,sl=NaN,mg="[object Symbol]",dg=/^\s+|\s+$/g,hg=/^[-+]0x[0-9a-f]+$/i,pg=/^0b[01]+$/i,gg=/^0o[0-7]+$/i,yg=parseInt,Eg=Object.prototype,wg=Eg.toString;function bg(r,e){var t;if(typeof e!="function")throw new TypeError(ug);return r=xg(r),function(){return--r>0&&(t=e.apply(this,arguments)),r<=1&&(e=void 0),t}}function Rg(r){return bg(2,r)}function ol(r){var e=typeof r;return!!r&&(e=="object"||e=="function")}function $g(r){return!!r&&typeof r=="object"}function vg(r){return typeof r=="symbol"||$g(r)&&wg.call(r)==mg}function Sg(r){if(!r)return r===0?r:0;if(r=_g(r),r===il||r===-il){var e=r<0?-1:1;return e*fg}return r===r?r:0}function xg(r){var e=Sg(r),t=e%1;return e===e?t?e-t:e:0}function _g(r){if(typeof r=="number")return r;if(vg(r))return sl;if(ol(r)){var e=typeof r.valueOf=="function"?r.valueOf():r;r=ol(e)?e+"":e}if(typeof r!="string")return r===0?r:+r;r=r.replace(dg,"");var t=pg.test(r);return t||gg.test(r)?yg(r.slice(2),t?2:8):hg.test(r)?sl:+r}al.exports=Rg});var yl=p((Ww,gl)=>{var cl=Qr(),Og=bn(),Cg=wn(),ul=Ot(),Ag=Va(),Yt=Ha(),fl=za(),On=Ka(),dl=tl(),ge=nl(),Tg=ll(),{KeyObject:kg,createSecretKey:Pg,createPrivateKey:Lg}=require("crypto"),hl=["RS256","RS384","RS512","ES256","ES384","ES512","HS256","HS384","HS512","none"];Og&&hl.splice(3,0,"PS256","PS384","PS512");var Ig={expiresIn:{isValid:function(r){return fl(r)||ge(r)&&r},message:'"expiresIn" should be a number of seconds or string representing a timespan'},notBefore:{isValid:function(r){return fl(r)||ge(r)&&r},message:'"notBefore" should be a number of seconds or string representing a timespan'},audience:{isValid:function(r){return ge(r)||Array.isArray(r)},message:'"audience" must be a string or array'},algorithm:{isValid:Ag.bind(null,hl),message:'"algorithm" must be a valid string enum value'},header:{isValid:dl,message:'"header" must be an object'},encoding:{isValid:ge,message:'"encoding" must be a string'},issuer:{isValid:ge,message:'"issuer" must be a string'},subject:{isValid:ge,message:'"subject" must be a string'},jwtid:{isValid:ge,message:'"jwtid" must be a string'},noTimestamp:{isValid:Yt,message:'"noTimestamp" must be a boolean'},keyid:{isValid:ge,message:'"keyid" must be a string'},mutatePayload:{isValid:Yt,message:'"mutatePayload" must be a boolean'},allowInsecureKeySizes:{isValid:Yt,message:'"allowInsecureKeySizes" must be a boolean'},allowInvalidAsymmetricKeyTypes:{isValid:Yt,message:'"allowInvalidAsymmetricKeyTypes" must be a boolean'}},Ng={iat:{isValid:On,message:'"iat" should be a number of seconds'},exp:{isValid:On,message:'"exp" should be a number of seconds'},nbf:{isValid:On,message:'"nbf" should be a number of seconds'}};function pl(r,e,t,n){if(!dl(t))throw new Error('Expected "'+n+'" to be a plain object.');Object.keys(t).forEach(function(i){let s=r[i];if(!s){if(!e)throw new Error('"'+i+'" is not allowed in "'+n+'"');return}if(!s.isValid(t[i]))throw new Error(s.message)})}function Mg(r){return pl(Ig,!1,r,"options")}function Dg(r){return pl(Ng,!0,r,"payload")}var ml={audience:"aud",issuer:"iss",subject:"sub",jwtid:"jti"},Fg=["expiresIn","notBefore","noTimestamp","audience","issuer","subject","jwtid"];gl.exports=function(r,e,t,n){typeof t=="function"?(n=t,t={}):t=t||{};let i=typeof r=="object"&&!Buffer.isBuffer(r),s=Object.assign({alg:t.algorithm||"HS256",typ:i?"JWT":void 0,kid:t.keyid},t.header);function o(u){if(n)return n(u);throw u}if(!e&&t.algorithm!=="none")return o(new Error("secretOrPrivateKey must have a value"));if(e!=null&&!(e instanceof kg))try{e=Lg(e)}catch{try{e=Pg(typeof e=="string"?Buffer.from(e):e)}catch{return o(new Error("secretOrPrivateKey is not valid key material"))}}if(s.alg.startsWith("HS")&&e.type!=="secret")return o(new Error(`secretOrPrivateKey must be a symmetric key when using ${s.alg}`));if(/^(?:RS|PS|ES)/.test(s.alg)){if(e.type!=="private")return o(new Error(`secretOrPrivateKey must be an asymmetric key when using ${s.alg}`));if(!t.allowInsecureKeySizes&&!s.alg.startsWith("ES")&&e.asymmetricKeyDetails!==void 0&&e.asymmetricKeyDetails.modulusLength<2048)return o(new Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${s.alg}`))}if(typeof r>"u")return o(new Error("payload is required"));if(i){try{Dg(r)}catch(u){return o(u)}t.mutatePayload||(r=Object.assign({},r))}else{let u=Fg.filter(function(c){return typeof t[c]<"u"});if(u.length>0)return o(new Error("invalid "+u.join(",")+" option for "+typeof r+" payload"))}if(typeof r.exp<"u"&&typeof t.expiresIn<"u")return o(new Error('Bad "options.expiresIn" option the payload already has an "exp" property.'));if(typeof r.nbf<"u"&&typeof t.notBefore<"u")return o(new Error('Bad "options.notBefore" option the payload already has an "nbf" property.'));try{Mg(t)}catch(u){return o(u)}if(!t.allowInvalidAsymmetricKeyTypes)try{Cg(s.alg,e)}catch(u){return o(u)}let a=r.iat||Math.floor(Date.now()/1e3);if(t.noTimestamp?delete r.iat:i&&(r.iat=a),typeof t.notBefore<"u"){try{r.nbf=cl(t.notBefore,a)}catch(u){return o(u)}if(typeof r.nbf>"u")return o(new Error('"notBefore" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60'))}if(typeof t.expiresIn<"u"&&typeof r=="object"){try{r.exp=cl(t.expiresIn,a)}catch(u){return o(u)}if(typeof r.exp>"u")return o(new Error('"expiresIn" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60'))}Object.keys(ml).forEach(function(u){let c=ml[u];if(typeof t[u]<"u"){if(typeof r[c]<"u")return o(new Error('Bad "options.'+u+'" option. The payload already has an "'+c+'" property.'));r[c]=t[u]}});let l=t.encoding||"utf8";if(typeof n=="function")n=n&&Tg(n),ul.createSign({header:s,privateKey:e,payload:r,encoding:l}).once("error",n).once("done",function(u){if(!t.allowInsecureKeySizes&&/^(?:RS|PS)/.test(s.alg)&&u.length<256)return n(new Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${s.alg}`));n(null,u)});else{let u=ul.sign({header:s,payload:r,secret:e,encoding:l});if(!t.allowInsecureKeySizes&&/^(?:RS|PS)/.test(s.alg)&&u.length<256)throw new Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${s.alg}`);return u}}});var wl=p((Bw,El)=>{El.exports={decode:zr(),verify:Ma(),sign:yl(),JsonWebTokenError:He(),NotBeforeError:Jr(),TokenExpiredError:Kr()}});(function(){Yn().config(Object.assign({},zn(),Kn()(process.argv)))})();var Jl=N(lt()),Kl=require("fs"),Ql=require("path");var re=N(require("fs")),vr=N(require("path")),di=N(require("os"));var Mc=process.stdout.isTTY===!0&&!process.env.NO_COLOR,me=r=>Mc?r:"",_=me("\x1B[32m"),P=me("\x1B[33m"),T=me("\x1B[36m"),de=me("\x1B[35m"),g=me("\x1B[31m"),E=me("\x1B[2m"),K=me("\x1B[1m"),m=me("\x1B[0m");var ci="app.boxel.realms";var Dc={"anthropic/claude-3.5-sonnet":"Anthropic: Claude 3.5 Sonnet","anthropic/claude-3.7-sonnet":"Anthropic: Claude 3.7 Sonnet","anthropic/claude-3.7-sonnet:thinking":"Anthropic: Claude 3.7 Sonnet (thinking)","anthropic/claude-haiku-4.5":"Anthropic: Claude Haiku 4.5","anthropic/claude-sonnet-4":"Anthropic: Claude Sonnet 4","anthropic/claude-sonnet-4.5":"Anthropic: Claude Sonnet 4.5","anthropic/claude-sonnet-4.6":"Anthropic: Claude Sonnet 4.6","anthropic/claude-opus-4.1":"Anthropic: Claude Opus 4.1","deepseek/deepseek-chat-v3-0324":"DeepSeek: DeepSeek V3 0324","google/gemini-2.5-pro":"Google: Gemini 2.5 Pro","google/gemini-2.5-flash-lite":"Google: Gemini 2.5 Flash Lite","google/gemini-2.5-flash":"Google: Gemini 2.5 Flash","meta-llama/llama-3.2-3b-instruct":"Meta: Llama 3.2 3B Instruct","openai/gpt-4.1-nano":"OpenAI: GPT-4.1 Nano","openai/gpt-4.1-mini":"OpenAI: GPT-4.1 Mini","openai/gpt-4.1":"OpenAI: GPT-4.1","openai/gpt-4o":"OpenAI: GPT-4o","openai/gpt-4o-mini":"OpenAI: GPT-4o-mini","openai/gpt-5-nano":"OpenAI: GPT-5 Nano","openai/gpt-5-mini":"OpenAI: GPT-5 Mini","openai/gpt-5":"OpenAI: GPT-5","openai/gpt-oss-20b":"OpenAI: GPT OSS 20B"},Ty=Object.keys(Dc);function C(r){return r.endsWith("/")?r:`${r}/`}async function ui(r,e,t){let n=await fetch(new URL("_matrix/client/v3/login",r).href,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({identifier:{type:"m.id.user",user:e},password:t,type:"m.login.password"})}),i=await n.json();if(!n.ok)throw new Error(`Matrix login failed: ${n.status} ${JSON.stringify(i)}`);return{accessToken:i.access_token,deviceId:i.device_id,userId:i.user_id,matrixUrl:r}}async function Fc(r){let e=await fetch(new URL(`_matrix/client/v3/user/${encodeURIComponent(r.userId)}/openid/request_token`,r.matrixUrl).href,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r.accessToken}`},body:"{}"});if(!e.ok){let t=await e.text();throw new Error(`OpenID token request failed: ${e.status} ${t}`)}return await e.json()}async function Er(r,e){let t=await Fc(r),n=`${e.replace(/\/$/,"")}/_server-session`,i=await fetch(n,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(t)});if(!i.ok){let o=await i.text();throw new Error(`Realm server session failed: ${i.status} ${o}`)}let s=i.headers.get("Authorization");if(!s)throw new Error("Realm server session response did not include an Authorization header");return s}async function wr(r,e){let t=`${r.replace(/\/$/,"")}/_realm-auth`,n=await fetch(t,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",Authorization:e}});if(!n.ok){let i=await n.text();throw new Error(`Realm auth lookup failed: ${n.status} ${i}`)}return await n.json()}function br(r){return new URL(`_matrix/client/v3/user/${encodeURIComponent(r.userId)}/account_data/${ci}`,r.matrixUrl).href}async function ct(r){try{let e=await fetch(br(r),{headers:{Authorization:`Bearer ${r.accessToken}`}});if(!e.ok)return[];let t=await e.json();return Array.isArray(t.realms)?[...t.realms]:[]}catch{return[]}}async function fi(r,e){let t=await ct(r);if(!t.includes(e)){t.push(e);let n=await fetch(br(r),{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r.accessToken}`},body:JSON.stringify({realms:t})});if(!n.ok){let i=await n.text();throw new Error(`Failed to update Matrix account data: ${n.status} ${i}`)}}}async function mi(r,e){let t=C(e),n=await ct(r),i=n.filter(o=>C(o)!==t);if(i.length===n.length)return!1;let s=await fetch(br(r),{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r.accessToken}`},body:JSON.stringify({realms:i})});if(!s.ok){let o=await s.text();throw new Error(`Failed to update Matrix account data: ${s.status} ${o}`)}return!0}var Uc=vr.join(di.homedir(),".boxel-cli"),jc="profiles.json",L="No active profile. Run `boxel profile add` to create one.";function ut(r){return r.endsWith(":stack.cards")?"staging":r.endsWith(":boxel.ai")?"production":r.endsWith(":localhost")?"local":"unknown"}function Oe(r){let e=r.match(/^@([^:]+):/);return e?e[1]:r}function ft(r){let e=r.match(/:([^:]+)$/);return e?e[1]:"unknown"}function ie(r){let e=Oe(r),t=ft(r);return`${E}[${m}${T}${e}${m} ${E}\xB7${m} ${de}${t}${m}${E}]${m}`}var $r=class{config;configDir;profilesFile;constructor(e){this.configDir=e||Uc,this.profilesFile=vr.join(this.configDir,jc),this.config=this.loadConfig()}ensureConfigDir(){re.existsSync(this.configDir)||re.mkdirSync(this.configDir,{recursive:!0})}loadConfig(){let e={profiles:{},activeProfile:null};if(re.existsSync(this.profilesFile))try{let t=re.readFileSync(this.profilesFile,"utf-8"),n=JSON.parse(t);if(n&&typeof n=="object"&&!Array.isArray(n)){let i=n,s=i.profiles&&typeof i.profiles=="object"&&!Array.isArray(i.profiles)?i.profiles:null,o=i.activeProfile===null||typeof i.activeProfile=="string"?i.activeProfile:null;if(s)return{profiles:s,activeProfile:o}}}catch{}return e}saveConfig(){this.ensureConfigDir(),re.writeFileSync(this.profilesFile,JSON.stringify(this.config,null,2),{mode:384});try{re.chmodSync(this.profilesFile,384)}catch{}}listProfiles(){return Object.keys(this.config.profiles)}getProfile(e){return this.config.profiles[e]}getActiveProfileId(){return this.config.activeProfile}getActiveProfile(){let e=this.config.activeProfile;if(!e)return null;let t=this.config.profiles[e];return t?{id:e,profile:t}:null}async addProfile(e,t,n,i,s){let o=ut(e),a=Oe(e);if(o==="unknown"&&(!i||!s))throw new Error(`Unknown domain in Matrix ID "${e}". You must provide explicit --matrix-url and --realm-server-url for non-standard domains.`);let l=o==="production"?"https://matrix.boxel.ai":"https://matrix-staging.stack.cards",u=o==="production"?"https://app.boxel.ai/":"https://realms-staging.stack.cards/",c=ft(e),f={displayName:n||`${a} \xB7 ${c}`,matrixUrl:i||l,realmServerUrl:s||u,password:t};this.config.profiles[e]=f,this.config.activeProfile||(this.config.activeProfile=e),this.saveConfig()}async removeProfile(e){if(!this.config.profiles[e])return!1;if(delete this.config.profiles[e],this.config.activeProfile===e){let t=Object.keys(this.config.profiles);this.config.activeProfile=t.length>0?t[0]:null}return this.saveConfig(),!0}switchProfile(e){return this.config.profiles[e]?(this.config.activeProfile=e,this.saveConfig(),!0):!1}async getActiveCredentials(){let e=this.getActiveProfile();if(e&&e.profile.password)return{matrixUrl:e.profile.matrixUrl,username:Oe(e.id),password:e.profile.password,realmServerUrl:e.profile.realmServerUrl,profileId:e.id};let t=process.env.MATRIX_URL,n=process.env.MATRIX_USERNAME,i=process.env.MATRIX_PASSWORD,s=process.env.REALM_SERVER_URL;return t&&n&&i&&s?{matrixUrl:t,username:n,password:i,realmServerUrl:s,profileId:null}:null}async getPassword(e){return this.config.profiles[e]?.password||null}async updatePassword(e,t){return this.config.profiles[e]?(this.config.profiles[e].password=t,this.saveConfig(),!0):!1}updateDisplayName(e,t){return this.config.profiles[e]?(this.config.profiles[e].displayName=t,this.saveConfig(),!0):!1}updateUrls(e,t){let n=this.config.profiles[e];if(!n)return!1;let i=!1;return t.matrixUrl&&t.matrixUrl!==n.matrixUrl&&(n.matrixUrl=t.matrixUrl,i=!0),t.realmServerUrl&&t.realmServerUrl!==n.realmServerUrl&&(n.realmServerUrl=t.realmServerUrl,i=!0),i&&(n.realmTokens=void 0,n.realmServerToken=void 0,this.saveConfig()),i}setRealmToken(e,t){let n=this.getActiveProfile();n&&(n.profile.realmTokens||(n.profile.realmTokens={}),n.profile.realmTokens[e]=t,this.saveConfig())}getRealmToken(e){return this.getActiveProfile()?.profile.realmTokens?.[e]}setRealmServerToken(e){let t=this.getActiveProfile();t&&(t.profile.realmServerToken=e,this.saveConfig())}getRealmServerToken(){return this.getActiveProfile()?.profile.realmServerToken}async loginToMatrix(){let e=this.getActiveProfile();if(!e)throw new Error("No active profile");let{id:t,profile:n}=e,i=Oe(t);return ui(n.matrixUrl,i,n.password)}async getOrRefreshServerToken(){let e=this.getRealmServerToken();if(e)return e;let t=await this.loginToMatrix(),i=this.getActiveProfile().profile.realmServerUrl.replace(/\/$/,""),s=await Er(t,i);return this.setRealmServerToken(s),s}async refreshServerToken(){let e=await this.loginToMatrix(),n=this.getActiveProfile().profile.realmServerUrl.replace(/\/$/,""),i=await Er(e,n);return this.setRealmServerToken(i),i}findRealmTokenForUrl(e){let n=this.getActiveProfile()?.profile.realmTokens;if(n){for(let[i,s]of Object.entries(n))if(e.startsWith(i)&&s)return s}}async fetchAndStoreAllRealmTokens(){let e=await this.getOrRefreshServerToken(),n=this.getActiveProfile().profile.realmServerUrl.replace(/\/$/,""),i=await wr(n,e);for(let[s,o]of Object.entries(i))this.setRealmToken(s,o)}async getRealmTokenForUrl(e){let t=this.findRealmTokenForUrl(e);if(t)return t;try{await this.fetchAndStoreAllRealmTokens()}catch{return}return this.findRealmTokenForUrl(e)}buildHeaders(e,t,n){let i=e instanceof Request?new Headers(e.headers):new Headers,s=new Headers(t?.headers);for(let[o,a]of s)i.set(o,a);return i.has("Authorization")||i.set("Authorization",n),i}async authedRealmFetch(e,t){let n=e instanceof Request?e.url:e instanceof URL?e.href:e,i=await this.getRealmTokenForUrl(n);if(i){let l=this.buildHeaders(e,t,i),u=await fetch(e,{...t,headers:l});if(u.status!==401)return u}let s=this.getActiveProfile();if(s&&(s.profile.realmTokens={},s.profile.realmServerToken=void 0,this.saveConfig()),await this.fetchAndStoreAllRealmTokens(),i=this.findRealmTokenForUrl(n),!i)throw new Error(`No realm token available for ${n}. The realm may not be accessible.`);let o=this.buildHeaders(e,t,i);return await fetch(e,{...t,headers:o})}async authedRealmServerFetch(e,t){let n=await this.getOrRefreshServerToken(),i=this.buildHeaders(e,t,n),s=await fetch(e,{...t,headers:i});return s.status===401&&(n=await this.refreshServerToken(),i=this.buildHeaders(e,t,n),s=await fetch(e,{...t,headers:i})),s}async fetchAndStoreRealmToken(e,t){let i=this.getActiveProfile().profile.realmServerUrl.replace(/\/$/,""),o=(await wr(i,t))[e];return o&&this.setRealmToken(e,o),o}async addToUserRealms(e){let t=await this.loginToMatrix();await fi(t,e)}async removeFromUserRealms(e){let t=await this.loginToMatrix();return mi(t,e)}async getUserRealms(){let e=await this.loginToMatrix();return ct(e)}async migrateFromEnv(){let e=process.env.MATRIX_URL,t=process.env.MATRIX_USERNAME,n=process.env.MATRIX_PASSWORD,i=process.env.REALM_SERVER_URL;if(!e||!t||!n||!i)return null;let o=e.includes("boxel.ai")?"boxel.ai":"stack.cards",a=`@${t}:${o}`;return this.config.profiles[a]?(this.config.profiles[a].password!==n&&(this.config.profiles[a].password=n,this.saveConfig()),{profileId:a,created:!1}):(await this.addProfile(a,n,void 0,e,i),{profileId:a,created:!0})}printStatus(){let e=this.getActiveProfile();e?(console.log(`
|
|
31
|
+
"HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".`,Ve="secret must be a string or buffer",Ce="key must be a string or a buffer",zu="key must be a string, a buffer or an object",Hr=typeof Z.createPublicKey=="function";Hr&&(Ce+=" or a KeyObject",Ve+="or a KeyObject");function ss(r){if(!Ae.isBuffer(r)&&typeof r!="string"&&(!Hr||typeof r!="object"||typeof r.type!="string"||typeof r.asymmetricKeyType!="string"||typeof r.export!="function"))throw ne(Ce)}function os(r){if(!Ae.isBuffer(r)&&typeof r!="string"&&typeof r!="object")throw ne(zu)}function Ju(r){if(!Ae.isBuffer(r)){if(typeof r=="string")return r;if(!Hr||typeof r!="object"||r.type!=="secret"||typeof r.export!="function")throw ne(Ve)}}function Wr(r){return r.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function as(r){r=r.toString();var e=4-r.length%4;if(e!==4)for(var t=0;t<e;++t)r+="=";return r.replace(/\-/g,"+").replace(/_/g,"/")}function ne(r){var e=[].slice.call(arguments,1),t=ns.format.bind(ns,r).apply(null,e);return new TypeError(t)}function Ku(r){return Ae.isBuffer(r)||typeof r=="string"}function Ge(r){return Ku(r)||(r=JSON.stringify(r)),r}function ls(r){return function(t,n){Ju(n),t=Ge(t);var i=Z.createHmac("sha"+r,n),s=(i.update(t),i.digest("base64"));return Wr(s)}}var Gr,Qu="timingSafeEqual"in Z?function(e,t){return e.byteLength!==t.byteLength?!1:Z.timingSafeEqual(e,t)}:function(e,t){return Gr||(Gr=rs()),Gr(e,t)};function Zu(r){return function(t,n,i){var s=ls(r)(t,i);return Qu(Ae.from(n),Ae.from(s))}}function cs(r){return function(t,n){os(n),t=Ge(t);var i=Z.createSign("RSA-SHA"+r),s=(i.update(t),i.sign(n,"base64"));return Wr(s)}}function us(r){return function(t,n,i){ss(i),t=Ge(t),n=as(n);var s=Z.createVerify("RSA-SHA"+r);return s.update(t),s.verify(i,n,"base64")}}function ef(r){return function(t,n){os(n),t=Ge(t);var i=Z.createSign("RSA-SHA"+r),s=(i.update(t),i.sign({key:n,padding:Z.constants.RSA_PKCS1_PSS_PADDING,saltLength:Z.constants.RSA_PSS_SALTLEN_DIGEST},"base64"));return Wr(s)}}function tf(r){return function(t,n,i){ss(i),t=Ge(t),n=as(n);var s=Z.createVerify("RSA-SHA"+r);return s.update(t),s.verify({key:i,padding:Z.constants.RSA_PKCS1_PSS_PADDING,saltLength:Z.constants.RSA_PSS_SALTLEN_DIGEST},n,"base64")}}function rf(r){var e=cs(r);return function(){var n=e.apply(null,arguments);return n=is.derToJose(n,"ES"+r),n}}function nf(r){var e=us(r);return function(n,i,s){i=is.joseToDer(i,"ES"+r).toString("base64");var o=e(n,i,s);return o}}function sf(){return function(){return""}}function of(){return function(e,t){return t===""}}fs.exports=function(e){var t={hs:ls,rs:cs,ps:ef,es:rf,none:sf},n={hs:Zu,rs:us,ps:tf,es:nf,none:of},i=e.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);if(!i)throw ne(Xu,e);var s=(i[1]||i[3]).toLowerCase(),o=i[2];return{sign:t[s](o),verify:n[s](o)}}});var Yr=h((ME,ms)=>{var af=require("buffer").Buffer;ms.exports=function(e){return typeof e=="string"?e:typeof e=="number"||af.isBuffer(e)?e.toString():JSON.stringify(e)}});var Es=h((DE,ys)=>{var lf=Oe().Buffer,ds=jr(),cf=Br(),uf=require("stream"),ps=Yr(),Xr=require("util");function hs(r,e){return lf.from(r,e).toString("base64").replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function ff(r,e,t){t=t||"utf8";var n=hs(ps(r),"binary"),i=hs(ps(e),t);return Xr.format("%s.%s",n,i)}function gs(r){var e=r.header,t=r.payload,n=r.secret||r.privateKey,i=r.encoding,s=cf(e.alg),o=ff(e,t,i),a=s.sign(o,n);return Xr.format("%s.%s",o,a)}function xt(r){var e=r.secret;if(e=e??r.privateKey,e=e??r.key,/^hs/i.test(r.header.alg)===!0&&e==null)throw new TypeError("secret must be a string or buffer or a KeyObject");var t=new ds(e);this.readable=!0,this.header=r.header,this.encoding=r.encoding,this.secret=this.privateKey=this.key=t,this.payload=new ds(r.payload),this.secret.once("close",function(){!this.payload.writable&&this.readable&&this.sign()}.bind(this)),this.payload.once("close",function(){!this.secret.writable&&this.readable&&this.sign()}.bind(this))}Xr.inherits(xt,uf);xt.prototype.sign=function(){try{var e=gs({header:this.header,payload:this.payload.buffer,secret:this.secret.buffer,encoding:this.encoding});return this.emit("done",e),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(t){this.readable=!1,this.emit("error",t),this.emit("close")}};xt.sign=gs;ys.exports=xt});var Cs=h((FE,Os)=>{var bs=Oe().Buffer,ws=jr(),mf=Br(),df=require("stream"),Rs=Yr(),pf=require("util"),hf=/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;function gf(r){return Object.prototype.toString.call(r)==="[object Object]"}function yf(r){if(gf(r))return r;try{return JSON.parse(r)}catch{return}}function $s(r){var e=r.split(".",1)[0];return yf(bs.from(e,"base64").toString("binary"))}function Ef(r){return r.split(".",2).join(".")}function vs(r){return r.split(".")[2]}function wf(r,e){e=e||"utf8";var t=r.split(".")[1];return bs.from(t,"base64").toString(e)}function Ss(r){return hf.test(r)&&!!$s(r)}function xs(r,e,t){if(!e){var n=new Error("Missing algorithm parameter for jws.verify");throw n.code="MISSING_ALGORITHM",n}r=Rs(r);var i=vs(r),s=Ef(r),o=mf(e);return o.verify(s,i,t)}function _s(r,e){if(e=e||{},r=Rs(r),!Ss(r))return null;var t=$s(r);if(!t)return null;var n=wf(r);return(t.typ==="JWT"||e.json)&&(n=JSON.parse(n,e.encoding)),{header:t,payload:n,signature:vs(r)}}function Te(r){r=r||{};var e=r.secret;if(e=e??r.publicKey,e=e??r.key,/^hs/i.test(r.algorithm)===!0&&e==null)throw new TypeError("secret must be a string or buffer or a KeyObject");var t=new ws(e);this.readable=!0,this.algorithm=r.algorithm,this.encoding=r.encoding,this.secret=this.publicKey=this.key=t,this.signature=new ws(r.signature),this.secret.once("close",function(){!this.signature.writable&&this.readable&&this.verify()}.bind(this)),this.signature.once("close",function(){!this.secret.writable&&this.readable&&this.verify()}.bind(this))}pf.inherits(Te,df);Te.prototype.verify=function(){try{var e=xs(this.signature.buffer,this.algorithm,this.key.buffer),t=_s(this.signature.buffer,this.encoding);return this.emit("done",e,t),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(n){this.readable=!1,this.emit("error",n),this.emit("close")}};Te.decode=_s;Te.isValid=Ss;Te.verify=xs;Os.exports=Te});var Ot=h(he=>{var As=Es(),_t=Cs(),bf=["HS256","HS384","HS512","RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512"];he.ALGORITHMS=bf;he.sign=As.sign;he.verify=_t.verify;he.decode=_t.decode;he.isValid=_t.isValid;he.createSign=function(e){return new As(e)};he.createVerify=function(e){return new _t(e)}});var zr=h((jE,Ts)=>{var Rf=Ot();Ts.exports=function(r,e){e=e||{};var t=Rf.decode(r,e);if(!t)return null;var n=t.payload;if(typeof n=="string")try{var i=JSON.parse(n);i!==null&&typeof i=="object"&&(n=i)}catch{}return e.complete===!0?{header:t.header,payload:n,signature:t.signature}:n}});var He=h((qE,ks)=>{var Ct=function(r,e){Error.call(this,r),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor),this.name="JsonWebTokenError",this.message=r,e&&(this.inner=e)};Ct.prototype=Object.create(Error.prototype);Ct.prototype.constructor=Ct;ks.exports=Ct});var Jr=h((VE,Ls)=>{var Ps=He(),At=function(r,e){Ps.call(this,r),this.name="NotBeforeError",this.date=e};At.prototype=Object.create(Ps.prototype);At.prototype.constructor=At;Ls.exports=At});var Kr=h((GE,Ns)=>{var Is=He(),Tt=function(r,e){Is.call(this,r),this.name="TokenExpiredError",this.expiredAt=e};Tt.prototype=Object.create(Is.prototype);Tt.prototype.constructor=Tt;Ns.exports=Tt});var Ds=h((HE,Ms)=>{var ke=1e3,Pe=ke*60,Le=Pe*60,$e=Le*24,$f=$e*7,vf=$e*365.25;Ms.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return Sf(r);if(t==="number"&&isFinite(r))return e.long?_f(r):xf(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function Sf(r){if(r=String(r),!(r.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(e){var t=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return t*vf;case"weeks":case"week":case"w":return t*$f;case"days":case"day":case"d":return t*$e;case"hours":case"hour":case"hrs":case"hr":case"h":return t*Le;case"minutes":case"minute":case"mins":case"min":case"m":return t*Pe;case"seconds":case"second":case"secs":case"sec":case"s":return t*ke;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function xf(r){var e=Math.abs(r);return e>=$e?Math.round(r/$e)+"d":e>=Le?Math.round(r/Le)+"h":e>=Pe?Math.round(r/Pe)+"m":e>=ke?Math.round(r/ke)+"s":r+"ms"}function _f(r){var e=Math.abs(r);return e>=$e?kt(r,e,$e,"day"):e>=Le?kt(r,e,Le,"hour"):e>=Pe?kt(r,e,Pe,"minute"):e>=ke?kt(r,e,ke,"second"):r+" ms"}function kt(r,e,t,n){var i=e>=t*1.5;return Math.round(r/t)+" "+n+(i?"s":"")}});var Qr=h((WE,Fs)=>{var Of=Ds();Fs.exports=function(r,e){var t=e||Math.floor(Date.now()/1e3);if(typeof r=="string"){var n=Of(r);return typeof n>"u"?void 0:Math.floor(t+n/1e3)}else return typeof r=="number"?t+r:void 0}});var We=h((BE,Us)=>{"use strict";var Cf="2.0.0",Af=Number.MAX_SAFE_INTEGER||9007199254740991,Tf=16,kf=250,Pf=["major","premajor","minor","preminor","patch","prepatch","prerelease"];Us.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:Tf,MAX_SAFE_BUILD_LENGTH:kf,MAX_SAFE_INTEGER:Af,RELEASE_TYPES:Pf,SEMVER_SPEC_VERSION:Cf,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var Be=h((YE,js)=>{"use strict";var Lf=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...r)=>console.error("SEMVER",...r):()=>{};js.exports=Lf});var Ie=h((ae,qs)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:Zr,MAX_SAFE_BUILD_LENGTH:If,MAX_LENGTH:Nf}=We(),Mf=Be();ae=qs.exports={};var Df=ae.re=[],Ff=ae.safeRe=[],w=ae.src=[],Uf=ae.safeSrc=[],b=ae.t={},jf=0,en="[a-zA-Z0-9-]",qf=[["\\s",1],["\\d",Nf],[en,If]],Vf=r=>{for(let[e,t]of qf)r=r.split(`${e}*`).join(`${e}{0,${t}}`).split(`${e}+`).join(`${e}{1,${t}}`);return r},v=(r,e,t)=>{let n=Vf(e),i=jf++;Mf(r,i,e),b[r]=i,w[i]=e,Uf[i]=n,Df[i]=new RegExp(e,t?"g":void 0),Ff[i]=new RegExp(n,t?"g":void 0)};v("NUMERICIDENTIFIER","0|[1-9]\\d*");v("NUMERICIDENTIFIERLOOSE","\\d+");v("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${en}*`);v("MAINVERSION",`(${w[b.NUMERICIDENTIFIER]})\\.(${w[b.NUMERICIDENTIFIER]})\\.(${w[b.NUMERICIDENTIFIER]})`);v("MAINVERSIONLOOSE",`(${w[b.NUMERICIDENTIFIERLOOSE]})\\.(${w[b.NUMERICIDENTIFIERLOOSE]})\\.(${w[b.NUMERICIDENTIFIERLOOSE]})`);v("PRERELEASEIDENTIFIER",`(?:${w[b.NONNUMERICIDENTIFIER]}|${w[b.NUMERICIDENTIFIER]})`);v("PRERELEASEIDENTIFIERLOOSE",`(?:${w[b.NONNUMERICIDENTIFIER]}|${w[b.NUMERICIDENTIFIERLOOSE]})`);v("PRERELEASE",`(?:-(${w[b.PRERELEASEIDENTIFIER]}(?:\\.${w[b.PRERELEASEIDENTIFIER]})*))`);v("PRERELEASELOOSE",`(?:-?(${w[b.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${w[b.PRERELEASEIDENTIFIERLOOSE]})*))`);v("BUILDIDENTIFIER",`${en}+`);v("BUILD",`(?:\\+(${w[b.BUILDIDENTIFIER]}(?:\\.${w[b.BUILDIDENTIFIER]})*))`);v("FULLPLAIN",`v?${w[b.MAINVERSION]}${w[b.PRERELEASE]}?${w[b.BUILD]}?`);v("FULL",`^${w[b.FULLPLAIN]}$`);v("LOOSEPLAIN",`[v=\\s]*${w[b.MAINVERSIONLOOSE]}${w[b.PRERELEASELOOSE]}?${w[b.BUILD]}?`);v("LOOSE",`^${w[b.LOOSEPLAIN]}$`);v("GTLT","((?:<|>)?=?)");v("XRANGEIDENTIFIERLOOSE",`${w[b.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);v("XRANGEIDENTIFIER",`${w[b.NUMERICIDENTIFIER]}|x|X|\\*`);v("XRANGEPLAIN",`[v=\\s]*(${w[b.XRANGEIDENTIFIER]})(?:\\.(${w[b.XRANGEIDENTIFIER]})(?:\\.(${w[b.XRANGEIDENTIFIER]})(?:${w[b.PRERELEASE]})?${w[b.BUILD]}?)?)?`);v("XRANGEPLAINLOOSE",`[v=\\s]*(${w[b.XRANGEIDENTIFIERLOOSE]})(?:\\.(${w[b.XRANGEIDENTIFIERLOOSE]})(?:\\.(${w[b.XRANGEIDENTIFIERLOOSE]})(?:${w[b.PRERELEASELOOSE]})?${w[b.BUILD]}?)?)?`);v("XRANGE",`^${w[b.GTLT]}\\s*${w[b.XRANGEPLAIN]}$`);v("XRANGELOOSE",`^${w[b.GTLT]}\\s*${w[b.XRANGEPLAINLOOSE]}$`);v("COERCEPLAIN",`(^|[^\\d])(\\d{1,${Zr}})(?:\\.(\\d{1,${Zr}}))?(?:\\.(\\d{1,${Zr}}))?`);v("COERCE",`${w[b.COERCEPLAIN]}(?:$|[^\\d])`);v("COERCEFULL",w[b.COERCEPLAIN]+`(?:${w[b.PRERELEASE]})?(?:${w[b.BUILD]})?(?:$|[^\\d])`);v("COERCERTL",w[b.COERCE],!0);v("COERCERTLFULL",w[b.COERCEFULL],!0);v("LONETILDE","(?:~>?)");v("TILDETRIM",`(\\s*)${w[b.LONETILDE]}\\s+`,!0);ae.tildeTrimReplace="$1~";v("TILDE",`^${w[b.LONETILDE]}${w[b.XRANGEPLAIN]}$`);v("TILDELOOSE",`^${w[b.LONETILDE]}${w[b.XRANGEPLAINLOOSE]}$`);v("LONECARET","(?:\\^)");v("CARETTRIM",`(\\s*)${w[b.LONECARET]}\\s+`,!0);ae.caretTrimReplace="$1^";v("CARET",`^${w[b.LONECARET]}${w[b.XRANGEPLAIN]}$`);v("CARETLOOSE",`^${w[b.LONECARET]}${w[b.XRANGEPLAINLOOSE]}$`);v("COMPARATORLOOSE",`^${w[b.GTLT]}\\s*(${w[b.LOOSEPLAIN]})$|^$`);v("COMPARATOR",`^${w[b.GTLT]}\\s*(${w[b.FULLPLAIN]})$|^$`);v("COMPARATORTRIM",`(\\s*)${w[b.GTLT]}\\s*(${w[b.LOOSEPLAIN]}|${w[b.XRANGEPLAIN]})`,!0);ae.comparatorTrimReplace="$1$2$3";v("HYPHENRANGE",`^\\s*(${w[b.XRANGEPLAIN]})\\s+-\\s+(${w[b.XRANGEPLAIN]})\\s*$`);v("HYPHENRANGELOOSE",`^\\s*(${w[b.XRANGEPLAINLOOSE]})\\s+-\\s+(${w[b.XRANGEPLAINLOOSE]})\\s*$`);v("STAR","(<|>)?=?\\s*\\*");v("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");v("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var Pt=h((XE,Vs)=>{"use strict";var Gf=Object.freeze({loose:!0}),Hf=Object.freeze({}),Wf=r=>r?typeof r!="object"?Gf:r:Hf;Vs.exports=Wf});var tn=h((zE,Ws)=>{"use strict";var Gs=/^[0-9]+$/,Hs=(r,e)=>{if(typeof r=="number"&&typeof e=="number")return r===e?0:r<e?-1:1;let t=Gs.test(r),n=Gs.test(e);return t&&n&&(r=+r,e=+e),r===e?0:t&&!n?-1:n&&!t?1:r<e?-1:1},Bf=(r,e)=>Hs(e,r);Ws.exports={compareIdentifiers:Hs,rcompareIdentifiers:Bf}});var H=h((JE,Ys)=>{"use strict";var Lt=Be(),{MAX_LENGTH:Bs,MAX_SAFE_INTEGER:It}=We(),{safeRe:Nt,t:Mt}=Ie(),Yf=Pt(),{compareIdentifiers:rn}=tn(),nn=class r{constructor(e,t){if(t=Yf(t),e instanceof r){if(e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease)return e;e=e.version}else if(typeof e!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof e}".`);if(e.length>Bs)throw new TypeError(`version is longer than ${Bs} characters`);Lt("SemVer",e,t),this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease;let n=e.trim().match(t.loose?Nt[Mt.LOOSE]:Nt[Mt.FULL]);if(!n)throw new TypeError(`Invalid Version: ${e}`);if(this.raw=e,this.major=+n[1],this.minor=+n[2],this.patch=+n[3],this.major>It||this.major<0)throw new TypeError("Invalid major version");if(this.minor>It||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>It||this.patch<0)throw new TypeError("Invalid patch version");n[4]?this.prerelease=n[4].split(".").map(i=>{if(/^[0-9]+$/.test(i)){let s=+i;if(s>=0&&s<It)return s}return i}):this.prerelease=[],this.build=n[5]?n[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(e){if(Lt("SemVer.compare",this.version,this.options,e),!(e instanceof r)){if(typeof e=="string"&&e===this.version)return 0;e=new r(e,this.options)}return e.version===this.version?0:this.compareMain(e)||this.comparePre(e)}compareMain(e){return e instanceof r||(e=new r(e,this.options)),this.major<e.major?-1:this.major>e.major?1:this.minor<e.minor?-1:this.minor>e.minor?1:this.patch<e.patch?-1:this.patch>e.patch?1:0}comparePre(e){if(e instanceof r||(e=new r(e,this.options)),this.prerelease.length&&!e.prerelease.length)return-1;if(!this.prerelease.length&&e.prerelease.length)return 1;if(!this.prerelease.length&&!e.prerelease.length)return 0;let t=0;do{let n=this.prerelease[t],i=e.prerelease[t];if(Lt("prerelease compare",t,n,i),n===void 0&&i===void 0)return 0;if(i===void 0)return 1;if(n===void 0)return-1;if(n===i)continue;return rn(n,i)}while(++t)}compareBuild(e){e instanceof r||(e=new r(e,this.options));let t=0;do{let n=this.build[t],i=e.build[t];if(Lt("build compare",t,n,i),n===void 0&&i===void 0)return 0;if(i===void 0)return 1;if(n===void 0)return-1;if(n===i)continue;return rn(n,i)}while(++t)}inc(e,t,n){if(e.startsWith("pre")){if(!t&&n===!1)throw new Error("invalid increment argument: identifier is empty");if(t){let i=`-${t}`.match(this.options.loose?Nt[Mt.PRERELEASELOOSE]:Nt[Mt.PRERELEASE]);if(!i||i[1]!==t)throw new Error(`invalid identifier: ${t}`)}}switch(e){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",t,n);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",t,n);break;case"prepatch":this.prerelease.length=0,this.inc("patch",t,n),this.inc("pre",t,n);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",t,n),this.inc("pre",t,n);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{let i=Number(n)?1:0;if(this.prerelease.length===0)this.prerelease=[i];else{let s=this.prerelease.length;for(;--s>=0;)typeof this.prerelease[s]=="number"&&(this.prerelease[s]++,s=-2);if(s===-1){if(t===this.prerelease.join(".")&&n===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(i)}}if(t){let s=[t,i];n===!1&&(s=[t]),rn(this.prerelease[0],t)===0?isNaN(this.prerelease[1])&&(this.prerelease=s):this.prerelease=s}break}default:throw new Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};Ys.exports=nn});var ve=h((KE,zs)=>{"use strict";var Xs=H(),Xf=(r,e,t=!1)=>{if(r instanceof Xs)return r;try{return new Xs(r,e)}catch(n){if(!t)return null;throw n}};zs.exports=Xf});var Ks=h((QE,Js)=>{"use strict";var zf=ve(),Jf=(r,e)=>{let t=zf(r,e);return t?t.version:null};Js.exports=Jf});var Zs=h((ZE,Qs)=>{"use strict";var Kf=ve(),Qf=(r,e)=>{let t=Kf(r.trim().replace(/^[=v]+/,""),e);return t?t.version:null};Qs.exports=Qf});var ro=h((ew,to)=>{"use strict";var eo=H(),Zf=(r,e,t,n,i)=>{typeof t=="string"&&(i=n,n=t,t=void 0);try{return new eo(r instanceof eo?r.version:r,t).inc(e,n,i).version}catch{return null}};to.exports=Zf});var so=h((tw,io)=>{"use strict";var no=ve(),em=(r,e)=>{let t=no(r,null,!0),n=no(e,null,!0),i=t.compare(n);if(i===0)return null;let s=i>0,o=s?t:n,a=s?n:t,l=!!o.prerelease.length;if(!!a.prerelease.length&&!l){if(!a.patch&&!a.minor)return"major";if(a.compareMain(o)===0)return a.minor&&!a.patch?"minor":"patch"}let c=l?"pre":"";return t.major!==n.major?c+"major":t.minor!==n.minor?c+"minor":t.patch!==n.patch?c+"patch":"prerelease"};io.exports=em});var ao=h((rw,oo)=>{"use strict";var tm=H(),rm=(r,e)=>new tm(r,e).major;oo.exports=rm});var co=h((nw,lo)=>{"use strict";var nm=H(),im=(r,e)=>new nm(r,e).minor;lo.exports=im});var fo=h((iw,uo)=>{"use strict";var sm=H(),om=(r,e)=>new sm(r,e).patch;uo.exports=om});var po=h((sw,mo)=>{"use strict";var am=ve(),lm=(r,e)=>{let t=am(r,e);return t&&t.prerelease.length?t.prerelease:null};mo.exports=lm});var ee=h((ow,go)=>{"use strict";var ho=H(),cm=(r,e,t)=>new ho(r,t).compare(new ho(e,t));go.exports=cm});var Eo=h((aw,yo)=>{"use strict";var um=ee(),fm=(r,e,t)=>um(e,r,t);yo.exports=fm});var bo=h((lw,wo)=>{"use strict";var mm=ee(),dm=(r,e)=>mm(r,e,!0);wo.exports=dm});var Dt=h((cw,$o)=>{"use strict";var Ro=H(),pm=(r,e,t)=>{let n=new Ro(r,t),i=new Ro(e,t);return n.compare(i)||n.compareBuild(i)};$o.exports=pm});var So=h((uw,vo)=>{"use strict";var hm=Dt(),gm=(r,e)=>r.sort((t,n)=>hm(t,n,e));vo.exports=gm});var _o=h((fw,xo)=>{"use strict";var ym=Dt(),Em=(r,e)=>r.sort((t,n)=>ym(n,t,e));xo.exports=Em});var Ye=h((mw,Oo)=>{"use strict";var wm=ee(),bm=(r,e,t)=>wm(r,e,t)>0;Oo.exports=bm});var Ft=h((dw,Co)=>{"use strict";var Rm=ee(),$m=(r,e,t)=>Rm(r,e,t)<0;Co.exports=$m});var sn=h((pw,Ao)=>{"use strict";var vm=ee(),Sm=(r,e,t)=>vm(r,e,t)===0;Ao.exports=Sm});var on=h((hw,To)=>{"use strict";var xm=ee(),_m=(r,e,t)=>xm(r,e,t)!==0;To.exports=_m});var Ut=h((gw,ko)=>{"use strict";var Om=ee(),Cm=(r,e,t)=>Om(r,e,t)>=0;ko.exports=Cm});var jt=h((yw,Po)=>{"use strict";var Am=ee(),Tm=(r,e,t)=>Am(r,e,t)<=0;Po.exports=Tm});var an=h((Ew,Lo)=>{"use strict";var km=sn(),Pm=on(),Lm=Ye(),Im=Ut(),Nm=Ft(),Mm=jt(),Dm=(r,e,t,n)=>{switch(e){case"===":return typeof r=="object"&&(r=r.version),typeof t=="object"&&(t=t.version),r===t;case"!==":return typeof r=="object"&&(r=r.version),typeof t=="object"&&(t=t.version),r!==t;case"":case"=":case"==":return km(r,t,n);case"!=":return Pm(r,t,n);case">":return Lm(r,t,n);case">=":return Im(r,t,n);case"<":return Nm(r,t,n);case"<=":return Mm(r,t,n);default:throw new TypeError(`Invalid operator: ${e}`)}};Lo.exports=Dm});var No=h((ww,Io)=>{"use strict";var Fm=H(),Um=ve(),{safeRe:qt,t:Vt}=Ie(),jm=(r,e)=>{if(r instanceof Fm)return r;if(typeof r=="number"&&(r=String(r)),typeof r!="string")return null;e=e||{};let t=null;if(!e.rtl)t=r.match(e.includePrerelease?qt[Vt.COERCEFULL]:qt[Vt.COERCE]);else{let l=e.includePrerelease?qt[Vt.COERCERTLFULL]:qt[Vt.COERCERTL],u;for(;(u=l.exec(r))&&(!t||t.index+t[0].length!==r.length);)(!t||u.index+u[0].length!==t.index+t[0].length)&&(t=u),l.lastIndex=u.index+u[1].length+u[2].length;l.lastIndex=-1}if(t===null)return null;let n=t[2],i=t[3]||"0",s=t[4]||"0",o=e.includePrerelease&&t[5]?`-${t[5]}`:"",a=e.includePrerelease&&t[6]?`+${t[6]}`:"";return Um(`${n}.${i}.${s}${o}${a}`,e)};Io.exports=jm});var Do=h((bw,Mo)=>{"use strict";var ln=class{constructor(){this.max=1e3,this.map=new Map}get(e){let t=this.map.get(e);if(t!==void 0)return this.map.delete(e),this.map.set(e,t),t}delete(e){return this.map.delete(e)}set(e,t){if(!this.delete(e)&&t!==void 0){if(this.map.size>=this.max){let i=this.map.keys().next().value;this.delete(i)}this.map.set(e,t)}return this}};Mo.exports=ln});var te=h((Rw,qo)=>{"use strict";var qm=/\s+/g,cn=class r{constructor(e,t){if(t=Gm(t),e instanceof r)return e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease?e:new r(e.raw,t);if(e instanceof un)return this.raw=e.value,this.set=[[e]],this.formatted=void 0,this;if(this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease,this.raw=e.trim().replace(qm," "),this.set=this.raw.split("||").map(n=>this.parseRange(n.trim())).filter(n=>n.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let n=this.set[0];if(this.set=this.set.filter(i=>!Uo(i[0])),this.set.length===0)this.set=[n];else if(this.set.length>1){for(let i of this.set)if(i.length===1&&Jm(i[0])){this.set=[i];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let e=0;e<this.set.length;e++){e>0&&(this.formatted+="||");let t=this.set[e];for(let n=0;n<t.length;n++)n>0&&(this.formatted+=" "),this.formatted+=t[n].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(e){let n=((this.options.includePrerelease&&Xm)|(this.options.loose&&zm))+":"+e,i=Fo.get(n);if(i)return i;let s=this.options.loose,o=s?Y[W.HYPHENRANGELOOSE]:Y[W.HYPHENRANGE];e=e.replace(o,od(this.options.includePrerelease)),I("hyphen replace",e),e=e.replace(Y[W.COMPARATORTRIM],Wm),I("comparator trim",e),e=e.replace(Y[W.TILDETRIM],Bm),I("tilde trim",e),e=e.replace(Y[W.CARETTRIM],Ym),I("caret trim",e);let a=e.split(" ").map(f=>Km(f,this.options)).join(" ").split(/\s+/).map(f=>sd(f,this.options));s&&(a=a.filter(f=>(I("loose invalid filter",f,this.options),!!f.match(Y[W.COMPARATORLOOSE])))),I("range list",a);let l=new Map,u=a.map(f=>new un(f,this.options));for(let f of u){if(Uo(f))return[f];l.set(f.value,f)}l.size>1&&l.has("")&&l.delete("");let c=[...l.values()];return Fo.set(n,c),c}intersects(e,t){if(!(e instanceof r))throw new TypeError("a Range is required");return this.set.some(n=>jo(n,t)&&e.set.some(i=>jo(i,t)&&n.every(s=>i.every(o=>s.intersects(o,t)))))}test(e){if(!e)return!1;if(typeof e=="string")try{e=new Hm(e,this.options)}catch{return!1}for(let t=0;t<this.set.length;t++)if(ad(this.set[t],e,this.options))return!0;return!1}};qo.exports=cn;var Vm=Do(),Fo=new Vm,Gm=Pt(),un=Xe(),I=Be(),Hm=H(),{safeRe:Y,t:W,comparatorTrimReplace:Wm,tildeTrimReplace:Bm,caretTrimReplace:Ym}=Ie(),{FLAG_INCLUDE_PRERELEASE:Xm,FLAG_LOOSE:zm}=We(),Uo=r=>r.value==="<0.0.0-0",Jm=r=>r.value==="",jo=(r,e)=>{let t=!0,n=r.slice(),i=n.pop();for(;t&&n.length;)t=n.every(s=>i.intersects(s,e)),i=n.pop();return t},Km=(r,e)=>(r=r.replace(Y[W.BUILD],""),I("comp",r,e),r=ed(r,e),I("caret",r),r=Qm(r,e),I("tildes",r),r=rd(r,e),I("xrange",r),r=id(r,e),I("stars",r),r),X=r=>!r||r.toLowerCase()==="x"||r==="*",Qm=(r,e)=>r.trim().split(/\s+/).map(t=>Zm(t,e)).join(" "),Zm=(r,e)=>{let t=e.loose?Y[W.TILDELOOSE]:Y[W.TILDE];return r.replace(t,(n,i,s,o,a)=>{I("tilde",r,n,i,s,o,a);let l;return X(i)?l="":X(s)?l=`>=${i}.0.0 <${+i+1}.0.0-0`:X(o)?l=`>=${i}.${s}.0 <${i}.${+s+1}.0-0`:a?(I("replaceTilde pr",a),l=`>=${i}.${s}.${o}-${a} <${i}.${+s+1}.0-0`):l=`>=${i}.${s}.${o} <${i}.${+s+1}.0-0`,I("tilde return",l),l})},ed=(r,e)=>r.trim().split(/\s+/).map(t=>td(t,e)).join(" "),td=(r,e)=>{I("caret",r,e);let t=e.loose?Y[W.CARETLOOSE]:Y[W.CARET],n=e.includePrerelease?"-0":"";return r.replace(t,(i,s,o,a,l)=>{I("caret",r,i,s,o,a,l);let u;return X(s)?u="":X(o)?u=`>=${s}.0.0${n} <${+s+1}.0.0-0`:X(a)?s==="0"?u=`>=${s}.${o}.0${n} <${s}.${+o+1}.0-0`:u=`>=${s}.${o}.0${n} <${+s+1}.0.0-0`:l?(I("replaceCaret pr",l),s==="0"?o==="0"?u=`>=${s}.${o}.${a}-${l} <${s}.${o}.${+a+1}-0`:u=`>=${s}.${o}.${a}-${l} <${s}.${+o+1}.0-0`:u=`>=${s}.${o}.${a}-${l} <${+s+1}.0.0-0`):(I("no pr"),s==="0"?o==="0"?u=`>=${s}.${o}.${a}${n} <${s}.${o}.${+a+1}-0`:u=`>=${s}.${o}.${a}${n} <${s}.${+o+1}.0-0`:u=`>=${s}.${o}.${a} <${+s+1}.0.0-0`),I("caret return",u),u})},rd=(r,e)=>(I("replaceXRanges",r,e),r.split(/\s+/).map(t=>nd(t,e)).join(" ")),nd=(r,e)=>{r=r.trim();let t=e.loose?Y[W.XRANGELOOSE]:Y[W.XRANGE];return r.replace(t,(n,i,s,o,a,l)=>{I("xRange",r,n,i,s,o,a,l);let u=X(s),c=u||X(o),f=c||X(a),d=f;return i==="="&&d&&(i=""),l=e.includePrerelease?"-0":"",u?i===">"||i==="<"?n="<0.0.0-0":n="*":i&&d?(c&&(o=0),a=0,i===">"?(i=">=",c?(s=+s+1,o=0,a=0):(o=+o+1,a=0)):i==="<="&&(i="<",c?s=+s+1:o=+o+1),i==="<"&&(l="-0"),n=`${i+s}.${o}.${a}${l}`):c?n=`>=${s}.0.0${l} <${+s+1}.0.0-0`:f&&(n=`>=${s}.${o}.0${l} <${s}.${+o+1}.0-0`),I("xRange return",n),n})},id=(r,e)=>(I("replaceStars",r,e),r.trim().replace(Y[W.STAR],"")),sd=(r,e)=>(I("replaceGTE0",r,e),r.trim().replace(Y[e.includePrerelease?W.GTE0PRE:W.GTE0],"")),od=r=>(e,t,n,i,s,o,a,l,u,c,f,d)=>(X(n)?t="":X(i)?t=`>=${n}.0.0${r?"-0":""}`:X(s)?t=`>=${n}.${i}.0${r?"-0":""}`:o?t=`>=${t}`:t=`>=${t}${r?"-0":""}`,X(u)?l="":X(c)?l=`<${+u+1}.0.0-0`:X(f)?l=`<${u}.${+c+1}.0-0`:d?l=`<=${u}.${c}.${f}-${d}`:r?l=`<${u}.${c}.${+f+1}-0`:l=`<=${l}`,`${t} ${l}`.trim()),ad=(r,e,t)=>{for(let n=0;n<r.length;n++)if(!r[n].test(e))return!1;if(e.prerelease.length&&!t.includePrerelease){for(let n=0;n<r.length;n++)if(I(r[n].semver),r[n].semver!==un.ANY&&r[n].semver.prerelease.length>0){let i=r[n].semver;if(i.major===e.major&&i.minor===e.minor&&i.patch===e.patch)return!0}return!1}return!0}});var Xe=h(($w,Yo)=>{"use strict";var ze=Symbol("SemVer ANY"),dn=class r{static get ANY(){return ze}constructor(e,t){if(t=Vo(t),e instanceof r){if(e.loose===!!t.loose)return e;e=e.value}e=e.trim().split(/\s+/).join(" "),mn("comparator",e,t),this.options=t,this.loose=!!t.loose,this.parse(e),this.semver===ze?this.value="":this.value=this.operator+this.semver.version,mn("comp",this)}parse(e){let t=this.options.loose?Go[Ho.COMPARATORLOOSE]:Go[Ho.COMPARATOR],n=e.match(t);if(!n)throw new TypeError(`Invalid comparator: ${e}`);this.operator=n[1]!==void 0?n[1]:"",this.operator==="="&&(this.operator=""),n[2]?this.semver=new Wo(n[2],this.options.loose):this.semver=ze}toString(){return this.value}test(e){if(mn("Comparator.test",e,this.options.loose),this.semver===ze||e===ze)return!0;if(typeof e=="string")try{e=new Wo(e,this.options)}catch{return!1}return fn(e,this.operator,this.semver,this.options)}intersects(e,t){if(!(e instanceof r))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new Bo(e.value,t).test(this.value):e.operator===""?e.value===""?!0:new Bo(this.value,t).test(e.semver):(t=Vo(t),t.includePrerelease&&(this.value==="<0.0.0-0"||e.value==="<0.0.0-0")||!t.includePrerelease&&(this.value.startsWith("<0.0.0")||e.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&e.operator.startsWith(">")||this.operator.startsWith("<")&&e.operator.startsWith("<")||this.semver.version===e.semver.version&&this.operator.includes("=")&&e.operator.includes("=")||fn(this.semver,"<",e.semver,t)&&this.operator.startsWith(">")&&e.operator.startsWith("<")||fn(this.semver,">",e.semver,t)&&this.operator.startsWith("<")&&e.operator.startsWith(">")))}};Yo.exports=dn;var Vo=Pt(),{safeRe:Go,t:Ho}=Ie(),fn=an(),mn=Be(),Wo=H(),Bo=te()});var Je=h((vw,Xo)=>{"use strict";var ld=te(),cd=(r,e,t)=>{try{e=new ld(e,t)}catch{return!1}return e.test(r)};Xo.exports=cd});var Jo=h((Sw,zo)=>{"use strict";var ud=te(),fd=(r,e)=>new ud(r,e).set.map(t=>t.map(n=>n.value).join(" ").trim().split(" "));zo.exports=fd});var Qo=h((xw,Ko)=>{"use strict";var md=H(),dd=te(),pd=(r,e,t)=>{let n=null,i=null,s=null;try{s=new dd(e,t)}catch{return null}return r.forEach(o=>{s.test(o)&&(!n||i.compare(o)===-1)&&(n=o,i=new md(n,t))}),n};Ko.exports=pd});var ea=h((_w,Zo)=>{"use strict";var hd=H(),gd=te(),yd=(r,e,t)=>{let n=null,i=null,s=null;try{s=new gd(e,t)}catch{return null}return r.forEach(o=>{s.test(o)&&(!n||i.compare(o)===1)&&(n=o,i=new hd(n,t))}),n};Zo.exports=yd});var na=h((Ow,ra)=>{"use strict";var pn=H(),Ed=te(),ta=Ye(),wd=(r,e)=>{r=new Ed(r,e);let t=new pn("0.0.0");if(r.test(t)||(t=new pn("0.0.0-0"),r.test(t)))return t;t=null;for(let n=0;n<r.set.length;++n){let i=r.set[n],s=null;i.forEach(o=>{let a=new pn(o.semver.version);switch(o.operator){case">":a.prerelease.length===0?a.patch++:a.prerelease.push(0),a.raw=a.format();case"":case">=":(!s||ta(a,s))&&(s=a);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${o.operator}`)}}),s&&(!t||ta(t,s))&&(t=s)}return t&&r.test(t)?t:null};ra.exports=wd});var sa=h((Cw,ia)=>{"use strict";var bd=te(),Rd=(r,e)=>{try{return new bd(r,e).range||"*"}catch{return null}};ia.exports=Rd});var Gt=h((Aw,ca)=>{"use strict";var $d=H(),la=Xe(),{ANY:vd}=la,Sd=te(),xd=Je(),oa=Ye(),aa=Ft(),_d=jt(),Od=Ut(),Cd=(r,e,t,n)=>{r=new $d(r,n),e=new Sd(e,n);let i,s,o,a,l;switch(t){case">":i=oa,s=_d,o=aa,a=">",l=">=";break;case"<":i=aa,s=Od,o=oa,a="<",l="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(xd(r,e,n))return!1;for(let u=0;u<e.set.length;++u){let c=e.set[u],f=null,d=null;if(c.forEach(p=>{p.semver===vd&&(p=new la(">=0.0.0")),f=f||p,d=d||p,i(p.semver,f.semver,n)?f=p:o(p.semver,d.semver,n)&&(d=p)}),f.operator===a||f.operator===l||(!d.operator||d.operator===a)&&s(r,d.semver))return!1;if(d.operator===l&&o(r,d.semver))return!1}return!0};ca.exports=Cd});var fa=h((Tw,ua)=>{"use strict";var Ad=Gt(),Td=(r,e,t)=>Ad(r,e,">",t);ua.exports=Td});var da=h((kw,ma)=>{"use strict";var kd=Gt(),Pd=(r,e,t)=>kd(r,e,"<",t);ma.exports=Pd});var ga=h((Pw,ha)=>{"use strict";var pa=te(),Ld=(r,e,t)=>(r=new pa(r,t),e=new pa(e,t),r.intersects(e,t));ha.exports=Ld});var Ea=h((Lw,ya)=>{"use strict";var Id=Je(),Nd=ee();ya.exports=(r,e,t)=>{let n=[],i=null,s=null,o=r.sort((c,f)=>Nd(c,f,t));for(let c of o)Id(c,e,t)?(s=c,i||(i=c)):(s&&n.push([i,s]),s=null,i=null);i&&n.push([i,null]);let a=[];for(let[c,f]of n)c===f?a.push(c):!f&&c===o[0]?a.push("*"):f?c===o[0]?a.push(`<=${f}`):a.push(`${c} - ${f}`):a.push(`>=${c}`);let l=a.join(" || "),u=typeof e.raw=="string"?e.raw:String(e);return l.length<u.length?l:e}});var Sa=h((Iw,va)=>{"use strict";var wa=te(),gn=Xe(),{ANY:hn}=gn,Ke=Je(),yn=ee(),Md=(r,e,t={})=>{if(r===e)return!0;r=new wa(r,t),e=new wa(e,t);let n=!1;e:for(let i of r.set){for(let s of e.set){let o=Fd(i,s,t);if(n=n||o!==null,o)continue e}if(n)return!1}return!0},Dd=[new gn(">=0.0.0-0")],ba=[new gn(">=0.0.0")],Fd=(r,e,t)=>{if(r===e)return!0;if(r.length===1&&r[0].semver===hn){if(e.length===1&&e[0].semver===hn)return!0;t.includePrerelease?r=Dd:r=ba}if(e.length===1&&e[0].semver===hn){if(t.includePrerelease)return!0;e=ba}let n=new Set,i,s;for(let p of r)p.operator===">"||p.operator===">="?i=Ra(i,p,t):p.operator==="<"||p.operator==="<="?s=$a(s,p,t):n.add(p.semver);if(n.size>1)return null;let o;if(i&&s){if(o=yn(i.semver,s.semver,t),o>0)return null;if(o===0&&(i.operator!==">="||s.operator!=="<="))return null}for(let p of n){if(i&&!Ke(p,String(i),t)||s&&!Ke(p,String(s),t))return null;for(let g of e)if(!Ke(p,String(g),t))return!1;return!0}let a,l,u,c,f=s&&!t.includePrerelease&&s.semver.prerelease.length?s.semver:!1,d=i&&!t.includePrerelease&&i.semver.prerelease.length?i.semver:!1;f&&f.prerelease.length===1&&s.operator==="<"&&f.prerelease[0]===0&&(f=!1);for(let p of e){if(c=c||p.operator===">"||p.operator===">=",u=u||p.operator==="<"||p.operator==="<=",i){if(d&&p.semver.prerelease&&p.semver.prerelease.length&&p.semver.major===d.major&&p.semver.minor===d.minor&&p.semver.patch===d.patch&&(d=!1),p.operator===">"||p.operator===">="){if(a=Ra(i,p,t),a===p&&a!==i)return!1}else if(i.operator===">="&&!Ke(i.semver,String(p),t))return!1}if(s){if(f&&p.semver.prerelease&&p.semver.prerelease.length&&p.semver.major===f.major&&p.semver.minor===f.minor&&p.semver.patch===f.patch&&(f=!1),p.operator==="<"||p.operator==="<="){if(l=$a(s,p,t),l===p&&l!==s)return!1}else if(s.operator==="<="&&!Ke(s.semver,String(p),t))return!1}if(!p.operator&&(s||i)&&o!==0)return!1}return!(i&&u&&!s&&o!==0||s&&c&&!i&&o!==0||d||f)},Ra=(r,e,t)=>{if(!r)return e;let n=yn(r.semver,e.semver,t);return n>0?r:n<0||e.operator===">"&&r.operator===">="?e:r},$a=(r,e,t)=>{if(!r)return e;let n=yn(r.semver,e.semver,t);return n<0?r:n>0||e.operator==="<"&&r.operator==="<="?e:r};va.exports=Md});var Ht=h((Nw,Oa)=>{"use strict";var En=Ie(),xa=We(),Ud=H(),_a=tn(),jd=ve(),qd=Ks(),Vd=Zs(),Gd=ro(),Hd=so(),Wd=ao(),Bd=co(),Yd=fo(),Xd=po(),zd=ee(),Jd=Eo(),Kd=bo(),Qd=Dt(),Zd=So(),ep=_o(),tp=Ye(),rp=Ft(),np=sn(),ip=on(),sp=Ut(),op=jt(),ap=an(),lp=No(),cp=Xe(),up=te(),fp=Je(),mp=Jo(),dp=Qo(),pp=ea(),hp=na(),gp=sa(),yp=Gt(),Ep=fa(),wp=da(),bp=ga(),Rp=Ea(),$p=Sa();Oa.exports={parse:jd,valid:qd,clean:Vd,inc:Gd,diff:Hd,major:Wd,minor:Bd,patch:Yd,prerelease:Xd,compare:zd,rcompare:Jd,compareLoose:Kd,compareBuild:Qd,sort:Zd,rsort:ep,gt:tp,lt:rp,eq:np,neq:ip,gte:sp,lte:op,cmp:ap,coerce:lp,Comparator:cp,Range:up,satisfies:fp,toComparators:mp,maxSatisfying:dp,minSatisfying:pp,minVersion:hp,validRange:gp,outside:yp,gtr:Ep,ltr:wp,intersects:bp,simplifyRange:Rp,subset:$p,SemVer:Ud,re:En.re,src:En.src,tokens:En.t,SEMVER_SPEC_VERSION:xa.SEMVER_SPEC_VERSION,RELEASE_TYPES:xa.RELEASE_TYPES,compareIdentifiers:_a.compareIdentifiers,rcompareIdentifiers:_a.rcompareIdentifiers}});var Aa=h((Mw,Ca)=>{var vp=Ht();Ca.exports=vp.satisfies(process.version,">=15.7.0")});var ka=h((Dw,Ta)=>{var Sp=Ht();Ta.exports=Sp.satisfies(process.version,">=16.9.0")});var wn=h((Fw,Pa)=>{var xp=Aa(),_p=ka(),Op={ec:["ES256","ES384","ES512"],rsa:["RS256","PS256","RS384","PS384","RS512","PS512"],"rsa-pss":["PS256","PS384","PS512"]},Cp={ES256:"prime256v1",ES384:"secp384r1",ES512:"secp521r1"};Pa.exports=function(r,e){if(!r||!e)return;let t=e.asymmetricKeyType;if(!t)return;let n=Op[t];if(!n)throw new Error(`Unknown key type "${t}".`);if(!n.includes(r))throw new Error(`"alg" parameter for "${t}" key type must be one of: ${n.join(", ")}.`);if(xp)switch(t){case"ec":let i=e.asymmetricKeyDetails.namedCurve,s=Cp[r];if(i!==s)throw new Error(`"alg" parameter "${r}" requires curve "${s}".`);break;case"rsa-pss":if(_p){let o=parseInt(r.slice(-3),10),{hashAlgorithm:a,mgf1HashAlgorithm:l,saltLength:u}=e.asymmetricKeyDetails;if(a!==`sha${o}`||l!==a)throw new Error(`Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" ${r}.`);if(u!==void 0&&u>o>>3)throw new Error(`Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of "alg" ${r}.`)}break}}});var bn=h((Uw,La)=>{var Ap=Ht();La.exports=Ap.satisfies(process.version,"^6.12.0 || >=8.0.0")});var Ma=h((jw,Na)=>{var k=He(),Tp=Jr(),Ia=Kr(),kp=zr(),Pp=Qr(),Lp=wn(),Ip=bn(),Np=Ot(),{KeyObject:Mp,createSecretKey:Dp,createPublicKey:Fp}=require("crypto"),Rn=["RS256","RS384","RS512"],Up=["ES256","ES384","ES512"],$n=["RS256","RS384","RS512"],jp=["HS256","HS384","HS512"];Ip&&(Rn.splice(Rn.length,0,"PS256","PS384","PS512"),$n.splice($n.length,0,"PS256","PS384","PS512"));Na.exports=function(r,e,t,n){typeof t=="function"&&!n&&(n=t,t={}),t||(t={}),t=Object.assign({},t);let i;if(n?i=n:i=function(c,f){if(c)throw c;return f},t.clockTimestamp&&typeof t.clockTimestamp!="number")return i(new k("clockTimestamp must be a number"));if(t.nonce!==void 0&&(typeof t.nonce!="string"||t.nonce.trim()===""))return i(new k("nonce must be a non-empty string"));if(t.allowInvalidAsymmetricKeyTypes!==void 0&&typeof t.allowInvalidAsymmetricKeyTypes!="boolean")return i(new k("allowInvalidAsymmetricKeyTypes must be a boolean"));let s=t.clockTimestamp||Math.floor(Date.now()/1e3);if(!r)return i(new k("jwt must be provided"));if(typeof r!="string")return i(new k("jwt must be a string"));let o=r.split(".");if(o.length!==3)return i(new k("jwt malformed"));let a;try{a=kp(r,{complete:!0})}catch(c){return i(c)}if(!a)return i(new k("invalid token"));let l=a.header,u;if(typeof e=="function"){if(!n)return i(new k("verify must be called asynchronous if secret or public key is provided as a callback"));u=e}else u=function(c,f){return f(null,e)};return u(l,function(c,f){if(c)return i(new k("error in secret or public key callback: "+c.message));let d=o[2].trim()!=="";if(!d&&f)return i(new k("jwt signature is required"));if(d&&!f)return i(new k("secret or public key must be provided"));if(!d&&!t.algorithms)return i(new k('please specify "none" in "algorithms" to verify unsigned tokens'));if(f!=null&&!(f instanceof Mp))try{f=Fp(f)}catch{try{f=Dp(typeof f=="string"?Buffer.from(f):f)}catch{return i(new k("secretOrPublicKey is not valid key material"))}}if(t.algorithms||(f.type==="secret"?t.algorithms=jp:["rsa","rsa-pss"].includes(f.asymmetricKeyType)?t.algorithms=$n:f.asymmetricKeyType==="ec"?t.algorithms=Up:t.algorithms=Rn),t.algorithms.indexOf(a.header.alg)===-1)return i(new k("invalid algorithm"));if(l.alg.startsWith("HS")&&f.type!=="secret")return i(new k(`secretOrPublicKey must be a symmetric key when using ${l.alg}`));if(/^(?:RS|PS|ES)/.test(l.alg)&&f.type!=="public")return i(new k(`secretOrPublicKey must be an asymmetric key when using ${l.alg}`));if(!t.allowInvalidAsymmetricKeyTypes)try{Lp(l.alg,f)}catch(S){return i(S)}let p;try{p=Np.verify(r,a.header.alg,f)}catch(S){return i(S)}if(!p)return i(new k("invalid signature"));let g=a.payload;if(typeof g.nbf<"u"&&!t.ignoreNotBefore){if(typeof g.nbf!="number")return i(new k("invalid nbf value"));if(g.nbf>s+(t.clockTolerance||0))return i(new Tp("jwt not active",new Date(g.nbf*1e3)))}if(typeof g.exp<"u"&&!t.ignoreExpiration){if(typeof g.exp!="number")return i(new k("invalid exp value"));if(s>=g.exp+(t.clockTolerance||0))return i(new Ia("jwt expired",new Date(g.exp*1e3)))}if(t.audience){let S=Array.isArray(t.audience)?t.audience:[t.audience];if(!(Array.isArray(g.aud)?g.aud:[g.aud]).some(function(R){return S.some(function($){return $ instanceof RegExp?$.test(R):$===R})}))return i(new k("jwt audience invalid. expected: "+S.join(" or ")))}if(t.issuer&&(typeof t.issuer=="string"&&g.iss!==t.issuer||Array.isArray(t.issuer)&&t.issuer.indexOf(g.iss)===-1))return i(new k("jwt issuer invalid. expected: "+t.issuer));if(t.subject&&g.sub!==t.subject)return i(new k("jwt subject invalid. expected: "+t.subject));if(t.jwtid&&g.jti!==t.jwtid)return i(new k("jwt jwtid invalid. expected: "+t.jwtid));if(t.nonce&&g.nonce!==t.nonce)return i(new k("jwt nonce invalid. expected: "+t.nonce));if(t.maxAge){if(typeof g.iat!="number")return i(new k("iat required when maxAge is specified"));let S=Pp(t.maxAge,g.iat);if(typeof S>"u")return i(new k('"maxAge" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60'));if(s>=S+(t.clockTolerance||0))return i(new Ia("maxAge exceeded",new Date(S*1e3)))}if(t.complete===!0){let S=a.signature;return i(null,{header:l,payload:g,signature:S})}return i(null,g)})}});var Va=h((qw,qa)=>{var Da=1/0,Ua=9007199254740991,qp=17976931348623157e292,Fa=NaN,Vp="[object Arguments]",Gp="[object Function]",Hp="[object GeneratorFunction]",Wp="[object String]",Bp="[object Symbol]",Yp=/^\s+|\s+$/g,Xp=/^[-+]0x[0-9a-f]+$/i,zp=/^0b[01]+$/i,Jp=/^0o[0-7]+$/i,Kp=/^(?:0|[1-9]\d*)$/,Qp=parseInt;function Zp(r,e){for(var t=-1,n=r?r.length:0,i=Array(n);++t<n;)i[t]=e(r[t],t,r);return i}function eh(r,e,t,n){for(var i=r.length,s=t+(n?1:-1);n?s--:++s<i;)if(e(r[s],s,r))return s;return-1}function th(r,e,t){if(e!==e)return eh(r,rh,t);for(var n=t-1,i=r.length;++n<i;)if(r[n]===e)return n;return-1}function rh(r){return r!==r}function nh(r,e){for(var t=-1,n=Array(r);++t<r;)n[t]=e(t);return n}function ih(r,e){return Zp(e,function(t){return r[t]})}function sh(r,e){return function(t){return r(e(t))}}var Wt=Object.prototype,Sn=Wt.hasOwnProperty,Bt=Wt.toString,oh=Wt.propertyIsEnumerable,ah=sh(Object.keys,Object),lh=Math.max;function ch(r,e){var t=ja(r)||ph(r)?nh(r.length,String):[],n=t.length,i=!!n;for(var s in r)(e||Sn.call(r,s))&&!(i&&(s=="length"||fh(s,n)))&&t.push(s);return t}function uh(r){if(!mh(r))return ah(r);var e=[];for(var t in Object(r))Sn.call(r,t)&&t!="constructor"&&e.push(t);return e}function fh(r,e){return e=e??Ua,!!e&&(typeof r=="number"||Kp.test(r))&&r>-1&&r%1==0&&r<e}function mh(r){var e=r&&r.constructor,t=typeof e=="function"&&e.prototype||Wt;return r===t}function dh(r,e,t,n){r=xn(r)?r:Sh(r),t=t&&!n?Rh(t):0;var i=r.length;return t<0&&(t=lh(i+t,0)),Eh(r)?t<=i&&r.indexOf(e,t)>-1:!!i&&th(r,e,t)>-1}function ph(r){return hh(r)&&Sn.call(r,"callee")&&(!oh.call(r,"callee")||Bt.call(r)==Vp)}var ja=Array.isArray;function xn(r){return r!=null&&yh(r.length)&&!gh(r)}function hh(r){return _n(r)&&xn(r)}function gh(r){var e=vn(r)?Bt.call(r):"";return e==Gp||e==Hp}function yh(r){return typeof r=="number"&&r>-1&&r%1==0&&r<=Ua}function vn(r){var e=typeof r;return!!r&&(e=="object"||e=="function")}function _n(r){return!!r&&typeof r=="object"}function Eh(r){return typeof r=="string"||!ja(r)&&_n(r)&&Bt.call(r)==Wp}function wh(r){return typeof r=="symbol"||_n(r)&&Bt.call(r)==Bp}function bh(r){if(!r)return r===0?r:0;if(r=$h(r),r===Da||r===-Da){var e=r<0?-1:1;return e*qp}return r===r?r:0}function Rh(r){var e=bh(r),t=e%1;return e===e?t?e-t:e:0}function $h(r){if(typeof r=="number")return r;if(wh(r))return Fa;if(vn(r)){var e=typeof r.valueOf=="function"?r.valueOf():r;r=vn(e)?e+"":e}if(typeof r!="string")return r===0?r:+r;r=r.replace(Yp,"");var t=zp.test(r);return t||Jp.test(r)?Qp(r.slice(2),t?2:8):Xp.test(r)?Fa:+r}function vh(r){return xn(r)?ch(r):uh(r)}function Sh(r){return r?ih(r,vh(r)):[]}qa.exports=dh});var Ha=h((Vw,Ga)=>{var xh="[object Boolean]",_h=Object.prototype,Oh=_h.toString;function Ch(r){return r===!0||r===!1||Ah(r)&&Oh.call(r)==xh}function Ah(r){return!!r&&typeof r=="object"}Ga.exports=Ch});var za=h((Gw,Xa)=>{var Wa=1/0,Th=17976931348623157e292,Ba=NaN,kh="[object Symbol]",Ph=/^\s+|\s+$/g,Lh=/^[-+]0x[0-9a-f]+$/i,Ih=/^0b[01]+$/i,Nh=/^0o[0-7]+$/i,Mh=parseInt,Dh=Object.prototype,Fh=Dh.toString;function Uh(r){return typeof r=="number"&&r==Gh(r)}function Ya(r){var e=typeof r;return!!r&&(e=="object"||e=="function")}function jh(r){return!!r&&typeof r=="object"}function qh(r){return typeof r=="symbol"||jh(r)&&Fh.call(r)==kh}function Vh(r){if(!r)return r===0?r:0;if(r=Hh(r),r===Wa||r===-Wa){var e=r<0?-1:1;return e*Th}return r===r?r:0}function Gh(r){var e=Vh(r),t=e%1;return e===e?t?e-t:e:0}function Hh(r){if(typeof r=="number")return r;if(qh(r))return Ba;if(Ya(r)){var e=typeof r.valueOf=="function"?r.valueOf():r;r=Ya(e)?e+"":e}if(typeof r!="string")return r===0?r:+r;r=r.replace(Ph,"");var t=Ih.test(r);return t||Nh.test(r)?Mh(r.slice(2),t?2:8):Lh.test(r)?Ba:+r}Xa.exports=Uh});var Ka=h((Hw,Ja)=>{var Wh="[object Number]",Bh=Object.prototype,Yh=Bh.toString;function Xh(r){return!!r&&typeof r=="object"}function zh(r){return typeof r=="number"||Xh(r)&&Yh.call(r)==Wh}Ja.exports=zh});var tl=h((Ww,el)=>{var Jh="[object Object]";function Kh(r){var e=!1;if(r!=null&&typeof r.toString!="function")try{e=!!(r+"")}catch{}return e}function Qh(r,e){return function(t){return r(e(t))}}var Zh=Function.prototype,Qa=Object.prototype,Za=Zh.toString,eg=Qa.hasOwnProperty,tg=Za.call(Object),rg=Qa.toString,ng=Qh(Object.getPrototypeOf,Object);function ig(r){return!!r&&typeof r=="object"}function sg(r){if(!ig(r)||rg.call(r)!=Jh||Kh(r))return!1;var e=ng(r);if(e===null)return!0;var t=eg.call(e,"constructor")&&e.constructor;return typeof t=="function"&&t instanceof t&&Za.call(t)==tg}el.exports=sg});var nl=h((Bw,rl)=>{var og="[object String]",ag=Object.prototype,lg=ag.toString,cg=Array.isArray;function ug(r){return!!r&&typeof r=="object"}function fg(r){return typeof r=="string"||!cg(r)&&ug(r)&&lg.call(r)==og}rl.exports=fg});var ll=h((Yw,al)=>{var mg="Expected a function",il=1/0,dg=17976931348623157e292,sl=NaN,pg="[object Symbol]",hg=/^\s+|\s+$/g,gg=/^[-+]0x[0-9a-f]+$/i,yg=/^0b[01]+$/i,Eg=/^0o[0-7]+$/i,wg=parseInt,bg=Object.prototype,Rg=bg.toString;function $g(r,e){var t;if(typeof e!="function")throw new TypeError(mg);return r=Og(r),function(){return--r>0&&(t=e.apply(this,arguments)),r<=1&&(e=void 0),t}}function vg(r){return $g(2,r)}function ol(r){var e=typeof r;return!!r&&(e=="object"||e=="function")}function Sg(r){return!!r&&typeof r=="object"}function xg(r){return typeof r=="symbol"||Sg(r)&&Rg.call(r)==pg}function _g(r){if(!r)return r===0?r:0;if(r=Cg(r),r===il||r===-il){var e=r<0?-1:1;return e*dg}return r===r?r:0}function Og(r){var e=_g(r),t=e%1;return e===e?t?e-t:e:0}function Cg(r){if(typeof r=="number")return r;if(xg(r))return sl;if(ol(r)){var e=typeof r.valueOf=="function"?r.valueOf():r;r=ol(e)?e+"":e}if(typeof r!="string")return r===0?r:+r;r=r.replace(hg,"");var t=yg.test(r);return t||Eg.test(r)?wg(r.slice(2),t?2:8):gg.test(r)?sl:+r}al.exports=vg});var yl=h((Xw,gl)=>{var cl=Qr(),Ag=bn(),Tg=wn(),ul=Ot(),kg=Va(),Yt=Ha(),fl=za(),On=Ka(),dl=tl(),ge=nl(),Pg=ll(),{KeyObject:Lg,createSecretKey:Ig,createPrivateKey:Ng}=require("crypto"),pl=["RS256","RS384","RS512","ES256","ES384","ES512","HS256","HS384","HS512","none"];Ag&&pl.splice(3,0,"PS256","PS384","PS512");var Mg={expiresIn:{isValid:function(r){return fl(r)||ge(r)&&r},message:'"expiresIn" should be a number of seconds or string representing a timespan'},notBefore:{isValid:function(r){return fl(r)||ge(r)&&r},message:'"notBefore" should be a number of seconds or string representing a timespan'},audience:{isValid:function(r){return ge(r)||Array.isArray(r)},message:'"audience" must be a string or array'},algorithm:{isValid:kg.bind(null,pl),message:'"algorithm" must be a valid string enum value'},header:{isValid:dl,message:'"header" must be an object'},encoding:{isValid:ge,message:'"encoding" must be a string'},issuer:{isValid:ge,message:'"issuer" must be a string'},subject:{isValid:ge,message:'"subject" must be a string'},jwtid:{isValid:ge,message:'"jwtid" must be a string'},noTimestamp:{isValid:Yt,message:'"noTimestamp" must be a boolean'},keyid:{isValid:ge,message:'"keyid" must be a string'},mutatePayload:{isValid:Yt,message:'"mutatePayload" must be a boolean'},allowInsecureKeySizes:{isValid:Yt,message:'"allowInsecureKeySizes" must be a boolean'},allowInvalidAsymmetricKeyTypes:{isValid:Yt,message:'"allowInvalidAsymmetricKeyTypes" must be a boolean'}},Dg={iat:{isValid:On,message:'"iat" should be a number of seconds'},exp:{isValid:On,message:'"exp" should be a number of seconds'},nbf:{isValid:On,message:'"nbf" should be a number of seconds'}};function hl(r,e,t,n){if(!dl(t))throw new Error('Expected "'+n+'" to be a plain object.');Object.keys(t).forEach(function(i){let s=r[i];if(!s){if(!e)throw new Error('"'+i+'" is not allowed in "'+n+'"');return}if(!s.isValid(t[i]))throw new Error(s.message)})}function Fg(r){return hl(Mg,!1,r,"options")}function Ug(r){return hl(Dg,!0,r,"payload")}var ml={audience:"aud",issuer:"iss",subject:"sub",jwtid:"jti"},jg=["expiresIn","notBefore","noTimestamp","audience","issuer","subject","jwtid"];gl.exports=function(r,e,t,n){typeof t=="function"?(n=t,t={}):t=t||{};let i=typeof r=="object"&&!Buffer.isBuffer(r),s=Object.assign({alg:t.algorithm||"HS256",typ:i?"JWT":void 0,kid:t.keyid},t.header);function o(u){if(n)return n(u);throw u}if(!e&&t.algorithm!=="none")return o(new Error("secretOrPrivateKey must have a value"));if(e!=null&&!(e instanceof Lg))try{e=Ng(e)}catch{try{e=Ig(typeof e=="string"?Buffer.from(e):e)}catch{return o(new Error("secretOrPrivateKey is not valid key material"))}}if(s.alg.startsWith("HS")&&e.type!=="secret")return o(new Error(`secretOrPrivateKey must be a symmetric key when using ${s.alg}`));if(/^(?:RS|PS|ES)/.test(s.alg)){if(e.type!=="private")return o(new Error(`secretOrPrivateKey must be an asymmetric key when using ${s.alg}`));if(!t.allowInsecureKeySizes&&!s.alg.startsWith("ES")&&e.asymmetricKeyDetails!==void 0&&e.asymmetricKeyDetails.modulusLength<2048)return o(new Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${s.alg}`))}if(typeof r>"u")return o(new Error("payload is required"));if(i){try{Ug(r)}catch(u){return o(u)}t.mutatePayload||(r=Object.assign({},r))}else{let u=jg.filter(function(c){return typeof t[c]<"u"});if(u.length>0)return o(new Error("invalid "+u.join(",")+" option for "+typeof r+" payload"))}if(typeof r.exp<"u"&&typeof t.expiresIn<"u")return o(new Error('Bad "options.expiresIn" option the payload already has an "exp" property.'));if(typeof r.nbf<"u"&&typeof t.notBefore<"u")return o(new Error('Bad "options.notBefore" option the payload already has an "nbf" property.'));try{Fg(t)}catch(u){return o(u)}if(!t.allowInvalidAsymmetricKeyTypes)try{Tg(s.alg,e)}catch(u){return o(u)}let a=r.iat||Math.floor(Date.now()/1e3);if(t.noTimestamp?delete r.iat:i&&(r.iat=a),typeof t.notBefore<"u"){try{r.nbf=cl(t.notBefore,a)}catch(u){return o(u)}if(typeof r.nbf>"u")return o(new Error('"notBefore" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60'))}if(typeof t.expiresIn<"u"&&typeof r=="object"){try{r.exp=cl(t.expiresIn,a)}catch(u){return o(u)}if(typeof r.exp>"u")return o(new Error('"expiresIn" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60'))}Object.keys(ml).forEach(function(u){let c=ml[u];if(typeof t[u]<"u"){if(typeof r[c]<"u")return o(new Error('Bad "options.'+u+'" option. The payload already has an "'+c+'" property.'));r[c]=t[u]}});let l=t.encoding||"utf8";if(typeof n=="function")n=n&&Pg(n),ul.createSign({header:s,privateKey:e,payload:r,encoding:l}).once("error",n).once("done",function(u){if(!t.allowInsecureKeySizes&&/^(?:RS|PS)/.test(s.alg)&&u.length<256)return n(new Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${s.alg}`));n(null,u)});else{let u=ul.sign({header:s,payload:r,secret:e,encoding:l});if(!t.allowInsecureKeySizes&&/^(?:RS|PS)/.test(s.alg)&&u.length<256)throw new Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${s.alg}`);return u}}});var wl=h((zw,El)=>{El.exports={decode:zr(),verify:Ma(),sign:yl(),JsonWebTokenError:He(),NotBeforeError:Jr(),TokenExpiredError:Kr()}});(function(){Yn().config(Object.assign({},zn(),Kn()(process.argv)))})();var Ql=require("fs"),Zl=require("path");var Jl=N(lt());var re=N(require("fs")),vr=N(require("path")),di=N(require("os"));var Dc=process.stdout.isTTY===!0&&!process.env.NO_COLOR,me=r=>Dc?r:"",_=me("\x1B[32m"),P=me("\x1B[33m"),T=me("\x1B[36m"),de=me("\x1B[35m"),y=me("\x1B[31m"),E=me("\x1B[2m"),K=me("\x1B[1m"),m=me("\x1B[0m");var ci="app.boxel.realms";var Fc={"anthropic/claude-3.5-sonnet":"Anthropic: Claude 3.5 Sonnet","anthropic/claude-3.7-sonnet":"Anthropic: Claude 3.7 Sonnet","anthropic/claude-3.7-sonnet:thinking":"Anthropic: Claude 3.7 Sonnet (thinking)","anthropic/claude-haiku-4.5":"Anthropic: Claude Haiku 4.5","anthropic/claude-sonnet-4":"Anthropic: Claude Sonnet 4","anthropic/claude-sonnet-4.5":"Anthropic: Claude Sonnet 4.5","anthropic/claude-sonnet-4.6":"Anthropic: Claude Sonnet 4.6","anthropic/claude-opus-4.1":"Anthropic: Claude Opus 4.1","deepseek/deepseek-chat-v3-0324":"DeepSeek: DeepSeek V3 0324","google/gemini-2.5-pro":"Google: Gemini 2.5 Pro","google/gemini-2.5-flash-lite":"Google: Gemini 2.5 Flash Lite","google/gemini-2.5-flash":"Google: Gemini 2.5 Flash","meta-llama/llama-3.2-3b-instruct":"Meta: Llama 3.2 3B Instruct","openai/gpt-4.1-nano":"OpenAI: GPT-4.1 Nano","openai/gpt-4.1-mini":"OpenAI: GPT-4.1 Mini","openai/gpt-4.1":"OpenAI: GPT-4.1","openai/gpt-4o":"OpenAI: GPT-4o","openai/gpt-4o-mini":"OpenAI: GPT-4o-mini","openai/gpt-5-nano":"OpenAI: GPT-5 Nano","openai/gpt-5-mini":"OpenAI: GPT-5 Mini","openai/gpt-5":"OpenAI: GPT-5","openai/gpt-oss-20b":"OpenAI: GPT OSS 20B"},Ly=Object.keys(Fc);function C(r){return r.endsWith("/")?r:`${r}/`}async function ui(r,e,t){let n=await fetch(new URL("_matrix/client/v3/login",r).href,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({identifier:{type:"m.id.user",user:e},password:t,type:"m.login.password"})}),i=await n.json();if(!n.ok)throw new Error(`Matrix login failed: ${n.status} ${JSON.stringify(i)}`);return{accessToken:i.access_token,deviceId:i.device_id,userId:i.user_id,matrixUrl:r}}async function Uc(r){let e=await fetch(new URL(`_matrix/client/v3/user/${encodeURIComponent(r.userId)}/openid/request_token`,r.matrixUrl).href,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r.accessToken}`},body:"{}"});if(!e.ok){let t=await e.text();throw new Error(`OpenID token request failed: ${e.status} ${t}`)}return await e.json()}async function Er(r,e){let t=await Uc(r),n=`${e.replace(/\/$/,"")}/_server-session`,i=await fetch(n,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(t)});if(!i.ok){let o=await i.text();throw new Error(`Realm server session failed: ${i.status} ${o}`)}let s=i.headers.get("Authorization");if(!s)throw new Error("Realm server session response did not include an Authorization header");return s}async function wr(r,e){let t=`${r.replace(/\/$/,"")}/_realm-auth`,n=await fetch(t,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",Authorization:e}});if(!n.ok){let i=await n.text();throw new Error(`Realm auth lookup failed: ${n.status} ${i}`)}return await n.json()}function br(r){return new URL(`_matrix/client/v3/user/${encodeURIComponent(r.userId)}/account_data/${ci}`,r.matrixUrl).href}async function ct(r){try{let e=await fetch(br(r),{headers:{Authorization:`Bearer ${r.accessToken}`}});if(!e.ok)return[];let t=await e.json();return Array.isArray(t.realms)?[...t.realms]:[]}catch{return[]}}async function fi(r,e){let t=await ct(r);if(!t.includes(e)){t.push(e);let n=await fetch(br(r),{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r.accessToken}`},body:JSON.stringify({realms:t})});if(!n.ok){let i=await n.text();throw new Error(`Failed to update Matrix account data: ${n.status} ${i}`)}}}async function mi(r,e){let t=C(e),n=await ct(r),i=n.filter(o=>C(o)!==t);if(i.length===n.length)return!1;let s=await fetch(br(r),{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r.accessToken}`},body:JSON.stringify({realms:i})});if(!s.ok){let o=await s.text();throw new Error(`Failed to update Matrix account data: ${s.status} ${o}`)}return!0}var jc=vr.join(di.homedir(),".boxel-cli"),qc="profiles.json",L="No active profile. Run `boxel profile add` to create one.";function ut(r){return r.endsWith(":stack.cards")?"staging":r.endsWith(":boxel.ai")?"production":r.endsWith(":localhost")?"local":"unknown"}function _e(r){let e=r.match(/^@([^:]+):/);return e?e[1]:r}function ft(r){let e=r.match(/:([^:]+)$/);return e?e[1]:"unknown"}function ie(r){let e=_e(r),t=ft(r);return`${E}[${m}${T}${e}${m} ${E}\xB7${m} ${de}${t}${m}${E}]${m}`}var $r=class{config;configDir;profilesFile;constructor(e){this.configDir=e||jc,this.profilesFile=vr.join(this.configDir,qc),this.config=this.loadConfig()}ensureConfigDir(){re.existsSync(this.configDir)||re.mkdirSync(this.configDir,{recursive:!0})}loadConfig(){let e={profiles:{},activeProfile:null};if(re.existsSync(this.profilesFile))try{let t=re.readFileSync(this.profilesFile,"utf-8"),n=JSON.parse(t);if(n&&typeof n=="object"&&!Array.isArray(n)){let i=n,s=i.profiles&&typeof i.profiles=="object"&&!Array.isArray(i.profiles)?i.profiles:null,o=i.activeProfile===null||typeof i.activeProfile=="string"?i.activeProfile:null;if(s)return{profiles:s,activeProfile:o}}}catch{}return e}saveConfig(){this.ensureConfigDir(),re.writeFileSync(this.profilesFile,JSON.stringify(this.config,null,2),{mode:384});try{re.chmodSync(this.profilesFile,384)}catch{}}listProfiles(){return Object.keys(this.config.profiles)}getProfile(e){return this.config.profiles[e]}getActiveProfileId(){return this.config.activeProfile}getActiveProfile(){let e=this.config.activeProfile;if(!e)return null;let t=this.config.profiles[e];return t?{id:e,profile:t}:null}async addProfile(e,t,n,i,s){let o=ut(e),a=_e(e);if(o==="unknown"&&(!i||!s))throw new Error(`Unknown domain in Matrix ID "${e}". You must provide explicit --matrix-url and --realm-server-url for non-standard domains.`);let l=o==="production"?"https://matrix.boxel.ai":"https://matrix-staging.stack.cards",u=o==="production"?"https://app.boxel.ai/":"https://realms-staging.stack.cards/",c=ft(e),f={displayName:n||`${a} \xB7 ${c}`,matrixUrl:i||l,realmServerUrl:s||u,password:t};this.config.profiles[e]=f,this.config.activeProfile||(this.config.activeProfile=e),this.saveConfig()}async removeProfile(e){if(!this.config.profiles[e])return!1;if(delete this.config.profiles[e],this.config.activeProfile===e){let t=Object.keys(this.config.profiles);this.config.activeProfile=t.length>0?t[0]:null}return this.saveConfig(),!0}switchProfile(e){return this.config.profiles[e]?(this.config.activeProfile=e,this.saveConfig(),!0):!1}async getActiveCredentials(){let e=this.getActiveProfile();if(e&&e.profile.password)return{matrixUrl:e.profile.matrixUrl,username:_e(e.id),password:e.profile.password,realmServerUrl:e.profile.realmServerUrl,profileId:e.id};let t=process.env.MATRIX_URL,n=process.env.MATRIX_USERNAME,i=process.env.MATRIX_PASSWORD,s=process.env.REALM_SERVER_URL;return t&&n&&i&&s?{matrixUrl:t,username:n,password:i,realmServerUrl:s,profileId:null}:null}async getPassword(e){return this.config.profiles[e]?.password||null}async updatePassword(e,t){return this.config.profiles[e]?(this.config.profiles[e].password=t,this.saveConfig(),!0):!1}updateDisplayName(e,t){return this.config.profiles[e]?(this.config.profiles[e].displayName=t,this.saveConfig(),!0):!1}updateUrls(e,t){let n=this.config.profiles[e];if(!n)return!1;let i=!1;return t.matrixUrl&&t.matrixUrl!==n.matrixUrl&&(n.matrixUrl=t.matrixUrl,i=!0),t.realmServerUrl&&t.realmServerUrl!==n.realmServerUrl&&(n.realmServerUrl=t.realmServerUrl,i=!0),i&&(n.realmTokens=void 0,n.realmServerToken=void 0,this.saveConfig()),i}setRealmToken(e,t){let n=this.getActiveProfile();n&&(n.profile.realmTokens||(n.profile.realmTokens={}),n.profile.realmTokens[e]=t,this.saveConfig())}getRealmToken(e){return this.getActiveProfile()?.profile.realmTokens?.[e]}setRealmServerToken(e){let t=this.getActiveProfile();t&&(t.profile.realmServerToken=e,this.saveConfig())}getRealmServerToken(){return this.getActiveProfile()?.profile.realmServerToken}async loginToMatrix(){let e=this.getActiveProfile();if(!e)throw new Error("No active profile");let{id:t,profile:n}=e,i=_e(t);return ui(n.matrixUrl,i,n.password)}async getOrRefreshServerToken(){let e=this.getRealmServerToken();if(e)return e;let t=await this.loginToMatrix(),i=this.getActiveProfile().profile.realmServerUrl.replace(/\/$/,""),s=await Er(t,i);return this.setRealmServerToken(s),s}async refreshServerToken(){let e=await this.loginToMatrix(),n=this.getActiveProfile().profile.realmServerUrl.replace(/\/$/,""),i=await Er(e,n);return this.setRealmServerToken(i),i}findRealmTokenForUrl(e){let n=this.getActiveProfile()?.profile.realmTokens;if(n){for(let[i,s]of Object.entries(n))if(e.startsWith(i)&&s)return s}}async fetchAndStoreAllRealmTokens(){let e=await this.getOrRefreshServerToken(),n=this.getActiveProfile().profile.realmServerUrl.replace(/\/$/,""),i=await wr(n,e);for(let[s,o]of Object.entries(i))this.setRealmToken(s,o)}async getRealmTokenForUrl(e){let t=this.findRealmTokenForUrl(e);if(t)return t;try{await this.fetchAndStoreAllRealmTokens()}catch{return}return this.findRealmTokenForUrl(e)}buildHeaders(e,t,n){let i=e instanceof Request?new Headers(e.headers):new Headers,s=new Headers(t?.headers);for(let[o,a]of s)i.set(o,a);return i.has("Authorization")||i.set("Authorization",n),i}async authedRealmFetch(e,t){let n=e instanceof Request?e.url:e instanceof URL?e.href:e,i=await this.getRealmTokenForUrl(n);if(i){let l=this.buildHeaders(e,t,i),u=await fetch(e,{...t,headers:l});if(u.status!==401)return u}let s=this.getActiveProfile();if(s&&(s.profile.realmTokens={},s.profile.realmServerToken=void 0,this.saveConfig()),await this.fetchAndStoreAllRealmTokens(),i=this.findRealmTokenForUrl(n),!i)throw new Error(`No realm token available for ${n}. The realm may not be accessible.`);let o=this.buildHeaders(e,t,i);return await fetch(e,{...t,headers:o})}async authedRealmServerFetch(e,t){let n=await this.getOrRefreshServerToken(),i=this.buildHeaders(e,t,n),s=await fetch(e,{...t,headers:i});return s.status===401&&(n=await this.refreshServerToken(),i=this.buildHeaders(e,t,n),s=await fetch(e,{...t,headers:i})),s}async fetchAndStoreRealmToken(e,t){let i=this.getActiveProfile().profile.realmServerUrl.replace(/\/$/,""),o=(await wr(i,t))[e];return o&&this.setRealmToken(e,o),o}async addToUserRealms(e){let t=await this.loginToMatrix();await fi(t,e)}async removeFromUserRealms(e){let t=await this.loginToMatrix();return mi(t,e)}async getUserRealms(){let e=await this.loginToMatrix();return ct(e)}async migrateFromEnv(){let e=process.env.MATRIX_URL,t=process.env.MATRIX_USERNAME,n=process.env.MATRIX_PASSWORD,i=process.env.REALM_SERVER_URL;if(!e||!t||!n||!i)return null;let o=e.includes("boxel.ai")?"boxel.ai":"stack.cards",a=`@${t}:${o}`;return this.config.profiles[a]?(this.config.profiles[a].password!==n&&(this.config.profiles[a].password=n,this.saveConfig()),{profileId:a,created:!1}):(await this.addProfile(a,n,void 0,e,i),{profileId:a,created:!0})}printStatus(){let e=this.getActiveProfile();e?(console.log(`
|
|
32
32
|
${K}Active Profile:${m} ${ie(e.id)}`),console.log(` ${E}Display Name:${m} ${e.profile.displayName}`),console.log(` ${E}Matrix URL:${m} ${e.profile.matrixUrl}`),console.log(` ${E}Realm Server:${m} ${e.profile.realmServerUrl}`)):process.env.MATRIX_USERNAME?(console.log(`
|
|
33
33
|
${K}Using environment variables${m} (no profile active)`),console.log(` ${E}Username:${m} ${process.env.MATRIX_USERNAME}`)):(console.log(`
|
|
34
|
-
${P}No active profile and no environment variables set.${m}`),console.log(`Run ${T}boxel profile add${m} to create a profile.`))}},Rr=null;function O(){return Rr||(Rr=new $r),Rr}var Sr=N(require("readline")),
|
|
34
|
+
${P}No active profile and no environment variables set.${m}`),console.log(`Run ${T}boxel profile add${m} to create a profile.`))}},Rr=null;function O(){return Rr||(Rr=new $r),Rr}var Sr=N(require("readline")),pi=require("stream");function J(r){let e=Sr.createInterface({input:process.stdin,output:process.stdout});return new Promise(t=>{e.question(r,n=>{e.close(),t(n.trim())})})}function xr(r){let e=new pi.Writable({write:(n,i,s)=>s()}),t=Sr.createInterface({input:process.stdin,output:e,terminal:!0});return new Promise((n,i)=>{let s=process.stdin,o=s.readableFlowing;s.isTTY&&s.setRawMode(!0);let a=()=>{s.removeListener("data",l),s.isTTY&&s.setRawMode(!1),t.close(),o||s.pause()},l=c=>{try{let f=c.toString().split("\x1B[200~").join("").split("\x1B[201~").join("");for(let d of f)if(d===`
|
|
35
35
|
`||d==="\r"){a(),process.stdout.write(`
|
|
36
|
-
`),n(u);return}else d===""?(a(),process.exit()):d==="\x7F"||d==="\b"?u.length>0&&(u=u.slice(0,-1),process.stdout.write("\b \b")):d>=" "&&(u+=d,process.stdout.write("*"))}catch(f){a(),i(f)}},u="";try{process.stdout.write(r),s.on("data",l),s.resume()}catch(c){a(),i(c)}})}async function
|
|
37
|
-
Available profiles:`),await gi(n),process.exit(1)),await
|
|
36
|
+
`),n(u);return}else d===""?(a(),process.exit()):d==="\x7F"||d==="\b"?u.length>0&&(u=u.slice(0,-1),process.stdout.write("\b \b")):d>=" "&&(u+=d,process.stdout.write("*"))}catch(f){a(),i(f)}},u="";try{process.stdout.write(r),s.on("data",l),s.resume()}catch(c){a(),i(c)}})}async function pe(r){let e=process.env.BOXEL_REALM_SECRET_SEED;if(e)return e;if(r){if(!process.stdin.isTTY)throw new Error("Cannot prompt for realm secret seed: stdin is not a TTY. Set BOXEL_REALM_SECRET_SEED in the environment instead.");return xr("Realm secret seed: ")}}var _r={staging:{domain:"stack.cards",matrixUrl:"https://matrix-staging.stack.cards",realmServerUrl:"https://realms-staging.stack.cards/"},production:{domain:"boxel.ai",matrixUrl:"https://matrix.boxel.ai",realmServerUrl:"https://app.boxel.ai/"},local:{domain:"localhost",matrixUrl:"http://localhost:8008",realmServerUrl:"http://localhost:4201/"}};function mt(r,e){let t=r.trim(),n;try{n=new URL(t)}catch{console.error(`${y}Error:${m} ${e} "${r}" is not a valid URL.`),process.exit(1)}return n.protocol!=="http:"&&n.protocol!=="https:"&&(console.error(`${y}Error:${m} ${e} "${r}" must use http:// or https://.`),process.exit(1)),t}function Vc(r){return r.toLowerCase().replace(/\//g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-+|-+$/g,"")}function hi(){let r=process.env.BOXEL_ENVIRONMENT;if(!r||!r.trim())return null;let e=Vc(r);return e||(console.error(`${y}Error:${m} BOXEL_ENVIRONMENT="${r}" contains no slug characters (expected letters, digits, or "-").`),process.exit(1)),{domain:`${e}.localhost`,matrixUrl:`http://matrix.${e}.localhost`,realmServerUrl:`http://realm-server.${e}.localhost/`}}async function yi(r,e,t){let n=O();switch(r){case"list":await gi(n);break;case"add":{let i=t?.password||process.env.BOXEL_PASSWORD;if(t?.user&&i){let s=t.matrixUrl?mt(t.matrixUrl,"--matrix-url"):void 0,o=t.realmServerUrl?mt(t.realmServerUrl,"--realm-server-url"):void 0,c=!(ut(t.user)!=="unknown")&&(!s||!o)?hi():null;c&&console.log(`${E}Using BOXEL_ENVIRONMENT=${process.env.BOXEL_ENVIRONMENT}${m}`),await Yc(n,t.user,i,t.name,s??c?.matrixUrl,o??c?.realmServerUrl)}else await Hc(n,hi());break}case"switch":e||(console.error(`${y}Error:${m} Please specify a profile to switch to.`),console.log("Usage: boxel profile switch <profile-id>"),console.log(`
|
|
37
|
+
Available profiles:`),await gi(n),process.exit(1)),await Wc(n,e);break;case"remove":e||(console.error(`${y}Error:${m} Please specify a profile to remove.`),process.exit(1)),await Bc(n,e);break;case"migrate":await Xc(n);break;default:n.printStatus(),console.log(`
|
|
38
38
|
${E}Commands:${m}`),console.log(` ${T}boxel profile list${m} List all profiles`),console.log(` ${T}boxel profile add${m} Add a new profile`),console.log(` ${T}boxel profile switch${m} Switch active profile`),console.log(` ${T}boxel profile remove${m} Remove a profile`),console.log(` ${T}boxel profile migrate${m} Import from .env file`)}}async function gi(r){let e=r.listProfiles(),t=r.getActiveProfileId();if(e.length===0){console.log(`
|
|
39
39
|
${P}No profiles configured.${m}`),console.log(`Run ${T}boxel profile add${m} to create one.`);return}console.log(`
|
|
40
40
|
${K}Saved Profiles:${m}
|
|
41
|
-
`);for(let n of e){let i=r.getProfile(n),s=n===t,o=ut(n),a=s?`${_}\u2605${m} `:" ",l=ft(n),u=o==="production"?de:T;console.log(`${a}${K}${n}${m}`),console.log(` ${E}Name:${m} ${i.displayName}`),console.log(` ${E}Environment:${m} ${u}${l}${m}`),console.log(` ${E}Realm Server:${m} ${i.realmServerUrl}`),console.log("")}t&&console.log(`${E}\u2605 = active profile${m}`)}async function
|
|
42
|
-
Choice [1/2/3/4]: `);if(r==="4"){let e=await J("Matrix server URL: ");e||(console.error(`${
|
|
41
|
+
`);for(let n of e){let i=r.getProfile(n),s=n===t,o=ut(n),a=s?`${_}\u2605${m} `:" ",l=ft(n),u=o==="production"?de:T;console.log(`${a}${K}${n}${m}`),console.log(` ${E}Name:${m} ${i.displayName}`),console.log(` ${E}Environment:${m} ${u}${l}${m}`),console.log(` ${E}Realm Server:${m} ${i.realmServerUrl}`),console.log("")}t&&console.log(`${E}\u2605 = active profile${m}`)}async function Gc(){console.log("Which environment?"),console.log(` ${T}1${m}) Staging (realms-staging.stack.cards)`),console.log(` ${de}2${m}) Production (app.boxel.ai)`),console.log(` ${_}3${m}) Local (localhost:4201)`),console.log(` ${P}4${m}) Custom (enter your own URLs)`);let r=await J(`
|
|
42
|
+
Choice [1/2/3/4]: `);if(r==="4"){let e=await J("Matrix server URL: ");e||(console.error(`${y}Error:${m} Matrix server URL is required.`),process.exit(1));let t=mt(e,"Matrix server URL"),n=await J("Realm server URL: ");n||(console.error(`${y}Error:${m} Realm server URL is required.`),process.exit(1));let i=mt(n,"Realm server URL"),s=new URL(t).hostname||"custom";return{domain:await J(`Domain for Matrix ID [${s}]: `)||s,matrixUrl:t,realmServerUrl:i}}return r==="3"?{..._r.local}:r==="2"?{..._r.production}:{..._r.staging}}async function Hc(r,e){console.log(`
|
|
43
43
|
${K}Add New Profile${m}
|
|
44
|
-
`);let t,n,i;if(e)console.log(`${E}Using BOXEL_ENVIRONMENT=${process.env.BOXEL_ENVIRONMENT}${m}`),t=e.domain,n=e.matrixUrl,i=e.realmServerUrl;else{let f=await
|
|
45
|
-
Enter your Boxel username (without @ or domain)`),console.log(`${E}Example: ctse, aallen90${m}`);let s=await J("Username: ");s||(console.error(`${
|
|
46
|
-
${P}Profile ${o} already exists.${m}`),(await J("Overwrite? [y/N]: ")).toLowerCase()!=="y")){console.log("Cancelled.");return}let a=await xr("Password: ");a||(console.error(`${
|
|
47
|
-
${_}\u2713${m} Profile created: ${ie(o)}`),r.getActiveProfileId()===o?console.log(`${E}This profile is now active.${m}`):(await J("Switch to this profile now? [Y/n]: ")).toLowerCase()!=="n"&&(r.switchProfile(o),console.log(`${_}\u2713${m} Switched to ${ie(o)}`))}async function
|
|
48
|
-
Available profiles:`);for(let s of t)console.log(` ${s}`);process.exit(1)}else if(i.length===1)n=i[0];else{console.error(`${
|
|
49
|
-
Matching profiles:`);for(let s of i)console.log(` ${s}`);process.exit(1)}}r.switchProfile(n)?console.log(`${_}\u2713${m} Switched to ${ie(n)}`):(console.error(`${
|
|
44
|
+
`);let t,n,i;if(e)console.log(`${E}Using BOXEL_ENVIRONMENT=${process.env.BOXEL_ENVIRONMENT}${m}`),t=e.domain,n=e.matrixUrl,i=e.realmServerUrl;else{let f=await Gc();t=f.domain,n=f.matrixUrl,i=f.realmServerUrl}console.log(`
|
|
45
|
+
Enter your Boxel username (without @ or domain)`),console.log(`${E}Example: ctse, aallen90${m}`);let s=await J("Username: ");s||(console.error(`${y}Error:${m} Username is required.`),process.exit(1));let o=`@${s}:${t}`;if(r.getProfile(o)&&(console.log(`
|
|
46
|
+
${P}Profile ${o} already exists.${m}`),(await J("Overwrite? [y/N]: ")).toLowerCase()!=="y")){console.log("Cancelled.");return}let a=await xr("Password: ");a||(console.error(`${y}Error:${m} Password is required.`),process.exit(1));let l=`${s} \xB7 ${t}`,c=await J(`Display name [${l}]: `)||l;await r.addProfile(o,a,c,n,i),console.log(`
|
|
47
|
+
${_}\u2713${m} Profile created: ${ie(o)}`),r.getActiveProfileId()===o?console.log(`${E}This profile is now active.${m}`):(await J("Switch to this profile now? [Y/n]: ")).toLowerCase()!=="n"&&(r.switchProfile(o),console.log(`${_}\u2713${m} Switched to ${ie(o)}`))}async function Wc(r,e){let t=r.listProfiles(),n=e;if(!t.includes(e)){let i=t.filter(s=>{let o=_e(s);return s.includes(e)||o===e});if(i.length===0){console.error(`${y}Error:${m} Profile not found: ${e}`),console.log(`
|
|
48
|
+
Available profiles:`);for(let s of t)console.log(` ${s}`);process.exit(1)}else if(i.length===1)n=i[0];else{console.error(`${y}Error:${m} Ambiguous profile: ${e}`),console.log(`
|
|
49
|
+
Matching profiles:`);for(let s of i)console.log(` ${s}`);process.exit(1)}}r.switchProfile(n)?console.log(`${_}\u2713${m} Switched to ${ie(n)}`):(console.error(`${y}Error:${m} Failed to switch profile.`),process.exit(1))}async function Bc(r,e){if(r.getProfile(e)||(console.error(`${y}Error:${m} Profile not found: ${e}`),process.exit(1)),(await J(`Remove profile ${e}? [y/N]: `)).toLowerCase()!=="y"){console.log("Cancelled.");return}if(await r.removeProfile(e)){console.log(`${_}\u2713${m} Profile removed.`);let i=r.getActiveProfileId();i&&console.log(`Active profile is now: ${ie(i)}`)}else console.error(`${y}Error:${m} Failed to remove profile.`),process.exit(1)}async function Yc(r,e,t,n,i,s){if((!e.startsWith("@")||!e.includes(":"))&&(console.error(`${y}Error:${m} Invalid Matrix ID format. Expected @user:domain`),process.exit(1)),r.getProfile(e)){console.log(`${P}Profile ${e} already exists. Updating password.${m}`),await r.updatePassword(e,t),n&&r.updateDisplayName(e,n),(i||s)&&r.updateUrls(e,{matrixUrl:i,realmServerUrl:s})&&console.log(`${E}Updated server URLs and cleared cached realm tokens.${m}`),console.log(`${_}\u2713${m} Profile updated: ${ie(e)}`);return}try{await r.addProfile(e,t,n,i,s)}catch(a){console.error(`${y}Error:${m} ${a instanceof Error?a.message:String(a)}`),process.exit(1)}console.log(`${_}\u2713${m} Profile created: ${ie(e)}`),r.getActiveProfileId()!==e&&console.log(`${E}Use 'boxel profile switch ${e}' to switch to this profile.${m}`)}async function Xc(r){console.log(`
|
|
50
50
|
${K}Migrate from .env${m}
|
|
51
51
|
`);let e=process.env.MATRIX_URL,t=process.env.MATRIX_USERNAME,n=process.env.MATRIX_PASSWORD,i=process.env.REALM_SERVER_URL;if(!e||!t||!n||!i){console.log(`${P}No complete credentials found in environment variables.${m}`),console.log(`
|
|
52
52
|
Required variables: MATRIX_URL, MATRIX_USERNAME, MATRIX_PASSWORD, REALM_SERVER_URL`);return}let s=await r.migrateFromEnv();s?s.created?(console.log(`${_}\u2713${m} Created profile: ${ie(s.profileId)}`),console.log(`
|
|
53
53
|
${E}You can now remove credentials from .env if desired.${m}`)):(console.log(`${P}Profile ${ie(s.profileId)} already exists.${m} Password has been updated if it changed.`),console.log(`
|
|
54
|
-
${E}Use 'boxel profile add -u ${s.profileId} -p <password>' to update other fields.${m}`)):console.log(`${P}Migration failed.${m}`)}var
|
|
54
|
+
${E}Use 'boxel profile add -u ${s.profileId} -p <password>' to update other fields.${m}`)):console.log(`${P}Migration failed.${m}`)}var pt=!1,zc=console.log.bind(console),Jc=console.info.bind(console),Kc=console.debug.bind(console);function ht(r){if(r!==pt)if(pt=r,pt){let e=()=>{};console.log=e,console.info=e,console.debug=e}else console.log=zc,console.info=Jc,console.debug=Kc}var M={info(...r){pt||process.stderr.write(r.map(dt).join(" ")+`
|
|
55
55
|
`)},warn(...r){process.stderr.write(r.map(dt).join(" ")+`
|
|
56
56
|
`)},error(...r){process.stderr.write(r.map(dt).join(" ")+`
|
|
57
57
|
`)},output(...r){process.stdout.write(r.map(dt).join(" ")+`
|
|
58
|
-
`)}};function dt(r){if(typeof r=="string")return r;if(r instanceof Error)return r.stack??r.message;try{return JSON.stringify(r)}catch{return String(r)}}async function Kc(r,e,t){let n=t?.profileManager??O();if(!n.getActiveProfile())throw new Error("No active profile. Run `boxel profile add` to create one.");let s=new URL(e,C(r)).href,o;try{o=await n.authedRealmFetch(s,{method:"GET",headers:{Accept:"*/*"}})}catch(l){return{ok:!1,error:l instanceof Error?l.message:String(l)}}if(!o.ok){let l=await o.text().catch(()=>"(no body)");return{ok:!1,status:o.status,error:`HTTP ${o.status}: ${l.slice(0,300)}`}}let a=await o.text();return{ok:!0,status:o.status,content:a}}function Ei(r){r.command("read-transpiled").description("Debugging tool ONLY for investigating runtime errors in .gts modules you've written. Use when an eval or instantiate error reports a line/column number \u2014 those line numbers refer to the transpiled output, not your .gts source, so fetching the transpiled output is how you locate the offending source construct. Never use the transpiled output as a reference for how to write code: do not copy its patterns (setComponentTemplate, precompileTemplate, wire-format templates, base64 CSS imports) into source. Always write idiomatic Ember / <template>-tag / CardDef source.").argument("<path>","Realm-relative module path. The .gts extension is optional \u2014 the realm accepts either form.").requiredOption("--realm <realm-url>","The realm URL to fetch from").option("--json","Output raw JSON response").action(async(e,t)=>{let n;try{n=await Kc(t.realm,e)}catch(i){console.error(`${g}Error:${m} ${i instanceof Error?i.message:String(i)}`),process.exit(1)}t.json?M.output(JSON.stringify(n,null,2)):n.ok?M.output(n.content??""):(console.error(`${E}Status:${m} ${n.status??"(no status)"}`),console.error(`${g}Error:${m} ${n.error}`)),n.ok||process.exit(1)})}async function Qc(r,e){let t=e?.profileManager??O();if(!t.getActiveProfile())return{ok:!1,error:L};let i=e?.cancelPending??!1,s=`${C(r)}_cancel-indexing-job`;try{let o=await t.authedRealmFetch(s,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({cancelPending:i})});if(!o.ok){let a=await o.text().catch(()=>"(no body)");return{ok:!1,error:`HTTP ${o.status}: ${a.slice(0,300)}`}}return{ok:!0}}catch(o){return{ok:!1,error:o instanceof Error?o.message:String(o)}}}function wi(r){r.command("cancel-indexing").description("Cancel running indexing jobs for a realm (use --cancel-pending to also cancel queued jobs)").requiredOption("--realm <realm-url>","URL of the realm to cancel indexing for").option("--cancel-pending","Also cancel queued/pending indexing jobs (default: cancel running only)").option("--json","Output raw JSON response").action(async e=>{let t=await Qc(e.realm,{cancelPending:e.cancelPending});if(e.json)M.output(JSON.stringify(t,null,2)),t.ok||process.exit(1);else if(t.ok){let n=e.cancelPending?"running and pending":"running";console.log(`${_}Cancelled ${n} indexing jobs for ${e.realm}${m}`)}else console.error(`${g}Error:${m} ${t.error}`),process.exit(1)})}var Zc=Object.freeze({a:"https://boxel-images.boxel.ai/icons/Letter-a.png",b:"https://boxel-images.boxel.ai/icons/Letter-b.png",c:"https://boxel-images.boxel.ai/icons/Letter-c.png",d:"https://boxel-images.boxel.ai/icons/Letter-d.png",e:"https://boxel-images.boxel.ai/icons/Letter-e.png",f:"https://boxel-images.boxel.ai/icons/Letter-f.png",g:"https://boxel-images.boxel.ai/icons/Letter-g.png",h:"https://boxel-images.boxel.ai/icons/Letter-h.png",i:"https://boxel-images.boxel.ai/icons/Letter-i.png",j:"https://boxel-images.boxel.ai/icons/Letter-j.png",k:"https://boxel-images.boxel.ai/icons/Letter-k.png",l:"https://boxel-images.boxel.ai/icons/Letter-l.png",m:"https://boxel-images.boxel.ai/icons/Letter-m.png",n:"https://boxel-images.boxel.ai/icons/Letter-n.png",o:"https://boxel-images.boxel.ai/icons/Letter-o.png",p:"https://boxel-images.boxel.ai/icons/Letter-p.png",q:"https://boxel-images.boxel.ai/icons/Letter-q.png",r:"https://boxel-images.boxel.ai/icons/Letter-r.png",s:"https://boxel-images.boxel.ai/icons/Letter-s.png",t:"https://boxel-images.boxel.ai/icons/Letter-t.png",u:"https://boxel-images.boxel.ai/icons/Letter-u.png",v:"https://boxel-images.boxel.ai/icons/Letter-v.png",w:"https://boxel-images.boxel.ai/icons/Letter-w.png",x:"https://boxel-images.boxel.ai/icons/Letter-x.png",y:"https://boxel-images.boxel.ai/icons/Letter-y.png",z:"https://boxel-images.boxel.ai/icons/letter-z.png"}),bi=Object.freeze(["https://boxel-images.boxel.ai/background-images/4k-arabic-teal.jpg","https://boxel-images.boxel.ai/background-images/4k-arrow-weave.jpg","https://boxel-images.boxel.ai/background-images/4k-atmosphere-curvature.jpg","https://boxel-images.boxel.ai/background-images/4k-brushed-slabs.jpg","https://boxel-images.boxel.ai/background-images/4k-coral-reefs.jpg","https://boxel-images.boxel.ai/background-images/4k-crescent-lake.jpg","https://boxel-images.boxel.ai/background-images/4k-curvilinear-stairs.jpg","https://boxel-images.boxel.ai/background-images/4k-desert-dunes.jpg","https://boxel-images.boxel.ai/background-images/4k-doodle-board.jpg","https://boxel-images.boxel.ai/background-images/4k-fallen-leaves.jpg","https://boxel-images.boxel.ai/background-images/4k-flowing-mesh.jpg","https://boxel-images.boxel.ai/background-images/4k-glass-reflection.jpg","https://boxel-images.boxel.ai/background-images/4k-glow-cells.jpg","https://boxel-images.boxel.ai/background-images/4k-granite-peaks.jpg","https://boxel-images.boxel.ai/background-images/4k-green-wormhole.jpg","https://boxel-images.boxel.ai/background-images/4k-joshua-dawn.jpg","https://boxel-images.boxel.ai/background-images/4k-lava-river.jpg","https://boxel-images.boxel.ai/background-images/4k-leaves-moss.jpg","https://boxel-images.boxel.ai/background-images/4k-light-streaks.jpg","https://boxel-images.boxel.ai/background-images/4k-lowres-glitch.jpg","https://boxel-images.boxel.ai/background-images/4k-marble-shimmer.jpg","https://boxel-images.boxel.ai/background-images/4k-metallic-leather.jpg","https://boxel-images.boxel.ai/background-images/4k-microscopic-crystals.jpg","https://boxel-images.boxel.ai/background-images/4k-moon-face.jpg","https://boxel-images.boxel.ai/background-images/4k-mountain-runway.jpg","https://boxel-images.boxel.ai/background-images/4k-origami-flock.jpg","https://boxel-images.boxel.ai/background-images/4k-paint-swirl.jpg","https://boxel-images.boxel.ai/background-images/4k-pastel-triangles.jpg","https://boxel-images.boxel.ai/background-images/4k-perforated-sheet.jpg","https://boxel-images.boxel.ai/background-images/4k-plastic-ripples.jpg","https://boxel-images.boxel.ai/background-images/4k-powder-puff.jpg","https://boxel-images.boxel.ai/background-images/4k-radiant-crystal.jpg","https://boxel-images.boxel.ai/background-images/4k-redrock-canyon.jpg","https://boxel-images.boxel.ai/background-images/4k-rock-portal.jpg","https://boxel-images.boxel.ai/background-images/4k-rolling-hills.jpg","https://boxel-images.boxel.ai/background-images/4k-sand-stone.jpg","https://boxel-images.boxel.ai/background-images/4k-silver-fur.jpg","https://boxel-images.boxel.ai/background-images/4k-spa-pool.jpg","https://boxel-images.boxel.ai/background-images/4k-stained-glass.jpg","https://boxel-images.boxel.ai/background-images/4k-stone-veins.jpg","https://boxel-images.boxel.ai/background-images/4k-tangerine-plains.jpg","https://boxel-images.boxel.ai/background-images/4k-techno-floor.jpg","https://boxel-images.boxel.ai/background-images/4k-thick-frost.jpg","https://boxel-images.boxel.ai/background-images/4k-water-surface.jpg","https://boxel-images.boxel.ai/background-images/4k-watercolor-splashes.jpg","https://boxel-images.boxel.ai/background-images/4k-wildflower-field.jpg","https://boxel-images.boxel.ai/background-images/4k-wood-grain.jpg"]);function Cr(r){if(!r)return;let e=r.toLowerCase().replace(/[^a-z0-9]/g,"").replace(/^[0-9]+/,"");return Zc[e.charAt(0)]}function Ri(){let r=Math.floor(Math.random()*bi.length);return bi[r]}var eu=/^[a-z0-9-]+$/;function vi(r){r.command("create").description("Create a new realm on the realm server").argument("<realm-name>","realm name (lowercase, numbers, hyphens only)").argument("<display-name>","display name for the realm").option("--background <url>","background image URL").option("--icon <url>","icon image URL").action(async(e,t,n)=>{await nu(e,t,n)})}async function tu(r,e,t={}){let n=t.profileManager??O(),i=n.getActiveProfile();if(!i)throw new Error("No active profile. Run `boxel profile add` to create one.");let s=i.profile.realmServerUrl.replace(/\/$/,""),o={endpoint:r,name:e,backgroundURL:t.background??Ri(),iconURL:t.icon??Cr(e)??Cr(r)},a=await n.authedRealmServerFetch(`${s}/_create-realm`,{method:"POST",headers:{"Content-Type":"application/vnd.api+json"},body:JSON.stringify({data:{type:"realm",attributes:o}})});if(!a.ok){let d;try{d=await a.text()}catch{d="server returned a non-serialized object body"}if(d.includes("[object Object]")&&(d="server returned a non-serialized object body"),d.includes("already exists")){let h=iu(d,s,r),y=await $i(n,h);try{await n.addToUserRealms(h)}catch{}return{realmUrl:h,created:!1,realmToken:y}}throw new Error(`Realm server returned ${a.status}: ${d}`)}let u=(await a.json())?.data?.id;if(typeof u!="string"||u.trim()==="")throw new Error(`Realm server response did not include a realm URL (data.id) for "${r}".`);let c=C(u),f=await $i(n,c);try{await n.addToUserRealms(c)}catch{}return t.waitForReady&&f&&await ru(c,f),{realmUrl:c,created:!0,realmToken:f}}async function $i(r,e){try{let t=await r.getOrRefreshServerToken();return await r.fetchAndStoreRealmToken(e,t)}catch{return}}async function ru(r,e){let t=new URL("_readiness-check",r).href,n=15e3,i=250,s=Date.now(),o;for(;Date.now()-s<n;){try{let a=await fetch(t,{headers:{Accept:"application/vnd.api+json",Authorization:e}});if(a.ok)return;o=`HTTP ${a.status}`}catch(a){o=a instanceof Error?a.message:String(a)}await new Promise(a=>setTimeout(a,i))}throw new Error(`Timed out waiting for realm ${r} to become ready${o?`: ${o}`:""}`)}async function nu(r,e,t){eu.test(r)||(console.error("Error: realm name must contain only lowercase letters, numbers, and hyphens"),process.exit(1));try{let n=await tu(r,e,t),i=n.created?"created":"already exists";console.log(`${_}Realm ${i}:${m} ${T}${n.realmUrl}${m}`)}catch(n){console.error(`Error: ${n instanceof Error?n.message:String(n)}`),process.exit(1)}}function iu(r,e,t){let n=r.match(/'(https?:\/\/[^']+)'/);if(n)return C(n[1]);throw new Error(`Could not determine realm URL from server error response for endpoint "${t}" on "${e}". The response did not include an explicit realm URL.`)}var je=N(require("fs"));var Di=require("child_process"),G=N(require("fs/promises")),V=N(require("path"));var q=N(require("fs/promises")),j=N(require("path")),Dr=N(Pi());var Nr=class{value;next;constructor(e){this.value=e}},Ue=class{#e;#t;#r;constructor(){this.clear()}enqueue(e){let t=new Nr(e);this.#e?(this.#t.next=t,this.#t=t):(this.#e=t,this.#t=t),this.#r++}dequeue(){let e=this.#e;if(e)return this.#e=this.#e.next,this.#r--,this.#e||(this.#t=void 0),e.value}peek(){if(this.#e)return this.#e.value}clear(){this.#e=void 0,this.#t=void 0,this.#r=0}get size(){return this.#r}*[Symbol.iterator](){let e=this.#e;for(;e;)yield e.value,e=e.next}*drain(){for(;this.#e;)yield this.dequeue()}};function Mr(r){let e=!1;if(typeof r=="object"&&({concurrency:r,rejectOnClear:e=!1}=r),Li(r),typeof e!="boolean")throw new TypeError("Expected `rejectOnClear` to be a boolean");let t=new Ue,n=0,i=()=>{n<r&&t.size>0&&(n++,t.dequeue().run())},s=()=>{n--,i()},o=async(u,c,f)=>{let d=(async()=>u(...f))();c(d);try{await d}catch{}s()},a=(u,c,f,d)=>{let h={reject:f};new Promise(y=>{h.run=y,t.enqueue(h)}).then(o.bind(void 0,u,c,d)),n<r&&i()},l=(u,...c)=>new Promise((f,d)=>{a(u,f,d,c)});return Object.defineProperties(l,{activeCount:{get:()=>n},pendingCount:{get:()=>t.size},clearQueue:{value(){if(!e){t.clear();return}let u=AbortSignal.abort().reason;for(;t.size>0;)t.dequeue().reject(u)}},concurrency:{get:()=>r,set(u){Li(u),r=u,queueMicrotask(()=>{for(;n<r&&t.size>0;)i()})}},map:{async value(u,c){let f=Array.from(u,(d,h)=>this(c,d,h));return Promise.all(f)}}}),l}function Li(r){if(!((Number.isInteger(r)||r===Number.POSITIVE_INFINITY)&&r>0))throw new TypeError("Expected `concurrency` to be a number from 1 and up")}var $u=Dr.default.default||Dr.default,vu=new Set([".realm.json"]);function F(r){let e=r.replace(/\\/g,"/").replace(/^\/+/,"");return vu.has(e)}async function Ii(r){try{return await q.access(r),!0}catch{return!1}}function Ni(r){try{return decodeURIComponent(r)}catch{return r}}var gt={CardSource:"application/vnd.card+source",DirectoryListing:"application/vnd.api+json",Mtimes:"application/vnd.api+json"},Su=10,Mi=new Set(["node_modules"]),se=class{constructor(e,t){this.options=e;this.authenticator=t;this.normalizedRealmUrl=this.normalizeRealmUrl(e.realmUrl)}normalizedRealmUrl;ignoreCache=new Map;remoteLimit=Mr(Su);normalizeRealmUrl(e){try{let t=new URL(e),n=t.pathname;return(n.split("/").filter(Boolean).pop()||"").includes(".")?console.warn(`Warning: "${e}" looks like a file URL, not a realm URL.
|
|
58
|
+
`)}};function dt(r){if(typeof r=="string")return r;if(r instanceof Error)return r.stack??r.message;try{return JSON.stringify(r)}catch{return String(r)}}async function Qc(r,e,t){let n=t?.profileManager??O();if(!n.getActiveProfile())throw new Error("No active profile. Run `boxel profile add` to create one.");let s=new URL(e,C(r)).href,o;try{o=await n.authedRealmFetch(s,{method:"GET",headers:{Accept:"*/*"}})}catch(l){return{ok:!1,error:l instanceof Error?l.message:String(l)}}if(!o.ok){let l=await o.text().catch(()=>"(no body)");return{ok:!1,status:o.status,error:`HTTP ${o.status}: ${l.slice(0,300)}`}}let a=await o.text();return{ok:!0,status:o.status,content:a}}function Ei(r){r.command("read-transpiled").description("Debugging tool ONLY for investigating runtime errors in .gts modules you've written. Use when an eval or instantiate error reports a line/column number \u2014 those line numbers refer to the transpiled output, not your .gts source, so fetching the transpiled output is how you locate the offending source construct. Never use the transpiled output as a reference for how to write code: do not copy its patterns (setComponentTemplate, precompileTemplate, wire-format templates, base64 CSS imports) into source. Always write idiomatic Ember / <template>-tag / CardDef source.").argument("<path>","Realm-relative module path. The .gts extension is optional \u2014 the realm accepts either form.").requiredOption("--realm <realm-url>","The realm URL to fetch from").option("--json","Output raw JSON response").action(async(e,t)=>{let n;try{n=await Qc(t.realm,e)}catch(i){console.error(`${y}Error:${m} ${i instanceof Error?i.message:String(i)}`),process.exit(1)}t.json?M.output(JSON.stringify(n,null,2)):n.ok?M.output(n.content??""):(console.error(`${E}Status:${m} ${n.status??"(no status)"}`),console.error(`${y}Error:${m} ${n.error}`)),n.ok||process.exit(1)})}async function Zc(r,e){let t=e?.profileManager??O();if(!t.getActiveProfile())return{ok:!1,error:L};let i=e?.cancelPending??!1,s=`${C(r)}_cancel-indexing-job`;try{let o=await t.authedRealmFetch(s,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({cancelPending:i})});if(!o.ok){let a=await o.text().catch(()=>"(no body)");return{ok:!1,error:`HTTP ${o.status}: ${a.slice(0,300)}`}}return{ok:!0}}catch(o){return{ok:!1,error:o instanceof Error?o.message:String(o)}}}function wi(r){r.command("cancel-indexing").description("Cancel running indexing jobs for a realm (use --cancel-pending to also cancel queued jobs)").requiredOption("--realm <realm-url>","URL of the realm to cancel indexing for").option("--cancel-pending","Also cancel queued/pending indexing jobs (default: cancel running only)").option("--json","Output raw JSON response").action(async e=>{let t=await Zc(e.realm,{cancelPending:e.cancelPending});if(e.json)M.output(JSON.stringify(t,null,2)),t.ok||process.exit(1);else if(t.ok){let n=e.cancelPending?"running and pending":"running";console.log(`${_}Cancelled ${n} indexing jobs for ${e.realm}${m}`)}else console.error(`${y}Error:${m} ${t.error}`),process.exit(1)})}var eu=Object.freeze({a:"https://boxel-images.boxel.ai/icons/Letter-a.png",b:"https://boxel-images.boxel.ai/icons/Letter-b.png",c:"https://boxel-images.boxel.ai/icons/Letter-c.png",d:"https://boxel-images.boxel.ai/icons/Letter-d.png",e:"https://boxel-images.boxel.ai/icons/Letter-e.png",f:"https://boxel-images.boxel.ai/icons/Letter-f.png",g:"https://boxel-images.boxel.ai/icons/Letter-g.png",h:"https://boxel-images.boxel.ai/icons/Letter-h.png",i:"https://boxel-images.boxel.ai/icons/Letter-i.png",j:"https://boxel-images.boxel.ai/icons/Letter-j.png",k:"https://boxel-images.boxel.ai/icons/Letter-k.png",l:"https://boxel-images.boxel.ai/icons/Letter-l.png",m:"https://boxel-images.boxel.ai/icons/Letter-m.png",n:"https://boxel-images.boxel.ai/icons/Letter-n.png",o:"https://boxel-images.boxel.ai/icons/Letter-o.png",p:"https://boxel-images.boxel.ai/icons/Letter-p.png",q:"https://boxel-images.boxel.ai/icons/Letter-q.png",r:"https://boxel-images.boxel.ai/icons/Letter-r.png",s:"https://boxel-images.boxel.ai/icons/Letter-s.png",t:"https://boxel-images.boxel.ai/icons/Letter-t.png",u:"https://boxel-images.boxel.ai/icons/Letter-u.png",v:"https://boxel-images.boxel.ai/icons/Letter-v.png",w:"https://boxel-images.boxel.ai/icons/Letter-w.png",x:"https://boxel-images.boxel.ai/icons/Letter-x.png",y:"https://boxel-images.boxel.ai/icons/Letter-y.png",z:"https://boxel-images.boxel.ai/icons/letter-z.png"}),bi=Object.freeze(["https://boxel-images.boxel.ai/background-images/4k-arabic-teal.jpg","https://boxel-images.boxel.ai/background-images/4k-arrow-weave.jpg","https://boxel-images.boxel.ai/background-images/4k-atmosphere-curvature.jpg","https://boxel-images.boxel.ai/background-images/4k-brushed-slabs.jpg","https://boxel-images.boxel.ai/background-images/4k-coral-reefs.jpg","https://boxel-images.boxel.ai/background-images/4k-crescent-lake.jpg","https://boxel-images.boxel.ai/background-images/4k-curvilinear-stairs.jpg","https://boxel-images.boxel.ai/background-images/4k-desert-dunes.jpg","https://boxel-images.boxel.ai/background-images/4k-doodle-board.jpg","https://boxel-images.boxel.ai/background-images/4k-fallen-leaves.jpg","https://boxel-images.boxel.ai/background-images/4k-flowing-mesh.jpg","https://boxel-images.boxel.ai/background-images/4k-glass-reflection.jpg","https://boxel-images.boxel.ai/background-images/4k-glow-cells.jpg","https://boxel-images.boxel.ai/background-images/4k-granite-peaks.jpg","https://boxel-images.boxel.ai/background-images/4k-green-wormhole.jpg","https://boxel-images.boxel.ai/background-images/4k-joshua-dawn.jpg","https://boxel-images.boxel.ai/background-images/4k-lava-river.jpg","https://boxel-images.boxel.ai/background-images/4k-leaves-moss.jpg","https://boxel-images.boxel.ai/background-images/4k-light-streaks.jpg","https://boxel-images.boxel.ai/background-images/4k-lowres-glitch.jpg","https://boxel-images.boxel.ai/background-images/4k-marble-shimmer.jpg","https://boxel-images.boxel.ai/background-images/4k-metallic-leather.jpg","https://boxel-images.boxel.ai/background-images/4k-microscopic-crystals.jpg","https://boxel-images.boxel.ai/background-images/4k-moon-face.jpg","https://boxel-images.boxel.ai/background-images/4k-mountain-runway.jpg","https://boxel-images.boxel.ai/background-images/4k-origami-flock.jpg","https://boxel-images.boxel.ai/background-images/4k-paint-swirl.jpg","https://boxel-images.boxel.ai/background-images/4k-pastel-triangles.jpg","https://boxel-images.boxel.ai/background-images/4k-perforated-sheet.jpg","https://boxel-images.boxel.ai/background-images/4k-plastic-ripples.jpg","https://boxel-images.boxel.ai/background-images/4k-powder-puff.jpg","https://boxel-images.boxel.ai/background-images/4k-radiant-crystal.jpg","https://boxel-images.boxel.ai/background-images/4k-redrock-canyon.jpg","https://boxel-images.boxel.ai/background-images/4k-rock-portal.jpg","https://boxel-images.boxel.ai/background-images/4k-rolling-hills.jpg","https://boxel-images.boxel.ai/background-images/4k-sand-stone.jpg","https://boxel-images.boxel.ai/background-images/4k-silver-fur.jpg","https://boxel-images.boxel.ai/background-images/4k-spa-pool.jpg","https://boxel-images.boxel.ai/background-images/4k-stained-glass.jpg","https://boxel-images.boxel.ai/background-images/4k-stone-veins.jpg","https://boxel-images.boxel.ai/background-images/4k-tangerine-plains.jpg","https://boxel-images.boxel.ai/background-images/4k-techno-floor.jpg","https://boxel-images.boxel.ai/background-images/4k-thick-frost.jpg","https://boxel-images.boxel.ai/background-images/4k-water-surface.jpg","https://boxel-images.boxel.ai/background-images/4k-watercolor-splashes.jpg","https://boxel-images.boxel.ai/background-images/4k-wildflower-field.jpg","https://boxel-images.boxel.ai/background-images/4k-wood-grain.jpg"]);function Or(r){if(!r)return;let e=r.toLowerCase().replace(/[^a-z0-9]/g,"").replace(/^[0-9]+/,"");return eu[e.charAt(0)]}function Ri(){let r=Math.floor(Math.random()*bi.length);return bi[r]}var tu=/^[a-z0-9-]+$/;function vi(r){r.command("create").description("Create a new realm on the realm server").argument("<realm-name>","realm name (lowercase, numbers, hyphens only)").argument("<display-name>","display name for the realm").option("--background <url>","background image URL").option("--icon <url>","icon image URL").action(async(e,t,n)=>{await iu(e,t,n)})}async function ru(r,e,t={}){let n=t.profileManager??O(),i=n.getActiveProfile();if(!i)throw new Error("No active profile. Run `boxel profile add` to create one.");let s=i.profile.realmServerUrl.replace(/\/$/,""),o={endpoint:r,name:e,backgroundURL:t.background??Ri(),iconURL:t.icon??Or(e)??Or(r)},a=await n.authedRealmServerFetch(`${s}/_create-realm`,{method:"POST",headers:{"Content-Type":"application/vnd.api+json"},body:JSON.stringify({data:{type:"realm",attributes:o}})});if(!a.ok){let d;try{d=await a.text()}catch{d="server returned a non-serialized object body"}if(d.includes("[object Object]")&&(d="server returned a non-serialized object body"),d.includes("already exists")){let p=su(d,s,r),g=await $i(n,p);try{await n.addToUserRealms(p)}catch{}return{realmUrl:p,created:!1,realmToken:g}}throw new Error(`Realm server returned ${a.status}: ${d}`)}let u=(await a.json())?.data?.id;if(typeof u!="string"||u.trim()==="")throw new Error(`Realm server response did not include a realm URL (data.id) for "${r}".`);let c=C(u),f=await $i(n,c);try{await n.addToUserRealms(c)}catch{}return t.waitForReady&&f&&await nu(c,f),{realmUrl:c,created:!0,realmToken:f}}async function $i(r,e){try{let t=await r.getOrRefreshServerToken();return await r.fetchAndStoreRealmToken(e,t)}catch{return}}async function nu(r,e){let t=new URL("_readiness-check",r).href,n=15e3,i=250,s=Date.now(),o;for(;Date.now()-s<n;){try{let a=await fetch(t,{headers:{Accept:"application/vnd.api+json",Authorization:e}});if(a.ok)return;o=`HTTP ${a.status}`}catch(a){o=a instanceof Error?a.message:String(a)}await new Promise(a=>setTimeout(a,i))}throw new Error(`Timed out waiting for realm ${r} to become ready${o?`: ${o}`:""}`)}async function iu(r,e,t){tu.test(r)||(console.error("Error: realm name must contain only lowercase letters, numbers, and hyphens"),process.exit(1));try{let n=await ru(r,e,t),i=n.created?"created":"already exists";console.log(`${_}Realm ${i}:${m} ${T}${n.realmUrl}${m}`)}catch(n){console.error(`Error: ${n instanceof Error?n.message:String(n)}`),process.exit(1)}}function su(r,e,t){let n=r.match(/'(https?:\/\/[^']+)'/);if(n)return C(n[1]);throw new Error(`Could not determine realm URL from server error response for endpoint "${t}" on "${e}". The response did not include an explicit realm URL.`)}var je=N(require("fs"));var Di=require("child_process"),G=N(require("fs/promises")),V=N(require("path"));var q=N(require("fs/promises")),j=N(require("path")),Dr=N(Pi());var Ir=class{value;next;constructor(e){this.value=e}},Fe=class{#e;#t;#r;constructor(){this.clear()}enqueue(e){let t=new Ir(e);this.#e?(this.#t.next=t,this.#t=t):(this.#e=t,this.#t=t),this.#r++}dequeue(){let e=this.#e;if(e)return this.#e=this.#e.next,this.#r--,this.#e||(this.#t=void 0),e.value}peek(){if(this.#e)return this.#e.value}clear(){this.#e=void 0,this.#t=void 0,this.#r=0}get size(){return this.#r}*[Symbol.iterator](){let e=this.#e;for(;e;)yield e.value,e=e.next}*drain(){for(;this.#e;)yield this.dequeue()}};function Nr(r){let e=!1;if(typeof r=="object"&&({concurrency:r,rejectOnClear:e=!1}=r),Li(r),typeof e!="boolean")throw new TypeError("Expected `rejectOnClear` to be a boolean");let t=new Fe,n=0,i=()=>{n<r&&t.size>0&&(n++,t.dequeue().run())},s=()=>{n--,i()},o=async(u,c,f)=>{let d=(async()=>u(...f))();c(d);try{await d}catch{}s()},a=(u,c,f,d)=>{let p={reject:f};new Promise(g=>{p.run=g,t.enqueue(p)}).then(o.bind(void 0,u,c,d)),n<r&&i()},l=(u,...c)=>new Promise((f,d)=>{a(u,f,d,c)});return Object.defineProperties(l,{activeCount:{get:()=>n},pendingCount:{get:()=>t.size},clearQueue:{value(){if(!e){t.clear();return}let u=AbortSignal.abort().reason;for(;t.size>0;)t.dequeue().reject(u)}},concurrency:{get:()=>r,set(u){Li(u),r=u,queueMicrotask(()=>{for(;n<r&&t.size>0;)i()})}},map:{async value(u,c){let f=Array.from(u,(d,p)=>this(c,d,p));return Promise.all(f)}}}),l}function Li(r){if(!((Number.isInteger(r)||r===Number.POSITIVE_INFINITY)&&r>0))throw new TypeError("Expected `concurrency` to be a number from 1 and up")}var vu=Dr.default.default||Dr.default,Su=new Set([".realm.json"]),Mr=1e4,xu=3e3;function F(r){let e=r.replace(/\\/g,"/").replace(/^\/+/,"");return Su.has(e)}async function Ii(r){try{return await q.access(r),!0}catch{return!1}}function Ni(r){try{return decodeURIComponent(r)}catch{return r}}var Ue={CardSource:"application/vnd.card+source",DirectoryListing:"application/vnd.api+json",Mtimes:"application/vnd.api+json"},_u=10,Mi=new Set(["node_modules"]),se=class{constructor(e,t){this.options=e;this.authenticator=t;this.normalizedRealmUrl=this.normalizeRealmUrl(e.realmUrl)}normalizedRealmUrl;ignoreCache=new Map;remoteLimit=Nr(_u);normalizeRealmUrl(e){try{let t=new URL(e),n=t.pathname;return(n.split("/").filter(Boolean).pop()||"").includes(".")?console.warn(`Warning: "${e}" looks like a file URL, not a realm URL.
|
|
59
59
|
Realm URLs should point to a directory (e.g., ${t.origin}${n.replace(/\/[^/]*\.[^/]*$/,"/")})`):e.endsWith("/")||console.warn(`Warning: Realm URL should end with a trailing slash.
|
|
60
|
-
Did you mean "${e}/"?`),t.href.replace(/\/+$/,"")+"/"}catch{throw new Error(`Invalid workspace URL: ${e}`)}}buildDirectoryUrl(e=""){if(!e)return this.normalizedRealmUrl;let t=e.replace(/^\/+|\/+$/g,"");return`${this.normalizedRealmUrl}${t}/`}buildFileUrl(e){let t=e.replace(/^\/+/,"");return`${this.normalizedRealmUrl}${t}`}async getRemoteFileList(e=""){let t=new Map;try{let n=this.buildDirectoryUrl(e),i=await this.authenticator.authedRealmFetch(n,{headers:{Accept:"application/vnd.api+json"}});if(!i.ok){if(i.status===404)return t;throw i.status===401||i.status===403?new Error(`Authentication failed (${i.status}): Cannot access workspace. Check your Matrix credentials and workspace permissions.`):new Error(`Failed to get directory listing: ${i.status} ${i.statusText}`)}let s=await i.json();if(s.data&&s.data.relationships){let o=Object.entries(s.data.relationships),a=await Promise.all(o.map(([l,u])=>{let f=u.meta.kind==="file",d=e?j.posix.join(e,l):l;return f?this.shouldIgnoreRemoteFile(d)?[]:[[d,!0]]:this.remoteLimit(async()=>{let h=await this.getRemoteFileList(d);return Array.from(h.entries())})}));for(let l of a)for(let[u,c]of l)t.set(u,c)}}catch(n){throw n instanceof Error&&(n.message.includes("Authentication failed")||n.message.includes("Cannot access workspace")||n.message.includes("401")||n.message.includes("403"))||console.error(`Error reading remote directory ${e}:`,n),n}return t}async getRemoteMtimes(){let e=new Map;try{let t=`${this.normalizedRealmUrl}_mtimes`,n=await this.authenticator.authedRealmFetch(t,{headers:{Accept:gt.Mtimes}});if(!n.ok){if(n.status===404)return console.log("Note: _mtimes endpoint not available, will upload all files"),e;throw new Error(`Failed to get mtimes: ${n.status} ${n.statusText}`)}let i=await n.json();if(i.data?.attributes?.mtimes){let s=Object.entries(i.data.attributes.mtimes);process.env.DEBUG&&(console.log(`Remote mtimes received: ${s.length} entries`),s.length>0&&console.log(`Sample: ${s[0][0]} = ${s[0][1]}`));for(let[o,a]of s){let l=o.replace(this.normalizedRealmUrl,""),u;try{u=decodeURIComponent(l)}catch{u=l}this.shouldIgnoreRemoteFile(u)||e.set(u,a)}}else process.env.DEBUG&&console.log("No mtimes in response:",JSON.stringify(i).slice(0,200))}catch(t){console.warn("Could not fetch remote mtimes, will upload all files:",t)}return e}async getLocalFileListWithMtimes(e=""){let t=new Map,n=j.join(this.options.localDir,e),i;try{i=await q.readdir(n,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")return t;throw o}let s=await Promise.all(i.map(async o=>{let a=j.join(n,o.name),l=e?j.posix.join(e,o.name):o.name;if(o.isDirectory()&&Mi.has(o.name))return[];if(await this.shouldIgnoreFile(l,a))return[];if(o.isFile()){let u=await q.stat(a);return[[l,{path:a,mtime:u.mtimeMs}]]}else if(o.isDirectory()){let u=await this.getLocalFileListWithMtimes(l);return Array.from(u.entries())}return[]}));for(let o of s)for(let[a,l]of o)t.set(a,l);return t}async getLocalFileList(e=""){let t=new Map,n=j.join(this.options.localDir,e),i;try{i=await q.readdir(n,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")return t;throw o}let s=await Promise.all(i.map(async o=>{let a=j.join(n,o.name),l=e?j.posix.join(e,o.name):o.name;if(o.isDirectory()&&Mi.has(o.name))return[];if(await this.shouldIgnoreFile(l,a))return[];if(o.isFile())return[[l,a]];if(o.isDirectory()){let u=await this.getLocalFileList(l);return Array.from(u.entries())}return[]}));for(let o of s)for(let[a,l]of o)t.set(a,l);return t}async uploadFile(e,t){if(F(e)){console.log(` Skipped (protected): ${e}`);return}if(console.log(`Uploading: ${e}`),this.options.dryRun){console.log(`[DRY RUN] Would upload ${e}`);return}let n=await q.readFile(t,"utf8"),i=this.buildFileUrl(e),s=await this.authenticator.authedRealmFetch(i,{method:"POST",headers:{"Content-Type":"text/plain;charset=UTF-8",Accept:gt.CardSource},body:n});if(!s.ok)throw new Error(`Failed to upload: ${s.status} ${s.statusText}`);console.log(` Uploaded: ${e}`)}async uploadFilesAtomic(e,t){let n=Array.from(e.entries()).filter(([u])=>!F(u));if(n.length===0)return{succeeded:[]};if(this.options.dryRun){for(let[u]of n)console.log(`[DRY RUN] Would upload ${u}`);return{succeeded:[]}}let i=await Promise.all(n.map(async([u,c])=>{let f=await q.readFile(c,"utf8");return{op:t.has(u)?"add":"update",href:this.buildFileUrl(u),data:{type:"source",attributes:{content:f},meta:{}}}})),s=`${this.normalizedRealmUrl}_atomic`,o=await this.authenticator.authedRealmFetch(s,{method:"POST",headers:{"Content-Type":"application/vnd.api+json",Accept:"application/vnd.api+json"},body:JSON.stringify({"atomic:operations":i})});if(o.status===201){let u=await o.json(),c=new Map(n.map(([d])=>[this.buildFileUrl(d),d])),f=(u["atomic:results"]??[]).map(d=>d.data?.id).filter(d=>typeof d=="string").map(d=>Ni(d)).map(d=>c.get(d)??d);for(let d of f)console.log(` Uploaded: ${d}`);return{succeeded:f}}let a={};try{a=await o.json()}catch{}let l=(a.errors??[]).map(u=>{let f=(u.detail??"").match(/Resource (\S+) /),d=f?Ni(f[1]):"";return{path:new Map(n.map(([y])=>[this.buildFileUrl(y),y])).get(d)??d,status:u.status??o.status,title:u.title??"Error"}});return{succeeded:[],error:{status:o.status,perFile:l,message:`Atomic upload failed: ${o.status} ${o.statusText}`}}}async downloadFile(e,t){if(console.log(`Downloading: ${e}`),this.options.dryRun){console.log(`[DRY RUN] Would download ${e}`);return}let n=this.buildFileUrl(e),i=await this.authenticator.authedRealmFetch(n,{headers:{Accept:gt.CardSource}});if(!i.ok)throw new Error(`Failed to download: ${i.status} ${i.statusText}`);let s=await i.text(),o=j.dirname(t);await q.mkdir(o,{recursive:!0}),await q.writeFile(t,s,"utf8"),console.log(` Downloaded: ${e}`)}async deleteFile(e){if(F(e)){console.log(` Skipped (protected): ${e}`);return}if(console.log(`Deleting remote: ${e}`),this.options.dryRun){console.log(`[DRY RUN] Would delete ${e}`);return}let t=this.buildFileUrl(e),n=await this.authenticator.authedRealmFetch(t,{method:"DELETE",headers:{Accept:gt.CardSource}});if(!n.ok&&n.status!==404)throw new Error(`Failed to delete: ${n.status} ${n.statusText}`);console.log(` Deleted: ${e}`)}async deleteLocalFile(e){if(console.log(`Deleting local: ${e}`),this.options.dryRun){console.log(`[DRY RUN] Would delete local file ${e}`);return}try{await q.unlink(e),console.log(` Deleted: ${e}`)}catch(t){if(t.code!=="ENOENT")throw t}}getIgnoreInstance(e){let t=this.ignoreCache.get(e);if(t)return t;let n=(async()=>{let i=$u(),s=e,o=this.options.localDir;for(;s.startsWith(o);){let a=j.join(s,".gitignore");if(await Ii(a))try{let c=await q.readFile(a,"utf8");i.add(c)}catch(c){console.warn(`Warning: Could not read .gitignore file at ${a}:`,c)}let l=j.join(s,".boxelignore");if(await Ii(l))try{let c=await q.readFile(l,"utf8");i.add(c)}catch(c){console.warn(`Warning: Could not read .boxelignore file at ${l}:`,c)}let u=j.dirname(s);if(u===s)break;s=u}return i})();return this.ignoreCache.set(e,n),n}async shouldIgnoreFile(e,t){let n=j.basename(e);if(n===".boxel-sync.json"||n.startsWith("."))return!0;let i=j.dirname(t),s=await this.getIgnoreInstance(i),o=e.replace(/\\/g,"/");return s.ignores(o)}shouldIgnoreRemoteFile(e){return!!j.basename(e).startsWith(".")}};async function Fr(r){try{return await G.access(r),!0}catch{return!1}}var B=class{workspaceDir;gitDir;constructor(e){this.workspaceDir=V.resolve(e),this.gitDir=V.join(this.workspaceDir,".boxel-history")}async init(){await Fr(this.gitDir)||await G.mkdir(this.gitDir,{recursive:!0});let e=V.join(this.gitDir,".git");await Fr(e)||(await this.git("init"),await this.git("config","user.email","boxel-cli@local"),await this.git("config","user.name","Boxel CLI"),await this.git("commit","--allow-empty","-m","[init] Initialize checkpoint history"))}async isInitialized(){return Fr(V.join(this.gitDir,".git"))}async syncFilesToHistory(){let e=await this.getWorkspaceFiles(),t=new Set(e),n=await this.getHistoryFiles();await Promise.all(n.map(async i=>{if(!t.has(i)){let s=V.join(this.gitDir,i);try{await G.unlink(s)}catch(o){if(o.code!=="ENOENT")throw o}}})),await Promise.all(e.map(async i=>{let s=V.join(this.workspaceDir,i),o=V.join(this.gitDir,i),a=V.dirname(o);await G.mkdir(a,{recursive:!0}),await G.copyFile(s,o)}))}async getWorkspaceFiles(){let e=[],t=async(n,i="")=>{let s;try{s=await G.readdir(n,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")return;throw o}await Promise.all(s.map(async o=>{if(o.name===".boxel-history"||o.name===".boxel-sync.json"||o.name==="node_modules"||o.name.startsWith("."))return;let a=i?`${i}/${o.name}`:o.name;o.isDirectory()?await t(V.join(n,o.name),a):e.push(a)}))};return await t(this.workspaceDir),e}async getHistoryFiles(){let e=[],t=async(n,i="")=>{let s;try{s=await G.readdir(n,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")return;throw o}await Promise.all(s.map(async o=>{if(o.name===".git")return;let a=i?`${i}/${o.name}`:o.name;o.isDirectory()?await t(V.join(n,o.name),a):e.push(a)}))};return await t(this.gitDir),e}async detectCurrentChanges(){if(!await this.isInitialized())return(await this.getWorkspaceFiles()).map(i=>({file:i,status:"added"}));await this.syncFilesToHistory();let e=(await this.git("status","--porcelain")).replace(/\n+$/,"");if(!e)return[];let t=[];for(let n of e.split(`
|
|
60
|
+
Did you mean "${e}/"?`),t.href.replace(/\/+$/,"")+"/"}catch{throw new Error(`Invalid workspace URL: ${e}`)}}buildDirectoryUrl(e=""){if(!e)return this.normalizedRealmUrl;let t=e.replace(/^\/+|\/+$/g,"");return`${this.normalizedRealmUrl}${t}/`}buildFileUrl(e){let t=e.replace(/^\/+/,"");return`${this.normalizedRealmUrl}${t}`}async getRemoteFileList(e=""){let t=new Map;try{let n=this.buildDirectoryUrl(e),i=await this.authenticator.authedRealmFetch(n,{headers:{Accept:"application/vnd.api+json"}});if(!i.ok){if(i.status===404)return t;throw i.status===401||i.status===403?new Error(`Authentication failed (${i.status}): Cannot access workspace. Check your Matrix credentials and workspace permissions.`):new Error(`Failed to get directory listing: ${i.status} ${i.statusText}`)}let s=await i.json();if(s.data&&s.data.relationships){let o=Object.entries(s.data.relationships),a=await Promise.all(o.map(([l,u])=>{let f=u.meta.kind==="file",d=e?j.posix.join(e,l):l;return f?this.shouldIgnoreRemoteFile(d)?[]:[[d,!0]]:this.remoteLimit(async()=>{let p=await this.getRemoteFileList(d);return Array.from(p.entries())})}));for(let l of a)for(let[u,c]of l)t.set(u,c)}}catch(n){throw n instanceof Error&&(n.message.includes("Authentication failed")||n.message.includes("Cannot access workspace")||n.message.includes("401")||n.message.includes("403"))||console.error(`Error reading remote directory ${e}:`,n),n}return t}async getRemoteMtimes(){let e=new Map;try{let t=`${this.normalizedRealmUrl}_mtimes`,n=await this.authenticator.authedRealmFetch(t,{headers:{Accept:Ue.Mtimes}});if(!n.ok){if(n.status===404)return console.log("Note: _mtimes endpoint not available, will upload all files"),e;throw new Error(`Failed to get mtimes: ${n.status} ${n.statusText}`)}let i=await n.json();if(i.data?.attributes?.mtimes){let s=Object.entries(i.data.attributes.mtimes);process.env.DEBUG&&(console.log(`Remote mtimes received: ${s.length} entries`),s.length>0&&console.log(`Sample: ${s[0][0]} = ${s[0][1]}`));for(let[o,a]of s){let l=o.replace(this.normalizedRealmUrl,""),u;try{u=decodeURIComponent(l)}catch{u=l}this.shouldIgnoreRemoteFile(u)||e.set(u,a)}}else process.env.DEBUG&&console.log("No mtimes in response:",JSON.stringify(i).slice(0,200))}catch(t){console.warn("Could not fetch remote mtimes, will upload all files:",t)}return e}async getLocalFileListWithMtimes(e=""){let t=new Map,n=j.join(this.options.localDir,e),i;try{i=await q.readdir(n,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")return t;throw o}let s=await Promise.all(i.map(async o=>{let a=j.join(n,o.name),l=e?j.posix.join(e,o.name):o.name;if(o.isDirectory()&&Mi.has(o.name))return[];if(await this.shouldIgnoreFile(l,a))return[];if(o.isFile()){let u=await q.stat(a);return[[l,{path:a,mtime:u.mtimeMs}]]}else if(o.isDirectory()){let u=await this.getLocalFileListWithMtimes(l);return Array.from(u.entries())}return[]}));for(let o of s)for(let[a,l]of o)t.set(a,l);return t}async getLocalFileList(e=""){let t=new Map,n=j.join(this.options.localDir,e),i;try{i=await q.readdir(n,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")return t;throw o}let s=await Promise.all(i.map(async o=>{let a=j.join(n,o.name),l=e?j.posix.join(e,o.name):o.name;if(o.isDirectory()&&Mi.has(o.name))return[];if(await this.shouldIgnoreFile(l,a))return[];if(o.isFile())return[[l,a]];if(o.isDirectory()){let u=await this.getLocalFileList(l);return Array.from(u.entries())}return[]}));for(let o of s)for(let[a,l]of o)t.set(a,l);return t}async uploadFile(e,t){if(F(e)){console.log(` Skipped (protected): ${e}`);return}if(console.log(`Uploading: ${e}`),this.options.dryRun){console.log(`[DRY RUN] Would upload ${e}`);return}let n=await q.readFile(t,"utf8"),i=this.buildFileUrl(e),s=await this.authenticator.authedRealmFetch(i,{method:"POST",headers:{"Content-Type":"text/plain;charset=UTF-8",Accept:Ue.CardSource},body:n});if(!s.ok)throw new Error(`Failed to upload: ${s.status} ${s.statusText}`);console.log(` Uploaded: ${e}`)}async uploadFilesAtomic(e,t){let n=Array.from(e.entries()).filter(([u])=>!F(u));if(n.length===0)return{succeeded:[]};if(this.options.dryRun){for(let[u]of n)console.log(`[DRY RUN] Would upload ${u}`);return{succeeded:[]}}let i=await Promise.all(n.map(async([u,c])=>{let f=await q.readFile(c,"utf8");return{op:t.has(u)?"add":"update",href:this.buildFileUrl(u),data:{type:"source",attributes:{content:f},meta:{}}}})),s=this.options.waitForIndex?`${this.normalizedRealmUrl}_atomic?waitForIndex=true`:`${this.normalizedRealmUrl}_atomic`,o=await this.authenticator.authedRealmFetch(s,{method:"POST",headers:{"Content-Type":"application/vnd.api+json",Accept:"application/vnd.api+json"},body:JSON.stringify({"atomic:operations":i})});if(o.status===201){let u=await o.json(),c=new Map(n.map(([d])=>[this.buildFileUrl(d),d])),f=(u["atomic:results"]??[]).map(d=>d.data?.id).filter(d=>typeof d=="string").map(d=>Ni(d)).map(d=>c.get(d)??d);for(let d of f)console.log(` Uploaded: ${d}`);return{succeeded:f}}let a={};try{a=await o.json()}catch{}let l=(a.errors??[]).map(u=>{let f=(u.detail??"").match(/Resource (\S+) /),d=f?Ni(f[1]):"";return{path:new Map(n.map(([g])=>[this.buildFileUrl(g),g])).get(d)??d,status:u.status??o.status,title:u.title??"Error"}});return{succeeded:[],error:{status:o.status,perFile:l,message:`Atomic upload failed: ${o.status} ${o.statusText}`}}}async downloadFile(e,t){if(console.log(`Downloading: ${e}`),this.options.dryRun){console.log(`[DRY RUN] Would download ${e}`);return}let n=this.buildFileUrl(e),i=await this.authenticator.authedRealmFetch(n,{headers:{Accept:Ue.CardSource}});if(!i.ok)throw new Error(`Failed to download: ${i.status} ${i.statusText}`);let s=await i.text(),o=j.dirname(t);await q.mkdir(o,{recursive:!0}),await q.writeFile(t,s,"utf8"),console.log(` Downloaded: ${e}`)}async deleteFile(e){if(F(e)){console.log(` Skipped (protected): ${e}`);return}if(console.log(`Deleting remote: ${e}`),this.options.dryRun){console.log(`[DRY RUN] Would delete ${e}`);return}let t=this.buildFileUrl(e),n=Date.now(),i;try{i=await this.authenticator.authedRealmFetch(t,{method:"DELETE",headers:{Accept:Ue.CardSource},signal:AbortSignal.timeout(Mr)})}catch(o){let a=Date.now()-n;if(console.error(` Delete request failed after ${a}ms: ${e}`),o instanceof Error&&(o.name==="TimeoutError"||o.name==="AbortError")){if(await this.verifyDeleteApplied(e)===!0){console.warn(` Delete response timed out after ${Mr}ms, but ${e} is already gone on the realm; continuing`);return}throw new Error(`Timed out deleting ${e} after ${Mr}ms`,{cause:o})}throw o}let s=Date.now()-n;if(console.log(` Delete response for ${e}: ${i.status} ${i.statusText} (${s}ms)`),!i.ok&&i.status!==404)throw new Error(`Failed to delete: ${i.status} ${i.statusText}`);console.log(` Deleted: ${e}`)}async verifyDeleteApplied(e){let t=this.buildFileUrl(e);try{let n=await this.authenticator.authedRealmFetch(t,{headers:{Accept:Ue.CardSource},signal:AbortSignal.timeout(xu)});return console.warn(` Delete-timeout probe for ${e}: ${n.status} ${n.statusText}`),n.status===404}catch(n){return console.warn(` Delete-timeout probe failed for ${e}:`,n),"unknown"}}async deleteLocalFile(e){if(console.log(`Deleting local: ${e}`),this.options.dryRun){console.log(`[DRY RUN] Would delete local file ${e}`);return}try{await q.unlink(e),console.log(` Deleted: ${e}`)}catch(t){if(t.code!=="ENOENT")throw t}}getIgnoreInstance(e){let t=this.ignoreCache.get(e);if(t)return t;let n=(async()=>{let i=vu(),s=e,o=this.options.localDir;for(;s.startsWith(o);){let a=j.join(s,".gitignore");if(await Ii(a))try{let c=await q.readFile(a,"utf8");i.add(c)}catch(c){console.warn(`Warning: Could not read .gitignore file at ${a}:`,c)}let l=j.join(s,".boxelignore");if(await Ii(l))try{let c=await q.readFile(l,"utf8");i.add(c)}catch(c){console.warn(`Warning: Could not read .boxelignore file at ${l}:`,c)}let u=j.dirname(s);if(u===s)break;s=u}return i})();return this.ignoreCache.set(e,n),n}async shouldIgnoreFile(e,t){let n=j.basename(e);if(n===".boxel-sync.json"||n.startsWith("."))return!0;let i=j.dirname(t),s=await this.getIgnoreInstance(i),o=e.replace(/\\/g,"/");return s.ignores(o)}shouldIgnoreRemoteFile(e){return!!j.basename(e).startsWith(".")}};async function Fr(r){try{return await G.access(r),!0}catch{return!1}}var B=class{workspaceDir;gitDir;constructor(e){this.workspaceDir=V.resolve(e),this.gitDir=V.join(this.workspaceDir,".boxel-history")}async init(){await Fr(this.gitDir)||await G.mkdir(this.gitDir,{recursive:!0});let e=V.join(this.gitDir,".git");await Fr(e)||(await this.git("init"),await this.git("config","user.email","boxel-cli@local"),await this.git("config","user.name","Boxel CLI"),await this.git("commit","--allow-empty","-m","[init] Initialize checkpoint history"))}async isInitialized(){return Fr(V.join(this.gitDir,".git"))}async syncFilesToHistory(){let e=await this.getWorkspaceFiles(),t=new Set(e),n=await this.getHistoryFiles();await Promise.all(n.map(async i=>{if(!t.has(i)){let s=V.join(this.gitDir,i);try{await G.unlink(s)}catch(o){if(o.code!=="ENOENT")throw o}}})),await Promise.all(e.map(async i=>{let s=V.join(this.workspaceDir,i),o=V.join(this.gitDir,i),a=V.dirname(o);await G.mkdir(a,{recursive:!0}),await G.copyFile(s,o)}))}async getWorkspaceFiles(){let e=[],t=async(n,i="")=>{let s;try{s=await G.readdir(n,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")return;throw o}await Promise.all(s.map(async o=>{if(o.name===".boxel-history"||o.name===".boxel-sync.json"||o.name==="node_modules"||o.name.startsWith("."))return;let a=i?`${i}/${o.name}`:o.name;o.isDirectory()?await t(V.join(n,o.name),a):e.push(a)}))};return await t(this.workspaceDir),e}async getHistoryFiles(){let e=[],t=async(n,i="")=>{let s;try{s=await G.readdir(n,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")return;throw o}await Promise.all(s.map(async o=>{if(o.name===".git")return;let a=i?`${i}/${o.name}`:o.name;o.isDirectory()?await t(V.join(n,o.name),a):e.push(a)}))};return await t(this.gitDir),e}async detectCurrentChanges(){if(!await this.isInitialized())return(await this.getWorkspaceFiles()).map(i=>({file:i,status:"added"}));await this.syncFilesToHistory();let e=(await this.git("status","--porcelain")).replace(/\n+$/,"");if(!e)return[];let t=[];for(let n of e.split(`
|
|
61
61
|
`)){if(!n)continue;let i=n.substring(0,2),s=n.substring(3);if(i.includes("R")){let o=s.indexOf(" -> ");if(o!==-1){let a=s.substring(0,o),l=s.substring(o+4);t.push({file:a,status:"deleted"}),t.push({file:l,status:"added"});continue}}i.includes("D")?t.push({file:s,status:"deleted"}):i.includes("A")||i.includes("C")||i==="??"?t.push({file:s,status:"added"}):(i.includes("M")||i.includes("U")||i.includes("T"))&&t.push({file:s,status:"modified"})}return t}async createCheckpoint(e,t,n){if(await this.isInitialized()||await this.init(),await this.syncFilesToHistory(),await this.git("add","-A"),!(await this.git("status","--porcelain")).trim())return null;let s=this.classifyChanges(t),{message:o,description:a}=n?{message:n,description:""}:this.generateCommitMessage(e,t,s),l=s?"[MAJOR]":"[minor]",u=`[${e}]`,c=`${l} ${u} ${o}${a?`
|
|
62
62
|
|
|
63
63
|
`+a:""}`;await this.git("commit","-m",c);let f=(await this.git("rev-parse","HEAD")).trim(),d=f.substring(0,7);return{hash:f,shortHash:d,message:o,description:a,date:new Date,isMajor:s,filesChanged:t.length,insertions:0,deletions:0,source:e,isMilestone:!1}}classifyChanges(e){if(e.length>3)return!0;for(let t of e)if(t.status==="added"||t.status==="deleted"||t.file.endsWith(".gts"))return!0;return!1}generateCommitMessage(e,t,n){let i=e==="local"?"Push":e==="remote"?"Pull":"Manual";if(t.length===0)return{message:`${i}: No changes detected`,description:""};if(t.length===1){let f=t[0],d=f.status==="added"?"Add":f.status==="deleted"?"Delete":"Update";return{message:`${i}: ${d} ${f.file}`,description:""}}let s=t.filter(f=>f.status==="added"),o=t.filter(f=>f.status==="modified"),a=t.filter(f=>f.status==="deleted"),l=[];s.length>0&&l.push(`+${s.length}`),o.length>0&&l.push(`~${o.length}`),a.length>0&&l.push(`-${a.length}`);let u=`${i}: ${t.length} files (${l.join(", ")})`,c=[];return s.length>0&&(c.push("Added:"),s.forEach(f=>c.push(` + ${f.file}`))),o.length>0&&(c.push("Modified:"),o.forEach(f=>c.push(` ~ ${f.file}`))),a.length>0&&(c.push("Deleted:"),a.forEach(f=>c.push(` - ${f.file}`))),{message:u,description:c.join(`
|
|
64
64
|
`)}}async getCheckpoints(e=50){if(!await this.isInitialized())return[];let n=await this.git("log","--format=%H|%h|%s|%aI|%an",`-${e}`);if(!n.trim())return[];let i=await this.getAllMilestones(),s=n.trim().split(`
|
|
65
|
-
`).filter(o=>!(o.split("|")[2]??"").startsWith("[init]"));return Promise.all(s.map(async o=>{let[a,l,u,c]=o.split("|"),f=u.includes("[MAJOR]"),d=u.includes("[local]")?"local":u.includes("[remote]")?"remote":"manual",
|
|
65
|
+
`).filter(o=>!(o.split("|")[2]??"").startsWith("[init]"));return Promise.all(s.map(async o=>{let[a,l,u,c]=o.split("|"),f=u.includes("[MAJOR]"),d=u.includes("[local]")?"local":u.includes("[remote]")?"remote":"manual",p=u.replace(/\[(MAJOR|minor)\]\s*/i,"").replace(/\[(local|remote|manual)\]\s*/i,""),g=await this.getCommitStats(a),S=i.get(a),z=!!S;return{hash:a,shortHash:l,message:p,description:"",date:new Date(c),isMajor:f,source:d,isMilestone:z,milestoneName:S,...g}}))}async getCommitStats(e){try{let n=(await this.git("show","--stat","--format=",e)).trim().split(`
|
|
66
66
|
`),i=n[n.length-1]||"",s=i.match(/(\d+) files? changed/),o=i.match(/(\d+) insertions?/),a=i.match(/(\d+) deletions?/);return{filesChanged:s?parseInt(s[1]):0,insertions:o?parseInt(o[1]):0,deletions:a?parseInt(a[1]):0}}catch{return{filesChanged:0,insertions:0,deletions:0}}}async getChangedFiles(e){return(await this.git("show","--name-only","--format=",e)).trim().split(`
|
|
67
67
|
`).filter(Boolean)}async getDiff(e){return this.git("show","--format=",e)}async restore(e){let t=await this.getHistoryFiles();await Promise.all(t.map(async o=>{let a=V.join(this.gitDir,o);try{await G.unlink(a)}catch(l){if(l.code!=="ENOENT")throw l}})),await this.git("checkout",e,"--",".");let n=await this.getHistoryFiles(),i=new Set(n),s=await this.getWorkspaceFiles();await Promise.all(s.map(async o=>{if(!F(o)&&!i.has(o)){let a=V.join(this.workspaceDir,o);try{await G.unlink(a)}catch(l){if(l.code!=="ENOENT")throw l}}})),await Promise.all(n.map(async o=>{if(F(o))return;let a=V.join(this.gitDir,o),l=V.join(this.workspaceDir,o),u=V.dirname(l);await G.mkdir(u,{recursive:!0}),await G.copyFile(a,l)})),await this.git("checkout","HEAD","--",".")}async markMilestone(e,t){if(!await this.isInitialized())return null;let n;if(typeof e=="number"){let s=await this.getCheckpoints(e+1);if(e<1||e>s.length)return null;n=s[e-1].hash}else n=e;let i=`milestone/${t.replace(/\s+/g,"-").replace(/[^a-zA-Z0-9\-_.]/g,"")}`;try{return await this.git("tag","-a",i,n,"-m",`Milestone: ${t}`),{hash:n,name:t}}catch{return null}}async unmarkMilestone(e){if(!await this.isInitialized())return!1;let t;if(typeof e=="number"){let i=await this.getCheckpoints(e+1);if(e<1||e>i.length)return!1;t=i[e-1].hash}else t=e;let n=await this.getMilestoneTags(t);if(n.length===0)return!1;for(let i of n)try{await this.git("tag","-d",i)}catch{}return!0}async getMilestoneTags(e){try{return(await this.git("tag","--points-at",e)).trim().split(`
|
|
68
68
|
`).filter(n=>n.startsWith("milestone/")).filter(Boolean)}catch{return[]}}async getAllMilestones(){let e=new Map;try{let t=await this.git("tag","-l","milestone/*");for(let n of t.trim().split(`
|
|
69
|
-
`).filter(Boolean))try{let i=(await this.git("rev-list","-1",n)).trim(),s=n.replace("milestone/","").replace(/-/g," ");e.set(i,s)}catch{}}catch{}return e}async getMilestones(){return(await this.getCheckpoints(100)).filter(t=>t.isMilestone)}git(...e){return new Promise((t,n)=>{let i=(0,Di.spawn)("git",e,{cwd:this.gitDir}),s="",o="";i.stdout.on("data",a=>{s+=a.toString("utf-8")}),i.stderr.on("data",a=>{o+=a.toString("utf-8")}),i.on("error",a=>n(a)),i.on("close",a=>{if(a!==0&&!e.includes("status")){n(new Error(`git ${e.join(" ")} failed: ${o}`));return}t(s)})})}};function Fi(r,e){let t=r.trim();if(t==="")return{kind:"none"};if(t.length===7){let i=e.filter(s=>s.shortHash===t);if(i.length===1)return{kind:"found",target:i[0]};if(i.length>1)return{kind:"ambiguous",matches:i}}if(/^\d+$/.test(t)){let i=parseInt(t,10);return i>=1&&i<=e.length?{kind:"found",target:e[i-1]}:{kind:"none"}}let n=e.filter(i=>i.hash.startsWith(t));return n.length===0?{kind:"none"}:n.length===1?{kind:"found",target:n[0]}:{kind:"ambiguous",matches:n}}var Ui=100;function yt(r){return r instanceof Error?r.message:String(r)}async function
|
|
69
|
+
`).filter(Boolean))try{let i=(await this.git("rev-list","-1",n)).trim(),s=n.replace("milestone/","").replace(/-/g," ");e.set(i,s)}catch{}}catch{}return e}async getMilestones(){return(await this.getCheckpoints(100)).filter(t=>t.isMilestone)}git(...e){return new Promise((t,n)=>{let i=(0,Di.spawn)("git",e,{cwd:this.gitDir}),s="",o="";i.stdout.on("data",a=>{s+=a.toString("utf-8")}),i.stderr.on("data",a=>{o+=a.toString("utf-8")}),i.on("error",a=>n(a)),i.on("close",a=>{if(a!==0&&!e.includes("status")){n(new Error(`git ${e.join(" ")} failed: ${o}`));return}t(s)})})}};function Fi(r,e){let t=r.trim();if(t==="")return{kind:"none"};if(t.length===7){let i=e.filter(s=>s.shortHash===t);if(i.length===1)return{kind:"found",target:i[0]};if(i.length>1)return{kind:"ambiguous",matches:i}}if(/^\d+$/.test(t)){let i=parseInt(t,10);return i>=1&&i<=e.length?{kind:"found",target:e[i-1]}:{kind:"none"}}let n=e.filter(i=>i.hash.startsWith(t));return n.length===0?{kind:"none"}:n.length===1?{kind:"found",target:n[0]}:{kind:"ambiguous",matches:n}}var Ui=100;function yt(r){return r instanceof Error?r.message:String(r)}async function Ou(r,e){if(!je.existsSync(r))return{ok:!1,error:`Directory not found: ${r}`};try{let t=new B(r);if(!await t.isInitialized())return{ok:!0,checkpoints:[],truncated:!1};let n=await t.getCheckpoints(e+1),i=n.length>e;return{ok:!0,checkpoints:i?n.slice(0,e):n,truncated:i}}catch(t){return{ok:!1,error:`Failed to read checkpoint history: ${yt(t)}`}}}async function Cu(r,e){if(!je.existsSync(r))return{ok:!1,error:`Directory not found: ${r}`};let t=e.trim();if(!t)return{ok:!1,error:"--message must not be empty."};try{let n=new B(r);await n.isInitialized()||await n.init();let i=await n.detectCurrentChanges(),s=await n.createCheckpoint("manual",i,t);return s?{ok:!0,created:s}:{ok:!1,error:"No changes to checkpoint."}}catch(n){return{ok:!1,error:`Failed to create checkpoint: ${yt(n)}`}}}async function Au(r,e,t){if(!je.existsSync(r))return{ok:!1,error:`Directory not found: ${r}`};try{let n=new B(r);if(!await n.isInitialized())return{ok:!1,error:"No checkpoint history found for this workspace. Checkpoints are created automatically during sync operations."};let i=await n.getCheckpoints(t),s=Fi(e,i);if(s.kind==="none")return{ok:!1,error:`Checkpoint not found: ${e}. Use a number (1-${i.length}) or a commit hash.`};if(s.kind==="ambiguous"){let o=s.matches.slice(0,5).map(l=>l.shortHash).join(", "),a=s.matches.length>5?", \u2026":"";return{ok:!1,error:`Ambiguous reference: ${e} matches ${s.matches.length} checkpoints (${o}${a}). Use a longer prefix or full hash.`}}return{ok:!0,target:s.target}}catch(n){return{ok:!1,error:`Failed to read checkpoint history: ${yt(n)}`}}}async function Tu(r,e){if(!je.existsSync(r))return{ok:!1,error:`Directory not found: ${r}`};try{let t=new B(r);return await t.isInitialized()?(await t.restore(e),{ok:!0}):{ok:!1,error:"No checkpoint history found for this workspace."}}catch(t){return{ok:!1,error:`Failed to restore checkpoint: ${yt(t)}`}}}function ku(r){return r==="local"?`${_}LOCAL${m}`:r==="remote"?`${T}SERVER${m}`:`${de}MANUAL${m}`}function ji(r){let e=Date.now()-r.getTime(),t=Math.floor(e/6e4),n=Math.floor(t/60),i=Math.floor(n/24);return i>7?`${r.toLocaleDateString()} ${r.toLocaleTimeString()}`:i>0?`${i} day${i===1?"":"s"} ago`:n>0?`${n} hour${n===1?"":"s"} ago`:t>0?`${t} minute${t===1?"":"s"} ago`:"just now"}function Pu(r,e,t){if(r.length===0){console.log("No checkpoints found.");return}console.log(`
|
|
70
70
|
${K}Checkpoint History${m}
|
|
71
|
-
`);let n=String(r.length).length;r.forEach((i,s)=>{let o=s+1,a=`${E}${String(o).padStart(n," ")}${m}`,l=i.isMajor?`${P}[MAJOR]${m}`:`${E}[minor]${m}`,u=i.isMilestone?`${P}\u2B50${m} ${de}[${i.milestoneName}]${m} `:"";console.log(`${a} ${P}${i.shortHash}${m} ${u}${
|
|
72
|
-
`)}),e&&console.log(`${E}Showing first ${t} checkpoints. Pass --limit <n> to see more.${m}`),console.log(`${E}Restore: boxel realm history <local-dir> -r <ref>${m}`)}function
|
|
71
|
+
`);let n=String(r.length).length;r.forEach((i,s)=>{let o=s+1,a=`${E}${String(o).padStart(n," ")}${m}`,l=i.isMajor?`${P}[MAJOR]${m}`:`${E}[minor]${m}`,u=i.isMilestone?`${P}\u2B50${m} ${de}[${i.milestoneName}]${m} `:"";console.log(`${a} ${P}${i.shortHash}${m} ${u}${ku(i.source)} ${l} ${i.message} ${E}(${i.filesChanged} files)${m}`),console.log(` ${E}${ji(i.date)}${m}
|
|
72
|
+
`)}),e&&console.log(`${E}Showing first ${t} checkpoints. Pass --limit <n> to see more.${m}`),console.log(`${E}Restore: boxel realm history <local-dir> -r <ref>${m}`)}function Lu(r){if(r===void 0)return Ui;if(!/^\d+$/.test(r))return null;let e=parseInt(r,10);return e>0?e:null}function be(r){console.error(`${y}Error:${m} ${r}`),process.exit(1)}function qi(r){r.command("history").alias("hist").description("View, restore, or create local checkpoints stored under .boxel-history/").argument("<local-dir>","The local workspace directory").option("-r, --restore <ref>","Restore the workspace to a checkpoint (1-based index, short hash, or full hash)").option("-m, --message <message>","Create a manual checkpoint with the given message").option("-y, --yes","Skip the interactive confirmation prompt before --restore").option("--limit <n>",`Maximum number of checkpoints to list or consider for --restore (default: ${Ui})`).action(async(e,t)=>{t.restore!==void 0&&t.message!==void 0&&be("Only one of --restore or --message may be specified.");let n=Lu(t.limit);if(n===null&&be("--limit must be a positive integer."),t.message!==void 0){let s=await Cu(e,t.message);s.ok||be(s.error),console.log(`${_}\u2713${m} Checkpoint created: ${P}${s.created.shortHash}${m} ${s.created.message}`);return}if(t.restore!==void 0){let s=await Au(e,t.restore,n);s.ok||be(s.error);let o=s.target;if(!t.yes){process.stdin.isTTY||be("--restore overwrites local files. Pass --yes to confirm in non-interactive mode."),console.log(`
|
|
73
73
|
${K}Restoring to:${m} ${P}${o.shortHash}${m} - ${o.message}`),console.log(`${E}${ji(o.date)}${m}
|
|
74
|
-
`);let l=await J(`${P}This will overwrite current files. Continue? (y/N) ${m}`);if(!/^y/i.test(l)){console.log(`${E}Restore cancelled.${m}`);return}}let a=await
|
|
74
|
+
`);let l=await J(`${P}This will overwrite current files. Continue? (y/N) ${m}`);if(!/^y/i.test(l)){console.log(`${E}Restore cancelled.${m}`);return}}let a=await Tu(e,o.hash);a.ok||be(a.error),console.log(`${_}\u2713${m} Restored to ${P}${o.shortHash}${m} ${o.message}`),console.log(`${E}Run 'boxel realm sync <local-dir> <realm-url> --prefer-local' to push the restored state to the realm.${m}`);return}let i=await Ou(e,n);i.ok||be(i.error),Pu(i.checkpoints,i.truncated,n)})}var Iu="--all-accessible and --hidden are mutually exclusive";async function Nu(r={}){if(r.allAccessible&&r.hidden)return{realms:[],error:Iu};let e=r.profileManager??O(),t=e.getActiveProfile();if(!t)return{realms:[],error:L};let n=t.profile.realmServerUrl.replace(/\/$/,""),i=await e.authedRealmServerFetch(`${n}/_realm-auth`,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"}});if(!i.ok){let c=await i.text();return{realms:[],error:`Realm auth lookup failed: ${i.status} ${c}`}}let s=await i.json(),o=Object.keys(s).map(C),a;try{a=await e.getUserRealms()}catch(c){return{realms:[],error:`Failed to load UI realm list: ${c instanceof Error?c.message:String(c)}`}}let l=new Set(a.map(C)),u=o.map(c=>({url:c,hidden:!l.has(c)}));return r.allAccessible||(r.hidden?u=u.filter(c=>c.hidden):u=u.filter(c=>!c.hidden)),u.sort((c,f)=>c.url.localeCompare(f.url)),{realms:u}}function Vi(r){r.command("list").alias("ls").description("List realms accessible to the active profile").option("--json","Output JSON").option("--all-accessible","Show all accessible realms, including hidden ones").option("--hidden","Show only realms not in the user's UI realm list").action(async e=>{let t;try{t=await Nu({allAccessible:e.allAccessible,hidden:e.hidden})}catch(n){console.error(`${y}Error:${m} ${n instanceof Error?n.message:String(n)}`),process.exit(1)}if(e.json){console.log(JSON.stringify(t,null,2)),t.error&&process.exit(1);return}if(t.error&&(console.error(`${y}Error:${m} ${t.error}`),process.exit(1)),t.realms.length===0){console.log(`${E}No realms found.${m}`);return}console.log(`${K}${t.realms.length} realm(s):${m}`);for(let n of t.realms){let i=n.hidden?` ${E}(hidden)${m}`:"";console.log(` ${T}${n.url}${m}${i}`)}})}var bl=N(wl()),Rl="realm_server";function qg(r){let{hostname:e}=new URL(r);if(e==="localhost"||e.endsWith(".localhost"))return"localhost";let t=e.split(".");return t.length<=2?e:t.slice(-2).join(".")}function Vg(r,e=Rl){return`@${e}:${qg(r)}`}function Gg(r){return new URL(r).origin+"/"}function Hg(r){try{return new URL(r).href.replace(/\/+$/,"")+"/"}catch{throw new Error(`Invalid realm URL: ${r}`)}}var Xt=class{#e;#t;#r;#i;#n=new Map;constructor(e){if(!e.seed)throw new Error("SeedAuthenticator requires a non-empty seed");this.#e=e.seed,this.#t=e.botUsername??Rl,this.#r=e.botUserId,this.#i=e.expiresIn??"7d"}buildClaims(e){let t=Hg(e);return{user:this.#r??Vg(t,this.#t),realm:t,sessionRoom:void 0,permissions:[],realmServerURL:Gg(t)}}mintTokenForRealm(e){let t=this.buildClaims(e),n=this.#n.get(t.realm);if(n)return n;let i=bl.default.sign(t,this.#e,{expiresIn:this.#i});return this.#n.set(t.realm,i),i}#s(e){for(let s of this.#n.keys())if(e.startsWith(s))return s;let t=new URL(e),n=t.pathname.split("/").filter(Boolean),i=n.length>0?`/${n.slice(0,2).join("/")}/`:"/";return`${t.origin}${i}`}async authedRealmFetch(e,t){let n=e instanceof Request?e.url:e instanceof URL?e.href:e,i=this.#s(n),s=this.mintTokenForRealm(i),o=this.#o(e,t,s);return fetch(e,{...t,headers:o})}#o(e,t,n){let i=e instanceof Request?new Headers(e.headers):new Headers,s=new Headers(t?.headers);for(let[o,a]of s)i.set(o,a);return i.has("Authorization")||i.set("Authorization",n),i}registerRealmUrl(e){this.mintTokenForRealm(e)}};function ye(r){if(r.realmSecretSeed)try{let t=new Xt({seed:r.realmSecretSeed});return t.registerRealmUrl(r.realmUrl),{ok:!0,authenticator:t,mode:"seed"}}catch(t){return{ok:!1,error:t instanceof Error?t.message:String(t)}}let e=r.profileManager??O();return e.getActiveProfile()?{ok:!0,authenticator:e,mode:"profile"}:{ok:!1,error:L}}var zt=N(require("fs/promises")),$l=N(require("path")),Cn=class extends se{constructor(t,n){super(t,n);this.pullOptions=t}hasError=!1;downloadedFiles=[];async sync(){console.log(`Starting pull from ${this.options.realmUrl} to ${this.options.localDir}`),console.log("Testing realm access...");try{await this.getRemoteFileList("")}catch(l){throw console.error("Failed to access realm:",l),new Error("Cannot proceed with pull: Authentication or access failed. Please check your credentials and realm permissions.")}console.log("Realm access verified");let[t,n]=await Promise.all([this.getRemoteFileList(),this.getLocalFileList()]);if(console.log(`Found ${t.size} files in remote realm`),console.log(`Found ${n.size} files in local directory`),this.options.dryRun)try{await zt.access(this.options.localDir)}catch{console.log(`[DRY RUN] Would create directory: ${this.options.localDir}`)}else await zt.mkdir(this.options.localDir,{recursive:!0});let i=new Set;if(this.pullOptions.deleteLocal)for(let l of n.keys())t.has(l)||i.add(l);let s=new B(this.options.localDir);if(i.size>0&&!this.options.dryRun){let l=Array.from(i).map(c=>({file:c,status:"deleted"})),u=await s.createCheckpoint("remote",l,`Pre-delete checkpoint: ${i.size} files not on server`);u&&console.log(`
|
|
75
75
|
Checkpoint created before deletion: ${u.shortHash}`)}let o=await Promise.all(Array.from(t.keys()).map(l=>this.remoteLimit(async()=>{try{let u=$l.join(this.options.localDir,l);return await this.downloadFile(l,u),l}catch(u){return this.hasError=!0,console.error(`Error downloading ${l}:`,u),null}})));this.downloadedFiles=o.filter(l=>l!==null);let a=[];if(i.size>0&&(console.log(`
|
|
76
76
|
Deleting ${i.size} local files that don't exist in realm...`),a=(await Promise.all(Array.from(i).map(async u=>{try{let c=n.get(u);return c?(await this.deleteLocalFile(c),console.log(` Deleted: ${u}`),u):null}catch(c){return this.hasError=!0,console.error(`Error deleting local file ${u}:`,c),null}}))).filter(u=>u!==null)),!this.options.dryRun&&this.downloadedFiles.length+a.length>0){let l=[...this.downloadedFiles.map(c=>({file:c,status:"modified"})),...a.map(c=>({file:c,status:"deleted"}))],u=await s.createCheckpoint("remote",l);if(u){let c=u.isMajor?"[MAJOR]":"[minor]";console.log(`
|
|
77
|
-
Checkpoint created: ${u.shortHash} ${c} ${u.message}`)}}console.log("Pull completed")}};function vl(r){r.command("pull").description("Pull files from a Boxel realm to a local directory").argument("<realm-url>","The URL of the source realm (e.g., https://app.boxel.ai/demo/)").argument("<local-dir>","The local directory to sync files to").option("--delete","Delete local files that do not exist in the realm").option("--dry-run","Show what would be done without making changes").option("--realm-secret-seed","Administrative auth: prompt for a realm secret seed and mint a JWT locally instead of using a Matrix profile (env: BOXEL_REALM_SECRET_SEED)").action(async(e,t,n)=>{let i=await
|
|
78
|
-
Checkpoint created: ${d.shortHash} ${
|
|
79
|
-
${E}Sync plan:${m}`),f.length>0&&console.log(` ${_}\u2191 Push:${m} ${f.length} file(s)`),d.length>0&&console.log(` ${T}\u2193 Pull:${m} ${d.length} file(s)`),
|
|
77
|
+
Checkpoint created: ${u.shortHash} ${c} ${u.message}`)}}console.log("Pull completed")}};function vl(r){r.command("pull").description("Pull files from a Boxel realm to a local directory").argument("<realm-url>","The URL of the source realm (e.g., https://app.boxel.ai/demo/)").argument("<local-dir>","The local directory to sync files to").option("--delete","Delete local files that do not exist in the realm").option("--dry-run","Show what would be done without making changes").option("--realm-secret-seed","Administrative auth: prompt for a realm secret seed and mint a JWT locally instead of using a Matrix profile (env: BOXEL_REALM_SECRET_SEED)").action(async(e,t,n)=>{let i=await pe(n.realmSecretSeed===!0),s=await Wg(e,t,{delete:n.delete,dryRun:n.dryRun,realmSecretSeed:i});s.error&&(console.error(`Error: ${s.error}`),process.exit(s.files.length>0?2:1)),console.log("Pull completed successfully")})}async function Wg(r,e,t){let n;if(t.authenticator)n=t.authenticator;else{let i=ye({realmUrl:r,realmSecretSeed:t.realmSecretSeed,profileManager:t.profileManager});if(!i.ok)return{files:[],error:i.error};n=i.authenticator}try{let i=new Cn({realmUrl:r,localDir:e,deleteLocal:t.delete,dryRun:t.dryRun},n);return await i.sync(),i.hasError?{files:i.downloadedFiles.sort(),error:"Pull completed with errors. Some files may not have been downloaded."}:{files:i.downloadedFiles.sort()}}catch(i){return{files:[],error:`Pull failed: ${i instanceof Error?i.message:String(i)}`}}}var Se=N(require("fs/promises")),An=N(require("path")),Sl=N(require("crypto"));function Bg(r){if(typeof r!="object"||r===null)return!1;let e=r;if(typeof e.realmUrl!="string"||typeof e.files!="object"||e.files===null)return!1;for(let t of Object.values(e.files))if(typeof t!="string")return!1;if(e.remoteMtimes!==void 0){if(typeof e.remoteMtimes!="object"||e.remoteMtimes===null)return!1;for(let t of Object.values(e.remoteMtimes))if(typeof t!="number")return!1}return!0}async function Jt(r){try{return await Se.access(r),!0}catch{return!1}}async function fe(r){let e=await Se.readFile(r);return Sl.createHash("md5").update(e).digest("hex")}async function xe(r){let e=An.join(r,".boxel-sync.json"),t;try{t=await Se.readFile(e,"utf8")}catch(i){if(i.code==="ENOENT")return null;throw i}let n;try{n=JSON.parse(t)}catch{return null}return Bg(n)?n:(console.warn("Warning: .boxel-sync.json is malformed or has an unexpected shape; falling back to a full upload."),null)}async function Ne(r,e){let t=An.join(r,".boxel-sync.json");await Se.writeFile(t,JSON.stringify(e,null,2))}var Yg=new Set(["index.json","realm.json"]),Tn=class extends se{constructor(t,n){super(t,n);this.pushOptions=t}hasError=!1;async sync(){console.log(`Starting push from ${this.options.localDir} to ${this.options.realmUrl}`),console.log("Testing realm access...");let t;try{t=await this.getRemoteFileList("")}catch(c){throw console.error("Failed to access realm:",c),new Error("Cannot proceed with push: Authentication or access failed. Please check your credentials and realm permissions.")}console.log("Realm access verified");let n=await this.getLocalFileList();console.log(`Found ${n.size} files in local directory`);let i=await xe(this.options.localDir),s={realmUrl:this.normalizedRealmUrl,files:{},remoteMtimes:{}},o=new Map,a=new Set;if(!this.pushOptions.force&&i!==null&&i.realmUrl===this.normalizedRealmUrl){console.log("Checking for changed files...");let c=0,[f,d]=await Promise.all([this.getRemoteMtimes(),Promise.all(Array.from(n.entries()).map(async([p,g])=>{if(F(p))return{relativePath:p,localPath:g,currentHash:"",protected:!0};let S=await fe(g);return{relativePath:p,localPath:g,currentHash:S,protected:!1}}))]);for(let p of d){if(p.protected){c++;continue}let g=i.files[p.relativePath],S=i.remoteMtimes?.[p.relativePath],z=f.get(p.relativePath),rt=g!==p.currentHash,R=g!==void 0&&!t.has(p.relativePath),$=S!==void 0&&z!==void 0&&z!==S;rt||R||$?(o.set(p.relativePath,p.localPath),!rt&&(R||$)&&a.add(p.relativePath)):(c++,s.files[p.relativePath]=p.currentHash,S!==void 0&&(s.remoteMtimes[p.relativePath]=S))}if(c>0&&console.log(`Skipping ${c} unchanged files`),a.size>0){let p=Array.from(a),g=p.slice(0,5).join(", "),S=p.length>5?", ...":"";console.warn(`Warning: ${a.size} file(s) changed on the realm since your last push; your local versions will overwrite them: ${g}${S}`)}}else{this.pushOptions.force?console.log("Force mode: uploading all files"):console.log(i?"Realm URL changed, will upload all files":"No sync manifest found, will upload all files");for(let[c,f]of n)F(c)||o.set(c,f)}let u=!1;if(o.size===0)console.log("No files to upload - everything is up to date");else{console.log(`Uploading ${o.size} file(s) via /_atomic...`);let c=new Set,f=this.pushOptions.force||!i;for(let p of o.keys())if(f)t.has(p)||c.add(p);else{let g=i.files[p]!==void 0,S=g&&!t.has(p);(!g||S)&&c.add(p)}let d=await this.uploadFilesAtomic(o,c);if(d.error){u=!0,this.hasError=!0,console.error(d.error.message);for(let p of d.error.perFile){let g;p.status===409?g=`${p.path} was created on the realm concurrently \u2014 run with --force to overwrite.`:p.status===404?g=`${p.path} was removed from the realm concurrently \u2014 run with --force to re-create it from your local copy.`:g=`${p.path}: ${p.title}`,console.error(` ${g}`)}}else if(d.succeeded.length>0){let p=await Promise.all(d.succeeded.map(async g=>({rel:g,hash:await fe(o.get(g))})));for(let{rel:g,hash:S}of p)s.files[g]=S}}if(this.pushOptions.deleteRemote){let c=new Set(t.keys()),f=[];for(let d of c){if(F(d)){c.delete(d);continue}Yg.has(d)&&(c.delete(d),f.push(d))}for(let d of n.keys())c.delete(d);if(f.length>0&&console.log(`Skipping ${f.length} realm-managed remote artifact(s): ${f.join(", ")}`),c.size>0){let d=Array.from(c).sort();console.log(`Deleting ${d.length} remote files that don't exist locally: ${d.join(", ")}`);for(let p of d)try{await this.deleteFile(p)}catch(g){this.hasError=!0,console.error(`Error deleting ${p}:`,g)}}}if(!this.options.dryRun&&!u&&o.size>0)try{let c=await this.getRemoteMtimes();for(let f of Object.keys(s.files)){let d=c.get(f);d!==void 0&&(s.remoteMtimes[f]=d)}}catch(c){console.warn("Could not refresh remote mtimes after upload:",c)}if(s.remoteMtimes&&Object.keys(s.remoteMtimes).length===0&&delete s.remoteMtimes,!this.options.dryRun&&!u&&await Ne(this.options.localDir,s),!this.options.dryRun&&o.size>0&&!u){let c=new B(this.options.localDir),f=Array.from(o.keys()).map(p=>({file:p,status:"modified"})),d=await c.createCheckpoint("local",f);if(d){let p=d.isMajor?"[MAJOR]":"[minor]";console.log(`
|
|
78
|
+
Checkpoint created: ${d.shortHash} ${p} ${d.message}`)}}console.log("Push completed")}};function xl(r){r.command("push").description("Push local files to a Boxel realm").argument("<local-dir>","The local directory containing files to sync").argument("<realm-url>","The URL of the target realm (e.g., https://app.boxel.ai/demo/)").option("--delete","Delete remote files that do not exist locally").option("--dry-run","Show what would be done without making changes").option("--force","Upload all files, even if unchanged").option("--realm-secret-seed","Administrative auth: prompt for a realm secret seed and mint a JWT locally instead of using a Matrix profile (env: BOXEL_REALM_SECRET_SEED)").action(async(e,t,n)=>{let i=await pe(n.realmSecretSeed===!0);await Xg(e,t,{delete:n.delete,dryRun:n.dryRun,force:n.force,realmSecretSeed:i})})}async function Xg(r,e,t){let n;if(t.authenticator)n=t.authenticator;else{let i=ye({realmUrl:e,realmSecretSeed:t.realmSecretSeed,profileManager:t.profileManager});i.ok||(console.error(`Error: ${i.error}`),process.exit(1)),n=i.authenticator}await Jt(r)||(console.error(`Local directory does not exist: ${r}`),process.exit(1));try{let i=new Tn({realmUrl:e,localDir:r,deleteRemote:t.delete,dryRun:t.dryRun,force:t.force},n);await i.sync(),i.hasError?(console.log("Push did not complete successfully. View logs for details"),process.exit(2)):console.log("Push completed successfully")}catch(i){console.error("Push failed:",i),process.exit(1)}}async function _l(r){let e=C(r.realmUrl.trim()),t=r.profileManager??O(),n=t.getActiveProfile();if(!n)return{realmUrl:e,removed:!1,serverDeleted:!1,unlinked:!1,previousCount:0,nextCount:0,error:L};let i;try{i=await t.getUserRealms()}catch(d){return{realmUrl:e,removed:!1,serverDeleted:!1,unlinked:!1,previousCount:0,nextCount:0,error:`Failed to load realm list: ${d instanceof Error?d.message:String(d)}`}}let s=i.map(C),o=s.length,a=s.filter(d=>d===e).length;if(a===0)return{realmUrl:e,removed:!1,serverDeleted:!1,unlinked:!1,previousCount:o,nextCount:o,notInList:!0,error:"Realm is not in app.boxel.realms. Nothing to remove."};let l=o-a;if(r.dryRun)return{realmUrl:e,removed:!1,serverDeleted:!1,unlinked:!1,previousCount:o,nextCount:l};let u=n.profile.realmServerUrl.replace(/\/$/,""),c;try{c=await t.authedRealmServerFetch(`${u}/_delete-realm`,{method:"DELETE",headers:{"Content-Type":"application/vnd.api+json"},body:JSON.stringify({data:{type:"realm",id:e}})})}catch(d){return{realmUrl:e,removed:!1,serverDeleted:!1,unlinked:!1,previousCount:o,nextCount:o,error:`Failed to reach realm server: ${d instanceof Error?d.message:String(d)}`}}if(!c.ok){let d=await zg(c),p=c.status===403?`You do not own this realm and cannot delete it on the server. Server returned 403: ${d}`:`Realm server returned ${c.status}: ${d}`;return{realmUrl:e,removed:!1,serverDeleted:!1,unlinked:!1,previousCount:o,nextCount:o,error:p}}let f;try{f=await t.removeFromUserRealms(e)}catch(d){return{realmUrl:e,removed:!1,serverDeleted:!0,unlinked:!1,previousCount:o,nextCount:o,error:`Server delete succeeded, but Matrix unlink failed: ${d instanceof Error?d.message:String(d)}`}}return f?{realmUrl:e,removed:!0,serverDeleted:!0,unlinked:f,previousCount:o,nextCount:l}:{realmUrl:e,removed:!1,serverDeleted:!0,unlinked:!1,previousCount:o,nextCount:o,error:"Server delete succeeded, but Matrix account_data did not contain the URL by the time we PUT (concurrent edit?). Server-side files are gone; please refresh and check your realm list."}}async function zg(r){try{return await r.text()}catch{return"<no response body>"}}function Ol(r){r.command("remove").description("Remove a realm \u2014 deletes server-side files and unlinks it from your realm list").argument("<realm-url>","realm URL to remove").option("-y, --yes","Skip the interactive confirmation prompt").option("--dry-run","Preview the change without writing to Matrix").action(async(e,t)=>{let n=C(e.trim()),i=await _l({realmUrl:n,dryRun:!0});if(i.error&&!i.notInList&&(console.error(`${y}Error:${m} ${i.error}`),process.exit(1)),i.notInList&&(console.error(`${y}Error:${m} ${i.error}`),process.exit(1)),console.log(`Remove target: ${T}${i.realmUrl}${m}`),console.log(`${E}app.boxel.realms: ${i.previousCount} -> ${i.nextCount}${m}`),t.dryRun){console.log(`${E}[DRY RUN] No server delete or Matrix changes sent.${m}`);return}if(!t.yes){process.stdin.isTTY||(console.error(`${y}Error:${m} stdin is not a TTY. Pass --yes to confirm in non-interactive mode.`),process.exit(1));let o=await J("This will permanently delete the realm files, indexer state, and registry entry on the server. Proceed? (y/N) ");if(!/^y/i.test(o)){console.log(`${E}Cancelled.${m}`);return}}let s=await _l({realmUrl:n});(s.error||!s.removed)&&(console.error(`${y}Error:${m} ${s.error??"Removal did not complete."}`),s.serverDeleted&&!s.unlinked&&console.error(`${E}The realm is gone, but your account_data still references ${s.realmUrl}.${m}`),process.exit(1)),console.log(`${_}Removed:${m} ${T}${s.realmUrl}${m}`)})}var Pn=N(require("path"));function Cl(r,e,t){let n=e.has(r),i=t?.files[r]!==void 0;return n&&i?e.get(r)===t.files[r]?"unchanged":"changed":n&&!i?"added":!n&&i?"deleted":"unchanged"}function Al(r,e,t){let n=e.has(r),i=t?.remoteMtimes?.[r]!==void 0,s=t?.files[r]!==void 0,o=i||s;return n&&i?e.get(r)===t.remoteMtimes[r]?"unchanged":"changed":n&&s?"changed":n&&!o?"added":!n&&o?"deleted":"unchanged"}function Tl(r,e,t){return r==="unchanged"&&e==="unchanged"?"noop":r==="changed"&&e==="unchanged"?"push":r==="unchanged"&&e==="changed"?"pull":r==="added"&&e==="unchanged"?"push":r==="unchanged"&&e==="added"?"pull":r==="changed"&&e==="changed"||r==="added"&&e==="added"||r==="changed"&&e==="added"||r==="added"&&e==="changed"?"conflict":r==="deleted"&&e==="unchanged"?t.deleteSync||t.preferLocal?"push-delete":"noop":r==="unchanged"&&e==="deleted"?t.deleteSync||t.preferRemote?"pull-delete":"noop":r==="deleted"&&e==="changed"||r==="changed"&&e==="deleted"?"conflict":r==="deleted"&&e==="deleted"?"noop":r==="added"&&e==="deleted"?"push":r==="deleted"&&e==="added"?"pull":"noop"}function kl(r,e,t,n){let{localStatus:i,remoteStatus:s,relativePath:o}=r;if(!n)return null;switch(n){case"prefer-local":return i==="deleted"?"push-delete":"push";case"prefer-remote":return s==="deleted"?"pull-delete":"pull";case"prefer-newest":{if(i==="deleted"&&s==="changed")return"pull";if(i==="changed"&&s==="deleted")return"push";let a=e.get(o),l=t.get(o);return a&&l!==void 0?a.mtime>l*1e3?"push":"pull":"push"}}}var Ln=class extends se{constructor(t,n){super(t,n);this.syncOptions=t}hasError=!1;pushedFiles=[];pulledFiles=[];remoteDeletedFiles=[];localDeletedFiles=[];skippedConflicts=[];get conflictStrategy(){return this.syncOptions.preferLocal?"prefer-local":this.syncOptions.preferRemote?"prefer-remote":this.syncOptions.preferNewest?"prefer-newest":null}async sync(){console.log(`Starting sync between ${this.options.localDir} and ${this.options.realmUrl}`),console.log("Testing realm access...");let t;try{t=await this.getRemoteFileList("")}catch(R){throw console.error("Failed to access realm:",R),new Error("Cannot proceed with sync: Authentication or access failed. Please check your credentials and realm permissions.")}console.log("Realm access verified");let[n,i,s]=await Promise.all([this.getLocalFileListWithMtimes(),this.getRemoteMtimes(),xe(this.options.localDir)]),o=new Map;for(let[R,$]of n)o.set(R,$.path);if(i.size===0&&t&&t.size>0){console.log("Remote mtimes unavailable, falling back to file listing for remote detection");for(let[R]of t)i.set(R,0)}console.log(`Found ${o.size} local files`),console.log(`Found ${i.size} remote files`),s&&s.realmUrl!==this.normalizedRealmUrl&&console.warn(`${P}Warning:${m} Manifest realm URL (${s.realmUrl}) differs from target (${this.normalizedRealmUrl}). Treating as first sync.`);let a=s&&s.realmUrl===this.normalizedRealmUrl?s:null,l=new Map;await Promise.all(Array.from(o.entries()).map(async([R,$])=>{F(R)||l.set(R,await fe($))}));let u=new Set;for(let R of o.keys())u.add(R);for(let R of i.keys())u.add(R);if(a){for(let R of Object.keys(a.files))u.add(R);if(a.remoteMtimes)for(let R of Object.keys(a.remoteMtimes))u.add(R)}let c=[];for(let R of u){if(F(R))continue;let $=Cl(R,l,a),x=Al(R,i,a),D=Tl($,x,this.syncOptions);c.push({relativePath:R,localStatus:$,remoteStatus:x,action:D})}let f=[],d=[],p=[],g=[],S=[],z=0;for(let R of c)switch(R.action){case"push":f.push(R.relativePath);break;case"pull":d.push(R.relativePath);break;case"push-delete":p.push(R.relativePath);break;case"pull-delete":g.push(R.relativePath);break;case"conflict":S.push(R);break;case"noop":z++;break}for(let R of S)switch(kl(R,n,i,this.conflictStrategy)){case"push":f.push(R.relativePath);break;case"pull":d.push(R.relativePath);break;case"push-delete":p.push(R.relativePath);break;case"pull-delete":g.push(R.relativePath);break;case"noop":break;default:this.skippedConflicts.push(R.relativePath);break}if(console.log(`
|
|
79
|
+
${E}Sync plan:${m}`),f.length>0&&console.log(` ${_}\u2191 Push:${m} ${f.length} file(s)`),d.length>0&&console.log(` ${T}\u2193 Pull:${m} ${d.length} file(s)`),p.length>0&&console.log(` ${y}\u2191 Delete remote:${m} ${p.length} file(s)`),g.length>0&&console.log(` ${y}\u2193 Delete local:${m} ${g.length} file(s)`),this.skippedConflicts.length>0){console.log(` ${P}\u26A0 Conflicts skipped:${m} ${this.skippedConflicts.length} file(s)`);for(let R of this.skippedConflicts)console.log(` ${R}`);console.log(` ${E}Use --prefer-local, --prefer-remote, or --prefer-newest to resolve.${m}`)}if(z>0&&console.log(` ${E}Unchanged: ${z} file(s)${m}`),f.length+d.length+p.length+g.length===0){console.log(`
|
|
80
80
|
Everything is up to date`),!this.options.dryRun&&!a&&this.skippedConflicts.length===0&&await this.writeManifest(l,i);return}if(d.length>0){console.log(`
|
|
81
81
|
Pulling ${d.length} file(s)...`);let R=await Promise.all(d.map($=>this.remoteLimit(async()=>{try{let x=Pn.join(this.options.localDir,$);return await this.downloadFile($,x),$}catch(x){return this.hasError=!0,console.error(`Error downloading ${$}:`,x),null}})));this.pulledFiles.push(...R.filter($=>$!==null))}if(f.length>0){console.log(`
|
|
82
|
-
Pushing ${f.length} file(s)...`);let R=new Map;for(let D of f){let nt=o.get(D);nt&&R.set(D,nt)}let $=new Set;for(let D of R.keys()){let nt=a?.files[D]!==void 0,
|
|
83
|
-
Deleting ${
|
|
84
|
-
Deleting ${
|
|
82
|
+
Pushing ${f.length} file(s)...`);let R=new Map;for(let D of f){let nt=o.get(D);nt&&R.set(D,nt)}let $=new Set;for(let D of R.keys()){let nt=a?.files[D]!==void 0,ec=i.has(D);!nt&&!ec&&$.add(D)}let x=await this.uploadFilesAtomic(R,$);if(x.error){this.hasError=!0,console.error(x.error.message);for(let D of x.error.perFile)console.error(` ${D.path}: ${D.title}`)}else this.pushedFiles.push(...x.succeeded)}if(p.length>0){console.log(`
|
|
83
|
+
Deleting ${p.length} remote file(s)...`);let R=await Promise.all(p.map($=>this.remoteLimit(async()=>{try{return await this.deleteFile($),$}catch(x){return this.hasError=!0,console.error(`Error deleting remote ${$}:`,x),null}})));this.remoteDeletedFiles.push(...R.filter($=>$!==null))}if(g.length>0){console.log(`
|
|
84
|
+
Deleting ${g.length} local file(s)...`);let R=await Promise.all(g.map(async $=>{try{let x=o.get($);return x?(await this.deleteLocalFile(x),$):null}catch(x){return this.hasError=!0,console.error(`Error deleting local ${$}:`,x),null}}));this.localDeletedFiles.push(...R.filter($=>$!==null))}if(!this.options.dryRun&&!this.hasError){let R=new Map;if(a)for(let[x,D]of Object.entries(a.files))R.set(x,D);for(let[x,D]of l)R.set(x,D);for(let x of this.pushedFiles){let D=o.get(x);D&&R.set(x,await fe(D))}for(let x of this.pulledFiles){let D=Pn.join(this.options.localDir,x);R.set(x,await fe(D))}for(let x of this.remoteDeletedFiles)R.delete(x);for(let x of this.localDeletedFiles)R.delete(x);let $=i;if(this.pushedFiles.length>0||this.remoteDeletedFiles.length>0)try{$=await this.getRemoteMtimes()}catch{console.warn("Could not refresh remote mtimes after sync")}await this.writeManifest(R,$)}if(!this.options.dryRun){let R=[...this.pushedFiles.map($=>({file:$,status:"modified"})),...this.pulledFiles.map($=>({file:$,status:"modified"})),...this.remoteDeletedFiles.map($=>({file:$,status:"deleted"})),...this.localDeletedFiles.map($=>({file:$,status:"deleted"}))];if(R.length>0){let x=await new B(this.options.localDir).createCheckpoint("local",R);if(x){let D=x.isMajor?"[MAJOR]":"[minor]";console.log(`
|
|
85
85
|
Checkpoint created: ${x.shortHash} ${D} ${x.message}`)}}}console.log(`
|
|
86
|
-
Sync completed`)}async writeManifest(t,n){let i={realmUrl:this.normalizedRealmUrl,files:{},remoteMtimes:{}};for(let[s,o]of t){i.files[s]=o;let a=n.get(s);a!==void 0&&a!==0&&(i.remoteMtimes[s]=a)}i.remoteMtimes&&Object.keys(i.remoteMtimes).length===0&&delete i.remoteMtimes,await
|
|
87
|
-
`),{ok:!0,staleOverwrote:n}}async function Kt(r){try{await Ee.unlink(In(r))}catch(e){if(e?.code!=="ENOENT")throw e}}var Nn=class extends se{name;debounceMs;checkpointManager;lastKnownMtimes=new Map;pendingChanges=new Map;debounceTimer=null;isShutdown=!1;constructor(e,t,n){super({realmUrl:e.realmUrl,localDir:e.localDir},t),this.debounceMs=n.debounceMs,this.checkpointManager=new B(e.localDir),this.name=
|
|
88
|
-
`)}let l=async()=>{await Promise.all(a.map(async d=>{try{await d.poll()&&(i||console.log(`${E}[${Mn()}]${m} [${d.name}] ${P}\u26A1 ${d.pendingCount} change(s) detected${m}`),d.scheduleFlush(
|
|
89
|
-
${T}\u21C5 Watch stopped${m}`),S()},
|
|
86
|
+
Sync completed`)}async writeManifest(t,n){let i={realmUrl:this.normalizedRealmUrl,files:{},remoteMtimes:{}};for(let[s,o]of t){i.files[s]=o;let a=n.get(s);a!==void 0&&a!==0&&(i.remoteMtimes[s]=a)}i.remoteMtimes&&Object.keys(i.remoteMtimes).length===0&&delete i.remoteMtimes,await Ne(this.options.localDir,i)}};function Pl(r){r.command("sync").description("Bidirectional sync between a local directory and a Boxel realm").argument("<local-dir>","The local directory to sync").argument("<realm-url>","The URL of the target realm (e.g., https://app.boxel.ai/demo/)").option("--prefer-local","Resolve conflicts by keeping local version").option("--prefer-remote","Resolve conflicts by keeping remote version").option("--prefer-newest","Resolve conflicts by keeping newest version").option("--delete","Sync deletions both ways").option("--dry-run","Preview without making changes").option("--realm-secret-seed","Administrative auth: prompt for a realm secret seed and mint a JWT locally instead of using a Matrix profile (env: BOXEL_REALM_SECRET_SEED)").action(async(e,t,n)=>{let i=await pe(n.realmSecretSeed===!0),s=await Jg(e,t,{preferLocal:n.preferLocal,preferRemote:n.preferRemote,preferNewest:n.preferNewest,delete:n.delete,dryRun:n.dryRun,realmSecretSeed:i}),o=Array.isArray(s.pushed)&&s.pushed.length>0||Array.isArray(s.pulled)&&s.pulled.length>0||Array.isArray(s.remoteDeleted)&&s.remoteDeleted.length>0||Array.isArray(s.localDeleted)&&s.localDeleted.length>0;s.error&&(console.error(`Error: ${s.error}`),process.exit(o?2:1)),console.log("Sync completed successfully")})}async function Jg(r,e,t){let n;if(t.authenticator)n=t.authenticator;else{let o=ye({realmUrl:e,realmSecretSeed:t.realmSecretSeed,profileManager:t.profileManager});if(!o.ok)return kn({error:o.error});n=o.authenticator}if([t.preferLocal,t.preferRemote,t.preferNewest].filter(Boolean).length>1)return kn({error:"Only one conflict strategy can be specified (--prefer-local, --prefer-remote, or --prefer-newest)."});if(!await Jt(r))return kn({error:`Local directory does not exist: ${r}`});let s;try{s=new Ln({realmUrl:e,localDir:r,preferLocal:t.preferLocal,preferRemote:t.preferRemote,preferNewest:t.preferNewest,deleteSync:t.delete,dryRun:t.dryRun,waitForIndex:t.waitForIndex},n),await s.sync()}catch(o){return{pushed:s?.pushedFiles.slice().sort()??[],pulled:s?.pulledFiles.slice().sort()??[],remoteDeleted:s?.remoteDeletedFiles.slice().sort()??[],localDeleted:s?.localDeletedFiles.slice().sort()??[],skippedConflicts:s?.skippedConflicts.slice().sort()??[],hasError:!0,error:`Sync failed: ${o instanceof Error?o.message:String(o)}`}}return{pushed:s.pushedFiles.slice().sort(),pulled:s.pulledFiles.slice().sort(),remoteDeleted:s.remoteDeletedFiles.slice().sort(),localDeleted:s.localDeletedFiles.slice().sort(),skippedConflicts:s.skippedConflicts.slice().sort(),hasError:s.hasError,error:s.hasError?Kg(s):void 0}}function Kg(r){return`Sync completed with errors. ${[`${r.pushedFiles.length} pushed`,`${r.pulledFiles.length} pulled`,`${r.remoteDeletedFiles.length} remote deleted`,`${r.localDeletedFiles.length} local deleted`,`${r.skippedConflicts.length} conflicts skipped`].join(", ")}.`}function kn(r){return{pushed:[],pulled:[],remoteDeleted:[],localDeleted:[],skippedConflicts:[],hasError:!0,...r}}var Ll=N(lt());function Qg(r){let e=Number.parseInt(r,10);if(!Number.isFinite(e)||e<0||String(e)!==r.trim())throw new Ll.InvalidArgumentError("--timeout must be a non-negative integer (milliseconds).");return e}async function Zg(r,e={}){let t=e.timeoutMs??3e4;if(!Number.isFinite(t)||t<0)return{ready:!1,error:`Invalid timeoutMs: must be a finite, non-negative number (got ${e.timeoutMs}).`};let n=e.profileManager??O();if(!n.getActiveProfile())return{ready:!1,error:L};let s=`${C(r)}_readiness-check`,o=Date.now();for(;Date.now()-o<t;){try{if((await n.authedRealmFetch(s,{method:"GET",headers:{Accept:"application/vnd.api+json"}})).ok)return{ready:!0}}catch{}let a=t-(Date.now()-o);if(a<=0)break;await new Promise(l=>setTimeout(l,Math.min(1e3,a)))}return{ready:!1,error:`Realm not ready after ${t}ms: ${s}`}}function Il(r){r.command("wait-for-ready").description("Poll a realm readiness-check endpoint until it responds OK or the timeout is reached").requiredOption("--realm <realm-url>","The realm URL to check").option("--timeout <ms>","Timeout in milliseconds (default: 30000)",Qg).action(async e=>{let t;try{t=await Zg(e.realm,{timeoutMs:e.timeout})}catch(n){console.error(`${y}Error:${m} ${n instanceof Error?n.message:String(n)}`),process.exit(1)}t.ready?console.log(`${_}Realm is ready.${m}`):(console.error(`${y}Error:${m} ${t.error??"Realm not ready"}`),process.exit(1))})}var Dn=N(lt()),Dl=N(require("fs/promises")),Ze=N(require("path"));var Ee=N(require("fs/promises")),Nl=N(require("path")),ey=".boxel-watch.lock";function In(r){return Nl.join(r,ey)}function ty(r){try{return process.kill(r,0),!0}catch(e){return e?.code==="EPERM"}}async function ry(r){try{let e=await Ee.readFile(In(r),"utf8"),t=JSON.parse(e);return typeof t.pid!="number"||typeof t.startedAt!="string"||typeof t.realmUrl!="string"?null:t}catch{return null}}async function Ml(r,e){await Ee.mkdir(r,{recursive:!0});let t=await ry(r),n=!1;if(t&&ty(t.pid))return{ok:!1,existing:t};t&&(n=!0);let i={pid:process.pid,startedAt:new Date().toISOString(),realmUrl:e};return await Ee.writeFile(In(r),JSON.stringify(i,null,2)+`
|
|
87
|
+
`),{ok:!0,staleOverwrote:n}}async function Kt(r){try{await Ee.unlink(In(r))}catch(e){if(e?.code!=="ENOENT")throw e}}var Nn=class extends se{name;debounceMs;checkpointManager;lastKnownMtimes=new Map;pendingChanges=new Map;debounceTimer=null;isShutdown=!1;constructor(e,t,n){super({realmUrl:e.realmUrl,localDir:e.localDir},t),this.debounceMs=n.debounceMs,this.checkpointManager=new B(e.localDir),this.name=oy(this.normalizedRealmUrl)}async sync(){await this.poll(),await this.flushPending()}async getRemoteMtimes(){let e=`${this.normalizedRealmUrl}_mtimes`,t=await this.authenticator.authedRealmFetch(e,{headers:{Accept:"application/vnd.api+json"}});if(!t.ok)throw new Error(`_mtimes fetch failed for ${this.normalizedRealmUrl}: ${t.status} ${t.statusText}`);let n=await t.json(),i=new Map;for(let[s,o]of Object.entries(n.data?.attributes?.mtimes??{}))i.set(s.replace(this.normalizedRealmUrl,""),o);return i}get localDir(){return this.options.localDir}get realmUrl(){return this.normalizedRealmUrl}get pendingCount(){return this.pendingChanges.size}async initialize(){await this.getRemoteMtimes(),await this.checkpointManager.isInitialized()||await this.checkpointManager.init();let e=await xe(this.options.localDir);if(e&&e.realmUrl===this.normalizedRealmUrl&&e.remoteMtimes)for(let[t,n]of Object.entries(e.remoteMtimes))this.lastKnownMtimes.set(t,n)}async poll(){let e=await this.getRemoteMtimes(),t=!1;for(let[n,i]of e){if(F(n))continue;let s=this.lastKnownMtimes.get(n);s===void 0?this.recordPending(n,{status:"added",mtime:i})&&(t=!0):i>s&&this.recordPending(n,{status:"modified",mtime:i})&&(t=!0)}for(let n of this.lastKnownMtimes.keys())F(n)||e.has(n)||this.pendingChanges.get(n)?.status!=="deleted"&&(this.pendingChanges.set(n,{status:"deleted",mtime:0}),t=!0);return t}async flushPending(){if(this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.pendingChanges.size===0)return{pulled:[],deleted:[],checkpoint:null};let e=new Map(this.pendingChanges);this.pendingChanges.clear();let t=[],n=[],i=[];for(let[o,a]of e)if(a.status==="deleted"){let l=Ze.join(this.options.localDir,o);try{await Dl.unlink(l)}catch(u){if(u.code!=="ENOENT")throw u}n.push(o),i.push({file:o,status:"deleted"})}else{let l=Ze.join(this.options.localDir,o);await this.downloadFile(o,l),t.push(o),i.push({file:o,status:a.status})}for(let[o,a]of e)a.status==="deleted"?this.lastKnownMtimes.delete(o):this.lastKnownMtimes.set(o,a.mtime);await this.persistManifest(t,n);let s=await this.checkpointManager.createCheckpoint("remote",i);return{pulled:t,deleted:n,checkpoint:s}}scheduleFlush(e){this.isShutdown||(this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(async()=>{this.debounceTimer=null;try{let t=await this.flushPending();e?.(t)}catch(t){console.error(`${y}[${this.name}] Error applying changes:${m}`,t)}},this.debounceMs))}shutdown(){this.isShutdown=!0,this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null)}recordPending(e,t){let n=this.pendingChanges.get(e);return n&&n.mtime===t.mtime?!1:(this.pendingChanges.set(e,t),!0)}async persistManifest(e,t){let n=await xe(this.options.localDir),i=n?.files?{...n.files}:{};for(let a of t)delete i[a];for(let a of e){let l=Ze.join(this.options.localDir,a);try{i[a]=await fe(l)}catch(u){if(u.code!=="ENOENT")throw u}}let s={};for(let[a,l]of this.lastKnownMtimes)l!==0&&(s[a]=l);let o={realmUrl:this.normalizedRealmUrl,files:i};Object.keys(s).length>0&&(o.remoteMtimes=s),await Ne(this.options.localDir,o)}};async function ny(r,e={}){if(r.length===0)return{watchers:[],error:"No realms provided to watch."};let t=e.intervalMs??3e4,n=e.debounceMs??5e3,i=e.quiet??!1;if(!Number.isFinite(t)||t<=0)return{watchers:[],error:"`intervalMs` must be a positive number."};if(!Number.isFinite(n)||n<0)return{watchers:[],error:"`debounceMs` must be a non-negative number."};let s;if(e.authenticator)s=e.authenticator;else{let d=ye({realmUrl:r[0].realmUrl,realmSecretSeed:e.realmSecretSeed,profileManager:e.profileManager});if(!d.ok)return{watchers:[],error:d.error};s=d.authenticator}let o=[];for(let d of r){let p=await Ml(d.localDir,d.realmUrl);if(!p.ok){for(let g of o)await Kt(g);return{watchers:[],error:iy(d.localDir,p.existing)}}p.staleOverwrote&&!i&&console.log(`${E}[${Mn()}] overwrote stale lock at ${d.localDir}${m}`),o.push(d.localDir)}let a=[];for(let d of r){let p=new Nn(d,s,{debounceMs:n});try{await p.initialize()}catch(g){for(let S of a)S.shutdown();for(let S of o)await Kt(S);return{watchers:[],error:`Failed to initialize watch on ${d.realmUrl}: ${g instanceof Error?g.message:String(g)}`}}a.push(p)}if(!i){console.log(`${T}\u21C5 Watching ${a.length} realm${a.length>1?"s":""}:${m}`);for(let d of a)console.log(` ${d.name} ${E}\u2192${m} ${d.localDir}`);console.log(` ${E}Interval: ${t/1e3}s, Debounce: ${n/1e3}s${m}`),console.log(` ${E}Press Ctrl+C to stop${m}
|
|
88
|
+
`)}let l=async()=>{await Promise.all(a.map(async d=>{try{await d.poll()&&(i||console.log(`${E}[${Mn()}]${m} [${d.name}] ${P}\u26A1 ${d.pendingCount} change(s) detected${m}`),d.scheduleFlush(g=>{i||sy(d.name,g)}))}catch(p){console.error(`${y}[${d.name}] poll error:${m}`,p instanceof Error?p.message:p)}}))},u=!1,c=null,f=()=>{u||(c=setTimeout(async()=>{c=null,!u&&(await l(),f())},t))};return await l(),f(),await new Promise(d=>{let p=null,g=null,S=async()=>{if(!u){u=!0,c!==null&&(clearTimeout(c),c=null);for(let z of a)z.shutdown();p&&process.off("SIGINT",p),g&&process.off("SIGTERM",g);for(let z of o)try{await Kt(z)}catch{}d()}};if(e.signal){if(e.signal.aborted){S();return}e.signal.addEventListener("abort",()=>void S(),{once:!0})}else p=()=>{i||console.log(`
|
|
89
|
+
${T}\u21C5 Watch stopped${m}`),S()},g=p,process.on("SIGINT",p),process.on("SIGTERM",g)}),{watchers:a}}function iy(r,e){return`A boxel realm watch process is already active for ${r} (pid ${e.pid}, started ${e.startedAt}). Stop it before starting a new one, or remove ${Ze.join(r,".boxel-watch.lock")} if it's stale.`}function sy(r,e){let t=e.pulled.length+e.deleted.length;if(t!==0&&(console.log(`${E}[${Mn()}]${m} [${r}] ${_}applied ${t} change(s)${m} (${e.pulled.length} pulled, ${e.deleted.length} deleted)`),e.checkpoint)){let n=e.checkpoint.isMajor?"[MAJOR]":"[minor]";console.log(` ${E}Checkpoint:${m} ${e.checkpoint.shortHash} ${n} ${e.checkpoint.message}`)}}function oy(r){return r.replace(/\/$/,"").split("/").slice(-2).join("/")}function Mn(){return new Date().toLocaleTimeString()}function ay(r){return e=>{let t=Number.parseFloat(e);if(!Number.isFinite(t)||t<=0)throw new Dn.InvalidArgumentError(`${r} must be a positive number.`);return t}}function ly(r){return e=>{let t=Number.parseFloat(e);if(!Number.isFinite(t)||t<0)throw new Dn.InvalidArgumentError(`${r} must be a non-negative number.`);return t}}function Fl(r){r.command("watch").description("Watch a Boxel realm for server-side changes and pull them into a local directory").argument("<realm-url>","The URL of the realm to watch (e.g., https://app.boxel.ai/demo/)").argument("<local-dir>","The local directory to write changes into").option("-i, --interval <seconds>","Polling interval in seconds",ay("--interval"),30).option("-d, --debounce <seconds>","Seconds to wait after a burst of changes before applying them",ly("--debounce"),5).option("--realm-secret-seed","Administrative auth: prompt for a realm secret seed and mint a JWT locally instead of using a Matrix profile (env: BOXEL_REALM_SECRET_SEED)").action(async(e,t,n)=>{let i=await pe(n.realmSecretSeed===!0),s=await ny([{realmUrl:e,localDir:t}],{intervalMs:n.interval*1e3,debounceMs:n.debounce*1e3,realmSecretSeed:i});s.error&&(console.error(`${y}Error:${m} ${s.error}`),process.exit(1))})}function Ul(r){let e=r.command("realm").description("Manage realms on the realm server");wi(e),vi(e),qi(e),Vi(e),vl(e),xl(e),Ol(e),Pl(e),Il(e),Fl(e)}async function cy(r,e,t){let n=t?.profileManager??O();if(!n.getActiveProfile())return{ok:!1,error:L};if(F(e))return{ok:!1,error:`Cannot delete protected file: ${e}`};let s=new URL(e,C(r)).href,o;try{o=await n.authedRealmFetch(s,{method:"DELETE",headers:{Accept:"application/vnd.card+source"}})}catch(a){return{ok:!1,error:a instanceof Error?a.message:String(a)}}if(!o.ok){let a=await o.text().catch(()=>"(no body)");return{ok:!1,error:`HTTP ${o.status}: ${a.slice(0,300)}`}}return{ok:!0}}function jl(r){r.command("delete").description("Delete a file from a realm").argument("<path>","Realm-relative file path to delete").requiredOption("--realm <realm-url>","The realm URL to delete from").option("--json","Output raw JSON response").action(async(e,t)=>{let n;try{n=await cy(t.realm,e)}catch(i){console.error(`${y}Error:${m} ${i instanceof Error?i.message:String(i)}`),process.exit(1)}t.json?M.output(JSON.stringify(n,null,2)):n.ok?console.log(`${E}Deleted:${m} ${e}`):console.error(`${y}Error:${m} ${n.error}`),n.ok||process.exit(1)})}async function Fn(r,e){let t=e?.profileManager??O();if(!t.getActiveProfile())return{filenames:[],error:L};let i=C(r),s=`${i}_mtimes`;try{let o=await t.authedRealmFetch(s,{method:"GET",headers:{Accept:"application/vnd.api+json"}});if(!o.ok){let c=await o.text().catch(()=>"(no body)");return{filenames:[],error:`_mtimes returned HTTP ${o.status}: ${c.slice(0,300)}`}}let a=await o.json(),l=a?.data?.attributes?.mtimes??a,u=[];for(let c of Object.keys(l)){if(!c.startsWith(i))continue;let f=c.slice(i.length);!f||f.endsWith("/")||u.push(f)}return{filenames:u.sort()}}catch(o){return{filenames:[],error:o instanceof Error?o.message:String(o)}}}function ql(r){r.command("list").alias("ls").description("List all files in a realm").requiredOption("--realm <realm-url>","The realm URL to list files from").option("--json","Output raw JSON response").action(async e=>{let t;try{t=await Fn(e.realm)}catch(n){console.error(`${y}Error:${m} ${n instanceof Error?n.message:String(n)}`),process.exit(1)}if(e.json)M.output(JSON.stringify(t,null,2)),t.error&&process.exit(1);else if(t.error)console.error(`${y}Error:${m} ${t.error}`),process.exit(1);else{for(let n of t.filenames)console.log(`${E}${n}${m}`);console.log(`
|
|
90
90
|
${E}${t.filenames.length} file(s)${m}`)}})}var Qt=require("fs");var Vl=require("fs");async function tt(r,e,t,n){let i=n?.profileManager??O();if(!i.getActiveProfile())return{ok:!1,error:L};let o=new URL(e,C(r)).href;try{let a=await i.authedRealmFetch(o,{method:"POST",headers:{Accept:"application/vnd.card+source","Content-Type":"application/vnd.card+source"},body:t});if(!a.ok){let l=await a.text().catch(()=>"(no body)");return{ok:!1,error:`HTTP ${a.status}: ${l.slice(0,300)}`}}return{ok:!0}}catch(a){return{ok:!1,error:a instanceof Error?a.message:String(a)}}}function et(r){process.stderr.write(r+`
|
|
91
|
-
`)}async function
|
|
92
|
-
${E}${l.length} error(s), ${u.length} warning(s)${m}`),l.length>0&&process.exit(1)})}async function Un(r,e,t){let n=t?.profileManager??O();if(!n.getActiveProfile())return{ok:!1,error:L};let s=new URL(e,C(r)).href,o;try{o=await n.authedRealmFetch(s,{method:"GET",headers:{Accept:"application/vnd.card+source"}})}catch(l){return{ok:!1,error:l instanceof Error?l.message:String(l)}}if(!o.ok){let l=await o.text().catch(()=>"(no body)");return{ok:!1,status:o.status,error:`HTTP ${o.status}: ${l.slice(0,300)}`}}let a=await o.text();return{ok:!0,status:o.status,content:a}}function Wl(r){r.command("read").description("Read a file from a realm").argument("<path>","Realm-relative file path (e.g., hello-world.json, Cards/my-card.gts)").requiredOption("--realm <realm-url>","The realm URL to read from").option("--json","Output raw JSON response").action(async(e,t)=>{let n;try{n=await Un(t.realm,e)}catch(i){console.error(`${
|
|
93
|
-
`}catch{}return
|
|
91
|
+
`)}async function uy(){let r=[];for await(let e of process.stdin)r.push(e);return Buffer.concat(r).toString("utf-8")}function Gl(r){r.command("write").description("Write a file to a realm (reads content from STDIN or --file)").argument("<path>","Realm-relative file path (e.g., hello.gts, Cards/my-card.json)").requiredOption("--realm <realm-url>","The realm URL to write to").option("--file <filepath>","Read content from a local file instead of STDIN").option("--json","Output raw JSON response").action(async(e,t)=>{let n;if(t.file)try{n=(0,Vl.readFileSync)(t.file,"utf-8")}catch(s){et(`${y}Error:${m} Could not read file: ${s instanceof Error?s.message:String(s)}`),process.exit(1)}else process.stdin.isTTY&&et(`${E}Reading from STDIN. Type or paste content, then press Enter followed by Ctrl+D to finish.${m}`),n=await uy(),et(`${E}Received ${n.length} bytes. Writing to realm...${m}`);let i;try{i=await tt(t.realm,e,n)}catch(s){et(`${y}Error:${m} ${s instanceof Error?s.message:String(s)}`),process.exit(1)}t.json?M.output(JSON.stringify(i,null,2)):i.ok?console.log(`${_}Written:${m} ${e} ${E}\u2192${m} ${t.realm}`):et(`${y}Error:${m} ${i.error}`),i.ok||process.exit(1)})}async function fy(r,e,t,n){let i=n?.profileManager??O();if(!i.getActiveProfile())return{ok:!1,error:L};let o=`${C(r)}_lint`;try{let a=await i.authedRealmFetch(o,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/vnd.card+source","X-Filename":t,"X-HTTP-Method-Override":"QUERY"},body:e});if(!a.ok){let u=await a.text().catch(()=>"(no body)");return{ok:!1,error:`HTTP ${a.status}: ${u.slice(0,300)}`}}let l=await a.json();return{ok:!0,fixed:l.fixed,output:l.output,messages:l.messages}}catch(a){return{ok:!1,error:a instanceof Error?a.message:String(a)}}}function Hl(r){r.command("lint").description("Lint a file in a realm using the realm lint endpoint").argument("<path>","Realm-relative file path to lint (e.g., my-card.gts)").requiredOption("--realm <realm-url>","The realm URL to lint against").option("--file <local-filepath>","Read source from a local file instead of fetching from the realm").option("--json","Output raw JSON response").option("--fix","Write auto-fixed output back to the source").action(async(e,t)=>{let n=O();n.getActiveProfile()||(console.error(`${y}Error:${m} ${L}`),process.exit(1));let s;if(t.file)try{s=(0,Qt.readFileSync)(t.file,"utf-8")}catch(c){console.error(`${y}Error:${m} Could not read local file: ${c instanceof Error?c.message:String(c)}`),process.exit(1)}else{let c=new URL(e,C(t.realm)).href;try{let f=await n.authedRealmFetch(c,{method:"GET",headers:{Accept:"application/vnd.card+source"}});if(!f.ok){let d=await f.text().catch(()=>"(no body)");console.error(`${y}Error:${m} Could not read file from realm: HTTP ${f.status}: ${d.slice(0,300)}`),process.exit(1)}s=await f.text()}catch(f){console.error(`${y}Error:${m} ${f instanceof Error?f.message:String(f)}`),process.exit(1)}}let o;try{o=await fy(t.realm,s,e,{profileManager:n})}catch(c){console.error(`${y}Error:${m} ${c instanceof Error?c.message:String(c)}`),process.exit(1)}if(t.json){M.output(JSON.stringify(o,null,2)),o.ok||process.exit(1);return}if(o.ok||(console.error(`${y}Error:${m} ${o.error}`),process.exit(1)),t.fix&&o.fixed&&o.output)if(t.file)(0,Qt.writeFileSync)(t.file,o.output,"utf-8"),console.log(`${_}Fixed:${m} ${t.file}`);else{let c=await tt(t.realm,e,o.output,{profileManager:n});c.ok||(console.error(`${y}Error:${m} Could not write fixed file: ${c.error}`),process.exit(1)),console.log(`${_}Fixed:${m} ${e} ${E}\u2192${m} ${t.realm}`)}let a=o.messages??[],l=a.filter(c=>c.severity===2),u=a.filter(c=>c.severity===1);if(a.length===0){console.log(`${E}No lint issues found.${m}`);return}for(let c of a){let f=c.severity===2?y:P,d=c.severity===2?"error":"warning",p=c.ruleId?` (${c.ruleId})`:"";console.log(`${f}${d}${m} ${c.line}:${c.column} ${c.message}${E}${p}${m}`)}console.log(`
|
|
92
|
+
${E}${l.length} error(s), ${u.length} warning(s)${m}`),l.length>0&&process.exit(1)})}async function Un(r,e,t){let n=t?.profileManager??O();if(!n.getActiveProfile())return{ok:!1,error:L};let s=new URL(e,C(r)).href,o;try{o=await n.authedRealmFetch(s,{method:"GET",headers:{Accept:"application/vnd.card+source"}})}catch(l){return{ok:!1,error:l instanceof Error?l.message:String(l)}}if(!o.ok){let l=await o.text().catch(()=>"(no body)");return{ok:!1,status:o.status,error:`HTTP ${o.status}: ${l.slice(0,300)}`}}let a=await o.text();return{ok:!0,status:o.status,content:a}}function Wl(r){r.command("read").description("Read a file from a realm").argument("<path>","Realm-relative file path (e.g., hello-world.json, Cards/my-card.gts)").requiredOption("--realm <realm-url>","The realm URL to read from").option("--json","Output raw JSON response").action(async(e,t)=>{let n;try{n=await Un(t.realm,e)}catch(i){console.error(`${y}Error:${m} ${i instanceof Error?i.message:String(i)}`),process.exit(1)}t.json?M.output(JSON.stringify(n,null,2)):n.ok?M.output(n.content??""):(console.error(`${E}Status:${m} ${n.status??"(no status)"}`),console.error(`${y}Error:${m} ${n.error}`)),n.ok||process.exit(1)})}var jn="// touched for re-index";async function my(r,e,t){let n=t?.profileManager??O();if(!n.getActiveProfile())return{ok:!1,touched:[],skipped:[],error:L};let s;if(t?.all){if(e.length>0)return{ok:!1,touched:[],skipped:[],error:"Cannot pass file paths together with --all"};let l=await Fn(r,{profileManager:n});if(l.error)return{ok:!1,touched:[],skipped:[],error:l.error};s=l.filenames.filter(u=>(u.endsWith(".json")||u.endsWith(".gts"))&&!F(u))}else{if(e.length===0)return{ok:!1,touched:[],skipped:[],error:"No file paths provided. Pass paths or use --all."};s=e}let o=[],a=[];for(let l of s){if(!l.endsWith(".json")&&!l.endsWith(".gts")){a.push({path:l,reason:"unsupported extension"});continue}if(F(l)){a.push({path:l,reason:"protected file"});continue}let u=await Un(r,l,{profileManager:n});if(!u.ok||u.content==null){a.push({path:l,reason:u.error??"read failed"});continue}if(t?.dryRun){o.push(l);continue}let c=l.endsWith(".json")?dy(u.content):hy(u.content),f=await tt(r,l,c,{profileManager:n});if(!f.ok){a.push({path:l,reason:f.error??"write failed"});continue}o.push(l)}return{ok:a.length===0,touched:o,skipped:a}}function dy(r){try{let e=JSON.parse(r);if(e?.data)return e.data.meta={...e.data.meta??{},_touched:Date.now()},JSON.stringify(e,null,2)+`
|
|
93
|
+
`}catch{}return py(r)}function py(r){return r.endsWith(`
|
|
94
94
|
|
|
95
95
|
`)?r.slice(0,-1):r+`
|
|
96
|
-
`}function
|
|
96
|
+
`}function hy(r){let e=`
|
|
97
97
|
${jn}
|
|
98
98
|
`;return r.endsWith(e)?r.slice(0,-e.length)+`
|
|
99
99
|
`:r.endsWith(`
|
|
100
100
|
`)?r+jn+`
|
|
101
101
|
`:r+`
|
|
102
102
|
`+jn+`
|
|
103
|
-
`}function Bl(r){r.command("touch").description("Force realm re-indexing of one or more files by making a semantically-neutral edit. --all touches every .json/.gts in the realm without confirmation; use with care.").argument("[paths...]","Realm-relative file path(s) to touch (omit when using --all)").requiredOption("--realm <realm-url>","The realm URL to touch files in").option("--all","Touch every .json and .gts file in the realm").option("--dry-run","Print files that would be touched without writing").option("--json","Output raw JSON response").action(async(e,t)=>{let n;try{n=await
|
|
104
|
-
${E}${s} ${n.touched.length} file(s)${n.skipped.length>0?`, skipped ${n.skipped.length}`:""}${m}`)}n.ok||process.exit(1)})}function Yl(r){let e=r.command("file").description("Read, write, search, and manage files in a realm");jl(e),ql(e),Hl(e),Wl(e),Bl(e),Gl(e)}async function
|
|
103
|
+
`}function Bl(r){r.command("touch").description("Force realm re-indexing of one or more files by making a semantically-neutral edit. --all touches every .json/.gts in the realm without confirmation; use with care.").argument("[paths...]","Realm-relative file path(s) to touch (omit when using --all)").requiredOption("--realm <realm-url>","The realm URL to touch files in").option("--all","Touch every .json and .gts file in the realm").option("--dry-run","Print files that would be touched without writing").option("--json","Output raw JSON response").action(async(e,t)=>{let n;try{n=await my(t.realm,e,{all:t.all,dryRun:t.dryRun})}catch(i){console.error(`${y}Error:${m} ${i instanceof Error?i.message:String(i)}`),process.exit(1)}if(t.json)console.log(JSON.stringify(n,null,2));else if(n.error)console.error(`${y}Error:${m} ${n.error}`);else{let i=t.dryRun?`${E}[dry-run]${m} `:"";for(let o of n.touched)console.log(`${i}${_}touched${m} ${o}`);for(let{path:o,reason:a}of n.skipped)console.log(`${y}skipped${m} ${o} ${E}(${a})${m}`);let s=t.dryRun?"would touch":"touched";console.log(`
|
|
104
|
+
${E}${s} ${n.touched.length} file(s)${n.skipped.length>0?`, skipped ${n.skipped.length}`:""}${m}`)}n.ok||process.exit(1)})}function Yl(r){let e=r.command("file").description("Read, write, search, and manage files in a realm");jl(e),ql(e),Hl(e),Wl(e),Bl(e),Gl(e)}async function gy(r,e,t){let n=t?.profileManager??O(),i=n.getActiveProfile();if(!i)throw new Error("No active profile. Run `boxel profile add` to create one.");let o=`${i.profile.realmServerUrl.replace(/\/$/,"")}/_run-command`,a={data:{type:"run-command",attributes:{realmURL:e,command:r,commandInput:t?.input??null}}},l;try{l=await n.authedRealmServerFetch(o,{method:"POST",headers:{"Content-Type":"application/vnd.api+json",Accept:"application/vnd.api+json"},body:JSON.stringify(a)})}catch(f){return{status:"error",error:`run-command fetch failed: ${f instanceof Error?f.message:String(f)}`}}if(!l.ok){let f=await l.text().catch(()=>"(no body)");return{status:"error",error:`run-command HTTP ${l.status}: ${f}`}}let u;try{u=await l.json()}catch{return{status:"error",error:`run-command response was not valid JSON (HTTP ${l.status})`}}let c=u.data?.attributes;return{status:c?.status??"error",result:c?.cardResultString??null,error:c?.error??null}}function Xl(r){r.command("run-command").description("Execute a host command on the realm server via the prerenderer").argument("<command-specifier>","Command module path (e.g. @cardstack/boxel-host/commands/get-card-type-schema/default)").requiredOption("--realm <realm-url>","The realm URL context for the command").option("--input <json>","JSON string of command input").option("--json","Output raw JSON response").action(async(e,t)=>{let n;if(t.input)try{let s=JSON.parse(t.input);(typeof s!="object"||s===null||Array.isArray(s))&&(console.error(`${y}Error:${m} --input must be a JSON object, got ${Array.isArray(s)?"array":typeof s}`),process.exit(1)),n=s}catch{console.error(`${y}Error:${m} --input is not valid JSON: ${t.input}`),process.exit(1)}let i;try{i=await gy(e,t.realm,{input:n})}catch(s){console.error(`${y}Error:${m} ${s instanceof Error?s.message:String(s)}`),process.exit(1)}if(t.json)M.output(JSON.stringify(i,null,2));else{if(console.log(`${E}Status:${m} ${yy(i.status)}${i.status}${m}`),i.result){console.log(`${E}Result:${m}`);try{M.output(JSON.stringify(JSON.parse(i.result),null,2))}catch{M.output(i.result)}}i.error&&console.error(`${y}Error:${m} ${i.error}`)}(i.status==="error"||i.status==="unusable")&&process.exit(1)})}function yy(r){switch(r){case"ready":return _;case"error":return y;default:return T}}async function Ey(r,e,t){let n=t?.profileManager??O(),i=n.getActiveProfile();if(!i)return{ok:!1,error:L};let o=`${i.profile.realmServerUrl.replace(/\/$/,"")}/_federated-search`,a=(Array.isArray(r)?r:[r]).map(C);try{let l=await n.authedRealmServerFetch(o,{method:"QUERY",headers:{Accept:"application/vnd.card+json","Content-Type":"application/json"},body:JSON.stringify({realms:a,...e})});if(!l.ok){let c=await l.text();return{ok:!1,status:l.status,error:`HTTP ${l.status}: ${c.slice(0,300)}`}}let u=await l.json();return{ok:!0,status:l.status,data:u.data}}catch(l){return{ok:!1,status:0,error:l instanceof Error?l.message:String(l)}}}function zl(r){r.command("search").description("Federated search across realms using a JSON query").requiredOption("--realm <realm-url>","Realm URL to search (repeatable)",(e,t)=>(t.push(e),t),[]).requiredOption("--query <json>","JSON query object (as a string)").option("--json","Output raw JSON response").action(async e=>{e.realm.length===0&&(console.error(`${y}Error:${m} At least one --realm is required`),process.exit(1));let t;try{let i=JSON.parse(e.query);(typeof i!="object"||i===null||Array.isArray(i))&&(console.error(`${y}Error:${m} --query must be a JSON object, got ${Array.isArray(i)?"array":typeof i}`),process.exit(1)),t=i}catch(i){console.error(`${y}Error:${m} Invalid JSON in --query: ${i instanceof Error?i.message:String(i)}`),process.exit(1);return}let n;try{n=await Ey(e.realm,t)}catch(i){console.error(`${y}Error:${m} ${i instanceof Error?i.message:String(i)}`),process.exit(1);return}e.json?M.output(JSON.stringify(n,null,2)):n.ok?M.output(JSON.stringify(n.data??[],null,2)):(console.error(`${E}Status:${m} ${n.status??"(no status)"}`),console.error(`${y}Error:${m} ${n.error}`)),n.ok||process.exit(1)})}function Kl(r){let e=new Jl.Command;return e.name("boxel").description("CLI tools for Boxel workspace management").version(r).option("-q, --quiet","Suppress informational progress logs (info/log/debug). Errors and warnings, plus command result payloads (JSON, file contents), are still emitted. Use this when invoking the CLI from automation (e.g. the software factory test harness) to keep stdout focused on the result.").hook("preAction",t=>{(t.optsWithGlobals?.()??t.opts()).quiet&&ht(!0)}),e.command("profile").description("Manage saved profiles for different users/environments").argument("[subcommand]","list | add | switch | remove | migrate").argument("[arg]","Profile ID (for switch/remove)").option("-u, --user <matrixId>","Matrix user ID (e.g., @user:boxel.ai)").option("-p, --password <password>","Password (for add command)").option("-n, --name <displayName>","Display name (for add command)").option("-m, --matrix-url <url>","Matrix server URL (for add command with non-standard domains)").option("-r, --realm-server-url <url>","Realm server URL (for add command with non-standard domains)").addHelpText("after",`
|
|
105
105
|
Environment variables (for 'add'):
|
|
106
106
|
BOXEL_PASSWORD Password; preferred over -p to avoid shell history.
|
|
107
107
|
BOXEL_ENVIRONMENT An env-mode slug (e.g. a branch name), interpreted
|
|
108
108
|
like scripts/env-slug.sh: URLs are derived as
|
|
109
109
|
http://matrix.<slug>.localhost and
|
|
110
110
|
http://realm-server.<slug>.localhost/. Overridden
|
|
111
|
-
by --matrix-url / --realm-server-url if provided.`).action(async(
|
|
111
|
+
by --matrix-url / --realm-server-url if provided.`).action(async(t,n,i)=>{i?.password&&console.warn('Warning: Supplying a password via -p/--password may expose it in shell history and process listings. For non-interactive usage, prefer the BOXEL_PASSWORD environment variable or use "boxel profile add" interactively.'),await yi(t,n,i)}),Yl(e),Ul(e),Xl(e),zl(e),Ei(e),e}var wy=JSON.parse((0,Ql.readFileSync)((0,Zl.resolve)(__dirname,"../package.json"),"utf-8"));process.argv.includes("--quiet")&&ht(!0);Kl(wy.version).parse();
|
|
112
112
|
/*! Bundled license information:
|
|
113
113
|
|
|
114
114
|
safe-buffer/index.js:
|