@cardstack/boxel-cli 0.2.0-unstable.327 → 0.2.0-unstable.425
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/dist/index.js +73 -73
- package/package.json +1 -1
- package/src/commands/realm/index.ts +4 -0
- package/src/commands/realm/publish.ts +291 -0
- package/src/commands/realm/unpublish.ts +150 -0
package/dist/index.js
CHANGED
|
@@ -1,130 +1,130 @@
|
|
|
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 Au(r){r=r||{};let e=Di(r);r.path=e;let t=G.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=Ni(r).split(","),i=n.length,s;for(let o=0;o<i;o++)try{let a=n[o].trim(),l=Mu(t,a);s=G.decrypt(l.ciphertext,l.key);break}catch(a){if(o+1>=i)throw a}return G.parse(s)}function Lu(r){console.log(`[dotenv@${Cr}][WARN] ${r}`)}function ze(r){console.log(`[dotenv@${Cr}][DEBUG] ${r}`)}function Ii(r){console.log(`[dotenv@${Cr}] ${r}`)}function Ni(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 Mu(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 Di(r){let e=null;if(r&&r.path&&r.path.length>0)if(Array.isArray(r.path))for(let t of r.path)_r.existsSync(t)&&(e=t.endsWith(".vault")?t:`${t}.vault`);else e=r.path.endsWith(".vault")?r.path:`${r.path}.vault`;else e=Rt.resolve(process.cwd(),".env.vault");return _r.existsSync(e)?e:null}function Mi(r){return r[0]==="~"?Rt.join(_u.homedir(),r.slice(1)):r}function Iu(r){let e=!!(r&&r.debug),t=r&&"quiet"in r?r.quiet:!0;(e||!t)&&Ii("Loading env from encrypted .env.vault");let n=G._parseVault(r),i=process.env;return r&&r.processEnv!=null&&(i=r.processEnv),G.populate(i,n,r),{parsed:n}}function Nu(r){let e=Rt.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&&ze("No encoding is specified. UTF-8 is used by default");let s=[e];if(r&&r.path)if(!Array.isArray(r.path))s=[Mi(r.path)];else{s=[];for(let c of r.path)s.push(Mi(c))}let o,a={};for(let c of s)try{let u=G.parse(_r.readFileSync(c,{encoding:t}));G.populate(a,u,r)}catch(u){n&&ze(`Failed to load ${c} ${u.message}`),o=u}let l=process.env;if(r&&r.processEnv!=null&&(l=r.processEnv),G.populate(l,a,r),n||!i){let c=Object.keys(a).length,u=[];for(let f of s)try{let d=Rt.relative(process.cwd(),f);u.push(d)}catch(d){n&&ze(`Failed to load ${f} ${d.message}`),o=d}Ii(`injecting env (${c}) from ${u.join(",")}`)}return o?{parsed:a,error:o}:{parsed:a}}function Du(r){if(Ni(r).length===0)return G.configDotenv(r);let e=Di(r);return e?G._configVault(r):(Lu(`You set DOTENV_KEY but you are missing a .env.vault file at ${e}. Did you forget to build it?`),G.configDotenv(r))}function Fu(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=Cu.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",c=o.message==="Unsupported state or unable to authenticate data";if(a||l){let u=new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");throw u.code="INVALID_DOTENV_KEY",u}else if(c){let u=new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");throw u.code="DECRYPTION_FAILED",u}else throw o}}function Uu(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&&ze(i===!0?`"${s}" is already defined and WAS overwritten`:`"${s}" is already defined and was NOT overwritten`)):r[s]=e[s]}var G={configDotenv:Nu,_configVault:Iu,_parseVault:Au,config:Du,decrypt:Fu,parse:Tu,populate:Uu};Ee.exports.configDotenv=G.configDotenv;Ee.exports._configVault=G._configVault;Ee.exports._parseVault=G._parseVault;Ee.exports.config=G.config;Ee.exports.decrypt=G.decrypt;Ee.exports.parse=G.parse;Ee.exports.populate=G.populate;Ee.exports=G});var ji=w((VE,Ui)=>{var Oe={};process.env.DOTENV_CONFIG_ENCODING!=null&&(Oe.encoding=process.env.DOTENV_CONFIG_ENCODING);process.env.DOTENV_CONFIG_PATH!=null&&(Oe.path=process.env.DOTENV_CONFIG_PATH);process.env.DOTENV_CONFIG_QUIET!=null&&(Oe.quiet=process.env.DOTENV_CONFIG_QUIET);process.env.DOTENV_CONFIG_DEBUG!=null&&(Oe.debug=process.env.DOTENV_CONFIG_DEBUG);process.env.DOTENV_CONFIG_OVERRIDE!=null&&(Oe.override=process.env.DOTENV_CONFIG_OVERRIDE);process.env.DOTENV_CONFIG_DOTENV_KEY!=null&&(Oe.DOTENV_KEY=process.env.DOTENV_CONFIG_DOTENV_KEY);Ui.exports=Oe});var Gi=w((BE,qi)=>{var ju=/^dotenv_config_(encoding|path|quiet|debug|override|DOTENV_KEY)=(.+)$/;qi.exports=function(e){let t=e.reduce(function(n,i){let s=i.match(ju);return s&&(n[s[1]]=s[2]),n},{});return"quiet"in t||(t.quiet="true"),t}});var Ke=w(Pr=>{var $t=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}},Or=class extends $t{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};Pr.CommanderError=$t;Pr.InvalidArgumentError=Or});var bt=w(Ar=>{var{InvalidArgumentError:qu}=Ke(),Tr=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 qu(`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 Gu(r){let e=r.name()+(r.variadic===!0?"...":"");return r.required?"<"+e+">":"["+e+"]"}Ar.Argument=Tr;Ar.humanReadableArgName=Gu});var Ir=w(Mr=>{var{humanReadableArgName:Hu}=bt(),Lr=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=>Hu(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 c=t.visibleOptions(e).map(f=>s(t.styleOptionTerm(t.optionTerm(f)),t.styleOptionDescription(t.optionDescription(f))));if(c.length>0&&(o=o.concat([t.styleTitle("Options:"),...c,""])),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 u=t.visibleCommands(e).map(f=>s(t.styleSubcommandTerm(t.subcommandTerm(f)),t.styleSubcommandDescription(t.subcommandDescription(f))));return u.length>0&&(o=o.concat([t.styleTitle("Commands:"),...u,""])),o.join(`
|
|
5
|
-
`)}displayWidth(e){return
|
|
2
|
+
"use strict";var ku=Object.create;var Li=Object.defineProperty;var _u=Object.getOwnPropertyDescriptor;var Cu=Object.getOwnPropertyNames;var Ou=Object.getPrototypeOf,Pu=Object.prototype.hasOwnProperty;var w=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports);var Tu=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Cu(e))!Pu.call(r,i)&&i!==t&&Li(r,i,{get:()=>e[i],enumerable:!(n=_u(e,i))||n.enumerable});return r};var T=(r,e,t)=>(t=r!=null?ku(Ou(r)):{},Tu(e||!r||!r.__esModule?Li(t,"default",{value:r,enumerable:!0}):t,r));var Mi=w((tb,Au)=>{Au.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 Ui=w((rb,Ee)=>{var _r=require("fs"),bt=require("path"),Lu=require("os"),Mu=require("crypto"),Iu=Mi(),Cr=Iu.version,Nu=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;function Fu(r){let e={},t=r.toString();t=t.replace(/\r\n?/mg,`
|
|
3
|
+
`);let n;for(;(n=Nu.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 Du(r){r=r||{};let e=Di(r);r.path=e;let t=G.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=Fi(r).split(","),i=n.length,s;for(let o=0;o<i;o++)try{let a=n[o].trim(),l=ju(t,a);s=G.decrypt(l.ciphertext,l.key);break}catch(a){if(o+1>=i)throw a}return G.parse(s)}function Uu(r){console.log(`[dotenv@${Cr}][WARN] ${r}`)}function Xe(r){console.log(`[dotenv@${Cr}][DEBUG] ${r}`)}function Ni(r){console.log(`[dotenv@${Cr}] ${r}`)}function Fi(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 ju(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 Di(r){let e=null;if(r&&r.path&&r.path.length>0)if(Array.isArray(r.path))for(let t of r.path)_r.existsSync(t)&&(e=t.endsWith(".vault")?t:`${t}.vault`);else e=r.path.endsWith(".vault")?r.path:`${r.path}.vault`;else e=bt.resolve(process.cwd(),".env.vault");return _r.existsSync(e)?e:null}function Ii(r){return r[0]==="~"?bt.join(Lu.homedir(),r.slice(1)):r}function qu(r){let e=!!(r&&r.debug),t=r&&"quiet"in r?r.quiet:!0;(e||!t)&&Ni("Loading env from encrypted .env.vault");let n=G._parseVault(r),i=process.env;return r&&r.processEnv!=null&&(i=r.processEnv),G.populate(i,n,r),{parsed:n}}function Gu(r){let e=bt.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&&Xe("No encoding is specified. UTF-8 is used by default");let s=[e];if(r&&r.path)if(!Array.isArray(r.path))s=[Ii(r.path)];else{s=[];for(let c of r.path)s.push(Ii(c))}let o,a={};for(let c of s)try{let u=G.parse(_r.readFileSync(c,{encoding:t}));G.populate(a,u,r)}catch(u){n&&Xe(`Failed to load ${c} ${u.message}`),o=u}let l=process.env;if(r&&r.processEnv!=null&&(l=r.processEnv),G.populate(l,a,r),n||!i){let c=Object.keys(a).length,u=[];for(let f of s)try{let d=bt.relative(process.cwd(),f);u.push(d)}catch(d){n&&Xe(`Failed to load ${f} ${d.message}`),o=d}Ni(`injecting env (${c}) from ${u.join(",")}`)}return o?{parsed:a,error:o}:{parsed:a}}function Hu(r){if(Fi(r).length===0)return G.configDotenv(r);let e=Di(r);return e?G._configVault(r):(Uu(`You set DOTENV_KEY but you are missing a .env.vault file at ${e}. Did you forget to build it?`),G.configDotenv(r))}function Wu(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=Mu.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",c=o.message==="Unsupported state or unable to authenticate data";if(a||l){let u=new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");throw u.code="INVALID_DOTENV_KEY",u}else if(c){let u=new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");throw u.code="DECRYPTION_FAILED",u}else throw o}}function Vu(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&&Xe(i===!0?`"${s}" is already defined and WAS overwritten`:`"${s}" is already defined and was NOT overwritten`)):r[s]=e[s]}var G={configDotenv:Gu,_configVault:qu,_parseVault:Du,config:Hu,decrypt:Wu,parse:Fu,populate:Vu};Ee.exports.configDotenv=G.configDotenv;Ee.exports._configVault=G._configVault;Ee.exports._parseVault=G._parseVault;Ee.exports.config=G.config;Ee.exports.decrypt=G.decrypt;Ee.exports.parse=G.parse;Ee.exports.populate=G.populate;Ee.exports=G});var qi=w((nb,ji)=>{var Oe={};process.env.DOTENV_CONFIG_ENCODING!=null&&(Oe.encoding=process.env.DOTENV_CONFIG_ENCODING);process.env.DOTENV_CONFIG_PATH!=null&&(Oe.path=process.env.DOTENV_CONFIG_PATH);process.env.DOTENV_CONFIG_QUIET!=null&&(Oe.quiet=process.env.DOTENV_CONFIG_QUIET);process.env.DOTENV_CONFIG_DEBUG!=null&&(Oe.debug=process.env.DOTENV_CONFIG_DEBUG);process.env.DOTENV_CONFIG_OVERRIDE!=null&&(Oe.override=process.env.DOTENV_CONFIG_OVERRIDE);process.env.DOTENV_CONFIG_DOTENV_KEY!=null&&(Oe.DOTENV_KEY=process.env.DOTENV_CONFIG_DOTENV_KEY);ji.exports=Oe});var Hi=w((ib,Gi)=>{var Bu=/^dotenv_config_(encoding|path|quiet|debug|override|DOTENV_KEY)=(.+)$/;Gi.exports=function(e){let t=e.reduce(function(n,i){let s=i.match(Bu);return s&&(n[s[1]]=s[2]),n},{});return"quiet"in t||(t.quiet="true"),t}});var Ke=w(Pr=>{var Rt=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}},Or=class extends Rt{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};Pr.CommanderError=Rt;Pr.InvalidArgumentError=Or});var $t=w(Ar=>{var{InvalidArgumentError:Yu}=Ke(),Tr=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 Yu(`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 Ju(r){let e=r.name()+(r.variadic===!0?"...":"");return r.required?"<"+e+">":"["+e+"]"}Ar.Argument=Tr;Ar.humanReadableArgName=Ju});var Ir=w(Mr=>{var{humanReadableArgName:zu}=$t(),Lr=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=>zu(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 c=t.visibleOptions(e).map(f=>s(t.styleOptionTerm(t.optionTerm(f)),t.styleOptionDescription(t.optionDescription(f))));if(c.length>0&&(o=o.concat([t.styleTitle("Options:"),...c,""])),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 u=t.visibleCommands(e).map(f=>s(t.styleSubcommandTerm(t.subcommandTerm(f)),t.styleSubcommandDescription(t.subcommandDescription(f))));return u.length>0&&(o=o.concat([t.styleTitle("Commands:"),...u,""])),o.join(`
|
|
5
|
+
`)}displayWidth(e){return Wi(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,u=(this.helpWidth??80)-t-l-2,f;return u<this.minWidthToWrap||i.preformatted(n)?f=n:f=i.boxWrap(n,u).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()],c=this.displayWidth(l[0]);a.forEach(u=>{let f=this.displayWidth(u);if(c+f<=t){l.push(u),c+=f;return}s.push(l.join(""));let d=u.trimStart();l=[d],c=this.displayWidth(d)}),s.push(l.join(""))}),s.join(`
|
|
8
|
-
`)}};function
|
|
8
|
+
`)}};function Wi(r){let e=/\x1b\[\d*(;\d*)*m/g;return r.replace(e,"")}Mr.Help=Lr;Mr.stripColor=Wi});var Ur=w(Dr=>{var{InvalidArgumentError:Xu}=Ke(),Nr=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=Ku(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 Xu(`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?Vi(this.name().replace(/^no-/,"")):Vi(this.name())}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},Fr=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 Vi(r){return r.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function Ku(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}}
|
|
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}}Dr.Option=Nr;Dr.DualOptions=Fr});var Yi=w(Bi=>{function Qu(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 Zu(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=Qu(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]}?)`:""}
|
|
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
|
|
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 qr(e,t,n)),
|
|
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
|
|
16
|
+
(Did you mean ${n[0]}?)`:""}Bi.suggestSimilar=Zu});var Ki=w(Wr=>{var ef=require("node:events").EventEmitter,jr=require("node:child_process"),be=require("node:path"),St=require("node:fs"),L=require("node:process"),{Argument:tf,humanReadableArgName:rf}=$t(),{CommanderError:qr}=Ke(),{Help:nf,stripColor:sf}=Ir(),{Option:Ji,DualOptions:of}=Ur(),{suggestSimilar:zi}=Yi(),Gr=class r extends ef{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=>L.stdout.write(t),writeErr:t=>L.stderr.write(t),outputError:(t,n)=>n(t),getOutHelpWidth:()=>L.stdout.isTTY?L.stdout.columns:void 0,getErrHelpWidth:()=>L.stderr.isTTY?L.stderr.columns:void 0,getOutHasColors:()=>Hr()??(L.stdout.isTTY&&L.stdout.hasColors?.()),getErrHasColors:()=>Hr()??(L.stderr.isTTY&&L.stderr.hasColors?.()),stripColor:t=>sf(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 nf,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 tf(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
|
+
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 qr(e,t,n)),L.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 Ji(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
|
+
- 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 Ji)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,c)=>{let u=a.exec(l);return u?u[0]:c},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){L.versions?.electron&&(t.from="electron");let i=L.execArgv??[];(i.includes("-e")||i.includes("--eval")||i.includes("-p")||i.includes("--print"))&&(t.from="eval")}e===void 0&&(e=L.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":L.defaultApp?(this._scriptPath=e[1],n=e.slice(2)):n=e.slice(1);break;case"user":n=e.slice(0);break;case"eval":n=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${t.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",n}parse(e,t){this._prepareForParse();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(St.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(u,f){let d=
|
|
23
|
+
- ${i}`;throw new Error(s)}_executeSubCommand(e,t){t=t.slice();let n=!1,i=[".js",".ts",".tsx",".mjs",".cjs"];function s(u,f){let d=be.resolve(u,f);if(St.existsSync(d))return d;if(i.includes(be.extname(f)))return;let p=i.find(y=>St.existsSync(`${d}${y}`));if(p)return`${d}${p}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let u;try{u=St.realpathSync(this._scriptPath)}catch{u=this._scriptPath}a=be.resolve(be.dirname(u),a)}if(a){let u=s(a,o);if(!u&&!e._executableFile&&this._scriptPath){let f=be.basename(this._scriptPath,be.extname(this._scriptPath));f!==this._name&&(u=s(a,`${f}-${e._name}`))}o=u||o}n=i.includes(be.extname(o));let l;L.platform!=="win32"?n?(t.unshift(o),t=Xi(L.execArgv).concat(t),l=jr.spawn(L.argv[0],t,{stdio:"inherit"})):l=jr.spawn(o,t,{stdio:"inherit"}):(this._checkForMissingExecutable(o,a,e._name),t.unshift(o),t=Xi(L.execArgv).concat(t),l=jr.spawn(L.execPath,t,{stdio:"inherit"})),l.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(f=>{L.on(f,()=>{l.killed===!1&&l.exitCode===null&&l.kill(f)})});let c=this._exitCallback;l.on("close",u=>{u=u??1,c?c(new qr(u,"commander.executeSubCommandAsync","(close)")):L.exit(u)}),l.on("error",u=>{if(u.code==="ENOENT")this._checkForMissingExecutable(o,a,e._name);else if(u.code==="EACCES")throw new Error(`'${o}' not executable`);if(!c)L.exit(1);else{let f=new qr(1,"commander.executeSubCommandAsync","(error)");f.nestedError=u,c(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 c=this._findOption(l);if(c){if(c.required){let u=s.shift();u===void 0&&this.optionMissingArgument(c),this.emit(`option:${c.name()}`,u)}else if(c.optional){let u=null;s.length>0&&!o(s[0])&&(u=s.shift()),this.emit(`option:${c.name()}`,u)}else this.emit(`option:${c.name()}`);a=c.variadic?c:null;continue}}if(l.length>2&&l[0]==="-"&&l[1]!=="-"){let c=this._findOption(`-${l[1]}`);if(c){c.required||c.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${c.name()}`,l.slice(2)):(this.emit(`option:${c.name()}`),s.unshift(`-${l.slice(2)}`));continue}}if(/^--[^=]+=/.test(l)){let c=l.indexOf("="),u=this._findOption(l.slice(0,c));if(u&&(u.required||u.optional)){this.emit(`option:${u.name()}`,l.slice(c+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
|
|
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 L.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()}`,L.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new of(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),c=this.options.find(f=>f.negate&&a===f.attributeName()),u=this.options.find(f=>!f.negate&&a===f.attributeName());return c&&(c.presetArg===void 0&&l===!1||c.presetArg!==void 0&&l===c.presetArg)?c:u||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=zi(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=zi(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=>rf(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=be.basename(e,be.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(L.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 Xi(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(
|
|
29
|
+
`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(i=>t.is(i))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function Xi(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(L.env.NO_COLOR||L.env.FORCE_COLOR==="0"||L.env.FORCE_COLOR==="false")return!1;if(L.env.FORCE_COLOR||L.env.CLICOLOR_FORCE!==void 0)return!0}Wr.Command=Gr;Wr.useColor=Hr});var vt=w(ne=>{var{Argument:Qi}=$t(),{Command:Vr}=Ki(),{CommanderError:af,InvalidArgumentError:Zi}=Ke(),{Help:lf}=Ir(),{Option:es}=Ur();ne.program=new Vr;ne.createCommand=r=>new Vr(r);ne.createOption=(r,e)=>new es(r,e);ne.createArgument=(r,e)=>new Qi(r,e);ne.Command=Vr;ne.Option=es;ne.Argument=Qi;ne.Help=lf;ne.CommanderError=af;ne.InvalidArgumentError=Zi;ne.InvalidOptionArgumentError=Zi});var Fe=w((Br,rs)=>{var xt=require("buffer"),de=xt.Buffer;function ts(r,e){for(var t in r)e[t]=r[t]}de.from&&de.alloc&&de.allocUnsafe&&de.allocUnsafeSlow?rs.exports=xt:(ts(xt,Br),Br.Buffer=Pe);function Pe(r,e,t){return de(r,e,t)}Pe.prototype=Object.create(de.prototype);ts(de,Pe);Pe.from=function(r,e,t){if(typeof r=="number")throw new TypeError("Argument must not be a number");return de(r,e,t)};Pe.alloc=function(r,e,t){if(typeof r!="number")throw new TypeError("Argument must be a number");var n=de(r);return e!==void 0?typeof t=="string"?n.fill(e,t):n.fill(e):n.fill(0),n};Pe.allocUnsafe=function(r){if(typeof r!="number")throw new TypeError("Argument must be a number");return de(r)};Pe.allocUnsafeSlow=function(r){if(typeof r!="number")throw new TypeError("Argument must be a number");return xt.SlowBuffer(r)}});var Yr=w((mb,ns)=>{var kt=Fe().Buffer,cf=require("stream"),uf=require("util");function _t(r){if(this.buffer=null,this.writable=!0,this.readable=!0,!r)return this.buffer=kt.alloc(0),this;if(typeof r.pipe=="function")return this.buffer=kt.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+")")}uf.inherits(_t,cf);_t.prototype.write=function(e){this.buffer=kt.concat([this.buffer,kt.from(e)]),this.emit("data",e)};_t.prototype.end=function(e){e&&this.write(e),this.emit("end",e),this.emit("close"),this.writable=!1,this.readable=!1};ns.exports=_t});var ss=w((db,is)=>{"use strict";function Jr(r){var e=(r/8|0)+(r%8===0?0:1);return e}var ff={ES256:Jr(256),ES384:Jr(384),ES512:Jr(521)};function mf(r){var e=ff[r];if(e)return e;throw new Error('Unknown algorithm "'+r+'"')}is.exports=mf});var ms=w((pb,fs)=>{"use strict";var Ct=Fe().Buffer,as=ss(),Ot=128,ls=0,df=32,pf=16,hf=2,cs=pf|df|ls<<6,Pt=hf|ls<<6;function gf(r){return r.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function us(r){if(Ct.isBuffer(r))return r;if(typeof r=="string")return Ct.from(r,"base64");throw new TypeError("ECDSA signature must be a Base64 string or a Buffer")}function yf(r,e){r=us(r);var t=as(e),n=t+1,i=r.length,s=0;if(r[s++]!==cs)throw new Error('Could not find expected "seq"');var o=r[s++];if(o===(Ot|1)&&(o=r[s++]),i-s<o)throw new Error('"seq" specified length of "'+o+'", only "'+(i-s)+'" remaining');if(r[s++]!==Pt)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++]!==Pt)throw new Error('Could not find expected "int" for "s"');var c=r[s++];if(i-s!==c)throw new Error('"s" specified length of "'+c+'", expected "'+(i-s)+'"');if(n<c)throw new Error('"s" specified length of "'+c+'", max of "'+n+'" is acceptable');var u=s;if(s+=c,s!==i)throw new Error('Expected to consume entire buffer, but "'+(i-s)+'" bytes remain');var f=t-a,d=t-c,p=Ct.allocUnsafe(f+a+d+c);for(s=0;s<f;++s)p[s]=0;r.copy(p,s,l+Math.max(-f,0),l+a),s=t;for(var y=s;s<y+d;++s)p[s]=0;return r.copy(p,s,u+Math.max(-d,0),u+c),p=p.toString("base64"),p=gf(p),p}function os(r,e,t){for(var n=0;e+n<t&&r[e+n]===0;)++n;var i=r[e+n]>=Ot;return i&&--n,n}function wf(r,e){r=us(r);var t=as(e),n=r.length;if(n!==t*2)throw new TypeError('"'+e+'" signatures must be "'+t*2+'" bytes, saw "'+n+'"');var i=os(r,0,t),s=os(r,t,r.length),o=t-i,a=t-s,l=2+o+1+1+a,c=l<Ot,u=Ct.allocUnsafe((c?2:3)+l),f=0;return u[f++]=cs,c?u[f++]=l:(u[f++]=Ot|1,u[f++]=l&255),u[f++]=Pt,u[f++]=o,i<0?(u[f++]=0,f+=r.copy(u,f,0,t)):f+=r.copy(u,f,i,t),u[f++]=Pt,u[f++]=a,s<0?(u[f++]=0,r.copy(u,f,t)):r.copy(u,f,t+s),u}fs.exports={derToJose:yf,joseToDer:wf}});var ps=w((hb,ds)=>{"use strict";var Qe=require("buffer").Buffer,zr=require("buffer").SlowBuffer;ds.exports=Tt;function Tt(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}Tt.install=function(){Qe.prototype.equal=zr.prototype.equal=function(e){return Tt(this,e)}};var Ef=Qe.prototype.equal,bf=zr.prototype.equal;Tt.restore=function(){Qe.prototype.equal=Ef,zr.prototype.equal=bf}});var Zr=w((gb,Ss)=>{var Ue=Fe().Buffer,ie=require("crypto"),gs=ms(),hs=require("util"),Rf=`"%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".`,Ze="secret must be a string or buffer",Fe="key must be a string or a buffer",gf="key must be a string, a buffer or an object",Kr=typeof ie.createPublicKey=="function";Kr&&(Fe+=" or a KeyObject",Ze+="or a KeyObject");function gs(r){if(!Ue.isBuffer(r)&&typeof r!="string"&&(!Kr||typeof r!="object"||typeof r.type!="string"||typeof r.asymmetricKeyType!="string"||typeof r.export!="function"))throw ce(Fe)}function ys(r){if(!Ue.isBuffer(r)&&typeof r!="string"&&typeof r!="object")throw ce(gf)}function yf(r){if(!Ue.isBuffer(r)){if(typeof r=="string")return r;if(!Kr||typeof r!="object"||r.type!=="secret"||typeof r.export!="function")throw ce(Ze)}}function Qr(r){return r.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function ws(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 ce(r){var e=[].slice.call(arguments,1),t=ps.format.bind(ps,r).apply(null,e);return new TypeError(t)}function wf(r){return Ue.isBuffer(r)||typeof r=="string"}function et(r){return wf(r)||(r=JSON.stringify(r)),r}function Es(r){return function(t,n){yf(n),t=et(t);var i=ie.createHmac("sha"+r,n),s=(i.update(t),i.digest("base64"));return Qr(s)}}var zr,Ef="timingSafeEqual"in ie?function(e,t){return e.byteLength!==t.byteLength?!1:ie.timingSafeEqual(e,t)}:function(e,t){return zr||(zr=ds()),zr(e,t)};function Rf(r){return function(t,n,i){var s=Es(r)(t,i);return Ef(Ue.from(n),Ue.from(s))}}function Rs(r){return function(t,n){ys(n),t=et(t);var i=ie.createSign("RSA-SHA"+r),s=(i.update(t),i.sign(n,"base64"));return Qr(s)}}function $s(r){return function(t,n,i){gs(i),t=et(t),n=ws(n);var s=ie.createVerify("RSA-SHA"+r);return s.update(t),s.verify(i,n,"base64")}}function $f(r){return function(t,n){ys(n),t=et(t);var i=ie.createSign("RSA-SHA"+r),s=(i.update(t),i.sign({key:n,padding:ie.constants.RSA_PKCS1_PSS_PADDING,saltLength:ie.constants.RSA_PSS_SALTLEN_DIGEST},"base64"));return Qr(s)}}function bf(r){return function(t,n,i){gs(i),t=et(t),n=ws(n);var s=ie.createVerify("RSA-SHA"+r);return s.update(t),s.verify({key:i,padding:ie.constants.RSA_PKCS1_PSS_PADDING,saltLength:ie.constants.RSA_PSS_SALTLEN_DIGEST},n,"base64")}}function Sf(r){var e=Rs(r);return function(){var n=e.apply(null,arguments);return n=hs.derToJose(n,"ES"+r),n}}function vf(r){var e=$s(r);return function(n,i,s){i=hs.joseToDer(i,"ES"+r).toString("base64");var o=e(n,i,s);return o}}function xf(){return function(){return""}}function kf(){return function(e,t){return t===""}}bs.exports=function(e){var t={hs:Es,rs:Rs,ps:$f,es:Sf,none:xf},n={hs:Rf,rs:$s,ps:bf,es:vf,none:kf},i=e.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);if(!i)throw ce(hf,e);var s=(i[1]||i[3]).toLowerCase(),o=i[2];return{sign:t[s](o),verify:n[s](o)}}});var en=w((sR,Ss)=>{var _f=require("buffer").Buffer;Ss.exports=function(e){return typeof e=="string"?e:typeof e=="number"||_f.isBuffer(e)?e.toString():JSON.stringify(e)}});var Os=w((oR,Cs)=>{var Cf=De().Buffer,vs=Yr(),Of=Zr(),Pf=require("stream"),xs=en(),tn=require("util");function ks(r,e){return Cf.from(r,e).toString("base64").replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function Tf(r,e,t){t=t||"utf8";var n=ks(xs(r),"binary"),i=ks(xs(e),t);return tn.format("%s.%s",n,i)}function _s(r){var e=r.header,t=r.payload,n=r.secret||r.privateKey,i=r.encoding,s=Of(e.alg),o=Tf(e,t,i),a=s.sign(o,n);return tn.format("%s.%s",o,a)}function At(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 vs(e);this.readable=!0,this.header=r.header,this.encoding=r.encoding,this.secret=this.privateKey=this.key=t,this.payload=new vs(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))}tn.inherits(At,Pf);At.prototype.sign=function(){try{var e=_s({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")}};At.sign=_s;Cs.exports=At});var Us=w((aR,Fs)=>{var Ts=De().Buffer,Ps=Yr(),Af=Zr(),Lf=require("stream"),As=en(),Mf=require("util"),If=/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;function Nf(r){return Object.prototype.toString.call(r)==="[object Object]"}function Df(r){if(Nf(r))return r;try{return JSON.parse(r)}catch{return}}function Ls(r){var e=r.split(".",1)[0];return Df(Ts.from(e,"base64").toString("binary"))}function Ff(r){return r.split(".",2).join(".")}function Ms(r){return r.split(".")[2]}function Uf(r,e){e=e||"utf8";var t=r.split(".")[1];return Ts.from(t,"base64").toString(e)}function Is(r){return If.test(r)&&!!Ls(r)}function Ns(r,e,t){if(!e){var n=new Error("Missing algorithm parameter for jws.verify");throw n.code="MISSING_ALGORITHM",n}r=As(r);var i=Ms(r),s=Ff(r),o=Af(e);return o.verify(s,i,t)}function Ds(r,e){if(e=e||{},r=As(r),!Is(r))return null;var t=Ls(r);if(!t)return null;var n=Uf(r);return(t.typ==="JWT"||e.json)&&(n=JSON.parse(n,e.encoding)),{header:t,payload:n,signature:Ms(r)}}function je(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 Ps(e);this.readable=!0,this.algorithm=r.algorithm,this.encoding=r.encoding,this.secret=this.publicKey=this.key=t,this.signature=new Ps(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(je,Lf);je.prototype.verify=function(){try{var e=Ns(this.signature.buffer,this.algorithm,this.key.buffer),t=Ds(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")}};je.decode=Ds;je.isValid=Is;je.verify=Ns;Fs.exports=je});var Mt=w(be=>{var js=Os(),Lt=Us(),jf=["HS256","HS384","HS512","RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512"];be.ALGORITHMS=jf;be.sign=js.sign;be.verify=Lt.verify;be.decode=Lt.decode;be.isValid=Lt.isValid;be.createSign=function(e){return new js(e)};be.createVerify=function(e){return new Lt(e)}});var rn=w((cR,qs)=>{var qf=Mt();qs.exports=function(r,e){e=e||{};var t=qf.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 tt=w((uR,Gs)=>{var It=function(r,e){Error.call(this,r),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor),this.name="JsonWebTokenError",this.message=r,e&&(this.inner=e)};It.prototype=Object.create(Error.prototype);It.prototype.constructor=It;Gs.exports=It});var nn=w((fR,Ws)=>{var Hs=tt(),Nt=function(r,e){Hs.call(this,r),this.name="NotBeforeError",this.date=e};Nt.prototype=Object.create(Hs.prototype);Nt.prototype.constructor=Nt;Ws.exports=Nt});var sn=w((mR,Bs)=>{var Vs=tt(),Dt=function(r,e){Vs.call(this,r),this.name="TokenExpiredError",this.expiredAt=e};Dt.prototype=Object.create(Vs.prototype);Dt.prototype.constructor=Dt;Bs.exports=Dt});var Js=w((dR,Ys)=>{var qe=1e3,Ge=qe*60,He=Ge*60,Te=He*24,Gf=Te*7,Hf=Te*365.25;Ys.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return Wf(r);if(t==="number"&&isFinite(r))return e.long?Bf(r):Vf(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function Wf(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*Hf;case"weeks":case"week":case"w":return t*Gf;case"days":case"day":case"d":return t*Te;case"hours":case"hour":case"hrs":case"hr":case"h":return t*He;case"minutes":case"minute":case"mins":case"min":case"m":return t*Ge;case"seconds":case"second":case"secs":case"sec":case"s":return t*qe;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function Vf(r){var e=Math.abs(r);return e>=Te?Math.round(r/Te)+"d":e>=He?Math.round(r/He)+"h":e>=Ge?Math.round(r/Ge)+"m":e>=qe?Math.round(r/qe)+"s":r+"ms"}function Bf(r){var e=Math.abs(r);return e>=Te?Ft(r,e,Te,"day"):e>=He?Ft(r,e,He,"hour"):e>=Ge?Ft(r,e,Ge,"minute"):e>=qe?Ft(r,e,qe,"second"):r+" ms"}function Ft(r,e,t,n){var i=e>=t*1.5;return Math.round(r/t)+" "+n+(i?"s":"")}});var on=w((pR,Xs)=>{var Yf=Js();Xs.exports=function(r,e){var t=e||Math.floor(Date.now()/1e3);if(typeof r=="string"){var n=Yf(r);return typeof n>"u"?void 0:Math.floor(t+n/1e3)}else return typeof r=="number"?t+r:void 0}});var We=w((hR,zs)=>{"use strict";var Jf="2.0.0",Xf=Number.MAX_SAFE_INTEGER||9007199254740991,zf=16,Kf=250,Qf=["major","premajor","minor","preminor","patch","prepatch","prerelease"];zs.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:zf,MAX_SAFE_BUILD_LENGTH:Kf,MAX_SAFE_INTEGER:Xf,RELEASE_TYPES:Qf,SEMVER_SPEC_VERSION:Jf,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var rt=w((gR,Ks)=>{"use strict";var Zf=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...r)=>console.error("SEMVER",...r):()=>{};Ks.exports=Zf});var Ve=w((pe,Qs)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:an,MAX_SAFE_BUILD_LENGTH:em,MAX_LENGTH:tm}=We(),rm=rt();pe=Qs.exports={};var nm=pe.re=[],im=pe.safeRe=[],E=pe.src=[],sm=pe.safeSrc=[],R=pe.t={},om=0,ln="[a-zA-Z0-9-]",am=[["\\s",1],["\\d",tm],[ln,em]],lm=r=>{for(let[e,t]of am)r=r.split(`${e}*`).join(`${e}{0,${t}}`).split(`${e}+`).join(`${e}{1,${t}}`);return r},x=(r,e,t)=>{let n=lm(e),i=om++;rm(r,i,e),R[r]=i,E[i]=e,sm[i]=n,nm[i]=new RegExp(e,t?"g":void 0),im[i]=new RegExp(n,t?"g":void 0)};x("NUMERICIDENTIFIER","0|[1-9]\\d*");x("NUMERICIDENTIFIERLOOSE","\\d+");x("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${ln}*`);x("MAINVERSION",`(${E[R.NUMERICIDENTIFIER]})\\.(${E[R.NUMERICIDENTIFIER]})\\.(${E[R.NUMERICIDENTIFIER]})`);x("MAINVERSIONLOOSE",`(${E[R.NUMERICIDENTIFIERLOOSE]})\\.(${E[R.NUMERICIDENTIFIERLOOSE]})\\.(${E[R.NUMERICIDENTIFIERLOOSE]})`);x("PRERELEASEIDENTIFIER",`(?:${E[R.NONNUMERICIDENTIFIER]}|${E[R.NUMERICIDENTIFIER]})`);x("PRERELEASEIDENTIFIERLOOSE",`(?:${E[R.NONNUMERICIDENTIFIER]}|${E[R.NUMERICIDENTIFIERLOOSE]})`);x("PRERELEASE",`(?:-(${E[R.PRERELEASEIDENTIFIER]}(?:\\.${E[R.PRERELEASEIDENTIFIER]})*))`);x("PRERELEASELOOSE",`(?:-?(${E[R.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${E[R.PRERELEASEIDENTIFIERLOOSE]})*))`);x("BUILDIDENTIFIER",`${ln}+`);x("BUILD",`(?:\\+(${E[R.BUILDIDENTIFIER]}(?:\\.${E[R.BUILDIDENTIFIER]})*))`);x("FULLPLAIN",`v?${E[R.MAINVERSION]}${E[R.PRERELEASE]}?${E[R.BUILD]}?`);x("FULL",`^${E[R.FULLPLAIN]}$`);x("LOOSEPLAIN",`[v=\\s]*${E[R.MAINVERSIONLOOSE]}${E[R.PRERELEASELOOSE]}?${E[R.BUILD]}?`);x("LOOSE",`^${E[R.LOOSEPLAIN]}$`);x("GTLT","((?:<|>)?=?)");x("XRANGEIDENTIFIERLOOSE",`${E[R.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);x("XRANGEIDENTIFIER",`${E[R.NUMERICIDENTIFIER]}|x|X|\\*`);x("XRANGEPLAIN",`[v=\\s]*(${E[R.XRANGEIDENTIFIER]})(?:\\.(${E[R.XRANGEIDENTIFIER]})(?:\\.(${E[R.XRANGEIDENTIFIER]})(?:${E[R.PRERELEASE]})?${E[R.BUILD]}?)?)?`);x("XRANGEPLAINLOOSE",`[v=\\s]*(${E[R.XRANGEIDENTIFIERLOOSE]})(?:\\.(${E[R.XRANGEIDENTIFIERLOOSE]})(?:\\.(${E[R.XRANGEIDENTIFIERLOOSE]})(?:${E[R.PRERELEASELOOSE]})?${E[R.BUILD]}?)?)?`);x("XRANGE",`^${E[R.GTLT]}\\s*${E[R.XRANGEPLAIN]}$`);x("XRANGELOOSE",`^${E[R.GTLT]}\\s*${E[R.XRANGEPLAINLOOSE]}$`);x("COERCEPLAIN",`(^|[^\\d])(\\d{1,${an}})(?:\\.(\\d{1,${an}}))?(?:\\.(\\d{1,${an}}))?`);x("COERCE",`${E[R.COERCEPLAIN]}(?:$|[^\\d])`);x("COERCEFULL",E[R.COERCEPLAIN]+`(?:${E[R.PRERELEASE]})?(?:${E[R.BUILD]})?(?:$|[^\\d])`);x("COERCERTL",E[R.COERCE],!0);x("COERCERTLFULL",E[R.COERCEFULL],!0);x("LONETILDE","(?:~>?)");x("TILDETRIM",`(\\s*)${E[R.LONETILDE]}\\s+`,!0);pe.tildeTrimReplace="$1~";x("TILDE",`^${E[R.LONETILDE]}${E[R.XRANGEPLAIN]}$`);x("TILDELOOSE",`^${E[R.LONETILDE]}${E[R.XRANGEPLAINLOOSE]}$`);x("LONECARET","(?:\\^)");x("CARETTRIM",`(\\s*)${E[R.LONECARET]}\\s+`,!0);pe.caretTrimReplace="$1^";x("CARET",`^${E[R.LONECARET]}${E[R.XRANGEPLAIN]}$`);x("CARETLOOSE",`^${E[R.LONECARET]}${E[R.XRANGEPLAINLOOSE]}$`);x("COMPARATORLOOSE",`^${E[R.GTLT]}\\s*(${E[R.LOOSEPLAIN]})$|^$`);x("COMPARATOR",`^${E[R.GTLT]}\\s*(${E[R.FULLPLAIN]})$|^$`);x("COMPARATORTRIM",`(\\s*)${E[R.GTLT]}\\s*(${E[R.LOOSEPLAIN]}|${E[R.XRANGEPLAIN]})`,!0);pe.comparatorTrimReplace="$1$2$3";x("HYPHENRANGE",`^\\s*(${E[R.XRANGEPLAIN]})\\s+-\\s+(${E[R.XRANGEPLAIN]})\\s*$`);x("HYPHENRANGELOOSE",`^\\s*(${E[R.XRANGEPLAINLOOSE]})\\s+-\\s+(${E[R.XRANGEPLAINLOOSE]})\\s*$`);x("STAR","(<|>)?=?\\s*\\*");x("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");x("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var Ut=w((yR,Zs)=>{"use strict";var cm=Object.freeze({loose:!0}),um=Object.freeze({}),fm=r=>r?typeof r!="object"?cm:r:um;Zs.exports=fm});var cn=w((wR,ro)=>{"use strict";var eo=/^[0-9]+$/,to=(r,e)=>{if(typeof r=="number"&&typeof e=="number")return r===e?0:r<e?-1:1;let t=eo.test(r),n=eo.test(e);return t&&n&&(r=+r,e=+e),r===e?0:t&&!n?-1:n&&!t?1:r<e?-1:1},mm=(r,e)=>to(e,r);ro.exports={compareIdentifiers:to,rcompareIdentifiers:mm}});var Y=w((ER,io)=>{"use strict";var jt=rt(),{MAX_LENGTH:no,MAX_SAFE_INTEGER:qt}=We(),{safeRe:Gt,t:Ht}=Ve(),dm=Ut(),{compareIdentifiers:un}=cn(),fn=class r{constructor(e,t){if(t=dm(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>no)throw new TypeError(`version is longer than ${no} characters`);jt("SemVer",e,t),this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease;let n=e.trim().match(t.loose?Gt[Ht.LOOSE]:Gt[Ht.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>qt||this.major<0)throw new TypeError("Invalid major version");if(this.minor>qt||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>qt||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<qt)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(jt("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(jt("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 un(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(jt("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 un(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?Gt[Ht.PRERELEASELOOSE]:Gt[Ht.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]),un(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}};io.exports=fn});var Se=w((RR,oo)=>{"use strict";var so=Y(),pm=(r,e,t=!1)=>{if(r instanceof so)return r;try{return new so(r,e)}catch(n){if(!t)return null;throw n}};oo.exports=pm});var lo=w(($R,ao)=>{"use strict";var hm=Se(),gm=(r,e)=>{let t=hm(r,e);return t?t.version:null};ao.exports=gm});var uo=w((bR,co)=>{"use strict";var ym=Se(),wm=(r,e)=>{let t=ym(r.trim().replace(/^[=v]+/,""),e);return t?t.version:null};co.exports=wm});var po=w((SR,mo)=>{"use strict";var fo=Y(),Em=(r,e,t,n,i)=>{typeof t=="string"&&(i=n,n=t,t=void 0);try{return new fo(r instanceof fo?r.version:r,t).inc(e,n,i).version}catch{return null}};mo.exports=Em});var yo=w((vR,go)=>{"use strict";var ho=Se(),Rm=(r,e)=>{let t=ho(r,null,!0),n=ho(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 u=l?"pre":"";return t.major!==n.major?u+"major":t.minor!==n.minor?u+"minor":t.patch!==n.patch?u+"patch":"prerelease"};go.exports=Rm});var Eo=w((xR,wo)=>{"use strict";var $m=Y(),bm=(r,e)=>new $m(r,e).major;wo.exports=bm});var $o=w((kR,Ro)=>{"use strict";var Sm=Y(),vm=(r,e)=>new Sm(r,e).minor;Ro.exports=vm});var So=w((_R,bo)=>{"use strict";var xm=Y(),km=(r,e)=>new xm(r,e).patch;bo.exports=km});var xo=w((CR,vo)=>{"use strict";var _m=Se(),Cm=(r,e)=>{let t=_m(r,e);return t&&t.prerelease.length?t.prerelease:null};vo.exports=Cm});var se=w((OR,_o)=>{"use strict";var ko=Y(),Om=(r,e,t)=>new ko(r,t).compare(new ko(e,t));_o.exports=Om});var Oo=w((PR,Co)=>{"use strict";var Pm=se(),Tm=(r,e,t)=>Pm(e,r,t);Co.exports=Tm});var To=w((TR,Po)=>{"use strict";var Am=se(),Lm=(r,e)=>Am(r,e,!0);Po.exports=Lm});var Wt=w((AR,Lo)=>{"use strict";var Ao=Y(),Mm=(r,e,t)=>{let n=new Ao(r,t),i=new Ao(e,t);return n.compare(i)||n.compareBuild(i)};Lo.exports=Mm});var Io=w((LR,Mo)=>{"use strict";var Im=Wt(),Nm=(r,e)=>r.sort((t,n)=>Im(t,n,e));Mo.exports=Nm});var Do=w((MR,No)=>{"use strict";var Dm=Wt(),Fm=(r,e)=>r.sort((t,n)=>Dm(n,t,e));No.exports=Fm});var nt=w((IR,Fo)=>{"use strict";var Um=se(),jm=(r,e,t)=>Um(r,e,t)>0;Fo.exports=jm});var Vt=w((NR,Uo)=>{"use strict";var qm=se(),Gm=(r,e,t)=>qm(r,e,t)<0;Uo.exports=Gm});var mn=w((DR,jo)=>{"use strict";var Hm=se(),Wm=(r,e,t)=>Hm(r,e,t)===0;jo.exports=Wm});var dn=w((FR,qo)=>{"use strict";var Vm=se(),Bm=(r,e,t)=>Vm(r,e,t)!==0;qo.exports=Bm});var Bt=w((UR,Go)=>{"use strict";var Ym=se(),Jm=(r,e,t)=>Ym(r,e,t)>=0;Go.exports=Jm});var Yt=w((jR,Ho)=>{"use strict";var Xm=se(),zm=(r,e,t)=>Xm(r,e,t)<=0;Ho.exports=zm});var pn=w((qR,Wo)=>{"use strict";var Km=mn(),Qm=dn(),Zm=nt(),ed=Bt(),td=Vt(),rd=Yt(),nd=(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 Qm(r,t,n);case">":return Zm(r,t,n);case">=":return ed(r,t,n);case"<":return td(r,t,n);case"<=":return rd(r,t,n);default:throw new TypeError(`Invalid operator: ${e}`)}};Wo.exports=nd});var Bo=w((GR,Vo)=>{"use strict";var id=Y(),sd=Se(),{safeRe:Jt,t:Xt}=Ve(),od=(r,e)=>{if(r instanceof id)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?Jt[Xt.COERCEFULL]:Jt[Xt.COERCE]);else{let l=e.includePrerelease?Jt[Xt.COERCERTLFULL]:Jt[Xt.COERCERTL],c;for(;(c=l.exec(r))&&(!t||t.index+t[0].length!==r.length);)(!t||c.index+c[0].length!==t.index+t[0].length)&&(t=c),l.lastIndex=c.index+c[1].length+c[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 sd(`${n}.${i}.${s}${o}${a}`,e)};Vo.exports=od});var Jo=w((HR,Yo)=>{"use strict";var ad=Se(),ld=We(),cd=Y(),ud=(r,e,t)=>{if(!ld.RELEASE_TYPES.includes(e))return null;let n=fd(r,t);return n&&md(n,e)},fd=(r,e)=>{let t=r instanceof cd?r.version:r;return ad(t,e)},md=(r,e)=>{if(dd(e))return r.version;switch(r.prerelease=[],e){case"major":r.minor=0,r.patch=0;break;case"minor":r.patch=0;break}return r.format()},dd=r=>r.startsWith("pre");Yo.exports=ud});var zo=w((WR,Xo)=>{"use strict";var hn=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}};Xo.exports=hn});var oe=w((VR,ea)=>{"use strict";var pd=/\s+/g,gn=class r{constructor(e,t){if(t=gd(t),e instanceof r)return e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease?e:new r(e.raw,t);if(e instanceof yn)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(pd," "),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=>!Qo(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&&Sd(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&&$d)|(this.options.loose&&bd))+":"+e,i=Ko.get(n);if(i)return i;let s=this.options.loose,o=s?K[X.HYPHENRANGELOOSE]:K[X.HYPHENRANGE];e=e.replace(o,Ld(this.options.includePrerelease)),D("hyphen replace",e),e=e.replace(K[X.COMPARATORTRIM],wd),D("comparator trim",e),e=e.replace(K[X.TILDETRIM],Ed),D("tilde trim",e),e=e.replace(K[X.CARETTRIM],Rd),D("caret trim",e);let a=e.split(" ").map(f=>vd(f,this.options)).join(" ").split(/\s+/).map(f=>Ad(f,this.options));s&&(a=a.filter(f=>(D("loose invalid filter",f,this.options),!!f.match(K[X.COMPARATORLOOSE])))),D("range list",a);let l=new Map,c=a.map(f=>new yn(f,this.options));for(let f of c){if(Qo(f))return[f];l.set(f.value,f)}l.size>1&&l.has("")&&l.delete("");let u=[...l.values()];return Ko.set(n,u),u}intersects(e,t){if(!(e instanceof r))throw new TypeError("a Range is required");return this.set.some(n=>Zo(n,t)&&e.set.some(i=>Zo(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 yd(e,this.options)}catch{return!1}for(let t=0;t<this.set.length;t++)if(Md(this.set[t],e,this.options))return!0;return!1}};ea.exports=gn;var hd=zo(),Ko=new hd,gd=Ut(),yn=it(),D=rt(),yd=Y(),{safeRe:K,t:X,comparatorTrimReplace:wd,tildeTrimReplace:Ed,caretTrimReplace:Rd}=Ve(),{FLAG_INCLUDE_PRERELEASE:$d,FLAG_LOOSE:bd}=We(),Qo=r=>r.value==="<0.0.0-0",Sd=r=>r.value==="",Zo=(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},vd=(r,e)=>(r=r.replace(K[X.BUILD],""),D("comp",r,e),r=_d(r,e),D("caret",r),r=xd(r,e),D("tildes",r),r=Od(r,e),D("xrange",r),r=Td(r,e),D("stars",r),r),Q=r=>!r||r.toLowerCase()==="x"||r==="*",xd=(r,e)=>r.trim().split(/\s+/).map(t=>kd(t,e)).join(" "),kd=(r,e)=>{let t=e.loose?K[X.TILDELOOSE]:K[X.TILDE];return r.replace(t,(n,i,s,o,a)=>{D("tilde",r,n,i,s,o,a);let l;return Q(i)?l="":Q(s)?l=`>=${i}.0.0 <${+i+1}.0.0-0`:Q(o)?l=`>=${i}.${s}.0 <${i}.${+s+1}.0-0`:a?(D("replaceTilde pr",a),l=`>=${i}.${s}.${o}-${a} <${i}.${+s+1}.0-0`):l=`>=${i}.${s}.${o} <${i}.${+s+1}.0-0`,D("tilde return",l),l})},_d=(r,e)=>r.trim().split(/\s+/).map(t=>Cd(t,e)).join(" "),Cd=(r,e)=>{D("caret",r,e);let t=e.loose?K[X.CARETLOOSE]:K[X.CARET],n=e.includePrerelease?"-0":"";return r.replace(t,(i,s,o,a,l)=>{D("caret",r,i,s,o,a,l);let c;return Q(s)?c="":Q(o)?c=`>=${s}.0.0${n} <${+s+1}.0.0-0`:Q(a)?s==="0"?c=`>=${s}.${o}.0${n} <${s}.${+o+1}.0-0`:c=`>=${s}.${o}.0${n} <${+s+1}.0.0-0`:l?(D("replaceCaret pr",l),s==="0"?o==="0"?c=`>=${s}.${o}.${a}-${l} <${s}.${o}.${+a+1}-0`:c=`>=${s}.${o}.${a}-${l} <${s}.${+o+1}.0-0`:c=`>=${s}.${o}.${a}-${l} <${+s+1}.0.0-0`):(D("no pr"),s==="0"?o==="0"?c=`>=${s}.${o}.${a}${n} <${s}.${o}.${+a+1}-0`:c=`>=${s}.${o}.${a}${n} <${s}.${+o+1}.0-0`:c=`>=${s}.${o}.${a} <${+s+1}.0.0-0`),D("caret return",c),c})},Od=(r,e)=>(D("replaceXRanges",r,e),r.split(/\s+/).map(t=>Pd(t,e)).join(" ")),Pd=(r,e)=>{r=r.trim();let t=e.loose?K[X.XRANGELOOSE]:K[X.XRANGE];return r.replace(t,(n,i,s,o,a,l)=>{D("xRange",r,n,i,s,o,a,l);let c=Q(s),u=c||Q(o),f=u||Q(a),d=f;return i==="="&&d&&(i=""),l=e.includePrerelease?"-0":"",c?i===">"||i==="<"?n="<0.0.0-0":n="*":i&&d?(u&&(o=0),a=0,i===">"?(i=">=",u?(s=+s+1,o=0,a=0):(o=+o+1,a=0)):i==="<="&&(i="<",u?s=+s+1:o=+o+1),i==="<"&&(l="-0"),n=`${i+s}.${o}.${a}${l}`):u?n=`>=${s}.0.0${l} <${+s+1}.0.0-0`:f&&(n=`>=${s}.${o}.0${l} <${s}.${+o+1}.0-0`),D("xRange return",n),n})},Td=(r,e)=>(D("replaceStars",r,e),r.trim().replace(K[X.STAR],"")),Ad=(r,e)=>(D("replaceGTE0",r,e),r.trim().replace(K[e.includePrerelease?X.GTE0PRE:X.GTE0],"")),Ld=r=>(e,t,n,i,s,o,a,l,c,u,f,d)=>(Q(n)?t="":Q(i)?t=`>=${n}.0.0${r?"-0":""}`:Q(s)?t=`>=${n}.${i}.0${r?"-0":""}`:o?t=`>=${t}`:t=`>=${t}${r?"-0":""}`,Q(c)?l="":Q(u)?l=`<${+c+1}.0.0-0`:Q(f)?l=`<${c}.${+u+1}.0-0`:d?l=`<=${c}.${u}.${f}-${d}`:r?l=`<${c}.${u}.${+f+1}-0`:l=`<=${l}`,`${t} ${l}`.trim()),Md=(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(D(r[n].semver),r[n].semver!==yn.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 it=w((BR,oa)=>{"use strict";var st=Symbol("SemVer ANY"),Rn=class r{static get ANY(){return st}constructor(e,t){if(t=ta(t),e instanceof r){if(e.loose===!!t.loose)return e;e=e.value}e=e.trim().split(/\s+/).join(" "),En("comparator",e,t),this.options=t,this.loose=!!t.loose,this.parse(e),this.semver===st?this.value="":this.value=this.operator+this.semver.version,En("comp",this)}parse(e){let t=this.options.loose?ra[na.COMPARATORLOOSE]:ra[na.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 ia(n[2],this.options.loose):this.semver=st}toString(){return this.value}test(e){if(En("Comparator.test",e,this.options.loose),this.semver===st||e===st)return!0;if(typeof e=="string")try{e=new ia(e,this.options)}catch{return!1}return wn(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 sa(e.value,t).test(this.value):e.operator===""?e.value===""?!0:new sa(this.value,t).test(e.semver):(t=ta(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("=")||wn(this.semver,"<",e.semver,t)&&this.operator.startsWith(">")&&e.operator.startsWith("<")||wn(this.semver,">",e.semver,t)&&this.operator.startsWith("<")&&e.operator.startsWith(">")))}};oa.exports=Rn;var ta=Ut(),{safeRe:ra,t:na}=Ve(),wn=pn(),En=rt(),ia=Y(),sa=oe()});var ot=w((YR,aa)=>{"use strict";var Id=oe(),Nd=(r,e,t)=>{try{e=new Id(e,t)}catch{return!1}return e.test(r)};aa.exports=Nd});var ca=w((JR,la)=>{"use strict";var Dd=oe(),Fd=(r,e)=>new Dd(r,e).set.map(t=>t.map(n=>n.value).join(" ").trim().split(" "));la.exports=Fd});var fa=w((XR,ua)=>{"use strict";var Ud=Y(),jd=oe(),qd=(r,e,t)=>{let n=null,i=null,s=null;try{s=new jd(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};ua.exports=qd});var da=w((zR,ma)=>{"use strict";var Gd=Y(),Hd=oe(),Wd=(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 Gd(n,t))}),n};ma.exports=Wd});var ga=w((KR,ha)=>{"use strict";var $n=Y(),Vd=oe(),pa=nt(),Bd=(r,e)=>{r=new Vd(r,e);let t=new $n("0.0.0");if(r.test(t)||(t=new $n("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 $n(o.semver.version);switch(o.operator){case">":a.prerelease.length===0?a.patch++:a.prerelease.push(0),a.raw=a.format();case"":case">=":(!s||pa(a,s))&&(s=a);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${o.operator}`)}}),s&&(!t||pa(t,s))&&(t=s)}return t&&r.test(t)?t:null};ha.exports=Bd});var wa=w((QR,ya)=>{"use strict";var Yd=oe(),Jd=(r,e)=>{try{return new Yd(r,e).range||"*"}catch{return null}};ya.exports=Jd});var zt=w((ZR,ba)=>{"use strict";var Xd=Y(),$a=it(),{ANY:zd}=$a,Kd=oe(),Qd=ot(),Ea=nt(),Ra=Vt(),Zd=Yt(),ep=Bt(),tp=(r,e,t,n)=>{r=new Xd(r,n),e=new Kd(e,n);let i,s,o,a,l;switch(t){case">":i=Ea,s=Zd,o=Ra,a=">",l=">=";break;case"<":i=Ra,s=ep,o=Ea,a="<",l="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(Qd(r,e,n))return!1;for(let c=0;c<e.set.length;++c){let u=e.set[c],f=null,d=null;if(u.forEach(p=>{p.semver===zd&&(p=new $a(">=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};ba.exports=tp});var va=w((e$,Sa)=>{"use strict";var rp=zt(),np=(r,e,t)=>rp(r,e,">",t);Sa.exports=np});var ka=w((t$,xa)=>{"use strict";var ip=zt(),sp=(r,e,t)=>ip(r,e,"<",t);xa.exports=sp});var Oa=w((r$,Ca)=>{"use strict";var _a=oe(),op=(r,e,t)=>(r=new _a(r,t),e=new _a(e,t),r.intersects(e,t));Ca.exports=op});var Ta=w((n$,Pa)=>{"use strict";var ap=ot(),lp=se();Pa.exports=(r,e,t)=>{let n=[],i=null,s=null,o=r.sort((u,f)=>lp(u,f,t));for(let u of o)ap(u,e,t)?(s=u,i||(i=u)):(s&&n.push([i,s]),s=null,i=null);i&&n.push([i,null]);let a=[];for(let[u,f]of n)u===f?a.push(u):!f&&u===o[0]?a.push("*"):f?u===o[0]?a.push(`<=${f}`):a.push(`${u} - ${f}`):a.push(`>=${u}`);let l=a.join(" || "),c=typeof e.raw=="string"?e.raw:String(e);return l.length<c.length?l:e}});var Da=w((i$,Na)=>{"use strict";var Aa=oe(),Sn=it(),{ANY:bn}=Sn,at=ot(),vn=se(),cp=(r,e,t={})=>{if(r===e)return!0;r=new Aa(r,t),e=new Aa(e,t);let n=!1;e:for(let i of r.set){for(let s of e.set){let o=fp(i,s,t);if(n=n||o!==null,o)continue e}if(n)return!1}return!0},up=[new Sn(">=0.0.0-0")],La=[new Sn(">=0.0.0")],fp=(r,e,t)=>{if(r===e)return!0;if(r.length===1&&r[0].semver===bn){if(e.length===1&&e[0].semver===bn)return!0;t.includePrerelease?r=up:r=La}if(e.length===1&&e[0].semver===bn){if(t.includePrerelease)return!0;e=La}let n=new Set,i,s;for(let p of r)p.operator===">"||p.operator===">="?i=Ma(i,p,t):p.operator==="<"||p.operator==="<="?s=Ia(s,p,t):n.add(p.semver);if(n.size>1)return null;let o;if(i&&s){if(o=vn(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&&!at(p,String(i),t)||s&&!at(p,String(s),t))return null;for(let y of e)if(!at(p,String(y),t))return!1;return!0}let a,l,c,u,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(u=u||p.operator===">"||p.operator===">=",c=c||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=Ma(i,p,t),a===p&&a!==i)return!1}else if(i.operator===">="&&!at(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=Ia(s,p,t),l===p&&l!==s)return!1}else if(s.operator==="<="&&!at(s.semver,String(p),t))return!1}if(!p.operator&&(s||i)&&o!==0)return!1}return!(i&&c&&!s&&o!==0||s&&u&&!i&&o!==0||d||f)},Ma=(r,e,t)=>{if(!r)return e;let n=vn(r.semver,e.semver,t);return n>0?r:n<0||e.operator===">"&&r.operator===">="?e:r},Ia=(r,e,t)=>{if(!r)return e;let n=vn(r.semver,e.semver,t);return n<0?r:n>0||e.operator==="<"&&r.operator==="<="?e:r};Na.exports=cp});var Kt=w((s$,ja)=>{"use strict";var xn=Ve(),Fa=We(),mp=Y(),Ua=cn(),dp=Se(),pp=lo(),hp=uo(),gp=po(),yp=yo(),wp=Eo(),Ep=$o(),Rp=So(),$p=xo(),bp=se(),Sp=Oo(),vp=To(),xp=Wt(),kp=Io(),_p=Do(),Cp=nt(),Op=Vt(),Pp=mn(),Tp=dn(),Ap=Bt(),Lp=Yt(),Mp=pn(),Ip=Bo(),Np=Jo(),Dp=it(),Fp=oe(),Up=ot(),jp=ca(),qp=fa(),Gp=da(),Hp=ga(),Wp=wa(),Vp=zt(),Bp=va(),Yp=ka(),Jp=Oa(),Xp=Ta(),zp=Da();ja.exports={parse:dp,valid:pp,clean:hp,inc:gp,diff:yp,major:wp,minor:Ep,patch:Rp,prerelease:$p,compare:bp,rcompare:Sp,compareLoose:vp,compareBuild:xp,sort:kp,rsort:_p,gt:Cp,lt:Op,eq:Pp,neq:Tp,gte:Ap,lte:Lp,cmp:Mp,coerce:Ip,truncate:Np,Comparator:Dp,Range:Fp,satisfies:Up,toComparators:jp,maxSatisfying:qp,minSatisfying:Gp,minVersion:Hp,validRange:Wp,outside:Vp,gtr:Bp,ltr:Yp,intersects:Jp,simplifyRange:Xp,subset:zp,SemVer:mp,re:xn.re,src:xn.src,tokens:xn.t,SEMVER_SPEC_VERSION:Fa.SEMVER_SPEC_VERSION,RELEASE_TYPES:Fa.RELEASE_TYPES,compareIdentifiers:Ua.compareIdentifiers,rcompareIdentifiers:Ua.rcompareIdentifiers}});var Ga=w((o$,qa)=>{var Kp=Kt();qa.exports=Kp.satisfies(process.version,">=15.7.0")});var Wa=w((a$,Ha)=>{var Qp=Kt();Ha.exports=Qp.satisfies(process.version,">=16.9.0")});var kn=w((l$,Va)=>{var Zp=Ga(),eh=Wa(),th={ec:["ES256","ES384","ES512"],rsa:["RS256","PS256","RS384","PS384","RS512","PS512"],"rsa-pss":["PS256","PS384","PS512"]},rh={ES256:"prime256v1",ES384:"secp384r1",ES512:"secp521r1"};Va.exports=function(r,e){if(!r||!e)return;let t=e.asymmetricKeyType;if(!t)return;let n=th[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(Zp)switch(t){case"ec":let i=e.asymmetricKeyDetails.namedCurve,s=rh[r];if(i!==s)throw new Error(`"alg" parameter "${r}" requires curve "${s}".`);break;case"rsa-pss":if(eh){let o=parseInt(r.slice(-3),10),{hashAlgorithm:a,mgf1HashAlgorithm:l,saltLength:c}=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(c!==void 0&&c>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 _n=w((c$,Ba)=>{var nh=Kt();Ba.exports=nh.satisfies(process.version,"^6.12.0 || >=8.0.0")});var Xa=w((u$,Ja)=>{var N=tt(),ih=nn(),Ya=sn(),sh=rn(),oh=on(),ah=kn(),lh=_n(),ch=Mt(),{KeyObject:uh,createSecretKey:fh,createPublicKey:mh}=require("crypto"),Cn=["RS256","RS384","RS512"],dh=["ES256","ES384","ES512"],On=["RS256","RS384","RS512"],ph=["HS256","HS384","HS512"];lh&&(Cn.splice(Cn.length,0,"PS256","PS384","PS512"),On.splice(On.length,0,"PS256","PS384","PS512"));Ja.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(u,f){if(u)throw u;return f},t.clockTimestamp&&typeof t.clockTimestamp!="number")return i(new N("clockTimestamp must be a number"));if(t.nonce!==void 0&&(typeof t.nonce!="string"||t.nonce.trim()===""))return i(new N("nonce must be a non-empty string"));if(t.allowInvalidAsymmetricKeyTypes!==void 0&&typeof t.allowInvalidAsymmetricKeyTypes!="boolean")return i(new N("allowInvalidAsymmetricKeyTypes must be a boolean"));let s=t.clockTimestamp||Math.floor(Date.now()/1e3);if(!r)return i(new N("jwt must be provided"));if(typeof r!="string")return i(new N("jwt must be a string"));let o=r.split(".");if(o.length!==3)return i(new N("jwt malformed"));let a;try{a=sh(r,{complete:!0})}catch(u){return i(u)}if(!a)return i(new N("invalid token"));let l=a.header,c;if(typeof e=="function"){if(!n)return i(new N("verify must be called asynchronous if secret or public key is provided as a callback"));c=e}else c=function(u,f){return f(null,e)};return c(l,function(u,f){if(u)return i(new N("error in secret or public key callback: "+u.message));let d=o[2].trim()!=="";if(!d&&f)return i(new N("jwt signature is required"));if(d&&!f)return i(new N("secret or public key must be provided"));if(!d&&!t.algorithms)return i(new N('please specify "none" in "algorithms" to verify unsigned tokens'));if(f!=null&&!(f instanceof uh))try{f=mh(f)}catch{try{f=fh(typeof f=="string"?Buffer.from(f):f)}catch{return i(new N("secretOrPublicKey is not valid key material"))}}if(t.algorithms||(f.type==="secret"?t.algorithms=ph:["rsa","rsa-pss"].includes(f.asymmetricKeyType)?t.algorithms=On:f.asymmetricKeyType==="ec"?t.algorithms=dh:t.algorithms=Cn),t.algorithms.indexOf(a.header.alg)===-1)return i(new N("invalid algorithm"));if(l.alg.startsWith("HS")&&f.type!=="secret")return i(new N(`secretOrPublicKey must be a symmetric key when using ${l.alg}`));if(/^(?:RS|PS|ES)/.test(l.alg)&&f.type!=="public")return i(new N(`secretOrPublicKey must be an asymmetric key when using ${l.alg}`));if(!t.allowInvalidAsymmetricKeyTypes)try{ah(l.alg,f)}catch($){return i($)}let p;try{p=ch.verify(r,a.header.alg,f)}catch($){return i($)}if(!p)return i(new N("invalid signature"));let y=a.payload;if(typeof y.nbf<"u"&&!t.ignoreNotBefore){if(typeof y.nbf!="number")return i(new N("invalid nbf value"));if(y.nbf>s+(t.clockTolerance||0))return i(new ih("jwt not active",new Date(y.nbf*1e3)))}if(typeof y.exp<"u"&&!t.ignoreExpiration){if(typeof y.exp!="number")return i(new N("invalid exp value"));if(s>=y.exp+(t.clockTolerance||0))return i(new Ya("jwt expired",new Date(y.exp*1e3)))}if(t.audience){let $=Array.isArray(t.audience)?t.audience:[t.audience];if(!(Array.isArray(y.aud)?y.aud:[y.aud]).some(function(b){return $.some(function(v){return v instanceof RegExp?v.test(b):v===b})}))return i(new N("jwt audience invalid. expected: "+$.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 N("jwt issuer invalid. expected: "+t.issuer));if(t.subject&&y.sub!==t.subject)return i(new N("jwt subject invalid. expected: "+t.subject));if(t.jwtid&&y.jti!==t.jwtid)return i(new N("jwt jwtid invalid. expected: "+t.jwtid));if(t.nonce&&y.nonce!==t.nonce)return i(new N("jwt nonce invalid. expected: "+t.nonce));if(t.maxAge){if(typeof y.iat!="number")return i(new N("iat required when maxAge is specified"));let $=oh(t.maxAge,y.iat);if(typeof $>"u")return i(new N('"maxAge" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60'));if(s>=$+(t.clockTolerance||0))return i(new Ya("maxAge exceeded",new Date($*1e3)))}if(t.complete===!0){let $=a.signature;return i(null,{header:l,payload:y,signature:$})}return i(null,y)})}});var tl=w((f$,el)=>{var za=1/0,Qa=9007199254740991,hh=17976931348623157e292,Ka=NaN,gh="[object Arguments]",yh="[object Function]",wh="[object GeneratorFunction]",Eh="[object String]",Rh="[object Symbol]",$h=/^\s+|\s+$/g,bh=/^[-+]0x[0-9a-f]+$/i,Sh=/^0b[01]+$/i,vh=/^0o[0-7]+$/i,xh=/^(?:0|[1-9]\d*)$/,kh=parseInt;function _h(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 Ch(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 Oh(r,e,t){if(e!==e)return Ch(r,Ph,t);for(var n=t-1,i=r.length;++n<i;)if(r[n]===e)return n;return-1}function Ph(r){return r!==r}function Th(r,e){for(var t=-1,n=Array(r);++t<r;)n[t]=e(t);return n}function Ah(r,e){return _h(e,function(t){return r[t]})}function Lh(r,e){return function(t){return r(e(t))}}var Qt=Object.prototype,Tn=Qt.hasOwnProperty,Zt=Qt.toString,Mh=Qt.propertyIsEnumerable,Ih=Lh(Object.keys,Object),Nh=Math.max;function Dh(r,e){var t=Za(r)||Gh(r)?Th(r.length,String):[],n=t.length,i=!!n;for(var s in r)(e||Tn.call(r,s))&&!(i&&(s=="length"||Uh(s,n)))&&t.push(s);return t}function Fh(r){if(!jh(r))return Ih(r);var e=[];for(var t in Object(r))Tn.call(r,t)&&t!="constructor"&&e.push(t);return e}function Uh(r,e){return e=e??Qa,!!e&&(typeof r=="number"||xh.test(r))&&r>-1&&r%1==0&&r<e}function jh(r){var e=r&&r.constructor,t=typeof e=="function"&&e.prototype||Qt;return r===t}function qh(r,e,t,n){r=An(r)?r:Qh(r),t=t&&!n?Xh(t):0;var i=r.length;return t<0&&(t=Nh(i+t,0)),Bh(r)?t<=i&&r.indexOf(e,t)>-1:!!i&&Oh(r,e,t)>-1}function Gh(r){return Hh(r)&&Tn.call(r,"callee")&&(!Mh.call(r,"callee")||Zt.call(r)==gh)}var Za=Array.isArray;function An(r){return r!=null&&Vh(r.length)&&!Wh(r)}function Hh(r){return Ln(r)&&An(r)}function Wh(r){var e=Pn(r)?Zt.call(r):"";return e==yh||e==wh}function Vh(r){return typeof r=="number"&&r>-1&&r%1==0&&r<=Qa}function Pn(r){var e=typeof r;return!!r&&(e=="object"||e=="function")}function Ln(r){return!!r&&typeof r=="object"}function Bh(r){return typeof r=="string"||!Za(r)&&Ln(r)&&Zt.call(r)==Eh}function Yh(r){return typeof r=="symbol"||Ln(r)&&Zt.call(r)==Rh}function Jh(r){if(!r)return r===0?r:0;if(r=zh(r),r===za||r===-za){var e=r<0?-1:1;return e*hh}return r===r?r:0}function Xh(r){var e=Jh(r),t=e%1;return e===e?t?e-t:e:0}function zh(r){if(typeof r=="number")return r;if(Yh(r))return Ka;if(Pn(r)){var e=typeof r.valueOf=="function"?r.valueOf():r;r=Pn(e)?e+"":e}if(typeof r!="string")return r===0?r:+r;r=r.replace($h,"");var t=Sh.test(r);return t||vh.test(r)?kh(r.slice(2),t?2:8):bh.test(r)?Ka:+r}function Kh(r){return An(r)?Dh(r):Fh(r)}function Qh(r){return r?Ah(r,Kh(r)):[]}el.exports=qh});var nl=w((m$,rl)=>{var Zh="[object Boolean]",eg=Object.prototype,tg=eg.toString;function rg(r){return r===!0||r===!1||ng(r)&&tg.call(r)==Zh}function ng(r){return!!r&&typeof r=="object"}rl.exports=rg});var ll=w((d$,al)=>{var il=1/0,ig=17976931348623157e292,sl=NaN,sg="[object Symbol]",og=/^\s+|\s+$/g,ag=/^[-+]0x[0-9a-f]+$/i,lg=/^0b[01]+$/i,cg=/^0o[0-7]+$/i,ug=parseInt,fg=Object.prototype,mg=fg.toString;function dg(r){return typeof r=="number"&&r==yg(r)}function ol(r){var e=typeof r;return!!r&&(e=="object"||e=="function")}function pg(r){return!!r&&typeof r=="object"}function hg(r){return typeof r=="symbol"||pg(r)&&mg.call(r)==sg}function gg(r){if(!r)return r===0?r:0;if(r=wg(r),r===il||r===-il){var e=r<0?-1:1;return e*ig}return r===r?r:0}function yg(r){var e=gg(r),t=e%1;return e===e?t?e-t:e:0}function wg(r){if(typeof r=="number")return r;if(hg(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(og,"");var t=lg.test(r);return t||cg.test(r)?ug(r.slice(2),t?2:8):ag.test(r)?sl:+r}al.exports=dg});var ul=w((p$,cl)=>{var Eg="[object Number]",Rg=Object.prototype,$g=Rg.toString;function bg(r){return!!r&&typeof r=="object"}function Sg(r){return typeof r=="number"||bg(r)&&$g.call(r)==Eg}cl.exports=Sg});var pl=w((h$,dl)=>{var vg="[object Object]";function xg(r){var e=!1;if(r!=null&&typeof r.toString!="function")try{e=!!(r+"")}catch{}return e}function kg(r,e){return function(t){return r(e(t))}}var _g=Function.prototype,fl=Object.prototype,ml=_g.toString,Cg=fl.hasOwnProperty,Og=ml.call(Object),Pg=fl.toString,Tg=kg(Object.getPrototypeOf,Object);function Ag(r){return!!r&&typeof r=="object"}function Lg(r){if(!Ag(r)||Pg.call(r)!=vg||xg(r))return!1;var e=Tg(r);if(e===null)return!0;var t=Cg.call(e,"constructor")&&e.constructor;return typeof t=="function"&&t instanceof t&&ml.call(t)==Og}dl.exports=Lg});var gl=w((g$,hl)=>{var Mg="[object String]",Ig=Object.prototype,Ng=Ig.toString,Dg=Array.isArray;function Fg(r){return!!r&&typeof r=="object"}function Ug(r){return typeof r=="string"||!Dg(r)&&Fg(r)&&Ng.call(r)==Mg}hl.exports=Ug});var $l=w((y$,Rl)=>{var jg="Expected a function",yl=1/0,qg=17976931348623157e292,wl=NaN,Gg="[object Symbol]",Hg=/^\s+|\s+$/g,Wg=/^[-+]0x[0-9a-f]+$/i,Vg=/^0b[01]+$/i,Bg=/^0o[0-7]+$/i,Yg=parseInt,Jg=Object.prototype,Xg=Jg.toString;function zg(r,e){var t;if(typeof e!="function")throw new TypeError(jg);return r=ty(r),function(){return--r>0&&(t=e.apply(this,arguments)),r<=1&&(e=void 0),t}}function Kg(r){return zg(2,r)}function El(r){var e=typeof r;return!!r&&(e=="object"||e=="function")}function Qg(r){return!!r&&typeof r=="object"}function Zg(r){return typeof r=="symbol"||Qg(r)&&Xg.call(r)==Gg}function ey(r){if(!r)return r===0?r:0;if(r=ry(r),r===yl||r===-yl){var e=r<0?-1:1;return e*qg}return r===r?r:0}function ty(r){var e=ey(r),t=e%1;return e===e?t?e-t:e:0}function ry(r){if(typeof r=="number")return r;if(Zg(r))return wl;if(El(r)){var e=typeof r.valueOf=="function"?r.valueOf():r;r=El(e)?e+"":e}if(typeof r!="string")return r===0?r:+r;r=r.replace(Hg,"");var t=Vg.test(r);return t||Bg.test(r)?Yg(r.slice(2),t?2:8):Wg.test(r)?wl:+r}Rl.exports=Kg});var Pl=w((w$,Ol)=>{var bl=on(),ny=_n(),iy=kn(),Sl=Mt(),sy=tl(),er=nl(),vl=ll(),Mn=ul(),kl=pl(),ve=gl(),oy=$l(),{KeyObject:ay,createSecretKey:ly,createPrivateKey:cy}=require("crypto"),_l=["RS256","RS384","RS512","ES256","ES384","ES512","HS256","HS384","HS512","none"];ny&&_l.splice(3,0,"PS256","PS384","PS512");var uy={expiresIn:{isValid:function(r){return vl(r)||ve(r)&&r},message:'"expiresIn" should be a number of seconds or string representing a timespan'},notBefore:{isValid:function(r){return vl(r)||ve(r)&&r},message:'"notBefore" should be a number of seconds or string representing a timespan'},audience:{isValid:function(r){return ve(r)||Array.isArray(r)},message:'"audience" must be a string or array'},algorithm:{isValid:sy.bind(null,_l),message:'"algorithm" must be a valid string enum value'},header:{isValid:kl,message:'"header" must be an object'},encoding:{isValid:ve,message:'"encoding" must be a string'},issuer:{isValid:ve,message:'"issuer" must be a string'},subject:{isValid:ve,message:'"subject" must be a string'},jwtid:{isValid:ve,message:'"jwtid" must be a string'},noTimestamp:{isValid:er,message:'"noTimestamp" must be a boolean'},keyid:{isValid:ve,message:'"keyid" must be a string'},mutatePayload:{isValid:er,message:'"mutatePayload" must be a boolean'},allowInsecureKeySizes:{isValid:er,message:'"allowInsecureKeySizes" must be a boolean'},allowInvalidAsymmetricKeyTypes:{isValid:er,message:'"allowInvalidAsymmetricKeyTypes" must be a boolean'}},fy={iat:{isValid:Mn,message:'"iat" should be a number of seconds'},exp:{isValid:Mn,message:'"exp" should be a number of seconds'},nbf:{isValid:Mn,message:'"nbf" should be a number of seconds'}};function Cl(r,e,t,n){if(!kl(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 my(r){return Cl(uy,!1,r,"options")}function dy(r){return Cl(fy,!0,r,"payload")}var xl={audience:"aud",issuer:"iss",subject:"sub",jwtid:"jti"},py=["expiresIn","notBefore","noTimestamp","audience","issuer","subject","jwtid"];Ol.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(c){if(n)return n(c);throw c}if(!e&&t.algorithm!=="none")return o(new Error("secretOrPrivateKey must have a value"));if(e!=null&&!(e instanceof ay))try{e=cy(e)}catch{try{e=ly(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{dy(r)}catch(c){return o(c)}t.mutatePayload||(r=Object.assign({},r))}else{let c=py.filter(function(u){return typeof t[u]<"u"});if(c.length>0)return o(new Error("invalid "+c.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{my(t)}catch(c){return o(c)}if(!t.allowInvalidAsymmetricKeyTypes)try{iy(s.alg,e)}catch(c){return o(c)}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=bl(t.notBefore,a)}catch(c){return o(c)}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=bl(t.expiresIn,a)}catch(c){return o(c)}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(xl).forEach(function(c){let u=xl[c];if(typeof t[c]<"u"){if(typeof r[u]<"u")return o(new Error('Bad "options.'+c+'" option. The payload already has an "'+u+'" property.'));r[u]=t[c]}});let l=t.encoding||"utf8";if(typeof n=="function")n=n&&oy(n),Sl.createSign({header:s,privateKey:e,payload:r,encoding:l}).once("error",n).once("done",function(c){if(!t.allowInsecureKeySizes&&/^(?:RS|PS)/.test(s.alg)&&c.length<256)return n(new Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${s.alg}`));n(null,c)});else{let c=Sl.sign({header:s,payload:r,secret:e,encoding:l});if(!t.allowInsecureKeySizes&&/^(?:RS|PS)/.test(s.alg)&&c.length<256)throw new Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${s.alg}`);return c}}});var In=w((E$,Tl)=>{Tl.exports={decode:rn(),verify:Xa(),sign:Pl(),JsonWebTokenError:tt(),NotBeforeError:nn(),TokenExpiredError:sn()}});var wc=w((zb,yc)=>{function uc(r){return Array.isArray(r)?r:[r]}var ni="",fc=" ",ti="\\",fw=/^\s+$/,mw=/(?:[^\\]|^)\\$/,dw=/^\\!/,pw=/^\\#/,hw=/\r?\n/g,gw=/^\.*\/|^\.+$/,ri="/",pc="node-ignore";typeof Symbol<"u"&&(pc=Symbol.for("node-ignore"));var mc=pc,yw=(r,e,t)=>Object.defineProperty(r,e,{value:t}),ww=/([0-z])-([0-z])/g,hc=()=>!1,Ew=r=>r.replace(ww,(e,t,n)=>t.charCodeAt(0)<=n.charCodeAt(0)?e:ni),Rw=r=>{let{length:e}=r;return r.slice(0,e-e%2)},$w=[[/^\uFEFF/,()=>ni],[/((?:\\\\)*?)(\\?\s+)$/,(r,e,t)=>e+(t.indexOf("\\")===0?fc:ni)],[/(\\+?)\s/g,(r,e)=>{let{length:t}=e;return e.slice(0,t-t%2)+fc}],[/[\\$.|*+(){^]/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,()=>ti],[/\\\\/g,()=>ti],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(r,e,t,n,i)=>e===ti?`\\[${t}${Rw(n)}${i}`:i==="]"&&n.length%2===0?`[${Ew(t)}${n}]`:"[]"],[/(?:[^*])$/,r=>/\/$/.test(r)?`${r}$`:`${r}(?=$|\\/$)`],[/(\^|\\\/)?\\\*$/,(r,e)=>`${e?`${e}[^/]+`:"[^/]*"}(?=$|\\/$)`]],dc=Object.create(null),bw=(r,e)=>{let t=dc[r];return t||(t=$w.reduce((n,[i,s])=>n.replace(i,s.bind(r)),r),dc[r]=t),e?new RegExp(t,"i"):new RegExp(t)},oi=r=>typeof r=="string",Sw=r=>r&&oi(r)&&!fw.test(r)&&!mw.test(r)&&r.indexOf("#")!==0,vw=r=>r.split(hw),ii=class{constructor(e,t,n,i){this.origin=e,this.pattern=t,this.negative=n,this.regex=i}},xw=(r,e)=>{let t=r,n=!1;r.indexOf("!")===0&&(n=!0,r=r.substr(1)),r=r.replace(dw,"!").replace(pw,"#");let i=bw(r,e);return new ii(t,r,n,i)},kw=(r,e)=>{throw new e(r)},$e=(r,e,t)=>oi(r)?r?$e.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),gc=r=>gw.test(r);$e.isNotRelative=gc;$e.convert=r=>r;var si=class{constructor({ignorecase:e=!0,ignoreCase:t=e,allowRelativePaths:n=!1}={}){yw(this,mc,!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[mc]){this._rules=this._rules.concat(e._rules),this._added=!0;return}if(Sw(e)){let t=xw(e,this._ignoreCase);this._added=!0,this._rules.push(t)}}add(e){return this._added=!1,uc(oi(e)?vw(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&&$e.convert(e);return $e(s,e,this._allowRelativePaths?hc:kw),this._t(s,t,n,i)}_t(e,t,n,i){if(e in t)return t[e];if(i||(i=e.split(ri)),i.pop(),!i.length)return t[e]=this._testOne(e,n);let s=this._t(i.join(ri)+ri,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 uc(e).filter(this.createFilter())}test(e){return this._test(e,this._testCache,!0)}},pr=r=>new si(r),_w=r=>$e(r&&$e.convert(r),r,hc);pr.isPathValid=_w;pr.default=pr;yc.exports=pr;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,"/");$e.convert=r;let e=/^[a-z]:\//i;$e.isNotRelative=t=>e.test(t)||gc(t)}});(function(){Fi().config(Object.assign({},ji(),Gi()(process.argv)))})();var yu=require("fs"),wu=require("path");var hu=T(vt());var ue=T(require("fs")),qn=T(require("path")),Nl=T(require("os")),Dl=T(In());var hy=process.stdout.isTTY===!0&&!process.env.NO_COLOR,xe=r=>hy?r:"",S=xe("\x1B[32m"),P=xe("\x1B[33m"),C=xe("\x1B[36m"),ae=xe("\x1B[35m"),h=xe("\x1B[31m"),g=xe("\x1B[2m"),Z=xe("\x1B[1m"),m=xe("\x1B[0m");var Al="app.boxel.realms";var gy={"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"},$$=Object.keys(gy);function k(r){return r.endsWith("/")?r:`${r}/`}async function Ll(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 yy(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 Nn(r,e){let t=await yy(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 Dn(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 Fn(r){return new URL(`_matrix/client/v3/user/${encodeURIComponent(r.userId)}/account_data/${Al}`,r.matrixUrl).href}async function tr(r){try{let e=await fetch(Fn(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 Ml(r,e){let t=await tr(r);if(!t.includes(e)){t.push(e);let n=await fetch(Fn(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 Il(r,e){let t=k(e),n=await tr(r),i=n.filter(o=>k(o)!==t);if(i.length===n.length)return!1;let s=await fetch(Fn(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 wy=qn.join(Nl.homedir(),".boxel-cli"),Ey="profiles.json",Ry=86400;function $y(r,e=Ry){let t=r.replace(/^Bearer\s+/i,""),n=Dl.default.decode(t);if(!n?.exp)return!0;let i=Math.floor(Date.now()/1e3);return n.exp-i<e}var L="No active profile. Run `boxel profile add` to create one.";function rr(r){return r.endsWith(":stack.cards")?"staging":r.endsWith(":boxel.ai")?"production":r.endsWith(":localhost")?"local":"unknown"}function Be(r){let e=r.match(/^@([^:]+):/);return e?e[1]:r}function nr(r){let e=r.match(/:([^:]+)$/);return e?e[1]:"unknown"}function he(r){let e=Be(r),t=nr(r);return`${g}[${m}${C}${e}${m} ${g}\xB7${m} ${ae}${t}${m}${g}]${m}`}var jn=class{config;configDir;profilesFile;constructor(e){this.configDir=e||wy,this.profilesFile=qn.join(this.configDir,Ey),this.config=this.loadConfig()}ensureConfigDir(){ue.existsSync(this.configDir)||ue.mkdirSync(this.configDir,{recursive:!0})}loadConfig(){let e={profiles:{},activeProfile:null};if(ue.existsSync(this.profilesFile))try{let t=ue.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(),ue.writeFileSync(this.profilesFile,JSON.stringify(this.config,null,2),{mode:384});try{ue.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=rr(e),a=Be(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",c=o==="production"?"https://app.boxel.ai/":"https://realms-staging.stack.cards/",u=nr(e),f={displayName:n||`${a} \xB7 ${u}`,matrixUrl:i||l,realmServerUrl:s||c,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:Be(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=Be(t);return Ll(n.matrixUrl,i,n.password)}async getOrRefreshServerToken(){let e=this.getRealmServerToken();if(e&&!$y(e))return e;let t=await this.loginToMatrix(),i=this.getActiveProfile().profile.realmServerUrl.replace(/\/$/,""),s=await Nn(t,i);return this.setRealmServerToken(s),s}async refreshServerToken(){let e=await this.loginToMatrix(),n=this.getActiveProfile().profile.realmServerUrl.replace(/\/$/,""),i=await Nn(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 Dn(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),c=await fetch(e,{...t,headers:l});if(c.status!==401)return c}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 Dn(i,t))[e];return o&&this.setRealmToken(e,o),o}async addToUserRealms(e){let t=await this.loginToMatrix();await Ml(t,e)}async removeFromUserRealms(e){let t=await this.loginToMatrix();return Il(t,e)}async getUserRealms(){let e=await this.loginToMatrix();return tr(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".`,Ze="secret must be a string or buffer",De="key must be a string or a buffer",$f="key must be a string, a buffer or an object",Kr=typeof ie.createPublicKey=="function";Kr&&(De+=" or a KeyObject",Ze+="or a KeyObject");function ys(r){if(!Ue.isBuffer(r)&&typeof r!="string"&&(!Kr||typeof r!="object"||typeof r.type!="string"||typeof r.asymmetricKeyType!="string"||typeof r.export!="function"))throw ce(De)}function ws(r){if(!Ue.isBuffer(r)&&typeof r!="string"&&typeof r!="object")throw ce($f)}function Sf(r){if(!Ue.isBuffer(r)){if(typeof r=="string")return r;if(!Kr||typeof r!="object"||r.type!=="secret"||typeof r.export!="function")throw ce(Ze)}}function Qr(r){return r.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function Es(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 ce(r){var e=[].slice.call(arguments,1),t=hs.format.bind(hs,r).apply(null,e);return new TypeError(t)}function vf(r){return Ue.isBuffer(r)||typeof r=="string"}function et(r){return vf(r)||(r=JSON.stringify(r)),r}function bs(r){return function(t,n){Sf(n),t=et(t);var i=ie.createHmac("sha"+r,n),s=(i.update(t),i.digest("base64"));return Qr(s)}}var Xr,xf="timingSafeEqual"in ie?function(e,t){return e.byteLength!==t.byteLength?!1:ie.timingSafeEqual(e,t)}:function(e,t){return Xr||(Xr=ps()),Xr(e,t)};function kf(r){return function(t,n,i){var s=bs(r)(t,i);return xf(Ue.from(n),Ue.from(s))}}function Rs(r){return function(t,n){ws(n),t=et(t);var i=ie.createSign("RSA-SHA"+r),s=(i.update(t),i.sign(n,"base64"));return Qr(s)}}function $s(r){return function(t,n,i){ys(i),t=et(t),n=Es(n);var s=ie.createVerify("RSA-SHA"+r);return s.update(t),s.verify(i,n,"base64")}}function _f(r){return function(t,n){ws(n),t=et(t);var i=ie.createSign("RSA-SHA"+r),s=(i.update(t),i.sign({key:n,padding:ie.constants.RSA_PKCS1_PSS_PADDING,saltLength:ie.constants.RSA_PSS_SALTLEN_DIGEST},"base64"));return Qr(s)}}function Cf(r){return function(t,n,i){ys(i),t=et(t),n=Es(n);var s=ie.createVerify("RSA-SHA"+r);return s.update(t),s.verify({key:i,padding:ie.constants.RSA_PKCS1_PSS_PADDING,saltLength:ie.constants.RSA_PSS_SALTLEN_DIGEST},n,"base64")}}function Of(r){var e=Rs(r);return function(){var n=e.apply(null,arguments);return n=gs.derToJose(n,"ES"+r),n}}function Pf(r){var e=$s(r);return function(n,i,s){i=gs.joseToDer(i,"ES"+r).toString("base64");var o=e(n,i,s);return o}}function Tf(){return function(){return""}}function Af(){return function(e,t){return t===""}}Ss.exports=function(e){var t={hs:bs,rs:Rs,ps:_f,es:Of,none:Tf},n={hs:kf,rs:$s,ps:Cf,es:Pf,none:Af},i=e.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);if(!i)throw ce(Rf,e);var s=(i[1]||i[3]).toLowerCase(),o=i[2];return{sign:t[s](o),verify:n[s](o)}}});var en=w((yb,vs)=>{var Lf=require("buffer").Buffer;vs.exports=function(e){return typeof e=="string"?e:typeof e=="number"||Lf.isBuffer(e)?e.toString():JSON.stringify(e)}});var Ps=w((wb,Os)=>{var Mf=Fe().Buffer,xs=Yr(),If=Zr(),Nf=require("stream"),ks=en(),tn=require("util");function _s(r,e){return Mf.from(r,e).toString("base64").replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function Ff(r,e,t){t=t||"utf8";var n=_s(ks(r),"binary"),i=_s(ks(e),t);return tn.format("%s.%s",n,i)}function Cs(r){var e=r.header,t=r.payload,n=r.secret||r.privateKey,i=r.encoding,s=If(e.alg),o=Ff(e,t,i),a=s.sign(o,n);return tn.format("%s.%s",o,a)}function At(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 xs(e);this.readable=!0,this.header=r.header,this.encoding=r.encoding,this.secret=this.privateKey=this.key=t,this.payload=new xs(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))}tn.inherits(At,Nf);At.prototype.sign=function(){try{var e=Cs({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")}};At.sign=Cs;Os.exports=At});var js=w((Eb,Us)=>{var As=Fe().Buffer,Ts=Yr(),Df=Zr(),Uf=require("stream"),Ls=en(),jf=require("util"),qf=/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;function Gf(r){return Object.prototype.toString.call(r)==="[object Object]"}function Hf(r){if(Gf(r))return r;try{return JSON.parse(r)}catch{return}}function Ms(r){var e=r.split(".",1)[0];return Hf(As.from(e,"base64").toString("binary"))}function Wf(r){return r.split(".",2).join(".")}function Is(r){return r.split(".")[2]}function Vf(r,e){e=e||"utf8";var t=r.split(".")[1];return As.from(t,"base64").toString(e)}function Ns(r){return qf.test(r)&&!!Ms(r)}function Fs(r,e,t){if(!e){var n=new Error("Missing algorithm parameter for jws.verify");throw n.code="MISSING_ALGORITHM",n}r=Ls(r);var i=Is(r),s=Wf(r),o=Df(e);return o.verify(s,i,t)}function Ds(r,e){if(e=e||{},r=Ls(r),!Ns(r))return null;var t=Ms(r);if(!t)return null;var n=Vf(r);return(t.typ==="JWT"||e.json)&&(n=JSON.parse(n,e.encoding)),{header:t,payload:n,signature:Is(r)}}function je(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 Ts(e);this.readable=!0,this.algorithm=r.algorithm,this.encoding=r.encoding,this.secret=this.publicKey=this.key=t,this.signature=new Ts(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))}jf.inherits(je,Uf);je.prototype.verify=function(){try{var e=Fs(this.signature.buffer,this.algorithm,this.key.buffer),t=Ds(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")}};je.decode=Ds;je.isValid=Ns;je.verify=Fs;Us.exports=je});var Mt=w($e=>{var qs=Ps(),Lt=js(),Bf=["HS256","HS384","HS512","RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512"];$e.ALGORITHMS=Bf;$e.sign=qs.sign;$e.verify=Lt.verify;$e.decode=Lt.decode;$e.isValid=Lt.isValid;$e.createSign=function(e){return new qs(e)};$e.createVerify=function(e){return new Lt(e)}});var rn=w((Rb,Gs)=>{var Yf=Mt();Gs.exports=function(r,e){e=e||{};var t=Yf.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 tt=w(($b,Hs)=>{var It=function(r,e){Error.call(this,r),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor),this.name="JsonWebTokenError",this.message=r,e&&(this.inner=e)};It.prototype=Object.create(Error.prototype);It.prototype.constructor=It;Hs.exports=It});var nn=w((Sb,Vs)=>{var Ws=tt(),Nt=function(r,e){Ws.call(this,r),this.name="NotBeforeError",this.date=e};Nt.prototype=Object.create(Ws.prototype);Nt.prototype.constructor=Nt;Vs.exports=Nt});var sn=w((vb,Ys)=>{var Bs=tt(),Ft=function(r,e){Bs.call(this,r),this.name="TokenExpiredError",this.expiredAt=e};Ft.prototype=Object.create(Bs.prototype);Ft.prototype.constructor=Ft;Ys.exports=Ft});var zs=w((xb,Js)=>{var qe=1e3,Ge=qe*60,He=Ge*60,Te=He*24,Jf=Te*7,zf=Te*365.25;Js.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return Xf(r);if(t==="number"&&isFinite(r))return e.long?Qf(r):Kf(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function Xf(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*zf;case"weeks":case"week":case"w":return t*Jf;case"days":case"day":case"d":return t*Te;case"hours":case"hour":case"hrs":case"hr":case"h":return t*He;case"minutes":case"minute":case"mins":case"min":case"m":return t*Ge;case"seconds":case"second":case"secs":case"sec":case"s":return t*qe;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function Kf(r){var e=Math.abs(r);return e>=Te?Math.round(r/Te)+"d":e>=He?Math.round(r/He)+"h":e>=Ge?Math.round(r/Ge)+"m":e>=qe?Math.round(r/qe)+"s":r+"ms"}function Qf(r){var e=Math.abs(r);return e>=Te?Dt(r,e,Te,"day"):e>=He?Dt(r,e,He,"hour"):e>=Ge?Dt(r,e,Ge,"minute"):e>=qe?Dt(r,e,qe,"second"):r+" ms"}function Dt(r,e,t,n){var i=e>=t*1.5;return Math.round(r/t)+" "+n+(i?"s":"")}});var on=w((kb,Xs)=>{var Zf=zs();Xs.exports=function(r,e){var t=e||Math.floor(Date.now()/1e3);if(typeof r=="string"){var n=Zf(r);return typeof n>"u"?void 0:Math.floor(t+n/1e3)}else return typeof r=="number"?t+r:void 0}});var We=w((_b,Ks)=>{"use strict";var em="2.0.0",tm=Number.MAX_SAFE_INTEGER||9007199254740991,rm=16,nm=250,im=["major","premajor","minor","preminor","patch","prepatch","prerelease"];Ks.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:rm,MAX_SAFE_BUILD_LENGTH:nm,MAX_SAFE_INTEGER:tm,RELEASE_TYPES:im,SEMVER_SPEC_VERSION:em,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var rt=w((Cb,Qs)=>{"use strict";var sm=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...r)=>console.error("SEMVER",...r):()=>{};Qs.exports=sm});var Ve=w((pe,Zs)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:an,MAX_SAFE_BUILD_LENGTH:om,MAX_LENGTH:am}=We(),lm=rt();pe=Zs.exports={};var cm=pe.re=[],um=pe.safeRe=[],E=pe.src=[],fm=pe.safeSrc=[],b=pe.t={},mm=0,ln="[a-zA-Z0-9-]",dm=[["\\s",1],["\\d",am],[ln,om]],pm=r=>{for(let[e,t]of dm)r=r.split(`${e}*`).join(`${e}{0,${t}}`).split(`${e}+`).join(`${e}{1,${t}}`);return r},k=(r,e,t)=>{let n=pm(e),i=mm++;lm(r,i,e),b[r]=i,E[i]=e,fm[i]=n,cm[i]=new RegExp(e,t?"g":void 0),um[i]=new RegExp(n,t?"g":void 0)};k("NUMERICIDENTIFIER","0|[1-9]\\d*");k("NUMERICIDENTIFIERLOOSE","\\d+");k("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${ln}*`);k("MAINVERSION",`(${E[b.NUMERICIDENTIFIER]})\\.(${E[b.NUMERICIDENTIFIER]})\\.(${E[b.NUMERICIDENTIFIER]})`);k("MAINVERSIONLOOSE",`(${E[b.NUMERICIDENTIFIERLOOSE]})\\.(${E[b.NUMERICIDENTIFIERLOOSE]})\\.(${E[b.NUMERICIDENTIFIERLOOSE]})`);k("PRERELEASEIDENTIFIER",`(?:${E[b.NONNUMERICIDENTIFIER]}|${E[b.NUMERICIDENTIFIER]})`);k("PRERELEASEIDENTIFIERLOOSE",`(?:${E[b.NONNUMERICIDENTIFIER]}|${E[b.NUMERICIDENTIFIERLOOSE]})`);k("PRERELEASE",`(?:-(${E[b.PRERELEASEIDENTIFIER]}(?:\\.${E[b.PRERELEASEIDENTIFIER]})*))`);k("PRERELEASELOOSE",`(?:-?(${E[b.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${E[b.PRERELEASEIDENTIFIERLOOSE]})*))`);k("BUILDIDENTIFIER",`${ln}+`);k("BUILD",`(?:\\+(${E[b.BUILDIDENTIFIER]}(?:\\.${E[b.BUILDIDENTIFIER]})*))`);k("FULLPLAIN",`v?${E[b.MAINVERSION]}${E[b.PRERELEASE]}?${E[b.BUILD]}?`);k("FULL",`^${E[b.FULLPLAIN]}$`);k("LOOSEPLAIN",`[v=\\s]*${E[b.MAINVERSIONLOOSE]}${E[b.PRERELEASELOOSE]}?${E[b.BUILD]}?`);k("LOOSE",`^${E[b.LOOSEPLAIN]}$`);k("GTLT","((?:<|>)?=?)");k("XRANGEIDENTIFIERLOOSE",`${E[b.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);k("XRANGEIDENTIFIER",`${E[b.NUMERICIDENTIFIER]}|x|X|\\*`);k("XRANGEPLAIN",`[v=\\s]*(${E[b.XRANGEIDENTIFIER]})(?:\\.(${E[b.XRANGEIDENTIFIER]})(?:\\.(${E[b.XRANGEIDENTIFIER]})(?:${E[b.PRERELEASE]})?${E[b.BUILD]}?)?)?`);k("XRANGEPLAINLOOSE",`[v=\\s]*(${E[b.XRANGEIDENTIFIERLOOSE]})(?:\\.(${E[b.XRANGEIDENTIFIERLOOSE]})(?:\\.(${E[b.XRANGEIDENTIFIERLOOSE]})(?:${E[b.PRERELEASELOOSE]})?${E[b.BUILD]}?)?)?`);k("XRANGE",`^${E[b.GTLT]}\\s*${E[b.XRANGEPLAIN]}$`);k("XRANGELOOSE",`^${E[b.GTLT]}\\s*${E[b.XRANGEPLAINLOOSE]}$`);k("COERCEPLAIN",`(^|[^\\d])(\\d{1,${an}})(?:\\.(\\d{1,${an}}))?(?:\\.(\\d{1,${an}}))?`);k("COERCE",`${E[b.COERCEPLAIN]}(?:$|[^\\d])`);k("COERCEFULL",E[b.COERCEPLAIN]+`(?:${E[b.PRERELEASE]})?(?:${E[b.BUILD]})?(?:$|[^\\d])`);k("COERCERTL",E[b.COERCE],!0);k("COERCERTLFULL",E[b.COERCEFULL],!0);k("LONETILDE","(?:~>?)");k("TILDETRIM",`(\\s*)${E[b.LONETILDE]}\\s+`,!0);pe.tildeTrimReplace="$1~";k("TILDE",`^${E[b.LONETILDE]}${E[b.XRANGEPLAIN]}$`);k("TILDELOOSE",`^${E[b.LONETILDE]}${E[b.XRANGEPLAINLOOSE]}$`);k("LONECARET","(?:\\^)");k("CARETTRIM",`(\\s*)${E[b.LONECARET]}\\s+`,!0);pe.caretTrimReplace="$1^";k("CARET",`^${E[b.LONECARET]}${E[b.XRANGEPLAIN]}$`);k("CARETLOOSE",`^${E[b.LONECARET]}${E[b.XRANGEPLAINLOOSE]}$`);k("COMPARATORLOOSE",`^${E[b.GTLT]}\\s*(${E[b.LOOSEPLAIN]})$|^$`);k("COMPARATOR",`^${E[b.GTLT]}\\s*(${E[b.FULLPLAIN]})$|^$`);k("COMPARATORTRIM",`(\\s*)${E[b.GTLT]}\\s*(${E[b.LOOSEPLAIN]}|${E[b.XRANGEPLAIN]})`,!0);pe.comparatorTrimReplace="$1$2$3";k("HYPHENRANGE",`^\\s*(${E[b.XRANGEPLAIN]})\\s+-\\s+(${E[b.XRANGEPLAIN]})\\s*$`);k("HYPHENRANGELOOSE",`^\\s*(${E[b.XRANGEPLAINLOOSE]})\\s+-\\s+(${E[b.XRANGEPLAINLOOSE]})\\s*$`);k("STAR","(<|>)?=?\\s*\\*");k("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");k("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var Ut=w((Ob,eo)=>{"use strict";var hm=Object.freeze({loose:!0}),gm=Object.freeze({}),ym=r=>r?typeof r!="object"?hm:r:gm;eo.exports=ym});var cn=w((Pb,no)=>{"use strict";var to=/^[0-9]+$/,ro=(r,e)=>{if(typeof r=="number"&&typeof e=="number")return r===e?0:r<e?-1:1;let t=to.test(r),n=to.test(e);return t&&n&&(r=+r,e=+e),r===e?0:t&&!n?-1:n&&!t?1:r<e?-1:1},wm=(r,e)=>ro(e,r);no.exports={compareIdentifiers:ro,rcompareIdentifiers:wm}});var Y=w((Tb,so)=>{"use strict";var jt=rt(),{MAX_LENGTH:io,MAX_SAFE_INTEGER:qt}=We(),{safeRe:Gt,t:Ht}=Ve(),Em=Ut(),{compareIdentifiers:un}=cn(),fn=class r{constructor(e,t){if(t=Em(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>io)throw new TypeError(`version is longer than ${io} characters`);jt("SemVer",e,t),this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease;let n=e.trim().match(t.loose?Gt[Ht.LOOSE]:Gt[Ht.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>qt||this.major<0)throw new TypeError("Invalid major version");if(this.minor>qt||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>qt||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<qt)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(jt("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(jt("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 un(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(jt("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 un(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?Gt[Ht.PRERELEASELOOSE]:Gt[Ht.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]),un(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}};so.exports=fn});var Se=w((Ab,ao)=>{"use strict";var oo=Y(),bm=(r,e,t=!1)=>{if(r instanceof oo)return r;try{return new oo(r,e)}catch(n){if(!t)return null;throw n}};ao.exports=bm});var co=w((Lb,lo)=>{"use strict";var Rm=Se(),$m=(r,e)=>{let t=Rm(r,e);return t?t.version:null};lo.exports=$m});var fo=w((Mb,uo)=>{"use strict";var Sm=Se(),vm=(r,e)=>{let t=Sm(r.trim().replace(/^[=v]+/,""),e);return t?t.version:null};uo.exports=vm});var ho=w((Ib,po)=>{"use strict";var mo=Y(),xm=(r,e,t,n,i)=>{typeof t=="string"&&(i=n,n=t,t=void 0);try{return new mo(r instanceof mo?r.version:r,t).inc(e,n,i).version}catch{return null}};po.exports=xm});var wo=w((Nb,yo)=>{"use strict";var go=Se(),km=(r,e)=>{let t=go(r,null,!0),n=go(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 u=l?"pre":"";return t.major!==n.major?u+"major":t.minor!==n.minor?u+"minor":t.patch!==n.patch?u+"patch":"prerelease"};yo.exports=km});var bo=w((Fb,Eo)=>{"use strict";var _m=Y(),Cm=(r,e)=>new _m(r,e).major;Eo.exports=Cm});var $o=w((Db,Ro)=>{"use strict";var Om=Y(),Pm=(r,e)=>new Om(r,e).minor;Ro.exports=Pm});var vo=w((Ub,So)=>{"use strict";var Tm=Y(),Am=(r,e)=>new Tm(r,e).patch;So.exports=Am});var ko=w((jb,xo)=>{"use strict";var Lm=Se(),Mm=(r,e)=>{let t=Lm(r,e);return t&&t.prerelease.length?t.prerelease:null};xo.exports=Mm});var se=w((qb,Co)=>{"use strict";var _o=Y(),Im=(r,e,t)=>new _o(r,t).compare(new _o(e,t));Co.exports=Im});var Po=w((Gb,Oo)=>{"use strict";var Nm=se(),Fm=(r,e,t)=>Nm(e,r,t);Oo.exports=Fm});var Ao=w((Hb,To)=>{"use strict";var Dm=se(),Um=(r,e)=>Dm(r,e,!0);To.exports=Um});var Wt=w((Wb,Mo)=>{"use strict";var Lo=Y(),jm=(r,e,t)=>{let n=new Lo(r,t),i=new Lo(e,t);return n.compare(i)||n.compareBuild(i)};Mo.exports=jm});var No=w((Vb,Io)=>{"use strict";var qm=Wt(),Gm=(r,e)=>r.sort((t,n)=>qm(t,n,e));Io.exports=Gm});var Do=w((Bb,Fo)=>{"use strict";var Hm=Wt(),Wm=(r,e)=>r.sort((t,n)=>Hm(n,t,e));Fo.exports=Wm});var nt=w((Yb,Uo)=>{"use strict";var Vm=se(),Bm=(r,e,t)=>Vm(r,e,t)>0;Uo.exports=Bm});var Vt=w((Jb,jo)=>{"use strict";var Ym=se(),Jm=(r,e,t)=>Ym(r,e,t)<0;jo.exports=Jm});var mn=w((zb,qo)=>{"use strict";var zm=se(),Xm=(r,e,t)=>zm(r,e,t)===0;qo.exports=Xm});var dn=w((Xb,Go)=>{"use strict";var Km=se(),Qm=(r,e,t)=>Km(r,e,t)!==0;Go.exports=Qm});var Bt=w((Kb,Ho)=>{"use strict";var Zm=se(),ed=(r,e,t)=>Zm(r,e,t)>=0;Ho.exports=ed});var Yt=w((Qb,Wo)=>{"use strict";var td=se(),rd=(r,e,t)=>td(r,e,t)<=0;Wo.exports=rd});var pn=w((Zb,Vo)=>{"use strict";var nd=mn(),id=dn(),sd=nt(),od=Bt(),ad=Vt(),ld=Yt(),cd=(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 nd(r,t,n);case"!=":return id(r,t,n);case">":return sd(r,t,n);case">=":return od(r,t,n);case"<":return ad(r,t,n);case"<=":return ld(r,t,n);default:throw new TypeError(`Invalid operator: ${e}`)}};Vo.exports=cd});var Yo=w((eR,Bo)=>{"use strict";var ud=Y(),fd=Se(),{safeRe:Jt,t:zt}=Ve(),md=(r,e)=>{if(r instanceof ud)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?Jt[zt.COERCEFULL]:Jt[zt.COERCE]);else{let l=e.includePrerelease?Jt[zt.COERCERTLFULL]:Jt[zt.COERCERTL],c;for(;(c=l.exec(r))&&(!t||t.index+t[0].length!==r.length);)(!t||c.index+c[0].length!==t.index+t[0].length)&&(t=c),l.lastIndex=c.index+c[1].length+c[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 fd(`${n}.${i}.${s}${o}${a}`,e)};Bo.exports=md});var zo=w((tR,Jo)=>{"use strict";var dd=Se(),pd=We(),hd=Y(),gd=(r,e,t)=>{if(!pd.RELEASE_TYPES.includes(e))return null;let n=yd(r,t);return n&&wd(n,e)},yd=(r,e)=>{let t=r instanceof hd?r.version:r;return dd(t,e)},wd=(r,e)=>{if(Ed(e))return r.version;switch(r.prerelease=[],e){case"major":r.minor=0,r.patch=0;break;case"minor":r.patch=0;break}return r.format()},Ed=r=>r.startsWith("pre");Jo.exports=gd});var Ko=w((rR,Xo)=>{"use strict";var hn=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}};Xo.exports=hn});var oe=w((nR,ta)=>{"use strict";var bd=/\s+/g,gn=class r{constructor(e,t){if(t=$d(t),e instanceof r)return e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease?e:new r(e.raw,t);if(e instanceof yn)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(bd," "),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=>!Zo(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&&Od(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&&_d)|(this.options.loose&&Cd))+":"+e,i=Qo.get(n);if(i)return i;let s=this.options.loose,o=s?K[z.HYPHENRANGELOOSE]:K[z.HYPHENRANGE];e=e.replace(o,Ud(this.options.includePrerelease)),F("hyphen replace",e),e=e.replace(K[z.COMPARATORTRIM],vd),F("comparator trim",e),e=e.replace(K[z.TILDETRIM],xd),F("tilde trim",e),e=e.replace(K[z.CARETTRIM],kd),F("caret trim",e);let a=e.split(" ").map(f=>Pd(f,this.options)).join(" ").split(/\s+/).map(f=>Dd(f,this.options));s&&(a=a.filter(f=>(F("loose invalid filter",f,this.options),!!f.match(K[z.COMPARATORLOOSE])))),F("range list",a);let l=new Map,c=a.map(f=>new yn(f,this.options));for(let f of c){if(Zo(f))return[f];l.set(f.value,f)}l.size>1&&l.has("")&&l.delete("");let u=[...l.values()];return Qo.set(n,u),u}intersects(e,t){if(!(e instanceof r))throw new TypeError("a Range is required");return this.set.some(n=>ea(n,t)&&e.set.some(i=>ea(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 Sd(e,this.options)}catch{return!1}for(let t=0;t<this.set.length;t++)if(jd(this.set[t],e,this.options))return!0;return!1}};ta.exports=gn;var Rd=Ko(),Qo=new Rd,$d=Ut(),yn=it(),F=rt(),Sd=Y(),{safeRe:K,t:z,comparatorTrimReplace:vd,tildeTrimReplace:xd,caretTrimReplace:kd}=Ve(),{FLAG_INCLUDE_PRERELEASE:_d,FLAG_LOOSE:Cd}=We(),Zo=r=>r.value==="<0.0.0-0",Od=r=>r.value==="",ea=(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},Pd=(r,e)=>(r=r.replace(K[z.BUILD],""),F("comp",r,e),r=Ld(r,e),F("caret",r),r=Td(r,e),F("tildes",r),r=Id(r,e),F("xrange",r),r=Fd(r,e),F("stars",r),r),Q=r=>!r||r.toLowerCase()==="x"||r==="*",Td=(r,e)=>r.trim().split(/\s+/).map(t=>Ad(t,e)).join(" "),Ad=(r,e)=>{let t=e.loose?K[z.TILDELOOSE]:K[z.TILDE];return r.replace(t,(n,i,s,o,a)=>{F("tilde",r,n,i,s,o,a);let l;return Q(i)?l="":Q(s)?l=`>=${i}.0.0 <${+i+1}.0.0-0`:Q(o)?l=`>=${i}.${s}.0 <${i}.${+s+1}.0-0`:a?(F("replaceTilde pr",a),l=`>=${i}.${s}.${o}-${a} <${i}.${+s+1}.0-0`):l=`>=${i}.${s}.${o} <${i}.${+s+1}.0-0`,F("tilde return",l),l})},Ld=(r,e)=>r.trim().split(/\s+/).map(t=>Md(t,e)).join(" "),Md=(r,e)=>{F("caret",r,e);let t=e.loose?K[z.CARETLOOSE]:K[z.CARET],n=e.includePrerelease?"-0":"";return r.replace(t,(i,s,o,a,l)=>{F("caret",r,i,s,o,a,l);let c;return Q(s)?c="":Q(o)?c=`>=${s}.0.0${n} <${+s+1}.0.0-0`:Q(a)?s==="0"?c=`>=${s}.${o}.0${n} <${s}.${+o+1}.0-0`:c=`>=${s}.${o}.0${n} <${+s+1}.0.0-0`:l?(F("replaceCaret pr",l),s==="0"?o==="0"?c=`>=${s}.${o}.${a}-${l} <${s}.${o}.${+a+1}-0`:c=`>=${s}.${o}.${a}-${l} <${s}.${+o+1}.0-0`:c=`>=${s}.${o}.${a}-${l} <${+s+1}.0.0-0`):(F("no pr"),s==="0"?o==="0"?c=`>=${s}.${o}.${a}${n} <${s}.${o}.${+a+1}-0`:c=`>=${s}.${o}.${a}${n} <${s}.${+o+1}.0-0`:c=`>=${s}.${o}.${a} <${+s+1}.0.0-0`),F("caret return",c),c})},Id=(r,e)=>(F("replaceXRanges",r,e),r.split(/\s+/).map(t=>Nd(t,e)).join(" ")),Nd=(r,e)=>{r=r.trim();let t=e.loose?K[z.XRANGELOOSE]:K[z.XRANGE];return r.replace(t,(n,i,s,o,a,l)=>{F("xRange",r,n,i,s,o,a,l);let c=Q(s),u=c||Q(o),f=u||Q(a),d=f;return i==="="&&d&&(i=""),l=e.includePrerelease?"-0":"",c?i===">"||i==="<"?n="<0.0.0-0":n="*":i&&d?(u&&(o=0),a=0,i===">"?(i=">=",u?(s=+s+1,o=0,a=0):(o=+o+1,a=0)):i==="<="&&(i="<",u?s=+s+1:o=+o+1),i==="<"&&(l="-0"),n=`${i+s}.${o}.${a}${l}`):u?n=`>=${s}.0.0${l} <${+s+1}.0.0-0`:f&&(n=`>=${s}.${o}.0${l} <${s}.${+o+1}.0-0`),F("xRange return",n),n})},Fd=(r,e)=>(F("replaceStars",r,e),r.trim().replace(K[z.STAR],"")),Dd=(r,e)=>(F("replaceGTE0",r,e),r.trim().replace(K[e.includePrerelease?z.GTE0PRE:z.GTE0],"")),Ud=r=>(e,t,n,i,s,o,a,l,c,u,f,d)=>(Q(n)?t="":Q(i)?t=`>=${n}.0.0${r?"-0":""}`:Q(s)?t=`>=${n}.${i}.0${r?"-0":""}`:o?t=`>=${t}`:t=`>=${t}${r?"-0":""}`,Q(c)?l="":Q(u)?l=`<${+c+1}.0.0-0`:Q(f)?l=`<${c}.${+u+1}.0-0`:d?l=`<=${c}.${u}.${f}-${d}`:r?l=`<${c}.${u}.${+f+1}-0`:l=`<=${l}`,`${t} ${l}`.trim()),jd=(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(F(r[n].semver),r[n].semver!==yn.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 it=w((iR,aa)=>{"use strict";var st=Symbol("SemVer ANY"),bn=class r{static get ANY(){return st}constructor(e,t){if(t=ra(t),e instanceof r){if(e.loose===!!t.loose)return e;e=e.value}e=e.trim().split(/\s+/).join(" "),En("comparator",e,t),this.options=t,this.loose=!!t.loose,this.parse(e),this.semver===st?this.value="":this.value=this.operator+this.semver.version,En("comp",this)}parse(e){let t=this.options.loose?na[ia.COMPARATORLOOSE]:na[ia.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 sa(n[2],this.options.loose):this.semver=st}toString(){return this.value}test(e){if(En("Comparator.test",e,this.options.loose),this.semver===st||e===st)return!0;if(typeof e=="string")try{e=new sa(e,this.options)}catch{return!1}return wn(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 oa(e.value,t).test(this.value):e.operator===""?e.value===""?!0:new oa(this.value,t).test(e.semver):(t=ra(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("=")||wn(this.semver,"<",e.semver,t)&&this.operator.startsWith(">")&&e.operator.startsWith("<")||wn(this.semver,">",e.semver,t)&&this.operator.startsWith("<")&&e.operator.startsWith(">")))}};aa.exports=bn;var ra=Ut(),{safeRe:na,t:ia}=Ve(),wn=pn(),En=rt(),sa=Y(),oa=oe()});var ot=w((sR,la)=>{"use strict";var qd=oe(),Gd=(r,e,t)=>{try{e=new qd(e,t)}catch{return!1}return e.test(r)};la.exports=Gd});var ua=w((oR,ca)=>{"use strict";var Hd=oe(),Wd=(r,e)=>new Hd(r,e).set.map(t=>t.map(n=>n.value).join(" ").trim().split(" "));ca.exports=Wd});var ma=w((aR,fa)=>{"use strict";var Vd=Y(),Bd=oe(),Yd=(r,e,t)=>{let n=null,i=null,s=null;try{s=new Bd(e,t)}catch{return null}return r.forEach(o=>{s.test(o)&&(!n||i.compare(o)===-1)&&(n=o,i=new Vd(n,t))}),n};fa.exports=Yd});var pa=w((lR,da)=>{"use strict";var Jd=Y(),zd=oe(),Xd=(r,e,t)=>{let n=null,i=null,s=null;try{s=new zd(e,t)}catch{return null}return r.forEach(o=>{s.test(o)&&(!n||i.compare(o)===1)&&(n=o,i=new Jd(n,t))}),n};da.exports=Xd});var ya=w((cR,ga)=>{"use strict";var Rn=Y(),Kd=oe(),ha=nt(),Qd=(r,e)=>{r=new Kd(r,e);let t=new Rn("0.0.0");if(r.test(t)||(t=new Rn("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 Rn(o.semver.version);switch(o.operator){case">":a.prerelease.length===0?a.patch++:a.prerelease.push(0),a.raw=a.format();case"":case">=":(!s||ha(a,s))&&(s=a);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${o.operator}`)}}),s&&(!t||ha(t,s))&&(t=s)}return t&&r.test(t)?t:null};ga.exports=Qd});var Ea=w((uR,wa)=>{"use strict";var Zd=oe(),ep=(r,e)=>{try{return new Zd(r,e).range||"*"}catch{return null}};wa.exports=ep});var Xt=w((fR,Sa)=>{"use strict";var tp=Y(),$a=it(),{ANY:rp}=$a,np=oe(),ip=ot(),ba=nt(),Ra=Vt(),sp=Yt(),op=Bt(),ap=(r,e,t,n)=>{r=new tp(r,n),e=new np(e,n);let i,s,o,a,l;switch(t){case">":i=ba,s=sp,o=Ra,a=">",l=">=";break;case"<":i=Ra,s=op,o=ba,a="<",l="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(ip(r,e,n))return!1;for(let c=0;c<e.set.length;++c){let u=e.set[c],f=null,d=null;if(u.forEach(p=>{p.semver===rp&&(p=new $a(">=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};Sa.exports=ap});var xa=w((mR,va)=>{"use strict";var lp=Xt(),cp=(r,e,t)=>lp(r,e,">",t);va.exports=cp});var _a=w((dR,ka)=>{"use strict";var up=Xt(),fp=(r,e,t)=>up(r,e,"<",t);ka.exports=fp});var Pa=w((pR,Oa)=>{"use strict";var Ca=oe(),mp=(r,e,t)=>(r=new Ca(r,t),e=new Ca(e,t),r.intersects(e,t));Oa.exports=mp});var Aa=w((hR,Ta)=>{"use strict";var dp=ot(),pp=se();Ta.exports=(r,e,t)=>{let n=[],i=null,s=null,o=r.sort((u,f)=>pp(u,f,t));for(let u of o)dp(u,e,t)?(s=u,i||(i=u)):(s&&n.push([i,s]),s=null,i=null);i&&n.push([i,null]);let a=[];for(let[u,f]of n)u===f?a.push(u):!f&&u===o[0]?a.push("*"):f?u===o[0]?a.push(`<=${f}`):a.push(`${u} - ${f}`):a.push(`>=${u}`);let l=a.join(" || "),c=typeof e.raw=="string"?e.raw:String(e);return l.length<c.length?l:e}});var Da=w((gR,Fa)=>{"use strict";var La=oe(),Sn=it(),{ANY:$n}=Sn,at=ot(),vn=se(),hp=(r,e,t={})=>{if(r===e)return!0;r=new La(r,t),e=new La(e,t);let n=!1;e:for(let i of r.set){for(let s of e.set){let o=yp(i,s,t);if(n=n||o!==null,o)continue e}if(n)return!1}return!0},gp=[new Sn(">=0.0.0-0")],Ma=[new Sn(">=0.0.0")],yp=(r,e,t)=>{if(r===e)return!0;if(r.length===1&&r[0].semver===$n){if(e.length===1&&e[0].semver===$n)return!0;t.includePrerelease?r=gp:r=Ma}if(e.length===1&&e[0].semver===$n){if(t.includePrerelease)return!0;e=Ma}let n=new Set,i,s;for(let p of r)p.operator===">"||p.operator===">="?i=Ia(i,p,t):p.operator==="<"||p.operator==="<="?s=Na(s,p,t):n.add(p.semver);if(n.size>1)return null;let o;if(i&&s){if(o=vn(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&&!at(p,String(i),t)||s&&!at(p,String(s),t))return null;for(let y of e)if(!at(p,String(y),t))return!1;return!0}let a,l,c,u,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(u=u||p.operator===">"||p.operator===">=",c=c||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=Ia(i,p,t),a===p&&a!==i)return!1}else if(i.operator===">="&&!at(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=Na(s,p,t),l===p&&l!==s)return!1}else if(s.operator==="<="&&!at(s.semver,String(p),t))return!1}if(!p.operator&&(s||i)&&o!==0)return!1}return!(i&&c&&!s&&o!==0||s&&u&&!i&&o!==0||d||f)},Ia=(r,e,t)=>{if(!r)return e;let n=vn(r.semver,e.semver,t);return n>0?r:n<0||e.operator===">"&&r.operator===">="?e:r},Na=(r,e,t)=>{if(!r)return e;let n=vn(r.semver,e.semver,t);return n<0?r:n>0||e.operator==="<"&&r.operator==="<="?e:r};Fa.exports=hp});var Kt=w((yR,qa)=>{"use strict";var xn=Ve(),Ua=We(),wp=Y(),ja=cn(),Ep=Se(),bp=co(),Rp=fo(),$p=ho(),Sp=wo(),vp=bo(),xp=$o(),kp=vo(),_p=ko(),Cp=se(),Op=Po(),Pp=Ao(),Tp=Wt(),Ap=No(),Lp=Do(),Mp=nt(),Ip=Vt(),Np=mn(),Fp=dn(),Dp=Bt(),Up=Yt(),jp=pn(),qp=Yo(),Gp=zo(),Hp=it(),Wp=oe(),Vp=ot(),Bp=ua(),Yp=ma(),Jp=pa(),zp=ya(),Xp=Ea(),Kp=Xt(),Qp=xa(),Zp=_a(),eh=Pa(),th=Aa(),rh=Da();qa.exports={parse:Ep,valid:bp,clean:Rp,inc:$p,diff:Sp,major:vp,minor:xp,patch:kp,prerelease:_p,compare:Cp,rcompare:Op,compareLoose:Pp,compareBuild:Tp,sort:Ap,rsort:Lp,gt:Mp,lt:Ip,eq:Np,neq:Fp,gte:Dp,lte:Up,cmp:jp,coerce:qp,truncate:Gp,Comparator:Hp,Range:Wp,satisfies:Vp,toComparators:Bp,maxSatisfying:Yp,minSatisfying:Jp,minVersion:zp,validRange:Xp,outside:Kp,gtr:Qp,ltr:Zp,intersects:eh,simplifyRange:th,subset:rh,SemVer:wp,re:xn.re,src:xn.src,tokens:xn.t,SEMVER_SPEC_VERSION:Ua.SEMVER_SPEC_VERSION,RELEASE_TYPES:Ua.RELEASE_TYPES,compareIdentifiers:ja.compareIdentifiers,rcompareIdentifiers:ja.rcompareIdentifiers}});var Ha=w((wR,Ga)=>{var nh=Kt();Ga.exports=nh.satisfies(process.version,">=15.7.0")});var Va=w((ER,Wa)=>{var ih=Kt();Wa.exports=ih.satisfies(process.version,">=16.9.0")});var kn=w((bR,Ba)=>{var sh=Ha(),oh=Va(),ah={ec:["ES256","ES384","ES512"],rsa:["RS256","PS256","RS384","PS384","RS512","PS512"],"rsa-pss":["PS256","PS384","PS512"]},lh={ES256:"prime256v1",ES384:"secp384r1",ES512:"secp521r1"};Ba.exports=function(r,e){if(!r||!e)return;let t=e.asymmetricKeyType;if(!t)return;let n=ah[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(sh)switch(t){case"ec":let i=e.asymmetricKeyDetails.namedCurve,s=lh[r];if(i!==s)throw new Error(`"alg" parameter "${r}" requires curve "${s}".`);break;case"rsa-pss":if(oh){let o=parseInt(r.slice(-3),10),{hashAlgorithm:a,mgf1HashAlgorithm:l,saltLength:c}=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(c!==void 0&&c>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 _n=w((RR,Ya)=>{var ch=Kt();Ya.exports=ch.satisfies(process.version,"^6.12.0 || >=8.0.0")});var Xa=w(($R,za)=>{var N=tt(),uh=nn(),Ja=sn(),fh=rn(),mh=on(),dh=kn(),ph=_n(),hh=Mt(),{KeyObject:gh,createSecretKey:yh,createPublicKey:wh}=require("crypto"),Cn=["RS256","RS384","RS512"],Eh=["ES256","ES384","ES512"],On=["RS256","RS384","RS512"],bh=["HS256","HS384","HS512"];ph&&(Cn.splice(Cn.length,0,"PS256","PS384","PS512"),On.splice(On.length,0,"PS256","PS384","PS512"));za.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(u,f){if(u)throw u;return f},t.clockTimestamp&&typeof t.clockTimestamp!="number")return i(new N("clockTimestamp must be a number"));if(t.nonce!==void 0&&(typeof t.nonce!="string"||t.nonce.trim()===""))return i(new N("nonce must be a non-empty string"));if(t.allowInvalidAsymmetricKeyTypes!==void 0&&typeof t.allowInvalidAsymmetricKeyTypes!="boolean")return i(new N("allowInvalidAsymmetricKeyTypes must be a boolean"));let s=t.clockTimestamp||Math.floor(Date.now()/1e3);if(!r)return i(new N("jwt must be provided"));if(typeof r!="string")return i(new N("jwt must be a string"));let o=r.split(".");if(o.length!==3)return i(new N("jwt malformed"));let a;try{a=fh(r,{complete:!0})}catch(u){return i(u)}if(!a)return i(new N("invalid token"));let l=a.header,c;if(typeof e=="function"){if(!n)return i(new N("verify must be called asynchronous if secret or public key is provided as a callback"));c=e}else c=function(u,f){return f(null,e)};return c(l,function(u,f){if(u)return i(new N("error in secret or public key callback: "+u.message));let d=o[2].trim()!=="";if(!d&&f)return i(new N("jwt signature is required"));if(d&&!f)return i(new N("secret or public key must be provided"));if(!d&&!t.algorithms)return i(new N('please specify "none" in "algorithms" to verify unsigned tokens'));if(f!=null&&!(f instanceof gh))try{f=wh(f)}catch{try{f=yh(typeof f=="string"?Buffer.from(f):f)}catch{return i(new N("secretOrPublicKey is not valid key material"))}}if(t.algorithms||(f.type==="secret"?t.algorithms=bh:["rsa","rsa-pss"].includes(f.asymmetricKeyType)?t.algorithms=On:f.asymmetricKeyType==="ec"?t.algorithms=Eh:t.algorithms=Cn),t.algorithms.indexOf(a.header.alg)===-1)return i(new N("invalid algorithm"));if(l.alg.startsWith("HS")&&f.type!=="secret")return i(new N(`secretOrPublicKey must be a symmetric key when using ${l.alg}`));if(/^(?:RS|PS|ES)/.test(l.alg)&&f.type!=="public")return i(new N(`secretOrPublicKey must be an asymmetric key when using ${l.alg}`));if(!t.allowInvalidAsymmetricKeyTypes)try{dh(l.alg,f)}catch(R){return i(R)}let p;try{p=hh.verify(r,a.header.alg,f)}catch(R){return i(R)}if(!p)return i(new N("invalid signature"));let y=a.payload;if(typeof y.nbf<"u"&&!t.ignoreNotBefore){if(typeof y.nbf!="number")return i(new N("invalid nbf value"));if(y.nbf>s+(t.clockTolerance||0))return i(new uh("jwt not active",new Date(y.nbf*1e3)))}if(typeof y.exp<"u"&&!t.ignoreExpiration){if(typeof y.exp!="number")return i(new N("invalid exp value"));if(s>=y.exp+(t.clockTolerance||0))return i(new Ja("jwt expired",new Date(y.exp*1e3)))}if(t.audience){let R=Array.isArray(t.audience)?t.audience:[t.audience];if(!(Array.isArray(y.aud)?y.aud:[y.aud]).some(function($){return R.some(function(v){return v instanceof RegExp?v.test($):v===$})}))return i(new N("jwt audience invalid. expected: "+R.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 N("jwt issuer invalid. expected: "+t.issuer));if(t.subject&&y.sub!==t.subject)return i(new N("jwt subject invalid. expected: "+t.subject));if(t.jwtid&&y.jti!==t.jwtid)return i(new N("jwt jwtid invalid. expected: "+t.jwtid));if(t.nonce&&y.nonce!==t.nonce)return i(new N("jwt nonce invalid. expected: "+t.nonce));if(t.maxAge){if(typeof y.iat!="number")return i(new N("iat required when maxAge is specified"));let R=mh(t.maxAge,y.iat);if(typeof R>"u")return i(new N('"maxAge" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60'));if(s>=R+(t.clockTolerance||0))return i(new Ja("maxAge exceeded",new Date(R*1e3)))}if(t.complete===!0){let R=a.signature;return i(null,{header:l,payload:y,signature:R})}return i(null,y)})}});var rl=w((SR,tl)=>{var Ka=1/0,Za=9007199254740991,Rh=17976931348623157e292,Qa=NaN,$h="[object Arguments]",Sh="[object Function]",vh="[object GeneratorFunction]",xh="[object String]",kh="[object Symbol]",_h=/^\s+|\s+$/g,Ch=/^[-+]0x[0-9a-f]+$/i,Oh=/^0b[01]+$/i,Ph=/^0o[0-7]+$/i,Th=/^(?:0|[1-9]\d*)$/,Ah=parseInt;function Lh(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 Mh(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 Ih(r,e,t){if(e!==e)return Mh(r,Nh,t);for(var n=t-1,i=r.length;++n<i;)if(r[n]===e)return n;return-1}function Nh(r){return r!==r}function Fh(r,e){for(var t=-1,n=Array(r);++t<r;)n[t]=e(t);return n}function Dh(r,e){return Lh(e,function(t){return r[t]})}function Uh(r,e){return function(t){return r(e(t))}}var Qt=Object.prototype,Tn=Qt.hasOwnProperty,Zt=Qt.toString,jh=Qt.propertyIsEnumerable,qh=Uh(Object.keys,Object),Gh=Math.max;function Hh(r,e){var t=el(r)||Jh(r)?Fh(r.length,String):[],n=t.length,i=!!n;for(var s in r)(e||Tn.call(r,s))&&!(i&&(s=="length"||Vh(s,n)))&&t.push(s);return t}function Wh(r){if(!Bh(r))return qh(r);var e=[];for(var t in Object(r))Tn.call(r,t)&&t!="constructor"&&e.push(t);return e}function Vh(r,e){return e=e??Za,!!e&&(typeof r=="number"||Th.test(r))&&r>-1&&r%1==0&&r<e}function Bh(r){var e=r&&r.constructor,t=typeof e=="function"&&e.prototype||Qt;return r===t}function Yh(r,e,t,n){r=An(r)?r:ig(r),t=t&&!n?tg(t):0;var i=r.length;return t<0&&(t=Gh(i+t,0)),Qh(r)?t<=i&&r.indexOf(e,t)>-1:!!i&&Ih(r,e,t)>-1}function Jh(r){return zh(r)&&Tn.call(r,"callee")&&(!jh.call(r,"callee")||Zt.call(r)==$h)}var el=Array.isArray;function An(r){return r!=null&&Kh(r.length)&&!Xh(r)}function zh(r){return Ln(r)&&An(r)}function Xh(r){var e=Pn(r)?Zt.call(r):"";return e==Sh||e==vh}function Kh(r){return typeof r=="number"&&r>-1&&r%1==0&&r<=Za}function Pn(r){var e=typeof r;return!!r&&(e=="object"||e=="function")}function Ln(r){return!!r&&typeof r=="object"}function Qh(r){return typeof r=="string"||!el(r)&&Ln(r)&&Zt.call(r)==xh}function Zh(r){return typeof r=="symbol"||Ln(r)&&Zt.call(r)==kh}function eg(r){if(!r)return r===0?r:0;if(r=rg(r),r===Ka||r===-Ka){var e=r<0?-1:1;return e*Rh}return r===r?r:0}function tg(r){var e=eg(r),t=e%1;return e===e?t?e-t:e:0}function rg(r){if(typeof r=="number")return r;if(Zh(r))return Qa;if(Pn(r)){var e=typeof r.valueOf=="function"?r.valueOf():r;r=Pn(e)?e+"":e}if(typeof r!="string")return r===0?r:+r;r=r.replace(_h,"");var t=Oh.test(r);return t||Ph.test(r)?Ah(r.slice(2),t?2:8):Ch.test(r)?Qa:+r}function ng(r){return An(r)?Hh(r):Wh(r)}function ig(r){return r?Dh(r,ng(r)):[]}tl.exports=Yh});var il=w((vR,nl)=>{var sg="[object Boolean]",og=Object.prototype,ag=og.toString;function lg(r){return r===!0||r===!1||cg(r)&&ag.call(r)==sg}function cg(r){return!!r&&typeof r=="object"}nl.exports=lg});var cl=w((xR,ll)=>{var sl=1/0,ug=17976931348623157e292,ol=NaN,fg="[object Symbol]",mg=/^\s+|\s+$/g,dg=/^[-+]0x[0-9a-f]+$/i,pg=/^0b[01]+$/i,hg=/^0o[0-7]+$/i,gg=parseInt,yg=Object.prototype,wg=yg.toString;function Eg(r){return typeof r=="number"&&r==Sg(r)}function al(r){var e=typeof r;return!!r&&(e=="object"||e=="function")}function bg(r){return!!r&&typeof r=="object"}function Rg(r){return typeof r=="symbol"||bg(r)&&wg.call(r)==fg}function $g(r){if(!r)return r===0?r:0;if(r=vg(r),r===sl||r===-sl){var e=r<0?-1:1;return e*ug}return r===r?r:0}function Sg(r){var e=$g(r),t=e%1;return e===e?t?e-t:e:0}function vg(r){if(typeof r=="number")return r;if(Rg(r))return ol;if(al(r)){var e=typeof r.valueOf=="function"?r.valueOf():r;r=al(e)?e+"":e}if(typeof r!="string")return r===0?r:+r;r=r.replace(mg,"");var t=pg.test(r);return t||hg.test(r)?gg(r.slice(2),t?2:8):dg.test(r)?ol:+r}ll.exports=Eg});var fl=w((kR,ul)=>{var xg="[object Number]",kg=Object.prototype,_g=kg.toString;function Cg(r){return!!r&&typeof r=="object"}function Og(r){return typeof r=="number"||Cg(r)&&_g.call(r)==xg}ul.exports=Og});var hl=w((_R,pl)=>{var Pg="[object Object]";function Tg(r){var e=!1;if(r!=null&&typeof r.toString!="function")try{e=!!(r+"")}catch{}return e}function Ag(r,e){return function(t){return r(e(t))}}var Lg=Function.prototype,ml=Object.prototype,dl=Lg.toString,Mg=ml.hasOwnProperty,Ig=dl.call(Object),Ng=ml.toString,Fg=Ag(Object.getPrototypeOf,Object);function Dg(r){return!!r&&typeof r=="object"}function Ug(r){if(!Dg(r)||Ng.call(r)!=Pg||Tg(r))return!1;var e=Fg(r);if(e===null)return!0;var t=Mg.call(e,"constructor")&&e.constructor;return typeof t=="function"&&t instanceof t&&dl.call(t)==Ig}pl.exports=Ug});var yl=w((CR,gl)=>{var jg="[object String]",qg=Object.prototype,Gg=qg.toString,Hg=Array.isArray;function Wg(r){return!!r&&typeof r=="object"}function Vg(r){return typeof r=="string"||!Hg(r)&&Wg(r)&&Gg.call(r)==jg}gl.exports=Vg});var $l=w((OR,Rl)=>{var Bg="Expected a function",wl=1/0,Yg=17976931348623157e292,El=NaN,Jg="[object Symbol]",zg=/^\s+|\s+$/g,Xg=/^[-+]0x[0-9a-f]+$/i,Kg=/^0b[01]+$/i,Qg=/^0o[0-7]+$/i,Zg=parseInt,ey=Object.prototype,ty=ey.toString;function ry(r,e){var t;if(typeof e!="function")throw new TypeError(Bg);return r=ay(r),function(){return--r>0&&(t=e.apply(this,arguments)),r<=1&&(e=void 0),t}}function ny(r){return ry(2,r)}function bl(r){var e=typeof r;return!!r&&(e=="object"||e=="function")}function iy(r){return!!r&&typeof r=="object"}function sy(r){return typeof r=="symbol"||iy(r)&&ty.call(r)==Jg}function oy(r){if(!r)return r===0?r:0;if(r=ly(r),r===wl||r===-wl){var e=r<0?-1:1;return e*Yg}return r===r?r:0}function ay(r){var e=oy(r),t=e%1;return e===e?t?e-t:e:0}function ly(r){if(typeof r=="number")return r;if(sy(r))return El;if(bl(r)){var e=typeof r.valueOf=="function"?r.valueOf():r;r=bl(e)?e+"":e}if(typeof r!="string")return r===0?r:+r;r=r.replace(zg,"");var t=Kg.test(r);return t||Qg.test(r)?Zg(r.slice(2),t?2:8):Xg.test(r)?El:+r}Rl.exports=ny});var Tl=w((PR,Pl)=>{var Sl=on(),cy=_n(),uy=kn(),vl=Mt(),fy=rl(),er=il(),xl=cl(),Mn=fl(),_l=hl(),ve=yl(),my=$l(),{KeyObject:dy,createSecretKey:py,createPrivateKey:hy}=require("crypto"),Cl=["RS256","RS384","RS512","ES256","ES384","ES512","HS256","HS384","HS512","none"];cy&&Cl.splice(3,0,"PS256","PS384","PS512");var gy={expiresIn:{isValid:function(r){return xl(r)||ve(r)&&r},message:'"expiresIn" should be a number of seconds or string representing a timespan'},notBefore:{isValid:function(r){return xl(r)||ve(r)&&r},message:'"notBefore" should be a number of seconds or string representing a timespan'},audience:{isValid:function(r){return ve(r)||Array.isArray(r)},message:'"audience" must be a string or array'},algorithm:{isValid:fy.bind(null,Cl),message:'"algorithm" must be a valid string enum value'},header:{isValid:_l,message:'"header" must be an object'},encoding:{isValid:ve,message:'"encoding" must be a string'},issuer:{isValid:ve,message:'"issuer" must be a string'},subject:{isValid:ve,message:'"subject" must be a string'},jwtid:{isValid:ve,message:'"jwtid" must be a string'},noTimestamp:{isValid:er,message:'"noTimestamp" must be a boolean'},keyid:{isValid:ve,message:'"keyid" must be a string'},mutatePayload:{isValid:er,message:'"mutatePayload" must be a boolean'},allowInsecureKeySizes:{isValid:er,message:'"allowInsecureKeySizes" must be a boolean'},allowInvalidAsymmetricKeyTypes:{isValid:er,message:'"allowInvalidAsymmetricKeyTypes" must be a boolean'}},yy={iat:{isValid:Mn,message:'"iat" should be a number of seconds'},exp:{isValid:Mn,message:'"exp" should be a number of seconds'},nbf:{isValid:Mn,message:'"nbf" should be a number of seconds'}};function Ol(r,e,t,n){if(!_l(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 wy(r){return Ol(gy,!1,r,"options")}function Ey(r){return Ol(yy,!0,r,"payload")}var kl={audience:"aud",issuer:"iss",subject:"sub",jwtid:"jti"},by=["expiresIn","notBefore","noTimestamp","audience","issuer","subject","jwtid"];Pl.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(c){if(n)return n(c);throw c}if(!e&&t.algorithm!=="none")return o(new Error("secretOrPrivateKey must have a value"));if(e!=null&&!(e instanceof dy))try{e=hy(e)}catch{try{e=py(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{Ey(r)}catch(c){return o(c)}t.mutatePayload||(r=Object.assign({},r))}else{let c=by.filter(function(u){return typeof t[u]<"u"});if(c.length>0)return o(new Error("invalid "+c.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{wy(t)}catch(c){return o(c)}if(!t.allowInvalidAsymmetricKeyTypes)try{uy(s.alg,e)}catch(c){return o(c)}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=Sl(t.notBefore,a)}catch(c){return o(c)}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=Sl(t.expiresIn,a)}catch(c){return o(c)}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(kl).forEach(function(c){let u=kl[c];if(typeof t[c]<"u"){if(typeof r[u]<"u")return o(new Error('Bad "options.'+c+'" option. The payload already has an "'+u+'" property.'));r[u]=t[c]}});let l=t.encoding||"utf8";if(typeof n=="function")n=n&&my(n),vl.createSign({header:s,privateKey:e,payload:r,encoding:l}).once("error",n).once("done",function(c){if(!t.allowInsecureKeySizes&&/^(?:RS|PS)/.test(s.alg)&&c.length<256)return n(new Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${s.alg}`));n(null,c)});else{let c=vl.sign({header:s,payload:r,secret:e,encoding:l});if(!t.allowInsecureKeySizes&&/^(?:RS|PS)/.test(s.alg)&&c.length<256)throw new Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${s.alg}`);return c}}});var In=w((TR,Al)=>{Al.exports={decode:rn(),verify:Xa(),sign:Tl(),JsonWebTokenError:tt(),NotBeforeError:nn(),TokenExpiredError:sn()}});var Ec=w((lS,wc)=>{function fc(r){return Array.isArray(r)?r:[r]}var ni="",mc=" ",ti="\\",yw=/^\s+$/,ww=/(?:[^\\]|^)\\$/,Ew=/^\\!/,bw=/^\\#/,Rw=/\r?\n/g,$w=/^\.*\/|^\.+$/,ri="/",hc="node-ignore";typeof Symbol<"u"&&(hc=Symbol.for("node-ignore"));var dc=hc,Sw=(r,e,t)=>Object.defineProperty(r,e,{value:t}),vw=/([0-z])-([0-z])/g,gc=()=>!1,xw=r=>r.replace(vw,(e,t,n)=>t.charCodeAt(0)<=n.charCodeAt(0)?e:ni),kw=r=>{let{length:e}=r;return r.slice(0,e-e%2)},_w=[[/^\uFEFF/,()=>ni],[/((?:\\\\)*?)(\\?\s+)$/,(r,e,t)=>e+(t.indexOf("\\")===0?mc:ni)],[/(\\+?)\s/g,(r,e)=>{let{length:t}=e;return e.slice(0,t-t%2)+mc}],[/[\\$.|*+(){^]/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,()=>ti],[/\\\\/g,()=>ti],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(r,e,t,n,i)=>e===ti?`\\[${t}${kw(n)}${i}`:i==="]"&&n.length%2===0?`[${xw(t)}${n}]`:"[]"],[/(?:[^*])$/,r=>/\/$/.test(r)?`${r}$`:`${r}(?=$|\\/$)`],[/(\^|\\\/)?\\\*$/,(r,e)=>`${e?`${e}[^/]+`:"[^/]*"}(?=$|\\/$)`]],pc=Object.create(null),Cw=(r,e)=>{let t=pc[r];return t||(t=_w.reduce((n,[i,s])=>n.replace(i,s.bind(r)),r),pc[r]=t),e?new RegExp(t,"i"):new RegExp(t)},oi=r=>typeof r=="string",Ow=r=>r&&oi(r)&&!yw.test(r)&&!ww.test(r)&&r.indexOf("#")!==0,Pw=r=>r.split(Rw),ii=class{constructor(e,t,n,i){this.origin=e,this.pattern=t,this.negative=n,this.regex=i}},Tw=(r,e)=>{let t=r,n=!1;r.indexOf("!")===0&&(n=!0,r=r.substr(1)),r=r.replace(Ew,"!").replace(bw,"#");let i=Cw(r,e);return new ii(t,r,n,i)},Aw=(r,e)=>{throw new e(r)},Re=(r,e,t)=>oi(r)?r?Re.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),yc=r=>$w.test(r);Re.isNotRelative=yc;Re.convert=r=>r;var si=class{constructor({ignorecase:e=!0,ignoreCase:t=e,allowRelativePaths:n=!1}={}){Sw(this,dc,!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[dc]){this._rules=this._rules.concat(e._rules),this._added=!0;return}if(Ow(e)){let t=Tw(e,this._ignoreCase);this._added=!0,this._rules.push(t)}}add(e){return this._added=!1,fc(oi(e)?Pw(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&&Re.convert(e);return Re(s,e,this._allowRelativePaths?gc:Aw),this._t(s,t,n,i)}_t(e,t,n,i){if(e in t)return t[e];if(i||(i=e.split(ri)),i.pop(),!i.length)return t[e]=this._testOne(e,n);let s=this._t(i.join(ri)+ri,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 fc(e).filter(this.createFilter())}test(e){return this._test(e,this._testCache,!0)}},pr=r=>new si(r),Lw=r=>Re(r&&Re.convert(r),r,gc);pr.isPathValid=Lw;pr.default=pr;wc.exports=pr;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,"/");Re.convert=r;let e=/^[a-z]:\//i;Re.isNotRelative=t=>e.test(t)||yc(t)}});(function(){Ui().config(Object.assign({},qi(),Hi()(process.argv)))})();var Su=require("fs"),vu=require("path");var Ru=T(vt());var ue=T(require("fs")),qn=T(require("path")),Fl=T(require("os")),Dl=T(In());var Ry=process.stdout.isTTY===!0&&!process.env.NO_COLOR,xe=r=>Ry?r:"",S=xe("\x1B[32m"),P=xe("\x1B[33m"),_=xe("\x1B[36m"),ae=xe("\x1B[35m"),h=xe("\x1B[31m"),g=xe("\x1B[2m"),Z=xe("\x1B[1m"),m=xe("\x1B[0m");var Ll="app.boxel.realms";var $y={"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"},LR=Object.keys($y);function x(r){return r.endsWith("/")?r:`${r}/`}async function Ml(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 Sy(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 Nn(r,e){let t=await Sy(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 Fn(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 Dn(r){return new URL(`_matrix/client/v3/user/${encodeURIComponent(r.userId)}/account_data/${Ll}`,r.matrixUrl).href}async function tr(r){try{let e=await fetch(Dn(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 Il(r,e){let t=await tr(r);if(!t.includes(e)){t.push(e);let n=await fetch(Dn(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 Nl(r,e){let t=x(e),n=await tr(r),i=n.filter(o=>x(o)!==t);if(i.length===n.length)return!1;let s=await fetch(Dn(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 vy=qn.join(Fl.homedir(),".boxel-cli"),xy="profiles.json",ky=86400;function _y(r,e=ky){let t=r.replace(/^Bearer\s+/i,""),n=Dl.default.decode(t);if(!n?.exp)return!0;let i=Math.floor(Date.now()/1e3);return n.exp-i<e}var A="No active profile. Run `boxel profile add` to create one.";function rr(r){return r.endsWith(":stack.cards")?"staging":r.endsWith(":boxel.ai")?"production":r.endsWith(":localhost")?"local":"unknown"}function Be(r){let e=r.match(/^@([^:]+):/);return e?e[1]:r}function nr(r){let e=r.match(/:([^:]+)$/);return e?e[1]:"unknown"}function he(r){let e=Be(r),t=nr(r);return`${g}[${m}${_}${e}${m} ${g}\xB7${m} ${ae}${t}${m}${g}]${m}`}var jn=class{config;configDir;profilesFile;constructor(e){this.configDir=e||vy,this.profilesFile=qn.join(this.configDir,xy),this.config=this.loadConfig()}ensureConfigDir(){ue.existsSync(this.configDir)||ue.mkdirSync(this.configDir,{recursive:!0})}loadConfig(){let e={profiles:{},activeProfile:null};if(ue.existsSync(this.profilesFile))try{let t=ue.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(),ue.writeFileSync(this.profilesFile,JSON.stringify(this.config,null,2),{mode:384});try{ue.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=rr(e),a=Be(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",c=o==="production"?"https://app.boxel.ai/":"https://realms-staging.stack.cards/",u=nr(e),f={displayName:n||`${a} \xB7 ${u}`,matrixUrl:i||l,realmServerUrl:s||c,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:Be(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=Be(t);return Ml(n.matrixUrl,i,n.password)}async getOrRefreshServerToken(){let e=this.getRealmServerToken();if(e&&!_y(e))return e;let t=await this.loginToMatrix(),i=this.getActiveProfile().profile.realmServerUrl.replace(/\/$/,""),s=await Nn(t,i);return this.setRealmServerToken(s),s}async refreshServerToken(){let e=await this.loginToMatrix(),n=this.getActiveProfile().profile.realmServerUrl.replace(/\/$/,""),i=await Nn(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 Fn(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),c=await fetch(e,{...t,headers:l});if(c.status!==401)return c}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 Fn(i,t))[e];return o&&this.setRealmToken(e,o),o}async addToUserRealms(e){let t=await this.loginToMatrix();await Il(t,e)}async removeFromUserRealms(e){let t=await this.loginToMatrix();return Nl(t,e)}async getUserRealms(){let e=await this.loginToMatrix();return tr(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
|
${Z}Active Profile:${m} ${he(e.id)}`),console.log(` ${g}Display Name:${m} ${e.profile.displayName}`),console.log(` ${g}Matrix URL:${m} ${e.profile.matrixUrl}`),console.log(` ${g}Realm Server:${m} ${e.profile.realmServerUrl}`)):process.env.MATRIX_USERNAME?(console.log(`
|
|
33
33
|
${Z}Using environment variables${m} (no profile active)`),console.log(` ${g}Username:${m} ${process.env.MATRIX_USERNAME}`)):(console.log(`
|
|
34
|
-
${P}No active profile and no environment variables set.${m}`),console.log(`Run ${
|
|
34
|
+
${P}No active profile and no environment variables set.${m}`),console.log(`Run ${_}boxel profile add${m} to create a profile.`))}},Un=null;function C(){return Un||(Un=new jn),Un}var Gn=T(require("readline")),Ul=require("stream");function te(r){let e=Gn.createInterface({input:process.stdin,output:process.stdout});return new Promise(t=>{e.question(r,n=>{e.close(),t(n.trim())})})}function Hn(r){let e=new Ul.Writable({write:(n,i,s)=>s()}),t=Gn.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=u=>{try{let f=u.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(c);return}else d===""?(a(),process.exit()):d==="\x7F"||d==="\b"?c.length>0&&(c=c.slice(0,-1),process.stdout.write("\b \b")):d>=" "&&(c+=d,process.stdout.write("*"))}catch(f){a(),i(f)}},c="";try{process.stdout.write(r),s.on("data",l),s.resume()}catch(u){a(),i(u)}})}async function ge(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 Hn("Realm secret seed: ")}}var Wn={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 ir(r,e){let t=r.trim(),n;try{n=new URL(t)}catch{console.error(`${h}Error:${m} ${e} "${r}" is not a valid URL.`),process.exit(1)}return n.protocol!=="http:"&&n.protocol!=="https:"&&(console.error(`${h}Error:${m} ${e} "${r}" must use http:// or https://.`),process.exit(1)),t}function
|
|
37
|
-
Available profiles:`),await
|
|
38
|
-
${g}Commands:${m}`),console.log(` ${
|
|
39
|
-
${P}No profiles configured.${m}`),console.log(`Run ${
|
|
36
|
+
`),n(c);return}else d===""?(a(),process.exit()):d==="\x7F"||d==="\b"?c.length>0&&(c=c.slice(0,-1),process.stdout.write("\b \b")):d>=" "&&(c+=d,process.stdout.write("*"))}catch(f){a(),i(f)}},c="";try{process.stdout.write(r),s.on("data",l),s.resume()}catch(u){a(),i(u)}})}async function ge(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 Hn("Realm secret seed: ")}}var Wn={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 ir(r,e){let t=r.trim(),n;try{n=new URL(t)}catch{console.error(`${h}Error:${m} ${e} "${r}" is not a valid URL.`),process.exit(1)}return n.protocol!=="http:"&&n.protocol!=="https:"&&(console.error(`${h}Error:${m} ${e} "${r}" must use http:// or https://.`),process.exit(1)),t}function Cy(r){return r.toLowerCase().replace(/\//g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-+|-+$/g,"")}function jl(){let r=process.env.BOXEL_ENVIRONMENT;if(!r||!r.trim())return null;let e=Cy(r);return e||(console.error(`${h}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 Gl(r,e,t){let n=C();switch(r){case"list":await ql(n);break;case"add":{let i=t?.password||process.env.BOXEL_PASSWORD;if(t?.user&&i){let s=t.matrixUrl?ir(t.matrixUrl,"--matrix-url"):void 0,o=t.realmServerUrl?ir(t.realmServerUrl,"--realm-server-url"):void 0,u=!(rr(t.user)!=="unknown")&&(!s||!o)?jl():null;u&&console.log(`${g}Using BOXEL_ENVIRONMENT=${process.env.BOXEL_ENVIRONMENT}${m}`),await Ly(n,t.user,i,t.name,s??u?.matrixUrl,o??u?.realmServerUrl)}else await Py(n,jl());break}case"switch":e||(console.error(`${h}Error:${m} Please specify a profile to switch to.`),console.log("Usage: boxel profile switch <profile-id>"),console.log(`
|
|
37
|
+
Available profiles:`),await ql(n),process.exit(1)),await Ty(n,e);break;case"remove":e||(console.error(`${h}Error:${m} Please specify a profile to remove.`),process.exit(1)),await Ay(n,e);break;case"migrate":await My(n);break;default:n.printStatus(),console.log(`
|
|
38
|
+
${g}Commands:${m}`),console.log(` ${_}boxel profile list${m} List all profiles`),console.log(` ${_}boxel profile add${m} Add a new profile`),console.log(` ${_}boxel profile switch${m} Switch active profile`),console.log(` ${_}boxel profile remove${m} Remove a profile`),console.log(` ${_}boxel profile migrate${m} Import from .env file`)}}async function ql(r){let e=r.listProfiles(),t=r.getActiveProfileId();if(e.length===0){console.log(`
|
|
39
|
+
${P}No profiles configured.${m}`),console.log(`Run ${_}boxel profile add${m} to create one.`);return}console.log(`
|
|
40
40
|
${Z}Saved Profiles:${m}
|
|
41
|
-
`);for(let n of e){let i=r.getProfile(n),s=n===t,o=rr(n),a=s?`${S}\u2605${m} `:" ",l=nr(n),c=o==="production"?ae:
|
|
42
|
-
Choice [1/2/3/4]: `);if(r==="4"){let e=await te("Matrix server URL: ");e||(console.error(`${h}Error:${m} Matrix server URL is required.`),process.exit(1));let t=ir(e,"Matrix server URL"),n=await te("Realm server URL: ");n||(console.error(`${h}Error:${m} Realm server URL is required.`),process.exit(1));let i=ir(n,"Realm server URL"),s=new URL(t).hostname||"custom";return{domain:await te(`Domain for Matrix ID [${s}]: `)||s,matrixUrl:t,realmServerUrl:i}}return r==="3"?{...Wn.local}:r==="2"?{...Wn.production}:{...Wn.staging}}async function
|
|
41
|
+
`);for(let n of e){let i=r.getProfile(n),s=n===t,o=rr(n),a=s?`${S}\u2605${m} `:" ",l=nr(n),c=o==="production"?ae:_;console.log(`${a}${Z}${n}${m}`),console.log(` ${g}Name:${m} ${i.displayName}`),console.log(` ${g}Environment:${m} ${c}${l}${m}`),console.log(` ${g}Realm Server:${m} ${i.realmServerUrl}`),console.log("")}t&&console.log(`${g}\u2605 = active profile${m}`)}async function Oy(){console.log("Which environment?"),console.log(` ${_}1${m}) Staging (realms-staging.stack.cards)`),console.log(` ${ae}2${m}) Production (app.boxel.ai)`),console.log(` ${S}3${m}) Local (localhost:4201)`),console.log(` ${P}4${m}) Custom (enter your own URLs)`);let r=await te(`
|
|
42
|
+
Choice [1/2/3/4]: `);if(r==="4"){let e=await te("Matrix server URL: ");e||(console.error(`${h}Error:${m} Matrix server URL is required.`),process.exit(1));let t=ir(e,"Matrix server URL"),n=await te("Realm server URL: ");n||(console.error(`${h}Error:${m} Realm server URL is required.`),process.exit(1));let i=ir(n,"Realm server URL"),s=new URL(t).hostname||"custom";return{domain:await te(`Domain for Matrix ID [${s}]: `)||s,matrixUrl:t,realmServerUrl:i}}return r==="3"?{...Wn.local}:r==="2"?{...Wn.production}:{...Wn.staging}}async function Py(r,e){console.log(`
|
|
43
43
|
${Z}Add New Profile${m}
|
|
44
|
-
`);let t,n,i;if(e)console.log(`${g}Using BOXEL_ENVIRONMENT=${process.env.BOXEL_ENVIRONMENT}${m}`),t=e.domain,n=e.matrixUrl,i=e.realmServerUrl;else{let f=await
|
|
44
|
+
`);let t,n,i;if(e)console.log(`${g}Using BOXEL_ENVIRONMENT=${process.env.BOXEL_ENVIRONMENT}${m}`),t=e.domain,n=e.matrixUrl,i=e.realmServerUrl;else{let f=await Oy();t=f.domain,n=f.matrixUrl,i=f.realmServerUrl}console.log(`
|
|
45
45
|
Enter your Boxel username (without @ or domain)`),console.log(`${g}Example: ctse, aallen90${m}`);let s=await te("Username: ");s||(console.error(`${h}Error:${m} Username is required.`),process.exit(1));let o=`@${s}:${t}`;if(r.getProfile(o)&&(console.log(`
|
|
46
46
|
${P}Profile ${o} already exists.${m}`),(await te("Overwrite? [y/N]: ")).toLowerCase()!=="y")){console.log("Cancelled.");return}let a=await Hn("Password: ");a||(console.error(`${h}Error:${m} Password is required.`),process.exit(1));let l=`${s} \xB7 ${t}`,u=await te(`Display name [${l}]: `)||l;await r.addProfile(o,a,u,n,i),console.log(`
|
|
47
|
-
${S}\u2713${m} Profile created: ${he(o)}`),r.getActiveProfileId()===o?console.log(`${g}This profile is now active.${m}`):(await te("Switch to this profile now? [Y/n]: ")).toLowerCase()!=="n"&&(r.switchProfile(o),console.log(`${S}\u2713${m} Switched to ${he(o)}`))}async function
|
|
47
|
+
${S}\u2713${m} Profile created: ${he(o)}`),r.getActiveProfileId()===o?console.log(`${g}This profile is now active.${m}`):(await te("Switch to this profile now? [Y/n]: ")).toLowerCase()!=="n"&&(r.switchProfile(o),console.log(`${S}\u2713${m} Switched to ${he(o)}`))}async function Ty(r,e){let t=r.listProfiles(),n=e;if(!t.includes(e)){let i=t.filter(s=>{let o=Be(s);return s.includes(e)||o===e});if(i.length===0){console.error(`${h}Error:${m} Profile not found: ${e}`),console.log(`
|
|
48
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(`${h}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(`${S}\u2713${m} Switched to ${he(n)}`):(console.error(`${h}Error:${m} Failed to switch profile.`),process.exit(1))}async function
|
|
49
|
+
Matching profiles:`);for(let s of i)console.log(` ${s}`);process.exit(1)}}r.switchProfile(n)?console.log(`${S}\u2713${m} Switched to ${he(n)}`):(console.error(`${h}Error:${m} Failed to switch profile.`),process.exit(1))}async function Ay(r,e){if(r.getProfile(e)||(console.error(`${h}Error:${m} Profile not found: ${e}`),process.exit(1)),(await te(`Remove profile ${e}? [y/N]: `)).toLowerCase()!=="y"){console.log("Cancelled.");return}if(await r.removeProfile(e)){console.log(`${S}\u2713${m} Profile removed.`);let i=r.getActiveProfileId();i&&console.log(`Active profile is now: ${he(i)}`)}else console.error(`${h}Error:${m} Failed to remove profile.`),process.exit(1)}async function Ly(r,e,t,n,i,s){if((!e.startsWith("@")||!e.includes(":"))&&(console.error(`${h}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(`${g}Updated server URLs and cleared cached realm tokens.${m}`),console.log(`${S}\u2713${m} Profile updated: ${he(e)}`);return}try{await r.addProfile(e,t,n,i,s)}catch(a){console.error(`${h}Error:${m} ${a instanceof Error?a.message:String(a)}`),process.exit(1)}console.log(`${S}\u2713${m} Profile created: ${he(e)}`),r.getActiveProfileId()!==e&&console.log(`${g}Use 'boxel profile switch ${e}' to switch to this profile.${m}`)}async function My(r){console.log(`
|
|
50
50
|
${Z}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(`${S}\u2713${m} Created profile: ${he(s.profileId)}`),console.log(`
|
|
53
53
|
${g}You can now remove credentials from .env if desired.${m}`)):(console.log(`${P}Profile ${he(s.profileId)} already exists.${m} Password has been updated if it changed.`),console.log(`
|
|
54
|
-
${g}Use 'boxel profile add -u ${s.profileId} -p <password>' to update other fields.${m}`)):console.log(`${P}Migration failed.${m}`)}var fe=T(require("fs")),Ae=T(require("path"));var Ye=T(require("fs")),H=T(require("path"));var lt=!1,
|
|
54
|
+
${g}Use 'boxel profile add -u ${s.profileId} -p <password>' to update other fields.${m}`)):console.log(`${P}Migration failed.${m}`)}var fe=T(require("fs")),Ae=T(require("path"));var Ye=T(require("fs")),H=T(require("path"));var lt=!1,Iy=console.log.bind(console),Ny=console.info.bind(console),Fy=console.debug.bind(console);function or(r){if(r!==lt)if(lt=r,lt){let e=()=>{};console.log=e,console.info=e,console.debug=e}else console.log=Iy,console.info=Ny,console.debug=Fy}function Hl(){return lt}var M={info(...r){lt||process.stderr.write(r.map(sr).join(" ")+`
|
|
55
55
|
`)},warn(...r){process.stderr.write(r.map(sr).join(" ")+`
|
|
56
56
|
`)},error(...r){process.stderr.write(r.map(sr).join(" ")+`
|
|
57
57
|
`)},output(...r){process.stdout.write(r.map(sr).join(" ")+`
|
|
58
|
-
`)}};function sr(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)}}var
|
|
58
|
+
`)}};function sr(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)}}var Wl=!1,Dy=new Set([".git","node_modules","dist",".boxel-history",".claude"]);function Uy(r){return Dy.has(r)}function jy(r){return r==="stack.cards"||r.endsWith(".stack.cards")?"stack.cards":r==="boxel.ai"||r.endsWith(".boxel.ai")?"boxel.ai":r}function Vn(r){if(!r)return!1;let e;try{e=decodeURIComponent(r)}catch{return!1}return!(e==="."||e===".."||e.includes("/")||e.includes("\\")||e.includes("\0"))}function qy(r){let e;try{e=new URL(r)}catch{return null}let t=jy(e.hostname);if(!Vn(t))return null;let n=e.pathname.replace(/^\/|\/$/g,"").split("/").filter(Boolean),i=n[0]??"unknown-owner",s=n[1]??n[0]??"workspace";return!Vn(i)||!Vn(s)?null:H.join(t,i,s)}function Gy(r,e){let t=qy(r);return t===null?null:H.resolve(e,t)}function Hy(r){let e;try{e=Ye.readFileSync(r,"utf-8")}catch{return null}let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null)return null;let n=t.realmUrl;return typeof n!="string"||n===""?null:{realmUrl:n}}function Vl(r,e){let t=H.join(r,".boxel-sync.json");Ye.existsSync(t)&&e.push(t)}function ar(r){try{return Ye.readdirSync(r,{withFileTypes:!0}).filter(e=>e.isDirectory()&&!Uy(e.name)).map(e=>H.join(r,e.name))}catch{return[]}}function Wy(r){let e=[],t=H.resolve(r);for(let n of ar(t))Vl(n,e);for(let n of ar(t))for(let i of ar(n))for(let s of ar(i))Vl(s,e);return e}function Vy(r,e){let t=H.relative(r,e);return t===""?!0:t.startsWith("..")?!1:!H.isAbsolute(t)}function Bn(r){let e=H.resolve(r),t=Wy(e),n=new Set,i=[];for(let s of t){if(n.has(s))continue;n.add(s);let o=Hy(s);if(!o)continue;let a=Gy(o.realmUrl,e);if(a===null||!Vy(e,a))continue;let l=H.dirname(s);H.resolve(l)!==H.resolve(a)&&i.push({manifestPath:s,currentDir:l,expectedDir:a,realmUrl:o.realmUrl})}return i}function Bl(r){if(Wl||process.env.BOXEL_DISABLE_PATH_WARNING==="1"||Hl())return;let e=Bn(r);if(e.length===0)return;Wl=!0,console.warn(`
|
|
59
59
|
\u26A0\uFE0F Detected local realm directories at legacy local paths:`);let t=H.resolve(r);for(let n of e.slice(0,5)){let i=H.relative(t,n.currentDir)||".",s=H.relative(t,n.expectedDir)||".";console.warn(` - ${i} -> ${s}`)}e.length>5&&console.warn(` ...and ${e.length-5} more`),console.warn(`
|
|
60
60
|
Run to preview:`),console.warn(" boxel consolidate-workspaces . --dry-run"),console.warn("Then apply:"),console.warn(` boxel consolidate-workspaces .
|
|
61
|
-
`)}function
|
|
62
|
-
`);let i=0,s=0;for(let o of n){let a=Ae.relative(t,o.currentDir)||".",l=Ae.relative(t,o.expectedDir)||".";if(console.log(`- ${a} -> ${l}`),!e.dryRun){if(fe.existsSync(o.expectedDir)){console.warn(" Skipping: target path already exists"),s+=1;continue}
|
|
61
|
+
`)}function By(r){fe.existsSync(r)||fe.mkdirSync(r,{recursive:!0})}function Yy(r,e){try{fe.renameSync(r,e)}catch(t){let n=t;if(n.code!=="EXDEV")throw n;fe.cpSync(r,e,{recursive:!0}),fe.rmSync(r,{recursive:!0,force:!0})}}async function Jy(r,e){let t=Ae.resolve(r||"."),n=Bn(t);if(n.length===0){console.log(`No misplaced local realm paths found under ${t}`);return}console.log(`Found ${n.length} misplaced local realm path(s):
|
|
62
|
+
`);let i=0,s=0;for(let o of n){let a=Ae.relative(t,o.currentDir)||".",l=Ae.relative(t,o.expectedDir)||".";if(console.log(`- ${a} -> ${l}`),!e.dryRun){if(fe.existsSync(o.expectedDir)){console.warn(" Skipping: target path already exists"),s+=1;continue}By(Ae.dirname(o.expectedDir));try{Yy(o.currentDir,o.expectedDir),i+=1}catch(c){let u=c instanceof Error?c.message:String(c);console.warn(` Skipping: failed to move (${u})`),s+=1}}}if(e.dryRun){console.log(`
|
|
63
63
|
[DRY RUN] No directories moved.`);return}console.log(`
|
|
64
|
-
Moved ${i} director${i===1?"y":"ies"}.`),s>0&&console.log(`Skipped ${s} due to existing target paths or move failures.`)}function
|
|
65
|
-
`)}async function
|
|
66
|
-
${g}${l.length} error(s), ${c.length} warning(s)${m}`),l.length>0&&process.exit(1)})}async function Me(r,e){let t=e?.profileManager??
|
|
67
|
-
${g}${t.filenames.length} file(s)${m}`)}})}var Jn=[".gts",".gjs",".ts",".js"];async function
|
|
64
|
+
Moved ${i} director${i===1?"y":"ies"}.`),s>0&&console.log(`Skipped ${s} due to existing target paths or move failures.`)}function Yl(r){r.command("consolidate-workspaces").description("Move local realm mirror directories into the canonical <root>/<domain>/<owner>/<realm> layout").argument("[root-dir]","Root directory to scan (default: current directory)").option("--dry-run","Preview without moving anything").action(async(e,t)=>{await Jy(e,t)})}function ct(r){if(r.trim()==="")return"Path must be a non-empty realm-relative file path.";if(/^[a-z][a-z0-9+.-]*:/i.test(r))return`Path "${r}" must be realm-relative \u2014 absolute URLs (with a scheme) are not accepted.`;if(r.startsWith("/"))return`Path "${r}" must be realm-relative \u2014 paths starting with "/" are not accepted.`;if(r.includes("\\"))return`Path "${r}" must not contain backslash characters.`;let e;try{e=decodeURIComponent(r)}catch{return`Path "${r}" contains an invalid percent-encoded escape.`}return e.split("/").some(n=>n==="..")?`Path "${r}" must not contain ".." segments \u2014 the path must stay inside the target realm.`:null}var lr=require("fs");var Jl=require("fs");async function ft(r,e,t,n){let i=n?.profileManager??C();if(!i.getActiveProfile())return{ok:!1,error:A};let o=new URL(e,x(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 ut(r){process.stderr.write(r+`
|
|
65
|
+
`)}async function zy(){let r=[];for await(let e of process.stdin)r.push(e);return Buffer.concat(r).toString("utf-8")}function zl(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,Jl.readFileSync)(t.file,"utf-8")}catch(s){ut(`${h}Error:${m} Could not read file: ${s instanceof Error?s.message:String(s)}`),process.exit(1)}else process.stdin.isTTY&&ut(`${g}Reading from STDIN. Type or paste content, then press Enter followed by Ctrl+D to finish.${m}`),n=await zy(),ut(`${g}Received ${n.length} bytes. Writing to realm...${m}`);let i;try{i=await ft(t.realm,e,n)}catch(s){ut(`${h}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(`${S}Written:${m} ${e} ${g}\u2192${m} ${t.realm}`):ut(`${h}Error:${m} ${i.error}`),i.ok||process.exit(1)})}async function Yn(r,e,t,n){let i=n?.profileManager??C();if(!i.getActiveProfile())return{ok:!1,error:A};let o=`${x(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 c=await a.text().catch(()=>"(no body)");return{ok:!1,error:`HTTP ${a.status}: ${c.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 Xl(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=C();n.getActiveProfile()||(console.error(`${h}Error:${m} ${A}`),process.exit(1));let s;if(t.file)try{s=(0,lr.readFileSync)(t.file,"utf-8")}catch(u){console.error(`${h}Error:${m} Could not read local file: ${u instanceof Error?u.message:String(u)}`),process.exit(1)}else{let u=new URL(e,x(t.realm)).href;try{let f=await n.authedRealmFetch(u,{method:"GET",headers:{Accept:"application/vnd.card+source"}});if(!f.ok){let d=await f.text().catch(()=>"(no body)");console.error(`${h}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(`${h}Error:${m} ${f instanceof Error?f.message:String(f)}`),process.exit(1)}}let o;try{o=await Yn(t.realm,s,e,{profileManager:n})}catch(u){console.error(`${h}Error:${m} ${u instanceof Error?u.message:String(u)}`),process.exit(1)}if(t.json){M.output(JSON.stringify(o,null,2)),o.ok||process.exit(1);return}if(o.ok||(console.error(`${h}Error:${m} ${o.error}`),process.exit(1)),t.fix&&o.fixed&&o.output)if(t.file)(0,lr.writeFileSync)(t.file,o.output,"utf-8"),console.log(`${S}Fixed:${m} ${t.file}`);else{let u=await ft(t.realm,e,o.output,{profileManager:n});u.ok||(console.error(`${h}Error:${m} Could not write fixed file: ${u.error}`),process.exit(1)),console.log(`${S}Fixed:${m} ${e} ${g}\u2192${m} ${t.realm}`)}let a=o.messages??[],l=a.filter(u=>u.severity===2),c=a.filter(u=>u.severity===1);if(a.length===0){console.log(`${g}No lint issues found.${m}`);return}for(let u of a){let f=u.severity===2?h:P,d=u.severity===2?"error":"warning",p=u.ruleId?` (${u.ruleId})`:"";console.log(`${f}${d}${m} ${u.line}:${u.column} ${u.message}${g}${p}${m}`)}console.log(`
|
|
66
|
+
${g}${l.length} error(s), ${c.length} warning(s)${m}`),l.length>0&&process.exit(1)})}async function Me(r,e){let t=e?.profileManager??C();if(!t.getActiveProfile())return{filenames:[],error:A};let i=x(r),s=`${i}_mtimes`;try{let o=await t.authedRealmFetch(s,{method:"GET",headers:{Accept:"application/vnd.api+json"}});if(!o.ok){let u=await o.text().catch(()=>"(no body)");return{filenames:[],error:`_mtimes returned HTTP ${o.status}: ${u.slice(0,300)}`}}let a=await o.json(),l=a?.data?.attributes?.mtimes??a,c=[];for(let u of Object.keys(l)){if(!u.startsWith(i))continue;let f=u.slice(i.length);!f||f.endsWith("/")||c.push(f)}return{filenames:c.sort()}}catch(o){return{filenames:[],error:o instanceof Error?o.message:String(o)}}}function Kl(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 Me(e.realm)}catch(n){console.error(`${h}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(`${h}Error:${m} ${t.error}`),process.exit(1);else{for(let n of t.filenames)console.log(`${g}${n}${m}`);console.log(`
|
|
67
|
+
${g}${t.filenames.length} file(s)${m}`)}})}var Jn=[".gts",".gjs",".ts",".js"];async function Xy(r,e){let t=e?.profileManager??C();if(!t.getActiveProfile())return cr(A);let i=x(r),s=Date.now(),o;if(e?.path){let f=e.path,d=ct(f);if(d)return cr(d);if(!Jn.some(p=>f.endsWith(p)))return cr(`Path "${f}" is not lintable \u2014 must end with one of ${Jn.join(", ")}`);o=[f]}else{let f=await Me(i,{profileManager:t});if(f.error)return cr(`Failed to list realm files: ${f.error}`);o=f.filenames.filter(d=>Jn.some(p=>d.endsWith(p)))}if(o.length===0)return{status:"passed",filesChecked:0,filesWithErrors:0,errorCount:0,warningCount:0,durationMs:Date.now()-s,lintableFiles:[],violations:[]};let a=[],l=0,c=0,u=0;for(let f of o){let d;try{let R=new URL(f,i).href,I=await t.authedRealmFetch(R,{method:"GET",headers:{Accept:"application/vnd.card+source"}});if(!I.ok){let ee=await I.text().catch(()=>"(no body)");zn(f,`HTTP ${I.status}: ${ee.slice(0,300)}`,a),l+=1,c+=1;continue}d=await I.text()}catch(R){zn(f,R instanceof Error?R.message:String(R),a),l+=1,c+=1;continue}let p=await Yn(i,d,f,{profileManager:t});if(!p.ok){zn(f,p.error??"lint failed",a),l+=1,c+=1;continue}let y=!1;for(let R of p.messages??[]){let I=R.severity===2?"error":"warning";a.push({rule:R.ruleId,file:f,line:R.line,column:R.column,message:R.message,severity:I}),I==="error"?(c+=1,y=!0):u+=1}y&&(l+=1)}return{status:c===0?"passed":"failed",filesChecked:o.length,filesWithErrors:l,errorCount:c,warningCount:u,durationMs:Date.now()-s,lintableFiles:o,violations:a}}function zn(r,e,t){t.push({rule:"lint-error",file:r,line:0,column:0,message:e,severity:"error"})}function cr(r){return{status:"error",filesChecked:0,filesWithErrors:0,errorCount:0,warningCount:0,durationMs:0,lintableFiles:[],violations:[],errorMessage:r}}function Ql(r){r.command("lint").description("Lint every lintable (.gts/.gjs/.ts/.js) file in a realm via the realm lint endpoint. Pass a realm-relative path to lint a single file.").argument("[path]","Optional realm-relative file path. When omitted, lints every lintable file in the realm.").requiredOption("--realm <realm-url>","The realm URL to lint against").option("--json","Output structured JSON result").action(async(e,t)=>{let n;try{n=await Xy(t.realm,e?{path:e}:{})}catch(s){console.error(`${h}Error:${m} ${s instanceof Error?s.message:String(s)}`),process.exit(1)}if(t.json){M.output(JSON.stringify(n,null,2)),n.status!=="passed"&&process.exit(1);return}if(n.errorMessage&&(console.error(`${h}Error:${m} ${n.errorMessage}`),process.exit(1)),n.violations.length===0){console.log(`${g}No lint issues found (${n.filesChecked} file(s) checked).${m}`);return}let i;for(let s of n.violations){s.file!==i&&(i=s.file,console.log(`
|
|
68
68
|
${g}${s.file}${m}`));let o=s.severity==="error"?h:P,a=s.rule?` (${s.rule})`:"";console.log(` ${o}${s.severity}${m} ${s.line}:${s.column} ${s.message}${g}${a}${m}`)}console.log(`
|
|
69
|
-
${g}${n.errorCount} error(s), ${n.warningCount} warning(s) across ${n.filesChecked} file(s)${m}`),n.errorCount>0&&process.exit(1)})}var
|
|
70
|
-
`)){let l=a.match(/^(.+?)\((\d+),(\d+)\):\s*error\s+(TS\d+):\s*(.+)/);if(!l)continue;o++;let[,c,u,f,d,p]=l,y=(0,J.resolve)(e,c);if(!y.startsWith(e)||d==="TS2353"&&p.includes("'scoped'"))continue;let
|
|
69
|
+
${g}${n.errorCount} error(s), ${n.warningCount} warning(s) across ${n.filesChecked} file(s)${m}`),n.errorCount>0&&process.exit(1)})}var tc=require("node:child_process"),me=require("node:fs"),rc=require("node:os"),J=require("node:path");var ur=require("node:fs"),fr=require("node:path");function mt(r){let e=r;for(;;){let t=(0,fr.join)(e,"package.json");if((0,ur.existsSync)(t))try{if(JSON.parse((0,ur.readFileSync)(t,"utf8"))?.name==="@cardstack/boxel-cli")return e}catch{}let n=(0,fr.dirname)(e);if(n===e)throw new Error("Could not locate the @cardstack/boxel-cli package root walking up from "+r);e=n}}async function Xn(r,e,t){let n=t?.profileManager??C(),i=n.getActiveProfile();if(!i)return{ok:!1,error:A};let o=`${i.profile.realmServerUrl.replace(/\/$/,"")}/_federated-search`,a=(Array.isArray(r)?r:[r]).map(x);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 u=await l.text();return{ok:!1,status:l.status,error:`HTTP ${l.status}: ${u.slice(0,300)}`}}let c=await l.json();return{ok:!0,status:l.status,data:c.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(`${h}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(`${h}Error:${m} --query must be a JSON object, got ${Array.isArray(i)?"array":typeof i}`),process.exit(1)),t=i}catch(i){console.error(`${h}Error:${m} Invalid JSON in --query: ${i instanceof Error?i.message:String(i)}`),process.exit(1);return}let n;try{n=await Xn(e.realm,t)}catch(i){console.error(`${h}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(`${g}Status:${m} ${n.status??"(no status)"}`),console.error(`${h}Error:${m} ${n.error}`)),n.ok||process.exit(1)})}var Ky={module:"https://cardstack.com/base/spec",name:"Spec"},Qn=[".gts",".gjs",".ts"],dr=".json",nc=mt(__dirname),Zn=(0,J.resolve)(nc,".."),Qy=(0,J.join)(Zn,"base"),dt=(0,J.join)(Zn,"host"),Zy=(0,J.join)(Zn,"boxel-ui","addon","src"),ew=(0,J.join)(dt,"node_modules"),Kn;async function tw(r,e,t={}){let n=t.totalWaitMs??3e4,i=t.pollMs??250,s=Date.now()+n,o=await r();for(;e(o)&&Date.now()<s;)await new Promise(a=>setTimeout(a,i)),o=await r();return o}async function rw(r,e){let t=e?.profileManager??C();if(!t.getActiveProfile())return mr(A);let i=x(r),s=Date.now(),o=[],a=[];if(e?.path){let f=e.path,d=ct(f);if(d)return mr(d);if(Qn.some(p=>f.endsWith(p)))o=[f];else if(f.endsWith(dr))a=[f];else return mr(`Path "${f}" is not parseable \u2014 must end with one of ${Qn.join(", ")}, or ${dr}`)}else try{[o,a]=await Promise.all([nw(i,t),iw(i,t)])}catch(f){return mr(`Failed to discover parseable files: ${f instanceof Error?f.message:String(f)}`)}let l=[...o,...a];if(l.length===0)return{status:"passed",filesChecked:0,filesWithErrors:0,errorCount:0,durationMs:Date.now()-s,parseableFiles:[],errors:[]};let c=[],u=new Set;if(o.length>0){let f=[];for(let d of o){let p=await ec(i,d,t);if(!p.ok){c.push({file:d,line:0,column:0,message:`Could not read ${d}: ${p.error}`}),u.add(d);continue}f.push({path:d,content:p.content})}if(f.length>0)try{let d=await ow(f);for(let p of d)c.push(p),u.add(p.file)}catch(d){let p=f[0].path;c.push({file:p,line:0,column:0,message:`Glint check failed: ${d instanceof Error?d.message:String(d)}`}),u.add(p)}}for(let f of a){let d=await ec(i,f,t);if(!d.ok){c.push({file:f,line:0,column:0,message:`Could not read ${f}: ${d.error}`}),u.add(f);continue}let p=aw(f,d.content);for(let y of p)c.push(y),u.add(y.file)}return{status:c.length===0?"passed":"failed",filesChecked:l.length,filesWithErrors:u.size,errorCount:c.length,durationMs:Date.now()-s,parseableFiles:l,errors:c}}async function nw(r,e){let t=`${r}_mtimes`,n=await e.authedRealmFetch(t,{method:"GET",headers:{Accept:"application/vnd.api+json"}});if(!n.ok){let a=await n.text().catch(()=>"(no body)");throw new Error(`_mtimes returned HTTP ${n.status}: ${a.slice(0,300)}`)}let i=await n.json(),s=i?.data?.attributes?.mtimes??i,o=[];for(let a of Object.keys(s)){if(!a.startsWith(r))continue;let l=a.slice(r.length);!l||l.endsWith("/")||Qn.some(c=>l.endsWith(c))&&o.push(l)}return o.sort()}async function iw(r,e){let t=await tw(()=>Xn(r,{filter:{type:Ky}},{profileManager:e}),s=>s.ok&&(s.data?.length??0)===0);if(!t.ok)return[];let n=[];for(let s of t.data??[]){let o=s.id;if(!o)continue;let a=s.attributes;if(!a||a.specType==="field")continue;let c=s.relationships,u=sw(c),f=new URL(o,r).href,d=[];for(let p of u){let y=new URL(p,f).href;y.startsWith(r)&&d.push(y.slice(r.length))}n.push({specId:o,exampleUrls:d})}let i=[];for(let s of n)for(let o of s.exampleUrls){let a=o.endsWith(dr)?o:`${o}${dr}`;i.includes(a)||i.push(a)}return i.sort()}function sw(r){if(!r)return[];let e=[];for(let t=0;;t++){let n=r[`linkedExamples.${t}`];if(!n?.links?.self)break;e.push(n.links.self)}if(e.length===0){let t=r.linkedExamples;t?.links?.self&&e.push(t.links.self)}return e}async function ec(r,e,t){try{let n=new URL(e,r).href,i=await t.authedRealmFetch(n,{method:"GET",headers:{Accept:"application/vnd.card+source"}});if(!i.ok){let s=await i.text().catch(()=>"(no body)");return{ok:!1,error:`HTTP ${i.status}: ${s.slice(0,300)}`}}return{ok:!0,content:await i.text()}}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}}async function ow(r){let e=(0,me.mkdtempSync)((0,J.join)((0,rc.tmpdir)(),"boxel-parse-"));try{for(let a of r){let l=ct(a.path);if(l)throw new Error(l);let c=(0,J.join)(e,a.path),u=(0,J.resolve)(c);if(!u.startsWith(e+"/"))throw new Error(`Path "${a.path}" resolves outside the parse workspace and was rejected.`);(0,me.mkdirSync)((0,J.dirname)(u),{recursive:!0}),(0,me.writeFileSync)(u,a.content,"utf8")}if(!Kn){let a={compilerOptions:{target:"es2022",allowJs:!0,moduleResolution:"bundler",allowSyntheticDefaultImports:!0,noEmit:!0,baseUrl:".",module:"es2022",strict:!0,experimentalDecorators:!0,skipLibCheck:!0,noUnusedLocals:!1,noUnusedParameters:!1,types:["qunit-dom","@cardstack/local-types"],paths:{"https://cardstack.com/base/*":[`${Qy}/*`],"@cardstack/host/tests/*":[`${dt}/tests/*`],"@cardstack/host/*":[`${dt}/app/*`],"@cardstack/boxel-host/commands/*":[`${dt}/app/commands/*`],"@cardstack/boxel-ui/*":[`${Zy}/*`],"*":[`${dt}/types/*`]}},include:["**/*.ts","**/*.gts","**/*.gjs"],exclude:["node_modules"]};Kn=JSON.stringify(a,null,2)}(0,me.writeFileSync)((0,J.join)(e,"tsconfig.json"),Kn,"utf8"),(0,me.symlinkSync)(ew,(0,J.join)(e,"node_modules"));let t=(0,J.join)(nc,"node_modules",".bin","ember-tsc"),{output:n,exitedWithError:i}=await new Promise((a,l)=>{let c=(0,tc.execFile)(t,["--noEmit","--project",(0,J.join)(e,"tsconfig.json")],{cwd:e,timeout:12e4,maxBuffer:10485760},(u,f,d)=>{if(u&&!f&&!d){l(new Error(`ember-tsc execution failed: ${u.message}`));return}if(c.killed||u?.killed){l(new Error("ember-tsc was killed (timeout or signal)"));return}a({output:f+d,exitedWithError:!!u})})}),s=[],o=0;for(let a of n.split(`
|
|
70
|
+
`)){let l=a.match(/^(.+?)\((\d+),(\d+)\):\s*error\s+(TS\d+):\s*(.+)/);if(!l)continue;o++;let[,c,u,f,d,p]=l,y=(0,J.resolve)(e,c);if(!y.startsWith(e)||d==="TS2353"&&p.includes("'scoped'"))continue;let R=y.slice(e.length+1),I=r.find(ee=>ee.path===R);I&&s.push({file:I.path,line:parseInt(u,10),column:parseInt(f,10),message:p})}if(i&&s.length===0&&o===0){let a=n.slice(0,500).trim();s.push({file:r[0]?.path??"unknown",line:0,column:0,message:`ember-tsc exited with errors but produced no TS diagnostics. Check the tsconfig paths and node_modules symlink. Output: ${a}`})}return s}finally{try{(0,me.rmSync)(e,{recursive:!0,force:!0})}catch{}}}function aw(r,e){let t;try{t=JSON.parse(e)}catch(n){let i=n instanceof Error?n.message:String(n);return[{file:r,line:0,column:0,message:`Invalid JSON: ${i}`}]}return typeof t!="object"||t===null||Array.isArray(t)?[{file:r,line:0,column:0,message:"Card document must be a JSON object"}]:lw(r,t)}function lw(r,e){let t=[],n=e.data;if(typeof n!="object"||n===null||Array.isArray(n))return t.push({file:r,line:0,column:0,message:'Card document must have a "data" object'}),t;let i=n;typeof i.type!="string"&&t.push({file:r,line:0,column:0,message:'Card document "data.type" must be a string'});let s=i.meta;if(typeof s!="object"||s===null)t.push({file:r,line:0,column:0,message:'Card document must have a "data.meta" object'});else{let o=s.adoptsFrom;typeof o!="object"||o===null?t.push({file:r,line:0,column:0,message:'Card document must have a "data.meta.adoptsFrom" object with "module" and "name"'}):(typeof o.module!="string"&&t.push({file:r,line:0,column:0,message:'"data.meta.adoptsFrom.module" must be a string'}),typeof o.name!="string"&&t.push({file:r,line:0,column:0,message:'"data.meta.adoptsFrom.name" must be a string'}))}return t}function mr(r){return{status:"error",filesChecked:0,filesWithErrors:0,errorCount:0,durationMs:0,parseableFiles:[],errors:[],errorMessage:r}}function ic(r){r.command("parse").description("Type-check every .gts / .gjs / .ts file in a realm with glint, plus validate the document structure of any .json files linked as Spec.linkedExamples. Pass a realm-relative path to parse a single file. Monorepo-only (relies on packages/base, packages/host, packages/boxel-ui, and @glint/ember-tsc resolvable from this CLI's location).").argument("[path]","Optional realm-relative file path. When omitted, parses every parseable file (gts/gjs/ts + Spec linkedExamples JSON) in the realm.").requiredOption("--realm <realm-url>","The realm URL to parse against").option("--json","Output structured JSON result").action(async(e,t)=>{let n;try{n=await rw(t.realm,e?{path:e}:{})}catch(s){console.error(`${h}Error:${m} ${s instanceof Error?s.message:String(s)}`),process.exit(1)}if(t.json){M.output(JSON.stringify(n,null,2)),n.status!=="passed"&&process.exit(1);return}if(n.errorMessage&&(console.error(`${h}Error:${m} ${n.errorMessage}`),process.exit(1)),n.errors.length===0){console.log(`${g}No parse errors (${n.filesChecked} file(s) checked).${m}`);return}let i;for(let s of n.errors)s.file!==i&&(i=s.file,console.log(`
|
|
71
71
|
${g}${s.file}${m}`)),console.log(` ${h}error${m} ${s.line}:${s.column} ${s.message}`);console.log(`
|
|
72
|
-
${g}${n.errorCount} error(s) across ${n.filesWithErrors} of ${n.filesChecked} file(s)${m}`),n.errorCount>0&&process.exit(1)})}async function nw(r,e,t){let n=t?.profileManager??_();if(!n.getActiveProfile())throw new Error("No active profile. Run `boxel profile add` to create one.");let s=new URL(e,k(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 ic(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 nw(t.realm,e)}catch(i){console.error(`${h}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(`${g}Status:${m} ${n.status??"(no status)"}`),console.error(`${h}Error:${m} ${n.error}`)),n.ok||process.exit(1)})}async function iw(r,e){let t=e?.profileManager??_();if(!t.getActiveProfile())return{ok:!1,error:L};let i=e?.cancelPending??!1,s=`${k(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 sc(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 iw(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(`${S}Cancelled ${n} indexing jobs for ${e.realm}${m}`)}else console.error(`${h}Error:${m} ${t.error}`),process.exit(1)})}var sw=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"}),oc=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 ei(r){if(!r)return;let e=r.toLowerCase().replace(/[^a-z0-9]/g,"").replace(/^[0-9]+/,"");return sw[e.charAt(0)]}function ac(){let r=Math.floor(Math.random()*oc.length);return oc[r]}var ow=/^[a-z0-9-]+$/;function cc(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 cw(e,t,n)})}async function aw(r,e,t={}){let n=t.profileManager??_(),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??ac(),iconURL:t.icon??ei(e)??ei(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=uw(d,s,r),y=await lc(n,p);try{await n.addToUserRealms(p)}catch{}return{realmUrl:p,created:!1,realmToken:y}}throw new Error(`Realm server returned ${a.status}: ${d}`)}let c=(await a.json())?.data?.id;if(typeof c!="string"||c.trim()==="")throw new Error(`Realm server response did not include a realm URL (data.id) for "${r}".`);let u=k(c),f=await lc(n,u);try{await n.addToUserRealms(u)}catch{}return t.waitForReady&&f&&await lw(u,f),{realmUrl:u,created:!0,realmToken:f}}async function lc(r,e){try{let t=await r.getOrRefreshServerToken();return await r.fetchAndStoreRealmToken(e,t)}catch{return}}async function lw(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 cw(r,e,t){ow.test(r)||(console.error("Error: realm name must contain only lowercase letters, numbers, and hyphens"),process.exit(1));try{let n=await aw(r,e,t),i=n.created?"created":"already exists";console.log(`${S}Realm ${i}:${m} ${C}${n.realmUrl}${m}`)}catch(n){console.error(`Error: ${n instanceof Error?n.message:String(n)}`),process.exit(1)}}function uw(r,e,t){let n=r.match(/'(https?:\/\/[^']+)'/);if(n)return k(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 gt=T(require("fs"));var Sc=require("child_process"),z=T(require("fs/promises")),B=T(require("path"));var V=T(require("fs/promises")),W=T(require("path")),ui=T(wc());var ai=class{value;next;constructor(e){this.value=e}},pt=class{#e;#t;#r;constructor(){this.clear()}enqueue(e){let t=new ai(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 li(r){let e=!1;if(typeof r=="object"&&({concurrency:r,rejectOnClear:e=!1}=r),Ec(r),typeof e!="boolean")throw new TypeError("Expected `rejectOnClear` to be a boolean");let t=new pt,n=0,i=()=>{n<r&&t.size>0&&(n++,t.dequeue().run())},s=()=>{n--,i()},o=async(c,u,f)=>{let d=(async()=>c(...f))();u(d);try{await d}catch{}s()},a=(c,u,f,d)=>{let p={reject:f};new Promise(y=>{p.run=y,t.enqueue(p)}).then(o.bind(void 0,c,u,d)),n<r&&i()},l=(c,...u)=>new Promise((f,d)=>{a(c,f,d,u)});return Object.defineProperties(l,{activeCount:{get:()=>n},pendingCount:{get:()=>t.size},clearQueue:{value(){if(!e){t.clear();return}let c=AbortSignal.abort().reason;for(;t.size>0;)t.dequeue().reject(c)}},concurrency:{get:()=>r,set(c){Ec(c),r=c,queueMicrotask(()=>{for(;n<r&&t.size>0;)i()})}},map:{async value(c,u){let f=Array.from(c,(d,p)=>this(u,d,p));return Promise.all(f)}}}),l}function Ec(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 Cw=ui.default.default||ui.default,Ow=new Set([".realm.json"]),ci=1e4,Pw=3e3;function F(r){let e=r.replace(/\\/g,"/").replace(/^\/+/,"");return Ow.has(e)}async function Rc(r){try{return await V.access(r),!0}catch{return!1}}function $c(r){try{return decodeURIComponent(r)}catch{return r}}var ht={CardSource:"application/vnd.card+source",DirectoryListing:"application/vnd.api+json",Mtimes:"application/vnd.api+json"},Tw=10,bc=new Set(["node_modules"]),le=class{constructor(e,t){this.options=e;this.authenticator=t;this.normalizedRealmUrl=this.normalizeRealmUrl(e.realmUrl)}normalizedRealmUrl;ignoreCache=new Map;remoteLimit=li(Tw);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.
|
|
72
|
+
${g}${n.errorCount} error(s) across ${n.filesWithErrors} of ${n.filesChecked} file(s)${m}`),n.errorCount>0&&process.exit(1)})}async function cw(r,e,t){let n=t?.profileManager??C();if(!n.getActiveProfile())throw new Error("No active profile. Run `boxel profile add` to create one.");let s=new URL(e,x(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 sc(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 cw(t.realm,e)}catch(i){console.error(`${h}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(`${g}Status:${m} ${n.status??"(no status)"}`),console.error(`${h}Error:${m} ${n.error}`)),n.ok||process.exit(1)})}async function uw(r,e){let t=e?.profileManager??C();if(!t.getActiveProfile())return{ok:!1,error:A};let i=e?.cancelPending??!1,s=`${x(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 oc(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 uw(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(`${S}Cancelled ${n} indexing jobs for ${e.realm}${m}`)}else console.error(`${h}Error:${m} ${t.error}`),process.exit(1)})}var fw=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"}),ac=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 ei(r){if(!r)return;let e=r.toLowerCase().replace(/[^a-z0-9]/g,"").replace(/^[0-9]+/,"");return fw[e.charAt(0)]}function lc(){let r=Math.floor(Math.random()*ac.length);return ac[r]}var mw=/^[a-z0-9-]+$/;function uc(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 hw(e,t,n)})}async function dw(r,e,t={}){let n=t.profileManager??C(),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??lc(),iconURL:t.icon??ei(e)??ei(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=gw(d,s,r),y=await cc(n,p);try{await n.addToUserRealms(p)}catch{}return{realmUrl:p,created:!1,realmToken:y}}throw new Error(`Realm server returned ${a.status}: ${d}`)}let c=(await a.json())?.data?.id;if(typeof c!="string"||c.trim()==="")throw new Error(`Realm server response did not include a realm URL (data.id) for "${r}".`);let u=x(c),f=await cc(n,u);try{await n.addToUserRealms(u)}catch{}return t.waitForReady&&f&&await pw(u,f),{realmUrl:u,created:!0,realmToken:f}}async function cc(r,e){try{let t=await r.getOrRefreshServerToken();return await r.fetchAndStoreRealmToken(e,t)}catch{return}}async function pw(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 hw(r,e,t){mw.test(r)||(console.error("Error: realm name must contain only lowercase letters, numbers, and hyphens"),process.exit(1));try{let n=await dw(r,e,t),i=n.created?"created":"already exists";console.log(`${S}Realm ${i}:${m} ${_}${n.realmUrl}${m}`)}catch(n){console.error(`Error: ${n instanceof Error?n.message:String(n)}`),process.exit(1)}}function gw(r,e,t){let n=r.match(/'(https?:\/\/[^']+)'/);if(n)return x(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 gt=T(require("fs"));var vc=require("child_process"),X=T(require("fs/promises")),B=T(require("path"));var V=T(require("fs/promises")),W=T(require("path")),ui=T(Ec());var ai=class{value;next;constructor(e){this.value=e}},pt=class{#e;#t;#r;constructor(){this.clear()}enqueue(e){let t=new ai(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 li(r){let e=!1;if(typeof r=="object"&&({concurrency:r,rejectOnClear:e=!1}=r),bc(r),typeof e!="boolean")throw new TypeError("Expected `rejectOnClear` to be a boolean");let t=new pt,n=0,i=()=>{n<r&&t.size>0&&(n++,t.dequeue().run())},s=()=>{n--,i()},o=async(c,u,f)=>{let d=(async()=>c(...f))();u(d);try{await d}catch{}s()},a=(c,u,f,d)=>{let p={reject:f};new Promise(y=>{p.run=y,t.enqueue(p)}).then(o.bind(void 0,c,u,d)),n<r&&i()},l=(c,...u)=>new Promise((f,d)=>{a(c,f,d,u)});return Object.defineProperties(l,{activeCount:{get:()=>n},pendingCount:{get:()=>t.size},clearQueue:{value(){if(!e){t.clear();return}let c=AbortSignal.abort().reason;for(;t.size>0;)t.dequeue().reject(c)}},concurrency:{get:()=>r,set(c){bc(c),r=c,queueMicrotask(()=>{for(;n<r&&t.size>0;)i()})}},map:{async value(c,u){let f=Array.from(c,(d,p)=>this(u,d,p));return Promise.all(f)}}}),l}function bc(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 Mw=ui.default.default||ui.default,Iw=new Set([".realm.json"]),ci=1e4,Nw=3e3;function D(r){let e=r.replace(/\\/g,"/").replace(/^\/+/,"");return Iw.has(e)}async function Rc(r){try{return await V.access(r),!0}catch{return!1}}function $c(r){try{return decodeURIComponent(r)}catch{return r}}var ht={CardSource:"application/vnd.card+source",DirectoryListing:"application/vnd.api+json",Mtimes:"application/vnd.api+json"},Fw=10,Sc=new Set(["node_modules"]),le=class{constructor(e,t){this.options=e;this.authenticator=t;this.normalizedRealmUrl=this.normalizeRealmUrl(e.realmUrl)}normalizedRealmUrl;ignoreCache=new Map;remoteLimit=li(Fw);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.
|
|
73
73
|
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.
|
|
74
|
-
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.remoteLimit(()=>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,c])=>{let f=c.meta.kind==="file",d=e?W.posix.join(e,l):l;return f?this.shouldIgnoreRemoteFile(d)?[]:[[d,!0]]:(async()=>{let p=await this.getRemoteFileList(d);return Array.from(p.entries())})()}));for(let l of a)for(let[c,u]of l)t.set(c,u)}}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:ht.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,""),c;try{c=decodeURIComponent(l)}catch{c=l}this.shouldIgnoreRemoteFile(c)||e.set(c,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=W.join(this.options.localDir,e),i;try{i=await V.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=W.join(n,o.name),l=e?W.posix.join(e,o.name):o.name;if(o.isDirectory()&&bc.has(o.name))return[];if(await this.shouldIgnoreFile(l,a))return[];if(o.isFile()){let c=await V.stat(a);return[[l,{path:a,mtime:c.mtimeMs}]]}else if(o.isDirectory()){let c=await this.getLocalFileListWithMtimes(l);return Array.from(c.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=W.join(this.options.localDir,e),i;try{i=await V.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=W.join(n,o.name),l=e?W.posix.join(e,o.name):o.name;if(o.isDirectory()&&bc.has(o.name))return[];if(await this.shouldIgnoreFile(l,a))return[];if(o.isFile())return[[l,a]];if(o.isDirectory()){let c=await this.getLocalFileList(l);return Array.from(c.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 V.readFile(t,"utf8"),i=this.buildFileUrl(e),s=await this.authenticator.authedRealmFetch(i,{method:"POST",headers:{"Content-Type":"text/plain;charset=UTF-8",Accept:ht.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(([c])=>!F(c));if(n.length===0)return{succeeded:[]};if(this.options.dryRun){for(let[c]of n)console.log(`[DRY RUN] Would upload ${c}`);return{succeeded:[]}}let i=await Promise.all(n.map(async([c,u])=>{let f=await V.readFile(u,"utf8");return{op:t.has(c)?"add":"update",href:this.buildFileUrl(c),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 c=await o.json(),u=new Map(n.map(([d])=>[this.buildFileUrl(d),d])),f=(c["atomic:results"]??[]).map(d=>d.data?.id).filter(d=>typeof d=="string").map(d=>$c(d)).map(d=>u.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(c=>{let f=(c.detail??"").match(/Resource (\S+) /),d=f?$c(f[1]):"";return{path:new Map(n.map(([y])=>[this.buildFileUrl(y),y])).get(d)??d,status:c.status??o.status,title:c.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:ht.CardSource}});if(!i.ok)throw new Error(`Failed to download: ${i.status} ${i.statusText}`);let s=await i.text(),o=W.dirname(t);await V.mkdir(o,{recursive:!0}),await V.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:ht.CardSource},signal:AbortSignal.timeout(ci)})}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 ${ci}ms, but ${e} is already gone on the realm; continuing`);return}throw new Error(`Timed out deleting ${e} after ${ci}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:ht.CardSource},signal:AbortSignal.timeout(Pw)});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 V.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=Cw(),s=e,o=this.options.localDir;for(;s.startsWith(o);){let a=W.join(s,".gitignore");if(await Rc(a))try{let u=await V.readFile(a,"utf8");i.add(u)}catch(u){console.warn(`Warning: Could not read .gitignore file at ${a}:`,u)}let l=W.join(s,".boxelignore");if(await Rc(l))try{let u=await V.readFile(l,"utf8");i.add(u)}catch(u){console.warn(`Warning: Could not read .boxelignore file at ${l}:`,u)}let c=W.dirname(s);if(c===s)break;s=c}return i})();return this.ignoreCache.set(e,n),n}async shouldIgnoreFile(e,t){let n=W.basename(e);if(n===".boxel-sync.json"||n.startsWith("."))return!0;let i=W.dirname(t),s=await this.getIgnoreInstance(i),o=e.replace(/\\/g,"/");return s.ignores(o)}shouldIgnoreRemoteFile(e){return!!W.basename(e).startsWith(".")}};async function fi(r){try{return await z.access(r),!0}catch{return!1}}var j=class{workspaceDir;gitDir;constructor(e){this.workspaceDir=B.resolve(e),this.gitDir=B.join(this.workspaceDir,".boxel-history")}async init(){await fi(this.gitDir)||await z.mkdir(this.gitDir,{recursive:!0});let e=B.join(this.gitDir,".git");await fi(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 fi(B.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=B.join(this.gitDir,i);try{await z.unlink(s)}catch(o){if(o.code!=="ENOENT")throw o}}})),await Promise.all(e.map(async i=>{let s=B.join(this.workspaceDir,i),o=B.join(this.gitDir,i),a=B.dirname(o);await z.mkdir(a,{recursive:!0}),await z.copyFile(s,o)}))}async getWorkspaceFiles(){let e=[],t=async(n,i="")=>{let s;try{s=await z.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(B.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 z.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(B.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(`
|
|
74
|
+
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.remoteLimit(()=>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,c])=>{let f=c.meta.kind==="file",d=e?W.posix.join(e,l):l;return f?this.shouldIgnoreRemoteFile(d)?[]:[[d,!0]]:(async()=>{let p=await this.getRemoteFileList(d);return Array.from(p.entries())})()}));for(let l of a)for(let[c,u]of l)t.set(c,u)}}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:ht.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,""),c;try{c=decodeURIComponent(l)}catch{c=l}this.shouldIgnoreRemoteFile(c)||e.set(c,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=W.join(this.options.localDir,e),i;try{i=await V.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=W.join(n,o.name),l=e?W.posix.join(e,o.name):o.name;if(o.isDirectory()&&Sc.has(o.name))return[];if(await this.shouldIgnoreFile(l,a))return[];if(o.isFile()){let c=await V.stat(a);return[[l,{path:a,mtime:c.mtimeMs}]]}else if(o.isDirectory()){let c=await this.getLocalFileListWithMtimes(l);return Array.from(c.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=W.join(this.options.localDir,e),i;try{i=await V.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=W.join(n,o.name),l=e?W.posix.join(e,o.name):o.name;if(o.isDirectory()&&Sc.has(o.name))return[];if(await this.shouldIgnoreFile(l,a))return[];if(o.isFile())return[[l,a]];if(o.isDirectory()){let c=await this.getLocalFileList(l);return Array.from(c.entries())}return[]}));for(let o of s)for(let[a,l]of o)t.set(a,l);return t}async uploadFile(e,t){if(D(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 V.readFile(t,"utf8"),i=this.buildFileUrl(e),s=await this.authenticator.authedRealmFetch(i,{method:"POST",headers:{"Content-Type":"text/plain;charset=UTF-8",Accept:ht.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(([c])=>!D(c));if(n.length===0)return{succeeded:[]};if(this.options.dryRun){for(let[c]of n)console.log(`[DRY RUN] Would upload ${c}`);return{succeeded:[]}}let i=await Promise.all(n.map(async([c,u])=>{let f=await V.readFile(u,"utf8");return{op:t.has(c)?"add":"update",href:this.buildFileUrl(c),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 c=await o.json(),u=new Map(n.map(([d])=>[this.buildFileUrl(d),d])),f=(c["atomic:results"]??[]).map(d=>d.data?.id).filter(d=>typeof d=="string").map(d=>$c(d)).map(d=>u.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(c=>{let f=(c.detail??"").match(/Resource (\S+) /),d=f?$c(f[1]):"";return{path:new Map(n.map(([y])=>[this.buildFileUrl(y),y])).get(d)??d,status:c.status??o.status,title:c.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:ht.CardSource}});if(!i.ok)throw new Error(`Failed to download: ${i.status} ${i.statusText}`);let s=await i.text(),o=W.dirname(t);await V.mkdir(o,{recursive:!0}),await V.writeFile(t,s,"utf8"),console.log(` Downloaded: ${e}`)}async deleteFile(e){if(D(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:ht.CardSource},signal:AbortSignal.timeout(ci)})}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 ${ci}ms, but ${e} is already gone on the realm; continuing`);return}throw new Error(`Timed out deleting ${e} after ${ci}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:ht.CardSource},signal:AbortSignal.timeout(Nw)});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 V.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=Mw(),s=e,o=this.options.localDir;for(;s.startsWith(o);){let a=W.join(s,".gitignore");if(await Rc(a))try{let u=await V.readFile(a,"utf8");i.add(u)}catch(u){console.warn(`Warning: Could not read .gitignore file at ${a}:`,u)}let l=W.join(s,".boxelignore");if(await Rc(l))try{let u=await V.readFile(l,"utf8");i.add(u)}catch(u){console.warn(`Warning: Could not read .boxelignore file at ${l}:`,u)}let c=W.dirname(s);if(c===s)break;s=c}return i})();return this.ignoreCache.set(e,n),n}async shouldIgnoreFile(e,t){let n=W.basename(e);if(n===".boxel-sync.json"||n.startsWith("."))return!0;let i=W.dirname(t),s=await this.getIgnoreInstance(i),o=e.replace(/\\/g,"/");return s.ignores(o)}shouldIgnoreRemoteFile(e){return!!W.basename(e).startsWith(".")}};async function fi(r){try{return await X.access(r),!0}catch{return!1}}var j=class{workspaceDir;gitDir;constructor(e){this.workspaceDir=B.resolve(e),this.gitDir=B.join(this.workspaceDir,".boxel-history")}async init(){await fi(this.gitDir)||await X.mkdir(this.gitDir,{recursive:!0});let e=B.join(this.gitDir,".git");await fi(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 fi(B.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=B.join(this.gitDir,i);try{await X.unlink(s)}catch(o){if(o.code!=="ENOENT")throw o}}})),await Promise.all(e.map(async i=>{let s=B.join(this.workspaceDir,i),o=B.join(this.gitDir,i),a=B.dirname(o);await X.mkdir(a,{recursive:!0}),await X.copyFile(s,o)}))}async getWorkspaceFiles(){let e=[],t=async(n,i="")=>{let s;try{s=await X.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(B.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 X.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(B.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(`
|
|
75
75
|
`)){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]",c=`[${e}]`,u=`${l} ${c} ${o}${a?`
|
|
76
76
|
|
|
77
77
|
`+a:""}`;await this.git("commit","-m",u);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 c=`${i}: ${t.length} files (${l.join(", ")})`,u=[];return s.length>0&&(u.push("Added:"),s.forEach(f=>u.push(` + ${f.file}`))),o.length>0&&(u.push("Modified:"),o.forEach(f=>u.push(` ~ ${f.file}`))),a.length>0&&(u.push("Deleted:"),a.forEach(f=>u.push(` - ${f.file}`))),{message:c,description:u.join(`
|
|
78
78
|
`)}}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(`
|
|
79
79
|
`).filter(o=>!(o.split("|")[2]??"").startsWith("[init]"));return Promise.all(s.map(o=>this.parseCheckpointLine(o,i)))}async parseCheckpointLine(e,t){let[n,i,s,o]=e.split("|"),a=s.includes("[MAJOR]"),l=s.includes("[local]")?"local":s.includes("[remote]")?"remote":"manual",c=s.replace(/\[(MAJOR|minor)\]\s*/i,"").replace(/\[(local|remote|manual)\]\s*/i,""),u=await this.getCommitStats(n),f=t.get(n),d=!!f;return{hash:n,shortHash:i,message:c,description:"",date:new Date(o),isMajor:a,source:l,isMilestone:d,milestoneName:f,...u}}async getCommitStats(e){try{let n=(await this.git("show","--stat","--format=",e)).trim().split(`
|
|
80
80
|
`),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(`
|
|
81
|
-
`).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=B.join(this.gitDir,o);try{await
|
|
81
|
+
`).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=B.join(this.gitDir,o);try{await X.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(!D(o)&&!i.has(o)){let a=B.join(this.workspaceDir,o);try{await X.unlink(a)}catch(l){if(l.code!=="ENOENT")throw l}}})),await Promise.all(n.map(async o=>{if(D(o))return;let a=B.join(this.gitDir,o),l=B.join(this.workspaceDir,o),c=B.dirname(l);await X.mkdir(c,{recursive:!0}),await X.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(`
|
|
82
82
|
`).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(`
|
|
83
83
|
`).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(){if(!await this.isInitialized())return[];let e=await this.getAllMilestones();if(e.size===0)return[];let n=await this.git("log","--no-walk","--format=%H|%h|%s|%aI|%an",...e.keys());return n.trim()?Promise.all(n.trim().split(`
|
|
84
|
-
`).map(i=>this.parseCheckpointLine(i,e))):[]}git(...e){return new Promise((t,n)=>{let i=(0,
|
|
84
|
+
`).map(i=>this.parseCheckpointLine(i,e))):[]}git(...e){return new Promise((t,n)=>{let i=(0,vc.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 hr(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 xc=100;function gr(r){return r instanceof Error?r.message:String(r)}async function Dw(r,e){if(!gt.existsSync(r))return{ok:!1,error:`Directory not found: ${r}`};try{let t=new j(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: ${gr(t)}`}}}async function Uw(r,e){if(!gt.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 j(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: ${gr(n)}`}}}async function jw(r,e,t){if(!gt.existsSync(r))return{ok:!1,error:`Directory not found: ${r}`};try{let n=new j(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=hr(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: ${gr(n)}`}}}async function qw(r,e){if(!gt.existsSync(r))return{ok:!1,error:`Directory not found: ${r}`};try{let t=new j(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: ${gr(t)}`}}}function Gw(r){return r==="local"?`${S}LOCAL${m}`:r==="remote"?`${_}SERVER${m}`:`${ae}MANUAL${m}`}function kc(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 Hw(r,e,t){if(r.length===0){console.log("No checkpoints found.");return}console.log(`
|
|
85
85
|
${Z}Checkpoint History${m}
|
|
86
|
-
`);let n=String(r.length).length;r.forEach((i,s)=>{let o=s+1,a=`${g}${String(o).padStart(n," ")}${m}`,l=i.isMajor?`${P}[MAJOR]${m}`:`${g}[minor]${m}`,c=i.isMilestone?`${P}\u2B50${m} ${ae}[${i.milestoneName}]${m} `:"";console.log(`${a} ${P}${i.shortHash}${m} ${c}${
|
|
87
|
-
`)}),e&&console.log(`${g}Showing first ${t} checkpoints. Pass --limit <n> to see more.${m}`),console.log(`${g}Restore: boxel realm history <local-dir> -r <ref>${m}`)}function
|
|
88
|
-
${Z}Restoring to:${m} ${P}${o.shortHash}${m} - ${o.message}`),console.log(`${g}${
|
|
89
|
-
`);let l=await te(`${P}This will overwrite current files. Continue? (y/N) ${m}`);if(!/^y/i.test(l)){console.log(`${g}Restore cancelled.${m}`);return}}let a=await
|
|
86
|
+
`);let n=String(r.length).length;r.forEach((i,s)=>{let o=s+1,a=`${g}${String(o).padStart(n," ")}${m}`,l=i.isMajor?`${P}[MAJOR]${m}`:`${g}[minor]${m}`,c=i.isMilestone?`${P}\u2B50${m} ${ae}[${i.milestoneName}]${m} `:"";console.log(`${a} ${P}${i.shortHash}${m} ${c}${Gw(i.source)} ${l} ${i.message} ${g}(${i.filesChanged} files)${m}`),console.log(` ${g}${kc(i.date)}${m}
|
|
87
|
+
`)}),e&&console.log(`${g}Showing first ${t} checkpoints. Pass --limit <n> to see more.${m}`),console.log(`${g}Restore: boxel realm history <local-dir> -r <ref>${m}`)}function Ww(r){if(r===void 0)return xc;if(!/^\d+$/.test(r))return null;let e=parseInt(r,10);return e>0?e:null}function Ie(r){console.error(`${h}Error:${m} ${r}`),process.exit(1)}function _c(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: ${xc})`).action(async(e,t)=>{t.restore!==void 0&&t.message!==void 0&&Ie("Only one of --restore or --message may be specified.");let n=Ww(t.limit);if(n===null&&Ie("--limit must be a positive integer."),t.message!==void 0){let s=await Uw(e,t.message);s.ok||Ie(s.error),console.log(`${S}\u2713${m} Checkpoint created: ${P}${s.created.shortHash}${m} ${s.created.message}`);return}if(t.restore!==void 0){let s=await jw(e,t.restore,n);s.ok||Ie(s.error);let o=s.target;if(!t.yes){process.stdin.isTTY||Ie("--restore overwrites local files. Pass --yes to confirm in non-interactive mode."),console.log(`
|
|
88
|
+
${Z}Restoring to:${m} ${P}${o.shortHash}${m} - ${o.message}`),console.log(`${g}${kc(o.date)}${m}
|
|
89
|
+
`);let l=await te(`${P}This will overwrite current files. Continue? (y/N) ${m}`);if(!/^y/i.test(l)){console.log(`${g}Restore cancelled.${m}`);return}}let a=await qw(e,o.hash);a.ok||Ie(a.error),console.log(`${S}\u2713${m} Restored to ${P}${o.shortHash}${m} ${o.message}`),console.log(`${g}Run 'boxel realm sync <local-dir> <realm-url> --prefer-local' to push the restored state to the realm.${m}`);return}let i=await Dw(e,n);i.ok||Ie(i.error),Hw(i.checkpoints,i.truncated,n)})}var Vw="--all-accessible and --hidden are mutually exclusive";async function Bw(r={}){if(r.allAccessible&&r.hidden)return{realms:[],error:Vw};let e=r.profileManager??C(),t=e.getActiveProfile();if(!t)return{realms:[],error:A};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 u=await i.text();return{realms:[],error:`Realm auth lookup failed: ${i.status} ${u}`}}let s=await i.json(),o=Object.keys(s).map(x),a;try{a=await e.getUserRealms()}catch(u){return{realms:[],error:`Failed to load UI realm list: ${u instanceof Error?u.message:String(u)}`}}let l=new Set(a.map(x)),c=o.map(u=>({url:u,hidden:!l.has(u)}));return r.allAccessible||(r.hidden?c=c.filter(u=>u.hidden):c=c.filter(u=>!u.hidden)),c.sort((u,f)=>u.url.localeCompare(f.url)),{realms:c}}function Cc(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 Bw({allAccessible:e.allAccessible,hidden:e.hidden})}catch(n){console.error(`${h}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(`${h}Error:${m} ${t.error}`),process.exit(1)),t.realms.length===0){console.log(`${g}No realms found.${m}`);return}console.log(`${Z}${t.realms.length} realm(s):${m}`);for(let n of t.realms){let i=n.hidden?` ${g}(hidden)${m}`:"";console.log(` ${_}${n.url}${m}${i}`)}})}var wr=T(require("fs"));var mi=100;function Er(r){return r instanceof Error?r.message:String(r)}function Yw(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"}async function Oc(r,e,t){try{let n=new j(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=hr(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 checkpoints: ${Er(n)}`}}}async function Jw(r){if(!wr.existsSync(r))return{ok:!1,error:`Directory not found: ${r}`};try{let e=new j(r);return await e.isInitialized()?{ok:!0,milestones:await e.getMilestones()}:{ok:!0,milestones:[]}}catch(e){return{ok:!1,error:`Failed to read milestones: ${Er(e)}`}}}async function zw(r,e,t,n){if(!wr.existsSync(r))return{ok:!1,error:`Directory not found: ${r}`};let i=t.trim();if(!i)return{ok:!1,error:"--name must not be empty."};let s=await Oc(r,e,n);if(!s.ok)return s;try{let o=new j(r);if(!await o.markMilestone(s.target.hash,i))return{ok:!1,error:"Could not mark milestone. The checkpoint may already have one."};let c=(await o.getCheckpoints(n)).find(u=>u.hash===s.target.hash);return c?{ok:!0,marked:c}:{ok:!1,error:"Milestone created but checkpoint could not be re-read."}}catch(o){return{ok:!1,error:`Failed to mark milestone: ${Er(o)}`}}}async function Xw(r,e,t){if(!wr.existsSync(r))return{ok:!1,error:`Directory not found: ${r}`};let n=await Oc(r,e,t);if(!n.ok)return n;let i=n.target;if(!i.isMilestone)return{ok:!1,error:`Checkpoint ${i.shortHash} is not marked as a milestone.`};try{return{ok:!0,removed:await new j(r).unmarkMilestone(i.hash)}}catch(s){return{ok:!1,error:`Failed to remove milestone: ${Er(s)}`}}}async function Kw(r,e={}){if(e.mark!==void 0&&e.remove!==void 0)return{ok:!1,error:"Only one of --mark or --remove may be specified."};if(e.limit!==void 0&&(!Number.isInteger(e.limit)||e.limit<=0))return{ok:!1,error:"limit must be a positive integer."};let t=e.limit??mi;if(e.mark!==void 0){if(e.name===void 0)return{ok:!1,error:"--name is required when using --mark."};let i=await zw(r,e.mark,e.name,t);return i.ok?{ok:!0,marked:i.marked}:{ok:!1,error:i.error}}if(e.remove!==void 0){let i=await Xw(r,e.remove,t);return i.ok?{ok:!0,removed:i.removed}:{ok:!1,error:i.error}}let n=await Jw(r);return n.ok?{ok:!0,milestones:n.milestones}:{ok:!1,error:n.error}}function Qw(r,e){if(r.length===0){console.log(`
|
|
90
90
|
No milestones marked yet.
|
|
91
|
-
`),console.log(`Use ${
|
|
91
|
+
`),console.log(`Use ${_}boxel realm milestone <local-dir> --mark <ref> --name <name>${m} to mark a checkpoint.`),console.log(`Use ${_}boxel realm history <local-dir>${m} to see available checkpoints.
|
|
92
92
|
`);return}console.log(`
|
|
93
93
|
${Z}Milestones${m} ${g}(${e})${m}
|
|
94
|
-
`);for(let t of r){let n=t.source==="local"?"\u2191":t.source==="remote"?"\u2193":"\u25CF",i=t.source==="local"?S:t.source==="remote"?
|
|
95
|
-
${S}\u2713${m} ${P}\u2B50${m} Milestone created: ${ae}${s.milestoneName}${m}`),console.log(` Checkpoint: ${P}${s.shortHash}${m} ${s.message}`),console.log();return}if(i.removed!==void 0){console.log(`${S}\u2713${m} Milestone removed`);return}
|
|
96
|
-
Checkpoint created before deletion: ${c.shortHash}`)}let o=await Promise.all(Array.from(t.keys()).map(l=>this.remoteLimit(async()=>{try{let c=
|
|
94
|
+
`);for(let t of r){let n=t.source==="local"?"\u2191":t.source==="remote"?"\u2193":"\u25CF",i=t.source==="local"?S:t.source==="remote"?_:ae;console.log(` ${P}\u2B50${m} ${P}${t.shortHash}${m} ${i}${n}${m} ${ae}[${t.milestoneName}]${m} ${t.message}`),console.log(` ${g}${Yw(t.date)}${m}`)}console.log()}function Zw(r){if(r===void 0)return mi;if(!/^\d+$/.test(r))return null;let e=parseInt(r,10);return e>0?e:null}function yr(r){console.error(`${h}Error:${m} ${r}`),process.exit(1)}function Pc(r){r.command("milestone").description("List, mark, or remove milestones in the local .boxel-history/ checkpoint log").argument("<local-dir>","The local workspace directory").option("--mark <ref>","Mark a checkpoint as a milestone (1-based index, short hash, or full hash)").option("--name <name>","Name for the milestone (required with --mark)").option("--remove <ref>","Remove the milestone tag from a checkpoint (1-based index, short hash, or full hash)").option("--limit <n>",`Maximum number of checkpoints to consider for ref resolution (default: ${mi})`).option("--json","Output result as JSON").action(async(e,t)=>{t.mark!==void 0&&t.remove!==void 0&&yr("Only one of --mark or --remove may be specified.");let n=Zw(t.limit);n===null&&yr("--limit must be a positive integer."),t.mark!==void 0&&t.name===void 0&&yr("--name is required when using --mark.");let i=await Kw(e,{mark:t.mark,name:t.name,remove:t.remove,limit:n});if(t.json){M.output(JSON.stringify(i,null,2)),i.ok||process.exit(1);return}if(i.ok||yr(i.error),i.marked){let s=i.marked;console.log(`
|
|
95
|
+
${S}\u2713${m} ${P}\u2B50${m} Milestone created: ${ae}${s.milestoneName}${m}`),console.log(` Checkpoint: ${P}${s.shortHash}${m} ${s.message}`),console.log();return}if(i.removed!==void 0){console.log(`${S}\u2713${m} Milestone removed`);return}Qw(i.milestones,e)})}async function di(r,e={}){let t=x(r),n=e.profileManager??C(),i=n.getActiveProfile();if(!i)return{publishedRealmURL:t,unpublished:!1,error:A};let s=i.profile.realmServerUrl.replace(/\/$/,""),o;try{o=await n.authedRealmServerFetch(`${s}/_unpublish-realm`,{method:"POST",headers:{Accept:"application/vnd.api+json","Content-Type":"application/json"},body:JSON.stringify({publishedRealmURL:t})})}catch(c){return{publishedRealmURL:t,unpublished:!1,error:`Failed to reach realm server: ${c instanceof Error?c.message:String(c)}`}}if(o.ok)return{publishedRealmURL:t,unpublished:!0};let a=await eE(o);return o.status===404||o.status===422&&/not found/i.test(a)?e.tolerateMissing?{publishedRealmURL:t,unpublished:!1,notFound:!0}:{publishedRealmURL:t,unpublished:!1,notFound:!0,error:`Published realm ${t} is not currently published`}:{publishedRealmURL:t,unpublished:!1,error:`Realm server returned ${o.status}: ${a.slice(0,500)}`}}async function eE(r){try{return await r.text()}catch{return"<no response body>"}}function Tc(r){r.command("unpublish").description("Unpublish a published realm by its public-facing URL").argument("<published-realm-url>","URL of the published realm to remove").option("--tolerate-missing","Exit successfully when the realm is already unpublished").action(async(e,t)=>{let n=await di(e,{tolerateMissing:t.tolerateMissing===!0});if(n.error&&(console.error(`${h}Error:${m} ${n.error}`),process.exit(1)),n.notFound){console.log(`Already unpublished: ${_}${n.publishedRealmURL}${m}`);return}console.log(`${S}Unpublished:${m} ${_}${n.publishedRealmURL}${m}`)})}var Mc=3e5,tE=1e3;async function rE(r,e,t={}){let n=t.profileManager??C(),i=n.getActiveProfile();if(!i)throw new Error(A);let s=x(r),o=x(e),a=i.profile.realmServerUrl.replace(/\/$/,""),l=await Ac(n,a,s,o);if((l.status===400||l.status===409)&&t.republish!==!1){let d=await Lc(l);console.log(`Publish returned ${l.status} (${d.slice(0,200)}). Unpublishing and retrying.`);let p=await di(o,{profileManager:n,tolerateMissing:!0});if(!p.unpublished&&!p.notFound)throw new Error(`Conflict on publish; unpublish-then-retry also failed: ${p.error??"unknown"}`);l=await Ac(n,a,s,o)}if(l.status!==200&&l.status!==201&&l.status!==202){let d=await Lc(l);throw new Error(`Publish failed: HTTP ${l.status}: ${d.slice(0,1e3)}`)}let c=await l.json(),u=c?.data?.attributes;if(!u?.publishedRealmURL)throw new Error(`Publish response missing data.attributes.publishedRealmURL: ${JSON.stringify(c).slice(0,500)}`);let f={publishedRealmURL:x(u.publishedRealmURL),publishedRealmId:c.data.id,lastPublishedAt:u.lastPublishedAt,status:u.status};if(t.waitForReady!==!1){let d=t.timeoutMs??Mc,p;try{let y=await n.getOrRefreshServerToken();p=await n.fetchAndStoreRealmToken(f.publishedRealmURL,y)}catch{}await nE(f.publishedRealmURL,p,d)}return f}async function Ac(r,e,t,n){return r.authedRealmServerFetch(`${e}/_publish-realm`,{method:"POST",headers:{Accept:"application/vnd.api+json","Content-Type":"application/json"},body:JSON.stringify({sourceRealmURL:t,publishedRealmURL:n})})}async function nE(r,e,t){let n=new URL("_readiness-check",r).href,i=Date.now(),s;for(;Date.now()-i<t;){try{let a={Accept:"application/vnd.api+json"};e&&(a.Authorization=e);let l=await fetch(n,{headers:a});if(l.ok)return;s=`HTTP ${l.status}`}catch(a){s=a instanceof Error?a.message:String(a)}let o=t-(Date.now()-i);if(o<=0)break;await new Promise(a=>setTimeout(a,Math.min(tE,o)))}throw new Error(`Timed out after ${t}ms waiting for ${r} to pass readiness check${s?`: ${s}`:""}`)}async function Lc(r){try{return await r.text()}catch{return"<no response body>"}}function iE(r){return{waitForReady:r.wait!==!1,timeoutMs:r.timeout,republish:r.republish!==!1}}function Ic(r){r.command("publish").description("Publish a source realm to a published-realm URL, polling readiness until ready").argument("<source-realm-url>","URL of the source realm to publish").argument("<published-realm-url>","Public-facing URL the published copy will serve at").option("--no-wait","Return as soon as the server accepts the publish").option("--timeout <ms>",`Readiness-poll timeout in milliseconds (default: ${Mc})`,sE).option("--no-republish","Do not auto-unpublish + retry when the server returns 400/409").action(async(e,t,n)=>{try{let i=await rE(e,t,iE(n));console.log(`${S}Published:${m} ${_}${i.publishedRealmURL}${m}`)}catch(i){console.error(`${h}Error:${m} ${i instanceof Error?i.message:String(i)}`),process.exit(1)}})}function sE(r){let e=Number.parseInt(r,10);if(!Number.isFinite(e)||e<0||String(e)!==r.trim())throw new Error("--timeout must be a non-negative integer (milliseconds).");return e}var Nc=T(In()),Fc="realm_server";function oE(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 aE(r,e=Fc){return`@${e}:${oE(r)}`}function lE(r){return new URL(r).origin+"/"}function cE(r){try{return new URL(r).href.replace(/\/+$/,"")+"/"}catch{throw new Error(`Invalid realm URL: ${r}`)}}var br=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??Fc,this.#r=e.botUserId,this.#i=e.expiresIn??"7d"}buildClaims(e){let t=cE(e);return{user:this.#r??aE(t,this.#t),realm:t,sessionRoom:void 0,permissions:[],realmServerURL:lE(t)}}mintTokenForRealm(e){let t=this.buildClaims(e),n=this.#n.get(t.realm);if(n)return n;let i=Nc.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 br({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??C();return e.getActiveProfile()?{ok:!0,authenticator:e,mode:"profile"}:{ok:!1,error:A}}var Rr=T(require("fs/promises")),Dc=T(require("path")),pi=class extends le{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 Rr.access(this.options.localDir)}catch{console.log(`[DRY RUN] Would create directory: ${this.options.localDir}`)}else await Rr.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 j(this.options.localDir);if(i.size>0&&!this.options.dryRun){let l=Array.from(i).map(u=>({file:u,status:"deleted"})),c=await s.createCheckpoint("remote",l,`Pre-delete checkpoint: ${i.size} files not on server`);c&&console.log(`
|
|
96
|
+
Checkpoint created before deletion: ${c.shortHash}`)}let o=await Promise.all(Array.from(t.keys()).map(l=>this.remoteLimit(async()=>{try{let c=Dc.join(this.options.localDir,l);return await this.downloadFile(l,c),l}catch(c){return this.hasError=!0,console.error(`Error downloading ${l}:`,c),null}})));this.downloadedFiles=o.filter(l=>l!==null);let a=[];if(i.size>0&&(console.log(`
|
|
97
97
|
Deleting ${i.size} local files that don't exist in realm...`),a=(await Promise.all(Array.from(i).map(async c=>{try{let u=n.get(c);return u?(await this.deleteLocalFile(u),console.log(` Deleted: ${c}`),c):null}catch(u){return this.hasError=!0,console.error(`Error deleting local file ${c}:`,u),null}}))).filter(c=>c!==null)),!this.options.dryRun&&this.downloadedFiles.length+a.length>0){let l=[...this.downloadedFiles.map(u=>({file:u,status:"modified"})),...a.map(u=>({file:u,status:"deleted"}))],c=await s.createCheckpoint("remote",l);if(c){let u=c.isMajor?"[MAJOR]":"[minor]";console.log(`
|
|
98
|
-
Checkpoint created: ${c.shortHash} ${u} ${c.message}`)}}console.log("Pull completed")}};function
|
|
99
|
-
Checkpoint created: ${d.shortHash} ${p} ${d.message}`)}}console.log("Push completed")}};function Ic(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 ge(n.realmSecretSeed===!0);await eE(e,t,{delete:n.delete,dryRun:n.dryRun,force:n.force,realmSecretSeed:i})})}async function eE(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 Je(r)||(console.error(`Local directory does not exist: ${r}`),process.exit(1));try{let i=new gi({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 Nc(r){let e=k(r.realmUrl.trim()),t=r.profileManager??_(),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(k),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 c=n.profile.realmServerUrl.replace(/\/$/,""),u;try{u=await t.authedRealmServerFetch(`${c}/_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(!u.ok){let d=await tE(u),p=u.status===403?`You do not own this realm and cannot delete it on the server. Server returned 403: ${d}`:`Realm server returned ${u.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 tE(r){try{return await r.text()}catch{return"<no response body>"}}function Dc(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=k(e.trim()),i=await Nc({realmUrl:n,dryRun:!0});if(i.error&&!i.notInList&&(console.error(`${h}Error:${m} ${i.error}`),process.exit(1)),i.notInList&&(console.error(`${h}Error:${m} ${i.error}`),process.exit(1)),console.log(`Remove target: ${C}${i.realmUrl}${m}`),console.log(`${g}app.boxel.realms: ${i.previousCount} -> ${i.nextCount}${m}`),t.dryRun){console.log(`${g}[DRY RUN] No server delete or Matrix changes sent.${m}`);return}if(!t.yes){process.stdin.isTTY||(console.error(`${h}Error:${m} stdin is not a TTY. Pass --yes to confirm in non-interactive mode.`),process.exit(1));let o=await te("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(`${g}Cancelled.${m}`);return}}let s=await Nc({realmUrl:n});(s.error||!s.removed)&&(console.error(`${h}Error:${m} ${s.error??"Removal did not complete."}`),s.serverDeleted&&!s.unlinked&&console.error(`${g}The realm is gone, but your account_data still references ${s.realmUrl}.${m}`),process.exit(1)),console.log(`${S}Removed:${m} ${C}${s.realmUrl}${m}`)})}var Xe=T(require("fs/promises")),yt=T(require("path"));function br(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 Sr(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 Fc(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 Uc(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 rE=new Set(["node_modules",".git",".boxel-history",".cache",".vscode","dist","build","tmp"]),nE=6;function iE(r,e){return r==="unchanged"&&e==="unchanged"||r==="deleted"&&e==="deleted"?null:r==="unchanged"&&e==="added"?"new-remote":r==="unchanged"&&e==="changed"?"modified-remote":r==="unchanged"&&e==="deleted"?"deleted-remote":r==="added"&&e==="unchanged"?"new-local":r==="changed"&&e==="unchanged"?"modified-local":r==="deleted"&&e==="unchanged"?"deleted-local":r==="changed"&&e==="changed"||r==="added"&&e==="added"||r==="changed"&&e==="added"||r==="added"&&e==="changed"||r==="changed"&&e==="deleted"||r==="deleted"&&e==="changed"?"conflict":r==="added"&&e==="deleted"?"new-local":r==="deleted"&&e==="added"?"new-remote":null}var yi=class extends le{constructor(t,n,i){super(t,i);this.statusOptions=t;this.loadedManifest=n}changes=[];pulled=[];hasError=!1;error;remoteMtimes=new Map;async sync(){let t,n;try{[t,this.remoteMtimes,n]=await Promise.all([this.getLocalFileListWithMtimes(),this.getRemoteMtimes(),this.getRemoteFileList()])}catch(a){this.hasError=!0,this.error=a instanceof Error?`Failed to fetch realm state: ${a.message}`:`Failed to fetch realm state: ${String(a)}`;return}if(n&&this.remoteMtimes.size===0&&n.size>0)for(let[a]of n)this.remoteMtimes.set(a,0);let i=new Map;for(let[a,l]of t)i.set(a,l.path);let s=new Map;await Promise.all(Array.from(i.entries()).map(async([a,l])=>{F(a)||s.set(a,await re(l))}));let o=new Set;for(let a of i.keys())o.add(a);for(let a of this.remoteMtimes.keys())o.add(a);for(let a of Object.keys(this.loadedManifest.files))o.add(a);if(this.loadedManifest.remoteMtimes)for(let a of Object.keys(this.loadedManifest.remoteMtimes))o.add(a);for(let a of o){if(F(a))continue;let l=br(a,s,this.loadedManifest),c=Sr(a,this.remoteMtimes,this.loadedManifest),u=iE(l,c);u!==null&&this.changes.push({file:a,status:u})}this.changes.sort((a,l)=>a.file.localeCompare(l.file)),this.statusOptions.pull&&await this.performSafePull()}async performSafePull(){let t=this.changes.filter(i=>i.status==="new-remote"||i.status==="modified-remote");if(t.length===0)return;let n=[];for(let i of t){let s=yt.join(this.options.localDir,i.file);try{await this.downloadFile(i.file,s),this.pulled.push(i.file);let o=await re(s);this.loadedManifest.files[i.file]=o;let a=this.remoteMtimes.get(i.file);a!==void 0&&(this.loadedManifest.remoteMtimes=this.loadedManifest.remoteMtimes??{},this.loadedManifest.remoteMtimes[i.file]=a)}catch(o){this.hasError=!0;let a=o instanceof Error?o.message:String(o);n.push({file:i.file,message:a}),console.error(` ${h}\u2717 ${i.file}${m} (${a})`)}}n.length>0&&(this.error=`Failed to pull ${n.length} file(s): ${n.map(i=>`${i.file} (${i.message})`).join("; ")}`),this.pulled.length>0&&await ke(this.options.localDir,this.loadedManifest)}};async function jc(r,e){let t={localDir:r,realmUrl:"",changes:[],pulled:[],inSync:!1,hasError:!1},n=yt.join(r,".boxel-sync.json");if(!await Je(n))return{...t,hasError:!0,error:`No .boxel-sync.json found in ${r}. Run: boxel realm sync ${r} <realm-url>`};let i=await we(r);if(!i)return{...t,hasError:!0,error:`Malformed .boxel-sync.json in ${r}`};let s;try{s=(await Xe.stat(n)).mtimeMs}catch{}let o;if(e.authenticator)o=e.authenticator;else{let l=ye({realmUrl:i.realmUrl,realmSecretSeed:e.realmSecretSeed,profileManager:e.profileManager});if(!l.ok)return{...t,realmUrl:i.realmUrl,manifestMtime:s,hasError:!0,error:l.error};o=l.authenticator}let a=new yi({realmUrl:i.realmUrl,localDir:r,pull:e.pull},i,o);return await a.sync(),{localDir:r,realmUrl:i.realmUrl,manifestMtime:s,changes:a.changes,pulled:a.pulled.slice().sort(),inSync:!a.hasError&&a.changes.length===0,hasError:a.hasError,error:a.error}}async function sE(r,e){let t=[];async function n(i,s){if(s>e)return;let o;try{o=await Xe.readdir(i,{withFileTypes:!0})}catch{return}if(o.some(l=>l.isFile()&&l.name===".boxel-sync.json")){t.push(i);return}for(let l of o)l.isDirectory()&&(rE.has(l.name)||await n(yt.join(i,l.name),s+1))}return await n(r,0),t.sort(),t}async function oE(r,e){if(e.pull)return{rootDir:r,workspaces:[],hasError:!0,error:"Cannot use --pull with --all"};let t=process.env.BOXEL_STATUS_ALL_MAX_DEPTH,n=t!==void 0?Number(t):NaN,i=Number.isFinite(n)&&n>=0?n:nE,s=await sE(r,i),o=[],a=!1;for(let l of s){let c=yt.join(l,".boxel-sync.json"),u;try{u=await Xe.readFile(c,"utf8")}catch{o.push({localDir:l,realmUrl:"",changes:[],pulled:[],inSync:!1,hasError:!0,skipped:"no-manifest"}),a=!0;continue}let f;try{f=JSON.parse(u)}catch{f=void 0}if(!hi(f)){o.push({localDir:l,realmUrl:"",changes:[],pulled:[],inSync:!1,hasError:!0,skipped:"malformed"}),a=!0;continue}let d=await jc(l,{profileManager:e.profileManager,realmSecretSeed:e.realmSecretSeed,authenticator:e.authenticator}),p={...d};d.hasError&&(p.skipped="fetch-failed",a=!0),o.push(p)}return{rootDir:r,workspaces:o,hasError:a}}function aE(r){if(r.hasError&&r.error){console.error(`${h}Error:${m} ${r.error}`);return}if(console.log(`Realm: ${r.realmUrl}`),console.log(`Local: ${r.localDir}`),r.manifestMtime&&console.log(`${g}Manifest updated:${m} ${new Date(r.manifestMtime).toISOString()}`),console.log(""),r.changes.length===0){console.log(`${S}\u2713 In sync${m}`);return}let e={"new-remote":[],"modified-remote":[],"new-local":[],"modified-local":[],conflict:[],"deleted-local":[],"deleted-remote":[]};for(let t of r.changes)e[t.status].push(t.file);if(e["new-remote"].length>0){console.log(`${C}\u2193 New on remote (${e["new-remote"].length}):${m}`);for(let t of e["new-remote"])console.log(` + ${t}`);console.log("")}if(e["modified-remote"].length>0){console.log(`${C}\u2193 Modified on remote (${e["modified-remote"].length}):${m}`);for(let t of e["modified-remote"])console.log(` ~ ${t}`);console.log("")}if(e["new-local"].length>0){console.log(`${S}\u2191 New locally (${e["new-local"].length}):${m}`);for(let t of e["new-local"])console.log(` + ${t}`);console.log("")}if(e["modified-local"].length>0){console.log(`${S}\u2191 Modified locally (${e["modified-local"].length}):${m}`);for(let t of e["modified-local"])console.log(` ~ ${t}`);console.log("")}if(e.conflict.length>0){console.log(`${P}\u26A0 Conflicts (${e.conflict.length}):${m}`);for(let t of e.conflict)console.log(` ! ${t}`);console.log("")}if(e["deleted-local"].length>0){console.log(`${h}- Deleted locally (${e["deleted-local"].length}):${m}`);for(let t of e["deleted-local"])console.log(` - ${t}`);console.log("")}if(e["deleted-remote"].length>0){console.log(`${h}- Deleted on remote (${e["deleted-remote"].length}):${m}`);for(let t of e["deleted-remote"])console.log(` - ${t}`);console.log("")}if(r.pulled.length>0){console.log(`${C}Pulled ${r.pulled.length} file(s):${m}`);for(let t of r.pulled)console.log(` \u2713 ${t}`)}}function lE(r){if(r.error){console.error(`${h}Error:${m} ${r.error}`);return}if(r.workspaces.length===0){console.log(`No .boxel-sync.json directories found under ${r.rootDir}.`);return}for(let e of r.workspaces){if(e.skipped){console.log(`${P}${e.localDir}${m} [${e.skipped}]`),e.error&&console.log(` ${g}${e.error}${m}`),console.log("");continue}let t={newRemote:0,modRemote:0,newLocal:0,modLocal:0,conflict:0,delLocal:0,delRemote:0};for(let n of e.changes)n.status==="new-remote"?t.newRemote++:n.status==="modified-remote"?t.modRemote++:n.status==="new-local"?t.newLocal++:n.status==="modified-local"?t.modLocal++:n.status==="conflict"?t.conflict++:n.status==="deleted-local"?t.delLocal++:n.status==="deleted-remote"&&t.delRemote++;if(console.log(`${e.localDir} ${g}${e.realmUrl}${m}`),e.inSync)console.log(` ${S}\u2713 in sync${m}`);else{let n=[];t.newRemote>0&&n.push(`${C}\u2193+${t.newRemote}${m}`),t.modRemote>0&&n.push(`${C}\u2193~${t.modRemote}${m}`),t.newLocal>0&&n.push(`${S}\u2191+${t.newLocal}${m}`),t.modLocal>0&&n.push(`${S}\u2191~${t.modLocal}${m}`),t.conflict>0&&n.push(`${P}\u26A0${t.conflict}${m}`),t.delLocal>0&&n.push(`${h}-L${t.delLocal}${m}`),t.delRemote>0&&n.push(`${h}-R${t.delRemote}${m}`),console.log(` ${n.join(" ")}`)}console.log("")}}function qc(r){r.command("status").aliases(["st"]).description("Show pending changes between a local sync dir and its realm").argument("[local-dir]","Local sync directory (defaults to current working directory)").option("--pull","Download safe remote changes and update manifest").option("--all","Recursively report all .boxel-sync.json dirs under the current directory").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)=>{let n=await ge(t.realmSecretSeed===!0);if(t.all){t.pull&&(console.error(`${h}Error:${m} Cannot use --pull with --all`),process.exit(1));let s=await oE(e??process.cwd(),{all:!0,realmSecretSeed:n});lE(s),s.hasError&&process.exit(2);return}let i=await jc(e??process.cwd(),{pull:t.pull,realmSecretSeed:n});aE(i),i.hasError&&process.exit(i.pulled.length>0?2:1)})}var Ei=T(require("path"));var Ri=class extends le{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(b){throw console.error("Failed to access realm:",b),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(),we(this.options.localDir)]),o=new Map;for(let[b,v]of n)o.set(b,v.path);if(i.size===0&&t&&t.size>0){console.log("Remote mtimes unavailable, falling back to file listing for remote detection");for(let[b]of t)i.set(b,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([b,v])=>{F(b)||l.set(b,await re(v))}));let c=new Set;for(let b of o.keys())c.add(b);for(let b of i.keys())c.add(b);if(a){for(let b of Object.keys(a.files))c.add(b);if(a.remoteMtimes)for(let b of Object.keys(a.remoteMtimes))c.add(b)}let u=[];for(let b of c){if(F(b))continue;let v=br(b,l,a),O=Sr(b,i,a),U=Fc(v,O,this.syncOptions);u.push({relativePath:b,localStatus:v,remoteStatus:O,action:U})}let f=[],d=[],p=[],y=[],$=[],I=0;for(let b of u)switch(b.action){case"push":f.push(b.relativePath);break;case"pull":d.push(b.relativePath);break;case"push-delete":p.push(b.relativePath);break;case"pull-delete":y.push(b.relativePath);break;case"conflict":$.push(b);break;case"noop":I++;break}for(let b of $)switch(Uc(b,n,i,this.conflictStrategy)){case"push":f.push(b.relativePath);break;case"pull":d.push(b.relativePath);break;case"push-delete":p.push(b.relativePath);break;case"pull-delete":y.push(b.relativePath);break;case"noop":break;default:this.skippedConflicts.push(b.relativePath);break}if(console.log(`
|
|
100
|
-
${g}Sync plan:${m}`),f.length>0&&console.log(` ${S}\u2191 Push:${m} ${f.length} file(s)`),d.length>0&&console.log(` ${
|
|
98
|
+
Checkpoint created: ${c.shortHash} ${u} ${c.message}`)}}console.log("Pull completed")}};function Uc(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 ge(n.realmSecretSeed===!0),s=await uE(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 uE(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 pi({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 Ne=T(require("fs/promises")),hi=T(require("path")),jc=T(require("crypto"));function gi(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 Je(r){try{return await Ne.access(r),!0}catch{return!1}}async function re(r){let e=await Ne.readFile(r);return jc.createHash("md5").update(e).digest("hex")}async function we(r){let e=hi.join(r,".boxel-sync.json"),t;try{t=await Ne.readFile(e,"utf8")}catch(i){if(i.code==="ENOENT")return null;throw i}let n;try{n=JSON.parse(t)}catch{return null}return gi(n)?n:(console.warn("Warning: .boxel-sync.json is malformed or has an unexpected shape; falling back to a full upload."),null)}async function ke(r,e){let t=hi.join(r,".boxel-sync.json");await Ne.writeFile(t,JSON.stringify(e,null,2))}var fE=new Set(["index.json","realm.json"]),yi=class extends le{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(u){throw console.error("Failed to access realm:",u),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 we(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 u=0,[f,d]=await Promise.all([this.getRemoteMtimes(),Promise.all(Array.from(n.entries()).map(async([p,y])=>{if(D(p))return{relativePath:p,localPath:y,currentHash:"",protected:!0};let R=await re(y);return{relativePath:p,localPath:y,currentHash:R,protected:!1}}))]);for(let p of d){if(p.protected){u++;continue}let y=i.files[p.relativePath],R=i.remoteMtimes?.[p.relativePath],I=f.get(p.relativePath),ee=y!==p.currentHash,$=y!==void 0&&!t.has(p.relativePath),v=R!==void 0&&I!==void 0&&I!==R;ee||$||v?(o.set(p.relativePath,p.localPath),!ee&&($||v)&&a.add(p.relativePath)):(u++,s.files[p.relativePath]=p.currentHash,R!==void 0&&(s.remoteMtimes[p.relativePath]=R))}if(u>0&&console.log(`Skipping ${u} unchanged files`),a.size>0){let p=Array.from(a),y=p.slice(0,5).join(", "),R=p.length>5?", ...":"";console.warn(`Warning: ${a.size} file(s) changed on the realm since your last push; your local versions will overwrite them: ${y}${R}`)}}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[u,f]of n)D(u)||o.set(u,f)}let c=!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 u=new Set,f=this.pushOptions.force||!i;for(let p of o.keys())if(f)t.has(p)||u.add(p);else{let y=i.files[p]!==void 0,R=y&&!t.has(p);(!y||R)&&u.add(p)}let d=await this.uploadFilesAtomic(o,u);if(d.error){c=!0,this.hasError=!0,console.error(d.error.message);for(let p of d.error.perFile){let y;p.status===409?y=`${p.path} was created on the realm concurrently \u2014 run with --force to overwrite.`:p.status===404?y=`${p.path} was removed from the realm concurrently \u2014 run with --force to re-create it from your local copy.`:y=`${p.path}: ${p.title}`,console.error(` ${y}`)}}else if(d.succeeded.length>0){let p=await Promise.all(d.succeeded.map(async y=>({rel:y,hash:await re(o.get(y))})));for(let{rel:y,hash:R}of p)s.files[y]=R}}if(this.pushOptions.deleteRemote){let u=new Set(t.keys()),f=[];for(let d of u){if(D(d)){u.delete(d);continue}fE.has(d)&&(u.delete(d),f.push(d))}for(let d of n.keys())u.delete(d);if(f.length>0&&console.log(`Skipping ${f.length} realm-managed remote artifact(s): ${f.join(", ")}`),u.size>0){let d=Array.from(u).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(y){this.hasError=!0,console.error(`Error deleting ${p}:`,y)}}}if(!this.options.dryRun&&!c&&o.size>0)try{let u=await this.getRemoteMtimes();for(let f of Object.keys(s.files)){let d=u.get(f);d!==void 0&&(s.remoteMtimes[f]=d)}}catch(u){console.warn("Could not refresh remote mtimes after upload:",u)}if(s.remoteMtimes&&Object.keys(s.remoteMtimes).length===0&&delete s.remoteMtimes,!this.options.dryRun&&!c&&await ke(this.options.localDir,s),!this.options.dryRun&&o.size>0&&!c){let u=new j(this.options.localDir),f=Array.from(o.keys()).map(p=>({file:p,status:"modified"})),d=await u.createCheckpoint("local",f);if(d){let p=d.isMajor?"[MAJOR]":"[minor]";console.log(`
|
|
99
|
+
Checkpoint created: ${d.shortHash} ${p} ${d.message}`)}}console.log("Push completed")}};function qc(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 ge(n.realmSecretSeed===!0);await mE(e,t,{delete:n.delete,dryRun:n.dryRun,force:n.force,realmSecretSeed:i})})}async function mE(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 Je(r)||(console.error(`Local directory does not exist: ${r}`),process.exit(1));try{let i=new yi({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 Gc(r){let e=x(r.realmUrl.trim()),t=r.profileManager??C(),n=t.getActiveProfile();if(!n)return{realmUrl:e,removed:!1,serverDeleted:!1,unlinked:!1,previousCount:0,nextCount:0,error:A};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(x),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 c=n.profile.realmServerUrl.replace(/\/$/,""),u;try{u=await t.authedRealmServerFetch(`${c}/_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(!u.ok){let d=await dE(u),p=u.status===403?`You do not own this realm and cannot delete it on the server. Server returned 403: ${d}`:`Realm server returned ${u.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 dE(r){try{return await r.text()}catch{return"<no response body>"}}function Hc(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=x(e.trim()),i=await Gc({realmUrl:n,dryRun:!0});if(i.error&&!i.notInList&&(console.error(`${h}Error:${m} ${i.error}`),process.exit(1)),i.notInList&&(console.error(`${h}Error:${m} ${i.error}`),process.exit(1)),console.log(`Remove target: ${_}${i.realmUrl}${m}`),console.log(`${g}app.boxel.realms: ${i.previousCount} -> ${i.nextCount}${m}`),t.dryRun){console.log(`${g}[DRY RUN] No server delete or Matrix changes sent.${m}`);return}if(!t.yes){process.stdin.isTTY||(console.error(`${h}Error:${m} stdin is not a TTY. Pass --yes to confirm in non-interactive mode.`),process.exit(1));let o=await te("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(`${g}Cancelled.${m}`);return}}let s=await Gc({realmUrl:n});(s.error||!s.removed)&&(console.error(`${h}Error:${m} ${s.error??"Removal did not complete."}`),s.serverDeleted&&!s.unlinked&&console.error(`${g}The realm is gone, but your account_data still references ${s.realmUrl}.${m}`),process.exit(1)),console.log(`${S}Removed:${m} ${_}${s.realmUrl}${m}`)})}var ze=T(require("fs/promises")),yt=T(require("path"));function $r(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 Sr(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 Wc(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 Vc(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 pE=new Set(["node_modules",".git",".boxel-history",".cache",".vscode","dist","build","tmp"]),hE=6;function gE(r,e){return r==="unchanged"&&e==="unchanged"||r==="deleted"&&e==="deleted"?null:r==="unchanged"&&e==="added"?"new-remote":r==="unchanged"&&e==="changed"?"modified-remote":r==="unchanged"&&e==="deleted"?"deleted-remote":r==="added"&&e==="unchanged"?"new-local":r==="changed"&&e==="unchanged"?"modified-local":r==="deleted"&&e==="unchanged"?"deleted-local":r==="changed"&&e==="changed"||r==="added"&&e==="added"||r==="changed"&&e==="added"||r==="added"&&e==="changed"||r==="changed"&&e==="deleted"||r==="deleted"&&e==="changed"?"conflict":r==="added"&&e==="deleted"?"new-local":r==="deleted"&&e==="added"?"new-remote":null}var wi=class extends le{constructor(t,n,i){super(t,i);this.statusOptions=t;this.loadedManifest=n}changes=[];pulled=[];hasError=!1;error;remoteMtimes=new Map;async sync(){let t,n;try{[t,this.remoteMtimes,n]=await Promise.all([this.getLocalFileListWithMtimes(),this.getRemoteMtimes(),this.getRemoteFileList()])}catch(a){this.hasError=!0,this.error=a instanceof Error?`Failed to fetch realm state: ${a.message}`:`Failed to fetch realm state: ${String(a)}`;return}if(n&&this.remoteMtimes.size===0&&n.size>0)for(let[a]of n)this.remoteMtimes.set(a,0);let i=new Map;for(let[a,l]of t)i.set(a,l.path);let s=new Map;await Promise.all(Array.from(i.entries()).map(async([a,l])=>{D(a)||s.set(a,await re(l))}));let o=new Set;for(let a of i.keys())o.add(a);for(let a of this.remoteMtimes.keys())o.add(a);for(let a of Object.keys(this.loadedManifest.files))o.add(a);if(this.loadedManifest.remoteMtimes)for(let a of Object.keys(this.loadedManifest.remoteMtimes))o.add(a);for(let a of o){if(D(a))continue;let l=$r(a,s,this.loadedManifest),c=Sr(a,this.remoteMtimes,this.loadedManifest),u=gE(l,c);u!==null&&this.changes.push({file:a,status:u})}this.changes.sort((a,l)=>a.file.localeCompare(l.file)),this.statusOptions.pull&&await this.performSafePull()}async performSafePull(){let t=this.changes.filter(i=>i.status==="new-remote"||i.status==="modified-remote");if(t.length===0)return;let n=[];for(let i of t){let s=yt.join(this.options.localDir,i.file);try{await this.downloadFile(i.file,s),this.pulled.push(i.file);let o=await re(s);this.loadedManifest.files[i.file]=o;let a=this.remoteMtimes.get(i.file);a!==void 0&&(this.loadedManifest.remoteMtimes=this.loadedManifest.remoteMtimes??{},this.loadedManifest.remoteMtimes[i.file]=a)}catch(o){this.hasError=!0;let a=o instanceof Error?o.message:String(o);n.push({file:i.file,message:a}),console.error(` ${h}\u2717 ${i.file}${m} (${a})`)}}n.length>0&&(this.error=`Failed to pull ${n.length} file(s): ${n.map(i=>`${i.file} (${i.message})`).join("; ")}`),this.pulled.length>0&&await ke(this.options.localDir,this.loadedManifest)}};async function Bc(r,e){let t={localDir:r,realmUrl:"",changes:[],pulled:[],inSync:!1,hasError:!1},n=yt.join(r,".boxel-sync.json");if(!await Je(n))return{...t,hasError:!0,error:`No .boxel-sync.json found in ${r}. Run: boxel realm sync ${r} <realm-url>`};let i=await we(r);if(!i)return{...t,hasError:!0,error:`Malformed .boxel-sync.json in ${r}`};let s;try{s=(await ze.stat(n)).mtimeMs}catch{}let o;if(e.authenticator)o=e.authenticator;else{let l=ye({realmUrl:i.realmUrl,realmSecretSeed:e.realmSecretSeed,profileManager:e.profileManager});if(!l.ok)return{...t,realmUrl:i.realmUrl,manifestMtime:s,hasError:!0,error:l.error};o=l.authenticator}let a=new wi({realmUrl:i.realmUrl,localDir:r,pull:e.pull},i,o);return await a.sync(),{localDir:r,realmUrl:i.realmUrl,manifestMtime:s,changes:a.changes,pulled:a.pulled.slice().sort(),inSync:!a.hasError&&a.changes.length===0,hasError:a.hasError,error:a.error}}async function yE(r,e){let t=[];async function n(i,s){if(s>e)return;let o;try{o=await ze.readdir(i,{withFileTypes:!0})}catch{return}if(o.some(l=>l.isFile()&&l.name===".boxel-sync.json")){t.push(i);return}for(let l of o)l.isDirectory()&&(pE.has(l.name)||await n(yt.join(i,l.name),s+1))}return await n(r,0),t.sort(),t}async function wE(r,e){if(e.pull)return{rootDir:r,workspaces:[],hasError:!0,error:"Cannot use --pull with --all"};let t=process.env.BOXEL_STATUS_ALL_MAX_DEPTH,n=t!==void 0?Number(t):NaN,i=Number.isFinite(n)&&n>=0?n:hE,s=await yE(r,i),o=[],a=!1;for(let l of s){let c=yt.join(l,".boxel-sync.json"),u;try{u=await ze.readFile(c,"utf8")}catch{o.push({localDir:l,realmUrl:"",changes:[],pulled:[],inSync:!1,hasError:!0,skipped:"no-manifest"}),a=!0;continue}let f;try{f=JSON.parse(u)}catch{f=void 0}if(!gi(f)){o.push({localDir:l,realmUrl:"",changes:[],pulled:[],inSync:!1,hasError:!0,skipped:"malformed"}),a=!0;continue}let d=await Bc(l,{profileManager:e.profileManager,realmSecretSeed:e.realmSecretSeed,authenticator:e.authenticator}),p={...d};d.hasError&&(p.skipped="fetch-failed",a=!0),o.push(p)}return{rootDir:r,workspaces:o,hasError:a}}function EE(r){if(r.hasError&&r.error){console.error(`${h}Error:${m} ${r.error}`);return}if(console.log(`Realm: ${r.realmUrl}`),console.log(`Local: ${r.localDir}`),r.manifestMtime&&console.log(`${g}Manifest updated:${m} ${new Date(r.manifestMtime).toISOString()}`),console.log(""),r.changes.length===0){console.log(`${S}\u2713 In sync${m}`);return}let e={"new-remote":[],"modified-remote":[],"new-local":[],"modified-local":[],conflict:[],"deleted-local":[],"deleted-remote":[]};for(let t of r.changes)e[t.status].push(t.file);if(e["new-remote"].length>0){console.log(`${_}\u2193 New on remote (${e["new-remote"].length}):${m}`);for(let t of e["new-remote"])console.log(` + ${t}`);console.log("")}if(e["modified-remote"].length>0){console.log(`${_}\u2193 Modified on remote (${e["modified-remote"].length}):${m}`);for(let t of e["modified-remote"])console.log(` ~ ${t}`);console.log("")}if(e["new-local"].length>0){console.log(`${S}\u2191 New locally (${e["new-local"].length}):${m}`);for(let t of e["new-local"])console.log(` + ${t}`);console.log("")}if(e["modified-local"].length>0){console.log(`${S}\u2191 Modified locally (${e["modified-local"].length}):${m}`);for(let t of e["modified-local"])console.log(` ~ ${t}`);console.log("")}if(e.conflict.length>0){console.log(`${P}\u26A0 Conflicts (${e.conflict.length}):${m}`);for(let t of e.conflict)console.log(` ! ${t}`);console.log("")}if(e["deleted-local"].length>0){console.log(`${h}- Deleted locally (${e["deleted-local"].length}):${m}`);for(let t of e["deleted-local"])console.log(` - ${t}`);console.log("")}if(e["deleted-remote"].length>0){console.log(`${h}- Deleted on remote (${e["deleted-remote"].length}):${m}`);for(let t of e["deleted-remote"])console.log(` - ${t}`);console.log("")}if(r.pulled.length>0){console.log(`${_}Pulled ${r.pulled.length} file(s):${m}`);for(let t of r.pulled)console.log(` \u2713 ${t}`)}}function bE(r){if(r.error){console.error(`${h}Error:${m} ${r.error}`);return}if(r.workspaces.length===0){console.log(`No .boxel-sync.json directories found under ${r.rootDir}.`);return}for(let e of r.workspaces){if(e.skipped){console.log(`${P}${e.localDir}${m} [${e.skipped}]`),e.error&&console.log(` ${g}${e.error}${m}`),console.log("");continue}let t={newRemote:0,modRemote:0,newLocal:0,modLocal:0,conflict:0,delLocal:0,delRemote:0};for(let n of e.changes)n.status==="new-remote"?t.newRemote++:n.status==="modified-remote"?t.modRemote++:n.status==="new-local"?t.newLocal++:n.status==="modified-local"?t.modLocal++:n.status==="conflict"?t.conflict++:n.status==="deleted-local"?t.delLocal++:n.status==="deleted-remote"&&t.delRemote++;if(console.log(`${e.localDir} ${g}${e.realmUrl}${m}`),e.inSync)console.log(` ${S}\u2713 in sync${m}`);else{let n=[];t.newRemote>0&&n.push(`${_}\u2193+${t.newRemote}${m}`),t.modRemote>0&&n.push(`${_}\u2193~${t.modRemote}${m}`),t.newLocal>0&&n.push(`${S}\u2191+${t.newLocal}${m}`),t.modLocal>0&&n.push(`${S}\u2191~${t.modLocal}${m}`),t.conflict>0&&n.push(`${P}\u26A0${t.conflict}${m}`),t.delLocal>0&&n.push(`${h}-L${t.delLocal}${m}`),t.delRemote>0&&n.push(`${h}-R${t.delRemote}${m}`),console.log(` ${n.join(" ")}`)}console.log("")}}function Yc(r){r.command("status").aliases(["st"]).description("Show pending changes between a local sync dir and its realm").argument("[local-dir]","Local sync directory (defaults to current working directory)").option("--pull","Download safe remote changes and update manifest").option("--all","Recursively report all .boxel-sync.json dirs under the current directory").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)=>{let n=await ge(t.realmSecretSeed===!0);if(t.all){t.pull&&(console.error(`${h}Error:${m} Cannot use --pull with --all`),process.exit(1));let s=await wE(e??process.cwd(),{all:!0,realmSecretSeed:n});bE(s),s.hasError&&process.exit(2);return}let i=await Bc(e??process.cwd(),{pull:t.pull,realmSecretSeed:n});EE(i),i.hasError&&process.exit(i.pulled.length>0?2:1)})}var bi=T(require("path"));var Ri=class extends le{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($){throw console.error("Failed to access realm:",$),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(),we(this.options.localDir)]),o=new Map;for(let[$,v]of n)o.set($,v.path);if(i.size===0&&t&&t.size>0){console.log("Remote mtimes unavailable, falling back to file listing for remote detection");for(let[$]of t)i.set($,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([$,v])=>{D($)||l.set($,await re(v))}));let c=new Set;for(let $ of o.keys())c.add($);for(let $ of i.keys())c.add($);if(a){for(let $ of Object.keys(a.files))c.add($);if(a.remoteMtimes)for(let $ of Object.keys(a.remoteMtimes))c.add($)}let u=[];for(let $ of c){if(D($))continue;let v=$r($,l,a),O=Sr($,i,a),U=Wc(v,O,this.syncOptions);u.push({relativePath:$,localStatus:v,remoteStatus:O,action:U})}let f=[],d=[],p=[],y=[],R=[],I=0;for(let $ of u)switch($.action){case"push":f.push($.relativePath);break;case"pull":d.push($.relativePath);break;case"push-delete":p.push($.relativePath);break;case"pull-delete":y.push($.relativePath);break;case"conflict":R.push($);break;case"noop":I++;break}for(let $ of R)switch(Vc($,n,i,this.conflictStrategy)){case"push":f.push($.relativePath);break;case"pull":d.push($.relativePath);break;case"push-delete":p.push($.relativePath);break;case"pull-delete":y.push($.relativePath);break;case"noop":break;default:this.skippedConflicts.push($.relativePath);break}if(console.log(`
|
|
100
|
+
${g}Sync plan:${m}`),f.length>0&&console.log(` ${S}\u2191 Push:${m} ${f.length} file(s)`),d.length>0&&console.log(` ${_}\u2193 Pull:${m} ${d.length} file(s)`),p.length>0&&console.log(` ${h}\u2191 Delete remote:${m} ${p.length} file(s)`),y.length>0&&console.log(` ${h}\u2193 Delete local:${m} ${y.length} file(s)`),this.skippedConflicts.length>0){console.log(` ${P}\u26A0 Conflicts skipped:${m} ${this.skippedConflicts.length} file(s)`);for(let $ of this.skippedConflicts)console.log(` ${$}`);console.log(` ${g}Use --prefer-local, --prefer-remote, or --prefer-newest to resolve.${m}`)}if(I>0&&console.log(` ${g}Unchanged: ${I} file(s)${m}`),f.length+d.length+p.length+y.length===0){console.log(`
|
|
101
101
|
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(`
|
|
102
|
-
Pulling ${d.length} file(s)...`);let
|
|
103
|
-
Pushing ${f.length} file(s)...`);let
|
|
104
|
-
Deleting ${p.length} remote file(s)...`);let
|
|
105
|
-
Deleting ${y.length} local file(s)...`);let
|
|
102
|
+
Pulling ${d.length} file(s)...`);let $=await Promise.all(d.map(v=>this.remoteLimit(async()=>{try{let O=bi.join(this.options.localDir,v);return await this.downloadFile(v,O),v}catch(O){return this.hasError=!0,console.error(`Error downloading ${v}:`,O),null}})));this.pulledFiles.push(...$.filter(v=>v!==null))}if(f.length>0){console.log(`
|
|
103
|
+
Pushing ${f.length} file(s)...`);let $=new Map;for(let U of f){let Et=o.get(U);Et&&$.set(U,Et)}let v=new Set;for(let U of $.keys()){let Et=a?.files[U]!==void 0,xu=i.has(U);!Et&&!xu&&v.add(U)}let O=await this.uploadFilesAtomic($,v);if(O.error){this.hasError=!0,console.error(O.error.message);for(let U of O.error.perFile)console.error(` ${U.path}: ${U.title}`)}else this.pushedFiles.push(...O.succeeded)}if(p.length>0){console.log(`
|
|
104
|
+
Deleting ${p.length} remote file(s)...`);let $=await Promise.all(p.map(v=>this.remoteLimit(async()=>{try{return await this.deleteFile(v),v}catch(O){return this.hasError=!0,console.error(`Error deleting remote ${v}:`,O),null}})));this.remoteDeletedFiles.push(...$.filter(v=>v!==null))}if(y.length>0){console.log(`
|
|
105
|
+
Deleting ${y.length} local file(s)...`);let $=await Promise.all(y.map(async v=>{try{let O=o.get(v);return O?(await this.deleteLocalFile(O),v):null}catch(O){return this.hasError=!0,console.error(`Error deleting local ${v}:`,O),null}}));this.localDeletedFiles.push(...$.filter(v=>v!==null))}if(!this.options.dryRun&&!this.hasError){let $=new Map;if(a)for(let[O,U]of Object.entries(a.files))$.set(O,U);for(let[O,U]of l)$.set(O,U);for(let O of this.pushedFiles){let U=o.get(O);U&&$.set(O,await re(U))}for(let O of this.pulledFiles){let U=bi.join(this.options.localDir,O);$.set(O,await re(U))}for(let O of this.remoteDeletedFiles)$.delete(O);for(let O of this.localDeletedFiles)$.delete(O);let v=i;if(this.pushedFiles.length>0||this.remoteDeletedFiles.length>0)try{v=await this.getRemoteMtimes()}catch{console.warn("Could not refresh remote mtimes after sync")}await this.writeManifest($,v)}if(!this.options.dryRun){let $=[...this.pushedFiles.map(v=>({file:v,status:"modified"})),...this.pulledFiles.map(v=>({file:v,status:"modified"})),...this.remoteDeletedFiles.map(v=>({file:v,status:"deleted"})),...this.localDeletedFiles.map(v=>({file:v,status:"deleted"}))];if($.length>0){let O=await new j(this.options.localDir).createCheckpoint("local",$);if(O){let U=O.isMajor?"[MAJOR]":"[minor]";console.log(`
|
|
106
106
|
Checkpoint created: ${O.shortHash} ${U} ${O.message}`)}}}console.log(`
|
|
107
|
-
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 ke(this.options.localDir,i)}};function
|
|
108
|
-
`),{ok:!0,staleOverwrote:n}}async function vr(r){try{await _e.unlink($i(r))}catch(e){if(e?.code!=="ENOENT")throw e}}var Ce=T(require("fs/promises")),
|
|
109
|
-
`),await Ce.rename(t,e)}async function
|
|
110
|
-
`)}let c=async()=>{await Promise.all(l.map(async p=>{try{await p.poll()&&(i||console.log(`${g}[${kr()}]${m} [${p.name}] ${P}\u26A1 ${p.pendingCount} change(s) detected${m}`),p.scheduleFlush(
|
|
111
|
-
${
|
|
112
|
-
`)){if(!n)continue;let i=n.trim().split(/\s+/),s=Number.parseInt(i[1]??"",10);if(!Number.isFinite(s)||t.has(s))continue;t.add(s);let o=".",a=n.match(/\bstart\s+\S+\s+(\S+)/);a&&a[1]&&!a[1].startsWith("-")&&(o=a[1]),e.push({pid:s,workspace:o})}return e}async function
|
|
113
|
-
${S}\u2713 Stopped ${r.stopped.length} process${e}${m}`)}}function
|
|
114
|
-
`}catch{}return
|
|
107
|
+
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 ke(this.options.localDir,i)}};function Jc(r){return 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(t,n,i)=>{let s=await ge(i.realmSecretSeed===!0),o=await RE(t,n,{preferLocal:i.preferLocal,preferRemote:i.preferRemote,preferNewest:i.preferNewest,delete:i.delete,dryRun:i.dryRun,realmSecretSeed:s}),a=Array.isArray(o.pushed)&&o.pushed.length>0||Array.isArray(o.pulled)&&o.pulled.length>0||Array.isArray(o.remoteDeleted)&&o.remoteDeleted.length>0||Array.isArray(o.localDeleted)&&o.localDeleted.length>0;o.error&&(console.error(`Error: ${o.error}`),process.exit(a?2:1)),console.log("Sync completed successfully")})}async function RE(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 Ei({error:o.error});n=o.authenticator}if([t.preferLocal,t.preferRemote,t.preferNewest].filter(Boolean).length>1)return Ei({error:"Only one conflict strategy can be specified (--prefer-local, --prefer-remote, or --prefer-newest)."});if(!await Je(r))return Ei({error:`Local directory does not exist: ${r}`});let s;try{s=new Ri({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?$E(s):void 0}}function $E(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 Ei(r){return{pushed:[],pulled:[],remoteDeleted:[],localDeleted:[],skippedConflicts:[],hasError:!0,...r}}var zc=T(vt());function SE(r){let e=Number.parseInt(r,10);if(!Number.isFinite(e)||e<0||String(e)!==r.trim())throw new zc.InvalidArgumentError("--timeout must be a non-negative integer (milliseconds).");return e}async function vE(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??C();if(!n.getActiveProfile())return{ready:!1,error:A};let s=`${x(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 Xc(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)",SE).action(async e=>{let t;try{t=await vE(e.realm,{timeoutMs:e.timeout})}catch(n){console.error(`${h}Error:${m} ${n instanceof Error?n.message:String(n)}`),process.exit(1)}t.ready?console.log(`${S}Realm is ready.${m}`):(console.error(`${h}Error:${m} ${t.error??"Realm not ready"}`),process.exit(1))})}var Ci=T(vt()),ou=T(require("fs/promises")),xr=T(require("path"));var _e=T(require("fs/promises")),Kc=T(require("path")),xE=".boxel-watch.lock";function $i(r){return Kc.join(r,xE)}function Si(r){try{return process.kill(r,0),!0}catch(e){return e?.code==="EPERM"}}async function kE(r){try{let e=await _e.readFile($i(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 Qc(r,e){await _e.mkdir(r,{recursive:!0});let t=await kE(r),n=!1;if(t&&Si(t.pid))return{ok:!1,existing:t};t&&(n=!0);let i={pid:process.pid,startedAt:new Date().toISOString(),realmUrl:e};return await _e.writeFile($i(r),JSON.stringify(i,null,2)+`
|
|
108
|
+
`),{ok:!0,staleOverwrote:n}}async function vr(r){try{await _e.unlink($i(r))}catch(e){if(e?.code!=="ENOENT")throw e}}var Ce=T(require("fs/promises")),Zc=T(require("os")),vi=T(require("path"));function eu(){return vi.join(Zc.homedir(),".boxel-cli")}function tu(){return vi.join(eu(),"watch-processes.json")}async function ru(){try{let r=await Ce.readFile(tu(),"utf8"),e=JSON.parse(r);return Array.isArray(e?.processes)?{processes:e.processes.filter(n=>typeof n?.pid=="number"&&typeof n?.workspace=="string"&&typeof n?.startedAt=="string")}:{processes:[]}}catch{return{processes:[]}}}async function xi(r){await Ce.mkdir(eu(),{recursive:!0});let e=tu(),t=`${e}.${process.pid}.tmp`;await Ce.writeFile(t,JSON.stringify(r,null,2)+`
|
|
109
|
+
`),await Ce.rename(t,e)}async function nu(){let r=await ru(),e=r.processes.filter(t=>Si(t.pid));return e.length!==r.processes.length&&await xi({processes:e}),{processes:e}}async function iu(r){let t=(await nu()).processes.filter(n=>n.pid!==process.pid);t.push({pid:process.pid,workspace:r,startedAt:new Date().toISOString()}),await xi({processes:t})}async function su(){let r=await ru(),e=r.processes.filter(t=>t.pid!==process.pid);e.length!==r.processes.length&&await xi({processes:e})}async function ki(){return(await nu()).processes}var _i=class extends le{name;debounceMs;overwriteLocal;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.overwriteLocal=n.overwriteLocal??!1,this.checkpointManager=new j(e.localDir),this.name=PE(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 we(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(D(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())D(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:[],skipped:[],checkpoint:null};let e=new Map(this.pendingChanges);this.pendingChanges.clear();let t=[],n=[],i=[],s=[],o=null;if(!this.overwriteLocal){let c=await we(this.options.localDir);c&&c.realmUrl===this.normalizedRealmUrl&&(o=c)}for(let[c,u]of e){let f=xr.join(this.options.localDir,c);if(!this.overwriteLocal&&await this.localDivergesFromManifest(f,c,o,u.status)){i.push(c);continue}if(u.status==="deleted"){try{await ou.unlink(f)}catch(d){if(d.code!=="ENOENT")throw d}n.push(c),s.push({file:c,status:"deleted"})}else await this.downloadFile(c,f),t.push(c),s.push({file:c,status:u.status})}let a=new Set(i);for(let[c,u]of e)a.has(c)||(u.status==="deleted"?this.lastKnownMtimes.delete(c):this.lastKnownMtimes.set(c,u.mtime));let l=null;return s.length>0&&(await this.persistManifest(t,n),l=await this.checkpointManager.createCheckpoint("remote",s)),{pulled:t,deleted:n,skipped:i,checkpoint:l}}async localDivergesFromManifest(e,t,n,i){let s;try{s=await re(e)}catch(a){if(a.code!=="ENOENT")throw a;return i==="deleted"?!1:n?.files[t]!==void 0}let o=n?.files[t];return o===void 0?!0:s!==o}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(`${h}[${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 we(this.options.localDir),i=n&&n.realmUrl===this.normalizedRealmUrl?n.files:null,s=i?{...i}:{};for(let l of t)delete s[l];for(let l of e){let c=xr.join(this.options.localDir,l);try{s[l]=await re(c)}catch(u){if(u.code!=="ENOENT")throw u}}let o={};for(let[l,c]of this.lastKnownMtimes)c!==0&&(o[l]=c);let a={realmUrl:this.normalizedRealmUrl,files:s};Object.keys(o).length>0&&(a.remoteMtimes=o),await ke(this.options.localDir,a)}};async function _E(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,s=e.overwriteLocal??!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 o;if(e.authenticator)o=e.authenticator;else{let p=ye({realmUrl:r[0].realmUrl,realmSecretSeed:e.realmSecretSeed,profileManager:e.profileManager});if(!p.ok)return{watchers:[],error:p.error};o=p.authenticator}let a=[];for(let p of r){let y=await Qc(p.localDir,p.realmUrl);if(!y.ok){for(let R of a)await vr(R);return{watchers:[],error:CE(p.localDir,y.existing)}}y.staleOverwrote&&!i&&console.log(`${g}[${kr()}] overwrote stale lock at ${p.localDir}${m}`),a.push(p.localDir)}let l=[];for(let p of r){let y=new _i(p,o,{debounceMs:n,overwriteLocal:s});try{await y.initialize()}catch(R){for(let I of l)I.shutdown();for(let I of a)await vr(I);return{watchers:[],error:`Failed to initialize watch on ${p.realmUrl}: ${R instanceof Error?R.message:String(R)}`}}l.push(y)}if(!i){console.log(`${_}\u21C5 Watching ${l.length} realm${l.length>1?"s":""}:${m}`);for(let p of l)console.log(` ${p.name} ${g}\u2192${m} ${p.localDir}`);console.log(` ${g}Interval: ${t/1e3}s, Debounce: ${n/1e3}s${m}`),console.log(` ${g}Press Ctrl+C to stop${m}
|
|
110
|
+
`)}let c=async()=>{await Promise.all(l.map(async p=>{try{await p.poll()&&(i||console.log(`${g}[${kr()}]${m} [${p.name}] ${P}\u26A1 ${p.pendingCount} change(s) detected${m}`),p.scheduleFlush(R=>{i||OE(p.name,R)}))}catch(y){console.error(`${h}[${p.name}] poll error:${m}`,y instanceof Error?y.message:y)}}))},u=!1,f=null,d=()=>{u||(f=setTimeout(async()=>{f=null,!u&&(await c(),d())},t))};try{await iu(r.map(p=>p.localDir).join(", "))}catch{}return await c(),d(),await new Promise(p=>{let y=null,R=null,I=async()=>{if(!u){u=!0,f!==null&&(clearTimeout(f),f=null);for(let ee of l)ee.shutdown();y&&process.off("SIGINT",y),R&&process.off("SIGTERM",R);for(let ee of a)try{await vr(ee)}catch{}try{await su()}catch{}p()}};if(e.signal){if(e.signal.aborted){I();return}e.signal.addEventListener("abort",()=>void I(),{once:!0})}else y=()=>{i||console.log(`
|
|
111
|
+
${_}\u21C5 Watch stopped${m}`),I()},R=y,process.on("SIGINT",y),process.on("SIGTERM",R)}),{watchers:l}}function CE(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 ${xr.join(r,".boxel-watch.lock")} if it's stale.`}function OE(r,e){let t=e.pulled.length+e.deleted.length;if(t>0&&(console.log(`${g}[${kr()}]${m} [${r}] ${S}applied ${t} change(s)${m} (${e.pulled.length} pulled, ${e.deleted.length} deleted)`),e.checkpoint)){let n=e.checkpoint.isMajor?"[MAJOR]":"[minor]";console.log(` ${g}Checkpoint:${m} ${e.checkpoint.shortHash} ${n} ${e.checkpoint.message}`)}for(let n of e.skipped)console.log(`${g}[${kr()}]${m} [${r}] ${P}\u26A0 skipped ${n}: local diverges from sync manifest (rerun with --overwrite-local to discard, or \`boxel realm sync\` to reconcile)${m}`)}function PE(r){return r.replace(/\/$/,"").split("/").slice(-2).join("/")}function kr(){return new Date().toLocaleTimeString()}function TE(r){return e=>{let t=Number.parseFloat(e);if(!Number.isFinite(t)||t<=0)throw new Ci.InvalidArgumentError(`${r} must be a positive number.`);return t}}function AE(r){return e=>{let t=Number.parseFloat(e);if(!Number.isFinite(t)||t<0)throw new Ci.InvalidArgumentError(`${r} must be a non-negative number.`);return t}}function au(r){r.command("start").description("Start watching 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",TE("--interval"),30).option("-d, --debounce <seconds>","Seconds to wait after a burst of changes before applying them",AE("--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)").option("--overwrite-local","Overwrite local files when the remote changes. Default: skip + warn when the local copy diverges from the sync manifest.").action(async(e,t,n)=>{let i=await ge(n.realmSecretSeed===!0),s=await _E([{realmUrl:e,localDir:t}],{intervalMs:n.interval*1e3,debounceMs:n.debounce*1e3,realmSecretSeed:i,overwriteLocal:n.overwriteLocal===!0});s.error&&(console.error(`${h}Error:${m} ${s.error}`),process.exit(1))})}var Oi=require("child_process");var LE=200;function ME(r){return new Promise(e=>setTimeout(e,r))}function lu(r){try{if(process.platform==="win32")try{process.kill(r)}catch{(0,Oi.execSync)(`taskkill /PID ${r} /F`,{stdio:"ignore"})}else process.kill(r,"SIGINT");return{ok:!0,alreadyGone:!1}}catch(e){return e?.code==="ESRCH"?{ok:!0,alreadyGone:!0}:{ok:!1,alreadyGone:!1}}}function IE(){if(process.platform==="win32")return[];let r;try{r=(0,Oi.execSync)('ps aux | grep -E "(tsx[[:space:]].*src/index\\.ts[[:space:]]+realm[[:space:]]+watch[[:space:]]+start|[[:space:]]boxel[[:space:]]+realm[[:space:]]+watch[[:space:]]+start|node[[:space:]].*boxel[[:space:]]+realm[[:space:]]+watch[[:space:]]+start)" | grep -v grep | grep -v "[[:space:]]stop"',{encoding:"utf8"}).trim()}catch{return[]}if(!r)return[];let e=[],t=new Set;for(let n of r.split(`
|
|
112
|
+
`)){if(!n)continue;let i=n.trim().split(/\s+/),s=Number.parseInt(i[1]??"",10);if(!Number.isFinite(s)||t.has(s))continue;t.add(s);let o=".",a=n.match(/\bstart\s+\S+\s+(\S+)/);a&&a[1]&&!a[1].startsWith("-")&&(o=a[1]),e.push({pid:s,workspace:o})}return e}async function NE(){let r=[],e=[],t=new Set,n=await ki();for(let i of n){if(i.pid===process.pid)continue;t.add(i.pid);let s=lu(i.pid),o={pid:i.pid,workspace:i.workspace};s.ok?r.push(o):e.push(o)}for(let i of IE()){if(i.pid===process.pid||t.has(i.pid))continue;t.add(i.pid);let s=lu(i.pid),o={pid:i.pid,workspace:i.workspace};s.ok?r.push(o):e.push(o)}return r.length>0&&(await ME(LE),await ki()),{stopped:r,failed:e}}function FE(r){if(r.stopped.length===0&&r.failed.length===0){console.log("No running watch processes found.");return}for(let e of r.stopped)console.log(` ${g}\u21C5${m} Stopped: boxel realm watch ${e.workspace} (PID ${e.pid})`);for(let e of r.failed)console.log(` ${h}\xD7${m} Failed to stop: boxel realm watch ${e.workspace} (PID ${e.pid})`);if(r.stopped.length>0){let e=r.stopped.length>1?"es":"";console.log(`
|
|
113
|
+
${S}\u2713 Stopped ${r.stopped.length} process${e}${m}`)}}function cu(r){r.command("stop").description("Stop all running boxel realm watch processes").action(async()=>{let e=await NE();FE(e)})}function uu(r){let e=r.command("watch").description("Watch a Boxel realm; subcommands manage watch processes");au(e),cu(e)}function fu(r){let e=r.command("realm").description("Manage realms on the realm server");oc(e),uc(e),_c(e),Cc(e),Pc(e),Ic(e),Uc(e),qc(e),Hc(e);let t=Jc(e);Yc(t),Tc(e),Xc(e),uu(e)}async function DE(r,e,t){let n=t?.profileManager??C();if(!n.getActiveProfile())return{ok:!1,error:A};if(D(e))return{ok:!1,error:`Cannot delete protected file: ${e}`};let s=new URL(e,x(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 mu(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 DE(t.realm,e)}catch(i){console.error(`${h}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(`${g}Deleted:${m} ${e}`):console.error(`${h}Error:${m} ${n.error}`),n.ok||process.exit(1)})}async function Pi(r,e,t){let n=t?.profileManager??C();if(!n.getActiveProfile())return{ok:!1,error:A};let s=new URL(e,x(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 du(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 Pi(t.realm,e)}catch(i){console.error(`${h}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(`${g}Status:${m} ${n.status??"(no status)"}`),console.error(`${h}Error:${m} ${n.error}`)),n.ok||process.exit(1)})}var Ti="// touched for re-index";async function UE(r,e,t){let n=t?.profileManager??C();if(!n.getActiveProfile())return{ok:!1,touched:[],skipped:[],error:A};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 Me(r,{profileManager:n});if(l.error)return{ok:!1,touched:[],skipped:[],error:l.error};s=l.filenames.filter(c=>(c.endsWith(".json")||c.endsWith(".gts"))&&!D(c))}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(D(l)){a.push({path:l,reason:"protected file"});continue}let c=await Pi(r,l,{profileManager:n});if(!c.ok||c.content==null){a.push({path:l,reason:c.error??"read failed"});continue}if(t?.dryRun){o.push(l);continue}let u=l.endsWith(".json")?jE(c.content):GE(c.content),f=await ft(r,l,u,{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 jE(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)+`
|
|
114
|
+
`}catch{}return qE(r)}function qE(r){return r.endsWith(`
|
|
115
115
|
|
|
116
116
|
`)?r.slice(0,-1):r+`
|
|
117
|
-
`}function
|
|
118
|
-
${
|
|
117
|
+
`}function GE(r){let e=`
|
|
118
|
+
${Ti}
|
|
119
119
|
`;return r.endsWith(e)?r.slice(0,-e.length)+`
|
|
120
120
|
`:r.endsWith(`
|
|
121
|
-
`)?r+
|
|
121
|
+
`)?r+Ti+`
|
|
122
122
|
`:r+`
|
|
123
|
-
`+
|
|
124
|
-
`}function
|
|
125
|
-
${g}${s} ${n.touched.length} file(s)${n.skipped.length>0?`, skipped ${n.skipped.length}`:""}${m}`)}n.ok||process.exit(1)})}function
|
|
126
|
-
`)}),u.on("pageerror"
|
|
127
|
-
`)}));let f=r.pm.getRealmToken(r.targetRealm);if(f){let
|
|
123
|
+
`+Ti+`
|
|
124
|
+
`}function pu(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 UE(t.realm,e,{all:t.all,dryRun:t.dryRun})}catch(i){console.error(`${h}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(`${h}Error:${m} ${n.error}`);else{let i=t.dryRun?`${g}[dry-run]${m} `:"";for(let o of n.touched)console.log(`${i}${S}touched${m} ${o}`);for(let{path:o,reason:a}of n.skipped)console.log(`${h}skipped${m} ${o} ${g}(${a})${m}`);let s=t.dryRun?"would touch":"touched";console.log(`
|
|
125
|
+
${g}${s} ${n.touched.length} file(s)${n.skipped.length>0?`, skipped ${n.skipped.length}`:""}${m}`)}n.ok||process.exit(1)})}function hu(r){let e=r.command("file").description("Read, write, and manage files in a realm");mu(e),Kl(e),Xl(e),du(e),pu(e),zl(e)}async function HE(r,e,t){let n=t?.profileManager??C(),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 c;try{c=await l.json()}catch{return{status:"error",error:`run-command response was not valid JSON (HTTP ${l.status})`}}let u=c.data?.attributes;return{status:u?.status??"error",result:u?.cardResultString??null,error:u?.error??null}}function gu(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(`${h}Error:${m} --input must be a JSON object, got ${Array.isArray(s)?"array":typeof s}`),process.exit(1)),n=s}catch{console.error(`${h}Error:${m} --input is not valid JSON: ${t.input}`),process.exit(1)}let i;try{i=await HE(e,t.realm,{input:n})}catch(s){console.error(`${h}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(`${g}Status:${m} ${WE(i.status)}${i.status}${m}`),i.result){console.log(`${g}Result:${m}`);try{M.output(JSON.stringify(JSON.parse(i.result),null,2))}catch{M.output(i.result)}}i.error&&console.error(`${h}Error:${m} ${i.error}`)}(i.status==="error"||i.status==="unusable")&&process.exit(1)})}function WE(r){switch(r){case"ready":return S;case"error":return h;default:return _}}var yu=require("node:child_process"),wt=require("node:fs"),wu=require("node:http"),q=require("node:path");async function VE(){try{return(await import("@playwright/test")).chromium}catch(r){let e=r instanceof Error?r.message:String(r);throw new Error(`Could not load @playwright/test (${e}). \`boxel test\` is monorepo-only \u2014 install Playwright in the boxel-cli package via \`pnpm --filter @cardstack/boxel-cli install\` and run \`npx playwright install chromium\` once.`)}}async function BE(r,e){let t=e?.profileManager??C(),n=t.getActiveProfile();if(!n)return Ai(A);let i=x(r),s=x(e?.hostAppUrl??n.profile.realmServerUrl),o;try{let a=await Me(i,{profileManager:t});if(a.error)return Ai(`Failed to discover test files: ${a.error}`);o=a.filenames.filter(l=>l.endsWith(".test.gts"))}catch(a){return Ai(`Failed to discover test files: ${a instanceof Error?a.message:String(a)}`)}if(o.length===0)return{status:"failed",passedCount:0,failedCount:0,skippedCount:0,durationMs:0,testFiles:[],failures:[],errorMessage:"No `*.test.gts` files found in the realm. Every implementation Issue must ship with at least one test file."};try{let{qunitResults:a,durationMs:l}=await YE({pm:t,targetRealm:i,hostAppUrl:s,hostDistDir:e?.hostDistDir,debug:e?.debug});return{...QE(a),durationMs:l,testFiles:o}}catch(a){let l=a instanceof Error?a.message:String(a);return{status:"error",passedCount:0,failedCount:0,skippedCount:0,durationMs:0,testFiles:o,failures:[],errorMessage:l}}}async function YE(r){let e=Date.now(),t,n;try{let i=r.hostDistDir??(0,q.join)(XE()??(0,q.join)((0,q.resolve)(mt(__dirname),".."),"host"),"dist");if(!Eu((0,q.join)(i,"tests","index.html")))throw new Error(`Host app dist not found at ${i}. Build the host app (e.g., \`pnpm --filter @cardstack/host build\`) or set TEST_HARNESS_HOST_DIST_PACKAGE_DIR.`);let{url:s,server:o,setHtml:a}=await zE(i);n=o;let l=JE({assetServerUrl:s,hostDistDir:i,realmProxyUrl:r.hostAppUrl});a(l),t=await(await VE()).launch({headless:!0});let u=await t.newPage();r.debug&&(u.on("console",R=>{process.stderr.write(`[browser ${R.type()}] ${R.text()}
|
|
126
|
+
`)}),u.on("pageerror",R=>{process.stderr.write(`[browser pageerror] ${R.message}
|
|
127
|
+
`)}));let f=r.pm.getRealmToken(r.targetRealm);if(f){let R=new URL(r.targetRealm).origin;await u.route(`${R}/**`,I=>{let ee={...I.request().headers(),Authorization:f};I.continue({headers:ee})})}let d=encodeURIComponent(r.targetRealm),p=`${s}?liveTest=true&realmURL=${d}&hidepassed`;return await u.goto(p,{waitUntil:"domcontentloaded"}),await u.waitForFunction(()=>window.__qunitResults?.runEnd!==null,null,{timeout:3e5}),{qunitResults:await u.evaluate(()=>window.__qunitResults),durationMs:Date.now()-e}}finally{t&&await t.close().catch(()=>{}),n&&n.close()}}function JE(r){let e=r.assetServerUrl.replace(/\/$/,""),t=r.realmProxyUrl.replace(/\/$/,""),n=(0,q.resolve)(r.hostDistDir,"tests","index.html"),i;try{i=(0,wt.readFileSync)(n,"utf8")}catch{throw new Error(`Could not read host test page at ${n}. Build the host app with test support.`)}let s=(i.match(/<meta[^>]+>/g)??[]).filter(c=>!c.includes("charset")&&!c.includes("viewport")).map(c=>{if(!c.includes("config/environment"))return c;let u=c.match(/content="([^"]+)"/);if(!u)return c;try{let f=JSON.parse(decodeURIComponent(u[1]));f.resolvedBaseRealmURL&&(f.resolvedBaseRealmURL=`${t}/base/`),f.resolvedSkillsRealmURL&&(f.resolvedSkillsRealmURL=`${t}/skills/`),f.resolvedOpenRouterRealmURL&&(f.resolvedOpenRouterRealmURL=`${t}/openrouter/`),f.realmServerURL&&(f.realmServerURL=`${t}/`);let d=encodeURIComponent(JSON.stringify(f));return c.replace(/content="[^"]+"/,`content="${d}"`)}catch{return c}}),o=(i.match(/<script[^>]*src="[^"]*"[^>]*><\/script>/g)??[]).filter(c=>!c.includes("testem.js")&&!c.includes("ember-cli-live-reload")).map(c=>c.replace(/src="\/([^"]*)"/g,`src="${e}/$1"`)),a=(i.match(/<link[^>]*rel="stylesheet"[^>]*>/g)??[]).map(c=>c.replace(/href="\/([^"]*)"/g,`href="${e}/$1"`)),l=(i.match(/<script type="module">[^]*?<\/script>/g)??[]).map(c=>c.replace(/from '\/([^']*)'/g,`from '${e}/$1'`));return`<!DOCTYPE html>
|
|
128
128
|
<html>
|
|
129
129
|
<head>
|
|
130
130
|
<meta charset="utf-8">
|
|
@@ -172,18 +172,18 @@ ${g}${s} ${n.touched.length} file(s)${n.skipped.length>0?`, skipped ${n.skipped.
|
|
|
172
172
|
${o.join(`
|
|
173
173
|
`)}
|
|
174
174
|
</body>
|
|
175
|
-
</html>`}async function
|
|
175
|
+
</html>`}async function zE(r){let e={".js":"application/javascript",".css":"text/css",".map":"application/json",".html":"text/html",".wasm":"application/wasm",".svg":"image/svg+xml",".png":"image/png",".woff2":"font/woff2",".woff":"font/woff",".ttf":"font/ttf"},t="",n=i=>{t=i};return new Promise((i,s)=>{let o=(0,wu.createServer)((a,l)=>{let c=(a.url??"/").split("?")[0];if(c!=="/"){let u=(0,q.normalize)(c.slice(1));if(u.startsWith("..")||u.startsWith("/")){l.writeHead(403),l.end("Forbidden");return}let f=(0,q.resolve)(r,u);if(!f.startsWith((0,q.resolve)(r))){l.writeHead(403),l.end("Forbidden");return}try{let d=(0,wt.readFileSync)(f),p=f.match(/\.[^.]+$/)?.[0]??"",y=e[p]??"application/octet-stream";l.writeHead(200,{"Content-Type":y,"Access-Control-Allow-Origin":"*"}),l.end(d)}catch{l.writeHead(404),l.end("Not found")}return}l.writeHead(200,{"Content-Type":"text/html","Access-Control-Allow-Origin":"*"}),l.end(t)});o.on("error",s),o.listen(0,"127.0.0.1",()=>{let a=o.address();if(!a||typeof a=="string"){s(new Error("Failed to start test page server"));return}i({url:`http://127.0.0.1:${a.port}`,server:o,setHtml:n})})})}function Eu(r){try{return(0,wt.statSync)(r).isFile()}catch{return!1}}function XE(){let r=mt(__dirname),e=(0,q.resolve)(r,".."),t=(0,q.resolve)(e,".."),n=(0,q.join)(e,"host"),i=KE(t),s=i&&i!==t?(0,q.resolve)(i,"packages","host"):void 0,o=[process.env.TEST_HARNESS_HOST_DIST_PACKAGE_DIR,n,s].filter(l=>!!l).map(l=>(0,q.resolve)(l)),a=new Set;for(let l of o)if(!a.has(l)&&(a.add(l),Eu((0,q.join)(l,"dist","index.html"))))return l}function KE(r){let e=(0,yu.spawnSync)("git",["rev-parse","--path-format=absolute","--git-common-dir"],{cwd:r,encoding:"utf8",stdio:["ignore","pipe","ignore"]});if(e.status!==0)return;let t=e.stdout.trim();if(t.endsWith(`${(0,q.join)(".git")}`))return(0,q.dirname)(t)}function QE(r){if(!r.runEnd)return{status:"error",passedCount:0,failedCount:0,skippedCount:0,failures:[],errorMessage:"QUnit did not complete \u2014 runEnd event was not received"};let e=0,t=0,n=0,i=[];for(let o of r.tests)if(o.status==="failed"){t+=1;let a=o.errors[0];i.push({testName:o.name,module:o.module||"default",message:a?.message??"Test failed",...a?.stack?{stackTrace:a.stack.slice(0,500)}:{}})}else o.status==="skipped"||o.status==="todo"?n+=1:e+=1;let s;return r.tests.length===0?s="error":t>0||e===0&&n>0?s="failed":s="passed",{status:s,passedCount:e,failedCount:t,skippedCount:n,failures:i}}function Ai(r){return{status:"error",passedCount:0,failedCount:0,skippedCount:0,durationMs:0,testFiles:[],failures:[],errorMessage:r}}function bu(r){r.command("test").description("Run the realm's QUnit test suite (every `*.test.gts` file) in a headless Chromium driven against the host app. Monorepo-only: relies on the host app's compiled `dist/` being reachable from this CLI's location (or via TEST_HARNESS_HOST_DIST_PACKAGE_DIR).").requiredOption("--realm <realm-url>","The realm URL to test").option("--host-app-url <url>","Host app URL (compat proxy). Defaults to the active profile's realm-server URL.").option("--host-dist-dir <path>","Override the host app dist directory used to build the test page.").option("--debug","Stream browser console output to stderr").option("--json","Output structured JSON result").action(async e=>{let t;try{t=await BE(e.realm,{...e.hostAppUrl?{hostAppUrl:e.hostAppUrl}:{},...e.hostDistDir?{hostDistDir:e.hostDistDir}:{},...e.debug?{debug:!0}:{}})}catch(i){console.error(`${h}Error:${m} ${i instanceof Error?i.message:String(i)}`),process.exit(1)}if(e.json){M.output(JSON.stringify(t,null,2)),t.status!=="passed"&&process.exit(1);return}if(t.errorMessage&&console.error(`${h}Error:${m} ${t.errorMessage}`),t.testFiles.length===0){console.log(`${g}No .test.gts files found in the realm.${m}`),t.status!=="passed"&&process.exit(1);return}if(t.failures.length>0)for(let i of t.failures)console.log(`
|
|
176
176
|
${h}FAIL${m} ${g}${i.module}${m} \u203A ${i.testName}`),console.log(` ${i.message}`),i.stackTrace&&console.log(` ${g}${i.stackTrace.split(`
|
|
177
177
|
`).slice(0,3).join(`
|
|
178
178
|
`)}${m}`);let n=t.status==="passed"?S:t.status==="failed"?h:h;console.log(`
|
|
179
|
-
${n}${t.status}${m} ${g}\u2014${m} ${t.passedCount} passed, ${t.failedCount} failed${t.skippedCount>0?`, ${t.skippedCount} skipped`:""} ${g}(${t.durationMs}ms across ${t.testFiles.length} file(s))${m}`),t.status!=="passed"&&process.exit(1)})}function
|
|
179
|
+
${n}${t.status}${m} ${g}\u2014${m} ${t.passedCount} passed, ${t.failedCount} failed${t.skippedCount>0?`, ${t.skippedCount} skipped`:""} ${g}(${t.durationMs}ms across ${t.testFiles.length} file(s))${m}`),t.status!=="passed"&&process.exit(1)})}function $u(r){let e=new Ru.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&&or(!0),Bl(process.cwd())}),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",`
|
|
180
180
|
Environment variables (for 'add'):
|
|
181
181
|
BOXEL_PASSWORD Password; preferred over -p to avoid shell history.
|
|
182
182
|
BOXEL_ENVIRONMENT An env-mode slug (e.g. a branch name), interpreted
|
|
183
183
|
like scripts/env-slug.sh: URLs are derived as
|
|
184
184
|
http://matrix.<slug>.localhost and
|
|
185
185
|
http://realm-server.<slug>.localhost/. Overridden
|
|
186
|
-
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
|
|
186
|
+
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 Gl(t,n,i)}),hu(e),Ql(e),ic(e),fu(e),gu(e),Zl(e),bu(e),sc(e),Yl(e),e}var ZE=JSON.parse((0,Su.readFileSync)((0,vu.resolve)(__dirname,"../package.json"),"utf-8"));process.argv.includes("--quiet")&&or(!0);$u(ZE.version).parse();
|
|
187
187
|
/*! Bundled license information:
|
|
188
188
|
|
|
189
189
|
safe-buffer/index.js:
|